angry-pixel 2.0.21 → 2.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -3
- package/lib/index.cjs.js +1 -1
- package/lib/index.cjs.js.map +1 -1
- package/lib/index.d.ts +303 -92
- package/lib/index.esm.js +1 -1
- package/lib/index.esm.js.map +1 -1
- package/lib/index.js +1 -1
- package/lib/index.js.map +1 -1
- package/package.json +1 -1
package/lib/index.esm.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const t={AssetManager:Symbol.for("AssetManager"),CanvasElement:Symbol.for("CanvasElement"),CollisionRepository:Symbol.for("CollisionRepository"),CollisionBroadphaseResolver:Symbol.for("CollisionBroadphaseResolver"),CollisionResolutionMethod:Symbol.for("CollisionResolutionMethod"),CollisionAABBResolver:Symbol.for("CollisionAABBResolver"),CollisionCircumferenceAABBResolver:Symbol.for("CollisionCircumferenceAABBResolver"),CollisionCircumferenceResolver:Symbol.for("CollisionCircumferenceResolver"),CollisionSatResolver:Symbol.for("CollisionSatResolver"),CollisionMatrix:Symbol.for("CollisionMatrix"),CreateSystemService:Symbol.for("CreateSystemService"),EntityManager:Symbol.for("EntityManager"),GameConfig:Symbol.for("GameConfig"),InputManager:Symbol.for("InputManager"),LoopManager:Symbol.for("LoopManager"),RenderManager:Symbol.for("RenderManager"),SceneManager:Symbol.for("SceneManager"),SystemManager:Symbol.for("SystemManager"),TimeManager:Symbol.for("TimeManager"),WebGLManager:Symbol.for("WebGLManager")};class e{constructor(){this.instances=new Map,this.types=new Map}add(t,e){if(!e&&!t.prototype.__ioc_injectable)throw new Error(`Type ${t.name} is not injectable`);return this.types.set(null!=e?e:t.prototype.__ioc_injectable,t),this}set(t,e){return this.instances.set(t,e),this}get(t){var e,i;if(!this.instances.has(t)){const s=this.types.get(t);if(!s)throw new Error(`${t.toString()} is not a valid type`);const r=new s(...(null!==(e=s.prototype.__ioc_inject_constructor)&&void 0!==e?e:[]).map((t=>this.get(t))));(null!==(i=s.prototype.__ioc_inject_prop)&&void 0!==i?i:[]).forEach((([t,e])=>r[t]=this.get(e))),this.instances.set(t,r)}return this.instances.get(t)}has(t){return this.types.has(t)||this.instances.has(t)}}function i(t){return function(e){e.prototype.__ioc_injectable&&e.prototype.__ioc_injectable===t||(e.prototype.__ioc_injectable=t)}}function s(t){return function(e,i,s){void 0!==s?(e.prototype.__ioc_inject_constructor||(e.prototype.__ioc_inject_constructor=[]),e.prototype.__ioc_inject_constructor[s]=t):void 0!==i&&(e.constructor.prototype.__ioc_inject_prop||(e.constructor.prototype.__ioc_inject_prop=[]),e.constructor.prototype.__ioc_inject_prop.push([i,t]))}}var r;function o(t,e,i,s){var r,o=arguments.length,a=o<3?e:null===s?s=Object.getOwnPropertyDescriptor(e,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(t,e,i,s);else for(var n=t.length-1;n>=0;n--)(r=t[n])&&(a=(o<3?r(a):o>3?r(e,i,a):r(e,i))||a);return o>3&&a&&Object.defineProperty(e,i,a),a}function a(t,e){return function(i,s){e(i,s,t)}}!function(t){t[t.QuadTree=0]="QuadTree",t[t.SpartialGrid=1]="SpartialGrid"}(r||(r={})),"function"==typeof SuppressedError&&SuppressedError;class n{constructor(t=0,e=0){this._x=t,this._y=e}get x(){return this._x}set x(t){this._x=t}get y(){return this._y}set y(t){this._y=t}get magnitude(){return Math.sqrt(Math.pow(this._x,2)+Math.pow(this._y,2))}get direction(){return this._direction||(this._direction=new n),n.unit(this._direction,this)}set(t,e){this._x=t,this._y=e}copy(t){this.set(t.x,t.y)}equals(t){return this._x===t.x&&this._y===t.y}clone(){return new n(this._x,this._y)}distance(t){return Math.sqrt(Math.pow(this._x-t.x,2)+Math.pow(this._y-t.y,2))}static add(t,e,i){return t.set(e.x+i.x,e.y+i.y),t}static subtract(t,e,i){return t.set(e.x-i.x,e.y-i.y),t}static unit(t,e){return 0===e.magnitude?t.set(0,0):t.set(e.x/e.magnitude,e.y/e.magnitude),t}static normal(t,e){return t.set(-e.y,e.x),this.unit(t,t)}static scale(t,e,i){return t.set(e.x*i,e.y*i),t}static dot(t,e){return t.x*e.x+t.y*e.y}static cross(t,e){return t.x*e.y-t.y*e.x}static round(t,e){return t.set(Math.round(e.x),Math.round(e.y)),t}static floor(t,e){return t.set(Math.floor(e.x),Math.floor(e.y)),t}static ceil(t,e){return t.set(Math.ceil(e.x),Math.ceil(e.y)),t}toString(){return`(${this._x}, ${this._y})`}}class h{constructor(t=0,e=0,i=0,s=0){this.width=0,this.height=0,this._position=new n,this._center=new n,this.set(t,e,i,s)}get x(){return this._position.x}set x(t){this._position.set(t,this._position.y)}get y(){return this._position.y}set y(t){this._position.set(this._position.x,t)}get x1(){return this._position.x+this.width}get y1(){return this._position.y+this.height}get position(){return this._position}set position(t){this._position.set(t.x,t.y)}get center(){return this._center.set(this.x+this.width/2,this.y+this.height/2),this._center}set(t,e,i,s){this._position.set(t,e),this.width=i,this.height=s}equals(t){return this.position.equals(t.position)&&this.width===t.width&&this.height===t.height}copy(t){this.set(t.x,t.y,t.width,t.height)}overlaps(t){return this.x1>=t.x&&this.x<t.x1&&this.y1>=t.y&&this.y<t.y1}contains(t){return t instanceof h?t.x1<=this.x1&&t.x>=this.x&&t.y1<=this.y1&&t.y>=this.y:t instanceof n&&!(t.x<this.x||t.y<this.y||t.x>=this.x1||t.y>=this.y1)}}const l=(t,e,i)=>Math.min(i,Math.max(e,t)),c=(t,e)=>Math.round(Math.random()*(e-t))+t,d=(t,e,i=2)=>g(Math.random()*(e-t)+t,i),g=(t,e)=>Math.round(t*Math.pow(10,e))/Math.pow(10,e),m=(t,e,i=1)=>{const s=[];for(let r=t;r<=e;r+=i)s.push(r);return s},u=(t,e,i)=>t>=e&&t<=i,p=t=>t*(180/Math.PI),y=t=>t*(Math.PI/180),f=({r:t,g:e,b:i},s="#")=>{const r=t=>t.toString(16).padStart(2,"0");return`${s}${r(t)}${r(e)}${r(i)}`};var x;let M=x=class{constructor(t=new h,e=0){this.children=[],this.shapes=[],this.minArea=new n,this.maxArea=new n,this.area=t,this.depth=e}clear(){this.shapes=[],this.children=[]}update(t){this.clear(),this.resizeArea(t),t.forEach((({id:t,boundingBox:e})=>this.insert(t,e)))}resizeArea(t){this.minArea.set(0,0),this.maxArea.set(0,0),t.forEach((({boundingBox:t})=>{this.minArea.set(Math.min(t.x,this.minArea.x),Math.min(t.y,this.minArea.y)),this.maxArea.set(Math.max(t.x1,this.maxArea.x),Math.max(t.y1,this.maxArea.y))})),this.area.set(this.minArea.x,this.minArea.y,this.maxArea.x-this.minArea.x,this.maxArea.y-this.minArea.y)}retrieve(t){const e=[];return this.children.length>0?this.getChildrenForBox(t).forEach((i=>e.push(...i.retrieve(t).filter((t=>!e.includes(t)))))):this.shapes.forEach((t=>e.push(t[0]))),e}insert(t,e){0===this.children.length&&this.shapes.length>16&&this.depth<8&&this.split(),this.children.length>0?this.insertItemIntoChildren(t,e):this.shapes.push([t,e])}split(){const t=this.area.width/2,e=this.area.height/2;this.children=[new h(this.area.x,this.area.y,t,e),new h(this.area.x,this.area.y+e,t,e),new h(this.area.x+t,this.area.y+e,t,e),new h(this.area.x+t,this.area.y,t,e)].map((t=>new x(t,this.depth+1))),this.shapes.forEach((t=>this.insertItemIntoChildren(t[0],t[1]))),this.shapes=[]}insertItemIntoChildren(t,e){this.getChildrenForBox(e).forEach((i=>i.insert(t,e)))}getChildrenForBox(t){const e=[];return t.x<=this.area.center.x&&t.y<=this.area.center.y&&e.push(this.children[0]),t.x<=this.area.center.x&&t.y1>=this.area.center.y&&e.push(this.children[1]),t.x1>=this.area.center.x&&t.y1>=this.area.center.y&&e.push(this.children[2]),t.x1>=this.area.center.x&&t.y<=this.area.center.y&&e.push(this.children[3]),e}};M=x=o([i(t.CollisionBroadphaseResolver)],M);const v=(t,e,i,s)=>Math.min((t-e)/i|0,s-1);let C=class{constructor(){this.area=new h,this.colliders=[],this.subdivisions=0,this.coordinates={x0:0,x1:0,y0:0,y1:0},this.minArea=new n,this.maxArea=new n}clear(){for(let t=0;t<this.subdivisions;t++)for(let e=0;e<this.subdivisions;e++)this.colliders[t][e]=[]}update(t){this.resizeArea(t),this.updateSubdivisions(t.length),t.forEach((({id:t,boundingBox:e})=>this.insert(t,e)))}resizeArea(t){this.minArea.set(0,0),this.maxArea.set(0,0),t.forEach((({boundingBox:t})=>{this.minArea.set(Math.min(t.x,this.minArea.x),Math.min(t.y,this.minArea.y)),this.maxArea.set(Math.max(t.x1,this.maxArea.x),Math.max(t.y1,this.maxArea.y))})),this.area.set(this.minArea.x,this.minArea.y,this.maxArea.x-this.minArea.x,this.maxArea.y-this.minArea.y)}updateSubdivisions(t){this.subdivisions=1+(t/10|0),this.cellWidth=Math.ceil(this.area.width/this.subdivisions),this.cellHeight=Math.ceil(this.area.height/this.subdivisions),this.colliders=[];for(let t=0;t<this.subdivisions;t++){this.colliders[t]=[];for(let e=0;e<this.subdivisions;e++)this.colliders[t][e]=[]}}insert(t,e){this.updateCoordinates(e);for(let e=this.coordinates.x0;e<=this.coordinates.x1;e++)for(let i=this.coordinates.y0;i<=this.coordinates.y1;i++)this.colliders[e][i].push(t)}retrieve(t){const e=[];this.updateCoordinates(t);for(let t=this.coordinates.x0;t<=this.coordinates.x1;t++)for(let i=this.coordinates.y0;i<=this.coordinates.y1;i++)this.colliders[t][i].forEach((t=>e.includes(t)?void 0:e.push(t)));return e}updateCoordinates(t){this.coordinates.x0=v(t.x,this.area.x,this.cellWidth,this.subdivisions),this.coordinates.x1=v(t.x1,this.area.x,this.cellWidth,this.subdivisions),this.coordinates.y0=v(t.y,this.area.y,this.cellHeight,this.subdivisions),this.coordinates.y1=v(t.y1,this.area.y,this.cellHeight,this.subdivisions)}};C=o([i(t.CollisionBroadphaseResolver)],C);class S{get vertexModel(){return this._vertexModel}set vertexModel(t){if(this._vertexModel=t,2===t.length)return this.vertices=[new n,new n],void(this.projectionAxes=[new n]);this.vertices=[],this.projectionAxes=[],this._vertexModel.forEach((()=>{this.vertices.push(new n),this.projectionAxes.push(new n)}))}constructor(t,e=0){this.rotation=e,this.boundingBox=new h,this.collider=void 0,this.entity=void 0,this.id=void 0,this.ignoreCollisionsWithLayers=void 0,this.layer=void 0,this.position=new n,this.projectionAxes=[],this.radius=0,this.vertices=[],this.updateCollisions=!0,this._vertexModel=[],this.vertexModel=t}}class b{constructor(t){this.radius=t,this.boundingBox=new h,this.collider=void 0,this.entity=void 0,this.id=void 0,this.ignoreCollisionsWithLayers=void 0,this.layer=void 0,this.position=new n,this.projectionAxes=[new n],this.rotation=0,this.vertexModel=[],this.vertices=[new n,new n],this.updateCollisions=!0}}let A=class{constructor(t,e,i){this.AABBResolver=t,this.circumferenceAABBResolver=e,this.circumferenceResolver=i}findCollision(t,e){return t instanceof S&&e instanceof S?this.AABBResolver.resolve(t,e):t instanceof b&&e instanceof S?this.circumferenceAABBResolver.resolve(t,e):t instanceof S&&e instanceof b?this.circumferenceAABBResolver.resolve(e,t,!0):t instanceof b&&e instanceof b?this.circumferenceResolver.resolve(t,e):void 0}};var w;A=o([i(t.CollisionResolutionMethod),a(0,s(t.CollisionAABBResolver)),a(1,s(t.CollisionCircumferenceAABBResolver)),a(2,s(t.CollisionCircumferenceResolver))],A),function(t){t[t.AABB=0]="AABB",t[t.SAT=1]="SAT"}(w||(w={}));let _=class{constructor(t,e){this.circumferenceResolver=t,this.satResolver=e}findCollision(t,e){return t instanceof b&&e instanceof b?this.circumferenceResolver.resolve(t,e):this.satResolver.resolve(t,e)}};_=o([i(t.CollisionResolutionMethod),a(0,s(t.CollisionCircumferenceResolver)),a(1,s(t.CollisionSatResolver))],_);let E=class{constructor(){this.direction=new n,this.resolutionDirection=new n}resolve({boundingBox:t},{boundingBox:e}){if(this.overlapX=Math.min(t.x1,e.x1)-Math.max(t.x,e.x),this.overlapY=Math.min(t.y1,e.y1)-Math.max(t.y,e.y),!(this.overlapX<0||this.overlapY<0))return this.checkOverlapForLines(t,e),this.direction.set(Math.sign(e.center.x-t.center.x),Math.sign(e.center.y-t.center.y)),this.preventContainment(t,e),this.overlapY<this.overlapX?(this.minOverlap=this.overlapY,this.resolutionDirection.set(0,this.direction.y)):(this.minOverlap=this.overlapX,this.resolutionDirection.set(this.direction.x,this.overlapY===this.overlapX?this.direction.y:0)),{direction:n.unit(new n,this.resolutionDirection),penetration:this.minOverlap}}checkOverlapForLines(t,e){0!==t.width&&0!==e.width||0!==this.overlapX||(this.overlapX=Math.min(Math.abs(t.x-e.x),Math.abs(t.x1-e.x1))),0!==t.height&&0!==e.height||0!==this.overlapY||(this.overlapY=Math.min(Math.abs(t.y-e.y),Math.abs(t.y1-e.y1)))}preventContainment(t,e){if(this.overlapY>0&&(t.y1>e.y1&&t.y<e.y||t.y1<e.y1&&t.y>e.y)){const i=Math.abs(t.y-e.y),s=Math.abs(t.y1-e.y1);this.overlapY+=i<s?i:s}if(this.overlapX>0&&(t.x1>e.x1&&t.x<e.x||t.x1<e.x1&&t.x>e.x)){const i=Math.abs(t.x-e.x),s=Math.abs(t.x1-e.x1);this.overlapX+=i<s?i:s}}};E=o([i(t.CollisionAABBResolver)],E);let R=class{constructor(){this.closestPoint=new n,this.distance=new n,this.direction=new n}resolve(t,e,i=!1){if(this.closestPoint.set(l(t.position.x,e.boundingBox.x,e.boundingBox.x1),l(t.position.y,e.boundingBox.y,e.boundingBox.y1)),n.subtract(this.distance,this.closestPoint,t.position),!(this.distance.magnitude>t.radius))return n.unit(this.direction,this.distance),{direction:i?n.scale(new n,this.direction,-1):this.direction.clone(),penetration:t.radius-this.distance.magnitude}}};R=o([i(t.CollisionCircumferenceAABBResolver)],R);let T=class{constructor(){this.distance=new n,this.direction=new n}resolve(t,e){if(n.subtract(this.distance,e.position,t.position),!(this.distance.magnitude>t.radius+e.radius))return n.unit(this.direction,this.distance),{direction:this.direction.clone(),penetration:t.radius+e.radius-this.distance.magnitude}}};T=o([i(t.CollisionCircumferenceResolver)],T);let B=class{constructor(){this.projA={min:0,max:0},this.projB={min:0,max:0},this.smallestAxis=new n,this.distance=new n(1/0,1/0),this.cache=new n}resolve(t,e){this.minOverlap=1/0,t instanceof b?this.setCircumferenceAxis(t,e):e instanceof b&&this.setCircumferenceAxis(e,t),this.axes=[...t.projectionAxes],e.projectionAxes.forEach((t=>this.axes.some((e=>e.equals(t)))?void 0:this.axes.push(t)));for(let i=0;i<this.axes.length;i++){if(t instanceof b?this.setCircumferenceVertices(t,this.axes[i]):e instanceof b&&this.setCircumferenceVertices(e,this.axes[i]),this.projectShapeOntoAxis(this.projA,t,this.axes[i]),this.projectShapeOntoAxis(this.projB,e,this.axes[i]),this.currentOverlap=Math.min(this.projA.max,this.projB.max)-Math.max(this.projA.min,this.projB.min),this.currentOverlap<0)return;if(this.invertAxis=!0,this.projA.max>this.projB.max&&this.projA.min<this.projB.min||this.projA.max<this.projB.max&&this.projA.min>this.projB.min){const t=Math.abs(this.projA.min-this.projB.min),e=Math.abs(this.projA.max-this.projB.max);t<e?this.currentOverlap+=t:(this.currentOverlap+=e,n.scale(this.axes[i],this.axes[i],-1),this.invertAxis=!1)}this.currentOverlap<this.minOverlap&&(this.minOverlap=this.currentOverlap,this.smallestAxis.copy(this.axes[i]),this.invertAxis&&this.projA.max<this.projB.max&&n.scale(this.smallestAxis,this.axes[i],-1))}return{direction:n.scale(new n,this.smallestAxis,-1),penetration:this.minOverlap}}projectShapeOntoAxis(t,e,i){return t.min=1/0,t.max=-1/0,e.vertices.forEach((e=>{t.min=Math.min(n.dot(i,e),t.min),t.max=Math.max(n.dot(i,e),t.max)})),t}setCircumferenceAxis(t,e){this.distance.set(1/0,1/0),e.vertices.forEach((e=>{n.subtract(this.cache,e,t.position),this.cache.magnitude<this.distance.magnitude&&this.distance.copy(this.cache)})),n.unit(t.projectionAxes[0],this.distance)}setCircumferenceVertices(t,e){n.add(t.vertices[0],t.position,n.scale(this.cache,n.unit(this.cache,e),-t.radius)),n.add(t.vertices[1],t.position,n.scale(this.cache,n.unit(this.cache,e),t.radius))}};B=o([i(t.CollisionSatResolver)],B);let P=class{constructor(){this.collisions=[]}findCollisionsForCollider(t){return this.collisions.filter((e=>e.localCollider===t))}findCollisionsForColliderAndLayer(t,e){return this.collisions.filter((i=>i.localCollider===t&&i.remoteCollider.layer===e))}findAll(){return this.collisions}persist(t){this.collisions.push(t)}removeAll(){this.collisions=[]}};P=o([i(t.CollisionRepository)],P);let D=class{constructor(){this.lastEntityId=0,this.lastComponentTypeId=0,this.entities=new Set,this.components=new Map,this.disabledEntities=new Set,this.disabledComponents=new Map}createEntity(t){return this.lastEntityId++,this.entities.add(this.lastEntityId),t&&t.forEach((t=>this.addComponent(this.lastEntityId,t))),this.lastEntityId}createEntities(t){const e=[];return t.forEach((t=>e.push(this.createEntity(t)))),e}removeEntity(t){this.components.forEach((e=>{e.has(t)&&e.delete(t)})),this.disabledComponents.delete(t),this.disabledEntities.delete(t),this.entities.delete(t)}removeAllEntities(){this.components.clear(),this.disabledComponents.clear(),this.disabledEntities.clear(),this.lastEntityId=0,this.entities.clear()}isEntity(t){return this.entities.has(t)}isEntityEnabled(t){return this.isEntity(t)&&!this.disabledEntities.has(t)}enableEntity(t){this.isEntity(t)&&this.disabledEntities.delete(t)}disableEntity(t){this.isEntity(t)&&this.disabledEntities.add(t)}disableEntitiesByComponent(t){var e,i;for(const s of null!==(i=null===(e=this.components.get(this.getComponentTypeId(t)))||void 0===e?void 0:e.keys())&&void 0!==i?i:[])this.disableEntity(s)}enableEntitiesByComponent(t){var e,i;for(const s of null!==(i=null===(e=this.components.get(this.getComponentTypeId(t)))||void 0===e?void 0:e.keys())&&void 0!==i?i:[])this.enableEntity(s)}addComponent(t,e){const i=this.getComponentTypeId(e),s="object"==typeof e?e:new e;if(this.components.has(i)||this.components.set(i,new Map),this.components.get(i).has(t))throw new Error(`Entity ${t} already has a component of type ${i}`);return this.components.get(i).set(t,s),s}hasComponent(t,e){return void 0!==this.getComponent(t,e)}getComponent(t,e){var i;return null===(i=this.components.get(this.getComponentTypeId(e)))||void 0===i?void 0:i.get(t)}getComponents(t){const e=[];return this.components.forEach((i=>i.forEach(((i,s)=>{t===s&&e.push(i)})))),e}getEntityForComponent(t){const e=this.getComponentTypeId(t);if(this.components.has(e))for(const[i,s]of this.components.get(e))if(s===t)return i}removeComponent(t,e){var i;const s=this.getComponentTypeId("object"==typeof t?t:e),r="number"==typeof t?t:this.getEntityForComponent(t);void 0!==r&&(null===(i=this.components.get(s))||void 0===i?void 0:i.has(r))&&this.components.get(s).delete(r)}isComponentEnabled(t,e){var i;const s=this.getComponentTypeId("object"==typeof t?t:e),r="number"==typeof t?t:this.getEntityForComponent(t);return void 0!==r&&!(null===(i=this.disabledComponents.get(r))||void 0===i?void 0:i.has(s))}disableComponent(t,e){const i="number"==typeof t?t:this.getEntityForComponent(t),s=this.getComponentTypeId("object"==typeof t?t:e);null!=i&&(this.disabledComponents.has(i)?this.disabledComponents.get(i).has(s)||this.disabledComponents.get(i).add(s):this.disabledComponents.set(i,new Set([s])))}enableComponent(t,e){var i;const s="number"==typeof t?t:this.getEntityForComponent(t),r=this.getComponentTypeId("object"==typeof t?t:e);void 0!==s&&(null===(i=this.disabledComponents.get(s))||void 0===i?void 0:i.has(r))&&this.disabledComponents.get(s).delete(r)}search(t,e,i=!1){const s=[],r=this.getComponentTypeId(t);return this.components.has(r)&&this.components.get(r).forEach(((r,o)=>{e&&!Object.keys(e).every((t=>r[t]===e[t]))||!(i||this.isEntityEnabled(o)&&this.isComponentEnabled(o,t))||s.push({entity:o,component:r})})),s}searchEntitiesByComponents(t){const e=[];let i=!0;for(const s of t){const t=this.getComponentTypeId(s);if(!t||!this.components.has(t))return[];if(i){e.push(...this.components.get(t).keys()),i=!1;continue}const r=new Set(this.components.get(t).keys());e.forEach(((t,i)=>{r.has(t)||e.splice(i,1)}))}return e}getComponentTypeId(t){const e="object"==typeof t?t.constructor.prototype:t.prototype;return void 0===e.__ecs_type_id&&(e.__ecs_type_id=++this.lastComponentTypeId),e.__ecs_type_id}};D=o([i(t.EntityManager)],D);let F=class{constructor(){this.systems=[]}findSystemIndex(t){return this.systems.findIndex((e=>e[0]instanceof t))}addSystem(t,e){if(this.systems.some((t=>t[0]instanceof t.constructor)))throw new Error(`SystemManager already has an instance of ${t.constructor.name}.`);this.systems.push([t,e,!1,!1])}hasSystem(t){return this.systems.some((e=>e[0]instanceof t))}getSystem(t){const e=this.findSystemIndex(t);return-1!==e?this.systems[e][0]:void 0}groupHasSystems(t){return this.systems.filter((e=>e[1]===t)).length>0}enableSystem(t){const e=this.findSystemIndex(t);if(-1===e||!0===this.systems[e][2])return;const i=this.systems[e];!1===i[3]&&(i[3]=!0,i[0].onCreate&&i[0].onCreate()),i[2]=!0,i[0].onEnabled&&i[0].onEnabled()}disableSystem(t){const e=this.findSystemIndex(t);if(-1===e||!1===this.systems[e][2])return;const i=this.systems[e];i[2]=!1,i[0].onDisabled&&i[0].onDisabled()}setExecutionOrder(t,e){const i=this.findSystemIndex(t);if(-1===i)throw new Error(`Cannot set execution order because ${t.name} is not a system.`);this.systems.splice(e,0,this.systems.splice(i,1)[0])}removeSystem(t){const e=this.findSystemIndex(t);if(-1===e)return;const i=this.systems.splice(e,1)[0][0];i.onDestroy&&i.onDestroy()}disableAllSystems(){this.systems.forEach((t=>{t[2]&&this.disableSystem(t[0].constructor)}))}update(t){this.systems.filter((e=>e[1]===t&&!0===e[2])).forEach((t=>t[0].onUpdate()))}};F=o([i(t.SystemManager)],F);class U{constructor(){this.buttons=new Map,this.axes=new Map,this._dpadAxes=new n,this._leftStickAxes=new n,this._rightStickAxes=new n}get dpadAxes(){return this._dpadAxes.set(this.dpadRight?1:this.dpadLeft?-1:0,this.dpadUp?1:this.dpadDown?-1:0),this._dpadAxes}get leftStickAxes(){return this._leftStickAxes.set(this.leftStickHorizontal,this.leftStickVertical),this._leftStickAxes}get rightStickAxes(){return this._rightStickAxes.set(this.rightStickHorizontal,this.rightStickVertical),this._rightStickAxes}get dpadUp(){var t;return null!==(t=this.buttons.get(12))&&void 0!==t&&t}get dpadDown(){var t;return null!==(t=this.buttons.get(13))&&void 0!==t&&t}get dpadLeft(){var t;return null!==(t=this.buttons.get(14))&&void 0!==t&&t}get dpadRight(){var t;return null!==(t=this.buttons.get(15))&&void 0!==t&&t}get bottomFace(){var t;return null!==(t=this.buttons.get(0))&&void 0!==t&&t}get rightFace(){var t;return null!==(t=this.buttons.get(1))&&void 0!==t&&t}get leftFace(){var t;return null!==(t=this.buttons.get(2))&&void 0!==t&&t}get topFace(){var t;return null!==(t=this.buttons.get(3))&&void 0!==t&&t}get leftShoulder(){var t;return null!==(t=this.buttons.get(4))&&void 0!==t&&t}get rightShoulder(){var t;return null!==(t=this.buttons.get(5))&&void 0!==t&&t}get leftTrigger(){var t;return null!==(t=this.buttons.get(6))&&void 0!==t&&t}get rightTrigger(){var t;return null!==(t=this.buttons.get(7))&&void 0!==t&&t}get back(){var t;return null!==(t=this.buttons.get(8))&&void 0!==t&&t}get start(){var t;return null!==(t=this.buttons.get(9))&&void 0!==t&&t}get leftStickButton(){var t;return null!==(t=this.buttons.get(10))&&void 0!==t&&t}get rightStickButton(){var t;return null!==(t=this.buttons.get(11))&&void 0!==t&&t}get leftStickHorizontal(){var t;return null!==(t=this.axes.get(0))&&void 0!==t?t:0}get leftStickVertical(){var t;return-(null!==(t=this.axes.get(1))&&void 0!==t?t:0)}get rightStickHorizontal(){var t;return null!==(t=this.axes.get(2))&&void 0!==t?t:0}get rightStickVertical(){var t;return-(null!==(t=this.axes.get(3))&&void 0!==t?t:0)}get anyButtonPressed(){var t;return null!==(t=Array.from(this.buttons.values()).find((t=>t)))&&void 0!==t&&t}vibrate(t=200,e=.2,i=.2,s=0){this.vibrationInput={duration:t,weakMagnitude:e,startDelay:s,strongMagnitude:i}}}class I{constructor(){this.pressedKeys=[]}isPressed(t){return this.pressedKeys.includes(t)}orPressed(t){return t.reduce(((t,e)=>t||this.pressedKeys.includes(e)),!1)}andPressed(t){return t.reduce(((t,e)=>t&&this.pressedKeys.includes(e)),!0)}isPressedReturn(t,e,i){return this.pressedKeys.includes(t)?e:i}orPressedReturn(t,e,i){return t.reduce(((t,e)=>t||this.pressedKeys.includes(e)),!1)?e:i}andPressedReturn(t,e,i){return t.reduce(((t,e)=>t&&this.pressedKeys.includes(e)),!0)?e:i}}class L{constructor(){this.leftButtonPressed=!1,this.scrollButtonPressed=!1,this.rightButtonPressed=!1,this.positionInViewport=new n,this.hasMoved=!1,this.wheelScroll=new n}}class j{constructor(){this.touching=!1,this.interactions=[]}}let O=class{constructor(){this.keyboard=new I,this.mouse=new L,this.touchScreen=new j,this.gamepads=[]}};O=o([i(t.InputManager)],O);const k=[60,120,180,240];let V=class{get deltaTime(){return this.unscaledDeltaTime*this.timeScale}get physicsDeltaTime(){return this.unscaledPhysicsDeltaTime*this.timeScale}get renderDeltaTime(){return this.browserDeltaTime*this.timeScale}constructor({physicsFramerate:t}){if(this.timeScale=1,this.browserDeltaTime=0,this.unscaledDeltaTime=0,this.unscaledPhysicsDeltaTime=0,this.maxDeltaTime=1/30,this.thenForGame=0,this.thenForPhysics=0,this.thenForRender=0,this.lastIntervalId=0,this.intervals=new Map,t&&!k.includes(t))throw new Error(`Invalid Physics frame rate. Allowed: [${k.join(", ")}]`);this.fixedGameFramerate=60,this.fixedGameDeltaTime=parseFloat((1/this.fixedGameFramerate).toFixed(6)),this.fixedPhysicsFramerate=null!=t?t:180,this.fixedPhysicsDeltaTime=parseFloat((1/this.fixedPhysicsFramerate).toFixed(6))}updateForRender(t){this.browserDeltaTime=Math.min(Math.max(0,t-this.thenForRender),this.maxDeltaTime),this.thenForRender=t}updateForGame(t){this.unscaledDeltaTime=Math.min(Math.max(this.fixedGameDeltaTime,t-this.thenForGame),this.maxDeltaTime),this.thenForGame=t}updateForPhysics(t){this.unscaledPhysicsDeltaTime=Math.min(Math.max(0,t-this.thenForPhysics),this.maxDeltaTime),this.thenForPhysics=t}updateIntervals(){if(0===this.intervals.size)return;const t=performance.now();for(const[e,i]of this.intervals)i.executeImmediately&&(i.timestamp=t-i.delay,i.executeImmediately=!1),t-i.timestamp>=i.delay&&(i.callback(),i.times&&--i.times<=0?(this.intervals.delete(e),0===this.intervals.size&&(this.lastIntervalId=0)):i.timestamp=t)}setInterval({callback:t,delay:e,times:i,executeImmediately:s}){const r=++this.lastIntervalId;return this.intervals.set(r,{callback:t,delay:e,times:i,executeImmediately:s,timestamp:performance.now()}),r}clearInterval(t){this.intervals.delete(t),0===this.intervals.size&&(this.lastIntervalId=0)}clearAllIntervals(){this.intervals.clear(),this.lastIntervalId=0}};var G;V=o([i(t.TimeManager),a(0,s(t.GameConfig))],V),function(t){t[t.Image=0]="Image",t[t.Audio=1]="Audio",t[t.Font=2]="Font",t[t.Video=3]="Video"}(G||(G={}));let z=class{constructor(){this.assets=[]}getAssetsLoaded(){return this.assets.reduce(((t,e)=>t&&e.loaded),!0)}loadImage(t,e){const i=new Image;i.crossOrigin="",i.src=t;const s=this.createAsset(t,G.Image,i,e),r=()=>s.loaded=!0;return i.complete?r():i.addEventListener("load",r),i}loadAudio(t,e){const i=new Audio;i.src=t;const s=this.createAsset(t,G.Audio,i,e);return i.duration?s.loaded=!0:i.addEventListener("canplaythrough",(()=>s.loaded=!0)),i}loadFont(t,e){const i=new FontFace(t,`url(${e})`),s=this.createAsset(e,G.Font,i);return s.family=t,document.fonts.add(i),i.load().then((()=>s.loaded=!0)),i}loadVideo(t,e){const i=document.createElement("video");i.playsInline=!0,i.src=t;const s=this.createAsset(t,G.Video,i,e);return i.duration?s.loaded=!0:i.addEventListener("canplaythrough",(()=>s.loaded=!0)),i}getImage(t){var e;return null===(e=this.assets.find((e=>e.type===G.Image&&(e.url===t||e.name===t))))||void 0===e?void 0:e.element}getAudio(t){var e;return null===(e=this.assets.find((e=>e.type===G.Audio&&(e.url===t||e.name===t))))||void 0===e?void 0:e.element}getFont(t){var e;return null===(e=this.assets.find((e=>e.type===G.Font&&e.family===t)))||void 0===e?void 0:e.element}getVideo(t){var e;return null===(e=this.assets.find((e=>e.type===G.Video&&(e.url===t||e.name===t))))||void 0===e?void 0:e.element}createAsset(t,e,i,s){const r={type:e,url:t,element:i,loaded:!1,name:s};return this.assets.push(r),r}};z=o([i(t.AssetManager)],z);class W{get playing(){return"playing"===this.state}get paused(){return"paused"===this.state}get stopped(){return"stopped"===this.state}constructor(t){this.action=void 0,this.fixedToTimeScale=!1,this.loop=!1,this.state="stopped",this.volume=1,this._currentAudioSource=void 0,this._playPromisePendind=!1,Object.assign(this,t)}play(t){t&&(this.audioSource=t),this.action="play"}pause(){this.action="pause"}stop(){this.action="stop"}}const H={AudioPlayerSystem:Symbol.for("AudioPlayerSystem"),ButtonSystem:Symbol.for("ButtonSystem"),ChildrenSystem:Symbol.for("ChildrenSystem"),ParentSystem:Symbol.for("ParentSystem"),TiledWrapperSystem:Symbol.for("TiledWrapperSystem"),TilemapPreProcessingSystem:Symbol.for("TilemapPreProcessingSystem"),TransformSystem:Symbol.for("TransformSystem"),GamepadSystem:Symbol.for("GamepadSystem"),KeyboardSystem:Symbol.for("KeyboardSystem"),MouseSystem:Symbol.for("MouseSystem"),TouchScreenSystem:Symbol.for("TouchScreenSystem"),UpdateBallColliderShapeSystem:Symbol.for("UpdateBallColliderShapeSystem"),UpdateBoxColliderShapeSystem:Symbol.for("UpdateBoxColliderShapeSystem"),UpdateEdgeColliderShapeSystem:Symbol.for("UpdateEdgeColliderShapeSystem"),UpdatePolygonColliderShapeSystem:Symbol.for("UpdatePolygonColliderShapeSystem"),UpdateTilemapColliderShapeSystem:Symbol.for("UpdateTilemapColliderShapeSystem"),UpdateCollidersAfterRepositionSystem:Symbol.for("UpdateCollidersAfterRepositionSystem"),ApplyRepositionSystem:Symbol.for("ApplyRepositionSystem"),ApplyVelocitySystem:Symbol.for("ApplyVelocitySystem"),ResolveCollisionSystem:Symbol.for("ResolveCollisionSystem"),AnimatorSystem:Symbol.for("AnimatorSystem"),CameraSystem:Symbol.for("CameraSystem"),ClearScreenSystem:Symbol.for("ClearScreenSystem"),CullingSystem:Symbol.for("CullingSystem"),MaskRendererSystem:Symbol.for("MaskRendererSystem"),RenderSystem:Symbol.for("RenderSystem"),ShadowLightRendererSystem:Symbol.for("ShadowLightRendererSystem"),SpriteRendererSystem:Symbol.for("SpriteRendererSystem"),TextRendererSystem:Symbol.for("TextRendererSystem"),TilemapRendererSystem:Symbol.for("TilemapRendererSystem"),VideoRendererSystem:Symbol.for("VideoRendererSystem"),DebugColliderRenderSystem:Symbol.for("DebugColliderRenderSystem"),DebugMousePositionSystem:Symbol.for("DebugMousePositionSystem")},N=["click","contextmenu","auxclick","dblclick","mousedown","mouseup","pointerup","touchend","keydown","keyup"];let Y=class{constructor(t,e,i){this.entityManager=t,this.inputManager=e,this.timeManager=i,this.canPlay=!0,this.userInputErrorCatched=!1,this.userInputEventHandler=()=>{N.forEach((t=>{window.removeEventListener(t,this.userInputEventHandler)})),this.canPlay=!0}}onCreate(){document.addEventListener("visibilitychange",(()=>{this.entityManager.search(W).forEach((({component:{audioSource:t,playing:e}})=>{document.hidden&&t?t.pause():!document.hidden&&t&&e&&t.play()}))}))}catchUserInput(){this.canPlay=!1,this.userInputErrorCatched=!0,N.forEach((t=>window.addEventListener(t,this.userInputEventHandler)))}checkGamepad(){return this.canPlay=this.inputManager.gamepads.some((t=>t.anyButtonPressed)),this.canPlay}onUpdate(){(this.canPlay||this.checkGamepad())&&this.entityManager.search(W).forEach((({component:t})=>{t.audioSource&&t.audioSource.duration&&(t.audioSource!==t._currentAudioSource&&(t._currentAudioSource&&(t._currentAudioSource.pause(),t._currentAudioSource.currentTime=0),t._currentAudioSource=t.audioSource,t.audioSource.currentTime=0,t.state="stopped"),t.audioSource.loop=t.loop,t.audioSource.volume=t.volume,"play"!==t.action||"playing"===t.state||t._playPromisePendind?"pause"===t.action&&"playing"===t.state?(t.audioSource.pause(),t.state="paused"):"stop"!==t.action||t.audioSource.paused&&0===t.audioSource.currentTime?"playing"===t.state&&t.audioSource.paused&&(t.state="stopped"):(t.audioSource.pause(),t.audioSource.currentTime=0,t.state="stopped"):(t._playPromisePendind=!0,t.audioSource.playbackRate=t.fixedToTimeScale?this.timeManager.timeScale<.0625?0:Math.min(this.timeManager.timeScale,16):1,t.audioSource.play().then((()=>{t._playPromisePendind=!1,t.state="playing"})).catch((()=>{t._playPromisePendind=!1,this.userInputErrorCatched||this.catchUserInput()}))),t.action=void 0)}))}onDisabled(){this.entityManager.search(W).forEach((({component:{audioSource:t}})=>{t&&(t.pause(),t.currentTime=0)}))}onDestroy(){this.onDisabled()}};var X;function $(){return function(t){Q(t,X.GameLogic)}}function K(){return function(t){Q(t,X.GamePhysics)}}function q(){return function(t){Q(t,X.GamePreRender)}}Y=o([i(H.AudioPlayerSystem),a(0,s(t.EntityManager)),a(1,s(t.InputManager)),a(2,s(t.TimeManager))],Y),function(t){t[t.GameLogic=0]="GameLogic",t[t.GamePhysics=1]="GamePhysics",t[t.GamePreRender=2]="GamePreRender",t[t.Physics=3]="Physics",t[t.PreGameLogic=4]="PreGameLogic",t[t.Render=5]="Render",t[t.Transform=6]="Transform"}(X||(X={}));const Q=(t,e)=>{t.prototype.__system_group||(t.prototype.__system_group=e)};class J{get parent(){return this._parent}set parent(t){this._parent!==t&&(this._parent=t,this._parent?(this.localPosition.copy(this.position),n.subtract(this.position,this.position,this._parent.position)):this.position.copy(this.localPosition))}constructor(t){this.position=new n,this.scale=new n(1,1),this.rotation=0,this.localPosition=new n,this.localScale=new n(1,1),this.localRotation=0,this._childEntities=[],this._parent=void 0,t&&t.parent&&(this.position=t.parent.position.clone(),this.parent=t.parent,delete t.parent),Object.assign(this,t)}}const Z="Default",tt="Debug";class et{constructor(t){this.layers=[Z],this.zoom=1,this.depth=0,this.debug=!1,this._renderData={position:new n,depth:0,zoom:1,layers:[]},Object.assign(this,t)}}var it;!function(t){t.LegacyWebGL="webgl",t.WebGL2="webgl2"}(it||(it={}));class st{constructor(t){if(this.canvas=t,this.contextVersion=this.getContextVersion(),!this.contextVersion)throw new Error("Your browser does not support WebGL.");this.gl=this.canvas.getContext(this.contextVersion)}getContextVersion(){return null!==this.canvas.getContext(it.WebGL2)?it.WebGL2:null!==this.canvas.getContext(it.LegacyWebGL)?it.LegacyWebGL:void 0}}class rt{constructor(){this.fontAtlas=new Map}hasFontAtlas(t){return this.fontAtlas.has(this.getId(t))}getFontAtlas(t){return this.fontAtlas.get(this.getId(t))}getOrCreate(t){var e;return null!==(e=this.getFontAtlas(t))&&void 0!==e?e:this.create(t)}create(t){const{font:e,charRanges:i,fontSize:s,spacing:r}=t;this.chars=[];for(let t=0;t<i.length;t+=2)for(let e=i[t];e<=i[t+1];e++)this.chars.push(String.fromCharCode(e));this.font=e instanceof FontFace?e.family:e,this.fontSize=s,this.spacing=r,this.id=this.getId(t);const o=this.renderAtlas();return this.fontAtlas.set(this.id,o),o}getId({font:t,charRanges:e,fontSize:i,spacing:s}){return JSON.stringify({font:t instanceof FontFace?t.family:t,charRanges:e,fontSize:i,spacing:s})}renderAtlas(){const t=new ot(this.id,this.fontSize,Math.ceil(Math.sqrt(this.chars.length)),this.spacing),e=t.canvas.getContext("2d");e.clearRect(0,0,t.canvas.width,t.canvas.height),e.textBaseline="top",e.fillStyle="#FFFFFF",e.font=`${this.fontSize}px ${this.font}`;let i=0,s=0;for(let r=0;r<this.chars.length;r++)e.fillText(this.chars[r],i,s),t.glyphs.set(this.chars[r],{id:r,width:e.measureText(this.chars[r]).width}),(i+=this.fontSize+this.spacing)>t.canvas.width-this.fontSize&&(i=0,s+=this.fontSize+this.spacing);return t}}class ot{constructor(t,e,i,s){this.id=t,this.fontSize=e,this.gridSize=i,this.spacing=s,this.canvas=document.createElement("canvas"),this.glyphs=new Map,this.canvas.width=this.gridSize*(this.fontSize+this.spacing),this.canvas.height=this.canvas.width}}class at{constructor(t,e){this.gl=t,this.shaderLoader=e}create(t,e){const i=this.gl.createProgram(),s=this.shaderLoader.load(this.gl.VERTEX_SHADER,t),r=this.shaderLoader.load(this.gl.FRAGMENT_SHADER,e);this.gl.attachShader(i,s),this.gl.attachShader(i,r),this.gl.linkProgram(i);const o=this.gl.LINK_STATUS;if(!this.gl.getProgramParameter(i,o)){const t=this.gl.getProgramInfoLog(i);throw this.gl.deleteProgram(i),new Error(`Unable to initialize the Program: ${t}`)}return i}}class nt{constructor(t,e,i){this.gl=t,this.contextVersion=e,this.programFactory=i}loadProgram(){this.program=this.contextVersion===it.WebGL2?this.programFactory.create("#version 300 es\n\nin vec4 positionCoords;\nin vec2 textureCoords;\n\nuniform mat4 projectionMatrix;\nuniform mat4 modelMatrix;\nuniform mat4 textureMatrix;\n\nout vec2 texCoords;\n\nvoid main()\n{\n gl_Position = projectionMatrix * modelMatrix * positionCoords;\n texCoords = (textureMatrix * vec4(textureCoords, 0, 1)).xy;\n}","#version 300 es\nprecision highp float;\n\nin vec2 texCoords;\n\n// texture, mask and shadow\nuniform int u_renderTexture;\nuniform sampler2D u_texImage;\nuniform vec4 u_solidColor;\nuniform int u_useTintColor;\nuniform vec4 u_tintColor;\nuniform int u_useMaskColor;\nuniform vec4 u_maskColor;\nuniform float u_maskColorMix;\nuniform float u_alpha;\n\n// light\nstruct Light {\n vec2 position;\n float radius;\n float smoothMode;\n float intensity;\n};\n\nuniform int u_renderLight;\nuniform Light u_lights[64];\nuniform int u_numLights;\n\nout vec4 fragColor;\n\nvoid main()\n{\n if (u_renderTexture == 1) {\n vec4 texColor = texture(u_texImage, texCoords);\n\n if (texColor.a < 0.0001) {\n discard;\n }\n\n if (u_useTintColor == 1) {\n texColor = u_tintColor * texColor;\n }\n\n if (u_useMaskColor == 1) {\n texColor = mix(texColor, u_maskColor, clamp(u_maskColorMix, 0.0, 1.0));\n }\n\n fragColor = vec4(texColor.rgb, u_alpha * texColor.a); \n } else if (u_renderLight == 1) {\n vec2 fragCoord = gl_FragCoord.xy;\n float alpha = u_alpha;\n\n for (int i = 0; i < u_numLights; i++) {\n Light light = u_lights[i];\n float dist = distance(fragCoord, light.position);\n \n if (dist < light.radius) {\n alpha -= (light.smoothMode > 0.0 ? smoothstep(light.radius, 0.0, dist) : 1.0) * light.intensity;\n }\n }\n\n alpha = clamp(alpha, 0.0, u_alpha);\n\n fragColor = vec4(u_solidColor.rgb, alpha);\n } else {\n fragColor = vec4(u_solidColor.rgb, u_alpha);\n }\n}"):this.programFactory.create("precision mediump float;\n\nattribute vec2 positionCoords;\nattribute vec2 textureCoords;\n\nvarying vec2 texCoords;\n\nuniform mat4 projectionMatrix;\nuniform mat4 modelMatrix;\nuniform mat4 textureMatrix;\n\nvoid main()\n{\n gl_Position = projectionMatrix * modelMatrix * vec4(positionCoords, 0, 1);\n texCoords = (textureMatrix * vec4(textureCoords, 0, 1)).xy;\n}","precision mediump float;\n\nvarying vec2 texCoords;\n\n// texture, mask and shadow\nuniform int u_renderTexture;\nuniform sampler2D u_texImage;\nuniform vec4 u_solidColor;\nuniform int u_useTintColor;\nuniform vec4 u_tintColor;\nuniform int u_useMaskColor;\nuniform vec4 u_maskColor;\nuniform float u_maskColorMix;\nuniform float u_alpha;\n\n// light\nstruct Light {\n vec2 position;\n float radius;\n float smoothMode;\n float intensity;\n};\n\nuniform int u_renderLight;\nuniform Light u_lights[64];\nuniform int u_numLights;\n\nvoid main()\n{\n if (u_renderTexture == 1) {\n vec4 texColor = texture2D(u_texImage, texCoords);\n\n if (texColor.a < 0.0001) {\n discard;\n }\n\n if (u_useTintColor == 1) {\n texColor = u_tintColor * texColor;\n }\n\n if (u_useMaskColor == 1) {\n texColor = mix(texColor, u_maskColor, clamp(u_maskColorMix, 0.0, 1.0));\n }\n\n gl_FragColor = vec4(texColor.rgb, u_alpha * texColor.a);\n } else if (u_renderLight == 1) {\n vec2 fragCoord = gl_FragCoord.xy;\n float alpha = u_alpha;\n\n for (int i = 0; i < 64; i++) {\n if (u_lights[i].intensity == 0.0) continue; \n \n Light light = u_lights[i];\n float dist = distance(fragCoord, light.position);\n \n if (dist < light.radius) {\n alpha -= (light.smoothMode > 0.0 ? smoothstep(light.radius, 0.0, dist) : 1.0) * light.intensity;\n }\n }\n\n alpha = clamp(alpha, 0.0, u_alpha);\n\n gl_FragColor = vec4(u_solidColor.rgb, alpha);\n } else {\n gl_FragColor = vec4(u_solidColor.rgb, u_alpha);\n }\n}"),this.positionCoordsAttr=this.gl.getAttribLocation(this.program,"positionCoords"),this.texCoordsAttr=this.gl.getAttribLocation(this.program,"textureCoords"),this.modelMatrixUniform=this.gl.getUniformLocation(this.program,"modelMatrix"),this.projectionMatrixUniform=this.gl.getUniformLocation(this.program,"projectionMatrix"),this.textureMatrixUniform=this.gl.getUniformLocation(this.program,"textureMatrix"),this.renderTextureUniform=this.gl.getUniformLocation(this.program,"u_renderTexture"),this.textureUniform=this.gl.getUniformLocation(this.program,"u_texImage"),this.solidColorUniform=this.gl.getUniformLocation(this.program,"u_solidColor"),this.useTintColorUniform=this.gl.getUniformLocation(this.program,"u_useTintColor"),this.tintColorUniform=this.gl.getUniformLocation(this.program,"u_tintColor"),this.useMaskColorUniform=this.gl.getUniformLocation(this.program,"u_useMaskColor"),this.maskColorUniform=this.gl.getUniformLocation(this.program,"u_maskColor"),this.maskColorMixUniform=this.gl.getUniformLocation(this.program,"u_maskColorMix"),this.alphaUniform=this.gl.getUniformLocation(this.program,"u_alpha"),this.renderLightUniform=this.gl.getUniformLocation(this.program,"u_renderLight"),this.numLightsUniform=this.gl.getUniformLocation(this.program,"u_numLights"),this.gl.useProgram(this.program),this.gl.blendFunc(this.gl.SRC_ALPHA,this.gl.ONE_MINUS_SRC_ALPHA)}}class ht{constructor(t){this.gl=t}load(t,e){const i=this.gl.createShader(t);this.gl.shaderSource(i,e),this.gl.compileShader(i);const s=this.gl.COMPILE_STATUS;if(!this.gl.getShaderParameter(i,s)){const t=this.gl.getShaderInfoLog(i);throw this.gl.deleteShader(i),new Error(`Unable to initialize the shader program: ${t}`)}return i}}var lt="undefined"!=typeof Float32Array?Float32Array:Array;function ct(){var t=new lt(16);return lt!=Float32Array&&(t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0),t[0]=1,t[5]=1,t[10]=1,t[15]=1,t}function dt(t){return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}function gt(t,e,i){var s,r,o,a,n,h,l,c,d,g,m,u,p=i[0],y=i[1],f=i[2];return e===t?(t[12]=e[0]*p+e[4]*y+e[8]*f+e[12],t[13]=e[1]*p+e[5]*y+e[9]*f+e[13],t[14]=e[2]*p+e[6]*y+e[10]*f+e[14],t[15]=e[3]*p+e[7]*y+e[11]*f+e[15]):(s=e[0],r=e[1],o=e[2],a=e[3],n=e[4],h=e[5],l=e[6],c=e[7],d=e[8],g=e[9],m=e[10],u=e[11],t[0]=s,t[1]=r,t[2]=o,t[3]=a,t[4]=n,t[5]=h,t[6]=l,t[7]=c,t[8]=d,t[9]=g,t[10]=m,t[11]=u,t[12]=s*p+n*y+d*f+e[12],t[13]=r*p+h*y+g*f+e[13],t[14]=o*p+l*y+m*f+e[14],t[15]=a*p+c*y+u*f+e[15]),t}function mt(t,e,i){var s=i[0],r=i[1],o=i[2];return t[0]=e[0]*s,t[1]=e[1]*s,t[2]=e[2]*s,t[3]=e[3]*s,t[4]=e[4]*r,t[5]=e[5]*r,t[6]=e[6]*r,t[7]=e[7]*r,t[8]=e[8]*o,t[9]=e[9]*o,t[10]=e[10]*o,t[11]=e[11]*o,t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],t}function ut(t,e,i){var s=Math.sin(i),r=Math.cos(i),o=e[0],a=e[1],n=e[2],h=e[3],l=e[4],c=e[5],d=e[6],g=e[7];return e!==t&&(t[8]=e[8],t[9]=e[9],t[10]=e[10],t[11]=e[11],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t[0]=o*r+l*s,t[1]=a*r+c*s,t[2]=n*r+d*s,t[3]=h*r+g*s,t[4]=l*r-o*s,t[5]=c*r-a*s,t[6]=d*r-n*s,t[7]=g*r-h*s,t}Math.hypot||(Math.hypot=function(){for(var t=0,e=arguments.length;e--;)t+=arguments[e]*arguments[e];return Math.sqrt(t)});var pt=function(t,e,i,s,r,o,a){var n=1/(e-i),h=1/(s-r),l=1/(o-a);return t[0]=-2*n,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=-2*h,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=2*l,t[11]=0,t[12]=(e+i)*n,t[13]=(r+s)*h,t[14]=(a+o)*l,t[15]=1,t};const yt=(t,e,i,s)=>{t=dt(t),pt(t,-e.canvas.width/2,e.canvas.width/2,-e.canvas.height/2,e.canvas.height/2,-1,1),mt(t,t,[null!=i?i:1,null!=i?i:1,1]),gt(t,t,[-s.x,-s.y,0])},ft=t=>{const e=/^#?([a-f\d]{2})?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);return e?{r:parseInt(e[2],16)/256,g:parseInt(e[3],16)/256,b:parseInt(e[4],16)/256,a:void 0!==e[1]?parseInt(e[1],16)/256:1}:null};class xt{constructor(t){this.gl=t}render(t){const e=ft(t);this.gl.clearColor(e.r,e.g,e.b,e.a),this.gl.clear(this.gl.COLOR_BUFFER_BIT)}}var Mt;!function(t){t[t.Sprite=0]="Sprite",t[t.Text=1]="Text",t[t.Tilemap=2]="Tilemap",t[t.Mask=3]="Mask",t[t.Geometric=4]="Geometric",t[t.Video=5]="Video",t[t.Shadow=6]="Shadow"}(Mt||(Mt={}));var vt,Ct;!function(t){t[t.Polygon=0]="Polygon",t[t.Circumference=1]="Circumference",t[t.Line=2]="Line"}(vt||(vt={}));class St{constructor(t,e){this.gl=t,this.programManager=e,this.projectionMatrix=ct(),this.modelMatrix=ct(),this.textureMatrix=ct(),this.circumferencePositionBuffer=this.gl.createBuffer(),this.linesPositionBuffer=this.gl.createBuffer();const i=2*Math.PI/60,s=new Float32Array(m(1,60,1).reduce(((t,e)=>[...t,Math.cos(e*i),Math.sin(e*i)]),[]));this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.circumferencePositionBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,s,this.gl.STATIC_DRAW)}render(t,e,i){switch(this.gl.disableVertexAttribArray(this.programManager.texCoordsAttr),t.shape){case vt.Polygon:this.renderLines(t,e,this.gl.LINE_LOOP);break;case vt.Line:this.renderLines(t,e,this.gl.LINES);break;case vt.Circumference:this.renderCircumference(t,e,i);break;default:return!1}return!0}renderLines(t,e,i){var s;this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.linesPositionBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array(t.vertexModel.reduce(((t,e)=>[...t,e.x,e.y]),[])),this.gl.DYNAMIC_DRAW),this.gl.enableVertexAttribArray(this.programManager.positionCoordsAttr),this.gl.vertexAttribPointer(this.programManager.positionCoordsAttr,2,this.gl.FLOAT,!1,0,0),this.modelMatrix=dt(this.modelMatrix),gt(this.modelMatrix,this.modelMatrix,[t.position.x,t.position.y,0]),ut(this.modelMatrix,this.modelMatrix,null!==(s=t.rotation)&&void 0!==s?s:0),yt(this.projectionMatrix,this.gl,e.zoom,e.position),this.gl.uniformMatrix4fv(this.programManager.projectionMatrixUniform,!1,this.projectionMatrix),this.gl.uniformMatrix4fv(this.programManager.modelMatrixUniform,!1,this.modelMatrix),this.gl.uniformMatrix4fv(this.programManager.textureMatrixUniform,!1,this.textureMatrix),this.gl.uniform1i(this.programManager.renderTextureUniform,0);const{r:r,g:o,b:a,a:n}=ft(t.color);this.gl.uniform4f(this.programManager.solidColorUniform,r,o,a,n),this.gl.uniform1f(this.programManager.alphaUniform,1),this.gl.drawArrays(i,0,t.vertexModel.length),this.lastShape="polygon"}renderCircumference(t,e,i){i===Mt.Geometric&&"circumference"===this.lastShape||(this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.circumferencePositionBuffer),this.gl.enableVertexAttribArray(this.programManager.positionCoordsAttr),this.gl.vertexAttribPointer(this.programManager.positionCoordsAttr,2,this.gl.FLOAT,!1,0,0)),this.modelMatrix=dt(this.modelMatrix),gt(this.modelMatrix,this.modelMatrix,[t.position.x,t.position.y,0]),mt(this.modelMatrix,this.modelMatrix,[t.radius,t.radius,1]),yt(this.projectionMatrix,this.gl,e.zoom,e.position),this.gl.uniformMatrix4fv(this.programManager.projectionMatrixUniform,!1,this.projectionMatrix),this.gl.uniformMatrix4fv(this.programManager.modelMatrixUniform,!1,this.modelMatrix),this.gl.uniformMatrix4fv(this.programManager.textureMatrixUniform,!1,this.textureMatrix),this.gl.uniform1i(this.programManager.renderTextureUniform,0);const{r:s,g:r,b:o,a:a}=ft(t.color);this.gl.uniform4f(this.programManager.solidColorUniform,s,r,o,a),this.gl.uniform1f(this.programManager.alphaUniform,1),this.gl.drawArrays(this.gl.LINE_LOOP,0,60),this.lastShape="circumference"}}!function(t){t[t.Rectangle=0]="Rectangle",t[t.Circumference=1]="Circumference",t[t.Polygon=2]="Polygon"}(Ct||(Ct={}));let bt=class{constructor(t,e){this.gl=t,this.programManager=e,this.type=Mt.Mask,this.projectionMatrix=ct(),this.modelMatrix=ct(),this.textureMatrix=ct(),this.circumferencePositionBuffer=this.gl.createBuffer(),this.rectanglePositionBuffer=this.gl.createBuffer(),this.polygonPositionBuffer=this.gl.createBuffer();const i=2*Math.PI/60,s=[0,0];for(let t=0;t<=60;t++)s.push(Math.cos(t*i),Math.sin(t*i));this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.circumferencePositionBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array(s),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.rectanglePositionBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-.5,-.5,-.5,.5,.5,-.5,.5,-.5,-.5,.5,.5,.5]),this.gl.STATIC_DRAW)}render(t,e,i){return this.gl.disableVertexAttribArray(this.programManager.texCoordsAttr),t.shape===Ct.Rectangle?this.renderRectangle(t,e,i):t.shape===Ct.Circumference?this.renderCircumference(t,e,i):t.shape===Ct.Polygon&&this.renderPolygon(t,e,i),this.lastShape=t.shape,!0}renderRectangle(t,e,i){var s,r;i===Mt.Mask&&this.lastShape===Ct.Rectangle||(this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.rectanglePositionBuffer),this.gl.enableVertexAttribArray(this.programManager.positionCoordsAttr),this.gl.vertexAttribPointer(this.programManager.positionCoordsAttr,2,this.gl.FLOAT,!1,0,0)),this.modelMatrix=dt(this.modelMatrix),gt(this.modelMatrix,this.modelMatrix,[t.position.x,t.position.y,0]),ut(this.modelMatrix,this.modelMatrix,null!==(s=t.rotation)&&void 0!==s?s:0),mt(this.modelMatrix,this.modelMatrix,[t.width,t.height,1]),yt(this.projectionMatrix,this.gl,e.zoom,e.position),this.gl.uniformMatrix4fv(this.programManager.projectionMatrixUniform,!1,this.projectionMatrix),this.gl.uniformMatrix4fv(this.programManager.modelMatrixUniform,!1,this.modelMatrix),this.gl.uniformMatrix4fv(this.programManager.textureMatrixUniform,!1,this.textureMatrix),t.opacity>=0&&t.opacity<1?this.gl.enable(this.gl.BLEND):this.gl.disable(this.gl.BLEND),this.gl.uniform1i(this.programManager.renderTextureUniform,0);const{r:o,g:a,b:n,a:h}=ft(t.color);this.gl.uniform4f(this.programManager.solidColorUniform,o,a,n,h),this.gl.uniform1f(this.programManager.alphaUniform,null!==(r=t.opacity)&&void 0!==r?r:1),this.gl.drawArrays(this.gl.TRIANGLES,0,6)}renderCircumference(t,e,i){var s,r;i===Mt.Mask&&this.lastShape===Ct.Circumference||(this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.circumferencePositionBuffer),this.gl.enableVertexAttribArray(this.programManager.positionCoordsAttr),this.gl.vertexAttribPointer(this.programManager.positionCoordsAttr,2,this.gl.FLOAT,!1,0,0)),this.modelMatrix=dt(this.modelMatrix),gt(this.modelMatrix,this.modelMatrix,[t.position.x,t.position.y,0]),ut(this.modelMatrix,this.modelMatrix,null!==(s=t.rotation)&&void 0!==s?s:0),mt(this.modelMatrix,this.modelMatrix,[t.radius,t.radius,1]),yt(this.projectionMatrix,this.gl,e.zoom,e.position),this.gl.uniformMatrix4fv(this.programManager.projectionMatrixUniform,!1,this.projectionMatrix),this.gl.uniformMatrix4fv(this.programManager.modelMatrixUniform,!1,this.modelMatrix),this.gl.uniformMatrix4fv(this.programManager.textureMatrixUniform,!1,this.textureMatrix),t.opacity>=0&&t.opacity<1?this.gl.enable(this.gl.BLEND):this.gl.disable(this.gl.BLEND),this.gl.uniform1i(this.programManager.renderTextureUniform,0);const{r:o,g:a,b:n,a:h}=ft(t.color);this.gl.uniform4f(this.programManager.solidColorUniform,o,a,n,h),this.gl.uniform1f(this.programManager.alphaUniform,null!==(r=t.opacity)&&void 0!==r?r:1),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,62)}renderPolygon(t,e,i){var s,r;i===Mt.Mask&&this.lastShape===Ct.Polygon||(this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.polygonPositionBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array(t.vertices.reduce(((t,e)=>[...t,e.x,e.y]),[0,0])),this.gl.DYNAMIC_DRAW),this.gl.enableVertexAttribArray(this.programManager.positionCoordsAttr),this.gl.vertexAttribPointer(this.programManager.positionCoordsAttr,2,this.gl.FLOAT,!1,0,0)),this.modelMatrix=dt(this.modelMatrix),gt(this.modelMatrix,this.modelMatrix,[t.position.x,t.position.y,0]),ut(this.modelMatrix,this.modelMatrix,null!==(s=t.rotation)&&void 0!==s?s:0),yt(this.projectionMatrix,this.gl,e.zoom,e.position),this.gl.uniformMatrix4fv(this.programManager.projectionMatrixUniform,!1,this.projectionMatrix),this.gl.uniformMatrix4fv(this.programManager.modelMatrixUniform,!1,this.modelMatrix),this.gl.uniformMatrix4fv(this.programManager.textureMatrixUniform,!1,this.textureMatrix),t.opacity>=0&&t.opacity<1?this.gl.enable(this.gl.BLEND):this.gl.disable(this.gl.BLEND),this.gl.uniform1i(this.programManager.renderTextureUniform,0);const{r:o,g:a,b:n,a:h}=ft(t.color);this.gl.uniform4f(this.programManager.solidColorUniform,o,a,n,h),this.gl.uniform1f(this.programManager.alphaUniform,null!==(r=t.opacity)&&void 0!==r?r:1),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,t.vertices.length+1)}},At=class{constructor(t,e){this.gl=t,this.programManager=e,this.projectionMatrix=ct(),this.modelMatrix=ct(),this.textureMatrix=ct(),this.positionBuffer=this.gl.createBuffer(),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.positionBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-.5,-.5,-.5,.5,.5,-.5,.5,-.5,-.5,.5,.5,.5]),this.gl.STATIC_DRAW)}render(t,e,i){var s,r;i!==Mt.Shadow&&(this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.positionBuffer),this.gl.enableVertexAttribArray(this.programManager.positionCoordsAttr),this.gl.vertexAttribPointer(this.programManager.positionCoordsAttr,2,this.gl.FLOAT,!1,0,0),this.gl.disableVertexAttribArray(this.programManager.texCoordsAttr)),this.modelMatrix=dt(this.modelMatrix),gt(this.modelMatrix,this.modelMatrix,[t.position.x,t.position.y,0]),ut(this.modelMatrix,this.modelMatrix,null!==(s=t.rotation)&&void 0!==s?s:0),mt(this.modelMatrix,this.modelMatrix,[t.width,t.height,1]),yt(this.projectionMatrix,this.gl,e.zoom,e.position),this.gl.uniformMatrix4fv(this.programManager.projectionMatrixUniform,!1,this.projectionMatrix),this.gl.uniformMatrix4fv(this.programManager.modelMatrixUniform,!1,this.modelMatrix),this.gl.uniformMatrix4fv(this.programManager.textureMatrixUniform,!1,this.textureMatrix),this.gl.enable(this.gl.BLEND),this.gl.uniform1i(this.programManager.renderTextureUniform,0),this.gl.uniform1i(this.programManager.renderLightUniform,1);const{r:o,g:a,b:n,a:h}=ft(t.color);this.gl.uniform4f(this.programManager.solidColorUniform,o,a,n,h),this.gl.uniform1f(this.programManager.alphaUniform,null!==(r=t.opacity)&&void 0!==r?r:1),this.gl.uniform1i(this.programManager.numLightsUniform,t.lights.length);for(const[i,s]of t.lights.entries()){if(i>=64)break;this.gl.uniform2f(this.gl.getUniformLocation(this.programManager.program,`u_lights[${i}].position`),this.gl.canvas.width/2+(s.position.x-e.position.x)*e.zoom,this.gl.canvas.height/2+(s.position.y-e.position.y)*e.zoom),this.gl.uniform1f(this.gl.getUniformLocation(this.programManager.program,`u_lights[${i}].radius`),s.radius*e.zoom),this.gl.uniform1f(this.gl.getUniformLocation(this.programManager.program,`u_lights[${i}].smoothMode`),s.smooth?1:0),this.gl.uniform1f(this.gl.getUniformLocation(this.programManager.program,`u_lights[${i}].intensity`),Math.max(0,Math.min(1,s.intensity)))}return this.gl.drawArrays(this.gl.TRIANGLES,0,6),this.gl.uniform1i(this.programManager.renderLightUniform,0),!0}},wt=class{constructor(t,e,i){this.gl=t,this.programManager=e,this.textureManager=i,this.tiledPosVertices=new Map,this.tiledTexVertices=new Map,this.lastTexture=null,this.projectionMatrix=ct(),this.modelMatrix=ct(),this.textureMatrix=ct(),this.positionBuffer=this.gl.createBuffer(),this.textureBuffer=this.gl.createBuffer(),this.tiledPositionBuffer=this.gl.createBuffer(),this.tiledTextureBuffer=this.gl.createBuffer(),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.positionBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-.5,-.5,-.5,.5,.5,-.5,.5,-.5,-.5,.5,.5,.5]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([0,1,0,0,1,1,1,1,0,0,1,0]),this.gl.STATIC_DRAW),this.lastDrawMode="sprite"}render(t,e,i){var s,r,o,a;i!==Mt.Sprite&&!t.tiled||!t.tiled&&"sprite"!==this.lastDrawMode?(this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.positionBuffer),this.gl.enableVertexAttribArray(this.programManager.positionCoordsAttr),this.gl.vertexAttribPointer(this.programManager.positionCoordsAttr,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureBuffer),this.gl.enableVertexAttribArray(this.programManager.texCoordsAttr),this.gl.vertexAttribPointer(this.programManager.texCoordsAttr,2,this.gl.FLOAT,!1,0,0)):t.tiled&&(this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.tiledPositionBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,this.getTiledPositionVertices(t.tiled),this.gl.STATIC_DRAW),this.gl.enableVertexAttribArray(this.programManager.positionCoordsAttr),this.gl.vertexAttribPointer(this.programManager.positionCoordsAttr,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.tiledTextureBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,this.getTiledTextureVertices(t.tiled),this.gl.STATIC_DRAW),this.gl.enableVertexAttribArray(this.programManager.texCoordsAttr),this.gl.vertexAttribPointer(this.programManager.texCoordsAttr,2,this.gl.FLOAT,!1,0,0)),this.lastDrawMode=t.tiled?"tiled":"sprite",this.modelMatrix=dt(this.modelMatrix),gt(this.modelMatrix,this.modelMatrix,[t.position.x,t.position.y,0]),ut(this.modelMatrix,this.modelMatrix,null!==(s=t.rotation)&&void 0!==s?s:0),mt(this.modelMatrix,this.modelMatrix,[t.width*(t.flipHorizontally?-1:1),t.height*(t.flipVertically?-1:1),1]),this.textureMatrix=dt(this.textureMatrix),t.slice&&(gt(this.textureMatrix,this.textureMatrix,[t.slice.x/t.image.naturalWidth,t.slice.y/t.image.naturalHeight,0]),mt(this.textureMatrix,this.textureMatrix,[t.slice.width/t.image.naturalWidth,t.slice.height/t.image.naturalHeight,1])),yt(this.projectionMatrix,this.gl,e.zoom,e.position),this.gl.uniformMatrix4fv(this.programManager.projectionMatrixUniform,!1,this.projectionMatrix),this.gl.uniformMatrix4fv(this.programManager.modelMatrixUniform,!1,this.modelMatrix),this.gl.uniformMatrix4fv(this.programManager.textureMatrixUniform,!1,this.textureMatrix),this.gl.enable(this.gl.BLEND);const n=this.textureManager.getOrCreateTextureFromImage(t.image,t.smooth);if(this.lastTexture===n&&i===t.type||(this.gl.bindTexture(this.gl.TEXTURE_2D,n),this.gl.uniform1i(this.programManager.textureUniform,0),this.lastTexture=n),this.gl.uniform1i(this.programManager.renderTextureUniform,1),this.gl.uniform1f(this.programManager.alphaUniform,null!==(r=t.opacity)&&void 0!==r?r:1),this.gl.uniform1i(this.programManager.useTintColorUniform,t.tintColor?1:0),t.tintColor){const{r:e,g:i,b:s,a:r}=ft(t.tintColor);this.gl.uniform4f(this.programManager.tintColorUniform,e,i,s,r)}if(this.gl.uniform1i(this.programManager.useMaskColorUniform,t.maskColor?1:0),t.maskColor){const{r:e,g:i,b:s}=ft(t.maskColor);this.gl.uniform4f(this.programManager.maskColorUniform,e,i,s,null!==(o=t.opacity)&&void 0!==o?o:1),this.gl.uniform1f(this.programManager.maskColorMixUniform,null!==(a=t.maskColorMix)&&void 0!==a?a:1)}return t.tiled?this.gl.drawArrays(this.gl.TRIANGLES,0,t.tiled.x*t.tiled.y*6):this.gl.drawArrays(this.gl.TRIANGLES,0,6),!0}getTiledPositionVertices(t){const e=t.toString();if(!this.tiledPosVertices.has(e)){const i=[];for(let e=-t.x/2;e<t.x/2;e++)for(let s=-t.y/2;s<t.y/2;s++)i.push(e,s,e,s+1,e+1,s,e+1,s,e,s+1,e+1,s+1);this.tiledPosVertices.set(e,new Float32Array(i))}return this.tiledPosVertices.get(e)}getTiledTextureVertices(t){const e=t.toString();if(!this.tiledTexVertices.has(e)){const i=[];for(let e=0;e<t.x*t.y;e++)i.push(0,1,0,0,1,1,1,1,0,0,1,0);this.tiledTexVertices.set(e,new Float32Array(i))}return this.tiledTexVertices.get(e)}};var _t;!function(t){t[t.Center=0]="Center",t[t.RightUp=1]="RightUp",t[t.RightDown=2]="RightDown",t[t.RightCenter=3]="RightCenter"}(_t||(_t={}));let Et=class{constructor(t,e,i,s){this.gl=t,this.programManager=e,this.textureManager=i,this.fontAtlasFactory=s,this.type=Mt.Text,this.posVertices=[],this.texVertices=[],this.lastTexture=null,this.textSize=new n,this.modelPosition=new n,this.shadowPosition=new n,this.projectionMatrix=ct(),this.modelMatrix=ct(),this.textureMatrix=ct(),this.positionBuffer=this.gl.createBuffer(),this.textureBuffer=this.gl.createBuffer()}render(t,e,i,s=!1){var r;if(!t.text)return!1;const o=this.fontAtlasFactory.getOrCreate(Object.assign({font:t.font},t.textureAtlas));if(s||(this.generateTextVertices(o,t),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.positionBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array(this.posVertices),this.gl.DYNAMIC_DRAW),this.gl.enableVertexAttribArray(this.programManager.positionCoordsAttr),this.gl.vertexAttribPointer(this.programManager.positionCoordsAttr,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array(this.texVertices),this.gl.DYNAMIC_DRAW),this.gl.enableVertexAttribArray(this.programManager.texCoordsAttr),this.gl.vertexAttribPointer(this.programManager.texCoordsAttr,2,this.gl.FLOAT,!1,0,0)),t.shadow){const{color:s,offset:r,opacity:o}=t.shadow,a=Object.assign(Object.assign({},t),{color:s,opacity:o,position:n.add(this.shadowPosition,t.position,r)});a.shadow=void 0,this.render(a,e,i,!0),i=Mt.Text}this.modelMatrix=dt(this.modelMatrix),this.setPositionFromOrientation(t),gt(this.modelMatrix,this.modelMatrix,[this.modelPosition.x,this.modelPosition.y,0]),ut(this.modelMatrix,this.modelMatrix,null!==(r=t.rotation)&&void 0!==r?r:0),mt(this.modelMatrix,this.modelMatrix,[t.fontSize*(t.flipHorizontally?-1:1),t.fontSize*(t.flipVertically?-1:1),1]),this.textureMatrix=dt(this.textureMatrix),yt(this.projectionMatrix,this.gl,e.zoom,e.position),this.gl.uniformMatrix4fv(this.programManager.projectionMatrixUniform,!1,this.projectionMatrix),this.gl.uniformMatrix4fv(this.programManager.modelMatrixUniform,!1,this.modelMatrix),this.gl.uniformMatrix4fv(this.programManager.textureMatrixUniform,!1,this.textureMatrix),this.gl.enable(this.gl.BLEND);const a=this.textureManager.getOrCreateTextureFromCanvas(o.id,o.canvas,t.smooth);this.lastTexture===a&&i===Mt.Text||(this.gl.bindTexture(this.gl.TEXTURE_2D,a),this.gl.uniform1i(this.programManager.textureUniform,0),this.lastTexture=a),this.gl.uniform1i(this.programManager.useMaskColorUniform,0),this.gl.uniform1i(this.programManager.renderTextureUniform,1),this.gl.uniform1f(this.programManager.alphaUniform,t.opacity);const{r:h,g:l,b:c,a:d}=ft(t.color);return this.gl.uniform1i(this.programManager.useTintColorUniform,1),this.gl.uniform4f(this.programManager.tintColorUniform,h,l,c,d),this.gl.drawArrays(this.gl.TRIANGLES,0,this.posVertices.length/2),!0}generateTextVertices(t,{text:e,fontSize:i,letterSpacing:s,lineHeight:r}){this.posVertices=[],this.texVertices=[];let o=0,a=0,n=0;s/=i,r/=i;for(let i=0;i<e.length;i++){const h=e[i];if("\n"===h){n=Math.max(n,o),o=0,a-=r;continue}const l=t.glyphs.get(h);if(l){const e=l.width/t.fontSize;this.posVertices.push(o,a-1,o+e,a-1,o,a,o,a,o+e,a-1,o+e,a);const i=l.id%t.gridSize*(t.fontSize+t.spacing),r=(l.id/t.gridSize|0)*(t.fontSize+t.spacing),n=i/t.canvas.width,h=r/t.canvas.height,c=(i+l.width)/t.canvas.width,d=(r+t.fontSize)/t.canvas.height;this.texVertices.push(n,d,c,d,n,h,n,h,c,d,c,h),o+=e+s}}this.textSize.set(Math.max(n,o)*i,Math.abs(a-1)*i)}setPositionFromOrientation(t){this.modelPosition.set(t.position.x+(t.orientation===_t.Center?-this.textSize.x/2:0),t.position.y+(t.orientation===_t.Center||t.orientation===_t.RightCenter?this.textSize.y/2:t.orientation===_t.RightUp?this.textSize.y:0))}};var Rt;!function(t){t[t.Center=0]="Center",t[t.RightUp=1]="RightUp",t[t.RightDown=2]="RightDown",t[t.RightCenter=3]="RightCenter"}(Rt||(Rt={}));let Tt=class{constructor(t,e,i){this.gl=t,this.programManager=e,this.textureManager=i,this.posVertices=[],this.texVertices=[],this.lastTexture=null,this.tileset={width:0,tileWidth:0,tileHeight:0,texMargin:new n,texSpacing:new n,texWidth:0,texHeight:0,texCorrection:new n},this.projectionMatrix=ct(),this.modelMatrix=ct(),this.textureMatrix=ct(),this.positionBuffer=this.gl.createBuffer(),this.textureBuffer=this.gl.createBuffer()}render(t,e,i){var s,r,o,a;if(0===t.tiles.reduce(((t,e)=>t+e),0))return!1;if(this.processTileset(t),this.generateVertices(t),0===this.posVertices.length)return!1;this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.positionBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array(this.posVertices),this.gl.DYNAMIC_DRAW),this.gl.enableVertexAttribArray(this.programManager.positionCoordsAttr),this.gl.vertexAttribPointer(this.programManager.positionCoordsAttr,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array(this.texVertices),this.gl.DYNAMIC_DRAW),this.gl.enableVertexAttribArray(this.programManager.texCoordsAttr),this.gl.vertexAttribPointer(this.programManager.texCoordsAttr,2,this.gl.FLOAT,!1,0,0),this.modelMatrix=dt(this.modelMatrix),gt(this.modelMatrix,this.modelMatrix,[t.position.x,t.position.y,0]),ut(this.modelMatrix,this.modelMatrix,null!==(s=t.rotation)&&void 0!==s?s:0),mt(this.modelMatrix,this.modelMatrix,[t.tilemap.tileWidth*(t.flipHorizontal?-1:1),t.tilemap.tileHeight*(t.flipVertical?-1:1),1]),this.textureMatrix=dt(this.textureMatrix),mt(this.textureMatrix,this.textureMatrix,[this.tileset.tileWidth/t.tileset.image.naturalWidth,this.tileset.tileHeight/t.tileset.image.naturalHeight,1]),yt(this.projectionMatrix,this.gl,e.zoom,e.position),this.gl.uniformMatrix4fv(this.programManager.projectionMatrixUniform,!1,this.projectionMatrix),this.gl.uniformMatrix4fv(this.programManager.modelMatrixUniform,!1,this.modelMatrix),this.gl.uniformMatrix4fv(this.programManager.textureMatrixUniform,!1,this.textureMatrix),this.gl.enable(this.gl.BLEND);const n=this.textureManager.getOrCreateTextureFromImage(t.tileset.image,t.smooth);if(this.lastTexture===n&&i===Mt.Tilemap||(this.gl.bindTexture(this.gl.TEXTURE_2D,n),this.gl.uniform1i(this.programManager.textureUniform,0),this.lastTexture=n),this.gl.uniform1i(this.programManager.renderTextureUniform,1),this.gl.uniform1f(this.programManager.alphaUniform,null!==(r=t.opacity)&&void 0!==r?r:1),this.gl.uniform1i(this.programManager.useTintColorUniform,t.tintColor?1:0),t.tintColor){const{r:e,g:i,b:s,a:r}=ft(t.tintColor);this.gl.uniform4f(this.programManager.tintColorUniform,e,i,s,r)}if(this.gl.uniform1i(this.programManager.useMaskColorUniform,t.maskColor?1:0),t.maskColor){const{r:e,g:i,b:s}=ft(t.maskColor);this.gl.uniform4f(this.programManager.maskColorUniform,e,i,s,null!==(o=t.opacity)&&void 0!==o?o:1),this.gl.uniform1f(this.programManager.maskColorMixUniform,null!==(a=t.maskColorMix)&&void 0!==a?a:1)}return this.gl.drawArrays(this.gl.TRIANGLES,0,this.posVertices.length/2),!0}processTileset({tileset:t}){var e,i,s,r,o,a,h;t.margin=null!==(e=t.margin)&&void 0!==e?e:new n,t.spacing=null!==(i=t.spacing)&&void 0!==i?i:new n,t.correction=null!==(s=t.correction)&&void 0!==s?s:new n,this.tileset.width=t.width,this.tileset.tileWidth=t.tileWidth+(null!==(r=t.margin.x)&&void 0!==r?r:0)+(null!==(o=t.spacing.x)&&void 0!==o?o:0),this.tileset.tileHeight=t.tileHeight+(null!==(a=t.margin.y)&&void 0!==a?a:0)+(null!==(h=t.spacing.y)&&void 0!==h?h:0),this.tileset.texMargin.set(t.margin.x/this.tileset.tileWidth,t.margin.y/this.tileset.tileHeight),this.tileset.texSpacing.set(t.spacing.x/this.tileset.tileWidth,t.spacing.y/this.tileset.tileHeight),this.tileset.texCorrection.set(t.correction.x/this.tileset.tileWidth,t.correction.y/this.tileset.tileHeight),this.tileset.texWidth=1-this.tileset.texMargin.x-this.tileset.texSpacing.x-2*this.tileset.texCorrection.x,this.tileset.texHeight=1-this.tileset.texMargin.y-this.tileset.texSpacing.y-2*this.tileset.texCorrection.y}generateVertices({tiles:t,tilemap:e}){this.posVertices=[],this.texVertices=[];const i=Math.floor(t.length/e.width);t.forEach(((t,s)=>{if(0===t)return;const r=s%e.width-e.width/2,o=i/2-Math.floor(s/e.width);this.posVertices.push(r,o-1,r+1,o-1,r,o,r,o,r+1,o-1,r+1,o);const a=(t-1)%this.tileset.width+this.tileset.texMargin.x+this.tileset.texCorrection.x,n=Math.floor((t-1)/this.tileset.width)+this.tileset.texMargin.y+this.tileset.texCorrection.y;this.texVertices.push(a,n+this.tileset.texHeight,a+this.tileset.texWidth,n+this.tileset.texHeight,a,n,a,n,a+this.tileset.texWidth,n+this.tileset.texHeight,a+this.tileset.texWidth,n)}))}},Bt=class{constructor(t,e,i){this.gl=t,this.programManager=e,this.textureManager=i,this.lastTexture=null,this.projectionMatrix=ct(),this.modelMatrix=ct(),this.textureMatrix=ct(),this.positionBuffer=this.gl.createBuffer(),this.textureBuffer=this.gl.createBuffer(),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.positionBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-.5,-.5,-.5,.5,.5,-.5,.5,-.5,-.5,.5,.5,.5]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([0,1,0,0,1,1,1,1,0,0,1,0]),this.gl.STATIC_DRAW)}render(t,e,i){var s,r,o,a;i!==Mt.Video&&(this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.positionBuffer),this.gl.enableVertexAttribArray(this.programManager.positionCoordsAttr),this.gl.vertexAttribPointer(this.programManager.positionCoordsAttr,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureBuffer),this.gl.enableVertexAttribArray(this.programManager.texCoordsAttr),this.gl.vertexAttribPointer(this.programManager.texCoordsAttr,2,this.gl.FLOAT,!1,0,0)),this.modelMatrix=dt(this.modelMatrix),gt(this.modelMatrix,this.modelMatrix,[t.position.x,t.position.y,0]),ut(this.modelMatrix,this.modelMatrix,null!==(s=t.rotation)&&void 0!==s?s:0),mt(this.modelMatrix,this.modelMatrix,[t.width*(t.flipHorizontal?-1:1),t.height*(t.flipVertical?-1:1),1]),this.textureMatrix=dt(this.textureMatrix),t.slice&&(gt(this.textureMatrix,this.textureMatrix,[t.slice.x/t.video.videoWidth,t.slice.y/t.video.videoHeight,0]),mt(this.textureMatrix,this.textureMatrix,[t.slice.width/t.video.videoWidth,t.slice.height/t.video.videoHeight,1])),yt(this.projectionMatrix,this.gl,e.zoom,e.position),this.gl.uniformMatrix4fv(this.programManager.projectionMatrixUniform,!1,this.projectionMatrix),this.gl.uniformMatrix4fv(this.programManager.modelMatrixUniform,!1,this.modelMatrix),this.gl.uniformMatrix4fv(this.programManager.textureMatrixUniform,!1,this.textureMatrix),this.gl.enable(this.gl.BLEND);const n=this.textureManager.getOrCreateTextureFromVideo(t.video);if(this.lastTexture===n&&i===Mt.Video||(this.gl.bindTexture(this.gl.TEXTURE_2D,n),this.gl.uniform1i(this.programManager.textureUniform,0),this.lastTexture=n),t.video.readyState>=HTMLMediaElement.HAVE_CURRENT_DATA&&this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,t.video),this.gl.uniform1i(this.programManager.renderTextureUniform,1),this.gl.uniform1f(this.programManager.alphaUniform,null!==(r=t.opacity)&&void 0!==r?r:1),this.gl.uniform1i(this.programManager.useTintColorUniform,t.tintColor?1:0),t.tintColor){const{r:e,g:i,b:s,a:r}=ft(t.tintColor);this.gl.uniform4f(this.programManager.tintColorUniform,e,i,s,r)}if(this.gl.uniform1i(this.programManager.useMaskColorUniform,t.maskColor?1:0),t.maskColor){const{r:e,g:i,b:s}=ft(t.maskColor);this.gl.uniform4f(this.programManager.maskColorUniform,e,i,s,null!==(o=t.opacity)&&void 0!==o?o:1),this.gl.uniform1f(this.programManager.maskColorMixUniform,null!==(a=t.maskColorMix)&&void 0!==a?a:1)}return this.gl.drawArrays(this.gl.TRIANGLES,0,6),!0}};class Pt{constructor(t){this.gl=t}createFromImage(t,e=!1,i=null){return i=null!=i?i:this.gl.createTexture(),t.naturalWidth?this.createFromSource(t,i,e):t.addEventListener("load",(()=>this.createFromSource(t,i,e))),i}createFromCanvas(t,e=!1,i=null){return i=null!=i?i:this.gl.createTexture(),this.createFromSource(t,i,e),i}createPixelTexture(){const t=this.gl.createTexture();return this.gl.bindTexture(this.gl.TEXTURE_2D,t),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,1,1,0,this.gl.RGBA,this.gl.UNSIGNED_BYTE,new Uint8Array([0,0,0,255])),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.bindTexture(this.gl.TEXTURE_2D,null),t}createFromSource(t,e,i=!1){this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,t),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),i?(this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR)):(this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.NEAREST),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.NEAREST)),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}}const Dt=(t,e)=>`${e?"_smooth_":""}${t}`;class Ft{constructor(t){this.textureFactory=t,this.textures=new Map}getOrCreateTextureFromImage(t,e=!1){var i;return null!==(i=this.textures.get(Dt(t.src,e)))&&void 0!==i?i:this.createTextureFromImage(t,e)}createTextureFromImage(t,e=!1){const i=this.textureFactory.createFromImage(t,e);return this.textures.set(Dt(t.src,e),i),i}getOrCreateTextureFromCanvas(t,e,i=!1){var s;return null!==(s=this.textures.get(Dt(t,i)))&&void 0!==s?s:this.createTextureFromCanvas(t,e,i)}createTextureFromCanvas(t,e,i=!1){const s=this.textureFactory.createFromCanvas(e,i);return this.textures.set(Dt(t,i),s),s}getOrCreateTextureFromVideo(t){var e;return null!==(e=this.textures.get(t.src))&&void 0!==e?e:this.createTextureFromVideo(t)}createTextureFromVideo(t){const e=this.textureFactory.createPixelTexture();return this.textures.set(t.src,e),e}}let Ut=class{constructor(t){this.renderers=new Map;const e=new st(t),i=e.gl,s=e.contextVersion,r=new nt(i,s,new at(i,new ht(i))),o=new Ft(new Pt(i)),a=new rt;this.renderers.set(Mt.Sprite,new wt(i,r,o)),this.renderers.set(Mt.Text,new Et(i,r,o,a)),this.renderers.set(Mt.Tilemap,new Tt(i,r,o)),this.renderers.set(Mt.Geometric,new St(i,r)),this.renderers.set(Mt.Mask,new bt(i,r)),this.renderers.set(Mt.Video,new Bt(i,r,o)),this.renderers.set(Mt.Shadow,new At(i,r)),this.canvasColorRenderer=new xt(i),r.loadProgram()}render(t,e){this.renderers.get(t.type).render(t,e,this.lastRender)&&(this.lastRender=t.type)}renderCanvasColor(t){this.canvasColorRenderer.render(t)}};Ut=o([i(t.WebGLManager),a(0,s(t.CanvasElement))],Ut);class It{constructor(t){this.fixedToTimeScale=!1,this.layer=Z,this.loop=!1,this.offset=new n,this.playing=!1,this.rotation=0,this.volume=1,this._currentVideoSrc=void 0,this._playPromisePendind=!1,this._renderData={type:Mt.Video,height:void 0,layer:void 0,position:new n,video:void 0,width:void 0,flipHorizontal:void 0,flipVertical:void 0,maskColor:void 0,maskColorMix:void 0,opacity:void 0,rotation:void 0,slice:void 0,tintColor:void 0},Object.assign(this,t)}play(t){t&&(this.video=t),this.action="play"}pause(){this.action="pause"}stop(){this.action="stop"}}const Lt=["click","contextmenu","auxclick","dblclick","mousedown","mouseup","pointerup","touchend","keydown","keyup"];let jt=class{constructor(t,e,i){this.entityManager=t,this.renderManager=e,this.timeManager=i,this.scaledOffset=new n,this.canPlay=!0,this.userInputErrorCatched=!1,this.userInputEventHandler=()=>{Lt.forEach((t=>{window.removeEventListener(t,this.userInputEventHandler)})),this.canPlay=!0}}onCreate(){document.addEventListener("visibilitychange",(()=>{this.entityManager.search(It).forEach((({component:{video:t,playing:e}})=>{document.hidden&&t?t.pause():!document.hidden&&t&&e&&t.play()}))}))}catchUserInput(){this.canPlay=!1,this.userInputErrorCatched=!0,Lt.forEach((t=>window.addEventListener(t,this.userInputEventHandler)))}onUpdate(){this.entityManager.search(It).forEach((({entity:t,component:e})=>{var i,s;const r=this.entityManager.getComponent(t,J);if(!r)throw new Error("VideoRenderer component needs a Transform");e.video&&e.video.duration&&(this.checkVideoState(e),this.scaledOffset.set(e.offset.x*r.localScale.x,e.offset.y*r.localScale.y),n.add(e._renderData.position,r.localPosition,this.scaledOffset),e._renderData.layer=e.layer,e._renderData.video=e.video,e._renderData.width=(null!==(i=e.width)&&void 0!==i?i:e.video.videoWidth)*Math.abs(r.localScale.x),e._renderData.height=(null!==(s=e.height)&&void 0!==s?s:e.video.videoHeight)*Math.abs(r.localScale.y),e._renderData.rotation=r.localRotation+e.rotation,e._renderData.slice=e.slice,e._renderData.flipHorizontal=e.flipHorizontally,e._renderData.flipVertical=e.flipVertically,e._renderData.opacity=e.opacity,e._renderData.maskColor=e.maskColor,e._renderData.maskColorMix=e.maskColorMix,e._renderData.tintColor=e.tintColor,0!==r.localRotation&&this.scaledOffset.magnitude>0&&this.translateRenderPosition(e._renderData,r),this.renderManager.addRenderData(e._renderData))}))}translateRenderPosition(t,e){const i=Math.atan2(this.scaledOffset.y,this.scaledOffset.x)+e.localRotation;t.position.set(e.localPosition.x+this.scaledOffset.magnitude*Math.cos(i),e.localPosition.y+this.scaledOffset.magnitude*Math.sin(i))}checkVideoState(t){const{video:e,action:i,loop:s,volume:r}=t;e.src!==t._currentVideoSrc&&(t._currentVideoSrc=e.src,t.playing=!1,e.currentTime=0),e.loop=s,e.volume=r,e.playbackRate=t.fixedToTimeScale?this.timeManager.timeScale<.0625?0:Math.min(this.timeManager.timeScale,16):1,"play"!==i||t.playing||t._playPromisePendind||!this.canPlay||(t._playPromisePendind=!0,e.play().then((()=>{t._playPromisePendind=!1,t.playing=!0})).catch((()=>{t._playPromisePendind=!1,this.userInputErrorCatched||this.catchUserInput()}))),"play"===i&&e.ended&&(t.action="stop",t.playing=!1),"stop"===i&&e.currentTime>0&&(e.pause(),e.currentTime=0,t.playing=!1),"pause"!==i||e.paused||e.pause()}onDisabled(){this.entityManager.search(It).forEach((({component:t})=>{t.video&&(t.video.pause(),t.video.currentTime=0)}))}onDestroy(){this.onDisabled()}};jt=o([i(H.VideoRendererSystem),a(0,s(t.EntityManager)),a(1,s(t.RenderManager)),a(2,s(t.TimeManager))],jt);class Ot{constructor(t,e){this.entityManager=t,this.assetManager=e,this.systems=[]}loadSystems(){}loadAssets(){}setup(){}}let kt=class{constructor(t,e,i,s,r){this.systemManager=t,this.systemFactory=e,this.entityManager=i,this.assetManager=s,this.timeManager=r,this.scenes=new Map,this._loadingScene=!1,this._sceneLoadedThisFrame=!1}addScene(t,e,i=!1){const s=new t(this.entityManager,this.assetManager);this.scenes.set(e,s),i&&(this.openingSceneName=e)}loadScene(t){if(!this.scenes.has(t))throw new Error(`Invalid scene name: '${t}'`);this.sceneNameToBeLoaded=t}loadOpeningScene(){if(!this.openingSceneName)throw new Error("There is no opening scene");this.sceneNameToBeLoaded=this.openingSceneName}get loadingScene(){return this._loadingScene}get sceneLoadedThisFrame(){return this._sceneLoadedThisFrame}update(){this._sceneLoadedThisFrame=!1,this.sceneNameToBeLoaded&&(this.currentSceneName&&this.destroyCurrentScene(),this.currentSceneName=this.sceneNameToBeLoaded,this.sceneNameToBeLoaded=void 0,this.scenes.get(this.currentSceneName).loadAssets(),this.scenes.get(this.currentSceneName).loadSystems(),this._loadingScene=!0),this._loadingScene&&this.assetManager.getAssetsLoaded()&&(this._loadingScene=!1,this._sceneLoadedThisFrame=!0,this.scenes.get(this.currentSceneName).setup(),this.systemManager.update(X.Transform),this.systemManager.update(X.PreGameLogic),this.scenes.get(this.currentSceneName).systems.forEach(((t,e)=>{this.systemFactory.createSystemIfNotExists(t),this.systemManager.enableSystem(t),this.systemManager.setExecutionOrder(t,e)})))}destroyCurrentScene(){this.systemManager.disableSystem(Y),this.systemManager.disableSystem(jt),this.scenes.get(this.currentSceneName).systems.forEach((t=>this.systemManager.disableSystem(t))),this.entityManager.removeAllEntities(),this.timeManager.clearAllIntervals(),this.systemManager.enableSystem(Y),this.systemManager.enableSystem(jt)}};kt=o([i(t.SceneManager),a(0,s(t.SystemManager)),a(1,s(t.CreateSystemService)),a(2,s(t.EntityManager)),a(3,s(t.AssetManager)),a(4,s(t.TimeManager))],kt);class Vt{constructor(t){this.width=0,this.height=0,this.radius=0,this.touchEnabled=!0,this.offset=new n,this.pressed=!1,this.mouseOver=!1,Object.assign(this,t)}}var Gt;!function(t){t[t.Rectangle=0]="Rectangle",t[t.Circumference=1]="Circumference"}(Gt||(Gt={}));let zt=class{constructor(t,e){this.entityManager=t,this.scaled={position:new n,width:0,height:0,radius:0},this.distance=new n,this.pressedLastFrame=!1,this.mouse=e.mouse,this.touchScreen=e.touchScreen}onUpdate(){this.entityManager.search(Vt).forEach((({entity:t,component:e})=>{const i=this.entityManager.getComponent(t,J);if(!i)throw new Error("Button component needs a Transform");this.pressedLastFrame=e.pressed,e.pressed=!1,this.scale(e,i),e.mouseOver=this.isMouseOverButton(e),e.pressed=e.mouseOver&&this.mouse.leftButtonPressed,e.touchEnabled&&this.touchScreen.touching&&(this.resolveTouchAndRectangle(e),this.resolveTouchAndCircumference(e)),e.onClick&&!this.pressedLastFrame&&e.pressed&&e.onClick(),e.onPressed&&e.pressed&&e.onPressed()}))}scale(t,{localPosition:e,localScale:i}){this.scaled.width=t.width*i.x,this.scaled.height=t.height*i.y,this.scaled.position.x=e.x+t.offset.x*i.x,this.scaled.position.y=e.y+t.offset.y*i.y,this.scaled.radius=t.radius*Math.max(Math.abs(i.x),Math.abs(i.y))}isMouseOverButton(t){return this.isMouseOverRectangleButton(t)||this.isMouseOverCircumferenceButton(t)}isMouseOverRectangleButton(t){return t.shape===Gt.Rectangle&&(u(this.mouse.positionInViewport.x,this.scaled.position.x-this.scaled.width/2,this.scaled.position.x+this.scaled.width/2)&&u(this.mouse.positionInViewport.y,this.scaled.position.y-this.scaled.height/2,this.scaled.position.y+this.scaled.height/2))}isMouseOverCircumferenceButton(t){return t.shape===Gt.Circumference&&(n.subtract(this.distance,this.scaled.position,this.mouse.positionInViewport),this.distance.magnitude<=this.scaled.radius)}resolveTouchAndRectangle(t){if(t.shape===Gt.Rectangle)for(const{positionInViewport:e,radius:i}of this.touchScreen.interactions){if(t.pressed)return;t.pressed=this.scaled.position.x+this.scaled.width/2>=e.x-i.x&&this.scaled.position.x-this.scaled.width/2<=e.x+i.x&&this.scaled.position.y+this.scaled.height/2>=e.y-i.y&&this.scaled.position.y-this.scaled.height/2<=e.y+i.y}}resolveTouchAndCircumference(t){if(t.shape===Gt.Circumference)for(const{positionInViewport:e,radius:i}of this.touchScreen.interactions){if(t.pressed)return;n.subtract(this.distance,this.scaled.position,e),t.pressed=this.distance.magnitude<=this.scaled.radius+Math.max(i.x,i.y)}}};zt=o([i(H.ButtonSystem),a(0,s(t.EntityManager)),a(1,s(t.InputManager))],zt);class Wt{constructor(){this.entities=[]}}let Ht=class{constructor(t){this.entityManager=t}onUpdate(){this.entityManager.search(Wt).forEach((({entity:t,component:e})=>{e.entities=this.entityManager.getComponent(t,J)._childEntities}))}};Ht=o([i(H.ChildrenSystem),a(0,s(t.EntityManager))],Ht);class Nt{}let Yt=class{constructor(t){this.entityManager=t}onUpdate(){this.entityManager.search(Nt).forEach((({entity:t,component:e})=>{e.entity=this.entityManager.getComponent(t,J)._parentEntity}))}};Yt=o([i(H.ParentSystem),a(0,s(t.EntityManager))],Yt);class Xt{constructor(t){Object.assign(this,t)}}class $t{constructor(t){this.layer=Z,this.tileset=void 0,this.data=[],this.chunks=[],this.width=0,this.height=0,this.tileWidth=void 0,this.tileHeight=void 0,this.tintColor=void 0,this.opacity=1,this.smooth=!1,this._processed=!1,this._renderData=[],Object.assign(this,t)}}let Kt=class{constructor(t){this.entityManager=t}onUpdate(){this.entityManager.search(Xt).forEach((({entity:t,component:e})=>{const i=this.entityManager.getComponent(t,$t);if(!i)return;const s=e.tilemap.layers.find((t=>t.name===e.layerToRender&&"tilelayer"===t.type));s&&(e.tilemap.infinite?i.chunks=s.chunks:i.data=s.data,i.width=e.tilemap.width)}))}};Kt=o([i(H.TiledWrapperSystem),a(0,s(t.EntityManager))],Kt);const qt=16;let Qt=class{constructor(t){this.entityManager=t}onUpdate(){this.entityManager.search($t).forEach((({component:t})=>{var e,i;t._processed||(t.chunks&&t.chunks.length>0?this.chunksToData(t):t.data&&t.data.length>0&&this.dataToChunks(t),t.tileWidth=null!==(e=t.tileWidth)&&void 0!==e?e:t.tileset.tileWidth,t.tileHeight=null!==(i=t.tileHeight)&&void 0!==i?i:t.tileset.tileHeight,t._processed=!0)}))}dataToChunks(t){t.height=Math.ceil(t.data.length/t.width);const e=Math.ceil(t.width/qt),i=Math.ceil(t.height/qt);for(let s=0;s<i;s++)for(let i=0;i<e;i++){const e={x:i*qt,y:s*qt,width:qt,height:qt,data:[]};for(let i=0;i<e.width*e.height;i++){const s=e.x+i%e.width,r=t.width*(e.y+Math.floor(i/e.width));e.data[i]=s<t.width&&r<t.height*t.width?t.data[r+s]:0}t.chunks.push(e)}}chunksToData(t){t.data=[],t.chunks.forEach((e=>e.data.forEach(((i,s)=>{t.data[t.width*(e.y+Math.floor(s/e.width))+e.x+s%e.width]=i})))),t.height=Math.ceil(t.data.length/t.width)}};Qt=o([i(H.TilemapPreProcessingSystem),a(0,s(t.EntityManager))],Qt);const Jt=t=>t.parent?1+Jt(t.parent):0;let Zt=class{constructor(t){this.entityManager=t}onUpdate(){this.entityManager.search(J).sort(((t,e)=>Jt(t.component)-Jt(e.component))).forEach((({component:t,entity:e})=>{t.parent&&this.entityManager.getEntityForComponent(t.parent)?(t._childEntities=[],t._parentEntity=this.entityManager.getEntityForComponent(t.parent),t.parent._childEntities.push(e),this.translateChild(t.parent,t)):this.updateTransform(t)}))}updateTransform(t){t.parent=void 0,t._parentEntity=void 0,t._childEntities=[],t.localPosition.copy(t.position),t.localScale.copy(t.scale),t.localRotation=t.rotation}translateChild(t,e){e.localRotation=e.rotation+t.localRotation,e.localScale.x=e.scale.x*t.scale.x,e.localScale.y=e.scale.y*t.scale.y;const i=Math.atan2(e.position.y,e.position.x)+t.localRotation;e.localPosition.set(t.localPosition.x+e.position.magnitude*Math.cos(i),t.localPosition.y+e.position.magnitude*Math.sin(i))}};Zt=o([i(H.TransformSystem),a(0,s(t.EntityManager))],Zt);let te=class{constructor(t){this.inputManager=t,this.gamepads=new Map,this.eventHandler=t=>{"gamepadconnected"===t.type?this.gamepadConnected(t.gamepad):"gamepaddisconnected"===t.type&&this.gamepadDisconected(t.gamepad)},window.addEventListener("gamepadconnected",this.eventHandler),window.addEventListener("gamepaddisconnected",this.eventHandler)}gamepadConnected(t){this.gamepads.set(t.index,t),this.inputManager.gamepads[t.index]||(this.inputManager.gamepads[t.index]=new U,this.inputManager.gamepads[t.index].index=t.index),this.inputManager.gamepads[t.index].id=t.id,this.inputManager.gamepads[t.index].connected=!0}gamepadDisconected(t){this.gamepads.delete(t.index),this.inputManager.gamepads[t.index].connected=!1}onUpdate(){for(const t of this.getGamepadsFromBrowser())t&&(!1===this.gamepads.has(t.index)?this.gamepadConnected(t):this.gamepads.set(t.index,t));this.gamepads.forEach((t=>{const e=this.inputManager.gamepads[t.index];t.buttons.forEach(((t,i)=>e.buttons.set(i,t.pressed))),t.axes.forEach(((t,i)=>e.axes.set(i,t))),e.vibrationInput&&(t.vibrationActuator.playEffect(t.vibrationActuator.type,{duration:e.vibrationInput.duration,weakMagnitude:e.vibrationInput.weakMagnitude,strongMagnitude:e.vibrationInput.strongMagnitude,startDelay:e.vibrationInput.startDelay}).catch((()=>e.vibrating=!1)).finally((()=>e.vibrating=!1)),e.vibrating=!0,e.vibrationInput=void 0)}))}getGamepadsFromBrowser(){return navigator.getGamepads?navigator.getGamepads():navigator.webkitGetGamepads?navigator.webkitGetGamepads:[]}};te=o([i(H.GamepadSystem),a(0,s(t.InputManager))],te);let ee=class{constructor(t,{keyboard:e}){this.pressedKeys=[],this.eventHandler=t=>{"keydown"!==t.type||this.pressedKeys.includes(t.code)||this.pressedKeys.push(t.code),"keyup"===t.type&&this.pressedKeys.includes(t.code)&&this.pressedKeys.splice(this.pressedKeys.indexOf(t.code),1)},this.keyboard=e,t.addEventListener("keydown",this.eventHandler),t.addEventListener("keyup",this.eventHandler),t.addEventListener("focusout",(()=>this.pressedKeys=[]))}onUpdate(){this.keyboard.pressedKeys=[...this.pressedKeys]}};ee=o([i(H.KeyboardSystem),a(0,s(t.CanvasElement)),a(1,s(t.InputManager))],ee);let ie=class{constructor(t,{mouse:e}){this.canvas=t,this.leftButtonPressed=!1,this.scrollButtonPressed=!1,this.rightButtonPressed=!1,this.positionInViewport=new n,this.lastPositionInViewport=new n,this.mouse=e,this.canvas.addEventListener("mousemove",(t=>this.updatePosition(t))),this.canvas.addEventListener("mousedown",(t=>this.updateButtonDown(t))),this.canvas.addEventListener("mouseup",(t=>this.updateButtonUp(t))),this.canvas.addEventListener("wheel",(t=>this.handleWheelEvent(t))),this.canvas.addEventListener("focusout",(()=>this.onFocusOut()))}updateButtonDown(t){this.canvas.focus(),t.preventDefault(),t.stopPropagation(),this.leftButtonPressed=0===t.button,this.scrollButtonPressed=1===t.button,this.rightButtonPressed=2===t.button}updateButtonUp(t){t.preventDefault(),t.stopPropagation(),this.leftButtonPressed=0!==t.button&&this.leftButtonPressed,this.scrollButtonPressed=1!==t.button&&this.scrollButtonPressed,this.rightButtonPressed=2!==t.button&&this.rightButtonPressed}updatePosition(t){t.preventDefault(),t.stopPropagation(),this.positionInViewport.set(t.offsetX/(this.canvas.clientWidth/this.canvas.width)-this.canvas.width/2,-t.offsetY/(this.canvas.clientHeight/this.canvas.height)+this.canvas.height/2)}handleWheelEvent(t){t.preventDefault(),t.stopPropagation(),this.wheelEvent=t}onFocusOut(){this.leftButtonPressed=!1,this.scrollButtonPressed=!1,this.rightButtonPressed=!1}onUpdate(){this.mouse.leftButtonPressed=this.leftButtonPressed,this.mouse.rightButtonPressed=this.rightButtonPressed,this.mouse.scrollButtonPressed=this.scrollButtonPressed,this.mouse.positionInViewport.copy(this.positionInViewport),this.positionInViewport.equals(this.lastPositionInViewport)?this.mouse.hasMoved=!1:(this.mouse.hasMoved=!0,this.lastPositionInViewport.copy(this.positionInViewport)),this.wheelEvent?(this.mouse.wheelScroll.set(this.wheelEvent.deltaX,this.wheelEvent.deltaY),this.wheelEvent=void 0):this.mouse.wheelScroll.set(0,0)}};ie=o([i(H.MouseSystem),a(0,s(t.CanvasElement)),a(1,s(t.InputManager))],ie);let se=class{constructor(t,{touchScreen:e}){this.canvas=t,this.touching=!1,this.interactions=[],this.eventHandler=t=>{"touchstart"===t.type&&(this.touching=!0,this.updatePosition(t)),"touchmove"===t.type&&this.updatePosition(t),"touchend"!==t.type&&"touchcancel"!==t.type||(this.touching=!1)},this.touchScreen=e,this.canvas.addEventListener("touchstart",this.eventHandler),this.canvas.addEventListener("touchend",this.eventHandler),this.canvas.addEventListener("touchcancel",this.eventHandler),this.canvas.addEventListener("touchmove",this.eventHandler)}updatePosition(t){if(t.preventDefault(),t.stopPropagation(),this.interactions=[],0!==t.targetTouches.length)for(let e=0;e<t.targetTouches.length;e++)this.interactions[e]={positionInViewport:new n((t.targetTouches[e].clientX-this.canvas.offsetLeft)/(this.canvas.clientWidth/this.canvas.width)-this.canvas.width/2,-(t.targetTouches[e].clientY-this.canvas.offsetTop)/(this.canvas.clientHeight/this.canvas.height)+this.canvas.height/2),radius:new n(t.targetTouches[e].radiusX,t.targetTouches[e].radiusY)}}onUpdate(){this.touchScreen.touching=this.touching,this.touchScreen.interactions=[...this.touchScreen.interactions]}};se=o([i(H.TouchScreenSystem),a(0,s(t.CanvasElement)),a(1,s(t.InputManager))],se);class re{constructor(t){this.animations=new Map,this.speed=1,this.reset=!1,this.playing=!1,this.currentFrame=0,this.currentTime=0,this._currentAnimation=void 0,Object.assign(this,t)}}class oe{constructor(t){this.slice={size:new n,offset:new n,padding:new n},this.frames=[],this.fps=12,this.loop=!1,Object.assign(this,t)}}class ae{constructor(t){this.layer=Z,this.smooth=!1,this.offset=new n,this.flipHorizontally=!1,this.flipVertically=!1,this.rotation=0,this.opacity=1,this.scale=new n(1,1),this._renderData={type:Mt.Sprite,position:new n,layer:void 0,image:void 0,width:void 0,height:void 0},Object.assign(this,t)}}let ne=class{constructor(t,e){this.entityManager=t,this.timeManager=e}onUpdate(){this.entityManager.search(re).forEach((({entity:t,component:e})=>{if(this.reset(e),this.animation=e.animations.get(e.animation),!this.animation)return;this.play(e),e._currentAnimation=e.animation;const i=this.entityManager.getComponent(t,ae);i&&this.renderSprite(e,i)}))}reset(t){t.reset&&(t.currentFrame=0,t.currentTime=0,t.playing=void 0!==t.animation,t.reset=!1)}play(t){t.animation!==t._currentAnimation&&(t._currentAnimation=t.animation,t.currentFrame=0,t.currentTime=0,t.playing=!0),t.playing&&(t.currentTime>=1/this.animation.fps*(t.currentFrame+1)&&(t.currentFrame===this.animation.frames.length-1?this.animation.loop?(t.currentFrame=0,t.currentTime=0):t.playing=!1:t.currentFrame++),t.currentTime+=this.timeManager.renderDeltaTime*t.speed)}renderSprite(t,e){if(Array.isArray(this.animation.image))e.image=this.animation.image[t.currentFrame];else{const i=this.animation.frames[t.currentFrame],s=Math.floor(this.animation.image.naturalWidth/this.animation.slice.size.x);e.image=this.animation.image,e.slice={x:i%s*this.animation.slice.size.x+this.animation.slice.offset.x,y:Math.floor(i/s)*this.animation.slice.size.y+this.animation.slice.offset.y,width:this.animation.slice.size.x-this.animation.slice.padding.y,height:this.animation.slice.size.y-this.animation.slice.padding.y}}}};ne=o([i(H.AnimatorSystem),a(0,s(t.EntityManager)),a(1,s(t.TimeManager))],ne);let he=class{constructor(t,e){this.entityManager=t,this.renderManager=e}onUpdate(){this.entityManager.search(et).forEach((({entity:t,component:e})=>{const i=this.entityManager.getComponent(t,J);if(!i)throw new Error("Camera component needs a Transform");e._renderData.position.copy(i.localPosition),e._renderData.layers=e.layers,e._renderData.depth=e.depth,e._renderData.zoom=e.zoom,e.debug&&e._renderData.layers.push(tt),this.renderManager.addCameraData(e._renderData)}))}};he=o([i(H.CameraSystem),a(0,s(t.EntityManager)),a(1,s(t.RenderManager))],he);let le=class{constructor(t,e){this.webGLManager=t,this.gameConfig=e}onUpdate(){this.webGLManager.renderCanvasColor(this.gameConfig.canvasColor)}};le=o([i(H.ClearScreenSystem),a(0,s(t.WebGLManager)),a(1,s(t.GameConfig))],le);class ce{constructor(t){this.radius=0,this.offset=new n,this.layer="",this.physics=!0,this.ignoreCollisionsWithLayers=[],this.shapes=[],Object.assign(this,t)}}class de{constructor(t){this.layer="",this.physics=!0,this.width=0,this.height=0,this.offset=new n,this.rotation=0,this.ignoreCollisionsWithLayers=[],this.shapes=[],Object.assign(this,t)}}class ge{constructor(t){this.vertexModel=[],this.offset=new n,this.rotation=0,this.layer="",this.physics=!0,this.ignoreCollisionsWithLayers=[],this.shapes=[],Object.assign(this,t)}}class me{constructor(t){this.vertexModel=[],this.offset=new n,this.rotation=0,this.layer="",this.physics=!0,this.ignoreCollisionsWithLayers=[],this.shapes=[],Object.assign(this,t)}}class ue{constructor(t){this.composite=!0,this.layer="",this.ignoreCollisionsWithLayers=[],this.offset=new n,this.physics=!0,this.shapes=[],Object.assign(this,t)}}let pe=class{constructor(t,e,i){this.entityManager=t,this.renderManager=e,this.gameConfig=i}onUpdate(){var t;(null===(t=this.gameConfig.debug)||void 0===t?void 0:t.colliders)&&[ce,de,me,ge,ue].forEach((t=>this.entityManager.search(t).forEach((({component:t})=>t.shapes.forEach((t=>{const e={type:Mt.Geometric,position:new n,layer:tt,color:this.gameConfig.debug.collidersColor,shape:void 0,radius:void 0,rotation:void 0,vertexModel:void 0};t instanceof S?this.gameConfig.collisions.collisionMethod===w.SAT?(e.shape=t.vertices.length>2?vt.Polygon:vt.Line,e.vertexModel=t.vertices):this.gameConfig.collisions.collisionMethod===w.AABB&&(e.shape=vt.Polygon,e.vertexModel=[new n(t.boundingBox.x,t.boundingBox.y),new n(t.boundingBox.x,t.boundingBox.y1),new n(t.boundingBox.x1,t.boundingBox.y1),new n(t.boundingBox.x1,t.boundingBox.y)]):t instanceof b&&(e.shape=vt.Circumference,e.position.copy(t.position),e.radius=t.radius),this.renderManager.addRenderData(e)}))))))}};pe=o([i(H.DebugColliderRenderSystem),a(0,s(t.EntityManager)),a(1,s(t.RenderManager)),a(2,s(t.GameConfig))],pe);let ye=class{constructor(t,e){this.renderManager=t,this.canvas=e,this.viewport={x:0,x1:0,y:0,y1:0},this.object={x:0,x1:0,y:0,y1:0},this.culledRenderData=[]}onUpdate(){this.culledRenderData=[],this.renderManager.getCameraData().forEach((t=>{this.setViewport(t),this.renderManager.getRenderData().filter((e=>t.layers.includes(e.layer))).forEach((t=>{this.isInViewPort(t)&&(t.type===Mt.Tilemap&&this.applyCullingInTiles(t),this.culledRenderData.push(t))}))})),this.renderManager.setRenderData(this.culledRenderData)}isInViewPort(t){switch(t.type){case Mt.Video:case Mt.Shadow:case Mt.Sprite:this.setObjectForResizeable(t);break;case Mt.Mask:this.setObjectForMask(t);break;case Mt.Geometric:this.setObjectForGeometric(t);break;case Mt.Text:this.setObjectForText(t);break;case Mt.Tilemap:this.setObjectForTilemap(t)}return this.viewport.x1>=this.object.x&&this.viewport.x<=this.object.x1&&this.viewport.y1>=this.object.y&&this.viewport.y<=this.object.y1}setViewport({position:t,zoom:e}){this.viewport.x=t.x-this.canvas.width/e/2,this.viewport.x1=t.x+this.canvas.width/e/2,this.viewport.y=t.y-this.canvas.height/e/2,this.viewport.y1=t.y+this.canvas.height/e/2}setObjectForResizeable({position:t,width:e,height:i,rotation:s=0,tiled:r}){const o=Math.abs(Math.sin(s)),a=Math.abs(Math.cos(s));r&&(e*=r.x,i*=r.y);const n=o*i+a*e,h=o*e+a*i;this.object.x=t.x-n/2,this.object.x1=t.x+n/2,this.object.y=t.y-h/2,this.object.y1=t.y+h/2}setObjectForText({position:t,text:e,fontSize:i,lineHeight:s,letterSpacing:r,rotation:o}){const a=e.split("\n").reduce(((t,e)=>Math.max(t,e.length)),0)*(i+(null!=r?r:0))*2,n=e.split("\n").length*(null!=s?s:i);this.setObjectForResizeable({position:t,width:a,height:n,rotation:o})}setObjectForGeometric({position:t,vertexModel:e,shape:i,radius:s}){i===vt.Circumference?(this.object.x=t.x-s,this.object.y=t.y-s,this.object.x1=t.x+s,this.object.y1=t.y+s):(this.object.x=Number.MAX_SAFE_INTEGER,this.object.y=Number.MAX_SAFE_INTEGER,this.object.x1=Number.MIN_SAFE_INTEGER,this.object.y1=Number.MIN_SAFE_INTEGER,e.forEach((e=>{this.object.x=Math.min(e.x+t.x,this.object.x),this.object.y=Math.min(e.y+t.y,this.object.y),this.object.x1=Math.max(e.x+t.x,this.object.x1),this.object.y1=Math.max(e.y+t.y,this.object.y1)})))}setObjectForMask({position:t,vertices:e,shape:i,radius:s,rotation:r,width:o,height:a}){i===Ct.Circumference?(this.object.x=t.x-s,this.object.y=t.y-s,this.object.x1=t.x+s,this.object.y1=t.y+s):i===Ct.Polygon?(this.object.x=Number.MAX_SAFE_INTEGER,this.object.y=Number.MAX_SAFE_INTEGER,this.object.x1=Number.MIN_SAFE_INTEGER,this.object.y1=Number.MIN_SAFE_INTEGER,e.forEach((e=>{this.object.x=Math.min(e.x+t.x,this.object.x),this.object.y=Math.min(e.y+t.y,this.object.y),this.object.x1=Math.max(e.x+t.x,this.object.x1),this.object.y1=Math.max(e.y+t.y,this.object.y1)}))):this.setObjectForResizeable({position:t,width:o,height:a,rotation:r})}setObjectForTilemap(t){t.tilemap.height=Math.ceil(t.tiles.length/t.tilemap.width),this.setObjectForResizeable({position:t.position,width:t.tilemap.width*t.tilemap.tileWidth,height:t.tilemap.height*t.tilemap.tileHeight,rotation:t.rotation})}applyCullingInTiles(t){const{tiles:e,tilemap:{width:i,tileWidth:s,tileHeight:r}}=t;t.tiles=e.map(((t,e)=>this.viewport.x1>=this.object.x+e%i*s&&this.viewport.x<=this.object.x+e%i*s+s&&this.viewport.y1>=this.object.y1-((e/i|0)*r+r)&&this.viewport.y<=this.object.y1-(e/i|0)*r?t:0))}};ye=o([i(H.CullingSystem),a(0,s(t.RenderManager)),a(1,s(t.CanvasElement))],ye);class fe{constructor(t){this.width=0,this.height=0,this.radius=0,this.vertexModel=[],this.offset=new n,this.rotation=0,this.opacity=1,this.layer=Z,this._renderData={type:Mt.Mask,color:void 0,height:void 0,vertices:[],layer:void 0,opacity:void 0,position:new n,radius:void 0,rotation:void 0,shape:void 0,width:void 0},Object.assign(this,t)}}let xe=class{constructor(t,e){this.entityManager=t,this.renderManager=e,this.scaledOffset=new n}onUpdate(){this.entityManager.search(fe).forEach((({entity:t,component:e})=>{const i=this.entityManager.getComponent(t,J);if(!i)throw new Error("MaskRenderer component needs a Transform");this.scaledOffset.set(e.offset.x*i.localScale.x,e.offset.y*i.localScale.y),n.add(e._renderData.position,i.localPosition,this.scaledOffset),e._renderData.width=e.width*Math.abs(i.localScale.x),e._renderData.height=e.height*Math.abs(i.localScale.y),e._renderData.rotation=i.localRotation+e.rotation,e._renderData.color=e.color,e._renderData.layer=e.layer,e._renderData.opacity=e.opacity,e._renderData.radius=e.radius*Math.max(Math.abs(i.localScale.x),Math.abs(i.localScale.y)),e._renderData.shape=e.shape,e.shape===Ct.Polygon&&(e._renderData.vertices.length!==e.vertexModel.length&&(e._renderData.vertices=e.vertexModel.map((()=>new n))),e.vertexModel.forEach(((t,s)=>e._renderData.vertices[s].set(t.x*i.localScale.x,t.y*i.localScale.y))),0!==i.localRotation&&e._renderData.vertices.forEach((t=>t.set(t.x*Math.cos(i.localRotation)-t.y*Math.sin(i.localRotation),t.x*Math.sin(i.localRotation)+t.y*Math.cos(i.localRotation))))),0!==i.localRotation&&this.scaledOffset.magnitude>0&&this.translateRenderPosition(e._renderData,i),this.renderManager.addRenderData(e._renderData)}))}translateRenderPosition(t,e){const i=Math.atan2(this.scaledOffset.y,this.scaledOffset.x)+e.localRotation;t.position.set(e.localPosition.x+this.scaledOffset.magnitude*Math.cos(i),e.localPosition.y+this.scaledOffset.magnitude*Math.sin(i))}};xe=o([i(H.MaskRendererSystem),a(0,s(t.EntityManager)),a(1,s(t.RenderManager))],xe);let Me=class{constructor(t){this.renderManager=t}onUpdate(){this.renderManager.render(),this.renderManager.removeCameraData(),this.renderManager.removeRenderData()}};Me=o([i(H.RenderSystem),a(0,s(t.RenderManager))],Me);class ve{constructor(t){this.radius=0,this.smooth=!1,this.layer=Z,this.intensity=1,this._boundingBox=new h,Object.assign(this,t)}}class Ce{constructor(t){this.width=0,this.height=0,this.color="#000000",this.opacity=1,this.layer=Z,this._boundingBox=new h,this._renderData={type:Mt.Shadow,layer:void 0,color:void 0,opacity:void 0,width:void 0,height:void 0,position:void 0,rotation:void 0,lights:[]},Object.assign(this,t)}}let Se=class{constructor(t,e){this.entityManager=t,this.renderManager=e}onUpdate(){const t=this.entityManager.search(ve);t.forEach((({entity:t,component:e})=>this.updateLightRendererBoundingBox(t,e))),this.entityManager.search(Ce).forEach((({entity:e,component:i})=>{this.updatShadowRendererBoundingBox(e,i),i._renderData.layer=i.layer,i._renderData.color=i.color,i._renderData.opacity=i.opacity,i._renderData.width=i._boundingBox.width,i._renderData.height=i._boundingBox.height,i._renderData.position=i._boundingBox.center,i._renderData.rotation=0,i._renderData.lights=[],i._renderData.lights=t.filter((({component:t})=>t.layer===i.layer&&t._boundingBox.overlaps(i._boundingBox))).map((({component:{_boundingBox:t,smooth:e,intensity:i}})=>({position:t.center,radius:t.width/2,smooth:e,intensity:i}))),this.renderManager.addRenderData(i._renderData)}))}updateLightRendererBoundingBox(t,e){const i=this.entityManager.getComponent(t,J);if(!i)throw new Error("LightRenderer component needs a Transform");const s=e.radius*Math.abs(Math.max(i.localScale.x,i.localScale.y));e._boundingBox.set(i.localPosition.x-s,i.localPosition.y-s,2*s,2*s)}updatShadowRendererBoundingBox(t,e){const i=this.entityManager.getComponent(t,J);if(!i)throw new Error("ShadowRenderer component needs a Transform");const s=e.width*Math.abs(i.localScale.x),r=e.height*Math.abs(i.localScale.y);e._boundingBox.set(i.localPosition.x-s/2,i.localPosition.y-r/2,s,r)}};Se=o([i(H.ShadowLightRendererSystem),a(0,s(t.EntityManager)),a(1,s(t.RenderManager))],Se);let be=class{constructor(t,e){this.entityManager=t,this.renderManager=e,this.scaledOffset=new n}onUpdate(){this.entityManager.search(ae).forEach((({component:t,entity:e})=>{var i,s,r,o,a,h;const l=this.entityManager.getComponent(e,J);if(!l)throw new Error("SpriteRenderer component needs a Transform");t.image&&t.image.complete&&(this.scaledOffset.set(t.offset.x*l.localScale.x,t.offset.y*l.localScale.y),n.add(t._renderData.position,l.localPosition,this.scaledOffset),t._renderData.width=(null!==(r=null!==(i=t.width)&&void 0!==i?i:null===(s=t.slice)||void 0===s?void 0:s.width)&&void 0!==r?r:t.image.naturalWidth)*Math.abs(t.scale.x*l.localScale.x),t._renderData.height=(null!==(h=null!==(o=t.height)&&void 0!==o?o:null===(a=t.slice)||void 0===a?void 0:a.height)&&void 0!==h?h:t.image.naturalHeight)*Math.abs(t.scale.y*l.localScale.y),t._renderData.flipHorizontally=t.flipHorizontally!==l.scale.x<0,t._renderData.flipVertically=t.flipVertically!==l.scale.y<0,t._renderData.rotation=l.localRotation+t.rotation,0!==l.localRotation&&this.scaledOffset.magnitude>0&&this.translateRenderPosition(t._renderData,l),t._renderData.image=t.image,t._renderData.layer=t.layer,t._renderData.maskColor=t.maskColor,t._renderData.maskColorMix=t.maskColorMix,t._renderData.opacity=t.opacity,t._renderData.slice=t.slice,t._renderData.smooth=t.smooth,t._renderData.tintColor=t.tintColor,t._renderData.tiled=t.tiled,this.renderManager.addRenderData(t._renderData))}))}translateRenderPosition(t,e){const i=Math.atan2(this.scaledOffset.y,this.scaledOffset.x)+e.localRotation;t.position.set(e.localPosition.x+this.scaledOffset.magnitude*Math.cos(i),e.localPosition.y+this.scaledOffset.magnitude*Math.sin(i))}};be=o([i(H.SpriteRendererSystem),a(0,s(t.EntityManager)),a(1,s(t.RenderManager))],be);const Ae={charRanges:[32,126,161,255],fontSize:64,spacing:8};class we{constructor(t){this.color="#000000",this.flipHorizontally=!1,this.flipVertically=!1,this.font="Arial",this.fontSize=16,this.height=16,this.layer=Z,this.letterSpacing=0,this.lineHeight=void 0,this.offset=new n,this.opacity=1,this.orientation=_t.Center,this.rotation=0,this.shadow=void 0,this.smooth=!1,this.text="Hello World!",this.textureAtlas=Object.assign({},Ae),this.width=160,this._renderData={color:void 0,flipHorizontally:!1,flipVertically:!1,font:void 0,fontSize:void 0,layer:void 0,letterSpacing:void 0,lineHeight:void 0,opacity:void 0,orientation:void 0,position:new n,rotation:void 0,shadow:void 0,smooth:void 0,text:void 0,textureAtlas:Object.assign({},Ae),type:Mt.Text},Object.assign(this,t)}}let _e=class{constructor(t,e){this.entityManager=t,this.renderManager=e,this.scaledOffset=new n}onUpdate(){this.entityManager.search(we).forEach((({entity:t,component:e})=>{var i;const s=this.entityManager.getComponent(t,J);if(!s)throw new Error("TextRenderer component needs a Transform");if(0===e.text.length||e.font instanceof FontFace&&"loaded"!==e.font.status)return;this.scaledOffset.set(e.offset.x*s.localScale.x,e.offset.y*s.localScale.y),n.add(e._renderData.position,s.localPosition,this.scaledOffset),e._renderData.layer=e.layer,e._renderData.font=e.font,e._renderData.fontSize=e.fontSize,e._renderData.text=this.crop(e),e._renderData.orientation=e.orientation,e._renderData.color=e.color,e._renderData.lineHeight=null!==(i=e.lineHeight)&&void 0!==i?i:e.fontSize,e._renderData.letterSpacing=e.letterSpacing,e._renderData.smooth=e.smooth,e._renderData.rotation=s.localRotation+e.rotation,e._renderData.opacity=e.opacity;const{charRanges:r,fontSize:o,spacing:a}=e.textureAtlas;r&&(e._renderData.textureAtlas.charRanges=e.textureAtlas.charRanges),o&&(e._renderData.textureAtlas.fontSize=e.textureAtlas.fontSize),a&&(e._renderData.textureAtlas.spacing=e.textureAtlas.spacing),e._renderData.flipHorizontally=e.flipHorizontally,e._renderData.flipVertically=e.flipVertically,e._renderData.shadow=e.shadow,0!==s.localRotation&&this.scaledOffset.magnitude>0&&this.translateRenderPosition(e._renderData,s),this.renderManager.addRenderData(e._renderData)}))}translateRenderPosition(t,e){const i=Math.atan2(this.scaledOffset.y,this.scaledOffset.x)+e.localRotation;t.position.set(e.localPosition.x+this.scaledOffset.magnitude*Math.cos(i),e.localPosition.y+this.scaledOffset.magnitude*Math.sin(i))}crop({fontSize:t,height:e,width:i,text:s,letterSpacing:r,lineHeight:o}){if(t>e)return"";const a=[];let n=0;for(const h of s.split("\n")){const s=h.split(/(\s+)/).reduce(((e,s)=>{const o=e.length-1,a=e[o]+s;return a.length*(t+r)>i?e.push(s):e[o]=a,e}),[""]);for(const t of s){if(n+=o,n>e)return a.join("\n");a.push(t)}}return a.join("\n")}};_e=o([i(H.TextRendererSystem),a(0,s(t.EntityManager)),a(1,s(t.RenderManager))],_e);let Ee=class{constructor(t,e){this.entityManager=t,this.renderManager=e}onUpdate(){this.entityManager.search($t).forEach((({entity:t,component:e})=>{const i=this.entityManager.getComponent(t,J);if(!i)throw new Error("TilemapRenderer component needs a Transform");e._processed&&e.tileset.image&&e.tileset.image.complete&&e.chunks.forEach(((t,s)=>{e._renderData[s]||(e._renderData[s]=Re());const r=e._renderData[s];r.type=Mt.Tilemap,r.orientation=Rt.Center,r.position=new n,r.layer=e.layer,r.tilemap.width=t.width,r.tilemap.height=Math.ceil(e.data.length/t.width),r.tilemap.tileWidth=e.tileWidth*Math.abs(i.localScale.x),r.tilemap.tileHeight=e.tileHeight*Math.abs(i.localScale.y),r.tilemap.realWidth=r.tilemap.width*r.tilemap.tileWidth,r.tilemap.realHeight=r.tilemap.height*r.tilemap.tileHeight,r.tiles=t.data,r.tileset=e.tileset,r.opacity=e.opacity,r.rotation=i.localRotation,r.tintColor=e.tintColor,r.smooth=e.smooth,r.maskColor=e.maskColor,r.maskColorMix=e.maskColorMix,r.position.x=i.localPosition.x+(t.x-e.width/2+t.width/2)*r.tilemap.tileWidth,r.position.y=i.localPosition.y+(e.height/2-t.y-t.height/2)*r.tilemap.tileHeight,this.renderManager.addRenderData(r)}))}))}};Ee=o([i(H.TilemapRendererSystem),a(0,s(t.EntityManager)),a(1,s(t.RenderManager))],Ee);const Re=()=>({type:Mt.Tilemap,layer:void 0,position:new n,tilemap:{height:void 0,realHeight:void 0,realWidth:void 0,tileHeight:void 0,tileWidth:void 0,width:void 0},tiles:void 0,tileset:void 0});var Te;!function(t){t[t.Dynamic=0]="Dynamic",t[t.Kinematic=1]="Kinematic",t[t.Static=2]="Static"}(Te||(Te={}));class Be{constructor(t){this.type=Te.Dynamic,this.velocity=new n,this.gravity=0,this.acceleration=new n,Object.assign(this,t)}}let Pe=class{constructor(t,e,i){this.entityManager=t,this.timeManager=e,this.transformSystem=i,this.types=new Set([Te.Dynamic,Te.Kinematic]),this.displacement=new n,this.totalAcceleration=new n,this.scaledAcceleration=new n,this.scaledVelocity=new n}onUpdate(){this.entityManager.search(Be).filter((({component:{type:t}})=>this.types.has(t))).forEach((({component:{velocity:t,acceleration:e,gravity:i,type:s},entity:r})=>{const{position:o}=this.entityManager.getComponent(r,J);s===Te.Dynamic?(this.totalAcceleration.y=e.y-i,this.totalAcceleration.x=e.x):this.totalAcceleration.copy(e),n.add(t,t,n.scale(this.scaledAcceleration,this.totalAcceleration,this.timeManager.physicsDeltaTime)),n.add(o,o,n.add(this.displacement,n.scale(this.scaledVelocity,t,this.timeManager.physicsDeltaTime),n.scale(this.scaledAcceleration,this.totalAcceleration,.5*Math.pow(this.timeManager.physicsDeltaTime,2))))})),this.transformSystem.onUpdate()}};Pe=o([i(H.ApplyVelocitySystem),a(0,s(t.EntityManager)),a(1,s(t.TimeManager)),a(2,s(H.TransformSystem))],Pe);class De{constructor(){this.auxMin=new n,this.auxMax=new n,this.auxScaledOffset=new n}updatePositionAndVertices(t,e,i){this.translatePosition(t,e,i),t instanceof S?(this.auxAngle=t.rotation+i.localRotation,t.vertexModel.forEach(((e,s)=>t.vertices[s].set(e.x*i.localScale.x,e.y*i.localScale.y))),t.vertices.forEach((e=>e.set(e.x*Math.cos(this.auxAngle)-e.y*Math.sin(this.auxAngle)+t.position.x,e.x*Math.sin(this.auxAngle)+e.y*Math.cos(this.auxAngle)+t.position.y)))):t instanceof b&&(t.radius*=Math.max(Math.abs(i.localScale.x),Math.abs(i.localScale.y)))}translatePosition(t,e,{localPosition:i,localScale:s,localRotation:r}){if(this.auxScaledOffset.set(e.x*s.x,e.y*s.y),0!==r){const e=Math.atan2(this.auxScaledOffset.y,this.auxScaledOffset.x)+r;t.position.set(i.x+this.auxScaledOffset.magnitude*Math.cos(e),i.y+this.auxScaledOffset.magnitude*Math.sin(e))}else n.add(t.position,i,this.auxScaledOffset)}updateBoundingBox(t){t instanceof b?this.updateCircumferenceBoundingBox(t):t instanceof S&&this.updatePolygonBoundingBox(t)}updateCircumferenceBoundingBox(t){t.boundingBox.set(t.position.x-t.radius,t.position.y-t.radius,2*t.radius,2*t.radius)}updatePolygonBoundingBox(t){this.auxMin.x=t.vertices[0].x,this.auxMin.y=t.vertices[0].y,this.auxMax.x=t.vertices[0].x,this.auxMax.y=t.vertices[0].y,t.vertices.forEach((t=>{this.auxMin.x=Math.min(t.x,this.auxMin.x),this.auxMin.y=Math.min(t.y,this.auxMin.y),this.auxMax.x=Math.max(t.x,this.auxMax.x),this.auxMax.y=Math.max(t.y,this.auxMax.y)})),t.boundingBox.set(this.auxMin.x,this.auxMin.y,this.auxMax.x-this.auxMin.x,this.auxMax.y-this.auxMin.y)}updateProjectionAxes(t){var e;if(t.vertices.length>2)for(let i=0;i<t.vertices.length;i++)n.normal(t.projectionAxes[i],n.subtract(t.projectionAxes[i],null!==(e=t.vertices[i+1])&&void 0!==e?e:t.vertices[0],t.vertices[i]));else n.normal(t.projectionAxes[0],n.subtract(t.projectionAxes[0],t.vertices[1],t.vertices[0]))}}let Fe=class extends De{constructor(t){super(),this.entityManager=t}onUpdate(){this.entityManager.search(ce).forEach((({component:t,entity:e})=>{0===t.shapes.length&&(t.shapes[0]=new b(t.radius)),t.shapes[0].radius=t.radius,this.updatePositionAndVertices(t.shapes[0],t.offset,this.entityManager.getComponent(e,J)),this.updateBoundingBox(t.shapes[0]),this.updateProjectionAxes(t.shapes[0])}))}};Fe=o([i(H.UpdateBallColliderShapeSystem),a(0,s(t.EntityManager))],Fe);let Ue=class extends De{constructor(t){super(),this.entityManager=t}onUpdate(){this.entityManager.search(de).forEach((({component:t,entity:e})=>{0===t.shapes.length&&(t.shapes[0]=new S([new n,new n,new n,new n])),t.shapes[0].rotation=t.rotation,t.shapes[0].vertexModel[0].set(-t.width/2,-t.height/2),t.shapes[0].vertexModel[1].set(-t.width/2,t.height/2),t.shapes[0].vertexModel[2].set(t.width/2,t.height/2),t.shapes[0].vertexModel[3].set(t.width/2,-t.height/2),this.updatePositionAndVertices(t.shapes[0],t.offset,this.entityManager.getComponent(e,J)),this.updateBoundingBox(t.shapes[0]),this.updateProjectionAxes(t.shapes[0])}))}};Ue=o([i(H.UpdateBoxColliderShapeSystem),a(0,s(t.EntityManager))],Ue);let Ie=class extends De{constructor(t){super(),this.entityManager=t}onUpdate(){this.entityManager.search(ge).forEach((({component:t,entity:e})=>{for(let i=0;i<t.vertexModel.length-1;i++)t.shapes[i]||(t.shapes[i]=new S([new n,new n])),t.shapes[i].rotation=t.rotation,t.shapes[i].vertexModel=[t.vertexModel[i],t.vertexModel[i+1]],this.updatePositionAndVertices(t.shapes[i],t.offset,this.entityManager.getComponent(e,J)),this.updateBoundingBox(t.shapes[i]),this.updateProjectionAxes(t.shapes[i])}))}};Ie=o([i(H.UpdateEdgeColliderShapeSystem),a(0,s(t.EntityManager))],Ie);let Le=class extends De{constructor(t){super(),this.entityManager=t}onUpdate(){this.entityManager.search(me).forEach((({component:t,entity:e})=>{0===t.shapes.length&&(t.shapes[0]=new S([])),t.shapes[0].rotation=t.rotation,t.shapes[0].vertexModel=t.vertexModel,this.updatePositionAndVertices(t.shapes[0],t.offset,this.entityManager.getComponent(e,J)),this.updateBoundingBox(t.shapes[0]),this.updateProjectionAxes(t.shapes[0])}))}};Le=o([i(H.UpdatePolygonColliderShapeSystem),a(0,s(t.EntityManager))],Le);let je=class extends De{constructor(t){super(),this.entityManager=t}onUpdate(){this.entityManager.search(ue).forEach((({component:t,entity:e})=>{const i=this.entityManager.getComponent(e,$t);if(i&&0!==i.data.length){0===t.shapes.length&&(t.composite?this.useEdges(t,i):this.useBoxes(t,i));for(const i of t.shapes)this.updatePositionAndVertices(i,t.offset,this.entityManager.getComponent(e,J)),this.updateBoundingBox(i),this.updateProjectionAxes(i)}}))}useBoxes(t,e){t.shapes=[],e.data.forEach(((i,s)=>{if(!this.needsCollider(i,s,e))return;const r=new S(this.generateRectangleVertices(s,e));r.updateCollisions=!1,t.shapes.push(r)}))}generateRectangleVertices(t,{width:e,height:i,tileWidth:s,tileHeight:r}){const o=-e*s/2+t%e*s,a=i*r/2-Math.floor(t/e)*r;return[new n(o,a-r),new n(o,a),new n(o+s,a),new n(o+s,a-r)]}needsCollider(t,e,{data:i,width:s,height:r}){return 0!==t&&this.getNeighbors(e,s,r).some((t=>!t||!i[t]||0===i[t]))}useEdges(t,e){t.shapes=[];const i=[],s=[];let r,o;e.data.forEach(((t,r)=>{if(0===t)return;const o=r%e.width,a=Math.floor(r/e.width);i[a]||(i[a]=[]),i[a+1]||(i[a+1]=[]),s[a]||(s[a]=[]),s[a+1]||(s[a+1]=[]);const n=this.getNeighbors(r,e.width,e.height);this.hasTile(n[0],e)||(i[a][o]=!0),this.hasTile(n[2],e)||(i[a+1][o]=!0),this.hasTile(n[1],e)||(s[a][o]=!0),this.hasTile(n[3],e)||(s[a][o+1]=!0)}));for(let s=0;s<i.length;s++)if(i[s])for(let a=0;a<i[s].length;a++)!r||!o||s===o.y&&i[s][a]||(t.shapes.push(this.createEdge(r,o,e)),r=void 0,o=void 0),i[s][a]&&(r||(r=new n(a,s)),o=new n(a+1,s));r&&o&&t.shapes.push(this.createEdge(r,o,e)),r=void 0,o=void 0;for(let i=0;i<=e.width;i++)for(let a=0;a<s.length;a++)s[a]&&(!r||!o||i===o.x&&s[a][i]||(t.shapes.push(this.createEdge(r,o,e)),r=void 0,o=void 0),s[a][i]&&(r||(r=new n(i,a)),o=new n(i,a+1)));r&&o&&t.shapes.push(this.createEdge(r,o,e))}hasTile(t,{data:e}){return void 0!==t&&e[t]&&e[t]>0}createEdge(t,e,{width:i,height:s,tileWidth:r,tileHeight:o}){t.x=-i*r/2+t.x*r,t.y=s*o/2-t.y*o,e.x=-i*r/2+e.x*r,e.y=s*o/2-e.y*o;const a=new S([new n(t.x,t.y),new n(e.x,e.y)]);return a.updateCollisions=!1,a}getNeighbors(t,e,i){return[t-e>=0?t-e:void 0,t%e>0?t-1:void 0,t+e<=e*i?t+e:void 0,t%e<e-1?t+1:void 0]}};je=o([i(H.UpdateTilemapColliderShapeSystem),a(0,s(t.EntityManager))],je);let Oe=class{constructor(t,e,i,s,r){this.entityManager=t,this.broadPhaseResolver=e,this.collisionMatrix=i,this.collisionResolutionMethod=s,this.collisionRepository=r,this.colliders=[],this.collisions=new Set,this.shapes=[]}onUpdate(){this.collisionRepository.removeAll(),this.colliders=[],this.collisions.clear(),this.shapes=[],[ce,de,me,ge,ue].forEach((t=>this.entityManager.search(t).forEach((({component:t,entity:e})=>{this.colliders.push(t),t.shapes.forEach((i=>{var s;i.entity=e,i.collider=this.colliders.length-1,i.id=this.shapes.length,i.ignoreCollisionsWithLayers=null!==(s=t.ignoreCollisionsWithLayers)&&void 0!==s?s:[],i.layer=t.layer,this.shapes.push(i)}))})))),this.broadPhaseResolver.update(this.shapes),this.shapes.filter((t=>t.updateCollisions)).forEach((t=>this.narrowPhase(t,this.broadPhase(t))))}broadPhase({boundingBox:t,layer:e}){return this.collisionMatrix?this.broadPhaseResolver.retrieve(t).map((t=>this.shapes[t])).filter((t=>this.collisionMatrix.some((i=>i[0]===e&&i[1]===t.layer||i[1]===e&&i[0]===t.layer)))):this.broadPhaseResolver.retrieve(t).map((t=>this.shapes[t]))}narrowPhase(t,e){e.filter((e=>t.entity!==e.entity&&t.id!==e.id&&!t.ignoreCollisionsWithLayers.includes(e.layer)&&!e.ignoreCollisionsWithLayers.includes(t.layer)&&!this.isResolved(t,e))).forEach((e=>{const i=this.collisionResolutionMethod.findCollision(t,e);i&&(this.collisionRepository.persist({localCollider:this.colliders[t.collider],localEntity:t.entity,remoteCollider:this.colliders[e.collider],remoteEntity:e.entity,resolution:i}),this.collisionRepository.persist({localCollider:this.colliders[e.collider],localEntity:e.entity,remoteCollider:this.colliders[t.collider],remoteEntity:t.entity,resolution:{direction:n.scale(new n,i.direction,-1),penetration:i.penetration}}),this.collisions.add(`${t.id}-${e.id}`),this.collisions.add(`${e.id}-${t.id}`))}))}isResolved(t,e){return this.collisions.has(`${t.id}-${e.id}`)}};Oe=o([i(H.ResolveCollisionSystem),a(0,s(t.EntityManager)),a(1,s(t.CollisionBroadphaseResolver)),a(2,s(t.CollisionMatrix)),a(3,s(t.CollisionResolutionMethod)),a(4,s(t.CollisionRepository))],Oe);let ke=class{constructor(t,e,i){this.entityManager=t,this.collisionRepository=e,this.transformSystem=i,this.correction=new n,this.maxCorrection=new n}onUpdate(){const t=this.collisionRepository.findAll().filter((({localCollider:t,remoteCollider:e,remoteEntity:i,localEntity:s})=>t.physics&&e.physics&&this.entityManager.hasComponent(s,Be)&&this.entityManager.hasComponent(i,Be)));0!==t.length&&(this.entityManager.search(Be,{type:Te.Dynamic}).forEach((({component:e,entity:i})=>{if(this.maxCorrection.set(0,0),t.filter((({localEntity:t})=>i===t)).forEach((({remoteEntity:t,resolution:{direction:e,penetration:i}})=>{this.entityManager.getComponent(t,Be).type===Te.Dynamic&&(i/=2),n.scale(this.correction,e,-i),this.correction.magnitude>this.maxCorrection.magnitude&&this.maxCorrection.copy(this.correction)})),0===this.maxCorrection.x&&0===this.maxCorrection.y)return;const{position:s}=this.entityManager.getComponent(i,J);n.add(s,s,this.maxCorrection),e.gravity>0&&this.maxCorrection.y*e.velocity.y<0&&(e.velocity.y=0)})),this.transformSystem.onUpdate())}};ke=o([i(H.ApplyRepositionSystem),a(0,s(t.EntityManager)),a(1,s(t.CollisionRepository)),a(2,s(H.TransformSystem))],ke);let Ve=class extends De{constructor(t){super(),this.entityManager=t}onUpdate(){[ce,de,me,ge,ue].forEach((t=>this.entityManager.search(t,{updateCollisions:!0}).forEach((({component:t,entity:e})=>t.shapes.forEach((i=>{this.updatePositionAndVertices(i,t.offset,this.entityManager.getComponent(e,J)),this.updateBoundingBox(i)}))))))}};Ve=o([i(H.UpdateCollidersAfterRepositionSystem),a(0,s(t.EntityManager))],Ve);const Ge=24;let ze=class{constructor(t,e,i,s,r){this.entityManager=t,this.renderManager=e,this.inputManager=i,this.canvas=s,this.gameConfig=r,this.positionInViewport=new n,this.positionInCameraViewport=new n,this.positionInWorldspace=new n,this.renderDataPerCamera=new Map}onUpdate(){var t;if(!(null===(t=this.gameConfig.debug)||void 0===t?void 0:t.mousePosition)||!this.inputManager.mouse)return;const{positionInViewport:e}=this.inputManager.mouse;this.entityManager.search(et,{debug:!0}).forEach((({entity:t,component:i},s)=>{var r;const{zoom:o}=i,a=this.entityManager.getComponent(t,J).position,h=null!==(r=this.renderDataPerCamera.get(s))&&void 0!==r?r:We();n.floor(this.positionInWorldspace,n.add(this.positionInWorldspace,a,n.scale(this.positionInWorldspace,e,1/o))),n.floor(this.positionInCameraViewport,n.scale(this.positionInCameraViewport,e,1/o)),n.round(this.positionInViewport,e),h.color=this.gameConfig.debug.textColor,h.text=`mouse_position: canvas_viewport=${this.positionInViewport}, camera_viewport=${this.positionInCameraViewport}, world_space=${this.positionInWorldspace}`,h.fontSize=Ge/o,h.shadow.offset.x=2/o,h.shadow.offset.y=-2/o,this.updateRenderDataPosition(h,a,o),this.renderManager.addRenderData(h)}))}updateRenderDataPosition(t,e,i){switch(this.gameConfig.debug.textPosition){case"top-left":t.position.set(e.x-(this.canvas.width/2-Ge)/i,e.y+(this.canvas.height/2-Ge)/i);break;case"top-right":t.position.set(e.x+(this.canvas.width/2-t.text.length/2*Ge)/i,e.y+(this.canvas.height/2-Ge)/i);break;case"bottom-left":default:t.position.set(e.x-(this.canvas.width/2-Ge)/i,e.y-(this.canvas.height/2-Ge)/i);break;case"bottom-right":t.position.set(e.x+(this.canvas.width/2-t.text.length/2*Ge)/i,e.y-(this.canvas.height/2-Ge)/i)}}};ze=o([i(H.DebugMousePositionSystem),a(0,s(t.EntityManager)),a(1,s(t.RenderManager)),a(2,s(t.InputManager)),a(3,s(t.CanvasElement)),a(4,s(t.GameConfig))],ze);const We=(t=24)=>({type:Mt.Text,text:"",position:new n,layer:tt,color:"#00FF00",fontSize:t,font:"Arial",shadow:{color:"#000000",opacity:1,offset:new n(1,-1)},orientation:_t.RightCenter,flipHorizontally:!1,flipVertically:!1,letterSpacing:0,lineHeight:t,opacity:1,rotation:0,smooth:!1,textureAtlas:Object.assign({},Ae)}),He=new Map([[X.PreGameLogic,[{name:H.KeyboardSystem,type:ee},{name:H.MouseSystem,type:ie},{name:H.TouchScreenSystem,type:se},{name:H.GamepadSystem,type:te},{name:H.ButtonSystem,type:zt},{name:H.AudioPlayerSystem,type:Y},{name:H.TiledWrapperSystem,type:Kt},{name:H.TilemapPreProcessingSystem,type:Qt},{name:H.ChildrenSystem,type:Ht},{name:H.ParentSystem,type:Yt}]],[X.Transform,[{name:H.TransformSystem,type:Zt}]],[X.Physics,[{name:H.ApplyVelocitySystem,type:Pe},{name:H.UpdateBallColliderShapeSystem,type:Fe},{name:H.UpdateBoxColliderShapeSystem,type:Ue},{name:H.UpdateEdgeColliderShapeSystem,type:Ie},{name:H.UpdatePolygonColliderShapeSystem,type:Le},{name:H.UpdateTilemapColliderShapeSystem,type:je},{name:H.ResolveCollisionSystem,type:Oe},{name:H.ApplyRepositionSystem,type:ke},{name:H.UpdateCollidersAfterRepositionSystem,type:Ve}]],[X.Render,[{name:H.AnimatorSystem,type:ne},{name:H.CameraSystem,type:he},{name:H.TilemapRendererSystem,type:Ee},{name:H.SpriteRendererSystem,type:be},{name:H.MaskRendererSystem,type:xe},{name:H.ShadowLightRendererSystem,type:Se},{name:H.TextRendererSystem,type:_e},{name:H.VideoRendererSystem,type:jt},{name:H.DebugColliderRenderSystem,type:pe},{name:H.DebugMousePositionSystem,type:ze},{name:H.CullingSystem,type:ye},{name:H.ClearScreenSystem,type:le},{name:H.RenderSystem,type:Me}]]]);let Ne=class{constructor(t,e,i){this.timeManager=t,this.systemManager=e,this.sceneManager=i,this.running=!1,this.gameLoopAccumulator=0}start(){this.running||(this.running=!0,this.gameLoopAccumulator=0,this.enableSystems(),this.sceneManager.loadOpeningScene(),this.requestAnimationLoop(window.performance.now()),this.asyncPhysicsLoop())}enableSystems(){He.forEach((t=>{t.forEach((({type:t})=>this.systemManager.enableSystem(t)))}))}stop(){this.running&&(this.systemManager.disableAllSystems(),this.running=!1)}requestAnimationLoop(t){this.running&&(this.timeManager.updateForRender(.001*t),this.sceneManager.update(),this.sceneManager.loadingScene||(this.gameLoopAccumulator+=this.timeManager.browserDeltaTime,this.sceneManager.sceneLoadedThisFrame&&(this.gameLoopAccumulator=this.timeManager.fixedGameDeltaTime),this.gameLoopAccumulator>=this.timeManager.fixedGameDeltaTime&&(this.gameLogicIteration(.001*t),this.gameLoopAccumulator-=this.timeManager.fixedGameDeltaTime),this.renderIteration()),window.requestAnimationFrame((t=>this.requestAnimationLoop(t))))}gameLogicIteration(t){this.timeManager.updateForGame(t),this.systemManager.update(X.PreGameLogic),this.systemManager.update(X.GameLogic),this.timeManager.updateIntervals(),this.systemManager.update(X.Transform)}renderIteration(){this.systemManager.groupHasSystems(X.GamePreRender)&&(this.systemManager.update(X.GamePreRender),this.systemManager.update(X.Transform)),this.systemManager.update(X.Render)}asyncPhysicsLoop(){this.physicsIntervalId=window.setInterval((()=>{if(!this.running)return window.clearInterval(this.physicsIntervalId);this.timeManager.updateForPhysics(.001*window.performance.now()),document.hidden||this.physicsIteration()}),1e3/this.timeManager.fixedPhysicsFramerate)}physicsIteration(){this.timeManager.timeScale<=0||(this.systemManager.groupHasSystems(X.GamePhysics)&&(this.systemManager.update(X.GamePhysics),this.systemManager.update(X.Transform)),this.systemManager.update(X.Physics))}};Ne=o([i(t.LoopManager),a(0,s(t.TimeManager)),a(1,s(t.SystemManager)),a(2,s(t.SceneManager))],Ne);class Ye{constructor(t,e){this.container=t,this.systemManager=e,this.lastSystemTypeId=0}createSystemIfNotExists(t){if(this.systemManager.hasSystem(t))return;const e="__system_"+this.lastSystemTypeId++;var i;this.container.add(t,e),this.systemManager.addSystem(this.container.get(e),null!==(i=t.prototype.__system_group)&&void 0!==i?i:X.GameLogic)}}let Xe=class{constructor(t){this.webGLManager=t,this.renderData=[],this.cameraData=[]}addCameraData(t){this.cameraData.push(t)}addRenderData(t){this.renderData.push(t)}setRenderData(t){this.renderData=t}getCameraData(){return this.cameraData}getRenderData(){return this.renderData}removeCameraData(){this.cameraData=[]}removeRenderData(){this.renderData=[]}render(){this.cameraData.sort(((t,e)=>t.depth-e.depth)).forEach((t=>this.renderData.filter((e=>t.layers.includes(e.layer))).sort(((e,i)=>t.layers.indexOf(e.layer)-t.layers.indexOf(i.layer))).forEach((e=>this.webGLManager.render(e,t)))))}};Xe=o([i(t.RenderManager),a(0,s(t.WebGLManager))],Xe);const $e=t=>{var e,i,s,o,a,n,h,l,c,d,g;if(!(t.containerNode instanceof HTMLElement))throw new Error("GameConfig Error: Invalid containerNode");if("number"!=typeof t.width)throw new Error("GameConfig Error: Invalid width");if("number"!=typeof t.height)throw new Error("GameConfig Error: Invalid height");t.canvasColor=null!==(e=t.canvasColor)&&void 0!==e?e:"#000000",t.physicsFramerate=null!==(i=t.physicsFramerate)&&void 0!==i?i:180,t.headless=null!==(s=t.headless)&&void 0!==s&&s,t.debug=null!==(o=t.debug)&&void 0!==o?o:{colliders:!1,mousePosition:!1},t.debug.collidersColor=null!==(a=t.debug.collidersColor)&&void 0!==a?a:"#00FF00",t.debug.textColor=null!==(n=t.debug.textColor)&&void 0!==n?n:"#00FF00",t.debug.textPosition=null!==(h=t.debug.textPosition)&&void 0!==h?h:"bottom-left",t.collisions=null!==(l=t.collisions)&&void 0!==l?l:{},t.collisions.collisionBroadPhaseMethod=null!==(c=t.collisions.collisionBroadPhaseMethod)&&void 0!==c?c:r.SpartialGrid,t.collisions.collisionMatrix=null!==(d=t.collisions.collisionMatrix)&&void 0!==d?d:void 0,t.collisions.collisionMethod=null!==(g=t.collisions.collisionMethod)&&void 0!==g?g:w.SAT},Ke=({containerNode:t,width:e,height:i})=>{const s=document.createElement("canvas");return s.id="angryPixelGameCanvas",s.width=Math.floor(e),s.height=Math.floor(i),s.tabIndex=0,s.addEventListener("contextmenu",(t=>t.preventDefault())),t.appendChild(s),s.focus(),s},qe=e=>{e.add(D),e.add(F),e.set(t.CreateSystemService,new Ye(e,e.get(t.SystemManager))),e.add(V),e.add(z),e.add(O),e.add(kt),e.add(O),e.add(Ne),e.add(Ut),e.add(Xe)},Qe=e=>{e.get(t.GameConfig).headless&&Je(He),He.forEach(((i,s)=>i.forEach((({type:i,name:r})=>{e.add(i),e.get(t.SystemManager).addSystem(e.get(r),s)}))))},Je=t=>{t.delete(X.Render),t.set(X.PreGameLogic,t.get(X.PreGameLogic).filter((({name:t})=>![H.AudioPlayerSystem,H.ButtonSystem,H.GamepadSystem,H.KeyboardSystem,H.MouseSystem,H.TouchScreenSystem].includes(t))))},Ze=e=>{const{collisions:{collisionBroadPhaseMethod:i,collisionMatrix:s,collisionMethod:o}}=e.get(t.GameConfig);e.add(P),e.add(T),o===w.AABB?(e.add(E),e.add(R)):e.add(B),e.add(i===r.QuadTree?M:C),e.add(o===w.AABB?A:_),e.set(t.CollisionMatrix,s)},ti=e=>{const i=e.get(t.GameConfig);i.dependencies&&i.dependencies.forEach((([t,i])=>{e.set(t,i)}))};class ei{constructor(i){this.container=(i=>{$e(i);const s=new e;return s.set(t.GameConfig,i),s.set(t.CanvasElement,Ke(i)),Ze(s),qe(s),Qe(s),ti(s),s})(i)}get running(){return this.container.get(t.LoopManager).running}addScene(e,i,s=!1){this.container.get(t.SceneManager).addScene(e,i,s)}addDependencyType(t,e){this.container.add(t,e)}addDependencyInstance(t,e){this.container.set(e,t)}start(){this.container.get(t.LoopManager).start()}stop(){this.container.get(t.LoopManager).stop()}}class ii{onUpdate(){}onCreate(){}onEnabled(){}onDisabled(){}onDestroy(){}}function si(t,e,i){"number"==typeof i?t(e.prototype,void 0,i):void 0!==i?t(e.prototype,i):t(e)}o([s(t.EntityManager)],ii.prototype,"entityManager",void 0),o([s(t.AssetManager)],ii.prototype,"assetManager",void 0),o([s(t.SceneManager)],ii.prototype,"sceneManager",void 0),o([s(t.TimeManager)],ii.prototype,"timeManager",void 0),o([s(t.InputManager)],ii.prototype,"inputManager",void 0),o([s(t.CollisionRepository)],ii.prototype,"collisionRepository",void 0),o([s(t.GameConfig)],ii.prototype,"gameConfig",void 0);const ri=({audioSource:t,volume:e=1,loop:i=!1})=>{t.volume=e,t.loop=i,t.currentTime=0,t.play().catch((t=>console.warn("playSfx error:",t)))},oi=t=>{t.pause(),t.currentTime=0},ai={AssetManager:t.AssetManager,CanvasElement:t.CanvasElement,CollisionRepository:t.CollisionRepository,EntityManager:t.EntityManager,GameConfig:t.GameConfig,InputManager:t.InputManager,SceneManager:t.SceneManager,SystemManager:t.SystemManager,TimeManager:t.TimeManager};export{oe as Animation,re as Animator,z as AssetManager,W as AudioPlayer,ce as BallCollider,de as BoxCollider,r as BroadPhaseMethods,Vt as Button,Gt as ButtonShape,et as Camera,Wt as Children,b as Circumference,w as CollisionMethods,P as CollisionRepository,ge as EdgeCollider,D as EntityManager,ei as Game,ii as GameSystem,U as GamepadController,O as InputManager,I as Keyboard,ve as LightRenderer,fe as MaskRenderer,Ct as MaskShape,L as Mouse,Nt as Parent,S as Polygon,me as PolygonCollider,h as Rectangle,Be as RigidBody,Te as RigidBodyType,Ot as Scene,kt as SceneManager,Ce as ShadowRenderer,ae as SpriteRenderer,ai as Symbols,F as SystemManager,_t as TextOrientation,we as TextRenderer,Xt as TiledWrapper,ue as TilemapCollider,Rt as TilemapOrientation,$t as TilemapRenderer,V as TimeManager,j as TouchScreen,J as Transform,n as Vector2,It as VideoRenderer,u as between,l as clamp,tt as debugRenderLayer,si as decorate,Z as defaultRenderLayer,Ae as defaultTextureAtlasOptions,y as degreesToRadians,g as fixedRound,$ as gameLogicSystem,K as gamePhysicsSystem,q as gamePreRenderSystem,s as inject,i as injectable,ri as playSfx,p as radiansToDegrees,d as randomFloat,c as randomInt,m as range,f as rgbToHex,oi as stopSfx};
|
|
1
|
+
const t={AssetManager:Symbol.for("AssetManager"),CanvasElement:Symbol.for("CanvasElement"),CollisionRepository:Symbol.for("CollisionRepository"),CollisionBroadphaseResolver:Symbol.for("CollisionBroadphaseResolver"),CollisionResolutionMethod:Symbol.for("CollisionResolutionMethod"),CollisionAABBResolver:Symbol.for("CollisionAABBResolver"),CollisionCircumferenceAABBResolver:Symbol.for("CollisionCircumferenceAABBResolver"),CollisionCircumferenceResolver:Symbol.for("CollisionCircumferenceResolver"),CollisionSatResolver:Symbol.for("CollisionSatResolver"),CollisionMatrix:Symbol.for("CollisionMatrix"),CreateSystemService:Symbol.for("CreateSystemService"),EntityManager:Symbol.for("EntityManager"),GameConfig:Symbol.for("GameConfig"),InputManager:Symbol.for("InputManager"),LoopManager:Symbol.for("LoopManager"),RenderManager:Symbol.for("RenderManager"),SceneManager:Symbol.for("SceneManager"),SystemManager:Symbol.for("SystemManager"),TimeManager:Symbol.for("TimeManager"),WebGLManager:Symbol.for("WebGLManager")};class e{constructor(){this.instances=new Map,this.types=new Map}add(t,e){if(!e&&!t.prototype.__ioc_injectable)throw new Error(`Type ${t.name} is not injectable`);return this.types.set(null!=e?e:t.prototype.__ioc_injectable,t),this}set(t,e){return this.instances.set(t,e),this}get(t){var e,i;if(!this.instances.has(t)){const s=this.types.get(t);if(!s)throw new Error(`${t.toString()} is not a valid type`);const r=new s(...(null!==(e=s.prototype.__ioc_inject_constructor)&&void 0!==e?e:[]).map((t=>this.get(t))));(null!==(i=s.prototype.__ioc_inject_prop)&&void 0!==i?i:[]).forEach((([t,e])=>r[t]=this.get(e))),this.instances.set(t,r)}return this.instances.get(t)}has(t){return this.types.has(t)||this.instances.has(t)}}function i(t){return function(e){e.prototype.__ioc_injectable&&e.prototype.__ioc_injectable===t||(e.prototype.__ioc_injectable=t)}}function s(t){return function(e,i,s){void 0!==s?(e.prototype.__ioc_inject_constructor||(e.prototype.__ioc_inject_constructor=[]),e.prototype.__ioc_inject_constructor[s]=t):void 0!==i&&(e.constructor.prototype.__ioc_inject_prop||(e.constructor.prototype.__ioc_inject_prop=[]),e.constructor.prototype.__ioc_inject_prop.push([i,t]))}}var r;function o(t,e,i,s){var r,o=arguments.length,a=o<3?e:null===s?s=Object.getOwnPropertyDescriptor(e,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(t,e,i,s);else for(var n=t.length-1;n>=0;n--)(r=t[n])&&(a=(o<3?r(a):o>3?r(e,i,a):r(e,i))||a);return o>3&&a&&Object.defineProperty(e,i,a),a}function a(t,e){return function(i,s){e(i,s,t)}}!function(t){t[t.QuadTree=0]="QuadTree",t[t.SpartialGrid=1]="SpartialGrid"}(r||(r={})),"function"==typeof SuppressedError&&SuppressedError;class n{constructor(t=0,e=0){this._x=t,this._y=e}get x(){return this._x}set x(t){this._x=t}get y(){return this._y}set y(t){this._y=t}get magnitude(){return Math.sqrt(Math.pow(this._x,2)+Math.pow(this._y,2))}get direction(){return this._direction||(this._direction=new n),n.unit(this._direction,this)}set(t,e){this._x=t,this._y=e}copy(t){this.set(t.x,t.y)}equals(t){return this._x===t.x&&this._y===t.y}clone(){return new n(this._x,this._y)}distance(t){return Math.sqrt(Math.pow(this._x-t.x,2)+Math.pow(this._y-t.y,2))}static add(t,e,i){return t.set(e.x+i.x,e.y+i.y),t}static subtract(t,e,i){return t.set(e.x-i.x,e.y-i.y),t}static unit(t,e){return 0===e.magnitude?t.set(0,0):t.set(e.x/e.magnitude,e.y/e.magnitude),t}static normal(t,e){return t.set(-e.y,e.x),this.unit(t,t)}static scale(t,e,i){return t.set(e.x*i,e.y*i),t}static dot(t,e){return t.x*e.x+t.y*e.y}static cross(t,e){return t.x*e.y-t.y*e.x}static round(t,e){return t.set(Math.round(e.x),Math.round(e.y)),t}static floor(t,e){return t.set(Math.floor(e.x),Math.floor(e.y)),t}static ceil(t,e){return t.set(Math.ceil(e.x),Math.ceil(e.y)),t}toString(){return`(${this._x}, ${this._y})`}}class h{constructor(t=0,e=0,i=0,s=0){this.width=0,this.height=0,this._position=new n,this._center=new n,this.set(t,e,i,s)}get x(){return this._position.x}set x(t){this._position.set(t,this._position.y)}get y(){return this._position.y}set y(t){this._position.set(this._position.x,t)}get x1(){return this._position.x+this.width}get y1(){return this._position.y+this.height}get position(){return this._position}set position(t){this._position.set(t.x,t.y)}get center(){return this._center.set(this.x+this.width/2,this.y+this.height/2),this._center}set(t,e,i,s){this._position.set(t,e),this.width=i,this.height=s}equals(t){return this.position.equals(t.position)&&this.width===t.width&&this.height===t.height}copy(t){this.set(t.x,t.y,t.width,t.height)}intersects(t){return!(this.x1<t.x||this.x>t.x1||this.y1<t.y||this.y>t.y1)}contains(t){return t instanceof h?t.x1<=this.x1&&t.x>=this.x&&t.y1<=this.y1&&t.y>=this.y:t instanceof n&&!(t.x<this.x||t.y<this.y||t.x>=this.x1||t.y>=this.y1)}toString(){return`(${this.position.x}, ${this.position.y}, ${this.width}, ${this.height})`}}const l=(t,e,i)=>Math.min(i,Math.max(e,t)),c=(t,e)=>Math.round(Math.random()*(e-t))+t,d=(t,e,i=2)=>g(Math.random()*(e-t)+t,i),g=(t,e)=>Math.round(t*Math.pow(10,e))/Math.pow(10,e),m=(t,e,i=1)=>{const s=[];for(let r=t;r<=e;r+=i)s.push(r);return s},u=(t,e,i)=>t>=e&&t<=i,p=t=>t*(180/Math.PI),y=t=>t*(Math.PI/180),f=({r:t,g:e,b:i},s="#")=>{const r=t=>t.toString(16).padStart(2,"0");return`${s}${r(t)}${r(e)}${r(i)}`};var x;let M=x=class{constructor(t=new h,e=0){this.rects=new Map,this.children=null,this.minArea=new n,this.maxArea=new n,this.bounds=t,this.depth=e}update(t){this.clear(),0!==t.length&&(this.resize(t),t.forEach((({id:t,boundingBox:e})=>this.insert(t,e))))}clear(){this.rects.clear(),this.children&&(this.children.forEach((t=>t.clear())),this.children=null)}resize(t){this.minArea.set(1/0,1/0),this.maxArea.set(-1/0,-1/0),t.forEach((({boundingBox:t})=>{this.minArea.set(Math.min(t.x,this.minArea.x),Math.min(t.y,this.minArea.y)),this.maxArea.set(Math.max(t.x1,this.maxArea.x),Math.max(t.y1,this.maxArea.y))})),this.bounds.set(this.minArea.x,this.minArea.y,this.maxArea.x-this.minArea.x,this.maxArea.y-this.minArea.y)}insert(t,e){!this.children&&this.rects.size>=16&&this.depth<8&&(this.subdivide(),this.rects.forEach(((t,e)=>this.children.forEach((i=>{i.bounds.intersects(t)&&i.insert(e,t)})))),this.rects.clear()),this.children?this.children.forEach((i=>{i.bounds.intersects(e)&&i.insert(t,e)})):this.rects.set(t,e)}subdivide(){const t=this.bounds.x,e=this.bounds.y,i=this.bounds.width/2,s=this.bounds.height/2;this.children=[new x(new h(t,e,i,s),this.depth+1),new x(new h(t+i,e,i,s),this.depth+1),new x(new h(t,e+s,i,s),this.depth+1),new x(new h(t+i,e+s,i,s),this.depth+1)]}retrieve(t){const e=[];return this.retrieveFromNode(t,e),e}retrieveFromNode(t,e){this.children?this.children.forEach((i=>{i.bounds.intersects(t)&&i.retrieveFromNode(t,e)})):this.rects.forEach(((i,s)=>{i.intersects(t)&&-1===e.indexOf(s)&&e.push(s)}))}};M=x=o([i(t.CollisionBroadphaseResolver)],M);const v=(t,e,i,s)=>Math.min((t-e)/i|0,s-1);let b=class{constructor(){this.area=new h,this.grid=[],this.rects=new Map,this.subdivisions=0,this.minArea=new n,this.maxArea=new n,this.coordinates={x0:0,x1:0,y0:0,y1:0}}update(t){this.clear(),0!==t.length&&(this.resize(t),t.forEach((({id:t,boundingBox:e})=>this.insert(t,e))))}clear(){this.grid=[],this.rects.clear()}resize(t){this.minArea.set(1/0,1/0),this.maxArea.set(-1/0,-1/0),t.forEach((({boundingBox:t})=>{this.minArea.set(Math.min(t.x,this.minArea.x),Math.min(t.y,this.minArea.y)),this.maxArea.set(Math.max(t.x1,this.maxArea.x),Math.max(t.y1,this.maxArea.y))})),this.area.set(this.minArea.x,this.minArea.y,this.maxArea.x-this.minArea.x,this.maxArea.y-this.minArea.y),this.updateSubdivisions(t.length)}updateSubdivisions(t){this.subdivisions=1+(t/16|0),this.cellWidth=Math.ceil(this.area.width/this.subdivisions),this.cellHeight=Math.ceil(this.area.height/this.subdivisions),this.grid=[];for(let t=0;t<this.subdivisions;t++){this.grid[t]=[];for(let e=0;e<this.subdivisions;e++)this.grid[t][e]=[]}}insert(t,e){this.updateCoordinates(e);for(let e=this.coordinates.x0;e<=this.coordinates.x1;e++)for(let i=this.coordinates.y0;i<=this.coordinates.y1;i++)this.grid[e][i].push(t);this.rects.set(t,e)}retrieve(t){const e=new Set;this.updateCoordinates(t);for(let i=this.coordinates.x0;i<=this.coordinates.x1;i++)for(let s=this.coordinates.y0;s<=this.coordinates.y1;s++)this.grid[i][s].forEach((i=>{this.rects.get(i).intersects(t)&&e.add(i)}));return Array.from(e)}updateCoordinates(t){this.coordinates.x0=v(t.x,this.area.x,this.cellWidth,this.subdivisions),this.coordinates.x1=v(t.x1,this.area.x,this.cellWidth,this.subdivisions),this.coordinates.y0=v(t.y,this.area.y,this.cellHeight,this.subdivisions),this.coordinates.y1=v(t.y1,this.area.y,this.cellHeight,this.subdivisions)}};b=o([i(t.CollisionBroadphaseResolver)],b);class C{get vertexModel(){return this._vertexModel}set vertexModel(t){if(this._vertexModel=t,2===t.length)return this.vertices=[new n,new n],void(this.projectionAxes=[new n]);this.vertices=[],this.projectionAxes=[],this._vertexModel.forEach((()=>{this.vertices.push(new n),this.projectionAxes.push(new n)}))}constructor(t,e=0){this.rotation=e,this.boundingBox=new h,this.collider=void 0,this.entity=void 0,this.id=void 0,this.ignoreCollisionsWithLayers=void 0,this.layer=void 0,this.position=new n,this.projectionAxes=[],this.radius=0,this.vertices=[],this.updateCollisions=!0,this._vertexModel=[],this.vertexModel=t}}class S{constructor(t){this.radius=t,this.boundingBox=new h,this.collider=void 0,this.entity=void 0,this.id=void 0,this.ignoreCollisionsWithLayers=void 0,this.layer=void 0,this.position=new n,this.projectionAxes=[new n],this.rotation=0,this.vertexModel=[],this.vertices=[new n,new n],this.updateCollisions=!0}}let A=class{constructor(t,e,i){this.AABBResolver=t,this.circumferenceAABBResolver=e,this.circumferenceResolver=i}findCollision(t,e){return t instanceof C&&e instanceof C?this.AABBResolver.resolve(t,e):t instanceof S&&e instanceof C?this.circumferenceAABBResolver.resolve(t,e):t instanceof C&&e instanceof S?this.circumferenceAABBResolver.resolve(e,t,!0):t instanceof S&&e instanceof S?this.circumferenceResolver.resolve(t,e):void 0}};var w;A=o([i(t.CollisionResolutionMethod),a(0,s(t.CollisionAABBResolver)),a(1,s(t.CollisionCircumferenceAABBResolver)),a(2,s(t.CollisionCircumferenceResolver))],A),function(t){t[t.AABB=0]="AABB",t[t.SAT=1]="SAT"}(w||(w={}));let E=class{constructor(t,e){this.circumferenceResolver=t,this.satResolver=e}findCollision(t,e){return t instanceof S&&e instanceof S?this.circumferenceResolver.resolve(t,e):this.satResolver.resolve(t,e)}};E=o([i(t.CollisionResolutionMethod),a(0,s(t.CollisionCircumferenceResolver)),a(1,s(t.CollisionSatResolver))],E);let _=class{constructor(){this.direction=new n,this.resolutionDirection=new n}resolve({boundingBox:t},{boundingBox:e}){if(this.overlapX=Math.min(t.x1,e.x1)-Math.max(t.x,e.x),this.overlapY=Math.min(t.y1,e.y1)-Math.max(t.y,e.y),!(this.overlapX<0||this.overlapY<0))return this.checkOverlapForLines(t,e),this.direction.set(Math.sign(e.center.x-t.center.x),Math.sign(e.center.y-t.center.y)),this.preventContainment(t,e),this.overlapY<this.overlapX?(this.minOverlap=this.overlapY,this.resolutionDirection.set(0,this.direction.y)):(this.minOverlap=this.overlapX,this.resolutionDirection.set(this.direction.x,this.overlapY===this.overlapX?this.direction.y:0)),{direction:n.unit(new n,this.resolutionDirection),penetration:this.minOverlap}}checkOverlapForLines(t,e){0!==t.width&&0!==e.width||0!==this.overlapX||(this.overlapX=Math.min(Math.abs(t.x-e.x),Math.abs(t.x1-e.x1))),0!==t.height&&0!==e.height||0!==this.overlapY||(this.overlapY=Math.min(Math.abs(t.y-e.y),Math.abs(t.y1-e.y1)))}preventContainment(t,e){if(this.overlapY>0&&(t.y1>e.y1&&t.y<e.y||t.y1<e.y1&&t.y>e.y)){const i=Math.abs(t.y-e.y),s=Math.abs(t.y1-e.y1);this.overlapY+=i<s?i:s}if(this.overlapX>0&&(t.x1>e.x1&&t.x<e.x||t.x1<e.x1&&t.x>e.x)){const i=Math.abs(t.x-e.x),s=Math.abs(t.x1-e.x1);this.overlapX+=i<s?i:s}}};_=o([i(t.CollisionAABBResolver)],_);let R=class{constructor(){this.closestPoint=new n,this.distance=new n,this.direction=new n}resolve(t,e,i=!1){if(this.closestPoint.set(l(t.position.x,e.boundingBox.x,e.boundingBox.x1),l(t.position.y,e.boundingBox.y,e.boundingBox.y1)),n.subtract(this.distance,this.closestPoint,t.position),!(this.distance.magnitude>t.radius))return n.unit(this.direction,this.distance),{direction:i?n.scale(new n,this.direction,-1):this.direction.clone(),penetration:t.radius-this.distance.magnitude}}};R=o([i(t.CollisionCircumferenceAABBResolver)],R);let T=class{constructor(){this.distance=new n,this.direction=new n}resolve(t,e){if(n.subtract(this.distance,e.position,t.position),!(this.distance.magnitude>t.radius+e.radius))return n.unit(this.direction,this.distance),{direction:this.direction.clone(),penetration:t.radius+e.radius-this.distance.magnitude}}};T=o([i(t.CollisionCircumferenceResolver)],T);let B=class{constructor(){this.projA={min:0,max:0},this.projB={min:0,max:0},this.smallestAxis=new n,this.distance=new n(1/0,1/0),this.cache=new n}resolve(t,e){this.minOverlap=1/0,t instanceof S?this.setCircumferenceAxis(t,e):e instanceof S&&this.setCircumferenceAxis(e,t),this.axes=[...t.projectionAxes],e.projectionAxes.forEach((t=>this.axes.some((e=>e.equals(t)))?void 0:this.axes.push(t)));for(let i=0;i<this.axes.length;i++){if(t instanceof S?this.setCircumferenceVertices(t,this.axes[i]):e instanceof S&&this.setCircumferenceVertices(e,this.axes[i]),this.projectShapeOntoAxis(this.projA,t,this.axes[i]),this.projectShapeOntoAxis(this.projB,e,this.axes[i]),this.currentOverlap=Math.min(this.projA.max,this.projB.max)-Math.max(this.projA.min,this.projB.min),this.currentOverlap<0)return;if(this.invertAxis=!0,this.projA.max>this.projB.max&&this.projA.min<this.projB.min||this.projA.max<this.projB.max&&this.projA.min>this.projB.min){const t=Math.abs(this.projA.min-this.projB.min),e=Math.abs(this.projA.max-this.projB.max);t<e?this.currentOverlap+=t:(this.currentOverlap+=e,n.scale(this.axes[i],this.axes[i],-1),this.invertAxis=!1)}this.currentOverlap<this.minOverlap&&(this.minOverlap=this.currentOverlap,this.smallestAxis.copy(this.axes[i]),this.invertAxis&&this.projA.max<this.projB.max&&n.scale(this.smallestAxis,this.axes[i],-1))}return{direction:n.scale(new n,this.smallestAxis,-1),penetration:this.minOverlap}}projectShapeOntoAxis(t,e,i){return t.min=1/0,t.max=-1/0,e.vertices.forEach((e=>{t.min=Math.min(n.dot(i,e),t.min),t.max=Math.max(n.dot(i,e),t.max)})),t}setCircumferenceAxis(t,e){this.distance.set(1/0,1/0),e.vertices.forEach((e=>{n.subtract(this.cache,e,t.position),this.cache.magnitude<this.distance.magnitude&&this.distance.copy(this.cache)})),n.unit(t.projectionAxes[0],this.distance)}setCircumferenceVertices(t,e){n.add(t.vertices[0],t.position,n.scale(this.cache,n.unit(this.cache,e),-t.radius)),n.add(t.vertices[1],t.position,n.scale(this.cache,n.unit(this.cache,e),t.radius))}};B=o([i(t.CollisionSatResolver)],B);let P=class{constructor(){this.collisions=[]}findCollisionsForCollider(t){return this.collisions.filter((e=>e.localCollider===t))}findCollisionsForColliderAndLayer(t,e){return this.collisions.filter((i=>i.localCollider===t&&i.remoteCollider.layer===e))}findAll(){return this.collisions}persist(t){this.collisions.push(t)}removeAll(){this.collisions=[]}};P=o([i(t.CollisionRepository)],P);let D=class{constructor(){this.lastEntityId=0,this.lastComponentTypeId=0,this.entities=new Set,this.components=new Map,this.disabledEntities=new Set,this.manuallyDisabledEntities=new Set,this.disabledComponents=new Map,this.parentEntities=new Map,this.childEntities=new Map}createEntity(t,e){return t instanceof Array?this.createEntityFromComponents(t,e):t instanceof Object?this.createEntityFromArchetype(t):++this.lastEntityId}createEntityFromComponents(t,e){const i=this.lastEntityId++;return this.entities.add(i),t.forEach((t=>this.addComponent(i,t))),e&&this.setParent(i,e),i}createEntityFromArchetype({components:t,children:e,enabled:i},s){const r=this.lastEntityId++;return this.entities.add(r),t.forEach((t=>{let e;if(t.type&&"function"==typeof t.type){const{type:i,data:s,enabled:o}=t;e=this.addComponent(r,i),s&&Object.assign(e,s),!1===o&&this.disableComponent(e)}else e=new t.constructor,Object.assign(e,t),this.addComponent(r,e)})),s&&this.setParent(r,s),e&&e.forEach((t=>this.createEntityFromArchetype(t,r))),!1===i&&this.disableEntity(r),r}createEntities(t){const e=[];return t.forEach((t=>e.push(this.createEntity(t)))),e}removeEntity(t){var e;this.getChildren(t).forEach((t=>this.removeEntity(t))),this.components.forEach((e=>{e.has(t)&&e.delete(t)})),this.disabledComponents.delete(t),this.disabledEntities.delete(t),this.manuallyDisabledEntities.delete(t);const i=this.getParent(t);i&&(null===(e=this.childEntities.get(i))||void 0===e||e.delete(t)),this.parentEntities.delete(t),this.childEntities.delete(t),this.entities.delete(t)}removeAllEntities(){this.components.clear(),this.disabledComponents.clear(),this.disabledEntities.clear(),this.manuallyDisabledEntities.clear(),this.lastEntityId=0,this.entities.clear(),this.parentEntities.clear(),this.childEntities.clear()}isEntity(t){return this.entities.has(t)}isEntityEnabled(t){return this.isEntity(t)&&!this.disabledEntities.has(t)}enableEntity(t){this.disabledEntities.has(t)&&(this.disabledEntities.delete(t),this.getChildren(t).forEach((t=>{this.manuallyDisabledEntities.has(t)||this.enableEntity(t)})))}disableEntity(t){this.disabledEntities.has(t)||(this.disabledEntities.add(t),this.getChildren(t).forEach((t=>{this.disabledEntities.has(t)?this.manuallyDisabledEntities.add(t):this.disableEntity(t)})))}disableEntitiesByComponent(t){var e,i;for(const s of null!==(i=null===(e=this.components.get(this.getComponentTypeId(t)))||void 0===e?void 0:e.keys())&&void 0!==i?i:[])this.disableEntity(s)}enableEntitiesByComponent(t){var e,i;for(const s of null!==(i=null===(e=this.components.get(this.getComponentTypeId(t)))||void 0===e?void 0:e.keys())&&void 0!==i?i:[])this.enableEntity(s)}setParent(t,e){if(!this.isEntity(t)||!this.isEntity(e))throw new Error("Both entities must exist to set a parent-child relationship.");this.parentEntities.set(t,e),this.childEntities.has(e)||this.childEntities.set(e,new Set),this.childEntities.get(e).add(t)}getParent(t){return this.parentEntities.get(t)}getChildren(t){return Array.from(this.childEntities.get(t)||[])}removeParent(t){const e=this.parentEntities.get(t);e&&(this.parentEntities.delete(t),this.childEntities.get(e).delete(t))}removeChild(t,e){this.parentEntities.get(e)===t&&(this.parentEntities.delete(e),this.childEntities.get(t).delete(e))}addComponent(t,e){const i=this.getComponentTypeId(e),s="object"==typeof e?e:new e;if(this.components.has(i)||this.components.set(i,new Map),this.components.get(i).has(t))throw new Error(`Entity ${t} already has a component of type ${i}`);return this.components.get(i).set(t,s),s}hasComponent(t,e){return void 0!==this.getComponent(t,e)}getComponent(t,e){var i;return null===(i=this.components.get(this.getComponentTypeId(e)))||void 0===i?void 0:i.get(t)}getComponents(t){const e=[];return this.components.forEach((i=>i.forEach(((i,s)=>{t===s&&e.push(i)})))),e}getEntityForComponent(t){const e=this.getComponentTypeId(t);if(this.components.has(e))for(const[i,s]of this.components.get(e))if(s===t)return i}removeComponent(t,e){var i;const s=this.getComponentTypeId("object"==typeof t?t:e),r="number"==typeof t?t:this.getEntityForComponent(t);void 0!==r&&(null===(i=this.components.get(s))||void 0===i?void 0:i.has(r))&&this.components.get(s).delete(r)}isComponentEnabled(t,e){var i;const s=this.getComponentTypeId("object"==typeof t?t:e),r="number"==typeof t?t:this.getEntityForComponent(t);return void 0!==r&&!(null===(i=this.disabledComponents.get(r))||void 0===i?void 0:i.has(s))}disableComponent(t,e){const i="number"==typeof t?t:this.getEntityForComponent(t),s=this.getComponentTypeId("object"==typeof t?t:e);null!=i&&(this.disabledComponents.has(i)?this.disabledComponents.get(i).has(s)||this.disabledComponents.get(i).add(s):this.disabledComponents.set(i,new Set([s])))}enableComponent(t,e){var i;const s="number"==typeof t?t:this.getEntityForComponent(t),r=this.getComponentTypeId("object"==typeof t?t:e);void 0!==s&&(null===(i=this.disabledComponents.get(s))||void 0===i?void 0:i.has(r))&&this.disabledComponents.get(s).delete(r)}getComponentFromParent(t,e){let i=t;for(;i;){const t=this.getComponent(i,e);if(t)return t;i=this.getParent(i)}}search(t,e,i=!1){const s=[],r=this.getComponentTypeId(t),o="boolean"==typeof e?e:i,a="object"==typeof e?e:void 0;return this.components.has(r)&&this.components.get(r).forEach(((e,i)=>{a&&!Object.keys(a).every((t=>e[t]===a[t]))||!(o||this.isEntityEnabled(i)&&this.isComponentEnabled(i,t))||s.push({entity:i,component:e})})),s}searchEntitiesByComponents(t){const e=[];let i=!0;for(const s of t){const t=this.getComponentTypeId(s);if(!t||!this.components.has(t))return[];if(i){e.push(...this.components.get(t).keys()),i=!1;continue}const r=new Set(this.components.get(t).keys());e.forEach(((t,i)=>{r.has(t)||e.splice(i,1)}))}return e}searchInChildren(t,e,i=!1){const s=this.getChildren(t);return this.search(e,i).filter((({entity:t})=>s.includes(t)))}getComponentTypeId(t){const e="object"==typeof t?t.constructor.prototype:t.prototype;return void 0===e.__ecs_type_id&&(e.__ecs_type_id=++this.lastComponentTypeId),e.__ecs_type_id}};D=o([i(t.EntityManager)],D);let F=class{constructor(){this.systems=[]}findSystemIndex(t){return this.systems.findIndex((e=>e[0]instanceof t))}addSystem(t,e){if(this.systems.some((t=>t[0]instanceof t.constructor)))throw new Error(`SystemManager already has an instance of ${t.constructor.name}.`);this.systems.push([t,e,!1,!1])}hasSystem(t){return this.systems.some((e=>e[0]instanceof t))}getSystem(t){const e=this.findSystemIndex(t);return-1!==e?this.systems[e][0]:void 0}groupHasSystems(t){return this.systems.filter((e=>e[1]===t)).length>0}enableSystem(t){const e=this.findSystemIndex(t);if(-1===e||!0===this.systems[e][2])return;const i=this.systems[e];!1===i[3]&&(i[3]=!0,i[0].onCreate&&i[0].onCreate()),i[2]=!0,i[0].onEnabled&&i[0].onEnabled()}disableSystem(t){const e=this.findSystemIndex(t);if(-1===e||!1===this.systems[e][2])return;const i=this.systems[e];i[2]=!1,i[0].onDisabled&&i[0].onDisabled()}setExecutionOrder(t,e){const i=this.findSystemIndex(t);if(-1===i)throw new Error(`Cannot set execution order because ${t.name} is not a system.`);this.systems.splice(e,0,this.systems.splice(i,1)[0])}removeSystem(t){const e=this.findSystemIndex(t);if(-1===e)return;const i=this.systems.splice(e,1)[0][0];i.onDestroy&&i.onDestroy()}disableAllSystems(){this.systems.forEach((t=>{t[2]&&this.disableSystem(t[0].constructor)}))}update(t){this.systems.filter((e=>e[1]===t&&!0===e[2])).forEach((t=>t[0].onUpdate()))}};F=o([i(t.SystemManager)],F);class U{constructor(){this.buttons=new Map,this.axes=new Map,this._dpadAxes=new n,this._leftStickAxes=new n,this._rightStickAxes=new n}get dpadAxes(){return this._dpadAxes.set(this.dpadRight?1:this.dpadLeft?-1:0,this.dpadUp?1:this.dpadDown?-1:0),this._dpadAxes}get leftStickAxes(){return this._leftStickAxes.set(this.leftStickHorizontal,this.leftStickVertical),this._leftStickAxes}get rightStickAxes(){return this._rightStickAxes.set(this.rightStickHorizontal,this.rightStickVertical),this._rightStickAxes}get dpadUp(){var t;return null!==(t=this.buttons.get(12))&&void 0!==t&&t}get dpadDown(){var t;return null!==(t=this.buttons.get(13))&&void 0!==t&&t}get dpadLeft(){var t;return null!==(t=this.buttons.get(14))&&void 0!==t&&t}get dpadRight(){var t;return null!==(t=this.buttons.get(15))&&void 0!==t&&t}get bottomFace(){var t;return null!==(t=this.buttons.get(0))&&void 0!==t&&t}get rightFace(){var t;return null!==(t=this.buttons.get(1))&&void 0!==t&&t}get leftFace(){var t;return null!==(t=this.buttons.get(2))&&void 0!==t&&t}get topFace(){var t;return null!==(t=this.buttons.get(3))&&void 0!==t&&t}get leftShoulder(){var t;return null!==(t=this.buttons.get(4))&&void 0!==t&&t}get rightShoulder(){var t;return null!==(t=this.buttons.get(5))&&void 0!==t&&t}get leftTrigger(){var t;return null!==(t=this.buttons.get(6))&&void 0!==t&&t}get rightTrigger(){var t;return null!==(t=this.buttons.get(7))&&void 0!==t&&t}get back(){var t;return null!==(t=this.buttons.get(8))&&void 0!==t&&t}get start(){var t;return null!==(t=this.buttons.get(9))&&void 0!==t&&t}get leftStickButton(){var t;return null!==(t=this.buttons.get(10))&&void 0!==t&&t}get rightStickButton(){var t;return null!==(t=this.buttons.get(11))&&void 0!==t&&t}get leftStickHorizontal(){var t;return null!==(t=this.axes.get(0))&&void 0!==t?t:0}get leftStickVertical(){var t;return-(null!==(t=this.axes.get(1))&&void 0!==t?t:0)}get rightStickHorizontal(){var t;return null!==(t=this.axes.get(2))&&void 0!==t?t:0}get rightStickVertical(){var t;return-(null!==(t=this.axes.get(3))&&void 0!==t?t:0)}get anyButtonPressed(){var t;return null!==(t=Array.from(this.buttons.values()).find((t=>t)))&&void 0!==t&&t}vibrate(t=200,e=.2,i=.2,s=0){this.vibrationInput={duration:t,weakMagnitude:e,startDelay:s,strongMagnitude:i}}}class I{constructor(){this.pressedKeys=[]}isPressed(t){return this.pressedKeys.includes(t)}orPressed(t){return t.reduce(((t,e)=>t||this.pressedKeys.includes(e)),!1)}andPressed(t){return t.reduce(((t,e)=>t&&this.pressedKeys.includes(e)),!0)}isPressedReturn(t,e,i){return this.pressedKeys.includes(t)?e:i}orPressedReturn(t,e,i){return t.reduce(((t,e)=>t||this.pressedKeys.includes(e)),!1)?e:i}andPressedReturn(t,e,i){return t.reduce(((t,e)=>t&&this.pressedKeys.includes(e)),!0)?e:i}}class L{constructor(){this.leftButtonPressed=!1,this.scrollButtonPressed=!1,this.rightButtonPressed=!1,this.positionInViewport=new n,this.hasMoved=!1,this.wheelScroll=new n}}class j{constructor(){this.touching=!1,this.interactions=[]}}let O=class{constructor(){this.keyboard=new I,this.mouse=new L,this.touchScreen=new j,this.gamepads=[]}};O=o([i(t.InputManager)],O);const k=[60,120,180,240];let V=class{get deltaTime(){return this.unscaledDeltaTime*this.timeScale}get physicsDeltaTime(){return this.unscaledPhysicsDeltaTime*this.timeScale}get renderDeltaTime(){return this.browserDeltaTime*this.timeScale}constructor({physicsFramerate:t}){if(this.timeScale=1,this.browserDeltaTime=0,this.unscaledDeltaTime=0,this.unscaledPhysicsDeltaTime=0,this.maxDeltaTime=1/30,this.thenForGame=0,this.thenForPhysics=0,this.thenForRender=0,this.lastIntervalId=0,this.intervals=new Map,t&&!k.includes(t))throw new Error(`Invalid Physics frame rate. Allowed: [${k.join(", ")}]`);this.fixedGameFramerate=60,this.fixedGameDeltaTime=parseFloat((1/this.fixedGameFramerate).toFixed(6)),this.fixedPhysicsFramerate=null!=t?t:180,this.fixedPhysicsDeltaTime=parseFloat((1/this.fixedPhysicsFramerate).toFixed(6))}updateForRender(t){this.browserDeltaTime=Math.min(Math.max(0,t-this.thenForRender),this.maxDeltaTime),this.thenForRender=t}updateForGame(t){this.unscaledDeltaTime=Math.min(Math.max(this.fixedGameDeltaTime,t-this.thenForGame),this.maxDeltaTime),this.thenForGame=t}updateForPhysics(t){this.unscaledPhysicsDeltaTime=Math.min(Math.max(0,t-this.thenForPhysics),this.maxDeltaTime),this.thenForPhysics=t}updateIntervals(){if(0===this.intervals.size)return;const t=performance.now();for(const[e,i]of this.intervals)i.executeImmediately&&(i.timestamp=t-i.delay,i.executeImmediately=!1),t-i.timestamp>=i.delay&&(i.callback(),i.times&&--i.times<=0?(this.intervals.delete(e),0===this.intervals.size&&(this.lastIntervalId=0)):i.timestamp=t)}setInterval({callback:t,delay:e,times:i,executeImmediately:s}){const r=++this.lastIntervalId;return this.intervals.set(r,{callback:t,delay:e,times:i,executeImmediately:s,timestamp:performance.now()}),r}clearInterval(t){this.intervals.delete(t),0===this.intervals.size&&(this.lastIntervalId=0)}clearAllIntervals(){this.intervals.clear(),this.lastIntervalId=0}};var G;V=o([i(t.TimeManager),a(0,s(t.GameConfig))],V),function(t){t[t.Image=0]="Image",t[t.Audio=1]="Audio",t[t.Font=2]="Font",t[t.Video=3]="Video"}(G||(G={}));let z=class{constructor(){this.assets=[]}getAssetsLoaded(){return this.assets.reduce(((t,e)=>t&&e.loaded),!0)}loadImage(t,e){const i=new Image;i.crossOrigin="",i.src=t;const s=this.createAsset(t,G.Image,i,e),r=()=>s.loaded=!0;return i.complete?r():i.addEventListener("load",r),i}loadAudio(t,e){const i=new Audio;i.src=t;const s=this.createAsset(t,G.Audio,i,e);return i.duration?s.loaded=!0:i.addEventListener("canplaythrough",(()=>s.loaded=!0)),i}loadFont(t,e){const i=new FontFace(t,`url(${e})`),s=this.createAsset(e,G.Font,i);return s.family=t,document.fonts.add(i),i.load().then((()=>s.loaded=!0)),i}loadVideo(t,e){const i=document.createElement("video");i.playsInline=!0,i.src=t;const s=this.createAsset(t,G.Video,i,e);return i.duration?s.loaded=!0:i.addEventListener("canplaythrough",(()=>s.loaded=!0)),i}getImage(t){var e;return null===(e=this.assets.find((e=>e.type===G.Image&&(e.url===t||e.name===t))))||void 0===e?void 0:e.element}getAudio(t){var e;return null===(e=this.assets.find((e=>e.type===G.Audio&&(e.url===t||e.name===t))))||void 0===e?void 0:e.element}getFont(t){var e;return null===(e=this.assets.find((e=>e.type===G.Font&&e.family===t)))||void 0===e?void 0:e.element}getVideo(t){var e;return null===(e=this.assets.find((e=>e.type===G.Video&&(e.url===t||e.name===t))))||void 0===e?void 0:e.element}createAsset(t,e,i,s){const r={type:e,url:t,element:i,loaded:!1,name:s};return this.assets.push(r),r}};z=o([i(t.AssetManager)],z);class N{get playing(){return"playing"===this.state}get paused(){return"paused"===this.state}get stopped(){return"stopped"===this.state}constructor(t){this.action=void 0,this.fixedToTimeScale=!1,this.loop=!1,this.state="stopped",this.volume=1,this._currentAudioSource=void 0,this._playPromisePendind=!1,Object.assign(this,t)}play(t){t&&(this.audioSource=t),this.action="play"}pause(){this.action="pause"}stop(){this.action="stop"}}const W={AudioPlayerSystem:Symbol.for("AudioPlayerSystem"),ButtonSystem:Symbol.for("ButtonSystem"),TiledWrapperSystem:Symbol.for("TiledWrapperSystem"),TilemapPreProcessingSystem:Symbol.for("TilemapPreProcessingSystem"),TransformSystem:Symbol.for("TransformSystem"),GamepadSystem:Symbol.for("GamepadSystem"),KeyboardSystem:Symbol.for("KeyboardSystem"),MouseSystem:Symbol.for("MouseSystem"),TouchScreenSystem:Symbol.for("TouchScreenSystem"),UpdateBallColliderShapeSystem:Symbol.for("UpdateBallColliderShapeSystem"),UpdateBoxColliderShapeSystem:Symbol.for("UpdateBoxColliderShapeSystem"),UpdateEdgeColliderShapeSystem:Symbol.for("UpdateEdgeColliderShapeSystem"),UpdatePolygonColliderShapeSystem:Symbol.for("UpdatePolygonColliderShapeSystem"),UpdateTilemapColliderShapeSystem:Symbol.for("UpdateTilemapColliderShapeSystem"),UpdateCollidersAfterRepositionSystem:Symbol.for("UpdateCollidersAfterRepositionSystem"),ApplyRepositionSystem:Symbol.for("ApplyRepositionSystem"),ApplyVelocitySystem:Symbol.for("ApplyVelocitySystem"),ResolveCollisionSystem:Symbol.for("ResolveCollisionSystem"),AnimatorSystem:Symbol.for("AnimatorSystem"),CameraSystem:Symbol.for("CameraSystem"),ClearScreenSystem:Symbol.for("ClearScreenSystem"),CullingSystem:Symbol.for("CullingSystem"),MaskRendererSystem:Symbol.for("MaskRendererSystem"),RenderSystem:Symbol.for("RenderSystem"),ShadowLightRendererSystem:Symbol.for("ShadowLightRendererSystem"),SpriteRendererSystem:Symbol.for("SpriteRendererSystem"),TextRendererSystem:Symbol.for("TextRendererSystem"),TilemapRendererSystem:Symbol.for("TilemapRendererSystem"),VideoRendererSystem:Symbol.for("VideoRendererSystem"),DebugColliderRenderSystem:Symbol.for("DebugColliderRenderSystem"),DebugMousePositionSystem:Symbol.for("DebugMousePositionSystem")},H=["click","contextmenu","auxclick","dblclick","mousedown","mouseup","pointerup","touchend","keydown","keyup"];let Y=class{constructor(t,e,i){this.entityManager=t,this.inputManager=e,this.timeManager=i,this.canPlay=!0,this.userInputErrorCatched=!1,this.userInputEventHandler=()=>{H.forEach((t=>{window.removeEventListener(t,this.userInputEventHandler)})),this.canPlay=!0}}onCreate(){document.addEventListener("visibilitychange",(()=>{this.entityManager.search(N).forEach((({component:{audioSource:t,playing:e}})=>{document.hidden&&t?t.pause():!document.hidden&&t&&e&&t.play()}))}))}catchUserInput(){this.canPlay=!1,this.userInputErrorCatched=!0,H.forEach((t=>window.addEventListener(t,this.userInputEventHandler)))}checkGamepad(){return this.canPlay=this.inputManager.gamepads.some((t=>t.anyButtonPressed)),this.canPlay}onUpdate(){(this.canPlay||this.checkGamepad())&&this.entityManager.search(N).forEach((({component:t})=>{t.audioSource&&t.audioSource.duration&&(t.audioSource!==t._currentAudioSource&&(t._currentAudioSource&&(t._currentAudioSource.pause(),t._currentAudioSource.currentTime=0),t._currentAudioSource=t.audioSource,t.audioSource.currentTime=0,t.state="stopped"),t.audioSource.loop=t.loop,t.audioSource.volume=t.volume,"play"!==t.action||"playing"===t.state||t._playPromisePendind?"pause"===t.action&&"playing"===t.state?(t.audioSource.pause(),t.state="paused"):"stop"!==t.action||t.audioSource.paused&&0===t.audioSource.currentTime?"playing"===t.state&&t.audioSource.paused&&(t.state="stopped"):(t.audioSource.pause(),t.audioSource.currentTime=0,t.state="stopped"):(t._playPromisePendind=!0,t.audioSource.playbackRate=t.fixedToTimeScale?this.timeManager.timeScale<.0625?0:Math.min(this.timeManager.timeScale,16):1,t.audioSource.play().then((()=>{t._playPromisePendind=!1,t.state="playing"})).catch((()=>{t._playPromisePendind=!1,this.userInputErrorCatched||this.catchUserInput()}))),t.action=void 0)}))}onDisabled(){this.entityManager.search(N).forEach((({component:{audioSource:t}})=>{t&&(t.pause(),t.currentTime=0)}))}onDestroy(){this.onDisabled()}};var X;function $(){return function(t){Q(t,X.GameLogic)}}function K(){return function(t){Q(t,X.GamePhysics)}}function q(){return function(t){Q(t,X.GamePreRender)}}Y=o([i(W.AudioPlayerSystem),a(0,s(t.EntityManager)),a(1,s(t.InputManager)),a(2,s(t.TimeManager))],Y),function(t){t[t.GameLogic=0]="GameLogic",t[t.GamePhysics=1]="GamePhysics",t[t.GamePreRender=2]="GamePreRender",t[t.Physics=3]="Physics",t[t.PreGameLogic=4]="PreGameLogic",t[t.Render=5]="Render",t[t.Transform=6]="Transform"}(X||(X={}));const Q=(t,e)=>{t.prototype.__system_group||(t.prototype.__system_group=e)};class J{constructor(t){this.position=new n,this.scale=new n(1,1),this.rotation=0,this.localPosition=new n,this.localScale=new n(1,1),this.localRotation=0,this._awake=!1,this._parent=void 0,Object.assign(this,t)}}const Z="Default",tt="Debug";class et{constructor(t){this.layers=[Z],this.zoom=1,this.depth=0,this.debug=!1,this._renderData={position:new n,depth:0,zoom:1,layers:[]},Object.assign(this,t)}}var it;!function(t){t.LegacyWebGL="webgl",t.WebGL2="webgl2"}(it||(it={}));class st{constructor(t){if(this.canvas=t,this.contextVersion=this.getContextVersion(),!this.contextVersion)throw new Error("Your browser does not support WebGL.");this.gl=this.canvas.getContext(this.contextVersion)}getContextVersion(){return null!==this.canvas.getContext(it.WebGL2)?it.WebGL2:null!==this.canvas.getContext(it.LegacyWebGL)?it.LegacyWebGL:void 0}}class rt{constructor(){this.fontAtlas=new Map}hasFontAtlas(t){return this.fontAtlas.has(this.getId(t))}getFontAtlas(t){return this.fontAtlas.get(this.getId(t))}getOrCreate(t){var e;return null!==(e=this.getFontAtlas(t))&&void 0!==e?e:this.create(t)}create(t){const{font:e,charRanges:i,fontSize:s,spacing:r}=t;this.chars=[];for(let t=0;t<i.length;t+=2)for(let e=i[t];e<=i[t+1];e++)this.chars.push(String.fromCharCode(e));this.font=e instanceof FontFace?e.family:e,this.fontSize=s,this.spacing=r,this.id=this.getId(t);const o=this.renderAtlas();return this.fontAtlas.set(this.id,o),o}getId({font:t,charRanges:e,fontSize:i,spacing:s}){return JSON.stringify({font:t instanceof FontFace?t.family:t,charRanges:e,fontSize:i,spacing:s})}renderAtlas(){const t=new ot(this.id,this.fontSize,Math.ceil(Math.sqrt(this.chars.length)),this.spacing),e=t.canvas.getContext("2d");e.clearRect(0,0,t.canvas.width,t.canvas.height),e.textBaseline="top",e.fillStyle="#FFFFFF",e.font=`${this.fontSize}px ${this.font}`;let i=0,s=0;for(let r=0;r<this.chars.length;r++)e.fillText(this.chars[r],i,s),t.glyphs.set(this.chars[r],{id:r,width:e.measureText(this.chars[r]).width}),(i+=this.fontSize+this.spacing)>t.canvas.width-this.fontSize&&(i=0,s+=this.fontSize+this.spacing);return t}}class ot{constructor(t,e,i,s){this.id=t,this.fontSize=e,this.gridSize=i,this.spacing=s,this.canvas=document.createElement("canvas"),this.glyphs=new Map,this.canvas.width=this.gridSize*(this.fontSize+this.spacing),this.canvas.height=this.canvas.width}}class at{constructor(t,e){this.gl=t,this.shaderLoader=e}create(t,e){const i=this.gl.createProgram(),s=this.shaderLoader.load(this.gl.VERTEX_SHADER,t),r=this.shaderLoader.load(this.gl.FRAGMENT_SHADER,e);this.gl.attachShader(i,s),this.gl.attachShader(i,r),this.gl.linkProgram(i);const o=this.gl.LINK_STATUS;if(!this.gl.getProgramParameter(i,o)){const t=this.gl.getProgramInfoLog(i);throw this.gl.deleteProgram(i),new Error(`Unable to initialize the Program: ${t}`)}return i}}class nt{constructor(t,e,i){this.gl=t,this.contextVersion=e,this.programFactory=i}loadProgram(){this.program=this.contextVersion===it.WebGL2?this.programFactory.create("#version 300 es\n\nin vec4 positionCoords;\nin vec2 textureCoords;\n\nuniform mat4 projectionMatrix;\nuniform mat4 modelMatrix;\nuniform mat4 textureMatrix;\n\nout vec2 texCoords;\n\nvoid main()\n{\n gl_Position = projectionMatrix * modelMatrix * positionCoords;\n texCoords = (textureMatrix * vec4(textureCoords, 0, 1)).xy;\n}","#version 300 es\nprecision highp float;\n\nin vec2 texCoords;\n\n// texture, mask and shadow\nuniform int u_renderTexture;\nuniform sampler2D u_texImage;\nuniform vec4 u_solidColor;\nuniform int u_useTintColor;\nuniform vec4 u_tintColor;\nuniform int u_useMaskColor;\nuniform vec4 u_maskColor;\nuniform float u_maskColorMix;\nuniform float u_alpha;\n\n// light\nstruct Light {\n vec2 position;\n float radius;\n float smoothMode;\n float intensity;\n};\n\nuniform int u_renderLight;\nuniform Light u_lights[64];\nuniform int u_numLights;\n\nout vec4 fragColor;\n\nvoid main()\n{\n if (u_renderTexture == 1) {\n vec4 texColor = texture(u_texImage, texCoords);\n\n if (texColor.a < 0.0001) {\n discard;\n }\n\n if (u_useTintColor == 1) {\n texColor = u_tintColor * texColor;\n }\n\n if (u_useMaskColor == 1) {\n texColor = mix(texColor, u_maskColor, clamp(u_maskColorMix, 0.0, 1.0));\n }\n\n fragColor = vec4(texColor.rgb, u_alpha * texColor.a); \n } else if (u_renderLight == 1) {\n vec2 fragCoord = gl_FragCoord.xy;\n float alpha = u_alpha;\n\n for (int i = 0; i < u_numLights; i++) {\n Light light = u_lights[i];\n float dist = distance(fragCoord, light.position);\n \n if (dist < light.radius) {\n alpha -= (light.smoothMode > 0.0 ? smoothstep(light.radius, 0.0, dist) : 1.0) * light.intensity;\n }\n }\n\n alpha = clamp(alpha, 0.0, u_alpha);\n\n fragColor = vec4(u_solidColor.rgb, alpha);\n } else {\n fragColor = vec4(u_solidColor.rgb, u_alpha);\n }\n}"):this.programFactory.create("precision mediump float;\n\nattribute vec2 positionCoords;\nattribute vec2 textureCoords;\n\nvarying vec2 texCoords;\n\nuniform mat4 projectionMatrix;\nuniform mat4 modelMatrix;\nuniform mat4 textureMatrix;\n\nvoid main()\n{\n gl_Position = projectionMatrix * modelMatrix * vec4(positionCoords, 0, 1);\n texCoords = (textureMatrix * vec4(textureCoords, 0, 1)).xy;\n}","precision mediump float;\n\nvarying vec2 texCoords;\n\n// texture, mask and shadow\nuniform int u_renderTexture;\nuniform sampler2D u_texImage;\nuniform vec4 u_solidColor;\nuniform int u_useTintColor;\nuniform vec4 u_tintColor;\nuniform int u_useMaskColor;\nuniform vec4 u_maskColor;\nuniform float u_maskColorMix;\nuniform float u_alpha;\n\n// light\nstruct Light {\n vec2 position;\n float radius;\n float smoothMode;\n float intensity;\n};\n\nuniform int u_renderLight;\nuniform Light u_lights[64];\nuniform int u_numLights;\n\nvoid main()\n{\n if (u_renderTexture == 1) {\n vec4 texColor = texture2D(u_texImage, texCoords);\n\n if (texColor.a < 0.0001) {\n discard;\n }\n\n if (u_useTintColor == 1) {\n texColor = u_tintColor * texColor;\n }\n\n if (u_useMaskColor == 1) {\n texColor = mix(texColor, u_maskColor, clamp(u_maskColorMix, 0.0, 1.0));\n }\n\n gl_FragColor = vec4(texColor.rgb, u_alpha * texColor.a);\n } else if (u_renderLight == 1) {\n vec2 fragCoord = gl_FragCoord.xy;\n float alpha = u_alpha;\n\n for (int i = 0; i < 64; i++) {\n if (u_lights[i].intensity == 0.0) continue; \n \n Light light = u_lights[i];\n float dist = distance(fragCoord, light.position);\n \n if (dist < light.radius) {\n alpha -= (light.smoothMode > 0.0 ? smoothstep(light.radius, 0.0, dist) : 1.0) * light.intensity;\n }\n }\n\n alpha = clamp(alpha, 0.0, u_alpha);\n\n gl_FragColor = vec4(u_solidColor.rgb, alpha);\n } else {\n gl_FragColor = vec4(u_solidColor.rgb, u_alpha);\n }\n}"),this.positionCoordsAttr=this.gl.getAttribLocation(this.program,"positionCoords"),this.texCoordsAttr=this.gl.getAttribLocation(this.program,"textureCoords"),this.modelMatrixUniform=this.gl.getUniformLocation(this.program,"modelMatrix"),this.projectionMatrixUniform=this.gl.getUniformLocation(this.program,"projectionMatrix"),this.textureMatrixUniform=this.gl.getUniformLocation(this.program,"textureMatrix"),this.renderTextureUniform=this.gl.getUniformLocation(this.program,"u_renderTexture"),this.textureUniform=this.gl.getUniformLocation(this.program,"u_texImage"),this.solidColorUniform=this.gl.getUniformLocation(this.program,"u_solidColor"),this.useTintColorUniform=this.gl.getUniformLocation(this.program,"u_useTintColor"),this.tintColorUniform=this.gl.getUniformLocation(this.program,"u_tintColor"),this.useMaskColorUniform=this.gl.getUniformLocation(this.program,"u_useMaskColor"),this.maskColorUniform=this.gl.getUniformLocation(this.program,"u_maskColor"),this.maskColorMixUniform=this.gl.getUniformLocation(this.program,"u_maskColorMix"),this.alphaUniform=this.gl.getUniformLocation(this.program,"u_alpha"),this.renderLightUniform=this.gl.getUniformLocation(this.program,"u_renderLight"),this.numLightsUniform=this.gl.getUniformLocation(this.program,"u_numLights"),this.gl.useProgram(this.program),this.gl.blendFunc(this.gl.SRC_ALPHA,this.gl.ONE_MINUS_SRC_ALPHA)}}class ht{constructor(t){this.gl=t}load(t,e){const i=this.gl.createShader(t);this.gl.shaderSource(i,e),this.gl.compileShader(i);const s=this.gl.COMPILE_STATUS;if(!this.gl.getShaderParameter(i,s)){const t=this.gl.getShaderInfoLog(i);throw this.gl.deleteShader(i),new Error(`Unable to initialize the shader program: ${t}`)}return i}}var lt="undefined"!=typeof Float32Array?Float32Array:Array;function ct(){var t=new lt(16);return lt!=Float32Array&&(t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0),t[0]=1,t[5]=1,t[10]=1,t[15]=1,t}function dt(t){return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}function gt(t,e,i){var s,r,o,a,n,h,l,c,d,g,m,u,p=i[0],y=i[1],f=i[2];return e===t?(t[12]=e[0]*p+e[4]*y+e[8]*f+e[12],t[13]=e[1]*p+e[5]*y+e[9]*f+e[13],t[14]=e[2]*p+e[6]*y+e[10]*f+e[14],t[15]=e[3]*p+e[7]*y+e[11]*f+e[15]):(s=e[0],r=e[1],o=e[2],a=e[3],n=e[4],h=e[5],l=e[6],c=e[7],d=e[8],g=e[9],m=e[10],u=e[11],t[0]=s,t[1]=r,t[2]=o,t[3]=a,t[4]=n,t[5]=h,t[6]=l,t[7]=c,t[8]=d,t[9]=g,t[10]=m,t[11]=u,t[12]=s*p+n*y+d*f+e[12],t[13]=r*p+h*y+g*f+e[13],t[14]=o*p+l*y+m*f+e[14],t[15]=a*p+c*y+u*f+e[15]),t}function mt(t,e,i){var s=i[0],r=i[1],o=i[2];return t[0]=e[0]*s,t[1]=e[1]*s,t[2]=e[2]*s,t[3]=e[3]*s,t[4]=e[4]*r,t[5]=e[5]*r,t[6]=e[6]*r,t[7]=e[7]*r,t[8]=e[8]*o,t[9]=e[9]*o,t[10]=e[10]*o,t[11]=e[11]*o,t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],t}function ut(t,e,i){var s=Math.sin(i),r=Math.cos(i),o=e[0],a=e[1],n=e[2],h=e[3],l=e[4],c=e[5],d=e[6],g=e[7];return e!==t&&(t[8]=e[8],t[9]=e[9],t[10]=e[10],t[11]=e[11],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t[0]=o*r+l*s,t[1]=a*r+c*s,t[2]=n*r+d*s,t[3]=h*r+g*s,t[4]=l*r-o*s,t[5]=c*r-a*s,t[6]=d*r-n*s,t[7]=g*r-h*s,t}Math.hypot||(Math.hypot=function(){for(var t=0,e=arguments.length;e--;)t+=arguments[e]*arguments[e];return Math.sqrt(t)});var pt=function(t,e,i,s,r,o,a){var n=1/(e-i),h=1/(s-r),l=1/(o-a);return t[0]=-2*n,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=-2*h,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=2*l,t[11]=0,t[12]=(e+i)*n,t[13]=(r+s)*h,t[14]=(a+o)*l,t[15]=1,t};const yt=(t,e,i,s)=>{t=dt(t),pt(t,-e.canvas.width/2,e.canvas.width/2,-e.canvas.height/2,e.canvas.height/2,-1,1),mt(t,t,[null!=i?i:1,null!=i?i:1,1]),gt(t,t,[-s.x,-s.y,0])},ft=t=>{const e=/^#?([a-f\d]{2})?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);return e?{r:parseInt(e[2],16)/256,g:parseInt(e[3],16)/256,b:parseInt(e[4],16)/256,a:void 0!==e[1]?parseInt(e[1],16)/256:1}:null};class xt{constructor(t){this.gl=t}render(t){const e=ft(t);this.gl.clearColor(e.r,e.g,e.b,e.a),this.gl.clear(this.gl.COLOR_BUFFER_BIT)}}var Mt;!function(t){t[t.Sprite=0]="Sprite",t[t.Text=1]="Text",t[t.Tilemap=2]="Tilemap",t[t.Mask=3]="Mask",t[t.Geometric=4]="Geometric",t[t.Video=5]="Video",t[t.Shadow=6]="Shadow"}(Mt||(Mt={}));var vt,bt;!function(t){t[t.Polygon=0]="Polygon",t[t.Circumference=1]="Circumference",t[t.Line=2]="Line"}(vt||(vt={}));class Ct{constructor(t,e){this.gl=t,this.programManager=e,this.projectionMatrix=ct(),this.modelMatrix=ct(),this.textureMatrix=ct(),this.circumferencePositionBuffer=this.gl.createBuffer(),this.linesPositionBuffer=this.gl.createBuffer();const i=2*Math.PI/60,s=new Float32Array(m(1,60,1).reduce(((t,e)=>[...t,Math.cos(e*i),Math.sin(e*i)]),[]));this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.circumferencePositionBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,s,this.gl.STATIC_DRAW)}render(t,e,i){switch(this.gl.disableVertexAttribArray(this.programManager.texCoordsAttr),t.shape){case vt.Polygon:this.renderLines(t,e,this.gl.LINE_LOOP);break;case vt.Line:this.renderLines(t,e,this.gl.LINES);break;case vt.Circumference:this.renderCircumference(t,e,i);break;default:return!1}return!0}renderLines(t,e,i){var s;this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.linesPositionBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array(t.vertexModel.reduce(((t,e)=>[...t,e.x,e.y]),[])),this.gl.DYNAMIC_DRAW),this.gl.enableVertexAttribArray(this.programManager.positionCoordsAttr),this.gl.vertexAttribPointer(this.programManager.positionCoordsAttr,2,this.gl.FLOAT,!1,0,0),this.modelMatrix=dt(this.modelMatrix),gt(this.modelMatrix,this.modelMatrix,[t.position.x,t.position.y,0]),ut(this.modelMatrix,this.modelMatrix,null!==(s=t.rotation)&&void 0!==s?s:0),yt(this.projectionMatrix,this.gl,e.zoom,e.position),this.gl.uniformMatrix4fv(this.programManager.projectionMatrixUniform,!1,this.projectionMatrix),this.gl.uniformMatrix4fv(this.programManager.modelMatrixUniform,!1,this.modelMatrix),this.gl.uniformMatrix4fv(this.programManager.textureMatrixUniform,!1,this.textureMatrix),this.gl.uniform1i(this.programManager.renderTextureUniform,0);const{r:r,g:o,b:a,a:n}=ft(t.color);this.gl.uniform4f(this.programManager.solidColorUniform,r,o,a,n),this.gl.uniform1f(this.programManager.alphaUniform,1),this.gl.drawArrays(i,0,t.vertexModel.length),this.lastShape="polygon"}renderCircumference(t,e,i){i===Mt.Geometric&&"circumference"===this.lastShape||(this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.circumferencePositionBuffer),this.gl.enableVertexAttribArray(this.programManager.positionCoordsAttr),this.gl.vertexAttribPointer(this.programManager.positionCoordsAttr,2,this.gl.FLOAT,!1,0,0)),this.modelMatrix=dt(this.modelMatrix),gt(this.modelMatrix,this.modelMatrix,[t.position.x,t.position.y,0]),mt(this.modelMatrix,this.modelMatrix,[t.radius,t.radius,1]),yt(this.projectionMatrix,this.gl,e.zoom,e.position),this.gl.uniformMatrix4fv(this.programManager.projectionMatrixUniform,!1,this.projectionMatrix),this.gl.uniformMatrix4fv(this.programManager.modelMatrixUniform,!1,this.modelMatrix),this.gl.uniformMatrix4fv(this.programManager.textureMatrixUniform,!1,this.textureMatrix),this.gl.uniform1i(this.programManager.renderTextureUniform,0);const{r:s,g:r,b:o,a:a}=ft(t.color);this.gl.uniform4f(this.programManager.solidColorUniform,s,r,o,a),this.gl.uniform1f(this.programManager.alphaUniform,1),this.gl.drawArrays(this.gl.LINE_LOOP,0,60),this.lastShape="circumference"}}!function(t){t[t.Rectangle=0]="Rectangle",t[t.Circumference=1]="Circumference",t[t.Polygon=2]="Polygon"}(bt||(bt={}));let St=class{constructor(t,e){this.gl=t,this.programManager=e,this.type=Mt.Mask,this.projectionMatrix=ct(),this.modelMatrix=ct(),this.textureMatrix=ct(),this.circumferencePositionBuffer=this.gl.createBuffer(),this.rectanglePositionBuffer=this.gl.createBuffer(),this.polygonPositionBuffer=this.gl.createBuffer();const i=2*Math.PI/60,s=[0,0];for(let t=0;t<=60;t++)s.push(Math.cos(t*i),Math.sin(t*i));this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.circumferencePositionBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array(s),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.rectanglePositionBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-.5,-.5,-.5,.5,.5,-.5,.5,-.5,-.5,.5,.5,.5]),this.gl.STATIC_DRAW)}render(t,e,i){return this.gl.disableVertexAttribArray(this.programManager.texCoordsAttr),t.shape===bt.Rectangle?this.renderRectangle(t,e,i):t.shape===bt.Circumference?this.renderCircumference(t,e,i):t.shape===bt.Polygon&&this.renderPolygon(t,e,i),this.lastShape=t.shape,!0}renderRectangle(t,e,i){var s,r;i===Mt.Mask&&this.lastShape===bt.Rectangle||(this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.rectanglePositionBuffer),this.gl.enableVertexAttribArray(this.programManager.positionCoordsAttr),this.gl.vertexAttribPointer(this.programManager.positionCoordsAttr,2,this.gl.FLOAT,!1,0,0)),this.modelMatrix=dt(this.modelMatrix),gt(this.modelMatrix,this.modelMatrix,[t.position.x,t.position.y,0]),ut(this.modelMatrix,this.modelMatrix,null!==(s=t.rotation)&&void 0!==s?s:0),mt(this.modelMatrix,this.modelMatrix,[t.width,t.height,1]),yt(this.projectionMatrix,this.gl,e.zoom,e.position),this.gl.uniformMatrix4fv(this.programManager.projectionMatrixUniform,!1,this.projectionMatrix),this.gl.uniformMatrix4fv(this.programManager.modelMatrixUniform,!1,this.modelMatrix),this.gl.uniformMatrix4fv(this.programManager.textureMatrixUniform,!1,this.textureMatrix),t.opacity>=0&&t.opacity<1?this.gl.enable(this.gl.BLEND):this.gl.disable(this.gl.BLEND),this.gl.uniform1i(this.programManager.renderTextureUniform,0);const{r:o,g:a,b:n,a:h}=ft(t.color);this.gl.uniform4f(this.programManager.solidColorUniform,o,a,n,h),this.gl.uniform1f(this.programManager.alphaUniform,null!==(r=t.opacity)&&void 0!==r?r:1),this.gl.drawArrays(this.gl.TRIANGLES,0,6)}renderCircumference(t,e,i){var s,r;i===Mt.Mask&&this.lastShape===bt.Circumference||(this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.circumferencePositionBuffer),this.gl.enableVertexAttribArray(this.programManager.positionCoordsAttr),this.gl.vertexAttribPointer(this.programManager.positionCoordsAttr,2,this.gl.FLOAT,!1,0,0)),this.modelMatrix=dt(this.modelMatrix),gt(this.modelMatrix,this.modelMatrix,[t.position.x,t.position.y,0]),ut(this.modelMatrix,this.modelMatrix,null!==(s=t.rotation)&&void 0!==s?s:0),mt(this.modelMatrix,this.modelMatrix,[t.radius,t.radius,1]),yt(this.projectionMatrix,this.gl,e.zoom,e.position),this.gl.uniformMatrix4fv(this.programManager.projectionMatrixUniform,!1,this.projectionMatrix),this.gl.uniformMatrix4fv(this.programManager.modelMatrixUniform,!1,this.modelMatrix),this.gl.uniformMatrix4fv(this.programManager.textureMatrixUniform,!1,this.textureMatrix),t.opacity>=0&&t.opacity<1?this.gl.enable(this.gl.BLEND):this.gl.disable(this.gl.BLEND),this.gl.uniform1i(this.programManager.renderTextureUniform,0);const{r:o,g:a,b:n,a:h}=ft(t.color);this.gl.uniform4f(this.programManager.solidColorUniform,o,a,n,h),this.gl.uniform1f(this.programManager.alphaUniform,null!==(r=t.opacity)&&void 0!==r?r:1),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,62)}renderPolygon(t,e,i){var s,r;i===Mt.Mask&&this.lastShape===bt.Polygon||(this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.polygonPositionBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array(t.vertices.reduce(((t,e)=>[...t,e.x,e.y]),[0,0])),this.gl.DYNAMIC_DRAW),this.gl.enableVertexAttribArray(this.programManager.positionCoordsAttr),this.gl.vertexAttribPointer(this.programManager.positionCoordsAttr,2,this.gl.FLOAT,!1,0,0)),this.modelMatrix=dt(this.modelMatrix),gt(this.modelMatrix,this.modelMatrix,[t.position.x,t.position.y,0]),ut(this.modelMatrix,this.modelMatrix,null!==(s=t.rotation)&&void 0!==s?s:0),yt(this.projectionMatrix,this.gl,e.zoom,e.position),this.gl.uniformMatrix4fv(this.programManager.projectionMatrixUniform,!1,this.projectionMatrix),this.gl.uniformMatrix4fv(this.programManager.modelMatrixUniform,!1,this.modelMatrix),this.gl.uniformMatrix4fv(this.programManager.textureMatrixUniform,!1,this.textureMatrix),t.opacity>=0&&t.opacity<1?this.gl.enable(this.gl.BLEND):this.gl.disable(this.gl.BLEND),this.gl.uniform1i(this.programManager.renderTextureUniform,0);const{r:o,g:a,b:n,a:h}=ft(t.color);this.gl.uniform4f(this.programManager.solidColorUniform,o,a,n,h),this.gl.uniform1f(this.programManager.alphaUniform,null!==(r=t.opacity)&&void 0!==r?r:1),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,t.vertices.length+1)}},At=class{constructor(t,e){this.gl=t,this.programManager=e,this.projectionMatrix=ct(),this.modelMatrix=ct(),this.textureMatrix=ct(),this.positionBuffer=this.gl.createBuffer(),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.positionBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-.5,-.5,-.5,.5,.5,-.5,.5,-.5,-.5,.5,.5,.5]),this.gl.STATIC_DRAW)}render(t,e,i){var s,r;i!==Mt.Shadow&&(this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.positionBuffer),this.gl.enableVertexAttribArray(this.programManager.positionCoordsAttr),this.gl.vertexAttribPointer(this.programManager.positionCoordsAttr,2,this.gl.FLOAT,!1,0,0),this.gl.disableVertexAttribArray(this.programManager.texCoordsAttr)),this.modelMatrix=dt(this.modelMatrix),gt(this.modelMatrix,this.modelMatrix,[t.position.x,t.position.y,0]),ut(this.modelMatrix,this.modelMatrix,null!==(s=t.rotation)&&void 0!==s?s:0),mt(this.modelMatrix,this.modelMatrix,[t.width,t.height,1]),yt(this.projectionMatrix,this.gl,e.zoom,e.position),this.gl.uniformMatrix4fv(this.programManager.projectionMatrixUniform,!1,this.projectionMatrix),this.gl.uniformMatrix4fv(this.programManager.modelMatrixUniform,!1,this.modelMatrix),this.gl.uniformMatrix4fv(this.programManager.textureMatrixUniform,!1,this.textureMatrix),this.gl.enable(this.gl.BLEND),this.gl.uniform1i(this.programManager.renderTextureUniform,0),this.gl.uniform1i(this.programManager.renderLightUniform,1);const{r:o,g:a,b:n,a:h}=ft(t.color);this.gl.uniform4f(this.programManager.solidColorUniform,o,a,n,h),this.gl.uniform1f(this.programManager.alphaUniform,null!==(r=t.opacity)&&void 0!==r?r:1),this.gl.uniform1i(this.programManager.numLightsUniform,t.lights.length);for(const[i,s]of t.lights.entries()){if(i>=64)break;this.gl.uniform2f(this.gl.getUniformLocation(this.programManager.program,`u_lights[${i}].position`),this.gl.canvas.width/2+(s.position.x-e.position.x)*e.zoom,this.gl.canvas.height/2+(s.position.y-e.position.y)*e.zoom),this.gl.uniform1f(this.gl.getUniformLocation(this.programManager.program,`u_lights[${i}].radius`),s.radius*e.zoom),this.gl.uniform1f(this.gl.getUniformLocation(this.programManager.program,`u_lights[${i}].smoothMode`),s.smooth?1:0),this.gl.uniform1f(this.gl.getUniformLocation(this.programManager.program,`u_lights[${i}].intensity`),Math.max(0,Math.min(1,s.intensity)))}return this.gl.drawArrays(this.gl.TRIANGLES,0,6),this.gl.uniform1i(this.programManager.renderLightUniform,0),!0}},wt=class{constructor(t,e,i){this.gl=t,this.programManager=e,this.textureManager=i,this.tiledPosVertices=new Map,this.tiledTexVertices=new Map,this.lastTexture=null,this.projectionMatrix=ct(),this.modelMatrix=ct(),this.textureMatrix=ct(),this.positionBuffer=this.gl.createBuffer(),this.textureBuffer=this.gl.createBuffer(),this.tiledPositionBuffer=this.gl.createBuffer(),this.tiledTextureBuffer=this.gl.createBuffer(),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.positionBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-.5,-.5,-.5,.5,.5,-.5,.5,-.5,-.5,.5,.5,.5]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([0,1,0,0,1,1,1,1,0,0,1,0]),this.gl.STATIC_DRAW),this.lastDrawMode="sprite"}render(t,e,i){var s,r,o,a;i!==Mt.Sprite&&!t.tiled||!t.tiled&&"sprite"!==this.lastDrawMode?(this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.positionBuffer),this.gl.enableVertexAttribArray(this.programManager.positionCoordsAttr),this.gl.vertexAttribPointer(this.programManager.positionCoordsAttr,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureBuffer),this.gl.enableVertexAttribArray(this.programManager.texCoordsAttr),this.gl.vertexAttribPointer(this.programManager.texCoordsAttr,2,this.gl.FLOAT,!1,0,0)):t.tiled&&(this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.tiledPositionBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,this.getTiledPositionVertices(t.tiled),this.gl.STATIC_DRAW),this.gl.enableVertexAttribArray(this.programManager.positionCoordsAttr),this.gl.vertexAttribPointer(this.programManager.positionCoordsAttr,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.tiledTextureBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,this.getTiledTextureVertices(t.tiled),this.gl.STATIC_DRAW),this.gl.enableVertexAttribArray(this.programManager.texCoordsAttr),this.gl.vertexAttribPointer(this.programManager.texCoordsAttr,2,this.gl.FLOAT,!1,0,0)),this.lastDrawMode=t.tiled?"tiled":"sprite",this.modelMatrix=dt(this.modelMatrix),gt(this.modelMatrix,this.modelMatrix,[t.position.x,t.position.y,0]),ut(this.modelMatrix,this.modelMatrix,null!==(s=t.rotation)&&void 0!==s?s:0),mt(this.modelMatrix,this.modelMatrix,[t.width*(t.flipHorizontally?-1:1),t.height*(t.flipVertically?-1:1),1]),this.textureMatrix=dt(this.textureMatrix),t.slice&&(gt(this.textureMatrix,this.textureMatrix,[t.slice.x/t.image.naturalWidth,t.slice.y/t.image.naturalHeight,0]),mt(this.textureMatrix,this.textureMatrix,[t.slice.width/t.image.naturalWidth,t.slice.height/t.image.naturalHeight,1])),yt(this.projectionMatrix,this.gl,e.zoom,e.position),this.gl.uniformMatrix4fv(this.programManager.projectionMatrixUniform,!1,this.projectionMatrix),this.gl.uniformMatrix4fv(this.programManager.modelMatrixUniform,!1,this.modelMatrix),this.gl.uniformMatrix4fv(this.programManager.textureMatrixUniform,!1,this.textureMatrix),this.gl.enable(this.gl.BLEND);const n=this.textureManager.getOrCreateTextureFromImage(t.image,t.smooth);if(this.lastTexture===n&&i===t.type||(this.gl.bindTexture(this.gl.TEXTURE_2D,n),this.gl.uniform1i(this.programManager.textureUniform,0),this.lastTexture=n),this.gl.uniform1i(this.programManager.renderTextureUniform,1),this.gl.uniform1f(this.programManager.alphaUniform,null!==(r=t.opacity)&&void 0!==r?r:1),this.gl.uniform1i(this.programManager.useTintColorUniform,t.tintColor?1:0),t.tintColor){const{r:e,g:i,b:s,a:r}=ft(t.tintColor);this.gl.uniform4f(this.programManager.tintColorUniform,e,i,s,r)}if(this.gl.uniform1i(this.programManager.useMaskColorUniform,t.maskColor?1:0),t.maskColor){const{r:e,g:i,b:s}=ft(t.maskColor);this.gl.uniform4f(this.programManager.maskColorUniform,e,i,s,null!==(o=t.opacity)&&void 0!==o?o:1),this.gl.uniform1f(this.programManager.maskColorMixUniform,null!==(a=t.maskColorMix)&&void 0!==a?a:1)}return t.tiled?this.gl.drawArrays(this.gl.TRIANGLES,0,t.tiled.x*t.tiled.y*6):this.gl.drawArrays(this.gl.TRIANGLES,0,6),!0}getTiledPositionVertices(t){const e=t.toString();if(!this.tiledPosVertices.has(e)){const i=[];for(let e=-t.x/2;e<t.x/2;e++)for(let s=-t.y/2;s<t.y/2;s++)i.push(e,s,e,s+1,e+1,s,e+1,s,e,s+1,e+1,s+1);this.tiledPosVertices.set(e,new Float32Array(i))}return this.tiledPosVertices.get(e)}getTiledTextureVertices(t){const e=t.toString();if(!this.tiledTexVertices.has(e)){const i=[];for(let e=0;e<t.x*t.y;e++)i.push(0,1,0,0,1,1,1,1,0,0,1,0);this.tiledTexVertices.set(e,new Float32Array(i))}return this.tiledTexVertices.get(e)}};var Et;!function(t){t[t.Center=0]="Center",t[t.RightUp=1]="RightUp",t[t.RightDown=2]="RightDown",t[t.RightCenter=3]="RightCenter"}(Et||(Et={}));let _t=class{constructor(t,e,i,s){this.gl=t,this.programManager=e,this.textureManager=i,this.fontAtlasFactory=s,this.type=Mt.Text,this.posVertices=[],this.texVertices=[],this.lastTexture=null,this.textSize=new n,this.modelPosition=new n,this.shadowPosition=new n,this.projectionMatrix=ct(),this.modelMatrix=ct(),this.textureMatrix=ct(),this.positionBuffer=this.gl.createBuffer(),this.textureBuffer=this.gl.createBuffer()}render(t,e,i,s=!1){var r;if(!t.text)return!1;const o=this.fontAtlasFactory.getOrCreate(Object.assign({font:t.font},t.textureAtlas));if(s||(this.generateTextVertices(o,t),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.positionBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array(this.posVertices),this.gl.DYNAMIC_DRAW),this.gl.enableVertexAttribArray(this.programManager.positionCoordsAttr),this.gl.vertexAttribPointer(this.programManager.positionCoordsAttr,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array(this.texVertices),this.gl.DYNAMIC_DRAW),this.gl.enableVertexAttribArray(this.programManager.texCoordsAttr),this.gl.vertexAttribPointer(this.programManager.texCoordsAttr,2,this.gl.FLOAT,!1,0,0)),t.shadow){const{color:s,offset:r,opacity:o}=t.shadow,a=Object.assign(Object.assign({},t),{color:s,opacity:o,position:n.add(this.shadowPosition,t.position,r)});a.shadow=void 0,this.render(a,e,i,!0),i=Mt.Text}this.modelMatrix=dt(this.modelMatrix),this.setPositionFromOrientation(t),gt(this.modelMatrix,this.modelMatrix,[this.modelPosition.x,this.modelPosition.y,0]),ut(this.modelMatrix,this.modelMatrix,null!==(r=t.rotation)&&void 0!==r?r:0),mt(this.modelMatrix,this.modelMatrix,[t.fontSize*(t.flipHorizontally?-1:1),t.fontSize*(t.flipVertically?-1:1),1]),this.textureMatrix=dt(this.textureMatrix),yt(this.projectionMatrix,this.gl,e.zoom,e.position),this.gl.uniformMatrix4fv(this.programManager.projectionMatrixUniform,!1,this.projectionMatrix),this.gl.uniformMatrix4fv(this.programManager.modelMatrixUniform,!1,this.modelMatrix),this.gl.uniformMatrix4fv(this.programManager.textureMatrixUniform,!1,this.textureMatrix),this.gl.enable(this.gl.BLEND);const a=this.textureManager.getOrCreateTextureFromCanvas(o.id,o.canvas,t.smooth);this.lastTexture===a&&i===Mt.Text||(this.gl.bindTexture(this.gl.TEXTURE_2D,a),this.gl.uniform1i(this.programManager.textureUniform,0),this.lastTexture=a),this.gl.uniform1i(this.programManager.useMaskColorUniform,0),this.gl.uniform1i(this.programManager.renderTextureUniform,1),this.gl.uniform1f(this.programManager.alphaUniform,t.opacity);const{r:h,g:l,b:c,a:d}=ft(t.color);return this.gl.uniform1i(this.programManager.useTintColorUniform,1),this.gl.uniform4f(this.programManager.tintColorUniform,h,l,c,d),this.gl.drawArrays(this.gl.TRIANGLES,0,this.posVertices.length/2),!0}generateTextVertices(t,{text:e,fontSize:i,letterSpacing:s,lineHeight:r}){this.posVertices=[],this.texVertices=[];let o=0,a=0,n=0;s/=i,r/=i;for(let i=0;i<e.length;i++){const h=e[i];if("\n"===h){n=Math.max(n,o),o=0,a-=r;continue}const l=t.glyphs.get(h);if(l){const e=l.width/t.fontSize;this.posVertices.push(o,a-1,o+e,a-1,o,a,o,a,o+e,a-1,o+e,a);const i=l.id%t.gridSize*(t.fontSize+t.spacing),r=(l.id/t.gridSize|0)*(t.fontSize+t.spacing),n=i/t.canvas.width,h=r/t.canvas.height,c=(i+l.width)/t.canvas.width,d=(r+t.fontSize)/t.canvas.height;this.texVertices.push(n,d,c,d,n,h,n,h,c,d,c,h),o+=e+s}}this.textSize.set(Math.max(n,o)*i,Math.abs(a-1)*i)}setPositionFromOrientation(t){this.modelPosition.set(t.position.x+(t.orientation===Et.Center?-this.textSize.x/2:0),t.position.y+(t.orientation===Et.Center||t.orientation===Et.RightCenter?this.textSize.y/2:t.orientation===Et.RightUp?this.textSize.y:0))}};var Rt;!function(t){t[t.Center=0]="Center",t[t.RightUp=1]="RightUp",t[t.RightDown=2]="RightDown",t[t.RightCenter=3]="RightCenter"}(Rt||(Rt={}));let Tt=class{constructor(t,e,i){this.gl=t,this.programManager=e,this.textureManager=i,this.posVertices=[],this.texVertices=[],this.lastTexture=null,this.tileset={width:0,tileWidth:0,tileHeight:0,texMargin:new n,texSpacing:new n,texWidth:0,texHeight:0,texCorrection:new n},this.projectionMatrix=ct(),this.modelMatrix=ct(),this.textureMatrix=ct(),this.positionBuffer=this.gl.createBuffer(),this.textureBuffer=this.gl.createBuffer()}render(t,e,i){var s,r,o,a;if(0===t.tiles.reduce(((t,e)=>t+e),0))return!1;if(this.processTileset(t),this.generateVertices(t),0===this.posVertices.length)return!1;this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.positionBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array(this.posVertices),this.gl.DYNAMIC_DRAW),this.gl.enableVertexAttribArray(this.programManager.positionCoordsAttr),this.gl.vertexAttribPointer(this.programManager.positionCoordsAttr,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array(this.texVertices),this.gl.DYNAMIC_DRAW),this.gl.enableVertexAttribArray(this.programManager.texCoordsAttr),this.gl.vertexAttribPointer(this.programManager.texCoordsAttr,2,this.gl.FLOAT,!1,0,0),this.modelMatrix=dt(this.modelMatrix),gt(this.modelMatrix,this.modelMatrix,[t.position.x,t.position.y,0]),ut(this.modelMatrix,this.modelMatrix,null!==(s=t.rotation)&&void 0!==s?s:0),mt(this.modelMatrix,this.modelMatrix,[t.tilemap.tileWidth*(t.flipHorizontal?-1:1),t.tilemap.tileHeight*(t.flipVertical?-1:1),1]),this.textureMatrix=dt(this.textureMatrix),mt(this.textureMatrix,this.textureMatrix,[this.tileset.tileWidth/t.tileset.image.naturalWidth,this.tileset.tileHeight/t.tileset.image.naturalHeight,1]),yt(this.projectionMatrix,this.gl,e.zoom,e.position),this.gl.uniformMatrix4fv(this.programManager.projectionMatrixUniform,!1,this.projectionMatrix),this.gl.uniformMatrix4fv(this.programManager.modelMatrixUniform,!1,this.modelMatrix),this.gl.uniformMatrix4fv(this.programManager.textureMatrixUniform,!1,this.textureMatrix),this.gl.enable(this.gl.BLEND);const n=this.textureManager.getOrCreateTextureFromImage(t.tileset.image,t.smooth);if(this.lastTexture===n&&i===Mt.Tilemap||(this.gl.bindTexture(this.gl.TEXTURE_2D,n),this.gl.uniform1i(this.programManager.textureUniform,0),this.lastTexture=n),this.gl.uniform1i(this.programManager.renderTextureUniform,1),this.gl.uniform1f(this.programManager.alphaUniform,null!==(r=t.opacity)&&void 0!==r?r:1),this.gl.uniform1i(this.programManager.useTintColorUniform,t.tintColor?1:0),t.tintColor){const{r:e,g:i,b:s,a:r}=ft(t.tintColor);this.gl.uniform4f(this.programManager.tintColorUniform,e,i,s,r)}if(this.gl.uniform1i(this.programManager.useMaskColorUniform,t.maskColor?1:0),t.maskColor){const{r:e,g:i,b:s}=ft(t.maskColor);this.gl.uniform4f(this.programManager.maskColorUniform,e,i,s,null!==(o=t.opacity)&&void 0!==o?o:1),this.gl.uniform1f(this.programManager.maskColorMixUniform,null!==(a=t.maskColorMix)&&void 0!==a?a:1)}return this.gl.drawArrays(this.gl.TRIANGLES,0,this.posVertices.length/2),!0}processTileset({tileset:t}){var e,i,s,r,o,a,h;t.margin=null!==(e=t.margin)&&void 0!==e?e:new n,t.spacing=null!==(i=t.spacing)&&void 0!==i?i:new n,t.correction=null!==(s=t.correction)&&void 0!==s?s:new n,this.tileset.width=t.width,this.tileset.tileWidth=t.tileWidth+(null!==(r=t.margin.x)&&void 0!==r?r:0)+(null!==(o=t.spacing.x)&&void 0!==o?o:0),this.tileset.tileHeight=t.tileHeight+(null!==(a=t.margin.y)&&void 0!==a?a:0)+(null!==(h=t.spacing.y)&&void 0!==h?h:0),this.tileset.texMargin.set(t.margin.x/this.tileset.tileWidth,t.margin.y/this.tileset.tileHeight),this.tileset.texSpacing.set(t.spacing.x/this.tileset.tileWidth,t.spacing.y/this.tileset.tileHeight),this.tileset.texCorrection.set(t.correction.x/this.tileset.tileWidth,t.correction.y/this.tileset.tileHeight),this.tileset.texWidth=1-this.tileset.texMargin.x-this.tileset.texSpacing.x-2*this.tileset.texCorrection.x,this.tileset.texHeight=1-this.tileset.texMargin.y-this.tileset.texSpacing.y-2*this.tileset.texCorrection.y}generateVertices({tiles:t,tilemap:e}){this.posVertices=[],this.texVertices=[];const i=Math.floor(t.length/e.width);t.forEach(((t,s)=>{if(0===t)return;const r=s%e.width-e.width/2,o=i/2-Math.floor(s/e.width);this.posVertices.push(r,o-1,r+1,o-1,r,o,r,o,r+1,o-1,r+1,o);const a=(t-1)%this.tileset.width+this.tileset.texMargin.x+this.tileset.texCorrection.x,n=Math.floor((t-1)/this.tileset.width)+this.tileset.texMargin.y+this.tileset.texCorrection.y;this.texVertices.push(a,n+this.tileset.texHeight,a+this.tileset.texWidth,n+this.tileset.texHeight,a,n,a,n,a+this.tileset.texWidth,n+this.tileset.texHeight,a+this.tileset.texWidth,n)}))}},Bt=class{constructor(t,e,i){this.gl=t,this.programManager=e,this.textureManager=i,this.lastTexture=null,this.projectionMatrix=ct(),this.modelMatrix=ct(),this.textureMatrix=ct(),this.positionBuffer=this.gl.createBuffer(),this.textureBuffer=this.gl.createBuffer(),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.positionBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-.5,-.5,-.5,.5,.5,-.5,.5,-.5,-.5,.5,.5,.5]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([0,1,0,0,1,1,1,1,0,0,1,0]),this.gl.STATIC_DRAW)}render(t,e,i){var s,r,o,a;i!==Mt.Video&&(this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.positionBuffer),this.gl.enableVertexAttribArray(this.programManager.positionCoordsAttr),this.gl.vertexAttribPointer(this.programManager.positionCoordsAttr,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureBuffer),this.gl.enableVertexAttribArray(this.programManager.texCoordsAttr),this.gl.vertexAttribPointer(this.programManager.texCoordsAttr,2,this.gl.FLOAT,!1,0,0)),this.modelMatrix=dt(this.modelMatrix),gt(this.modelMatrix,this.modelMatrix,[t.position.x,t.position.y,0]),ut(this.modelMatrix,this.modelMatrix,null!==(s=t.rotation)&&void 0!==s?s:0),mt(this.modelMatrix,this.modelMatrix,[t.width*(t.flipHorizontal?-1:1),t.height*(t.flipVertical?-1:1),1]),this.textureMatrix=dt(this.textureMatrix),t.slice&&(gt(this.textureMatrix,this.textureMatrix,[t.slice.x/t.video.videoWidth,t.slice.y/t.video.videoHeight,0]),mt(this.textureMatrix,this.textureMatrix,[t.slice.width/t.video.videoWidth,t.slice.height/t.video.videoHeight,1])),yt(this.projectionMatrix,this.gl,e.zoom,e.position),this.gl.uniformMatrix4fv(this.programManager.projectionMatrixUniform,!1,this.projectionMatrix),this.gl.uniformMatrix4fv(this.programManager.modelMatrixUniform,!1,this.modelMatrix),this.gl.uniformMatrix4fv(this.programManager.textureMatrixUniform,!1,this.textureMatrix),this.gl.enable(this.gl.BLEND);const n=this.textureManager.getOrCreateTextureFromVideo(t.video);if(this.lastTexture===n&&i===Mt.Video||(this.gl.bindTexture(this.gl.TEXTURE_2D,n),this.gl.uniform1i(this.programManager.textureUniform,0),this.lastTexture=n),t.video.readyState>=HTMLMediaElement.HAVE_CURRENT_DATA&&this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,t.video),this.gl.uniform1i(this.programManager.renderTextureUniform,1),this.gl.uniform1f(this.programManager.alphaUniform,null!==(r=t.opacity)&&void 0!==r?r:1),this.gl.uniform1i(this.programManager.useTintColorUniform,t.tintColor?1:0),t.tintColor){const{r:e,g:i,b:s,a:r}=ft(t.tintColor);this.gl.uniform4f(this.programManager.tintColorUniform,e,i,s,r)}if(this.gl.uniform1i(this.programManager.useMaskColorUniform,t.maskColor?1:0),t.maskColor){const{r:e,g:i,b:s}=ft(t.maskColor);this.gl.uniform4f(this.programManager.maskColorUniform,e,i,s,null!==(o=t.opacity)&&void 0!==o?o:1),this.gl.uniform1f(this.programManager.maskColorMixUniform,null!==(a=t.maskColorMix)&&void 0!==a?a:1)}return this.gl.drawArrays(this.gl.TRIANGLES,0,6),!0}};class Pt{constructor(t){this.gl=t}createFromImage(t,e=!1,i=null){return i=null!=i?i:this.gl.createTexture(),t.naturalWidth?this.createFromSource(t,i,e):t.addEventListener("load",(()=>this.createFromSource(t,i,e))),i}createFromCanvas(t,e=!1,i=null){return i=null!=i?i:this.gl.createTexture(),this.createFromSource(t,i,e),i}createPixelTexture(){const t=this.gl.createTexture();return this.gl.bindTexture(this.gl.TEXTURE_2D,t),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,1,1,0,this.gl.RGBA,this.gl.UNSIGNED_BYTE,new Uint8Array([0,0,0,255])),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.bindTexture(this.gl.TEXTURE_2D,null),t}createFromSource(t,e,i=!1){this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,t),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),i?(this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR)):(this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.NEAREST),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.NEAREST)),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}}const Dt=(t,e)=>`${e?"_smooth_":""}${t}`;class Ft{constructor(t){this.textureFactory=t,this.textures=new Map}getOrCreateTextureFromImage(t,e=!1){var i;return null!==(i=this.textures.get(Dt(t.src,e)))&&void 0!==i?i:this.createTextureFromImage(t,e)}createTextureFromImage(t,e=!1){const i=this.textureFactory.createFromImage(t,e);return this.textures.set(Dt(t.src,e),i),i}getOrCreateTextureFromCanvas(t,e,i=!1){var s;return null!==(s=this.textures.get(Dt(t,i)))&&void 0!==s?s:this.createTextureFromCanvas(t,e,i)}createTextureFromCanvas(t,e,i=!1){const s=this.textureFactory.createFromCanvas(e,i);return this.textures.set(Dt(t,i),s),s}getOrCreateTextureFromVideo(t){var e;return null!==(e=this.textures.get(t.src))&&void 0!==e?e:this.createTextureFromVideo(t)}createTextureFromVideo(t){const e=this.textureFactory.createPixelTexture();return this.textures.set(t.src,e),e}}let Ut=class{constructor(t){this.renderers=new Map;const e=new st(t),i=e.gl,s=e.contextVersion,r=new nt(i,s,new at(i,new ht(i))),o=new Ft(new Pt(i)),a=new rt;this.renderers.set(Mt.Sprite,new wt(i,r,o)),this.renderers.set(Mt.Text,new _t(i,r,o,a)),this.renderers.set(Mt.Tilemap,new Tt(i,r,o)),this.renderers.set(Mt.Geometric,new Ct(i,r)),this.renderers.set(Mt.Mask,new St(i,r)),this.renderers.set(Mt.Video,new Bt(i,r,o)),this.renderers.set(Mt.Shadow,new At(i,r)),this.canvasColorRenderer=new xt(i),r.loadProgram()}render(t,e){this.renderers.get(t.type).render(t,e,this.lastRender)&&(this.lastRender=t.type)}renderCanvasColor(t){this.canvasColorRenderer.render(t)}};Ut=o([i(t.WebGLManager),a(0,s(t.CanvasElement))],Ut);class It{constructor(t){this.fixedToTimeScale=!1,this.layer=Z,this.loop=!1,this.offset=new n,this.playing=!1,this.rotation=0,this.volume=1,this._currentVideoSrc=void 0,this._playPromisePendind=!1,this._renderData={type:Mt.Video,height:void 0,layer:void 0,position:new n,video:void 0,width:void 0,flipHorizontal:void 0,flipVertical:void 0,maskColor:void 0,maskColorMix:void 0,opacity:void 0,rotation:void 0,slice:void 0,tintColor:void 0},Object.assign(this,t)}play(t){t&&(this.video=t),this.action="play"}pause(){this.action="pause"}stop(){this.action="stop"}}const Lt=["click","contextmenu","auxclick","dblclick","mousedown","mouseup","pointerup","touchend","keydown","keyup"];let jt=class{constructor(t,e,i){this.entityManager=t,this.renderManager=e,this.timeManager=i,this.scaledOffset=new n,this.canPlay=!0,this.userInputErrorCatched=!1,this.userInputEventHandler=()=>{Lt.forEach((t=>{window.removeEventListener(t,this.userInputEventHandler)})),this.canPlay=!0}}onCreate(){document.addEventListener("visibilitychange",(()=>{this.entityManager.search(It).forEach((({component:{video:t,playing:e}})=>{document.hidden&&t?t.pause():!document.hidden&&t&&e&&t.play()}))}))}catchUserInput(){this.canPlay=!1,this.userInputErrorCatched=!0,Lt.forEach((t=>window.addEventListener(t,this.userInputEventHandler)))}onUpdate(){this.entityManager.search(It).forEach((({entity:t,component:e})=>{var i,s;const r=this.entityManager.getComponent(t,J);if(!r)throw new Error("VideoRenderer component needs a Transform");e.video&&e.video.duration&&(this.checkVideoState(e),this.scaledOffset.set(e.offset.x*r.localScale.x,e.offset.y*r.localScale.y),n.add(e._renderData.position,r.localPosition,this.scaledOffset),e._renderData.layer=e.layer,e._renderData.video=e.video,e._renderData.width=(null!==(i=e.width)&&void 0!==i?i:e.video.videoWidth)*Math.abs(r.localScale.x),e._renderData.height=(null!==(s=e.height)&&void 0!==s?s:e.video.videoHeight)*Math.abs(r.localScale.y),e._renderData.rotation=r.localRotation+e.rotation,e._renderData.slice=e.slice,e._renderData.flipHorizontal=e.flipHorizontally,e._renderData.flipVertical=e.flipVertically,e._renderData.opacity=e.opacity,e._renderData.maskColor=e.maskColor,e._renderData.maskColorMix=e.maskColorMix,e._renderData.tintColor=e.tintColor,0!==r.localRotation&&this.scaledOffset.magnitude>0&&this.translateRenderPosition(e._renderData,r),this.renderManager.addRenderData(e._renderData))}))}translateRenderPosition(t,e){const i=Math.atan2(this.scaledOffset.y,this.scaledOffset.x)+e.localRotation;t.position.set(e.localPosition.x+this.scaledOffset.magnitude*Math.cos(i),e.localPosition.y+this.scaledOffset.magnitude*Math.sin(i))}checkVideoState(t){const{video:e,action:i,loop:s,volume:r}=t;e.src!==t._currentVideoSrc&&(t._currentVideoSrc=e.src,t.playing=!1,e.currentTime=0),e.loop=s,e.volume=r,e.playbackRate=t.fixedToTimeScale?this.timeManager.timeScale<.0625?0:Math.min(this.timeManager.timeScale,16):1,"play"!==i||t.playing||t._playPromisePendind||!this.canPlay||(t._playPromisePendind=!0,e.play().then((()=>{t._playPromisePendind=!1,t.playing=!0})).catch((()=>{t._playPromisePendind=!1,this.userInputErrorCatched||this.catchUserInput()}))),"play"===i&&e.ended&&(t.action="stop",t.playing=!1),"stop"===i&&e.currentTime>0&&(e.pause(),e.currentTime=0,t.playing=!1),"pause"!==i||e.paused||e.pause()}onDisabled(){this.entityManager.search(It).forEach((({component:t})=>{t.video&&(t.video.pause(),t.video.currentTime=0)}))}onDestroy(){this.onDisabled()}};jt=o([i(W.VideoRendererSystem),a(0,s(t.EntityManager)),a(1,s(t.RenderManager)),a(2,s(t.TimeManager))],jt);class Ot{constructor(t,e){this.entityManager=t,this.assetManager=e,this.systems=[]}loadSystems(){}loadAssets(){}setup(){}}let kt=class{constructor(t,e,i,s,r){this.systemManager=t,this.systemFactory=e,this.entityManager=i,this.assetManager=s,this.timeManager=r,this.scenes=new Map,this._loadingScene=!1,this._sceneLoadedThisFrame=!1}addScene(t,e,i=!1){const s=new t(this.entityManager,this.assetManager);this.scenes.set(e,s),i&&(this.openingSceneName=e)}loadScene(t){if(!this.scenes.has(t))throw new Error(`Invalid scene name: '${t}'`);this.sceneNameToBeLoaded=t}loadOpeningScene(){if(!this.openingSceneName)throw new Error("There is no opening scene");this.sceneNameToBeLoaded=this.openingSceneName}get loadingScene(){return this._loadingScene}get sceneLoadedThisFrame(){return this._sceneLoadedThisFrame}update(){this._sceneLoadedThisFrame=!1,this.sceneNameToBeLoaded&&(this.currentSceneName&&this.destroyCurrentScene(),this.currentSceneName=this.sceneNameToBeLoaded,this.sceneNameToBeLoaded=void 0,this.scenes.get(this.currentSceneName).loadAssets(),this.scenes.get(this.currentSceneName).loadSystems(),this._loadingScene=!0),this._loadingScene&&this.assetManager.getAssetsLoaded()&&(this._loadingScene=!1,this._sceneLoadedThisFrame=!0,this.scenes.get(this.currentSceneName).setup(),this.systemManager.update(X.Transform),this.systemManager.update(X.PreGameLogic),this.scenes.get(this.currentSceneName).systems.forEach(((t,e)=>{this.systemFactory.createSystemIfNotExists(t),this.systemManager.enableSystem(t),this.systemManager.setExecutionOrder(t,e)})))}destroyCurrentScene(){this.systemManager.disableSystem(Y),this.systemManager.disableSystem(jt),this.scenes.get(this.currentSceneName).systems.forEach((t=>this.systemManager.disableSystem(t))),this.entityManager.removeAllEntities(),this.timeManager.clearAllIntervals(),this.systemManager.enableSystem(Y),this.systemManager.enableSystem(jt)}};kt=o([i(t.SceneManager),a(0,s(t.SystemManager)),a(1,s(t.CreateSystemService)),a(2,s(t.EntityManager)),a(3,s(t.AssetManager)),a(4,s(t.TimeManager))],kt);class Vt{constructor(t){this.width=0,this.height=0,this.radius=0,this.touchEnabled=!0,this.offset=new n,this.pressed=!1,this.mouseOver=!1,Object.assign(this,t)}}var Gt;!function(t){t[t.Rectangle=0]="Rectangle",t[t.Circumference=1]="Circumference"}(Gt||(Gt={}));let zt=class{constructor(t,e){this.entityManager=t,this.scaled={position:new n,width:0,height:0,radius:0},this.distance=new n,this.pressedLastFrame=!1,this.mouse=e.mouse,this.touchScreen=e.touchScreen}onUpdate(){this.entityManager.search(Vt).forEach((({entity:t,component:e})=>{const i=this.entityManager.getComponent(t,J);if(!i)throw new Error("Button component needs a Transform");this.pressedLastFrame=e.pressed,e.pressed=!1,this.scale(e,i),e.mouseOver=this.isMouseOverButton(e),e.pressed=e.mouseOver&&this.mouse.leftButtonPressed,e.touchEnabled&&this.touchScreen.touching&&(this.resolveTouchAndRectangle(e),this.resolveTouchAndCircumference(e)),e.onClick&&!this.pressedLastFrame&&e.pressed&&e.onClick(),e.onPressed&&e.pressed&&e.onPressed()}))}scale(t,{localPosition:e,localScale:i}){this.scaled.width=t.width*i.x,this.scaled.height=t.height*i.y,this.scaled.position.x=e.x+t.offset.x*i.x,this.scaled.position.y=e.y+t.offset.y*i.y,this.scaled.radius=t.radius*Math.max(Math.abs(i.x),Math.abs(i.y))}isMouseOverButton(t){return this.isMouseOverRectangleButton(t)||this.isMouseOverCircumferenceButton(t)}isMouseOverRectangleButton(t){return t.shape===Gt.Rectangle&&(u(this.mouse.positionInViewport.x,this.scaled.position.x-this.scaled.width/2,this.scaled.position.x+this.scaled.width/2)&&u(this.mouse.positionInViewport.y,this.scaled.position.y-this.scaled.height/2,this.scaled.position.y+this.scaled.height/2))}isMouseOverCircumferenceButton(t){return t.shape===Gt.Circumference&&(n.subtract(this.distance,this.scaled.position,this.mouse.positionInViewport),this.distance.magnitude<=this.scaled.radius)}resolveTouchAndRectangle(t){if(t.shape===Gt.Rectangle)for(const{positionInViewport:e,radius:i}of this.touchScreen.interactions){if(t.pressed)return;t.pressed=this.scaled.position.x+this.scaled.width/2>=e.x-i.x&&this.scaled.position.x-this.scaled.width/2<=e.x+i.x&&this.scaled.position.y+this.scaled.height/2>=e.y-i.y&&this.scaled.position.y-this.scaled.height/2<=e.y+i.y}}resolveTouchAndCircumference(t){if(t.shape===Gt.Circumference)for(const{positionInViewport:e,radius:i}of this.touchScreen.interactions){if(t.pressed)return;n.subtract(this.distance,this.scaled.position,e),t.pressed=this.distance.magnitude<=this.scaled.radius+Math.max(i.x,i.y)}}};zt=o([i(W.ButtonSystem),a(0,s(t.EntityManager)),a(1,s(t.InputManager))],zt);class Nt{constructor(t){Object.assign(this,t)}}class Wt{constructor(t){this.layer=Z,this.tileset=void 0,this.data=[],this.chunks=[],this.width=0,this.height=0,this.tileWidth=void 0,this.tileHeight=void 0,this.tintColor=void 0,this.opacity=1,this.smooth=!1,this._processed=!1,this._renderData=[],Object.assign(this,t)}}let Ht=class{constructor(t){this.entityManager=t}onUpdate(){this.entityManager.search(Nt).forEach((({entity:t,component:e})=>{const i=this.entityManager.getComponent(t,Wt);if(!i)return;const s=e.tilemap.layers.find((t=>t.name===e.layerToRender&&"tilelayer"===t.type));s&&(e.tilemap.infinite?i.chunks=s.chunks:i.data=s.data,i.width=e.tilemap.width)}))}};Ht=o([i(W.TiledWrapperSystem),a(0,s(t.EntityManager))],Ht);const Yt=16;let Xt=class{constructor(t){this.entityManager=t}onUpdate(){this.entityManager.search(Wt).forEach((({component:t})=>{var e,i;t._processed||(t.chunks&&t.chunks.length>0?this.chunksToData(t):t.data&&t.data.length>0&&this.dataToChunks(t),t.tileWidth=null!==(e=t.tileWidth)&&void 0!==e?e:t.tileset.tileWidth,t.tileHeight=null!==(i=t.tileHeight)&&void 0!==i?i:t.tileset.tileHeight,t._processed=!0)}))}dataToChunks(t){t.height=Math.ceil(t.data.length/t.width);const e=Math.ceil(t.width/Yt),i=Math.ceil(t.height/Yt);for(let s=0;s<i;s++)for(let i=0;i<e;i++){const e={x:i*Yt,y:s*Yt,width:Yt,height:Yt,data:[]};for(let i=0;i<e.width*e.height;i++){const s=e.x+i%e.width,r=t.width*(e.y+Math.floor(i/e.width));e.data[i]=s<t.width&&r<t.height*t.width?t.data[r+s]:0}t.chunks.push(e)}}chunksToData(t){t.data=[],t.chunks.forEach((e=>e.data.forEach(((i,s)=>{t.data[t.width*(e.y+Math.floor(s/e.width))+e.x+s%e.width]=i})))),t.height=Math.ceil(t.data.length/t.width)}};Xt=o([i(W.TilemapPreProcessingSystem),a(0,s(t.EntityManager))],Xt);let $t=class{constructor(t){this.entityManager=t}onUpdate(){this.entityManager.search(J).sort(((t,e)=>this.getBranchLength(t.entity)-this.getBranchLength(e.entity))).forEach((({component:t,entity:e})=>{const i=this.entityManager.getParent(e);i&&this.entityManager.isEntityEnabled(i)&&this.entityManager.isComponentEnabled(i,J)?(t._parent||(t._parent=this.entityManager.getComponent(i,J),t._awake&&n.subtract(t.position,t.localPosition,t._parent.position)),t._parent?this.translateChild(t):this.updateTransform(t)):(t._parent&&this.removeParent(t),this.updateTransform(t)),t._awake=!0}))}getBranchLength(t){const e=this.entityManager.getParent(t);return e?1+this.getBranchLength(e):0}removeParent(t){t._parent=void 0,t.position.copy(t.localPosition),t.rotation=t.localRotation}updateTransform(t){t.localPosition.copy(t.position),t.localScale.copy(t.scale),t.localRotation=t.rotation,t._parent=void 0}translateChild(t){t.localRotation=t.rotation+t._parent.localRotation,t.localScale.x=t.scale.x*t._parent.scale.x,t.localScale.y=t.scale.y*t._parent.scale.y;const e=Math.atan2(t.position.y,t.position.x)+t._parent.localRotation;t.localPosition.set(t._parent.localPosition.x+t.position.magnitude*Math.cos(e),t._parent.localPosition.y+t.position.magnitude*Math.sin(e))}};$t=o([i(W.TransformSystem),a(0,s(t.EntityManager))],$t);let Kt=class{constructor(t){this.inputManager=t,this.gamepads=new Map,this.eventHandler=t=>{"gamepadconnected"===t.type?this.gamepadConnected(t.gamepad):"gamepaddisconnected"===t.type&&this.gamepadDisconected(t.gamepad)},window.addEventListener("gamepadconnected",this.eventHandler),window.addEventListener("gamepaddisconnected",this.eventHandler)}gamepadConnected(t){this.gamepads.set(t.index,t),this.inputManager.gamepads[t.index]||(this.inputManager.gamepads[t.index]=new U,this.inputManager.gamepads[t.index].index=t.index),this.inputManager.gamepads[t.index].id=t.id,this.inputManager.gamepads[t.index].connected=!0}gamepadDisconected(t){this.gamepads.delete(t.index),this.inputManager.gamepads[t.index].connected=!1}onUpdate(){for(const t of this.getGamepadsFromBrowser())t&&(!1===this.gamepads.has(t.index)?this.gamepadConnected(t):this.gamepads.set(t.index,t));this.gamepads.forEach((t=>{const e=this.inputManager.gamepads[t.index];t.buttons.forEach(((t,i)=>e.buttons.set(i,t.pressed))),t.axes.forEach(((t,i)=>e.axes.set(i,t))),e.vibrationInput&&(t.vibrationActuator.playEffect(t.vibrationActuator.type,{duration:e.vibrationInput.duration,weakMagnitude:e.vibrationInput.weakMagnitude,strongMagnitude:e.vibrationInput.strongMagnitude,startDelay:e.vibrationInput.startDelay}).catch((()=>e.vibrating=!1)).finally((()=>e.vibrating=!1)),e.vibrating=!0,e.vibrationInput=void 0)}))}getGamepadsFromBrowser(){return navigator.getGamepads?navigator.getGamepads():navigator.webkitGetGamepads?navigator.webkitGetGamepads:[]}};Kt=o([i(W.GamepadSystem),a(0,s(t.InputManager))],Kt);let qt=class{constructor(t,{keyboard:e}){this.pressedKeys=[],this.eventHandler=t=>{"keydown"!==t.type||this.pressedKeys.includes(t.code)||this.pressedKeys.push(t.code),"keyup"===t.type&&this.pressedKeys.includes(t.code)&&this.pressedKeys.splice(this.pressedKeys.indexOf(t.code),1)},this.keyboard=e,t.addEventListener("keydown",this.eventHandler),t.addEventListener("keyup",this.eventHandler),t.addEventListener("focusout",(()=>this.pressedKeys=[]))}onUpdate(){this.keyboard.pressedKeys=[...this.pressedKeys]}};qt=o([i(W.KeyboardSystem),a(0,s(t.CanvasElement)),a(1,s(t.InputManager))],qt);let Qt=class{constructor(t,{mouse:e}){this.canvas=t,this.leftButtonPressed=!1,this.scrollButtonPressed=!1,this.rightButtonPressed=!1,this.positionInViewport=new n,this.lastPositionInViewport=new n,this.mouse=e,this.canvas.addEventListener("mousemove",(t=>this.updatePosition(t))),this.canvas.addEventListener("mousedown",(t=>this.updateButtonDown(t))),this.canvas.addEventListener("mouseup",(t=>this.updateButtonUp(t))),this.canvas.addEventListener("wheel",(t=>this.handleWheelEvent(t))),this.canvas.addEventListener("focusout",(()=>this.onFocusOut()))}updateButtonDown(t){this.canvas.focus(),t.preventDefault(),t.stopPropagation(),this.leftButtonPressed=0===t.button,this.scrollButtonPressed=1===t.button,this.rightButtonPressed=2===t.button}updateButtonUp(t){t.preventDefault(),t.stopPropagation(),this.leftButtonPressed=0!==t.button&&this.leftButtonPressed,this.scrollButtonPressed=1!==t.button&&this.scrollButtonPressed,this.rightButtonPressed=2!==t.button&&this.rightButtonPressed}updatePosition(t){t.preventDefault(),t.stopPropagation(),this.positionInViewport.set(t.offsetX/(this.canvas.clientWidth/this.canvas.width)-this.canvas.width/2,-t.offsetY/(this.canvas.clientHeight/this.canvas.height)+this.canvas.height/2)}handleWheelEvent(t){t.preventDefault(),t.stopPropagation(),this.wheelEvent=t}onFocusOut(){this.leftButtonPressed=!1,this.scrollButtonPressed=!1,this.rightButtonPressed=!1}onUpdate(){this.mouse.leftButtonPressed=this.leftButtonPressed,this.mouse.rightButtonPressed=this.rightButtonPressed,this.mouse.scrollButtonPressed=this.scrollButtonPressed,this.mouse.positionInViewport.copy(this.positionInViewport),this.positionInViewport.equals(this.lastPositionInViewport)?this.mouse.hasMoved=!1:(this.mouse.hasMoved=!0,this.lastPositionInViewport.copy(this.positionInViewport)),this.wheelEvent?(this.mouse.wheelScroll.set(this.wheelEvent.deltaX,this.wheelEvent.deltaY),this.wheelEvent=void 0):this.mouse.wheelScroll.set(0,0)}};Qt=o([i(W.MouseSystem),a(0,s(t.CanvasElement)),a(1,s(t.InputManager))],Qt);let Jt=class{constructor(t,{touchScreen:e}){this.canvas=t,this.touching=!1,this.interactions=[],this.eventHandler=t=>{"touchstart"===t.type&&(this.touching=!0,this.updatePosition(t)),"touchmove"===t.type&&this.updatePosition(t),"touchend"!==t.type&&"touchcancel"!==t.type||(this.touching=!1)},this.touchScreen=e,this.canvas.addEventListener("touchstart",this.eventHandler),this.canvas.addEventListener("touchend",this.eventHandler),this.canvas.addEventListener("touchcancel",this.eventHandler),this.canvas.addEventListener("touchmove",this.eventHandler)}updatePosition(t){if(t.preventDefault(),t.stopPropagation(),this.interactions=[],0!==t.targetTouches.length)for(let e=0;e<t.targetTouches.length;e++)this.interactions[e]={positionInViewport:new n((t.targetTouches[e].clientX-this.canvas.offsetLeft)/(this.canvas.clientWidth/this.canvas.width)-this.canvas.width/2,-(t.targetTouches[e].clientY-this.canvas.offsetTop)/(this.canvas.clientHeight/this.canvas.height)+this.canvas.height/2),radius:new n(t.targetTouches[e].radiusX,t.targetTouches[e].radiusY)}}onUpdate(){this.touchScreen.touching=this.touching,this.touchScreen.interactions=[...this.touchScreen.interactions]}};Jt=o([i(W.TouchScreenSystem),a(0,s(t.CanvasElement)),a(1,s(t.InputManager))],Jt);class Zt{constructor(t){this.animations=new Map,this.speed=1,this.reset=!1,this.playing=!1,this.currentFrame=0,this.currentTime=0,this._currentAnimation=void 0,Object.assign(this,t)}}class te{constructor(t){this.slice={size:new n,offset:new n,padding:new n},this.frames=[],this.fps=12,this.loop=!1,Object.assign(this,t)}}class ee{constructor(t){this.layer=Z,this.smooth=!1,this.offset=new n,this.flipHorizontally=!1,this.flipVertically=!1,this.rotation=0,this.opacity=1,this.scale=new n(1,1),this._renderData={type:Mt.Sprite,position:new n,layer:void 0,image:void 0,width:void 0,height:void 0},Object.assign(this,t)}}let ie=class{constructor(t,e){this.entityManager=t,this.timeManager=e}onUpdate(){this.entityManager.search(Zt).forEach((({entity:t,component:e})=>{if(this.reset(e),this.animation=e.animations.get(e.animation),!this.animation)return;this.play(e),e._currentAnimation=e.animation;const i=this.entityManager.getComponent(t,ee);i&&this.renderSprite(e,i)}))}reset(t){t.reset&&(t.currentFrame=0,t.currentTime=0,t.playing=void 0!==t.animation,t.reset=!1)}play(t){t.animation!==t._currentAnimation&&(t._currentAnimation=t.animation,t.currentFrame=0,t.currentTime=0,t.playing=!0),t.playing&&(t.currentTime>=1/this.animation.fps*(t.currentFrame+1)&&(t.currentFrame===this.animation.frames.length-1?this.animation.loop?(t.currentFrame=0,t.currentTime=0):t.playing=!1:t.currentFrame++),t.currentTime+=this.timeManager.renderDeltaTime*t.speed)}renderSprite(t,e){if(Array.isArray(this.animation.image))e.image=this.animation.image[t.currentFrame];else{const i=this.animation.frames[t.currentFrame],s=Math.floor(this.animation.image.naturalWidth/this.animation.slice.size.x);e.image=this.animation.image,e.slice={x:i%s*this.animation.slice.size.x+this.animation.slice.offset.x,y:Math.floor(i/s)*this.animation.slice.size.y+this.animation.slice.offset.y,width:this.animation.slice.size.x-this.animation.slice.padding.y,height:this.animation.slice.size.y-this.animation.slice.padding.y}}}};ie=o([i(W.AnimatorSystem),a(0,s(t.EntityManager)),a(1,s(t.TimeManager))],ie);let se=class{constructor(t,e){this.entityManager=t,this.renderManager=e}onUpdate(){this.entityManager.search(et).forEach((({entity:t,component:e})=>{const i=this.entityManager.getComponent(t,J);if(!i)throw new Error("Camera component needs a Transform");e._renderData.position.copy(i.localPosition),e._renderData.layers=e.layers,e._renderData.depth=e.depth,e._renderData.zoom=e.zoom,e.debug&&e._renderData.layers.push(tt),this.renderManager.addCameraData(e._renderData)}))}};se=o([i(W.CameraSystem),a(0,s(t.EntityManager)),a(1,s(t.RenderManager))],se);let re=class{constructor(t,e){this.webGLManager=t,this.gameConfig=e}onUpdate(){this.webGLManager.renderCanvasColor(this.gameConfig.canvasColor)}};re=o([i(W.ClearScreenSystem),a(0,s(t.WebGLManager)),a(1,s(t.GameConfig))],re);class oe{constructor(t){this.radius=0,this.offset=new n,this.layer="",this.physics=!0,this.ignoreCollisionsWithLayers=[],this.shapes=[],Object.assign(this,t)}}class ae{constructor(t){this.layer="",this.physics=!0,this.width=0,this.height=0,this.offset=new n,this.rotation=0,this.ignoreCollisionsWithLayers=[],this.shapes=[],Object.assign(this,t)}}class ne{constructor(t){this.vertexModel=[],this.offset=new n,this.rotation=0,this.layer="",this.physics=!0,this.ignoreCollisionsWithLayers=[],this.shapes=[],Object.assign(this,t)}}class he{constructor(t){this.vertexModel=[],this.offset=new n,this.rotation=0,this.layer="",this.physics=!0,this.ignoreCollisionsWithLayers=[],this.shapes=[],Object.assign(this,t)}}class le{constructor(t){this.composite=!0,this.layer="",this.ignoreCollisionsWithLayers=[],this.offset=new n,this.physics=!0,this.shapes=[],Object.assign(this,t)}}let ce=class{constructor(t,e,i){this.entityManager=t,this.renderManager=e,this.gameConfig=i}onUpdate(){var t;(null===(t=this.gameConfig.debug)||void 0===t?void 0:t.colliders)&&[oe,ae,he,ne,le].forEach((t=>this.entityManager.search(t).forEach((({component:t})=>t.shapes.forEach((t=>{const e={type:Mt.Geometric,position:new n,layer:tt,color:this.gameConfig.debug.collidersColor,shape:void 0,radius:void 0,rotation:void 0,vertexModel:void 0};t instanceof C?this.gameConfig.collisions.collisionMethod===w.SAT?(e.shape=t.vertices.length>2?vt.Polygon:vt.Line,e.vertexModel=t.vertices):this.gameConfig.collisions.collisionMethod===w.AABB&&(e.shape=vt.Polygon,e.vertexModel=[new n(t.boundingBox.x,t.boundingBox.y),new n(t.boundingBox.x,t.boundingBox.y1),new n(t.boundingBox.x1,t.boundingBox.y1),new n(t.boundingBox.x1,t.boundingBox.y)]):t instanceof S&&(e.shape=vt.Circumference,e.position.copy(t.position),e.radius=t.radius),this.renderManager.addRenderData(e)}))))))}};ce=o([i(W.DebugColliderRenderSystem),a(0,s(t.EntityManager)),a(1,s(t.RenderManager)),a(2,s(t.GameConfig))],ce);let de=class{constructor(t,e){this.renderManager=t,this.canvas=e,this.viewport={x:0,x1:0,y:0,y1:0},this.object={x:0,x1:0,y:0,y1:0},this.culledRenderData=[]}onUpdate(){this.culledRenderData=[],this.renderManager.getCameraData().forEach((t=>{this.setViewport(t),this.renderManager.getRenderData().filter((e=>t.layers.includes(e.layer))).forEach((t=>{this.isInViewPort(t)&&(t.type===Mt.Tilemap&&this.applyCullingInTiles(t),this.culledRenderData.push(t))}))})),this.renderManager.setRenderData(this.culledRenderData)}isInViewPort(t){switch(t.type){case Mt.Video:case Mt.Shadow:case Mt.Sprite:this.setObjectForResizeable(t);break;case Mt.Mask:this.setObjectForMask(t);break;case Mt.Geometric:this.setObjectForGeometric(t);break;case Mt.Text:this.setObjectForText(t);break;case Mt.Tilemap:this.setObjectForTilemap(t)}return this.viewport.x1>=this.object.x&&this.viewport.x<=this.object.x1&&this.viewport.y1>=this.object.y&&this.viewport.y<=this.object.y1}setViewport({position:t,zoom:e}){this.viewport.x=t.x-this.canvas.width/e/2,this.viewport.x1=t.x+this.canvas.width/e/2,this.viewport.y=t.y-this.canvas.height/e/2,this.viewport.y1=t.y+this.canvas.height/e/2}setObjectForResizeable({position:t,width:e,height:i,rotation:s=0,tiled:r}){const o=Math.abs(Math.sin(s)),a=Math.abs(Math.cos(s));r&&(e*=r.x,i*=r.y);const n=o*i+a*e,h=o*e+a*i;this.object.x=t.x-n/2,this.object.x1=t.x+n/2,this.object.y=t.y-h/2,this.object.y1=t.y+h/2}setObjectForText({position:t,text:e,fontSize:i,lineHeight:s,letterSpacing:r,rotation:o}){const a=e.split("\n").reduce(((t,e)=>Math.max(t,e.length)),0)*(i+(null!=r?r:0))*2,n=e.split("\n").length*(null!=s?s:i);this.setObjectForResizeable({position:t,width:a,height:n,rotation:o})}setObjectForGeometric({position:t,vertexModel:e,shape:i,radius:s}){i===vt.Circumference?(this.object.x=t.x-s,this.object.y=t.y-s,this.object.x1=t.x+s,this.object.y1=t.y+s):(this.object.x=Number.MAX_SAFE_INTEGER,this.object.y=Number.MAX_SAFE_INTEGER,this.object.x1=Number.MIN_SAFE_INTEGER,this.object.y1=Number.MIN_SAFE_INTEGER,e.forEach((e=>{this.object.x=Math.min(e.x+t.x,this.object.x),this.object.y=Math.min(e.y+t.y,this.object.y),this.object.x1=Math.max(e.x+t.x,this.object.x1),this.object.y1=Math.max(e.y+t.y,this.object.y1)})))}setObjectForMask({position:t,vertices:e,shape:i,radius:s,rotation:r,width:o,height:a}){i===bt.Circumference?(this.object.x=t.x-s,this.object.y=t.y-s,this.object.x1=t.x+s,this.object.y1=t.y+s):i===bt.Polygon?(this.object.x=Number.MAX_SAFE_INTEGER,this.object.y=Number.MAX_SAFE_INTEGER,this.object.x1=Number.MIN_SAFE_INTEGER,this.object.y1=Number.MIN_SAFE_INTEGER,e.forEach((e=>{this.object.x=Math.min(e.x+t.x,this.object.x),this.object.y=Math.min(e.y+t.y,this.object.y),this.object.x1=Math.max(e.x+t.x,this.object.x1),this.object.y1=Math.max(e.y+t.y,this.object.y1)}))):this.setObjectForResizeable({position:t,width:o,height:a,rotation:r})}setObjectForTilemap(t){t.tilemap.height=Math.ceil(t.tiles.length/t.tilemap.width),this.setObjectForResizeable({position:t.position,width:t.tilemap.width*t.tilemap.tileWidth,height:t.tilemap.height*t.tilemap.tileHeight,rotation:t.rotation})}applyCullingInTiles(t){const{tiles:e,tilemap:{width:i,tileWidth:s,tileHeight:r}}=t;t.tiles=e.map(((t,e)=>this.viewport.x1>=this.object.x+e%i*s&&this.viewport.x<=this.object.x+e%i*s+s&&this.viewport.y1>=this.object.y1-((e/i|0)*r+r)&&this.viewport.y<=this.object.y1-(e/i|0)*r?t:0))}};de=o([i(W.CullingSystem),a(0,s(t.RenderManager)),a(1,s(t.CanvasElement))],de);class ge{constructor(t){this.width=0,this.height=0,this.radius=0,this.vertexModel=[],this.offset=new n,this.rotation=0,this.opacity=1,this.layer=Z,this._renderData={type:Mt.Mask,color:void 0,height:void 0,vertices:[],layer:void 0,opacity:void 0,position:new n,radius:void 0,rotation:void 0,shape:void 0,width:void 0},Object.assign(this,t)}}let me=class{constructor(t,e){this.entityManager=t,this.renderManager=e,this.scaledOffset=new n}onUpdate(){this.entityManager.search(ge).forEach((({entity:t,component:e})=>{const i=this.entityManager.getComponent(t,J);if(!i)throw new Error("MaskRenderer component needs a Transform");this.scaledOffset.set(e.offset.x*i.localScale.x,e.offset.y*i.localScale.y),n.add(e._renderData.position,i.localPosition,this.scaledOffset),e._renderData.width=e.width*Math.abs(i.localScale.x),e._renderData.height=e.height*Math.abs(i.localScale.y),e._renderData.rotation=i.localRotation+e.rotation,e._renderData.color=e.color,e._renderData.layer=e.layer,e._renderData.opacity=e.opacity,e._renderData.radius=e.radius*Math.max(Math.abs(i.localScale.x),Math.abs(i.localScale.y)),e._renderData.shape=e.shape,e.shape===bt.Polygon&&(e._renderData.vertices.length!==e.vertexModel.length&&(e._renderData.vertices=e.vertexModel.map((()=>new n))),e.vertexModel.forEach(((t,s)=>e._renderData.vertices[s].set(t.x*i.localScale.x,t.y*i.localScale.y))),0!==i.localRotation&&e._renderData.vertices.forEach((t=>t.set(t.x*Math.cos(i.localRotation)-t.y*Math.sin(i.localRotation),t.x*Math.sin(i.localRotation)+t.y*Math.cos(i.localRotation))))),0!==i.localRotation&&this.scaledOffset.magnitude>0&&this.translateRenderPosition(e._renderData,i),this.renderManager.addRenderData(e._renderData)}))}translateRenderPosition(t,e){const i=Math.atan2(this.scaledOffset.y,this.scaledOffset.x)+e.localRotation;t.position.set(e.localPosition.x+this.scaledOffset.magnitude*Math.cos(i),e.localPosition.y+this.scaledOffset.magnitude*Math.sin(i))}};me=o([i(W.MaskRendererSystem),a(0,s(t.EntityManager)),a(1,s(t.RenderManager))],me);let ue=class{constructor(t){this.renderManager=t}onUpdate(){this.renderManager.render(),this.renderManager.removeCameraData(),this.renderManager.removeRenderData()}};ue=o([i(W.RenderSystem),a(0,s(t.RenderManager))],ue);class pe{constructor(t){this.radius=0,this.smooth=!1,this.layer=Z,this.intensity=1,this._boundingBox=new h,Object.assign(this,t)}}class ye{constructor(t){this.width=0,this.height=0,this.color="#000000",this.opacity=1,this.layer=Z,this._boundingBox=new h,this._renderData={type:Mt.Shadow,layer:void 0,color:void 0,opacity:void 0,width:void 0,height:void 0,position:void 0,rotation:void 0,lights:[]},Object.assign(this,t)}}let fe=class{constructor(t,e){this.entityManager=t,this.renderManager=e}onUpdate(){const t=this.entityManager.search(pe);t.forEach((({entity:t,component:e})=>this.updateLightRendererBoundingBox(t,e))),this.entityManager.search(ye).forEach((({entity:e,component:i})=>{this.updatShadowRendererBoundingBox(e,i),i._renderData.layer=i.layer,i._renderData.color=i.color,i._renderData.opacity=i.opacity,i._renderData.width=i._boundingBox.width,i._renderData.height=i._boundingBox.height,i._renderData.position=i._boundingBox.center,i._renderData.rotation=0,i._renderData.lights=[],i._renderData.lights=t.filter((({component:t})=>t.layer===i.layer&&t._boundingBox.intersects(i._boundingBox))).map((({component:{_boundingBox:t,smooth:e,intensity:i}})=>({position:t.center,radius:t.width/2,smooth:e,intensity:i}))),this.renderManager.addRenderData(i._renderData)}))}updateLightRendererBoundingBox(t,e){const i=this.entityManager.getComponent(t,J);if(!i)throw new Error("LightRenderer component needs a Transform");const s=e.radius*Math.abs(Math.max(i.localScale.x,i.localScale.y));e._boundingBox.set(i.localPosition.x-s,i.localPosition.y-s,2*s,2*s)}updatShadowRendererBoundingBox(t,e){const i=this.entityManager.getComponent(t,J);if(!i)throw new Error("ShadowRenderer component needs a Transform");const s=e.width*Math.abs(i.localScale.x),r=e.height*Math.abs(i.localScale.y);e._boundingBox.set(i.localPosition.x-s/2,i.localPosition.y-r/2,s,r)}};fe=o([i(W.ShadowLightRendererSystem),a(0,s(t.EntityManager)),a(1,s(t.RenderManager))],fe);let xe=class{constructor(t,e){this.entityManager=t,this.renderManager=e,this.scaledOffset=new n}onUpdate(){this.entityManager.search(ee).forEach((({component:t,entity:e})=>{var i,s,r,o,a,h;const l=this.entityManager.getComponent(e,J);if(!l)throw new Error("SpriteRenderer component needs a Transform");t.image&&t.image.complete&&(this.scaledOffset.set(t.offset.x*l.localScale.x,t.offset.y*l.localScale.y),n.add(t._renderData.position,l.localPosition,this.scaledOffset),t._renderData.width=(null!==(r=null!==(i=t.width)&&void 0!==i?i:null===(s=t.slice)||void 0===s?void 0:s.width)&&void 0!==r?r:t.image.naturalWidth)*Math.abs(t.scale.x*l.localScale.x),t._renderData.height=(null!==(h=null!==(o=t.height)&&void 0!==o?o:null===(a=t.slice)||void 0===a?void 0:a.height)&&void 0!==h?h:t.image.naturalHeight)*Math.abs(t.scale.y*l.localScale.y),t._renderData.flipHorizontally=t.flipHorizontally!==l.scale.x<0,t._renderData.flipVertically=t.flipVertically!==l.scale.y<0,t._renderData.rotation=l.localRotation+t.rotation,0!==l.localRotation&&this.scaledOffset.magnitude>0&&this.translateRenderPosition(t._renderData,l),t._renderData.image=t.image,t._renderData.layer=t.layer,t._renderData.maskColor=t.maskColor,t._renderData.maskColorMix=t.maskColorMix,t._renderData.opacity=t.opacity,t._renderData.slice=t.slice,t._renderData.smooth=t.smooth,t._renderData.tintColor=t.tintColor,t._renderData.tiled=t.tiled,this.renderManager.addRenderData(t._renderData))}))}translateRenderPosition(t,e){const i=Math.atan2(this.scaledOffset.y,this.scaledOffset.x)+e.localRotation;t.position.set(e.localPosition.x+this.scaledOffset.magnitude*Math.cos(i),e.localPosition.y+this.scaledOffset.magnitude*Math.sin(i))}};xe=o([i(W.SpriteRendererSystem),a(0,s(t.EntityManager)),a(1,s(t.RenderManager))],xe);const Me={charRanges:[32,126,161,255],fontSize:64,spacing:8};class ve{constructor(t){this.color="#000000",this.flipHorizontally=!1,this.flipVertically=!1,this.font="Arial",this.fontSize=16,this.height=16,this.layer=Z,this.letterSpacing=0,this.lineHeight=void 0,this.offset=new n,this.opacity=1,this.orientation=Et.Center,this.rotation=0,this.shadow=void 0,this.smooth=!1,this.text="Hello World!",this.textureAtlas=Object.assign({},Me),this.width=160,this._renderData={color:void 0,flipHorizontally:!1,flipVertically:!1,font:void 0,fontSize:void 0,layer:void 0,letterSpacing:void 0,lineHeight:void 0,opacity:void 0,orientation:void 0,position:new n,rotation:void 0,shadow:void 0,smooth:void 0,text:void 0,textureAtlas:Object.assign({},Me),type:Mt.Text},Object.assign(this,t)}}let be=class{constructor(t,e){this.entityManager=t,this.renderManager=e,this.scaledOffset=new n}onUpdate(){this.entityManager.search(ve).forEach((({entity:t,component:e})=>{var i;const s=this.entityManager.getComponent(t,J);if(!s)throw new Error("TextRenderer component needs a Transform");if(0===e.text.length||e.font instanceof FontFace&&"loaded"!==e.font.status)return;this.scaledOffset.set(e.offset.x*s.localScale.x,e.offset.y*s.localScale.y),n.add(e._renderData.position,s.localPosition,this.scaledOffset),e._renderData.layer=e.layer,e._renderData.font=e.font,e._renderData.fontSize=e.fontSize,e._renderData.text=this.crop(e),e._renderData.orientation=e.orientation,e._renderData.color=e.color,e._renderData.lineHeight=null!==(i=e.lineHeight)&&void 0!==i?i:e.fontSize,e._renderData.letterSpacing=e.letterSpacing,e._renderData.smooth=e.smooth,e._renderData.rotation=s.localRotation+e.rotation,e._renderData.opacity=e.opacity;const{charRanges:r,fontSize:o,spacing:a}=e.textureAtlas;r&&(e._renderData.textureAtlas.charRanges=e.textureAtlas.charRanges),o&&(e._renderData.textureAtlas.fontSize=e.textureAtlas.fontSize),a&&(e._renderData.textureAtlas.spacing=e.textureAtlas.spacing),e._renderData.flipHorizontally=e.flipHorizontally,e._renderData.flipVertically=e.flipVertically,e._renderData.shadow=e.shadow,0!==s.localRotation&&this.scaledOffset.magnitude>0&&this.translateRenderPosition(e._renderData,s),this.renderManager.addRenderData(e._renderData)}))}translateRenderPosition(t,e){const i=Math.atan2(this.scaledOffset.y,this.scaledOffset.x)+e.localRotation;t.position.set(e.localPosition.x+this.scaledOffset.magnitude*Math.cos(i),e.localPosition.y+this.scaledOffset.magnitude*Math.sin(i))}crop({fontSize:t,height:e,width:i,text:s,letterSpacing:r,lineHeight:o}){if(t>e)return"";const a=[];let n=0;for(const h of s.split("\n")){const s=h.split(/(\s+)/).reduce(((e,s)=>{const o=e.length-1,a=e[o]+s;return a.length*(t+r)>i?e.push(s):e[o]=a,e}),[""]);for(const t of s){if(n+=o,n>e)return a.join("\n");a.push(t)}}return a.join("\n")}};be=o([i(W.TextRendererSystem),a(0,s(t.EntityManager)),a(1,s(t.RenderManager))],be);let Ce=class{constructor(t,e){this.entityManager=t,this.renderManager=e}onUpdate(){this.entityManager.search(Wt).forEach((({entity:t,component:e})=>{const i=this.entityManager.getComponent(t,J);if(!i)throw new Error("TilemapRenderer component needs a Transform");e._processed&&e.tileset.image&&e.tileset.image.complete&&e.chunks.forEach(((t,s)=>{e._renderData[s]||(e._renderData[s]=Se());const r=e._renderData[s];r.type=Mt.Tilemap,r.orientation=Rt.Center,r.position=new n,r.layer=e.layer,r.tilemap.width=t.width,r.tilemap.height=Math.ceil(e.data.length/t.width),r.tilemap.tileWidth=e.tileWidth*Math.abs(i.localScale.x),r.tilemap.tileHeight=e.tileHeight*Math.abs(i.localScale.y),r.tilemap.realWidth=r.tilemap.width*r.tilemap.tileWidth,r.tilemap.realHeight=r.tilemap.height*r.tilemap.tileHeight,r.tiles=t.data,r.tileset=e.tileset,r.opacity=e.opacity,r.rotation=i.localRotation,r.tintColor=e.tintColor,r.smooth=e.smooth,r.maskColor=e.maskColor,r.maskColorMix=e.maskColorMix,r.position.x=i.localPosition.x+(t.x-e.width/2+t.width/2)*r.tilemap.tileWidth,r.position.y=i.localPosition.y+(e.height/2-t.y-t.height/2)*r.tilemap.tileHeight,this.renderManager.addRenderData(r)}))}))}};Ce=o([i(W.TilemapRendererSystem),a(0,s(t.EntityManager)),a(1,s(t.RenderManager))],Ce);const Se=()=>({type:Mt.Tilemap,layer:void 0,position:new n,tilemap:{height:void 0,realHeight:void 0,realWidth:void 0,tileHeight:void 0,tileWidth:void 0,width:void 0},tiles:void 0,tileset:void 0});var Ae;!function(t){t[t.Dynamic=0]="Dynamic",t[t.Kinematic=1]="Kinematic",t[t.Static=2]="Static"}(Ae||(Ae={}));class we{constructor(t){this.type=Ae.Dynamic,this.velocity=new n,this.gravity=0,this.acceleration=new n,Object.assign(this,t)}}let Ee=class{constructor(t,e,i){this.entityManager=t,this.timeManager=e,this.transformSystem=i,this.types=new Set([Ae.Dynamic,Ae.Kinematic]),this.displacement=new n,this.totalAcceleration=new n,this.scaledAcceleration=new n,this.scaledVelocity=new n}onUpdate(){this.entityManager.search(we).filter((({component:{type:t}})=>this.types.has(t))).forEach((({component:{velocity:t,acceleration:e,gravity:i,type:s},entity:r})=>{const{position:o}=this.entityManager.getComponent(r,J);s===Ae.Dynamic?(this.totalAcceleration.y=e.y-i,this.totalAcceleration.x=e.x):this.totalAcceleration.copy(e),n.add(t,t,n.scale(this.scaledAcceleration,this.totalAcceleration,this.timeManager.physicsDeltaTime)),n.add(o,o,n.add(this.displacement,n.scale(this.scaledVelocity,t,this.timeManager.physicsDeltaTime),n.scale(this.scaledAcceleration,this.totalAcceleration,.5*Math.pow(this.timeManager.physicsDeltaTime,2))))})),this.transformSystem.onUpdate()}};Ee=o([i(W.ApplyVelocitySystem),a(0,s(t.EntityManager)),a(1,s(t.TimeManager)),a(2,s(W.TransformSystem))],Ee);class _e{constructor(){this.auxMin=new n,this.auxMax=new n,this.auxScaledOffset=new n}updatePositionAndVertices(t,e,i){this.translatePosition(t,e,i),t instanceof C?(this.auxAngle=t.rotation+i.localRotation,t.vertexModel.forEach(((e,s)=>t.vertices[s].set(e.x*i.localScale.x,e.y*i.localScale.y))),t.vertices.forEach((e=>e.set(e.x*Math.cos(this.auxAngle)-e.y*Math.sin(this.auxAngle)+t.position.x,e.x*Math.sin(this.auxAngle)+e.y*Math.cos(this.auxAngle)+t.position.y)))):t instanceof S&&(t.radius*=Math.max(Math.abs(i.localScale.x),Math.abs(i.localScale.y)))}translatePosition(t,e,{localPosition:i,localScale:s,localRotation:r}){if(this.auxScaledOffset.set(e.x*s.x,e.y*s.y),0!==r){const e=Math.atan2(this.auxScaledOffset.y,this.auxScaledOffset.x)+r;t.position.set(i.x+this.auxScaledOffset.magnitude*Math.cos(e),i.y+this.auxScaledOffset.magnitude*Math.sin(e))}else n.add(t.position,i,this.auxScaledOffset)}updateBoundingBox(t){t instanceof S?this.updateCircumferenceBoundingBox(t):t instanceof C&&this.updatePolygonBoundingBox(t)}updateCircumferenceBoundingBox(t){t.boundingBox.set(t.position.x-t.radius,t.position.y-t.radius,2*t.radius,2*t.radius)}updatePolygonBoundingBox(t){this.auxMin.x=t.vertices[0].x,this.auxMin.y=t.vertices[0].y,this.auxMax.x=t.vertices[0].x,this.auxMax.y=t.vertices[0].y,t.vertices.forEach((t=>{this.auxMin.x=Math.min(t.x,this.auxMin.x),this.auxMin.y=Math.min(t.y,this.auxMin.y),this.auxMax.x=Math.max(t.x,this.auxMax.x),this.auxMax.y=Math.max(t.y,this.auxMax.y)})),t.boundingBox.set(this.auxMin.x,this.auxMin.y,this.auxMax.x-this.auxMin.x,this.auxMax.y-this.auxMin.y)}updateProjectionAxes(t){var e;if(t.vertices.length>2)for(let i=0;i<t.vertices.length;i++)n.normal(t.projectionAxes[i],n.subtract(t.projectionAxes[i],null!==(e=t.vertices[i+1])&&void 0!==e?e:t.vertices[0],t.vertices[i]));else n.normal(t.projectionAxes[0],n.subtract(t.projectionAxes[0],t.vertices[1],t.vertices[0]))}}let Re=class extends _e{constructor(t){super(),this.entityManager=t}onUpdate(){this.entityManager.search(oe).forEach((({component:t,entity:e})=>{0===t.shapes.length&&(t.shapes[0]=new S(t.radius)),t.shapes[0].radius=t.radius,this.updatePositionAndVertices(t.shapes[0],t.offset,this.entityManager.getComponent(e,J)),this.updateBoundingBox(t.shapes[0]),this.updateProjectionAxes(t.shapes[0])}))}};Re=o([i(W.UpdateBallColliderShapeSystem),a(0,s(t.EntityManager))],Re);let Te=class extends _e{constructor(t){super(),this.entityManager=t}onUpdate(){this.entityManager.search(ae).forEach((({component:t,entity:e})=>{0===t.shapes.length&&(t.shapes[0]=new C([new n,new n,new n,new n])),t.shapes[0].rotation=t.rotation,t.shapes[0].vertexModel[0].set(-t.width/2,-t.height/2),t.shapes[0].vertexModel[1].set(-t.width/2,t.height/2),t.shapes[0].vertexModel[2].set(t.width/2,t.height/2),t.shapes[0].vertexModel[3].set(t.width/2,-t.height/2),this.updatePositionAndVertices(t.shapes[0],t.offset,this.entityManager.getComponent(e,J)),this.updateBoundingBox(t.shapes[0]),this.updateProjectionAxes(t.shapes[0])}))}};Te=o([i(W.UpdateBoxColliderShapeSystem),a(0,s(t.EntityManager))],Te);let Be=class extends _e{constructor(t){super(),this.entityManager=t}onUpdate(){this.entityManager.search(ne).forEach((({component:t,entity:e})=>{for(let i=0;i<t.vertexModel.length-1;i++)t.shapes[i]||(t.shapes[i]=new C([new n,new n])),t.shapes[i].rotation=t.rotation,t.shapes[i].vertexModel=[t.vertexModel[i],t.vertexModel[i+1]],this.updatePositionAndVertices(t.shapes[i],t.offset,this.entityManager.getComponent(e,J)),this.updateBoundingBox(t.shapes[i]),this.updateProjectionAxes(t.shapes[i])}))}};Be=o([i(W.UpdateEdgeColliderShapeSystem),a(0,s(t.EntityManager))],Be);let Pe=class extends _e{constructor(t){super(),this.entityManager=t}onUpdate(){this.entityManager.search(he).forEach((({component:t,entity:e})=>{0===t.shapes.length&&(t.shapes[0]=new C([])),t.shapes[0].rotation=t.rotation,t.shapes[0].vertexModel=t.vertexModel,this.updatePositionAndVertices(t.shapes[0],t.offset,this.entityManager.getComponent(e,J)),this.updateBoundingBox(t.shapes[0]),this.updateProjectionAxes(t.shapes[0])}))}};Pe=o([i(W.UpdatePolygonColliderShapeSystem),a(0,s(t.EntityManager))],Pe);let De=class extends _e{constructor(t){super(),this.entityManager=t}onUpdate(){this.entityManager.search(le).forEach((({component:t,entity:e})=>{const i=this.entityManager.getComponent(e,Wt);if(i&&0!==i.data.length){0===t.shapes.length&&(t.composite?this.useEdges(t,i):this.useBoxes(t,i));for(const i of t.shapes)this.updatePositionAndVertices(i,t.offset,this.entityManager.getComponent(e,J)),this.updateBoundingBox(i),this.updateProjectionAxes(i)}}))}useBoxes(t,e){t.shapes=[],e.data.forEach(((i,s)=>{if(!this.needsCollider(i,s,e))return;const r=new C(this.generateRectangleVertices(s,e));r.updateCollisions=!1,t.shapes.push(r)}))}generateRectangleVertices(t,{width:e,height:i,tileWidth:s,tileHeight:r}){const o=-e*s/2+t%e*s,a=i*r/2-Math.floor(t/e)*r;return[new n(o,a-r),new n(o,a),new n(o+s,a),new n(o+s,a-r)]}needsCollider(t,e,{data:i,width:s,height:r}){return 0!==t&&this.getNeighbors(e,s,r).some((t=>!t||!i[t]||0===i[t]))}useEdges(t,e){t.shapes=[];const i=[],s=[];let r,o;e.data.forEach(((t,r)=>{if(0===t)return;const o=r%e.width,a=Math.floor(r/e.width);i[a]||(i[a]=[]),i[a+1]||(i[a+1]=[]),s[a]||(s[a]=[]),s[a+1]||(s[a+1]=[]);const n=this.getNeighbors(r,e.width,e.height);this.hasTile(n[0],e)||(i[a][o]=!0),this.hasTile(n[2],e)||(i[a+1][o]=!0),this.hasTile(n[1],e)||(s[a][o]=!0),this.hasTile(n[3],e)||(s[a][o+1]=!0)}));for(let s=0;s<i.length;s++)if(i[s])for(let a=0;a<i[s].length;a++)!r||!o||s===o.y&&i[s][a]||(t.shapes.push(this.createEdge(r,o,e)),r=void 0,o=void 0),i[s][a]&&(r||(r=new n(a,s)),o=new n(a+1,s));r&&o&&t.shapes.push(this.createEdge(r,o,e)),r=void 0,o=void 0;for(let i=0;i<=e.width;i++)for(let a=0;a<s.length;a++)s[a]&&(!r||!o||i===o.x&&s[a][i]||(t.shapes.push(this.createEdge(r,o,e)),r=void 0,o=void 0),s[a][i]&&(r||(r=new n(i,a)),o=new n(i,a+1)));r&&o&&t.shapes.push(this.createEdge(r,o,e))}hasTile(t,{data:e}){return void 0!==t&&e[t]&&e[t]>0}createEdge(t,e,{width:i,height:s,tileWidth:r,tileHeight:o}){t.x=-i*r/2+t.x*r,t.y=s*o/2-t.y*o,e.x=-i*r/2+e.x*r,e.y=s*o/2-e.y*o;const a=new C([new n(t.x,t.y),new n(e.x,e.y)]);return a.updateCollisions=!1,a}getNeighbors(t,e,i){return[t-e>=0?t-e:void 0,t%e>0?t-1:void 0,t+e<=e*i?t+e:void 0,t%e<e-1?t+1:void 0]}};De=o([i(W.UpdateTilemapColliderShapeSystem),a(0,s(t.EntityManager))],De);let Fe=class{constructor(t,e,i,s,r){this.entityManager=t,this.broadPhaseResolver=e,this.collisionMatrix=i,this.collisionResolutionMethod=s,this.collisionRepository=r,this.colliders=[],this.collisions=new Set,this.shapes=[]}onUpdate(){this.collisionRepository.removeAll(),this.colliders=[],this.collisions.clear(),this.shapes=[],[oe,ae,he,ne,le].forEach((t=>this.entityManager.search(t).forEach((({component:t,entity:e})=>{this.colliders.push(t),t.shapes.forEach((i=>{var s;i.entity=e,i.collider=this.colliders.length-1,i.id=this.shapes.length,i.ignoreCollisionsWithLayers=null!==(s=t.ignoreCollisionsWithLayers)&&void 0!==s?s:[],i.layer=t.layer,this.shapes.push(i)}))})))),this.broadPhaseResolver.update(this.shapes),this.shapes.filter((t=>t.updateCollisions)).forEach((t=>this.narrowPhase(t,this.broadPhase(t))))}broadPhase({boundingBox:t,layer:e}){return this.collisionMatrix?this.broadPhaseResolver.retrieve(t).map((t=>this.shapes[t])).filter((t=>this.collisionMatrix.some((i=>i[0]===e&&i[1]===t.layer||i[1]===e&&i[0]===t.layer)))):this.broadPhaseResolver.retrieve(t).map((t=>this.shapes[t]))}narrowPhase(t,e){e.filter((e=>t.entity!==e.entity&&t.id!==e.id&&!t.ignoreCollisionsWithLayers.includes(e.layer)&&!e.ignoreCollisionsWithLayers.includes(t.layer)&&!this.isResolved(t,e))).forEach((e=>{const i=this.collisionResolutionMethod.findCollision(t,e);i&&(this.collisionRepository.persist({localCollider:this.colliders[t.collider],localEntity:t.entity,remoteCollider:this.colliders[e.collider],remoteEntity:e.entity,resolution:i}),this.collisionRepository.persist({localCollider:this.colliders[e.collider],localEntity:e.entity,remoteCollider:this.colliders[t.collider],remoteEntity:t.entity,resolution:{direction:n.scale(new n,i.direction,-1),penetration:i.penetration}}),this.collisions.add(`${t.id}-${e.id}`),this.collisions.add(`${e.id}-${t.id}`))}))}isResolved(t,e){return this.collisions.has(`${t.id}-${e.id}`)}};Fe=o([i(W.ResolveCollisionSystem),a(0,s(t.EntityManager)),a(1,s(t.CollisionBroadphaseResolver)),a(2,s(t.CollisionMatrix)),a(3,s(t.CollisionResolutionMethod)),a(4,s(t.CollisionRepository))],Fe);let Ue=class{constructor(t,e,i){this.entityManager=t,this.collisionRepository=e,this.transformSystem=i,this.correction=new n,this.maxCorrection=new n}onUpdate(){const t=this.collisionRepository.findAll().filter((({localCollider:t,remoteCollider:e,remoteEntity:i,localEntity:s})=>t.physics&&e.physics&&this.entityManager.hasComponent(s,we)&&this.entityManager.hasComponent(i,we)));0!==t.length&&(this.entityManager.search(we,{type:Ae.Dynamic}).forEach((({component:e,entity:i})=>{if(this.maxCorrection.set(0,0),t.filter((({localEntity:t})=>i===t)).forEach((({remoteEntity:t,resolution:{direction:e,penetration:i}})=>{this.entityManager.getComponent(t,we).type===Ae.Dynamic&&(i/=2),n.scale(this.correction,e,-i),this.correction.magnitude>this.maxCorrection.magnitude&&this.maxCorrection.copy(this.correction)})),0===this.maxCorrection.x&&0===this.maxCorrection.y)return;const{position:s}=this.entityManager.getComponent(i,J);n.add(s,s,this.maxCorrection),e.gravity>0&&this.maxCorrection.y*e.velocity.y<0&&(e.velocity.y=0)})),this.transformSystem.onUpdate())}};Ue=o([i(W.ApplyRepositionSystem),a(0,s(t.EntityManager)),a(1,s(t.CollisionRepository)),a(2,s(W.TransformSystem))],Ue);let Ie=class extends _e{constructor(t){super(),this.entityManager=t}onUpdate(){[oe,ae,he,ne,le].forEach((t=>this.entityManager.search(t,{updateCollisions:!0}).forEach((({component:t,entity:e})=>t.shapes.forEach((i=>{this.updatePositionAndVertices(i,t.offset,this.entityManager.getComponent(e,J)),this.updateBoundingBox(i)}))))))}};Ie=o([i(W.UpdateCollidersAfterRepositionSystem),a(0,s(t.EntityManager))],Ie);const Le=24;let je=class{constructor(t,e,i,s,r){this.entityManager=t,this.renderManager=e,this.inputManager=i,this.canvas=s,this.gameConfig=r,this.positionInViewport=new n,this.positionInCameraViewport=new n,this.positionInWorldspace=new n,this.renderDataPerCamera=new Map}onUpdate(){var t;if(!(null===(t=this.gameConfig.debug)||void 0===t?void 0:t.mousePosition)||!this.inputManager.mouse)return;const{positionInViewport:e}=this.inputManager.mouse;this.entityManager.search(et,{debug:!0}).forEach((({entity:t,component:i},s)=>{var r;const{zoom:o}=i,a=this.entityManager.getComponent(t,J).position,h=null!==(r=this.renderDataPerCamera.get(s))&&void 0!==r?r:Oe();n.floor(this.positionInWorldspace,n.add(this.positionInWorldspace,a,n.scale(this.positionInWorldspace,e,1/o))),n.floor(this.positionInCameraViewport,n.scale(this.positionInCameraViewport,e,1/o)),n.round(this.positionInViewport,e),h.color=this.gameConfig.debug.textColor,h.text=`mouse_position: canvas_viewport=${this.positionInViewport}, camera_viewport=${this.positionInCameraViewport}, world_space=${this.positionInWorldspace}`,h.fontSize=Le/o,h.shadow.offset.x=2/o,h.shadow.offset.y=-2/o,this.updateRenderDataPosition(h,a,o),this.renderManager.addRenderData(h)}))}updateRenderDataPosition(t,e,i){switch(this.gameConfig.debug.textPosition){case"top-left":t.position.set(e.x-(this.canvas.width/2-Le)/i,e.y+(this.canvas.height/2-Le)/i);break;case"top-right":t.position.set(e.x+(this.canvas.width/2-t.text.length/2*Le)/i,e.y+(this.canvas.height/2-Le)/i);break;case"bottom-left":default:t.position.set(e.x-(this.canvas.width/2-Le)/i,e.y-(this.canvas.height/2-Le)/i);break;case"bottom-right":t.position.set(e.x+(this.canvas.width/2-t.text.length/2*Le)/i,e.y-(this.canvas.height/2-Le)/i)}}};je=o([i(W.DebugMousePositionSystem),a(0,s(t.EntityManager)),a(1,s(t.RenderManager)),a(2,s(t.InputManager)),a(3,s(t.CanvasElement)),a(4,s(t.GameConfig))],je);const Oe=(t=24)=>({type:Mt.Text,text:"",position:new n,layer:tt,color:"#00FF00",fontSize:t,font:"Arial",shadow:{color:"#000000",opacity:1,offset:new n(1,-1)},orientation:Et.RightCenter,flipHorizontally:!1,flipVertically:!1,letterSpacing:0,lineHeight:t,opacity:1,rotation:0,smooth:!1,textureAtlas:Object.assign({},Me)}),ke=new Map([[X.PreGameLogic,[{name:W.KeyboardSystem,type:qt},{name:W.MouseSystem,type:Qt},{name:W.TouchScreenSystem,type:Jt},{name:W.GamepadSystem,type:Kt},{name:W.ButtonSystem,type:zt},{name:W.AudioPlayerSystem,type:Y},{name:W.TiledWrapperSystem,type:Ht},{name:W.TilemapPreProcessingSystem,type:Xt}]],[X.Transform,[{name:W.TransformSystem,type:$t}]],[X.Physics,[{name:W.ApplyVelocitySystem,type:Ee},{name:W.UpdateBallColliderShapeSystem,type:Re},{name:W.UpdateBoxColliderShapeSystem,type:Te},{name:W.UpdateEdgeColliderShapeSystem,type:Be},{name:W.UpdatePolygonColliderShapeSystem,type:Pe},{name:W.UpdateTilemapColliderShapeSystem,type:De},{name:W.ResolveCollisionSystem,type:Fe},{name:W.ApplyRepositionSystem,type:Ue},{name:W.UpdateCollidersAfterRepositionSystem,type:Ie}]],[X.Render,[{name:W.AnimatorSystem,type:ie},{name:W.CameraSystem,type:se},{name:W.TilemapRendererSystem,type:Ce},{name:W.SpriteRendererSystem,type:xe},{name:W.MaskRendererSystem,type:me},{name:W.ShadowLightRendererSystem,type:fe},{name:W.TextRendererSystem,type:be},{name:W.VideoRendererSystem,type:jt},{name:W.DebugColliderRenderSystem,type:ce},{name:W.DebugMousePositionSystem,type:je},{name:W.CullingSystem,type:de},{name:W.ClearScreenSystem,type:re},{name:W.RenderSystem,type:ue}]]]);let Ve=class{constructor(t,e,i){this.timeManager=t,this.systemManager=e,this.sceneManager=i,this.running=!1,this.gameLoopAccumulator=0}start(){this.running||(this.running=!0,this.gameLoopAccumulator=0,this.enableSystems(),this.sceneManager.loadOpeningScene(),this.requestAnimationLoop(window.performance.now()),this.asyncPhysicsLoop())}enableSystems(){ke.forEach((t=>{t.forEach((({type:t})=>this.systemManager.enableSystem(t)))}))}stop(){this.running&&(this.systemManager.disableAllSystems(),this.running=!1)}requestAnimationLoop(t){this.running&&(this.timeManager.updateForRender(.001*t),this.sceneManager.update(),this.sceneManager.loadingScene||(this.gameLoopAccumulator+=this.timeManager.browserDeltaTime,this.sceneManager.sceneLoadedThisFrame&&(this.gameLoopAccumulator=this.timeManager.fixedGameDeltaTime),this.gameLoopAccumulator>=this.timeManager.fixedGameDeltaTime&&(this.gameLogicIteration(.001*t),this.gameLoopAccumulator-=this.timeManager.fixedGameDeltaTime),this.renderIteration()),window.requestAnimationFrame((t=>this.requestAnimationLoop(t))))}gameLogicIteration(t){this.timeManager.updateForGame(t),this.systemManager.update(X.PreGameLogic),this.systemManager.update(X.GameLogic),this.timeManager.updateIntervals(),this.systemManager.update(X.Transform)}renderIteration(){this.systemManager.groupHasSystems(X.GamePreRender)&&(this.systemManager.update(X.GamePreRender),this.systemManager.update(X.Transform)),this.systemManager.update(X.Render)}asyncPhysicsLoop(){this.physicsIntervalId=window.setInterval((()=>{if(!this.running)return window.clearInterval(this.physicsIntervalId);this.timeManager.updateForPhysics(.001*window.performance.now()),document.hidden||this.physicsIteration()}),1e3/this.timeManager.fixedPhysicsFramerate)}physicsIteration(){this.timeManager.timeScale<=0||(this.systemManager.groupHasSystems(X.GamePhysics)&&(this.systemManager.update(X.GamePhysics),this.systemManager.update(X.Transform)),this.systemManager.update(X.Physics))}};Ve=o([i(t.LoopManager),a(0,s(t.TimeManager)),a(1,s(t.SystemManager)),a(2,s(t.SceneManager))],Ve);class Ge{constructor(t,e){this.container=t,this.systemManager=e,this.lastSystemTypeId=0}createSystemIfNotExists(t){if(this.systemManager.hasSystem(t))return;const e="__system_"+this.lastSystemTypeId++;var i;this.container.add(t,e),this.systemManager.addSystem(this.container.get(e),null!==(i=t.prototype.__system_group)&&void 0!==i?i:X.GameLogic)}}let ze=class{constructor(t){this.webGLManager=t,this.renderData=[],this.cameraData=[]}addCameraData(t){this.cameraData.push(t)}addRenderData(t){this.renderData.push(t)}setRenderData(t){this.renderData=t}getCameraData(){return this.cameraData}getRenderData(){return this.renderData}removeCameraData(){this.cameraData=[]}removeRenderData(){this.renderData=[]}render(){this.cameraData.sort(((t,e)=>t.depth-e.depth)).forEach((t=>this.renderData.filter((e=>t.layers.includes(e.layer))).sort(((e,i)=>t.layers.indexOf(e.layer)-t.layers.indexOf(i.layer))).forEach((e=>this.webGLManager.render(e,t)))))}};ze=o([i(t.RenderManager),a(0,s(t.WebGLManager))],ze);const Ne=t=>{var e,i,s,o,a,n,h,l,c,d,g;if(!(t.containerNode instanceof HTMLElement))throw new Error("GameConfig Error: Invalid containerNode");if("number"!=typeof t.width)throw new Error("GameConfig Error: Invalid width");if("number"!=typeof t.height)throw new Error("GameConfig Error: Invalid height");t.canvasColor=null!==(e=t.canvasColor)&&void 0!==e?e:"#000000",t.physicsFramerate=null!==(i=t.physicsFramerate)&&void 0!==i?i:180,t.headless=null!==(s=t.headless)&&void 0!==s&&s,t.debug=null!==(o=t.debug)&&void 0!==o?o:{colliders:!1,mousePosition:!1},t.debug.collidersColor=null!==(a=t.debug.collidersColor)&&void 0!==a?a:"#00FF00",t.debug.textColor=null!==(n=t.debug.textColor)&&void 0!==n?n:"#00FF00",t.debug.textPosition=null!==(h=t.debug.textPosition)&&void 0!==h?h:"bottom-left",t.collisions=null!==(l=t.collisions)&&void 0!==l?l:{},t.collisions.collisionBroadPhaseMethod=null!==(c=t.collisions.collisionBroadPhaseMethod)&&void 0!==c?c:r.SpartialGrid,t.collisions.collisionMatrix=null!==(d=t.collisions.collisionMatrix)&&void 0!==d?d:void 0,t.collisions.collisionMethod=null!==(g=t.collisions.collisionMethod)&&void 0!==g?g:w.SAT},We=({containerNode:t,width:e,height:i})=>{const s=document.createElement("canvas");return s.id="angryPixelGameCanvas",s.width=Math.floor(e),s.height=Math.floor(i),s.tabIndex=0,s.addEventListener("contextmenu",(t=>t.preventDefault())),t.appendChild(s),s.focus(),s},He=e=>{e.add(D),e.add(F),e.set(t.CreateSystemService,new Ge(e,e.get(t.SystemManager))),e.add(V),e.add(z),e.add(O),e.add(kt),e.add(O),e.add(Ve),e.add(Ut),e.add(ze)},Ye=e=>{e.get(t.GameConfig).headless&&Xe(ke),ke.forEach(((i,s)=>i.forEach((({type:i,name:r})=>{e.add(i),e.get(t.SystemManager).addSystem(e.get(r),s)}))))},Xe=t=>{t.delete(X.Render),t.set(X.PreGameLogic,t.get(X.PreGameLogic).filter((({name:t})=>![W.AudioPlayerSystem,W.ButtonSystem,W.GamepadSystem,W.KeyboardSystem,W.MouseSystem,W.TouchScreenSystem].includes(t))))},$e=e=>{const{collisions:{collisionBroadPhaseMethod:i,collisionMatrix:s,collisionMethod:o}}=e.get(t.GameConfig);e.add(P),e.add(T),o===w.AABB?(e.add(_),e.add(R)):e.add(B),e.add(i===r.QuadTree?M:b),e.add(o===w.AABB?A:E),e.set(t.CollisionMatrix,s)},Ke=e=>{const i=e.get(t.GameConfig);i.dependencies&&i.dependencies.forEach((([t,i])=>{e.set(t,i)}))};class qe{constructor(i){this.container=(i=>{Ne(i);const s=new e;return s.set(t.GameConfig,i),s.set(t.CanvasElement,We(i)),$e(s),He(s),Ye(s),Ke(s),s})(i)}get running(){return this.container.get(t.LoopManager).running}addScene(e,i,s=!1){this.container.get(t.SceneManager).addScene(e,i,s)}addDependencyType(t,e){this.container.add(t,e)}addDependencyInstance(t,e){this.container.set(e,t)}start(){this.container.get(t.LoopManager).start()}stop(){this.container.get(t.LoopManager).stop()}}class Qe{onUpdate(){}onCreate(){}onEnabled(){}onDisabled(){}onDestroy(){}}function Je(t,e,i){"number"==typeof i?t(e.prototype,void 0,i):void 0!==i?t(e.prototype,i):t(e)}o([s(t.EntityManager)],Qe.prototype,"entityManager",void 0),o([s(t.AssetManager)],Qe.prototype,"assetManager",void 0),o([s(t.SceneManager)],Qe.prototype,"sceneManager",void 0),o([s(t.TimeManager)],Qe.prototype,"timeManager",void 0),o([s(t.InputManager)],Qe.prototype,"inputManager",void 0),o([s(t.CollisionRepository)],Qe.prototype,"collisionRepository",void 0),o([s(t.GameConfig)],Qe.prototype,"gameConfig",void 0);const Ze=({audioSource:t,volume:e=1,loop:i=!1})=>{t.volume=e,t.loop=i,t.currentTime=0,t.play().catch((t=>console.warn("playSfx error:",t)))},ti=t=>{t.pause(),t.currentTime=0},ei={AssetManager:t.AssetManager,CanvasElement:t.CanvasElement,CollisionRepository:t.CollisionRepository,EntityManager:t.EntityManager,GameConfig:t.GameConfig,InputManager:t.InputManager,SceneManager:t.SceneManager,SystemManager:t.SystemManager,TimeManager:t.TimeManager};export{te as Animation,Zt as Animator,z as AssetManager,N as AudioPlayer,oe as BallCollider,ae as BoxCollider,r as BroadPhaseMethods,Vt as Button,Gt as ButtonShape,et as Camera,S as Circumference,w as CollisionMethods,P as CollisionRepository,ne as EdgeCollider,D as EntityManager,qe as Game,Qe as GameSystem,U as GamepadController,O as InputManager,I as Keyboard,pe as LightRenderer,ge as MaskRenderer,bt as MaskShape,L as Mouse,C as Polygon,he as PolygonCollider,h as Rectangle,we as RigidBody,Ae as RigidBodyType,Ot as Scene,kt as SceneManager,ye as ShadowRenderer,ee as SpriteRenderer,ei as Symbols,F as SystemManager,Et as TextOrientation,ve as TextRenderer,Nt as TiledWrapper,le as TilemapCollider,Rt as TilemapOrientation,Wt as TilemapRenderer,V as TimeManager,j as TouchScreen,J as Transform,n as Vector2,It as VideoRenderer,u as between,l as clamp,tt as debugRenderLayer,Je as decorate,Z as defaultRenderLayer,Me as defaultTextureAtlasOptions,y as degreesToRadians,g as fixedRound,$ as gameLogicSystem,K as gamePhysicsSystem,q as gamePreRenderSystem,s as inject,i as injectable,Ze as playSfx,p as radiansToDegrees,d as randomFloat,c as randomInt,m as range,f as rgbToHex,ti as stopSfx};
|
|
2
2
|
//# sourceMappingURL=index.esm.js.map
|