(function (global, factory) {
    typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
    typeof define === 'function' && define.amd ? define(['exports'], factory) :
    (global = global || self, factory(global.shuijf = {}));
}(this, function (exports) { 'use strict';

    /*! *****************************************************************************
    Copyright (c) Microsoft Corporation. All rights reserved.
    Licensed under the Apache License, Version 2.0 (the "License"); you may not use
    this file except in compliance with the License. You may obtain a copy of the
    License at http://www.apache.org/licenses/LICENSE-2.0

    THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
    WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
    MERCHANTABLITY OR NON-INFRINGEMENT.

    See the Apache Version 2.0 License for specific language governing permissions
    and limitations under the License.
    ***************************************************************************** */
    /* global Reflect, Promise */

    var extendStatics = function(d, b) {
        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 extendStatics(d, b);
    };

    function __extends(d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    }

    function __decorate(decorators, target, key, desc) {
        var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
        if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
        else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
        return c > 3 && r && Object.defineProperty(target, key, r), r;
    }

    function __awaiter(thisArg, _arguments, P, generator) {
        return new (P || (P = Promise))(function (resolve, reject) {
            function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
            function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
            function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
            step((generator = generator.apply(thisArg, _arguments || [])).next());
        });
    }

    function __generator(thisArg, body) {
        var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
        return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
        function verb(n) { return function (v) { return step([n, v]); }; }
        function step(op) {
            if (f) throw new TypeError("Generator is already executing.");
            while (_) try {
                if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
                if (y = 0, t) op = [op[0] & 2, t.value];
                switch (op[0]) {
                    case 0: case 1: t = op; break;
                    case 4: _.label++; return { value: op[1], done: false };
                    case 5: _.label++; y = op[1]; op = [0]; continue;
                    case 7: op = _.ops.pop(); _.trys.pop(); continue;
                    default:
                        if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                        if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                        if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                        if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                        if (t[2]) _.ops.pop();
                        _.trys.pop(); continue;
                }
                op = body.call(thisArg, _);
            } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
            if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
        }
    }

    function __values(o) {
        var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0;
        if (m) return m.call(o);
        return {
            next: function () {
                if (o && i >= o.length) o = void 0;
                return { value: o && o[i++], done: !o };
            }
        };
    }

    function __read(o, n) {
        var m = typeof Symbol === "function" && o[Symbol.iterator];
        if (!m) return o;
        var i = m.call(o), r, ar = [], e;
        try {
            while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
        }
        catch (error) { e = { error: error }; }
        finally {
            try {
                if (r && !r.done && (m = i["return"])) m.call(i);
            }
            finally { if (e) throw e.error; }
        }
        return ar;
    }

    function __spread() {
        for (var ar = [], i = 0; i < arguments.length; i++)
            ar = ar.concat(__read(arguments[i]));
        return ar;
    }

    var HASH_CODE_INK = 0;
    function getHashCode() {
        return ++HASH_CODE_INK;
    }
    var HashObject = (function () {
        function HashObject() {
            this._hashCode = getHashCode();
        }
        Object.defineProperty(HashObject.prototype, "hashCode", {
            get: function () {
                return this._hashCode;
            },
            enumerable: true,
            configurable: true
        });
        return HashObject;
    }());

    function injectProp(target, data, callback, ignoreMethod, ignoreNull) {
        if (ignoreMethod === void 0) { ignoreMethod = true; }
        if (ignoreNull === void 0) { ignoreNull = true; }
        if (!target || !data) {
            return false;
        }
        var result = false;
        for (var key in data) {
            var value = data[key];
            if ((!ignoreMethod || typeof value != 'function') && (!ignoreNull || value != null) && key.indexOf('_') !== 0 && key.indexOf('$') !== 0) {
                if (callback) {
                    callback(target, key, value);
                }
                else {
                    try {
                        target[key] = value;
                    }
                    catch (e) {
                    }
                }
                result = true;
            }
        }
        return result;
    }
    function copyProp(target, data, config) {
        var e_1, _a;
        if (config) {
            for (var key in config) {
                var valueConfig = config[key];
                if (Array.isArray(valueConfig)) {
                    target[key] = {};
                    try {
                        for (var valueConfig_1 = __values(valueConfig), valueConfig_1_1 = valueConfig_1.next(); !valueConfig_1_1.done; valueConfig_1_1 = valueConfig_1.next()) {
                            var field = valueConfig_1_1.value;
                            target[key][field] = data[key][field];
                        }
                    }
                    catch (e_1_1) { e_1 = { error: e_1_1 }; }
                    finally {
                        try {
                            if (valueConfig_1_1 && !valueConfig_1_1.done && (_a = valueConfig_1.return)) _a.call(valueConfig_1);
                        }
                        finally { if (e_1) throw e_1.error; }
                    }
                }
                else if (typeof valueConfig === 'string') {
                    target[valueConfig] = data[valueConfig];
                }
                else if (typeof valueConfig === 'object') {
                    target[key] = {};
                    copyProp(target[key], data[key], valueConfig);
                }
            }
        }
    }
    function objectStringify(obj) {
        if (!obj) {
            return '';
        }
        var arr = [];
        for (var key in obj) {
            arr.push(key + '=' + obj[key]);
        }
        return arr.join('&');
    }
    function dotEval(expression, context, strict, dotChar) {
        if (context === void 0) { context = window; }
        if (strict === void 0) { strict = true; }
        if (dotChar === void 0) { dotChar = '.'; }
        if (!expression || !context) {
            return context;
        }
        var result = expression
            .split(dotChar)
            .reduce(function (pre, cur, index, arr) {
            var ref;
            if (strict) {
                if (pre && pre.hasOwnProperty(cur)) {
                    ref = pre[cur];
                }
                else {
                    var e = "can not get " + cur + " on " + (index === 0 ? 'context' : arr.slice(0, index).join(dotChar));
                    console.warn(e);
                    throw new Error(e);
                }
            }
            else {
                ref = cur && pre[cur] || pre;
            }
            return ref;
        }, context);
        return result;
    }

    var EngineConfig = {
        lineHeightRatio: 1.2,
        entityEnabled: true,
        componentEnabled: true,
        awakeComponentWhenAdded: true,
        sleepComponentWhenRemoved: true,
        drawRenderRect: false,
        imgCrossOrigin: true,
        editorMode: false,
    };
    function modifyEngineConfig(_options) {
        injectProp(EngineConfig, _options);
    }

    var interactiveMap = [
        '_dealGlobalTouchBegin',
        '_dealGlobalTouchMove',
        '_dealGlobalTouchEnd',
    ];
    var Component = (function (_super) {
        __extends(Component, _super);
        function Component() {
            var _this = _super !== null && _super.apply(this, arguments) || this;
            _this.delayCallbacks = [];
            _this._enabled = EngineConfig.componentEnabled;
            _this._firstUpdate = EngineConfig.componentEnabled;
            return _this;
        }
        Object.defineProperty(Component.prototype, "enabled", {
            get: function () {
                return this._enabled;
            },
            set: function (value) {
                if (this._enabled !== value) {
                    this._enabled = value;
                    if (this.entity && this.entity.isActive) {
                        if (!EngineConfig.editorMode) {
                            if (this._enabled) {
                                this.onEnable();
                            }
                            else {
                                this.onDisable();
                            }
                        }
                    }
                }
            },
            enumerable: true,
            configurable: true
        });
        Component.prototype._setup = function (entity) {
            this.entity = entity;
        };
        Component.prototype._unSetup = function () {
            this.entity = null;
        };
        Component.prototype.onCreate = function () {
        };
        Component.prototype.$onAwake = function () {
            if (!EngineConfig.editorMode) {
                this.onAwake();
            }
        };
        Component.prototype.onAwake = function () {
        };
        Component.prototype.onEnable = function () {
        };
        Component.prototype.onDisable = function () {
        };
        Component.prototype.$onUpdate = function (t) {
            this.onUpdate(t);
            if (!this._firstUpdate) {
                this.invokeDelayCallback(t);
            }
            this._firstUpdate = false;
        };
        Component.prototype.$onEditorUpdate = function (t) {
            this.onEditorUpdate(t);
        };
        Component.prototype.$afterUpdate = function () {
            this.afterUpdate();
        };
        Component.prototype.$afterEditorUpdate = function () {
            this.afterEditorUpdate();
        };
        Component.prototype.invokeDelayCallback = function (t) {
            for (var i = 0, li = this.delayCallbacks.length; i < li; i++) {
                var _a = this.delayCallbacks[i], callback = _a.callback, once = _a.once;
                if (once) {
                    this.delayCallbacks.splice(i, 1);
                    i--;
                    li--;
                }
                callback.call(this, t);
            }
        };
        Component.prototype.onUpdate = function (t) {
        };
        Component.prototype.onEditorUpdate = function (t) {
        };
        Component.prototype.afterUpdate = function () {
        };
        Component.prototype.afterEditorUpdate = function () {
        };
        Component.prototype.$onSleep = function () {
            if (!EngineConfig.editorMode) {
                this.onSleep();
            }
        };
        Component.prototype.onSleep = function () {
        };
        Component.prototype.onDestroy = function () {
        };
        Component.prototype.onModify = function (value, key, oldValue) {
        };
        Component.prototype.getDelayCallback = function (callback) {
            var e_1, _a;
            var result;
            try {
                for (var _b = __values(this.delayCallbacks), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var item = _c.value;
                    if (item.callback == callback) {
                        result = item;
                        break;
                    }
                }
            }
            catch (e_1_1) { e_1 = { error: e_1_1 }; }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
                }
                finally { if (e_1) throw e_1.error; }
            }
            return result;
        };
        Component.prototype.callOnNextTick = function (callback, once) {
            if (once === void 0) { once = true; }
            var item = this.getDelayCallback(callback);
            if (!item) {
                this.delayCallbacks.push({ callback: callback, once: once });
            }
        };
        Component.prototype.cancelOnNextTick = function (callback) {
            var item = this.getDelayCallback(callback);
            var index = this.delayCallbacks.indexOf(item);
            if (index >= 0) {
                this.delayCallbacks.splice(index, 1);
            }
        };
        Component.prototype.onInteract = function (type, event) {
            try {
                var hitOn = this[interactiveMap[type]](event);
                return hitOn;
            }
            catch (e) {
                console.warn(e);
            }
        };
        Component.prototype._dealGlobalTouchBegin = function (e) {
            return this.onGlobalTouchBegin(e);
        };
        Component.prototype._dealGlobalTouchMove = function (e) {
            return this.onGlobalTouchMove(e);
        };
        Component.prototype._dealGlobalTouchEnd = function (e) {
            return this.onGlobalTouchEnd(e);
        };
        Component.prototype.onGlobalTouchBegin = function (e) {
            return false;
        };
        Component.prototype.onGlobalTouchMove = function (e) {
            return false;
        };
        Component.prototype.onGlobalTouchEnd = function (e) {
            return false;
        };
        Component.prototype.broadcast = function (method, level) {
            var _a;
            if (level === void 0) { level = -1; }
            var params = [];
            for (var _i = 2; _i < arguments.length; _i++) {
                params[_i - 2] = arguments[_i];
            }
            (_a = this.entity).broadcast.apply(_a, __spread([method, level], params));
        };
        Component.prototype.bubbling = function (method) {
            var _a;
            var params = [];
            for (var _i = 1; _i < arguments.length; _i++) {
                params[_i - 1] = arguments[_i];
            }
            (_a = this.entity).bubbling.apply(_a, __spread([method], params));
        };
        return Component;
    }(HashObject));

    function traverse(target, hitChild, level, includeSelf, fullCallback) {
        var e_1, _a;
        if (level === void 0) { level = -1; }
        if (includeSelf === void 0) { includeSelf = false; }
        var params = [];
        for (var _i = 5; _i < arguments.length; _i++) {
            params[_i - 5] = arguments[_i];
        }
        if (includeSelf) {
            hitChild.apply(void 0, __spread([target], params));
        }
        if (level !== 0) {
            try {
                for (var _b = __values(target.children), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var child = _c.value;
                    if (hitChild.apply(void 0, __spread([child], params))) {
                        continue;
                    }
                    if (child.children.length > 0) {
                        traverse.apply(void 0, __spread([child, hitChild, level - 1, false, fullCallback], params));
                    }
                }
            }
            catch (e_1_1) { e_1 = { error: e_1_1 }; }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
                }
                finally { if (e_1) throw e_1.error; }
            }
        }
        fullCallback && fullCallback(target);
    }
    function traversePostorder(target, hitChild, level, includeSelf, fullCallback) {
        if (level === void 0) { level = -1; }
        if (includeSelf === void 0) { includeSelf = false; }
        var params = [];
        for (var _i = 5; _i < arguments.length; _i++) {
            params[_i - 5] = arguments[_i];
        }
        if (level !== 0) {
            for (var i = target.children.length - 1; i >= 0; i--) {
                var child = target.children[i];
                if (!child.enabled) {
                    continue;
                }
                if (traversePostorder.apply(void 0, __spread([child, hitChild, level - 1, false, fullCallback], params))) {
                    return true;
                }
                if (hitChild.apply(void 0, __spread([child], params))) {
                    return true;
                }
            }
        }
        if (includeSelf) {
            hitChild.apply(void 0, __spread([target], params));
        }
        fullCallback && fullCallback(target);
    }
    function bubbling(target, hitParent, includeSelf) {
        if (includeSelf === void 0) { includeSelf = false; }
        var params = [];
        for (var _i = 3; _i < arguments.length; _i++) {
            params[_i - 3] = arguments[_i];
        }
        if (includeSelf) {
            hitParent.apply(void 0, __spread([target], params));
        }
        var entity = target;
        while (entity = entity.parent) {
            if (hitParent.apply(void 0, __spread([entity], params))) {
                break;
            }
        }
    }

    var EventDispatcher = (function (_super) {
        __extends(EventDispatcher, _super);
        function EventDispatcher() {
            var _this = _super !== null && _super.apply(this, arguments) || this;
            _this._eventListMap = {};
            return _this;
        }
        EventDispatcher.prototype.addEventListener = function (type, listener, once) {
            if (once === void 0) { once = false; }
            var eventList = this._eventListMap[type];
            if (!eventList) {
                eventList = this._eventListMap[type] = [];
            }
            eventList.push({
                listener: listener,
                once: once,
            });
        };
        EventDispatcher.prototype.removeEventListener = function (type, listener) {
            var eventList = this._eventListMap[type];
            if (eventList) {
                if (listener) {
                    for (var i = 0, li = eventList.length; i < li; i++) {
                        var event = eventList[i];
                        if (event.listener === listener) {
                            eventList.splice(i, 1);
                            i--;
                        }
                    }
                }
                else {
                    eventList.splice(0);
                }
            }
        };
        EventDispatcher.prototype.hasEventListener = function (type) {
            return this._eventListMap[type] && this._eventListMap[type].length > 0;
        };
        EventDispatcher.prototype.dispatch = function (type) {
            var e_1, _a;
            var data = [];
            for (var _i = 1; _i < arguments.length; _i++) {
                data[_i - 1] = arguments[_i];
            }
            var eventList = this._eventListMap[type];
            if (eventList && eventList.length > 0) {
                var eventListTemp = eventList.concat();
                try {
                    for (var eventListTemp_1 = __values(eventListTemp), eventListTemp_1_1 = eventListTemp_1.next(); !eventListTemp_1_1.done; eventListTemp_1_1 = eventListTemp_1.next()) {
                        var event = eventListTemp_1_1.value;
                        event.listener.apply(null, data);
                    }
                }
                catch (e_1_1) { e_1 = { error: e_1_1 }; }
                finally {
                    try {
                        if (eventListTemp_1_1 && !eventListTemp_1_1.done && (_a = eventListTemp_1.return)) _a.call(eventListTemp_1);
                    }
                    finally { if (e_1) throw e_1.error; }
                }
                for (var i = 0, li = eventList.length; i < li; i++) {
                    var event = eventList[i];
                    if (event.once) {
                        eventList.splice(i, 1);
                        i--;
                    }
                }
            }
        };
        return EventDispatcher;
    }(HashObject));

    var Entity = (function (_super) {
        __extends(Entity, _super);
        function Entity(name, uuid) {
            var _this = _super.call(this) || this;
            _this.name = 'Entity';
            _this._isFree = true;
            _this._enabled = EngineConfig.entityEnabled;
            _this._parent = null;
            _this._children = [];
            _this._components = [];
            _this.invokeOnEntity = function (hitEntity, method) {
                var params = [];
                for (var _i = 2; _i < arguments.length; _i++) {
                    params[_i - 2] = arguments[_i];
                }
                var hitBreak = false;
                hitEntity.forEachComponent(function (comp) {
                    var m = comp[method];
                    if (m) {
                        var result = m.apply(comp, params);
                        if (result) {
                            hitBreak = true;
                        }
                    }
                    return false;
                });
                if (hitBreak) {
                    return true;
                }
            };
            if (name) {
                _this.name = name;
            }
            if (uuid) {
                _this._uuid = uuid;
            }
            return _this;
        }
        Object.defineProperty(Entity.prototype, "uuid", {
            get: function () {
                return this._uuid;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Entity.prototype, "enabled", {
            get: function () {
                return this._enabled;
            },
            set: function (value) {
                if (this._enabled !== value) {
                    this._enabled = value;
                    var that_1 = this;
                    traverse(this, function (child) {
                        if (child !== that_1 && !child._enabled) {
                            return true;
                        }
                        child._invokeEnabledState(value);
                        return false;
                    }, -1, true);
                }
            },
            enumerable: true,
            configurable: true
        });
        Entity.prototype._invokeEnabledState = function (enabled) {
            if (this._enabled) {
                if (enabled) {
                    this.onEnable();
                }
                else {
                    this.onDisable();
                }
            }
        };
        Object.defineProperty(Entity.prototype, "isParentActive", {
            get: function () {
                return this._parent && this._parent.enabled && !this._parent.isFree;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Entity.prototype, "isActive", {
            get: function () {
                return this.isParentActive && this._enabled;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Entity.prototype, "isFree", {
            get: function () {
                return this._isFree;
            },
            enumerable: true,
            configurable: true
        });
        Entity.prototype._free = function () {
            this._isFree = true;
            traverse(this, function (child) {
                if (child.isParentActive) {
                    child._invokeEnabledState(false);
                }
                child._free();
                return false;
            }, 1);
        };
        Entity.prototype._restrict = function () {
            this._isFree = false;
            traverse(this, function (child) {
                if (child.isParentActive) {
                    child._invokeEnabledState(true);
                }
                child._restrict();
                return false;
            }, 1);
        };
        Object.defineProperty(Entity.prototype, "parent", {
            get: function () {
                return this._parent;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Entity.prototype, "root", {
            get: function () {
                var p = this;
                do {
                    if (p instanceof RootEntity) {
                        return p;
                    }
                } while (p = p.parent);
            },
            enumerable: true,
            configurable: true
        });
        Entity.prototype.containsChild = function (child) {
            return this.getChildIndex(child) >= 0;
        };
        Entity.prototype._onChildAdded = function (child) {
            child._parent = this;
            if (!this._isFree && child._isFree) {
                if (child.isParentActive) {
                    child._invokeEnabledState(true);
                }
                child._restrict();
            }
        };
        Entity.prototype._onChildRemoved = function (child) {
            child._parent = null;
            if (!this._isFree && !child._isFree) {
                if (child.isActive) {
                    child._invokeEnabledState(false);
                }
                child._free();
            }
        };
        Entity.prototype.addChild = function (child) {
            this.addChildAt(child, this._children.length);
        };
        Entity.prototype.addChildAt = function (child, index) {
            if (child.parent && child.parent !== this) {
                child.parent.removeChild(child);
            }
            var currentIndex = this.getChildIndex(child);
            if (index < 0 || currentIndex == index) {
                return;
            }
            index = Math.min(this._children.length, index);
            if (currentIndex >= 0 || index < this._children.length) {
                if (currentIndex >= 0) {
                    this._children.splice(currentIndex, 1);
                }
                this._children.splice(index, 0, child);
            }
            else {
                this._children.push(child);
            }
            this._onChildAdded(child);
        };
        Entity.prototype.removeChild = function (child) {
            var index = this.getChildIndex(child);
            if (index >= 0) {
                return this.removeChildAt(index);
            }
        };
        Entity.prototype.removeChildAt = function (index) {
            var child = this._children[index];
            if (child) {
                this._onChildRemoved(child);
                this._children.splice(index, 1);
                return child;
            }
        };
        Entity.prototype.getChildIndex = function (child) {
            return this._children.indexOf(child);
        };
        Entity.prototype.getChildAt = function (index) {
            return this._children[index];
        };
        Entity.prototype.getChildrenByName = function (name) {
            var e_1, _a;
            var children = [];
            try {
                for (var _b = __values(this._children), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var child = _c.value;
                    if (child.name === name) {
                        children.push(child);
                    }
                }
            }
            catch (e_1_1) { e_1 = { error: e_1_1 }; }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
                }
                finally { if (e_1) throw e_1.error; }
            }
            return children;
        };
        Entity.prototype.removeChildren = function () {
            while (this._children.length > 0) {
                this.removeChildAt(0);
            }
        };
        Object.defineProperty(Entity.prototype, "children", {
            get: function () {
                return this._children;
            },
            enumerable: true,
            configurable: true
        });
        Entity.prototype.addComponent = function (component) {
            this.onAddComponent(component);
            this._components.push(component);
        };
        Entity.prototype.addComponentAt = function (component, index) {
            var currentIndex = this._components.indexOf(component);
            if (currentIndex == index) {
                return;
            }
            if (currentIndex >= 0) {
                this._components.splice(currentIndex, 1);
            }
            this._components.splice(index, 0, component);
            this.onAddComponent(component);
        };
        Entity.prototype.removeComponent = function (component) {
            this.onRemoveComponent(component);
            var index = this._components.indexOf(component);
            if (index >= 0) {
                this._components.splice(index, 1);
            }
        };
        Entity.prototype.removeAllComponents = function () {
            while (this._components.length > 0) {
                this.removeComponent(this._components[0]);
            }
        };
        Entity.prototype.getComponentsByName = function (name) {
            return this._components.filter(function (value) {
                return value.constructor['__class__'] === name;
            });
        };
        Entity.prototype.getComponents = function (clazz) {
            return this._components.filter(function (component) {
                return component instanceof clazz;
            });
        };
        Entity.prototype.getComponentByName = function (name) {
            return this.getComponentsByName(name)[0];
        };
        Entity.prototype.getComponent = function (clazz) {
            return this.getComponents(clazz)[0];
        };
        Object.defineProperty(Entity.prototype, "components", {
            get: function () {
                return this._components;
            },
            enumerable: true,
            configurable: true
        });
        Entity.prototype.forEachComponent = function (func) {
            var e_2, _a;
            try {
                for (var _b = __values(this._components), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var component = _c.value;
                    if (func(component)) {
                        break;
                    }
                }
            }
            catch (e_2_1) { e_2 = { error: e_2_1 }; }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
                }
                finally { if (e_2) throw e_2.error; }
            }
        };
        Entity.prototype.active = function () {
            this.forEachComponent(function (comp) {
                if (comp.enabled) {
                    return comp.onCreate();
                }
            });
        };
        Entity.prototype.onEnable = function () {
            this.forEachComponent(function (comp) {
                if (comp.enabled) {
                    return comp.$onAwake();
                }
            });
        };
        Entity.prototype.onDisable = function () {
            this.forEachComponent(function (comp) {
                if (comp.enabled) {
                    return comp.$onSleep();
                }
            });
        };
        Entity.prototype.$onUpdate = function (t) {
            this.preUpdate(t);
            this.updateComponents(t);
            this.onUpdate(t);
        };
        Entity.prototype.preUpdate = function (t) {
        };
        Entity.prototype.updateComponents = function (t) {
            this.forEachComponent(function (comp) {
                if (comp.enabled) {
                    if (EngineConfig.editorMode) {
                        return comp.$onEditorUpdate(t);
                    }
                    else {
                        return comp.$onUpdate(t);
                    }
                }
            });
        };
        Entity.prototype.onUpdate = function (t) {
        };
        Entity.prototype.$afterUpdate = function () {
            this.forEachComponent(function (comp) {
                if (comp.enabled) {
                    if (EngineConfig.editorMode) {
                        return comp.$afterEditorUpdate();
                    }
                    else {
                        return comp.$afterUpdate();
                    }
                }
            });
        };
        Entity.prototype.onInteract = function (type, event) {
            if (!this.isFree && this.enabled) {
                var interrupt_1 = false;
                this.forEachComponent(function (comp) {
                    if (comp.enabled && comp.interactable) {
                        var r = comp.onInteract(type, event);
                        if (r) {
                            interrupt_1 = true;
                        }
                        return false;
                    }
                });
                return interrupt_1;
            }
            else {
                return false;
            }
        };
        Entity.prototype.onAddComponent = function (component) {
            component._setup(this);
            if (EngineConfig.awakeComponentWhenAdded) {
                this.awakeComponent(component);
            }
        };
        Entity.prototype.awakeComponent = function (component) {
            if (!this._isFree && this._enabled) {
                component.$onAwake();
            }
        };
        Entity.prototype.onRemoveComponent = function (component) {
            if (EngineConfig.sleepComponentWhenRemoved) {
                this.sleepComponent(component);
            }
            component._unSetup();
        };
        Entity.prototype.sleepComponent = function (component) {
            if (!this._isFree && this._enabled) {
                component.$onSleep();
            }
        };
        Entity.prototype.broadcast = function (method, level) {
            if (level === void 0) { level = -1; }
            var params = [];
            for (var _i = 2; _i < arguments.length; _i++) {
                params[_i - 2] = arguments[_i];
            }
            traverse.apply(void 0, __spread([this, this.invokeOnEntity, level, true, null, method], params));
        };
        Entity.prototype.bubbling = function (method) {
            var params = [];
            for (var _i = 1; _i < arguments.length; _i++) {
                params[_i - 1] = arguments[_i];
            }
            bubbling.apply(void 0, __spread([this, this.invokeOnEntity, false, method], params));
        };
        return Entity;
    }(EventDispatcher));
    var RootEntity = (function (_super) {
        __extends(RootEntity, _super);
        function RootEntity(engine) {
            var _this = _super.call(this) || this;
            _this.name = 'root';
            _this._engine = engine;
            return _this;
        }
        Object.defineProperty(RootEntity.prototype, "engine", {
            get: function () {
                return this._engine;
            },
            enumerable: true,
            configurable: true
        });
        return RootEntity;
    }(Entity));

    var ScillaEvent = (function () {
        function ScillaEvent() {
            this._subscribers = [];
        }
        ScillaEvent.prototype.findListener = function (callback) {
            var _subscribers = this._subscribers;
            var result;
            for (var i = 0, li = _subscribers.length; i < li; i++) {
                var subscriber = _subscribers[i];
                if (subscriber.callback == callback) {
                    result = {
                        subscriber: subscriber,
                        index: i,
                    };
                    break;
                }
            }
            return result;
        };
        ScillaEvent.prototype.addListener = function (callback, thisObj, priority) {
            if (priority === void 0) { priority = 0; }
            var params = [];
            for (var _i = 3; _i < arguments.length; _i++) {
                params[_i - 3] = arguments[_i];
            }
            if (!callback) {
                return;
            }
            var _subscribers = this._subscribers;
            var listener = this.findListener(callback);
            if (!listener) {
                _subscribers.push({
                    callback: callback,
                    thisObj: thisObj,
                    priority: priority,
                    params: params,
                });
            }
        };
        ScillaEvent.prototype.once = function (callback, thisObj, priority) {
            if (priority === void 0) { priority = 0; }
            var params = [];
            for (var _i = 3; _i < arguments.length; _i++) {
                params[_i - 3] = arguments[_i];
            }
            if (!callback) {
                return;
            }
            var _subscribers = this._subscribers;
            var listener = this.findListener(callback);
            if (!listener) {
                _subscribers.push({
                    callback: callback,
                    thisObj: thisObj,
                    priority: priority,
                    params: params,
                    once: true,
                });
            }
        };
        ScillaEvent.prototype.removeListener = function (callback) {
            if (!callback) {
                return;
            }
            var _subscribers = this._subscribers;
            var listener = this.findListener(callback);
            if (listener) {
                _subscribers.splice(listener.index, 1);
            }
        };
        ScillaEvent.prototype.hasListener = function (callback) {
            return !!this.findListener(callback);
        };
        ScillaEvent.prototype.invoke = function () {
            var e_1, _a;
            var paramsNew = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                paramsNew[_i] = arguments[_i];
            }
            var _subscribers = this._subscribers;
            _subscribers.sort(function (a, b) {
                return a.priority - b.priority;
            });
            try {
                for (var _subscribers_1 = __values(_subscribers), _subscribers_1_1 = _subscribers_1.next(); !_subscribers_1_1.done; _subscribers_1_1 = _subscribers_1.next()) {
                    var subscriber = _subscribers_1_1.value;
                    if (subscriber) {
                        var callback = subscriber.callback, thisObj = subscriber.thisObj, once = subscriber.once, params = subscriber.params;
                        var allParams = params.concat(paramsNew);
                        try {
                            callback.apply(thisObj, allParams);
                        }
                        catch (e) {
                            console.log(e);
                        }
                        if (once) {
                            this.removeListener(callback);
                        }
                    }
                }
            }
            catch (e_1_1) { e_1 = { error: e_1_1 }; }
            finally {
                try {
                    if (_subscribers_1_1 && !_subscribers_1_1.done && (_a = _subscribers_1.return)) _a.call(_subscribers_1);
                }
                finally { if (e_1) throw e_1.error; }
            }
        };
        return ScillaEvent;
    }());

    function fieldChanged(onChange) {
        return function (target, key) {
            var privateKey = '_' + key;
            Object.defineProperty(target, key, {
                enumerable: true,
                get: function () {
                    return this[privateKey];
                },
                set: function (v) {
                    var oldValue = this[privateKey];
                    if (oldValue !== v) {
                        this[privateKey] = v;
                        onChange.apply(this, [v, key, oldValue]);
                    }
                }
            });
        };
    }
    var dirtyFieldDetector = fieldChanged(function (value, key, oldValue) {
        this['dirty'] = true;
    });
    var dirtyFieldTrigger = fieldChanged(function (value, key, oldValue) {
        this['onModify'] && this['onModify'](value, key, oldValue);
    });

    var ScaleMode;
    (function (ScaleMode) {
        ScaleMode["SHOW_ALL"] = "showAll";
        ScaleMode["FIXED_WIDTH"] = "fixedWidth";
        ScaleMode["FIXED_HEIGHT"] = "fixedHeight";
        ScaleMode["NO_SCALE"] = "noScale";
        ScaleMode["NO_FIXED"] = "noFixed";
    })(ScaleMode || (ScaleMode = {}));
    var RenderContext = (function () {
        function RenderContext(engine) {
            this._rotation = 0;
            this.dirtyFieldTriggerLock = false;
            this.engine = engine;
        }
        RenderContext.prototype.onModify = function (value, key, oldValue) {
            if (!this.dirtyFieldTriggerLock) {
                this.updateScaleModeSelf();
            }
        };
        RenderContext.prototype.setup = function (options) {
            if (options === void 0) { options = {}; }
            var canvas = options.canvas, designWidth = options.designWidth, designHeight = options.designHeight, _a = options.scaleMode, scaleMode = _a === void 0 ? ScaleMode.SHOW_ALL : _a, _b = options.modifyCanvasSize, modifyCanvasSize = _b === void 0 ? false : _b, _c = options.autoAdjustSize, autoAdjustSize = _c === void 0 ? false : _c, onUpdateScale = options.onUpdateScale;
            this.canvas = canvas;
            this.canvasContext = canvas.getContext('2d');
            this.dirtyFieldTriggerLock = true;
            this.designWidth = designWidth;
            this.designHeight = designHeight;
            this.scaleMode = scaleMode;
            this.modifyCanvasSize = modifyCanvasSize;
            this.autoAdjustSize = autoAdjustSize;
            this.onUpdateScale = onUpdateScale;
            this.dirtyFieldTriggerLock = false;
            this.updateScaleModeSelf();
        };
        Object.defineProperty(RenderContext.prototype, "scaleX", {
            get: function () {
                return this._scaleX;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(RenderContext.prototype, "scaleY", {
            get: function () {
                return this._scaleY;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(RenderContext.prototype, "rotation", {
            get: function () {
                return this._rotation;
            },
            enumerable: true,
            configurable: true
        });
        RenderContext.prototype.clear = function () {
            this.canvasContext.setTransform(1, 0, 0, 1, 0, 0);
            this.canvasContext.clearRect(0, 0, this.canvas.width, this.canvas.height);
        };
        Object.defineProperty(RenderContext.prototype, "context", {
            get: function () {
                return this.canvasContext;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(RenderContext.prototype, "stageSize", {
            get: function () {
                return {
                    width: this.stageWidth,
                    height: this.stageHeight,
                };
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(RenderContext.prototype, "stageScale", {
            get: function () {
                return {
                    x: this._scaleX,
                    y: this._scaleY,
                };
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(RenderContext.prototype, "stageCenter", {
            get: function () {
                return {
                    x: this.stageWidth / 2,
                    y: this.stageHeight / 2,
                };
            },
            enumerable: true,
            configurable: true
        });
        RenderContext.prototype.updateScaleModeSelf = function () {
            var _a = this, canvas = _a.canvas, designWidth = _a.designWidth, designHeight = _a.designHeight, scaleMode = _a.scaleMode, _rotation = _a._rotation, modifyCanvasSize = _a.modifyCanvasSize;
            var parent = canvas.parentElement;
            var containerWidth = parent.clientWidth;
            var containerHeight = parent.clientHeight;
            var dWidth = designWidth || containerWidth;
            var dHeight = designHeight || containerHeight;
            var width, stageWidth;
            var height, stageHeight;
            var scaleX = containerWidth / dWidth;
            var scaleY = containerHeight / dHeight;
            var styleWidth;
            var styleHeight;
            switch (scaleMode) {
                case ScaleMode.SHOW_ALL:
                    break;
                case ScaleMode.NO_SCALE:
                    scaleX = scaleY = 1;
                    break;
                case ScaleMode.NO_FIXED:
                    scaleX = scaleY = 1;
                    break;
                case ScaleMode.FIXED_WIDTH:
                case ScaleMode.FIXED_HEIGHT:
                    break;
            }
            switch (scaleMode) {
                case ScaleMode.SHOW_ALL:
                    width = dWidth;
                    height = dHeight;
                    stageWidth = dWidth;
                    stageHeight = dHeight;
                    break;
                case ScaleMode.NO_SCALE:
                    width = dWidth;
                    height = dHeight;
                    stageWidth = dWidth;
                    stageHeight = dHeight;
                    break;
                case ScaleMode.NO_FIXED:
                    width = containerWidth;
                    height = containerHeight;
                    stageWidth = dWidth;
                    stageHeight = dHeight;
                    break;
                case ScaleMode.FIXED_WIDTH:
                    width = dWidth;
                    if (modifyCanvasSize) {
                        height = dHeight;
                    }
                    else {
                        height = containerHeight / scaleX;
                    }
                    scaleY = scaleX;
                    stageWidth = width;
                    stageHeight = height;
                    break;
                case ScaleMode.FIXED_HEIGHT:
                    if (modifyCanvasSize) {
                        width = dWidth;
                    }
                    else {
                        width = containerWidth / scaleY;
                    }
                    height = dHeight;
                    scaleX = scaleY;
                    stageWidth = width;
                    stageHeight = height;
                    break;
            }
            switch (scaleMode) {
                case ScaleMode.SHOW_ALL:
                    styleWidth = containerWidth;
                    styleHeight = containerHeight;
                    break;
                case ScaleMode.NO_FIXED:
                    styleWidth = containerWidth;
                    styleHeight = containerHeight;
                    break;
                case ScaleMode.NO_SCALE:
                    styleWidth = designWidth;
                    styleHeight = designHeight;
                    break;
                case ScaleMode.FIXED_WIDTH:
                case ScaleMode.FIXED_HEIGHT:
                    styleWidth = modifyCanvasSize ? designWidth * scaleX : containerWidth;
                    styleHeight = modifyCanvasSize ? designHeight * scaleY : containerHeight;
                    break;
            }
            this.onUpdateScale(scaleX, scaleY, _rotation);
            this.stageWidth = stageWidth;
            this.stageHeight = stageHeight;
            this._scaleX = scaleX;
            this._scaleY = scaleY;
            canvas.width = width;
            canvas.height = height;
            canvas.style.display = 'block';
            canvas.style.width = styleWidth + 'px';
            canvas.style.height = styleHeight + 'px';
        };
        RenderContext.prototype.shortcut = function (type, params) {
            if (type === void 0) { type = 0; }
            return __awaiter(this, void 0, void 0, function () {
                var targetImg, dataUrl, img;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            if (!(params.bounds || params.zoomToDom)) return [3, 3];
                            dataUrl = this.canvas.toDataURL('image/png');
                            return [4, dataUrlToImage(dataUrl)];
                        case 1:
                            img = _a.sent();
                            return [4, this.shortcutWithSize(img, type, params.imgType, params.quality, params.bounds, params.zoomToDom ? this._scaleX : 1)];
                        case 2:
                            targetImg = _a.sent();
                            return [3, 4];
                        case 3:
                            targetImg = this.canvas.toDataURL(params.imgType, params.quality);
                            _a.label = 4;
                        case 4: return [2, targetImg];
                    }
                });
            });
        };
        RenderContext.prototype.shortcutWithSize = function (img, type, imgType, quality, bounds, scale) {
            if (scale === void 0) { scale = 1; }
            return __awaiter(this, void 0, void 0, function () {
                var _a, shortcutCanvas, stageWidth, stageHeight, sx, sy, sw, sh, dw, dh, canvasContext, dataUrl, _b;
                return __generator(this, function (_c) {
                    switch (_c.label) {
                        case 0:
                            _a = this, shortcutCanvas = _a.shortcutCanvas, stageWidth = _a.stageWidth, stageHeight = _a.stageHeight;
                            if (!shortcutCanvas) {
                                this.shortcutCanvas = createCanvas();
                            }
                            sx = bounds ? bounds.x || 0 : 0;
                            sy = bounds ? bounds.y || 0 : 0;
                            sw = bounds ? (bounds.width ? Math.min(bounds.width, stageWidth) : stageWidth) : stageWidth;
                            sh = bounds ? (bounds.height ? Math.min(bounds.height, stageHeight) : stageHeight) : stageHeight;
                            dw = sw * scale;
                            dh = sh * scale;
                            shortcutCanvas.width = dw;
                            shortcutCanvas.height = dh;
                            canvasContext = shortcutCanvas.getContext('2d');
                            canvasContext.drawImage(img, sx, sy, sw, sh, 0, 0, dw, dh);
                            dataUrl = shortcutCanvas.toDataURL('image/' + imgType, quality);
                            _b = type;
                            switch (_b) {
                                case 0: return [3, 1];
                                case 1: return [3, 3];
                            }
                            return [3, 4];
                        case 1: return [4, dataUrlToImage(dataUrl)];
                        case 2: return [2, _c.sent()];
                        case 3: return [2, dataUrl];
                        case 4: return [2];
                    }
                });
            });
        };
        __decorate([
            dirtyFieldTrigger
        ], RenderContext.prototype, "designWidth", void 0);
        __decorate([
            dirtyFieldTrigger
        ], RenderContext.prototype, "designHeight", void 0);
        __decorate([
            dirtyFieldTrigger
        ], RenderContext.prototype, "scaleMode", void 0);
        __decorate([
            dirtyFieldTrigger
        ], RenderContext.prototype, "modifyCanvasSize", void 0);
        __decorate([
            dirtyFieldTrigger
        ], RenderContext.prototype, "autoAdjustSize", void 0);
        return RenderContext;
    }());
    function dataUrlToImage(dataUrl) {
        return new Promise(function (resolve, reject) {
            var image = new Image();
            image.onload = function () {
                resolve(image);
            };
            image.onerror = function (e) {
                reject(e);
            };
            image.src = dataUrl;
        });
    }
    function createCanvas() {
        return document.createElement('canvas');
    }

    var ua = navigator.userAgent.toLowerCase();
    var isMobile = (ua.indexOf('mobile') !== -1 || ua.indexOf('android') !== -1);
    var InteractContext = (function () {
        function InteractContext(engine) {
            this.engine = engine;
        }
        InteractContext.prototype.setup = function (options) {
            if (options === void 0) { options = {}; }
            var canvas = options.canvas, touchHandlers = options.touchHandlers, touchEnabled = options.touchEnabled;
            this.touchHandlers = touchHandlers;
            this.canvas = canvas;
            if (touchEnabled) {
                this.addListeners();
            }
        };
        InteractContext.prototype.updateScale = function (scaleX, scaleY, rotation) {
            this.scaleX = scaleX;
            this.scaleY = scaleY;
            this.rotation = rotation;
        };
        InteractContext.prototype.addListeners = function () {
            var _this = this;
            if (window.navigator.msPointerEnabled) {
                this.canvas.addEventListener("MSPointerDown", function (event) {
                    event.identifier = event.pointerId;
                    _this.onTouchBegin(event);
                    _this.prevent(event);
                }, false);
                this.canvas.addEventListener("MSPointerMove", function (event) {
                    event.identifier = event.pointerId;
                    _this.onTouchMove(event);
                    _this.prevent(event);
                }, false);
                this.canvas.addEventListener("MSPointerUp", function (event) {
                    event.identifier = event.pointerId;
                    _this.onTouchEnd(event);
                    _this.prevent(event);
                }, false);
            }
            else {
                if (!isMobile) {
                    this.addMouseListener();
                }
                this.addTouchListener();
            }
        };
        InteractContext.prototype.prevent = function (event) {
            event.stopPropagation();
            if (event["isScroll"] != true && !this.canvas['userTyping']) {
                event.preventDefault();
            }
        };
        InteractContext.prototype.addMouseListener = function () {
            this.canvas.addEventListener("mousedown", this.onTouchBegin.bind(this));
            this.canvas.addEventListener("mousemove", this.onMouseMove.bind(this));
            this.canvas.addEventListener("mouseup", this.onTouchEnd.bind(this));
        };
        InteractContext.prototype.addTouchListener = function () {
            var _this = this;
            this.canvas.addEventListener("touchstart", function (event) {
                var e_1, _a;
                try {
                    for (var _b = __values(event.changedTouches), _c = _b.next(); !_c.done; _c = _b.next()) {
                        var touch = _c.value;
                        _this.onTouchBegin(touch);
                    }
                }
                catch (e_1_1) { e_1 = { error: e_1_1 }; }
                finally {
                    try {
                        if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
                    }
                    finally { if (e_1) throw e_1.error; }
                }
                _this.prevent(event);
            }, false);
            this.canvas.addEventListener("touchmove", function (event) {
                var e_2, _a;
                try {
                    for (var _b = __values(event.changedTouches), _c = _b.next(); !_c.done; _c = _b.next()) {
                        var touch = _c.value;
                        _this.onTouchMove(touch);
                    }
                }
                catch (e_2_1) { e_2 = { error: e_2_1 }; }
                finally {
                    try {
                        if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
                    }
                    finally { if (e_2) throw e_2.error; }
                }
                _this.prevent(event);
            }, false);
            this.canvas.addEventListener("touchend", function (event) {
                var e_3, _a;
                try {
                    for (var _b = __values(event.changedTouches), _c = _b.next(); !_c.done; _c = _b.next()) {
                        var touch = _c.value;
                        _this.onTouchEnd(touch);
                    }
                }
                catch (e_3_1) { e_3 = { error: e_3_1 }; }
                finally {
                    try {
                        if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
                    }
                    finally { if (e_3) throw e_3.error; }
                }
                _this.prevent(event);
            }, false);
            this.canvas.addEventListener("touchcancel", function (event) {
                var e_4, _a;
                try {
                    for (var _b = __values(event.changedTouches), _c = _b.next(); !_c.done; _c = _b.next()) {
                        var touch = _c.value;
                        _this.onTouchEnd(touch);
                    }
                }
                catch (e_4_1) { e_4 = { error: e_4_1 }; }
                finally {
                    try {
                        if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
                    }
                    finally { if (e_4) throw e_4.error; }
                }
                _this.prevent(event);
            }, false);
        };
        InteractContext.prototype.onTouchBegin = function (event) {
            var location = this.getLocation(event);
            this.touchHandlers.onTouchBegin(location);
        };
        InteractContext.prototype.onMouseMove = function (event) {
            if (event.buttons === 0) {
                this.onTouchEnd(event);
            }
            else {
                this.onTouchMove(event);
            }
        };
        InteractContext.prototype.onTouchMove = function (event) {
            var location = this.getLocation(event);
            this.touchHandlers.onTouchMove(location);
        };
        InteractContext.prototype.onTouchEnd = function (event) {
            var location = this.getLocation(event);
            this.touchHandlers.onTouchEnd(location);
        };
        InteractContext.prototype.getLocation = function (event) {
            return this.engine.pagePosToCanvasPos(event.pageX, event.pageY, event.identifier);
        };
        return InteractContext;
    }());

    var lastTime = 0;
    var vendors = ['webkit', 'moz'];
    for (var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
        window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'];
        window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame'] ||
            window[vendors[x] + 'CancelRequestAnimationFrame'];
    }
    if (!window.requestAnimationFrame) {
        window.requestAnimationFrame = function (callback) {
            var currTime = new Date().getTime();
            var timeToCall = Math.max(0, 16.7 - (currTime - lastTime));
            var id = window.setTimeout(function () {
                callback(currTime + timeToCall);
            }, timeToCall);
            lastTime = currTime + timeToCall;
            return id;
        };
    }
    if (!window.cancelAnimationFrame) {
        window.cancelAnimationFrame = function (id) {
            clearTimeout(id);
        };
    }

    var Bounds = (function () {
        function Bounds(x, y, width, height, onChange) {
            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;
            this._onChange = onChange;
        }
        Bounds.prototype.onModify = function (value, key, oldValue) {
            this._onChange && this._onChange(value, key, oldValue);
        };
        Object.defineProperty(Bounds.prototype, "left", {
            get: function () {
                return this.x;
            },
            set: function (v) {
                this.x = v;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Bounds.prototype, "top", {
            get: function () {
                return this.y;
            },
            set: function (v) {
                this.y = v;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Bounds.prototype, "right", {
            get: function () {
                return this.x + this.width;
            },
            set: function (v) {
                this.width = v - this.x;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Bounds.prototype, "bottom", {
            get: function () {
                return this.y + this.height;
            },
            set: function (v) {
                this.height = v - this.y;
            },
            enumerable: true,
            configurable: true
        });
        Bounds.prototype.contains = function (x, y) {
            return this.x <= x &&
                this.x + this.width >= x &&
                this.y <= y &&
                this.y + this.height >= y;
        };
        Bounds.prototype.setTo = function (x, y, width, height) {
            this.x = x;
            this.y = y;
            this.width = width;
            this.height = height;
        };
        Bounds.prototype.copyFrom = function (target) {
            this.x = target.x;
            this.y = target.y;
            this.width = target.width;
            this.height = target.height;
        };
        Bounds.prototype.clone = function () {
            return new Bounds(this.x, this.y, this.width, this.height);
        };
        Bounds.prototype.inflate = function (dx, dy) {
            this.x -= dx;
            this.width += 2 * dx;
            this.y -= dy;
            this.height += 2 * dy;
        };
        Object.defineProperty(Bounds.prototype, "isEmpty", {
            get: function () {
                return this.width <= 0 || this.height <= 0;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Bounds.prototype, "isZero", {
            get: function () {
                return this.x === 0 && this.y === 0 && this.isEmpty;
            },
            enumerable: true,
            configurable: true
        });
        Bounds.prototype.setEmpty = function () {
            this.x = 0;
            this.y = 0;
            this.width = 0;
            this.height = 0;
        };
        Bounds.prototype.intersects = function (toIntersect) {
            return Math.max(this.x, toIntersect.x) <= Math.min(this.right, toIntersect.right)
                && Math.max(this.y, toIntersect.y) <= Math.min(this.bottom, toIntersect.bottom);
        };
        Bounds.prototype.containsBounds = function (bounds) {
            var r1 = bounds.x + bounds.width;
            var b1 = bounds.y + bounds.height;
            var r2 = this.x + this.width;
            var b2 = this.y + this.height;
            return (bounds.x >= this.x) && (bounds.x < r2) && (bounds.y >= this.y) && (bounds.y < b2) && (r1 > this.x) && (r1 <= r2) && (b1 > this.y) && (b1 <= b2);
        };
        Bounds.prototype.equals = function (toCompare) {
            if (this === toCompare) {
                return true;
            }
            return this.x === toCompare.x && this.y === toCompare.y
                && this.width === toCompare.width && this.height === toCompare.height;
        };
        Bounds.prototype.toString = function () {
            var _a = this, x = _a.x, y = _a.y, width = _a.width, height = _a.height;
            return "(x=" + x + ", y=" + y + ", width=" + width + ", height=" + height + ")";
        };
        __decorate([
            dirtyFieldTrigger
        ], Bounds.prototype, "x", void 0);
        __decorate([
            dirtyFieldTrigger
        ], Bounds.prototype, "y", void 0);
        __decorate([
            dirtyFieldTrigger
        ], Bounds.prototype, "width", void 0);
        __decorate([
            dirtyFieldTrigger
        ], Bounds.prototype, "height", void 0);
        return Bounds;
    }());

    var Texture = (function (_super) {
        __extends(Texture, _super);
        function Texture() {
            var _this = _super.call(this) || this;
            _this['isDirty'] = true;
            _this._bounds = new Bounds(0, 0, 0, 0, function () {
                _this['isDirty'] = true;
            });
            return _this;
        }
        Texture.prototype.setFrame = function (frame) {
            var x = frame.x, y = frame.y, w = frame.w, h = frame.h;
            this._bounds.setTo(x, y, w, h);
        };
        Texture.prototype.setImg = function (img) {
            this.img = img;
        };
        Object.defineProperty(Texture.prototype, "width", {
            get: function () {
                return this._bounds.width;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Texture.prototype, "height", {
            get: function () {
                return this._bounds.height;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Texture.prototype, "bounds", {
            get: function () {
                return this._bounds;
            },
            enumerable: true,
            configurable: true
        });
        Texture.prototype.getCacheCanvas = function () {
            var canvas = this._cacheCanvas;
            if (this['isDirty']) {
                this['isDirty'] = false;
                var _a = this._bounds, width = _a.width, height = _a.height;
                if (!canvas) {
                    canvas = this._cacheCanvas = createCanvas();
                }
                var context = this._cacheContext;
                if (!context) {
                    context = canvas.getContext('2d');
                }
                canvas.width = width;
                canvas.height = height;
                this.drawToCanvas(context);
                this.drawToCanvas(context);
            }
            return canvas;
        };
        Texture.prototype.drawToCanvas = function (context, dx, dy, sx, sy, dw, dh) {
            if (dx === void 0) { dx = 0; }
            if (dy === void 0) { dy = 0; }
            var _a = this._bounds, x = _a.x, y = _a.y, width = _a.width, height = _a.height;
            context.drawImage(this.img, sx || x, sy || y, width, height, dx, dy, dw || width, dh || height);
        };
        Texture.prototype.destroy = function () {
            this.img = null;
            this._bounds = null;
            this.destroyCacheCanvas();
        };
        Texture.prototype.destroyCacheCanvas = function () {
            this._cacheCanvas = null;
        };
        __decorate([
            dirtyFieldDetector
        ], Texture.prototype, "img", void 0);
        return Texture;
    }(HashObject));
    function createTexture(img, frame) {
        var texture = new Texture();
        texture.setImg(img);
        texture.setFrame(frame || { x: 0, y: 0, w: img.width, h: img.height });
        return texture;
    }

    var Sheet = (function (_super) {
        __extends(Sheet, _super);
        function Sheet(img, frames) {
            var _this = _super.call(this) || this;
            _this._textureCache = {};
            if (img) {
                _this.img = img;
            }
            if (frames) {
                _this.frames = frames;
            }
            return _this;
        }
        Sheet.prototype.generateAll = function () {
            for (var key in this.frames) {
                this.generateTexture(key);
            }
        };
        Sheet.prototype.generateTexture = function (name, force) {
            if (force === void 0) { force = false; }
            var _a = this, img = _a.img, frames = _a.frames, _textureCache = _a._textureCache;
            if (!force && _textureCache[name]) {
                return _textureCache[name];
            }
            var frame = frames[name];
            if (frame) {
                return _textureCache[name] = createTexture(img, frame);
            }
        };
        Sheet.prototype.inputTexture = function (name, texture) {
            this._textureCache[name] = texture;
        };
        Sheet.prototype.hasTexture = function (name) {
            return !!this.frames[name];
        };
        Sheet.prototype.getTexture = function (name) {
            var texture = this._textureCache[name];
            if (texture) {
                return texture;
            }
            else {
                return this.generateTexture(name);
            }
        };
        Sheet.prototype.getAllTextures = function () {
            return this._textureCache;
        };
        Sheet.prototype.destroy = function () {
            this.img = null;
            for (var key in this._textureCache) {
                this._textureCache[key].destroy();
                delete this._textureCache[key];
            }
        };
        return Sheet;
    }(HashObject));

    var animationMap = {};
    var animDataMap = {};
    var textureMap = {};
    function getFrameAnimation(name) {
        var animation = animationMap[name];
        if (!animation) {
            animation = animationMap[name] = new FrameAnimationImpl(name);
            animation.fillMcData(name);
        }
        return animation;
    }
    function putFrameAnim(img, data) {
        var mc = data.mc, res = data.res;
        var sheet = new Sheet(img, res);
        for (var key in mc) {
            var animData = animDataMap[key] = mc[key];
            animData.sheet = sheet;
        }
    }
    var FrameAnimationImpl = (function () {
        function FrameAnimationImpl(name) {
            this._name = name;
        }
        Object.defineProperty(FrameAnimationImpl.prototype, "name", {
            get: function () {
                return this._name;
            },
            enumerable: true,
            configurable: true
        });
        FrameAnimationImpl.prototype.fillMcData = function (name) {
            var animData = animDataMap[name];
            if (animData) {
                this._animData = animData;
            }
            else {
                console.warn("anim data [" + name + "] is not exist");
            }
        };
        Object.defineProperty(FrameAnimationImpl.prototype, "fps", {
            get: function () {
                return this._animData.frameRate;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(FrameAnimationImpl.prototype, "labels", {
            get: function () {
                return this._animData.labels;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(FrameAnimationImpl.prototype, "frameCount", {
            get: function () {
                return this._animData.frames.length;
            },
            enumerable: true,
            configurable: true
        });
        FrameAnimationImpl.prototype.getLabel = function (name) {
            var e_1, _a;
            var result;
            try {
                for (var _b = __values(this._animData.labels), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var label = _c.value;
                    if (label.name == name) {
                        result = label;
                        break;
                    }
                }
            }
            catch (e_1_1) { e_1 = { error: e_1_1 }; }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
                }
                finally { if (e_1) throw e_1.error; }
            }
            return result;
        };
        FrameAnimationImpl.prototype.getFrame = function (frameIndex) {
            var _animData = this._animData;
            var texture, frameData;
            if (_animData) {
                var frames = _animData.frames;
                frameData = frames[frameIndex];
                if (frameData) {
                    var res = frameData.res;
                    texture = textureMap[res];
                    if (!texture) {
                        texture = textureMap[res] = _animData.sheet.getTexture(res);
                    }
                }
            }
            return {
                texture: texture,
                data: frameData,
            };
        };
        FrameAnimationImpl.prototype.destroy = function () {
            this._animData = null;
        };
        return FrameAnimationImpl;
    }());

    var AssetsManager = (function () {
        function AssetsManager() {
            this.resCache = {};
            this.resPath = '';
            this.resLoaderType = {
                '.json': this.loadJson,
                '.json5': this.loadJson5,
                '.txt': this.loadTxt,
                '.png': this.loadTexture,
                '.jpg': this.loadTexture,
                '.svg': this.loadTexture,
                '.bimg': this.loadTextureFromBlob,
                '.sht': this.loadSheet,
                '.sht-disperse': this.loadSheetDisperse,
                '.fnt': this.loadFont,
                '.anim': this.loadAnim,
                '.pfb': this.loadPrefab,
            };
        }
        AssetsManager.prototype.getLoader = function (ext, url) {
            ext = ext || url.substr(url.lastIndexOf('.'));
            return this.resLoaderType[ext] || this.loadAny;
        };
        AssetsManager.prototype.addLoader = function (ext, loader) {
            this.resLoaderType[ext] = loader;
        };
        AssetsManager.prototype.setResPath = function (path) {
            this.resPath = path;
        };
        AssetsManager.prototype.loadResItems = function (items, replaceConfig, progress) {
            var _this = this;
            var total = items.length;
            var count = 0;
            return Promise.all(items.map(function (item) {
                var uuid, url, config, ext;
                if (typeof item === 'string') {
                    url = item;
                }
                else {
                    url = item.url;
                }
                if (replaceConfig) {
                    url = replaceConfig[url] || url;
                }
                if (!url) {
                    return Promise.resolve();
                }
                if (typeof item === 'string') {
                    uuid = _this.getUUIDFromUrl(url);
                }
                else {
                    uuid = item.uuid || _this.getUUIDFromUrl(url);
                    ext = item.ext;
                    config = item.config;
                }
                var loader = _this.getLoader(ext, url);
                return loader.call(_this, url, uuid, true, config).then(function (res) {
                    count++;
                    progress && progress(count / total);
                    return res;
                });
            }));
        };
        AssetsManager.prototype.getRes = function (uuid) {
            if (this.resCacheProxy) {
                return this.resCacheProxy(uuid);
            }
            return this.resCache[uuid];
        };
        AssetsManager.prototype.setResCacheProxy = function (proxyFunc) {
            this.resCacheProxy = proxyFunc;
        };
        AssetsManager.prototype.destroyRes = function (uuidOrUuids) {
            if (Array.isArray(uuidOrUuids)) {
                while (uuidOrUuids.length > 0) {
                    delete this.resCache[uuidOrUuids.pop()];
                }
            }
            else {
                delete this.resCache[uuidOrUuids];
            }
        };
        AssetsManager.prototype.destroyAllRes = function () {
            for (var key in this.resCache) {
                this.destroyRes(key);
            }
        };
        AssetsManager.prototype.getAllResUuids = function () {
            return Object.keys(this.resCache);
        };
        AssetsManager.prototype.resolveUrl = function (url) {
            if (url.indexOf('//') === 0 || url.indexOf('http:') === 0 || url.indexOf('https:') === 0) {
                return url;
            }
            return this.resPath + url;
        };
        AssetsManager.prototype.getUUIDFromUrl = function (url) {
            return url.substring(url.lastIndexOf('/') + 1, url.lastIndexOf('.'));
        };
        AssetsManager.prototype.cacheRes = function (res, url, uuid) {
            uuid = uuid || this.getUUIDFromUrl(url);
            this.resCache[uuid] = res;
        };
        AssetsManager.prototype.loadAny = function (url, uuid, cache, config, options, type) {
            if (cache === void 0) { cache = true; }
            if (options === void 0) { options = {}; }
            if (type === void 0) { type = 'arraybuffer'; }
            return __awaiter(this, void 0, Promise, function () {
                var response, result;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0: return [4, fetch(this.resolveUrl(url), options)];
                        case 1:
                            response = _a.sent();
                            switch (type) {
                                case 'json':
                                    result = response.json();
                                    break;
                                case 'text':
                                    result = response.text();
                                    break;
                                case 'arraybuffer':
                                    result = response.arrayBuffer();
                                    break;
                                case 'blob':
                                    result = response.blob();
                                    break;
                            }
                            return [2, result];
                    }
                });
            });
        };
        AssetsManager.prototype.loadTxt = function (url, uuid, cache, config) {
            var _this = this;
            if (cache === void 0) { cache = true; }
            var p = this.loadAny(url, uuid, cache, config, undefined, 'text');
            if (cache) {
                p.then(function (data) {
                    _this.cacheRes(data, url, uuid);
                    return data;
                });
            }
            return p;
        };
        AssetsManager.prototype.loadJson = function (url, uuid, cache, config) {
            var _this = this;
            if (cache === void 0) { cache = true; }
            var p = this.loadAny(url, uuid, cache, config, undefined, 'json');
            if (cache) {
                p.then(function (data) {
                    _this.cacheRes(data, url, uuid);
                    return data;
                });
            }
            return p;
        };
        AssetsManager.prototype.loadJson5 = function (url, uuid, cache, config) {
            if (cache === void 0) { cache = true; }
            return __awaiter(this, void 0, Promise, function () {
                var txt, jsonData;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0: return [4, this.loadTxt(url, uuid)];
                        case 1:
                            txt = _a.sent();
                            jsonData = window['eval']("(" + txt + ")");
                            if (cache) {
                                this.cacheRes(jsonData, url, uuid);
                            }
                            return [2, jsonData];
                    }
                });
            });
        };
        AssetsManager.prototype.loadPrefab = function (url, uuid, cache, config) {
            if (cache === void 0) { cache = true; }
            return __awaiter(this, void 0, Promise, function () {
                var data;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0: return [4, this.loadJson5(url, uuid, false)];
                        case 1:
                            data = _a.sent();
                            if (cache) {
                                this.cacheRes(data, url, uuid);
                            }
                            return [2, data];
                    }
                });
            });
        };
        AssetsManager.prototype.loadSheet = function (url, uuid, cache, config) {
            var _this = this;
            if (cache === void 0) { cache = true; }
            var pngFile = url.substring(0, url.lastIndexOf('.')) + '.png';
            return Promise.all([
                this.loadJson(url, null, false),
                this.loadImage(pngFile, null, false),
            ]).then(function (result) {
                var e_1, _a;
                var data = result[0];
                var img = result[1];
                var sheet = new Sheet(img, data.frames);
                sheet.generateAll();
                if (cache) {
                    _this.cacheRes(sheet, url, uuid);
                    if (config) {
                        try {
                            for (var _b = __values(config.textures), _c = _b.next(); !_c.done; _c = _b.next()) {
                                var textureConfig = _c.value;
                                var name = textureConfig.name, uuid_1 = textureConfig.uuid;
                                var texture = sheet.getTexture(name);
                                _this.cacheRes(texture, name, uuid_1);
                            }
                        }
                        catch (e_1_1) { e_1 = { error: e_1_1 }; }
                        finally {
                            try {
                                if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
                            }
                            finally { if (e_1) throw e_1.error; }
                        }
                    }
                    else {
                        var textures = sheet.getAllTextures();
                        for (var key in textures) {
                            _this.cacheRes(textures[key], key, key);
                        }
                    }
                }
                return sheet;
            });
        };
        AssetsManager.prototype.loadSheetDisperse = function (url, uuid, cache, config) {
            if (cache === void 0) { cache = true; }
            return __awaiter(this, void 0, Promise, function () {
                var e_2, _a, sheet, _b, _c, _d, name, uuid_2, subUrl, texture, e_2_1;
                return __generator(this, function (_e) {
                    switch (_e.label) {
                        case 0:
                            sheet = new Sheet();
                            _e.label = 1;
                        case 1:
                            _e.trys.push([1, 6, 7, 8]);
                            _b = __values(config.textures), _c = _b.next();
                            _e.label = 2;
                        case 2:
                            if (!!_c.done) return [3, 5];
                            _d = _c.value, name = _d.name, uuid_2 = _d.uuid;
                            subUrl = url.replace('-disperse', '') + '/' + name;
                            return [4, this.loadTexture(subUrl, uuid_2)];
                        case 3:
                            texture = _e.sent();
                            sheet.inputTexture(name, texture);
                            _e.label = 4;
                        case 4:
                            _c = _b.next();
                            return [3, 2];
                        case 5: return [3, 8];
                        case 6:
                            e_2_1 = _e.sent();
                            e_2 = { error: e_2_1 };
                            return [3, 8];
                        case 7:
                            try {
                                if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
                            }
                            finally { if (e_2) throw e_2.error; }
                            return [7];
                        case 8:
                            if (cache) {
                                this.cacheRes(sheet, url, uuid);
                            }
                            return [2, sheet];
                    }
                });
            });
        };
        AssetsManager.prototype.loadFont = function (url, uuid, cache, config) {
            var _this = this;
            if (cache === void 0) { cache = true; }
            return this.loadSheet(url, null, false).then(function (sheet) {
                if (cache) {
                    _this.cacheRes(sheet, url, uuid);
                }
                return sheet;
            });
        };
        AssetsManager.prototype.findAnimConfig = function (animations, name) {
            var result;
            animations.some(function (item) {
                if (item.name === name) {
                    result = item;
                    return true;
                }
            });
            return result;
        };
        AssetsManager.prototype.loadAnim = function (url, uuid, cache, config) {
            var _this = this;
            if (cache === void 0) { cache = true; }
            var pngFile = url.substring(0, url.lastIndexOf('.')) + '.png';
            return Promise.all([
                this.loadJson(url, null, false),
                this.loadImage(pngFile, null, false),
            ]).then(function (result) {
                var data = result[0];
                var img = result[1];
                putFrameAnim(img, data);
                var animations = {};
                for (var name in data.mc) {
                    var animation = getFrameAnimation(name);
                    if (cache) {
                        var uuid_3 = name;
                        if (config) {
                            var cfg = _this.findAnimConfig(config.animations, name);
                            uuid_3 = cfg.uuid;
                        }
                        _this.cacheRes(animation, name, uuid_3);
                    }
                    animations[name] = animation;
                }
                if (cache) {
                    _this.cacheRes(animations, url, uuid);
                }
                return animations;
            });
        };
        AssetsManager.prototype.loadImage = function (url, uuid, cache, config) {
            var _this = this;
            if (cache === void 0) { cache = true; }
            return new Promise(function (resolve, reject) {
                var img = new Image();
                if (EngineConfig.imgCrossOrigin) {
                    img.setAttribute('crossOrigin', 'anonymous');
                }
                img.onload = function (e) {
                    resolve(img);
                };
                img.onerror = function (e) {
                    reject(e);
                };
                img.src = _this.resolveUrl(url);
            });
        };
        AssetsManager.prototype.loadImageFromBlob = function (url, uuid, cache, config) {
            if (cache === void 0) { cache = true; }
            return __awaiter(this, void 0, Promise, function () {
                var imgBlob, e_3;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            _a.trys.push([0, 3, , 4]);
                            return [4, this.loadAny(url, uuid, false, config, undefined, 'blob')];
                        case 1:
                            imgBlob = _a.sent();
                            return [4, this.blobToImage(imgBlob)];
                        case 2: return [2, _a.sent()];
                        case 3:
                            e_3 = _a.sent();
                            console.log(e_3);
                            return [3, 4];
                        case 4: return [2];
                    }
                });
            });
        };
        AssetsManager.prototype.loadTexture = function (url, uuid, cache, config) {
            if (cache === void 0) { cache = true; }
            return __awaiter(this, void 0, Promise, function () {
                var img, texture;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0: return [4, this.loadImage(url, uuid, false)];
                        case 1:
                            img = _a.sent();
                            texture = createTexture(img);
                            if (cache) {
                                this.cacheRes(texture, url, uuid);
                            }
                            return [2, texture];
                    }
                });
            });
        };
        AssetsManager.prototype.loadTextureFromBlob = function (url, uuid, cache, config) {
            if (cache === void 0) { cache = true; }
            return __awaiter(this, void 0, Promise, function () {
                var img, texture;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0: return [4, this.loadImageFromBlob(url, uuid, false)];
                        case 1:
                            img = _a.sent();
                            texture = createTexture(img);
                            if (cache) {
                                this.cacheRes(texture, url, uuid);
                            }
                            return [2, texture];
                    }
                });
            });
        };
        AssetsManager.prototype.fileOrBlobToDataURL = function (obj) {
            return new Promise(function (resolve, reject) {
                var a = new FileReader();
                a.readAsDataURL(obj);
                a.onload = function (e) {
                    resolve(e.target['result']);
                };
                a.onerror = function (e) {
                    reject(e);
                };
            });
        };
        AssetsManager.prototype.blobToImage = function (blob) {
            return __awaiter(this, void 0, void 0, function () {
                var dataUrl;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0: return [4, this.fileOrBlobToDataURL(blob)];
                        case 1:
                            dataUrl = _a.sent();
                            return [2, new Promise(function (resolve, reject) {
                                    var img = new Image();
                                    if (EngineConfig.imgCrossOrigin) {
                                        img.setAttribute('crossOrigin', 'anonymous');
                                    }
                                    img.onload = function () {
                                        resolve(img);
                                    };
                                    img.onerror = function (e) {
                                        reject(e);
                                    };
                                    img.src = dataUrl;
                                })];
                    }
                });
            });
        };
        return AssetsManager;
    }());

    var has = Object.prototype.hasOwnProperty, prefix = '~';
    function Events() { }
    if (Object.create) {
        Events.prototype = Object.create(null);
        if (!new Events().__proto__)
            prefix = '';
    }
    function EE(fn, context, once) {
        this.fn = fn;
        this.context = context;
        this.once = once || false;
    }
    function addListener(emitter, event, fn, context, once) {
        if (typeof fn !== 'function') {
            throw new TypeError('The listener must be a function');
        }
        var listener = new EE(fn, context || emitter, once), evt = prefix ? prefix + event : event;
        if (!emitter._events[evt])
            emitter._events[evt] = listener, emitter._eventsCount++;
        else if (!emitter._events[evt].fn)
            emitter._events[evt].push(listener);
        else
            emitter._events[evt] = [emitter._events[evt], listener];
        return emitter;
    }
    function clearEvent(emitter, evt) {
        if (--emitter._eventsCount === 0)
            emitter._events = new Events();
        else
            delete emitter._events[evt];
    }
    var EventEmitter = (function () {
        function EventEmitter() {
            this._events = new Events();
            this._eventsCount = 0;
            this.off = this.removeListener;
            this.addListener = this.on;
        }
        Object.defineProperty(EventEmitter, "prefixed", {
            get: function () {
                return prefix;
            },
            enumerable: true,
            configurable: true
        });
        EventEmitter.prototype.eventNames = function () {
            var names = [], events, name;
            if (this._eventsCount === 0)
                return names;
            for (name in (events = this._events)) {
                if (has.call(events, name))
                    names.push(prefix ? name.slice(1) : name);
            }
            return names;
        };
        EventEmitter.prototype.listeners = function (event) {
            var evt = prefix ? prefix + event : event, handlers = this._events[evt];
            if (!handlers)
                return [];
            if (handlers.fn)
                return [handlers.fn];
            for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {
                ee[i] = handlers[i].fn;
            }
            return ee;
        };
        EventEmitter.prototype.listenerCount = function (event) {
            var evt = prefix ? prefix + event : event, listeners = this._events[evt];
            if (!listeners)
                return 0;
            if (listeners.fn)
                return 1;
            return listeners.length;
        };
        EventEmitter.prototype.emit = function (event, a1, a2, a3, a4, a5) {
            var evt = prefix ? prefix + event : event;
            if (!this._events[evt])
                return false;
            var listeners = this._events[evt], len = arguments.length, args, i;
            if (listeners.fn) {
                if (listeners.once)
                    this.removeListener(event, listeners.fn, undefined, true);
                switch (len) {
                    case 1: return listeners.fn.call(listeners.context), true;
                    case 2: return listeners.fn.call(listeners.context, a1), true;
                    case 3: return listeners.fn.call(listeners.context, a1, a2), true;
                    case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;
                    case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
                    case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
                }
                for (i = 1, args = new Array(len - 1); i < len; i++) {
                    args[i - 1] = arguments[i];
                }
                listeners.fn.apply(listeners.context, args);
            }
            else {
                var length = listeners.length, j;
                for (i = 0; i < length; i++) {
                    if (listeners[i].once)
                        this.removeListener(event, listeners[i].fn, undefined, true);
                    switch (len) {
                        case 1:
                            listeners[i].fn.call(listeners[i].context);
                            break;
                        case 2:
                            listeners[i].fn.call(listeners[i].context, a1);
                            break;
                        case 3:
                            listeners[i].fn.call(listeners[i].context, a1, a2);
                            break;
                        case 4:
                            listeners[i].fn.call(listeners[i].context, a1, a2, a3);
                            break;
                        default:
                            if (!args)
                                for (j = 1, args = new Array(len - 1); j < len; j++) {
                                    args[j - 1] = arguments[j];
                                }
                            listeners[i].fn.apply(listeners[i].context, args);
                    }
                }
            }
            return true;
        };
        EventEmitter.prototype.on = function (event, fn, context) {
            return addListener(this, event, fn, context, false);
        };
        EventEmitter.prototype.once = function (event, fn, context) {
            return addListener(this, event, fn, context, true);
        };
        EventEmitter.prototype.removeListener = function (event, fn, context, once) {
            var evt = prefix ? prefix + event : event;
            if (!this._events[evt])
                return this;
            if (!fn) {
                clearEvent(this, evt);
                return this;
            }
            var listeners = this._events[evt];
            if (listeners.fn) {
                if (listeners.fn === fn &&
                    (!once || listeners.once) &&
                    (!context || listeners.context === context)) {
                    clearEvent(this, evt);
                }
            }
            else {
                for (var i = 0, events = [], length = listeners.length; i < length; i++) {
                    if (listeners[i].fn !== fn ||
                        (once && !listeners[i].once) ||
                        (context && listeners[i].context !== context)) {
                        events.push(listeners[i]);
                    }
                }
                if (events.length)
                    this._events[evt] = events.length === 1 ? events[0] : events;
                else
                    clearEvent(this, evt);
            }
            return this;
        };
        EventEmitter.prototype.removeAllListeners = function (event) {
            var evt;
            if (event) {
                evt = prefix ? prefix + event : event;
                if (this._events[evt])
                    clearEvent(this, evt);
            }
            else {
                this._events = new Events();
                this._eventsCount = 0;
            }
            return this;
        };
        return EventEmitter;
    }());

    var Ease;
    (function (Ease) {
        Ease["linear"] = "linear";
        Ease["quadIn"] = "quadIn";
        Ease["quadOut"] = "quadOut";
        Ease["quadInOut"] = "quadInOut";
        Ease["cubicIn"] = "cubicIn";
        Ease["cubicOut"] = "cubicOut";
        Ease["cubicInOut"] = "cubicInOut";
        Ease["quartIn"] = "quartIn";
        Ease["quartOut"] = "quartOut";
        Ease["quartInOut"] = "quartInOut";
        Ease["quintIn"] = "quintIn";
        Ease["quintOut"] = "quintOut";
        Ease["quintInOut"] = "quintInOut";
        Ease["sineIn"] = "sineIn";
        Ease["sineOut"] = "sineOut";
        Ease["sineInOut"] = "sineInOut";
        Ease["backIn"] = "backIn";
        Ease["backOut"] = "backOut";
        Ease["backInOut"] = "backInOut";
        Ease["circIn"] = "circIn";
        Ease["circOut"] = "circOut";
        Ease["circInOut"] = "circInOut";
        Ease["bounceIn"] = "bounceIn";
        Ease["bounceOut"] = "bounceOut";
        Ease["bounceInOut"] = "bounceInOut";
        Ease["elasticIn"] = "elasticIn";
        Ease["elasticOut"] = "elasticOut";
        Ease["elasticInOut"] = "elasticInOut";
    })(Ease || (Ease = {}));
    function linear(t) {
        return t;
    }
    function get(amount) {
        if (amount < -1) {
            amount = -1;
        }
        if (amount > 1) {
            amount = 1;
        }
        return function (t) {
            if (amount == 0) {
                return t;
            }
            if (amount < 0) {
                return t * (t * -amount + 1 + amount);
            }
            return t * ((2 - t) * amount + (1 - amount));
        };
    }
    function getPowIn(pow) {
        return function (t) {
            return Math.pow(t, pow);
        };
    }
    function getPowOut(pow) {
        return function (t) {
            return 1 - Math.pow(1 - t, pow);
        };
    }
    function getPowInOut(pow) {
        return function (t) {
            if ((t *= 2) < 1)
                return 0.5 * Math.pow(t, pow);
            return 1 - 0.5 * Math.abs(Math.pow(2 - t, pow));
        };
    }
    var quadIn = getPowIn(2);
    var quadOut = getPowOut(2);
    var quadInOut = getPowInOut(2);
    var cubicIn = getPowIn(3);
    var cubicOut = getPowOut(3);
    var cubicInOut = getPowInOut(3);
    var quartIn = getPowIn(4);
    var quartOut = getPowOut(4);
    var quartInOut = getPowInOut(4);
    var quintIn = getPowIn(5);
    var quintOut = getPowOut(5);
    var quintInOut = getPowInOut(5);
    function sineIn(t) {
        return 1 - Math.cos(t * Math.PI / 2);
    }
    function sineOut(t) {
        return Math.sin(t * Math.PI / 2);
    }
    function sineInOut(t) {
        return -0.5 * (Math.cos(Math.PI * t) - 1);
    }
    function getBackIn(amount) {
        return function (t) {
            return t * t * ((amount + 1) * t - amount);
        };
    }
    var backIn = getBackIn(1.7);
    function getBackOut(amount) {
        return function (t) {
            return (--t * t * ((amount + 1) * t + amount) + 1);
        };
    }
    var backOut = getBackOut(1.7);
    function getBackInOut(amount) {
        amount *= 1.525;
        return function (t) {
            if ((t *= 2) < 1)
                return 0.5 * (t * t * ((amount + 1) * t - amount));
            return 0.5 * ((t -= 2) * t * ((amount + 1) * t + amount) + 2);
        };
    }
    var backInOut = getBackInOut(1.7);
    function circIn(t) {
        return -(Math.sqrt(1 - t * t) - 1);
    }
    function circOut(t) {
        return Math.sqrt(1 - (--t) * t);
    }
    function circInOut(t) {
        if ((t *= 2) < 1) {
            return -0.5 * (Math.sqrt(1 - t * t) - 1);
        }
        return 0.5 * (Math.sqrt(1 - (t -= 2) * t) + 1);
    }
    function bounceIn(t) {
        return 1 - bounceOut(1 - t);
    }
    function bounceOut(t) {
        if (t < 1 / 2.75) {
            return (7.5625 * t * t);
        }
        else if (t < 2 / 2.75) {
            return (7.5625 * (t -= 1.5 / 2.75) * t + 0.75);
        }
        else if (t < 2.5 / 2.75) {
            return (7.5625 * (t -= 2.25 / 2.75) * t + 0.9375);
        }
        else {
            return (7.5625 * (t -= 2.625 / 2.75) * t + 0.984375);
        }
    }
    function bounceInOut(t) {
        if (t < 0.5)
            return bounceIn(t * 2) * .5;
        return bounceOut(t * 2 - 1) * 0.5 + 0.5;
    }
    function getElasticIn(amplitude, period) {
        var pi2 = Math.PI * 2;
        return function (t) {
            if (t == 0 || t == 1)
                return t;
            var s = period / pi2 * Math.asin(1 / amplitude);
            return -(amplitude * Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * pi2 / period));
        };
    }
    var elasticIn = getElasticIn(1, 0.3);
    function getElasticOut(amplitude, period) {
        var pi2 = Math.PI * 2;
        return function (t) {
            if (t == 0 || t == 1)
                return t;
            var s = period / pi2 * Math.asin(1 / amplitude);
            return (amplitude * Math.pow(2, -10 * t) * Math.sin((t - s) * pi2 / period) + 1);
        };
    }
    var elasticOut = getElasticOut(1, 0.3);
    function getElasticInOut(amplitude, period) {
        var pi2 = Math.PI * 2;
        return function (t) {
            var s = period / pi2 * Math.asin(1 / amplitude);
            if ((t *= 2) < 1)
                return -0.5 * (amplitude * Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * pi2 / period));
            return amplitude * Math.pow(2, -10 * (t -= 1)) * Math.sin((t - s) * pi2 / period) * 0.5 + 1;
        };
    }
    var elasticInOut = getElasticInOut(1, 0.3 * 1.5);

    var ease = /*#__PURE__*/Object.freeze({
        get Ease () { return Ease; },
        linear: linear,
        get: get,
        getPowIn: getPowIn,
        getPowOut: getPowOut,
        getPowInOut: getPowInOut,
        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,
        getBackIn: getBackIn,
        backIn: backIn,
        getBackOut: getBackOut,
        backOut: backOut,
        getBackInOut: getBackInOut,
        backInOut: backInOut,
        circIn: circIn,
        circOut: circOut,
        circInOut: circInOut,
        bounceIn: bounceIn,
        bounceOut: bounceOut,
        bounceInOut: bounceInOut,
        getElasticIn: getElasticIn,
        elasticIn: elasticIn,
        getElasticOut: getElasticOut,
        elasticOut: elasticOut,
        getElasticInOut: getElasticInOut,
        elasticInOut: elasticInOut
    });

    function lerp(begin, end, t, allowOutOfBounds) {
        if (allowOutOfBounds === void 0) { allowOutOfBounds = false; }
        var type = typeof begin;
        if (type !== typeof end) {
            console.error('begin and end need same type');
        }
        if (!allowOutOfBounds) {
            t = Math.max(0, Math.min(1, t));
        }
        var sign = end - begin;
        sign = sign > 0 ? 1 : (sign < 0 ? -1 : 0);
        var distance = Math.abs(end - begin);
        return begin + distance * t * sign;
    }
    function lerpObj(begin, end, t, fields, allowOutOfBounds) {
        var e_1, _a;
        if (allowOutOfBounds === void 0) { allowOutOfBounds = false; }
        var type = typeof begin;
        if (type !== typeof end) {
            console.error('begin and end need same type');
        }
        var temp = {};
        try {
            for (var fields_1 = __values(fields), fields_1_1 = fields_1.next(); !fields_1_1.done; fields_1_1 = fields_1.next()) {
                var field = fields_1_1.value;
                temp[field] = lerp(begin[field], end[field], t, allowOutOfBounds);
            }
        }
        catch (e_1_1) { e_1 = { error: e_1_1 }; }
        finally {
            try {
                if (fields_1_1 && !fields_1_1.done && (_a = fields_1.return)) _a.call(fields_1);
            }
            finally { if (e_1) throw e_1.error; }
        }
        return temp;
    }
    function makeRandomInt(max, min) {
        if (min === void 0) { min = 0; }
        return Math.floor(Math.random() * (max - min)) + min;
    }

    var DataCenter = (function (_super) {
        __extends(DataCenter, _super);
        function DataCenter() {
            var _this = _super !== null && _super.apply(this, arguments) || this;
            _this.store = {};
            return _this;
        }
        DataCenter.prototype.register = function (type) {
            this.store[type] = this.store[type] || {};
        };
        DataCenter.prototype.clean = function (type) {
            var e_1, _a;
            var target = type ? this.store[type] : this.store;
            if (target) {
                var keys = Object.keys(target);
                try {
                    for (var keys_1 = __values(keys), keys_1_1 = keys_1.next(); !keys_1_1.done; keys_1_1 = keys_1.next()) {
                        var key = keys_1_1.value;
                        delete target[key];
                    }
                }
                catch (e_1_1) { e_1 = { error: e_1_1 }; }
                finally {
                    try {
                        if (keys_1_1 && !keys_1_1.done && (_a = keys_1.return)) _a.call(keys_1);
                    }
                    finally { if (e_1) throw e_1.error; }
                }
            }
        };
        DataCenter.prototype.set = function (type, key, value) {
            if (arguments.length <= 2) {
                this.store[type] = key;
            }
            else {
                this.store[type][key] = value;
            }
        };
        DataCenter.prototype.get = function (type, key) {
            if (!key)
                return this.store[type];
            return this.store[type][key];
        };
        DataCenter.prototype.use = function (type, key) {
            var _this = this;
            return function (resopnse) {
                _this.set(type, key, resopnse);
                return resopnse;
            };
        };
        DataCenter.prototype.parse = function (type, expression) {
            var entity = this.store[type];
            var result = null;
            try {
                result = dotEval(expression, entity);
            }
            catch (e) {
            }
            return result;
        };
        return DataCenter;
    }(EventEmitter));

    var ScillaEngine = (function () {
        function ScillaEngine() {
            var _this = this;
            this.engineConfig = {
                fps: 60,
                designWidth: 750,
                designHeight: 1334,
                scaleMode: ScaleMode.FIXED_WIDTH,
                touchEnabled: true,
            };
            this.customConfig = {};
            this.dataCenterConfig = {};
            this._flush = 0;
            this._currentFlush = 0;
            this.lastFPS = 0;
            this.nextTicks = [];
            this.defMap = {};
            this.flush = function (tsNow) {
                if (_this._flush == 0) {
                    _this.onFrameTick(tsNow);
                }
                else {
                    if (_this._currentFlush == 0) {
                        _this.onFrameTick(tsNow);
                        _this._currentFlush = _this._flush;
                    }
                    else {
                        _this._currentFlush--;
                    }
                }
                _this.tickId = requestAnimationFrame(_this.flush);
            };
            this._assetsManager = new AssetsManager();
            this._dataCenter = new DataCenter();
        }
        ScillaEngine.prototype.registerDef = function (name, def) {
            this.defMap[name] = def;
            def.__class__ = name;
        };
        ScillaEngine.prototype.unregisterDef = function (name) {
            delete this.defMap[name];
        };
        ScillaEngine.prototype.getDefByName = function (name, showWarn) {
            if (showWarn === void 0) { showWarn = true; }
            var def;
            def = this.defMap[name];
            if (!def && showWarn) {
                console.warn('missing def:', name);
                return;
            }
            return def;
        };
        ScillaEngine.prototype.setup = function (_engineConfig, _customConfig, _dataCenterConfig) {
            var e_1, _a;
            injectProp(this.engineConfig, _engineConfig);
            injectProp(this.customConfig, _customConfig);
            injectProp(this.dataCenterConfig, _dataCenterConfig);
            if (this.dataCenterConfig.dataCenterRoot) {
                try {
                    for (var _b = __values(this.dataCenterConfig.dataCenterRoot), _c = _b.next(); !_c.done; _c = _b.next()) {
                        var item = _c.value;
                        this._dataCenter.register(item);
                    }
                }
                catch (e_1_1) { e_1 = { error: e_1_1 }; }
                finally {
                    try {
                        if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
                    }
                    finally { if (e_1) throw e_1.error; }
                }
            }
            var _d = this.engineConfig, canvas = _d.canvas, designWidth = _d.designWidth, designHeight = _d.designHeight, scaleMode = _d.scaleMode, modifyCanvasSize = _d.modifyCanvasSize, touchEnabled = _d.touchEnabled;
            this._canvasElement = typeof canvas == 'string' ? document.getElementById(canvas) : canvas;
            this._interactContext = new InteractContext(this);
            this._interactContext.setup({
                canvas: this._canvasElement,
                touchHandlers: {
                    onTouchBegin: this.onTouchBegin.bind(this),
                    onTouchMove: this.onTouchMove.bind(this),
                    onTouchEnd: this.onTouchEnd.bind(this),
                },
                touchEnabled: touchEnabled,
            });
            this._renderContext = new RenderContext(this);
            this._renderContext.setup({
                canvas: this._canvasElement,
                designWidth: designWidth,
                designHeight: designHeight,
                scaleMode: scaleMode,
                modifyCanvasSize: modifyCanvasSize,
                onUpdateScale: this.onUpdateScale.bind(this),
            });
            this._root = new RootEntity(this);
            this._root._restrict();
        };
        ScillaEngine.prototype.start = function () {
            this._root.enabled = true;
            this.tsStart = -1;
            this.startTick();
        };
        ScillaEngine.prototype.pause = function () {
            this._root.enabled = false;
            this.stopTick();
        };
        Object.defineProperty(ScillaEngine.prototype, "root", {
            get: function () {
                return this._root;
            },
            enumerable: true,
            configurable: true
        });
        ScillaEngine.prototype.getEntityPath = function (entity) {
            var path = '';
            var current = entity || this._root;
            while (current.parent) {
                path = current.parent.children.indexOf(current) + (path.length > 0 ? '|' : '') + path;
                current = current.parent;
            }
            return path;
        };
        ScillaEngine.prototype.getEntityByPath = function (path) {
            var e_2, _a;
            var target = this._root;
            if (path.length > 0) {
                var arr = path.split('|');
                try {
                    for (var arr_1 = __values(arr), arr_1_1 = arr_1.next(); !arr_1_1.done; arr_1_1 = arr_1.next()) {
                        var item = arr_1_1.value;
                        target = target.children[item];
                        if (!target) {
                            target = null;
                            break;
                        }
                    }
                }
                catch (e_2_1) { e_2 = { error: e_2_1 }; }
                finally {
                    try {
                        if (arr_1_1 && !arr_1_1.done && (_a = arr_1.return)) _a.call(arr_1);
                    }
                    finally { if (e_2) throw e_2.error; }
                }
            }
            return target;
        };
        ScillaEngine.prototype.getFPS = function () {
            return this.lastFPS;
        };
        Object.defineProperty(ScillaEngine.prototype, "renderContext", {
            get: function () {
                return this._renderContext;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ScillaEngine.prototype, "interactContext", {
            get: function () {
                return this._interactContext;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ScillaEngine.prototype, "assetsManager", {
            get: function () {
                return this._assetsManager;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ScillaEngine.prototype, "canvasElement", {
            get: function () {
                return this._canvasElement;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ScillaEngine.prototype, "dataCenter", {
            get: function () {
                return this._dataCenter;
            },
            enumerable: true,
            configurable: true
        });
        ScillaEngine.prototype.onUpdateScale = function (scaleX, scaleY, rotation) {
            this._interactContext.updateScale(scaleX, scaleY, rotation);
        };
        ScillaEngine.prototype.startTick = function () {
            this._flush = 60 / this.engineConfig.fps - 1 >> 0;
            if (this._flush < 0) {
                this._flush = 0;
            }
            this.tickId = requestAnimationFrame(this.flush);
        };
        ScillaEngine.prototype.stopTick = function () {
            cancelAnimationFrame(this.tickId);
        };
        ScillaEngine.prototype.nextTick = function (func, tickCount) {
            if (tickCount === void 0) { tickCount = 1; }
            this.nextTicks.push({ func: func, tickCount: tickCount });
        };
        ScillaEngine.prototype.onFrameTick = function (tsNow) {
            if (this.tsStart < 0) {
                this.tsStart = tsNow;
            }
            this._renderContext.clear();
            this.lastFPS = Math.floor(1000 / (tsNow - this.tsLast));
            this.tsLast = tsNow;
            var ts = tsNow - this.tsStart;
            traverse(this._root, function (child) {
                if (!child.isFree && child.enabled) {
                    child.$onUpdate(ts);
                }
                else {
                    return true;
                }
            }, -1, true, function (current) {
                current.$afterUpdate();
            });
            for (var i = 0, li = this.nextTicks.length; i < li; i++) {
                var item = this.nextTicks[i];
                item.tickCount--;
                if (item.tickCount <= 0) {
                    item.func(ts);
                    this.nextTicks.splice(i, 1);
                    i--;
                    li--;
                }
            }
        };
        ScillaEngine.prototype.onTouchBegin = function (event) {
            traversePostorder(this._root, function (child) {
                return child.onInteract(0, event);
            });
        };
        ScillaEngine.prototype.onTouchMove = function (event) {
            traversePostorder(this._root, function (child) {
                return child.onInteract(1, event);
            });
        };
        ScillaEngine.prototype.onTouchEnd = function (event) {
            traversePostorder(this._root, function (child) {
                return child.onInteract(2, event);
            });
        };
        ScillaEngine.prototype.getEntitiesByRayTest = function (x, y, ignoreMask) {
            if (ignoreMask === void 0) { ignoreMask = true; }
            var entities = [];
            var localPos = {};
            var rendererDef = this.getDefByName('components/renderer/Renderer');
            traversePostorder(this._root, function (child) {
                var e_3, _a;
                var transform = child.components[0];
                var matrix = transform['getMatrix'](true, true, true);
                matrix.transformPoint(x, y, localPos);
                var renderers = child.getComponents(rendererDef);
                var result = false;
                try {
                    for (var renderers_1 = __values(renderers), renderers_1_1 = renderers_1.next(); !renderers_1_1.done; renderers_1_1 = renderers_1.next()) {
                        var renderer = renderers_1_1.value;
                        if ((ignoreMask || !renderer['isUsedToMask']) && renderer['hitTest'](localPos.x, localPos.y)) {
                            result = true;
                            break;
                        }
                    }
                }
                catch (e_3_1) { e_3 = { error: e_3_1 }; }
                finally {
                    try {
                        if (renderers_1_1 && !renderers_1_1.done && (_a = renderers_1.return)) _a.call(renderers_1);
                    }
                    finally { if (e_3) throw e_3.error; }
                }
                if (result) {
                    entities.push(child);
                }
                return false;
            });
            return entities;
        };
        ScillaEngine.prototype.pagePosToCanvasPos = function (pageX, pageY, identifier, isLocalPos) {
            if (isLocalPos === void 0) { isLocalPos = false; }
            var _a = this.renderContext, scaleX = _a.scaleX, scaleY = _a.scaleY, rotation = _a.rotation;
            var x = pageX, y = pageY;
            var box = this._canvasElement.getBoundingClientRect();
            if (!isLocalPos) {
                var doc = document.documentElement;
                var left = box.left + window.pageXOffset - doc.clientLeft;
                var top = box.top + window.pageYOffset - doc.clientTop;
                x = pageX - left;
                y = pageY - top;
            }
            var newX = x;
            var newY = y;
            if (rotation === 90) {
                newX = y;
                newY = box.width - x;
            }
            else if (rotation === -90) {
                newX = box.height - y;
                newY = x;
            }
            newX = newX / scaleX;
            newY = newY / scaleY;
            return {
                x: Math.round(newX),
                y: Math.round(newY),
                identifier: identifier || 0,
            };
        };
        ScillaEngine.prototype.canvasPosToPagePos = function (x, y, isLocalPos) {
            if (isLocalPos === void 0) { isLocalPos = true; }
            var _a = this.renderContext, scaleX = _a.scaleX, scaleY = _a.scaleY, rotation = _a.rotation;
            x = x * scaleX;
            y = y * scaleY;
            if (!isLocalPos) {
                var box = this._canvasElement.getBoundingClientRect();
                var doc = document.documentElement;
                var left = box.left + window.pageXOffset - doc.clientLeft;
                var top = box.top + window.pageYOffset - doc.clientTop;
                x += left;
                y += top;
            }
            return {
                x: x, y: y,
            };
        };
        return ScillaEngine;
    }());
    var engine = new ScillaEngine();

    var entityMap = {};
    var prefabID = 0;
    var _getResProxy;
    function setGetResProxy(func) {
        _getResProxy = func;
    }
    function setupScene(config, root, getResProxy) {
        setGetResProxy(getResProxy);
        instantiateConfig(config, root);
    }
    function cleanEntity(entity) {
        entity.removeAllComponents();
        entity.removeChildren();
    }
    function instantiate(config) {
        var pid = ++prefabID;
        var entity = instantiateConfig(config, null, pid);
        return entity.children[0];
    }
    function instantiateConfig(config, root, pid) {
        var rootConfig = config.root;
        var entity = setupEntity(rootConfig, root, pid);
        setupComponent(rootConfig, entity, true);
        injectComponent(rootConfig, entity, true, pid);
        traverse(entity, function (child) {
            child.active();
            return false;
        });
        entityMap = {};
        return entity;
    }
    function setupEntity(config, root, pid) {
        var entity = null;
        if (config) {
            var name = config.name, uuid = config.uuid, children = config.children;
            if (pid !== undefined && uuid !== undefined) {
                uuid = pid + '_' + uuid;
            }
            entity = root || new Entity(name, uuid);
            entityMap[uuid] = entity;
            if (children) {
                for (var i = 0, li = children.length; i < li; i++) {
                    var child = children[i];
                    var childEntity = setupEntity(child, null, pid);
                    entity.addChild(childEntity);
                }
            }
            if (!root) {
                entity.enabled = !config.disabled;
            }
        }
        return entity;
    }
    function setupComponent(config, root, includeSelf) {
        if (includeSelf === void 0) { includeSelf = false; }
        if (includeSelf) {
            instantiateComponents(root, config);
        }
        if (config && config.children) {
            for (var i = 0, li = root.children.length; i < li; i++) {
                var child = config.children[i];
                var entity = root.children[i];
                instantiateComponents(entity, child);
                setupComponent(child, entity);
            }
        }
    }
    function injectComponent(config, root, includeSelf, pid) {
        if (includeSelf === void 0) { includeSelf = false; }
        if (includeSelf) {
            injectComponents(root, config, pid);
        }
        if (config && config.children) {
            for (var i = 0, li = root.children.length; i < li; i++) {
                var child = config.children[i];
                var entity = root.children[i];
                injectComponents(entity, child, pid);
                injectComponent(child, entity, false, pid);
            }
        }
    }
    function instantiateComponents(entity, config) {
        var e_1, _a;
        if (config.components) {
            try {
                for (var _b = __values(config.components), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var component = _c.value;
                    instantiateComponent(entity, component);
                }
            }
            catch (e_1_1) { e_1 = { error: e_1_1 }; }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
                }
                finally { if (e_1) throw e_1.error; }
            }
        }
    }
    function injectComponents(entity, config, pid) {
        if (config.components) {
            var components = entity.components;
            for (var i = 0, li = config.components.length; i < li; i++) {
                var component = config.components[i];
                injectComponentProperties(components[i], component, pid);
            }
        }
    }
    function injectComponentProperties(component, config, pid) {
        var properties = config.properties;
        if (properties) {
            injectProperties(component, properties, pid);
        }
    }
    function instantiateComponent(entity, config) {
        var script = config.script;
        var def = engine.getDefByName(script);
        if (!def) {
            return;
        }
        var instance = new def();
        instance.enabled = !config.disabled;
        entity.addComponent(instance);
        return instance;
    }
    var skipKeys = ['_type_', '_constructor_'];
    function injectProperties(entity, propertiesConfig, pid) {
        if (!entity) {
            console.warn('entity is null.');
            return;
        }
        for (var key in propertiesConfig) {
            if (skipKeys.indexOf(key) >= 0) {
                continue;
            }
            var propertyOfConfig = propertiesConfig[key];
            var propertyOfInstance = entity[key];
            if (typeof propertyOfConfig === 'object') {
                if (propertyOfInstance instanceof ScillaEvent) {
                    if (!EngineConfig.editorMode) {
                        injectEvent(propertyOfInstance, propertyOfConfig, pid);
                    }
                }
                else if (propertyOfConfig._type_ === 'raw') {
                    entity[key] = propertyOfInstance = propertyOfConfig.data;
                }
                else {
                    if (Array.isArray(propertyOfConfig) && !propertyOfInstance) {
                        entity[key] = propertyOfInstance = [];
                    }
                    entity[key] = injectObject(propertyOfInstance, propertyOfConfig, pid);
                }
            }
            else {
                injectBaseType(entity, key, propertyOfConfig, pid);
            }
        }
    }
    function injectObject(propertyOfInstance, propertyOfConfig, pid) {
        if (propertyOfInstance === undefined) {
            if (propertyOfConfig._type_) {
                var def = engine.getDefByName(propertyOfConfig._type_);
                if (def) {
                    var constructorArgs = propertyOfConfig._constructor_;
                    if (constructorArgs && constructorArgs.length > 0) {
                        propertyOfInstance = def.constructor.apply(null, constructorArgs);
                    }
                    else {
                        propertyOfInstance = new def();
                    }
                }
            }
        }
        if (propertyOfInstance) {
            injectProperties(propertyOfInstance, propertyOfConfig, pid);
        }
        return propertyOfInstance;
    }
    function injectBaseType(entity, key, propertyOfConfig, pid) {
        var propertyValue;
        if (typeof propertyOfConfig === 'string') {
            propertyValue = getLink(propertyOfConfig, pid);
        }
        else {
            propertyValue = propertyOfConfig;
        }
        var keyAvatar = key;
        if (propertyValue instanceof Promise) {
            keyAvatar = 'async_' + keyAvatar;
        }
        if (typeof propertyValue === 'function') {
            Object.defineProperty(entity, keyAvatar, {
                get: function () {
                    return this["func_" + keyAvatar](entity, engine.dataCenter);
                },
                set: function (v) {
                    this["func_" + keyAvatar] = v;
                }
            });
        }
        entity[keyAvatar] = propertyValue;
    }
    function injectEvent(event, config, pid) {
        var e_2, _a;
        try {
            for (var config_1 = __values(config), config_1_1 = config_1.next(); !config_1_1.done; config_1_1 = config_1.next()) {
                var _b = config_1_1.value, entityName = _b.entity, componentIndex = _b.component, methodName = _b.method, param = _b.param;
                if (entityName && componentIndex >= 0 && methodName) {
                    var entity = getLink(entityName, pid);
                    var component = entity.components[componentIndex];
                    var method = component[methodName];
                    if (method) {
                        if (param == undefined) {
                            event.addListener(method, component, 0);
                        }
                        else {
                            event.addListener(method, component, 0, param);
                        }
                    }
                }
            }
        }
        catch (e_2_1) { e_2 = { error: e_2_1 }; }
        finally {
            try {
                if (config_1_1 && !config_1_1.done && (_a = config_1.return)) _a.call(config_1);
            }
            finally { if (e_2) throw e_2.error; }
        }
    }
    function getLink(str, pid) {
        var result;
        if (str.indexOf('res|') == 0) {
            var uuid = str.substr(4);
            result = _getResProxy(uuid);
        }
        else if (str.indexOf('entity|') == 0) {
            var uuid = transPrefabUUID(str.substr(7), pid);
            result = entityMap[uuid];
        }
        else if (str.indexOf('dynamic|') == 0) {
            var _a = __read(str.split('|'), 3), _ = _a[0], type_1 = _a[1], expression_1 = _a[2];
            result = function () {
                return engine.dataCenter.parse(type_1, expression_1);
            };
        }
        else if (str.indexOf('script|') == 0) {
            var script = str.substr(7);
            result = wrapperScript(script);
        }
        else {
            result = str;
        }
        return result;
    }
    function transPrefabUUID(uuid, pid) {
        return pid ? pid + '_' + uuid : uuid;
    }
    function wrapperScript(script) {
        try {
            return new Function('component', 'dataCenter', script);
        }
        catch (e) {
            console.warn('script is correct :', script);
        }
    }

    var all = {};
    function getGroup(name) {
        var group = all[name];
        if (!group) {
            throw new Error('group ' + name + ' not registered.');
        }
        return group;
    }
    function register(name, newFunc, initFunc) {
        all[name] = { name: name, newFunc: newFunc, initFunc: initFunc, pool: [] };
    }
    function get$1(name) {
        var params = [];
        for (var _i = 1; _i < arguments.length; _i++) {
            params[_i - 1] = arguments[_i];
        }
        var group = getGroup(name);
        var newFunc = group.newFunc, initFunc = group.initFunc, pool = group.pool;
        var instance;
        if (pool.length == 0) {
            instance = newFunc();
        }
        else {
            instance = pool.pop();
        }
        initFunc.apply(void 0, __spread([instance], params));
        return instance;
    }

    var name = 'Vector2D';
    register(name, function () {
        return new Vector2D();
    }, function (instance, x, y) {
        instance.setXY(x, y);
    });
    function createVector2D(x, y) {
        if (x === void 0) { x = 0; }
        if (y === void 0) { y = 0; }
        return get$1(name, x, y);
    }
    var Vector2D = (function (_super) {
        __extends(Vector2D, _super);
        function Vector2D(x, y, onChange) {
            if (x === void 0) { x = 0; }
            if (y === void 0) { y = 0; }
            var _this = _super.call(this) || this;
            _this.onChange = onChange;
            _this._x = 0;
            _this._y = 0;
            _this.setXY(x, y);
            return _this;
        }
        Object.defineProperty(Vector2D.prototype, "x", {
            get: function () {
                return this._x;
            },
            set: function (v) {
                if (this._x !== v) {
                    var old = this._x;
                    this._x = v;
                    this.onChange && this.onChange(v, 'x', old);
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Vector2D.prototype, "y", {
            get: function () {
                return this._y;
            },
            set: function (v) {
                if (this._y !== v) {
                    var old = this._y;
                    this._y = v;
                    this.onChange && this.onChange(v, 'y', old);
                }
            },
            enumerable: true,
            configurable: true
        });
        Vector2D.prototype.setXY = function (x, y) {
            if (x === void 0) { x = 0; }
            if (y === void 0) { y = 0; }
            this.x = x;
            this.y = y;
            return this;
        };
        Vector2D.prototype.copyFrom = function (v2) {
            this.x = v2.x;
            this.y = v2.y;
            return this;
        };
        Vector2D.prototype.clone = function () {
            return new Vector2D(this.x, this.y);
        };
        Vector2D.prototype.zero = function () {
            this.x = 0;
            this.y = 0;
            return this;
        };
        Object.defineProperty(Vector2D.prototype, "isZero", {
            get: function () {
                return this.x == 0 && this.y == 0;
            },
            enumerable: true,
            configurable: true
        });
        Vector2D.prototype.normalize = function () {
            var len = this.length;
            if (len == 0) {
                this.x = 1;
                return this;
            }
            this.x /= len;
            this.y /= len;
            return this;
        };
        Object.defineProperty(Vector2D.prototype, "isNormalized", {
            get: function () {
                return this.length == 1.0;
            },
            enumerable: true,
            configurable: true
        });
        Vector2D.prototype.truncate = function (max) {
            this.length = Math.min(max, this.length);
            return this;
        };
        Vector2D.prototype.reverse = function () {
            this.x = -this.x;
            this.y = -this.y;
            return this;
        };
        Vector2D.prototype.dotProd = function (v2) {
            return this.x * v2.x + this.y * v2.y;
        };
        Vector2D.prototype.crossProd = function (v2) {
            return this.x * v2.y - this.y * v2.x;
        };
        Vector2D.prototype.distSQ = function (v2) {
            var dx = v2.x - this.x;
            var dy = v2.y - this.y;
            return dx * dx + dy * dy;
        };
        Vector2D.prototype.distance = function (v2) {
            return Math.sqrt(this.distSQ(v2));
        };
        Vector2D.prototype.add = function (v2) {
            this.x += v2.x;
            this.y += v2.y;
            return this;
        };
        Vector2D.prototype.subtract = function (v2) {
            this.x -= v2.x;
            this.y -= v2.y;
            return this;
        };
        Vector2D.prototype.multiply = function (value) {
            this.x *= value;
            this.y *= value;
            return this;
        };
        Vector2D.prototype.divide = function (value) {
            this.x /= value;
            this.y /= value;
            return this;
        };
        Object.defineProperty(Vector2D.prototype, "angle", {
            get: function () {
                return this.radian * 180 / Math.PI;
            },
            set: function (value) {
                this.radian = value * Math.PI / 180;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Vector2D.prototype, "radian", {
            get: function () {
                return Math.atan2(this.y, this.x);
            },
            set: function (value) {
                var len = this.length;
                this.setXY(Math.cos(value) * len, Math.sin(value) * len);
            },
            enumerable: true,
            configurable: true
        });
        Vector2D.prototype.equals = function (v2) {
            return this.x == v2.x && this.y == v2.y;
        };
        Object.defineProperty(Vector2D.prototype, "length", {
            get: function () {
                return Math.sqrt(this.lengthSQ);
            },
            set: function (value) {
                var a = this.radian;
                this.setXY(Math.cos(a) * value, Math.sin(a) * value);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Vector2D.prototype, "lengthSQ", {
            get: function () {
                return this.x * this.x + this.y * this.y;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Vector2D.prototype, "slope", {
            get: function () {
                return this.y / this.x;
            },
            enumerable: true,
            configurable: true
        });
        Vector2D.prototype.toString = function () {
            return "[Vector2D (x:" + this.x + ", y:" + this.y + ")]";
        };
        Vector2D.prototype.toObj = function () {
            return { x: this.x, y: this.y };
        };
        Vector2D.prototype.toArray = function () {
            return [this.x, this.y];
        };
        Vector2D.corner = function (v1, v2) {
            return Math.acos(v1.dotProd(v2) / (v1.length * v2.length));
        };
        return Vector2D;
    }(HashObject));

    var STATUS;
    (function (STATUS) {
        STATUS[STATUS["IDLE"] = 0] = "IDLE";
        STATUS[STATUS["PENDING"] = 1] = "PENDING";
        STATUS[STATUS["DO_SET"] = 2] = "DO_SET";
        STATUS[STATUS["DO_TO"] = 3] = "DO_TO";
        STATUS[STATUS["DO_WAIT"] = 4] = "DO_WAIT";
        STATUS[STATUS["DO_CALL"] = 5] = "DO_CALL";
    })(STATUS || (STATUS = {}));
    function injectChildProps(target, key, value) {
        if (typeof value === 'object') {
            injectProp(target[key], value);
        }
        else {
            target[key] = value;
        }
    }
    function createTween(host, target, override, options, plugins) {
        if (override === void 0) { override = false; }
        if (plugins === void 0) { plugins = []; }
        if (override) {
            killTweens(target);
        }
        var tween = new Tween(host, target, options);
        addTween(target, tween);
        return tween;
    }
    function killTweens(target) {
        var e_1, _a;
        var tweens = target['tweens'];
        if (tweens) {
            try {
                for (var tweens_1 = __values(tweens), tweens_1_1 = tweens_1.next(); !tweens_1_1.done; tweens_1_1 = tweens_1.next()) {
                    var tween = tweens_1_1.value;
                    tween.stop();
                }
            }
            catch (e_1_1) { e_1 = { error: e_1_1 }; }
            finally {
                try {
                    if (tweens_1_1 && !tweens_1_1.done && (_a = tweens_1.return)) _a.call(tweens_1);
                }
                finally { if (e_1) throw e_1.error; }
            }
            tweens.splice(0);
        }
    }
    function addTween(target, tween) {
        var tweens = target['tweens'];
        if (!tweens) {
            tweens = target['tweens'] = [];
        }
        tweens.push(tween);
    }
    var Tween = (function (_super) {
        __extends(Tween, _super);
        function Tween(host, target, options, plugins) {
            if (plugins === void 0) { plugins = []; }
            var _this = _super.call(this) || this;
            _this._queue = [];
            _this.loopCounting = 0;
            _this.status = STATUS.IDLE;
            _this.onUpdate = function (t) {
                _this.t = t;
                switch (_this.status) {
                    case STATUS.DO_TO:
                        var _a = _this, target = _a.target, startTime = _a.startTime, fromProps = _a.fromProps, toProps = _a.toProps, duration = _a.duration, ease = _a.ease;
                        var passTime = t - startTime;
                        var timeRatio = Math.min(1, passTime / duration);
                        var ratio = timeRatio;
                        if (ease) {
                            ratio = ease(ratio);
                        }
                        for (var key in fromProps) {
                            var toValue = toProps[key];
                            var fromValue = fromProps[key];
                            var currentValue = void 0;
                            if (timeRatio < 1) {
                                currentValue = _this.resolveLerp(fromValue, toValue, ratio);
                            }
                            else {
                                currentValue = toValue;
                            }
                            if (typeof currentValue === 'object') {
                                injectProp(target[key], currentValue);
                            }
                            else {
                                target[key] = currentValue;
                            }
                        }
                        if (timeRatio >= 1) {
                            _this._doNextAction();
                        }
                        break;
                    case STATUS.DO_WAIT:
                        var _b = _this, startTime = _b.startTime, duration = _b.duration;
                        var passTime = t - startTime;
                        if (passTime > duration) {
                            _this._doNextAction();
                        }
                        break;
                }
            };
            _this._doPlay = function (resetLoopCounting) {
                addTween(_this.target, _this);
                _this._start(resetLoopCounting);
            };
            _this._readyStart = function (t) {
                _this.t = t;
                _this._doStart();
            };
            _this._doNextAction = function () {
                if (_this.step < _this._queue.length) {
                    var action = _this._queue[_this.step++];
                    switch (action.action) {
                        case 'set':
                            _this._set(action.props);
                            break;
                        case 'to':
                            if (action.duration > 0) {
                                _this._to(action.props, action.duration, action.ease);
                            }
                            else {
                                _this._set(action.props);
                            }
                            break;
                        case 'wait':
                            _this._wait(action.duration);
                            break;
                        case 'call':
                            _this._call(action.func, action.thisObj, action.params);
                            break;
                    }
                }
                else {
                    _this._onEnd();
                }
            };
            _this.host = host;
            _this.target = target;
            _this.loop = options ? options.loop : 0;
            _this.autoPlay = options ? (options.hasOwnProperty('autoPlay') ? options.autoPlay : true) : true;
            _this.fields = options ? options.fields : null;
            _this.onLoopComplete = options ? options.onLoopComplete : null;
            _this.onComplete = options ? options.onComplete : null;
            _this.plugins = plugins;
            if (options && options.initFields && options.initFields.length > 0) {
                _this.initProps = _this.getInitProps(options.initFields);
            }
            return _this;
        }
        Object.defineProperty(Tween.prototype, "queue", {
            get: function () {
                return this._queue;
            },
            enumerable: true,
            configurable: true
        });
        Tween.prototype.resolveLerp = function (fromValue, toValue, ratio) {
            var e_2, _a;
            var currentValue;
            if (this.plugins.length > 0) {
                try {
                    for (var _b = __values(this.plugins), _c = _b.next(); !_c.done; _c = _b.next()) {
                        var plugin = _c.value;
                        currentValue = plugin.resolveLerp(fromValue, toValue, ratio, true);
                    }
                }
                catch (e_2_1) { e_2 = { error: e_2_1 }; }
                finally {
                    try {
                        if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
                    }
                    finally { if (e_2) throw e_2.error; }
                }
            }
            else {
                if (typeof toValue == 'object') {
                    var fields = this.fields;
                    currentValue = lerpObj(fromValue, toValue, ratio, fields || Object.keys(toValue), true);
                }
                else {
                    currentValue = lerp(fromValue, toValue, ratio, true);
                }
            }
            return currentValue;
        };
        Tween.prototype.getInitProps = function (fields) {
            var e_3, _a;
            var props = {};
            try {
                for (var fields_1 = __values(fields), fields_1_1 = fields_1.next(); !fields_1_1.done; fields_1_1 = fields_1.next()) {
                    var field = fields_1_1.value;
                    if (field in this.target) {
                        var value = this.target[field];
                        if (typeof value === 'object') {
                            if (value.clone) {
                                value = value.clone();
                            }
                            else {
                                injectProp(props[field] = {}, this.target[field]);
                            }
                        }
                        props[field] = value;
                    }
                }
            }
            catch (e_3_1) { e_3 = { error: e_3_1 }; }
            finally {
                try {
                    if (fields_1_1 && !fields_1_1.done && (_a = fields_1.return)) _a.call(fields_1);
                }
                finally { if (e_3) throw e_3.error; }
            }
            return props;
        };
        Tween.prototype.set = function (props, immediately) {
            if (immediately === void 0) { immediately = false; }
            this._queue.push({ action: 'set', props: props });
            if (this.autoPlay) {
                this._start();
            }
            if (immediately) {
                this._set(props, immediately);
            }
            return this;
        };
        Tween.prototype.to = function (props, duration, ease) {
            this._queue.push({ action: 'to', props: props, duration: duration, ease: ease });
            if (this.autoPlay) {
                this._start();
            }
            return this;
        };
        Tween.prototype.wait = function (duration) {
            this._queue.push({ action: 'wait', duration: duration });
            if (this.autoPlay) {
                this._start();
            }
            return this;
        };
        Tween.prototype.call = function (func, thisObj, params) {
            this._queue.push({ action: 'call', func: func, thisObj: thisObj, params: params });
            if (this.autoPlay) {
                this._start();
            }
            return this;
        };
        Tween.prototype.play = function (override, delay, resetLoopCounting) {
            if (override === void 0) { override = false; }
            if (delay === void 0) { delay = 0; }
            if (resetLoopCounting === void 0) { resetLoopCounting = true; }
            if (override) {
                killTweens(this.target);
            }
            if (delay > 0) {
                setTimeout(this._doPlay, delay, resetLoopCounting);
            }
            else {
                this._doPlay(resetLoopCounting);
            }
        };
        Tween.prototype.stop = function () {
            this.status = STATUS.IDLE;
            this.host.cancelOnNextTick(this.onUpdate);
        };
        Tween.prototype.getPromise = function () {
            var _this = this;
            return new Promise(function (resolve) {
                _this.promise = { resolve: resolve };
            });
        };
        Tween.prototype._set = function (props, immediately) {
            if (immediately === void 0) { immediately = false; }
            injectProp(this.target, props, injectChildProps);
            if (!immediately) {
                this.status = STATUS.DO_SET;
                this._doNextAction();
            }
        };
        Tween.prototype._to = function (props, duration, ease) {
            this.status = STATUS.DO_TO;
            this.startTime = this.t;
            this.fromProps = {};
            for (var key in props) {
                var value = this.target[key];
                if (typeof value === 'object') {
                    if (value.clone) {
                        value = value.clone();
                    }
                    else {
                        injectProp(props[key] = {}, this.target[key]);
                    }
                }
                this.fromProps[key] = value;
            }
            this.toProps = {};
            injectProp(this.toProps, props);
            this.ease = ease;
            this.duration = duration;
        };
        Tween.prototype._wait = function (duration) {
            this.status = STATUS.DO_WAIT;
            this.startTime = this.t;
            this.duration = duration;
        };
        Tween.prototype._call = function (func, thisObj, params) {
            this.status = STATUS.DO_CALL;
            func.apply(thisObj || this.host, params);
            this._doNextAction();
        };
        Tween.prototype._start = function (resetLoopCounting) {
            if (resetLoopCounting === void 0) { resetLoopCounting = true; }
            this.status = STATUS.PENDING;
            if (resetLoopCounting) {
                this.loopCounting = 0;
            }
            this.host.callOnNextTick(this._readyStart);
            this.host.callOnNextTick(this.onUpdate, false);
        };
        Tween.prototype._doStart = function () {
            if (this.status == STATUS.IDLE) {
                return;
            }
            this.step = 0;
            this.loopCounting++;
            if (this.loopCounting > 1 && this.initProps) {
                injectProp(this.target, this.initProps, injectChildProps);
            }
            setTimeout(this._doNextAction);
        };
        Tween.prototype._onEnd = function () {
            this.onLoopComplete && this.onLoopComplete();
            if (this.loop < 0) {
                this._doStart();
            }
            else if (this.loopCounting < this.loop) {
                this._doStart();
            }
            else {
                this.status = STATUS.IDLE;
                this.onComplete && this.onComplete();
                this.promise && this.promise.resolve();
                this.promise = null;
            }
        };
        return Tween;
    }(HashObject));

    var PI = Math.PI;
    var TwoPI = PI * 2;
    var DEG_TO_RAD = PI / 180;
    var matrixPool = [];
    var Matrix = (function () {
        function Matrix(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;
        }
        Matrix.release = function (matrix) {
            if (!matrix) {
                return;
            }
            matrixPool.push(matrix);
        };
        Matrix.create = function () {
            var matrix = matrixPool.pop();
            if (!matrix) {
                matrix = new Matrix();
            }
            return matrix;
        };
        Matrix.prototype.clone = function () {
            var m = Matrix.create();
            m.setTo(this.a, this.b, this.c, this.d, this.tx, this.ty);
            return m;
        };
        Matrix.prototype.concat = function (other) {
            var a = this.a * other.a;
            var b = 0.0;
            var c = 0.0;
            var d = this.d * other.d;
            var tx = this.tx * other.a + other.tx;
            var ty = this.ty * other.d + other.ty;
            if (this.b !== 0.0 || this.c !== 0.0 || other.b !== 0.0 || other.c !== 0.0) {
                a += this.b * other.c;
                d += this.c * other.b;
                b += this.a * other.b + this.b * other.d;
                c += this.c * other.a + this.d * other.c;
                tx += this.ty * other.c;
                ty += this.tx * other.b;
            }
            this.a = a;
            this.b = b;
            this.c = c;
            this.d = d;
            this.tx = tx;
            this.ty = ty;
        };
        Matrix.prototype.copyFrom = function (other) {
            this.a = other.a;
            this.b = other.b;
            this.c = other.c;
            this.d = other.d;
            this.tx = other.tx;
            this.ty = other.ty;
            return this;
        };
        Matrix.prototype.identity = function () {
            this.a = this.d = 1;
            this.b = this.c = this.tx = this.ty = 0;
        };
        Matrix.prototype.invert = function () {
            this.$invertInto(this);
        };
        Matrix.prototype.$invertInto = function (target) {
            var a = this.a;
            var b = this.b;
            var c = this.c;
            var d = this.d;
            var tx = this.tx;
            var ty = this.ty;
            if (b == 0 && c == 0) {
                target.b = target.c = 0;
                if (a == 0 || d == 0) {
                    target.a = target.d = target.tx = target.ty = 0;
                }
                else {
                    a = target.a = 1 / a;
                    d = target.d = 1 / d;
                    target.tx = -a * tx;
                    target.ty = -d * ty;
                }
                return;
            }
            var determinant = a * d - b * c;
            if (determinant == 0) {
                target.identity();
                return;
            }
            determinant = 1 / determinant;
            var k = target.a = d * determinant;
            b = target.b = -b * determinant;
            c = target.c = -c * determinant;
            d = target.d = a * determinant;
            target.tx = -(k * tx + c * ty);
            target.ty = -(b * tx + d * ty);
        };
        Matrix.prototype.rotate = function (radian) {
            radian = +radian;
            if (radian !== 0) {
                var u = Math.cos(radian);
                var v = Math.sin(radian);
                var _a = this, a = _a.a, b = _a.b, c = _a.c, d = _a.d, tx = _a.tx, ty = _a.ty;
                this.a = a * u - b * v;
                this.b = a * v + b * u;
                this.c = c * u - d * v;
                this.d = c * v + d * u;
                this.tx = tx * u - ty * v;
                this.ty = tx * v + ty * u;
            }
        };
        Object.defineProperty(Matrix.prototype, "rotation", {
            get: function () {
                return Math.atan2(this.b, this.a);
            },
            enumerable: true,
            configurable: true
        });
        Matrix.prototype.scale = function (sx, sy) {
            if (sx !== 1) {
                this.a *= sx;
                this.c *= sx;
                this.tx *= sx;
            }
            if (sy !== 1) {
                this.b *= sy;
                this.d *= sy;
                this.ty *= sy;
            }
        };
        Matrix.prototype.setTo = function (a, b, c, d, tx, ty) {
            this.a = a;
            this.b = b;
            this.c = c;
            this.d = d;
            this.tx = tx;
            this.ty = ty;
            return this;
        };
        Matrix.prototype.transformPoint = function (pointX, pointY, resultPoint) {
            var _a = this, a = _a.a, b = _a.b, c = _a.c, d = _a.d, tx = _a.tx, ty = _a.ty;
            var x = a * pointX + c * pointY + tx;
            var y = b * pointX + d * pointY + ty;
            if (resultPoint) {
                resultPoint.x = x;
                resultPoint.y = y;
                return resultPoint;
            }
            return { x: x, y: y };
        };
        Matrix.prototype.deltaTransformPoint = function (pointX, pointY, resultPoint) {
            var _a = this, a = _a.a, b = _a.b, c = _a.c, d = _a.d;
            var x = a * pointX + c * pointY;
            var y = b * pointX + d * pointY;
            if (resultPoint) {
                resultPoint.x = x;
                resultPoint.y = y;
                return resultPoint;
            }
            return { x: x, y: y };
        };
        Matrix.prototype.translate = function (dx, dy) {
            this.tx += dx;
            this.ty += dy;
        };
        Matrix.prototype.equals = function (other) {
            return this.a == other.a && this.b == other.b &&
                this.c == other.c && this.d == other.d &&
                this.tx == other.tx && this.ty == other.ty;
        };
        Matrix.prototype.prepend = function (a, b, c, d, tx, ty) {
            var tx1 = this.tx;
            if (a != 1 || b != 0 || c != 0 || d != 1) {
                var a1 = this.a;
                var c1 = this.c;
                this.a = a1 * a + this.b * c;
                this.b = a1 * b + this.b * d;
                this.c = c1 * a + this.d * c;
                this.d = c1 * b + this.d * d;
            }
            this.tx = tx1 * a + this.ty * c + tx;
            this.ty = tx1 * b + this.ty * d + ty;
            return this;
        };
        Matrix.prototype.append = function (a, b, c, d, tx, ty) {
            var a1 = this.a;
            var b1 = this.b;
            var c1 = this.c;
            var d1 = this.d;
            if (a != 1 || b != 0 || c != 0 || d != 1) {
                this.a = a * a1 + b * c1;
                this.b = a * b1 + b * d1;
                this.c = c * a1 + d * c1;
                this.d = c * b1 + d * d1;
            }
            this.tx = tx * a1 + ty * c1 + this.tx;
            this.ty = tx * b1 + ty * d1 + this.ty;
            return this;
        };
        Matrix.prototype.toString = function () {
            return "(a=" + this.a + ", b=" + this.b + ", c=" + this.c + ", d=" + this.d + ", tx=" + this.tx + ", ty=" + this.ty + ")";
        };
        Matrix.prototype.createBox = function (scaleX, scaleY, rotation, tx, ty) {
            if (rotation === void 0) { rotation = 0; }
            if (tx === void 0) { tx = 0; }
            if (ty === void 0) { ty = 0; }
            var self = this;
            if (rotation !== 0) {
                rotation = rotation / DEG_TO_RAD;
                var u = Math.cos(rotation);
                var v = Math.sin(rotation);
                self.a = u * scaleX;
                self.b = v * scaleY;
                self.c = -v * scaleX;
                self.d = u * scaleY;
            }
            else {
                self.a = scaleX;
                self.b = 0;
                self.c = 0;
                self.d = scaleY;
            }
            self.tx = tx;
            self.ty = ty;
        };
        Matrix.prototype.createGradientBox = function (width, height, rotation, tx, ty) {
            if (rotation === void 0) { rotation = 0; }
            if (tx === void 0) { tx = 0; }
            if (ty === void 0) { ty = 0; }
            this.createBox(width / 1638.4, height / 1638.4, rotation, tx + width / 2, ty + height / 2);
        };
        Matrix.prototype.$transformBounds = function (bounds) {
            var a = this.a;
            var b = this.b;
            var c = this.c;
            var d = this.d;
            var tx = this.tx;
            var ty = this.ty;
            var x = bounds.x;
            var y = bounds.y;
            var xMax = x + bounds.width;
            var yMax = y + bounds.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;
            if (x0 > x1) {
                tmp = x0;
                x0 = x1;
                x1 = tmp;
            }
            if (x2 > x3) {
                tmp = x2;
                x2 = x3;
                x3 = tmp;
            }
            bounds.x = Math.floor(x0 < x2 ? x0 : x2);
            bounds.width = Math.ceil((x1 > x3 ? x1 : x3) - bounds.x);
            if (y0 > y1) {
                tmp = y0;
                y0 = y1;
                y1 = tmp;
            }
            if (y2 > y3) {
                tmp = y2;
                y2 = y3;
                y3 = tmp;
            }
            bounds.y = Math.floor(y0 < y2 ? y0 : y2);
            bounds.height = Math.ceil((y1 > y3 ? y1 : y3) - bounds.y);
        };
        Matrix.prototype.getDeterminant = function () {
            return this.a * this.d - this.b * this.c;
        };
        Matrix.prototype.$getScaleX = function () {
            var m = this;
            if (m.b == 0) {
                return m.a;
            }
            var result = Math.sqrt(m.a * m.a + m.b * m.b);
            return this.getDeterminant() < 0 ? -result : result;
        };
        Matrix.prototype.$getScaleY = function () {
            var m = this;
            if (m.c == 0) {
                return m.d;
            }
            var result = Math.sqrt(m.c * m.c + m.d * m.d);
            return this.getDeterminant() < 0 ? -result : result;
        };
        Matrix.prototype.$getSkewX = function () {
            if (this.d < 0) {
                return Math.atan2(this.d, this.c) + (PI / 2);
            }
            else {
                return Math.atan2(this.d, this.c) - (PI / 2);
            }
        };
        Matrix.prototype.$getSkewY = function () {
            if (this.a < 0) {
                return Math.atan2(this.b, this.a) - PI;
            }
            else {
                return Math.atan2(this.b, this.a);
            }
        };
        Matrix.prototype.$updateScaleAndRotation = function (scaleX, scaleY, skewX, skewY) {
            if ((skewX == 0 || skewX == TwoPI) && (skewY == 0 || skewY == TwoPI)) {
                this.a = scaleX;
                this.b = this.c = 0;
                this.d = scaleY;
                return;
            }
            skewX = skewX / DEG_TO_RAD;
            skewY = skewY / DEG_TO_RAD;
            var u = Math.cos(skewX);
            var v = Math.sin(skewX);
            if (skewX == skewY) {
                this.a = u * scaleX;
                this.b = v * scaleX;
            }
            else {
                this.a = Math.cos(skewY) * scaleX;
                this.b = Math.sin(skewY) * scaleX;
            }
            this.c = -v * scaleY;
            this.d = u * scaleY;
        };
        Matrix.prototype.$preMultiplyInto = function (other, target) {
            var a = other.a * this.a;
            var b = 0.0;
            var c = 0.0;
            var d = other.d * this.d;
            var tx = other.tx * this.a + this.tx;
            var ty = other.ty * this.d + this.ty;
            if (other.b !== 0.0 || other.c !== 0.0 || this.b !== 0.0 || this.c !== 0.0) {
                a += other.b * this.c;
                d += other.c * this.b;
                b += other.a * this.b + other.b * this.d;
                c += other.c * this.a + other.d * this.c;
                tx += other.ty * this.c;
                ty += other.tx * this.b;
            }
            target.a = a;
            target.b = b;
            target.c = c;
            target.d = d;
            target.tx = tx;
            target.ty = ty;
        };
        return Matrix;
    }());

    var Size = (function (_super) {
        __extends(Size, _super);
        function Size(width, height, onChange) {
            if (width === void 0) { width = NaN; }
            if (height === void 0) { height = NaN; }
            var _this = _super.call(this) || this;
            _this.onChange = onChange;
            _this.width = width;
            _this.height = height;
            return _this;
        }
        Size.prototype.setNaN = function () {
            this.width = NaN;
            this.height = NaN;
        };
        Object.defineProperty(Size.prototype, "isEmpty", {
            get: function () {
                return this.width === 0 && this.height === 0;
            },
            enumerable: true,
            configurable: true
        });
        Size.prototype.set = function (width, height) {
            if (width !== undefined) {
                this.width = width;
            }
            if (height !== undefined) {
                this.height = height;
            }
        };
        Size.prototype.clone = function () {
            return new Size(this.width, this.height);
        };
        Size.prototype.copyFrom = function (target) {
            this.width = target.width;
            this.height = target.height;
        };
        Size.prototype.onModify = function (value, key, oldValue) {
            this.onChange && this.onChange(value, key, oldValue);
        };
        __decorate([
            dirtyFieldTrigger
        ], Size.prototype, "width", void 0);
        __decorate([
            dirtyFieldTrigger
        ], Size.prototype, "height", void 0);
        return Size;
    }(HashObject));

    var FontStyle;
    (function (FontStyle) {
        FontStyle["NORMAL"] = "normal";
        FontStyle["ITALIC"] = "italic";
        FontStyle["OBLIQUE"] = "oblique";
    })(FontStyle || (FontStyle = {}));
    var FontVariant;
    (function (FontVariant) {
        FontVariant["NORMAL"] = "normal";
        FontVariant["SMALL_CAPS"] = "small-caps";
    })(FontVariant || (FontVariant = {}));
    var FontWeight;
    (function (FontWeight) {
        FontWeight["NORMAL"] = "normal";
        FontWeight["BOLD"] = "bold";
        FontWeight["BOLDER"] = "bolder";
        FontWeight["LIGHTER"] = "lighter";
    })(FontWeight || (FontWeight = {}));
    var TextStyle = (function () {
        function TextStyle() {
            this.fontStyle = FontStyle.NORMAL;
            this.fontVariant = FontVariant.NORMAL;
            this.fontWeight = FontWeight.NORMAL;
            this.fontSize = 25;
            this.fontFamily = 'Arial';
        }
        TextStyle.prototype.onModify = function (value, key, oldValue) {
            this.onChange && this.onChange(value, key, oldValue, 'textStyle');
        };
        __decorate([
            dirtyFieldTrigger
        ], TextStyle.prototype, "fontStyle", void 0);
        __decorate([
            dirtyFieldTrigger
        ], TextStyle.prototype, "fontVariant", void 0);
        __decorate([
            dirtyFieldTrigger
        ], TextStyle.prototype, "fontWeight", void 0);
        __decorate([
            dirtyFieldTrigger
        ], TextStyle.prototype, "fontSize", void 0);
        __decorate([
            dirtyFieldTrigger
        ], TextStyle.prototype, "fontFamily", void 0);
        return TextStyle;
    }());

    var Scene = (function () {
        function Scene(engine) {
            this._resourceGroups = {
                preload: [],
                delay: [],
            };
            this._engine = engine;
        }
        Object.defineProperty(Scene.prototype, "root", {
            get: function () {
                return this._root;
            },
            enumerable: true,
            configurable: true
        });
        Scene.prototype.initByConfig = function (config) {
            this._config = config;
            this._name = config.name;
            var resourceGroups = config['resource-groups'];
            for (var key in resourceGroups) {
                this._resourceGroups[key] = resourceGroups[key];
            }
        };
        Scene.prototype.setup = function (root) {
            this._root = root;
            var assetsManager = this._engine.assetsManager;
            setupScene(this._config, root, assetsManager.getRes.bind(assetsManager));
        };
        Scene.prototype.loadResGroup = function (name, replaceConfig, progress) {
            return __awaiter(this, void 0, void 0, function () {
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0: return [4, this._engine.assetsManager.loadResItems(this._resourceGroups[name], replaceConfig, progress)];
                        case 1:
                            _a.sent();
                            return [2];
                    }
                });
            });
        };
        return Scene;
    }());

    var ScillaLauncher = (function () {
        function ScillaLauncher() {
        }
        ScillaLauncher.prototype.launch = function (containerElement, options, onProgress) {
            if (options === void 0) { options = {}; }
            return __awaiter(this, void 0, void 0, function () {
                var resPath, manifest, engineConfig, customConfig, dataCenterConfig, canvas, entryScene;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            resPath = options.resPath || '';
                            return [4, engine.assetsManager.loadJson(resPath + 'manifest.json')];
                        case 1:
                            manifest = _a.sent();
                            engine.assetsManager.setResPath(resPath + 'assets/');
                            engineConfig = {};
                            injectProp(engineConfig, manifest.engineConfig);
                            injectProp(engineConfig, options.engineConfig);
                            customConfig = {};
                            injectProp(customConfig, manifest.customConfig);
                            injectProp(customConfig, options.customConfig);
                            dataCenterConfig = {};
                            injectProp(dataCenterConfig, manifest.dataCenterConfig);
                            injectProp(dataCenterConfig, options.dataCenterConfig);
                            canvas = document.createElement('canvas');
                            containerElement.appendChild(canvas);
                            engineConfig.canvas = canvas;
                            engine.setup(engineConfig, customConfig, dataCenterConfig);
                            entryScene = options.scene || customConfig.scene.entryScene;
                            return [4, this.launchScene(entryScene, options.resReplaceConfigs, onProgress)];
                        case 2:
                            _a.sent();
                            return [2];
                    }
                });
            });
        };
        ScillaLauncher.prototype.launchScene = function (sceneNameOrPath, resReplaceConfigs, progress) {
            return __awaiter(this, void 0, void 0, function () {
                var sceneConfig, sceneFile, scene, replaceConfig;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            sceneConfig = engine.customConfig.scene;
                            sceneFile = sceneConfig.scenes[sceneNameOrPath];
                            if (!sceneFile) {
                                sceneFile = sceneNameOrPath;
                            }
                            return [4, this.loadScene(sceneFile, 'scene_' + sceneFile)];
                        case 1:
                            scene = _a.sent();
                            this.resUUIDs = engine.assetsManager.getAllResUuids();
                            replaceConfig = resReplaceConfigs && resReplaceConfigs[sceneFile];
                            return [4, scene.loadResGroup('preload', replaceConfig, progress)];
                        case 2:
                            _a.sent();
                            if (this.currentScene) {
                                this.unmountScene(this.currentScene);
                            }
                            this.currentScene = scene;
                            this.mountScene(scene);
                            scene.loadResGroup('delay', null, progress);
                            return [2];
                    }
                });
            });
        };
        ScillaLauncher.prototype.mountScene = function (scene) {
            engine.pause();
            scene.setup(engine.root);
            engine.start();
        };
        ScillaLauncher.prototype.unmountScene = function (scene) {
            engine.pause();
            cleanEntity(scene.root);
            engine.assetsManager.destroyRes(this.resUUIDs);
        };
        ScillaLauncher.prototype.loadScene = function (url, uuid, cache, config) {
            if (cache === void 0) { cache = false; }
            return __awaiter(this, void 0, void 0, function () {
                var sceneConfig, scene;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0: return [4, engine.assetsManager.loadJson5(url)];
                        case 1:
                            sceneConfig = _a.sent();
                            scene = new Scene(engine);
                            scene.initByConfig(sceneConfig);
                            return [2, scene];
                    }
                });
            });
        };
        return ScillaLauncher;
    }());

    var ScillaComponent = (function (_super) {
        __extends(ScillaComponent, _super);
        function ScillaComponent() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        Object.defineProperty(ScillaComponent.prototype, "transform", {
            get: function () {
                return this.entity.components[0];
            },
            enumerable: true,
            configurable: true
        });
        ScillaComponent.prototype.getComponentsByName = function (name) {
            return this.entity.getComponentsByName(name);
        };
        ScillaComponent.prototype.getComponents = function (clazz) {
            return this.entity.getComponents(clazz);
        };
        ScillaComponent.prototype.getComponentByName = function (name) {
            return this.entity.getComponentByName(name);
        };
        ScillaComponent.prototype.getComponent = function (clazz) {
            return this.entity.getComponent(clazz);
        };
        return ScillaComponent;
    }(Component));

    var dirtyFieldTrigger$1 = dirtyFieldTrigger;
    var Renderer = (function (_super) {
        __extends(Renderer, _super);
        function Renderer() {
            var _this = _super !== null && _super.apply(this, arguments) || this;
            _this.onVector2DModify = function () {
                _this.makeDirty();
            };
            _this.dirty = true;
            _this._useCacheMode = false;
            _this.alpha = 1;
            _this.anchor = new Vector2D(0.5, 0.5);
            _this.bounds = new Bounds();
            _this.cacheCanvas = null;
            _this._anchorOffset = new Vector2D();
            _this._margin = 0;
            return _this;
        }
        Object.defineProperty(Renderer.prototype, "useCacheMode", {
            get: function () {
                return this.getUseCacheMode();
            },
            set: function (value) {
                this._useCacheMode = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Renderer.prototype, "context", {
            get: function () {
                if (!this._context) {
                    this._context = engine.renderContext.context;
                }
                return this._context;
            },
            enumerable: true,
            configurable: true
        });
        Renderer.prototype.onCreate = function () {
            _super.prototype.onCreate.call(this);
            this._debugDrawColor = "hsl(" + makeRandomInt(360) + ", " + makeRandomInt(100) + "%, 60%)";
        };
        Renderer.prototype.getUseCacheMode = function () {
            return this._useCacheMode;
        };
        Object.defineProperty(Renderer.prototype, "currentCanvasContext", {
            get: function () {
                return this.cacheCanvasContext || this.context;
            },
            enumerable: true,
            configurable: true
        });
        Renderer.prototype.makeDirty = function () {
            this.dirty = true;
        };
        Renderer.prototype.onModify = function (value, key, oldValue) {
            _super.prototype.onModify.call(this, value, key, oldValue);
            this.makeDirty();
            switch (key) {
                case 'anchor':
                    value.onChange = this.onVector2DModify;
                    break;
            }
        };
        Renderer.prototype.onAwake = function () {
            _super.prototype.onAwake.call(this);
            if (!this.transform) {
                console.warn('renderer need a transform component');
            }
        };
        Renderer.prototype.onUpdate = function (t) {
            if (this.dirty) {
                if (this.useCacheMode) {
                    this.readyCacheCanvas();
                }
                this.measureBounds();
                if (this.useCacheMode) {
                    this.updateCacheCanvas();
                }
            }
            this.transformToLocal();
            this.render();
            if (EngineConfig.drawRenderRect) {
                var _a = this, context = _a.context, _debugDrawColor = _a._debugDrawColor, _b = _a.bounds, width = _b.width, height = _b.height, _c = _a._anchorOffset, x = _c.x, y = _c.y, _d = _a.transform.pivot, px = _d.x, py = _d.y;
                context.globalAlpha = 0.9;
                context.strokeStyle = _debugDrawColor;
                context.fillStyle = _debugDrawColor;
                context.beginPath();
                context.rect(0, 0, width, height);
                context.stroke();
                context.beginPath();
                context.arc(width * px, height * py, 3, 0, 2 * Math.PI);
                context.fill();
            }
        };
        Renderer.prototype.onEditorUpdate = function (t) {
            this.onUpdate(t);
        };
        Renderer.prototype.readyCacheCanvas = function () {
            var canvas = this.cacheCanvas;
            if (!canvas) {
                canvas = this.cacheCanvas = createCanvas();
                this.cacheCanvasContext = canvas.getContext('2d');
            }
        };
        Renderer.prototype.updateCacheCanvas = function () {
            var canvas = this.cacheCanvas;
            var _a = this.bounds, width = _a.width, height = _a.height;
            canvas.width = width + this._margin * 2;
            canvas.height = height + this._margin * 2;
        };
        Renderer.prototype.render = function () {
            this.beforeDraw();
            this.drawClip();
            if (this.dirty) {
                if (this.useCacheMode) {
                    this.draw();
                }
                this.dirty = false;
            }
            if (this.useCacheMode) {
                this.drawCache();
            }
            else {
                this.draw();
            }
        };
        Renderer.prototype.beforeDraw = function () {
            this.applyAlpha();
        };
        Renderer.prototype.transformToLocal = function () {
            var _a = this, transform = _a.transform, _b = _a._anchorOffset, ax = _b.x, ay = _b.y;
            if (transform && transform.enabled) {
                var _c = transform.getMatrix(true, false, true), a = _c.a, b = _c.b, c = _c.c, d = _c.d, tx = _c.tx, ty = _c.ty;
                var offX = ax * a + ay * c;
                var offY = ax * b + ay * d;
                this.context.setTransform(a, b, c, d, tx - offX, ty - offY);
            }
            else {
                this.context.setTransform(1, 0, 0, 1, -ax, -ay);
            }
        };
        Renderer.prototype.applyAlpha = function () {
            this.context.globalAlpha = this.alpha * this.transform.renderAlpha;
        };
        Renderer.prototype.drawCache = function () {
            if (this.cacheCanvas.width > 0 && this.cacheCanvas.height > 0) {
                this.context.drawImage(this.cacheCanvas, -this._margin, -this._margin);
            }
        };
        Renderer.prototype.drawClip = function () {
        };
        Renderer.prototype.draw = function () {
        };
        Renderer.prototype.measureBounds = function () {
            var _a = this, _b = _a.anchor, x = _b.x, y = _b.y, bounds = _a.bounds, _c = _a.bounds, width = _c.width, height = _c.height;
            var anchorOffsetX = this._anchorOffset.x = width * x;
            var anchorOffsetY = this._anchorOffset.y = height * y;
            bounds.x = -anchorOffsetX;
            bounds.y = -anchorOffsetY;
        };
        Renderer.prototype.hitTest = function (x, y) {
            return this.bounds.contains(x, y);
        };
        __decorate([
            dirtyFieldTrigger$1
        ], Renderer.prototype, "anchor", void 0);
        return Renderer;
    }(ScillaComponent));

    var dirtyFieldDetector$1 = dirtyFieldDetector, dirtyFieldTrigger$2 = dirtyFieldTrigger;
    var MATRIX_ORDER;
    (function (MATRIX_ORDER) {
        MATRIX_ORDER[MATRIX_ORDER["SCALE_ROTATE"] = 0] = "SCALE_ROTATE";
        MATRIX_ORDER[MATRIX_ORDER["ROTATE_SCALE"] = 1] = "ROTATE_SCALE";
    })(MATRIX_ORDER || (MATRIX_ORDER = {}));
    var Transform = (function (_super) {
        __extends(Transform, _super);
        function Transform() {
            var _this = _super !== null && _super.apply(this, arguments) || this;
            _this.localPos = {};
            _this.onVector2DModify = function (value, key, oldValue) {
                _this.makeDirty(value, key, oldValue);
            };
            _this.position = new Vector2D(0, 0);
            _this._globalPosition = new Vector2D(0, 0);
            _this.alpha = 1;
            _this.affectChildren = true;
            _this._width = NaN;
            _this._height = NaN;
            _this.scale = new Vector2D(1, 1);
            _this.pivot = new Vector2D(0.5, 0.5);
            _this.rotation = 0;
            _this.order = MATRIX_ORDER.SCALE_ROTATE;
            _this._localMatrix = Matrix.create();
            _this._globalMatrix = Matrix.create();
            _this._globalInvertMatrix = Matrix.create();
            _this._globalPivotMatrix = Matrix.create();
            return _this;
        }
        Object.defineProperty(Transform.prototype, "renderAlpha", {
            get: function () {
                return this._renderAlpha;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Transform.prototype, "width", {
            get: function () {
                var renderer = this.getComponent(Renderer);
                return renderer ? renderer.bounds.width : (isNaN(this._width) ? 0 : this._width);
            },
            set: function (value) {
                if (this._width != value) {
                    this._width = value;
                    this.makeDirty(value, 'width');
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Transform.prototype, "explicitWidth", {
            get: function () {
                return this._width;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Transform.prototype, "height", {
            get: function () {
                var renderer = this.getComponent(Renderer);
                return renderer ? renderer.bounds.height : (isNaN(this._height) ? 0 : this._height);
            },
            set: function (value) {
                if (this._height != value) {
                    this._height = value;
                    this.makeDirty(value, 'height');
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Transform.prototype, "explicitHeight", {
            get: function () {
                return this._height;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Transform.prototype, "globalPosition", {
            get: function () {
                this._globalPosition.setXY(this._globalMatrix.tx, this._globalMatrix.ty);
                return this._globalPosition;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Transform.prototype, "globalRotation", {
            get: function () {
                return this._globalMatrix.rotation * 180 / Math.PI;
            },
            enumerable: true,
            configurable: true
        });
        Transform.prototype.globalPositionToLocal = function (position) {
            var matrix = this.getMatrix(true, true, true);
            matrix.transformPoint(position.x, position.y, this.localPos);
            return this.localPos;
        };
        Transform.prototype.makeDirty = function (value, key, oldValue) {
            var e_1, _a;
            this.dirty = true;
            switch (key) {
                case 'width':
                case 'height':
                    var renderers = this.getComponents(Renderer);
                    try {
                        for (var renderers_1 = __values(renderers), renderers_1_1 = renderers_1.next(); !renderers_1_1.done; renderers_1_1 = renderers_1.next()) {
                            var renderer = renderers_1_1.value;
                            renderer.makeDirty();
                        }
                    }
                    catch (e_1_1) { e_1 = { error: e_1_1 }; }
                    finally {
                        try {
                            if (renderers_1_1 && !renderers_1_1.done && (_a = renderers_1.return)) _a.call(renderers_1);
                        }
                        finally { if (e_1) throw e_1.error; }
                    }
                    break;
            }
        };
        Transform.prototype.onModify = function (value, key, oldValue) {
            _super.prototype.onModify.call(this, value, key, oldValue);
            this.makeDirty(value, key, oldValue);
            switch (key) {
                case 'position':
                case 'scale':
                    value.onChange = this.onVector2DModify;
                    break;
            }
        };
        Transform.prototype.updateLocalMatrix = function () {
            var _a = this, _b = _a.position, x = _b.x, y = _b.y, _c = _a.scale, sx = _c.x, sy = _c.y, rotation = _a.rotation;
            var matrix = this._localMatrix;
            matrix.identity();
            if (this.order === MATRIX_ORDER.SCALE_ROTATE) {
                matrix.scale(sx, sy);
                matrix.rotate(rotation * Math.PI / 180);
            }
            else {
                matrix.rotate(rotation * Math.PI / 180);
                matrix.scale(sx, sy);
            }
            matrix.translate(x, y);
        };
        Transform.prototype.updateGlobalMatrix = function () {
            var _a = this, entity = _a.entity, _globalMatrix = _a._globalMatrix, _localMatrix = _a._localMatrix, _globalPivotMatrix = _a._globalPivotMatrix, _b = _a.pivot, px = _b.x, py = _b.y, width = _a.width, height = _a.height;
            _globalMatrix.copyFrom(_localMatrix);
            if (entity.parent) {
                var parentTransform = entity.parent.getComponent(Transform);
                if (parentTransform) {
                    this._renderAlpha = parentTransform._renderAlpha * this.alpha;
                    _globalMatrix.concat(parentTransform.getMatrix(true, false));
                }
                else {
                    this._renderAlpha = this.alpha;
                }
            }
            else {
                this._renderAlpha = this.alpha;
            }
            if (this.entity.name === 'Miner') {
                console.log();
            }
            _globalPivotMatrix.copyFrom(_globalMatrix);
            var a = _globalMatrix.a, d = _globalMatrix.d;
            _globalPivotMatrix.translate(-(px - 0.5) * width * a, -(py - 0.5) * height * d);
        };
        Transform.prototype.getMatrix = function (withPivot, invert, affectChildren) {
            if (withPivot === void 0) { withPivot = false; }
            if (invert === void 0) { invert = false; }
            if (affectChildren === void 0) { affectChildren = false; }
            var matrix;
            if (this.affectChildren || affectChildren) {
                matrix = withPivot ? this._globalPivotMatrix : this._globalMatrix;
                if (invert) {
                    var invertMatrix = this._globalInvertMatrix;
                    invertMatrix.copyFrom(matrix);
                    invertMatrix.invert();
                    return invertMatrix;
                }
            }
            else {
                matrix = this.entity.parent.getComponent(Transform).getMatrix(withPivot, invert);
            }
            return matrix;
        };
        Transform.prototype.onUpdate = function (t) {
            if (this.dirty) {
                this.updateLocalMatrix();
                this.dirty = false;
            }
            this.updateGlobalMatrix();
            _super.prototype.onUpdate.call(this, t);
        };
        Transform.prototype.onEditorUpdate = function (t) {
            this.onUpdate(t);
        };
        __decorate([
            dirtyFieldTrigger$2
        ], Transform.prototype, "position", void 0);
        __decorate([
            dirtyFieldTrigger$2
        ], Transform.prototype, "alpha", void 0);
        __decorate([
            dirtyFieldTrigger$2
        ], Transform.prototype, "affectChildren", void 0);
        __decorate([
            dirtyFieldTrigger$2
        ], Transform.prototype, "scale", void 0);
        __decorate([
            dirtyFieldTrigger$2
        ], Transform.prototype, "pivot", void 0);
        __decorate([
            dirtyFieldDetector$1
        ], Transform.prototype, "rotation", void 0);
        return Transform;
    }(ScillaComponent));

    var CameraController = (function (_super) {
        __extends(CameraController, _super);
        function CameraController() {
            var _this = _super !== null && _super.apply(this, arguments) || this;
            _this.viewportAnchor = createVector2D(0.5, 0.5);
            _this.maxScale = 1.2;
            _this.once = true;
            return _this;
        }
        CameraController.prototype.onAwake = function () {
            _super.prototype.onAwake.call(this);
            var target = this.target;
            if (target) {
                this.targetPosition = target.getComponent(Transform).position;
            }
            this.followPosition = createVector2D();
            if (this.once) {
                this.updateViewport();
            }
        };
        Object.defineProperty(CameraController.prototype, "stageSize", {
            get: function () {
                if (!this._stageSize) {
                    this._stageSize = engine.renderContext.stageSize;
                }
                return this._stageSize;
            },
            enumerable: true,
            configurable: true
        });
        CameraController.prototype.onUpdate = function (t) {
            _super.prototype.onUpdate.call(this, t);
            if (!this.once) {
                this.updateViewport();
            }
            this.followTarget();
        };
        CameraController.prototype.onEditorUpdate = function (t) {
            this.updateViewport();
        };
        CameraController.prototype.updateViewport = function () {
            if (this.viewportAnchor) {
                var _a = this.stageSize, width = _a.width, height = _a.height;
                var _b = this.viewportAnchor, x = _b.x, y = _b.y;
                var _c = this.transform.scale, sx = _c.x, sy = _c.y;
                this.transform.position.setXY(width * x * sx, height * y * sy);
            }
        };
        CameraController.prototype.followTarget = function () {
            if (!this.targetPosition) {
                return;
            }
            var _a = this, _b = _a.transform, scale = _b.scale, position = _b.position, _c = _a.stageSize, width = _c.width, height = _c.height, _d = _a.targetPosition, x = _d.x, y = _d.y, length = _d.length, maxScale = _a.maxScale;
            var newScale = maxScale - length * maxScale / 2048;
            scale.setXY(newScale, newScale);
            this.followPosition.setXY(width / 2, height / 2).subtract(this.targetPosition);
            position.copyFrom(lerpObj(position, this.followPosition, 0.1, ['x', 'y']));
        };
        return CameraController;
    }(ScillaComponent));

    var dirtyFieldDetector$2 = dirtyFieldDetector;
    var FillMode;
    (function (FillMode) {
        FillMode[FillMode["NORMAL"] = 0] = "NORMAL";
        FillMode[FillMode["SLICED"] = 1] = "SLICED";
        FillMode[FillMode["TILED"] = 2] = "TILED";
    })(FillMode || (FillMode = {}));
    var TextureRenderer = (function (_super) {
        __extends(TextureRenderer, _super);
        function TextureRenderer() {
            var _this = _super !== null && _super.apply(this, arguments) || this;
            _this.fillMode = FillMode.NORMAL;
            _this.filters = [];
            return _this;
        }
        Object.defineProperty(TextureRenderer.prototype, "hasFilters", {
            get: function () {
                return this.filters && this.filters.length > 0;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(TextureRenderer.prototype, "async_texture", {
            set: function (promise) {
                var _this = this;
                if (!promise) {
                    return;
                }
                promise.then(function (texture) {
                    _this.texture = texture;
                });
            },
            enumerable: true,
            configurable: true
        });
        TextureRenderer.prototype.draw = function () {
            _super.prototype.draw.call(this);
            this.drawImage();
            this.applyFilters();
        };
        TextureRenderer.prototype.applyFilters = function () {
            var e_1, _a;
            if (!this.hasFilters)
                return;
            var _b = this, texture = _b.texture, filters = _b.filters, currentCanvasContext = _b.currentCanvasContext;
            var _c = texture.bounds, textureWidth = _c.width, textureHeight = _c.height;
            var imageData = currentCanvasContext.getImageData(0, 0, textureWidth, textureHeight);
            try {
                for (var filters_1 = __values(filters), filters_1_1 = filters_1.next(); !filters_1_1.done; filters_1_1 = filters_1.next()) {
                    var filter = filters_1_1.value;
                    filter.drawFilter(imageData);
                }
            }
            catch (e_1_1) { e_1 = { error: e_1_1 }; }
            finally {
                try {
                    if (filters_1_1 && !filters_1_1.done && (_a = filters_1.return)) _a.call(filters_1);
                }
                finally { if (e_1) throw e_1.error; }
            }
            currentCanvasContext.putImageData(imageData, 0, 0);
        };
        TextureRenderer.prototype.drawImage = function () {
            if (!this.texture) {
                return;
            }
            var _a = this, texture = _a.texture, fillMode = _a.fillMode, currentCanvasContext = _a.currentCanvasContext, _b = _a.bounds, width = _b.width, height = _b.height;
            var _c = texture.bounds, x = _c.x, y = _c.y, textureWidth = _c.width, textureHeight = _c.height;
            switch (fillMode) {
                case FillMode.NORMAL:
                    texture.drawToCanvas(currentCanvasContext, 0, 0, undefined, undefined, width, height);
                    break;
                case FillMode.SLICED:
                    break;
                case FillMode.TILED:
                    var textureCanvas = texture.getCacheCanvas();
                    var pattern = currentCanvasContext.createPattern(textureCanvas, 'repeat');
                    currentCanvasContext.rect(0, 0, width, height);
                    currentCanvasContext.fillStyle = pattern;
                    currentCanvasContext.fill();
                    break;
            }
        };
        TextureRenderer.prototype.measureBounds = function () {
            if (!this.dirty) {
                return;
            }
            var _a = this, bounds = _a.bounds, _b = _a.transform, tWidth = _b.explicitWidth, tHeight = _b.explicitHeight;
            if (this.texture) {
                var _c = this.texture, textureWidth = _c.width, textureHeight = _c.height;
                bounds.width = isNaN(tWidth) ? textureWidth : tWidth;
                bounds.height = isNaN(tHeight) ? textureHeight : tHeight;
            }
            else {
                bounds.width = isNaN(tWidth) ? 0 : tWidth;
                bounds.height = isNaN(tHeight) ? 0 : tHeight;
            }
            _super.prototype.measureBounds.call(this);
        };
        __decorate([
            dirtyFieldDetector$2
        ], TextureRenderer.prototype, "texture", void 0);
        __decorate([
            dirtyFieldDetector$2
        ], TextureRenderer.prototype, "fillMode", void 0);
        __decorate([
            dirtyFieldDetector$2
        ], TextureRenderer.prototype, "filters", void 0);
        return TextureRenderer;
    }(Renderer));

    var dirtyFieldTrigger$3 = dirtyFieldTrigger;
    var InteractComponent = (function (_super) {
        __extends(InteractComponent, _super);
        function InteractComponent() {
            var _this = _super.call(this) || this;
            _this.interactable = true;
            _this.touchInterrupt = false;
            _this.invertMatrix = Matrix.create();
            _this.localPos = {};
            _this.isOut = true;
            return _this;
        }
        InteractComponent.prototype.onModify = function (value, key, oldValue) {
            _super.prototype.onModify.call(this, value, key, oldValue);
            if (key === 'interactable') {
                if (this.entity) {
                    this.onInteractableChanged(value);
                }
            }
        };
        InteractComponent.prototype.onInteractableChanged = function (interactable) {
        };
        InteractComponent.prototype._dealGlobalTouchBegin = function (e) {
            var interrupt = _super.prototype._dealGlobalTouchBegin.call(this, e);
            var hitOn = this.hitTest(e);
            if (hitOn) {
                this._touchBeginFlag = true;
                this.onTouchBegin(e);
                this._dealTouchOver(e);
            }
            return hitOn && (interrupt || this.touchInterrupt);
        };
        InteractComponent.prototype._dealGlobalTouchMove = function (e) {
            var interrupt = _super.prototype._dealGlobalTouchMove.call(this, e);
            var hitOn = this.hitTest(e);
            if (hitOn) {
                this._dealTouchOver(e);
                this.onTouchMove(e);
            }
            else {
                this._dealTouchOut(e);
            }
            return hitOn && (interrupt || this.touchInterrupt);
        };
        InteractComponent.prototype._dealGlobalTouchEnd = function (e) {
            var interrupt = _super.prototype._dealGlobalTouchEnd.call(this, e);
            var hitOn = this.hitTest(e);
            if (hitOn) {
                this.onTouchEnd(e);
                if (this._touchBeginFlag) {
                    this.onTouchTap(e);
                    this._touchBeginFlag = false;
                }
            }
            this.isOut = true;
            return hitOn && (interrupt || this.touchInterrupt);
        };
        InteractComponent.prototype._dealTouchOver = function (e) {
            if (this.isOut) {
                this.isOut = false;
                this.onTouchOver(e);
            }
        };
        InteractComponent.prototype._dealTouchOut = function (e) {
            if (!this.isOut) {
                this.isOut = true;
                this.onTouchOut(e);
            }
        };
        InteractComponent.prototype.onTouchBegin = function (e) {
        };
        InteractComponent.prototype.onTouchMove = function (e) {
        };
        InteractComponent.prototype.onTouchOver = function (e) {
        };
        InteractComponent.prototype.onTouchOut = function (e) {
        };
        InteractComponent.prototype.onTouchEnd = function (e) {
        };
        InteractComponent.prototype.onTouchTap = function (e) {
        };
        InteractComponent.prototype.hitTest = function (e) {
            var e_1, _a;
            var matrix = this.transform.getMatrix(true, true, true);
            matrix.transformPoint(e.x, e.y, this.localPos);
            var renderers = this.getComponents(Renderer);
            var result = false;
            try {
                for (var renderers_1 = __values(renderers), renderers_1_1 = renderers_1.next(); !renderers_1_1.done; renderers_1_1 = renderers_1.next()) {
                    var renderer = renderers_1_1.value;
                    if (!renderer['isUsedToMask'] && renderer.hitTest(this.localPos.x, this.localPos.y)) {
                        result = true;
                        break;
                    }
                }
            }
            catch (e_1_1) { e_1 = { error: e_1_1 }; }
            finally {
                try {
                    if (renderers_1_1 && !renderers_1_1.done && (_a = renderers_1.return)) _a.call(renderers_1);
                }
                finally { if (e_1) throw e_1.error; }
            }
            return result;
        };
        __decorate([
            dirtyFieldTrigger$3
        ], InteractComponent.prototype, "interactable", void 0);
        return InteractComponent;
    }(ScillaComponent));

    var TouchInterrupt = (function (_super) {
        __extends(TouchInterrupt, _super);
        function TouchInterrupt() {
            var _this = _super !== null && _super.apply(this, arguments) || this;
            _this.touchInterrupt = true;
            return _this;
        }
        return TouchInterrupt;
    }(InteractComponent));

    var TouchZoom = (function (_super) {
        __extends(TouchZoom, _super);
        function TouchZoom() {
            var _this = _super !== null && _super.apply(this, arguments) || this;
            _this.scaleOffset = createVector2D(0.1, 0.1);
            _this.duration = 200;
            _this.easeName = Ease.backOut;
            return _this;
        }
        TouchZoom.prototype.onAwake = function () {
            _super.prototype.onAwake.call(this);
            if (!this._zoomIn) {
                var _a = this, scaleOffset = _a.scaleOffset, duration = _a.duration, transform = _a.transform;
                var easeFunc = ease[this.easeName];
                var scaleFrom = transform.scale.clone();
                var scaleTo = transform.scale.clone().add(scaleOffset);
                this._zoomIn = createTween(this, transform, false, { autoPlay: false, fields: ['x', 'y'] })
                    .to({ scale: scaleTo }, duration, easeFunc);
                this._zoomOut = createTween(this, transform, false, { autoPlay: false, fields: ['x', 'y'] })
                    .to({ scale: scaleFrom }, duration, easeFunc);
            }
        };
        TouchZoom.prototype.onTouchBegin = function (e) {
            _super.prototype.onTouchOver.call(this, e);
            if (this.interactable) {
                this._touchBegin = true;
                this._zoomIn.play(true);
            }
        };
        TouchZoom.prototype.onGlobalTouchEnd = function (e) {
            _super.prototype.onGlobalTouchEnd.call(this, e);
            if (this._touchBegin) {
                this._touchBegin = false;
                this._zoomOut.play(true);
            }
            return false;
        };
        return TouchZoom;
    }(InteractComponent));

    var dirtyFieldDetector$3 = dirtyFieldDetector;
    var GraphicRenderer = (function (_super) {
        __extends(GraphicRenderer, _super);
        function GraphicRenderer() {
            var _this = _super !== null && _super.apply(this, arguments) || this;
            _this.fillColor = '#42bce4';
            _this.borderColor = '#0899d0';
            _this.borderWidth = 0;
            _this.isMask = false;
            _this.maskVisible = false;
            return _this;
        }
        GraphicRenderer.prototype.getUseCacheMode = function () {
            return this._useCacheMode && !this.isMask;
        };
        GraphicRenderer.prototype.getRenderSize = function () {
            return { width: 0, height: 0 };
        };
        GraphicRenderer.prototype.beforeDraw = function () {
            _super.prototype.beforeDraw.call(this);
            this.applyStyle();
            this.currentCanvasContext.beginPath();
        };
        GraphicRenderer.prototype.draw = function () {
            _super.prototype.draw.call(this);
            if (this.isMask) {
                this._context.clip();
                this.maskVisible && this.fillAndStoke();
            }
            else {
                this.fillAndStoke();
            }
        };
        GraphicRenderer.prototype.applyStyle = function () {
            var _a = this, currentCanvasContext = _a.currentCanvasContext, fillColor = _a.fillColor, borderColor = _a.borderColor, borderWidth = _a.borderWidth;
            currentCanvasContext.fillStyle = fillColor;
            if (borderWidth > 0) {
                currentCanvasContext.strokeStyle = borderColor;
                currentCanvasContext.lineWidth = borderWidth;
            }
        };
        GraphicRenderer.prototype.fillAndStoke = function () {
            var _a = this, currentCanvasContext = _a.currentCanvasContext, borderWidth = _a.borderWidth;
            currentCanvasContext.fill();
            if (borderWidth > 0) {
                currentCanvasContext.stroke();
            }
        };
        GraphicRenderer.prototype.drawClip = function () {
            this.isMask && this.currentCanvasContext.save();
        };
        GraphicRenderer.prototype.afterUpdate = function () {
            this.isMask && this.currentCanvasContext.restore();
        };
        GraphicRenderer.prototype.afterEditorUpdate = function () {
            this.afterUpdate();
        };
        GraphicRenderer.prototype.measureBounds = function () {
            if (!this.dirty) {
                return;
            }
            this._margin = this.borderWidth;
            var _a = this, bounds = _a.bounds, _b = _a.transform, tWidth = _b.explicitWidth, tHeight = _b.explicitHeight;
            var _c = this.getRenderSize(), sWidth = _c.width, sHeight = _c.height;
            bounds.width = isNaN(tWidth) ? sWidth : tWidth;
            bounds.height = isNaN(tHeight) ? sHeight : tHeight;
            _super.prototype.measureBounds.call(this);
        };
        __decorate([
            dirtyFieldDetector$3
        ], GraphicRenderer.prototype, "fillColor", void 0);
        __decorate([
            dirtyFieldDetector$3
        ], GraphicRenderer.prototype, "borderColor", void 0);
        __decorate([
            dirtyFieldDetector$3
        ], GraphicRenderer.prototype, "borderWidth", void 0);
        __decorate([
            dirtyFieldDetector$3
        ], GraphicRenderer.prototype, "isMask", void 0);
        __decorate([
            dirtyFieldDetector$3
        ], GraphicRenderer.prototype, "maskVisible", void 0);
        return GraphicRenderer;
    }(Renderer));

    var dirtyFieldDetector$4 = dirtyFieldDetector;
    var CircleRenderer = (function (_super) {
        __extends(CircleRenderer, _super);
        function CircleRenderer() {
            var _this = _super !== null && _super.apply(this, arguments) || this;
            _this.radius = 50;
            _this.startAngle = 0;
            _this.endAngle = 360;
            _this.backToCenter = true;
            return _this;
        }
        CircleRenderer.prototype.getRenderSize = function () {
            var radius = this.radius;
            return { width: radius * 2, height: radius * 2 };
        };
        CircleRenderer.prototype.draw = function () {
            var _a = this, currentCanvasContext = _a.currentCanvasContext, _b = _a.bounds, width = _b.width, height = _b.height, startAngle = _a.startAngle, endAngle = _a.endAngle, backToCenter = _a.backToCenter, _margin = _a._margin, _useCacheMode = _a._useCacheMode;
            var offset = _useCacheMode ? _margin : 0;
            var radius = Math.min(width, height) / 2;
            var pos = offset + radius;
            if (startAngle == 0 && endAngle == 360) {
                currentCanvasContext.arc(pos, pos, radius, 0, 2 * Math.PI);
            }
            else {
                if (backToCenter) {
                    currentCanvasContext.moveTo(pos, pos);
                }
                currentCanvasContext.arc(pos, pos, radius, startAngle * Math.PI / 180, endAngle * Math.PI / 180);
                if (backToCenter) {
                    currentCanvasContext.lineTo(pos, pos);
                }
            }
            _super.prototype.draw.call(this);
        };
        __decorate([
            dirtyFieldDetector$4
        ], CircleRenderer.prototype, "radius", void 0);
        __decorate([
            dirtyFieldDetector$4
        ], CircleRenderer.prototype, "startAngle", void 0);
        __decorate([
            dirtyFieldDetector$4
        ], CircleRenderer.prototype, "endAngle", void 0);
        __decorate([
            dirtyFieldDetector$4
        ], CircleRenderer.prototype, "backToCenter", void 0);
        return CircleRenderer;
    }(GraphicRenderer));

    var FrameAnimationRenderer = (function (_super) {
        __extends(FrameAnimationRenderer, _super);
        function FrameAnimationRenderer() {
            var _this = _super !== null && _super.apply(this, arguments) || this;
            _this.autoPlay = false;
            _this.fps = NaN;
            _this.onComplete = new ScillaEvent();
            _this.onLoopComplete = new ScillaEvent();
            return _this;
        }
        FrameAnimationRenderer.prototype.onAwake = function () {
            _super.prototype.onAwake.call(this);
            if (this.autoPlay) {
                this.play(0, -1);
            }
        };
        FrameAnimationRenderer.prototype.onUpdate = function (t) {
            if (this._playing) {
                var _a = this, frameAnimation = _a.frameAnimation, _startFrame = _a._startFrame, _endFrame = _a._endFrame, fps = _a.fps;
                if (this._startFlag) {
                    this._startFlag = false;
                    this._startTime = t;
                    this._loopCounting++;
                }
                var mFPS = isNaN(fps) ? frameAnimation.fps : fps;
                var passTime = t - this._startTime;
                var passFrameCount = Math.floor(passTime / (1000 / mFPS));
                var passFrameInRegion = passFrameCount % (_endFrame - _startFrame + 1);
                this._currentFrameIndex = _startFrame + passFrameInRegion;
                if (passFrameInRegion == 0 && passFrameCount > 0) {
                    this._currentFrameIndex = _endFrame;
                    this.onLoopEnd();
                }
            }
            _super.prototype.onUpdate.call(this, t);
        };
        FrameAnimationRenderer.prototype.onSleep = function () {
            _super.prototype.onSleep.call(this);
        };
        FrameAnimationRenderer.prototype.onLoopEnd = function () {
            if (this._loop < 0) {
                this._startFlag = true;
                this.onLoopComplete.invoke(this._lastLabel);
            }
            else if (this._loopCounting < this._loop) {
                this._startFlag = true;
                this.onLoopComplete.invoke(this._lastLabel);
            }
            else {
                this._playing = false;
                this.onComplete.invoke(this._lastLabel);
            }
        };
        FrameAnimationRenderer.prototype.play = function (frame, loop, force) {
            if (frame === void 0) { frame = 0; }
            if (loop === void 0) { loop = 0; }
            if (force === void 0) { force = true; }
            this._loop = loop;
            this._loopCounting = 0;
            if (!this.frameAnimation) {
                return;
            }
            var startFrame = 0, endFrame = this.frameAnimation.frameCount - 1;
            if (typeof frame == 'string') {
                this._lastLabel = frame;
                var label = this.frameAnimation.getLabel(frame);
                if (label) {
                    startFrame = label.frame - 1;
                    endFrame = label.end - 1;
                }
            }
            else {
                this._lastLabel = null;
                startFrame = frame;
            }
            this._startFrame = startFrame;
            this._endFrame = endFrame;
            this._currentFrameIndex = this._startFrame;
            this._startFlag = true;
            this._playing = true;
        };
        FrameAnimationRenderer.prototype.stop = function () {
            this._playing = false;
        };
        FrameAnimationRenderer.prototype.draw = function () {
            _super.prototype.draw.call(this);
            if (!this.frameAnimation) {
                return;
            }
            var _a = this, currentCanvasContext = _a.currentCanvasContext, frameAnimation = _a.frameAnimation, _currentFrameIndex = _a._currentFrameIndex, bounds = _a.bounds;
            var _b = frameAnimation.getFrame(_currentFrameIndex), texture = _b.texture, data = _b.data;
            if (texture) {
                var img = texture.img, _c = texture.bounds, x = _c.x, y = _c.y, textureWidth = _c.width, textureHeight = _c.height;
                bounds.setTo(data.x, data.y, textureWidth, textureHeight);
                currentCanvasContext.drawImage(img, x, y, textureWidth, textureHeight, data.x, data.y, textureWidth, textureHeight);
            }
        };
        return FrameAnimationRenderer;
    }(Renderer));

    var LineRenderer = (function (_super) {
        __extends(LineRenderer, _super);
        function LineRenderer() {
            var _this = _super !== null && _super.apply(this, arguments) || this;
            _this.x0 = 0;
            _this.y0 = 0;
            _this.x1 = 0;
            _this.y1 = 0;
            return _this;
        }
        LineRenderer.prototype.draw = function () {
            _super.prototype.draw.call(this);
            var _a = this, currentCanvasContext = _a.currentCanvasContext, x0 = _a.x0, y0 = _a.y0, x1 = _a.x1, y1 = _a.y1;
            currentCanvasContext.moveTo(x0, y0);
            currentCanvasContext.lineTo(x1, y1);
        };
        LineRenderer.prototype.measureBounds = function () {
            var bounds = this.bounds;
            bounds.width = 0;
            bounds.height = 0;
            _super.prototype.measureBounds.call(this);
        };
        return LineRenderer;
    }(GraphicRenderer));

    var dirtyFieldDetector$5 = dirtyFieldDetector;
    var RectRenderer = (function (_super) {
        __extends(RectRenderer, _super);
        function RectRenderer() {
            var _this = _super !== null && _super.apply(this, arguments) || this;
            _this.width = 100;
            _this.height = 100;
            _this.cornerRadius = 0;
            return _this;
        }
        RectRenderer.prototype.getRenderSize = function () {
            var _a = this, width = _a.width, height = _a.height;
            return { width: width, height: height };
        };
        RectRenderer.prototype.draw = function () {
            var PI = Math.PI;
            var _a = this, currentCanvasContext = _a.currentCanvasContext, r = _a.cornerRadius, _b = _a.bounds, width = _b.width, height = _b.height, _margin = _a._margin, _useCacheMode = _a._useCacheMode;
            var offset = _useCacheMode ? _margin : 0;
            if (r) {
                currentCanvasContext.moveTo(offset + r, offset + 0);
                currentCanvasContext.lineTo(offset + width - r, offset + 0);
                currentCanvasContext.arc(offset + width - r, offset + r, r, PI * 3 / 2, PI * 2);
                currentCanvasContext.lineTo(offset + width, offset + height - r);
                currentCanvasContext.arc(offset + width - r, offset + height - r, r, 0, PI / 2);
                currentCanvasContext.lineTo(offset + r, offset + height);
                currentCanvasContext.arc(offset + r, offset + height - r, r, PI / 2, PI);
                currentCanvasContext.lineTo(offset + 0, offset + r);
                currentCanvasContext.arc(offset + r, offset + r, r, PI, PI * 3 / 2);
            }
            else {
                currentCanvasContext.rect(offset, offset, width, height);
            }
            _super.prototype.draw.call(this);
        };
        __decorate([
            dirtyFieldDetector$5
        ], RectRenderer.prototype, "width", void 0);
        __decorate([
            dirtyFieldDetector$5
        ], RectRenderer.prototype, "height", void 0);
        __decorate([
            dirtyFieldDetector$5
        ], RectRenderer.prototype, "cornerRadius", void 0);
        return RectRenderer;
    }(GraphicRenderer));

    var dirtyFieldDetector$6 = dirtyFieldDetector, dirtyFieldTrigger$4 = dirtyFieldTrigger;
    var TextAlign;
    (function (TextAlign) {
        TextAlign["LEFT"] = "left";
        TextAlign["CENTER"] = "center";
        TextAlign["RIGHT"] = "right";
    })(TextAlign || (TextAlign = {}));
    var VerticalAlign;
    (function (VerticalAlign) {
        VerticalAlign["TOP"] = "top";
        VerticalAlign["MIDDLE"] = "middle";
        VerticalAlign["BOTTOM"] = "bottom";
    })(VerticalAlign || (VerticalAlign = {}));
    var TextRenderer = (function (_super) {
        __extends(TextRenderer, _super);
        function TextRenderer() {
            var _this = _super !== null && _super.apply(this, arguments) || this;
            _this.text = '';
            _this.textFlow = null;
            _this.textAlign = TextAlign.CENTER;
            _this.verticalAlign = VerticalAlign.MIDDLE;
            _this.lineSpacing = 0;
            _this.letterSpacing = 0;
            _this._lineHeight = NaN;
            _this._bmpLineHeight = 0;
            _this.textStyle = new TextStyle();
            _this.useCacheMode = true;
            _this.measureCache = {};
            return _this;
        }
        TextRenderer.prototype.onModify = function (value, key, oldValue) {
            _super.prototype.onModify.call(this, value, key, oldValue);
            switch (key) {
                case 'textFlow':
                    if (value) {
                        this.updateTextFlow();
                    }
                    break;
                case 'textStyle':
                    value.onChange = this.makeDirty.bind(this);
                    this.makeDirty();
                    break;
            }
        };
        TextRenderer.prototype.updateTextFlow = function () {
            var e_1, _a;
            var text = '';
            if (this.textFlow) {
                try {
                    for (var _b = __values(this.textFlow), _c = _b.next(); !_c.done; _c = _b.next()) {
                        var item = _c.value;
                        text += item.text;
                    }
                }
                catch (e_1_1) { e_1 = { error: e_1_1 }; }
                finally {
                    try {
                        if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
                    }
                    finally { if (e_1) throw e_1.error; }
                }
            }
            this._pureText = text;
            this.makeDirty();
        };
        Object.defineProperty(TextRenderer.prototype, "lineHeight", {
            get: function () {
                return isNaN(this._lineHeight) ? (this.isBmpMode ? this._bmpLineHeight : this.textStyle.fontSize * EngineConfig.lineHeightRatio) : this._lineHeight;
            },
            set: function (value) {
                if (this._lineHeight != value) {
                    this._lineHeight = value;
                    this.dirty = true;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(TextRenderer.prototype, "pureText", {
            get: function () {
                return this.textFlow ? this._pureText : this.text;
            },
            enumerable: true,
            configurable: true
        });
        TextRenderer.prototype.getRenderSize = function () {
            return {
                width: this._textWidth,
                height: this._textHeight,
            };
        };
        TextRenderer.prototype.beforeDraw = function () {
            _super.prototype.beforeDraw.call(this);
            if (!this.isBmpMode) {
                this.applyTextStyle();
            }
        };
        TextRenderer.prototype.applyTextStyle = function () {
            var _a = this, currentCanvasContext = _a.currentCanvasContext, textStyle = _a.textStyle;
            var fontStyle = textStyle.fontStyle, fontVariant = textStyle.fontVariant, fontWeight = textStyle.fontWeight, fontSize = textStyle.fontSize, fontFamily = textStyle.fontFamily;
            currentCanvasContext.font = fontStyle + " " + fontVariant + " " + fontWeight + " " + fontSize + "px " + fontFamily;
        };
        TextRenderer.prototype.fillAndStoke = function () {
            if (!this.pureText || this.pureText.length == 0) {
                return;
            }
            var _a = this, currentCanvasContext = _a.currentCanvasContext, measureCache = _a.measureCache, lineHeight = _a.lineHeight, lineSpacing = _a.lineSpacing, letterSpacing = _a.letterSpacing, rows = _a.rows, textAlign = _a.textAlign, verticalAlign = _a.verticalAlign, isBmpMode = _a.isBmpMode, _b = _a.transform, width = _b.width, height = _b.height;
            var rowCount = rows.length;
            var x = 0;
            switch (textAlign) {
                case "left":
                    x = 0;
                    break;
                case "right":
                    x = width;
                    break;
                case "center":
                default:
                    x = width / 2;
                    break;
            }
            var y = 0;
            var drawHeight = rowCount * lineHeight + lineSpacing * (rowCount - 1);
            switch (verticalAlign) {
                case "top":
                    y = 0;
                    break;
                case "bottom":
                    y = height - drawHeight;
                    break;
                case "middle":
                default:
                    y = (height - drawHeight) / 2;
                    break;
            }
            y += lineHeight;
            currentCanvasContext.textAlign = letterSpacing == 0 && !this.textFlow ? textAlign : 'left';
            currentCanvasContext.textBaseline = 'bottom';
            var offY = 0;
            for (var i = 0; i < rowCount; i++) {
                var _c = rows[i], text = _c.text, lineWidth = _c.lineWidth;
                if (letterSpacing == 0 && !isBmpMode && !this.textFlow) {
                    this.drawText(i, text, x, y + offY);
                }
                else {
                    var offX = 0;
                    switch (textAlign) {
                        case "left":
                            offX = 0;
                            break;
                        case "right":
                            offX = -lineWidth;
                            break;
                        case "center":
                        default:
                            offX = -lineWidth / 2;
                            break;
                    }
                    for (var j = 0, lj = text.length; j < lj; j++) {
                        var char = text[j];
                        this.drawText(j, char, x + offX, y + offY);
                        if (measureCache[char].width > 0) {
                            offX += measureCache[char].width + letterSpacing;
                        }
                    }
                }
                offY += lineHeight + lineSpacing;
            }
        };
        TextRenderer.prototype.getStyle = function (index) {
            var e_2, _a;
            if (!this.textFlow) {
                return null;
            }
            var targetItem;
            var count = 0;
            try {
                for (var _b = __values(this.textFlow), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var item = _c.value;
                    count += item.text.length;
                    if (index < count) {
                        targetItem = item;
                        break;
                    }
                }
            }
            catch (e_2_1) { e_2 = { error: e_2_1 }; }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
                }
                finally { if (e_2) throw e_2.error; }
            }
            return targetItem.style;
        };
        TextRenderer.prototype.drawText = function (index, text, x, y) {
            var _a = this, currentCanvasContext = _a.currentCanvasContext, borderWidth = _a.borderWidth, isBmpMode = _a.isBmpMode, fontRes = _a.fontRes;
            if (isBmpMode) {
                var texture = fontRes.getTexture(text);
                if (!texture) {
                    return;
                }
                var _b = texture.bounds, textureX = _b.x, textureY = _b.y, textureWidth = _b.width, textureHeight = _b.height;
                currentCanvasContext.drawImage(texture.img, textureX, textureY, textureWidth, textureHeight, x, y, textureWidth, textureHeight);
            }
            else {
                var style = this.getStyle(index);
                if (style) {
                    if (style.hasOwnProperty('textColor')) {
                        currentCanvasContext.fillStyle = style.textColor;
                    }
                }
                else {
                    currentCanvasContext.fillStyle = this.fillColor;
                }
                currentCanvasContext.fillText(text, x, y + 1);
                if (borderWidth > 0) {
                    currentCanvasContext.strokeText(text, x, y + 1);
                }
            }
        };
        Object.defineProperty(TextRenderer.prototype, "isBmpMode", {
            get: function () {
                return !!this.fontRes;
            },
            enumerable: true,
            configurable: true
        });
        TextRenderer.prototype.measureText = function (text) {
            var e_3, _a, e_4, _b;
            var result;
            if (this.measureCache.hasOwnProperty(text)) {
                result = this.measureCache[text];
            }
            else {
                var _c = this, currentCanvasContext = _c.currentCanvasContext, letterSpacing = _c.letterSpacing, isBmpMode = _c.isBmpMode, fontRes = _c.fontRes, lineHeight = _c.lineHeight;
                if (isBmpMode) {
                    if (text.length == 1) {
                        var texture = fontRes.getTexture(text);
                        result = {
                            width: texture ? texture.width : 0,
                            height: texture ? texture.height : 0,
                        };
                    }
                    else {
                        var totalWidth = 0, totalHeight = 0;
                        try {
                            for (var text_1 = __values(text), text_1_1 = text_1.next(); !text_1_1.done; text_1_1 = text_1.next()) {
                                var char = text_1_1.value;
                                var measureResult = this.measureText(char);
                                totalWidth += measureResult.width;
                                if (measureResult.height > totalHeight) {
                                    totalHeight = measureResult.height;
                                }
                            }
                        }
                        catch (e_3_1) { e_3 = { error: e_3_1 }; }
                        finally {
                            try {
                                if (text_1_1 && !text_1_1.done && (_a = text_1.return)) _a.call(text_1);
                            }
                            finally { if (e_3) throw e_3.error; }
                        }
                        result = {
                            width: totalWidth,
                            height: totalHeight,
                        };
                    }
                }
                else {
                    result = {
                        width: currentCanvasContext.measureText(text).width,
                        height: lineHeight,
                    };
                }
                result.width += letterSpacing * (text.length - 1);
                if (text.length == 1) {
                    this.measureCache[text] = result;
                }
                if (letterSpacing != 0 && text.length > 1 || this.textFlow) {
                    try {
                        for (var text_2 = __values(text), text_2_1 = text_2.next(); !text_2_1.done; text_2_1 = text_2.next()) {
                            var char = text_2_1.value;
                            this.measureCache[char] = this.measureText(char);
                        }
                    }
                    catch (e_4_1) { e_4 = { error: e_4_1 }; }
                    finally {
                        try {
                            if (text_2_1 && !text_2_1.done && (_b = text_2.return)) _b.call(text_2);
                        }
                        finally { if (e_4) throw e_4.error; }
                    }
                }
            }
            return result;
        };
        TextRenderer.prototype.splitText = function () {
            var e_5, _a;
            var _b = this, text = _b.pureText, letterSpacing = _b.letterSpacing, lineSpacing = _b.lineSpacing, lineHeight = _b.lineHeight, isBmpMode = _b.isBmpMode, _c = _b.transform, explicitWidth = _c.explicitWidth, explicitHeight = _c.explicitHeight;
            this.measureCache = {};
            var textWidth = 0, textHeight = 0, maxHeight = 0;
            var rows = [], measureResult;
            if (text && text.length > 0) {
                if (isNaN(explicitWidth)) {
                    var lines = text.split('\n');
                    try {
                        for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
                            var line = lines_1_1.value;
                            measureResult = this.measureText(line);
                            var mw = measureResult.width;
                            if (mw > textWidth) {
                                textWidth = mw;
                            }
                            if (isBmpMode) {
                                var mh = measureResult.height;
                                if (mh > maxHeight) {
                                    maxHeight = mh;
                                }
                            }
                            rows.push({
                                text: line,
                                lineWidth: mw,
                            });
                        }
                    }
                    catch (e_5_1) { e_5 = { error: e_5_1 }; }
                    finally {
                        try {
                            if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
                        }
                        finally { if (e_5) throw e_5.error; }
                    }
                    if (!isBmpMode) {
                        maxHeight = lineHeight;
                    }
                    this._bmpLineHeight = maxHeight;
                }
                else {
                    var chars = text.split('');
                    var lineWidth = 0, charWidth = 0, index = 0;
                    var line = '';
                    for (var i = 0, li = chars.length; i < li; i++) {
                        var char = chars[i];
                        if (char == '\n') {
                            rows.push({
                                text: line,
                                lineWidth: lineWidth,
                            });
                            line = '';
                            lineWidth = 0;
                            index = 0;
                        }
                        else {
                            measureResult = this.measureText(char);
                            if (measureResult.width == 0) {
                                continue;
                            }
                            charWidth = measureResult.width;
                            var mh = measureResult.height;
                            if (mh > maxHeight) {
                                maxHeight = mh;
                            }
                            if (index > 0 && lineWidth + charWidth + (index == 0 ? 0 : letterSpacing) > explicitWidth) {
                                rows.push({
                                    text: line,
                                    lineWidth: lineWidth,
                                });
                                line = '';
                                lineWidth = 0;
                                index = 0;
                            }
                            line += char;
                            lineWidth += charWidth + (index == 0 ? 0 : letterSpacing);
                            index++;
                        }
                    }
                    this._bmpLineHeight = maxHeight;
                    rows.push({
                        text: line,
                        lineWidth: lineWidth,
                    });
                    textWidth = explicitWidth;
                }
                textHeight = isNaN(explicitHeight) ? (maxHeight * rows.length + lineSpacing * (rows.length - 1)) : explicitHeight;
            }
            else {
                textWidth = isNaN(explicitWidth) ? 0 : explicitWidth;
                textHeight = isNaN(explicitHeight) ? 0 : explicitHeight;
            }
            this.rows = rows;
            this._textWidth = textWidth;
            this._textHeight = textHeight;
            return {
                rows: rows,
                textWidth: textWidth,
                textHeight: textHeight,
            };
        };
        TextRenderer.prototype.measureBounds = function () {
            if (!this.dirty) {
                return;
            }
            if (!this.isBmpMode) {
                this.applyTextStyle();
            }
            this.splitText();
            _super.prototype.measureBounds.call(this);
        };
        __decorate([
            dirtyFieldDetector$6
        ], TextRenderer.prototype, "text", void 0);
        __decorate([
            dirtyFieldTrigger$4
        ], TextRenderer.prototype, "textFlow", void 0);
        __decorate([
            dirtyFieldDetector$6
        ], TextRenderer.prototype, "textAlign", void 0);
        __decorate([
            dirtyFieldDetector$6
        ], TextRenderer.prototype, "verticalAlign", void 0);
        __decorate([
            dirtyFieldDetector$6
        ], TextRenderer.prototype, "lineSpacing", void 0);
        __decorate([
            dirtyFieldDetector$6
        ], TextRenderer.prototype, "letterSpacing", void 0);
        __decorate([
            dirtyFieldDetector$6
        ], TextRenderer.prototype, "fontRes", void 0);
        __decorate([
            dirtyFieldDetector$6
        ], TextRenderer.prototype, "textStyle", void 0);
        __decorate([
            dirtyFieldDetector$6
        ], TextRenderer.prototype, "useCacheMode", void 0);
        return TextRenderer;
    }(GraphicRenderer));

    var dirtyFieldDetector$7 = dirtyFieldDetector;
    var floatLayerName = 'floatLayer';
    function getFloatLayer() {
        var floatLayer = engine.canvasElement.nextElementSibling;
        if (!floatLayer || floatLayer.id !== floatLayerName) {
            floatLayer = document.createElement('div');
            floatLayer.id = floatLayerName;
            floatLayer.style.position = 'absolute';
            floatLayer.style.overflowY = 'auto';
            engine.canvasElement.parentElement.append(floatLayer);
        }
        return floatLayer;
    }
    function showFloatLayer() {
        var floatLayer = getFloatLayer();
        floatLayer.style.display = 'inherit';
    }
    function hideFloatLayer() {
        var floatLayer = getFloatLayer();
        floatLayer.style.display = 'none';
    }
    var HtmlRenderer = (function (_super) {
        __extends(HtmlRenderer, _super);
        function HtmlRenderer() {
            var _this = _super !== null && _super.apply(this, arguments) || this;
            _this.fontSize = 14;
            _this.color = '#000';
            return _this;
        }
        HtmlRenderer.prototype.onAwake = function () {
            _super.prototype.onAwake.call(this);
            showFloatLayer();
        };
        HtmlRenderer.prototype.onSleep = function () {
            _super.prototype.onSleep.call(this);
            hideFloatLayer();
        };
        HtmlRenderer.prototype.onUpdate = function (t) {
            _super.prototype.onUpdate.call(this, t);
            var floatLayer = getFloatLayer();
            var style = floatLayer.style;
            if (this['dirty']) {
                this['dirty'] = false;
                floatLayer.innerHTML = this.htmlText;
                style.fontSize = this.fontSize + 'px';
                style.color = this.color;
            }
            if (this.htmlText) {
                var _a = this.transform, _b = _a.globalPosition, x = _b.x, y = _b.y, width = _a.width, height = _a.height;
                var _c = engine.canvasPosToPagePos(x, y), px = _c.x, py = _c.y;
                var _d = engine.canvasPosToPagePos(width, height), pWidth = _d.x, pHeight = _d.y;
                if (style.left !== (px - pWidth / 2) + 'px') {
                    style.left = (px - pWidth / 2) + 'px';
                }
                if (style.top !== (py - pHeight / 2) + 'px') {
                    style.top = (py - pHeight / 2) + 'px';
                }
                if (style.width !== pWidth + 'px') {
                    style.width = pWidth + 'px';
                }
                if (style.height !== pHeight + 'px') {
                    style.height = pHeight + 'px';
                }
            }
        };
        __decorate([
            dirtyFieldDetector$7
        ], HtmlRenderer.prototype, "htmlText", void 0);
        __decorate([
            dirtyFieldDetector$7
        ], HtmlRenderer.prototype, "fontSize", void 0);
        __decorate([
            dirtyFieldDetector$7
        ], HtmlRenderer.prototype, "color", void 0);
        return HtmlRenderer;
    }(ScillaComponent));

    var dirtyFieldDetector$8 = dirtyFieldDetector;
    var STATUS$1;
    (function (STATUS) {
        STATUS[STATUS["UP"] = 0] = "UP";
        STATUS[STATUS["DOWN"] = 1] = "DOWN";
        STATUS[STATUS["DISABLED"] = 2] = "DISABLED";
    })(STATUS$1 || (STATUS$1 = {}));
    var Button = (function (_super) {
        __extends(Button, _super);
        function Button() {
            var _this = _super !== null && _super.apply(this, arguments) || this;
            _this.onClick = new ScillaEvent();
            _this.touchInterrupt = true;
            return _this;
        }
        Button.prototype.onInteractableChanged = function (interactable) {
            var e_1, _a;
            var interactComponents = this.getComponents(InteractComponent);
            try {
                for (var interactComponents_1 = __values(interactComponents), interactComponents_1_1 = interactComponents_1.next(); !interactComponents_1_1.done; interactComponents_1_1 = interactComponents_1.next()) {
                    var interactComponent = interactComponents_1_1.value;
                    if (interactComponent !== this) {
                        interactComponent.interactable = interactable;
                    }
                }
            }
            catch (e_1_1) { e_1 = { error: e_1_1 }; }
            finally {
                try {
                    if (interactComponents_1_1 && !interactComponents_1_1.done && (_a = interactComponents_1.return)) _a.call(interactComponents_1);
                }
                finally { if (e_1) throw e_1.error; }
            }
            this.changeTexture();
        };
        Button.prototype.onAwake = function () {
            _super.prototype.onAwake.call(this);
            if (!this._bgRenderer) {
                this._bgRenderer = this.getComponent(TextureRenderer);
                this._label = this.Label && this.Label.getComponent(TextRenderer);
                this.changeTexture(STATUS$1.UP);
            }
        };
        Button.prototype.onUpdate = function (t) {
            _super.prototype.onUpdate.call(this, t);
            if (this['dirty']) {
                this.changeTexture();
                this['dirty'] = false;
            }
        };
        Button.prototype.onTouchBegin = function (e) {
            _super.prototype.onTouchBegin.call(this, e);
            this._touchBeginWithSelf = true;
            this.changeTexture(STATUS$1.DOWN);
        };
        Button.prototype.onTouchOver = function (e) {
            _super.prototype.onTouchOver.call(this, e);
            if (this._touchBeginWithSelf) {
                this._touchBeginWithSelf = true;
                this.changeTexture(STATUS$1.DOWN);
            }
            this._touchOut = false;
        };
        Button.prototype.onTouchOut = function (e) {
            _super.prototype.onTouchOut.call(this, e);
            if (this._touchBeginWithSelf) {
                this.changeTexture(STATUS$1.UP);
            }
            this._touchOut = true;
        };
        Button.prototype.onGlobalTouchEnd = function (e) {
            if (this._touchBeginWithSelf && !this._touchOut) {
                this.onClick.invoke();
            }
            this._touchBeginWithSelf = false;
            this.changeTexture(STATUS$1.UP);
            return _super.prototype.onGlobalTouchEnd.call(this, e);
        };
        Button.prototype.changeTexture = function (status) {
            if (!this._bgRenderer) {
                return;
            }
            var res, labelColor;
            switch (status) {
                case STATUS$1.UP:
                    res = this.upRes;
                    labelColor = this.upLabelColor;
                    break;
                case STATUS$1.DOWN:
                    res = this.downRes;
                    labelColor = this.downLabelColor;
                    break;
                case STATUS$1.DISABLED:
                    res = this.disabledRes;
                    labelColor = this.disabledLabelColor;
                    break;
            }
            var currentRes = res || this.upRes;
            var currentColor = labelColor || this.upLabelColor;
            if (this.interactable) {
                this._bgRenderer.texture = currentRes;
                if (this._label) {
                    this._label.fillColor = currentColor;
                }
            }
            else {
                this._bgRenderer.texture = this.disabledRes;
                if (this._label) {
                    this._label.fillColor = this.disabledLabelColor;
                }
            }
        };
        __decorate([
            dirtyFieldDetector$8
        ], Button.prototype, "upRes", void 0);
        __decorate([
            dirtyFieldDetector$8
        ], Button.prototype, "downRes", void 0);
        __decorate([
            dirtyFieldDetector$8
        ], Button.prototype, "disabledRes", void 0);
        __decorate([
            dirtyFieldDetector$8
        ], Button.prototype, "Label", void 0);
        __decorate([
            dirtyFieldDetector$8
        ], Button.prototype, "upLabelColor", void 0);
        __decorate([
            dirtyFieldDetector$8
        ], Button.prototype, "downLabelColor", void 0);
        __decorate([
            dirtyFieldDetector$8
        ], Button.prototype, "disabledLabelColor", void 0);
        return Button;
    }(InteractComponent));

    var FullStageSize = (function (_super) {
        __extends(FullStageSize, _super);
        function FullStageSize() {
            var _this = _super !== null && _super.apply(this, arguments) || this;
            _this.once = true;
            _this.applyWidth = true;
            _this.applyHeight = true;
            return _this;
        }
        Object.defineProperty(FullStageSize.prototype, "stageSize", {
            get: function () {
                if (!this._stageSize) {
                    this._stageSize = engine.renderContext.stageSize;
                }
                return this._stageSize;
            },
            enumerable: true,
            configurable: true
        });
        FullStageSize.prototype.onCreate = function () {
            _super.prototype.onCreate.call(this);
        };
        FullStageSize.prototype.onAwake = function () {
            _super.prototype.onAwake.call(this);
            this.execute();
        };
        FullStageSize.prototype.onUpdate = function (t) {
            _super.prototype.onUpdate.call(this, t);
            if (!this.once) {
                this.execute();
            }
        };
        FullStageSize.prototype.onEditorUpdate = function (t) {
            _super.prototype.onEditorUpdate.call(this, t);
            this.execute();
        };
        FullStageSize.prototype.execute = function () {
            var _a = this.stageSize, width = _a.width, height = _a.height;
            if (this.applyWidth) {
                this.transform.width = width;
            }
            if (this.applyHeight) {
                this.transform.height = height;
            }
        };
        return FullStageSize;
    }(ScillaComponent));

    var LockingType;
    (function (LockingType) {
        LockingType[LockingType["NOSET"] = 0] = "NOSET";
        LockingType[LockingType["HORIZON"] = 1] = "HORIZON";
        LockingType[LockingType["VERTICAL"] = 2] = "VERTICAL";
    })(LockingType || (LockingType = {}));
    var ScrollView = (function (_super) {
        __extends(ScrollView, _super);
        function ScrollView() {
            var _this = _super !== null && _super.apply(this, arguments) || this;
            _this.lockingType = LockingType.NOSET;
            _this._lastPos = createVector2D();
            _this._speed = createVector2D();
            _this.updatePosOffset = function () {
                var _a = _this._contentTransform.position, x = _a.x, y = _a.y;
                _this._posOffset = { x: x, y: y };
            };
            _this.updatePosRange = function () {
                var _a = _this._viewportTransform, pWidth = _a.width, pHeight = _a.height;
                var _b = _this._contentTransform, width = _b.width, height = _b.height;
                _this._posRange = new Size(pWidth - width, pHeight - height);
            };
            return _this;
        }
        ScrollView.prototype.onAwake = function () {
            _super.prototype.onAwake.call(this);
            this._contentTransform = this.content.getComponent(Transform);
            this._viewportTransform = this.viewport.getComponent(Transform);
            this.callOnNextTick(this.updatePosOffset);
        };
        ScrollView.prototype.onTouchBegin = function (e) {
            _super.prototype.onTouchBegin.call(this, e);
            this.updatePosRange();
            var tx = e.x, ty = e.y;
            var _a = this._contentTransform.position, cx = _a.x, cy = _a.y;
            this._beginPos = {
                tx: tx,
                ty: ty,
                cx: cx,
                cy: cy,
            };
            this._lastPos.setXY(tx, ty);
        };
        ScrollView.prototype.onGlobalTouchMove = function (e) {
            _super.prototype.onGlobalTouchMove.call(this, e);
            if (!this._beginPos) {
                return;
            }
            var _a = this, _b = _a._beginPos, tx = _b.tx, ty = _b.ty, cx = _b.cx, cy = _b.cy, _c = _a._posOffset, offX = _c.x, offY = _c.y, position = _a._contentTransform.position, lockingType = _a.lockingType;
            var x = e.x, y = e.y;
            var px = x - tx + cx;
            var py = y - ty + cy;
            var _d = this._posRange, rWidth = _d.width, rHeight = _d.height;
            var halfWidth = Math.abs(rWidth / 2);
            var paddingX = halfWidth - Math.abs(offX - halfWidth - px);
            if (paddingX < 0) {
                px += paddingX * 0.8 * (x - tx > 0 ? 1 : -1);
            }
            var halfHeight = Math.abs(rHeight / 2);
            var paddingY = halfHeight - Math.abs(offY - halfHeight - py);
            if (paddingY < 0) {
                py += paddingY * 0.8 * (y - ty > 0 ? 1 : -1);
            }
            switch (lockingType) {
                case LockingType.HORIZON:
                    position.y = py;
                    break;
                case LockingType.VERTICAL:
                    position.x = px;
                    break;
                default:
                    position.setXY(px, py);
            }
            this._speed.copyFrom(this._lastPos.subtract({ x: x, y: y }));
            this._lastPos.setXY(x, y);
        };
        ScrollView.prototype.onGlobalTouchEnd = function (e) {
            _super.prototype.onGlobalTouchEnd.call(this, e);
            if (!this._beginPos) {
                return;
            }
            this._beginPos = null;
            var _a = this._posOffset, offX = _a.x, offY = _a.y;
            var _b = this._posRange, rWidth = _b.width, rHeight = _b.height;
            var _c = this._contentTransform, position = _c.position, _d = _c.position, x = _d.x, y = _d.y;
            var tx = Math.min(Math.max(offX + rWidth, x), offX);
            var ty = Math.min(Math.max(offY + rHeight, y), offY);
            var targetPos = createVector2D(tx, ty);
            var duration = Math.min(500, Math.max(targetPos.distance(position), 200));
            createTween(this, this._contentTransform, true, { fields: ['x', 'y'] })
                .to({ position: targetPos }, duration, cubicOut);
        };
        return ScrollView;
    }(InteractComponent));

    var RelativeLayout = (function (_super) {
        __extends(RelativeLayout, _super);
        function RelativeLayout() {
            var _this = _super !== null && _super.apply(this, arguments) || this;
            _this.left = NaN;
            _this.right = NaN;
            _this.top = NaN;
            _this.bottom = NaN;
            _this.horizontalCenter = NaN;
            _this.verticalCenter = NaN;
            _this.once = true;
            _this.adjust = function () {
                var e_1, _a, e_2, _b, e_3, _c;
                var _d = _this, entity = _d.entity, parent = _d.entity.parent, transform = _d.transform, _e = _d.transform, position = _e.position, _f = _e.pivot, ax = _f.x, ay = _f.y, left = _d.left, right = _d.right, top = _d.top, bottom = _d.bottom, horizontalCenter = _d.horizontalCenter, verticalCenter = _d.verticalCenter;
                var hasLeft = !isNaN(left);
                var hasRight = !isNaN(right);
                var hasTop = !isNaN(top);
                var hasBottom = !isNaN(bottom);
                var hasHorizontalCenter = !isNaN(horizontalCenter);
                var hasVerticalCenter = !isNaN(verticalCenter);
                var parentRenderers = parent.getComponents(Renderer);
                try {
                    for (var parentRenderers_1 = __values(parentRenderers), parentRenderers_1_1 = parentRenderers_1.next(); !parentRenderers_1_1.done; parentRenderers_1_1 = parentRenderers_1.next()) {
                        var parentRenderer = parentRenderers_1_1.value;
                        parentRenderer.measureBounds();
                    }
                }
                catch (e_1_1) { e_1 = { error: e_1_1 }; }
                finally {
                    try {
                        if (parentRenderers_1_1 && !parentRenderers_1_1.done && (_a = parentRenderers_1.return)) _a.call(parentRenderers_1);
                    }
                    finally { if (e_1) throw e_1.error; }
                }
                var parentTransform = parent.getComponent(Transform);
                var pWidth, pHeight;
                if (parentRenderers.length > 0) {
                    var parentBounds = parentRenderers[0].bounds;
                    pWidth = parentBounds.width;
                    pHeight = parentBounds.height;
                }
                else {
                    pWidth = parentTransform.explicitWidth;
                    pHeight = parentTransform.explicitHeight;
                }
                var _g = parentTransform.pivot, pax = _g.x, pay = _g.y;
                var renderers = entity.getComponents(Renderer);
                try {
                    for (var renderers_1 = __values(renderers), renderers_1_1 = renderers_1.next(); !renderers_1_1.done; renderers_1_1 = renderers_1.next()) {
                        var renderer = renderers_1_1.value;
                        renderer.measureBounds();
                    }
                }
                catch (e_2_1) { e_2 = { error: e_2_1 }; }
                finally {
                    try {
                        if (renderers_1_1 && !renderers_1_1.done && (_b = renderers_1.return)) _b.call(renderers_1);
                    }
                    finally { if (e_2) throw e_2.error; }
                }
                var width = transform.width, height = transform.height;
                var x = position.x, y = position.y;
                var widthModified = false, heightModified = false;
                {
                    if (hasHorizontalCenter) {
                        x = (pWidth - width) / 2 - pWidth * pax + width * ax;
                    }
                    else if (hasLeft) {
                        if (hasRight) {
                            widthModified = true;
                            width = pWidth - right - left;
                            x = (left - right) / 2 - (0.5 - ax) * width;
                        }
                        else {
                            x = left - pWidth * 0.5 + width * ax;
                        }
                    }
                    else if (hasRight) {
                        x = -right + pWidth * 0.5 - width * (1 - ax);
                    }
                    if (hasVerticalCenter) {
                        y = (pHeight - height) / 2 - pHeight * pay + height * ay;
                    }
                    else if (hasTop) {
                        if (hasBottom) {
                            heightModified = true;
                            height = pHeight - bottom - top;
                            y = (top - bottom) / 2 - (0.5 - ay) * height;
                        }
                        else {
                            y = top - pHeight * 0.5 + height * ay;
                        }
                    }
                    else if (hasBottom) {
                        y = -bottom + pHeight * 0.5 - height * (1 - ay);
                    }
                }
                position.x = x;
                position.y = y;
                if (widthModified) {
                    transform.width = width;
                }
                if (heightModified) {
                    transform.height = height;
                }
                if (widthModified || heightModified) {
                    try {
                        for (var renderers_2 = __values(renderers), renderers_2_1 = renderers_2.next(); !renderers_2_1.done; renderers_2_1 = renderers_2.next()) {
                            var renderer = renderers_2_1.value;
                            renderer.measureBounds();
                        }
                    }
                    catch (e_3_1) { e_3 = { error: e_3_1 }; }
                    finally {
                        try {
                            if (renderers_2_1 && !renderers_2_1.done && (_c = renderers_2.return)) _c.call(renderers_2);
                        }
                        finally { if (e_3) throw e_3.error; }
                    }
                }
            };
            return _this;
        }
        RelativeLayout.prototype.onCreate = function () {
            _super.prototype.onCreate.call(this);
        };
        RelativeLayout.prototype.onAwake = function () {
            _super.prototype.onAwake.call(this);
            this.adjust();
        };
        RelativeLayout.prototype.onUpdate = function (t) {
            _super.prototype.onUpdate.call(this, t);
            if (!this.once) {
                this.adjust();
            }
        };
        RelativeLayout.prototype.onEditorUpdate = function (t) {
            this.adjust();
        };
        RelativeLayout.prototype.onSleep = function () {
            _super.prototype.onSleep.call(this);
        };
        RelativeLayout.prototype.onDestroy = function () {
            _super.prototype.onDestroy.call(this);
        };
        return RelativeLayout;
    }(ScillaComponent));

    var Translation = (function (_super) {
        __extends(Translation, _super);
        function Translation() {
            var _this = _super !== null && _super.apply(this, arguments) || this;
            _this.duration = 1000;
            _this.autoPlay = false;
            _this.easeName = Ease.linear;
            _this.delay = 0;
            _this.loop = -1;
            _this.onLoopComplete = new ScillaEvent();
            _this.onComplete = new ScillaEvent();
            _this._onLoopComplete = function () {
                _this.onLoopComplete.invoke();
            };
            _this._onComplete = function () {
                _this.onComplete.invoke();
            };
            return _this;
        }
        Translation.prototype.onAwake = function () {
            _super.prototype.onAwake.call(this);
            if (this.autoPlay) {
                this.play();
            }
        };
        Translation.prototype.play = function () {
            var easeFunc = ease[this.easeName];
            this._tween = createTween(this, this.transform, false, { autoPlay: true, loop: this.loop, onLoopComplete: this._onLoopComplete, onComplete: this._onComplete })
                .set(this.getFromProp(), true)
                .wait(this.delay)
                .to(this.getToProp(), this.duration, easeFunc);
        };
        Translation.prototype.stop = function () {
            this._tween.stop();
        };
        Translation.prototype.getFromProp = function () {
            return {};
        };
        Translation.prototype.getToProp = function () {
            return {};
        };
        return Translation;
    }(ScillaComponent));

    var Fade = (function (_super) {
        __extends(Fade, _super);
        function Fade() {
            var _this = _super !== null && _super.apply(this, arguments) || this;
            _this.fromAlpha = 0;
            _this.toAlpha = 1;
            return _this;
        }
        Fade.prototype.getFromProp = function () {
            return {
                alpha: this.fromAlpha
            };
        };
        Fade.prototype.getToProp = function () {
            return {
                alpha: this.toAlpha
            };
        };
        return Fade;
    }(Translation));

    var Zoom = (function (_super) {
        __extends(Zoom, _super);
        function Zoom() {
            var _this = _super !== null && _super.apply(this, arguments) || this;
            _this.fromScale = new Vector2D(0, 0);
            _this.toScale = new Vector2D(1, 1);
            return _this;
        }
        Zoom.prototype.getFromProp = function () {
            return {
                scale: this.fromScale ? this.fromScale.toObj() : null
            };
        };
        Zoom.prototype.getToProp = function () {
            return {
                scale: this.toScale ? this.toScale.toObj() : null
            };
        };
        return Zoom;
    }(Translation));

    var PI2 = Math.PI * 2;
    var dirtyFieldTrigger$5 = dirtyFieldTrigger;
    var oldPropFields = {
        position: ['x', 'y'],
        scale: ['x', 'y'],
        alpha: 'alpha',
        rotation: 'rotation',
    };
    var Wave = (function (_super) {
        __extends(Wave, _super);
        function Wave() {
            var _this = _super !== null && _super.apply(this, arguments) || this;
            _this.duration = 1000;
            _this.loop = -1;
            _this.autoPlay = true;
            _this.onComplete = new ScillaEvent();
            _this.onLoopComplete = new ScillaEvent();
            _this._oldProps = {};
            return _this;
        }
        Object.defineProperty(Wave.prototype, "waveAlgorithm", {
            get: function () {
                return this._waveAlgorithm;
            },
            set: function (v) {
                this._waveAlgorithm = v;
            },
            enumerable: true,
            configurable: true
        });
        Wave.prototype.onModify = function (value, key, oldValue) {
            _super.prototype.onModify.call(this, value, key, oldValue);
            switch (key) {
                case 'waveMethod':
                    this._waveAlgorithm = waveLibs[this.waveMethod];
                    break;
            }
        };
        Wave.prototype.onAwake = function () {
            _super.prototype.onAwake.call(this);
            this._startTime = 0;
            copyProp(this._oldProps, this.transform, oldPropFields);
            if (this.autoPlay) {
                this.play();
            }
        };
        Wave.prototype.onUpdate = function (t) {
            _super.prototype.onUpdate.call(this, t);
            if (this._playing) {
                if (!this._startTime) {
                    this._startTime = t;
                }
                var _a = this, duration = _a.duration, waveParams = _a.waveParams, _waveAlgorithm = _a._waveAlgorithm, transform = _a.transform, _b = _a.transform, position = _b.position, scale = _b.scale, _oldProps = _a._oldProps;
                var pass = (t - this._startTime) % duration;
                var r = pass / duration * PI2;
                var loopCounting = Math.floor((t - this._startTime) / duration);
                if (loopCounting != this._loopCounting) {
                    this._loopCounting = loopCounting;
                    if (this.onLoopEnd()) {
                        r = PI2;
                    }
                }
                var params = waveParams || [];
                var props = _waveAlgorithm.apply(void 0, __spread(params, [r]));
                if (props.hasOwnProperty('x')) {
                    position.x = (props.x || 0) + _oldProps.position.x;
                }
                if (props.hasOwnProperty('y')) {
                    position.y = (props.y || 0) + _oldProps.position.y;
                }
                if (props.hasOwnProperty('sx')) {
                    scale.x = props.sx;
                }
                if (props.hasOwnProperty('sy')) {
                    scale.y = props.sy;
                }
                if (props.hasOwnProperty('r')) {
                    transform.rotation = props.r;
                }
            }
        };
        Wave.prototype.onLoopEnd = function () {
            if (this.loop < 0) {
                this.onLoopComplete.invoke();
            }
            else if (this._loopCounting < this.loop) {
                this.onLoopComplete.invoke();
            }
            else {
                this._playing = false;
                this.onComplete.invoke();
                return true;
            }
        };
        Wave.prototype.play = function () {
            this._loopCounting = 0;
            this._playing = true;
            this._startTime = 0;
        };
        Wave.prototype.stop = function (revert) {
            if (revert === void 0) { revert = false; }
            this._playing = false;
            if (revert) {
                for (var key in this._oldProps) {
                    var prop = this._oldProps[key];
                    if (typeof prop === 'object') {
                        injectProp(this.transform[key], prop);
                    }
                    else {
                        this.transform[key] = prop;
                    }
                }
            }
        };
        __decorate([
            dirtyFieldTrigger$5
        ], Wave.prototype, "waveMethod", void 0);
        return Wave;
    }(ScillaComponent));
    var WaveMethod;
    (function (WaveMethod) {
        WaveMethod["round"] = "round";
        WaveMethod["rotate"] = "rotate";
        WaveMethod["zoom"] = "zoom";
        WaveMethod["fade"] = "fade";
        WaveMethod["cosWave"] = "cosWave";
        WaveMethod["sinWave"] = "sinWave";
        WaveMethod["shake"] = "shake";
        WaveMethod["breath"] = "breath";
    })(WaveMethod || (WaveMethod = {}));
    var cos = Math.cos, sin = Math.sin, PI$1 = Math.PI;
    var waveLibs = {
        round: function (radius, t) {
            return { x: cos(t) * radius, y: sin(t) * radius };
        },
        cosWave: function (h, t) {
            return { x: cos(t) * h, y: 0 };
        },
        sinWave: function (h, t) {
            h = h || 1;
            return { x: 0, y: sin(t) * h };
        },
        rotate: function (t) {
            return { r: 360 * t / PI$1 / 2 };
        },
        shake: function (angle, count, t) {
            return { r: sin(t * count) * angle };
        },
        breath: function (scale, t) {
            if (scale === void 0) { scale = 0.1; }
            return { sx: sin(t) * scale + 1, sy: -sin(t + PI$1 / 4) * scale + 1 };
        },
        zoom: function (scale, t) {
            if (scale === void 0) { scale = 0.1; }
            return { sx: sin(t) * scale + 1, sy: sin(t) * scale + 1 };
        },
        fade: function (base, t) {
            if (base === void 0) { base = 1; }
            return { alpha: (sin(t) + 1) * 0.5 + base };
        },
    };

    var ContentSizeFitter = (function (_super) {
        __extends(ContentSizeFitter, _super);
        function ContentSizeFitter() {
            var _this = _super !== null && _super.apply(this, arguments) || this;
            _this._measureSize = new Size();
            return _this;
        }
        ContentSizeFitter.prototype.afterUpdate = function () {
            var e_1, _a;
            _super.prototype.afterUpdate.call(this);
            var measureSize = this._measureSize;
            measureSize.set(0, 0);
            try {
                for (var _b = __values(this.entity.children), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var child = _c.value;
                    var transform = child.getComponent(Transform);
                    if (transform) {
                        var width = transform.width, height = transform.height, pivot = transform.pivot;
                        measureSize.width += width;
                        measureSize.height += height;
                    }
                }
            }
            catch (e_1_1) { e_1 = { error: e_1_1 }; }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
                }
                finally { if (e_1) throw e_1.error; }
            }
            this.transform.width = measureSize.width;
            this.transform.height = measureSize.height;
        };
        return ContentSizeFitter;
    }(ScillaComponent));

    var dirtyFieldTrigger$6 = dirtyFieldTrigger;
    function renderLabelFuncSample(value, maximum, minimum) {
        return Math.floor(value / (maximum - minimum) * 100) + '%';
    }
    var ProgressBar = (function (_super) {
        __extends(ProgressBar, _super);
        function ProgressBar() {
            var _this = _super !== null && _super.apply(this, arguments) || this;
            _this.value = 0;
            _this.minimum = 0;
            _this.maximum = 0;
            _this.snapInterval = 1;
            _this.fixWithRange = true;
            _this.updateThumbSize = function () {
                var _a = _this.thumb.getComponent(Transform), width = _a.width, height = _a.height;
                _this._thumbSize = { width: width, height: height };
                _this.update();
            };
            return _this;
        }
        ProgressBar.prototype.onCreate = function () {
            _super.prototype.onCreate.call(this);
            this.renderLabelFunc = renderLabelFuncSample;
        };
        ProgressBar.prototype.onAwake = function () {
            _super.prototype.onAwake.call(this);
            this._mask = this.viewport.getComponent(RectRenderer);
            this._mask.width = 0;
            if (this.widget) {
                this._widgetTransform = this.widget.getComponent(Transform);
            }
            this._label = this.label.getComponent(TextRenderer);
            this.callOnNextTick(this.updateThumbSize);
        };
        ProgressBar.prototype.onModify = function (value, key, oldValue) {
            _super.prototype.onModify.call(this, value, key, oldValue);
            if (oldValue === undefined) {
                return;
            }
            this.callOnNextTick(this.update);
        };
        ProgressBar.prototype.update = function () {
            var _a = this, minimum = _a.minimum, maximum = _a.maximum, _thumbSize = _a._thumbSize;
            if (!_thumbSize) {
                return;
            }
            var range = maximum - minimum;
            var value = Math.max(minimum, Math.min(maximum, this.value));
            var percentage = (value - minimum) / range;
            var width = percentage * _thumbSize.width;
            createTween(this, this._mask, true)
                .to({ width: width }, 300, cubicOut);
            if (this._widgetTransform) {
                this._widgetTransform.position.x = width;
            }
            var renderValue = this.fixWithRange ? Math.max(minimum, Math.min(maximum, this.value)) : this.value;
            this.value = value;
            if (this._label) {
                var text = this.renderLabelFunc(renderValue, this.maximum, this.minimum);
                if (typeof text == 'string') {
                    this._label.text = text;
                    this._label.textFlow = null;
                }
                else {
                    this._label.textFlow = text;
                    this._label.updateTextFlow();
                }
            }
        };
        __decorate([
            dirtyFieldTrigger$6
        ], ProgressBar.prototype, "value", void 0);
        __decorate([
            dirtyFieldTrigger$6
        ], ProgressBar.prototype, "minimum", void 0);
        __decorate([
            dirtyFieldTrigger$6
        ], ProgressBar.prototype, "maximum", void 0);
        __decorate([
            dirtyFieldTrigger$6
        ], ProgressBar.prototype, "snapInterval", void 0);
        __decorate([
            dirtyFieldTrigger$6
        ], ProgressBar.prototype, "renderLabelFunc", void 0);
        __decorate([
            dirtyFieldTrigger$6
        ], ProgressBar.prototype, "fixWithRange", void 0);
        return ProgressBar;
    }(ScillaComponent));

    var registerDef = engine.registerDef.bind(engine);

    var setX = function (entity, x) {
        entity.getComponent(Transform).position.x = x;
    };
    var setRotation = function (entity, x) {
        entity.getComponent(Transform).rotation = x;
    };
    var getRotation = function (entity) {
        return entity.getComponent(Transform).rotation;
    };
    var setScale = function (val, sacle) {
        if (val instanceof Entity) {
            val.getComponent(Transform).scale.x = sacle;
            val.getComponent(Transform).scale.y = sacle;
        }
        else if (val instanceof ScillaComponent) {
            val.entity.getComponent(Transform).scale.x = sacle;
            val.entity.getComponent(Transform).scale.y = sacle;
        }
    };
    var setText = function (entity, text) {
        entity.getComponent(TextRenderer).text = text + '';
    };
    var setY = function (entity, y) {
        entity.getComponent(Transform).position.y = y;
    };
    var getX = function (val) {
        var entity;
        if (val instanceof Entity)
            entity = val;
        else
            entity = val.entity;
        return entity.getComponent(Transform).position.x;
    };
    var getY = function (val) {
        var entity;
        if (val instanceof Entity)
            entity = val;
        else
            entity = val.entity;
        return entity.getComponent(Transform).position.y;
    };
    var setXY = function (val, x, y) {
        var entity;
        if (val instanceof Entity)
            entity = val;
        else
            entity = val.entity;
        setX(entity, x);
        setY(entity, y);
    };

    var Rotation = (function (_super) {
        __extends(Rotation, _super);
        function Rotation() {
            var _this = _super !== null && _super.apply(this, arguments) || this;
            _this.speed = .5;
            return _this;
        }
        Rotation.prototype.onAwake = function () {
            _super.prototype.onAwake.call(this);
        };
        Rotation.prototype.onUpdate = function (t) {
            _super.prototype.onUpdate.call(this, t);
            setRotation(this.entity, getRotation(this.entity) - this.speed);
        };
        return Rotation;
    }(ScillaComponent));

    var setText$1 = function (entity, text) {
        entity.getComponent(TextRenderer).text = text + '';
    };

    var getTween = function (context, val, obj, duration, ease) {
        return new Promise(function (r) {
            var target;
            if (val instanceof Transform) {
                target = val;
            }
            else {
                target = val.getComponent(Transform);
            }
            var postionObj = {};
            for (var key in obj) {
                if (key == 'x' || key == 'y') {
                    postionObj[key] = obj[key];
                    delete obj[key];
                }
            }
            var scaleObj = {};
            for (var key in obj) {
                if (key == 'scalex') {
                    scaleObj['x'] = obj[key];
                    delete obj[key];
                }
                if (key == 'scaley') {
                    scaleObj['y'] = obj[key];
                    delete obj[key];
                }
            }
            createTween(context, target.position, true).to(postionObj, duration, ease);
            createTween(context, target.scale, true).to(scaleObj, duration, ease);
            createTween(context, target, true).to(obj, duration, ease).call(r);
        });
    };

    var ScenePlay = (function (_super) {
        __extends(ScenePlay, _super);
        function ScenePlay() {
            var _this_1 = _super !== null && _super.apply(this, arguments) || this;
            _this_1.COUNT_DOWN_SEC = window['COUNT_DOWN_SEC'];
            _this_1._startTag = false;
            _this_1._msPassed = 0;
            _this_1._ballCounter = 0;
            _this_1._balllist = [];
            return _this_1;
        }
        ScenePlay.prototype.onAwake = function () {
            var _this_1 = this;
            _super.prototype.onAwake.call(this);
            this.showBox1();
            this.initText();
            this.play321Countdown();
            var addCounter = 0;
            var add = function () {
                addCounter++;
                _this_1.addBall();
            };
            setInterval(function () {
                console.log('上一秒摇晃的能量是', addCounter);
                addCounter = 0;
            }, 1000);
            if (window['DeviceMotionEvent']) {
                window.addEventListener('devicemotion', deviceMotionHandler, false);
            }
            var SHAKE_THRESHOLD = 50;
            var x, y, z, last_x = 0, last_y = 0, last_z = 0;
            var speedCounter = 0;
            var _this = this;
            function deviceMotionHandler(eventData) {
                if (!_this._startTag)
                    return;
                var acceleration = eventData.accelerationIncludingGravity;
                x = acceleration.x;
                y = acceleration.y;
                z = acceleration.z;
                var speed = Math.abs(x + y + z - last_x - last_y - last_z) * 1;
                speedCounter += speed;
                if (speedCounter >= SHAKE_THRESHOLD) {
                    speedCounter = 0;
                    add();
                }
                last_x = x;
                last_y = y;
                last_z = z;
            }
            this._startTag = false;
        };
        ScenePlay.prototype.wait = function (ms) {
            return __awaiter(this, void 0, void 0, function () {
                return __generator(this, function (_a) {
                    return [2, new Promise(function (r) {
                            setTimeout(r, ms);
                        })];
                });
            });
        };
        ScenePlay.prototype.play321Countdown = function () {
            return __awaiter(this, void 0, void 0, function () {
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            setScale(this.num1, 3);
                            setScale(this.num2, 3);
                            setScale(this.num3, 3);
                            this.num1.enabled = false;
                            this.num2.enabled = false;
                            this.num3.enabled = true;
                            return [4, getTween(this, this.num3, { scalex: 1, scaley: 1 }, 300)];
                        case 1:
                            _a.sent();
                            return [4, this.wait(600)];
                        case 2:
                            _a.sent();
                            this.num3.enabled = false;
                            this.num2.enabled = true;
                            return [4, getTween(this, this.num2, { scalex: 1, scaley: 1 }, 300)];
                        case 3:
                            _a.sent();
                            return [4, this.wait(600)];
                        case 4:
                            _a.sent();
                            this.num2.enabled = false;
                            this.num1.enabled = true;
                            return [4, getTween(this, this.num1, { scalex: 1, scaley: 1 }, 300)];
                        case 5:
                            _a.sent();
                            return [4, this.wait(600)];
                        case 6:
                            _a.sent();
                            this.num1.enabled = false;
                            this.startRealCountdown();
                            return [2];
                    }
                });
            });
        };
        ScenePlay.prototype.startRealCountdown = function () {
            this._startTag = true;
            this._msPassed = 0;
            this._lastTimer = Date.now();
            this._ballCounter = 0;
        };
        ScenePlay.prototype.onUpdate = function () {
            if (!this._startTag)
                return;
            this._msPassed += (Date.now() - this._lastTimer);
            var left = this.COUNT_DOWN_SEC * 1000 - this._msPassed;
            var mPassed = Math.floor(left / 1000);
            var msPassed = left % 1000;
            msPassed = Math.floor(msPassed / 10);
            this.updateText(mPassed, msPassed);
            this._lastTimer = Date.now();
            if (left <= 0) {
                this.updateText(0, 0);
                this._startTag = false;
                this.onTimerout();
            }
        };
        ScenePlay.prototype.onTimerout = function () {
            console.log('onTimerout');
            this.broadcast('callApi', 1, 'activitySubmit', {
                weddingId: window['CFG'].weddingId,
                activityId: window['CFG'].activityId,
                orderId: this.doJoin.orderId,
                score: this._ballCounter
            });
        };
        ScenePlay.prototype.onRespone_activitySubmit = function () {
            this.bubbling('showDialog', 'Score', this._ballCounter);
        };
        ScenePlay.prototype.onError_activitySubmit = function (error) {
            this.bubbling('showDialog', 'Alert', '网络异常，请稍后再试~');
        };
        ScenePlay.prototype.getNumber = function (num) {
            if (num < 10)
                return "0" + num;
            return "" + num;
        };
        ScenePlay.prototype.updateText = function (a, b) {
            setText$1(this.countTxt, this.getNumber(a) + "." + this.getNumber(b) + "s");
        };
        ScenePlay.prototype.initText = function () {
            setText$1(this.countTxt, this.getNumber(this.COUNT_DOWN_SEC) + ".00s");
        };
        ScenePlay.prototype.addBall = function () {
            this._ballCounter++;
            var iocn = instantiate(this.iconResource);
            this.entity.addChild(iocn);
            this._balllist.push(iocn);
            if (this._ballCounter > 100 / (16 / this.COUNT_DOWN_SEC)) {
                this.showBox3();
            }
            else if (this._ballCounter > 50 / (16 / this.COUNT_DOWN_SEC)) {
                this.showBox2();
            }
            else {
                this.showBox1();
            }
        };
        ScenePlay.prototype.showBox1 = function () {
            this.box1.enabled = true;
            this.box2.enabled = false;
            this.box3.enabled = false;
        };
        ScenePlay.prototype.showBox2 = function () {
            this.box1.enabled = false;
            this.box2.enabled = true;
            this.box3.enabled = false;
        };
        ScenePlay.prototype.showBox3 = function () {
            this.box1.enabled = false;
            this.box2.enabled = false;
            this.box3.enabled = true;
        };
        ScenePlay.prototype.onDidEnter = function (last, action, parameters) {
            this.entity.enabled = true;
        };
        ScenePlay.prototype.onDidLeave = function (next, action, parameters) {
            var _this_1 = this;
            this._balllist.forEach(function (iocn) { return _this_1.entity.removeChild(iocn); });
            this._balllist = [];
            this.entity.enabled = false;
        };
        ScenePlay.prototype.onWillEnter = function (last, action, parameters) {
            return __awaiter(this, void 0, void 0, function () {
                return __generator(this, function (_a) {
                    return [2];
                });
            });
        };
        ScenePlay.prototype.onWillLeave = function (next, action, parameters) {
            return __awaiter(this, void 0, void 0, function () {
                return __generator(this, function (_a) {
                    return [2];
                });
            });
        };
        ScenePlay.prototype.onWillMount = function (last, action, parameters) {
            return undefined;
        };
        ScenePlay.prototype.onWillUnMount = function (next, action, parameters) {
            return undefined;
        };
        return ScenePlay;
    }(ScillaComponent));

    var SceneGuide = (function (_super) {
        __extends(SceneGuide, _super);
        function SceneGuide() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        SceneGuide.prototype.onAwake = function () {
            _super.prototype.onAwake.call(this);
        };
        SceneGuide.prototype.onGlobalTouchBegin = function (e) {
            _super.prototype.onGlobalTouchBegin.call(this, e);
            this.onNextScene();
            return false;
        };
        SceneGuide.prototype.onNextScene = function () {
            this.bubbling('fuck', 'play');
        };
        SceneGuide.prototype.onDidEnter = function (last, action, parameters) {
            this.entity.enabled = true;
        };
        SceneGuide.prototype.onDidLeave = function (next, action, parameters) {
            this.entity.enabled = false;
        };
        SceneGuide.prototype.onWillEnter = function (last, action, parameters) {
            return __awaiter(this, void 0, void 0, function () {
                return __generator(this, function (_a) {
                    return [2];
                });
            });
        };
        SceneGuide.prototype.onWillLeave = function (next, action, parameters) {
            return __awaiter(this, void 0, void 0, function () {
                return __generator(this, function (_a) {
                    return [2];
                });
            });
        };
        SceneGuide.prototype.onWillMount = function (last, action, parameters) {
            return undefined;
        };
        SceneGuide.prototype.onWillUnMount = function (next, action, parameters) {
            return undefined;
        };
        return SceneGuide;
    }(InteractComponent));

    var RankItem = (function (_super) {
        __extends(RankItem, _super);
        function RankItem() {
            var _this = _super !== null && _super.apply(this, arguments) || this;
            _this.loadImage = function (url) {
                return new Promise(function (resolve, reject) {
                    var img = new Image();
                    if (EngineConfig.imgCrossOrigin) {
                        img.setAttribute('crossOrigin', 'anonymous');
                    }
                    img.onload = function (e) {
                        resolve(img);
                    };
                    img.onerror = function (e) {
                        reject(e);
                    };
                    img.src = url;
                });
            };
            _this.loadTexture = function (url) { return __awaiter(_this, void 0, Promise, function () {
                var img, texture;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0: return [4, this.loadImage(url)];
                        case 1:
                            img = _a.sent();
                            texture = createTexture(img);
                            return [2, texture];
                    }
                });
            }); };
            return _this;
        }
        RankItem.prototype.onAwake = function () {
            _super.prototype.onAwake.call(this);
        };
        RankItem.prototype.setdata = function (data) {
            return __awaiter(this, void 0, void 0, function () {
                var texRender, texture;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            setText$1(this.score, data.score + '');
                            setText$1(this.rank, data.rank);
                            setText$1(this.name, data.nickName);
                            texRender = this.avatar.getComponent(TextureRenderer);
                            return [4, this.loadTexture(data.avatar)];
                        case 1:
                            texture = _a.sent();
                            texRender.texture = texture;
                            setScale(this.avatar, 40 / texture.bounds.width);
                            return [2];
                    }
                });
            });
        };
        RankItem.prototype.onUpdate = function (t) {
            _super.prototype.onUpdate.call(this, t);
        };
        return RankItem;
    }(ScillaComponent));

    function bearingsToOutPos(bearings) {
        var _a = engine.renderContext.stageSize, width = _a.width, height = _a.height;
        var x, y;
        switch (bearings) {
            case 'south':
                x = 0;
                y = height / 2;
                break;
            case 'west':
                x = -width / 2;
                y = 0;
                break;
            case 'east':
                x = width / 2;
                y = 0;
                break;
            case 'north':
            default:
                x = 0;
                y = -height / 2;
        }
        return {
            x: x, y: y,
        };
    }
    var none = {
        show: function (transform, options) {
            transform.position.setXY(0, 0);
            return Promise.resolve();
        },
        hide: function (transform, options) {
            transform.position.setXY(engine.renderContext.stageSize.width, 0);
            return Promise.resolve();
        }
    };
    var fade = {
        show: function (transform, options) {
            options = options || {};
            transform.alpha = 0;
            var toProps = {
                alpha: 1,
            };
            return new Promise(function (resolve) {
                createTween(transform, transform)
                    .to(toProps, options.duration || 300, options.easeFunc)
                    .call(resolve);
            });
        },
        hide: function (transform, options) {
            options = options || {};
            var toProps = {
                alpha: 0,
            };
            return new Promise(function (resolve) {
                createTween(transform, transform)
                    .to(toProps, options.duration || 200, options.easeFunc)
                    .call(resolve);
            });
        }
    };
    var flew = {
        show: function (transform, options) {
            options = options || {};
            var outPos = bearingsToOutPos(options.bearings);
            transform.position.copyFrom(outPos);
            var toProps = {
                position: { x: 0, y: 0, },
            };
            var withFade = options.hasOwnProperty('withFade') ? options.withFade : false;
            if (withFade) {
                transform.alpha = 0;
                toProps.alpha = 1;
            }
            return new Promise(function (resolve) {
                createTween(transform, transform)
                    .to(toProps, options.duration || 300, options.easeFunc || backOut)
                    .call(resolve);
            });
        },
        hide: function (transform, options) {
            options = options || {};
            var outPos = bearingsToOutPos(options.bearings);
            var toProps = {
                position: outPos,
            };
            var withFade = options.hasOwnProperty('withFade') ? options.withFade : false;
            if (withFade) {
                toProps.alpha = 0;
            }
            return new Promise(function (resolve) {
                createTween(transform, transform)
                    .to(toProps, options.duration || 200, options.easeFunc || backIn)
                    .call(resolve);
            });
        }
    };
    var zoom = {
        show: function (transform, options) {
            options = options || {};
            transform.scale.setXY(0, 0);
            var toProps = {
                scale: { x: 1, y: 1, },
            };
            var withFade = options.hasOwnProperty('withFade') ? options.withFade : false;
            if (withFade) {
                transform.alpha = 0;
                toProps.alpha = 1;
            }
            return new Promise(function (resolve) {
                createTween(transform, transform)
                    .to(toProps, options.duration || 300, options.easeFunc || backOut)
                    .call(resolve);
            });
        },
        hide: function (transform, options) {
            options = options || {};
            var toProps = {
                scale: { x: 0, y: 0 },
            };
            var withFade = options.hasOwnProperty('withFade') ? options.withFade : false;
            if (withFade) {
                toProps.alpha = 0;
            }
            return new Promise(function (resolve) {
                createTween(transform, transform)
                    .to(toProps, options.duration || 200, options.easeFunc || backIn)
                    .call(resolve);
            });
        }
    };

    var dirtyFieldTrigger$7 = dirtyFieldTrigger;
    var DialogContent = (function (_super) {
        __extends(DialogContent, _super);
        function DialogContent() {
            var _this = _super !== null && _super.apply(this, arguments) || this;
            _this.effect = PopupEffect.flew;
            _this.effectImpl = none;
            _this.show = function (data, callback) {
                _this.bubbling('showDialog', _this.entity.name, data, callback);
            };
            _this.hide = function (action) {
                _this.bubbling('hideDialog', _this.entity.name, action || 'close');
            };
            return _this;
        }
        DialogContent.prototype.onModify = function (value, key, oldValue) {
            _super.prototype.onModify.call(this, value, key, oldValue);
            if (key === 'effect') {
                this.effectImpl = effects[value];
            }
        };
        DialogContent.prototype.onAwake = function () {
            var _this = this;
            _super.prototype.onAwake.call(this);
            if (!this._closeButtons) {
                this._closeButtons = [];
                var buttons = this.entity.getChildrenByName('CloseButton');
                if (buttons) {
                    buttons.forEach(function (button) {
                        var closeBtn = button.getComponent(Button);
                        closeBtn.onClick.addListener(_this.onTapCloseButton, _this);
                    });
                }
            }
        };
        DialogContent.prototype.onTapCloseButton = function () {
            this.hide();
        };
        DialogContent.prototype.setup = function (data) {
        };
        __decorate([
            dirtyFieldTrigger$7
        ], DialogContent.prototype, "effect", void 0);
        return DialogContent;
    }(ScillaComponent));
    var effects = {
        none: none,
        fade: fade,
        flew: flew,
        zoom: zoom,
    };
    var PopupEffect;
    (function (PopupEffect) {
        PopupEffect["none"] = "none";
        PopupEffect["fade"] = "fade";
        PopupEffect["flew"] = "flew";
        PopupEffect["zoom"] = "zoom";
    })(PopupEffect || (PopupEffect = {}));

    var ScoreDialogContent = (function (_super) {
        __extends(ScoreDialogContent, _super);
        function ScoreDialogContent() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        ScoreDialogContent.prototype.onAwake = function () {
            _super.prototype.onAwake.call(this);
        };
        ScoreDialogContent.prototype.setup = function (data) {
            if (data === void 0) { data = {}; }
            setText$1(this.content, "\u606D\u559C\u4F60\u5171\u6447\u51FA" + data + "\u4E2A\u798F");
        };
        ScoreDialogContent.prototype.onTapCloseButton = function () {
            _super.prototype.onTapCloseButton.call(this);
            this.bubbling('fuckNavigator', 'start');
        };
        ScoreDialogContent.prototype.onclick_ranbtn = function () {
            this.hide();
            this.bubbling('fuckNavigator', 'start');
            window.location.href = getRankURL();
        };
        return ScoreDialogContent;
    }(DialogContent));
    var getRankURL = function () {
        return "/customActivity/sjf/activity/recordIndex?weddingId=" + window['CFG'].weddingId + "&activityId=" + window['CFG'].activityId + "&brickType=7";
    };
    var getURL = function () {
        return "/customActivity/sjf/mainIndex?weddingId=" + window['CFG'].weddingId;
    };
    var getRecordURL = function () {
        return "/customActivity/sjf/activity/recordIndex?weddingId=" + window['CFG'].weddingId + "&activityId=" + window['CFG'].activityId + "&brickType=6";
    };

    var SceneStart = (function (_super) {
        __extends(SceneStart, _super);
        function SceneStart() {
            var _this = _super !== null && _super.apply(this, arguments) || this;
            _this.INTERVAL = 3000;
            _this.STREN = 3;
            _this.FREQ = 5;
            _this.SHAK_TIMERS = 10;
            _this._shakeTimes = -1;
            _this._counter = -1;
            _this._lastTime = -1;
            return _this;
        }
        SceneStart.prototype.onclick_music = function () {
            this.musicoffbtn.enabled = !this.musicoffbtn.enabled;
            this.musiconbtn.enabled = !this.musiconbtn.enabled;
            if (this.musiconbtn.enabled) {
                document.getElementById('bgmusic')['play']();
            }
            else {
                document.getElementById('bgmusic')['pause']();
            }
        };
        SceneStart.prototype.onUpdate = function () {
            if (Date.now() - this._lastTime > this.INTERVAL) {
                this._lastTime = Date.now();
                setRotation(this.box, this.STREN);
                this._shakeTimes = this.SHAK_TIMERS;
                this._counter = 0;
            }
            if (this._shakeTimes > 0) {
                if (this._counter <= 0) {
                    this._shakeTimes--;
                    setRotation(this.box, -getRotation(this.box));
                    if (this._shakeTimes <= 0) {
                        setRotation(this.box, 0);
                    }
                    this._counter = this.FREQ;
                }
                else {
                    this._counter--;
                }
            }
        };
        SceneStart.prototype.updateCountFromNet = function (limit) {
            if (limit < 0)
                limit = 0;
            setText(this.countTxt, "\u5269\u4F59\u6B21\u6570\uFF1A" + limit);
            console.log('updateCountFromNet', "\u5269\u4F59\u6B21\u6570\uFF1A" + limit);
        };
        SceneStart.prototype.onErrorLimitFree = function (data) {
            console.log('onErrorLimitFree', data);
            if (data == '400005')
                setText(this.countTxt, "\u5269\u4F59\u6B21\u6570\uFF1A" + window['CFG'].freeLimit);
            else
                setText(this.countTxt, "\u5269\u4F59\u6B21\u6570\uFF1A0");
        };
        SceneStart.prototype.updateCountTxtFromDojoin = function () {
            var limit = 0;
            if (this.doJoin) {
                limit = this.doJoin.freeLimit;
            }
            if (limit < 0)
                limit = 0;
            setText(this.countTxt, "\u5269\u4F59\u6B21\u6570\uFF1A" + limit);
            console.log('updateCountTxtFromDojoin', "\u5269\u4F59\u6B21\u6570\uFF1A" + limit);
        };
        SceneStart.prototype.onAwake = function () {
            _super.prototype.onAwake.call(this);
            this.broadcast('callApi', 1, 'rankInfo2', {
                weddingId: window['CFG'].weddingId,
                activityId: window['CFG'].activityId
            });
            this.broadcast('callApi', 1, 'limitTimes', {
                weddingId: window['CFG'].weddingId,
                activityId: window['CFG'].activityId
            });
            this._shakeTimes = 0;
            this._counter = 0;
            this._lastTime = -1;
            setRotation(this.box, 0);
        };
        SceneStart.prototype.onResponse_rankInfo2 = function (data) {
            if (data.openPrize && data.score > 0) {
                console.log('开奖了....');
                console.log('prizelist', JSON.stringify(window['CFG'].activity.prizeList));
                var prize_1;
                window['CFG'].activity.prizeList.forEach(function (p) {
                    if (p.prizeType == data.prizeType)
                        prize_1 = p;
                });
                if (prize_1)
                    console.log('中奖了', JSON.stringify(prize_1));
                else
                    console.log('没有中奖');
                if (!window.localStorage.getItem(this.getKey())) {
                    if (prize_1)
                        this.bubbling('showDialog', 'Prize', prize_1);
                    else
                        this.bubbling('showDialog', 'Alert', '您与奖品擦肩而过~');
                }
                else {
                    console.log('已经弹窗过了', this.getKey());
                }
                window.localStorage.setItem(this.getKey(), '1');
            }
        };
        SceneStart.prototype.getKey = function () {
            return 'prizeShowed-' + window['CFG'].weixinUid + '-' + window['CFG'].weddingId + '-' + window['CFG'].activityId;
        };
        SceneStart.prototype.initGameStage = function () {
            console.log('initGameStage');
        };
        SceneStart.prototype.onClick_startbtn = function () {
            this.startbtn.getComponent(Button).enabled = false;
            this.sendDojoin();
        };
        SceneStart.prototype.sendDojoin = function () {
            this.dojoinFunc();
        };
        SceneStart.prototype.dojoinFunc = function (token) {
            this.broadcast('callApi', 1, 'doJoin', {
                activityId: window['CFG'].activityId,
                weddingId: window['CFG'].weddingId,
            });
        };
        SceneStart.prototype.onGotDojoin = function () {
            var _this = this;
            console.log('onGotDojoin', this.doJoin);
            this.startbtn.getComponent(Button).enabled = true;
            this.updateCountTxtFromDojoin();
            setTimeout(function () {
                if (localStorage.getItem('yylguide')) {
                    _this.bubbling('fuck', 'play');
                }
                else {
                    _this.bubbling('fuck', 'guide');
                    localStorage.setItem('yylguide', '1');
                }
            }, 50);
        };
        SceneStart.prototype.onGotDojoinError = function (error) {
            this.startbtn.getComponent(Button).enabled = true;
            if (error === '400005') {
                this.bubbling('showToast', '活动还未开始\n敬请期待~');
            }
            else if (error === '400006') {
                this.bubbling('showToast', '活动已结束\n下次早点来哦~');
            }
            else if (error === '400002') {
                this.bubbling('showDialog', 'Alert', '您已经没有抽奖机会了');
            }
            else {
                this.bubbling('showDialog', 'Alert', '网络异常，请稍后再试~');
            }
            console.log('onGotDojoinError', error);
        };
        SceneStart.prototype.onClick_rulebtn = function () {
            console.log('onClick_rulebtn');
            this.bubbling('showDialog', 'Rule');
        };
        SceneStart.prototype.onClick_rankbtn = function () {
            window.location.href = getRankURL();
        };
        SceneStart.prototype.onClick_backbtn = function () {
            window.location.href = getURL();
        };
        SceneStart.prototype.onResponse_rank = function () {
            this.bubbling('fuck', 'result');
            this.rankbtn.getComponent(Button).enabled = true;
        };
        SceneStart.prototype.onClick_recordbtn = function () {
            window.location.href = getRecordURL();
        };
        SceneStart.prototype.onDidEnter = function (last, action, parameters) {
            this.entity.enabled = true;
        };
        SceneStart.prototype.onDidLeave = function (next, action, parameters) {
            this.entity.enabled = false;
        };
        SceneStart.prototype.onWillEnter = function (last, action, parameters) {
            return __awaiter(this, void 0, void 0, function () {
                return __generator(this, function (_a) {
                    return [2];
                });
            });
        };
        SceneStart.prototype.onWillLeave = function (next, action, parameters) {
            return __awaiter(this, void 0, void 0, function () {
                return __generator(this, function (_a) {
                    return [2];
                });
            });
        };
        SceneStart.prototype.onWillMount = function (last, action, parameters) {
            return undefined;
        };
        SceneStart.prototype.onWillUnMount = function (next, action, parameters) {
            return undefined;
        };
        return SceneStart;
    }(ScillaComponent));

    function callApi(uri, params, method, responseType, ignoreSuccessField) {
        if (params === void 0) { params = null; }
        if (method === void 0) { method = 'post'; }
        if (responseType === void 0) { responseType = 'json'; }
        if (ignoreSuccessField === void 0) { ignoreSuccessField = false; }
        var ts = Date.now() + Math.floor(Math.random() * 9999999);
        var url = uri.startsWith('//') ? uri : "" + engine.customConfig.webServiceUrl + uri + "?_=" + ts;
        params = params || {};
        var options = {
            method: method,
        };
        var temp = typeof params === 'string' ? params : objectStringify(params);
        switch (method.toUpperCase()) {
            case 'GET':
                if (temp && temp.length > 0) {
                    url += (url.indexOf('?') < 0 ? '?' : '') + '&' + temp;
                }
                break;
            case 'POST':
                options.body = temp;
                options.headers = {
                    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
                };
                break;
        }
        var fetchMethod = responseType == 'jsonp' ? window['fetchJsonp'] : fetch;
        return fetchMethod(url, options)
            .then(function (response) {
            if (response.type === 'opaque') {
                return null;
            }
            return response.text();
        })
            .then(function (response) {
            if (response) {
                var data = void 0;
                switch (responseType) {
                    case 'json':
                        try {
                            data = JSON.parse(response);
                        }
                        catch (e) {
                            console.log('decode json failed: ' + url);
                            return Promise.reject({});
                        }
                        if (ignoreSuccessField || data.success) {
                            return {
                                data: data.hasOwnProperty('data') ? data.data : data,
                                origin: data,
                            };
                        }
                        else {
                            return Promise.reject(data.code);
                        }
                    case 'html':
                        var html = null;
                        return html;
                    case 'txt':
                        return response;
                }
            }
            return Promise.reject();
        });
    }

    var BuriedPoint = (function (_super) {
        __extends(BuriedPoint, _super);
        function BuriedPoint() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        BuriedPoint.prototype.onAwake = function () {
            _super.prototype.onAwake.call(this);
            if (this.dpm && this.dcm && !this._exposured) {
                this.setConfig(this.dpm, this.dcm, true);
            }
        };
        BuriedPoint.prototype.onTouchTap = function (e) {
            _super.prototype.onTouchTap.call(this, e);
            if (this._buriedPointName) {
                logClick(this._buriedPointName);
            }
        };
        BuriedPoint.prototype.setConfig = function (dpm, dcm, needLogExposure) {
            if (needLogExposure === void 0) { needLogExposure = false; }
            this._buriedPointName = 'buried-point-' + Date.now() + Math.floor(Math.random() * 999999);
            addBuriedPointConfig(this._buriedPointName, { dpm: dpm, dcm: dcm });
            if (needLogExposure) {
                logExposure(this._buriedPointName);
                this._exposured = true;
            }
        };
        return BuriedPoint;
    }(InteractComponent));
    var _buriedPoints = {};
    var env;
    function initEnv() {
        var cfg = engine.dataCenter.get('CFG');
        env = {
            app_id: cfg.appId,
            oaid: cfg.opActivityId,
            page_id: 3,
            comp_id: 4,
        };
    }
    function addBuriedPointConfig(name, config) {
        var dpm = config.dpm, dcm = config.dcm;
        _buriedPoints[name] = new BuriedPointData(dpm, dcm);
    }
    function logExposure(name) {
        return log(name, 'exposure');
    }
    function logClick(name) {
        return log(name, 'click');
    }
    function log(name, type) {
        var logPoint = _buriedPoints[name];
        var appId = engine.dataCenter.get('CFG', 'appId');
        var dpm = logPoint.dpm, dcm = logPoint.dcm;
        return callApi(type == 'exposure' ? '//embedlog.duiba.com.cn/exposure/standard' : '/log/click', {
            dpm: dpm, dcm: dcm, appId: appId
        }, 'get', type == 'exposure' ? 'jsonp' : 'json').catch(function (e) {
        });
    }
    function fillData(src) {
        var result = src;
        for (var key in env) {
            result = result.replace(key, env[key]);
        }
        return result;
    }
    var BuriedPointData = (function () {
        function BuriedPointData(dpm, dcm) {
            this.dpm = fillData(dpm);
            this.dcm = fillData(dcm);
        }
        return BuriedPointData;
    }());

    var Toast = (function (_super) {
        __extends(Toast, _super);
        function Toast() {
            var _this = _super !== null && _super.apply(this, arguments) || this;
            _this.ypadding = 20;
            _this.xpadding = 50;
            _this.offsetY = 0;
            _this.showDuration = 300;
            _this.hideDuration = 300;
            return _this;
        }
        Toast.prototype.onAwake = function () {
            _super.prototype.onAwake.call(this);
            if (!this._bgTransform) {
                var _a = this, offsetY = _a.offsetY, hideDuration = _a.hideDuration, showDuration = _a.showDuration, transform = _a.transform;
                this._bgTransform = this.getComponent(Transform);
                this._labelRenderer = this.Label.getComponent(TextRenderer);
                this._labelTransform = this.Label.getComponent(Transform);
                this._tweenIn = createTween(this, transform, false, { autoPlay: false })
                    .to({ position: { x: 0, y: offsetY } }, showDuration, cubicOut);
                this._tweenOut = createTween(this, transform, false, { autoPlay: false })
                    .to({ position: { y: 0 } }, hideDuration, cubicIn)
                    .call(this.onHidden);
                this.transform.position.y = this.outPos;
            }
        };
        Object.defineProperty(Toast.prototype, "outPos", {
            get: function () {
                return engine.renderContext.stageCenter.y + this._bgTransform.height;
            },
            enumerable: true,
            configurable: true
        });
        Toast.prototype.show = function (_a) {
            var _this = this;
            var content = _a.content, _b = _a.duration, duration = _b === void 0 ? 1000 : _b;
            this.entity.enabled = true;
            var _c = this, _bgTransform = _c._bgTransform, _labelRenderer = _c._labelRenderer, _labelTransform = _c._labelTransform, xpadding = _c.xpadding, ypadding = _c.ypadding;
            _labelRenderer.text = content;
            _labelRenderer.measureBounds();
            _bgTransform.width = _labelTransform.width + xpadding * 2;
            _bgTransform.height = _labelTransform.height + ypadding * 2;
            this._tweenOut.queue[0].props.position.y = this.outPos;
            this._tweenIn.play(true);
            if (this._timerDuration) {
                clearTimeout(this._timerDuration);
                this._timerDuration = null;
            }
            this._timerDuration = setTimeout(function () {
                _this.hide();
            }, duration);
        };
        Toast.prototype.hide = function () {
            this._tweenOut.play(true);
        };
        Toast.prototype.onHidden = function () {
            this.entity.enabled = false;
        };
        return Toast;
    }(ScillaComponent));

    var alien;
    (function (alien) {
        var NavigatorAction;
        (function (NavigatorAction) {
            NavigatorAction[NavigatorAction["Push"] = 0] = "Push";
            NavigatorAction[NavigatorAction["Pop"] = 1] = "Pop";
            NavigatorAction[NavigatorAction["Replace"] = 2] = "Replace";
            NavigatorAction[NavigatorAction["Jump"] = 3] = "Jump";
        })(NavigatorAction = alien.NavigatorAction || (alien.NavigatorAction = {}));
        var StackNavigator = (function () {
            function StackNavigator(delegate) {
                this._stack = [];
                this._delegate = delegate;
            }
            StackNavigator.prototype.catchPromise = function (p) {
                var _this = this;
                if (p) {
                    p.catch((function (e) {
                        _this._delegate.onError(e);
                    }));
                }
            };
            StackNavigator.prototype.push = function (name, parameters) {
                if (parameters === void 0) { parameters = null; }
                var last = this.getTopSceneName();
                if (last) {
                    if (last == name) {
                        return;
                    }
                    this.catchPromise(this._delegate.onLeave(last, name, NavigatorAction.Push, parameters));
                }
                this._stack.push(name);
                this.catchPromise(this._delegate.onEnter(name, last, NavigatorAction.Push, parameters));
            };
            StackNavigator.prototype.popTo = function (index, name, parameters) {
                if (parameters === void 0) { parameters = null; }
                if (this._stack.length > 0 && this._stack.length < (index + 1)) {
                    return;
                }
                var last = this.getTopSceneName();
                this._stack.splice(Math.max(index + 1, 0));
                var next = this._stack[index];
                if (!next) {
                    this._stack.push(next = name);
                }
                if (last) {
                    this.catchPromise(this._delegate.onLeave(last, next, NavigatorAction.Pop, parameters));
                }
                this.catchPromise(this._delegate.onEnter(next, last, NavigatorAction.Pop, parameters));
            };
            StackNavigator.prototype.pop = function (parameters) {
                if (parameters === void 0) { parameters = null; }
                this.popTo(this._stack.length - 2, null, parameters);
            };
            StackNavigator.prototype.popAll = function (name, parameters) {
                if (parameters === void 0) { parameters = null; }
                this.popTo(-1, name, parameters);
            };
            StackNavigator.prototype.replace = function (name, parameters) {
                if (parameters === void 0) { parameters = null; }
                var last = this._stack.pop();
                this._stack.push(name);
                this.catchPromise(this._delegate.onLeave(last, name, NavigatorAction.Replace, parameters));
                this.catchPromise(this._delegate.onEnter(name, last, NavigatorAction.Replace, parameters));
            };
            StackNavigator.prototype.jump = function (name, parameters) {
                if (parameters === void 0) { parameters = null; }
                if (this._stack.length < 2) {
                    this.push(name, parameters);
                    return;
                }
                var last = this._stack.pop();
                this._stack.splice(1);
                var next = name;
                this._stack.push(next);
                this._delegate.onLeave(last, next, NavigatorAction.Pop, parameters);
                this._delegate.onEnter(next, last, NavigatorAction.Pop, parameters);
            };
            StackNavigator.prototype.getTopSceneName = function () {
                return this._stack.length > 0 ? this._stack[this._stack.length - 1] : null;
            };
            StackNavigator.prototype.getBottomSceneName = function () {
                return this._stack.length > 0 ? this._stack[0] : null;
            };
            return StackNavigator;
        }());
        alien.StackNavigator = StackNavigator;
    })(alien || (alien = {}));

    var StackNavigator = alien.StackNavigator;
    var VIEW_WILL_ENTER = 'VIEW_WILL_ENTER';
    var VIEW_DID_ENTER = 'VIEW_DID_ENTER';
    var VIEW_WILL_LEAVE = 'VIEW_WILL_LEAVE';
    var VIEW_DID_LEAVE = 'VIEW_DID_LEAVE';
    var VirtualNavigator = (function (_super) {
        __extends(VirtualNavigator, _super);
        function VirtualNavigator(container) {
            var _this = _super.call(this) || this;
            _this._container = container;
            _this._classDic = {};
            _this.stack = new StackNavigator(_this);
            return _this;
        }
        VirtualNavigator.prototype.register = function (alias, childName, componentDef) {
            this._classDic[alias] = {
                childName: childName,
                componentDef: componentDef,
            };
        };
        Object.defineProperty(VirtualNavigator.prototype, "currentView", {
            get: function () {
                return this._currentView;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(VirtualNavigator.prototype, "currentName", {
            get: function () {
                return this._currentName;
            },
            enumerable: true,
            configurable: true
        });
        VirtualNavigator.prototype.getViewInstanceByName = function (name) {
            var _a = this._classDic[name], childName = _a.childName, componentDef = _a.componentDef;
            var scene = this._container.getChildrenByName(childName)[0];
            var component = scene.getComponent(componentDef);
            return component;
        };
        VirtualNavigator.prototype.onEnter = function (name, last, action, parameters) {
            return __awaiter(this, void 0, void 0, function () {
                var view;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            view = this.getViewInstanceByName(name);
                            this._currentView = view;
                            this._currentName = name;
                            return [4, view.onWillMount(last, action, parameters)];
                        case 1:
                            _a.sent();
                            this.emit(VIEW_WILL_ENTER, { name: name, last: last, action: action, parameters: parameters });
                            return [4, view.onWillEnter(last, action, parameters)];
                        case 2:
                            _a.sent();
                            this.emit(VIEW_DID_ENTER, { name: name, last: last, action: action, parameters: parameters });
                            view.onDidEnter(last, action, parameters);
                            return [2];
                    }
                });
            });
        };
        VirtualNavigator.prototype.onLeave = function (name, next, action, parameters) {
            return __awaiter(this, void 0, void 0, function () {
                var view;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            view = this.getViewInstanceByName(name);
                            return [4, view.onWillUnMount(name, action, parameters)];
                        case 1:
                            _a.sent();
                            this.emit(VIEW_WILL_LEAVE, { name: name, next: next, action: action, parameters: parameters });
                            return [4, view.onWillLeave(next, action, parameters)];
                        case 2:
                            _a.sent();
                            this.emit(VIEW_DID_LEAVE, { name: name, next: next, action: action, parameters: parameters });
                            view.onDidLeave(next, action, parameters);
                            return [2];
                    }
                });
            });
        };
        VirtualNavigator.prototype.onError = function (error) {
            console.log(error);
        };
        return VirtualNavigator;
    }(EventEmitter));

    var SceneResult = (function (_super) {
        __extends(SceneResult, _super);
        function SceneResult() {
            var _this = _super !== null && _super.apply(this, arguments) || this;
            _this.loadImage = function (url) {
                return new Promise(function (resolve, reject) {
                    var img = new Image();
                    if (EngineConfig.imgCrossOrigin) {
                        img.setAttribute('crossOrigin', 'anonymous');
                    }
                    img.onload = function (e) {
                        resolve(img);
                    };
                    img.onerror = function (e) {
                        reject(e);
                    };
                    img.src = url;
                });
            };
            _this.loadTexture = function (url) { return __awaiter(_this, void 0, Promise, function () {
                var img, texture;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0: return [4, this.loadImage(url)];
                        case 1:
                            img = _a.sent();
                            texture = createTexture(img);
                            return [2, texture];
                    }
                });
            }); };
            return _this;
        }
        SceneResult.prototype.onAwake = function () {
            _super.prototype.onAwake.call(this);
            this.onResponse(this.rankInfo);
        };
        SceneResult.prototype.onResponse = function (data) {
            setText(this.myname, data.nickName);
            if (data.rank > 500)
                setText(this.myrank, '未上榜');
            else
                setText(this.myrank, data.rank + '');
            setText(this.myscore, data.score);
            this.loadAvatar(this.myavatar, data.avatar, 78);
            var _a = __read(data.list, 3), rankinfo1 = _a[0], rankinfo2 = _a[1], rankinfo3 = _a[2];
            if (rankinfo1) {
                this.loadAvatar(this.avatar1, rankinfo1.avatar, 78);
                setText(this.name1, rankinfo1.nickName);
                setText(this.score1, rankinfo1.score);
            }
            if (rankinfo2) {
                this.loadAvatar(this.avatar2, rankinfo2.avatar, 64);
                setText(this.name2, rankinfo2.nickName);
                setText(this.score2, rankinfo2.score);
            }
            if (rankinfo3) {
                this.loadAvatar(this.avatar3, rankinfo3.avatar, 64);
                setText(this.name3, rankinfo3.nickName);
                setText(this.score3, rankinfo3.score);
            }
        };
        SceneResult.prototype.onTapCloseButton = function () {
            this.bubbling('fuck', 'start');
        };
        SceneResult.prototype.onDidEnter = function (last, action, parameters) {
            this.entity.enabled = true;
        };
        SceneResult.prototype.onDidLeave = function (next, action, parameters) {
            this.entity.enabled = false;
        };
        SceneResult.prototype.onWillEnter = function (last, action, parameters) {
            return __awaiter(this, void 0, void 0, function () {
                return __generator(this, function (_a) {
                    return [2];
                });
            });
        };
        SceneResult.prototype.onWillLeave = function (next, action, parameters) {
            return __awaiter(this, void 0, void 0, function () {
                return __generator(this, function (_a) {
                    return [2];
                });
            });
        };
        SceneResult.prototype.onWillMount = function (last, action, parameters) {
            return undefined;
        };
        SceneResult.prototype.onWillUnMount = function (next, action, parameters) {
            return undefined;
        };
        SceneResult.prototype.loadAvatar = function (avatar, url, width) {
            return __awaiter(this, void 0, void 0, function () {
                var texRender, texture;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            texRender = avatar.getComponent(TextureRenderer);
                            return [4, this.loadTexture(url)];
                        case 1:
                            texture = _a.sent();
                            texRender.texture = texture;
                            setScale(avatar, width / texture.bounds.width);
                            return [2];
                    }
                });
            });
        };
        return SceneResult;
    }(ScillaComponent));

    var SingleSceneNavigator = (function (_super) {
        __extends(SingleSceneNavigator, _super);
        function SingleSceneNavigator() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        SingleSceneNavigator.prototype.onCreate = function () {
            _super.prototype.onCreate.call(this);
            this._navigator = new VirtualNavigator(this.entity);
            this._navigator.register('start', 'SceneStart', SceneStart);
            this._navigator.register('play', 'ScenePlay', ScenePlay);
            this._navigator.register('guide', 'SceneGuide', SceneGuide);
            this._navigator.register('result', 'SceneResult', SceneResult);
        };
        SingleSceneNavigator.prototype.onAwake = function () {
            _super.prototype.onAwake.call(this);
            this.push('start');
        };
        SingleSceneNavigator.prototype.onUpdate = function (t) {
            _super.prototype.onUpdate.call(this, t);
        };
        SingleSceneNavigator.prototype.onSleep = function () {
            _super.prototype.onSleep.call(this);
        };
        SingleSceneNavigator.prototype.onDestroy = function () {
            _super.prototype.onDestroy.call(this);
        };
        SingleSceneNavigator.prototype.push = function (name, parameters) {
            if (parameters === void 0) { parameters = null; }
            this._navigator.stack.push(name, parameters);
        };
        SingleSceneNavigator.prototype.pop = function (parameters) {
            if (parameters === void 0) { parameters = null; }
            this._navigator.stack.pop(parameters);
        };
        SingleSceneNavigator.prototype.popToBottom = function (parameters) {
            if (parameters === void 0) { parameters = null; }
            this._navigator.stack.popTo(0, null, parameters);
        };
        SingleSceneNavigator.prototype.popAll = function (name, parameters) {
            if (parameters === void 0) { parameters = null; }
            this._navigator.stack.popAll(name, parameters);
        };
        SingleSceneNavigator.prototype.replace = function (name, parameters) {
            if (parameters === void 0) { parameters = null; }
            this._navigator.stack.replace(name, parameters);
        };
        SingleSceneNavigator.prototype.jump = function (name, parameters) {
            if (parameters === void 0) { parameters = null; }
            this._navigator.stack.jump(name, parameters);
        };
        return SingleSceneNavigator;
    }(ScillaComponent));

    var Popup = (function (_super) {
        __extends(Popup, _super);
        function Popup() {
            var _this = _super !== null && _super.apply(this, arguments) || this;
            _this.blackLayerDuration = 300;
            _this._dialogStack = [];
            return _this;
        }
        Popup.prototype.onAwake = function () {
            _super.prototype.onAwake.call(this);
            this._touchInterrupt = this.getComponent(TouchInterrupt);
            this._touchInterrupt.enabled = false;
            this._navigator = this.sceneContainer.getComponent(SingleSceneNavigator);
            this.entity.children.forEach(function (child) { return child.enabled = false; });
        };
        Popup.prototype.fuckNavigator = function (p) {
            console.log('fuckNavigator', p);
            this._navigator.push(p);
        };
        Popup.prototype.onUpdate = function (t) {
            _super.prototype.onUpdate.call(this, t);
        };
        Popup.prototype.onSleep = function () {
            _super.prototype.onSleep.call(this);
        };
        Popup.prototype.onDestroy = function () {
            _super.prototype.onDestroy.call(this);
        };
        Popup.prototype.setBgVisible = function (visible) {
            this.bgRenderer.enabled = visible;
        };
        Popup.prototype.getDialogInStack = function (name) {
            var e_1, _a;
            var result;
            try {
                for (var _b = __values(this._dialogStack), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var dialog = _c.value;
                    if (dialog.name === name) {
                        result = dialog;
                        break;
                    }
                }
            }
            catch (e_1_1) { e_1 = { error: e_1_1 }; }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
                }
                finally { if (e_1) throw e_1.error; }
            }
            return result;
        };
        Popup.prototype.bringToTop = function (dialogConfig) {
            var index = this._dialogStack.indexOf(dialogConfig);
            if (index >= 0) {
                this._dialogStack.splice(index, 1);
            }
            this._dialogStack.push(dialogConfig);
        };
        Popup.prototype.delete = function (dialogConfig) {
            var index = this._dialogStack.indexOf(dialogConfig);
            this._dialogStack.splice(index, 1);
        };
        Popup.prototype.showDialog = function (name, data, callback) {
            return __awaiter(this, void 0, void 0, function () {
                var dialogConfig, dialog, parent, content, transform, effect, effectOptions;
                return __generator(this, function (_a) {
                    dialogConfig = this.getDialogInStack(name);
                    dialog = this.entity.getChildrenByName(name)[0];
                    if (!dialogConfig) {
                        dialogConfig = {
                            name: name, data: data, callback: callback, dialog: dialog
                        };
                        dialog.enabled = true;
                    }
                    this.bringToTop(dialogConfig);
                    parent = dialog.parent;
                    parent.removeChild(dialog);
                    parent.addChildAt(dialog, parent.children.length);
                    this.setBgVisible(true);
                    this._touchInterrupt.enabled = true;
                    content = dialog.getComponent(DialogContent);
                    content && content.setup(data);
                    transform = dialog.getComponent(Transform);
                    effect = content ? content.effectImpl : none;
                    effectOptions = content ? content.showEffectOptions : null;
                    return [2];
                });
            });
        };
        Popup.prototype.hideDialog = function (name, action, data) {
            return __awaiter(this, void 0, void 0, function () {
                var dialogConfig, dialog, transform, content, effect, effectOptions;
                return __generator(this, function (_a) {
                    dialogConfig = this.getDialogInStack(name);
                    if (!dialogConfig) {
                        return [2];
                    }
                    dialog = this.entity.getChildrenByName(name)[0];
                    this.delete(dialogConfig);
                    if (this._dialogStack.length === 0) {
                        this.setBgVisible(false);
                        this._touchInterrupt.enabled = false;
                    }
                    transform = dialog.getComponent(Transform);
                    content = dialog.getComponent(DialogContent);
                    effect = content ? content.effectImpl : none;
                    effectOptions = content ? content.hideEffectOptions : null;
                    dialog.enabled = false;
                    if (dialogConfig.callback) {
                        dialogConfig.callback(action, data);
                        dialogConfig.callback = null;
                    }
                    return [2];
                });
            });
        };
        Popup.prototype.hideAll = function () {
            var e_2, _a;
            try {
                for (var _b = __values(this._dialogStack), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var dialog = _c.value;
                    this.hideDialog(dialog.name);
                }
            }
            catch (e_2_1) { e_2 = { error: e_2_1 }; }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
                }
                finally { if (e_2) throw e_2.error; }
            }
        };
        return Popup;
    }(ScillaComponent));

    var MainController = (function (_super) {
        __extends(MainController, _super);
        function MainController() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        MainController.prototype.onAwake = function () {
            _super.prototype.onAwake.call(this);
            engine.dataCenter.set('CFG', window['CFG']);
            this._toast = this.Toast.getComponent(Toast);
            this._popup = this.Popup.getComponent(Popup);
            initEnv();
            console.log('游戏刷新了...');
        };
        MainController.prototype.showToast = function (content, duration) {
            this._toast.show({
                content: content,
                duration: duration,
            });
        };
        MainController.prototype.showDialog = function (name, data, callback) {
            this._popup.showDialog(name, data, callback);
        };
        MainController.prototype.showNetError = function (action) {
        };
        return MainController;
    }(ScillaComponent));

    var RankList = (function (_super) {
        __extends(RankList, _super);
        function RankList() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        RankList.prototype.onAwake = function () {
            _super.prototype.onAwake.call(this);
            this.updateRankList(this.rankInfo);
        };
        RankList.prototype.updateRankList = function (rankInfo) {
            var _this = this;
            var _a = __read(rankInfo.list), data = _a.slice(3);
            this._bg = this.content.getComponent(RectRenderer);
            if (this._list) {
                this._list.forEach(function (item) {
                    _this.content.removeChild(item);
                });
            }
            var itemHeight = 73;
            var totalHeight = itemHeight * data.length;
            this._list = [];
            this._bg.height = totalHeight;
            data.forEach(function (item, index) {
                var rank = instantiate(_this.item);
                rank.getComponent(RankItem).setdata(item);
                _this.content.addChild(rank);
                rank.getComponent(Transform).position.y = index * itemHeight - totalHeight / 2 + itemHeight / 2 + 10;
                _this._list.push(rank);
            });
        };
        return RankList;
    }(ScillaComponent));

    var RequestMethod;
    (function (RequestMethod) {
        RequestMethod["GET"] = "GET";
        RequestMethod["POST"] = "POST";
        RequestMethod["PUT"] = "PUT";
        RequestMethod["DELETE"] = "DELETE";
    })(RequestMethod || (RequestMethod = {}));
    var ApiComponent = (function (_super) {
        __extends(ApiComponent, _super);
        function ApiComponent() {
            var _this = _super !== null && _super.apply(this, arguments) || this;
            _this.method = RequestMethod.POST;
            _this.onResponse = new ScillaEvent();
            _this.onError = new ScillaEvent();
            _this.onFinish = new ScillaEvent();
            _this.autoCall = false;
            return _this;
        }
        ApiComponent.prototype.onAwake = function () {
            _super.prototype.onAwake.call(this);
            if (this.autoCall) {
                this.execute();
            }
        };
        ApiComponent.prototype.execute = function (paramsInput) {
            var args = [];
            for (var _i = 1; _i < arguments.length; _i++) {
                args[_i - 1] = arguments[_i];
            }
            return __awaiter(this, void 0, void 0, function () {
                return __generator(this, function (_a) {
                    this._args = args;
                    return [2];
                });
            });
        };
        ApiComponent.prototype.onGotResponse = function (response) {
            var _a;
            if (this.name) {
                engine.dataCenter.set('API', this.name, response.data);
            }
            if (this._args && this._args.length > 0) {
                (_a = this.onResponse).invoke.apply(_a, __spread([response.data], this._args));
            }
            else {
                this.onResponse.invoke(response.data);
            }
            this.onCallFinish();
        };
        ApiComponent.prototype.onGotError = function (e) {
            var _a;
            if (this._args && this._args.length > 0) {
                (_a = this.onError).invoke.apply(_a, __spread([e], this._args));
            }
            else {
                this.onError.invoke(e);
            }
            this.onCallFinish();
        };
        ApiComponent.prototype.onCallFinish = function () {
            var _a;
            if (this._args && this._args.length > 0) {
                (_a = this.onFinish).invoke.apply(_a, __spread(this._args));
            }
            else {
                this.onFinish.invoke();
            }
        };
        return ApiComponent;
    }(ScillaComponent));

    var SampleApi = (function (_super) {
        __extends(SampleApi, _super);
        function SampleApi() {
            var _this = _super !== null && _super.apply(this, arguments) || this;
            _this.ignoreSuccessField = false;
            return _this;
        }
        SampleApi.prototype.callApi = function (name, paramsInput) {
            var args = [];
            for (var _i = 2; _i < arguments.length; _i++) {
                args[_i - 2] = arguments[_i];
            }
            return __awaiter(this, void 0, void 0, function () {
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            if (!(this.name == name)) return [3, 2];
                            return [4, this.execute.apply(this, __spread([paramsInput], args))];
                        case 1:
                            _a.sent();
                            _a.label = 2;
                        case 2: return [2];
                    }
                });
            });
        };
        SampleApi.prototype.execute = function (paramsInput) {
            var args = [];
            for (var _i = 1; _i < arguments.length; _i++) {
                args[_i - 1] = arguments[_i];
            }
            return __awaiter(this, void 0, void 0, function () {
                var params, _a, uri, method, response, e_1;
                return __generator(this, function (_b) {
                    switch (_b.label) {
                        case 0: return [4, _super.prototype.execute.apply(this, __spread([paramsInput], args))];
                        case 1:
                            _b.sent();
                            params = {};
                            if (this.params) {
                                injectProp(params, this.params);
                            }
                            if (paramsInput) {
                                injectProp(params, paramsInput);
                            }
                            _a = this, uri = _a.uri, method = _a.method;
                            _b.label = 2;
                        case 2:
                            _b.trys.push([2, 4, , 5]);
                            console.log(uri + "==>" + JSON.stringify(params));
                            return [4, callApi(uri, params, method, 'json', this.ignoreSuccessField)];
                        case 3:
                            response = _b.sent();
                            this.onGotResponse(response);
                            console.log(uri + "<<==" + JSON.stringify(response));
                            return [2, response.data];
                        case 4:
                            e_1 = _b.sent();
                            this.onGotError(e_1);
                            return [3, 5];
                        case 5: return [2];
                    }
                });
            });
        };
        return SampleApi;
    }(ApiComponent));

    var SceneController = (function (_super) {
        __extends(SceneController, _super);
        function SceneController() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        SceneController.prototype.onAwake = function () {
            _super.prototype.onAwake.call(this);
            this.entity.children.forEach(function (c) { return c.enabled = false; });
        };
        SceneController.prototype.fuck = function (p) {
            var nav = this.entity.getComponent(SingleSceneNavigator);
            nav.push(p);
        };
        SceneController.prototype.onUpdate = function (t) {
            _super.prototype.onUpdate.call(this, t);
        };
        return SceneController;
    }(ScillaComponent));

    var RuleDialogContent = (function (_super) {
        __extends(RuleDialogContent, _super);
        function RuleDialogContent() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        RuleDialogContent.prototype.onAwake = function () {
            _super.prototype.onAwake.call(this);
            this._contentRenderer = this.Content.getComponent(HtmlRenderer);
        };
        RuleDialogContent.prototype.setup = function (data) {
            this._contentRenderer.htmlText = window['ruleContent'];
        };
        return RuleDialogContent;
    }(DialogContent));

    var CustomTextRenderer = (function (_super) {
        __extends(CustomTextRenderer, _super);
        function CustomTextRenderer() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return CustomTextRenderer;
    }(TextRenderer));

    var AlertDialogContent = (function (_super) {
        __extends(AlertDialogContent, _super);
        function AlertDialogContent() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        AlertDialogContent.prototype.onAwake = function () {
            _super.prototype.onAwake.call(this);
        };
        AlertDialogContent.prototype.onTapCloseButton = function () {
            _super.prototype.onTapCloseButton.call(this);
            this.bubbling('fuckNavigator', 'start');
        };
        AlertDialogContent.prototype.setup = function (data) {
            if (data === void 0) { data = {}; }
            setText$1(this.content, data);
        };
        return AlertDialogContent;
    }(DialogContent));

    var PrizeDialogContent = (function (_super) {
        __extends(PrizeDialogContent, _super);
        function PrizeDialogContent() {
            var _this = _super !== null && _super.apply(this, arguments) || this;
            _this.loadImage = function (url) {
                return new Promise(function (resolve, reject) {
                    var img = new Image();
                    if (EngineConfig.imgCrossOrigin) {
                        img.setAttribute('crossOrigin', 'anonymous');
                    }
                    img.onload = function (e) {
                        resolve(img);
                    };
                    img.onerror = function (e) {
                        reject(e);
                    };
                    img.src = url;
                });
            };
            _this.loadTexture = function (url) { return __awaiter(_this, void 0, Promise, function () {
                var img, texture;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0: return [4, this.loadImage(url)];
                        case 1:
                            img = _a.sent();
                            texture = createTexture(img);
                            return [2, texture];
                    }
                });
            }); };
            return _this;
        }
        PrizeDialogContent.prototype.onClick_usebtn = function () {
            window.location.href = getRecordURL();
        };
        PrizeDialogContent.prototype.onAwake = function () {
            _super.prototype.onAwake.call(this);
        };
        PrizeDialogContent.prototype.setup = function (data) {
            if (data === void 0) { data = {}; }
            return __awaiter(this, void 0, void 0, function () {
                var texRender, texture, maxwidth, maxheight;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            setText(this.name, data.prizeName);
                            setText(this.title, this.getTypeStr(data.prizeType));
                            texRender = this.pic.getComponent(TextureRenderer);
                            return [4, this.loadTexture(data.prizeImage)];
                        case 1:
                            texture = _a.sent();
                            texRender.texture = texture;
                            if (texture.bounds.width > texture.bounds.height) {
                                maxwidth = 250;
                                setScale(this.pic, maxwidth / texture.bounds.width);
                            }
                            else {
                                maxheight = 250;
                                setScale(this.pic, maxheight / texture.bounds.height);
                            }
                            return [2];
                    }
                });
            });
        };
        PrizeDialogContent.prototype.getTypeStr = function (type) {
            if (type == 1) {
                return "\u83B7\u5F97\u4E00\u7B49\u5956";
            }
            if (type == 2) {
                return "\u83B7\u5F97\u4E8C\u7B49\u5956";
            }
            if (type == 3) {
                return "\u83B7\u5F97\u4E09\u7B49\u5956";
            }
            if (type == 4) {
                return "\u83B7\u5F97\u56DB\u7B49\u5956";
            }
        };
        return PrizeDialogContent;
    }(DialogContent));

    var Icon = (function (_super) {
        __extends(Icon, _super);
        function Icon() {
            var _this = _super !== null && _super.apply(this, arguments) || this;
            _this.GRAVITY = .7;
            _this._vx = 0;
            _this._vy = 0;
            return _this;
        }
        Icon.prototype.onAwake = function () {
            _super.prototype.onAwake.call(this);
            var children = this.entity.children;
            var index = Math.floor(children.length * Math.random());
            children.forEach(function (v, i) { return v.enabled = index == i; });
            var baseY = -100;
            var offsetX = 150;
            var offsetY = -100;
            var randomXoffset = Math.random() * offsetX * 2 - offsetX;
            var randomYoffset = Math.random() * offsetY;
            setXY(this.entity, randomXoffset, baseY + randomYoffset);
            this._vy = (-Math.random() * 3 - 10) * 2;
            this._vx = (Math.random() * 5 + 5) * (Math.random() > 0.5 ? 1 : -1) * 1;
        };
        Icon.prototype.onUpdate = function (t) {
            this._vy += this.GRAVITY;
            _super.prototype.onUpdate.call(this, t);
            var x = getX(this) + this._vx;
            var y = getY(this) + this._vy;
            setXY(this, x, y);
        };
        return Icon;
    }(ScillaComponent));

    engine.registerDef('components/other/CameraController', CameraController);
    engine.registerDef('components/base/Transform', Transform);
    engine.registerDef('components/renderer/TextureRenderer', TextureRenderer);
    engine.registerDef('components/animation/TouchZoom', TouchZoom);
    engine.registerDef('components/ui/Button', Button);
    engine.registerDef('components/renderer/TextRenderer', TextRenderer);
    engine.registerDef('components/other/FullStageSize', FullStageSize);
    engine.registerDef('components/renderer/RectRenderer', RectRenderer);
    engine.registerDef('components/ui/ScrollView', ScrollView);
    engine.registerDef('components/other/RelativeLayout', RelativeLayout);
    engine.registerDef('components/base/TouchInterrupt', TouchInterrupt);
    engine.registerDef('components/renderer/HtmlRenderer', HtmlRenderer);
    engine.registerDef('./scripts/Rotation', Rotation);
    engine.registerDef('./scripts/scenes/ScenePlay', ScenePlay);
    engine.registerDef('./scripts/scenes/SceneGuide', SceneGuide);
    engine.registerDef('./scripts/scenes/result/RankItem', RankItem);
    engine.registerDef('./scripts/scenes/SceneStart', SceneStart);
    engine.registerDef('./scripts/MainController', MainController);
    engine.registerDef('./scripts/scenes/result/RankList', RankList);
    engine.registerDef('./scripts/api/SampleApi', SampleApi);
    engine.registerDef('./scripts/popup/Popup', Popup);
    engine.registerDef('./scripts/scenes/SceneController', SceneController);
    engine.registerDef('./scripts/dialogs/RuleDialogContent', RuleDialogContent);
    engine.registerDef('./scripts/game/CustomTextRenderer', CustomTextRenderer);
    engine.registerDef('./scripts/navigator/SingleSceneNavigator', SingleSceneNavigator);
    engine.registerDef('./scripts/dialogs/AlertDialogContent', AlertDialogContent);
    engine.registerDef('./scripts/dialogs/PrizeDialogContent', PrizeDialogContent);
    engine.registerDef('./scripts/dialogs/ScoreDialogContent', ScoreDialogContent);
    engine.registerDef('./scripts/common/Toast', Toast);
    engine.registerDef('./scripts/Icon', Icon);
    engine.registerDef('./scripts/scenes/SceneResult', SceneResult);

    var launcher;
    modifyEngineConfig({
        lineHeightRatio: 1.2,
        entityEnabled: false,
        awakeComponentWhenAdded: false,
        sleepComponentWhenRemoved: false,
        drawRenderRect: false,
    });
    function startup(containerElement, options, onProgress) {
        if (options === void 0) { options = {}; }
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        launcher = new ScillaLauncher();
                        return [4, launcher.launch(containerElement, options, onProgress)];
                    case 1:
                        _a.sent();
                        return [2];
                }
            });
        });
    }

    exports.startup = startup;

    Object.defineProperty(exports, '__esModule', { value: true });

}));
//# sourceMappingURL=bundle.js.map
