reformat code

This commit is contained in:
yhh
2020-07-28 16:25:20 +08:00
parent 5994f0bee3
commit 514572f291
103 changed files with 2896 additions and 2839 deletions

View File

@@ -6,30 +6,30 @@ module es {
public clientArea: Rectangle;
public safeArea: Rectangle;
constructor(){
constructor() {
this.clientArea = new Rectangle(0, 0, Core.graphicsDevice.viewport.width, Core.graphicsDevice.viewport.height);
this.safeArea = this.clientArea;
}
public place(size: Vector2, horizontalMargin: number, verticalMargine: number, alignment: Alignment){
public place(size: Vector2, horizontalMargin: number, verticalMargine: number, alignment: Alignment) {
let rc = new Rectangle(0, 0, size.x, size.y);
if ((alignment & Alignment.left) != 0){
if ((alignment & Alignment.left) != 0) {
rc.x = this.clientArea.x + (this.clientArea.width * horizontalMargin);
}else if((alignment & Alignment.right) != 0){
} else if ((alignment & Alignment.right) != 0) {
rc.x = this.clientArea.x + (this.clientArea.width * (1 - horizontalMargin)) - rc.width;
} else if((alignment & Alignment.horizontalCenter) != 0){
} else if ((alignment & Alignment.horizontalCenter) != 0) {
rc.x = this.clientArea.x + (this.clientArea.width - rc.width) / 2 + (horizontalMargin * this.clientArea.width);
}else{
} else {
}
if ((alignment & Alignment.top) != 0){
if ((alignment & Alignment.top) != 0) {
rc.y = this.clientArea.y + (this.clientArea.height * verticalMargine);
}else if((alignment & Alignment.bottom) != 0){
} else if ((alignment & Alignment.bottom) != 0) {
rc.y = this.clientArea.y + (this.clientArea.height * (1 - verticalMargine)) - rc.height;
} else if((alignment & Alignment.verticalCenter) != 0){
} else if ((alignment & Alignment.verticalCenter) != 0) {
rc.y = this.clientArea.y + (this.clientArea.height - rc.height) / 2 + (verticalMargine * this.clientArea.height);
}else{
} else {
}

View File

@@ -1,21 +1,21 @@
namespace stopwatch {
/**
* 记录时间的持续时间,一些设计灵感来自物理秒表。
*/
* 记录时间的持续时间,一些设计灵感来自物理秒表。
*/
export class Stopwatch {
/**
/**
* 秒表启动的系统时间。
* undefined如果秒表尚未启动或已复位。
* undefined如果秒表尚未启动或已复位。
*/
private _startSystemTime: number | undefined;
/**
/**
* 秒表停止的系统时间。
* undefined如果秒表目前没有停止尚未开始或已复位。
* undefined如果秒表目前没有停止尚未开始或已复位。
*/
private _stopSystemTime: number | undefined;
/** 自上次复位以来,秒表已停止的系统时间总数。 */
private _stopDuration: number = 0;
/**
/**
* 用秒表计时,当前等待的切片开始的时间。
* undefined如果秒表尚未启动或已复位。
*/
@@ -25,7 +25,8 @@ namespace stopwatch {
*/
private _completeSlices: Slice[] = [];
constructor(private readonly getSystemTime = _defaultSystemTimeGetter) { }
constructor(private readonly getSystemTime = _defaultSystemTimeGetter) {
}
public getState() {
if (this._startSystemTime === undefined) {
@@ -37,22 +38,22 @@ namespace stopwatch {
}
}
public isIdle(){
public isIdle() {
return this.getState() === State.IDLE;
}
public isRunning(){
public isRunning() {
return this.getState() === State.RUNNING;
}
public isStopped(){
public isStopped() {
return this.getState() === State.STOPPED;
}
/**
*
*
*/
public slice(){
public slice() {
return this.recordPendingSlice();
}
@@ -80,20 +81,70 @@ namespace stopwatch {
/**
* 获取当前秒表时间。这是这个秒表自上次复位以来运行的系统时间总数。
*/
public getTime(){
public getTime() {
return this.caculateStopwatchTime();
}
/**
* 完全重置这个秒表到它的初始状态。清除所有记录的运行持续时间、切片等。
*/
public reset() {
this._startSystemTime = this._pendingSliceStartStopwatchTime = this._stopSystemTime = undefined;
this._stopDuration = 0;
this._completeSlices = [];
}
/**
* 开始(或继续)运行秒表。
* @param forceReset
*/
public start(forceReset: boolean = false) {
if (forceReset) {
this.reset();
}
if (this._stopSystemTime !== undefined) {
const systemNow = this.getSystemTime();
const stopDuration = systemNow - this._stopSystemTime;
this._stopDuration += stopDuration;
this._stopSystemTime = undefined;
} else if (this._startSystemTime === undefined) {
const systemNow = this.getSystemTime();
this._startSystemTime = systemNow;
this._pendingSliceStartStopwatchTime = 0;
}
}
/**
*
* @param recordPendingSlice
*/
public stop(recordPendingSlice: boolean = false) {
if (this._startSystemTime === undefined) {
return 0;
}
const systemTimeOfStopwatchTime = this.getSystemTimeOfCurrentStopwatchTime();
if (recordPendingSlice) {
this.recordPendingSlice(this.caculateStopwatchTime(systemTimeOfStopwatchTime));
}
this._stopSystemTime = systemTimeOfStopwatchTime;
return this.getTime();
}
/**
* 计算指定秒表时间的当前挂起片。
* @param endStopwatchTime
* @param endStopwatchTime
*/
private calculatePendingSlice(endStopwatchTime?: number): Slice {
if (this._pendingSliceStartStopwatchTime === undefined){
if (this._pendingSliceStartStopwatchTime === undefined) {
return Object.freeze({startTime: 0, endTime: 0, duration: 0});
}
if (endStopwatchTime === undefined){
if (endStopwatchTime === undefined) {
endStopwatchTime = this.getTime();
}
@@ -106,9 +157,9 @@ namespace stopwatch {
/**
* 计算指定系统时间的当前秒表时间。
* @param endSystemTime
* @param endSystemTime
*/
private caculateStopwatchTime(endSystemTime?: number){
private caculateStopwatchTime(endSystemTime?: number) {
if (this._startSystemTime === undefined)
return 0;
@@ -122,67 +173,17 @@ namespace stopwatch {
* 获取与当前秒表时间等效的系统时间。
* 如果该秒表当前停止,则返回该秒表停止时的系统时间。
*/
private getSystemTimeOfCurrentStopwatchTime(){
private getSystemTimeOfCurrentStopwatchTime() {
return this._stopSystemTime === undefined ? this.getSystemTime() : this._stopSystemTime;
}
/**
* 完全重置这个秒表到它的初始状态。清除所有记录的运行持续时间、切片等。
*/
public reset(){
this._startSystemTime = this._pendingSliceStartStopwatchTime = this._stopSystemTime = undefined;
this._stopDuration = 0;
this._completeSlices = [];
}
/**
* 开始(或继续)运行秒表。
* @param forceReset
*/
public start(forceReset: boolean = false){
if (forceReset){
this.reset();
}
if (this._stopSystemTime !== undefined){
const systemNow = this.getSystemTime();
const stopDuration = systemNow - this._stopSystemTime;
this._stopDuration += stopDuration;
this._stopSystemTime = undefined;
} else if (this._startSystemTime === undefined){
const systemNow = this.getSystemTime();
this._startSystemTime = systemNow;
this._pendingSliceStartStopwatchTime = 0;
}
}
/**
*
* @param recordPendingSlice
*/
public stop(recordPendingSlice: boolean = false){
if (this._startSystemTime === undefined){
return 0;
}
const systemTimeOfStopwatchTime = this.getSystemTimeOfCurrentStopwatchTime();
if (recordPendingSlice){
this.recordPendingSlice(this.caculateStopwatchTime(systemTimeOfStopwatchTime));
}
this._stopSystemTime = systemTimeOfStopwatchTime;
return this.getTime();
}
/**
* 结束/记录当前挂起的片的私有实现。
* @param endStopwatchTime
* @param endStopwatchTime
*/
private recordPendingSlice(endStopwatchTime?: number){
if (this._pendingSliceStartStopwatchTime !== undefined){
if (endStopwatchTime === undefined){
private recordPendingSlice(endStopwatchTime?: number) {
if (this._pendingSliceStartStopwatchTime !== undefined) {
if (endStopwatchTime === undefined) {
endStopwatchTime = this.getTime();
}
@@ -196,7 +197,7 @@ namespace stopwatch {
}
}
}
/**
* 返回某个系统的“当前时间”的函数。
* 惟一的要求是,对该函数的每次调用都必须返回一个大于或等于前一次对该函数的调用的数字。

View File

@@ -18,23 +18,19 @@ module es {
public static readonly barPadding = 2;
public static readonly autoAdjustDelay = 30;
private static _instance;
public static get Instance(): TimeRuler{
if (!this._instance)
this._instance = new TimeRuler();
return this._instance;
}
private _frameKey = 'frame';
private _logKey = 'log';
/** 每帧的日志 */
private _logs: FrameLog[];
/** 当前显示帧计数 */
private sampleFrames: number;
/** 获取/设置目标样本帧。 */
public targetSampleFrames: number;
/** 获取/设置计时器标尺宽度。 */
public width: number;
public enabled: true;
/** */
public showLog = false;
private _frameKey = 'frame';
private _logKey = 'log';
/** 每帧的日志 */
private _logs: FrameLog[];
/** 当前显示帧计数 */
private sampleFrames: number;
/** TimerRuler画的位置。 */
private _position: Vector2;
/** 上一帧日志 */
@@ -56,8 +52,6 @@ module es {
* 为此我们只需一直跟踪StartFrame调用的次数直到Draw被调用。
*/
private _updateCount: number;
/** */
public showLog = false;
private _frameAdjust: number;
constructor() {
@@ -72,9 +66,10 @@ module es {
this.onGraphicsDeviceReset();
}
private onGraphicsDeviceReset() {
let layout = new Layout();
this._position = layout.place(new Vector2(this.width, TimeRuler.barHeight), 0, 0.01, Alignment.bottomCenter).location;
public static get Instance(): TimeRuler {
if (!this._instance)
this._instance = new TimeRuler();
return this._instance;
}
/**
@@ -244,7 +239,7 @@ module es {
count += 1;
egret.localStorage.setItem(this._logKey, count.toString());
this.markers.forEach(markerInfo => {
for (let i = 0; i < markerInfo.logs.length; ++i){
for (let i = 0; i < markerInfo.logs.length; ++i) {
markerInfo.logs[i].initialized = false;
markerInfo.logs[i].snapMin = 0;
markerInfo.logs[i].snapMax = 0;
@@ -260,7 +255,7 @@ module es {
});
}
public render(position: Vector2 = this._position, width: number = this.width){
public render(position: Vector2 = this._position, width: number = this.width) {
egret.localStorage.setItem(this._frameKey, "0");
if (!this.showLog)
@@ -269,22 +264,22 @@ module es {
let height = 0;
let maxTime = 0;
this._prevLog.bars.forEach(bar => {
if (bar.markCount > 0){
if (bar.markCount > 0) {
height += TimeRuler.barHeight + TimeRuler.barPadding * 2;
maxTime = Math.max(maxTime, bar.markers[bar.markCount - 1].endTime);
}
})
});
const frameSpan = 1 / 60 * 1000;
let sampleSpan = this.sampleFrames * frameSpan;
if (maxTime > sampleSpan){
if (maxTime > sampleSpan) {
this._frameAdjust = Math.max(0, this._frameAdjust) + 1;
}else{
} else {
this._frameAdjust = Math.min(0, this._frameAdjust) - 1;
}
if (Math.max(this._frameAdjust) > TimeRuler.autoAdjustDelay){
if (Math.max(this._frameAdjust) > TimeRuler.autoAdjustDelay) {
this.sampleFrames = Math.min(TimeRuler.maxSampleFrames, this.sampleFrames);
this.sampleFrames = Math.max(this.targetSampleFrames, (maxTime / frameSpan) + 1);
@@ -297,6 +292,11 @@ module es {
// TODO: draw
}
private onGraphicsDeviceReset() {
let layout = new Layout();
this._position = layout.place(new Vector2(this.width, TimeRuler.barHeight), 0, 0.01, Alignment.bottomCenter).location;
}
}
/**
@@ -320,7 +320,7 @@ module es {
public markerNests: number[] = new Array<number>(TimeRuler.maxNestCall);
public nestCount: number = 0;
constructor(){
constructor() {
this.markers.fill(new Marker(), 0, TimeRuler.maxSamples);
this.markerNests.fill(0, 0, TimeRuler.maxNestCall);
}

View File

@@ -1,7 +1,7 @@
class ArrayUtils {
/**
* 执行冒泡排序
* @param ary
* @param ary
* 算法参考 -- http://www.hiahia.org/datastructure/paixu/paixu8.3.1.1-1.htm
*/
public static bubbleSort(ary: number[]): void {
@@ -24,7 +24,7 @@ class ArrayUtils {
/**
* 执行插入排序
* @param ary
* @param ary
*/
public static insertionSort(ary: number[]): void {
let len: number = ary.length;
@@ -39,8 +39,8 @@ class ArrayUtils {
/**
* 执行二分搜索
* @param ary 搜索的数组(必须排序过)
* @param value 需要搜索的值
* @param ary 搜索的数组(必须排序过)
* @param value 需要搜索的值
* @return 返回匹配结果的数组索引
*/
public static binarySearch(ary: number[], value: number): number {
@@ -59,8 +59,8 @@ class ArrayUtils {
/**
* 返回匹配项的索引
* @param ary
* @param num
* @param ary
* @param num
* @return 返回匹配项的索引
*/
public static findElementIndex(ary: any[], num: any): any {
@@ -74,7 +74,7 @@ class ArrayUtils {
/**
* 返回数组中最大值的索引
* @param ary
* @param ary
* @return 返回数组中最大值的索引
*/
public static getMaxElementIndex(ary: number[]): number {
@@ -88,10 +88,10 @@ class ArrayUtils {
}
/**
* 返回数组中最小值的索引
* @param ary
* @return 返回数组中最小值的索引
*/
* 返回数组中最小值的索引
* @param ary
* @return 返回数组中最小值的索引
*/
public static getMinElementIndex(ary: number[]): number {
let matchIndex: number = 0;
let len: number = ary.length;
@@ -104,8 +104,8 @@ class ArrayUtils {
/**
* 返回一个"唯一性"数组
* @param ary 需要唯一性的数组
* @return 唯一性的数组
* @param ary 需要唯一性的数组
* @return 唯一性的数组
* 比如: [1, 2, 2, 3, 4]
* 返回: [1, 2, 3, 4]
*/
@@ -131,25 +131,24 @@ class ArrayUtils {
* 比如数组A = [1, 2, 3, 4, 6]
* 数组B = [0, 2, 1, 3, 4]
* 返回[6, 0]
* @param aryA
* @param aryB
* @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 uObj: 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]] = {};
uObj[ary[j]].count = 0;
uObj[ary[j]].key = ary[j];
uObj[ary[j]].count++;
}
else {
} else {
if (uObj[ary[j]] instanceof Object) {
uObj[ary[j]].count++;
}
@@ -165,9 +164,9 @@ class ArrayUtils {
/**
* 交换数组元素
* @param array 目标数组
* @param index1 交换后的索引
* @param index2 交换前的索引
* @param array 目标数组
* @param index1 交换后的索引
* @param index2 交换前的索引
*/
public static swap(array: any[], index1: number, index2: number): void {
let temp: any = array[index1];
@@ -178,7 +177,7 @@ class ArrayUtils {
/**
* 清除列表
* @param ary 列表
* @param ary 列表
*/
public static clearList(ary: any[]): void {
if (!ary) return;
@@ -190,7 +189,7 @@ class ArrayUtils {
/**
* 克隆一个数组
* @param ary 需要克隆的数组
* @param ary 需要克隆的数组
* @return 克隆的数组
*/
public static cloneList(ary: any[]): any[] {
@@ -201,9 +200,9 @@ class ArrayUtils {
/**
* 判断2个数组是否相同
* @param ary1 数组1
* @param ary2 数组2
* @return 是否相同
* @param ary1 数组1
* @param ary2 数组2
* @return 是否相同
*/
public static equals(ary1: number[], ary2: number[]): Boolean {
if (ary1 == ary2) return true;
@@ -219,8 +218,8 @@ class ArrayUtils {
/**
* 根据索引插入元素,索引和索引后的元素都向后移动一位
* @param index 插入索引
* @param value 插入的元素
* @param index 插入索引
* @param value 插入的元素
* @return 插入的元素 未插入则返回空
*/
public static insert(ary: any[], index: number, value: any): any {

View File

@@ -4,7 +4,7 @@ class Base64Utils {
private static _keyAll = Base64Utils._keyNum + Base64Utils._keyStr;
/**
* 加密
* @param input
* @param input
*/
public static encode = function (input) {
let output = "";
@@ -29,32 +29,12 @@ class Base64Utils {
this._keyAll.charAt(enc3) + this._keyAll.charAt(enc4);
}
return this._keyStr.charAt(Math.floor((Math.random() * this._keyStr.length))) + output;
}
private static _utf8_encode(string) {
string = string.replace(/\r\n/g, "\n");
let utftext = "";
for (let n = 0; n < string.length; n++) {
let c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
} else if ((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
} else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
}
};
/**
* 解码
* @param input
* @param isNotStr
* @param input
* @param isNotStr
*/
public static decode(input, isNotStr: boolean = true) {
let output = "";
@@ -92,6 +72,26 @@ class Base64Utils {
return output;
}
private static _utf8_encode(string) {
string = string.replace(/\r\n/g, "\n");
let utftext = "";
for (let n = 0; n < string.length; n++) {
let c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
} else if ((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
} else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
}
private static _utf8_decode(utftext) {
let string = "";
let i = 0;

View File

@@ -1,11 +1,11 @@
module es {
/** 各种辅助方法来辅助绘图 */
export class DrawUtils {
public static drawLine(shape: egret.Shape, start: Vector2, end: Vector2, color: number, thickness: number = 1){
public static drawLine(shape: egret.Shape, start: Vector2, end: Vector2, color: number, thickness: number = 1) {
this.drawLineAngle(shape, start, MathHelper.angleBetweenVectors(start, end), Vector2.distance(start, end), color, thickness);
}
public static drawLineAngle(shape: egret.Shape, start: Vector2, radians: number, length: number, color: number, thickness = 1){
public static drawLineAngle(shape: egret.Shape, start: Vector2, radians: number, length: number, color: number, thickness = 1) {
shape.graphics.beginFill(color);
shape.graphics.drawRect(start.x, start.y, 1, 1);
shape.graphics.endFill();
@@ -17,11 +17,11 @@ module es {
shape.rotation = radians;
}
public static drawHollowRect(shape: egret.Shape, rect: Rectangle, color: number, thickness = 1){
public static drawHollowRect(shape: egret.Shape, rect: Rectangle, color: number, thickness = 1) {
this.drawHollowRectR(shape, rect.x, rect.y, rect.width, rect.height, color, thickness);
}
public static drawHollowRectR(shape: egret.Shape, x: number, y: number, width: number, height: number, color: number, thickness = 1){
public static drawHollowRectR(shape: egret.Shape, x: number, y: number, width: number, height: number, color: number, thickness = 1) {
let tl = new Vector2(x, y).round();
let tr = new Vector2(x + width, y).round();
let br = new Vector2(x + width, y + height).round();
@@ -33,9 +33,9 @@ module es {
this.drawLine(shape, bl, tl, color, thickness);
}
public static drawPixel(shape: egret.Shape, position: Vector2, color: number, size: number = 1){
public static drawPixel(shape: egret.Shape, position: Vector2, color: number, size: number = 1) {
let destRect = new Rectangle(position.x, position.y, size, size);
if (size != 1){
if (size != 1) {
destRect.x -= size * 0.5;
destRect.y -= size * 0.5;
}
@@ -45,7 +45,7 @@ module es {
shape.graphics.endFill();
}
public static getColorMatrix(color: number): egret.ColorMatrixFilter{
public static getColorMatrix(color: number): egret.ColorMatrixFilter {
let colorMatrix = [
1, 0, 0, 0, 0,
0, 1, 0, 0, 0,

View File

@@ -8,18 +8,19 @@ module es {
/** 上下文 */
public context: any;
constructor(func: Function, context: any){
constructor(func: Function, context: any) {
this.func = func;
this.context = context;
}
}
/**
* 用于事件管理
*/
export class Emitter<T> {
private _messageTable: Map<T, FuncPack[]>;
constructor(){
constructor() {
this._messageTable = new Map<T, FuncPack[]>();
}
@@ -29,9 +30,9 @@ module es {
* @param handler 监听函数
* @param context 监听上下文
*/
public addObserver(eventType: T, handler: Function, context: any){
public addObserver(eventType: T, handler: Function, context: any) {
let list: FuncPack[] = this._messageTable.get(eventType);
if (!list){
if (!list) {
list = [];
this._messageTable.set(eventType, list);
}
@@ -46,7 +47,7 @@ module es {
* @param eventType 事件类型
* @param handler 事件函数
*/
public removeObserver(eventType: T, handler: Function){
public removeObserver(eventType: T, handler: Function) {
let messageData = this._messageTable.get(eventType);
let index = messageData.findIndex(data => data.func == handler);
if (index != -1)
@@ -58,10 +59,10 @@ module es {
* @param eventType 事件类型
* @param data 事件数据
*/
public emit(eventType: T, data?: any){
public emit(eventType: T, data?: any) {
let list: FuncPack[] = this._messageTable.get(eventType);
if (list){
for (let i = list.length - 1; i >= 0; i --)
if (list) {
for (let i = list.length - 1; i >= 0; i--)
list[i].func.call(list[i].context, data);
}
}

View File

@@ -1,10 +1,12 @@
module es {
export class GlobalManager {
public _enabled: boolean;
/**
* 如果true则启用了GlobalManager。
* 状态的改变会导致调用OnEnabled/OnDisable
*/
public get enabled(){
public get enabled() {
return this._enabled;
}
@@ -13,7 +15,7 @@ module es {
* 状态的改变会导致调用OnEnabled/OnDisable
* @param value
*/
public set enabled(value: boolean){
public set enabled(value: boolean) {
this.setEnabled(value);
}
@@ -21,31 +23,33 @@ module es {
* 启用/禁用这个GlobalManager
* @param isEnabled
*/
public setEnabled(isEnabled: boolean){
if (this._enabled != isEnabled){
public setEnabled(isEnabled: boolean) {
if (this._enabled != isEnabled) {
this._enabled = isEnabled;
if (this._enabled){
if (this._enabled) {
this.onEnabled();
} else {
this.onDisabled();
}
}
}
public _enabled: boolean;
/**
* 此GlobalManager启用时调用
*/
public onEnabled(){}
public onEnabled() {
}
/**
* 此GlobalManager禁用时调用
*/
public onDisabled(){}
public onDisabled() {
}
/**
* 在frame .update之前调用每一帧
*/
public update(){}
public update() {
}
}
}

View File

@@ -4,11 +4,12 @@ module es {
public y = 0;
public touchPoint: number = -1;
public touchDown: boolean = false;
public get position(){
public get position() {
return new Vector2(this.x, this.y);
}
public reset(){
public reset() {
this.x = 0;
this.y = 0;
this.touchDown = false;
@@ -19,55 +20,64 @@ module es {
export class Input {
private static _init: boolean = false;
private static _previousTouchState: TouchState = new TouchState();
private static _gameTouchs: TouchState[] = [];
private static _resolutionOffset: Vector2 = new Vector2();
private static _resolutionScale: Vector2 = Vector2.one;
private static _touchIndex: number = 0;
private static _totalTouchCount: number = 0;
/** 返回第一个触摸点的坐标 */
public static get touchPosition(){
if (!this._gameTouchs[0])
return Vector2.zero;
return this._gameTouchs[0].position;
}
/** 获取最大触摸数 */
public static get maxSupportedTouch(){
return Core._instance.stage.maxTouches;
}
/**
* 设置最大触摸数
*/
public static set maxSupportedTouch(value: number){
Core._instance.stage.maxTouches = value;
this.initTouchCache();
}
/** 获取缩放值 默认为1 */
public static get resolutionScale(){
return this._resolutionScale;
}
/** 当前触摸点数量 */
public static get totalTouchCount(){
return this._totalTouchCount;
}
private static _gameTouchs: TouchState[] = [];
/**
* 触摸列表 存放最大个数量触摸点信息
* 可通过判断touchPoint是否为-1 来确定是否为有触摸
* 通过判断touchDown 判断触摸点是否有按下
*/
public static get gameTouchs(){
public static get gameTouchs() {
return this._gameTouchs;
}
private static _resolutionScale: Vector2 = Vector2.one;
/** 获取缩放值 默认为1 */
public static get resolutionScale() {
return this._resolutionScale;
}
private static _totalTouchCount: number = 0;
/** 当前触摸点数量 */
public static get totalTouchCount() {
return this._totalTouchCount;
}
/** 返回第一个触摸点的坐标 */
public static get touchPosition() {
if (!this._gameTouchs[0])
return Vector2.zero;
return this._gameTouchs[0].position;
}
/** 获取最大触摸数 */
public static get maxSupportedTouch() {
return Core._instance.stage.maxTouches;
}
/**
* 设置最大触摸数
*/
public static set maxSupportedTouch(value: number) {
Core._instance.stage.maxTouches = value;
this.initTouchCache();
}
/** 获取第一个触摸点距离上次距离的增量 */
public static get touchPositionDelta(){
public static get touchPositionDelta() {
let delta = Vector2.subtract(this.touchPosition, this._previousTouchState.position);
if (delta.length() > 0){
if (delta.length() > 0) {
this.setpreviousTouchState(this._gameTouchs[0]);
}
return delta;
}
public static initialize(){
public static initialize() {
if (this._init)
return;
@@ -81,67 +91,67 @@ module es {
this.initTouchCache();
}
private static initTouchCache(){
public static scaledPosition(position: Vector2) {
let scaledPos = new Vector2(position.x - this._resolutionOffset.x, position.y - this._resolutionOffset.y);
return Vector2.multiply(scaledPos, this.resolutionScale);
}
private static initTouchCache() {
this._totalTouchCount = 0;
this._touchIndex = 0;
this._gameTouchs.length = 0;
for (let i = 0; i < this.maxSupportedTouch; i ++){
for (let i = 0; i < this.maxSupportedTouch; i++) {
this._gameTouchs.push(new TouchState());
}
}
private static touchBegin(evt: egret.TouchEvent){
if (this._touchIndex < this.maxSupportedTouch){
private static touchBegin(evt: egret.TouchEvent) {
if (this._touchIndex < this.maxSupportedTouch) {
this._gameTouchs[this._touchIndex].touchPoint = evt.touchPointID;
this._gameTouchs[this._touchIndex].touchDown = evt.touchDown;
this._gameTouchs[this._touchIndex].x = evt.stageX;
this._gameTouchs[this._touchIndex].y = evt.stageY;
if (this._touchIndex == 0){
if (this._touchIndex == 0) {
this.setpreviousTouchState(this._gameTouchs[0]);
}
this._touchIndex ++;
this._totalTouchCount ++;
this._touchIndex++;
this._totalTouchCount++;
}
}
private static touchMove(evt: egret.TouchEvent){
if (evt.touchPointID == this._gameTouchs[0].touchPoint){
private static touchMove(evt: egret.TouchEvent) {
if (evt.touchPointID == this._gameTouchs[0].touchPoint) {
this.setpreviousTouchState(this._gameTouchs[0]);
}
let touchIndex = this._gameTouchs.findIndex(touch => touch.touchPoint == evt.touchPointID);
if (touchIndex != -1){
if (touchIndex != -1) {
let touchData = this._gameTouchs[touchIndex];
touchData.x = evt.stageX;
touchData.y = evt.stageY;
}
}
private static touchEnd(evt: egret.TouchEvent){
private static touchEnd(evt: egret.TouchEvent) {
let touchIndex = this._gameTouchs.findIndex(touch => touch.touchPoint == evt.touchPointID);
if (touchIndex != -1){
if (touchIndex != -1) {
let touchData = this._gameTouchs[touchIndex];
touchData.reset();
if (touchIndex == 0)
this._previousTouchState.reset();
this._totalTouchCount --;
if (this.totalTouchCount == 0){
this._totalTouchCount--;
if (this.totalTouchCount == 0) {
this._touchIndex = 0;
}
}
}
private static setpreviousTouchState(touchState: TouchState){
private static setpreviousTouchState(touchState: TouchState) {
this._previousTouchState = new TouchState();
this._previousTouchState.x = touchState.position.x;
this._previousTouchState.y = touchState.position.y;
this._previousTouchState.touchPoint = touchState.touchPoint;
this._previousTouchState.touchDown = touchState.touchDown;
}
public static scaledPosition(position: Vector2){
let scaledPos = new Vector2(position.x - this._resolutionOffset.x, position.y - this._resolutionOffset.y);
return Vector2.multiply(scaledPos, this.resolutionScale);
}
}
}

View File

@@ -4,12 +4,6 @@ class KeyboardUtils {
*/
public static TYPE_KEY_DOWN: number = 0;
public static TYPE_KEY_UP: number = 1;
//存放按下注册数据的字典
private static keyDownDict: Object;
//存放按起注册数据的字典
private static keyUpDict: Object;
/**
* 键值字符串枚举
*/
@@ -39,7 +33,6 @@ class KeyboardUtils {
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";
@@ -53,7 +46,6 @@ class KeyboardUtils {
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";
@@ -64,7 +56,6 @@ class KeyboardUtils {
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";
@@ -73,25 +64,24 @@ class KeyboardUtils {
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";
//存放按下注册数据的字典
private static keyDownDict: Object;
//存放按起注册数据的字典
private static keyUpDict: Object;
public static init(): void {
this.keyDownDict = {};
@@ -100,6 +90,37 @@ class KeyboardUtils {
document.addEventListener("keyup", this.onKeyUpHander);
}
/**
* 注册按键
* @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];
}
/**
* 销毁方法
*/
public static destroy(): void {
this.keyDownDict = null;
this.keyUpDict = null;
document.removeEventListener("keydown", this.onKeyDonwHander);
document.removeEventListener("keyup", this.onKeyUpHander);
}
private static onKeyDonwHander(event: KeyboardEvent): void {
if (!this.keyDownDict) return;
var key: string = this.keyCodeToString(event.keyCode);
@@ -112,7 +133,6 @@ class KeyboardUtils {
}
}
private static onKeyUpHander(event: KeyboardEvent): void {
if (!this.keyUpDict) return;
var key: string = this.keyCodeToString(event.keyCode);
@@ -125,33 +145,10 @@ class KeyboardUtils {
}
}
/**
* 注册按键
* @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 键盘所指字符串代号
* @param keyCode
* @return 键盘所指字符串代号
*/
private static keyCodeToString(keyCode: number): string {
switch (keyCode) {
@@ -225,15 +222,4 @@ class KeyboardUtils {
return String.fromCharCode(keyCode);
}
}
/**
* 销毁方法
*/
public static destroy(): void {
this.keyDownDict = null;
this.keyUpDict = null;
document.removeEventListener("keydown", this.onKeyDonwHander);
document.removeEventListener("keyup", this.onKeyUpHander);
}
}

View File

@@ -9,10 +9,10 @@ module es {
* 预热缓存使用最大的cacheCount对象填充缓存
* @param cacheCount
*/
public static warmCache(cacheCount: number){
public static warmCache(cacheCount: number) {
cacheCount -= this._objectQueue.length;
if (cacheCount > 0){
for (let i = 0; i < cacheCount; i ++){
if (cacheCount > 0) {
for (let i = 0; i < cacheCount; i++) {
this._objectQueue.unshift([]);
}
}
@@ -22,7 +22,7 @@ module es {
* 将缓存修剪为cacheCount项目
* @param cacheCount
*/
public static trimCache(cacheCount){
public static trimCache(cacheCount) {
while (cacheCount > this._objectQueue.length)
this._objectQueue.shift();
}
@@ -30,7 +30,7 @@ module es {
/**
* 清除缓存
*/
public static clearCache(){
public static clearCache() {
this._objectQueue.length = 0;
}
@@ -48,7 +48,7 @@ module es {
* 将项推回堆栈
* @param obj
*/
public static free<T>(obj: Array<T>){
public static free<T>(obj: Array<T>) {
this._objectQueue.unshift(obj);
obj.length = 0;
}

View File

@@ -13,24 +13,25 @@ const nextTick = fn => {
class LockUtils {
private _keyX: string;
private _keyY: string;
constructor(key){
constructor(key) {
this._keyX = `mutex_key_${key}_X`;
this._keyY = `mutex_key_${key}_Y`;
}
public lock(){
public lock() {
return new Promise((resolve, reject) => {
const fn = () => {
setItem(this._keyX, THREAD_ID);
if (!getItem(this._keyY) === null){
if (!getItem(this._keyY) === null) {
// restart
nextTick(fn);
}
setItem(this._keyY, THREAD_ID);
if (getItem(this._keyX) !== THREAD_ID){
if (getItem(this._keyX) !== THREAD_ID) {
// delay
setTimeout(()=>{
if (getItem(this._keyY) !== THREAD_ID){
setTimeout(() => {
if (getItem(this._keyY) !== THREAD_ID) {
// restart
nextTick(fn);
return;

View File

@@ -6,16 +6,16 @@ module es {
public first: T;
public second: T;
constructor(first: T, second: T){
constructor(first: T, second: T) {
this.first = first;
this.second = second;
}
public clear(){
public clear() {
this.first = this.second = null;
}
public equals(other: Pair<T>){
public equals(other: Pair<T>) {
return this.first == other.first && this.second == other.second;
}
}

View File

@@ -43,36 +43,32 @@ class RandomUtils {
}
/**
* 返回 a - b之间的随机数不包括 Math.max(a, b)
* @param a
* @param b
* @return 假设 a < b, [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
*/
* 打乱数组
* @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 序列中的某一个元素
*
*/
* 从序列中随机取一个元素
* @param sequence 可以是 数组、 vector等只要是有length属性并且可以用数字索引获取元素的对象
* 另外,字符串也是允许的。
* @return 序列中的某一个元素
*
*/
public static choice(sequence: any): any {
if (!sequence.hasOwnProperty("length"))
throw new Error('无法对此对象执行此操作');
@@ -83,7 +79,6 @@ class RandomUtils {
return sequence[index];
}
/**
* 对列表中的元素进行随机采æ ?
* <pre>
@@ -125,10 +120,14 @@ class RandomUtils {
/**
* 计算概率
* @param chance 概率
* @param chance 概率
* @return
*/
public static boolean(chance: number = .5): boolean {
return (this.random() < chance) ? true : false;
}
private static _randomCompare(a: Object, b: Object): number {
return (this.random() > .5) ? 1 : -1;
}
}

View File

@@ -5,7 +5,7 @@ module es {
* @param first
* @param point
*/
public static union(first: Rectangle, point: Vector2){
public static union(first: Rectangle, point: Vector2) {
let rect = new Rectangle(point.x, point.y, 0, 0);
// let rectResult = first.union(rect);
let result = new Rectangle();

View File

@@ -11,12 +11,25 @@ module es {
private _triPrev: number[] = new Array<number>(12);
private _triNext: number[] = new Array<number>(12);
public static testPointTriangle(point: Vector2, a: Vector2, b: Vector2, c: Vector2): boolean {
if (Vector2Ext.cross(Vector2.subtract(point, a), Vector2.subtract(b, a)) < 0)
return false;
if (Vector2Ext.cross(Vector2.subtract(point, b), Vector2.subtract(c, b)) < 0)
return false;
if (Vector2Ext.cross(Vector2.subtract(point, c), Vector2.subtract(a, c)) < 0)
return false;
return true;
}
/**
* 计算一个三角形列表该列表完全覆盖给定点集所包含的区域。如果点不是CCW则将arePointsCCW参数传递为false
* @param points 定义封闭路径的点列表
* @param arePointsCCW
*/
public triangulate(points: Vector2[], arePointsCCW: boolean = true){
public triangulate(points: Vector2[], arePointsCCW: boolean = true) {
let count = points.length;
// 设置前一个链接和下一个链接
@@ -29,29 +42,29 @@ module es {
let index = 0;
// 继续移除所有的三角形,直到只剩下一个三角形
while (count > 3 && iterations < 500){
iterations ++;
while (count > 3 && iterations < 500) {
iterations++;
let isEar = true;
let a = points[this._triPrev[index]];
let b = points[index];
let c = points[this._triNext[index]];
if (Vector2Ext.isTriangleCCW(a, b, c)){
if (Vector2Ext.isTriangleCCW(a, b, c)) {
let k = this._triNext[this._triNext[index]];
do {
if (Triangulator.testPointTriangle(points[k], a, b, c)){
if (Triangulator.testPointTriangle(points[k], a, b, c)) {
isEar = false;
break;
}
k = this._triNext[k];
} while (k != this._triPrev[index]);
}else{
} else {
isEar = false;
}
if (isEar){
if (isEar) {
this.triangleIndices.push(this._triPrev[index]);
this.triangleIndices.push(index);
this.triangleIndices.push(this._triNext[index]);
@@ -59,11 +72,11 @@ module es {
// 删除vert通过重定向相邻vert的上一个和下一个链接从而减少vertext计数
this._triNext[this._triPrev[index]] = this._triNext[index];
this._triPrev[this._triNext[index]] = this._triPrev[index];
count --;
count--;
// 接下来访问前一个vert
index = this._triPrev[index];
}else{
} else {
index = this._triNext[index];
}
}
@@ -76,19 +89,19 @@ module es {
this.triangleIndices.reverse();
}
private initialize(count: number){
private initialize(count: number) {
this.triangleIndices.length = 0;
if (this._triNext.length < count){
if (this._triNext.length < count) {
this._triNext.reverse();
this._triNext = new Array<number>(Math.max(this._triNext.length * 2, count));
}
if (this._triPrev.length < count){
if (this._triPrev.length < count) {
this._triPrev.reverse();
this._triPrev = new Array<number>(Math.max(this._triPrev.length * 2, count));
}
for (let i = 0; i < count;i ++){
for (let i = 0; i < count; i++) {
this._triPrev[i] = i - 1;
this._triNext[i] = i + 1;
}
@@ -96,18 +109,5 @@ module es {
this._triPrev[0] = count - 1;
this._triNext[count - 1] = 0;
}
public static testPointTriangle(point: Vector2, a: Vector2, b: Vector2, c: Vector2): boolean{
if (Vector2Ext.cross(Vector2.subtract(point, a), Vector2.subtract(b, a)) < 0)
return false;
if (Vector2Ext.cross(Vector2.subtract(point, b), Vector2.subtract(c, b)) < 0)
return false;
if (Vector2Ext.cross(Vector2.subtract(point, c), Vector2.subtract(a, c)) < 0)
return false;
return true;
}
}
}

View File

@@ -55,7 +55,7 @@ module es {
*/
public static transformA(sourceArray: Vector2[], sourceIndex: number, matrix: Matrix2D,
destinationArray: Vector2[], destinationIndex: number, length: number) {
for (let i = 0; i < length; i ++){
for (let i = 0; i < length; i++) {
let position = sourceArray[sourceIndex + i];
let destination = destinationArray[destinationIndex + i];
destination.x = (position.x * matrix.m11) + (position.y * matrix.m21) + matrix.m31;
@@ -64,7 +64,7 @@ module es {
}
}
public static transformR(position: Vector2, matrix: Matrix2D){
public static transformR(position: Vector2, matrix: Matrix2D) {
let x = (position.x * matrix.m11) + (position.y * matrix.m21) + matrix.m31;
let y = (position.x * matrix.m12) + (position.y * matrix.m22) + matrix.m32;
return new Vector2(x, y);
@@ -80,7 +80,7 @@ module es {
this.transformA(sourceArray, 0, matrix, destinationArray, 0, sourceArray.length);
}
public static round(vec: Vector2){
public static round(vec: Vector2) {
return new Vector2(Math.round(vec.x), Math.round(vec.y));
}
}

View File

@@ -2,7 +2,7 @@ class WebGLUtils {
/**
* 获取webgl context
*/
public static getContext(){
public static getContext() {
const canvas = document.getElementsByTagName('canvas')[0];
return canvas.getContext('2d');
}