diff --git a/README.md b/README.md index 9919f43b..7ad9c452 100644 --- a/README.md +++ b/README.md @@ -30,7 +30,7 @@ - [x] 简易2d 向量类 - [x] 掩码实用类 - [x] 贝塞尔曲线 - - [ ] 快速随机数类 + - [x] 快速随机数类 - [x] BreadthFirst 寻路算法 - [x] Dijkstra 寻路算法 - [x] 事件处理器 @@ -51,10 +51,10 @@ Scene是ecs包含系统和实体最外面的容器。 ## 组件(Component) 组件应该只包含数据而没有逻辑代码。对数据进行逻辑是系统的工作。 - + ## 系统(System) ecs中的系统会不断的更新实体。系统使用过滤器选择某些实体,然后仅更新那些选择的实体。 - + ## 作者其他库(egret) - [行为树/实用AI 系统](https://github.com/esengine/egret-BehaviourTree-ai) diff --git a/demo/libs/framework/framework.d.ts b/demo/libs/framework/framework.d.ts index 0bf8e9b5..68e981e1 100644 --- a/demo/libs/framework/framework.d.ts +++ b/demo/libs/framework/framework.d.ts @@ -649,6 +649,9 @@ declare class Matcher { exclude(...types: any[]): this; one(...types: any[]): this; } +declare class ObjectUtils { + static clone(p: any, c?: T): T; +} declare class RenderableComponentList { private _components; readonly count: number; @@ -657,6 +660,29 @@ declare class RenderableComponentList { remove(component: IRenderable): void; updateList(): void; } +declare class StringUtils { + static matchChineseWord(str: string): string[]; + static lTrim(target: string): string; + static rTrim(target: string): string; + static trim(target: string): string; + static isWhiteSpace(str: string): boolean; + static replaceMatch(mainStr: string, targetStr: string, replaceStr: string, caseMark?: boolean): string; + private static specialSigns; + static htmlSpecialChars(str: string, reversion?: boolean): string; + static zfill(str: string, width?: number): string; + static reverse(str: string): string; + static cutOff(str: string, start: number, len: number, order?: boolean): string; + static strReplace(str: string, rStr: string[]): string; +} +declare class TextureUtils { + static sharedCanvas: HTMLCanvasElement; + static sharedContext: CanvasRenderingContext2D; + static convertImageToCanvas(texture: egret.Texture, rect?: egret.Rectangle): HTMLCanvasElement; + static toDataURL(type: string, texture: egret.Texture, rect?: egret.Rectangle, encoderOptions?: any): string; + static eliFoTevas(type: string, texture: egret.Texture, filePath: string, rect?: egret.Rectangle, encoderOptions?: any): void; + static getPixel32(texture: egret.Texture, x: number, y: number): number[]; + static getPixels(texture: egret.Texture, x: number, y: number, width?: number, height?: number): number[]; +} declare class Time { static unscaledDeltaTime: any; static deltaTime: number; @@ -668,18 +694,21 @@ declare class Time { static sceneChanged(): void; static checkEvery(interval: number): boolean; } -declare class GraphicsCapabilities { - supportsTextureFilterAnisotropic: boolean; - supportsNonPowerOfTwo: boolean; - supportsDepth24: boolean; - supportsPackedDepthStencil: boolean; - supportsDepthNonLinear: boolean; - supportsTextureMaxLevel: boolean; - supportsS3tc: boolean; - supportsDxt1: boolean; - supportsPvrtc: boolean; - supportsAtitc: boolean; - supportsFramebufferObjectARB: boolean; +declare class TimeUtils { + static monthId(d?: Date): number; + static dateId(t?: Date): number; + static weekId(d?: Date, first?: boolean): number; + static diffDay(a: Date, b: Date, fixOne?: boolean): number; + static getFirstDayOfWeek(d?: Date): Date; + static getFirstOfDay(d?: Date): Date; + static getNextFirstOfDay(d?: Date): Date; + static formatDate(date: Date): string; + static formatDateTime(date: Date): string; + static parseDate(s: string): Date; + static secondToTime(time?: number, partition?: string, showHour?: boolean): string; + static timeToMillisecond(time: string, partition?: string): string; +} +declare class GraphicsCapabilities extends egret.Capabilities { initialize(device: GraphicsDevice): void; private platformInitialize; } @@ -1038,7 +1067,20 @@ declare class NumberDictionary { tryGetValue(x: number, y: number): Collider[]; clear(): void; } -declare class fui { +declare class ArrayUtils { + static bubbleSort(ary: number[]): void; + static insertionSort(ary: number[]): void; + static binarySearch(ary: number[], value: number): number; + static findElementIndex(ary: any[], num: any): any; + static getMaxElementIndex(ary: number[]): number; + static getMinElementIndex(ary: number[]): number; + static getUniqueAry(ary: number[]): number[]; + static getDifferAry(aryA: number[], aryB: number[]): number[]; + static swap(array: any[], index1: number, index2: number): void; + static clearList(ary: any[]): void; + static cloneList(ary: any[]): any[]; + static equals(ary1: number[], ary2: number[]): Boolean; + static insert(ary: any[], index: number, value: any): any; } declare class ContentManager { protected loadedAssets: Map; @@ -1107,6 +1149,90 @@ declare class Input { private static setpreviousTouchState; static scaledPosition(position: Vector2): Vector2; } +declare class KeyboardUtils { + static TYPE_KEY_DOWN: number; + static TYPE_KEY_UP: number; + private static keyDownDict; + private static keyUpDict; + static A: string; + static B: string; + static C: string; + static D: string; + static E: string; + static F: string; + static G: string; + static H: string; + static I: string; + static J: string; + static K: string; + static L: string; + static M: string; + static N: string; + static O: string; + static P: string; + static Q: string; + static R: string; + static S: string; + static T: string; + static U: string; + static V: string; + static W: string; + static X: string; + static Y: string; + static Z: string; + static ESC: string; + static F1: string; + static F2: string; + static F3: string; + static F4: string; + static F5: string; + static F6: string; + static F7: string; + static F8: string; + static F9: string; + static F10: string; + static F11: string; + static F12: string; + static NUM_1: string; + static NUM_2: string; + static NUM_3: string; + static NUM_4: string; + static NUM_5: string; + static NUM_6: string; + static NUM_7: string; + static NUM_8: string; + static NUM_9: string; + static NUM_0: string; + static TAB: string; + static CTRL: string; + static ALT: string; + static SHIFT: string; + static CAPS_LOCK: string; + static ENTER: string; + static SPACE: string; + static BACK_SPACE: string; + static INSERT: string; + static DELETE: string; + static HOME: string; + static END: string; + static PAGE_UP: string; + static PAGE_DOWN: string; + static LEFT: string; + static RIGHT: string; + static UP: string; + static DOWN: string; + static PAUSE_BREAK: string; + static NUM_LOCK: string; + static SCROLL_LOCK: string; + static WINDOWS: string; + static init(): void; + private static onKeyDonwHander; + private static onKeyUpHander; + static registerKey(key: string, fun: Function, thisObj: any, type?: number, ...args: any[]): void; + static unregisterKey(key: string, type?: number): void; + private static keyCodeToString; + static destroy(): void; +} declare class ListPool { private static readonly _objectQueue; static warmCache(cacheCount: number): void; @@ -1133,6 +1259,17 @@ declare class Pair { clear(): void; equals(other: Pair): boolean; } +declare class RandomUtils { + static randrange(start: number, stop: number, step?: number): number; + static randint(a: number, b: number): number; + static randnum(a: number, b: number): number; + static shuffle(array: any[]): any[]; + private static _randomCompare; + static choice(sequence: any): any; + static sample(sequence: any[], num: number): any[]; + static random(): number; + static boolean(chance?: number): boolean; +} declare class RectangleExt { static union(first: Rectangle, point: Vector2): Rectangle; } diff --git a/demo/libs/framework/framework.js b/demo/libs/framework/framework.js index 9bd9a05c..e64b16f3 100644 --- a/demo/libs/framework/framework.js +++ b/demo/libs/framework/framework.js @@ -300,7 +300,6 @@ var AStarPathfinder = (function () { return "break"; } graph.getNeighbors(current.data).forEach(function (next) { - console.log(next); var newCost = costSoFar.get(current.data) + graph.cost(current.data, next); if (!_this.hasKey(costSoFar, next) || newCost < costSoFar.get(next)) { costSoFar.set(next, newCost); @@ -3040,6 +3039,25 @@ var Matcher = (function () { }; return Matcher; }()); +var ObjectUtils = (function () { + function ObjectUtils() { + } + ObjectUtils.clone = function (p, c) { + if (c === void 0) { c = null; } + var c = c || {}; + for (var i in p) { + if (typeof p[i] === 'object') { + c[i] = p[i] instanceof Array ? [] : {}; + this.clone(p[i], c[i]); + } + else { + c[i] = p[i]; + } + } + return c; + }; + return ObjectUtils; +}()); var RenderableComponentList = (function () { function RenderableComponentList() { this._components = []; @@ -3068,6 +3086,276 @@ var RenderableComponentList = (function () { }; return RenderableComponentList; }()); +var StringUtils = (function () { + function StringUtils() { + } + StringUtils.matchChineseWord = function (str) { + var patternA = /[\u4E00-\u9FA5]+/gim; + return str.match(patternA); + }; + StringUtils.lTrim = function (target) { + var startIndex = 0; + while (this.isWhiteSpace(target.charAt(startIndex))) { + startIndex++; + } + return target.slice(startIndex, target.length); + }; + StringUtils.rTrim = function (target) { + var endIndex = target.length - 1; + while (this.isWhiteSpace(target.charAt(endIndex))) { + endIndex--; + } + return target.slice(0, endIndex + 1); + }; + StringUtils.trim = function (target) { + if (target == null) { + return null; + } + return this.rTrim(this.lTrim(target)); + }; + StringUtils.isWhiteSpace = function (str) { + if (str == " " || str == "\t" || str == "\r" || str == "\n") + return true; + return false; + }; + StringUtils.replaceMatch = function (mainStr, targetStr, replaceStr, caseMark) { + if (caseMark === void 0) { caseMark = false; } + var len = mainStr.length; + var tempStr = ""; + var isMatch = false; + var tempTarget = caseMark == true ? targetStr.toLowerCase() : targetStr; + for (var i = 0; i < len; i++) { + isMatch = false; + if (mainStr.charAt(i) == tempTarget.charAt(0)) { + if (mainStr.substr(i, tempTarget.length) == tempTarget) { + isMatch = true; + } + } + if (isMatch) { + tempStr += replaceStr; + i = i + tempTarget.length - 1; + } + else { + tempStr += mainStr.charAt(i); + } + } + return tempStr; + }; + StringUtils.htmlSpecialChars = function (str, reversion) { + if (reversion === void 0) { reversion = false; } + var len = this.specialSigns.length; + for (var i = 0; i < len; i += 2) { + var from = void 0; + var to = void 0; + from = this.specialSigns[i]; + to = this.specialSigns[i + 1]; + if (reversion) { + var temp = from; + from = to; + to = temp; + } + str = this.replaceMatch(str, from, to); + } + return str; + }; + StringUtils.zfill = function (str, width) { + if (width === void 0) { width = 2; } + if (!str) { + return str; + } + width = Math.floor(width); + var slen = str.length; + if (slen >= width) { + return str; + } + var negative = false; + if (str.substr(0, 1) == '-') { + negative = true; + str = str.substr(1); + } + var len = width - slen; + for (var i = 0; i < len; i++) { + str = '0' + str; + } + if (negative) { + str = '-' + str; + } + return str; + }; + StringUtils.reverse = function (str) { + if (str.length > 1) + return this.reverse(str.substring(1)) + str.substring(0, 1); + else + return str; + }; + StringUtils.cutOff = function (str, start, len, order) { + if (order === void 0) { order = true; } + start = Math.floor(start); + len = Math.floor(len); + var length = str.length; + if (start > length) + start = length; + var s = start; + var e = start + len; + var newStr; + if (order) { + newStr = str.substring(0, s) + str.substr(e, length); + } + else { + s = length - 1 - start - len; + e = s + len; + newStr = str.substring(0, s + 1) + str.substr(e + 1, length); + } + return newStr; + }; + StringUtils.strReplace = function (str, rStr) { + var i = 0, len = rStr.length; + for (; i < len; i++) { + if (rStr[i] == null || rStr[i] == "") { + rStr[i] = "无"; + } + str = str.replace("{" + i + "}", rStr[i]); + } + return str; + }; + StringUtils.specialSigns = [ + '&', '&', + '<', '<', + '>', '>', + '"', '"', + "'", ''', + '®', '®', + '©', '©', + '™', '™', + ]; + return StringUtils; +}()); +var TextureUtils = (function () { + function TextureUtils() { + } + TextureUtils.convertImageToCanvas = function (texture, rect) { + if (!this.sharedCanvas) { + this.sharedCanvas = egret.sys.createCanvas(); + this.sharedContext = this.sharedCanvas.getContext("2d"); + } + var w = texture.$getTextureWidth(); + var h = texture.$getTextureHeight(); + if (!rect) { + rect = egret.$TempRectangle; + rect.x = 0; + rect.y = 0; + rect.width = w; + rect.height = h; + } + rect.x = Math.min(rect.x, w - 1); + rect.y = Math.min(rect.y, h - 1); + rect.width = Math.min(rect.width, w - rect.x); + rect.height = Math.min(rect.height, h - rect.y); + var iWidth = Math.floor(rect.width); + var iHeight = Math.floor(rect.height); + var surface = this.sharedCanvas; + surface["style"]["width"] = iWidth + "px"; + surface["style"]["height"] = iHeight + "px"; + this.sharedCanvas.width = iWidth; + this.sharedCanvas.height = iHeight; + if (egret.Capabilities.renderMode == "webgl") { + var renderTexture = void 0; + if (!texture.$renderBuffer) { + if (egret.sys.systemRenderer["renderClear"]) { + egret.sys.systemRenderer["renderClear"](); + } + renderTexture = new egret.RenderTexture(); + renderTexture.drawToTexture(new egret.Bitmap(texture)); + } + else { + renderTexture = texture; + } + var pixels = renderTexture.$renderBuffer.getPixels(rect.x, rect.y, iWidth, iHeight); + var x = 0; + var y = 0; + for (var i = 0; i < pixels.length; i += 4) { + this.sharedContext.fillStyle = + 'rgba(' + pixels[i] + + ',' + pixels[i + 1] + + ',' + pixels[i + 2] + + ',' + (pixels[i + 3] / 255) + ')'; + this.sharedContext.fillRect(x, y, 1, 1); + x++; + if (x == iWidth) { + x = 0; + y++; + } + } + if (!texture.$renderBuffer) { + renderTexture.dispose(); + } + return surface; + } + else { + var bitmapData = texture; + var offsetX = Math.round(bitmapData.$offsetX); + var offsetY = Math.round(bitmapData.$offsetY); + var bitmapWidth = bitmapData.$bitmapWidth; + var bitmapHeight = bitmapData.$bitmapHeight; + var $TextureScaleFactor = SceneManager.stage.textureScaleFactor; + this.sharedContext.drawImage(bitmapData.$bitmapData.source, bitmapData.$bitmapX + rect.x / $TextureScaleFactor, bitmapData.$bitmapY + rect.y / $TextureScaleFactor, bitmapWidth * rect.width / w, bitmapHeight * rect.height / h, offsetX, offsetY, rect.width, rect.height); + return surface; + } + }; + TextureUtils.toDataURL = function (type, texture, rect, encoderOptions) { + try { + var surface = this.convertImageToCanvas(texture, rect); + var result = surface.toDataURL(type, encoderOptions); + return result; + } + catch (e) { + egret.$error(1033); + } + return null; + }; + TextureUtils.eliFoTevas = function (type, texture, filePath, rect, encoderOptions) { + var surface = this.convertImageToCanvas(texture, rect); + var result = surface.toTempFilePathSync({ + fileType: type.indexOf("png") >= 0 ? "png" : "jpg" + }); + wx.getFileSystemManager().saveFile({ + tempFilePath: result, + filePath: wx.env.USER_DATA_PATH + "/" + filePath, + success: function (res) { + } + }); + return result; + }; + TextureUtils.getPixel32 = function (texture, x, y) { + egret.$warn(1041, "getPixel32", "getPixels"); + return texture.getPixels(x, y); + }; + TextureUtils.getPixels = function (texture, x, y, width, height) { + if (width === void 0) { width = 1; } + if (height === void 0) { height = 1; } + if (egret.Capabilities.renderMode == "webgl") { + var renderTexture = void 0; + if (!texture.$renderBuffer) { + renderTexture = new egret.RenderTexture(); + renderTexture.drawToTexture(new egret.Bitmap(texture)); + } + else { + renderTexture = texture; + } + var pixels = renderTexture.$renderBuffer.getPixels(x, y, width, height); + return pixels; + } + try { + var surface = this.convertImageToCanvas(texture); + var result = this.sharedContext.getImageData(x, y, width, height).data; + return result; + } + catch (e) { + egret.$error(1039); + } + }; + return TextureUtils; +}()); var Time = (function () { function Time() { } @@ -3091,29 +3379,189 @@ var Time = (function () { Time._lastTime = 0; return Time; }()); -var GraphicsCapabilities = (function () { +var TimeUtils = (function () { + function TimeUtils() { + } + TimeUtils.monthId = function (d) { + if (d === void 0) { d = null; } + d = d ? d : new Date(); + var y = d.getFullYear(); + var m = d.getMonth() + 1; + var g = m < 10 ? "0" : ""; + return parseInt(y + g + m); + }; + TimeUtils.dateId = function (t) { + if (t === void 0) { t = null; } + t = t ? t : new Date(); + var m = t.getMonth() + 1; + var a = m < 10 ? "0" : ""; + var d = t.getDate(); + var b = d < 10 ? "0" : ""; + return parseInt(t.getFullYear() + a + m + b + d); + }; + TimeUtils.weekId = function (d, first) { + if (d === void 0) { d = null; } + if (first === void 0) { first = true; } + d = d ? d : new Date(); + var c = new Date(); + c.setTime(d.getTime()); + c.setDate(1); + c.setMonth(0); + var year = c.getFullYear(); + var firstDay = c.getDay(); + if (firstDay == 0) { + firstDay = 7; + } + var max = false; + if (firstDay <= 4) { + max = firstDay > 1; + c.setDate(c.getDate() - (firstDay - 1)); + } + else { + c.setDate(c.getDate() + 7 - firstDay + 1); + } + var num = this.diffDay(d, c, false); + if (num < 0) { + c.setDate(1); + c.setMonth(0); + c.setDate(c.getDate() - 1); + return this.weekId(c, false); + } + var week = num / 7; + var weekIdx = Math.floor(week) + 1; + if (weekIdx == 53) { + c.setTime(d.getTime()); + c.setDate(c.getDate() - 1); + var endDay = c.getDay(); + if (endDay == 0) { + endDay = 7; + } + if (first && (!max || endDay < 4)) { + c.setFullYear(c.getFullYear() + 1); + c.setDate(1); + c.setMonth(0); + return this.weekId(c, false); + } + } + var g = weekIdx > 9 ? "" : "0"; + var s = year + "00" + g + weekIdx; + return parseInt(s); + }; + TimeUtils.diffDay = function (a, b, fixOne) { + if (fixOne === void 0) { fixOne = false; } + var x = (a.getTime() - b.getTime()) / 86400000; + return fixOne ? Math.ceil(x) : Math.floor(x); + }; + TimeUtils.getFirstDayOfWeek = function (d) { + d = d ? d : new Date(); + var day = d.getDay() || 7; + return new Date(d.getFullYear(), d.getMonth(), d.getDate() + 1 - day, 0, 0, 0, 0); + }; + TimeUtils.getFirstOfDay = function (d) { + d = d ? d : new Date(); + d.setHours(0, 0, 0, 0); + return d; + }; + TimeUtils.getNextFirstOfDay = function (d) { + return new Date(this.getFirstOfDay(d).getTime() + 86400000); + }; + TimeUtils.formatDate = function (date) { + var y = date.getFullYear(); + var m = date.getMonth() + 1; + m = m < 10 ? '0' + m : m; + var d = date.getDate(); + d = d < 10 ? ('0' + d) : d; + return y + '-' + m + '-' + d; + }; + TimeUtils.formatDateTime = function (date) { + var y = date.getFullYear(); + var m = date.getMonth() + 1; + m = m < 10 ? ('0' + m) : m; + var d = date.getDate(); + d = d < 10 ? ('0' + d) : d; + var h = date.getHours(); + var i = date.getMinutes(); + i = i < 10 ? ('0' + i) : i; + var s = date.getSeconds(); + s = s < 10 ? ('0' + s) : s; + return y + '-' + m + '-' + d + ' ' + h + ':' + i + ":" + s; + }; + TimeUtils.parseDate = function (s) { + var t = Date.parse(s); + if (!isNaN(t)) { + return new Date(Date.parse(s.replace(/-/g, "/"))); + } + else { + return new Date(); + } + }; + TimeUtils.secondToTime = function (time, partition, showHour) { + if (time === void 0) { time = 0; } + if (partition === void 0) { partition = ":"; } + if (showHour === void 0) { showHour = true; } + var hours = Math.floor(time / 3600); + var minutes = Math.floor(time % 3600 / 60); + var seconds = Math.floor(time % 3600 % 60); + var h = hours.toString(); + var m = minutes.toString(); + var s = seconds.toString(); + if (hours < 10) + h = "0" + h; + if (minutes < 10) + m = "0" + m; + if (seconds < 10) + s = "0" + s; + var timeStr; + if (showHour) + timeStr = h + partition + m + partition + s; + else + timeStr = m + partition + s; + return timeStr; + }; + TimeUtils.timeToMillisecond = function (time, partition) { + if (partition === void 0) { partition = ":"; } + var _ary = time.split(partition); + var timeNum = 0; + var len = _ary.length; + for (var i = 0; i < len; i++) { + var n = _ary[i]; + timeNum += n * Math.pow(60, (len - 1 - i)); + } + timeNum *= 1000; + return timeNum.toString(); + }; + return TimeUtils; +}()); +var GraphicsCapabilities = (function (_super) { + __extends(GraphicsCapabilities, _super); function GraphicsCapabilities() { + return _super !== null && _super.apply(this, arguments) || this; } GraphicsCapabilities.prototype.initialize = function (device) { this.platformInitialize(device); }; GraphicsCapabilities.prototype.platformInitialize = function (device) { - var gl = new egret.sys.RenderBuffer().context.getInstance(); - this.supportsNonPowerOfTwo = false; - this.supportsTextureFilterAnisotropic = gl.getExtension("EXT_texture_filter_anisotropic") != null; - this.supportsDepth24 = true; - this.supportsPackedDepthStencil = true; - this.supportsDepthNonLinear = false; - this.supportsTextureMaxLevel = true; - this.supportsS3tc = gl.getExtension("WEBGL_compressed_texture_s3tc") != null || - gl.getExtension("WEBGL_compressed_texture_s3tc_srgb") != null; - this.supportsDxt1 = this.supportsS3tc; - this.supportsPvrtc = false; - this.supportsAtitc = gl.getExtension("WEBGL_compressed_texture_astc") != null; - this.supportsFramebufferObjectARB = false; + var capabilities = this; + capabilities["isMobile"] = true; + var systemInfo = wx.getSystemInfoSync(); + var systemStr = systemInfo.system.toLowerCase(); + if (systemStr.indexOf("ios") > -1) { + capabilities["os"] = "iOS"; + } + else if (systemStr.indexOf("android") > -1) { + capabilities["os"] = "Android"; + } + var language = systemInfo.language; + if (language.indexOf('zh') > -1) { + language = "zh-CN"; + } + else { + language = "en-US"; + } + capabilities["language"] = language; }; return GraphicsCapabilities; -}()); +}(egret.Capabilities)); var GraphicsDevice = (function () { function GraphicsDevice() { this.graphicsCapabilities = new GraphicsCapabilities(); @@ -4876,6 +5324,170 @@ var NumberDictionary = (function () { }; return NumberDictionary; }()); +var ArrayUtils = (function () { + function ArrayUtils() { + } + ArrayUtils.bubbleSort = function (ary) { + var isExchange = false; + for (var i = 0; i < ary.length; i++) { + isExchange = false; + for (var j = ary.length - 1; j > i; j--) { + if (ary[j] < ary[j - 1]) { + var temp = ary[j]; + ary[j] = ary[j - 1]; + ary[j - 1] = temp; + isExchange = true; + } + } + if (!isExchange) + break; + } + }; + ArrayUtils.insertionSort = function (ary) { + var len = ary.length; + for (var i = 1; i < len; i++) { + var val = ary[i]; + for (var j = i; j > 0 && ary[j - 1] > val; j--) { + ary[j] = ary[j - 1]; + } + ary[j] = val; + } + }; + ArrayUtils.binarySearch = function (ary, value) { + var startIndex = 0; + var endIndex = ary.length; + var sub = (startIndex + endIndex) >> 1; + while (startIndex < endIndex) { + if (value <= ary[sub]) + endIndex = sub; + else if (value >= ary[sub]) + startIndex = sub + 1; + sub = (startIndex + endIndex) >> 1; + } + if (ary[startIndex] == value) + return startIndex; + return -1; + }; + ArrayUtils.findElementIndex = function (ary, num) { + var len = ary.length; + for (var i = 0; i < len; ++i) { + if (ary[i] == num) + return i; + } + return null; + }; + ArrayUtils.getMaxElementIndex = function (ary) { + var matchIndex = 0; + var len = ary.length; + for (var j = 1; j < len; j++) { + if (ary[j] > ary[matchIndex]) + matchIndex = j; + } + return matchIndex; + }; + ArrayUtils.getMinElementIndex = function (ary) { + var matchIndex = 0; + var len = ary.length; + for (var j = 1; j < len; j++) { + if (ary[j] < ary[matchIndex]) + matchIndex = j; + } + return matchIndex; + }; + ArrayUtils.getUniqueAry = function (ary) { + var uAry = []; + var newAry = []; + var count = ary.length; + for (var i = 0; i < count; ++i) { + var value = ary[i]; + if (uAry.indexOf(value) == -1) + uAry.push(value); + } + count = uAry.length; + for (var i = count - 1; i >= 0; --i) { + newAry.unshift(uAry[i]); + } + return newAry; + }; + ArrayUtils.getDifferAry = function (aryA, aryB) { + aryA = this.getUniqueAry(aryA); + aryB = this.getUniqueAry(aryB); + var ary = aryA.concat(aryB); + var uObj = new Object(); + var newAry = []; + var count = ary.length; + for (var j = 0; j < count; ++j) { + if (!uObj[ary[j]]) { + uObj[ary[j]] = new Object(); + uObj[ary[j]].count = 0; + uObj[ary[j]].key = ary[j]; + uObj[ary[j]].count++; + } + else { + if (uObj[ary[j]] instanceof Object) { + uObj[ary[j]].count++; + } + } + } + for (var i in uObj) { + if (uObj[i].count != 2) { + newAry.unshift(uObj[i].key); + } + } + return newAry; + }; + ArrayUtils.swap = function (array, index1, index2) { + var temp = array[index1]; + array[index1] = array[index2]; + array[index2] = temp; + }; + ArrayUtils.clearList = function (ary) { + if (!ary) + return; + var length = ary.length; + for (var i = length - 1; i >= 0; i -= 1) { + ary.splice(i, 1); + } + }; + ArrayUtils.cloneList = function (ary) { + if (!ary) + return null; + return ary.slice(0, ary.length); + }; + ArrayUtils.equals = function (ary1, ary2) { + if (ary1 == ary2) + return true; + var length = ary1.length; + if (length != ary2.length) + return false; + while (length--) { + if (ary1[length] != ary2[length]) + return false; + } + return true; + }; + ArrayUtils.insert = function (ary, index, value) { + if (!ary) + return null; + var length = ary.length; + if (index > length) + index = length; + if (index < 0) + index = 0; + if (index == length) + ary.push(value); + else if (index == 0) + ary.unshift(value); + else { + for (var i = length - 1; i >= index; i -= 1) { + ary[i + 1] = ary[i]; + } + ary[index] = value; + } + return value; + }; + return ArrayUtils; +}()); var ContentManager = (function () { function ContentManager() { this.loadedAssets = new Map(); @@ -5199,6 +5811,206 @@ var Input = (function () { Input._totalTouchCount = 0; return Input; }()); +var KeyboardUtils = (function () { + function KeyboardUtils() { + } + KeyboardUtils.init = function () { + this.keyDownDict = {}; + this.keyUpDict = {}; + document.addEventListener("keydown", this.onKeyDonwHander); + document.addEventListener("keyup", this.onKeyUpHander); + }; + KeyboardUtils.onKeyDonwHander = function (event) { + if (!this.keyDownDict) + return; + var key = this.keyCodeToString(event.keyCode); + var o = this.keyDownDict[key]; + if (o) { + var fun = o["fun"]; + var thisObj = o["thisObj"]; + var args = o["args"]; + fun.apply(thisObj, args); + } + }; + KeyboardUtils.onKeyUpHander = function (event) { + if (!this.keyUpDict) + return; + var key = this.keyCodeToString(event.keyCode); + var o = this.keyUpDict[key]; + if (o) { + var fun = o["fun"]; + var thisObj = o["thisObj"]; + var args = o["args"]; + fun.apply(thisObj, args); + } + }; + KeyboardUtils.registerKey = function (key, fun, thisObj, type) { + if (type === void 0) { type = 0; } + var args = []; + for (var _i = 4; _i < arguments.length; _i++) { + args[_i - 4] = arguments[_i]; + } + var keyDict = type ? this.keyUpDict : this.keyDownDict; + keyDict[key] = { "fun": fun, args: args, "thisObj": thisObj }; + }; + KeyboardUtils.unregisterKey = function (key, type) { + if (type === void 0) { type = 0; } + var keyDict = type ? this.keyUpDict : this.keyDownDict; + delete keyDict[key]; + }; + KeyboardUtils.keyCodeToString = function (keyCode) { + switch (keyCode) { + case 8: + return this.BACK_SPACE; + case 9: + return this.TAB; + case 13: + return this.ENTER; + case 16: + return this.SHIFT; + case 17: + return this.CTRL; + case 19: + return this.PAUSE_BREAK; + case 20: + return this.CAPS_LOCK; + case 27: + return this.ESC; + case 32: + return this.SPACE; + case 33: + return this.PAGE_UP; + case 34: + return this.PAGE_DOWN; + case 35: + return this.END; + case 36: + return this.HOME; + case 37: + return this.LEFT; + case 38: + return this.UP; + case 39: + return this.RIGHT; + case 40: + return this.DOWN; + case 45: + return this.INSERT; + case 46: + return this.DELETE; + case 91: + return this.WINDOWS; + case 112: + return this.F1; + case 113: + return this.F2; + case 114: + return this.F3; + case 115: + return this.F4; + case 116: + return this.F5; + case 117: + return this.F6; + case 118: + return this.F7; + case 119: + return this.F8; + case 120: + return this.F9; + case 122: + return this.F11; + case 123: + return this.F12; + case 144: + return this.NUM_LOCK; + case 145: + return this.SCROLL_LOCK; + default: + return String.fromCharCode(keyCode); + } + }; + KeyboardUtils.destroy = function () { + this.keyDownDict = null; + this.keyUpDict = null; + document.removeEventListener("keydown", this.onKeyDonwHander); + document.removeEventListener("keyup", this.onKeyUpHander); + }; + KeyboardUtils.TYPE_KEY_DOWN = 0; + KeyboardUtils.TYPE_KEY_UP = 1; + KeyboardUtils.A = "A"; + KeyboardUtils.B = "B"; + KeyboardUtils.C = "C"; + KeyboardUtils.D = "D"; + KeyboardUtils.E = "E"; + KeyboardUtils.F = "F"; + KeyboardUtils.G = "G"; + KeyboardUtils.H = "H"; + KeyboardUtils.I = "I"; + KeyboardUtils.J = "J"; + KeyboardUtils.K = "K"; + KeyboardUtils.L = "L"; + KeyboardUtils.M = "M"; + KeyboardUtils.N = "N"; + KeyboardUtils.O = "O"; + KeyboardUtils.P = "P"; + KeyboardUtils.Q = "Q"; + KeyboardUtils.R = "R"; + KeyboardUtils.S = "S"; + KeyboardUtils.T = "T"; + KeyboardUtils.U = "U"; + KeyboardUtils.V = "V"; + KeyboardUtils.W = "W"; + KeyboardUtils.X = "X"; + KeyboardUtils.Y = "Y"; + KeyboardUtils.Z = "Z"; + KeyboardUtils.ESC = "Esc"; + KeyboardUtils.F1 = "F1"; + KeyboardUtils.F2 = "F2"; + KeyboardUtils.F3 = "F3"; + KeyboardUtils.F4 = "F4"; + KeyboardUtils.F5 = "F5"; + KeyboardUtils.F6 = "F6"; + KeyboardUtils.F7 = "F7"; + KeyboardUtils.F8 = "F8"; + KeyboardUtils.F9 = "F9"; + KeyboardUtils.F10 = "F10"; + KeyboardUtils.F11 = "F11"; + KeyboardUtils.F12 = "F12"; + KeyboardUtils.NUM_1 = "1"; + KeyboardUtils.NUM_2 = "2"; + KeyboardUtils.NUM_3 = "3"; + KeyboardUtils.NUM_4 = "4"; + KeyboardUtils.NUM_5 = "5"; + KeyboardUtils.NUM_6 = "6"; + KeyboardUtils.NUM_7 = "7"; + KeyboardUtils.NUM_8 = "8"; + KeyboardUtils.NUM_9 = "9"; + KeyboardUtils.NUM_0 = "0"; + KeyboardUtils.TAB = "Tab"; + KeyboardUtils.CTRL = "Ctrl"; + KeyboardUtils.ALT = "Alt"; + KeyboardUtils.SHIFT = "Shift"; + KeyboardUtils.CAPS_LOCK = "Caps Lock"; + KeyboardUtils.ENTER = "Enter"; + KeyboardUtils.SPACE = "Space"; + KeyboardUtils.BACK_SPACE = "Back Space"; + KeyboardUtils.INSERT = "Insert"; + KeyboardUtils.DELETE = "Page Down"; + KeyboardUtils.HOME = "Home"; + KeyboardUtils.END = "Page Down"; + KeyboardUtils.PAGE_UP = "Page Up"; + KeyboardUtils.PAGE_DOWN = "Page Down"; + KeyboardUtils.LEFT = "Left"; + KeyboardUtils.RIGHT = "Right"; + KeyboardUtils.UP = "Up"; + KeyboardUtils.DOWN = "Down"; + KeyboardUtils.PAUSE_BREAK = "Pause Break"; + KeyboardUtils.NUM_LOCK = "Num Lock"; + KeyboardUtils.SCROLL_LOCK = "Scroll Lock"; + KeyboardUtils.WINDOWS = "Windows"; + return KeyboardUtils; +}()); var ListPool = (function () { function ListPool() { } @@ -5283,6 +6095,73 @@ var Pair = (function () { }; return Pair; }()); +var RandomUtils = (function () { + function RandomUtils() { + } + RandomUtils.randrange = function (start, stop, step) { + if (step === void 0) { step = 1; } + if (step == 0) + throw new Error('step 不能为 0'); + var width = stop - start; + if (width == 0) + throw new Error('没有可用的范围(' + start + ',' + stop + ')'); + if (width < 0) + width = start - stop; + var n = Math.floor((width + step - 1) / step); + return Math.floor(this.random() * n) * step + Math.min(start, stop); + }; + RandomUtils.randint = function (a, b) { + a = Math.floor(a); + b = Math.floor(b); + if (a > b) + a++; + else + b++; + return this.randrange(a, b); + }; + RandomUtils.randnum = function (a, b) { + return this.random() * (b - a) + a; + }; + RandomUtils.shuffle = function (array) { + array.sort(this._randomCompare); + return array; + }; + RandomUtils._randomCompare = function (a, b) { + return (this.random() > .5) ? 1 : -1; + }; + RandomUtils.choice = function (sequence) { + if (!sequence.hasOwnProperty("length")) + throw new Error('无法对此对象执行此操作'); + var index = Math.floor(this.random() * sequence.length); + if (sequence instanceof String) + return String(sequence).charAt(index); + else + return sequence[index]; + }; + RandomUtils.sample = function (sequence, num) { + var len = sequence.length; + if (num <= 0 || len < num) + throw new Error("采样数量不够"); + var selected = []; + var indices = []; + for (var i = 0; i < num; i++) { + var index = Math.floor(this.random() * len); + while (indices.indexOf(index) >= 0) + index = Math.floor(this.random() * len); + selected.push(sequence[index]); + indices.push(index); + } + return selected; + }; + RandomUtils.random = function () { + return Math.random(); + }; + RandomUtils.boolean = function (chance) { + if (chance === void 0) { chance = .5; } + return (this.random() < chance) ? true : false; + }; + return RandomUtils; +}()); var RectangleExt = (function () { function RectangleExt() { } diff --git a/demo/libs/framework/framework.min.js b/demo/libs/framework/framework.min.js index 4dd9e548..f10d4cd7 100644 --- a/demo/libs/framework/framework.min.js +++ b/demo/libs/framework/framework.min.js @@ -1 +1 @@ -window.framework={},window.__extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])};return function(e,n){function i(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}();var __awaiter=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(o,r){function s(t){try{c(i.next(t))}catch(t){r(t)}}function a(t){try{c(i.throw(t))}catch(t){r(t)}}function c(t){t.done?o(t.value):new n(function(e){e(t.value)}).then(s,a)}c((i=i.apply(t,e||[])).next())})},__generator=this&&this.__generator||function(t,e){var n,i,o,r,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return r={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(r[Symbol.iterator]=function(){return this}),r;function a(r){return function(a){return function(r){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,i&&(o=2&r[0]?i.return:r[0]?i.throw||((o=i.return)&&o.call(i),0):i.next)&&!(o=o.call(i,r[1])).done)return o;switch(i=0,o&&(r=[2&r[0],o.value]),r[0]){case 0:case 1:o=r;break;case 4:return s.label++,{value:r[1],done:!1};case 5:s.label++,i=r[1],r=[0];continue;case 7:r=s.ops.pop(),s.trys.pop();continue;default:if(!(o=(o=s.trys).length>0&&o[o.length-1])&&(6===r[0]||2===r[0])){s=0;continue}if(3===r[0]&&(!o||r[1]>o[0]&&r[1]-1}(this,t)},Array.prototype.firstOrDefault=function(t){return function(t,e){var n=t.findIndex(e);return-1==n?null:t[n]}(this,t)},Array.prototype.find=function(t){return function(t,e){return t.firstOrDefault(e)}(this,t)},Array.prototype.where=function(t){return function(t,e){if("function"==typeof t.reduce)return t.reduce(function(n,i,o){return e.call(arguments[2],i,o,t)&&n.push(i),n},[]);for(var n=[],i=0,o=t.length;i=0&&t.splice(n,1)}while(n>=0)}(this,t)},Array.prototype.remove=function(t){return function(t,e){var n=t.findIndex(function(t){return t===e});return n>=0&&(t.splice(n,1),!0)}(this,t)},Array.prototype.removeAt=function(t){return function(t,e){t.splice(e,1)}(this,t)},Array.prototype.removeRange=function(t,e){return function(t,e,n){t.splice(e,n)}(this,t,e)},Array.prototype.select=function(t){return function(t,e){if("function"==typeof t.reduce)return t.reduce(function(n,i,o){return n.push(e.call(arguments[2],i,o,t)),n},[]);for(var n=[],i=0,o=t.length;ir?1:-1}),t}(this,t,e)},Array.prototype.orderByDescending=function(t,e){return function(t,e,n){return t.sort(function(t,i){var o=e(t),r=e(i);return n?-n(o,r):o0;){if("break"===c())break}return o?this.recontructPath(r,e,n):null},t.hasKey=function(t,e){for(var n,i=t.keys();!(n=i.next()).done;)if(JSON.stringify(n.value)==JSON.stringify(e))return!0;return!1},t.getKey=function(t,e){for(var n,i,o=t.keys(),r=t.values();n=o.next(),i=r.next(),!n.done;)if(JSON.stringify(n.value)==JSON.stringify(e))return i.value;return null},t.recontructPath=function(t,e,n){var i=[],o=n;for(i.push(n);o!=e;)o=this.getKey(t,o),i.push(o);return i.reverse(),i},t}(),AStarNode=function(t){function e(e){var n=t.call(this)||this;return n.data=e,n}return __extends(e,t),e}(PriorityQueueNode),AstarGridGraph=function(){function t(t,e){this.dirs=[new Vector2(1,0),new Vector2(0,-1),new Vector2(-1,0),new Vector2(0,1)],this.walls=[],this.weightedNodes=[],this.defaultWeight=1,this.weightedNodeWeight=5,this._neighbors=new Array(4),this._width=t,this._height=e}return t.prototype.isNodeInBounds=function(t){return 0<=t.x&&t.x=this._nodes.length?(console.error("node.QueueIndex has been corrupted. Did you change it manually? Or add this node to another queue?"),!1):this._nodes[t.queueIndex]==t:(console.error("node cannot be null"),!1)},t.prototype.enqueue=function(t,e){t.priority=e,this._numNodes++,this._nodes[this._numNodes]=t,t.queueIndex=this._numNodes,t.insertionIndex=this._numNodesEverEnqueued++,this.cascadeUp(this._nodes[this._numNodes])},t.prototype.dequeue=function(){var t=this._nodes[1];return this.remove(t),t},t.prototype.remove=function(t){if(t.queueIndex==this._numNodes)return this._nodes[this._numNodes]=null,void this._numNodes--;var e=this._nodes[this._numNodes];this.swap(t,e),delete this._nodes[this._numNodes],this._numNodes--,this.onNodeUpdated(e)},t.prototype.isValidQueue=function(){for(var t=1;t0&&this.hasHigherPriority(t,n)?this.cascadeUp(t):this.cascadeDown(t)},t.prototype.cascadeDown=function(t){for(var e,n=t.queueIndex;;){e=t;var i=2*n;if(i>this._numNodes){t.queueIndex=n,this._nodes[n]=t;break}var o=this._nodes[i];this.hasHigherPriority(o,e)&&(e=o);var r=i+1;if(r<=this._numNodes){var s=this._nodes[r];this.hasHigherPriority(s,e)&&(e=s)}if(e==t){t.queueIndex=n,this._nodes[n]=t;break}this._nodes[n]=e;var a=e.queueIndex;e.queueIndex=n,n=a}},t.prototype.cascadeUp=function(t){for(var e=Math.floor(t.queueIndex/2);e>=1;){var n=this._nodes[e];if(this.hasHigherPriority(n,t))break;this.swap(t,n),e=Math.floor(t.queueIndex/2)}},t.prototype.swap=function(t,e){this._nodes[t.queueIndex]=e,this._nodes[e.queueIndex]=t;var n=t.queueIndex;t.queueIndex=e.queueIndex,e.queueIndex=n},t.prototype.hasHigherPriority=function(t,e){return t.priority0;){if("break"===a())break}return o?AStarPathfinder.recontructPath(s,e,n):null},t.hasKey=function(t,e){for(var n,i=t.keys();!(n=i.next()).done;)if(JSON.stringify(n.value)==JSON.stringify(e))return!0;return!1},t}(),UnweightedGraph=function(){function t(){this.edges=new Map}return t.prototype.addEdgesForNode=function(t,e){return this.edges.set(t,e),this},t.prototype.getNeighbors=function(t){return this.edges.get(t)},t}(),Vector2=function(){function t(t,e){this.x=0,this.y=0,this.x=t||0,this.y=e||this.x}return Object.defineProperty(t,"zero",{get:function(){return t.zeroVector2},enumerable:!0,configurable:!0}),Object.defineProperty(t,"one",{get:function(){return t.unitVector2},enumerable:!0,configurable:!0}),Object.defineProperty(t,"unitX",{get:function(){return t.unitXVector},enumerable:!0,configurable:!0}),Object.defineProperty(t,"unitY",{get:function(){return t.unitYVector},enumerable:!0,configurable:!0}),t.add=function(e,n){var i=new t(0,0);return i.x=e.x+n.x,i.y=e.y+n.y,i},t.divide=function(e,n){var i=new t(0,0);return i.x=e.x/n.x,i.y=e.y/n.y,i},t.multiply=function(e,n){var i=new t(0,0);return i.x=e.x*n.x,i.y=e.y*n.y,i},t.subtract=function(e,n){var i=new t(0,0);return i.x=e.x-n.x,i.y=e.y-n.y,i},t.prototype.normalize=function(){var t=1/Math.sqrt(this.x*this.x+this.y*this.y);this.x*=t,this.y*=t},t.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},t.prototype.round=function(){return new t(Math.round(this.x),Math.round(this.y))},t.normalize=function(t){var e=1/Math.sqrt(t.x*t.x+t.y*t.y);return t.x*=e,t.y*=e,t},t.dot=function(t,e){return t.x*e.x+t.y*e.y},t.distanceSquared=function(t,e){var n=t.x-e.x,i=t.y-e.y;return n*n+i*i},t.clamp=function(e,n,i){return new t(MathHelper.clamp(e.x,n.x,i.x),MathHelper.clamp(e.y,n.y,i.y))},t.lerp=function(e,n,i){return new t(MathHelper.lerp(e.x,n.x,i),MathHelper.lerp(e.y,n.y,i))},t.transform=function(e,n){return new t(e.x*n.m11+e.y*n.m21,e.x*n.m12+e.y*n.m22)},t.distance=function(t,e){var n=t.x-e.x,i=t.y-e.y;return Math.sqrt(n*n+i*i)},t.negate=function(e){var n=new t;return n.x=-e.x,n.y=-e.y,n},t.unitYVector=new t(0,1),t.unitXVector=new t(1,0),t.unitVector2=new t(1,1),t.zeroVector2=new t(0,0),t}(),UnweightedGridGraph=function(){function t(e,n,i){void 0===i&&(i=!1),this.walls=[],this._neighbors=new Array(4),this._width=e,this._hegiht=n,this._dirs=i?t.COMPASS_DIRS:t.CARDINAL_DIRS}return t.prototype.isNodeInBounds=function(t){return 0<=t.x&&t.x0;){if("break"===c())break}return o?this.recontructPath(r,e,n):null},t.hasKey=function(t,e){for(var n,i=t.keys();!(n=i.next()).done;)if(JSON.stringify(n.value)==JSON.stringify(e))return!0;return!1},t.getKey=function(t,e){for(var n,i,o=t.keys(),r=t.values();n=o.next(),i=r.next(),!n.done;)if(JSON.stringify(n.value)==JSON.stringify(e))return i.value;return null},t.recontructPath=function(t,e,n){var i=[],o=n;for(i.push(n);o!=e;)o=this.getKey(t,o),i.push(o);return i.reverse(),i},t}(),Debug=function(){function t(){}return t.drawHollowRect=function(t,e,n){void 0===n&&(n=0),this._debugDrawItems.push(new DebugDrawItem(t,e,n))},t.render=function(){if(this._debugDrawItems.length>0){var t=new egret.Shape;SceneManager.scene&&SceneManager.scene.addChild(t);for(var e=this._debugDrawItems.length-1;e>=0;e--){this._debugDrawItems[e].draw(t)&&this._debugDrawItems.removeAt(e)}}},t._debugDrawItems=[],t}(),DebugDefaults=function(){function t(){}return t.verletParticle=14431326,t.verletConstraintEdge=4406838,t}();!function(t){t[t.line=0]="line",t[t.hollowRectangle=1]="hollowRectangle",t[t.pixel=2]="pixel",t[t.text=3]="text"}(DebugDrawType||(DebugDrawType={}));var CoreEvents,DebugDrawItem=function(){function t(t,e,n){this.rectangle=t,this.color=e,this.duration=n,this.drawType=DebugDrawType.hollowRectangle}return t.prototype.draw=function(t){switch(this.drawType){case DebugDrawType.line:DrawUtils.drawLine(t,this.start,this.end,this.color);break;case DebugDrawType.hollowRectangle:DrawUtils.drawHollowRect(t,this.rectangle,this.color);break;case DebugDrawType.pixel:DrawUtils.drawPixel(t,new Vector2(this.x,this.y),this.color,this.size);break;case DebugDrawType.text:}return this.duration-=Time.deltaTime,this.duration<0},t}(),Component=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e._enabled=!0,e.updateInterval=1,e._updateOrder=0,e}return __extends(e,t),Object.defineProperty(e.prototype,"enabled",{get:function(){return this.entity?this.entity.enabled&&this._enabled:this._enabled},set:function(t){this.setEnabled(t)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"localPosition",{get:function(){return new Vector2(this.entity.x+this.x,this.entity.y+this.y)},enumerable:!0,configurable:!0}),e.prototype.setEnabled=function(t){return this._enabled!=t&&(this._enabled=t,this._enabled?this.onEnabled():this.onDisabled()),this},Object.defineProperty(e.prototype,"updateOrder",{get:function(){return this._updateOrder},set:function(t){this.setUpdateOrder(t)},enumerable:!0,configurable:!0}),e.prototype.setUpdateOrder=function(t){return this._updateOrder!=t&&(this._updateOrder=t),this},e.prototype.initialize=function(){},e.prototype.onAddedToEntity=function(){},e.prototype.onRemovedFromEntity=function(){},e.prototype.onEnabled=function(){},e.prototype.onDisabled=function(){},e.prototype.debugRender=function(){},e.prototype.update=function(){},e.prototype.onEntityTransformChanged=function(t){},e.prototype.registerComponent=function(){this.entity.componentBits.set(ComponentTypeManager.getIndexFor(this),!1),this.entity.scene.entityProcessors.onComponentAdded(this.entity)},e.prototype.deregisterComponent=function(){this.entity.componentBits.set(ComponentTypeManager.getIndexFor(this)),this.entity.scene.entityProcessors.onComponentRemoved(this.entity)},e}(egret.DisplayObjectContainer);!function(t){t[t.SceneChanged=0]="SceneChanged"}(CoreEvents||(CoreEvents={}));var TransformComponent,Entity=function(t){function e(n){var i=t.call(this)||this;return i._updateOrder=0,i._enabled=!0,i._tag=0,i.name=n,i.components=new ComponentList(i),i.id=e._idGenerator++,i.componentBits=new BitSet,i.addEventListener(egret.Event.ADDED_TO_STAGE,i.onAddToStage,i),i}return __extends(e,t),Object.defineProperty(e.prototype,"isDestoryed",{get:function(){return this._isDestoryed},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"position",{get:function(){return new Vector2(this.x,this.y)},set:function(t){this.$setX(t.x),this.$setY(t.y),this.onEntityTransformChanged(TransformComponent.position)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"scale",{get:function(){return new Vector2(this.scaleX,this.scaleY)},set:function(t){this.$setScaleX(t.x),this.$setScaleY(t.y),this.onEntityTransformChanged(TransformComponent.scale)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"rotation",{get:function(){return this.$getRotation()},set:function(t){this.$setRotation(t),this.onEntityTransformChanged(TransformComponent.rotation)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"enabled",{get:function(){return this._enabled},set:function(t){this.setEnabled(t)},enumerable:!0,configurable:!0}),e.prototype.setEnabled=function(t){return this._enabled!=t&&(this._enabled=t),this},Object.defineProperty(e.prototype,"tag",{get:function(){return this._tag},set:function(t){this.setTag(t)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"stage",{get:function(){return this.scene?this.scene.stage:null},enumerable:!0,configurable:!0}),e.prototype.onAddToStage=function(){this.onEntityTransformChanged(TransformComponent.position)},Object.defineProperty(e.prototype,"updateOrder",{get:function(){return this._updateOrder},set:function(t){this.setUpdateOrder(t)},enumerable:!0,configurable:!0}),e.prototype.roundPosition=function(){this.position=Vector2Ext.round(this.position)},e.prototype.setUpdateOrder=function(t){if(this._updateOrder!=t)return this._updateOrder=t,this.scene,this},e.prototype.setTag=function(t){return this._tag!=t&&(this.scene&&this.scene.entities.removeFromTagList(this),this._tag=t,this.scene&&this.scene.entities.addToTagList(this)),this},e.prototype.attachToScene=function(t){this.scene=t,t.entities.add(this),this.components.registerAllComponents();for(var e=0;e=0;t--){this.getChildAt(t).entity.destroy()}},e}(egret.DisplayObjectContainer);!function(t){t[t.rotation=0]="rotation",t[t.scale=1]="scale",t[t.position=2]="position"}(TransformComponent||(TransformComponent={}));var CameraStyle,Scene=function(t){function e(){var e=t.call(this)||this;return e.enablePostProcessing=!0,e._renderers=[],e._postProcessors=[],e.entityProcessors=new EntityProcessorList,e.renderableComponents=new RenderableComponentList,e.entities=new EntityList(e),e.content=new ContentManager,e.width=SceneManager.stage.stageWidth,e.height=SceneManager.stage.stageHeight,e.addEventListener(egret.Event.ACTIVATE,e.onActive,e),e.addEventListener(egret.Event.DEACTIVATE,e.onDeactive,e),e}return __extends(e,t),e.prototype.createEntity=function(t){var e=new Entity(t);return e.position=new Vector2(0,0),this.addEntity(e)},e.prototype.addEntity=function(t){this.entities.add(t),t.scene=this,this.addChild(t);for(var e=0;e=0;e--)GlobalManager.globalManagers[e].enabled&&GlobalManager.globalManagers[e].update();t.sceneTransition&&(!t.sceneTransition||t.sceneTransition.loadsNewScene&&!t.sceneTransition.isNewSceneLoaded)||t._scene.update(),t._nextScene&&(t._scene.end(),t._scene=t._nextScene,t._nextScene=null,t._instnace.onSceneChanged(),t._scene.begin())}t.render()},t.render=function(){this.sceneTransition?(this.sceneTransition.preRender(),this._scene&&!this.sceneTransition.hasPreviousSceneRender?(this._scene.render(),this._scene.postRender(),this.sceneTransition.onBeginTransition()):this.sceneTransition&&(this._scene&&this.sceneTransition.isNewSceneLoaded&&(this._scene.render(),this._scene.postRender()),this.sceneTransition.render())):this._scene&&(this._scene.render(),Debug.render(),this._scene.postRender())},t.startSceneTransition=function(t){if(!this.sceneTransition)return this.sceneTransition=t,t;console.warn("在前一个场景完成之前,不能开始一个新的场景转换。")},t.registerActiveSceneChanged=function(t,e){this.activeSceneChanged&&this.activeSceneChanged(t,e)},t.prototype.onSceneChanged=function(){t.emitter.emit(CoreEvents.SceneChanged),Time.sceneChanged()},t}(),Camera=function(t){function e(){var e=t.call(this)||this;return e._origin=Vector2.zero,e._minimumZoom=.3,e._maximumZoom=3,e._position=Vector2.zero,e.followLerp=.1,e.deadzone=new Rectangle,e.focusOffset=new Vector2,e.mapLockEnabled=!1,e.mapSize=new Vector2,e._worldSpaceDeadZone=new Rectangle,e._desiredPositionDelta=new Vector2,e.cameraStyle=CameraStyle.lockOn,e.width=SceneManager.stage.stageWidth,e.height=SceneManager.stage.stageHeight,e.setZoom(0),e}return __extends(e,t),Object.defineProperty(e.prototype,"zoom",{get:function(){return 0==this._zoom?1:this._zoom<1?MathHelper.map(this._zoom,this._minimumZoom,1,-1,0):MathHelper.map(this._zoom,1,this._maximumZoom,0,1)},set:function(t){this.setZoom(t)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"minimumZoom",{get:function(){return this._minimumZoom},set:function(t){this.setMinimumZoom(t)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"maximumZoom",{get:function(){return this._maximumZoom},set:function(t){this.setMaximumZoom(t)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"origin",{get:function(){return this._origin},set:function(t){this._origin!=t&&(this._origin=t)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"position",{get:function(){return this._position},set:function(t){this._position=t},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"x",{get:function(){return this._position.x},set:function(t){this._position.x=t},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"y",{get:function(){return this._position.y},set:function(t){this._position.y=t},enumerable:!0,configurable:!0}),e.prototype.onSceneSizeChanged=function(t,e){var n=this._origin;this.origin=new Vector2(t/2,e/2),this.entity.position=Vector2.add(this.entity.position,Vector2.subtract(this._origin,n))},e.prototype.setMinimumZoom=function(t){return this._zoomt&&(this._zoom=t),this._maximumZoom=t,this},e.prototype.setZoom=function(t){var e=MathHelper.clamp(t,-1,1);return this._zoom=0==e?1:e<0?MathHelper.map(e,-1,0,this._minimumZoom,1):MathHelper.map(e,0,1,1,this._maximumZoom),SceneManager.scene.scaleX=this._zoom,SceneManager.scene.scaleY=this._zoom,this},e.prototype.setRotation=function(t){return SceneManager.scene.rotation=t,this},e.prototype.setPosition=function(t){return this.entity.position=t,this},e.prototype.follow=function(t,e){void 0===e&&(e=CameraStyle.cameraWindow),this.targetEntity=t,this.cameraStyle=e;var n=new Rectangle(0,0,SceneManager.stage.stageWidth,SceneManager.stage.stageHeight);switch(this.cameraStyle){case CameraStyle.cameraWindow:var i=n.width/6,o=n.height/3;this.deadzone=new Rectangle((n.width-i)/2,(n.height-o)/2,i,o);break;case CameraStyle.lockOn:this.deadzone=new Rectangle(n.width/2,n.height/2,10,10)}},e.prototype.update=function(){var t=new Rectangle(0,0,SceneManager.stage.stageWidth,SceneManager.stage.stageHeight),e=Vector2.multiply(new Vector2(t.width,t.height),new Vector2(.5));this._worldSpaceDeadZone.x=this.position.x-e.x+this.deadzone.x+this.focusOffset.x,this._worldSpaceDeadZone.y=this.position.y-e.y+this.deadzone.y+this.focusOffset.y,this._worldSpaceDeadZone.width=this.deadzone.width,this._worldSpaceDeadZone.height=this.deadzone.height,this.targetEntity&&this.updateFollow(),this.position=Vector2.lerp(this.position,Vector2.add(this.position,this._desiredPositionDelta),this.followLerp),this.entity.roundPosition(),this.mapLockEnabled&&(this.position=this.clampToMapSize(this.position),this.entity.roundPosition())},e.prototype.clampToMapSize=function(t){var e=new Rectangle(0,0,SceneManager.stage.stageWidth,SceneManager.stage.stageHeight),n=Vector2.multiply(new Vector2(e.width,e.height),new Vector2(.5)),i=new Vector2(this.mapSize.x-n.x,this.mapSize.y-n.y);return Vector2.clamp(t,n,i)},e.prototype.updateFollow=function(){if(this._desiredPositionDelta.x=this._desiredPositionDelta.y=0,this.cameraStyle==CameraStyle.lockOn){var t=this.targetEntity.position.x,e=this.targetEntity.position.y;this._worldSpaceDeadZone.x>t?this._desiredPositionDelta.x=t-this._worldSpaceDeadZone.x:this._worldSpaceDeadZone.xe&&(this._desiredPositionDelta.y=e-this._worldSpaceDeadZone.y)}else{if(!this._targetCollider&&(this._targetCollider=this.targetEntity.getComponent(Collider),!this._targetCollider))return;var n=this.targetEntity.getComponent(Collider).bounds;this._worldSpaceDeadZone.containsRect(n)||(this._worldSpaceDeadZone.left>n.left?this._desiredPositionDelta.x=n.left-this._worldSpaceDeadZone.left:this._worldSpaceDeadZone.rightn.top&&(this._desiredPositionDelta.y=n.top-this._worldSpaceDeadZone.top))}},e}(Component);!function(t){t[t.lockOn=0]="lockOn",t[t.cameraWindow=1]="cameraWindow"}(CameraStyle||(CameraStyle={}));var LoopMode,State,ComponentPool=function(){function t(t){this._type=t,this._cache=[]}return t.prototype.obtain=function(){try{return this._cache.length>0?this._cache.shift():new this._type}catch(t){throw new Error(this._type+t)}},t.prototype.free=function(t){t.reset(),this._cache.push(t)},t}(),PooledComponent=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return __extends(e,t),e}(Component),RenderableComponent=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e._areBoundsDirty=!0,e._bounds=new Rectangle,e._localOffset=Vector2.zero,e.color=0,e}return __extends(e,t),Object.defineProperty(e.prototype,"width",{get:function(){return this.getWidth()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"height",{get:function(){return this.getHeight()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"isVisible",{get:function(){return this._isVisible},set:function(t){this._isVisible=t,this._isVisible?this.onBecameVisible():this.onBecameInvisible()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"bounds",{get:function(){return new Rectangle(this.getBounds().x,this.getBounds().y,this.getBounds().width,this.getBounds().height)},enumerable:!0,configurable:!0}),e.prototype.getWidth=function(){return this.bounds.width},e.prototype.getHeight=function(){return this.bounds.height},e.prototype.onBecameVisible=function(){},e.prototype.onBecameInvisible=function(){},e.prototype.isVisibleFromCamera=function(t){return this.isVisible=t.getBounds().intersects(this.getBounds()),this.isVisible},e}(PooledComponent),Mesh=function(t){function e(){var e=t.call(this)||this;return e._mesh=new egret.Mesh,e}return __extends(e,t),e.prototype.setTexture=function(t){return this._mesh.texture=t,this},e.prototype.onAddedToEntity=function(){this.addChild(this._mesh)},e.prototype.onRemovedFromEntity=function(){this.removeChild(this._mesh)},e.prototype.render=function(t){this.x=this.entity.position.x-t.position.x+t.origin.x,this.y=this.entity.position.y-t.position.y+t.origin.y},e.prototype.reset=function(){},e}(RenderableComponent),SpriteRenderer=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return __extends(e,t),Object.defineProperty(e.prototype,"sprite",{get:function(){return this._sprite},set:function(t){this.setSprite(t)},enumerable:!0,configurable:!0}),e.prototype.setSprite=function(t){return this.removeChildren(),this._sprite=t,this._sprite&&(this.anchorOffsetX=this._sprite.origin.x/this._sprite.sourceRect.width,this.anchorOffsetY=this._sprite.origin.y/this._sprite.sourceRect.height),this.bitmap=new egret.Bitmap(t.texture2D),this.addChild(this.bitmap),this},e.prototype.setColor=function(t){var e=[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0];e[0]=Math.floor(t/256/256)/255,e[6]=Math.floor(t/256%256)/255,e[12]=t%256/255;var n=new egret.ColorMatrixFilter(e);return this.filters=[n],this},e.prototype.isVisibleFromCamera=function(t){return this.isVisible=new Rectangle(0,0,this.stage.stageWidth,this.stage.stageHeight).intersects(this.bounds),this.visible=this.isVisible,this.isVisible},e.prototype.render=function(t){this.x=-t.position.x+t.origin.x,this.y=-t.position.y+t.origin.y},e.prototype.onRemovedFromEntity=function(){this.parent&&this.parent.removeChild(this)},e.prototype.reset=function(){},e}(RenderableComponent),TiledSpriteRenderer=function(t){function e(e){var n=t.call(this)||this;return n.leftTexture=new egret.Bitmap,n.rightTexture=new egret.Bitmap,n.leftTexture.texture=e.texture2D,n.rightTexture.texture=e.texture2D,n.setSprite(e),n.sourceRect=e.sourceRect,n}return __extends(e,t),Object.defineProperty(e.prototype,"scrollX",{get:function(){return this.sourceRect.x},set:function(t){this.sourceRect.x=t},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"scrollY",{get:function(){return this.sourceRect.y},set:function(t){this.sourceRect.y=t},enumerable:!0,configurable:!0}),e.prototype.render=function(e){if(this.sprite){t.prototype.render.call(this,e);var n=new egret.RenderTexture,i=new egret.DisplayObjectContainer;i.removeChildren(),i.addChild(this.leftTexture),i.addChild(this.rightTexture),this.leftTexture.x=this.sourceRect.x,this.rightTexture.x=this.sourceRect.x-this.sourceRect.width,this.leftTexture.y=this.sourceRect.y,this.rightTexture.y=this.sourceRect.y,i.cacheAsBitmap=!0,n.drawToTexture(i,new egret.Rectangle(0,0,this.sourceRect.width,this.sourceRect.height)),this.bitmap.texture=n}},e}(SpriteRenderer),ScrollingSpriteRenderer=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e.scrollSpeedX=15,e.scroolSpeedY=0,e._scrollX=0,e._scrollY=0,e}return __extends(e,t),e.prototype.update=function(){this._scrollX+=this.scrollSpeedX*Time.deltaTime,this._scrollY+=this.scroolSpeedY*Time.deltaTime,this.sourceRect.x=this._scrollX,this.sourceRect.y=this._scrollY},e.prototype.render=function(e){if(this.sprite){t.prototype.render.call(this,e);var n=new egret.RenderTexture,i=new egret.DisplayObjectContainer;i.removeChildren(),i.addChild(this.leftTexture),i.addChild(this.rightTexture),this.leftTexture.x=this.sourceRect.x,this.rightTexture.x=this.sourceRect.x-this.sourceRect.width,this.leftTexture.y=this.sourceRect.y,this.rightTexture.y=this.sourceRect.y,i.cacheAsBitmap=!0,n.drawToTexture(i,new egret.Rectangle(0,0,this.sourceRect.width,this.sourceRect.height)),this.bitmap.texture=n}},e}(TiledSpriteRenderer),Sprite=function(){return function(t,e,n){void 0===e&&(e=new Rectangle(0,0,t.textureWidth,t.textureHeight)),void 0===n&&(n=e.getHalfSize()),this.uvs=new Rectangle,this.texture2D=t,this.sourceRect=e,this.center=new Vector2(.5*e.width,.5*e.height),this.origin=n;var i=1/t.textureWidth,o=1/t.textureHeight;this.uvs.x=e.x*i,this.uvs.y=e.y*o,this.uvs.width=e.width*i,this.uvs.height=e.height*o}}(),SpriteAnimation=function(){return function(t,e){this.sprites=t,this.frameRate=e}}(),SpriteAnimator=function(t){function e(e){var n=t.call(this)||this;return n.speed=1,n.animationState=State.none,n._animations=new Map,n._elapsedTime=0,e&&n.setSprite(e),n}return __extends(e,t),Object.defineProperty(e.prototype,"isRunning",{get:function(){return this.animationState==State.running},enumerable:!0,configurable:!0}),e.prototype.addAnimation=function(t,e){return!this.sprite&&e.sprites.length>0&&this.setSprite(e.sprites[0]),this._animations[t]=e,this},e.prototype.play=function(t,e){void 0===e&&(e=null),this.currentAnimation=this._animations[t],this.currentAnimationName=t,this.currentFrame=0,this.animationState=State.running,this.sprite=this.currentAnimation.sprites[0],this._elapsedTime=0,this._loopMode=e||LoopMode.loop},e.prototype.isAnimationActive=function(t){return this.currentAnimation&&this.currentAnimationName==t},e.prototype.pause=function(){this.animationState=State.paused},e.prototype.unPause=function(){this.animationState=State.running},e.prototype.stop=function(){this.currentAnimation=null,this.currentAnimationName=null,this.currentFrame=0,this.animationState=State.none},e.prototype.update=function(){if(this.animationState==State.running&&this.currentAnimation){var t=this.currentAnimation,e=1/(t.frameRate*this.speed),n=e*t.sprites.length;this._elapsedTime+=Time.deltaTime;var i=Math.abs(this._elapsedTime);if(this._loopMode==LoopMode.once&&i>n||this._loopMode==LoopMode.pingPongOnce&&i>2*n)return this.animationState=State.completed,this._elapsedTime=0,this.currentFrame=0,void(this.sprite=t.sprites[this.currentFrame]);var o=Math.floor(i/e),r=t.sprites.length;if(r>2&&(this._loopMode==LoopMode.pingPong||this._loopMode==LoopMode.pingPongOnce)){var s=r-1;this.currentFrame=s-Math.abs(s-o%(2*s))}else this.currentFrame=o%r;this.sprite=t.sprites[this.currentFrame]}},e}(SpriteRenderer);!function(t){t[t.loop=0]="loop",t[t.once=1]="once",t[t.clampForever=2]="clampForever",t[t.pingPong=3]="pingPong",t[t.pingPongOnce=4]="pingPongOnce"}(LoopMode||(LoopMode={})),function(t){t[t.none=0]="none",t[t.running=1]="running",t[t.paused=2]="paused",t[t.completed=3]="completed"}(State||(State={}));var PointSectors,Mover=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return __extends(e,t),e.prototype.onAddedToEntity=function(){this._triggerHelper=new ColliderTriggerHelper(this.entity)},e.prototype.calculateMovement=function(t){var e=new CollisionResult;if(!this.entity.getComponent(Collider)||!this._triggerHelper)return null;for(var n=this.entity.getComponents(Collider),i=0;i>6;0!=(e&t.LONG_MASK)&&n++,this._bits=new Array(n)}return t.prototype.and=function(t){for(var e,n=Math.min(this._bits.length,t._bits.length),i=0;i=0;)this._bits[e]&=~t._bits[e]},t.prototype.cardinality=function(){for(var t=0,e=this._bits.length-1;e>=0;e--){var n=this._bits[e];if(0!=n)if(-1!=n){var i=((n=((n=(n>>1&0x5555555555555400)+(0x5555555555555400&n))>>2&0x3333333333333400)+(0x3333333333333400&n))>>32)+n;t+=((i=((i=(i>>4&252645135)+(252645135&i))>>8&16711935)+(16711935&i))>>16&65535)+(65535&i)}else t+=64}return t},t.prototype.clear=function(t){if(null!=t){var e=t>>6;this.ensure(e),this._bits[e]&=~(1<=this._bits.length){var e=new Number[t+1];e=this._bits.copyWithin(0,0,this._bits.length),this._bits=e}},t.prototype.get=function(t){var e=t>>6;return!(e>=this._bits.length)&&0!=(this._bits[e]&1<=0;)if(0!=(this._bits[e]&t._bits[e]))return!0;return!1},t.prototype.isEmpty=function(){for(var t=this._bits.length-1;t>=0;t--)if(this._bits[t])return!1;return!0},t.prototype.nextSetBit=function(t){for(var e=t>>6,n=1<>6;this.ensure(n),this._bits[n]|=1<0){for(var t=0;t0){t=0;for(var e=this._componentsToAdd.length;t0){var e=this._entitiesToRemove;this._entitiesToRemove=this._tempEntityList,this._tempEntityList=e,this._tempEntityList.forEach(function(e){t._entities.remove(e),e.scene=null,t.scene.entityProcessors.onEntityRemoved(e)}),this._tempEntityList.length=0}if(this._entitiesToAdded.length>0){e=this._entitiesToAdded;this._entitiesToAdded=this._tempEntityList,this._tempEntityList=e,this._tempEntityList.forEach(function(e){t._entities.contains(e)||(t._entities.push(e),e.scene=t.scene,t.scene.entityProcessors.onEntityAdded(e))}),this._tempEntityList.forEach(function(t){return t.onAddedToScene()}),this._tempEntityList.length=0}this._unsortedTags.length>0&&(this._unsortedTags.forEach(function(e){t._entityDict.get(e).sort()}),this._unsortedTags.length=0)},t}(),EntityProcessorList=function(){function t(){this._processors=[]}return t.prototype.add=function(t){this._processors.push(t)},t.prototype.remove=function(t){this._processors.remove(t)},t.prototype.onComponentAdded=function(t){this.notifyEntityChanged(t)},t.prototype.onComponentRemoved=function(t){this.notifyEntityChanged(t)},t.prototype.onEntityAdded=function(t){this.notifyEntityChanged(t)},t.prototype.onEntityRemoved=function(t){this.removeFromProcessors(t)},t.prototype.notifyEntityChanged=function(t){for(var e=0;e=0;e=this.allSet.nextSetBit(e+1))if(!t.componentBits.get(e))return!1;return!(!this.exclusionSet.isEmpty()&&this.exclusionSet.intersects(t.componentBits))&&!(!this.oneSet.isEmpty()&&!this.oneSet.intersects(t.componentBits))},t.prototype.all=function(){for(var t=this,e=[],n=0;n(this._timeSinceSceneLoad-this.deltaTime)/t},t.deltaTime=0,t.timeScale=1,t.frameCount=0,t._lastTime=0,t}(),GraphicsCapabilities=function(){function t(){}return t.prototype.initialize=function(t){this.platformInitialize(t)},t.prototype.platformInitialize=function(t){var e=(new egret.sys.RenderBuffer).context.getInstance();this.supportsNonPowerOfTwo=!1,this.supportsTextureFilterAnisotropic=null!=e.getExtension("EXT_texture_filter_anisotropic"),this.supportsDepth24=!0,this.supportsPackedDepthStencil=!0,this.supportsDepthNonLinear=!1,this.supportsTextureMaxLevel=!0,this.supportsS3tc=null!=e.getExtension("WEBGL_compressed_texture_s3tc")||null!=e.getExtension("WEBGL_compressed_texture_s3tc_srgb"),this.supportsDxt1=this.supportsS3tc,this.supportsPvrtc=!1,this.supportsAtitc=null!=e.getExtension("WEBGL_compressed_texture_astc"),this.supportsFramebufferObjectARB=!1},t}(),GraphicsDevice=function(){return function(){this.graphicsCapabilities=new GraphicsCapabilities,this.graphicsCapabilities.initialize(this)}}(),Viewport=function(){function t(t,e,n,i){this._x=t,this._y=e,this._width=n,this._height=i,this._minDepth=0,this._maxDepth=1}return Object.defineProperty(t.prototype,"aspectRatio",{get:function(){return 0!=this._height&&0!=this._width?this._width/this._height:0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"bounds",{get:function(){return new Rectangle(this._x,this._y,this._width,this._height)},set:function(t){this._x=t.x,this._y=t.y,this._width=t.width,this._height=t.height},enumerable:!0,configurable:!0}),t}(),GaussianBlurEffect=function(t){function e(){return t.call(this,PostProcessor.default_vert,e.blur_frag,{screenWidth:SceneManager.stage.stageWidth,screenHeight:SceneManager.stage.stageHeight})||this}return __extends(e,t),e.blur_frag="precision mediump float;\nuniform sampler2D uSampler;\nuniform float screenWidth;\nuniform float screenHeight;\nfloat normpdf(in float x, in float sigma)\n{\nreturn 0.39894*exp(-0.5*x*x/(sigma*sigma))/sigma;\n}\nvoid main()\n{\nvec3 c = texture2D(uSampler, gl_FragCoord.xy / vec2(screenWidth, screenHeight).xy).rgb;\nconst int mSize = 11;\nconst int kSize = (mSize - 1)/2;\nfloat kernel[mSize];\nvec3 final_colour = vec3(0.0);\nfloat sigma = 7.0;\nfloat z = 0.0;\nfor (int j = 0; j <= kSize; ++j)\n{\nkernel[kSize+j] = kernel[kSize-j] = normpdf(float(j),sigma);\n}\nfor (int j = 0; j < mSize; ++j)\n{\nz += kernel[j];\n}\nfor (int i = -kSize; i <= kSize; ++i)\n{\nfor (int j = -kSize; j <= kSize; ++j)\n{\nfinal_colour += kernel[kSize+j]*kernel[kSize+i]*texture2D(uSampler, (gl_FragCoord.xy+vec2(float(i),float(j))) / vec2(screenWidth, screenHeight).xy).rgb;\n}\n}\ngl_FragColor = vec4(final_colour/(z*z), 1.0);\n}",e}(egret.CustomFilter),PolygonLightEffect=function(t){function e(){return t.call(this,e.vertSrc,e.fragmentSrc)||this}return __extends(e,t),e.vertSrc="attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\nuniform vec2 projectionVector;\nvarying vec2 vTextureCoord;\nconst vec2 center = vec2(-1.0, 1.0);\nvoid main(void) {\n gl_Position = vec4( (aVertexPosition / projectionVector) + center , 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}",e.fragmentSrc="precision lowp float;\nvarying vec2 vTextureCoord;\nuniform sampler2D uSampler;\n#define SAMPLE_COUNT 15\nuniform vec2 _sampleOffsets[SAMPLE_COUNT];\nuniform float _sampleWeights[SAMPLE_COUNT];\nvoid main(void) {\nvec4 c = vec4(0, 0, 0, 0);\nfor( int i = 0; i < SAMPLE_COUNT; i++ )\n c += texture2D( uSampler, vTextureCoord + _sampleOffsets[i] ) * _sampleWeights[i];\ngl_FragColor = c;\n}",e}(egret.CustomFilter),PostProcessor=function(){function t(t){void 0===t&&(t=null),this.enable=!0,this.effect=t}return t.prototype.onAddedToScene=function(t){this.scene=t,this.shape=new egret.Shape,this.shape.graphics.beginFill(16777215,1),this.shape.graphics.drawRect(0,0,SceneManager.stage.stageWidth,SceneManager.stage.stageHeight),this.shape.graphics.endFill(),t.addChild(this.shape)},t.prototype.process=function(){this.drawFullscreenQuad()},t.prototype.onSceneBackBufferSizeChanged=function(t,e){},t.prototype.drawFullscreenQuad=function(){this.scene.filters=[this.effect]},t.prototype.unload=function(){this.effect&&(this.effect=null),this.scene.removeChild(this.shape),this.scene=null},t.default_vert="attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\nattribute vec2 aColor;\nuniform vec2 projectionVector;\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\nconst vec2 center = vec2(-1.0, 1.0);\nvoid main(void) {\ngl_Position = vec4( (aVertexPosition / projectionVector) + center , 0.0, 1.0);\nvTextureCoord = aTextureCoord;\nvColor = vec4(aColor.x, aColor.x, aColor.x, aColor.x);\n}",t}(),GaussianBlurPostProcessor=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return __extends(e,t),e.prototype.onAddedToScene=function(e){t.prototype.onAddedToScene.call(this,e),this.effect=new GaussianBlurEffect},e}(PostProcessor),Renderer=function(){function t(){}return t.prototype.onAddedToScene=function(t){},t.prototype.beginRender=function(t){},t.prototype.unload=function(){},t.prototype.renderAfterStateCheck=function(t,e){t.render(e)},t}(),DefaultRenderer=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return __extends(e,t),e.prototype.render=function(t){var e=this.camera?this.camera:t.camera;this.beginRender(e);for(var n=0;nn?n:t},t.pointOnCirlce=function(e,n,i){var o=t.toRadians(i);return new Vector2(Math.cos(o)*o+e.x,Math.sin(o)*o+e.y)},t.isEven=function(t){return t%2==0},t.clamp01=function(t){return t<0?0:t>1?1:t},t.angleBetweenVectors=function(t,e){return Math.atan2(e.y-t.y,e.x-t.x)},t.Epsilon=1e-5,t.Rad2Deg=57.29578,t.Deg2Rad=.0174532924,t}(),Matrix2D=function(){function t(t,e,n,i,o,r){this.m11=0,this.m12=0,this.m21=0,this.m22=0,this.m31=0,this.m32=0,this.m11=t||1,this.m12=e||0,this.m21=n||0,this.m22=i||1,this.m31=o||0,this.m32=r||0}return Object.defineProperty(t,"identity",{get:function(){return t._identity},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"translation",{get:function(){return new Vector2(this.m31,this.m32)},set:function(t){this.m31=t.x,this.m32=t.y},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"rotation",{get:function(){return Math.atan2(this.m21,this.m11)},set:function(t){var e=Math.cos(t),n=Math.sin(t);this.m11=e,this.m12=n,this.m21=-n,this.m22=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"rotationDegrees",{get:function(){return MathHelper.toDegrees(this.rotation)},set:function(t){this.rotation=MathHelper.toRadians(t)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"scale",{get:function(){return new Vector2(this.m11,this.m22)},set:function(t){this.m11=t.x,this.m12=t.y},enumerable:!0,configurable:!0}),t.add=function(t,e){return t.m11+=e.m11,t.m12+=e.m12,t.m21+=e.m21,t.m22+=e.m22,t.m31+=e.m31,t.m32+=e.m32,t},t.divide=function(t,e){return t.m11/=e.m11,t.m12/=e.m12,t.m21/=e.m21,t.m22/=e.m22,t.m31/=e.m31,t.m32/=e.m32,t},t.multiply=function(e,n){var i=new t,o=e.m11*n.m11+e.m12*n.m21,r=e.m11*n.m12+e.m12*n.m22,s=e.m21*n.m11+e.m22*n.m21,a=e.m21*n.m12+e.m22*n.m22,c=e.m31*n.m11+e.m32*n.m21+n.m31,h=e.m31*n.m12+e.m32*n.m22+n.m32;return i.m11=o,i.m12=r,i.m21=s,i.m22=a,i.m31=c,i.m32=h,i},t.multiplyTranslation=function(e,n,i){var o=t.createTranslation(n,i);return t.multiply(e,o)},t.prototype.determinant=function(){return this.m11*this.m22-this.m12*this.m21},t.invert=function(e,n){void 0===n&&(n=new t);var i=1/e.determinant();return n.m11=e.m22*i,n.m12=-e.m12*i,n.m21=-e.m21*i,n.m22=e.m11*i,n.m31=(e.m32*e.m21-e.m31*e.m22)*i,n.m32=-(e.m32*e.m11-e.m31*e.m12)*i,n},t.createTranslation=function(e,n){var i=new t;return i.m11=1,i.m12=0,i.m21=0,i.m22=1,i.m31=e,i.m32=n,i},t.createTranslationVector=function(t){return this.createTranslation(t.x,t.y)},t.createRotation=function(e,n){n=new t;var i=Math.cos(e),o=Math.sin(e);return n.m11=i,n.m12=o,n.m21=-o,n.m22=i,n},t.createScale=function(e,n,i){return void 0===i&&(i=new t),i.m11=e,i.m12=0,i.m21=0,i.m22=n,i.m31=0,i.m32=0,i},t.prototype.toEgretMatrix=function(){return new egret.Matrix(this.m11,this.m12,this.m21,this.m22,this.m31,this.m32)},t._identity=new t(1,0,0,1,0,0),t}(),Rectangle=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return __extends(e,t),Object.defineProperty(e.prototype,"max",{get:function(){return new Vector2(this.right,this.bottom)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"center",{get:function(){return new Vector2(this.x+this.width/2,this.y+this.height/2)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"location",{get:function(){return new Vector2(this.x,this.y)},set:function(t){this.x=t.x,this.y=t.y},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"size",{get:function(){return new Vector2(this.width,this.height)},set:function(t){this.width=t.x,this.height=t.y},enumerable:!0,configurable:!0}),e.prototype.intersects=function(t){return t.lefti&&(i=s.x),s.yo&&(o=s.y)}return this.fromMinMax(e,n,i,o)},e}(egret.Rectangle),Vector3=function(){return function(t,e,n){this.x=t,this.y=e,this.z=n}}(),ColliderTriggerHelper=function(){function t(t){this._activeTriggerIntersections=[],this._previousTriggerIntersections=[],this._tempTriggerList=[],this._entity=t}return t.prototype.update=function(){for(var t=this._entity.getComponents(Collider),e=0;e1)return!1;var h=(a.x*o.y-a.y*o.x)/s;return!(h<0||h>1)},t.lineToLineIntersection=function(t,e,n,i){var o=new Vector2(0,0),r=Vector2.subtract(e,t),s=Vector2.subtract(i,n),a=r.x*s.y-r.y*s.x;if(0==a)return o;var c=Vector2.subtract(n,t),h=(c.x*s.y-c.y*s.x)/a;if(h<0||h>1)return o;var u=(c.x*r.y-c.y*r.x)/a;return u<0||u>1?o:o=Vector2.add(t,new Vector2(h*r.x,h*r.y))},t.closestPointOnLine=function(t,e,n){var i=Vector2.subtract(e,t),o=Vector2.subtract(n,t),r=Vector2.dot(o,i)/Vector2.dot(i,i);return r=MathHelper.clamp(r,0,1),Vector2.add(t,new Vector2(i.x*r,i.y*r))},t.isCircleToCircle=function(t,e,n,i){return Vector2.distanceSquared(t,n)<(e+i)*(e+i)},t.isCircleToLine=function(t,e,n,i){return Vector2.distanceSquared(t,this.closestPointOnLine(n,i,t))=t&&o.y>=e&&o.x=t+n&&(r|=PointSectors.right),o.y=e+i&&(r|=PointSectors.bottom),r},t}(),Physics=function(){function t(){}return t.reset=function(){this._spatialHash=new SpatialHash(this.spatialHashCellSize)},t.clear=function(){this._spatialHash.clear()},t.overlapCircleAll=function(t,e,n,i){return void 0===i&&(i=-1),this._spatialHash.overlapCircle(t,e,n,i)},t.boxcastBroadphase=function(t,e){void 0===e&&(e=this.allLayers);var n=this._spatialHash.aabbBroadphase(t,null,e);return{colliders:n.tempHashSet,rect:n.bounds}},t.boxcastBroadphaseExcludingSelf=function(t,e,n){return void 0===n&&(n=this.allLayers),this._spatialHash.aabbBroadphase(e,t,n)},t.addCollider=function(e){t._spatialHash.register(e)},t.removeCollider=function(e){t._spatialHash.remove(e)},t.updateCollider=function(t){this._spatialHash.remove(t),this._spatialHash.register(t)},t.debugDraw=function(t){this._spatialHash.debugDraw(t,2)},t.spatialHashCellSize=100,t.allLayers=-1,t}(),Shape=function(){return function(){this.bounds=new Rectangle,this.position=Vector2.zero}}(),Polygon=function(t){function e(e,n){var i=t.call(this)||this;return i.isUnrotated=!0,i._areEdgeNormalsDirty=!0,i.center=new Vector2,i.setPoints(e),i.isBox=n,i}return __extends(e,t),Object.defineProperty(e.prototype,"edgeNormals",{get:function(){return this._areEdgeNormalsDirty&&this.buildEdgeNormals(),this._edgeNormals},enumerable:!0,configurable:!0}),e.prototype.buildEdgeNormals=function(){var t,e=this.isBox?2:this.points.length;null!=this._edgeNormals&&this._edgeNormals.length==e||(this._edgeNormals=new Array(e));for(var n=0;n=this.points.length?this.points[0]:this.points[n+1];var o=Vector2Ext.perpendicular(i,t);o=Vector2.normalize(o),this._edgeNormals[n]=o}},e.prototype.setPoints=function(t){this.points=t,this.recalculateCenterAndEdgeNormals(),this._originalPoints=[];for(var e=0;et.y!=this.points[i].y>t.y&&t.x<(this.points[i].x-this.points[n].x)*(t.y-this.points[n].y)/(this.points[i].y-this.points[n].y)+this.points[n].x&&(e=!e);return e},e.buildSymmertricalPolygon=function(t,e){for(var n=new Array(t),i=0;i0&&(o=!1),!o)return null;(g=Math.abs(g))i&&(i=o);return{min:n,max:i}},t.circleToPolygon=function(t,e){var n=new CollisionResult,i=Vector2.subtract(t.position,e.position),o=Polygon.getClosestPointOnPolygonToPoint(e.points,i),r=o.closestPoint,s=o.distanceSquared;n.normal=o.edgeNormal;var a,c=e.containsPoint(t.position);if(s>t.radius*t.radius&&!c)return null;if(c)a=Vector2.multiply(n.normal,new Vector2(Math.sqrt(s)-t.radius));else if(0==s)a=Vector2.multiply(n.normal,new Vector2(t.radius));else{var h=Math.sqrt(s);a=Vector2.multiply(new Vector2(-Vector2.subtract(i,r)),new Vector2((t.radius-s)/h))}return n.minimumTranslationVector=a,n.point=Vector2.add(r,e.position),n},t.circleToBox=function(t,e){var n=new CollisionResult,i=e.bounds.getClosestPointOnRectangleBorderToPoint(t.position).res;if(e.containsPoint(t.position)){n.point=i;var o=Vector2.add(i,Vector2.subtract(n.normal,new Vector2(t.radius)));return n.minimumTranslationVector=Vector2.subtract(t.position,o),n}var r=Vector2.distanceSquared(i,t.position);if(0==r)n.minimumTranslationVector=Vector2.multiply(n.normal,new Vector2(t.radius));else if(r<=t.radius*t.radius){n.normal=Vector2.subtract(t.position,i);var s=n.normal.length()-t.radius;return n.normal=Vector2Ext.normalize(n.normal),n.minimumTranslationVector=Vector2.multiply(new Vector2(s),n.normal),n}return null},t.pointToCircle=function(t,e){var n=new CollisionResult,i=Vector2.distanceSquared(t,e.position),o=1+e.radius;if(i0&&this.debugDrawCellDetails(n,i,o.length,t,e)}},t.prototype.debugDrawCellDetails=function(t,e,n,i,o){void 0===i&&(i=.5),void 0===o&&(o=1)},t}(),RaycastResultParser=function(){return function(){}}(),NumberDictionary=function(){function t(){this._store=new Map}return t.prototype.getKey=function(t,e){return Long.fromNumber(t).shiftLeft(32).or(this.intToUint(e)).toString()},t.prototype.intToUint=function(t){return t>=0?t:4294967296+t},t.prototype.add=function(t,e,n){this._store.set(this.getKey(t,e),n)},t.prototype.remove=function(t){this._store.forEach(function(e){e.contains(t)&&e.remove(t)})},t.prototype.tryGetValue=function(t,e){return this._store.get(this.getKey(t,e))},t.prototype.clear=function(){this._store.clear()},t}(),ContentManager=function(){function t(){this.loadedAssets=new Map}return t.prototype.loadRes=function(t,e){var n=this;return void 0===e&&(e=!0),new Promise(function(i,o){var r=n.loadedAssets.get(t);r?i(r):e?RES.getResAsync(t).then(function(e){n.loadedAssets.set(t,e),i(e)}).catch(function(e){console.error("资源加载错误:",t,e),o(e)}):RES.getResByUrl(t).then(function(e){n.loadedAssets.set(t,e),i(e)}).catch(function(e){console.error("资源加载错误:",t,e),o(e)})})},t.prototype.dispose=function(){this.loadedAssets.forEach(function(t){t.dispose()}),this.loadedAssets.clear()},t}(),DrawUtils=function(){function t(){}return t.drawLine=function(t,e,n,i,o){void 0===o&&(o=1),this.drawLineAngle(t,e,MathHelper.angleBetweenVectors(e,n),Vector2.distance(e,n),i,o)},t.drawLineAngle=function(t,e,n,i,o,r){void 0===r&&(r=1),t.graphics.beginFill(o),t.graphics.drawRect(e.x,e.y,1,1),t.graphics.endFill(),t.scaleX=i,t.scaleY=r,t.$anchorOffsetX=0,t.$anchorOffsetY=0,t.rotation=n},t.drawHollowRect=function(t,e,n,i){void 0===i&&(i=1),this.drawHollowRectR(t,e.x,e.y,e.width,e.height,n,i)},t.drawHollowRectR=function(t,e,n,i,o,r,s){void 0===s&&(s=1);var a=new Vector2(e,n).round(),c=new Vector2(e+i,n).round(),h=new Vector2(e+i,n+o).round(),u=new Vector2(e,n+o).round();this.drawLine(t,a,c,r,s),this.drawLine(t,c,h,r,s),this.drawLine(t,h,u,r,s),this.drawLine(t,u,a,r,s)},t.drawPixel=function(t,e,n,i){void 0===i&&(i=1);var o=new Rectangle(e.x,e.y,i,i);1!=i&&(o.x-=.5*i,o.y-=.5*i),t.graphics.beginFill(n),t.graphics.drawRect(o.x,o.y,o.width,o.height),t.graphics.endFill()},t}(),Emitter=function(){function t(){this._messageTable=new Map}return t.prototype.addObserver=function(t,e,n){var i=this._messageTable.get(t);i||(i=[],this._messageTable.set(t,i)),i.contains(e)&&console.warn("您试图添加相同的观察者两次"),i.push(new FuncPack(e,n))},t.prototype.removeObserver=function(t,e){var n=this._messageTable.get(t),i=n.findIndex(function(t){return t.func==e});-1!=i&&n.removeAt(i)},t.prototype.emit=function(t,e){var n=this._messageTable.get(t);if(n)for(var i=n.length-1;i>=0;i--)n[i].func.call(n[i].context,e)},t}(),FuncPack=function(){return function(t,e){this.func=t,this.context=e}}(),GlobalManager=function(){function t(){}return Object.defineProperty(t.prototype,"enabled",{get:function(){return this._enabled},set:function(t){this.setEnabled(t)},enumerable:!0,configurable:!0}),t.prototype.setEnabled=function(t){this._enabled!=t&&(this._enabled=t,this._enabled?this.onEnabled():this.onDisabled())},t.prototype.onEnabled=function(){},t.prototype.onDisabled=function(){},t.prototype.update=function(){},t.registerGlobalManager=function(t){this.globalManagers.push(t),t.enabled=!0},t.unregisterGlobalManager=function(t){this.globalManagers.remove(t),t.enabled=!1},t.getGlobalManager=function(t){for(var e=0;e0&&this.setpreviousTouchState(this._gameTouchs[0]),t},enumerable:!0,configurable:!0}),t.initialize=function(t){this._init||(this._init=!0,this._stage=t,this._stage.addEventListener(egret.TouchEvent.TOUCH_BEGIN,this.touchBegin,this),this._stage.addEventListener(egret.TouchEvent.TOUCH_MOVE,this.touchMove,this),this._stage.addEventListener(egret.TouchEvent.TOUCH_END,this.touchEnd,this),this._stage.addEventListener(egret.TouchEvent.TOUCH_CANCEL,this.touchEnd,this),this._stage.addEventListener(egret.TouchEvent.TOUCH_RELEASE_OUTSIDE,this.touchEnd,this),this.initTouchCache())},t.initTouchCache=function(){this._totalTouchCount=0,this._touchIndex=0,this._gameTouchs.length=0;for(var t=0;t0)for(var e=0;ethis._objectQueue.length;)this._objectQueue.shift()},t.clearCache=function(){this._objectQueue.length=0},t.obtain=function(){return this._objectQueue.length>0?this._objectQueue.shift():[]},t.free=function(t){this._objectQueue.unshift(t),t.length=0},t._objectQueue=[],t}(),THREAD_ID=Math.floor(1e3*Math.random())+"-"+Date.now(),setItem=egret.localStorage.setItem.bind(localStorage),getItem=egret.localStorage.getItem.bind(localStorage),removeItem=egret.localStorage.removeItem.bind(localStorage),nextTick=function(t){setTimeout(t,0)},LockUtils=function(){function t(t){this._keyX="mutex_key_"+t+"_X",this._keyY="mutex_key_"+t+"_Y"}return t.prototype.lock=function(){var t=this;return new Promise(function(e,n){var i=function(){setItem(t._keyX,THREAD_ID),null===!getItem(t._keyY)&&nextTick(i),setItem(t._keyY,THREAD_ID),getItem(t._keyX)!==THREAD_ID?setTimeout(function(){getItem(t._keyY)===THREAD_ID?(e(),removeItem(t._keyY)):nextTick(i)},10):(e(),removeItem(t._keyY))};i()})},t}(),Pair=function(){function t(t,e){this.first=t,this.second=e}return t.prototype.clear=function(){this.first=this.second=null},t.prototype.equals=function(t){return this.first==t.first&&this.second==t.second},t}(),RectangleExt=function(){function t(){}return t.union=function(t,e){var n=new Rectangle(e.x,e.y,0,0),i=t.union(n);return new Rectangle(i.x,i.y,i.width,i.height)},t}(),Triangulator=function(){function t(){this.triangleIndices=[],this._triPrev=new Array(12),this._triNext=new Array(12)}return t.prototype.triangulate=function(e,n){void 0===n&&(n=!0);var i=e.length;this.initialize(i);for(var o=0,r=0;i>3&&o<500;){o++;var s=!0,a=e[this._triPrev[r]],c=e[r],h=e[this._triNext[r]];if(Vector2Ext.isTriangleCCW(a,c,h)){var u=this._triNext[this._triNext[r]];do{if(t.testPointTriangle(e[u],a,c,h)){s=!1;break}u=this._triNext[u]}while(u!=this._triPrev[r])}else s=!1;s?(this.triangleIndices.push(this._triPrev[r]),this.triangleIndices.push(r),this.triangleIndices.push(this._triNext[r]),this._triNext[this._triPrev[r]]=this._triNext[r],this._triPrev[this._triNext[r]]=this._triPrev[r],i--,r=this._triPrev[r]):r=this._triNext[r]}this.triangleIndices.push(this._triPrev[r]),this.triangleIndices.push(r),this.triangleIndices.push(this._triNext[r]),n||this.triangleIndices.reverse()},t.prototype.initialize=function(t){this.triangleIndices.length=0,this._triNext.lengthMathHelper.Epsilon?t=Vector2.divide(t,new Vector2(e)):t.x=t.y=0,t},t.transformA=function(t,e,n,i,o,r){for(var s=0;sthis.safeArea.right&&(o.x=this.safeArea.right-o.width),o.topthis.safeArea.bottom&&(o.y=this.safeArea.bottom-o.height),o},t}();!function(t){t[t.none=0]="none",t[t.left=1]="left",t[t.right=2]="right",t[t.horizontalCenter=4]="horizontalCenter",t[t.top=8]="top",t[t.bottom=16]="bottom",t[t.verticalCenter=32]="verticalCenter",t[t.topLeft=9]="topLeft",t[t.topRight=10]="topRight",t[t.topCenter=12]="topCenter",t[t.bottomLeft=17]="bottomLeft",t[t.bottomRight=18]="bottomRight",t[t.bottomCenter=20]="bottomCenter",t[t.centerLeft=33]="centerLeft",t[t.centerRight=34]="centerRight",t[t.center=36]="center"}(Alignment||(Alignment={})),function(t){var e,n=function(){function t(t){void 0===t&&(t=i),this.getSystemTime=t,this._stopDuration=0,this._completeSlices=[]}return t.prototype.getState=function(){return void 0===this._startSystemTime?e.IDLE:void 0===this._stopSystemTime?e.RUNNING:e.STOPPED},t.prototype.isIdle=function(){return this.getState()===e.IDLE},t.prototype.isRunning=function(){return this.getState()===e.RUNNING},t.prototype.isStopped=function(){return this.getState()===e.STOPPED},t.prototype.slice=function(){return this.recordPendingSlice()},t.prototype.getCompletedSlices=function(){return Array.from(this._completeSlices)},t.prototype.getCompletedAndPendingSlices=function(){return this._completeSlices.concat([this.getPendingSlice()])},t.prototype.getPendingSlice=function(){return this.calculatePendingSlice()},t.prototype.getTime=function(){return this.caculateStopwatchTime()},t.prototype.calculatePendingSlice=function(t){return void 0===this._pendingSliceStartStopwatchTime?Object.freeze({startTime:0,endTime:0,duration:0}):(void 0===t&&(t=this.getTime()),Object.freeze({startTime:this._pendingSliceStartStopwatchTime,endTime:t,duration:t-this._pendingSliceStartStopwatchTime}))},t.prototype.caculateStopwatchTime=function(t){return void 0===this._startSystemTime?0:(void 0===t&&(t=this.getSystemTimeOfCurrentStopwatchTime()),t-this._startSystemTime-this._stopDuration)},t.prototype.getSystemTimeOfCurrentStopwatchTime=function(){return void 0===this._stopSystemTime?this.getSystemTime():this._stopSystemTime},t.prototype.reset=function(){this._startSystemTime=this._pendingSliceStartStopwatchTime=this._stopSystemTime=void 0,this._stopDuration=0,this._completeSlices=[]},t.prototype.start=function(t){if(void 0===t&&(t=!1),t&&this.reset(),void 0!==this._stopSystemTime){var e=(n=this.getSystemTime())-this._stopSystemTime;this._stopDuration+=e,this._stopSystemTime=void 0}else if(void 0===this._startSystemTime){var n=this.getSystemTime();this._startSystemTime=n,this._pendingSliceStartStopwatchTime=0}},t.prototype.stop=function(t){if(void 0===t&&(t=!1),void 0===this._startSystemTime)return 0;var e=this.getSystemTimeOfCurrentStopwatchTime();return t&&this.recordPendingSlice(this.caculateStopwatchTime(e)),this._stopSystemTime=e,this.getTime()},t.prototype.recordPendingSlice=function(t){if(void 0!==this._pendingSliceStartStopwatchTime){void 0===t&&(t=this.getTime());var e=this.calculatePendingSlice(t);return this._pendingSliceStartStopwatchTime=e.endTime,this._completeSlices.push(e),e}return this.calculatePendingSlice()},t}();t.Stopwatch=n,function(t){t.IDLE="IDLE",t.RUNNING="RUNNING",t.STOPPED="STOPPED"}(e||(e={})),t.setDefaultSystemTimeGetter=function(t){void 0===t&&(t=Date.now),i=t};var i=Date.now}(stopwatch||(stopwatch={}));var TimeRuler=function(){function t(){this._frameKey="frame",this._logKey="log",this.markers=[],this.stopwacth=new stopwatch.Stopwatch,this._markerNameToIdMap=new Map,this.showLog=!1,t.Instance=this,this._logs=new Array(2);for(var e=0;e=t.logSnapDuration&&(l.logs[o].snapMin=l.logs[o].min,l.logs[o].snapMax=l.logs[o].max,l.logs[o].snapAvg=l.logs[o].avg,l.logs[o].samples=0)):(l.logs[o].min=h,l.logs[o].max=h,l.logs[o].avg=h,l.logs[o].initialized=!0)}s.markCount=r.nestCount,s.nestCount=r.nestCount}e.stopwacth.reset(),e.stopwacth.start()}})},t.prototype.beginMark=function(e,n,i){var o=this;void 0===i&&(i=0),new LockUtils(this._frameKey).lock().then(function(){if(i<0||i>=t.maxBars)throw new Error("barIndex argument out of range");var r=o._curLog.bars[i];if(r.markCount>=t.maxSamples)throw new Error("exceeded sample count. either set larger number to timeruler.maxsaple or lower sample count");if(r.nestCount>=t.maxNestCall)throw new Error("exceeded nest count. either set larger number to timeruler.maxnestcall or lower nest calls");var s=o._markerNameToIdMap.get(e);s||(s=o.markers.length,o._markerNameToIdMap.set(e,s)),r.markerNests[r.nestCount++]=r.markCount,r.markers[r.markCount].markerId=s,r.markers[r.markCount].color=n,r.markers[r.markCount].beginTime=o.stopwacth.getTime(),r.markers[r.markCount].endTime=-1})},t.prototype.endMark=function(e,n){var i=this;void 0===n&&(n=0),new LockUtils(this._frameKey).lock().then(function(){if(n<0||n>=t.maxBars)throw new Error("barIndex argument out of range");var o=i._curLog.bars[n];if(o.nestCount<=0)throw new Error("call beginMark method before calling endMark method");var r=i._markerNameToIdMap.get(e);if(!r)throw new Error("Marker "+e+" is not registered. Make sure you specifed same name as you used for beginMark method");var s=o.markerNests[--o.nestCount];if(o.markers[s].markerId!=r)throw new Error("Incorrect call order of beginMark/endMark method. beginMark(A), beginMark(B), endMark(B), endMark(A) But you can't called it like beginMark(A), beginMark(B), endMark(A), endMark(B).");o.markers[s].endTime=i.stopwacth.getTime()})},t.prototype.getAverageTime=function(e,n){if(e<0||e>=t.maxBars)throw new Error("barIndex argument out of range");var i=0,o=this._markerNameToIdMap.get(n);return o&&(i=this.markers[o].logs[e].avg),i},t.prototype.resetLog=function(){var t=this;new LockUtils(this._logKey).lock().then(function(){var e=parseInt(egret.localStorage.getItem(t._logKey),10);e+=1,egret.localStorage.setItem(t._logKey,e.toString()),t.markers.forEach(function(t){for(var e=0;e0&&(i+=t.barHeight+2*t.barPadding,o=Math.max(o,e.markers[e.markCount-1].endTime))});var r=this.sampleFrames*(1/60*1e3);this._frameAdjust=o>r?Math.max(0,this._frameAdjust)+1:Math.min(0,this._frameAdjust)-1,Math.max(this._frameAdjust)>t.autoAdjustDelay&&(this.sampleFrames=Math.min(t.maxSampleFrames,this.sampleFrames),this.sampleFrames=Math.max(this.targetSampleFrames,o/(1/60*1e3)+1),this._frameAdjust=0);e.y,t.barHeight}},t.maxBars=0,t.maxSamples=256,t.maxNestCall=32,t.barHeight=8,t.maxSampleFrames=4,t.logSnapDuration=120,t.barPadding=2,t.autoAdjustDelay=30,t}(),FrameLog=function(){return function(){this.bars=new Array(TimeRuler.maxBars);for(var t=0;t0&&r[r.length-1])&&(6===o[0]||2===o[0])){s=0;continue}if(3===o[0]&&(!r||o[1]>r[0]&&o[1]-1}(this,t)},Array.prototype.firstOrDefault=function(t){return function(t,e){var n=t.findIndex(e);return-1==n?null:t[n]}(this,t)},Array.prototype.find=function(t){return function(t,e){return t.firstOrDefault(e)}(this,t)},Array.prototype.where=function(t){return function(t,e){if("function"==typeof t.reduce)return t.reduce(function(n,i,r){return e.call(arguments[2],i,r,t)&&n.push(i),n},[]);for(var n=[],i=0,r=t.length;i=0&&t.splice(n,1)}while(n>=0)}(this,t)},Array.prototype.remove=function(t){return function(t,e){var n=t.findIndex(function(t){return t===e});return n>=0&&(t.splice(n,1),!0)}(this,t)},Array.prototype.removeAt=function(t){return function(t,e){t.splice(e,1)}(this,t)},Array.prototype.removeRange=function(t,e){return function(t,e,n){t.splice(e,n)}(this,t,e)},Array.prototype.select=function(t){return function(t,e){if("function"==typeof t.reduce)return t.reduce(function(n,i,r){return n.push(e.call(arguments[2],i,r,t)),n},[]);for(var n=[],i=0,r=t.length;io?1:-1}),t}(this,t,e)},Array.prototype.orderByDescending=function(t,e){return function(t,e,n){return t.sort(function(t,i){var r=e(t),o=e(i);return n?-n(r,o):r0;){if("break"===c())break}return r?this.recontructPath(o,e,n):null},t.hasKey=function(t,e){for(var n,i=t.keys();!(n=i.next()).done;)if(JSON.stringify(n.value)==JSON.stringify(e))return!0;return!1},t.getKey=function(t,e){for(var n,i,r=t.keys(),o=t.values();n=r.next(),i=o.next(),!n.done;)if(JSON.stringify(n.value)==JSON.stringify(e))return i.value;return null},t.recontructPath=function(t,e,n){var i=[],r=n;for(i.push(n);r!=e;)r=this.getKey(t,r),i.push(r);return i.reverse(),i},t}(),AStarNode=function(t){function e(e){var n=t.call(this)||this;return n.data=e,n}return __extends(e,t),e}(PriorityQueueNode),AstarGridGraph=function(){function t(t,e){this.dirs=[new Vector2(1,0),new Vector2(0,-1),new Vector2(-1,0),new Vector2(0,1)],this.walls=[],this.weightedNodes=[],this.defaultWeight=1,this.weightedNodeWeight=5,this._neighbors=new Array(4),this._width=t,this._height=e}return t.prototype.isNodeInBounds=function(t){return 0<=t.x&&t.x=this._nodes.length?(console.error("node.QueueIndex has been corrupted. Did you change it manually? Or add this node to another queue?"),!1):this._nodes[t.queueIndex]==t:(console.error("node cannot be null"),!1)},t.prototype.enqueue=function(t,e){t.priority=e,this._numNodes++,this._nodes[this._numNodes]=t,t.queueIndex=this._numNodes,t.insertionIndex=this._numNodesEverEnqueued++,this.cascadeUp(this._nodes[this._numNodes])},t.prototype.dequeue=function(){var t=this._nodes[1];return this.remove(t),t},t.prototype.remove=function(t){if(t.queueIndex==this._numNodes)return this._nodes[this._numNodes]=null,void this._numNodes--;var e=this._nodes[this._numNodes];this.swap(t,e),delete this._nodes[this._numNodes],this._numNodes--,this.onNodeUpdated(e)},t.prototype.isValidQueue=function(){for(var t=1;t0&&this.hasHigherPriority(t,n)?this.cascadeUp(t):this.cascadeDown(t)},t.prototype.cascadeDown=function(t){for(var e,n=t.queueIndex;;){e=t;var i=2*n;if(i>this._numNodes){t.queueIndex=n,this._nodes[n]=t;break}var r=this._nodes[i];this.hasHigherPriority(r,e)&&(e=r);var o=i+1;if(o<=this._numNodes){var s=this._nodes[o];this.hasHigherPriority(s,e)&&(e=s)}if(e==t){t.queueIndex=n,this._nodes[n]=t;break}this._nodes[n]=e;var a=e.queueIndex;e.queueIndex=n,n=a}},t.prototype.cascadeUp=function(t){for(var e=Math.floor(t.queueIndex/2);e>=1;){var n=this._nodes[e];if(this.hasHigherPriority(n,t))break;this.swap(t,n),e=Math.floor(t.queueIndex/2)}},t.prototype.swap=function(t,e){this._nodes[t.queueIndex]=e,this._nodes[e.queueIndex]=t;var n=t.queueIndex;t.queueIndex=e.queueIndex,e.queueIndex=n},t.prototype.hasHigherPriority=function(t,e){return t.priority0;){if("break"===a())break}return r?AStarPathfinder.recontructPath(s,e,n):null},t.hasKey=function(t,e){for(var n,i=t.keys();!(n=i.next()).done;)if(JSON.stringify(n.value)==JSON.stringify(e))return!0;return!1},t}(),UnweightedGraph=function(){function t(){this.edges=new Map}return t.prototype.addEdgesForNode=function(t,e){return this.edges.set(t,e),this},t.prototype.getNeighbors=function(t){return this.edges.get(t)},t}(),Vector2=function(){function t(t,e){this.x=0,this.y=0,this.x=t||0,this.y=e||this.x}return Object.defineProperty(t,"zero",{get:function(){return t.zeroVector2},enumerable:!0,configurable:!0}),Object.defineProperty(t,"one",{get:function(){return t.unitVector2},enumerable:!0,configurable:!0}),Object.defineProperty(t,"unitX",{get:function(){return t.unitXVector},enumerable:!0,configurable:!0}),Object.defineProperty(t,"unitY",{get:function(){return t.unitYVector},enumerable:!0,configurable:!0}),t.add=function(e,n){var i=new t(0,0);return i.x=e.x+n.x,i.y=e.y+n.y,i},t.divide=function(e,n){var i=new t(0,0);return i.x=e.x/n.x,i.y=e.y/n.y,i},t.multiply=function(e,n){var i=new t(0,0);return i.x=e.x*n.x,i.y=e.y*n.y,i},t.subtract=function(e,n){var i=new t(0,0);return i.x=e.x-n.x,i.y=e.y-n.y,i},t.prototype.normalize=function(){var t=1/Math.sqrt(this.x*this.x+this.y*this.y);this.x*=t,this.y*=t},t.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},t.prototype.round=function(){return new t(Math.round(this.x),Math.round(this.y))},t.normalize=function(t){var e=1/Math.sqrt(t.x*t.x+t.y*t.y);return t.x*=e,t.y*=e,t},t.dot=function(t,e){return t.x*e.x+t.y*e.y},t.distanceSquared=function(t,e){var n=t.x-e.x,i=t.y-e.y;return n*n+i*i},t.clamp=function(e,n,i){return new t(MathHelper.clamp(e.x,n.x,i.x),MathHelper.clamp(e.y,n.y,i.y))},t.lerp=function(e,n,i){return new t(MathHelper.lerp(e.x,n.x,i),MathHelper.lerp(e.y,n.y,i))},t.transform=function(e,n){return new t(e.x*n.m11+e.y*n.m21,e.x*n.m12+e.y*n.m22)},t.distance=function(t,e){var n=t.x-e.x,i=t.y-e.y;return Math.sqrt(n*n+i*i)},t.negate=function(e){var n=new t;return n.x=-e.x,n.y=-e.y,n},t.unitYVector=new t(0,1),t.unitXVector=new t(1,0),t.unitVector2=new t(1,1),t.zeroVector2=new t(0,0),t}(),UnweightedGridGraph=function(){function t(e,n,i){void 0===i&&(i=!1),this.walls=[],this._neighbors=new Array(4),this._width=e,this._hegiht=n,this._dirs=i?t.COMPASS_DIRS:t.CARDINAL_DIRS}return t.prototype.isNodeInBounds=function(t){return 0<=t.x&&t.x0;){if("break"===c())break}return r?this.recontructPath(o,e,n):null},t.hasKey=function(t,e){for(var n,i=t.keys();!(n=i.next()).done;)if(JSON.stringify(n.value)==JSON.stringify(e))return!0;return!1},t.getKey=function(t,e){for(var n,i,r=t.keys(),o=t.values();n=r.next(),i=o.next(),!n.done;)if(JSON.stringify(n.value)==JSON.stringify(e))return i.value;return null},t.recontructPath=function(t,e,n){var i=[],r=n;for(i.push(n);r!=e;)r=this.getKey(t,r),i.push(r);return i.reverse(),i},t}(),Debug=function(){function t(){}return t.drawHollowRect=function(t,e,n){void 0===n&&(n=0),this._debugDrawItems.push(new DebugDrawItem(t,e,n))},t.render=function(){if(this._debugDrawItems.length>0){var t=new egret.Shape;SceneManager.scene&&SceneManager.scene.addChild(t);for(var e=this._debugDrawItems.length-1;e>=0;e--){this._debugDrawItems[e].draw(t)&&this._debugDrawItems.removeAt(e)}}},t._debugDrawItems=[],t}(),DebugDefaults=function(){function t(){}return t.verletParticle=14431326,t.verletConstraintEdge=4406838,t}();!function(t){t[t.line=0]="line",t[t.hollowRectangle=1]="hollowRectangle",t[t.pixel=2]="pixel",t[t.text=3]="text"}(DebugDrawType||(DebugDrawType={}));var CoreEvents,DebugDrawItem=function(){function t(t,e,n){this.rectangle=t,this.color=e,this.duration=n,this.drawType=DebugDrawType.hollowRectangle}return t.prototype.draw=function(t){switch(this.drawType){case DebugDrawType.line:DrawUtils.drawLine(t,this.start,this.end,this.color);break;case DebugDrawType.hollowRectangle:DrawUtils.drawHollowRect(t,this.rectangle,this.color);break;case DebugDrawType.pixel:DrawUtils.drawPixel(t,new Vector2(this.x,this.y),this.color,this.size);break;case DebugDrawType.text:}return this.duration-=Time.deltaTime,this.duration<0},t}(),Component=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e._enabled=!0,e.updateInterval=1,e._updateOrder=0,e}return __extends(e,t),Object.defineProperty(e.prototype,"enabled",{get:function(){return this.entity?this.entity.enabled&&this._enabled:this._enabled},set:function(t){this.setEnabled(t)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"localPosition",{get:function(){return new Vector2(this.entity.x+this.x,this.entity.y+this.y)},enumerable:!0,configurable:!0}),e.prototype.setEnabled=function(t){return this._enabled!=t&&(this._enabled=t,this._enabled?this.onEnabled():this.onDisabled()),this},Object.defineProperty(e.prototype,"updateOrder",{get:function(){return this._updateOrder},set:function(t){this.setUpdateOrder(t)},enumerable:!0,configurable:!0}),e.prototype.setUpdateOrder=function(t){return this._updateOrder!=t&&(this._updateOrder=t),this},e.prototype.initialize=function(){},e.prototype.onAddedToEntity=function(){},e.prototype.onRemovedFromEntity=function(){},e.prototype.onEnabled=function(){},e.prototype.onDisabled=function(){},e.prototype.debugRender=function(){},e.prototype.update=function(){},e.prototype.onEntityTransformChanged=function(t){},e.prototype.registerComponent=function(){this.entity.componentBits.set(ComponentTypeManager.getIndexFor(this),!1),this.entity.scene.entityProcessors.onComponentAdded(this.entity)},e.prototype.deregisterComponent=function(){this.entity.componentBits.set(ComponentTypeManager.getIndexFor(this)),this.entity.scene.entityProcessors.onComponentRemoved(this.entity)},e}(egret.DisplayObjectContainer);!function(t){t[t.SceneChanged=0]="SceneChanged"}(CoreEvents||(CoreEvents={}));var TransformComponent,Entity=function(t){function e(n){var i=t.call(this)||this;return i._updateOrder=0,i._enabled=!0,i._tag=0,i.name=n,i.components=new ComponentList(i),i.id=e._idGenerator++,i.componentBits=new BitSet,i.addEventListener(egret.Event.ADDED_TO_STAGE,i.onAddToStage,i),i}return __extends(e,t),Object.defineProperty(e.prototype,"isDestoryed",{get:function(){return this._isDestoryed},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"position",{get:function(){return new Vector2(this.x,this.y)},set:function(t){this.$setX(t.x),this.$setY(t.y),this.onEntityTransformChanged(TransformComponent.position)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"scale",{get:function(){return new Vector2(this.scaleX,this.scaleY)},set:function(t){this.$setScaleX(t.x),this.$setScaleY(t.y),this.onEntityTransformChanged(TransformComponent.scale)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"rotation",{get:function(){return this.$getRotation()},set:function(t){this.$setRotation(t),this.onEntityTransformChanged(TransformComponent.rotation)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"enabled",{get:function(){return this._enabled},set:function(t){this.setEnabled(t)},enumerable:!0,configurable:!0}),e.prototype.setEnabled=function(t){return this._enabled!=t&&(this._enabled=t),this},Object.defineProperty(e.prototype,"tag",{get:function(){return this._tag},set:function(t){this.setTag(t)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"stage",{get:function(){return this.scene?this.scene.stage:null},enumerable:!0,configurable:!0}),e.prototype.onAddToStage=function(){this.onEntityTransformChanged(TransformComponent.position)},Object.defineProperty(e.prototype,"updateOrder",{get:function(){return this._updateOrder},set:function(t){this.setUpdateOrder(t)},enumerable:!0,configurable:!0}),e.prototype.roundPosition=function(){this.position=Vector2Ext.round(this.position)},e.prototype.setUpdateOrder=function(t){if(this._updateOrder!=t)return this._updateOrder=t,this.scene,this},e.prototype.setTag=function(t){return this._tag!=t&&(this.scene&&this.scene.entities.removeFromTagList(this),this._tag=t,this.scene&&this.scene.entities.addToTagList(this)),this},e.prototype.attachToScene=function(t){this.scene=t,t.entities.add(this),this.components.registerAllComponents();for(var e=0;e=0;t--){this.getChildAt(t).entity.destroy()}},e}(egret.DisplayObjectContainer);!function(t){t[t.rotation=0]="rotation",t[t.scale=1]="scale",t[t.position=2]="position"}(TransformComponent||(TransformComponent={}));var CameraStyle,Scene=function(t){function e(){var e=t.call(this)||this;return e.enablePostProcessing=!0,e._renderers=[],e._postProcessors=[],e.entityProcessors=new EntityProcessorList,e.renderableComponents=new RenderableComponentList,e.entities=new EntityList(e),e.content=new ContentManager,e.width=SceneManager.stage.stageWidth,e.height=SceneManager.stage.stageHeight,e.addEventListener(egret.Event.ACTIVATE,e.onActive,e),e.addEventListener(egret.Event.DEACTIVATE,e.onDeactive,e),e}return __extends(e,t),e.prototype.createEntity=function(t){var e=new Entity(t);return e.position=new Vector2(0,0),this.addEntity(e)},e.prototype.addEntity=function(t){this.entities.add(t),t.scene=this,this.addChild(t);for(var e=0;e=0;e--)GlobalManager.globalManagers[e].enabled&&GlobalManager.globalManagers[e].update();t.sceneTransition&&(!t.sceneTransition||t.sceneTransition.loadsNewScene&&!t.sceneTransition.isNewSceneLoaded)||t._scene.update(),t._nextScene&&(t._scene.end(),t._scene=t._nextScene,t._nextScene=null,t._instnace.onSceneChanged(),t._scene.begin())}t.render()},t.render=function(){this.sceneTransition?(this.sceneTransition.preRender(),this._scene&&!this.sceneTransition.hasPreviousSceneRender?(this._scene.render(),this._scene.postRender(),this.sceneTransition.onBeginTransition()):this.sceneTransition&&(this._scene&&this.sceneTransition.isNewSceneLoaded&&(this._scene.render(),this._scene.postRender()),this.sceneTransition.render())):this._scene&&(this._scene.render(),Debug.render(),this._scene.postRender())},t.startSceneTransition=function(t){if(!this.sceneTransition)return this.sceneTransition=t,t;console.warn("在前一个场景完成之前,不能开始一个新的场景转换。")},t.registerActiveSceneChanged=function(t,e){this.activeSceneChanged&&this.activeSceneChanged(t,e)},t.prototype.onSceneChanged=function(){t.emitter.emit(CoreEvents.SceneChanged),Time.sceneChanged()},t}(),Camera=function(t){function e(){var e=t.call(this)||this;return e._origin=Vector2.zero,e._minimumZoom=.3,e._maximumZoom=3,e._position=Vector2.zero,e.followLerp=.1,e.deadzone=new Rectangle,e.focusOffset=new Vector2,e.mapLockEnabled=!1,e.mapSize=new Vector2,e._worldSpaceDeadZone=new Rectangle,e._desiredPositionDelta=new Vector2,e.cameraStyle=CameraStyle.lockOn,e.width=SceneManager.stage.stageWidth,e.height=SceneManager.stage.stageHeight,e.setZoom(0),e}return __extends(e,t),Object.defineProperty(e.prototype,"zoom",{get:function(){return 0==this._zoom?1:this._zoom<1?MathHelper.map(this._zoom,this._minimumZoom,1,-1,0):MathHelper.map(this._zoom,1,this._maximumZoom,0,1)},set:function(t){this.setZoom(t)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"minimumZoom",{get:function(){return this._minimumZoom},set:function(t){this.setMinimumZoom(t)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"maximumZoom",{get:function(){return this._maximumZoom},set:function(t){this.setMaximumZoom(t)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"origin",{get:function(){return this._origin},set:function(t){this._origin!=t&&(this._origin=t)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"position",{get:function(){return this._position},set:function(t){this._position=t},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"x",{get:function(){return this._position.x},set:function(t){this._position.x=t},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"y",{get:function(){return this._position.y},set:function(t){this._position.y=t},enumerable:!0,configurable:!0}),e.prototype.onSceneSizeChanged=function(t,e){var n=this._origin;this.origin=new Vector2(t/2,e/2),this.entity.position=Vector2.add(this.entity.position,Vector2.subtract(this._origin,n))},e.prototype.setMinimumZoom=function(t){return this._zoomt&&(this._zoom=t),this._maximumZoom=t,this},e.prototype.setZoom=function(t){var e=MathHelper.clamp(t,-1,1);return this._zoom=0==e?1:e<0?MathHelper.map(e,-1,0,this._minimumZoom,1):MathHelper.map(e,0,1,1,this._maximumZoom),SceneManager.scene.scaleX=this._zoom,SceneManager.scene.scaleY=this._zoom,this},e.prototype.setRotation=function(t){return SceneManager.scene.rotation=t,this},e.prototype.setPosition=function(t){return this.entity.position=t,this},e.prototype.follow=function(t,e){void 0===e&&(e=CameraStyle.cameraWindow),this.targetEntity=t,this.cameraStyle=e;var n=new Rectangle(0,0,SceneManager.stage.stageWidth,SceneManager.stage.stageHeight);switch(this.cameraStyle){case CameraStyle.cameraWindow:var i=n.width/6,r=n.height/3;this.deadzone=new Rectangle((n.width-i)/2,(n.height-r)/2,i,r);break;case CameraStyle.lockOn:this.deadzone=new Rectangle(n.width/2,n.height/2,10,10)}},e.prototype.update=function(){var t=new Rectangle(0,0,SceneManager.stage.stageWidth,SceneManager.stage.stageHeight),e=Vector2.multiply(new Vector2(t.width,t.height),new Vector2(.5));this._worldSpaceDeadZone.x=this.position.x-e.x+this.deadzone.x+this.focusOffset.x,this._worldSpaceDeadZone.y=this.position.y-e.y+this.deadzone.y+this.focusOffset.y,this._worldSpaceDeadZone.width=this.deadzone.width,this._worldSpaceDeadZone.height=this.deadzone.height,this.targetEntity&&this.updateFollow(),this.position=Vector2.lerp(this.position,Vector2.add(this.position,this._desiredPositionDelta),this.followLerp),this.entity.roundPosition(),this.mapLockEnabled&&(this.position=this.clampToMapSize(this.position),this.entity.roundPosition())},e.prototype.clampToMapSize=function(t){var e=new Rectangle(0,0,SceneManager.stage.stageWidth,SceneManager.stage.stageHeight),n=Vector2.multiply(new Vector2(e.width,e.height),new Vector2(.5)),i=new Vector2(this.mapSize.x-n.x,this.mapSize.y-n.y);return Vector2.clamp(t,n,i)},e.prototype.updateFollow=function(){if(this._desiredPositionDelta.x=this._desiredPositionDelta.y=0,this.cameraStyle==CameraStyle.lockOn){var t=this.targetEntity.position.x,e=this.targetEntity.position.y;this._worldSpaceDeadZone.x>t?this._desiredPositionDelta.x=t-this._worldSpaceDeadZone.x:this._worldSpaceDeadZone.xe&&(this._desiredPositionDelta.y=e-this._worldSpaceDeadZone.y)}else{if(!this._targetCollider&&(this._targetCollider=this.targetEntity.getComponent(Collider),!this._targetCollider))return;var n=this.targetEntity.getComponent(Collider).bounds;this._worldSpaceDeadZone.containsRect(n)||(this._worldSpaceDeadZone.left>n.left?this._desiredPositionDelta.x=n.left-this._worldSpaceDeadZone.left:this._worldSpaceDeadZone.rightn.top&&(this._desiredPositionDelta.y=n.top-this._worldSpaceDeadZone.top))}},e}(Component);!function(t){t[t.lockOn=0]="lockOn",t[t.cameraWindow=1]="cameraWindow"}(CameraStyle||(CameraStyle={}));var LoopMode,State,ComponentPool=function(){function t(t){this._type=t,this._cache=[]}return t.prototype.obtain=function(){try{return this._cache.length>0?this._cache.shift():new this._type}catch(t){throw new Error(this._type+t)}},t.prototype.free=function(t){t.reset(),this._cache.push(t)},t}(),PooledComponent=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return __extends(e,t),e}(Component),RenderableComponent=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e._areBoundsDirty=!0,e._bounds=new Rectangle,e._localOffset=Vector2.zero,e.color=0,e}return __extends(e,t),Object.defineProperty(e.prototype,"width",{get:function(){return this.getWidth()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"height",{get:function(){return this.getHeight()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"isVisible",{get:function(){return this._isVisible},set:function(t){this._isVisible=t,this._isVisible?this.onBecameVisible():this.onBecameInvisible()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"bounds",{get:function(){return new Rectangle(this.getBounds().x,this.getBounds().y,this.getBounds().width,this.getBounds().height)},enumerable:!0,configurable:!0}),e.prototype.getWidth=function(){return this.bounds.width},e.prototype.getHeight=function(){return this.bounds.height},e.prototype.onBecameVisible=function(){},e.prototype.onBecameInvisible=function(){},e.prototype.isVisibleFromCamera=function(t){return this.isVisible=t.getBounds().intersects(this.getBounds()),this.isVisible},e}(PooledComponent),Mesh=function(t){function e(){var e=t.call(this)||this;return e._mesh=new egret.Mesh,e}return __extends(e,t),e.prototype.setTexture=function(t){return this._mesh.texture=t,this},e.prototype.onAddedToEntity=function(){this.addChild(this._mesh)},e.prototype.onRemovedFromEntity=function(){this.removeChild(this._mesh)},e.prototype.render=function(t){this.x=this.entity.position.x-t.position.x+t.origin.x,this.y=this.entity.position.y-t.position.y+t.origin.y},e.prototype.reset=function(){},e}(RenderableComponent),SpriteRenderer=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return __extends(e,t),Object.defineProperty(e.prototype,"sprite",{get:function(){return this._sprite},set:function(t){this.setSprite(t)},enumerable:!0,configurable:!0}),e.prototype.setSprite=function(t){return this.removeChildren(),this._sprite=t,this._sprite&&(this.anchorOffsetX=this._sprite.origin.x/this._sprite.sourceRect.width,this.anchorOffsetY=this._sprite.origin.y/this._sprite.sourceRect.height),this.bitmap=new egret.Bitmap(t.texture2D),this.addChild(this.bitmap),this},e.prototype.setColor=function(t){var e=[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0];e[0]=Math.floor(t/256/256)/255,e[6]=Math.floor(t/256%256)/255,e[12]=t%256/255;var n=new egret.ColorMatrixFilter(e);return this.filters=[n],this},e.prototype.isVisibleFromCamera=function(t){return this.isVisible=new Rectangle(0,0,this.stage.stageWidth,this.stage.stageHeight).intersects(this.bounds),this.visible=this.isVisible,this.isVisible},e.prototype.render=function(t){this.x=-t.position.x+t.origin.x,this.y=-t.position.y+t.origin.y},e.prototype.onRemovedFromEntity=function(){this.parent&&this.parent.removeChild(this)},e.prototype.reset=function(){},e}(RenderableComponent),TiledSpriteRenderer=function(t){function e(e){var n=t.call(this)||this;return n.leftTexture=new egret.Bitmap,n.rightTexture=new egret.Bitmap,n.leftTexture.texture=e.texture2D,n.rightTexture.texture=e.texture2D,n.setSprite(e),n.sourceRect=e.sourceRect,n}return __extends(e,t),Object.defineProperty(e.prototype,"scrollX",{get:function(){return this.sourceRect.x},set:function(t){this.sourceRect.x=t},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"scrollY",{get:function(){return this.sourceRect.y},set:function(t){this.sourceRect.y=t},enumerable:!0,configurable:!0}),e.prototype.render=function(e){if(this.sprite){t.prototype.render.call(this,e);var n=new egret.RenderTexture,i=new egret.DisplayObjectContainer;i.removeChildren(),i.addChild(this.leftTexture),i.addChild(this.rightTexture),this.leftTexture.x=this.sourceRect.x,this.rightTexture.x=this.sourceRect.x-this.sourceRect.width,this.leftTexture.y=this.sourceRect.y,this.rightTexture.y=this.sourceRect.y,i.cacheAsBitmap=!0,n.drawToTexture(i,new egret.Rectangle(0,0,this.sourceRect.width,this.sourceRect.height)),this.bitmap.texture=n}},e}(SpriteRenderer),ScrollingSpriteRenderer=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e.scrollSpeedX=15,e.scroolSpeedY=0,e._scrollX=0,e._scrollY=0,e}return __extends(e,t),e.prototype.update=function(){this._scrollX+=this.scrollSpeedX*Time.deltaTime,this._scrollY+=this.scroolSpeedY*Time.deltaTime,this.sourceRect.x=this._scrollX,this.sourceRect.y=this._scrollY},e.prototype.render=function(e){if(this.sprite){t.prototype.render.call(this,e);var n=new egret.RenderTexture,i=new egret.DisplayObjectContainer;i.removeChildren(),i.addChild(this.leftTexture),i.addChild(this.rightTexture),this.leftTexture.x=this.sourceRect.x,this.rightTexture.x=this.sourceRect.x-this.sourceRect.width,this.leftTexture.y=this.sourceRect.y,this.rightTexture.y=this.sourceRect.y,i.cacheAsBitmap=!0,n.drawToTexture(i,new egret.Rectangle(0,0,this.sourceRect.width,this.sourceRect.height)),this.bitmap.texture=n}},e}(TiledSpriteRenderer),Sprite=function(){return function(t,e,n){void 0===e&&(e=new Rectangle(0,0,t.textureWidth,t.textureHeight)),void 0===n&&(n=e.getHalfSize()),this.uvs=new Rectangle,this.texture2D=t,this.sourceRect=e,this.center=new Vector2(.5*e.width,.5*e.height),this.origin=n;var i=1/t.textureWidth,r=1/t.textureHeight;this.uvs.x=e.x*i,this.uvs.y=e.y*r,this.uvs.width=e.width*i,this.uvs.height=e.height*r}}(),SpriteAnimation=function(){return function(t,e){this.sprites=t,this.frameRate=e}}(),SpriteAnimator=function(t){function e(e){var n=t.call(this)||this;return n.speed=1,n.animationState=State.none,n._animations=new Map,n._elapsedTime=0,e&&n.setSprite(e),n}return __extends(e,t),Object.defineProperty(e.prototype,"isRunning",{get:function(){return this.animationState==State.running},enumerable:!0,configurable:!0}),e.prototype.addAnimation=function(t,e){return!this.sprite&&e.sprites.length>0&&this.setSprite(e.sprites[0]),this._animations[t]=e,this},e.prototype.play=function(t,e){void 0===e&&(e=null),this.currentAnimation=this._animations[t],this.currentAnimationName=t,this.currentFrame=0,this.animationState=State.running,this.sprite=this.currentAnimation.sprites[0],this._elapsedTime=0,this._loopMode=e||LoopMode.loop},e.prototype.isAnimationActive=function(t){return this.currentAnimation&&this.currentAnimationName==t},e.prototype.pause=function(){this.animationState=State.paused},e.prototype.unPause=function(){this.animationState=State.running},e.prototype.stop=function(){this.currentAnimation=null,this.currentAnimationName=null,this.currentFrame=0,this.animationState=State.none},e.prototype.update=function(){if(this.animationState==State.running&&this.currentAnimation){var t=this.currentAnimation,e=1/(t.frameRate*this.speed),n=e*t.sprites.length;this._elapsedTime+=Time.deltaTime;var i=Math.abs(this._elapsedTime);if(this._loopMode==LoopMode.once&&i>n||this._loopMode==LoopMode.pingPongOnce&&i>2*n)return this.animationState=State.completed,this._elapsedTime=0,this.currentFrame=0,void(this.sprite=t.sprites[this.currentFrame]);var r=Math.floor(i/e),o=t.sprites.length;if(o>2&&(this._loopMode==LoopMode.pingPong||this._loopMode==LoopMode.pingPongOnce)){var s=o-1;this.currentFrame=s-Math.abs(s-r%(2*s))}else this.currentFrame=r%o;this.sprite=t.sprites[this.currentFrame]}},e}(SpriteRenderer);!function(t){t[t.loop=0]="loop",t[t.once=1]="once",t[t.clampForever=2]="clampForever",t[t.pingPong=3]="pingPong",t[t.pingPongOnce=4]="pingPongOnce"}(LoopMode||(LoopMode={})),function(t){t[t.none=0]="none",t[t.running=1]="running",t[t.paused=2]="paused",t[t.completed=3]="completed"}(State||(State={}));var PointSectors,Mover=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return __extends(e,t),e.prototype.onAddedToEntity=function(){this._triggerHelper=new ColliderTriggerHelper(this.entity)},e.prototype.calculateMovement=function(t){var e=new CollisionResult;if(!this.entity.getComponent(Collider)||!this._triggerHelper)return null;for(var n=this.entity.getComponents(Collider),i=0;i>6;0!=(e&t.LONG_MASK)&&n++,this._bits=new Array(n)}return t.prototype.and=function(t){for(var e,n=Math.min(this._bits.length,t._bits.length),i=0;i=0;)this._bits[e]&=~t._bits[e]},t.prototype.cardinality=function(){for(var t=0,e=this._bits.length-1;e>=0;e--){var n=this._bits[e];if(0!=n)if(-1!=n){var i=((n=((n=(n>>1&0x5555555555555400)+(0x5555555555555400&n))>>2&0x3333333333333400)+(0x3333333333333400&n))>>32)+n;t+=((i=((i=(i>>4&252645135)+(252645135&i))>>8&16711935)+(16711935&i))>>16&65535)+(65535&i)}else t+=64}return t},t.prototype.clear=function(t){if(null!=t){var e=t>>6;this.ensure(e),this._bits[e]&=~(1<=this._bits.length){var e=new Number[t+1];e=this._bits.copyWithin(0,0,this._bits.length),this._bits=e}},t.prototype.get=function(t){var e=t>>6;return!(e>=this._bits.length)&&0!=(this._bits[e]&1<=0;)if(0!=(this._bits[e]&t._bits[e]))return!0;return!1},t.prototype.isEmpty=function(){for(var t=this._bits.length-1;t>=0;t--)if(this._bits[t])return!1;return!0},t.prototype.nextSetBit=function(t){for(var e=t>>6,n=1<>6;this.ensure(n),this._bits[n]|=1<0){for(var t=0;t0){t=0;for(var e=this._componentsToAdd.length;t0){var e=this._entitiesToRemove;this._entitiesToRemove=this._tempEntityList,this._tempEntityList=e,this._tempEntityList.forEach(function(e){t._entities.remove(e),e.scene=null,t.scene.entityProcessors.onEntityRemoved(e)}),this._tempEntityList.length=0}if(this._entitiesToAdded.length>0){e=this._entitiesToAdded;this._entitiesToAdded=this._tempEntityList,this._tempEntityList=e,this._tempEntityList.forEach(function(e){t._entities.contains(e)||(t._entities.push(e),e.scene=t.scene,t.scene.entityProcessors.onEntityAdded(e))}),this._tempEntityList.forEach(function(t){return t.onAddedToScene()}),this._tempEntityList.length=0}this._unsortedTags.length>0&&(this._unsortedTags.forEach(function(e){t._entityDict.get(e).sort()}),this._unsortedTags.length=0)},t}(),EntityProcessorList=function(){function t(){this._processors=[]}return t.prototype.add=function(t){this._processors.push(t)},t.prototype.remove=function(t){this._processors.remove(t)},t.prototype.onComponentAdded=function(t){this.notifyEntityChanged(t)},t.prototype.onComponentRemoved=function(t){this.notifyEntityChanged(t)},t.prototype.onEntityAdded=function(t){this.notifyEntityChanged(t)},t.prototype.onEntityRemoved=function(t){this.removeFromProcessors(t)},t.prototype.notifyEntityChanged=function(t){for(var e=0;e=0;e=this.allSet.nextSetBit(e+1))if(!t.componentBits.get(e))return!1;return!(!this.exclusionSet.isEmpty()&&this.exclusionSet.intersects(t.componentBits))&&!(!this.oneSet.isEmpty()&&!this.oneSet.intersects(t.componentBits))},t.prototype.all=function(){for(var t=this,e=[],n=0;n=e)return t;var i=!1;"-"==t.substr(0,1)&&(i=!0,t=t.substr(1));for(var r=e-n,o=0;o1?this.reverse(t.substring(1))+t.substring(0,1):t},t.cutOff=function(t,e,n,i){void 0===i&&(i=!0),e=Math.floor(e),n=Math.floor(n);var r=t.length;e>r&&(e=r);var o,s=e,a=e+n;return i?o=t.substring(0,s)+t.substr(a,r):(a=(s=r-1-e-n)+n,o=t.substring(0,s+1)+t.substr(a+1,r)),o},t.strReplace=function(t,e){for(var n=0,i=e.length;n",">",'"',""","'","'","®","®","©","©","™","™"],t}(),TextureUtils=function(){function t(){}return t.convertImageToCanvas=function(t,e){this.sharedCanvas||(this.sharedCanvas=egret.sys.createCanvas(),this.sharedContext=this.sharedCanvas.getContext("2d"));var n=t.$getTextureWidth(),i=t.$getTextureHeight();e||((e=egret.$TempRectangle).x=0,e.y=0,e.width=n,e.height=i),e.x=Math.min(e.x,n-1),e.y=Math.min(e.y,i-1),e.width=Math.min(e.width,n-e.x),e.height=Math.min(e.height,i-e.y);var r=Math.floor(e.width),o=Math.floor(e.height),s=this.sharedCanvas;if(s.style.width=r+"px",s.style.height=o+"px",this.sharedCanvas.width=r,this.sharedCanvas.height=o,"webgl"==egret.Capabilities.renderMode){var a=void 0;t.$renderBuffer?a=t:(egret.sys.systemRenderer.renderClear&&egret.sys.systemRenderer.renderClear(),(a=new egret.RenderTexture).drawToTexture(new egret.Bitmap(t)));for(var c=a.$renderBuffer.getPixels(e.x,e.y,r,o),h=0,u=0,l=0;l=0?"png":"jpg"});return wx.getFileSystemManager().saveFile({tempFilePath:o,filePath:wx.env.USER_DATA_PATH+"/"+n,success:function(t){}}),o},t.getPixel32=function(t,e,n){return egret.$warn(1041,"getPixel32","getPixels"),t.getPixels(e,n)},t.getPixels=function(t,e,n,i,r){if(void 0===i&&(i=1),void 0===r&&(r=1),"webgl"==egret.Capabilities.renderMode){var o=void 0;return t.$renderBuffer?o=t:(o=new egret.RenderTexture).drawToTexture(new egret.Bitmap(t)),o.$renderBuffer.getPixels(e,n,i,r)}try{this.convertImageToCanvas(t);return this.sharedContext.getImageData(e,n,i,r).data}catch(t){egret.$error(1039)}},t}(),Time=function(){function t(){}return t.update=function(t){var e=(t-this._lastTime)/1e3;this.deltaTime=e*this.timeScale,this.unscaledDeltaTime=e,this._timeSinceSceneLoad+=e,this.frameCount++,this._lastTime=t},t.sceneChanged=function(){this._timeSinceSceneLoad=0},t.checkEvery=function(t){return this._timeSinceSceneLoad/t>(this._timeSinceSceneLoad-this.deltaTime)/t},t.deltaTime=0,t.timeScale=1,t.frameCount=0,t._lastTime=0,t}(),TimeUtils=function(){function t(){}return t.monthId=function(t){void 0===t&&(t=null);var e=(t=t||new Date).getFullYear(),n=t.getMonth()+1;return parseInt(e+(n<10?"0":"")+n)},t.dateId=function(t){void 0===t&&(t=null);var e=(t=t||new Date).getMonth()+1,n=e<10?"0":"",i=t.getDate(),r=i<10?"0":"";return parseInt(t.getFullYear()+n+e+r+i)},t.weekId=function(t,e){void 0===t&&(t=null),void 0===e&&(e=!0),t=t||new Date;var n=new Date;n.setTime(t.getTime()),n.setDate(1),n.setMonth(0);var i=n.getFullYear(),r=n.getDay();0==r&&(r=7);var o=!1;r<=4?(o=r>1,n.setDate(n.getDate()-(r-1))):n.setDate(n.getDate()+7-r+1);var s=this.diffDay(t,n,!1);if(s<0)return n.setDate(1),n.setMonth(0),n.setDate(n.getDate()-1),this.weekId(n,!1);var a=s/7,c=Math.floor(a)+1;if(53==c){n.setTime(t.getTime()),n.setDate(n.getDate()-1);var h=n.getDay();if(0==h&&(h=7),e&&(!o||h<4))return n.setFullYear(n.getFullYear()+1),n.setDate(1),n.setMonth(0),this.weekId(n,!1)}return parseInt(i+"00"+(c>9?"":"0")+c)},t.diffDay=function(t,e,n){void 0===n&&(n=!1);var i=(t.getTime()-e.getTime())/864e5;return n?Math.ceil(i):Math.floor(i)},t.getFirstDayOfWeek=function(t){var e=(t=t||new Date).getDay()||7;return new Date(t.getFullYear(),t.getMonth(),t.getDate()+1-e,0,0,0,0)},t.getFirstOfDay=function(t){return(t=t||new Date).setHours(0,0,0,0),t},t.getNextFirstOfDay=function(t){return new Date(this.getFirstOfDay(t).getTime()+864e5)},t.formatDate=function(t){var e=t.getFullYear(),n=t.getMonth()+1;n=n<10?"0"+n:n;var i=t.getDate();return e+"-"+n+"-"+(i=i<10?"0"+i:i)},t.formatDateTime=function(t){var e=t.getFullYear(),n=t.getMonth()+1;n=n<10?"0"+n:n;var i=t.getDate();i=i<10?"0"+i:i;var r=t.getHours(),o=t.getMinutes();o=o<10?"0"+o:o;var s=t.getSeconds();return e+"-"+n+"-"+i+" "+r+":"+o+":"+(s=s<10?"0"+s:s)},t.parseDate=function(t){var e=Date.parse(t);return isNaN(e)?new Date:new Date(Date.parse(t.replace(/-/g,"/")))},t.secondToTime=function(t,e,n){void 0===t&&(t=0),void 0===e&&(e=":"),void 0===n&&(n=!0);var i=Math.floor(t/3600),r=Math.floor(t%3600/60),o=Math.floor(t%3600%60),s=i.toString(),a=r.toString(),c=o.toString();return i<10&&(s="0"+s),r<10&&(a="0"+a),o<10&&(c="0"+c),n?s+e+a+e+c:a+e+c},t.timeToMillisecond=function(t,e){void 0===e&&(e=":");for(var n=t.split(e),i=0,r=n.length,o=0;o-1?this.os="iOS":n.indexOf("android")>-1&&(this.os="Android");var i=e.language;i=i.indexOf("zh")>-1?"zh-CN":"en-US",this.language=i},e}(egret.Capabilities),GraphicsDevice=function(){return function(){this.graphicsCapabilities=new GraphicsCapabilities,this.graphicsCapabilities.initialize(this)}}(),Viewport=function(){function t(t,e,n,i){this._x=t,this._y=e,this._width=n,this._height=i,this._minDepth=0,this._maxDepth=1}return Object.defineProperty(t.prototype,"aspectRatio",{get:function(){return 0!=this._height&&0!=this._width?this._width/this._height:0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"bounds",{get:function(){return new Rectangle(this._x,this._y,this._width,this._height)},set:function(t){this._x=t.x,this._y=t.y,this._width=t.width,this._height=t.height},enumerable:!0,configurable:!0}),t}(),GaussianBlurEffect=function(t){function e(){return t.call(this,PostProcessor.default_vert,e.blur_frag,{screenWidth:SceneManager.stage.stageWidth,screenHeight:SceneManager.stage.stageHeight})||this}return __extends(e,t),e.blur_frag="precision mediump float;\nuniform sampler2D uSampler;\nuniform float screenWidth;\nuniform float screenHeight;\nfloat normpdf(in float x, in float sigma)\n{\nreturn 0.39894*exp(-0.5*x*x/(sigma*sigma))/sigma;\n}\nvoid main()\n{\nvec3 c = texture2D(uSampler, gl_FragCoord.xy / vec2(screenWidth, screenHeight).xy).rgb;\nconst int mSize = 11;\nconst int kSize = (mSize - 1)/2;\nfloat kernel[mSize];\nvec3 final_colour = vec3(0.0);\nfloat sigma = 7.0;\nfloat z = 0.0;\nfor (int j = 0; j <= kSize; ++j)\n{\nkernel[kSize+j] = kernel[kSize-j] = normpdf(float(j),sigma);\n}\nfor (int j = 0; j < mSize; ++j)\n{\nz += kernel[j];\n}\nfor (int i = -kSize; i <= kSize; ++i)\n{\nfor (int j = -kSize; j <= kSize; ++j)\n{\nfinal_colour += kernel[kSize+j]*kernel[kSize+i]*texture2D(uSampler, (gl_FragCoord.xy+vec2(float(i),float(j))) / vec2(screenWidth, screenHeight).xy).rgb;\n}\n}\ngl_FragColor = vec4(final_colour/(z*z), 1.0);\n}",e}(egret.CustomFilter),PolygonLightEffect=function(t){function e(){return t.call(this,e.vertSrc,e.fragmentSrc)||this}return __extends(e,t),e.vertSrc="attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\nuniform vec2 projectionVector;\nvarying vec2 vTextureCoord;\nconst vec2 center = vec2(-1.0, 1.0);\nvoid main(void) {\n gl_Position = vec4( (aVertexPosition / projectionVector) + center , 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}",e.fragmentSrc="precision lowp float;\nvarying vec2 vTextureCoord;\nuniform sampler2D uSampler;\n#define SAMPLE_COUNT 15\nuniform vec2 _sampleOffsets[SAMPLE_COUNT];\nuniform float _sampleWeights[SAMPLE_COUNT];\nvoid main(void) {\nvec4 c = vec4(0, 0, 0, 0);\nfor( int i = 0; i < SAMPLE_COUNT; i++ )\n c += texture2D( uSampler, vTextureCoord + _sampleOffsets[i] ) * _sampleWeights[i];\ngl_FragColor = c;\n}",e}(egret.CustomFilter),PostProcessor=function(){function t(t){void 0===t&&(t=null),this.enable=!0,this.effect=t}return t.prototype.onAddedToScene=function(t){this.scene=t,this.shape=new egret.Shape,this.shape.graphics.beginFill(16777215,1),this.shape.graphics.drawRect(0,0,SceneManager.stage.stageWidth,SceneManager.stage.stageHeight),this.shape.graphics.endFill(),t.addChild(this.shape)},t.prototype.process=function(){this.drawFullscreenQuad()},t.prototype.onSceneBackBufferSizeChanged=function(t,e){},t.prototype.drawFullscreenQuad=function(){this.scene.filters=[this.effect]},t.prototype.unload=function(){this.effect&&(this.effect=null),this.scene.removeChild(this.shape),this.scene=null},t.default_vert="attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\nattribute vec2 aColor;\nuniform vec2 projectionVector;\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\nconst vec2 center = vec2(-1.0, 1.0);\nvoid main(void) {\ngl_Position = vec4( (aVertexPosition / projectionVector) + center , 0.0, 1.0);\nvTextureCoord = aTextureCoord;\nvColor = vec4(aColor.x, aColor.x, aColor.x, aColor.x);\n}",t}(),GaussianBlurPostProcessor=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return __extends(e,t),e.prototype.onAddedToScene=function(e){t.prototype.onAddedToScene.call(this,e),this.effect=new GaussianBlurEffect},e}(PostProcessor),Renderer=function(){function t(){}return t.prototype.onAddedToScene=function(t){},t.prototype.beginRender=function(t){},t.prototype.unload=function(){},t.prototype.renderAfterStateCheck=function(t,e){t.render(e)},t}(),DefaultRenderer=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return __extends(e,t),e.prototype.render=function(t){var e=this.camera?this.camera:t.camera;this.beginRender(e);for(var n=0;nn?n:t},t.pointOnCirlce=function(e,n,i){var r=t.toRadians(i);return new Vector2(Math.cos(r)*r+e.x,Math.sin(r)*r+e.y)},t.isEven=function(t){return t%2==0},t.clamp01=function(t){return t<0?0:t>1?1:t},t.angleBetweenVectors=function(t,e){return Math.atan2(e.y-t.y,e.x-t.x)},t.Epsilon=1e-5,t.Rad2Deg=57.29578,t.Deg2Rad=.0174532924,t}(),Matrix2D=function(){function t(t,e,n,i,r,o){this.m11=0,this.m12=0,this.m21=0,this.m22=0,this.m31=0,this.m32=0,this.m11=t||1,this.m12=e||0,this.m21=n||0,this.m22=i||1,this.m31=r||0,this.m32=o||0}return Object.defineProperty(t,"identity",{get:function(){return t._identity},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"translation",{get:function(){return new Vector2(this.m31,this.m32)},set:function(t){this.m31=t.x,this.m32=t.y},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"rotation",{get:function(){return Math.atan2(this.m21,this.m11)},set:function(t){var e=Math.cos(t),n=Math.sin(t);this.m11=e,this.m12=n,this.m21=-n,this.m22=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"rotationDegrees",{get:function(){return MathHelper.toDegrees(this.rotation)},set:function(t){this.rotation=MathHelper.toRadians(t)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"scale",{get:function(){return new Vector2(this.m11,this.m22)},set:function(t){this.m11=t.x,this.m12=t.y},enumerable:!0,configurable:!0}),t.add=function(t,e){return t.m11+=e.m11,t.m12+=e.m12,t.m21+=e.m21,t.m22+=e.m22,t.m31+=e.m31,t.m32+=e.m32,t},t.divide=function(t,e){return t.m11/=e.m11,t.m12/=e.m12,t.m21/=e.m21,t.m22/=e.m22,t.m31/=e.m31,t.m32/=e.m32,t},t.multiply=function(e,n){var i=new t,r=e.m11*n.m11+e.m12*n.m21,o=e.m11*n.m12+e.m12*n.m22,s=e.m21*n.m11+e.m22*n.m21,a=e.m21*n.m12+e.m22*n.m22,c=e.m31*n.m11+e.m32*n.m21+n.m31,h=e.m31*n.m12+e.m32*n.m22+n.m32;return i.m11=r,i.m12=o,i.m21=s,i.m22=a,i.m31=c,i.m32=h,i},t.multiplyTranslation=function(e,n,i){var r=t.createTranslation(n,i);return t.multiply(e,r)},t.prototype.determinant=function(){return this.m11*this.m22-this.m12*this.m21},t.invert=function(e,n){void 0===n&&(n=new t);var i=1/e.determinant();return n.m11=e.m22*i,n.m12=-e.m12*i,n.m21=-e.m21*i,n.m22=e.m11*i,n.m31=(e.m32*e.m21-e.m31*e.m22)*i,n.m32=-(e.m32*e.m11-e.m31*e.m12)*i,n},t.createTranslation=function(e,n){var i=new t;return i.m11=1,i.m12=0,i.m21=0,i.m22=1,i.m31=e,i.m32=n,i},t.createTranslationVector=function(t){return this.createTranslation(t.x,t.y)},t.createRotation=function(e,n){n=new t;var i=Math.cos(e),r=Math.sin(e);return n.m11=i,n.m12=r,n.m21=-r,n.m22=i,n},t.createScale=function(e,n,i){return void 0===i&&(i=new t),i.m11=e,i.m12=0,i.m21=0,i.m22=n,i.m31=0,i.m32=0,i},t.prototype.toEgretMatrix=function(){return new egret.Matrix(this.m11,this.m12,this.m21,this.m22,this.m31,this.m32)},t._identity=new t(1,0,0,1,0,0),t}(),Rectangle=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return __extends(e,t),Object.defineProperty(e.prototype,"max",{get:function(){return new Vector2(this.right,this.bottom)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"center",{get:function(){return new Vector2(this.x+this.width/2,this.y+this.height/2)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"location",{get:function(){return new Vector2(this.x,this.y)},set:function(t){this.x=t.x,this.y=t.y},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"size",{get:function(){return new Vector2(this.width,this.height)},set:function(t){this.width=t.x,this.height=t.y},enumerable:!0,configurable:!0}),e.prototype.intersects=function(t){return t.lefti&&(i=s.x),s.yr&&(r=s.y)}return this.fromMinMax(e,n,i,r)},e}(egret.Rectangle),Vector3=function(){return function(t,e,n){this.x=t,this.y=e,this.z=n}}(),ColliderTriggerHelper=function(){function t(t){this._activeTriggerIntersections=[],this._previousTriggerIntersections=[],this._tempTriggerList=[],this._entity=t}return t.prototype.update=function(){for(var t=this._entity.getComponents(Collider),e=0;e1)return!1;var h=(a.x*r.y-a.y*r.x)/s;return!(h<0||h>1)},t.lineToLineIntersection=function(t,e,n,i){var r=new Vector2(0,0),o=Vector2.subtract(e,t),s=Vector2.subtract(i,n),a=o.x*s.y-o.y*s.x;if(0==a)return r;var c=Vector2.subtract(n,t),h=(c.x*s.y-c.y*s.x)/a;if(h<0||h>1)return r;var u=(c.x*o.y-c.y*o.x)/a;return u<0||u>1?r:r=Vector2.add(t,new Vector2(h*o.x,h*o.y))},t.closestPointOnLine=function(t,e,n){var i=Vector2.subtract(e,t),r=Vector2.subtract(n,t),o=Vector2.dot(r,i)/Vector2.dot(i,i);return o=MathHelper.clamp(o,0,1),Vector2.add(t,new Vector2(i.x*o,i.y*o))},t.isCircleToCircle=function(t,e,n,i){return Vector2.distanceSquared(t,n)<(e+i)*(e+i)},t.isCircleToLine=function(t,e,n,i){return Vector2.distanceSquared(t,this.closestPointOnLine(n,i,t))=t&&r.y>=e&&r.x=t+n&&(o|=PointSectors.right),r.y=e+i&&(o|=PointSectors.bottom),o},t}(),Physics=function(){function t(){}return t.reset=function(){this._spatialHash=new SpatialHash(this.spatialHashCellSize)},t.clear=function(){this._spatialHash.clear()},t.overlapCircleAll=function(t,e,n,i){return void 0===i&&(i=-1),this._spatialHash.overlapCircle(t,e,n,i)},t.boxcastBroadphase=function(t,e){void 0===e&&(e=this.allLayers);var n=this._spatialHash.aabbBroadphase(t,null,e);return{colliders:n.tempHashSet,rect:n.bounds}},t.boxcastBroadphaseExcludingSelf=function(t,e,n){return void 0===n&&(n=this.allLayers),this._spatialHash.aabbBroadphase(e,t,n)},t.addCollider=function(e){t._spatialHash.register(e)},t.removeCollider=function(e){t._spatialHash.remove(e)},t.updateCollider=function(t){this._spatialHash.remove(t),this._spatialHash.register(t)},t.debugDraw=function(t){this._spatialHash.debugDraw(t,2)},t.spatialHashCellSize=100,t.allLayers=-1,t}(),Shape=function(){return function(){this.bounds=new Rectangle,this.position=Vector2.zero}}(),Polygon=function(t){function e(e,n){var i=t.call(this)||this;return i.isUnrotated=!0,i._areEdgeNormalsDirty=!0,i.center=new Vector2,i.setPoints(e),i.isBox=n,i}return __extends(e,t),Object.defineProperty(e.prototype,"edgeNormals",{get:function(){return this._areEdgeNormalsDirty&&this.buildEdgeNormals(),this._edgeNormals},enumerable:!0,configurable:!0}),e.prototype.buildEdgeNormals=function(){var t,e=this.isBox?2:this.points.length;null!=this._edgeNormals&&this._edgeNormals.length==e||(this._edgeNormals=new Array(e));for(var n=0;n=this.points.length?this.points[0]:this.points[n+1];var r=Vector2Ext.perpendicular(i,t);r=Vector2.normalize(r),this._edgeNormals[n]=r}},e.prototype.setPoints=function(t){this.points=t,this.recalculateCenterAndEdgeNormals(),this._originalPoints=[];for(var e=0;et.y!=this.points[i].y>t.y&&t.x<(this.points[i].x-this.points[n].x)*(t.y-this.points[n].y)/(this.points[i].y-this.points[n].y)+this.points[n].x&&(e=!e);return e},e.buildSymmertricalPolygon=function(t,e){for(var n=new Array(t),i=0;i0&&(r=!1),!r)return null;(g=Math.abs(g))i&&(i=r);return{min:n,max:i}},t.circleToPolygon=function(t,e){var n=new CollisionResult,i=Vector2.subtract(t.position,e.position),r=Polygon.getClosestPointOnPolygonToPoint(e.points,i),o=r.closestPoint,s=r.distanceSquared;n.normal=r.edgeNormal;var a,c=e.containsPoint(t.position);if(s>t.radius*t.radius&&!c)return null;if(c)a=Vector2.multiply(n.normal,new Vector2(Math.sqrt(s)-t.radius));else if(0==s)a=Vector2.multiply(n.normal,new Vector2(t.radius));else{var h=Math.sqrt(s);a=Vector2.multiply(new Vector2(-Vector2.subtract(i,o)),new Vector2((t.radius-s)/h))}return n.minimumTranslationVector=a,n.point=Vector2.add(o,e.position),n},t.circleToBox=function(t,e){var n=new CollisionResult,i=e.bounds.getClosestPointOnRectangleBorderToPoint(t.position).res;if(e.containsPoint(t.position)){n.point=i;var r=Vector2.add(i,Vector2.subtract(n.normal,new Vector2(t.radius)));return n.minimumTranslationVector=Vector2.subtract(t.position,r),n}var o=Vector2.distanceSquared(i,t.position);if(0==o)n.minimumTranslationVector=Vector2.multiply(n.normal,new Vector2(t.radius));else if(o<=t.radius*t.radius){n.normal=Vector2.subtract(t.position,i);var s=n.normal.length()-t.radius;return n.normal=Vector2Ext.normalize(n.normal),n.minimumTranslationVector=Vector2.multiply(new Vector2(s),n.normal),n}return null},t.pointToCircle=function(t,e){var n=new CollisionResult,i=Vector2.distanceSquared(t,e.position),r=1+e.radius;if(i0&&this.debugDrawCellDetails(n,i,r.length,t,e)}},t.prototype.debugDrawCellDetails=function(t,e,n,i,r){void 0===i&&(i=.5),void 0===r&&(r=1)},t}(),RaycastResultParser=function(){return function(){}}(),NumberDictionary=function(){function t(){this._store=new Map}return t.prototype.getKey=function(t,e){return Long.fromNumber(t).shiftLeft(32).or(this.intToUint(e)).toString()},t.prototype.intToUint=function(t){return t>=0?t:4294967296+t},t.prototype.add=function(t,e,n){this._store.set(this.getKey(t,e),n)},t.prototype.remove=function(t){this._store.forEach(function(e){e.contains(t)&&e.remove(t)})},t.prototype.tryGetValue=function(t,e){return this._store.get(this.getKey(t,e))},t.prototype.clear=function(){this._store.clear()},t}(),ArrayUtils=function(){function t(){}return t.bubbleSort=function(t){for(var e=!1,n=0;nn;i--)if(t[i]0&&t[r-1]>i;r--)t[r]=t[r-1];t[r]=i}},t.binarySearch=function(t,e){for(var n=0,i=t.length,r=n+i>>1;n=t[r]&&(n=r+1),r=n+i>>1;return t[n]==e?n:-1},t.findElementIndex=function(t,e){for(var n=t.length,i=0;it[e]&&(e=i);return e},t.getMinElementIndex=function(t){for(var e=0,n=t.length,i=1;i=0;--r)n.unshift(e[r]);return n},t.getDifferAry=function(t,e){t=this.getUniqueAry(t),e=this.getUniqueAry(e);for(var n=t.concat(e),i=new Object,r=[],o=n.length,s=0;s=0;e-=1)t.splice(e,1)},t.cloneList=function(t){return t?t.slice(0,t.length):null},t.equals=function(t,e){if(t==e)return!0;var n=t.length;if(n!=e.length)return!1;for(;n--;)if(t[n]!=e[n])return!1;return!0},t.insert=function(t,e,n){if(!t)return null;var i=t.length;if(e>i&&(e=i),e<0&&(e=0),e==i)t.push(n);else if(0==e)t.unshift(n);else{for(var r=i-1;r>=e;r-=1)t[r+1]=t[r];t[e]=n}return n},t}(),ContentManager=function(){function t(){this.loadedAssets=new Map}return t.prototype.loadRes=function(t,e){var n=this;return void 0===e&&(e=!0),new Promise(function(i,r){var o=n.loadedAssets.get(t);o?i(o):e?RES.getResAsync(t).then(function(e){n.loadedAssets.set(t,e),i(e)}).catch(function(e){console.error("资源加载错误:",t,e),r(e)}):RES.getResByUrl(t).then(function(e){n.loadedAssets.set(t,e),i(e)}).catch(function(e){console.error("资源加载错误:",t,e),r(e)})})},t.prototype.dispose=function(){this.loadedAssets.forEach(function(t){t.dispose()}),this.loadedAssets.clear()},t}(),DrawUtils=function(){function t(){}return t.drawLine=function(t,e,n,i,r){void 0===r&&(r=1),this.drawLineAngle(t,e,MathHelper.angleBetweenVectors(e,n),Vector2.distance(e,n),i,r)},t.drawLineAngle=function(t,e,n,i,r,o){void 0===o&&(o=1),t.graphics.beginFill(r),t.graphics.drawRect(e.x,e.y,1,1),t.graphics.endFill(),t.scaleX=i,t.scaleY=o,t.$anchorOffsetX=0,t.$anchorOffsetY=0,t.rotation=n},t.drawHollowRect=function(t,e,n,i){void 0===i&&(i=1),this.drawHollowRectR(t,e.x,e.y,e.width,e.height,n,i)},t.drawHollowRectR=function(t,e,n,i,r,o,s){void 0===s&&(s=1);var a=new Vector2(e,n).round(),c=new Vector2(e+i,n).round(),h=new Vector2(e+i,n+r).round(),u=new Vector2(e,n+r).round();this.drawLine(t,a,c,o,s),this.drawLine(t,c,h,o,s),this.drawLine(t,h,u,o,s),this.drawLine(t,u,a,o,s)},t.drawPixel=function(t,e,n,i){void 0===i&&(i=1);var r=new Rectangle(e.x,e.y,i,i);1!=i&&(r.x-=.5*i,r.y-=.5*i),t.graphics.beginFill(n),t.graphics.drawRect(r.x,r.y,r.width,r.height),t.graphics.endFill()},t}(),Emitter=function(){function t(){this._messageTable=new Map}return t.prototype.addObserver=function(t,e,n){var i=this._messageTable.get(t);i||(i=[],this._messageTable.set(t,i)),i.contains(e)&&console.warn("您试图添加相同的观察者两次"),i.push(new FuncPack(e,n))},t.prototype.removeObserver=function(t,e){var n=this._messageTable.get(t),i=n.findIndex(function(t){return t.func==e});-1!=i&&n.removeAt(i)},t.prototype.emit=function(t,e){var n=this._messageTable.get(t);if(n)for(var i=n.length-1;i>=0;i--)n[i].func.call(n[i].context,e)},t}(),FuncPack=function(){return function(t,e){this.func=t,this.context=e}}(),GlobalManager=function(){function t(){}return Object.defineProperty(t.prototype,"enabled",{get:function(){return this._enabled},set:function(t){this.setEnabled(t)},enumerable:!0,configurable:!0}),t.prototype.setEnabled=function(t){this._enabled!=t&&(this._enabled=t,this._enabled?this.onEnabled():this.onDisabled())},t.prototype.onEnabled=function(){},t.prototype.onDisabled=function(){},t.prototype.update=function(){},t.registerGlobalManager=function(t){this.globalManagers.push(t),t.enabled=!0},t.unregisterGlobalManager=function(t){this.globalManagers.remove(t),t.enabled=!1},t.getGlobalManager=function(t){for(var e=0;e0&&this.setpreviousTouchState(this._gameTouchs[0]),t},enumerable:!0,configurable:!0}),t.initialize=function(t){this._init||(this._init=!0,this._stage=t,this._stage.addEventListener(egret.TouchEvent.TOUCH_BEGIN,this.touchBegin,this),this._stage.addEventListener(egret.TouchEvent.TOUCH_MOVE,this.touchMove,this),this._stage.addEventListener(egret.TouchEvent.TOUCH_END,this.touchEnd,this),this._stage.addEventListener(egret.TouchEvent.TOUCH_CANCEL,this.touchEnd,this),this._stage.addEventListener(egret.TouchEvent.TOUCH_RELEASE_OUTSIDE,this.touchEnd,this),this.initTouchCache())},t.initTouchCache=function(){this._totalTouchCount=0,this._touchIndex=0,this._gameTouchs.length=0;for(var t=0;t0)for(var e=0;ethis._objectQueue.length;)this._objectQueue.shift()},t.clearCache=function(){this._objectQueue.length=0},t.obtain=function(){return this._objectQueue.length>0?this._objectQueue.shift():[]},t.free=function(t){this._objectQueue.unshift(t),t.length=0},t._objectQueue=[],t}(),THREAD_ID=Math.floor(1e3*Math.random())+"-"+Date.now(),setItem=egret.localStorage.setItem.bind(localStorage),getItem=egret.localStorage.getItem.bind(localStorage),removeItem=egret.localStorage.removeItem.bind(localStorage),nextTick=function(t){setTimeout(t,0)},LockUtils=function(){function t(t){this._keyX="mutex_key_"+t+"_X",this._keyY="mutex_key_"+t+"_Y"}return t.prototype.lock=function(){var t=this;return new Promise(function(e,n){var i=function(){setItem(t._keyX,THREAD_ID),null===!getItem(t._keyY)&&nextTick(i),setItem(t._keyY,THREAD_ID),getItem(t._keyX)!==THREAD_ID?setTimeout(function(){getItem(t._keyY)===THREAD_ID?(e(),removeItem(t._keyY)):nextTick(i)},10):(e(),removeItem(t._keyY))};i()})},t}(),Pair=function(){function t(t,e){this.first=t,this.second=e}return t.prototype.clear=function(){this.first=this.second=null},t.prototype.equals=function(t){return this.first==t.first&&this.second==t.second},t}(),RandomUtils=function(){function t(){}return t.randrange=function(t,e,n){if(void 0===n&&(n=1),0==n)throw new Error("step 不能为 0");var i=e-t;if(0==i)throw new Error("没有可用的范围("+t+","+e+")");i<0&&(i=t-e);var r=Math.floor((i+n-1)/n);return Math.floor(this.random()*r)*n+Math.min(t,e)},t.randint=function(t,e){return(t=Math.floor(t))>(e=Math.floor(e))?t++:e++,this.randrange(t,e)},t.randnum=function(t,e){return this.random()*(e-t)+t},t.shuffle=function(t){return t.sort(this._randomCompare),t},t._randomCompare=function(t,e){return this.random()>.5?1:-1},t.choice=function(t){if(!t.hasOwnProperty("length"))throw new Error("无法对此对象执行此操作");var e=Math.floor(this.random()*t.length);return t instanceof String?String(t).charAt(e):t[e]},t.sample=function(t,e){var n=t.length;if(e<=0||n=0;)s=Math.floor(this.random()*n);i.push(t[s]),r.push(s)}return i},t.random=function(){return Math.random()},t.boolean=function(t){return void 0===t&&(t=.5),this.random()3&&r<500;){r++;var s=!0,a=e[this._triPrev[o]],c=e[o],h=e[this._triNext[o]];if(Vector2Ext.isTriangleCCW(a,c,h)){var u=this._triNext[this._triNext[o]];do{if(t.testPointTriangle(e[u],a,c,h)){s=!1;break}u=this._triNext[u]}while(u!=this._triPrev[o])}else s=!1;s?(this.triangleIndices.push(this._triPrev[o]),this.triangleIndices.push(o),this.triangleIndices.push(this._triNext[o]),this._triNext[this._triPrev[o]]=this._triNext[o],this._triPrev[this._triNext[o]]=this._triPrev[o],i--,o=this._triPrev[o]):o=this._triNext[o]}this.triangleIndices.push(this._triPrev[o]),this.triangleIndices.push(o),this.triangleIndices.push(this._triNext[o]),n||this.triangleIndices.reverse()},t.prototype.initialize=function(t){this.triangleIndices.length=0,this._triNext.lengthMathHelper.Epsilon?t=Vector2.divide(t,new Vector2(e)):t.x=t.y=0,t},t.transformA=function(t,e,n,i,r,o){for(var s=0;sthis.safeArea.right&&(r.x=this.safeArea.right-r.width),r.topthis.safeArea.bottom&&(r.y=this.safeArea.bottom-r.height),r},t}();!function(t){t[t.none=0]="none",t[t.left=1]="left",t[t.right=2]="right",t[t.horizontalCenter=4]="horizontalCenter",t[t.top=8]="top",t[t.bottom=16]="bottom",t[t.verticalCenter=32]="verticalCenter",t[t.topLeft=9]="topLeft",t[t.topRight=10]="topRight",t[t.topCenter=12]="topCenter",t[t.bottomLeft=17]="bottomLeft",t[t.bottomRight=18]="bottomRight",t[t.bottomCenter=20]="bottomCenter",t[t.centerLeft=33]="centerLeft",t[t.centerRight=34]="centerRight",t[t.center=36]="center"}(Alignment||(Alignment={})),function(t){var e,n=function(){function t(t){void 0===t&&(t=i),this.getSystemTime=t,this._stopDuration=0,this._completeSlices=[]}return t.prototype.getState=function(){return void 0===this._startSystemTime?e.IDLE:void 0===this._stopSystemTime?e.RUNNING:e.STOPPED},t.prototype.isIdle=function(){return this.getState()===e.IDLE},t.prototype.isRunning=function(){return this.getState()===e.RUNNING},t.prototype.isStopped=function(){return this.getState()===e.STOPPED},t.prototype.slice=function(){return this.recordPendingSlice()},t.prototype.getCompletedSlices=function(){return Array.from(this._completeSlices)},t.prototype.getCompletedAndPendingSlices=function(){return this._completeSlices.concat([this.getPendingSlice()])},t.prototype.getPendingSlice=function(){return this.calculatePendingSlice()},t.prototype.getTime=function(){return this.caculateStopwatchTime()},t.prototype.calculatePendingSlice=function(t){return void 0===this._pendingSliceStartStopwatchTime?Object.freeze({startTime:0,endTime:0,duration:0}):(void 0===t&&(t=this.getTime()),Object.freeze({startTime:this._pendingSliceStartStopwatchTime,endTime:t,duration:t-this._pendingSliceStartStopwatchTime}))},t.prototype.caculateStopwatchTime=function(t){return void 0===this._startSystemTime?0:(void 0===t&&(t=this.getSystemTimeOfCurrentStopwatchTime()),t-this._startSystemTime-this._stopDuration)},t.prototype.getSystemTimeOfCurrentStopwatchTime=function(){return void 0===this._stopSystemTime?this.getSystemTime():this._stopSystemTime},t.prototype.reset=function(){this._startSystemTime=this._pendingSliceStartStopwatchTime=this._stopSystemTime=void 0,this._stopDuration=0,this._completeSlices=[]},t.prototype.start=function(t){if(void 0===t&&(t=!1),t&&this.reset(),void 0!==this._stopSystemTime){var e=(n=this.getSystemTime())-this._stopSystemTime;this._stopDuration+=e,this._stopSystemTime=void 0}else if(void 0===this._startSystemTime){var n=this.getSystemTime();this._startSystemTime=n,this._pendingSliceStartStopwatchTime=0}},t.prototype.stop=function(t){if(void 0===t&&(t=!1),void 0===this._startSystemTime)return 0;var e=this.getSystemTimeOfCurrentStopwatchTime();return t&&this.recordPendingSlice(this.caculateStopwatchTime(e)),this._stopSystemTime=e,this.getTime()},t.prototype.recordPendingSlice=function(t){if(void 0!==this._pendingSliceStartStopwatchTime){void 0===t&&(t=this.getTime());var e=this.calculatePendingSlice(t);return this._pendingSliceStartStopwatchTime=e.endTime,this._completeSlices.push(e),e}return this.calculatePendingSlice()},t}();t.Stopwatch=n,function(t){t.IDLE="IDLE",t.RUNNING="RUNNING",t.STOPPED="STOPPED"}(e||(e={})),t.setDefaultSystemTimeGetter=function(t){void 0===t&&(t=Date.now),i=t};var i=Date.now}(stopwatch||(stopwatch={}));var TimeRuler=function(){function t(){this._frameKey="frame",this._logKey="log",this.markers=[],this.stopwacth=new stopwatch.Stopwatch,this._markerNameToIdMap=new Map,this.showLog=!1,t.Instance=this,this._logs=new Array(2);for(var e=0;e=t.logSnapDuration&&(l.logs[r].snapMin=l.logs[r].min,l.logs[r].snapMax=l.logs[r].max,l.logs[r].snapAvg=l.logs[r].avg,l.logs[r].samples=0)):(l.logs[r].min=h,l.logs[r].max=h,l.logs[r].avg=h,l.logs[r].initialized=!0)}s.markCount=o.nestCount,s.nestCount=o.nestCount}e.stopwacth.reset(),e.stopwacth.start()}})},t.prototype.beginMark=function(e,n,i){var r=this;void 0===i&&(i=0),new LockUtils(this._frameKey).lock().then(function(){if(i<0||i>=t.maxBars)throw new Error("barIndex argument out of range");var o=r._curLog.bars[i];if(o.markCount>=t.maxSamples)throw new Error("exceeded sample count. either set larger number to timeruler.maxsaple or lower sample count");if(o.nestCount>=t.maxNestCall)throw new Error("exceeded nest count. either set larger number to timeruler.maxnestcall or lower nest calls");var s=r._markerNameToIdMap.get(e);s||(s=r.markers.length,r._markerNameToIdMap.set(e,s)),o.markerNests[o.nestCount++]=o.markCount,o.markers[o.markCount].markerId=s,o.markers[o.markCount].color=n,o.markers[o.markCount].beginTime=r.stopwacth.getTime(),o.markers[o.markCount].endTime=-1})},t.prototype.endMark=function(e,n){var i=this;void 0===n&&(n=0),new LockUtils(this._frameKey).lock().then(function(){if(n<0||n>=t.maxBars)throw new Error("barIndex argument out of range");var r=i._curLog.bars[n];if(r.nestCount<=0)throw new Error("call beginMark method before calling endMark method");var o=i._markerNameToIdMap.get(e);if(!o)throw new Error("Marker "+e+" is not registered. Make sure you specifed same name as you used for beginMark method");var s=r.markerNests[--r.nestCount];if(r.markers[s].markerId!=o)throw new Error("Incorrect call order of beginMark/endMark method. beginMark(A), beginMark(B), endMark(B), endMark(A) But you can't called it like beginMark(A), beginMark(B), endMark(A), endMark(B).");r.markers[s].endTime=i.stopwacth.getTime()})},t.prototype.getAverageTime=function(e,n){if(e<0||e>=t.maxBars)throw new Error("barIndex argument out of range");var i=0,r=this._markerNameToIdMap.get(n);return r&&(i=this.markers[r].logs[e].avg),i},t.prototype.resetLog=function(){var t=this;new LockUtils(this._logKey).lock().then(function(){var e=parseInt(egret.localStorage.getItem(t._logKey),10);e+=1,egret.localStorage.setItem(t._logKey,e.toString()),t.markers.forEach(function(t){for(var e=0;e0&&(i+=t.barHeight+2*t.barPadding,r=Math.max(r,e.markers[e.markCount-1].endTime))});var o=this.sampleFrames*(1/60*1e3);this._frameAdjust=r>o?Math.max(0,this._frameAdjust)+1:Math.min(0,this._frameAdjust)-1,Math.max(this._frameAdjust)>t.autoAdjustDelay&&(this.sampleFrames=Math.min(t.maxSampleFrames,this.sampleFrames),this.sampleFrames=Math.max(this.targetSampleFrames,r/(1/60*1e3)+1),this._frameAdjust=0);e.y,t.barHeight}},t.maxBars=0,t.maxSamples=256,t.maxNestCall=32,t.barHeight=8,t.maxSampleFrames=4,t.logSnapDuration=120,t.barPadding=2,t.autoAdjustDelay=30,t}(),FrameLog=function(){return function(){this.bars=new Array(TimeRuler.maxBars);for(var t=0;t(p: any, c?: T): T; +} declare class RenderableComponentList { private _components; readonly count: number; @@ -657,6 +660,29 @@ declare class RenderableComponentList { remove(component: IRenderable): void; updateList(): void; } +declare class StringUtils { + static matchChineseWord(str: string): string[]; + static lTrim(target: string): string; + static rTrim(target: string): string; + static trim(target: string): string; + static isWhiteSpace(str: string): boolean; + static replaceMatch(mainStr: string, targetStr: string, replaceStr: string, caseMark?: boolean): string; + private static specialSigns; + static htmlSpecialChars(str: string, reversion?: boolean): string; + static zfill(str: string, width?: number): string; + static reverse(str: string): string; + static cutOff(str: string, start: number, len: number, order?: boolean): string; + static strReplace(str: string, rStr: string[]): string; +} +declare class TextureUtils { + static sharedCanvas: HTMLCanvasElement; + static sharedContext: CanvasRenderingContext2D; + static convertImageToCanvas(texture: egret.Texture, rect?: egret.Rectangle): HTMLCanvasElement; + static toDataURL(type: string, texture: egret.Texture, rect?: egret.Rectangle, encoderOptions?: any): string; + static eliFoTevas(type: string, texture: egret.Texture, filePath: string, rect?: egret.Rectangle, encoderOptions?: any): void; + static getPixel32(texture: egret.Texture, x: number, y: number): number[]; + static getPixels(texture: egret.Texture, x: number, y: number, width?: number, height?: number): number[]; +} declare class Time { static unscaledDeltaTime: any; static deltaTime: number; @@ -668,18 +694,21 @@ declare class Time { static sceneChanged(): void; static checkEvery(interval: number): boolean; } -declare class GraphicsCapabilities { - supportsTextureFilterAnisotropic: boolean; - supportsNonPowerOfTwo: boolean; - supportsDepth24: boolean; - supportsPackedDepthStencil: boolean; - supportsDepthNonLinear: boolean; - supportsTextureMaxLevel: boolean; - supportsS3tc: boolean; - supportsDxt1: boolean; - supportsPvrtc: boolean; - supportsAtitc: boolean; - supportsFramebufferObjectARB: boolean; +declare class TimeUtils { + static monthId(d?: Date): number; + static dateId(t?: Date): number; + static weekId(d?: Date, first?: boolean): number; + static diffDay(a: Date, b: Date, fixOne?: boolean): number; + static getFirstDayOfWeek(d?: Date): Date; + static getFirstOfDay(d?: Date): Date; + static getNextFirstOfDay(d?: Date): Date; + static formatDate(date: Date): string; + static formatDateTime(date: Date): string; + static parseDate(s: string): Date; + static secondToTime(time?: number, partition?: string, showHour?: boolean): string; + static timeToMillisecond(time: string, partition?: string): string; +} +declare class GraphicsCapabilities extends egret.Capabilities { initialize(device: GraphicsDevice): void; private platformInitialize; } @@ -1038,7 +1067,20 @@ declare class NumberDictionary { tryGetValue(x: number, y: number): Collider[]; clear(): void; } -declare class fui { +declare class ArrayUtils { + static bubbleSort(ary: number[]): void; + static insertionSort(ary: number[]): void; + static binarySearch(ary: number[], value: number): number; + static findElementIndex(ary: any[], num: any): any; + static getMaxElementIndex(ary: number[]): number; + static getMinElementIndex(ary: number[]): number; + static getUniqueAry(ary: number[]): number[]; + static getDifferAry(aryA: number[], aryB: number[]): number[]; + static swap(array: any[], index1: number, index2: number): void; + static clearList(ary: any[]): void; + static cloneList(ary: any[]): any[]; + static equals(ary1: number[], ary2: number[]): Boolean; + static insert(ary: any[], index: number, value: any): any; } declare class ContentManager { protected loadedAssets: Map; @@ -1107,6 +1149,90 @@ declare class Input { private static setpreviousTouchState; static scaledPosition(position: Vector2): Vector2; } +declare class KeyboardUtils { + static TYPE_KEY_DOWN: number; + static TYPE_KEY_UP: number; + private static keyDownDict; + private static keyUpDict; + static A: string; + static B: string; + static C: string; + static D: string; + static E: string; + static F: string; + static G: string; + static H: string; + static I: string; + static J: string; + static K: string; + static L: string; + static M: string; + static N: string; + static O: string; + static P: string; + static Q: string; + static R: string; + static S: string; + static T: string; + static U: string; + static V: string; + static W: string; + static X: string; + static Y: string; + static Z: string; + static ESC: string; + static F1: string; + static F2: string; + static F3: string; + static F4: string; + static F5: string; + static F6: string; + static F7: string; + static F8: string; + static F9: string; + static F10: string; + static F11: string; + static F12: string; + static NUM_1: string; + static NUM_2: string; + static NUM_3: string; + static NUM_4: string; + static NUM_5: string; + static NUM_6: string; + static NUM_7: string; + static NUM_8: string; + static NUM_9: string; + static NUM_0: string; + static TAB: string; + static CTRL: string; + static ALT: string; + static SHIFT: string; + static CAPS_LOCK: string; + static ENTER: string; + static SPACE: string; + static BACK_SPACE: string; + static INSERT: string; + static DELETE: string; + static HOME: string; + static END: string; + static PAGE_UP: string; + static PAGE_DOWN: string; + static LEFT: string; + static RIGHT: string; + static UP: string; + static DOWN: string; + static PAUSE_BREAK: string; + static NUM_LOCK: string; + static SCROLL_LOCK: string; + static WINDOWS: string; + static init(): void; + private static onKeyDonwHander; + private static onKeyUpHander; + static registerKey(key: string, fun: Function, thisObj: any, type?: number, ...args: any[]): void; + static unregisterKey(key: string, type?: number): void; + private static keyCodeToString; + static destroy(): void; +} declare class ListPool { private static readonly _objectQueue; static warmCache(cacheCount: number): void; @@ -1133,6 +1259,17 @@ declare class Pair { clear(): void; equals(other: Pair): boolean; } +declare class RandomUtils { + static randrange(start: number, stop: number, step?: number): number; + static randint(a: number, b: number): number; + static randnum(a: number, b: number): number; + static shuffle(array: any[]): any[]; + private static _randomCompare; + static choice(sequence: any): any; + static sample(sequence: any[], num: number): any[]; + static random(): number; + static boolean(chance?: number): boolean; +} declare class RectangleExt { static union(first: Rectangle, point: Vector2): Rectangle; } diff --git a/source/bin/framework.js b/source/bin/framework.js index 9bd9a05c..e64b16f3 100644 --- a/source/bin/framework.js +++ b/source/bin/framework.js @@ -300,7 +300,6 @@ var AStarPathfinder = (function () { return "break"; } graph.getNeighbors(current.data).forEach(function (next) { - console.log(next); var newCost = costSoFar.get(current.data) + graph.cost(current.data, next); if (!_this.hasKey(costSoFar, next) || newCost < costSoFar.get(next)) { costSoFar.set(next, newCost); @@ -3040,6 +3039,25 @@ var Matcher = (function () { }; return Matcher; }()); +var ObjectUtils = (function () { + function ObjectUtils() { + } + ObjectUtils.clone = function (p, c) { + if (c === void 0) { c = null; } + var c = c || {}; + for (var i in p) { + if (typeof p[i] === 'object') { + c[i] = p[i] instanceof Array ? [] : {}; + this.clone(p[i], c[i]); + } + else { + c[i] = p[i]; + } + } + return c; + }; + return ObjectUtils; +}()); var RenderableComponentList = (function () { function RenderableComponentList() { this._components = []; @@ -3068,6 +3086,276 @@ var RenderableComponentList = (function () { }; return RenderableComponentList; }()); +var StringUtils = (function () { + function StringUtils() { + } + StringUtils.matchChineseWord = function (str) { + var patternA = /[\u4E00-\u9FA5]+/gim; + return str.match(patternA); + }; + StringUtils.lTrim = function (target) { + var startIndex = 0; + while (this.isWhiteSpace(target.charAt(startIndex))) { + startIndex++; + } + return target.slice(startIndex, target.length); + }; + StringUtils.rTrim = function (target) { + var endIndex = target.length - 1; + while (this.isWhiteSpace(target.charAt(endIndex))) { + endIndex--; + } + return target.slice(0, endIndex + 1); + }; + StringUtils.trim = function (target) { + if (target == null) { + return null; + } + return this.rTrim(this.lTrim(target)); + }; + StringUtils.isWhiteSpace = function (str) { + if (str == " " || str == "\t" || str == "\r" || str == "\n") + return true; + return false; + }; + StringUtils.replaceMatch = function (mainStr, targetStr, replaceStr, caseMark) { + if (caseMark === void 0) { caseMark = false; } + var len = mainStr.length; + var tempStr = ""; + var isMatch = false; + var tempTarget = caseMark == true ? targetStr.toLowerCase() : targetStr; + for (var i = 0; i < len; i++) { + isMatch = false; + if (mainStr.charAt(i) == tempTarget.charAt(0)) { + if (mainStr.substr(i, tempTarget.length) == tempTarget) { + isMatch = true; + } + } + if (isMatch) { + tempStr += replaceStr; + i = i + tempTarget.length - 1; + } + else { + tempStr += mainStr.charAt(i); + } + } + return tempStr; + }; + StringUtils.htmlSpecialChars = function (str, reversion) { + if (reversion === void 0) { reversion = false; } + var len = this.specialSigns.length; + for (var i = 0; i < len; i += 2) { + var from = void 0; + var to = void 0; + from = this.specialSigns[i]; + to = this.specialSigns[i + 1]; + if (reversion) { + var temp = from; + from = to; + to = temp; + } + str = this.replaceMatch(str, from, to); + } + return str; + }; + StringUtils.zfill = function (str, width) { + if (width === void 0) { width = 2; } + if (!str) { + return str; + } + width = Math.floor(width); + var slen = str.length; + if (slen >= width) { + return str; + } + var negative = false; + if (str.substr(0, 1) == '-') { + negative = true; + str = str.substr(1); + } + var len = width - slen; + for (var i = 0; i < len; i++) { + str = '0' + str; + } + if (negative) { + str = '-' + str; + } + return str; + }; + StringUtils.reverse = function (str) { + if (str.length > 1) + return this.reverse(str.substring(1)) + str.substring(0, 1); + else + return str; + }; + StringUtils.cutOff = function (str, start, len, order) { + if (order === void 0) { order = true; } + start = Math.floor(start); + len = Math.floor(len); + var length = str.length; + if (start > length) + start = length; + var s = start; + var e = start + len; + var newStr; + if (order) { + newStr = str.substring(0, s) + str.substr(e, length); + } + else { + s = length - 1 - start - len; + e = s + len; + newStr = str.substring(0, s + 1) + str.substr(e + 1, length); + } + return newStr; + }; + StringUtils.strReplace = function (str, rStr) { + var i = 0, len = rStr.length; + for (; i < len; i++) { + if (rStr[i] == null || rStr[i] == "") { + rStr[i] = "无"; + } + str = str.replace("{" + i + "}", rStr[i]); + } + return str; + }; + StringUtils.specialSigns = [ + '&', '&', + '<', '<', + '>', '>', + '"', '"', + "'", ''', + '®', '®', + '©', '©', + '™', '™', + ]; + return StringUtils; +}()); +var TextureUtils = (function () { + function TextureUtils() { + } + TextureUtils.convertImageToCanvas = function (texture, rect) { + if (!this.sharedCanvas) { + this.sharedCanvas = egret.sys.createCanvas(); + this.sharedContext = this.sharedCanvas.getContext("2d"); + } + var w = texture.$getTextureWidth(); + var h = texture.$getTextureHeight(); + if (!rect) { + rect = egret.$TempRectangle; + rect.x = 0; + rect.y = 0; + rect.width = w; + rect.height = h; + } + rect.x = Math.min(rect.x, w - 1); + rect.y = Math.min(rect.y, h - 1); + rect.width = Math.min(rect.width, w - rect.x); + rect.height = Math.min(rect.height, h - rect.y); + var iWidth = Math.floor(rect.width); + var iHeight = Math.floor(rect.height); + var surface = this.sharedCanvas; + surface["style"]["width"] = iWidth + "px"; + surface["style"]["height"] = iHeight + "px"; + this.sharedCanvas.width = iWidth; + this.sharedCanvas.height = iHeight; + if (egret.Capabilities.renderMode == "webgl") { + var renderTexture = void 0; + if (!texture.$renderBuffer) { + if (egret.sys.systemRenderer["renderClear"]) { + egret.sys.systemRenderer["renderClear"](); + } + renderTexture = new egret.RenderTexture(); + renderTexture.drawToTexture(new egret.Bitmap(texture)); + } + else { + renderTexture = texture; + } + var pixels = renderTexture.$renderBuffer.getPixels(rect.x, rect.y, iWidth, iHeight); + var x = 0; + var y = 0; + for (var i = 0; i < pixels.length; i += 4) { + this.sharedContext.fillStyle = + 'rgba(' + pixels[i] + + ',' + pixels[i + 1] + + ',' + pixels[i + 2] + + ',' + (pixels[i + 3] / 255) + ')'; + this.sharedContext.fillRect(x, y, 1, 1); + x++; + if (x == iWidth) { + x = 0; + y++; + } + } + if (!texture.$renderBuffer) { + renderTexture.dispose(); + } + return surface; + } + else { + var bitmapData = texture; + var offsetX = Math.round(bitmapData.$offsetX); + var offsetY = Math.round(bitmapData.$offsetY); + var bitmapWidth = bitmapData.$bitmapWidth; + var bitmapHeight = bitmapData.$bitmapHeight; + var $TextureScaleFactor = SceneManager.stage.textureScaleFactor; + this.sharedContext.drawImage(bitmapData.$bitmapData.source, bitmapData.$bitmapX + rect.x / $TextureScaleFactor, bitmapData.$bitmapY + rect.y / $TextureScaleFactor, bitmapWidth * rect.width / w, bitmapHeight * rect.height / h, offsetX, offsetY, rect.width, rect.height); + return surface; + } + }; + TextureUtils.toDataURL = function (type, texture, rect, encoderOptions) { + try { + var surface = this.convertImageToCanvas(texture, rect); + var result = surface.toDataURL(type, encoderOptions); + return result; + } + catch (e) { + egret.$error(1033); + } + return null; + }; + TextureUtils.eliFoTevas = function (type, texture, filePath, rect, encoderOptions) { + var surface = this.convertImageToCanvas(texture, rect); + var result = surface.toTempFilePathSync({ + fileType: type.indexOf("png") >= 0 ? "png" : "jpg" + }); + wx.getFileSystemManager().saveFile({ + tempFilePath: result, + filePath: wx.env.USER_DATA_PATH + "/" + filePath, + success: function (res) { + } + }); + return result; + }; + TextureUtils.getPixel32 = function (texture, x, y) { + egret.$warn(1041, "getPixel32", "getPixels"); + return texture.getPixels(x, y); + }; + TextureUtils.getPixels = function (texture, x, y, width, height) { + if (width === void 0) { width = 1; } + if (height === void 0) { height = 1; } + if (egret.Capabilities.renderMode == "webgl") { + var renderTexture = void 0; + if (!texture.$renderBuffer) { + renderTexture = new egret.RenderTexture(); + renderTexture.drawToTexture(new egret.Bitmap(texture)); + } + else { + renderTexture = texture; + } + var pixels = renderTexture.$renderBuffer.getPixels(x, y, width, height); + return pixels; + } + try { + var surface = this.convertImageToCanvas(texture); + var result = this.sharedContext.getImageData(x, y, width, height).data; + return result; + } + catch (e) { + egret.$error(1039); + } + }; + return TextureUtils; +}()); var Time = (function () { function Time() { } @@ -3091,29 +3379,189 @@ var Time = (function () { Time._lastTime = 0; return Time; }()); -var GraphicsCapabilities = (function () { +var TimeUtils = (function () { + function TimeUtils() { + } + TimeUtils.monthId = function (d) { + if (d === void 0) { d = null; } + d = d ? d : new Date(); + var y = d.getFullYear(); + var m = d.getMonth() + 1; + var g = m < 10 ? "0" : ""; + return parseInt(y + g + m); + }; + TimeUtils.dateId = function (t) { + if (t === void 0) { t = null; } + t = t ? t : new Date(); + var m = t.getMonth() + 1; + var a = m < 10 ? "0" : ""; + var d = t.getDate(); + var b = d < 10 ? "0" : ""; + return parseInt(t.getFullYear() + a + m + b + d); + }; + TimeUtils.weekId = function (d, first) { + if (d === void 0) { d = null; } + if (first === void 0) { first = true; } + d = d ? d : new Date(); + var c = new Date(); + c.setTime(d.getTime()); + c.setDate(1); + c.setMonth(0); + var year = c.getFullYear(); + var firstDay = c.getDay(); + if (firstDay == 0) { + firstDay = 7; + } + var max = false; + if (firstDay <= 4) { + max = firstDay > 1; + c.setDate(c.getDate() - (firstDay - 1)); + } + else { + c.setDate(c.getDate() + 7 - firstDay + 1); + } + var num = this.diffDay(d, c, false); + if (num < 0) { + c.setDate(1); + c.setMonth(0); + c.setDate(c.getDate() - 1); + return this.weekId(c, false); + } + var week = num / 7; + var weekIdx = Math.floor(week) + 1; + if (weekIdx == 53) { + c.setTime(d.getTime()); + c.setDate(c.getDate() - 1); + var endDay = c.getDay(); + if (endDay == 0) { + endDay = 7; + } + if (first && (!max || endDay < 4)) { + c.setFullYear(c.getFullYear() + 1); + c.setDate(1); + c.setMonth(0); + return this.weekId(c, false); + } + } + var g = weekIdx > 9 ? "" : "0"; + var s = year + "00" + g + weekIdx; + return parseInt(s); + }; + TimeUtils.diffDay = function (a, b, fixOne) { + if (fixOne === void 0) { fixOne = false; } + var x = (a.getTime() - b.getTime()) / 86400000; + return fixOne ? Math.ceil(x) : Math.floor(x); + }; + TimeUtils.getFirstDayOfWeek = function (d) { + d = d ? d : new Date(); + var day = d.getDay() || 7; + return new Date(d.getFullYear(), d.getMonth(), d.getDate() + 1 - day, 0, 0, 0, 0); + }; + TimeUtils.getFirstOfDay = function (d) { + d = d ? d : new Date(); + d.setHours(0, 0, 0, 0); + return d; + }; + TimeUtils.getNextFirstOfDay = function (d) { + return new Date(this.getFirstOfDay(d).getTime() + 86400000); + }; + TimeUtils.formatDate = function (date) { + var y = date.getFullYear(); + var m = date.getMonth() + 1; + m = m < 10 ? '0' + m : m; + var d = date.getDate(); + d = d < 10 ? ('0' + d) : d; + return y + '-' + m + '-' + d; + }; + TimeUtils.formatDateTime = function (date) { + var y = date.getFullYear(); + var m = date.getMonth() + 1; + m = m < 10 ? ('0' + m) : m; + var d = date.getDate(); + d = d < 10 ? ('0' + d) : d; + var h = date.getHours(); + var i = date.getMinutes(); + i = i < 10 ? ('0' + i) : i; + var s = date.getSeconds(); + s = s < 10 ? ('0' + s) : s; + return y + '-' + m + '-' + d + ' ' + h + ':' + i + ":" + s; + }; + TimeUtils.parseDate = function (s) { + var t = Date.parse(s); + if (!isNaN(t)) { + return new Date(Date.parse(s.replace(/-/g, "/"))); + } + else { + return new Date(); + } + }; + TimeUtils.secondToTime = function (time, partition, showHour) { + if (time === void 0) { time = 0; } + if (partition === void 0) { partition = ":"; } + if (showHour === void 0) { showHour = true; } + var hours = Math.floor(time / 3600); + var minutes = Math.floor(time % 3600 / 60); + var seconds = Math.floor(time % 3600 % 60); + var h = hours.toString(); + var m = minutes.toString(); + var s = seconds.toString(); + if (hours < 10) + h = "0" + h; + if (minutes < 10) + m = "0" + m; + if (seconds < 10) + s = "0" + s; + var timeStr; + if (showHour) + timeStr = h + partition + m + partition + s; + else + timeStr = m + partition + s; + return timeStr; + }; + TimeUtils.timeToMillisecond = function (time, partition) { + if (partition === void 0) { partition = ":"; } + var _ary = time.split(partition); + var timeNum = 0; + var len = _ary.length; + for (var i = 0; i < len; i++) { + var n = _ary[i]; + timeNum += n * Math.pow(60, (len - 1 - i)); + } + timeNum *= 1000; + return timeNum.toString(); + }; + return TimeUtils; +}()); +var GraphicsCapabilities = (function (_super) { + __extends(GraphicsCapabilities, _super); function GraphicsCapabilities() { + return _super !== null && _super.apply(this, arguments) || this; } GraphicsCapabilities.prototype.initialize = function (device) { this.platformInitialize(device); }; GraphicsCapabilities.prototype.platformInitialize = function (device) { - var gl = new egret.sys.RenderBuffer().context.getInstance(); - this.supportsNonPowerOfTwo = false; - this.supportsTextureFilterAnisotropic = gl.getExtension("EXT_texture_filter_anisotropic") != null; - this.supportsDepth24 = true; - this.supportsPackedDepthStencil = true; - this.supportsDepthNonLinear = false; - this.supportsTextureMaxLevel = true; - this.supportsS3tc = gl.getExtension("WEBGL_compressed_texture_s3tc") != null || - gl.getExtension("WEBGL_compressed_texture_s3tc_srgb") != null; - this.supportsDxt1 = this.supportsS3tc; - this.supportsPvrtc = false; - this.supportsAtitc = gl.getExtension("WEBGL_compressed_texture_astc") != null; - this.supportsFramebufferObjectARB = false; + var capabilities = this; + capabilities["isMobile"] = true; + var systemInfo = wx.getSystemInfoSync(); + var systemStr = systemInfo.system.toLowerCase(); + if (systemStr.indexOf("ios") > -1) { + capabilities["os"] = "iOS"; + } + else if (systemStr.indexOf("android") > -1) { + capabilities["os"] = "Android"; + } + var language = systemInfo.language; + if (language.indexOf('zh') > -1) { + language = "zh-CN"; + } + else { + language = "en-US"; + } + capabilities["language"] = language; }; return GraphicsCapabilities; -}()); +}(egret.Capabilities)); var GraphicsDevice = (function () { function GraphicsDevice() { this.graphicsCapabilities = new GraphicsCapabilities(); @@ -4876,6 +5324,170 @@ var NumberDictionary = (function () { }; return NumberDictionary; }()); +var ArrayUtils = (function () { + function ArrayUtils() { + } + ArrayUtils.bubbleSort = function (ary) { + var isExchange = false; + for (var i = 0; i < ary.length; i++) { + isExchange = false; + for (var j = ary.length - 1; j > i; j--) { + if (ary[j] < ary[j - 1]) { + var temp = ary[j]; + ary[j] = ary[j - 1]; + ary[j - 1] = temp; + isExchange = true; + } + } + if (!isExchange) + break; + } + }; + ArrayUtils.insertionSort = function (ary) { + var len = ary.length; + for (var i = 1; i < len; i++) { + var val = ary[i]; + for (var j = i; j > 0 && ary[j - 1] > val; j--) { + ary[j] = ary[j - 1]; + } + ary[j] = val; + } + }; + ArrayUtils.binarySearch = function (ary, value) { + var startIndex = 0; + var endIndex = ary.length; + var sub = (startIndex + endIndex) >> 1; + while (startIndex < endIndex) { + if (value <= ary[sub]) + endIndex = sub; + else if (value >= ary[sub]) + startIndex = sub + 1; + sub = (startIndex + endIndex) >> 1; + } + if (ary[startIndex] == value) + return startIndex; + return -1; + }; + ArrayUtils.findElementIndex = function (ary, num) { + var len = ary.length; + for (var i = 0; i < len; ++i) { + if (ary[i] == num) + return i; + } + return null; + }; + ArrayUtils.getMaxElementIndex = function (ary) { + var matchIndex = 0; + var len = ary.length; + for (var j = 1; j < len; j++) { + if (ary[j] > ary[matchIndex]) + matchIndex = j; + } + return matchIndex; + }; + ArrayUtils.getMinElementIndex = function (ary) { + var matchIndex = 0; + var len = ary.length; + for (var j = 1; j < len; j++) { + if (ary[j] < ary[matchIndex]) + matchIndex = j; + } + return matchIndex; + }; + ArrayUtils.getUniqueAry = function (ary) { + var uAry = []; + var newAry = []; + var count = ary.length; + for (var i = 0; i < count; ++i) { + var value = ary[i]; + if (uAry.indexOf(value) == -1) + uAry.push(value); + } + count = uAry.length; + for (var i = count - 1; i >= 0; --i) { + newAry.unshift(uAry[i]); + } + return newAry; + }; + ArrayUtils.getDifferAry = function (aryA, aryB) { + aryA = this.getUniqueAry(aryA); + aryB = this.getUniqueAry(aryB); + var ary = aryA.concat(aryB); + var uObj = new Object(); + var newAry = []; + var count = ary.length; + for (var j = 0; j < count; ++j) { + if (!uObj[ary[j]]) { + uObj[ary[j]] = new Object(); + uObj[ary[j]].count = 0; + uObj[ary[j]].key = ary[j]; + uObj[ary[j]].count++; + } + else { + if (uObj[ary[j]] instanceof Object) { + uObj[ary[j]].count++; + } + } + } + for (var i in uObj) { + if (uObj[i].count != 2) { + newAry.unshift(uObj[i].key); + } + } + return newAry; + }; + ArrayUtils.swap = function (array, index1, index2) { + var temp = array[index1]; + array[index1] = array[index2]; + array[index2] = temp; + }; + ArrayUtils.clearList = function (ary) { + if (!ary) + return; + var length = ary.length; + for (var i = length - 1; i >= 0; i -= 1) { + ary.splice(i, 1); + } + }; + ArrayUtils.cloneList = function (ary) { + if (!ary) + return null; + return ary.slice(0, ary.length); + }; + ArrayUtils.equals = function (ary1, ary2) { + if (ary1 == ary2) + return true; + var length = ary1.length; + if (length != ary2.length) + return false; + while (length--) { + if (ary1[length] != ary2[length]) + return false; + } + return true; + }; + ArrayUtils.insert = function (ary, index, value) { + if (!ary) + return null; + var length = ary.length; + if (index > length) + index = length; + if (index < 0) + index = 0; + if (index == length) + ary.push(value); + else if (index == 0) + ary.unshift(value); + else { + for (var i = length - 1; i >= index; i -= 1) { + ary[i + 1] = ary[i]; + } + ary[index] = value; + } + return value; + }; + return ArrayUtils; +}()); var ContentManager = (function () { function ContentManager() { this.loadedAssets = new Map(); @@ -5199,6 +5811,206 @@ var Input = (function () { Input._totalTouchCount = 0; return Input; }()); +var KeyboardUtils = (function () { + function KeyboardUtils() { + } + KeyboardUtils.init = function () { + this.keyDownDict = {}; + this.keyUpDict = {}; + document.addEventListener("keydown", this.onKeyDonwHander); + document.addEventListener("keyup", this.onKeyUpHander); + }; + KeyboardUtils.onKeyDonwHander = function (event) { + if (!this.keyDownDict) + return; + var key = this.keyCodeToString(event.keyCode); + var o = this.keyDownDict[key]; + if (o) { + var fun = o["fun"]; + var thisObj = o["thisObj"]; + var args = o["args"]; + fun.apply(thisObj, args); + } + }; + KeyboardUtils.onKeyUpHander = function (event) { + if (!this.keyUpDict) + return; + var key = this.keyCodeToString(event.keyCode); + var o = this.keyUpDict[key]; + if (o) { + var fun = o["fun"]; + var thisObj = o["thisObj"]; + var args = o["args"]; + fun.apply(thisObj, args); + } + }; + KeyboardUtils.registerKey = function (key, fun, thisObj, type) { + if (type === void 0) { type = 0; } + var args = []; + for (var _i = 4; _i < arguments.length; _i++) { + args[_i - 4] = arguments[_i]; + } + var keyDict = type ? this.keyUpDict : this.keyDownDict; + keyDict[key] = { "fun": fun, args: args, "thisObj": thisObj }; + }; + KeyboardUtils.unregisterKey = function (key, type) { + if (type === void 0) { type = 0; } + var keyDict = type ? this.keyUpDict : this.keyDownDict; + delete keyDict[key]; + }; + KeyboardUtils.keyCodeToString = function (keyCode) { + switch (keyCode) { + case 8: + return this.BACK_SPACE; + case 9: + return this.TAB; + case 13: + return this.ENTER; + case 16: + return this.SHIFT; + case 17: + return this.CTRL; + case 19: + return this.PAUSE_BREAK; + case 20: + return this.CAPS_LOCK; + case 27: + return this.ESC; + case 32: + return this.SPACE; + case 33: + return this.PAGE_UP; + case 34: + return this.PAGE_DOWN; + case 35: + return this.END; + case 36: + return this.HOME; + case 37: + return this.LEFT; + case 38: + return this.UP; + case 39: + return this.RIGHT; + case 40: + return this.DOWN; + case 45: + return this.INSERT; + case 46: + return this.DELETE; + case 91: + return this.WINDOWS; + case 112: + return this.F1; + case 113: + return this.F2; + case 114: + return this.F3; + case 115: + return this.F4; + case 116: + return this.F5; + case 117: + return this.F6; + case 118: + return this.F7; + case 119: + return this.F8; + case 120: + return this.F9; + case 122: + return this.F11; + case 123: + return this.F12; + case 144: + return this.NUM_LOCK; + case 145: + return this.SCROLL_LOCK; + default: + return String.fromCharCode(keyCode); + } + }; + KeyboardUtils.destroy = function () { + this.keyDownDict = null; + this.keyUpDict = null; + document.removeEventListener("keydown", this.onKeyDonwHander); + document.removeEventListener("keyup", this.onKeyUpHander); + }; + KeyboardUtils.TYPE_KEY_DOWN = 0; + KeyboardUtils.TYPE_KEY_UP = 1; + KeyboardUtils.A = "A"; + KeyboardUtils.B = "B"; + KeyboardUtils.C = "C"; + KeyboardUtils.D = "D"; + KeyboardUtils.E = "E"; + KeyboardUtils.F = "F"; + KeyboardUtils.G = "G"; + KeyboardUtils.H = "H"; + KeyboardUtils.I = "I"; + KeyboardUtils.J = "J"; + KeyboardUtils.K = "K"; + KeyboardUtils.L = "L"; + KeyboardUtils.M = "M"; + KeyboardUtils.N = "N"; + KeyboardUtils.O = "O"; + KeyboardUtils.P = "P"; + KeyboardUtils.Q = "Q"; + KeyboardUtils.R = "R"; + KeyboardUtils.S = "S"; + KeyboardUtils.T = "T"; + KeyboardUtils.U = "U"; + KeyboardUtils.V = "V"; + KeyboardUtils.W = "W"; + KeyboardUtils.X = "X"; + KeyboardUtils.Y = "Y"; + KeyboardUtils.Z = "Z"; + KeyboardUtils.ESC = "Esc"; + KeyboardUtils.F1 = "F1"; + KeyboardUtils.F2 = "F2"; + KeyboardUtils.F3 = "F3"; + KeyboardUtils.F4 = "F4"; + KeyboardUtils.F5 = "F5"; + KeyboardUtils.F6 = "F6"; + KeyboardUtils.F7 = "F7"; + KeyboardUtils.F8 = "F8"; + KeyboardUtils.F9 = "F9"; + KeyboardUtils.F10 = "F10"; + KeyboardUtils.F11 = "F11"; + KeyboardUtils.F12 = "F12"; + KeyboardUtils.NUM_1 = "1"; + KeyboardUtils.NUM_2 = "2"; + KeyboardUtils.NUM_3 = "3"; + KeyboardUtils.NUM_4 = "4"; + KeyboardUtils.NUM_5 = "5"; + KeyboardUtils.NUM_6 = "6"; + KeyboardUtils.NUM_7 = "7"; + KeyboardUtils.NUM_8 = "8"; + KeyboardUtils.NUM_9 = "9"; + KeyboardUtils.NUM_0 = "0"; + KeyboardUtils.TAB = "Tab"; + KeyboardUtils.CTRL = "Ctrl"; + KeyboardUtils.ALT = "Alt"; + KeyboardUtils.SHIFT = "Shift"; + KeyboardUtils.CAPS_LOCK = "Caps Lock"; + KeyboardUtils.ENTER = "Enter"; + KeyboardUtils.SPACE = "Space"; + KeyboardUtils.BACK_SPACE = "Back Space"; + KeyboardUtils.INSERT = "Insert"; + KeyboardUtils.DELETE = "Page Down"; + KeyboardUtils.HOME = "Home"; + KeyboardUtils.END = "Page Down"; + KeyboardUtils.PAGE_UP = "Page Up"; + KeyboardUtils.PAGE_DOWN = "Page Down"; + KeyboardUtils.LEFT = "Left"; + KeyboardUtils.RIGHT = "Right"; + KeyboardUtils.UP = "Up"; + KeyboardUtils.DOWN = "Down"; + KeyboardUtils.PAUSE_BREAK = "Pause Break"; + KeyboardUtils.NUM_LOCK = "Num Lock"; + KeyboardUtils.SCROLL_LOCK = "Scroll Lock"; + KeyboardUtils.WINDOWS = "Windows"; + return KeyboardUtils; +}()); var ListPool = (function () { function ListPool() { } @@ -5283,6 +6095,73 @@ var Pair = (function () { }; return Pair; }()); +var RandomUtils = (function () { + function RandomUtils() { + } + RandomUtils.randrange = function (start, stop, step) { + if (step === void 0) { step = 1; } + if (step == 0) + throw new Error('step 不能为 0'); + var width = stop - start; + if (width == 0) + throw new Error('没有可用的范围(' + start + ',' + stop + ')'); + if (width < 0) + width = start - stop; + var n = Math.floor((width + step - 1) / step); + return Math.floor(this.random() * n) * step + Math.min(start, stop); + }; + RandomUtils.randint = function (a, b) { + a = Math.floor(a); + b = Math.floor(b); + if (a > b) + a++; + else + b++; + return this.randrange(a, b); + }; + RandomUtils.randnum = function (a, b) { + return this.random() * (b - a) + a; + }; + RandomUtils.shuffle = function (array) { + array.sort(this._randomCompare); + return array; + }; + RandomUtils._randomCompare = function (a, b) { + return (this.random() > .5) ? 1 : -1; + }; + RandomUtils.choice = function (sequence) { + if (!sequence.hasOwnProperty("length")) + throw new Error('无法对此对象执行此操作'); + var index = Math.floor(this.random() * sequence.length); + if (sequence instanceof String) + return String(sequence).charAt(index); + else + return sequence[index]; + }; + RandomUtils.sample = function (sequence, num) { + var len = sequence.length; + if (num <= 0 || len < num) + throw new Error("采样数量不够"); + var selected = []; + var indices = []; + for (var i = 0; i < num; i++) { + var index = Math.floor(this.random() * len); + while (indices.indexOf(index) >= 0) + index = Math.floor(this.random() * len); + selected.push(sequence[index]); + indices.push(index); + } + return selected; + }; + RandomUtils.random = function () { + return Math.random(); + }; + RandomUtils.boolean = function (chance) { + if (chance === void 0) { chance = .5; } + return (this.random() < chance) ? true : false; + }; + return RandomUtils; +}()); var RectangleExt = (function () { function RectangleExt() { } diff --git a/source/bin/framework.min.js b/source/bin/framework.min.js index 4dd9e548..f10d4cd7 100644 --- a/source/bin/framework.min.js +++ b/source/bin/framework.min.js @@ -1 +1 @@ -window.framework={},window.__extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])};return function(e,n){function i(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}();var __awaiter=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(o,r){function s(t){try{c(i.next(t))}catch(t){r(t)}}function a(t){try{c(i.throw(t))}catch(t){r(t)}}function c(t){t.done?o(t.value):new n(function(e){e(t.value)}).then(s,a)}c((i=i.apply(t,e||[])).next())})},__generator=this&&this.__generator||function(t,e){var n,i,o,r,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return r={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(r[Symbol.iterator]=function(){return this}),r;function a(r){return function(a){return function(r){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,i&&(o=2&r[0]?i.return:r[0]?i.throw||((o=i.return)&&o.call(i),0):i.next)&&!(o=o.call(i,r[1])).done)return o;switch(i=0,o&&(r=[2&r[0],o.value]),r[0]){case 0:case 1:o=r;break;case 4:return s.label++,{value:r[1],done:!1};case 5:s.label++,i=r[1],r=[0];continue;case 7:r=s.ops.pop(),s.trys.pop();continue;default:if(!(o=(o=s.trys).length>0&&o[o.length-1])&&(6===r[0]||2===r[0])){s=0;continue}if(3===r[0]&&(!o||r[1]>o[0]&&r[1]-1}(this,t)},Array.prototype.firstOrDefault=function(t){return function(t,e){var n=t.findIndex(e);return-1==n?null:t[n]}(this,t)},Array.prototype.find=function(t){return function(t,e){return t.firstOrDefault(e)}(this,t)},Array.prototype.where=function(t){return function(t,e){if("function"==typeof t.reduce)return t.reduce(function(n,i,o){return e.call(arguments[2],i,o,t)&&n.push(i),n},[]);for(var n=[],i=0,o=t.length;i=0&&t.splice(n,1)}while(n>=0)}(this,t)},Array.prototype.remove=function(t){return function(t,e){var n=t.findIndex(function(t){return t===e});return n>=0&&(t.splice(n,1),!0)}(this,t)},Array.prototype.removeAt=function(t){return function(t,e){t.splice(e,1)}(this,t)},Array.prototype.removeRange=function(t,e){return function(t,e,n){t.splice(e,n)}(this,t,e)},Array.prototype.select=function(t){return function(t,e){if("function"==typeof t.reduce)return t.reduce(function(n,i,o){return n.push(e.call(arguments[2],i,o,t)),n},[]);for(var n=[],i=0,o=t.length;ir?1:-1}),t}(this,t,e)},Array.prototype.orderByDescending=function(t,e){return function(t,e,n){return t.sort(function(t,i){var o=e(t),r=e(i);return n?-n(o,r):o0;){if("break"===c())break}return o?this.recontructPath(r,e,n):null},t.hasKey=function(t,e){for(var n,i=t.keys();!(n=i.next()).done;)if(JSON.stringify(n.value)==JSON.stringify(e))return!0;return!1},t.getKey=function(t,e){for(var n,i,o=t.keys(),r=t.values();n=o.next(),i=r.next(),!n.done;)if(JSON.stringify(n.value)==JSON.stringify(e))return i.value;return null},t.recontructPath=function(t,e,n){var i=[],o=n;for(i.push(n);o!=e;)o=this.getKey(t,o),i.push(o);return i.reverse(),i},t}(),AStarNode=function(t){function e(e){var n=t.call(this)||this;return n.data=e,n}return __extends(e,t),e}(PriorityQueueNode),AstarGridGraph=function(){function t(t,e){this.dirs=[new Vector2(1,0),new Vector2(0,-1),new Vector2(-1,0),new Vector2(0,1)],this.walls=[],this.weightedNodes=[],this.defaultWeight=1,this.weightedNodeWeight=5,this._neighbors=new Array(4),this._width=t,this._height=e}return t.prototype.isNodeInBounds=function(t){return 0<=t.x&&t.x=this._nodes.length?(console.error("node.QueueIndex has been corrupted. Did you change it manually? Or add this node to another queue?"),!1):this._nodes[t.queueIndex]==t:(console.error("node cannot be null"),!1)},t.prototype.enqueue=function(t,e){t.priority=e,this._numNodes++,this._nodes[this._numNodes]=t,t.queueIndex=this._numNodes,t.insertionIndex=this._numNodesEverEnqueued++,this.cascadeUp(this._nodes[this._numNodes])},t.prototype.dequeue=function(){var t=this._nodes[1];return this.remove(t),t},t.prototype.remove=function(t){if(t.queueIndex==this._numNodes)return this._nodes[this._numNodes]=null,void this._numNodes--;var e=this._nodes[this._numNodes];this.swap(t,e),delete this._nodes[this._numNodes],this._numNodes--,this.onNodeUpdated(e)},t.prototype.isValidQueue=function(){for(var t=1;t0&&this.hasHigherPriority(t,n)?this.cascadeUp(t):this.cascadeDown(t)},t.prototype.cascadeDown=function(t){for(var e,n=t.queueIndex;;){e=t;var i=2*n;if(i>this._numNodes){t.queueIndex=n,this._nodes[n]=t;break}var o=this._nodes[i];this.hasHigherPriority(o,e)&&(e=o);var r=i+1;if(r<=this._numNodes){var s=this._nodes[r];this.hasHigherPriority(s,e)&&(e=s)}if(e==t){t.queueIndex=n,this._nodes[n]=t;break}this._nodes[n]=e;var a=e.queueIndex;e.queueIndex=n,n=a}},t.prototype.cascadeUp=function(t){for(var e=Math.floor(t.queueIndex/2);e>=1;){var n=this._nodes[e];if(this.hasHigherPriority(n,t))break;this.swap(t,n),e=Math.floor(t.queueIndex/2)}},t.prototype.swap=function(t,e){this._nodes[t.queueIndex]=e,this._nodes[e.queueIndex]=t;var n=t.queueIndex;t.queueIndex=e.queueIndex,e.queueIndex=n},t.prototype.hasHigherPriority=function(t,e){return t.priority0;){if("break"===a())break}return o?AStarPathfinder.recontructPath(s,e,n):null},t.hasKey=function(t,e){for(var n,i=t.keys();!(n=i.next()).done;)if(JSON.stringify(n.value)==JSON.stringify(e))return!0;return!1},t}(),UnweightedGraph=function(){function t(){this.edges=new Map}return t.prototype.addEdgesForNode=function(t,e){return this.edges.set(t,e),this},t.prototype.getNeighbors=function(t){return this.edges.get(t)},t}(),Vector2=function(){function t(t,e){this.x=0,this.y=0,this.x=t||0,this.y=e||this.x}return Object.defineProperty(t,"zero",{get:function(){return t.zeroVector2},enumerable:!0,configurable:!0}),Object.defineProperty(t,"one",{get:function(){return t.unitVector2},enumerable:!0,configurable:!0}),Object.defineProperty(t,"unitX",{get:function(){return t.unitXVector},enumerable:!0,configurable:!0}),Object.defineProperty(t,"unitY",{get:function(){return t.unitYVector},enumerable:!0,configurable:!0}),t.add=function(e,n){var i=new t(0,0);return i.x=e.x+n.x,i.y=e.y+n.y,i},t.divide=function(e,n){var i=new t(0,0);return i.x=e.x/n.x,i.y=e.y/n.y,i},t.multiply=function(e,n){var i=new t(0,0);return i.x=e.x*n.x,i.y=e.y*n.y,i},t.subtract=function(e,n){var i=new t(0,0);return i.x=e.x-n.x,i.y=e.y-n.y,i},t.prototype.normalize=function(){var t=1/Math.sqrt(this.x*this.x+this.y*this.y);this.x*=t,this.y*=t},t.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},t.prototype.round=function(){return new t(Math.round(this.x),Math.round(this.y))},t.normalize=function(t){var e=1/Math.sqrt(t.x*t.x+t.y*t.y);return t.x*=e,t.y*=e,t},t.dot=function(t,e){return t.x*e.x+t.y*e.y},t.distanceSquared=function(t,e){var n=t.x-e.x,i=t.y-e.y;return n*n+i*i},t.clamp=function(e,n,i){return new t(MathHelper.clamp(e.x,n.x,i.x),MathHelper.clamp(e.y,n.y,i.y))},t.lerp=function(e,n,i){return new t(MathHelper.lerp(e.x,n.x,i),MathHelper.lerp(e.y,n.y,i))},t.transform=function(e,n){return new t(e.x*n.m11+e.y*n.m21,e.x*n.m12+e.y*n.m22)},t.distance=function(t,e){var n=t.x-e.x,i=t.y-e.y;return Math.sqrt(n*n+i*i)},t.negate=function(e){var n=new t;return n.x=-e.x,n.y=-e.y,n},t.unitYVector=new t(0,1),t.unitXVector=new t(1,0),t.unitVector2=new t(1,1),t.zeroVector2=new t(0,0),t}(),UnweightedGridGraph=function(){function t(e,n,i){void 0===i&&(i=!1),this.walls=[],this._neighbors=new Array(4),this._width=e,this._hegiht=n,this._dirs=i?t.COMPASS_DIRS:t.CARDINAL_DIRS}return t.prototype.isNodeInBounds=function(t){return 0<=t.x&&t.x0;){if("break"===c())break}return o?this.recontructPath(r,e,n):null},t.hasKey=function(t,e){for(var n,i=t.keys();!(n=i.next()).done;)if(JSON.stringify(n.value)==JSON.stringify(e))return!0;return!1},t.getKey=function(t,e){for(var n,i,o=t.keys(),r=t.values();n=o.next(),i=r.next(),!n.done;)if(JSON.stringify(n.value)==JSON.stringify(e))return i.value;return null},t.recontructPath=function(t,e,n){var i=[],o=n;for(i.push(n);o!=e;)o=this.getKey(t,o),i.push(o);return i.reverse(),i},t}(),Debug=function(){function t(){}return t.drawHollowRect=function(t,e,n){void 0===n&&(n=0),this._debugDrawItems.push(new DebugDrawItem(t,e,n))},t.render=function(){if(this._debugDrawItems.length>0){var t=new egret.Shape;SceneManager.scene&&SceneManager.scene.addChild(t);for(var e=this._debugDrawItems.length-1;e>=0;e--){this._debugDrawItems[e].draw(t)&&this._debugDrawItems.removeAt(e)}}},t._debugDrawItems=[],t}(),DebugDefaults=function(){function t(){}return t.verletParticle=14431326,t.verletConstraintEdge=4406838,t}();!function(t){t[t.line=0]="line",t[t.hollowRectangle=1]="hollowRectangle",t[t.pixel=2]="pixel",t[t.text=3]="text"}(DebugDrawType||(DebugDrawType={}));var CoreEvents,DebugDrawItem=function(){function t(t,e,n){this.rectangle=t,this.color=e,this.duration=n,this.drawType=DebugDrawType.hollowRectangle}return t.prototype.draw=function(t){switch(this.drawType){case DebugDrawType.line:DrawUtils.drawLine(t,this.start,this.end,this.color);break;case DebugDrawType.hollowRectangle:DrawUtils.drawHollowRect(t,this.rectangle,this.color);break;case DebugDrawType.pixel:DrawUtils.drawPixel(t,new Vector2(this.x,this.y),this.color,this.size);break;case DebugDrawType.text:}return this.duration-=Time.deltaTime,this.duration<0},t}(),Component=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e._enabled=!0,e.updateInterval=1,e._updateOrder=0,e}return __extends(e,t),Object.defineProperty(e.prototype,"enabled",{get:function(){return this.entity?this.entity.enabled&&this._enabled:this._enabled},set:function(t){this.setEnabled(t)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"localPosition",{get:function(){return new Vector2(this.entity.x+this.x,this.entity.y+this.y)},enumerable:!0,configurable:!0}),e.prototype.setEnabled=function(t){return this._enabled!=t&&(this._enabled=t,this._enabled?this.onEnabled():this.onDisabled()),this},Object.defineProperty(e.prototype,"updateOrder",{get:function(){return this._updateOrder},set:function(t){this.setUpdateOrder(t)},enumerable:!0,configurable:!0}),e.prototype.setUpdateOrder=function(t){return this._updateOrder!=t&&(this._updateOrder=t),this},e.prototype.initialize=function(){},e.prototype.onAddedToEntity=function(){},e.prototype.onRemovedFromEntity=function(){},e.prototype.onEnabled=function(){},e.prototype.onDisabled=function(){},e.prototype.debugRender=function(){},e.prototype.update=function(){},e.prototype.onEntityTransformChanged=function(t){},e.prototype.registerComponent=function(){this.entity.componentBits.set(ComponentTypeManager.getIndexFor(this),!1),this.entity.scene.entityProcessors.onComponentAdded(this.entity)},e.prototype.deregisterComponent=function(){this.entity.componentBits.set(ComponentTypeManager.getIndexFor(this)),this.entity.scene.entityProcessors.onComponentRemoved(this.entity)},e}(egret.DisplayObjectContainer);!function(t){t[t.SceneChanged=0]="SceneChanged"}(CoreEvents||(CoreEvents={}));var TransformComponent,Entity=function(t){function e(n){var i=t.call(this)||this;return i._updateOrder=0,i._enabled=!0,i._tag=0,i.name=n,i.components=new ComponentList(i),i.id=e._idGenerator++,i.componentBits=new BitSet,i.addEventListener(egret.Event.ADDED_TO_STAGE,i.onAddToStage,i),i}return __extends(e,t),Object.defineProperty(e.prototype,"isDestoryed",{get:function(){return this._isDestoryed},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"position",{get:function(){return new Vector2(this.x,this.y)},set:function(t){this.$setX(t.x),this.$setY(t.y),this.onEntityTransformChanged(TransformComponent.position)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"scale",{get:function(){return new Vector2(this.scaleX,this.scaleY)},set:function(t){this.$setScaleX(t.x),this.$setScaleY(t.y),this.onEntityTransformChanged(TransformComponent.scale)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"rotation",{get:function(){return this.$getRotation()},set:function(t){this.$setRotation(t),this.onEntityTransformChanged(TransformComponent.rotation)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"enabled",{get:function(){return this._enabled},set:function(t){this.setEnabled(t)},enumerable:!0,configurable:!0}),e.prototype.setEnabled=function(t){return this._enabled!=t&&(this._enabled=t),this},Object.defineProperty(e.prototype,"tag",{get:function(){return this._tag},set:function(t){this.setTag(t)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"stage",{get:function(){return this.scene?this.scene.stage:null},enumerable:!0,configurable:!0}),e.prototype.onAddToStage=function(){this.onEntityTransformChanged(TransformComponent.position)},Object.defineProperty(e.prototype,"updateOrder",{get:function(){return this._updateOrder},set:function(t){this.setUpdateOrder(t)},enumerable:!0,configurable:!0}),e.prototype.roundPosition=function(){this.position=Vector2Ext.round(this.position)},e.prototype.setUpdateOrder=function(t){if(this._updateOrder!=t)return this._updateOrder=t,this.scene,this},e.prototype.setTag=function(t){return this._tag!=t&&(this.scene&&this.scene.entities.removeFromTagList(this),this._tag=t,this.scene&&this.scene.entities.addToTagList(this)),this},e.prototype.attachToScene=function(t){this.scene=t,t.entities.add(this),this.components.registerAllComponents();for(var e=0;e=0;t--){this.getChildAt(t).entity.destroy()}},e}(egret.DisplayObjectContainer);!function(t){t[t.rotation=0]="rotation",t[t.scale=1]="scale",t[t.position=2]="position"}(TransformComponent||(TransformComponent={}));var CameraStyle,Scene=function(t){function e(){var e=t.call(this)||this;return e.enablePostProcessing=!0,e._renderers=[],e._postProcessors=[],e.entityProcessors=new EntityProcessorList,e.renderableComponents=new RenderableComponentList,e.entities=new EntityList(e),e.content=new ContentManager,e.width=SceneManager.stage.stageWidth,e.height=SceneManager.stage.stageHeight,e.addEventListener(egret.Event.ACTIVATE,e.onActive,e),e.addEventListener(egret.Event.DEACTIVATE,e.onDeactive,e),e}return __extends(e,t),e.prototype.createEntity=function(t){var e=new Entity(t);return e.position=new Vector2(0,0),this.addEntity(e)},e.prototype.addEntity=function(t){this.entities.add(t),t.scene=this,this.addChild(t);for(var e=0;e=0;e--)GlobalManager.globalManagers[e].enabled&&GlobalManager.globalManagers[e].update();t.sceneTransition&&(!t.sceneTransition||t.sceneTransition.loadsNewScene&&!t.sceneTransition.isNewSceneLoaded)||t._scene.update(),t._nextScene&&(t._scene.end(),t._scene=t._nextScene,t._nextScene=null,t._instnace.onSceneChanged(),t._scene.begin())}t.render()},t.render=function(){this.sceneTransition?(this.sceneTransition.preRender(),this._scene&&!this.sceneTransition.hasPreviousSceneRender?(this._scene.render(),this._scene.postRender(),this.sceneTransition.onBeginTransition()):this.sceneTransition&&(this._scene&&this.sceneTransition.isNewSceneLoaded&&(this._scene.render(),this._scene.postRender()),this.sceneTransition.render())):this._scene&&(this._scene.render(),Debug.render(),this._scene.postRender())},t.startSceneTransition=function(t){if(!this.sceneTransition)return this.sceneTransition=t,t;console.warn("在前一个场景完成之前,不能开始一个新的场景转换。")},t.registerActiveSceneChanged=function(t,e){this.activeSceneChanged&&this.activeSceneChanged(t,e)},t.prototype.onSceneChanged=function(){t.emitter.emit(CoreEvents.SceneChanged),Time.sceneChanged()},t}(),Camera=function(t){function e(){var e=t.call(this)||this;return e._origin=Vector2.zero,e._minimumZoom=.3,e._maximumZoom=3,e._position=Vector2.zero,e.followLerp=.1,e.deadzone=new Rectangle,e.focusOffset=new Vector2,e.mapLockEnabled=!1,e.mapSize=new Vector2,e._worldSpaceDeadZone=new Rectangle,e._desiredPositionDelta=new Vector2,e.cameraStyle=CameraStyle.lockOn,e.width=SceneManager.stage.stageWidth,e.height=SceneManager.stage.stageHeight,e.setZoom(0),e}return __extends(e,t),Object.defineProperty(e.prototype,"zoom",{get:function(){return 0==this._zoom?1:this._zoom<1?MathHelper.map(this._zoom,this._minimumZoom,1,-1,0):MathHelper.map(this._zoom,1,this._maximumZoom,0,1)},set:function(t){this.setZoom(t)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"minimumZoom",{get:function(){return this._minimumZoom},set:function(t){this.setMinimumZoom(t)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"maximumZoom",{get:function(){return this._maximumZoom},set:function(t){this.setMaximumZoom(t)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"origin",{get:function(){return this._origin},set:function(t){this._origin!=t&&(this._origin=t)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"position",{get:function(){return this._position},set:function(t){this._position=t},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"x",{get:function(){return this._position.x},set:function(t){this._position.x=t},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"y",{get:function(){return this._position.y},set:function(t){this._position.y=t},enumerable:!0,configurable:!0}),e.prototype.onSceneSizeChanged=function(t,e){var n=this._origin;this.origin=new Vector2(t/2,e/2),this.entity.position=Vector2.add(this.entity.position,Vector2.subtract(this._origin,n))},e.prototype.setMinimumZoom=function(t){return this._zoomt&&(this._zoom=t),this._maximumZoom=t,this},e.prototype.setZoom=function(t){var e=MathHelper.clamp(t,-1,1);return this._zoom=0==e?1:e<0?MathHelper.map(e,-1,0,this._minimumZoom,1):MathHelper.map(e,0,1,1,this._maximumZoom),SceneManager.scene.scaleX=this._zoom,SceneManager.scene.scaleY=this._zoom,this},e.prototype.setRotation=function(t){return SceneManager.scene.rotation=t,this},e.prototype.setPosition=function(t){return this.entity.position=t,this},e.prototype.follow=function(t,e){void 0===e&&(e=CameraStyle.cameraWindow),this.targetEntity=t,this.cameraStyle=e;var n=new Rectangle(0,0,SceneManager.stage.stageWidth,SceneManager.stage.stageHeight);switch(this.cameraStyle){case CameraStyle.cameraWindow:var i=n.width/6,o=n.height/3;this.deadzone=new Rectangle((n.width-i)/2,(n.height-o)/2,i,o);break;case CameraStyle.lockOn:this.deadzone=new Rectangle(n.width/2,n.height/2,10,10)}},e.prototype.update=function(){var t=new Rectangle(0,0,SceneManager.stage.stageWidth,SceneManager.stage.stageHeight),e=Vector2.multiply(new Vector2(t.width,t.height),new Vector2(.5));this._worldSpaceDeadZone.x=this.position.x-e.x+this.deadzone.x+this.focusOffset.x,this._worldSpaceDeadZone.y=this.position.y-e.y+this.deadzone.y+this.focusOffset.y,this._worldSpaceDeadZone.width=this.deadzone.width,this._worldSpaceDeadZone.height=this.deadzone.height,this.targetEntity&&this.updateFollow(),this.position=Vector2.lerp(this.position,Vector2.add(this.position,this._desiredPositionDelta),this.followLerp),this.entity.roundPosition(),this.mapLockEnabled&&(this.position=this.clampToMapSize(this.position),this.entity.roundPosition())},e.prototype.clampToMapSize=function(t){var e=new Rectangle(0,0,SceneManager.stage.stageWidth,SceneManager.stage.stageHeight),n=Vector2.multiply(new Vector2(e.width,e.height),new Vector2(.5)),i=new Vector2(this.mapSize.x-n.x,this.mapSize.y-n.y);return Vector2.clamp(t,n,i)},e.prototype.updateFollow=function(){if(this._desiredPositionDelta.x=this._desiredPositionDelta.y=0,this.cameraStyle==CameraStyle.lockOn){var t=this.targetEntity.position.x,e=this.targetEntity.position.y;this._worldSpaceDeadZone.x>t?this._desiredPositionDelta.x=t-this._worldSpaceDeadZone.x:this._worldSpaceDeadZone.xe&&(this._desiredPositionDelta.y=e-this._worldSpaceDeadZone.y)}else{if(!this._targetCollider&&(this._targetCollider=this.targetEntity.getComponent(Collider),!this._targetCollider))return;var n=this.targetEntity.getComponent(Collider).bounds;this._worldSpaceDeadZone.containsRect(n)||(this._worldSpaceDeadZone.left>n.left?this._desiredPositionDelta.x=n.left-this._worldSpaceDeadZone.left:this._worldSpaceDeadZone.rightn.top&&(this._desiredPositionDelta.y=n.top-this._worldSpaceDeadZone.top))}},e}(Component);!function(t){t[t.lockOn=0]="lockOn",t[t.cameraWindow=1]="cameraWindow"}(CameraStyle||(CameraStyle={}));var LoopMode,State,ComponentPool=function(){function t(t){this._type=t,this._cache=[]}return t.prototype.obtain=function(){try{return this._cache.length>0?this._cache.shift():new this._type}catch(t){throw new Error(this._type+t)}},t.prototype.free=function(t){t.reset(),this._cache.push(t)},t}(),PooledComponent=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return __extends(e,t),e}(Component),RenderableComponent=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e._areBoundsDirty=!0,e._bounds=new Rectangle,e._localOffset=Vector2.zero,e.color=0,e}return __extends(e,t),Object.defineProperty(e.prototype,"width",{get:function(){return this.getWidth()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"height",{get:function(){return this.getHeight()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"isVisible",{get:function(){return this._isVisible},set:function(t){this._isVisible=t,this._isVisible?this.onBecameVisible():this.onBecameInvisible()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"bounds",{get:function(){return new Rectangle(this.getBounds().x,this.getBounds().y,this.getBounds().width,this.getBounds().height)},enumerable:!0,configurable:!0}),e.prototype.getWidth=function(){return this.bounds.width},e.prototype.getHeight=function(){return this.bounds.height},e.prototype.onBecameVisible=function(){},e.prototype.onBecameInvisible=function(){},e.prototype.isVisibleFromCamera=function(t){return this.isVisible=t.getBounds().intersects(this.getBounds()),this.isVisible},e}(PooledComponent),Mesh=function(t){function e(){var e=t.call(this)||this;return e._mesh=new egret.Mesh,e}return __extends(e,t),e.prototype.setTexture=function(t){return this._mesh.texture=t,this},e.prototype.onAddedToEntity=function(){this.addChild(this._mesh)},e.prototype.onRemovedFromEntity=function(){this.removeChild(this._mesh)},e.prototype.render=function(t){this.x=this.entity.position.x-t.position.x+t.origin.x,this.y=this.entity.position.y-t.position.y+t.origin.y},e.prototype.reset=function(){},e}(RenderableComponent),SpriteRenderer=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return __extends(e,t),Object.defineProperty(e.prototype,"sprite",{get:function(){return this._sprite},set:function(t){this.setSprite(t)},enumerable:!0,configurable:!0}),e.prototype.setSprite=function(t){return this.removeChildren(),this._sprite=t,this._sprite&&(this.anchorOffsetX=this._sprite.origin.x/this._sprite.sourceRect.width,this.anchorOffsetY=this._sprite.origin.y/this._sprite.sourceRect.height),this.bitmap=new egret.Bitmap(t.texture2D),this.addChild(this.bitmap),this},e.prototype.setColor=function(t){var e=[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0];e[0]=Math.floor(t/256/256)/255,e[6]=Math.floor(t/256%256)/255,e[12]=t%256/255;var n=new egret.ColorMatrixFilter(e);return this.filters=[n],this},e.prototype.isVisibleFromCamera=function(t){return this.isVisible=new Rectangle(0,0,this.stage.stageWidth,this.stage.stageHeight).intersects(this.bounds),this.visible=this.isVisible,this.isVisible},e.prototype.render=function(t){this.x=-t.position.x+t.origin.x,this.y=-t.position.y+t.origin.y},e.prototype.onRemovedFromEntity=function(){this.parent&&this.parent.removeChild(this)},e.prototype.reset=function(){},e}(RenderableComponent),TiledSpriteRenderer=function(t){function e(e){var n=t.call(this)||this;return n.leftTexture=new egret.Bitmap,n.rightTexture=new egret.Bitmap,n.leftTexture.texture=e.texture2D,n.rightTexture.texture=e.texture2D,n.setSprite(e),n.sourceRect=e.sourceRect,n}return __extends(e,t),Object.defineProperty(e.prototype,"scrollX",{get:function(){return this.sourceRect.x},set:function(t){this.sourceRect.x=t},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"scrollY",{get:function(){return this.sourceRect.y},set:function(t){this.sourceRect.y=t},enumerable:!0,configurable:!0}),e.prototype.render=function(e){if(this.sprite){t.prototype.render.call(this,e);var n=new egret.RenderTexture,i=new egret.DisplayObjectContainer;i.removeChildren(),i.addChild(this.leftTexture),i.addChild(this.rightTexture),this.leftTexture.x=this.sourceRect.x,this.rightTexture.x=this.sourceRect.x-this.sourceRect.width,this.leftTexture.y=this.sourceRect.y,this.rightTexture.y=this.sourceRect.y,i.cacheAsBitmap=!0,n.drawToTexture(i,new egret.Rectangle(0,0,this.sourceRect.width,this.sourceRect.height)),this.bitmap.texture=n}},e}(SpriteRenderer),ScrollingSpriteRenderer=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e.scrollSpeedX=15,e.scroolSpeedY=0,e._scrollX=0,e._scrollY=0,e}return __extends(e,t),e.prototype.update=function(){this._scrollX+=this.scrollSpeedX*Time.deltaTime,this._scrollY+=this.scroolSpeedY*Time.deltaTime,this.sourceRect.x=this._scrollX,this.sourceRect.y=this._scrollY},e.prototype.render=function(e){if(this.sprite){t.prototype.render.call(this,e);var n=new egret.RenderTexture,i=new egret.DisplayObjectContainer;i.removeChildren(),i.addChild(this.leftTexture),i.addChild(this.rightTexture),this.leftTexture.x=this.sourceRect.x,this.rightTexture.x=this.sourceRect.x-this.sourceRect.width,this.leftTexture.y=this.sourceRect.y,this.rightTexture.y=this.sourceRect.y,i.cacheAsBitmap=!0,n.drawToTexture(i,new egret.Rectangle(0,0,this.sourceRect.width,this.sourceRect.height)),this.bitmap.texture=n}},e}(TiledSpriteRenderer),Sprite=function(){return function(t,e,n){void 0===e&&(e=new Rectangle(0,0,t.textureWidth,t.textureHeight)),void 0===n&&(n=e.getHalfSize()),this.uvs=new Rectangle,this.texture2D=t,this.sourceRect=e,this.center=new Vector2(.5*e.width,.5*e.height),this.origin=n;var i=1/t.textureWidth,o=1/t.textureHeight;this.uvs.x=e.x*i,this.uvs.y=e.y*o,this.uvs.width=e.width*i,this.uvs.height=e.height*o}}(),SpriteAnimation=function(){return function(t,e){this.sprites=t,this.frameRate=e}}(),SpriteAnimator=function(t){function e(e){var n=t.call(this)||this;return n.speed=1,n.animationState=State.none,n._animations=new Map,n._elapsedTime=0,e&&n.setSprite(e),n}return __extends(e,t),Object.defineProperty(e.prototype,"isRunning",{get:function(){return this.animationState==State.running},enumerable:!0,configurable:!0}),e.prototype.addAnimation=function(t,e){return!this.sprite&&e.sprites.length>0&&this.setSprite(e.sprites[0]),this._animations[t]=e,this},e.prototype.play=function(t,e){void 0===e&&(e=null),this.currentAnimation=this._animations[t],this.currentAnimationName=t,this.currentFrame=0,this.animationState=State.running,this.sprite=this.currentAnimation.sprites[0],this._elapsedTime=0,this._loopMode=e||LoopMode.loop},e.prototype.isAnimationActive=function(t){return this.currentAnimation&&this.currentAnimationName==t},e.prototype.pause=function(){this.animationState=State.paused},e.prototype.unPause=function(){this.animationState=State.running},e.prototype.stop=function(){this.currentAnimation=null,this.currentAnimationName=null,this.currentFrame=0,this.animationState=State.none},e.prototype.update=function(){if(this.animationState==State.running&&this.currentAnimation){var t=this.currentAnimation,e=1/(t.frameRate*this.speed),n=e*t.sprites.length;this._elapsedTime+=Time.deltaTime;var i=Math.abs(this._elapsedTime);if(this._loopMode==LoopMode.once&&i>n||this._loopMode==LoopMode.pingPongOnce&&i>2*n)return this.animationState=State.completed,this._elapsedTime=0,this.currentFrame=0,void(this.sprite=t.sprites[this.currentFrame]);var o=Math.floor(i/e),r=t.sprites.length;if(r>2&&(this._loopMode==LoopMode.pingPong||this._loopMode==LoopMode.pingPongOnce)){var s=r-1;this.currentFrame=s-Math.abs(s-o%(2*s))}else this.currentFrame=o%r;this.sprite=t.sprites[this.currentFrame]}},e}(SpriteRenderer);!function(t){t[t.loop=0]="loop",t[t.once=1]="once",t[t.clampForever=2]="clampForever",t[t.pingPong=3]="pingPong",t[t.pingPongOnce=4]="pingPongOnce"}(LoopMode||(LoopMode={})),function(t){t[t.none=0]="none",t[t.running=1]="running",t[t.paused=2]="paused",t[t.completed=3]="completed"}(State||(State={}));var PointSectors,Mover=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return __extends(e,t),e.prototype.onAddedToEntity=function(){this._triggerHelper=new ColliderTriggerHelper(this.entity)},e.prototype.calculateMovement=function(t){var e=new CollisionResult;if(!this.entity.getComponent(Collider)||!this._triggerHelper)return null;for(var n=this.entity.getComponents(Collider),i=0;i>6;0!=(e&t.LONG_MASK)&&n++,this._bits=new Array(n)}return t.prototype.and=function(t){for(var e,n=Math.min(this._bits.length,t._bits.length),i=0;i=0;)this._bits[e]&=~t._bits[e]},t.prototype.cardinality=function(){for(var t=0,e=this._bits.length-1;e>=0;e--){var n=this._bits[e];if(0!=n)if(-1!=n){var i=((n=((n=(n>>1&0x5555555555555400)+(0x5555555555555400&n))>>2&0x3333333333333400)+(0x3333333333333400&n))>>32)+n;t+=((i=((i=(i>>4&252645135)+(252645135&i))>>8&16711935)+(16711935&i))>>16&65535)+(65535&i)}else t+=64}return t},t.prototype.clear=function(t){if(null!=t){var e=t>>6;this.ensure(e),this._bits[e]&=~(1<=this._bits.length){var e=new Number[t+1];e=this._bits.copyWithin(0,0,this._bits.length),this._bits=e}},t.prototype.get=function(t){var e=t>>6;return!(e>=this._bits.length)&&0!=(this._bits[e]&1<=0;)if(0!=(this._bits[e]&t._bits[e]))return!0;return!1},t.prototype.isEmpty=function(){for(var t=this._bits.length-1;t>=0;t--)if(this._bits[t])return!1;return!0},t.prototype.nextSetBit=function(t){for(var e=t>>6,n=1<>6;this.ensure(n),this._bits[n]|=1<0){for(var t=0;t0){t=0;for(var e=this._componentsToAdd.length;t0){var e=this._entitiesToRemove;this._entitiesToRemove=this._tempEntityList,this._tempEntityList=e,this._tempEntityList.forEach(function(e){t._entities.remove(e),e.scene=null,t.scene.entityProcessors.onEntityRemoved(e)}),this._tempEntityList.length=0}if(this._entitiesToAdded.length>0){e=this._entitiesToAdded;this._entitiesToAdded=this._tempEntityList,this._tempEntityList=e,this._tempEntityList.forEach(function(e){t._entities.contains(e)||(t._entities.push(e),e.scene=t.scene,t.scene.entityProcessors.onEntityAdded(e))}),this._tempEntityList.forEach(function(t){return t.onAddedToScene()}),this._tempEntityList.length=0}this._unsortedTags.length>0&&(this._unsortedTags.forEach(function(e){t._entityDict.get(e).sort()}),this._unsortedTags.length=0)},t}(),EntityProcessorList=function(){function t(){this._processors=[]}return t.prototype.add=function(t){this._processors.push(t)},t.prototype.remove=function(t){this._processors.remove(t)},t.prototype.onComponentAdded=function(t){this.notifyEntityChanged(t)},t.prototype.onComponentRemoved=function(t){this.notifyEntityChanged(t)},t.prototype.onEntityAdded=function(t){this.notifyEntityChanged(t)},t.prototype.onEntityRemoved=function(t){this.removeFromProcessors(t)},t.prototype.notifyEntityChanged=function(t){for(var e=0;e=0;e=this.allSet.nextSetBit(e+1))if(!t.componentBits.get(e))return!1;return!(!this.exclusionSet.isEmpty()&&this.exclusionSet.intersects(t.componentBits))&&!(!this.oneSet.isEmpty()&&!this.oneSet.intersects(t.componentBits))},t.prototype.all=function(){for(var t=this,e=[],n=0;n(this._timeSinceSceneLoad-this.deltaTime)/t},t.deltaTime=0,t.timeScale=1,t.frameCount=0,t._lastTime=0,t}(),GraphicsCapabilities=function(){function t(){}return t.prototype.initialize=function(t){this.platformInitialize(t)},t.prototype.platformInitialize=function(t){var e=(new egret.sys.RenderBuffer).context.getInstance();this.supportsNonPowerOfTwo=!1,this.supportsTextureFilterAnisotropic=null!=e.getExtension("EXT_texture_filter_anisotropic"),this.supportsDepth24=!0,this.supportsPackedDepthStencil=!0,this.supportsDepthNonLinear=!1,this.supportsTextureMaxLevel=!0,this.supportsS3tc=null!=e.getExtension("WEBGL_compressed_texture_s3tc")||null!=e.getExtension("WEBGL_compressed_texture_s3tc_srgb"),this.supportsDxt1=this.supportsS3tc,this.supportsPvrtc=!1,this.supportsAtitc=null!=e.getExtension("WEBGL_compressed_texture_astc"),this.supportsFramebufferObjectARB=!1},t}(),GraphicsDevice=function(){return function(){this.graphicsCapabilities=new GraphicsCapabilities,this.graphicsCapabilities.initialize(this)}}(),Viewport=function(){function t(t,e,n,i){this._x=t,this._y=e,this._width=n,this._height=i,this._minDepth=0,this._maxDepth=1}return Object.defineProperty(t.prototype,"aspectRatio",{get:function(){return 0!=this._height&&0!=this._width?this._width/this._height:0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"bounds",{get:function(){return new Rectangle(this._x,this._y,this._width,this._height)},set:function(t){this._x=t.x,this._y=t.y,this._width=t.width,this._height=t.height},enumerable:!0,configurable:!0}),t}(),GaussianBlurEffect=function(t){function e(){return t.call(this,PostProcessor.default_vert,e.blur_frag,{screenWidth:SceneManager.stage.stageWidth,screenHeight:SceneManager.stage.stageHeight})||this}return __extends(e,t),e.blur_frag="precision mediump float;\nuniform sampler2D uSampler;\nuniform float screenWidth;\nuniform float screenHeight;\nfloat normpdf(in float x, in float sigma)\n{\nreturn 0.39894*exp(-0.5*x*x/(sigma*sigma))/sigma;\n}\nvoid main()\n{\nvec3 c = texture2D(uSampler, gl_FragCoord.xy / vec2(screenWidth, screenHeight).xy).rgb;\nconst int mSize = 11;\nconst int kSize = (mSize - 1)/2;\nfloat kernel[mSize];\nvec3 final_colour = vec3(0.0);\nfloat sigma = 7.0;\nfloat z = 0.0;\nfor (int j = 0; j <= kSize; ++j)\n{\nkernel[kSize+j] = kernel[kSize-j] = normpdf(float(j),sigma);\n}\nfor (int j = 0; j < mSize; ++j)\n{\nz += kernel[j];\n}\nfor (int i = -kSize; i <= kSize; ++i)\n{\nfor (int j = -kSize; j <= kSize; ++j)\n{\nfinal_colour += kernel[kSize+j]*kernel[kSize+i]*texture2D(uSampler, (gl_FragCoord.xy+vec2(float(i),float(j))) / vec2(screenWidth, screenHeight).xy).rgb;\n}\n}\ngl_FragColor = vec4(final_colour/(z*z), 1.0);\n}",e}(egret.CustomFilter),PolygonLightEffect=function(t){function e(){return t.call(this,e.vertSrc,e.fragmentSrc)||this}return __extends(e,t),e.vertSrc="attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\nuniform vec2 projectionVector;\nvarying vec2 vTextureCoord;\nconst vec2 center = vec2(-1.0, 1.0);\nvoid main(void) {\n gl_Position = vec4( (aVertexPosition / projectionVector) + center , 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}",e.fragmentSrc="precision lowp float;\nvarying vec2 vTextureCoord;\nuniform sampler2D uSampler;\n#define SAMPLE_COUNT 15\nuniform vec2 _sampleOffsets[SAMPLE_COUNT];\nuniform float _sampleWeights[SAMPLE_COUNT];\nvoid main(void) {\nvec4 c = vec4(0, 0, 0, 0);\nfor( int i = 0; i < SAMPLE_COUNT; i++ )\n c += texture2D( uSampler, vTextureCoord + _sampleOffsets[i] ) * _sampleWeights[i];\ngl_FragColor = c;\n}",e}(egret.CustomFilter),PostProcessor=function(){function t(t){void 0===t&&(t=null),this.enable=!0,this.effect=t}return t.prototype.onAddedToScene=function(t){this.scene=t,this.shape=new egret.Shape,this.shape.graphics.beginFill(16777215,1),this.shape.graphics.drawRect(0,0,SceneManager.stage.stageWidth,SceneManager.stage.stageHeight),this.shape.graphics.endFill(),t.addChild(this.shape)},t.prototype.process=function(){this.drawFullscreenQuad()},t.prototype.onSceneBackBufferSizeChanged=function(t,e){},t.prototype.drawFullscreenQuad=function(){this.scene.filters=[this.effect]},t.prototype.unload=function(){this.effect&&(this.effect=null),this.scene.removeChild(this.shape),this.scene=null},t.default_vert="attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\nattribute vec2 aColor;\nuniform vec2 projectionVector;\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\nconst vec2 center = vec2(-1.0, 1.0);\nvoid main(void) {\ngl_Position = vec4( (aVertexPosition / projectionVector) + center , 0.0, 1.0);\nvTextureCoord = aTextureCoord;\nvColor = vec4(aColor.x, aColor.x, aColor.x, aColor.x);\n}",t}(),GaussianBlurPostProcessor=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return __extends(e,t),e.prototype.onAddedToScene=function(e){t.prototype.onAddedToScene.call(this,e),this.effect=new GaussianBlurEffect},e}(PostProcessor),Renderer=function(){function t(){}return t.prototype.onAddedToScene=function(t){},t.prototype.beginRender=function(t){},t.prototype.unload=function(){},t.prototype.renderAfterStateCheck=function(t,e){t.render(e)},t}(),DefaultRenderer=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return __extends(e,t),e.prototype.render=function(t){var e=this.camera?this.camera:t.camera;this.beginRender(e);for(var n=0;nn?n:t},t.pointOnCirlce=function(e,n,i){var o=t.toRadians(i);return new Vector2(Math.cos(o)*o+e.x,Math.sin(o)*o+e.y)},t.isEven=function(t){return t%2==0},t.clamp01=function(t){return t<0?0:t>1?1:t},t.angleBetweenVectors=function(t,e){return Math.atan2(e.y-t.y,e.x-t.x)},t.Epsilon=1e-5,t.Rad2Deg=57.29578,t.Deg2Rad=.0174532924,t}(),Matrix2D=function(){function t(t,e,n,i,o,r){this.m11=0,this.m12=0,this.m21=0,this.m22=0,this.m31=0,this.m32=0,this.m11=t||1,this.m12=e||0,this.m21=n||0,this.m22=i||1,this.m31=o||0,this.m32=r||0}return Object.defineProperty(t,"identity",{get:function(){return t._identity},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"translation",{get:function(){return new Vector2(this.m31,this.m32)},set:function(t){this.m31=t.x,this.m32=t.y},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"rotation",{get:function(){return Math.atan2(this.m21,this.m11)},set:function(t){var e=Math.cos(t),n=Math.sin(t);this.m11=e,this.m12=n,this.m21=-n,this.m22=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"rotationDegrees",{get:function(){return MathHelper.toDegrees(this.rotation)},set:function(t){this.rotation=MathHelper.toRadians(t)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"scale",{get:function(){return new Vector2(this.m11,this.m22)},set:function(t){this.m11=t.x,this.m12=t.y},enumerable:!0,configurable:!0}),t.add=function(t,e){return t.m11+=e.m11,t.m12+=e.m12,t.m21+=e.m21,t.m22+=e.m22,t.m31+=e.m31,t.m32+=e.m32,t},t.divide=function(t,e){return t.m11/=e.m11,t.m12/=e.m12,t.m21/=e.m21,t.m22/=e.m22,t.m31/=e.m31,t.m32/=e.m32,t},t.multiply=function(e,n){var i=new t,o=e.m11*n.m11+e.m12*n.m21,r=e.m11*n.m12+e.m12*n.m22,s=e.m21*n.m11+e.m22*n.m21,a=e.m21*n.m12+e.m22*n.m22,c=e.m31*n.m11+e.m32*n.m21+n.m31,h=e.m31*n.m12+e.m32*n.m22+n.m32;return i.m11=o,i.m12=r,i.m21=s,i.m22=a,i.m31=c,i.m32=h,i},t.multiplyTranslation=function(e,n,i){var o=t.createTranslation(n,i);return t.multiply(e,o)},t.prototype.determinant=function(){return this.m11*this.m22-this.m12*this.m21},t.invert=function(e,n){void 0===n&&(n=new t);var i=1/e.determinant();return n.m11=e.m22*i,n.m12=-e.m12*i,n.m21=-e.m21*i,n.m22=e.m11*i,n.m31=(e.m32*e.m21-e.m31*e.m22)*i,n.m32=-(e.m32*e.m11-e.m31*e.m12)*i,n},t.createTranslation=function(e,n){var i=new t;return i.m11=1,i.m12=0,i.m21=0,i.m22=1,i.m31=e,i.m32=n,i},t.createTranslationVector=function(t){return this.createTranslation(t.x,t.y)},t.createRotation=function(e,n){n=new t;var i=Math.cos(e),o=Math.sin(e);return n.m11=i,n.m12=o,n.m21=-o,n.m22=i,n},t.createScale=function(e,n,i){return void 0===i&&(i=new t),i.m11=e,i.m12=0,i.m21=0,i.m22=n,i.m31=0,i.m32=0,i},t.prototype.toEgretMatrix=function(){return new egret.Matrix(this.m11,this.m12,this.m21,this.m22,this.m31,this.m32)},t._identity=new t(1,0,0,1,0,0),t}(),Rectangle=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return __extends(e,t),Object.defineProperty(e.prototype,"max",{get:function(){return new Vector2(this.right,this.bottom)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"center",{get:function(){return new Vector2(this.x+this.width/2,this.y+this.height/2)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"location",{get:function(){return new Vector2(this.x,this.y)},set:function(t){this.x=t.x,this.y=t.y},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"size",{get:function(){return new Vector2(this.width,this.height)},set:function(t){this.width=t.x,this.height=t.y},enumerable:!0,configurable:!0}),e.prototype.intersects=function(t){return t.lefti&&(i=s.x),s.yo&&(o=s.y)}return this.fromMinMax(e,n,i,o)},e}(egret.Rectangle),Vector3=function(){return function(t,e,n){this.x=t,this.y=e,this.z=n}}(),ColliderTriggerHelper=function(){function t(t){this._activeTriggerIntersections=[],this._previousTriggerIntersections=[],this._tempTriggerList=[],this._entity=t}return t.prototype.update=function(){for(var t=this._entity.getComponents(Collider),e=0;e1)return!1;var h=(a.x*o.y-a.y*o.x)/s;return!(h<0||h>1)},t.lineToLineIntersection=function(t,e,n,i){var o=new Vector2(0,0),r=Vector2.subtract(e,t),s=Vector2.subtract(i,n),a=r.x*s.y-r.y*s.x;if(0==a)return o;var c=Vector2.subtract(n,t),h=(c.x*s.y-c.y*s.x)/a;if(h<0||h>1)return o;var u=(c.x*r.y-c.y*r.x)/a;return u<0||u>1?o:o=Vector2.add(t,new Vector2(h*r.x,h*r.y))},t.closestPointOnLine=function(t,e,n){var i=Vector2.subtract(e,t),o=Vector2.subtract(n,t),r=Vector2.dot(o,i)/Vector2.dot(i,i);return r=MathHelper.clamp(r,0,1),Vector2.add(t,new Vector2(i.x*r,i.y*r))},t.isCircleToCircle=function(t,e,n,i){return Vector2.distanceSquared(t,n)<(e+i)*(e+i)},t.isCircleToLine=function(t,e,n,i){return Vector2.distanceSquared(t,this.closestPointOnLine(n,i,t))=t&&o.y>=e&&o.x=t+n&&(r|=PointSectors.right),o.y=e+i&&(r|=PointSectors.bottom),r},t}(),Physics=function(){function t(){}return t.reset=function(){this._spatialHash=new SpatialHash(this.spatialHashCellSize)},t.clear=function(){this._spatialHash.clear()},t.overlapCircleAll=function(t,e,n,i){return void 0===i&&(i=-1),this._spatialHash.overlapCircle(t,e,n,i)},t.boxcastBroadphase=function(t,e){void 0===e&&(e=this.allLayers);var n=this._spatialHash.aabbBroadphase(t,null,e);return{colliders:n.tempHashSet,rect:n.bounds}},t.boxcastBroadphaseExcludingSelf=function(t,e,n){return void 0===n&&(n=this.allLayers),this._spatialHash.aabbBroadphase(e,t,n)},t.addCollider=function(e){t._spatialHash.register(e)},t.removeCollider=function(e){t._spatialHash.remove(e)},t.updateCollider=function(t){this._spatialHash.remove(t),this._spatialHash.register(t)},t.debugDraw=function(t){this._spatialHash.debugDraw(t,2)},t.spatialHashCellSize=100,t.allLayers=-1,t}(),Shape=function(){return function(){this.bounds=new Rectangle,this.position=Vector2.zero}}(),Polygon=function(t){function e(e,n){var i=t.call(this)||this;return i.isUnrotated=!0,i._areEdgeNormalsDirty=!0,i.center=new Vector2,i.setPoints(e),i.isBox=n,i}return __extends(e,t),Object.defineProperty(e.prototype,"edgeNormals",{get:function(){return this._areEdgeNormalsDirty&&this.buildEdgeNormals(),this._edgeNormals},enumerable:!0,configurable:!0}),e.prototype.buildEdgeNormals=function(){var t,e=this.isBox?2:this.points.length;null!=this._edgeNormals&&this._edgeNormals.length==e||(this._edgeNormals=new Array(e));for(var n=0;n=this.points.length?this.points[0]:this.points[n+1];var o=Vector2Ext.perpendicular(i,t);o=Vector2.normalize(o),this._edgeNormals[n]=o}},e.prototype.setPoints=function(t){this.points=t,this.recalculateCenterAndEdgeNormals(),this._originalPoints=[];for(var e=0;et.y!=this.points[i].y>t.y&&t.x<(this.points[i].x-this.points[n].x)*(t.y-this.points[n].y)/(this.points[i].y-this.points[n].y)+this.points[n].x&&(e=!e);return e},e.buildSymmertricalPolygon=function(t,e){for(var n=new Array(t),i=0;i0&&(o=!1),!o)return null;(g=Math.abs(g))i&&(i=o);return{min:n,max:i}},t.circleToPolygon=function(t,e){var n=new CollisionResult,i=Vector2.subtract(t.position,e.position),o=Polygon.getClosestPointOnPolygonToPoint(e.points,i),r=o.closestPoint,s=o.distanceSquared;n.normal=o.edgeNormal;var a,c=e.containsPoint(t.position);if(s>t.radius*t.radius&&!c)return null;if(c)a=Vector2.multiply(n.normal,new Vector2(Math.sqrt(s)-t.radius));else if(0==s)a=Vector2.multiply(n.normal,new Vector2(t.radius));else{var h=Math.sqrt(s);a=Vector2.multiply(new Vector2(-Vector2.subtract(i,r)),new Vector2((t.radius-s)/h))}return n.minimumTranslationVector=a,n.point=Vector2.add(r,e.position),n},t.circleToBox=function(t,e){var n=new CollisionResult,i=e.bounds.getClosestPointOnRectangleBorderToPoint(t.position).res;if(e.containsPoint(t.position)){n.point=i;var o=Vector2.add(i,Vector2.subtract(n.normal,new Vector2(t.radius)));return n.minimumTranslationVector=Vector2.subtract(t.position,o),n}var r=Vector2.distanceSquared(i,t.position);if(0==r)n.minimumTranslationVector=Vector2.multiply(n.normal,new Vector2(t.radius));else if(r<=t.radius*t.radius){n.normal=Vector2.subtract(t.position,i);var s=n.normal.length()-t.radius;return n.normal=Vector2Ext.normalize(n.normal),n.minimumTranslationVector=Vector2.multiply(new Vector2(s),n.normal),n}return null},t.pointToCircle=function(t,e){var n=new CollisionResult,i=Vector2.distanceSquared(t,e.position),o=1+e.radius;if(i0&&this.debugDrawCellDetails(n,i,o.length,t,e)}},t.prototype.debugDrawCellDetails=function(t,e,n,i,o){void 0===i&&(i=.5),void 0===o&&(o=1)},t}(),RaycastResultParser=function(){return function(){}}(),NumberDictionary=function(){function t(){this._store=new Map}return t.prototype.getKey=function(t,e){return Long.fromNumber(t).shiftLeft(32).or(this.intToUint(e)).toString()},t.prototype.intToUint=function(t){return t>=0?t:4294967296+t},t.prototype.add=function(t,e,n){this._store.set(this.getKey(t,e),n)},t.prototype.remove=function(t){this._store.forEach(function(e){e.contains(t)&&e.remove(t)})},t.prototype.tryGetValue=function(t,e){return this._store.get(this.getKey(t,e))},t.prototype.clear=function(){this._store.clear()},t}(),ContentManager=function(){function t(){this.loadedAssets=new Map}return t.prototype.loadRes=function(t,e){var n=this;return void 0===e&&(e=!0),new Promise(function(i,o){var r=n.loadedAssets.get(t);r?i(r):e?RES.getResAsync(t).then(function(e){n.loadedAssets.set(t,e),i(e)}).catch(function(e){console.error("资源加载错误:",t,e),o(e)}):RES.getResByUrl(t).then(function(e){n.loadedAssets.set(t,e),i(e)}).catch(function(e){console.error("资源加载错误:",t,e),o(e)})})},t.prototype.dispose=function(){this.loadedAssets.forEach(function(t){t.dispose()}),this.loadedAssets.clear()},t}(),DrawUtils=function(){function t(){}return t.drawLine=function(t,e,n,i,o){void 0===o&&(o=1),this.drawLineAngle(t,e,MathHelper.angleBetweenVectors(e,n),Vector2.distance(e,n),i,o)},t.drawLineAngle=function(t,e,n,i,o,r){void 0===r&&(r=1),t.graphics.beginFill(o),t.graphics.drawRect(e.x,e.y,1,1),t.graphics.endFill(),t.scaleX=i,t.scaleY=r,t.$anchorOffsetX=0,t.$anchorOffsetY=0,t.rotation=n},t.drawHollowRect=function(t,e,n,i){void 0===i&&(i=1),this.drawHollowRectR(t,e.x,e.y,e.width,e.height,n,i)},t.drawHollowRectR=function(t,e,n,i,o,r,s){void 0===s&&(s=1);var a=new Vector2(e,n).round(),c=new Vector2(e+i,n).round(),h=new Vector2(e+i,n+o).round(),u=new Vector2(e,n+o).round();this.drawLine(t,a,c,r,s),this.drawLine(t,c,h,r,s),this.drawLine(t,h,u,r,s),this.drawLine(t,u,a,r,s)},t.drawPixel=function(t,e,n,i){void 0===i&&(i=1);var o=new Rectangle(e.x,e.y,i,i);1!=i&&(o.x-=.5*i,o.y-=.5*i),t.graphics.beginFill(n),t.graphics.drawRect(o.x,o.y,o.width,o.height),t.graphics.endFill()},t}(),Emitter=function(){function t(){this._messageTable=new Map}return t.prototype.addObserver=function(t,e,n){var i=this._messageTable.get(t);i||(i=[],this._messageTable.set(t,i)),i.contains(e)&&console.warn("您试图添加相同的观察者两次"),i.push(new FuncPack(e,n))},t.prototype.removeObserver=function(t,e){var n=this._messageTable.get(t),i=n.findIndex(function(t){return t.func==e});-1!=i&&n.removeAt(i)},t.prototype.emit=function(t,e){var n=this._messageTable.get(t);if(n)for(var i=n.length-1;i>=0;i--)n[i].func.call(n[i].context,e)},t}(),FuncPack=function(){return function(t,e){this.func=t,this.context=e}}(),GlobalManager=function(){function t(){}return Object.defineProperty(t.prototype,"enabled",{get:function(){return this._enabled},set:function(t){this.setEnabled(t)},enumerable:!0,configurable:!0}),t.prototype.setEnabled=function(t){this._enabled!=t&&(this._enabled=t,this._enabled?this.onEnabled():this.onDisabled())},t.prototype.onEnabled=function(){},t.prototype.onDisabled=function(){},t.prototype.update=function(){},t.registerGlobalManager=function(t){this.globalManagers.push(t),t.enabled=!0},t.unregisterGlobalManager=function(t){this.globalManagers.remove(t),t.enabled=!1},t.getGlobalManager=function(t){for(var e=0;e0&&this.setpreviousTouchState(this._gameTouchs[0]),t},enumerable:!0,configurable:!0}),t.initialize=function(t){this._init||(this._init=!0,this._stage=t,this._stage.addEventListener(egret.TouchEvent.TOUCH_BEGIN,this.touchBegin,this),this._stage.addEventListener(egret.TouchEvent.TOUCH_MOVE,this.touchMove,this),this._stage.addEventListener(egret.TouchEvent.TOUCH_END,this.touchEnd,this),this._stage.addEventListener(egret.TouchEvent.TOUCH_CANCEL,this.touchEnd,this),this._stage.addEventListener(egret.TouchEvent.TOUCH_RELEASE_OUTSIDE,this.touchEnd,this),this.initTouchCache())},t.initTouchCache=function(){this._totalTouchCount=0,this._touchIndex=0,this._gameTouchs.length=0;for(var t=0;t0)for(var e=0;ethis._objectQueue.length;)this._objectQueue.shift()},t.clearCache=function(){this._objectQueue.length=0},t.obtain=function(){return this._objectQueue.length>0?this._objectQueue.shift():[]},t.free=function(t){this._objectQueue.unshift(t),t.length=0},t._objectQueue=[],t}(),THREAD_ID=Math.floor(1e3*Math.random())+"-"+Date.now(),setItem=egret.localStorage.setItem.bind(localStorage),getItem=egret.localStorage.getItem.bind(localStorage),removeItem=egret.localStorage.removeItem.bind(localStorage),nextTick=function(t){setTimeout(t,0)},LockUtils=function(){function t(t){this._keyX="mutex_key_"+t+"_X",this._keyY="mutex_key_"+t+"_Y"}return t.prototype.lock=function(){var t=this;return new Promise(function(e,n){var i=function(){setItem(t._keyX,THREAD_ID),null===!getItem(t._keyY)&&nextTick(i),setItem(t._keyY,THREAD_ID),getItem(t._keyX)!==THREAD_ID?setTimeout(function(){getItem(t._keyY)===THREAD_ID?(e(),removeItem(t._keyY)):nextTick(i)},10):(e(),removeItem(t._keyY))};i()})},t}(),Pair=function(){function t(t,e){this.first=t,this.second=e}return t.prototype.clear=function(){this.first=this.second=null},t.prototype.equals=function(t){return this.first==t.first&&this.second==t.second},t}(),RectangleExt=function(){function t(){}return t.union=function(t,e){var n=new Rectangle(e.x,e.y,0,0),i=t.union(n);return new Rectangle(i.x,i.y,i.width,i.height)},t}(),Triangulator=function(){function t(){this.triangleIndices=[],this._triPrev=new Array(12),this._triNext=new Array(12)}return t.prototype.triangulate=function(e,n){void 0===n&&(n=!0);var i=e.length;this.initialize(i);for(var o=0,r=0;i>3&&o<500;){o++;var s=!0,a=e[this._triPrev[r]],c=e[r],h=e[this._triNext[r]];if(Vector2Ext.isTriangleCCW(a,c,h)){var u=this._triNext[this._triNext[r]];do{if(t.testPointTriangle(e[u],a,c,h)){s=!1;break}u=this._triNext[u]}while(u!=this._triPrev[r])}else s=!1;s?(this.triangleIndices.push(this._triPrev[r]),this.triangleIndices.push(r),this.triangleIndices.push(this._triNext[r]),this._triNext[this._triPrev[r]]=this._triNext[r],this._triPrev[this._triNext[r]]=this._triPrev[r],i--,r=this._triPrev[r]):r=this._triNext[r]}this.triangleIndices.push(this._triPrev[r]),this.triangleIndices.push(r),this.triangleIndices.push(this._triNext[r]),n||this.triangleIndices.reverse()},t.prototype.initialize=function(t){this.triangleIndices.length=0,this._triNext.lengthMathHelper.Epsilon?t=Vector2.divide(t,new Vector2(e)):t.x=t.y=0,t},t.transformA=function(t,e,n,i,o,r){for(var s=0;sthis.safeArea.right&&(o.x=this.safeArea.right-o.width),o.topthis.safeArea.bottom&&(o.y=this.safeArea.bottom-o.height),o},t}();!function(t){t[t.none=0]="none",t[t.left=1]="left",t[t.right=2]="right",t[t.horizontalCenter=4]="horizontalCenter",t[t.top=8]="top",t[t.bottom=16]="bottom",t[t.verticalCenter=32]="verticalCenter",t[t.topLeft=9]="topLeft",t[t.topRight=10]="topRight",t[t.topCenter=12]="topCenter",t[t.bottomLeft=17]="bottomLeft",t[t.bottomRight=18]="bottomRight",t[t.bottomCenter=20]="bottomCenter",t[t.centerLeft=33]="centerLeft",t[t.centerRight=34]="centerRight",t[t.center=36]="center"}(Alignment||(Alignment={})),function(t){var e,n=function(){function t(t){void 0===t&&(t=i),this.getSystemTime=t,this._stopDuration=0,this._completeSlices=[]}return t.prototype.getState=function(){return void 0===this._startSystemTime?e.IDLE:void 0===this._stopSystemTime?e.RUNNING:e.STOPPED},t.prototype.isIdle=function(){return this.getState()===e.IDLE},t.prototype.isRunning=function(){return this.getState()===e.RUNNING},t.prototype.isStopped=function(){return this.getState()===e.STOPPED},t.prototype.slice=function(){return this.recordPendingSlice()},t.prototype.getCompletedSlices=function(){return Array.from(this._completeSlices)},t.prototype.getCompletedAndPendingSlices=function(){return this._completeSlices.concat([this.getPendingSlice()])},t.prototype.getPendingSlice=function(){return this.calculatePendingSlice()},t.prototype.getTime=function(){return this.caculateStopwatchTime()},t.prototype.calculatePendingSlice=function(t){return void 0===this._pendingSliceStartStopwatchTime?Object.freeze({startTime:0,endTime:0,duration:0}):(void 0===t&&(t=this.getTime()),Object.freeze({startTime:this._pendingSliceStartStopwatchTime,endTime:t,duration:t-this._pendingSliceStartStopwatchTime}))},t.prototype.caculateStopwatchTime=function(t){return void 0===this._startSystemTime?0:(void 0===t&&(t=this.getSystemTimeOfCurrentStopwatchTime()),t-this._startSystemTime-this._stopDuration)},t.prototype.getSystemTimeOfCurrentStopwatchTime=function(){return void 0===this._stopSystemTime?this.getSystemTime():this._stopSystemTime},t.prototype.reset=function(){this._startSystemTime=this._pendingSliceStartStopwatchTime=this._stopSystemTime=void 0,this._stopDuration=0,this._completeSlices=[]},t.prototype.start=function(t){if(void 0===t&&(t=!1),t&&this.reset(),void 0!==this._stopSystemTime){var e=(n=this.getSystemTime())-this._stopSystemTime;this._stopDuration+=e,this._stopSystemTime=void 0}else if(void 0===this._startSystemTime){var n=this.getSystemTime();this._startSystemTime=n,this._pendingSliceStartStopwatchTime=0}},t.prototype.stop=function(t){if(void 0===t&&(t=!1),void 0===this._startSystemTime)return 0;var e=this.getSystemTimeOfCurrentStopwatchTime();return t&&this.recordPendingSlice(this.caculateStopwatchTime(e)),this._stopSystemTime=e,this.getTime()},t.prototype.recordPendingSlice=function(t){if(void 0!==this._pendingSliceStartStopwatchTime){void 0===t&&(t=this.getTime());var e=this.calculatePendingSlice(t);return this._pendingSliceStartStopwatchTime=e.endTime,this._completeSlices.push(e),e}return this.calculatePendingSlice()},t}();t.Stopwatch=n,function(t){t.IDLE="IDLE",t.RUNNING="RUNNING",t.STOPPED="STOPPED"}(e||(e={})),t.setDefaultSystemTimeGetter=function(t){void 0===t&&(t=Date.now),i=t};var i=Date.now}(stopwatch||(stopwatch={}));var TimeRuler=function(){function t(){this._frameKey="frame",this._logKey="log",this.markers=[],this.stopwacth=new stopwatch.Stopwatch,this._markerNameToIdMap=new Map,this.showLog=!1,t.Instance=this,this._logs=new Array(2);for(var e=0;e=t.logSnapDuration&&(l.logs[o].snapMin=l.logs[o].min,l.logs[o].snapMax=l.logs[o].max,l.logs[o].snapAvg=l.logs[o].avg,l.logs[o].samples=0)):(l.logs[o].min=h,l.logs[o].max=h,l.logs[o].avg=h,l.logs[o].initialized=!0)}s.markCount=r.nestCount,s.nestCount=r.nestCount}e.stopwacth.reset(),e.stopwacth.start()}})},t.prototype.beginMark=function(e,n,i){var o=this;void 0===i&&(i=0),new LockUtils(this._frameKey).lock().then(function(){if(i<0||i>=t.maxBars)throw new Error("barIndex argument out of range");var r=o._curLog.bars[i];if(r.markCount>=t.maxSamples)throw new Error("exceeded sample count. either set larger number to timeruler.maxsaple or lower sample count");if(r.nestCount>=t.maxNestCall)throw new Error("exceeded nest count. either set larger number to timeruler.maxnestcall or lower nest calls");var s=o._markerNameToIdMap.get(e);s||(s=o.markers.length,o._markerNameToIdMap.set(e,s)),r.markerNests[r.nestCount++]=r.markCount,r.markers[r.markCount].markerId=s,r.markers[r.markCount].color=n,r.markers[r.markCount].beginTime=o.stopwacth.getTime(),r.markers[r.markCount].endTime=-1})},t.prototype.endMark=function(e,n){var i=this;void 0===n&&(n=0),new LockUtils(this._frameKey).lock().then(function(){if(n<0||n>=t.maxBars)throw new Error("barIndex argument out of range");var o=i._curLog.bars[n];if(o.nestCount<=0)throw new Error("call beginMark method before calling endMark method");var r=i._markerNameToIdMap.get(e);if(!r)throw new Error("Marker "+e+" is not registered. Make sure you specifed same name as you used for beginMark method");var s=o.markerNests[--o.nestCount];if(o.markers[s].markerId!=r)throw new Error("Incorrect call order of beginMark/endMark method. beginMark(A), beginMark(B), endMark(B), endMark(A) But you can't called it like beginMark(A), beginMark(B), endMark(A), endMark(B).");o.markers[s].endTime=i.stopwacth.getTime()})},t.prototype.getAverageTime=function(e,n){if(e<0||e>=t.maxBars)throw new Error("barIndex argument out of range");var i=0,o=this._markerNameToIdMap.get(n);return o&&(i=this.markers[o].logs[e].avg),i},t.prototype.resetLog=function(){var t=this;new LockUtils(this._logKey).lock().then(function(){var e=parseInt(egret.localStorage.getItem(t._logKey),10);e+=1,egret.localStorage.setItem(t._logKey,e.toString()),t.markers.forEach(function(t){for(var e=0;e0&&(i+=t.barHeight+2*t.barPadding,o=Math.max(o,e.markers[e.markCount-1].endTime))});var r=this.sampleFrames*(1/60*1e3);this._frameAdjust=o>r?Math.max(0,this._frameAdjust)+1:Math.min(0,this._frameAdjust)-1,Math.max(this._frameAdjust)>t.autoAdjustDelay&&(this.sampleFrames=Math.min(t.maxSampleFrames,this.sampleFrames),this.sampleFrames=Math.max(this.targetSampleFrames,o/(1/60*1e3)+1),this._frameAdjust=0);e.y,t.barHeight}},t.maxBars=0,t.maxSamples=256,t.maxNestCall=32,t.barHeight=8,t.maxSampleFrames=4,t.logSnapDuration=120,t.barPadding=2,t.autoAdjustDelay=30,t}(),FrameLog=function(){return function(){this.bars=new Array(TimeRuler.maxBars);for(var t=0;t0&&r[r.length-1])&&(6===o[0]||2===o[0])){s=0;continue}if(3===o[0]&&(!r||o[1]>r[0]&&o[1]-1}(this,t)},Array.prototype.firstOrDefault=function(t){return function(t,e){var n=t.findIndex(e);return-1==n?null:t[n]}(this,t)},Array.prototype.find=function(t){return function(t,e){return t.firstOrDefault(e)}(this,t)},Array.prototype.where=function(t){return function(t,e){if("function"==typeof t.reduce)return t.reduce(function(n,i,r){return e.call(arguments[2],i,r,t)&&n.push(i),n},[]);for(var n=[],i=0,r=t.length;i=0&&t.splice(n,1)}while(n>=0)}(this,t)},Array.prototype.remove=function(t){return function(t,e){var n=t.findIndex(function(t){return t===e});return n>=0&&(t.splice(n,1),!0)}(this,t)},Array.prototype.removeAt=function(t){return function(t,e){t.splice(e,1)}(this,t)},Array.prototype.removeRange=function(t,e){return function(t,e,n){t.splice(e,n)}(this,t,e)},Array.prototype.select=function(t){return function(t,e){if("function"==typeof t.reduce)return t.reduce(function(n,i,r){return n.push(e.call(arguments[2],i,r,t)),n},[]);for(var n=[],i=0,r=t.length;io?1:-1}),t}(this,t,e)},Array.prototype.orderByDescending=function(t,e){return function(t,e,n){return t.sort(function(t,i){var r=e(t),o=e(i);return n?-n(r,o):r0;){if("break"===c())break}return r?this.recontructPath(o,e,n):null},t.hasKey=function(t,e){for(var n,i=t.keys();!(n=i.next()).done;)if(JSON.stringify(n.value)==JSON.stringify(e))return!0;return!1},t.getKey=function(t,e){for(var n,i,r=t.keys(),o=t.values();n=r.next(),i=o.next(),!n.done;)if(JSON.stringify(n.value)==JSON.stringify(e))return i.value;return null},t.recontructPath=function(t,e,n){var i=[],r=n;for(i.push(n);r!=e;)r=this.getKey(t,r),i.push(r);return i.reverse(),i},t}(),AStarNode=function(t){function e(e){var n=t.call(this)||this;return n.data=e,n}return __extends(e,t),e}(PriorityQueueNode),AstarGridGraph=function(){function t(t,e){this.dirs=[new Vector2(1,0),new Vector2(0,-1),new Vector2(-1,0),new Vector2(0,1)],this.walls=[],this.weightedNodes=[],this.defaultWeight=1,this.weightedNodeWeight=5,this._neighbors=new Array(4),this._width=t,this._height=e}return t.prototype.isNodeInBounds=function(t){return 0<=t.x&&t.x=this._nodes.length?(console.error("node.QueueIndex has been corrupted. Did you change it manually? Or add this node to another queue?"),!1):this._nodes[t.queueIndex]==t:(console.error("node cannot be null"),!1)},t.prototype.enqueue=function(t,e){t.priority=e,this._numNodes++,this._nodes[this._numNodes]=t,t.queueIndex=this._numNodes,t.insertionIndex=this._numNodesEverEnqueued++,this.cascadeUp(this._nodes[this._numNodes])},t.prototype.dequeue=function(){var t=this._nodes[1];return this.remove(t),t},t.prototype.remove=function(t){if(t.queueIndex==this._numNodes)return this._nodes[this._numNodes]=null,void this._numNodes--;var e=this._nodes[this._numNodes];this.swap(t,e),delete this._nodes[this._numNodes],this._numNodes--,this.onNodeUpdated(e)},t.prototype.isValidQueue=function(){for(var t=1;t0&&this.hasHigherPriority(t,n)?this.cascadeUp(t):this.cascadeDown(t)},t.prototype.cascadeDown=function(t){for(var e,n=t.queueIndex;;){e=t;var i=2*n;if(i>this._numNodes){t.queueIndex=n,this._nodes[n]=t;break}var r=this._nodes[i];this.hasHigherPriority(r,e)&&(e=r);var o=i+1;if(o<=this._numNodes){var s=this._nodes[o];this.hasHigherPriority(s,e)&&(e=s)}if(e==t){t.queueIndex=n,this._nodes[n]=t;break}this._nodes[n]=e;var a=e.queueIndex;e.queueIndex=n,n=a}},t.prototype.cascadeUp=function(t){for(var e=Math.floor(t.queueIndex/2);e>=1;){var n=this._nodes[e];if(this.hasHigherPriority(n,t))break;this.swap(t,n),e=Math.floor(t.queueIndex/2)}},t.prototype.swap=function(t,e){this._nodes[t.queueIndex]=e,this._nodes[e.queueIndex]=t;var n=t.queueIndex;t.queueIndex=e.queueIndex,e.queueIndex=n},t.prototype.hasHigherPriority=function(t,e){return t.priority0;){if("break"===a())break}return r?AStarPathfinder.recontructPath(s,e,n):null},t.hasKey=function(t,e){for(var n,i=t.keys();!(n=i.next()).done;)if(JSON.stringify(n.value)==JSON.stringify(e))return!0;return!1},t}(),UnweightedGraph=function(){function t(){this.edges=new Map}return t.prototype.addEdgesForNode=function(t,e){return this.edges.set(t,e),this},t.prototype.getNeighbors=function(t){return this.edges.get(t)},t}(),Vector2=function(){function t(t,e){this.x=0,this.y=0,this.x=t||0,this.y=e||this.x}return Object.defineProperty(t,"zero",{get:function(){return t.zeroVector2},enumerable:!0,configurable:!0}),Object.defineProperty(t,"one",{get:function(){return t.unitVector2},enumerable:!0,configurable:!0}),Object.defineProperty(t,"unitX",{get:function(){return t.unitXVector},enumerable:!0,configurable:!0}),Object.defineProperty(t,"unitY",{get:function(){return t.unitYVector},enumerable:!0,configurable:!0}),t.add=function(e,n){var i=new t(0,0);return i.x=e.x+n.x,i.y=e.y+n.y,i},t.divide=function(e,n){var i=new t(0,0);return i.x=e.x/n.x,i.y=e.y/n.y,i},t.multiply=function(e,n){var i=new t(0,0);return i.x=e.x*n.x,i.y=e.y*n.y,i},t.subtract=function(e,n){var i=new t(0,0);return i.x=e.x-n.x,i.y=e.y-n.y,i},t.prototype.normalize=function(){var t=1/Math.sqrt(this.x*this.x+this.y*this.y);this.x*=t,this.y*=t},t.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},t.prototype.round=function(){return new t(Math.round(this.x),Math.round(this.y))},t.normalize=function(t){var e=1/Math.sqrt(t.x*t.x+t.y*t.y);return t.x*=e,t.y*=e,t},t.dot=function(t,e){return t.x*e.x+t.y*e.y},t.distanceSquared=function(t,e){var n=t.x-e.x,i=t.y-e.y;return n*n+i*i},t.clamp=function(e,n,i){return new t(MathHelper.clamp(e.x,n.x,i.x),MathHelper.clamp(e.y,n.y,i.y))},t.lerp=function(e,n,i){return new t(MathHelper.lerp(e.x,n.x,i),MathHelper.lerp(e.y,n.y,i))},t.transform=function(e,n){return new t(e.x*n.m11+e.y*n.m21,e.x*n.m12+e.y*n.m22)},t.distance=function(t,e){var n=t.x-e.x,i=t.y-e.y;return Math.sqrt(n*n+i*i)},t.negate=function(e){var n=new t;return n.x=-e.x,n.y=-e.y,n},t.unitYVector=new t(0,1),t.unitXVector=new t(1,0),t.unitVector2=new t(1,1),t.zeroVector2=new t(0,0),t}(),UnweightedGridGraph=function(){function t(e,n,i){void 0===i&&(i=!1),this.walls=[],this._neighbors=new Array(4),this._width=e,this._hegiht=n,this._dirs=i?t.COMPASS_DIRS:t.CARDINAL_DIRS}return t.prototype.isNodeInBounds=function(t){return 0<=t.x&&t.x0;){if("break"===c())break}return r?this.recontructPath(o,e,n):null},t.hasKey=function(t,e){for(var n,i=t.keys();!(n=i.next()).done;)if(JSON.stringify(n.value)==JSON.stringify(e))return!0;return!1},t.getKey=function(t,e){for(var n,i,r=t.keys(),o=t.values();n=r.next(),i=o.next(),!n.done;)if(JSON.stringify(n.value)==JSON.stringify(e))return i.value;return null},t.recontructPath=function(t,e,n){var i=[],r=n;for(i.push(n);r!=e;)r=this.getKey(t,r),i.push(r);return i.reverse(),i},t}(),Debug=function(){function t(){}return t.drawHollowRect=function(t,e,n){void 0===n&&(n=0),this._debugDrawItems.push(new DebugDrawItem(t,e,n))},t.render=function(){if(this._debugDrawItems.length>0){var t=new egret.Shape;SceneManager.scene&&SceneManager.scene.addChild(t);for(var e=this._debugDrawItems.length-1;e>=0;e--){this._debugDrawItems[e].draw(t)&&this._debugDrawItems.removeAt(e)}}},t._debugDrawItems=[],t}(),DebugDefaults=function(){function t(){}return t.verletParticle=14431326,t.verletConstraintEdge=4406838,t}();!function(t){t[t.line=0]="line",t[t.hollowRectangle=1]="hollowRectangle",t[t.pixel=2]="pixel",t[t.text=3]="text"}(DebugDrawType||(DebugDrawType={}));var CoreEvents,DebugDrawItem=function(){function t(t,e,n){this.rectangle=t,this.color=e,this.duration=n,this.drawType=DebugDrawType.hollowRectangle}return t.prototype.draw=function(t){switch(this.drawType){case DebugDrawType.line:DrawUtils.drawLine(t,this.start,this.end,this.color);break;case DebugDrawType.hollowRectangle:DrawUtils.drawHollowRect(t,this.rectangle,this.color);break;case DebugDrawType.pixel:DrawUtils.drawPixel(t,new Vector2(this.x,this.y),this.color,this.size);break;case DebugDrawType.text:}return this.duration-=Time.deltaTime,this.duration<0},t}(),Component=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e._enabled=!0,e.updateInterval=1,e._updateOrder=0,e}return __extends(e,t),Object.defineProperty(e.prototype,"enabled",{get:function(){return this.entity?this.entity.enabled&&this._enabled:this._enabled},set:function(t){this.setEnabled(t)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"localPosition",{get:function(){return new Vector2(this.entity.x+this.x,this.entity.y+this.y)},enumerable:!0,configurable:!0}),e.prototype.setEnabled=function(t){return this._enabled!=t&&(this._enabled=t,this._enabled?this.onEnabled():this.onDisabled()),this},Object.defineProperty(e.prototype,"updateOrder",{get:function(){return this._updateOrder},set:function(t){this.setUpdateOrder(t)},enumerable:!0,configurable:!0}),e.prototype.setUpdateOrder=function(t){return this._updateOrder!=t&&(this._updateOrder=t),this},e.prototype.initialize=function(){},e.prototype.onAddedToEntity=function(){},e.prototype.onRemovedFromEntity=function(){},e.prototype.onEnabled=function(){},e.prototype.onDisabled=function(){},e.prototype.debugRender=function(){},e.prototype.update=function(){},e.prototype.onEntityTransformChanged=function(t){},e.prototype.registerComponent=function(){this.entity.componentBits.set(ComponentTypeManager.getIndexFor(this),!1),this.entity.scene.entityProcessors.onComponentAdded(this.entity)},e.prototype.deregisterComponent=function(){this.entity.componentBits.set(ComponentTypeManager.getIndexFor(this)),this.entity.scene.entityProcessors.onComponentRemoved(this.entity)},e}(egret.DisplayObjectContainer);!function(t){t[t.SceneChanged=0]="SceneChanged"}(CoreEvents||(CoreEvents={}));var TransformComponent,Entity=function(t){function e(n){var i=t.call(this)||this;return i._updateOrder=0,i._enabled=!0,i._tag=0,i.name=n,i.components=new ComponentList(i),i.id=e._idGenerator++,i.componentBits=new BitSet,i.addEventListener(egret.Event.ADDED_TO_STAGE,i.onAddToStage,i),i}return __extends(e,t),Object.defineProperty(e.prototype,"isDestoryed",{get:function(){return this._isDestoryed},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"position",{get:function(){return new Vector2(this.x,this.y)},set:function(t){this.$setX(t.x),this.$setY(t.y),this.onEntityTransformChanged(TransformComponent.position)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"scale",{get:function(){return new Vector2(this.scaleX,this.scaleY)},set:function(t){this.$setScaleX(t.x),this.$setScaleY(t.y),this.onEntityTransformChanged(TransformComponent.scale)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"rotation",{get:function(){return this.$getRotation()},set:function(t){this.$setRotation(t),this.onEntityTransformChanged(TransformComponent.rotation)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"enabled",{get:function(){return this._enabled},set:function(t){this.setEnabled(t)},enumerable:!0,configurable:!0}),e.prototype.setEnabled=function(t){return this._enabled!=t&&(this._enabled=t),this},Object.defineProperty(e.prototype,"tag",{get:function(){return this._tag},set:function(t){this.setTag(t)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"stage",{get:function(){return this.scene?this.scene.stage:null},enumerable:!0,configurable:!0}),e.prototype.onAddToStage=function(){this.onEntityTransformChanged(TransformComponent.position)},Object.defineProperty(e.prototype,"updateOrder",{get:function(){return this._updateOrder},set:function(t){this.setUpdateOrder(t)},enumerable:!0,configurable:!0}),e.prototype.roundPosition=function(){this.position=Vector2Ext.round(this.position)},e.prototype.setUpdateOrder=function(t){if(this._updateOrder!=t)return this._updateOrder=t,this.scene,this},e.prototype.setTag=function(t){return this._tag!=t&&(this.scene&&this.scene.entities.removeFromTagList(this),this._tag=t,this.scene&&this.scene.entities.addToTagList(this)),this},e.prototype.attachToScene=function(t){this.scene=t,t.entities.add(this),this.components.registerAllComponents();for(var e=0;e=0;t--){this.getChildAt(t).entity.destroy()}},e}(egret.DisplayObjectContainer);!function(t){t[t.rotation=0]="rotation",t[t.scale=1]="scale",t[t.position=2]="position"}(TransformComponent||(TransformComponent={}));var CameraStyle,Scene=function(t){function e(){var e=t.call(this)||this;return e.enablePostProcessing=!0,e._renderers=[],e._postProcessors=[],e.entityProcessors=new EntityProcessorList,e.renderableComponents=new RenderableComponentList,e.entities=new EntityList(e),e.content=new ContentManager,e.width=SceneManager.stage.stageWidth,e.height=SceneManager.stage.stageHeight,e.addEventListener(egret.Event.ACTIVATE,e.onActive,e),e.addEventListener(egret.Event.DEACTIVATE,e.onDeactive,e),e}return __extends(e,t),e.prototype.createEntity=function(t){var e=new Entity(t);return e.position=new Vector2(0,0),this.addEntity(e)},e.prototype.addEntity=function(t){this.entities.add(t),t.scene=this,this.addChild(t);for(var e=0;e=0;e--)GlobalManager.globalManagers[e].enabled&&GlobalManager.globalManagers[e].update();t.sceneTransition&&(!t.sceneTransition||t.sceneTransition.loadsNewScene&&!t.sceneTransition.isNewSceneLoaded)||t._scene.update(),t._nextScene&&(t._scene.end(),t._scene=t._nextScene,t._nextScene=null,t._instnace.onSceneChanged(),t._scene.begin())}t.render()},t.render=function(){this.sceneTransition?(this.sceneTransition.preRender(),this._scene&&!this.sceneTransition.hasPreviousSceneRender?(this._scene.render(),this._scene.postRender(),this.sceneTransition.onBeginTransition()):this.sceneTransition&&(this._scene&&this.sceneTransition.isNewSceneLoaded&&(this._scene.render(),this._scene.postRender()),this.sceneTransition.render())):this._scene&&(this._scene.render(),Debug.render(),this._scene.postRender())},t.startSceneTransition=function(t){if(!this.sceneTransition)return this.sceneTransition=t,t;console.warn("在前一个场景完成之前,不能开始一个新的场景转换。")},t.registerActiveSceneChanged=function(t,e){this.activeSceneChanged&&this.activeSceneChanged(t,e)},t.prototype.onSceneChanged=function(){t.emitter.emit(CoreEvents.SceneChanged),Time.sceneChanged()},t}(),Camera=function(t){function e(){var e=t.call(this)||this;return e._origin=Vector2.zero,e._minimumZoom=.3,e._maximumZoom=3,e._position=Vector2.zero,e.followLerp=.1,e.deadzone=new Rectangle,e.focusOffset=new Vector2,e.mapLockEnabled=!1,e.mapSize=new Vector2,e._worldSpaceDeadZone=new Rectangle,e._desiredPositionDelta=new Vector2,e.cameraStyle=CameraStyle.lockOn,e.width=SceneManager.stage.stageWidth,e.height=SceneManager.stage.stageHeight,e.setZoom(0),e}return __extends(e,t),Object.defineProperty(e.prototype,"zoom",{get:function(){return 0==this._zoom?1:this._zoom<1?MathHelper.map(this._zoom,this._minimumZoom,1,-1,0):MathHelper.map(this._zoom,1,this._maximumZoom,0,1)},set:function(t){this.setZoom(t)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"minimumZoom",{get:function(){return this._minimumZoom},set:function(t){this.setMinimumZoom(t)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"maximumZoom",{get:function(){return this._maximumZoom},set:function(t){this.setMaximumZoom(t)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"origin",{get:function(){return this._origin},set:function(t){this._origin!=t&&(this._origin=t)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"position",{get:function(){return this._position},set:function(t){this._position=t},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"x",{get:function(){return this._position.x},set:function(t){this._position.x=t},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"y",{get:function(){return this._position.y},set:function(t){this._position.y=t},enumerable:!0,configurable:!0}),e.prototype.onSceneSizeChanged=function(t,e){var n=this._origin;this.origin=new Vector2(t/2,e/2),this.entity.position=Vector2.add(this.entity.position,Vector2.subtract(this._origin,n))},e.prototype.setMinimumZoom=function(t){return this._zoomt&&(this._zoom=t),this._maximumZoom=t,this},e.prototype.setZoom=function(t){var e=MathHelper.clamp(t,-1,1);return this._zoom=0==e?1:e<0?MathHelper.map(e,-1,0,this._minimumZoom,1):MathHelper.map(e,0,1,1,this._maximumZoom),SceneManager.scene.scaleX=this._zoom,SceneManager.scene.scaleY=this._zoom,this},e.prototype.setRotation=function(t){return SceneManager.scene.rotation=t,this},e.prototype.setPosition=function(t){return this.entity.position=t,this},e.prototype.follow=function(t,e){void 0===e&&(e=CameraStyle.cameraWindow),this.targetEntity=t,this.cameraStyle=e;var n=new Rectangle(0,0,SceneManager.stage.stageWidth,SceneManager.stage.stageHeight);switch(this.cameraStyle){case CameraStyle.cameraWindow:var i=n.width/6,r=n.height/3;this.deadzone=new Rectangle((n.width-i)/2,(n.height-r)/2,i,r);break;case CameraStyle.lockOn:this.deadzone=new Rectangle(n.width/2,n.height/2,10,10)}},e.prototype.update=function(){var t=new Rectangle(0,0,SceneManager.stage.stageWidth,SceneManager.stage.stageHeight),e=Vector2.multiply(new Vector2(t.width,t.height),new Vector2(.5));this._worldSpaceDeadZone.x=this.position.x-e.x+this.deadzone.x+this.focusOffset.x,this._worldSpaceDeadZone.y=this.position.y-e.y+this.deadzone.y+this.focusOffset.y,this._worldSpaceDeadZone.width=this.deadzone.width,this._worldSpaceDeadZone.height=this.deadzone.height,this.targetEntity&&this.updateFollow(),this.position=Vector2.lerp(this.position,Vector2.add(this.position,this._desiredPositionDelta),this.followLerp),this.entity.roundPosition(),this.mapLockEnabled&&(this.position=this.clampToMapSize(this.position),this.entity.roundPosition())},e.prototype.clampToMapSize=function(t){var e=new Rectangle(0,0,SceneManager.stage.stageWidth,SceneManager.stage.stageHeight),n=Vector2.multiply(new Vector2(e.width,e.height),new Vector2(.5)),i=new Vector2(this.mapSize.x-n.x,this.mapSize.y-n.y);return Vector2.clamp(t,n,i)},e.prototype.updateFollow=function(){if(this._desiredPositionDelta.x=this._desiredPositionDelta.y=0,this.cameraStyle==CameraStyle.lockOn){var t=this.targetEntity.position.x,e=this.targetEntity.position.y;this._worldSpaceDeadZone.x>t?this._desiredPositionDelta.x=t-this._worldSpaceDeadZone.x:this._worldSpaceDeadZone.xe&&(this._desiredPositionDelta.y=e-this._worldSpaceDeadZone.y)}else{if(!this._targetCollider&&(this._targetCollider=this.targetEntity.getComponent(Collider),!this._targetCollider))return;var n=this.targetEntity.getComponent(Collider).bounds;this._worldSpaceDeadZone.containsRect(n)||(this._worldSpaceDeadZone.left>n.left?this._desiredPositionDelta.x=n.left-this._worldSpaceDeadZone.left:this._worldSpaceDeadZone.rightn.top&&(this._desiredPositionDelta.y=n.top-this._worldSpaceDeadZone.top))}},e}(Component);!function(t){t[t.lockOn=0]="lockOn",t[t.cameraWindow=1]="cameraWindow"}(CameraStyle||(CameraStyle={}));var LoopMode,State,ComponentPool=function(){function t(t){this._type=t,this._cache=[]}return t.prototype.obtain=function(){try{return this._cache.length>0?this._cache.shift():new this._type}catch(t){throw new Error(this._type+t)}},t.prototype.free=function(t){t.reset(),this._cache.push(t)},t}(),PooledComponent=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return __extends(e,t),e}(Component),RenderableComponent=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e._areBoundsDirty=!0,e._bounds=new Rectangle,e._localOffset=Vector2.zero,e.color=0,e}return __extends(e,t),Object.defineProperty(e.prototype,"width",{get:function(){return this.getWidth()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"height",{get:function(){return this.getHeight()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"isVisible",{get:function(){return this._isVisible},set:function(t){this._isVisible=t,this._isVisible?this.onBecameVisible():this.onBecameInvisible()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"bounds",{get:function(){return new Rectangle(this.getBounds().x,this.getBounds().y,this.getBounds().width,this.getBounds().height)},enumerable:!0,configurable:!0}),e.prototype.getWidth=function(){return this.bounds.width},e.prototype.getHeight=function(){return this.bounds.height},e.prototype.onBecameVisible=function(){},e.prototype.onBecameInvisible=function(){},e.prototype.isVisibleFromCamera=function(t){return this.isVisible=t.getBounds().intersects(this.getBounds()),this.isVisible},e}(PooledComponent),Mesh=function(t){function e(){var e=t.call(this)||this;return e._mesh=new egret.Mesh,e}return __extends(e,t),e.prototype.setTexture=function(t){return this._mesh.texture=t,this},e.prototype.onAddedToEntity=function(){this.addChild(this._mesh)},e.prototype.onRemovedFromEntity=function(){this.removeChild(this._mesh)},e.prototype.render=function(t){this.x=this.entity.position.x-t.position.x+t.origin.x,this.y=this.entity.position.y-t.position.y+t.origin.y},e.prototype.reset=function(){},e}(RenderableComponent),SpriteRenderer=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return __extends(e,t),Object.defineProperty(e.prototype,"sprite",{get:function(){return this._sprite},set:function(t){this.setSprite(t)},enumerable:!0,configurable:!0}),e.prototype.setSprite=function(t){return this.removeChildren(),this._sprite=t,this._sprite&&(this.anchorOffsetX=this._sprite.origin.x/this._sprite.sourceRect.width,this.anchorOffsetY=this._sprite.origin.y/this._sprite.sourceRect.height),this.bitmap=new egret.Bitmap(t.texture2D),this.addChild(this.bitmap),this},e.prototype.setColor=function(t){var e=[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0];e[0]=Math.floor(t/256/256)/255,e[6]=Math.floor(t/256%256)/255,e[12]=t%256/255;var n=new egret.ColorMatrixFilter(e);return this.filters=[n],this},e.prototype.isVisibleFromCamera=function(t){return this.isVisible=new Rectangle(0,0,this.stage.stageWidth,this.stage.stageHeight).intersects(this.bounds),this.visible=this.isVisible,this.isVisible},e.prototype.render=function(t){this.x=-t.position.x+t.origin.x,this.y=-t.position.y+t.origin.y},e.prototype.onRemovedFromEntity=function(){this.parent&&this.parent.removeChild(this)},e.prototype.reset=function(){},e}(RenderableComponent),TiledSpriteRenderer=function(t){function e(e){var n=t.call(this)||this;return n.leftTexture=new egret.Bitmap,n.rightTexture=new egret.Bitmap,n.leftTexture.texture=e.texture2D,n.rightTexture.texture=e.texture2D,n.setSprite(e),n.sourceRect=e.sourceRect,n}return __extends(e,t),Object.defineProperty(e.prototype,"scrollX",{get:function(){return this.sourceRect.x},set:function(t){this.sourceRect.x=t},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"scrollY",{get:function(){return this.sourceRect.y},set:function(t){this.sourceRect.y=t},enumerable:!0,configurable:!0}),e.prototype.render=function(e){if(this.sprite){t.prototype.render.call(this,e);var n=new egret.RenderTexture,i=new egret.DisplayObjectContainer;i.removeChildren(),i.addChild(this.leftTexture),i.addChild(this.rightTexture),this.leftTexture.x=this.sourceRect.x,this.rightTexture.x=this.sourceRect.x-this.sourceRect.width,this.leftTexture.y=this.sourceRect.y,this.rightTexture.y=this.sourceRect.y,i.cacheAsBitmap=!0,n.drawToTexture(i,new egret.Rectangle(0,0,this.sourceRect.width,this.sourceRect.height)),this.bitmap.texture=n}},e}(SpriteRenderer),ScrollingSpriteRenderer=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e.scrollSpeedX=15,e.scroolSpeedY=0,e._scrollX=0,e._scrollY=0,e}return __extends(e,t),e.prototype.update=function(){this._scrollX+=this.scrollSpeedX*Time.deltaTime,this._scrollY+=this.scroolSpeedY*Time.deltaTime,this.sourceRect.x=this._scrollX,this.sourceRect.y=this._scrollY},e.prototype.render=function(e){if(this.sprite){t.prototype.render.call(this,e);var n=new egret.RenderTexture,i=new egret.DisplayObjectContainer;i.removeChildren(),i.addChild(this.leftTexture),i.addChild(this.rightTexture),this.leftTexture.x=this.sourceRect.x,this.rightTexture.x=this.sourceRect.x-this.sourceRect.width,this.leftTexture.y=this.sourceRect.y,this.rightTexture.y=this.sourceRect.y,i.cacheAsBitmap=!0,n.drawToTexture(i,new egret.Rectangle(0,0,this.sourceRect.width,this.sourceRect.height)),this.bitmap.texture=n}},e}(TiledSpriteRenderer),Sprite=function(){return function(t,e,n){void 0===e&&(e=new Rectangle(0,0,t.textureWidth,t.textureHeight)),void 0===n&&(n=e.getHalfSize()),this.uvs=new Rectangle,this.texture2D=t,this.sourceRect=e,this.center=new Vector2(.5*e.width,.5*e.height),this.origin=n;var i=1/t.textureWidth,r=1/t.textureHeight;this.uvs.x=e.x*i,this.uvs.y=e.y*r,this.uvs.width=e.width*i,this.uvs.height=e.height*r}}(),SpriteAnimation=function(){return function(t,e){this.sprites=t,this.frameRate=e}}(),SpriteAnimator=function(t){function e(e){var n=t.call(this)||this;return n.speed=1,n.animationState=State.none,n._animations=new Map,n._elapsedTime=0,e&&n.setSprite(e),n}return __extends(e,t),Object.defineProperty(e.prototype,"isRunning",{get:function(){return this.animationState==State.running},enumerable:!0,configurable:!0}),e.prototype.addAnimation=function(t,e){return!this.sprite&&e.sprites.length>0&&this.setSprite(e.sprites[0]),this._animations[t]=e,this},e.prototype.play=function(t,e){void 0===e&&(e=null),this.currentAnimation=this._animations[t],this.currentAnimationName=t,this.currentFrame=0,this.animationState=State.running,this.sprite=this.currentAnimation.sprites[0],this._elapsedTime=0,this._loopMode=e||LoopMode.loop},e.prototype.isAnimationActive=function(t){return this.currentAnimation&&this.currentAnimationName==t},e.prototype.pause=function(){this.animationState=State.paused},e.prototype.unPause=function(){this.animationState=State.running},e.prototype.stop=function(){this.currentAnimation=null,this.currentAnimationName=null,this.currentFrame=0,this.animationState=State.none},e.prototype.update=function(){if(this.animationState==State.running&&this.currentAnimation){var t=this.currentAnimation,e=1/(t.frameRate*this.speed),n=e*t.sprites.length;this._elapsedTime+=Time.deltaTime;var i=Math.abs(this._elapsedTime);if(this._loopMode==LoopMode.once&&i>n||this._loopMode==LoopMode.pingPongOnce&&i>2*n)return this.animationState=State.completed,this._elapsedTime=0,this.currentFrame=0,void(this.sprite=t.sprites[this.currentFrame]);var r=Math.floor(i/e),o=t.sprites.length;if(o>2&&(this._loopMode==LoopMode.pingPong||this._loopMode==LoopMode.pingPongOnce)){var s=o-1;this.currentFrame=s-Math.abs(s-r%(2*s))}else this.currentFrame=r%o;this.sprite=t.sprites[this.currentFrame]}},e}(SpriteRenderer);!function(t){t[t.loop=0]="loop",t[t.once=1]="once",t[t.clampForever=2]="clampForever",t[t.pingPong=3]="pingPong",t[t.pingPongOnce=4]="pingPongOnce"}(LoopMode||(LoopMode={})),function(t){t[t.none=0]="none",t[t.running=1]="running",t[t.paused=2]="paused",t[t.completed=3]="completed"}(State||(State={}));var PointSectors,Mover=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return __extends(e,t),e.prototype.onAddedToEntity=function(){this._triggerHelper=new ColliderTriggerHelper(this.entity)},e.prototype.calculateMovement=function(t){var e=new CollisionResult;if(!this.entity.getComponent(Collider)||!this._triggerHelper)return null;for(var n=this.entity.getComponents(Collider),i=0;i>6;0!=(e&t.LONG_MASK)&&n++,this._bits=new Array(n)}return t.prototype.and=function(t){for(var e,n=Math.min(this._bits.length,t._bits.length),i=0;i=0;)this._bits[e]&=~t._bits[e]},t.prototype.cardinality=function(){for(var t=0,e=this._bits.length-1;e>=0;e--){var n=this._bits[e];if(0!=n)if(-1!=n){var i=((n=((n=(n>>1&0x5555555555555400)+(0x5555555555555400&n))>>2&0x3333333333333400)+(0x3333333333333400&n))>>32)+n;t+=((i=((i=(i>>4&252645135)+(252645135&i))>>8&16711935)+(16711935&i))>>16&65535)+(65535&i)}else t+=64}return t},t.prototype.clear=function(t){if(null!=t){var e=t>>6;this.ensure(e),this._bits[e]&=~(1<=this._bits.length){var e=new Number[t+1];e=this._bits.copyWithin(0,0,this._bits.length),this._bits=e}},t.prototype.get=function(t){var e=t>>6;return!(e>=this._bits.length)&&0!=(this._bits[e]&1<=0;)if(0!=(this._bits[e]&t._bits[e]))return!0;return!1},t.prototype.isEmpty=function(){for(var t=this._bits.length-1;t>=0;t--)if(this._bits[t])return!1;return!0},t.prototype.nextSetBit=function(t){for(var e=t>>6,n=1<>6;this.ensure(n),this._bits[n]|=1<0){for(var t=0;t0){t=0;for(var e=this._componentsToAdd.length;t0){var e=this._entitiesToRemove;this._entitiesToRemove=this._tempEntityList,this._tempEntityList=e,this._tempEntityList.forEach(function(e){t._entities.remove(e),e.scene=null,t.scene.entityProcessors.onEntityRemoved(e)}),this._tempEntityList.length=0}if(this._entitiesToAdded.length>0){e=this._entitiesToAdded;this._entitiesToAdded=this._tempEntityList,this._tempEntityList=e,this._tempEntityList.forEach(function(e){t._entities.contains(e)||(t._entities.push(e),e.scene=t.scene,t.scene.entityProcessors.onEntityAdded(e))}),this._tempEntityList.forEach(function(t){return t.onAddedToScene()}),this._tempEntityList.length=0}this._unsortedTags.length>0&&(this._unsortedTags.forEach(function(e){t._entityDict.get(e).sort()}),this._unsortedTags.length=0)},t}(),EntityProcessorList=function(){function t(){this._processors=[]}return t.prototype.add=function(t){this._processors.push(t)},t.prototype.remove=function(t){this._processors.remove(t)},t.prototype.onComponentAdded=function(t){this.notifyEntityChanged(t)},t.prototype.onComponentRemoved=function(t){this.notifyEntityChanged(t)},t.prototype.onEntityAdded=function(t){this.notifyEntityChanged(t)},t.prototype.onEntityRemoved=function(t){this.removeFromProcessors(t)},t.prototype.notifyEntityChanged=function(t){for(var e=0;e=0;e=this.allSet.nextSetBit(e+1))if(!t.componentBits.get(e))return!1;return!(!this.exclusionSet.isEmpty()&&this.exclusionSet.intersects(t.componentBits))&&!(!this.oneSet.isEmpty()&&!this.oneSet.intersects(t.componentBits))},t.prototype.all=function(){for(var t=this,e=[],n=0;n=e)return t;var i=!1;"-"==t.substr(0,1)&&(i=!0,t=t.substr(1));for(var r=e-n,o=0;o1?this.reverse(t.substring(1))+t.substring(0,1):t},t.cutOff=function(t,e,n,i){void 0===i&&(i=!0),e=Math.floor(e),n=Math.floor(n);var r=t.length;e>r&&(e=r);var o,s=e,a=e+n;return i?o=t.substring(0,s)+t.substr(a,r):(a=(s=r-1-e-n)+n,o=t.substring(0,s+1)+t.substr(a+1,r)),o},t.strReplace=function(t,e){for(var n=0,i=e.length;n",">",'"',""","'","'","®","®","©","©","™","™"],t}(),TextureUtils=function(){function t(){}return t.convertImageToCanvas=function(t,e){this.sharedCanvas||(this.sharedCanvas=egret.sys.createCanvas(),this.sharedContext=this.sharedCanvas.getContext("2d"));var n=t.$getTextureWidth(),i=t.$getTextureHeight();e||((e=egret.$TempRectangle).x=0,e.y=0,e.width=n,e.height=i),e.x=Math.min(e.x,n-1),e.y=Math.min(e.y,i-1),e.width=Math.min(e.width,n-e.x),e.height=Math.min(e.height,i-e.y);var r=Math.floor(e.width),o=Math.floor(e.height),s=this.sharedCanvas;if(s.style.width=r+"px",s.style.height=o+"px",this.sharedCanvas.width=r,this.sharedCanvas.height=o,"webgl"==egret.Capabilities.renderMode){var a=void 0;t.$renderBuffer?a=t:(egret.sys.systemRenderer.renderClear&&egret.sys.systemRenderer.renderClear(),(a=new egret.RenderTexture).drawToTexture(new egret.Bitmap(t)));for(var c=a.$renderBuffer.getPixels(e.x,e.y,r,o),h=0,u=0,l=0;l=0?"png":"jpg"});return wx.getFileSystemManager().saveFile({tempFilePath:o,filePath:wx.env.USER_DATA_PATH+"/"+n,success:function(t){}}),o},t.getPixel32=function(t,e,n){return egret.$warn(1041,"getPixel32","getPixels"),t.getPixels(e,n)},t.getPixels=function(t,e,n,i,r){if(void 0===i&&(i=1),void 0===r&&(r=1),"webgl"==egret.Capabilities.renderMode){var o=void 0;return t.$renderBuffer?o=t:(o=new egret.RenderTexture).drawToTexture(new egret.Bitmap(t)),o.$renderBuffer.getPixels(e,n,i,r)}try{this.convertImageToCanvas(t);return this.sharedContext.getImageData(e,n,i,r).data}catch(t){egret.$error(1039)}},t}(),Time=function(){function t(){}return t.update=function(t){var e=(t-this._lastTime)/1e3;this.deltaTime=e*this.timeScale,this.unscaledDeltaTime=e,this._timeSinceSceneLoad+=e,this.frameCount++,this._lastTime=t},t.sceneChanged=function(){this._timeSinceSceneLoad=0},t.checkEvery=function(t){return this._timeSinceSceneLoad/t>(this._timeSinceSceneLoad-this.deltaTime)/t},t.deltaTime=0,t.timeScale=1,t.frameCount=0,t._lastTime=0,t}(),TimeUtils=function(){function t(){}return t.monthId=function(t){void 0===t&&(t=null);var e=(t=t||new Date).getFullYear(),n=t.getMonth()+1;return parseInt(e+(n<10?"0":"")+n)},t.dateId=function(t){void 0===t&&(t=null);var e=(t=t||new Date).getMonth()+1,n=e<10?"0":"",i=t.getDate(),r=i<10?"0":"";return parseInt(t.getFullYear()+n+e+r+i)},t.weekId=function(t,e){void 0===t&&(t=null),void 0===e&&(e=!0),t=t||new Date;var n=new Date;n.setTime(t.getTime()),n.setDate(1),n.setMonth(0);var i=n.getFullYear(),r=n.getDay();0==r&&(r=7);var o=!1;r<=4?(o=r>1,n.setDate(n.getDate()-(r-1))):n.setDate(n.getDate()+7-r+1);var s=this.diffDay(t,n,!1);if(s<0)return n.setDate(1),n.setMonth(0),n.setDate(n.getDate()-1),this.weekId(n,!1);var a=s/7,c=Math.floor(a)+1;if(53==c){n.setTime(t.getTime()),n.setDate(n.getDate()-1);var h=n.getDay();if(0==h&&(h=7),e&&(!o||h<4))return n.setFullYear(n.getFullYear()+1),n.setDate(1),n.setMonth(0),this.weekId(n,!1)}return parseInt(i+"00"+(c>9?"":"0")+c)},t.diffDay=function(t,e,n){void 0===n&&(n=!1);var i=(t.getTime()-e.getTime())/864e5;return n?Math.ceil(i):Math.floor(i)},t.getFirstDayOfWeek=function(t){var e=(t=t||new Date).getDay()||7;return new Date(t.getFullYear(),t.getMonth(),t.getDate()+1-e,0,0,0,0)},t.getFirstOfDay=function(t){return(t=t||new Date).setHours(0,0,0,0),t},t.getNextFirstOfDay=function(t){return new Date(this.getFirstOfDay(t).getTime()+864e5)},t.formatDate=function(t){var e=t.getFullYear(),n=t.getMonth()+1;n=n<10?"0"+n:n;var i=t.getDate();return e+"-"+n+"-"+(i=i<10?"0"+i:i)},t.formatDateTime=function(t){var e=t.getFullYear(),n=t.getMonth()+1;n=n<10?"0"+n:n;var i=t.getDate();i=i<10?"0"+i:i;var r=t.getHours(),o=t.getMinutes();o=o<10?"0"+o:o;var s=t.getSeconds();return e+"-"+n+"-"+i+" "+r+":"+o+":"+(s=s<10?"0"+s:s)},t.parseDate=function(t){var e=Date.parse(t);return isNaN(e)?new Date:new Date(Date.parse(t.replace(/-/g,"/")))},t.secondToTime=function(t,e,n){void 0===t&&(t=0),void 0===e&&(e=":"),void 0===n&&(n=!0);var i=Math.floor(t/3600),r=Math.floor(t%3600/60),o=Math.floor(t%3600%60),s=i.toString(),a=r.toString(),c=o.toString();return i<10&&(s="0"+s),r<10&&(a="0"+a),o<10&&(c="0"+c),n?s+e+a+e+c:a+e+c},t.timeToMillisecond=function(t,e){void 0===e&&(e=":");for(var n=t.split(e),i=0,r=n.length,o=0;o-1?this.os="iOS":n.indexOf("android")>-1&&(this.os="Android");var i=e.language;i=i.indexOf("zh")>-1?"zh-CN":"en-US",this.language=i},e}(egret.Capabilities),GraphicsDevice=function(){return function(){this.graphicsCapabilities=new GraphicsCapabilities,this.graphicsCapabilities.initialize(this)}}(),Viewport=function(){function t(t,e,n,i){this._x=t,this._y=e,this._width=n,this._height=i,this._minDepth=0,this._maxDepth=1}return Object.defineProperty(t.prototype,"aspectRatio",{get:function(){return 0!=this._height&&0!=this._width?this._width/this._height:0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"bounds",{get:function(){return new Rectangle(this._x,this._y,this._width,this._height)},set:function(t){this._x=t.x,this._y=t.y,this._width=t.width,this._height=t.height},enumerable:!0,configurable:!0}),t}(),GaussianBlurEffect=function(t){function e(){return t.call(this,PostProcessor.default_vert,e.blur_frag,{screenWidth:SceneManager.stage.stageWidth,screenHeight:SceneManager.stage.stageHeight})||this}return __extends(e,t),e.blur_frag="precision mediump float;\nuniform sampler2D uSampler;\nuniform float screenWidth;\nuniform float screenHeight;\nfloat normpdf(in float x, in float sigma)\n{\nreturn 0.39894*exp(-0.5*x*x/(sigma*sigma))/sigma;\n}\nvoid main()\n{\nvec3 c = texture2D(uSampler, gl_FragCoord.xy / vec2(screenWidth, screenHeight).xy).rgb;\nconst int mSize = 11;\nconst int kSize = (mSize - 1)/2;\nfloat kernel[mSize];\nvec3 final_colour = vec3(0.0);\nfloat sigma = 7.0;\nfloat z = 0.0;\nfor (int j = 0; j <= kSize; ++j)\n{\nkernel[kSize+j] = kernel[kSize-j] = normpdf(float(j),sigma);\n}\nfor (int j = 0; j < mSize; ++j)\n{\nz += kernel[j];\n}\nfor (int i = -kSize; i <= kSize; ++i)\n{\nfor (int j = -kSize; j <= kSize; ++j)\n{\nfinal_colour += kernel[kSize+j]*kernel[kSize+i]*texture2D(uSampler, (gl_FragCoord.xy+vec2(float(i),float(j))) / vec2(screenWidth, screenHeight).xy).rgb;\n}\n}\ngl_FragColor = vec4(final_colour/(z*z), 1.0);\n}",e}(egret.CustomFilter),PolygonLightEffect=function(t){function e(){return t.call(this,e.vertSrc,e.fragmentSrc)||this}return __extends(e,t),e.vertSrc="attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\nuniform vec2 projectionVector;\nvarying vec2 vTextureCoord;\nconst vec2 center = vec2(-1.0, 1.0);\nvoid main(void) {\n gl_Position = vec4( (aVertexPosition / projectionVector) + center , 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}",e.fragmentSrc="precision lowp float;\nvarying vec2 vTextureCoord;\nuniform sampler2D uSampler;\n#define SAMPLE_COUNT 15\nuniform vec2 _sampleOffsets[SAMPLE_COUNT];\nuniform float _sampleWeights[SAMPLE_COUNT];\nvoid main(void) {\nvec4 c = vec4(0, 0, 0, 0);\nfor( int i = 0; i < SAMPLE_COUNT; i++ )\n c += texture2D( uSampler, vTextureCoord + _sampleOffsets[i] ) * _sampleWeights[i];\ngl_FragColor = c;\n}",e}(egret.CustomFilter),PostProcessor=function(){function t(t){void 0===t&&(t=null),this.enable=!0,this.effect=t}return t.prototype.onAddedToScene=function(t){this.scene=t,this.shape=new egret.Shape,this.shape.graphics.beginFill(16777215,1),this.shape.graphics.drawRect(0,0,SceneManager.stage.stageWidth,SceneManager.stage.stageHeight),this.shape.graphics.endFill(),t.addChild(this.shape)},t.prototype.process=function(){this.drawFullscreenQuad()},t.prototype.onSceneBackBufferSizeChanged=function(t,e){},t.prototype.drawFullscreenQuad=function(){this.scene.filters=[this.effect]},t.prototype.unload=function(){this.effect&&(this.effect=null),this.scene.removeChild(this.shape),this.scene=null},t.default_vert="attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\nattribute vec2 aColor;\nuniform vec2 projectionVector;\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\nconst vec2 center = vec2(-1.0, 1.0);\nvoid main(void) {\ngl_Position = vec4( (aVertexPosition / projectionVector) + center , 0.0, 1.0);\nvTextureCoord = aTextureCoord;\nvColor = vec4(aColor.x, aColor.x, aColor.x, aColor.x);\n}",t}(),GaussianBlurPostProcessor=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return __extends(e,t),e.prototype.onAddedToScene=function(e){t.prototype.onAddedToScene.call(this,e),this.effect=new GaussianBlurEffect},e}(PostProcessor),Renderer=function(){function t(){}return t.prototype.onAddedToScene=function(t){},t.prototype.beginRender=function(t){},t.prototype.unload=function(){},t.prototype.renderAfterStateCheck=function(t,e){t.render(e)},t}(),DefaultRenderer=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return __extends(e,t),e.prototype.render=function(t){var e=this.camera?this.camera:t.camera;this.beginRender(e);for(var n=0;nn?n:t},t.pointOnCirlce=function(e,n,i){var r=t.toRadians(i);return new Vector2(Math.cos(r)*r+e.x,Math.sin(r)*r+e.y)},t.isEven=function(t){return t%2==0},t.clamp01=function(t){return t<0?0:t>1?1:t},t.angleBetweenVectors=function(t,e){return Math.atan2(e.y-t.y,e.x-t.x)},t.Epsilon=1e-5,t.Rad2Deg=57.29578,t.Deg2Rad=.0174532924,t}(),Matrix2D=function(){function t(t,e,n,i,r,o){this.m11=0,this.m12=0,this.m21=0,this.m22=0,this.m31=0,this.m32=0,this.m11=t||1,this.m12=e||0,this.m21=n||0,this.m22=i||1,this.m31=r||0,this.m32=o||0}return Object.defineProperty(t,"identity",{get:function(){return t._identity},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"translation",{get:function(){return new Vector2(this.m31,this.m32)},set:function(t){this.m31=t.x,this.m32=t.y},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"rotation",{get:function(){return Math.atan2(this.m21,this.m11)},set:function(t){var e=Math.cos(t),n=Math.sin(t);this.m11=e,this.m12=n,this.m21=-n,this.m22=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"rotationDegrees",{get:function(){return MathHelper.toDegrees(this.rotation)},set:function(t){this.rotation=MathHelper.toRadians(t)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"scale",{get:function(){return new Vector2(this.m11,this.m22)},set:function(t){this.m11=t.x,this.m12=t.y},enumerable:!0,configurable:!0}),t.add=function(t,e){return t.m11+=e.m11,t.m12+=e.m12,t.m21+=e.m21,t.m22+=e.m22,t.m31+=e.m31,t.m32+=e.m32,t},t.divide=function(t,e){return t.m11/=e.m11,t.m12/=e.m12,t.m21/=e.m21,t.m22/=e.m22,t.m31/=e.m31,t.m32/=e.m32,t},t.multiply=function(e,n){var i=new t,r=e.m11*n.m11+e.m12*n.m21,o=e.m11*n.m12+e.m12*n.m22,s=e.m21*n.m11+e.m22*n.m21,a=e.m21*n.m12+e.m22*n.m22,c=e.m31*n.m11+e.m32*n.m21+n.m31,h=e.m31*n.m12+e.m32*n.m22+n.m32;return i.m11=r,i.m12=o,i.m21=s,i.m22=a,i.m31=c,i.m32=h,i},t.multiplyTranslation=function(e,n,i){var r=t.createTranslation(n,i);return t.multiply(e,r)},t.prototype.determinant=function(){return this.m11*this.m22-this.m12*this.m21},t.invert=function(e,n){void 0===n&&(n=new t);var i=1/e.determinant();return n.m11=e.m22*i,n.m12=-e.m12*i,n.m21=-e.m21*i,n.m22=e.m11*i,n.m31=(e.m32*e.m21-e.m31*e.m22)*i,n.m32=-(e.m32*e.m11-e.m31*e.m12)*i,n},t.createTranslation=function(e,n){var i=new t;return i.m11=1,i.m12=0,i.m21=0,i.m22=1,i.m31=e,i.m32=n,i},t.createTranslationVector=function(t){return this.createTranslation(t.x,t.y)},t.createRotation=function(e,n){n=new t;var i=Math.cos(e),r=Math.sin(e);return n.m11=i,n.m12=r,n.m21=-r,n.m22=i,n},t.createScale=function(e,n,i){return void 0===i&&(i=new t),i.m11=e,i.m12=0,i.m21=0,i.m22=n,i.m31=0,i.m32=0,i},t.prototype.toEgretMatrix=function(){return new egret.Matrix(this.m11,this.m12,this.m21,this.m22,this.m31,this.m32)},t._identity=new t(1,0,0,1,0,0),t}(),Rectangle=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return __extends(e,t),Object.defineProperty(e.prototype,"max",{get:function(){return new Vector2(this.right,this.bottom)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"center",{get:function(){return new Vector2(this.x+this.width/2,this.y+this.height/2)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"location",{get:function(){return new Vector2(this.x,this.y)},set:function(t){this.x=t.x,this.y=t.y},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"size",{get:function(){return new Vector2(this.width,this.height)},set:function(t){this.width=t.x,this.height=t.y},enumerable:!0,configurable:!0}),e.prototype.intersects=function(t){return t.lefti&&(i=s.x),s.yr&&(r=s.y)}return this.fromMinMax(e,n,i,r)},e}(egret.Rectangle),Vector3=function(){return function(t,e,n){this.x=t,this.y=e,this.z=n}}(),ColliderTriggerHelper=function(){function t(t){this._activeTriggerIntersections=[],this._previousTriggerIntersections=[],this._tempTriggerList=[],this._entity=t}return t.prototype.update=function(){for(var t=this._entity.getComponents(Collider),e=0;e1)return!1;var h=(a.x*r.y-a.y*r.x)/s;return!(h<0||h>1)},t.lineToLineIntersection=function(t,e,n,i){var r=new Vector2(0,0),o=Vector2.subtract(e,t),s=Vector2.subtract(i,n),a=o.x*s.y-o.y*s.x;if(0==a)return r;var c=Vector2.subtract(n,t),h=(c.x*s.y-c.y*s.x)/a;if(h<0||h>1)return r;var u=(c.x*o.y-c.y*o.x)/a;return u<0||u>1?r:r=Vector2.add(t,new Vector2(h*o.x,h*o.y))},t.closestPointOnLine=function(t,e,n){var i=Vector2.subtract(e,t),r=Vector2.subtract(n,t),o=Vector2.dot(r,i)/Vector2.dot(i,i);return o=MathHelper.clamp(o,0,1),Vector2.add(t,new Vector2(i.x*o,i.y*o))},t.isCircleToCircle=function(t,e,n,i){return Vector2.distanceSquared(t,n)<(e+i)*(e+i)},t.isCircleToLine=function(t,e,n,i){return Vector2.distanceSquared(t,this.closestPointOnLine(n,i,t))=t&&r.y>=e&&r.x=t+n&&(o|=PointSectors.right),r.y=e+i&&(o|=PointSectors.bottom),o},t}(),Physics=function(){function t(){}return t.reset=function(){this._spatialHash=new SpatialHash(this.spatialHashCellSize)},t.clear=function(){this._spatialHash.clear()},t.overlapCircleAll=function(t,e,n,i){return void 0===i&&(i=-1),this._spatialHash.overlapCircle(t,e,n,i)},t.boxcastBroadphase=function(t,e){void 0===e&&(e=this.allLayers);var n=this._spatialHash.aabbBroadphase(t,null,e);return{colliders:n.tempHashSet,rect:n.bounds}},t.boxcastBroadphaseExcludingSelf=function(t,e,n){return void 0===n&&(n=this.allLayers),this._spatialHash.aabbBroadphase(e,t,n)},t.addCollider=function(e){t._spatialHash.register(e)},t.removeCollider=function(e){t._spatialHash.remove(e)},t.updateCollider=function(t){this._spatialHash.remove(t),this._spatialHash.register(t)},t.debugDraw=function(t){this._spatialHash.debugDraw(t,2)},t.spatialHashCellSize=100,t.allLayers=-1,t}(),Shape=function(){return function(){this.bounds=new Rectangle,this.position=Vector2.zero}}(),Polygon=function(t){function e(e,n){var i=t.call(this)||this;return i.isUnrotated=!0,i._areEdgeNormalsDirty=!0,i.center=new Vector2,i.setPoints(e),i.isBox=n,i}return __extends(e,t),Object.defineProperty(e.prototype,"edgeNormals",{get:function(){return this._areEdgeNormalsDirty&&this.buildEdgeNormals(),this._edgeNormals},enumerable:!0,configurable:!0}),e.prototype.buildEdgeNormals=function(){var t,e=this.isBox?2:this.points.length;null!=this._edgeNormals&&this._edgeNormals.length==e||(this._edgeNormals=new Array(e));for(var n=0;n=this.points.length?this.points[0]:this.points[n+1];var r=Vector2Ext.perpendicular(i,t);r=Vector2.normalize(r),this._edgeNormals[n]=r}},e.prototype.setPoints=function(t){this.points=t,this.recalculateCenterAndEdgeNormals(),this._originalPoints=[];for(var e=0;et.y!=this.points[i].y>t.y&&t.x<(this.points[i].x-this.points[n].x)*(t.y-this.points[n].y)/(this.points[i].y-this.points[n].y)+this.points[n].x&&(e=!e);return e},e.buildSymmertricalPolygon=function(t,e){for(var n=new Array(t),i=0;i0&&(r=!1),!r)return null;(g=Math.abs(g))i&&(i=r);return{min:n,max:i}},t.circleToPolygon=function(t,e){var n=new CollisionResult,i=Vector2.subtract(t.position,e.position),r=Polygon.getClosestPointOnPolygonToPoint(e.points,i),o=r.closestPoint,s=r.distanceSquared;n.normal=r.edgeNormal;var a,c=e.containsPoint(t.position);if(s>t.radius*t.radius&&!c)return null;if(c)a=Vector2.multiply(n.normal,new Vector2(Math.sqrt(s)-t.radius));else if(0==s)a=Vector2.multiply(n.normal,new Vector2(t.radius));else{var h=Math.sqrt(s);a=Vector2.multiply(new Vector2(-Vector2.subtract(i,o)),new Vector2((t.radius-s)/h))}return n.minimumTranslationVector=a,n.point=Vector2.add(o,e.position),n},t.circleToBox=function(t,e){var n=new CollisionResult,i=e.bounds.getClosestPointOnRectangleBorderToPoint(t.position).res;if(e.containsPoint(t.position)){n.point=i;var r=Vector2.add(i,Vector2.subtract(n.normal,new Vector2(t.radius)));return n.minimumTranslationVector=Vector2.subtract(t.position,r),n}var o=Vector2.distanceSquared(i,t.position);if(0==o)n.minimumTranslationVector=Vector2.multiply(n.normal,new Vector2(t.radius));else if(o<=t.radius*t.radius){n.normal=Vector2.subtract(t.position,i);var s=n.normal.length()-t.radius;return n.normal=Vector2Ext.normalize(n.normal),n.minimumTranslationVector=Vector2.multiply(new Vector2(s),n.normal),n}return null},t.pointToCircle=function(t,e){var n=new CollisionResult,i=Vector2.distanceSquared(t,e.position),r=1+e.radius;if(i0&&this.debugDrawCellDetails(n,i,r.length,t,e)}},t.prototype.debugDrawCellDetails=function(t,e,n,i,r){void 0===i&&(i=.5),void 0===r&&(r=1)},t}(),RaycastResultParser=function(){return function(){}}(),NumberDictionary=function(){function t(){this._store=new Map}return t.prototype.getKey=function(t,e){return Long.fromNumber(t).shiftLeft(32).or(this.intToUint(e)).toString()},t.prototype.intToUint=function(t){return t>=0?t:4294967296+t},t.prototype.add=function(t,e,n){this._store.set(this.getKey(t,e),n)},t.prototype.remove=function(t){this._store.forEach(function(e){e.contains(t)&&e.remove(t)})},t.prototype.tryGetValue=function(t,e){return this._store.get(this.getKey(t,e))},t.prototype.clear=function(){this._store.clear()},t}(),ArrayUtils=function(){function t(){}return t.bubbleSort=function(t){for(var e=!1,n=0;nn;i--)if(t[i]0&&t[r-1]>i;r--)t[r]=t[r-1];t[r]=i}},t.binarySearch=function(t,e){for(var n=0,i=t.length,r=n+i>>1;n=t[r]&&(n=r+1),r=n+i>>1;return t[n]==e?n:-1},t.findElementIndex=function(t,e){for(var n=t.length,i=0;it[e]&&(e=i);return e},t.getMinElementIndex=function(t){for(var e=0,n=t.length,i=1;i=0;--r)n.unshift(e[r]);return n},t.getDifferAry=function(t,e){t=this.getUniqueAry(t),e=this.getUniqueAry(e);for(var n=t.concat(e),i=new Object,r=[],o=n.length,s=0;s=0;e-=1)t.splice(e,1)},t.cloneList=function(t){return t?t.slice(0,t.length):null},t.equals=function(t,e){if(t==e)return!0;var n=t.length;if(n!=e.length)return!1;for(;n--;)if(t[n]!=e[n])return!1;return!0},t.insert=function(t,e,n){if(!t)return null;var i=t.length;if(e>i&&(e=i),e<0&&(e=0),e==i)t.push(n);else if(0==e)t.unshift(n);else{for(var r=i-1;r>=e;r-=1)t[r+1]=t[r];t[e]=n}return n},t}(),ContentManager=function(){function t(){this.loadedAssets=new Map}return t.prototype.loadRes=function(t,e){var n=this;return void 0===e&&(e=!0),new Promise(function(i,r){var o=n.loadedAssets.get(t);o?i(o):e?RES.getResAsync(t).then(function(e){n.loadedAssets.set(t,e),i(e)}).catch(function(e){console.error("资源加载错误:",t,e),r(e)}):RES.getResByUrl(t).then(function(e){n.loadedAssets.set(t,e),i(e)}).catch(function(e){console.error("资源加载错误:",t,e),r(e)})})},t.prototype.dispose=function(){this.loadedAssets.forEach(function(t){t.dispose()}),this.loadedAssets.clear()},t}(),DrawUtils=function(){function t(){}return t.drawLine=function(t,e,n,i,r){void 0===r&&(r=1),this.drawLineAngle(t,e,MathHelper.angleBetweenVectors(e,n),Vector2.distance(e,n),i,r)},t.drawLineAngle=function(t,e,n,i,r,o){void 0===o&&(o=1),t.graphics.beginFill(r),t.graphics.drawRect(e.x,e.y,1,1),t.graphics.endFill(),t.scaleX=i,t.scaleY=o,t.$anchorOffsetX=0,t.$anchorOffsetY=0,t.rotation=n},t.drawHollowRect=function(t,e,n,i){void 0===i&&(i=1),this.drawHollowRectR(t,e.x,e.y,e.width,e.height,n,i)},t.drawHollowRectR=function(t,e,n,i,r,o,s){void 0===s&&(s=1);var a=new Vector2(e,n).round(),c=new Vector2(e+i,n).round(),h=new Vector2(e+i,n+r).round(),u=new Vector2(e,n+r).round();this.drawLine(t,a,c,o,s),this.drawLine(t,c,h,o,s),this.drawLine(t,h,u,o,s),this.drawLine(t,u,a,o,s)},t.drawPixel=function(t,e,n,i){void 0===i&&(i=1);var r=new Rectangle(e.x,e.y,i,i);1!=i&&(r.x-=.5*i,r.y-=.5*i),t.graphics.beginFill(n),t.graphics.drawRect(r.x,r.y,r.width,r.height),t.graphics.endFill()},t}(),Emitter=function(){function t(){this._messageTable=new Map}return t.prototype.addObserver=function(t,e,n){var i=this._messageTable.get(t);i||(i=[],this._messageTable.set(t,i)),i.contains(e)&&console.warn("您试图添加相同的观察者两次"),i.push(new FuncPack(e,n))},t.prototype.removeObserver=function(t,e){var n=this._messageTable.get(t),i=n.findIndex(function(t){return t.func==e});-1!=i&&n.removeAt(i)},t.prototype.emit=function(t,e){var n=this._messageTable.get(t);if(n)for(var i=n.length-1;i>=0;i--)n[i].func.call(n[i].context,e)},t}(),FuncPack=function(){return function(t,e){this.func=t,this.context=e}}(),GlobalManager=function(){function t(){}return Object.defineProperty(t.prototype,"enabled",{get:function(){return this._enabled},set:function(t){this.setEnabled(t)},enumerable:!0,configurable:!0}),t.prototype.setEnabled=function(t){this._enabled!=t&&(this._enabled=t,this._enabled?this.onEnabled():this.onDisabled())},t.prototype.onEnabled=function(){},t.prototype.onDisabled=function(){},t.prototype.update=function(){},t.registerGlobalManager=function(t){this.globalManagers.push(t),t.enabled=!0},t.unregisterGlobalManager=function(t){this.globalManagers.remove(t),t.enabled=!1},t.getGlobalManager=function(t){for(var e=0;e0&&this.setpreviousTouchState(this._gameTouchs[0]),t},enumerable:!0,configurable:!0}),t.initialize=function(t){this._init||(this._init=!0,this._stage=t,this._stage.addEventListener(egret.TouchEvent.TOUCH_BEGIN,this.touchBegin,this),this._stage.addEventListener(egret.TouchEvent.TOUCH_MOVE,this.touchMove,this),this._stage.addEventListener(egret.TouchEvent.TOUCH_END,this.touchEnd,this),this._stage.addEventListener(egret.TouchEvent.TOUCH_CANCEL,this.touchEnd,this),this._stage.addEventListener(egret.TouchEvent.TOUCH_RELEASE_OUTSIDE,this.touchEnd,this),this.initTouchCache())},t.initTouchCache=function(){this._totalTouchCount=0,this._touchIndex=0,this._gameTouchs.length=0;for(var t=0;t0)for(var e=0;ethis._objectQueue.length;)this._objectQueue.shift()},t.clearCache=function(){this._objectQueue.length=0},t.obtain=function(){return this._objectQueue.length>0?this._objectQueue.shift():[]},t.free=function(t){this._objectQueue.unshift(t),t.length=0},t._objectQueue=[],t}(),THREAD_ID=Math.floor(1e3*Math.random())+"-"+Date.now(),setItem=egret.localStorage.setItem.bind(localStorage),getItem=egret.localStorage.getItem.bind(localStorage),removeItem=egret.localStorage.removeItem.bind(localStorage),nextTick=function(t){setTimeout(t,0)},LockUtils=function(){function t(t){this._keyX="mutex_key_"+t+"_X",this._keyY="mutex_key_"+t+"_Y"}return t.prototype.lock=function(){var t=this;return new Promise(function(e,n){var i=function(){setItem(t._keyX,THREAD_ID),null===!getItem(t._keyY)&&nextTick(i),setItem(t._keyY,THREAD_ID),getItem(t._keyX)!==THREAD_ID?setTimeout(function(){getItem(t._keyY)===THREAD_ID?(e(),removeItem(t._keyY)):nextTick(i)},10):(e(),removeItem(t._keyY))};i()})},t}(),Pair=function(){function t(t,e){this.first=t,this.second=e}return t.prototype.clear=function(){this.first=this.second=null},t.prototype.equals=function(t){return this.first==t.first&&this.second==t.second},t}(),RandomUtils=function(){function t(){}return t.randrange=function(t,e,n){if(void 0===n&&(n=1),0==n)throw new Error("step 不能为 0");var i=e-t;if(0==i)throw new Error("没有可用的范围("+t+","+e+")");i<0&&(i=t-e);var r=Math.floor((i+n-1)/n);return Math.floor(this.random()*r)*n+Math.min(t,e)},t.randint=function(t,e){return(t=Math.floor(t))>(e=Math.floor(e))?t++:e++,this.randrange(t,e)},t.randnum=function(t,e){return this.random()*(e-t)+t},t.shuffle=function(t){return t.sort(this._randomCompare),t},t._randomCompare=function(t,e){return this.random()>.5?1:-1},t.choice=function(t){if(!t.hasOwnProperty("length"))throw new Error("无法对此对象执行此操作");var e=Math.floor(this.random()*t.length);return t instanceof String?String(t).charAt(e):t[e]},t.sample=function(t,e){var n=t.length;if(e<=0||n=0;)s=Math.floor(this.random()*n);i.push(t[s]),r.push(s)}return i},t.random=function(){return Math.random()},t.boolean=function(t){return void 0===t&&(t=.5),this.random()3&&r<500;){r++;var s=!0,a=e[this._triPrev[o]],c=e[o],h=e[this._triNext[o]];if(Vector2Ext.isTriangleCCW(a,c,h)){var u=this._triNext[this._triNext[o]];do{if(t.testPointTriangle(e[u],a,c,h)){s=!1;break}u=this._triNext[u]}while(u!=this._triPrev[o])}else s=!1;s?(this.triangleIndices.push(this._triPrev[o]),this.triangleIndices.push(o),this.triangleIndices.push(this._triNext[o]),this._triNext[this._triPrev[o]]=this._triNext[o],this._triPrev[this._triNext[o]]=this._triPrev[o],i--,o=this._triPrev[o]):o=this._triNext[o]}this.triangleIndices.push(this._triPrev[o]),this.triangleIndices.push(o),this.triangleIndices.push(this._triNext[o]),n||this.triangleIndices.reverse()},t.prototype.initialize=function(t){this.triangleIndices.length=0,this._triNext.lengthMathHelper.Epsilon?t=Vector2.divide(t,new Vector2(e)):t.x=t.y=0,t},t.transformA=function(t,e,n,i,r,o){for(var s=0;sthis.safeArea.right&&(r.x=this.safeArea.right-r.width),r.topthis.safeArea.bottom&&(r.y=this.safeArea.bottom-r.height),r},t}();!function(t){t[t.none=0]="none",t[t.left=1]="left",t[t.right=2]="right",t[t.horizontalCenter=4]="horizontalCenter",t[t.top=8]="top",t[t.bottom=16]="bottom",t[t.verticalCenter=32]="verticalCenter",t[t.topLeft=9]="topLeft",t[t.topRight=10]="topRight",t[t.topCenter=12]="topCenter",t[t.bottomLeft=17]="bottomLeft",t[t.bottomRight=18]="bottomRight",t[t.bottomCenter=20]="bottomCenter",t[t.centerLeft=33]="centerLeft",t[t.centerRight=34]="centerRight",t[t.center=36]="center"}(Alignment||(Alignment={})),function(t){var e,n=function(){function t(t){void 0===t&&(t=i),this.getSystemTime=t,this._stopDuration=0,this._completeSlices=[]}return t.prototype.getState=function(){return void 0===this._startSystemTime?e.IDLE:void 0===this._stopSystemTime?e.RUNNING:e.STOPPED},t.prototype.isIdle=function(){return this.getState()===e.IDLE},t.prototype.isRunning=function(){return this.getState()===e.RUNNING},t.prototype.isStopped=function(){return this.getState()===e.STOPPED},t.prototype.slice=function(){return this.recordPendingSlice()},t.prototype.getCompletedSlices=function(){return Array.from(this._completeSlices)},t.prototype.getCompletedAndPendingSlices=function(){return this._completeSlices.concat([this.getPendingSlice()])},t.prototype.getPendingSlice=function(){return this.calculatePendingSlice()},t.prototype.getTime=function(){return this.caculateStopwatchTime()},t.prototype.calculatePendingSlice=function(t){return void 0===this._pendingSliceStartStopwatchTime?Object.freeze({startTime:0,endTime:0,duration:0}):(void 0===t&&(t=this.getTime()),Object.freeze({startTime:this._pendingSliceStartStopwatchTime,endTime:t,duration:t-this._pendingSliceStartStopwatchTime}))},t.prototype.caculateStopwatchTime=function(t){return void 0===this._startSystemTime?0:(void 0===t&&(t=this.getSystemTimeOfCurrentStopwatchTime()),t-this._startSystemTime-this._stopDuration)},t.prototype.getSystemTimeOfCurrentStopwatchTime=function(){return void 0===this._stopSystemTime?this.getSystemTime():this._stopSystemTime},t.prototype.reset=function(){this._startSystemTime=this._pendingSliceStartStopwatchTime=this._stopSystemTime=void 0,this._stopDuration=0,this._completeSlices=[]},t.prototype.start=function(t){if(void 0===t&&(t=!1),t&&this.reset(),void 0!==this._stopSystemTime){var e=(n=this.getSystemTime())-this._stopSystemTime;this._stopDuration+=e,this._stopSystemTime=void 0}else if(void 0===this._startSystemTime){var n=this.getSystemTime();this._startSystemTime=n,this._pendingSliceStartStopwatchTime=0}},t.prototype.stop=function(t){if(void 0===t&&(t=!1),void 0===this._startSystemTime)return 0;var e=this.getSystemTimeOfCurrentStopwatchTime();return t&&this.recordPendingSlice(this.caculateStopwatchTime(e)),this._stopSystemTime=e,this.getTime()},t.prototype.recordPendingSlice=function(t){if(void 0!==this._pendingSliceStartStopwatchTime){void 0===t&&(t=this.getTime());var e=this.calculatePendingSlice(t);return this._pendingSliceStartStopwatchTime=e.endTime,this._completeSlices.push(e),e}return this.calculatePendingSlice()},t}();t.Stopwatch=n,function(t){t.IDLE="IDLE",t.RUNNING="RUNNING",t.STOPPED="STOPPED"}(e||(e={})),t.setDefaultSystemTimeGetter=function(t){void 0===t&&(t=Date.now),i=t};var i=Date.now}(stopwatch||(stopwatch={}));var TimeRuler=function(){function t(){this._frameKey="frame",this._logKey="log",this.markers=[],this.stopwacth=new stopwatch.Stopwatch,this._markerNameToIdMap=new Map,this.showLog=!1,t.Instance=this,this._logs=new Array(2);for(var e=0;e=t.logSnapDuration&&(l.logs[r].snapMin=l.logs[r].min,l.logs[r].snapMax=l.logs[r].max,l.logs[r].snapAvg=l.logs[r].avg,l.logs[r].samples=0)):(l.logs[r].min=h,l.logs[r].max=h,l.logs[r].avg=h,l.logs[r].initialized=!0)}s.markCount=o.nestCount,s.nestCount=o.nestCount}e.stopwacth.reset(),e.stopwacth.start()}})},t.prototype.beginMark=function(e,n,i){var r=this;void 0===i&&(i=0),new LockUtils(this._frameKey).lock().then(function(){if(i<0||i>=t.maxBars)throw new Error("barIndex argument out of range");var o=r._curLog.bars[i];if(o.markCount>=t.maxSamples)throw new Error("exceeded sample count. either set larger number to timeruler.maxsaple or lower sample count");if(o.nestCount>=t.maxNestCall)throw new Error("exceeded nest count. either set larger number to timeruler.maxnestcall or lower nest calls");var s=r._markerNameToIdMap.get(e);s||(s=r.markers.length,r._markerNameToIdMap.set(e,s)),o.markerNests[o.nestCount++]=o.markCount,o.markers[o.markCount].markerId=s,o.markers[o.markCount].color=n,o.markers[o.markCount].beginTime=r.stopwacth.getTime(),o.markers[o.markCount].endTime=-1})},t.prototype.endMark=function(e,n){var i=this;void 0===n&&(n=0),new LockUtils(this._frameKey).lock().then(function(){if(n<0||n>=t.maxBars)throw new Error("barIndex argument out of range");var r=i._curLog.bars[n];if(r.nestCount<=0)throw new Error("call beginMark method before calling endMark method");var o=i._markerNameToIdMap.get(e);if(!o)throw new Error("Marker "+e+" is not registered. Make sure you specifed same name as you used for beginMark method");var s=r.markerNests[--r.nestCount];if(r.markers[s].markerId!=o)throw new Error("Incorrect call order of beginMark/endMark method. beginMark(A), beginMark(B), endMark(B), endMark(A) But you can't called it like beginMark(A), beginMark(B), endMark(A), endMark(B).");r.markers[s].endTime=i.stopwacth.getTime()})},t.prototype.getAverageTime=function(e,n){if(e<0||e>=t.maxBars)throw new Error("barIndex argument out of range");var i=0,r=this._markerNameToIdMap.get(n);return r&&(i=this.markers[r].logs[e].avg),i},t.prototype.resetLog=function(){var t=this;new LockUtils(this._logKey).lock().then(function(){var e=parseInt(egret.localStorage.getItem(t._logKey),10);e+=1,egret.localStorage.setItem(t._logKey,e.toString()),t.markers.forEach(function(t){for(var e=0;e0&&(i+=t.barHeight+2*t.barPadding,r=Math.max(r,e.markers[e.markCount-1].endTime))});var o=this.sampleFrames*(1/60*1e3);this._frameAdjust=r>o?Math.max(0,this._frameAdjust)+1:Math.min(0,this._frameAdjust)-1,Math.max(this._frameAdjust)>t.autoAdjustDelay&&(this.sampleFrames=Math.min(t.maxSampleFrames,this.sampleFrames),this.sampleFrames=Math.max(this.targetSampleFrames,r/(1/60*1e3)+1),this._frameAdjust=0);e.y,t.barHeight}},t.maxBars=0,t.maxSamples=256,t.maxNestCall=32,t.barHeight=8,t.maxSampleFrames=4,t.logSnapDuration=120,t.barPadding=2,t.autoAdjustDelay=30,t}(),FrameLog=function(){return function(){this.bars=new Array(TimeRuler.maxBars);for(var t=0;t; + + /** + * 创建目录 + */ + mkdir(param: wx.types.MkdirParams): void; + /** + * mkdir 的同步版本 + * @param dirPath 创建的目录路径 + * @param recursive 是否在递归创建该目录的上级目录后再创建该目录。如果对应的上级目录已经存在,则不创建该上级目录。如 dirPath 为 a/b/c/d 且 recursive 为 true,将创建 a 目录,再在 a 目录下创建 b 目录,以此类推直至创建 a/b/c 目录下的 d 目录。 + * @throws 上级目录不存在 + * @throws 指定的 filePath 路径没有写权限 + * @throws 有同名文件或目录 + */ + mkdirSync(dirPath: string, recursive?: boolean): void; + + /** + * 解链文件 + */ + unlink(param: wx.types.UnlinkParams): void; + /** + * unlink 的同步版本 + * @param filePath 要解链的文件路径 + * @throws 指定的 path 路径没有读权限 + * @throws 文件不存在 + * @throws 传入的 filePath 是一个目录 + */ + unlinkSync(filePath: string): void; + + /** + * 解压文件 + */ + unzip(param: wx.types.UnzipParams): void; + + /** + * 读取本地文件内容 + */ + readFile(param: wx.types.ReadfileParams): void; + /** + * readFile 的同步版本,读取并返回指定路径的文件的原始二进制内容 + * @param filePath 要读取的文件的路径 + * @throws 指定的 filePath 所在目录不存在 + * @throws 指定的 filePath 路径没有读权限 + */ + readFileSync(filePath: string): ArrayBuffer; + /** + * readFile 的同步版本,读取并按指定字符编码返回字符串 + * @param filePath 要读取的文件的路径 + * @param encoding 指定读取文件的字符编码 + * @throws 指定的 filePath 所在目录不存在 + * @throws 指定的 filePath 路径没有读权限 + */ + readFileSync(filePath: string, encoding: wx.types.FileContentEncoding): string; + + /** + * 获取文件 Stats 对象 + */ + stat(param: wx.types.StatParams): void; + /** + * stat 的同步版本 + * @param path 文件/目录路径 + * @throws 指定的 path 路径没有读权限 + * @throws 文件不存在 + */ + statSync(path: string): Stats; + + /** + * 写文件 + */ + writeFile(param: wx.types.WritefileParams): void; + /** + * writeFile 的同步版本,写入二进制原始文件数据 + * @param filePath 要写入的文件路径 + * @param data 要写入的二进制数据 + * @throws 指定的 filePath 所在目录不存在 + * @throws 指定的 filePath 路径没有写权限 + */ + writeFileSync(filePath: string, data: ArrayBuffer): void; + /** + * writeFile 的同步版本,写入文本字符串数据至文件 + * @param filePath 要写入的文件路径 + * @param data 要写入的文本内容 + * @param encoding 指定写入的文本的字符编码格式 + * @throws 指定的 filePath 所在目录不存在 + * @throws 指定的 filePath 路径没有写权限 + */ + writeFileSync(filePath: string, data: string, encoding: wx.types.FileContentEncoding): void; + + /** + * 判断文件/目录是否存在 + */ + access(param: wx.types.AccessfileParams): void; + /** + * access的同步版本 + * @param path 要判断是否存在的文件/目录路径 + * @throws 文件/目录不存在 + */ + accessSync(path: string): void; + + /** + * 复制文件 + */ + copyFile(param: wx.types.CopyfileParams): void; + /** + * copyFile 的同步版本 + * @param srcPath 源文件路径,只可以是普通文件 + * @param destPath 目标文件路径 + * @throws 指定目标文件路径没有写权限 + * @throws 源文件不存在,或目标文件路径的上层目录不存在 + */ + copyFileSync(srcPath: string, destPath: string): void; + + /** + * 获取该小程序下已保存的本地缓存文件列表 + * @param res.fileList.filePath 本地路径 + * @param res.fileList.size 本地文件大小,以字节为单位 + * @param res.fileList.createTime 文件创建时间 + */ + getSavedFileList(param: wx.types.CallbacksWithType): void; + + /** + * 获取该小程序下的 本地临时文件 或 本地缓存文件 信息 + */ + getFileInfo(param: wx.types.FileinfoParams): void; + + /** + * 删除该小程序下已保存的本地缓存文件(新版本应使用unlink) + */ + removeSavedFile(param: wx.types.RemovefileParams): void; + + /** + * 保存临时文件到本地。此接口会移动临时文件,因此调用成功后,tempFilePath 将不可用。 + */ + saveFile(param: wx.types.SavefileParams): void; + /** + * saveFile的同步版本 + * @param tempFilePath 临时存储文件路径 + * @param filePath 要存储的文件路径 + * @throws 指定的 tempFilePath 找不到文件 + * @throws 指定的 filePath 路径没有写权限 + * @throws 上级目录不存在 + */ + saveFileSync(tempFilePath: string, filePath?: string): string; + + /** + * 在文件结尾追加内容 + */ + appendFile(param: wx.types.AppendfileParams): void; + /** + * appendFile的同步版本 + * @param filePath 要追加内容的文件路径 + * @param data 要追加的文本或二进制数据 + * @param encoding 指定写入文件的字符编码 + * @throws 指定的 filePath 文件不存在 + * @throws 指定的 filePath 是一个已经存在的目录 + * @throws 指定的 filePath 路径没有写权限 + * @throws 指定的 filePath 是一个已经存在的目录 + */ + appendFileSync(filePath: string, data: string | ArrayBuffer, encoding: wx.types.FileContentEncoding): void; +} + +declare class DownloadTask { + /** + * 中断下载任务 + */ + abort(): void; + /** + * 监听下载进度变化事件 + * @param res.progress 下载进度百分比,值为0至100 + * @param res.totalBytesWritten 已经下载的数据长度,单位 Bytes + * @param res.totalBytesExpectedToWrite 预期需要下载的数据总长度,单位 Bytes + */ + onProgressUpdate(callback: (res: { progress: number, totalBytesWritten: number, totalBytesExpectedToWrite: number }) => void): void; +} + +declare class RequestTask { + /** + * 中断请求任务 + */ + abort(): void; +} + +declare class SocketTask { + /** + * 通过WebSocket发送数据 + */ + send(param: wx.types.SocketSendParams): void; + /** + * 关闭WebSocket连接 + */ + close(param: wx.types.SocketCloseParams): void; + /** + * 监听WebSocket 连接打开事件 + */ + onOpen(callback: wx.types.SocketOpenCallback): void; + /** + * 监听WebSocket 连接关闭事件 + */ + onClose(callback: () => void): void; + /** + * 监听WebSocket 错误事件 + */ + onError(callback: wx.types.SocketErrorCallback): void; + /** + * 监听WebSocket 接受到服务器的消息事件 + */ + onMessage(callback: wx.types.SocketMessageCallback): void; +} + +/** + * 一个 UDP Socket 实例,默认使用 IPv4 协议。 + * 错误码: + * -1 系统错误 + * -2 socket接口错误 + * -3 发送失败,无接口权限 + * 1 发送失败,参数错误,address不合法 + * 2 发送失败,参数错误,port不合法 + */ +declare class UDPSocket { + /** + * 绑定一个系统随机分配的可用端口,或绑定一个指定的端口号 + * @param port 需要绑定的端口号,不指定时使用随机端口 + * @returns 绑定成功的端口号 + */ + bind(port?: number): number; + + /** + * 向指定的 IP 和 port 发送消息 + */ + send(param: wx.types.UDPSendParams): void; + + /** + * 关闭 UDP Socket 实例,相当于销毁。 在关闭之后,UDP Socket 实例不能再发送消息,每次调用 UDPSocket.send 将会触发错误事件, + * 并且 message 事件回调函数也不会再执行。在 UDPSocket 实例被创建后将被 Native 强引用,保证其不被 GC。在 UDPSocket.close 后 + * 将解除对其的强引用,让 UDPSocket 实例遵从 GC。 + */ + close(): void; + + /** + * 设置监听关闭事件回调 + * @param callback 关闭事件的回调函数 + */ + onClose(callback: () => void): void; + + /** + * 清除监听关闭事件回调 + * @param callback 之前监听的函数 + */ + offClose(callback: () => void): void; + + /** + * 监听错误事件 + * @param callback 错误回调函数 + */ + onError(callback: (res: { + /** + * 错误信息 + */ + errMsg: string; + }) => void): void; + + /** + * 取消监听错误事件 + * @param callback 之前设置的错误回调函数 + */ + offError(callback: (res: { + /** + * 错误信息 + */ + errMsg: string; + }) => void): void; + + /** + * 监听开始监听数据包消息的事件 + * @param callback 回调函数 + */ + onListening(callback: () => void): void; + + /** + * 取消监听开始监听数据包消息的事件 + * @param callback 之前设置的回调函数 + */ + offListening(callback: () => void): void; + + /** + * 监听收到消息的事件 + * @param callback 回调函数 + */ + onMessage(callback: (res: wx.types.UDPMessage) => void): void; + + /** + * 取消监听收到消息的事件 + * @param callback 之前设置的回调函数 + */ + offMessage(callback: (res: wx.types.UDPMessage) => void): void; +} + +declare class UploadTask { + /** + * 中断上传任务 + */ + abort(): void; + /** + * 监听上传进度变化事件 + * @param callback.res.progress 上传进度百分比 + * @param callback.res.totalBytesSent 已经上传的数据长度,单位 Bytes + * @param callback.res.totalBytesExpectedToSend 预期需要上传的数据总长度,单位 Bytes + */ + onProgressUpdate(callback: (res: { progress: number, totalBytesSent: number, totalBytesExpectedToSend: number }) => void): void; +} + +declare class KVData { + key: string; + value: string; +} + +declare class UserGameData { + /** + * 用户的微信头像 url + */ + avatarUrl: string; + /** + * 用户的微信昵称 + */ + nickname: string; + /** + * 用户的openid + */ + openid: string; + /** + * 用户的托管 KV 数据列表 + */ + KVDataList: ReadonlyArray; +} + +declare class CreatedButton { + type: wx.types.ButtonType; + text: string; + image: string; + style: wx.types.ButtonStyle; + show(): void; + hide(): void; + onTap(callback: (res?: any) => void): void; // res参数会被具体按钮的API定义覆盖为具体信息 + offTap(callback: (res?: any) => void): void; + destroy(): void; +} +declare class UserInfoButton extends CreatedButton { + onTap(callback: (res: { + /** + * 用户信息对象,不包含 openid 等敏感信息 + */ + userInfo: wx.types.UserInfo, + /** + * 不包括敏感信息的原始数据字符串,用于计算签名 + */ + rawData: string, + /** + * 使用 sha1( rawData + sessionkey ) 得到字符串,用于校验用户信息,参考文档signature(https://mp.weixin.qq.com/debug/wxagame/dev/tutorial/open-ability/http-signature.html?t=201822) + */ + signature: string, + /** + * 包括敏感数据在内的完整用户信息的加密数据,详见加密数据解密算法(https://mp.weixin.qq.com/debug/wxagame/dev/tutorial/open-ability/signature.html?t=201822) + */ + encryptedData: string, + /** + * 加密算法的初始向量,详见加密数据解密算法(https://mp.weixin.qq.com/debug/wxagame/dev/tutorial/open-ability/signature.html?t=201822) + */ + iv: string, + errMsg: string + }) => void): void; +} +declare class OpenSettingButton extends CreatedButton { + onTap(callback: () => void): void; + offTap(callback: () => void): void; +} +declare class GameClubButton extends CreatedButton { + icon: wx.types.GameClubButtonIcon; + onTap(callback: (res: { + errMsg: string; + }) => void): void; +} +declare class FeedbackButton extends CreatedButton { + onTap(callback: (res: { + errMsg: string; + }) => void): void; +} + +declare class OpenDataContext { + /** + * 开放数据域和主域共享的 sharedCanvas,注意在开放数据域内时getContext只能使用2d模式 + */ + canvas: Canvas; + /** + * 向开放数据域发送消息 + * @param message 要发送的消息,message 中及嵌套对象中 key 的 value 只能是 primitive value。即 number、string、boolean、null、undefined。 + */ + postMessage(message: any): void; +} + +declare class LoadSubpackageTask { + /** + * 监听分包加载进度变化事件 + * @param callback.res.progress 分包下载进度百分比 + * @param callback.res.totalBytesWritten 已经下载的数据长度,单位 Bytes + * @param callback.res.totalBytesExpectedToWrite 预期需要下载的数据总长度,单位 Bytes + */ + onProgressUpdate(callback: (res: { progress: number, totalBytesWritten: number, totalBytesExpectedToWrite: number }) => void): void; +} + +declare class UpdateManager { + /** + * 应用更新包并重启 + */ + applyUpdate(): void; + /** + * 监听检查更新结果回调 + */ + onCheckForUpdate(callback: () => void): void; + /** + * 监听更新包下载成功回调 + */ + onUpdateReady(callback: () => void): void; + /** + * 监听更新包下载失败回调 + */ + onUpdateFailed(callback: () => void): void; +} + +declare class WxWorker { + /** + * 向主线程或Worker线程发送的消息。 + * @param message 需要发送的消息,必须是一个可序列化的 JavaScript 对象。 + */ + postMessage(message: any): void; + /** + * 结束当前 worker 线程,仅限在主线程 worker 对象上调用。 + */ + terminate(): void; + /** + * 监听接收主线程/Worker 线程向当前线程发送的消息 + * @param callback.res.message 接收主线程/Worker 线程向当前线程发送的消息 + */ + onMessage(callback: (res: { message: any }) => void): void; +} + +/** + * InnerAudioContext 实例,可通过 wx.createInnerAudioContext 接口获取实例。 + */ +declare class InnerAudioContext { + /** + * 音频资源的地址 + */ + src: string; + /** + * 是否自动播放 + */ + autoplay: boolean; + /** + * 是否循环播放 + */ + loop: boolean; + /** + * 是否遵循系统静音开关,当此参数为 false 时,即使用户打开了静音开关,也能继续发出声音 + */ + obeyMuteSwitch: boolean; + /** + * 当前音频的长度,单位 s。只有在当前有合法的 src 时返回 + */ + readonly duration: number; + /** + * 当前音频的播放位置,单位 s。只有在当前有合法的 src 时返回,时间不取整,保留小数点后 6 位 + */ + readonly currentTime: number; + /** + * 当前是是否暂停或停止状态,true 表示暂停或停止,false 表示正在播放 + */ + paused: boolean; + /** + * 音频缓冲的时间点,仅保证当前播放时间点到此时间点内容已缓冲 + */ + readonly buffered: number; + /** + * 音量。范围 0~1。 + */ + volume: number; + + /** + * 播放 + */ + play(): void; + /** + * 暂停。暂停后的音频再播放会从暂停处开始播放 + */ + pause(): void; + /** + * 停止。停止后的音频再播放会从头开始播放。 + */ + stop(): void; + /** + * 跳转到指定位置,单位 s + * @param position 跳转的时间 + */ + seek(position: number): void; + /** + * 销毁当前实例 + */ + destroy(): void; + /** + * 监听音频进入可以播放状态的事件 + */ + onCanplay(callback: () => void): void; + /** + * 取消监听音频进入可以播放状态的事件 + */ + offCanplay(callback: () => void): void; + /** + * 监听音频播放事件 + */ + onPlay(callback: () => void): void; + /** + * 取消监听音频播放事件 + */ + offPlay(callback: () => void): void; + /** + * 监听音频暂停事件 + */ + onPause(callback: () => void): void; + /** + * 取消监听音频暂停事件 + */ + offPause(callback: () => void): void; + /** + * 监听音频停止事件 + */ + onStop(callback: () => void): void; + /** + * 取消监听音频停止事件 + */ + offStop(callback: () => void): void; + /** + * 监听音频自然播放至结束的事件 + */ + onEnded(callback: () => void): void; + /** + * 取消监听音频自然播放至结束的事件 + */ + offEnded(callback: () => void): void; + /** + * 监听音频播放进度更新事件 + */ + onTimeUpdate(callback: () => void): void; + /** + * 取消监听音频播放进度更新事件 + */ + offTimeUpdate(callback: () => void): void; + /** + * 监听音频播放错误事件 + */ + onError(callback: () => void): void; + /** + * 取消监听音频播放错误事件 + */ + offError(callback: () => void): void; + /** + * 监听音频加载中事件,当音频因为数据不足,需要停下来加载时会触发 + */ + onWaiting(callback: () => void): void; + /** + * 取消监听音频加载中事件,当音频因为数据不足,需要停下来加载时会触发 + */ + offWaiting(callback: () => void): void; + /** + * 监听音频进行跳转操作的事件 + */ + onSeeking(callback: () => void): void; + /** + * 取消监听音频进行跳转操作的事件 + */ + offSeeking(callback: () => void): void; + /** + * 监听音频完成跳转操作的事件 + */ + onSeeked(callback: () => void): void; + /** + * 取消监听音频完成跳转操作的事件 + */ + offSeeked(callback: () => void): void; +} + +declare class RecorderManager { + /** + * 开始录音 + */ + start(param: { + /** + * 录音的时长,单位 ms,最大值 600000(10 分钟),默认值60000(1 分钟) + */ + duration?: number, + /** + * 采样率 + */ + sampleRate: 8000 | 11025 | 12000 | 16000 | 22050 | 24000 | 32000 | 44100 | 48000, + /** + * 录音通道数 + */ + numberOfChannels: 1 | 2, + /** + * 编码码率 + */ + encodeBitRate: number, + /** + * 音频格式 + */ + format: "mp3" | "aac", + /** + * 指定帧大小,单位 KB。传入 frameSize 后,每录制指定帧大小的内容后,会回调录制的文件内容,不指定则不会回调 + */ + frameSize: number, + /** + * 指定录音的音频源,可通过 wx.getAvailableAudioSources() 获取当前可用的音频源,默认值auto + */ + audioSource?: wx.types.AudioSourceType + }): void; + /** + * 暂停录音 + */ + pause(): void; + /** + * 继续录音 + */ + resume(): void; + /** + * 停止录音 + */ + stop(): void; + /** + * 监听录音开始事件 + */ + onStart(callback: () => void): void; + /** + * 监听录音继续事件 + */ + onResume(callback: () => void): void; + /** + * 监听录音暂停事件 + */ + onPause(callback: () => void): void; + /** + * 监听录音结束事件 + * @param callback.res.tempFilePath 录音文件的临时路径 + */ + onStop(callback: (res: { tempFilePath: string }) => void): void; + /** + * 监听已录制完指定帧大小的文件事件。如果设置了 frameSize,则会回调此事件。 + * @param callback.res.frameBuffer 录音分片数据 + * @param callback.res.isLastFrame 当前帧是否正常录音结束前的最后一帧 + */ + onFrameRecorded(callback: (res: { frameBuffer: ArrayBuffer, isLastFrame: boolean }) => void): void; + /** + * 监听录音错误事件 + */ + onError(callback: (res: { errMsg: string }) => void): void; +} + +declare class ImageFile { + /** + * 本地文件路径 + */ + path: string; + /** + * 本地文件大小,单位 B + */ + size: number; +} + +declare class Video { + /** + * 视频的左上角横坐标 + */ + x: number; + /** + * 视频的左上角纵坐标 + */ + y: number; + /** + * 视频的宽度,默认值300 + */ + width: number; + /** + * 默认值150 + */ + height: number; + /** + * 视频的资源地址 + */ + src: string; + /** + * 视频的封面 + */ + poster: string; + /** + * 视频的初始播放位置,单位为 s 秒,默认值0 + */ + initialTime: number; + /** + * 视频的播放速率,有效值有 0.5、0.8、1.0、1.25、1.5默认值1.0 + */ + playbackRate: number; + /** + * 视频是否为直播,默认值0 + */ + live?: number; + /** + * 视频的缩放模式 + * fill - 填充,视频拉伸填满整个容器,不保证保持原有长宽比例 + * contain - 包含,保持原有长宽比例。保证视频尺寸一定可以在容器里面放得下。因此,可能会有部分空白 + * cover - 覆盖,保持原有长宽比例。保证视频尺寸一定大于容器尺寸,宽度和高度至少有一个和容器一致。因此,视频有部分会看不见 + */ + objectFit: "contain" | "cover" | "fill"; + /** + * 视频是否显示控件,默认true + */ + controls: boolean; + /** + * 视频是否自动播放,默认false + */ + autoplay: boolean; + /** + * 视频是否是否循环播放,默认值false + */ + loop: boolean; + /** + * 视频是否禁音播放,默认值false + */ + muted: boolean; + + /** + * 视频开始缓冲时触发的回调函数 + */ + onwaiting: () => void; + /** + * 视频开始播放时触发的回调函数 + */ + onplay: () => void; + /** + * 视频暂停时触发的回调函数 + */ + onpause: () => void; + /** + * 视频播放到末尾时触发的回调函数 + */ + onended: () => void; + /** + * 每当视频播放进度更新时触发的回调函数 + */ + ontimeupdate: () => void; + /** + * 视频发生错误时触发的回调函数 + */ + onerror: () => void; + + /** + * 销毁视频 + */ + destroy(): void; + /** + * 监听视频缓冲事件 + */ + onWaiting(callback: () => void): void; + /** + * 取消监听视频缓冲事件 + */ + offWaiting(callback: () => void): void; + + /** + * 监听视频播放事件 + */ + onPlay(callback: () => void): void; + /** + * 取消监听视频播放事件 + */ + offPlay(callback: () => void): void; + /** + * 监听视频暂停事件 + */ + onPause(callback: () => void): void; + /** + * 取消监听视频暂停事件 + */ + offPause(callback: () => void): void; + /** + * 监听视频播放到末尾事件 + */ + onEnded(callback: () => void): void; + /** + * 取消监听视频播放到末尾事件 + */ + offEnded(callback: () => void): void; + /** + * 监听视频播放进度更新事件 + * @param callback.res.position 当前的播放位置,单位为秒 + * @param callback.res.duration 视频的总时长,单位为秒 + */ + onTimeUpdate(callback: (res: { position: number, duration: number }) => void): void; + /** + * 取消监听视频播放进度更新事件 + */ + offTimeUpdate(callback: (res: { position: number, duration: number }) => void): void; + /** + * 监听视频错误事件 + * @param callback.res.errMsg 错误信息,有如下值 + * MEDIA_ERR_NETWORK - 当下载时发生错误 + * MEDIA_ERR_DECODE - 当解码时发生错误 + * MEDIA_ERR_SRC_NOT_SUPPORTED - video 的 src 属性是不支持的资源类型 + */ + onError(callback: (res: { errMsg: string }) => void): void; + /** + * 取消监听视频错误事件 + */ + offError(callback: (res: { errMsg: string }) => void): void; + + /** + * 播放视频 + */ + play(): Promise; + /** + * 暂停视频 + */ + pause(): Promise; + /** + * 停止视频 + */ + stop(): Promise; + /** + * 视频跳转 + * @param time 视频跳转到指定位置,单位为 s 秒 + */ + seek(time: number): Promise; + + /** + * 视频全屏 + */ + requestFullScreen(): Promise; + + /** + * 视频退出全屏 + */ + exitFullScreen(): Promise; +} + +/** + * banner 广告组件。banner 广告组件是一个原生组件,层级比上屏 Canvas 高,会覆盖在上屏 Canvas 上。banner 广告组件默认是隐藏的,需要调用 BannerAd.show() 将其显示。banner 广告会根据开发者设置的宽度进行等比缩放,缩放后的尺寸将通过 BannerAd.onResize() 事件中提供。 + */ +declare class BannerAd { + /** + * 广告单元 id + */ + adUnitId: string; + /** + * banner 广告组件的样式。style 上的属性的值仅为开发者设置的值,banner 广告会根据开发者设置的宽度进行等比缩放,缩放后的真实尺寸需要通过 BannerAd.onResize() 事件获得。 + */ + style: wx.types.AdStyle; + + /** + * 显示 banner 广告。 + */ + show(): Promise; + /** + * 隐藏 banner 广告 + */ + hide(): void; + /** + * 销毁 banner 广告 + */ + destroy(): void; + /** + * 监听 banner 广告缩放 + */ + onResize(callback: (res: { width: number, height: number }) => void): void; + /** + * 取消监听隐藏 banner 广告缩放 + */ + offResize(callback: (res: { width: number, height: number }) => void): void; + /** + * 监听banner 广告加载事件 + */ + onLoad(callback: () => void): void; + /** + * 取消监听banner 广告加载事件 + */ + offLoad(callback: () => void): void; + /** + * 监听banner 广告错误事件 + */ + onError(callback: (res: { errMsg: string }) => void): void; + /** + * 取消监听banner 广告错误事件 + */ + offError(callback: (res: { errMsg: string }) => void): void; +} + +declare class InterstitialAd extends BannerAd { + /** + * 加载视频广告 + */ + load(): Promise; + /** + * 监听用户点击 关闭广告 按钮的事件 + */ + onClose(callback: (res: { isEnded: boolean }) => void): void; + /** + * 监听用户点击 关闭广告 按钮的事件 + */ + offClose(callback: (res: { isEnded: boolean }) => void): void; +} + +declare class RewardedVideoAd extends InterstitialAd { +} + +// --定时器 +declare function clearTimeout(timeoutID: number): void; +declare function clearInterval(intervalID: number): void; +declare function setTimeout(fn: () => void, delay: number, ...rest: any[]): number; +declare function setInterval(fn: () => void, delay: number, ...rest: any[]): number; + +// --渲染 +declare function cancelAnimationFrame(requestID: number): void; +declare function requestAnimationFrame(callback: () => void): number; + +declare namespace wx { + namespace types { + interface Callbacks { + success?: () => void; + fail?: () => void; + complete?: () => void; + } + + interface CallbacksWithType { + success?: (res: T) => void; + fail?: () => void; + complete?: () => void; + } + + interface CallbacksWithType2 { + success?: (res: T) => void; + fail?: (res: F) => void; + complete?: () => void; + } + + interface RenderingContextConfig { + /** + * 表示是否抗锯齿 + */ + antialias?: boolean; + /** + * 表示是否绘图完成后是否保留绘图缓冲区 + */ + preserveDrawingBuffer?: boolean; + /** + * 抗锯齿样本数。最小值为 2,最大不超过系统限制数量,仅 iOS 支持 + */ + antialiasSamples?: number; + } + + interface ToTempFileSyncParams { + /** + * 截取 canvas 的左上角横坐标 + */ + x?: number; + /** + * 截取 canvas 的左上角纵坐标 + */ + y?: number; + /** + * 截取 canvas 的宽度 + */ + width?: number; + /** + * 截取 canvas 的高度 + */ + height?: number; + /** + * 目标文件的宽度,会将截取的部分拉伸或压缩至该数值 + */ + destWidth?: number; + /** + * 目标文件的高度,会将截取的部分拉伸或压缩至该数值 + */ + destHeight?: number; + /** + * 目标文件的类型 + */ + fileType?: "jpg" | "png"; + /** + * jpg图片的质量,仅当 fileType 为 jpg 时有效。取值范围为 0.0(最低)- 1.0(最高),不含 0。不在范围内时当作 1.0 + */ + quality?: number; + } + + interface ToTempFileParams extends ToTempFileSyncParams { + success?: (res: { tempFilePath: string }) => void; + fail?: () => void; + complete?: () => void; + } + + interface RenameParams { + oldPath: string; + newPath: string; + success?: () => void; + fail?: (res: { errMsg: string }) => void; + complete?: () => void; + } + + interface RmdirParams { + dirPath: string; + recursive?: boolean; + success?: () => void; + fail?: (res: { errMsg: string }) => void; + complete?: () => void; + } + + interface ReaddirParams { + dirPath: string; + success?: (res: { files: ReadonlyArray }) => void; + fail?: (res: { errMsg: string }) => void; + complete?: () => void; + } + + interface MkdirParams { + dirPath: string; + recursive?: boolean; + success?: () => void; + fail?: (res: { errMsg: string }) => void; + complete?: () => void; + } + + type FileContentEncoding = "ascii" | "base64" | "binary" | "hex" | "ucs2" | "ucs-2" | "utf16le" | "utf-16le" | "utf-8" | "utf8" | "latin1"; + + interface ReadfileParams { + filePath: string; + encoding?: FileContentEncoding; + success?: (res: { data: string | ArrayBuffer }) => void; + fail?: (res: { errMsg: string }) => void; + complete?: () => void; + } + + interface StatParams { + path: string; + success?: (res: { stat: Stats }) => void; + fail?: (res: { errMsg: string }) => void; + complete?: () => void; + } + + interface WritefileParams { + filePath: string; + data: string | ArrayBuffer; + encoding?: FileContentEncoding; + success?: () => void; + fail?: (res: { errMsg: string }) => void; + complete?: () => void; + } + + interface UnlinkParams { + filePath: string; + success?: () => void; + fail?: (res: { errMsg: string }) => void; + complete?: () => void; + } + + interface UnzipParams { + zipFilePath: string; + targetPath: string; + success?: () => void; + fail?: (res: { errMsg: string }) => void; + complete?: () => void; + } + + interface AccessfileParams { + path: string; + success?: () => void; + fail?: (res: { errMsg: string }) => void; + complete?: () => void; + } + + interface SavedfileList { + fileList: { + filePath: string; + size: number; + createTime: number; + }; + } + + interface CopyfileParams { + srcPath: string; + destPath: string; + success?: () => void; + fail?: (res: { errMsg: string }) => void; + complete?: () => void; + } + + interface FileinfoParams { + filePath: string; + success?: (res: { size: number, digest: string }) => void; + fail?: (res: { errMsg: string }) => void; + complete?: () => void; + } + + interface RemovefileParams { + filePath: string; + success?: () => void; + fail?: () => void; + complete?: () => void; + } + + interface SavefileParams { + tempFilePath: string; + filePath?: string; + success?: (res: { savedFilePath: string }) => void; + fail?: (res: { errMsg: string }) => void; + complete?: () => void; + } + + interface AppendfileParams { + filePath: string; + data: string | ArrayBuffer; + encoding?: FileContentEncoding; + success?: () => void; + fail?: (res: { errMsg: string }) => void; + complete?: () => void; + } + + interface LineHeightParams { + fontStyle?: "normal" | "italic"; + fontWeight?: "normal" | "bold"; + fontSize?: number; + fontFamily: string; + text: string; + success?: (res: { lineHeight: number }) => void; + fail?: () => void; + complete?: () => void; + } + + interface Image { + src: string; + width: number; + height: number; + onload: () => void; + onerror: (e?: any) => void; + } + + // --启动参数 + interface LaunchOption { + /** + * 场景值 + */ + scene: number; + /** + * 启动参数 + */ + query: any; + /** + * 当前小游戏是否被显示在聊天顶部 + */ + isSticky: boolean; + /** + * 票据 + */ + shareTicket: string; + } + + // --系统信息 + interface SystemInfo { + /** + * 手机品牌 + */ + brand: string; + /** + * 手机型号 + */ + model: string; + /** + * 设备像素比 + */ + pixelRatio: number; + /** + * 屏幕宽度 + */ + screenWidth: number; + /** + * 屏幕高度 + */ + screenHeight: number; + /** + * 可使用窗口宽度 + */ + windowWidth: number; + /** + * 可使用窗口高度 + */ + windowHeight: number; + /** + * 微信设置的语言 + */ + language: string; + /** + * 微信版本号 + */ + version: string; + /** + * 操作系统版本 + */ + system: string; + /** + * 客户端平台 + */ + platform: string; + /** + * 用户字体大小设置。以“我-设置-通用-字体大小”中的设置为准,单位 px。 + */ + fontSizeSetting: string; + /** + * 客户端基础库版本 + */ + SDKVersion: string; + /** + * 性能等级 + */ + benchmarkLevel: number; + /** + * 电量,范围 1 - 100 + */ + battery: number; + /** + * wifi 信号强度,范围 0 - 4 + */ + wifiSignal: number; + } + + // --触摸对象 + interface Touch { + /** + * Touch 对象的唯一标识符,只读属性。一次触摸动作(我们值的是手指的触摸)在平面上移动的整个过程中, 该标识符不变。可以根据它来判断跟踪的是否是同一次触摸过程。 + */ + identifier: number; + /** + * 触点相对于整体页面的 X 轴距离。 + */ + pageX: number; + /** + * 触点相对于整体页面的 Y 轴距离。 + */ + pageY: number; + /** + * 触点相对于游戏窗口的 X 轴距离。 + */ + clientX: number; + /** + * 触点相对于游戏窗口的 Y 轴距离。 + */ + clientY: number; + } + + interface TouchData { + /** + * 当前事件的类型 + */ + type: string; + /** + * 当前所有触摸点的列表 + */ + touches: ReadonlyArray; + /** + * 触发此次事件的触摸点列表 + */ + changedTouches: ReadonlyArray; + /** + * 事件触发时的时间戳 + */ + timeStamp: number; + } + + // --iBeacon(TODO) + /** + * 停止搜索附近的 iBeacon 设备 + */ + function stopBeaconDiscovery(param: any): void; + /** + * 开始搜索附近的 iBeacon 设备 + */ + function startBeaconDiscovery(param: any): void; + /** + * 监听 iBeacon 设备更新事件,仅能注册一个监听 + */ + function onBeaconUpdate(callback: any): void; + /** + * 监听 iBeacon 服务状态变化事件,仅能注册一个监听 + */ + function onBeaconServiceChange(callback: any): void; + /** + * 取消监听 iBeacon 设备更新事件 + */ + function offBeaconUpdate(callback: any): void; + /** + * 取消监听 iBeacon 服务状态变化事件 + */ + function offBeaconServiceChange(callback: any): void; + /** + * 获取所有已搜索到的 iBeacon 设备 + */ + function getBeacons(param: any): void; + /* + IBeaconInfo + 属性 + string uuid + iBeacon 设备广播的 uuid + string major + iBeacon 设备的主 id + string minor + iBeacon 设备的次 id + number proximity + 表示设备距离的枚举值 + number accuracy + iBeacon 设备的距离 + number rssi + 表示设备的信号强度 + */ + + // --低功耗蓝牙(TODO) + function writeBLECharacteristicValue(): void; + function readBLECharacteristicValue(): void; + function onBLEConnectionStateChange(): void; + function onBLECharacteristicValueChange(): void; + function notifyBLECharacteristicValueChange(): void; + function getBLEDeviceServices(): void; + function getBLEDeviceCharacteristics(): void; + function createBLEConnection(): void; + function closeBLEConnection(): void; + + // --蓝牙(TODO) + function stopBluetoothDevicesDiscovery(): void; + function startBluetoothDevicesDiscovery(): void; + function openBluetoothAdapter(): void; + function onBluetoothDeviceFound(): void; + function onBluetoothAdapterStateChange(): void; + function getConnectedBluetoothDevices(): void; + function getBluetoothDevices(): void; + function getBluetoothAdapterState(): void; + function closeBluetoothAdapter(): void; + + // --电量 + interface BatteryInfo { + /** + * 设备电量,范围 1 - 100 + */ + level: string; + /** + * 是否正在充电 + */ + isCharging: boolean; + } + + // --剪切板 + interface ClipboardData { + data: string; + } + + interface SetClipboardDataParams { + success?: () => void; + fail?: () => void; + complete?: () => void; + data: string; + } + + interface SetKeepScreenOnParams { + success?: () => void; + fail?: () => void; + complete?: () => void; + keepScreenOn: boolean; + } + + interface SetScreenBrightnessParams { + success?: () => void; + fail?: () => void; + complete?: () => void; + /** + * 屏幕亮度值,范围 0 ~ 1,0 最暗,1 最亮 + */ + value: number; + } + + interface DownfileParams { + url: string; + /** + * 在指定filePath之后success回调中将不会有res.tempFilePath路径值,下载的文件会直接写入filePath指定的路径(有写入权限的情况下,根目录请使用wx.env.USER_DATA_PATH,路径文件夹必须存在,否则写入失败) + */ + filePath?: string; + /** + * HTTP 请求的 Header,Header 中不能设置 Referer + */ + header?: { [key: string]: string }; + /** + * res.tempFilePath 临时文件路径。如果没传入 filePath 指定文件存储路径,则下载后的文件会存储到一个临时文件 + * res.statusCode 开发者服务器返回的 HTTP 状态码 + */ + success?: (res: { tempFilePath?: string, statusCode: number }) => void; + fail?: (res: { errMsg: string }) => void; + complete?: () => void; + } + + type NetworkType = "wifi" | "2g" | "3g" | "4g" | "any" | "none"; + + type RequestMethod = "GET" | "HEAD" | "POST" | "PUT" | "DELETE" | "TRACE" | "CONNECT"; + + interface RequestParams { + /** + * 开发者服务器接口地址 + */ + url: string; + /** + * 请求的参数 + */ + data?: string | { [key: string]: any }; + /** + * 设置请求的 header,header 中不能设置 Referer + */ + header?: { [name: string]: string }; + /** + * HTTP 请求方法 + */ + method?: RequestMethod; + /** + * 返回的数据格式 + */ + dataType?: "json" | "arraybuffer"; + /** + * res.data usually can be string or ArrayBuffer + */ + success?: (res: { data: any, statusCode: number, header?: { [key: string]: string } }) => void; + fail?: () => void; + complete?: () => void; + } + + interface SocketSendParams { + data: string | ArrayBuffer; + success?: () => void; + fail?: () => void; + complete?: () => void; + } + interface SocketConnectParams { + url: string; + protocols?: string[]; + header?: { [key: string]: string }; + method?: RequestMethod; + success?: () => void; + fail?: () => void; + complete?: () => void; + } + interface SocketCloseParams { + /** + * 一个数字值表示关闭连接的状态号,表示连接被关闭的原因。如果这个参数没有被指定,默认的取值是1000 (表示正常连接关闭) + */ + code?: number; + /** + * 一个可读的字符串,表示连接被关闭的原因。这个字符串必须是不长于123字节的UTF-8 文本(不是字符) + */ + reason?: string; + success?: () => void; + fail?: () => void; + complete?: () => void; + } + + type SocketOpenCallback = (res: { header?: { [key: string]: string } }) => void; + type SocketMessageCallback = (res: { data: string | ArrayBuffer }) => void; + type SocketErrorCallback = (res: { errMsg: string }) => void; + + interface UDPSendParams { + /** + * 要发消息的地址。可以是一个和本机同网段的 IP 地址,也可以是在安全域名列表内的域名地址 + */ + address: string; + /** + * 要发送消息的端口号 + */ + port: number; + /** + * 要发送的数据 + */ + message: string | ArrayBuffer; + /** + * 发送数据的偏移量,仅当 message 为 ArrayBuffer 类型时有效,默认值0 + */ + offset?: number; + /** + * 发送数据的长度,仅当 message 为 ArrayBuffer 类型时有效,默认值message.byteLength + */ + length?: number; + } + interface UDPMessage { + /** + * 收到的消息 + */ + message: ArrayBuffer; + /** + * 消息来源的结构化信息 + */ + remoteInfo: { + /** + * 发送消息的 socket 的地址 + */ + address: string; + /** + * 使用的协议族,为 IPv4 或者 IPv6 + */ + family: string; + /** + * 端口号 + */ + port: number; + /** + * message 的大小,单位:字节 + */ + size: number; + }; + } + + /** + * wx.getUserInfo的旧版本API参数,随时会被删除,不推荐使用 + */ + interface OldUserInfoParam { + /** + * 是否带上登录态信息。当 withCredentials 为 true 时,要求此前有调用过 wx.login 且登录态尚未过期,此时返回的数据会包含 encryptedData, iv 等敏感信息;当 withCredentials 为 false 时,不要求有登录态,返回的数据不包含 encryptedData, iv 等敏感信息。 + */ + withCredentials?: boolean; + /** + * 显示用户信息的语言 + */ + lang?: "en" | "zh_CN" | "zh_TW"; + success?: (res: { + /** + * 用户信息对象,不包含 openid 等敏感信息 + */ + userInfo: UserInfo, + /** + * 不包括敏感信息的原始数据字符串,用于计算签名 + */ + rawData: string, + /** + * 使用 sha1( rawData + sessionkey ) 得到字符串,用于校验用户信息,参考文档signature(https://mp.weixin.qq.com/debug/wxagame/dev/tutorial/open-ability/http-signature.html?t=201822) + */ + signature: string, + /** + * 包括敏感数据在内的完整用户信息的加密数据,详见加密数据解密算法(https://mp.weixin.qq.com/debug/wxagame/dev/tutorial/open-ability/signature.html?t=201822) + */ + encryptedData: string, + /** + * 加密算法的初始向量,详见加密数据解密算法(https://mp.weixin.qq.com/debug/wxagame/dev/tutorial/open-ability/signature.html?t=201822) + */ + iv: string, + errMsg: string + }) => void; + fail?: () => void; + complete?: () => void; + } + + /** + * 新版本wx.getUserInfo的参数,需要在开放数据域内调用 + */ + interface NewUserInfoParam { + /** + * 要获取信息的用户的 openId 数组,如果要获取当前用户信息,则将数组中的一个元素设为 'selfOpenId' + */ + openIdList?: string[]; + /** + * 显示用户信息的语言 + */ + lang?: "en" | "zh_CN" | "zh_TW"; + success?: (res: { data: ReadonlyArray }) => void; + fail?: () => void; + complete?: () => void; + } + + interface UserInfo { + language: string; + nickName: string; + avatarUrl: string; + /** + * 0:未知、1:男、2:女 + */ + gender: 0 | 1 | 2; + country: string; + province: string; + city: string; + } + + type ButtonType = "text" | "image"; + interface ButtonStyle { + left?: number; + top?: number; + width?: number; + height?: number; + /** + * 格式#ff0000 + */ + backgroundColor?: string; + /** + * 格式#ff0000 + */ + borderColor?: string; + borderWidth?: number; + borderRadius?: number; + textAlign?: "left" | "center" | "right"; + fontSize?: number; + lineHeight?: number; + } + + type GameClubButtonIcon = "green" | "white" | "dark" | "light"; + + // --设置 + interface AuthSetting { + /** + * 用户信息,对应接口 wx.getUserInfo + */ + "scope.userInfo"?: boolean; + /** + * 地理位置,对应接口 wx.getLocation wx.chooseLocation + */ + "scope.userLocation"?: boolean; + /** + * 通讯地址,对应接口 wx.chooseAddress + */ + "scope.address"?: boolean; + /** + * 发票抬头,对应接口 wx.chooseInvoiceTitle + */ + "scope.invoiceTitle"?: boolean; + /** + * 微信运动步数,对应接口 wx.getWeRunData + */ + "scope.werun"?: boolean; + /** + * 录音功能,对应接口 wx.startRecord + */ + "scope.record"?: boolean; + /** + * 保存到相册 wx.saveImageToPhotosAlbum, wx.saveVideoToPhotosAlbum + */ + "scope.writePhotosAlbum"?: boolean; + /** + * 摄像头 wx.camera + */ + "scope.camera"?: boolean; + } + + interface SetStorageParams { + key: string; + data: any; + success?: () => void; + fail?: () => void; + complete?: () => void; + } + interface RemoveStorageParams { + key: string; + success?: () => void; + fail?: () => void; + complete?: () => void; + } + interface GetStorageParams { + key: string; + success?: (res: { data: any }) => void; + fail?: () => void; + complete?: () => void; + } + + interface StorageInfo { + /** + * 当前 storage 中所有的 key + */ + keys: ReadonlyArray; + /** + * 当前占用的空间大小, 单位 KB + */ + currentSize: number; + /** + * 限制的空间大小,单位 KB + */ + limitSize: number; + } + + interface ShareOption { + /** + * 转发标题,不传则默认使用当前小游戏的昵称。 + */ + title?: string; + /** + * 转发显示图片的链接,可以是网络图片路径或本地图片文件路径或相对代码包根目录的图片文件路径。显示图片长宽比是 5:4 + */ + imageUrl?: string; + /** + * 查询字符串,必须是 key1=val1&key2=val2 的格式。从这条转发消息进入后,可通过 wx.getLaunchOptionsSync() 或 wx.onShow 获取启动参数中的 query。 + */ + query?: string; + } + + interface AccelerometerParams { + interval: "game" | "ui" | "normal"; + success?: () => void; + fail?: () => void; + complete?: () => void; + } + + type AudioSourceType = "auto" | "buildInMic" | "headsetMic" | "mic" | "camcorder"; + + interface AdStyle { + /** + * 广告组件的左上角横坐标 + */ + left: number; + /** + * banner 广告组件的左上角纵坐标 + */ + top: number; + /** + * banner 广告组件的宽度。最小 300,最大至 屏幕宽度(屏幕宽度可以通过 wx.getSystemInfoSync() 获取)。 + */ + width: number; + /** + * banner 广告组件的高度 + */ + height: number; + /** + * banner 广告组件经过缩放后真实的宽度 + */ + realWidth: number; + /** + * banner 广告组件经过缩放后真实的高度 + */ + realHeight: number; + } + } + + /** + * 创建一个画布对象。首次调用创建的是显示在屏幕上的画布,之后调用创建的都是离屏画布。 + */ + function createCanvas(): Canvas; + + /** + * 只有开放数据域能调用,获取主域和开放数据域共享的 sharedCanvas + */ + function getSharedCanvas(): Canvas; + + /** + * 创建一个图片对象 + */ + function createImage(): types.Image; + + /** + * 获取一行文本的行高 + * @param p 字体参数 + */ + function getTextLineHeight(p: types.LineHeightParams): number; + + /** + * 加载自定义字体文件 + * @param path 字体文件路径。可以是代码包文件路径,也可以是 wxfile:// 协议的本地文件路径。 + */ + function loadFont(path: string): string; + + /** + * 可以修改渲染帧率。默认渲染帧率为 60 帧每秒。修改后,requestAnimationFrame 的回调频率会发生改变。 + * @param fps 帧率,有效范围 1 - 60。 + */ + function setPreferredFramesPerSecond(fps: number): void; + + // --生命周期 + function exitMiniProgram(cb?: types.Callbacks): void; + function getLaunchOptionsSync(): types.LaunchOption; + function onHide(cb: () => void): void; + function offHide(cb: () => void): void; + function onShow(cb: (res: { scene: string, query: any, shareTicket: string }) => void): void; + function offShow(cb: (res: { scene: string, query: any, shareTicket: string }) => void): void; + + // --系统信息 + function getSystemInfo(cb: types.CallbacksWithType): void; + function getSystemInfoSync(): types.SystemInfo; + + /** + * 监听音频中断结束,在收到 onAudioInterruptionBegin 事件之后,小程序内所有音频会暂停,收到此事件之后才可再次播放成功 + */ + function onAudioInterruptionEnd(cb: () => void): void; + /** + * 取消监听音频中断结束,在收到 onAudioInterruptionBegin 事件之后,小程序内所有音频会暂停,收到此事件之后才可再次播放成功 + */ + function offAudioInterruptionEnd(cb: () => void): void; + /** + * 监听音频因为受到系统占用而被中断开始,以下场景会触发此事件:闹钟、电话、FaceTime 通话、微信语音聊天、微信视频聊天。此事件触发后,小程序内所有音频会暂停。 + */ + function onAudioInterruptionBegin(cb: () => void): void; + /** + * 取消监听音频因为受到系统占用而被中断开始,以下场景会触发此事件:闹钟、电话、FaceTime 通话、微信语音聊天、微信视频聊天。此事件触发后,小程序内所有音频会暂停。 + */ + function offAudioInterruptionBegin(cb: () => void): void; + /** + * 监听全局错误事件 + */ + function onError(cb: (res: { message: string, stack: string }) => void): void; + function offError(cb: (res: { message: string, stack: string }) => void): void; + + // --触摸事件 + /** + * 监听开始始触摸事件 + */ + function onTouchStart(cb: (res: types.TouchData) => void): void; + function offTouchStart(cb: (res: types.TouchData) => void): void; + /** + * 监听触点移动事件 + */ + function onTouchMove(cb: (res: types.TouchData) => void): void; + function offTouchMove(cb: (res: types.TouchData) => void): void; + /** + * 监听触摸结束事件 + */ + function onTouchEnd(cb: (res: types.TouchData) => void): void; + function offTouchEnd(cb: (res: types.TouchData) => void): void; + /** + * 监听触点失效事件 + */ + function onTouchCancel(cb: (res: types.TouchData) => void): void; + function offTouchCancel(cb: (res: types.TouchData) => void): void; + + // --加速计 + /** + * 监听加速度数据,频率:5次/秒,接口调用后会自动开始监听,可使用 wx.stopAccelerometer 停止监听。 + */ + function onAccelerometerChange(cb: (res: { x: number, y: number, z: number }) => void): void; + /** + * 开始监听加速度数据。 + */ + function startAccelerometer(cb: types.AccelerometerParams): void; + /** + * 停止监听加速度数据。 + */ + function stopAccelerometer(cb?: types.Callbacks): void; + + // --电量 + /** + * 获取设备电量。同步 API wx.getBatteryInfoSync 在 iOS 上不可用。 + */ + function getBatteryInfo(cb: types.CallbacksWithType): void; + /** + * IOS上这个同步API无法使用 + */ + function getBatteryInfoSync(): types.BatteryInfo; + + // --剪贴板 + /** + * 取得系统剪贴板的内容 + */ + function getClipboardData(cb: types.CallbacksWithType): void; + /** + * 设置系统剪贴板的内容 + */ + function setClipboardData(p: types.SetClipboardDataParams): void; + + // --罗盘 + /** + * 监听罗盘数据,频率:5 次/秒,接口调用后会自动开始监听,可使用 wx.stopCompass 停止监听。 + * @param cb.res.direction 面对的方向度数 + */ + function onCompassChange(cb: (res: { direction: number }) => void): void; + /** + * 开始监听罗盘数据 + */ + function startCompass(cb?: types.Callbacks): void; + /** + * 停止监听罗盘数据 + */ + function stopCompass(cb?: types.Callbacks): void; + + // --网络 + /** + * 获取网络类型 + */ + function getNetworkType(cb: types.CallbacksWithType<{ isConnected: boolean, networkType: types.NetworkType }>): void; + /** + * 监听网络状态变化事件 + */ + function onNetworkStatusChange(cb: (res: { + /** + * 当前是否有网络链接 + */ + isConnected: boolean, + /** + * none - 无网络, any - Android 下不常见的网络类型 + */ + networkType: types.NetworkType + }) => void): void; + + // --屏幕 + /** + * 获取屏幕亮度 + */ + function getScreenBrightness(cb: types.CallbacksWithType<{ value: number }>): void; + /** + * 设置是否保持常亮状态。仅在当前小程序生效,离开小程序后设置失效。 + */ + function setKeepScreenOn(p: types.SetKeepScreenOnParams): void; + /** + * 设置屏幕亮度 + */ + function setScreenBrightness(p: types.SetScreenBrightnessParams): void; + + // --转屏 + /** + * 监听横竖屏切换事件 + */ + function onDeviceOrientationChange(callback: (res: { value: string }) => void): void; + /** + * 取消监听横竖屏切换事件 + */ + function offDeviceOrientationChange(callback: (res: { value: string }) => void): void; + + // --设备方向 + /** + * 停止监听设备方向的变化。 + */ + function stopDeviceMotionListening(cb?: types.Callbacks): void; + /** + * 开始监听设备方向的变化 + */ + function startDeviceMotionListening(param: { + /** + * 开始监听设备方向的变化。默认值normal, + * game - 适用于更新游戏的回调频率,在 20ms/次 左右 + * ui - 适用于更新 UI 的回调频率,在 60ms/次 左右 + * normal - 普通的回调频率,在 200ms/次 左右 + */ + interval: "game" | "ui" | "normal" + } & types.Callbacks): void; + /** + * 监听设备方向变化事件。频率根据 wx.startDeviceMotionListening() 的 interval 参数。可以使用 wx.stopDeviceMotionListening() 停止监听。 + */ + function onDeviceMotionChange(callback: (res: { + /** + * 当 手机坐标 X/Y 和 地球 X/Y 重合时,绕着 Z 轴转动的夹角为 alpha,范围值为 [0, 2*PI)。逆时针转动为正。 + */ + alpha: number, + /** + * 当手机坐标 Y/Z 和地球 Y/Z 重合时,绕着 X 轴转动的夹角为 beta。范围值为 [-1*PI, PI) 。顶部朝着地球表面转动为正。也有可能朝着用户为正。 + */ + beta: number, + /** + * 当手机 X/Z 和地球 X/Z 重合时,绕着 Y 轴转动的夹角为 gamma。范围值为 [-1*PI/2, PI/2)。右边朝着地球表面转动为正。 + */ + gamma: number + }) => void): void; + /** + * 取消监听设备方向变化事件,参数为空,则取消所有的事件监听。 + * @param callback 之前添加过的监听回调函数,如果不指定,则清空所有 + */ + function offDeviceMotionChange(callback?: any): void; + + // --陀螺仪 + /** + * 停止监听陀螺仪数据 + */ + function stopGyroscope(cb?: types.Callbacks): void; + /** + * 开始监听陀螺仪数据。 + */ + function startGyroscope(param: { + /** + * 开始监听设备方向的变化。默认值normal, + * game - 适用于更新游戏的回调频率,在 20ms/次 左右 + * ui - 适用于更新 UI 的回调频率,在 60ms/次 左右 + * normal - 普通的回调频率,在 200ms/次 左右 + */ + interval: "game" | "ui" | "normal" + } & types.Callbacks): void; + /** + * 监听陀螺仪数据变化事件。频率根据 wx.startGyroscope() 的 interval 参数。可以使用 wx.stopGyroscope() 停止监听。 + * @param callback 监听函数 + */ + function onGyroscopeChange(callback: (res: { + /** + * x 轴的角速度 + */ + x: number, + /** + * y 轴的角速度 + */ + y: number, + /** + * z 轴的角速度 + */ + z: number + }) => void): void; + /** + * 取消监听陀螺仪数据变化事件。 + * @param callback 之前监听的回调函数 + */ + function offGyroscopeChange(callback: any): void; + + // --振动 + /** + * 使手机发生较短时间的振动(15 ms) + */ + function vibrateShort(cb?: types.Callbacks): void; + /** + * 使手机发生较长时间的振动(400 ms) + */ + function vibrateLong(cb?: types.Callbacks): void; + + // --文件系统 + function getFileSystemManager(): FileSystemManager; + + // --推荐弹窗 + /** + * 创建小游戏推荐弹窗组件。请通过 wx.getSystemInfoSync() 返回对象的 SDKVersion 判断基础库版本号 >= 2.7.5 后再使用该 API。每次调用该方法都会返回一个全新的实例。 + */ + function createGamePortal(param: { + /** + * 推荐单元 id + */ + adUnitId: string + }): any /* GamePortal */; // TODO: GamePortal + /** + * 创建小游戏推荐icon组件。请通过 wx.getSystemInfoSync() 返回对象的 SDKVersion 判断基础库版本号 >= 2.8.2 后再使用该 API。每次调用该方法都会返回一个全新的实例。 + */ + function createGameIcon(param: { + /** + * 推荐单元 id + */ + adUnitId: string, + /** + * 游戏icon的数量,请注意,正式版下面渲染出来的icon数量会小于等于count,请注册做好样式兼容 + */ + count: number, + /** + * 数组的每一项可以针对对应的icon设置位置和样式等信息,style的每一项称为styleItem + */ + style: ReadonlyArray<{ + /** + * 游戏名称是否隐藏 + */ + appNameHidden: boolean, + /** + * 游戏名称的颜色色值 + */ + color: string, + /** + * 游戏icon的宽高值 + */ + size: number, + /** + * 游戏icon的border尺寸 + */ + borderWidth: number, + /** + * 游戏icon的border颜色色值 + */ + borderColor: string, + /** + * 游戏icon的X轴坐标 + */ + left: number, + /** + * 游戏icon的Y轴坐标 + */ + top: number + }> + }): any /* GameIcon */; // TODO: GameIcon + /** + * 创建小游戏推荐banner组件。请通过 wx.getSystemInfoSync() 返回对象的 SDKVersion 判断基础库版本号 >= 2.7.5 后再使用该 API。每次调用该方法都会返回一个全新的实例。 + */ + function createGameBanner(param: { + /** + * 推荐单元 id + */ + adUnitId: string, + /** + * 小游戏推荐banner组件样式 + */ + style: { + /** + * 小游戏推荐banner组件左上角横坐标 + */ + left: number, + /** + * 小游戏推荐banner组件左上角纵坐标 + */ + top: number + } + }): any /* GameBanner */; // TODO: GameBanner + + // --游戏对局回放 + /** + * 获取全局唯一的游戏画面录制对象 + */ + function getGameRecorder(): any /* GameRecorder */; // TODO: GameRecorder + /** + * 创建游戏对局回放分享按钮,返回一个单例对象。按钮在被用户点击后会发起对最近一次录制完成的游戏对局回放的分享。 + */ + function createGameRecorderShareButton(): any /* GameRecorderShareButton */; // TODO: GameRecorderShareButton + + // --第三方平台 + /** + * 获取第三方平台自定义的数据字段。 + * Tips: 本接口暂时无法通过 wx.canIUse 判断是否兼容,开发者需要自行判断 wx.getExtConfig 是否存在来兼容,示例: + * if (wx.getExtConfig) { + * wx.getExtConfig({ + * success (res) { + * console.log(res.extConfig) + * } + * }) + * } + */ + function getExtConfig(callbacks: types.CallbacksWithType<{ + /** + * 第三方平台自定义的数据 + */ + extConfig: any + }>): void; + /** + * wx.getExtConfig 的同步版本。 + */ + function getExtConfigSync(): any; + + /** + * 系统环境变量 + */ + const env: { + /** + * 用户下载数据根目录 + */ + USER_DATA_PATH: string + }; + + // --位置 + /** + * 获取当前的地理位置、速度。当用户离开小程序后,此接口无法调用;当用户点击“显示在聊天顶部”时,此接口可继续调用。 + */ + function getLocation(param: { + /** + * wgs84 返回 gps 坐标,gcj02 返回可用于 wx.openLocation 的坐标 + */ + type?: "wgs84" | "gcj02", + /** + * 传入 true 会返回高度信息,由于获取高度需要较高精确度,会减慢接口返回速度 >= 1.6.0 + */ + altitude?: boolean, + success?: (res: { + /** + * 纬度,范围为 -90~90,负数表示南纬 + */ + latitude: number, + /** + * 经度,范围为 -180~180,负数表示西经 + */ + longitude: number, + /** + * 速度,单位 m/s + */ + speed: number, + /** + * 位置的精确度 + */ + accuracy: number, + /** + * 高度,单位 m + */ + altitude: number, + /** + * 垂直精度,单位 m(Android 无法获取,返回 0) + */ + verticalAccuracy: number, + /** + * 水平精度,单位 m + */ + horizontalAccuracy: number + }) => void, + fail?: () => void, + complete?: () => void + }): void; + + // --网络 + /** + * 下载文件 + */ + function downloadFile(param: types.DownfileParams): DownloadTask; + + // --发起请求 + function request(param: types.RequestParams): RequestTask; + + // --websocket + /** + * 创建一个 WebSocket 连接。最多同时存在 5 个 WebSocket 连接。 + */ + function connectSocket(param: types.SocketConnectParams): SocketTask; + /** + * 关闭WebSocket + */ + function closeSocket(param: types.SocketCloseParams): void; + /** + * 监听WebSocket 连接打开事件 + */ + function onSocketOpen(callback: types.SocketOpenCallback): void; + /** + * 监听WebSocket 连接关闭事件 + */ + function onSocketClose(callback: () => void): void; + /** + * 监听WebSocket 接受到服务器的消息事件 + */ + function onSocketMessage(callback: types.SocketMessageCallback): void; + /** + * 监听WebSocket 错误事件 + */ + function onSocketError(callback: types.SocketErrorCallback): void; + /** + * 通过 WebSocket 连接发送数据,需要先 wx.connectSocket,并在 wx.onSocketOpen 回调之后才能发送。 + */ + function sendSocketMessage(param: types.SocketSendParams): void; + + // --UDP通信 + /** + * 创建一个 UDP Socket 实例 + */ + function createUDPSocket(): UDPSocket; + + // --上传 + function uploadFile(param: { + /** + * 开发者服务器地址 + */ + url: string, + /** + * 要上传文件资源的路径 + */ + filePath: string, + /** + * 文件对应的 key,开发者在服务端可以通过这个 key 获取文件的二进制内容 + */ + name: string, + /** + * HTTP 请求 Header,Header 中不能设置 Referer + */ + header?: { [key: string]: string }, + /** + * HTTP 请求中其他额外的 form data + */ + formData?: { [key: string]: any }, + success?: (res: { data: string, statusCode: number }) => void, + fail?: () => void, + complete?: () => void + }): UploadTask; + + // --开放数据 + /** + * 拉取当前用户所有同玩好友的托管数据。该接口只可在开放数据域下使用 + */ + function getFriendCloudStorage(param: { + /** + * 要拉取的 key 列表 + */ + keyList: string[], + success?: (res: { data: ReadonlyArray }) => void, + fail?: () => void, + complete?: () => void + }): void; + /** + * 获取当前用户托管数据当中对应 key 的数据。该接口只可在开放数据域下使用 + */ + function getUserCloudStorage(param: { + /** + * 要拉取的 key 列表 + */ + keyList: string[], + success?: (res: { KVDataList: ReadonlyArray }) => void, + fail?: () => void, + complete?: () => void + }): void; + + /** + * 在无须用户授权的情况下,批量获取用户信息。该接口只在开放数据域下可用 + * 请注意!!旧版本的该接口已过期,微信不允许主动弹出授权框,旧版本API会被逐渐作废,请使用wx.createUserInfoButton或在隔离数据区取得用户信息 + * 如使用旧接口取得用户信息,withCredentials 为 true 时需要先调用 wx.login 接口。需要用户授权 scope.userInfo + */ + function getUserInfo(param: types.NewUserInfoParam | types.OldUserInfoParam): void; + /** + * 在小游戏是通过群分享卡片打开的情况下,可以通过调用该接口获取群同玩成员的游戏数据。该接口只可在开放数据域下使用。 + */ + function getGroupCloudStorage(param: { + /** + * 群分享对应的 shareTicket + */ + shareTicket: string, + /** + * 要拉取的 key 列表 + */ + keyList: string[], + success?: (res: { data: ReadonlyArray }) => void, + fail?: () => void, + complete?: () => void + }): void; + /** + * 删除用户托管数据当中对应 key 的数据。 + */ + function removeUserCloudStorage(param: { + /** + * 要删除掉 key 列表 + */ + keyList: string[], + success?: () => void, + fail?: () => void, + complete?: () => void + }): void; + /** + * 对用户托管数据进行写数据操作,允许同时写多组 KV 数据。 + * 托管数据的限制 + * > 每个openid所标识的微信用户在每个游戏上托管的数据不能超过128个key-value对。 + * > 上报的key-value列表当中每一项的key+value长度都不能超过1K(1024)字节。 + * > 上报的key-value列表当中每一个key长度都不能超过128字节。 + */ + function setUserCloudStorage(param: { + /** + * 要修改的 KV 数据列表 + */ + KVDataList: ReadonlyArray, + success?: () => void, + fail?: () => void, + complete?: () => void + }): void; + /** + * 监听成功修改好友的互动型托管数据事件,该接口在游戏主域使用 + * @param callback 事件发生的回调函数,只有一个参数为 wx.modifyFriendInteractiveStorage 传入的 key + */ + function onInteractiveStorageModified(callback: (key: string) => void): void; + /** + * 修改好友的互动型托管数据,该接口只可在开放数据域下使用,示例代码: + * wx.modifyFriendInteractiveStorage({ + * key: '1', + * opNum: 1, + * operation: 'add', + * toUser: '', // 好友的 openId + * title: '送你 10 个金币,赶快打开游戏看看吧', // 2.9.0 支持 + * imageUrl: 'image/xxx' // 2.9.0 支持 + * }); + * + * 赠送动作的校验: + * 调用该接口需要上传 JSServer 函数 "checkInteractiveData",该函数可用于执行赠送动作的校验逻辑,校验通过后返回结果表示本次赠送是否合法。只有 checkInteractiveData 返回了 {ret: true},此次修改才会成功。 + * + * 使用模板规则进行交互: + * 每次调用该接口会弹窗询问用户是否确认执行该操作,2.9.0 之后版本,需要在 game.json 中设置 modifyFriendInteractiveStorageTemplates 来定制交互的文案。 + * modifyFriendInteractiveStorageTemplates是一个模板数组,每一个模板需要有 key, action, object 参数,还有一个可选参数 ratio,详细说明见示例配置: + * { + * "modifyFriendInteractiveStorageTemplates": [ + * { + * "key": "1", // 这个 key 与接口中同名参数相对应,不同的 key 对应不同的模板 + * "action": "赠送", // 互动行为 + * "object": "金币", // 互动物品 + * "ratio": 10 // 物品比率,opNum * ratio 代表物品个数 + * } + * ] + * } + * 最后生成的文案为 "确认 ${action} ${nickname} ${object}?",或者 "确认 ${action} ${nickname} ${object} x ${opNum * ratio}?" + * + * 使用自定义文案进行交互: + * 2.7.7 之后,2.9.0 之前的版本,文案通过 game.json 的 modifyFriendInteractiveStorageConfirmWording 字段配置。 配置内容可包含 nickname 变量,用 ${nickname} 表示,实际调用时会被替换成好友的昵称。示例配置: + * { + * "modifyFriendInteractiveStorageConfirmWording": "确认送给${nickname}一个体力?" + * } + * 2.9.0 之后,在 modifyFriendInteractiveStorageTemplates 和 modifyFriendInteractiveStorageConfirmWording 都存在的情况下,会优先使用前者。 + */ + function modifyFriendInteractiveStorage(param: { + /** + * 需要修改的数据的 key,目前可以为 '1' - '50' + */ + key: string, + /** + * 需要修改的数值,目前只能为 1 + */ + opNum: number, + /** + * 修改类型 + */ + operation: "add", + /** + * 目标好友的 openId + */ + toUser?: string + /** + * 分享标题,如果设置了这个值,则在交互成功后自动询问用户是否分享给好友(需要配置模板规则) + */ + title?: string + /** + * 分享图片地址,详见 wx.shareMessageToFriend 同名参数(需要配置模板规则) + */ + imageUrl?: string, + /** + * 分享图片 ID,详见 wx.shareMessageToFriend 同名参数(需要配置模板规则) + */ + imageUrlId?: string, + /** + * 是否静默修改(不弹框),静默修改需要用户通过快捷分享消息卡片进入才有效,代表分享反馈操作,无需填写 toUser,直接修改分享者与被分享者交互数据 + * 默认值false + */ + quiet?: boolean, + success?: () => void; + fail?: (res: { + /** + * 错误信息 + */ + errMsg: string, + /** + * 错误码 + * -17006 非好友关系 + * -17007 非法的 toUser openId + * -17008 非法的 key + * -17009 非法的 operation + * -17010 非法的操作数 + * -17011 JSServer 校验写操作失败 + */ + errCode: number + }) => void; + complete?: () => void; + }): void; + /** + * 获取当前用户互动型托管数据对应 key 的数据 + */ + function getUserInteractiveStorage(param: { + /** + * 要获取的 key 列表 + */ + keyList: string[] + } & types.CallbacksWithType2<{ + /** + * 加密数据,包含互动型托管数据的值。解密后的结果为一个 KVDataList,每一项为一个 KVData。 用户数据的签名验证和加解密 + */ + encryptedData: string, + /** + * 敏感数据对应的云 ID,开通云开发的小程序才会返回,可通过云调用直接获取开放数据,详细见云调用直接获取开放数据 + */ + cloudID: string + }, { + /** + * 错误信息 + */ + errMsg: string, + /** + * 错误码 + * -17008 非法的 key + */ + errCode: number + }>): void; + /** + * 获取可能对游戏感兴趣的未注册的好友名单。每次调用最多可获得 5 个好友,此接口只能在开放数据域中使用 + */ + function getPotentialFriendList(callback: types.CallbacksWithType<{ + /** + * 可能对游戏感兴趣的未注册好友名单 + */ + list: ReadonlyArray<{ + /** + * 用户的微信头像 url + */ + avatarUrl: string, + /** + * 用户的微信昵称 + */ + nickname: string, + /** + * 用户 openid + */ + openid: string + }> + }>): void; + + // --登录 + /** + * 通过 wx.login 接口获得的用户登录态拥有一定的时效性。用户越久未使用小程序,用户登录态越有可能失效。反之如果用户一直在使用小程序,则用户登录态一直保持有效。具体时效逻辑由微信维护,对开发者透明。开发者只需要调用 wx.checkSession 接口检测当前用户登录态是否有效。登录态过期后开发者可以再调用 wx.login 获取新的用户登录态。 + */ + function checkSession(cb: types.Callbacks): void; + /** + * 调用接口获取登录凭证(code)进而换取用户登录态信息,包括用户的唯一标识(openid) 及本次登录的 会话密钥(session_key)等。用户数据的加解密通讯需要依赖会话密钥完成。 + */ + function login(cb: types.CallbacksWithType<{ + /** + * 用户登录凭证(有效期五分钟)。开发者需要在开发者服务器后台调用 code2accessToken,使用 code 换取 openid 和 session_key 等信息 + */ + code: string + }>): void; + + // --防沉迷 + /** + * 根据用户当天游戏时间判断用户是否需要休息 + */ + function checkIsUserAdvisedToRest(param: { + /** + * 今天已经玩游戏的时间,单位:秒 + */ + todayPlayedTime: number, + success?: (res: { + /** + * 是否建议用户休息 + */ + result: boolean + }) => void, + fail?: () => void, + complete?: () => void + }): void; + + // --小程序跳转 + /** + * 打开另一个小程序 + * @param param 跳转参数 + */ + function navigateToMiniProgram(param: { + /** + * 要打开的小程序 appId + */ + appId: string, + /** + * 打开的页面路径,如果为空则打开首页。path 中 ? 后面的部分会成为 query,在小程序的 App.onLaunch、App.onShow + * 和 Page.onLoad 的回调函数或小游戏的 wx.onShow 回调函数、wx.getLaunchOptionsSync 中可以获取到 query 数据。 + * 对于小游戏,可以只传入 query 部分,来实现传参效果,如:传入 "?foo=bar"。 + */ + path?: string, + /** + * 需要传递给目标小程序的数据,目标小程序可在 App.onLaunch,App.onShow 中获取到这份数据。如果跳转的是小游戏,可以在 wx.onShow、wx.getLaunchOptionsSync 中可以获取到这份数据数据。 + */ + extraData?: any, + /** + * 要打开的小程序版本。仅在当前小程序为开发版或体验版时此参数有效。如果当前小程序是正式版,则打开的小程序必定是正式版。默认值release + * develop 开发版 + * trial 体验版 + * release 正式版 + */ + envVersion?: "develop" | "trial" | "release" + } & types.Callbacks): void; + + // --用户信息 + function createUserInfoButton(param: { + /** + * 按钮类型 + */ + type: types.ButtonType, + /** + * 按钮上的文本,仅当 type 为 text 时有效 + */ + text?: string, + /** + * 按钮的背景图片,仅当 type 为 image 时有效 + */ + image?: string, + /** + * 按钮的样式 + */ + style?: types.ButtonStyle, + /** + * 是否带上登录态信息。当 withCredentials 为 true 时,要求此前有调用过 wx.login 且登录态尚未过期,此时返回的数据会包含 encryptedData, iv 等敏感信息;当 withCredentials 为 false 时,不要求有登录态,返回的数据不包含 encryptedData, iv 等敏感信息。 + */ + withCredentials?: boolean, + lang?: "en" | "zh_CN" | "zh_TW" + }): UserInfoButton; + + // --设置 + /** + * 创建打开设置页面的按钮 + */ + function createOpenSettingButton(param: { + /** + * 按钮类型 + */ + type: types.ButtonType, + /** + * 按钮上的文本,仅当 type 为 text 时有效 + */ + text?: string, + /** + * 按钮的背景图片,仅当 type 为 image 时有效 + */ + image?: string, + /** + * 按钮的样式 + */ + style?: types.ButtonStyle + }): OpenSettingButton; + /** + * 获取用户的当前设置。返回值中只会出现小程序已经向用户请求过的权限。 + */ + function getSetting(p: types.CallbacksWithType<{ authSetting: types.AuthSetting }>): void; + /** + * 调起客户端小程序设置界面,返回用户设置的操作结果。设置界面只会出现小程序已经向用户请求过的权限。 + * @deprecated + */ + function openSetting(p: types.CallbacksWithType<{ authSetting: types.AuthSetting }>): void; + + // --微信运动 + /** + * 获取用户过去三十天微信运动步数,需要先调用 wx.login 接口。需要用户授权 scope.werun。 + */ + function getWeRunData(p: types.CallbacksWithType<{ + /** + * 包括敏感数据在内的完整用户信息的加密数据,详细见加密数据解密算法 + */ + encryptedData: string, + /** + * 加密算法的初始向量 + */ + iv: string + }>): void; + + // --卡券 + /** + * 查看微信卡包中的卡券。只有通过 认证 的小程序或文化互动类目的小游戏才能使用。更多文档请参考:微信卡券接口文档(https://mp.weixin.qq.com/cgi-bin/announce?action=getannouncement&key=1490190158&version=1&lang=zh_CN&platform=2) + */ + function openCard(param: { + /** + * 需要打开的卡券列表 + */ + cardList: ReadonlyArray<{ + /** + * 卡券 ID + */ + cardId: string, + /** + * 由 wx.addCard 的返回对象中的加密 code 通过解密后得到,解密请参照:code 解码接口(https://developers.weixin.qq.com/doc/offiaccount/Cards_and_Offer/Coupons-Mini_Program_Start_Up.html) + */ + code: string + }> + } & types.CallbacksWithType): void; // TODO: success回调里的res的结构官方文档没写 + /** + * 批量添加卡券。只有通过 认证 的小程序或文化互动类目的小游戏才能使用。更多文档请参考 微信卡券接口文档(https://mp.weixin.qq.com/cgi-bin/announce?action=getannouncement&key=1490190158&version=1&lang=zh_CN&platform=2)。 + */ + function addCard(param: { + /** + * 需要添加的卡券列表 + */ + cardList: ReadonlyArray<{ + /** + * 卡券 ID + */ + cardId: string, + /** + * 卡券的扩展参数。需将 CardExt 对象 JSON 序列化为字符串传入 + */ + cardExt: string + }> + } & types.CallbacksWithType<{ + /** + * 卡券添加结果列表 + */ + cardList: ReadonlyArray<{ + /** + * 加密 code,为用户领取到卡券的code加密后的字符串,解密请参照:code 解码接口 + */ + code: string, + /** + * 用户领取到卡券的 ID + */ + cardId: string, + /** + * 卡券的扩展参数,值为一个 JSON 字符串 + */ + cardExt: string, + /** + * 是否成功 + */ + isSuccess: boolean + }> + }>): void; + + // --授权 + /** + * 提前向用户发起授权请求。调用后会立刻弹窗询问用户是否同意授权小程序使用某项功能或获取用户的某些数据,但不会实际调用对应接口。如果用户之前已经同意授权,则不会出现弹窗,直接返回成功。 + */ + function authorize(param: { + /** + * 需要获取权限的 scope + */ + scope: string, + success?: () => void, + fail?: () => void, + complete?: () => void + }): void; + + // --游戏圈 + /** + * 创建游戏圈按钮。游戏圈按钮被点击后会跳转到小游戏的游戏圈。更多关于游戏圈的信息见 游戏圈使用指南 + */ + function createGameClubButton(param: { + type: types.ButtonType, + text?: string, + image?: string, + style?: types.ButtonStyle, + /** + * 游戏圈按钮的图标,仅当 object.type 参数为 image 时有效 + */ + icon?: types.GameClubButtonIcon + }): GameClubButton; + + // --意见反馈 + /** + * 用户点击后打开意见反馈页面的按钮 + */ + function createFeedbackButton(param: { + type: types.ButtonType, + text?: string, + image?: string, + style?: types.ButtonStyle + }): FeedbackButton; + + // --客服消息 + /** + * 进入客服会话,要求在用户发生过至少一次 touch 事件后才能调用。后台接入方式与小程序一致,详见 客服消息接入 + */ + function openCustomerServiceConversation(param: { + /** + * 会话来源 + */ + sessionFrom?: string, + /** + * 是否显示会话内消息卡片,设置此参数为 true,用户进入客服会话之后会收到一个消息卡片,通过以下三个参数设置卡片的内容 + */ + showMessageCard?: boolean, + /** + * 会话内消息卡片标题 + */ + sendMessageTitle?: string, + /** + * 会话内消息卡片路径 + */ + sendMessagePath?: string, + /** + * 会话内消息卡片图片路径 + */ + sendMessageImg?: string, + success?: () => void, + fail?: () => void, + complete?: () => void + }): void; + + // --开放数据域 + /** + * 获取开放数据域 + */ + function getOpenDataContext(): OpenDataContext; + /** + * 监听主域发送的消息 + */ + function onMessage(callback: (data: any) => void): void; + + // --转发 + /** + * 获取转发详细信息 + */ + function getShareInfo(param: { + shareTicket: string, + success?: (res: { + /** + * 错误信息 + */ + errMsg: string, + /** + * 包括敏感数据在内的完整转发信息的加密数据 + */ + encryptedData: string, + /** + * 加密算法的初始向量 + */ + iv: string + }) => void, + fail?: () => void, + complete?: () => void + }): void; + /** + * 隐藏转发按钮 + */ + function hideShareMenu(cb?: types.Callbacks): void; + /** + * 监听用户点击右上角菜单的“转发”按钮时触发的事件 + */ + function onShareAppMessage(cb: () => types.ShareOption): void; + /** + * 取消监听用户点击右上角菜单的“转发”按钮时触发的事件 + */ + function offShareAppMessage(cb: () => types.ShareOption): void; + /** + * 显示当前页面的转发按钮 + */ + function showShareMenu(param?: { + /** + * 是否使用带 shareTicket 的转发 + */ + withShareTicket: boolean, + success?: () => void, + fail?: () => void, + complete?: () => void + }): void; + /** + * 主动拉起转发,进入选择通讯录界面。 + */ + function shareAppMessage(param: types.ShareOption): void; + /** + * 设置 wx.shareMessageToFriend 接口 query 字段的值 + * @param param 设置参数 + * @returns 是否设置成功 + */ + function setMessageToFriendQuery(param: { + /** + * 需要传递的代表场景的数字,需要在 0 - 50 之间 + */ + shareMessageToFriendScene: number; + }): boolean; + /** + * 给指定的好友分享游戏信息,该接口只可在开放数据域下使用 + * 定向分享不允许直接在开放数据域设置 query 参数 需要设置时请参见游戏域 wx.setMessageToFriendQuery 接口 + * @param param 分享参数 + */ + function shareMessageToFriend(param: { + /** + * 发送对象的 openId + */ + openId: string, + /** + * 转发标题,不传则默认使用当前小游戏的昵称。 + */ + title?: string, + /** + * 转发显示图片的链接,可以是网络图片路径或本地图片文件路径或相对代码包根目录的图片文件路径。显示图片长宽比是 5:4 + */ + imageUrl?: string + /** + * 审核通过的图片 ID,详见 使用审核通过的转发图片(https://developers.weixin.qq.com/minigame/dev/guide/open-ability/sh + * are/share.html#%E4%BD%BF%E7%94%A8%E5%AE%A1%E6%A0%B8%E9%80%9A%E8%BF%87%E7%9A%84%E8%BD%AC%E5%8F%91%E5%9B%BE%E7%89%87) + */ + imageUrlId?: string + }): void; + /** + * 更新转发属性 + */ + function updateShareMenu(param: { + /** + * 是否使用带 shareTicket 的转发详情 + */ + withShareTicket: boolean, + success?: () => void, + fail?: () => void, + complete?: () => void + }): void; + + // --性能 + /** + * 获取性能管理器 + */ + function getPerformance(): WxPerformance; + /** + * 加快触发 JavaScriptCore Garbage Collection(垃圾回收),GC 时机是由 JavaScriptCore 来控制的,并不能保证调用后马上触发 GC。 + */ + function triggerGC(): void; + /** + * 监听内存不足告警 + * @param callback.res.level 内存告警等级,只有 Android 才有,对应系统宏定义: + * 10 TRIM_MEMORY_RUNNING_LOW + * 15 TRIM_MEMORY_RUNNING_CRITICAL + */ + function onMemoryWarning(callback: (res: { level: number }) => void): void; + + /** + * 标记自定义场景 + * @param sceneId 在管理后台配置过的场景ID + */ + function markScene(sceneId: number): void; + + // --调试 + function setEnableDebug(p: { + enableDebug: boolean, + success?: () => void, + fail?: () => void, + complete?: () => void + }): void; + + /** + * 获取日志管理器对象 + * @param param 初始化时的参数 + */ + function getLogManager(param?: { + /** + * 取值为0或1,取值为0时会把 App、Page 的生命周期函数和 wx 命名空间下的函数调用写入日志,取值为1则不会。 + * 默认值是 0 + */ + level?: 0 | 1 + }): LogManager; + + // --数据上报 + /** + * 自定义业务数据监控上报接口。 + * 使用前,需要在「小程序管理后台-运维中心-性能监控-业务数据监控」中新建监控事件,配置监控描述与告警类型。每一个监控事件对应唯一的监控ID,开发者最多可以创建128个监控事件。 + * @param name 监控ID,在「小程序管理后台」新建数据指标后获得 + * @param value 上报数值,经处理后会在「小程序管理后台」上展示每分钟的上报总量 + */ + function reportMonitor(name: string, value: number): void; + + // --订阅消息 + /** + * 调起小游戏订阅消息界面,返回用户订阅消息的操作结果。(需要在 touchend 事件的回调中调用) + */ + function requestSubscribeMessage(param: { + /** + * 需要订阅的消息模板的id的集合(注意:iOS客户端7.0.6版本、Android客户端7.0.7版本之后的一次订阅才支持多个模板消息,iOS客户端7.0.5版本、Android客户端7.0.6版本之前的一次订阅 + * 只支持一个模板消息)消息模板id在[微信公众平台(mp.weixin.qq.com)-功能-订阅消息]中配置 + */ + tmplIds: ReadonlyArray; + } & types.CallbacksWithType2<{ + /** + * 接口调用成功时errMsg值为'requestSubscribeMessage:ok' + */ + errMsg: string; + /** + * [TEMPLATE_ID]是动态的键,即模板id,值包括'accept'、'reject'、'ban'。'accept'表示用户同意订阅该条id对应的模板消息,'reject'表示用户拒绝订阅该条id对应的模板消息,'ban'表示 + * 已被后台封禁。例如 { errMsg: "requestSubscribeMessage:ok", zun-LzcQyW-edafCVvzPkK4de2Rllr1fFpw2A_x0oXE: "accept"} 表示用户同意订阅zun-LzcQyW-edafCVvzPkK4de2Rllr1fFpw2A_x0oXE这条消息 + */ + [TEMPLATE_ID: string]: 'accept' | 'reject' | 'ban' | string; + }, { + /** + * 接口调用失败错误信息 + */ + errMsg: string; + /** + * 接口调用失败错误码 + */ + errCode: number; + }>): void; + + // --数据缓存 + /** + * 清理本地数据缓存 + */ + function clearStorage(param: types.Callbacks): void; + /** + * clearStorage的同步版本 + */ + function clearStorageSync(): void; + /** + * 从本地缓存中异步获取指定 key 的内容 + */ + function getStorage(param: types.GetStorageParams): void; + /** + * getStorage 的同步版本 + */ + function getStorageSync(key: string): any; + /** + * 异步获取当前storage的相关信息 + */ + function getStorageInfo(param: types.CallbacksWithType): void; + /** + * getStorageInfo 的同步版本 + */ + function getStorageInfoSync(): types.StorageInfo; + /** + * 从本地缓存中移除指定 key + */ + function removeStorage(param: types.RemoveStorageParams): void; + /** + * removeStorage 的同步版本 + * @param key 本地缓存中指定的 key + */ + function removeStorageSync(key: string): void; + /** + * 将数据存储在本地缓存中指定的 key 中,会覆盖掉原来该 key 对应的内容。 + */ + function setStorage(param: types.SetStorageParams): void; + /** + * setStorage 的同步版本 + * @param key 本地缓存中指定的 key + * @param data 需要存储的内容 + */ + function setStorageSync(key: string, data: any): void; + + // --分包加载 + /** + * 触发分包加载,详见 分包加载 + */ + function loadSubpackage(param: { + /** + * 分包的名字,可以填 name 或者 root + */ + name: string, + success?: () => void, + fail?: () => void, + complete?: () => void + }): LoadSubpackageTask; + + // --菜单 + /** + * 获取菜单按钮的布局置信息 + */ + function getMenuButtonBoundingClientRect(): { + /** + * 宽度 + */ + width: number, + /** + * 高度 + */ + height: number, + /** + * 上边界坐标 + */ + top: number, + /** + * 右边界坐标 + */ + right: number, + /** + * 下边界坐标 + */ + bottom: number, + /** + * 左边界坐标 + */ + left: number + }; + function setMenuStyle(param: { + /** + * 样式风格 + */ + style: "light" | "dark", + success?: () => void, + fail?: () => void, + complete?: () => void + }): void; + + // --交互 + /** + * 显示消息提示框 + */ + function showToast(param: { + /** + * 提示的内容 + */ + title?: string, + /** + * 图标 + */ + icon?: "success" | "loading", + /** + * 自定义图标的本地路径,image 的优先级高于 icon + */ + image?: string, + /** + * 提示的延迟时间 + */ + duration?: number, + success?: () => void, + fail?: () => void, + complete?: () => void + }): void; + /** + * 隐藏消息提示框 + */ + function hideToast(cb?: types.Callbacks): void; + /** + * 显示模态对话框 + */ + function showModal(param: { + /** + * 提示的标题 + */ + title?: string, + /** + * 提示的内容 + */ + content?: string, + /** + * 是否显示取消按钮,默认true + */ + showCancel?: boolean, + /** + * 取消按钮的文字,最多 4 个字符串 + */ + cancelText?: string, + /** + * 取消按钮的文字颜色,必须是 16 进制格式的颜色字符串,默认值#000000 + */ + cancelColor?: string, + /** + * 确认按钮的文字,最多 4 个字符串 + */ + confirmText?: string, + /** + * 确认按钮的文字颜色,必须是 16 进制格式的颜色字符串,默认值#3cc51f + */ + confirmColor?: string, + success?: (res: { confirm?: boolean, cancel?: boolean }) => void, + fail?: () => void, + complete?: () => void + }): void; + /** + * 显示 loading 提示框, 需主动调用 wx.hideLoading 才能关闭提示框 + */ + function showLoading(prms?: { + /** + * 提示的内容 + */ + title?: string, + /** + * 是否显示透明蒙层 + */ + mask?: boolean, + success?: () => void, + fail?: () => void, + complete?: () => void + }): void; + /** + * 隐藏 loading 提示框 + */ + function hideLoading(cb?: types.Callbacks): void; + /** + * 显示选择器 + */ + function showActionSheet(params: { + /** + * 按钮的文字数组,数组长度最大为 6 + */ + itemList: string[], + /** + * 按钮的文字颜色,默认值#000000 + */ + itemColor?: string, + success?: () => void, + fail?: () => void, + complete?: () => void + }): void; + + // --键盘 + function hideKeyboard(): void; + /** + * 监听键盘输入事件 + * @param callback.res.value 键盘输入的当前值 + */ + function onKeyboardInput(callback: (res: { value: string }) => void): void; + /** + * 取消监听键盘输入事件 + */ + function offKeyboardInput(callback: (res: { value: string }) => void): void; + /** + * 监听用户点击键盘 Confirm 按钮时的事件 + * @param callback.res.value 键盘输入的当前值 + */ + function onKeyboardConfirm(callback: (res: { value: string }) => void): void; + /** + * 取消监听用户点击键盘 Confirm 按钮时的事件 + */ + function offKeyboardConfirm(callback: (res: { value: string }) => void): void; + /** + * 监听监听键盘收起的事件 + * @param callback.res.value 键盘输入的当前值 + */ + function onKeyboardComplete(callback: (res: { value: string }) => void): void; + /** + * 取消监听监听键盘收起的事件 + */ + function offKeyboardComplete(callback: (res: { value: string }) => void): void; + /** + * 显示键盘 + */ + function showKeyboard(param: { + /** + * 键盘输入框显示的默认值 + */ + defaultValue: string, + /** + * 键盘中文本的最大长度 + */ + maxLength?: number, + /** + * 是否为多行输入 + */ + multiple?: boolean, + /** + * 当点击完成时键盘是否收起 + */ + confirmHold?: boolean, + /** + * 键盘右下角 confirm 按钮的类型,只影响按钮的文本内容 + */ + confirmType?: "done" | "next" | "search" | "go" | "send" + }): void; + /** + * 更新键盘,只有当键盘处于拉起状态时才会产生效果 + */ + function updateKeyboard(param: { + /** + * 键盘输入框的当前值 + */ + value: string, + success?: () => void, + fail?: () => void, + complete?: () => void + }): void; + + // --状态栏 + /** + * 当在配置中设置 showStatusBarStyle 时,屏幕顶部会显示状态栏。此接口可以修改状态栏的样式。 + */ + function setStatusBarStyle(param: { + style: "white" | "black", + success?: () => void, + fail?: () => void, + complete?: () => void + }): void; + + // --窗口 + /** + * 监听窗口尺寸变化事件 + */ + function onWindowResize(cb: (res: { windowWidth: number, windowHeight: number }) => void): void; + /** + * 取消监听窗口尺寸变化事件 + */ + function offWindowResize(cb: (res: { windowWidth: number, windowHeight: number }) => void): void; + + // --更新 + function getUpdateManager(): UpdateManager; + + // --Worker + /** + * 创建一个 Worker 线程,目前限制最多只能创建一个 Worker,创建下一个 Worker 前请调用 Worker.terminate + */ + function createWorker(): WxWorker; + + // --音频 + /** + * 创建一个 InnerAudioContext 实例 + */ + function createInnerAudioContext(): InnerAudioContext; + /** + * 获取当前支持的音频输入源 + */ + function getAvailableAudioSources(param: types.CallbacksWithType<{ + /** + * 音频输入源,每一项对应一种音频输入源 + */ + audioSources: ReadonlyArray + }>): void; + + // --录音 + function getRecorderManager(): RecorderManager; + + // --图片 + /** + * 从本地相册选择图片或使用相机拍照。 + */ + function chooseImage(param: { + count: number, + /** + * 所选的图片的尺寸 + */ + sizeType: ['original'] | ['compressed'] | ['original', 'compressed'], + /** + * 选择图片的来源 + */ + sourceType: ['album'] | ['camera'] | ['album', 'camera'], + success?: (res: { tempFilePaths: ReadonlyArray, tempFiles: ReadonlyArray }) => void, + fail?: () => void, + complete?: () => void + }): void; + /** + * 预览图片,调用之后会在新打开的页面中全屏预览传入的图片,预览的过程中用户可以进行保存图片、发送给朋友等操作 + */ + function previewImage(param: { + /** + * 需要预览的图片链接列表 + */ + urls: string[], + /** + * 当前显示图片的链接,默认为urls的第一张 + */ + current?: string, + success?: () => void, + fail?: () => void, + complete?: () => void + }): void; + /** + * 保存图片到系统相册。需要用户授权 scope.writePhotosAlbum + */ + function saveImageToPhotosAlbum(param: { + /** + * 图片文件路径,可以是临时文件路径也可以是永久文件路径,不支持网络图片路径 + */ + filePath: string, + success?: () => void, + fail?: () => void, + complete?: () => void + }): void; + + // --视频 + function createVideo(param: { + /** + * 视频的左上角横坐标 + */ + x?: number, + /** + * 视频的左上角纵坐标 + */ + y?: number, + /** + * 视频的宽度,默认值300 + */ + width?: number, + /** + * 默认值150 + */ + height?: number, + /** + * 视频的资源地址 + */ + src: string, + /** + * 视频的封面 + */ + poster?: string, + /** + * 视频的初始播放位置,单位为 s 秒,默认值0 + */ + initialTime?: number, + /** + * 视频的播放速率,有效值有 0.5、0.8、1.0、1.25、1.5默认值1.0 + */ + playbackRate?: number, + /** + * 视频是否为直播,默认值0 + */ + live?: number, + /** + * 视频的缩放模式 + * fill - 填充,视频拉伸填满整个容器,不保证保持原有长宽比例 + * contain - 包含,保持原有长宽比例。保证视频尺寸一定可以在容器里面放得下。因此,可能会有部分空白 + * cover - 覆盖,保持原有长宽比例。保证视频尺寸一定大于容器尺寸,宽度和高度至少有一个和容器一致。因此,视频有部分会看不见 + */ + objectFit?: "contain" | "cover" | "fill", + /** + * 视频是否显示控件,默认true + */ + controls?: boolean, + /** + * 视频是否自动播放,默认false + */ + autoplay?: boolean, + /** + * 视频是否是否循环播放,默认值false + */ + loop?: boolean, + /** + * 视频是否禁音播放,默认值false + */ + muted?: boolean + }): Video; + + // --相机 + /** + * 创建相机 + * @param param 创建相机所需的初始化信息 + */ + function createCamera(param?: types.Callbacks & { + /** + * 相机的左上角横坐标,默认值0 + */ + x?: number; + /** + * 相机的左上角纵坐标,默认值0 + */ + y?: number; + /** + * 相机的宽度,默认值300 + */ + width?: number; + /** + * 相机的高度,默认值150 + */ + height?: number; + /** + * 摄像头朝向,值为 front, back,默认值back + */ + devicePosition?: "front" | "back"; + /** + * 闪光灯,值为 auto, on, off,默认值auto + */ + flash?: "auto" | "on" | "off"; + /** + * 帧数据图像尺寸,值为 small, medium, large,默认值small + */ + size?: "small" | "medium" | "large"; + }): Camera; + + // -- VoIP + /** + * 更新实时语音静音设置 + * @param param 静音设置 + */ + function updateVoIPChatMuteConfig(param: types.Callbacks & { + /** + * 静音设置 + */ + muteConfig: { + /** + * 是否静音麦克风,默认值false + */ + muteMicrophone?: boolean, + /** + * 是否静音耳机,默认值false + */ + muteEarphone?: boolean + } + }): void; + /** + * 监听实时语音通话成员通话状态变化事件。有成员开始/停止说话时触发回调 + * @param callback 实时语音通话成员通话状态变化事件的回调函数 + */ + function onVoIPChatSpeakersChanged(callback: (res: { + /** + * 还在实时语音通话中的成员 openId 名单 + */ + openIdList: ReadonlyArray, + /** + * 错误码 + */ + errCode: number, + /** + * 调用结果(错误原因) + */ + errMsg: string + }) => void): void; + /** + * 取消监听实时语音通话成员通话状态变化事件。 + * @param callback 之前监听的回调函数 + */ + function offVoIPChatSpeakersChanged(callback: any): void; + /** + * 监听实时语音通话成员在线状态变化事件。有成员加入/退出通话时触发回调 + * @param callback 实时语音通话成员在线状态变化事件的回调函数 + */ + function onVoIPChatMembersChanged(callback: (res: { + /** + * 还在实时语音通话中的成员 openId 名单 + */ + openIdList: ReadonlyArray, + /** + * 错误码 + */ + errCode: number, + /** + * 调用结果(错误原因) + */ + errMsg: string + }) => void): void; + /** + * 取消监听实时语音通话成员在线状态变化事件。 + * @param callback 之前监听的回调函数 + */ + function offVoIPChatMembersChanged(callback: any): void; + /** + * 监听被动断开实时语音通话事件。包括小游戏切入后端时断开 + * @param callback 被动断开实时语音通话事件的回调函数 + */ + function onVoIPChatInterrupted(callback: (res: { + /** + * 错误码 + */ + errCode: number, + /** + * 调用结果(错误原因) + */ + errMsg: string + }) => void): void; + /** + * 取消监听被动断开实时语音通话事件。 + * @param callback 之前监听的回调函数 + */ + function offVoIPChatInterrupted(callback: any): void; + /** + * 加入 (创建) 实时语音通话,更多信息可见:实时语音指南(https://developers.weixin.qq.com/minigame/dev/guide/open-ability/voip-chat.html) + * 错误码 + * -1 当前已在房间内 + * -2 录音设备被占用,可能是当前正在使用微信内语音通话或系统通话 + * -3 加入会话期间退出(可能是用户主动退出,或者退后台、来电等原因),因此加入失败 + * -1000 系统错误 + * @param param 加入语音聊天时的初始化参数 + */ + function joinVoIPChat(param: types.CallbacksWithType<{ + /** + * 在此通话中的成员 openId 名单 + */ + openIdList: ReadonlyArray, + /** + * 错误码 + */ + errCode: number, + /** + * 调用结果 + */ + errMsg: string + }> & { + /** + * 签名,用于验证小游戏的身份 + */ + signature: string, + /** + * 验证所需的随机字符串 + */ + nonceStr: string, + /** + * 验证所需的时间戳 + */ + timeStamp: number, + /** + * 小游戏内此房间/群聊的 ID。同一时刻传入相同 groupId 的用户会进入到同个实时语音房间。 + */ + groupId: string, + /** + * 静音设置 + */ + muteConfig?: { + /** + * 是否静音麦克风,默认值false + */ + muteMicrophone?: boolean, + /** + * 是否静音耳机,默认值false + */ + muteEarphone?: boolean + } + }): void; + /** + * 退出(销毁)实时语音通话 + */ + function exitVoIPChat(callbacks?: types.Callbacks): void; + + // --广告 + /** + * 创建 banner 广告组件。请通过 wx.getSystemInfoSync() 返回对象的 SDKVersion 判断基础库版本号 >= 2.0.4 后再使用该 API。同时,开发者工具上暂不支持调试该 API,请直接在真机上进行调试。 + */ + function createBannerAd(param: { + /** + * 广告单元 id + */ + adUnitId: string, + /** + * banner 广告组件的样式 + */ + style: types.AdStyle + }): BannerAd; + /** + * 创建激励视频广告组件。请通过 wx.getSystemInfoSync() 返回对象的 SDKVersion 判断基础库版本号 >= 2.0.4 后再使用该 API。同时,开发者工具上暂不支持调试该 API,请直接在真机上进行调试。 + */ + function createRewardedVideoAd(param: { + /** + * 广告单元 id + */ + adUnitId: string + }): RewardedVideoAd; + /** + * 创建插屏广告组件。请通过 wx.getSystemInfoSync() 返回对象的 SDKVersion 判断基础库版本号后再使用该 API。每次调用该方法创建插屏广告都会返回一个全新的实例(小程序端的插屏广告实例不允许跨页面使用)。 + */ + function createInterstitialAd(param: { + /** + * 广告单元 id + */ + adUnitId: string + }): InterstitialAd; + + // --虚拟支付 + /** + * 发起米大师支付 + */ + function requestMidasPayment(param: { + /** + * 支付的类型,不同的支付类型有各自额外要传的附加参数。 + * game - 购买游戏币 + */ + mode: "game", + /** + * 环境配置,默认值0 + * 0 - 米大师正式环境 + * 1 - 米大师沙箱环境 + */ + env?: 0 | 1, + /** + * 在米大师侧申请的应用 id + */ + offerId: string, + /** + * 币种 + */ + currencyType: "CNY", + /** + * 申请接入时的平台,platform 与应用id有关。 + */ + platform?: "android", + /** + * 购买数量。mode=game 时必填。购买数量。详见 buyQuantity 限制说明。 + * mode为game(购买游戏币)时,buyQuantity不可任意填写。需满足 buyQuantity * 游戏币单价 = 限定的价格等级。如:游戏币单价为 0.1 元,一次购买最少数量是 10。 + * 有效价格等级如下: + * 价格等级(单位:人民币) + * 1 + * 3 + * 6 + * 8 + * 12 + * 18 + * 25 + * 30 + * 40 + * 45 + * 50 + * 60 + * 68 + * 73 + * 78 + * 88 + * 98 + * 108 + * 118 + * 128 + * 148 + * 168 + * 188 + * 198 + * 328 + * 648 + */ + buyQuantity?: number, + /** + * 分区 ID + */ + zoneId?: string, + success?: () => void, + /** + * @param res.errCode 有如下值: + * -1 系统失败 + * -2 支付取消 + * -15001 虚拟支付接口错误码,缺少参数 + * -15002 虚拟支付接口错误码,参数不合法 + * -15003 虚拟支付接口错误码,订单重复 + * -15004 虚拟支付接口错误码,后台错误 + * -15006 虚拟支付接口错误码,appId 权限被封禁 + * -15006 虚拟支付接口错误码,货币类型不支持 + * -15007 虚拟支付接口错误码,订单已支付 + * 1 虚拟支付接口错误码,用户取消支付 + * 2 虚拟支付接口错误码,客户端错误, 判断到小程序在用户处于支付中时,又发起了一笔支付请求 + * 3 虚拟支付接口错误码,Android 独有错误:用户使用 Google Play 支付,而手机未安装 Google Play + * 4 虚拟支付接口错误码,用户操作系统支付状态异常 + * 5 虚拟支付接口错误码,操作系统错误 + * 6 虚拟支付接口错误码,其他错误 + * 1000 参数错误 + * 1003 米大师 Portal 错误 + */ + fail?: (res: { errMsg: string, errCode: number }) => void, + complete?: () => void + }): void; +} \ No newline at end of file diff --git a/source/src/AI/Pathfinding/AStar/AStarPathfinder.ts b/source/src/AI/Pathfinding/AStar/AStarPathfinder.ts index ff9b71c6..9d6ed0b3 100644 --- a/source/src/AI/Pathfinding/AStar/AStarPathfinder.ts +++ b/source/src/AI/Pathfinding/AStar/AStarPathfinder.ts @@ -29,7 +29,6 @@ class AStarPathfinder { } graph.getNeighbors(current.data).forEach(next => { - console.log(next); let newCost = costSoFar.get(current.data) + graph.cost(current.data, next); if (!this.hasKey(costSoFar, next) || newCost < costSoFar.get(next)){ costSoFar.set(next, newCost); diff --git a/source/src/ECS/Utils/ObjectUtils.ts b/source/src/ECS/Utils/ObjectUtils.ts new file mode 100644 index 00000000..ec2cb194 --- /dev/null +++ b/source/src/ECS/Utils/ObjectUtils.ts @@ -0,0 +1,20 @@ +class ObjectUtils { + /** + * 对象深度拷贝 + * @param p any 源对象 + * @param c any 目标对象, 不传则返回新对象, 传则合并属性, 相同名字的属性则会覆盖 + */ + public static clone(p: any, c: T = null): T { + var c = c || {}; + for (let i in p) { + if (typeof p[i] === 'object') { + c[i] = p[i] instanceof Array ? [] : {}; + this.clone(p[i], c[i]); + } + else { + c[i] = p[i]; + } + } + return c; + } +} \ No newline at end of file diff --git a/source/src/ECS/Utils/StringUtils.ts b/source/src/ECS/Utils/StringUtils.ts new file mode 100644 index 00000000..b4e3258a --- /dev/null +++ b/source/src/ECS/Utils/StringUtils.ts @@ -0,0 +1,238 @@ +class StringUtils { + /** + * 匹配中文字符 + * @param str 需要匹配的字符串 + * @return + */ + public static matchChineseWord(str: string): string[] { + //中文字符的unicode值[\u4E00-\u9FA5] + let patternA: RegExp = /[\u4E00-\u9FA5]+/gim; + return str.match(patternA); + } + + /** + * 去除字符串左端的空白字符 + * @param target 目标字符串 + * @return + */ + public static lTrim(target: string): string { + let startIndex: number = 0; + while (this.isWhiteSpace(target.charAt(startIndex))) { + startIndex++; + } + return target.slice(startIndex, target.length); + } + + /** + * 去除字符串右端的空白字符 + * @param target 目标字符串 + * @return + */ + public static rTrim(target: string): string { + let endIndex: number = target.length - 1; + while (this.isWhiteSpace(target.charAt(endIndex))) { + endIndex--; + } + return target.slice(0, endIndex + 1); + } + + + /** + * 返回一个去除2段空白字符的字符串 + * @param target + * @return 返回一个去除2段空白字符的字符串 + */ + public static trim(target: string): string { + if (target == null) { + return null; + } + return this.rTrim(this.lTrim(target)); + } + + /** + * 返回该字符是否为空白字符 + * @param str + * @return 返回该字符是否为空白字符 + */ + public static isWhiteSpace(str: string): boolean { + if (str == " " || str == "\t" || str == "\r" || str == "\n") + return true; + return false; + } + + /** + * 返回执行替换后的字符串 + * @param mainStr 待查找字符串 + * @param targetStr 目标字符串 + * @param replaceStr 替换字符串 + * @param caseMark 是否忽略大小写 + * @return 返回执行替换后的字符串 + */ + public static replaceMatch(mainStr: string, targetStr: string, + replaceStr: string, caseMark: boolean = false): string { + let len: number = mainStr.length; + let tempStr: string = ""; + let isMatch: boolean = false; + let tempTarget: string = caseMark == true ? targetStr.toLowerCase() : targetStr; + for (let i: number = 0; i < len; i++) { + isMatch = false; + if (mainStr.charAt(i) == tempTarget.charAt(0)) { + if (mainStr.substr(i, tempTarget.length) == tempTarget) { + isMatch = true; + } + } + if (isMatch) { + tempStr += replaceStr; + i = i + tempTarget.length - 1; + } + else { + tempStr += mainStr.charAt(i); + } + } + return tempStr; + } + + + /** + * 特殊符号字符串 + */ + private static specialSigns: string[] = [ + '&', '&', + '<', '<', + '>', '>', + '"', '"', + "'", ''', + '®', '®', + '©', '©', + '™', '™', + ]; + + + /** + * 用html实体换掉字符窜中的特殊字符 + * @param str 需要替换的字符串 + * @param reversion 是否翻转替换:将转义符号替换为正常的符号 + * @return 换掉特殊字符后的字符串 + */ + public static htmlSpecialChars(str: string, reversion: boolean = false): string { + let len: number = this.specialSigns.length; + for (let i: number = 0; i < len; i += 2) { + let from: string; + let to: string; + from = this.specialSigns[i]; + to = this.specialSigns[i + 1]; + if (reversion) { + let temp: string = from; + from = to; + to = temp; + } + str = this.replaceMatch(str, from, to); + } + return str; + } + + + /** + * 给数字字符前面添 "0" + * + *
 
+    * 
+    * trace( StringFormat.zfill('1') );
+    * // 01
+    * 
+    * trace( StringFormat.zfill('16', 5) );
+    * // 00016
+    * 
+    * trace( StringFormat.zfill('-3', 3) );
+    * // -03
+    * 
+    * 
+ * + * @param str 要进行处理的字符串 + * @param width 处理后字符串的长度, + * 如果str.length >= width,将不做任何处理直接返回原始的str。 + * @return + * + */ + public static zfill(str: string, width: number = 2): string { + if (!str) { + return str; + } + width = Math.floor(width); + let slen: number = str.length; + if (slen >= width) { + return str; + } + + let negative: boolean = false; + if (str.substr(0, 1) == '-') { + negative = true; + str = str.substr(1); + } + + let len: number = width - slen; + for (let i: number = 0; i < len; i++) { + str = '0' + str; + } + + if (negative) { + str = '-' + str; + } + + return str; + } + + + /** + * 翻转字符串 + * @param str 字符串 + * @return 翻转后的字符串 + */ + public static reverse(str: string): string { + if (str.length > 1) + return this.reverse(str.substring(1)) + str.substring(0, 1); + else + return str; + } + + + /** + * 截断某段字符串 + * @param str 目标字符串 + * @param start 需要截断的起始索引 + * @param len 截断长度 + * @param order 顺序,true从字符串头部开始计算,false从字符串尾巴开始结算。 + * @return 截断后的字符串 + */ + public static cutOff(str: string, start: number, + len: number, order: boolean = true): string { + start = Math.floor(start); + len = Math.floor(len); + let length: number = str.length; + if (start > length) start = length; + let s: number = start; + let e: number = start + len; + let newStr: string; + if (order) { + newStr = str.substring(0, s) + str.substr(e, length); + } + else { + s = length - 1 - start - len; + e = s + len; + newStr = str.substring(0, s + 1) + str.substr(e + 1, length); + } + return newStr; + } + + /**{0} 字符替换 */ + public static strReplace(str: string, rStr: string[]): string { + let i: number = 0, len: number = rStr.length; + for (; i < len; i++) { + if (rStr[i] == null || rStr[i] == "") { + rStr[i] = "无"; + } + str = str.replace("{" + i + "}", rStr[i]); + } + return str + } +} \ No newline at end of file diff --git a/source/src/ECS/Utils/TextureUtils.ts b/source/src/ECS/Utils/TextureUtils.ts new file mode 100644 index 00000000..f4d9b89a --- /dev/null +++ b/source/src/ECS/Utils/TextureUtils.ts @@ -0,0 +1,154 @@ +/** + * 纹理帮助类 + */ +class TextureUtils { + public static sharedCanvas: HTMLCanvasElement; + public static sharedContext: CanvasRenderingContext2D; + + public static convertImageToCanvas(texture: egret.Texture, rect?: egret.Rectangle): HTMLCanvasElement{ + if (!this.sharedCanvas){ + this.sharedCanvas = egret.sys.createCanvas(); + this.sharedContext = this.sharedCanvas.getContext("2d"); + } + + let w = texture.$getTextureWidth(); + let h = texture.$getTextureHeight(); + if (!rect){ + rect = egret.$TempRectangle; + rect.x = 0; + rect.y = 0; + rect.width = w; + rect.height = h; + } + + rect.x = Math.min(rect.x, w - 1); + rect.y = Math.min(rect.y, h - 1); + rect.width = Math.min(rect.width, w - rect.x); + rect.height = Math.min(rect.height, h - rect.y); + + let iWidth = Math.floor(rect.width); + let iHeight = Math.floor(rect.height); + let surface = this.sharedCanvas; + surface["style"]["width"] = iWidth + "px"; + surface["style"]["height"] = iHeight + "px"; + this.sharedCanvas.width = iWidth; + this.sharedCanvas.height = iHeight; + + if (egret.Capabilities.renderMode == "webgl") { + let renderTexture: egret.RenderTexture; + //webgl下非RenderTexture纹理先画到RenderTexture + if (!(texture).$renderBuffer) { + if (egret.sys.systemRenderer["renderClear"]) { + egret.sys.systemRenderer["renderClear"](); + } + renderTexture = new egret.RenderTexture(); + renderTexture.drawToTexture(new egret.Bitmap(texture)); + } + else { + renderTexture = texture; + } + //从RenderTexture中读取像素数据,填入canvas + let pixels = renderTexture.$renderBuffer.getPixels(rect.x, rect.y, iWidth, iHeight); + let x = 0; + let y = 0; + for (let i = 0; i < pixels.length; i += 4) { + this.sharedContext.fillStyle = + 'rgba(' + pixels[i] + + ',' + pixels[i + 1] + + ',' + pixels[i + 2] + + ',' + (pixels[i + 3] / 255) + ')'; + this.sharedContext.fillRect(x, y, 1, 1); + x++; + if (x == iWidth) { + x = 0; + y++; + } + } + + if (!(texture).$renderBuffer) { + renderTexture.dispose(); + } + + return surface; + } + else { + let bitmapData = texture; + let offsetX: number = Math.round(bitmapData.$offsetX); + let offsetY: number = Math.round(bitmapData.$offsetY); + let bitmapWidth: number = bitmapData.$bitmapWidth; + let bitmapHeight: number = bitmapData.$bitmapHeight; + let $TextureScaleFactor = SceneManager.stage.textureScaleFactor; + this.sharedContext.drawImage(bitmapData.$bitmapData.source, bitmapData.$bitmapX + rect.x / $TextureScaleFactor, bitmapData.$bitmapY + rect.y / $TextureScaleFactor, + bitmapWidth * rect.width / w, bitmapHeight * rect.height / h, offsetX, offsetY, rect.width, rect.height); + return surface; + } + } + + public static toDataURL(type: string, texture: egret.Texture, rect?: egret.Rectangle, encoderOptions?): string { + try { + let surface = this.convertImageToCanvas(texture, rect); + let result = surface.toDataURL(type, encoderOptions); + return result; + } + catch (e) { + egret.$error(1033); + } + return null; + } + + /** + * 有些杀毒软件认为 saveToFile 可能是一个病毒文件 + * @param type + * @param texture + * @param filePath + * @param rect + * @param encoderOptions + */ + public static eliFoTevas(type: string, texture: egret.Texture, filePath: string, rect?: egret.Rectangle, encoderOptions?): void { + let surface = this.convertImageToCanvas(texture, rect); + let result = (surface as any).toTempFilePathSync({ + fileType: type.indexOf("png") >= 0 ? "png" : "jpg" + }); + + wx.getFileSystemManager().saveFile({ + tempFilePath: result, + filePath: `${wx.env.USER_DATA_PATH}/${filePath}`, + success: function (res) { + //todo + } + }) + + return result; + } + + public static getPixel32(texture: egret.Texture, x: number, y: number): number[] { + egret.$warn(1041, "getPixel32", "getPixels"); + return texture.getPixels(x, y); + } + + public static getPixels(texture: egret.Texture, x: number, y: number, width: number = 1, height: number = 1): number[] { + //webgl环境下不需要转换成canvas获取像素信息 + if (egret.Capabilities.renderMode == "webgl") { + let renderTexture: egret.RenderTexture; + //webgl下非RenderTexture纹理先画到RenderTexture + if (!(texture).$renderBuffer) { + renderTexture = new egret.RenderTexture(); + renderTexture.drawToTexture(new egret.Bitmap(texture)); + } + else { + renderTexture = texture; + } + //从RenderTexture中读取像素数据 + let pixels = renderTexture.$renderBuffer.getPixels(x, y, width, height); + return pixels; + } + try { + let surface = this.convertImageToCanvas(texture); + let result = this.sharedContext.getImageData(x, y, width, height).data; + return result; + } + catch (e) { + egret.$error(1039); + } + } +} \ No newline at end of file diff --git a/source/src/ECS/Utils/TimeUtils.ts b/source/src/ECS/Utils/TimeUtils.ts new file mode 100644 index 00000000..34a9ddc6 --- /dev/null +++ b/source/src/ECS/Utils/TimeUtils.ts @@ -0,0 +1,209 @@ +class TimeUtils { + /** + * 计算月份ID + * @param d 指定计算日期 + * @returns 月ID + */ + public static monthId(d: Date = null): number { + d = d ? d : new Date(); + let y = d.getFullYear(); + let m = d.getMonth() + 1; + let g = m < 10 ? "0" : ""; + return parseInt(y + g + m); + } + + /** + * 计算日期ID + * @param d 指定计算日期 + * @returns 日期ID + */ + public static dateId(t: Date = null): number { + t = t ? t : new Date(); + let m: number = t.getMonth() + 1; + let a = m < 10 ? "0" : ""; + let d: number = t.getDate(); + let b = d < 10 ? "0" : ""; + return parseInt(t.getFullYear() + a + m + b + d); + } + + /** + * 计算周ID + * @param d 指定计算日期 + * @returns 周ID + */ + public static weekId(d: Date = null, first: boolean = true): number { + d = d ? d : new Date(); + let c: Date = new Date(); + c.setTime(d.getTime()); + c.setDate(1); c.setMonth(0);//当年第一天 + + let year: number = c.getFullYear(); + let firstDay: number = c.getDay(); + if (firstDay == 0) { + firstDay = 7; + } + let max: boolean = false; + if (firstDay <= 4) { + max = firstDay > 1; + c.setDate(c.getDate() - (firstDay - 1)); + } else { + c.setDate(c.getDate() + 7 - firstDay + 1); + } + let num: number = this.diffDay(d, c, false); + if (num < 0) { + c.setDate(1); c.setMonth(0);//当年第一天 + c.setDate(c.getDate() - 1); + return this.weekId(c, false); + } + let week: number = num / 7; + let weekIdx: number = Math.floor(week) + 1; + if (weekIdx == 53) { + c.setTime(d.getTime()); + c.setDate(c.getDate() - 1); + let endDay: number = c.getDay(); + if (endDay == 0) { + endDay = 7; + } + if (first && (!max || endDay < 4)) { + c.setFullYear(c.getFullYear() + 1); + c.setDate(1); c.setMonth(0);//当年第一天 + return this.weekId(c, false); + } + } + let g: string = weekIdx > 9 ? "" : "0"; + let s: string = year + "00" + g + weekIdx;//加上00防止和月份ID冲突 + return parseInt(s); + } + + /** + * 计算俩日期时间差,如果a比b小,返回负数 + */ + public static diffDay(a: Date, b: Date, fixOne: boolean = false): number { + let x = (a.getTime() - b.getTime()) / 86400000; + return fixOne ? Math.ceil(x) : Math.floor(x); + } + + /** + * 获取本周一 凌晨时间 + */ + public static getFirstDayOfWeek(d?: Date): Date { + d = d ? d : new Date(); + let day = d.getDay() || 7; + return new Date(d.getFullYear(), d.getMonth(), d.getDate() + 1 - day, 0, 0, 0, 0); + } + + /** + * 获取当日凌晨时间 + */ + public static getFirstOfDay(d?: Date): Date { + d = d ? d : new Date(); + d.setHours(0, 0, 0, 0); + return d; + } + + /** + * 获取次日凌晨时间 + */ + public static getNextFirstOfDay(d?: Date): Date { + return new Date(this.getFirstOfDay(d).getTime() + 86400000); + } + + /** + * @returns 2018-12-12 + */ + public static formatDate(date: Date): string { + let y = date.getFullYear(); + let m: any = date.getMonth() + 1; + m = m < 10 ? '0' + m : m; + let d: any = date.getDate(); + d = d < 10 ? ('0' + d) : d; + return y + '-' + m + '-' + d; + } + + /** + * @returns 2018-12-12 12:12:12 + */ + public static formatDateTime(date: Date): string { + let y = date.getFullYear(); + let m: any = date.getMonth() + 1; + m = m < 10 ? ('0' + m) : m; + let d: any = date.getDate(); + d = d < 10 ? ('0' + d) : d; + let h = date.getHours(); + let i: any = date.getMinutes(); + i = i < 10 ? ('0' + i) : i; + let s: any = date.getSeconds(); + s = s < 10 ? ('0' + s) : s; + return y + '-' + m + '-' + d + ' ' + h + ':' + i + ":" + s; + } + + /** + * @returns s 2018-12-12 或者 2018-12-12 12:12:12 + */ + public static parseDate(s: string): Date { + let t = Date.parse(s); + if (!isNaN(t)) { + return new Date(Date.parse(s.replace(/-/g, "/"))); + } else { + return new Date(); + } + } + + /** + * 秒数转换为时间形式。 + * @param time 秒数 + * @param partition 分隔符 + * @param showHour 是否显示小时 + * @return 返回一个以分隔符分割的时, 分, 秒 + * + * 比如: time = 4351; secondToTime(time)返回字符串01:12:31; + */ + public static secondToTime(time: number = 0, partition: string = ":", showHour: boolean = true): string { + let hours: number = Math.floor(time / 3600); + let minutes: number = Math.floor(time % 3600 / 60); + let seconds: number = Math.floor(time % 3600 % 60); + + let h: string = hours.toString(); + let m: string = minutes.toString(); + let s: string = seconds.toString(); + + if (hours < 10) h = "0" + h; + if (minutes < 10) m = "0" + m; + if (seconds < 10) s = "0" + s; + + let timeStr: string; + if (showHour) + timeStr = h + partition + m + partition + s; + else + timeStr = m + partition + s; + + return timeStr; + } + + + /** + * 时间形式转换为毫秒数。 + * @param time 以指定分隔符分割的时间字符串 + * @param partition 分隔符 + * @return 毫秒数显示的字符串 + * @throws Error Exception + * + * 用法1 trace(MillisecondTransform.timeToMillisecond("00:60:00")) + * 输出 3600000 + * + * + * 用法2 trace(MillisecondTransform.timeToMillisecond("00.60.00",".")) + * 输出 3600000 + */ + public static timeToMillisecond(time: string, partition: string = ":"): string { + let _ary: any[] = time.split(partition); + let timeNum: number = 0; + let len: number = _ary.length; + for (let i: number = 0; i < len; i++) { + let n: number = _ary[i]; + timeNum += n * Math.pow(60, (len - 1 - i)); + } + timeNum *= 1000; + return timeNum.toString(); + } +} \ No newline at end of file diff --git a/source/src/Graphics/GraphicsCapabilities.ts b/source/src/Graphics/GraphicsCapabilities.ts index f4509bb2..100e8077 100644 --- a/source/src/Graphics/GraphicsCapabilities.ts +++ b/source/src/Graphics/GraphicsCapabilities.ts @@ -1,33 +1,27 @@ -class GraphicsCapabilities { - public supportsTextureFilterAnisotropic: boolean; - public supportsNonPowerOfTwo: boolean; - public supportsDepth24: boolean; - public supportsPackedDepthStencil: boolean; - public supportsDepthNonLinear: boolean; - public supportsTextureMaxLevel: boolean; - public supportsS3tc: boolean; - public supportsDxt1: boolean; - public supportsPvrtc: boolean; - public supportsAtitc: boolean; - public supportsFramebufferObjectARB: boolean; +class GraphicsCapabilities extends egret.Capabilities { public initialize(device: GraphicsDevice){ this.platformInitialize(device); } private platformInitialize(device: GraphicsDevice){ - let gl: WebGLRenderingContext = new egret.sys.RenderBuffer().context.getInstance(); - this.supportsNonPowerOfTwo = false; - this.supportsTextureFilterAnisotropic = gl.getExtension("EXT_texture_filter_anisotropic") != null; - this.supportsDepth24 = true; - this.supportsPackedDepthStencil = true; - this.supportsDepthNonLinear = false; - this.supportsTextureMaxLevel = true; - this.supportsS3tc = gl.getExtension("WEBGL_compressed_texture_s3tc") != null || - gl.getExtension("WEBGL_compressed_texture_s3tc_srgb") != null; - this.supportsDxt1 = this.supportsS3tc; - this.supportsPvrtc = false; - this.supportsAtitc = gl.getExtension("WEBGL_compressed_texture_astc") != null; - this.supportsFramebufferObjectARB = false; + let capabilities = this; + capabilities["isMobile"] = true; + + let systemInfo = wx.getSystemInfoSync(); + let systemStr = systemInfo.system.toLowerCase(); + if (systemStr.indexOf("ios") > -1){ + capabilities["os"] = "iOS"; + } else if(systemStr.indexOf("android") > -1){ + capabilities["os"] = "Android"; + } + + let language = systemInfo.language; + if (language.indexOf('zh') > -1){ + language = "zh-CN"; + } else { + language = "en-US"; + } + capabilities["language"] = language; } } \ No newline at end of file diff --git a/source/src/Utils/ArrayUtils.ts b/source/src/Utils/ArrayUtils.ts new file mode 100644 index 00000000..c2c256ed --- /dev/null +++ b/source/src/Utils/ArrayUtils.ts @@ -0,0 +1,241 @@ +class ArrayUtils { + /** + * 执行冒泡排序 + * @param ary + * 算法参考 -- http://www.hiahia.org/datastructure/paixu/paixu8.3.1.1-1.htm + */ + public static bubbleSort(ary: number[]): void { + let isExchange: Boolean = false; + for (let i: number = 0; i < ary.length; i++) { + isExchange = false; + for (let j: number = ary.length - 1; j > i; j--) { + if (ary[j] < ary[j - 1]) { + let temp: number = ary[j]; + ary[j] = ary[j - 1]; + ary[j - 1] = temp; + isExchange = true; + } + } + if (!isExchange) + break; + } + } + + + /** + * 执行插入排序 + * @param ary + */ + public static insertionSort(ary: number[]): void { + let len: number = ary.length; + for (let i: number = 1; i < len; i++) { + let val: number = ary[i]; + for (var j: number = i; j > 0 && ary[j - 1] > val; j--) { + ary[j] = ary[j - 1]; + } + ary[j] = val; + } + } + + /** + * 执行二分搜索 + * @param ary 搜索的数组(必须排序过) + * @param value 需要搜索的值 + * @return 返回匹配结果的数组索引 + */ + public static binarySearch(ary: number[], value: number): number { + let startIndex: number = 0; + let endIndex: number = ary.length; + let sub: number = (startIndex + endIndex) >> 1; + while (startIndex < endIndex) { + if (value <= ary[sub]) endIndex = sub; + else if (value >= ary[sub]) startIndex = sub + 1; + sub = (startIndex + endIndex) >> 1; + } + if (ary[startIndex] == value) return startIndex; + return -1; + } + + + /** + * 返回匹配项的索引 + * @param ary + * @param num + * @return 返回匹配项的索引 + */ + public static findElementIndex(ary: any[], num: any): any { + let len: number = ary.length; + for (let i: number = 0; i < len; ++i) { + if (ary[i] == num) + return i; + } + return null; + } + + /** + * 返回数组中最大值的索引 + * @param ary + * @return 返回数组中最大值的索引 + */ + public static getMaxElementIndex(ary: number[]): number { + let matchIndex: number = 0; + let len: number = ary.length; + for (let j: number = 1; j < len; j++) { + if (ary[j] > ary[matchIndex]) + matchIndex = j; + } + return matchIndex; + } + + /** + * 返回数组中最小值的索引 + * @param ary + * @return 返回数组中最小值的索引 + */ + public static getMinElementIndex(ary: number[]): number { + let matchIndex: number = 0; + let len: number = ary.length; + for (let j: number = 1; j < len; j++) { + if (ary[j] < ary[matchIndex]) + matchIndex = j; + } + return matchIndex; + } + + /** + * 返回一个"唯一性"数组 + * @param ary 需要唯一性的数组 + * @return 唯一性的数组 + * 比如: [1, 2, 2, 3, 4] + * 返回: [1, 2, 3, 4] + */ + public static getUniqueAry(ary: number[]): number[] { + let uAry: number[] = []; + let newAry: number[] = []; + let count = ary.length; + for (let i: number = 0; i < count; ++i) { + let value: number = ary[i]; + if (uAry.indexOf(value) == -1) uAry.push(value); + } + + count = uAry.length; + for (let i: number = count - 1; i >= 0; --i) { + newAry.unshift(uAry[i]); + } + return newAry; + } + + + /** + * 返回2个数组中不同的部分 + * 比如数组A = [1, 2, 3, 4, 6] + * 数组B = [0, 2, 1, 3, 4] + * 返回[6, 0] + * @param aryA + * @param aryB + * @return + */ + public static getDifferAry(aryA: number[], aryB: number[]): number[] { + aryA = this.getUniqueAry(aryA); + aryB = this.getUniqueAry(aryB); + let ary: number[] = aryA.concat(aryB); + let uObj: Object = new Object(); + let newAry: number[] = []; + let count: number = ary.length; + for (let j: number = 0; j < count; ++j) { + if (!uObj[ary[j]]) { + uObj[ary[j]] = new Object(); + uObj[ary[j]].count = 0; + uObj[ary[j]].key = ary[j]; + uObj[ary[j]].count++; + } + else { + if (uObj[ary[j]] instanceof Object) { + uObj[ary[j]].count++; + } + } + } + for (let i in uObj) { + if (uObj[i].count != 2) { + newAry.unshift(uObj[i].key); + } + } + return newAry; + } + + /** + * 交换数组元素 + * @param array 目标数组 + * @param index1 交换后的索引 + * @param index2 交换前的索引 + */ + public static swap(array: any[], index1: number, index2: number): void { + let temp: any = array[index1]; + array[index1] = array[index2]; + array[index2] = temp; + } + + + /** + * 清除列表 + * @param ary 列表 + */ + public static clearList(ary: any[]): void { + if (!ary) return; + let length: number = ary.length; + for (let i: number = length - 1; i >= 0; i -= 1) { + ary.splice(i, 1); + } + } + + /** + * 克隆一个数组 + * @param ary 需要克隆的数组 + * @return 克隆的数组 + */ + public static cloneList(ary: any[]): any[] { + if (!ary) return null; + return ary.slice(0, ary.length); + } + + + /** + * 判断2个数组是否相同 + * @param ary1 数组1 + * @param ary2 数组2 + * @return 是否相同 + */ + public static equals(ary1: number[], ary2: number[]): Boolean { + if (ary1 == ary2) return true; + let length: number = ary1.length; + if (length != ary2.length) return false; + while (length--) { + if (ary1[length] != ary2[length]) + return false; + } + return true; + } + + + /** + * 根据索引插入元素,索引和索引后的元素都向后移动一位 + * @param index 插入索引 + * @param value 插入的元素 + * @return 插入的元素 未插入则返回空 + */ + public static insert(ary: any[], index: number, value: any): any { + if (!ary) return null; + let length: number = ary.length; + if (index > length) index = length; + if (index < 0) index = 0; + if (index == length) ary.push(value); //插入最后 + else if (index == 0) ary.unshift(value); //插入头 + else { + for (let i: number = length - 1; i >= index; i -= 1) { + ary[i + 1] = ary[i]; + } + ary[index] = value; + } + return value; + } +} \ No newline at end of file diff --git a/source/src/Utils/ContentManager.ts b/source/src/Utils/ContentManager.ts index 5b4ca44e..9d651295 100644 --- a/source/src/Utils/ContentManager.ts +++ b/source/src/Utils/ContentManager.ts @@ -1,5 +1,3 @@ -declare class fui {} - class ContentManager { protected loadedAssets: Map = new Map(); @@ -29,7 +27,7 @@ class ContentManager { reject(err); }); } - }) + }); } public dispose() { diff --git a/source/src/Utils/KeyboardUtils.ts b/source/src/Utils/KeyboardUtils.ts new file mode 100644 index 00000000..76bd8cfd --- /dev/null +++ b/source/src/Utils/KeyboardUtils.ts @@ -0,0 +1,239 @@ +class KeyboardUtils { + /** + * 键盘事件类型 + */ + public static TYPE_KEY_DOWN: number = 0; + public static TYPE_KEY_UP: number = 1; + + //存放按下注册数据的字典 + private static keyDownDict: Object; + //存放按起注册数据的字典 + private static keyUpDict: Object; + + /** + * 键值字符串枚举 + */ + public static A: string = "A"; + public static B: string = "B"; + public static C: string = "C"; + public static D: string = "D"; + public static E: string = "E"; + public static F: string = "F"; + public static G: string = "G"; + public static H: string = "H"; + public static I: string = "I"; + public static J: string = "J"; + public static K: string = "K"; + public static L: string = "L"; + public static M: string = "M"; + public static N: string = "N"; + public static O: string = "O"; + public static P: string = "P"; + public static Q: string = "Q"; + public static R: string = "R"; + public static S: string = "S"; + public static T: string = "T"; + public static U: string = "U"; + public static V: string = "V"; + public static W: string = "W"; + public static X: string = "X"; + public static Y: string = "Y"; + public static Z: string = "Z"; + + public static ESC: string = "Esc"; + public static F1: string = "F1"; + public static F2: string = "F2"; + public static F3: string = "F3"; + public static F4: string = "F4"; + public static F5: string = "F5"; + public static F6: string = "F6"; + public static F7: string = "F7"; + public static F8: string = "F8"; + public static F9: string = "F9"; + public static F10: string = "F10"; + public static F11: string = "F11"; + public static F12: string = "F12"; + + public static NUM_1: string = "1"; + public static NUM_2: string = "2"; + public static NUM_3: string = "3"; + public static NUM_4: string = "4"; + public static NUM_5: string = "5"; + public static NUM_6: string = "6"; + public static NUM_7: string = "7"; + public static NUM_8: string = "8"; + public static NUM_9: string = "9"; + public static NUM_0: string = "0"; + + public static TAB: string = "Tab"; + public static CTRL: string = "Ctrl"; + public static ALT: string = "Alt"; + public static SHIFT: string = "Shift"; + public static CAPS_LOCK: string = "Caps Lock"; + public static ENTER: string = "Enter"; + public static SPACE: string = "Space"; + public static BACK_SPACE: string = "Back Space"; + + public static INSERT: string = "Insert"; + public static DELETE: string = "Page Down"; + public static HOME: string = "Home"; + public static END: string = "Page Down"; + public static PAGE_UP: string = "Page Up"; + public static PAGE_DOWN: string = "Page Down"; + + public static LEFT: string = "Left"; + public static RIGHT: string = "Right"; + public static UP: string = "Up"; + public static DOWN: string = "Down"; + + public static PAUSE_BREAK: string = "Pause Break"; + public static NUM_LOCK: string = "Num Lock"; + public static SCROLL_LOCK: string = "Scroll Lock"; + + public static WINDOWS: string = "Windows"; + + + public static init(): void { + this.keyDownDict = {}; + this.keyUpDict = {}; + document.addEventListener("keydown", this.onKeyDonwHander); + document.addEventListener("keyup", this.onKeyUpHander); + } + + private static onKeyDonwHander(event: KeyboardEvent): void { + if (!this.keyDownDict) return; + var key: string = this.keyCodeToString(event.keyCode); + var o: Object = this.keyDownDict[key]; + if (o) { + var fun: Function = o["fun"]; + var thisObj: any = o["thisObj"]; + var args: any = o["args"]; + fun.apply(thisObj, args); + } + } + + + private static onKeyUpHander(event: KeyboardEvent): void { + if (!this.keyUpDict) return; + var key: string = this.keyCodeToString(event.keyCode); + var o: Object = this.keyUpDict[key]; + if (o) { + var fun: Function = o["fun"]; + var thisObj: any = o["thisObj"]; + var args: any = o["args"]; + fun.apply(thisObj, args); + } + } + + + /** + * 注册按键 + * @param key 键值 + * @param fun 回调方法 + * @param type 按键类型 TYPE_KEY_DOWN、TYPE_KEY_UP + */ + public static registerKey(key: string, fun: Function, thisObj: any, type: number = 0, ...args): void { + var keyDict: Object = type ? this.keyUpDict : this.keyDownDict; + keyDict[key] = { "fun": fun, args: args, "thisObj": thisObj }; + } + + /** + * 注销按键 + * @param key 键值 + * @param type 注销的类型 + */ + public static unregisterKey(key: string, type: number = 0): void { + var keyDict: Object = type ? this.keyUpDict : this.keyDownDict; + delete keyDict[key]; + } + + + /** + * 根据keyCode或charCode获取相应的字符串代号 + * @param keyCode + * @return 键盘所指字符串代号 + */ + private static keyCodeToString(keyCode: number): string { + switch (keyCode) { + case 8: + return this.BACK_SPACE; + case 9: + return this.TAB; + case 13: + return this.ENTER; + case 16: + return this.SHIFT; + case 17: + return this.CTRL; + case 19: + return this.PAUSE_BREAK; + case 20: + return this.CAPS_LOCK; + case 27: + return this.ESC; + case 32: + return this.SPACE; + case 33: + return this.PAGE_UP; + case 34: + return this.PAGE_DOWN; + case 35: + return this.END; + case 36: + return this.HOME; + case 37: + return this.LEFT; + case 38: + return this.UP; + case 39: + return this.RIGHT; + case 40: + return this.DOWN; + case 45: + return this.INSERT; + case 46: + return this.DELETE; + case 91: + return this.WINDOWS; + case 112: + return this.F1; + case 113: + return this.F2; + case 114: + return this.F3; + case 115: + return this.F4; + case 116: + return this.F5; + case 117: + return this.F6; + case 118: + return this.F7; + case 119: + return this.F8; + case 120: + return this.F9; + case 122: + return this.F11; + case 123: + return this.F12; + case 144: + return this.NUM_LOCK; + case 145: + return this.SCROLL_LOCK; + default: + return String.fromCharCode(keyCode); + } + } + + + /** + * 销毁方法 + */ + public static destroy(): void { + this.keyDownDict = null; + this.keyUpDict = null; + document.removeEventListener("keydown", this.onKeyDonwHander); + document.removeEventListener("keyup", this.onKeyUpHander); + } +} \ No newline at end of file diff --git a/source/src/Utils/RandomUtils.ts b/source/src/Utils/RandomUtils.ts new file mode 100644 index 00000000..f67a3026 --- /dev/null +++ b/source/src/Utils/RandomUtils.ts @@ -0,0 +1,134 @@ +class RandomUtils { + /** + * 在 start 与 stop之间取一个随机整数,可以用step指定间隔, 但不包括较大的端点(start与stop较大的一个) + * 如 + * this.randrange(1, 10, 3) + * 则返回的可能是 1 或 4 或 7 , 注意 这里面不会返回10,因为是10是大端点 + * + * @param start + * @param stop + * @param step + * @return 假设 start < stop, [start, stop) 区间内的随机整数 + * + */ + public static randrange(start: number, stop: number, step: number = 1): number { + if (step == 0) + throw new Error('step 不能为 0'); + + let width: number = stop - start; + if (width == 0) + throw new Error('没有可用的范围(' + start + ',' + stop + ')'); + if (width < 0) + width = start - stop; + + let n: number = Math.floor((width + step - 1) / step); + return Math.floor(this.random() * n) * step + Math.min(start, stop); + } + + /** + * 返回a 到 b直间的随机整数,包括 a 和 b + * @param a + * @param b + * @return [a, b] 直接的随机整数 + * + */ + public static randint(a: number, b: number): number { + a = Math.floor(a); + b = Math.floor(b); + if (a > b) + a++; + else + b++; + return this.randrange(a, b); + } + + /** + * 返回 a - b之间的随机数,不包括 Math.max(a, b) + * @param a + * @param b + * @return 假设 a < b, [a, b) + */ + public static randnum(a: number, b: number): number { + return this.random() * (b - a) + a; + } + + /** + * 打乱数组 + * @param array + * @return + */ + public static shuffle(array: any[]): any[] { + array.sort(this._randomCompare); + return array; + } + + private static _randomCompare(a: Object, b: Object): number { + return (this.random() > .5) ? 1 : -1; + } + + /** + * 从序列中随机取一个元素 + * @param sequence 可以是 数组、 vector,等只要是有length属性,并且可以用数字索引获取元素的对象, + * 另外,字符串也是允许的。 + * @return 序列中的某一个元素 + * + */ + public static choice(sequence: any): any { + if (!sequence.hasOwnProperty("length")) + throw new Error('无法对此对象执行此操作'); + let index: number = Math.floor(this.random() * sequence.length); + if (sequence instanceof String) + return String(sequence).charAt(index); + else + return sequence[index]; + } + + + /** + * 对列表中的元素进行随机采æ ? + *
+     * this.sample([1, 2, 3, 4, 5],  3)  // Choose 3 elements
+     * [4, 1, 5]
+     * 
+ * @param sequence + * @param num + * @return + * + */ + public static sample(sequence: any[], num: number): any[] { + let len: number = sequence.length; + if (num <= 0 || len < num) + throw new Error("采样数量不够"); + + let selected: any[] = []; + let indices: any[] = []; + for (let i: number = 0; i < num; i++) { + let index: number = Math.floor(this.random() * len); + while (indices.indexOf(index) >= 0) + index = Math.floor(this.random() * len); + + selected.push(sequence[index]); + indices.push(index); + } + + return selected; + } + + /** + * 返回 0.0 - 1.0 之间的随机数,等同于 Math.random() + * @return Math.random() + * + */ + public static random(): number { + return Math.random(); + } + + /** + * 计算概率 + * @param chance 概率 + * @return + */ + public static boolean(chance: number = .5): boolean { + return (this.random() < chance) ? true : false; + } +} \ No newline at end of file