rapid-render 0.1.0 → 0.1.2-1.1
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 +59 -97
- package/dist/assets.d.ts +92 -0
- package/dist/audio.d.ts +59 -0
- package/dist/depth.d.ts +8 -0
- package/dist/game.d.ts +292 -0
- package/dist/index.d.ts +9 -3
- package/dist/input.d.ts +93 -0
- package/dist/interface.d.ts +337 -32
- package/dist/light.d.ts +7 -0
- package/dist/line.d.ts +15 -2
- package/dist/log.d.ts +2 -0
- package/dist/math.d.ts +272 -45
- package/dist/particle.d.ts +73 -0
- package/dist/rapid.global.js +1 -1
- package/dist/rapid.js +1 -1
- package/dist/rapid.umd.cjs +1 -1
- package/dist/regions/attributes.d.ts +44 -0
- package/dist/regions/graphic_region.d.ts +7 -20
- package/dist/regions/region.d.ts +23 -7
- package/dist/regions/sprite_region.d.ts +5 -26
- package/dist/render.d.ts +159 -45
- package/dist/texture.d.ts +105 -13
- package/dist/tilemap.d.ts +98 -0
- package/dist/utils.d.ts +106 -0
- package/dist/webgl/glshader.d.ts +15 -4
- package/dist/webgl/uniform.d.ts +14 -0
- package/dist/webgl/utils.d.ts +11 -1
- package/package.json +11 -5
package/dist/rapid.global.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var rapid=function(t){"use strict";const e=(t,e,r)=>{const i=t.createShader(r);if(!i)throw new Error("Unable to create webgl shader");t.shaderSource(i,e),t.compileShader(i);if(!t.getShaderParameter(i,t.COMPILE_STATUS)){const r=t.getShaderInfoLog(i);throw console.error("Shader compilation failed:",r),new Error("Unable to compile shader: "+r+e)}return i};const r=5126;class i{constructor(t){this.usedElemNum=0,this.maxElemNum=512,this.bytePerElem=t.BYTES_PER_ELEMENT,this.arrayType=t,this.arraybuffer=new ArrayBuffer(this.maxElemNum*this.bytePerElem),this.typedArray=new t(this.arraybuffer),t==Float32Array&&(this.uint32=new Uint32Array(this.arraybuffer))}clear(){this.usedElemNum=0}resize(t=0){if((t+=this.usedElemNum)>this.maxElemNum){for(;t>this.maxElemNum;)this.maxElemNum<<=1;this.setMaxSize(this.maxElemNum)}}setMaxSize(t=this.maxElemNum){const e=this.typedArray;this.maxElemNum=t,this.arraybuffer=new ArrayBuffer(t*this.bytePerElem),this.typedArray=new this.arrayType(this.arraybuffer),this.uint32&&(this.uint32=new Uint32Array(this.arraybuffer)),this.typedArray.set(e)}push(t){this.typedArray[this.usedElemNum++]=t}pushUint(t){this.uint32[this.usedElemNum++]=t}pop(t){this.usedElemNum-=t}getArray(t=0,e){return null==e?this.typedArray:this.typedArray.subarray(t,e)}get length(){return this.typedArray.length}}class s extends i{constructor(t,e,r=t.ARRAY_BUFFER){super(e),this.dirty=!0,this.webglBufferSize=0,this.gl=t,this.buffer=t.createBuffer(),this.type=r}push(t){super.push(t),this.dirty=!0}bindBuffer(){this.gl.bindBuffer(this.type,this.buffer)}bufferData(){if(this.dirty){const t=this.gl;this.maxElemNum>this.webglBufferSize?(t.bufferData(this.type,this.getArray(),t.STATIC_DRAW),this.webglBufferSize=this.maxElemNum):t.bufferSubData(this.type,0,this.getArray(0,this.usedElemNum)),this.dirty=!1}}}class n extends i{constructor(){super(Float32Array)}pushMat(){const t=this.usedElemNum-6,e=this.typedArray;this.resize(6),this.push(e[t+0]),this.push(e[t+1]),this.push(e[t+2]),this.push(e[t+3]),this.push(e[t+4]),this.push(e[t+5])}popMat(){this.pop(6)}pushIdentity(){this.resize(6),this.push(1),this.push(0),this.push(0),this.push(1),this.push(0),this.push(0)}translate(t,e){if(t instanceof o)return this.translate(t.x,t.y);const r=this.usedElemNum-6,i=this.typedArray;i[r+4]=i[r+0]*t+i[r+2]*e+i[r+4],i[r+5]=i[r+1]*t+i[r+3]*e+i[r+5]}rotate(t){const e=this.usedElemNum-6,r=this.typedArray,i=Math.cos(t),s=Math.sin(t),n=r[e+0],h=r[e+1],a=r[e+2],o=r[e+3];r[e+0]=n*i-h*s,r[e+1]=n*s+h*i,r[e+2]=a*i-o*s,r[e+3]=a*s+o*i}scale(t,e){if(t instanceof o)return this.scale(t.x,t.y);e||(e=t);const r=this.usedElemNum-6,i=this.typedArray;i[r+0]=i[r+0]*t,i[r+1]=i[r+1]*t,i[r+2]=i[r+2]*e,i[r+3]=i[r+3]*e}apply(t,e){if(t instanceof o)return new o(...this.apply(t.x,t.y));const r=this.usedElemNum-6,i=this.typedArray;return[i[r+0]*t+i[r+2]*e+i[r+4],i[r+1]*t+i[r+3]*e+i[r+5]]}getInverse(){const t=this.usedElemNum-6,e=this.typedArray,r=e[t+0],i=e[t+1],s=e[t+2],n=e[t+3],h=e[t+4],a=e[t+5],o=r*n-i*s;return new Float32Array([n/o,-i/o,-s/o,r/o,(s*a-n*h)/o,(i*h-r*a)/o])}getTransform(){const t=this.usedElemNum-6,e=this.typedArray;return new Float32Array([e[t+0],e[t+1],e[t+2],e[t+3],e[t+4],e[t+5]])}setTransform(t){const e=this.usedElemNum-6,r=this.typedArray;r[e+0]=t[0],r[e+1]=t[1],r[e+2]=t[2],r[e+3]=t[3],r[e+4]=t[4],r[e+5]=t[5]}}class h extends s{constructor(t,e,r,i){super(t,Uint16Array,t.ELEMENT_ARRAY_BUFFER),this.setMaxSize(e*i);for(let t=0;t<i;t++)this.addObject(t*r);this.bindBuffer(),this.bufferData()}addObject(t){}}class a{constructor(t,e,r,i){this._r=t,this._g=e,this._b=r,this._a=i,this.updateUint()}get r(){return this._r}set r(t){this._r=t,this.updateUint()}get g(){return this._g}set g(t){this._g=t,this.updateUint()}get b(){return this._b}set b(t){this._b=t,this.updateUint()}get a(){return this._a}set a(t){this._a=t,this.updateUint()}updateUint(){this.uint32=(this._a<<24|this._b<<16|this._g<<8|this._r)>>>0}setRGBA(t,e,r,i){this.r=t,this.g=e,this.b=r,this.a=i,this.updateUint()}copy(t){this.setRGBA(t.r,t.g,t.b,t.a)}equals(t){return t.r===this.r&&t.g===this.g&&t.b===this.b&&t.a===this.a}static fromHex(t){t.startsWith("#")&&(t=t.slice(1));const e=parseInt(t.slice(0,2),16),r=parseInt(t.slice(2,4),16),i=parseInt(t.slice(4,6),16);let s=255;return t.length>=8&&(s=parseInt(t.slice(6,8),16)),new a(e,r,i,s)}add(t){return new a(Math.min(this.r+t.r,255),Math.min(this.g+t.g,255),Math.min(this.b+t.b,255),Math.min(this.a+t.a,255))}subtract(t){return new a(Math.max(this.r-t.r,0),Math.max(this.g-t.g,0),Math.max(this.b-t.b,0),Math.max(this.a-t.a,0))}}class o{constructor(t,e){this.x=void 0!==t?t:0,this.y=void 0!==e?e:0}scalarMult(t){return this.x*=t,this.y*=t,this}perpendicular(){const t=this.x;return this.x=-this.y,this.y=t,this}invert(){return this.x=-this.x,this.y=-this.y,this}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}normalize(){const t=this.length();return this.x/=t,this.y/=t,this}angle(){return this.y/this.x}static Angle(t,e){return Math.atan2(e.y-t.y,e.x-t.x)}static Add(t,e){return new o(t.x+e.x,t.y+e.y)}static Sub(t,e){return new o(t.x-e.x,t.y-e.y)}static Middle(t,e){return o.Add(t,e).scalarMult(.5)}static FormArray(t){return t.map((t=>new o(t[0],t[1])))}}class u{constructor(t){this.cache=new Map,this.render=t}async textureFromUrl(t,e=!1){let r=this.cache.get(t);if(!r){const i=await this.loadImage(t);r=l.fromImageSource(this.render,i,e),this.cache.set(t,r)}return new d(r)}async loadImage(t){return new Promise((e=>{const r=new Image;r.onload=()=>{e(r)},r.src=t}))}createText(t){return new c(this.render,t)}}class l{constructor(t,e,r){this.texture=t,this.width=e,this.height=r}static fromImageSource(t,e,r=!1){return new l(function(t,e,r){const i=t.createTexture();if(t.bindTexture(t.TEXTURE_2D,i),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,r?t.LINEAR:t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,r?t.LINEAR:t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),!i)throw new Error("unable to create texture");return i}(t.gl,e,r),e.width,e.height)}}class d{constructor(t){this.scale=1,this.setBaseTextur(t)}setBaseTextur(t){t&&(this.base=t,this.setClipRegion(0,0,t.width,t.height))}setClipRegion(t,e,r,i){this.base&&(this.clipX=t/this.base.width,this.clipY=e/this.base.width,this.clipW=this.clipX+r/this.base.width,this.clipH=this.clipY+i/this.base.height,this.width=r*this.scale,this.height=i*this.scale)}static fromImageSource(t,e,r=!1){return new d(l.fromImageSource(t,e,r))}static fromUrl(t,e){return t.textures.textureFromUrl(e)}}class c extends d{constructor(t,e){super(),this.scale=.5,this.rapid=t,this.options=e,this.text=e.text||"",this.updateTextImage()}updateTextImage(){const t=this.createTextCanvas();this.setBaseTextur(l.fromImageSource(this.rapid,t,!0))}createTextCanvas(){const t=document.createElement("canvas"),e=t.getContext("2d");if(!e)throw new Error("Failed to get canvas context");e.font=`${this.options.fontSize||16}px ${this.options.fontFamily||"Arial"}`,e.fillStyle=this.options.color||"#000",e.textAlign=this.options.textAlign||"left",e.textBaseline=this.options.textBaseline||"top";const r=this.text.split("\n");let i=0,s=0;for(const t of r){const r=e.measureText(t);i=Math.max(i,r.width),s+=this.options.fontSize||16}t.width=2*i,t.height=2*s,e.scale(2,2),e.font=`${this.options.fontSize||16}px ${this.options.fontFamily||"Arial"}`,e.fillStyle=this.options.color||"#000",e.textAlign=this.options.textAlign||"left",e.textBaseline=this.options.textBaseline||"top";let n=0;for(const t of r)e.fillText(t,0,n),n+=this.options.fontSize||16;return t}setText(t){this.text=t,this.updateTextImage()}}class p{constructor(t,r,i){this.attributeLoc={},this.uniformLoc={};const s=function(t,e){if(t.includes("%TEXTURE_NUM%")&&(t=t.replace("%TEXTURE_NUM%",e.toString())),t.includes("%GET_COLOR%")){let r="";for(let t=0;t<e;t++)r+=0==t?`if(vTextureId == ${t}.0)`:t==e-1?"else":`else if(vTextureId == ${t}.0)`,r+=`{color = texture2D(uTextures[${t}], vRegion);}`;t=t.replace("%GET_COLOR%",r)}return t}(i,t.maxTextureUnits);this.program=((t,r,i)=>{var s=t.createProgram(),n=e(t,r,35633),h=e(t,i,35632);if(!s)throw new Error("Unable to create program shader");return t.attachShader(s,n),t.attachShader(s,h),t.linkProgram(s),s})(t.gl,r,s),this.gl=t.gl,this.parseShader(r),this.parseShader(s)}setUniforms(t,e){var r;const i=this.gl;for(const s in t){const n=t[s],h=this.getUniform(s);if(n instanceof d&&(null===(r=n.base)||void 0===r?void 0:r.texture))i.activeTexture(i.TEXTURE0+e),i.bindTexture(i.TEXTURE_2D,n.base.texture),i.uniform1i(h,e),e+=1;else if("number"==typeof n)i.uniform1f(h,n);else if(Array.isArray(n))switch(n.length){case 1:Number.isInteger(n[0])?i.uniform1i(h,n[0]):i.uniform1f(h,n[0]);break;case 2:Number.isInteger(n[0])?i.uniform2iv(h,n):i.uniform2fv(h,n);break;case 3:Number.isInteger(n[0])?i.uniform3iv(h,n):i.uniform3fv(h,n);break;case 4:Number.isInteger(n[0])?i.uniform4iv(h,n):i.uniform4fv(h,n);break;case 9:i.uniformMatrix3fv(h,!1,n);break;case 16:i.uniformMatrix4fv(h,!1,n);break;default:console.error(`Unsupported uniform array length for ${s}:`,n.length)}else"boolean"==typeof n?i.uniform1i(h,n?1:0):console.error(`Unsupported uniform type for ${s}:`,typeof n)}}getUniform(t){return this.uniformLoc[t]}use(){this.gl.useProgram(this.program)}parseShader(t){const e=this.gl,r=t.match(/attribute\s+\w+\s+(\w+)/g);if(r)for(const t of r){const r=t.split(" ")[2],i=e.getAttribLocation(this.program,r);-1!=i&&(this.attributeLoc[r]=i)}const i=t.match(/uniform\s+\w+\s+(\w+)/g);if(i)for(const t of i){const r=t.split(" ")[2];this.uniformLoc[r]=e.getUniformLocation(this.program,r)}}setAttribute(t){const e=this.attributeLoc[t.name];if(void 0!==e){const r=this.gl;r.vertexAttribPointer(e,t.size,t.type,t.normalized||!1,t.stride,t.offset||0),r.enableVertexAttribArray(e)}}}class f{constructor(t,e){this.usedTextures=[],this.needBind=new Set,this.attribute=e,this.rapid=t,this.gl=t.gl,this.webglArrayBuffer=new s(t.gl,Float32Array,t.gl.ARRAY_BUFFER),this.TEXTURE_UNITS_ARRAY=Array.from({length:t.maxTextureUnits},((t,e)=>e))}addVertex(t,e,...r){const[i,s]=this.rapid.transformPoint(t,e);this.webglArrayBuffer.push(i),this.webglArrayBuffer.push(s)}useTexture(t){let e=this.usedTextures.indexOf(t);return-1===e&&(this.usedTextures.length>=this.rapid.maxTextureUnits&&this.render(),this.usedTextures.push(t),e=this.usedTextures.length-1,this.needBind.add(e)),e}enterRegion(t){this.currentShader=null!=t?t:this.defaultShader,this.currentShader.use(),this.initializeForNextRender(),this.webglArrayBuffer.bindBuffer();for(const t of this.attribute)this.currentShader.setAttribute(t);this.gl.uniformMatrix4fv(this.currentShader.uniformLoc.uProjectionMatrix,!1,this.rapid.projection)}exitRegion(){}initDefaultShader(t,e){this.webglArrayBuffer.bindBuffer(),this.defaultShader=new p(this.rapid,t,e)}render(){this.executeRender(),this.initializeForNextRender()}executeRender(){this.webglArrayBuffer.bufferData();const t=this.gl;for(const e of this.needBind)t.activeTexture(t.TEXTURE0+e),t.bindTexture(t.TEXTURE_2D,this.usedTextures[e]);this.needBind.clear()}initializeForNextRender(){this.webglArrayBuffer.clear(),this.usedTextures=[]}}class g extends f{constructor(t){super(t,m),this.vertex=0,this.drawType=t.gl.TRIANGLE_FAN,this.initDefaultShader("precision mediump float;\r\n\r\nattribute vec2 aPosition;\r\nattribute vec4 aColor;\r\nvarying vec4 vColor;\r\nuniform mat4 uProjectionMatrix;\r\nuniform vec4 uColor;\r\n\r\nvoid main(void) {\r\n gl_Position = uProjectionMatrix * vec4(aPosition, 0.0, 1.0);\r\n vColor = aColor;\r\n}\r\n","precision mediump float;\r\n\r\nvarying vec4 vColor;\r\nvoid main(void) {\r\n gl_FragColor = vColor;//vColor;\r\n}\r\n")}startRender(){this.vertex=0,this.webglArrayBuffer.clear()}addVertex(t,e,r){this.webglArrayBuffer.resize(3),super.addVertex(t,e),this.webglArrayBuffer.pushUint(r),this.vertex+=1}drawCircle(t,e,r,i){const s=2*Math.PI/30;this.startRender(),this.addVertex(t,e,i);for(let n=0;n<=30;n++){const h=n*s,a=t+r*Math.cos(h),o=e+r*Math.sin(h);this.addVertex(a,o,i)}this.executeRender()}executeRender(){super.executeRender();this.gl.drawArrays(this.drawType,0,this.vertex),this.drawType=this.rapid.gl.TRIANGLE_FAN,this.vertex=0}}const m=[{name:"aPosition",size:2,type:r,stride:12},{name:"aColor",size:4,type:5121,stride:12,offset:2*Float32Array.BYTES_PER_ELEMENT,normalized:!0}];class x extends h{constructor(t,e){super(t,6,4,e)}addObject(t){super.addObject(),this.push(t),this.push(t+3),this.push(t+2),this.push(t),this.push(t+1),this.push(t+2)}}class y extends f{constructor(t){const e=t.gl;super(t,T),this.batchSprite=0,this.initDefaultShader("precision mediump float;\r\n\r\nattribute vec2 aPosition;\r\nattribute vec2 aRegion;\r\nattribute float aTextureId;\r\nattribute vec4 aColor;\r\n\r\nuniform mat4 uProjectionMatrix;\r\n\r\nvarying vec2 vRegion;\r\nvarying float vTextureId;\r\nvarying vec4 vColor;\r\n\r\nvoid main(void) {\r\n vRegion = aRegion;\r\n vTextureId = aTextureId;\r\n vColor = aColor;\r\n gl_Position = uProjectionMatrix * vec4(aPosition, 0.0, 1.0);\r\n}","precision mediump float;\r\nuniform sampler2D uTextures[%TEXTURE_NUM%];\r\n\r\nvarying vec2 vRegion;\r\nvarying float vTextureId;\r\nvarying vec4 vColor;\r\n\r\nvoid main(void) {\r\n vec4 color;\r\n %GET_COLOR%\r\n\r\n gl_FragColor = color*vColor;\r\n}"),this.MAX_BATCH=Math.floor(16384),this.indexBuffer=new x(e,this.MAX_BATCH)}addVertex(t,e,r,i,s,n){super.addVertex(t,e),this.webglArrayBuffer.push(r),this.webglArrayBuffer.push(i),this.webglArrayBuffer.push(s),this.webglArrayBuffer.pushUint(n)}renderSprite(t,e,r,i,s,n,h,a,o,u,l){var d;l&&(null===(d=this.currentShader)||void 0===d||d.setUniforms(l,1)),this.batchSprite>=this.MAX_BATCH&&this.render(),this.batchSprite++,this.webglArrayBuffer.resize(24);const c=this.useTexture(t),p=a+e,f=o+r,g=i+n,m=s+h;this.addVertex(a,o,i,s,c,u),this.addVertex(p,o,g,s,c,u),this.addVertex(p,f,g,m,c,u),this.addVertex(a,f,i,m,c,u)}executeRender(){super.executeRender();const t=this.gl;t.drawElements(t.TRIANGLES,6*this.batchSprite,t.UNSIGNED_SHORT,0)}enterRegion(t){super.enterRegion(t),this.indexBuffer.bindBuffer(),this.gl.uniform1iv(this.currentShader.uniformLoc.uTextures,this.TEXTURE_UNITS_ARRAY)}initializeForNextRender(){super.initializeForNextRender(),this.batchSprite=0}}const T=[{name:"aPosition",size:2,type:r,stride:24},{name:"aRegion",size:2,type:r,stride:24,offset:2*Float32Array.BYTES_PER_ELEMENT},{name:"aTextureId",size:1,type:r,stride:24,offset:4*Float32Array.BYTES_PER_ELEMENT},{name:"aColor",size:4,type:5121,stride:24,offset:5*Float32Array.BYTES_PER_ELEMENT,normalized:!0}];var E,b;t.JoinTyps=void 0,(E=t.JoinTyps||(t.JoinTyps={}))[E.BEVEL=0]="BEVEL",E[E.ROUND=1]="ROUND",E[E.MITER=2]="MITER",t.CapTyps=void 0,(b=t.CapTyps||(t.CapTyps={}))[b.BUTT=0]="BUTT",b[b.ROUND=1]="ROUND",b[b.SQUARE=2]="SQUARE";const A=1e-4,R=(t,e,r,i)=>{i.push(t),i.push(o.Add(t,r)),i.push(o.Add(e,r)),i.push(e),i.push(o.Add(e,r)),i.push(t)},S=(t,e,r,i,s)=>{const n=o.Sub(t,e).length();let h=Math.atan2(r.y-t.y,r.x-t.x),a=Math.atan2(e.y-t.y,e.x-t.x);const u=h;a>h?a-h>=Math.PI-A&&(a-=2*Math.PI):h-a>=Math.PI-A&&(h-=2*Math.PI);let l=a-h;if(Math.abs(l)>=Math.PI-A&&Math.abs(l)<=Math.PI+A){const e=o.Sub(t,i);0===e.x?e.y>0&&(l=-l):e.x>=-1e-4&&(l=-l)}const d=(Math.abs(l*n)/7|0)+1,c=l/d;for(let e=0;e<d;e++)s.push(new o(t.x,t.y)),s.push(new o(t.x+n*Math.cos(u+c*e),t.y+n*Math.sin(u+c*e))),s.push(new o(t.x+n*Math.cos(u+c*(1+e)),t.y+n*Math.sin(u+c*(1+e))))},w=(e,r,i,s,n,h,a)=>{const u=o.Sub(r,e).perpendicular(),l=o.Sub(i,r).perpendicular();((t,e,r)=>(e.x-t.x)*(r.y-t.y)-(r.x-t.x)*(e.y-t.y))(e,r,i)>0&&(u.invert(),l.invert()),u.normalize().scalarMult(n),l.normalize().scalarMult(n);const d=((t,e,r,i)=>{const s=e.y-t.y,n=t.x-e.x,h=i.y-r.y,a=r.x-i.x,u=s*a-h*n;if(u>-1e-4&&u<A)return null;{const e=s*t.x+n*t.y,i=h*r.x+a*r.y;return new o((a*e-n*i)/u,(s*i-h*e)/u)}})(o.Add(u,e),o.Add(u,r),o.Add(l,i),o.Add(l,r));let c=null,p=Number.MAX_VALUE;d&&(c=o.Sub(d,r),p=c.length());const f=p/n|0,g=o.Sub(e,r).length(),m=o.Sub(r,i).length();if(p>g||p>m)s.push(o.Add(e,u)),s.push(o.Sub(e,u)),s.push(o.Add(r,u)),s.push(o.Sub(e,u)),s.push(o.Add(r,u)),s.push(o.Sub(r,u)),h===t.JoinTyps.ROUND?S(r,o.Add(r,u),o.Add(r,l),i,s):h===t.JoinTyps.BEVEL||h===t.JoinTyps.MITER&&f>=a?(s.push(r),s.push(o.Add(r,u)),s.push(o.Add(r,l))):h===t.JoinTyps.MITER&&f<a&&d&&(s.push(o.Add(r,u)),s.push(r),s.push(d),s.push(o.Add(r,l)),s.push(r),s.push(d)),s.push(o.Add(i,l)),s.push(o.Sub(r,l)),s.push(o.Add(r,l)),s.push(o.Add(i,l)),s.push(o.Sub(r,l)),s.push(o.Sub(i,l));else{if(s.push(o.Add(e,u)),s.push(o.Sub(e,u)),s.push(o.Sub(r,c)),s.push(o.Add(e,u)),s.push(o.Sub(r,c)),s.push(o.Add(r,u)),h===t.JoinTyps.ROUND){const t=o.Add(r,u),e=o.Add(r,l),i=o.Sub(r,c),n=r;s.push(t),s.push(n),s.push(i),S(n,t,e,i,s),s.push(n),s.push(e),s.push(i)}else(h===t.JoinTyps.BEVEL||h===t.JoinTyps.MITER&&f>=a)&&(s.push(o.Add(r,u)),s.push(o.Add(r,l)),s.push(o.Sub(r,c))),h===t.JoinTyps.MITER&&f<a&&(s.push(d),s.push(o.Add(r,u)),s.push(o.Add(r,l)));s.push(o.Add(i,l)),s.push(o.Sub(r,c)),s.push(o.Add(r,l)),s.push(o.Add(i,l)),s.push(o.Sub(r,c)),s.push(o.Sub(i,l))}};return t.BaseTexture=l,t.Color=a,t.DynamicArrayBuffer=i,t.GLShader=p,t.MatrixStack=n,t.Rapid=class{constructor(t){this.projectionDirty=!0,this.matrixStack=new n,this.textures=new u(this),this.devicePixelRatio=window.devicePixelRatio||1,this.defaultColor=new a(255,255,255,255),this.defaultColorBlack=new a(0,0,0,255),this.regions=new Map;const e=(t=>{const e=t.getContext("webgl2")||t.getContext("webgl");if(!e)throw new Error("TODO");return e})(t.canvas);this.gl=e,this.canvas=t.canvas,this.maxTextureUnits=e.getParameter(this.gl.MAX_TEXTURE_IMAGE_UNITS),this.width=t.width||this.canvas.width,this.height=t.width||this.canvas.height,this.backgroundColor=t.backgroundColor||new a(255,255,255,255),this.registerBuildInRegion(),this.initWebgl(e)}initWebgl(t){this.resize(this.width,this.height),t.enable(t.BLEND),t.disable(t.DEPTH_TEST),t.blendFunc(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA)}registerBuildInRegion(){this.registerRegion("sprite",y),this.registerRegion("graphic",g)}registerRegion(t,e){this.regions.set(t,new e(this))}setRegion(t,e){if(t!=this.currentRegionName||e&&e!==this.currentRegion.currentShader){const r=this.regions.get(t);this.currentRegion&&(this.currentRegion.render(),this.currentRegion.exitRegion()),this.currentRegion=r,this.currentRegionName=t,r.enterRegion(e)}}save(){this.matrixStack.pushMat()}restore(){this.matrixStack.popMat()}startRender(t=!0){t&&this.matrixStack.clear(),this.matrixStack.pushIdentity(),this.currentRegion=void 0,this.currentRegionName=void 0}endRender(){var t;null===(t=this.currentRegion)||void 0===t||t.render(),this.projectionDirty=!1}renderSprite(t,e=0,r=0,i){if(t.base){if(i instanceof a)return this.renderSprite(t,e,r,{color:i});this.setRegion("sprite",null==i?void 0:i.shader),this.currentRegion.renderSprite(t.base.texture,t.width,t.height,t.clipX,t.clipY,t.clipW,t.clipH,e,r,((null==i?void 0:i.color)||this.defaultColor).uint32,null==i?void 0:i.uniforms)}}renderLine(e=0,r=0,i){const s=((e,r)=>{if(e.length<2)return[];let i=r.cap||t.CapTyps.BUTT,s=r.join||t.JoinTyps.BEVEL,n=(r.width||1)/2,h=r.miterLimit||10,a=[],u=[];if(2===e.length)s=t.JoinTyps.BEVEL,w(e[0],o.Middle(e[0],e[1]),e[1],a,n,s,h);else{for(let t=0;t<e.length-1;t++)0===t?u.push(e[0]):t===e.length-2?u.push(e[e.length-1]):u.push(o.Middle(e[t],e[t+1]));for(let t=1;t<u.length;t++)w(u[t-1],e[t],u[t],a,n,s,h)}if(i===t.CapTyps.ROUND){let t=a[0],r=a[1],i=e[1],s=a[a.length-1],n=a[a.length-3],h=e[e.length-2];S(e[0],t,r,i,a),S(e[e.length-1],s,n,h,a)}else if(i===t.CapTyps.SQUARE){let t=a[a.length-1],r=a[a.length-3];R(a[0],a[1],o.Sub(e[0],e[1]).normalize().scalarMult(o.Sub(e[0],a[0]).length()),a),R(t,r,o.Sub(e[e.length-1],e[e.length-2]).normalize().scalarMult(o.Sub(r,e[e.length-1]).length()),a)}return a})(i.points,i);this.renderGraphic(e,r,{color:i.color,drawType:this.gl.TRIANGLES,points:s})}renderGraphic(t=0,e=0,r){if(r instanceof Array)return this.renderGraphic(t,e,{points:r});this.startGraphicDraw(),r.drawType&&(this.currentRegion.drawType=r.drawType),r.points.forEach((i=>{this.addGraphicVertex(i.x+t,i.y+e,r.color||this.defaultColorBlack)})),this.endGraphicDraw()}startGraphicDraw(t){this.setRegion("graphic",t),this.currentRegion.startRender()}addGraphicVertex(t,e,r){if(t instanceof o)return this.addGraphicVertex(t.x,t.y,e);this.currentRegion.addVertex(t,e,r.uint32)}endGraphicDraw(){this.currentRegion.render()}resize(t,e){this.width=t,this.height=e;const r=t*this.devicePixelRatio,i=e*this.devicePixelRatio;this.canvas.width=r,this.canvas.height=i,this.gl.viewport(0,0,r,i),this.projection=this.createOrthMatrix(0,t,e,0),this.projectionDirty=!0}clear(){const t=this.gl,e=this.backgroundColor;t.clearColor(e.r,e.g,e.b,e.a),t.clear(t.COLOR_BUFFER_BIT)}createOrthMatrix(t,e,r,i){return new Float32Array([2/(e-t),0,0,0,0,2/(i-r),0,0,0,0,-1,0,-(e+t)/(e-t),-(i+r)/(i-r),0,1])}transformPoint(t,e){return this.matrixStack.apply(t,e)}},t.SCALEFACTOR=2,t.Text=c,t.Texture=d,t.TextureCache=u,t.Vec2=o,t.WebglBufferArray=s,t.WebglElementBufferArray=h,t.graphicAttributes=m,t.spriteAttributes=T,t}({});
|
|
1
|
+
var rapid=function(t){"use strict";var e,i,s,r,n,a,o,h;t.ScaleRadio=void 0,(e=t.ScaleRadio||(t.ScaleRadio={})).KEEP="keep",e.KEEP_H="keep_h",e.KEEP_W="keep_w",e.IGNORE="ignore",e.EXPAND="expand",t.LineTextureMode=void 0,(i=t.LineTextureMode||(t.LineTextureMode={})).STRETCH="stretch",i.REPEAT="repeat",t.TextureWrapMode=void 0,(s=t.TextureWrapMode||(t.TextureWrapMode={})).REPEAT="repeat",s.CLAMP="clamp",s.MIRROR="mirror",t.MaskType=void 0,(r=t.MaskType||(t.MaskType={})).Include="normal",r.Exclude="inverse",t.TilemapShape=void 0,(n=t.TilemapShape||(t.TilemapShape={})).SQUARE="square",n.ISOMETRIC="isometric",t.ShaderType=void 0,(a=t.ShaderType||(t.ShaderType={})).SPRITE="sprite",a.GRAPHIC="graphic",t.BlendMode=void 0,(o=t.BlendMode||(t.BlendMode={})).Additive="additive",o.Subtractive="subtractive",o.Mix="mix",t.ParticleShape=void 0,(h=t.ParticleShape||(t.ParticleShape={})).POINT="point",h.CIRCLE="circle",h.RECT="rect";var l;t.ArrayType=void 0,(l=t.ArrayType||(t.ArrayType={}))[l.Float32=0]="Float32",l[l.Uint32=1]="Uint32",l[l.Uint16=2]="Uint16";class u{constructor(t){this.usedElemNum=0,this.maxElemNum=512,this.bytePerElem=this.getArrayType(t).BYTES_PER_ELEMENT,this.arrayType=t,this.arraybuffer=new ArrayBuffer(this.maxElemNum*this.bytePerElem),this.updateTypedArray()}getArrayType(e){switch(e){case t.ArrayType.Float32:return Float32Array;case t.ArrayType.Uint32:return Uint32Array;case t.ArrayType.Uint16:return Uint16Array}}updateTypedArray(){switch(this.uint32=new Uint32Array(this.arraybuffer),this.float32=new Float32Array(this.arraybuffer),this.uint16=new Uint16Array(this.arraybuffer),this.arrayType){case t.ArrayType.Float32:this.typedArray=this.float32;break;case t.ArrayType.Uint32:this.typedArray=this.uint32;break;case t.ArrayType.Uint16:this.typedArray=this.uint16}}clear(){this.usedElemNum=0}resize(t=0){if((t+=this.usedElemNum)>this.maxElemNum){for(;t>this.maxElemNum;)this.maxElemNum<<=1;this.setMaxSize(this.maxElemNum)}}setMaxSize(t=this.maxElemNum){const e=this.typedArray;this.maxElemNum=t,this.arraybuffer=new ArrayBuffer(t*this.bytePerElem),this.updateTypedArray(),this.typedArray.set(e)}pushUint32(t){this.uint32[this.usedElemNum++]=t}pushFloat32(t){this.float32[this.usedElemNum++]=t}pushUint16(t){this.uint16[this.usedElemNum++]=t}pop(t){this.usedElemNum-=t}getArray(t=0,e){return null==e?this.typedArray:this.typedArray.subarray(t,e)}get length(){return this.typedArray.length}}class c extends u{constructor(t,e,i=t.ARRAY_BUFFER,s=t.STATIC_DRAW){super(e),this.dirty=!0,this.webglBufferSize=0,this.gl=t,this.buffer=t.createBuffer(),this.type=i,this.usage=s}pushFloat32(t){super.pushFloat32(t),this.dirty=!0}pushUint32(t){super.pushUint32(t),this.dirty=!0}pushUint16(t){super.pushUint16(t),this.dirty=!0}bindBuffer(){this.gl.bindBuffer(this.type,this.buffer)}bufferData(){if(this.dirty){const t=this.gl;this.maxElemNum>this.webglBufferSize?(t.bufferData(this.type,this.getArray(),this.usage),this.webglBufferSize=this.maxElemNum):t.bufferSubData(this.type,0,this.getArray(0,this.usedElemNum)),this.dirty=!1}}}class d extends u{constructor(){super(t.ArrayType.Float32)}pushMat(){const t=this.usedElemNum-6,e=this.typedArray;this.resize(6),this.pushFloat32(e[t+0]),this.pushFloat32(e[t+1]),this.pushFloat32(e[t+2]),this.pushFloat32(e[t+3]),this.pushFloat32(e[t+4]),this.pushFloat32(e[t+5])}popMat(){this.pop(6)}pushIdentity(){this.resize(6),this.pushFloat32(1),this.pushFloat32(0),this.pushFloat32(0),this.pushFloat32(1),this.pushFloat32(0),this.pushFloat32(0)}translate(t,e){if("number"!=typeof t)return this.translate(t.x,t.y);const i=this.usedElemNum-6,s=this.typedArray;s[i+4]=s[i+0]*t+s[i+2]*e+s[i+4],s[i+5]=s[i+1]*t+s[i+3]*e+s[i+5]}rotate(t){const e=this.usedElemNum-6,i=this.typedArray,s=Math.cos(t),r=Math.sin(t),n=i[e+0],a=i[e+1],o=i[e+2],h=i[e+3];i[e+0]=n*s-a*r,i[e+1]=n*r+a*s,i[e+2]=o*s-h*r,i[e+3]=o*r+h*s}scale(t,e){if("number"!=typeof t)return this.scale(t.x,t.y);e||(e=t);const i=this.usedElemNum-6,s=this.typedArray;s[i+0]=s[i+0]*t,s[i+1]=s[i+1]*t,s[i+2]=s[i+2]*e,s[i+3]=s[i+3]*e}apply(t,e){if("number"!=typeof t)return new m(...this.apply(t.x,t.y));const i=this.usedElemNum-6,s=this.typedArray;return[s[i+0]*t+s[i+2]*e+s[i+4],s[i+1]*t+s[i+3]*e+s[i+5]]}getInverse(){const t=this.usedElemNum-6,e=this.typedArray,i=e[t+0],s=e[t+1],r=e[t+2],n=e[t+3],a=e[t+4],o=e[t+5],h=i*n-s*r;return new Float32Array([n/h,-s/h,-r/h,i/h,(r*o-n*a)/h,(s*a-i*o)/h])}getTransform(){const t=this.usedElemNum-6,e=this.typedArray;return new Float32Array([e[t+0],e[t+1],e[t+2],e[t+3],e[t+4],e[t+5]])}setTransform(t){const e=this.usedElemNum-6,i=this.typedArray;i[e+0]=t[0],i[e+1]=t[1],i[e+2]=t[2],i[e+3]=t[3],i[e+4]=t[4],i[e+5]=t[5]}getGlobalPosition(){const t=this.usedElemNum-6,e=this.typedArray;return new m(e[t+4],e[t+5])}setGlobalPosition(t,e){if("number"!=typeof t)return void this.setGlobalPosition(t.x,t.y);const i=this.usedElemNum-6,s=this.typedArray;s[i+4]=t,s[i+5]=e}getGlobalRotation(){const t=this.usedElemNum-6,e=this.typedArray;return Math.atan2(e[t+1],e[t+0])}setGlobalRotation(t){const e=this.usedElemNum-6,i=this.typedArray,s=this.getGlobalScale(),r=Math.cos(t),n=Math.sin(t);i[e+0]=r*s.x,i[e+1]=n*s.x,i[e+2]=-n*s.y,i[e+3]=r*s.y}getGlobalScale(){const t=this.usedElemNum-6,e=this.typedArray,i=Math.sqrt(e[t+0]*e[t+0]+e[t+1]*e[t+1]),s=Math.sqrt(e[t+2]*e[t+2]+e[t+3]*e[t+3]);return new m(i,s)}setGlobalScale(t,e){if("number"!=typeof t)return void this.setGlobalScale(t.x,t.y);const i=this.getGlobalRotation(),s=Math.cos(i),r=Math.sin(i),n=this.usedElemNum-6,a=this.typedArray;a[n+0]=s*t,a[n+1]=r*t,a[n+2]=-r*e,a[n+3]=s*e}globalToLocal(t){const e=this.getInverse();return new m(e[0]*t.x+e[2]*t.y+e[4],e[1]*t.x+e[3]*t.y+e[5])}localToGlobal(t){return this.apply(t)}toCSSTransform(){const t=this.usedElemNum-6,e=this.typedArray;return`matrix(${e[t+0]}, ${e[t+1]}, ${e[t+2]}, ${e[t+3]}, ${e[t+4]}, ${e[t+5]})`}identity(){const t=this.usedElemNum-6,e=this.typedArray;e[t+0]=1,e[t+1]=0,e[t+2]=0,e[t+3]=1,e[t+4]=0,e[t+5]=0}applyTransform(t,e=0,i=0){(t.saveTransform??1)&&this.pushMat(),t.afterSave&&t.afterSave();const s=t.x||0,r=t.y||0;(s||r)&&this.translate(s,r),t.position&&this.translate(t.position),t.rotation&&this.rotate(t.rotation),t.scale&&this.scale(t.scale);let n=t.offsetX||0,a=t.offsetY||0;t.offset&&(n+=t.offset.x,a+=t.offset.y);const o=t.origin;return o&&("number"==typeof o?(n-=o*e,a-=o*i):(n-=o.x*e,a-=o.y*i)),{offsetX:n,offsetY:a}}applyTransformAfter(t){t.beforRestore&&t.beforRestore(),(t.restoreTransform??1)&&this.popMat()}}class p extends c{constructor(e,i,s,r){super(e,t.ArrayType.Uint16,e.ELEMENT_ARRAY_BUFFER,e.STATIC_DRAW),this.setMaxSize(i*r);for(let t=0;t<r;t++)this.addObject(t*s);this.bindBuffer(),this.bufferData()}addObject(t){}}class f{constructor(t,e,i,s=255){this._r=t,this._g=e,this._b=i,this._a=s,this.updateUint()}get r(){return this._r}set r(t){this._r=t,this.updateUint()}get g(){return this._g}set g(t){this._g=t,this.updateUint()}get b(){return this._b}set b(t){this._b=t,this.updateUint()}get a(){return this._a}set a(t){this._a=t,this.updateUint()}updateUint(){this.uint32=(this._a<<24|this._b<<16|this._g<<8|this._r)>>>0}setRGBA(t,e,i,s){this.r=t,this.g=e,this.b=i,this.a=s,this.updateUint()}copy(t){this.setRGBA(t.r,t.g,t.b,t.a)}clone(){return new f(this._r,this._g,this._b,this._a)}equal(t){return t.r===this.r&&t.g===this.g&&t.b===this.b&&t.a===this.a}static fromHex(t){t.startsWith("#")&&(t=t.slice(1));const e=parseInt(t.slice(0,2),16),i=parseInt(t.slice(2,4),16),s=parseInt(t.slice(4,6),16);let r=255;return t.length>=8&&(r=parseInt(t.slice(6,8),16)),new f(e,i,s,r)}add(t){return new f(Math.min(this.r+t.r,255),Math.min(this.g+t.g,255),Math.min(this.b+t.b,255),Math.min(this.a+t.a,255))}subtract(t){return new f(Math.max(0,this.r-t.r),Math.max(0,this.g-t.g),Math.max(0,this.b-t.b),Math.max(0,this.a-t.a))}divide(t){return t instanceof f?new f(this.r/t.r,this.g/t.g,this.b/t.b,this.a/t.a):new f(this.r/t,this.g/t,this.b/t,this.a/t)}multiply(t){return t instanceof f?new f(this.r*t.r,this.g*t.g,this.b*t.b,this.a*t.a):new f(this.r*t,this.g*t,this.b*t,this.a*t)}clamp(){this.r=Math.max(0,Math.min(255,this.r)),this.g=Math.max(0,Math.min(255,this.g)),this.b=Math.max(0,Math.min(255,this.b)),this.a=Math.max(0,Math.min(255,this.a))}}f.Red=new f(255,0,0,255),f.Green=new f(0,255,0,255),f.Blue=new f(0,0,255,255),f.Yellow=new f(255,255,0,255),f.Purple=new f(128,0,128,255),f.Orange=new f(255,165,0,255),f.Pink=new f(255,192,203,255),f.Gray=new f(128,128,128,255),f.Brown=new f(139,69,19,255),f.Cyan=new f(0,255,255,255),f.Magenta=new f(255,0,255,255),f.Lime=new f(192,255,0,255),f.White=new f(255,255,255,255),f.Black=new f(0,0,0,255),f.TRANSPARENT=new f(0,0,0,0);class m{constructor(t,e){this.x=void 0!==t?t:0,this.y=void 0!==e?e:0}set(t,e){return Array.isArray(t)?(this.x=t[0],this.y=t[0]):e?(this.x=t,this.y=e):(this.x=t,this.y=t),this}add(t){return new m(this.x+t.x,this.y+t.y)}subtract(t){return new m(this.x-t.x,this.y-t.y)}multiply(t){return t instanceof m?new m(this.x*t.x,this.y*t.y):new m(this.x*t,this.y*t)}divide(t){return t instanceof m?new m(this.x/t.x,this.y/t.y):new m(this.x/t,this.y/t)}dot(t){return this.x*t.x+this.y*t.y}cross(t){return this.x*t.y-this.y*t.x}distanceTo(t){const e=this.x-t.x,i=this.y-t.y;return Math.sqrt(e*e+i*i)}clone(){return new m(this.x,this.y)}copy(t){this.x=t.x,this.y=t.y}equal(t){return t.x==this.x&&t.y==this.y}perpendicular(){const t=this.x;return this.x=-this.y,this.y=t,this}invert(){return this.x=-this.x,this.y=-this.y,this}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}normalize(){const t=this.length();return this.x=this.x/t||0,this.y=this.y/t||0,this}angle(){return Math.atan2(this.y,this.x)}middle(t){return new m((this.x+t.x)/2,(this.y+t.y)/2)}abs(){return new m(Math.abs(this.x),Math.abs(this.y))}floor(){return new m(Math.floor(this.x),Math.floor(this.y))}ceil(){return new m(Math.ceil(this.x),Math.ceil(this.y))}snap(t){return new m(Math.round(this.x/t)*t,Math.round(this.y/t)*t)}stringify(){return`Vec2(${this.x}, ${this.y})`}static FromArray(t){return t.map((t=>new m(t[0],t[1])))}static fromAngle(t){return new m(Math.cos(t),Math.sin(t))}angleBetween(t){const e=this.dot(t),i=this.length()*t.length(),s=Math.max(-1,Math.min(1,e/i));return Math.acos(s)}}m.ZERO=new m(0,0),m.ONE=new m(1,1),m.UP=new m(0,1),m.DOWN=new m(0,-1),m.LEFT=new m(-1,0),m.RIGHT=new m(1,0);class g{static float(t,e){return Math.random()*(e-t)+t}static int(t,e){return Math.floor(Math.random()*(e-t+1))+t}static angle(){return Math.random()*Math.PI*2}static vector(t,e,i,s){return new m(g.float(t,e),g.float(i,s))}static direction(t){const e=g.angle();return new m(Math.cos(e)*t,Math.sin(e)*t)}static randomColor(t,e){return new f(g.float(t.r,e.r),g.float(t.g,e.g),g.float(t.b,e.b),g.float(t.a,e.a))}static pick(t){return t[g.int(0,t.length-1)]}static pickWeight(t){if(!t||0===t.length)return null;let e=0;for(const i of t)e+=i[1];const i=Math.random()*e;let s=0;for(const e of t)if(s+=e[1],i<=s)return e[0];return t[t.length-1][0]}static scalarOrRange(t,e){if(void 0===t)return e;if(Array.isArray(t)){if("number"==typeof t[0])return g.float(t[0],t[1]);if(t[0]instanceof m)return g.vector(t[0].x,t[1].x,t[0].y,t[1].y);if(t[0]instanceof f)return g.randomColor(t[0],t[1])}return"number"==typeof t?t:t.clone()}}class y{constructor(t){this.render=t}createLightShadowMaskPolygon(t,e,i){const s=[];t.forEach((t=>{for(let e=0;e<t.length;e++){const i=t[e],r=t[(e+1)%t.length];s.push([i,r])}})),i=i||Math.sqrt(Math.pow(this.render.width,2)+Math.pow(this.render.height,2));const r=[];return s.forEach((([t,s])=>{const n=new m(t.x-e.x,t.y-e.y),a=new m(s.x-e.x,s.y-e.y),o=s.subtract(t).perpendicular(),h=Math.abs(o.dot(n))/(o.length()*n.length())+.01,l=Math.abs(o.dot(a))/(o.length()*a.length())+.01,u=i/h,c=i/l,d=new m(n.x,n.y).normalize(),p=new m(a.x,a.y).normalize(),f=new m(t.x+d.x*u,t.y+d.y*u),g=new m(s.x+p.x*c,s.y+p.y*c);r.push([t,s,g,f])})),r}}const x=(t,e,i,s)=>{const r=[],n=s?Math.atan2(e.y,e.x):Math.atan2(-e.y,-e.x),a=Math.PI;for(let e=0;e<10;e++){const s=n+e/10*a,o=n+(e+1)/10*a,h=Math.cos(s)*i,l=Math.sin(s)*i,u=Math.cos(o)*i,c=Math.sin(o)*i;r.push(t),r.push(t.add(new m(h,l))),r.push(t.add(new m(u,c)))}return r},T=e=>{const i=e.points;if(i.length<2)return{vertices:[],uv:[]};const{normals:s,length:r}=((t,e=!1)=>{const i=[];if(t.length<2||e&&t.length<3)return{normals:i,length:0};const s=t.length;let r=0;if(e)for(let e=0;e<s;e++){const i=t[e],n=t[(e+1)%s];r+=i.distanceTo(n)}else for(let e=0;e<s-1;e++)r+=t[e].distanceTo(t[e+1]);const n=(t,e,i)=>{const s=e.subtract(t).normalize(),r=e.subtract(i).normalize(),n=r.dot(s);if(n<-.999)return{normal:s.perpendicular(),miters:1};{let t=r.add(s).normalize();s.cross(r)<0&&(t=t.multiply(-1));let e=1/Math.sqrt((1-n)/2);return{normal:t,miters:Math.min(e,4)}}};if(e){for(let e=0;e<s-1;e++){const r=0===e?t[s-2]:t[e-1],a=t[e],o=t[e+1];i.push(n(r,a,o))}i.push(i[0])}else for(let e=0;e<s;e++)if(0===e){const e=t[1].subtract(t[0]).normalize();i.push({normal:e.perpendicular(),miters:1})}else if(e===s-1){const s=t[e].subtract(t[e-1]).normalize();i.push({normal:s.perpendicular(),miters:1})}else i.push(n(t[e-1],t[e],t[e+1]));return{normals:i,length:r}})(i,e.closed),n=(e.width||1)/2,a=[],o=[],h=e.roundCap||!1,l=e.textureMode||t.LineTextureMode.STRETCH;let u=0;const c=e.texture?.width||1;for(let e=0;e<i.length-1;e++){const h=i[e],d=s[e].normal,p=s[e].miters,f=h.add(d.multiply(p*n)),g=h.subtract(d.multiply(p*n)),y=i[e+1],x=s[e+1].normal,T=s[e+1].miters,w=y.add(x.multiply(T*n)),b=y.subtract(x.multiply(T*n)),E=h.distanceTo(y);let R=0,v=0;l===t.LineTextureMode.STRETCH?(R=u/r,v=(u+E)/r):(R=u/c,v=R+E/c);const S=new m(R,0),A=new m(R,1),M=new m(v,0),C=new m(v,1);a.push(f),o.push(S),a.push(g),o.push(A),a.push(w),o.push(M),a.push(w),o.push(M),a.push(b),o.push(C),a.push(g),o.push(A),u+=E}if(h&&!e.closed){const t=i[0],e=s[0].normal,r=x(t,e,n,!0);a.push(...r);const o=i[i.length-1],h=s[i.length-1].normal,l=x(o,h,n,!1);a.push(...l)}return{vertices:a,uv:o}};var w="precision mediump float;\r\nvarying vec2 vRegion;\r\nvarying vec4 vColor;\r\n\r\nuniform sampler2D uTexture;\r\nuniform int uUseTexture;\r\n\r\nvoid main(void) {\r\n vec4 color;\r\n if(uUseTexture > 0){\r\n color = texture2D(uTexture, vRegion) * vColor;\r\n }else{\r\n color = vColor;\r\n }\r\n // fragment\r\n gl_FragColor = color;\r\n}\r\n",b="precision mediump float;\r\n\r\nattribute vec2 aPosition;\r\nattribute vec4 aColor;\r\nattribute vec2 aRegion;\r\n\r\nvarying vec4 vColor;\r\nuniform mat4 uProjectionMatrix;\r\nuniform vec4 uColor;\r\nvarying vec2 vRegion;\r\n\r\nvoid main(void) {\r\n // vertex s\r\n gl_Position = uProjectionMatrix * vec4(aPosition, 0.0, 1.0);\r\n // vertex e\r\n vColor = aColor;\r\n vRegion = aRegion;\r\n}\r\n";const E=(t,e,i)=>{const s=t.createShader(i);if(!s)throw new Error("Unable to create webgl shader");t.shaderSource(s,e),t.compileShader(s);if(!t.getShaderParameter(s,t.COMPILE_STATUS)){const i=t.getShaderInfoLog(s);throw console.error("Shader compilation failed:",i),new Error("Unable to compile shader: "+i+e)}return s};function R(t,e,i,s=!1,r=!1,n="clamp"){const a=t.createTexture();if(!a)throw new Error("unable to create texture");let o;switch(t.bindTexture(t.TEXTURE_2D,a),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,i?t.LINEAR:t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,i?t.LINEAR:t.NEAREST),n){case"repeat":o=t.REPEAT;break;case"mirror":o=t.MIRRORED_REPEAT;break;default:o=t.CLAMP_TO_EDGE}return t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,o),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,o),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,r),s?t.texImage2D(t.TEXTURE_2D,0,t.RGBA,e.width,e.height,0,t.RGBA,t.UNSIGNED_BYTE,null):t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),a}const v=5126;var S="precision mediump float;\r\nuniform sampler2D uTextures[%TEXTURE_NUM%];\r\n\r\nvarying vec2 vRegion;\r\nvarying float vTextureId;\r\nvarying vec4 vColor;\r\n\r\nvoid main(void) {\r\n vec4 color;\r\n %GET_COLOR%\r\n // fragment\r\n gl_FragColor = color * vColor;\r\n}",A="precision mediump float;\r\n\r\nattribute vec2 aPosition;\r\nattribute vec2 aRegion;\r\nattribute float aTextureId;\r\nattribute vec4 aColor;\r\n\r\nuniform mat4 uProjectionMatrix;\r\n\r\nvarying vec2 vRegion;\r\nvarying float vTextureId;\r\nvarying vec4 vColor;\r\n\r\nvoid main(void) {\r\n vRegion = aRegion;\r\n vTextureId = aTextureId;\r\n vColor = aColor;\r\n\r\n // vertex s\r\n gl_Position = uProjectionMatrix * vec4(aPosition, 0.0, 1.0);\r\n // vertex e\r\n}";const M=[{name:"aPosition",size:2,type:v,stride:24},{name:"aRegion",size:2,type:v,stride:24,offset:2*Float32Array.BYTES_PER_ELEMENT},{name:"aTextureId",size:1,type:v,stride:24,offset:4*Float32Array.BYTES_PER_ELEMENT},{name:"aColor",size:4,type:5121,stride:24,offset:5*Float32Array.BYTES_PER_ELEMENT,normalized:!0}],C=[{name:"aPosition",size:2,type:v,stride:20},{name:"aColor",size:4,type:5121,stride:20,offset:2*Float32Array.BYTES_PER_ELEMENT,normalized:!0},{name:"aRegion",size:2,type:v,stride:20,offset:3*Float32Array.BYTES_PER_ELEMENT}];class U{constructor(t,e,i,s,r=0){this.attributeLoc={},this.uniformLoc={},this.textureUnitNum=0,this.attributes=[];const n=function(t,e){if(t.includes("%TEXTURE_NUM%")&&(t=t.replace("%TEXTURE_NUM%",e.toString())),t.includes("%GET_COLOR%")){let i="";for(let t=0;t<e;t++)i+=0==t?`if(vTextureId == ${t}.0)`:t==e-1?"else":`else if(vTextureId == ${t}.0)`,i+=`{color = texture2D(uTextures[${t}], vRegion);}`;t=t.replace("%GET_COLOR%",i)}return t}(i,t.maxTextureUnits-r);this.program=((t,e,i)=>{var s=t.createProgram(),r=E(t,e,35633),n=E(t,i,35632);if(!s)throw new Error("Unable to create program shader");if(t.attachShader(s,r),t.attachShader(s,n),t.linkProgram(s),!t.getProgramParameter(s,t.LINK_STATUS)){const e=t.getProgramInfoLog(s);throw new Error("Unable to link shader program: "+e)}return s})(t.gl,e,n),this.gl=t.gl,this.textureUnitNum=r,this.parseShader(e),this.parseShader(n),s&&this.setAttributes(s)}setUniforms(t,e){const i=this.gl;for(const s of t.getUnifromNames()){const r=this.getUniform(s);t.bind(i,s,r,e)}}getUniform(t){return this.uniformLoc[t]}use(){this.gl.useProgram(this.program)}parseShader(t){const e=this.gl,i=t.match(/attribute\s+\w+\s+(\w+)/g);if(i)for(const t of i){const i=t.split(" ")[2],s=e.getAttribLocation(this.program,i);-1!=s&&(this.attributeLoc[i]=s)}const s=t.match(/uniform\s+\w+\s+(\w+)/g);if(s)for(const t of s){const i=t.split(" ")[2];this.uniformLoc[i]=e.getUniformLocation(this.program,i)}}setAttribute(t){const e=this.attributeLoc[t.name];if(void 0!==e){const i=this.gl;i.vertexAttribPointer(e,t.size,t.type,t.normalized||!1,t.stride,t.offset||0),i.enableVertexAttribArray(e)}}setAttributes(t){this.attributes=t;for(const e of t)this.setAttribute(e)}updateAttributes(){this.setAttributes(this.attributes)}static createCostumShader(e,i,s,r,n=0){let a={[t.ShaderType.SPRITE]:S,[t.ShaderType.GRAPHIC]:w}[r],o={[t.ShaderType.SPRITE]:A,[t.ShaderType.GRAPHIC]:b}[r];const h={[t.ShaderType.SPRITE]:M,[t.ShaderType.GRAPHIC]:C}[r];return a=a.replace("void main(void) {",s+"\nvoid main(void) {"),o=o.replace("void main(void) {",i+"\nvoid main(void) {"),a=a.replace("// fragment","fragment(color);"),o=o.replace(/\/\/ vertex s[\s\S]*?\/\/ vertex e/,"vec2 position = aPosition;\n vertex(position, vRegion);\n gl_Position = uProjectionMatrix * vec4(position, 0.0, 1.0);"),new U(e,o,a,h,n)}}class _{constructor(e){this.usedTextures=[],this.shaders=new Map,this.isCostumShader=!1,this.freeTextureUnitNum=0,this.rapid=e,this.gl=e.gl,this.webglArrayBuffer=new c(e.gl,t.ArrayType.Float32,e.gl.ARRAY_BUFFER,e.gl.STREAM_DRAW),this.maxTextureUnits=e.maxTextureUnits}getTextureUnitList(){return Array.from({length:this.maxTextureUnits},((t,e)=>e))}addVertex(t,e,...i){const[s,r]=this.rapid.matrixStack.apply(t,e);this.webglArrayBuffer.pushFloat32(s),this.webglArrayBuffer.pushFloat32(r)}useTexture(t){const e=this.usedTextures.indexOf(t);return-1==e?(this.usedTextures.push(t),this.freeTextureUnitNum=this.maxTextureUnits-this.usedTextures.length,[this.usedTextures.length-1,!0]):[e,!1]}enterRegion(t){this.currentShader=t??this.getShader("default"),this.currentShader.use(),this.initializeForNextRender(),this.webglArrayBuffer.bindBuffer(),this.currentShader.updateAttributes(),this.updateProjection(),this.isCostumShader=Boolean(t)}updateProjection(){this.gl.uniformMatrix4fv(this.currentShader.uniformLoc.uProjectionMatrix,!1,this.rapid.projection)}isUnifromChanged(t){return!!t&&(this.costumUnifrom!=t||!!t?.isDirty)}setCurrentUniform(t){t.clearDirty(),this.costumUnifrom=t}exitRegion(){}initDefaultShader(t,e,i){this.setShader("default",t,e,i)}setShader(t,e,i,s){this.webglArrayBuffer.bindBuffer(),this.shaders.set(t,new U(this.rapid,e,i,s)),"default"===t&&(this.defaultShader=this.shaders.get(t))}getShader(t){return this.shaders.get(t)}render(){this.executeRender(),this.initializeForNextRender()}executeRender(){const t=this.gl;for(let e=0;e<this.usedTextures.length;e++)t.activeTexture(t.TEXTURE0+e),t.bindTexture(t.TEXTURE_2D,this.usedTextures[e]);this.webglArrayBuffer.bufferData()}initializeForNextRender(){this.webglArrayBuffer.clear(),this.usedTextures.length=0,this.isCostumShader=!1,this.freeTextureUnitNum=this.maxTextureUnits}hasPendingContent(){return!1}isShaderChanged(t){return(t||this.defaultShader)!=this.currentShader}}class F extends _{constructor(t){super(t),this.vertex=0,this.offset=m.ZERO,this.drawType=t.gl.TRIANGLE_FAN,this.setShader("default",b,w,C)}startRender(t,e,i,s){s&&this.currentShader?.setUniforms(s,this),this.offset=new m(t,e),this.vertex=0,this.webglArrayBuffer.clear(),i&&i.base&&(this.texture=this.useTexture(i.base.texture)[0])}addVertex(t,e,i,s,r){this.webglArrayBuffer.resize(3),super.addVertex(t+this.offset.x,e+this.offset.y),this.webglArrayBuffer.pushUint32(r),this.webglArrayBuffer.pushFloat32(i),this.webglArrayBuffer.pushFloat32(s),this.vertex+=1}executeRender(){super.executeRender();const t=this.gl;t.uniform1i(this.currentShader.uniformLoc.uUseTexture,void 0===this.texture?0:1),this.texture&&t.uniform1i(this.currentShader.uniformLoc.uTexture,this.texture),t.drawArrays(this.drawType,0,this.vertex),this.drawType=this.rapid.gl.TRIANGLE_FAN,this.vertex=0,this.texture=void 0}}const P=Math.floor(16384);class L extends p{constructor(t,e){super(t,6,4,e)}addObject(t){super.addObject(),this.pushUint16(t),this.pushUint16(t+1),this.pushUint16(t+2),this.pushUint16(t),this.pushUint16(t+3),this.pushUint16(t+2)}}class D extends _{constructor(t){const e=t.gl;super(t),this.batchSprite=0,this.spriteTextureUnits=[],this.spriteTextureUnitIndexOffset=0,this.setShader("default",A,S,M),this.indexBuffer=new L(e,P)}addVertex(t,e,i,s,r,n){super.addVertex(t,e),this.webglArrayBuffer.pushFloat32(i),this.webglArrayBuffer.pushFloat32(s),this.webglArrayBuffer.pushFloat32(r),this.webglArrayBuffer.pushUint32(n)}renderSprite(t,e,i,s,r,n,a,o,h,l,u,c,d,p=0){(1+p>this.freeTextureUnitNum||this.batchSprite>=P||this.isUnifromChanged(u)||this.rapid.projectionDirty)&&(this.render(),u&&this.isUnifromChanged(u)&&(this.currentShader.setUniforms(u,this),this.setCurrentUniform(u)),this.rapid.projectionDirty&&this.updateProjection()),this.batchSprite++,this.webglArrayBuffer.resize(20);const[f,m]=this.useTexture(t);m&&(this.spriteTextureUnits.push(f),this.spriteTextureUnitIndexOffset=this.spriteTextureUnits[0]);const g=f-this.spriteTextureUnitIndexOffset,y=c?n:s,x=c?s:n,T=d?a:r,w=d?r:a,b=o,E=o+e,R=h,v=h+i;this.addVertex(b,R,y,T,g,l),this.addVertex(E,R,x,T,g,l),this.addVertex(E,v,x,w,g,l),this.addVertex(b,v,y,w,g,l)}executeRender(){if(super.executeRender(),this.batchSprite<=0)return;const t=this.gl;this.spriteTextureUnits.length>0&&this.gl.uniform1iv(this.currentShader.uniformLoc.uTextures,this.spriteTextureUnits),t.drawElements(t.TRIANGLES,6*this.batchSprite,t.UNSIGNED_SHORT,0)}enterRegion(t){super.enterRegion(t),this.indexBuffer.bindBuffer()}initializeForNextRender(){super.initializeForNextRender(),this.batchSprite=0,this.spriteTextureUnits.length=0}hasPendingContent(){return this.batchSprite>0}}class N{constructor(t,e){this.cache=new Map,this.render=t,this.antialias=e}async textureFromUrl(e,i=this.antialias,s=t.TextureWrapMode.CLAMP){let r=this.cache.get(e);if(!r){const t=await this.loadImage(e);r=I.fromImageSource(this.render,t,i,s),this.cache.set(e,r)}return new k(r)}textureFromFrameBufferObject(t){return new k(t)}textureFromSource(e,i=this.antialias,s=t.TextureWrapMode.CLAMP){let r=this.cache.get(e);return r||(r=I.fromImageSource(this.render,e,i,s),this.cache.set(e,r)),new k(r)}async loadImage(t){return new Promise((e=>{const i=new Image;i.onload=()=>{e(i)},i.src=t}))}createText(t){return new B(this.render,t)}destroy(t){t instanceof k?(t.base?.destroy(this.render.gl),this.removeCache(t)):(t.destroy(this.render.gl),this.removeCache(t))}createFrameBufferObject(t,e,i=this.antialias){return new O(this.render,t,e,i)}removeCache(t){const e=t instanceof k?t.base?.texture:t.texture;e&&this.cache.forEach(((t,i)=>{t===e&&this.cache.delete(i)}))}}class I{constructor(e,i,s,r=t.TextureWrapMode.CLAMP){this.texture=e,this.width=i,this.height=s,this.wrapMode=r}static fromImageSource(e,i,s=!1,r=t.TextureWrapMode.CLAMP){return new I(R(e.gl,i,s,!1,!1,r),i.width,i.height)}destroy(t){t.deleteTexture(this.texture)}}class k{constructor(t){this.scale=1,this.setBaseTextur(t)}setBaseTextur(t){t&&(this.base=t,this.setClipRegion(0,0,t.width,t.height))}setClipRegion(t,e,i,s){if(this.base)return this.clipX=t/this.base.width,this.clipY=e/this.base.height,this.clipW=this.clipX+i/this.base.width,this.clipH=this.clipY+s/this.base.height,this.width=i*this.scale,this.height=s*this.scale,this}static fromImageSource(t,e,i=!1){return new k(I.fromImageSource(t,e,i))}createSpritesHeet(t,e){if(!this.base)return[];const i=[],s=Math.floor(this.base.width/t),r=Math.floor(this.base.height/e);for(let n=0;n<r;n++)for(let r=0;r<s;r++){const s=this.clone();s.setClipRegion(r*t,n*e,t,e),i.push(s)}return i}clone(){return new k(this.base)}}class B extends k{constructor(t,e){super(),this.scale=.5,this.rapid=t,this.options=e,this.text=e.text||" ",this.updateTextImage()}updateTextImage(){const t=this.createTextCanvas();this.setBaseTextur(I.fromImageSource(this.rapid,t,!0))}createTextCanvas(){const t=document.createElement("canvas"),e=t.getContext("2d");if(!e)throw new Error("Failed to get canvas context");e.font=`${this.options.fontSize||16}px ${this.options.fontFamily||"Arial"}`,e.fillStyle=this.options.color||"#000",e.textAlign=this.options.textAlign||"left",e.textBaseline=this.options.textBaseline||"top";const i=this.text.split("\n");let s=0,r=0;for(const t of i){const i=e.measureText(t);s=Math.max(s,i.width),r+=this.options.fontSize||16}t.width=2*s,t.height=2*r,e.scale(2,2),e.font=`${this.options.fontSize||16}px ${this.options.fontFamily||"Arial"}`,e.fillStyle=this.options.color||"#000",e.textAlign=this.options.textAlign||"left",e.textBaseline=this.options.textBaseline||"top";let n=0;for(const t of i)e.fillText(t,0,n),n+=this.options.fontSize||16;return t}setText(t){this.text!=t&&(this.text=t,this.updateTextImage())}}class O extends I{constructor(t,e,i,s=!1){const r=t.gl,n=R(r,{width:e,height:i},s,!0,!1),a=r.createFramebuffer();if(!a)throw r.deleteTexture(n),new Error("Failed to create WebGL framebuffer");r.bindFramebuffer(r.FRAMEBUFFER,a),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,n,0);const o=r.createRenderbuffer();if(!o)throw r.deleteFramebuffer(a),r.deleteTexture(n),new Error("Failed to create depth-stencil renderbuffer");r.bindRenderbuffer(r.RENDERBUFFER,o),r.renderbufferStorage(r.RENDERBUFFER,r.STENCIL_INDEX8,e,i),r.framebufferRenderbuffer(r.FRAMEBUFFER,r.STENCIL_ATTACHMENT,r.RENDERBUFFER,o),super(n,e,i),this.gl=r,this.framebuffer=a,r.bindTexture(r.TEXTURE_2D,null),r.bindFramebuffer(r.FRAMEBUFFER,null)}bind(){const t=this.gl;t.bindTexture(t.TEXTURE_2D,null),t.bindFramebuffer(t.FRAMEBUFFER,this.framebuffer),t.clearColor(.5,.2,.5,.5),t.clear(t.COLOR_BUFFER_BIT)}unbind(){this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,null),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}resize(t,e){this.width=t,this.height=e,this.gl.bindTexture(this.gl.TEXTURE_2D,this.texture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,t,e,0,this.gl.RGBA,this.gl.UNSIGNED_BYTE,null),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}destroy(t){t.deleteFramebuffer(this.framebuffer),super.destroy(t)}}class G{constructor(t,e){this.textures=new Map,this.width=t,this.height=e}setTile(t,e){e instanceof k&&(e={texture:e}),this.textures.set(t,e)}getTile(t){return this.textures.get(t)}}class z{constructor(t){this.rapid=t}getYSortRow(t,e){const i=new Map;if(!t)return i;for(const s of t){const t=Math.floor(s.ySort/e);i.has(t)||i.set(t,[]),i.get(t).push(s)}return i}getOffset(t){let e=(t.errorX??2)+1,i=(t.errorY??2)+1;if("number"==typeof t.error){const s=(t.error??2)+1;e=s,i=s}else t.error&&(e=t.error.x+1,i=t.error.y+1);return{errorX:e,errorY:i}}renderYSortRow(t,e){if(e&&0!==e.length)for(const i of e)i.render?i.render():i.entity?i.entity.onRender(t):i.renderSprite&&t.renderSprite(i.renderSprite)}getTileData(e,i){const s=i.shape??t.TilemapShape.SQUARE,r=e.width,n=s===t.TilemapShape.ISOMETRIC?e.height/2:e.height,a=this.rapid.matrixStack,{errorX:o,errorY:h}=this.getOffset(i),l=new m(0,0),u=new m(this.rapid.width,0),c=new m(0,this.rapid.height),d=new m(this.rapid.width,this.rapid.height),p=a.globalToLocal(l),f=a.globalToLocal(u),g=a.globalToLocal(c),y=a.globalToLocal(d),x=Math.min(p.x,f.x,g.x,y.x),T=Math.max(p.x,f.x,g.x,y.x),w=Math.min(p.y,f.y,g.y,y.y),b=Math.max(p.y,f.y,g.y,y.y),E=new m(Math.floor(x/r)-o,Math.floor(w/n)-h),R=new m(Math.ceil(T/r)+o,Math.ceil(b/n)+h);return{startTile:E,viewportWidth:R.x-E.x,viewportHeight:R.y-E.y,height:n}}renderLayer(t,e){this.rapid.matrixStack.applyTransform(e);const i=e.tileSet,{startTile:s,viewportWidth:r,viewportHeight:n,height:a}=this.getTileData(i,e),o=this.getYSortRow(e.ySortCallback,a),h=e.ySortCallback&&e.ySortCallback.length>0;for(let a=0;a<n;a++){const n=a+s.y,l=o.get(n)??[];if(n<0||n>=t.length)this.renderYSortRow(this.rapid,l);else{for(let a=0;a<r;a++){const r=a+s.x;if(r<0||r>=t[n].length)continue;const o=t[n][r],h=i.getTile(o);if(!h)continue;const u=this.mapToLocal(new m(r,n),e),c=this.rapid.matrixStack.localToGlobal(u).y+(h.ySortOffset??0),d=e.eachTile&&e.eachTile(o,r,n)||{};l.push({ySort:c,renderSprite:{...h,x:u.x+(h.x||0),y:u.y+(h.y||0),...d}})}h&&l.sort(((t,e)=>t.ySort-e.ySort)),this.renderYSortRow(this.rapid,l)}}this.rapid.matrixStack.applyTransformAfter(e)}localToMap(e,i){const s=i.tileSet;if(i.shape===t.TilemapShape.ISOMETRIC){let t=0,i=0;const r=s.height/2,n=s.width/2;let a=Math.floor(e.y/r);const o=a%2==0;let h=Math.floor(e.x/n);const l=h%2==0,u=e.x%n/n,c=e.y%r/r,d=c<u,p=c<1-u;return o||(a-=1),d&&!l&&o?a-=1:d||!l||o?p&&l&&o?(h-=2,a-=1):p||l||o||(a+=1):(a+=1,h-=2),t=h,i=a,t=Math.floor(h/2),new m(t,i)}return new m(Math.floor(e.x/s.width),Math.floor(e.y/s.height))}mapToLocal(e,i){const s=i.tileSet;if(i.shape===t.TilemapShape.ISOMETRIC){let t=new m(e.x*s.width,e.y*s.height/2);return e.y%2!=0&&(t.x+=s.width/2),t}return new m(e.x*s.width,e.y*s.height)}}function j(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var X,W={exports:{}};var Y=(X||(X=1,function(t){var e=Object.prototype.hasOwnProperty,i="~";function s(){}function r(t,e,i){this.fn=t,this.context=e,this.once=i||!1}function n(t,e,s,n,a){if("function"!=typeof s)throw new TypeError("The listener must be a function");var o=new r(s,n||t,a),h=i?i+e:e;return t._events[h]?t._events[h].fn?t._events[h]=[t._events[h],o]:t._events[h].push(o):(t._events[h]=o,t._eventsCount++),t}function a(t,e){0==--t._eventsCount?t._events=new s:delete t._events[e]}function o(){this._events=new s,this._eventsCount=0}Object.create&&(s.prototype=Object.create(null),(new s).__proto__||(i=!1)),o.prototype.eventNames=function(){var t,s,r=[];if(0===this._eventsCount)return r;for(s in t=this._events)e.call(t,s)&&r.push(i?s.slice(1):s);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(t)):r},o.prototype.listeners=function(t){var e=i?i+t:t,s=this._events[e];if(!s)return[];if(s.fn)return[s.fn];for(var r=0,n=s.length,a=new Array(n);r<n;r++)a[r]=s[r].fn;return a},o.prototype.listenerCount=function(t){var e=i?i+t:t,s=this._events[e];return s?s.fn?1:s.length:0},o.prototype.emit=function(t,e,s,r,n,a){var o=i?i+t:t;if(!this._events[o])return!1;var h,l,u=this._events[o],c=arguments.length;if(u.fn){switch(u.once&&this.removeListener(t,u.fn,void 0,!0),c){case 1:return u.fn.call(u.context),!0;case 2:return u.fn.call(u.context,e),!0;case 3:return u.fn.call(u.context,e,s),!0;case 4:return u.fn.call(u.context,e,s,r),!0;case 5:return u.fn.call(u.context,e,s,r,n),!0;case 6:return u.fn.call(u.context,e,s,r,n,a),!0}for(l=1,h=new Array(c-1);l<c;l++)h[l-1]=arguments[l];u.fn.apply(u.context,h)}else{var d,p=u.length;for(l=0;l<p;l++)switch(u[l].once&&this.removeListener(t,u[l].fn,void 0,!0),c){case 1:u[l].fn.call(u[l].context);break;case 2:u[l].fn.call(u[l].context,e);break;case 3:u[l].fn.call(u[l].context,e,s);break;case 4:u[l].fn.call(u[l].context,e,s,r);break;default:if(!h)for(d=1,h=new Array(c-1);d<c;d++)h[d-1]=arguments[d];u[l].fn.apply(u[l].context,h)}}return!0},o.prototype.on=function(t,e,i){return n(this,t,e,i,!1)},o.prototype.once=function(t,e,i){return n(this,t,e,i,!0)},o.prototype.removeListener=function(t,e,s,r){var n=i?i+t:t;if(!this._events[n])return this;if(!e)return a(this,n),this;var o=this._events[n];if(o.fn)o.fn!==e||r&&!o.once||s&&o.context!==s||a(this,n);else{for(var h=0,l=[],u=o.length;h<u;h++)(o[h].fn!==e||r&&!o[h].once||s&&o[h].context!==s)&&l.push(o[h]);l.length?this._events[n]=1===l.length?l[0]:l:a(this,n)}return this},o.prototype.removeAllListeners=function(t){var e;return t?(e=i?i+t:t,this._events[e]&&a(this,e)):(this._events=new s,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=i,o.EventEmitter=o,t.exports=o}(W)),W.exports),H=j(Y);class K extends H{constructor(t,e,i,s,r){super(),this.elapsed=0,this.isRunning=!1,this.isFinished=!1,this.target=t,this.property=e,this.to=i,this.duration=s,this.easing=r}start(){const t=this.target[this.property];if("number"==typeof t)this.from=t;else{if("function"!=typeof t.clone)return console.error("Tween target property is not a 'number' or does not have a 'clone' method."),void(this.isFinished=!0);this.from=t.clone()}this.elapsed=0,this.isRunning=!0,this.isFinished=!1}update(t){if(!this.isRunning||this.isFinished)return;this.elapsed+=t;const e=Math.min(this.elapsed/this.duration,1),i=this.easing(e);let s;if("number"==typeof this.from&&"number"==typeof this.to)s=this.from+(this.to-this.from)*i;else{const t=this.from,e=this.to.subtract(t).multiply(i);s=t.add(e)}this.target[this.property]=s,e>=1&&(this.isFinished=!0,this.isRunning=!1,this.target[this.property]=this.to,this.emit("complete"))}}class ${}$.Linear=t=>t,$.EaseInQuad=t=>t*t,$.EaseOutQuad=t=>t*(2-t),$.EaseInOutQuad=t=>t<.5?2*t*t:(4-2*t)*t-1,$.EaseInCubic=t=>t*t*t,$.EaseOutCubic=t=>--t*t*t+1,$.EaseInOutCubic=t=>t<.5?4*t*t*t:(t-1)*(2*t-2)*(2*t-2)+1,$.EaseInQuart=t=>t*t*t*t,$.EaseOutQuart=t=>1- --t*t*t*t,$.EaseInOutQuart=t=>t<.5?8*t*t*t*t:1-8*--t*t*t*t;class q extends H{constructor(t,e=!1){super(),this.elapsedTime=0,this.isRunning=!1,this.isFinished=!1,this.duration=t,this.repeat=e}start(){this.isRunning=!0}stop(){this.isRunning=!1}update(t){this.isRunning&&!this.isFinished&&(this.elapsedTime+=t,this.elapsedTime>=this.duration&&(this.emit("timeout"),this.repeat?this.elapsedTime-=this.duration:(this.isFinished=!0,this.isRunning=!1)))}destroy(){this.isFinished=!0,this.isRunning=!1}}const Q=!0;class Z{constructor(t,e){this.life=0,this.datas={},this.rapid=t,this.options=e,e.texture instanceof k?this.texture=e.texture:e.texture instanceof Array&&e.texture[0]instanceof Array?this.texture=g.pickWeight(e.texture):e.texture instanceof Array&&(this.texture=g.pick(e.texture)),this.maxLife=g.scalarOrRange(e.life,1),this.datas={speed:this.processAttribute(e.animation.speed,0),rotation:this.processAttribute(e.animation.rotation,0),scale:this.processAttribute(e.animation.scale,1),color:this.processAttribute(e.animation.color,f.White),velocity:this.processAttribute(e.animation.velocity,m.ZERO),acceleration:this.processAttribute(e.animation.acceleration,m.ZERO)},this.position=m.ZERO,this.initializePosition()}processAttribute(t,e){if(!t)return{value:e};if("object"==typeof(i=t)&&null!==i&&Object.getPrototypeOf(i)===Object.prototype){const i=g.scalarOrRange(t.start,e),s=g.scalarOrRange(t.end||i,e);return{delta:t.delta??this.getDelta(i,s,this.maxLife),value:i,damping:t.damping}}return this.processAttribute({start:t},e);var i}updateDamping(t){for(const e of Object.values(this.datas))if(e.damping){const i=e.value,s=Math.pow(e.damping,t);e.value="number"==typeof i?i*s:i.multiply(s)}}updateDelta(t){const e=this.datas;for(const e of Object.values(this.datas))if(e.delta){const i=e.value;"number"==typeof i?e.value+=t*e.delta:e.value=i.add(e.delta.multiply(t))}e.color.value.clamp();const i=m.fromAngle(e.rotation.value).multiply(e.speed.value*t);this.position=this.position.add(i).add(e.velocity.value.multiply(t)).add(e.acceleration.value.multiply(t))}getDelta(t,e,i){return"number"==typeof t&&"number"==typeof e?(e-t)/i:t instanceof m&&e instanceof m||t instanceof f&&e instanceof f?e.subtract(t).divide(i):t}update(t){return this.life+=t,!(this.life>=this.maxLife)&&(this.updateDamping(t),this.updateDelta(t),!0)}render(){this.rapid.renderSprite({...this.options,position:this.position,scale:this.datas.scale.value,rotation:this.datas.rotation.value,color:this.datas.color.value,texture:this.texture})}initializePosition(){switch(this.options.emitShape){case t.ParticleShape.POINT:this.position=m.ZERO;break;case t.ParticleShape.CIRCLE:const e=Math.random()*Math.PI*2,i=(this.options.emitRadius||0)*Math.sqrt(Math.random());this.position=new m(Math.cos(e)*i,Math.sin(e)*i);break;case t.ParticleShape.RECT:this.position=new m((Math.random()-.5)*(this.options.emitRect?.width||0),(Math.random()-.5)*(this.options.emitRect?.height||0))}!this.options.localSpace&&this.options.position&&(this.position=this.position.add(this.options.position))}}class V{constructor(t,e){this.particles=[],this.emitting=!1,this.emitTimer=0,this.emitRate=10,this.emitTime=0,this.emitTimeCounter=0,this.localSpace=Q,this.position=m.ZERO,this.rapid=t,this.options=e,this.emitRate=void 0!==e.emitRate?e.emitRate:10,this.emitTime=void 0!==e.emitTime?e.emitTime:0,this.localSpace=void 0!==e.localSpace?e.localSpace:Q,this.position=e.position||m.ZERO}getTransform(){return this.options}setEmitRate(t){this.emitRate=t}setEmitTime(t){this.emitTime=t}start(){this.emitting=!0,this.emitTimeCounter=0}stop(){this.emitting=!1}clear(){this.particles=[],this.emitTimeCounter=0}emit(t){const e=Math.min(t,(this.options.maxParticles||1/0)-this.particles.length);for(let t=0;t<e;t++){const t={...this.options},e=new Z(this.rapid,t);this.particles.unshift(e)}}update(t){if(this.emitting&&this.emitRate>0)if(this.emitTime>0){if(this.emitTimeCounter+=t,this.emitTimeCounter>=this.emitTime){const t=Math.floor(this.emitTimeCounter/this.emitTime);this.emit(this.emitRate*t),this.emitTimeCounter-=t*this.emitTime}}else{this.emitTimer+=t;const e=this.emitRate*t,i=Math.floor(e);i>0&&(this.emit(i),this.emitTimer-=i/this.emitRate);this.emitTimer*this.emitRate>=1&&(this.emit(1),this.emitTimer-=1/this.emitRate)}for(let e=this.particles.length-1;e>=0;e--)this.particles[e].update(t)||this.particles.splice(e,1)}render(){for(const t of this.particles)t.render()}getParticleCount(){return this.particles.length}isActive(){return this.emitting||this.particles.length>0}oneShot(){this.emit(this.emitRate)}}class J{constructor(e){this.projectionDirty=!0,this.matrixStack=new d,this.tileMap=new z(this),this.light=new y(this),this.defaultColor=new f(255,255,255,255),this.regions=new Map,this.currentMaskType=[],this.currentTransform=[],this.currentFBO=[],this.lastTime=0;const i=(t=>{const e={stencil:!0},i=t.getContext("webgl2",e)||t.getContext("webgl",e);if(!i)throw new Error("Unable to initialize WebGL. Your browser may not support it.");return i})(e.canvas);this.gl=i,this.canvas=e.canvas,this.texture=new N(this,e.antialias??!1),this.maxTextureUnits=i.getParameter(this.gl.MAX_TEXTURE_IMAGE_UNITS),this.width=e.width||this.canvas.width,this.height=e.height||this.canvas.height,this.scaleEnable=e.scaleEnable??!1,this.scaleRadio=e.scaleRadio||t.ScaleRadio.KEEP,this.devicePixelRatio=e.devicePixelRatio??window.devicePixelRatio??1,this.backgroundColor=e.backgroundColor||new f(255,255,255,255),this.registerBuildInRegion(),this.initWebgl(i),this.updateDisplaySize(this.width,this.height),this.projectionDirty=!1,this.canvas.style.display="block"}updateDisplaySize(e,i){const s=this.width,r=this.height;let n,a,o,h;if(this.scaleEnable){const l=s/r,u=e/i;switch(this.scaleRadio){case t.ScaleRadio.IGNORE:n=s,a=r,o=e*this.devicePixelRatio,h=i*this.devicePixelRatio;break;case t.ScaleRadio.KEEP:let c,d;n=s,a=r,u>l?(d=i,c=d*l):(c=e,d=c/l),o=c*this.devicePixelRatio,h=d*this.devicePixelRatio;break;case t.ScaleRadio.EXPAND:u>l?(a=r,n=r*u):(n=s,a=s/u),o=e*this.devicePixelRatio,h=i*this.devicePixelRatio;break;case t.ScaleRadio.KEEP_W:n=s,a=s/u,o=e*this.devicePixelRatio,h=i*this.devicePixelRatio;break;case t.ScaleRadio.KEEP_H:a=r,n=r*u,o=e*this.devicePixelRatio,h=i*this.devicePixelRatio;break;default:n=s,a=r,o=e*this.devicePixelRatio,h=i*this.devicePixelRatio}}else n=s,a=r,o=s*this.devicePixelRatio,h=r*this.devicePixelRatio;this.logicWidth=n,this.logicHeight=a,this.physicsWidth=o,this.physicsHeight=h,this.resizeSize(n,a,o,h,!0)}resizeSize(t,e,i,s,r=!1){this.updateProjection(0,t,e,0),this.gl.viewport(0,0,i,s),this.gl.scissor(0,0,i,s),r&&(this.canvas.width=i,this.canvas.height=s,this.canvas.style.width=i/this.devicePixelRatio+"px",this.canvas.style.height=s/this.devicePixelRatio+"px")}updateProjection(t,e,i,s){this.projection=this.createOrthMatrix(t,e,i,s),this.projectionDirty=!0}initWebgl(t){t.enable(t.BLEND),t.disable(t.DEPTH_TEST),t.blendFunc(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA),t.enable(t.STENCIL_TEST),t.enable(t.SCISSOR_TEST)}clearTextureUnit(){for(let t=0;t<this.maxTextureUnits;t++)this.gl.activeTexture(this.gl.TEXTURE0+t),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}registerBuildInRegion(){this.registerRegion("sprite",D),this.registerRegion("graphic",F)}registerRegion(t,e){this.regions.set(t,new e(this))}quitCurrentRegion(){this.currentRegion&&this.currentRegion.hasPendingContent()&&(this.currentRegion.render(),this.currentRegion.exitRegion())}setRegion(t,e){if(t!=this.currentRegionName||this.currentRegion&&this.currentRegion.isShaderChanged(e)){const i=this.regions.get(t);this.quitCurrentRegion(),this.currentRegion=i,this.currentRegionName=t,i.enterRegion(e)}}save(){this.matrixStack.pushMat()}restore(){this.matrixStack.popMat()}withTransform(t){this.save(),t(),this.restore()}startRender(t=!0){this.clear(),t&&this.matrixStack.clear(),this.matrixStack.pushIdentity(),this.currentRegion=void 0,this.currentRegionName=void 0;const e=performance.now(),i=this.lastTime?(e-this.lastTime)/1e3:0;return this.lastTime=e,i}endRender(){this.currentRegion?.render(),this.projectionDirty=!1}render(t){t(this.startRender()),this.endRender()}renderTileMapLayer(t,e){this.tileMap.renderLayer(t,e instanceof G?{tileSet:e}:e)}renderSprite(t){const e=t.texture;if(!e||!e.base)return;const{offsetX:i,offsetY:s}=this.startDraw(t,e.width,e.height);this.setRegion("sprite",t.shader),this.currentRegion.renderSprite(e.base.texture,e.width,e.height,e.clipX,e.clipY,e.clipW,e.clipH,i,s,(t.color||this.defaultColor).uint32,t.uniforms,t.flipX,t.flipY),this.afterDraw()}renderParticles(t){t.localSpace?(this.startDraw(t.getTransform()),t.render(),this.afterDraw()):t.render()}renderTexture(t){t.base&&this.renderSprite({texture:t})}renderLine(t){const e=t.closed?[...t.points,t.points[0]]:t.points,{vertices:i,uv:s}=T({...t,points:e});this.renderGraphic({...t,drawType:this.gl.TRIANGLES,points:i,uv:s})}renderGraphic(t){this.startGraphicDraw(t),t.points.forEach(((e,i)=>{const s=Array.isArray(t.color)?t.color[i]:t.color,r=t.uv?.[i];this.addGraphicVertex(e.x,e.y,r,s)})),this.endGraphicDraw()}startGraphicDraw(t){const{offsetX:e,offsetY:i}=this.startDraw(t);this.setRegion("graphic",t.shader);const s=this.currentRegion;s.startRender(e,i,t.texture,t.uniforms),t.drawType&&(s.drawType=t.drawType)}addGraphicVertex(t,e,i,s){this.currentRegion.addVertex(t,e,i?.x,i?.y,(s||this.defaultColor).uint32)}endGraphicDraw(){this.currentRegion.render(),this.afterDraw()}startDraw(t,e=0,i=0){return this.currentTransform.push(t),this.matrixStack.applyTransform(t,e,i)}afterDraw(){this.currentTransform.length>0&&this.matrixStack.applyTransformAfter(this.currentTransform.pop())}renderRect(t){const{width:e,height:i}=t,s=[new m(0,0),new m(e,0),new m(e,i),new m(0,i)];this.renderGraphic({...t,points:s,drawType:this.gl.TRIANGLE_FAN})}renderCircle(t){const e=t.segments||32,i=t.radius,s=t.color||this.defaultColor,r=[];for(let t=0;t<=e;t++){const s=t/e*Math.PI*2,n=Math.cos(s)*i,a=Math.sin(s)*i;r.push(new m(n,a))}this.renderGraphic({...t,points:r,color:s,drawType:this.gl.TRIANGLE_FAN})}clear(t){const e=this.gl,i=t||this.backgroundColor;e.clearColor(i.r/255,i.g/255,i.b/255,i.a/255),e.clear(e.COLOR_BUFFER_BIT),this.clearMask()}createOrthMatrix(t,e,i,s){return new Float32Array([2/(e-t),0,0,0,0,2/(s-i),0,0,0,0,-1,0,-(e+t)/(e-t),-(s+i)/(s-i),0,1])}drawMask(e=t.MaskType.Include,i){this.startDrawMask(e),i(),this.endDrawMask()}startDrawMask(e=t.MaskType.Include){const i=this.gl;this.currentMaskType.push(e),this.setMaskType(e,!0),i.stencilOp(i.KEEP,i.KEEP,i.REPLACE),i.colorMask(!1,!1,!1,!1)}endDrawMask(){const e=this.gl;this.quitCurrentRegion(),e.stencilOp(e.KEEP,e.KEEP,e.KEEP),e.colorMask(!0,!0,!0,!0),this.setMaskType(this.currentMaskType.pop()??t.MaskType.Include,!1)}setMaskType(e,i=!1){const s=this.gl;if(this.quitCurrentRegion(),i)this.clearMask(),s.stencilFunc(s.ALWAYS,1,255);else switch(e){case t.MaskType.Include:s.stencilFunc(s.EQUAL,1,255);break;case t.MaskType.Exclude:s.stencilFunc(s.NOTEQUAL,1,255)}}clearMask(){const t=this.gl;this.quitCurrentRegion(),t.clearStencil(0),t.clear(t.STENCIL_BUFFER_BIT),t.stencilFunc(t.ALWAYS,1,255)}createCostumShader(t,e,i,s=0){return U.createCostumShader(this,t,e,i,s)}startFBO(t){this.quitCurrentRegion(),t.bind(),this.clearTextureUnit(),this.resizeSize(t.width,t.height,t.width,t.height),this.updateProjection(0,t.width,0,t.height),this.save(),this.matrixStack.identity(),this.currentFBO.push(t)}endFBO(){if(this.currentFBO.length>0){const t=this.currentFBO.pop();this.quitCurrentRegion(),t.unbind(),this.clearTextureUnit(),this.resizeSize(this.logicWidth,this.logicHeight,this.physicsWidth,this.physicsHeight),this.restore()}}drawToFBO(t,e){this.startFBO(t),e(),this.endFBO()}setBlendMode(e){switch(e){case t.BlendMode.Additive:this.gl.blendFunc(this.gl.SRC_ALPHA,this.gl.ONE);break;case t.BlendMode.Subtractive:this.gl.blendFunc(this.gl.ZERO,this.gl.ONE_MINUS_SRC_COLOR);break;case t.BlendMode.Mix:this.gl.blendFunc(this.gl.SRC_ALPHA,this.gl.ONE_MINUS_SRC_ALPHA)}}drawLightShadowMask(e){this.startDrawMask(e.type||t.MaskType.Exclude);this.light.createLightShadowMaskPolygon(e.occlusion,e.lightSource,e.baseProjectionLength).forEach((t=>{this.renderGraphic({points:t,color:f.Black})})),this.endDrawMask()}createParticleEmitter(t){return new V(this,t)}cssToGameCoords(t,e){const i=t instanceof m?t:new m(t,e),s=this.canvas.getBoundingClientRect(),r=i.x/s.width,n=i.y/s.height,a=r*this.logicWidth,o=n*this.logicHeight;return new m(a,o)}gameToCssCoords(t,e){const i=t instanceof m?t:new m(t,e??0),s=this.canvas.getBoundingClientRect(),r=i.x/this.logicWidth,n=i.y/this.logicHeight,a=r*s.width,o=n*s.height;return new m(a,o)}}class tt extends H{constructor(t,e){super(),this.element=t,this.audioContext=e,this.source=null,this.gainNode=this.audioContext.createGain(),this.element.addEventListener("ended",this.handleEnded.bind(this))}handleEnded(){this.emit("ended")}async play(t=!1){try{this.element.loop=t,this.source=this.audioContext.createMediaElementSource(this.element),this.source.connect(this.gainNode),this.gainNode.connect(this.audioContext.destination),await this.element.play()}catch(t){console.error("Error playing audio:",t)}}pause(){this.element.pause()}stop(){this.element.pause(),this.element.currentTime=0,this.source&&(this.source.disconnect(),this.source=null)}setVolume(t){this.gainNode.gain.value=Math.max(0,Math.min(1,t))}destroy(){this.stop(),this.gainNode.disconnect(),this.element.removeEventListener("ended",this.handleEnded.bind(this)),this.removeAllListeners()}}class et{constructor(){this.audioContext=new(window.AudioContext||window.webkitAudioContext)}destroy(){this.audioContext.close()}}class it extends H{constructor(t){super(),this.totalAsset=0,this.loadedAssets=0,this.game=t,this.assets={json:{},audio:{},images:{}}}loadJson(t,e){this.totalAsset++,fetch(e).then((t=>t.json())).then((e=>{this.assets.json[t]=e,this.assetLoaded()})).catch((i=>this.handleError(t,e,i)))}loadAudio(t,e){this.totalAsset++;const i=new Audio;i.src=e,i.oncanplaythrough=()=>{this.assets.audio[t]=new tt(i,this.game.audio.audioContext),this.assetLoaded(),i.oncanplaythrough=null},i.onerror=()=>this.handleError(t,e,"Audio load error")}loadImage(t,e){this.totalAsset++;const i=new Image;i.src=e,i.onload=()=>{this.assets.images[t]=this.game.render.texture.textureFromSource(i),this.assetLoaded()},i.onerror=()=>this.handleError(t,e,"Image load error")}loadAssets(t){t.forEach((t=>{switch(t.type){case"json":this.loadJson(t.name,t.url);break;case"audio":this.loadAudio(t.name,t.url);break;case"image":this.loadImage(t.name,t.url);break;default:console.warn(`Unknown asset type: ${t.type}`)}}))}assetLoaded(){this.loadedAssets++;const t=this.loadedAssets/this.totalAsset;this.emit("progress",t,this.loadedAssets,this.totalAsset),this.loadedAssets===this.totalAsset&&this.emit("complete",this.assets)}handleError(t,e,i){this.emit("error",{name:t,url:e,error:i}),console.error(`Failed to load asset ${t} from ${e}:`,i)}get(t,e){return this.assets[t]?.[e]}getJSON(t){return this.assets.json[t]}getAudio(t){return this.assets.audio[t]}getTexture(t){return this.assets.images[t]}}class st{constructor(t){this.mousePosition=m.ZERO,this.keysDown=new Set,this.keysDownLastFrame=new Set,this.buttonsDown=new Set,this.buttonsDownLastFrame=new Set,this.rapid=t,this.canvas=t.canvas,this.attachEventListeners()}attachEventListeners(){const t=this.canvas.getBoundingClientRect();this.canvas.addEventListener("mousemove",this.handleMouseMove=e=>{this.mousePosition=this.rapid.cssToGameCoords(e.clientX-t.left,e.clientY-t.top)}),window.addEventListener("keydown",this.handleKeyDown=t=>{this.keysDown.add(t.code)}),window.addEventListener("keyup",this.handleKeyUp=t=>{this.keysDown.delete(t.code)}),this.canvas.addEventListener("mousedown",this.handleMouseDown=t=>{this.buttonsDown.add(t.button)}),this.canvas.addEventListener("mouseup",this.handleMouseUp=t=>{this.buttonsDown.delete(t.button)})}updateNextFrame(){this.keysDownLastFrame=new Set(this.keysDown),this.buttonsDownLastFrame=new Set(this.buttonsDown)}isKeyDown(t){return this.keysDown.has(t)}isKeyUp(t){return!this.keysDown.has(t)}wasKeyPressed(t){return this.keysDown.has(t)&&!this.keysDownLastFrame.has(t)}wasKeyReleased(t){return!this.keysDown.has(t)&&this.keysDownLastFrame.has(t)}isButtonDown(t){return this.buttonsDown.has(t)}isButtonUp(t){return!this.buttonsDown.has(t)}wasButtonPressed(t){return this.buttonsDown.has(t)&&!this.buttonsDownLastFrame.has(t)}wasButtonReleased(t){return!this.buttonsDown.has(t)&&this.buttonsDownLastFrame.has(t)}getMouseLocal(t){return t.transform.globalToLocal(this.mousePosition)}destroy(){this.canvas.removeEventListener("mousemove",this.handleMouseMove),window.removeEventListener("keydown",this.handleKeyDown),window.removeEventListener("keyup",this.handleKeyUp),this.canvas.removeEventListener("mousedown",this.handleMouseDown),this.canvas.removeEventListener("mouseup",this.handleMouseUp),this.keysDown.clear(),this.keysDownLastFrame.clear(),this.buttonsDown.clear(),this.buttonsDownLastFrame.clear()}}class rt{get x(){return this.position.x}get y(){return this.position.x}set x(t){this.x=t}set y(t){this.y=t}constructor(t,e={}){this.parent=null,this.globalZindex=0,this.localZindex=0,this.transform=new d,this.children=[],this.transform.pushIdentity(),this.game=t,this.rapid=t.render,this.tags=e.tags??[],e.position?this.position=e.position:this.position=new m(e.x??0,e.y??0),"number"==typeof e.scale?this.scale=new m(e.scale,e.scale):e.scale?this.scale=e.scale:this.scale=new m(1,1),this.rotation=e.rotation??0}getParentTransform(){return this.parent?this.parent.transform:this.rapid.matrixStack}update(t){this.onUpdate(t);for(const e of this.children)e.update(t)}onUpdate(t){}collectRenderables(t){this.onRender!==rt.prototype.onRender&&t.push(this);for(const e of this.children)e.collectRenderables(t)}beforOnRender(){const t=this.transform;this.rapid.matrixStack.setTransform(t.getTransform())}onRender(t){}updateTransform(t=!1){t&&this.parent&&this.parent.updateTransform(t);const e=this.transform,i=this.getParentTransform();e.setTransform(i.getTransform()),e.translate(this.position),e.rotate(this.rotation),e.scale(this.scale)}addChild(t){t.parent&&t.parent.removeChild(t),t.parent=this,this.children.push(t)}removeChild(t){const e=this.children.indexOf(t);e>-1&&(t.parent=null,this.children.splice(e,1))}findDescendant(t,e=!0){const i=[];for(const s of this.children){if(t(s)){if(e)return s;i.push(s)}const r=s.findDescendant(t,e);if(e){if(r)return r}else i.push(...r)}return e?null:i}findDescendantByTag(t,e=!1){return this.findDescendant((e=>0!==t.length&&t.every((t=>e.tags.includes(t)))),e)}dispose(){this.postDispose(),this.parent&&this.parent.removeChild(this)}postDispose(){this.children.forEach((t=>{t.dispose()}))}}class nt extends rt{constructor(e,i){super(e,i),this.error=new m(nt.DEFAULT_ERROR),this.data=[[]],this.ySortCallback=[],i.error?"number"==typeof i.error?this.error=new m(i.error):this.error=i.error:this.error=new m(i.errorX??nt.DEFAULT_ERROR,i.errorY??nt.DEFAULT_ERROR),this.tileSet=i.tileSet,this.shape=i.shape??t.TilemapShape.SQUARE,this.eachTile=i.eachTile}collectRenderables(t){this.onRender!==rt.prototype.onRender&&t.push(this)}setTile(t,e,i){return e<0||e>=this.data.length||t<0||t>=this.data[e].length?(console.warn(`Tilemap.setTile: Coordinates (${t}, ${e}) are out of bounds.`),!1):(this.data[e][t]=i,!0)}getTile(t,e){if(!(e<0||e>=this.data.length||t<0||t>=this.data[e].length))return this.data[e][t]}removeTile(t,e){return this.setTile(t,e,nt.EMPTY_TILE)}fill(t,e,i,s,r){const n=e+s,a=i+r;for(let s=i;s<a;s++)for(let i=e;i<n;i++)this.setTile(i,s,t)}setData(t){this.data=t}localToMap(t){this.rapid.tileMap.localToMap(t,{tileSet:this.tileSet})}mapToLocal(t){this.rapid.tileMap.mapToLocal(t,{tileSet:this.tileSet})}onRender(t){const e=[...this.ySortCallback];this.children.forEach((t=>{e.push({ySort:t.localZindex,entity:t})})),t.renderTileMapLayer(this.data,{error:this.error,tileSet:this.tileSet,eachTile:this.eachTile,ySortCallback:e})}}nt.DEFAULT_ERROR=0,nt.EMPTY_TILE=-1;return t.BaseTexture=I,t.Camera=class extends rt{updateTransform(){const t=this.transform;t.identity();const e=new m(-this.rapid.logicWidth,-this.rapid.logicHeight).divide(2);t.translate(e),t.translate(this.position),t.rotate(this.rotation),t.scale(this.scale),t.setTransform(t.getInverse())}},t.Color=f,t.DynamicArrayBuffer=u,t.Entity=rt,t.FrameBufferObject=O,t.GLShader=U,t.Game=class{constructor(t){this.mainScene=null,this.isRunning=!1,this.lastTime=0,this.tweens=[],this.timers=[],this.renderQueue=[],this.render=new J(t),this.input=new st(this.render),this.asset=new it(this),this.audio=new et,this.texture=this.render.texture}switchScene(t){this.mainScene&&this.mainScene.dispose(),this.mainScene=t,t.create()}start(){this.isRunning||(this.isRunning=!0,this.lastTime=performance.now(),this.gameLoop())}stop(){this.isRunning=!1}addEntityRenderQueue(t){this.renderQueue.push(t)}gameLoop(){if(!this.isRunning)return;const t=performance.now(),e=(t-this.lastTime)/1e3;this.lastTime=t,this.render.startRender(),this.mainScene&&(this.mainScene.update(e),this.mainScene.collectRenderables(this.renderQueue),this.renderQueue.sort(((t,e)=>{const i=t.parent&&t.parent===e.parent,s=t.globalZindex-e.globalZindex;return 0===s||i?i?t.localZindex-e.localZindex:0:s})),this.renderQueue.forEach((t=>{t.beforOnRender(),t.onRender(this.render)})),this.renderQueue.length=0),this.render.endRender(),this.input.updateNextFrame(),this.updateTweens(e),this.updateTimers(e),requestAnimationFrame(this.gameLoop.bind(this))}destroy(){this.audio.destroy(),this.input.destroy()}createTimer(t,e=!1){const i=new q(t,e);return this.timers.push(i),i.start(),i}updateTimers(t){for(const e of this.timers)e.update(t);this.timers=this.timers.filter((t=>!t.isFinished))}createTween(t,e,i,s,r=$.Linear){const n=new K(t,e,i,s,r);return this.tweens.push(n),n.start(),n}updateTweens(t){for(const e of this.tweens)e.update(t);this.tweens=this.tweens.filter((t=>!t.isFinished))}},t.InputManager=st,t.MathUtils=class{static deg2rad(t){return t*(Math.PI/180)}static rad2deg(t){return t/(Math.PI/180)}static normalizeDegrees(t){return(t%360+360)%360}},t.MatrixStack=d,t.ParticleEmitter=V,t.Random=g,t.Rapid=J,t.SCALEFACTOR=2,t.Scene=class extends rt{create(){}},t.Text=B,t.Texture=k,t.TextureCache=N,t.TileMapRender=z,t.TileSet=G,t.Tilemap=nt,t.Uniform=class{constructor(t){this.isDirty=!1,this.data=t}setUniform(t,e){this.data[t]!=e&&(this.isDirty=!0),this.data[t]=e}clearDirty(){this.isDirty=!1}getUnifromNames(){return Object.keys(this.data)}bind(t,e,i,s){if(!i)return;const r=this.data[e];if("number"==typeof r)t.uniform1f(i,r);else if(Array.isArray(r))switch(r.length){case 1:Number.isInteger(r[0])?t.uniform1i(i,r[0]):t.uniform1f(i,r[0]);break;case 2:Number.isInteger(r[0])?t.uniform2iv(i,r):t.uniform2fv(i,r);break;case 3:Number.isInteger(r[0])?t.uniform3iv(i,r):t.uniform3fv(i,r);break;case 4:Number.isInteger(r[0])?t.uniform4iv(i,r):t.uniform4fv(i,r);break;case 9:t.uniformMatrix3fv(i,!1,r);break;case 16:t.uniformMatrix4fv(i,!1,r);break;default:console.error(`Unsupported uniform array length for ${e}:`,r.length)}else if("boolean"==typeof r)t.uniform1i(i,r?1:0);else if(r.base?.texture){const e=s.useTexture(r.base.texture)[0];t.uniform1i(i,e)}else console.error(`Unsupported uniform type for ${e}:`,typeof r)}},t.Vec2=m,t.WebglBufferArray=c,t.WebglElementBufferArray=p,t.graphicAttributes=C,t.spriteAttributes=M,t}({});
|
package/dist/rapid.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const t=(t,e,r)=>{const i=t.createShader(r);if(!i)throw new Error("Unable to create webgl shader");t.shaderSource(i,e),t.compileShader(i);if(!t.getShaderParameter(i,t.COMPILE_STATUS)){const r=t.getShaderInfoLog(i);throw console.error("Shader compilation failed:",r),new Error("Unable to compile shader: "+r+e)}return i};const e=5126;class r{constructor(t){this.usedElemNum=0,this.maxElemNum=512,this.bytePerElem=t.BYTES_PER_ELEMENT,this.arrayType=t,this.arraybuffer=new ArrayBuffer(this.maxElemNum*this.bytePerElem),this.typedArray=new t(this.arraybuffer),t==Float32Array&&(this.uint32=new Uint32Array(this.arraybuffer))}clear(){this.usedElemNum=0}resize(t=0){if((t+=this.usedElemNum)>this.maxElemNum){for(;t>this.maxElemNum;)this.maxElemNum<<=1;this.setMaxSize(this.maxElemNum)}}setMaxSize(t=this.maxElemNum){const e=this.typedArray;this.maxElemNum=t,this.arraybuffer=new ArrayBuffer(t*this.bytePerElem),this.typedArray=new this.arrayType(this.arraybuffer),this.uint32&&(this.uint32=new Uint32Array(this.arraybuffer)),this.typedArray.set(e)}push(t){this.typedArray[this.usedElemNum++]=t}pushUint(t){this.uint32[this.usedElemNum++]=t}pop(t){this.usedElemNum-=t}getArray(t=0,e){return null==e?this.typedArray:this.typedArray.subarray(t,e)}get length(){return this.typedArray.length}}class i extends r{constructor(t,e,r=t.ARRAY_BUFFER){super(e),this.dirty=!0,this.webglBufferSize=0,this.gl=t,this.buffer=t.createBuffer(),this.type=r}push(t){super.push(t),this.dirty=!0}bindBuffer(){this.gl.bindBuffer(this.type,this.buffer)}bufferData(){if(this.dirty){const t=this.gl;this.maxElemNum>this.webglBufferSize?(t.bufferData(this.type,this.getArray(),t.STATIC_DRAW),this.webglBufferSize=this.maxElemNum):t.bufferSubData(this.type,0,this.getArray(0,this.usedElemNum)),this.dirty=!1}}}class s extends r{constructor(){super(Float32Array)}pushMat(){const t=this.usedElemNum-6,e=this.typedArray;this.resize(6),this.push(e[t+0]),this.push(e[t+1]),this.push(e[t+2]),this.push(e[t+3]),this.push(e[t+4]),this.push(e[t+5])}popMat(){this.pop(6)}pushIdentity(){this.resize(6),this.push(1),this.push(0),this.push(0),this.push(1),this.push(0),this.push(0)}translate(t,e){if(t instanceof a)return this.translate(t.x,t.y);const r=this.usedElemNum-6,i=this.typedArray;i[r+4]=i[r+0]*t+i[r+2]*e+i[r+4],i[r+5]=i[r+1]*t+i[r+3]*e+i[r+5]}rotate(t){const e=this.usedElemNum-6,r=this.typedArray,i=Math.cos(t),s=Math.sin(t),n=r[e+0],h=r[e+1],a=r[e+2],o=r[e+3];r[e+0]=n*i-h*s,r[e+1]=n*s+h*i,r[e+2]=a*i-o*s,r[e+3]=a*s+o*i}scale(t,e){if(t instanceof a)return this.scale(t.x,t.y);e||(e=t);const r=this.usedElemNum-6,i=this.typedArray;i[r+0]=i[r+0]*t,i[r+1]=i[r+1]*t,i[r+2]=i[r+2]*e,i[r+3]=i[r+3]*e}apply(t,e){if(t instanceof a)return new a(...this.apply(t.x,t.y));const r=this.usedElemNum-6,i=this.typedArray;return[i[r+0]*t+i[r+2]*e+i[r+4],i[r+1]*t+i[r+3]*e+i[r+5]]}getInverse(){const t=this.usedElemNum-6,e=this.typedArray,r=e[t+0],i=e[t+1],s=e[t+2],n=e[t+3],h=e[t+4],a=e[t+5],o=r*n-i*s;return new Float32Array([n/o,-i/o,-s/o,r/o,(s*a-n*h)/o,(i*h-r*a)/o])}getTransform(){const t=this.usedElemNum-6,e=this.typedArray;return new Float32Array([e[t+0],e[t+1],e[t+2],e[t+3],e[t+4],e[t+5]])}setTransform(t){const e=this.usedElemNum-6,r=this.typedArray;r[e+0]=t[0],r[e+1]=t[1],r[e+2]=t[2],r[e+3]=t[3],r[e+4]=t[4],r[e+5]=t[5]}}class n extends i{constructor(t,e,r,i){super(t,Uint16Array,t.ELEMENT_ARRAY_BUFFER),this.setMaxSize(e*i);for(let t=0;t<i;t++)this.addObject(t*r);this.bindBuffer(),this.bufferData()}addObject(t){}}class h{constructor(t,e,r,i){this._r=t,this._g=e,this._b=r,this._a=i,this.updateUint()}get r(){return this._r}set r(t){this._r=t,this.updateUint()}get g(){return this._g}set g(t){this._g=t,this.updateUint()}get b(){return this._b}set b(t){this._b=t,this.updateUint()}get a(){return this._a}set a(t){this._a=t,this.updateUint()}updateUint(){this.uint32=(this._a<<24|this._b<<16|this._g<<8|this._r)>>>0}setRGBA(t,e,r,i){this.r=t,this.g=e,this.b=r,this.a=i,this.updateUint()}copy(t){this.setRGBA(t.r,t.g,t.b,t.a)}equals(t){return t.r===this.r&&t.g===this.g&&t.b===this.b&&t.a===this.a}static fromHex(t){t.startsWith("#")&&(t=t.slice(1));const e=parseInt(t.slice(0,2),16),r=parseInt(t.slice(2,4),16),i=parseInt(t.slice(4,6),16);let s=255;return t.length>=8&&(s=parseInt(t.slice(6,8),16)),new h(e,r,i,s)}add(t){return new h(Math.min(this.r+t.r,255),Math.min(this.g+t.g,255),Math.min(this.b+t.b,255),Math.min(this.a+t.a,255))}subtract(t){return new h(Math.max(this.r-t.r,0),Math.max(this.g-t.g,0),Math.max(this.b-t.b,0),Math.max(this.a-t.a,0))}}class a{constructor(t,e){this.x=void 0!==t?t:0,this.y=void 0!==e?e:0}scalarMult(t){return this.x*=t,this.y*=t,this}perpendicular(){const t=this.x;return this.x=-this.y,this.y=t,this}invert(){return this.x=-this.x,this.y=-this.y,this}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}normalize(){const t=this.length();return this.x/=t,this.y/=t,this}angle(){return this.y/this.x}static Angle(t,e){return Math.atan2(e.y-t.y,e.x-t.x)}static Add(t,e){return new a(t.x+e.x,t.y+e.y)}static Sub(t,e){return new a(t.x-e.x,t.y-e.y)}static Middle(t,e){return a.Add(t,e).scalarMult(.5)}static FormArray(t){return t.map((t=>new a(t[0],t[1])))}}class o{constructor(t){this.cache=new Map,this.render=t}async textureFromUrl(t,e=!1){let r=this.cache.get(t);if(!r){const i=await this.loadImage(t);r=u.fromImageSource(this.render,i,e),this.cache.set(t,r)}return new l(r)}async loadImage(t){return new Promise((e=>{const r=new Image;r.onload=()=>{e(r)},r.src=t}))}createText(t){return new c(this.render,t)}}class u{constructor(t,e,r){this.texture=t,this.width=e,this.height=r}static fromImageSource(t,e,r=!1){return new u(function(t,e,r){const i=t.createTexture();if(t.bindTexture(t.TEXTURE_2D,i),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,r?t.LINEAR:t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,r?t.LINEAR:t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),!i)throw new Error("unable to create texture");return i}(t.gl,e,r),e.width,e.height)}}class l{constructor(t){this.scale=1,this.setBaseTextur(t)}setBaseTextur(t){t&&(this.base=t,this.setClipRegion(0,0,t.width,t.height))}setClipRegion(t,e,r,i){this.base&&(this.clipX=t/this.base.width,this.clipY=e/this.base.width,this.clipW=this.clipX+r/this.base.width,this.clipH=this.clipY+i/this.base.height,this.width=r*this.scale,this.height=i*this.scale)}static fromImageSource(t,e,r=!1){return new l(u.fromImageSource(t,e,r))}static fromUrl(t,e){return t.textures.textureFromUrl(e)}}const d=2;class c extends l{constructor(t,e){super(),this.scale=.5,this.rapid=t,this.options=e,this.text=e.text||"",this.updateTextImage()}updateTextImage(){const t=this.createTextCanvas();this.setBaseTextur(u.fromImageSource(this.rapid,t,!0))}createTextCanvas(){const t=document.createElement("canvas"),e=t.getContext("2d");if(!e)throw new Error("Failed to get canvas context");e.font=`${this.options.fontSize||16}px ${this.options.fontFamily||"Arial"}`,e.fillStyle=this.options.color||"#000",e.textAlign=this.options.textAlign||"left",e.textBaseline=this.options.textBaseline||"top";const r=this.text.split("\n");let i=0,s=0;for(const t of r){const r=e.measureText(t);i=Math.max(i,r.width),s+=this.options.fontSize||16}t.width=2*i,t.height=2*s,e.scale(2,2),e.font=`${this.options.fontSize||16}px ${this.options.fontFamily||"Arial"}`,e.fillStyle=this.options.color||"#000",e.textAlign=this.options.textAlign||"left",e.textBaseline=this.options.textBaseline||"top";let n=0;for(const t of r)e.fillText(t,0,n),n+=this.options.fontSize||16;return t}setText(t){this.text=t,this.updateTextImage()}}class p{constructor(e,r,i){this.attributeLoc={},this.uniformLoc={};const s=function(t,e){if(t.includes("%TEXTURE_NUM%")&&(t=t.replace("%TEXTURE_NUM%",e.toString())),t.includes("%GET_COLOR%")){let r="";for(let t=0;t<e;t++)r+=0==t?`if(vTextureId == ${t}.0)`:t==e-1?"else":`else if(vTextureId == ${t}.0)`,r+=`{color = texture2D(uTextures[${t}], vRegion);}`;t=t.replace("%GET_COLOR%",r)}return t}(i,e.maxTextureUnits);this.program=((e,r,i)=>{var s=e.createProgram(),n=t(e,r,35633),h=t(e,i,35632);if(!s)throw new Error("Unable to create program shader");return e.attachShader(s,n),e.attachShader(s,h),e.linkProgram(s),s})(e.gl,r,s),this.gl=e.gl,this.parseShader(r),this.parseShader(s)}setUniforms(t,e){var r;const i=this.gl;for(const s in t){const n=t[s],h=this.getUniform(s);if(n instanceof l&&(null===(r=n.base)||void 0===r?void 0:r.texture))i.activeTexture(i.TEXTURE0+e),i.bindTexture(i.TEXTURE_2D,n.base.texture),i.uniform1i(h,e),e+=1;else if("number"==typeof n)i.uniform1f(h,n);else if(Array.isArray(n))switch(n.length){case 1:Number.isInteger(n[0])?i.uniform1i(h,n[0]):i.uniform1f(h,n[0]);break;case 2:Number.isInteger(n[0])?i.uniform2iv(h,n):i.uniform2fv(h,n);break;case 3:Number.isInteger(n[0])?i.uniform3iv(h,n):i.uniform3fv(h,n);break;case 4:Number.isInteger(n[0])?i.uniform4iv(h,n):i.uniform4fv(h,n);break;case 9:i.uniformMatrix3fv(h,!1,n);break;case 16:i.uniformMatrix4fv(h,!1,n);break;default:console.error(`Unsupported uniform array length for ${s}:`,n.length)}else"boolean"==typeof n?i.uniform1i(h,n?1:0):console.error(`Unsupported uniform type for ${s}:`,typeof n)}}getUniform(t){return this.uniformLoc[t]}use(){this.gl.useProgram(this.program)}parseShader(t){const e=this.gl,r=t.match(/attribute\s+\w+\s+(\w+)/g);if(r)for(const t of r){const r=t.split(" ")[2],i=e.getAttribLocation(this.program,r);-1!=i&&(this.attributeLoc[r]=i)}const i=t.match(/uniform\s+\w+\s+(\w+)/g);if(i)for(const t of i){const r=t.split(" ")[2];this.uniformLoc[r]=e.getUniformLocation(this.program,r)}}setAttribute(t){const e=this.attributeLoc[t.name];if(void 0!==e){const r=this.gl;r.vertexAttribPointer(e,t.size,t.type,t.normalized||!1,t.stride,t.offset||0),r.enableVertexAttribArray(e)}}}class f{constructor(t,e){this.usedTextures=[],this.needBind=new Set,this.attribute=e,this.rapid=t,this.gl=t.gl,this.webglArrayBuffer=new i(t.gl,Float32Array,t.gl.ARRAY_BUFFER),this.TEXTURE_UNITS_ARRAY=Array.from({length:t.maxTextureUnits},((t,e)=>e))}addVertex(t,e,...r){const[i,s]=this.rapid.transformPoint(t,e);this.webglArrayBuffer.push(i),this.webglArrayBuffer.push(s)}useTexture(t){let e=this.usedTextures.indexOf(t);return-1===e&&(this.usedTextures.length>=this.rapid.maxTextureUnits&&this.render(),this.usedTextures.push(t),e=this.usedTextures.length-1,this.needBind.add(e)),e}enterRegion(t){this.currentShader=null!=t?t:this.defaultShader,this.currentShader.use(),this.initializeForNextRender(),this.webglArrayBuffer.bindBuffer();for(const t of this.attribute)this.currentShader.setAttribute(t);this.gl.uniformMatrix4fv(this.currentShader.uniformLoc.uProjectionMatrix,!1,this.rapid.projection)}exitRegion(){}initDefaultShader(t,e){this.webglArrayBuffer.bindBuffer(),this.defaultShader=new p(this.rapid,t,e)}render(){this.executeRender(),this.initializeForNextRender()}executeRender(){this.webglArrayBuffer.bufferData();const t=this.gl;for(const e of this.needBind)t.activeTexture(t.TEXTURE0+e),t.bindTexture(t.TEXTURE_2D,this.usedTextures[e]);this.needBind.clear()}initializeForNextRender(){this.webglArrayBuffer.clear(),this.usedTextures=[]}}class g extends f{constructor(t){super(t,m),this.vertex=0,this.drawType=t.gl.TRIANGLE_FAN,this.initDefaultShader("precision mediump float;\r\n\r\nattribute vec2 aPosition;\r\nattribute vec4 aColor;\r\nvarying vec4 vColor;\r\nuniform mat4 uProjectionMatrix;\r\nuniform vec4 uColor;\r\n\r\nvoid main(void) {\r\n gl_Position = uProjectionMatrix * vec4(aPosition, 0.0, 1.0);\r\n vColor = aColor;\r\n}\r\n","precision mediump float;\r\n\r\nvarying vec4 vColor;\r\nvoid main(void) {\r\n gl_FragColor = vColor;//vColor;\r\n}\r\n")}startRender(){this.vertex=0,this.webglArrayBuffer.clear()}addVertex(t,e,r){this.webglArrayBuffer.resize(3),super.addVertex(t,e),this.webglArrayBuffer.pushUint(r),this.vertex+=1}drawCircle(t,e,r,i){const s=2*Math.PI/30;this.startRender(),this.addVertex(t,e,i);for(let n=0;n<=30;n++){const h=n*s,a=t+r*Math.cos(h),o=e+r*Math.sin(h);this.addVertex(a,o,i)}this.executeRender()}executeRender(){super.executeRender();this.gl.drawArrays(this.drawType,0,this.vertex),this.drawType=this.rapid.gl.TRIANGLE_FAN,this.vertex=0}}const m=[{name:"aPosition",size:2,type:e,stride:12},{name:"aColor",size:4,type:5121,stride:12,offset:2*Float32Array.BYTES_PER_ELEMENT,normalized:!0}];class x extends n{constructor(t,e){super(t,6,4,e)}addObject(t){super.addObject(),this.push(t),this.push(t+3),this.push(t+2),this.push(t),this.push(t+1),this.push(t+2)}}class y extends f{constructor(t){const e=t.gl;super(t,E),this.batchSprite=0,this.initDefaultShader("precision mediump float;\r\n\r\nattribute vec2 aPosition;\r\nattribute vec2 aRegion;\r\nattribute float aTextureId;\r\nattribute vec4 aColor;\r\n\r\nuniform mat4 uProjectionMatrix;\r\n\r\nvarying vec2 vRegion;\r\nvarying float vTextureId;\r\nvarying vec4 vColor;\r\n\r\nvoid main(void) {\r\n vRegion = aRegion;\r\n vTextureId = aTextureId;\r\n vColor = aColor;\r\n gl_Position = uProjectionMatrix * vec4(aPosition, 0.0, 1.0);\r\n}","precision mediump float;\r\nuniform sampler2D uTextures[%TEXTURE_NUM%];\r\n\r\nvarying vec2 vRegion;\r\nvarying float vTextureId;\r\nvarying vec4 vColor;\r\n\r\nvoid main(void) {\r\n vec4 color;\r\n %GET_COLOR%\r\n\r\n gl_FragColor = color*vColor;\r\n}"),this.MAX_BATCH=Math.floor(16384),this.indexBuffer=new x(e,this.MAX_BATCH)}addVertex(t,e,r,i,s,n){super.addVertex(t,e),this.webglArrayBuffer.push(r),this.webglArrayBuffer.push(i),this.webglArrayBuffer.push(s),this.webglArrayBuffer.pushUint(n)}renderSprite(t,e,r,i,s,n,h,a,o,u,l){var d;l&&(null===(d=this.currentShader)||void 0===d||d.setUniforms(l,1)),this.batchSprite>=this.MAX_BATCH&&this.render(),this.batchSprite++,this.webglArrayBuffer.resize(24);const c=this.useTexture(t),p=a+e,f=o+r,g=i+n,m=s+h;this.addVertex(a,o,i,s,c,u),this.addVertex(p,o,g,s,c,u),this.addVertex(p,f,g,m,c,u),this.addVertex(a,f,i,m,c,u)}executeRender(){super.executeRender();const t=this.gl;t.drawElements(t.TRIANGLES,6*this.batchSprite,t.UNSIGNED_SHORT,0)}enterRegion(t){super.enterRegion(t),this.indexBuffer.bindBuffer(),this.gl.uniform1iv(this.currentShader.uniformLoc.uTextures,this.TEXTURE_UNITS_ARRAY)}initializeForNextRender(){super.initializeForNextRender(),this.batchSprite=0}}const E=[{name:"aPosition",size:2,type:e,stride:24},{name:"aRegion",size:2,type:e,stride:24,offset:2*Float32Array.BYTES_PER_ELEMENT},{name:"aTextureId",size:1,type:e,stride:24,offset:4*Float32Array.BYTES_PER_ELEMENT},{name:"aColor",size:4,type:5121,stride:24,offset:5*Float32Array.BYTES_PER_ELEMENT,normalized:!0}];var b,A;!function(t){t[t.BEVEL=0]="BEVEL",t[t.ROUND=1]="ROUND",t[t.MITER=2]="MITER"}(b||(b={})),function(t){t[t.BUTT=0]="BUTT",t[t.ROUND=1]="ROUND",t[t.SQUARE=2]="SQUARE"}(A||(A={}));const T=1e-4,R=(t,e,r,i)=>{i.push(t),i.push(a.Add(t,r)),i.push(a.Add(e,r)),i.push(e),i.push(a.Add(e,r)),i.push(t)},w=(t,e,r,i,s)=>{const n=a.Sub(t,e).length();let h=Math.atan2(r.y-t.y,r.x-t.x),o=Math.atan2(e.y-t.y,e.x-t.x);const u=h;o>h?o-h>=Math.PI-T&&(o-=2*Math.PI):h-o>=Math.PI-T&&(h-=2*Math.PI);let l=o-h;if(Math.abs(l)>=Math.PI-T&&Math.abs(l)<=Math.PI+T){const e=a.Sub(t,i);0===e.x?e.y>0&&(l=-l):e.x>=-1e-4&&(l=-l)}const d=(Math.abs(l*n)/7|0)+1,c=l/d;for(let e=0;e<d;e++)s.push(new a(t.x,t.y)),s.push(new a(t.x+n*Math.cos(u+c*e),t.y+n*Math.sin(u+c*e))),s.push(new a(t.x+n*Math.cos(u+c*(1+e)),t.y+n*Math.sin(u+c*(1+e))))},S=(t,e,r,i,s,n,h)=>{const o=a.Sub(e,t).perpendicular(),u=a.Sub(r,e).perpendicular();((t,e,r)=>(e.x-t.x)*(r.y-t.y)-(r.x-t.x)*(e.y-t.y))(t,e,r)>0&&(o.invert(),u.invert()),o.normalize().scalarMult(s),u.normalize().scalarMult(s);const l=((t,e,r,i)=>{const s=e.y-t.y,n=t.x-e.x,h=i.y-r.y,o=r.x-i.x,u=s*o-h*n;if(u>-1e-4&&u<T)return null;{const e=s*t.x+n*t.y,i=h*r.x+o*r.y;return new a((o*e-n*i)/u,(s*i-h*e)/u)}})(a.Add(o,t),a.Add(o,e),a.Add(u,r),a.Add(u,e));let d=null,c=Number.MAX_VALUE;l&&(d=a.Sub(l,e),c=d.length());const p=c/s|0,f=a.Sub(t,e).length(),g=a.Sub(e,r).length();if(c>f||c>g)i.push(a.Add(t,o)),i.push(a.Sub(t,o)),i.push(a.Add(e,o)),i.push(a.Sub(t,o)),i.push(a.Add(e,o)),i.push(a.Sub(e,o)),n===b.ROUND?w(e,a.Add(e,o),a.Add(e,u),r,i):n===b.BEVEL||n===b.MITER&&p>=h?(i.push(e),i.push(a.Add(e,o)),i.push(a.Add(e,u))):n===b.MITER&&p<h&&l&&(i.push(a.Add(e,o)),i.push(e),i.push(l),i.push(a.Add(e,u)),i.push(e),i.push(l)),i.push(a.Add(r,u)),i.push(a.Sub(e,u)),i.push(a.Add(e,u)),i.push(a.Add(r,u)),i.push(a.Sub(e,u)),i.push(a.Sub(r,u));else{if(i.push(a.Add(t,o)),i.push(a.Sub(t,o)),i.push(a.Sub(e,d)),i.push(a.Add(t,o)),i.push(a.Sub(e,d)),i.push(a.Add(e,o)),n===b.ROUND){const t=a.Add(e,o),r=a.Add(e,u),s=a.Sub(e,d),n=e;i.push(t),i.push(n),i.push(s),w(n,t,r,s,i),i.push(n),i.push(r),i.push(s)}else(n===b.BEVEL||n===b.MITER&&p>=h)&&(i.push(a.Add(e,o)),i.push(a.Add(e,u)),i.push(a.Sub(e,d))),n===b.MITER&&p<h&&(i.push(l),i.push(a.Add(e,o)),i.push(a.Add(e,u)));i.push(a.Add(r,u)),i.push(a.Sub(e,d)),i.push(a.Add(e,u)),i.push(a.Add(r,u)),i.push(a.Sub(e,d)),i.push(a.Sub(r,u))}};class v{constructor(t){this.projectionDirty=!0,this.matrixStack=new s,this.textures=new o(this),this.devicePixelRatio=window.devicePixelRatio||1,this.defaultColor=new h(255,255,255,255),this.defaultColorBlack=new h(0,0,0,255),this.regions=new Map;const e=(t=>{const e=t.getContext("webgl2")||t.getContext("webgl");if(!e)throw new Error("TODO");return e})(t.canvas);this.gl=e,this.canvas=t.canvas,this.maxTextureUnits=e.getParameter(this.gl.MAX_TEXTURE_IMAGE_UNITS),this.width=t.width||this.canvas.width,this.height=t.width||this.canvas.height,this.backgroundColor=t.backgroundColor||new h(255,255,255,255),this.registerBuildInRegion(),this.initWebgl(e)}initWebgl(t){this.resize(this.width,this.height),t.enable(t.BLEND),t.disable(t.DEPTH_TEST),t.blendFunc(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA)}registerBuildInRegion(){this.registerRegion("sprite",y),this.registerRegion("graphic",g)}registerRegion(t,e){this.regions.set(t,new e(this))}setRegion(t,e){if(t!=this.currentRegionName||e&&e!==this.currentRegion.currentShader){const r=this.regions.get(t);this.currentRegion&&(this.currentRegion.render(),this.currentRegion.exitRegion()),this.currentRegion=r,this.currentRegionName=t,r.enterRegion(e)}}save(){this.matrixStack.pushMat()}restore(){this.matrixStack.popMat()}startRender(t=!0){t&&this.matrixStack.clear(),this.matrixStack.pushIdentity(),this.currentRegion=void 0,this.currentRegionName=void 0}endRender(){var t;null===(t=this.currentRegion)||void 0===t||t.render(),this.projectionDirty=!1}renderSprite(t,e=0,r=0,i){if(t.base){if(i instanceof h)return this.renderSprite(t,e,r,{color:i});this.setRegion("sprite",null==i?void 0:i.shader),this.currentRegion.renderSprite(t.base.texture,t.width,t.height,t.clipX,t.clipY,t.clipW,t.clipH,e,r,((null==i?void 0:i.color)||this.defaultColor).uint32,null==i?void 0:i.uniforms)}}renderLine(t=0,e=0,r){const i=((t,e)=>{if(t.length<2)return[];let r=e.cap||A.BUTT,i=e.join||b.BEVEL,s=(e.width||1)/2,n=e.miterLimit||10,h=[],o=[];if(2===t.length)i=b.BEVEL,S(t[0],a.Middle(t[0],t[1]),t[1],h,s,i,n);else{for(let e=0;e<t.length-1;e++)0===e?o.push(t[0]):e===t.length-2?o.push(t[t.length-1]):o.push(a.Middle(t[e],t[e+1]));for(let e=1;e<o.length;e++)S(o[e-1],t[e],o[e],h,s,i,n)}if(r===A.ROUND){let e=h[0],r=h[1],i=t[1],s=h[h.length-1],n=h[h.length-3],a=t[t.length-2];w(t[0],e,r,i,h),w(t[t.length-1],s,n,a,h)}else if(r===A.SQUARE){let e=h[h.length-1],r=h[h.length-3];R(h[0],h[1],a.Sub(t[0],t[1]).normalize().scalarMult(a.Sub(t[0],h[0]).length()),h),R(e,r,a.Sub(t[t.length-1],t[t.length-2]).normalize().scalarMult(a.Sub(r,t[t.length-1]).length()),h)}return h})(r.points,r);this.renderGraphic(t,e,{color:r.color,drawType:this.gl.TRIANGLES,points:i})}renderGraphic(t=0,e=0,r){if(r instanceof Array)return this.renderGraphic(t,e,{points:r});this.startGraphicDraw(),r.drawType&&(this.currentRegion.drawType=r.drawType),r.points.forEach((i=>{this.addGraphicVertex(i.x+t,i.y+e,r.color||this.defaultColorBlack)})),this.endGraphicDraw()}startGraphicDraw(t){this.setRegion("graphic",t),this.currentRegion.startRender()}addGraphicVertex(t,e,r){if(t instanceof a)return this.addGraphicVertex(t.x,t.y,e);this.currentRegion.addVertex(t,e,r.uint32)}endGraphicDraw(){this.currentRegion.render()}resize(t,e){this.width=t,this.height=e;const r=t*this.devicePixelRatio,i=e*this.devicePixelRatio;this.canvas.width=r,this.canvas.height=i,this.gl.viewport(0,0,r,i),this.projection=this.createOrthMatrix(0,t,e,0),this.projectionDirty=!0}clear(){const t=this.gl,e=this.backgroundColor;t.clearColor(e.r,e.g,e.b,e.a),t.clear(t.COLOR_BUFFER_BIT)}createOrthMatrix(t,e,r,i){return new Float32Array([2/(e-t),0,0,0,0,2/(i-r),0,0,0,0,-1,0,-(e+t)/(e-t),-(i+r)/(i-r),0,1])}transformPoint(t,e){return this.matrixStack.apply(t,e)}}export{u as BaseTexture,A as CapTyps,h as Color,r as DynamicArrayBuffer,p as GLShader,b as JoinTyps,s as MatrixStack,v as Rapid,d as SCALEFACTOR,c as Text,l as Texture,o as TextureCache,a as Vec2,i as WebglBufferArray,n as WebglElementBufferArray,m as graphicAttributes,E as spriteAttributes};
|
|
1
|
+
var t,e,i,s,r,n,a,o;!function(t){t.KEEP="keep",t.KEEP_H="keep_h",t.KEEP_W="keep_w",t.IGNORE="ignore",t.EXPAND="expand"}(t||(t={})),function(t){t.STRETCH="stretch",t.REPEAT="repeat"}(e||(e={})),function(t){t.REPEAT="repeat",t.CLAMP="clamp",t.MIRROR="mirror"}(i||(i={})),function(t){t.Include="normal",t.Exclude="inverse"}(s||(s={})),function(t){t.SQUARE="square",t.ISOMETRIC="isometric"}(r||(r={})),function(t){t.SPRITE="sprite",t.GRAPHIC="graphic"}(n||(n={})),function(t){t.Additive="additive",t.Subtractive="subtractive",t.Mix="mix"}(a||(a={})),function(t){t.POINT="point",t.CIRCLE="circle",t.RECT="rect"}(o||(o={}));var h;!function(t){t[t.Float32=0]="Float32",t[t.Uint32=1]="Uint32",t[t.Uint16=2]="Uint16"}(h||(h={}));class l{constructor(t){this.usedElemNum=0,this.maxElemNum=512,this.bytePerElem=this.getArrayType(t).BYTES_PER_ELEMENT,this.arrayType=t,this.arraybuffer=new ArrayBuffer(this.maxElemNum*this.bytePerElem),this.updateTypedArray()}getArrayType(t){switch(t){case h.Float32:return Float32Array;case h.Uint32:return Uint32Array;case h.Uint16:return Uint16Array}}updateTypedArray(){switch(this.uint32=new Uint32Array(this.arraybuffer),this.float32=new Float32Array(this.arraybuffer),this.uint16=new Uint16Array(this.arraybuffer),this.arrayType){case h.Float32:this.typedArray=this.float32;break;case h.Uint32:this.typedArray=this.uint32;break;case h.Uint16:this.typedArray=this.uint16}}clear(){this.usedElemNum=0}resize(t=0){if((t+=this.usedElemNum)>this.maxElemNum){for(;t>this.maxElemNum;)this.maxElemNum<<=1;this.setMaxSize(this.maxElemNum)}}setMaxSize(t=this.maxElemNum){const e=this.typedArray;this.maxElemNum=t,this.arraybuffer=new ArrayBuffer(t*this.bytePerElem),this.updateTypedArray(),this.typedArray.set(e)}pushUint32(t){this.uint32[this.usedElemNum++]=t}pushFloat32(t){this.float32[this.usedElemNum++]=t}pushUint16(t){this.uint16[this.usedElemNum++]=t}pop(t){this.usedElemNum-=t}getArray(t=0,e){return null==e?this.typedArray:this.typedArray.subarray(t,e)}get length(){return this.typedArray.length}}class u extends l{constructor(t,e,i=t.ARRAY_BUFFER,s=t.STATIC_DRAW){super(e),this.dirty=!0,this.webglBufferSize=0,this.gl=t,this.buffer=t.createBuffer(),this.type=i,this.usage=s}pushFloat32(t){super.pushFloat32(t),this.dirty=!0}pushUint32(t){super.pushUint32(t),this.dirty=!0}pushUint16(t){super.pushUint16(t),this.dirty=!0}bindBuffer(){this.gl.bindBuffer(this.type,this.buffer)}bufferData(){if(this.dirty){const t=this.gl;this.maxElemNum>this.webglBufferSize?(t.bufferData(this.type,this.getArray(),this.usage),this.webglBufferSize=this.maxElemNum):t.bufferSubData(this.type,0,this.getArray(0,this.usedElemNum)),this.dirty=!1}}}class c extends l{constructor(){super(h.Float32)}pushMat(){const t=this.usedElemNum-6,e=this.typedArray;this.resize(6),this.pushFloat32(e[t+0]),this.pushFloat32(e[t+1]),this.pushFloat32(e[t+2]),this.pushFloat32(e[t+3]),this.pushFloat32(e[t+4]),this.pushFloat32(e[t+5])}popMat(){this.pop(6)}pushIdentity(){this.resize(6),this.pushFloat32(1),this.pushFloat32(0),this.pushFloat32(0),this.pushFloat32(1),this.pushFloat32(0),this.pushFloat32(0)}translate(t,e){if("number"!=typeof t)return this.translate(t.x,t.y);const i=this.usedElemNum-6,s=this.typedArray;s[i+4]=s[i+0]*t+s[i+2]*e+s[i+4],s[i+5]=s[i+1]*t+s[i+3]*e+s[i+5]}rotate(t){const e=this.usedElemNum-6,i=this.typedArray,s=Math.cos(t),r=Math.sin(t),n=i[e+0],a=i[e+1],o=i[e+2],h=i[e+3];i[e+0]=n*s-a*r,i[e+1]=n*r+a*s,i[e+2]=o*s-h*r,i[e+3]=o*r+h*s}scale(t,e){if("number"!=typeof t)return this.scale(t.x,t.y);e||(e=t);const i=this.usedElemNum-6,s=this.typedArray;s[i+0]=s[i+0]*t,s[i+1]=s[i+1]*t,s[i+2]=s[i+2]*e,s[i+3]=s[i+3]*e}apply(t,e){if("number"!=typeof t)return new f(...this.apply(t.x,t.y));const i=this.usedElemNum-6,s=this.typedArray;return[s[i+0]*t+s[i+2]*e+s[i+4],s[i+1]*t+s[i+3]*e+s[i+5]]}getInverse(){const t=this.usedElemNum-6,e=this.typedArray,i=e[t+0],s=e[t+1],r=e[t+2],n=e[t+3],a=e[t+4],o=e[t+5],h=i*n-s*r;return new Float32Array([n/h,-s/h,-r/h,i/h,(r*o-n*a)/h,(s*a-i*o)/h])}getTransform(){const t=this.usedElemNum-6,e=this.typedArray;return new Float32Array([e[t+0],e[t+1],e[t+2],e[t+3],e[t+4],e[t+5]])}setTransform(t){const e=this.usedElemNum-6,i=this.typedArray;i[e+0]=t[0],i[e+1]=t[1],i[e+2]=t[2],i[e+3]=t[3],i[e+4]=t[4],i[e+5]=t[5]}getGlobalPosition(){const t=this.usedElemNum-6,e=this.typedArray;return new f(e[t+4],e[t+5])}setGlobalPosition(t,e){if("number"!=typeof t)return void this.setGlobalPosition(t.x,t.y);const i=this.usedElemNum-6,s=this.typedArray;s[i+4]=t,s[i+5]=e}getGlobalRotation(){const t=this.usedElemNum-6,e=this.typedArray;return Math.atan2(e[t+1],e[t+0])}setGlobalRotation(t){const e=this.usedElemNum-6,i=this.typedArray,s=this.getGlobalScale(),r=Math.cos(t),n=Math.sin(t);i[e+0]=r*s.x,i[e+1]=n*s.x,i[e+2]=-n*s.y,i[e+3]=r*s.y}getGlobalScale(){const t=this.usedElemNum-6,e=this.typedArray,i=Math.sqrt(e[t+0]*e[t+0]+e[t+1]*e[t+1]),s=Math.sqrt(e[t+2]*e[t+2]+e[t+3]*e[t+3]);return new f(i,s)}setGlobalScale(t,e){if("number"!=typeof t)return void this.setGlobalScale(t.x,t.y);const i=this.getGlobalRotation(),s=Math.cos(i),r=Math.sin(i),n=this.usedElemNum-6,a=this.typedArray;a[n+0]=s*t,a[n+1]=r*t,a[n+2]=-r*e,a[n+3]=s*e}globalToLocal(t){const e=this.getInverse();return new f(e[0]*t.x+e[2]*t.y+e[4],e[1]*t.x+e[3]*t.y+e[5])}localToGlobal(t){return this.apply(t)}toCSSTransform(){const t=this.usedElemNum-6,e=this.typedArray;return`matrix(${e[t+0]}, ${e[t+1]}, ${e[t+2]}, ${e[t+3]}, ${e[t+4]}, ${e[t+5]})`}identity(){const t=this.usedElemNum-6,e=this.typedArray;e[t+0]=1,e[t+1]=0,e[t+2]=0,e[t+3]=1,e[t+4]=0,e[t+5]=0}applyTransform(t,e=0,i=0){(t.saveTransform??1)&&this.pushMat(),t.afterSave&&t.afterSave();const s=t.x||0,r=t.y||0;(s||r)&&this.translate(s,r),t.position&&this.translate(t.position),t.rotation&&this.rotate(t.rotation),t.scale&&this.scale(t.scale);let n=t.offsetX||0,a=t.offsetY||0;t.offset&&(n+=t.offset.x,a+=t.offset.y);const o=t.origin;return o&&("number"==typeof o?(n-=o*e,a-=o*i):(n-=o.x*e,a-=o.y*i)),{offsetX:n,offsetY:a}}applyTransformAfter(t){t.beforRestore&&t.beforRestore(),(t.restoreTransform??1)&&this.popMat()}}class d extends u{constructor(t,e,i,s){super(t,h.Uint16,t.ELEMENT_ARRAY_BUFFER,t.STATIC_DRAW),this.setMaxSize(e*s);for(let t=0;t<s;t++)this.addObject(t*i);this.bindBuffer(),this.bufferData()}addObject(t){}}class p{constructor(t,e,i,s=255){this._r=t,this._g=e,this._b=i,this._a=s,this.updateUint()}get r(){return this._r}set r(t){this._r=t,this.updateUint()}get g(){return this._g}set g(t){this._g=t,this.updateUint()}get b(){return this._b}set b(t){this._b=t,this.updateUint()}get a(){return this._a}set a(t){this._a=t,this.updateUint()}updateUint(){this.uint32=(this._a<<24|this._b<<16|this._g<<8|this._r)>>>0}setRGBA(t,e,i,s){this.r=t,this.g=e,this.b=i,this.a=s,this.updateUint()}copy(t){this.setRGBA(t.r,t.g,t.b,t.a)}clone(){return new p(this._r,this._g,this._b,this._a)}equal(t){return t.r===this.r&&t.g===this.g&&t.b===this.b&&t.a===this.a}static fromHex(t){t.startsWith("#")&&(t=t.slice(1));const e=parseInt(t.slice(0,2),16),i=parseInt(t.slice(2,4),16),s=parseInt(t.slice(4,6),16);let r=255;return t.length>=8&&(r=parseInt(t.slice(6,8),16)),new p(e,i,s,r)}add(t){return new p(Math.min(this.r+t.r,255),Math.min(this.g+t.g,255),Math.min(this.b+t.b,255),Math.min(this.a+t.a,255))}subtract(t){return new p(Math.max(0,this.r-t.r),Math.max(0,this.g-t.g),Math.max(0,this.b-t.b),Math.max(0,this.a-t.a))}divide(t){return t instanceof p?new p(this.r/t.r,this.g/t.g,this.b/t.b,this.a/t.a):new p(this.r/t,this.g/t,this.b/t,this.a/t)}multiply(t){return t instanceof p?new p(this.r*t.r,this.g*t.g,this.b*t.b,this.a*t.a):new p(this.r*t,this.g*t,this.b*t,this.a*t)}clamp(){this.r=Math.max(0,Math.min(255,this.r)),this.g=Math.max(0,Math.min(255,this.g)),this.b=Math.max(0,Math.min(255,this.b)),this.a=Math.max(0,Math.min(255,this.a))}}p.Red=new p(255,0,0,255),p.Green=new p(0,255,0,255),p.Blue=new p(0,0,255,255),p.Yellow=new p(255,255,0,255),p.Purple=new p(128,0,128,255),p.Orange=new p(255,165,0,255),p.Pink=new p(255,192,203,255),p.Gray=new p(128,128,128,255),p.Brown=new p(139,69,19,255),p.Cyan=new p(0,255,255,255),p.Magenta=new p(255,0,255,255),p.Lime=new p(192,255,0,255),p.White=new p(255,255,255,255),p.Black=new p(0,0,0,255),p.TRANSPARENT=new p(0,0,0,0);class f{constructor(t,e){this.x=void 0!==t?t:0,this.y=void 0!==e?e:0}set(t,e){return Array.isArray(t)?(this.x=t[0],this.y=t[0]):e?(this.x=t,this.y=e):(this.x=t,this.y=t),this}add(t){return new f(this.x+t.x,this.y+t.y)}subtract(t){return new f(this.x-t.x,this.y-t.y)}multiply(t){return t instanceof f?new f(this.x*t.x,this.y*t.y):new f(this.x*t,this.y*t)}divide(t){return t instanceof f?new f(this.x/t.x,this.y/t.y):new f(this.x/t,this.y/t)}dot(t){return this.x*t.x+this.y*t.y}cross(t){return this.x*t.y-this.y*t.x}distanceTo(t){const e=this.x-t.x,i=this.y-t.y;return Math.sqrt(e*e+i*i)}clone(){return new f(this.x,this.y)}copy(t){this.x=t.x,this.y=t.y}equal(t){return t.x==this.x&&t.y==this.y}perpendicular(){const t=this.x;return this.x=-this.y,this.y=t,this}invert(){return this.x=-this.x,this.y=-this.y,this}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}normalize(){const t=this.length();return this.x=this.x/t||0,this.y=this.y/t||0,this}angle(){return Math.atan2(this.y,this.x)}middle(t){return new f((this.x+t.x)/2,(this.y+t.y)/2)}abs(){return new f(Math.abs(this.x),Math.abs(this.y))}floor(){return new f(Math.floor(this.x),Math.floor(this.y))}ceil(){return new f(Math.ceil(this.x),Math.ceil(this.y))}snap(t){return new f(Math.round(this.x/t)*t,Math.round(this.y/t)*t)}stringify(){return`Vec2(${this.x}, ${this.y})`}static FromArray(t){return t.map((t=>new f(t[0],t[1])))}static fromAngle(t){return new f(Math.cos(t),Math.sin(t))}angleBetween(t){const e=this.dot(t),i=this.length()*t.length(),s=Math.max(-1,Math.min(1,e/i));return Math.acos(s)}}f.ZERO=new f(0,0),f.ONE=new f(1,1),f.UP=new f(0,1),f.DOWN=new f(0,-1),f.LEFT=new f(-1,0),f.RIGHT=new f(1,0);class m{static deg2rad(t){return t*(Math.PI/180)}static rad2deg(t){return t/(Math.PI/180)}static normalizeDegrees(t){return(t%360+360)%360}}class g{static float(t,e){return Math.random()*(e-t)+t}static int(t,e){return Math.floor(Math.random()*(e-t+1))+t}static angle(){return Math.random()*Math.PI*2}static vector(t,e,i,s){return new f(g.float(t,e),g.float(i,s))}static direction(t){const e=g.angle();return new f(Math.cos(e)*t,Math.sin(e)*t)}static randomColor(t,e){return new p(g.float(t.r,e.r),g.float(t.g,e.g),g.float(t.b,e.b),g.float(t.a,e.a))}static pick(t){return t[g.int(0,t.length-1)]}static pickWeight(t){if(!t||0===t.length)return null;let e=0;for(const i of t)e+=i[1];const i=Math.random()*e;let s=0;for(const e of t)if(s+=e[1],i<=s)return e[0];return t[t.length-1][0]}static scalarOrRange(t,e){if(void 0===t)return e;if(Array.isArray(t)){if("number"==typeof t[0])return g.float(t[0],t[1]);if(t[0]instanceof f)return g.vector(t[0].x,t[1].x,t[0].y,t[1].y);if(t[0]instanceof p)return g.randomColor(t[0],t[1])}return"number"==typeof t?t:t.clone()}}class y{constructor(t){this.render=t}createLightShadowMaskPolygon(t,e,i){const s=[];t.forEach((t=>{for(let e=0;e<t.length;e++){const i=t[e],r=t[(e+1)%t.length];s.push([i,r])}})),i=i||Math.sqrt(Math.pow(this.render.width,2)+Math.pow(this.render.height,2));const r=[];return s.forEach((([t,s])=>{const n=new f(t.x-e.x,t.y-e.y),a=new f(s.x-e.x,s.y-e.y),o=s.subtract(t).perpendicular(),h=Math.abs(o.dot(n))/(o.length()*n.length())+.01,l=Math.abs(o.dot(a))/(o.length()*a.length())+.01,u=i/h,c=i/l,d=new f(n.x,n.y).normalize(),p=new f(a.x,a.y).normalize(),m=new f(t.x+d.x*u,t.y+d.y*u),g=new f(s.x+p.x*c,s.y+p.y*c);r.push([t,s,g,m])})),r}}const x=(t,e,i,s)=>{const r=[],n=s?Math.atan2(e.y,e.x):Math.atan2(-e.y,-e.x),a=Math.PI;for(let e=0;e<10;e++){const s=n+e/10*a,o=n+(e+1)/10*a,h=Math.cos(s)*i,l=Math.sin(s)*i,u=Math.cos(o)*i,c=Math.sin(o)*i;r.push(t),r.push(t.add(new f(h,l))),r.push(t.add(new f(u,c)))}return r},w=t=>{const i=t.points;if(i.length<2)return{vertices:[],uv:[]};const{normals:s,length:r}=((t,e=!1)=>{const i=[];if(t.length<2||e&&t.length<3)return{normals:i,length:0};const s=t.length;let r=0;if(e)for(let e=0;e<s;e++){const i=t[e],n=t[(e+1)%s];r+=i.distanceTo(n)}else for(let e=0;e<s-1;e++)r+=t[e].distanceTo(t[e+1]);const n=(t,e,i)=>{const s=e.subtract(t).normalize(),r=e.subtract(i).normalize(),n=r.dot(s);if(n<-.999)return{normal:s.perpendicular(),miters:1};{let t=r.add(s).normalize();s.cross(r)<0&&(t=t.multiply(-1));let e=1/Math.sqrt((1-n)/2);return{normal:t,miters:Math.min(e,4)}}};if(e){for(let e=0;e<s-1;e++){const r=0===e?t[s-2]:t[e-1],a=t[e],o=t[e+1];i.push(n(r,a,o))}i.push(i[0])}else for(let e=0;e<s;e++)if(0===e){const e=t[1].subtract(t[0]).normalize();i.push({normal:e.perpendicular(),miters:1})}else if(e===s-1){const s=t[e].subtract(t[e-1]).normalize();i.push({normal:s.perpendicular(),miters:1})}else i.push(n(t[e-1],t[e],t[e+1]));return{normals:i,length:r}})(i,t.closed),n=(t.width||1)/2,a=[],o=[],h=t.roundCap||!1,l=t.textureMode||e.STRETCH;let u=0;const c=t.texture?.width||1;for(let t=0;t<i.length-1;t++){const h=i[t],d=s[t].normal,p=s[t].miters,m=h.add(d.multiply(p*n)),g=h.subtract(d.multiply(p*n)),y=i[t+1],x=s[t+1].normal,w=s[t+1].miters,T=y.add(x.multiply(w*n)),b=y.subtract(x.multiply(w*n)),E=h.distanceTo(y);let R=0,v=0;l===e.STRETCH?(R=u/r,v=(u+E)/r):(R=u/c,v=R+E/c);const A=new f(R,0),S=new f(R,1),M=new f(v,0),U=new f(v,1);a.push(m),o.push(A),a.push(g),o.push(S),a.push(T),o.push(M),a.push(T),o.push(M),a.push(b),o.push(U),a.push(g),o.push(S),u+=E}if(h&&!t.closed){const t=i[0],e=s[0].normal,r=x(t,e,n,!0);a.push(...r);const o=i[i.length-1],h=s[i.length-1].normal,l=x(o,h,n,!1);a.push(...l)}return{vertices:a,uv:o}};var T="precision mediump float;\r\nvarying vec2 vRegion;\r\nvarying vec4 vColor;\r\n\r\nuniform sampler2D uTexture;\r\nuniform int uUseTexture;\r\n\r\nvoid main(void) {\r\n vec4 color;\r\n if(uUseTexture > 0){\r\n color = texture2D(uTexture, vRegion) * vColor;\r\n }else{\r\n color = vColor;\r\n }\r\n // fragment\r\n gl_FragColor = color;\r\n}\r\n",b="precision mediump float;\r\n\r\nattribute vec2 aPosition;\r\nattribute vec4 aColor;\r\nattribute vec2 aRegion;\r\n\r\nvarying vec4 vColor;\r\nuniform mat4 uProjectionMatrix;\r\nuniform vec4 uColor;\r\nvarying vec2 vRegion;\r\n\r\nvoid main(void) {\r\n // vertex s\r\n gl_Position = uProjectionMatrix * vec4(aPosition, 0.0, 1.0);\r\n // vertex e\r\n vColor = aColor;\r\n vRegion = aRegion;\r\n}\r\n";const E=(t,e,i)=>{const s=t.createShader(i);if(!s)throw new Error("Unable to create webgl shader");t.shaderSource(s,e),t.compileShader(s);if(!t.getShaderParameter(s,t.COMPILE_STATUS)){const i=t.getShaderInfoLog(s);throw console.error("Shader compilation failed:",i),new Error("Unable to compile shader: "+i+e)}return s};function R(t,e,i,s=!1,r=!1,n="clamp"){const a=t.createTexture();if(!a)throw new Error("unable to create texture");let o;switch(t.bindTexture(t.TEXTURE_2D,a),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,i?t.LINEAR:t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,i?t.LINEAR:t.NEAREST),n){case"repeat":o=t.REPEAT;break;case"mirror":o=t.MIRRORED_REPEAT;break;default:o=t.CLAMP_TO_EDGE}return t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,o),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,o),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,r),s?t.texImage2D(t.TEXTURE_2D,0,t.RGBA,e.width,e.height,0,t.RGBA,t.UNSIGNED_BYTE,null):t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),a}const v=5126;var A="precision mediump float;\r\nuniform sampler2D uTextures[%TEXTURE_NUM%];\r\n\r\nvarying vec2 vRegion;\r\nvarying float vTextureId;\r\nvarying vec4 vColor;\r\n\r\nvoid main(void) {\r\n vec4 color;\r\n %GET_COLOR%\r\n // fragment\r\n gl_FragColor = color * vColor;\r\n}",S="precision mediump float;\r\n\r\nattribute vec2 aPosition;\r\nattribute vec2 aRegion;\r\nattribute float aTextureId;\r\nattribute vec4 aColor;\r\n\r\nuniform mat4 uProjectionMatrix;\r\n\r\nvarying vec2 vRegion;\r\nvarying float vTextureId;\r\nvarying vec4 vColor;\r\n\r\nvoid main(void) {\r\n vRegion = aRegion;\r\n vTextureId = aTextureId;\r\n vColor = aColor;\r\n\r\n // vertex s\r\n gl_Position = uProjectionMatrix * vec4(aPosition, 0.0, 1.0);\r\n // vertex e\r\n}";const M=[{name:"aPosition",size:2,type:v,stride:24},{name:"aRegion",size:2,type:v,stride:24,offset:2*Float32Array.BYTES_PER_ELEMENT},{name:"aTextureId",size:1,type:v,stride:24,offset:4*Float32Array.BYTES_PER_ELEMENT},{name:"aColor",size:4,type:5121,stride:24,offset:5*Float32Array.BYTES_PER_ELEMENT,normalized:!0}],U=[{name:"aPosition",size:2,type:v,stride:20},{name:"aColor",size:4,type:5121,stride:20,offset:2*Float32Array.BYTES_PER_ELEMENT,normalized:!0},{name:"aRegion",size:2,type:v,stride:20,offset:3*Float32Array.BYTES_PER_ELEMENT}];class C{constructor(t,e,i,s,r=0){this.attributeLoc={},this.uniformLoc={},this.textureUnitNum=0,this.attributes=[];const n=function(t,e){if(t.includes("%TEXTURE_NUM%")&&(t=t.replace("%TEXTURE_NUM%",e.toString())),t.includes("%GET_COLOR%")){let i="";for(let t=0;t<e;t++)i+=0==t?`if(vTextureId == ${t}.0)`:t==e-1?"else":`else if(vTextureId == ${t}.0)`,i+=`{color = texture2D(uTextures[${t}], vRegion);}`;t=t.replace("%GET_COLOR%",i)}return t}(i,t.maxTextureUnits-r);this.program=((t,e,i)=>{var s=t.createProgram(),r=E(t,e,35633),n=E(t,i,35632);if(!s)throw new Error("Unable to create program shader");if(t.attachShader(s,r),t.attachShader(s,n),t.linkProgram(s),!t.getProgramParameter(s,t.LINK_STATUS)){const e=t.getProgramInfoLog(s);throw new Error("Unable to link shader program: "+e)}return s})(t.gl,e,n),this.gl=t.gl,this.textureUnitNum=r,this.parseShader(e),this.parseShader(n),s&&this.setAttributes(s)}setUniforms(t,e){const i=this.gl;for(const s of t.getUnifromNames()){const r=this.getUniform(s);t.bind(i,s,r,e)}}getUniform(t){return this.uniformLoc[t]}use(){this.gl.useProgram(this.program)}parseShader(t){const e=this.gl,i=t.match(/attribute\s+\w+\s+(\w+)/g);if(i)for(const t of i){const i=t.split(" ")[2],s=e.getAttribLocation(this.program,i);-1!=s&&(this.attributeLoc[i]=s)}const s=t.match(/uniform\s+\w+\s+(\w+)/g);if(s)for(const t of s){const i=t.split(" ")[2];this.uniformLoc[i]=e.getUniformLocation(this.program,i)}}setAttribute(t){const e=this.attributeLoc[t.name];if(void 0!==e){const i=this.gl;i.vertexAttribPointer(e,t.size,t.type,t.normalized||!1,t.stride,t.offset||0),i.enableVertexAttribArray(e)}}setAttributes(t){this.attributes=t;for(const e of t)this.setAttribute(e)}updateAttributes(){this.setAttributes(this.attributes)}static createCostumShader(t,e,i,s,r=0){let a={[n.SPRITE]:A,[n.GRAPHIC]:T}[s],o={[n.SPRITE]:S,[n.GRAPHIC]:b}[s];const h={[n.SPRITE]:M,[n.GRAPHIC]:U}[s];return a=a.replace("void main(void) {",i+"\nvoid main(void) {"),o=o.replace("void main(void) {",e+"\nvoid main(void) {"),a=a.replace("// fragment","fragment(color);"),o=o.replace(/\/\/ vertex s[\s\S]*?\/\/ vertex e/,"vec2 position = aPosition;\n vertex(position, vRegion);\n gl_Position = uProjectionMatrix * vec4(position, 0.0, 1.0);"),new C(t,o,a,h,r)}}class _{constructor(t){this.usedTextures=[],this.shaders=new Map,this.isCostumShader=!1,this.freeTextureUnitNum=0,this.rapid=t,this.gl=t.gl,this.webglArrayBuffer=new u(t.gl,h.Float32,t.gl.ARRAY_BUFFER,t.gl.STREAM_DRAW),this.maxTextureUnits=t.maxTextureUnits}getTextureUnitList(){return Array.from({length:this.maxTextureUnits},((t,e)=>e))}addVertex(t,e,...i){const[s,r]=this.rapid.matrixStack.apply(t,e);this.webglArrayBuffer.pushFloat32(s),this.webglArrayBuffer.pushFloat32(r)}useTexture(t){const e=this.usedTextures.indexOf(t);return-1==e?(this.usedTextures.push(t),this.freeTextureUnitNum=this.maxTextureUnits-this.usedTextures.length,[this.usedTextures.length-1,!0]):[e,!1]}enterRegion(t){this.currentShader=t??this.getShader("default"),this.currentShader.use(),this.initializeForNextRender(),this.webglArrayBuffer.bindBuffer(),this.currentShader.updateAttributes(),this.updateProjection(),this.isCostumShader=Boolean(t)}updateProjection(){this.gl.uniformMatrix4fv(this.currentShader.uniformLoc.uProjectionMatrix,!1,this.rapid.projection)}isUnifromChanged(t){return!!t&&(this.costumUnifrom!=t||!!t?.isDirty)}setCurrentUniform(t){t.clearDirty(),this.costumUnifrom=t}exitRegion(){}initDefaultShader(t,e,i){this.setShader("default",t,e,i)}setShader(t,e,i,s){this.webglArrayBuffer.bindBuffer(),this.shaders.set(t,new C(this.rapid,e,i,s)),"default"===t&&(this.defaultShader=this.shaders.get(t))}getShader(t){return this.shaders.get(t)}render(){this.executeRender(),this.initializeForNextRender()}executeRender(){const t=this.gl;for(let e=0;e<this.usedTextures.length;e++)t.activeTexture(t.TEXTURE0+e),t.bindTexture(t.TEXTURE_2D,this.usedTextures[e]);this.webglArrayBuffer.bufferData()}initializeForNextRender(){this.webglArrayBuffer.clear(),this.usedTextures.length=0,this.isCostumShader=!1,this.freeTextureUnitNum=this.maxTextureUnits}hasPendingContent(){return!1}isShaderChanged(t){return(t||this.defaultShader)!=this.currentShader}}class F extends _{constructor(t){super(t),this.vertex=0,this.offset=f.ZERO,this.drawType=t.gl.TRIANGLE_FAN,this.setShader("default",b,T,U)}startRender(t,e,i,s){s&&this.currentShader?.setUniforms(s,this),this.offset=new f(t,e),this.vertex=0,this.webglArrayBuffer.clear(),i&&i.base&&(this.texture=this.useTexture(i.base.texture)[0])}addVertex(t,e,i,s,r){this.webglArrayBuffer.resize(3),super.addVertex(t+this.offset.x,e+this.offset.y),this.webglArrayBuffer.pushUint32(r),this.webglArrayBuffer.pushFloat32(i),this.webglArrayBuffer.pushFloat32(s),this.vertex+=1}executeRender(){super.executeRender();const t=this.gl;t.uniform1i(this.currentShader.uniformLoc.uUseTexture,void 0===this.texture?0:1),this.texture&&t.uniform1i(this.currentShader.uniformLoc.uTexture,this.texture),t.drawArrays(this.drawType,0,this.vertex),this.drawType=this.rapid.gl.TRIANGLE_FAN,this.vertex=0,this.texture=void 0}}const P=Math.floor(16384);class L extends d{constructor(t,e){super(t,6,4,e)}addObject(t){super.addObject(),this.pushUint16(t),this.pushUint16(t+1),this.pushUint16(t+2),this.pushUint16(t),this.pushUint16(t+3),this.pushUint16(t+2)}}class D extends _{constructor(t){const e=t.gl;super(t),this.batchSprite=0,this.spriteTextureUnits=[],this.spriteTextureUnitIndexOffset=0,this.setShader("default",S,A,M),this.indexBuffer=new L(e,P)}addVertex(t,e,i,s,r,n){super.addVertex(t,e),this.webglArrayBuffer.pushFloat32(i),this.webglArrayBuffer.pushFloat32(s),this.webglArrayBuffer.pushFloat32(r),this.webglArrayBuffer.pushUint32(n)}renderSprite(t,e,i,s,r,n,a,o,h,l,u,c,d,p=0){(1+p>this.freeTextureUnitNum||this.batchSprite>=P||this.isUnifromChanged(u)||this.rapid.projectionDirty)&&(this.render(),u&&this.isUnifromChanged(u)&&(this.currentShader.setUniforms(u,this),this.setCurrentUniform(u)),this.rapid.projectionDirty&&this.updateProjection()),this.batchSprite++,this.webglArrayBuffer.resize(20);const[f,m]=this.useTexture(t);m&&(this.spriteTextureUnits.push(f),this.spriteTextureUnitIndexOffset=this.spriteTextureUnits[0]);const g=f-this.spriteTextureUnitIndexOffset,y=c?n:s,x=c?s:n,w=d?a:r,T=d?r:a,b=o,E=o+e,R=h,v=h+i;this.addVertex(b,R,y,w,g,l),this.addVertex(E,R,x,w,g,l),this.addVertex(E,v,x,T,g,l),this.addVertex(b,v,y,T,g,l)}executeRender(){if(super.executeRender(),this.batchSprite<=0)return;const t=this.gl;this.spriteTextureUnits.length>0&&this.gl.uniform1iv(this.currentShader.uniformLoc.uTextures,this.spriteTextureUnits),t.drawElements(t.TRIANGLES,6*this.batchSprite,t.UNSIGNED_SHORT,0)}enterRegion(t){super.enterRegion(t),this.indexBuffer.bindBuffer()}initializeForNextRender(){super.initializeForNextRender(),this.batchSprite=0,this.spriteTextureUnits.length=0}hasPendingContent(){return this.batchSprite>0}}class N{constructor(t,e){this.cache=new Map,this.render=t,this.antialias=e}async textureFromUrl(t,e=this.antialias,s=i.CLAMP){let r=this.cache.get(t);if(!r){const i=await this.loadImage(t);r=I.fromImageSource(this.render,i,e,s),this.cache.set(t,r)}return new k(r)}textureFromFrameBufferObject(t){return new k(t)}textureFromSource(t,e=this.antialias,s=i.CLAMP){let r=this.cache.get(t);return r||(r=I.fromImageSource(this.render,t,e,s),this.cache.set(t,r)),new k(r)}async loadImage(t){return new Promise((e=>{const i=new Image;i.onload=()=>{e(i)},i.src=t}))}createText(t){return new B(this.render,t)}destroy(t){t instanceof k?(t.base?.destroy(this.render.gl),this.removeCache(t)):(t.destroy(this.render.gl),this.removeCache(t))}createFrameBufferObject(t,e,i=this.antialias){return new G(this.render,t,e,i)}removeCache(t){const e=t instanceof k?t.base?.texture:t.texture;e&&this.cache.forEach(((t,i)=>{t===e&&this.cache.delete(i)}))}}class I{constructor(t,e,s,r=i.CLAMP){this.texture=t,this.width=e,this.height=s,this.wrapMode=r}static fromImageSource(t,e,s=!1,r=i.CLAMP){return new I(R(t.gl,e,s,!1,!1,r),e.width,e.height)}destroy(t){t.deleteTexture(this.texture)}}class k{constructor(t){this.scale=1,this.setBaseTextur(t)}setBaseTextur(t){t&&(this.base=t,this.setClipRegion(0,0,t.width,t.height))}setClipRegion(t,e,i,s){if(this.base)return this.clipX=t/this.base.width,this.clipY=e/this.base.height,this.clipW=this.clipX+i/this.base.width,this.clipH=this.clipY+s/this.base.height,this.width=i*this.scale,this.height=s*this.scale,this}static fromImageSource(t,e,i=!1){return new k(I.fromImageSource(t,e,i))}createSpritesHeet(t,e){if(!this.base)return[];const i=[],s=Math.floor(this.base.width/t),r=Math.floor(this.base.height/e);for(let n=0;n<r;n++)for(let r=0;r<s;r++){const s=this.clone();s.setClipRegion(r*t,n*e,t,e),i.push(s)}return i}clone(){return new k(this.base)}}const O=2;class B extends k{constructor(t,e){super(),this.scale=.5,this.rapid=t,this.options=e,this.text=e.text||" ",this.updateTextImage()}updateTextImage(){const t=this.createTextCanvas();this.setBaseTextur(I.fromImageSource(this.rapid,t,!0))}createTextCanvas(){const t=document.createElement("canvas"),e=t.getContext("2d");if(!e)throw new Error("Failed to get canvas context");e.font=`${this.options.fontSize||16}px ${this.options.fontFamily||"Arial"}`,e.fillStyle=this.options.color||"#000",e.textAlign=this.options.textAlign||"left",e.textBaseline=this.options.textBaseline||"top";const i=this.text.split("\n");let s=0,r=0;for(const t of i){const i=e.measureText(t);s=Math.max(s,i.width),r+=this.options.fontSize||16}t.width=2*s,t.height=2*r,e.scale(2,2),e.font=`${this.options.fontSize||16}px ${this.options.fontFamily||"Arial"}`,e.fillStyle=this.options.color||"#000",e.textAlign=this.options.textAlign||"left",e.textBaseline=this.options.textBaseline||"top";let n=0;for(const t of i)e.fillText(t,0,n),n+=this.options.fontSize||16;return t}setText(t){this.text!=t&&(this.text=t,this.updateTextImage())}}class G extends I{constructor(t,e,i,s=!1){const r=t.gl,n=R(r,{width:e,height:i},s,!0,!1),a=r.createFramebuffer();if(!a)throw r.deleteTexture(n),new Error("Failed to create WebGL framebuffer");r.bindFramebuffer(r.FRAMEBUFFER,a),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,n,0);const o=r.createRenderbuffer();if(!o)throw r.deleteFramebuffer(a),r.deleteTexture(n),new Error("Failed to create depth-stencil renderbuffer");r.bindRenderbuffer(r.RENDERBUFFER,o),r.renderbufferStorage(r.RENDERBUFFER,r.STENCIL_INDEX8,e,i),r.framebufferRenderbuffer(r.FRAMEBUFFER,r.STENCIL_ATTACHMENT,r.RENDERBUFFER,o),super(n,e,i),this.gl=r,this.framebuffer=a,r.bindTexture(r.TEXTURE_2D,null),r.bindFramebuffer(r.FRAMEBUFFER,null)}bind(){const t=this.gl;t.bindTexture(t.TEXTURE_2D,null),t.bindFramebuffer(t.FRAMEBUFFER,this.framebuffer),t.clearColor(.5,.2,.5,.5),t.clear(t.COLOR_BUFFER_BIT)}unbind(){this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,null),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}resize(t,e){this.width=t,this.height=e,this.gl.bindTexture(this.gl.TEXTURE_2D,this.texture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,t,e,0,this.gl.RGBA,this.gl.UNSIGNED_BYTE,null),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}destroy(t){t.deleteFramebuffer(this.framebuffer),super.destroy(t)}}class z{constructor(t,e){this.textures=new Map,this.width=t,this.height=e}setTile(t,e){e instanceof k&&(e={texture:e}),this.textures.set(t,e)}getTile(t){return this.textures.get(t)}}class j{constructor(t){this.rapid=t}getYSortRow(t,e){const i=new Map;if(!t)return i;for(const s of t){const t=Math.floor(s.ySort/e);i.has(t)||i.set(t,[]),i.get(t).push(s)}return i}getOffset(t){let e=(t.errorX??2)+1,i=(t.errorY??2)+1;if("number"==typeof t.error){const s=(t.error??2)+1;e=s,i=s}else t.error&&(e=t.error.x+1,i=t.error.y+1);return{errorX:e,errorY:i}}renderYSortRow(t,e){if(e&&0!==e.length)for(const i of e)i.render?i.render():i.entity?i.entity.onRender(t):i.renderSprite&&t.renderSprite(i.renderSprite)}getTileData(t,e){const i=e.shape??r.SQUARE,s=t.width,n=i===r.ISOMETRIC?t.height/2:t.height,a=this.rapid.matrixStack,{errorX:o,errorY:h}=this.getOffset(e),l=new f(0,0),u=new f(this.rapid.width,0),c=new f(0,this.rapid.height),d=new f(this.rapid.width,this.rapid.height),p=a.globalToLocal(l),m=a.globalToLocal(u),g=a.globalToLocal(c),y=a.globalToLocal(d),x=Math.min(p.x,m.x,g.x,y.x),w=Math.max(p.x,m.x,g.x,y.x),T=Math.min(p.y,m.y,g.y,y.y),b=Math.max(p.y,m.y,g.y,y.y),E=new f(Math.floor(x/s)-o,Math.floor(T/n)-h),R=new f(Math.ceil(w/s)+o,Math.ceil(b/n)+h);return{startTile:E,viewportWidth:R.x-E.x,viewportHeight:R.y-E.y,height:n}}renderLayer(t,e){this.rapid.matrixStack.applyTransform(e);const i=e.tileSet,{startTile:s,viewportWidth:r,viewportHeight:n,height:a}=this.getTileData(i,e),o=this.getYSortRow(e.ySortCallback,a),h=e.ySortCallback&&e.ySortCallback.length>0;for(let a=0;a<n;a++){const n=a+s.y,l=o.get(n)??[];if(n<0||n>=t.length)this.renderYSortRow(this.rapid,l);else{for(let a=0;a<r;a++){const r=a+s.x;if(r<0||r>=t[n].length)continue;const o=t[n][r],h=i.getTile(o);if(!h)continue;const u=this.mapToLocal(new f(r,n),e),c=this.rapid.matrixStack.localToGlobal(u).y+(h.ySortOffset??0),d=e.eachTile&&e.eachTile(o,r,n)||{};l.push({ySort:c,renderSprite:{...h,x:u.x+(h.x||0),y:u.y+(h.y||0),...d}})}h&&l.sort(((t,e)=>t.ySort-e.ySort)),this.renderYSortRow(this.rapid,l)}}this.rapid.matrixStack.applyTransformAfter(e)}localToMap(t,e){const i=e.tileSet;if(e.shape===r.ISOMETRIC){let e=0,s=0;const r=i.height/2,n=i.width/2;let a=Math.floor(t.y/r);const o=a%2==0;let h=Math.floor(t.x/n);const l=h%2==0,u=t.x%n/n,c=t.y%r/r,d=c<u,p=c<1-u;return o||(a-=1),d&&!l&&o?a-=1:d||!l||o?p&&l&&o?(h-=2,a-=1):p||l||o||(a+=1):(a+=1,h-=2),e=h,s=a,e=Math.floor(h/2),new f(e,s)}return new f(Math.floor(t.x/i.width),Math.floor(t.y/i.height))}mapToLocal(t,e){const i=e.tileSet;if(e.shape===r.ISOMETRIC){let e=new f(t.x*i.width,t.y*i.height/2);return t.y%2!=0&&(e.x+=i.width/2),e}return new f(t.x*i.width,t.y*i.height)}}function X(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Y,H={exports:{}};var W=(Y||(Y=1,function(t){var e=Object.prototype.hasOwnProperty,i="~";function s(){}function r(t,e,i){this.fn=t,this.context=e,this.once=i||!1}function n(t,e,s,n,a){if("function"!=typeof s)throw new TypeError("The listener must be a function");var o=new r(s,n||t,a),h=i?i+e:e;return t._events[h]?t._events[h].fn?t._events[h]=[t._events[h],o]:t._events[h].push(o):(t._events[h]=o,t._eventsCount++),t}function a(t,e){0==--t._eventsCount?t._events=new s:delete t._events[e]}function o(){this._events=new s,this._eventsCount=0}Object.create&&(s.prototype=Object.create(null),(new s).__proto__||(i=!1)),o.prototype.eventNames=function(){var t,s,r=[];if(0===this._eventsCount)return r;for(s in t=this._events)e.call(t,s)&&r.push(i?s.slice(1):s);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(t)):r},o.prototype.listeners=function(t){var e=i?i+t:t,s=this._events[e];if(!s)return[];if(s.fn)return[s.fn];for(var r=0,n=s.length,a=new Array(n);r<n;r++)a[r]=s[r].fn;return a},o.prototype.listenerCount=function(t){var e=i?i+t:t,s=this._events[e];return s?s.fn?1:s.length:0},o.prototype.emit=function(t,e,s,r,n,a){var o=i?i+t:t;if(!this._events[o])return!1;var h,l,u=this._events[o],c=arguments.length;if(u.fn){switch(u.once&&this.removeListener(t,u.fn,void 0,!0),c){case 1:return u.fn.call(u.context),!0;case 2:return u.fn.call(u.context,e),!0;case 3:return u.fn.call(u.context,e,s),!0;case 4:return u.fn.call(u.context,e,s,r),!0;case 5:return u.fn.call(u.context,e,s,r,n),!0;case 6:return u.fn.call(u.context,e,s,r,n,a),!0}for(l=1,h=new Array(c-1);l<c;l++)h[l-1]=arguments[l];u.fn.apply(u.context,h)}else{var d,p=u.length;for(l=0;l<p;l++)switch(u[l].once&&this.removeListener(t,u[l].fn,void 0,!0),c){case 1:u[l].fn.call(u[l].context);break;case 2:u[l].fn.call(u[l].context,e);break;case 3:u[l].fn.call(u[l].context,e,s);break;case 4:u[l].fn.call(u[l].context,e,s,r);break;default:if(!h)for(d=1,h=new Array(c-1);d<c;d++)h[d-1]=arguments[d];u[l].fn.apply(u[l].context,h)}}return!0},o.prototype.on=function(t,e,i){return n(this,t,e,i,!1)},o.prototype.once=function(t,e,i){return n(this,t,e,i,!0)},o.prototype.removeListener=function(t,e,s,r){var n=i?i+t:t;if(!this._events[n])return this;if(!e)return a(this,n),this;var o=this._events[n];if(o.fn)o.fn!==e||r&&!o.once||s&&o.context!==s||a(this,n);else{for(var h=0,l=[],u=o.length;h<u;h++)(o[h].fn!==e||r&&!o[h].once||s&&o[h].context!==s)&&l.push(o[h]);l.length?this._events[n]=1===l.length?l[0]:l:a(this,n)}return this},o.prototype.removeAllListeners=function(t){var e;return t?(e=i?i+t:t,this._events[e]&&a(this,e)):(this._events=new s,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=i,o.EventEmitter=o,t.exports=o}(H)),H.exports),K=X(W);class $ extends K{constructor(t,e,i,s,r){super(),this.elapsed=0,this.isRunning=!1,this.isFinished=!1,this.target=t,this.property=e,this.to=i,this.duration=s,this.easing=r}start(){const t=this.target[this.property];if("number"==typeof t)this.from=t;else{if("function"!=typeof t.clone)return console.error("Tween target property is not a 'number' or does not have a 'clone' method."),void(this.isFinished=!0);this.from=t.clone()}this.elapsed=0,this.isRunning=!0,this.isFinished=!1}update(t){if(!this.isRunning||this.isFinished)return;this.elapsed+=t;const e=Math.min(this.elapsed/this.duration,1),i=this.easing(e);let s;if("number"==typeof this.from&&"number"==typeof this.to)s=this.from+(this.to-this.from)*i;else{const t=this.from,e=this.to.subtract(t).multiply(i);s=t.add(e)}this.target[this.property]=s,e>=1&&(this.isFinished=!0,this.isRunning=!1,this.target[this.property]=this.to,this.emit("complete"))}}class q{}q.Linear=t=>t,q.EaseInQuad=t=>t*t,q.EaseOutQuad=t=>t*(2-t),q.EaseInOutQuad=t=>t<.5?2*t*t:(4-2*t)*t-1,q.EaseInCubic=t=>t*t*t,q.EaseOutCubic=t=>--t*t*t+1,q.EaseInOutCubic=t=>t<.5?4*t*t*t:(t-1)*(2*t-2)*(2*t-2)+1,q.EaseInQuart=t=>t*t*t*t,q.EaseOutQuart=t=>1- --t*t*t*t,q.EaseInOutQuart=t=>t<.5?8*t*t*t*t:1-8*--t*t*t*t;class Q extends K{constructor(t,e=!1){super(),this.elapsedTime=0,this.isRunning=!1,this.isFinished=!1,this.duration=t,this.repeat=e}start(){this.isRunning=!0}stop(){this.isRunning=!1}update(t){this.isRunning&&!this.isFinished&&(this.elapsedTime+=t,this.elapsedTime>=this.duration&&(this.emit("timeout"),this.repeat?this.elapsedTime-=this.duration:(this.isFinished=!0,this.isRunning=!1)))}destroy(){this.isFinished=!0,this.isRunning=!1}}const Z=!0;class V{constructor(t,e){this.life=0,this.datas={},this.rapid=t,this.options=e,e.texture instanceof k?this.texture=e.texture:e.texture instanceof Array&&e.texture[0]instanceof Array?this.texture=g.pickWeight(e.texture):e.texture instanceof Array&&(this.texture=g.pick(e.texture)),this.maxLife=g.scalarOrRange(e.life,1),this.datas={speed:this.processAttribute(e.animation.speed,0),rotation:this.processAttribute(e.animation.rotation,0),scale:this.processAttribute(e.animation.scale,1),color:this.processAttribute(e.animation.color,p.White),velocity:this.processAttribute(e.animation.velocity,f.ZERO),acceleration:this.processAttribute(e.animation.acceleration,f.ZERO)},this.position=f.ZERO,this.initializePosition()}processAttribute(t,e){if(!t)return{value:e};if("object"==typeof(i=t)&&null!==i&&Object.getPrototypeOf(i)===Object.prototype){const i=g.scalarOrRange(t.start,e),s=g.scalarOrRange(t.end||i,e);return{delta:t.delta??this.getDelta(i,s,this.maxLife),value:i,damping:t.damping}}return this.processAttribute({start:t},e);var i}updateDamping(t){for(const e of Object.values(this.datas))if(e.damping){const i=e.value,s=Math.pow(e.damping,t);e.value="number"==typeof i?i*s:i.multiply(s)}}updateDelta(t){const e=this.datas;for(const e of Object.values(this.datas))if(e.delta){const i=e.value;"number"==typeof i?e.value+=t*e.delta:e.value=i.add(e.delta.multiply(t))}e.color.value.clamp();const i=f.fromAngle(e.rotation.value).multiply(e.speed.value*t);this.position=this.position.add(i).add(e.velocity.value.multiply(t)).add(e.acceleration.value.multiply(t))}getDelta(t,e,i){return"number"==typeof t&&"number"==typeof e?(e-t)/i:t instanceof f&&e instanceof f||t instanceof p&&e instanceof p?e.subtract(t).divide(i):t}update(t){return this.life+=t,!(this.life>=this.maxLife)&&(this.updateDamping(t),this.updateDelta(t),!0)}render(){this.rapid.renderSprite({...this.options,position:this.position,scale:this.datas.scale.value,rotation:this.datas.rotation.value,color:this.datas.color.value,texture:this.texture})}initializePosition(){switch(this.options.emitShape){case o.POINT:this.position=f.ZERO;break;case o.CIRCLE:const t=Math.random()*Math.PI*2,e=(this.options.emitRadius||0)*Math.sqrt(Math.random());this.position=new f(Math.cos(t)*e,Math.sin(t)*e);break;case o.RECT:this.position=new f((Math.random()-.5)*(this.options.emitRect?.width||0),(Math.random()-.5)*(this.options.emitRect?.height||0))}!this.options.localSpace&&this.options.position&&(this.position=this.position.add(this.options.position))}}class J{constructor(t,e){this.particles=[],this.emitting=!1,this.emitTimer=0,this.emitRate=10,this.emitTime=0,this.emitTimeCounter=0,this.localSpace=Z,this.position=f.ZERO,this.rapid=t,this.options=e,this.emitRate=void 0!==e.emitRate?e.emitRate:10,this.emitTime=void 0!==e.emitTime?e.emitTime:0,this.localSpace=void 0!==e.localSpace?e.localSpace:Z,this.position=e.position||f.ZERO}getTransform(){return this.options}setEmitRate(t){this.emitRate=t}setEmitTime(t){this.emitTime=t}start(){this.emitting=!0,this.emitTimeCounter=0}stop(){this.emitting=!1}clear(){this.particles=[],this.emitTimeCounter=0}emit(t){const e=Math.min(t,(this.options.maxParticles||1/0)-this.particles.length);for(let t=0;t<e;t++){const t={...this.options},e=new V(this.rapid,t);this.particles.unshift(e)}}update(t){if(this.emitting&&this.emitRate>0)if(this.emitTime>0){if(this.emitTimeCounter+=t,this.emitTimeCounter>=this.emitTime){const t=Math.floor(this.emitTimeCounter/this.emitTime);this.emit(this.emitRate*t),this.emitTimeCounter-=t*this.emitTime}}else{this.emitTimer+=t;const e=this.emitRate*t,i=Math.floor(e);i>0&&(this.emit(i),this.emitTimer-=i/this.emitRate);this.emitTimer*this.emitRate>=1&&(this.emit(1),this.emitTimer-=1/this.emitRate)}for(let e=this.particles.length-1;e>=0;e--)this.particles[e].update(t)||this.particles.splice(e,1)}render(){for(const t of this.particles)t.render()}getParticleCount(){return this.particles.length}isActive(){return this.emitting||this.particles.length>0}oneShot(){this.emit(this.emitRate)}}class tt{constructor(e){this.projectionDirty=!0,this.matrixStack=new c,this.tileMap=new j(this),this.light=new y(this),this.defaultColor=new p(255,255,255,255),this.regions=new Map,this.currentMaskType=[],this.currentTransform=[],this.currentFBO=[],this.lastTime=0;const i=(t=>{const e={stencil:!0},i=t.getContext("webgl2",e)||t.getContext("webgl",e);if(!i)throw new Error("Unable to initialize WebGL. Your browser may not support it.");return i})(e.canvas);this.gl=i,this.canvas=e.canvas,this.texture=new N(this,e.antialias??!1),this.maxTextureUnits=i.getParameter(this.gl.MAX_TEXTURE_IMAGE_UNITS),this.width=e.width||this.canvas.width,this.height=e.height||this.canvas.height,this.scaleEnable=e.scaleEnable??!1,this.scaleRadio=e.scaleRadio||t.KEEP,this.devicePixelRatio=e.devicePixelRatio??window.devicePixelRatio??1,this.backgroundColor=e.backgroundColor||new p(255,255,255,255),this.registerBuildInRegion(),this.initWebgl(i),this.updateDisplaySize(this.width,this.height),this.projectionDirty=!1,this.canvas.style.display="block"}updateDisplaySize(e,i){const s=this.width,r=this.height;let n,a,o,h;if(this.scaleEnable){const l=s/r,u=e/i;switch(this.scaleRadio){case t.IGNORE:n=s,a=r,o=e*this.devicePixelRatio,h=i*this.devicePixelRatio;break;case t.KEEP:let c,d;n=s,a=r,u>l?(d=i,c=d*l):(c=e,d=c/l),o=c*this.devicePixelRatio,h=d*this.devicePixelRatio;break;case t.EXPAND:u>l?(a=r,n=r*u):(n=s,a=s/u),o=e*this.devicePixelRatio,h=i*this.devicePixelRatio;break;case t.KEEP_W:n=s,a=s/u,o=e*this.devicePixelRatio,h=i*this.devicePixelRatio;break;case t.KEEP_H:a=r,n=r*u,o=e*this.devicePixelRatio,h=i*this.devicePixelRatio;break;default:n=s,a=r,o=e*this.devicePixelRatio,h=i*this.devicePixelRatio}}else n=s,a=r,o=s*this.devicePixelRatio,h=r*this.devicePixelRatio;this.logicWidth=n,this.logicHeight=a,this.physicsWidth=o,this.physicsHeight=h,this.resizeSize(n,a,o,h,!0)}resizeSize(t,e,i,s,r=!1){this.updateProjection(0,t,e,0),this.gl.viewport(0,0,i,s),this.gl.scissor(0,0,i,s),r&&(this.canvas.width=i,this.canvas.height=s,this.canvas.style.width=i/this.devicePixelRatio+"px",this.canvas.style.height=s/this.devicePixelRatio+"px")}updateProjection(t,e,i,s){this.projection=this.createOrthMatrix(t,e,i,s),this.projectionDirty=!0}initWebgl(t){t.enable(t.BLEND),t.disable(t.DEPTH_TEST),t.blendFunc(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA),t.enable(t.STENCIL_TEST),t.enable(t.SCISSOR_TEST)}clearTextureUnit(){for(let t=0;t<this.maxTextureUnits;t++)this.gl.activeTexture(this.gl.TEXTURE0+t),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}registerBuildInRegion(){this.registerRegion("sprite",D),this.registerRegion("graphic",F)}registerRegion(t,e){this.regions.set(t,new e(this))}quitCurrentRegion(){this.currentRegion&&this.currentRegion.hasPendingContent()&&(this.currentRegion.render(),this.currentRegion.exitRegion())}setRegion(t,e){if(t!=this.currentRegionName||this.currentRegion&&this.currentRegion.isShaderChanged(e)){const i=this.regions.get(t);this.quitCurrentRegion(),this.currentRegion=i,this.currentRegionName=t,i.enterRegion(e)}}save(){this.matrixStack.pushMat()}restore(){this.matrixStack.popMat()}withTransform(t){this.save(),t(),this.restore()}startRender(t=!0){this.clear(),t&&this.matrixStack.clear(),this.matrixStack.pushIdentity(),this.currentRegion=void 0,this.currentRegionName=void 0;const e=performance.now(),i=this.lastTime?(e-this.lastTime)/1e3:0;return this.lastTime=e,i}endRender(){this.currentRegion?.render(),this.projectionDirty=!1}render(t){t(this.startRender()),this.endRender()}renderTileMapLayer(t,e){this.tileMap.renderLayer(t,e instanceof z?{tileSet:e}:e)}renderSprite(t){const e=t.texture;if(!e||!e.base)return;const{offsetX:i,offsetY:s}=this.startDraw(t,e.width,e.height);this.setRegion("sprite",t.shader),this.currentRegion.renderSprite(e.base.texture,e.width,e.height,e.clipX,e.clipY,e.clipW,e.clipH,i,s,(t.color||this.defaultColor).uint32,t.uniforms,t.flipX,t.flipY),this.afterDraw()}renderParticles(t){t.localSpace?(this.startDraw(t.getTransform()),t.render(),this.afterDraw()):t.render()}renderTexture(t){t.base&&this.renderSprite({texture:t})}renderLine(t){const e=t.closed?[...t.points,t.points[0]]:t.points,{vertices:i,uv:s}=w({...t,points:e});this.renderGraphic({...t,drawType:this.gl.TRIANGLES,points:i,uv:s})}renderGraphic(t){this.startGraphicDraw(t),t.points.forEach(((e,i)=>{const s=Array.isArray(t.color)?t.color[i]:t.color,r=t.uv?.[i];this.addGraphicVertex(e.x,e.y,r,s)})),this.endGraphicDraw()}startGraphicDraw(t){const{offsetX:e,offsetY:i}=this.startDraw(t);this.setRegion("graphic",t.shader);const s=this.currentRegion;s.startRender(e,i,t.texture,t.uniforms),t.drawType&&(s.drawType=t.drawType)}addGraphicVertex(t,e,i,s){this.currentRegion.addVertex(t,e,i?.x,i?.y,(s||this.defaultColor).uint32)}endGraphicDraw(){this.currentRegion.render(),this.afterDraw()}startDraw(t,e=0,i=0){return this.currentTransform.push(t),this.matrixStack.applyTransform(t,e,i)}afterDraw(){this.currentTransform.length>0&&this.matrixStack.applyTransformAfter(this.currentTransform.pop())}renderRect(t){const{width:e,height:i}=t,s=[new f(0,0),new f(e,0),new f(e,i),new f(0,i)];this.renderGraphic({...t,points:s,drawType:this.gl.TRIANGLE_FAN})}renderCircle(t){const e=t.segments||32,i=t.radius,s=t.color||this.defaultColor,r=[];for(let t=0;t<=e;t++){const s=t/e*Math.PI*2,n=Math.cos(s)*i,a=Math.sin(s)*i;r.push(new f(n,a))}this.renderGraphic({...t,points:r,color:s,drawType:this.gl.TRIANGLE_FAN})}clear(t){const e=this.gl,i=t||this.backgroundColor;e.clearColor(i.r/255,i.g/255,i.b/255,i.a/255),e.clear(e.COLOR_BUFFER_BIT),this.clearMask()}createOrthMatrix(t,e,i,s){return new Float32Array([2/(e-t),0,0,0,0,2/(s-i),0,0,0,0,-1,0,-(e+t)/(e-t),-(s+i)/(s-i),0,1])}drawMask(t=s.Include,e){this.startDrawMask(t),e(),this.endDrawMask()}startDrawMask(t=s.Include){const e=this.gl;this.currentMaskType.push(t),this.setMaskType(t,!0),e.stencilOp(e.KEEP,e.KEEP,e.REPLACE),e.colorMask(!1,!1,!1,!1)}endDrawMask(){const t=this.gl;this.quitCurrentRegion(),t.stencilOp(t.KEEP,t.KEEP,t.KEEP),t.colorMask(!0,!0,!0,!0),this.setMaskType(this.currentMaskType.pop()??s.Include,!1)}setMaskType(t,e=!1){const i=this.gl;if(this.quitCurrentRegion(),e)this.clearMask(),i.stencilFunc(i.ALWAYS,1,255);else switch(t){case s.Include:i.stencilFunc(i.EQUAL,1,255);break;case s.Exclude:i.stencilFunc(i.NOTEQUAL,1,255)}}clearMask(){const t=this.gl;this.quitCurrentRegion(),t.clearStencil(0),t.clear(t.STENCIL_BUFFER_BIT),t.stencilFunc(t.ALWAYS,1,255)}createCostumShader(t,e,i,s=0){return C.createCostumShader(this,t,e,i,s)}startFBO(t){this.quitCurrentRegion(),t.bind(),this.clearTextureUnit(),this.resizeSize(t.width,t.height,t.width,t.height),this.updateProjection(0,t.width,0,t.height),this.save(),this.matrixStack.identity(),this.currentFBO.push(t)}endFBO(){if(this.currentFBO.length>0){const t=this.currentFBO.pop();this.quitCurrentRegion(),t.unbind(),this.clearTextureUnit(),this.resizeSize(this.logicWidth,this.logicHeight,this.physicsWidth,this.physicsHeight),this.restore()}}drawToFBO(t,e){this.startFBO(t),e(),this.endFBO()}setBlendMode(t){switch(t){case a.Additive:this.gl.blendFunc(this.gl.SRC_ALPHA,this.gl.ONE);break;case a.Subtractive:this.gl.blendFunc(this.gl.ZERO,this.gl.ONE_MINUS_SRC_COLOR);break;case a.Mix:this.gl.blendFunc(this.gl.SRC_ALPHA,this.gl.ONE_MINUS_SRC_ALPHA)}}drawLightShadowMask(t){this.startDrawMask(t.type||s.Exclude);this.light.createLightShadowMaskPolygon(t.occlusion,t.lightSource,t.baseProjectionLength).forEach((t=>{this.renderGraphic({points:t,color:p.Black})})),this.endDrawMask()}createParticleEmitter(t){return new J(this,t)}cssToGameCoords(t,e){const i=t instanceof f?t:new f(t,e),s=this.canvas.getBoundingClientRect(),r=i.x/s.width,n=i.y/s.height,a=r*this.logicWidth,o=n*this.logicHeight;return new f(a,o)}gameToCssCoords(t,e){const i=t instanceof f?t:new f(t,e??0),s=this.canvas.getBoundingClientRect(),r=i.x/this.logicWidth,n=i.y/this.logicHeight,a=r*s.width,o=n*s.height;return new f(a,o)}}class et{constructor(t){this.isDirty=!1,this.data=t}setUniform(t,e){this.data[t]!=e&&(this.isDirty=!0),this.data[t]=e}clearDirty(){this.isDirty=!1}getUnifromNames(){return Object.keys(this.data)}bind(t,e,i,s){if(!i)return;const r=this.data[e];if("number"==typeof r)t.uniform1f(i,r);else if(Array.isArray(r))switch(r.length){case 1:Number.isInteger(r[0])?t.uniform1i(i,r[0]):t.uniform1f(i,r[0]);break;case 2:Number.isInteger(r[0])?t.uniform2iv(i,r):t.uniform2fv(i,r);break;case 3:Number.isInteger(r[0])?t.uniform3iv(i,r):t.uniform3fv(i,r);break;case 4:Number.isInteger(r[0])?t.uniform4iv(i,r):t.uniform4fv(i,r);break;case 9:t.uniformMatrix3fv(i,!1,r);break;case 16:t.uniformMatrix4fv(i,!1,r);break;default:console.error(`Unsupported uniform array length for ${e}:`,r.length)}else if("boolean"==typeof r)t.uniform1i(i,r?1:0);else if(r.base?.texture){const e=s.useTexture(r.base.texture)[0];t.uniform1i(i,e)}else console.error(`Unsupported uniform type for ${e}:`,typeof r)}}class it extends K{constructor(t,e){super(),this.element=t,this.audioContext=e,this.source=null,this.gainNode=this.audioContext.createGain(),this.element.addEventListener("ended",this.handleEnded.bind(this))}handleEnded(){this.emit("ended")}async play(t=!1){try{this.element.loop=t,this.source=this.audioContext.createMediaElementSource(this.element),this.source.connect(this.gainNode),this.gainNode.connect(this.audioContext.destination),await this.element.play()}catch(t){console.error("Error playing audio:",t)}}pause(){this.element.pause()}stop(){this.element.pause(),this.element.currentTime=0,this.source&&(this.source.disconnect(),this.source=null)}setVolume(t){this.gainNode.gain.value=Math.max(0,Math.min(1,t))}destroy(){this.stop(),this.gainNode.disconnect(),this.element.removeEventListener("ended",this.handleEnded.bind(this)),this.removeAllListeners()}}class st{constructor(){this.audioContext=new(window.AudioContext||window.webkitAudioContext)}destroy(){this.audioContext.close()}}class rt extends K{constructor(t){super(),this.totalAsset=0,this.loadedAssets=0,this.game=t,this.assets={json:{},audio:{},images:{}}}loadJson(t,e){this.totalAsset++,fetch(e).then((t=>t.json())).then((e=>{this.assets.json[t]=e,this.assetLoaded()})).catch((i=>this.handleError(t,e,i)))}loadAudio(t,e){this.totalAsset++;const i=new Audio;i.src=e,i.oncanplaythrough=()=>{this.assets.audio[t]=new it(i,this.game.audio.audioContext),this.assetLoaded(),i.oncanplaythrough=null},i.onerror=()=>this.handleError(t,e,"Audio load error")}loadImage(t,e){this.totalAsset++;const i=new Image;i.src=e,i.onload=()=>{this.assets.images[t]=this.game.render.texture.textureFromSource(i),this.assetLoaded()},i.onerror=()=>this.handleError(t,e,"Image load error")}loadAssets(t){t.forEach((t=>{switch(t.type){case"json":this.loadJson(t.name,t.url);break;case"audio":this.loadAudio(t.name,t.url);break;case"image":this.loadImage(t.name,t.url);break;default:console.warn(`Unknown asset type: ${t.type}`)}}))}assetLoaded(){this.loadedAssets++;const t=this.loadedAssets/this.totalAsset;this.emit("progress",t,this.loadedAssets,this.totalAsset),this.loadedAssets===this.totalAsset&&this.emit("complete",this.assets)}handleError(t,e,i){this.emit("error",{name:t,url:e,error:i}),console.error(`Failed to load asset ${t} from ${e}:`,i)}get(t,e){return this.assets[t]?.[e]}getJSON(t){return this.assets.json[t]}getAudio(t){return this.assets.audio[t]}getTexture(t){return this.assets.images[t]}}class nt{constructor(t){this.mousePosition=f.ZERO,this.keysDown=new Set,this.keysDownLastFrame=new Set,this.buttonsDown=new Set,this.buttonsDownLastFrame=new Set,this.rapid=t,this.canvas=t.canvas,this.attachEventListeners()}attachEventListeners(){const t=this.canvas.getBoundingClientRect();this.canvas.addEventListener("mousemove",this.handleMouseMove=e=>{this.mousePosition=this.rapid.cssToGameCoords(e.clientX-t.left,e.clientY-t.top)}),window.addEventListener("keydown",this.handleKeyDown=t=>{this.keysDown.add(t.code)}),window.addEventListener("keyup",this.handleKeyUp=t=>{this.keysDown.delete(t.code)}),this.canvas.addEventListener("mousedown",this.handleMouseDown=t=>{this.buttonsDown.add(t.button)}),this.canvas.addEventListener("mouseup",this.handleMouseUp=t=>{this.buttonsDown.delete(t.button)})}updateNextFrame(){this.keysDownLastFrame=new Set(this.keysDown),this.buttonsDownLastFrame=new Set(this.buttonsDown)}isKeyDown(t){return this.keysDown.has(t)}isKeyUp(t){return!this.keysDown.has(t)}wasKeyPressed(t){return this.keysDown.has(t)&&!this.keysDownLastFrame.has(t)}wasKeyReleased(t){return!this.keysDown.has(t)&&this.keysDownLastFrame.has(t)}isButtonDown(t){return this.buttonsDown.has(t)}isButtonUp(t){return!this.buttonsDown.has(t)}wasButtonPressed(t){return this.buttonsDown.has(t)&&!this.buttonsDownLastFrame.has(t)}wasButtonReleased(t){return!this.buttonsDown.has(t)&&this.buttonsDownLastFrame.has(t)}getMouseLocal(t){return t.transform.globalToLocal(this.mousePosition)}destroy(){this.canvas.removeEventListener("mousemove",this.handleMouseMove),window.removeEventListener("keydown",this.handleKeyDown),window.removeEventListener("keyup",this.handleKeyUp),this.canvas.removeEventListener("mousedown",this.handleMouseDown),this.canvas.removeEventListener("mouseup",this.handleMouseUp),this.keysDown.clear(),this.keysDownLastFrame.clear(),this.buttonsDown.clear(),this.buttonsDownLastFrame.clear()}}class at{get x(){return this.position.x}get y(){return this.position.x}set x(t){this.x=t}set y(t){this.y=t}constructor(t,e={}){this.parent=null,this.globalZindex=0,this.localZindex=0,this.transform=new c,this.children=[],this.transform.pushIdentity(),this.game=t,this.rapid=t.render,this.tags=e.tags??[],e.position?this.position=e.position:this.position=new f(e.x??0,e.y??0),"number"==typeof e.scale?this.scale=new f(e.scale,e.scale):e.scale?this.scale=e.scale:this.scale=new f(1,1),this.rotation=e.rotation??0}getParentTransform(){return this.parent?this.parent.transform:this.rapid.matrixStack}update(t){this.onUpdate(t);for(const e of this.children)e.update(t)}onUpdate(t){}collectRenderables(t){this.onRender!==at.prototype.onRender&&t.push(this);for(const e of this.children)e.collectRenderables(t)}beforOnRender(){const t=this.transform;this.rapid.matrixStack.setTransform(t.getTransform())}onRender(t){}updateTransform(t=!1){t&&this.parent&&this.parent.updateTransform(t);const e=this.transform,i=this.getParentTransform();e.setTransform(i.getTransform()),e.translate(this.position),e.rotate(this.rotation),e.scale(this.scale)}addChild(t){t.parent&&t.parent.removeChild(t),t.parent=this,this.children.push(t)}removeChild(t){const e=this.children.indexOf(t);e>-1&&(t.parent=null,this.children.splice(e,1))}findDescendant(t,e=!0){const i=[];for(const s of this.children){if(t(s)){if(e)return s;i.push(s)}const r=s.findDescendant(t,e);if(e){if(r)return r}else i.push(...r)}return e?null:i}findDescendantByTag(t,e=!1){return this.findDescendant((e=>0!==t.length&&t.every((t=>e.tags.includes(t)))),e)}dispose(){this.postDispose(),this.parent&&this.parent.removeChild(this)}postDispose(){this.children.forEach((t=>{t.dispose()}))}}class ot extends at{updateTransform(){const t=this.transform;t.identity();const e=new f(-this.rapid.logicWidth,-this.rapid.logicHeight).divide(2);t.translate(e),t.translate(this.position),t.rotate(this.rotation),t.scale(this.scale),t.setTransform(t.getInverse())}}class ht extends at{constructor(t,e){super(t,e),this.error=new f(ht.DEFAULT_ERROR),this.data=[[]],this.ySortCallback=[],e.error?"number"==typeof e.error?this.error=new f(e.error):this.error=e.error:this.error=new f(e.errorX??ht.DEFAULT_ERROR,e.errorY??ht.DEFAULT_ERROR),this.tileSet=e.tileSet,this.shape=e.shape??r.SQUARE,this.eachTile=e.eachTile}collectRenderables(t){this.onRender!==at.prototype.onRender&&t.push(this)}setTile(t,e,i){return e<0||e>=this.data.length||t<0||t>=this.data[e].length?(console.warn(`Tilemap.setTile: Coordinates (${t}, ${e}) are out of bounds.`),!1):(this.data[e][t]=i,!0)}getTile(t,e){if(!(e<0||e>=this.data.length||t<0||t>=this.data[e].length))return this.data[e][t]}removeTile(t,e){return this.setTile(t,e,ht.EMPTY_TILE)}fill(t,e,i,s,r){const n=e+s,a=i+r;for(let s=i;s<a;s++)for(let i=e;i<n;i++)this.setTile(i,s,t)}setData(t){this.data=t}localToMap(t){this.rapid.tileMap.localToMap(t,{tileSet:this.tileSet})}mapToLocal(t){this.rapid.tileMap.mapToLocal(t,{tileSet:this.tileSet})}onRender(t){const e=[...this.ySortCallback];this.children.forEach((t=>{e.push({ySort:t.localZindex,entity:t})})),t.renderTileMapLayer(this.data,{error:this.error,tileSet:this.tileSet,eachTile:this.eachTile,ySortCallback:e})}}ht.DEFAULT_ERROR=0,ht.EMPTY_TILE=-1;class lt extends at{create(){}}class ut{constructor(t){this.mainScene=null,this.isRunning=!1,this.lastTime=0,this.tweens=[],this.timers=[],this.renderQueue=[],this.render=new tt(t),this.input=new nt(this.render),this.asset=new rt(this),this.audio=new st,this.texture=this.render.texture}switchScene(t){this.mainScene&&this.mainScene.dispose(),this.mainScene=t,t.create()}start(){this.isRunning||(this.isRunning=!0,this.lastTime=performance.now(),this.gameLoop())}stop(){this.isRunning=!1}addEntityRenderQueue(t){this.renderQueue.push(t)}gameLoop(){if(!this.isRunning)return;const t=performance.now(),e=(t-this.lastTime)/1e3;this.lastTime=t,this.render.startRender(),this.mainScene&&(this.mainScene.update(e),this.mainScene.collectRenderables(this.renderQueue),this.renderQueue.sort(((t,e)=>{const i=t.parent&&t.parent===e.parent,s=t.globalZindex-e.globalZindex;return 0===s||i?i?t.localZindex-e.localZindex:0:s})),this.renderQueue.forEach((t=>{t.beforOnRender(),t.onRender(this.render)})),this.renderQueue.length=0),this.render.endRender(),this.input.updateNextFrame(),this.updateTweens(e),this.updateTimers(e),requestAnimationFrame(this.gameLoop.bind(this))}destroy(){this.audio.destroy(),this.input.destroy()}createTimer(t,e=!1){const i=new Q(t,e);return this.timers.push(i),i.start(),i}updateTimers(t){for(const e of this.timers)e.update(t);this.timers=this.timers.filter((t=>!t.isFinished))}createTween(t,e,i,s,r=q.Linear){const n=new $(t,e,i,s,r);return this.tweens.push(n),n.start(),n}updateTweens(t){for(const e of this.tweens)e.update(t);this.tweens=this.tweens.filter((t=>!t.isFinished))}}export{h as ArrayType,I as BaseTexture,a as BlendMode,ot as Camera,p as Color,l as DynamicArrayBuffer,at as Entity,G as FrameBufferObject,C as GLShader,ut as Game,nt as InputManager,e as LineTextureMode,s as MaskType,m as MathUtils,c as MatrixStack,J as ParticleEmitter,o as ParticleShape,g as Random,tt as Rapid,O as SCALEFACTOR,t as ScaleRadio,lt as Scene,n as ShaderType,B as Text,k as Texture,N as TextureCache,i as TextureWrapMode,j as TileMapRender,z as TileSet,ht as Tilemap,r as TilemapShape,et as Uniform,f as Vec2,u as WebglBufferArray,d as WebglElementBufferArray,U as graphicAttributes,M as spriteAttributes};
|
package/dist/rapid.umd.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";const t=(t,e,r)=>{const s=t.createShader(r);if(!s)throw new Error("Unable to create webgl shader");t.shaderSource(s,e),t.compileShader(s);if(!t.getShaderParameter(s,t.COMPILE_STATUS)){const r=t.getShaderInfoLog(s);throw console.error("Shader compilation failed:",r),new Error("Unable to compile shader: "+r+e)}return s};const e=5126;class r{constructor(t){this.usedElemNum=0,this.maxElemNum=512,this.bytePerElem=t.BYTES_PER_ELEMENT,this.arrayType=t,this.arraybuffer=new ArrayBuffer(this.maxElemNum*this.bytePerElem),this.typedArray=new t(this.arraybuffer),t==Float32Array&&(this.uint32=new Uint32Array(this.arraybuffer))}clear(){this.usedElemNum=0}resize(t=0){if((t+=this.usedElemNum)>this.maxElemNum){for(;t>this.maxElemNum;)this.maxElemNum<<=1;this.setMaxSize(this.maxElemNum)}}setMaxSize(t=this.maxElemNum){const e=this.typedArray;this.maxElemNum=t,this.arraybuffer=new ArrayBuffer(t*this.bytePerElem),this.typedArray=new this.arrayType(this.arraybuffer),this.uint32&&(this.uint32=new Uint32Array(this.arraybuffer)),this.typedArray.set(e)}push(t){this.typedArray[this.usedElemNum++]=t}pushUint(t){this.uint32[this.usedElemNum++]=t}pop(t){this.usedElemNum-=t}getArray(t=0,e){return null==e?this.typedArray:this.typedArray.subarray(t,e)}get length(){return this.typedArray.length}}class s extends r{constructor(t,e,r=t.ARRAY_BUFFER){super(e),this.dirty=!0,this.webglBufferSize=0,this.gl=t,this.buffer=t.createBuffer(),this.type=r}push(t){super.push(t),this.dirty=!0}bindBuffer(){this.gl.bindBuffer(this.type,this.buffer)}bufferData(){if(this.dirty){const t=this.gl;this.maxElemNum>this.webglBufferSize?(t.bufferData(this.type,this.getArray(),t.STATIC_DRAW),this.webglBufferSize=this.maxElemNum):t.bufferSubData(this.type,0,this.getArray(0,this.usedElemNum)),this.dirty=!1}}}class i extends r{constructor(){super(Float32Array)}pushMat(){const t=this.usedElemNum-6,e=this.typedArray;this.resize(6),this.push(e[t+0]),this.push(e[t+1]),this.push(e[t+2]),this.push(e[t+3]),this.push(e[t+4]),this.push(e[t+5])}popMat(){this.pop(6)}pushIdentity(){this.resize(6),this.push(1),this.push(0),this.push(0),this.push(1),this.push(0),this.push(0)}translate(t,e){if(t instanceof a)return this.translate(t.x,t.y);const r=this.usedElemNum-6,s=this.typedArray;s[r+4]=s[r+0]*t+s[r+2]*e+s[r+4],s[r+5]=s[r+1]*t+s[r+3]*e+s[r+5]}rotate(t){const e=this.usedElemNum-6,r=this.typedArray,s=Math.cos(t),i=Math.sin(t),n=r[e+0],h=r[e+1],a=r[e+2],o=r[e+3];r[e+0]=n*s-h*i,r[e+1]=n*i+h*s,r[e+2]=a*s-o*i,r[e+3]=a*i+o*s}scale(t,e){if(t instanceof a)return this.scale(t.x,t.y);e||(e=t);const r=this.usedElemNum-6,s=this.typedArray;s[r+0]=s[r+0]*t,s[r+1]=s[r+1]*t,s[r+2]=s[r+2]*e,s[r+3]=s[r+3]*e}apply(t,e){if(t instanceof a)return new a(...this.apply(t.x,t.y));const r=this.usedElemNum-6,s=this.typedArray;return[s[r+0]*t+s[r+2]*e+s[r+4],s[r+1]*t+s[r+3]*e+s[r+5]]}getInverse(){const t=this.usedElemNum-6,e=this.typedArray,r=e[t+0],s=e[t+1],i=e[t+2],n=e[t+3],h=e[t+4],a=e[t+5],o=r*n-s*i;return new Float32Array([n/o,-s/o,-i/o,r/o,(i*a-n*h)/o,(s*h-r*a)/o])}getTransform(){const t=this.usedElemNum-6,e=this.typedArray;return new Float32Array([e[t+0],e[t+1],e[t+2],e[t+3],e[t+4],e[t+5]])}setTransform(t){const e=this.usedElemNum-6,r=this.typedArray;r[e+0]=t[0],r[e+1]=t[1],r[e+2]=t[2],r[e+3]=t[3],r[e+4]=t[4],r[e+5]=t[5]}}class n extends s{constructor(t,e,r,s){super(t,Uint16Array,t.ELEMENT_ARRAY_BUFFER),this.setMaxSize(e*s);for(let t=0;t<s;t++)this.addObject(t*r);this.bindBuffer(),this.bufferData()}addObject(t){}}class h{constructor(t,e,r,s){this._r=t,this._g=e,this._b=r,this._a=s,this.updateUint()}get r(){return this._r}set r(t){this._r=t,this.updateUint()}get g(){return this._g}set g(t){this._g=t,this.updateUint()}get b(){return this._b}set b(t){this._b=t,this.updateUint()}get a(){return this._a}set a(t){this._a=t,this.updateUint()}updateUint(){this.uint32=(this._a<<24|this._b<<16|this._g<<8|this._r)>>>0}setRGBA(t,e,r,s){this.r=t,this.g=e,this.b=r,this.a=s,this.updateUint()}copy(t){this.setRGBA(t.r,t.g,t.b,t.a)}equals(t){return t.r===this.r&&t.g===this.g&&t.b===this.b&&t.a===this.a}static fromHex(t){t.startsWith("#")&&(t=t.slice(1));const e=parseInt(t.slice(0,2),16),r=parseInt(t.slice(2,4),16),s=parseInt(t.slice(4,6),16);let i=255;return t.length>=8&&(i=parseInt(t.slice(6,8),16)),new h(e,r,s,i)}add(t){return new h(Math.min(this.r+t.r,255),Math.min(this.g+t.g,255),Math.min(this.b+t.b,255),Math.min(this.a+t.a,255))}subtract(t){return new h(Math.max(this.r-t.r,0),Math.max(this.g-t.g,0),Math.max(this.b-t.b,0),Math.max(this.a-t.a,0))}}class a{constructor(t,e){this.x=void 0!==t?t:0,this.y=void 0!==e?e:0}scalarMult(t){return this.x*=t,this.y*=t,this}perpendicular(){const t=this.x;return this.x=-this.y,this.y=t,this}invert(){return this.x=-this.x,this.y=-this.y,this}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}normalize(){const t=this.length();return this.x/=t,this.y/=t,this}angle(){return this.y/this.x}static Angle(t,e){return Math.atan2(e.y-t.y,e.x-t.x)}static Add(t,e){return new a(t.x+e.x,t.y+e.y)}static Sub(t,e){return new a(t.x-e.x,t.y-e.y)}static Middle(t,e){return a.Add(t,e).scalarMult(.5)}static FormArray(t){return t.map((t=>new a(t[0],t[1])))}}class o{constructor(t){this.cache=new Map,this.render=t}async textureFromUrl(t,e=!1){let r=this.cache.get(t);if(!r){const s=await this.loadImage(t);r=u.fromImageSource(this.render,s,e),this.cache.set(t,r)}return new l(r)}async loadImage(t){return new Promise((e=>{const r=new Image;r.onload=()=>{e(r)},r.src=t}))}createText(t){return new d(this.render,t)}}class u{constructor(t,e,r){this.texture=t,this.width=e,this.height=r}static fromImageSource(t,e,r=!1){return new u(function(t,e,r){const s=t.createTexture();if(t.bindTexture(t.TEXTURE_2D,s),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,r?t.LINEAR:t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,r?t.LINEAR:t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),!s)throw new Error("unable to create texture");return s}(t.gl,e,r),e.width,e.height)}}class l{constructor(t){this.scale=1,this.setBaseTextur(t)}setBaseTextur(t){t&&(this.base=t,this.setClipRegion(0,0,t.width,t.height))}setClipRegion(t,e,r,s){this.base&&(this.clipX=t/this.base.width,this.clipY=e/this.base.width,this.clipW=this.clipX+r/this.base.width,this.clipH=this.clipY+s/this.base.height,this.width=r*this.scale,this.height=s*this.scale)}static fromImageSource(t,e,r=!1){return new l(u.fromImageSource(t,e,r))}static fromUrl(t,e){return t.textures.textureFromUrl(e)}}class d extends l{constructor(t,e){super(),this.scale=.5,this.rapid=t,this.options=e,this.text=e.text||"",this.updateTextImage()}updateTextImage(){const t=this.createTextCanvas();this.setBaseTextur(u.fromImageSource(this.rapid,t,!0))}createTextCanvas(){const t=document.createElement("canvas"),e=t.getContext("2d");if(!e)throw new Error("Failed to get canvas context");e.font=`${this.options.fontSize||16}px ${this.options.fontFamily||"Arial"}`,e.fillStyle=this.options.color||"#000",e.textAlign=this.options.textAlign||"left",e.textBaseline=this.options.textBaseline||"top";const r=this.text.split("\n");let s=0,i=0;for(const t of r){const r=e.measureText(t);s=Math.max(s,r.width),i+=this.options.fontSize||16}t.width=2*s,t.height=2*i,e.scale(2,2),e.font=`${this.options.fontSize||16}px ${this.options.fontFamily||"Arial"}`,e.fillStyle=this.options.color||"#000",e.textAlign=this.options.textAlign||"left",e.textBaseline=this.options.textBaseline||"top";let n=0;for(const t of r)e.fillText(t,0,n),n+=this.options.fontSize||16;return t}setText(t){this.text=t,this.updateTextImage()}}class c{constructor(e,r,s){this.attributeLoc={},this.uniformLoc={};const i=function(t,e){if(t.includes("%TEXTURE_NUM%")&&(t=t.replace("%TEXTURE_NUM%",e.toString())),t.includes("%GET_COLOR%")){let r="";for(let t=0;t<e;t++)r+=0==t?`if(vTextureId == ${t}.0)`:t==e-1?"else":`else if(vTextureId == ${t}.0)`,r+=`{color = texture2D(uTextures[${t}], vRegion);}`;t=t.replace("%GET_COLOR%",r)}return t}(s,e.maxTextureUnits);this.program=((e,r,s)=>{var i=e.createProgram(),n=t(e,r,35633),h=t(e,s,35632);if(!i)throw new Error("Unable to create program shader");return e.attachShader(i,n),e.attachShader(i,h),e.linkProgram(i),i})(e.gl,r,i),this.gl=e.gl,this.parseShader(r),this.parseShader(i)}setUniforms(t,e){var r;const s=this.gl;for(const i in t){const n=t[i],h=this.getUniform(i);if(n instanceof l&&(null===(r=n.base)||void 0===r?void 0:r.texture))s.activeTexture(s.TEXTURE0+e),s.bindTexture(s.TEXTURE_2D,n.base.texture),s.uniform1i(h,e),e+=1;else if("number"==typeof n)s.uniform1f(h,n);else if(Array.isArray(n))switch(n.length){case 1:Number.isInteger(n[0])?s.uniform1i(h,n[0]):s.uniform1f(h,n[0]);break;case 2:Number.isInteger(n[0])?s.uniform2iv(h,n):s.uniform2fv(h,n);break;case 3:Number.isInteger(n[0])?s.uniform3iv(h,n):s.uniform3fv(h,n);break;case 4:Number.isInteger(n[0])?s.uniform4iv(h,n):s.uniform4fv(h,n);break;case 9:s.uniformMatrix3fv(h,!1,n);break;case 16:s.uniformMatrix4fv(h,!1,n);break;default:console.error(`Unsupported uniform array length for ${i}:`,n.length)}else"boolean"==typeof n?s.uniform1i(h,n?1:0):console.error(`Unsupported uniform type for ${i}:`,typeof n)}}getUniform(t){return this.uniformLoc[t]}use(){this.gl.useProgram(this.program)}parseShader(t){const e=this.gl,r=t.match(/attribute\s+\w+\s+(\w+)/g);if(r)for(const t of r){const r=t.split(" ")[2],s=e.getAttribLocation(this.program,r);-1!=s&&(this.attributeLoc[r]=s)}const s=t.match(/uniform\s+\w+\s+(\w+)/g);if(s)for(const t of s){const r=t.split(" ")[2];this.uniformLoc[r]=e.getUniformLocation(this.program,r)}}setAttribute(t){const e=this.attributeLoc[t.name];if(void 0!==e){const r=this.gl;r.vertexAttribPointer(e,t.size,t.type,t.normalized||!1,t.stride,t.offset||0),r.enableVertexAttribArray(e)}}}class p{constructor(t,e){this.usedTextures=[],this.needBind=new Set,this.attribute=e,this.rapid=t,this.gl=t.gl,this.webglArrayBuffer=new s(t.gl,Float32Array,t.gl.ARRAY_BUFFER),this.TEXTURE_UNITS_ARRAY=Array.from({length:t.maxTextureUnits},((t,e)=>e))}addVertex(t,e,...r){const[s,i]=this.rapid.transformPoint(t,e);this.webglArrayBuffer.push(s),this.webglArrayBuffer.push(i)}useTexture(t){let e=this.usedTextures.indexOf(t);return-1===e&&(this.usedTextures.length>=this.rapid.maxTextureUnits&&this.render(),this.usedTextures.push(t),e=this.usedTextures.length-1,this.needBind.add(e)),e}enterRegion(t){this.currentShader=null!=t?t:this.defaultShader,this.currentShader.use(),this.initializeForNextRender(),this.webglArrayBuffer.bindBuffer();for(const t of this.attribute)this.currentShader.setAttribute(t);this.gl.uniformMatrix4fv(this.currentShader.uniformLoc.uProjectionMatrix,!1,this.rapid.projection)}exitRegion(){}initDefaultShader(t,e){this.webglArrayBuffer.bindBuffer(),this.defaultShader=new c(this.rapid,t,e)}render(){this.executeRender(),this.initializeForNextRender()}executeRender(){this.webglArrayBuffer.bufferData();const t=this.gl;for(const e of this.needBind)t.activeTexture(t.TEXTURE0+e),t.bindTexture(t.TEXTURE_2D,this.usedTextures[e]);this.needBind.clear()}initializeForNextRender(){this.webglArrayBuffer.clear(),this.usedTextures=[]}}class f extends p{constructor(t){super(t,x),this.vertex=0,this.drawType=t.gl.TRIANGLE_FAN,this.initDefaultShader("precision mediump float;\r\n\r\nattribute vec2 aPosition;\r\nattribute vec4 aColor;\r\nvarying vec4 vColor;\r\nuniform mat4 uProjectionMatrix;\r\nuniform vec4 uColor;\r\n\r\nvoid main(void) {\r\n gl_Position = uProjectionMatrix * vec4(aPosition, 0.0, 1.0);\r\n vColor = aColor;\r\n}\r\n","precision mediump float;\r\n\r\nvarying vec4 vColor;\r\nvoid main(void) {\r\n gl_FragColor = vColor;//vColor;\r\n}\r\n")}startRender(){this.vertex=0,this.webglArrayBuffer.clear()}addVertex(t,e,r){this.webglArrayBuffer.resize(3),super.addVertex(t,e),this.webglArrayBuffer.pushUint(r),this.vertex+=1}drawCircle(t,e,r,s){const i=2*Math.PI/30;this.startRender(),this.addVertex(t,e,s);for(let n=0;n<=30;n++){const h=n*i,a=t+r*Math.cos(h),o=e+r*Math.sin(h);this.addVertex(a,o,s)}this.executeRender()}executeRender(){super.executeRender();this.gl.drawArrays(this.drawType,0,this.vertex),this.drawType=this.rapid.gl.TRIANGLE_FAN,this.vertex=0}}const x=[{name:"aPosition",size:2,type:e,stride:12},{name:"aColor",size:4,type:5121,stride:12,offset:2*Float32Array.BYTES_PER_ELEMENT,normalized:!0}];class g extends n{constructor(t,e){super(t,6,4,e)}addObject(t){super.addObject(),this.push(t),this.push(t+3),this.push(t+2),this.push(t),this.push(t+1),this.push(t+2)}}class m extends p{constructor(t){const e=t.gl;super(t,y),this.batchSprite=0,this.initDefaultShader("precision mediump float;\r\n\r\nattribute vec2 aPosition;\r\nattribute vec2 aRegion;\r\nattribute float aTextureId;\r\nattribute vec4 aColor;\r\n\r\nuniform mat4 uProjectionMatrix;\r\n\r\nvarying vec2 vRegion;\r\nvarying float vTextureId;\r\nvarying vec4 vColor;\r\n\r\nvoid main(void) {\r\n vRegion = aRegion;\r\n vTextureId = aTextureId;\r\n vColor = aColor;\r\n gl_Position = uProjectionMatrix * vec4(aPosition, 0.0, 1.0);\r\n}","precision mediump float;\r\nuniform sampler2D uTextures[%TEXTURE_NUM%];\r\n\r\nvarying vec2 vRegion;\r\nvarying float vTextureId;\r\nvarying vec4 vColor;\r\n\r\nvoid main(void) {\r\n vec4 color;\r\n %GET_COLOR%\r\n\r\n gl_FragColor = color*vColor;\r\n}"),this.MAX_BATCH=Math.floor(16384),this.indexBuffer=new g(e,this.MAX_BATCH)}addVertex(t,e,r,s,i,n){super.addVertex(t,e),this.webglArrayBuffer.push(r),this.webglArrayBuffer.push(s),this.webglArrayBuffer.push(i),this.webglArrayBuffer.pushUint(n)}renderSprite(t,e,r,s,i,n,h,a,o,u,l){var d;l&&(null===(d=this.currentShader)||void 0===d||d.setUniforms(l,1)),this.batchSprite>=this.MAX_BATCH&&this.render(),this.batchSprite++,this.webglArrayBuffer.resize(24);const c=this.useTexture(t),p=a+e,f=o+r,x=s+n,g=i+h;this.addVertex(a,o,s,i,c,u),this.addVertex(p,o,x,i,c,u),this.addVertex(p,f,x,g,c,u),this.addVertex(a,f,s,g,c,u)}executeRender(){super.executeRender();const t=this.gl;t.drawElements(t.TRIANGLES,6*this.batchSprite,t.UNSIGNED_SHORT,0)}enterRegion(t){super.enterRegion(t),this.indexBuffer.bindBuffer(),this.gl.uniform1iv(this.currentShader.uniformLoc.uTextures,this.TEXTURE_UNITS_ARRAY)}initializeForNextRender(){super.initializeForNextRender(),this.batchSprite=0}}const y=[{name:"aPosition",size:2,type:e,stride:24},{name:"aRegion",size:2,type:e,stride:24,offset:2*Float32Array.BYTES_PER_ELEMENT},{name:"aTextureId",size:1,type:e,stride:24,offset:4*Float32Array.BYTES_PER_ELEMENT},{name:"aColor",size:4,type:5121,stride:24,offset:5*Float32Array.BYTES_PER_ELEMENT,normalized:!0}];var T,E;exports.JoinTyps=void 0,(T=exports.JoinTyps||(exports.JoinTyps={}))[T.BEVEL=0]="BEVEL",T[T.ROUND=1]="ROUND",T[T.MITER=2]="MITER",exports.CapTyps=void 0,(E=exports.CapTyps||(exports.CapTyps={}))[E.BUTT=0]="BUTT",E[E.ROUND=1]="ROUND",E[E.SQUARE=2]="SQUARE";const b=1e-4,A=(t,e,r,s)=>{s.push(t),s.push(a.Add(t,r)),s.push(a.Add(e,r)),s.push(e),s.push(a.Add(e,r)),s.push(t)},R=(t,e,r,s,i)=>{const n=a.Sub(t,e).length();let h=Math.atan2(r.y-t.y,r.x-t.x),o=Math.atan2(e.y-t.y,e.x-t.x);const u=h;o>h?o-h>=Math.PI-b&&(o-=2*Math.PI):h-o>=Math.PI-b&&(h-=2*Math.PI);let l=o-h;if(Math.abs(l)>=Math.PI-b&&Math.abs(l)<=Math.PI+b){const e=a.Sub(t,s);0===e.x?e.y>0&&(l=-l):e.x>=-1e-4&&(l=-l)}const d=(Math.abs(l*n)/7|0)+1,c=l/d;for(let e=0;e<d;e++)i.push(new a(t.x,t.y)),i.push(new a(t.x+n*Math.cos(u+c*e),t.y+n*Math.sin(u+c*e))),i.push(new a(t.x+n*Math.cos(u+c*(1+e)),t.y+n*Math.sin(u+c*(1+e))))},S=(t,e,r,s,i,n,h)=>{const o=a.Sub(e,t).perpendicular(),u=a.Sub(r,e).perpendicular();((t,e,r)=>(e.x-t.x)*(r.y-t.y)-(r.x-t.x)*(e.y-t.y))(t,e,r)>0&&(o.invert(),u.invert()),o.normalize().scalarMult(i),u.normalize().scalarMult(i);const l=((t,e,r,s)=>{const i=e.y-t.y,n=t.x-e.x,h=s.y-r.y,o=r.x-s.x,u=i*o-h*n;if(u>-1e-4&&u<b)return null;{const e=i*t.x+n*t.y,s=h*r.x+o*r.y;return new a((o*e-n*s)/u,(i*s-h*e)/u)}})(a.Add(o,t),a.Add(o,e),a.Add(u,r),a.Add(u,e));let d=null,c=Number.MAX_VALUE;l&&(d=a.Sub(l,e),c=d.length());const p=c/i|0,f=a.Sub(t,e).length(),x=a.Sub(e,r).length();if(c>f||c>x)s.push(a.Add(t,o)),s.push(a.Sub(t,o)),s.push(a.Add(e,o)),s.push(a.Sub(t,o)),s.push(a.Add(e,o)),s.push(a.Sub(e,o)),n===exports.JoinTyps.ROUND?R(e,a.Add(e,o),a.Add(e,u),r,s):n===exports.JoinTyps.BEVEL||n===exports.JoinTyps.MITER&&p>=h?(s.push(e),s.push(a.Add(e,o)),s.push(a.Add(e,u))):n===exports.JoinTyps.MITER&&p<h&&l&&(s.push(a.Add(e,o)),s.push(e),s.push(l),s.push(a.Add(e,u)),s.push(e),s.push(l)),s.push(a.Add(r,u)),s.push(a.Sub(e,u)),s.push(a.Add(e,u)),s.push(a.Add(r,u)),s.push(a.Sub(e,u)),s.push(a.Sub(r,u));else{if(s.push(a.Add(t,o)),s.push(a.Sub(t,o)),s.push(a.Sub(e,d)),s.push(a.Add(t,o)),s.push(a.Sub(e,d)),s.push(a.Add(e,o)),n===exports.JoinTyps.ROUND){const t=a.Add(e,o),r=a.Add(e,u),i=a.Sub(e,d),n=e;s.push(t),s.push(n),s.push(i),R(n,t,r,i,s),s.push(n),s.push(r),s.push(i)}else(n===exports.JoinTyps.BEVEL||n===exports.JoinTyps.MITER&&p>=h)&&(s.push(a.Add(e,o)),s.push(a.Add(e,u)),s.push(a.Sub(e,d))),n===exports.JoinTyps.MITER&&p<h&&(s.push(l),s.push(a.Add(e,o)),s.push(a.Add(e,u)));s.push(a.Add(r,u)),s.push(a.Sub(e,d)),s.push(a.Add(e,u)),s.push(a.Add(r,u)),s.push(a.Sub(e,d)),s.push(a.Sub(r,u))}};exports.BaseTexture=u,exports.Color=h,exports.DynamicArrayBuffer=r,exports.GLShader=c,exports.MatrixStack=i,exports.Rapid=class{constructor(t){this.projectionDirty=!0,this.matrixStack=new i,this.textures=new o(this),this.devicePixelRatio=window.devicePixelRatio||1,this.defaultColor=new h(255,255,255,255),this.defaultColorBlack=new h(0,0,0,255),this.regions=new Map;const e=(t=>{const e=t.getContext("webgl2")||t.getContext("webgl");if(!e)throw new Error("TODO");return e})(t.canvas);this.gl=e,this.canvas=t.canvas,this.maxTextureUnits=e.getParameter(this.gl.MAX_TEXTURE_IMAGE_UNITS),this.width=t.width||this.canvas.width,this.height=t.width||this.canvas.height,this.backgroundColor=t.backgroundColor||new h(255,255,255,255),this.registerBuildInRegion(),this.initWebgl(e)}initWebgl(t){this.resize(this.width,this.height),t.enable(t.BLEND),t.disable(t.DEPTH_TEST),t.blendFunc(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA)}registerBuildInRegion(){this.registerRegion("sprite",m),this.registerRegion("graphic",f)}registerRegion(t,e){this.regions.set(t,new e(this))}setRegion(t,e){if(t!=this.currentRegionName||e&&e!==this.currentRegion.currentShader){const r=this.regions.get(t);this.currentRegion&&(this.currentRegion.render(),this.currentRegion.exitRegion()),this.currentRegion=r,this.currentRegionName=t,r.enterRegion(e)}}save(){this.matrixStack.pushMat()}restore(){this.matrixStack.popMat()}startRender(t=!0){t&&this.matrixStack.clear(),this.matrixStack.pushIdentity(),this.currentRegion=void 0,this.currentRegionName=void 0}endRender(){var t;null===(t=this.currentRegion)||void 0===t||t.render(),this.projectionDirty=!1}renderSprite(t,e=0,r=0,s){if(t.base){if(s instanceof h)return this.renderSprite(t,e,r,{color:s});this.setRegion("sprite",null==s?void 0:s.shader),this.currentRegion.renderSprite(t.base.texture,t.width,t.height,t.clipX,t.clipY,t.clipW,t.clipH,e,r,((null==s?void 0:s.color)||this.defaultColor).uint32,null==s?void 0:s.uniforms)}}renderLine(t=0,e=0,r){const s=((t,e)=>{if(t.length<2)return[];let r=e.cap||exports.CapTyps.BUTT,s=e.join||exports.JoinTyps.BEVEL,i=(e.width||1)/2,n=e.miterLimit||10,h=[],o=[];if(2===t.length)s=exports.JoinTyps.BEVEL,S(t[0],a.Middle(t[0],t[1]),t[1],h,i,s,n);else{for(let e=0;e<t.length-1;e++)0===e?o.push(t[0]):e===t.length-2?o.push(t[t.length-1]):o.push(a.Middle(t[e],t[e+1]));for(let e=1;e<o.length;e++)S(o[e-1],t[e],o[e],h,i,s,n)}if(r===exports.CapTyps.ROUND){let e=h[0],r=h[1],s=t[1],i=h[h.length-1],n=h[h.length-3],a=t[t.length-2];R(t[0],e,r,s,h),R(t[t.length-1],i,n,a,h)}else if(r===exports.CapTyps.SQUARE){let e=h[h.length-1],r=h[h.length-3];A(h[0],h[1],a.Sub(t[0],t[1]).normalize().scalarMult(a.Sub(t[0],h[0]).length()),h),A(e,r,a.Sub(t[t.length-1],t[t.length-2]).normalize().scalarMult(a.Sub(r,t[t.length-1]).length()),h)}return h})(r.points,r);this.renderGraphic(t,e,{color:r.color,drawType:this.gl.TRIANGLES,points:s})}renderGraphic(t=0,e=0,r){if(r instanceof Array)return this.renderGraphic(t,e,{points:r});this.startGraphicDraw(),r.drawType&&(this.currentRegion.drawType=r.drawType),r.points.forEach((s=>{this.addGraphicVertex(s.x+t,s.y+e,r.color||this.defaultColorBlack)})),this.endGraphicDraw()}startGraphicDraw(t){this.setRegion("graphic",t),this.currentRegion.startRender()}addGraphicVertex(t,e,r){if(t instanceof a)return this.addGraphicVertex(t.x,t.y,e);this.currentRegion.addVertex(t,e,r.uint32)}endGraphicDraw(){this.currentRegion.render()}resize(t,e){this.width=t,this.height=e;const r=t*this.devicePixelRatio,s=e*this.devicePixelRatio;this.canvas.width=r,this.canvas.height=s,this.gl.viewport(0,0,r,s),this.projection=this.createOrthMatrix(0,t,e,0),this.projectionDirty=!0}clear(){const t=this.gl,e=this.backgroundColor;t.clearColor(e.r,e.g,e.b,e.a),t.clear(t.COLOR_BUFFER_BIT)}createOrthMatrix(t,e,r,s){return new Float32Array([2/(e-t),0,0,0,0,2/(s-r),0,0,0,0,-1,0,-(e+t)/(e-t),-(s+r)/(s-r),0,1])}transformPoint(t,e){return this.matrixStack.apply(t,e)}},exports.SCALEFACTOR=2,exports.Text=d,exports.Texture=l,exports.TextureCache=o,exports.Vec2=a,exports.WebglBufferArray=s,exports.WebglElementBufferArray=n,exports.graphicAttributes=x,exports.spriteAttributes=y;
|
|
1
|
+
"use strict";var t,e,s,i,r,n,a,o;exports.ScaleRadio=void 0,(t=exports.ScaleRadio||(exports.ScaleRadio={})).KEEP="keep",t.KEEP_H="keep_h",t.KEEP_W="keep_w",t.IGNORE="ignore",t.EXPAND="expand",exports.LineTextureMode=void 0,(e=exports.LineTextureMode||(exports.LineTextureMode={})).STRETCH="stretch",e.REPEAT="repeat",exports.TextureWrapMode=void 0,(s=exports.TextureWrapMode||(exports.TextureWrapMode={})).REPEAT="repeat",s.CLAMP="clamp",s.MIRROR="mirror",exports.MaskType=void 0,(i=exports.MaskType||(exports.MaskType={})).Include="normal",i.Exclude="inverse",exports.TilemapShape=void 0,(r=exports.TilemapShape||(exports.TilemapShape={})).SQUARE="square",r.ISOMETRIC="isometric",exports.ShaderType=void 0,(n=exports.ShaderType||(exports.ShaderType={})).SPRITE="sprite",n.GRAPHIC="graphic",exports.BlendMode=void 0,(a=exports.BlendMode||(exports.BlendMode={})).Additive="additive",a.Subtractive="subtractive",a.Mix="mix",exports.ParticleShape=void 0,(o=exports.ParticleShape||(exports.ParticleShape={})).POINT="point",o.CIRCLE="circle",o.RECT="rect";var h;exports.ArrayType=void 0,(h=exports.ArrayType||(exports.ArrayType={}))[h.Float32=0]="Float32",h[h.Uint32=1]="Uint32",h[h.Uint16=2]="Uint16";class l{constructor(t){this.usedElemNum=0,this.maxElemNum=512,this.bytePerElem=this.getArrayType(t).BYTES_PER_ELEMENT,this.arrayType=t,this.arraybuffer=new ArrayBuffer(this.maxElemNum*this.bytePerElem),this.updateTypedArray()}getArrayType(t){switch(t){case exports.ArrayType.Float32:return Float32Array;case exports.ArrayType.Uint32:return Uint32Array;case exports.ArrayType.Uint16:return Uint16Array}}updateTypedArray(){switch(this.uint32=new Uint32Array(this.arraybuffer),this.float32=new Float32Array(this.arraybuffer),this.uint16=new Uint16Array(this.arraybuffer),this.arrayType){case exports.ArrayType.Float32:this.typedArray=this.float32;break;case exports.ArrayType.Uint32:this.typedArray=this.uint32;break;case exports.ArrayType.Uint16:this.typedArray=this.uint16}}clear(){this.usedElemNum=0}resize(t=0){if((t+=this.usedElemNum)>this.maxElemNum){for(;t>this.maxElemNum;)this.maxElemNum<<=1;this.setMaxSize(this.maxElemNum)}}setMaxSize(t=this.maxElemNum){const e=this.typedArray;this.maxElemNum=t,this.arraybuffer=new ArrayBuffer(t*this.bytePerElem),this.updateTypedArray(),this.typedArray.set(e)}pushUint32(t){this.uint32[this.usedElemNum++]=t}pushFloat32(t){this.float32[this.usedElemNum++]=t}pushUint16(t){this.uint16[this.usedElemNum++]=t}pop(t){this.usedElemNum-=t}getArray(t=0,e){return null==e?this.typedArray:this.typedArray.subarray(t,e)}get length(){return this.typedArray.length}}class u extends l{constructor(t,e,s=t.ARRAY_BUFFER,i=t.STATIC_DRAW){super(e),this.dirty=!0,this.webglBufferSize=0,this.gl=t,this.buffer=t.createBuffer(),this.type=s,this.usage=i}pushFloat32(t){super.pushFloat32(t),this.dirty=!0}pushUint32(t){super.pushUint32(t),this.dirty=!0}pushUint16(t){super.pushUint16(t),this.dirty=!0}bindBuffer(){this.gl.bindBuffer(this.type,this.buffer)}bufferData(){if(this.dirty){const t=this.gl;this.maxElemNum>this.webglBufferSize?(t.bufferData(this.type,this.getArray(),this.usage),this.webglBufferSize=this.maxElemNum):t.bufferSubData(this.type,0,this.getArray(0,this.usedElemNum)),this.dirty=!1}}}class c extends l{constructor(){super(exports.ArrayType.Float32)}pushMat(){const t=this.usedElemNum-6,e=this.typedArray;this.resize(6),this.pushFloat32(e[t+0]),this.pushFloat32(e[t+1]),this.pushFloat32(e[t+2]),this.pushFloat32(e[t+3]),this.pushFloat32(e[t+4]),this.pushFloat32(e[t+5])}popMat(){this.pop(6)}pushIdentity(){this.resize(6),this.pushFloat32(1),this.pushFloat32(0),this.pushFloat32(0),this.pushFloat32(1),this.pushFloat32(0),this.pushFloat32(0)}translate(t,e){if("number"!=typeof t)return this.translate(t.x,t.y);const s=this.usedElemNum-6,i=this.typedArray;i[s+4]=i[s+0]*t+i[s+2]*e+i[s+4],i[s+5]=i[s+1]*t+i[s+3]*e+i[s+5]}rotate(t){const e=this.usedElemNum-6,s=this.typedArray,i=Math.cos(t),r=Math.sin(t),n=s[e+0],a=s[e+1],o=s[e+2],h=s[e+3];s[e+0]=n*i-a*r,s[e+1]=n*r+a*i,s[e+2]=o*i-h*r,s[e+3]=o*r+h*i}scale(t,e){if("number"!=typeof t)return this.scale(t.x,t.y);e||(e=t);const s=this.usedElemNum-6,i=this.typedArray;i[s+0]=i[s+0]*t,i[s+1]=i[s+1]*t,i[s+2]=i[s+2]*e,i[s+3]=i[s+3]*e}apply(t,e){if("number"!=typeof t)return new f(...this.apply(t.x,t.y));const s=this.usedElemNum-6,i=this.typedArray;return[i[s+0]*t+i[s+2]*e+i[s+4],i[s+1]*t+i[s+3]*e+i[s+5]]}getInverse(){const t=this.usedElemNum-6,e=this.typedArray,s=e[t+0],i=e[t+1],r=e[t+2],n=e[t+3],a=e[t+4],o=e[t+5],h=s*n-i*r;return new Float32Array([n/h,-i/h,-r/h,s/h,(r*o-n*a)/h,(i*a-s*o)/h])}getTransform(){const t=this.usedElemNum-6,e=this.typedArray;return new Float32Array([e[t+0],e[t+1],e[t+2],e[t+3],e[t+4],e[t+5]])}setTransform(t){const e=this.usedElemNum-6,s=this.typedArray;s[e+0]=t[0],s[e+1]=t[1],s[e+2]=t[2],s[e+3]=t[3],s[e+4]=t[4],s[e+5]=t[5]}getGlobalPosition(){const t=this.usedElemNum-6,e=this.typedArray;return new f(e[t+4],e[t+5])}setGlobalPosition(t,e){if("number"!=typeof t)return void this.setGlobalPosition(t.x,t.y);const s=this.usedElemNum-6,i=this.typedArray;i[s+4]=t,i[s+5]=e}getGlobalRotation(){const t=this.usedElemNum-6,e=this.typedArray;return Math.atan2(e[t+1],e[t+0])}setGlobalRotation(t){const e=this.usedElemNum-6,s=this.typedArray,i=this.getGlobalScale(),r=Math.cos(t),n=Math.sin(t);s[e+0]=r*i.x,s[e+1]=n*i.x,s[e+2]=-n*i.y,s[e+3]=r*i.y}getGlobalScale(){const t=this.usedElemNum-6,e=this.typedArray,s=Math.sqrt(e[t+0]*e[t+0]+e[t+1]*e[t+1]),i=Math.sqrt(e[t+2]*e[t+2]+e[t+3]*e[t+3]);return new f(s,i)}setGlobalScale(t,e){if("number"!=typeof t)return void this.setGlobalScale(t.x,t.y);const s=this.getGlobalRotation(),i=Math.cos(s),r=Math.sin(s),n=this.usedElemNum-6,a=this.typedArray;a[n+0]=i*t,a[n+1]=r*t,a[n+2]=-r*e,a[n+3]=i*e}globalToLocal(t){const e=this.getInverse();return new f(e[0]*t.x+e[2]*t.y+e[4],e[1]*t.x+e[3]*t.y+e[5])}localToGlobal(t){return this.apply(t)}toCSSTransform(){const t=this.usedElemNum-6,e=this.typedArray;return`matrix(${e[t+0]}, ${e[t+1]}, ${e[t+2]}, ${e[t+3]}, ${e[t+4]}, ${e[t+5]})`}identity(){const t=this.usedElemNum-6,e=this.typedArray;e[t+0]=1,e[t+1]=0,e[t+2]=0,e[t+3]=1,e[t+4]=0,e[t+5]=0}applyTransform(t,e=0,s=0){(t.saveTransform??1)&&this.pushMat(),t.afterSave&&t.afterSave();const i=t.x||0,r=t.y||0;(i||r)&&this.translate(i,r),t.position&&this.translate(t.position),t.rotation&&this.rotate(t.rotation),t.scale&&this.scale(t.scale);let n=t.offsetX||0,a=t.offsetY||0;t.offset&&(n+=t.offset.x,a+=t.offset.y);const o=t.origin;return o&&("number"==typeof o?(n-=o*e,a-=o*s):(n-=o.x*e,a-=o.y*s)),{offsetX:n,offsetY:a}}applyTransformAfter(t){t.beforRestore&&t.beforRestore(),(t.restoreTransform??1)&&this.popMat()}}class d extends u{constructor(t,e,s,i){super(t,exports.ArrayType.Uint16,t.ELEMENT_ARRAY_BUFFER,t.STATIC_DRAW),this.setMaxSize(e*i);for(let t=0;t<i;t++)this.addObject(t*s);this.bindBuffer(),this.bufferData()}addObject(t){}}class p{constructor(t,e,s,i=255){this._r=t,this._g=e,this._b=s,this._a=i,this.updateUint()}get r(){return this._r}set r(t){this._r=t,this.updateUint()}get g(){return this._g}set g(t){this._g=t,this.updateUint()}get b(){return this._b}set b(t){this._b=t,this.updateUint()}get a(){return this._a}set a(t){this._a=t,this.updateUint()}updateUint(){this.uint32=(this._a<<24|this._b<<16|this._g<<8|this._r)>>>0}setRGBA(t,e,s,i){this.r=t,this.g=e,this.b=s,this.a=i,this.updateUint()}copy(t){this.setRGBA(t.r,t.g,t.b,t.a)}clone(){return new p(this._r,this._g,this._b,this._a)}equal(t){return t.r===this.r&&t.g===this.g&&t.b===this.b&&t.a===this.a}static fromHex(t){t.startsWith("#")&&(t=t.slice(1));const e=parseInt(t.slice(0,2),16),s=parseInt(t.slice(2,4),16),i=parseInt(t.slice(4,6),16);let r=255;return t.length>=8&&(r=parseInt(t.slice(6,8),16)),new p(e,s,i,r)}add(t){return new p(Math.min(this.r+t.r,255),Math.min(this.g+t.g,255),Math.min(this.b+t.b,255),Math.min(this.a+t.a,255))}subtract(t){return new p(Math.max(0,this.r-t.r),Math.max(0,this.g-t.g),Math.max(0,this.b-t.b),Math.max(0,this.a-t.a))}divide(t){return t instanceof p?new p(this.r/t.r,this.g/t.g,this.b/t.b,this.a/t.a):new p(this.r/t,this.g/t,this.b/t,this.a/t)}multiply(t){return t instanceof p?new p(this.r*t.r,this.g*t.g,this.b*t.b,this.a*t.a):new p(this.r*t,this.g*t,this.b*t,this.a*t)}clamp(){this.r=Math.max(0,Math.min(255,this.r)),this.g=Math.max(0,Math.min(255,this.g)),this.b=Math.max(0,Math.min(255,this.b)),this.a=Math.max(0,Math.min(255,this.a))}}p.Red=new p(255,0,0,255),p.Green=new p(0,255,0,255),p.Blue=new p(0,0,255,255),p.Yellow=new p(255,255,0,255),p.Purple=new p(128,0,128,255),p.Orange=new p(255,165,0,255),p.Pink=new p(255,192,203,255),p.Gray=new p(128,128,128,255),p.Brown=new p(139,69,19,255),p.Cyan=new p(0,255,255,255),p.Magenta=new p(255,0,255,255),p.Lime=new p(192,255,0,255),p.White=new p(255,255,255,255),p.Black=new p(0,0,0,255),p.TRANSPARENT=new p(0,0,0,0);class f{constructor(t,e){this.x=void 0!==t?t:0,this.y=void 0!==e?e:0}set(t,e){return Array.isArray(t)?(this.x=t[0],this.y=t[0]):e?(this.x=t,this.y=e):(this.x=t,this.y=t),this}add(t){return new f(this.x+t.x,this.y+t.y)}subtract(t){return new f(this.x-t.x,this.y-t.y)}multiply(t){return t instanceof f?new f(this.x*t.x,this.y*t.y):new f(this.x*t,this.y*t)}divide(t){return t instanceof f?new f(this.x/t.x,this.y/t.y):new f(this.x/t,this.y/t)}dot(t){return this.x*t.x+this.y*t.y}cross(t){return this.x*t.y-this.y*t.x}distanceTo(t){const e=this.x-t.x,s=this.y-t.y;return Math.sqrt(e*e+s*s)}clone(){return new f(this.x,this.y)}copy(t){this.x=t.x,this.y=t.y}equal(t){return t.x==this.x&&t.y==this.y}perpendicular(){const t=this.x;return this.x=-this.y,this.y=t,this}invert(){return this.x=-this.x,this.y=-this.y,this}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}normalize(){const t=this.length();return this.x=this.x/t||0,this.y=this.y/t||0,this}angle(){return Math.atan2(this.y,this.x)}middle(t){return new f((this.x+t.x)/2,(this.y+t.y)/2)}abs(){return new f(Math.abs(this.x),Math.abs(this.y))}floor(){return new f(Math.floor(this.x),Math.floor(this.y))}ceil(){return new f(Math.ceil(this.x),Math.ceil(this.y))}snap(t){return new f(Math.round(this.x/t)*t,Math.round(this.y/t)*t)}stringify(){return`Vec2(${this.x}, ${this.y})`}static FromArray(t){return t.map((t=>new f(t[0],t[1])))}static fromAngle(t){return new f(Math.cos(t),Math.sin(t))}angleBetween(t){const e=this.dot(t),s=this.length()*t.length(),i=Math.max(-1,Math.min(1,e/s));return Math.acos(i)}}f.ZERO=new f(0,0),f.ONE=new f(1,1),f.UP=new f(0,1),f.DOWN=new f(0,-1),f.LEFT=new f(-1,0),f.RIGHT=new f(1,0);class m{static float(t,e){return Math.random()*(e-t)+t}static int(t,e){return Math.floor(Math.random()*(e-t+1))+t}static angle(){return Math.random()*Math.PI*2}static vector(t,e,s,i){return new f(m.float(t,e),m.float(s,i))}static direction(t){const e=m.angle();return new f(Math.cos(e)*t,Math.sin(e)*t)}static randomColor(t,e){return new p(m.float(t.r,e.r),m.float(t.g,e.g),m.float(t.b,e.b),m.float(t.a,e.a))}static pick(t){return t[m.int(0,t.length-1)]}static pickWeight(t){if(!t||0===t.length)return null;let e=0;for(const s of t)e+=s[1];const s=Math.random()*e;let i=0;for(const e of t)if(i+=e[1],s<=i)return e[0];return t[t.length-1][0]}static scalarOrRange(t,e){if(void 0===t)return e;if(Array.isArray(t)){if("number"==typeof t[0])return m.float(t[0],t[1]);if(t[0]instanceof f)return m.vector(t[0].x,t[1].x,t[0].y,t[1].y);if(t[0]instanceof p)return m.randomColor(t[0],t[1])}return"number"==typeof t?t:t.clone()}}class x{constructor(t){this.render=t}createLightShadowMaskPolygon(t,e,s){const i=[];t.forEach((t=>{for(let e=0;e<t.length;e++){const s=t[e],r=t[(e+1)%t.length];i.push([s,r])}})),s=s||Math.sqrt(Math.pow(this.render.width,2)+Math.pow(this.render.height,2));const r=[];return i.forEach((([t,i])=>{const n=new f(t.x-e.x,t.y-e.y),a=new f(i.x-e.x,i.y-e.y),o=i.subtract(t).perpendicular(),h=Math.abs(o.dot(n))/(o.length()*n.length())+.01,l=Math.abs(o.dot(a))/(o.length()*a.length())+.01,u=s/h,c=s/l,d=new f(n.x,n.y).normalize(),p=new f(a.x,a.y).normalize(),m=new f(t.x+d.x*u,t.y+d.y*u),x=new f(i.x+p.x*c,i.y+p.y*c);r.push([t,i,x,m])})),r}}const g=(t,e,s,i)=>{const r=[],n=i?Math.atan2(e.y,e.x):Math.atan2(-e.y,-e.x),a=Math.PI;for(let e=0;e<10;e++){const i=n+e/10*a,o=n+(e+1)/10*a,h=Math.cos(i)*s,l=Math.sin(i)*s,u=Math.cos(o)*s,c=Math.sin(o)*s;r.push(t),r.push(t.add(new f(h,l))),r.push(t.add(new f(u,c)))}return r},y=t=>{const e=t.points;if(e.length<2)return{vertices:[],uv:[]};const{normals:s,length:i}=((t,e=!1)=>{const s=[];if(t.length<2||e&&t.length<3)return{normals:s,length:0};const i=t.length;let r=0;if(e)for(let e=0;e<i;e++){const s=t[e],n=t[(e+1)%i];r+=s.distanceTo(n)}else for(let e=0;e<i-1;e++)r+=t[e].distanceTo(t[e+1]);const n=(t,e,s)=>{const i=e.subtract(t).normalize(),r=e.subtract(s).normalize(),n=r.dot(i);if(n<-.999)return{normal:i.perpendicular(),miters:1};{let t=r.add(i).normalize();i.cross(r)<0&&(t=t.multiply(-1));let e=1/Math.sqrt((1-n)/2);return{normal:t,miters:Math.min(e,4)}}};if(e){for(let e=0;e<i-1;e++){const r=0===e?t[i-2]:t[e-1],a=t[e],o=t[e+1];s.push(n(r,a,o))}s.push(s[0])}else for(let e=0;e<i;e++)if(0===e){const e=t[1].subtract(t[0]).normalize();s.push({normal:e.perpendicular(),miters:1})}else if(e===i-1){const i=t[e].subtract(t[e-1]).normalize();s.push({normal:i.perpendicular(),miters:1})}else s.push(n(t[e-1],t[e],t[e+1]));return{normals:s,length:r}})(e,t.closed),r=(t.width||1)/2,n=[],a=[],o=t.roundCap||!1,h=t.textureMode||exports.LineTextureMode.STRETCH;let l=0;const u=t.texture?.width||1;for(let t=0;t<e.length-1;t++){const o=e[t],c=s[t].normal,d=s[t].miters,p=o.add(c.multiply(d*r)),m=o.subtract(c.multiply(d*r)),x=e[t+1],g=s[t+1].normal,y=s[t+1].miters,T=x.add(g.multiply(y*r)),w=x.subtract(g.multiply(y*r)),b=o.distanceTo(x);let E=0,R=0;h===exports.LineTextureMode.STRETCH?(E=l/i,R=(l+b)/i):(E=l/u,R=E+b/u);const v=new f(E,0),S=new f(E,1),A=new f(R,0),M=new f(R,1);n.push(p),a.push(v),n.push(m),a.push(S),n.push(T),a.push(A),n.push(T),a.push(A),n.push(w),a.push(M),n.push(m),a.push(S),l+=b}if(o&&!t.closed){const t=e[0],i=s[0].normal,a=g(t,i,r,!0);n.push(...a);const o=e[e.length-1],h=s[e.length-1].normal,l=g(o,h,r,!1);n.push(...l)}return{vertices:n,uv:a}};var T="precision mediump float;\r\nvarying vec2 vRegion;\r\nvarying vec4 vColor;\r\n\r\nuniform sampler2D uTexture;\r\nuniform int uUseTexture;\r\n\r\nvoid main(void) {\r\n vec4 color;\r\n if(uUseTexture > 0){\r\n color = texture2D(uTexture, vRegion) * vColor;\r\n }else{\r\n color = vColor;\r\n }\r\n // fragment\r\n gl_FragColor = color;\r\n}\r\n",w="precision mediump float;\r\n\r\nattribute vec2 aPosition;\r\nattribute vec4 aColor;\r\nattribute vec2 aRegion;\r\n\r\nvarying vec4 vColor;\r\nuniform mat4 uProjectionMatrix;\r\nuniform vec4 uColor;\r\nvarying vec2 vRegion;\r\n\r\nvoid main(void) {\r\n // vertex s\r\n gl_Position = uProjectionMatrix * vec4(aPosition, 0.0, 1.0);\r\n // vertex e\r\n vColor = aColor;\r\n vRegion = aRegion;\r\n}\r\n";const b=(t,e,s)=>{const i=t.createShader(s);if(!i)throw new Error("Unable to create webgl shader");t.shaderSource(i,e),t.compileShader(i);if(!t.getShaderParameter(i,t.COMPILE_STATUS)){const s=t.getShaderInfoLog(i);throw console.error("Shader compilation failed:",s),new Error("Unable to compile shader: "+s+e)}return i};function E(t,e,s,i=!1,r=!1,n="clamp"){const a=t.createTexture();if(!a)throw new Error("unable to create texture");let o;switch(t.bindTexture(t.TEXTURE_2D,a),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,s?t.LINEAR:t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,s?t.LINEAR:t.NEAREST),n){case"repeat":o=t.REPEAT;break;case"mirror":o=t.MIRRORED_REPEAT;break;default:o=t.CLAMP_TO_EDGE}return t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,o),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,o),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,r),i?t.texImage2D(t.TEXTURE_2D,0,t.RGBA,e.width,e.height,0,t.RGBA,t.UNSIGNED_BYTE,null):t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),a}const R=5126;var v="precision mediump float;\r\nuniform sampler2D uTextures[%TEXTURE_NUM%];\r\n\r\nvarying vec2 vRegion;\r\nvarying float vTextureId;\r\nvarying vec4 vColor;\r\n\r\nvoid main(void) {\r\n vec4 color;\r\n %GET_COLOR%\r\n // fragment\r\n gl_FragColor = color * vColor;\r\n}",S="precision mediump float;\r\n\r\nattribute vec2 aPosition;\r\nattribute vec2 aRegion;\r\nattribute float aTextureId;\r\nattribute vec4 aColor;\r\n\r\nuniform mat4 uProjectionMatrix;\r\n\r\nvarying vec2 vRegion;\r\nvarying float vTextureId;\r\nvarying vec4 vColor;\r\n\r\nvoid main(void) {\r\n vRegion = aRegion;\r\n vTextureId = aTextureId;\r\n vColor = aColor;\r\n\r\n // vertex s\r\n gl_Position = uProjectionMatrix * vec4(aPosition, 0.0, 1.0);\r\n // vertex e\r\n}";const A=[{name:"aPosition",size:2,type:R,stride:24},{name:"aRegion",size:2,type:R,stride:24,offset:2*Float32Array.BYTES_PER_ELEMENT},{name:"aTextureId",size:1,type:R,stride:24,offset:4*Float32Array.BYTES_PER_ELEMENT},{name:"aColor",size:4,type:5121,stride:24,offset:5*Float32Array.BYTES_PER_ELEMENT,normalized:!0}],M=[{name:"aPosition",size:2,type:R,stride:20},{name:"aColor",size:4,type:5121,stride:20,offset:2*Float32Array.BYTES_PER_ELEMENT,normalized:!0},{name:"aRegion",size:2,type:R,stride:20,offset:3*Float32Array.BYTES_PER_ELEMENT}];class C{constructor(t,e,s,i,r=0){this.attributeLoc={},this.uniformLoc={},this.textureUnitNum=0,this.attributes=[];const n=function(t,e){if(t.includes("%TEXTURE_NUM%")&&(t=t.replace("%TEXTURE_NUM%",e.toString())),t.includes("%GET_COLOR%")){let s="";for(let t=0;t<e;t++)s+=0==t?`if(vTextureId == ${t}.0)`:t==e-1?"else":`else if(vTextureId == ${t}.0)`,s+=`{color = texture2D(uTextures[${t}], vRegion);}`;t=t.replace("%GET_COLOR%",s)}return t}(s,t.maxTextureUnits-r);this.program=((t,e,s)=>{var i=t.createProgram(),r=b(t,e,35633),n=b(t,s,35632);if(!i)throw new Error("Unable to create program shader");if(t.attachShader(i,r),t.attachShader(i,n),t.linkProgram(i),!t.getProgramParameter(i,t.LINK_STATUS)){const e=t.getProgramInfoLog(i);throw new Error("Unable to link shader program: "+e)}return i})(t.gl,e,n),this.gl=t.gl,this.textureUnitNum=r,this.parseShader(e),this.parseShader(n),i&&this.setAttributes(i)}setUniforms(t,e){const s=this.gl;for(const i of t.getUnifromNames()){const r=this.getUniform(i);t.bind(s,i,r,e)}}getUniform(t){return this.uniformLoc[t]}use(){this.gl.useProgram(this.program)}parseShader(t){const e=this.gl,s=t.match(/attribute\s+\w+\s+(\w+)/g);if(s)for(const t of s){const s=t.split(" ")[2],i=e.getAttribLocation(this.program,s);-1!=i&&(this.attributeLoc[s]=i)}const i=t.match(/uniform\s+\w+\s+(\w+)/g);if(i)for(const t of i){const s=t.split(" ")[2];this.uniformLoc[s]=e.getUniformLocation(this.program,s)}}setAttribute(t){const e=this.attributeLoc[t.name];if(void 0!==e){const s=this.gl;s.vertexAttribPointer(e,t.size,t.type,t.normalized||!1,t.stride,t.offset||0),s.enableVertexAttribArray(e)}}setAttributes(t){this.attributes=t;for(const e of t)this.setAttribute(e)}updateAttributes(){this.setAttributes(this.attributes)}static createCostumShader(t,e,s,i,r=0){let n={[exports.ShaderType.SPRITE]:v,[exports.ShaderType.GRAPHIC]:T}[i],a={[exports.ShaderType.SPRITE]:S,[exports.ShaderType.GRAPHIC]:w}[i];const o={[exports.ShaderType.SPRITE]:A,[exports.ShaderType.GRAPHIC]:M}[i];return n=n.replace("void main(void) {",s+"\nvoid main(void) {"),a=a.replace("void main(void) {",e+"\nvoid main(void) {"),n=n.replace("// fragment","fragment(color);"),a=a.replace(/\/\/ vertex s[\s\S]*?\/\/ vertex e/,"vec2 position = aPosition;\n vertex(position, vRegion);\n gl_Position = uProjectionMatrix * vec4(position, 0.0, 1.0);"),new C(t,a,n,o,r)}}class U{constructor(t){this.usedTextures=[],this.shaders=new Map,this.isCostumShader=!1,this.freeTextureUnitNum=0,this.rapid=t,this.gl=t.gl,this.webglArrayBuffer=new u(t.gl,exports.ArrayType.Float32,t.gl.ARRAY_BUFFER,t.gl.STREAM_DRAW),this.maxTextureUnits=t.maxTextureUnits}getTextureUnitList(){return Array.from({length:this.maxTextureUnits},((t,e)=>e))}addVertex(t,e,...s){const[i,r]=this.rapid.matrixStack.apply(t,e);this.webglArrayBuffer.pushFloat32(i),this.webglArrayBuffer.pushFloat32(r)}useTexture(t){const e=this.usedTextures.indexOf(t);return-1==e?(this.usedTextures.push(t),this.freeTextureUnitNum=this.maxTextureUnits-this.usedTextures.length,[this.usedTextures.length-1,!0]):[e,!1]}enterRegion(t){this.currentShader=t??this.getShader("default"),this.currentShader.use(),this.initializeForNextRender(),this.webglArrayBuffer.bindBuffer(),this.currentShader.updateAttributes(),this.updateProjection(),this.isCostumShader=Boolean(t)}updateProjection(){this.gl.uniformMatrix4fv(this.currentShader.uniformLoc.uProjectionMatrix,!1,this.rapid.projection)}isUnifromChanged(t){return!!t&&(this.costumUnifrom!=t||!!t?.isDirty)}setCurrentUniform(t){t.clearDirty(),this.costumUnifrom=t}exitRegion(){}initDefaultShader(t,e,s){this.setShader("default",t,e,s)}setShader(t,e,s,i){this.webglArrayBuffer.bindBuffer(),this.shaders.set(t,new C(this.rapid,e,s,i)),"default"===t&&(this.defaultShader=this.shaders.get(t))}getShader(t){return this.shaders.get(t)}render(){this.executeRender(),this.initializeForNextRender()}executeRender(){const t=this.gl;for(let e=0;e<this.usedTextures.length;e++)t.activeTexture(t.TEXTURE0+e),t.bindTexture(t.TEXTURE_2D,this.usedTextures[e]);this.webglArrayBuffer.bufferData()}initializeForNextRender(){this.webglArrayBuffer.clear(),this.usedTextures.length=0,this.isCostumShader=!1,this.freeTextureUnitNum=this.maxTextureUnits}hasPendingContent(){return!1}isShaderChanged(t){return(t||this.defaultShader)!=this.currentShader}}class _ extends U{constructor(t){super(t),this.vertex=0,this.offset=f.ZERO,this.drawType=t.gl.TRIANGLE_FAN,this.setShader("default",w,T,M)}startRender(t,e,s,i){i&&this.currentShader?.setUniforms(i,this),this.offset=new f(t,e),this.vertex=0,this.webglArrayBuffer.clear(),s&&s.base&&(this.texture=this.useTexture(s.base.texture)[0])}addVertex(t,e,s,i,r){this.webglArrayBuffer.resize(3),super.addVertex(t+this.offset.x,e+this.offset.y),this.webglArrayBuffer.pushUint32(r),this.webglArrayBuffer.pushFloat32(s),this.webglArrayBuffer.pushFloat32(i),this.vertex+=1}executeRender(){super.executeRender();const t=this.gl;t.uniform1i(this.currentShader.uniformLoc.uUseTexture,void 0===this.texture?0:1),this.texture&&t.uniform1i(this.currentShader.uniformLoc.uTexture,this.texture),t.drawArrays(this.drawType,0,this.vertex),this.drawType=this.rapid.gl.TRIANGLE_FAN,this.vertex=0,this.texture=void 0}}const F=Math.floor(16384);class P extends d{constructor(t,e){super(t,6,4,e)}addObject(t){super.addObject(),this.pushUint16(t),this.pushUint16(t+1),this.pushUint16(t+2),this.pushUint16(t),this.pushUint16(t+3),this.pushUint16(t+2)}}class L extends U{constructor(t){const e=t.gl;super(t),this.batchSprite=0,this.spriteTextureUnits=[],this.spriteTextureUnitIndexOffset=0,this.setShader("default",S,v,A),this.indexBuffer=new P(e,F)}addVertex(t,e,s,i,r,n){super.addVertex(t,e),this.webglArrayBuffer.pushFloat32(s),this.webglArrayBuffer.pushFloat32(i),this.webglArrayBuffer.pushFloat32(r),this.webglArrayBuffer.pushUint32(n)}renderSprite(t,e,s,i,r,n,a,o,h,l,u,c,d,p=0){(1+p>this.freeTextureUnitNum||this.batchSprite>=F||this.isUnifromChanged(u)||this.rapid.projectionDirty)&&(this.render(),u&&this.isUnifromChanged(u)&&(this.currentShader.setUniforms(u,this),this.setCurrentUniform(u)),this.rapid.projectionDirty&&this.updateProjection()),this.batchSprite++,this.webglArrayBuffer.resize(20);const[f,m]=this.useTexture(t);m&&(this.spriteTextureUnits.push(f),this.spriteTextureUnitIndexOffset=this.spriteTextureUnits[0]);const x=f-this.spriteTextureUnitIndexOffset,g=c?n:i,y=c?i:n,T=d?a:r,w=d?r:a,b=o,E=o+e,R=h,v=h+s;this.addVertex(b,R,g,T,x,l),this.addVertex(E,R,y,T,x,l),this.addVertex(E,v,y,w,x,l),this.addVertex(b,v,g,w,x,l)}executeRender(){if(super.executeRender(),this.batchSprite<=0)return;const t=this.gl;this.spriteTextureUnits.length>0&&this.gl.uniform1iv(this.currentShader.uniformLoc.uTextures,this.spriteTextureUnits),t.drawElements(t.TRIANGLES,6*this.batchSprite,t.UNSIGNED_SHORT,0)}enterRegion(t){super.enterRegion(t),this.indexBuffer.bindBuffer()}initializeForNextRender(){super.initializeForNextRender(),this.batchSprite=0,this.spriteTextureUnits.length=0}hasPendingContent(){return this.batchSprite>0}}class D{constructor(t,e){this.cache=new Map,this.render=t,this.antialias=e}async textureFromUrl(t,e=this.antialias,s=exports.TextureWrapMode.CLAMP){let i=this.cache.get(t);if(!i){const r=await this.loadImage(t);i=N.fromImageSource(this.render,r,e,s),this.cache.set(t,i)}return new I(i)}textureFromFrameBufferObject(t){return new I(t)}textureFromSource(t,e=this.antialias,s=exports.TextureWrapMode.CLAMP){let i=this.cache.get(t);return i||(i=N.fromImageSource(this.render,t,e,s),this.cache.set(t,i)),new I(i)}async loadImage(t){return new Promise((e=>{const s=new Image;s.onload=()=>{e(s)},s.src=t}))}createText(t){return new k(this.render,t)}destroy(t){t instanceof I?(t.base?.destroy(this.render.gl),this.removeCache(t)):(t.destroy(this.render.gl),this.removeCache(t))}createFrameBufferObject(t,e,s=this.antialias){return new B(this.render,t,e,s)}removeCache(t){const e=t instanceof I?t.base?.texture:t.texture;e&&this.cache.forEach(((t,s)=>{t===e&&this.cache.delete(s)}))}}class N{constructor(t,e,s,i=exports.TextureWrapMode.CLAMP){this.texture=t,this.width=e,this.height=s,this.wrapMode=i}static fromImageSource(t,e,s=!1,i=exports.TextureWrapMode.CLAMP){return new N(E(t.gl,e,s,!1,!1,i),e.width,e.height)}destroy(t){t.deleteTexture(this.texture)}}class I{constructor(t){this.scale=1,this.setBaseTextur(t)}setBaseTextur(t){t&&(this.base=t,this.setClipRegion(0,0,t.width,t.height))}setClipRegion(t,e,s,i){if(this.base)return this.clipX=t/this.base.width,this.clipY=e/this.base.height,this.clipW=this.clipX+s/this.base.width,this.clipH=this.clipY+i/this.base.height,this.width=s*this.scale,this.height=i*this.scale,this}static fromImageSource(t,e,s=!1){return new I(N.fromImageSource(t,e,s))}createSpritesHeet(t,e){if(!this.base)return[];const s=[],i=Math.floor(this.base.width/t),r=Math.floor(this.base.height/e);for(let n=0;n<r;n++)for(let r=0;r<i;r++){const i=this.clone();i.setClipRegion(r*t,n*e,t,e),s.push(i)}return s}clone(){return new I(this.base)}}class k extends I{constructor(t,e){super(),this.scale=.5,this.rapid=t,this.options=e,this.text=e.text||" ",this.updateTextImage()}updateTextImage(){const t=this.createTextCanvas();this.setBaseTextur(N.fromImageSource(this.rapid,t,!0))}createTextCanvas(){const t=document.createElement("canvas"),e=t.getContext("2d");if(!e)throw new Error("Failed to get canvas context");e.font=`${this.options.fontSize||16}px ${this.options.fontFamily||"Arial"}`,e.fillStyle=this.options.color||"#000",e.textAlign=this.options.textAlign||"left",e.textBaseline=this.options.textBaseline||"top";const s=this.text.split("\n");let i=0,r=0;for(const t of s){const s=e.measureText(t);i=Math.max(i,s.width),r+=this.options.fontSize||16}t.width=2*i,t.height=2*r,e.scale(2,2),e.font=`${this.options.fontSize||16}px ${this.options.fontFamily||"Arial"}`,e.fillStyle=this.options.color||"#000",e.textAlign=this.options.textAlign||"left",e.textBaseline=this.options.textBaseline||"top";let n=0;for(const t of s)e.fillText(t,0,n),n+=this.options.fontSize||16;return t}setText(t){this.text!=t&&(this.text=t,this.updateTextImage())}}class B extends N{constructor(t,e,s,i=!1){const r=t.gl,n=E(r,{width:e,height:s},i,!0,!1),a=r.createFramebuffer();if(!a)throw r.deleteTexture(n),new Error("Failed to create WebGL framebuffer");r.bindFramebuffer(r.FRAMEBUFFER,a),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,n,0);const o=r.createRenderbuffer();if(!o)throw r.deleteFramebuffer(a),r.deleteTexture(n),new Error("Failed to create depth-stencil renderbuffer");r.bindRenderbuffer(r.RENDERBUFFER,o),r.renderbufferStorage(r.RENDERBUFFER,r.STENCIL_INDEX8,e,s),r.framebufferRenderbuffer(r.FRAMEBUFFER,r.STENCIL_ATTACHMENT,r.RENDERBUFFER,o),super(n,e,s),this.gl=r,this.framebuffer=a,r.bindTexture(r.TEXTURE_2D,null),r.bindFramebuffer(r.FRAMEBUFFER,null)}bind(){const t=this.gl;t.bindTexture(t.TEXTURE_2D,null),t.bindFramebuffer(t.FRAMEBUFFER,this.framebuffer),t.clearColor(.5,.2,.5,.5),t.clear(t.COLOR_BUFFER_BIT)}unbind(){this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,null),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}resize(t,e){this.width=t,this.height=e,this.gl.bindTexture(this.gl.TEXTURE_2D,this.texture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,t,e,0,this.gl.RGBA,this.gl.UNSIGNED_BYTE,null),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}destroy(t){t.deleteFramebuffer(this.framebuffer),super.destroy(t)}}class O{constructor(t,e){this.textures=new Map,this.width=t,this.height=e}setTile(t,e){e instanceof I&&(e={texture:e}),this.textures.set(t,e)}getTile(t){return this.textures.get(t)}}class G{constructor(t){this.rapid=t}getYSortRow(t,e){const s=new Map;if(!t)return s;for(const i of t){const t=Math.floor(i.ySort/e);s.has(t)||s.set(t,[]),s.get(t).push(i)}return s}getOffset(t){let e=(t.errorX??2)+1,s=(t.errorY??2)+1;if("number"==typeof t.error){const i=(t.error??2)+1;e=i,s=i}else t.error&&(e=t.error.x+1,s=t.error.y+1);return{errorX:e,errorY:s}}renderYSortRow(t,e){if(e&&0!==e.length)for(const s of e)s.render?s.render():s.entity?s.entity.onRender(t):s.renderSprite&&t.renderSprite(s.renderSprite)}getTileData(t,e){const s=e.shape??exports.TilemapShape.SQUARE,i=t.width,r=s===exports.TilemapShape.ISOMETRIC?t.height/2:t.height,n=this.rapid.matrixStack,{errorX:a,errorY:o}=this.getOffset(e),h=new f(0,0),l=new f(this.rapid.width,0),u=new f(0,this.rapid.height),c=new f(this.rapid.width,this.rapid.height),d=n.globalToLocal(h),p=n.globalToLocal(l),m=n.globalToLocal(u),x=n.globalToLocal(c),g=Math.min(d.x,p.x,m.x,x.x),y=Math.max(d.x,p.x,m.x,x.x),T=Math.min(d.y,p.y,m.y,x.y),w=Math.max(d.y,p.y,m.y,x.y),b=new f(Math.floor(g/i)-a,Math.floor(T/r)-o),E=new f(Math.ceil(y/i)+a,Math.ceil(w/r)+o);return{startTile:b,viewportWidth:E.x-b.x,viewportHeight:E.y-b.y,height:r}}renderLayer(t,e){this.rapid.matrixStack.applyTransform(e);const s=e.tileSet,{startTile:i,viewportWidth:r,viewportHeight:n,height:a}=this.getTileData(s,e),o=this.getYSortRow(e.ySortCallback,a),h=e.ySortCallback&&e.ySortCallback.length>0;for(let a=0;a<n;a++){const n=a+i.y,l=o.get(n)??[];if(n<0||n>=t.length)this.renderYSortRow(this.rapid,l);else{for(let a=0;a<r;a++){const r=a+i.x;if(r<0||r>=t[n].length)continue;const o=t[n][r],h=s.getTile(o);if(!h)continue;const u=this.mapToLocal(new f(r,n),e),c=this.rapid.matrixStack.localToGlobal(u).y+(h.ySortOffset??0),d=e.eachTile&&e.eachTile(o,r,n)||{};l.push({ySort:c,renderSprite:{...h,x:u.x+(h.x||0),y:u.y+(h.y||0),...d}})}h&&l.sort(((t,e)=>t.ySort-e.ySort)),this.renderYSortRow(this.rapid,l)}}this.rapid.matrixStack.applyTransformAfter(e)}localToMap(t,e){const s=e.tileSet;if(e.shape===exports.TilemapShape.ISOMETRIC){let e=0,i=0;const r=s.height/2,n=s.width/2;let a=Math.floor(t.y/r);const o=a%2==0;let h=Math.floor(t.x/n);const l=h%2==0,u=t.x%n/n,c=t.y%r/r,d=c<u,p=c<1-u;return o||(a-=1),d&&!l&&o?a-=1:d||!l||o?p&&l&&o?(h-=2,a-=1):p||l||o||(a+=1):(a+=1,h-=2),e=h,i=a,e=Math.floor(h/2),new f(e,i)}return new f(Math.floor(t.x/s.width),Math.floor(t.y/s.height))}mapToLocal(t,e){const s=e.tileSet;if(e.shape===exports.TilemapShape.ISOMETRIC){let e=new f(t.x*s.width,t.y*s.height/2);return t.y%2!=0&&(e.x+=s.width/2),e}return new f(t.x*s.width,t.y*s.height)}}function z(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var j,X={exports:{}};var W=(j||(j=1,function(t){var e=Object.prototype.hasOwnProperty,s="~";function i(){}function r(t,e,s){this.fn=t,this.context=e,this.once=s||!1}function n(t,e,i,n,a){if("function"!=typeof i)throw new TypeError("The listener must be a function");var o=new r(i,n||t,a),h=s?s+e:e;return t._events[h]?t._events[h].fn?t._events[h]=[t._events[h],o]:t._events[h].push(o):(t._events[h]=o,t._eventsCount++),t}function a(t,e){0==--t._eventsCount?t._events=new i:delete t._events[e]}function o(){this._events=new i,this._eventsCount=0}Object.create&&(i.prototype=Object.create(null),(new i).__proto__||(s=!1)),o.prototype.eventNames=function(){var t,i,r=[];if(0===this._eventsCount)return r;for(i in t=this._events)e.call(t,i)&&r.push(s?i.slice(1):i);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(t)):r},o.prototype.listeners=function(t){var e=s?s+t:t,i=this._events[e];if(!i)return[];if(i.fn)return[i.fn];for(var r=0,n=i.length,a=new Array(n);r<n;r++)a[r]=i[r].fn;return a},o.prototype.listenerCount=function(t){var e=s?s+t:t,i=this._events[e];return i?i.fn?1:i.length:0},o.prototype.emit=function(t,e,i,r,n,a){var o=s?s+t:t;if(!this._events[o])return!1;var h,l,u=this._events[o],c=arguments.length;if(u.fn){switch(u.once&&this.removeListener(t,u.fn,void 0,!0),c){case 1:return u.fn.call(u.context),!0;case 2:return u.fn.call(u.context,e),!0;case 3:return u.fn.call(u.context,e,i),!0;case 4:return u.fn.call(u.context,e,i,r),!0;case 5:return u.fn.call(u.context,e,i,r,n),!0;case 6:return u.fn.call(u.context,e,i,r,n,a),!0}for(l=1,h=new Array(c-1);l<c;l++)h[l-1]=arguments[l];u.fn.apply(u.context,h)}else{var d,p=u.length;for(l=0;l<p;l++)switch(u[l].once&&this.removeListener(t,u[l].fn,void 0,!0),c){case 1:u[l].fn.call(u[l].context);break;case 2:u[l].fn.call(u[l].context,e);break;case 3:u[l].fn.call(u[l].context,e,i);break;case 4:u[l].fn.call(u[l].context,e,i,r);break;default:if(!h)for(d=1,h=new Array(c-1);d<c;d++)h[d-1]=arguments[d];u[l].fn.apply(u[l].context,h)}}return!0},o.prototype.on=function(t,e,s){return n(this,t,e,s,!1)},o.prototype.once=function(t,e,s){return n(this,t,e,s,!0)},o.prototype.removeListener=function(t,e,i,r){var n=s?s+t:t;if(!this._events[n])return this;if(!e)return a(this,n),this;var o=this._events[n];if(o.fn)o.fn!==e||r&&!o.once||i&&o.context!==i||a(this,n);else{for(var h=0,l=[],u=o.length;h<u;h++)(o[h].fn!==e||r&&!o[h].once||i&&o[h].context!==i)&&l.push(o[h]);l.length?this._events[n]=1===l.length?l[0]:l:a(this,n)}return this},o.prototype.removeAllListeners=function(t){var e;return t?(e=s?s+t:t,this._events[e]&&a(this,e)):(this._events=new i,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=s,o.EventEmitter=o,t.exports=o}(X)),X.exports),Y=z(W);class H extends Y{constructor(t,e,s,i,r){super(),this.elapsed=0,this.isRunning=!1,this.isFinished=!1,this.target=t,this.property=e,this.to=s,this.duration=i,this.easing=r}start(){const t=this.target[this.property];if("number"==typeof t)this.from=t;else{if("function"!=typeof t.clone)return console.error("Tween target property is not a 'number' or does not have a 'clone' method."),void(this.isFinished=!0);this.from=t.clone()}this.elapsed=0,this.isRunning=!0,this.isFinished=!1}update(t){if(!this.isRunning||this.isFinished)return;this.elapsed+=t;const e=Math.min(this.elapsed/this.duration,1),s=this.easing(e);let i;if("number"==typeof this.from&&"number"==typeof this.to)i=this.from+(this.to-this.from)*s;else{const t=this.from,e=this.to.subtract(t).multiply(s);i=t.add(e)}this.target[this.property]=i,e>=1&&(this.isFinished=!0,this.isRunning=!1,this.target[this.property]=this.to,this.emit("complete"))}}class K{}K.Linear=t=>t,K.EaseInQuad=t=>t*t,K.EaseOutQuad=t=>t*(2-t),K.EaseInOutQuad=t=>t<.5?2*t*t:(4-2*t)*t-1,K.EaseInCubic=t=>t*t*t,K.EaseOutCubic=t=>--t*t*t+1,K.EaseInOutCubic=t=>t<.5?4*t*t*t:(t-1)*(2*t-2)*(2*t-2)+1,K.EaseInQuart=t=>t*t*t*t,K.EaseOutQuart=t=>1- --t*t*t*t,K.EaseInOutQuart=t=>t<.5?8*t*t*t*t:1-8*--t*t*t*t;class $ extends Y{constructor(t,e=!1){super(),this.elapsedTime=0,this.isRunning=!1,this.isFinished=!1,this.duration=t,this.repeat=e}start(){this.isRunning=!0}stop(){this.isRunning=!1}update(t){this.isRunning&&!this.isFinished&&(this.elapsedTime+=t,this.elapsedTime>=this.duration&&(this.emit("timeout"),this.repeat?this.elapsedTime-=this.duration:(this.isFinished=!0,this.isRunning=!1)))}destroy(){this.isFinished=!0,this.isRunning=!1}}const q=!0;class Q{constructor(t,e){this.life=0,this.datas={},this.rapid=t,this.options=e,e.texture instanceof I?this.texture=e.texture:e.texture instanceof Array&&e.texture[0]instanceof Array?this.texture=m.pickWeight(e.texture):e.texture instanceof Array&&(this.texture=m.pick(e.texture)),this.maxLife=m.scalarOrRange(e.life,1),this.datas={speed:this.processAttribute(e.animation.speed,0),rotation:this.processAttribute(e.animation.rotation,0),scale:this.processAttribute(e.animation.scale,1),color:this.processAttribute(e.animation.color,p.White),velocity:this.processAttribute(e.animation.velocity,f.ZERO),acceleration:this.processAttribute(e.animation.acceleration,f.ZERO)},this.position=f.ZERO,this.initializePosition()}processAttribute(t,e){if(!t)return{value:e};if("object"==typeof(s=t)&&null!==s&&Object.getPrototypeOf(s)===Object.prototype){const s=m.scalarOrRange(t.start,e),i=m.scalarOrRange(t.end||s,e);return{delta:t.delta??this.getDelta(s,i,this.maxLife),value:s,damping:t.damping}}return this.processAttribute({start:t},e);var s}updateDamping(t){for(const e of Object.values(this.datas))if(e.damping){const s=e.value,i=Math.pow(e.damping,t);e.value="number"==typeof s?s*i:s.multiply(i)}}updateDelta(t){const e=this.datas;for(const e of Object.values(this.datas))if(e.delta){const s=e.value;"number"==typeof s?e.value+=t*e.delta:e.value=s.add(e.delta.multiply(t))}e.color.value.clamp();const s=f.fromAngle(e.rotation.value).multiply(e.speed.value*t);this.position=this.position.add(s).add(e.velocity.value.multiply(t)).add(e.acceleration.value.multiply(t))}getDelta(t,e,s){return"number"==typeof t&&"number"==typeof e?(e-t)/s:t instanceof f&&e instanceof f||t instanceof p&&e instanceof p?e.subtract(t).divide(s):t}update(t){return this.life+=t,!(this.life>=this.maxLife)&&(this.updateDamping(t),this.updateDelta(t),!0)}render(){this.rapid.renderSprite({...this.options,position:this.position,scale:this.datas.scale.value,rotation:this.datas.rotation.value,color:this.datas.color.value,texture:this.texture})}initializePosition(){switch(this.options.emitShape){case exports.ParticleShape.POINT:this.position=f.ZERO;break;case exports.ParticleShape.CIRCLE:const t=Math.random()*Math.PI*2,e=(this.options.emitRadius||0)*Math.sqrt(Math.random());this.position=new f(Math.cos(t)*e,Math.sin(t)*e);break;case exports.ParticleShape.RECT:this.position=new f((Math.random()-.5)*(this.options.emitRect?.width||0),(Math.random()-.5)*(this.options.emitRect?.height||0))}!this.options.localSpace&&this.options.position&&(this.position=this.position.add(this.options.position))}}class Z{constructor(t,e){this.particles=[],this.emitting=!1,this.emitTimer=0,this.emitRate=10,this.emitTime=0,this.emitTimeCounter=0,this.localSpace=q,this.position=f.ZERO,this.rapid=t,this.options=e,this.emitRate=void 0!==e.emitRate?e.emitRate:10,this.emitTime=void 0!==e.emitTime?e.emitTime:0,this.localSpace=void 0!==e.localSpace?e.localSpace:q,this.position=e.position||f.ZERO}getTransform(){return this.options}setEmitRate(t){this.emitRate=t}setEmitTime(t){this.emitTime=t}start(){this.emitting=!0,this.emitTimeCounter=0}stop(){this.emitting=!1}clear(){this.particles=[],this.emitTimeCounter=0}emit(t){const e=Math.min(t,(this.options.maxParticles||1/0)-this.particles.length);for(let t=0;t<e;t++){const t={...this.options},e=new Q(this.rapid,t);this.particles.unshift(e)}}update(t){if(this.emitting&&this.emitRate>0)if(this.emitTime>0){if(this.emitTimeCounter+=t,this.emitTimeCounter>=this.emitTime){const t=Math.floor(this.emitTimeCounter/this.emitTime);this.emit(this.emitRate*t),this.emitTimeCounter-=t*this.emitTime}}else{this.emitTimer+=t;const e=this.emitRate*t,s=Math.floor(e);s>0&&(this.emit(s),this.emitTimer-=s/this.emitRate);this.emitTimer*this.emitRate>=1&&(this.emit(1),this.emitTimer-=1/this.emitRate)}for(let e=this.particles.length-1;e>=0;e--)this.particles[e].update(t)||this.particles.splice(e,1)}render(){for(const t of this.particles)t.render()}getParticleCount(){return this.particles.length}isActive(){return this.emitting||this.particles.length>0}oneShot(){this.emit(this.emitRate)}}class V{constructor(t){this.projectionDirty=!0,this.matrixStack=new c,this.tileMap=new G(this),this.light=new x(this),this.defaultColor=new p(255,255,255,255),this.regions=new Map,this.currentMaskType=[],this.currentTransform=[],this.currentFBO=[],this.lastTime=0;const e=(t=>{const e={stencil:!0},s=t.getContext("webgl2",e)||t.getContext("webgl",e);if(!s)throw new Error("Unable to initialize WebGL. Your browser may not support it.");return s})(t.canvas);this.gl=e,this.canvas=t.canvas,this.texture=new D(this,t.antialias??!1),this.maxTextureUnits=e.getParameter(this.gl.MAX_TEXTURE_IMAGE_UNITS),this.width=t.width||this.canvas.width,this.height=t.height||this.canvas.height,this.scaleEnable=t.scaleEnable??!1,this.scaleRadio=t.scaleRadio||exports.ScaleRadio.KEEP,this.devicePixelRatio=t.devicePixelRatio??window.devicePixelRatio??1,this.backgroundColor=t.backgroundColor||new p(255,255,255,255),this.registerBuildInRegion(),this.initWebgl(e),this.updateDisplaySize(this.width,this.height),this.projectionDirty=!1,this.canvas.style.display="block"}updateDisplaySize(t,e){const s=this.width,i=this.height;let r,n,a,o;if(this.scaleEnable){const h=s/i,l=t/e;switch(this.scaleRadio){case exports.ScaleRadio.IGNORE:r=s,n=i,a=t*this.devicePixelRatio,o=e*this.devicePixelRatio;break;case exports.ScaleRadio.KEEP:let u,c;r=s,n=i,l>h?(c=e,u=c*h):(u=t,c=u/h),a=u*this.devicePixelRatio,o=c*this.devicePixelRatio;break;case exports.ScaleRadio.EXPAND:l>h?(n=i,r=i*l):(r=s,n=s/l),a=t*this.devicePixelRatio,o=e*this.devicePixelRatio;break;case exports.ScaleRadio.KEEP_W:r=s,n=s/l,a=t*this.devicePixelRatio,o=e*this.devicePixelRatio;break;case exports.ScaleRadio.KEEP_H:n=i,r=i*l,a=t*this.devicePixelRatio,o=e*this.devicePixelRatio;break;default:r=s,n=i,a=t*this.devicePixelRatio,o=e*this.devicePixelRatio}}else r=s,n=i,a=s*this.devicePixelRatio,o=i*this.devicePixelRatio;this.logicWidth=r,this.logicHeight=n,this.physicsWidth=a,this.physicsHeight=o,this.resizeSize(r,n,a,o,!0)}resizeSize(t,e,s,i,r=!1){this.updateProjection(0,t,e,0),this.gl.viewport(0,0,s,i),this.gl.scissor(0,0,s,i),r&&(this.canvas.width=s,this.canvas.height=i,this.canvas.style.width=s/this.devicePixelRatio+"px",this.canvas.style.height=i/this.devicePixelRatio+"px")}updateProjection(t,e,s,i){this.projection=this.createOrthMatrix(t,e,s,i),this.projectionDirty=!0}initWebgl(t){t.enable(t.BLEND),t.disable(t.DEPTH_TEST),t.blendFunc(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA),t.enable(t.STENCIL_TEST),t.enable(t.SCISSOR_TEST)}clearTextureUnit(){for(let t=0;t<this.maxTextureUnits;t++)this.gl.activeTexture(this.gl.TEXTURE0+t),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}registerBuildInRegion(){this.registerRegion("sprite",L),this.registerRegion("graphic",_)}registerRegion(t,e){this.regions.set(t,new e(this))}quitCurrentRegion(){this.currentRegion&&this.currentRegion.hasPendingContent()&&(this.currentRegion.render(),this.currentRegion.exitRegion())}setRegion(t,e){if(t!=this.currentRegionName||this.currentRegion&&this.currentRegion.isShaderChanged(e)){const s=this.regions.get(t);this.quitCurrentRegion(),this.currentRegion=s,this.currentRegionName=t,s.enterRegion(e)}}save(){this.matrixStack.pushMat()}restore(){this.matrixStack.popMat()}withTransform(t){this.save(),t(),this.restore()}startRender(t=!0){this.clear(),t&&this.matrixStack.clear(),this.matrixStack.pushIdentity(),this.currentRegion=void 0,this.currentRegionName=void 0;const e=performance.now(),s=this.lastTime?(e-this.lastTime)/1e3:0;return this.lastTime=e,s}endRender(){this.currentRegion?.render(),this.projectionDirty=!1}render(t){t(this.startRender()),this.endRender()}renderTileMapLayer(t,e){this.tileMap.renderLayer(t,e instanceof O?{tileSet:e}:e)}renderSprite(t){const e=t.texture;if(!e||!e.base)return;const{offsetX:s,offsetY:i}=this.startDraw(t,e.width,e.height);this.setRegion("sprite",t.shader),this.currentRegion.renderSprite(e.base.texture,e.width,e.height,e.clipX,e.clipY,e.clipW,e.clipH,s,i,(t.color||this.defaultColor).uint32,t.uniforms,t.flipX,t.flipY),this.afterDraw()}renderParticles(t){t.localSpace?(this.startDraw(t.getTransform()),t.render(),this.afterDraw()):t.render()}renderTexture(t){t.base&&this.renderSprite({texture:t})}renderLine(t){const e=t.closed?[...t.points,t.points[0]]:t.points,{vertices:s,uv:i}=y({...t,points:e});this.renderGraphic({...t,drawType:this.gl.TRIANGLES,points:s,uv:i})}renderGraphic(t){this.startGraphicDraw(t),t.points.forEach(((e,s)=>{const i=Array.isArray(t.color)?t.color[s]:t.color,r=t.uv?.[s];this.addGraphicVertex(e.x,e.y,r,i)})),this.endGraphicDraw()}startGraphicDraw(t){const{offsetX:e,offsetY:s}=this.startDraw(t);this.setRegion("graphic",t.shader);const i=this.currentRegion;i.startRender(e,s,t.texture,t.uniforms),t.drawType&&(i.drawType=t.drawType)}addGraphicVertex(t,e,s,i){this.currentRegion.addVertex(t,e,s?.x,s?.y,(i||this.defaultColor).uint32)}endGraphicDraw(){this.currentRegion.render(),this.afterDraw()}startDraw(t,e=0,s=0){return this.currentTransform.push(t),this.matrixStack.applyTransform(t,e,s)}afterDraw(){this.currentTransform.length>0&&this.matrixStack.applyTransformAfter(this.currentTransform.pop())}renderRect(t){const{width:e,height:s}=t,i=[new f(0,0),new f(e,0),new f(e,s),new f(0,s)];this.renderGraphic({...t,points:i,drawType:this.gl.TRIANGLE_FAN})}renderCircle(t){const e=t.segments||32,s=t.radius,i=t.color||this.defaultColor,r=[];for(let t=0;t<=e;t++){const i=t/e*Math.PI*2,n=Math.cos(i)*s,a=Math.sin(i)*s;r.push(new f(n,a))}this.renderGraphic({...t,points:r,color:i,drawType:this.gl.TRIANGLE_FAN})}clear(t){const e=this.gl,s=t||this.backgroundColor;e.clearColor(s.r/255,s.g/255,s.b/255,s.a/255),e.clear(e.COLOR_BUFFER_BIT),this.clearMask()}createOrthMatrix(t,e,s,i){return new Float32Array([2/(e-t),0,0,0,0,2/(i-s),0,0,0,0,-1,0,-(e+t)/(e-t),-(i+s)/(i-s),0,1])}drawMask(t=exports.MaskType.Include,e){this.startDrawMask(t),e(),this.endDrawMask()}startDrawMask(t=exports.MaskType.Include){const e=this.gl;this.currentMaskType.push(t),this.setMaskType(t,!0),e.stencilOp(e.KEEP,e.KEEP,e.REPLACE),e.colorMask(!1,!1,!1,!1)}endDrawMask(){const t=this.gl;this.quitCurrentRegion(),t.stencilOp(t.KEEP,t.KEEP,t.KEEP),t.colorMask(!0,!0,!0,!0),this.setMaskType(this.currentMaskType.pop()??exports.MaskType.Include,!1)}setMaskType(t,e=!1){const s=this.gl;if(this.quitCurrentRegion(),e)this.clearMask(),s.stencilFunc(s.ALWAYS,1,255);else switch(t){case exports.MaskType.Include:s.stencilFunc(s.EQUAL,1,255);break;case exports.MaskType.Exclude:s.stencilFunc(s.NOTEQUAL,1,255)}}clearMask(){const t=this.gl;this.quitCurrentRegion(),t.clearStencil(0),t.clear(t.STENCIL_BUFFER_BIT),t.stencilFunc(t.ALWAYS,1,255)}createCostumShader(t,e,s,i=0){return C.createCostumShader(this,t,e,s,i)}startFBO(t){this.quitCurrentRegion(),t.bind(),this.clearTextureUnit(),this.resizeSize(t.width,t.height,t.width,t.height),this.updateProjection(0,t.width,0,t.height),this.save(),this.matrixStack.identity(),this.currentFBO.push(t)}endFBO(){if(this.currentFBO.length>0){const t=this.currentFBO.pop();this.quitCurrentRegion(),t.unbind(),this.clearTextureUnit(),this.resizeSize(this.logicWidth,this.logicHeight,this.physicsWidth,this.physicsHeight),this.restore()}}drawToFBO(t,e){this.startFBO(t),e(),this.endFBO()}setBlendMode(t){switch(t){case exports.BlendMode.Additive:this.gl.blendFunc(this.gl.SRC_ALPHA,this.gl.ONE);break;case exports.BlendMode.Subtractive:this.gl.blendFunc(this.gl.ZERO,this.gl.ONE_MINUS_SRC_COLOR);break;case exports.BlendMode.Mix:this.gl.blendFunc(this.gl.SRC_ALPHA,this.gl.ONE_MINUS_SRC_ALPHA)}}drawLightShadowMask(t){this.startDrawMask(t.type||exports.MaskType.Exclude);this.light.createLightShadowMaskPolygon(t.occlusion,t.lightSource,t.baseProjectionLength).forEach((t=>{this.renderGraphic({points:t,color:p.Black})})),this.endDrawMask()}createParticleEmitter(t){return new Z(this,t)}cssToGameCoords(t,e){const s=t instanceof f?t:new f(t,e),i=this.canvas.getBoundingClientRect(),r=s.x/i.width,n=s.y/i.height,a=r*this.logicWidth,o=n*this.logicHeight;return new f(a,o)}gameToCssCoords(t,e){const s=t instanceof f?t:new f(t,e??0),i=this.canvas.getBoundingClientRect(),r=s.x/this.logicWidth,n=s.y/this.logicHeight,a=r*i.width,o=n*i.height;return new f(a,o)}}class J extends Y{constructor(t,e){super(),this.element=t,this.audioContext=e,this.source=null,this.gainNode=this.audioContext.createGain(),this.element.addEventListener("ended",this.handleEnded.bind(this))}handleEnded(){this.emit("ended")}async play(t=!1){try{this.element.loop=t,this.source=this.audioContext.createMediaElementSource(this.element),this.source.connect(this.gainNode),this.gainNode.connect(this.audioContext.destination),await this.element.play()}catch(t){console.error("Error playing audio:",t)}}pause(){this.element.pause()}stop(){this.element.pause(),this.element.currentTime=0,this.source&&(this.source.disconnect(),this.source=null)}setVolume(t){this.gainNode.gain.value=Math.max(0,Math.min(1,t))}destroy(){this.stop(),this.gainNode.disconnect(),this.element.removeEventListener("ended",this.handleEnded.bind(this)),this.removeAllListeners()}}class tt{constructor(){this.audioContext=new(window.AudioContext||window.webkitAudioContext)}destroy(){this.audioContext.close()}}class et extends Y{constructor(t){super(),this.totalAsset=0,this.loadedAssets=0,this.game=t,this.assets={json:{},audio:{},images:{}}}loadJson(t,e){this.totalAsset++,fetch(e).then((t=>t.json())).then((e=>{this.assets.json[t]=e,this.assetLoaded()})).catch((s=>this.handleError(t,e,s)))}loadAudio(t,e){this.totalAsset++;const s=new Audio;s.src=e,s.oncanplaythrough=()=>{this.assets.audio[t]=new J(s,this.game.audio.audioContext),this.assetLoaded(),s.oncanplaythrough=null},s.onerror=()=>this.handleError(t,e,"Audio load error")}loadImage(t,e){this.totalAsset++;const s=new Image;s.src=e,s.onload=()=>{this.assets.images[t]=this.game.render.texture.textureFromSource(s),this.assetLoaded()},s.onerror=()=>this.handleError(t,e,"Image load error")}loadAssets(t){t.forEach((t=>{switch(t.type){case"json":this.loadJson(t.name,t.url);break;case"audio":this.loadAudio(t.name,t.url);break;case"image":this.loadImage(t.name,t.url);break;default:console.warn(`Unknown asset type: ${t.type}`)}}))}assetLoaded(){this.loadedAssets++;const t=this.loadedAssets/this.totalAsset;this.emit("progress",t,this.loadedAssets,this.totalAsset),this.loadedAssets===this.totalAsset&&this.emit("complete",this.assets)}handleError(t,e,s){this.emit("error",{name:t,url:e,error:s}),console.error(`Failed to load asset ${t} from ${e}:`,s)}get(t,e){return this.assets[t]?.[e]}getJSON(t){return this.assets.json[t]}getAudio(t){return this.assets.audio[t]}getTexture(t){return this.assets.images[t]}}class st{constructor(t){this.mousePosition=f.ZERO,this.keysDown=new Set,this.keysDownLastFrame=new Set,this.buttonsDown=new Set,this.buttonsDownLastFrame=new Set,this.rapid=t,this.canvas=t.canvas,this.attachEventListeners()}attachEventListeners(){const t=this.canvas.getBoundingClientRect();this.canvas.addEventListener("mousemove",this.handleMouseMove=e=>{this.mousePosition=this.rapid.cssToGameCoords(e.clientX-t.left,e.clientY-t.top)}),window.addEventListener("keydown",this.handleKeyDown=t=>{this.keysDown.add(t.code)}),window.addEventListener("keyup",this.handleKeyUp=t=>{this.keysDown.delete(t.code)}),this.canvas.addEventListener("mousedown",this.handleMouseDown=t=>{this.buttonsDown.add(t.button)}),this.canvas.addEventListener("mouseup",this.handleMouseUp=t=>{this.buttonsDown.delete(t.button)})}updateNextFrame(){this.keysDownLastFrame=new Set(this.keysDown),this.buttonsDownLastFrame=new Set(this.buttonsDown)}isKeyDown(t){return this.keysDown.has(t)}isKeyUp(t){return!this.keysDown.has(t)}wasKeyPressed(t){return this.keysDown.has(t)&&!this.keysDownLastFrame.has(t)}wasKeyReleased(t){return!this.keysDown.has(t)&&this.keysDownLastFrame.has(t)}isButtonDown(t){return this.buttonsDown.has(t)}isButtonUp(t){return!this.buttonsDown.has(t)}wasButtonPressed(t){return this.buttonsDown.has(t)&&!this.buttonsDownLastFrame.has(t)}wasButtonReleased(t){return!this.buttonsDown.has(t)&&this.buttonsDownLastFrame.has(t)}getMouseLocal(t){return t.transform.globalToLocal(this.mousePosition)}destroy(){this.canvas.removeEventListener("mousemove",this.handleMouseMove),window.removeEventListener("keydown",this.handleKeyDown),window.removeEventListener("keyup",this.handleKeyUp),this.canvas.removeEventListener("mousedown",this.handleMouseDown),this.canvas.removeEventListener("mouseup",this.handleMouseUp),this.keysDown.clear(),this.keysDownLastFrame.clear(),this.buttonsDown.clear(),this.buttonsDownLastFrame.clear()}}class it{get x(){return this.position.x}get y(){return this.position.x}set x(t){this.x=t}set y(t){this.y=t}constructor(t,e={}){this.parent=null,this.globalZindex=0,this.localZindex=0,this.transform=new c,this.children=[],this.transform.pushIdentity(),this.game=t,this.rapid=t.render,this.tags=e.tags??[],e.position?this.position=e.position:this.position=new f(e.x??0,e.y??0),"number"==typeof e.scale?this.scale=new f(e.scale,e.scale):e.scale?this.scale=e.scale:this.scale=new f(1,1),this.rotation=e.rotation??0}getParentTransform(){return this.parent?this.parent.transform:this.rapid.matrixStack}update(t){this.onUpdate(t);for(const e of this.children)e.update(t)}onUpdate(t){}collectRenderables(t){this.onRender!==it.prototype.onRender&&t.push(this);for(const e of this.children)e.collectRenderables(t)}beforOnRender(){const t=this.transform;this.rapid.matrixStack.setTransform(t.getTransform())}onRender(t){}updateTransform(t=!1){t&&this.parent&&this.parent.updateTransform(t);const e=this.transform,s=this.getParentTransform();e.setTransform(s.getTransform()),e.translate(this.position),e.rotate(this.rotation),e.scale(this.scale)}addChild(t){t.parent&&t.parent.removeChild(t),t.parent=this,this.children.push(t)}removeChild(t){const e=this.children.indexOf(t);e>-1&&(t.parent=null,this.children.splice(e,1))}findDescendant(t,e=!0){const s=[];for(const i of this.children){if(t(i)){if(e)return i;s.push(i)}const r=i.findDescendant(t,e);if(e){if(r)return r}else s.push(...r)}return e?null:s}findDescendantByTag(t,e=!1){return this.findDescendant((e=>0!==t.length&&t.every((t=>e.tags.includes(t)))),e)}dispose(){this.postDispose(),this.parent&&this.parent.removeChild(this)}postDispose(){this.children.forEach((t=>{t.dispose()}))}}class rt extends it{constructor(t,e){super(t,e),this.error=new f(rt.DEFAULT_ERROR),this.data=[[]],this.ySortCallback=[],e.error?"number"==typeof e.error?this.error=new f(e.error):this.error=e.error:this.error=new f(e.errorX??rt.DEFAULT_ERROR,e.errorY??rt.DEFAULT_ERROR),this.tileSet=e.tileSet,this.shape=e.shape??exports.TilemapShape.SQUARE,this.eachTile=e.eachTile}collectRenderables(t){this.onRender!==it.prototype.onRender&&t.push(this)}setTile(t,e,s){return e<0||e>=this.data.length||t<0||t>=this.data[e].length?(console.warn(`Tilemap.setTile: Coordinates (${t}, ${e}) are out of bounds.`),!1):(this.data[e][t]=s,!0)}getTile(t,e){if(!(e<0||e>=this.data.length||t<0||t>=this.data[e].length))return this.data[e][t]}removeTile(t,e){return this.setTile(t,e,rt.EMPTY_TILE)}fill(t,e,s,i,r){const n=e+i,a=s+r;for(let i=s;i<a;i++)for(let s=e;s<n;s++)this.setTile(s,i,t)}setData(t){this.data=t}localToMap(t){this.rapid.tileMap.localToMap(t,{tileSet:this.tileSet})}mapToLocal(t){this.rapid.tileMap.mapToLocal(t,{tileSet:this.tileSet})}onRender(t){const e=[...this.ySortCallback];this.children.forEach((t=>{e.push({ySort:t.localZindex,entity:t})})),t.renderTileMapLayer(this.data,{error:this.error,tileSet:this.tileSet,eachTile:this.eachTile,ySortCallback:e})}}rt.DEFAULT_ERROR=0,rt.EMPTY_TILE=-1;exports.BaseTexture=N,exports.Camera=class extends it{updateTransform(){const t=this.transform;t.identity();const e=new f(-this.rapid.logicWidth,-this.rapid.logicHeight).divide(2);t.translate(e),t.translate(this.position),t.rotate(this.rotation),t.scale(this.scale),t.setTransform(t.getInverse())}},exports.Color=p,exports.DynamicArrayBuffer=l,exports.Entity=it,exports.FrameBufferObject=B,exports.GLShader=C,exports.Game=class{constructor(t){this.mainScene=null,this.isRunning=!1,this.lastTime=0,this.tweens=[],this.timers=[],this.renderQueue=[],this.render=new V(t),this.input=new st(this.render),this.asset=new et(this),this.audio=new tt,this.texture=this.render.texture}switchScene(t){this.mainScene&&this.mainScene.dispose(),this.mainScene=t,t.create()}start(){this.isRunning||(this.isRunning=!0,this.lastTime=performance.now(),this.gameLoop())}stop(){this.isRunning=!1}addEntityRenderQueue(t){this.renderQueue.push(t)}gameLoop(){if(!this.isRunning)return;const t=performance.now(),e=(t-this.lastTime)/1e3;this.lastTime=t,this.render.startRender(),this.mainScene&&(this.mainScene.update(e),this.mainScene.collectRenderables(this.renderQueue),this.renderQueue.sort(((t,e)=>{const s=t.parent&&t.parent===e.parent,i=t.globalZindex-e.globalZindex;return 0===i||s?s?t.localZindex-e.localZindex:0:i})),this.renderQueue.forEach((t=>{t.beforOnRender(),t.onRender(this.render)})),this.renderQueue.length=0),this.render.endRender(),this.input.updateNextFrame(),this.updateTweens(e),this.updateTimers(e),requestAnimationFrame(this.gameLoop.bind(this))}destroy(){this.audio.destroy(),this.input.destroy()}createTimer(t,e=!1){const s=new $(t,e);return this.timers.push(s),s.start(),s}updateTimers(t){for(const e of this.timers)e.update(t);this.timers=this.timers.filter((t=>!t.isFinished))}createTween(t,e,s,i,r=K.Linear){const n=new H(t,e,s,i,r);return this.tweens.push(n),n.start(),n}updateTweens(t){for(const e of this.tweens)e.update(t);this.tweens=this.tweens.filter((t=>!t.isFinished))}},exports.InputManager=st,exports.MathUtils=class{static deg2rad(t){return t*(Math.PI/180)}static rad2deg(t){return t/(Math.PI/180)}static normalizeDegrees(t){return(t%360+360)%360}},exports.MatrixStack=c,exports.ParticleEmitter=Z,exports.Random=m,exports.Rapid=V,exports.SCALEFACTOR=2,exports.Scene=class extends it{create(){}},exports.Text=k,exports.Texture=I,exports.TextureCache=D,exports.TileMapRender=G,exports.TileSet=O,exports.Tilemap=rt,exports.Uniform=class{constructor(t){this.isDirty=!1,this.data=t}setUniform(t,e){this.data[t]!=e&&(this.isDirty=!0),this.data[t]=e}clearDirty(){this.isDirty=!1}getUnifromNames(){return Object.keys(this.data)}bind(t,e,s,i){if(!s)return;const r=this.data[e];if("number"==typeof r)t.uniform1f(s,r);else if(Array.isArray(r))switch(r.length){case 1:Number.isInteger(r[0])?t.uniform1i(s,r[0]):t.uniform1f(s,r[0]);break;case 2:Number.isInteger(r[0])?t.uniform2iv(s,r):t.uniform2fv(s,r);break;case 3:Number.isInteger(r[0])?t.uniform3iv(s,r):t.uniform3fv(s,r);break;case 4:Number.isInteger(r[0])?t.uniform4iv(s,r):t.uniform4fv(s,r);break;case 9:t.uniformMatrix3fv(s,!1,r);break;case 16:t.uniformMatrix4fv(s,!1,r);break;default:console.error(`Unsupported uniform array length for ${e}:`,r.length)}else if("boolean"==typeof r)t.uniform1i(s,r?1:0);else if(r.base?.texture){const e=i.useTexture(r.base.texture)[0];t.uniform1i(s,e)}else console.error(`Unsupported uniform type for ${e}:`,typeof r)}},exports.Vec2=f,exports.WebglBufferArray=u,exports.WebglElementBufferArray=d,exports.graphicAttributes=M,exports.spriteAttributes=A;
|