From 514572f29146da8189fcad441fc04bd2a1c0c10f Mon Sep 17 00:00:00 2001 From: yhh <359807859@qq.com> Date: Tue, 28 Jul 2020 16:25:20 +0800 Subject: [PATCH] reformat code --- source/.vscode/tasks.json | 22 +- source/.wing/settings.json | 2 +- source/bin/framework.d.ts | 334 ++--- source/bin/framework.js | 1078 +++++++++-------- source/bin/framework.min.js | 2 +- source/gulpfile.js | 2 +- .../AI/Pathfinding/AStar/AStarPathfinder.ts | 56 +- .../AI/Pathfinding/AStar/AstarGridGraph.ts | 6 +- .../src/AI/Pathfinding/AStar/IAstarGraph.ts | 2 + .../src/AI/Pathfinding/AStar/PriorityQueue.ts | 22 +- .../BreadthFirst/BreadthFirstPathfinder.ts | 10 +- .../BreadthFirst/IUnweightedGraph.ts | 2 +- .../BreadthFirst/UnweightedGraph.ts | 4 +- .../AI/Pathfinding/Dijkstra/IWeightedGraph.ts | 2 +- .../Pathfinding/Dijkstra/WeightedGridGraph.ts | 10 +- .../Dijkstra/WeightedPathfinder.ts | 44 +- source/src/Debug/Debug.ts | 10 +- source/src/Debug/DebugDrawItem.ts | 6 +- source/src/ECS/Component.ts | 16 +- source/src/ECS/Components/Camera.ts | 170 +-- source/src/ECS/Components/ComponentPool.ts | 10 +- .../src/ECS/Components/IUpdatableComparer.ts | 6 +- source/src/ECS/Components/Mesh.ts | 4 +- .../Physics/Colliders/BoxCollider.ts | 48 +- .../Physics/Colliders/CircleCollider.ts | 16 +- .../Components/Physics/Colliders/Collider.ts | 94 +- .../Components/Physics/ITriggerListener.ts | 2 +- source/src/ECS/Components/Physics/Mover.ts | 18 +- .../ECS/Components/Physics/ProjectileMover.ts | 14 +- .../src/ECS/Components/RenderableComponent.ts | 125 +- .../ECS/Components/ScrollingSpriteRenderer.ts | 2 +- source/src/ECS/Components/SpriteAnimation.ts | 2 +- source/src/ECS/Components/SpriteAnimator.ts | 16 +- source/src/ECS/Components/SpriteRenderer.ts | 53 +- .../src/ECS/Components/TiledSpriteRenderer.ts | 29 +- source/src/ECS/Core.ts | 228 ++-- source/src/ECS/CoreEvents.ts | 2 +- source/src/ECS/Entity.ts | 117 +- source/src/ECS/Scene.ts | 623 +++++----- source/src/ECS/Systems/EntitySystem.ts | 44 +- source/src/ECS/Systems/PassiveSystem.ts | 4 +- source/src/ECS/Systems/ProcessingSystem.ts | 14 +- source/src/ECS/Transform.ts | 351 +++--- source/src/ECS/Utils/BitSet.ts | 68 +- source/src/ECS/Utils/ComponentList.ts | 12 +- source/src/ECS/Utils/ComponentTypeManager.ts | 8 +- source/src/ECS/Utils/EntityList.ts | 80 +- source/src/ECS/Utils/EntityProcessorList.ts | 52 +- source/src/ECS/Utils/Matcher.ts | 22 +- source/src/ECS/Utils/ObjectUtils.ts | 13 +- source/src/ECS/Utils/StringUtils.ts | 113 +- source/src/ECS/Utils/TextureUtils.ts | 23 +- source/src/ECS/Utils/Time.ts | 11 +- source/src/ECS/Utils/TimeUtils.ts | 23 +- source/src/Extension.ts | 2 +- .../Graphics/Effects/GaussianBlurEffect.ts | 4 +- .../Graphics/Effects/PolygonLightEffect.ts | 2 +- source/src/Graphics/GraphicsCapabilities.ts | 10 +- source/src/Graphics/GraphicsDevice.ts | 15 +- .../Graphics/PostProcessing/PostProcessor.ts | 30 +- .../GaussianBlurPostProcessor.ts | 2 +- .../src/Graphics/Renderers/DefaultRenderer.ts | 4 +- source/src/Graphics/Renderers/IRenderable.ts | 2 +- .../Renderers/PolygonLight/PolyLight.ts | 40 +- source/src/Graphics/Renderers/Renderer.ts | 43 +- .../Graphics/Transitions/FadeTransition.ts | 6 +- .../Graphics/Transitions/SceneTransition.ts | 44 +- .../Graphics/Transitions/WindTransition.ts | 20 +- source/src/Graphics/Viewport.ts | 71 +- source/src/Math/Flags.ts | 12 +- source/src/Math/MathHelper.ts | 18 +- source/src/Math/Matrix2D.ts | 64 +- source/src/Math/Rectangle.ts | 76 +- source/src/Math/Vector2.ts | 162 +-- source/src/Math/Vector3.ts | 2 +- source/src/Physics/ColliderTriggerHelper.ts | 20 +- source/src/Physics/Collision.ts | 16 +- source/src/Physics/Physics.ts | 22 +- source/src/Physics/Shapes/Box.ts | 18 +- source/src/Physics/Shapes/CollisionResult.ts | 2 +- source/src/Physics/Shapes/Polygon.ts | 137 ++- source/src/Physics/Shapes/Shape.ts | 5 +- .../Shapes/ShapeCollisions/ShapeCollisions.ts | 12 +- source/src/Physics/Verlet/SpatialHash.ts | 104 +- source/src/Utils/Analysis/Layout.ts | 20 +- source/src/Utils/Analysis/Stopwatch.ts | 151 +-- source/src/Utils/Analysis/TimeRuler.ts | 50 +- source/src/Utils/ArrayUtils.ts | 57 +- source/src/Utils/Base64Utils.ts | 48 +- source/src/Utils/DrawUtils.ts | 14 +- source/src/Utils/Emitter.ts | 17 +- source/src/Utils/GlobalManager.ts | 22 +- source/src/Utils/Input.ts | 118 +- source/src/Utils/KeyboardUtils.ts | 88 +- source/src/Utils/ListPool.ts | 12 +- source/src/Utils/LockUtils.ts | 13 +- source/src/Utils/Pair.ts | 6 +- source/src/Utils/RandomUtils.ts | 41 +- source/src/Utils/RectangleExt.ts | 2 +- source/src/Utils/Triangulator.ts | 52 +- source/src/Utils/Vector2Ext.ts | 6 +- source/src/Utils/WebGLUtils.ts | 2 +- source/tsconfig.json | 4 +- 103 files changed, 2896 insertions(+), 2839 deletions(-) diff --git a/source/.vscode/tasks.json b/source/.vscode/tasks.json index aba11758..8d24ee93 100644 --- a/source/.vscode/tasks.json +++ b/source/.vscode/tasks.json @@ -1,13 +1,13 @@ { - // See https://go.microsoft.com/fwlink/?LinkId=733558 - // for the documentation about the tasks.json format - "version": "2.0.0", - "tasks": [ - { - "type": "gulp", - "task": "build", - "group": "build", - "problemMatcher": [] - } - ] + // See https://go.microsoft.com/fwlink/?LinkId=733558 + // for the documentation about the tasks.json format + "version": "2.0.0", + "tasks": [ + { + "type": "gulp", + "task": "build", + "group": "build", + "problemMatcher": [] + } + ] } \ No newline at end of file diff --git a/source/.wing/settings.json b/source/.wing/settings.json index b44c2020..c3fcd996 100644 --- a/source/.wing/settings.json +++ b/source/.wing/settings.json @@ -1,3 +1,3 @@ { - "typescript.tsdk": "./node_modules/typescript/lib" + "typescript.tsdk": "./node_modules/typescript/lib" } \ No newline at end of file diff --git a/source/bin/framework.d.ts b/source/bin/framework.d.ts index 874ce29d..16079948 100644 --- a/source/bin/framework.d.ts +++ b/source/bin/framework.d.ts @@ -27,9 +27,9 @@ declare module es { declare module es { class AStarPathfinder { static search(graph: IAstarGraph, start: T, goal: T): T[]; + static recontructPath(cameFrom: Map, start: T, goal: T): T[]; private static hasKey; private static getKey; - static recontructPath(cameFrom: Map, start: T, goal: T): T[]; } class AStarNode extends PriorityQueueNode { data: T; @@ -68,9 +68,9 @@ declare module es { private _nodes; private _numNodesEverEnqueued; constructor(maxNodes: number); - clear(): void; readonly count: number; readonly maxSize: number; + clear(): void; contains(node: T): boolean; enqueue(node: T, priority: number): void; dequeue(): T; @@ -103,28 +103,21 @@ declare module es { } declare module es { class Vector2 { - x: number; - y: number; private static readonly unitYVector; private static readonly unitXVector; private static readonly unitVector2; private static readonly zeroVector2; + x: number; + y: number; + constructor(x?: number, y?: number); static readonly zero: Vector2; static readonly one: Vector2; static readonly unitX: Vector2; static readonly unitY: Vector2; - constructor(x?: number, y?: number); - add(value: Vector2): Vector2; - divide(value: Vector2): Vector2; - multiply(value: Vector2): Vector2; - subtract(value: Vector2): this; static add(value1: Vector2, value2: Vector2): Vector2; static divide(value1: Vector2, value2: Vector2): Vector2; static multiply(value1: Vector2, value2: Vector2): Vector2; static subtract(value1: Vector2, value2: Vector2): Vector2; - normalize(): void; - length(): number; - round(): Vector2; static normalize(value: Vector2): Vector2; static dot(value1: Vector2, value2: Vector2): number; static distanceSquared(value1: Vector2, value2: Vector2): number; @@ -133,6 +126,13 @@ declare module es { static transform(position: Vector2, matrix: Matrix2D): Vector2; static distance(value1: Vector2, value2: Vector2): number; static negate(value: Vector2): Vector2; + add(value: Vector2): Vector2; + divide(value: Vector2): Vector2; + multiply(value: Vector2): Vector2; + subtract(value: Vector2): this; + normalize(): void; + length(): number; + round(): Vector2; equals(other: Vector2): boolean; } } @@ -185,9 +185,9 @@ declare module es { } class WeightedPathfinder { static search(graph: IWeightedGraph, start: T, goal: T): T[]; + static recontructPath(cameFrom: Map, start: T, goal: T): T[]; private static hasKey; private static getKey; - static recontructPath(cameFrom: Map, start: T, goal: T): T[]; } } declare module es { @@ -228,12 +228,12 @@ declare module es { declare module es { abstract class Component { entity: Entity; - readonly transform: Transform; - enabled: boolean; - updateOrder: number; updateInterval: number; + readonly transform: Transform; private _enabled; + enabled: boolean; private _updateOrder; + updateOrder: number; initialize(): void; onAddedToEntity(): void; onRemovedFromEntity(): void; @@ -252,27 +252,27 @@ declare module es { static emitter: Emitter; static graphicsDevice: GraphicsDevice; static content: ContentManager; - static readonly Instance: Core; static _instance: Core; - _scene: Scene; _nextScene: Scene; _sceneTransition: SceneTransition; _globalManagers: GlobalManager[]; - static scene: Scene; constructor(); - private onAddToStage; - onOrientationChanged(): void; - protected onGraphicsDeviceReset(): void; - protected initialize(): void; - protected update(): Promise; - draw(): Promise; - startDebugUpdate(): void; - endDebugUpdate(): void; - onSceneChanged(): void; + static readonly Instance: Core; + _scene: Scene; + static scene: Scene; static startSceneTransition(sceneTransition: T): T; static registerGlobalManager(manager: es.GlobalManager): void; static unregisterGlobalManager(manager: es.GlobalManager): void; static getGlobalManager(type: any): T; + onOrientationChanged(): void; + draw(): Promise; + startDebugUpdate(): void; + endDebugUpdate(): void; + onSceneChanged(): void; + protected onGraphicsDeviceReset(): void; + protected initialize(): void; + protected update(): Promise; + private onAddToStage; } } declare module es { @@ -290,16 +290,17 @@ declare module es { readonly id: number; readonly transform: Transform; readonly components: ComponentList; - tag: number; updateInterval: number; - enabled: boolean; - updateOrder: number; + componentBits: BitSet; + constructor(name: string); _isDestroyed: boolean; readonly isDestroyed: boolean; - componentBits: BitSet; private _tag; + tag: number; private _enabled; + enabled: boolean; private _updateOrder; + updateOrder: number; parent: Transform; readonly childCount: number; position: Vector2; @@ -313,7 +314,6 @@ declare module es { readonly worldInverseTransform: Matrix2D; readonly localToWorldTransform: Matrix2D; readonly worldToLocalTransform: Matrix2D; - constructor(name: string); onTransformChanged(comp: transform.Component): void; setTag(tag: number): Entity; setEnabled(isEnabled: boolean): this; @@ -322,7 +322,6 @@ declare module es { detachFromScene(): void; attachToScene(newScene: Scene): void; clone(position?: Vector2): Entity; - protected copyFrom(entity: Entity): void; onAddedToScene(): void; onRemovedFromScene(): void; update(): void; @@ -336,6 +335,7 @@ declare module es { removeAllComponents(): void; compareTo(other: Entity): number; toString(): string; + protected copyFrom(entity: Entity): void; } } declare module es { @@ -349,8 +349,8 @@ declare module es { _renderers: Renderer[]; readonly _postProcessors: PostProcessor[]; _didSceneBegin: any; - static createWithDefaultRenderer(): Scene; constructor(); + static createWithDefaultRenderer(): Scene; initialize(): void; onStart(): Promise; unload(): void; @@ -397,20 +397,6 @@ declare module es { } class Transform extends HashObject { readonly entity: Entity; - parent: Transform; - readonly childCount: number; - position: Vector2; - localPosition: Vector2; - rotation: number; - rotationDegrees: number; - localRotation: number; - localRotationDegrees: number; - scale: Vector2; - localScale: Vector2; - readonly worldInverseTransform: Matrix2D; - readonly localToWorldTransform: Matrix2D; - readonly worldToLocalTransform: Matrix2D; - _parent: Transform; hierarchyDirty: DirtyType; _localDirty: boolean; _localPositionDirty: boolean; @@ -421,19 +407,33 @@ declare module es { _worldInverseDirty: boolean; _localTransform: Matrix2D; _worldTransform: Matrix2D; - _worldToLocalTransform: Matrix2D; - _worldInverseTransform: Matrix2D; _rotationMatrix: Matrix2D; _translationMatrix: Matrix2D; _scaleMatrix: Matrix2D; - _position: Vector2; - _scale: Vector2; - _rotation: number; - _localPosition: Vector2; - _localScale: Vector2; - _localRotation: number; _children: Transform[]; constructor(entity: Entity); + readonly childCount: number; + rotationDegrees: number; + localRotationDegrees: number; + readonly localToWorldTransform: Matrix2D; + _parent: Transform; + parent: Transform; + _worldToLocalTransform: Matrix2D; + readonly worldToLocalTransform: Matrix2D; + _worldInverseTransform: Matrix2D; + readonly worldInverseTransform: Matrix2D; + _position: Vector2; + position: Vector2; + _scale: Vector2; + scale: Vector2; + _rotation: number; + rotation: number; + _localPosition: Vector2; + localPosition: Vector2; + _localScale: Vector2; + localScale: Vector2; + _localRotation: number; + localRotation: number; getChild(index: number): Transform; setParent(parent: Transform): Transform; setPosition(x: number, y: number): Transform; @@ -465,23 +465,7 @@ declare module es { bottom: number; } class Camera extends Component { - position: Vector2; - rotation: number; - zoom: number; - minimumZoom: number; - maximumZoom: number; - readonly bounds: Rectangle; - readonly transformMatrix: Matrix2D; - readonly inverseTransformMatrix: Matrix2D; - origin: Vector2; - _zoom: any; - _minimumZoom: number; - _maximumZoom: number; - _bounds: Rectangle; _inset: CameraInset; - _transformMatrix: Matrix2D; - _inverseTransformMatrix: Matrix2D; - _origin: Vector2; _areMatrixedDirty: boolean; _areBoundsDirty: boolean; _isProjectionMatrixDirty: boolean; @@ -496,8 +480,23 @@ declare module es { _cameraStyle: CameraStyle; _worldSpaceDeadZone: Rectangle; constructor(targetEntity?: Entity, cameraStyle?: CameraStyle); + position: Vector2; + rotation: number; + _zoom: any; + zoom: number; + _minimumZoom: number; + minimumZoom: number; + _maximumZoom: number; + maximumZoom: number; + _bounds: Rectangle; + readonly bounds: Rectangle; + _transformMatrix: Matrix2D; + readonly transformMatrix: Matrix2D; + _inverseTransformMatrix: Matrix2D; + readonly inverseTransformMatrix: Matrix2D; + _origin: Vector2; + origin: Vector2; onSceneSizeChanged(newWidth: number, newHeight: number): void; - protected updateMatrixes(): void; setInset(left: number, right: number, top: number, bottom: number): Camera; setPosition(position: Vector2): this; setRotation(rotation: number): Camera; @@ -516,6 +515,7 @@ declare module es { updateFollow(): void; follow(targetEntity: Entity, cameraStyle?: CameraStyle): void; setCenteredDeadzone(width: number, height: number): void; + protected updateMatrixes(): void; } } declare module es { @@ -540,28 +540,28 @@ declare module es { declare module es { abstract class RenderableComponent extends Component implements IRenderable { displayObject: egret.DisplayObject; + color: number; + protected _areBoundsDirty: boolean; readonly width: number; readonly height: number; - readonly bounds: Rectangle; - renderLayer: number; - color: number; - localOffset: Vector2; - isVisible: boolean; protected _localOffset: Vector2; + localOffset: Vector2; protected _renderLayer: number; + renderLayer: number; protected _bounds: Rectangle; + readonly bounds: Rectangle; private _isVisible; - protected _areBoundsDirty: boolean; + isVisible: boolean; onEntityTransformChanged(comp: transform.Component): void; abstract render(camera: Camera): any; - protected onBecameVisible(): void; - protected onBecameInvisible(): void; isVisibleFromCamera(camera: Camera): boolean; setRenderLayer(renderLayer: number): RenderableComponent; setColor(color: number): RenderableComponent; setLocalOffset(offset: Vector2): RenderableComponent; sync(camera: Camera): void; toString(): string; + protected onBecameVisible(): void; + protected onBecameInvisible(): void; } } declare module es { @@ -575,13 +575,13 @@ declare module es { } declare module es { class SpriteRenderer extends RenderableComponent { - readonly bounds: Rectangle; - origin: Vector2; - originNormalized: Vector2; - sprite: Sprite; - protected _origin: Vector2; - protected _sprite: Sprite; constructor(sprite?: Sprite | egret.Texture); + readonly bounds: Rectangle; + originNormalized: Vector2; + protected _origin: Vector2; + origin: Vector2; + protected _sprite: Sprite; + sprite: Sprite; setSprite(sprite: Sprite): SpriteRenderer; setOrigin(origin: Vector2): SpriteRenderer; setOriginNormalized(value: Vector2): SpriteRenderer; @@ -593,9 +593,9 @@ declare module es { protected sourceRect: Rectangle; protected leftTexture: egret.Bitmap; protected rightTexture: egret.Bitmap; + constructor(sprite: Sprite); scrollX: number; scrollY: number; - constructor(sprite: Sprite); render(camera: es.Camera): void; } } @@ -647,12 +647,12 @@ declare module es { currentAnimation: SpriteAnimation; currentAnimationName: string; currentFrame: number; - readonly isRunning: boolean; - readonly animations: Map; - private _animations; _elapsedTime: number; _loopMode: LoopMode; constructor(sprite?: Sprite); + readonly isRunning: boolean; + private _animations; + readonly animations: Map; update(): void; addAnimation(name: string, animation: SpriteAnimation): SpriteAnimator; play(name: string, loopMode?: LoopMode): void; @@ -689,22 +689,22 @@ declare module es { declare module es { abstract class Collider extends Component { shape: Shape; - localOffset: Vector2; - readonly absolutePosition: Vector2; - readonly rotation: number; isTrigger: boolean; physicsLayer: number; collidesWithLayers: number; shouldColliderScaleAndRotateWithTransform: boolean; - readonly bounds: Rectangle; registeredPhysicsBounds: Rectangle; - protected _colliderRequiresAutoSizing: any; - protected _localOffset: Vector2; _localOffsetLength: number; - protected _isParentEntityAddedToScene: any; - protected _isColliderRegistered: any; _isPositionDirty: boolean; _isRotationDirty: boolean; + protected _colliderRequiresAutoSizing: any; + protected _isParentEntityAddedToScene: any; + protected _isColliderRegistered: any; + readonly absolutePosition: Vector2; + readonly rotation: number; + readonly bounds: Rectangle; + protected _localOffset: Vector2; + localOffset: Vector2; setLocalOffset(offset: Vector2): Collider; setShouldColliderScaleAndRotateWithTransform(shouldColliderScaleAndRotationWithTransform: boolean): Collider; onAddedToEntity(): void; @@ -721,9 +721,9 @@ declare module es { } declare module es { class BoxCollider extends Collider { + constructor(); width: number; height: number; - constructor(); setSize(width: number, height: number): this; setWidth(width: number): BoxCollider; setHeight(height: number): void; @@ -732,8 +732,8 @@ declare module es { } declare module es { class CircleCollider extends Collider { - radius: number; constructor(radius?: number); + radius: number; setRadius(radius: number): CircleCollider; toString(): string; } @@ -745,12 +745,12 @@ declare module es { } declare module es { class EntitySystem { - private _scene; private _entities; + constructor(matcher?: Matcher); + private _scene; + scene: Scene; private _matcher; readonly matcher: Matcher; - scene: Scene; - constructor(matcher?: Matcher); initialize(): void; onChanged(entity: Entity): void; add(entity: Entity): void; @@ -783,8 +783,8 @@ declare module es { declare module es { abstract class ProcessingSystem extends EntitySystem { onChanged(entity: Entity): void; - protected process(entities: Entity[]): void; abstract processSystem(): any; + protected process(entities: Entity[]): void; } } declare module es { @@ -796,12 +796,12 @@ declare module es { andNot(bs: BitSet): void; cardinality(): number; clear(pos?: number): void; - private ensure; get(pos: number): boolean; intersects(set: BitSet): boolean; isEmpty(): boolean; nextSetBit(from: number): number; set(pos: number, value?: boolean): void; + private ensure; } } declare module es { @@ -879,13 +879,13 @@ declare module es { onComponentRemoved(entity: Entity): void; onEntityAdded(entity: Entity): void; onEntityRemoved(entity: Entity): void; - protected notifyEntityChanged(entity: Entity): void; - protected removeFromProcessors(entity: Entity): void; begin(): void; update(): void; lateUpdate(): void; end(): void; getProcessor(): T; + protected notifyEntityChanged(entity: Entity): void; + protected removeFromProcessors(entity: Entity): void; } } declare module es { @@ -939,13 +939,13 @@ declare module es { } } declare class StringUtils { + private static specialSigns; 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; @@ -969,8 +969,8 @@ declare module es { static deltaTime: number; static timeScale: number; static frameCount: number; - private static _lastTime; static _timeSinceSceneLoad: any; + private static _lastTime; static update(currentTime: number): void; static sceneChanged(): void; static checkEvery(interval: number): boolean; @@ -998,10 +998,10 @@ declare module es { } declare module es { class GraphicsDevice { - private _viewport; - readonly viewport: Viewport; graphicsCapabilities: GraphicsCapabilities; constructor(); + private _viewport; + readonly viewport: Viewport; private setup; } } @@ -1009,15 +1009,15 @@ declare module es { class Viewport { private _x; private _y; - private _width; - private _height; private _minDepth; private _maxDepth; - height: number; + constructor(x: number, y: number, width: number, height: number); + private _width; width: number; + private _height; + height: number; readonly aspectRatio: number; bounds: Rectangle; - constructor(x: number, y: number, width: number, height: number); } } declare module es { @@ -1035,17 +1035,17 @@ declare module es { } declare module es { class PostProcessor { + static default_vert: string; enabled: boolean; effect: egret.Filter; scene: Scene; shape: egret.Shape; - static default_vert: string; constructor(effect?: egret.Filter); onAddedToScene(scene: Scene): void; process(): void; onSceneBackBufferSizeChanged(newWidth: number, newHeight: number): void; - protected drawFullscreenQuad(): void; unload(): void; + protected drawFullscreenQuad(): void; } } declare module es { @@ -1060,11 +1060,11 @@ declare module es { protected constructor(renderOrder: number, camera?: Camera); onAddedToScene(scene: Scene): void; unload(): void; - protected beginRender(cam: Camera): void; abstract render(scene: Scene): any; - protected renderAfterStateCheck(renderable: IRenderable, cam: Camera): void; onSceneBackBufferSizeChanged(newWidth: number, newHeight: number): void; compareTo(other: Renderer): number; + protected beginRender(cam: Camera): void; + protected renderAfterStateCheck(renderable: IRenderable, cam: Camera): void; } } declare module es { @@ -1081,33 +1081,33 @@ declare module es { declare module es { class PolyLight extends RenderableComponent { power: number; - protected _radius: number; private _lightEffect; private _indices; - radius: number; constructor(radius: number, color: number, power: number); - private computeTriangleIndices; + protected _radius: number; + radius: number; setRadius(radius: number): void; render(camera: Camera): void; reset(): void; + private computeTriangleIndices; } } declare module es { abstract class SceneTransition { - private _hasPreviousSceneRender; loadsNewScene: boolean; isNewSceneLoaded: boolean; - protected sceneLoadAction: Function; onScreenObscured: Function; onTransitionCompleted: Function; - readonly hasPreviousSceneRender: boolean; + protected sceneLoadAction: Function; constructor(sceneLoadAction: Function); + private _hasPreviousSceneRender; + readonly hasPreviousSceneRender: boolean; preRender(): void; render(): void; onBeginTransition(): Promise; + tickEffectProgressProperty(filter: egret.CustomFilter, duration: number, easeType: Function, reverseDirection?: boolean): Promise; protected transitionComplete(): void; protected loadNextScene(): Promise; - tickEffectProgressProperty(filter: egret.CustomFilter, duration: number, easeType: Function, reverseDirection?: boolean): Promise; } } declare module es { @@ -1125,13 +1125,13 @@ declare module es { } declare module es { class WindTransition extends SceneTransition { + duration: number; + easeType: (t: number) => number; private _mask; private _windEffect; - duration: number; + constructor(sceneLoadAction: Function); windSegments: number; size: number; - easeType: (t: number) => number; - constructor(sceneLoadAction: Function); onBeginTransition(): Promise; } } @@ -1202,14 +1202,14 @@ declare module es { readonly center: Vector2; location: Vector2; size: Vector2; + static fromMinMax(minX: number, minY: number, maxX: number, maxY: number): Rectangle; + static rectEncompassingPoints(points: Vector2[]): Rectangle; intersects(value: egret.Rectangle): boolean; containsRect(value: Rectangle): boolean; getHalfSize(): Vector2; - static fromMinMax(minX: number, minY: number, maxX: number, maxY: number): Rectangle; getClosestPointOnRectangleBorderToPoint(point: Vector2, edgeNormal: Vector2): Vector2; getClosestPointOnBoundsToOrigin(): Vector2; calculateBounds(parentPosition: Vector2, position: Vector2, origin: Vector2, scale: Vector2, rotation: number, width: number, height: number): void; - static rectEncompassingPoints(points: Vector2[]): Rectangle; } } declare module es { @@ -1259,9 +1259,9 @@ declare module es { } declare module es { class Physics { - private static _spatialHash; static spatialHashCellSize: number; static readonly allLayers: number; + private static _spatialHash; static reset(): void; static clear(): void; static overlapCircleAll(center: Vector2, randius: number, results: any[], layerMask?: number): number; @@ -1288,21 +1288,21 @@ declare module es { declare module es { class Polygon extends Shape { points: Vector2[]; - readonly edgeNormals: Vector2[]; _areEdgeNormalsDirty: boolean; - _edgeNormals: Vector2[]; _originalPoints: Vector2[]; _polygonCenter: Vector2; isBox: boolean; isUnrotated: boolean; constructor(points: Vector2[], isBox?: boolean); - setPoints(points: Vector2[]): void; - recalculateCenterAndEdgeNormals(): void; - buildEdgeNormals(): void; + _edgeNormals: Vector2[]; + readonly edgeNormals: Vector2[]; static buildSymmetricalPolygon(vertCount: number, radius: number): any[]; static recenterPolygonVerts(points: Vector2[]): void; static findPolygonCenter(points: Vector2[]): Vector2; static getClosestPointOnPolygonToPoint(points: Vector2[], point: Vector2, distanceSquared: number, edgeNormal: Vector2): Vector2; + setPoints(points: Vector2[]): void; + recalculateCenterAndEdgeNormals(): void; + buildEdgeNormals(): void; recalculateBounds(collider: Collider): void; overlaps(other: Shape): any; collidesWithShape(other: Shape, result: CollisionResult): boolean; @@ -1370,24 +1370,24 @@ declare module es { _cellDict: NumberDictionary; _tempHashSet: Collider[]; constructor(cellSize?: number); - private cellCoords; - private cellAtPosition; register(collider: Collider): void; remove(collider: Collider): void; removeWithBruteForce(obj: Collider): void; clear(): void; debugDraw(secondsToDisplay: number, textScale?: number): void; - private debugDrawCellDetails; aabbBroadphase(bounds: Rectangle, excludeCollider: Collider, layerMask: number): Collider[]; overlapCircle(circleCenter: Vector2, radius: number, results: Collider[], layerMask: any): number; + private cellCoords; + private cellAtPosition; + private debugDrawCellDetails; } class NumberDictionary { _store: Map; - private getKey; add(x: number, y: number, list: Collider[]): void; remove(obj: Collider): void; tryGetValue(x: number, y: number): Collider[]; clear(): void; + private getKey; } class RaycastResultParser { } @@ -1412,8 +1412,8 @@ declare class Base64Utils { private static _keyStr; private static _keyAll; static encode: (input: any) => string; - private static _utf8_encode; static decode(input: any, isNotStr?: boolean): string; + private static _utf8_encode; private static _utf8_decode; private static getConfKey; } @@ -1450,9 +1450,9 @@ declare module es { } declare module es { class GlobalManager { + _enabled: boolean; enabled: boolean; setEnabled(isEnabled: boolean): void; - _enabled: boolean; onEnabled(): void; onDisabled(): void; update(): void; @@ -1470,31 +1470,29 @@ declare module es { class Input { private static _init; private static _previousTouchState; - private static _gameTouchs; private static _resolutionOffset; - private static _resolutionScale; private static _touchIndex; + private static _gameTouchs; + static readonly gameTouchs: TouchState[]; + private static _resolutionScale; + static readonly resolutionScale: Vector2; private static _totalTouchCount; + static readonly totalTouchCount: number; static readonly touchPosition: Vector2; static maxSupportedTouch: number; - static readonly resolutionScale: Vector2; - static readonly totalTouchCount: number; - static readonly gameTouchs: TouchState[]; static readonly touchPositionDelta: Vector2; static initialize(): void; + static scaledPosition(position: Vector2): Vector2; private static initTouchCache; private static touchBegin; private static touchMove; private static touchEnd; 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; @@ -1566,13 +1564,15 @@ declare class KeyboardUtils { static NUM_LOCK: string; static SCROLL_LOCK: string; static WINDOWS: string; + private static keyDownDict; + private static keyUpDict; 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; + private static onKeyDonwHander; + private static onKeyUpHander; + private static keyCodeToString; } declare module es { class ListPool { @@ -1609,11 +1609,11 @@ declare class RandomUtils { 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; + private static _randomCompare; } declare module es { class RectangleExt { @@ -1625,9 +1625,9 @@ declare module es { triangleIndices: number[]; private _triPrev; private _triNext; + static testPointTriangle(point: Vector2, a: Vector2, b: Vector2, c: Vector2): boolean; triangulate(points: Vector2[], arePointsCCW?: boolean): void; private initialize; - static testPointTriangle(point: Vector2, a: Vector2, b: Vector2, c: Vector2): boolean; } } declare module es { @@ -1689,12 +1689,12 @@ declare namespace stopwatch { getCompletedAndPendingSlices(): Slice[]; getPendingSlice(): Slice; getTime(): number; - private calculatePendingSlice; - private caculateStopwatchTime; - private getSystemTimeOfCurrentStopwatchTime; reset(): void; start(forceReset?: boolean): void; stop(recordPendingSlice?: boolean): number; + private calculatePendingSlice; + private caculateStopwatchTime; + private getSystemTimeOfCurrentStopwatchTime; private recordPendingSlice; } type GetTimeFunc = () => number; @@ -1721,14 +1721,14 @@ declare module es { static readonly barPadding: number; static readonly autoAdjustDelay: number; private static _instance; - static readonly Instance: TimeRuler; + targetSampleFrames: number; + width: number; + enabled: true; + showLog: boolean; private _frameKey; private _logKey; private _logs; private sampleFrames; - targetSampleFrames: number; - width: number; - enabled: true; private _position; private _prevLog; private _curLog; @@ -1737,16 +1737,16 @@ declare module es { private stopwacth; private _markerNameToIdMap; private _updateCount; - showLog: boolean; private _frameAdjust; constructor(); - private onGraphicsDeviceReset; + static readonly Instance: TimeRuler; startFrame(): void; beginMark(markerName: string, color: number, barIndex?: number): void; endMark(markerName: string, barIndex?: number): void; getAverageTime(barIndex: number, markerName: string): number; resetLog(): void; render(position?: Vector2, width?: number): void; + private onGraphicsDeviceReset; } class FrameLog { bars: MarkerCollection[]; diff --git a/source/bin/framework.js b/source/bin/framework.js index c4d4c03b..ef454902 100644 --- a/source/bin/framework.js +++ b/source/bin/framework.js @@ -326,6 +326,17 @@ var es; } return foundPath ? this.recontructPath(cameFrom, start, goal) : null; }; + AStarPathfinder.recontructPath = function (cameFrom, start, goal) { + var path = []; + var current = goal; + path.push(goal); + while (current != start) { + current = this.getKey(cameFrom, current); + path.push(current); + } + path.reverse(); + return path; + }; AStarPathfinder.hasKey = function (map, compareKey) { var iterator = map.keys(); var r; @@ -346,17 +357,6 @@ var es; } return null; }; - AStarPathfinder.recontructPath = function (cameFrom, start, goal) { - var path = []; - var current = goal; - path.push(goal); - while (current != start) { - current = this.getKey(cameFrom, current); - path.push(current); - } - path.reverse(); - return path; - }; return AStarPathfinder; }()); es.AStarPathfinder = AStarPathfinder; @@ -426,10 +426,6 @@ var es; this._nodes = new Array(maxNodes + 1); this._numNodesEverEnqueued = 0; } - PriorityQueue.prototype.clear = function () { - this._nodes.splice(1, this._numNodes); - this._numNodes = 0; - }; Object.defineProperty(PriorityQueue.prototype, "count", { get: function () { return this._numNodes; @@ -444,6 +440,10 @@ var es; enumerable: true, configurable: true }); + PriorityQueue.prototype.clear = function () { + this._nodes.splice(1, this._numNodes); + this._numNodes = 0; + }; PriorityQueue.prototype.contains = function (node) { if (!node) { console.error("node cannot be null"); @@ -664,26 +664,6 @@ var es; enumerable: true, configurable: true }); - Vector2.prototype.add = function (value) { - this.x += value.x; - this.y += value.y; - return this; - }; - Vector2.prototype.divide = function (value) { - this.x /= value.x; - this.y /= value.y; - return this; - }; - Vector2.prototype.multiply = function (value) { - this.x *= value.x; - this.y *= value.y; - return this; - }; - Vector2.prototype.subtract = function (value) { - this.x -= value.x; - this.y -= value.y; - return this; - }; Vector2.add = function (value1, value2) { var result = new Vector2(0, 0); result.x = value1.x + value2.x; @@ -708,17 +688,6 @@ var es; result.y = value1.y - value2.y; return result; }; - Vector2.prototype.normalize = function () { - var val = 1 / Math.sqrt((this.x * this.x) + (this.y * this.y)); - this.x *= val; - this.y *= val; - }; - Vector2.prototype.length = function () { - return Math.sqrt((this.x * this.x) + (this.y * this.y)); - }; - Vector2.prototype.round = function () { - return new Vector2(Math.round(this.x), Math.round(this.y)); - }; Vector2.normalize = function (value) { var val = 1 / Math.sqrt((value.x * value.x) + (value.y * value.y)); value.x *= val; @@ -751,6 +720,37 @@ var es; result.y = -value.y; return result; }; + Vector2.prototype.add = function (value) { + this.x += value.x; + this.y += value.y; + return this; + }; + Vector2.prototype.divide = function (value) { + this.x /= value.x; + this.y /= value.y; + return this; + }; + Vector2.prototype.multiply = function (value) { + this.x *= value.x; + this.y *= value.y; + return this; + }; + Vector2.prototype.subtract = function (value) { + this.x -= value.x; + this.y -= value.y; + return this; + }; + Vector2.prototype.normalize = function () { + var val = 1 / Math.sqrt((this.x * this.x) + (this.y * this.y)); + this.x *= val; + this.y *= val; + }; + Vector2.prototype.length = function () { + return Math.sqrt((this.x * this.x) + (this.y * this.y)); + }; + Vector2.prototype.round = function () { + return new Vector2(Math.round(this.x), Math.round(this.y)); + }; Vector2.prototype.equals = function (other) { return other.x == this.x && other.y == this.y; }; @@ -915,6 +915,17 @@ var es; } return foundPath ? this.recontructPath(cameFrom, start, goal) : null; }; + WeightedPathfinder.recontructPath = function (cameFrom, start, goal) { + var path = []; + var current = goal; + path.push(goal); + while (current != start) { + current = this.getKey(cameFrom, current); + path.push(current); + } + path.reverse(); + return path; + }; WeightedPathfinder.hasKey = function (map, compareKey) { var iterator = map.keys(); var r; @@ -935,17 +946,6 @@ var es; } return null; }; - WeightedPathfinder.recontructPath = function (cameFrom, start, goal) { - var path = []; - var current = goal; - path.push(goal); - while (current != start) { - current = this.getKey(cameFrom, current); - path.push(current); - } - path.reverse(); - return path; - }; return WeightedPathfinder; }()); es.WeightedPathfinder = WeightedPathfinder; @@ -1147,57 +1147,32 @@ var es; enumerable: true, configurable: true }); - Core.prototype.onAddToStage = function () { - Core.graphicsDevice = new es.GraphicsDevice(); - this.addEventListener(egret.Event.RESIZE, this.onGraphicsDeviceReset, this); - this.addEventListener(egret.StageOrientationEvent.ORIENTATION_CHANGE, this.onOrientationChanged, this); - this.addEventListener(egret.Event.ENTER_FRAME, this.update, this); - es.Input.initialize(); - this.initialize(); + Core.startSceneTransition = function (sceneTransition) { + if (this._instance._sceneTransition) { + console.warn("在前一个场景完成之前,不能开始一个新的场景转换。"); + return; + } + this._instance._sceneTransition = sceneTransition; + return sceneTransition; + }; + Core.registerGlobalManager = function (manager) { + this._instance._globalManagers.push(manager); + manager.enabled = true; + }; + Core.unregisterGlobalManager = function (manager) { + this._instance._globalManagers.remove(manager); + manager.enabled = false; + }; + Core.getGlobalManager = function (type) { + for (var i = 0; i < this._instance._globalManagers.length; i++) { + if (this._instance._globalManagers[i] instanceof type) + return this._instance._globalManagers[i]; + } + return null; }; Core.prototype.onOrientationChanged = function () { Core.emitter.emit(es.CoreEvents.OrientationChanged); }; - Core.prototype.onGraphicsDeviceReset = function () { - Core.emitter.emit(es.CoreEvents.GraphicsDeviceReset); - }; - Core.prototype.initialize = function () { - }; - Core.prototype.update = function () { - return __awaiter(this, void 0, void 0, function () { - var i; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - es.Time.update(egret.getTimer()); - if (!this._scene) return [3, 2]; - for (i = this._globalManagers.length - 1; i >= 0; i--) { - if (this._globalManagers[i].enabled) - this._globalManagers[i].update(); - } - if (!this._sceneTransition || - (this._sceneTransition && (!this._sceneTransition.loadsNewScene || this._sceneTransition.isNewSceneLoaded))) { - this._scene.update(); - } - if (!this._nextScene) return [3, 2]; - this.removeChild(this._scene); - this._scene.end(); - this._scene = this._nextScene; - this._nextScene = null; - this.onSceneChanged(); - this.addChild(this._scene); - return [4, this._scene.begin()]; - case 1: - _a.sent(); - _a.label = 2; - case 2: return [4, this.draw()]; - case 3: - _a.sent(); - return [2]; - } - }); - }); - }; Core.prototype.draw = function () { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { @@ -1245,28 +1220,53 @@ var es; Core.emitter.emit(es.CoreEvents.SceneChanged); es.Time.sceneChanged(); }; - Core.startSceneTransition = function (sceneTransition) { - if (this._instance._sceneTransition) { - console.warn("在前一个场景完成之前,不能开始一个新的场景转换。"); - return; - } - this._instance._sceneTransition = sceneTransition; - return sceneTransition; + Core.prototype.onGraphicsDeviceReset = function () { + Core.emitter.emit(es.CoreEvents.GraphicsDeviceReset); }; - Core.registerGlobalManager = function (manager) { - this._instance._globalManagers.push(manager); - manager.enabled = true; + Core.prototype.initialize = function () { }; - Core.unregisterGlobalManager = function (manager) { - this._instance._globalManagers.remove(manager); - manager.enabled = false; + Core.prototype.update = function () { + return __awaiter(this, void 0, void 0, function () { + var i; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + es.Time.update(egret.getTimer()); + if (!this._scene) return [3, 2]; + for (i = this._globalManagers.length - 1; i >= 0; i--) { + if (this._globalManagers[i].enabled) + this._globalManagers[i].update(); + } + if (!this._sceneTransition || + (this._sceneTransition && (!this._sceneTransition.loadsNewScene || this._sceneTransition.isNewSceneLoaded))) { + this._scene.update(); + } + if (!this._nextScene) return [3, 2]; + this.removeChild(this._scene); + this._scene.end(); + this._scene = this._nextScene; + this._nextScene = null; + this.onSceneChanged(); + this.addChild(this._scene); + return [4, this._scene.begin()]; + case 1: + _a.sent(); + _a.label = 2; + case 2: return [4, this.draw()]; + case 3: + _a.sent(); + return [2]; + } + }); + }); }; - Core.getGlobalManager = function (type) { - for (var i = 0; i < this._instance._globalManagers.length; i++) { - if (this._instance._globalManagers[i] instanceof type) - return this._instance._globalManagers[i]; - } - return null; + Core.prototype.onAddToStage = function () { + Core.graphicsDevice = new es.GraphicsDevice(); + this.addEventListener(egret.Event.RESIZE, this.onGraphicsDeviceReset, this); + this.addEventListener(egret.StageOrientationEvent.ORIENTATION_CHANGE, this.onOrientationChanged, this); + this.addEventListener(egret.Event.ENTER_FRAME, this.update, this); + es.Input.initialize(); + this.initialize(); }; return Core; }(egret.DisplayObjectContainer)); @@ -1295,6 +1295,13 @@ var es; this.id = Entity._idGenerator++; this.componentBits = new es.BitSet(); } + Object.defineProperty(Entity.prototype, "isDestroyed", { + get: function () { + return this._isDestroyed; + }, + enumerable: true, + configurable: true + }); Object.defineProperty(Entity.prototype, "tag", { get: function () { return this._tag; @@ -1325,13 +1332,6 @@ var es; enumerable: true, configurable: true }); - Object.defineProperty(Entity.prototype, "isDestroyed", { - get: function () { - return this._isDestroyed; - }, - enumerable: true, - configurable: true - }); Object.defineProperty(Entity.prototype, "parent", { get: function () { return this.transform.parent; @@ -1513,24 +1513,6 @@ var es; entity.transform.position = position; return entity; }; - Entity.prototype.copyFrom = function (entity) { - this.tag = entity.tag; - this.updateInterval = entity.updateInterval; - this.updateOrder = entity.updateOrder; - this.enabled = entity.enabled; - this.transform.scale = entity.transform.scale; - this.transform.rotation = entity.transform.rotation; - for (var i = 0; i < entity.components.count; i++) - this.addComponent(entity.components.buffer[i].clone()); - for (var i = 0; i < entity.components._componentsToAdd.length; i++) - this.addComponent(entity.components._componentsToAdd[i].clone()); - for (var i = 0; i < entity.transform.childCount; i++) { - var child = entity.transform.getChild(i).entity; - var childClone = child.clone(); - childClone.transform.copyFrom(child.transform); - childClone.transform.parent = this.transform; - } - }; Entity.prototype.onAddedToScene = function () { }; Entity.prototype.onRemovedFromScene = function () { @@ -1587,6 +1569,24 @@ var es; Entity.prototype.toString = function () { return "[Entity: name: " + this.name + ", tag: " + this.tag + ", enabled: " + this.enabled + ", depth: " + this.updateOrder + "]"; }; + Entity.prototype.copyFrom = function (entity) { + this.tag = entity.tag; + this.updateInterval = entity.updateInterval; + this.updateOrder = entity.updateOrder; + this.enabled = entity.enabled; + this.transform.scale = entity.transform.scale; + this.transform.rotation = entity.transform.rotation; + for (var i = 0; i < entity.components.count; i++) + this.addComponent(entity.components.buffer[i].clone()); + for (var i = 0; i < entity.components._componentsToAdd.length; i++) + this.addComponent(entity.components._componentsToAdd[i].clone()); + for (var i = 0; i < entity.transform.childCount; i++) { + var child = entity.transform.getChild(i).entity; + var childClone = child.clone(); + childClone.transform.copyFrom(child.transform); + childClone.transform.parent = this.transform; + } + }; return Entity; }()); es.Entity = Entity; @@ -1612,15 +1612,21 @@ var es; scene.addRenderer(new es.DefaultRenderer()); return scene; }; - Scene.prototype.initialize = function () { }; - Scene.prototype.onStart = function () { - return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { - return [2]; - }); }); + Scene.prototype.initialize = function () { + }; + Scene.prototype.onStart = function () { + return __awaiter(this, void 0, void 0, function () { + return __generator(this, function (_a) { + return [2]; + }); + }); + }; + Scene.prototype.unload = function () { + }; + Scene.prototype.onActive = function () { + }; + Scene.prototype.onDeactive = function () { }; - Scene.prototype.unload = function () { }; - Scene.prototype.onActive = function () { }; - Scene.prototype.onDeactive = function () { }; Scene.prototype.begin = function () { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { @@ -1802,11 +1808,11 @@ var es; var _this = _super.call(this) || this; _this._localTransform = es.Matrix2D.create(); _this._worldTransform = es.Matrix2D.create().identity(); - _this._worldToLocalTransform = es.Matrix2D.create().identity(); - _this._worldInverseTransform = es.Matrix2D.create().identity(); _this._rotationMatrix = es.Matrix2D.create(); _this._translationMatrix = es.Matrix2D.create(); _this._scaleMatrix = es.Matrix2D.create(); + _this._worldToLocalTransform = es.Matrix2D.create().identity(); + _this._worldInverseTransform = es.Matrix2D.create().identity(); _this._position = es.Vector2.zero; _this._scale = es.Vector2.one; _this._rotation = 0; @@ -1818,6 +1824,41 @@ var es; _this._children = []; return _this; } + Object.defineProperty(Transform.prototype, "childCount", { + get: function () { + return this._children.length; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Transform.prototype, "rotationDegrees", { + get: function () { + return es.MathHelper.toDegrees(this._rotation); + }, + set: function (value) { + this.setRotation(es.MathHelper.toRadians(value)); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Transform.prototype, "localRotationDegrees", { + get: function () { + return es.MathHelper.toDegrees(this._localRotation); + }, + set: function (value) { + this.localRotation = es.MathHelper.toRadians(value); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Transform.prototype, "localToWorldTransform", { + get: function () { + this.updateTransform(); + return this._worldTransform; + }, + enumerable: true, + configurable: true + }); Object.defineProperty(Transform.prototype, "parent", { get: function () { return this._parent; @@ -1828,9 +1869,31 @@ var es; enumerable: true, configurable: true }); - Object.defineProperty(Transform.prototype, "childCount", { + Object.defineProperty(Transform.prototype, "worldToLocalTransform", { get: function () { - return this._children.length; + if (this._worldToLocalDirty) { + if (!this.parent) { + this._worldToLocalTransform = es.Matrix2D.create().identity(); + } + else { + this.parent.updateTransform(); + this._worldToLocalTransform = this.parent._worldTransform.invert(); + } + this._worldToLocalDirty = false; + } + return this._worldToLocalTransform; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Transform.prototype, "worldInverseTransform", { + get: function () { + this.updateTransform(); + if (this._worldInverseDirty) { + this._worldInverseTransform = this._worldTransform.invert(); + this._worldInverseDirty = false; + } + return this._worldInverseTransform; }, enumerable: true, configurable: true @@ -1856,13 +1919,13 @@ var es; enumerable: true, configurable: true }); - Object.defineProperty(Transform.prototype, "localPosition", { + Object.defineProperty(Transform.prototype, "scale", { get: function () { this.updateTransform(); - return this._localPosition; + return this._scale; }, set: function (value) { - this.setLocalPosition(value); + this.setScale(value); }, enumerable: true, configurable: true @@ -1878,44 +1941,13 @@ var es; enumerable: true, configurable: true }); - Object.defineProperty(Transform.prototype, "rotationDegrees", { - get: function () { - return es.MathHelper.toDegrees(this._rotation); - }, - set: function (value) { - this.setRotation(es.MathHelper.toRadians(value)); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Transform.prototype, "localRotation", { + Object.defineProperty(Transform.prototype, "localPosition", { get: function () { this.updateTransform(); - return this._localRotation; + return this._localPosition; }, set: function (value) { - this.setLocalRotation(value); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Transform.prototype, "localRotationDegrees", { - get: function () { - return es.MathHelper.toDegrees(this._localRotation); - }, - set: function (value) { - this.localRotation = es.MathHelper.toRadians(value); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Transform.prototype, "scale", { - get: function () { - this.updateTransform(); - return this._scale; - }, - set: function (value) { - this.setScale(value); + this.setLocalPosition(value); }, enumerable: true, configurable: true @@ -1931,39 +1963,13 @@ var es; enumerable: true, configurable: true }); - Object.defineProperty(Transform.prototype, "worldInverseTransform", { + Object.defineProperty(Transform.prototype, "localRotation", { get: function () { this.updateTransform(); - if (this._worldInverseDirty) { - this._worldInverseTransform = this._worldTransform.invert(); - this._worldInverseDirty = false; - } - return this._worldInverseTransform; + return this._localRotation; }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Transform.prototype, "localToWorldTransform", { - get: function () { - this.updateTransform(); - return this._worldTransform; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Transform.prototype, "worldToLocalTransform", { - get: function () { - if (this._worldToLocalDirty) { - if (!this.parent) { - this._worldToLocalTransform = es.Matrix2D.create().identity(); - } - else { - this.parent.updateTransform(); - this._worldToLocalTransform = this.parent._worldTransform.invert(); - } - this._worldToLocalDirty = false; - } - return this._worldToLocalTransform; + set: function (value) { + this.setLocalRotation(value); }, enumerable: true, configurable: true @@ -2152,13 +2158,7 @@ var es; if (targetEntity === void 0) { targetEntity = null; } if (cameraStyle === void 0) { cameraStyle = CameraStyle.lockOn; } var _this = _super.call(this) || this; - _this._minimumZoom = 0.3; - _this._maximumZoom = 3; - _this._bounds = new es.Rectangle(); _this._inset = new CameraInset(); - _this._transformMatrix = new es.Matrix2D().identity(); - _this._inverseTransformMatrix = new es.Matrix2D().identity(); - _this._origin = es.Vector2.zero; _this._areMatrixedDirty = true; _this._areBoundsDirty = true; _this._isProjectionMatrixDirty = true; @@ -2169,6 +2169,12 @@ var es; _this.mapSize = es.Vector2.zero; _this._desiredPositionDelta = new es.Vector2(); _this._worldSpaceDeadZone = new es.Rectangle(); + _this._minimumZoom = 0.3; + _this._maximumZoom = 3; + _this._bounds = new es.Rectangle(); + _this._transformMatrix = new es.Matrix2D().identity(); + _this._inverseTransformMatrix = new es.Matrix2D().identity(); + _this._origin = es.Vector2.zero; _this._targetEntity = targetEntity; _this._cameraStyle = cameraStyle; _this.setZoom(0); @@ -2294,25 +2300,6 @@ var es; this.origin = new es.Vector2(newWidth / 2, newHeight / 2); this.entity.transform.position = es.Vector2.add(this.entity.transform.position, es.Vector2.subtract(this._origin, oldOrigin)); }; - Camera.prototype.updateMatrixes = function () { - if (!this._areMatrixedDirty) - return; - var tempMat; - this._transformMatrix = es.Matrix2D.create().translate(-this.entity.transform.position.x, -this.entity.transform.position.y); - if (this._zoom != 1) { - tempMat = es.Matrix2D.create().scale(this._zoom, this._zoom); - this._transformMatrix = this._transformMatrix.multiply(tempMat); - } - if (this.entity.transform.rotation != 0) { - tempMat = es.Matrix2D.create().rotate(this.entity.transform.rotation); - this._transformMatrix = this._transformMatrix.multiply(tempMat); - } - tempMat = es.Matrix2D.create().translate(this._origin.x, this._origin.y); - this._transformMatrix = this._transformMatrix.multiply(tempMat); - this._inverseTransformMatrix = this._transformMatrix.invert(); - this._areBoundsDirty = true; - this._areMatrixedDirty = false; - }; Camera.prototype.setInset = function (left, right, top, bottom) { this._inset = new CameraInset(); this._inset.left = left; @@ -2460,6 +2447,25 @@ var es; Camera.prototype.setCenteredDeadzone = function (width, height) { this.deadzone = new es.Rectangle((this.bounds.width - width) / 2, (this.bounds.height - height) / 2, width, height); }; + Camera.prototype.updateMatrixes = function () { + if (!this._areMatrixedDirty) + return; + var tempMat; + this._transformMatrix = es.Matrix2D.create().translate(-this.entity.transform.position.x, -this.entity.transform.position.y); + if (this._zoom != 1) { + tempMat = es.Matrix2D.create().scale(this._zoom, this._zoom); + this._transformMatrix = this._transformMatrix.multiply(tempMat); + } + if (this.entity.transform.rotation != 0) { + tempMat = es.Matrix2D.create().rotate(this.entity.transform.rotation); + this._transformMatrix = this._transformMatrix.multiply(tempMat); + } + tempMat = es.Matrix2D.create().translate(this._origin.x, this._origin.y); + this._transformMatrix = this._transformMatrix.multiply(tempMat); + this._inverseTransformMatrix = this._transformMatrix.invert(); + this._areBoundsDirty = true; + this._areMatrixedDirty = false; + }; return Camera; }(es.Component)); es.Camera = Camera; @@ -2518,10 +2524,10 @@ var es; var _this = _super !== null && _super.apply(this, arguments) || this; _this.displayObject = new egret.DisplayObject(); _this.color = 0x000000; + _this._areBoundsDirty = true; _this._localOffset = es.Vector2.zero; _this._renderLayer = 0; _this._bounds = new es.Rectangle(); - _this._areBoundsDirty = true; return _this; } Object.defineProperty(RenderableComponent.prototype, "width", { @@ -2538,13 +2544,12 @@ var es; enumerable: true, configurable: true }); - Object.defineProperty(RenderableComponent.prototype, "bounds", { + Object.defineProperty(RenderableComponent.prototype, "localOffset", { get: function () { - if (this._areBoundsDirty) { - this._bounds.calculateBounds(this.entity.transform.position, this._localOffset, es.Vector2.zero, this.entity.transform.scale, this.entity.transform.rotation, this.width, this.height); - this._areBoundsDirty = false; - } - return this._bounds; + return this._localOffset; + }, + set: function (value) { + this.setLocalOffset(value); }, enumerable: true, configurable: true @@ -2558,12 +2563,13 @@ var es; enumerable: true, configurable: true }); - Object.defineProperty(RenderableComponent.prototype, "localOffset", { + Object.defineProperty(RenderableComponent.prototype, "bounds", { get: function () { - return this._localOffset; - }, - set: function (value) { - this.setLocalOffset(value); + if (this._areBoundsDirty) { + this._bounds.calculateBounds(this.entity.transform.position, this._localOffset, es.Vector2.zero, this.entity.transform.scale, this.entity.transform.rotation, this.width, this.height); + this._areBoundsDirty = false; + } + return this._bounds; }, enumerable: true, configurable: true @@ -2587,12 +2593,6 @@ var es; RenderableComponent.prototype.onEntityTransformChanged = function (comp) { this._areBoundsDirty = true; }; - RenderableComponent.prototype.onBecameVisible = function () { - this.displayObject.visible = this.isVisible; - }; - RenderableComponent.prototype.onBecameInvisible = function () { - this.displayObject.visible = this.isVisible; - }; RenderableComponent.prototype.isVisibleFromCamera = function (camera) { this.isVisible = camera.bounds.intersects(this.bounds); return this.isVisible; @@ -2626,6 +2626,12 @@ var es; RenderableComponent.prototype.toString = function () { return "[RenderableComponent] renderLayer: " + this.renderLayer; }; + RenderableComponent.prototype.onBecameVisible = function () { + this.displayObject.visible = this.isVisible; + }; + RenderableComponent.prototype.onBecameInvisible = function () { + this.displayObject.visible = this.isVisible; + }; return RenderableComponent; }(es.Component)); es.RenderableComponent = RenderableComponent; @@ -2678,16 +2684,6 @@ var es; enumerable: true, configurable: true }); - Object.defineProperty(SpriteRenderer.prototype, "origin", { - get: function () { - return this._origin; - }, - set: function (value) { - this.setOrigin(value); - }, - enumerable: true, - configurable: true - }); Object.defineProperty(SpriteRenderer.prototype, "originNormalized", { get: function () { return new es.Vector2(this._origin.x / this.width * this.entity.transform.scale.x, this._origin.y / this.height * this.entity.transform.scale.y); @@ -2698,6 +2694,16 @@ var es; enumerable: true, configurable: true }); + Object.defineProperty(SpriteRenderer.prototype, "origin", { + get: function () { + return this._origin; + }, + set: function (value) { + this.setOrigin(value); + }, + enumerable: true, + configurable: true + }); Object.defineProperty(SpriteRenderer.prototype, "sprite", { get: function () { return this._sprite; @@ -2888,8 +2894,8 @@ var es; var _this = _super.call(this, sprite) || this; _this.speed = 1; _this.animationState = State.none; - _this._animations = new Map(); _this._elapsedTime = 0; + _this._animations = new Map(); return _this; } Object.defineProperty(SpriteAnimator.prototype, "isRunning", { @@ -3076,21 +3082,11 @@ var es; _this.collidesWithLayers = es.Physics.allLayers; _this.shouldColliderScaleAndRotateWithTransform = true; _this.registeredPhysicsBounds = new es.Rectangle(); - _this._localOffset = es.Vector2.zero; _this._isPositionDirty = true; _this._isRotationDirty = true; + _this._localOffset = es.Vector2.zero; return _this; } - Object.defineProperty(Collider.prototype, "localOffset", { - get: function () { - return this._localOffset; - }, - set: function (value) { - this.setLocalOffset(value); - }, - enumerable: true, - configurable: true - }); Object.defineProperty(Collider.prototype, "absolutePosition", { get: function () { return es.Vector2.add(this.entity.transform.position, this._localOffset); @@ -3118,6 +3114,16 @@ var es; enumerable: true, configurable: true }); + Object.defineProperty(Collider.prototype, "localOffset", { + get: function () { + return this._localOffset; + }, + set: function (value) { + this.setLocalOffset(value); + }, + enumerable: true, + configurable: true + }); Collider.prototype.setLocalOffset = function (offset) { if (this._localOffset != offset) { this.unregisterColliderWithPhysicsSystem(); @@ -3352,13 +3358,6 @@ var es; this._entities = []; this._matcher = matcher ? matcher : es.Matcher.empty(); } - Object.defineProperty(EntitySystem.prototype, "matcher", { - get: function () { - return this._matcher; - }, - enumerable: true, - configurable: true - }); Object.defineProperty(EntitySystem.prototype, "scene", { get: function () { return this._scene; @@ -3370,6 +3369,13 @@ var es; enumerable: true, configurable: true }); + Object.defineProperty(EntitySystem.prototype, "matcher", { + get: function () { + return this._matcher; + }, + enumerable: true, + configurable: true + }); EntitySystem.prototype.initialize = function () { }; EntitySystem.prototype.onChanged = function (entity) { @@ -3521,13 +3527,6 @@ var es; this._bits[i] = 0; } }; - BitSet.prototype.ensure = function (lastElt) { - if (lastElt >= this._bits.length) { - var nd = new Number[lastElt + 1]; - nd = this._bits.copyWithin(0, 0, this._bits.length); - this._bits = nd; - } - }; BitSet.prototype.get = function (pos) { var offset = pos >> 6; if (offset >= this._bits.length) @@ -3576,6 +3575,13 @@ var es; this.clear(pos); } }; + BitSet.prototype.ensure = function (lastElt) { + if (lastElt >= this._bits.length) { + var nd = new Number[lastElt + 1]; + nd = this._bits.copyWithin(0, 0, this._bits.length); + this._bits = nd; + } + }; BitSet.LONG_MASK = 0x3f; return BitSet; }()); @@ -4016,16 +4022,6 @@ var es; EntityProcessorList.prototype.onEntityRemoved = function (entity) { this.removeFromProcessors(entity); }; - EntityProcessorList.prototype.notifyEntityChanged = function (entity) { - for (var i = 0; i < this._processors.length; i++) { - this._processors[i].onChanged(entity); - } - }; - EntityProcessorList.prototype.removeFromProcessors = function (entity) { - for (var i = 0; i < this._processors.length; i++) { - this._processors[i].remove(entity); - } - }; EntityProcessorList.prototype.begin = function () { }; EntityProcessorList.prototype.update = function () { @@ -4048,6 +4044,16 @@ var es; } return null; }; + EntityProcessorList.prototype.notifyEntityChanged = function (entity) { + for (var i = 0; i < this._processors.length; i++) { + this._processors[i].onChanged(entity); + } + }; + EntityProcessorList.prototype.removeFromProcessors = function (entity) { + for (var i = 0; i < this._processors.length; i++) { + this._processors[i].remove(entity); + } + }; return EntityProcessorList; }()); es.EntityProcessorList = EntityProcessorList; @@ -4758,16 +4764,6 @@ var es; this._minDepth = 0; this._maxDepth = 1; } - Object.defineProperty(Viewport.prototype, "height", { - get: function () { - return this._height; - }, - set: function (value) { - this._height = value; - }, - enumerable: true, - configurable: true - }); Object.defineProperty(Viewport.prototype, "width", { get: function () { return this._width; @@ -4778,6 +4774,16 @@ var es; enumerable: true, configurable: true }); + Object.defineProperty(Viewport.prototype, "height", { + get: function () { + return this._height; + }, + set: function (value) { + this._height = value; + }, + enumerable: true, + configurable: true + }); Object.defineProperty(Viewport.prototype, "aspectRatio", { get: function () { if ((this._height != 0) && (this._width != 0)) @@ -4902,9 +4908,7 @@ var es; PostProcessor.prototype.process = function () { this.drawFullscreenQuad(); }; - PostProcessor.prototype.onSceneBackBufferSizeChanged = function (newWidth, newHeight) { }; - PostProcessor.prototype.drawFullscreenQuad = function () { - this.scene.filters = [this.effect]; + PostProcessor.prototype.onSceneBackBufferSizeChanged = function (newWidth, newHeight) { }; PostProcessor.prototype.unload = function () { if (this.effect) { @@ -4913,6 +4917,9 @@ var es; this.scene.removeChild(this.shape); this.scene = null; }; + PostProcessor.prototype.drawFullscreenQuad = function () { + this.scene.filters = [this.effect]; + }; PostProcessor.default_vert = "attribute vec2 aVertexPosition;\n" + "attribute vec2 aTextureCoord;\n" + "attribute vec2 aColor;\n" + @@ -4953,17 +4960,20 @@ var es; this.camera = camera; this.renderOrder = renderOrder; } - Renderer.prototype.onAddedToScene = function (scene) { }; - Renderer.prototype.unload = function () { }; - Renderer.prototype.beginRender = function (cam) { }; - Renderer.prototype.renderAfterStateCheck = function (renderable, cam) { - renderable.render(cam); + Renderer.prototype.onAddedToScene = function (scene) { + }; + Renderer.prototype.unload = function () { }; Renderer.prototype.onSceneBackBufferSizeChanged = function (newWidth, newHeight) { }; Renderer.prototype.compareTo = function (other) { return this.renderOrder - other.renderOrder; }; + Renderer.prototype.beginRender = function (cam) { + }; + Renderer.prototype.renderAfterStateCheck = function (renderable, cam) { + renderable.render(cam); + }; return Renderer; }()); es.Renderer = Renderer; @@ -5024,15 +5034,6 @@ var es; enumerable: true, configurable: true }); - PolyLight.prototype.computeTriangleIndices = function (totalTris) { - if (totalTris === void 0) { totalTris = 20; } - this._indices.length = 0; - for (var i = 0; i < totalTris; i += 2) { - this._indices.push(0); - this._indices.push(i + 2); - this._indices.push(i + 1); - } - }; PolyLight.prototype.setRadius = function (radius) { if (radius != this._radius) { this._radius = radius; @@ -5043,6 +5044,15 @@ var es; }; PolyLight.prototype.reset = function () { }; + PolyLight.prototype.computeTriangleIndices = function (totalTris) { + if (totalTris === void 0) { totalTris = 20; } + this._indices.length = 0; + for (var i = 0; i < totalTris; i += 2) { + this._indices.push(0); + this._indices.push(i + 2); + this._indices.push(i + 1); + } + }; return PolyLight; }(es.RenderableComponent)); es.PolyLight = PolyLight; @@ -5065,7 +5075,8 @@ var es; enumerable: true, configurable: true }); - SceneTransition.prototype.preRender = function () { }; + SceneTransition.prototype.preRender = function () { + }; SceneTransition.prototype.render = function () { }; SceneTransition.prototype.onBeginTransition = function () { @@ -5081,6 +5092,16 @@ var es; }); }); }; + SceneTransition.prototype.tickEffectProgressProperty = function (filter, duration, easeType, reverseDirection) { + if (reverseDirection === void 0) { reverseDirection = false; } + return new Promise(function (resolve) { + var start = reverseDirection ? 1 : 0; + var end = reverseDirection ? 0 : 1; + egret.Tween.get(filter.uniforms).set({ _progress: start }).to({ _progress: end }, duration * 1000, easeType).call(function () { + resolve(); + }); + }); + }; SceneTransition.prototype.transitionComplete = function () { es.Core._instance._sceneTransition = null; if (this.onTransitionCompleted) { @@ -5108,16 +5129,6 @@ var es; }); }); }; - SceneTransition.prototype.tickEffectProgressProperty = function (filter, duration, easeType, reverseDirection) { - if (reverseDirection === void 0) { reverseDirection = false; } - return new Promise(function (resolve) { - var start = reverseDirection ? 1 : 0; - var end = reverseDirection ? 0 : 1; - egret.Tween.get(filter.uniforms).set({ _progress: start }).to({ _progress: end }, duration * 1000, easeType).call(function () { - resolve(); - }); - }); - }; return SceneTransition; }()); es.SceneTransition = SceneTransition; @@ -5596,6 +5607,27 @@ var es; enumerable: true, configurable: true }); + Rectangle.fromMinMax = function (minX, minY, maxX, maxY) { + return new Rectangle(minX, minY, maxX - minX, maxY - minY); + }; + Rectangle.rectEncompassingPoints = function (points) { + var minX = Number.POSITIVE_INFINITY; + var minY = Number.POSITIVE_INFINITY; + var maxX = Number.NEGATIVE_INFINITY; + var maxY = Number.NEGATIVE_INFINITY; + for (var i = 0; i < points.length; i++) { + var pt = points[i]; + if (pt.x < minX) + minX = pt.x; + if (pt.x > maxX) + maxX = pt.x; + if (pt.y < minY) + minY = pt.y; + if (pt.y > maxY) + maxY = pt.y; + } + return this.fromMinMax(minX, minY, maxX, maxY); + }; Rectangle.prototype.intersects = function (value) { return value.left < this.right && this.left < value.right && @@ -5610,9 +5642,6 @@ var es; Rectangle.prototype.getHalfSize = function () { return new es.Vector2(this.width * 0.5, this.height * 0.5); }; - Rectangle.fromMinMax = function (minX, minY, maxX, maxY) { - return new Rectangle(minX, minY, maxX - minX, maxY - minY); - }; Rectangle.prototype.getClosestPointOnRectangleBorderToPoint = function (point, edgeNormal) { edgeNormal = es.Vector2.zero; var res = new es.Vector2(); @@ -5708,24 +5737,6 @@ var es; this.height = maxY - minY; } }; - Rectangle.rectEncompassingPoints = function (points) { - var minX = Number.POSITIVE_INFINITY; - var minY = Number.POSITIVE_INFINITY; - var maxX = Number.NEGATIVE_INFINITY; - var maxY = Number.NEGATIVE_INFINITY; - for (var i = 0; i < points.length; i++) { - var pt = points[i]; - if (pt.x < minX) - minX = pt.x; - if (pt.x > maxX) - maxX = pt.x; - if (pt.y < minY) - minY = pt.y; - if (pt.y > maxY) - maxY = pt.y; - } - return this.fromMinMax(minX, minY, maxX, maxY); - }; return Rectangle; }(egret.Rectangle)); es.Rectangle = Rectangle; @@ -6045,34 +6056,6 @@ var es; enumerable: true, configurable: true }); - Polygon.prototype.setPoints = function (points) { - this.points = points; - this.recalculateCenterAndEdgeNormals(); - this._originalPoints = []; - for (var i = 0; i < this.points.length; i++) { - this._originalPoints.push(this.points[i]); - } - }; - Polygon.prototype.recalculateCenterAndEdgeNormals = function () { - this._polygonCenter = Polygon.findPolygonCenter(this.points); - this._areEdgeNormalsDirty = true; - }; - Polygon.prototype.buildEdgeNormals = function () { - var totalEdges = this.isBox ? 2 : this.points.length; - if (this._edgeNormals == null || this._edgeNormals.length != totalEdges) - this._edgeNormals = new Array(totalEdges); - var p2; - for (var i = 0; i < totalEdges; i++) { - var p1 = this.points[i]; - if (i + 1 >= this.points.length) - p2 = this.points[0]; - else - p2 = this.points[i + 1]; - var perp = es.Vector2Ext.perpendicular(p1, p2); - perp = es.Vector2.normalize(perp); - this._edgeNormals[i] = perp; - } - }; Polygon.buildSymmetricalPolygon = function (vertCount, radius) { var verts = new Array(vertCount); for (var i = 0; i < vertCount; i++) { @@ -6115,6 +6098,34 @@ var es; edgeNormal = es.Vector2Ext.normalize(edgeNormal); return closestPoint; }; + Polygon.prototype.setPoints = function (points) { + this.points = points; + this.recalculateCenterAndEdgeNormals(); + this._originalPoints = []; + for (var i = 0; i < this.points.length; i++) { + this._originalPoints.push(this.points[i]); + } + }; + Polygon.prototype.recalculateCenterAndEdgeNormals = function () { + this._polygonCenter = Polygon.findPolygonCenter(this.points); + this._areEdgeNormalsDirty = true; + }; + Polygon.prototype.buildEdgeNormals = function () { + var totalEdges = this.isBox ? 2 : this.points.length; + if (this._edgeNormals == null || this._edgeNormals.length != totalEdges) + this._edgeNormals = new Array(totalEdges); + var p2; + for (var i = 0; i < totalEdges; i++) { + var p1 = this.points[i]; + if (i + 1 >= this.points.length) + p2 = this.points[0]; + else + p2 = this.points[i + 1]; + var perp = es.Vector2Ext.perpendicular(p1, p2); + perp = es.Vector2.normalize(perp); + this._edgeNormals[i] = perp; + } + }; Polygon.prototype.recalculateBounds = function (collider) { this.center = collider.localOffset; if (collider.shouldColliderScaleAndRotateWithTransform) { @@ -6512,20 +6523,6 @@ var es; this._inverseCellSize = 1 / this._cellSize; this._raycastParser = new RaycastResultParser(); } - SpatialHash.prototype.cellCoords = function (x, y) { - return new es.Vector2(Math.floor(x * this._inverseCellSize), Math.floor(y * this._inverseCellSize)); - }; - SpatialHash.prototype.cellAtPosition = function (x, y, createCellIfEmpty) { - if (createCellIfEmpty === void 0) { createCellIfEmpty = false; } - var cell = this._cellDict.tryGetValue(x, y); - if (!cell) { - if (createCellIfEmpty) { - cell = []; - this._cellDict.add(x, y, cell); - } - } - return cell; - }; SpatialHash.prototype.register = function (collider) { var bounds = collider.bounds; collider.registeredPhysicsBounds = bounds; @@ -6575,10 +6572,6 @@ var es; } } }; - SpatialHash.prototype.debugDrawCellDetails = function (x, y, cellCount, secondsToDisplay, textScale) { - if (secondsToDisplay === void 0) { secondsToDisplay = 0.5; } - if (textScale === void 0) { textScale = 1; } - }; SpatialHash.prototype.aabbBroadphase = function (bounds, excludeCollider, layerMask) { this._tempHashSet.length = 0; var p1 = this.cellCoords(bounds.x, bounds.y); @@ -6633,6 +6626,24 @@ var es; } return resultCounter; }; + SpatialHash.prototype.cellCoords = function (x, y) { + return new es.Vector2(Math.floor(x * this._inverseCellSize), Math.floor(y * this._inverseCellSize)); + }; + SpatialHash.prototype.cellAtPosition = function (x, y, createCellIfEmpty) { + if (createCellIfEmpty === void 0) { createCellIfEmpty = false; } + var cell = this._cellDict.tryGetValue(x, y); + if (!cell) { + if (createCellIfEmpty) { + cell = []; + this._cellDict.add(x, y, cell); + } + } + return cell; + }; + SpatialHash.prototype.debugDrawCellDetails = function (x, y, cellCount, secondsToDisplay, textScale) { + if (secondsToDisplay === void 0) { secondsToDisplay = 0.5; } + if (textScale === void 0) { textScale = 1; } + }; return SpatialHash; }()); es.SpatialHash = SpatialHash; @@ -6640,9 +6651,6 @@ var es; function NumberDictionary() { this._store = new Map(); } - NumberDictionary.prototype.getKey = function (x, y) { - return Long.fromNumber(x).shiftLeft(32).or(Long.fromNumber(y, true)).toString(); - }; NumberDictionary.prototype.add = function (x, y, list) { this._store.set(this.getKey(x, y), list); }; @@ -6658,6 +6666,9 @@ var es; NumberDictionary.prototype.clear = function () { this._store.clear(); }; + NumberDictionary.prototype.getKey = function (x, y) { + return Long.fromNumber(x).shiftLeft(32).or(Long.fromNumber(y, true)).toString(); + }; return NumberDictionary; }()); es.NumberDictionary = NumberDictionary; @@ -6757,12 +6768,12 @@ var ArrayUtils = (function () { aryA = this.getUniqueAry(aryA); aryB = this.getUniqueAry(aryB); var ary = aryA.concat(aryB); - var uObj = new Object(); + var uObj = {}; 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]] = {}; uObj[ary[j]].count = 0; uObj[ary[j]].key = ary[j]; uObj[ary[j]].count++; @@ -6835,26 +6846,6 @@ var ArrayUtils = (function () { var Base64Utils = (function () { function Base64Utils() { } - Base64Utils._utf8_encode = function (string) { - string = string.replace(/\r\n/g, "\n"); - var utftext = ""; - for (var n = 0; n < string.length; n++) { - var 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; - }; Base64Utils.decode = function (input, isNotStr) { if (isNotStr === void 0) { isNotStr = true; } var output = ""; @@ -6894,6 +6885,26 @@ var Base64Utils = (function () { output = this._utf8_decode(output); return output; }; + Base64Utils._utf8_encode = function (string) { + string = string.replace(/\r\n/g, "\n"); + var utftext = ""; + for (var n = 0; n < string.length; n++) { + var 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; + }; Base64Utils._utf8_decode = function (utftext) { var string = ""; var i = 0; @@ -7129,9 +7140,12 @@ var es; } } }; - GlobalManager.prototype.onEnabled = function () { }; - GlobalManager.prototype.onDisabled = function () { }; - GlobalManager.prototype.update = function () { }; + GlobalManager.prototype.onEnabled = function () { + }; + GlobalManager.prototype.onDisabled = function () { + }; + GlobalManager.prototype.update = function () { + }; return GlobalManager; }()); es.GlobalManager = GlobalManager; @@ -7164,22 +7178,9 @@ var es; var Input = (function () { function Input() { } - Object.defineProperty(Input, "touchPosition", { + Object.defineProperty(Input, "gameTouchs", { get: function () { - if (!this._gameTouchs[0]) - return es.Vector2.zero; - return this._gameTouchs[0].position; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Input, "maxSupportedTouch", { - get: function () { - return es.Core._instance.stage.maxTouches; - }, - set: function (value) { - es.Core._instance.stage.maxTouches = value; - this.initTouchCache(); + return this._gameTouchs; }, enumerable: true, configurable: true @@ -7198,9 +7199,22 @@ var es; enumerable: true, configurable: true }); - Object.defineProperty(Input, "gameTouchs", { + Object.defineProperty(Input, "touchPosition", { get: function () { - return this._gameTouchs; + if (!this._gameTouchs[0]) + return es.Vector2.zero; + return this._gameTouchs[0].position; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Input, "maxSupportedTouch", { + get: function () { + return es.Core._instance.stage.maxTouches; + }, + set: function (value) { + es.Core._instance.stage.maxTouches = value; + this.initTouchCache(); }, enumerable: true, configurable: true @@ -7227,6 +7241,10 @@ var es; es.Core._instance.stage.addEventListener(egret.TouchEvent.TOUCH_RELEASE_OUTSIDE, this.touchEnd, this); this.initTouchCache(); }; + Input.scaledPosition = function (position) { + var scaledPos = new es.Vector2(position.x - this._resolutionOffset.x, position.y - this._resolutionOffset.y); + return es.Vector2.multiply(scaledPos, this.resolutionScale); + }; Input.initTouchCache = function () { this._totalTouchCount = 0; this._touchIndex = 0; @@ -7279,16 +7297,12 @@ var es; this._previousTouchState.touchPoint = touchState.touchPoint; this._previousTouchState.touchDown = touchState.touchDown; }; - Input.scaledPosition = function (position) { - var scaledPos = new es.Vector2(position.x - this._resolutionOffset.x, position.y - this._resolutionOffset.y); - return es.Vector2.multiply(scaledPos, this.resolutionScale); - }; Input._init = false; Input._previousTouchState = new TouchState(); - Input._gameTouchs = []; Input._resolutionOffset = new es.Vector2(); - Input._resolutionScale = es.Vector2.one; Input._touchIndex = 0; + Input._gameTouchs = []; + Input._resolutionScale = es.Vector2.one; Input._totalTouchCount = 0; return Input; }()); @@ -7303,6 +7317,26 @@ var KeyboardUtils = (function () { document.addEventListener("keydown", this.onKeyDonwHander); document.addEventListener("keyup", this.onKeyUpHander); }; + 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.destroy = function () { + this.keyDownDict = null; + this.keyUpDict = null; + document.removeEventListener("keydown", this.onKeyDonwHander); + document.removeEventListener("keyup", this.onKeyUpHander); + }; KeyboardUtils.onKeyDonwHander = function (event) { if (!this.keyDownDict) return; @@ -7327,20 +7361,6 @@ var KeyboardUtils = (function () { 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: @@ -7413,12 +7433,6 @@ var KeyboardUtils = (function () { 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"; @@ -7617,9 +7631,6 @@ var RandomUtils = (function () { 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('无法对此对象执行此操作'); @@ -7651,6 +7662,9 @@ var RandomUtils = (function () { if (chance === void 0) { chance = .5; } return (this.random() < chance) ? true : false; }; + RandomUtils._randomCompare = function (a, b) { + return (this.random() > .5) ? 1 : -1; + }; return RandomUtils; }()); var es; @@ -7679,6 +7693,15 @@ var es; this._triPrev = new Array(12); this._triNext = new Array(12); } + Triangulator.testPointTriangle = function (point, a, b, c) { + if (es.Vector2Ext.cross(es.Vector2.subtract(point, a), es.Vector2.subtract(b, a)) < 0) + return false; + if (es.Vector2Ext.cross(es.Vector2.subtract(point, b), es.Vector2.subtract(c, b)) < 0) + return false; + if (es.Vector2Ext.cross(es.Vector2.subtract(point, c), es.Vector2.subtract(a, c)) < 0) + return false; + return true; + }; Triangulator.prototype.triangulate = function (points, arePointsCCW) { if (arePointsCCW === void 0) { arePointsCCW = true; } var count = points.length; @@ -7740,15 +7763,6 @@ var es; this._triPrev[0] = count - 1; this._triNext[count - 1] = 0; }; - Triangulator.testPointTriangle = function (point, a, b, c) { - if (es.Vector2Ext.cross(es.Vector2.subtract(point, a), es.Vector2.subtract(b, a)) < 0) - return false; - if (es.Vector2Ext.cross(es.Vector2.subtract(point, b), es.Vector2.subtract(c, b)) < 0) - return false; - if (es.Vector2Ext.cross(es.Vector2.subtract(point, c), es.Vector2.subtract(a, c)) < 0) - return false; - return true; - }; return Triangulator; }()); es.Triangulator = Triangulator; @@ -7918,29 +7932,6 @@ var stopwatch; Stopwatch.prototype.getTime = function () { return this.caculateStopwatchTime(); }; - Stopwatch.prototype.calculatePendingSlice = function (endStopwatchTime) { - if (this._pendingSliceStartStopwatchTime === undefined) { - return Object.freeze({ startTime: 0, endTime: 0, duration: 0 }); - } - if (endStopwatchTime === undefined) { - endStopwatchTime = this.getTime(); - } - return Object.freeze({ - startTime: this._pendingSliceStartStopwatchTime, - endTime: endStopwatchTime, - duration: endStopwatchTime - this._pendingSliceStartStopwatchTime - }); - }; - Stopwatch.prototype.caculateStopwatchTime = function (endSystemTime) { - if (this._startSystemTime === undefined) - return 0; - if (endSystemTime === undefined) - endSystemTime = this.getSystemTimeOfCurrentStopwatchTime(); - return endSystemTime - this._startSystemTime - this._stopDuration; - }; - Stopwatch.prototype.getSystemTimeOfCurrentStopwatchTime = function () { - return this._stopSystemTime === undefined ? this.getSystemTime() : this._stopSystemTime; - }; Stopwatch.prototype.reset = function () { this._startSystemTime = this._pendingSliceStartStopwatchTime = this._stopSystemTime = undefined; this._stopDuration = 0; @@ -7975,6 +7966,29 @@ var stopwatch; this._stopSystemTime = systemTimeOfStopwatchTime; return this.getTime(); }; + Stopwatch.prototype.calculatePendingSlice = function (endStopwatchTime) { + if (this._pendingSliceStartStopwatchTime === undefined) { + return Object.freeze({ startTime: 0, endTime: 0, duration: 0 }); + } + if (endStopwatchTime === undefined) { + endStopwatchTime = this.getTime(); + } + return Object.freeze({ + startTime: this._pendingSliceStartStopwatchTime, + endTime: endStopwatchTime, + duration: endStopwatchTime - this._pendingSliceStartStopwatchTime + }); + }; + Stopwatch.prototype.caculateStopwatchTime = function (endSystemTime) { + if (this._startSystemTime === undefined) + return 0; + if (endSystemTime === undefined) + endSystemTime = this.getSystemTimeOfCurrentStopwatchTime(); + return endSystemTime - this._startSystemTime - this._stopDuration; + }; + Stopwatch.prototype.getSystemTimeOfCurrentStopwatchTime = function () { + return this._stopSystemTime === undefined ? this.getSystemTime() : this._stopSystemTime; + }; Stopwatch.prototype.recordPendingSlice = function (endStopwatchTime) { if (this._pendingSliceStartStopwatchTime !== undefined) { if (endStopwatchTime === undefined) { @@ -8009,12 +8023,12 @@ var es; (function (es) { var TimeRuler = (function () { function TimeRuler() { + this.showLog = false; this._frameKey = 'frame'; this._logKey = 'log'; this.markers = []; this.stopwacth = new stopwatch.Stopwatch(); this._markerNameToIdMap = new Map(); - this.showLog = false; this._logs = new Array(2); for (var i = 0; i < this._logs.length; ++i) this._logs[i] = new FrameLog(); @@ -8032,10 +8046,6 @@ var es; enumerable: true, configurable: true }); - TimeRuler.prototype.onGraphicsDeviceReset = function () { - var layout = new es.Layout(); - this._position = layout.place(new es.Vector2(this.width, TimeRuler.barHeight), 0, 0.01, es.Alignment.bottomCenter).location; - }; TimeRuler.prototype.startFrame = function () { var _this = this; var lock = new LockUtils(this._frameKey); @@ -8205,6 +8215,10 @@ var es; var startY = position.y - (height - TimeRuler.barHeight); var y = startY; }; + TimeRuler.prototype.onGraphicsDeviceReset = function () { + var layout = new es.Layout(); + this._position = layout.place(new es.Vector2(this.width, TimeRuler.barHeight), 0, 0.01, es.Alignment.bottomCenter).location; + }; TimeRuler.maxBars = 8; TimeRuler.maxSamples = 256; TimeRuler.maxNestCall = 32; diff --git a/source/bin/framework.min.js b/source/bin/framework.min.js index 565e3b28..8f6f46d1 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 transform,__awaiter=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,o){function s(t){try{c(i.next(t))}catch(t){o(t)}}function a(t){try{c(i.throw(t))}catch(t){o(t)}}function c(t){t.done?r(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,r,o,s={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return o={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function a(o){return function(a){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,i&&(r=2&o[0]?i.return:o[0]?i.throw||((r=i.return)&&r.call(i),0):i.next)&&!(r=r.call(i,o[1])).done)return r;switch(i=0,r&&(o=[2&o[0],r.value]),o[0]){case 0:case 1:r=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,i=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(r=(r=s.trys).length>0&&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"===u())break}return s?this.recontructPath(a,i,r):null},e.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},e.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},e.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},e}();t.AStarPathfinder=e;var n=function(t){function e(e){var n=t.call(this)||this;return n.data=e,n}return __extends(e,t),e}(t.PriorityQueueNode);t.AStarNode=n}(es||(es={})),function(t){var e=function(){function e(e,n){this.dirs=[new t.Vector2(1,0),new t.Vector2(0,-1),new t.Vector2(-1,0),new t.Vector2(0,1)],this.walls=[],this.weightedNodes=[],this.defaultWeight=1,this.weightedNodeWeight=5,this._neighbors=new Array(4),this._width=e,this._height=n}return e.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"===c())break}return o?t.AStarPathfinder.recontructPath(a,n,i):null},e.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},e}();t.BreadthFirstPathfinder=e}(es||(es={})),function(t){var e=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}();t.UnweightedGraph=e}(es||(es={})),function(t){var e=function(){function e(t,e){this.x=0,this.y=0,this.x=t||0,this.y=e||this.x}return Object.defineProperty(e,"zero",{get:function(){return e.zeroVector2},enumerable:!0,configurable:!0}),Object.defineProperty(e,"one",{get:function(){return e.unitVector2},enumerable:!0,configurable:!0}),Object.defineProperty(e,"unitX",{get:function(){return e.unitXVector},enumerable:!0,configurable:!0}),Object.defineProperty(e,"unitY",{get:function(){return e.unitYVector},enumerable:!0,configurable:!0}),e.prototype.add=function(t){return this.x+=t.x,this.y+=t.y,this},e.prototype.divide=function(t){return this.x/=t.x,this.y/=t.y,this},e.prototype.multiply=function(t){return this.x*=t.x,this.y*=t.y,this},e.prototype.subtract=function(t){return this.x-=t.x,this.y-=t.y,this},e.add=function(t,n){var i=new e(0,0);return i.x=t.x+n.x,i.y=t.y+n.y,i},e.divide=function(t,n){var i=new e(0,0);return i.x=t.x/n.x,i.y=t.y/n.y,i},e.multiply=function(t,n){var i=new e(0,0);return i.x=t.x*n.x,i.y=t.y*n.y,i},e.subtract=function(t,n){var i=new e(0,0);return i.x=t.x-n.x,i.y=t.y-n.y,i},e.prototype.normalize=function(){var t=1/Math.sqrt(this.x*this.x+this.y*this.y);this.x*=t,this.y*=t},e.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},e.prototype.round=function(){return new e(Math.round(this.x),Math.round(this.y))},e.normalize=function(t){var e=1/Math.sqrt(t.x*t.x+t.y*t.y);return t.x*=e,t.y*=e,t},e.dot=function(t,e){return t.x*e.x+t.y*e.y},e.distanceSquared=function(t,e){var n=t.x-e.x,i=t.y-e.y;return n*n+i*i},e.clamp=function(n,i,r){return new e(t.MathHelper.clamp(n.x,i.x,r.x),t.MathHelper.clamp(n.y,i.y,r.y))},e.lerp=function(n,i,r){return new e(t.MathHelper.lerp(n.x,i.x,r),t.MathHelper.lerp(n.y,i.y,r))},e.transform=function(t,n){return new e(t.x*n.m11+t.y*n.m21+n.m31,t.x*n.m12+t.y*n.m22+n.m32)},e.distance=function(t,e){var n=t.x-e.x,i=t.y-e.y;return Math.sqrt(n*n+i*i)},e.negate=function(t){var n=new e;return n.x=-t.x,n.y=-t.y,n},e.prototype.equals=function(t){return t.x==this.x&&t.y==this.y},e.unitYVector=new e(0,1),e.unitXVector=new e(1,0),e.unitVector2=new e(1,1),e.zeroVector2=new e(0,0),e}();t.Vector2=e}(es||(es={})),function(t){var e=function(){function e(t,n,i){void 0===i&&(i=!1),this.walls=[],this._neighbors=new Array(4),this._width=t,this._hegiht=n,this._dirs=i?e.COMPASS_DIRS:e.CARDINAL_DIRS}return e.prototype.isNodeInBounds=function(t){return 0<=t.x&&t.x0;){if("break"===u())break}return s?this.recontructPath(a,i,r):null},n.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},n.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},n.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},n}();t.WeightedPathfinder=n}(es||(es={})),function(t){var e=function(){function e(){}return e.drawHollowRect=function(e,n,i){void 0===i&&(i=0),this._debugDrawItems.push(new t.DebugDrawItem(e,n,i))},e.render=function(){if(this._debugDrawItems.length>0){var e=new egret.Shape;t.Core.scene&&t.Core.scene.addChild(e);for(var n=this._debugDrawItems.length-1;n>=0;n--){this._debugDrawItems[n].draw(e)&&this._debugDrawItems.removeAt(n)}}},e._debugDrawItems=[],e}();t.Debug=e}(es||(es={})),function(t){var e=function(){function t(){}return t.verletParticle=14431326,t.verletConstraintEdge=4406838,t}();t.DebugDefaults=e}(es||(es={})),function(t){var e;!function(t){t[t.line=0]="line",t[t.hollowRectangle=1]="hollowRectangle",t[t.pixel=2]="pixel",t[t.text=3]="text"}(e=t.DebugDrawType||(t.DebugDrawType={}));var n=function(){function n(t,n,i){this.rectangle=t,this.color=n,this.duration=i,this.drawType=e.hollowRectangle}return n.prototype.draw=function(n){switch(this.drawType){case e.line:t.DrawUtils.drawLine(n,this.start,this.end,this.color);break;case e.hollowRectangle:t.DrawUtils.drawHollowRect(n,this.rectangle,this.color);break;case e.pixel:t.DrawUtils.drawPixel(n,new t.Vector2(this.x,this.y),this.color,this.size);break;case e.text:}return this.duration-=t.Time.deltaTime,this.duration<0},n}();t.DebugDrawItem=n}(es||(es={})),function(t){var e=function(){function t(){this.updateInterval=1,this._enabled=!0,this._updateOrder=0}return Object.defineProperty(t.prototype,"transform",{get:function(){return this.entity.transform},enumerable:!0,configurable:!0}),Object.defineProperty(t.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(t.prototype,"updateOrder",{get:function(){return this._updateOrder},set:function(t){this.setUpdateOrder(t)},enumerable:!0,configurable:!0}),t.prototype.initialize=function(){},t.prototype.onAddedToEntity=function(){},t.prototype.onRemovedFromEntity=function(){},t.prototype.onEntityTransformChanged=function(t){},t.prototype.debugRender=function(){},t.prototype.onEnabled=function(){},t.prototype.onDisabled=function(){},t.prototype.update=function(){},t.prototype.setEnabled=function(t){return this._enabled!=t&&(this._enabled=t,this._enabled?this.onEnabled():this.onDisabled()),this},t.prototype.setUpdateOrder=function(t){return this._updateOrder!=t&&(this._updateOrder=t),this},t.prototype.clone=function(){var t=ObjectUtils.clone(this);return t.entity=null,t},t}();t.Component=e}(es||(es={})),function(t){var e=function(e){function n(){var i=e.call(this)||this;return i._globalManagers=[],n._instance=i,n.emitter=new t.Emitter,n.content=new t.ContentManager,i.addEventListener(egret.Event.ADDED_TO_STAGE,i.onAddToStage,i),i}return __extends(n,e),Object.defineProperty(n,"Instance",{get:function(){return this._instance},enumerable:!0,configurable:!0}),Object.defineProperty(n,"scene",{get:function(){return this._instance?this._instance._scene:null},set:function(t){t?null==this._instance._scene?(this._instance._scene=t,this._instance.addChild(t),this._instance._scene.begin(),n.Instance.onSceneChanged()):this._instance._nextScene=t:console.error("场景不能为空")},enumerable:!0,configurable:!0}),n.prototype.onAddToStage=function(){n.graphicsDevice=new t.GraphicsDevice,this.addEventListener(egret.Event.RESIZE,this.onGraphicsDeviceReset,this),this.addEventListener(egret.StageOrientationEvent.ORIENTATION_CHANGE,this.onOrientationChanged,this),this.addEventListener(egret.Event.ENTER_FRAME,this.update,this),t.Input.initialize(),this.initialize()},n.prototype.onOrientationChanged=function(){n.emitter.emit(t.CoreEvents.OrientationChanged)},n.prototype.onGraphicsDeviceReset=function(){n.emitter.emit(t.CoreEvents.GraphicsDeviceReset)},n.prototype.initialize=function(){},n.prototype.update=function(){return __awaiter(this,void 0,void 0,function(){var e;return __generator(this,function(n){switch(n.label){case 0:if(t.Time.update(egret.getTimer()),!this._scene)return[3,2];for(e=this._globalManagers.length-1;e>=0;e--)this._globalManagers[e].enabled&&this._globalManagers[e].update();return this._sceneTransition&&(!this._sceneTransition||this._sceneTransition.loadsNewScene&&!this._sceneTransition.isNewSceneLoaded)||this._scene.update(),this._nextScene?(this.removeChild(this._scene),this._scene.end(),this._scene=this._nextScene,this._nextScene=null,this.onSceneChanged(),this.addChild(this._scene),[4,this._scene.begin()]):[3,2];case 1:n.sent(),n.label=2;case 2:return[4,this.draw()];case 3:return n.sent(),[2]}})})},n.prototype.draw=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return this._sceneTransition?(this._sceneTransition.preRender(),!this._scene||this._sceneTransition.hasPreviousSceneRender?[3,2]:(this._scene.render(),this._scene.postRender(),[4,this._sceneTransition.onBeginTransition()])):[3,4];case 1:return e.sent(),[3,3];case 2:this._sceneTransition&&(this._scene&&this._sceneTransition.isNewSceneLoaded&&(this._scene.render(),this._scene.postRender()),this._sceneTransition.render()),e.label=3;case 3:return[3,5];case 4:this._scene&&(this._scene.render(),t.Debug.render(),this._scene.postRender()),e.label=5;case 5:return[2]}})})},n.prototype.startDebugUpdate=function(){t.TimeRuler.Instance.startFrame(),t.TimeRuler.Instance.beginMark("update",65280)},n.prototype.endDebugUpdate=function(){t.TimeRuler.Instance.endMark("update")},n.prototype.onSceneChanged=function(){n.emitter.emit(t.CoreEvents.SceneChanged),t.Time.sceneChanged()},n.startSceneTransition=function(t){if(!this._instance._sceneTransition)return this._instance._sceneTransition=t,t;console.warn("在前一个场景完成之前,不能开始一个新的场景转换。")},n.registerGlobalManager=function(t){this._instance._globalManagers.push(t),t.enabled=!0},n.unregisterGlobalManager=function(t){this._instance._globalManagers.remove(t),t.enabled=!1},n.getGlobalManager=function(t){for(var e=0;e=0;t--){this.transform.getChild(t).entity.destroy()}},e.prototype.detachFromScene=function(){this.scene.entities.remove(this),this.components.deregisterAllComponents();for(var t=0;te.x?-1:1,i=t.Vector2.normalize(t.Vector2.subtract(this.position,e));this.rotation=n*Math.acos(t.Vector2.dot(i,t.Vector2.unitY))},i.prototype.setLocalRotation=function(t){return this._localRotation=t,this._localDirty=this._positionDirty=this._localPositionDirty=this._localRotationDirty=this._localScaleDirty=!0,this.setDirty(e.rotationDirty),this},i.prototype.setLocalRotationDegrees=function(e){return this.setLocalRotation(t.MathHelper.toRadians(e))},i.prototype.setScale=function(e){return this._scale=e,this.parent?this.localScale=t.Vector2.divide(e,this.parent._scale):this.localScale=e,this},i.prototype.setLocalScale=function(t){return this._localScale=t,this._localDirty=this._positionDirty=this._localScaleDirty=!0,this.setDirty(e.scaleDirty),this},i.prototype.roundPosition=function(){this.position=this._position.round()},i.prototype.updateTransform=function(){this.hierarchyDirty!=e.clean&&(this.parent&&this.parent.updateTransform(),this._localDirty&&(this._localPositionDirty&&(this._translationMatrix=t.Matrix2D.create().translate(this._localPosition.x,this._localPosition.y),this._localPositionDirty=!1),this._localRotationDirty&&(this._rotationMatrix=t.Matrix2D.create().rotate(this._localRotation),this._localRotationDirty=!1),this._localScaleDirty&&(this._scaleMatrix=t.Matrix2D.create().scale(this._localScale.x,this._localScale.y),this._localScaleDirty=!1),this._localTransform=this._scaleMatrix.multiply(this._rotationMatrix),this._localTransform=this._localTransform.multiply(this._translationMatrix),this.parent||(this._worldTransform=this._localTransform,this._rotation=this._localRotation,this._scale=this._localScale,this._worldInverseDirty=!0),this._localDirty=!1),this.parent&&(this._worldTransform=this._localTransform.multiply(this.parent._worldTransform),this._rotation=this._localRotation+this.parent._rotation,this._scale=t.Vector2.multiply(this.parent._scale,this._localScale),this._worldInverseDirty=!0),this._worldToLocalDirty=!0,this._positionDirty=!0,this.hierarchyDirty=e.clean)},i.prototype.setDirty=function(e){if(0==(this.hierarchyDirty&e)){switch(this.hierarchyDirty|=e,e){case t.DirtyType.positionDirty:this.entity.onTransformChanged(transform.Component.position);break;case t.DirtyType.rotationDirty:this.entity.onTransformChanged(transform.Component.rotation);break;case t.DirtyType.scaleDirty:this.entity.onTransformChanged(transform.Component.scale)}this._children||(this._children=[]);for(var n=0;nt&&(this._zoom=t),this._maximumZoom=t,this;console.error("maximumZoom must be greater than zero")},r.prototype.onEntityTransformChanged=function(t){this._areMatrixedDirty=!0},r.prototype.zoomIn=function(t){this.zoom+=t},r.prototype.zoomOut=function(t){this.zoom-=t},r.prototype.worldToScreenPoint=function(e){return this.updateMatrixes(),e=t.Vector2.transform(e,this._transformMatrix)},r.prototype.screenToWorldPoint=function(e){return this.updateMatrixes(),e=t.Vector2.transform(e,this._inverseTransformMatrix)},r.prototype.mouseToWorldPoint=function(){return this.screenToWorldPoint(t.Input.touchPosition)},r.prototype.onAddedToEntity=function(){this.follow(this._targetEntity,this._cameraStyle)},r.prototype.update=function(){var e=t.Vector2.multiply(new t.Vector2(this.bounds.width,this.bounds.height),new t.Vector2(.5));this._worldSpaceDeadZone.x=this.position.x-e.x*t.Core.scene.scaleX+this.deadzone.x+this.focusOffset.x,this._worldSpaceDeadZone.y=this.position.y-e.y*t.Core.scene.scaleY+this.deadzone.y+this.focusOffset.y,this._worldSpaceDeadZone.width=this.deadzone.width,this._worldSpaceDeadZone.height=this.deadzone.height,this._targetEntity&&this.updateFollow(),this.position=t.Vector2.lerp(this.position,t.Vector2.add(this.position,this._desiredPositionDelta),this.followLerp),this.entity.transform.roundPosition(),this.mapLockEnabled&&(this.position=this.clampToMapSize(this.position),this.entity.transform.roundPosition())},r.prototype.clampToMapSize=function(e){var n=t.Vector2.multiply(new t.Vector2(this.bounds.width,this.bounds.height),new t.Vector2(.5)),i=new t.Vector2(this.mapSize.x-n.x,this.mapSize.y-n.y);return t.Vector2.clamp(e,n,i)},r.prototype.updateFollow=function(){if(this._desiredPositionDelta.x=this._desiredPositionDelta.y=0,this._cameraStyle==e.lockOn){var n=this._targetEntity.transform.position.x,i=this._targetEntity.transform.position.y;this._worldSpaceDeadZone.x>n?this._desiredPositionDelta.x=n-this._worldSpaceDeadZone.x:this._worldSpaceDeadZone.xi&&(this._desiredPositionDelta.y=i-this._worldSpaceDeadZone.y)}else{if(!this._targetCollider&&(this._targetCollider=this._targetEntity.getComponent(t.Collider),!this._targetCollider))return;var r=this._targetEntity.getComponent(t.Collider).bounds;this._worldSpaceDeadZone.containsRect(r)||(this._worldSpaceDeadZone.left>r.left?this._desiredPositionDelta.x=r.left-this._worldSpaceDeadZone.left:this._worldSpaceDeadZone.rightr.top&&(this._desiredPositionDelta.y=r.top-this._worldSpaceDeadZone.top))}},r.prototype.follow=function(n,i){switch(void 0===i&&(i=e.cameraWindow),this._targetEntity=n,this._cameraStyle=i,this._cameraStyle){case e.cameraWindow:var r=this.bounds.width/6,o=this.bounds.height/3;this.deadzone=new t.Rectangle((this.bounds.width-r)/2,(this.bounds.height-o)/2,r,o);break;case e.lockOn:this.deadzone=new t.Rectangle(this.bounds.width/2,this.bounds.height/2,10,10)}},r.prototype.setCenteredDeadzone=function(e,n){this.deadzone=new t.Rectangle((this.bounds.width-e)/2,(this.bounds.height-n)/2,e,n)},r}(t.Component);t.Camera=i}(es||(es={})),function(t){var e=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}();t.ComponentPool=e}(es||(es={})),function(t){var e=function(){function t(){}return t.prototype.compare=function(t,e){return t.updateOrder-e.updateOrder},t}();t.IUpdatableComparer=e}(es||(es={})),function(t){var e=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return __extends(e,t),e}(t.Component);t.PooledComponent=e}(es||(es={})),function(t){var e=function(e){function n(){var n=null!==e&&e.apply(this,arguments)||this;return n.displayObject=new egret.DisplayObject,n.color=0,n._localOffset=t.Vector2.zero,n._renderLayer=0,n._bounds=new t.Rectangle,n._areBoundsDirty=!0,n}return __extends(n,e),Object.defineProperty(n.prototype,"width",{get:function(){return this.bounds.width},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"height",{get:function(){return this.bounds.height},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"bounds",{get:function(){return this._areBoundsDirty&&(this._bounds.calculateBounds(this.entity.transform.position,this._localOffset,t.Vector2.zero,this.entity.transform.scale,this.entity.transform.rotation,this.width,this.height),this._areBoundsDirty=!1),this._bounds},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"renderLayer",{get:function(){return this._renderLayer},set:function(t){},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"localOffset",{get:function(){return this._localOffset},set:function(t){this.setLocalOffset(t)},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"isVisible",{get:function(){return this._isVisible},set:function(t){this._isVisible!=t&&(this._isVisible=t,this._isVisible?this.onBecameVisible():this.onBecameInvisible())},enumerable:!0,configurable:!0}),n.prototype.onEntityTransformChanged=function(t){this._areBoundsDirty=!0},n.prototype.onBecameVisible=function(){this.displayObject.visible=this.isVisible},n.prototype.onBecameInvisible=function(){this.displayObject.visible=this.isVisible},n.prototype.isVisibleFromCamera=function(t){return this.isVisible=t.bounds.intersects(this.bounds),this.isVisible},n.prototype.setRenderLayer=function(t){if(t!=this._renderLayer){var e=this._renderLayer;this._renderLayer=t,this.entity&&this.entity.scene&&this.entity.scene.renderableComponents.updateRenderableRenderLayer(this,e,this._renderLayer)}return this},n.prototype.setColor=function(t){return this.color=t,this},n.prototype.setLocalOffset=function(t){return this._localOffset!=t&&(this._localOffset=t),this},n.prototype.sync=function(t){this.displayObject.x=this.entity.position.x+this.localOffset.x-t.position.x+t.origin.x,this.displayObject.y=this.entity.position.y+this.localOffset.y-t.position.y+t.origin.y,this.displayObject.scaleX=this.entity.scale.x,this.displayObject.scaleY=this.entity.scale.y,this.displayObject.rotation=this.entity.rotation},n.prototype.toString=function(){return"[RenderableComponent] renderLayer: "+this.renderLayer},n}(t.Component);t.RenderableComponent=e}(es||(es={})),function(t){var e=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.reset=function(){},e.prototype.render=function(t){},e}(t.RenderableComponent);t.Mesh=e}(es||(es={})),function(t){var e=egret.Bitmap,n=function(n){function i(e){void 0===e&&(e=null);var i=n.call(this)||this;return e instanceof t.Sprite?i.setSprite(e):e instanceof egret.Texture&&i.setSprite(new t.Sprite(e)),i}return __extends(i,n),Object.defineProperty(i.prototype,"bounds",{get:function(){return this._areBoundsDirty&&this._sprite&&(this._bounds.calculateBounds(this.entity.transform.position,this._localOffset,this._origin,this.entity.transform.scale,this.entity.transform.rotation,this._sprite.sourceRect.width,this._sprite.sourceRect.height),this._areBoundsDirty=!1),this._bounds},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"origin",{get:function(){return this._origin},set:function(t){this.setOrigin(t)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"originNormalized",{get:function(){return new t.Vector2(this._origin.x/this.width*this.entity.transform.scale.x,this._origin.y/this.height*this.entity.transform.scale.y)},set:function(e){this.setOrigin(new t.Vector2(e.x*this.width/this.entity.transform.scale.x,e.y*this.height/this.entity.transform.scale.y))},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"sprite",{get:function(){return this._sprite},set:function(t){this.setSprite(t)},enumerable:!0,configurable:!0}),i.prototype.setSprite=function(t){return this._sprite=t,this._sprite&&(this._origin=this._sprite.origin,this.displayObject.anchorOffsetX=this._origin.x,this.displayObject.anchorOffsetY=this._origin.y),this.displayObject=new e(t.texture2D),this},i.prototype.setOrigin=function(t){return this._origin!=t&&(this._origin=t,this.displayObject.anchorOffsetX=this._origin.x,this.displayObject.anchorOffsetY=this._origin.y,this._areBoundsDirty=!0),this},i.prototype.setOriginNormalized=function(e){return this.setOrigin(new t.Vector2(e.x*this.width/this.entity.transform.scale.x,e.y*this.height/this.entity.transform.scale.y)),this},i.prototype.render=function(t){this.sync(t),this.displayObject.x=this.entity.position.x-this.origin.x+this.localOffset.x-t.position.x+t.origin.x,this.displayObject.y=this.entity.position.y-this.origin.y+this.localOffset.y-t.position.y+t.origin.y},i}(t.RenderableComponent);t.SpriteRenderer=n}(es||(es={})),function(t){var e=function(t){function e(e){var n=t.call(this,e)||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))}},e}(t.SpriteRenderer);t.TiledSpriteRenderer=e}(es||(es={})),function(t){var e=function(e){function n(){var t=null!==e&&e.apply(this,arguments)||this;return t.scrollSpeedX=15,t.scroolSpeedY=0,t._scrollX=0,t._scrollY=0,t}return __extends(n,e),n.prototype.update=function(){this._scrollX+=this.scrollSpeedX*t.Time.deltaTime,this._scrollY+=this.scroolSpeedY*t.Time.deltaTime,this.sourceRect.x=this._scrollX,this.sourceRect.y=this._scrollY},n.prototype.render=function(t){if(this.sprite){e.prototype.render.call(this,t);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))}},n}(t.TiledSpriteRenderer);t.ScrollingSpriteRenderer=e}(es||(es={})),function(t){var e=function(){return function(e,n,i){void 0===n&&(n=new t.Rectangle(0,0,e.textureWidth,e.textureHeight)),void 0===i&&(i=n.getHalfSize()),this.uvs=new t.Rectangle,this.texture2D=e,this.sourceRect=n,this.center=new t.Vector2(.5*n.width,.5*n.height),this.origin=i;var r=1/e.textureWidth,o=1/e.textureHeight;this.uvs.x=n.x*r,this.uvs.y=n.y*o,this.uvs.width=n.width*r,this.uvs.height=n.height*o}}();t.Sprite=e}(es||(es={})),function(t){var e=function(){return function(t,e){this.sprites=t,this.frameRate=e}}();t.SpriteAnimation=e}(es||(es={})),function(t){var e,n;!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"}(e=t.LoopMode||(t.LoopMode={})),function(t){t[t.none=0]="none",t[t.running=1]="running",t[t.paused=2]="paused",t[t.completed=3]="completed"}(n=t.State||(t.State={}));var i=function(i){function r(t){var e=i.call(this,t)||this;return e.speed=1,e.animationState=n.none,e._animations=new Map,e._elapsedTime=0,e}return __extends(r,i),Object.defineProperty(r.prototype,"isRunning",{get:function(){return this.animationState==n.running},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"animations",{get:function(){return this._animations},enumerable:!0,configurable:!0}),r.prototype.update=function(){if(this.animationState==n.running&&this.currentAnimation){var i=this.currentAnimation,r=1/(i.frameRate*this.speed),o=r*i.sprites.length;this._elapsedTime+=t.Time.deltaTime;var s=Math.abs(this._elapsedTime);if(this._loopMode==e.once&&s>o||this._loopMode==e.pingPongOnce&&s>2*o)return this.animationState=n.completed,this._elapsedTime=0,this.currentFrame=0,void(this.sprite=i.sprites[this.currentFrame]);var a=Math.floor(s/r),c=i.sprites.length;if(c>2&&(this._loopMode==e.pingPong||this._loopMode==e.pingPongOnce)){var h=c-1;this.currentFrame=h-Math.abs(h-a%(2*h))}else this.currentFrame=a%c;this.sprite=i.sprites[this.currentFrame]}},r.prototype.addAnimation=function(t,e){return!this.sprite&&e.sprites.length>0&&this.setSprite(e.sprites[0]),this._animations[t]=e,this},r.prototype.play=function(t,i){void 0===i&&(i=null),this.currentAnimation=this._animations[t],this.currentAnimationName=t,this.currentFrame=0,this.animationState=n.running,this.sprite=this.currentAnimation.sprites[0],this._elapsedTime=0,this._loopMode=i||e.loop},r.prototype.isAnimationActive=function(t){return this.currentAnimation&&this.currentAnimationName==t},r.prototype.pause=function(){this.animationState=n.paused},r.prototype.unPause=function(){this.animationState=n.running},r.prototype.stop=function(){this.currentAnimation=null,this.currentAnimationName=null,this.currentFrame=0,this.animationState=n.none},r}(t.SpriteRenderer);t.SpriteAnimator=i}(es||(es={})),function(t){var e=function(e){function n(){return null!==e&&e.apply(this,arguments)||this}return __extends(n,e),n.prototype.onAddedToEntity=function(){this._triggerHelper=new t.ColliderTriggerHelper(this.entity)},n.prototype.calculateMovement=function(e,n){if(!this.entity.getComponent(t.Collider)||!this._triggerHelper)return!1;for(var i=this.entity.getComponents(t.Collider),r=0;r>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 n=0;n0){n=0;for(var i=this._componentsToAdd.length;n0){var e=this._entitiesToRemove;this._entitiesToRemove=this._tempEntityList,this._tempEntityList=e,this._tempEntityList.forEach(function(e){t.removeFromTagList(e),t._entities.remove(e),e.onRemovedFromScene(),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.addToTagList(e),t.scene.entityProcessors.onEntityAdded(e))}),this._tempEntityList.forEach(function(t){return t.onAddedToScene()}),this._tempEntityList.length=0,this._isEntityListUnsorted=!0}this._isEntityListUnsorted&&(this._entities.sort(),this._isEntityListUnsorted=!1),this._unsortedTags.length>0&&(this._unsortedTags.forEach(function(e){t._entityDict.get(e).sort()}),this._unsortedTags.length=0)},e.prototype.findEntity=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))},e.prototype.all=function(){for(var e=this,n=[],i=0;i0){for(var t=0,n=this._unsortedRenderLayers.length;t=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}();!function(t){var e=function(){function e(){}return e.convertImageToCanvas=function(e,n){this.sharedCanvas||(this.sharedCanvas=egret.sys.createCanvas(),this.sharedContext=this.sharedCanvas.getContext("2d"));var i=e.$getTextureWidth(),r=e.$getTextureHeight();n||((n=egret.$TempRectangle).x=0,n.y=0,n.width=i,n.height=r),n.x=Math.min(n.x,i-1),n.y=Math.min(n.y,r-1),n.width=Math.min(n.width,i-n.x),n.height=Math.min(n.height,r-n.y);var o=Math.floor(n.width),s=Math.floor(n.height),a=this.sharedCanvas;if(a.style.width=o+"px",a.style.height=s+"px",this.sharedCanvas.width=o,this.sharedCanvas.height=s,"webgl"==egret.Capabilities.renderMode){var c=void 0;e.$renderBuffer?c=e:(egret.sys.systemRenderer.renderClear&&egret.sys.systemRenderer.renderClear(),(c=new egret.RenderTexture).drawToTexture(new egret.Bitmap(e)));for(var h=c.$renderBuffer.getPixels(n.x,n.y,o,s),u=0,l=0,p=0;p=0?"png":"jpg"});return wx.getFileSystemManager().saveFile({tempFilePath:o,filePath:wx.env.USER_DATA_PATH+"/"+n,success:function(t){}}),o},e.getPixel32=function(t,e,n){return egret.$warn(1041,"getPixel32","getPixels"),t.getPixels(e,n)},e.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)}},e}();t.TextureUtils=e}(es||(es={})),function(t){var e=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}();t.Time=e}(es||(es={}));var 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":i.indexOf("android")>-1&&(this.os="Android");var r=n.language;r=r.indexOf("zh")>-1?"zh-CN":"en-US",this.language=r}},e}(egret.Capabilities);t.GraphicsCapabilities=e}(es||(es={})),function(t){var e=function(){function e(){this.setup(),this.graphicsCapabilities=new t.GraphicsCapabilities,this.graphicsCapabilities.initialize(this)}return Object.defineProperty(e.prototype,"viewport",{get:function(){return this._viewport},enumerable:!0,configurable:!0}),e.prototype.setup=function(){this._viewport=new t.Viewport(0,0,t.Core._instance.stage.stageWidth,t.Core._instance.stage.stageHeight)},e}();t.GraphicsDevice=e}(es||(es={})),function(t){var e=function(){function e(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(e.prototype,"height",{get:function(){return this._height},set:function(t){this._height=t},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"width",{get:function(){return this._width},set:function(t){this._width=t},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"aspectRatio",{get:function(){return 0!=this._height&&0!=this._width?this._width/this._height:0},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"bounds",{get:function(){return new t.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}),e}();t.Viewport=e}(es||(es={})),function(t){var e=function(e){function n(){return e.call(this,t.PostProcessor.default_vert,n.blur_frag,{screenWidth:t.Core.graphicsDevice.viewport.width,screenHeight:t.Core.graphicsDevice.viewport.height})||this}return __extends(n,e),n.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}",n}(egret.CustomFilter);t.GaussianBlurEffect=e}(es||(es={})),function(t){var e=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);t.PolygonLightEffect=e}(es||(es={})),function(t){var e=function(){function e(t){void 0===t&&(t=null),this.enabled=!0,this.effect=t}return e.prototype.onAddedToScene=function(e){this.scene=e,this.shape=new egret.Shape,this.shape.graphics.beginFill(16777215,1),this.shape.graphics.drawRect(0,0,t.Core.graphicsDevice.viewport.width,t.Core.graphicsDevice.viewport.height),this.shape.graphics.endFill(),e.addChild(this.shape)},e.prototype.process=function(){this.drawFullscreenQuad()},e.prototype.onSceneBackBufferSizeChanged=function(t,e){},e.prototype.drawFullscreenQuad=function(){this.scene.filters=[this.effect]},e.prototype.unload=function(){this.effect&&(this.effect=null),this.scene.removeChild(this.shape),this.scene=null},e.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}",e}();t.PostProcessor=e}(es||(es={})),function(t){var e=function(e){function n(){return null!==e&&e.apply(this,arguments)||this}return __extends(n,e),n.prototype.onAddedToScene=function(n){e.prototype.onAddedToScene.call(this,n),this.effect=new t.GaussianBlurEffect},n}(t.PostProcessor);t.GaussianBlurPostProcessor=e}(es||(es={})),function(t){var e=function(){function t(t,e){void 0===e&&(e=null),this.renderOrder=0,this.camera=e,this.renderOrder=t}return t.prototype.onAddedToScene=function(t){},t.prototype.unload=function(){},t.prototype.beginRender=function(t){},t.prototype.renderAfterStateCheck=function(t,e){t.render(e)},t.prototype.onSceneBackBufferSizeChanged=function(t,e){},t.prototype.compareTo=function(t){return this.renderOrder-t.renderOrder},t}();t.Renderer=e}(es||(es={})),function(t){var e=function(t){function e(){return t.call(this,0,null)||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},e.pointOnCirlce=function(n,i,r){var o=e.toRadians(r);return new t.Vector2(Math.cos(o)*o+n.x,Math.sin(o)*o+n.y)},e.isEven=function(t){return t%2==0},e.clamp01=function(t){return t<0?0:t>1?1:t},e.angleBetweenVectors=function(t,e){return Math.atan2(e.y-t.y,e.x-t.x)},e.Epsilon=1e-5,e.Rad2Deg=57.29578,e.Deg2Rad=.0174532924,e}();t.MathHelper=e}(es||(es={})),function(t){t.matrixPool=[];var e=function(e){function n(){return null!==e&&e.apply(this,arguments)||this}return __extends(n,e),Object.defineProperty(n.prototype,"m11",{get:function(){return this.a},set:function(t){this.a=t},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"m12",{get:function(){return this.b},set:function(t){this.b=t},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"m21",{get:function(){return this.c},set:function(t){this.c=t},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"m22",{get:function(){return this.d},set:function(t){this.d=t},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"m31",{get:function(){return this.tx},set:function(t){this.tx=t},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"m32",{get:function(){return this.ty},set:function(t){this.ty=t},enumerable:!0,configurable:!0}),n.create=function(){var e=t.matrixPool.pop();return e||(e=new n),e},n.prototype.identity=function(){return this.a=this.d=1,this.b=this.c=this.tx=this.ty=0,this},n.prototype.translate=function(t,e){return this.tx+=t,this.ty+=e,this},n.prototype.scale=function(t,e){return 1!==t&&(this.a*=t,this.c*=t,this.tx*=t),1!==e&&(this.b*=e,this.d*=e,this.ty*=e),this},n.prototype.rotate=function(t){if(0!==(t=+t)){t/=DEG_TO_RAD;var e=Math.cos(t),n=Math.sin(t),i=this.a,r=this.b,o=this.c,s=this.d,a=this.tx,c=this.ty;this.a=i*e-r*n,this.b=i*n+r*e,this.c=o*e-s*n,this.d=o*n+s*e,this.tx=a*e-c*n,this.ty=a*n+c*e}return this},n.prototype.invert=function(){return this.$invertInto(this),this},n.prototype.add=function(t){return this.m11+=t.m11,this.m12+=t.m12,this.m21+=t.m21,this.m22+=t.m22,this.m31+=t.m31,this.m32+=t.m32,this},n.prototype.substract=function(t){return this.m11-=t.m11,this.m12-=t.m12,this.m21-=t.m21,this.m22-=t.m22,this.m31-=t.m31,this.m32-=t.m32,this},n.prototype.divide=function(t){return this.m11/=t.m11,this.m12/=t.m12,this.m21/=t.m21,this.m22/=t.m22,this.m31/=t.m31,this.m32/=t.m32,this},n.prototype.multiply=function(t){var e=this.m11*t.m11+this.m12*t.m21,n=this.m11*t.m12+this.m12*t.m22,i=this.m21*t.m11+this.m22*t.m21,r=this.m21*t.m12+this.m22*t.m22,o=this.m31*t.m11+this.m32*t.m21+t.m31,s=this.m31*t.m12+this.m32*t.m22+t.m32;return this.m11=e,this.m12=n,this.m21=i,this.m22=r,this.m31=o,this.m32=s,this},n.prototype.determinant=function(){return this.m11*this.m22-this.m12*this.m21},n.prototype.release=function(e){e&&t.matrixPool.push(e)},n}(egret.Matrix);t.Matrix2D=e}(es||(es={})),function(t){var e=function(e){function n(){return null!==e&&e.apply(this,arguments)||this}return __extends(n,e),Object.defineProperty(n.prototype,"max",{get:function(){return new t.Vector2(this.right,this.bottom)},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"center",{get:function(){return new t.Vector2(this.x+this.width/2,this.y+this.height/2)},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"location",{get:function(){return new t.Vector2(this.x,this.y)},set:function(t){this.x=t.x,this.y=t.y},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"size",{get:function(){return new t.Vector2(this.width,this.height)},set:function(t){this.width=t.x,this.height=t.y},enumerable:!0,configurable:!0}),n.prototype.intersects=function(t){return t.lefti&&(i=s.x),s.yr&&(r=s.y)}return this.fromMinMax(e,n,i,r)},n}(egret.Rectangle);t.Rectangle=e}(es||(es={})),function(t){var e=function(){return function(t,e,n){this.x=t,this.y=e,this.z=n}}();t.Vector3=e}(es||(es={})),function(t){var e=function(){function e(t){this._activeTriggerIntersections=[],this._previousTriggerIntersections=[],this._tempTriggerList=[],this._entity=t}return e.prototype.update=function(){for(var e=this._entity.getComponents(t.Collider),n=0;n1)return!1;var u=(c.x*o.y-c.y*o.x)/a;return!(u<0||u>1)},n.lineToLineIntersection=function(e,n,i,r){var o=new t.Vector2(0,0),s=t.Vector2.subtract(n,e),a=t.Vector2.subtract(r,i),c=s.x*a.y-s.y*a.x;if(0==c)return o;var h=t.Vector2.subtract(i,e),u=(h.x*a.y-h.y*a.x)/c;if(u<0||u>1)return o;var l=(h.x*s.y-h.y*s.x)/c;return l<0||l>1?o:o=t.Vector2.add(e,new t.Vector2(u*s.x,u*s.y))},n.closestPointOnLine=function(e,n,i){var r=t.Vector2.subtract(n,e),o=t.Vector2.subtract(i,e),s=t.Vector2.dot(o,r)/t.Vector2.dot(r,r);return s=t.MathHelper.clamp(s,0,1),t.Vector2.add(e,new t.Vector2(r.x*s,r.y*s))},n.isCircleToCircle=function(e,n,i,r){return t.Vector2.distanceSquared(e,i)<(n+r)*(n+r)},n.isCircleToLine=function(e,n,i,r){return t.Vector2.distanceSquared(e,this.closestPointOnLine(i,r,e))=t&&r.y>=e&&r.x=t+i&&(s|=e.right),o.y=n+r&&(s|=e.bottom),s},n}();t.Collisions=n}(es||(es={})),function(t){var e=function(){function e(){}return e.reset=function(){this._spatialHash=new t.SpatialHash(this.spatialHashCellSize)},e.clear=function(){this._spatialHash.clear()},e.overlapCircleAll=function(t,e,n,i){if(void 0===i&&(i=-1),0!=n.length)return this._spatialHash.overlapCircle(t,e,n,i);console.error("An empty results array was passed in. No results will ever be returned.")},e.boxcastBroadphase=function(t,e){return void 0===e&&(e=this.allLayers),this._spatialHash.aabbBroadphase(t,null,e)},e.boxcastBroadphaseExcludingSelf=function(t,e,n){return void 0===n&&(n=this.allLayers),this._spatialHash.aabbBroadphase(e,t,n)},e.addCollider=function(t){e._spatialHash.register(t)},e.removeCollider=function(t){e._spatialHash.remove(t)},e.updateCollider=function(t){this._spatialHash.remove(t),this._spatialHash.register(t)},e.debugDraw=function(t){this._spatialHash.debugDraw(t,2)},e.spatialHashCellSize=100,e.allLayers=-1,e}();t.Physics=e}(es||(es={})),function(t){var e=function(){function t(){}return t.prototype.clone=function(){return ObjectUtils.clone(this)},t}();t.Shape=e}(es||(es={})),function(t){var e=function(e){function n(t,n){var i=e.call(this)||this;return i._areEdgeNormalsDirty=!0,i.isUnrotated=!0,i.setPoints(t),i.isBox=n,i}return __extends(n,e),Object.defineProperty(n.prototype,"edgeNormals",{get:function(){return this._areEdgeNormalsDirty&&this.buildEdgeNormals(),this._edgeNormals},enumerable:!0,configurable:!0}),n.prototype.setPoints=function(t){this.points=t,this.recalculateCenterAndEdgeNormals(),this._originalPoints=[];for(var e=0;e=this.points.length?this.points[0]:this.points[i+1];var o=t.Vector2Ext.perpendicular(r,e);o=t.Vector2.normalize(o),this._edgeNormals[i]=o}},n.buildSymmetricalPolygon=function(e,n){for(var i=new Array(e),r=0;re.y!=this.points[r].y>e.y&&e.x<(this.points[r].x-this.points[i].x)*(e.y-this.points[i].y)/(this.points[r].y-this.points[i].y)+this.points[i].x&&(n=!n);return n},n.prototype.pointCollidesWithShape=function(e,n){return t.ShapeCollisions.pointToPoly(e,this,n)},n}(t.Shape);t.Polygon=e}(es||(es={})),function(t){var e=function(e){function n(t,i){var r=e.call(this,n.buildBox(t,i),!0)||this;return r.width=t,r.height=i,r}return __extends(n,e),n.buildBox=function(e,n){var i=e/2,r=n/2,o=new Array(4);return o[0]=new t.Vector2(-i,-r),o[1]=new t.Vector2(i,-r),o[2]=new t.Vector2(i,r),o[3]=new t.Vector2(-i,r),o},n.prototype.updateBox=function(e,n){this.width=e,this.height=n;var i=e/2,r=n/2;this.points[0]=new t.Vector2(-i,-r),this.points[1]=new t.Vector2(i,-r),this.points[2]=new t.Vector2(i,r),this.points[3]=new t.Vector2(-i,r);for(var o=0;o0&&(o=!1),!o)return!1;(m=Math.abs(m))r&&(r=o);return{min:i,max:r}},e.circleToPolygon=function(e,n,i){var r,o=t.Vector2.subtract(e.position,n.position),s=t.Polygon.getClosestPointOnPolygonToPoint(n.points,o,0,i.normal),a=n.containsPoint(e.position);if(0>e.radius*e.radius&&!a)return!1;a?r=t.Vector2.multiply(i.normal,new t.Vector2(Math.sqrt(0)-e.radius)):r=t.Vector2.multiply(i.normal,new t.Vector2(e.radius));return i.minimumTranslationVector=r,i.point=t.Vector2.add(s,n.position),!0},e.circleToBox=function(e,n,i){var r=n.bounds.getClosestPointOnRectangleBorderToPoint(e.position,i.normal);if(n.containsPoint(e.position)){i.point=r;var o=t.Vector2.add(r,t.Vector2.multiply(i.normal,new t.Vector2(e.radius)));return i.minimumTranslationVector=t.Vector2.subtract(e.position,o),!0}var s=t.Vector2.distanceSquared(r,e.position);if(0==s)i.minimumTranslationVector=t.Vector2.multiply(i.normal,new t.Vector2(e.radius));else if(s<=e.radius*e.radius){i.normal=t.Vector2.subtract(e.position,r);var a=i.normal.length()-e.radius;return i.point=r,i.normal=t.Vector2Ext.normalize(i.normal),i.minimumTranslationVector=t.Vector2.multiply(new t.Vector2(a),i.normal),!0}return!1},e.pointToCircle=function(e,n,i){var r=t.Vector2.distanceSquared(e,n.position),o=1+n.radius;if(r0&&this.debugDrawCellDetails(n,i,r.length,t,e)}},e.prototype.debugDrawCellDetails=function(t,e,n,i,r){void 0===i&&(i=.5),void 0===r&&(r=1)},e.prototype.aabbBroadphase=function(e,n,i){this._tempHashSet.length=0;for(var r=this.cellCoords(e.x,e.y),o=this.cellCoords(e.right,e.bottom),s=r.x;s<=o.x;s++)for(var a=r.y;a<=o.y;a++){var c=this.cellAtPosition(s,a);if(c)for(var h=0;hn;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}(),Base64Utils=function(){function t(){}return t._utf8_encode=function(t){t=t.replace(/\r\n/g,"\n");for(var e="",n=0;n127&&i<2048?(e+=String.fromCharCode(i>>6|192),e+=String.fromCharCode(63&i|128)):(e+=String.fromCharCode(i>>12|224),e+=String.fromCharCode(i>>6&63|128),e+=String.fromCharCode(63&i|128))}return e},t.decode=function(t,e){void 0===e&&(e=!0);var n,i,r,o,s,a,c="",h=0;for(t=(t=this.getConfKey(t)).replace(/[^A-Za-z0-9\+\/\=]/g,"");h>4,i=(15&o)<<4|(s=this._keyAll.indexOf(t.charAt(h++)))>>2,r=(3&s)<<6|(a=this._keyAll.indexOf(t.charAt(h++))),c+=String.fromCharCode(n),64!=s&&(0==i?e&&(c+=String.fromCharCode(i)):c+=String.fromCharCode(i)),64!=a&&(0==r?e&&(c+=String.fromCharCode(r)):c+=String.fromCharCode(r));return c=this._utf8_decode(c)},t._utf8_decode=function(t){for(var e="",n=0,i=0,r=0,o=0;n191&&i<224?(r=t.charCodeAt(n+1),e+=String.fromCharCode((31&i)<<6|63&r),n+=2):(r=t.charCodeAt(n+1),o=t.charCodeAt(n+2),e+=String.fromCharCode((15&i)<<12|(63&r)<<6|63&o),n+=3);return e},t.getConfKey=function(t){return t.slice(1,t.length)},t._keyNum="0123456789+/",t._keyStr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",t._keyAll=t._keyNum+t._keyStr,t.encode=function(t){var e,n,i,r,o,s,a,c="",h=0;for(t=this._utf8_encode(t);h>2,o=(3&e)<<4|(n=t.charCodeAt(h++))>>4,s=(15&n)<<2|(i=t.charCodeAt(h++))>>6,a=63&i,isNaN(n)?s=a=64:isNaN(i)&&(a=64),c=c+this._keyAll.charAt(r)+this._keyAll.charAt(o)+this._keyAll.charAt(s)+this._keyAll.charAt(a);return this._keyStr.charAt(Math.floor(Math.random()*this._keyStr.length))+c},t}();!function(t){var e=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}();t.ContentManager=e}(es||(es={})),function(t){var e=function(){function e(){}return e.drawLine=function(e,n,i,r,o){void 0===o&&(o=1),this.drawLineAngle(e,n,t.MathHelper.angleBetweenVectors(n,i),t.Vector2.distance(n,i),r,o)},e.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},e.drawHollowRect=function(t,e,n,i){void 0===i&&(i=1),this.drawHollowRectR(t,e.x,e.y,e.width,e.height,n,i)},e.drawHollowRectR=function(e,n,i,r,o,s,a){void 0===a&&(a=1);var c=new t.Vector2(n,i).round(),h=new t.Vector2(n+r,i).round(),u=new t.Vector2(n+r,i+o).round(),l=new t.Vector2(n,i+o).round();this.drawLine(e,c,h,s,a),this.drawLine(e,h,u,s,a),this.drawLine(e,u,l,s,a),this.drawLine(e,l,c,s,a)},e.drawPixel=function(e,n,i,r){void 0===r&&(r=1);var o=new t.Rectangle(n.x,n.y,r,r);1!=r&&(o.x-=.5*r,o.y-=.5*r),e.graphics.beginFill(i),e.graphics.drawRect(o.x,o.y,o.width,o.height),e.graphics.endFill()},e.getColorMatrix=function(t){var e=[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0];return e[0]=Math.floor(t/256/256)/255,e[6]=Math.floor(t/256%256)/255,e[12]=t%256/255,new egret.ColorMatrixFilter(e)},e}();t.DrawUtils=e}(es||(es={})),function(t){var e=function(){return function(t,e){this.func=t,this.context=e}}();t.FuncPack=e;var n=function(){function t(){this._messageTable=new Map}return t.prototype.addObserver=function(t,n,i){var r=this._messageTable.get(t);r||(r=[],this._messageTable.set(t,r)),-1!=r.findIndex(function(t){return t.func==n})&&console.warn("您试图添加相同的观察者两次"),r.push(new e(n,i))},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}();t.Emitter=n}(es||(es={})),function(t){var e=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}();t.GlobalManager=e}(es||(es={})),function(t){var e=function(){function e(){this.x=0,this.y=0,this.touchPoint=-1,this.touchDown=!1}return Object.defineProperty(e.prototype,"position",{get:function(){return new t.Vector2(this.x,this.y)},enumerable:!0,configurable:!0}),e.prototype.reset=function(){this.x=0,this.y=0,this.touchDown=!1,this.touchPoint=-1},e}();t.TouchState=e;var n=function(){function n(){}return Object.defineProperty(n,"touchPosition",{get:function(){return this._gameTouchs[0]?this._gameTouchs[0].position:t.Vector2.zero},enumerable:!0,configurable:!0}),Object.defineProperty(n,"maxSupportedTouch",{get:function(){return t.Core._instance.stage.maxTouches},set:function(e){t.Core._instance.stage.maxTouches=e,this.initTouchCache()},enumerable:!0,configurable:!0}),Object.defineProperty(n,"resolutionScale",{get:function(){return this._resolutionScale},enumerable:!0,configurable:!0}),Object.defineProperty(n,"totalTouchCount",{get:function(){return this._totalTouchCount},enumerable:!0,configurable:!0}),Object.defineProperty(n,"gameTouchs",{get:function(){return this._gameTouchs},enumerable:!0,configurable:!0}),Object.defineProperty(n,"touchPositionDelta",{get:function(){var e=t.Vector2.subtract(this.touchPosition,this._previousTouchState.position);return e.length()>0&&this.setpreviousTouchState(this._gameTouchs[0]),e},enumerable:!0,configurable:!0}),n.initialize=function(){this._init||(this._init=!0,t.Core._instance.stage.addEventListener(egret.TouchEvent.TOUCH_BEGIN,this.touchBegin,this),t.Core._instance.stage.addEventListener(egret.TouchEvent.TOUCH_MOVE,this.touchMove,this),t.Core._instance.stage.addEventListener(egret.TouchEvent.TOUCH_END,this.touchEnd,this),t.Core._instance.stage.addEventListener(egret.TouchEvent.TOUCH_CANCEL,this.touchEnd,this),t.Core._instance.stage.addEventListener(egret.TouchEvent.TOUCH_RELEASE_OUTSIDE,this.touchEnd,this),this.initTouchCache())},n.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}();t.ListPool=e}(es||(es={}));var 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}();!function(t){var e=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}();t.Pair=e}(es||(es={}));var 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&&o<500;){o++;var a=!0,c=n[this._triPrev[s]],h=n[s],u=n[this._triNext[s]];if(t.Vector2Ext.isTriangleCCW(c,h,u)){var l=this._triNext[this._triNext[s]];do{if(e.testPointTriangle(n[l],c,h,u)){a=!1;break}l=this._triNext[l]}while(l!=this._triPrev[s])}else a=!1;a?(this.triangleIndices.push(this._triPrev[s]),this.triangleIndices.push(s),this.triangleIndices.push(this._triNext[s]),this._triNext[this._triPrev[s]]=this._triNext[s],this._triPrev[this._triNext[s]]=this._triPrev[s],r--,s=this._triPrev[s]):s=this._triNext[s]}this.triangleIndices.push(this._triPrev[s]),this.triangleIndices.push(s),this.triangleIndices.push(this._triNext[s]),i||this.triangleIndices.reverse()},e.prototype.initialize=function(t){this.triangleIndices.length=0,this._triNext.lengtht.MathHelper.Epsilon?e=t.Vector2.divide(e,new t.Vector2(n)):e.x=e.y=0,e},e.transformA=function(t,e,n,i,r,o){for(var s=0;sthis.safeArea.right&&(s.x=this.safeArea.right-s.width),s.topthis.safeArea.bottom&&(s.y=this.safeArea.bottom-s.height),s},n}();t.Layout=n,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"}(e=t.Alignment||(t.Alignment={}))}(es||(es={})),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={})),function(t){var e=function(){function e(){this._frameKey="frame",this._logKey="log",this.markers=[],this.stopwacth=new stopwatch.Stopwatch,this._markerNameToIdMap=new Map,this.showLog=!1,this._logs=new Array(2);for(var e=0;e=e.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}t.stopwacth.reset(),t.stopwacth.start()}})},e.prototype.beginMark=function(t,n,i){var r=this;void 0===i&&(i=0),new LockUtils(this._frameKey).lock().then(function(){if(i<0||i>=e.maxBars)throw new Error("barIndex argument out of range");var o=r._curLog.bars[i];if(o.markCount>=e.maxSamples)throw new Error("exceeded sample count. either set larger number to timeruler.maxsaple or lower sample count");if(o.nestCount>=e.maxNestCall)throw new Error("exceeded nest count. either set larger number to timeruler.maxnestcall or lower nest calls");var s=r._markerNameToIdMap.get(t);isNaN(s)&&(s=r.markers.length,r._markerNameToIdMap.set(t,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})},e.prototype.endMark=function(t,n){var i=this;void 0===n&&(n=0),new LockUtils(this._frameKey).lock().then(function(){if(n<0||n>=e.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(t);if(isNaN(o))throw new Error("Marker "+t+" 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()})},e.prototype.getAverageTime=function(t,n){if(t<0||t>=e.maxBars)throw new Error("barIndex argument out of range");var i=0,r=this._markerNameToIdMap.get(n);return r&&(i=this.markers[r].logs[t].avg),i},e.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+=e.barHeight+2*e.barPadding,r=Math.max(r,t.markers[t.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)>e.autoAdjustDelay&&(this.sampleFrames=Math.min(e.maxSampleFrames,this.sampleFrames),this.sampleFrames=Math.max(this.targetSampleFrames,r/(1/60*1e3)+1),this._frameAdjust=0);t.y,e.barHeight}},e.maxBars=8,e.maxSamples=256,e.maxNestCall=32,e.barHeight=8,e.maxSampleFrames=4,e.logSnapDuration=120,e.barPadding=2,e.autoAdjustDelay=30,e}();t.TimeRuler=e;var n=function(){return function(){this.bars=new Array(e.maxBars),this.bars.fill(new i,0,e.maxBars)}}();t.FrameLog=n;var i=function(){return function(){this.markers=new Array(e.maxSamples),this.markCount=0,this.markerNests=new Array(e.maxNestCall),this.nestCount=0,this.markers.fill(new r,0,e.maxSamples),this.markerNests.fill(0,0,e.maxNestCall)}}();t.MarkerCollection=i;var r=function(){return function(){this.markerId=0,this.beginTime=0,this.endTime=0,this.color=0}}();t.Marker=r;var o=function(){return function(t){this.logs=new Array(e.maxBars),this.name=t,this.logs.fill(new s,0,e.maxBars)}}();t.MarkerInfo=o;var s=function(){return function(){this.snapMin=0,this.snapMax=0,this.snapAvg=0,this.min=0,this.max=0,this.avg=0,this.samples=0,this.color=0,this.initialized=!1}}();t.MarkerLog=s}(es||(es={})); \ No newline at end of file +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 transform,__awaiter=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,o){function s(t){try{c(i.next(t))}catch(t){o(t)}}function a(t){try{c(i.throw(t))}catch(t){o(t)}}function c(t){t.done?r(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,r,o,s={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return o={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function a(o){return function(a){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,i&&(r=2&o[0]?i.return:o[0]?i.throw||((r=i.return)&&r.call(i),0):i.next)&&!(r=r.call(i,o[1])).done)return r;switch(i=0,r&&(o=[2&o[0],r.value]),o[0]){case 0:case 1:r=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,i=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(r=(r=s.trys).length>0&&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"===u())break}return s?this.recontructPath(a,i,r):null},e.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},e.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},e.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},e}();t.AStarPathfinder=e;var n=function(t){function e(e){var n=t.call(this)||this;return n.data=e,n}return __extends(e,t),e}(t.PriorityQueueNode);t.AStarNode=n}(es||(es={})),function(t){var e=function(){function e(e,n){this.dirs=[new t.Vector2(1,0),new t.Vector2(0,-1),new t.Vector2(-1,0),new t.Vector2(0,1)],this.walls=[],this.weightedNodes=[],this.defaultWeight=1,this.weightedNodeWeight=5,this._neighbors=new Array(4),this._width=e,this._height=n}return e.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"===c())break}return o?t.AStarPathfinder.recontructPath(a,n,i):null},e.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},e}();t.BreadthFirstPathfinder=e}(es||(es={})),function(t){var e=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}();t.UnweightedGraph=e}(es||(es={})),function(t){var e=function(){function e(t,e){this.x=0,this.y=0,this.x=t||0,this.y=e||this.x}return Object.defineProperty(e,"zero",{get:function(){return e.zeroVector2},enumerable:!0,configurable:!0}),Object.defineProperty(e,"one",{get:function(){return e.unitVector2},enumerable:!0,configurable:!0}),Object.defineProperty(e,"unitX",{get:function(){return e.unitXVector},enumerable:!0,configurable:!0}),Object.defineProperty(e,"unitY",{get:function(){return e.unitYVector},enumerable:!0,configurable:!0}),e.add=function(t,n){var i=new e(0,0);return i.x=t.x+n.x,i.y=t.y+n.y,i},e.divide=function(t,n){var i=new e(0,0);return i.x=t.x/n.x,i.y=t.y/n.y,i},e.multiply=function(t,n){var i=new e(0,0);return i.x=t.x*n.x,i.y=t.y*n.y,i},e.subtract=function(t,n){var i=new e(0,0);return i.x=t.x-n.x,i.y=t.y-n.y,i},e.normalize=function(t){var e=1/Math.sqrt(t.x*t.x+t.y*t.y);return t.x*=e,t.y*=e,t},e.dot=function(t,e){return t.x*e.x+t.y*e.y},e.distanceSquared=function(t,e){var n=t.x-e.x,i=t.y-e.y;return n*n+i*i},e.clamp=function(n,i,r){return new e(t.MathHelper.clamp(n.x,i.x,r.x),t.MathHelper.clamp(n.y,i.y,r.y))},e.lerp=function(n,i,r){return new e(t.MathHelper.lerp(n.x,i.x,r),t.MathHelper.lerp(n.y,i.y,r))},e.transform=function(t,n){return new e(t.x*n.m11+t.y*n.m21+n.m31,t.x*n.m12+t.y*n.m22+n.m32)},e.distance=function(t,e){var n=t.x-e.x,i=t.y-e.y;return Math.sqrt(n*n+i*i)},e.negate=function(t){var n=new e;return n.x=-t.x,n.y=-t.y,n},e.prototype.add=function(t){return this.x+=t.x,this.y+=t.y,this},e.prototype.divide=function(t){return this.x/=t.x,this.y/=t.y,this},e.prototype.multiply=function(t){return this.x*=t.x,this.y*=t.y,this},e.prototype.subtract=function(t){return this.x-=t.x,this.y-=t.y,this},e.prototype.normalize=function(){var t=1/Math.sqrt(this.x*this.x+this.y*this.y);this.x*=t,this.y*=t},e.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},e.prototype.round=function(){return new e(Math.round(this.x),Math.round(this.y))},e.prototype.equals=function(t){return t.x==this.x&&t.y==this.y},e.unitYVector=new e(0,1),e.unitXVector=new e(1,0),e.unitVector2=new e(1,1),e.zeroVector2=new e(0,0),e}();t.Vector2=e}(es||(es={})),function(t){var e=function(){function e(t,n,i){void 0===i&&(i=!1),this.walls=[],this._neighbors=new Array(4),this._width=t,this._hegiht=n,this._dirs=i?e.COMPASS_DIRS:e.CARDINAL_DIRS}return e.prototype.isNodeInBounds=function(t){return 0<=t.x&&t.x0;){if("break"===u())break}return s?this.recontructPath(a,i,r):null},n.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},n.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},n.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},n}();t.WeightedPathfinder=n}(es||(es={})),function(t){var e=function(){function e(){}return e.drawHollowRect=function(e,n,i){void 0===i&&(i=0),this._debugDrawItems.push(new t.DebugDrawItem(e,n,i))},e.render=function(){if(this._debugDrawItems.length>0){var e=new egret.Shape;t.Core.scene&&t.Core.scene.addChild(e);for(var n=this._debugDrawItems.length-1;n>=0;n--){this._debugDrawItems[n].draw(e)&&this._debugDrawItems.removeAt(n)}}},e._debugDrawItems=[],e}();t.Debug=e}(es||(es={})),function(t){var e=function(){function t(){}return t.verletParticle=14431326,t.verletConstraintEdge=4406838,t}();t.DebugDefaults=e}(es||(es={})),function(t){var e;!function(t){t[t.line=0]="line",t[t.hollowRectangle=1]="hollowRectangle",t[t.pixel=2]="pixel",t[t.text=3]="text"}(e=t.DebugDrawType||(t.DebugDrawType={}));var n=function(){function n(t,n,i){this.rectangle=t,this.color=n,this.duration=i,this.drawType=e.hollowRectangle}return n.prototype.draw=function(n){switch(this.drawType){case e.line:t.DrawUtils.drawLine(n,this.start,this.end,this.color);break;case e.hollowRectangle:t.DrawUtils.drawHollowRect(n,this.rectangle,this.color);break;case e.pixel:t.DrawUtils.drawPixel(n,new t.Vector2(this.x,this.y),this.color,this.size);break;case e.text:}return this.duration-=t.Time.deltaTime,this.duration<0},n}();t.DebugDrawItem=n}(es||(es={})),function(t){var e=function(){function t(){this.updateInterval=1,this._enabled=!0,this._updateOrder=0}return Object.defineProperty(t.prototype,"transform",{get:function(){return this.entity.transform},enumerable:!0,configurable:!0}),Object.defineProperty(t.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(t.prototype,"updateOrder",{get:function(){return this._updateOrder},set:function(t){this.setUpdateOrder(t)},enumerable:!0,configurable:!0}),t.prototype.initialize=function(){},t.prototype.onAddedToEntity=function(){},t.prototype.onRemovedFromEntity=function(){},t.prototype.onEntityTransformChanged=function(t){},t.prototype.debugRender=function(){},t.prototype.onEnabled=function(){},t.prototype.onDisabled=function(){},t.prototype.update=function(){},t.prototype.setEnabled=function(t){return this._enabled!=t&&(this._enabled=t,this._enabled?this.onEnabled():this.onDisabled()),this},t.prototype.setUpdateOrder=function(t){return this._updateOrder!=t&&(this._updateOrder=t),this},t.prototype.clone=function(){var t=ObjectUtils.clone(this);return t.entity=null,t},t}();t.Component=e}(es||(es={})),function(t){var e=function(e){function n(){var i=e.call(this)||this;return i._globalManagers=[],n._instance=i,n.emitter=new t.Emitter,n.content=new t.ContentManager,i.addEventListener(egret.Event.ADDED_TO_STAGE,i.onAddToStage,i),i}return __extends(n,e),Object.defineProperty(n,"Instance",{get:function(){return this._instance},enumerable:!0,configurable:!0}),Object.defineProperty(n,"scene",{get:function(){return this._instance?this._instance._scene:null},set:function(t){t?null==this._instance._scene?(this._instance._scene=t,this._instance.addChild(t),this._instance._scene.begin(),n.Instance.onSceneChanged()):this._instance._nextScene=t:console.error("场景不能为空")},enumerable:!0,configurable:!0}),n.startSceneTransition=function(t){if(!this._instance._sceneTransition)return this._instance._sceneTransition=t,t;console.warn("在前一个场景完成之前,不能开始一个新的场景转换。")},n.registerGlobalManager=function(t){this._instance._globalManagers.push(t),t.enabled=!0},n.unregisterGlobalManager=function(t){this._instance._globalManagers.remove(t),t.enabled=!1},n.getGlobalManager=function(t){for(var e=0;e=0;e--)this._globalManagers[e].enabled&&this._globalManagers[e].update();return this._sceneTransition&&(!this._sceneTransition||this._sceneTransition.loadsNewScene&&!this._sceneTransition.isNewSceneLoaded)||this._scene.update(),this._nextScene?(this.removeChild(this._scene),this._scene.end(),this._scene=this._nextScene,this._nextScene=null,this.onSceneChanged(),this.addChild(this._scene),[4,this._scene.begin()]):[3,2];case 1:n.sent(),n.label=2;case 2:return[4,this.draw()];case 3:return n.sent(),[2]}})})},n.prototype.onAddToStage=function(){n.graphicsDevice=new t.GraphicsDevice,this.addEventListener(egret.Event.RESIZE,this.onGraphicsDeviceReset,this),this.addEventListener(egret.StageOrientationEvent.ORIENTATION_CHANGE,this.onOrientationChanged,this),this.addEventListener(egret.Event.ENTER_FRAME,this.update,this),t.Input.initialize(),this.initialize()},n}(egret.DisplayObjectContainer);t.Core=e}(es||(es={})),function(t){!function(t){t[t.GraphicsDeviceReset=0]="GraphicsDeviceReset",t[t.SceneChanged=1]="SceneChanged",t[t.OrientationChanged=2]="OrientationChanged"}(t.CoreEvents||(t.CoreEvents={}))}(es||(es={})),function(t){var e=function(){function e(n){this.updateInterval=1,this._tag=0,this._enabled=!0,this._updateOrder=0,this.components=new t.ComponentList(this),this.transform=new t.Transform(this),this.name=n,this.id=e._idGenerator++,this.componentBits=new t.BitSet}return Object.defineProperty(e.prototype,"isDestroyed",{get:function(){return this._isDestroyed},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"tag",{get:function(){return this._tag},set:function(t){this.setTag(t)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"enabled",{get:function(){return this._enabled},set:function(t){this.setEnabled(t)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"updateOrder",{get:function(){return this._updateOrder},set:function(t){this.setUpdateOrder(t)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"parent",{get:function(){return this.transform.parent},set:function(t){this.transform.setParent(t)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"childCount",{get:function(){return this.transform.childCount},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"position",{get:function(){return this.transform.position},set:function(t){this.transform.setPosition(t.x,t.y)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"localPosition",{get:function(){return this.transform.localPosition},set:function(t){this.transform.setLocalPosition(t)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"rotation",{get:function(){return this.transform.rotation},set:function(t){this.transform.setRotation(t)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"rotationDegrees",{get:function(){return this.transform.rotationDegrees},set:function(t){this.transform.setRotationDegrees(t)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"localRotation",{get:function(){return this.transform.localRotation},set:function(t){this.transform.setLocalRotation(t)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"localRotationDegrees",{get:function(){return this.transform.localRotationDegrees},set:function(t){this.transform.setLocalRotationDegrees(t)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"scale",{get:function(){return this.transform.scale},set:function(t){this.transform.setScale(t)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"localScale",{get:function(){return this.transform.localScale},set:function(t){this.transform.setLocalScale(t)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"worldInverseTransform",{get:function(){return this.transform.worldInverseTransform},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"localToWorldTransform",{get:function(){return this.transform.localToWorldTransform},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"worldToLocalTransform",{get:function(){return this.transform.worldToLocalTransform},enumerable:!0,configurable:!0}),e.prototype.onTransformChanged=function(t){this.components.onEntityTransformChanged(t)},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.setEnabled=function(t){return this._enabled!=t&&(this._enabled=t,this._enabled?this.components.onEntityEnabled():this.components.onEntityDisabled()),this},e.prototype.setUpdateOrder=function(t){if(this._updateOrder!=t)return this._updateOrder=t,this.scene&&(this.scene.entities.markEntityListUnsorted(),this.scene.entities.markTagUnsorted(this.tag)),this},e.prototype.destroy=function(){this._isDestroyed=!0,this.scene.entities.remove(this),this.transform.parent=null;for(var t=this.transform.childCount-1;t>=0;t--){this.transform.getChild(t).entity.destroy()}},e.prototype.detachFromScene=function(){this.scene.entities.remove(this),this.components.deregisterAllComponents();for(var t=0;te.x?-1:1,i=t.Vector2.normalize(t.Vector2.subtract(this.position,e));this.rotation=n*Math.acos(t.Vector2.dot(i,t.Vector2.unitY))},i.prototype.setLocalRotation=function(t){return this._localRotation=t,this._localDirty=this._positionDirty=this._localPositionDirty=this._localRotationDirty=this._localScaleDirty=!0,this.setDirty(e.rotationDirty),this},i.prototype.setLocalRotationDegrees=function(e){return this.setLocalRotation(t.MathHelper.toRadians(e))},i.prototype.setScale=function(e){return this._scale=e,this.parent?this.localScale=t.Vector2.divide(e,this.parent._scale):this.localScale=e,this},i.prototype.setLocalScale=function(t){return this._localScale=t,this._localDirty=this._positionDirty=this._localScaleDirty=!0,this.setDirty(e.scaleDirty),this},i.prototype.roundPosition=function(){this.position=this._position.round()},i.prototype.updateTransform=function(){this.hierarchyDirty!=e.clean&&(this.parent&&this.parent.updateTransform(),this._localDirty&&(this._localPositionDirty&&(this._translationMatrix=t.Matrix2D.create().translate(this._localPosition.x,this._localPosition.y),this._localPositionDirty=!1),this._localRotationDirty&&(this._rotationMatrix=t.Matrix2D.create().rotate(this._localRotation),this._localRotationDirty=!1),this._localScaleDirty&&(this._scaleMatrix=t.Matrix2D.create().scale(this._localScale.x,this._localScale.y),this._localScaleDirty=!1),this._localTransform=this._scaleMatrix.multiply(this._rotationMatrix),this._localTransform=this._localTransform.multiply(this._translationMatrix),this.parent||(this._worldTransform=this._localTransform,this._rotation=this._localRotation,this._scale=this._localScale,this._worldInverseDirty=!0),this._localDirty=!1),this.parent&&(this._worldTransform=this._localTransform.multiply(this.parent._worldTransform),this._rotation=this._localRotation+this.parent._rotation,this._scale=t.Vector2.multiply(this.parent._scale,this._localScale),this._worldInverseDirty=!0),this._worldToLocalDirty=!0,this._positionDirty=!0,this.hierarchyDirty=e.clean)},i.prototype.setDirty=function(e){if(0==(this.hierarchyDirty&e)){switch(this.hierarchyDirty|=e,e){case t.DirtyType.positionDirty:this.entity.onTransformChanged(transform.Component.position);break;case t.DirtyType.rotationDirty:this.entity.onTransformChanged(transform.Component.rotation);break;case t.DirtyType.scaleDirty:this.entity.onTransformChanged(transform.Component.scale)}this._children||(this._children=[]);for(var n=0;nt&&(this._zoom=t),this._maximumZoom=t,this;console.error("maximumZoom must be greater than zero")},r.prototype.onEntityTransformChanged=function(t){this._areMatrixedDirty=!0},r.prototype.zoomIn=function(t){this.zoom+=t},r.prototype.zoomOut=function(t){this.zoom-=t},r.prototype.worldToScreenPoint=function(e){return this.updateMatrixes(),e=t.Vector2.transform(e,this._transformMatrix)},r.prototype.screenToWorldPoint=function(e){return this.updateMatrixes(),e=t.Vector2.transform(e,this._inverseTransformMatrix)},r.prototype.mouseToWorldPoint=function(){return this.screenToWorldPoint(t.Input.touchPosition)},r.prototype.onAddedToEntity=function(){this.follow(this._targetEntity,this._cameraStyle)},r.prototype.update=function(){var e=t.Vector2.multiply(new t.Vector2(this.bounds.width,this.bounds.height),new t.Vector2(.5));this._worldSpaceDeadZone.x=this.position.x-e.x*t.Core.scene.scaleX+this.deadzone.x+this.focusOffset.x,this._worldSpaceDeadZone.y=this.position.y-e.y*t.Core.scene.scaleY+this.deadzone.y+this.focusOffset.y,this._worldSpaceDeadZone.width=this.deadzone.width,this._worldSpaceDeadZone.height=this.deadzone.height,this._targetEntity&&this.updateFollow(),this.position=t.Vector2.lerp(this.position,t.Vector2.add(this.position,this._desiredPositionDelta),this.followLerp),this.entity.transform.roundPosition(),this.mapLockEnabled&&(this.position=this.clampToMapSize(this.position),this.entity.transform.roundPosition())},r.prototype.clampToMapSize=function(e){var n=t.Vector2.multiply(new t.Vector2(this.bounds.width,this.bounds.height),new t.Vector2(.5)),i=new t.Vector2(this.mapSize.x-n.x,this.mapSize.y-n.y);return t.Vector2.clamp(e,n,i)},r.prototype.updateFollow=function(){if(this._desiredPositionDelta.x=this._desiredPositionDelta.y=0,this._cameraStyle==e.lockOn){var n=this._targetEntity.transform.position.x,i=this._targetEntity.transform.position.y;this._worldSpaceDeadZone.x>n?this._desiredPositionDelta.x=n-this._worldSpaceDeadZone.x:this._worldSpaceDeadZone.xi&&(this._desiredPositionDelta.y=i-this._worldSpaceDeadZone.y)}else{if(!this._targetCollider&&(this._targetCollider=this._targetEntity.getComponent(t.Collider),!this._targetCollider))return;var r=this._targetEntity.getComponent(t.Collider).bounds;this._worldSpaceDeadZone.containsRect(r)||(this._worldSpaceDeadZone.left>r.left?this._desiredPositionDelta.x=r.left-this._worldSpaceDeadZone.left:this._worldSpaceDeadZone.rightr.top&&(this._desiredPositionDelta.y=r.top-this._worldSpaceDeadZone.top))}},r.prototype.follow=function(n,i){switch(void 0===i&&(i=e.cameraWindow),this._targetEntity=n,this._cameraStyle=i,this._cameraStyle){case e.cameraWindow:var r=this.bounds.width/6,o=this.bounds.height/3;this.deadzone=new t.Rectangle((this.bounds.width-r)/2,(this.bounds.height-o)/2,r,o);break;case e.lockOn:this.deadzone=new t.Rectangle(this.bounds.width/2,this.bounds.height/2,10,10)}},r.prototype.setCenteredDeadzone=function(e,n){this.deadzone=new t.Rectangle((this.bounds.width-e)/2,(this.bounds.height-n)/2,e,n)},r.prototype.updateMatrixes=function(){var e;this._areMatrixedDirty&&(this._transformMatrix=t.Matrix2D.create().translate(-this.entity.transform.position.x,-this.entity.transform.position.y),1!=this._zoom&&(e=t.Matrix2D.create().scale(this._zoom,this._zoom),this._transformMatrix=this._transformMatrix.multiply(e)),0!=this.entity.transform.rotation&&(e=t.Matrix2D.create().rotate(this.entity.transform.rotation),this._transformMatrix=this._transformMatrix.multiply(e)),e=t.Matrix2D.create().translate(this._origin.x,this._origin.y),this._transformMatrix=this._transformMatrix.multiply(e),this._inverseTransformMatrix=this._transformMatrix.invert(),this._areBoundsDirty=!0,this._areMatrixedDirty=!1)},r}(t.Component);t.Camera=i}(es||(es={})),function(t){var e=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}();t.ComponentPool=e}(es||(es={})),function(t){var e=function(){function t(){}return t.prototype.compare=function(t,e){return t.updateOrder-e.updateOrder},t}();t.IUpdatableComparer=e}(es||(es={})),function(t){var e=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return __extends(e,t),e}(t.Component);t.PooledComponent=e}(es||(es={})),function(t){var e=function(e){function n(){var n=null!==e&&e.apply(this,arguments)||this;return n.displayObject=new egret.DisplayObject,n.color=0,n._areBoundsDirty=!0,n._localOffset=t.Vector2.zero,n._renderLayer=0,n._bounds=new t.Rectangle,n}return __extends(n,e),Object.defineProperty(n.prototype,"width",{get:function(){return this.bounds.width},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"height",{get:function(){return this.bounds.height},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"localOffset",{get:function(){return this._localOffset},set:function(t){this.setLocalOffset(t)},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"renderLayer",{get:function(){return this._renderLayer},set:function(t){},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"bounds",{get:function(){return this._areBoundsDirty&&(this._bounds.calculateBounds(this.entity.transform.position,this._localOffset,t.Vector2.zero,this.entity.transform.scale,this.entity.transform.rotation,this.width,this.height),this._areBoundsDirty=!1),this._bounds},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"isVisible",{get:function(){return this._isVisible},set:function(t){this._isVisible!=t&&(this._isVisible=t,this._isVisible?this.onBecameVisible():this.onBecameInvisible())},enumerable:!0,configurable:!0}),n.prototype.onEntityTransformChanged=function(t){this._areBoundsDirty=!0},n.prototype.isVisibleFromCamera=function(t){return this.isVisible=t.bounds.intersects(this.bounds),this.isVisible},n.prototype.setRenderLayer=function(t){if(t!=this._renderLayer){var e=this._renderLayer;this._renderLayer=t,this.entity&&this.entity.scene&&this.entity.scene.renderableComponents.updateRenderableRenderLayer(this,e,this._renderLayer)}return this},n.prototype.setColor=function(t){return this.color=t,this},n.prototype.setLocalOffset=function(t){return this._localOffset!=t&&(this._localOffset=t),this},n.prototype.sync=function(t){this.displayObject.x=this.entity.position.x+this.localOffset.x-t.position.x+t.origin.x,this.displayObject.y=this.entity.position.y+this.localOffset.y-t.position.y+t.origin.y,this.displayObject.scaleX=this.entity.scale.x,this.displayObject.scaleY=this.entity.scale.y,this.displayObject.rotation=this.entity.rotation},n.prototype.toString=function(){return"[RenderableComponent] renderLayer: "+this.renderLayer},n.prototype.onBecameVisible=function(){this.displayObject.visible=this.isVisible},n.prototype.onBecameInvisible=function(){this.displayObject.visible=this.isVisible},n}(t.Component);t.RenderableComponent=e}(es||(es={})),function(t){var e=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.reset=function(){},e.prototype.render=function(t){},e}(t.RenderableComponent);t.Mesh=e}(es||(es={})),function(t){var e=egret.Bitmap,n=function(n){function i(e){void 0===e&&(e=null);var i=n.call(this)||this;return e instanceof t.Sprite?i.setSprite(e):e instanceof egret.Texture&&i.setSprite(new t.Sprite(e)),i}return __extends(i,n),Object.defineProperty(i.prototype,"bounds",{get:function(){return this._areBoundsDirty&&this._sprite&&(this._bounds.calculateBounds(this.entity.transform.position,this._localOffset,this._origin,this.entity.transform.scale,this.entity.transform.rotation,this._sprite.sourceRect.width,this._sprite.sourceRect.height),this._areBoundsDirty=!1),this._bounds},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"originNormalized",{get:function(){return new t.Vector2(this._origin.x/this.width*this.entity.transform.scale.x,this._origin.y/this.height*this.entity.transform.scale.y)},set:function(e){this.setOrigin(new t.Vector2(e.x*this.width/this.entity.transform.scale.x,e.y*this.height/this.entity.transform.scale.y))},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"origin",{get:function(){return this._origin},set:function(t){this.setOrigin(t)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"sprite",{get:function(){return this._sprite},set:function(t){this.setSprite(t)},enumerable:!0,configurable:!0}),i.prototype.setSprite=function(t){return this._sprite=t,this._sprite&&(this._origin=this._sprite.origin,this.displayObject.anchorOffsetX=this._origin.x,this.displayObject.anchorOffsetY=this._origin.y),this.displayObject=new e(t.texture2D),this},i.prototype.setOrigin=function(t){return this._origin!=t&&(this._origin=t,this.displayObject.anchorOffsetX=this._origin.x,this.displayObject.anchorOffsetY=this._origin.y,this._areBoundsDirty=!0),this},i.prototype.setOriginNormalized=function(e){return this.setOrigin(new t.Vector2(e.x*this.width/this.entity.transform.scale.x,e.y*this.height/this.entity.transform.scale.y)),this},i.prototype.render=function(t){this.sync(t),this.displayObject.x=this.entity.position.x-this.origin.x+this.localOffset.x-t.position.x+t.origin.x,this.displayObject.y=this.entity.position.y-this.origin.y+this.localOffset.y-t.position.y+t.origin.y},i}(t.RenderableComponent);t.SpriteRenderer=n}(es||(es={})),function(t){var e=function(t){function e(e){var n=t.call(this,e)||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))}},e}(t.SpriteRenderer);t.TiledSpriteRenderer=e}(es||(es={})),function(t){var e=function(e){function n(){var t=null!==e&&e.apply(this,arguments)||this;return t.scrollSpeedX=15,t.scroolSpeedY=0,t._scrollX=0,t._scrollY=0,t}return __extends(n,e),n.prototype.update=function(){this._scrollX+=this.scrollSpeedX*t.Time.deltaTime,this._scrollY+=this.scroolSpeedY*t.Time.deltaTime,this.sourceRect.x=this._scrollX,this.sourceRect.y=this._scrollY},n.prototype.render=function(t){if(this.sprite){e.prototype.render.call(this,t);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))}},n}(t.TiledSpriteRenderer);t.ScrollingSpriteRenderer=e}(es||(es={})),function(t){var e=function(){return function(e,n,i){void 0===n&&(n=new t.Rectangle(0,0,e.textureWidth,e.textureHeight)),void 0===i&&(i=n.getHalfSize()),this.uvs=new t.Rectangle,this.texture2D=e,this.sourceRect=n,this.center=new t.Vector2(.5*n.width,.5*n.height),this.origin=i;var r=1/e.textureWidth,o=1/e.textureHeight;this.uvs.x=n.x*r,this.uvs.y=n.y*o,this.uvs.width=n.width*r,this.uvs.height=n.height*o}}();t.Sprite=e}(es||(es={})),function(t){var e=function(){return function(t,e){this.sprites=t,this.frameRate=e}}();t.SpriteAnimation=e}(es||(es={})),function(t){var e,n;!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"}(e=t.LoopMode||(t.LoopMode={})),function(t){t[t.none=0]="none",t[t.running=1]="running",t[t.paused=2]="paused",t[t.completed=3]="completed"}(n=t.State||(t.State={}));var i=function(i){function r(t){var e=i.call(this,t)||this;return e.speed=1,e.animationState=n.none,e._elapsedTime=0,e._animations=new Map,e}return __extends(r,i),Object.defineProperty(r.prototype,"isRunning",{get:function(){return this.animationState==n.running},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"animations",{get:function(){return this._animations},enumerable:!0,configurable:!0}),r.prototype.update=function(){if(this.animationState==n.running&&this.currentAnimation){var i=this.currentAnimation,r=1/(i.frameRate*this.speed),o=r*i.sprites.length;this._elapsedTime+=t.Time.deltaTime;var s=Math.abs(this._elapsedTime);if(this._loopMode==e.once&&s>o||this._loopMode==e.pingPongOnce&&s>2*o)return this.animationState=n.completed,this._elapsedTime=0,this.currentFrame=0,void(this.sprite=i.sprites[this.currentFrame]);var a=Math.floor(s/r),c=i.sprites.length;if(c>2&&(this._loopMode==e.pingPong||this._loopMode==e.pingPongOnce)){var h=c-1;this.currentFrame=h-Math.abs(h-a%(2*h))}else this.currentFrame=a%c;this.sprite=i.sprites[this.currentFrame]}},r.prototype.addAnimation=function(t,e){return!this.sprite&&e.sprites.length>0&&this.setSprite(e.sprites[0]),this._animations[t]=e,this},r.prototype.play=function(t,i){void 0===i&&(i=null),this.currentAnimation=this._animations[t],this.currentAnimationName=t,this.currentFrame=0,this.animationState=n.running,this.sprite=this.currentAnimation.sprites[0],this._elapsedTime=0,this._loopMode=i||e.loop},r.prototype.isAnimationActive=function(t){return this.currentAnimation&&this.currentAnimationName==t},r.prototype.pause=function(){this.animationState=n.paused},r.prototype.unPause=function(){this.animationState=n.running},r.prototype.stop=function(){this.currentAnimation=null,this.currentAnimationName=null,this.currentFrame=0,this.animationState=n.none},r}(t.SpriteRenderer);t.SpriteAnimator=i}(es||(es={})),function(t){var e=function(e){function n(){return null!==e&&e.apply(this,arguments)||this}return __extends(n,e),n.prototype.onAddedToEntity=function(){this._triggerHelper=new t.ColliderTriggerHelper(this.entity)},n.prototype.calculateMovement=function(e,n){if(!this.entity.getComponent(t.Collider)||!this._triggerHelper)return!1;for(var i=this.entity.getComponents(t.Collider),r=0;r>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<>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<=this._bits.length){var e=new Number[t+1];e=this._bits.copyWithin(0,0,this._bits.length),this._bits=e}},t.LONG_MASK=63,t}();t.BitSet=e}(es||(es={})),function(t){var e=function(){function e(t){this._components=[],this._componentsToAdd=[],this._componentsToRemove=[],this._tempBufferList=[],this._entity=t}return Object.defineProperty(e.prototype,"count",{get:function(){return this._components.length},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"buffer",{get:function(){return this._components},enumerable:!0,configurable:!0}),e.prototype.markEntityListUnsorted=function(){this._isComponentListUnsorted=!0},e.prototype.add=function(t){this._componentsToAdd.push(t)},e.prototype.remove=function(t){this._componentsToRemove.contains(t)&&console.warn("You are trying to remove a Component ("+t+") that you already removed"),this._componentsToAdd.contains(t)?this._componentsToAdd.remove(t):this._componentsToRemove.push(t)},e.prototype.removeAllComponents=function(){for(var t=0;t0){for(var n=0;n0){n=0;for(var i=this._componentsToAdd.length;n0){var e=this._entitiesToRemove;this._entitiesToRemove=this._tempEntityList,this._tempEntityList=e,this._tempEntityList.forEach(function(e){t.removeFromTagList(e),t._entities.remove(e),e.onRemovedFromScene(),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.addToTagList(e),t.scene.entityProcessors.onEntityAdded(e))}),this._tempEntityList.forEach(function(t){return t.onAddedToScene()}),this._tempEntityList.length=0,this._isEntityListUnsorted=!0}this._isEntityListUnsorted&&(this._entities.sort(),this._isEntityListUnsorted=!1),this._unsortedTags.length>0&&(this._unsortedTags.forEach(function(e){t._entityDict.get(e).sort()}),this._unsortedTags.length=0)},e.prototype.findEntity=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))},e.prototype.all=function(){for(var e=this,n=[],i=0;i0){for(var t=0,n=this._unsortedRenderLayers.length;t=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}();!function(t){var e=function(){function e(){}return e.convertImageToCanvas=function(e,n){this.sharedCanvas||(this.sharedCanvas=egret.sys.createCanvas(),this.sharedContext=this.sharedCanvas.getContext("2d"));var i=e.$getTextureWidth(),r=e.$getTextureHeight();n||((n=egret.$TempRectangle).x=0,n.y=0,n.width=i,n.height=r),n.x=Math.min(n.x,i-1),n.y=Math.min(n.y,r-1),n.width=Math.min(n.width,i-n.x),n.height=Math.min(n.height,r-n.y);var o=Math.floor(n.width),s=Math.floor(n.height),a=this.sharedCanvas;if(a.style.width=o+"px",a.style.height=s+"px",this.sharedCanvas.width=o,this.sharedCanvas.height=s,"webgl"==egret.Capabilities.renderMode){var c=void 0;e.$renderBuffer?c=e:(egret.sys.systemRenderer.renderClear&&egret.sys.systemRenderer.renderClear(),(c=new egret.RenderTexture).drawToTexture(new egret.Bitmap(e)));for(var h=c.$renderBuffer.getPixels(n.x,n.y,o,s),u=0,l=0,p=0;p=0?"png":"jpg"});return wx.getFileSystemManager().saveFile({tempFilePath:o,filePath:wx.env.USER_DATA_PATH+"/"+n,success:function(t){}}),o},e.getPixel32=function(t,e,n){return egret.$warn(1041,"getPixel32","getPixels"),t.getPixels(e,n)},e.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)}},e}();t.TextureUtils=e}(es||(es={})),function(t){var e=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}();t.Time=e}(es||(es={}));var 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":i.indexOf("android")>-1&&(this.os="Android");var r=n.language;r=r.indexOf("zh")>-1?"zh-CN":"en-US",this.language=r}},e}(egret.Capabilities);t.GraphicsCapabilities=e}(es||(es={})),function(t){var e=function(){function e(){this.setup(),this.graphicsCapabilities=new t.GraphicsCapabilities,this.graphicsCapabilities.initialize(this)}return Object.defineProperty(e.prototype,"viewport",{get:function(){return this._viewport},enumerable:!0,configurable:!0}),e.prototype.setup=function(){this._viewport=new t.Viewport(0,0,t.Core._instance.stage.stageWidth,t.Core._instance.stage.stageHeight)},e}();t.GraphicsDevice=e}(es||(es={})),function(t){var e=function(){function e(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(e.prototype,"width",{get:function(){return this._width},set:function(t){this._width=t},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"height",{get:function(){return this._height},set:function(t){this._height=t},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"aspectRatio",{get:function(){return 0!=this._height&&0!=this._width?this._width/this._height:0},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"bounds",{get:function(){return new t.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}),e}();t.Viewport=e}(es||(es={})),function(t){var e=function(e){function n(){return e.call(this,t.PostProcessor.default_vert,n.blur_frag,{screenWidth:t.Core.graphicsDevice.viewport.width,screenHeight:t.Core.graphicsDevice.viewport.height})||this}return __extends(n,e),n.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}",n}(egret.CustomFilter);t.GaussianBlurEffect=e}(es||(es={})),function(t){var e=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);t.PolygonLightEffect=e}(es||(es={})),function(t){var e=function(){function e(t){void 0===t&&(t=null),this.enabled=!0,this.effect=t}return e.prototype.onAddedToScene=function(e){this.scene=e,this.shape=new egret.Shape,this.shape.graphics.beginFill(16777215,1),this.shape.graphics.drawRect(0,0,t.Core.graphicsDevice.viewport.width,t.Core.graphicsDevice.viewport.height),this.shape.graphics.endFill(),e.addChild(this.shape)},e.prototype.process=function(){this.drawFullscreenQuad()},e.prototype.onSceneBackBufferSizeChanged=function(t,e){},e.prototype.unload=function(){this.effect&&(this.effect=null),this.scene.removeChild(this.shape),this.scene=null},e.prototype.drawFullscreenQuad=function(){this.scene.filters=[this.effect]},e.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}",e}();t.PostProcessor=e}(es||(es={})),function(t){var e=function(e){function n(){return null!==e&&e.apply(this,arguments)||this}return __extends(n,e),n.prototype.onAddedToScene=function(n){e.prototype.onAddedToScene.call(this,n),this.effect=new t.GaussianBlurEffect},n}(t.PostProcessor);t.GaussianBlurPostProcessor=e}(es||(es={})),function(t){var e=function(){function t(t,e){void 0===e&&(e=null),this.renderOrder=0,this.camera=e,this.renderOrder=t}return t.prototype.onAddedToScene=function(t){},t.prototype.unload=function(){},t.prototype.onSceneBackBufferSizeChanged=function(t,e){},t.prototype.compareTo=function(t){return this.renderOrder-t.renderOrder},t.prototype.beginRender=function(t){},t.prototype.renderAfterStateCheck=function(t,e){t.render(e)},t}();t.Renderer=e}(es||(es={})),function(t){var e=function(t){function e(){return t.call(this,0,null)||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},e.pointOnCirlce=function(n,i,r){var o=e.toRadians(r);return new t.Vector2(Math.cos(o)*o+n.x,Math.sin(o)*o+n.y)},e.isEven=function(t){return t%2==0},e.clamp01=function(t){return t<0?0:t>1?1:t},e.angleBetweenVectors=function(t,e){return Math.atan2(e.y-t.y,e.x-t.x)},e.Epsilon=1e-5,e.Rad2Deg=57.29578,e.Deg2Rad=.0174532924,e}();t.MathHelper=e}(es||(es={})),function(t){t.matrixPool=[];var e=function(e){function n(){return null!==e&&e.apply(this,arguments)||this}return __extends(n,e),Object.defineProperty(n.prototype,"m11",{get:function(){return this.a},set:function(t){this.a=t},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"m12",{get:function(){return this.b},set:function(t){this.b=t},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"m21",{get:function(){return this.c},set:function(t){this.c=t},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"m22",{get:function(){return this.d},set:function(t){this.d=t},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"m31",{get:function(){return this.tx},set:function(t){this.tx=t},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"m32",{get:function(){return this.ty},set:function(t){this.ty=t},enumerable:!0,configurable:!0}),n.create=function(){var e=t.matrixPool.pop();return e||(e=new n),e},n.prototype.identity=function(){return this.a=this.d=1,this.b=this.c=this.tx=this.ty=0,this},n.prototype.translate=function(t,e){return this.tx+=t,this.ty+=e,this},n.prototype.scale=function(t,e){return 1!==t&&(this.a*=t,this.c*=t,this.tx*=t),1!==e&&(this.b*=e,this.d*=e,this.ty*=e),this},n.prototype.rotate=function(t){if(0!==(t=+t)){t/=DEG_TO_RAD;var e=Math.cos(t),n=Math.sin(t),i=this.a,r=this.b,o=this.c,s=this.d,a=this.tx,c=this.ty;this.a=i*e-r*n,this.b=i*n+r*e,this.c=o*e-s*n,this.d=o*n+s*e,this.tx=a*e-c*n,this.ty=a*n+c*e}return this},n.prototype.invert=function(){return this.$invertInto(this),this},n.prototype.add=function(t){return this.m11+=t.m11,this.m12+=t.m12,this.m21+=t.m21,this.m22+=t.m22,this.m31+=t.m31,this.m32+=t.m32,this},n.prototype.substract=function(t){return this.m11-=t.m11,this.m12-=t.m12,this.m21-=t.m21,this.m22-=t.m22,this.m31-=t.m31,this.m32-=t.m32,this},n.prototype.divide=function(t){return this.m11/=t.m11,this.m12/=t.m12,this.m21/=t.m21,this.m22/=t.m22,this.m31/=t.m31,this.m32/=t.m32,this},n.prototype.multiply=function(t){var e=this.m11*t.m11+this.m12*t.m21,n=this.m11*t.m12+this.m12*t.m22,i=this.m21*t.m11+this.m22*t.m21,r=this.m21*t.m12+this.m22*t.m22,o=this.m31*t.m11+this.m32*t.m21+t.m31,s=this.m31*t.m12+this.m32*t.m22+t.m32;return this.m11=e,this.m12=n,this.m21=i,this.m22=r,this.m31=o,this.m32=s,this},n.prototype.determinant=function(){return this.m11*this.m22-this.m12*this.m21},n.prototype.release=function(e){e&&t.matrixPool.push(e)},n}(egret.Matrix);t.Matrix2D=e}(es||(es={})),function(t){var e=function(e){function n(){return null!==e&&e.apply(this,arguments)||this}return __extends(n,e),Object.defineProperty(n.prototype,"max",{get:function(){return new t.Vector2(this.right,this.bottom)},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"center",{get:function(){return new t.Vector2(this.x+this.width/2,this.y+this.height/2)},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"location",{get:function(){return new t.Vector2(this.x,this.y)},set:function(t){this.x=t.x,this.y=t.y},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"size",{get:function(){return new t.Vector2(this.width,this.height)},set:function(t){this.width=t.x,this.height=t.y},enumerable:!0,configurable:!0}),n.fromMinMax=function(t,e,i,r){return new n(t,e,i-t,r-e)},n.rectEncompassingPoints=function(t){for(var e=Number.POSITIVE_INFINITY,n=Number.POSITIVE_INFINITY,i=Number.NEGATIVE_INFINITY,r=Number.NEGATIVE_INFINITY,o=0;oi&&(i=s.x),s.yr&&(r=s.y)}return this.fromMinMax(e,n,i,r)},n.prototype.intersects=function(t){return t.left1)return!1;var u=(c.x*o.y-c.y*o.x)/a;return!(u<0||u>1)},n.lineToLineIntersection=function(e,n,i,r){var o=new t.Vector2(0,0),s=t.Vector2.subtract(n,e),a=t.Vector2.subtract(r,i),c=s.x*a.y-s.y*a.x;if(0==c)return o;var h=t.Vector2.subtract(i,e),u=(h.x*a.y-h.y*a.x)/c;if(u<0||u>1)return o;var l=(h.x*s.y-h.y*s.x)/c;return l<0||l>1?o:o=t.Vector2.add(e,new t.Vector2(u*s.x,u*s.y))},n.closestPointOnLine=function(e,n,i){var r=t.Vector2.subtract(n,e),o=t.Vector2.subtract(i,e),s=t.Vector2.dot(o,r)/t.Vector2.dot(r,r);return s=t.MathHelper.clamp(s,0,1),t.Vector2.add(e,new t.Vector2(r.x*s,r.y*s))},n.isCircleToCircle=function(e,n,i,r){return t.Vector2.distanceSquared(e,i)<(n+r)*(n+r)},n.isCircleToLine=function(e,n,i,r){return t.Vector2.distanceSquared(e,this.closestPointOnLine(i,r,e))=t&&r.y>=e&&r.x=t+i&&(s|=e.right),o.y=n+r&&(s|=e.bottom),s},n}();t.Collisions=n}(es||(es={})),function(t){var e=function(){function e(){}return e.reset=function(){this._spatialHash=new t.SpatialHash(this.spatialHashCellSize)},e.clear=function(){this._spatialHash.clear()},e.overlapCircleAll=function(t,e,n,i){if(void 0===i&&(i=-1),0!=n.length)return this._spatialHash.overlapCircle(t,e,n,i);console.error("An empty results array was passed in. No results will ever be returned.")},e.boxcastBroadphase=function(t,e){return void 0===e&&(e=this.allLayers),this._spatialHash.aabbBroadphase(t,null,e)},e.boxcastBroadphaseExcludingSelf=function(t,e,n){return void 0===n&&(n=this.allLayers),this._spatialHash.aabbBroadphase(e,t,n)},e.addCollider=function(t){e._spatialHash.register(t)},e.removeCollider=function(t){e._spatialHash.remove(t)},e.updateCollider=function(t){this._spatialHash.remove(t),this._spatialHash.register(t)},e.debugDraw=function(t){this._spatialHash.debugDraw(t,2)},e.spatialHashCellSize=100,e.allLayers=-1,e}();t.Physics=e}(es||(es={})),function(t){var e=function(){function t(){}return t.prototype.clone=function(){return ObjectUtils.clone(this)},t}();t.Shape=e}(es||(es={})),function(t){var e=function(e){function n(t,n){var i=e.call(this)||this;return i._areEdgeNormalsDirty=!0,i.isUnrotated=!0,i.setPoints(t),i.isBox=n,i}return __extends(n,e),Object.defineProperty(n.prototype,"edgeNormals",{get:function(){return this._areEdgeNormalsDirty&&this.buildEdgeNormals(),this._edgeNormals},enumerable:!0,configurable:!0}),n.buildSymmetricalPolygon=function(e,n){for(var i=new Array(e),r=0;r=this.points.length?this.points[0]:this.points[i+1];var o=t.Vector2Ext.perpendicular(r,e);o=t.Vector2.normalize(o),this._edgeNormals[i]=o}},n.prototype.recalculateBounds=function(e){if(this.center=e.localOffset,e.shouldColliderScaleAndRotateWithTransform){var n=!0,i=void 0,r=t.Matrix2D.create().translate(-this._polygonCenter.x,-this._polygonCenter.y);if(e.entity.transform.scale!=t.Vector2.zero&&(i=t.Matrix2D.create().scale(e.entity.transform.scale.x,e.entity.transform.scale.y),r=r.multiply(i),n=!1,this.center=t.Vector2.multiply(e.localOffset,e.entity.transform.scale)),0!=e.entity.transform.rotation){i=t.Matrix2D.create().rotate(e.entity.transform.rotation),r=r.multiply(i);var o=Math.atan2(e.localOffset.y,e.localOffset.x)*t.MathHelper.Rad2Deg,s=n?e._localOffsetLength:t.Vector2.multiply(e.localOffset,e.entity.transform.scale).length();this.center=t.MathHelper.pointOnCirlce(t.Vector2.zero,s,e.entity.transform.rotation+o)}i=t.Matrix2D.create().translate(this._polygonCenter.x,this._polygonCenter.y),r=r.multiply(i),t.Vector2Ext.transform(this._originalPoints,r,this.points),this.isUnrotated=0==e.entity.transform.rotation,e._isRotationDirty&&(this._areEdgeNormalsDirty=!0)}this.position=t.Vector2.add(e.entity.transform.position,this.center),this.bounds=t.Rectangle.rectEncompassingPoints(this.points),this.bounds.location=this.bounds.location.add(this.position)},n.prototype.overlaps=function(e){var i=new t.CollisionResult;if(e instanceof n)return t.ShapeCollisions.polygonToPolygon(this,e,i);if(e instanceof t.Circle)return!!t.ShapeCollisions.circleToPolygon(e,this,i)&&(i.invertResult(),!0);throw new Error("overlaps of Pologon to "+e+" are not supported")},n.prototype.collidesWithShape=function(e,i){if(e instanceof n)return t.ShapeCollisions.polygonToPolygon(this,e,i);if(e instanceof t.Circle)return!!t.ShapeCollisions.circleToPolygon(e,this,i)&&(i.invertResult(),!0);throw new Error("overlaps of Polygon to "+e+" are not supported")},n.prototype.containsPoint=function(e){e=t.Vector2.subtract(e,this.position);for(var n=!1,i=0,r=this.points.length-1;ie.y!=this.points[r].y>e.y&&e.x<(this.points[r].x-this.points[i].x)*(e.y-this.points[i].y)/(this.points[r].y-this.points[i].y)+this.points[i].x&&(n=!n);return n},n.prototype.pointCollidesWithShape=function(e,n){return t.ShapeCollisions.pointToPoly(e,this,n)},n}(t.Shape);t.Polygon=e}(es||(es={})),function(t){var e=function(e){function n(t,i){var r=e.call(this,n.buildBox(t,i),!0)||this;return r.width=t,r.height=i,r}return __extends(n,e),n.buildBox=function(e,n){var i=e/2,r=n/2,o=new Array(4);return o[0]=new t.Vector2(-i,-r),o[1]=new t.Vector2(i,-r),o[2]=new t.Vector2(i,r),o[3]=new t.Vector2(-i,r),o},n.prototype.updateBox=function(e,n){this.width=e,this.height=n;var i=e/2,r=n/2;this.points[0]=new t.Vector2(-i,-r),this.points[1]=new t.Vector2(i,-r),this.points[2]=new t.Vector2(i,r),this.points[3]=new t.Vector2(-i,r);for(var o=0;o0&&(o=!1),!o)return!1;(m=Math.abs(m))r&&(r=o);return{min:i,max:r}},e.circleToPolygon=function(e,n,i){var r,o=t.Vector2.subtract(e.position,n.position),s=t.Polygon.getClosestPointOnPolygonToPoint(n.points,o,0,i.normal),a=n.containsPoint(e.position);if(0>e.radius*e.radius&&!a)return!1;a?r=t.Vector2.multiply(i.normal,new t.Vector2(Math.sqrt(0)-e.radius)):r=t.Vector2.multiply(i.normal,new t.Vector2(e.radius));return i.minimumTranslationVector=r,i.point=t.Vector2.add(s,n.position),!0},e.circleToBox=function(e,n,i){var r=n.bounds.getClosestPointOnRectangleBorderToPoint(e.position,i.normal);if(n.containsPoint(e.position)){i.point=r;var o=t.Vector2.add(r,t.Vector2.multiply(i.normal,new t.Vector2(e.radius)));return i.minimumTranslationVector=t.Vector2.subtract(e.position,o),!0}var s=t.Vector2.distanceSquared(r,e.position);if(0==s)i.minimumTranslationVector=t.Vector2.multiply(i.normal,new t.Vector2(e.radius));else if(s<=e.radius*e.radius){i.normal=t.Vector2.subtract(e.position,r);var a=i.normal.length()-e.radius;return i.point=r,i.normal=t.Vector2Ext.normalize(i.normal),i.minimumTranslationVector=t.Vector2.multiply(new t.Vector2(a),i.normal),!0}return!1},e.pointToCircle=function(e,n,i){var r=t.Vector2.distanceSquared(e,n.position),o=1+n.radius;if(r0&&this.debugDrawCellDetails(n,i,r.length,t,e)}},e.prototype.aabbBroadphase=function(e,n,i){this._tempHashSet.length=0;for(var r=this.cellCoords(e.x,e.y),o=this.cellCoords(e.right,e.bottom),s=r.x;s<=o.x;s++)for(var a=r.y;a<=o.y;a++){var c=this.cellAtPosition(s,a);if(c)for(var h=0;hn;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={},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}(),Base64Utils=function(){function t(){}return t.decode=function(t,e){void 0===e&&(e=!0);var n,i,r,o,s,a,c="",h=0;for(t=(t=this.getConfKey(t)).replace(/[^A-Za-z0-9\+\/\=]/g,"");h>4,i=(15&o)<<4|(s=this._keyAll.indexOf(t.charAt(h++)))>>2,r=(3&s)<<6|(a=this._keyAll.indexOf(t.charAt(h++))),c+=String.fromCharCode(n),64!=s&&(0==i?e&&(c+=String.fromCharCode(i)):c+=String.fromCharCode(i)),64!=a&&(0==r?e&&(c+=String.fromCharCode(r)):c+=String.fromCharCode(r));return c=this._utf8_decode(c)},t._utf8_encode=function(t){t=t.replace(/\r\n/g,"\n");for(var e="",n=0;n127&&i<2048?(e+=String.fromCharCode(i>>6|192),e+=String.fromCharCode(63&i|128)):(e+=String.fromCharCode(i>>12|224),e+=String.fromCharCode(i>>6&63|128),e+=String.fromCharCode(63&i|128))}return e},t._utf8_decode=function(t){for(var e="",n=0,i=0,r=0,o=0;n191&&i<224?(r=t.charCodeAt(n+1),e+=String.fromCharCode((31&i)<<6|63&r),n+=2):(r=t.charCodeAt(n+1),o=t.charCodeAt(n+2),e+=String.fromCharCode((15&i)<<12|(63&r)<<6|63&o),n+=3);return e},t.getConfKey=function(t){return t.slice(1,t.length)},t._keyNum="0123456789+/",t._keyStr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",t._keyAll=t._keyNum+t._keyStr,t.encode=function(t){var e,n,i,r,o,s,a,c="",h=0;for(t=this._utf8_encode(t);h>2,o=(3&e)<<4|(n=t.charCodeAt(h++))>>4,s=(15&n)<<2|(i=t.charCodeAt(h++))>>6,a=63&i,isNaN(n)?s=a=64:isNaN(i)&&(a=64),c=c+this._keyAll.charAt(r)+this._keyAll.charAt(o)+this._keyAll.charAt(s)+this._keyAll.charAt(a);return this._keyStr.charAt(Math.floor(Math.random()*this._keyStr.length))+c},t}();!function(t){var e=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}();t.ContentManager=e}(es||(es={})),function(t){var e=function(){function e(){}return e.drawLine=function(e,n,i,r,o){void 0===o&&(o=1),this.drawLineAngle(e,n,t.MathHelper.angleBetweenVectors(n,i),t.Vector2.distance(n,i),r,o)},e.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},e.drawHollowRect=function(t,e,n,i){void 0===i&&(i=1),this.drawHollowRectR(t,e.x,e.y,e.width,e.height,n,i)},e.drawHollowRectR=function(e,n,i,r,o,s,a){void 0===a&&(a=1);var c=new t.Vector2(n,i).round(),h=new t.Vector2(n+r,i).round(),u=new t.Vector2(n+r,i+o).round(),l=new t.Vector2(n,i+o).round();this.drawLine(e,c,h,s,a),this.drawLine(e,h,u,s,a),this.drawLine(e,u,l,s,a),this.drawLine(e,l,c,s,a)},e.drawPixel=function(e,n,i,r){void 0===r&&(r=1);var o=new t.Rectangle(n.x,n.y,r,r);1!=r&&(o.x-=.5*r,o.y-=.5*r),e.graphics.beginFill(i),e.graphics.drawRect(o.x,o.y,o.width,o.height),e.graphics.endFill()},e.getColorMatrix=function(t){var e=[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0];return e[0]=Math.floor(t/256/256)/255,e[6]=Math.floor(t/256%256)/255,e[12]=t%256/255,new egret.ColorMatrixFilter(e)},e}();t.DrawUtils=e}(es||(es={})),function(t){var e=function(){return function(t,e){this.func=t,this.context=e}}();t.FuncPack=e;var n=function(){function t(){this._messageTable=new Map}return t.prototype.addObserver=function(t,n,i){var r=this._messageTable.get(t);r||(r=[],this._messageTable.set(t,r)),-1!=r.findIndex(function(t){return t.func==n})&&console.warn("您试图添加相同的观察者两次"),r.push(new e(n,i))},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}();t.Emitter=n}(es||(es={})),function(t){var e=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}();t.GlobalManager=e}(es||(es={})),function(t){var e=function(){function e(){this.x=0,this.y=0,this.touchPoint=-1,this.touchDown=!1}return Object.defineProperty(e.prototype,"position",{get:function(){return new t.Vector2(this.x,this.y)},enumerable:!0,configurable:!0}),e.prototype.reset=function(){this.x=0,this.y=0,this.touchDown=!1,this.touchPoint=-1},e}();t.TouchState=e;var n=function(){function n(){}return Object.defineProperty(n,"gameTouchs",{get:function(){return this._gameTouchs},enumerable:!0,configurable:!0}),Object.defineProperty(n,"resolutionScale",{get:function(){return this._resolutionScale},enumerable:!0,configurable:!0}),Object.defineProperty(n,"totalTouchCount",{get:function(){return this._totalTouchCount},enumerable:!0,configurable:!0}),Object.defineProperty(n,"touchPosition",{get:function(){return this._gameTouchs[0]?this._gameTouchs[0].position:t.Vector2.zero},enumerable:!0,configurable:!0}),Object.defineProperty(n,"maxSupportedTouch",{get:function(){return t.Core._instance.stage.maxTouches},set:function(e){t.Core._instance.stage.maxTouches=e,this.initTouchCache()},enumerable:!0,configurable:!0}),Object.defineProperty(n,"touchPositionDelta",{get:function(){var e=t.Vector2.subtract(this.touchPosition,this._previousTouchState.position);return e.length()>0&&this.setpreviousTouchState(this._gameTouchs[0]),e},enumerable:!0,configurable:!0}),n.initialize=function(){this._init||(this._init=!0,t.Core._instance.stage.addEventListener(egret.TouchEvent.TOUCH_BEGIN,this.touchBegin,this),t.Core._instance.stage.addEventListener(egret.TouchEvent.TOUCH_MOVE,this.touchMove,this),t.Core._instance.stage.addEventListener(egret.TouchEvent.TOUCH_END,this.touchEnd,this),t.Core._instance.stage.addEventListener(egret.TouchEvent.TOUCH_CANCEL,this.touchEnd,this),t.Core._instance.stage.addEventListener(egret.TouchEvent.TOUCH_RELEASE_OUTSIDE,this.touchEnd,this),this.initTouchCache())},n.scaledPosition=function(e){var n=new t.Vector2(e.x-this._resolutionOffset.x,e.y-this._resolutionOffset.y);return t.Vector2.multiply(n,this.resolutionScale)},n.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}();t.ListPool=e}(es||(es={}));var 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}();!function(t){var e=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}();t.Pair=e}(es||(es={}));var 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.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().5?1:-1},t}();!function(t){var e=function(){function e(){}return e.union=function(e,n){var i=new t.Rectangle(n.x,n.y,0,0),r=new t.Rectangle;return r.x=Math.min(e.x,i.x),r.y=Math.min(e.y,i.y),r.width=Math.max(e.right,i.right)-r.x,r.height=Math.max(e.bottom,r.bottom)-r.y,r},e}();t.RectangleExt=e}(es||(es={})),function(t){var e=function(){function e(){this.triangleIndices=[],this._triPrev=new Array(12),this._triNext=new Array(12)}return e.testPointTriangle=function(e,n,i,r){return!(t.Vector2Ext.cross(t.Vector2.subtract(e,n),t.Vector2.subtract(i,n))<0)&&(!(t.Vector2Ext.cross(t.Vector2.subtract(e,i),t.Vector2.subtract(r,i))<0)&&!(t.Vector2Ext.cross(t.Vector2.subtract(e,r),t.Vector2.subtract(n,r))<0))},e.prototype.triangulate=function(n,i){void 0===i&&(i=!0);var r=n.length;this.initialize(r);for(var o=0,s=0;r>3&&o<500;){o++;var a=!0,c=n[this._triPrev[s]],h=n[s],u=n[this._triNext[s]];if(t.Vector2Ext.isTriangleCCW(c,h,u)){var l=this._triNext[this._triNext[s]];do{if(e.testPointTriangle(n[l],c,h,u)){a=!1;break}l=this._triNext[l]}while(l!=this._triPrev[s])}else a=!1;a?(this.triangleIndices.push(this._triPrev[s]),this.triangleIndices.push(s),this.triangleIndices.push(this._triNext[s]),this._triNext[this._triPrev[s]]=this._triNext[s],this._triPrev[this._triNext[s]]=this._triPrev[s],r--,s=this._triPrev[s]):s=this._triNext[s]}this.triangleIndices.push(this._triPrev[s]),this.triangleIndices.push(s),this.triangleIndices.push(this._triNext[s]),i||this.triangleIndices.reverse()},e.prototype.initialize=function(t){this.triangleIndices.length=0,this._triNext.lengtht.MathHelper.Epsilon?e=t.Vector2.divide(e,new t.Vector2(n)):e.x=e.y=0,e},e.transformA=function(t,e,n,i,r,o){for(var s=0;sthis.safeArea.right&&(s.x=this.safeArea.right-s.width),s.topthis.safeArea.bottom&&(s.y=this.safeArea.bottom-s.height),s},n}();t.Layout=n,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"}(e=t.Alignment||(t.Alignment={}))}(es||(es={})),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.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.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.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={})),function(t){var e=function(){function e(){this.showLog=!1,this._frameKey="frame",this._logKey="log",this.markers=[],this.stopwacth=new stopwatch.Stopwatch,this._markerNameToIdMap=new Map,this._logs=new Array(2);for(var e=0;e=e.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}t.stopwacth.reset(),t.stopwacth.start()}})},e.prototype.beginMark=function(t,n,i){var r=this;void 0===i&&(i=0),new LockUtils(this._frameKey).lock().then(function(){if(i<0||i>=e.maxBars)throw new Error("barIndex argument out of range");var o=r._curLog.bars[i];if(o.markCount>=e.maxSamples)throw new Error("exceeded sample count. either set larger number to timeruler.maxsaple or lower sample count");if(o.nestCount>=e.maxNestCall)throw new Error("exceeded nest count. either set larger number to timeruler.maxnestcall or lower nest calls");var s=r._markerNameToIdMap.get(t);isNaN(s)&&(s=r.markers.length,r._markerNameToIdMap.set(t,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})},e.prototype.endMark=function(t,n){var i=this;void 0===n&&(n=0),new LockUtils(this._frameKey).lock().then(function(){if(n<0||n>=e.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(t);if(isNaN(o))throw new Error("Marker "+t+" 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()})},e.prototype.getAverageTime=function(t,n){if(t<0||t>=e.maxBars)throw new Error("barIndex argument out of range");var i=0,r=this._markerNameToIdMap.get(n);return r&&(i=this.markers[r].logs[t].avg),i},e.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+=e.barHeight+2*e.barPadding,r=Math.max(r,t.markers[t.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)>e.autoAdjustDelay&&(this.sampleFrames=Math.min(e.maxSampleFrames,this.sampleFrames),this.sampleFrames=Math.max(this.targetSampleFrames,r/(1/60*1e3)+1),this._frameAdjust=0);t.y,e.barHeight}},e.prototype.onGraphicsDeviceReset=function(){var n=new t.Layout;this._position=n.place(new t.Vector2(this.width,e.barHeight),0,.01,t.Alignment.bottomCenter).location},e.maxBars=8,e.maxSamples=256,e.maxNestCall=32,e.barHeight=8,e.maxSampleFrames=4,e.logSnapDuration=120,e.barPadding=2,e.autoAdjustDelay=30,e}();t.TimeRuler=e;var n=function(){return function(){this.bars=new Array(e.maxBars),this.bars.fill(new i,0,e.maxBars)}}();t.FrameLog=n;var i=function(){return function(){this.markers=new Array(e.maxSamples),this.markCount=0,this.markerNests=new Array(e.maxNestCall),this.nestCount=0,this.markers.fill(new r,0,e.maxSamples),this.markerNests.fill(0,0,e.maxNestCall)}}();t.MarkerCollection=i;var r=function(){return function(){this.markerId=0,this.beginTime=0,this.endTime=0,this.color=0}}();t.Marker=r;var o=function(){return function(t){this.logs=new Array(e.maxBars),this.name=t,this.logs.fill(new s,0,e.maxBars)}}();t.MarkerInfo=o;var s=function(){return function(){this.snapMin=0,this.snapMax=0,this.snapAvg=0,this.min=0,this.max=0,this.avg=0,this.samples=0,this.color=0,this.initialized=!1}}();t.MarkerLog=s}(es||(es={})); \ No newline at end of file diff --git a/source/gulpfile.js b/source/gulpfile.js index 7f85a5b2..4c5e6136 100644 --- a/source/gulpfile.js +++ b/source/gulpfile.js @@ -11,7 +11,7 @@ gulp.task('buildJs', () => { .js.pipe(inject.replace('var framework;', '')) .pipe(inject.prepend('window.framework = {};\n')) .pipe(inject.replace('var __extends =', 'window.__extends =')) - .pipe(minify({ ext: { min: ".min.js" } })) + .pipe(minify({ext: {min: ".min.js"}})) .pipe(gulp.dest('./bin')); }); diff --git a/source/src/AI/Pathfinding/AStar/AStarPathfinder.ts b/source/src/AI/Pathfinding/AStar/AStarPathfinder.ts index 2be43c70..692d87a2 100644 --- a/source/src/AI/Pathfinding/AStar/AStarPathfinder.ts +++ b/source/src/AI/Pathfinding/AStar/AStarPathfinder.ts @@ -10,7 +10,7 @@ module es { * @param start * @param goal */ - public static search(graph: IAstarGraph, start: T, goal: T){ + public static search(graph: IAstarGraph, start: T, goal: T) { let foundPath = false; let cameFrom = new Map(); cameFrom.set(start, start); @@ -21,17 +21,17 @@ module es { costSoFar.set(start, 0); - while (frontier.count > 0){ + while (frontier.count > 0) { let current = frontier.dequeue(); - if (JSON.stringify(current.data) == JSON.stringify(goal)){ + if (JSON.stringify(current.data) == JSON.stringify(goal)) { foundPath = true; break; } graph.getNeighbors(current.data).forEach(next => { let newCost = costSoFar.get(current.data) + graph.cost(current.data, next); - if (!this.hasKey(costSoFar, next) || newCost < costSoFar.get(next)){ + if (!this.hasKey(costSoFar, next) || newCost < costSoFar.get(next)) { costSoFar.set(next, newCost); let priority = newCost + graph.heuristic(next, goal); frontier.enqueue(new AStarNode(next), priority); @@ -43,7 +43,28 @@ module es { return foundPath ? this.recontructPath(cameFrom, start, goal) : null; } - private static hasKey(map: Map, compareKey: T){ + /** + * 从cameFrom字典重新构造路径 + * @param cameFrom + * @param start + * @param goal + */ + public static recontructPath(cameFrom: Map, start: T, goal: T): T[] { + let path = []; + let current = goal; + path.push(goal); + + while (current != start) { + current = this.getKey(cameFrom, current); + path.push(current); + } + + path.reverse(); + + return path; + } + + private static hasKey(map: Map, compareKey: T) { let iterator = map.keys(); let r: IteratorResult; while (r = iterator.next() , !r.done) { @@ -54,7 +75,7 @@ module es { return false; } - private static getKey(map: Map, compareKey: T){ + private static getKey(map: Map, compareKey: T) { let iterator = map.keys(); let valueIterator = map.values(); let r: IteratorResult; @@ -66,27 +87,6 @@ module es { return null; } - - /** - * 从cameFrom字典重新构造路径 - * @param cameFrom - * @param start - * @param goal - */ - public static recontructPath(cameFrom: Map, start: T, goal: T): T[]{ - let path = []; - let current = goal; - path.push(goal); - - while (current != start){ - current = this.getKey(cameFrom, current); - path.push(current); - } - - path.reverse(); - - return path; - } } /** @@ -95,7 +95,7 @@ module es { export class AStarNode extends PriorityQueueNode { public data: T; - constructor(data: T){ + constructor(data: T) { super(); this.data = data; } diff --git a/source/src/AI/Pathfinding/AStar/AstarGridGraph.ts b/source/src/AI/Pathfinding/AStar/AstarGridGraph.ts index 8c35b25e..844c07b4 100644 --- a/source/src/AI/Pathfinding/AStar/AstarGridGraph.ts +++ b/source/src/AI/Pathfinding/AStar/AstarGridGraph.ts @@ -20,7 +20,7 @@ module es { private _height; private _neighbors: Vector2[] = new Array(4); - constructor(width: number, height: number){ + constructor(width: number, height: number) { this._width = width; this._height = height; } @@ -46,7 +46,7 @@ module es { * @param start * @param goal */ - public search(start: Vector2, goal: Vector2){ + public search(start: Vector2, goal: Vector2) { return AStarPathfinder.search(this, start, goal); } @@ -63,7 +63,7 @@ module es { } public cost(from: Vector2, to: Vector2): number { - return this.weightedNodes.find((p)=> JSON.stringify(p) == JSON.stringify(to)) ? this.weightedNodeWeight : this.defaultWeight; + return this.weightedNodes.find((p) => JSON.stringify(p) == JSON.stringify(to)) ? this.weightedNodeWeight : this.defaultWeight; } public heuristic(node: Vector2, goal: Vector2) { diff --git a/source/src/AI/Pathfinding/AStar/IAstarGraph.ts b/source/src/AI/Pathfinding/AStar/IAstarGraph.ts index 6b0fc08f..839edb41 100644 --- a/source/src/AI/Pathfinding/AStar/IAstarGraph.ts +++ b/source/src/AI/Pathfinding/AStar/IAstarGraph.ts @@ -8,12 +8,14 @@ module es { * @param node */ getNeighbors(node: T): Array; + /** * 计算从从from到to的成本 * @param from * @param to */ cost(from: T, to: T): number; + /** * 计算从node到to的启发式。参见WeightedGridGraph了解常用的Manhatten方法。 * @param node diff --git a/source/src/AI/Pathfinding/AStar/PriorityQueue.ts b/source/src/AI/Pathfinding/AStar/PriorityQueue.ts index 85c0a318..ae315fa4 100644 --- a/source/src/AI/Pathfinding/AStar/PriorityQueue.ts +++ b/source/src/AI/Pathfinding/AStar/PriorityQueue.ts @@ -19,15 +19,6 @@ module es { this._numNodesEverEnqueued = 0; } - /** - * 从队列中删除每个节点。 - * O(n)复杂度 所有尽可能少调用该方法 - */ - public clear() { - this._nodes.splice(1, this._numNodes); - this._numNodes = 0; - } - /** * 返回队列中的节点数。 * O(1)复杂度 @@ -44,18 +35,27 @@ module es { return this._nodes.length - 1; } + /** + * 从队列中删除每个节点。 + * O(n)复杂度 所有尽可能少调用该方法 + */ + public clear() { + this._nodes.splice(1, this._numNodes); + this._numNodes = 0; + } + /** * 返回(在O(1)中)给定节点是否在队列中 * O (1)复杂度 * @param node */ public contains(node: T): boolean { - if (!node){ + if (!node) { console.error("node cannot be null"); return false; } - if (node.queueIndex < 0 || node.queueIndex >= this._nodes.length){ + if (node.queueIndex < 0 || node.queueIndex >= this._nodes.length) { console.error("node.QueueIndex has been corrupted. Did you change it manually? Or add this node to another queue?"); return false; } diff --git a/source/src/AI/Pathfinding/BreadthFirst/BreadthFirstPathfinder.ts b/source/src/AI/Pathfinding/BreadthFirst/BreadthFirstPathfinder.ts index 4cad3f8e..c352fea3 100644 --- a/source/src/AI/Pathfinding/BreadthFirst/BreadthFirstPathfinder.ts +++ b/source/src/AI/Pathfinding/BreadthFirst/BreadthFirstPathfinder.ts @@ -3,7 +3,7 @@ module es { * 计算路径给定的IUnweightedGraph和开始/目标位置 */ export class BreadthFirstPathfinder { - public static search(graph: IUnweightedGraph, start: T, goal: T): T[]{ + public static search(graph: IUnweightedGraph, start: T, goal: T): T[] { let foundPath = false; let frontier = []; frontier.unshift(start); @@ -11,15 +11,15 @@ module es { let cameFrom = new Map(); cameFrom.set(start, start); - while (frontier.length > 0){ + while (frontier.length > 0) { let current = frontier.shift(); - if (JSON.stringify(current) == JSON.stringify(goal)){ + if (JSON.stringify(current) == JSON.stringify(goal)) { foundPath = true; break; } graph.getNeighbors(current).forEach(next => { - if (!this.hasKey(cameFrom, next)){ + if (!this.hasKey(cameFrom, next)) { frontier.unshift(next); cameFrom.set(next, current); } @@ -29,7 +29,7 @@ module es { return foundPath ? AStarPathfinder.recontructPath(cameFrom, start, goal) : null; } - private static hasKey(map: Map, compareKey: T){ + private static hasKey(map: Map, compareKey: T) { let iterator = map.keys(); let r: IteratorResult; while (r = iterator.next() , !r.done) { diff --git a/source/src/AI/Pathfinding/BreadthFirst/IUnweightedGraph.ts b/source/src/AI/Pathfinding/BreadthFirst/IUnweightedGraph.ts index 60c07253..7e53339c 100644 --- a/source/src/AI/Pathfinding/BreadthFirst/IUnweightedGraph.ts +++ b/source/src/AI/Pathfinding/BreadthFirst/IUnweightedGraph.ts @@ -1,5 +1,5 @@ module es { - export interface IUnweightedGraph{ + export interface IUnweightedGraph { /** * getNeighbors方法应该返回从传入的节点可以到达的任何相邻节点。 * @param node diff --git a/source/src/AI/Pathfinding/BreadthFirst/UnweightedGraph.ts b/source/src/AI/Pathfinding/BreadthFirst/UnweightedGraph.ts index 745b1eb6..fb841a61 100644 --- a/source/src/AI/Pathfinding/BreadthFirst/UnweightedGraph.ts +++ b/source/src/AI/Pathfinding/BreadthFirst/UnweightedGraph.ts @@ -6,12 +6,12 @@ module es { export class UnweightedGraph implements IUnweightedGraph { public edges: Map = new Map(); - public addEdgesForNode(node: T, edges: T[]){ + public addEdgesForNode(node: T, edges: T[]) { this.edges.set(node, edges); return this; } - public getNeighbors(node: T){ + public getNeighbors(node: T) { return this.edges.get(node); } } diff --git a/source/src/AI/Pathfinding/Dijkstra/IWeightedGraph.ts b/source/src/AI/Pathfinding/Dijkstra/IWeightedGraph.ts index 2a6223e8..60e743ce 100644 --- a/source/src/AI/Pathfinding/Dijkstra/IWeightedGraph.ts +++ b/source/src/AI/Pathfinding/Dijkstra/IWeightedGraph.ts @@ -1,5 +1,5 @@ module es { - export interface IWeightedGraph{ + export interface IWeightedGraph { /** * * @param node diff --git a/source/src/AI/Pathfinding/Dijkstra/WeightedGridGraph.ts b/source/src/AI/Pathfinding/Dijkstra/WeightedGridGraph.ts index 1de59287..3392d5b1 100644 --- a/source/src/AI/Pathfinding/Dijkstra/WeightedGridGraph.ts +++ b/source/src/AI/Pathfinding/Dijkstra/WeightedGridGraph.ts @@ -32,13 +32,13 @@ module es { private _dirs: Vector2[]; private _neighbors: Vector2[] = new Array(4); - constructor(width: number, height: number, allowDiagonalSearch: boolean = false){ + constructor(width: number, height: number, allowDiagonalSearch: boolean = false) { this._width = width; this._height = height; this._dirs = allowDiagonalSearch ? WeightedGridGraph.COMPASS_DIRS : WeightedGridGraph.CARDINAL_DIRS; } - public isNodeInBounds(node: Vector2){ + public isNodeInBounds(node: Vector2) { return 0 <= node.x && node.x < this._width && 0 <= node.y && node.y < this._height; } @@ -46,11 +46,11 @@ module es { return !this.walls.firstOrDefault(wall => JSON.stringify(wall) == JSON.stringify(node)); } - public search(start: Vector2, goal: Vector2){ + public search(start: Vector2, goal: Vector2) { return WeightedPathfinder.search(this, start, goal); } - public getNeighbors(node: Vector2): Vector2[]{ + public getNeighbors(node: Vector2): Vector2[] { this._neighbors.length = 0; this._dirs.forEach(dir => { @@ -62,7 +62,7 @@ module es { return this._neighbors; } - public cost(from: Vector2, to: Vector2): number{ + public cost(from: Vector2, to: Vector2): number { return this.weightedNodes.find(t => JSON.stringify(t) == JSON.stringify(to)) ? this.weightedNodeWeight : this.defaultWeight; } } diff --git a/source/src/AI/Pathfinding/Dijkstra/WeightedPathfinder.ts b/source/src/AI/Pathfinding/Dijkstra/WeightedPathfinder.ts index 6c609356..0e10e293 100644 --- a/source/src/AI/Pathfinding/Dijkstra/WeightedPathfinder.ts +++ b/source/src/AI/Pathfinding/Dijkstra/WeightedPathfinder.ts @@ -2,14 +2,14 @@ module es { export class WeightedNode extends PriorityQueueNode { public data: T; - constructor(data: T){ + constructor(data: T) { super(); this.data = data; } } export class WeightedPathfinder { - public static search(graph: IWeightedGraph, start: T, goal: T){ + public static search(graph: IWeightedGraph, start: T, goal: T) { let foundPath = false; let cameFrom = new Map(); @@ -21,17 +21,17 @@ module es { costSoFar.set(start, 0); - while (frontier.count > 0){ + while (frontier.count > 0) { let current = frontier.dequeue(); - if (JSON.stringify(current.data) == JSON.stringify(goal)){ + if (JSON.stringify(current.data) == JSON.stringify(goal)) { foundPath = true; break; } graph.getNeighbors(current.data).forEach(next => { let newCost = costSoFar.get(current.data) + graph.cost(current.data, next); - if (!this.hasKey(costSoFar, next) || newCost < costSoFar.get(next)){ + if (!this.hasKey(costSoFar, next) || newCost < costSoFar.get(next)) { costSoFar.set(next, newCost); let priprity = newCost; frontier.enqueue(new WeightedNode(next), priprity); @@ -43,7 +43,22 @@ module es { return foundPath ? this.recontructPath(cameFrom, start, goal) : null; } - private static hasKey(map: Map, compareKey: T){ + public static recontructPath(cameFrom: Map, start: T, goal: T): T[] { + let path = []; + let current = goal; + path.push(goal); + + while (current != start) { + current = this.getKey(cameFrom, current); + path.push(current); + } + + path.reverse(); + + return path; + } + + private static hasKey(map: Map, compareKey: T) { let iterator = map.keys(); let r: IteratorResult; while (r = iterator.next() , !r.done) { @@ -54,7 +69,7 @@ module es { return false; } - private static getKey(map: Map, compareKey: T){ + private static getKey(map: Map, compareKey: T) { let iterator = map.keys(); let valueIterator = map.values(); let r: IteratorResult; @@ -66,20 +81,5 @@ module es { return null; } - - public static recontructPath(cameFrom: Map, start: T, goal: T): T[]{ - let path = []; - let current = goal; - path.push(goal); - - while (current != start){ - current = this.getKey(cameFrom, current); - path.push(current); - } - - path.reverse(); - - return path; - } } } diff --git a/source/src/Debug/Debug.ts b/source/src/Debug/Debug.ts index f889b517..be5abb28 100644 --- a/source/src/Debug/Debug.ts +++ b/source/src/Debug/Debug.ts @@ -2,18 +2,18 @@ module es { export class Debug { private static _debugDrawItems: DebugDrawItem[] = []; - public static drawHollowRect(rectanle: Rectangle, color: number, duration = 0){ + public static drawHollowRect(rectanle: Rectangle, color: number, duration = 0) { this._debugDrawItems.push(new DebugDrawItem(rectanle, color, duration)); } - public static render(){ - if (this._debugDrawItems.length > 0){ + public static render() { + if (this._debugDrawItems.length > 0) { let debugShape = new egret.Shape(); - if (Core.scene){ + if (Core.scene) { Core.scene.addChild(debugShape); } - for (let i = this._debugDrawItems.length - 1; i >= 0; i --){ + for (let i = this._debugDrawItems.length - 1; i >= 0; i--) { let item = this._debugDrawItems[i]; if (item.draw(debugShape)) this._debugDrawItems.removeAt(i); diff --git a/source/src/Debug/DebugDrawItem.ts b/source/src/Debug/DebugDrawItem.ts index a13011fe..cb57f5b3 100644 --- a/source/src/Debug/DebugDrawItem.ts +++ b/source/src/Debug/DebugDrawItem.ts @@ -18,15 +18,15 @@ module es { public y: number; public size: number; - constructor(rectangle: Rectangle, color: number, duration: number){ + constructor(rectangle: Rectangle, color: number, duration: number) { this.rectangle = rectangle; this.color = color; this.duration = duration; this.drawType = DebugDrawType.hollowRectangle; } - public draw(shape: egret.Shape): boolean{ - switch (this.drawType){ + public draw(shape: egret.Shape): boolean { + switch (this.drawType) { case DebugDrawType.line: DrawUtils.drawLine(shape, this.start, this.end, this.color); break; diff --git a/source/src/ECS/Component.ts b/source/src/ECS/Component.ts index ce3af7ba..04fe8007 100644 --- a/source/src/ECS/Component.ts +++ b/source/src/ECS/Component.ts @@ -12,6 +12,10 @@ module es { * 此组件附加的实体 */ public entity: Entity; + /** + * 更新该组件的时间间隔。这与实体的更新间隔无关。 + */ + public updateInterval: number = 1; /** * 快速访问 this.entity.transform @@ -20,6 +24,8 @@ module es { return this.entity.transform; } + private _enabled: boolean = true; + /** * 如果组件和实体都已启用,则为。当启用该组件时,将调用该组件的生命周期方法。状态的改变会导致调用onEnabled/onDisable。 */ @@ -35,6 +41,8 @@ module es { this.setEnabled(value); } + private _updateOrder = 0; + /** 更新此实体上组件的顺序 */ public get updateOrder() { return this._updateOrder; @@ -45,14 +53,6 @@ module es { this.setUpdateOrder(value); } - /** - * 更新该组件的时间间隔。这与实体的更新间隔无关。 - */ - public updateInterval: number = 1; - - private _enabled: boolean = true; - private _updateOrder = 0; - /** * 当此组件已分配其实体,但尚未添加到实体的活动组件列表时调用。有用的东西,如物理组件,需要访问转换来修改碰撞体的属性。 */ diff --git a/source/src/ECS/Components/Camera.ts b/source/src/ECS/Components/Camera.ts index 1af2d159..4c3c67f0 100644 --- a/source/src/ECS/Components/Camera.ts +++ b/source/src/ECS/Components/Camera.ts @@ -12,6 +12,46 @@ module es { } export class Camera extends Component { + public _inset: CameraInset = new CameraInset(); + public _areMatrixedDirty: boolean = true; + public _areBoundsDirty: boolean = true; + public _isProjectionMatrixDirty = true; + /** + * 如果相机模式为cameraWindow 则会进行缓动移动 + * 该值为移动速度 + */ + public followLerp = 0.1; + /** + * 在cameraWindow模式下,宽度/高度被用做边界框,允许在不移动相机的情况下移动 + * 在lockOn模式下,只使用deadZone的x/y值 你可以通过直接setCenteredDeadzone重写它来自定义deadZone + */ + public deadzone: Rectangle = new Rectangle(); + /** + * 相机聚焦于屏幕中心的偏移 + */ + public focusOffset: Vector2 = Vector2.zero; + /** + * 如果为true 相机位置则不会超出地图矩形(0, 0, mapwidth, mapheight) + */ + public mapLockEnabled: boolean = false; + /** + * 當前地圖映射的寬度和高度 + */ + public mapSize: Vector2 = Vector2.zero; + public _targetEntity: Entity; + public _targetCollider: Collider; + public _desiredPositionDelta: Vector2 = new Vector2(); + public _cameraStyle: CameraStyle; + public _worldSpaceDeadZone: Rectangle = new Rectangle(); + + constructor(targetEntity: Entity = null, cameraStyle: CameraStyle = CameraStyle.lockOn) { + super(); + + this._targetEntity = targetEntity; + this._cameraStyle = cameraStyle; + this.setZoom(0); + } + /** * 对entity.transform.position的快速访问 */ @@ -42,6 +82,8 @@ module es { this.entity.transform.rotation = value; } + public _zoom; + /** * 缩放值应该在-1和1之间、然后将该值从minimumZoom转换为maximumZoom。 * 允许你设置适当的最小/最大值,然后使用更直观的-1到1的映射来更改缩放 @@ -65,6 +107,8 @@ module es { this.setZoom(value); } + public _minimumZoom = 0.3; + /** * 相机变焦可以达到的最小非缩放值(0-number.max)。默认为0.3 */ @@ -80,6 +124,8 @@ module es { this.setMinimumZoom(value); } + public _maximumZoom = 3; + /** * 相机变焦可以达到的最大非缩放值(0-number.max)。默认为3 */ @@ -95,20 +141,22 @@ module es { this.setMaximumZoom(value); } + public _bounds: Rectangle = new Rectangle(); + /** * 相机的世界-空间边界 */ - public get bounds(){ + public get bounds() { if (this._areMatrixedDirty) this.updateMatrixes(); - if (this._areBoundsDirty){ + if (this._areBoundsDirty) { // 旋转或非旋转的边界都需要左上角和右下角 let topLeft = this.screenToWorldPoint(new Vector2(this._inset.left, this._inset.top)); let bottomRight = this.screenToWorldPoint(new Vector2(Core.graphicsDevice.viewport.width - this._inset.right, Core.graphicsDevice.viewport.height - this._inset.bottom)); - if (this.entity.transform.rotation != 0){ + if (this.entity.transform.rotation != 0) { // 特别注意旋转的边界。我们需要找到绝对的最小/最大值并从中创建边界 let topRight = this.screenToWorldPoint(new Vector2(Core.graphicsDevice.viewport.width - this._inset.right, this._inset.top)); @@ -135,6 +183,8 @@ module es { return this._bounds; } + public _transformMatrix: Matrix2D = new Matrix2D().identity(); + /** * 用于从世界坐标转换到屏幕 */ @@ -144,6 +194,8 @@ module es { return this._transformMatrix; } + public _inverseTransformMatrix: Matrix2D = new Matrix2D().identity(); + /** * 用于从屏幕坐标到世界的转换 */ @@ -153,6 +205,8 @@ module es { return this._inverseTransformMatrix; } + public _origin: Vector2 = Vector2.zero; + public get origin() { return this._origin; } @@ -164,56 +218,6 @@ module es { } } - public _zoom; - public _minimumZoom = 0.3; - public _maximumZoom = 3; - public _bounds: Rectangle = new Rectangle(); - public _inset: CameraInset = new CameraInset(); - public _transformMatrix: Matrix2D = new Matrix2D().identity(); - public _inverseTransformMatrix: Matrix2D = new Matrix2D().identity(); - public _origin: Vector2 = Vector2.zero; - - public _areMatrixedDirty: boolean = true; - public _areBoundsDirty: boolean = true; - public _isProjectionMatrixDirty = true; - - /** - * 如果相机模式为cameraWindow 则会进行缓动移动 - * 该值为移动速度 - */ - public followLerp = 0.1; - /** - * 在cameraWindow模式下,宽度/高度被用做边界框,允许在不移动相机的情况下移动 - * 在lockOn模式下,只使用deadZone的x/y值 你可以通过直接setCenteredDeadzone重写它来自定义deadZone - */ - public deadzone: Rectangle = new Rectangle(); - /** - * 相机聚焦于屏幕中心的偏移 - */ - public focusOffset: Vector2 = Vector2.zero; - /** - * 如果为true 相机位置则不会超出地图矩形(0, 0, mapwidth, mapheight) - */ - public mapLockEnabled: boolean = false; - /** - * 當前地圖映射的寬度和高度 - */ - public mapSize: Vector2 = Vector2.zero; - - public _targetEntity: Entity; - public _targetCollider: Collider; - public _desiredPositionDelta: Vector2 = new Vector2(); - public _cameraStyle: CameraStyle; - public _worldSpaceDeadZone: Rectangle = new Rectangle(); - - constructor(targetEntity: Entity = null, cameraStyle: CameraStyle = CameraStyle.lockOn) { - super(); - - this._targetEntity = targetEntity; - this._cameraStyle = cameraStyle; - this.setZoom(0); - } - /** * 当场景渲染目标的大小发生变化时,我们会更新相机的原点并调整它的位置以保持它原来的位置 * @param newWidth @@ -226,33 +230,6 @@ module es { this.entity.transform.position = Vector2.add(this.entity.transform.position, Vector2.subtract(this._origin, oldOrigin)); } - protected updateMatrixes(){ - if (!this._areMatrixedDirty) - return; - - let tempMat: Matrix2D; - this._transformMatrix = Matrix2D.create().translate(-this.entity.transform.position.x, -this.entity.transform.position.y); - - if (this._zoom != 1){ - tempMat = Matrix2D.create().scale(this._zoom, this._zoom); - this._transformMatrix = this._transformMatrix.multiply(tempMat); - } - - if (this.entity.transform.rotation != 0){ - tempMat = Matrix2D.create().rotate(this.entity.transform.rotation); - this._transformMatrix = this._transformMatrix.multiply(tempMat); - } - - tempMat = Matrix2D.create().translate(this._origin.x, this._origin.y); - this._transformMatrix =this._transformMatrix.multiply(tempMat); - - this._inverseTransformMatrix = this._transformMatrix.invert(); - - // 无论何时矩阵改变边界都是无效的 - this._areBoundsDirty = true; - this._areMatrixedDirty = false; - } - /** * 设置用于从视口边缘插入摄像机边界的量 * @param left @@ -357,7 +334,7 @@ module es { * 将一个点从世界坐标转换到屏幕 * @param worldPosition */ - public worldToScreenPoint(worldPosition: Vector2): Vector2{ + public worldToScreenPoint(worldPosition: Vector2): Vector2 { this.updateMatrixes(); worldPosition = Vector2.transform(worldPosition, this._transformMatrix); return worldPosition; @@ -367,7 +344,7 @@ module es { * 将点从屏幕坐标转换为世界坐标 * @param screenPosition */ - public screenToWorldPoint(screenPosition: Vector2): Vector2{ + public screenToWorldPoint(screenPosition: Vector2): Vector2 { this.updateMatrixes(); screenPosition = Vector2.transform(screenPosition, this._inverseTransformMatrix); return screenPosition; @@ -376,7 +353,7 @@ module es { /** * 返回鼠标在世界空间中的位置 */ - public mouseToWorldPoint(): Vector2{ + public mouseToWorldPoint(): Vector2 { return this.screenToWorldPoint(Input.touchPosition); } @@ -476,5 +453,32 @@ module es { public setCenteredDeadzone(width: number, height: number) { this.deadzone = new Rectangle((this.bounds.width - width) / 2, (this.bounds.height - height) / 2, width, height); } + + protected updateMatrixes() { + if (!this._areMatrixedDirty) + return; + + let tempMat: Matrix2D; + this._transformMatrix = Matrix2D.create().translate(-this.entity.transform.position.x, -this.entity.transform.position.y); + + if (this._zoom != 1) { + tempMat = Matrix2D.create().scale(this._zoom, this._zoom); + this._transformMatrix = this._transformMatrix.multiply(tempMat); + } + + if (this.entity.transform.rotation != 0) { + tempMat = Matrix2D.create().rotate(this.entity.transform.rotation); + this._transformMatrix = this._transformMatrix.multiply(tempMat); + } + + tempMat = Matrix2D.create().translate(this._origin.x, this._origin.y); + this._transformMatrix = this._transformMatrix.multiply(tempMat); + + this._inverseTransformMatrix = this._transformMatrix.invert(); + + // 无论何时矩阵改变边界都是无效的 + this._areBoundsDirty = true; + this._areMatrixedDirty = false; + } } } diff --git a/source/src/ECS/Components/ComponentPool.ts b/source/src/ECS/Components/ComponentPool.ts index bcac36fb..8b52e501 100644 --- a/source/src/ECS/Components/ComponentPool.ts +++ b/source/src/ECS/Components/ComponentPool.ts @@ -1,22 +1,22 @@ module es { - export class ComponentPool{ + export class ComponentPool { private _cache: T[]; private _type: any; - constructor(typeClass: any){ + constructor(typeClass: any) { this._type = typeClass; this._cache = []; } - public obtain(): T{ + public obtain(): T { try { return this._cache.length > 0 ? this._cache.shift() : new this._type(); - } catch(err){ + } catch (err) { throw new Error(this._type + err); } } - public free(component: T){ + public free(component: T) { component.reset(); this._cache.push(component); } diff --git a/source/src/ECS/Components/IUpdatableComparer.ts b/source/src/ECS/Components/IUpdatableComparer.ts index 46a4f90a..48185319 100644 --- a/source/src/ECS/Components/IUpdatableComparer.ts +++ b/source/src/ECS/Components/IUpdatableComparer.ts @@ -3,8 +3,8 @@ module es { * 用于比较组件更新排序 */ export class IUpdatableComparer { - public compare(a: Component, b: Component){ - return a.updateOrder - b.updateOrder; - } + public compare(a: Component, b: Component) { + return a.updateOrder - b.updateOrder; + } } } \ No newline at end of file diff --git a/source/src/ECS/Components/Mesh.ts b/source/src/ECS/Components/Mesh.ts index 211d50e2..d5bb8bf0 100644 --- a/source/src/ECS/Components/Mesh.ts +++ b/source/src/ECS/Components/Mesh.ts @@ -3,13 +3,13 @@ module es { export class Mesh extends RenderableComponent { private _mesh: egret.Mesh; - constructor(){ + constructor() { super(); this._mesh = new egret.Mesh(); } - public setTexture(texture: egret.Texture): Mesh{ + public setTexture(texture: egret.Texture): Mesh { this._mesh.texture = texture; return this; diff --git a/source/src/ECS/Components/Physics/Colliders/BoxCollider.ts b/source/src/ECS/Components/Physics/Colliders/BoxCollider.ts index 504d59f3..d8433430 100644 --- a/source/src/ECS/Components/Physics/Colliders/BoxCollider.ts +++ b/source/src/ECS/Components/Physics/Colliders/BoxCollider.ts @@ -1,26 +1,10 @@ /// module es { export class BoxCollider extends Collider { - public get width(){ - return (this.shape as Box).width; - } - - public set width(value: number){ - this.setWidth(value); - } - - public get height(){ - return (this.shape as Box).height; - } - - public set height(value: number){ - this.setHeight(value); - } - /** * 零参数构造函数要求RenderableComponent在实体上,这样碰撞器可以在实体被添加到场景时调整自身的大小。 */ - constructor(){ + constructor() { super(); // 我们在这里插入一个1x1框作为占位符,直到碰撞器在下一阵被添加到实体并可以获得更精确的自动调整大小数据 @@ -28,15 +12,31 @@ module es { this._colliderRequiresAutoSizing = true; } + public get width() { + return (this.shape as Box).width; + } + + public set width(value: number) { + this.setWidth(value); + } + + public get height() { + return (this.shape as Box).height; + } + + public set height(value: number) { + this.setHeight(value); + } + /** * 设置BoxCollider的大小 * @param width * @param height */ - public setSize(width: number, height: number){ + public setSize(width: number, height: number) { this._colliderRequiresAutoSizing = false; let box = this.shape as Box; - if (width != box.width || height != box.height){ + if (width != box.width || height != box.height) { // 更新框,改变边界,如果我们需要更新物理系统中的边界 box.updateBox(width, height); if (this.entity && this._isParentEntityAddedToScene) @@ -50,10 +50,10 @@ module es { * 设置BoxCollider的宽度 * @param width */ - public setWidth(width: number): BoxCollider{ + public setWidth(width: number): BoxCollider { this._colliderRequiresAutoSizing = false; let box = this.shape as Box; - if (width != box.width){ + if (width != box.width) { // 更新框,改变边界,如果我们需要更新物理系统中的边界 box.updateBox(width, box.height); if (this.entity && this._isParentEntityAddedToScene) @@ -67,10 +67,10 @@ module es { * 设置BoxCollider的高度 * @param height */ - public setHeight(height: number){ + public setHeight(height: number) { this._colliderRequiresAutoSizing = false; let box = this.shape as Box; - if (height != box.height){ + if (height != box.height) { // 更新框,改变边界,如果我们需要更新物理系统中的边界 box.updateBox(box.width, height); if (this.entity && this._isParentEntityAddedToScene) @@ -78,7 +78,7 @@ module es { } } - public toString(){ + public toString() { return `[BoxCollider: bounds: ${this.bounds}]`; } } diff --git a/source/src/ECS/Components/Physics/Colliders/CircleCollider.ts b/source/src/ECS/Components/Physics/Colliders/CircleCollider.ts index 26df381b..3612f6cb 100644 --- a/source/src/ECS/Components/Physics/Colliders/CircleCollider.ts +++ b/source/src/ECS/Components/Physics/Colliders/CircleCollider.ts @@ -1,13 +1,5 @@ module es { export class CircleCollider extends Collider { - public get radius(): number { - return (this.shape as Circle).radius; - } - - public set radius(value: number) { - this.setRadius(value); - } - /** * 创建一个有半径的圆 * @@ -23,6 +15,14 @@ module es { this.shape = new Circle(radius ? radius : 1); } + public get radius(): number { + return (this.shape as Circle).radius; + } + + public set radius(value: number) { + this.setRadius(value); + } + /** * 设置圆的半径 * @param radius diff --git a/source/src/ECS/Components/Physics/Colliders/Collider.ts b/source/src/ECS/Components/Physics/Colliders/Collider.ts index 0f13b2cd..dd53c5c4 100644 --- a/source/src/ECS/Components/Physics/Colliders/Collider.ts +++ b/source/src/ECS/Components/Physics/Colliders/Collider.ts @@ -4,23 +4,40 @@ module es { * 对撞机的基本形状 */ public shape: Shape; - /** - * 将localOffset添加到实体。获取碰撞器几何图形的最终位置。 - * 允许向一个实体添加多个碰撞器并分别定位,还允许你设置缩放/旋转 + * 如果这个碰撞器是一个触发器,它将不会引起碰撞,但它仍然会触发事件 */ - public get localOffset(): Vector2 { - return this._localOffset; - } - + public isTrigger: boolean; /** - * 将localOffset添加到实体。获取碰撞器几何图形的最终位置。 - * 允许向一个实体添加多个碰撞器并分别定位,还允许你设置缩放/旋转 - * @param value + * 在处理冲突时,physicsLayer可以用作过滤器。Flags类有帮助位掩码的方法 */ - public set localOffset(value: Vector2) { - this.setLocalOffset(value); - } + public physicsLayer = 1 << 0; + /** + * 碰撞器在使用移动器移动时应该碰撞的层 + * 默认为所有层 + */ + public collidesWithLayers = Physics.allLayers; + /** + * 如果为true,碰撞器将根据附加的变换缩放和旋转 + */ + public shouldColliderScaleAndRotateWithTransform = true; + /** + * 这个对撞机在物理系统注册时的边界。 + * 存储这个允许我们始终能够安全地从物理系统中移除对撞机,即使它在试图移除它之前已经被移动了。 + */ + public registeredPhysicsBounds: Rectangle = new Rectangle(); + public _localOffsetLength: number; + public _isPositionDirty: boolean = true; + public _isRotationDirty: boolean = true; + protected _colliderRequiresAutoSizing; + /** + * 标记来跟踪我们的实体是否被添加到场景中 + */ + protected _isParentEntityAddedToScene; + /** + * 标记来记录我们是否注册了物理系统 + */ + protected _isColliderRegistered; /** * 镖师碰撞器的绝对位置 @@ -39,27 +56,8 @@ module es { return 0; } - /** - * 如果这个碰撞器是一个触发器,它将不会引起碰撞,但它仍然会触发事件 - */ - public isTrigger: boolean; - /** - * 在处理冲突时,physicsLayer可以用作过滤器。Flags类有帮助位掩码的方法 - */ - public physicsLayer = 1 << 0; - /** - * 碰撞器在使用移动器移动时应该碰撞的层 - * 默认为所有层 - */ - public collidesWithLayers = Physics.allLayers; - - /** - * 如果为true,碰撞器将根据附加的变换缩放和旋转 - */ - public shouldColliderScaleAndRotateWithTransform = true; - public get bounds(): Rectangle { - if (this._isPositionDirty || this._isRotationDirty){ + if (this._isPositionDirty || this._isRotationDirty) { this.shape.recalculateBounds(this); this._isPositionDirty = this._isRotationDirty = false; } @@ -67,26 +65,24 @@ module es { return this.shape.bounds; } - /** - * 这个对撞机在物理系统注册时的边界。 - * 存储这个允许我们始终能够安全地从物理系统中移除对撞机,即使它在试图移除它之前已经被移动了。 - */ - public registeredPhysicsBounds: Rectangle = new Rectangle(); - protected _colliderRequiresAutoSizing; protected _localOffset: Vector2 = Vector2.zero; - public _localOffsetLength: number; /** - * 标记来跟踪我们的实体是否被添加到场景中 + * 将localOffset添加到实体。获取碰撞器几何图形的最终位置。 + * 允许向一个实体添加多个碰撞器并分别定位,还允许你设置缩放/旋转 */ - protected _isParentEntityAddedToScene; - /** - * 标记来记录我们是否注册了物理系统 - */ - protected _isColliderRegistered; + public get localOffset(): Vector2 { + return this._localOffset; + } - public _isPositionDirty: boolean = true; - public _isRotationDirty: boolean = true; + /** + * 将localOffset添加到实体。获取碰撞器几何图形的最终位置。 + * 允许向一个实体添加多个碰撞器并分别定位,还允许你设置缩放/旋转 + * @param value + */ + public set localOffset(value: Vector2) { + this.setLocalOffset(value); + } /** * 将localOffset添加到实体。获取碰撞器的最终位置。 @@ -229,7 +225,7 @@ module es { return didCollide; } - public clone(): Component{ + public clone(): Component { let collider = ObjectUtils.clone(this); collider.entity = null; diff --git a/source/src/ECS/Components/Physics/ITriggerListener.ts b/source/src/ECS/Components/Physics/ITriggerListener.ts index dd7e2ff0..d7585ef3 100644 --- a/source/src/ECS/Components/Physics/ITriggerListener.ts +++ b/source/src/ECS/Components/Physics/ITriggerListener.ts @@ -1,4 +1,4 @@ -module es{ +module es { /** * 当添加到组件时,每当实体上的冲突器与另一个组件重叠/退出时,将调用这些方法。 * ITriggerListener方法将在实现接口的触发器实体上的任何组件上调用。 diff --git a/source/src/ECS/Components/Physics/Mover.ts b/source/src/ECS/Components/Physics/Mover.ts index 85461ecb..a13c1132 100644 --- a/source/src/ECS/Components/Physics/Mover.ts +++ b/source/src/ECS/Components/Physics/Mover.ts @@ -9,7 +9,7 @@ module es { export class Mover extends Component { private _triggerHelper: ColliderTriggerHelper; - public onAddedToEntity(){ + public onAddedToEntity() { this._triggerHelper = new ColliderTriggerHelper(this.entity); } @@ -18,14 +18,14 @@ module es { * @param motion * @param collisionResult */ - public calculateMovement(motion: Vector2, collisionResult: CollisionResult): boolean{ - if (!this.entity.getComponent(Collider) || !this._triggerHelper){ + public calculateMovement(motion: Vector2, collisionResult: CollisionResult): boolean { + if (!this.entity.getComponent(Collider) || !this._triggerHelper) { return false; } // 移动所有的非触发碰撞器并获得最近的碰撞 let colliders: Collider[] = this.entity.getComponents(Collider); - for (let i = 0; i < colliders.length; i ++){ + for (let i = 0; i < colliders.length; i++) { let collider = colliders[i]; // 不检测触发器 在我们移动后会重新访问它 @@ -38,19 +38,19 @@ module es { bounds.y += motion.y; let neighbors = Physics.boxcastBroadphaseExcludingSelf(collider, bounds, collider.collidesWithLayers); - for (let j = 0; j < neighbors.length; j ++){ + for (let j = 0; j < neighbors.length; j++) { let neighbor = neighbors[j]; // 不检测触发器 if (neighbor.isTrigger) continue; let _internalcollisionResult: CollisionResult = new CollisionResult(); - if (collider.collidesWith(neighbor, motion, _internalcollisionResult)){ + if (collider.collidesWith(neighbor, motion, _internalcollisionResult)) { // 如果碰撞 则退回之前的移动量 motion = motion.subtract(_internalcollisionResult.minimumTranslationVector); // 如果我们碰到多个对象,为了简单起见,只取第一个。 - if (_internalcollisionResult.collider != null){ + if (_internalcollisionResult.collider != null) { collisionResult = _internalcollisionResult; } } @@ -66,7 +66,7 @@ module es { * 将calculatemomovement应用到实体并更新triggerHelper * @param motion */ - public applyMovement(motion: Vector2){ + public applyMovement(motion: Vector2) { // 移动实体到它的新位置,如果我们有一个碰撞,否则移动全部数量。当碰撞发生时,运动被更新 this.entity.position = Vector2.add(this.entity.position, motion); @@ -80,7 +80,7 @@ module es { * @param motion * @param collisionResult */ - public move(motion: Vector2, collisionResult: CollisionResult){ + public move(motion: Vector2, collisionResult: CollisionResult) { this.calculateMovement(motion, collisionResult); this.applyMovement(motion); return collisionResult.collider != null; diff --git a/source/src/ECS/Components/Physics/ProjectileMover.ts b/source/src/ECS/Components/Physics/ProjectileMover.ts index bf018140..a12d4e87 100644 --- a/source/src/ECS/Components/Physics/ProjectileMover.ts +++ b/source/src/ECS/Components/Physics/ProjectileMover.ts @@ -7,7 +7,7 @@ module es { private _tempTriggerList: ITriggerListener[] = []; private _collider: Collider; - public onAddedToEntity(){ + public onAddedToEntity() { this._collider = this.entity.getComponent(Collider); if (!this._collider) console.warn("ProjectileMover has no Collider. ProjectilMover requires a Collider!"); @@ -17,7 +17,7 @@ module es { * 移动考虑碰撞的实体 * @param motion */ - public move(motion: Vector2): boolean{ + public move(motion: Vector2): boolean { if (!this._collider) return false; @@ -28,9 +28,9 @@ module es { // 获取任何可能在新位置发生碰撞的东西 let neighbors = Physics.boxcastBroadphase(this._collider.bounds, this._collider.collidesWithLayers); - for (let i = 0; i < neighbors.length; i ++){ + for (let i = 0; i < neighbors.length; i++) { let neighbor = neighbors[i]; - if (this._collider.overlaps(neighbor) && neighbor.enabled){ + if (this._collider.overlaps(neighbor) && neighbor.enabled) { didCollide = true; this.notifyTriggerListeners(this._collider, neighbor); } @@ -39,17 +39,17 @@ module es { return didCollide; } - private notifyTriggerListeners(self: Collider, other: Collider){ + private notifyTriggerListeners(self: Collider, other: Collider) { // 通知我们重叠的碰撞器实体上的任何侦听器 other.entity.getComponents("ITriggerListener", this._tempTriggerList); - for (let i = 0; i < this._tempTriggerList.length; i ++){ + for (let i = 0; i < this._tempTriggerList.length; i++) { this._tempTriggerList[i].onTriggerEnter(self, other); } this._tempTriggerList.length = 0; // 通知此实体上的任何侦听器 this.entity.getComponents("ITriggerListener", this._tempTriggerList); - for (let i = 0; i < this._tempTriggerList.length; i ++){ + for (let i = 0; i < this._tempTriggerList.length; i++) { this._tempTriggerList[i].onTriggerEnter(other, self); } this._tempTriggerList.length = 0; diff --git a/source/src/ECS/Components/RenderableComponent.ts b/source/src/ECS/Components/RenderableComponent.ts index 64190f85..689539d2 100644 --- a/source/src/ECS/Components/RenderableComponent.ts +++ b/source/src/ECS/Components/RenderableComponent.ts @@ -8,6 +8,12 @@ module es { * 用于装载egret显示对象 */ public displayObject: egret.DisplayObject = new egret.DisplayObject(); + /** + * 用于着色器处理精灵 + */ + public color: number = 0x000000; + protected _areBoundsDirty = true; + /** * renderableComponent的宽度 * 如果你不重写bounds属性则需要实现这个 @@ -24,11 +30,43 @@ module es { return this.bounds.height; } + protected _localOffset: Vector2 = Vector2.zero; + + /** + * 从父实体的偏移量。用于向需要特定定位的实体 + */ + public get localOffset(): Vector2 { + return this._localOffset; + } + + /** + * 从父实体的偏移量。用于向需要特定定位的实体 + * @param value + */ + public set localOffset(value: Vector2) { + this.setLocalOffset(value); + } + + protected _renderLayer: number = 0; + + /** + * 较低的渲染层在前面,较高的在后面 + */ + public get renderLayer(): number { + return this._renderLayer; + } + + public set renderLayer(value: number) { + + } + + protected _bounds: Rectangle = new Rectangle(); + /** * 这个物体的AABB, 用于相机剔除 */ public get bounds(): Rectangle { - if (this._areBoundsDirty){ + if (this._areBoundsDirty) { this._bounds.calculateBounds(this.entity.transform.position, this._localOffset, Vector2.zero, this.entity.transform.scale, this.entity.transform.rotation, this.width, this.height); this._areBoundsDirty = false; @@ -37,36 +75,7 @@ module es { return this._bounds; } - /** - * 较低的渲染层在前面,较高的在后面 - */ - public get renderLayer(): number{ - return this._renderLayer; - } - - public set renderLayer(value: number){ - - } - - /** - * 用于着色器处理精灵 - */ - public color: number = 0x000000; - - /** - * 从父实体的偏移量。用于向需要特定定位的实体 - */ - public get localOffset(): Vector2{ - return this._localOffset; - } - - /** - * 从父实体的偏移量。用于向需要特定定位的实体 - * @param value - */ - public set localOffset(value: Vector2){ - this.setLocalOffset(value); - } + private _isVisible: boolean; /** * 可渲染的可见性。状态的改变会调用onBecameVisible/onBecameInvisible方法 @@ -80,7 +89,7 @@ module es { * @param value */ public set isVisible(value: boolean) { - if (this._isVisible != value){ + if (this._isVisible != value) { this._isVisible = value; if (this._isVisible) @@ -90,12 +99,6 @@ module es { } } - protected _localOffset: Vector2 = Vector2.zero; - protected _renderLayer: number = 0; - protected _bounds: Rectangle = new Rectangle(); - private _isVisible: boolean; - protected _areBoundsDirty = true; - public onEntityTransformChanged(comp: transform.Component) { this._areBoundsDirty = true; } @@ -106,22 +109,6 @@ module es { */ public abstract render(camera: Camera); - /** - * 当renderableComponent进入相机框架时调用 - * 如果渲染器不适用isVisibleFromCamera进行剔除检查 这些方法不会被调用 - */ - protected onBecameVisible() { - this.displayObject.visible = this.isVisible; - } - - /** - * 当renderableComponent离开相机框架时调用 - * 如果渲染器不适用isVisibleFromCamera进行剔除检查 这些方法不会被调用 - */ - protected onBecameInvisible() { - this.displayObject.visible = this.isVisible; - } - /** * 如果renderableComponent的边界与camera.bounds相交 返回true * 用于处理isVisible标志的状态开关 @@ -137,8 +124,8 @@ module es { * 较低的渲染层在前面,较高的在后面 * @param renderLayer */ - public setRenderLayer(renderLayer: number): RenderableComponent{ - if (renderLayer != this._renderLayer){ + public setRenderLayer(renderLayer: number): RenderableComponent { + if (renderLayer != this._renderLayer) { let oldRenderLayer = this._renderLayer; this._renderLayer = renderLayer; @@ -154,7 +141,7 @@ module es { * 用于着色器处理精灵 * @param color */ - public setColor(color: number): RenderableComponent{ + public setColor(color: number): RenderableComponent { this.color = color; return this; } @@ -163,8 +150,8 @@ module es { * 从父实体的偏移量。用于向需要特定定位的实体 * @param offset */ - public setLocalOffset(offset: Vector2): RenderableComponent{ - if (this._localOffset != offset){ + public setLocalOffset(offset: Vector2): RenderableComponent { + if (this._localOffset != offset) { this._localOffset = offset; } @@ -174,7 +161,7 @@ module es { /** * 进行状态同步 */ - public sync(camera: Camera){ + public sync(camera: Camera) { this.displayObject.x = this.entity.position.x + this.localOffset.x - camera.position.x + camera.origin.x; this.displayObject.y = this.entity.position.y + this.localOffset.y - camera.position.y + camera.origin.y; this.displayObject.scaleX = this.entity.scale.x; @@ -182,8 +169,24 @@ module es { this.displayObject.rotation = this.entity.rotation; } - public toString(){ + public toString() { return `[RenderableComponent] renderLayer: ${this.renderLayer}`; } + + /** + * 当renderableComponent进入相机框架时调用 + * 如果渲染器不适用isVisibleFromCamera进行剔除检查 这些方法不会被调用 + */ + protected onBecameVisible() { + this.displayObject.visible = this.isVisible; + } + + /** + * 当renderableComponent离开相机框架时调用 + * 如果渲染器不适用isVisibleFromCamera进行剔除检查 这些方法不会被调用 + */ + protected onBecameInvisible() { + this.displayObject.visible = this.isVisible; + } } } \ No newline at end of file diff --git a/source/src/ECS/Components/ScrollingSpriteRenderer.ts b/source/src/ECS/Components/ScrollingSpriteRenderer.ts index 9b8e38d2..5e0a069e 100644 --- a/source/src/ECS/Components/ScrollingSpriteRenderer.ts +++ b/source/src/ECS/Components/ScrollingSpriteRenderer.ts @@ -6,7 +6,7 @@ module es { private _scrollX = 0; private _scrollY = 0; - public update(){ + public update() { this._scrollX += this.scrollSpeedX * Time.deltaTime; this._scrollY += this.scroolSpeedY * Time.deltaTime; this.sourceRect.x = this._scrollX; diff --git a/source/src/ECS/Components/SpriteAnimation.ts b/source/src/ECS/Components/SpriteAnimation.ts index 77e33923..b5f81b75 100644 --- a/source/src/ECS/Components/SpriteAnimation.ts +++ b/source/src/ECS/Components/SpriteAnimation.ts @@ -3,7 +3,7 @@ module es { public readonly sprites: Sprite[]; public readonly frameRate: number; - constructor(sprites: Sprite[], frameRate: number){ + constructor(sprites: Sprite[], frameRate: number) { this.sprites = sprites; this.frameRate = frameRate; } diff --git a/source/src/ECS/Components/SpriteAnimator.ts b/source/src/ECS/Components/SpriteAnimator.ts index f4b6af29..6d649bf6 100644 --- a/source/src/ECS/Components/SpriteAnimator.ts +++ b/source/src/ECS/Components/SpriteAnimator.ts @@ -45,6 +45,12 @@ module es { * 当前动画的精灵数组中当前帧的索引 */ public currentFrame: number; + public _elapsedTime: number = 0; + public _loopMode: LoopMode; + + constructor(sprite?: Sprite) { + super(sprite); + } /** * 检查当前动画是否正在运行 @@ -53,19 +59,13 @@ module es { return this.animationState == State.running; } + private _animations: Map = new Map(); + /** 提供对可用动画列表的访问 */ public get animations() { return this._animations; } - private _animations: Map = new Map(); - public _elapsedTime: number = 0; - public _loopMode: LoopMode; - - constructor(sprite?: Sprite) { - super(sprite); - } - public update() { if (this.animationState != State.running || !this.currentAnimation) return; diff --git a/source/src/ECS/Components/SpriteRenderer.ts b/source/src/ECS/Components/SpriteRenderer.ts index baea0be7..30d37dd2 100644 --- a/source/src/ECS/Components/SpriteRenderer.ts +++ b/source/src/ECS/Components/SpriteRenderer.ts @@ -2,6 +2,14 @@ module es { import Bitmap = egret.Bitmap; export class SpriteRenderer extends RenderableComponent { + constructor(sprite: Sprite | egret.Texture = null) { + super(); + if (sprite instanceof Sprite) + this.setSprite(sprite); + else if (sprite instanceof egret.Texture) + this.setSprite(new Sprite(sprite)); + } + public get bounds() { if (this._areBoundsDirty) { if (this._sprite) { @@ -15,21 +23,6 @@ module es { return this._bounds; } - /** - * 精灵的原点。这是在设置精灵时自动设置的 - */ - public get origin(): Vector2 { - return this._origin; - } - - /** - * 精灵的原点。这是在设置精灵时自动设置的 - * @param value - */ - public set origin(value: Vector2) { - this.setOrigin(value); - } - /** * 用归一化方法设置原点 * x/y 均为 0-1 @@ -49,6 +42,25 @@ module es { value.y * this.height / this.entity.transform.scale.y)); } + protected _origin: Vector2; + + /** + * 精灵的原点。这是在设置精灵时自动设置的 + */ + public get origin(): Vector2 { + return this._origin; + } + + /** + * 精灵的原点。这是在设置精灵时自动设置的 + * @param value + */ + public set origin(value: Vector2) { + this.setOrigin(value); + } + + protected _sprite: Sprite; + /** * 应该由这个精灵显示的精灵 * 当设置时,精灵的原点也被设置为精灵的origin @@ -66,17 +78,6 @@ module es { this.setSprite(value); } - protected _origin: Vector2; - protected _sprite: Sprite; - - constructor(sprite: Sprite | egret.Texture = null) { - super(); - if (sprite instanceof Sprite) - this.setSprite(sprite); - else if (sprite instanceof egret.Texture) - this.setSprite(new Sprite(sprite)); - } - /** * 设置精灵并更新精灵的原点以匹配sprite.origin * @param sprite diff --git a/source/src/ECS/Components/TiledSpriteRenderer.ts b/source/src/ECS/Components/TiledSpriteRenderer.ts index a9316e09..710246e8 100644 --- a/source/src/ECS/Components/TiledSpriteRenderer.ts +++ b/source/src/ECS/Components/TiledSpriteRenderer.ts @@ -8,19 +8,6 @@ module es { protected leftTexture: egret.Bitmap; protected rightTexture: egret.Bitmap; - public get scrollX() { - return this.sourceRect.x; - } - public set scrollX(value: number) { - this.sourceRect.x = value; - } - public get scrollY() { - return this.sourceRect.y; - } - public set scrollY(value: number) { - this.sourceRect.y = value; - } - constructor(sprite: Sprite) { super(sprite); @@ -33,6 +20,22 @@ module es { this.sourceRect = sprite.sourceRect; } + public get scrollX() { + return this.sourceRect.x; + } + + public set scrollX(value: number) { + this.sourceRect.x = value; + } + + public get scrollY() { + return this.sourceRect.y; + } + + public set scrollY(value: number) { + this.sourceRect.y = value; + } + public render(camera: es.Camera) { if (!this.sprite) return; diff --git a/source/src/ECS/Core.ts b/source/src/ECS/Core.ts index 30ba1554..2e07ea4f 100644 --- a/source/src/ECS/Core.ts +++ b/source/src/ECS/Core.ts @@ -15,20 +15,10 @@ module es { * 全局内容管理器加载任何应该停留在场景之间的资产 */ public static content: ContentManager; - - /** - * 提供对单例/游戏实例的访问 - * @constructor - */ - public static get Instance(){ - return this._instance; - } - /** * 简化对内部类的全局内容实例的访问 */ public static _instance: Core; - public _scene: Scene; public _nextScene: Scene; public _sceneTransition: SceneTransition; /** @@ -36,6 +26,26 @@ module es { */ public _globalManagers: GlobalManager[] = []; + constructor() { + super(); + + Core._instance = this; + Core.emitter = new Emitter(); + Core.content = new ContentManager(); + + this.addEventListener(egret.Event.ADDED_TO_STAGE, this.onAddToStage, this); + } + + /** + * 提供对单例/游戏实例的访问 + * @constructor + */ + public static get Instance() { + return this._instance; + } + + public _scene: Scene; + /** * 当前活动的场景。注意,如果设置了该设置,在更新结束之前场景实际上不会改变 */ @@ -50,7 +60,7 @@ module es { * @param value */ public static set scene(value: Scene) { - if (!value){ + if (!value) { console.error("场景不能为空"); return; } @@ -65,39 +75,106 @@ module es { } } - constructor() { - super(); + /** + * 临时运行SceneTransition,允许一个场景过渡到另一个平滑的自定义效果。 + * @param sceneTransition + */ + public static startSceneTransition(sceneTransition: T): T { + if (this._instance._sceneTransition) { + console.warn("在前一个场景完成之前,不能开始一个新的场景转换。"); + return; + } - Core._instance = this; - Core.emitter = new Emitter(); - Core.content = new ContentManager(); - - this.addEventListener(egret.Event.ADDED_TO_STAGE, this.onAddToStage, this); + this._instance._sceneTransition = sceneTransition; + return sceneTransition; } - private onAddToStage(){ - Core.graphicsDevice = new GraphicsDevice(); - - this.addEventListener(egret.Event.RESIZE, this.onGraphicsDeviceReset, this); - this.addEventListener(egret.StageOrientationEvent.ORIENTATION_CHANGE, this.onOrientationChanged, this); - this.addEventListener(egret.Event.ENTER_FRAME, this.update, this); - - Input.initialize(); - this.initialize(); + /** + * 添加一个全局管理器对象,它的更新方法将调用场景前的每一帧。 + * @param manager + */ + public static registerGlobalManager(manager: es.GlobalManager) { + this._instance._globalManagers.push(manager); + manager.enabled = true; } - public onOrientationChanged(){ + /** + * 删除全局管理器对象 + * @param manager + */ + public static unregisterGlobalManager(manager: es.GlobalManager) { + this._instance._globalManagers.remove(manager); + manager.enabled = false; + } + + /** + * 获取类型为T的全局管理器 + * @param type + */ + public static getGlobalManager(type): T { + for (let i = 0; i < this._instance._globalManagers.length; i++) { + if (this._instance._globalManagers[i] instanceof type) + return this._instance._globalManagers[i] as T; + } + return null; + } + + public onOrientationChanged() { Core.emitter.emit(CoreEvents.OrientationChanged); } + public async draw() { + if (this._sceneTransition) { + this._sceneTransition.preRender(); + + // 如果我们有场景转换的特殊处理。我们要么渲染场景过渡,要么渲染场景 + if (this._scene && !this._sceneTransition.hasPreviousSceneRender) { + this._scene.render(); + this._scene.postRender(); + await this._sceneTransition.onBeginTransition(); + } else if (this._sceneTransition) { + if (this._scene && this._sceneTransition.isNewSceneLoaded) { + this._scene.render(); + this._scene.postRender(); + } + + this._sceneTransition.render(); + } + } else if (this._scene) { + this._scene.render(); + + Debug.render(); + + // 如果我们没有一个活跃的场景转换,就像平常一样渲染 + this._scene.postRender(); + } + } + + public startDebugUpdate() { + TimeRuler.Instance.startFrame(); + TimeRuler.Instance.beginMark("update", 0x00FF00); + } + + public endDebugUpdate() { + TimeRuler.Instance.endMark("update"); + } + + /** + * 在一个场景结束后,下一个场景开始之前调用 + */ + public onSceneChanged() { + Core.emitter.emit(CoreEvents.SceneChanged); + Time.sceneChanged(); + } + /** * 当屏幕大小发生改变时调用 */ - protected onGraphicsDeviceReset(){ + protected onGraphicsDeviceReset() { Core.emitter.emit(CoreEvents.GraphicsDeviceReset); } - protected initialize(){ + protected initialize() { } protected async update() { @@ -139,92 +216,15 @@ module es { await this.draw(); } - public async draw() { - if (this._sceneTransition){ - this._sceneTransition.preRender(); + private onAddToStage() { + Core.graphicsDevice = new GraphicsDevice(); - // 如果我们有场景转换的特殊处理。我们要么渲染场景过渡,要么渲染场景 - if (this._scene && !this._sceneTransition.hasPreviousSceneRender){ - this._scene.render(); - this._scene.postRender(); - await this._sceneTransition.onBeginTransition(); - } else if (this._sceneTransition) { - if (this._scene && this._sceneTransition.isNewSceneLoaded) { - this._scene.render(); - this._scene.postRender(); - } + this.addEventListener(egret.Event.RESIZE, this.onGraphicsDeviceReset, this); + this.addEventListener(egret.StageOrientationEvent.ORIENTATION_CHANGE, this.onOrientationChanged, this); + this.addEventListener(egret.Event.ENTER_FRAME, this.update, this); - this._sceneTransition.render(); - } - } else if (this._scene) { - this._scene.render(); - - Debug.render(); - - // 如果我们没有一个活跃的场景转换,就像平常一样渲染 - this._scene.postRender(); - } - } - - public startDebugUpdate(){ - TimeRuler.Instance.startFrame(); - TimeRuler.Instance.beginMark("update", 0x00FF00); - } - - public endDebugUpdate(){ - TimeRuler.Instance.endMark("update"); - } - - /** - * 在一个场景结束后,下一个场景开始之前调用 - */ - public onSceneChanged(){ - Core.emitter.emit(CoreEvents.SceneChanged); - Time.sceneChanged(); - } - - /** - * 临时运行SceneTransition,允许一个场景过渡到另一个平滑的自定义效果。 - * @param sceneTransition - */ - public static startSceneTransition(sceneTransition: T): T { - if (this._instance._sceneTransition) { - console.warn("在前一个场景完成之前,不能开始一个新的场景转换。"); - return; - } - - this._instance._sceneTransition = sceneTransition; - return sceneTransition; - } - - /** - * 添加一个全局管理器对象,它的更新方法将调用场景前的每一帧。 - * @param manager - */ - public static registerGlobalManager(manager: es.GlobalManager){ - this._instance._globalManagers.push(manager); - manager.enabled = true; - } - - /** - * 删除全局管理器对象 - * @param manager - */ - public static unregisterGlobalManager(manager: es.GlobalManager){ - this._instance._globalManagers.remove(manager); - manager.enabled = false; - } - - /** - * 获取类型为T的全局管理器 - * @param type - */ - public static getGlobalManager(type): T { - for (let i = 0; i < this._instance._globalManagers.length; i ++){ - if (this._instance._globalManagers[i] instanceof type) - return this._instance._globalManagers[i] as T; - } - return null; + Input.initialize(); + this.initialize(); } } } diff --git a/source/src/ECS/CoreEvents.ts b/source/src/ECS/CoreEvents.ts index 72581adc..074469e9 100644 --- a/source/src/ECS/CoreEvents.ts +++ b/source/src/ECS/CoreEvents.ts @@ -1,5 +1,5 @@ module es { - export enum CoreEvents{ + export enum CoreEvents { /** * 在图形设备重置时触发。当这种情况发生时,任何渲染目标或其他内容的VRAM将被擦除,需要重新生成 */ diff --git a/source/src/ECS/Entity.ts b/source/src/ECS/Entity.ts index 527e0a2d..8ba689ac 100644 --- a/source/src/ECS/Entity.ts +++ b/source/src/ECS/Entity.ts @@ -22,6 +22,31 @@ module es { * 当前附加到此实体的所有组件的列表 */ public readonly components: ComponentList; + /** + * 指定应该调用这个entity update方法的频率。1表示每一帧,2表示每一帧,以此类推 + */ + public updateInterval: number = 1; + public componentBits: BitSet; + + constructor(name: string) { + this.components = new ComponentList(this); + this.transform = new Transform(this); + this.name = name; + this.id = Entity._idGenerator++; + + this.componentBits = new BitSet(); + } + + public _isDestroyed: boolean; + + /** + * 如果调用了destroy,那么在下一次处理实体之前这将一直为true + */ + public get isDestroyed() { + return this._isDestroyed; + } + + private _tag: number = 0; /** * 你可以随意使用。稍后可以使用它来查询场景中具有特定标记的所有实体 @@ -38,10 +63,7 @@ module es { this.setTag(value); } - /** - * 指定应该调用这个entity update方法的频率。1表示每一帧,2表示每一帧,以此类推 - */ - public updateInterval: number = 1; + private _enabled: boolean = true; /** * 启用/禁用实体。当禁用碰撞器从物理系统和组件中移除时,方法将不会被调用 @@ -58,6 +80,8 @@ module es { this.setEnabled(value); } + private _updateOrder: number = 0; + /** * 更新此实体的顺序。updateOrder还用于对scene.entities上的标签列表进行排序 */ @@ -73,20 +97,6 @@ module es { this.setUpdateOrder(value); } - public _isDestroyed: boolean; - /** - * 如果调用了destroy,那么在下一次处理实体之前这将一直为true - */ - public get isDestroyed() { - return this._isDestroyed; - } - - public componentBits: BitSet; - - private _tag: number = 0; - private _enabled: boolean = true; - private _updateOrder: number = 0; - public get parent(): Transform { return this.transform.parent; } @@ -111,7 +121,7 @@ module es { return this.transform.localPosition; } - public set localPosition(value: Vector2){ + public set localPosition(value: Vector2) { this.transform.setLocalPosition(value); } @@ -127,7 +137,7 @@ module es { return this.transform.rotationDegrees; } - public set rotationDegrees(value: number){ + public set rotationDegrees(value: number) { this.transform.setRotationDegrees(value); } @@ -135,7 +145,7 @@ module es { return this.transform.localRotation; } - public set localRotation(value: number){ + public set localRotation(value: number) { this.transform.setLocalRotation(value); } @@ -143,7 +153,7 @@ module es { return this.transform.localRotationDegrees; } - public set localRotationDegrees(value: number){ + public set localRotationDegrees(value: number) { this.transform.setLocalRotationDegrees(value); } @@ -159,7 +169,7 @@ module es { return this.transform.localScale; } - public set localScale(value: Vector2){ + public set localScale(value: Vector2) { this.transform.setLocalScale(value); } @@ -175,15 +185,6 @@ module es { return this.transform.worldToLocalTransform; } - constructor(name: string) { - this.components = new ComponentList(this); - this.transform = new Transform(this); - this.name = name; - this.id = Entity._idGenerator++; - - this.componentBits = new BitSet(); - } - public onTransformChanged(comp: transform.Component) { // 通知我们的子项改变了位置 this.components.onEntityTransformChanged(comp); @@ -293,32 +294,6 @@ module es { return entity; } - /** - * 将实体的属性、组件和碰撞器复制到此实例 - * @param entity - */ - protected copyFrom(entity: Entity) { - this.tag = entity.tag; - this.updateInterval = entity.updateInterval; - this.updateOrder = entity.updateOrder; - this.enabled = entity.enabled; - - this.transform.scale = entity.transform.scale; - this.transform.rotation = entity.transform.rotation; - - for (let i = 0; i < entity.components.count; i++) - this.addComponent(entity.components.buffer[i].clone()); - for (let i = 0; i < entity.components._componentsToAdd.length; i++) - this.addComponent(entity.components._componentsToAdd[i].clone()); - - for (let i = 0; i < entity.transform.childCount; i++) { - let child = entity.transform.getChild(i).entity; - let childClone = child.clone(); - childClone.transform.copyFrom(child.transform); - childClone.transform.parent = this.transform; - } - } - /** * 在提交了所有挂起的实体更改后,将此实体添加到场景时调用 */ @@ -431,5 +406,31 @@ module es { public toString(): string { return `[Entity: name: ${this.name}, tag: ${this.tag}, enabled: ${this.enabled}, depth: ${this.updateOrder}]`; } + + /** + * 将实体的属性、组件和碰撞器复制到此实例 + * @param entity + */ + protected copyFrom(entity: Entity) { + this.tag = entity.tag; + this.updateInterval = entity.updateInterval; + this.updateOrder = entity.updateOrder; + this.enabled = entity.enabled; + + this.transform.scale = entity.transform.scale; + this.transform.rotation = entity.transform.rotation; + + for (let i = 0; i < entity.components.count; i++) + this.addComponent(entity.components.buffer[i].clone()); + for (let i = 0; i < entity.components._componentsToAdd.length; i++) + this.addComponent(entity.components._componentsToAdd[i].clone()); + + for (let i = 0; i < entity.transform.childCount; i++) { + let child = entity.transform.getChild(i).entity; + let childClone = child.clone(); + childClone.transform.copyFrom(child.transform); + childClone.transform.parent = this.transform; + } + } } } diff --git a/source/src/ECS/Scene.ts b/source/src/ECS/Scene.ts index 16359e42..63ce0c9d 100644 --- a/source/src/ECS/Scene.ts +++ b/source/src/ECS/Scene.ts @@ -1,350 +1,355 @@ module es { - /** 场景 */ - export class Scene extends egret.DisplayObjectContainer { - /** - * 默认场景摄像机 - */ - public camera: Camera; - /** - * 场景特定内容管理器。使用它来加载仅由这个场景需要的任何资源。如果你有全局/多场景资源,你可以使用SceneManager.content。 - * contentManager来加载它们,因为Nez不会卸载它们。 - */ - public readonly content: ContentManager; - /** - * 全局切换后处理器 - */ - public enablePostProcessing = true; - /** - * 这个场景中的实体列表 - */ - public readonly entities: EntityList; - /** - * 管理当前在场景实体上的所有可呈现组件的列表 - */ - public readonly renderableComponents: RenderableComponentList; - /** - * 管理所有实体处理器 - */ - public readonly entityProcessors: EntityProcessorList; + /** 场景 */ + export class Scene extends egret.DisplayObjectContainer { + /** + * 默认场景摄像机 + */ + public camera: Camera; + /** + * 场景特定内容管理器。使用它来加载仅由这个场景需要的任何资源。如果你有全局/多场景资源,你可以使用SceneManager.content。 + * contentManager来加载它们,因为Nez不会卸载它们。 + */ + public readonly content: ContentManager; + /** + * 全局切换后处理器 + */ + public enablePostProcessing = true; + /** + * 这个场景中的实体列表 + */ + public readonly entities: EntityList; + /** + * 管理当前在场景实体上的所有可呈现组件的列表 + */ + public readonly renderableComponents: RenderableComponentList; + /** + * 管理所有实体处理器 + */ + public readonly entityProcessors: EntityProcessorList; - public _renderers: Renderer[] = []; - public readonly _postProcessors: PostProcessor[] = []; - public _didSceneBegin; + public _renderers: Renderer[] = []; + public readonly _postProcessors: PostProcessor[] = []; + public _didSceneBegin; - /** - * 辅助器,创建一个场景与DefaultRenderer附加并准备使用 - */ - public static createWithDefaultRenderer(){ - let scene = new Scene(); - scene.addRenderer(new DefaultRenderer()); - return scene; - } + constructor() { + super(); + this.entities = new EntityList(this); + this.renderableComponents = new RenderableComponentList(); + this.content = new ContentManager(); - constructor() { - super(); - this.entities = new EntityList(this); - this.renderableComponents = new RenderableComponentList(); - this.content = new ContentManager(); + this.entityProcessors = new EntityProcessorList(); - this.entityProcessors = new EntityProcessorList(); + this.initialize(); + } - this.initialize(); - } + /** + * 辅助器,创建一个场景与DefaultRenderer附加并准备使用 + */ + public static createWithDefaultRenderer() { + let scene = new Scene(); + scene.addRenderer(new DefaultRenderer()); + return scene; + } - /** - * 在场景子类中重写这个并在这里进行加载。在场景设置好之后,在调用begin之前,从构造器中调用。 - */ - public initialize(){} + /** + * 在场景子类中重写这个并在这里进行加载。在场景设置好之后,在调用begin之前,从构造器中调用。 + */ + public initialize() { + } - /** - * 在场景子类中重写这个。当SceneManager将此场景设置为活动场景时,将调用此操作。 - */ - public async onStart() {} + /** + * 在场景子类中重写这个。当SceneManager将此场景设置为活动场景时,将调用此操作。 + */ + public async onStart() { + } - /** - * 在场景子类中重写这个,并在这里做任何必要的卸载。当SceneManager从活动槽中删除此场景时调用。 - */ - public unload() { } + /** + * 在场景子类中重写这个,并在这里做任何必要的卸载。当SceneManager从活动槽中删除此场景时调用。 + */ + public unload() { + } - /** - * 在场景子类中重写这个,当该场景当获得焦点时调用 - */ - public onActive() {} + /** + * 在场景子类中重写这个,当该场景当获得焦点时调用 + */ + public onActive() { + } - /** - * 在场景子类中重写这个,当该场景当失去焦点时调用 - */ - public onDeactive() {} + /** + * 在场景子类中重写这个,当该场景当失去焦点时调用 + */ + public onDeactive() { + } - public async begin() { - if (this._renderers.length == 0) { - this.addRenderer(new DefaultRenderer()); - console.warn("场景开始时没有渲染器 自动添加DefaultRenderer以保证能够正常渲染"); - } - - this.camera = this.createEntity("camera").getOrCreateComponent(new Camera()); - - Physics.reset(); - - if (this.entityProcessors) - this.entityProcessors.begin(); - - this.addEventListener(egret.Event.ACTIVATE, this.onActive, this); - this.addEventListener(egret.Event.DEACTIVATE, this.onDeactive, this); - this.camera.onSceneSizeChanged(this.stage.stageWidth, this.stage.stageHeight); - - this._didSceneBegin = true; - this.onStart(); - } - - public end() { - this._didSceneBegin = false; - - this.removeEventListener(egret.Event.DEACTIVATE, this.onDeactive, this); - this.removeEventListener(egret.Event.ACTIVATE, this.onActive, this); - - for (let i = 0; i < this._renderers.length; i++) { - this._renderers[i].unload(); - } - - for (let i = 0; i < this._postProcessors.length; i++) { - this._postProcessors[i].unload(); - } - - this.entities.removeAllEntities(); - this.removeChildren(); - - this.camera = null; - this.content.dispose(); - - if (this.entityProcessors) - this.entityProcessors.end(); - - if (this.parent) - this.parent.removeChild(this); - - this.unload(); - } - - public update() { - // 更新我们的列表,以防它们有任何变化 - this.entities.updateLists(); - - // 更新我们的实体解析器 - if (this.entityProcessors) - this.entityProcessors.update(); - - // 更新我们的实体组 - this.entities.update(); - - if (this.entityProcessors) - this.entityProcessors.lateUpdate(); - - // 我们在实体之后更新我们的呈现。如果添加了任何新的渲染,请进行更新 - this.renderableComponents.updateList(); - } - - public render() { - if (this._renderers.length == 0){ - console.error("there are no renderers in the scene!"); - return; - } - - for (let i = 0; i < this._renderers.length; i++) { - this._renderers[i].render(this); - } - } - - /** - * 现在的任何后处理器都要完成它的处理 - * 只有在SceneTransition请求渲染时,它才会有一个值。 - */ - public postRender() { - if (this.enablePostProcessing) { - for (let i = 0; i < this._postProcessors.length; i++) { - if (this._postProcessors[i].enabled) { - this._postProcessors[i].process(); - } + public async begin() { + if (this._renderers.length == 0) { + this.addRenderer(new DefaultRenderer()); + console.warn("场景开始时没有渲染器 自动添加DefaultRenderer以保证能够正常渲染"); } - } - } - /** - * 为场景添加一个渲染器 - * @param renderer - */ - public addRenderer(renderer: T) { - this._renderers.push(renderer); - this._renderers.sort(); + this.camera = this.createEntity("camera").getOrCreateComponent(new Camera()); - renderer.onAddedToScene(this); + Physics.reset(); - return renderer; - } + if (this.entityProcessors) + this.entityProcessors.begin(); - /** - * 获取类型为T的第一个渲染器 - * @param type - */ - public getRenderer(type): T { - for (let i = 0; i < this._renderers.length; i++) { - if (this._renderers[i] instanceof type) - return this._renderers[i] as T; - } + this.addEventListener(egret.Event.ACTIVATE, this.onActive, this); + this.addEventListener(egret.Event.DEACTIVATE, this.onDeactive, this); + this.camera.onSceneSizeChanged(this.stage.stageWidth, this.stage.stageHeight); - return null; - } + this._didSceneBegin = true; + this.onStart(); + } - /** - * 从场景中移除渲染器 - * @param renderer - */ - public removeRenderer(renderer: Renderer) { - if (!this._renderers.contains(renderer)) - return; - this._renderers.remove(renderer); - renderer.unload(); - } + public end() { + this._didSceneBegin = false; - /** - * 添加一个后处理器到场景。设置场景字段并调用后处理器。onAddedToScene使后处理器可以使用场景ContentManager加载资源。 - * @param postProcessor - */ - public addPostProcessor(postProcessor: T): T{ - this._postProcessors.push(postProcessor); - this._postProcessors.sort(); - postProcessor.onAddedToScene(this); + this.removeEventListener(egret.Event.DEACTIVATE, this.onDeactive, this); + this.removeEventListener(egret.Event.ACTIVATE, this.onActive, this); - if (this._didSceneBegin){ - postProcessor.onSceneBackBufferSizeChanged(this.stage.stageWidth, this.stage.stageHeight); - } + for (let i = 0; i < this._renderers.length; i++) { + this._renderers[i].unload(); + } - return postProcessor; - } + for (let i = 0; i < this._postProcessors.length; i++) { + this._postProcessors[i].unload(); + } - /** - * 获取类型为T的第一个后处理器 - * @param type - */ - public getPostProcessor(type): T{ - for (let i = 0; i < this._postProcessors.length; i ++){ - if (this._postProcessors[i] instanceof type) - return this._postProcessors[i] as T; - } + this.entities.removeAllEntities(); + this.removeChildren(); - return null; - } + this.camera = null; + this.content.dispose(); - /** - * 删除一个后处理程序。注意,在删除时不会调用unload,因此如果不再需要PostProcessor,请确保调用unload来释放资源。 - * @param postProcessor - */ - public removePostProcessor(postProcessor: PostProcessor){ - if (!this._postProcessors.contains(postProcessor)) - return; + if (this.entityProcessors) + this.entityProcessors.end(); - this._postProcessors.remove(postProcessor); - postProcessor.unload(); - } + if (this.parent) + this.parent.removeChild(this); - /** - * 将实体添加到此场景,并返回它 - * @param name - */ - public createEntity(name: string) { - let entity = new Entity(name); - return this.addEntity(entity); - } + this.unload(); + } - /** - * 在场景的实体列表中添加一个实体 - * @param entity - */ - public addEntity(entity: Entity) { - if (this.entities.buffer.contains(entity)) - console.warn(`You are attempting to add the same entity to a scene twice: ${entity}`); - this.entities.add(entity); - entity.scene = this; + public update() { + // 更新我们的列表,以防它们有任何变化 + this.entities.updateLists(); - for (let i = 0; i < entity.transform.childCount; i++) - this.addEntity(entity.transform.getChild(i).entity); + // 更新我们的实体解析器 + if (this.entityProcessors) + this.entityProcessors.update(); - return entity; - } + // 更新我们的实体组 + this.entities.update(); - /** - * 从场景中删除所有实体 - */ - public destroyAllEntities() { - for (let i = 0; i < this.entities.count; i++) { - this.entities.buffer[i].destroy(); - } - } + if (this.entityProcessors) + this.entityProcessors.lateUpdate(); - /** - * 搜索并返回第一个具有名称的实体 - * @param name - */ - public findEntity(name: string): Entity { - return this.entities.findEntity(name); - } + // 我们在实体之后更新我们的呈现。如果添加了任何新的渲染,请进行更新 + this.renderableComponents.updateList(); + } - /** - * 返回具有给定标记的所有实体 - * @param tag - */ - public findEntitiesWithTag(tag: number): Entity[]{ - return this.entities.entitiesWithTag(tag); - } + public render() { + if (this._renderers.length == 0) { + console.error("there are no renderers in the scene!"); + return; + } - /** - * 返回类型为T的所有实体 - * @param type - */ - public entitiesOfType(type): T[]{ - return this.entities.entitiesOfType(type); - } + for (let i = 0; i < this._renderers.length; i++) { + this._renderers[i].render(this); + } + } - /** - * 返回第一个启用加载的类型为T的组件 - * @param type - */ - public findComponentOfType(type): T { - return this.entities.findComponentOfType(type); - } + /** + * 现在的任何后处理器都要完成它的处理 + * 只有在SceneTransition请求渲染时,它才会有一个值。 + */ + public postRender() { + if (this.enablePostProcessing) { + for (let i = 0; i < this._postProcessors.length; i++) { + if (this._postProcessors[i].enabled) { + this._postProcessors[i].process(); + } + } + } + } - /** - * 返回类型为T的所有已启用已加载组件的列表 - * @param type - */ - public findComponentsOfType(type): T[] { - return this.entities.findComponentsOfType(type); - } + /** + * 为场景添加一个渲染器 + * @param renderer + */ + public addRenderer(renderer: T) { + this._renderers.push(renderer); + this._renderers.sort(); - /** - * 在场景中添加一个EntitySystem处理器 - * @param processor 处理器 - */ - public addEntityProcessor(processor: EntitySystem) { - processor.scene = this; - this.entityProcessors.add(processor); - return processor; - } + renderer.onAddedToScene(this); - /** - * 从场景中删除EntitySystem处理器 - * @param processor - */ - public removeEntityProcessor(processor: EntitySystem) { - this.entityProcessors.remove(processor); - } + return renderer; + } - /** - * 获取EntitySystem处理器 - */ - public getEntityProcessor(): T { - return this.entityProcessors.getProcessor(); - } - } + /** + * 获取类型为T的第一个渲染器 + * @param type + */ + public getRenderer(type): T { + for (let i = 0; i < this._renderers.length; i++) { + if (this._renderers[i] instanceof type) + return this._renderers[i] as T; + } + + return null; + } + + /** + * 从场景中移除渲染器 + * @param renderer + */ + public removeRenderer(renderer: Renderer) { + if (!this._renderers.contains(renderer)) + return; + this._renderers.remove(renderer); + renderer.unload(); + } + + /** + * 添加一个后处理器到场景。设置场景字段并调用后处理器。onAddedToScene使后处理器可以使用场景ContentManager加载资源。 + * @param postProcessor + */ + public addPostProcessor(postProcessor: T): T { + this._postProcessors.push(postProcessor); + this._postProcessors.sort(); + postProcessor.onAddedToScene(this); + + if (this._didSceneBegin) { + postProcessor.onSceneBackBufferSizeChanged(this.stage.stageWidth, this.stage.stageHeight); + } + + return postProcessor; + } + + /** + * 获取类型为T的第一个后处理器 + * @param type + */ + public getPostProcessor(type): T { + for (let i = 0; i < this._postProcessors.length; i++) { + if (this._postProcessors[i] instanceof type) + return this._postProcessors[i] as T; + } + + return null; + } + + /** + * 删除一个后处理程序。注意,在删除时不会调用unload,因此如果不再需要PostProcessor,请确保调用unload来释放资源。 + * @param postProcessor + */ + public removePostProcessor(postProcessor: PostProcessor) { + if (!this._postProcessors.contains(postProcessor)) + return; + + this._postProcessors.remove(postProcessor); + postProcessor.unload(); + } + + /** + * 将实体添加到此场景,并返回它 + * @param name + */ + public createEntity(name: string) { + let entity = new Entity(name); + return this.addEntity(entity); + } + + /** + * 在场景的实体列表中添加一个实体 + * @param entity + */ + public addEntity(entity: Entity) { + if (this.entities.buffer.contains(entity)) + console.warn(`You are attempting to add the same entity to a scene twice: ${entity}`); + this.entities.add(entity); + entity.scene = this; + + for (let i = 0; i < entity.transform.childCount; i++) + this.addEntity(entity.transform.getChild(i).entity); + + return entity; + } + + /** + * 从场景中删除所有实体 + */ + public destroyAllEntities() { + for (let i = 0; i < this.entities.count; i++) { + this.entities.buffer[i].destroy(); + } + } + + /** + * 搜索并返回第一个具有名称的实体 + * @param name + */ + public findEntity(name: string): Entity { + return this.entities.findEntity(name); + } + + /** + * 返回具有给定标记的所有实体 + * @param tag + */ + public findEntitiesWithTag(tag: number): Entity[] { + return this.entities.entitiesWithTag(tag); + } + + /** + * 返回类型为T的所有实体 + * @param type + */ + public entitiesOfType(type): T[] { + return this.entities.entitiesOfType(type); + } + + /** + * 返回第一个启用加载的类型为T的组件 + * @param type + */ + public findComponentOfType(type): T { + return this.entities.findComponentOfType(type); + } + + /** + * 返回类型为T的所有已启用已加载组件的列表 + * @param type + */ + public findComponentsOfType(type): T[] { + return this.entities.findComponentsOfType(type); + } + + /** + * 在场景中添加一个EntitySystem处理器 + * @param processor 处理器 + */ + public addEntityProcessor(processor: EntitySystem) { + processor.scene = this; + this.entityProcessors.add(processor); + return processor; + } + + /** + * 从场景中删除EntitySystem处理器 + * @param processor + */ + public removeEntityProcessor(processor: EntitySystem) { + this.entityProcessors.remove(processor); + } + + /** + * 获取EntitySystem处理器 + */ + public getEntityProcessor(): T { + return this.entityProcessors.getProcessor(); + } + } } \ No newline at end of file diff --git a/source/src/ECS/Systems/EntitySystem.ts b/source/src/ECS/Systems/EntitySystem.ts index 5f823fa5..a3e0c94a 100644 --- a/source/src/ECS/Systems/EntitySystem.ts +++ b/source/src/ECS/Systems/EntitySystem.ts @@ -1,80 +1,82 @@ module es { export class EntitySystem { - private _scene: Scene; private _entities: Entity[] = []; - private _matcher: Matcher; - public get matcher(){ - return this._matcher; + constructor(matcher?: Matcher) { + this._matcher = matcher ? matcher : Matcher.empty(); } - public get scene(){ + private _scene: Scene; + + public get scene() { return this._scene; } - public set scene(value: Scene){ + public set scene(value: Scene) { this._scene = value; this._entities = []; } - constructor(matcher?: Matcher){ - this._matcher = matcher ? matcher : Matcher.empty(); + private _matcher: Matcher; + + public get matcher() { + return this._matcher; } - public initialize(){ + public initialize() { } - public onChanged(entity: Entity){ + public onChanged(entity: Entity) { let contains = this._entities.contains(entity); let interest = this._matcher.IsIntersted(entity); if (interest && !contains) this.add(entity); - else if(!interest && contains) + else if (!interest && contains) this.remove(entity); } - public add(entity: Entity){ + public add(entity: Entity) { this._entities.push(entity); this.onAdded(entity); } - public onAdded(entity: Entity){ + public onAdded(entity: Entity) { } - public remove(entity: Entity){ + public remove(entity: Entity) { this._entities.remove(entity); this.onRemoved(entity); } - public onRemoved(entity: Entity){ + public onRemoved(entity: Entity) { } - public update(){ + public update() { this.begin(); this.process(this._entities); } - public lateUpdate(){ + public lateUpdate() { this.lateProcess(this._entities); this.end(); } - protected begin(){ + protected begin() { } - protected process(entities: Entity[]){ + protected process(entities: Entity[]) { } - protected lateProcess(entities: Entity[]){ + protected lateProcess(entities: Entity[]) { } - protected end(){ + protected end() { } } diff --git a/source/src/ECS/Systems/PassiveSystem.ts b/source/src/ECS/Systems/PassiveSystem.ts index 09a36a49..f6285f3c 100644 --- a/source/src/ECS/Systems/PassiveSystem.ts +++ b/source/src/ECS/Systems/PassiveSystem.ts @@ -1,10 +1,10 @@ module es { export abstract class PassiveSystem extends EntitySystem { - public onChanged(entity: Entity){ + public onChanged(entity: Entity) { } - protected process(entities: Entity[]){ + protected process(entities: Entity[]) { // 我们用我们自己的不考虑实体的基本实体系统来代替 this.begin(); this.end(); diff --git a/source/src/ECS/Systems/ProcessingSystem.ts b/source/src/ECS/Systems/ProcessingSystem.ts index d567c281..d09a8ef6 100644 --- a/source/src/ECS/Systems/ProcessingSystem.ts +++ b/source/src/ECS/Systems/ProcessingSystem.ts @@ -1,17 +1,17 @@ /** 用于协调其他系统的通用系统基类 */ module es { export abstract class ProcessingSystem extends EntitySystem { - public onChanged(entity: Entity){ + public onChanged(entity: Entity) { } - protected process(entities: Entity[]){ - this.begin(); - this.processSystem(); - this.end(); - } - /** 处理我们的系统 每帧调用 */ public abstract processSystem(); + + protected process(entities: Entity[]) { + this.begin(); + this.processSystem(); + this.end(); + } } } diff --git a/source/src/ECS/Transform.ts b/source/src/ECS/Transform.ts index 7b075238..6151919f 100644 --- a/source/src/ECS/Transform.ts +++ b/source/src/ECS/Transform.ts @@ -19,6 +19,78 @@ module es { export class Transform extends HashObject { /** 与此转换关联的实体 */ public readonly entity: Entity; + public hierarchyDirty: DirtyType; + public _localDirty: boolean; + public _localPositionDirty: boolean; + public _localScaleDirty: boolean; + public _localRotationDirty: boolean; + public _positionDirty: boolean; + public _worldToLocalDirty: boolean; + public _worldInverseDirty: boolean; + /** + * 值会根据位置、旋转和比例自动重新计算 + */ + public _localTransform: Matrix2D = Matrix2D.create(); + /** + * 值将自动从本地和父矩阵重新计算。 + */ + public _worldTransform = Matrix2D.create().identity(); + public _rotationMatrix: Matrix2D = Matrix2D.create(); + public _translationMatrix: Matrix2D = Matrix2D.create(); + public _scaleMatrix: Matrix2D = Matrix2D.create(); + public _children: Transform[]; + + constructor(entity: Entity) { + super(); + this.entity = entity; + this.scale = Vector2.one; + this._children = []; + } + + /** + * 这个转换的所有子元素 + */ + public get childCount() { + return this._children.length; + } + + /** + * 变换在世界空间的旋转度 + */ + public get rotationDegrees(): number { + return MathHelper.toDegrees(this._rotation); + } + + /** + * 变换在世界空间的旋转度 + * @param value + */ + public set rotationDegrees(value: number) { + this.setRotation(MathHelper.toRadians(value)); + } + + /** + * 旋转相对于父变换旋转的角度 + */ + public get localRotationDegrees(): number { + return MathHelper.toDegrees(this._localRotation); + } + + /** + * 旋转相对于父变换旋转的角度 + * @param value + */ + public set localRotationDegrees(value: number) { + this.localRotation = MathHelper.toRadians(value); + } + + public get localToWorldTransform(): Matrix2D { + this.updateTransform(); + return this._worldTransform; + } + + public _parent: Transform; + /** * 获取此转换的父转换 */ @@ -34,22 +106,46 @@ module es { this.setParent(value); } - /** - * 这个转换的所有子元素 - */ - public get childCount() { - return this._children.length; + public _worldToLocalTransform = Matrix2D.create().identity(); + + public get worldToLocalTransform(): Matrix2D { + if (this._worldToLocalDirty) { + if (!this.parent) { + this._worldToLocalTransform = Matrix2D.create().identity(); + } else { + this.parent.updateTransform(); + this._worldToLocalTransform = this.parent._worldTransform.invert(); + } + + this._worldToLocalDirty = false; + } + + return this._worldToLocalTransform; } + public _worldInverseTransform = Matrix2D.create().identity(); + + public get worldInverseTransform(): Matrix2D { + this.updateTransform(); + if (this._worldInverseDirty) { + this._worldInverseTransform = this._worldTransform.invert(); + this._worldInverseDirty = false; + } + + return this._worldInverseTransform; + } + + public _position: Vector2 = Vector2.zero; + /** * 变换在世界空间中的位置 */ public get position(): Vector2 { this.updateTransform(); - if (this._positionDirty){ - if (!this.parent){ + if (this._positionDirty) { + if (!this.parent) { this._position = this._localPosition; - }else{ + } else { this.parent.updateTransform(); this._position = Vector2Ext.transformR(this._localPosition, this.parent._worldTransform); } @@ -64,10 +160,48 @@ module es { * 变换在世界空间中的位置 * @param value */ - public set position(value: Vector2){ + public set position(value: Vector2) { this.setPosition(value.x, value.y); } + public _scale: Vector2 = Vector2.one; + + /** + * 变换在世界空间的缩放 + */ + public get scale(): Vector2 { + this.updateTransform(); + return this._scale; + } + + /** + * 变换在世界空间的缩放 + * @param value + */ + public set scale(value: Vector2) { + this.setScale(value); + } + + public _rotation: number = 0; + + /** + * 在世界空间中以弧度旋转的变换 + */ + public get rotation(): number { + this.updateTransform(); + return this._rotation; + } + + /** + * 变换在世界空间的旋转度 + * @param value + */ + public set rotation(value: number) { + this.setRotation(value); + } + + public _localPosition: Vector2 = Vector2.zero; + /** * 转换相对于父转换的位置。如果转换没有父元素,则与transform.position相同 */ @@ -80,87 +214,11 @@ module es { * 转换相对于父转换的位置。如果转换没有父元素,则与transform.position相同 * @param value */ - public set localPosition(value: Vector2){ + public set localPosition(value: Vector2) { this.setLocalPosition(value); } - /** - * 在世界空间中以弧度旋转的变换 - */ - public get rotation(): number { - this.updateTransform(); - return this._rotation; - } - - /** - * 变换在世界空间的旋转度 - */ - public get rotationDegrees(): number { - return MathHelper.toDegrees(this._rotation); - } - - /** - * 变换在世界空间的旋转度 - * @param value - */ - public set rotationDegrees(value: number){ - this.setRotation(MathHelper.toRadians(value)); - } - - /** - * 变换在世界空间的旋转度 - * @param value - */ - public set rotation(value: number){ - this.setRotation(value); - } - - /** - * 相对于父变换的旋转,变换的旋转。如果转换没有父元素,则与transform.rotation相同 - */ - public get localRotation(): number { - this.updateTransform(); - return this._localRotation; - } - - /** - * 相对于父变换的旋转,变换的旋转。如果转换没有父元素,则与transform.rotation相同 - * @param value - */ - public set localRotation(value: number){ - this.setLocalRotation(value); - } - - /** - * 旋转相对于父变换旋转的角度 - */ - public get localRotationDegrees(): number { - return MathHelper.toDegrees(this._localRotation); - } - - /** - * 旋转相对于父变换旋转的角度 - * @param value - */ - public set localRotationDegrees(value: number){ - this.localRotation = MathHelper.toRadians(value); - } - - /** - * 变换在世界空间的缩放 - */ - public get scale(): Vector2{ - this.updateTransform(); - return this._scale; - } - - /** - * 变换在世界空间的缩放 - * @param value - */ - public set scale(value: Vector2){ - this.setScale(value); - } + public _localScale: Vector2 = Vector2.one; /** * 转换相对于父元素的比例。如果转换没有父元素,则与transform.scale相同 @@ -174,81 +232,26 @@ module es { * 转换相对于父元素的比例。如果转换没有父元素,则与transform.scale相同 * @param value */ - public set localScale(value: Vector2){ + public set localScale(value: Vector2) { this.setLocalScale(value); } - public get worldInverseTransform(): Matrix2D { - this.updateTransform(); - if (this._worldInverseDirty){ - this._worldInverseTransform = this._worldTransform.invert(); - this._worldInverseDirty = false; - } - - return this._worldInverseTransform; - } - - public get localToWorldTransform(): Matrix2D { - this.updateTransform(); - return this._worldTransform; - } - - public get worldToLocalTransform(): Matrix2D { - if (this._worldToLocalDirty){ - if (!this.parent){ - this._worldToLocalTransform = Matrix2D.create().identity(); - }else{ - this.parent.updateTransform(); - this._worldToLocalTransform = this.parent._worldTransform.invert(); - } - - this._worldToLocalDirty = false; - } - - return this._worldToLocalTransform; - } - - public _parent: Transform; - public hierarchyDirty: DirtyType; - - public _localDirty: boolean; - public _localPositionDirty: boolean; - public _localScaleDirty: boolean; - public _localRotationDirty: boolean; - public _positionDirty: boolean; - public _worldToLocalDirty: boolean; - public _worldInverseDirty: boolean; - - /** - * 值会根据位置、旋转和比例自动重新计算 - */ - public _localTransform: Matrix2D = Matrix2D.create(); - /** - * 值将自动从本地和父矩阵重新计算。 - */ - public _worldTransform = Matrix2D.create().identity(); - public _worldToLocalTransform = Matrix2D.create().identity(); - public _worldInverseTransform = Matrix2D.create().identity(); - - public _rotationMatrix: Matrix2D = Matrix2D.create(); - public _translationMatrix: Matrix2D = Matrix2D.create(); - public _scaleMatrix: Matrix2D = Matrix2D.create(); - - public _position: Vector2 = Vector2.zero; - public _scale: Vector2 = Vector2.one; - public _rotation: number = 0; - - public _localPosition: Vector2 = Vector2.zero; - public _localScale: Vector2 = Vector2.one; public _localRotation: number = 0; - public _children: Transform[]; + /** + * 相对于父变换的旋转,变换的旋转。如果转换没有父元素,则与transform.rotation相同 + */ + public get localRotation(): number { + this.updateTransform(); + return this._localRotation; + } - constructor(entity: Entity) { - super(); - this.entity = entity; - this.scale = Vector2.one; - this._children = []; + /** + * 相对于父变换的旋转,变换的旋转。如果转换没有父元素,则与transform.rotation相同 + * @param value + */ + public set localRotation(value: number) { + this.setLocalRotation(value); } /** @@ -289,7 +292,7 @@ module es { return this; this._position = position; - if (this.parent){ + if (this.parent) { this.localPosition = Vector2Ext.transformR(this._position, this._worldToLocalTransform); } else { this.localPosition = position; @@ -321,7 +324,7 @@ module es { */ public setRotation(radians: number): Transform { this._rotation = radians; - if (this.parent){ + if (this.parent) { this.localRotation = this.parent.rotation + radians; } else { this.localRotation = radians; @@ -352,7 +355,7 @@ module es { * 相对于父变换的旋转设置变换的旋转。如果转换没有父元素,则与transform.rotation相同 * @param radians */ - public setLocalRotation(radians: number){ + public setLocalRotation(radians: number) { this._localRotation = radians; this._localDirty = this._positionDirty = this._localPositionDirty = this._localRotationDirty = this._localScaleDirty = true; this.setDirty(DirtyType.rotationDirty); @@ -374,9 +377,9 @@ module es { */ public setScale(scale: Vector2): Transform { this._scale = scale; - if (this.parent){ + if (this.parent) { this.localScale = Vector2.divide(scale, this.parent._scale); - }else{ + } else { this.localScale = scale; } return this; @@ -401,23 +404,23 @@ module es { this.position = this._position.round(); } - public updateTransform(){ - if (this.hierarchyDirty != DirtyType.clean){ + public updateTransform() { + if (this.hierarchyDirty != DirtyType.clean) { if (this.parent) this.parent.updateTransform(); - if (this._localDirty){ - if (this._localPositionDirty){ + if (this._localDirty) { + if (this._localPositionDirty) { this._translationMatrix = Matrix2D.create().translate(this._localPosition.x, this._localPosition.y); this._localPositionDirty = false; } - if (this._localRotationDirty){ + if (this._localRotationDirty) { this._rotationMatrix = Matrix2D.create().rotate(this._localRotation); this._localRotationDirty = false; } - if (this._localScaleDirty){ + if (this._localScaleDirty) { this._scaleMatrix = Matrix2D.create().scale(this._localScale.x, this._localScale.y); this._localScaleDirty = false; } @@ -425,7 +428,7 @@ module es { this._localTransform = this._scaleMatrix.multiply(this._rotationMatrix); this._localTransform = this._localTransform.multiply(this._translationMatrix); - if (!this.parent){ + if (!this.parent) { this._worldTransform = this._localTransform; this._rotation = this._localRotation; this._scale = this._localScale; @@ -435,7 +438,7 @@ module es { this._localDirty = false; } - if (this.parent){ + if (this.parent) { this._worldTransform = this._localTransform.multiply(this.parent._worldTransform); this._rotation = this._localRotation + this.parent._rotation; @@ -449,8 +452,8 @@ module es { } } - public setDirty(dirtyFlagType: DirtyType){ - if ((this.hierarchyDirty & dirtyFlagType) == 0){ + public setDirty(dirtyFlagType: DirtyType) { + if ((this.hierarchyDirty & dirtyFlagType) == 0) { this.hierarchyDirty |= dirtyFlagType; switch (dirtyFlagType) { @@ -469,7 +472,7 @@ module es { this._children = []; // 告诉子项发生了变换 - for (let i = 0; i < this._children.length; i ++) + for (let i = 0; i < this._children.length; i++) this._children[i].setDirty(dirtyFlagType); } } @@ -491,13 +494,13 @@ module es { this.setDirty(DirtyType.scaleDirty); } - public toString(): string{ + public toString(): string { return `[Transform: parent: ${this.parent}, position: ${this.position}, rotation: ${this.rotation}, scale: ${this.scale}, localPosition: ${this._localPosition}, localRotation: ${this._localRotation}, localScale: ${this._localScale}]`; } - public equals(other: Transform){ + public equals(other: Transform) { return other.hashCode == this.hashCode; } } diff --git a/source/src/ECS/Utils/BitSet.ts b/source/src/ECS/Utils/BitSet.ts index 7dcd6544..8ec94a8b 100644 --- a/source/src/ECS/Utils/BitSet.ts +++ b/source/src/ECS/Utils/BitSet.ts @@ -4,43 +4,43 @@ module es { * * 它是由一个位向量实现的,但同样可以把它看成是一个非负整数的集合;集合中的每个整数由对应索引处的集合位表示。该结构的大小由集合中的最大整数决定。 */ - export class BitSet{ + export class BitSet { private static LONG_MASK: number = 0x3f; private _bits: number[]; - constructor(nbits: number = 64){ + constructor(nbits: number = 64) { let length = nbits >> 6; if ((nbits & BitSet.LONG_MASK) != 0) - length ++; + length++; this._bits = new Array(length); } - public and(bs: BitSet){ + public and(bs: BitSet) { let max = Math.min(this._bits.length, bs._bits.length); let i; for (let i = 0; i < max; ++i) this._bits[i] &= bs._bits[i]; while (i < this._bits.length) - this._bits[i ++] = 0; + this._bits[i++] = 0; } - public andNot(bs: BitSet){ + public andNot(bs: BitSet) { let i = Math.min(this._bits.length, bs._bits.length); - while(--i >= 0) + while (--i >= 0) this._bits[i] &= ~bs._bits[i]; } - public cardinality(): number{ + public cardinality(): number { let card = 0; - for (let i = this._bits.length - 1; i >= 0; i --){ + for (let i = this._bits.length - 1; i >= 0; i--) { let a = this._bits[i]; if (a == 0) continue; - if (a == -1){ + if (a == -1) { card += 64; continue; } @@ -56,26 +56,18 @@ module es { return card; } - public clear(pos?: number){ - if (pos != undefined){ + public clear(pos?: number) { + if (pos != undefined) { let offset = pos >> 6; this.ensure(offset); this._bits[offset] &= ~(1 << pos); - }else{ - for (let i = 0; i < this._bits.length; i ++) + } else { + for (let i = 0; i < this._bits.length; i++) this._bits[i] = 0; } } - private ensure(lastElt: number){ - if (lastElt >= this._bits.length){ - let nd = new Number[lastElt + 1]; - nd = this._bits.copyWithin(0, 0, this._bits.length); - this._bits = nd; - } - } - - public get(pos: number): boolean{ + public get(pos: number): boolean { let offset = pos >> 6; if (offset >= this._bits.length) return false; @@ -83,9 +75,9 @@ module es { return (this._bits[offset] & (1 << pos)) != 0; } - public intersects(set: BitSet){ + public intersects(set: BitSet) { let i = Math.min(this._bits.length, set._bits.length); - while (--i >= 0){ + while (--i >= 0) { if ((this._bits[i] & set._bits[i]) != 0) return true; } @@ -93,8 +85,8 @@ module es { return false; } - public isEmpty(): boolean{ - for (let i = this._bits.length - 1; i >= 0; i --){ + public isEmpty(): boolean { + for (let i = this._bits.length - 1; i >= 0; i--) { if (this._bits[i]) return false; } @@ -102,34 +94,42 @@ module es { return true; } - public nextSetBit(from: number){ + public nextSetBit(from: number) { let offset = from >> 6; let mask = 1 << from; - while (offset < this._bits.length){ + while (offset < this._bits.length) { let h = this._bits[offset]; do { if ((h & mask) != 0) return from; mask <<= 1; - from ++; + from++; } while (mask != 0); mask = 1; - offset ++; + offset++; } return -1; } - public set(pos: number, value: boolean = true){ - if (value){ + public set(pos: number, value: boolean = true) { + if (value) { let offset = pos >> 6; this.ensure(offset); this._bits[offset] |= 1 << pos; - }else{ + } else { this.clear(pos); } } + + private ensure(lastElt: number) { + if (lastElt >= this._bits.length) { + let nd = new Number[lastElt + 1]; + nd = this._bits.copyWithin(0, 0, this._bits.length); + this._bits = nd; + } + } } } diff --git a/source/src/ECS/Utils/ComponentList.ts b/source/src/ECS/Utils/ComponentList.ts index 67bb89bd..1194ebab 100644 --- a/source/src/ECS/Utils/ComponentList.ts +++ b/source/src/ECS/Utils/ComponentList.ts @@ -37,7 +37,7 @@ module es { return this._components; } - public markEntityListUnsorted(){ + public markEntityListUnsorted() { this._isComponentListUnsorted = true; } @@ -76,7 +76,7 @@ module es { let component = this._components[i]; // 处理渲染层列表 - if (component instanceof RenderableComponent){ + if (component instanceof RenderableComponent) { this._entity.scene.removeChild(component.displayObject); this._entity.scene.renderableComponents.remove(component); } @@ -91,7 +91,7 @@ module es { for (let i = 0; i < this._components.length; i++) { let component = this._components[i]; - if (component instanceof RenderableComponent){ + if (component instanceof RenderableComponent) { this._entity.scene.addChild(component.displayObject); this._entity.scene.renderableComponents.add(component); } @@ -117,7 +117,7 @@ module es { if (this._componentsToAdd.length > 0) { for (let i = 0, count = this._componentsToAdd.length; i < count; i++) { let component = this._componentsToAdd[i]; - if (component instanceof RenderableComponent){ + if (component instanceof RenderableComponent) { this._entity.scene.addChild(component.displayObject); this._entity.scene.renderableComponents.add(component); } @@ -148,7 +148,7 @@ module es { this._tempBufferList.length = 0; } - if (this._isComponentListUnsorted){ + if (this._isComponentListUnsorted) { this._components.sort(ComponentList.compareUpdatableOrder.compare); this._isComponentListUnsorted = false; } @@ -156,7 +156,7 @@ module es { public handleRemove(component: Component) { // 处理渲染层列表 - if (component instanceof RenderableComponent){ + if (component instanceof RenderableComponent) { this._entity.scene.removeChild(component.displayObject); this._entity.scene.renderableComponents.remove(component); } diff --git a/source/src/ECS/Utils/ComponentTypeManager.ts b/source/src/ECS/Utils/ComponentTypeManager.ts index 7dc20b4b..fc8c5409 100644 --- a/source/src/ECS/Utils/ComponentTypeManager.ts +++ b/source/src/ECS/Utils/ComponentTypeManager.ts @@ -1,15 +1,15 @@ module es { - export class ComponentTypeManager{ + export class ComponentTypeManager { private static _componentTypesMask: Map = new Map(); - public static add(type){ + public static add(type) { if (!this._componentTypesMask.has(type)) this._componentTypesMask[type] = this._componentTypesMask.size; } - public static getIndexFor(type){ + public static getIndexFor(type) { let v = -1; - if (!this._componentTypesMask.has(type)){ + if (!this._componentTypesMask.has(type)) { this.add(type); v = this._componentTypesMask.get(type); } diff --git a/source/src/ECS/Utils/EntityList.ts b/source/src/ECS/Utils/EntityList.ts index 379bbca3..d00cbb2b 100644 --- a/source/src/ECS/Utils/EntityList.ts +++ b/source/src/ECS/Utils/EntityList.ts @@ -1,5 +1,5 @@ module es { - export class EntityList{ + export class EntityList { public scene: Scene; /** * 添加到场景中的实体列表 @@ -27,23 +27,23 @@ module es { */ public _tempEntityList: Entity[] = []; - constructor(scene: Scene){ + constructor(scene: Scene) { this.scene = scene; } - public get count(){ + public get count() { return this._entities.length; } - public get buffer(){ + public get buffer() { return this._entities; } - public markEntityListUnsorted(){ + public markEntityListUnsorted() { this._isEntityListUnsorted = true; } - public markTagUnsorted(tag: number){ + public markTagUnsorted(tag: number) { this._unsortedTags.push(tag); } @@ -51,7 +51,7 @@ module es { * 将实体添加到列表中。所有生命周期方法将在下一帧中被调用。 * @param entity */ - public add(entity: Entity){ + public add(entity: Entity) { if (this._entitiesToAdded.indexOf(entity) == -1) this._entitiesToAdded.push(entity); } @@ -60,14 +60,14 @@ module es { * 从列表中删除一个实体。所有生命周期方法将在下一帧中被调用。 * @param entity */ - public remove(entity: Entity){ - if (!this._entitiesToRemove.contains(entity)){ + public remove(entity: Entity) { + if (!this._entitiesToRemove.contains(entity)) { console.warn(`You are trying to remove an entity (${entity.name}) that you already removed`); return; } // 防止在同一帧中添加或删除实体 - if (this._entitiesToAdded.contains(entity)){ + if (this._entitiesToAdded.contains(entity)) { this._entitiesToAdded.remove(entity); return; } @@ -79,7 +79,7 @@ module es { /** * 从实体列表中删除所有实体 */ - public removeAllEntities(){ + public removeAllEntities() { this._unsortedTags.length = 0; this._entitiesToAdded.length = 0; this._isEntityListUnsorted = false; @@ -88,7 +88,7 @@ module es { // 它们仍然在_entitiesToRemove列表中,该列表将由更新列表处理。 this.updateLists(); - for (let i = 0; i < this._entities.length; i ++){ + for (let i = 0; i < this._entities.length; i++) { this._entities[i]._isDestroyed = true; this._entities[i].onRemovedFromScene(); this._entities[i].scene = null; @@ -106,9 +106,9 @@ module es { return this._entities.contains(entity) || this._entitiesToAdded.contains(entity); } - public getTagList(tag: number){ + public getTagList(tag: number) { let list = this._entityDict.get(tag); - if (!list){ + if (!list) { list = []; this._entityDict.set(tag, list); } @@ -116,31 +116,31 @@ module es { return this._entityDict.get(tag); } - public addToTagList(entity: Entity){ + public addToTagList(entity: Entity) { let list = this.getTagList(entity.tag); - if (!list.contains(entity)){ + if (!list.contains(entity)) { list.push(entity); this._unsortedTags.push(entity.tag); } } - public removeFromTagList(entity: Entity){ + public removeFromTagList(entity: Entity) { let list = this._entityDict.get(entity.tag); - if (list){ + if (list) { list.remove(entity); } } - public update(){ - for (let i = 0; i < this._entities.length; i++){ + public update() { + for (let i = 0; i < this._entities.length; i++) { let entity = this._entities[i]; if (entity.enabled && (entity.updateInterval == 1 || Time.frameCount % entity.updateInterval == 0)) entity.update(); } } - public updateLists(){ - if (this._entitiesToRemove.length > 0){ + public updateLists() { + if (this._entitiesToRemove.length > 0) { let temp = this._entitiesToRemove; this._entitiesToRemove = this._tempEntityList; this._tempEntityList = temp; @@ -157,12 +157,12 @@ module es { this._tempEntityList.length = 0; } - if (this._entitiesToAdded.length > 0){ + if (this._entitiesToAdded.length > 0) { let temp = this._entitiesToAdded; this._entitiesToAdded = this._tempEntityList; this._tempEntityList = temp; this._tempEntityList.forEach(entity => { - if (!this._entities.contains(entity)){ + if (!this._entities.contains(entity)) { this._entities.push(entity); entity.scene = this.scene; @@ -178,12 +178,12 @@ module es { this._isEntityListUnsorted = true; } - if (this._isEntityListUnsorted){ + if (this._isEntityListUnsorted) { this._entities.sort(); this._isEntityListUnsorted = false; } - if (this._unsortedTags.length > 0){ + if (this._unsortedTags.length > 0) { this._unsortedTags.forEach(tag => { this._entityDict.get(tag).sort(); }); @@ -196,8 +196,8 @@ module es { * 返回找到的第一个实体的名称。如果没有找到,则返回null。 * @param name */ - public findEntity(name: string){ - for (let i = 0; i < this._entities.length; i ++){ + public findEntity(name: string) { + for (let i = 0; i < this._entities.length; i++) { if (this._entities[i].name == name) return this._entities[i]; } @@ -209,11 +209,11 @@ module es { * 返回带有标记的所有实体的列表。如果没有实体具有标记,则返回一个空列表。可以通过ListPool.free将返回的列表放回池中。 * @param tag */ - public entitiesWithTag(tag: number){ + public entitiesWithTag(tag: number) { let list = this.getTagList(tag); let returnList = ListPool.obtain(); - for (let i = 0; i < list.length; i ++) + for (let i = 0; i < list.length; i++) returnList.push(list[i]); return returnList; @@ -223,9 +223,9 @@ module es { * 返回t类型的所有实体的列表。返回的列表可以通过ListPool.free放回池中。 * @param type */ - public entitiesOfType(type): T[]{ + public entitiesOfType(type): T[] { let list = ListPool.obtain(); - for (let i = 0; i < this._entities.length; i ++){ + for (let i = 0; i < this._entities.length; i++) { if (this._entities[i] instanceof type) list.push(this._entities[i] as T); } @@ -242,17 +242,17 @@ module es { * @param type */ public findComponentOfType(type): T { - for (let i = 0; i < this._entities.length; i ++){ - if (this._entities[i].enabled){ + for (let i = 0; i < this._entities.length; i++) { + if (this._entities[i].enabled) { let comp = this._entities[i].getComponent(type); if (comp) return comp; } } - for (let i = 0; i < this._entitiesToAdded.length; i ++){ + for (let i = 0; i < this._entitiesToAdded.length; i++) { let entity = this._entitiesToAdded[i]; - if (entity.enabled){ + if (entity.enabled) { let comp = entity.getComponent(type); if (comp) return comp; @@ -266,17 +266,17 @@ module es { * 返回在类型t的场景中找到的所有组件。返回的列表可以通过ListPool.free放回池中。 * @param type */ - public findComponentsOfType(type): T[]{ + public findComponentsOfType(type): T[] { let comps = ListPool.obtain(); - for (let i = 0; i < this._entities.length; i ++){ + for (let i = 0; i < this._entities.length; i++) { if (this._entities[i].enabled) this._entities[i].getComponents(type, comps); } - for (let i = 0; i < this._entitiesToAdded.length; i ++){ + for (let i = 0; i < this._entitiesToAdded.length; i++) { let entity = this._entitiesToAdded[i]; if (entity.enabled) - entity.getComponents(type,comps); + entity.getComponents(type, comps); } return comps; diff --git a/source/src/ECS/Utils/EntityProcessorList.ts b/source/src/ECS/Utils/EntityProcessorList.ts index 148f08b7..f816a573 100644 --- a/source/src/ECS/Utils/EntityProcessorList.ts +++ b/source/src/ECS/Utils/EntityProcessorList.ts @@ -2,64 +2,52 @@ module es { export class EntityProcessorList { private _processors: EntitySystem[] = []; - public add(processor: EntitySystem){ + public add(processor: EntitySystem) { this._processors.push(processor); } - public remove(processor: EntitySystem){ + public remove(processor: EntitySystem) { this._processors.remove(processor); } - public onComponentAdded(entity: Entity){ + public onComponentAdded(entity: Entity) { this.notifyEntityChanged(entity); } - public onComponentRemoved(entity: Entity){ + public onComponentRemoved(entity: Entity) { this.notifyEntityChanged(entity); } - public onEntityAdded(entity: Entity){ + public onEntityAdded(entity: Entity) { this.notifyEntityChanged(entity); } - public onEntityRemoved(entity: Entity){ + public onEntityRemoved(entity: Entity) { this.removeFromProcessors(entity); } - protected notifyEntityChanged(entity: Entity){ - for (let i = 0; i < this._processors.length; i ++){ - this._processors[i].onChanged(entity); - } - } - - protected removeFromProcessors(entity: Entity){ - for (let i = 0; i < this._processors.length; i ++){ - this._processors[i].remove(entity); - } - } - - public begin(){ + public begin() { } - public update(){ - for (let i = 0; i < this._processors.length; i++){ + public update() { + for (let i = 0; i < this._processors.length; i++) { this._processors[i].update(); } } - public lateUpdate(){ - for (let i = 0; i < this._processors.length; i ++){ + public lateUpdate() { + for (let i = 0; i < this._processors.length; i++) { this._processors[i].lateUpdate(); } } - public end(){ + public end() { } - public getProcessor(): T{ - for (let i = 0; i < this._processors.length; i ++){ + public getProcessor(): T { + for (let i = 0; i < this._processors.length; i++) { let processor = this._processors[i]; if (processor instanceof EntitySystem) return processor as T; @@ -67,5 +55,17 @@ module es { return null; } + + protected notifyEntityChanged(entity: Entity) { + for (let i = 0; i < this._processors.length; i++) { + this._processors[i].onChanged(entity); + } + } + + protected removeFromProcessors(entity: Entity) { + for (let i = 0; i < this._processors.length; i++) { + this._processors[i].remove(entity); + } + } } } diff --git a/source/src/ECS/Utils/Matcher.ts b/source/src/ECS/Utils/Matcher.ts index 7b5797cb..06a6960a 100644 --- a/source/src/ECS/Utils/Matcher.ts +++ b/source/src/ECS/Utils/Matcher.ts @@ -1,28 +1,28 @@ module es { - export class Matcher{ + export class Matcher { protected allSet = new BitSet(); protected exclusionSet = new BitSet(); protected oneSet = new BitSet(); - public static empty(){ + public static empty() { return new Matcher(); } - public getAllSet(){ + public getAllSet() { return this.allSet; } - public getExclusionSet(){ + public getExclusionSet() { return this.exclusionSet; } - public getOneSet(){ + public getOneSet() { return this.oneSet; } - public IsIntersted(e: Entity){ - if (!this.allSet.isEmpty()){ - for (let i = this.allSet.nextSetBit(0); i >= 0; i = this.allSet.nextSetBit(i + 1)){ + public IsIntersted(e: Entity) { + if (!this.allSet.isEmpty()) { + for (let i = this.allSet.nextSetBit(0); i >= 0; i = this.allSet.nextSetBit(i + 1)) { if (!e.componentBits.get(i)) return false; } @@ -37,7 +37,7 @@ module es { return true; } - public all(...types: any[]): Matcher{ + public all(...types: any[]): Matcher { types.forEach(type => { this.allSet.set(ComponentTypeManager.getIndexFor(type)); }); @@ -45,7 +45,7 @@ module es { return this; } - public exclude(...types: any[]){ + public exclude(...types: any[]) { types.forEach(type => { this.exclusionSet.set(ComponentTypeManager.getIndexFor(type)); }); @@ -53,7 +53,7 @@ module es { return this; } - public one(...types: any[]){ + public one(...types: any[]) { types.forEach(type => { this.oneSet.set(ComponentTypeManager.getIndexFor(type)); }); diff --git a/source/src/ECS/Utils/ObjectUtils.ts b/source/src/ECS/Utils/ObjectUtils.ts index ec2cb194..a0f95e2b 100644 --- a/source/src/ECS/Utils/ObjectUtils.ts +++ b/source/src/ECS/Utils/ObjectUtils.ts @@ -1,17 +1,16 @@ class ObjectUtils { - /** - * 对象深度拷贝 - * @param p any 源对象 - * @param c any 目标对象, 不传则返回新对象, 传则合并属性, 相同名字的属性则会覆盖 - */ + /** + * 对象深度拷贝 + * @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 { + } else { c[i] = p[i]; } } diff --git a/source/src/ECS/Utils/StringUtils.ts b/source/src/ECS/Utils/StringUtils.ts index b4e3258a..09d5fd2a 100644 --- a/source/src/ECS/Utils/StringUtils.ts +++ b/source/src/ECS/Utils/StringUtils.ts @@ -1,9 +1,23 @@ class StringUtils { /** - * 匹配中文字符 - * @param str 需要匹配的字符串 - * @return - */ + * 特殊符号字符串 + */ + private static specialSigns: string[] = [ + '&', '&', + '<', '<', + '>', '>', + '"', '"', + "'", ''', + '®', '®', + '©', '©', + '™', '™', + ]; + + /** + * 匹配中文字符 + * @param str 需要匹配的字符串 + * @return + */ public static matchChineseWord(str: string): string[] { //中文字符的unicode值[\u4E00-\u9FA5] let patternA: RegExp = /[\u4E00-\u9FA5]+/gim; @@ -12,7 +26,7 @@ class StringUtils { /** * 去除字符串左端的空白字符 - * @param target 目标字符串 + * @param target 目标字符串 * @return */ public static lTrim(target: string): string { @@ -25,7 +39,7 @@ class StringUtils { /** * 去除字符串右端的空白字符 - * @param target 目标字符串 + * @param target 目标字符串 * @return */ public static rTrim(target: string): string { @@ -36,7 +50,6 @@ class StringUtils { return target.slice(0, endIndex + 1); } - /** * 返回一个去除2段空白字符的字符串 * @param target @@ -69,7 +82,7 @@ class StringUtils { * @return 返回执行替换后的字符串 */ public static replaceMatch(mainStr: string, targetStr: string, - replaceStr: string, caseMark: boolean = false): string { + replaceStr: string, caseMark: boolean = false): string { let len: number = mainStr.length; let tempStr: string = ""; let isMatch: boolean = false; @@ -84,35 +97,18 @@ class StringUtils { if (isMatch) { tempStr += replaceStr; i = i + tempTarget.length - 1; - } - else { + } else { tempStr += mainStr.charAt(i); } } return tempStr; } - - /** - * 特殊符号字符串 - */ - private static specialSigns: string[] = [ - '&', '&', - '<', '<', - '>', '>', - '"', '"', - "'", ''', - '®', '®', - '©', '©', - '™', '™', - ]; - - /** * 用html实体换掉字符窜中的特殊字符 - * @param str 需要替换的字符串 - * @param reversion 是否翻转替换:将转义符号替换为正常的符号 - * @return 换掉特殊字符后的字符串 + * @param str 需要替换的字符串 + * @param reversion 是否翻转替换:将转义符号替换为正常的符号 + * @return 换掉特殊字符后的字符串 */ public static htmlSpecialChars(str: string, reversion: boolean = false): string { let len: number = this.specialSigns.length; @@ -133,27 +129,27 @@ class StringUtils { /** - * 给数字字符前面添 "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 - * - */ + * 给数字字符前面添 "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; @@ -185,7 +181,7 @@ class StringUtils { /** * 翻转字符串 - * @param str 字符串 + * @param str 字符串 * @return 翻转后的字符串 */ public static reverse(str: string): string { @@ -198,14 +194,14 @@ class StringUtils { /** * 截断某段字符串 - * @param str 目标字符串 - * @param start 需要截断的起始索引 - * @param len 截断长度 - * @param order 顺序,true从字符串头部开始计算,false从字符串尾巴开始结算。 - * @return 截断后的字符串 + * @param str 目标字符串 + * @param start 需要截断的起始索引 + * @param len 截断长度 + * @param order 顺序,true从字符串头部开始计算,false从字符串尾巴开始结算。 + * @return 截断后的字符串 */ public static cutOff(str: string, start: number, - len: number, order: boolean = true): string { + len: number, order: boolean = true): string { start = Math.floor(start); len = Math.floor(len); let length: number = str.length; @@ -215,8 +211,7 @@ class StringUtils { let newStr: string; if (order) { newStr = str.substring(0, s) + str.substr(e, length); - } - else { + } else { s = length - 1 - start - len; e = s + len; newStr = str.substring(0, s + 1) + str.substr(e + 1, length); diff --git a/source/src/ECS/Utils/TextureUtils.ts b/source/src/ECS/Utils/TextureUtils.ts index 169740f6..f1a6f4f4 100644 --- a/source/src/ECS/Utils/TextureUtils.ts +++ b/source/src/ECS/Utils/TextureUtils.ts @@ -6,15 +6,15 @@ module es { public static sharedCanvas: HTMLCanvasElement; public static sharedContext: CanvasRenderingContext2D; - public static convertImageToCanvas(texture: egret.Texture, rect?: egret.Rectangle): HTMLCanvasElement{ - if (!this.sharedCanvas){ + 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){ + if (!rect) { rect = egret.$TempRectangle; rect.x = 0; rect.y = 0; @@ -44,8 +44,7 @@ module es { } renderTexture = new egret.RenderTexture(); renderTexture.drawToTexture(new egret.Bitmap(texture)); - } - else { + } else { renderTexture = texture; } //从RenderTexture中读取像素数据,填入canvas @@ -71,8 +70,7 @@ module es { } return surface; - } - else { + } else { let bitmapData = texture; let offsetX: number = Math.round(bitmapData.$offsetX); let offsetY: number = Math.round(bitmapData.$offsetY); @@ -90,8 +88,7 @@ module es { let surface = this.convertImageToCanvas(texture, rect); let result = surface.toDataURL(type, encoderOptions); return result; - } - catch (e) { + } catch (e) { egret.$error(1033); } return null; @@ -117,7 +114,7 @@ module es { success: function (res) { //todo } - }) + }); return result; } @@ -135,8 +132,7 @@ module es { if (!(texture).$renderBuffer) { renderTexture = new egret.RenderTexture(); renderTexture.drawToTexture(new egret.Bitmap(texture)); - } - else { + } else { renderTexture = texture; } //从RenderTexture中读取像素数据 @@ -147,8 +143,7 @@ module es { let surface = this.convertImageToCanvas(texture); let result = this.sharedContext.getImageData(x, y, width, height).data; return result; - } - catch (e) { + } catch (e) { egret.$error(1039); } } diff --git a/source/src/ECS/Utils/Time.ts b/source/src/ECS/Utils/Time.ts index 31c2387e..e4acc278 100644 --- a/source/src/ECS/Utils/Time.ts +++ b/source/src/ECS/Utils/Time.ts @@ -9,22 +9,21 @@ module es { public static timeScale = 1; /** 已传递的帧总数 */ public static frameCount = 0; - - private static _lastTime = 0; /** 自场景加载以来的总时间 */ public static _timeSinceSceneLoad; + private static _lastTime = 0; - public static update(currentTime: number){ + public static update(currentTime: number) { let dt = (currentTime - this._lastTime) / 1000; this.deltaTime = dt * this.timeScale; this.unscaledDeltaTime = dt; this._timeSinceSceneLoad += dt; - this.frameCount ++; + this.frameCount++; this._lastTime = currentTime; } - public static sceneChanged(){ + public static sceneChanged() { this._timeSinceSceneLoad = 0; } @@ -32,7 +31,7 @@ module es { * 允许在间隔检查。只应该使用高于delta的间隔值,否则它将始终返回true。 * @param interval */ - public static checkEvery(interval: number){ + public static checkEvery(interval: number) { // 我们减去了delta,因为timeSinceSceneLoad已经包含了这个update ticks delta return (this._timeSinceSceneLoad / interval) > ((this._timeSinceSceneLoad - this.deltaTime) / interval); } diff --git a/source/src/ECS/Utils/TimeUtils.ts b/source/src/ECS/Utils/TimeUtils.ts index 34a9ddc6..b8277a80 100644 --- a/source/src/ECS/Utils/TimeUtils.ts +++ b/source/src/ECS/Utils/TimeUtils.ts @@ -1,9 +1,9 @@ class TimeUtils { /** - * 计算月份ID - * @param d 指定计算日期 - * @returns 月ID - */ + * 计算月份ID + * @param d 指定计算日期 + * @returns 月ID + */ public static monthId(d: Date = null): number { d = d ? d : new Date(); let y = d.getFullYear(); @@ -35,7 +35,8 @@ class TimeUtils { d = d ? d : new Date(); let c: Date = new Date(); c.setTime(d.getTime()); - c.setDate(1); c.setMonth(0);//当年第一天 + c.setDate(1); + c.setMonth(0);//当年第一天 let year: number = c.getFullYear(); let firstDay: number = c.getDay(); @@ -51,7 +52,8 @@ class TimeUtils { } let num: number = this.diffDay(d, c, false); if (num < 0) { - c.setDate(1); c.setMonth(0);//当年第一天 + c.setDate(1); + c.setMonth(0);//当年第一天 c.setDate(c.getDate() - 1); return this.weekId(c, false); } @@ -66,7 +68,8 @@ class TimeUtils { } if (first && (!max || endDay < 4)) { c.setFullYear(c.getFullYear() + 1); - c.setDate(1); c.setMonth(0);//当年第一天 + c.setDate(1); + c.setMonth(0);//当年第一天 return this.weekId(c, false); } } @@ -151,9 +154,9 @@ class TimeUtils { /** * 秒数转换为时间形式。 - * @param time 秒数 - * @param partition 分隔符 - * @param showHour 是否显示小时 + * @param time 秒数 + * @param partition 分隔符 + * @param showHour 是否显示小时 * @return 返回一个以分隔符分割的时, 分, 秒 * * 比如: time = 4351; secondToTime(time)返回字符串01:12:31; diff --git a/source/src/Extension.ts b/source/src/Extension.ts index ce827664..e3f9b865 100644 --- a/source/src/Extension.ts +++ b/source/src/Extension.ts @@ -309,7 +309,7 @@ Array.prototype.groupBy = function (keySelector) { if (typeof (array.reduce) === "function") { let keys = []; return array.reduce(function (groups, element, index) { - let key = JSON.stringify(keySelector.call(arguments[1], element, index, array)) + let key = JSON.stringify(keySelector.call(arguments[1], element, index, array)); let index2 = keys.findIndex(function (x) { return x === key; }); diff --git a/source/src/Graphics/Effects/GaussianBlurEffect.ts b/source/src/Graphics/Effects/GaussianBlurEffect.ts index b5ca7849..087c0ec9 100644 --- a/source/src/Graphics/Effects/GaussianBlurEffect.ts +++ b/source/src/Graphics/Effects/GaussianBlurEffect.ts @@ -64,8 +64,8 @@ module es { "gl_FragColor = vec4(final_colour/(z*z), 1.0);\n" + "}"; - constructor(){ - super(PostProcessor.default_vert, GaussianBlurEffect.blur_frag,{ + constructor() { + super(PostProcessor.default_vert, GaussianBlurEffect.blur_frag, { screenWidth: Core.graphicsDevice.viewport.width, screenHeight: Core.graphicsDevice.viewport.height }); diff --git a/source/src/Graphics/Effects/PolygonLightEffect.ts b/source/src/Graphics/Effects/PolygonLightEffect.ts index ce40e82e..0b5c7377 100644 --- a/source/src/Graphics/Effects/PolygonLightEffect.ts +++ b/source/src/Graphics/Effects/PolygonLightEffect.ts @@ -29,7 +29,7 @@ module es { "gl_FragColor = c;\n" + "}"; - constructor(){ + constructor() { super(PolygonLightEffect.vertSrc, PolygonLightEffect.fragmentSrc); } } diff --git a/source/src/Graphics/GraphicsCapabilities.ts b/source/src/Graphics/GraphicsCapabilities.ts index b967b22a..8e1fba29 100644 --- a/source/src/Graphics/GraphicsCapabilities.ts +++ b/source/src/Graphics/GraphicsCapabilities.ts @@ -1,11 +1,11 @@ module es { export class GraphicsCapabilities extends egret.Capabilities { - public initialize(device: GraphicsDevice){ + public initialize(device: GraphicsDevice) { this.platformInitialize(device); } - private platformInitialize(device: GraphicsDevice){ + private platformInitialize(device: GraphicsDevice) { if (GraphicsCapabilities.runtimeType != egret.RuntimeType.WXGAME) return; let capabilities = this; @@ -13,14 +13,14 @@ module es { let systemInfo = wx.getSystemInfoSync(); let systemStr = systemInfo.system.toLowerCase(); - if (systemStr.indexOf("ios") > -1){ + if (systemStr.indexOf("ios") > -1) { capabilities["os"] = "iOS"; - } else if(systemStr.indexOf("android") > -1){ + } else if (systemStr.indexOf("android") > -1) { capabilities["os"] = "Android"; } let language = systemInfo.language; - if (language.indexOf('zh') > -1){ + if (language.indexOf('zh') > -1) { language = "zh-CN"; } else { language = "en-US"; diff --git a/source/src/Graphics/GraphicsDevice.ts b/source/src/Graphics/GraphicsDevice.ts index ea5fb9ea..9892b045 100644 --- a/source/src/Graphics/GraphicsDevice.ts +++ b/source/src/Graphics/GraphicsDevice.ts @@ -1,19 +1,20 @@ module es { export class GraphicsDevice { - private _viewport: Viewport; - public get viewport(): Viewport{ - return this._viewport; - } - public graphicsCapabilities: GraphicsCapabilities; - constructor(){ + constructor() { this.setup(); this.graphicsCapabilities = new GraphicsCapabilities(); this.graphicsCapabilities.initialize(this); } - private setup(){ + private _viewport: Viewport; + + public get viewport(): Viewport { + return this._viewport; + } + + private setup() { this._viewport = new Viewport(0, 0, Core._instance.stage.stageWidth, Core._instance.stage.stageHeight); } } diff --git a/source/src/Graphics/PostProcessing/PostProcessor.ts b/source/src/Graphics/PostProcessing/PostProcessor.ts index 516b8cdd..51f6f3c2 100644 --- a/source/src/Graphics/PostProcessing/PostProcessor.ts +++ b/source/src/Graphics/PostProcessing/PostProcessor.ts @@ -1,10 +1,5 @@ module es { export class PostProcessor { - public enabled: boolean; - public effect: egret.Filter; - public scene: Scene; - public shape: egret.Shape; - public static default_vert = "attribute vec2 aVertexPosition;\n" + "attribute vec2 aTextureCoord;\n" + "attribute vec2 aColor;\n" + @@ -22,13 +17,17 @@ module es { "vTextureCoord = aTextureCoord;\n" + "vColor = vec4(aColor.x, aColor.x, aColor.x, aColor.x);\n" + "}"; + public enabled: boolean; + public effect: egret.Filter; + public scene: Scene; + public shape: egret.Shape; - constructor(effect: egret.Filter = null){ + constructor(effect: egret.Filter = null) { this.enabled = true; this.effect = effect; } - public onAddedToScene(scene: Scene){ + public onAddedToScene(scene: Scene) { this.scene = scene; this.shape = new egret.Shape(); this.shape.graphics.beginFill(0xFFFFFF, 1); @@ -37,24 +36,25 @@ module es { scene.addChild(this.shape); } - public process(){ + public process() { this.drawFullscreenQuad(); } - public onSceneBackBufferSizeChanged(newWidth: number, newHeight: number){} - - protected drawFullscreenQuad(){ - this.scene.filters = [this.effect]; - // this.shape.filters = [this.effect]; + public onSceneBackBufferSizeChanged(newWidth: number, newHeight: number) { } - public unload(){ - if (this.effect){ + public unload() { + if (this.effect) { this.effect = null; } this.scene.removeChild(this.shape); this.scene = null; } + + protected drawFullscreenQuad() { + this.scene.filters = [this.effect]; + // this.shape.filters = [this.effect]; + } } } diff --git a/source/src/Graphics/PostProcessing/PostProcessors/GaussianBlurPostProcessor.ts b/source/src/Graphics/PostProcessing/PostProcessors/GaussianBlurPostProcessor.ts index dc6d02d2..04316920 100644 --- a/source/src/Graphics/PostProcessing/PostProcessors/GaussianBlurPostProcessor.ts +++ b/source/src/Graphics/PostProcessing/PostProcessors/GaussianBlurPostProcessor.ts @@ -1,6 +1,6 @@ module es { export class GaussianBlurPostProcessor extends PostProcessor { - public onAddedToScene(scene: Scene){ + public onAddedToScene(scene: Scene) { super.onAddedToScene(scene); this.effect = new GaussianBlurEffect(); } diff --git a/source/src/Graphics/Renderers/DefaultRenderer.ts b/source/src/Graphics/Renderers/DefaultRenderer.ts index b862d70f..5a839623 100644 --- a/source/src/Graphics/Renderers/DefaultRenderer.ts +++ b/source/src/Graphics/Renderers/DefaultRenderer.ts @@ -1,7 +1,7 @@ /// module es { export class DefaultRenderer extends Renderer { - constructor(){ + constructor() { super(0, null); } @@ -9,7 +9,7 @@ module es { let cam = this.camera ? this.camera : scene.camera; this.beginRender(cam); - for (let i = 0; i < scene.renderableComponents.count; i++){ + for (let i = 0; i < scene.renderableComponents.count; i++) { let renderable = scene.renderableComponents.buffer[i]; if (renderable.enabled && renderable.isVisibleFromCamera(cam)) this.renderAfterStateCheck(renderable, cam); diff --git a/source/src/Graphics/Renderers/IRenderable.ts b/source/src/Graphics/Renderers/IRenderable.ts index cb1a2b9d..fbfbf21c 100644 --- a/source/src/Graphics/Renderers/IRenderable.ts +++ b/source/src/Graphics/Renderers/IRenderable.ts @@ -40,7 +40,7 @@ module es { * 用于排序IRenderables的比较器 */ export class RenderableComparer { - public compare(self: IRenderable, other: IRenderable){ + public compare(self: IRenderable, other: IRenderable) { return other.renderLayer - self.renderLayer; } } diff --git a/source/src/Graphics/Renderers/PolygonLight/PolyLight.ts b/source/src/Graphics/Renderers/PolygonLight/PolyLight.ts index d8567650..37a2ffa9 100644 --- a/source/src/Graphics/Renderers/PolygonLight/PolyLight.ts +++ b/source/src/Graphics/Renderers/PolygonLight/PolyLight.ts @@ -1,18 +1,10 @@ module es { export class PolyLight extends RenderableComponent { public power: number; - protected _radius: number; private _lightEffect; private _indices: number[] = []; - public get radius(){ - return this._radius; - } - public set radius(value: number){ - this.setRadius(value); - } - - constructor(radius: number, color: number, power: number){ + constructor(radius: number, color: number, power: number) { super(); this.radius = radius; @@ -21,18 +13,18 @@ module es { this.computeTriangleIndices(); } - private computeTriangleIndices(totalTris: number = 20){ - this._indices.length = 0; + protected _radius: number; - for (let i = 0; i < totalTris; i += 2){ - this._indices.push(0); - this._indices.push(i + 2); - this._indices.push(i + 1); - } + public get radius() { + return this._radius; } - public setRadius(radius: number){ - if (radius != this._radius){ + public set radius(value: number) { + this.setRadius(value); + } + + public setRadius(radius: number) { + if (radius != this._radius) { this._radius = radius; this._areBoundsDirty = true; } @@ -41,8 +33,18 @@ module es { public render(camera: Camera) { } - public reset(){ + public reset() { } + + private computeTriangleIndices(totalTris: number = 20) { + this._indices.length = 0; + + for (let i = 0; i < totalTris; i += 2) { + this._indices.push(0); + this._indices.push(i + 2); + this._indices.push(i + 1); + } + } } } diff --git a/source/src/Graphics/Renderers/Renderer.ts b/source/src/Graphics/Renderers/Renderer.ts index 364cc520..e761e4a8 100644 --- a/source/src/Graphics/Renderers/Renderer.ts +++ b/source/src/Graphics/Renderers/Renderer.ts @@ -14,7 +14,7 @@ module es { */ public readonly renderOrder: number = 0; - protected constructor(renderOrder: number, camera: Camera = null){ + protected constructor(renderOrder: number, camera: Camera = null) { this.camera = camera; this.renderOrder = renderOrder; } @@ -23,41 +23,44 @@ module es { * 当渲染器被添加到场景时调用 * @param scene */ - public onAddedToScene(scene: Scene){} + public onAddedToScene(scene: Scene) { + } /** * 当场景结束或渲染器从场景中移除时调用。使用这个进行清理。 */ - public unload(){ } - - /** - * - * @param cam - */ - protected beginRender(cam: Camera){ } + public unload() { + } public abstract render(scene: Scene); - /** - * - * @param renderable - * @param cam - */ - protected renderAfterStateCheck(renderable: IRenderable, cam: Camera){ - renderable.render(cam); - } - /** * 当默认场景渲染目标被调整大小和当场景已经开始添加渲染器时调用 * @param newWidth * @param newHeight */ - public onSceneBackBufferSizeChanged(newWidth: number, newHeight: number){ + public onSceneBackBufferSizeChanged(newWidth: number, newHeight: number) { } - public compareTo(other: Renderer): number{ + public compareTo(other: Renderer): number { return this.renderOrder - other.renderOrder; } + + /** + * + * @param cam + */ + protected beginRender(cam: Camera) { + } + + /** + * + * @param renderable + * @param cam + */ + protected renderAfterStateCheck(renderable: IRenderable, cam: Camera) { + renderable.render(cam); + } } } diff --git a/source/src/Graphics/Transitions/FadeTransition.ts b/source/src/Graphics/Transitions/FadeTransition.ts index 4aa0e148..d72b242f 100644 --- a/source/src/Graphics/Transitions/FadeTransition.ts +++ b/source/src/Graphics/Transitions/FadeTransition.ts @@ -18,17 +18,17 @@ module es { this._mask.graphics.drawRect(0, 0, Core.graphicsDevice.viewport.width, Core.graphicsDevice.viewport.height); this._mask.graphics.endFill(); - egret.Tween.get(this).to({ _alpha: 1}, this.fadeOutDuration * 1000, this.fadeEaseType) + egret.Tween.get(this).to({_alpha: 1}, this.fadeOutDuration * 1000, this.fadeEaseType) .call(async () => { await this.loadNextScene(); }).wait(this.delayBeforeFadeInDuration).call(() => { - egret.Tween.get(this).to({ _alpha: 0 }, this.fadeOutDuration * 1000, this.fadeEaseType).call(() => { + egret.Tween.get(this).to({_alpha: 0}, this.fadeOutDuration * 1000, this.fadeEaseType).call(() => { this.transitionComplete(); }); }); } - public render(){ + public render() { this._mask.graphics.clear(); this._mask.graphics.beginFill(this.fadeToColor, this._alpha); this._mask.graphics.drawRect(0, 0, Core.graphicsDevice.viewport.width, Core.graphicsDevice.viewport.height); diff --git a/source/src/Graphics/Transitions/SceneTransition.ts b/source/src/Graphics/Transitions/SceneTransition.ts index 34143455..6a23c0a1 100644 --- a/source/src/Graphics/Transitions/SceneTransition.ts +++ b/source/src/Graphics/Transitions/SceneTransition.ts @@ -3,7 +3,6 @@ module es { * SceneTransition用于从一个场景过渡到另一个场景或在一个有效果的场景中过渡 */ export abstract class SceneTransition { - private _hasPreviousSceneRender: boolean; /** 是否加载新场景的标志 */ public loadsNewScene: boolean; /** @@ -11,15 +10,22 @@ module es { * 对于场景过渡,isNewSceneLoaded应该在中点设置为true,这就标识一个新的场景被加载了。 */ public isNewSceneLoaded: boolean; - /** 返回新加载场景的函数 */ - protected sceneLoadAction: Function; /** 在loadNextScene执行时调用。这在进行场景间过渡时很有用,这样你就知道什么时候可以更多地使用相机或者重置任何实体 */ public onScreenObscured: Function; /** 当转换完成执行时调用,以便可以调用其他工作,比如启动另一个转换。 */ public onTransitionCompleted: Function; + /** 返回新加载场景的函数 */ + protected sceneLoadAction: Function; - public get hasPreviousSceneRender(){ - if (!this._hasPreviousSceneRender){ + constructor(sceneLoadAction: Function) { + this.sceneLoadAction = sceneLoadAction; + this.loadsNewScene = sceneLoadAction != null; + } + + private _hasPreviousSceneRender: boolean; + + public get hasPreviousSceneRender() { + if (!this._hasPreviousSceneRender) { this._hasPreviousSceneRender = true; return false; } @@ -27,13 +33,9 @@ module es { return true; } - constructor(sceneLoadAction: Function) { - this.sceneLoadAction = sceneLoadAction; - this.loadsNewScene = sceneLoadAction != null; + public preRender() { } - public preRender() { } - public render() { } @@ -43,6 +45,17 @@ module es { this.transitionComplete(); } + public tickEffectProgressProperty(filter: egret.CustomFilter, duration: number, easeType: Function, reverseDirection = false): Promise { + return new Promise((resolve) => { + let start = reverseDirection ? 1 : 0; + let end = reverseDirection ? 0 : 1; + + egret.Tween.get(filter.uniforms).set({_progress: start}).to({_progress: end}, duration * 1000, easeType).call(() => { + resolve(); + }); + }); + } + protected transitionComplete() { Core._instance._sceneTransition = null; @@ -62,16 +75,5 @@ module es { Core.scene = await this.sceneLoadAction(); this.isNewSceneLoaded = true; } - - public tickEffectProgressProperty(filter: egret.CustomFilter, duration: number, easeType: Function, reverseDirection = false): Promise{ - return new Promise((resolve)=>{ - let start = reverseDirection ? 1 : 0; - let end = reverseDirection ? 0 : 1; - - egret.Tween.get(filter.uniforms).set({_progress: start}).to({_progress: end}, duration * 1000, easeType).call(()=>{ - resolve(); - }); - }); - } } } diff --git a/source/src/Graphics/Transitions/WindTransition.ts b/source/src/Graphics/Transitions/WindTransition.ts index c476879b..8ce82c75 100644 --- a/source/src/Graphics/Transitions/WindTransition.ts +++ b/source/src/Graphics/Transitions/WindTransition.ts @@ -1,20 +1,14 @@ module es { export class WindTransition extends SceneTransition { + public duration = 1; + public easeType = egret.Ease.quadOut; private _mask: egret.Shape; private _windEffect: egret.CustomFilter; - public duration = 1; - public set windSegments(value: number) { - this._windEffect.uniforms._windSegments = value; - } - public set size(value: number) { - this._windEffect.uniforms._size = value; - } - public easeType = egret.Ease.quadOut; constructor(sceneLoadAction: Function) { super(sceneLoadAction); - let vertexSrc = "attribute vec2 aVertexPosition;\n" + + let vertexSrc = "attribute vec2 aVertexPosition;\n" + "attribute vec2 aTextureCoord;\n" + "uniform vec2 projectionVector;\n" + @@ -56,6 +50,14 @@ module es { this._mask.filters = [this._windEffect]; } + public set windSegments(value: number) { + this._windEffect.uniforms._windSegments = value; + } + + public set size(value: number) { + this._windEffect.uniforms._size = value; + } + public async onBeginTransition() { this.loadNextScene(); await this.tickEffectProgressProperty(this._windEffect, this.duration, this.easeType); diff --git a/source/src/Graphics/Viewport.ts b/source/src/Graphics/Viewport.ts index 18b39636..412dda02 100644 --- a/source/src/Graphics/Viewport.ts +++ b/source/src/Graphics/Viewport.ts @@ -2,42 +2,10 @@ module es { export class Viewport { private _x: number; private _y: number; - private _width: number; - private _height: number; private _minDepth: number; private _maxDepth: number; - public get height(){ - return this._height; - } - public set height(value: number){ - this._height = value; - } - - public get width(){ - return this._width; - } - public set width(value: number){ - this._width = value; - } - - public get aspectRatio(){ - if ((this._height != 0) && (this._width != 0)) - return (this._width / this._height); - return 0; - } - - public get bounds(){ - return new Rectangle(this._x, this._y, this._width, this._height); - } - public set bounds(value: Rectangle){ - this._x = value.x; - this._y = value.y; - this._width = value.width; - this._height = value.height; - } - - constructor(x: number, y: number, width: number, height: number){ + constructor(x: number, y: number, width: number, height: number) { this._x = x; this._y = y; this._width = width; @@ -46,5 +14,42 @@ module es { this._maxDepth = 1; } + private _width: number; + + public get width() { + return this._width; + } + + public set width(value: number) { + this._width = value; + } + + private _height: number; + + public get height() { + return this._height; + } + + public set height(value: number) { + this._height = value; + } + + public get aspectRatio() { + if ((this._height != 0) && (this._width != 0)) + return (this._width / this._height); + return 0; + } + + public get bounds() { + return new Rectangle(this._x, this._y, this._width, this._height); + } + + public set bounds(value: Rectangle) { + this._x = value.x; + this._y = value.y; + this._width = value.width; + this._height = value.height; + } + } } diff --git a/source/src/Math/Flags.ts b/source/src/Math/Flags.ts index f83ed4b5..55e473af 100644 --- a/source/src/Math/Flags.ts +++ b/source/src/Math/Flags.ts @@ -11,7 +11,7 @@ module es { * @param self * @param flag */ - public static isFlagSet(self: number, flag: number): boolean{ + public static isFlagSet(self: number, flag: number): boolean { return (self & flag) != 0; } @@ -20,7 +20,7 @@ module es { * @param self * @param flag */ - public static isUnshiftedFlagSet(self: number, flag: number): boolean{ + public static isUnshiftedFlagSet(self: number, flag: number): boolean { flag = 1 << flag; return (self & flag) != 0; } @@ -30,7 +30,7 @@ module es { * @param self * @param flag */ - public static setFlagExclusive(self: number, flag: number){ + public static setFlagExclusive(self: number, flag: number) { return 1 << flag; } @@ -39,7 +39,7 @@ module es { * @param self * @param flag */ - public static setFlag(self: number, flag: number){ + public static setFlag(self: number, flag: number) { return (self | 1 << flag); } @@ -48,7 +48,7 @@ module es { * @param self * @param flag */ - public static unsetFlag(self: number, flag: number){ + public static unsetFlag(self: number, flag: number) { flag = 1 << flag; return (self & (~flag)); } @@ -57,7 +57,7 @@ module es { * 反转数值集合位 * @param self */ - public static invertFlags(self: number){ + public static invertFlags(self: number) { return ~self; } } diff --git a/source/src/Math/MathHelper.ts b/source/src/Math/MathHelper.ts index 24186325..79030310 100644 --- a/source/src/Math/MathHelper.ts +++ b/source/src/Math/MathHelper.ts @@ -8,7 +8,7 @@ module es { * 将弧度转换成角度。 * @param radians 用弧度表示的角 */ - public static toDegrees(radians: number){ + public static toDegrees(radians: number) { return radians * 57.295779513082320876798154814105; } @@ -16,7 +16,7 @@ module es { * 将角度转换为弧度 * @param degrees */ - public static toRadians(degrees: number){ + public static toRadians(degrees: number) { return degrees * 0.017453292519943295769236907684886; } @@ -28,15 +28,15 @@ module es { * @param rightMin * @param rightMax */ - public static map(value: number, leftMin: number, leftMax: number, rightMin: number, rightMax: number){ + public static map(value: number, leftMin: number, leftMax: number, rightMin: number, rightMax: number) { return rightMin + (value - leftMin) * (rightMax - rightMin) / (leftMax - leftMin); } - public static lerp(value1: number, value2: number, amount: number){ + public static lerp(value1: number, value2: number, amount: number) { return value1 + (value2 - value1) * amount; } - public static clamp(value: number, min: number, max: number){ + public static clamp(value: number, min: number, max: number) { if (value < min) return min; @@ -46,7 +46,7 @@ module es { return value; } - public static pointOnCirlce(circleCenter: Vector2, radius: number, angleInDegrees: number){ + public static pointOnCirlce(circleCenter: Vector2, radius: number, angleInDegrees: number) { let radians = MathHelper.toRadians(angleInDegrees); return new Vector2(Math.cos(radians) * radians + circleCenter.x, Math.sin(radians) * radians + circleCenter.y); } @@ -55,7 +55,7 @@ module es { * 如果值为偶数,返回true * @param value */ - public static isEven(value: number){ + public static isEven(value: number) { return value % 2 == 0; } @@ -63,7 +63,7 @@ module es { * 数值限定在0-1之间 * @param value */ - public static clamp01(value: number){ + public static clamp01(value: number) { if (value < 0) return 0; @@ -73,7 +73,7 @@ module es { return value; } - public static angleBetweenVectors(from: Vector2, to: Vector2){ + public static angleBetweenVectors(from: Vector2, to: Vector2) { return Math.atan2(to.y - from.y, to.x - from.x); } } diff --git a/source/src/Math/Matrix2D.ts b/source/src/Math/Matrix2D.ts index cb91de0e..7a2b6d9d 100644 --- a/source/src/Math/Matrix2D.ts +++ b/source/src/Math/Matrix2D.ts @@ -1,57 +1,69 @@ module es { export var matrixPool = []; + /** * 表示右手3 * 3的浮点矩阵,可以存储平移、缩放和旋转信息。 */ - export class Matrix2D extends egret.Matrix{ - public get m11(): number{ + export class Matrix2D extends egret.Matrix { + public get m11(): number { return this.a; } - public set m11(value: number){ + + public set m11(value: number) { this.a = value; } - public get m12(): number{ + + public get m12(): number { return this.b; } - public set m12(value: number){ + + public set m12(value: number) { this.b = value; } - public get m21(): number{ + + public get m21(): number { return this.c; } - public set m21(value: number){ + + public set m21(value: number) { this.c = value; } - public get m22(): number{ + + public get m22(): number { return this.d; } - public set m22(value: number){ + + public set m22(value: number) { this.d = value; } + public get m31(): number { return this.tx; } - public set m31(value: number){ + + public set m31(value: number) { this.tx = value; } - public get m32(): number{ + + public get m32(): number { return this.ty; } - public set m32(value: number){ + + public set m32(value: number) { this.ty = value; } /** * 从对象池中取出或创建一个新的Matrix对象。 */ - public static create(): Matrix2D{ + public static create(): Matrix2D { let matrix = matrixPool.pop(); if (!matrix) matrix = new Matrix2D(); return matrix; } - public identity(): Matrix2D{ + public identity(): Matrix2D { this.a = this.d = 1; this.b = this.c = this.tx = this.ty = 0; return this; @@ -64,12 +76,12 @@ module es { } public scale(sx: number, sy: number): Matrix2D { - if (sx !== 1){ + if (sx !== 1) { this.a *= sx; this.c *= sx; this.tx *= sx; } - if (sy !== 1){ + if (sy !== 1) { this.b *= sy; this.d *= sy; this.ty *= sy; @@ -108,7 +120,7 @@ module es { * 创建一个新的matrix, 它包含两个矩阵的和。 * @param matrix */ - public add(matrix: Matrix2D): Matrix2D{ + public add(matrix: Matrix2D): Matrix2D { this.m11 += matrix.m11; this.m12 += matrix.m12; @@ -134,7 +146,7 @@ module es { return this; } - public divide(matrix: Matrix2D): Matrix2D{ + public divide(matrix: Matrix2D): Matrix2D { this.m11 /= matrix.m11; this.m12 /= matrix.m12; @@ -147,15 +159,15 @@ module es { return this; } - public multiply(matrix: Matrix2D): Matrix2D{ - let m11 = ( this.m11 * matrix.m11 ) + ( this.m12 * matrix.m21 ); - let m12 = ( this.m11 * matrix.m12 ) + ( this.m12 * matrix.m22 ); + public multiply(matrix: Matrix2D): Matrix2D { + let m11 = (this.m11 * matrix.m11) + (this.m12 * matrix.m21); + let m12 = (this.m11 * matrix.m12) + (this.m12 * matrix.m22); - let m21 = ( this.m21 * matrix.m11 ) + ( this.m22 * matrix.m21 ); - let m22 = ( this.m21 * matrix.m12 ) + ( this.m22 * matrix.m22 ); + let m21 = (this.m21 * matrix.m11) + (this.m22 * matrix.m21); + let m22 = (this.m21 * matrix.m12) + (this.m22 * matrix.m22); - let m31 = ( this.m31 * matrix.m11 ) + ( this.m32 * matrix.m21 ) + matrix.m31; - let m32 = ( this.m31 * matrix.m12 ) + ( this.m32 * matrix.m22 ) + matrix.m32; + let m31 = (this.m31 * matrix.m11) + (this.m32 * matrix.m21) + matrix.m31; + let m32 = (this.m31 * matrix.m12) + (this.m32 * matrix.m22) + matrix.m32; this.m11 = m11; this.m12 = m12; @@ -169,7 +181,7 @@ module es { return this; } - public determinant(){ + public determinant() { return this.m11 * this.m22 - this.m12 * this.m21; } diff --git a/source/src/Math/Rectangle.ts b/source/src/Math/Rectangle.ts index 08991731..e1baf3c8 100644 --- a/source/src/Math/Rectangle.ts +++ b/source/src/Math/Rectangle.ts @@ -2,6 +2,7 @@ module es { export class Rectangle extends egret.Rectangle { public _tempMat: Matrix2D; public _transformMat: Matrix2D; + /** * 获取矩形的最大点,即右下角 */ @@ -18,6 +19,7 @@ module es { public get location() { return new Vector2(this.x, this.y); } + /** 左上角的坐标 */ public set location(value: Vector2) { this.x = value.x; @@ -33,6 +35,41 @@ module es { this.height = value.y; } + /** + * 创建一个矩形的最小/最大点(左上角,右下角的点) + * @param minX + * @param minY + * @param maxX + * @param maxY + */ + public static fromMinMax(minX: number, minY: number, maxX: number, maxY: number) { + return new Rectangle(minX, minY, maxX - minX, maxY - minY); + } + + /** + * 给定多边形的点,计算边界 + * @param points + */ + public static rectEncompassingPoints(points: Vector2[]) { + // 我们需要求出x/y的最小值/最大值 + let minX = Number.POSITIVE_INFINITY; + let minY = Number.POSITIVE_INFINITY; + let maxX = Number.NEGATIVE_INFINITY; + let maxY = Number.NEGATIVE_INFINITY; + + for (let i = 0; i < points.length; i++) { + let pt = points[i]; + + if (pt.x < minX) minX = pt.x; + if (pt.x > maxX) maxX = pt.x; + + if (pt.y < minY) minY = pt.y; + if (pt.y > maxY) maxY = pt.y; + } + + return this.fromMinMax(minX, minY, maxX, maxY); + } + /** * 是否与另一个矩形相交 * @param value @@ -58,17 +95,6 @@ module es { return new Vector2(this.width * 0.5, this.height * 0.5); } - /** - * 创建一个矩形的最小/最大点(左上角,右下角的点) - * @param minX - * @param minY - * @param maxX - * @param maxY - */ - public static fromMinMax(minX: number, minY: number, maxX: number, maxY: number) { - return new Rectangle(minX, minY, maxX - minX, maxY - minY); - } - /** * 获取矩形边界上与给定点最近的点 * @param point @@ -142,8 +168,8 @@ module es { return boundsPoint; } - public calculateBounds(parentPosition: Vector2, position: Vector2, origin: Vector2, scale: Vector2, rotation: number, width: number, height: number){ - if (rotation == 0){ + public calculateBounds(parentPosition: Vector2, position: Vector2, origin: Vector2, scale: Vector2, rotation: number, width: number, height: number) { + if (rotation == 0) { this.x = parentPosition.x + position.x - origin.x * scale.x; this.y = parentPosition.y + position.y - origin.y * scale.y; this.width = width * scale.x; @@ -183,29 +209,5 @@ module es { this.height = maxY - minY; } } - - /** - * 给定多边形的点,计算边界 - * @param points - */ - public static rectEncompassingPoints(points: Vector2[]) { - // 我们需要求出x/y的最小值/最大值 - let minX = Number.POSITIVE_INFINITY; - let minY = Number.POSITIVE_INFINITY; - let maxX = Number.NEGATIVE_INFINITY; - let maxY = Number.NEGATIVE_INFINITY; - - for (let i = 0; i < points.length; i++) { - let pt = points[i]; - - if (pt.x < minX) minX = pt.x; - if (pt.x > maxX) maxX = pt.x; - - if (pt.y < minY) minY = pt.y; - if (pt.y > maxY) maxY = pt.y; - } - - return this.fromMinMax(minX, minY, maxX, maxY); - } } } diff --git a/source/src/Math/Vector2.ts b/source/src/Math/Vector2.ts index de4afad7..5123f2a9 100644 --- a/source/src/Math/Vector2.ts +++ b/source/src/Math/Vector2.ts @@ -1,77 +1,37 @@ module es { /** 2d 向量 */ export class Vector2 { - public x: number = 0; - public y: number = 0; - private static readonly unitYVector = new Vector2(0, 1); private static readonly unitXVector = new Vector2(1, 0); private static readonly unitVector2 = new Vector2(1, 1); private static readonly zeroVector2 = new Vector2(0, 0); - public static get zero(){ - return Vector2.zeroVector2; - } - - public static get one(){ - return Vector2.unitVector2; - } - - public static get unitX(){ - return Vector2.unitXVector; - } - - public static get unitY(){ - return Vector2.unitYVector; - } + public x: number = 0; + public y: number = 0; /** * 从两个值构造一个带有X和Y的二维向量。 * @param x 二维空间中的x坐标 * @param y 二维空间的y坐标 */ - constructor(x? : number, y?: number){ + constructor(x?: number, y?: number) { this.x = x ? x : 0; this.y = y ? y : this.x; } - /** - * - * @param value - */ - public add(value: Vector2): Vector2{ - this.x += value.x; - this.y += value.y; - return this; + public static get zero() { + return Vector2.zeroVector2; } - /** - * - * @param value - */ - public divide(value: Vector2): Vector2{ - this.x /= value.x; - this.y /= value.y; - return this; + public static get one() { + return Vector2.unitVector2; } - /** - * - * @param value - */ - public multiply(value: Vector2): Vector2{ - this.x *= value.x; - this.y *= value.y; - return this; + public static get unitX() { + return Vector2.unitXVector; } - /** - * - * @param value - */ - public subtract(value: Vector2){ - this.x -= value.x; - this.y -= value.y; - return this; + public static get unitY() { + return Vector2.unitYVector; } /** @@ -79,7 +39,7 @@ module es { * @param value1 * @param value2 */ - public static add(value1: Vector2, value2: Vector2){ + public static add(value1: Vector2, value2: Vector2) { let result: Vector2 = new Vector2(0, 0); result.x = value1.x + value2.x; result.y = value1.y + value2.y; @@ -91,7 +51,7 @@ module es { * @param value1 * @param value2 */ - public static divide(value1: Vector2, value2: Vector2){ + public static divide(value1: Vector2, value2: Vector2) { let result: Vector2 = new Vector2(0, 0); result.x = value1.x / value2.x; result.y = value1.y / value2.y; @@ -103,7 +63,7 @@ module es { * @param value1 * @param value2 */ - public static multiply(value1: Vector2, value2: Vector2){ + public static multiply(value1: Vector2, value2: Vector2) { let result: Vector2 = new Vector2(0, 0); result.x = value1.x * value2.x; result.y = value1.y * value2.y; @@ -115,36 +75,19 @@ module es { * @param value1 * @param value2 */ - public static subtract(value1: Vector2, value2: Vector2){ + public static subtract(value1: Vector2, value2: Vector2) { let result: Vector2 = new Vector2(0, 0); result.x = value1.x - value2.x; result.y = value1.y - value2.y; return result; } - /** 变成一个方向相同的单位向量 */ - public normalize(){ - let val = 1 / Math.sqrt((this.x * this.x) + (this.y * this.y)); - this.x *= val; - this.y *= val; - } - - /** 返回它的长度 */ - public length(){ - return Math.sqrt((this.x * this.x) + (this.y * this.y)); - } - - /** 对x和y值四舍五入 */ - public round(): Vector2{ - return new Vector2(Math.round(this.x), Math.round(this.y)); - } - /** * 创建一个新的Vector2 * 它包含来自另一个向量的标准化值。 * @param value */ - public static normalize(value: Vector2){ + public static normalize(value: Vector2) { let val = 1 / Math.sqrt((value.x * value.x) + (value.y * value.y)); value.x *= val; value.y *= val; @@ -156,7 +99,7 @@ module es { * @param value1 * @param value2 */ - public static dot(value1: Vector2, value2: Vector2): number{ + public static dot(value1: Vector2, value2: Vector2): number { return (value1.x * value2.x) + (value1.y * value2.y); } @@ -165,7 +108,7 @@ module es { * @param value1 * @param value2 */ - public static distanceSquared(value1: Vector2, value2: Vector2){ + public static distanceSquared(value1: Vector2, value2: Vector2) { let v1 = value1.x - value2.x, v2 = value1.y - value2.y; return (v1 * v1) + (v2 * v2); } @@ -176,7 +119,7 @@ module es { * @param min * @param max */ - public static clamp(value1: Vector2, min: Vector2, max: Vector2){ + public static clamp(value1: Vector2, min: Vector2, max: Vector2) { return new Vector2(MathHelper.clamp(value1.x, min.x, max.x), MathHelper.clamp(value1.y, min.y, max.y)); } @@ -187,7 +130,7 @@ module es { * @param value2 第二个向量 * @param amount 权重值(0.0到1.0之间) */ - public static lerp(value1: Vector2, value2: Vector2, amount: number){ + public static lerp(value1: Vector2, value2: Vector2, amount: number) { return new Vector2(MathHelper.lerp(value1.x, value2.x, amount), MathHelper.lerp(value1.y, value2.y, amount)); } @@ -196,7 +139,7 @@ module es { * @param position * @param matrix */ - public static transform(position: Vector2, matrix: Matrix2D){ + public static transform(position: Vector2, matrix: Matrix2D) { return new Vector2((position.x * matrix.m11) + (position.y * matrix.m21) + matrix.m31, (position.x * matrix.m12) + (position.y * matrix.m22) + matrix.m32); } @@ -206,7 +149,7 @@ module es { * @param value1 * @param value2 */ - public static distance(value1: Vector2, value2: Vector2){ + public static distance(value1: Vector2, value2: Vector2) { let v1 = value1.x - value2.x, v2 = value1.y - value2.y; return Math.sqrt((v1 * v1) + (v2 * v2)); } @@ -215,7 +158,7 @@ module es { * 矢量反演的结果 * @param value */ - public static negate(value: Vector2){ + public static negate(value: Vector2) { let result: Vector2 = new Vector2(); result.x = -value.x; result.y = -value.y; @@ -223,7 +166,64 @@ module es { return result; } - public equals(other: Vector2){ + /** + * + * @param value + */ + public add(value: Vector2): Vector2 { + this.x += value.x; + this.y += value.y; + return this; + } + + /** + * + * @param value + */ + public divide(value: Vector2): Vector2 { + this.x /= value.x; + this.y /= value.y; + return this; + } + + /** + * + * @param value + */ + public multiply(value: Vector2): Vector2 { + this.x *= value.x; + this.y *= value.y; + return this; + } + + /** + * + * @param value + */ + public subtract(value: Vector2) { + this.x -= value.x; + this.y -= value.y; + return this; + } + + /** 变成一个方向相同的单位向量 */ + public normalize() { + let val = 1 / Math.sqrt((this.x * this.x) + (this.y * this.y)); + this.x *= val; + this.y *= val; + } + + /** 返回它的长度 */ + public length() { + return Math.sqrt((this.x * this.x) + (this.y * this.y)); + } + + /** 对x和y值四舍五入 */ + public round(): Vector2 { + return new Vector2(Math.round(this.x), Math.round(this.y)); + } + + public equals(other: Vector2) { return other.x == this.x && other.y == this.y; } } diff --git a/source/src/Math/Vector3.ts b/source/src/Math/Vector3.ts index 72f627c7..c22878d2 100644 --- a/source/src/Math/Vector3.ts +++ b/source/src/Math/Vector3.ts @@ -4,7 +4,7 @@ module es { public y: number; public z: number; - constructor(x: number, y: number, z: number){ + constructor(x: number, y: number, z: number) { this.x = x; this.y = y; this.z = z; diff --git a/source/src/Physics/ColliderTriggerHelper.ts b/source/src/Physics/ColliderTriggerHelper.ts index 4496d54d..4dd0c985 100644 --- a/source/src/Physics/ColliderTriggerHelper.ts +++ b/source/src/Physics/ColliderTriggerHelper.ts @@ -50,8 +50,8 @@ module es { this.checkForExitedColliders(); } - private checkForExitedColliders(){ - for (let i = 0; i < this._activeTriggerIntersections.length; i ++){ + private checkForExitedColliders() { + for (let i = 0; i < this._activeTriggerIntersections.length; i++) { let index = this._previousTriggerIntersections.findIndex(value => { if (value.first == this._activeTriggerIntersections[i].first && value.second == this._activeTriggerIntersections[i].second) return true; @@ -62,12 +62,12 @@ module es { this._previousTriggerIntersections.removeAt(index); } - for (let i = 0; i < this._previousTriggerIntersections.length; i ++){ + for (let i = 0; i < this._previousTriggerIntersections.length; i++) { this.notifyTriggerListeners(this._previousTriggerIntersections[i], false) } this._previousTriggerIntersections.length = 0; - for (let i = 0; i < this._activeTriggerIntersections.length; i ++){ - if (!this._previousTriggerIntersections.contains(this._activeTriggerIntersections[i])){ + for (let i = 0; i < this._activeTriggerIntersections.length; i++) { + if (!this._previousTriggerIntersections.contains(this._activeTriggerIntersections[i])) { this._previousTriggerIntersections.push(this._activeTriggerIntersections[i]); } } @@ -76,8 +76,8 @@ module es { private notifyTriggerListeners(collisionPair: Pair, isEntering: boolean) { collisionPair.first.entity.getComponents("ITriggerListener", this._tempTriggerList); - for (let i = 0; i < this._tempTriggerList.length; i ++){ - if (isEntering){ + for (let i = 0; i < this._tempTriggerList.length; i++) { + if (isEntering) { this._tempTriggerList[i].onTriggerEnter(collisionPair.second, collisionPair.first); } else { this._tempTriggerList[i].onTriggerExit(collisionPair.second, collisionPair.first); @@ -85,10 +85,10 @@ module es { this._tempTriggerList.length = 0; - if (collisionPair.second.entity){ + if (collisionPair.second.entity) { collisionPair.second.entity.getComponents("ITriggerListener", this._tempTriggerList); - for (let i = 0; i < this._tempTriggerList.length; i ++){ - if (isEntering){ + for (let i = 0; i < this._tempTriggerList.length; i++) { + if (isEntering) { this._tempTriggerList[i].onTriggerEnter(collisionPair.first, collisionPair.second); } else { this._tempTriggerList[i].onTriggerExit(collisionPair.first, collisionPair.second); diff --git a/source/src/Physics/Collision.ts b/source/src/Physics/Collision.ts index 06b14bf5..dc82e398 100644 --- a/source/src/Physics/Collision.ts +++ b/source/src/Physics/Collision.ts @@ -88,42 +88,42 @@ module es { return vx * vx + vy * vy < cRadius * cRadius; } - public static isRectToLine(rect: Rectangle, lineFrom: Vector2, lineTo: Vector2){ + public static isRectToLine(rect: Rectangle, lineFrom: Vector2, lineTo: Vector2) { let fromSector = this.getSector(rect.x, rect.y, rect.width, rect.height, lineFrom); let toSector = this.getSector(rect.x, rect.y, rect.width, rect.height, lineTo); - if (fromSector == PointSectors.center || toSector == PointSectors.center){ + if (fromSector == PointSectors.center || toSector == PointSectors.center) { return true; - } else if((fromSector & toSector) != 0){ + } else if ((fromSector & toSector) != 0) { return false; - } else{ + } else { let both = fromSector | toSector; // 线对边进行检查 let edgeFrom: Vector2; let edgeTo: Vector2; - if ((both & PointSectors.top) != 0){ + if ((both & PointSectors.top) != 0) { edgeFrom = new Vector2(rect.x, rect.y); edgeTo = new Vector2(rect.x + rect.width, rect.y); if (this.isLineToLine(edgeFrom, edgeTo, lineFrom, lineTo)) return true; } - if ((both & PointSectors.bottom) != 0){ + if ((both & PointSectors.bottom) != 0) { edgeFrom = new Vector2(rect.x, rect.y + rect.height); edgeTo = new Vector2(rect.x + rect.width, rect.y + rect.height); if (this.isLineToLine(edgeFrom, edgeTo, lineFrom, lineTo)) return true; } - if ((both & PointSectors.left) != 0){ + if ((both & PointSectors.left) != 0) { edgeFrom = new Vector2(rect.x, rect.y); edgeTo = new Vector2(rect.x, rect.y + rect.height); if (this.isLineToLine(edgeFrom, edgeTo, lineFrom, lineTo)) return true; } - if ((both & PointSectors.right) != 0){ + if ((both & PointSectors.right) != 0) { edgeFrom = new Vector2(rect.x + rect.width, rect.y); edgeTo = new Vector2(rect.x + rect.width, rect.y + rect.height); if (this.isLineToLine(edgeFrom, edgeTo, lineFrom, lineTo)) diff --git a/source/src/Physics/Physics.ts b/source/src/Physics/Physics.ts index 7704aacd..05b17fed 100644 --- a/source/src/Physics/Physics.ts +++ b/source/src/Physics/Physics.ts @@ -1,19 +1,19 @@ module es { export class Physics { - private static _spatialHash: SpatialHash; /** 调用reset并创建一个新的SpatialHash时使用的单元格大小 */ public static spatialHashCellSize = 100; /** 接受layerMask的所有方法的默认值 */ public static readonly allLayers: number = -1; + private static _spatialHash: SpatialHash; - public static reset(){ + public static reset() { this._spatialHash = new SpatialHash(this.spatialHashCellSize); } /** * 从SpatialHash中移除所有碰撞器 */ - public static clear(){ + public static clear() { this._spatialHash.clear(); } @@ -24,8 +24,8 @@ module es { * @param results * @param layerMask */ - public static overlapCircleAll(center: Vector2, randius: number, results: any[], layerMask = -1){ - if (results.length == 0){ + public static overlapCircleAll(center: Vector2, randius: number, results: any[], layerMask = -1) { + if (results.length == 0) { console.error("An empty results array was passed in. No results will ever be returned."); return; } @@ -38,7 +38,7 @@ module es { * @param rect * @param layerMask */ - public static boxcastBroadphase(rect: Rectangle, layerMask: number = this.allLayers){ + public static boxcastBroadphase(rect: Rectangle, layerMask: number = this.allLayers) { return this._spatialHash.aabbBroadphase(rect, null, layerMask); } @@ -48,7 +48,7 @@ module es { * @param rect * @param layerMask */ - public static boxcastBroadphaseExcludingSelf(collider: Collider, rect: Rectangle, layerMask = this.allLayers){ + public static boxcastBroadphaseExcludingSelf(collider: Collider, rect: Rectangle, layerMask = this.allLayers) { return this._spatialHash.aabbBroadphase(rect, collider, layerMask); } @@ -56,7 +56,7 @@ module es { * 将对撞机添加到物理系统中 * @param collider */ - public static addCollider(collider: Collider){ + public static addCollider(collider: Collider) { Physics._spatialHash.register(collider); } @@ -64,7 +64,7 @@ module es { * 从物理系统中移除对撞机 * @param collider */ - public static removeCollider(collider: Collider){ + public static removeCollider(collider: Collider) { Physics._spatialHash.remove(collider); } @@ -72,7 +72,7 @@ module es { * 更新物理系统中对撞机的位置。这实际上只是移除然后重新添加带有新边界的碰撞器 * @param collider */ - public static updateCollider(collider: Collider){ + public static updateCollider(collider: Collider) { this._spatialHash.remove(collider); this._spatialHash.register(collider); } @@ -81,7 +81,7 @@ module es { * debug绘制空间散列的内容 * @param secondsToDisplay */ - public static debugDraw(secondsToDisplay){ + public static debugDraw(secondsToDisplay) { this._spatialHash.debugDraw(secondsToDisplay, 2); } } diff --git a/source/src/Physics/Shapes/Box.ts b/source/src/Physics/Shapes/Box.ts index afcc3e54..34705372 100644 --- a/source/src/Physics/Shapes/Box.ts +++ b/source/src/Physics/Shapes/Box.ts @@ -7,7 +7,7 @@ module es { public width: number; public height: number; - constructor(width: number, height: number){ + constructor(width: number, height: number) { super(Box.buildBox(width, height), true); this.width = width; this.height = height; @@ -18,7 +18,7 @@ module es { * @param width * @param height */ - private static buildBox(width: number, height: number): Vector2[]{ + private static buildBox(width: number, height: number): Vector2[] { // 我们在(0,0)的中心周围创建点 let halfWidth = width / 2; let halfHeight = height / 2; @@ -36,7 +36,7 @@ module es { * @param width * @param height */ - public updateBox(width: number, height: number){ + public updateBox(width: number, height: number) { this.width = width; this.height = height; @@ -49,13 +49,13 @@ module es { this.points[2] = new Vector2(halfWidth, halfHeight); this.points[3] = new Vector2(-halfWidth, halfHeight); - for (let i = 0; i < this.points.length; i ++) + for (let i = 0; i < this.points.length; i++) this._originalPoints[i] = this.points[i]; } - public overlaps(other: Shape){ + public overlaps(other: Shape) { // 特殊情况,这一个高性能方式实现,其他情况则使用polygon方法检测 - if (this.isUnrotated){ + if (this.isUnrotated) { if (other instanceof Box) return this.bounds.intersects(other.bounds); @@ -66,9 +66,9 @@ module es { return super.overlaps(other); } - public collidesWithShape(other: Shape, result: CollisionResult): boolean{ + public collidesWithShape(other: Shape, result: CollisionResult): boolean { // 特殊情况,这一个高性能方式实现,其他情况则使用polygon方法检测 - if (other instanceof Box && (other as Box).isUnrotated){ + if (other instanceof Box && (other as Box).isUnrotated) { return ShapeCollisions.boxToBox(this, other, result); } @@ -77,7 +77,7 @@ module es { return super.collidesWithShape(other, result); } - public containsPoint(point: Vector2){ + public containsPoint(point: Vector2) { if (this.isUnrotated) return this.bounds.contains(point.x, point.y); diff --git a/source/src/Physics/Shapes/CollisionResult.ts b/source/src/Physics/Shapes/CollisionResult.ts index 50a78dcc..7897c7e0 100644 --- a/source/src/Physics/Shapes/CollisionResult.ts +++ b/source/src/Physics/Shapes/CollisionResult.ts @@ -5,7 +5,7 @@ module es { public normal: Vector2 = Vector2.zero; public point: Vector2 = Vector2.zero; - public invertResult(){ + public invertResult() { this.minimumTranslationVector = Vector2.negate(this.minimumTranslationVector); this.normal = Vector2.negate(this.normal); } diff --git a/source/src/Physics/Shapes/Polygon.ts b/source/src/Physics/Shapes/Polygon.ts index 21c41595..23fc8022 100644 --- a/source/src/Physics/Shapes/Polygon.ts +++ b/source/src/Physics/Shapes/Polygon.ts @@ -9,19 +9,7 @@ module es { * 保持顺时针与凸边形 */ public points: Vector2[]; - - /** - * 边缘法线用于SAT碰撞检测。缓存它们用于避免squareRoots - * box只有两个边缘 因为其他两边是平行的 - */ - public get edgeNormals(){ - if (this._areEdgeNormalsDirty) - this.buildEdgeNormals(); - return this._edgeNormals; - } - public _areEdgeNormalsDirty = true; - public _edgeNormals: Vector2[]; /** * 多边形的原始数据 */ @@ -39,61 +27,25 @@ module es { * @param points * @param isBox */ - constructor(points: Vector2[], isBox?: boolean){ + constructor(points: Vector2[], isBox?: boolean) { super(); this.setPoints(points); this.isBox = isBox; } - /** - * 重置点并重新计算中心和边缘法线 - * @param points - */ - public setPoints(points: Vector2[]) { - this.points = points; - this.recalculateCenterAndEdgeNormals(); - - this._originalPoints = []; - for (let i = 0; i < this.points.length; i ++){ - this._originalPoints.push(this.points[i]); - } - } + public _edgeNormals: Vector2[]; /** - * 重新计算多边形中心 - * 如果点数改变必须调用该方法 + * 边缘法线用于SAT碰撞检测。缓存它们用于避免squareRoots + * box只有两个边缘 因为其他两边是平行的 */ - public recalculateCenterAndEdgeNormals() { - this._polygonCenter = Polygon.findPolygonCenter(this.points); - this._areEdgeNormalsDirty = true; + public get edgeNormals() { + if (this._areEdgeNormalsDirty) + this.buildEdgeNormals(); + return this._edgeNormals; } - /** - * 建立多边形边缘法线 - * 它们仅由edgeNormals getter惰性创建和更新 - */ - public buildEdgeNormals(){ - // 对于box 我们只需要两条边,因为另外两条边是平行的 - let totalEdges = this.isBox ? 2 : this.points.length; - if (this._edgeNormals == null || this._edgeNormals.length != totalEdges) - this._edgeNormals = new Array(totalEdges); - - let p2: Vector2; - for (let i = 0; i < totalEdges; i ++){ - let p1 = this.points[i]; - if (i + 1 >= this.points.length) - p2 = this.points[0]; - else - p2 = this.points[i + 1]; - - let perp = Vector2Ext.perpendicular(p1, p2); - perp = Vector2.normalize(perp); - this._edgeNormals[i] = perp; - } - } - - /** * 建立一个对称的多边形(六边形,八角形,n角形)并返回点 * @param vertCount @@ -114,9 +66,9 @@ module es { * 重定位多边形的点 * @param points */ - public static recenterPolygonVerts(points: Vector2[]){ + public static recenterPolygonVerts(points: Vector2[]) { let center = this.findPolygonCenter(points); - for (let i = 0; i < points.length; i ++) + for (let i = 0; i < points.length; i++) points[i] = Vector2.subtract(points[i], center); } @@ -173,16 +125,63 @@ module es { return closestPoint; } - public recalculateBounds(collider: Collider){ + /** + * 重置点并重新计算中心和边缘法线 + * @param points + */ + public setPoints(points: Vector2[]) { + this.points = points; + this.recalculateCenterAndEdgeNormals(); + + this._originalPoints = []; + for (let i = 0; i < this.points.length; i++) { + this._originalPoints.push(this.points[i]); + } + } + + /** + * 重新计算多边形中心 + * 如果点数改变必须调用该方法 + */ + public recalculateCenterAndEdgeNormals() { + this._polygonCenter = Polygon.findPolygonCenter(this.points); + this._areEdgeNormalsDirty = true; + } + + /** + * 建立多边形边缘法线 + * 它们仅由edgeNormals getter惰性创建和更新 + */ + public buildEdgeNormals() { + // 对于box 我们只需要两条边,因为另外两条边是平行的 + let totalEdges = this.isBox ? 2 : this.points.length; + if (this._edgeNormals == null || this._edgeNormals.length != totalEdges) + this._edgeNormals = new Array(totalEdges); + + let p2: Vector2; + for (let i = 0; i < totalEdges; i++) { + let p1 = this.points[i]; + if (i + 1 >= this.points.length) + p2 = this.points[0]; + else + p2 = this.points[i + 1]; + + let perp = Vector2Ext.perpendicular(p1, p2); + perp = Vector2.normalize(perp); + this._edgeNormals[i] = perp; + } + } + + public recalculateBounds(collider: Collider) { // 如果我们没有旋转或不关心TRS我们使用localOffset作为中心,我们会从那开始 this.center = collider.localOffset; - if (collider.shouldColliderScaleAndRotateWithTransform){ + if (collider.shouldColliderScaleAndRotateWithTransform) { let hasUnitScale = true; let tempMat: Matrix2D; let combinedMatrix = Matrix2D.create().translate(-this._polygonCenter.x, -this._polygonCenter.y); - if (collider.entity.transform.scale != Vector2.zero){ + if (collider.entity.transform.scale != Vector2.zero) { tempMat = Matrix2D.create().scale(collider.entity.transform.scale.x, collider.entity.transform.scale.y); combinedMatrix = combinedMatrix.multiply(tempMat); hasUnitScale = false; @@ -191,7 +190,7 @@ module es { this.center = Vector2.multiply(collider.localOffset, collider.entity.transform.scale); } - if (collider.entity.transform.rotation != 0){ + if (collider.entity.transform.rotation != 0) { tempMat = Matrix2D.create().rotate(collider.entity.transform.rotation); combinedMatrix = combinedMatrix.multiply(tempMat); @@ -222,13 +221,13 @@ module es { this.bounds.location = this.bounds.location.add(this.position); } - public overlaps(other: Shape){ + public overlaps(other: Shape) { let result: CollisionResult = new CollisionResult(); if (other instanceof Polygon) return ShapeCollisions.polygonToPolygon(this, other, result); - if (other instanceof Circle){ - if (ShapeCollisions.circleToPolygon(other, this, result)){ + if (other instanceof Circle) { + if (ShapeCollisions.circleToPolygon(other, this, result)) { result.invertResult(); return true; } @@ -239,13 +238,13 @@ module es { throw new Error(`overlaps of Pologon to ${other} are not supported`); } - public collidesWithShape(other: Shape, result: CollisionResult): boolean{ - if (other instanceof Polygon){ + public collidesWithShape(other: Shape, result: CollisionResult): boolean { + if (other instanceof Polygon) { return ShapeCollisions.polygonToPolygon(this, other, result); } - if (other instanceof Circle){ - if (ShapeCollisions.circleToPolygon(other, this, result)){ + if (other instanceof Circle) { + if (ShapeCollisions.circleToPolygon(other, this, result)) { result.invertResult(); return true; } diff --git a/source/src/Physics/Shapes/Shape.ts b/source/src/Physics/Shapes/Shape.ts index 5c7b81e1..b474dace 100644 --- a/source/src/Physics/Shapes/Shape.ts +++ b/source/src/Physics/Shapes/Shape.ts @@ -16,11 +16,14 @@ module es { public bounds: Rectangle; public abstract recalculateBounds(collider: Collider); + public abstract overlaps(other: Shape): boolean; + public abstract collidesWithShape(other: Shape, collisionResult: CollisionResult): boolean; + public abstract pointCollidesWithShape(point: Vector2, result: CollisionResult): boolean; - public clone(): Shape{ + public clone(): Shape { return ObjectUtils.clone(this); } } diff --git a/source/src/Physics/Shapes/ShapeCollisions/ShapeCollisions.ts b/source/src/Physics/Shapes/ShapeCollisions/ShapeCollisions.ts index 8c81309b..072073b9 100644 --- a/source/src/Physics/Shapes/ShapeCollisions/ShapeCollisions.ts +++ b/source/src/Physics/Shapes/ShapeCollisions/ShapeCollisions.ts @@ -108,7 +108,7 @@ module es { } } - return { min: min, max: max }; + return {min: min, max: max}; } /** @@ -245,11 +245,11 @@ module es { * @param first * @param second */ - public static circleToCircle(first: Circle, second: Circle, result: CollisionResult): boolean{ + public static circleToCircle(first: Circle, second: Circle, result: CollisionResult): boolean { let distanceSquared = Vector2.distanceSquared(first.position, second.position); let sumOfRadii = first.radius + second.radius; let collided = distanceSquared < sumOfRadii * sumOfRadii; - if (collided){ + if (collided) { result.normal = Vector2.normalize(Vector2.subtract(first.position, second.position)); let depth = sumOfRadii - Math.sqrt(distanceSquared); result.minimumTranslationVector = Vector2.multiply(new Vector2(-depth), result.normal); @@ -267,9 +267,9 @@ module es { * @param second * @param result */ - public static boxToBox(first: Box, second: Box, result: CollisionResult): boolean{ + public static boxToBox(first: Box, second: Box, result: CollisionResult): boolean { let minkowskiDiff = this.minkowskiDifference(first, second); - if (minkowskiDiff.contains(0, 0)){ + if (minkowskiDiff.contains(0, 0)) { // 计算MTV。如果它是零,我们就可以称它为非碰撞 result.minimumTranslationVector = minkowskiDiff.getClosestPointOnBoundsToOrigin(); @@ -285,7 +285,7 @@ module es { return false; } - private static minkowskiDifference(first: Box, second: Box){ + private static minkowskiDifference(first: Box, second: Box) { // 我们需要第一个框的左上角 // 碰撞器只会修改运动的位置所以我们需要用位置来计算出运动是什么。 let positionOffset = Vector2.subtract(first.position, Vector2.add(first.bounds.location, Vector2.divide(first.bounds.size, new Vector2(2)))); diff --git a/source/src/Physics/Verlet/SpatialHash.ts b/source/src/Physics/Verlet/SpatialHash.ts index 2fef18cc..22b5ca7e 100644 --- a/source/src/Physics/Verlet/SpatialHash.ts +++ b/source/src/Physics/Verlet/SpatialHash.ts @@ -30,33 +30,6 @@ module es { this._raycastParser = new RaycastResultParser(); } - /** - * 获取单元格的x,y值作为世界空间的x,y值 - * @param x - * @param y - */ - private cellCoords(x: number, y: number): Vector2 { - return new Vector2(Math.floor(x * this._inverseCellSize), Math.floor(y * this._inverseCellSize)); - } - - /** - * 获取世界空间x,y值的单元格。 - * 如果单元格为空且createCellIfEmpty为true,则会创建一个新的单元格 - * @param x - * @param y - * @param createCellIfEmpty - */ - private cellAtPosition(x: number, y: number, createCellIfEmpty: boolean = false) { - let cell: Collider[] = this._cellDict.tryGetValue(x, y); - if (!cell) { - if (createCellIfEmpty) { - cell = []; - this._cellDict.add(x, y, cell); - } - } - return cell; - } - /** * 将对象添加到SpatialHash * @param collider @@ -111,11 +84,11 @@ module es { * 使用蛮力方法从SpatialHash中删除对象 * @param obj */ - public removeWithBruteForce(obj: Collider){ + public removeWithBruteForce(obj: Collider) { this._cellDict.remove(obj); } - public clear(){ + public clear() { this._cellDict.clear(); } @@ -124,9 +97,9 @@ module es { * @param secondsToDisplay * @param textScale */ - public debugDraw(secondsToDisplay: number, textScale: number = 1){ - for (let x = this.gridBounds.x; x <= this.gridBounds.right; x ++){ - for (let y = this.gridBounds.y; y <= this.gridBounds.bottom; y ++){ + public debugDraw(secondsToDisplay: number, textScale: number = 1) { + for (let x = this.gridBounds.x; x <= this.gridBounds.right; x++) { + for (let y = this.gridBounds.y; y <= this.gridBounds.bottom; y++) { let cell = this.cellAtPosition(x, y); if (cell && cell.length > 0) this.debugDrawCellDetails(x, y, cell.length, secondsToDisplay, textScale); @@ -134,17 +107,13 @@ module es { } } - private debugDrawCellDetails(x: number, y: number, cellCount: number, secondsToDisplay = 0.5, textScale = 1){ - - } - /** * 返回边框与单元格相交的所有对象 * @param bounds * @param excludeCollider * @param layerMask */ - public aabbBroadphase(bounds: Rectangle, excludeCollider: Collider, layerMask: number) : Collider[]{ + public aabbBroadphase(bounds: Rectangle, excludeCollider: Collider, layerMask: number): Collider[] { this._tempHashSet.length = 0; let p1 = this.cellCoords(bounds.x, bounds.y); @@ -164,7 +133,7 @@ module es { if (collider == excludeCollider || !Flags.isFlagSet(layerMask, collider.physicsLayer)) continue; - if (bounds.intersects(collider.bounds)){ + if (bounds.intersects(collider.bounds)) { if (this._tempHashSet.indexOf(collider) == -1) this._tempHashSet.push(collider); } @@ -196,14 +165,14 @@ module es { results[resultCounter] = collider; resultCounter++; } else if (collider instanceof CircleCollider) { - if (collider.shape.overlaps(this._overlapTestCircle)){ + if (collider.shape.overlaps(this._overlapTestCircle)) { results[resultCounter] = collider; - resultCounter ++; + resultCounter++; } - } else if(collider instanceof PolygonCollider) { - if (collider.shape.overlaps(this._overlapTestCircle)){ + } else if (collider instanceof PolygonCollider) { + if (collider.shape.overlaps(this._overlapTestCircle)) { results[resultCounter] = collider; - resultCounter ++; + resultCounter++; } } else { throw new Error("overlapCircle against this collider type is not implemented!"); @@ -216,6 +185,37 @@ module es { return resultCounter; } + + /** + * 获取单元格的x,y值作为世界空间的x,y值 + * @param x + * @param y + */ + private cellCoords(x: number, y: number): Vector2 { + return new Vector2(Math.floor(x * this._inverseCellSize), Math.floor(y * this._inverseCellSize)); + } + + /** + * 获取世界空间x,y值的单元格。 + * 如果单元格为空且createCellIfEmpty为true,则会创建一个新的单元格 + * @param x + * @param y + * @param createCellIfEmpty + */ + private cellAtPosition(x: number, y: number, createCellIfEmpty: boolean = false) { + let cell: Collider[] = this._cellDict.tryGetValue(x, y); + if (!cell) { + if (createCellIfEmpty) { + cell = []; + this._cellDict.add(x, y, cell); + } + } + return cell; + } + + private debugDrawCellDetails(x: number, y: number, cellCount: number, secondsToDisplay = 0.5, textScale = 1) { + + } } /** @@ -225,15 +225,6 @@ module es { export class NumberDictionary { public _store: Map = new Map(); - /** - * 根据x和y值计算并返回散列键 - * @param x - * @param y - */ - private getKey(x: number, y: number): string { - return Long.fromNumber(x).shiftLeft(32).or(Long.fromNumber(y, true)).toString(); - } - public add(x: number, y: number, list: Collider[]) { this._store.set(this.getKey(x, y), list); } @@ -259,6 +250,15 @@ module es { public clear() { this._store.clear(); } + + /** + * 根据x和y值计算并返回散列键 + * @param x + * @param y + */ + private getKey(x: number, y: number): string { + return Long.fromNumber(x).shiftLeft(32).or(Long.fromNumber(y, true)).toString(); + } } export class RaycastResultParser { diff --git a/source/src/Utils/Analysis/Layout.ts b/source/src/Utils/Analysis/Layout.ts index 052dca9c..dc9468c9 100644 --- a/source/src/Utils/Analysis/Layout.ts +++ b/source/src/Utils/Analysis/Layout.ts @@ -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 { } diff --git a/source/src/Utils/Analysis/Stopwatch.ts b/source/src/Utils/Analysis/Stopwatch.ts index 330b47b4..2b630d29 100644 --- a/source/src/Utils/Analysis/Stopwatch.ts +++ b/source/src/Utils/Analysis/Stopwatch.ts @@ -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 { } } } - + /** * 返回某个系统的“当前时间”的函数。 * 惟一的要求是,对该函数的每次调用都必须返回一个大于或等于前一次对该函数的调用的数字。 diff --git a/source/src/Utils/Analysis/TimeRuler.ts b/source/src/Utils/Analysis/TimeRuler.ts index d90b9b27..696b1971 100644 --- a/source/src/Utils/Analysis/TimeRuler.ts +++ b/source/src/Utils/Analysis/TimeRuler.ts @@ -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(TimeRuler.maxNestCall); public nestCount: number = 0; - constructor(){ + constructor() { this.markers.fill(new Marker(), 0, TimeRuler.maxSamples); this.markerNests.fill(0, 0, TimeRuler.maxNestCall); } diff --git a/source/src/Utils/ArrayUtils.ts b/source/src/Utils/ArrayUtils.ts index c2c256ed..be6ecd6b 100644 --- a/source/src/Utils/ArrayUtils.ts +++ b/source/src/Utils/ArrayUtils.ts @@ -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 { diff --git a/source/src/Utils/Base64Utils.ts b/source/src/Utils/Base64Utils.ts index 7aad324e..5586731d 100644 --- a/source/src/Utils/Base64Utils.ts +++ b/source/src/Utils/Base64Utils.ts @@ -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; diff --git a/source/src/Utils/DrawUtils.ts b/source/src/Utils/DrawUtils.ts index 2ae27506..14332ad5 100644 --- a/source/src/Utils/DrawUtils.ts +++ b/source/src/Utils/DrawUtils.ts @@ -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, diff --git a/source/src/Utils/Emitter.ts b/source/src/Utils/Emitter.ts index 51e772cc..2d469a9a 100644 --- a/source/src/Utils/Emitter.ts +++ b/source/src/Utils/Emitter.ts @@ -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 { private _messageTable: Map; - constructor(){ + constructor() { this._messageTable = new Map(); } @@ -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); } } diff --git a/source/src/Utils/GlobalManager.ts b/source/src/Utils/GlobalManager.ts index fc6d520d..f4799309 100644 --- a/source/src/Utils/GlobalManager.ts +++ b/source/src/Utils/GlobalManager.ts @@ -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() { + } } } diff --git a/source/src/Utils/Input.ts b/source/src/Utils/Input.ts index c6500199..7dc5e8ee 100644 --- a/source/src/Utils/Input.ts +++ b/source/src/Utils/Input.ts @@ -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); - } } } diff --git a/source/src/Utils/KeyboardUtils.ts b/source/src/Utils/KeyboardUtils.ts index 76bd8cfd..3083301e 100644 --- a/source/src/Utils/KeyboardUtils.ts +++ b/source/src/Utils/KeyboardUtils.ts @@ -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); - } } \ No newline at end of file diff --git a/source/src/Utils/ListPool.ts b/source/src/Utils/ListPool.ts index f40a6dc2..acf5ea85 100644 --- a/source/src/Utils/ListPool.ts +++ b/source/src/Utils/ListPool.ts @@ -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(obj: Array){ + public static free(obj: Array) { this._objectQueue.unshift(obj); obj.length = 0; } diff --git a/source/src/Utils/LockUtils.ts b/source/src/Utils/LockUtils.ts index a95206c3..85604eea 100644 --- a/source/src/Utils/LockUtils.ts +++ b/source/src/Utils/LockUtils.ts @@ -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; diff --git a/source/src/Utils/Pair.ts b/source/src/Utils/Pair.ts index f11e98bf..69fb5a89 100644 --- a/source/src/Utils/Pair.ts +++ b/source/src/Utils/Pair.ts @@ -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){ + public equals(other: Pair) { return this.first == other.first && this.second == other.second; } } diff --git a/source/src/Utils/RandomUtils.ts b/source/src/Utils/RandomUtils.ts index f67a3026..6aca63de 100644 --- a/source/src/Utils/RandomUtils.ts +++ b/source/src/Utils/RandomUtils.ts @@ -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]; } - /** * 对列表中的元素进行随机采æ ? *
@@ -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;
+    }
 }
\ No newline at end of file
diff --git a/source/src/Utils/RectangleExt.ts b/source/src/Utils/RectangleExt.ts
index 03eb3124..76b59fe8 100644
--- a/source/src/Utils/RectangleExt.ts
+++ b/source/src/Utils/RectangleExt.ts
@@ -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();
diff --git a/source/src/Utils/Triangulator.ts b/source/src/Utils/Triangulator.ts
index 2ec650c4..5ef8b370 100644
--- a/source/src/Utils/Triangulator.ts
+++ b/source/src/Utils/Triangulator.ts
@@ -11,12 +11,25 @@ module es {
         private _triPrev: number[] = new Array(12);
         private _triNext: number[] = new Array(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(Math.max(this._triNext.length * 2, count));
             }
-            if (this._triPrev.length < count){
+            if (this._triPrev.length < count) {
                 this._triPrev.reverse();
                 this._triPrev = new Array(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;
-        }
     }
 }
diff --git a/source/src/Utils/Vector2Ext.ts b/source/src/Utils/Vector2Ext.ts
index 60ee6a4d..2819d3fb 100644
--- a/source/src/Utils/Vector2Ext.ts
+++ b/source/src/Utils/Vector2Ext.ts
@@ -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));
         }
     }
diff --git a/source/src/Utils/WebGLUtils.ts b/source/src/Utils/WebGLUtils.ts
index ea776969..be82c9a5 100644
--- a/source/src/Utils/WebGLUtils.ts
+++ b/source/src/Utils/WebGLUtils.ts
@@ -2,7 +2,7 @@ class WebGLUtils {
     /**
      * 获取webgl context
      */
-    public static getContext(){
+    public static getContext() {
         const canvas = document.getElementsByTagName('canvas')[0];
         return canvas.getContext('2d');
     }
diff --git a/source/tsconfig.json b/source/tsconfig.json
index ea8f743c..90444d67 100644
--- a/source/tsconfig.json
+++ b/source/tsconfig.json
@@ -11,8 +11,8 @@
       "es5",
       "dom",
       "es2015.promise",
-      "es6",
-  ] ,
+      "es6"
+    ]
   },
   "include": [
     "src",