var __extends;var __assign;var __rest;var __decorate;var __param;var __metadata;var __awaiter;var __generator;var __exportStar;var __values;var __read;var __spread;var __spreadArrays;var __await;var __asyncGenerator;var __asyncDelegator;var __asyncValues;var __makeTemplateObject;var __importStar;var __importDefault;(function(factory){var root=typeof global==="object"?global:typeof self==="object"?self:typeof this==="object"?this:{};if(typeof define==="function"&&define.amd){define("tslib",["exports"],function(exports){factory(createExporter(root,createExporter(exports)))})}else{if(typeof module==="object"&&typeof module.exports==="object"){factory(createExporter(root,createExporter(module.exports)))}else{factory(createExporter(root))}}function createExporter(exports,previous){if(exports!==root){if(typeof Object.create==="function"){Object.defineProperty(exports,"__esModule",{value:true})}else{exports.__esModule=true}}return function(id,v){return exports[id]=previous?previous(id,v):v}}})(function(exporter){var extendStatics=Object.setPrototypeOf||({__proto__:[]} instanceof Array&&function(d,b){d.__proto__=b})||function(d,b){for(var p in b){if(b.hasOwnProperty(p)){d[p]=b[p]}}};__extends=function(d,b){extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __())};__assign=Object.assign||function(t){for(var s,i=1,n=arguments.length;i<n;i++){s=arguments[i];for(var p in s){if(Object.prototype.hasOwnProperty.call(s,p)){t[p]=s[p]}}}return t};__rest=function(s,e){var t={};for(var p in s){if(Object.prototype.hasOwnProperty.call(s,p)&&e.indexOf(p)<0){t[p]=s[p]}}if(s!=null&&typeof Object.getOwnPropertySymbols==="function"){for(var i=0,p=Object.getOwnPropertySymbols(s);i<p.length;i++){if(e.indexOf(p[i])<0&&Object.prototype.propertyIsEnumerable.call(s,p[i])){t[p[i]]=s[p[i]]}}}return t};__decorate=function(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};__param=function(paramIndex,decorator){return function(target,key){decorator(target,key,paramIndex)}};__metadata=function(metadataKey,metadataValue){if(typeof Reflect==="object"&&typeof Reflect.metadata==="function"){return Reflect.metadata(metadataKey,metadataValue)}};__awaiter=function(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())})};__generator=function(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}
}};__exportStar=function(m,exports){for(var p in m){if(!exports.hasOwnProperty(p)){exports[p]=m[p]}}};__values=function(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}}}};__read=function(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};__spread=function(){for(var ar=[],i=0;i<arguments.length;i++){ar=ar.concat(__read(arguments[i]))}return ar};__spreadArrays=function(){for(var s=0,i=0,il=arguments.length;i<il;i++){s+=arguments[i].length}for(var r=Array(s),k=0,i=0;i<il;i++){for(var a=arguments[i],j=0,jl=a.length;j<jl;j++,k++){r[k]=a[j]}}return r};__await=function(v){return this instanceof __await?(this.v=v,this):new __await(v)};__asyncGenerator=function(thisArg,_arguments,generator){if(!Symbol.asyncIterator){throw new TypeError("Symbol.asyncIterator is not defined.")}var g=generator.apply(thisArg,_arguments||[]),i,q=[];return i={},verb("next"),verb("throw"),verb("return"),i[Symbol.asyncIterator]=function(){return this},i;function verb(n){if(g[n]){i[n]=function(v){return new Promise(function(a,b){q.push([n,v,a,b])>1||resume(n,v)})}}}function resume(n,v){try{step(g[n](v))}catch(e){settle(q[0][3],e)}}function step(r){r.value instanceof __await?Promise.resolve(r.value.v).then(fulfill,reject):settle(q[0][2],r)}function fulfill(value){resume("next",value)}function reject(value){resume("throw",value)}function settle(f,v){if(f(v),q.shift(),q.length){resume(q[0][0],q[0][1])}}};__asyncDelegator=function(o){var i,p;return i={},verb("next"),verb("throw",function(e){throw e}),verb("return"),i[Symbol.iterator]=function(){return this},i;function verb(n,f){i[n]=o[n]?function(v){return(p=!p)?{value:__await(o[n](v)),done:n==="return"}:f?f(v):v}:f}};__asyncValues=function(o){if(!Symbol.asyncIterator){throw new TypeError("Symbol.asyncIterator is not defined.")}var m=o[Symbol.asyncIterator],i;return m?m.call(o):(o=typeof __values==="function"?__values(o):o[Symbol.iterator](),i={},verb("next"),verb("throw"),verb("return"),i[Symbol.asyncIterator]=function(){return this},i);function verb(n){i[n]=o[n]&&function(v){return new Promise(function(resolve,reject){v=o[n](v),settle(resolve,reject,v.done,v.value)})}}function settle(resolve,reject,d,v){Promise.resolve(v).then(function(v){resolve({value:v,done:d})},reject)}};__makeTemplateObject=function(cooked,raw){if(Object.defineProperty){Object.defineProperty(cooked,"raw",{value:raw})}else{cooked.raw=raw}return cooked};__importStar=function(mod){if(mod&&mod.__esModule){return mod}var result={};if(mod!=null){for(var k in mod){if(Object.hasOwnProperty.call(mod,k)){result[k]=mod[k]}}}result["default"]=mod;return result};__importDefault=function(mod){return(mod&&mod.__esModule)?mod:{"default":mod}};exporter("__extends",__extends);exporter("__assign",__assign);exporter("__rest",__rest);exporter("__decorate",__decorate);exporter("__param",__param);exporter("__metadata",__metadata);exporter("__awaiter",__awaiter);exporter("__generator",__generator);exporter("__exportStar",__exportStar);exporter("__values",__values);exporter("__read",__read);exporter("__spread",__spread);exporter("__spreadArrays",__spreadArrays);exporter("__await",__await);exporter("__asyncGenerator",__asyncGenerator);exporter("__asyncDelegator",__asyncDelegator);exporter("__asyncValues",__asyncValues);exporter("__makeTemplateObject",__makeTemplateObject);exporter("__importStar",__importStar);exporter("__importDefault",__importDefault)});
var tslib = {__extends: __extends,__assign: __assign,__rest: __rest,__decorate: __decorate,__param: __param,__metadata: __metadata,__awaiter: __awaiter,__generator: __generator,__exportStar: __exportStar,__values: __values,__read: __read,__spread: __spread,__spreadArrays: __spreadArrays,__await: __await,__asyncGenerator: __asyncGenerator,__asyncDelegator: __asyncDelegator,__asyncValues: __asyncValues,__makeTemplateObject: __makeTemplateObject,__importStar: __importStar,__importDefault: __importDefault};
(function (global, factory) {
    typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('tslib')) :
    typeof define === 'function' && define.amd ? define(['exports', 'tslib'], factory) :
    (global = global || self, factory(global.FYGE = {}, global.tslib));
}(this, (function (exports, tslib_1) { 'use strict';

    var VERSION = "1.0";
    var devicePixelRatio = window && (window.devicePixelRatio || 1) || my.getSystemInfoSync().pixelRatio;
    var osType = navigator && navigator.userAgent && (function () {
        var n = navigator.userAgent.toLocaleLowerCase();
        var reg1 = /android/;
        var reg2 = /iphone|ipod|ipad/;
        if (reg1.test(n)) {
            return "android";
        }
        else if (reg2.test(n)) {
            return "ios";
        }
        else {
            return "pc";
        }
    })()
        || my.getSystemInfoSync().platform.toLowerCase();
    var PI = Math.PI;
    var HalfPI = PI >> 1;
    var PacPI = PI + HalfPI;
    function cos(angle) {
        switch (angle) {
            case HalfPI:
            case -PacPI:
                return 0;
            case PI:
            case -PI:
                return -1;
            case PacPI:
            case -HalfPI:
                return 0;
            default:
                return Math.cos(angle);
        }
    }
    function sin(angle) {
        switch (angle) {
            case HalfPI:
            case -PacPI:
                return 1;
            case PI:
            case -PI:
                return 0;
            case PacPI:
            case -HalfPI:
                return -1;
            default:
                return Math.sin(angle);
        }
    }
    var PI_2 = PI * 2;
    var RAD_TO_DEG = 180 / PI;
    var DEG_TO_RAD = PI / 180;
    (function (RENDERER_TYPE) {
        RENDERER_TYPE[RENDERER_TYPE["UNKNOWN"] = 0] = "UNKNOWN";
        RENDERER_TYPE[RENDERER_TYPE["WEBGL"] = 1] = "WEBGL";
        RENDERER_TYPE[RENDERER_TYPE["CANVAS"] = 2] = "CANVAS";
    })(exports.RENDERER_TYPE || (exports.RENDERER_TYPE = {}));
    (function (SHAPES) {
        SHAPES[SHAPES["POLY"] = 0] = "POLY";
        SHAPES[SHAPES["RECT"] = 1] = "RECT";
        SHAPES[SHAPES["CIRC"] = 2] = "CIRC";
        SHAPES[SHAPES["ELIP"] = 3] = "ELIP";
        SHAPES[SHAPES["RREC"] = 4] = "RREC";
    })(exports.SHAPES || (exports.SHAPES = {}));
    (function (PRECISION) {
        PRECISION["LOW"] = "lowp";
        PRECISION["MEDIUM"] = "mediump";
        PRECISION["HIGH"] = "highp";
    })(exports.PRECISION || (exports.PRECISION = {}));
    (function (TEXT_GRADIENT) {
        TEXT_GRADIENT[TEXT_GRADIENT["LINEAR_VERTICAL"] = 0] = "LINEAR_VERTICAL";
        TEXT_GRADIENT[TEXT_GRADIENT["LINEAR_HORIZONTAL"] = 1] = "LINEAR_HORIZONTAL";
    })(exports.TEXT_GRADIENT || (exports.TEXT_GRADIENT = {}));
    (function (TEXT_ALIGN) {
        TEXT_ALIGN["CENTER"] = "center";
        TEXT_ALIGN["LEFT"] = "left";
        TEXT_ALIGN["RIGHT"] = "right";
    })(exports.TEXT_ALIGN || (exports.TEXT_ALIGN = {}));
    (function (VERTICAL_ALIGN) {
        VERTICAL_ALIGN["MIDDLE"] = "middle";
        VERTICAL_ALIGN["UP"] = "up";
        VERTICAL_ALIGN["DOWN"] = "down";
    })(exports.VERTICAL_ALIGN || (exports.VERTICAL_ALIGN = {}));
    (function (TEXT_lINETYPE) {
        TEXT_lINETYPE["SINGLE"] = "single";
        TEXT_lINETYPE["MULTI"] = "multi";
    })(exports.TEXT_lINETYPE || (exports.TEXT_lINETYPE = {}));
    (function (LINE_ALIGNMENT) {
        LINE_ALIGNMENT[LINE_ALIGNMENT["middle"] = 0.5] = "middle";
        LINE_ALIGNMENT[LINE_ALIGNMENT["outter"] = 1] = "outter";
        LINE_ALIGNMENT[LINE_ALIGNMENT["inner"] = 0] = "inner";
    })(exports.LINE_ALIGNMENT || (exports.LINE_ALIGNMENT = {}));
    (function (LINE_CAP) {
        LINE_CAP["BUTT"] = "butt";
        LINE_CAP["ROUND"] = "round";
        LINE_CAP["SQUARE"] = "square";
    })(exports.LINE_CAP || (exports.LINE_CAP = {}));
    (function (LINE_JOIN) {
        LINE_JOIN["MITER"] = "miter";
        LINE_JOIN["ROUND"] = "round";
        LINE_JOIN["BEVEL"] = "bevel";
    })(exports.LINE_JOIN || (exports.LINE_JOIN = {}));
    (function (BLEND_MODES) {
        BLEND_MODES[BLEND_MODES["NORMAL"] = 0] = "NORMAL";
        BLEND_MODES[BLEND_MODES["ADD"] = 1] = "ADD";
        BLEND_MODES[BLEND_MODES["MULTIPLY"] = 2] = "MULTIPLY";
        BLEND_MODES[BLEND_MODES["SCREEN"] = 3] = "SCREEN";
        BLEND_MODES[BLEND_MODES["OVERLAY"] = 4] = "OVERLAY";
        BLEND_MODES[BLEND_MODES["DARKEN"] = 5] = "DARKEN";
        BLEND_MODES[BLEND_MODES["LIGHTEN"] = 6] = "LIGHTEN";
        BLEND_MODES[BLEND_MODES["COLOR_DODGE"] = 7] = "COLOR_DODGE";
        BLEND_MODES[BLEND_MODES["COLOR_BURN"] = 8] = "COLOR_BURN";
        BLEND_MODES[BLEND_MODES["HARD_LIGHT"] = 9] = "HARD_LIGHT";
        BLEND_MODES[BLEND_MODES["SOFT_LIGHT"] = 10] = "SOFT_LIGHT";
        BLEND_MODES[BLEND_MODES["DIFFERENCE"] = 11] = "DIFFERENCE";
        BLEND_MODES[BLEND_MODES["EXCLUSION"] = 12] = "EXCLUSION";
        BLEND_MODES[BLEND_MODES["HUE"] = 13] = "HUE";
        BLEND_MODES[BLEND_MODES["SATURATION"] = 14] = "SATURATION";
        BLEND_MODES[BLEND_MODES["COLOR"] = 15] = "COLOR";
        BLEND_MODES[BLEND_MODES["LUMINOSITY"] = 16] = "LUMINOSITY";
        BLEND_MODES[BLEND_MODES["NORMAL_NPM"] = 17] = "NORMAL_NPM";
        BLEND_MODES[BLEND_MODES["ADD_NPM"] = 18] = "ADD_NPM";
        BLEND_MODES[BLEND_MODES["SCREEN_NPM"] = 19] = "SCREEN_NPM";
        BLEND_MODES[BLEND_MODES["NONE"] = 20] = "NONE";
        BLEND_MODES[BLEND_MODES["SRC_OVER"] = 21] = "SRC_OVER";
        BLEND_MODES[BLEND_MODES["SRC_IN"] = 22] = "SRC_IN";
        BLEND_MODES[BLEND_MODES["SRC_OUT"] = 23] = "SRC_OUT";
        BLEND_MODES[BLEND_MODES["SRC_ATOP"] = 24] = "SRC_ATOP";
        BLEND_MODES[BLEND_MODES["DST_OVER"] = 25] = "DST_OVER";
        BLEND_MODES[BLEND_MODES["DST_IN"] = 26] = "DST_IN";
        BLEND_MODES[BLEND_MODES["DST_OUT"] = 27] = "DST_OUT";
        BLEND_MODES[BLEND_MODES["DST_ATOP"] = 28] = "DST_ATOP";
        BLEND_MODES[BLEND_MODES["ERASE"] = 29] = "ERASE";
        BLEND_MODES[BLEND_MODES["SUBTRACT"] = 30] = "SUBTRACT";
    })(exports.BLEND_MODES || (exports.BLEND_MODES = {}));
    (function (DRAW_MODES) {
        DRAW_MODES[DRAW_MODES["POINTS"] = 0] = "POINTS";
        DRAW_MODES[DRAW_MODES["LINES"] = 1] = "LINES";
        DRAW_MODES[DRAW_MODES["LINE_LOOP"] = 2] = "LINE_LOOP";
        DRAW_MODES[DRAW_MODES["LINE_STRIP"] = 3] = "LINE_STRIP";
        DRAW_MODES[DRAW_MODES["TRIANGLES"] = 4] = "TRIANGLES";
        DRAW_MODES[DRAW_MODES["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP";
        DRAW_MODES[DRAW_MODES["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN";
    })(exports.DRAW_MODES || (exports.DRAW_MODES = {}));
    (function (SCALE_MODES) {
        SCALE_MODES[SCALE_MODES["LINEAR"] = 0] = "LINEAR";
        SCALE_MODES[SCALE_MODES["NEAREST"] = 1] = "NEAREST";
    })(exports.SCALE_MODES || (exports.SCALE_MODES = {}));
    (function (WRAP_MODES) {
        WRAP_MODES[WRAP_MODES["CLAMP"] = 33071] = "CLAMP";
        WRAP_MODES[WRAP_MODES["REPEAT"] = 10497] = "REPEAT";
        WRAP_MODES[WRAP_MODES["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
    })(exports.WRAP_MODES || (exports.WRAP_MODES = {}));
    (function (GC_MODES) {
        GC_MODES[GC_MODES["AUTO"] = 0] = "AUTO";
        GC_MODES[GC_MODES["MANUAL"] = 1] = "MANUAL";
    })(exports.GC_MODES || (exports.GC_MODES = {}));

    var HashObject = (function () {
        function HashObject() {
            this._instanceId = 0;
            this._instanceType = "HashObject";
            this._instanceId = HashObject._object_id++;
        }
        Object.defineProperty(HashObject.prototype, "instanceId", {
            get: function () {
                return this._instanceId;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(HashObject.prototype, "instanceType", {
            get: function () {
                return this._instanceType;
            },
            enumerable: true,
            configurable: true
        });
        HashObject._object_id = 0;
        return HashObject;
    }());

    var Event = (function (_super) {
        tslib_1.__extends(Event, _super);
        function Event(type) {
            var _this = _super.call(this) || this;
            _this.type = "";
            _this.target = null;
            _this.data = null;
            _this._pd = false;
            _this._instanceType = "Event";
            _this.type = type;
            return _this;
        }
        Event.prototype.stopPropagation = function () {
            this._pd = true;
        };
        Event.prototype.destroy = function () {
            var s = this;
            s.target = null;
            s.data = null;
        };
        Event.prototype.reset = function (type, target) {
            var s = this;
            s.target = target;
            s._pd = false;
            s.type = type;
        };
        Event.RESIZE = "onResize";
        Event.SCROLL_TO_HEAD = "onScrollToHead";
        Event.SCROLL_STOP = "onScrollStop";
        Event.SCROLL_START = "onScrollStart";
        Event.SCROLL_TO_END = "onScrollToEnd";
        Event.INIT_STAGE = "onInitStage";
        Event.ADDED_TO_STAGE = "onAddedToStage";
        Event.REMOVED_FROM_STAGE = "onRemovedFromStage";
        Event.ENTER_FRAME = "onEnterFrame";
        Event.END_FRAME = "onEndFrame";
        Event.CALL_FRAME = "onCallFrame";
        Event.COMPLETE = "onComplete";
        Event.PROGRESS = "onProgress";
        Event.ERROR = "onError";
        Event.ABORT = "onAbort";
        Event.START = "onStart";
        Event.TIMER = "onTimer";
        Event.TIMER_COMPLETE = "onTimerComplete";
        return Event;
    }(HashObject));

    var EventDispatcher = (function (_super) {
        tslib_1.__extends(EventDispatcher, _super);
        function EventDispatcher() {
            var _this = _super.call(this) || this;
            _this.eventTypes = {};
            _this.eventTypes1 = {};
            _this._instanceType = "EventDispatcher";
            return _this;
        }
        EventDispatcher.getMouseEventCount = function (type) {
            if (type === void 0) { type = ""; }
            var count = 0;
            if (type == "") {
                for (var item in EventDispatcher._MECO) {
                    if (item.indexOf("onMouse") == 0) {
                        count += EventDispatcher._MECO[item];
                    }
                }
            }
            else {
                if (EventDispatcher._MECO[type]) {
                    count = EventDispatcher._MECO[type];
                }
            }
            return count;
        };
        EventDispatcher.prototype.addEventListener = function (type, listener, context, useCapture) {
            if (useCapture === void 0) { useCapture = true; }
            if (!type) {
                throw new Error("添加侦听的type值为undefined");
            }
            if (!listener) {
                throw new Error("侦听回调函数不能为null");
            }
            var s = this;
            var eventTypes = s.eventTypes;
            if (!useCapture) {
                eventTypes = s.eventTypes1;
            }
            if (!eventTypes[type]) {
                eventTypes[type] = [];
            }
            for (var i = 0, len = eventTypes[type].length; i < len; i++) {
                var ee = eventTypes[type][i];
                if (ee.fn === listener && ee.context === context) {
                    console.log("已添加过该事件");
                    return s;
                }
            }
            eventTypes[type].unshift(new EE(listener, context || s));
            if (type.indexOf("onMouse") == 0) {
                s._changeMouseCount(type, true);
            }
            return s;
        };
        EventDispatcher.prototype.once = function (type, listener, context, useCapture) {
            if (useCapture === void 0) { useCapture = true; }
            if (!type) {
                throw new Error("添加侦听的type值为undefined");
            }
            if (!listener) {
                throw new Error("侦听回调函数不能为null");
            }
            var s = this;
            var eventTypes = s.eventTypes;
            if (!useCapture) {
                eventTypes = s.eventTypes1;
            }
            if (!eventTypes[type]) {
                eventTypes[type] = [];
            }
            eventTypes[type].unshift(new EE(listener, context || s, true));
            if (type.indexOf("onMouse") == 0) {
                s._changeMouseCount(type, true);
            }
            return s;
        };
        EventDispatcher.prototype._changeMouseCount = function (type, isAdd) {
            var count = isAdd ? 1 : -1;
            if (!EventDispatcher._MECO[type]) {
                EventDispatcher._MECO[type] = 0;
            }
            EventDispatcher._MECO[type] += count;
            if (EventDispatcher._MECO[type] < 0) {
                EventDispatcher._MECO[type] = 0;
            }
            EventDispatcher._totalMEC += count;
        };
        EventDispatcher.prototype.dispatchEvent = function (event, data, useCapture) {
            if (data === void 0) { data = null; }
            if (useCapture === void 0) { useCapture = true; }
            var s = this;
            if (typeof (event) == "string") {
                if (!s._defaultEvent) {
                    s._defaultEvent = new Event(event);
                }
                else {
                    s._defaultEvent.reset(event, s);
                }
                event = s._defaultEvent;
            }
            var listeners = s.eventTypes[event.type];
            if (!useCapture) {
                listeners = s.eventTypes1[event.type];
            }
            if (listeners) {
                var len = listeners.length;
                if (event.target == null) {
                    event.target = s;
                }
                if (data != null) {
                    event.data = data;
                }
                for (var i = len - 1; i >= 0; i--) {
                    if (!event["_pd"]) {
                        if (listeners[i]) {
                            var listener = listeners[i];
                            var type = event.type;
                            listener.fn.call(listener.context, event);
                            if (listener.once) {
                                s.removeEventListener(type, listener.fn, listener.context, useCapture);
                            }
                        }
                        else {
                            listeners.splice(i, 1);
                        }
                    }
                }
                return true;
            }
            else {
                return false;
            }
        };
        EventDispatcher.prototype.hasEventListener = function (type, useCapture) {
            if (useCapture === void 0) { useCapture = true; }
            var s = this;
            if (useCapture) {
                if (s.eventTypes[type] && s.eventTypes[type].length > 0) {
                    return true;
                }
            }
            else {
                if (s.eventTypes1[type] && s.eventTypes1[type].length > 0) {
                    return true;
                }
            }
            return false;
        };
        EventDispatcher.prototype.removeEventListener = function (type, listener, context, useCapture) {
            if (useCapture === void 0) { useCapture = true; }
            var s = this;
            var listeners = s.eventTypes[type];
            if (!useCapture) {
                listeners = s.eventTypes1[type];
            }
            if (listeners) {
                var len = listeners.length;
                var thisObject = context || s;
                for (var i = len - 1; i >= 0; i--) {
                    if (listeners[i].fn === listener && listeners[i].context === thisObject) {
                        listeners.splice(i, 1);
                        if (type.indexOf("onMouse") == 0) {
                            s._changeMouseCount(type, false);
                        }
                    }
                }
            }
            return s;
        };
        EventDispatcher.prototype.removeAllEventListener = function () {
            var s = this;
            for (var type in s.eventTypes) {
                if (type.indexOf("onMouse") == 0) {
                    for (var j = 0; j < s.eventTypes[type].length; j++) {
                        s._changeMouseCount(type, false);
                    }
                }
            }
            for (var type in s.eventTypes1) {
                if (type.indexOf("onMouse") == 0) {
                    for (var j = 0; j < s.eventTypes1[type].length; j++) {
                        s._changeMouseCount(type, false);
                    }
                }
            }
            s.eventTypes1 = {};
            s.eventTypes = {};
        };
        EventDispatcher.prototype.destroy = function () {
            var s = this;
            s.removeAllEventListener();
            s.eventTypes = null;
            s.eventTypes1 = null;
        };
        EventDispatcher._MECO = {};
        EventDispatcher._totalMEC = 0;
        return EventDispatcher;
    }(HashObject));
    var EE = (function () {
        function EE(fn, context, once) {
            if (once === void 0) { once = false; }
            this.fn = fn;
            this.context = context;
            this.once = once;
        }
        return EE;
    }());

    var Point = (function (_super) {
        tslib_1.__extends(Point, _super);
        function Point(x, y) {
            if (x === void 0) { x = 0; }
            if (y === void 0) { y = 0; }
            var _this = _super.call(this) || this;
            _this.x = 0;
            _this.y = 0;
            var s = _this;
            s._instanceType = "Point";
            s.x = x;
            s.y = y;
            return _this;
        }
        Point.prototype.destroy = function () { };
        Point.distance = function () {
            var args = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                args[_i] = arguments[_i];
            }
            var len = args.length;
            if (len == 4) {
                return Math.sqrt((args[0] - args[2]) * (args[0] - args[2]) + (args[1] - args[3]) * (args[1] - args[3]));
            }
            else if (len == 2) {
                return Math.sqrt((args[0].x - args[1].x) * (args[0].x - args[1].x) + (args[0].y - args[1].y) * (args[0].y - args[1].y));
            }
        };
        Point.prototype.set = function (x, y) {
            this.x = x;
            this.y = y;
        };
        return Point;
    }(HashObject));

    var Matrix = (function (_super) {
        tslib_1.__extends(Matrix, _super);
        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; }
            var _this = _super.call(this) || this;
            _this.a = 1;
            _this.b = 0;
            _this.c = 0;
            _this.d = 1;
            _this.tx = 0;
            _this.ty = 0;
            _this.array = null;
            _this.prepend = function (mtx) {
                var s = this;
                var a = mtx.a;
                var b = mtx.b;
                var c = mtx.c;
                var d = mtx.d;
                var tx = mtx.tx;
                var ty = mtx.ty;
                var a1 = s.a;
                var c1 = s.c;
                var tx1 = s.tx;
                s.a = a * a1 + c * s.b;
                s.b = b * a1 + d * s.b;
                s.c = a * c1 + c * s.d;
                s.d = b * c1 + d * s.d;
                s.tx = a * tx1 + c * s.ty + tx;
                s.ty = b * tx1 + d * s.ty + ty;
                return this;
            };
            var s = _this;
            s._instanceType = "Matrix";
            s.a = a;
            s.b = b;
            s.c = c;
            s.d = d;
            s.tx = tx;
            s.ty = ty;
            return _this;
        }
        Matrix.prototype.clone = function () {
            var s = this;
            return new Matrix(s.a, s.b, s.c, s.d, s.tx, s.ty);
        };
        Matrix.prototype.copy = function (matrix) {
            this.a = matrix.a;
            this.b = matrix.b;
            this.c = matrix.c;
            this.d = matrix.d;
            this.tx = matrix.tx;
            this.ty = matrix.ty;
            return this;
        };
        Matrix.prototype.transformPoint = function (x, y, bp) {
            if (bp === void 0) { bp = null; }
            var s = this;
            if (!bp) {
                bp = new Point();
            }
            bp.x = x * s.a + y * s.c + s.tx;
            bp.y = x * s.b + y * s.d + s.ty;
            return bp;
        };
        Matrix.prototype.transformPointInverse = function (x, y, bp) {
            if (bp === void 0) { bp = null; }
            if (!bp) {
                bp = new Point();
            }
            var id = 1 / ((this.a * this.d) + (this.c * -this.b));
            bp.x = (this.d * id * x) + (-this.c * id * y) + (((this.ty * this.c) - (this.tx * this.d)) * id);
            bp.y = (this.a * id * y) + (-this.b * id * x) + (((-this.ty * this.a) + (this.tx * this.b)) * id);
            return bp;
        };
        Matrix.prototype.setFrom = function (mtx) {
            var s = this;
            s.a = mtx.a;
            s.b = mtx.b;
            s.c = mtx.c;
            s.d = mtx.d;
            s.tx = mtx.tx;
            s.ty = mtx.ty;
        };
        Matrix.prototype.identity = function () {
            var s = this;
            s.a = s.d = 1;
            s.b = s.c = s.tx = s.ty = 0;
        };
        Matrix.prototype.invert = function () {
            var s = this;
            var a = s.a;
            var b = s.b;
            var c = s.c;
            var d = s.d;
            var tx = s.tx;
            var ty = s.ty;
            if (b == 0 && c == 0) {
                if (a == 0 || d == 0) {
                    s.a = s.d = s.tx = s.ty = 0;
                }
                else {
                    a = s.a = 1 / a;
                    d = s.d = 1 / d;
                    s.tx = -a * tx;
                    s.ty = -d * ty;
                }
                return s;
            }
            var determinant = a * d - b * c;
            if (determinant == 0) {
                s.identity();
                return s;
            }
            determinant = 1 / determinant;
            var k = s.a = d * determinant;
            b = s.b = -b * determinant;
            c = s.c = -c * determinant;
            d = s.d = a * determinant;
            s.tx = -(k * tx + c * ty);
            s.ty = -(b * tx + d * ty);
            return s;
        };
        Matrix.prototype.createBox = function (x, y, scaleX, scaleY, rotation, skewX, skewY, ax, ay) {
            var s = this;
            if (rotation != 0) {
                skewX = skewY = rotation % 360;
            }
            else {
                skewX %= 360;
                skewY %= 360;
            }
            if ((skewX == 0) && (skewY == 0)) {
                s.a = scaleX;
                s.b = s.c = 0;
                s.d = scaleY;
            }
            else {
                skewX *= DEG_TO_RAD;
                skewY *= DEG_TO_RAD;
                var u = cos(skewX);
                var v = sin(skewX);
                if (skewX == skewY) {
                    s.a = u * scaleX;
                    s.b = v * scaleX;
                }
                else {
                    s.a = cos(skewY) * scaleX;
                    s.b = sin(skewY) * scaleX;
                }
                s.c = -v * scaleY;
                s.d = u * scaleY;
            }
            s.tx = x + ax - (ax * s.a + ay * s.c);
            s.ty = y + ay - (ax * s.b + ay * s.d);
        };
        Matrix.prototype.append = function (matrix) {
            var a1 = this.a;
            var b1 = this.b;
            var c1 = this.c;
            var d1 = this.d;
            this.a = (matrix.a * a1) + (matrix.b * c1);
            this.b = (matrix.a * b1) + (matrix.b * d1);
            this.c = (matrix.c * a1) + (matrix.d * c1);
            this.d = (matrix.c * b1) + (matrix.d * d1);
            this.tx = (matrix.tx * a1) + (matrix.ty * c1) + this.tx;
            this.ty = (matrix.tx * b1) + (matrix.ty * d1) + this.ty;
        };
        Matrix.isEqual = function (m1, m2) {
            return m1.tx == m2.tx && m1.ty == m2.ty && m1.a == m2.a && m1.b == m2.b && m1.c == m2.c && m1.d == m2.d;
        };
        Matrix.prototype.concat = function (mtx) {
            var s = this;
            var a = s.a, b = s.b, c = s.c, d = s.d, tx = s.tx, ty = s.ty;
            var ma = mtx.a, mb = mtx.b, mc = mtx.c, md = mtx.d, mx = mtx.tx, my = mtx.ty;
            s.a = a * ma + b * mc;
            s.b = a * mb + b * md;
            s.c = c * ma + d * mc;
            s.d = c * mb + d * md;
            s.tx = tx * ma + ty * mc + mx;
            s.ty = tx * mb + ty * md + my;
        };
        Matrix.prototype.rotate = function (angle) {
            var s = this;
            var sin = Math.sin(angle), cos = Math.cos(angle), a = s.a, b = s.b, c = s.c, d = s.d, tx = s.tx, ty = s.ty;
            s.a = a * cos - b * sin;
            s.b = a * sin + b * cos;
            s.c = c * cos - d * sin;
            s.d = c * sin + d * cos;
            s.tx = tx * cos - ty * sin;
            s.ty = tx * sin + ty * cos;
        };
        Matrix.prototype.scale = function (sx, sy) {
            var s = this;
            s.a *= sx;
            s.d *= sy;
            s.c *= sx;
            s.b *= sy;
            s.tx *= sx;
            s.ty *= sy;
        };
        Matrix.prototype.translate = function (dx, dy) {
            var s = this;
            s.tx += dx;
            s.ty += dy;
        };
        Matrix.prototype.set = 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.getRotation = function () {
            return Math.round(Math.atan2(this.b, this.a) * RAD_TO_DEG);
        };
        Matrix.prototype.toArray = function (transpose, out) {
            if (transpose === void 0) { transpose = false; }
            if (!this.array) {
                this.array = new Float32Array(9);
            }
            var array = out || this.array;
            if (transpose) {
                array[0] = this.a;
                array[1] = this.b;
                array[2] = 0;
                array[3] = this.c;
                array[4] = this.d;
                array[5] = 0;
                array[6] = this.tx;
                array[7] = this.ty;
                array[8] = 1;
            }
            else {
                array[0] = this.a;
                array[1] = this.c;
                array[2] = this.tx;
                array[3] = this.b;
                array[4] = this.d;
                array[5] = this.ty;
                array[6] = 0;
                array[7] = 0;
                array[8] = 1;
            }
            return array;
        };
        Object.defineProperty(Matrix, "IDENTITY", {
            get: function () {
                return new Matrix();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Matrix, "TEMP_MATRIX", {
            get: function () {
                return new Matrix();
            },
            enumerable: true,
            configurable: true
        });
        Matrix.prototype.destroy = function () {
        };
        return Matrix;
    }(HashObject));

    var ObservablePoint = (function (_super) {
        tslib_1.__extends(ObservablePoint, _super);
        function ObservablePoint(cb, scope, x, y) {
            if (x === void 0) { x = 0; }
            if (y === void 0) { y = 0; }
            var _this = _super.call(this) || this;
            var s = _this;
            s._instanceType = "ObservablePoint";
            _this._x = x;
            _this._y = y;
            _this.cb = cb;
            _this.scope = scope;
            return _this;
        }
        ObservablePoint.prototype.set = function (x, y) {
            if (x === void 0) { x = 0; }
            if (y === void 0) { y = 0; }
            var _x = x || 0;
            var _y = y || ((y !== 0) ? _x : 0);
            if (this._x !== _x || this._y !== _y) {
                this._x = _x;
                this._y = _y;
                this.cb.call(this.scope);
            }
        };
        ObservablePoint.prototype.copy = function (point) {
            if (this._x !== point.x || this._y !== point.y) {
                this._x = point.x;
                this._y = point.y;
                this.cb.call(this.scope);
            }
        };
        Object.defineProperty(ObservablePoint.prototype, "x", {
            get: function () {
                return this._x;
            },
            set: function (value) {
                if (this._x !== value) {
                    this._x = value;
                    this.cb.call(this.scope);
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ObservablePoint.prototype, "y", {
            get: function () {
                return this._y;
            },
            set: function (value) {
                if (this._y !== value) {
                    this._y = value;
                    this.cb.call(this.scope);
                }
            },
            enumerable: true,
            configurable: true
        });
        ObservablePoint.prototype.destroy = function () {
        };
        return ObservablePoint;
    }(HashObject));

    var Rectangle = (function (_super) {
        tslib_1.__extends(Rectangle, _super);
        function Rectangle(x, y, width, height) {
            if (x === void 0) { x = 0; }
            if (y === void 0) { y = 0; }
            if (width === void 0) { width = 0; }
            if (height === void 0) { height = 0; }
            var _this = _super.call(this) || this;
            _this.x = 0;
            _this.y = 0;
            _this.width = 0;
            _this.height = 0;
            var s = _this;
            s._instanceType = "Rectangle";
            s.x = x;
            s.y = y;
            s.height = height;
            s.width = width;
            _this.type = exports.SHAPES.RECT;
            return _this;
        }
        Rectangle.prototype.clear = function () {
            this.x = 0;
            this.y = 0;
            this.width = 0;
            this.height = 0;
        };
        Rectangle.prototype.copy = function (rect) {
            this.x = rect.x;
            this.y = rect.y;
            this.width = rect.width;
            this.height = rect.height;
            return this;
        };
        Rectangle.prototype.clone = function () {
            return new Rectangle(this.x, this.y, this.width, this.height);
        };
        Object.defineProperty(Rectangle.prototype, "left", {
            get: function () {
                return this.x;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Rectangle.prototype, "right", {
            get: function () {
                return this.x + this.width;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Rectangle.prototype, "top", {
            get: function () {
                return this.y;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Rectangle.prototype, "bottom", {
            get: function () {
                return this.y + this.height;
            },
            enumerable: true,
            configurable: true
        });
        Rectangle.prototype.isPointIn = function (point) {
            var s = this;
            return point.x >= s.x && point.x <= (s.x + s.width) && point.y >= s.y && point.y <= (s.y + s.height);
        };
        Rectangle.prototype.fit = function (rectangle) {
            var x1 = Math.max(this.x, rectangle.x);
            var x2 = Math.min(this.x + this.width, rectangle.x + rectangle.width);
            var y1 = Math.max(this.y, rectangle.y);
            var y2 = Math.min(this.y + this.height, rectangle.y + rectangle.height);
            this.x = x1;
            this.width = Math.max(x2 - x1, 0);
            this.y = y1;
            this.height = Math.max(y2 - y1, 0);
        };
        Rectangle.prototype.pad = function (paddingX, paddingY) {
            paddingX = paddingX || 0;
            paddingY = paddingY || ((paddingY !== 0) ? paddingX : 0);
            this.x -= paddingX;
            this.y -= paddingY;
            this.width += paddingX * 2;
            this.height += paddingY * 2;
        };
        Rectangle.createFromRects = function () {
            var arg = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                arg[_i] = arguments[_i];
            }
            if (arg.length == 0) {
                return null;
            }
            else if (arg.length == 1) {
                return arg[0];
            }
            else {
                var rect = arg[0];
                var x = rect.x, y = rect.y, w = rect.width, h = rect.height, wx1 = void 0, wx2 = void 0, hy1 = void 0, hy2 = void 0;
                for (var i = 1; i < arg.length; i++) {
                    wx1 = x + w;
                    hy1 = y + h;
                    wx2 = arg[i].x + arg[i].width;
                    hy2 = arg[i].y + arg[i].height;
                    if (x > arg[i].x || wx1 == 0) {
                        x = arg[i].x;
                    }
                    if (y > arg[i].y || hy1 == 0) {
                        y = arg[i].y;
                    }
                    if (wx1 < wx2) {
                        wx1 = wx2;
                    }
                    if (hy1 < hy2) {
                        hy1 = hy2;
                    }
                    rect.x = x;
                    rect.y = y;
                    rect.width = wx1 - x;
                    rect.height = hy1 - y;
                }
                return rect;
            }
        };
        Rectangle.createFromPoints = function (rect) {
            var arg = [];
            for (var _i = 1; _i < arguments.length; _i++) {
                arg[_i - 1] = arguments[_i];
            }
            var x = arg[0].x, y = arg[0].y, w = arg[0].x, h = arg[0].y;
            for (var i = 1; i < arg.length; i++) {
                if (arg[i] == null)
                    continue;
                if (x > arg[i].x) {
                    x = arg[i].x;
                }
                if (y > arg[i].y) {
                    y = arg[i].y;
                }
                if (w < arg[i].x) {
                    w = arg[i].x;
                }
                if (h < arg[i].y) {
                    h = arg[i].y;
                }
            }
            rect.x = x;
            rect.y = y;
            rect.width = w - x;
            rect.height = h - y;
            return rect;
        };
        Rectangle.createFromVertexData = function (rect, vertexData, matrix) {
            var temP = new Point();
            var x = vertexData[0], y = vertexData[1], w = vertexData[0], h = vertexData[1];
            if (matrix) {
                matrix.transformPoint(x, y, temP);
                x = w = temP.x;
                y = h = temP.y;
            }
            for (var i = 2; i < vertexData.length; i += 2) {
                if (vertexData[i] == null)
                    continue;
                temP.set(vertexData[i], vertexData[i + 1]);
                if (matrix)
                    matrix.transformPoint(temP.x, temP.y, temP);
                if (x > temP.x)
                    x = temP.x;
                if (y > temP.y)
                    y = temP.y;
                if (w < temP.x)
                    w = temP.x;
                if (h < temP.y)
                    h = temP.y;
            }
            rect.x = x;
            rect.y = y;
            rect.width = w - x;
            rect.height = h - y;
            return rect;
        };
        Rectangle.createRectfrom2Point = function (rect, p1, p2) {
            var x = p1.x, y = p1.y, w = p1.x, h = p1.y;
            if (x > p2.x) {
                x = p2.x;
            }
            if (y > p2.y) {
                y = p2.y;
            }
            if (w < p2.x) {
                w = p2.x;
            }
            if (h < p2.y) {
                h = p2.y;
            }
            rect.x = x, rect.y = y, rect.width = w - x, rect.height = h - y;
            return rect;
        };
        Rectangle.testRectCross = function (ra, rb) {
            var a_cx, a_cy;
            var b_cx, b_cy;
            a_cx = ra.x + (ra.width / 2);
            a_cy = ra.y + (ra.height / 2);
            b_cx = rb.x + (rb.width / 2);
            b_cy = rb.y + (rb.height / 2);
            return ((Math.abs(a_cx - b_cx) <= (ra.width / 2 + rb.width / 2)) && (Math.abs(a_cy - b_cy) <= (ra.height / 2 + rb.height / 2)));
        };
        Rectangle.prototype.destroy = function () {
        };
        return Rectangle;
    }(HashObject));

    var Transform = (function (_super) {
        tslib_1.__extends(Transform, _super);
        function Transform() {
            var _this = _super.call(this) || this;
            var s = _this;
            s._instanceType = "Transform";
            _this.worldMatrix = new Matrix();
            _this.localMatrix = new Matrix();
            _this._worldID = 0;
            _this._parentID = 0;
            _this.position = new ObservablePoint(_this.onChange, _this, 0, 0);
            _this.scale = new ObservablePoint(_this.onChange, _this, 1, 1);
            _this.anchor = new ObservablePoint(_this.onChange, _this, 0, 0);
            _this.skew = new ObservablePoint(_this.updateSkew, _this, 0, 0);
            _this._rotation = 0;
            _this._cx = 1;
            _this._sx = 0;
            _this._cy = 0;
            _this._sy = 1;
            _this._localID = 0;
            _this._currentLocalID = 0;
            return _this;
        }
        Transform.prototype.onChange = function () {
            this._localID++;
        };
        Transform.prototype.updateSkew = function () {
            this._cx = cos(this._rotation + this.skew._y);
            this._sx = sin(this._rotation + this.skew._y);
            this._cy = -sin(this._rotation - this.skew._x);
            this._sy = cos(this._rotation - this.skew._x);
            this._localID++;
        };
        Transform.prototype.updateLocalMatrix = function () {
            var lt = this.localMatrix;
            if (this._localID !== this._currentLocalID) {
                lt.a = this._cx * this.scale._x;
                lt.b = this._sx * this.scale._x;
                lt.c = this._cy * this.scale._y;
                lt.d = this._sy * this.scale._y;
                lt.tx = this.position._x + this.anchor._x - ((this.anchor._x * lt.a) + (this.anchor._y * lt.c));
                lt.ty = this.position._y + this.anchor._y - ((this.anchor._x * lt.b) + (this.anchor._y * lt.d));
                this._currentLocalID = this._localID;
                this._parentID = -1;
            }
        };
        Transform.prototype.updateWorldMatrix = function (parentTransform) {
            var lt = this.localMatrix;
            if (this._localID !== this._currentLocalID) {
                lt.a = this._cx * this.scale._x;
                lt.b = this._sx * this.scale._x;
                lt.c = this._cy * this.scale._y;
                lt.d = this._sy * this.scale._y;
                lt.tx = this.position._x + this.anchor._x - ((this.anchor._x * lt.a) + (this.anchor._y * lt.c));
                lt.ty = this.position._y + this.anchor._y - ((this.anchor._x * lt.b) + (this.anchor._y * lt.d));
                this._currentLocalID = this._localID;
                this._parentID = -1;
            }
            if (this._parentID !== parentTransform._worldID || parentTransform._worldID == -1) {
                var pt = parentTransform.worldMatrix;
                var wt = this.worldMatrix;
                wt.a = (lt.a * pt.a) + (lt.b * pt.c);
                wt.b = (lt.a * pt.b) + (lt.b * pt.d);
                wt.c = (lt.c * pt.a) + (lt.d * pt.c);
                wt.d = (lt.c * pt.b) + (lt.d * pt.d);
                wt.tx = (lt.tx * pt.a) + (lt.ty * pt.c) + pt.tx;
                wt.ty = (lt.tx * pt.b) + (lt.ty * pt.d) + pt.ty;
                if (parentTransform._worldID == -1) {
                    this._parentID = parentTransform._worldID = 0;
                }
                else {
                    this._parentID = parentTransform._worldID;
                }
                this._worldID++;
            }
        };
        Object.defineProperty(Transform.prototype, "rotation", {
            get: function () {
                return this._rotation;
            },
            set: function (value) {
                if (value === this._rotation)
                    return;
                this._rotation = value;
                this.updateSkew();
            },
            enumerable: true,
            configurable: true
        });
        Transform.prototype.destroy = function () {
            this.worldMatrix = null;
            this.localMatrix = null;
            this.position = null;
            this.skew = null;
            this.scale = null;
            this.anchor = null;
        };
        return Transform;
    }(HashObject));

    var ux = [1, 1, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1, -1, -1, 0, 1];
    var uy = [0, 1, 1, 1, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1, -1, -1];
    var vx = [0, -1, -1, -1, 0, 1, 1, 1, 0, 1, 1, 1, 0, -1, -1, -1];
    var vy = [1, 1, 0, -1, -1, -1, 0, 1, -1, -1, 0, 1, 1, 1, 0, -1];
    var tempMatrices = [];
    var mul = [];
    function signum(x) {
        if (x < 0) {
            return -1;
        }
        if (x > 0) {
            return 1;
        }
        return 0;
    }
    function init() {
        for (var i = 0; i < 16; i++) {
            var row = [];
            mul.push(row);
            for (var j = 0; j < 16; j++) {
                var _ux = signum((ux[i] * ux[j]) + (vx[i] * uy[j]));
                var _uy = signum((uy[i] * ux[j]) + (vy[i] * uy[j]));
                var _vx = signum((ux[i] * vx[j]) + (vx[i] * vy[j]));
                var _vy = signum((uy[i] * vx[j]) + (vy[i] * vy[j]));
                for (var k = 0; k < 16; k++) {
                    if (ux[k] === _ux && uy[k] === _uy && vx[k] === _vx && vy[k] === _vy) {
                        row.push(k);
                        break;
                    }
                }
            }
        }
        for (var i = 0; i < 16; i++) {
            var mat = new Matrix();
            mat.set(ux[i], uy[i], vx[i], vy[i], 0, 0);
            tempMatrices.push(mat);
        }
    }
    init();
    var GroupD8 = {
        E: 0,
        SE: 1,
        S: 2,
        SW: 3,
        W: 4,
        NW: 5,
        N: 6,
        NE: 7,
        MIRROR_VERTICAL: 8,
        MIRROR_HORIZONTAL: 12,
        uX: function (ind) { return ux[ind]; },
        uY: function (ind) { return uy[ind]; },
        vX: function (ind) { return vx[ind]; },
        vY: function (ind) { return vy[ind]; },
        inv: function (rotation) {
            if (rotation & 8) {
                return rotation & 15;
            }
            return (-rotation) & 7;
        },
        add: function (rotationSecond, rotationFirst) { return mul[rotationSecond][rotationFirst]; },
        sub: function (rotationSecond, rotationFirst) { return mul[rotationSecond][GroupD8.inv(rotationFirst)]; },
        rotate180: function (rotation) { return rotation ^ 4; },
        isVertical: function (rotation) { return (rotation & 3) === 2; },
        byDirection: function (dx, dy) {
            if (Math.abs(dx) * 2 <= Math.abs(dy)) {
                if (dy >= 0) {
                    return GroupD8.S;
                }
                return GroupD8.N;
            }
            else if (Math.abs(dy) * 2 <= Math.abs(dx)) {
                if (dx > 0) {
                    return GroupD8.E;
                }
                return GroupD8.W;
            }
            else if (dy > 0) {
                if (dx > 0) {
                    return GroupD8.SE;
                }
                return GroupD8.SW;
            }
            else if (dx > 0) {
                return GroupD8.NE;
            }
            return GroupD8.NW;
        },
        matrixAppendRotationInv: function (matrix, rotation, tx, ty) {
            if (tx === void 0) { tx = 0; }
            if (ty === void 0) { ty = 0; }
            var mat = tempMatrices[GroupD8.inv(rotation)];
            mat.tx = tx;
            mat.ty = ty;
            matrix.append(mat);
        },
    };

    var DisplayObject = (function (_super) {
        tslib_1.__extends(DisplayObject, _super);
        function DisplayObject() {
            var _this = _super.call(this) || this;
            _this.mouseEnable = true;
            _this._instanceType = "DisplayObject";
            _this.tempDisplayObjectParent = null;
            _this.transform = new Transform();
            _this._alpha = 1;
            _this.visible = true;
            _this.renderable = true;
            _this.parent = null;
            _this._worldAlpha = 1;
            _this.filterArea = null;
            _this._filters = null;
            _this._enabledFilters = null;
            _this._localBoundsSelf = new Rectangle();
            _this._bounds = new Rectangle();
            _this._boundsID = 0;
            _this._lastBoundsID = -1;
            _this._mask = null;
            _this.destroyed = false;
            return _this;
        }
        Object.defineProperty(DisplayObject.prototype, "filters", {
            get: function () { return this._filters && this._filters.slice(); },
            set: function (value) { this._filters = value && value.slice(); },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(DisplayObject.prototype, "_tempDisplayObjectParent", {
            get: function () {
                if (this.tempDisplayObjectParent === null) {
                    this.tempDisplayObjectParent = new DisplayObject();
                }
                return this.tempDisplayObjectParent;
            },
            enumerable: true,
            configurable: true
        });
        DisplayObject.prototype.updateTransform = function () {
            this.transform.updateWorldMatrix(this.parent.transform);
            this._worldAlpha = this.alpha * this.parent._worldAlpha;
        };
        DisplayObject.prototype.hitTestPoint = function (point, isMouseEvent) {
            if (isMouseEvent === void 0) { isMouseEvent = false; }
            var s = this;
            if (!s.visible)
                return null;
            if (isMouseEvent && !s.mouseEnable)
                return null;
            if (!isMouseEvent) {
                if (s._localBoundsSelf.isPointIn(point)) {
                    return s;
                }
            }
            else {
                if (s._localBoundsSelf.isPointIn(s.globalToLocal(point, DisplayObject._bp))) {
                    return s;
                }
            }
            return null;
        };
        DisplayObject.prototype._recursivePostUpdateTransform = function () {
            if (this.parent) {
                this.parent._recursivePostUpdateTransform();
                this.transform.updateWorldMatrix(this.parent.transform);
            }
            else {
                this.transform.updateWorldMatrix(this._tempDisplayObjectParent.transform);
            }
        };
        DisplayObject.prototype.getBounds = function (skipUpdate, rect) {
            if (skipUpdate === void 0) { skipUpdate = false; }
            if (rect === void 0) { rect = DisplayObject.temBounds; }
            if (!skipUpdate) {
                if (!this.parent) {
                    this.parent = this._tempDisplayObjectParent;
                    this.updateTransform();
                    this.parent = null;
                }
                else {
                    this._recursivePostUpdateTransform();
                    this.updateTransform();
                }
            }
            this.calculateBounds();
            return rect.copy(this._bounds);
        };
        DisplayObject.prototype.getLocalBounds = function (rect) {
            if (rect === void 0) { rect = DisplayObject.temBounds; }
            var transformRef = this.transform;
            var parentRef = this.parent;
            this.parent = null;
            this.transform = this._tempDisplayObjectParent.transform;
            var bounds = this.getBounds(false, rect);
            this.parent = parentRef;
            this.transform = transformRef;
            return bounds;
        };
        DisplayObject.prototype.calculateBounds = function () {
            if (this._lastBoundsID == this._boundsID)
                return;
            this._lastBoundsID = this._boundsID;
        };
        DisplayObject.prototype.globalToLocal = function (point, bp) {
            if (bp === void 0) { bp = null; }
            return this.worldMatrix.transformPointInverse(point.x, point.y, bp || DisplayObject._bp);
        };
        DisplayObject.prototype.localToGlobal = function (point, bp) {
            if (bp === void 0) { bp = null; }
            var wp = this.worldMatrix.transformPoint(point.x, point.y, bp || DisplayObject._bp);
            if (this.stage) {
                return this.stage.globalToLocal(wp, bp || DisplayObject._bp);
            }
            else {
                return wp;
            }
        };
        DisplayObject.prototype._onDispatchBubbledEvent = function (type) {
            var s = this;
            if (type == Event.REMOVED_FROM_STAGE && !s.stage)
                return;
            if (type == Event.REMOVED_FROM_STAGE) {
                s.dispatchEvent(type);
                s.stage = null;
            }
            else if (type == Event.ADDED_TO_STAGE) {
                s.stage = s.parent.stage;
                s.dispatchEvent(type);
            }
        };
        DisplayObject.prototype.renderWebGL = function (renderer) {
        };
        DisplayObject.prototype.renderCanvas = function (renderer) {
        };
        DisplayObject.prototype.setParent = function (container) {
            if (!container || !container.addChild) {
                throw new Error('setParent: Argument must be a Container');
            }
            container.addChild(this);
            return container;
        };
        DisplayObject.prototype.setTransform = function (x, y, scaleX, scaleY, rotation, skewX, skewY, anchorX, anchorY) {
            if (x === void 0) { x = 0; }
            if (y === void 0) { y = 0; }
            if (scaleX === void 0) { scaleX = 1; }
            if (scaleY === void 0) { scaleY = 1; }
            if (rotation === void 0) { rotation = 0; }
            if (skewX === void 0) { skewX = 0; }
            if (skewY === void 0) { skewY = 0; }
            if (anchorX === void 0) { anchorX = 0; }
            if (anchorY === void 0) { anchorY = 0; }
            this.position.x = x;
            this.position.y = y;
            this.scale.x = !scaleX ? 1 : scaleX;
            this.scale.y = !scaleY ? 1 : scaleY;
            this.rotation = rotation;
            this.skew.x = skewX;
            this.skew.y = skewY;
            this.anchor.x = anchorX;
            this.anchor.y = anchorY;
            return this;
        };
        DisplayObject.prototype.destroy = function () {
            this.removeAllEventListener();
            if (this.parent) {
                this.parent.removeChild(this);
            }
            _super.prototype.destroy.call(this);
            this.transform.destroy();
            this.transform = null;
            this._localBoundsSelf = null;
            this._bounds = null;
            this.tempDisplayObjectParent = null;
            this._mask = null;
            this.filterArea = null;
            this._filters = null;
            this._enabledFilters = null;
            this.mouseEnable = false;
            this.destroyed = true;
        };
        Object.defineProperty(DisplayObject.prototype, "alpha", {
            get: function () {
                return this._alpha;
            },
            set: function (value) {
                if (this._alpha != value) {
                    this._alpha = value;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(DisplayObject.prototype, "x", {
            get: function () {
                return this.position.x;
            },
            set: function (value) {
                this.transform.position.x = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(DisplayObject.prototype, "y", {
            get: function () {
                return this.position.y;
            },
            set: function (value) {
                this.transform.position.y = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(DisplayObject.prototype, "worldMatrix", {
            get: function () {
                return this.transform.worldMatrix;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(DisplayObject.prototype, "localMatrix", {
            get: function () {
                return this.transform.localMatrix;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(DisplayObject.prototype, "position", {
            get: function () {
                return this.transform.position;
            },
            set: function (value) {
                this.transform.position.copy(value);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(DisplayObject.prototype, "scale", {
            get: function () {
                return this.transform.scale;
            },
            set: function (value) {
                this.transform.scale.copy(value);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(DisplayObject.prototype, "scaleX", {
            get: function () {
                return this.transform.scale.x;
            },
            set: function (value) {
                this.transform.scale.x = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(DisplayObject.prototype, "scaleY", {
            get: function () {
                return this.transform.scale.y;
            },
            set: function (value) {
                this.transform.scale.y = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(DisplayObject.prototype, "anchor", {
            get: function () {
                return this.transform.anchor;
            },
            set: function (value) {
                this.transform.anchor.copy(value);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(DisplayObject.prototype, "anchorX", {
            get: function () {
                return this.transform.anchor.x;
            },
            set: function (value) {
                this.transform.anchor.x = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(DisplayObject.prototype, "anchorY", {
            get: function () {
                return this.transform.anchor.y;
            },
            set: function (value) {
                this.transform.anchor.y = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(DisplayObject.prototype, "skew", {
            get: function () {
                return this.transform.skew;
            },
            set: function (value) {
                this.transform.skew.copy(value);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(DisplayObject.prototype, "rotation", {
            get: function () {
                return this.transform.rotation * RAD_TO_DEG;
            },
            set: function (value) {
                this.transform.rotation = value * DEG_TO_RAD;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(DisplayObject.prototype, "worldVisible", {
            get: function () {
                var item = this;
                do {
                    if (!item.visible) {
                        return false;
                    }
                    item = item.parent;
                } while (item);
                return true;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(DisplayObject.prototype, "mask", {
            get: function () {
                return this._mask;
            },
            set: function (value) {
                if (this._mask == value)
                    return;
                if (this._mask) {
                    this._mask.renderable = true;
                    this._mask.isUsedToMask = false;
                }
                this._mask = value;
                if (this._mask) {
                    this._mask.renderable = false;
                    this._mask.isUsedToMask = true;
                    this._boundsID++;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(DisplayObject.prototype, "width", {
            get: function () {
                return this._width;
            },
            set: function (value) {
                this._width = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(DisplayObject.prototype, "height", {
            get: function () {
                return this._height;
            },
            set: function (value) {
                this._height = value;
            },
            enumerable: true,
            configurable: true
        });
        DisplayObject.prototype.update = function () {
            if (this.hasEventListener(Event.ENTER_FRAME)) {
                this.dispatchEvent(Event.ENTER_FRAME);
            }
        };
        DisplayObject._bp = new Point();
        DisplayObject._p1 = new Point();
        DisplayObject._p2 = new Point();
        DisplayObject._p3 = new Point();
        DisplayObject._p4 = new Point();
        DisplayObject.temBounds = new Rectangle();
        return DisplayObject;
    }(EventDispatcher));
    DisplayObject.prototype.displayObjectUpdateTransform = DisplayObject.prototype.updateTransform;
    DisplayObject.prototype.displayObjectHitTestPoint = DisplayObject.prototype.hitTestPoint;

    var Container = (function (_super) {
        tslib_1.__extends(Container, _super);
        function Container() {
            var _this = _super.call(this) || this;
            _this.mouseChildren = true;
            _this._instanceType = "Container";
            _this.children = [];
            return _this;
        }
        Container.prototype.onChildrenChange = function (index) {
        };
        Container.prototype.addChild = function (child) {
            this.addChildAt(child, this.children.length);
            return child;
        };
        Container.prototype.addChildren = function () {
            var _this = this;
            var children = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                children[_i] = arguments[_i];
            }
            children.forEach(function (child) { _this.addChild(child); });
            return children;
        };
        Container.prototype.addChildAt = function (child, index) {
            if (!child)
                return;
            var s = this;
            var sameParent = (s == child.parent);
            var len;
            if (child.parent) {
                if (!sameParent) {
                    child.parent.removeChild(child);
                }
                else {
                    len = s.children.length;
                    for (var i = 0; i < len; i++) {
                        if (s.children[i] == child) {
                            s.children.splice(i, 1);
                            break;
                        }
                    }
                }
            }
            child.parent = s;
            child.transform._parentID = -1;
            this._boundsID++;
            len = s.children.length;
            if (index >= len) {
                s.children[s.children.length] = child;
                index = len;
            }
            else if (index == 0 || index < 0) {
                s.children.unshift(child);
                index = 0;
            }
            else {
                s.children.splice(index, 0, child);
            }
            if (s.stage && !sameParent) {
                child._onDispatchBubbledEvent(Event.ADDED_TO_STAGE);
            }
            this.onChildrenChange(index);
            return child;
        };
        Container.prototype.swapChildren = function (child1, child2) {
            if (child1 === child2) {
                return;
            }
            var s = this;
            var id1 = -1;
            var id2 = -1;
            var childCount = s.children.length;
            if (typeof (child1) == "number") {
                id1 = child1;
            }
            else {
                id1 = s.getChildIndex(child1);
            }
            if (typeof (child2) == "number") {
                id2 = child2;
            }
            else {
                id2 = s.getChildIndex(child2);
            }
            if (id1 == id2 || id1 < 0 || id1 >= childCount || id2 < 0 || id2 >= childCount) {
                return false;
            }
            else {
                var temp = s.children[id1];
                s.children[id1] = s.children[id2];
                s.children[id2] = temp;
                this.onChildrenChange(id1 < id2 ? id1 : id2);
                return true;
            }
        };
        Container.prototype.getChildIndex = function (child) {
            var index = this.children.indexOf(child);
            if (index === -1) {
                return null;
            }
            return index;
        };
        Container.prototype.setChildIndex = function (child, index) {
            this.addChildAt(child, index);
        };
        Container.prototype.getChildAt = function (index) {
            if (index < 0 || index >= this.children.length) {
                return null;
            }
            return this.children[index];
        };
        Container.prototype.getChildByName = function (name, isOnlyOne, isRecursive) {
            if (isOnlyOne === void 0) { isOnlyOne = true; }
            if (isRecursive === void 0) { isRecursive = false; }
            if (!name)
                return null;
            var s = this;
            var rex;
            if (typeof (name) == "string") {
                rex = new RegExp("^" + name + "$");
            }
            else {
                rex = name;
            }
            var elements = [];
            Container._getElementsByName(rex, s, isOnlyOne, isRecursive, elements);
            var len = elements.length;
            if (len == 0) {
                return null;
            }
            else if (len == 1) {
                return elements[0];
            }
            else {
                return elements;
            }
        };
        Container.prototype.removeChild = function (child) {
            var index = this.children.indexOf(child);
            if (index === -1)
                return null;
            this.removeChildAt(index);
            return child;
        };
        Container.prototype.removeChildAt = function (index) {
            var s = this;
            var child;
            var len = s.children.length - 1;
            if (len < 0)
                return;
            if (index == len) {
                child = s.children.pop();
            }
            else if (index == 0) {
                child = s.children.shift();
            }
            else {
                child = s.children.splice(index, 1)[0];
            }
            child._onDispatchBubbledEvent(Event.REMOVED_FROM_STAGE);
            child.parent = null;
            child.transform._parentID = -1;
            this._boundsID++;
            this.onChildrenChange(index);
            return child;
        };
        Container.prototype.removeChildren = function () {
            var _this = this;
            var children = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                children[_i] = arguments[_i];
            }
            if (!children.length)
                return this.spliceChildren(0);
            children.forEach(function (child) { _this.removeChild(child); });
            return children;
        };
        Container.prototype.removeChildrenAt = function (beginIndex, endIndex) {
            if (beginIndex === void 0) { beginIndex = 0; }
            if (endIndex === void 0) { endIndex = this.children.length; }
            var begin = beginIndex;
            var end = typeof endIndex === 'number' ? endIndex : this.children.length;
            var range = end - begin;
            if (range > 0 && range <= end) {
                return this.spliceChildren(begin, range);
            }
            else if (range === 0 && this.children.length === 0) {
                return [];
            }
            throw new RangeError('removeChildren: numeric values are outside the acceptable range.');
        };
        Container.prototype.spliceChildren = function (beginIndex, count) {
            var removed = this.children.splice(beginIndex, count);
            if (!removed.length)
                return [];
            for (var i = 0; i < removed.length; ++i) {
                removed[i].parent = null;
                if (removed[i].transform) {
                    removed[i].transform._parentID = -1;
                }
            }
            this._boundsID++;
            this.onChildrenChange(beginIndex);
            for (var i = 0; i < removed.length; ++i) {
                removed[i]._onDispatchBubbledEvent(Event.REMOVED_FROM_STAGE);
            }
            return removed;
        };
        Container.prototype.updateTransform = function () {
            _super.prototype.updateTransform.call(this);
            for (var i = 0, j = this.children.length; i < j; ++i) {
                var child = this.children[i];
                if (child.visible) {
                    child.updateTransform();
                }
            }
        };
        Container.prototype.calculateBounds = function () {
            if (this._lastBoundsID == this._boundsID)
                return;
            this._lastBoundsID = this._boundsID;
            this._bounds.clear();
            this._calculateBounds();
            for (var i = 0; i < this.children.length; i++) {
                var child = this.children[i];
                if (!child.visible || !child.renderable) {
                    continue;
                }
                child.calculateBounds();
                if (child._mask) {
                    child._mask.calculateBounds();
                    if (child._bounds.x < child._mask._bounds.x) {
                        child._bounds.x = child._mask._bounds.x;
                    }
                    if (child._bounds.y < child._mask._bounds.y) {
                        child._bounds.y = child._mask._bounds.y;
                    }
                    if (child._bounds.width > child._mask._bounds.width) {
                        child._bounds.width = child._mask._bounds.width;
                    }
                    if (child._bounds.height > child._mask._bounds.height) {
                        child._bounds.height = child._mask._bounds.height;
                    }
                    Rectangle.createFromRects(this._bounds, child._bounds);
                }
                else if (child.filterArea) ;
                else {
                    Rectangle.createFromRects(this._bounds, child._bounds);
                }
            }
        };
        Container.prototype._calculateBounds = function () {
        };
        Container.prototype.hitTestPoint = function (globalPoint, isMouseEvent) {
            if (isMouseEvent === void 0) { isMouseEvent = false; }
            if (!this.visible)
                return null;
            if (isMouseEvent && !this.mouseChildren)
                return null;
            var children = this.children;
            var length = children.length;
            var child, hitDisplayObject;
            for (var i = length - 1; i >= 0; i--) {
                child = children[i];
                if (child.isUsedToMask)
                    continue;
                if (child.mask && !child.mask.hitTestPoint(globalPoint, isMouseEvent))
                    continue;
                hitDisplayObject = child.hitTestPoint(globalPoint, isMouseEvent);
                if (hitDisplayObject)
                    return hitDisplayObject;
            }
            return null;
        };
        Container.prototype.renderWebGL = function (renderer) {
            if (!this.visible || this._worldAlpha <= 0 || !this.renderable) {
                return;
            }
            if (this.mask || (this.filters && this.filters.length)) {
                this.renderAdvancedWebGL(renderer);
            }
            else {
                this._renderWebGL(renderer);
                for (var i = 0, j = this.children.length; i < j; ++i) {
                    this.children[i].renderWebGL(renderer);
                }
            }
        };
        Container.prototype.renderAdvancedWebGL = function (renderer) {
            renderer.batchManager.flush();
            var filters = this.filters;
            if (filters) {
                if (!this._enabledFilters)
                    this._enabledFilters = [];
                this._enabledFilters.length = 0;
                for (var i = 0; i < filters.length; i++) {
                    if (filters[i].enabled)
                        this._enabledFilters.push(filters[i]);
                }
                if (this._enabledFilters.length)
                    renderer.filterManager.pushFilter(this, this._enabledFilters);
            }
            var mask = this.mask;
            if (mask) {
                renderer.maskManager.pushMask(this, this.mask);
            }
            this._renderWebGL(renderer);
            for (var i = 0, j = this.children.length; i < j; i++) {
                this.children[i].renderWebGL(renderer);
            }
            renderer.batchManager.flush();
            if (mask) {
                renderer.maskManager.popMask(this, this.mask);
            }
            if (filters && this._enabledFilters && this._enabledFilters.length)
                renderer.filterManager.popFilter();
        };
        Container.prototype._renderWebGL = function (renderer) {
        };
        Container.prototype.renderCanvas = function (renderer) {
            if (!this.visible || this._worldAlpha <= 0 || !this.renderable) {
                return;
            }
            if (this.mask) {
                renderer.maskManager.pushMask(this.mask);
            }
            this._renderCanvas(renderer);
            for (var i = 0, j = this.children.length; i < j; ++i) {
                this.children[i].renderCanvas(renderer);
            }
            if (this.mask) {
                renderer.maskManager.popMask(renderer);
            }
        };
        Container.prototype._renderCanvas = function (renderer) {
        };
        Container.prototype.update = function () {
            if (!this.visible)
                return;
            _super.prototype.update.call(this);
            var len = this.children.length;
            for (var i = len - 1; i >= 0; i--) {
                var child = this.children[i];
                if (child.visible)
                    child.update();
            }
        };
        Container.prototype._onDispatchBubbledEvent = function (type) {
            var s = this;
            var len = s.children.length;
            if (type == Event.REMOVED_FROM_STAGE && !s.stage)
                return;
            _super.prototype._onDispatchBubbledEvent.call(this, type);
            for (var i = 0; i < len; i++) {
                s.children[i]._onDispatchBubbledEvent(type);
            }
        };
        Container.prototype.destroy = function () {
            var s = this;
            for (var i = s.children.length - 1; i >= 0; i--) {
                s.children[i].destroy();
            }
            _super.prototype.destroy.call(this);
            this.mouseChildren = false;
        };
        Object.defineProperty(Container.prototype, "width", {
            get: function () {
                return this.scale.x * this.getLocalBounds().width;
            },
            set: function (value) {
                var width = this.getLocalBounds().width;
                if (width !== 0) {
                    this.scale.x = value / width;
                }
                else {
                    this.scale.x = 1;
                }
                this._width = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Container.prototype, "height", {
            get: function () {
                return this.scale.y * this.getLocalBounds().height;
            },
            set: function (value) {
                var height = this.getLocalBounds().height;
                if (height !== 0) {
                    this.scale.y = value / height;
                }
                else {
                    this.scale.y = 1;
                }
                this._height = value;
            },
            enumerable: true,
            configurable: true
        });
        Container._getElementsByName = function (rex, root, isOnlyOne, isRecursive, resultList) {
            var len = root.children.length;
            if (len > 0) {
                var name = void 0;
                var child = void 0;
                for (var i = 0; i < len; i++) {
                    child = root.children[i];
                    name = child.name;
                    if (name && name != "") {
                        if (rex.test(name)) {
                            resultList[resultList.length] = child;
                            if (isOnlyOne) {
                                return;
                            }
                        }
                    }
                    if (isRecursive) {
                        if (child["children"] != null) {
                            Container._getElementsByName(rex, child, isOnlyOne, isRecursive, resultList);
                        }
                    }
                }
            }
        };
        return Container;
    }(DisplayObject));
    Container.prototype.containerUpdateTransform = Container.prototype.updateTransform;

    function mapPremultipliedBlendModes() {
        var pm = [];
        var npm = [];
        for (var i = 0; i < 32; i++) {
            pm[i] = i;
            npm[i] = i;
        }
        pm[exports.BLEND_MODES.NORMAL_NPM] = exports.BLEND_MODES.NORMAL;
        pm[exports.BLEND_MODES.ADD_NPM] = exports.BLEND_MODES.ADD;
        pm[exports.BLEND_MODES.SCREEN_NPM] = exports.BLEND_MODES.SCREEN;
        npm[exports.BLEND_MODES.NORMAL] = exports.BLEND_MODES.NORMAL_NPM;
        npm[exports.BLEND_MODES.ADD] = exports.BLEND_MODES.ADD_NPM;
        npm[exports.BLEND_MODES.SCREEN] = exports.BLEND_MODES.SCREEN_NPM;
        var array = [];
        array.push(npm);
        array.push(pm);
        return array;
    }

    function createCanvas() {
        return document && document.createElement("canvas") || my._createOffscreenCanvas();
    }
    var contentByCanvas;
    function initedByCanvas(canvas) {
        contentByCanvas = {
            createImage: canvas.createImage.bind(canvas),
            requestAnimationFrame: canvas.requestAnimationFrame.bind(canvas),
            cancelAnimationFrame: canvas.cancelAnimationFrame.bind(canvas),
        };
    }
    function destroyCanvasContent() {
        if (contentByCanvas) {
            contentByCanvas.createImage = null;
            contentByCanvas.requestAnimationFrame = null;
            contentByCanvas.cancelAnimationFrame = null;
            contentByCanvas = null;
        }
    }
    function getCreateImage() {
        return contentByCanvas && contentByCanvas.createImage || (function () { return new Image(); });
    }
    function getRequestAnimationFrame() {
        return contentByCanvas && contentByCanvas.requestAnimationFrame || window.requestAnimationFrame.bind(window);
    }
    function getCancelAnimationFrame() {
        return contentByCanvas && contentByCanvas.cancelAnimationFrame || window.cancelAnimationFrame.bind(window);
    }

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

    var CanvasGraphicsRenderer = (function () {
        function CanvasGraphicsRenderer(renderer) {
            this.renderer = renderer;
        }
        CanvasGraphicsRenderer.prototype.render = function (graphics) {
            var renderer = this.renderer;
            var context = renderer.context;
            var _worldAlpha = graphics._worldAlpha;
            var transform = graphics.transform.worldMatrix;
            context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx, transform.ty);
            renderer.setBlendMode(graphics.blendMode);
            for (var i = 0; i < graphics.graphicsData.length; i++) {
                var data = graphics.graphicsData[i];
                var shape = data.shape;
                var fillStyle = data.fillStyle;
                var lineStyle = data.lineStyle;
                var fillColor = fillStyle.color;
                var lineColor = lineStyle.color;
                context.lineWidth = lineStyle.width;
                var ccw = true;
                if (data.type === exports.SHAPES.POLY) {
                    context.beginPath();
                    var points = shape.points;
                    context.moveTo(points[0], points[1]);
                    for (var m = 1; m < points.length / 2; ++m) {
                        context.lineTo(points[m * 2], points[(m * 2) + 1]);
                    }
                    ccw = !judgeCcw(points);
                }
                else if (data.type === exports.SHAPES.RECT) {
                    if (data.holes.length) {
                        context.beginPath();
                        context.moveTo(shape.x, shape.y);
                        context.lineTo(shape.x + shape.width, shape.y);
                        context.lineTo(shape.x + shape.width, shape.y + shape.height);
                        context.lineTo(shape.x, shape.y + shape.height);
                        context.lineTo(shape.x, shape.y);
                    }
                    else {
                        if (fillStyle.visible) {
                            context.globalAlpha = fillStyle.alpha * _worldAlpha;
                            context.fillStyle = "#" + ("00000" + (fillColor | 0).toString(16)).substr(-6);
                            context.fillRect(shape["x"], shape["y"], shape["width"], shape["height"]);
                        }
                        if (lineStyle.visible) {
                            context.globalAlpha = lineStyle.alpha * _worldAlpha;
                            context.strokeStyle = "#" + ("00000" + (lineColor | 0).toString(16)).substr(-6);
                            context.strokeRect(shape["x"], shape["y"], shape["width"], shape["height"]);
                        }
                        continue;
                    }
                }
                else if (data.type === exports.SHAPES.CIRC) {
                    context.beginPath();
                    context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI, false);
                }
                else if (data.type === exports.SHAPES.ELIP) {
                    var w = shape.width * 2;
                    var h = shape.height * 2;
                    var x = shape.x - (w / 2);
                    var y = shape.y - (h / 2);
                    context.beginPath();
                    var kappa = 0.5522848;
                    var ox = (w / 2) * kappa;
                    var oy = (h / 2) * kappa;
                    var xe = x + w;
                    var ye = y + h;
                    var xm = x + (w / 2);
                    var ym = y + (h / 2);
                    context.moveTo(x, ym);
                    context.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
                    context.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
                    context.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
                    context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
                }
                else if (data.type === exports.SHAPES.RREC) {
                    var rx = shape.x;
                    var ry = shape.y;
                    var width = shape.width;
                    var height = shape.height;
                    var radius = shape.radius;
                    var maxRadius = Math.min(width, height) / 2 | 0;
                    radius = radius > maxRadius ? maxRadius : radius;
                    context.beginPath();
                    context.moveTo(rx, ry + radius);
                    context.quadraticCurveTo(rx, ry, rx + radius, ry);
                    context.lineTo(rx + width - radius, ry);
                    context.quadraticCurveTo(rx + width, ry, rx + width, ry + radius);
                    context.lineTo(rx + width, ry + height - radius);
                    context.quadraticCurveTo(rx + width, ry + height, rx + width - radius, ry + height);
                    context.lineTo(rx + radius, ry + height);
                    context.quadraticCurveTo(rx, ry + height, rx, ry + height - radius);
                    context.lineTo(rx, ry + radius);
                }
                for (var j = 0; j < data.holes.length; j++) {
                    holePath(data.holes[i], context, ccw);
                }
                if (fillStyle.visible) {
                    context.globalAlpha = fillStyle.alpha * _worldAlpha;
                    context.fillStyle = "#" + ("00000" + (fillColor | 0).toString(16)).substr(-6);
                    context.fill();
                }
                if (lineStyle.visible) {
                    if (shape.closed)
                        context.closePath();
                    context.globalAlpha = lineStyle.alpha * _worldAlpha;
                    context.strokeStyle = "#" + ("00000" + (lineColor | 0).toString(16)).substr(-6);
                    context.stroke();
                }
            }
        };
        CanvasGraphicsRenderer.prototype.destroy = function () {
            this.renderer = null;
        };
        return CanvasGraphicsRenderer;
    }());
    function holePath(graphicsData, context, ccw) {
        if (ccw === void 0) { ccw = true; }
        var type = graphicsData.type;
        var shape = graphicsData.shape;
        switch (type) {
            case exports.SHAPES.POLY:
                var points = shape.points;
                var hCcw = judgeCcw(points);
                if (ccw == hCcw) {
                    context.moveTo(points[0], points[1]);
                    for (var m = 1; m < points.length / 2; ++m) {
                        context.lineTo(points[m * 2], points[(m * 2) + 1]);
                    }
                }
                else {
                    context.moveTo(points[points.length - 2], points[points.length - 1]);
                    for (var m = points.length / 2 - 2; m >= 0; --m) {
                        context.lineTo(points[m * 2], points[(m * 2) + 1]);
                    }
                }
                if (points[0] === points[points.length - 2] && points[1] === points[points.length - 1]) ;
                else {
                    context.closePath();
                }
                break;
            case exports.SHAPES.RECT:
                context.moveTo(shape.x, shape.y);
                if (ccw) {
                    context.lineTo(shape.x, shape.y + shape.height);
                    context.lineTo(shape.x + shape.width, shape.y + shape.height);
                    context.lineTo(shape.x + shape.width, shape.y);
                    context.lineTo(shape.x, shape.y);
                }
                else {
                    context.lineTo(shape.x + shape.width, shape.y);
                    context.lineTo(shape.x + shape.width, shape.y + shape.height);
                    context.lineTo(shape.x, shape.y + shape.height);
                    context.lineTo(shape.x, shape.y);
                }
                break;
            case exports.SHAPES.CIRC:
                context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI, ccw);
                break;
            case exports.SHAPES.ELIP:
                var w = shape.width * 2;
                var h = shape.height * 2;
                var x = shape.x - (w / 2);
                var y = shape.y - (h / 2);
                var kappa = 0.5522848;
                var ox = (w / 2) * kappa;
                var oy = (h / 2) * kappa;
                var xe = x + w;
                var ye = y + h;
                var xm = x + (w / 2);
                var ym = y + (h / 2);
                context.moveTo(x, ym);
                if (ccw) {
                    context.bezierCurveTo(xm - ox, ye, x, ym + oy, xm, ye);
                    context.bezierCurveTo(xe, ym + oy, xm + ox, ye, xe, ym);
                    context.bezierCurveTo(xm + ox, y, xe, ym - oy, xm, y);
                    context.bezierCurveTo(x, ym - oy, xm - ox, y, x, ym);
                }
                else {
                    context.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
                    context.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
                    context.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
                    context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
                }
                break;
            case exports.SHAPES.RREC:
                var rx = shape.x;
                var ry = shape.y;
                var width = shape.width;
                var height = shape.height;
                var radius = shape.radius;
                var maxRadius = Math.min(width, height) / 2 | 0;
                radius = radius > maxRadius ? maxRadius : radius;
                context.moveTo(rx, ry + radius);
                if (ccw) {
                    context.lineTo(rx, ry + height - radius);
                    context.quadraticCurveTo(rx, ry + height, rx + radius, ry + height);
                    context.lineTo(rx + width - radius, ry + height);
                    context.quadraticCurveTo(rx + width, ry + height, rx + width, ry + height - radius);
                    context.lineTo(rx + width, ry + radius);
                    context.quadraticCurveTo(rx + width, ry, rx + width - radius, ry);
                    context.lineTo(rx + radius, ry);
                    context.quadraticCurveTo(rx, ry, rx, ry + radius);
                }
                else {
                    context.quadraticCurveTo(rx, ry, rx + radius, ry);
                    context.lineTo(rx + width - radius, ry);
                    context.quadraticCurveTo(rx + width, ry, rx + width, ry + radius);
                    context.lineTo(rx + width, ry + height - radius);
                    context.quadraticCurveTo(rx + width, ry + height, rx + width - radius, ry + height);
                    context.lineTo(rx + radius, ry + height);
                    context.quadraticCurveTo(rx, ry + height, rx, ry + height - radius);
                    context.lineTo(rx, ry + radius);
                }
                break;
        }
    }
    function judgeCcw(points) {
        var vector = [];
        if (points[0] === points[points.length - 2] && points[1] === points[points.length - 1]) ;
        for (var i = 0; i < points.length - 2; i += 2) {
            vector.push(points[i + 2] - points[i], points[i + 3] - points[i + 1]);
        }
        if (!(points[0] === points[points.length - 2]) || !(points[1] === points[points.length - 1])) {
            vector.push(points[0] - points[points.length - 2], points[1] - points[points.length - 1]);
        }
        var sum = 0;
        for (var i = 0; i < vector.length - 2; i += 2) {
            sum = sum + vector[i] * vector[i + 3] - vector[i + 1] * vector[i + 2];
        }
        sum = sum + vector[vector.length - 2] * vector[1] - vector[vector.length - 1] * vector[0];
        return !(sum > 0);
    }

    var CanvasMaskManager = (function (_super) {
        tslib_1.__extends(CanvasMaskManager, _super);
        function CanvasMaskManager(renderer) {
            var _this = _super.call(this) || this;
            _this._instanceType = "CanvasMaskManager";
            _this.renderer = renderer;
            return _this;
        }
        CanvasMaskManager.prototype.pushMask = function (maskData) {
            var renderer = this.renderer;
            renderer.context.save();
            var transform = maskData.transform.worldMatrix;
            renderer.context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx, transform.ty);
            if (maskData.instanceType == "Shape") {
                maskData["_drawShape"](renderer.context);
            }
            else {
                this.renderGraphicsShape(maskData);
            }
            renderer.context.clip();
        };
        CanvasMaskManager.prototype.renderGraphicsShape = function (graphics) {
            var context = this.renderer.context;
            var len = graphics.graphicsData.length;
            if (len === 0)
                return;
            context.beginPath();
            for (var i = 0; i < len; i++) {
                var data = graphics.graphicsData[i];
                var shape = data.shape;
                var ccw = true;
                if (data.type === exports.SHAPES.POLY) {
                    var points = shape.points;
                    context.moveTo(points[0], points[1]);
                    for (var j = 1; j < points.length / 2; j++) {
                        context.lineTo(points[j * 2], points[(j * 2) + 1]);
                    }
                    ccw = !judgeCcw(points);
                    if (points[0] === points[points.length - 2] && points[1] === points[points.length - 1]) ;
                    else {
                        context.closePath();
                    }
                }
                else if (data.type === exports.SHAPES.RECT) {
                    context.rect(shape.x, shape.y, shape.width, shape.height);
                }
                else if (data.type === exports.SHAPES.CIRC) {
                    context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI);
                }
                else if (data.type === exports.SHAPES.ELIP) {
                    var w = shape.width * 2;
                    var h = shape.height * 2;
                    var x = shape.x - (w / 2);
                    var y = shape.y - (h / 2);
                    var kappa = 0.5522848;
                    var ox = (w / 2) * kappa;
                    var oy = (h / 2) * kappa;
                    var xe = x + w;
                    var ye = y + h;
                    var xm = x + (w / 2);
                    var ym = y + (h / 2);
                    context.moveTo(x, ym);
                    context.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
                    context.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
                    context.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
                    context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
                }
                else if (data.type === exports.SHAPES.RREC) {
                    var rx = shape.x;
                    var ry = shape.y;
                    var width = shape.width;
                    var height = shape.height;
                    var radius = shape.radius;
                    var maxRadius = Math.min(width, height) / 2 | 0;
                    radius = radius > maxRadius ? maxRadius : radius;
                    context.moveTo(rx, ry + radius);
                    context.quadraticCurveTo(rx, ry, rx + radius, ry);
                    context.lineTo(rx + width - radius, ry);
                    context.quadraticCurveTo(rx + width, ry, rx + width, ry + radius);
                    context.lineTo(rx + width, ry + height - radius);
                    context.quadraticCurveTo(rx + width, ry + height, rx + width - radius, ry + height);
                    context.lineTo(rx + radius, ry + height);
                    context.quadraticCurveTo(rx, ry + height, rx, ry + height - radius);
                    context.lineTo(rx, ry + radius);
                }
                for (var j = 0; j < data.holes.length; j++) {
                    holePath(data.holes[i], context, ccw);
                }
            }
        };
        CanvasMaskManager.prototype.popMask = function (renderer) {
            renderer.context.restore();
        };
        CanvasMaskManager.prototype.destroy = function () {
        };
        return CanvasMaskManager;
    }(HashObject));

    var canvasRenderWorldTransform = new Matrix();
    var CanvasSpriteRenderer = (function () {
        function CanvasSpriteRenderer(renderer) {
            this.renderer = renderer;
        }
        CanvasSpriteRenderer.prototype.render = function (sprite) {
            var texture = sprite._texture;
            var renderer = this.renderer;
            var width = texture._frame.width;
            var height = texture._frame.height;
            var wt = sprite.transform.worldMatrix;
            var dx = 0;
            var dy = 0;
            if (texture.orig.width <= 0 || texture.orig.height <= 0 || !texture.baseTexture.source)
                return;
            if (!texture.valid)
                return;
            renderer.setBlendMode(sprite.blendMode);
            renderer.context.globalAlpha = sprite._worldAlpha;
            if (sprite._anchorTexture) {
                if (texture.trim) {
                    dx = (texture.trim.width / 2) + texture.trim.x - (sprite._anchorTexture.x * texture.orig.width);
                    dy = (texture.trim.height / 2) + texture.trim.y - (sprite._anchorTexture.y * texture.orig.height);
                }
                else {
                    dx = (0.5 - sprite._anchorTexture.x) * texture.orig.width;
                    dy = (0.5 - sprite._anchorTexture.y) * texture.orig.height;
                }
                if (texture.rotate) {
                    canvasRenderWorldTransform.copy(wt);
                    wt = canvasRenderWorldTransform;
                    GroupD8.matrixAppendRotationInv(wt, texture.rotate, dx, dy);
                    dx = 0;
                    dy = 0;
                }
                dx -= width / 2;
                dy -= height / 2;
            }
            else {
                dx = sprite["offsetX"] || 0;
                dy = sprite["offsetY"] || 0;
            }
            renderer.context.setTransform(wt.a, wt.b, wt.c, wt.d, wt.tx, wt.ty);
            var outerBlend = renderer._outerBlend;
            if (outerBlend) {
                renderer.context.save();
                renderer.context.beginPath();
                renderer.context.rect(dx, dy, width, height);
                renderer.context.clip();
            }
            if (sprite.tint !== 0xFFFFFF) {
                if (sprite.cachedTint !== sprite.tint || sprite.tintedTexture.tintId !== sprite._texture._updateID) {
                    sprite.cachedTint = sprite.tint;
                    sprite.tintedTexture = getTintedTexture(sprite._texture, sprite.tint);
                }
                renderer.context.drawImage(sprite.tintedTexture, 0, 0, width, height, dx, dy, width, height);
            }
            else {
                renderer.context.drawImage(texture.baseTexture.source, texture._frame.x, texture._frame.y, width, height, dx, dy, width, height);
            }
            if (outerBlend)
                renderer.context.restore();
            renderer.setBlendMode(exports.BLEND_MODES.NORMAL);
        };
        CanvasSpriteRenderer.prototype.destroy = function () {
            this.renderer = null;
        };
        return CanvasSpriteRenderer;
    }());

    var SystemRenderer = (function (_super) {
        tslib_1.__extends(SystemRenderer, _super);
        function SystemRenderer() {
            var _this = _super.call(this) || this;
            _this.transparent = true;
            _this._backgroundColor = 0x000000;
            _this._backgroundColorRgba = [0, 0, 0, 0];
            _this._backgroundColorString = '#000000';
            _this.backgroundColor = _this._backgroundColor;
            _this._tempDisplayObjectParent = new Container();
            _this._lastObjectRendered = _this._tempDisplayObjectParent;
            return _this;
        }
        SystemRenderer.prototype.resize = function (width, height) {
            this.width = width;
            this.height = height;
        };
        SystemRenderer.prototype.render = function (displayObject, renderTexture, transform) {
        };
        SystemRenderer.prototype.destroy = function () {
            this.type = exports.RENDERER_TYPE.UNKNOWN;
            this.transparent = false;
            this._backgroundColor = 0;
            this._backgroundColorRgba = null;
            this._backgroundColorString = null;
            this._tempDisplayObjectParent = null;
            this._lastObjectRendered = null;
        };
        Object.defineProperty(SystemRenderer.prototype, "backgroundColor", {
            get: function () {
                return this._backgroundColor;
            },
            set: function (value) {
                if (this._backgroundColor === value)
                    return;
                this._backgroundColor = value;
                this._backgroundColorString = hex2string(value);
                hex2rgb$1(value, this._backgroundColorRgba);
            },
            enumerable: true,
            configurable: true
        });
        return SystemRenderer;
    }(EventDispatcher));

    var CanvasRenderTarget = (function () {
        function CanvasRenderTarget(width, height) {
            this.canvas = createCanvas();
            this.resize(width, height);
            this.context = this.canvas.getContext('2d');
            this.resize(width, height);
        }
        CanvasRenderTarget.prototype.clear = function () {
            this.context.setTransform(1, 0, 0, 1, 0, 0);
            this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
        };
        CanvasRenderTarget.prototype.resize = function (width, height) {
            this.canvas.width = width;
            this.canvas.height = height;
        };
        CanvasRenderTarget.prototype.destroy = function () {
            this.context = null;
            this.canvas = null;
        };
        Object.defineProperty(CanvasRenderTarget.prototype, "width", {
            get: function () {
                return this.canvas.width;
            },
            set: function (val) {
                this.canvas.width = val;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(CanvasRenderTarget.prototype, "height", {
            get: function () {
                return this.canvas.height;
            },
            set: function (val) {
                this.canvas.height = val;
            },
            enumerable: true,
            configurable: true
        });
        return CanvasRenderTarget;
    }());

    var CanvasRenderer = (function (_super) {
        tslib_1.__extends(CanvasRenderer, _super);
        function CanvasRenderer(context, width, height) {
            var _this = _super.call(this) || this;
            _this.type = exports.RENDERER_TYPE.CANVAS;
            _this._instanceType = "CanvasRenderer";
            _this.rootContext = context;
            _this.maskManager = new CanvasMaskManager(_this);
            _this.plugins = {
                sprite: null,
                graphics: null,
            };
            _this.plugins.sprite = new CanvasSpriteRenderer(_this);
            _this.plugins.graphics = new CanvasGraphicsRenderer(_this);
            _this.blendModes = mapCanvasBlendModes();
            _this._activeBlendMode = null;
            _this._outerBlend = false;
            _this.resize(width, height);
            return _this;
        }
        CanvasRenderer.prototype.render = function (displayObject, renderTexture, transform) {
            this.dispatchEvent('prerender');
            var renderingToScreen = !renderTexture;
            if (renderTexture) {
                renderTexture = renderTexture.baseTexture || renderTexture;
                if (!renderTexture._canvasRenderTarget) {
                    renderTexture._canvasRenderTarget = new CanvasRenderTarget(renderTexture.width, renderTexture.height);
                    renderTexture.source = renderTexture._canvasRenderTarget.canvas;
                    renderTexture.valid = true;
                }
                else {
                    renderTexture._canvasRenderTarget.clear();
                    renderTexture._canvasRenderTarget.resize(renderTexture.width, renderTexture.height);
                }
                this.context = renderTexture._canvasRenderTarget.context;
            }
            else {
                this.context = this.rootContext;
            }
            var context = this.context;
            if (!renderTexture) {
                this._lastObjectRendered = displayObject;
            }
            displayObject.update();
            var cacheParent = displayObject.parent;
            var tempWt = this._tempDisplayObjectParent.transform.worldMatrix;
            if (transform) {
                tempWt.copy(transform);
                this._tempDisplayObjectParent.transform._worldID = -1;
            }
            else {
                tempWt.identity();
            }
            displayObject.parent = this._tempDisplayObjectParent;
            displayObject.updateTransform();
            displayObject.parent = cacheParent;
            context.save();
            context.setTransform(1, 0, 0, 1, 0, 0);
            context.globalAlpha = 1;
            this._activeBlendMode = exports.BLEND_MODES.NORMAL;
            this._outerBlend = false;
            context.globalCompositeOperation = this.blendModes[exports.BLEND_MODES.NORMAL];
            if (renderingToScreen) {
                if (this.transparent) {
                    context.clearRect(0, 0, this.width, this.height);
                }
                else {
                    context.fillStyle = this._backgroundColorString;
                    context.fillRect(0, 0, this.width, this.height);
                }
            }
            displayObject.renderCanvas(this);
            context.restore();
            this.dispatchEvent('postrender');
        };
        CanvasRenderer.prototype.setBlendMode = function (blendMode, readyForOuterBlend) {
            if (readyForOuterBlend === void 0) { readyForOuterBlend = false; }
            var outerBlend = blendMode === exports.BLEND_MODES.SRC_IN
                || blendMode === exports.BLEND_MODES.SRC_OUT
                || blendMode === exports.BLEND_MODES.DST_IN
                || blendMode === exports.BLEND_MODES.DST_ATOP;
            if (!readyForOuterBlend && outerBlend) {
                blendMode = exports.BLEND_MODES.NORMAL;
            }
            if (this._activeBlendMode === blendMode) {
                return;
            }
            this._activeBlendMode = blendMode;
            this._outerBlend = outerBlend;
            this.context.globalCompositeOperation = this.blendModes[blendMode];
        };
        CanvasRenderer.prototype.destroy = function () {
            this.destroyPlugins();
            _super.prototype.destroy.call(this);
            this.context = null;
            this.maskManager.destroy();
            this.maskManager = null;
        };
        CanvasRenderer.prototype.destroyPlugins = function () {
            this.plugins.sprite.destroy();
            this.plugins.graphics.destroy();
        };
        return CanvasRenderer;
    }(SystemRenderer));

    var _dRender = null;
    var _dCanvas;
    var tempMatrix = new Matrix();
    function toDisplayDataURL(obj, rect, typeInfo, bgColor) {
        if (rect === void 0) { rect = null; }
        if (typeInfo === void 0) { typeInfo = null; }
        var bounds = obj.getLocalBounds();
        var w = rect ? rect.width : bounds.width;
        var h = rect ? rect.height : bounds.height;
        var x = rect ? rect.x : bounds.x;
        var y = rect ? rect.y : bounds.y;
        if (!_dRender) {
            var canvas = createCanvas();
            canvas.width = w;
            canvas.height = h;
            _dCanvas = canvas;
            _dRender = new CanvasRenderer(canvas.getContext("2d"), w, h);
        }
        else {
            _dCanvas.width = w;
            _dCanvas.height = h;
        }
        if (!typeInfo) {
            typeInfo = { type: "png" };
        }
        obj.transform.updateLocalMatrix();
        tempMatrix.copy(obj.transform.localMatrix);
        tempMatrix.invert();
        tempMatrix.tx -= x;
        tempMatrix.ty -= y;
        _dRender.render(obj, null, tempMatrix);
        return _dCanvas.toDataURL("image/" + typeInfo.type, typeInfo.quality);
    }

    function determineCrossOrigin(url, loc) {
        if (url.indexOf('data:') === 0) {
            return '';
        }
        return 'anonymous';
    }

    var result = null;
    function createColoredCanvas(color) {
        var canvas = createCanvas();
        canvas.width = 6;
        canvas.height = 1;
        var context = canvas.getContext('2d');
        context.fillStyle = color;
        context.fillRect(0, 0, 6, 1);
        return canvas;
    }
    function canUseNewCanvasBlendModes() {
        if (result != null)
            return result;
        if (typeof document === 'undefined') {
            result = false;
            return result;
        }
        var magenta = createColoredCanvas('#ff00ff');
        var yellow = createColoredCanvas('#ffff00');
        var canvas = createCanvas();
        canvas.width = 6;
        canvas.height = 1;
        var context = canvas.getContext('2d');
        context.globalCompositeOperation = 'multiply';
        context.drawImage(magenta, 0, 0);
        context.drawImage(yellow, 2, 0);
        var imageData = context.getImageData(2, 0, 1, 1);
        if (!imageData) {
            result = false;
            return result;
        }
        var data = imageData.data;
        result = (data[0] === 255 && data[1] === 0 && data[2] === 0);
        return result;
    }

    var cacheStepsPerColorChannel = 8;
    var defaultCanvas;
    var tintMethod = canUseNewCanvasBlendModes() ? tintWithMultiply : tintWithPerPixel;
    function getTintedTexture(texture, color) {
        color = roundColor(color);
        var stringColor = "#" + ("00000" + (color | 0).toString(16)).substr(-6);
        texture["tintCache"] = texture["tintCache"] || {};
        var cachedTexture = texture["tintCache"][stringColor];
        var canvas;
        if (cachedTexture) {
            if (cachedTexture.tintId === texture._updateID) {
                return texture["tintCache"][stringColor];
            }
            canvas = texture["tintCache"][stringColor];
        }
        else {
            canvas = defaultCanvas || createCanvas();
        }
        tintMethod(texture, color, canvas);
        canvas.tintId = texture._updateID;
        {
            texture["tintCache"][stringColor] = canvas;
            defaultCanvas = null;
        }
        return canvas;
    }
    function tintWithMultiply(texture, color, canvas) {
        var context = canvas.getContext('2d');
        var crop = texture._frame.clone();
        canvas.width = Math.ceil(crop.width);
        canvas.height = Math.ceil(crop.height);
        context.save();
        context.fillStyle = "#" + ("00000" + (color | 0).toString(16)).substr(-6);
        context.fillRect(0, 0, crop.width, crop.height);
        context.globalCompositeOperation = 'multiply';
        context.drawImage(texture.baseTexture.source, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height);
        context.globalCompositeOperation = 'destination-atop';
        context.drawImage(texture.baseTexture.source, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height);
        context.restore();
    }
    function tintWithPerPixel(texture, color, canvas) {
        var context = canvas.getContext('2d');
        var crop = texture._frame.clone();
        canvas.width = Math.ceil(crop.width);
        canvas.height = Math.ceil(crop.height);
        context.save();
        context.globalCompositeOperation = 'copy';
        context.drawImage(texture.baseTexture.source, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height);
        context.restore();
        var rgbValues = hex2rgb(color);
        var r = rgbValues[0];
        var g = rgbValues[1];
        var b = rgbValues[2];
        var pixelData = context.getImageData(0, 0, crop.width, crop.height);
        var pixels = pixelData.data;
        for (var i = 0; i < pixels.length; i += 4) {
            pixels[i + 0] *= r;
            pixels[i + 1] *= g;
            pixels[i + 2] *= b;
        }
        context.putImageData(pixelData, 0, 0);
    }
    function rgb2hex(rgb) {
        return (((rgb[0] * 255) << 16) + ((rgb[1] * 255) << 8) + (rgb[2] * 255 | 0));
    }
    function hex2rgb(hex, out) {
        out = out || [];
        out[0] = ((hex >> 16) & 0xFF) / 255;
        out[1] = ((hex >> 8) & 0xFF) / 255;
        out[2] = (hex & 0xFF) / 255;
        return out;
    }
    function roundColor(color) {
        var step = cacheStepsPerColorChannel;
        var rgbValues = hex2rgb(color);
        rgbValues[0] = Math.min(255, (rgbValues[0] / step) * step);
        rgbValues[1] = Math.min(255, (rgbValues[1] / step) * step);
        rgbValues[2] = Math.min(255, (rgbValues[2] / step) * step);
        return rgb2hex(rgbValues);
    }

    function mapWebGLBlendModes(gl, array) {
        if (array === void 0) { array = []; }
        array[exports.BLEND_MODES.NORMAL] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
        array[exports.BLEND_MODES.ADD] = [gl.ONE, gl.DST_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
        array[exports.BLEND_MODES.MULTIPLY] = [gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
        array[exports.BLEND_MODES.SCREEN] = [gl.ONE, gl.ONE_MINUS_SRC_COLOR, gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
        array[exports.BLEND_MODES.OVERLAY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
        array[exports.BLEND_MODES.DARKEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
        array[exports.BLEND_MODES.LIGHTEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
        array[exports.BLEND_MODES.COLOR_DODGE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
        array[exports.BLEND_MODES.COLOR_BURN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
        array[exports.BLEND_MODES.HARD_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
        array[exports.BLEND_MODES.SOFT_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
        array[exports.BLEND_MODES.DIFFERENCE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
        array[exports.BLEND_MODES.EXCLUSION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
        array[exports.BLEND_MODES.HUE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
        array[exports.BLEND_MODES.SATURATION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
        array[exports.BLEND_MODES.COLOR] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
        array[exports.BLEND_MODES.LUMINOSITY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
        array[exports.BLEND_MODES.NONE] = [0, 0];
        array[exports.BLEND_MODES.NORMAL_NPM] = [gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
        array[exports.BLEND_MODES.ADD_NPM] = [gl.SRC_ALPHA, gl.DST_ALPHA, gl.ONE, gl.DST_ALPHA];
        array[exports.BLEND_MODES.SCREEN_NPM] = [gl.SRC_ALPHA, gl.ONE_MINUS_SRC_COLOR, gl.ONE, gl.ONE_MINUS_SRC_COLOR];
        array[exports.BLEND_MODES.SRC_OVER] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
        array[exports.BLEND_MODES.SRC_IN] = [gl.DST_ALPHA, gl.ZERO];
        array[exports.BLEND_MODES.SRC_OUT] = [gl.ONE_MINUS_DST_ALPHA, gl.ZERO];
        array[exports.BLEND_MODES.SRC_ATOP] = [gl.DST_ALPHA, gl.ONE_MINUS_SRC_ALPHA];
        array[exports.BLEND_MODES.DST_OVER] = [gl.ONE_MINUS_DST_ALPHA, gl.ONE];
        array[exports.BLEND_MODES.DST_IN] = [gl.ZERO, gl.SRC_ALPHA];
        array[exports.BLEND_MODES.DST_OUT] = [gl.ZERO, gl.ONE_MINUS_SRC_ALPHA];
        array[exports.BLEND_MODES.DST_ATOP] = [gl.ONE_MINUS_DST_ALPHA, gl.SRC_ALPHA];
        array[exports.BLEND_MODES.ERASE] = [gl.ZERO, gl.ONE, gl.SRC_ALPHA, 0];
        array[exports.BLEND_MODES.SUBTRACT] = [gl.ONE, gl.ONE, gl.ONE, gl.ONE, gl.FUNC_REVERSE_SUBTRACT, gl.FUNC_ADD];
        return array;
    }

    function mapCanvasBlendModes(array) {
        if (array === void 0) { array = []; }
        if (canUseNewCanvasBlendModes()) {
            array[exports.BLEND_MODES.NORMAL] = 'source-over';
            array[exports.BLEND_MODES.ADD] = 'lighter';
            array[exports.BLEND_MODES.MULTIPLY] = 'multiply';
            array[exports.BLEND_MODES.SCREEN] = 'screen';
            array[exports.BLEND_MODES.OVERLAY] = 'overlay';
            array[exports.BLEND_MODES.DARKEN] = 'darken';
            array[exports.BLEND_MODES.LIGHTEN] = 'lighten';
            array[exports.BLEND_MODES.COLOR_DODGE] = 'color-dodge';
            array[exports.BLEND_MODES.COLOR_BURN] = 'color-burn';
            array[exports.BLEND_MODES.HARD_LIGHT] = 'hard-light';
            array[exports.BLEND_MODES.SOFT_LIGHT] = 'soft-light';
            array[exports.BLEND_MODES.DIFFERENCE] = 'difference';
            array[exports.BLEND_MODES.EXCLUSION] = 'exclusion';
            array[exports.BLEND_MODES.HUE] = 'hue';
            array[exports.BLEND_MODES.SATURATION] = 'saturate';
            array[exports.BLEND_MODES.COLOR] = 'color';
            array[exports.BLEND_MODES.LUMINOSITY] = 'luminosity';
        }
        else {
            array[exports.BLEND_MODES.NORMAL] = 'source-over';
            array[exports.BLEND_MODES.ADD] = 'lighter';
            array[exports.BLEND_MODES.MULTIPLY] = 'source-over';
            array[exports.BLEND_MODES.SCREEN] = 'source-over';
            array[exports.BLEND_MODES.OVERLAY] = 'source-over';
            array[exports.BLEND_MODES.DARKEN] = 'source-over';
            array[exports.BLEND_MODES.LIGHTEN] = 'source-over';
            array[exports.BLEND_MODES.COLOR_DODGE] = 'source-over';
            array[exports.BLEND_MODES.COLOR_BURN] = 'source-over';
            array[exports.BLEND_MODES.HARD_LIGHT] = 'source-over';
            array[exports.BLEND_MODES.SOFT_LIGHT] = 'source-over';
            array[exports.BLEND_MODES.DIFFERENCE] = 'source-over';
            array[exports.BLEND_MODES.EXCLUSION] = 'source-over';
            array[exports.BLEND_MODES.HUE] = 'source-over';
            array[exports.BLEND_MODES.SATURATION] = 'source-over';
            array[exports.BLEND_MODES.COLOR] = 'source-over';
            array[exports.BLEND_MODES.LUMINOSITY] = 'source-over';
        }
        array[exports.BLEND_MODES.NORMAL_NPM] = array[exports.BLEND_MODES.NORMAL];
        array[exports.BLEND_MODES.ADD_NPM] = array[exports.BLEND_MODES.ADD];
        array[exports.BLEND_MODES.SCREEN_NPM] = array[exports.BLEND_MODES.SCREEN];
        array[exports.BLEND_MODES.SRC_OVER] = 'source-over';
        array[exports.BLEND_MODES.SRC_IN] = 'source-in';
        array[exports.BLEND_MODES.SRC_OUT] = 'source-out';
        array[exports.BLEND_MODES.SRC_ATOP] = 'source-atop';
        array[exports.BLEND_MODES.DST_OVER] = 'destination-over';
        array[exports.BLEND_MODES.DST_IN] = 'destination-in';
        array[exports.BLEND_MODES.DST_OUT] = 'destination-out';
        array[exports.BLEND_MODES.DST_ATOP] = 'destination-atop';
        array[exports.BLEND_MODES.SUBTRACT] = 'source-over';
        return array;
    }

    var Loader = (function (_super) {
        tslib_1.__extends(Loader, _super);
        function Loader() {
            var _this = _super.call(this) || this;
            _this.caches = {};
            _this._instanceType = "Loader";
            return _this;
        }
        Loader.prototype.loadSheet = function (callback, url) {
            var _this = this;
            var pngFile = url.substring(0, url.lastIndexOf('.')) + '.png';
            this.loadImage(function (suc, data) {
                if (suc) {
                    _this.cache(pngFile, data);
                    if (_this.caches[url]) {
                        callback(true, { json: _this.caches[url], img: data });
                        _this.caches[url] = null;
                        _this.caches[pngFile] = null;
                    }
                }
                else {
                    callback(false, data);
                }
            }, pngFile);
            this.loadJson(function (suc, data) {
                if (suc) {
                    _this.cache(url, data);
                    if (_this.caches[pngFile]) {
                        callback(true, { json: data, img: _this.caches[pngFile] });
                        _this.caches[url] = null;
                        _this.caches[pngFile] = null;
                    }
                }
                else {
                    callback(false, data);
                }
            }, url);
        };
        Loader.prototype.loadJson = function (callback, url) {
            my.request({
                url: url,
                dataType: "json",
                success: function (res) {
                    callback(true, res.data);
                },
                fail: function (res) {
                    callback(false, res);
                }
            });
        };
        Loader.prototype.loadImage = function (callback, url) {
            var createImage = getCreateImage();
            if (!createImage) {
                callback(false);
                return;
            }
            var img = createImage();
            img.onload = function () {
                callback(true, img);
            };
            img.onerror = function () {
                callback(false);
            };
            if (url.indexOf('data:') !== 0)
                img.crossOrigin = "anonymous";
            img.src = url;
        };
        Loader.prototype.loadAudio = function (callback, url) {
            var innerAudioContext = my.createInnerAudioContext();
            innerAudioContext.src = url;
            innerAudioContext.onCanplay(function () {
                callback(true, innerAudioContext);
            });
            innerAudioContext.onError(function (res) {
                callback(false);
            });
        };
        Loader.prototype.cache = function (name, data) {
            if (this.caches[name]) {
                console.log("覆盖原先数据：" + name);
            }
            this.caches[name] = data;
        };
        return Loader;
    }(EventDispatcher));
    var GlobalLoader = new Loader();

    var BaseTexture = (function (_super) {
        tslib_1.__extends(BaseTexture, _super);
        function BaseTexture(source, scaleMode) {
            if (source === void 0) { source = null; }
            if (scaleMode === void 0) { scaleMode = exports.SCALE_MODES.LINEAR; }
            var _this = _super.call(this) || this;
            _this._touchedId = 0;
            _this.width = 100;
            _this.height = 100;
            _this.scaleMode = scaleMode;
            _this.hasLoaded = false;
            _this._isLoading = false;
            _this.source = null;
            _this.imageType = null;
            _this.premultipliedAlpha = true;
            _this.imageUrl = null;
            _this.isPowerOfTwo = false;
            _this.mipmap = true;
            _this.wrapMode = exports.WRAP_MODES.CLAMP;
            _this._glTextures = {};
            _this._enabledId = 0;
            _this.textureCacheIds = [];
            if (source) {
                if (source.data) {
                    _this._sourceChange(source);
                }
                else if (source.getContext) {
                    _this._sourceChange(source);
                }
                else {
                    if (source.complete) {
                        _this._sourceChange(source);
                        _this.dispatchEvent("loaded");
                    }
                    else {
                        var self = _this;
                        source.onload = function () {
                            self._sourceChange(source);
                            self.dispatchEvent("loaded");
                        };
                    }
                }
            }
            return _this;
        }
        BaseTexture.prototype.update = function () {
            this.width = this.source.width;
            this.height = this.source.height;
            this.hasLoaded = this.width && this.height ? true : false;
            this.isPowerOfTwo = isPow2(this.width) && isPow2(this.height);
            this.dispatchEvent("update");
        };
        BaseTexture.prototype._sourceChange = function (source) {
            this.source = source;
            this.imageUrl = source.src || source.path || null;
            this.imageType = this.source.type || null;
            this.hasLoaded = true;
            this.update();
            this.dispatchEvent("loaded");
        };
        BaseTexture.prototype.destroy = function () {
            if (this.imageUrl) {
                delete TextureCache[this.imageUrl];
                this.imageUrl = null;
            }
            this.source = null;
            this.dispose();
            BaseTexture.removeFromCache(this);
            this.textureCacheIds = null;
        };
        BaseTexture.prototype.dispose = function () {
            this.dispatchEvent("dispose");
        };
        BaseTexture.fromUrl = function (url) {
            if (BaseTextureCache[url])
                return BaseTextureCache[url];
            var baseTexture = new BaseTexture();
            GlobalLoader.loadImage(function (s, res) {
                if (s) {
                    baseTexture._sourceChange(res);
                    if (url.indexOf('data:') !== 0)
                        BaseTexture.addToCache(baseTexture, url);
                }
            }, url);
            return baseTexture;
        };
        BaseTexture.fromData = function (data) {
            return new BaseTexture(data);
        };
        BaseTexture.fromCanvas = function (canvas, origin) {
            if (origin === void 0) { origin = 'canvas'; }
            if (!canvas["_canvasId"]) {
                canvas["_canvasId"] = origin + "_" + uid();
            }
            var baseTexture = BaseTextureCache[canvas["_canvasId"]];
            if (!baseTexture) {
                baseTexture = new BaseTexture(canvas);
                BaseTexture.addToCache(baseTexture, canvas["_canvasId"]);
            }
            return baseTexture;
        };
        BaseTexture.fromImage = function (image) {
            var imageUrl = image.src;
            var baseTexture = BaseTextureCache[imageUrl];
            if (!baseTexture) {
                baseTexture = new BaseTexture(image);
                if (imageUrl && imageUrl.indexOf('data:') !== 0)
                    BaseTexture.addToCache(baseTexture, imageUrl);
            }
            return baseTexture;
        };
        BaseTexture.from = function (anything) {
            if (typeof anything === 'string') {
                return BaseTexture.fromUrl(anything);
            }
            else if (anything.data) {
                return BaseTexture.fromData(anything);
            }
            else if (anything.getContext) {
                return BaseTexture.fromCanvas(anything);
            }
            else {
                return BaseTexture.fromImage(anything);
            }
        };
        BaseTexture.addToCache = function (baseTexture, id) {
            if (id) {
                if (baseTexture.textureCacheIds.indexOf(id) === -1) {
                    baseTexture.textureCacheIds.push(id);
                }
                if (BaseTextureCache[id]) {
                    console.warn("BaseTexture added to the cache with an id [" + id + "] that already had an entry");
                }
                BaseTextureCache[id] = baseTexture;
            }
        };
        BaseTexture.removeFromCache = function (baseTexture) {
            if (typeof baseTexture === 'string') {
                var baseTextureFromCache = BaseTextureCache[baseTexture];
                if (baseTextureFromCache) {
                    var index = baseTextureFromCache.textureCacheIds.indexOf(baseTexture);
                    if (index > -1) {
                        baseTextureFromCache.textureCacheIds.splice(index, 1);
                    }
                    delete BaseTextureCache[baseTexture];
                    return baseTextureFromCache;
                }
            }
            else if (baseTexture && baseTexture.textureCacheIds) {
                for (var i = 0; i < baseTexture.textureCacheIds.length; ++i) {
                    delete BaseTextureCache[baseTexture.textureCacheIds[i]];
                }
                baseTexture.textureCacheIds.length = 0;
                return baseTexture;
            }
            return null;
        };
        return BaseTexture;
    }(EventDispatcher));

    var TextureUvs = (function () {
        function TextureUvs() {
            this.x0 = 0;
            this.y0 = 0;
            this.x1 = 1;
            this.y1 = 0;
            this.x2 = 1;
            this.y2 = 1;
            this.x3 = 0;
            this.y3 = 1;
            this.uvsUint32 = new Uint32Array(4);
            this.uvsFloat32 = new Float32Array(8);
        }
        TextureUvs.prototype.set = function (frame, baseFrame, rotate) {
            var tw = baseFrame.width;
            var th = baseFrame.height;
            if (rotate) {
                var w2 = frame.width / 2 / tw;
                var h2 = frame.height / 2 / th;
                var cX = (frame.x / tw) + w2;
                var cY = (frame.y / th) + h2;
                rotate = GroupD8.add(rotate, GroupD8.NW);
                this.x0 = cX + (w2 * GroupD8.uX(rotate));
                this.y0 = cY + (h2 * GroupD8.uY(rotate));
                rotate = GroupD8.add(rotate, 2);
                this.x1 = cX + (w2 * GroupD8.uX(rotate));
                this.y1 = cY + (h2 * GroupD8.uY(rotate));
                rotate = GroupD8.add(rotate, 2);
                this.x2 = cX + (w2 * GroupD8.uX(rotate));
                this.y2 = cY + (h2 * GroupD8.uY(rotate));
                rotate = GroupD8.add(rotate, 2);
                this.x3 = cX + (w2 * GroupD8.uX(rotate));
                this.y3 = cY + (h2 * GroupD8.uY(rotate));
            }
            else {
                this.x0 = frame.x / tw;
                this.y0 = frame.y / th;
                this.x1 = (frame.x + frame.width) / tw;
                this.y1 = frame.y / th;
                this.x2 = (frame.x + frame.width) / tw;
                this.y2 = (frame.y + frame.height) / th;
                this.x3 = frame.x / tw;
                this.y3 = (frame.y + frame.height) / th;
            }
            this.uvsUint32[0] = (((this.y0 * 65535) & 0xFFFF) << 16) | ((this.x0 * 65535) & 0xFFFF);
            this.uvsUint32[1] = (((this.y1 * 65535) & 0xFFFF) << 16) | ((this.x1 * 65535) & 0xFFFF);
            this.uvsUint32[2] = (((this.y2 * 65535) & 0xFFFF) << 16) | ((this.x2 * 65535) & 0xFFFF);
            this.uvsUint32[3] = (((this.y3 * 65535) & 0xFFFF) << 16) | ((this.x3 * 65535) & 0xFFFF);
            this.uvsFloat32[0] = this.x0;
            this.uvsFloat32[1] = this.y0;
            this.uvsFloat32[2] = this.x1;
            this.uvsFloat32[3] = this.y1;
            this.uvsFloat32[4] = this.x2;
            this.uvsFloat32[5] = this.y2;
            this.uvsFloat32[6] = this.x3;
            this.uvsFloat32[7] = this.y3;
        };
        return TextureUvs;
    }());

    var Texture = (function (_super) {
        tslib_1.__extends(Texture, _super);
        function Texture(baseTexture, frame, orig, trim, rotate, anchor) {
            var _this = _super.call(this) || this;
            _this._instanceType = "Texture";
            _this.noFrame = false;
            if (!frame) {
                _this.noFrame = true;
                frame = new Rectangle(0, 0, 1, 1);
            }
            if (baseTexture instanceof Texture)
                baseTexture = baseTexture.baseTexture;
            _this.baseTexture = baseTexture;
            _this._frame = frame;
            _this.trim = trim || null;
            _this.valid = false;
            _this._uvs = null;
            _this.orig = orig || frame;
            _this._rotate = Number(rotate || 0);
            if (baseTexture.hasLoaded || (baseTexture.source && baseTexture.source.getContext)) {
                if (_this.noFrame) {
                    frame = new Rectangle(0, 0, baseTexture.width, baseTexture.height);
                    baseTexture.addEventListener('update', _this.onBaseTextureUpdated, _this);
                }
                _this.frame = frame;
            }
            else {
                baseTexture.once('loaded', _this.onBaseTextureLoaded, _this);
            }
            _this.defaultAnchor = anchor ? new Point(anchor.x, anchor.y) : new Point(0, 0);
            _this._updateID = 0;
            _this.transform = null;
            _this.textureCacheIds = [];
            return _this;
        }
        Texture.prototype.update = function () {
            this.baseTexture.update();
        };
        Texture.prototype.onBaseTextureLoaded = function (e) {
            var baseTexture = e.target;
            this._updateID++;
            if (this.noFrame) {
                this.frame = new Rectangle(0, 0, baseTexture.width, baseTexture.height);
                this.baseTexture.addEventListener('update', this.onBaseTextureUpdated, this);
            }
            else {
                this.frame = this._frame;
            }
            this.dispatchEvent("update");
            this.dispatchEvent("loaded");
        };
        Texture.prototype.onBaseTextureUpdated = function (e) {
            var baseTexture = e.target;
            this._updateID++;
            this._frame.width = baseTexture.width;
            this._frame.height = baseTexture.height;
            this.orig.width = this._frame.width;
            this.orig.height = this._frame.height;
            this.valid = baseTexture.hasLoaded;
            this.dispatchEvent("update");
        };
        Texture.prototype.destroy = function () {
            if (this.baseTexture) {
                this.baseTexture.removeEventListener('update', this.onBaseTextureUpdated, this);
                this.baseTexture.removeEventListener('loaded', this.onBaseTextureLoaded, this);
                this.baseTexture = null;
            }
            this._frame = null;
            this._uvs = null;
            this.trim = null;
            this.orig = null;
            this.valid = false;
            Texture.removeFromCache(this);
            this.textureCacheIds = null;
        };
        Texture.prototype.clone = function () {
            return new Texture(this.baseTexture, this.frame, this.orig, this.trim, this.rotate, this.defaultAnchor);
        };
        Texture.prototype.updateUvs = function () {
            if (!this._uvs)
                this._uvs = new TextureUvs();
            this._uvs.set(this._frame, this.baseTexture, this.rotate);
            this._updateID++;
        };
        Object.defineProperty(Texture.prototype, "frame", {
            get: function () {
                return this._frame;
            },
            set: function (frame) {
                this._frame = frame;
                this.noFrame = false;
                var x = frame.x, y = frame.y, width = frame.width, height = frame.height;
                var xNotFit = x + width > this.baseTexture.width;
                var yNotFit = y + height > this.baseTexture.height;
                if (xNotFit || yNotFit) {
                    var relationship = xNotFit && yNotFit ? 'and' : 'or';
                    var errorX = "X: " + x + " + " + width + " = " + (x + width) + " > " + this.baseTexture.width;
                    var errorY = "Y: " + y + " + " + height + " = " + (y + height) + " > " + this.baseTexture.height;
                    throw new Error('Texture Error: frame does not fit inside the base Texture dimensions: '
                        + (errorX + " " + relationship + " " + errorY));
                }
                this.valid = width && height && this.baseTexture.source && this.baseTexture.hasLoaded;
                if (!this.trim && !this.rotate)
                    this.orig = frame;
                if (this.valid)
                    this.updateUvs();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Texture.prototype, "rotate", {
            get: function () {
                return this._rotate;
            },
            set: function (rotate) {
                if (this._rotate != rotate) {
                    this._rotate = rotate;
                    if (this.valid)
                        this.updateUvs();
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Texture.prototype, "width", {
            get: function () {
                return this.orig.width;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Texture.prototype, "height", {
            get: function () {
                return this.orig.height;
            },
            enumerable: true,
            configurable: true
        });
        Texture.fromUrl = function (url) {
            var texture = TextureCache[url];
            if (!texture) {
                texture = new Texture(BaseTexture.fromUrl(url));
                Texture.addToCache(texture, url);
            }
            return texture;
        };
        Texture.fromCanvas = function (canvas, origin) {
            if (origin === void 0) { origin = 'canvas'; }
            return new Texture(BaseTexture.fromCanvas(canvas, origin));
        };
        Texture.fromData = function (data) {
            return new Texture(BaseTexture.fromData(data));
        };
        Texture.fromImage = function (image) {
            var imageUrl = image.src;
            var texture = TextureCache[imageUrl];
            if (!texture) {
                texture = new Texture(BaseTexture.fromImage(image));
                if (imageUrl && imageUrl.indexOf('data:') !== 0)
                    Texture.addToCache(texture, imageUrl);
            }
            return texture;
        };
        Texture.from = function (anything) {
            if (typeof anything === 'string') {
                return Texture.fromUrl(anything);
            }
            else if (anything.data) {
                return Texture.fromData(anything);
            }
            else if (anything.getContext) {
                return Texture.fromCanvas(anything);
            }
            else {
                return Texture.fromImage(anything);
            }
        };
        Texture.addToCache = function (texture, id) {
            if (id) {
                if (texture.textureCacheIds.indexOf(id) === -1) {
                    texture.textureCacheIds.push(id);
                }
                if (TextureCache[id]) {
                    console.warn("Texture added to the cache with an id [" + id + "] that already had an entry");
                }
                TextureCache[id] = texture;
            }
        };
        Texture.removeFromCache = function (texture) {
            if (typeof texture === 'string') {
                var textureFromCache = TextureCache[texture];
                if (textureFromCache) {
                    var index = textureFromCache.textureCacheIds.indexOf(texture);
                    if (index > -1) {
                        textureFromCache.textureCacheIds.splice(index, 1);
                    }
                    delete TextureCache[texture];
                    return textureFromCache;
                }
            }
            else if (texture && texture.textureCacheIds) {
                for (var i = 0; i < texture.textureCacheIds.length; ++i) {
                    if (TextureCache[texture.textureCacheIds[i]] === texture) {
                        delete TextureCache[texture.textureCacheIds[i]];
                    }
                }
                texture.textureCacheIds.length = 0;
                return texture;
            }
            return null;
        };
        return Texture;
    }(EventDispatcher));
    function removeAllHandlers(tex) {
        tex.destroy = function _emptyDestroy() { };
        tex.addEventListener = function _emptyOn() { };
        tex.once = function _emptyOnce() { };
        tex.dispatchEvent = function _emptyEmit() { };
    }
    Texture.EMPTY = new Texture(new BaseTexture());
    removeAllHandlers(Texture.EMPTY);
    removeAllHandlers(Texture.EMPTY.baseTexture);
    var whiteSource = {
        data: (function () {
            var arr = [];
            for (var i = 0; i < 16 * 16 * 4; i++) {
                arr.push(255);
            }
            return new Uint8Array(arr);
        })(),
        width: 16,
        height: 16,
        type: null,
        path: null
    };
    Texture.WHITE = new Texture(new BaseTexture(whiteSource));
    removeAllHandlers(Texture.WHITE);
    removeAllHandlers(Texture.WHITE.baseTexture);

    var padding = 2;
    var maxSize = 4096;
    function DrawAllToCanvas(images, callback) {
        var textures = {};
        var imagesAll = [];
        var countAll = Object.getOwnPropertyNames(images).length;
        preLoad(images, function (img) {
            imagesAll.push(img);
            if (imagesAll.length == countAll) {
                imagesAll.sort(compare('width', 'height'));
                while (imagesAll.length) {
                    putInCanvas(imagesAll, textures);
                }
                callback(textures);
            }
        });
    }
    function preLoad(images, callback) {
        var _loop_1 = function () {
            bitmap = images[key];
            if (typeof (bitmap) == 'string') {
                var imgTag_1 = new Image();
                if (bitmap.indexOf("iVBO") === 0 || bitmap.indexOf("/9j/2w") === 0) {
                    imgTag_1.src = 'data:image/png;base64,' + bitmap;
                }
                else {
                    imgTag_1.src = bitmap;
                }
                imgTag_1["imageKey"] = key;
                imgTag_1.onload = function () {
                    callback(imgTag_1);
                };
            }
            else if (bitmap instanceof HTMLImageElement) {
                bitmap["imageKey"] = key;
                if (bitmap.complete && bitmap.width && bitmap.height) {
                    callback(bitmap);
                }
                else {
                    bitmap.onload = function () {
                        callback(bitmap);
                    };
                }
            }
            else if (bitmap instanceof HTMLCanvasElement) {
                callback(bitmap);
            }
        };
        var bitmap;
        for (var key in images) {
            _loop_1();
        }
    }
    function compare(name1, name2) {
        return function (a, b) {
            var fir1 = a[name1];
            var sec1 = b[name1];
            if (fir1 === sec1) {
                var fir2 = a[name2];
                var sec2 = b[name2];
                if (fir2 === sec2) {
                    return 0;
                }
                else {
                    return fir2 > sec2 ? 1 : -1;
                }
            }
            else {
                return fir1 > sec1 ? 1 : -1;
            }
        };
    }
    function putInCanvas(imagesAll, textures) {
        var freeRects = [];
        var imageInfos = [];
        var canvas = createCanvas();
        canvas.width = maxSize;
        canvas.height = maxSize;
        freeRects.push(new Rectangle(0, 0, maxSize, maxSize));
        var canvasWidth = 0, canvasHeight = 0;
        var match = false;
        for (var i = imagesAll.length - 1; i >= 0; i--) {
            var img = imagesAll[i];
            match = false;
            for (var j = freeRects.length - 1; j >= 0; j--) {
                var freeRect = freeRects[j];
                if (freeRect.width >= img.width + padding && freeRect.height >= img.height + padding) {
                    match = true;
                    var imageIn = new imageInfo(img, freeRect.x, freeRect.y);
                    imageInfos.push(imageIn);
                    imagesAll.splice(i, 1);
                    freeRects.splice(j, 1);
                    var restW = freeRect.width - img.width - padding;
                    if (restW > 0) {
                        var rightRect = new Rectangle(freeRect.x + img.width + padding, freeRect.y, restW, img.height + padding);
                        freeRect.y == 0 ? freeRects.unshift(rightRect) : freeRects.push(rightRect);
                    }
                    var restH = freeRect.height - img.height - padding;
                    if (restH > 0) {
                        var downRect = new Rectangle(freeRect.x, freeRect.y + img.height + padding, freeRect.width, restH);
                        freeRect.x == 0 ? freeRects.unshift(downRect) : freeRects.push(downRect);
                    }
                    if (imageIn.image.width + imageIn.x > canvasWidth) {
                        canvasWidth = imageIn.image.width + imageIn.x;
                    }
                    if (imageIn.image.height + imageIn.y > canvasHeight) {
                        canvasHeight = imageIn.image.height + imageIn.y;
                    }
                    break;
                }
            }
            if (!match)
                break;
        }
        canvas.width = nextPow2(canvasWidth + padding);
        canvas.height = nextPow2(canvasHeight + padding);
        var ctx = canvas.getContext("2d");
        for (var m = 0; m < imageInfos.length; m++) {
            var imageInfo_1 = imageInfos[m];
            var image = imageInfo_1.image;
            ctx.drawImage(imageInfo_1.image, 0, 0, image.width, image.height, imageInfo_1.x, imageInfo_1.y, image.width, image.height);
        }
        var baseTexture = new BaseTexture(canvas);
        for (var n = 0; n < imageInfos.length; n++) {
            var imageInfo_2 = imageInfos[n];
            var image = imageInfo_2.image;
            textures[image.imageKey] = new Texture(baseTexture, new Rectangle(imageInfo_2.x, imageInfo_2.y, image.width, image.height), new Rectangle(0, 0, image.width, image.height), null);
        }
    }
    var imageInfo = (function () {
        function imageInfo(image, x, y) {
            if (x === void 0) { x = 0; }
            if (y === void 0) { y = 0; }
            this.image = image;
            this.x = x;
            this.y = y;
        }
        return imageInfo;
    }());

    var premultiplyBlendMode = mapPremultipliedBlendModes();
    var nextUid = 0;
    function uid() {
        return ++nextUid;
    }
    var backupCanvas = null;
    function getGradientColor(points, colors) {
        var colorObj;
        var ctx = backupCanvas.getContext("2d");
        if (points.length == 4) {
            colorObj = ctx.createLinearGradient(points[0], points[1], points[2], points[3]);
        }
        else {
            colorObj = ctx.createRadialGradient(points[0], points[1], 0, points[2], points[3], points[4]);
        }
        for (var i = 0, l = colors.length; i < l; i++) {
            colorObj.addColorStop(colors[i][0], getRGBA(colors[i][1], colors[i][2]));
        }
        return colorObj;
    }
    function getCanvasBitmapStyle(image) {
        var ctx = backupCanvas.getContext("2d");
        return ctx.createPattern(image, "repeat");
    }
    function hex2rgb$1(hex, out) {
        out = out || [];
        out[0] = ((hex >> 16) & 0xFF) / 255;
        out[1] = ((hex >> 8) & 0xFF) / 255;
        out[2] = (hex & 0xFF) / 255;
        return out;
    }
    function hex2string(hex) {
        hex = hex.toString(16);
        hex = '000000'.substr(0, 6 - hex.length) + hex;
        return "#" + hex;
    }
    function string2hex(string) {
        if (string.indexOf("#") == 0) {
            string = string.replace("#", "0x");
        }
        return parseInt(string);
    }
    function rgb2hex$1(rgb) {
        return (((rgb[0] * 255) << 16) + ((rgb[1] * 255) << 8) + (rgb[2] * 255 | 0));
    }
    function getRGBA(color, alpha) {
        if (color.indexOf("0x") == 0) {
            color = color.replace("0x", "#");
        }
        if (color.length < 7) {
            color = "#000000";
        }
        if (alpha != 1) {
            var r = parseInt("0x" + color.substr(1, 2));
            var g = parseInt("0x" + color.substr(3, 2));
            var b = parseInt("0x" + color.substr(5, 2));
            color = "rgba(" + r + "," + g + "," + b + "," + alpha + ")";
        }
        return color;
    }
    function inputFeildIosEnable() {
        var u = navigator.userAgent;
        var isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
        if (isIOS) {
            setTimeout(function () {
                window["$"]("input").blur(function () {
                    if (isIOS) {
                        blurAdjust();
                    }
                });
            }, 50);
        }
        function blurAdjust() {
            setTimeout(function () {
                if (document.activeElement.tagName == 'INPUT' || document.activeElement.tagName == 'TEXTAREA') {
                    return;
                }
                var result = 'pc';
                if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
                    result = 'ios';
                }
                else if (/(Android)/i.test(navigator.userAgent)) {
                    result = 'android';
                }
                if (result = 'ios') {
                    document.activeElement["scrollIntoViewIfNeeded"](true);
                }
            }, 100);
        }
    }
    var DATA_URI = /^\s*data:(?:([\w-]+)\/([\w+.-]+))?(?:;charset=([\w-]+))?(?:;(base64))?,(.*)/i;
    function decomposeDataUri(dataUri) {
        var dataUriMatch = DATA_URI.exec(dataUri);
        if (dataUriMatch) {
            return {
                mediaType: dataUriMatch[1] ? dataUriMatch[1].toLowerCase() : undefined,
                subType: dataUriMatch[2] ? dataUriMatch[2].toLowerCase() : undefined,
                charset: dataUriMatch[3] ? dataUriMatch[3].toLowerCase() : undefined,
                encoding: dataUriMatch[4] ? dataUriMatch[4].toLowerCase() : undefined,
                data: dataUriMatch[5],
            };
        }
        return undefined;
    }
    var URL_FILE_EXTENSION = /\.(\w{3,4})(?:$|\?|#)/i;
    function getUrlFileExtension(url) {
        var extension = URL_FILE_EXTENSION.exec(url);
        if (extension) {
            return extension[1].toLowerCase();
        }
        return undefined;
    }
    function sign(n) {
        if (n === 0)
            return 0;
        return n < 0 ? -1 : 1;
    }
    function premultiplyTint(tint, alpha) {
        if (alpha === 1.0) {
            return (alpha * 255 << 24) + tint;
        }
        if (alpha === 0.0) {
            return 0;
        }
        var R = ((tint >> 16) & 0xFF);
        var G = ((tint >> 8) & 0xFF);
        var B = (tint & 0xFF);
        R = ((R * alpha) + 0.5) | 0;
        G = ((G * alpha) + 0.5) | 0;
        B = ((B * alpha) + 0.5) | 0;
        return (alpha * 255 << 24) + (R << 16) + (G << 8) + B;
    }
    var TextureCache = Object.create(null);
    var BaseTextureCache = Object.create(null);
    var TextureSheetCache = Object.create(null);
    function destroyTextureCache() {
        var key;
        for (key in TextureCache) {
            TextureCache[key].destroy();
        }
        for (key in BaseTextureCache) {
            BaseTextureCache[key].destroy();
        }
    }
    function clearTextureCache() {
        var key;
        for (key in TextureCache) {
            delete TextureCache[key];
        }
        for (key in BaseTextureCache) {
            delete BaseTextureCache[key];
        }
    }
    var GlobalPro = {
        stageRenderType: exports.RENDERER_TYPE.WEBGL,
        dpi: 1,
        padding: 2,
    };
    function isWebGLSupported() {
        var contextOptions = { stencil: true, failIfMajorPerformanceCaveat: true };
        try {
            if (!window["WebGLRenderingContext"]) {
                return false;
            }
            var canvas = createCanvas();
            var gl = canvas.getContext('webgl', contextOptions) || canvas.getContext('experimental-webgl', contextOptions);
            var success = !!(gl && gl["getContextAttributes"]().stencil);
            if (gl) {
                var loseContext = gl["getExtension"]('WEBGL_lose_context');
                if (loseContext) {
                    loseContext.loseContext();
                }
            }
            gl = null;
            return success;
        }
        catch (e) {
            return false;
        }
    }
    function removeItems(arr, startIdx, removeCount) {
        var i, length = arr.length;
        if (startIdx >= length || removeCount === 0) {
            return;
        }
        removeCount = (startIdx + removeCount > length ? length - startIdx : removeCount);
        var len = length - removeCount;
        for (i = startIdx; i < len; ++i) {
            arr[i] = arr[i + removeCount];
        }
        arr.length = len;
    }

    var indices = new Uint16Array([0, 1, 2, 0, 2, 3]);
    var Sprite = (function (_super) {
        tslib_1.__extends(Sprite, _super);
        function Sprite(texture) {
            var _this = _super.call(this) || this;
            _this._blendMode = exports.BLEND_MODES.NORMAL;
            _this._instanceType = "Sprite";
            _this._anchorTexture = new ObservablePoint(_this._onAnchorUpdate, _this, (texture ? texture.defaultAnchor.x : 0), (texture ? texture.defaultAnchor.y : 0));
            _this._texture = null;
            _this._width = 0;
            _this._height = 0;
            _this._tint = null;
            _this._tintRGB = null;
            _this.tint = 0xFFFFFF;
            _this._cachedTint = 0xFFFFFF;
            _this._uvs = null;
            _this.texture = texture || Texture.EMPTY;
            _this._vertexData = new Float32Array(8);
            _this._vertexTrimmedData = null;
            _this._transformID = -1;
            _this._textureID = -1;
            _this._transformTrimmedID = -1;
            _this._textureTrimmedID = -1;
            _this._indices = indices;
            _this.pluginName = 'sprite';
            return _this;
        }
        Object.defineProperty(Sprite.prototype, "blendMode", {
            get: function () {
                return this._blendMode;
            },
            set: function (value) {
            },
            enumerable: true,
            configurable: true
        });
        Sprite.prototype._onTextureUpdate = function () {
            this._textureID = -1;
            this._textureTrimmedID = -1;
            this._cachedTint = 0xFFFFFF;
            if (this._texture.valid)
                this._uvs = this._texture._uvs.uvsFloat32;
            if (this._width) {
                this.scale.x = sign(this.scale.x) * this._width / this._texture.orig.width;
            }
            if (this._height) {
                this.scale.y = sign(this.scale.y) * this._height / this._texture.orig.height;
            }
            this.updateLocalBoundsSelf();
        };
        Sprite.prototype._onAnchorUpdate = function () {
            this._transformID = -1;
            this._transformTrimmedID = -1;
            this.updateLocalBoundsSelf();
        };
        Sprite.prototype.updateLocalBoundsSelf = function () {
            var width = this._texture.orig.width;
            var height = this._texture.orig.height;
            this._localBoundsSelf.x = -width * this.anchorTexture.x;
            this._localBoundsSelf.y = -height * this.anchorTexture.y;
            this._localBoundsSelf.width = width;
            this._localBoundsSelf.height = height;
        };
        Sprite.prototype.calculateVertices = function () {
            if (this._transformID === this.transform._worldID && this._textureID === this._texture._updateID) {
                return;
            }
            this._transformID = this.transform._worldID;
            this._textureID = this._texture._updateID;
            var texture = this._texture;
            var wt = this.transform.worldMatrix;
            var a = wt.a;
            var b = wt.b;
            var c = wt.c;
            var d = wt.d;
            var tx = wt.tx;
            var ty = wt.ty;
            var vertexData = this._vertexData;
            var trim = texture.trim;
            var orig = texture.orig;
            var anchor = this._anchorTexture;
            var w0 = 0;
            var w1 = 0;
            var h0 = 0;
            var h1 = 0;
            if (trim) {
                w1 = trim.x - (anchor._x * orig.width);
                w0 = w1 + trim.width;
                h1 = trim.y - (anchor._y * orig.height);
                h0 = h1 + trim.height;
            }
            else {
                w1 = -anchor._x * orig.width;
                w0 = w1 + orig.width;
                h1 = -anchor._y * orig.height;
                h0 = h1 + orig.height;
            }
            vertexData[0] = (a * w1) + (c * h1) + tx;
            vertexData[1] = (d * h1) + (b * w1) + ty;
            vertexData[2] = (a * w0) + (c * h1) + tx;
            vertexData[3] = (d * h1) + (b * w0) + ty;
            vertexData[4] = (a * w0) + (c * h0) + tx;
            vertexData[5] = (d * h0) + (b * w0) + ty;
            vertexData[6] = (a * w1) + (c * h0) + tx;
            vertexData[7] = (d * h0) + (b * w1) + ty;
        };
        Sprite.prototype.calculateTrimmedVertices = function () {
            if (!this._vertexTrimmedData) {
                this._vertexTrimmedData = new Float32Array(8);
            }
            else if (this._transformTrimmedID === this.transform._worldID && this._textureTrimmedID === this._texture._updateID) {
                return;
            }
            this._transformTrimmedID = this.transform._worldID;
            this._textureTrimmedID = this._texture._updateID;
            var texture = this._texture;
            var vertexData = this._vertexTrimmedData;
            var orig = texture.orig;
            var anchor = this._anchorTexture;
            var wt = this.transform.worldMatrix;
            var a = wt.a;
            var b = wt.b;
            var c = wt.c;
            var d = wt.d;
            var tx = wt.tx;
            var ty = wt.ty;
            var w1 = -anchor._x * orig.width;
            var w0 = w1 + orig.width;
            var h1 = -anchor._y * orig.height;
            var h0 = h1 + orig.height;
            vertexData[0] = (a * w1) + (c * h1) + tx;
            vertexData[1] = (d * h1) + (b * w1) + ty;
            vertexData[2] = (a * w0) + (c * h1) + tx;
            vertexData[3] = (d * h1) + (b * w0) + ty;
            vertexData[4] = (a * w0) + (c * h0) + tx;
            vertexData[5] = (d * h0) + (b * w0) + ty;
            vertexData[6] = (a * w1) + (c * h0) + tx;
            vertexData[7] = (d * h0) + (b * w1) + ty;
        };
        Sprite.prototype._renderWebGL = function (renderer) {
            this.calculateVertices();
            renderer.batchManager.setObjectRenderer(renderer.plugins["batch"]);
            renderer.plugins["batch"].render(this);
        };
        Sprite.prototype._renderCanvas = function (renderer) {
            renderer.plugins[this.pluginName].render(this);
        };
        Sprite.prototype._calculateBounds = function () {
            var trim = this._texture.trim;
            var orig = this._texture.orig;
            if (!trim || (trim.width === orig.width && trim.height === orig.height)) {
                this.calculateVertices();
                Rectangle.createFromVertexData(this._bounds, this._vertexData);
            }
            else {
                this.calculateTrimmedVertices();
                Rectangle.createFromVertexData(this._bounds, this._vertexTrimmedData);
            }
        };
        Sprite.prototype.getLocalBounds = function (rect) {
            if (this.children.length === 0) {
                if (!rect) {
                    rect = DisplayObject.temBounds;
                }
                rect.copy(this._localBoundsSelf);
                return rect;
            }
            return _super.prototype.getLocalBounds.call(this, rect);
        };
        Sprite.prototype.hitTestPoint = function (globalPoint, isMouseEvent) {
            if (isMouseEvent === void 0) { isMouseEvent = false; }
            if (!this.visible)
                return null;
            var hitDisplayObject;
            hitDisplayObject = _super.prototype.hitTestPoint.call(this, globalPoint, isMouseEvent);
            if (hitDisplayObject)
                return hitDisplayObject;
            hitDisplayObject = this.displayObjectHitTestPoint(globalPoint, isMouseEvent);
            if (hitDisplayObject)
                return hitDisplayObject;
            return null;
        };
        Sprite.prototype.destroy = function () {
            _super.prototype.destroy.call(this);
            this._texture.removeEventListener('update', this._onTextureUpdate, this);
            this._anchorTexture = null;
            this._texture = null;
            this._indices = null;
            this._uvs = null;
            this._vertexData = null;
            this._vertexTrimmedData = null;
            if (this["tintedTexture"])
                this["tintedTexture"] = null;
        };
        Object.defineProperty(Sprite.prototype, "width", {
            get: function () {
                return Math.abs(this.scale.x) * this._texture.orig.width;
            },
            set: function (value) {
                var s = sign(this.scale.x) || 1;
                this.scale.x = s * value / this._texture.orig.width;
                this._width = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Sprite.prototype, "height", {
            get: function () {
                return Math.abs(this.scale.y) * this._texture.orig.height;
            },
            set: function (value) {
                var s = sign(this.scale.y) || 1;
                this.scale.y = s * value / this._texture.orig.height;
                this._height = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Sprite.prototype, "anchorTexture", {
            get: function () {
                return this._anchorTexture;
            },
            set: function (value) {
                this._anchorTexture.copy(value);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Sprite.prototype, "texture", {
            get: function () {
                return this._texture;
            },
            set: function (value) {
                if (this._texture === value) {
                    return;
                }
                this._texture = value || Texture.EMPTY;
                this._textureID = -1;
                this._textureTrimmedID = -1;
                this._cachedTint = 0xFFFFFF;
                if (value) {
                    if (value.baseTexture.hasLoaded) {
                        this._onTextureUpdate();
                    }
                    else {
                        value.once('update', this._onTextureUpdate, this);
                    }
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Sprite.prototype, "tint", {
            get: function () {
                return this._tint;
            },
            set: function (value) {
                if (value === this._tint)
                    return;
                this._tint = value;
                this._tintRGB = (value >> 16) + (value & 0xff00) + ((value & 0xff) << 16);
            },
            enumerable: true,
            configurable: true
        });
        Sprite.fromUrl = function (url) {
            return new Sprite(Texture.fromUrl(url));
        };
        Sprite.fromFrame = function (frameId) {
            var texture = TextureCache[frameId];
            if (!texture) {
                throw new Error("The frameId \"" + frameId + "\" does not exist in the texture cache");
            }
            return new Sprite(texture);
        };
        return Sprite;
    }(Container));

    var MouseEvent = (function (_super) {
        tslib_1.__extends(MouseEvent, _super);
        function MouseEvent(type) {
            var _this = _super.call(this, type) || this;
            _this.clientX = 0;
            _this.clientY = 0;
            _this.stageX = 0;
            _this.stageY = 0;
            _this.localX = 0;
            _this.localY = 0;
            _this.currentTarget = null;
            _this.identifier = 0;
            _this._instanceType = "MouseEvent";
            return _this;
        }
        MouseEvent.prototype.updateAfterEvent = function () {
            this.target.stage._cp = true;
        };
        MouseEvent.prototype.destroy = function () {
            var s = this;
            s.currentTarget = null;
            _super.prototype.destroy.call(this);
        };
        MouseEvent.MOUSE_DOWN = "onMouseDown";
        MouseEvent.MOUSE_UP = "onMouseUp";
        MouseEvent.CLICK = "onMouseClick";
        MouseEvent.MOUSE_MOVE = "onMouseMove";
        MouseEvent.MOUSE_OVER = "onMouseOver";
        MouseEvent.MOUSE_OUT = "onMouseOut";
        return MouseEvent;
    }(Event));

    var BatchDrawCall = (function () {
        function BatchDrawCall() {
            this.textures = [];
            this.blend = 0;
            this.textureCount = 0;
            this.start = 0;
            this.size = 0;
            this.type = exports.DRAW_MODES.TRIANGLES;
        }
        return BatchDrawCall;
    }());

    var ObjectRenderer = (function () {
        function ObjectRenderer(renderer) {
            this.renderer = renderer;
            this.renderer.addEventListener('onContextChange', this.onContextChange, this);
        }
        ObjectRenderer.prototype.onContextChange = function () {
        };
        ObjectRenderer.prototype.start = function () {
        };
        ObjectRenderer.prototype.stop = function () {
            this.flush();
        };
        ObjectRenderer.prototype.flush = function () {
        };
        ObjectRenderer.prototype.render = function (object) {
        };
        ObjectRenderer.prototype.destroy = function () {
            this.renderer.removeEventListener('onContextChange', this.onContextChange, this);
            this.renderer = null;
        };
        return ObjectRenderer;
    }());

    function createContext(canvas, options) {
        var gl = canvas.getContext('webgl', options) ||
            canvas.getContext('experimental-webgl', options);
        if (!gl) {
            throw new Error('This browser does not support webGL. Try using the canvas renderer');
        }
        return gl;
    }

    var fragTemplate = [
        'precision mediump float;',
        'void main(void){',
        'float test = 0.1;',
        '%forloop%',
        'gl_FragColor = vec4(0.0);',
        '}',
    ].join('\n');
    function checkMaxIfStatementsInShader(maxIfs, gl) {
        var createTempContext = !gl;
        if (maxIfs === 0) {
            throw new Error('Invalid value of `0` passed to `checkMaxIfStatementsInShader`');
        }
        if (createTempContext) {
            var tinyCanvas = createCanvas();
            tinyCanvas.width = 1;
            tinyCanvas.height = 1;
            gl = createContext(tinyCanvas);
        }
        var shader = gl.createShader(gl.FRAGMENT_SHADER);
        while (true) {
            var fragmentSrc = fragTemplate.replace(/%forloop%/gi, generateIfTestSrc(maxIfs));
            gl.shaderSource(shader, fragmentSrc);
            gl.compileShader(shader);
            if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
                maxIfs = (maxIfs / 2) | 0;
            }
            else {
                break;
            }
        }
        if (createTempContext) {
            if (gl.getExtension('WEBGL_lose_context')) {
                gl.getExtension('WEBGL_lose_context').loseContext();
            }
        }
        return maxIfs;
    }
    function generateIfTestSrc(maxIfs) {
        var src = '';
        for (var i = 0; i < maxIfs; ++i) {
            if (i > 0) {
                src += '\nelse ';
            }
            if (i < maxIfs - 1) {
                src += "if(test == " + i + ".0){}";
            }
        }
        return src;
    }

    var BatchBuffer = (function () {
        function BatchBuffer(size) {
            this.vertices = new ArrayBuffer(size);
            this.float32View = new Float32Array(this.vertices);
            this.uint32View = new Uint32Array(this.vertices);
        }
        BatchBuffer.prototype.destroy = function () {
            this.vertices = null;
            this.positions = null;
            this.uvs = null;
            this.colors = null;
        };
        return BatchBuffer;
    }());

    var GLTexture = (function () {
        function GLTexture(gl, width, height, format, type) {
            this.uploadData = function (data, width, height) {
                this.bind();
                var gl = this.gl;
                if (data instanceof Float32Array) {
                    if (!FLOATING_POINT_AVAILABLE) {
                        var ext = gl.getExtension("OES_texture_float");
                        if (ext) {
                            FLOATING_POINT_AVAILABLE = true;
                        }
                        else {
                            throw new Error('floating point textures not available');
                        }
                    }
                    this.type = gl.FLOAT;
                }
                else {
                    this.type = this.type || gl.UNSIGNED_BYTE;
                }
                gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha);
                if (width !== this.width || height !== this.height) {
                    gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, data || null);
                }
                else {
                    gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, this.format, this.type, data || null);
                }
                this.width = width;
                this.height = height;
            };
            this.gl = gl;
            this.texture = gl.createTexture();
            this.mipmap = false;
            this.premultiplyAlpha = false;
            this.width = width || -1;
            this.height = height || -1;
            this.format = format || gl.RGBA;
            this.type = type || gl.UNSIGNED_BYTE;
        }
        GLTexture.prototype.upload = function (source) {
            this.bind();
            var gl = this.gl;
            gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha);
            var newWidth = source.videoWidth || source.width;
            var newHeight = source.videoHeight || source.height;
            if (newHeight !== this.height || newWidth !== this.width) {
                gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source);
            }
            else {
                gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source);
            }
            this.width = newWidth;
            this.height = newHeight;
        };
        GLTexture.prototype.bind = function (location) {
            var gl = this.gl;
            if (location !== undefined) {
                gl.activeTexture(gl.TEXTURE0 + location);
            }
            gl.bindTexture(gl.TEXTURE_2D, this.texture);
        };
        GLTexture.prototype.unbind = function () {
            var gl = this.gl;
            gl.bindTexture(gl.TEXTURE_2D, null);
        };
        GLTexture.prototype.minFilter = function (linear) {
            var gl = this.gl;
            this.bind();
            if (this.mipmap) {
                gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST);
            }
            else {
                gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST);
            }
        };
        GLTexture.prototype.magFilter = function (linear) {
            var gl = this.gl;
            this.bind();
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST);
        };
        GLTexture.prototype.enableMipmap = function () {
            var gl = this.gl;
            this.bind();
            this.mipmap = true;
            gl.generateMipmap(gl.TEXTURE_2D);
        };
        GLTexture.prototype.enableLinearScaling = function () {
            this.minFilter(true);
            this.magFilter(true);
        };
        GLTexture.prototype.enableNearestScaling = function () {
            this.minFilter(false);
            this.magFilter(false);
        };
        GLTexture.prototype.enableWrapClamp = function () {
            var gl = this.gl;
            this.bind();
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
        };
        GLTexture.prototype.enableWrapRepeat = function () {
            var gl = this.gl;
            this.bind();
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT);
        };
        GLTexture.prototype.enableWrapMirrorRepeat = function () {
            var gl = this.gl;
            this.bind();
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT);
        };
        GLTexture.prototype.destroy = function () {
            var gl = this.gl;
            gl.deleteTexture(this.texture);
        };
        GLTexture.fromSource = function (gl, source, premultiplyAlpha) {
            var texture = new GLTexture(gl);
            texture.premultiplyAlpha = premultiplyAlpha || false;
            texture.upload(source);
            return texture;
        };
        GLTexture.fromData = function (gl, data, width, height) {
            var texture = new GLTexture(gl);
            texture.uploadData(data, width, height);
            return texture;
        };
        return GLTexture;
    }());
    var FLOATING_POINT_AVAILABLE = false;

    var EMPTY_ARRAY_BUFFER = new ArrayBuffer(0);
    var GLBuffer = (function () {
        function GLBuffer(gl, type, data, drawType) {
            this.destroy = function () {
                this.gl.deleteBuffer(this.buffer);
            };
            this.gl = gl;
            this.buffer = gl.createBuffer();
            this.type = type || gl.ARRAY_BUFFER;
            this.drawType = drawType || gl.STATIC_DRAW;
            this.data = EMPTY_ARRAY_BUFFER;
            if (data) {
                this.upload(data);
            }
            this._updateID = 0;
        }
        GLBuffer.prototype.upload = function (data, offset, dontBind) {
            if (!dontBind)
                this.bind();
            var gl = this.gl;
            data = data || this.data;
            offset = offset || 0;
            if (this.data.byteLength >= data.byteLength) {
                gl.bufferSubData(this.type, offset, data);
            }
            else {
                gl.bufferData(this.type, data, this.drawType);
            }
            this.data = data;
        };
        GLBuffer.prototype.bind = function () {
            var gl = this.gl;
            gl.bindBuffer(this.type, this.buffer);
        };
        GLBuffer.createVertexBuffer = function (gl, data, drawType) {
            return new GLBuffer(gl, gl.ARRAY_BUFFER, data, drawType);
        };
        GLBuffer.createIndexBuffer = function (gl, data, drawType) {
            return new GLBuffer(gl, gl.ELEMENT_ARRAY_BUFFER, data, drawType);
        };
        GLBuffer.create = function (gl, type, data, drawType) {
            return new GLBuffer(gl, type, data, drawType);
        };
        return GLBuffer;
    }());

    function setVertexAttribArrays(gl, attribs, state) {
        var i;
        if (state) {
            var tempAttribState = state.tempAttribState, attribState = state.attribState;
            for (i = 0; i < tempAttribState.length; i++) {
                tempAttribState[i] = false;
            }
            for (i = 0; i < attribs.length; i++) {
                tempAttribState[attribs[i].attribute.location] = true;
            }
            for (i = 0; i < attribState.length; i++) {
                if (attribState[i] !== tempAttribState[i]) {
                    attribState[i] = tempAttribState[i];
                    if (state.attribState[i]) {
                        gl.enableVertexAttribArray(i);
                    }
                    else {
                        gl.disableVertexAttribArray(i);
                    }
                }
            }
        }
        else {
            for (i = 0; i < attribs.length; i++) {
                var attrib = attribs[i];
                gl.enableVertexAttribArray(attrib.attribute.location);
            }
        }
    }

    var VertexArrayObject = (function () {
        function VertexArrayObject(gl, state) {
            this.nativeVaoExtension = null;
            if (!VertexArrayObject.FORCE_NATIVE) {
                this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') ||
                    gl.getExtension('MOZ_OES_vertex_array_object') ||
                    gl.getExtension('WEBKIT_OES_vertex_array_object');
            }
            this.nativeState = state;
            if (this.nativeVaoExtension) {
                this.nativeVao = this.nativeVaoExtension.createVertexArrayOES();
                var maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS);
                this.nativeState = {
                    tempAttribState: new Array(maxAttribs),
                    attribState: new Array(maxAttribs)
                };
            }
            this.gl = gl;
            this.attributes = [];
            this.indexBuffer = null;
            this.dirty = false;
        }
        VertexArrayObject.prototype.bind = function () {
            if (this.nativeVao) {
                this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao);
                if (this.dirty) {
                    this.dirty = false;
                    this.activate();
                    return this;
                }
                if (this.indexBuffer) {
                    this.indexBuffer.bind();
                }
            }
            else {
                this.activate();
            }
            return this;
        };
        VertexArrayObject.prototype.unbind = function () {
            if (this.nativeVao) {
                this.nativeVaoExtension.bindVertexArrayOES(null);
            }
            return this;
        };
        VertexArrayObject.prototype.activate = function () {
            var gl = this.gl;
            var lastBuffer = null;
            for (var i = 0; i < this.attributes.length; i++) {
                var attrib = this.attributes[i];
                if (lastBuffer !== attrib.buffer) {
                    attrib.buffer.bind();
                    lastBuffer = attrib.buffer;
                }
                attrib.attribute.pointer(attrib.type || gl.FLOAT, attrib.normalized || false, attrib.stride || 0, attrib.start || 0);
            }
            setVertexAttribArrays(gl, this.attributes, this.nativeState);
            if (this.indexBuffer) {
                this.indexBuffer.bind();
            }
            return this;
        };
        VertexArrayObject.prototype.addAttribute = function (buffer, attribute, type, normalized, stride, start) {
            this.attributes.push({
                buffer: buffer,
                attribute: attribute,
                location: attribute.location,
                type: type || this.gl.FLOAT,
                normalized: normalized || false,
                stride: stride || 0,
                start: start || 0
            });
            this.dirty = true;
            return this;
        };
        VertexArrayObject.prototype.addIndex = function (buffer) {
            this.indexBuffer = buffer;
            this.dirty = true;
            return this;
        };
        VertexArrayObject.prototype.clear = function () {
            if (this.nativeVao) {
                this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao);
            }
            this.attributes.length = 0;
            this.indexBuffer = null;
            return this;
        };
        VertexArrayObject.prototype.draw = function (type, size, start) {
            var gl = this.gl;
            if (this.indexBuffer) {
                gl.drawElements(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2);
            }
            else {
                gl.drawArrays(type, start || 0, size || this.getSize());
            }
            return this;
        };
        VertexArrayObject.prototype.destroy = function () {
            this.gl = null;
            this.indexBuffer = null;
            this.attributes = null;
            this.nativeState = null;
            if (this.nativeVao) {
                this.nativeVaoExtension.deleteVertexArrayOES(this.nativeVao);
            }
            this.nativeVaoExtension = null;
            this.nativeVao = null;
        };
        VertexArrayObject.prototype.getSize = function () {
            var attrib = this.attributes[0];
            return attrib.buffer.data.length / ((attrib.stride / 4) || attrib.attribute.size);
        };
        VertexArrayObject.FORCE_NATIVE = false;
        return VertexArrayObject;
    }());

    var GLFramebuffer = (function () {
        function GLFramebuffer(gl, width, height) {
            this.gl = gl;
            this.framebuffer = gl.createFramebuffer();
            this.stencil = null;
            this.texture = null;
            this.width = width || 100;
            this.height = height || 100;
        }
        GLFramebuffer.prototype.enableTexture = function (texture) {
            var gl = this.gl;
            this.texture = texture || new GLTexture(gl);
            this.texture.bind();
            this.bind();
            gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.texture.texture, 0);
        };
        GLFramebuffer.prototype.enableStencil = function () {
            if (this.stencil)
                return;
            var gl = this.gl;
            this.stencil = gl.createRenderbuffer();
            gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil);
            gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, this.stencil);
            gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, this.width, this.height);
        };
        GLFramebuffer.prototype.clear = function (r, g, b, a) {
            this.bind();
            var gl = this.gl;
            gl.clearColor(r, g, b, a);
            gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
        };
        GLFramebuffer.prototype.bind = function () {
            var gl = this.gl;
            gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer);
        };
        GLFramebuffer.prototype.unbind = function () {
            var gl = this.gl;
            gl.bindFramebuffer(gl.FRAMEBUFFER, null);
        };
        GLFramebuffer.prototype.resize = function (width, height) {
            var gl = this.gl;
            this.width = width;
            this.height = height;
            if (this.texture) {
                this.texture.uploadData(null, width, height);
            }
            if (this.stencil) {
                gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil);
                gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
            }
        };
        GLFramebuffer.prototype.destroy = function () {
            var gl = this.gl;
            if (this.texture) {
                this.texture.destroy();
            }
            gl.deleteFramebuffer(this.framebuffer);
            this.gl = null;
            this.stencil = null;
            this.texture = null;
        };
        GLFramebuffer.createRGBA = function (gl, width, height, data) {
            var texture = GLTexture.fromData(gl, null, width, height);
            texture.enableNearestScaling();
            texture.enableWrapClamp();
            var fbo = new GLFramebuffer(gl, width, height);
            fbo.enableTexture(texture);
            fbo.unbind();
            return fbo;
        };
        GLFramebuffer.createFloat32 = function (gl, width, height, data) {
            var texture = GLTexture.fromData(gl, data, width, height);
            texture.enableNearestScaling();
            texture.enableWrapClamp();
            var fbo = new GLFramebuffer(gl, width, height);
            fbo.enableTexture(texture);
            fbo.unbind();
            return fbo;
        };
        return GLFramebuffer;
    }());

    function compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations) {
        var glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc);
        var glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc);
        var program = gl.createProgram();
        gl.attachShader(program, glVertShader);
        gl.attachShader(program, glFragShader);
        if (attributeLocations) {
            for (var i in attributeLocations) {
                gl.bindAttribLocation(program, attributeLocations[i], i);
            }
        }
        gl.linkProgram(program);
        if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
            console.error('Error: Could not initialize shader.');
            console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS));
            console.error('gl.getError()', gl.getError());
            if (gl.getProgramInfoLog(program) !== '') {
                console.warn('Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program));
            }
            gl.deleteProgram(program);
            program = null;
        }
        gl.deleteShader(glVertShader);
        gl.deleteShader(glFragShader);
        return program;
    }
    var compileShader = function (gl, type, src) {
        var shader = gl.createShader(type);
        gl.shaderSource(shader, src);
        gl.compileShader(shader);
        if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
            console.log(gl.getShaderInfoLog(shader));
            return null;
        }
        return shader;
    };

    function mapType(gl, type) {
        if (!GL_TABLE) {
            var typeNames = Object.keys(GL_TO_GLSL_TYPES);
            GL_TABLE = {};
            for (var i = 0; i < typeNames.length; ++i) {
                var tn = typeNames[i];
                GL_TABLE[gl[tn]] = GL_TO_GLSL_TYPES[tn];
            }
        }
        return GL_TABLE[type];
    }
    var GL_TABLE = null;
    var GL_TO_GLSL_TYPES = {
        'FLOAT': 'float',
        'FLOAT_VEC2': 'vec2',
        'FLOAT_VEC3': 'vec3',
        'FLOAT_VEC4': 'vec4',
        'INT': 'int',
        'INT_VEC2': 'ivec2',
        'INT_VEC3': 'ivec3',
        'INT_VEC4': 'ivec4',
        'BOOL': 'bool',
        'BOOL_VEC2': 'bvec2',
        'BOOL_VEC3': 'bvec3',
        'BOOL_VEC4': 'bvec4',
        'FLOAT_MAT2': 'mat2',
        'FLOAT_MAT3': 'mat3',
        'FLOAT_MAT4': 'mat4',
        'SAMPLER_2D': 'sampler2D'
    };

    function mapSize(type) {
        return GLSL_TO_SIZE[type];
    }
    var GLSL_TO_SIZE = {
        'float': 1,
        'vec2': 2,
        'vec3': 3,
        'vec4': 4,
        'int': 1,
        'ivec2': 2,
        'ivec3': 3,
        'ivec4': 4,
        'bool': 1,
        'bvec2': 2,
        'bvec3': 3,
        'bvec4': 4,
        'mat2': 4,
        'mat3': 9,
        'mat4': 16,
        'sampler2D': 1
    };

    function extractAttributes(gl, program) {
        var attributes = {};
        var totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES);
        for (var i = 0; i < totalAttributes; i++) {
            var attribData = gl.getActiveAttrib(program, i);
            var type = mapType(gl, attribData.type);
            attributes[attribData.name] = {
                type: type,
                size: mapSize(type),
                location: gl.getAttribLocation(program, attribData.name),
                pointer: function (type, normalized, stride, start) {
                    if (type === void 0) { type = gl.FLOAT; }
                    if (normalized === void 0) { normalized = false; }
                    if (stride === void 0) { stride = 0; }
                    if (start === void 0) { start = 0; }
                    gl.vertexAttribPointer(this.location, this.size, type, normalized, stride, start);
                }
            };
        }
        return attributes;
    }

    function defaultValue(type, size) {
        switch (type) {
            case 'float':
                return 0;
            case 'vec2':
                return new Float32Array(2 * size);
            case 'vec3':
                return new Float32Array(3 * size);
            case 'vec4':
                return new Float32Array(4 * size);
            case 'int':
            case 'sampler2D':
                return 0;
            case 'ivec2':
                return new Int32Array(2 * size);
            case 'ivec3':
                return new Int32Array(3 * size);
            case 'ivec4':
                return new Int32Array(4 * size);
            case 'bool':
                return false;
            case 'bvec2':
                return booleanArray(2 * size);
            case 'bvec3':
                return booleanArray(3 * size);
            case 'bvec4':
                return booleanArray(4 * size);
            case 'mat2':
                return new Float32Array([1, 0,
                    0, 1]);
            case 'mat3':
                return new Float32Array([1, 0, 0,
                    0, 1, 0,
                    0, 0, 1]);
            case 'mat4':
                return new Float32Array([1, 0, 0, 0,
                    0, 1, 0, 0,
                    0, 0, 1, 0,
                    0, 0, 0, 1]);
        }
    }
    var booleanArray = function (size) {
        var array = new Array(size);
        for (var i = 0; i < array.length; i++) {
            array[i] = false;
        }
        return array;
    };

    function extractUniforms(gl, program) {
        var uniforms = {};
        var totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
        for (var i = 0; i < totalUniforms; i++) {
            var uniformData = gl.getActiveUniform(program, i);
            var name = uniformData.name.replace(/\[.*?\]/, "");
            var type = mapType(gl, uniformData.type);
            uniforms[name] = {
                type: type,
                size: uniformData.size,
                location: gl.getUniformLocation(program, name),
                value: defaultValue(type, uniformData.size)
            };
        }
        return uniforms;
    }

    function setPrecision(src, precision) {
        if (src.substring(0, 9) !== 'precision') {
            return 'precision ' + precision + ' float;\n' + src;
        }
        return src;
    }

    function generateUniformAccessObject(gl, uniformData) {
        var uniforms = { data: {} };
        uniforms["gl"] = gl;
        var uniformKeys = Object.keys(uniformData);
        for (var i = 0; i < uniformKeys.length; i++) {
            var fullName = uniformKeys[i];
            var nameTokens = fullName.split('.');
            var name = nameTokens[nameTokens.length - 1];
            var uniformGroup = getUniformGroup(nameTokens, uniforms);
            var uniform = uniformData[fullName];
            uniformGroup.data[name] = uniform;
            uniformGroup.gl = gl;
            Object.defineProperty(uniformGroup, name, {
                get: generateGetter(name),
                set: generateSetter(name, uniform)
            });
        }
        return uniforms;
    }
    var generateGetter = function (name) {
        return function () {
            return this.data[name].value;
        };
    };
    var GLSL_SINGLE_SETTERS = {
        float: function setSingleFloat(gl, location, value) { gl.uniform1f(location, value); },
        vec2: function setSingleVec2(gl, location, value) { gl.uniform2f(location, value[0], value[1]); },
        vec3: function setSingleVec3(gl, location, value) { gl.uniform3f(location, value[0], value[1], value[2]); },
        vec4: function setSingleVec4(gl, location, value) { gl.uniform4f(location, value[0], value[1], value[2], value[3]); },
        int: function setSingleInt(gl, location, value) { gl.uniform1i(location, value); },
        ivec2: function setSingleIvec2(gl, location, value) { gl.uniform2i(location, value[0], value[1]); },
        ivec3: function setSingleIvec3(gl, location, value) { gl.uniform3i(location, value[0], value[1], value[2]); },
        ivec4: function setSingleIvec4(gl, location, value) { gl.uniform4i(location, value[0], value[1], value[2], value[3]); },
        bool: function setSingleBool(gl, location, value) { gl.uniform1i(location, value); },
        bvec2: function setSingleBvec2(gl, location, value) { gl.uniform2i(location, value[0], value[1]); },
        bvec3: function setSingleBvec3(gl, location, value) { gl.uniform3i(location, value[0], value[1], value[2]); },
        bvec4: function setSingleBvec4(gl, location, value) { gl.uniform4i(location, value[0], value[1], value[2], value[3]); },
        mat2: function setSingleMat2(gl, location, value) { gl.uniformMatrix2fv(location, false, value); },
        mat3: function setSingleMat3(gl, location, value) { gl.uniformMatrix3fv(location, false, value); },
        mat4: function setSingleMat4(gl, location, value) { gl.uniformMatrix4fv(location, false, value); },
        sampler2D: function setSingleSampler2D(gl, location, value) { gl.uniform1i(location, value); },
    };
    var GLSL_ARRAY_SETTERS = {
        float: function setFloatArray(gl, location, value) { gl.uniform1fv(location, value); },
        vec2: function setVec2Array(gl, location, value) { gl.uniform2fv(location, value); },
        vec3: function setVec3Array(gl, location, value) { gl.uniform3fv(location, value); },
        vec4: function setVec4Array(gl, location, value) { gl.uniform4fv(location, value); },
        int: function setIntArray(gl, location, value) { gl.uniform1iv(location, value); },
        ivec2: function setIvec2Array(gl, location, value) { gl.uniform2iv(location, value); },
        ivec3: function setIvec3Array(gl, location, value) { gl.uniform3iv(location, value); },
        ivec4: function setIvec4Array(gl, location, value) { gl.uniform4iv(location, value); },
        bool: function setBoolArray(gl, location, value) { gl.uniform1iv(location, value); },
        bvec2: function setBvec2Array(gl, location, value) { gl.uniform2iv(location, value); },
        bvec3: function setBvec3Array(gl, location, value) { gl.uniform3iv(location, value); },
        bvec4: function setBvec4Array(gl, location, value) { gl.uniform4iv(location, value); },
        sampler2D: function setSampler2DArray(gl, location, value) { gl.uniform1iv(location, value); },
    };
    function generateSetter(name, uniform) {
        return function (value) {
            this.data[name].value = value;
            var location = this.data[name].location;
            if (uniform.size === 1) {
                GLSL_SINGLE_SETTERS[uniform.type](this.gl, location, value);
            }
            else {
                GLSL_ARRAY_SETTERS[uniform.type](this.gl, location, value);
            }
        };
    }
    function getUniformGroup(nameTokens, uniform) {
        var cur = uniform;
        for (var i = 0; i < nameTokens.length - 1; i++) {
            var o = cur[nameTokens[i]] || { data: {} };
            cur[nameTokens[i]] = o;
            cur = o;
        }
        return cur;
    }

    var GLShader = (function () {
        function GLShader(gl, vertexSrc, fragmentSrc, precision, attributeLocations) {
            this.gl = gl;
            if (precision) {
                vertexSrc = setPrecision(vertexSrc, precision);
                fragmentSrc = setPrecision(fragmentSrc, precision);
            }
            this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations);
            this.attributes = extractAttributes(gl, this.program);
            this.uniformData = extractUniforms(gl, this.program);
            this.uniforms = generateUniformAccessObject(gl, this.uniformData);
        }
        GLShader.prototype.bind = function () {
            this.gl.useProgram(this.program);
            return this;
        };
        GLShader.prototype.destroy = function () {
            this.attributes = null;
            this.uniformData = null;
            this.uniforms = null;
            var gl = this.gl;
            gl.deleteProgram(this.program);
        };
        return GLShader;
    }());

    var VSHADER_SOURCE = "precision highp float;" +
        "attribute vec2 aVertexPosition;" +
        "attribute vec2 aTextureCoord;" +
        "attribute vec4 aColor;" +
        "attribute float aTextureId;" +
        "uniform mat3 projectionMatrix;" +
        "varying vec2 vTextureCoord;" +
        "varying vec4 vColor;" +
        "varying float vTextureId;" +
        "void main(void){" +
        "gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);" +
        "vTextureCoord = aTextureCoord;" +
        "vTextureId = aTextureId;" +
        "vColor = aColor;" +
        "}";
    var fragTemplate$1 = [
        'precision mediump float;',
        'varying vec2 vTextureCoord;',
        'varying vec4 vColor;',
        'varying float vTextureId;',
        'uniform sampler2D uSamplers[%count%];',
        'void main(void){',
        'vec4 color;',
        'float textureId = floor(vTextureId+0.5);',
        '%forloop%',
        'gl_FragColor = color * vColor;',
        '}',
    ].join('\n');
    function generateMultiTextureShader(gl, maxTextures) {
        var fragmentSrc = fragTemplate$1;
        fragmentSrc = fragmentSrc.replace(/%count%/gi, maxTextures);
        fragmentSrc = fragmentSrc.replace(/%forloop%/gi, generateSampleSrc(maxTextures));
        var shader = new GLShader(gl, VSHADER_SOURCE, fragmentSrc);
        var sampleValues = [];
        for (var i = 0; i < maxTextures; i++) {
            sampleValues[i] = i;
        }
        shader.bind();
        shader.uniforms["uSamplers"] = sampleValues;
        return shader;
    }
    function generateSampleSrc(maxTextures) {
        var src = '';
        src += '\n';
        src += '\n';
        for (var i = 0; i < maxTextures; i++) {
            if (i > 0) {
                src += '\nelse ';
            }
            if (i < maxTextures - 1) {
                src += "if(textureId == " + i + ".0)";
            }
            src += '\n{';
            src += "\n\tcolor = texture2D(uSamplers[" + i + "], vTextureCoord);";
            src += '\n}';
        }
        src += '\n';
        src += '\n';
        return src;
    }

    let TICK = 0;

    /**
     * 批处理核心渲染插件
     *
     * @class
     * @extends ObjectRenderer
     */
    class BatchRenderer extends ObjectRenderer {
      vertSize;
      vertByteSize;
      size;
      /**
       * 当前顶点数量
       */
      currentSize;
      /**
       * 当前索引数量
       */
      currentIndexSize;
      /**
       * 顶点数据
       */
      aBuffers;
      /**
       * 索引数据
       */
      iBuffers;
      /**
       * The default shaders that is used if a sprite doesn't have a more specific one.
       * there is a shader for each number of textures that can be rendered.
       * These shaders will also be generated on the fly as required.
       */
      shader;
      /**
       * 当前累计的绘制对象数量
       */
      currentIndex;
      /**
       * BatchDrawCall[]
       */
      groups;
      /**
       * 绘制对象数组
       * 包括图片的和矢量图的
       * @param batchElementInterface[]
       */
      elements;
      /**
       * @param  VertexArrayObject[]
       */
      vaos;
      vaoMax;
      vertexCount;
      MAX_TEXTURES;
      /**
       * @param  GLBuffer[]
       */
      vertexBuffers;
      indexBuffers;


      constructor(renderer) {
        super(renderer);
        /**
         * 每个点
         * Number of values sent in the vertex buffer.
         * aVertexPosition(2), aTextureCoord(2), aColor(1), aTextureId(1) = 6
         *
         * @member {number}
         */
        this.vertSize = 6;

        /**
         * The size of the vertex information in bytes.
         *
         * @member {number}
         */
        this.vertByteSize = this.vertSize * 4;

        /**
         * The number of images in the SpriteRenderer before it flushes.
         *
         * @member {number}
         */
        this.size = 2000 * 4;// settings.SPRITE_BATCH_SIZE; // 2000 is a nice balance between mobile / desktop

        this.currentSize = 0;
        this.currentIndexSize = 0;

        // the total number of bytes in our batch
        // let numVerts = this.size * 4 * this.vertByteSize;

        this.aBuffers = {};
        this.iBuffers = {};


        this.shader = null;


        this.currentIndex = 0;
        this.groups = [];

        for (let k = 0; k < this.size / 4; k++) {
          this.groups[k] = new BatchDrawCall();
        }

        this.elements = [];
        this.vertexBuffers = [];
        this.indexBuffers = [];
        this.vaos = [];

        this.vaoMax = 2;
        this.vertexCount = 0;

        this.renderer.addEventListener('onPreRender', this.onPreRender, this);

        // this.state = State.for2d();深度检测去掉

      }

      /**
       * Sets up the renderer context and necessary buffers.
       */
      onContextChange() {
        const gl = this.renderer.gl;

        {
          // step 1: first check max textures the GPU can handle.
          this.MAX_TEXTURES = Math.min(gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS), 16);

          // step 2: check the maximum number of if statements the shader can have too..
          this.MAX_TEXTURES = checkMaxIfStatementsInShader(this.MAX_TEXTURES, gl);
        }

        // generate generateMultiTextureProgram, may be a better move?
        this.shader = generateMultiTextureShader(gl, this.MAX_TEXTURES);

        // we use the second shader as the first one depending on your browser may omit aTextureId
        // as it is not used by the shader so is optimized out.


        this.renderer.bindVao(null);

        const attrs = this.shader.attributes;

        for (let i = 0; i < this.vaoMax; i++) {
          /* eslint-disable max-len */
          const vertexBuffer = this.vertexBuffers[i] = GLBuffer.createVertexBuffer(gl, null, gl.STREAM_DRAW);
          const indexBuffer = this.indexBuffers[i] = GLBuffer.createIndexBuffer(gl, null, gl.STREAM_DRAW);

          // build the vao object that will render..
          const vao = this.renderer.createVao()
            .addIndex(indexBuffer)
            .addAttribute(vertexBuffer, attrs.aVertexPosition, gl.FLOAT, false, this.vertByteSize, 0)
            // .addAttribute(vertexBuffer, attrs.aTextureCoord, gl.UNSIGNED_SHORT, true, this.vertByteSize, 2 * 4)
            // .addAttribute(vertexBuffer, attrs.aColor, gl.UNSIGNED_BYTE, true, this.vertByteSize, 3 * 4);
            .addAttribute(vertexBuffer, attrs.aTextureCoord, gl.FLOAT, true, this.vertByteSize, 2 * 4)
            .addAttribute(vertexBuffer, attrs.aColor, gl.UNSIGNED_BYTE, true, this.vertByteSize, 4 * 4)
            .addAttribute(vertexBuffer, attrs.aTextureId, gl.FLOAT, false, this.vertByteSize, 5 * 4);
          // if (attrs.aTextureId)
          // {
          //     vao.addAttribute(vertexBuffer, attrs.aTextureId, gl.FLOAT, false, this.vertByteSize, 4 * 4);
          // }

          this.vaos[i] = vao;
        }
      }

      /**
       * Called before the renderer starts rendering.
       *
       */
      onPreRender() {
        this.vertexCount = 0;
      }

      /**
       * Renders the sprite object.
       * element必须的属性
       * 
       * _texture  里面有.BaseTexture
       * _vertexData  
       * _indices 
       * _worldAlpha
       * _tintRGB
       * _uvs
       * 
       * @param batchElementInterface
       */
      render(element) {
        if (!element._texture || !element._texture.valid) {
          return;
        }

        if (this.currentSize + (element._vertexData.length / 2) > this.size) {
          this.flush();
        }

        this.elements[this.currentIndex++] = element;

        this.currentSize += element._vertexData.length / 2;
        this.currentIndexSize += element._indices.length;
      }

      /**
       * 获得索引buffer
       * @param size 
       */
      getIndexBuffer(size) {
        // 12 indices is enough for 2 quads
        const roundedP2 = nextPow2(Math.ceil(size / 12));
        const roundedSizeIndex = log2(roundedP2);
        const roundedSize = roundedP2 * 12;

        // if (this.iBuffers.length <= roundedSizeIndex) {
        //     this.iBuffers.length = roundedSizeIndex + 1;
        // }

        let buffer = this.iBuffers[roundedSizeIndex];

        if (!buffer) {
          this.iBuffers[roundedSizeIndex] = buffer = new Uint16Array(roundedSize);
        }

        return buffer;
      }

      /**
       * 获取相应的顶点数据buffer
       * @param size 
       */
      getAttributeBuffer(size) {
        // 8 vertices is enough for 2 quads
        const roundedP2 = nextPow2(Math.ceil(size / 8));
        const roundedSizeIndex = log2(roundedP2);
        const roundedSize = roundedP2 * 8;

        // if (this.aBuffers.length <= roundedSizeIndex) {
        //     this.iBuffers.length = roundedSizeIndex + 1;
        // }

        let buffer = this.aBuffers[roundedSize];

        if (!buffer) {
          this.aBuffers[roundedSize] = buffer = new BatchBuffer(roundedSize * this.vertByteSize);
        }

        return buffer;
      }

      /**
       * Renders the content and empties the current batch.
       *
       */
      flush() {
        if (this.currentSize === 0) {
          return;
        }

        const gl = this.renderer.gl;
        const MAX_TEXTURES = this.MAX_TEXTURES;

        const buffer = this.getAttributeBuffer(this.currentSize);
        const indexBuffer = this.getIndexBuffer(this.currentIndexSize);

        const elements = this.elements;
        const groups = this.groups;

        const float32View = buffer.float32View;
        const uint32View = buffer.uint32View;

        const touch = this.renderer.textureGC.count;

        let index = 0;
        let indexCount = 0;
        let nextTexture;
        let currentTexture;
        let groupCount = 1;

        let textureCount = 0;
        let currentGroup = groups[0];

        //let blendMode = -1;// premultiplyBlendMode[elements[0]._texture.baseTexture.premultiplyAlpha ? 0 : ][elements[0].blendMode];

        currentGroup.textureCount = 0;
        currentGroup.start = 0;
        // currentGroup.blend = blendMode;

        TICK++;

        let i;

        for (i = 0; i < this.currentIndex; ++i) {
          // upload the sprite elements...
          // they have all ready been calculated so we just need to push them into the buffer.

          const sprite = elements[i];

          elements[i] = null;

          nextTexture = sprite._texture.baseTexture;

          // const spriteBlendMode = premultiplyBlendMode[nextTexture.premultiplyAlpha ? 1 : 0][sprite.blendMode];

          // if (blendMode !== spriteBlendMode) {
          //     blendMode = spriteBlendMode;

          //     // force the batch to break!
          //     currentTexture = null;
          //     textureCount = MAX_TEXTURES;
          //     TICK++;
          // }

          if (currentTexture !== nextTexture) {
            currentTexture = nextTexture;

            if (nextTexture._enabledId !== TICK) {
              if (textureCount === MAX_TEXTURES) {
                TICK++;

                textureCount = 0;

                currentGroup.size = indexCount - currentGroup.start;

                currentGroup = groups[groupCount++];
                currentGroup.textureCount = 0;
                // currentGroup.blend = blendMode;
                currentGroup.start = indexCount;
              }

              nextTexture._touchedId = touch;
              nextTexture._enabledId = TICK;
              nextTexture._id = textureCount;

              currentGroup.textures[currentGroup.textureCount++] = nextTexture;
              textureCount++;
            }
          }
          // argb, nextTexture._id, float32View, uint32View, indexBuffer, index, indexCount);
          this.packGeometry(sprite, float32View, uint32View, indexBuffer, index, indexCount);

          // push a graphics..
          index += (sprite._vertexData.length / 2) * this.vertSize;
          indexCount += sprite._indices.length;
        }

        currentGroup.size = indexCount - currentGroup.start;

        //        this.indexBuffer.update();

        if (osType == "ios") {
          //可能有一帧，在多个地方执行flush
          // this is still needed for IOS performance..
          // it really does not like uploading to the same buffer in a single frame!
          if (this.vaoMax <= this.vertexCount) {
            this.vaoMax++;

            const attrs = this.shader.attributes;

            /* eslint-disable max-len */
            const vertexBuffer = this.vertexBuffers[this.vertexCount] = GLBuffer.createVertexBuffer(gl, null, gl.STREAM_DRAW);
            const indexBufferAdd = this.indexBuffers[this.vertexCount] = GLBuffer.createIndexBuffer(gl, null, gl.STREAM_DRAW);

            // build the vao object that will render..
            const vao = this.renderer.createVao()
              .addIndex(indexBufferAdd)
              .addAttribute(vertexBuffer, attrs.aVertexPosition, gl.FLOAT, false, this.vertByteSize, 0)
              .addAttribute(vertexBuffer, attrs.aTextureCoord, gl.FLOAT, true, this.vertByteSize, 2 * 4)
              .addAttribute(vertexBuffer, attrs.aColor, gl.UNSIGNED_BYTE, true, this.vertByteSize, 4 * 4)
              .addAttribute(vertexBuffer, attrs.aTextureId, gl.FLOAT, false, this.vertByteSize, 5 * 4);
            this.vaos[this.vertexCount] = vao;

            // console.log(this.vertexCount)
          }

          this.renderer.bindVao(this.vaos[this.vertexCount]);

          this.vertexBuffers[this.vertexCount].upload(buffer.vertices, 0, false);
          this.indexBuffers[this.vertexCount].upload(indexBuffer, 0, false);

          this.vertexCount++;

        }
        else {

          // lets use the faster option, always use buffer number 0
          this.vertexBuffers[this.vertexCount].upload(buffer.vertices, 0, true);
          this.indexBuffers[this.vertexCount].upload(indexBuffer, 0, true);
        }

        //   this.renderer.state.set(this.state);

        const textureManager = this.renderer.textureManager;
        // const stateSystem = this.renderer.state;
        // e.log(groupCount);
        // / render the groups..

        for (i = 0; i < groupCount; i++) {
          const group = groups[i];
          const groupTextureCount = group.textureCount;

          for (let j = 0; j < groupTextureCount; j++) {
            if (group.textures[j] != textureManager.boundTextures[j]) {
              //location已经和sampleId固定了，就算原先boundsTextures有，也要重新绑定位置
              // console.log("bindTexture")
              textureManager.bindTexture(group.textures[j], j, true);
            }
            group.textures[j] = null;
          }
          //混色模式暂不用
          // this.state.blendMode = group.blend;
          // this.state.blend = true;

          // this.renderer.state.setState(this.state);
          // set the blend mode..
          // stateSystem.setBlendMode(group.blend);

          gl.drawElements(group.type, group.size, gl.UNSIGNED_SHORT, group.start * 2);
        }

        // reset elements for the next flush
        this.currentIndex = 0;
        this.currentSize = 0;
        this.currentIndexSize = 0;
      }

      packGeometry(element, float32View, uint32View, indexBuffer, index, indexCount) {
        const p = index / this.vertSize;// float32View.length / 6 / 2;
        const uvs = element._uvs;
        const indicies = element._indices;// geometry.getIndex().data;// indicies;
        const vertexData = element._vertexData;
        const textureId = element._texture.baseTexture["_id"];

        var _tintRGB = element._tintRGB == undefined ? 16777215 : element._tintRGB;

        const alpha = Math.min(element._worldAlpha, 1.0);
        // we dont call extra function if alpha is 1.0, that's faster
        const argb = alpha < 1.0 && element._texture.baseTexture.premultipliedAlpha ? premultiplyTint(_tintRGB, alpha)
          : _tintRGB + (alpha * 255 << 24);

        // lets not worry about tint! for now..
        for (let i = 0; i < vertexData.length; i += 2) {
          float32View[index++] = vertexData[i];
          float32View[index++] = vertexData[i + 1];
          float32View[index++] = uvs[i];
          float32View[index++] = uvs[i + 1];
          uint32View[index++] = argb;
          float32View[index++] = textureId;
        }

        for (let i = 0; i < indicies.length; i++) {
          indexBuffer[indexCount++] = p + indicies[i];
        }
      }

      /**
       * Starts a new sprite batch.
       */
      start() {
        //暂时不考虑2d专门的状态机属性
        // this.renderer.state.setState(this.state);

        this.renderer.bindShader(this.shader);

        if (osType != "ios") {
          this.renderer.bindVao(this.vaos[this.vertexCount]);
          this.vertexBuffers[this.vertexCount].bind();
          this.indexBuffers[this.vertexCount].bind();
        }
      }

      /**
       * Stops and flushes the current batch.
       *
       */
      stop() {
        this.flush();
      }

      /**
       * Destroys the SpriteRenderer.
       *
       */
      destroy() {
        for (let i = 0; i < this.vaoMax; i++) {
          // if (this.vertexBuffers[i])
          // {
          //     this.vertexBuffers[i].destroy();
          // }
          if (this.vaos[i]) {
            this.vaos[i].destroy();
          }
        }

        this.renderer.removeEventListener('onPreRender', this.onPreRender, this);

        if (this.shader) {
          this.shader.destroy();
          this.shader = null;
        }

        this.vaos = null;

        super.destroy();
      }
    }

    // interface batchElementInterface {
    //     _texture: Texture,
    //     _worldAlpha,
    //     _vertexData: Float32Array,
    //     _indices: Uint16Array,
    //     _tintRGB?,
    //     _uvs: Float32Array,
    // }

    var RenderTarget = (function () {
        function RenderTarget(gl, width, height, scaleMode, root) {
            if (width === void 0) { width = 0; }
            if (height === void 0) { height = 0; }
            if (scaleMode === void 0) { scaleMode = exports.SCALE_MODES.LINEAR; }
            if (root === void 0) { root = false; }
            this.gl = gl;
            this.frameBuffer = null;
            this.texture = null;
            this.clearColor = [0, 0, 0, 0];
            this.size = new Rectangle(0, 0, 1, 1);
            this.projectionMatrix = new Matrix();
            this.transform = null;
            this.frame = null;
            this.defaultFrame = new Rectangle();
            this.destinationFrame = null;
            this.sourceFrame = null;
            this.stencilBuffer = null;
            this.stencilMaskStack = [];
            this.filterData = null;
            this.filterPoolKey = '';
            this.scaleMode = scaleMode;
            this.root = root;
            if (!this.root) {
                this.frameBuffer = GLFramebuffer.createRGBA(gl, 100, 100);
                if (this.scaleMode === exports.SCALE_MODES.NEAREST) {
                    this.frameBuffer.texture.enableNearestScaling();
                }
                else {
                    this.frameBuffer.texture.enableLinearScaling();
                }
                this.texture = this.frameBuffer.texture;
            }
            else {
                this.frameBuffer = new GLFramebuffer(gl, 100, 100);
                this.frameBuffer.framebuffer = null;
            }
            this.setFrame();
            this.resize(width, height);
        }
        RenderTarget.prototype.clear = function (clearColor) {
            var cc = clearColor || this.clearColor;
            this.frameBuffer.clear(cc[0], cc[1], cc[2], cc[3]);
        };
        RenderTarget.prototype.attachStencilBuffer = function () {
            if (!this.root) {
                this.frameBuffer.enableStencil();
            }
        };
        RenderTarget.prototype.setFrame = function (destinationFrame, sourceFrame) {
            this.destinationFrame = destinationFrame || this.destinationFrame || this.defaultFrame;
            this.sourceFrame = sourceFrame || this.sourceFrame || this.destinationFrame;
        };
        RenderTarget.prototype.activate = function () {
            var gl = this.gl;
            this.frameBuffer.bind();
            this.calculateProjection(this.destinationFrame, this.sourceFrame);
            if (this.transform) {
                this.projectionMatrix.append(this.transform);
            }
            if (this.destinationFrame !== this.sourceFrame) {
                gl.enable(gl.SCISSOR_TEST);
                gl.scissor(this.destinationFrame.x | 0, this.destinationFrame.y | 0, this.destinationFrame.width | 0, this.destinationFrame.height | 0);
            }
            else {
                gl.disable(gl.SCISSOR_TEST);
            }
            gl.viewport(this.destinationFrame.x | 0, this.destinationFrame.y | 0, this.destinationFrame.width | 0, this.destinationFrame.height | 0);
        };
        RenderTarget.prototype.calculateProjection = function (destinationFrame, sourceFrame) {
            var pm = this.projectionMatrix;
            sourceFrame = sourceFrame || destinationFrame;
            pm.identity();
            if (!this.root) {
                pm.a = 1 / destinationFrame.width * 2;
                pm.d = 1 / destinationFrame.height * 2;
                pm.tx = -1 - (sourceFrame.x * pm.a);
                pm.ty = -1 - (sourceFrame.y * pm.d);
            }
            else {
                pm.a = 1 / destinationFrame.width * 2;
                pm.d = -1 / destinationFrame.height * 2;
                pm.tx = -1 - (sourceFrame.x * pm.a);
                pm.ty = 1 - (sourceFrame.y * pm.d);
            }
        };
        RenderTarget.prototype.resize = function (width, height) {
            width = width | 0;
            height = height | 0;
            if (this.size.width === width && this.size.height === height) {
                return;
            }
            this.size.width = width;
            this.size.height = height;
            this.defaultFrame.width = width;
            this.defaultFrame.height = height;
            this.frameBuffer.resize(width, height);
            var projectionFrame = this.frame || this.size;
            this.calculateProjection(projectionFrame);
        };
        RenderTarget.prototype.destroy = function () {
            this.frameBuffer.destroy();
            this.frameBuffer = null;
            this.texture = null;
        };
        return RenderTarget;
    }());

    var TextureManager = (function () {
        function TextureManager(renderer) {
            this._nextTextureLocation = 0;
            this.renderer = renderer;
            this.gl = renderer.gl;
            this._managedTextures = [];
            this.renderer.addEventListener('onContextChange', this.onContextChange, this);
        }
        TextureManager.prototype.onContextChange = function () {
            var gl = this.gl;
            var maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS);
            this.boundTextures = new Array(maxTextures);
            this.emptyTextures = new Array(maxTextures);
            var emptyGLTexture = GLTexture.fromData(gl, null, 1, 1);
            var tempObj = { _glTextures: {} };
            tempObj._glTextures[this.renderer.CONTEXT_UID] = {};
            for (var i = 0; i < maxTextures; i++) {
                var empty = new BaseTexture();
                empty._glTextures[this.renderer.CONTEXT_UID] = emptyGLTexture;
                this.boundTextures[i] = tempObj;
                this.emptyTextures[i] = empty;
                this.bindTexture(null, i);
            }
        };
        TextureManager.prototype.bindTexture = function (texture, location, forceLocation) {
            texture = texture || this.emptyTextures[location];
            texture = texture.baseTexture || texture;
            texture._touchedId = this.renderer.textureGC.count;
            if (!forceLocation) {
                for (var i = 0; i < this.boundTextures.length; i++) {
                    if (this.boundTextures[i] === texture) {
                        return i;
                    }
                }
                if (location === undefined) {
                    this._nextTextureLocation++;
                    this._nextTextureLocation %= this.boundTextures.length;
                    location = this.boundTextures.length - this._nextTextureLocation - 1;
                }
            }
            else {
                location = location || 0;
            }
            var gl = this.gl;
            var glTexture = texture._glTextures[this.renderer.CONTEXT_UID];
            if (!glTexture) {
                this.updateTexture(texture, location);
            }
            else {
                if (this.currentLocation !== location) {
                    this.currentLocation = location;
                    gl.activeTexture(gl.TEXTURE0 + location);
                }
                if (this.boundTextures[location] !== texture) {
                    gl.bindTexture(gl.TEXTURE_2D, glTexture.texture);
                }
                this.boundTextures[location] = texture;
            }
            return location;
        };
        TextureManager.prototype.getTexture = function () {
        };
        TextureManager.prototype.updateTexture = function (texture, location) {
            if (texture.instanceType === "Event") {
                texture = texture.target.baseTexture || texture.target;
            }
            else {
                texture = texture.baseTexture || texture;
            }
            var gl = this.gl;
            var isRenderTexture = !!texture["_glRenderTargets"];
            if (!texture.hasLoaded) {
                return null;
            }
            var boundTextures = this.boundTextures;
            if (location === undefined) {
                location = 0;
                for (var i = 0; i < boundTextures.length; ++i) {
                    if (boundTextures[i] === texture) {
                        location = i;
                        break;
                    }
                }
            }
            boundTextures[location] = texture;
            if (this.currentLocation !== location) {
                this.currentLocation = location;
                gl.activeTexture(gl.TEXTURE0 + location);
            }
            var glTexture = texture._glTextures[this.renderer.CONTEXT_UID];
            if (!glTexture) {
                if (isRenderTexture) {
                    var renderTarget = new RenderTarget(this.gl, texture.width, texture.height, texture.scaleMode, false);
                    renderTarget.resize(texture.width, texture.height);
                    texture._glRenderTargets[this.renderer.CONTEXT_UID] = renderTarget;
                    glTexture = renderTarget.texture;
                }
                else {
                    glTexture = new GLTexture(this.gl, null, null, null, null);
                    glTexture.premultiplyAlpha = true;
                    if (texture.source.data) {
                        glTexture.uploadData(texture.source.data, texture.width, texture.height);
                    }
                    else {
                        glTexture.upload(texture.source);
                    }
                }
                texture._glTextures[this.renderer.CONTEXT_UID] = glTexture;
                texture.addEventListener('update', this.updateTexture, this);
                texture.addEventListener('dispose', this.destroyTexture, this);
                this._managedTextures.push(texture);
                if (texture.isPowerOfTwo) {
                    if (texture.mipmap) {
                        glTexture.enableMipmap();
                    }
                    if (texture.wrapMode === exports.WRAP_MODES.CLAMP) {
                        glTexture.enableWrapClamp();
                    }
                    else if (texture.wrapMode === exports.WRAP_MODES.REPEAT) {
                        glTexture.enableWrapRepeat();
                    }
                    else {
                        glTexture.enableWrapMirrorRepeat();
                    }
                }
                else {
                    glTexture.enableWrapClamp();
                }
                if (texture.scaleMode === exports.SCALE_MODES.NEAREST) {
                    glTexture.enableNearestScaling();
                }
                else {
                    glTexture.enableLinearScaling();
                }
            }
            else if (isRenderTexture) {
                texture._glRenderTargets[this.renderer.CONTEXT_UID].resize(texture.width, texture.height);
            }
            else {
                if (texture.source.data) {
                    glTexture.uploadData(texture.source.data, texture.width, texture.height);
                }
                else {
                    glTexture.upload(texture.source);
                }
            }
            return glTexture;
        };
        TextureManager.prototype.unbindTexture = function (texture) {
            var gl = this.gl;
            texture = texture.baseTexture || texture;
            for (var i = 0; i < this.boundTextures.length; i++) {
                if (this.boundTextures[i] === texture) {
                    this.boundTextures[i] = this.emptyTextures[i];
                    if (this.currentLocation !== i) {
                        gl.activeTexture(gl.TEXTURE0 + i);
                        this.currentLocation = i;
                    }
                    gl.bindTexture(gl.TEXTURE_2D, this.emptyTextures[i]._glTextures[this.renderer.CONTEXT_UID].texture);
                }
            }
        };
        TextureManager.prototype.destroyTexture = function (texture, skipRemove) {
            texture = texture.baseTexture || texture;
            if (!texture.hasLoaded) {
                return;
            }
            var uid = this.renderer.CONTEXT_UID;
            var glTextures = texture._glTextures;
            var glRenderTargets = texture._glRenderTargets;
            if (glTextures[uid]) {
                this.unbindTexture(texture);
                glTextures[uid].destroy();
                texture.removeEventListener('update', this.updateTexture, this);
                texture.removeEventListener('dispose', this.destroyTexture, this);
                delete glTextures[uid];
                if (!skipRemove) {
                    var i = this._managedTextures.indexOf(texture);
                    if (i !== -1) {
                        removeItems(this._managedTextures, i, 1);
                    }
                }
            }
            if (glRenderTargets && glRenderTargets[uid]) {
                glRenderTargets[uid].destroy();
                delete glRenderTargets[uid];
            }
        };
        TextureManager.prototype.removeAll = function () {
            for (var i = 0; i < this._managedTextures.length; ++i) {
                var texture = this._managedTextures[i];
                if (texture._glTextures[this.renderer.CONTEXT_UID]) {
                    delete texture._glTextures[this.renderer.CONTEXT_UID];
                }
            }
        };
        TextureManager.prototype.destroy = function () {
            for (var i = 0; i < this._managedTextures.length; ++i) {
                var texture = this._managedTextures[i];
                this.destroyTexture(texture, true);
            }
            this.renderer.removeEventListener('onContextChange', this.onContextChange, this);
            this.renderer = null;
            this._managedTextures = null;
        };
        return TextureManager;
    }());

    var TextureGarbageCollector = (function () {
        function TextureGarbageCollector(renderer) {
            this.renderer = renderer;
            this.count = 0;
            this.checkCount = 0;
            this.maxIdle = 60 * 60;
            this.checkCountMax = 60 * 10;
            this.mode = exports.GC_MODES.AUTO;
        }
        TextureGarbageCollector.prototype.update = function () {
            this.count++;
            if (this.mode === exports.GC_MODES.MANUAL) {
                return;
            }
            this.checkCount++;
            if (this.checkCount > this.checkCountMax) {
                this.checkCount = 0;
                this.run();
            }
        };
        TextureGarbageCollector.prototype.run = function () {
            var tm = this.renderer.textureManager;
            var managedTextures = tm._managedTextures;
            var wasRemoved = false;
            for (var i = 0; i < managedTextures.length; i++) {
                var texture = managedTextures[i];
                if (!texture._glRenderTargets && this.count - texture._touchedId > this.maxIdle) {
                    tm.destroyTexture(texture, true);
                    managedTextures[i] = null;
                    wasRemoved = true;
                }
            }
            if (wasRemoved) {
                var j = 0;
                for (var i = 0; i < managedTextures.length; i++) {
                    if (managedTextures[i] !== null) {
                        managedTextures[j++] = managedTextures[i];
                    }
                }
                managedTextures.length = j;
            }
        };
        TextureGarbageCollector.prototype.unload = function (displayObject) {
            var tm = this.renderer.textureManager;
            if (displayObject._texture && displayObject._texture._glRenderTargets) {
                tm.destroyTexture(displayObject._texture, true);
            }
            for (var i = displayObject.children.length - 1; i >= 0; i--) {
                this.unload(displayObject.children[i]);
            }
        };
        return TextureGarbageCollector;
    }());

    var BLEND = 0;
    var DEPTH_TEST = 1;
    var FRONT_FACE = 2;
    var CULL_FACE = 3;
    var BLEND_FUNC = 4;
    var WebGLState = (function () {
        function WebGLState(gl) {
            this.activeState = new Uint8Array(16);
            this.defaultState = new Uint8Array(16);
            this.defaultState[0] = 1;
            this.gl = gl;
            this.maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS);
            this.attribState = {
                tempAttribState: new Array(this.maxAttribs),
                attribState: new Array(this.maxAttribs),
            };
            this.blendModes = mapWebGLBlendModes(gl);
            this.nativeVaoExtension = (gl.getExtension('OES_vertex_array_object')
                || gl.getExtension('MOZ_OES_vertex_array_object')
                || gl.getExtension('WEBKIT_OES_vertex_array_object'));
        }
        WebGLState.prototype.setState = function (state) {
            this.setBlend(state[BLEND]);
            this.setDepthTest(state[DEPTH_TEST]);
            this.setFrontFace(state[FRONT_FACE]);
            this.setCullFace(state[CULL_FACE]);
            this.setBlendMode(state[BLEND_FUNC]);
        };
        WebGLState.prototype.setBlend = function (value) {
            value = value ? 1 : 0;
            if (this.activeState[BLEND] === value) {
                return;
            }
            this.activeState[BLEND] = value;
            this.gl[value ? 'enable' : 'disable'](this.gl.BLEND);
        };
        WebGLState.prototype.setBlendMode = function (value) {
            if (value === this.activeState[BLEND_FUNC]) {
                return;
            }
            this.activeState[BLEND_FUNC] = value;
            var mode = this.blendModes[value];
            if (mode.length === 2) {
                this.gl.blendFunc(mode[0], mode[1]);
            }
            else {
                this.gl.blendFuncSeparate(mode[0], mode[1], mode[2], mode[3]);
            }
        };
        WebGLState.prototype.setDepthTest = function (value) {
            value = value ? 1 : 0;
            if (this.activeState[DEPTH_TEST] === value) {
                return;
            }
            this.activeState[DEPTH_TEST] = value;
            this.gl[value ? 'enable' : 'disable'](this.gl.DEPTH_TEST);
        };
        WebGLState.prototype.setCullFace = function (value) {
            value = value ? 1 : 0;
            if (this.activeState[CULL_FACE] === value) {
                return;
            }
            this.activeState[CULL_FACE] = value;
            this.gl[value ? 'enable' : 'disable'](this.gl.CULL_FACE);
        };
        WebGLState.prototype.setFrontFace = function (value) {
            value = value ? 1 : 0;
            if (this.activeState[FRONT_FACE] === value) {
                return;
            }
            this.activeState[FRONT_FACE] = value;
            this.gl.frontFace(this.gl[value ? 'CW' : 'CCW']);
        };
        WebGLState.prototype.resetAttributes = function () {
            for (var i = 0; i < this.attribState.tempAttribState.length; i++) {
                this.attribState.tempAttribState[i] = 0;
            }
            for (var i = 0; i < this.attribState.attribState.length; i++) {
                this.attribState.attribState[i] = 0;
            }
            for (var i = 1; i < this.maxAttribs; i++) {
                this.gl.disableVertexAttribArray(i);
            }
        };
        WebGLState.prototype.resetToDefault = function () {
            if (this.nativeVaoExtension) {
                this.nativeVaoExtension.bindVertexArrayOES(null);
            }
            this.resetAttributes();
            for (var i = 0; i < this.activeState.length; ++i) {
                this.activeState[i] = 32;
            }
            this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL, false);
            this.setState(this.defaultState);
        };
        WebGLState.prototype.resetTo3D = function () {
            this.setDepthTest(1);
            this.setFrontFace(0);
            this.setCullFace(1);
        };
        return WebGLState;
    }());

    var BatchManager = (function () {
        function BatchManager(renderer) {
            this.renderer = renderer;
            this.emptyRenderer = new ObjectRenderer(renderer);
            this.currentRenderer = this.emptyRenderer;
        }
        BatchManager.prototype.setObjectRenderer = function (objectRenderer) {
            if (this.currentRenderer === objectRenderer) {
                return;
            }
            this.currentRenderer.stop();
            this.currentRenderer = objectRenderer;
            this.currentRenderer.start();
        };
        BatchManager.prototype.flush = function () {
            this.setObjectRenderer(this.emptyRenderer);
        };
        BatchManager.prototype.reset = function () {
            this.setObjectRenderer(this.emptyRenderer);
        };
        return BatchManager;
    }());

    function extractUniformsFromSrc(vertexSrc, fragmentSrc) {
        var vertUniforms = extractUniformsFromString(vertexSrc);
        var fragUniforms = extractUniformsFromString(fragmentSrc);
        return Object["assign"](vertUniforms, fragUniforms);
    }
    function extractUniformsFromString(string) {
        var maskRegex = new RegExp('^(projectionMatrix|uSampler|filterArea|filterClamp)$');
        var uniforms = {};
        var nameSplit;
        var lines = string.replace(/\s+/g, ' ')
            .split(/\s*;\s*/);
        for (var i = 0; i < lines.length; i++) {
            var line = lines[i].trim();
            if (line.indexOf('uniform') > -1) {
                var splitLine = line.split(' ');
                var type = splitLine[1];
                var name = splitLine[2];
                var size = 1;
                if (name.indexOf('[') > -1) {
                    nameSplit = name.split(/\[|]/);
                    name = nameSplit[0];
                    size *= Number(nameSplit[1]);
                }
                if (!name.match(maskRegex)) {
                    uniforms[name] = {
                        value: defaultValue(type, size),
                        name: name,
                        type: type,
                    };
                }
            }
        }
        return uniforms;
    }

    var SOURCE_KEY_MAP = {};
    var Filter = (function () {
        function Filter(vertexSrc, fragmentSrc, uniforms) {
            this.vertexSrc = vertexSrc || Filter.defaultVertexSrc;
            this.fragmentSrc = fragmentSrc || Filter.defaultFragmentSrc;
            this._blendMode = exports.BLEND_MODES.NORMAL;
            this.uniformData = uniforms || extractUniformsFromSrc(this.vertexSrc, this.fragmentSrc);
            this.uniforms = {};
            for (var i in this.uniformData) {
                this.uniforms[i] = this.uniformData[i].value;
                if (this.uniformData[i].type) {
                    this.uniformData[i].type = this.uniformData[i].type.toLowerCase();
                }
            }
            this.glShaders = {};
            if (!SOURCE_KEY_MAP[this.vertexSrc + this.fragmentSrc]) {
                SOURCE_KEY_MAP[this.vertexSrc + this.fragmentSrc] = uid();
            }
            this.glShaderKey = SOURCE_KEY_MAP[this.vertexSrc + this.fragmentSrc];
            this.padding = 4;
            this.resolution = 1;
            this.enabled = true;
            this.autoFit = true;
        }
        Object.defineProperty(Filter.prototype, "blendMode", {
            get: function () {
                return this._blendMode;
            },
            set: function (value) {
                this._blendMode = value;
            },
            enumerable: true,
            configurable: true
        });
        Filter.prototype.apply = function (filterManager, input, output, clear) {
            filterManager.applyFilter(this, input, output, clear);
        };
        Object.defineProperty(Filter, "defaultVertexSrc", {
            get: function () {
                return [
                    'attribute vec2 aVertexPosition;',
                    'attribute vec2 aTextureCoord;',
                    'uniform mat3 projectionMatrix;',
                    'uniform mat3 filterMatrix;',
                    'varying vec2 vTextureCoord;',
                    'varying vec2 vFilterCoord;',
                    'void main(void){',
                    '   gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);',
                    '   vFilterCoord = ( filterMatrix * vec3( aTextureCoord, 1.0)  ).xy;',
                    '   vTextureCoord = aTextureCoord ;',
                    '}',
                ].join('\n');
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Filter, "defaultFragmentSrc", {
            get: function () {
                return [
                    'varying vec2 vTextureCoord;',
                    'varying vec2 vFilterCoord;',
                    'uniform sampler2D uSampler;',
                    'uniform sampler2D filterSampler;',
                    'void main(void){',
                    '   vec4 masky = texture2D(filterSampler, vFilterCoord);',
                    '   vec4 sample = texture2D(uSampler, vTextureCoord);',
                    '   vec4 color;',
                    '   if(mod(vFilterCoord.x, 1.0) > 0.5)',
                    '   {',
                    '     color = vec4(1.0, 0.0, 0.0, 1.0);',
                    '   }',
                    '   else',
                    '   {',
                    '     color = vec4(0.0, 1.0, 0.0, 1.0);',
                    '   }',
                    '   gl_FragColor = mix(sample, masky, 0.5);',
                    '   gl_FragColor *= sample.a;',
                    '}',
                ].join('\n');
            },
            enumerable: true,
            configurable: true
        });
        return Filter;
    }());

    var fxaaVert = "precision highp float;" +
        "attribute vec2 aVertexPosition;" +
        "attribute vec2 aTextureCoord;" +
        "uniform mat3 projectionMatrix;" +
        "varying vec2 v_rgbNW;" +
        "varying vec2 v_rgbNE;" +
        "varying vec2 v_rgbSW;" +
        "varying vec2 v_rgbSE;" +
        "varying vec2 v_rgbM;" +
        "uniform vec4 filterArea;" +
        "varying vec2 vTextureCoord;" +
        "vec2 mapCoord( vec2 coord ){" +
        "coord *= filterArea.xy;" +
        "coord += filterArea.zw;" +
        "return coord;" +
        "}" +
        "vec2 unmapCoord( vec2 coord ){" +
        "coord -= filterArea.zw;" +
        "coord /= filterArea.xy;" +
        "return coord;" +
        "}" +
        "void texcoords(vec2 fragCoord, vec2 resolution," +
        "out vec2 v_rgbNW, out vec2 v_rgbNE," +
        "out vec2 v_rgbSW, out vec2 v_rgbSE," +
        "out vec2 v_rgbM) {" +
        "vec2 inverseVP = 1.0 / resolution.xy;" +
        "v_rgbNW = (fragCoord + vec2(-1.0, -1.0)) * inverseVP;" +
        "v_rgbNE = (fragCoord + vec2(1.0, -1.0)) * inverseVP;" +
        "v_rgbSW = (fragCoord + vec2(-1.0, 1.0)) * inverseVP;" +
        "v_rgbSE = (fragCoord + vec2(1.0, 1.0)) * inverseVP;" +
        "v_rgbM = vec2(fragCoord * inverseVP);" +
        "}" +
        "void main(void) {" +
        "gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);" +
        "vTextureCoord = aTextureCoord;" +
        "vec2 fragCoord = vTextureCoord * filterArea.xy;" +
        "texcoords(fragCoord, filterArea.xy, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);" +
        "}";
    var fxaaFrag = [
        'precision highp float;',
        'varying vec2 v_rgbNW;',
        'varying vec2 v_rgbNE;',
        'varying vec2 v_rgbSW;',
        'varying vec2 v_rgbSE;',
        'varying vec2 v_rgbM;',
        'varying vec2 vTextureCoord;',
        'uniform sampler2D uSampler;',
        'uniform vec4 filterArea;',
        '#ifndef FXAA_REDUCE_MIN',
        '#define FXAA_REDUCE_MIN   (1.0/ 128.0)',
        '#endif',
        '#ifndef FXAA_REDUCE_MUL',
        '#define FXAA_REDUCE_MUL   (1.0 / 8.0)',
        '#endif',
        '#ifndef FXAA_SPAN_MAX',
        '#define FXAA_SPAN_MAX     8.0',
        '#endif',
        'vec4 fxaa(sampler2D tex, vec2 fragCoord, vec2 resolution,',
        'vec2 v_rgbNW, vec2 v_rgbNE,',
        'vec2 v_rgbSW, vec2 v_rgbSE,',
        'vec2 v_rgbM) {',
        'vec4 color;',
        'mediump vec2 inverseVP = vec2(1.0 / resolution.x, 1.0 / resolution.y);',
        'vec3 rgbNW = texture2D(tex, v_rgbNW).xyz;',
        'vec3 rgbNE = texture2D(tex, v_rgbNE).xyz;',
        'vec3 rgbSW = texture2D(tex, v_rgbSW).xyz;',
        'vec3 rgbSE = texture2D(tex, v_rgbSE).xyz;',
        'vec4 texColor = texture2D(tex, v_rgbM);',
        'vec3 rgbM  = texColor.xyz;',
        'vec3 luma = vec3(0.299, 0.587, 0.114);',
        'float lumaNW = dot(rgbNW, luma);',
        'float lumaNE = dot(rgbNE, luma);',
        'float lumaSW = dot(rgbSW, luma);',
        'float lumaSE = dot(rgbSE, luma);',
        'float lumaM  = dot(rgbM,  luma);',
        'float lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));',
        'float lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));',
        'mediump vec2 dir;',
        'dir.x = -((lumaNW + lumaNE) - (lumaSW + lumaSE));',
        'dir.y =  ((lumaNW + lumaSW) - (lumaNE + lumaSE));',
        'float dirReduce = max((lumaNW + lumaNE + lumaSW + lumaSE) *',
        '(0.25 * FXAA_REDUCE_MUL), FXAA_REDUCE_MIN);',
        'float rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);',
        'dir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),',
        'max(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),',
        'dir * rcpDirMin)) * inverseVP;',
        'vec3 rgbA = 0.5 * (',
        'texture2D(tex, fragCoord * inverseVP + dir * (1.0 / 3.0 - 0.5)).xyz +',
        'texture2D(tex, fragCoord * inverseVP + dir * (2.0 / 3.0 - 0.5)).xyz);',
        'vec3 rgbB = rgbA * 0.5 + 0.25 * (',
        'texture2D(tex, fragCoord * inverseVP + dir * -0.5).xyz +',
        'texture2D(tex, fragCoord * inverseVP + dir * 0.5).xyz);',
        'float lumaB = dot(rgbB, luma);',
        'if ((lumaB < lumaMin) || (lumaB > lumaMax))',
        'color = vec4(rgbA, texColor.a);',
        'else',
        'color = vec4(rgbB, texColor.a);',
        'return color;',
        '}',
        'void main() {',
        'vec2 fragCoord = vTextureCoord * filterArea.xy;',
        'vec4 color;',
        'color = fxaa(uSampler, fragCoord, filterArea.xy, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);',
        'gl_FragColor = color;',
        '}'
    ].join("\n");
    var FXAAFilter = (function (_super) {
        tslib_1.__extends(FXAAFilter, _super);
        function FXAAFilter() {
            return _super.call(this, fxaaVert, fxaaFrag) || this;
        }
        return FXAAFilter;
    }(Filter));

    var defaultVert = "precision highp float;" +
        "attribute vec2 aVertexPosition;" +
        "attribute vec2 aTextureCoord;" +
        "uniform mat3 projectionMatrix;" +
        "varying vec2 vTextureCoord;" +
        "void main(void){" +
        "gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);" +
        "vTextureCoord = aTextureCoord;" +
        "}";
    var defaultFilterMatrix = "precision highp float;" +
        "attribute vec2 aVertexPosition;" +
        "attribute vec2 aTextureCoord;" +
        "uniform mat3 projectionMatrix;" +
        "uniform mat3 filterMatrix;" +
        "varying vec2 vTextureCoord;" +
        "varying vec2 vFilterCoord;" +
        "void main(void){" +
        "gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);" +
        "vFilterCoord = ( filterMatrix * vec3( aTextureCoord, 1.0)  ).xy;" +
        "vTextureCoord = aTextureCoord;" +
        "}";

    var noiseFrag = "precision mediump float;" +
        "varying vec2 vTextureCoord;" +
        "varying vec4 vColor;" +
        "uniform float uNoise;" +
        "uniform float uSeed;" +
        "uniform sampler2D uSampler;" +
        "float rand(vec2 co){" +
        "return fract(sin(dot(co.xy, vec2(12.9898, 78.233))) * 43758.5453);" +
        "}" +
        "void main(){" +
        "vec4 color = texture2D(uSampler, vTextureCoord);" +
        "float randomValue = rand(gl_FragCoord.xy * uSeed);" +
        "float diff = (randomValue - 0.5) * uNoise;" +
        "if (color.a > 0.0) {" +
        "color.rgb /= color.a;" +
        "}" +
        "color.r += diff;" +
        "color.g += diff;" +
        "color.b += diff;" +
        "color.rgb *= color.a;" +
        "gl_FragColor = color;" +
        "}";
    var NoiseFilter = (function (_super) {
        tslib_1.__extends(NoiseFilter, _super);
        function NoiseFilter(noise, seed) {
            if (noise === void 0) { noise = 0.5; }
            if (seed === void 0) { seed = Math.random(); }
            var _this = _super.call(this, defaultVert, noiseFrag) || this;
            _this.noise = noise;
            _this.seed = seed;
            return _this;
        }
        Object.defineProperty(NoiseFilter.prototype, "noise", {
            get: function () {
                return this.uniforms.uNoise;
            },
            set: function (value) {
                this.uniforms.uNoise = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(NoiseFilter.prototype, "seed", {
            get: function () {
                return this.uniforms.uSeed;
            },
            set: function (value) {
                this.uniforms.uSeed = value;
            },
            enumerable: true,
            configurable: true
        });
        return NoiseFilter;
    }(Filter));

    var displacementFrag = 'precision mediump float;' +
        'varying vec2 vFilterCoord;' +
        'varying vec2 vTextureCoord;' +
        'uniform vec2 scale;' +
        'uniform sampler2D uSampler;' +
        'uniform sampler2D mapSampler;' +
        'uniform vec4 filterArea;' +
        'uniform vec4 filterClamp;' +
        'void main(void){' +
        'vec4 map = texture2D(mapSampler, vFilterCoord);' +
        'map -= 0.5;' +
        'map.xy *= scale / filterArea.xy;' +
        'gl_FragColor = texture2D(uSampler, clamp(vec2(vTextureCoord.x + map.x, vTextureCoord.y + map.y), filterClamp.xy, filterClamp.zw));' +
        '}';
    var DisplacementFilter = (function (_super) {
        tslib_1.__extends(DisplacementFilter, _super);
        function DisplacementFilter(sprite, scale) {
            var _this = this;
            var maskMatrix = new Matrix();
            sprite.renderable = false;
            _this = _super.call(this, defaultFilterMatrix, displacementFrag) || this;
            _this.maskSprite = sprite;
            _this.maskMatrix = maskMatrix;
            _this.uniforms.mapSampler = sprite._texture;
            _this.uniforms.filterMatrix = maskMatrix;
            _this.uniforms.scale = { x: 1, y: 1 };
            if (scale === null || scale === undefined)
                scale = 20;
            _this.scale = new Point(scale, scale);
            return _this;
        }
        DisplacementFilter.prototype.apply = function (filterManager, input, output) {
            this.uniforms.filterMatrix = filterManager.calculateSpriteMatrix(this.maskMatrix, this.maskSprite);
            this.uniforms.scale.x = this.scale.x;
            this.uniforms.scale.y = this.scale.y;
            filterManager.applyFilter(this, input, output);
        };
        Object.defineProperty(DisplacementFilter.prototype, "map", {
            get: function () {
                return this.uniforms.mapSampler;
            },
            set: function (value) {
                this.uniforms.mapSampler = value;
            },
            enumerable: true,
            configurable: true
        });
        return DisplacementFilter;
    }(Filter));

    var vertTemplate = [
        'attribute vec2 aVertexPosition;',
        'attribute vec2 aTextureCoord;',
        'uniform float strength;',
        'uniform mat3 projectionMatrix;',
        'varying vec2 vBlurTexCoords[%size%];',
        'void main(void)',
        '{',
        'gl_Position = vec4((projectionMatrix * vec3((aVertexPosition), 1.0)).xy, 0.0, 1.0);',
        '%blur%',
        '}',
    ].join('\n');
    function generateVertBlurSource(kernelSize, x) {
        var halfLength = Math.ceil(kernelSize / 2);
        var vertSource = vertTemplate;
        var blurLoop = '';
        var template;
        if (x) {
            template = 'vBlurTexCoords[%index%] = aTextureCoord + vec2(%sampleIndex% * strength, 0.0);';
        }
        else {
            template = 'vBlurTexCoords[%index%] = aTextureCoord + vec2(0.0, %sampleIndex% * strength);';
        }
        for (var i = 0; i < kernelSize; i++) {
            var blur = template.replace('%index%', i);
            blur = blur.replace('%sampleIndex%', i - (halfLength - 1) + ".0");
            blurLoop += blur;
            blurLoop += '\n';
        }
        vertSource = vertSource.replace('%blur%', blurLoop);
        vertSource = vertSource.replace('%size%', kernelSize);
        return vertSource;
    }

    var GAUSSIAN_VALUES = {
        5: [0.153388, 0.221461, 0.250301],
        7: [0.071303, 0.131514, 0.189879, 0.214607],
        9: [0.028532, 0.067234, 0.124009, 0.179044, 0.20236],
        11: [0.0093, 0.028002, 0.065984, 0.121703, 0.175713, 0.198596],
        13: [0.002406, 0.009255, 0.027867, 0.065666, 0.121117, 0.174868, 0.197641],
        15: [0.000489, 0.002403, 0.009246, 0.02784, 0.065602, 0.120999, 0.174697, 0.197448],
    };
    var fragTemplate$2 = [
        'precision mediump float;',
        'varying vec2 vBlurTexCoords[%size%];',
        'uniform sampler2D uSampler;',
        'void main(void)',
        '{',
        '    gl_FragColor = vec4(0.0);',
        '    %blur%',
        '}',
    ].join('\n');
    function generateFragBlurSource(kernelSize) {
        var kernel = GAUSSIAN_VALUES[kernelSize];
        var halfLength = kernel.length;
        var fragSource = fragTemplate$2;
        var blurLoop = '';
        var template = 'gl_FragColor += texture2D(uSampler, vBlurTexCoords[%index%]) * %value%;';
        var value;
        for (var i = 0; i < kernelSize; i++) {
            var blur = template.replace('%index%', i + "");
            value = i;
            if (i >= halfLength) {
                value = kernelSize - i - 1;
            }
            blur = blur.replace('%value%', kernel[value]);
            blurLoop += blur;
            blurLoop += '\n';
        }
        fragSource = fragSource.replace('%blur%', blurLoop);
        fragSource = fragSource.replace('%size%', kernelSize);
        return fragSource;
    }

    function getMaxBlurKernelSize(gl) {
        var maxVaryings = (gl.getParameter(gl.MAX_VARYING_VECTORS));
        var kernelSize = 15;
        while (kernelSize > maxVaryings) {
            kernelSize -= 2;
        }
        return kernelSize;
    }

    var BlurXFilter = (function (_super) {
        tslib_1.__extends(BlurXFilter, _super);
        function BlurXFilter(strength, quality, resolution, kernelSize) {
            var _this = this;
            kernelSize = kernelSize || 5;
            var vertSrc = generateVertBlurSource(kernelSize, true);
            var fragSrc = generateFragBlurSource(kernelSize);
            _this = _super.call(this, vertSrc, fragSrc) || this;
            _this.resolution = resolution || 1;
            _this._quality = 0;
            _this.quality = quality || 4;
            _this.strength = strength || 8;
            _this.firstRun = true;
            return _this;
        }
        Object.defineProperty(BlurXFilter.prototype, "blur", {
            get: function () {
                return this.strength;
            },
            set: function (value) {
                this.padding = Math.abs(value) * 2;
                this.strength = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(BlurXFilter.prototype, "quality", {
            get: function () {
                return this._quality;
            },
            set: function (value) {
                this._quality = value;
                this.passes = value;
            },
            enumerable: true,
            configurable: true
        });
        BlurXFilter.prototype.apply = function (filterManager, input, output, clear) {
            if (this.firstRun) {
                var gl = filterManager.renderer.gl;
                var kernelSize = getMaxBlurKernelSize(gl);
                this.vertexSrc = generateVertBlurSource(kernelSize, true);
                this.fragmentSrc = generateFragBlurSource(kernelSize);
                this.firstRun = false;
            }
            this.uniforms.strength = (1 / output.size.width) * (output.size.width / input.size.width);
            this.uniforms.strength *= this.strength;
            this.uniforms.strength /= this.passes;
            if (this.passes === 1) {
                filterManager.applyFilter(this, input, output, clear);
            }
            else {
                var renderTarget = filterManager.getRenderTarget(true);
                var flip = input;
                var flop = renderTarget;
                for (var i = 0; i < this.passes - 1; i++) {
                    filterManager.applyFilter(this, flip, flop, true);
                    var temp = flop;
                    flop = flip;
                    flip = temp;
                }
                filterManager.applyFilter(this, flip, output, clear);
                filterManager.returnRenderTarget(renderTarget);
            }
        };
        return BlurXFilter;
    }(Filter));

    var BlurYFilter = (function (_super) {
        tslib_1.__extends(BlurYFilter, _super);
        function BlurYFilter(strength, quality, resolution, kernelSize) {
            var _this = this;
            kernelSize = kernelSize || 5;
            var vertSrc = generateVertBlurSource(kernelSize, false);
            var fragSrc = generateFragBlurSource(kernelSize);
            _this = _super.call(this, vertSrc, fragSrc) || this;
            _this.resolution = resolution || 1;
            _this._quality = 0;
            _this.quality = quality || 4;
            _this.strength = strength || 8;
            _this.firstRun = true;
            return _this;
        }
        Object.defineProperty(BlurYFilter.prototype, "blur", {
            get: function () {
                return this.strength;
            },
            set: function (value) {
                this.padding = Math.abs(value) * 2;
                this.strength = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(BlurYFilter.prototype, "quality", {
            get: function () {
                return this._quality;
            },
            set: function (value) {
                this._quality = value;
                this.passes = value;
            },
            enumerable: true,
            configurable: true
        });
        BlurYFilter.prototype.apply = function (filterManager, input, output, clear) {
            if (this.firstRun) {
                var gl = filterManager.renderer.gl;
                var kernelSize = getMaxBlurKernelSize(gl);
                this.vertexSrc = generateVertBlurSource(kernelSize, false);
                this.fragmentSrc = generateFragBlurSource(kernelSize);
                this.firstRun = false;
            }
            this.uniforms.strength = (1 / output.size.height) * (output.size.height / input.size.height);
            this.uniforms.strength *= this.strength;
            this.uniforms.strength /= this.passes;
            if (this.passes === 1) {
                filterManager.applyFilter(this, input, output, clear);
            }
            else {
                var renderTarget = filterManager.getRenderTarget(true);
                var flip = input;
                var flop = renderTarget;
                for (var i = 0; i < this.passes - 1; i++) {
                    filterManager.applyFilter(this, flip, flop, true);
                    var temp = flop;
                    flop = flip;
                    flip = temp;
                }
                filterManager.applyFilter(this, flip, output, clear);
                filterManager.returnRenderTarget(renderTarget);
            }
        };
        return BlurYFilter;
    }(Filter));

    var BlurFilter = (function (_super) {
        tslib_1.__extends(BlurFilter, _super);
        function BlurFilter(strength, quality, resolution, kernelSize) {
            var _this = _super.call(this) || this;
            _this.blurXFilter = new BlurXFilter(strength, quality, resolution, kernelSize);
            _this.blurYFilter = new BlurYFilter(strength, quality, resolution, kernelSize);
            _this.padding = 0;
            _this.resolution = resolution || 1;
            _this.quality = quality || 4;
            _this.blur = strength || 8;
            return _this;
        }
        BlurFilter.prototype.apply = function (filterManager, input, output) {
            var renderTarget = filterManager.getRenderTarget(true);
            this.blurXFilter.apply(filterManager, input, renderTarget, true);
            this.blurYFilter.apply(filterManager, renderTarget, output, false);
            filterManager.returnRenderTarget(renderTarget);
        };
        Object.defineProperty(BlurFilter.prototype, "blur", {
            get: function () {
                return this.blurXFilter.blur;
            },
            set: function (value) {
                this.blurXFilter.blur = this.blurYFilter.blur = value;
                this.padding = Math.max(Math.abs(this.blurXFilter.strength), Math.abs(this.blurYFilter.strength)) * 2;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(BlurFilter.prototype, "quality", {
            get: function () {
                return this.blurXFilter.quality;
            },
            set: function (value) {
                this.blurXFilter.quality = this.blurYFilter.quality = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(BlurFilter.prototype, "blurX", {
            get: function () {
                return this.blurXFilter.blur;
            },
            set: function (value) {
                this.blurXFilter.blur = value;
                this.padding = Math.max(Math.abs(this.blurXFilter.strength), Math.abs(this.blurYFilter.strength)) * 2;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(BlurFilter.prototype, "blurY", {
            get: function () {
                return this.blurYFilter.blur;
            },
            set: function (value) {
                this.blurYFilter.blur = value;
                this.padding = Math.max(Math.abs(this.blurXFilter.strength), Math.abs(this.blurYFilter.strength)) * 2;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(BlurFilter.prototype, "blendMode", {
            get: function () {
                return this.blurYFilter.blendMode;
            },
            set: function (value) {
                this.blurYFilter.blendMode = value;
            },
            enumerable: true,
            configurable: true
        });
        return BlurFilter;
    }(Filter));

    var colorMatrixFrag = 'precision mediump float;' +
        'varying vec2 vTextureCoord;' +
        'uniform sampler2D uSampler;' +
        'uniform float m[20];' +
        'uniform float uAlpha;' +
        'void main(void){' +
        'vec4 c = texture2D(uSampler, vTextureCoord);' +
        'if (uAlpha == 0.0) {' +
        'gl_FragColor = c;' +
        'return;' +
        '}' +
        'if (c.a > 0.0) {' +
        'c.rgb /= c.a;' +
        '}' +
        'vec4 result;' +
        'result.r = (m[0] * c.r);' +
        'result.r += (m[1] * c.g);' +
        'result.r += (m[2] * c.b);' +
        'result.r += (m[3] * c.a);' +
        'result.r += m[4];' +
        'result.g = (m[5] * c.r);' +
        'result.g += (m[6] * c.g);' +
        'result.g += (m[7] * c.b);' +
        'result.g += (m[8] * c.a);' +
        'result.g += m[9];' +
        'result.b = (m[10] * c.r);' +
        'result.b += (m[11] * c.g);' +
        'result.b += (m[12] * c.b);' +
        'result.b += (m[13] * c.a);' +
        'result.b += m[14];' +
        'result.a = (m[15] * c.r);' +
        'result.a += (m[16] * c.g);' +
        'result.a += (m[17] * c.b);' +
        'result.a += (m[18] * c.a);' +
        'result.a += m[19];' +
        'vec3 rgb = mix(c.rgb, result.rgb, uAlpha);' +
        'rgb *= result.a;' +
        'gl_FragColor = vec4(rgb, result.a);' +
        '}';
    var ColorMatrixFilter = (function (_super) {
        tslib_1.__extends(ColorMatrixFilter, _super);
        function ColorMatrixFilter(colorMatrix) {
            var _this = _super.call(this, defaultVert, colorMatrixFrag) || this;
            _this.uniforms.m = colorMatrix || [
                1, 0, 0, 0, 0,
                0, 1, 0, 0, 0,
                0, 0, 1, 0, 0,
                0, 0, 0, 1, 0
            ];
            _this.alpha = 1;
            return _this;
        }
        ColorMatrixFilter.prototype._loadMatrix = function (matrix, multiply) {
            if (multiply === void 0) { multiply = false; }
            var newMatrix = matrix;
            if (multiply) {
                this._multiply(newMatrix, this.uniforms.m, matrix);
                newMatrix = this._colorMatrix(newMatrix);
            }
            this.uniforms.m = newMatrix;
        };
        ColorMatrixFilter.prototype._multiply = function (out, a, b) {
            out[0] = (a[0] * b[0]) + (a[1] * b[5]) + (a[2] * b[10]) + (a[3] * b[15]);
            out[1] = (a[0] * b[1]) + (a[1] * b[6]) + (a[2] * b[11]) + (a[3] * b[16]);
            out[2] = (a[0] * b[2]) + (a[1] * b[7]) + (a[2] * b[12]) + (a[3] * b[17]);
            out[3] = (a[0] * b[3]) + (a[1] * b[8]) + (a[2] * b[13]) + (a[3] * b[18]);
            out[4] = (a[0] * b[4]) + (a[1] * b[9]) + (a[2] * b[14]) + (a[3] * b[19]) + a[4];
            out[5] = (a[5] * b[0]) + (a[6] * b[5]) + (a[7] * b[10]) + (a[8] * b[15]);
            out[6] = (a[5] * b[1]) + (a[6] * b[6]) + (a[7] * b[11]) + (a[8] * b[16]);
            out[7] = (a[5] * b[2]) + (a[6] * b[7]) + (a[7] * b[12]) + (a[8] * b[17]);
            out[8] = (a[5] * b[3]) + (a[6] * b[8]) + (a[7] * b[13]) + (a[8] * b[18]);
            out[9] = (a[5] * b[4]) + (a[6] * b[9]) + (a[7] * b[14]) + (a[8] * b[19]) + a[9];
            out[10] = (a[10] * b[0]) + (a[11] * b[5]) + (a[12] * b[10]) + (a[13] * b[15]);
            out[11] = (a[10] * b[1]) + (a[11] * b[6]) + (a[12] * b[11]) + (a[13] * b[16]);
            out[12] = (a[10] * b[2]) + (a[11] * b[7]) + (a[12] * b[12]) + (a[13] * b[17]);
            out[13] = (a[10] * b[3]) + (a[11] * b[8]) + (a[12] * b[13]) + (a[13] * b[18]);
            out[14] = (a[10] * b[4]) + (a[11] * b[9]) + (a[12] * b[14]) + (a[13] * b[19]) + a[14];
            out[15] = (a[15] * b[0]) + (a[16] * b[5]) + (a[17] * b[10]) + (a[18] * b[15]);
            out[16] = (a[15] * b[1]) + (a[16] * b[6]) + (a[17] * b[11]) + (a[18] * b[16]);
            out[17] = (a[15] * b[2]) + (a[16] * b[7]) + (a[17] * b[12]) + (a[18] * b[17]);
            out[18] = (a[15] * b[3]) + (a[16] * b[8]) + (a[17] * b[13]) + (a[18] * b[18]);
            out[19] = (a[15] * b[4]) + (a[16] * b[9]) + (a[17] * b[14]) + (a[18] * b[19]) + a[19];
            return out;
        };
        ColorMatrixFilter.prototype._colorMatrix = function (matrix) {
            var m = new Float32Array(matrix);
            m[4] /= 255;
            m[9] /= 255;
            m[14] /= 255;
            m[19] /= 255;
            return m;
        };
        ColorMatrixFilter.prototype.brightness = function (b, multiply) {
            var matrix = [
                b, 0, 0, 0, 0,
                0, b, 0, 0, 0,
                0, 0, b, 0, 0,
                0, 0, 0, 1, 0,
            ];
            this._loadMatrix(matrix, multiply);
        };
        ColorMatrixFilter.prototype.greyscale = function (scale, multiply) {
            var matrix = [
                scale, scale, scale, 0, 0,
                scale, scale, scale, 0, 0,
                scale, scale, scale, 0, 0,
                0, 0, 0, 1, 0,
            ];
            this._loadMatrix(matrix, multiply);
        };
        ColorMatrixFilter.prototype.blackAndWhite = function (multiply) {
            var matrix = [
                0.3, 0.6, 0.1, 0, 0,
                0.3, 0.6, 0.1, 0, 0,
                0.3, 0.6, 0.1, 0, 0,
                0, 0, 0, 1, 0,
            ];
            this._loadMatrix(matrix, multiply);
        };
        ColorMatrixFilter.prototype.hue = function (rotation, multiply) {
            rotation = (rotation || 0) / 180 * Math.PI;
            var cosR = Math.cos(rotation);
            var sinR = Math.sin(rotation);
            var sqrt = Math.sqrt;
            var w = 1 / 3;
            var sqrW = sqrt(w);
            var a00 = cosR + ((1.0 - cosR) * w);
            var a01 = (w * (1.0 - cosR)) - (sqrW * sinR);
            var a02 = (w * (1.0 - cosR)) + (sqrW * sinR);
            var a10 = (w * (1.0 - cosR)) + (sqrW * sinR);
            var a11 = cosR + (w * (1.0 - cosR));
            var a12 = (w * (1.0 - cosR)) - (sqrW * sinR);
            var a20 = (w * (1.0 - cosR)) - (sqrW * sinR);
            var a21 = (w * (1.0 - cosR)) + (sqrW * sinR);
            var a22 = cosR + (w * (1.0 - cosR));
            var matrix = [
                a00, a01, a02, 0, 0,
                a10, a11, a12, 0, 0,
                a20, a21, a22, 0, 0,
                0, 0, 0, 1, 0,
            ];
            this._loadMatrix(matrix, multiply);
        };
        ColorMatrixFilter.prototype.contrast = function (amount, multiply) {
            var v = (amount || 0) + 1;
            var o = -0.5 * (v - 1);
            var matrix = [
                v, 0, 0, 0, o,
                0, v, 0, 0, o,
                0, 0, v, 0, o,
                0, 0, 0, 1, 0,
            ];
            this._loadMatrix(matrix, multiply);
        };
        ColorMatrixFilter.prototype.saturate = function (amount, multiply) {
            if (amount === void 0) { amount = 0; }
            var x = (amount * 2 / 3) + 1;
            var y = ((x - 1) * -0.5);
            var matrix = [
                x, y, y, 0, 0,
                y, x, y, 0, 0,
                y, y, x, 0, 0,
                0, 0, 0, 1, 0,
            ];
            this._loadMatrix(matrix, multiply);
        };
        ColorMatrixFilter.prototype.desaturate = function () {
            this.saturate(-1);
        };
        ColorMatrixFilter.prototype.negative = function (multiply) {
            var matrix = [
                -1, 0, 0, 1, 0,
                0, -1, 0, 1, 0,
                0, 0, -1, 1, 0,
                0, 0, 0, 1, 0,
            ];
            this._loadMatrix(matrix, multiply);
        };
        ColorMatrixFilter.prototype.sepia = function (multiply) {
            var matrix = [
                0.393, 0.7689999, 0.18899999, 0, 0,
                0.349, 0.6859999, 0.16799999, 0, 0,
                0.272, 0.5339999, 0.13099999, 0, 0,
                0, 0, 0, 1, 0,
            ];
            this._loadMatrix(matrix, multiply);
        };
        ColorMatrixFilter.prototype.technicolor = function (multiply) {
            var matrix = [
                1.9125277891456083, -0.8545344976951645, -0.09155508482755585, 0, 11.793603434377337,
                -0.3087833385928097, 1.7658908555458428, -0.10601743074722245, 0, -70.35205161461398,
                -0.231103377548616, -0.7501899197440212, 1.847597816108189, 0, 30.950940869491138,
                0, 0, 0, 1, 0,
            ];
            this._loadMatrix(matrix, multiply);
        };
        ColorMatrixFilter.prototype.polaroid = function (multiply) {
            var matrix = [
                1.438, -0.062, -0.062, 0, 0,
                -0.122, 1.378, -0.122, 0, 0,
                -0.016, -0.016, 1.483, 0, 0,
                0, 0, 0, 1, 0,
            ];
            this._loadMatrix(matrix, multiply);
        };
        ColorMatrixFilter.prototype.toBGR = function (multiply) {
            var matrix = [
                0, 0, 1, 0, 0,
                0, 1, 0, 0, 0,
                1, 0, 0, 0, 0,
                0, 0, 0, 1, 0,
            ];
            this._loadMatrix(matrix, multiply);
        };
        ColorMatrixFilter.prototype.kodachrome = function (multiply) {
            var matrix = [
                1.1285582396593525, -0.3967382283601348, -0.03992559172921793, 0, 63.72958762196502,
                -0.16404339962244616, 1.0835251566291304, -0.05498805115633132, 0, 24.732407896706203,
                -0.16786010706155763, -0.5603416277695248, 1.6014850761964943, 0, 35.62982807460946,
                0, 0, 0, 1, 0,
            ];
            this._loadMatrix(matrix, multiply);
        };
        ColorMatrixFilter.prototype.browni = function (multiply) {
            var matrix = [
                0.5997023498159715, 0.34553243048391263, -0.2708298674538042, 0, 47.43192855600873,
                -0.037703249837783157, 0.8609577587992641, 0.15059552388459913, 0, -36.96841498319127,
                0.24113635128153335, -0.07441037908422492, 0.44972182064877153, 0, -7.562075277591283,
                0, 0, 0, 1, 0,
            ];
            this._loadMatrix(matrix, multiply);
        };
        ColorMatrixFilter.prototype.vintage = function (multiply) {
            var matrix = [
                0.6279345635605994, 0.3202183420819367, -0.03965408211312453, 0, 9.651285835294123,
                0.02578397704808868, 0.6441188644374771, 0.03259127616149294, 0, 7.462829176470591,
                0.0466055556782719, -0.0851232987247891, 0.5241648018700465, 0, 5.159190588235296,
                0, 0, 0, 1, 0,
            ];
            this._loadMatrix(matrix, multiply);
        };
        ColorMatrixFilter.prototype.colorTone = function (desaturation, toned, lightColor, darkColor, multiply) {
            desaturation = desaturation || 0.2;
            toned = toned || 0.15;
            lightColor = lightColor || 0xFFE580;
            darkColor = darkColor || 0x338000;
            var lR = ((lightColor >> 16) & 0xFF) / 255;
            var lG = ((lightColor >> 8) & 0xFF) / 255;
            var lB = (lightColor & 0xFF) / 255;
            var dR = ((darkColor >> 16) & 0xFF) / 255;
            var dG = ((darkColor >> 8) & 0xFF) / 255;
            var dB = (darkColor & 0xFF) / 255;
            var matrix = [
                0.3, 0.59, 0.11, 0, 0,
                lR, lG, lB, desaturation, 0,
                dR, dG, dB, toned, 0,
                lR - dR, lG - dG, lB - dB, 0, 0,
            ];
            this._loadMatrix(matrix, multiply);
        };
        ColorMatrixFilter.prototype.night = function (intensity, multiply) {
            intensity = intensity || 0.1;
            var matrix = [
                intensity * (-2.0), -intensity, 0, 0, 0,
                -intensity, 0, intensity, 0, 0,
                0, intensity, intensity * 2.0, 0, 0,
                0, 0, 0, 1, 0,
            ];
            this._loadMatrix(matrix, multiply);
        };
        ColorMatrixFilter.prototype.predator = function (amount, multiply) {
            var matrix = [
                11.224130630493164 * amount,
                -4.794486999511719 * amount,
                -2.8746118545532227 * amount,
                0 * amount,
                0.40342438220977783 * amount,
                -3.6330697536468506 * amount,
                9.193157196044922 * amount,
                -2.951810836791992 * amount,
                0 * amount,
                -1.316135048866272 * amount,
                -3.2184197902679443 * amount,
                -4.2375030517578125 * amount,
                7.476448059082031 * amount,
                0 * amount,
                0.8044459223747253 * amount,
                0, 0, 0, 1, 0,
            ];
            this._loadMatrix(matrix, multiply);
        };
        ColorMatrixFilter.prototype.lsd = function (multiply) {
            var matrix = [
                2, -0.4, 0.5, 0, 0,
                -0.5, 2, -0.4, 0, 0,
                -0.4, -0.5, 3, 0, 0,
                0, 0, 0, 1, 0,
            ];
            this._loadMatrix(matrix, multiply);
        };
        ColorMatrixFilter.prototype.reset = function () {
            var matrix = [
                1, 0, 0, 0, 0,
                0, 1, 0, 0, 0,
                0, 0, 1, 0, 0,
                0, 0, 0, 1, 0,
            ];
            this._loadMatrix(matrix, false);
        };
        Object.defineProperty(ColorMatrixFilter.prototype, "matrix", {
            get: function () {
                return this.uniforms.m;
            },
            set: function (value) {
                this.uniforms.m = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ColorMatrixFilter.prototype, "alpha", {
            get: function () {
                return this.uniforms.uAlpha;
            },
            set: function (value) {
                this.uniforms.uAlpha = value;
            },
            enumerable: true,
            configurable: true
        });
        return ColorMatrixFilter;
    }(Filter));
    ColorMatrixFilter.prototype.grayscale = ColorMatrixFilter.prototype.greyscale;

    var alphaFrag = 'precision mediump float;' +
        'varying vec2 vTextureCoord;' +
        'uniform sampler2D uSampler;' +
        'uniform float uAlpha;' +
        'void main(void){' +
        'gl_FragColor = texture2D(uSampler, vTextureCoord) * uAlpha;' +
        '}';
    var AlphaFilter = (function (_super) {
        tslib_1.__extends(AlphaFilter, _super);
        function AlphaFilter(alpha) {
            if (alpha === void 0) { alpha = 1.0; }
            var _this = _super.call(this, defaultVert, alphaFrag) || this;
            _this.alpha = alpha;
            _this.glShaderKey = 'alpha';
            return _this;
        }
        Object.defineProperty(AlphaFilter.prototype, "alpha", {
            get: function () {
                return this.uniforms.uAlpha;
            },
            set: function (value) {
                this.uniforms.uAlpha = value;
            },
            enumerable: true,
            configurable: true
        });
        return AlphaFilter;
    }(Filter));

    var tempMat = new Matrix();
    var TextureMatrix = (function () {
        function TextureMatrix(texture, clampMargin) {
            if (clampMargin === void 0) { clampMargin = 0.5; }
            this._texture = texture;
            this.mapCoord = new Matrix();
            this.uClampFrame = new Float32Array(4);
            this.uClampOffset = new Float32Array(2);
            this._lastTextureID = -1;
            this.clampOffset = 0;
            this.clampMargin = clampMargin;
        }
        Object.defineProperty(TextureMatrix.prototype, "texture", {
            get: function () {
                return this._texture;
            },
            set: function (value) {
                this._texture = value;
                this._lastTextureID = -1;
            },
            enumerable: true,
            configurable: true
        });
        TextureMatrix.prototype.multiplyUvs = function (uvs, out) {
            if (out === undefined) {
                out = uvs;
            }
            var mat = this.mapCoord;
            for (var i = 0; i < uvs.length; i += 2) {
                var x = uvs[i];
                var y = uvs[i + 1];
                out[i] = (x * mat.a) + (y * mat.c) + mat.tx;
                out[i + 1] = (x * mat.b) + (y * mat.d) + mat.ty;
            }
            return out;
        };
        TextureMatrix.prototype.update = function (forceUpdate) {
            var tex = this._texture;
            if (!tex || !tex.valid) {
                return false;
            }
            if (!forceUpdate
                && this._lastTextureID === tex._updateID) {
                return false;
            }
            this._lastTextureID = tex._updateID;
            var uvs = tex._uvs;
            this.mapCoord.set(uvs.x1 - uvs.x0, uvs.y1 - uvs.y0, uvs.x3 - uvs.x0, uvs.y3 - uvs.y0, uvs.x0, uvs.y0);
            var orig = tex.orig;
            var trim = tex.trim;
            if (trim) {
                tempMat.set(orig.width / trim.width, 0, 0, orig.height / trim.height, -trim.x / trim.width, -trim.y / trim.height);
                this.mapCoord.append(tempMat);
            }
            var texBase = tex.baseTexture;
            var frame = this.uClampFrame;
            var margin = this.clampMargin;
            var offset = this.clampOffset;
            frame[0] = (tex._frame.x + margin + offset) / texBase.width;
            frame[1] = (tex._frame.y + margin + offset) / texBase.height;
            frame[2] = (tex._frame.x + tex._frame.width - margin + offset) / texBase.width;
            frame[3] = (tex._frame.y + tex._frame.height - margin + offset) / texBase.height;
            this.uClampOffset[0] = offset / texBase.width;
            this.uClampOffset[1] = offset / texBase.height;
            return true;
        };
        return TextureMatrix;
    }());

    var spriteMaskFilterFrag = "precision mediump float;" +
        "varying vec2 vMaskCoord;" +
        "varying vec2 vTextureCoord;" +
        "uniform sampler2D uSampler;" +
        "uniform sampler2D mask;" +
        "uniform float alpha;" +
        "uniform vec4 maskClamp;" +
        "void main(void){" +
        "float clip = step(3.5," +
        "step(maskClamp.x, vMaskCoord.x) +" +
        "step(maskClamp.y, vMaskCoord.y) +" +
        "step(vMaskCoord.x, maskClamp.z) +" +
        "step(vMaskCoord.y, maskClamp.w));" +
        "vec4 original = texture2D(uSampler, vTextureCoord);" +
        "vec4 masky = texture2D(mask, vMaskCoord);" +
        "original *= (masky.a * alpha * clip);" +
        "gl_FragColor = original;" +
        "}";
    var spriteMaskFilterVert = "attribute vec2 aVertexPosition;" +
        "attribute vec2 aTextureCoord;" +
        "uniform mat3 projectionMatrix;" +
        "uniform mat3 otherMatrix;" +
        "varying vec2 vMaskCoord;" +
        "varying vec2 vTextureCoord;" +
        "void main(void){" +
        "gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);" +
        "vTextureCoord = aTextureCoord;" +
        "vMaskCoord = ( otherMatrix * vec3( aTextureCoord, 1.0)  ).xy;" +
        "}";
    var SpriteMaskFilter = (function (_super) {
        tslib_1.__extends(SpriteMaskFilter, _super);
        function SpriteMaskFilter(sprite) {
            var _this = this;
            var maskMatrix = new Matrix();
            _this = _super.call(this, spriteMaskFilterVert, spriteMaskFilterFrag) || this;
            sprite.renderable = false;
            _this.maskSprite = sprite;
            _this.maskMatrix = maskMatrix;
            return _this;
        }
        SpriteMaskFilter.prototype.apply = function (filterManager, input, output) {
            var maskSprite = this.maskSprite;
            var tex = this.maskSprite.texture;
            if (!tex || !tex.valid)
                return;
            if (!tex.transform) {
                tex.transform = new TextureMatrix(tex, 0.0);
            }
            tex.transform.update();
            this.uniforms.mask = tex;
            this.uniforms.otherMatrix = filterManager.calculateSpriteMatrix(this.maskMatrix, maskSprite)
                .prepend(tex.transform.mapCoord);
            this.uniforms.alpha = maskSprite._worldAlpha;
            this.uniforms.maskClamp = tex.transform.uClampFrame;
            filterManager.applyFilter(this, input, output);
        };
        return SpriteMaskFilter;
    }(Filter));

    var blurFrag = [
        "precision mediump float;",
        "varying vec2 vTextureCoord;",
        "uniform sampler2D uSampler;",
        "const float resolution=1024.0;",
        "uniform float radius;",
        "uniform vec2 dir;",
        "void main() {",
        "vec4 sum = vec4(0.0);",
        "vec2 tc = vTextureCoord;",
        "float blur = radius/resolution;",
        "float hstep = dir.x;",
        "float vstep = dir.y;",
        "sum += texture2D(uSampler, vec2(tc.x - 4.0*blur*hstep, tc.y - 4.0*blur*vstep)) * 0.0162162162;",
        "sum += texture2D(uSampler, vec2(tc.x - 3.0*blur*hstep, tc.y - 3.0*blur*vstep)) * 0.0540540541;",
        "sum += texture2D(uSampler, vec2(tc.x - 2.0*blur*hstep, tc.y - 2.0*blur*vstep)) * 0.1216216216;",
        "sum += texture2D(uSampler, vec2(tc.x - 1.0*blur*hstep, tc.y - 1.0*blur*vstep)) * 0.1945945946;",
        "sum += texture2D(uSampler, vec2(tc.x, tc.y)) * 0.2270270270;",
        "sum += texture2D(uSampler, vec2(tc.x + 1.0*blur*hstep, tc.y + 1.0*blur*vstep)) * 0.1945945946;",
        "sum += texture2D(uSampler, vec2(tc.x + 2.0*blur*hstep, tc.y + 2.0*blur*vstep)) * 0.1216216216;",
        "sum += texture2D(uSampler, vec2(tc.x + 3.0*blur*hstep, tc.y + 3.0*blur*vstep)) * 0.0540540541;",
        "sum += texture2D(uSampler, vec2(tc.x + 4.0*blur*hstep, tc.y + 4.0*blur*vstep)) * 0.0162162162;",
        "vec4 cc= texture2D(uSampler,vTextureCoord );",
        "gl_FragColor =vec4(sum.rgb, cc.a);",
        "}"
    ].join("\n");
    var BlurFilterNew = (function (_super) {
        tslib_1.__extends(BlurFilterNew, _super);
        function BlurFilterNew(blur) {
            if (blur === void 0) { blur = 0.5; }
            var _this = _super.call(this, defaultVert, blurFrag) || this;
            _this.blur = blur;
            _this.uniforms.dir = [1.0, 1.0];
            return _this;
        }
        Object.defineProperty(BlurFilterNew.prototype, "blur", {
            get: function () {
                return this._blur;
            },
            set: function (value) {
                if (this._blur === value)
                    return;
                if (value > 1)
                    value = 1;
                if (value < 0)
                    value = 0;
                this._blur = value;
                this.uniforms.radius = value * 10;
            },
            enumerable: true,
            configurable: true
        });
        return BlurFilterNew;
    }(Filter));

    var MaskManager = (function () {
        function MaskManager(renderer) {
            this.renderer = renderer;
            this.scissor = false;
            this.scissorData = null;
            this.scissorRenderTarget = null;
            this.enableScissor = true;
            this.alphaMaskPool = [];
            this.alphaMaskIndex = 0;
        }
        MaskManager.prototype.pushMask = function (target, maskData) {
            if (maskData.texture) {
                this.pushSpriteMask(target, maskData);
            }
            else
                this.pushStencilMask(maskData);
        };
        MaskManager.prototype.popMask = function (target, maskData) {
            if (maskData.texture) {
                this.popSpriteMask();
            }
            else
                this.popStencilMask();
        };
        MaskManager.prototype.pushSpriteMask = function (target, maskData) {
            var alphaMaskFilter = this.alphaMaskPool[this.alphaMaskIndex];
            if (!alphaMaskFilter) {
                alphaMaskFilter = this.alphaMaskPool[this.alphaMaskIndex] = [new SpriteMaskFilter(maskData)];
            }
            alphaMaskFilter[0].resolution = 1;
            alphaMaskFilter[0].maskSprite = maskData;
            this.renderer.filterManager.pushFilter(target, alphaMaskFilter);
            this.alphaMaskIndex++;
        };
        MaskManager.prototype.popSpriteMask = function () {
            this.renderer.filterManager.popFilter();
            this.alphaMaskIndex--;
        };
        MaskManager.prototype.pushStencilMask = function (maskData) {
            this.renderer.batchManager.flush();
            this.renderer.stencilManager.pushStencil(maskData);
        };
        MaskManager.prototype.popStencilMask = function () {
            this.renderer.stencilManager.popStencil();
        };
        MaskManager.prototype.pushScissorMask = function (target, maskData) {
            maskData.renderable = true;
            var renderTarget = this.renderer._activeRenderTarget;
            var bounds = maskData.getBounds();
            bounds.fit(renderTarget.size);
            maskData.renderable = false;
            this.renderer.gl.enable(this.renderer.gl.SCISSOR_TEST);
            this.renderer.gl.scissor(bounds.x, (renderTarget.root ? renderTarget.size.height - bounds.y - bounds.height : bounds.y), bounds.width, bounds.height);
            this.scissorRenderTarget = renderTarget;
            this.scissorData = maskData;
            this.scissor = true;
        };
        MaskManager.prototype.popScissorMask = function () {
            this.scissorRenderTarget = null;
            this.scissorData = null;
            this.scissor = false;
            var gl = this.renderer.gl;
            gl.disable(gl.SCISSOR_TEST);
        };
        MaskManager.prototype.destroy = function () {
            this.renderer = null;
        };
        return MaskManager;
    }());

    var StencilManager = (function () {
        function StencilManager(renderer) {
            this.renderer = renderer;
            this.stencilMaskStack = null;
        }
        StencilManager.prototype.setMaskStack = function (stencilMaskStack) {
            this.stencilMaskStack = stencilMaskStack;
            var gl = this.renderer.gl;
            if (stencilMaskStack.length === 0) {
                gl.disable(gl.STENCIL_TEST);
            }
            else {
                gl.enable(gl.STENCIL_TEST);
            }
        };
        StencilManager.prototype.pushStencil = function (graphics) {
            this.renderer._activeRenderTarget.attachStencilBuffer();
            var gl = this.renderer.gl;
            var prevMaskCount = this.stencilMaskStack.length;
            if (prevMaskCount === 0) {
                gl.enable(gl.STENCIL_TEST);
            }
            this.stencilMaskStack.push(graphics);
            gl.colorMask(false, false, false, false);
            gl.stencilFunc(gl.EQUAL, prevMaskCount, this._getBitwiseMask());
            gl.stencilOp(gl.KEEP, gl.KEEP, gl.INCR);
            graphics.renderable = true;
            var tempAlpha = graphics._worldAlpha;
            graphics._worldAlpha = 1;
            graphics.renderWebGL(this.renderer);
            this.renderer.batchManager.flush();
            graphics.renderable = false;
            graphics._worldAlpha = tempAlpha;
            this._useCurrent();
        };
        StencilManager.prototype.popStencil = function () {
            var gl = this.renderer.gl;
            var graphics = this.stencilMaskStack.pop();
            if (this.stencilMaskStack.length === 0) {
                gl.disable(gl.STENCIL_TEST);
                gl.clear(gl.STENCIL_BUFFER_BIT);
                gl.clearStencil(0);
            }
            else {
                gl.colorMask(false, false, false, false);
                gl.stencilOp(gl.KEEP, gl.KEEP, gl.DECR);
                graphics.renderable = true;
                var tempAlpha = graphics._worldAlpha;
                graphics._worldAlpha = 1;
                graphics.renderWebGL(this.renderer);
                this.renderer.batchManager.flush();
                graphics.renderable = false;
                graphics._worldAlpha = tempAlpha;
                this._useCurrent();
            }
        };
        StencilManager.prototype._useCurrent = function () {
            var gl = this.renderer.gl;
            gl.colorMask(true, true, true, true);
            gl.stencilFunc(gl.EQUAL, this.stencilMaskStack.length, this._getBitwiseMask());
            gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP);
        };
        StencilManager.prototype._getBitwiseMask = function () {
            return (1 << this.stencilMaskStack.length) - 1;
        };
        StencilManager.prototype.destroy = function () {
            this.renderer = null;
            this.stencilMaskStack = null;
        };
        return StencilManager;
    }());

    function createIndicesForQuads(size) {
        var totalIndices = size * 6;
        var indices = new Uint16Array(totalIndices);
        for (var i = 0, j = 0; i < totalIndices; i += 6, j += 4) {
            indices[i + 0] = j + 0;
            indices[i + 1] = j + 1;
            indices[i + 2] = j + 2;
            indices[i + 3] = j + 0;
            indices[i + 4] = j + 2;
            indices[i + 5] = j + 3;
        }
        return indices;
    }

    var Quad = (function () {
        function Quad(gl, state) {
            this.gl = gl;
            this.vertices = new Float32Array([
                -1, -1,
                1, -1,
                1, 1,
                -1, 1,
            ]);
            this.uvs = new Float32Array([
                0, 0,
                1, 0,
                1, 1,
                0, 1,
            ]);
            this.interleaved = new Float32Array(8 * 2);
            for (var i = 0; i < 4; i++) {
                this.interleaved[i * 4] = this.vertices[(i * 2)];
                this.interleaved[(i * 4) + 1] = this.vertices[(i * 2) + 1];
                this.interleaved[(i * 4) + 2] = this.uvs[i * 2];
                this.interleaved[(i * 4) + 3] = this.uvs[(i * 2) + 1];
            }
            this.indices = createIndicesForQuads(1);
            this.vertexBuffer = GLBuffer.createVertexBuffer(gl, this.interleaved, gl.STATIC_DRAW);
            this.indexBuffer = GLBuffer.createIndexBuffer(gl, this.indices, gl.STATIC_DRAW);
            this.vao = new VertexArrayObject(gl, state);
        }
        Quad.prototype.initVao = function (shader) {
            this.vao.clear()
                .addIndex(this.indexBuffer)
                .addAttribute(this.vertexBuffer, shader.attributes.aVertexPosition, this.gl.FLOAT, false, 4 * 4, 0)
                .addAttribute(this.vertexBuffer, shader.attributes.aTextureCoord, this.gl.FLOAT, false, 4 * 4, 2 * 4);
        };
        Quad.prototype.map = function (targetTextureFrame, destinationFrame) {
            var x = 0;
            var y = 0;
            this.uvs[0] = x;
            this.uvs[1] = y;
            this.uvs[2] = x + (destinationFrame.width / targetTextureFrame.width);
            this.uvs[3] = y;
            this.uvs[4] = x + (destinationFrame.width / targetTextureFrame.width);
            this.uvs[5] = y + (destinationFrame.height / targetTextureFrame.height);
            this.uvs[6] = x;
            this.uvs[7] = y + (destinationFrame.height / targetTextureFrame.height);
            x = destinationFrame.x;
            y = destinationFrame.y;
            this.vertices[0] = x;
            this.vertices[1] = y;
            this.vertices[2] = x + destinationFrame.width;
            this.vertices[3] = y;
            this.vertices[4] = x + destinationFrame.width;
            this.vertices[5] = y + destinationFrame.height;
            this.vertices[6] = x;
            this.vertices[7] = y + destinationFrame.height;
            return this;
        };
        Quad.prototype.upload = function () {
            for (var i = 0; i < 4; i++) {
                this.interleaved[i * 4] = this.vertices[(i * 2)];
                this.interleaved[(i * 4) + 1] = this.vertices[(i * 2) + 1];
                this.interleaved[(i * 4) + 2] = this.uvs[i * 2];
                this.interleaved[(i * 4) + 3] = this.uvs[(i * 2) + 1];
            }
            this.vertexBuffer.upload(this.interleaved);
            return this;
        };
        Quad.prototype.destroy = function () {
            var gl = this.gl;
            gl.deleteBuffer(this.vertexBuffer);
            gl.deleteBuffer(this.indexBuffer);
            this.gl = null;
            this.vertices = null;
            this.uvs = null;
            this.interleaved = null;
            this.indices = null;
            this.vertexBuffer.destroy();
            this.indexBuffer.destroy();
            this.vao.destroy();
        };
        return Quad;
    }());

    function calculateScreenSpaceMatrix(outputMatrix, filterArea, textureSize) {
        var mappedMatrix = outputMatrix.identity();
        mappedMatrix.translate(filterArea.x / textureSize.width, filterArea.y / textureSize.height);
        mappedMatrix.scale(textureSize.width, textureSize.height);
        return mappedMatrix;
    }
    function calculateNormalizedScreenSpaceMatrix(outputMatrix, filterArea, textureSize) {
        var mappedMatrix = outputMatrix.identity();
        mappedMatrix.translate(filterArea.x / textureSize.width, filterArea.y / textureSize.height);
        var translateScaleX = (textureSize.width / filterArea.width);
        var translateScaleY = (textureSize.height / filterArea.height);
        mappedMatrix.scale(translateScaleX, translateScaleY);
        return mappedMatrix;
    }
    function calculateSpriteMatrix(outputMatrix, filterArea, textureSize, sprite) {
        var orig = sprite._texture.orig;
        var mappedMatrix = outputMatrix.set(textureSize.width, 0, 0, textureSize.height, filterArea.x, filterArea.y);
        var worldTransform = Matrix.TEMP_MATRIX.copy(sprite.worldMatrix);
        worldTransform.invert();
        mappedMatrix.prepend(worldTransform);
        mappedMatrix.scale(1.0 / orig.width, 1.0 / orig.height);
        mappedMatrix.translate(sprite.anchorTexture.x, sprite.anchorTexture.y);
        return mappedMatrix;
    }

    var FilterState = (function () {
        function FilterState() {
            this.renderTarget = null;
            this.target = null;
            this.resolution = 1;
            this.sourceFrame = new Rectangle();
            this.destinationFrame = new Rectangle();
            this.filters = [];
        }
        FilterState.prototype.clear = function () {
            this.filters = null;
            this.target = null;
            this.renderTarget = null;
        };
        return FilterState;
    }());
    var screenKey = 'screen';
    var FilterManager = (function () {
        function FilterManager(renderer) {
            this.renderer = renderer;
            this.gl = this.renderer.gl;
            this.quad = new Quad(this.gl, renderer.state.attribState);
            this.shaderCache = {};
            this.pool = {};
            this.filterData = null;
            this.managedFilters = [];
            this.renderer.addEventListener('onPreRender', this.onPrerender, this);
            this._screenWidth = renderer.width;
            this._screenHeight = renderer.height;
        }
        FilterManager.prototype.pushFilter = function (target, filters) {
            var renderer = this.renderer;
            var filterData = this.filterData;
            if (!filterData) {
                var filterState = new FilterState();
                filterState.sourceFrame = filterState.destinationFrame = this.renderer._activeRenderTarget.size;
                filterState.renderTarget = renderer._activeRenderTarget;
                this.renderer._activeRenderTarget.filterData = filterData = {
                    index: 0,
                    stack: [filterState],
                };
                this.filterData = filterData;
            }
            var currentState = filterData.stack[++filterData.index];
            var renderTargetFrame = filterData.stack[0].destinationFrame;
            if (!currentState) {
                currentState = filterData.stack[filterData.index] = new FilterState();
            }
            var resolution = filters[0].resolution;
            var padding = filters[0].padding | 0;
            var targetBounds = target.getBounds(true);
            var sourceFrame = currentState.sourceFrame;
            var destinationFrame = currentState.destinationFrame;
            sourceFrame.x = ((targetBounds.x * resolution) | 0) / resolution;
            sourceFrame.y = ((targetBounds.y * resolution) | 0) / resolution;
            sourceFrame.width = ((targetBounds.width * resolution) | 0) / resolution;
            sourceFrame.height = ((targetBounds.height * resolution) | 0) / resolution;
            if (filterData.stack[0].renderTarget.transform) ;
            else if (filters[0].autoFit) {
                sourceFrame.fit(renderTargetFrame);
            }
            sourceFrame.pad(padding);
            destinationFrame.width = sourceFrame.width;
            destinationFrame.height = sourceFrame.height;
            var renderTarget = this.getPotRenderTarget(renderer.gl, sourceFrame.width, sourceFrame.height, resolution);
            currentState.target = target;
            currentState.filters = filters;
            currentState.resolution = resolution;
            currentState.renderTarget = renderTarget;
            renderTarget.setFrame(destinationFrame, sourceFrame);
            renderer.bindRenderTarget(renderTarget);
            renderTarget.clear();
        };
        FilterManager.prototype.popFilter = function () {
            var filterData = this.filterData;
            var lastState = filterData.stack[filterData.index - 1];
            var currentState = filterData.stack[filterData.index];
            this.quad.map(currentState.renderTarget.size, currentState.sourceFrame).upload();
            var filters = currentState.filters;
            if (filters.length === 1) {
                filters[0].apply(this, currentState.renderTarget, lastState.renderTarget, false, currentState);
                this.freePotRenderTarget(currentState.renderTarget);
            }
            else {
                var flip = currentState.renderTarget;
                var flop = this.getPotRenderTarget(this.renderer.gl, currentState.sourceFrame.width, currentState.sourceFrame.height, currentState.resolution);
                flop.setFrame(currentState.destinationFrame, currentState.sourceFrame);
                flop.clear();
                var i = 0;
                for (i = 0; i < filters.length - 1; ++i) {
                    filters[i].apply(this, flip, flop, true, currentState);
                    var t = flip;
                    flip = flop;
                    flop = t;
                }
                filters[i].apply(this, flip, lastState.renderTarget, false, currentState);
                this.freePotRenderTarget(flip);
                this.freePotRenderTarget(flop);
            }
            currentState.clear();
            filterData.index--;
            if (filterData.index === 0) {
                this.filterData = null;
            }
        };
        FilterManager.prototype.applyFilter = function (filter, input, output, clear) {
            var renderer = this.renderer;
            var gl = renderer.gl;
            var shader = filter.glShaders[renderer.CONTEXT_UID];
            if (!shader) {
                if (filter.glShaderKey) {
                    shader = this.shaderCache[filter.glShaderKey];
                    if (!shader) {
                        shader = new GLShader(this.gl, filter.vertexSrc, filter.fragmentSrc);
                        filter.glShaders[renderer.CONTEXT_UID] = this.shaderCache[filter.glShaderKey] = shader;
                        this.managedFilters.push(filter);
                    }
                }
                else {
                    shader = filter.glShaders[renderer.CONTEXT_UID] = new GLShader(this.gl, filter.vertexSrc, filter.fragmentSrc);
                    this.managedFilters.push(filter);
                }
                renderer.bindVao(null);
                this.quad.initVao(shader);
            }
            renderer.bindVao(this.quad.vao);
            renderer.bindRenderTarget(output);
            if (clear) {
                gl.disable(gl.SCISSOR_TEST);
                renderer.clear();
                gl.enable(gl.SCISSOR_TEST);
            }
            if (output === renderer.maskManager.scissorRenderTarget) {
                renderer.maskManager.pushScissorMask(null, renderer.maskManager.scissorData);
            }
            renderer.bindShader(shader);
            var tex = this.renderer.textureManager.emptyTextures[0];
            this.renderer.textureManager.boundTextures[0] = tex;
            this.syncUniforms(shader, filter);
            renderer.state.setBlendMode(filter.blendMode);
            gl.activeTexture(gl.TEXTURE0);
            gl.bindTexture(gl.TEXTURE_2D, input.texture.texture);
            this.quad.vao.draw(this.renderer.gl.TRIANGLES, 6, 0);
            gl.bindTexture(gl.TEXTURE_2D, tex._glTextures[this.renderer.CONTEXT_UID].texture);
            this.renderer.textureManager.currentLocation = -1;
        };
        FilterManager.prototype.syncUniforms = function (shader, filter) {
            var uniformData = filter.uniformData;
            var uniforms = filter.uniforms;
            var textureCount = 1;
            var currentState;
            if (shader.uniforms.filterArea) {
                currentState = this.filterData.stack[this.filterData.index];
                var filterArea = shader.uniforms.filterArea;
                filterArea[0] = currentState.renderTarget.size.width;
                filterArea[1] = currentState.renderTarget.size.height;
                filterArea[2] = currentState.sourceFrame.x;
                filterArea[3] = currentState.sourceFrame.y;
                shader.uniforms.filterArea = filterArea;
            }
            if (shader.uniforms.filterClamp) {
                currentState = currentState || this.filterData.stack[this.filterData.index];
                var filterClamp = shader.uniforms.filterClamp;
                filterClamp[0] = 0;
                filterClamp[1] = 0;
                filterClamp[2] = (currentState.sourceFrame.width - 1) / currentState.renderTarget.size.width;
                filterClamp[3] = (currentState.sourceFrame.height - 1) / currentState.renderTarget.size.height;
                shader.uniforms.filterClamp = filterClamp;
            }
            for (var i in uniformData) {
                var type = uniformData[i].type;
                if (type === 'sampler2d' && uniforms[i] !== 0) {
                    if (uniforms[i].baseTexture) {
                        shader.uniforms[i] = this.renderer.textureManager.bindTexture(uniforms[i].baseTexture, textureCount);
                    }
                    else {
                        shader.uniforms[i] = textureCount;
                        var gl = this.renderer.gl;
                        this.renderer.textureManager.boundTextures[textureCount] = this.renderer.textureManager.emptyTextures[textureCount];
                        gl.activeTexture(gl.TEXTURE0 + textureCount);
                        uniforms[i].texture.bind();
                    }
                    textureCount++;
                }
                else if (type === 'mat3') {
                    if (uniforms[i].a !== undefined) {
                        shader.uniforms[i] = uniforms[i].toArray(true);
                    }
                    else {
                        shader.uniforms[i] = uniforms[i];
                    }
                }
                else if (type === 'vec2') {
                    if (uniforms[i].x !== undefined) {
                        var val = shader.uniforms[i] || new Float32Array(2);
                        val[0] = uniforms[i].x;
                        val[1] = uniforms[i].y;
                        shader.uniforms[i] = val;
                    }
                    else {
                        shader.uniforms[i] = uniforms[i];
                    }
                }
                else if (type === 'float') {
                    if (shader.uniforms.data[i].value !== uniformData[i]) {
                        shader.uniforms[i] = uniforms[i];
                    }
                }
                else {
                    shader.uniforms[i] = uniforms[i];
                }
            }
        };
        FilterManager.prototype.getRenderTarget = function (clear, resolution) {
            var currentState = this.filterData.stack[this.filterData.index];
            var renderTarget = this.getPotRenderTarget(this.renderer.gl, currentState.sourceFrame.width, currentState.sourceFrame.height, resolution || currentState.resolution);
            renderTarget.setFrame(currentState.destinationFrame, currentState.sourceFrame);
            return renderTarget;
        };
        FilterManager.prototype.returnRenderTarget = function (renderTarget) {
            this.freePotRenderTarget(renderTarget);
        };
        FilterManager.prototype.calculateScreenSpaceMatrix = function (outputMatrix) {
            var currentState = this.filterData.stack[this.filterData.index];
            return calculateScreenSpaceMatrix(outputMatrix, currentState.sourceFrame, currentState.renderTarget.size);
        };
        FilterManager.prototype.calculateNormalizedScreenSpaceMatrix = function (outputMatrix) {
            var currentState = this.filterData.stack[this.filterData.index];
            return calculateNormalizedScreenSpaceMatrix(outputMatrix, currentState.sourceFrame, currentState.renderTarget.size);
        };
        FilterManager.prototype.calculateSpriteMatrix = function (outputMatrix, sprite) {
            var currentState = this.filterData.stack[this.filterData.index];
            return calculateSpriteMatrix(outputMatrix, currentState.sourceFrame, currentState.renderTarget.size, sprite);
        };
        FilterManager.prototype.destroy = function (contextLost) {
            if (contextLost === void 0) { contextLost = false; }
            var renderer = this.renderer;
            var filters = this.managedFilters;
            renderer.removeEventListener('onPrerender', this.onPrerender, this);
            this.renderer = null;
            for (var i = 0; i < filters.length; i++) {
                if (!contextLost) {
                    filters[i].glShaders[renderer.CONTEXT_UID].destroy();
                }
                delete filters[i].glShaders[renderer.CONTEXT_UID];
            }
            this.shaderCache = {};
            if (!contextLost) {
                this.emptyPool();
            }
            else {
                this.pool = {};
            }
        };
        FilterManager.prototype.getPotRenderTarget = function (gl, minWidth, minHeight, resolution) {
            var key = screenKey;
            minWidth *= resolution;
            minHeight *= resolution;
            if (minWidth !== this._screenWidth
                || minHeight !== this._screenHeight) {
                minWidth = nextPow2(minWidth);
                minHeight = nextPow2(minHeight);
                key = ((minWidth & 0xFFFF) << 16) | (minHeight & 0xFFFF);
            }
            if (!this.pool[key]) {
                this.pool[key] = [];
            }
            var renderTarget = this.pool[key].pop();
            if (!renderTarget) {
                var tex = this.renderer.textureManager.boundTextures[0];
                gl.activeTexture(gl.TEXTURE0);
                renderTarget = new RenderTarget(gl, minWidth, minHeight, undefined);
                gl.bindTexture(gl.TEXTURE_2D, tex._glTextures[this.renderer.CONTEXT_UID].texture);
                this.renderer.textureManager.currentLocation = -1;
            }
            renderTarget.resolution = resolution;
            renderTarget.defaultFrame.width = renderTarget.size.width = minWidth / resolution;
            renderTarget.defaultFrame.height = renderTarget.size.height = minHeight / resolution;
            renderTarget.filterPoolKey = key;
            return renderTarget;
        };
        FilterManager.prototype.emptyPool = function () {
            for (var i in this.pool) {
                var textures = this.pool[i];
                if (textures) {
                    for (var j = 0; j < textures.length; j++) {
                        textures[j].destroy(true);
                    }
                }
            }
            this.pool = {};
        };
        FilterManager.prototype.freePotRenderTarget = function (renderTarget) {
            this.pool[renderTarget.filterPoolKey].push(renderTarget);
        };
        FilterManager.prototype.onPrerender = function () {
            if (this._screenWidth !== this.renderer.width
                || this._screenHeight !== this.renderer.height) {
                this._screenWidth = this.renderer.width;
                this._screenHeight = this.renderer.height;
                var textures = this.pool[screenKey];
                if (textures) {
                    for (var j = 0; j < textures.length; j++) {
                        textures[j].destroy(true);
                    }
                }
                this.pool[screenKey] = [];
            }
        };
        return FilterManager;
    }());

    var CONTEXT_UID = 0;
    var WebglRenderer = (function (_super) {
        tslib_1.__extends(WebglRenderer, _super);
        function WebglRenderer(gl, width, height) {
            var _this = _super.call(this) || this;
            _this.plugins = {};
            _this._instanceType = "WebglRenderer";
            _this.type = exports.RENDERER_TYPE.WEBGL;
            _this._backgroundColorRgba[3] = _this.transparent ? 0 : 1;
            _this.gl = gl;
            _this.CONTEXT_UID = CONTEXT_UID++;
            _this.maskManager = new MaskManager(_this);
            _this.stencilManager = new StencilManager(_this);
            _this.batchManager = new BatchManager(_this);
            _this.textureManager = null;
            _this.initPlugins(WebglRenderer.__plugins);
            _this.state = new WebGLState(_this.gl);
            _this.renderingToScreen = true;
            _this._activeShader = null;
            _this._activeVao = null;
            _this._activeRenderTarget = null;
            _this._initContext();
            _this.resize(width, height);
            return _this;
        }
        WebglRenderer.prototype._initContext = function () {
            var gl = this.gl;
            if (gl.isContextLost() && gl.getExtension('WEBGL_lose_context')) {
                gl.getExtension('WEBGL_lose_context').restoreContext();
            }
            this._activeShader = null;
            this._activeVao = null;
            this.textureManager = new TextureManager(this);
            this.filterManager = new FilterManager(this);
            this.textureGC = new TextureGarbageCollector(this);
            this.state.resetToDefault();
            this.rootRenderTarget = new RenderTarget(gl, 1, 1, exports.SCALE_MODES.LINEAR, true);
            this.rootRenderTarget.clearColor = this._backgroundColorRgba;
            this.bindRenderTarget(this.rootRenderTarget);
            this.dispatchEvent('onContextChange');
        };
        WebglRenderer.prototype.render = function (displayObject, renderTexture, transform) {
            this.dispatchEvent('onPreRender');
            this.renderingToScreen = !renderTexture;
            if (!this.gl || this.gl.isContextLost()) {
                return;
            }
            if (!renderTexture) {
                this._lastObjectRendered = displayObject;
            }
            displayObject.update();
            var cacheParent = displayObject.parent;
            displayObject.parent = this._tempDisplayObjectParent;
            displayObject.updateTransform();
            displayObject.parent = cacheParent;
            this.bindRenderTexture(renderTexture, transform);
            this.batchManager.currentRenderer.start();
            this._activeRenderTarget.clear();
            displayObject.renderWebGL(this);
            this.batchManager.currentRenderer.flush();
            this.dispatchEvent('onPostRender');
        };
        WebglRenderer.prototype.clear = function (clearColor) {
            this._activeRenderTarget.clear(clearColor);
        };
        WebglRenderer.prototype.setTransform = function (matrix) {
            this._activeRenderTarget.transform = matrix;
        };
        WebglRenderer.prototype.clearRenderTexture = function (renderTexture, clearColor) {
            var baseTexture = renderTexture.baseTexture;
            var renderTarget = baseTexture._glRenderTargets[this.CONTEXT_UID];
            if (renderTarget) {
                renderTarget.clear(clearColor);
            }
            return this;
        };
        WebglRenderer.prototype.bindShader = function (shader, autoProject) {
            if (autoProject === void 0) { autoProject = true; }
            if (this._activeShader !== shader) {
                this._activeShader = shader;
                shader.bind();
                if (autoProject !== false) {
                    shader.uniforms["projectionMatrix"] = this._activeRenderTarget.projectionMatrix.toArray(true);
                }
            }
            return this;
        };
        WebglRenderer.prototype.createVao = function () {
            return new VertexArrayObject(this.gl, this.state.attribState);
        };
        WebglRenderer.prototype.bindVao = function (vao) {
            if (this._activeVao === vao) {
                return this;
            }
            if (vao) {
                vao.bind();
            }
            else if (this._activeVao) {
                this._activeVao.unbind();
            }
            this._activeVao = vao;
            return this;
        };
        WebglRenderer.prototype.reset = function () {
            this.batchManager.reset();
            this.bindVao(null);
            this._activeShader = null;
            this._activeRenderTarget = this.rootRenderTarget;
            for (var i = 0; i < this.textureManager.boundTextures.length; i++) {
                this.textureManager.boundTextures[i] = this.textureManager.emptyTextures[i];
            }
            this.rootRenderTarget.activate();
            this.state.resetToDefault();
            return this;
        };
        WebglRenderer.prototype.bindRenderTexture = function (renderTexture, transform) {
            var renderTarget;
            if (renderTexture) {
                var baseTexture = renderTexture.baseTexture;
                if (!baseTexture._glRenderTargets[this.CONTEXT_UID]) {
                    this.textureManager.updateTexture(baseTexture, 0);
                }
                this.textureManager.unbindTexture(baseTexture);
                renderTarget = baseTexture._glRenderTargets[this.CONTEXT_UID];
                renderTarget.setFrame(renderTexture.frame);
            }
            else {
                renderTarget = this.rootRenderTarget;
            }
            renderTarget.transform = transform;
            this.bindRenderTarget(renderTarget);
            return this;
        };
        WebglRenderer.prototype.bindRenderTarget = function (renderTarget) {
            if (renderTarget !== this._activeRenderTarget) {
                this._activeRenderTarget = renderTarget;
                renderTarget.activate();
                if (this._activeShader) {
                    this._activeShader.uniforms.projectionMatrix = renderTarget.projectionMatrix.toArray(true);
                }
                this.stencilManager.setMaskStack(renderTarget.stencilMaskStack);
            }
            return this;
        };
        WebglRenderer.prototype.setBlendMode = function (blendMode) {
            this.state.setBlendMode(blendMode);
        };
        WebglRenderer.prototype.resize = function (screenWidth, screenHeight) {
            _super.prototype.resize.call(this, screenWidth, screenHeight);
            this.rootRenderTarget.resize(screenWidth, screenHeight);
            if (this._activeRenderTarget === this.rootRenderTarget) {
                this.rootRenderTarget.activate();
                if (this._activeShader) {
                    this._activeShader.uniforms.projectionMatrix = this.rootRenderTarget.projectionMatrix.toArray(true);
                }
            }
        };
        WebglRenderer.prototype.destroy = function () {
            this.destroyPlugins();
            this.textureManager.destroy();
            _super.prototype.destroy.call(this);
            this.maskManager.destroy();
            this.stencilManager.destroy();
            this.filterManager.destroy();
            this.maskManager = null;
            this.filterManager = null;
            this.textureManager = null;
            this.handleContextLost = null;
            this.handleContextRestored = null;
        };
        WebglRenderer.prototype.handleContextRestored = function () {
            this.textureManager.removeAll();
            this.filterManager.destroy(true);
            this._initContext();
        };
        WebglRenderer.prototype.handleContextLost = function (event) {
            event.preventDefault();
        };
        WebglRenderer.prototype.initPlugins = function (staticMap) {
            for (var o in staticMap) {
                this.plugins[o] = new (staticMap[o])(this);
            }
        };
        WebglRenderer.prototype.destroyPlugins = function () {
            for (var o in this.plugins) {
                this.plugins[o].destroy();
                this.plugins[o] = null;
            }
            this.plugins = null;
        };
        WebglRenderer.registerPlugin = function (pluginName, ctor) {
            WebglRenderer.__plugins = WebglRenderer.__plugins || {};
            WebglRenderer.__plugins[pluginName] = ctor;
        };
        return WebglRenderer;
    }(SystemRenderer));
    WebglRenderer.registerPlugin('batch', BatchRenderer);

    var Stage = (function (_super) {
        tslib_1.__extends(Stage, _super);
        function Stage(canvas, desWidth, desHeight, divWidth, divHeight, renderType) {
            if (desWidth === void 0) { desWidth = 750; }
            if (desHeight === void 0) { desHeight = 1624; }
            if (renderType === void 0) { renderType = exports.RENDERER_TYPE.CANVAS; }
            var _this = _super.call(this) || this;
            _this.renderObj = null;
            _this.viewRect = new Rectangle();
            _this.desWidth = 0;
            _this.desHeight = 0;
            _this.divHeight = 0;
            _this.divWidth = 0;
            _this._bgColor = 0x000000;
            _this._lastDpList = {};
            _this._ml = [];
            _this._mp = [];
            _this._mouseDownPoint = {};
            _this._mouseEventTypes = {
                touchstart: "onMouseDown",
                touchmove: "onMouseMove",
                touchend: "onMouseUp",
                touchStart: "onMouseDown",
                touchMove: "onMouseMove",
                touchEnd: "onMouseUp"
            };
            var s = _this;
            _this._instanceType = "Stage";
            Stage._stageList["canvas"] = s;
            s.stage = _this;
            s.name = "stageInstance_" + s.instanceId;
            s.desWidth = desWidth || 750;
            s.desHeight = desHeight || 1206;
            s.divWidth = divWidth;
            s.divHeight = divHeight;
            if (renderType == exports.RENDERER_TYPE.CANVAS) {
                var context = canvas.getContext("2d");
                s.renderObj = new CanvasRenderer(context, canvas.width, canvas.height);
            }
            else {
                var context = canvas.getContext("webgl");
                s.renderObj = new WebglRenderer(context, canvas.width, canvas.height);
            }
            s.dpi = canvas.width / divWidth;
            s.anchorX = desWidth >> 1;
            s.anchorY = desHeight >> 1;
            s.x = (canvas.width - desWidth) >> 1;
            s.y = (canvas.height - desHeight) >> 1;
            var scale = canvas.width / desWidth;
            s.scaleX = scale;
            s.scaleY = scale;
            s.viewRect = new Rectangle();
            s.viewRect.x = (desWidth - canvas.width / scale) >> 1;
            s.viewRect.y = (desHeight - canvas.height / scale) >> 1;
            s.viewRect.width = desWidth - s.viewRect.x * 2;
            s.viewRect.height = desHeight - s.viewRect.y * 2;
            setTimeout(function () {
                s.dispatchEvent(Event.INIT_STAGE);
            }, 100);
            return _this;
        }
        Stage.getStage = function (stageName) {
            if (stageName === void 0) { stageName = "cusEngine"; }
            return Stage._stageList[stageName];
        };
        Object.defineProperty(Stage.prototype, "bgColor", {
            get: function () {
                return this._bgColor;
            },
            set: function (value) {
                if (this._bgColor === value)
                    return;
                this._bgColor = value;
                this.renderObj.backgroundColor = value;
            },
            enumerable: true,
            configurable: true
        });
        Stage.prototype._initMouseEvent = function (event, cp, sp, identifier) {
            event["_pd"] = false;
            event.clientX = cp.x;
            event.clientY = cp.y;
            event.stageX = sp.x;
            event.stageY = sp.y;
            event.identifier = identifier;
        };
        Stage.prototype.flush = function () {
            this.renderObj.render(this);
        };
        Stage.prototype.onMouseEvent = function (e) {
            var s = this;
            if (EventDispatcher._totalMEC > 0) {
                var points = void 0;
                var item = s._mouseEventTypes[e.type];
                var events = void 0;
                var event = void 0;
                var sp = void 0;
                var lp = void 0;
                var cp = void 0;
                var eLen = void 0;
                var identifier = void 0;
                points = [e.changedTouches[0]];
                for (var o = 0; o < points.length; o++) {
                    if (!points[o])
                        continue;
                    eLen = 0;
                    events = [];
                    identifier = "m" + points[o].identifier;
                    if (s._mp.length > 0) {
                        cp = s._mp.shift();
                    }
                    else {
                        cp = new Point();
                    }
                    cp.x = (points[o].pageX || points[o].x || points[o].b) * s.dpi;
                    cp.y = (points[o].pageY || points[o].y || points[o].c) * s.dpi;
                    sp = s.globalToLocal(cp, DisplayObject._bp);
                    if (EventDispatcher.getMouseEventCount() > 0) {
                        if (!s._ml[eLen]) {
                            event = new MouseEvent(item);
                            s._ml[eLen] = event;
                        }
                        else {
                            event = s._ml[eLen];
                            event.type = item;
                        }
                        events[events.length] = event;
                        s._initMouseEvent(event, cp, sp, identifier);
                        eLen++;
                    }
                    if (item == "onMouseDown") {
                        s._mouseDownPoint[identifier] = cp;
                    }
                    else if (item == "onMouseUp") {
                        if (s._mouseDownPoint[identifier]) {
                            if (Point.distance(s._mouseDownPoint[identifier], cp) < 20) {
                                if (EventDispatcher.getMouseEventCount("onMouseClick") > 0) {
                                    if (!s._ml[eLen]) {
                                        event = new MouseEvent("onMouseClick");
                                        s._ml[eLen] = event;
                                    }
                                    else {
                                        event = s._ml[eLen];
                                        event.type = "onMouseClick";
                                    }
                                    events[events.length] = event;
                                    s._initMouseEvent(event, cp, sp, identifier);
                                    eLen++;
                                }
                            }
                        }
                    }
                    if (eLen > 0) {
                        var d = s.hitTestPoint(cp, true);
                        var displayList = [];
                        if (d) {
                            while (d) {
                                if (d["mouseChildren"] === false) {
                                    displayList.length = 0;
                                }
                                displayList[displayList.length] = d;
                                d = d.parent;
                            }
                        }
                        else {
                            displayList[displayList.length] = s;
                        }
                        var len = displayList.length;
                        for (var i = len - 1; i >= 0; i--) {
                            d = displayList[i];
                            for (var j = 0; j < eLen; j++) {
                                if (!events[j]["_pd"]) {
                                    if (d.hasEventListener(events[j].type) && d.mouseEnable) {
                                        events[j].target = d;
                                        events[j].currentTarget = displayList[0];
                                        lp = d.globalToLocal(cp, DisplayObject._bp);
                                        events[j].localX = lp.x;
                                        events[j].localY = lp.y;
                                        d.dispatchEvent(events[j]);
                                    }
                                }
                            }
                        }
                        displayList.reverse();
                        for (var i = len - 1; i >= 0; i--) {
                            d = displayList[i];
                            for (var j = 0; j < eLen; j++) {
                                if (!events[j]["_pd"]) {
                                    if (d.hasEventListener(events[j].type, false) && d.mouseEnable) {
                                        events[j].target = d;
                                        events[j].currentTarget = displayList[eLen - 1];
                                        lp = d.globalToLocal(cp, DisplayObject._bp);
                                        events[j].localX = lp.x;
                                        events[j].localY = lp.y;
                                        d.dispatchEvent(events[j], null, false);
                                    }
                                }
                            }
                        }
                        if (item != "onMouseDown") {
                            if (EventDispatcher.getMouseEventCount("onMouseOver") > 0 || EventDispatcher.getMouseEventCount("onMouseOut") > 0) {
                                if (s._lastDpList[identifier]) {
                                    var len1 = s._lastDpList[identifier].length;
                                    var len2 = displayList.length;
                                    len = len1 > len2 ? len1 : len2;
                                    var isDiff = false;
                                    var overEvent = void 0;
                                    var outEvent = void 0;
                                    for (var i = 1; i < len; i++) {
                                        if (!isDiff) {
                                            if (s._lastDpList[identifier][i] != displayList[i]) {
                                                isDiff = true;
                                                if (!s._ml[eLen]) {
                                                    overEvent = new MouseEvent("onMouseOver");
                                                    s._ml[eLen] = overEvent;
                                                }
                                                else {
                                                    overEvent = s._ml[eLen];
                                                    overEvent.type = "onMouseOver";
                                                }
                                                s._initMouseEvent(overEvent, cp, sp, identifier);
                                                eLen++;
                                                if (!s._ml[eLen]) {
                                                    outEvent = new MouseEvent("onMouseOut");
                                                    s._ml[eLen] = outEvent;
                                                }
                                                else {
                                                    outEvent = s._ml[eLen];
                                                    outEvent.type = "onMouseOut";
                                                }
                                                s._initMouseEvent(outEvent, cp, sp, identifier);
                                            }
                                        }
                                        if (isDiff) {
                                            if (s._lastDpList[identifier][i]) {
                                                if (!outEvent["_pd"]) {
                                                    d = s._lastDpList[identifier][i];
                                                    if (d.hasEventListener("onMouseOut")) {
                                                        outEvent.currentTarget = d;
                                                        outEvent.target = s._lastDpList[identifier][len1 - 1];
                                                        lp = d.globalToLocal(cp, DisplayObject._bp);
                                                        outEvent.localX = lp.x;
                                                        outEvent.localY = lp.y;
                                                        d.dispatchEvent(outEvent);
                                                    }
                                                }
                                            }
                                            if (displayList[i]) {
                                                if (!overEvent["_pd"]) {
                                                    d = displayList[i];
                                                    if (d.hasEventListener("onMouseOver")) {
                                                        overEvent.currentTarget = d;
                                                        overEvent.target = displayList[len2 - 1];
                                                        lp = d.globalToLocal(cp, DisplayObject._bp);
                                                        overEvent.localX = lp.x;
                                                        overEvent.localY = lp.y;
                                                        d.dispatchEvent(overEvent);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            s._mp[s._mp.length] = cp;
                        }
                        if (item == "onMouseUp") {
                            delete s._mouseDownPoint[identifier];
                            delete s._lastDpList[identifier];
                        }
                        else {
                            s._lastDpList[identifier] = displayList;
                        }
                    }
                }
            }
        };
        Stage.prototype.getBounds = function () {
            return this.viewRect;
        };
        Stage.prototype.destroy = function () {
            var s = this;
            s.renderObj.destroy();
            s.renderObj = null;
            s.viewRect = null;
            s._lastDpList = null;
            s._ml = null;
            _super.prototype.destroy.call(this);
        };
        Stage._stageList = {};
        return Stage;
    }(Container));

    var GDispatcher = new EventDispatcher();

    var GraphicsData = (function (_super) {
        tslib_1.__extends(GraphicsData, _super);
        function GraphicsData(shape, fillStyle, lineStyle, matrix) {
            if (fillStyle === void 0) { fillStyle = null; }
            if (lineStyle === void 0) { lineStyle = null; }
            if (matrix === void 0) { matrix = null; }
            var _this = _super.call(this) || this;
            _this._instanceType = "GraphicsData";
            _this.shape = shape;
            _this.lineStyle = lineStyle;
            _this.fillStyle = fillStyle;
            _this.matrix = matrix;
            _this.holes = [];
            _this.type = shape.type;
            _this.points = [];
            return _this;
        }
        GraphicsData.prototype.clone = function () {
            return new GraphicsData(this.shape, this.fillStyle, this.lineStyle, this.matrix);
        };
        GraphicsData.prototype.destroy = function () {
            this.shape = null;
            this.holes.length = 0;
            this.holes = null;
            this.points.length = 0;
            this.points = null;
            this.lineStyle = null;
            this.fillStyle = null;
        };
        return GraphicsData;
    }(HashObject));

    var BaseRenderTexture = (function (_super) {
        tslib_1.__extends(BaseRenderTexture, _super);
        function BaseRenderTexture(width, height, scaleMode) {
            if (width === void 0) { width = 100; }
            if (height === void 0) { height = 100; }
            if (scaleMode === void 0) { scaleMode = exports.SCALE_MODES.LINEAR; }
            var _this = _super.call(this, null, scaleMode) || this;
            _this.width = Math.ceil(width);
            _this.height = Math.ceil(height);
            _this.scaleMode = scaleMode;
            _this.hasLoaded = true;
            _this._glRenderTargets = {};
            _this._canvasRenderTarget = null;
            _this.valid = false;
            return _this;
        }
        BaseRenderTexture.prototype.resize = function (width, height) {
            width = Math.ceil(width);
            height = Math.ceil(height);
            if (width === this.width && height === this.height) {
                return;
            }
            this.valid = (width > 0 && height > 0);
            this.width = width;
            this.height = height;
            if (!this.valid) {
                return;
            }
            this.dispatchEvent('update');
        };
        BaseRenderTexture.prototype.destroy = function () {
            _super.prototype.destroy.call(this);
        };
        return BaseRenderTexture;
    }(BaseTexture));

    var RenderTexture = (function (_super) {
        tslib_1.__extends(RenderTexture, _super);
        function RenderTexture(baseRenderTexture, frame) {
            var _this = _super.call(this, baseRenderTexture, frame) || this;
            _this.valid = true;
            _this.updateUvs();
            return _this;
        }
        RenderTexture.prototype.resize = function (width, height, doNotResizeBaseTexture) {
            if (doNotResizeBaseTexture === void 0) { doNotResizeBaseTexture = false; }
            width = Math.ceil(width);
            height = Math.ceil(height);
            this.valid = (width > 0 && height > 0);
            this._frame.width = this.orig.width = width;
            this._frame.height = this.orig.height = height;
            if (!doNotResizeBaseTexture) {
                this.baseTexture["resize"](width, height);
            }
            this.updateUvs();
        };
        RenderTexture.create = function (width, height, scaleMode) {
            if (scaleMode === void 0) { scaleMode = exports.SCALE_MODES.LINEAR; }
            return new RenderTexture(new BaseRenderTexture(width, height, scaleMode));
        };
        return RenderTexture;
    }(Texture));

    var Circle = (function () {
        function Circle(x, y, radius) {
            if (x === void 0) { x = 0; }
            if (y === void 0) { y = 0; }
            if (radius === void 0) { radius = 0; }
            this.x = x;
            this.y = y;
            this.radius = radius;
            this.type = exports.SHAPES.CIRC;
        }
        Circle.prototype.clone = function () {
            return new Circle(this.x, this.y, this.radius);
        };
        Circle.prototype.isPointIn = function (point) {
            if (this.radius <= 0) {
                return false;
            }
            var r2 = this.radius * this.radius;
            var dx = (this.x - point.x);
            var dy = (this.y - point.y);
            dx *= dx;
            dy *= dy;
            return (dx + dy <= r2);
        };
        Circle.prototype.getBounds = function () {
            return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2);
        };
        return Circle;
    }());

    var Ellipse = (function () {
        function Ellipse(x, y, width, height) {
            if (x === void 0) { x = 0; }
            if (y === void 0) { y = 0; }
            if (width === void 0) { width = 0; }
            if (height === void 0) { height = 0; }
            this.x = x;
            this.y = y;
            this.width = width;
            this.height = height;
            this.type = exports.SHAPES.ELIP;
        }
        Ellipse.prototype.clone = function () {
            return new Ellipse(this.x, this.y, this.width, this.height);
        };
        Ellipse.prototype.isPointIn = function (point) {
            if (this.width <= 0 || this.height <= 0) {
                return false;
            }
            var normx = ((point.x - this.x) / this.width);
            var normy = ((point.y - this.y) / this.height);
            normx *= normx;
            normy *= normy;
            return (normx + normy <= 1);
        };
        Ellipse.prototype.getBounds = function () {
            return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height);
        };
        return Ellipse;
    }());

    var Polygon = (function () {
        function Polygon() {
            var points = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                points[_i] = arguments[_i];
            }
            if (Array.isArray(points[0])) {
                points = points[0];
            }
            if (points[0] instanceof Point) {
                var p = [];
                for (var i = 0, il = points.length; i < il; i++) {
                    p.push(points[i].x, points[i].y);
                }
                points = p;
            }
            this.closed = true;
            this.points = points;
            this.type = exports.SHAPES.POLY;
        }
        Polygon.prototype.clone = function () {
            return new Polygon(this.points.slice());
        };
        Polygon.prototype.close = function () {
            var points = this.points;
            if (points[0] !== points[points.length - 2] || points[1] !== points[points.length - 1]) {
                points.push(points[0], points[1]);
            }
        };
        Polygon.prototype.isPointIn = function (point) {
            var x = point.x;
            var y = point.y;
            var inside = false;
            var length = this.points.length / 2;
            for (var i = 0, j = length - 1; i < length; j = i++) {
                var xi = this.points[i * 2];
                var yi = this.points[(i * 2) + 1];
                var xj = this.points[j * 2];
                var yj = this.points[(j * 2) + 1];
                var intersect = ((yi > y) !== (yj > y)) && (x < ((xj - xi) * ((y - yi) / (yj - yi))) + xi);
                if (intersect) {
                    inside = !inside;
                }
            }
            return inside;
        };
        return Polygon;
    }());

    var RoundedRectangle = (function () {
        function RoundedRectangle(x, y, width, height, radius) {
            if (x === void 0) { x = 0; }
            if (y === void 0) { y = 0; }
            if (width === void 0) { width = 0; }
            if (height === void 0) { height = 0; }
            if (radius === void 0) { radius = 20; }
            this.x = x;
            this.y = y;
            this.width = width;
            this.height = height;
            var max = (width < height ? width : height) / 2;
            radius = radius < 0 ? -radius : radius;
            radius = radius > max ? max : radius;
            this.radius = radius;
            this.type = exports.SHAPES.RREC;
        }
        RoundedRectangle.prototype.clone = function () {
            return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius);
        };
        RoundedRectangle.prototype.isPointIn = function (point) {
            var x = point.x;
            var y = point.y;
            if (this.width <= 0 || this.height <= 0) {
                return false;
            }
            if (x >= this.x && x <= this.x + this.width) {
                if (y >= this.y && y <= this.y + this.height) {
                    if ((y >= this.y + this.radius && y <= this.y + this.height - this.radius)
                        || (x >= this.x + this.radius && x <= this.x + this.width - this.radius)) {
                        return true;
                    }
                    var dx = x - (this.x + this.radius);
                    var dy = y - (this.y + this.radius);
                    var radius2 = this.radius * this.radius;
                    if ((dx * dx) + (dy * dy) <= radius2) {
                        return true;
                    }
                    dx = x - (this.x + this.width - this.radius);
                    if ((dx * dx) + (dy * dy) <= radius2) {
                        return true;
                    }
                    dy = y - (this.y + this.height - this.radius);
                    if ((dx * dx) + (dy * dy) <= radius2) {
                        return true;
                    }
                    dx = x - (this.x + this.radius);
                    if ((dx * dx) + (dy * dy) <= radius2) {
                        return true;
                    }
                }
            }
            return false;
        };
        return RoundedRectangle;
    }());

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

    var buildPoly = {
        build: function (graphicsData) {
            graphicsData.points = graphicsData.shape.points.slice();
        },
        triangulate: function (graphicsData, graphicsGeometry) {
            var points = graphicsData.points;
            var holes = graphicsData.holes;
            var verts = graphicsGeometry.verts;
            var indices = graphicsGeometry.indices;
            if (points.length >= 6) {
                var holeArray = [];
                for (var i = 0; i < holes.length; i++) {
                    var hole = holes[i];
                    holeArray.push(points.length / 2);
                    points = points.concat(hole.points);
                }
                var triangles = earcut(points, holeArray, 2);
                if (!triangles) {
                    return;
                }
                var vertPos = verts.length / 2;
                for (var i = 0; i < triangles.length; i += 3) {
                    indices.push(triangles[i] + vertPos);
                    indices.push(triangles[i + 1] + vertPos);
                    indices.push(triangles[i + 2] + vertPos);
                }
                for (var i = 0; i < points.length; i++) {
                    verts.push(points[i]);
                }
            }
        },
    };

    var buildCircle = {
        build: function (graphicsData) {
            var circleData = graphicsData.shape;
            var points = graphicsData.points;
            var x = circleData.x;
            var y = circleData.y;
            var width;
            var height;
            points.length = 0;
            if (graphicsData.type === exports.SHAPES.CIRC) {
                width = circleData.radius;
                height = circleData.radius;
            }
            else {
                width = circleData.width;
                height = circleData.height;
            }
            if (width === 0 || height === 0) {
                return;
            }
            var totalSegs = Math.floor(30 * Math.sqrt(circleData.radius))
                || Math.floor(15 * Math.sqrt(circleData.width + circleData.height));
            totalSegs /= 2.3;
            var seg = (Math.PI * 2) / totalSegs;
            for (var i = 0; i < totalSegs; i++) {
                points.push(x + (Math.sin(seg * i) * width), y + (Math.cos(seg * i) * height));
            }
            points.push(points[0], points[1]);
        },
        triangulate: function (graphicsData, graphicsGeometry) {
            var points = graphicsData.points;
            var verts = graphicsGeometry.verts;
            var indices = graphicsGeometry.indices;
            var vertPos = verts.length / 2;
            var center = vertPos;
            verts.push(graphicsData.shape.x, graphicsData.shape.y);
            for (var i = 0; i < points.length; i += 2) {
                verts.push(points[i], points[i + 1]);
                indices.push(vertPos++, center, vertPos);
            }
        },
    };

    var buildRectangle = {
        build: function (graphicsData) {
            var rectData = graphicsData.shape;
            var x = rectData.x;
            var y = rectData.y;
            var width = rectData.width;
            var height = rectData.height;
            var points = graphicsData.points;
            points.length = 0;
            points.push(x, y, x + width, y, x + width, y + height, x, y + height);
        },
        triangulate: function (graphicsData, graphics) {
            var points = graphicsData.points;
            var verts = graphics.verts;
            var vertPos = verts.length / 2;
            verts.push(points[0], points[1], points[2], points[3], points[6], points[7], points[4], points[5]);
            graphics.indices.push(vertPos, vertPos + 1, vertPos + 2, vertPos + 1, vertPos + 2, vertPos + 3);
        },
    };

    var buildRoundedRectangle = {
        build: function (graphicsData) {
            var rrectData = graphicsData.shape;
            var points = graphicsData.points;
            var x = rrectData.x;
            var y = rrectData.y;
            var width = rrectData.width;
            var height = rrectData.height;
            var radius = rrectData.radius;
            points.length = 0;
            points.push(x, y + radius);
            quadraticBezierCurve(x, y + height - radius, x, y + height, x + radius, y + height, points);
            quadraticBezierCurve(x + width - radius, y + height, x + width, y + height, x + width, y + height - radius, points);
            quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y, points);
            quadraticBezierCurve(x + radius, y, x, y, x, y + radius + 0.0000000001, points);
        },
        triangulate: function (graphicsData, graphicsGeometry) {
            var points = graphicsData.points;
            var verts = graphicsGeometry.verts;
            var indices = graphicsGeometry.indices;
            var vecPos = verts.length / 2;
            var triangles = earcut(points, null, 2);
            for (var i = 0, j = triangles.length; i < j; i += 3) {
                indices.push(triangles[i] + vecPos);
                indices.push(triangles[i + 1] + vecPos);
                indices.push(triangles[i + 2] + vecPos);
            }
            for (var i = 0, j = points.length; i < j; i++) {
                verts.push(points[i], points[++i]);
            }
        },
    };
    function getPt(n1, n2, perc) {
        var diff = n2 - n1;
        return n1 + (diff * perc);
    }
    function quadraticBezierCurve(fromX, fromY, cpX, cpY, toX, toY, out) {
        if (out === void 0) { out = []; }
        var n = 20;
        var points = out;
        var xa = 0;
        var ya = 0;
        var xb = 0;
        var yb = 0;
        var x = 0;
        var y = 0;
        for (var i = 0, j = 0; i <= n; ++i) {
            j = i / n;
            xa = getPt(fromX, cpX, j);
            ya = getPt(fromY, cpY, j);
            xb = getPt(cpX, toX, j);
            yb = getPt(cpY, toY, j);
            x = getPt(xa, xb, j);
            y = getPt(ya, yb, j);
            points.push(x, y);
        }
        return points;
    }

    function buildLine (graphicsData, graphicsGeometry) {
        buildLine$1(graphicsData, graphicsGeometry);
    }
    function buildLine$1(graphicsData, graphicsGeometry) {
        var shape = graphicsData.shape;
        var points = graphicsData.points || shape.points.slice();
        if (points.length === 0) {
            return;
        }
        var style = graphicsData.lineStyle;
        var firstPoint = new Point(points[0], points[1]);
        var lastPoint = new Point(points[points.length - 2], points[points.length - 1]);
        var closedShape = shape.type !== exports.SHAPES.POLY;
        var closedPath = firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y;
        if (closedPath || closedShape) {
            points = points.slice();
            if (closedPath) {
                points.pop();
                points.pop();
                lastPoint.set(points[points.length - 2], points[points.length - 1]);
            }
            var midPointX = lastPoint.x + ((firstPoint.x - lastPoint.x) * 0.5);
            var midPointY = lastPoint.y + ((firstPoint.y - lastPoint.y) * 0.5);
            points.unshift(midPointX, midPointY);
            points.push(midPointX, midPointY);
        }
        var verts = graphicsGeometry.verts;
        var length = points.length / 2;
        var indexCount = points.length;
        var indexStart = verts.length / 2;
        var width = style.width / 2;
        var p1x = points[0];
        var p1y = points[1];
        var p2x = points[2];
        var p2y = points[3];
        var p3x = 0;
        var p3y = 0;
        var perpx = -(p1y - p2y);
        var perpy = p1x - p2x;
        var perp2x = 0;
        var perp2y = 0;
        var perp3x = 0;
        var perp3y = 0;
        var dist = Math.sqrt((perpx * perpx) + (perpy * perpy));
        perpx /= dist;
        perpy /= dist;
        perpx *= width;
        perpy *= width;
        var ratio = style.alignment;
        var r1 = (1 - ratio) * 2;
        var r2 = ratio * 2;
        verts.push(p1x - (perpx * r1), p1y - (perpy * r1));
        verts.push(p1x + (perpx * r2), p1y + (perpy * r2));
        for (var i = 1; i < length - 1; ++i) {
            p1x = points[(i - 1) * 2];
            p1y = points[((i - 1) * 2) + 1];
            p2x = points[i * 2];
            p2y = points[(i * 2) + 1];
            p3x = points[(i + 1) * 2];
            p3y = points[((i + 1) * 2) + 1];
            perpx = -(p1y - p2y);
            perpy = p1x - p2x;
            dist = Math.sqrt((perpx * perpx) + (perpy * perpy));
            perpx /= dist;
            perpy /= dist;
            perpx *= width;
            perpy *= width;
            perp2x = -(p2y - p3y);
            perp2y = p2x - p3x;
            dist = Math.sqrt((perp2x * perp2x) + (perp2y * perp2y));
            perp2x /= dist;
            perp2y /= dist;
            perp2x *= width;
            perp2y *= width;
            var a1 = (-perpy + p1y) - (-perpy + p2y);
            var b1 = (-perpx + p2x) - (-perpx + p1x);
            var c1 = ((-perpx + p1x) * (-perpy + p2y)) - ((-perpx + p2x) * (-perpy + p1y));
            var a2 = (-perp2y + p3y) - (-perp2y + p2y);
            var b2 = (-perp2x + p2x) - (-perp2x + p3x);
            var c2 = ((-perp2x + p3x) * (-perp2y + p2y)) - ((-perp2x + p2x) * (-perp2y + p3y));
            var denom = (a1 * b2) - (a2 * b1);
            if (Math.abs(denom) < 0.1) {
                denom += 10.1;
                verts.push(p2x - (perpx * r1), p2y - (perpy * r1));
                verts.push(p2x + (perpx * r2), p2y + (perpy * r2));
                continue;
            }
            var px = ((b1 * c2) - (b2 * c1)) / denom;
            var py = ((a2 * c1) - (a1 * c2)) / denom;
            var pdist = ((px - p2x) * (px - p2x)) + ((py - p2y) * (py - p2y));
            if (pdist > (196 * width * width)) {
                perp3x = perpx - perp2x;
                perp3y = perpy - perp2y;
                dist = Math.sqrt((perp3x * perp3x) + (perp3y * perp3y));
                perp3x /= dist;
                perp3y /= dist;
                perp3x *= width;
                perp3y *= width;
                verts.push(p2x - (perp3x * r1), p2y - (perp3y * r1));
                verts.push(p2x + (perp3x * r2), p2y + (perp3y * r2));
                verts.push(p2x - (perp3x * r2 * r1), p2y - (perp3y * r1));
                indexCount++;
            }
            else {
                verts.push(p2x + ((px - p2x) * r1), p2y + ((py - p2y) * r1));
                verts.push(p2x - ((px - p2x) * r2), p2y - ((py - p2y) * r2));
            }
        }
        p1x = points[(length - 2) * 2];
        p1y = points[((length - 2) * 2) + 1];
        p2x = points[(length - 1) * 2];
        p2y = points[((length - 1) * 2) + 1];
        perpx = -(p1y - p2y);
        perpy = p1x - p2x;
        dist = Math.sqrt((perpx * perpx) + (perpy * perpy));
        perpx /= dist;
        perpy /= dist;
        perpx *= width;
        perpy *= width;
        verts.push(p2x - (perpx * r1), p2y - (perpy * r1));
        verts.push(p2x + (perpx * r2), p2y + (perpy * r2));
        var indices = graphicsGeometry.indices;
        for (var i = 0; i < indexCount - 2; ++i) {
            indices.push(indexStart, indexStart + 1, indexStart + 2);
            indexStart++;
        }
    }

    var FillStyle = (function () {
        function FillStyle() {
            this.reset();
        }
        FillStyle.prototype.clone = function () {
            var obj = new FillStyle();
            obj.color = this.color;
            obj.alpha = this.alpha;
            obj.texture = this.texture;
            obj.matrix = this.matrix;
            obj.visible = this.visible;
            obj.alphaBlock = this.alphaBlock;
            return obj;
        };
        FillStyle.prototype.reset = function () {
            this.color = 0xFFFFFF;
            this.alpha = 1;
            this.texture = Texture.WHITE;
            this.matrix = null;
            this.visible = false;
            this.alphaBlock = false;
        };
        FillStyle.prototype.destroy = function () {
            this.texture = null;
            this.matrix = null;
        };
        return FillStyle;
    }());

    var LineStyle = (function (_super) {
        tslib_1.__extends(LineStyle, _super);
        function LineStyle() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        LineStyle.prototype.clone = function () {
            var obj = new LineStyle();
            obj.color = this.color;
            obj.alpha = this.alpha;
            obj.texture = this.texture;
            obj.matrix = this.matrix;
            obj.visible = this.visible;
            obj.width = this.width;
            obj.alignment = this.alignment;
            obj.native = this.native;
            return obj;
        };
        LineStyle.prototype.reset = function () {
            _super.prototype.reset.call(this);
            this.color = 0x0;
            this.width = 0;
            this.alignment = 0.5;
            this.native = false;
        };
        return LineStyle;
    }(FillStyle));

    function bezierCurveTo(fromX, fromY, cpX, cpY, cpX2, cpY2, toX, toY, n, path) {
        if (path === void 0) { path = []; }
        var dt = 0;
        var dt2 = 0;
        var dt3 = 0;
        var t2 = 0;
        var t3 = 0;
        path.push(fromX, fromY);
        for (var i = 1, j = 0; i <= n; ++i) {
            j = i / n;
            dt = (1 - j);
            dt2 = dt * dt;
            dt3 = dt2 * dt;
            t2 = j * j;
            t3 = t2 * j;
            path.push((dt3 * fromX) + (3 * dt2 * j * cpX) + (3 * dt * t2 * cpX2) + (t3 * toX), (dt3 * fromY) + (3 * dt2 * j * cpY) + (3 * dt * t2 * cpY2) + (t3 * toY));
        }
        return path;
    }

    var GRAPHICS_CURVES = {
        adaptive: false,
        maxLength: 10,
        minSegments: 8,
        maxSegments: 2048,
        segmentsCount: function (length, defaultSegments) {
            if (defaultSegments === void 0) { defaultSegments = 20; }
            if (!this.adaptive)
                return defaultSegments;
            var result = Math.ceil(length / this.maxLength);
            if (result < this.minSegments) {
                result = this.minSegments;
            }
            else if (result > this.maxSegments) {
                result = this.maxSegments;
            }
            return result;
        }
    };
    function quadraticCurveLength(fromX, fromY, cpX, cpY, toX, toY) {
        var ax = fromX - ((2.0 * cpX) + toX);
        var ay = fromY - ((2.0 * cpY) + toY);
        var bx = 2.0 * ((cpX - 2.0) * fromX);
        var by = 2.0 * ((cpY - 2.0) * fromY);
        var a = 4.0 * ((ax * ax) + (ay * ay));
        var b = 4.0 * ((ax * bx) + (ay * by));
        var c = (bx * bx) + (by * by);
        var s = 2.0 * Math.sqrt(a + b + c);
        var a2 = Math.sqrt(a);
        var a32 = 2.0 * a * a2;
        var c2 = 2.0 * Math.sqrt(c);
        var ba = b / a2;
        return ((a32 * s)
            + (a2 * b * (s - c2))
            + (((4.0 * c * a) - (b * b))
                * Math.log(((2.0 * a2) + ba + s) / (ba + c2))))
            / (4.0 * a32);
    }
    function bezierCurveLength(fromX, fromY, cpX, cpY, cpX2, cpY2, toX, toY) {
        var n = 10;
        var result = 0.0;
        var t = 0.0;
        var t2 = 0.0;
        var t3 = 0.0;
        var nt = 0.0;
        var nt2 = 0.0;
        var nt3 = 0.0;
        var x = 0.0;
        var y = 0.0;
        var dx = 0.0;
        var dy = 0.0;
        var prevX = fromX;
        var prevY = fromY;
        for (var i = 1; i <= n; ++i) {
            t = i / n;
            t2 = t * t;
            t3 = t2 * t;
            nt = (1.0 - t);
            nt2 = nt * nt;
            nt3 = nt2 * nt;
            x = (nt3 * fromX) + (3.0 * nt2 * t * cpX) + (3.0 * nt * t2 * cpX2) + (t3 * toX);
            y = (nt3 * fromY) + (3.0 * nt2 * t * cpY) + (3 * nt * t2 * cpY2) + (t3 * toY);
            dx = prevX - x;
            dy = prevY - y;
            prevX = x;
            prevY = y;
            result += Math.sqrt((dx * dx) + (dy * dy));
        }
        return result;
    }

    var canvasRenderer;
    var tempMatrix$1 = new Matrix();
    var tempPoint = new Point();
    var temp = new Float32Array(3);
    var GEOBATCH_POOL = [];
    var fillCommands = {};
    fillCommands[exports.SHAPES.POLY] = buildPoly;
    fillCommands[exports.SHAPES.CIRC] = buildCircle;
    fillCommands[exports.SHAPES.ELIP] = buildCircle;
    fillCommands[exports.SHAPES.RECT] = buildRectangle;
    fillCommands[exports.SHAPES.RREC] = buildRoundedRectangle;
    var Graphics = (function (_super) {
        tslib_1.__extends(Graphics, _super);
        function Graphics() {
            var _this = _super.call(this) || this;
            _this._blendMode = exports.BLEND_MODES.NORMAL;
            _this.batchTint = -1;
            _this.hitTestByPixel = true;
            _this.cacheAsBitmap = true;
            _this._instanceType = "Graphics";
            _this._fillStyle = new FillStyle();
            _this._lineStyle = new LineStyle();
            _this.tint = 0xFFFFFF;
            _this.batchTint = -1;
            _this._matrix = null;
            _this._holeMode = false;
            _this._currentPath = null;
            _this.graphicsData = [];
            _this.isUsedToMask = false;
            _this.boundsPadding = 0;
            _this.dirty = 0;
            _this.boundsDirty = -1;
            _this.cacheDirty = -1;
            _this.verts = [];
            _this.indices = [];
            _this.batches = [];
            _this.geoBatches = [];
            _this.uvs = [];
            _this.batchDirty = -1;
            _this.shapeIndex = 0;
            _this.vertexData = null;
            _this._transformID = -1;
            return _this;
        }
        Object.defineProperty(Graphics.prototype, "blendMode", {
            get: function () {
                return this._blendMode;
            },
            set: function (value) {
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Graphics.prototype, "fill", {
            get: function () {
                return this._fillStyle;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Graphics.prototype, "line", {
            get: function () {
                return this._lineStyle;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Graphics.prototype, "tint", {
            get: function () {
                return this._tint;
            },
            set: function (value) {
                this._tint = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Graphics.prototype, "matrix", {
            get: function () {
                return this._matrix;
            },
            set: function (matrix) {
            },
            enumerable: true,
            configurable: true
        });
        Graphics.prototype.clone = function () {
            var clone = new Graphics();
            clone.renderable = this.renderable;
            clone._fillStyle = this._fillStyle;
            clone._lineStyle = this._lineStyle;
            clone.isUsedToMask = this.isUsedToMask;
            clone.boundsPadding = this.boundsPadding;
            clone.dirty = 0;
            for (var i = 0; i < this.graphicsData.length; ++i) {
                clone.graphicsData.push(this.graphicsData[i].clone());
            }
            clone._currentPath = null;
            clone.updateLocalBoundsSelf();
            return clone;
        };
        Graphics.prototype.lineStyle = function (lineWidth, color, alpha, alignment, native) {
            if (lineWidth === void 0) { lineWidth = 0; }
            if (color === void 0) { color = 0; }
            if (alpha === void 0) { alpha = 1; }
            if (alignment === void 0) { alignment = 0.5; }
            if (native === void 0) { native = false; }
            this.lineTextureStyle(lineWidth, Texture.WHITE, color, alpha, null, alignment, native);
            return this;
        };
        Graphics.prototype.lineTextureStyle = function (width, texture, color, alpha, matrix, alignment, native) {
            if (width === void 0) { width = 0; }
            if (texture === void 0) { texture = Texture.WHITE; }
            if (color === void 0) { color = 0xFFFFFF; }
            if (alpha === void 0) { alpha = 1; }
            if (matrix === void 0) { matrix = null; }
            if (alignment === void 0) { alignment = 0.5; }
            if (native === void 0) { native = false; }
            if (this._currentPath)
                this.startPoly();
            var visible = width > 0 && alpha > 0;
            if (!visible) {
                this._lineStyle.reset();
            }
            else {
                if (matrix) {
                    matrix = matrix.clone();
                    matrix.invert();
                }
                this._lineStyle.color = color;
                this._lineStyle.width = width;
                this._lineStyle.alpha = alpha;
                this._lineStyle.matrix = matrix;
                this._lineStyle.texture = texture;
                this._lineStyle.alignment = alignment;
                this._lineStyle.native = native;
                this._lineStyle.visible = visible;
            }
            return this;
        };
        Graphics.prototype.startPoly = function () {
            if (this._currentPath) {
                var points = this._currentPath.points;
                var len = this._currentPath.points.length;
                if (len > 2) {
                    this.drawShape(this._currentPath);
                    this._currentPath = new Polygon();
                    this._currentPath.closed = false;
                    this._currentPath.points.push(points[len - 2], points[len - 1]);
                }
            }
            else {
                this._currentPath = new Polygon();
                this._currentPath.closed = false;
            }
        };
        Graphics.prototype.finishPoly = function () {
            if (this._currentPath) {
                if (this._currentPath.points.length > 2) {
                    this.drawShape(this._currentPath);
                    this._currentPath = null;
                }
                else {
                    this._currentPath.points.length = 0;
                }
            }
        };
        Graphics.prototype.moveTo = function (x, y) {
            this.startPoly();
            this._currentPath.points[0] = x;
            this._currentPath.points[1] = y;
            return this;
        };
        Graphics.prototype.lineTo = function (x, y) {
            if (!this._currentPath)
                this.moveTo(0, 0);
            var points = this._currentPath.points;
            var fromX = points[points.length - 2];
            var fromY = points[points.length - 1];
            if (fromX !== x || fromY !== y) {
                points.push(x, y);
            }
            return this;
        };
        Graphics.prototype._initCurve = function (x, y) {
            if (x === void 0) { x = 0; }
            if (y === void 0) { y = 0; }
            if (this._currentPath) {
                if (this._currentPath.points.length === 0) {
                    this._currentPath.points = [x, y];
                }
            }
            else {
                this.moveTo(x, y);
            }
        };
        Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) {
            this._initCurve();
            var points = this._currentPath.points;
            if (points.length === 0) {
                this.moveTo(0, 0);
            }
            var xa = 0;
            var ya = 0;
            var fromX = points[points.length - 2];
            var fromY = points[points.length - 1];
            var n = GRAPHICS_CURVES.segmentsCount(quadraticCurveLength(fromX, fromY, cpX, cpY, toX, toY));
            for (var i = 1; i <= n; ++i) {
                var j = i / n;
                xa = fromX + ((cpX - fromX) * j);
                ya = fromY + ((cpY - fromY) * j);
                points.push(xa + (((cpX + ((toX - cpX) * j)) - xa) * j), ya + (((cpY + ((toY - cpY) * j)) - ya) * j));
            }
            return this;
        };
        Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) {
            this._initCurve();
            var points = this._currentPath.points;
            var fromX = points[points.length - 2];
            var fromY = points[points.length - 1];
            points.length -= 2;
            var n = GRAPHICS_CURVES.segmentsCount(bezierCurveLength(fromX, fromY, cpX, cpY, cpX2, cpY2, toX, toY));
            bezierCurveTo(fromX, fromY, cpX, cpY, cpX2, cpY2, toX, toY, n, points);
            return this;
        };
        Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) {
            this._initCurve(x1, y1);
            var points = this._currentPath.points;
            var fromX = points[points.length - 2];
            var fromY = points[points.length - 1];
            var a1 = fromY - y1;
            var b1 = fromX - x1;
            var a2 = y2 - y1;
            var b2 = x2 - x1;
            var mm = Math.abs((a1 * b2) - (b1 * a2));
            if (mm < 1.0e-8 || radius === 0) {
                if (points[points.length - 2] !== x1 || points[points.length - 1] !== y1) {
                    points.push(x1, y1);
                }
            }
            else {
                var dd = (a1 * a1) + (b1 * b1);
                var cc = (a2 * a2) + (b2 * b2);
                var tt = (a1 * a2) + (b1 * b2);
                var k1 = radius * Math.sqrt(dd) / mm;
                var k2 = radius * Math.sqrt(cc) / mm;
                var j1 = k1 * tt / dd;
                var j2 = k2 * tt / cc;
                var cx = (k1 * b2) + (k2 * b1);
                var cy = (k1 * a2) + (k2 * a1);
                var px = b1 * (k2 + j1);
                var py = a1 * (k2 + j1);
                var qx = b2 * (k1 + j2);
                var qy = a2 * (k1 + j2);
                var startAngle = Math.atan2(py - cy, px - cx);
                var endAngle = Math.atan2(qy - cy, qx - cx);
                this.arc(cx + x1, cy + y1, radius, startAngle, endAngle, b1 * a2 > b2 * a1);
            }
            return this;
        };
        Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) {
            if (anticlockwise === void 0) { anticlockwise = false; }
            if (startAngle === endAngle) {
                return this;
            }
            if (!anticlockwise && endAngle <= startAngle) {
                endAngle += PI_2;
            }
            else if (anticlockwise && startAngle <= endAngle) {
                startAngle += PI_2;
            }
            var sweep = endAngle - startAngle;
            if (sweep === 0) {
                return this;
            }
            var startX = cx + (Math.cos(startAngle) * radius);
            var startY = cy + (Math.sin(startAngle) * radius);
            var points = this._currentPath ? this._currentPath.points : null;
            if (points) {
                var xDiff = Math.abs(points[points.length - 2] - startX);
                var yDiff = Math.abs(points[points.length - 1] - startY);
                if (xDiff < 0.001 && yDiff < 0.001) ;
                else {
                    points.push(startX, startY);
                }
            }
            else {
                this.moveTo(startX, startY);
                points = this._currentPath.points;
            }
            var segs = GRAPHICS_CURVES.segmentsCount(Math.abs(sweep) * radius, Math.ceil(Math.abs(sweep) / PI_2) * 40);
            var theta = sweep / (segs * 2);
            var theta2 = theta * 2;
            var cTheta = Math.cos(theta);
            var sTheta = Math.sin(theta);
            var segMinus = segs - 1;
            var remainder = (segMinus % 1) / segMinus;
            for (var i = 0; i <= segMinus; ++i) {
                var real = i + (remainder * i);
                var angle = ((theta) + startAngle + (theta2 * real));
                var c = Math.cos(angle);
                var s = -Math.sin(angle);
                points.push((((cTheta * c) + (sTheta * s)) * radius) + cx, (((cTheta * -s) + (sTheta * c)) * radius) + cy);
            }
            return this;
        };
        Graphics.prototype.beginFill = function (color, alpha) {
            if (color === void 0) { color = 0; }
            if (alpha === void 0) { alpha = 1; }
            if (typeof (color) == "string")
                color = string2hex(color);
            return this.beginTextureFill(Texture.WHITE, color, alpha);
        };
        Graphics.prototype.beginTextureFill = function (texture, color, alpha, matrix) {
            if (texture === void 0) { texture = Texture.WHITE; }
            if (color === void 0) { color = 0xFFFFFF; }
            if (alpha === void 0) { alpha = 1; }
            if (matrix === void 0) { matrix = null; }
            if (this._currentPath)
                this.startPoly();
            var visible = alpha > 0;
            if (!visible) {
                this._fillStyle.reset();
                this._fillStyle.alphaBlock = true;
            }
            else {
                this._fillStyle.color = color;
                this._fillStyle.alpha = alpha;
                this._fillStyle.texture = texture;
                this._fillStyle.matrix = matrix;
                this._fillStyle.visible = visible;
            }
            return this;
        };
        Graphics.prototype.endFill = function () {
            this.finishPoly();
            this._fillStyle.reset();
            return this;
        };
        Graphics.prototype.endStroke = function () {
            this.finishPoly();
            this._lineStyle.reset();
            return this;
        };
        Graphics.prototype.closePath = function () {
            var _currentPath = this._currentPath;
            if (this._currentPath)
                _currentPath.close();
            return this;
        };
        Graphics.prototype.beginHole = function () {
            this.finishPoly();
            this._holeMode = true;
            return this;
        };
        Graphics.prototype.endHole = function () {
            this.finishPoly();
            this._holeMode = false;
            return this;
        };
        Graphics.prototype.drawRect = function (x, y, width, height) {
            return this.drawShape(new Rectangle(x, y, width, height));
        };
        Graphics.prototype.drawRoundedRect = function (x, y, width, height, radius) {
            return this.drawShape(new RoundedRectangle(x, y, width, height, radius));
        };
        Graphics.prototype.drawCircle = function (x, y, radius) {
            return this.drawShape(new Circle(x, y, radius));
        };
        Graphics.prototype.drawEllipse = function (x, y, width, height) {
            return this.drawShape(new Ellipse(x, y, width, height));
        };
        Graphics.prototype.drawPolygon = function (path) {
            var points = path;
            var closed = true;
            if (points instanceof Polygon) {
                closed = points.closed;
                points = points.points;
            }
            if (!Array.isArray(points)) {
                points = new Array(arguments.length);
                for (var i = 0; i < points.length; ++i) {
                    points[i] = arguments[i];
                }
            }
            var shape = new Polygon(points);
            shape.closed = closed;
            this.drawShape(shape);
            return this;
        };
        Graphics.prototype.drawStar = function (x, y, points, radius, innerRadius, rotation) {
            if (rotation === void 0) { rotation = 0; }
            innerRadius = innerRadius || radius / 2;
            var startAngle = (-1 * Math.PI / 2) + rotation;
            var len = points * 2;
            var delta = PI_2 / len;
            var polygon = [];
            for (var i = 0; i < len; i++) {
                var r = i % 2 ? innerRadius : radius;
                var angle = (i * delta) + startAngle;
                polygon.push(x + (r * Math.cos(angle)), y + (r * Math.sin(angle)));
            }
            return this.drawPolygon(polygon);
        };
        Graphics.prototype.drawShape = function (shape) {
            if (!this._holeMode) {
                var data = new GraphicsData(shape, this._fillStyle.clone(), this._lineStyle.clone(), this._matrix);
                this.graphicsData.push(data);
                this.dirty++;
            }
            else {
                if (!this.graphicsData.length)
                    return this;
                var data = new GraphicsData(shape, null, null, this._matrix);
                var lastShape = this.graphicsData[this.graphicsData.length - 1];
                lastShape.holes.push(data);
                this.dirty++;
            }
            return this;
        };
        Graphics.prototype.clear = function () {
            if (this.graphicsData.length > 0) {
                this.boundsDirty = -1;
                this.dirty++;
                this.graphicsData.length = 0;
                this.verts.length = 0;
                this.uvs.length = 0;
                this.indices.length = 0;
                this.shapeIndex = 0;
                for (var i = 0; i < this.geoBatches.length; i++) {
                    var batch = this.geoBatches[i];
                    batch.start = 0;
                    batch.attribStart = 0;
                    batch.style = null;
                    GEOBATCH_POOL.push(batch);
                }
                this.geoBatches.length = 0;
                this.batches.length = 0;
            }
            this._currentPath = null;
            this._matrix = null;
            this._holeMode = false;
            this._currentPath = null;
            return this;
        };
        Graphics.prototype.isFastRect = function () {
            return false;
        };
        Graphics.prototype._renderWebGL = function (renderer) {
            this.finishPoly();
            this.updateBatch();
            renderer.batchManager.setObjectRenderer(renderer.plugins["batch"]);
            if (this.batches.length) {
                this.calculateVertices();
                this.calculateTints();
                for (var i = 0; i < this.batches.length; i++) {
                    var batch = this.batches[i];
                    batch._worldAlpha = this._worldAlpha * batch.graAlpha;
                    renderer.plugins["batch"].render(batch);
                }
            }
        };
        Graphics.prototype.updateBatch = function () {
            if (this.batchDirty === this.dirty)
                return;
            if (this.graphicsData.length === 0)
                return;
            this.batchDirty = this.dirty;
            var uvs = this.uvs;
            var batchPart;
            batchPart = this.geoBatches.pop();
            if (!batchPart) {
                batchPart = GEOBATCH_POOL.pop() || new geoBatchPart();
                batchPart.style = batchPart.style ||
                    this.graphicsData[0].fillStyle ||
                    this.graphicsData[0].lineStyle;
            }
            var currentTexture = batchPart.style.texture.baseTexture;
            var currentColor = batchPart.style.color + batchPart.style.alpha;
            this.geoBatches.push(batchPart);
            for (var i = this.shapeIndex; i < this.graphicsData.length; i++) {
                this.shapeIndex++;
                var data = this.graphicsData[i];
                var command = fillCommands[data.type];
                var fillStyle = data.fillStyle;
                var lineStyle = data.lineStyle;
                command.build(data);
                if (data.matrix)
                    this.transformPoints(data.points, data.matrix);
                for (var j = 0; j < 2; j++) {
                    var style = (j === 0) ? fillStyle : lineStyle;
                    if (!style.visible)
                        continue;
                    var nextTexture = style.texture.baseTexture;
                    if (currentTexture !== nextTexture || (style.color + style.alpha) !== currentColor) {
                        nextTexture.wrapMode = exports.WRAP_MODES.REPEAT;
                        currentTexture = nextTexture;
                        currentColor = style.color + style.alpha;
                        var index_1 = this.indices.length;
                        var attribIndex = this.verts.length / 2;
                        batchPart.size = index_1 - batchPart.start;
                        batchPart.attribSize = attribIndex - batchPart.attribStart;
                        if (batchPart.size > 0) {
                            batchPart = GEOBATCH_POOL.pop() || new geoBatchPart();
                            this.geoBatches.push(batchPart);
                        }
                        batchPart.style = style;
                        batchPart.start = index_1;
                        batchPart.attribStart = attribIndex;
                    }
                    var start = this.verts.length / 2;
                    if (j === 0) {
                        if (data.holes.length) {
                            this.proccessHoles(data.holes);
                            buildPoly.triangulate(data, this);
                        }
                        else {
                            command.triangulate(data, this);
                        }
                    }
                    else {
                        buildLine(data, this);
                    }
                    var size = (this.verts.length / 2) - start;
                    this.addUvs(this.verts, uvs, style.texture, start, size, style.matrix);
                }
            }
            var index = this.indices.length;
            var attrib = this.verts.length / 2;
            batchPart.size = index - batchPart.start;
            batchPart.attribSize = attrib - batchPart.attribStart;
            var indicesUint16 = new Uint16Array(this.indices);
            var uvsFloat32 = new Float32Array(this.uvs);
            for (var i_1 = 0; i_1 < this.geoBatches.length; i_1++) {
                var batch = this.geoBatches[i_1];
                for (var j = 0; j < batch.size; j++) {
                    var index_2 = batch.start + j;
                    indicesUint16[index_2] = indicesUint16[index_2] - batch.attribStart;
                }
            }
            this._transformID = -1;
            this.batchTint = -1;
            this.batches = [];
            this.vertexData = new Float32Array(this.verts);
            var blendMode = this.blendMode;
            for (var i_2 = 0; i_2 < this.geoBatches.length; i_2++) {
                var gI = this.geoBatches[i_2];
                var color = gI.style.color;
                var vertexData = new Float32Array(this.vertexData.buffer, gI.attribStart * 4 * 2, gI.attribSize * 2);
                var uvs_1 = new Float32Array(uvsFloat32.buffer, gI.attribStart * 4 * 2, gI.attribSize * 2);
                var indices = new Uint16Array(indicesUint16.buffer, gI.start * 2, gI.size);
                var batch = {
                    _vertexData: vertexData,
                    _indices: indices,
                    _uvs: uvs_1,
                    _tintRGB: color,
                    _texture: gI.style.texture,
                    _worldAlpha: 1,
                    _blendMode: blendMode,
                    graAlpha: gI.style.alpha,
                    _batchRGB: hex2rgb$1(color),
                };
                this.batches[i_2] = batch;
            }
        };
        Graphics.prototype.calculateTints = function () {
            if (this.batchTint !== this.tint) {
                this.batchTint = this.tint;
                var tintRGB = hex2rgb$1(this.tint, temp);
                for (var i = 0; i < this.batches.length; i++) {
                    var batch = this.batches[i];
                    var batchTint = batch._batchRGB;
                    var r = (tintRGB[0] * batchTint[0]) * 255;
                    var g = (tintRGB[1] * batchTint[1]) * 255;
                    var b = (tintRGB[2] * batchTint[2]) * 255;
                    var color = (r << 16) + (g << 8) + (b | 0);
                    batch._tintRGB = (color >> 16)
                        + (color & 0xff00)
                        + ((color & 0xff) << 16);
                }
            }
        };
        Graphics.prototype.calculateVertices = function () {
            if (this._transformID === this.transform._worldID) {
                return;
            }
            this._transformID = this.transform._worldID;
            var wt = this.transform.worldMatrix;
            var a = wt.a;
            var b = wt.b;
            var c = wt.c;
            var d = wt.d;
            var tx = wt.tx;
            var ty = wt.ty;
            var data = this.verts;
            var vertexData = this.vertexData;
            var count = 0;
            for (var i = 0; i < data.length; i += 2) {
                var x = data[i];
                var y = data[i + 1];
                vertexData[count++] = (a * x) + (c * y) + tx;
                vertexData[count++] = (d * y) + (b * x) + ty;
            }
        };
        Graphics.prototype.transformPoints = function (points, matrix) {
            for (var i = 0; i < points.length / 2; i++) {
                var x = points[(i * 2)];
                var y = points[(i * 2) + 1];
                points[(i * 2)] = (matrix.a * x) + (matrix.c * y) + matrix.tx;
                points[(i * 2) + 1] = (matrix.b * x) + (matrix.d * y) + matrix.ty;
            }
        };
        Graphics.prototype._renderCanvas = function (renderer) {
            if (this.cacheAsBitmap) {
                if (this.cacheDirty != this.dirty) {
                    this.cacheDirty = this.dirty;
                    var tempMask = this.mask;
                    this.mask = null;
                    this.cacheAsBitmap = false;
                    var tempAlpha = this.alpha;
                    this.alpha = 1;
                    this.generateCanvasTexture();
                    this.mask = tempMask;
                    this.alpha = tempAlpha;
                    this.cacheAsBitmap = true;
                    this.updateTransform();
                }
                renderer.plugins.sprite.render(this);
            }
            else {
                renderer.plugins.graphics.render(this);
            }
        };
        Graphics.prototype._calculateBounds = function () {
            this.updateLocalBoundsSelf();
            var rect = this._localBoundsSelf;
            var matrix = this.transform.worldMatrix;
            matrix.transformPoint(rect.x, rect.y, DisplayObject._p1);
            matrix.transformPoint(rect.x + rect.width, rect.y, DisplayObject._p2);
            matrix.transformPoint(rect.x + rect.width, rect.y + rect.height, DisplayObject._p3);
            matrix.transformPoint(rect.x, rect.y + rect.height, DisplayObject._p4);
            Rectangle.createFromPoints(this._bounds, DisplayObject._p1, DisplayObject._p2, DisplayObject._p3, DisplayObject._p4);
        };
        Graphics.prototype.hitTestPoint = function (point, isMouseEvent) {
            if (isMouseEvent === void 0) { isMouseEvent = false; }
            if (!this.visible)
                return null;
            var hitDisplayObject;
            hitDisplayObject = _super.prototype.hitTestPoint.call(this, point, isMouseEvent);
            if (hitDisplayObject)
                return hitDisplayObject;
            if (isMouseEvent && !this.mouseEnable)
                return null;
            this.updateLocalBoundsSelf();
            hitDisplayObject = this.displayObjectHitTestPoint(point, isMouseEvent);
            if (hitDisplayObject) {
                if (!this.hitTestByPixel)
                    return hitDisplayObject;
                return this.hitTestPointAccuratly(point, isMouseEvent);
            }
            return null;
        };
        Graphics.prototype.hitTestPointAccuratly = function (point, isMouseEvent) {
            var s = this;
            if (isMouseEvent) {
                this.worldMatrix.transformPointInverse(point.x, point.y, tempPoint);
            }
            else {
                tempPoint.set(point.x, point.y);
            }
            var graphicsData = this.graphicsData;
            for (var i = 0; i < graphicsData.length; ++i) {
                var data = graphicsData[i];
                if (!data.fillStyle.visible && !data.fillStyle.alphaBlock)
                    continue;
                if (data.shape) {
                    if (data.shape.isPointIn(tempPoint)) {
                        if (data.holes) {
                            for (var i_3 = 0; i_3 < data.holes.length; i_3++) {
                                var hole = data.holes[i_3].shape;
                                if (hole.isPointIn(tempPoint)) {
                                    return null;
                                }
                            }
                        }
                        return s;
                    }
                }
            }
            return null;
        };
        Graphics.prototype.updateLocalBoundsSelf = function () {
            if (this.boundsDirty == this.dirty)
                return;
            this.boundsDirty = this.dirty;
            var minX = Infinity;
            var maxX = -Infinity;
            var minY = Infinity;
            var maxY = -Infinity;
            if (this.graphicsData.length) {
                var shape = void 0;
                var x = 0;
                var y = 0;
                var w = 0;
                var h = 0;
                for (var i = 0; i < this.graphicsData.length; i++) {
                    var data = this.graphicsData[i];
                    var type = data.type;
                    var lineStyle = data.lineStyle;
                    var nextMatrix = data.matrix || Matrix.IDENTITY;
                    var lineWidth = 0.0;
                    if (lineStyle && lineStyle.visible) {
                        var alignment = lineStyle.alignment;
                        lineWidth = lineStyle.width;
                        if (type === exports.SHAPES.POLY) {
                            lineWidth = lineWidth * (0.5 + Math.abs(0.5 - alignment));
                        }
                        else {
                            lineWidth = lineWidth * Math.max(0, alignment);
                        }
                    }
                    shape = data.shape;
                    if (type === exports.SHAPES.RECT || type === exports.SHAPES.RREC) {
                        x = shape.x - (lineWidth / 2);
                        y = shape.y - (lineWidth / 2);
                        w = shape.width + lineWidth;
                        h = shape.height + lineWidth;
                        minX = x < minX ? x : minX;
                        maxX = x + w > maxX ? x + w : maxX;
                        minY = y < minY ? y : minY;
                        maxY = y + h > maxY ? y + h : maxY;
                    }
                    else if (type === exports.SHAPES.CIRC) {
                        x = shape.x;
                        y = shape.y;
                        w = shape.radius + (lineWidth / 2);
                        h = shape.radius + (lineWidth / 2);
                        minX = x - w < minX ? x - w : minX;
                        maxX = x + w > maxX ? x + w : maxX;
                        minY = y - h < minY ? y - h : minY;
                        maxY = y + h > maxY ? y + h : maxY;
                    }
                    else if (type === exports.SHAPES.ELIP) {
                        x = shape.x;
                        y = shape.y;
                        w = shape.width + (lineWidth / 2);
                        h = shape.height + (lineWidth / 2);
                        minX = x - w < minX ? x - w : minX;
                        maxX = x + w > maxX ? x + w : maxX;
                        minY = y - h < minY ? y - h : minY;
                        maxY = y + h > maxY ? y + h : maxY;
                    }
                    else {
                        var points = shape.points;
                        var x2 = 0;
                        var y2 = 0;
                        var dx = 0;
                        var dy = 0;
                        var rw = 0;
                        var rh = 0;
                        var cx = 0;
                        var cy = 0;
                        for (var j = 0; j + 2 < points.length; j += 2) {
                            x = points[j];
                            y = points[j + 1];
                            x2 = points[j + 2];
                            y2 = points[j + 3];
                            dx = Math.abs(x2 - x);
                            dy = Math.abs(y2 - y);
                            h = lineWidth;
                            w = Math.sqrt((dx * dx) + (dy * dy));
                            if (w < 1e-9) {
                                continue;
                            }
                            rw = ((h / w * dy) + dx) / 2;
                            rh = ((h / w * dx) + dy) / 2;
                            cx = (x2 + x) / 2;
                            cy = (y2 + y) / 2;
                            minX = cx - rw < minX ? cx - rw : minX;
                            maxX = cx + rw > maxX ? cx + rw : maxX;
                            minY = cy - rh < minY ? cy - rh : minY;
                            maxY = cy + rh > maxY ? cy + rh : maxY;
                        }
                    }
                }
            }
            else {
                minX = 0;
                maxX = 0;
                minY = 0;
                maxY = 0;
            }
            var padding = this.boundsPadding;
            this._localBoundsSelf.x = minX - padding;
            this._localBoundsSelf.y = minY - padding;
            this._localBoundsSelf.width = maxX - minX + padding * 2;
            this._localBoundsSelf.height = maxY - minY + padding * 2;
        };
        Graphics.prototype.generateCanvasTexture = function (scaleMode) {
            if (scaleMode === void 0) { scaleMode = exports.SCALE_MODES.LINEAR; }
            this.updateLocalBoundsSelf();
            var bounds = this._localBoundsSelf;
            if (!this._canvasBuffer) {
                this._canvasBuffer = RenderTexture.create(bounds.width, bounds.height, scaleMode);
            }
            else {
                this._canvasBuffer.resize(bounds.width, bounds.height);
            }
            if (!canvasRenderer) {
                canvasRenderer = new CanvasRenderer(null, 0, 0);
            }
            this.transform.updateLocalMatrix();
            tempMatrix$1.copy(this.transform.localMatrix);
            tempMatrix$1.invert();
            tempMatrix$1.tx -= bounds.x;
            tempMatrix$1.ty -= bounds.y;
            canvasRenderer.render(this, this._canvasBuffer, tempMatrix$1);
            if (!this._texture) {
                this._texture = Texture.fromCanvas(this._canvasBuffer.baseTexture["_canvasRenderTarget"].canvas, 'graphics');
                this._texture.baseTexture.update();
            }
            else {
                this._texture.baseTexture.update();
            }
            this.offsetX = bounds.x;
            this.offsetY = bounds.y;
            return this._texture;
        };
        Graphics.prototype.destroy = function () {
            _super.prototype.destroy.call(this);
            for (var i = 0; i < this.graphicsData.length; ++i) {
                this.graphicsData[i].destroy();
            }
            this._matrix = null;
            this._currentPath = null;
            this._lineStyle.destroy();
            this._lineStyle = null;
            this._fillStyle.destroy();
            this._fillStyle = null;
            this.vertexData = null;
            this.geoBatches.length = 0;
            this.geoBatches = null;
            this.batches.length = 0;
            this.batches = null;
        };
        Object.defineProperty(Graphics.prototype, "width", {
            get: function () {
                this.updateLocalBoundsSelf();
                return Math.abs(this.scale.x) * this._localBoundsSelf.width;
            },
            set: function (value) {
                this.updateLocalBoundsSelf();
                var width = this._localBoundsSelf.width;
                if (width !== 0) {
                    var s = sign(this.scale.x) || 1;
                    this.scale.x = s * value / width;
                }
                else {
                    this.scale.x = 1;
                }
                this._width = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Graphics.prototype, "height", {
            get: function () {
                this.updateLocalBoundsSelf();
                return Math.abs(this.scale.y) * this._localBoundsSelf.height;
            },
            set: function (value) {
                this.updateLocalBoundsSelf();
                var height = this._localBoundsSelf.height;
                if (height !== 0) {
                    var s = sign(this.scale.y) || 1;
                    this.scale.y = s * value / height;
                }
                else {
                    this.scale.y = 1;
                }
                this._height = value;
            },
            enumerable: true,
            configurable: true
        });
        Graphics.prototype.proccessHoles = function (holes) {
            for (var i = 0; i < holes.length; i++) {
                var hole = holes[i];
                var command = fillCommands[hole.type];
                command.build(hole);
                if (hole.matrix)
                    this.transformPoints(hole.points, hole.matrix);
            }
        };
        Graphics.prototype.addUvs = function (verts, uvs, texture, start, size, matrix) {
            var index = 0;
            var uvsStart = uvs.length;
            var frame = texture.frame;
            while (index < size) {
                var x = verts[(start + index) * 2];
                var y = verts[((start + index) * 2) + 1];
                if (matrix) {
                    var nx = (matrix.a * x) + (matrix.c * y) + matrix.tx;
                    y = (matrix.b * x) + (matrix.d * y) + matrix.ty;
                    x = nx;
                }
                index++;
                var frame_1 = texture.frame;
                uvs.push(x / frame_1.width, y / frame_1.height);
            }
            var baseTexture = texture.baseTexture;
            if (frame.width < baseTexture.width
                || frame.height < baseTexture.height) {
                this.adjustUvs(uvs, texture, uvsStart, size);
            }
        };
        Graphics.prototype.adjustUvs = function (uvs, texture, start, size) {
            var baseTexture = texture.baseTexture;
            var eps = 1e-6;
            var finish = start + (size * 2);
            var frame = texture.frame;
            var scaleX = frame.width / baseTexture.width;
            var scaleY = frame.height / baseTexture.height;
            var offsetX = frame.x / frame.width;
            var offsetY = frame.y / frame.height;
            var minX = Math.floor(uvs[start] + eps);
            var minY = Math.floor(uvs[start + 1] + eps);
            for (var i = start + 2; i < finish; i += 2) {
                minX = Math.min(minX, Math.floor(uvs[i] + eps));
                minY = Math.min(minY, Math.floor(uvs[i + 1] + eps));
            }
            offsetX -= minX;
            offsetY -= minY;
            for (var i = start; i < finish; i += 2) {
                uvs[i] = (uvs[i] + offsetX) * scaleX;
                uvs[i + 1] = (uvs[i + 1] + offsetY) * scaleY;
            }
        };
        return Graphics;
    }(Container));
    var geoBatchPart = (function () {
        function geoBatchPart() {
            this.style = null;
            this.size = 0;
            this.start = 0;
            this.attribStart = 0;
            this.attribSize = 0;
        }
        return geoBatchPart;
    }());

    var tempPoint$1 = new Point();
    var tempPolygon = new Polygon();
    var Mesh = (function (_super) {
        tslib_1.__extends(Mesh, _super);
        function Mesh(texture, vertices, uvs, indices) {
            var _this = _super.call(this) || this;
            _this._blendMode = exports.BLEND_MODES.NORMAL;
            _this._texture = texture || Texture.EMPTY;
            _this._uvs = uvs || new Float32Array([
                0, 0,
                1, 0,
                1, 1,
                0, 1
            ]);
            _this._vertices = vertices || new Float32Array([
                0, 0,
                100, 0,
                100, 100,
                0, 100
            ]);
            _this._indices = indices || new Uint16Array([0, 1, 3, 2]);
            _this._vertexDirty = 0;
            _this._vertexId = -1;
            _this._localBoundsSelfId = -1;
            _this.blendMode = exports.BLEND_MODES.NORMAL;
            _this.canvasPadding = 0;
            _this._tint = null;
            _this._tintRGB = null;
            _this.tint = 0xFFFFFF;
            _this._uvTransform = new TextureMatrix(_this._texture);
            _this._needRefresh = true;
            return _this;
        }
        Object.defineProperty(Mesh.prototype, "blendMode", {
            get: function () {
                return this._blendMode;
            },
            set: function (value) {
            },
            enumerable: true,
            configurable: true
        });
        Mesh.prototype._renderWebGL = function (renderer) {
            this.refresh();
            this.calculateVertices();
            renderer.batchManager.setObjectRenderer(renderer.plugins["batch"]);
            renderer.plugins["batch"].render(this);
        };
        Mesh.prototype._renderCanvas = function (renderer) {
            this.refresh();
            renderer.plugins["mesh"].render(this);
        };
        Mesh.prototype._onTextureUpdate = function () {
            this._uvTransform.texture = this._texture;
            this._needRefresh = true;
        };
        Mesh.prototype.multiplyUvs = function () {
            this._uvTransform.multiplyUvs(this._uvs);
        };
        Mesh.prototype.refresh = function (forceUpdate) {
            if (forceUpdate === void 0) { forceUpdate = false; }
            if (!this._texture || !this._texture.valid)
                return;
            if (this._uvTransform.update(forceUpdate) ||
                this._needRefresh ||
                forceUpdate) {
                this._refresh();
            }
        };
        Mesh.prototype._refresh = function () {
        };
        Mesh.prototype.calculateVertices = function () {
            if (this._vertexId === this._vertexDirty && this._transformID === this.transform._worldID)
                return;
            this._vertexId = this._vertexDirty;
            this._transformID = this.transform._worldID;
            if (this._vertices.length <= 2)
                return;
            if (!this._vertexData)
                this._vertexData = new Float32Array(this._vertices.length);
            var wt = this.transform.worldMatrix;
            var a = wt.a;
            var b = wt.b;
            var c = wt.c;
            var d = wt.d;
            var tx = wt.tx;
            var ty = wt.ty;
            var vertexData = this._vertexData;
            for (var i = 0; i < vertexData.length / 2; i++) {
                var x = this._vertices[(i * 2)];
                var y = this._vertices[(i * 2) + 1];
                vertexData[(i * 2)] = (a * x) + (c * y) + tx;
                vertexData[(i * 2) + 1] = (b * x) + (d * y) + ty;
            }
        };
        Mesh.prototype._calculateBounds = function () {
            this.updateLocalBoundsSelf();
            var rect = this._localBoundsSelf;
            var matrix = this.transform.worldMatrix;
            matrix.transformPoint(rect.x, rect.y, DisplayObject._p1);
            matrix.transformPoint(rect.x + rect.width, rect.y, DisplayObject._p2);
            matrix.transformPoint(rect.x + rect.width, rect.y + rect.height, DisplayObject._p3);
            matrix.transformPoint(rect.x, rect.y + rect.height, DisplayObject._p4);
            Rectangle.createFromPoints(this._bounds, DisplayObject._p1, DisplayObject._p2, DisplayObject._p3, DisplayObject._p4);
        };
        Mesh.prototype.updateLocalBoundsSelf = function () {
            if (this._localBoundsSelfId == this._vertexDirty)
                return;
            this._localBoundsSelfId = this._vertexDirty;
            if (this._vertices.length <= 2)
                this._localBoundsSelf.clear();
            Rectangle.createFromVertexData(this._localBoundsSelf, this._vertices);
        };
        Mesh.prototype.hitTestPoint = function (point, isMouseEvent) {
            if (isMouseEvent === void 0) { isMouseEvent = false; }
            if (!this.visible)
                return null;
            var hitDisplayObject;
            hitDisplayObject = _super.prototype.hitTestPoint.call(this, point, isMouseEvent);
            if (hitDisplayObject)
                return hitDisplayObject;
            if (isMouseEvent && !this.mouseEnable)
                return null;
            this.updateLocalBoundsSelf();
            hitDisplayObject = this.displayObjectHitTestPoint(point, isMouseEvent);
            if (hitDisplayObject)
                return this.hitTestPointAccuratly(point, isMouseEvent);
            return null;
        };
        Mesh.prototype.hitTestPointAccuratly = function (point, isMouseEvent) {
            if (isMouseEvent) {
                this.globalToLocal(point, tempPoint$1);
            }
            else {
                tempPoint$1.set(point.x, point.y);
            }
            var vertices = this._vertices;
            var points = tempPolygon.points;
            var indices = this._indices;
            var len = this._indices.length;
            for (var i = 0; i + 2 < len; i += 3) {
                var ind0 = indices[i] * 2;
                var ind1 = indices[i + 1] * 2;
                var ind2 = indices[i + 2] * 2;
                points[0] = vertices[ind0];
                points[1] = vertices[ind0 + 1];
                points[2] = vertices[ind1];
                points[3] = vertices[ind1 + 1];
                points[4] = vertices[ind2];
                points[5] = vertices[ind2 + 1];
                if (tempPolygon.isPointIn(tempPoint$1))
                    return this;
            }
            return null;
        };
        Object.defineProperty(Mesh.prototype, "texture", {
            get: function () {
                return this._texture;
            },
            set: function (value) {
                if (this._texture === value)
                    return;
                this._texture = value;
                if (value) {
                    if (value.baseTexture.hasLoaded) {
                        this._onTextureUpdate();
                    }
                    else {
                        value.once('update', this._onTextureUpdate, this);
                    }
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Mesh.prototype, "tint", {
            get: function () {
                return this._tint;
            },
            set: function (value) {
                if (value === this._tint)
                    return;
                this._tint = value;
                this._tintRGB = (value >> 16) + (value & 0xff00) + ((value & 0xff) << 16);
            },
            enumerable: true,
            configurable: true
        });
        Mesh.prototype.destroy = function () {
            _super.prototype.destroy.call(this);
            this._texture.removeEventListener('update', this._onTextureUpdate, this);
            this._uvs = null;
            this._vertices = null;
            this._indices = null;
            this._vertexData = null;
        };
        return Mesh;
    }(Container));

    var Plane = (function (_super) {
        tslib_1.__extends(Plane, _super);
        function Plane(texture, verticesX, verticesY) {
            if (verticesX === void 0) { verticesX = 10; }
            if (verticesY === void 0) { verticesY = 10; }
            var _this = _super.call(this, texture) || this;
            _this.verticesX = verticesX || 10;
            _this.verticesY = verticesY || 10;
            _this.refresh();
            return _this;
        }
        Plane.prototype._refresh = function () {
            var texture = this.texture;
            var total = this.verticesX * this.verticesY;
            var verts = [];
            var uvs = [];
            var segmentsX = this.verticesX - 1;
            var segmentsY = this.verticesY - 1;
            var sizeX = texture.width / segmentsX;
            var sizeY = texture.height / segmentsY;
            for (var i = 0; i < total; i++) {
                var x = (i % this.verticesX);
                var y = ((i / this.verticesX) | 0);
                verts.push(x * sizeX, y * sizeY);
                uvs.push(x / segmentsX, y / segmentsY);
            }
            this._vertices = new Float32Array(verts);
            this._uvs = new Float32Array(uvs);
            this._indices = calculatePlaneIndices(this.verticesX, this.verticesY);
            this._vertexDirty++;
            this.multiplyUvs();
        };
        return Plane;
    }(Mesh));
    function calculatePlaneIndices(verticesX, verticesY) {
        var segmentsX = verticesX - 1;
        var segmentsY = verticesY - 1;
        var totalSub = segmentsX * segmentsY;
        var indices = [];
        for (var i = 0; i < totalSub; i++) {
            var xpos = i % segmentsX;
            var ypos = (i / segmentsX) | 0;
            var value = (ypos * verticesX) + xpos;
            var value2 = (ypos * verticesX) + xpos + 1;
            var value3 = ((ypos + 1) * verticesX) + xpos;
            var value4 = ((ypos + 1) * verticesX) + xpos + 1;
            indices.push(value, value2, value3);
            indices.push(value2, value4, value3);
        }
        return new Uint16Array(indices);
    }

    var indicesNN = calculatePlaneIndices(4, 4);
    var NineSlicePlane = (function (_super) {
        tslib_1.__extends(NineSlicePlane, _super);
        function NineSlicePlane(texture, leftWidth, topHeight, rightWidth, bottomHeight) {
            if (leftWidth === void 0) { leftWidth = 10; }
            if (topHeight === void 0) { topHeight = 10; }
            if (rightWidth === void 0) { rightWidth = 10; }
            if (bottomHeight === void 0) { bottomHeight = 10; }
            var _this = _super.call(this, texture) || this;
            _this._origWidth = texture.orig.width;
            _this._origHeight = texture.orig.height;
            _this._width = _this._origWidth;
            _this._height = _this._origHeight;
            _this._leftWidth = leftWidth;
            _this._rightWidth = rightWidth;
            _this._topHeight = topHeight;
            _this._bottomHeight = bottomHeight;
            _this._indices = indicesNN;
            _this._vertices = new Float32Array(4 * 4 * 2);
            _this._uvs = new Float32Array(4 * 4 * 2);
            _this.refresh(true);
            return _this;
        }
        NineSlicePlane.prototype.updateHorizontalVertices = function () {
            var vertices = this._vertices;
            var h = this._topHeight + this._bottomHeight;
            var scale = this._height > h ? 1.0 : this._height / h;
            vertices[9] = vertices[11] = vertices[13] = vertices[15] = this._topHeight * scale;
            vertices[17] = vertices[19] = vertices[21] = vertices[23] = this._height - (this._bottomHeight * scale);
            vertices[25] = vertices[27] = vertices[29] = vertices[31] = this._height;
        };
        NineSlicePlane.prototype.updateVerticalVertices = function () {
            var vertices = this._vertices;
            var w = this._leftWidth + this._rightWidth;
            var scale = this._width > w ? 1.0 : this._width / w;
            vertices[2] = vertices[10] = vertices[18] = vertices[26] = this._leftWidth * scale;
            vertices[4] = vertices[12] = vertices[20] = vertices[28] = this._width - (this._rightWidth * scale);
            vertices[6] = vertices[14] = vertices[22] = vertices[30] = this._width;
        };
        NineSlicePlane.prototype._renderCanvas = function (renderer) {
            var context = renderer.context;
            context.globalAlpha = this._worldAlpha;
            renderer.setBlendMode(this.blendMode);
            var transform = this.worldMatrix;
            context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx, transform.ty);
            var base = this.texture.baseTexture;
            var textureSource = base.source;
            var w = base.width;
            var h = base.height;
            this.drawSegment(context, textureSource, w, h, 0, 1, 10, 11);
            this.drawSegment(context, textureSource, w, h, 2, 3, 12, 13);
            this.drawSegment(context, textureSource, w, h, 4, 5, 14, 15);
            this.drawSegment(context, textureSource, w, h, 8, 9, 18, 19);
            this.drawSegment(context, textureSource, w, h, 10, 11, 20, 21);
            this.drawSegment(context, textureSource, w, h, 12, 13, 22, 23);
            this.drawSegment(context, textureSource, w, h, 16, 17, 26, 27);
            this.drawSegment(context, textureSource, w, h, 18, 19, 28, 29);
            this.drawSegment(context, textureSource, w, h, 20, 21, 30, 31);
        };
        NineSlicePlane.prototype.drawSegment = function (context, textureSource, w, h, x1, y1, x2, y2) {
            var uvs = this._uvs;
            var vertices = this._vertices;
            var sw = (uvs[x2] - uvs[x1]) * w;
            var sh = (uvs[y2] - uvs[y1]) * h;
            var dw = vertices[x2] - vertices[x1];
            var dh = vertices[y2] - vertices[y1];
            if (sw < 1) {
                sw = 1;
            }
            if (sh < 1) {
                sh = 1;
            }
            if (dw < 1) {
                dw = 1;
            }
            if (dh < 1) {
                dh = 1;
            }
            context.drawImage(textureSource, uvs[x1] * w, uvs[y1] * h, sw, sh, vertices[x1], vertices[y1], dw, dh);
        };
        Object.defineProperty(NineSlicePlane.prototype, "width", {
            get: function () {
                return this._width;
            },
            set: function (value) {
                this._width = value;
                this._needRefresh = true;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(NineSlicePlane.prototype, "height", {
            get: function () {
                return this._height;
            },
            set: function (value) {
                this._height = value;
                this._needRefresh = true;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(NineSlicePlane.prototype, "leftWidth", {
            get: function () {
                return this._leftWidth;
            },
            set: function (value) {
                this._leftWidth = value;
                this._needRefresh = true;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(NineSlicePlane.prototype, "rightWidth", {
            get: function () {
                return this._rightWidth;
            },
            set: function (value) {
                this._rightWidth = value;
                this._needRefresh = true;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(NineSlicePlane.prototype, "topHeight", {
            get: function () {
                return this._topHeight;
            },
            set: function (value) {
                this._topHeight = value;
                this._needRefresh = true;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(NineSlicePlane.prototype, "bottomHeight", {
            get: function () {
                return this._bottomHeight;
            },
            set: function (value) {
                this._bottomHeight = value;
                this._needRefresh = true;
            },
            enumerable: true,
            configurable: true
        });
        NineSlicePlane.prototype._refresh = function () {
            var uvs = this._uvs;
            var texture = this.texture;
            this._origWidth = texture.orig.width;
            this._origHeight = texture.orig.height;
            var _uvw = 1.0 / this._origWidth;
            var _uvh = 1.0 / this._origHeight;
            uvs[0] = uvs[8] = uvs[16] = uvs[24] = 0;
            uvs[1] = uvs[3] = uvs[5] = uvs[7] = 0;
            uvs[6] = uvs[14] = uvs[22] = uvs[30] = 1;
            uvs[25] = uvs[27] = uvs[29] = uvs[31] = 1;
            uvs[2] = uvs[10] = uvs[18] = uvs[26] = _uvw * this._leftWidth;
            uvs[4] = uvs[12] = uvs[20] = uvs[28] = 1 - (_uvw * this._rightWidth);
            uvs[9] = uvs[11] = uvs[13] = uvs[15] = _uvh * this._topHeight;
            uvs[17] = uvs[19] = uvs[21] = uvs[23] = 1 - (_uvh * this._bottomHeight);
            this.updateHorizontalVertices();
            this.updateVerticalVertices();
            this._vertexDirty++;
            this.multiplyUvs();
        };
        return NineSlicePlane;
    }(Mesh));

    var padding$1 = 10;
    var TextField = (function (_super) {
        tslib_1.__extends(TextField, _super);
        function TextField() {
            var _this = _super.call(this) || this;
            _this._textAlpha = 1;
            _this._textAlign = exports.TEXT_ALIGN.LEFT;
            _this._verticalAlign = exports.VERTICAL_ALIGN.UP;
            _this._textWidth = 0;
            _this._textHeight = 0;
            _this._lineSpacing = 14;
            _this._lineType = exports.TEXT_lINETYPE.SINGLE;
            _this._text = "";
            _this._font = "Arial";
            _this._size = 12;
            _this._fillColor = "#ffffff";
            _this._strokeColor = "#ffffff";
            _this._stroke = 0;
            _this._italic = false;
            _this._bold = false;
            _this._border = false;
            _this.realLines = [];
            _this._instanceType = "TextField";
            var canvas = createCanvas();
            canvas.width = canvas.height = 3;
            _this.texture = Texture.fromCanvas(canvas, "textCanvas");
            _this.canvas = canvas;
            _this.context = canvas.getContext("2d");
            Texture.addToCache(_this.texture, _this.texture.baseTexture.textureCacheIds[0]);
            _this.dirty = true;
            return _this;
        }
        Object.defineProperty(TextField.prototype, "textAlpha", {
            get: function () {
                return this._textAlpha;
            },
            set: function (value) {
                if (this._textAlpha != value) {
                    this._textAlpha = value;
                    this.dirty = true;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(TextField.prototype, "textAlign", {
            get: function () {
                return this._textAlign;
            },
            set: function (value) {
                if (this._textAlign != value) {
                    this._textAlign = value;
                    this.dirty = true;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(TextField.prototype, "verticalAlign", {
            get: function () {
                return this._verticalAlign;
            },
            set: function (value) {
                if (this._verticalAlign != value) {
                    this._verticalAlign = value;
                    this.dirty = true;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(TextField.prototype, "textWidth", {
            get: function () {
                if (this._textWidth) {
                    return this._textWidth;
                }
                else {
                    this.updateText();
                    return this.width - padding$1 * 2;
                }
            },
            set: function (value) {
                if (this._textWidth != value) {
                    this._textWidth = value;
                    this.dirty = true;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(TextField.prototype, "textHeight", {
            get: function () {
                if (this._textHeight) {
                    return this._textHeight;
                }
                else {
                    this.updateText();
                    return this.height - padding$1 * 2;
                }
            },
            set: function (value) {
                if (this._textHeight != value) {
                    this._textHeight = value;
                    this.dirty = true;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(TextField.prototype, "lineSpacing", {
            get: function () {
                return this._lineSpacing;
            },
            set: function (value) {
                if (this._lineSpacing != value) {
                    this._lineSpacing = value;
                    this.dirty = true;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(TextField.prototype, "lineType", {
            get: function () {
                return this._lineType;
            },
            set: function (value) {
                if (this._lineType != value) {
                    this._lineType = value;
                    this.dirty = true;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(TextField.prototype, "text", {
            get: function () {
                return this._text;
            },
            set: function (value) {
                if (this._text != value) {
                    this._text = value;
                    this.dirty = true;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(TextField.prototype, "font", {
            get: function () {
                return this._font;
            },
            set: function (value) {
                if (this._font != value) {
                    this._font = value;
                    this.dirty = true;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(TextField.prototype, "size", {
            get: function () {
                return this._size;
            },
            set: function (value) {
                if (this._size != value) {
                    this._size = value;
                    this.dirty = true;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(TextField.prototype, "fillColor", {
            get: function () {
                return this._fillColor;
            },
            set: function (value) {
                if (this._fillColor != value) {
                    this._fillColor = value;
                    this.dirty = true;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(TextField.prototype, "strokeColor", {
            get: function () {
                return this._strokeColor;
            },
            set: function (value) {
                if (this._strokeColor != value) {
                    this._strokeColor = value;
                    this.dirty = true;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(TextField.prototype, "stroke", {
            get: function () {
                return this._stroke;
            },
            set: function (value) {
                if (this._stroke != value) {
                    this._stroke = value;
                    this.dirty = true;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(TextField.prototype, "italic", {
            get: function () {
                return this._italic;
            },
            set: function (value) {
                if (this._italic != value) {
                    this._italic = value;
                    this.dirty = true;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(TextField.prototype, "bold", {
            get: function () {
                return this._bold;
            },
            set: function (value) {
                if (this._bold != value) {
                    this._bold = value;
                    this.dirty = true;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(TextField.prototype, "border", {
            get: function () {
                return this._border;
            },
            set: function (value) {
                if (this._border != value) {
                    this._border = value;
                    this.dirty = true;
                }
            },
            enumerable: true,
            configurable: true
        });
        TextField.prototype._prepContext = function (ctx) {
            var s = this;
            var font = s.size || 12;
            font += "px ";
            font += s.font;
            if (s._bold) {
                font = "bold " + font;
            }
            if (s._italic) {
                font = "italic " + font;
            }
            ctx.font = font;
            ctx.textAlign = s._textAlign || exports.TEXT_ALIGN.LEFT;
            ctx.textBaseline = "top";
            ctx.fillStyle = getRGBA(s._fillColor, s._textAlpha);
        };
        TextField.prototype.getTextWidth = function (lineIndex) {
            if (lineIndex === void 0) { lineIndex = 0; }
            var s = this;
            s.updateText();
            var ctx = s.context;
            var obj = ctx.measureText(s.realLines[lineIndex]);
            return obj.width;
        };
        Object.defineProperty(TextField.prototype, "lines", {
            get: function () {
                return this.realLines.length;
            },
            enumerable: true,
            configurable: true
        });
        TextField.prototype._getMeasuredWidth = function (text) {
            var ctx = this.context;
            var patternCh = new RegExp("[\u4E00-\u9FA5]+");
            var patternChB = /[\u3002|\uff1f|\uff01|\uff0c|\u3001|\uff1b|\uff1a|\u201c|\u201d|\u2018|\u2019|\uff08|\uff09|\u300a|\u300b|\u3008|\u3009|\u3010|\u3011|\u300e|\u300f|\u300c|\u300d|\ufe43|\ufe44|\u3014|\u3015|\u2026|\u2014|\uff5e|\ufe4f|\uffe5]/;
            var size = this.size;
            var width = 0;
            for (var i = 0; i < text.length; i++) {
                var str = text[i];
                if (patternCh.test(str) || patternChB.test(str)) {
                    width += size;
                }
                else {
                    width += size / 2;
                }
            }
            return width;
        };
        TextField.prototype.updateText = function () {
            var s = this;
            if (!s.dirty) {
                return;
            }
            s.dirty = false;
            if (!s._text) {
                s.canvas.width = 0;
                s.canvas.height = 0;
                s._localBoundsSelf.clear();
                s.anchorTexture = { x: 0, y: 0 };
                s.texture.update();
                return;
            }
            s._text += "";
            var can = s.canvas;
            var ctx = s.context;
            var hardLines = s._text.toString().split(/(?:\r\n|\r|\n)/);
            var realLines = [];
            s.realLines = realLines;
            s._prepContext(ctx);
            var textWidth = s._textWidth;
            if (s._text.indexOf("\n") < 0 && s.lineType == exports.TEXT_lINETYPE.SINGLE) {
                realLines[realLines.length] = hardLines[0];
                var str = hardLines[0];
                var lineW = s._getMeasuredWidth(str);
                textWidth = textWidth || lineW;
                if (lineW > textWidth) {
                    var w = s._getMeasuredWidth(str[0]);
                    var lineStr = str[0];
                    var wordW = 0;
                    var strLen = str.length;
                    for (var j = 1; j < strLen; j++) {
                        wordW = s._getMeasuredWidth(str[j]);
                        w += wordW;
                        if (w > textWidth) {
                            realLines[0] = lineStr;
                            break;
                        }
                        else {
                            lineStr += str[j];
                        }
                    }
                }
            }
            else {
                if (!textWidth) {
                    for (var i = 0, l = hardLines.length; i < l; i++) {
                        var str = hardLines[i];
                        if (!str)
                            continue;
                        textWidth = Math.max(s._getMeasuredWidth(str), textWidth);
                    }
                }
                for (var i = 0, l = hardLines.length; i < l; i++) {
                    var str = hardLines[i];
                    if (!str)
                        continue;
                    var w = s._getMeasuredWidth(str[0]);
                    var lineStr = str[0];
                    var wordW = 0;
                    var strLen = str.length;
                    for (var j = 1; j < strLen; j++) {
                        wordW = s._getMeasuredWidth(str[j]);
                        w += wordW;
                        if (w > textWidth) {
                            realLines[realLines.length] = lineStr;
                            lineStr = str[j];
                            w = wordW;
                        }
                        else {
                            lineStr += str[j];
                        }
                    }
                    realLines[realLines.length] = lineStr;
                }
            }
            var trueHeight = s.size * realLines.length + s._lineSpacing * (realLines.length - 1);
            var maxH = s._textHeight || trueHeight;
            var maxW = textWidth;
            var tx = 0;
            if (s._textAlign == exports.TEXT_ALIGN.CENTER) {
                tx = maxW * 0.5;
            }
            else if (s._textAlign == exports.TEXT_ALIGN.RIGHT) {
                tx = maxW;
            }
            var canWidth = maxW + padding$1 * 2;
            var canHeight = maxH + padding$1 * 2;
            can.width = canWidth;
            can.height = canHeight;
            ctx.setTransform(1, 0, 0, 1, 0, 0);
            ctx.clearRect(0, 0, can.width, can.height);
            if (s.border) {
                ctx.beginPath();
                ctx.strokeStyle = "#000";
                ctx.lineWidth = 1;
                ctx.strokeRect(padding$1 + 0.5, padding$1 + 0.5, maxW, maxH);
                ctx.closePath();
            }
            ctx.setTransform(1, 0, 0, 1, tx + padding$1, padding$1);
            s._prepContext(ctx);
            var lineH = s._lineSpacing + s.size;
            var upY = 0;
            if (s._textHeight) {
                if (s._verticalAlign == exports.VERTICAL_ALIGN.MIDDLE) {
                    upY = (s._textHeight - trueHeight) * 0.5;
                }
                else if (s._verticalAlign == exports.VERTICAL_ALIGN.DOWN) {
                    upY = s._textHeight - trueHeight;
                }
            }
            for (var i = 0; i < realLines.length; i++) {
                var ox = 0;
                if (s.stroke) {
                    ctx.strokeStyle = s.strokeColor;
                    ctx.lineWidth = s.stroke * 2;
                    ctx.strokeText(realLines[i], ox, upY + i * lineH, maxW);
                }
                ctx.fillText(realLines[i], ox, upY + i * lineH, maxW);
            }
            s.offsetX = -padding$1;
            s.offsetY = -padding$1;
            this.anchorTexture = { x: (padding$1 + 0.5) / canWidth, y: padding$1 / canHeight };
            s.texture.update();
            s._onTextureUpdate();
        };
        TextField.prototype._renderCanvas = function (renderer) {
            this.updateText();
            _super.prototype._renderCanvas.call(this, renderer);
        };
        TextField.prototype._renderWebGL = function (renderer) {
            this.updateText();
            _super.prototype._renderWebGL.call(this, renderer);
        };
        TextField.prototype.destroy = function () {
            this.canvas = null;
            this.context = null;
            _super.prototype.destroy.call(this);
        };
        return TextField;
    }(Sprite));

    var bitmapTextSinglePool = [];
    var BitmapText = (function (_super) {
        tslib_1.__extends(BitmapText, _super);
        function BitmapText(textures) {
            var _this = _super.call(this) || this;
            _this.textAlign = exports.TEXT_ALIGN.CENTER;
            _this.textures = textures;
            return _this;
        }
        Object.defineProperty(BitmapText.prototype, "text", {
            get: function () {
                return this._text;
            },
            set: function (value) {
                if (value === this._text)
                    return;
                this._text = value;
                var arr = value || [];
                for (var i = 0; i < arr.length; i++) {
                    if (this.children[i]) {
                        this.children[i]["text"] = arr[i];
                    }
                    else {
                        var o = bitmapTextSinglePool.shift();
                        if (!o) {
                            o = new BitmapTextSingle(this.textures);
                        }
                        else {
                            o.reset(this.textures);
                        }
                        o.text = arr[i];
                        this.addChild(o);
                    }
                }
                if (this.children.length > arr.length) {
                    for (var i = this.children.length - 1; i >= arr.length; i--) {
                        var c = this.children[i];
                        this.removeChild(c);
                        bitmapTextSinglePool.push(c);
                    }
                }
                this.adaptate();
            },
            enumerable: true,
            configurable: true
        });
        BitmapText.prototype.adaptate = function () {
            if (!this.children.length)
                return;
            var len = this.children.length;
            var sum = 0;
            for (var m = 0; m < len; m++) {
                sum += this.children[m].width;
            }
            var left = -sum / 2;
            if (this.textAlign == exports.TEXT_ALIGN.LEFT) {
                left = 0;
            }
            else if (this.textAlign == exports.TEXT_ALIGN.RIGHT) {
                left = sum;
            }
            var temSum = 0;
            for (var i = 0; i < this.children.length; i++) {
                this.children[i].x = left + temSum;
                temSum += this.children[i].width;
            }
        };
        return BitmapText;
    }(Container));
    var BitmapTextSingle = (function (_super) {
        tslib_1.__extends(BitmapTextSingle, _super);
        function BitmapTextSingle(textures) {
            var _this = _super.call(this) || this;
            _this.textures = textures;
            return _this;
        }
        Object.defineProperty(BitmapTextSingle.prototype, "text", {
            get: function () {
                return this._text;
            },
            set: function (value) {
                if (value == this._text)
                    return;
                this._text = value;
                this.texture = this.textures[this._text];
            },
            enumerable: true,
            configurable: true
        });
        BitmapTextSingle.prototype.reset = function (textures) {
            this.textures = textures;
        };
        return BitmapTextSingle;
    }(Sprite));

    function createTextureSheet(baseTexture, altaData) {
        var frames = altaData;
        var frameKeys = Object.keys(frames);
        var frameIndex = 0;
        var textures = {};
        while (frameIndex < frameKeys.length) {
            var i = frameKeys[frameIndex];
            var data = frames[i];
            var frame = null;
            var trim = null;
            var orig = new Rectangle(0, 0, Math.floor(data.sw), Math.floor(data.sh));
            if (data.ro) {
                frame = new Rectangle(Math.floor(data.x), Math.floor(data.y), Math.floor(data.h), Math.floor(data.w));
            }
            else {
                frame = new Rectangle(Math.floor(data.x), Math.floor(data.y), Math.floor(data.w), Math.floor(data.h));
            }
            if (data.ox || data.oy) {
                trim = new Rectangle(Math.floor(data.ox), Math.floor(data.oy), Math.floor(data.w), Math.floor(data.h));
            }
            var texture = new Texture(baseTexture, frame, orig, trim, data.ro ? 2 : 0);
            Texture.addToCache(texture, i);
            textures[i] = texture;
            frameIndex++;
        }
        return textures;
    }

    var Tween = (function () {
        function Tween(target, props, pluginData) {
            this._target = null;
            this._useTicks = false;
            this.ignoreGlobalPause = false;
            this.loop = false;
            this.pluginData = null;
            this._steps = null;
            this.paused = false;
            this.duration = 0;
            this._prevPos = -1;
            this.position = null;
            this._prevPosition = 0;
            this._stepPosition = 0;
            this.passive = false;
            this.initialize(target, props, pluginData);
        }
        Tween.get = function (target, props, pluginData, override) {
            if (pluginData === void 0) { pluginData = null; }
            if (override === void 0) { override = false; }
            if (override) {
                Tween.removeTweens(target);
            }
            return new Tween(target, props, pluginData);
        };
        Tween.removeTweens = function (target) {
            if (!target.tween_count) {
                return;
            }
            var tweens = Tween._tweens;
            for (var i = tweens.length - 1; i >= 0; i--) {
                if (tweens[i]._target == target) {
                    tweens[i].paused = true;
                    tweens.splice(i, 1);
                }
            }
            target.tween_count = 0;
        };
        Tween.pauseTweens = function (target) {
            if (!target.tween_count) {
                return;
            }
            var tweens = Tween._tweens;
            for (var i = tweens.length - 1; i >= 0; i--) {
                if (tweens[i]._target == target) {
                    tweens[i].paused = true;
                }
            }
        };
        Tween.resumeTweens = function (target) {
            if (!target.tween_count) {
                return;
            }
            var tweens = Tween._tweens;
            for (var i = tweens.length - 1; i >= 0; i--) {
                if (tweens[i]._target == target) {
                    tweens[i].paused = false;
                }
            }
        };
        Tween.tick = function (timeStamp, paused) {
            if (paused === void 0) { paused = false; }
            var delta = timeStamp - Tween._lastTime;
            Tween._lastTime = timeStamp;
            var tweens = Tween._tweens.concat();
            for (var i = tweens.length - 1; i >= 0; i--) {
                var tween = tweens[i];
                if ((paused && !tween.ignoreGlobalPause) || tween.paused) {
                    continue;
                }
                tween.$tick(tween._useTicks ? 1 : delta);
            }
            return false;
        };
        Tween.flush = function () {
            var timeStamp = Date.now();
            var delta = Tween._lastTime ? (timeStamp - Tween._lastTime) : 16.67;
            Tween._lastTime = timeStamp;
            var tweens = Tween._tweens.concat();
            for (var i = tweens.length - 1; i >= 0; i--) {
                var tween = tweens[i];
                if (tween.paused) {
                    continue;
                }
                tween.$tick(tween._useTicks ? 1 : delta);
            }
        };
        Tween._register = function (tween, value) {
            var target = tween._target;
            var tweens = Tween._tweens;
            if (value) {
                if (target) {
                    target.tween_count = target.tween_count > 0 ? target.tween_count + 1 : 1;
                }
                tweens.push(tween);
                if (!Tween._inited) {
                    Tween._inited = true;
                }
            }
            else {
                if (target) {
                    target.tween_count--;
                }
                var i = tweens.length;
                while (i--) {
                    if (tweens[i] == tween) {
                        tweens.splice(i, 1);
                        return;
                    }
                }
            }
        };
        Tween.removeAllTweens = function () {
            var tweens = Tween._tweens;
            for (var i = 0, l = tweens.length; i < l; i++) {
                var tween = tweens[i];
                tween.paused = true;
                tween._target.tween_count = 0;
            }
            tweens.length = 0;
        };
        Tween.prototype.initialize = function (target, props, pluginData) {
            this._target = target;
            if (props) {
                this._useTicks = props.useTicks;
                this.ignoreGlobalPause = props.ignoreGlobalPause;
                this.loop = props.loop;
                if (props.onChange) {
                    this.onChange = props.onChange.bind(props.onChangeObj);
                }
                else {
                    this.onChange = null;
                }
                if (props.override) {
                    Tween.removeTweens(target);
                }
            }
            this.pluginData = pluginData || {};
            this._curQueueProps = {};
            this._initQueueProps = {};
            this._steps = [];
            if (props && props.paused) {
                this.paused = true;
            }
            else {
                Tween._register(this, true);
            }
            if (props && props.position != null) {
                this.setPosition(props.position, Tween.NONE);
            }
        };
        Tween.prototype.setPosition = function (value, actionsMode) {
            if (actionsMode === void 0) { actionsMode = 1; }
            if (value < 0) {
                value = 0;
            }
            var t = value;
            var end = false;
            if (t >= this.duration) {
                if (this.loop) {
                    var newTime = t % this.duration;
                    if (t > 0 && newTime === 0) {
                        t = this.duration;
                    }
                    else {
                        t = newTime;
                    }
                }
                else {
                    t = this.duration;
                    end = true;
                }
            }
            if (t == this._prevPos) {
                return end;
            }
            if (end) {
                this.setPaused(true);
            }
            var prevPos = this._prevPos;
            this.position = this._prevPos = t;
            this._prevPosition = value;
            if (this._target) {
                if (this._steps.length > 0) {
                    var l = this._steps.length;
                    var stepIndex = -1;
                    for (var i = 0; i < l; i++) {
                        if (this._steps[i].type == "step") {
                            stepIndex = i;
                            if (this._steps[i].t <= t && this._steps[i].t + this._steps[i].d >= t) {
                                break;
                            }
                        }
                    }
                    for (var i = 0; i < l; i++) {
                        if (this._steps[i].type == "action") {
                            if (actionsMode != 0) {
                                if (this._useTicks) {
                                    this._runAction(this._steps[i], t, t);
                                }
                                else if (actionsMode == 1 && t < prevPos) {
                                    if (prevPos != this.duration) {
                                        this._runAction(this._steps[i], prevPos, this.duration);
                                    }
                                    this._runAction(this._steps[i], 0, t, true);
                                }
                                else {
                                    this._runAction(this._steps[i], prevPos, t);
                                }
                            }
                        }
                        else if (this._steps[i].type == "step") {
                            if (stepIndex == i) {
                                var step = this._steps[stepIndex];
                                this._updateTargetProps(step, Math.min((this._stepPosition = t - step.t) / step.d, 1));
                            }
                        }
                    }
                }
            }
            this.onChange && this.onChange();
            return end;
        };
        Tween.prototype._runAction = function (action, startPos, endPos, includeStart) {
            if (includeStart === void 0) { includeStart = false; }
            var sPos = startPos;
            var ePos = endPos;
            if (startPos > endPos) {
                sPos = endPos;
                ePos = startPos;
            }
            var pos = action.t;
            if (pos == ePos || (pos > sPos && pos < ePos) || (includeStart && pos == startPos)) {
                action.f.apply(action.o, action.p);
            }
        };
        Tween.prototype._updateTargetProps = function (step, ratio) {
            var p0, p1, v, v0, v1, arr;
            if (!step && ratio == 1) {
                this.passive = false;
                p0 = p1 = this._curQueueProps;
            }
            else {
                this.passive = !!step.v;
                if (this.passive) {
                    return;
                }
                if (step.e) {
                    ratio = step.e(ratio, 0, 1, 1);
                }
                p0 = step.p0;
                p1 = step.p1;
            }
            for (var n in this._initQueueProps) {
                if ((v0 = p0[n]) == null) {
                    p0[n] = v0 = this._initQueueProps[n];
                }
                if ((v1 = p1[n]) == null) {
                    p1[n] = v1 = v0;
                }
                if (v0 == v1 || ratio == 0 || ratio == 1 || (typeof (v0) != "number")) {
                    v = ratio == 1 ? v1 : v0;
                }
                else {
                    v = v0 + (v1 - v0) * ratio;
                }
                var ignore = false;
                if (arr = Tween._plugins[n]) {
                    for (var i = 0, l = arr.length; i < l; i++) {
                        var v2 = arr[i].tween(this, n, v, p0, p1, ratio, !!step && p0 == p1, !step);
                        if (v2 == Tween.IGNORE) {
                            ignore = true;
                        }
                        else {
                            v = v2;
                        }
                    }
                }
                if (!ignore) {
                    this._target[n] = v;
                }
            }
        };
        Tween.prototype.setPaused = function (value) {
            if (this.paused == value) {
                return this;
            }
            this.paused = value;
            Tween._register(this, !value);
            return this;
        };
        Tween.prototype._cloneProps = function (props) {
            var o = {};
            for (var n in props) {
                o[n] = props[n];
            }
            return o;
        };
        Tween.prototype._addStep = function (o) {
            if (o.d > 0) {
                o.type = "step";
                this._steps.push(o);
                o.t = this.duration;
                this.duration += o.d;
            }
            return this;
        };
        Tween.prototype._appendQueueProps = function (o) {
            var arr, oldValue, i, l, injectProps;
            for (var n in o) {
                if (this._initQueueProps[n] === undefined) {
                    oldValue = this._target[n];
                    if (arr = Tween._plugins[n]) {
                        for (i = 0, l = arr.length; i < l; i++) {
                            oldValue = arr[i].init(this, n, oldValue);
                        }
                    }
                    this._initQueueProps[n] = this._curQueueProps[n] = (oldValue === undefined) ? null : oldValue;
                }
                else {
                    oldValue = this._curQueueProps[n];
                }
            }
            for (var n in o) {
                oldValue = this._curQueueProps[n];
                if (arr = Tween._plugins[n]) {
                    injectProps = injectProps || {};
                    for (i = 0, l = arr.length; i < l; i++) {
                        if (arr[i].step) {
                            arr[i].step(this, n, oldValue, o[n], injectProps);
                        }
                    }
                }
                this._curQueueProps[n] = o[n];
            }
            if (injectProps) {
                this._appendQueueProps(injectProps);
            }
            return this._curQueueProps;
        };
        Tween.prototype._addAction = function (o) {
            o.t = this.duration;
            o.type = "action";
            this._steps.push(o);
            return this;
        };
        Tween.prototype._set = function (props, o) {
            for (var n in props) {
                o[n] = props[n];
            }
        };
        Tween.prototype.wait = function (duration, passive) {
            if (duration == null || duration <= 0) {
                return this;
            }
            var o = this._cloneProps(this._curQueueProps);
            return this._addStep({ d: duration, p0: o, p1: o, v: passive });
        };
        Tween.prototype.to = function (props, duration, ease) {
            if (ease === void 0) { ease = undefined; }
            if (isNaN(duration) || duration < 0) {
                duration = 0;
            }
            this._addStep({ d: duration || 0, p0: this._cloneProps(this._curQueueProps), e: ease, p1: this._cloneProps(this._appendQueueProps(props)) });
            return this.set(props);
        };
        Tween.prototype.call = function (callback, thisObj, params) {
            if (thisObj === void 0) { thisObj = undefined; }
            if (params === void 0) { params = undefined; }
            return this._addAction({ f: callback, p: params ? params : [], o: thisObj ? thisObj : this._target });
        };
        Tween.prototype.set = function (props, target) {
            if (target === void 0) { target = null; }
            this._appendQueueProps(props);
            return this._addAction({ f: this._set, o: this, p: [props, target ? target : this._target] });
        };
        Tween.prototype.play = function (tween) {
            if (!tween) {
                tween = this;
            }
            return this.call(tween.setPaused, tween, [false]);
        };
        Tween.prototype.pause = function (tween) {
            if (!tween) {
                tween = this;
            }
            return this.call(tween.setPaused, tween, [true]);
        };
        Tween.prototype.$tick = function (delta) {
            if (this.paused) {
                return;
            }
            this.setPosition(this._prevPosition + delta);
        };
        Tween.NONE = 0;
        Tween.LOOP = 1;
        Tween.REVERSE = 2;
        Tween._tweens = [];
        Tween.IGNORE = {};
        Tween._plugins = {};
        Tween._inited = false;
        Tween._lastTime = 0;
        return Tween;
    }());

    var Button = (function (_super) {
        tslib_1.__extends(Button, _super);
        function Button(tUp, tDown, tDisable) {
            var _this = _super.call(this, tUp) || this;
            _this._clicked = false;
            _this._instanceType = "Button";
            _this.textureUp = tUp;
            _this.textureDown = tDown === tUp ? null : tDown;
            _this.textureDisable = tDisable || tUp;
            _this.anchorX = _this.textureUp.width / 2;
            _this.anchorY = _this.textureUp.height / 2;
            _this.initButton();
            return _this;
        }
        Button.prototype._mouseEvent = function (e) {
            var s = this;
            if (!s._clicked) {
                if (e.type == MouseEvent.MOUSE_DOWN) {
                    if (s.textureDown) {
                        s.texture = s.textureDown;
                    }
                    else {
                        this["frames"] = null;
                        Tween.removeTweens(this);
                        Tween.get(this).to({ scaleX: 0.9, scaleY: 0.9 }, 50);
                    }
                }
                else {
                    if (s.textureDown) {
                        s.texture = s.textureUp;
                    }
                    else {
                        this["frames"] = this["framesOri"];
                        Tween.removeTweens(this);
                        Tween.get(this).to({ scaleX: 1, scaleY: 1 }, 50);
                    }
                }
            }
        };
        Button.prototype.initButton = function () {
            var s = this;
            s.mouseChildren = false;
            s.addEventListener("onMouseDown", s._mouseEvent, s);
            s.addEventListener("onMouseUp", s._mouseEvent, s);
            s.addEventListener("onMouseOut", s._mouseEvent, s);
            s.texture = s.textureUp;
        };
        Object.defineProperty(Button.prototype, "clicked", {
            get: function () {
                return this._clicked;
            },
            set: function (value) {
                var s = this;
                if (value != s._clicked) {
                    if (value) {
                        s._mouseEvent({ type: "onMouseDown" });
                    }
                    s._clicked = value;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Button.prototype, "textureStatusEnable", {
            set: function (value) {
                if (value) {
                    this.texture = this.textureUp;
                }
                else {
                    if (this.textureDisable) {
                        this.texture = this.textureDisable;
                        this["frames"] = null;
                    }
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Button.prototype, "enabled", {
            set: function (value) {
                this.mouseEnable = value;
                this.textureStatusEnable = value;
            },
            enumerable: true,
            configurable: true
        });
        Button.prototype.destroy = function () {
            this.textureUp = null;
            this.textureDown = null;
            this.textureDisable = null;
            Tween.removeTweens(this);
            _super.prototype.destroy.call(this);
        };
        return Button;
    }(Sprite));

    var FrameAni = (function (_super) {
        tslib_1.__extends(FrameAni, _super);
        function FrameAni(texturesAll) {
            var _this = _super.call(this) || this;
            _this.loop = 1;
            _this.count = 0;
            _this.showImage = new Sprite();
            _this.showImage.anchorTexture.set(0.5, 0.5);
            _this.addChild(_this.showImage);
            _this.texturesAll = texturesAll;
            _this.changeTexture(0);
            _this.currentFrame = 0;
            _this.addEventListener(Event.ENTER_FRAME, _this.onEnterFrame, _this);
            _this.frameRate = 30;
            return _this;
        }
        Object.defineProperty(FrameAni.prototype, "totalFrames", {
            get: function () {
                return this.texturesAll.length;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(FrameAni.prototype, "frameRate", {
            get: function () {
                return this._frameRate;
            },
            set: function (value) {
                if (value == this._frameRate)
                    return;
                this._frameRate = value;
                this.allTime = this.texturesAll.length / this._frameRate * 1000;
            },
            enumerable: true,
            configurable: true
        });
        FrameAni.prototype.onEnterFrame = function () {
            if (!this.isPlay) {
                return;
            }
            var dataNow = Date.now();
            var deltaTime = dataNow - this.startTime;
            var scale = deltaTime / this.allTime;
            if (scale >= 1) {
                this.loop--;
                if (this.loop == 0) {
                    this.isPlay = false;
                    this.callback && this.callback();
                }
                else {
                    this.startTime = Date.now();
                    this.currentFrame = 0;
                    this.changeTexture(this.currentFrame);
                }
            }
            else {
                this.currentFrame = (scale * this.texturesAll.length) >> 0;
                this.changeTexture(this.currentFrame);
            }
        };
        FrameAni.prototype.play = function (loop, callback) {
            if (loop === void 0) { loop = 1; }
            this.startTime = Date.now();
            this.isPlay = true;
            this.currentFrame = 0;
            this.changeTexture(0);
            this.loop = loop;
            this.callback = callback;
        };
        FrameAni.prototype.reset = function (frame) {
            if (frame === void 0) { frame = 0; }
            this.isPlay = false;
            this.currentFrame = frame;
            this.changeTexture(frame);
        };
        FrameAni.prototype.changeTexture = function (index) {
            if (this.texturesAll[index]) {
                this.showImage.texture = this.texturesAll[index];
            }
            else {
                this.showImage.texture = null;
            }
        };
        return FrameAni;
    }(Container));

    var ScrollPage = (function (_super) {
        tslib_1.__extends(ScrollPage, _super);
        function ScrollPage(vW, vH, maxDistance, isVertical, isFull) {
            if (isVertical === void 0) { isVertical = true; }
            if (isFull === void 0) { isFull = false; }
            var _this = _super.call(this) || this;
            _this.isVertical = true;
            _this.viewWidth = 0;
            _this.viewHeight = 0;
            _this._tweenId = 0;
            _this.maxDistance = 1040;
            _this.distance = 0;
            _this.minDis = 2;
            _this.maskObj = new Graphics();
            _this.view = new Container();
            _this.lastValue = 0;
            _this.speed = 0;
            _this.addSpeed = 0;
            _this.isStop = true;
            _this.maxSpeed = 100;
            _this.fSpeed = 20;
            _this.paramXY = "y";
            _this.stopTimes = -1;
            _this.isMouseDownState = 0;
            _this.autoScroll = false;
            _this.isSpringBack = true;
            var s = _this;
            s._instanceType = "ScrollPage";
            s.addChild(s.maskObj);
            s.addChild(s.view);
            if (!isFull) {
                s.view.mask = s.maskObj;
                s.maskObj.isUsedToMask = false;
            }
            s.maskObj.alpha = 0;
            s.maxDistance = maxDistance;
            s.setViewRect(vW, vH, isVertical);
            s.addEventListener(Event.ADDED_TO_STAGE, function (e) {
                s.stage.addEventListener(MouseEvent.MOUSE_MOVE, s.onMouseEvent, s);
                s.stage.addEventListener(MouseEvent.MOUSE_UP, s.onMouseEvent, s);
            });
            s.addEventListener(Event.REMOVED_FROM_STAGE, function (e) {
                s.stage.removeEventListener(MouseEvent.MOUSE_MOVE, s.onMouseEvent, s);
                s.stage.removeEventListener(MouseEvent.MOUSE_UP, s.onMouseEvent, s);
            });
            s.addEventListener(MouseEvent.MOUSE_DOWN, s.onMouseEvent, s, false);
            s.addEventListener(Event.ENTER_FRAME, function () {
                var view = s.view;
                if (s.autoScroll)
                    return;
                if (!s.isSpringBack) {
                    if (view[s.paramXY] > 0) {
                        s.addSpeed = 0;
                        s.speed = 0;
                        s.isStop = true;
                        view[s.paramXY] = 0;
                        return;
                    }
                    else if (view[s.paramXY] < s.distance - s.maxDistance) {
                        s.addSpeed = 0;
                        s.speed = 0;
                        s.isStop = true;
                        view[s.paramXY] = s.distance - s.maxDistance;
                        if (s.distance > s.maxDistance)
                            view[s.paramXY] = 0;
                        return;
                    }
                }
                if (!s.isStop) {
                    if (Math.abs(s.speed) > 0) {
                        view[s.paramXY] += s.speed;
                        if (view[s.paramXY] > 0 || view[s.paramXY] < s.distance - s.maxDistance) {
                            s.speed += s.addSpeed * s.fSpeed;
                        }
                        else {
                            s.speed += s.addSpeed;
                        }
                        if (s.speed * s.addSpeed > 0) {
                            s.dispatchEvent(Event.SCROLL_STOP);
                            s.speed = 0;
                        }
                    }
                    else {
                        if (s.addSpeed != 0) {
                            if (view[s.paramXY] > 0 || view[s.paramXY] < s.distance - s.maxDistance) {
                                var tarP = 0;
                                if (view[s.paramXY] < s.distance - s.maxDistance) {
                                    if (s.distance < s.maxDistance) {
                                        tarP = s.distance - s.maxDistance;
                                    }
                                }
                                view[s.paramXY] += 0.4 * (tarP - view[s.paramXY]);
                                if (Math.abs(tarP - view[s.paramXY]) < 0.1) {
                                    s.isStop = true;
                                    if (s.addSpeed > 0) {
                                        s.dispatchEvent(Event.SCROLL_TO_END);
                                    }
                                    else {
                                        s.dispatchEvent(Event.SCROLL_TO_HEAD);
                                    }
                                }
                            }
                        }
                        else {
                            s.isStop = true;
                        }
                    }
                }
                else {
                    if (s.stopTimes >= 0) {
                        s.stopTimes++;
                        if (s.stopTimes >= 15) {
                            s.speed = 0;
                            if (view[s.paramXY] > 0 || view[s.paramXY] < s.distance - s.maxDistance) {
                                s.isStop = false;
                                s.stopTimes = -1;
                                s.isMouseDownState = 0;
                            }
                        }
                    }
                }
            });
            return _this;
        }
        ScrollPage.prototype.setViewRect = function (w, h, isVertical) {
            var s = this;
            s.maskObj.clear();
            s.maskObj.beginFill("#000000");
            s.maskObj.drawRect(0, 0, w, h);
            s.viewWidth = w;
            s.viewHeight = h;
            s.maskObj.endFill();
            s.isVertical = isVertical;
            if (isVertical) {
                s.distance = s.viewHeight;
                s.paramXY = "y";
            }
            else {
                s.distance = s.viewWidth;
                s.paramXY = "x";
            }
            s.isVertical = isVertical;
        };
        ScrollPage.prototype.onMouseEvent = function (e) {
            var s = this;
            var view = s.view;
            if (e.type == MouseEvent.MOUSE_DOWN) {
                e.stopPropagation();
                if (!s.isStop) {
                    s.isStop = true;
                }
                if (s.autoScroll) {
                    s.autoScroll = false;
                    cancelAnimationFrame(s._tweenId);
                }
                if (s.isVertical) {
                    s.lastValue = e.stageY;
                }
                else {
                    s.lastValue = e.stageX;
                }
                s.speed = 0;
                s.isMouseDownState = 1;
            }
            else if (e.type == MouseEvent.MOUSE_MOVE) {
                if (s.isMouseDownState == 0)
                    return;
                if (s.isMouseDownState == 1) {
                    s.dispatchEvent(Event.SCROLL_START);
                }
                s.isMouseDownState = 2;
                var currentValue = void 0;
                if (s.isVertical) {
                    currentValue = e.stageY;
                }
                else {
                    currentValue = e.stageX;
                }
                s.speed = currentValue - s.lastValue;
                if (s.speed > s.minDis) {
                    s.addSpeed = -2;
                    if (s.speed > s.maxSpeed) {
                        s.speed = s.maxSpeed;
                    }
                }
                else if (s.speed < -s.minDis) {
                    if (s.speed < -s.maxSpeed) {
                        s.speed = -s.maxSpeed;
                    }
                    s.addSpeed = 2;
                }
                else {
                    s.speed = 0;
                }
                if (s.speed != 0) {
                    var speedPer = 1;
                    if (view[s.paramXY] > 0 || view[s.paramXY] < s.distance - s.maxDistance) {
                        speedPer = 0.2;
                    }
                    view[s.paramXY] += (currentValue - s.lastValue) * speedPer;
                }
                s.lastValue = currentValue;
                s.stopTimes = 0;
            }
            else {
                s.isStop = false;
                s.stopTimes = -1;
                if (s.speed == 0 && s.isMouseDownState == 2) {
                    s.dispatchEvent(Event.SCROLL_STOP);
                }
                s.isMouseDownState = 0;
            }
        };
        ScrollPage.prototype.scrollTo = function (dis, time) {
            if (time === void 0) { time = 0; }
            var s = this;
            var newDis = s.paramXY == "x" ? s.viewWidth : s.viewHeight;
            if (dis < 0) {
                dis = 0;
            }
            else if (dis > s.maxDistance - newDis) {
                dis = s.maxDistance - newDis;
            }
            if (Math.abs(s.view[s.paramXY] + dis) > 2) {
                s.isStop = true;
                s.isMouseDownState = 0;
                if (time) {
                    s.autoScroll = true;
                    var cdis_1 = s.view[s.paramXY];
                    cancelAnimationFrame(s._tweenId);
                    var last_1 = Date.now();
                    var fun_1 = function () {
                        var deltaTime = Date.now() - last_1;
                        if (deltaTime > time) {
                            s.view[s.paramXY] = -dis;
                            s.autoScroll = false;
                            cancelAnimationFrame(s._tweenId);
                        }
                        else {
                            s.view[s.paramXY] = (-dis - cdis_1) * (deltaTime / time) + cdis_1;
                            s._tweenId = requestAnimationFrame(fun_1);
                        }
                    };
                    s._tweenId = requestAnimationFrame(fun_1);
                    if (s.speed == 0)
                        s.dispatchEvent(Event.SCROLL_START);
                }
                else {
                    s.view[s.paramXY] = -dis;
                }
            }
        };
        ScrollPage.prototype.destroy = function () {
            var s = this;
            s.maskObj.destroy();
            s.view.destroy();
            s.maskObj = null;
            s.view = null;
            _super.prototype.destroy.call(this);
        };
        return ScrollPage;
    }(Container));

    var ScrollList = (function (_super) {
        tslib_1.__extends(ScrollList, _super);
        function ScrollList(itemClassName, itemWidth, itemHeight, vW, vH, isVertical, cols) {
            if (isVertical === void 0) { isVertical = true; }
            if (cols === void 0) { cols = 1; }
            var _this = _super.call(this, vW, vH, 0, isVertical) || this;
            _this._items = null;
            _this._isInit = 0;
            _this.data = [];
            _this.downL = null;
            _this._lastFirstId = -1;
            _this._updateId = -1;
            var s = _this;
            s._instanceType = "ScrollList";
            s._itemW = itemWidth;
            s._itemH = itemHeight;
            s._items = [];
            s._itemClass = itemClassName;
            s._itemCount = 0;
            s._cols = cols;
            s._updateViewRect();
            s.addEventListener(Event.ENTER_FRAME, s.flushData.bind(s));
            return _this;
        }
        Object.defineProperty(ScrollList.prototype, "loadingView", {
            get: function () {
                return this.downL;
            },
            enumerable: true,
            configurable: true
        });
        ScrollList.prototype.updateData = function (data, isReset) {
            if (isReset === void 0) { isReset = false; }
            var s = this;
            if (!s._isInit || isReset) {
                s.data = data;
            }
            else {
                s.data = s.data.concat(data);
            }
            s._isInit = 1;
            s._lastFirstId = -1;
            s.maxDistance = Math.ceil(s.data.length / s._cols) * s._itemRow;
            if (s.downL) {
                s.downL[s.paramXY] = Math.max(s.distance, s.maxDistance);
                var wh = s.downL.getWH();
                s.maxDistance += (s.paramXY == "x" ? wh.width : wh.height);
            }
        };
        ScrollList.prototype.flushData = function () {
            var s = this;
            if (s._isInit > 0) {
                if (s._updateId != s.view.transform._localID) {
                    s._updateId = s.view.transform._localID;
                    var id = s.view[s.paramXY] > 0 ? 0 : (Math.abs(Math.floor(s.view[s.paramXY] / s._itemRow)) - 1) * s._cols;
                    id = id < 0 ? 0 : id;
                    if (id != s._lastFirstId) {
                        s._lastFirstId = id;
                        if (id != s._items[0].id) {
                            for (var r = 0; r < s._cols; r++) {
                                if (s.speed > 0) {
                                    s._items.unshift(s._items.pop());
                                }
                                else {
                                    s._items.push(s._items.shift());
                                }
                            }
                        }
                    }
                    for (var i = 0; i < s._itemCount; i++) {
                        var item = s._items[i];
                        if (s._isInit == 1) {
                            item.sli_id = -1;
                        }
                        if (item.sli_id != id) {
                            item.initData(s.data[id] ? id : -1, s.data[id]);
                            item[s.paramXY] = Math.floor(id / s._cols) * s._itemRow;
                            item[s._disParam] = (id % s._cols) * s._itemCol;
                            if (s.data[id]) {
                                item.sli_id = id;
                                item.visible = true;
                            }
                            else {
                                item.sli_id = -1;
                                item.visible = false;
                            }
                        }
                        id++;
                    }
                    s._isInit = 2;
                }
            }
        };
        ScrollList.prototype.setViewRect = function (w, h, isVertical) {
            _super.prototype.setViewRect.call(this, w, h, isVertical);
            var s = this;
            if (s._itemRow && s._itemCol) {
                s._updateViewRect();
            }
        };
        ScrollList.prototype._updateViewRect = function () {
            var s = this;
            if (s.isVertical) {
                s._disParam = "x";
                s._itemRow = s._itemH;
                s._itemCol = s._itemW;
            }
            else {
                s._disParam = "y";
                s._itemRow = s._itemW;
                s._itemCol = s._itemH;
            }
            var newCount = (Math.ceil(s.distance / s._itemRow) + 1) * s._cols;
            if (newCount != s._itemCount) {
                if (newCount > s._itemCount) {
                    for (var i = s._itemCount; i < newCount; i++) {
                        var item = new s._itemClass();
                        item.id = -1;
                        item.data = null;
                        s._items.push(item);
                        s.view.addChild(item);
                    }
                }
                else {
                    for (var i = 0; i < s._itemCount - newCount; i++) {
                        s.view.removeChild(s._items.pop());
                    }
                }
                s._itemCount = newCount;
                s._lastFirstId = -1;
            }
        };
        ScrollList.prototype.setLoading = function (downLoading) {
            var s = this;
            if (s.downL) {
                s.view.removeChild(s.downL);
                var wh = s.downL.getWH();
                s.maxDistance -= (s.paramXY == "x" ? wh.width : wh.height);
                s.downL = null;
            }
            if (downLoading) {
                s.downL = downLoading;
                s.view.addChild(downLoading);
                s.downL[s.paramXY] = Math.max(s.distance, s.maxDistance);
                var wh = s.downL.getWH();
                s.maxDistance += (s.paramXY == "x" ? wh.width : wh.height);
            }
            else {
                s.isStop = false;
            }
        };
        ScrollList.prototype.destroy = function () {
            var s = this;
            s._items = null;
            s._itemClass = null;
            s.data = null;
            s.downL = null;
            _super.prototype.destroy.call(this);
        };
        return ScrollList;
    }(ScrollPage));

    var ShowWord = (function (_super) {
        tslib_1.__extends(ShowWord, _super);
        function ShowWord() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        ShowWord.prototype.playWords = function (text, deltaTime, callback) {
            var _this = this;
            if (deltaTime === void 0) { deltaTime = 100; }
            var spiltStrs = text.split("\n");
            var strs = [];
            for (var i = 0; i < spiltStrs.length; i++) {
                var spiltStr = spiltStrs[i];
                var ori = "";
                var index = 0;
                while (index < i) {
                    ori += spiltStrs[index];
                    ori += "\n";
                    index++;
                }
                for (var j = 0; j < spiltStr.length; j++) {
                    var str = "" + ori;
                    str += spiltStr.substring(0, j + 1);
                    strs.push(str);
                }
            }
            var _loop_1 = function (m) {
                var str_1 = strs[m];
                setTimeout(function () {
                    _this.text = str_1;
                    if (m == strs.length - 1) {
                        callback && callback();
                    }
                }, deltaTime * m);
            };
            for (var m = 0; m < strs.length; m++) {
                _loop_1(m);
            }
        };
        return ShowWord;
    }(TextField));

    var MovieClip = (function (_super) {
        tslib_1.__extends(MovieClip, _super);
        function MovieClip(mv) {
            var _this = _super.call(this) || this;
            _this.lockStep = false;
            _this._curFrame = 1;
            _this._isPlaying = true;
            _this._isFront = true;
            _this.textures = {};
            _this.frameCount = 0;
            _this._lastFrame = 0;
            _this.commonDeltaTime = 1000 / 60;
            var s = _this;
            s._instanceType = "MovieClip";
            if (mv) {
                s.init(mv);
            }
            else {
                s.totalFrames = 0;
            }
            return _this;
        }
        Object.defineProperty(MovieClip.prototype, "currentFrame", {
            get: function () {
                return this._curFrame;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(MovieClip.prototype, "isPlaying", {
            get: function () {
                return this._isPlaying;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(MovieClip.prototype, "isFront", {
            get: function () {
                return this._isFront;
            },
            enumerable: true,
            configurable: true
        });
        MovieClip.prototype.init = function (mv) {
            this.timeInterval = 1000 / mv.FPS;
            this.startTime = Date.now();
            this.startFrame = 1;
            this.totalFrames = mv.frames;
            this.deltaFrame = 60 / mv.FPS;
            this.frameCount = this.deltaFrame;
            this._curFrame = 1;
            this.videoWidth = mv.videoSize.width;
            this.videoHeight = mv.videoSize.height;
            var images = mv.images;
            if (mv.hasBeenCached) {
                for (var keyName in images) {
                    this.textures[keyName] = TextureCache[keyName];
                }
                this.initChildren(mv.sprites);
            }
            else {
                for (var key in images) {
                    var bitmap = images[key];
                    var imgTag = getCreateImage()();
                    var backCanvas = void 0;
                    if (bitmap.indexOf("iVBO") === 0 || bitmap.indexOf("/9j/2w") === 0) {
                        imgTag.src = 'data:image/png;base64,' + bitmap;
                    }
                    else {
                        imgTag.src = bitmap;
                    }
                    this.textures[key] = Texture.from(backCanvas || imgTag);
                    Texture.addToCache(this.textures[key], key);
                }
                mv.hasBeenCached = true;
                this.initChildren(mv.sprites);
            }
        };
        MovieClip.prototype.initChildren = function (sprites) {
            for (var i = 0, len = sprites.length; i < len; i++) {
                var ele = sprites[i];
                if (ele.imageKey) {
                    var child = new Sprite(this.textures[ele.imageKey]);
                    child["frames"] = ele.frames;
                    child.transform.localMatrix.copy(ele.frames[0].transform);
                    child.transform._parentID = -1;
                    this.addChild(child);
                    if (ele.frames[0].alpha < 0.05) {
                        child.visible = false;
                    }
                    else {
                        child.alpha = ele.frames[0].alpha;
                    }
                    child["framesOri"] = ele.frames;
                    child["imageKey"] = ele.imageKey;
                    child["matteKey"] = ele.matteKey;
                }
            }
        };
        MovieClip.prototype.resetTransform = function (display, transform) {
            display.x = transform.tx;
            display.y = transform.ty;
            display.scaleX = transform.a;
            display.scaleY = transform.d;
            display.rotation = Math.round(Math.atan2(transform.b, transform.a) * RAD_TO_DEG);
        };
        MovieClip.prototype.resetTransformAll = function (frameIndex) {
            if (frameIndex > this.totalFrames)
                frameIndex = this.totalFrames;
            if (frameIndex <= 0)
                frameIndex = 1;
            for (var i = 0; i < this.children.length; i++) {
                var child = this.children[i];
                if (child["frames"] && child["frames"][frameIndex - 1]) {
                    this.resetTransform(child, child["frames"][frameIndex - 1].transform);
                }
            }
        };
        MovieClip.prototype.setImage = function (imagekey, imageUrl) {
            if (!this.textures[imagekey])
                return;
            var texture = this.textures[imagekey];
            var width = texture.width;
            var height = texture.height;
            var image = getCreateImage()();
            var self = this;
            image.onload = function () {
                var newTexture;
                if (image.width == width && image.height == height) {
                    newTexture = Texture.from(image);
                }
                else {
                    var canvas = document.createElement("canvas");
                    canvas.width = width;
                    canvas.height = height;
                    var ctx = canvas.getContext("2d");
                    var scaleCan = width / height;
                    var scale = image.width / image.height;
                    if (scaleCan > scale) {
                        ctx.drawImage(image, 0, 0, image.width, image.height, (width - scale * height) / 2, 0, scale * height, height);
                    }
                    else {
                        ctx.drawImage(image, 0, 0, image.width, image.height, 0, (height - width / scale) / 2, width, width / scale);
                    }
                    newTexture = Texture.fromCanvas(canvas);
                }
                for (var i = 0; i < self.children.length; i++) {
                    var child = self.children[i];
                    if (child["imageKey"] == imagekey) {
                        child.texture = newTexture;
                    }
                }
            };
            image.src = imageUrl;
        };
        MovieClip.prototype.stop = function () {
            var s = this;
            s._isPlaying = false;
        };
        MovieClip.prototype.nextFrame = function () {
            var s = this;
            if (s._curFrame < s.totalFrames) {
                s._curFrame++;
            }
            s._isPlaying = false;
        };
        MovieClip.prototype.prevFrame = function () {
            var s = this;
            if (s._curFrame > 1) {
                s._curFrame--;
            }
            s._isPlaying = false;
        };
        MovieClip.prototype.gotoAndStop = function (frameIndex) {
            var s = this;
            s._isPlaying = false;
            if (frameIndex > s.totalFrames) {
                frameIndex = s.totalFrames;
            }
            if (frameIndex < 1) {
                frameIndex = 1;
            }
            s._curFrame = frameIndex;
        };
        MovieClip.prototype.play = function (isFront) {
            if (isFront === void 0) { isFront = true; }
            var s = this;
            s.frameCount = s.deltaFrame;
            s.startTime = Date.now();
            s.startFrame = s._curFrame;
            s._isPlaying = true;
            s._isFront = isFront;
        };
        Object.defineProperty(MovieClip.prototype, "isInTimeFrame", {
            get: function () {
                return this.frameCount == this.deltaFrame;
            },
            enumerable: true,
            configurable: true
        });
        MovieClip.prototype.gotoAndPlay = function (frameIndex, isFront) {
            if (isFront === void 0) { isFront = true; }
            var s = this;
            s._isFront = isFront;
            s._isPlaying = true;
            if (frameIndex > s.totalFrames) {
                frameIndex = s.totalFrames;
            }
            if (frameIndex < 1) {
                frameIndex = 1;
            }
            s.frameCount = s.deltaFrame;
            s.startTime = Date.now();
            s._curFrame = frameIndex;
            s.startFrame = s._curFrame;
        };
        MovieClip.prototype.startAniRange = function (beginFrame, endFrame, loops, callback) {
            var _this = this;
            if (beginFrame === void 0) { beginFrame = 1; }
            if (endFrame === void 0) { endFrame = this.totalFrames; }
            if (loops === void 0) { loops = 1; }
            if (beginFrame < 1) {
                beginFrame = 1;
            }
            if (beginFrame > this.totalFrames) {
                beginFrame = this.totalFrames;
            }
            if (endFrame < 1) {
                endFrame = 1;
            }
            if (endFrame > this.totalFrames) {
                endFrame = this.totalFrames;
            }
            if (beginFrame === endFrame) {
                this.gotoAndStop(beginFrame);
                return;
            }
            else if (beginFrame < endFrame) {
                this._isFront = true;
            }
            else {
                this._isFront = false;
                var temp = beginFrame;
                beginFrame = endFrame;
                endFrame = temp;
            }
            if (this.startAniRangeFun)
                this.removeEventListener(Event.ENTER_FRAME, this.startAniRangeFun, this);
            this._curFrame = beginFrame;
            this.frameCount = this.deltaFrame;
            this.startTime = Date.now();
            this.startFrame = this._curFrame;
            this._isPlaying = true;
            var loopCount = loops ? (loops + 0.5 >> 0) : Infinity;
            this.addEventListener(Event.ENTER_FRAME, this.startAniRangeFun = function (e) {
                if (e.target._isFront) {
                    if (e.target.currentFrame >= endFrame || e.target._endMark) {
                        loopCount--;
                        if (loopCount <= 0) {
                            e.target.gotoAndStop(endFrame);
                            e.target.removeEventListener(Event.ENTER_FRAME, _this.startAniRangeFun, _this);
                            _this.startAniRangeFun = null;
                            callback && callback();
                        }
                        else {
                            e.target.gotoAndPlay(beginFrame);
                        }
                    }
                }
                else {
                    if (e.target.currentFrame <= beginFrame || e.target._endMark) {
                        loopCount--;
                        if (loopCount <= 0) {
                            e.target.gotoAndStop(beginFrame);
                            e.target.removeEventListener(Event.ENTER_FRAME, _this.startAniRangeFun, _this);
                            _this.startAniRangeFun = null;
                            callback && callback();
                        }
                        else {
                            e.target.gotoAndPlay(endFrame, false);
                        }
                    }
                }
            }, this);
        };
        MovieClip.prototype.updateFrame = function () {
            var s = this;
            if (s.totalFrames == 0 || s.totalFrames == 1)
                return;
            var isNeedUpdate = false;
            if (s._lastFrame != s._curFrame) {
                isNeedUpdate = true;
                s._lastFrame = s._curFrame;
                s.startTime = Date.now();
                s.startFrame = s._curFrame;
                s._endMark = false;
            }
            else {
                if (s._isPlaying) {
                    if (s.lockStep) {
                        isNeedUpdate = s.getCurFrameWhenLockStep();
                    }
                    else {
                        if (--s.frameCount == 0) {
                            s.frameCount = s.deltaFrame;
                            isNeedUpdate = true;
                            if (s._isFront) {
                                s._curFrame++;
                                if (s._curFrame > s.totalFrames) {
                                    s._curFrame = 1;
                                }
                            }
                            else {
                                s._curFrame--;
                                if (s._curFrame < 1) {
                                    s._curFrame = s.totalFrames;
                                }
                            }
                            s._lastFrame = s._curFrame;
                        }
                    }
                }
            }
            if (isNeedUpdate) {
                for (var i = 0, len = s.children.length; i < len; i++) {
                    var child = s.children[i];
                    if (child["frames"] && child["frames"][s._curFrame - 1]) {
                        var frame = child["frames"][s._curFrame - 1];
                        if (frame.alpha < 0.05) {
                            child.visible = false;
                        }
                        else {
                            child.visible = true;
                            child.alpha = frame.alpha;
                            if (!Matrix.isEqual(child.transform.localMatrix, frame.transform)) {
                                child.transform.localMatrix.copy(frame.transform);
                                child.transform._parentID = -1;
                            }
                        }
                    }
                }
                if (!s.lockStep) {
                    if (((s._curFrame == 1 && !s._isFront) || (s._curFrame == s.totalFrames && s._isFront)) && s.hasEventListener(Event.END_FRAME)) {
                        s.dispatchEvent(Event.END_FRAME, {
                            frameIndex: s._curFrame,
                            frameName: "endFrame"
                        });
                    }
                }
                else {
                    if (s._endMark && s.hasEventListener(Event.END_FRAME)) {
                        s.dispatchEvent(Event.END_FRAME, {
                            frameIndex: s._curFrame,
                            frameName: "endFrame"
                        });
                    }
                }
            }
        };
        MovieClip.prototype.getCurFrameWhenLockStep = function () {
            var dateNow = Date.now();
            var deltaFrame = ((dateNow - this.startTime) / this.timeInterval) >> 0;
            if (deltaFrame == this.lastDeltaFrame) {
                this.frameCount = 0;
                return false;
            }
            this._endMark = false;
            this.frameCount = this.deltaFrame;
            this.lastDeltaFrame = deltaFrame;
            if (this._isFront) {
                this._curFrame = (this.startFrame + deltaFrame) % this.totalFrames;
                if (this._curFrame == 0) {
                    this._curFrame = this.totalFrames;
                    this._endMark = true;
                }
                else if (this._lastFrame > this._curFrame &&
                    this._lastFrame != this.totalFrames) {
                    this._endMark = true;
                }
            }
            else {
                this._curFrame = (this.startFrame - deltaFrame) % this.totalFrames;
                if (this._curFrame == 0) {
                    this._curFrame = this.totalFrames;
                }
                else if (this._curFrame < 0) {
                    this._curFrame += this.totalFrames;
                }
                if (this._curFrame == 1) {
                    this._endMark = true;
                }
                else if (this._lastFrame < this._curFrame &&
                    this._lastFrame != 1) {
                    this._endMark = true;
                }
            }
            this._lastFrame = this._curFrame;
            return true;
        };
        MovieClip.prototype.update = function () {
            this.updateFrame();
            _super.prototype.update.call(this);
        };
        MovieClip.prototype.destroy = function () {
            _super.prototype.destroy.call(this);
        };
        return MovieClip;
    }(Container));

    var Sound = (function (_super) {
        tslib_1.__extends(Sound, _super);
        function Sound() {
            var _this = _super.call(this) || this;
            _this.loaded = false;
            return _this;
        }
        Object.defineProperty(Sound.prototype, "length", {
            get: function () {
                if (this.originAudio) {
                    return this.originAudio.duration;
                }
                throw new Error("sound not loaded!");
            },
            enumerable: true,
            configurable: true
        });
        Sound.prototype.load = function (url) {
            var _this = this;
            this.url = url;
            GlobalLoader.loadAudio(function (s, audio) {
                _this.originAudio = audio;
                if (s) {
                    Sound.$recycle(_this.url, audio);
                    _this.loaded = true;
                    _this.dispatchEvent(Event.COMPLETE);
                }
                else {
                    _this.dispatchEvent(Event.ERROR);
                }
            }, url);
            if (Sound.clearAudios[this.url]) {
                delete Sound.clearAudios[this.url];
            }
        };
        Sound.prototype.play = function (startTime, loops) {
            startTime = +startTime || 0;
            loops = +loops || 0;
            var audio = Sound.$pop(this.url);
            if (audio == null) {
                audio = my.createInnerAudioContext();
                audio.src = this.url;
            }
            audio.autoplay = true;
            var channel = new SoundChannel(audio);
            channel.$url = this.url;
            channel.$loops = loops;
            channel.$startTime = startTime;
            channel.$play();
            return channel;
        };
        Sound.prototype.close = function () {
            if (this.loaded == false && this.originAudio)
                this.originAudio.src = "";
            if (this.originAudio)
                this.originAudio = null;
            Sound.$clear(this.url);
        };
        Sound.$clear = function (url) {
            Sound.clearAudios[url] = true;
            var array = Sound.audios[url];
            if (array) {
                array.length = 0;
            }
        };
        Sound.$pop = function (url) {
            var array = Sound.audios[url];
            if (array && array.length > 0) {
                return array.pop();
            }
            return null;
        };
        Sound.$recycle = function (url, audio) {
            if (Sound.clearAudios[url]) {
                return;
            }
            var array = Sound.audios[url];
            if (Sound.audios[url] == null) {
                array = Sound.audios[url] = [];
            }
            array.push(audio);
        };
        Sound.audios = {};
        Sound.clearAudios = {};
        return Sound;
    }(EventDispatcher));

    var SoundChannel = (function (_super) {
        tslib_1.__extends(SoundChannel, _super);
        function SoundChannel(audio) {
            var _this = _super.call(this) || this;
            _this.$startTime = 0;
            _this.audio = null;
            _this.isStopped = false;
            _this.canPlay = function () {
                try {
                    _this.audio.currentTime = _this.$startTime;
                }
                catch (e) {
                }
                finally {
                    _this.audio.play();
                }
            };
            _this.onPlayEnd = function () {
                if (_this.$loops == 1) {
                    _this.stop();
                    _this.dispatchEvent(Event.COMPLETE);
                    return;
                }
                if (_this.$loops > 0) {
                    _this.$loops--;
                }
                _this.$play();
            };
            _this._volume = 1;
            audio.onEnded(_this.onPlayEnd);
            _this.audio = audio;
            return _this;
        }
        SoundChannel.prototype.$play = function () {
            var _this = this;
            if (this.isStopped) {
                return;
            }
            try {
                this.audio.volume = this._volume;
                this.audio.currentTime = this.$startTime;
            }
            catch (e) {
                this.audio.onCanplay(function () { _this.canPlay(); });
                return;
            }
            this.audio.play();
        };
        SoundChannel.prototype.stop = function () {
            if (!this.audio)
                return;
            if (!this.isStopped) ;
            this.isStopped = true;
            var audio = this.audio;
            audio.onEnded(function () { });
            audio.onCanplay(function () { });
            audio.volume = 0;
            this._volume = 0;
            this.audio = null;
            var url = this.$url;
            setTimeout(function () {
                audio.pause();
                Sound.$recycle(url, audio);
            }, 200);
        };
        Object.defineProperty(SoundChannel.prototype, "volume", {
            get: function () {
                return this._volume;
            },
            set: function (value) {
                if (this.isStopped) {
                    return;
                }
                this._volume = value;
                if (!this.audio)
                    return;
                this.audio.volume = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(SoundChannel.prototype, "position", {
            get: function () {
                if (!this.audio)
                    return 0;
                return this.audio.currentTime;
            },
            enumerable: true,
            configurable: true
        });
        return SoundChannel;
    }(EventDispatcher));

    var Ease = (function () {
        function Ease() {
        }
        Ease.get = function (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));
            };
        };
        Ease.getPowIn = function (pow) {
            return function (t) {
                return Math.pow(t, pow);
            };
        };
        Ease.getPowOut = function (pow) {
            return function (t) {
                return 1 - Math.pow(1 - t, pow);
            };
        };
        Ease.getPowInOut = function (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));
            };
        };
        Ease.sineIn = function (t) {
            return 1 - Math.cos(t * Math.PI / 2);
        };
        Ease.sineOut = function (t) {
            return Math.sin(t * Math.PI / 2);
        };
        Ease.sineInOut = function (t) {
            return -0.5 * (Math.cos(Math.PI * t) - 1);
        };
        Ease.getBackIn = function (amount) {
            return function (t) {
                return t * t * ((amount + 1) * t - amount);
            };
        };
        Ease.getBackOut = function (amount) {
            return function (t) {
                return (--t * t * ((amount + 1) * t + amount) + 1);
            };
        };
        Ease.getBackInOut = function (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);
            };
        };
        Ease.circIn = function (t) {
            return -(Math.sqrt(1 - t * t) - 1);
        };
        Ease.circOut = function (t) {
            return Math.sqrt(1 - (--t) * t);
        };
        Ease.circInOut = function (t) {
            if ((t *= 2) < 1) {
                return -0.5 * (Math.sqrt(1 - t * t) - 1);
            }
            return 0.5 * (Math.sqrt(1 - (t -= 2) * t) + 1);
        };
        Ease.bounceIn = function (t) {
            return 1 - Ease.bounceOut(1 - t);
        };
        Ease.bounceOut = function (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);
            }
        };
        Ease.bounceInOut = function (t) {
            if (t < 0.5)
                return Ease.bounceIn(t * 2) * .5;
            return Ease.bounceOut(t * 2 - 1) * 0.5 + 0.5;
        };
        Ease.getElasticIn = function (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));
            };
        };
        Ease.getElasticOut = function (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);
            };
        };
        Ease.getElasticInOut = function (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;
            };
        };
        Ease.quadIn = Ease.getPowIn(2);
        Ease.quadOut = Ease.getPowOut(2);
        Ease.quadInOut = Ease.getPowInOut(2);
        Ease.cubicIn = Ease.getPowIn(3);
        Ease.cubicOut = Ease.getPowOut(3);
        Ease.cubicInOut = Ease.getPowInOut(3);
        Ease.quartIn = Ease.getPowIn(4);
        Ease.quartOut = Ease.getPowOut(4);
        Ease.quartInOut = Ease.getPowInOut(4);
        Ease.quintIn = Ease.getPowIn(5);
        Ease.quintOut = Ease.getPowOut(5);
        Ease.quintInOut = Ease.getPowInOut(5);
        Ease.backIn = Ease.getBackIn(1.7);
        Ease.backOut = Ease.getBackOut(1.7);
        Ease.backInOut = Ease.getBackInOut(1.7);
        Ease.elasticIn = Ease.getElasticIn(1, 0.3);
        Ease.elasticOut = Ease.getElasticOut(1, 0.3);
        Ease.elasticInOut = Ease.getElasticInOut(1, 0.3 * 1.5);
        return Ease;
    }());

    var Stats = function (canvasId) {
        var beginTime = Date.now(), prevTime = beginTime, frames = 0;
        var fpsPanel = new Stats.Panel(canvasId, 'FPS', '#0ff', '#002');
        return {
            begin: function () {
                beginTime = Date.now();
            },
            end: function () {
                frames++;
                var time = Date.now();
                if (time >= prevTime + 1000) {
                    fpsPanel.update((frames * 1000) / (time - prevTime), 100.0);
                    prevTime = time;
                    frames = 0;
                }
                return time;
            },
            update: function () {
                beginTime = this.end();
            },
        };
    };
    Stats.Panel = function (canvasId, name, fg, bg) {
        var min = Infinity, max = 0, round = Math.round;
        var PR = 3;
        var WIDTH = 80 * PR, HEIGHT = 48 * PR, TEXT_X = 3 * PR, TEXT_Y = 2 * PR, GRAPH_X = 3 * PR, GRAPH_Y = 15 * PR, GRAPH_WIDTH = 74 * PR, GRAPH_HEIGHT = 30 * PR;
        var GRAPH_SIZE = GRAPH_WIDTH / PR;
        var items = [];
        var context;
        my.createCanvas({
            id: canvasId,
            success: function (ccc) {
                context = ccc.getContext("2d");
                context.font = 'bold ' + (9 * PR) + 'px Helvetica,Arial,sans-serif';
                context.textBaseline = 'top';
                drawWithoutGraph(name);
            }
        });
        return {
            update: function (value, maxValue) {
                items.push(value);
                while (items.length > GRAPH_SIZE) {
                    items.shift();
                }
                min = Math.min(min, value);
                max = Math.max(max, value);
                drawWithoutGraph(round(value) + ' ' + name + ' (' + round(min) + '-' + round(max) + ')');
                for (var i = 0; i < items.length; i++) {
                    var startPos = GRAPH_X + (i + GRAPH_SIZE - items.length) * PR;
                    context.fillStyle = fg;
                    context.globalAlpha = 1;
                    context.fillRect(startPos, GRAPH_Y, PR, GRAPH_HEIGHT);
                    context.fillStyle = bg;
                    context.globalAlpha = 0.9;
                    context.fillRect(startPos, GRAPH_Y, PR, round((1 - (items[i] / maxValue)) * GRAPH_HEIGHT));
                }
            }
        };
        function drawWithoutGraph(text) {
            context.fillStyle = bg;
            context.globalAlpha = 1;
            context.fillRect(0, 0, WIDTH, HEIGHT);
            context.fillStyle = fg;
            context.fillText(text, TEXT_X, TEXT_Y);
            context.fillRect(GRAPH_X, GRAPH_Y, GRAPH_WIDTH, GRAPH_HEIGHT);
            context.fillStyle = bg;
            context.globalAlpha = 0.9;
            context.fillRect(GRAPH_X, GRAPH_Y, GRAPH_WIDTH, GRAPH_HEIGHT);
        }
    };

    if (window)
        window["my"] = null;

    exports.AlphaFilter = AlphaFilter;
    exports.BaseTexture = BaseTexture;
    exports.BaseTextureCache = BaseTextureCache;
    exports.BitmapText = BitmapText;
    exports.BlurFilter = BlurFilter;
    exports.BlurFilterNew = BlurFilterNew;
    exports.BlurXFilter = BlurXFilter;
    exports.BlurYFilter = BlurYFilter;
    exports.Button = Button;
    exports.CanvasRenderer = CanvasRenderer;
    exports.ColorMatrixFilter = ColorMatrixFilter;
    exports.Container = Container;
    exports.DEG_TO_RAD = DEG_TO_RAD;
    exports.DisplacementFilter = DisplacementFilter;
    exports.DisplayObject = DisplayObject;
    exports.DrawAllToCanvas = DrawAllToCanvas;
    exports.Ease = Ease;
    exports.Event = Event;
    exports.EventDispatcher = EventDispatcher;
    exports.FXAAFilter = FXAAFilter;
    exports.Filter = Filter;
    exports.FrameAni = FrameAni;
    exports.GDispatcher = GDispatcher;
    exports.GlobalLoader = GlobalLoader;
    exports.GlobalPro = GlobalPro;
    exports.Graphics = Graphics;
    exports.GroupD8 = GroupD8;
    exports.INT_BITS1 = INT_BITS1;
    exports.INT_MAX = INT_MAX;
    exports.INT_MIN = INT_MIN;
    exports.Loader = Loader;
    exports.Matrix = Matrix;
    exports.Mesh = Mesh;
    exports.MouseEvent = MouseEvent;
    exports.MovieClip = MovieClip;
    exports.NineSlicePlane = NineSlicePlane;
    exports.NoiseFilter = NoiseFilter;
    exports.ObservablePoint = ObservablePoint;
    exports.PI_2 = PI_2;
    exports.Plane = Plane;
    exports.Point = Point;
    exports.RAD_TO_DEG = RAD_TO_DEG;
    exports.Rectangle = Rectangle;
    exports.ScrollList = ScrollList;
    exports.ScrollPage = ScrollPage;
    exports.ShowWord = ShowWord;
    exports.Sound = Sound;
    exports.SoundChannel = SoundChannel;
    exports.Sprite = Sprite;
    exports.SpriteMaskFilter = SpriteMaskFilter;
    exports.Stage = Stage;
    exports.Stats = Stats;
    exports.TextField = TextField;
    exports.Texture = Texture;
    exports.TextureCache = TextureCache;
    exports.TextureSheetCache = TextureSheetCache;
    exports.Transform = Transform;
    exports.Tween = Tween;
    exports.VERSION = VERSION;
    exports.WebglRenderer = WebglRenderer;
    exports.abs = abs;
    exports.backupCanvas = backupCanvas;
    exports.calculatePlaneIndices = calculatePlaneIndices;
    exports.clearTextureCache = clearTextureCache;
    exports.cos = cos;
    exports.countTrailingZeros = countTrailingZeros;
    exports.createCanvas = createCanvas;
    exports.createTextureSheet = createTextureSheet;
    exports.decomposeDataUri = decomposeDataUri;
    exports.deinterleave2 = deinterleave2;
    exports.deinterleave3 = deinterleave3;
    exports.destroyCanvasContent = destroyCanvasContent;
    exports.destroyTextureCache = destroyTextureCache;
    exports.determineCrossOrigin = determineCrossOrigin;
    exports.devicePixelRatio = devicePixelRatio;
    exports.getCancelAnimationFrame = getCancelAnimationFrame;
    exports.getCanvasBitmapStyle = getCanvasBitmapStyle;
    exports.getCreateImage = getCreateImage;
    exports.getGradientColor = getGradientColor;
    exports.getRGBA = getRGBA;
    exports.getRequestAnimationFrame = getRequestAnimationFrame;
    exports.getTintedTexture = getTintedTexture;
    exports.getUrlFileExtension = getUrlFileExtension;
    exports.hex2rgb = hex2rgb$1;
    exports.hex2string = hex2string;
    exports.initedByCanvas = initedByCanvas;
    exports.inputFeildIosEnable = inputFeildIosEnable;
    exports.interleave2 = interleave2;
    exports.interleave3 = interleave3;
    exports.isPow2 = isPow2;
    exports.isWebGLSupported = isWebGLSupported;
    exports.log10 = log10;
    exports.log2 = log2;
    exports.mapCanvasBlendModes = mapCanvasBlendModes;
    exports.mapWebGLBlendModes = mapWebGLBlendModes;
    exports.max = max;
    exports.min = min;
    exports.nextCombination = nextCombination;
    exports.nextPow2 = nextPow2;
    exports.osType = osType;
    exports.parity = parity;
    exports.popCount = popCount;
    exports.premultiplyBlendMode = premultiplyBlendMode;
    exports.premultiplyTint = premultiplyTint;
    exports.prevPow2 = prevPow2;
    exports.removeItems = removeItems;
    exports.reverse = reverse;
    exports.rgb2hex = rgb2hex$1;
    exports.sign = sign;
    exports.sin = sin;
    exports.string2hex = string2hex;
    exports.toDisplayDataURL = toDisplayDataURL;
    exports.uid = uid;

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

})));
