littlejsengine 1.18.29 → 1.19.3
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/FAQ.md +5 -0
- package/README.md +207 -199
- package/dist/littlejs.d.ts +2099 -48
- package/dist/littlejs.esm.js +16251 -10317
- package/dist/littlejs.esm.min.js +13 -1
- package/dist/littlejs.js +15747 -9890
- package/dist/littlejs.min.js +13 -1
- package/dist/littlejs.release.js +15719 -9869
- package/package.json +1 -1
- package/plugins/audioEffects.js +371 -0
- package/plugins/lightSystem.js +5 -3
- package/plugins/math3d.js +870 -0
- package/plugins/medalSystem.js +280 -280
- package/plugins/pluginExport.js +181 -115
- package/plugins/postProcess.js +241 -166
- package/plugins/render3d.js +4006 -0
- package/plugins/textureSheet.js +458 -458
- package/plugins/threejs.js +6 -1
- package/plugins/tweenSystem.js +528 -526
- package/plugins/zzfxm.js +159 -166
- package/src/engine.js +172 -137
- package/src/engineAudio.js +918 -777
- package/src/engineBuild.mjs +3 -0
- package/src/engineDebug.js +15 -8
- package/src/engineDraw.js +1672 -1510
- package/src/engineExport.js +407 -396
- package/src/engineInput.js +1 -1
- package/src/engineLogo.js +4 -3
- package/src/engineMath.js +69 -0
- package/src/engineObject.js +560 -551
- package/src/engineSettings.js +759 -725
- package/src/engineTileLayer.js +3 -3
- package/src/engineUtilities.js +13 -0
- package/src/engineWebGL.js +1005 -941
package/dist/littlejs.esm.min.js
CHANGED
|
@@ -1,4 +1,16 @@
|
|
|
1
1
|
// LittleJS Engine - MIT License - Copyright 2021 Frank Force
|
|
2
2
|
// https://github.com/KilledByAPixel/LittleJS
|
|
3
3
|
|
|
4
|
-
"use strict";const engineName="LittleJS";const engineVersion="1.18.29";const frameRate=60;const timeDelta=1/frameRate;let engineObjects=[];let engineObjectsCollide=[];let frame=0;let time=0;let timeReal=0;let paused=false;function getPaused(){return paused}function setPaused(isPaused=true){paused=isPaused}let frameTimeLastMS=0,frameTimeBufferMS=0,averageFPS=0;let engineUpdateInternal;let showEngineVersion=true;const pluginList=[];class EnginePlugin{constructor(update,render,glContextLost,glContextRestored){this.update=update;this.render=render;this.glContextLost=glContextLost;this.glContextRestored=glContextRestored}}function engineAddPlugin(update,render,glContextLost,glContextRestored){ASSERT(!pluginList.find(p=>p.update===update&&p.render===render&&p.glContextLost===glContextLost&&p.glContextRestored===glContextRestored));const plugin=new EnginePlugin(update,render,glContextLost,glContextRestored);pluginList.push(plugin)}async function engineInit(gameInit,gameUpdate,gameUpdatePost,gameRender,gameRenderPost,imageSources=[],rootElement){showEngineVersion&&console.log(`${engineName} Engine v${engineVersion}`);ASSERT(!mainContext,"engine already initialized");if(mainContext)return;ASSERT(isArray(imageSources),"pass in images as array");if(!document.body)document.documentElement.appendChild(document.createElement("body"));rootElement||=document.body;gameInit||=()=>{};gameUpdate||=()=>{};gameUpdatePost||=()=>{};gameRender||=()=>{};gameRenderPost||=()=>{};function enginePreRender(){mainCanvasSize=vec2(mainCanvas.width,mainCanvas.height);mainContext.imageSmoothingEnabled=!tilesPixelated;glPreRender()}function engineUpdate(frameTimeMS=0){let frameTimeDeltaMS=frameTimeMS-frameTimeLastMS;if(!frameTimeLastMS)frameTimeDeltaMS=0;frameTimeLastMS=frameTimeMS;if(debug||debugWatermark)averageFPS=lerp(averageFPS,1e3/(frameTimeDeltaMS||1),.05);const debugSpeedUp=debug&&keyIsDown("Equal");const debugSpeedDown=debug&&keyIsDown("Minus");const debugScale=debugSpeedUp?10:debugSpeedDown?.1:1;timeReal+=frameTimeDeltaMS*debugScale/1e3;const combinedScale=timeScale*debugScale;frameTimeDeltaMS*=combinedScale;frameTimeBufferMS+=paused?0:frameTimeDeltaMS;if(combinedScale<=1)frameTimeBufferMS=min(frameTimeBufferMS,50);let wasUpdated=false;if(paused){wasUpdated=true;updateCanvas();inputUpdate();pluginList.forEach(plugin=>plugin.update?.());for(const o of engineObjects)o.parent||o.updateTransforms();debugUpdate();gameUpdatePost();inputUpdatePost();if(debugVideoCaptureIsActive())renderFrame()}else{let deltaSmooth=0;if(frameTimeBufferMS<0&&frameTimeBufferMS>-9){deltaSmooth=frameTimeBufferMS;frameTimeBufferMS=0}for(;frameTimeBufferMS>=0;frameTimeBufferMS-=1e3/frameRate){time=frame++/frameRate;wasUpdated=true;updateCanvas();inputUpdate();gameUpdate();pluginList.forEach(plugin=>plugin.update?.());engineObjectsUpdate();debugUpdate();gameUpdatePost();inputUpdatePost();if(debugVideoCaptureIsActive())renderFrame()}frameTimeBufferMS+=deltaSmooth}if(!debugVideoCaptureIsActive())renderFrame();if(!engineManualStep)requestAnimationFrame(engineUpdate);function renderFrame(){if(headlessMode)return;if(!wasUpdated)updateCanvas();enginePreRender();gameRender();engineObjects.sort((a,b)=>a.renderOrder-b.renderOrder);for(const o of engineObjects)o.destroyed||o.render();gameRenderPost();pluginList.forEach(plugin=>plugin.render?.());inputRender();debugRender();glFlush();debugRenderPost();drawCount=0;primitiveCount=0}}engineUpdateInternal=engineUpdate;function updateCanvas(){if(headlessMode)return;if(canvasFixedSize.x){mainCanvasSize=canvasFixedSize.copy();const innerAspect=innerWidth/innerHeight;const fixedAspect=canvasFixedSize.x/canvasFixedSize.y;const w=innerAspect<fixedAspect?"100%":"";const h=innerAspect<fixedAspect?"":"100%";mainCanvas.style.width=w;mainCanvas.style.height=h;if(glCanvas){glCanvas.style.width=w;glCanvas.style.height=h}}else{const dpr=canvasPixelRatio??(devicePixelRatio||1);const viewWidth=innerWidth*dpr|0;const viewHeight=innerHeight*dpr|0;mainCanvasSize.x=min(viewWidth,canvasMaxSize.x);mainCanvasSize.y=min(viewHeight,canvasMaxSize.y);const innerAspect=viewWidth/viewHeight;ASSERT(canvasMinAspect<=canvasMaxAspect);if(canvasMaxAspect&&innerAspect>canvasMaxAspect){const w=mainCanvasSize.y*canvasMaxAspect|0;mainCanvasSize.x=min(w,canvasMaxSize.x)}else if(innerAspect<canvasMinAspect){const h=mainCanvasSize.x/canvasMinAspect|0;mainCanvasSize.y=min(h,canvasMaxSize.y)}const cssW=(mainCanvasSize.x/dpr|0)+"px";const cssH=(mainCanvasSize.y/dpr|0)+"px";mainCanvas.style.width=cssW;mainCanvas.style.height=cssH;if(glCanvas){glCanvas.style.width=cssW;glCanvas.style.height=cssH}}mainCanvas.width=mainCanvasSize.x;mainCanvas.height=mainCanvasSize.y;if(canvasClearColor.a>0&&!glEnable){mainContext.fillStyle=canvasClearColor.toString();mainContext.fillRect(0,0,mainCanvasSize.x,mainCanvasSize.y);mainContext.fillStyle=BLACK.toString()}mainContext.lineJoin="round";mainContext.lineCap="round"}if(headlessMode)return startEngine();glInit(rootElement);const styleRoot="margin:0;"+"overflow:hidden;"+"background:#000;"+"user-select:none;"+"-webkit-user-select:none;"+"touch-action:none;"+"-webkit-touch-callout:none";rootElement.style.cssText=styleRoot;mainCanvas=rootElement.appendChild(document.createElement("canvas"));drawContext=mainContext=mainCanvas.getContext("2d");inputInit();audioInit();debugInit();const styleCanvas="position:absolute;"+"top:50%;left:50%;transform:translate(-50%,-50%)";mainCanvas.style.cssText=styleCanvas;if(glCanvas)glCanvas.style.cssText=styleCanvas;setCanvasPixelated(canvasPixelated);updateCanvas();glPreRender();workCanvas=new OffscreenCanvas(64,64);workContext=workCanvas.getContext("2d");workReadCanvas=new OffscreenCanvas(64,64);workReadContext=workReadCanvas.getContext("2d",{willReadFrequently:true});const promises=imageSources.map((src,i)=>loadTexture(i,src));if(!imageSources.length)promises.push(loadTexture(0));promises.push(imageFontInit());if(showSplashScreen){promises.push(new Promise(resolve=>{let t=0;updateSplash();function updateSplash(){inputClear();drawEngineLogo(t+=.01);t>1?resolve():setTimeout(updateSplash,16)}}))}await Promise.all(promises);return startEngine();async function startEngine(){await gameInit();engineManualStep||engineUpdate()}}const engineStepMaxFrames=36e3;function engineStep(frames=1){ASSERT(engineManualStep,"engineStep requires setEngineManualStep(true) before engineInit");ASSERT(engineUpdateInternal,"engineStep requires engineInit to complete");if(!engineManualStep||!engineUpdateInternal)return;ASSERT(Number.isInteger(frames)&&frames>=0&&frames<=engineStepMaxFrames,"engineStep requires a whole frame count from 0 to "+engineStepMaxFrames);frames=min(frames,engineStepMaxFrames);for(let i=frames;i>0;--i)engineUpdateInternal(frameTimeLastMS+1e3/frameRate)}function engineObjectsUpdate(){engineObjectsCollide=engineObjects.filter(o=>o.collideSolidObjects);for(const o of engineObjects)if(!o.parent&&!o.destroyed)o.updatePhysics();function updateChildObject(o){if(o.destroyed)return;o.update();for(const child of o.children)updateChildObject(child)}for(const o of engineObjects){if(o.parent||o.destroyed)continue;o.update();for(const child of o.children)updateChildObject(child);o.updateTransforms()}engineObjects=engineObjects.filter(o=>!o.destroyed)}function engineObjectsDestroy(immediate=true){for(const o of engineObjects)o.parent||o.destroy(immediate);engineObjects=engineObjects.filter(o=>!o.destroyed)}function engineObjectsCollect(pos,size,objects=engineObjects){const collectedObjects=[];if(!pos){for(const o of objects)collectedObjects.push(o)}else if(size instanceof Vector2){for(const o of objects)o.isOverlapping(pos,size)&&collectedObjects.push(o)}else{const sizeSquared=size*size;for(const o of objects)pos.distanceSquared(o.pos)<sizeSquared&&collectedObjects.push(o)}return collectedObjects}function engineObjectsCallback(pos,size,callbackFunction,objects=engineObjects){engineObjectsCollect(pos,size,objects).forEach(o=>callbackFunction(o))}function engineObjectsRaycast(start,end,objects=engineObjects){const hitObjects=[];for(const o of objects){if(o.collideRaycast&&isIntersecting(start,end,o.pos,o.size)){debugRaycast&&debugRect(o.pos,o.size,"#f00");hitObjects.push(o)}}debugRaycast&&debugLine(start,end,hitObjects.length?"#f00":"#00f",.02);return hitObjects}let debugWatermark=0;let debugKey="";const debug=0;const debugOverlay=0;const debugPhysics=0;const debugParticles=0;const debugRaycast=0;const debugGamepads=0;const debugSound=0;const debugPointSize=.5;function ASSERT(){}function LOG(){}function debugInit(){}function debugUpdate(){}function debugRender(){}function debugRenderPost(){}function debugRect(){}function debugPoly(){}function debugCircle(){}function debugPoint(){}function debugLine(){}function debugOverlap(){}function debugText(){}function debugClear(){}function debugScreenshot(){}function debugShowErrors(){}function debugVideoCaptureIsActive(){return false}function debugVideoCaptureStart(){}function debugVideoCaptureStop(){}function debugVideoCaptureUpdate(){}function debugProtectConstant(o){return o}const PI=Math.PI;const abs=Math.abs;const floor=Math.floor;const ceil=Math.ceil;const round=Math.round;const min=Math.min;const max=Math.max;const sign=x=>Math.sign(x);const hypot=(...values)=>Math.hypot(...values);const log2=x=>Math.log2(x);const sin=Math.sin;const cos=Math.cos;const tan=Math.tan;const atan2=Math.atan2;function mod(dividend,divisor=1){return(dividend%divisor+divisor)%divisor}function clamp(value,min=0,max=1){return value<min?min:value>max?max:value}function percent(value,valueA,valueB){return(valueB-=valueA)?clamp((value-valueA)/valueB):0}function lerp(valueA,valueB,percent){return valueA+clamp(percent)*(valueB-valueA)}function percentLerp(value,percentA,percentB,lerpA,lerpB){return lerp(lerpA,lerpB,percent(value,percentA,percentB))}function distanceWrap(valueA,valueB,wrapSize=1){ASSERT(wrapSize>0,"distanceWrap wrapSize must be > 0");const d=(valueA-valueB)%wrapSize;return d*2%wrapSize-d}function lerpWrap(valueA,valueB,percent,wrapSize=1){return valueA+clamp(percent)*distanceWrap(valueB,valueA,wrapSize)}function distanceAngle(angleA,angleB){return distanceWrap(angleA,angleB,2*PI)}function lerpAngle(angleA,angleB,percent){return lerpWrap(angleA,angleB,percent,2*PI)}function smoothStep(percent){return percent*percent*(3-2*percent)}function isPowerOfTwo(value){return value>0&&!(value&value-1)}function nearestPowerOfTwo(value){return 2**ceil(log2(value))}function isOverlapping(posA,sizeA,posB,sizeB=vec2()){const dx=(posA.x-posB.x)*2;const dy=(posA.y-posB.y)*2;const sx=sizeA.x+sizeB.x;const sy=sizeA.y+sizeB.y;return abs(dx)<sx&&abs(dy)<sy}function isIntersecting(start,end,pos,size){const boxMin=pos.subtract(size.scale(.5));const boxMax=boxMin.add(size);const delta=end.subtract(start);const a=start.subtract(boxMin);const b=start.subtract(boxMax);const p=[-delta.x,delta.x,-delta.y,delta.y];const q=[a.x,-b.x,a.y,-b.y];let tMin=0,tMax=1;for(let i=4;i--;){if(p[i]){const t=q[i]/p[i];if(p[i]<0){if(t>tMax)return false;tMin=max(t,tMin)}else{if(t<tMin)return false;tMax=min(t,tMax)}}else if(q[i]<0)return false}return true}function oscillate(frequency=1,amplitude=1,t=time,offset=0,type=0){const phase=mod(offset+t*frequency,1);let value;if(type===1)value=2*abs(2*phase-1)-1;else if(type===2)value=phase<.5?-1:1;else if(type===3)value=2*phase-1;else value=-cos(phase*2*PI);return amplitude/2*(value+1)}function isNumber(n){return typeof n==="number"&&!isNaN(n)}function isStringLike(s){return s!=null&&typeof s?.toString()==="string"}function isArray(a){return Array.isArray(a)}function lineTest(posStart,posEnd,testFunction,normal){ASSERT(isVector2(posStart),"posStart must be a vec2");ASSERT(isVector2(posEnd),"posEnd must be a vec2");ASSERT(typeof testFunction==="function","testFunction must be a function");ASSERT(!normal||isVector2(normal),"normal must be a vec2");const dx=posEnd.x-posStart.x;const dy=posEnd.y-posStart.y;const totalLength=(dx*dx+dy*dy)**.5;if(!totalLength)return;const pos=posStart.floor();const dirX=dx/totalLength;const dirY=dy/totalLength;const stepX=sign(dirX);const stepY=sign(dirY);const tDeltaX=dirX?abs(1/dirX):Infinity;const tDeltaY=dirY?abs(1/dirY):Infinity;const nextGridX=stepX>0?pos.x+1:pos.x;const nextGridY=stepY>0?pos.y+1:pos.y;const tMaxX=dirX?(nextGridX-posStart.x)/dirX:Infinity;const tMaxY=dirY?(nextGridY-posStart.y)/dirY:Infinity;let t=0,tX=tMaxX,tY=tMaxY,wasX=tDeltaX<tDeltaY;while(t<totalLength){if(testFunction(pos)){const hitPos=vec2(posStart.x+dirX*t,posStart.y+dirY*t);const e=1e-9;const hitPosFloor=hitPos.floor();if(hitPosFloor.x<pos.x)hitPos.x=pos.x;else if(hitPosFloor.x>pos.x)hitPos.x=pos.x+1-e;if(hitPosFloor.y<pos.y)hitPos.y=pos.y;else if(hitPosFloor.y>pos.y)hitPos.y=pos.y+1-e;if(normal)wasX?normal.set(-stepX,0):normal.set(0,-stepY);return hitPos}if(wasX=tX<tY){pos.x+=stepX;t=tX;tX+=tDeltaX}else{pos.y+=stepY;t=tY;tY+=tDeltaY}}}function rand(valueA=1,valueB=0){return valueB+Math.random()*(valueA-valueB)}function randInt(valueA,valueB=0){return floor(rand(valueA,valueB))}function randBool(chance=.5){return rand()<chance}function randSign(){return randInt(2)*2-1}function randVec2(length=1){return(new Vector2).setAngle(rand(2*PI),length)}function randInCircle(radius=1,minRadius=0){if(radius<=0)return new Vector2;const ratio=clamp(minRadius/radius);return randVec2(radius*rand(ratio*ratio,1)**.5)}function randColor(colorA=new Color,colorB=new Color(0,0,0,1),linear=false){return linear?colorA.lerp(colorB,rand()):new Color(rand(colorA.r,colorB.r),rand(colorA.g,colorB.g),rand(colorA.b,colorB.b),rand(colorA.a,colorB.a))}class RandomGenerator{constructor(seed=123456789){ASSERT(seed!==0,"RandomGenerator seed must be non-zero (xorshift is fixed at 0)");this.seed=seed}float(valueA=1,valueB=0){this.seed^=this.seed<<13;this.seed^=this.seed>>>17;this.seed^=this.seed<<5;return valueB+(valueA-valueB)*((this.seed>>>0)/2**32)}int(valueA,valueB=0){return floor(this.float(valueA,valueB))}bool(chance=.5){return this.float()<chance}sign(){return this.float()>.5?1:-1}floatSign(valueA=1,valueB=0){const lo=min(valueA,valueB);const hi=max(valueA,valueB);const d=hi-lo;const e=this.float(d*2);return e<d?lo+e:d-lo-e}angle(){return this.float(-PI,PI)}vec2(valueA=1,valueB=0){return vec2(this.float(valueA,valueB),this.float(valueA,valueB))}randColor(colorA=new Color,colorB=new Color(0,0,0,1),linear=false){return linear?colorA.lerp(colorB,this.float()):new Color(this.float(colorA.r,colorB.r),this.float(colorA.g,colorB.g),this.float(colorA.b,colorB.b),this.float(colorA.a,colorB.a))}mutateColor(color,amount=.05,alphaAmount=0){ASSERT_NUMBER_VALID(amount);ASSERT_NUMBER_VALID(alphaAmount);return new Color(color.r+this.float(amount,-amount),color.g+this.float(amount,-amount),color.b+this.float(amount,-amount),color.a+this.float(alphaAmount,-alphaAmount)).clamp()}}function vec2(x=0,y){return new Vector2(x,y??x)}function isVector2(v){return v instanceof Vector2&&v.isValid()}function ASSERT_VECTOR2_VALID(v){ASSERT(isVector2(v),"Vector2 is invalid.",v)}function ASSERT_NUMBER_VALID(n){ASSERT(isNumber(n),"Number is invalid.",n)}function ASSERT_VECTOR2_NORMAL(v){ASSERT_VECTOR2_VALID(v);ASSERT(abs(v.lengthSquared()-1)<.01,"Vector2 is not normal.",v)}class Vector2{constructor(x=0,y=0){this.x=x;this.y=y;ASSERT(this.isValid(),"Constructed Vector2 is invalid.",this)}set(x=0,y=0){this.x=x;this.y=y;ASSERT_VECTOR2_VALID(this);return this}setFrom(v){return this.set(v.x,v.y)}copy(){return new Vector2(this.x,this.y)}add(v){return new Vector2(this.x+v.x,this.y+v.y)}subtract(v){return new Vector2(this.x-v.x,this.y-v.y)}multiply(v){return new Vector2(this.x*v.x,this.y*v.y)}divide(v){return new Vector2(this.x/v.x,this.y/v.y)}scale(s){return new Vector2(this.x*s,this.y*s)}length(){return this.lengthSquared()**.5}lengthSquared(){return this.x**2+this.y**2}distance(v){return this.distanceSquared(v)**.5}distanceSquared(v){return(this.x-v.x)**2+(this.y-v.y)**2}normalize(length=1){const l=this.length();return l?this.scale(length/l):new Vector2(0,length)}clampLength(length=1){const l=this.length();return l>length?this.scale(length/l):this.copy()}dot(v){return this.x*v.x+this.y*v.y}cross(v){return this.x*v.y-this.y*v.x}reflect(normal,restitution=1){return this.subtract(normal.scale((1+restitution)*this.dot(normal)))}angle(){return atan2(this.x,this.y)}setAngle(angle=0,length=1){ASSERT_NUMBER_VALID(angle);ASSERT_NUMBER_VALID(length);this.x=length*sin(angle);this.y=length*cos(angle);return this}rotate(angle){ASSERT_NUMBER_VALID(angle);const c=cos(-angle),s=sin(-angle);return new Vector2(this.x*c-this.y*s,this.x*s+this.y*c)}setDirection(direction,length=1){ASSERT_NUMBER_VALID(direction);ASSERT_NUMBER_VALID(length);direction=mod(direction,4);ASSERT(direction===0||direction===1||direction===2||direction===3,"Vector2.setDirection() direction must be an integer between 0 and 3.");this.x=direction%2?direction-1?-length:length:0;this.y=direction%2?0:direction?-length:length;return this}direction(){return abs(this.x)>abs(this.y)?this.x<0?3:1:this.y<0?2:0}abs(){return new Vector2(abs(this.x),abs(this.y))}floor(){return new Vector2(floor(this.x),floor(this.y))}snap(grid){ASSERT_NUMBER_VALID(grid);return new Vector2(floor(this.x*grid)/grid,floor(this.y*grid)/grid)}mod(divisor=1){return new Vector2(mod(this.x,divisor),mod(this.y,divisor))}area(){return abs(this.x*this.y)}lerp(v,percent){ASSERT_VECTOR2_VALID(v);ASSERT_NUMBER_VALID(percent);const p=clamp(percent);return new Vector2(v.x*p+this.x*(1-p),v.y*p+this.y*(1-p))}arrayCheck(arraySize){return this.x>=0&&this.y>=0&&this.x<arraySize.x&&this.y<arraySize.y}toString(digits=3){ASSERT_NUMBER_VALID(digits);if(this.isValid())return`(${(this.x<0?"":" ")+this.x.toFixed(digits)},${(this.y<0?"":" ")+this.y.toFixed(digits)} )`;else return`(${this.x}, ${this.y})`}isValid(){return isNumber(this.x)&&isNumber(this.y)}}function rgb(r,g,b,a){return new Color(r,g,b,a)}function hsl(h,s,l,a){return(new Color).setHSLA(h,s,l,a)}function isColor(c){return c instanceof Color&&c.isValid()}function ASSERT_COLOR_VALID(c){ASSERT(isColor(c),"Color is invalid.",c)}class Color{constructor(r=1,g=1,b=1,a=1){this.r=r;this.g=g;this.b=b;this.a=a;ASSERT(this.isValid(),"Constructed Color is invalid.",this)}set(r=1,g=1,b=1,a=1){this.r=r;this.g=g;this.b=b;this.a=a;ASSERT_COLOR_VALID(this);return this}setFrom(c){return this.set(c.r,c.g,c.b,c.a)}setAlpha(a=1){this.a=a;ASSERT_COLOR_VALID(this);return this}copy(){return new Color(this.r,this.g,this.b,this.a)}withAlpha(a=1){return new Color(this.r,this.g,this.b,a)}add(c){return new Color(this.r+c.r,this.g+c.g,this.b+c.b,this.a+c.a)}subtract(c){return new Color(this.r-c.r,this.g-c.g,this.b-c.b,this.a-c.a)}multiply(c){return new Color(this.r*c.r,this.g*c.g,this.b*c.b,this.a*c.a)}divide(c){return new Color(this.r/c.r,this.g/c.g,this.b/c.b,this.a/c.a)}scale(scale,alphaScale=scale){return new Color(this.r*scale,this.g*scale,this.b*scale,this.a*alphaScale)}clamp(){return new Color(clamp(this.r),clamp(this.g),clamp(this.b),clamp(this.a))}lerp(c,percent){ASSERT_COLOR_VALID(c);ASSERT_NUMBER_VALID(percent);const p=clamp(percent);return new Color(c.r*p+this.r*(1-p),c.g*p+this.g*(1-p),c.b*p+this.b*(1-p),c.a*p+this.a*(1-p))}setHSLA(h=0,s=0,l=1,a=1){h=mod(h,1);s=clamp(s);l=clamp(l);const q=l<.5?l*(1+s):l+s-l*s,p=2*l-q,f=(p,q,t)=>(t=mod(t,1))*6<1?p+(q-p)*6*t:t*2<1?q:t*3<2?p+(q-p)*(4-t*6):p;this.r=f(p,q,h+1/3);this.g=f(p,q,h);this.b=f(p,q,h-1/3);this.a=a;ASSERT_COLOR_VALID(this);return this}HSLA(){const r=clamp(this.r);const g=clamp(this.g);const b=clamp(this.b);const a=clamp(this.a);const maxC=max(r,g,b);const minC=min(r,g,b);const l=(maxC+minC)/2;let h=0,s=0;if(maxC!==minC){let d=maxC-minC;s=l>.5?d/(2-maxC-minC):d/(maxC+minC);if(r===maxC)h=(g-b)/d+(g<b?6:0);else if(g===maxC)h=(b-r)/d+2;else if(b===maxC)h=(r-g)/d+4}return[h/6,s,l,a]}mutate(amount=.05,alphaAmount=0){ASSERT_NUMBER_VALID(amount);ASSERT_NUMBER_VALID(alphaAmount);return new Color(this.r+rand(amount,-amount),this.g+rand(amount,-amount),this.b+rand(amount,-amount),this.a+rand(alphaAmount,-alphaAmount)).clamp()}toString(useAlpha=true){if(debug&&!this.isValid())return"#000";const toHex=c=>((c=clamp(c)*255|0)<16?"0":"")+c.toString(16);return"#"+toHex(this.r)+toHex(this.g)+toHex(this.b)+(useAlpha?toHex(this.a):"")}setHex(hex){ASSERT(isStringLike(hex),"Color hex code must be a string");ASSERT(hex[0]==="#","Color hex code must start with #");ASSERT([4,5,7,9].includes(hex.length),"Invalid hex");if(hex.length<6){const fromHex=c=>clamp(parseInt(hex[c],16)/15);this.r=fromHex(1);this.g=fromHex(2);this.b=fromHex(3);this.a=hex.length===5?fromHex(4):1}else{const fromHex=c=>clamp(parseInt(hex.slice(c,c+2),16)/255);this.r=fromHex(1);this.g=fromHex(3);this.b=fromHex(5);this.a=hex.length===9?fromHex(7):1}ASSERT_COLOR_VALID(this);return this}rgbaInt(){const r=clamp(this.r)*255|0;const g=clamp(this.g)*255<<8;const b=clamp(this.b)*255<<16;const a=clamp(this.a)*255<<24;return r+g+b+a}isValid(){return isNumber(this.r)&&isNumber(this.g)&&isNumber(this.b)&&isNumber(this.a)}}const WHITE=debugProtectConstant(rgb());const CLEAR_WHITE=debugProtectConstant(rgb(1,1,1,0));const BLACK=debugProtectConstant(rgb(0,0,0));const CLEAR_BLACK=debugProtectConstant(rgb(0,0,0,0));const GRAY=debugProtectConstant(rgb(.5,.5,.5));const RED=debugProtectConstant(rgb(1,0,0));const ORANGE=debugProtectConstant(rgb(1,.5,0));const YELLOW=debugProtectConstant(rgb(1,1,0));const GREEN=debugProtectConstant(rgb(0,1,0));const CYAN=debugProtectConstant(rgb(0,1,1));const BLUE=debugProtectConstant(rgb(0,0,1));const PURPLE=debugProtectConstant(rgb(.5,0,1));const MAGENTA=debugProtectConstant(rgb(1,0,1));class Timer{constructor(timeLeft,useRealTime=false){ASSERT(timeLeft===undefined||isNumber(timeLeft),"Constructed Timer is invalid.",timeLeft);this.useRealTime=useRealTime;const globalTime=this.getGlobalTime();this.time=timeLeft===undefined?undefined:globalTime+timeLeft;this.setTime=timeLeft}set(timeLeft=0){ASSERT(isNumber(timeLeft),"Timer is invalid.",timeLeft);const globalTime=this.getGlobalTime();this.time=globalTime+timeLeft;this.setTime=timeLeft}setUseRealTime(useRealTime=true){ASSERT(!this.isSet(),"Cannot change global time setting while timer is set.");this.useRealTime=useRealTime}unset(){this.time=undefined}isSet(){return this.time!==undefined}active(){return this.getGlobalTime()<this.time}elapsed(){return this.getGlobalTime()>=this.time}get(){return this.isSet()?this.getGlobalTime()-this.time:0}getPercent(){if(!this.isSet())return 0;if(!this.setTime)return 1;return 1-percent(this.time-this.getGlobalTime(),0,this.setTime)}getSetTime(){return this.isSet()?this.setTime:0}getGlobalTime(){return this.useRealTime?timeReal:time}toString(){return this.isSet()?abs(this.get())+" seconds "+(this.get()<0?"before":"after"):"unset"}valueOf(){return this.get()}}function formatTime(t){const signStr=t<0?"-":"";t=abs(t)|0;return signStr+(t/60|0)+":"+(t%60<10?"0":"")+t%60}async function fetchJSON(url){const response=await fetch(url);if(!response.ok)throw new Error(`Failed to fetch JSON from ${url}: ${response.status} ${response.statusText}`);return response.json()}function saveText(text,filename="text",type="text/plain"){saveDataURL(URL.createObjectURL(new Blob([text],{type:type})),filename)}function saveCanvas(canvas,filename="screenshot",type="image/png"){if(canvas instanceof OffscreenCanvas){const saveCanvas=document.createElement("canvas");saveCanvas.width=canvas.width;saveCanvas.height=canvas.height;saveCanvas.getContext("2d").drawImage(canvas,0,0);saveDataURL(saveCanvas.toDataURL(type),filename)}else saveDataURL(canvas.toDataURL(type),filename)}function saveDataURL(url,filename="download",revokeTime){ASSERT(isStringLike(url),"saveDataURL requires url string");ASSERT(isStringLike(filename),"saveDataURL requires filename string");const link=document.createElement("a");link.download=filename;link.href=url;link.click();if(revokeTime!==undefined)setTimeout(()=>URL.revokeObjectURL(url),revokeTime)}function shareURL(title,url,callback){ASSERT(isStringLike(title),"shareURL requires title string");ASSERT(isStringLike(url),"shareURL requires url string");navigator.share?.({title:title,url:url}).then(()=>callback?.())}function readSaveData(saveName,defaultSaveData){ASSERT(isStringLike(saveName),"readSaveData requires saveName string");ASSERT(defaultSaveData===undefined||typeof defaultSaveData==="object"&&defaultSaveData!==null,"readSaveData: default must be an object - the result is "+"{...default, ...loaded}, so a scalar default yields {}. "+"Use readSaveData(key, {best:0}).best");let loadedData={};try{const data=localStorage[saveName];if(data){try{loadedData=JSON.parse(data)}catch{LOG("readSaveData: corrupt JSON for",saveName,"— using defaults")}}}catch{LOG("readSaveData: localStorage unavailable — using defaults")}return{...defaultSaveData,...loadedData}}function writeSaveData(saveName,saveData){ASSERT(isStringLike(saveName),"writeSaveData requires saveName string");try{localStorage[saveName]=JSON.stringify(saveData)}catch{LOG("writeSaveData: failed to write",saveName)}}function noiseHash(i){let h=(i|0)^2654435769;h=Math.imul(h^h>>>16,2246822507);h=Math.imul(h^h>>>13,3266489909);h^=h>>>16;return(h>>>0)/2**32}function noise1D(x){const i=floor(x);return lerp(noiseHash(i),noiseHash(i+1),smoothStep(x-i))}function noise2D(x,y){const ix=floor(x),iy=floor(y);const fx=smoothStep(x-ix),fy=smoothStep(y-iy);const h=(a,b)=>noiseHash(a+b*374761393);return lerp(lerp(h(ix,iy),h(ix+1,iy),fx),lerp(h(ix,iy+1),h(ix+1,iy+1),fx),fy)}let cameraPos=vec2();let cameraAngle=0;let cameraScale=32;let timeScale=1;let canvasColorTiles=true;let canvasClearColor=CLEAR_BLACK;let canvasMaxSize=vec2(1920,1080);let canvasMinAspect=0;let canvasMaxAspect=0;let canvasFixedSize=vec2();let canvasPixelated=false;let tilesPixelated=true;let canvasPixelRatio=1;let fontDefault="arial";let showSplashScreen=false;let headlessMode=false;let engineManualStep=false;let glEnable=true;let glCircleSides=32;let tileDefaultSize=vec2(16);let tileDefaultPadding=0;let tileDefaultBleed=0;let enablePhysicsSolver=true;let objectDefaultMass=1;let objectDefaultDamping=1;let objectDefaultAngleDamping=1;let objectDefaultRestitution=0;let objectDefaultFriction=.8;let objectMaxSpeed=1;let gravity=vec2();let particleEmitRateScale=1;let gamepadsEnable=true;let gamepadDirectionEmulateStick=true;let gamepadAxisFilterEnable=true;let inputWASDEmulateDirection=true;let touchInputEnable=true;let touchGamepadEnable=false;let touchGamepadPassthrough=false;let touchGamepadCenterButtonSize=0;let touchGamepadButtonCount=4;let touchGamepadLeftStick=true;let touchGamepadLeftButtonCount=0;let touchGamepadRightStick=false;let touchGamepadAnalog=true;let touchGamepadFloating=false;let touchGamepadSize=100;let touchGamepadAlpha=.3;let touchGamepadDisplayTime=3;let touchGamepadVibration=0;let vibrateEnable=true;let soundEnable=true;let soundVolume=.3;let soundDefaultRange=40;let soundDefaultTaper=.7;function setCameraPos(pos){cameraPos=pos.copy()}function setCameraAngle(angle){cameraAngle=angle}function setCameraScale(scale){cameraScale=scale}function setTimeScale(scale){timeScale=scale}function setCanvasColorTiles(colorTiles){canvasColorTiles=colorTiles}function setCanvasClearColor(color){canvasClearColor=color.copy()}function setCanvasMaxSize(size){canvasMaxSize=size.copy()}function setCanvasMinAspect(aspect){canvasMinAspect=aspect}function setCanvasMaxAspect(aspect){canvasMaxAspect=aspect}function setCanvasFixedSize(size){canvasFixedSize=size.copy()}function setCanvasPixelated(pixelated){canvasPixelated=pixelated;if(mainCanvas)mainCanvas.style.imageRendering=pixelated?"pixelated":"";if(glCanvas)glCanvas.style.imageRendering=pixelated?"pixelated":""}function setTilesPixelated(pixelated){tilesPixelated=pixelated}function setCanvasPixelRatio(pixelRatio){canvasPixelRatio=pixelRatio}function setFontDefault(font){fontDefault=font}function setShowSplashScreen(show){showSplashScreen=show}function setHeadlessMode(headless){headlessMode=headless}function setEngineManualStep(enable=true){engineManualStep=enable}function setGLEnable(enable){if(enable&&!glCanBeEnabled){console.warn("Can not enable WebGL if it was disabled on start.");return}glEnable=enable;if(glCanvas)glCanvas.style.display=enable?"":"none"}function setGLCircleSides(sides){glCircleSides=sides}function setTileDefaultSize(size){tileDefaultSize=size.copy()}function setTileDefaultPadding(padding){tileDefaultPadding=padding}function setTileDefaultBleed(bleed){tileDefaultBleed=bleed}function setEnablePhysicsSolver(enable){enablePhysicsSolver=enable}function setObjectDefaultMass(mass){objectDefaultMass=mass}function setObjectDefaultDamping(damp){objectDefaultDamping=damp}function setObjectDefaultAngleDamping(damp){objectDefaultAngleDamping=damp}function setObjectDefaultRestitution(restitution){objectDefaultRestitution=restitution}function setObjectDefaultFriction(friction){objectDefaultFriction=friction}function setObjectMaxSpeed(speed){objectMaxSpeed=speed}function setGravity(newGravity){gravity=newGravity.copy()}function setParticleEmitRateScale(scale){particleEmitRateScale=scale}function setGamepadsEnable(enable){gamepadsEnable=enable}function setGamepadDirectionEmulateStick(enable){gamepadDirectionEmulateStick=enable}function setGamepadAxisFilterEnable(enable){gamepadAxisFilterEnable=enable}function setInputWASDEmulateDirection(enable){inputWASDEmulateDirection=enable}function setTouchInputEnable(enable){touchInputEnable=enable}function setTouchGamepadEnable(enable){touchGamepadEnable=enable}function setTouchGamepadPassthrough(passthrough){touchGamepadPassthrough=passthrough}function setTouchGamepadCenterButtonSize(size){touchGamepadCenterButtonSize=size}function setTouchGamepadButtonCount(count){touchGamepadButtonCount=count;if(count>0)touchGamepadRightStick=false}function setTouchGamepadLeftStick(enable){touchGamepadLeftStick=enable;if(enable)touchGamepadLeftButtonCount=0}function setTouchGamepadLeftButtonCount(count){touchGamepadLeftButtonCount=count;if(count>0)touchGamepadLeftStick=false}function setTouchGamepadRightStick(rightStick){touchGamepadRightStick=rightStick;if(rightStick)touchGamepadButtonCount=0}function setTouchGamepadAnalog(analog){touchGamepadAnalog=analog}function setTouchGamepadFloating(floating){touchGamepadFloating=floating}function setTouchGamepadSize(size){touchGamepadSize=size}function setTouchGamepadAlpha(alpha){touchGamepadAlpha=alpha}function setTouchGamepadDisplayTime(time){touchGamepadDisplayTime=time}function setTouchGamepadVibration(ms){touchGamepadVibration=ms}function setVibrateEnable(enable){vibrateEnable=enable}function setSoundEnable(enable){soundEnable=enable}function setSoundVolume(volume){soundVolume=volume;if(soundEnable&&!headlessMode&&audioMasterGain)audioMasterGain.gain.value=volume}function setSoundDefaultRange(range){soundDefaultRange=range}function setSoundDefaultTaper(taper){soundDefaultTaper=taper}function setDebugWatermark(show){debugWatermark=show}function setDebugKey(key){debugKey=key}class EngineObject{constructor(pos=vec2(),size=vec2(1),tileInfo,angle=0,color=WHITE,renderOrder=0){ASSERT(isVector2(pos),"object pos must be a vec2");ASSERT(isVector2(size),"object size must be a vec2");ASSERT(!tileInfo||tileInfo instanceof TileInfo,"object tileInfo should be a TileInfo or undefined");ASSERT(typeof angle==="number"&&isFinite(angle),"object angle should be a number");ASSERT(isColor(color),"object color should be a valid rgba color");ASSERT(typeof renderOrder==="number","object renderOrder should be a number");this.pos=pos.copy();this.size=size.copy();this.drawSize=undefined;this.tileInfo=tileInfo;this.angle=angle;this.color=color.copy();this.additiveColor=undefined;this.mirror=false;this.destroyed=false;this.mass=objectDefaultMass;this.damping=objectDefaultDamping;this.angleDamping=objectDefaultAngleDamping;this.restitution=objectDefaultRestitution;this.friction=objectDefaultFriction;this.gravityScale=1;this.renderOrder=renderOrder;this.velocity=vec2();this.angleVelocity=0;this.spawnTime=time;this.children=[];this.clampSpeed=true;this.groundObject=undefined;this.parent=undefined;this.localPos=vec2();this.localAngle=0;this.collideTiles=false;this.collideSolidObjects=false;this.isSolid=false;this.collideRaycast=false;engineObjects.push(this)}updateTransforms(){const parent=this.parent;if(parent){const mirror=parent.getMirrorSign();const lp=this.localPos,pp=parent.pos;const lx=lp.x*mirror,ly=lp.y,pa=parent.angle;if(pa){const c=cos(-pa),s=sin(-pa);this.pos.set(lx*c-ly*s+pp.x,lx*s+ly*c+pp.y)}else this.pos.set(lx+pp.x,ly+pp.y);this.angle=mirror*this.localAngle+pa}for(const child of this.children)child.updateTransforms()}updatePhysics(){ASSERT(!this.parent);if(this.destroyed)return;if(this.clampSpeed){this.velocity.x=clamp(this.velocity.x,-objectMaxSpeed,objectMaxSpeed);this.velocity.y=clamp(this.velocity.y,-objectMaxSpeed,objectMaxSpeed)}const oldPos=this.pos.copy();this.velocity.x*=this.damping;this.velocity.y*=this.damping;if(this.mass){this.velocity.x+=gravity.x*this.gravityScale;this.velocity.y+=gravity.y*this.gravityScale}this.pos.x+=this.velocity.x;this.pos.y+=this.velocity.y;this.angle+=this.angleVelocity*=this.angleDamping;ASSERT(this.angleDamping>=0&&this.angleDamping<=1);ASSERT(this.damping>=0&&this.damping<=1);if(!enablePhysicsSolver||!this.mass)return;const wasFalling=this.velocity.y<0&&gravity.y<0||this.velocity.y>0&&gravity.y>0;if(this.groundObject){const friction=max(this.friction,this.groundObject.friction);const groundSpeed=this.groundObject.velocity.x;this.velocity.x=groundSpeed+(this.velocity.x-groundSpeed)*friction;this.groundObject=undefined}if(this.collideSolidObjects){const epsilon=.001;for(const o of engineObjectsCollide){if(o.destroyed||o.parent||o===this)continue;if(!this.isSolid&&!o.isSolid)continue;if(!this.isOverlappingObject(o))continue;const collide1=this.collideWithObject(o);const collide2=o.collideWithObject(this);if(!collide1||!collide2)continue;if(isOverlapping(oldPos,this.size,o.pos,o.size)){const deltaPos=oldPos.subtract(o.pos);const length=deltaPos.length();const pushAwayAccel=.001;const velocity=length<.001?vec2(0,1):deltaPos.scale(pushAwayAccel/length);this.velocity=this.velocity.add(velocity);if(o.mass)o.velocity=o.velocity.subtract(velocity);debugPhysics&&debugOverlap(this.pos,this.size,o.pos,o.size,"#f00");continue}const sizeBoth=this.size.add(o.size);const smallStepUp=(oldPos.y-o.pos.y)*2>sizeBoth.y+gravity.y;const isBlockedX=abs(oldPos.y-o.pos.y)*2<sizeBoth.y;const isBlockedY=abs(oldPos.x-o.pos.x)*2<sizeBoth.x;const restitution=max(this.restitution,o.restitution);if(smallStepUp||isBlockedY||!isBlockedX){this.pos.y=o.pos.y+(sizeBoth.y/2+epsilon)*sign(oldPos.y-o.pos.y);if(o.groundObject&&wasFalling||!o.mass){if(wasFalling)this.groundObject=o;this.velocity.y*=-restitution}else if(o.mass){const inelastic=(this.mass*this.velocity.y+o.mass*o.velocity.y)/(this.mass+o.mass);const elastic0=this.velocity.y*(this.mass-o.mass)/(this.mass+o.mass)+o.velocity.y*2*o.mass/(this.mass+o.mass);const elastic1=o.velocity.y*(o.mass-this.mass)/(this.mass+o.mass)+this.velocity.y*2*this.mass/(this.mass+o.mass);this.velocity.y=lerp(inelastic,elastic0,restitution);o.velocity.y=lerp(inelastic,elastic1,restitution)}}if(!smallStepUp&&isBlockedX){this.pos.x=o.pos.x+(sizeBoth.x/2+epsilon)*sign(oldPos.x-o.pos.x);if(o.mass){const inelastic=(this.mass*this.velocity.x+o.mass*o.velocity.x)/(this.mass+o.mass);const elastic0=this.velocity.x*(this.mass-o.mass)/(this.mass+o.mass)+o.velocity.x*2*o.mass/(this.mass+o.mass);const elastic1=o.velocity.x*(o.mass-this.mass)/(this.mass+o.mass)+this.velocity.x*2*this.mass/(this.mass+o.mass);this.velocity.x=lerp(inelastic,elastic0,restitution);o.velocity.x=lerp(inelastic,elastic1,restitution)}else this.velocity.x*=-restitution}debugPhysics&&debugOverlap(this.pos,this.size,o.pos,o.size,"#f0f")}}if(this.collideTiles){const hitLayer=tileCollisionTest(this.pos,this.size,this);if(hitLayer){if(!tileCollisionTest(oldPos,this.size,this)){const isBlockedX=tileCollisionTest(vec2(this.pos.x,oldPos.y),this.size,this);const isBlockedY=tileCollisionTest(vec2(oldPos.x,this.pos.y),this.size,this);const restitution=max(this.restitution,hitLayer.restitution);if(isBlockedX){const epsilon=.001;const maxMove=.1;const gravitySign=gravity.y>0?-1:1;const y=gravitySign>0?floor(oldPos.y-this.size.y/2+1)+this.size.y/2+epsilon:ceil(oldPos.y+this.size.y/2-1)-this.size.y/2-epsilon;const delta=abs(y-this.pos.y);if(delta<maxMove)if(!tileCollisionTest(vec2(this.pos.x,y),this.size,this)){this.pos.y=y;debugPhysics&&debugRect(this.pos,this.size,"#ff0");return}this.pos.x=oldPos.x;this.velocity.x*=-restitution}if(isBlockedY||!isBlockedX){if(wasFalling){const epsilon=1e-4;const offset=this.size.y/2+epsilon;this.pos.y=gravity.y<0?floor(oldPos.y-this.size.y/2)+offset:ceil(oldPos.y+this.size.y/2)-offset;this.groundObject=hitLayer}else{this.pos.y=oldPos.y;this.groundObject=undefined}this.velocity.y*=-restitution}debugPhysics&&debugRect(this.pos,this.size,"#f00")}}}}update(){}render(){drawTile(this.pos,this.drawSize||this.size,this.tileInfo,this.color,this.angle,this.mirror,this.additiveColor)}renderLight(){}destroy(immediate=false){if(this.destroyed)return;this.destroyed=true;this.parent?.removeChild(this);for(const child of this.children){child.parent=undefined;child.destroy(immediate)}}localToWorld(pos){return this.pos.add(pos.rotate(this.angle))}worldToLocal(pos){return pos.subtract(this.pos).rotate(-this.angle)}localToWorldVector(vec){return vec.rotate(this.angle)}worldToLocalVector(vec){return vec.rotate(-this.angle)}collideWithTile(tileData,pos){return tileData>0}collideWithObject(object){return true}getUp(scale=1){return vec2().setAngle(this.angle,scale)}getRight(scale=1){return vec2().setAngle(this.angle+PI/2,scale)}getAliveTime(){return time-this.spawnTime}getSpeed(){return this.velocity.length()}applyAcceleration(acceleration){if(this.mass)this.velocity=this.velocity.add(acceleration)}applyAngularAcceleration(acceleration){if(this.mass)this.angleVelocity+=acceleration}applyForce(force){if(this.mass)this.applyAcceleration(force.scale(1/this.mass))}getMirrorSign(){return this.mirror?-1:1}addChild(child,localPos=vec2(),localAngle=0){ASSERT(!this.destroyed,"cannot add child to destroyed object");if(this.destroyed)return child;ASSERT(!child.parent&&!this.children.includes(child));ASSERT(child instanceof EngineObject,"child must be an EngineObject");ASSERT(child!==this,"cannot add self as child");this.children.push(child);child.parent=this;child.localPos=localPos.copy();child.localAngle=localAngle;child.updateTransforms();return child}removeChild(child){ASSERT(child.parent===this&&this.children.includes(child));this.children.splice(this.children.indexOf(child),1);child.parent=undefined}isOverlappingObject(object){return this.isOverlapping(object.pos,object.size)}isOverlapping(pos,size=vec2()){return isOverlapping(this.pos,this.size,pos,size)}setCollision(collideSolidObjects=true,isSolid=true,collideTiles=true,collideRaycast=true){ASSERT(collideSolidObjects||!isSolid,"solid objects must be set to collide");this.collideSolidObjects=collideSolidObjects;this.isSolid=isSolid;this.collideTiles=collideTiles;this.collideRaycast=collideRaycast}toString(){let text="type = "+this.constructor.name;if(this.pos.x||this.pos.y)text+="\npos = "+this.pos;if(this.velocity.x||this.velocity.y)text+="\nvelocity = "+this.velocity;if(this.size.x||this.size.y)text+="\nsize = "+this.size;if(this.angle)text+="\nangle = "+this.angle.toFixed(3);if(this.color)text+="\ncolor = "+this.color;return text}renderDebugInfo(){if(!debug)return;const hasPhysics=this.collideTiles||this.collideSolidObjects||this.isSolid;if(!hasPhysics&&!this.parent)return;const size=vec2(max(this.size.x,.2),max(this.size.y,.2));const color=rgb(this.collideTiles?1:0,this.collideSolidObjects?1:0,this.isSolid?1:0,.5);debugRect(this.pos,size,color,0,this.angle,hasPhysics);if(this.parent)debugRect(this.pos,size.scale(.8),rgb(1,1,1,.5),0,this.angle);this.parent&&debugLine(this.pos,this.parent.pos,rgb(1,1,1,.5),.5)}}let mainCanvas;let mainContext;let drawContext;let workCanvas;let workContext;let workReadCanvas;let workReadContext;let backgroundCanvas;let mainCanvasSize=vec2();let textureInfos=[];let drawCount;let primitiveCount;function isWhite(c){return c.r>=1&&c.g>=1&&c.b>=1}function isBlack(c){return c.r<=0&&c.g<=0&&c.b<=0&&c.a<=0}function tile(index=0,size=tileDefaultSize,texture=0,padding=tileDefaultPadding,bleed=tileDefaultBleed){ASSERT(isVector2(index)||typeof index==="number","index must be a vec2 or number");ASSERT(isVector2(size)||typeof size==="number","size must be a vec2 or number");ASSERT(isNumber(texture)||texture instanceof TextureInfo,"texture must be a number or TextureInfo");ASSERT(isNumber(padding),"padding must be a number");if(headlessMode)return new TileInfo;if(typeof size==="number"){ASSERT(size>0);size=new Vector2(size,size)}const textureInfo=typeof texture==="number"?textureInfos[texture]:texture;ASSERT(textureInfo instanceof TextureInfo,"tile texture is not loaded");ASSERT(textureInfo.size.x>0,"tile texture is not loaded");const sizePaddedX=size.x+padding*2;const sizePaddedY=size.y+padding*2;let x,y;if(typeof index==="number"){const cols=textureInfo.size.x/sizePaddedX|0;x=index%cols;y=index/cols|0}else{x=index.x;y=index.y}const pos=new Vector2(x*sizePaddedX+padding,y*sizePaddedY+padding);return new TileInfo(pos,size,textureInfo,padding,bleed)}class TileInfo{constructor(pos=vec2(),size=tileDefaultSize,textureInfo=textureInfos[0],padding=tileDefaultPadding,bleed=tileDefaultBleed,columns=0){this.pos=pos.copy();this.size=size.copy();this.padding=padding;this.textureInfo=textureInfo;this.bleed=bleed;this.columns=columns}offset(offset){return new TileInfo(this.pos.add(offset),this.size,this.textureInfo,this.padding,this.bleed,this.columns)}frame(frame){ASSERT(typeof frame==="number");const w=this.size.x+this.padding*2;const h=this.size.y+this.padding*2;const x=(this.columns?frame%this.columns:frame)*w;const y=(this.columns?frame/this.columns|0:0)*h;ASSERT(this.pos.x+x+this.size.x<=this.textureInfo.size.x,"frame extends beyond texture width!");ASSERT(this.pos.y+y+this.size.y<=this.textureInfo.size.y,"frame extends beyond texture height!");return this.offset(new Vector2(x,y))}setColumns(columns=0){ASSERT(isNumber(columns)&&columns>=0,"columns must be a number >= 0");this.columns=columns;return this}index(index){return tile(index,this.size,this.textureInfo,this.padding,this.bleed).setColumns(this.columns)}setFullImage(textureInfo=this.textureInfo){this.textureInfo=textureInfo;this.pos=new Vector2;this.size=textureInfo.size.copy();this.bleed=this.padding=this.columns=0;return this}}class TextureInfo{constructor(image,useWebGL=true,wrap=false){this.image=image;this.size=image?vec2(image.width,image.height):vec2();this.sizeInverse=image?vec2(1/image.width,1/image.height):vec2();this.glTexture=undefined;this.wrap=wrap;useWebGL&&this.createWebGLTexture()}createWebGLTexture(){glRegisterTextureInfo(this)}destroyWebGLTexture(){glUnregisterTextureInfo(this)}hasWebGL(){return!!this.glTexture}setWrap(wrap=true){this.wrap=wrap;glSetTextureWrap(this.glTexture,wrap)}}function drawTile(pos,size=vec2(1),tileInfo,color=WHITE,angle=0,mirror,additiveColor,useWebGL=glEnable,screenSpace=false,context){ASSERT(isVector2(pos),"pos must be a vec2");ASSERT(isVector2(size),"size must be a vec2");ASSERT(isColor(color),"color is invalid");ASSERT(isNumber(angle),"angle must be a number");ASSERT(!additiveColor||isColor(additiveColor),"additiveColor must be a color");ASSERT(!context||!useWebGL,"context only supported in canvas 2D mode");const textureInfo=tileInfo?.textureInfo;const bleed=tileInfo?.bleed??0;if(useWebGL&&glEnable){ASSERT(!!glContext,"WebGL is not enabled!");if(screenSpace)[pos,size,angle]=screenToWorldTransform(pos,size,angle);if(textureInfo){const sizeInverse=textureInfo.sizeInverse;const x=tileInfo.pos.x*sizeInverse.x;const y=tileInfo.pos.y*sizeInverse.y;const w=tileInfo.size.x*sizeInverse.x;const h=tileInfo.size.y*sizeInverse.y;glSetTexture(textureInfo.glTexture);if(bleed){const bleedX=sizeInverse.x*bleed;const bleedY=sizeInverse.y*bleed;glDraw(pos.x,pos.y,mirror?-size.x:size.x,size.y,angle,x+bleedX,y+bleedY,x-bleedX+w,y-bleedY+h,color.rgbaInt(),additiveColor&&additiveColor.rgbaInt())}else{glDraw(pos.x,pos.y,mirror?-size.x:size.x,size.y,angle,x,y,x+w,y+h,color.rgbaInt(),additiveColor&&additiveColor.rgbaInt())}}else{const combined=additiveColor?color.add(additiveColor):color;glDrawUntextured(pos.x,pos.y,size.x,size.y,angle,combined.rgbaInt())}}else{++drawCount;++primitiveCount;drawCanvas2D(pos,size,angle,mirror,context=>{if(textureInfo){context.scale(1,-1);const x=tileInfo.pos.x,y=tileInfo.pos.y;const w=tileInfo.size.x,h=tileInfo.size.y;drawImageColor(context,textureInfo.image,x,y,w,h,-.5,-.5,1,1,color,additiveColor,bleed)}else{const c=additiveColor?color.add(additiveColor):color;context.fillStyle=c.toString();context.fillRect(-.5,-.5,1,1)}},screenSpace,context)}}function drawRect(pos,size,color,angle,useWebGL,screenSpace,context){drawTile(pos,size,undefined,color,angle,false,undefined,useWebGL,screenSpace,context)}function drawRectGradient(pos,size,colorTop=WHITE,colorBottom=CLEAR_WHITE,angle=0,useWebGL=glEnable,screenSpace=false,context){ASSERT(isVector2(pos),"pos must be a vec2");ASSERT(isVector2(size),"size must be a vec2");ASSERT(isColor(colorTop)&&isColor(colorBottom),"color is invalid");ASSERT(isNumber(angle),"angle must be a number");ASSERT(!context||!useWebGL,"context only supported in canvas 2D mode");if(useWebGL&&glEnable){ASSERT(!!glContext,"WebGL is not enabled!");if(screenSpace){pos=screenToWorld(pos);size=size.scale(1/cameraScale);angle+=cameraAngle}const points=[],colors=[];const halfSizeX=size.x/2,halfSizeY=size.y/2;const colorTopInt=colorTop.rgbaInt();const colorBottomInt=colorBottom.rgbaInt();const c=cos(-angle),s=sin(-angle);for(let i=4;i--;){const x=i&1?halfSizeX:-halfSizeX;const y=i&2?halfSizeY:-halfSizeY;const rx=x*c-y*s;const ry=x*s+y*c;const color=i&2?colorTopInt:colorBottomInt;points.push(vec2(pos.x+rx,pos.y+ry));colors.push(color)}glDrawColoredPoints(points,colors)}else{++drawCount;++primitiveCount;drawCanvas2D(pos,size,angle,false,context=>{const gradient=context.createLinearGradient(0,.5,0,-.5);gradient.addColorStop(0,colorTop.toString());gradient.addColorStop(1,colorBottom.toString());context.fillStyle=gradient;context.fillRect(-.5,-.5,1,1)},screenSpace,context)}}function drawTextureWrapped(pos,size,wrapCount,texture=0,color=WHITE,angle=0,additiveColor,useWebGL=glEnable,screenSpace=false,context){ASSERT(isVector2(pos),"pos must be a vec2");ASSERT(isVector2(size),"size must be a vec2");ASSERT(isVector2(wrapCount),"wrapCount must be a vec2");ASSERT(isColor(color),"color is invalid");ASSERT(isNumber(angle),"angle must be a number");ASSERT(!additiveColor||isColor(additiveColor),"additiveColor must be a color");ASSERT(!context||!useWebGL,"context only supported in canvas 2D mode");ASSERT(!(texture instanceof TileInfo),"pass a TextureInfo or texture index, not a TileInfo — use tileInfo.textureInfo");if(headlessMode)return;const textureInfo=typeof texture==="number"?textureInfos[texture]:texture;ASSERT(textureInfo instanceof TextureInfo,"texture not loaded");ASSERT(textureInfo.size.x>0,"texture not loaded");ASSERT(textureInfo.wrap,"drawTextureWrapped requires a wrap-enabled texture; call textureInfo.setWrap(true) first");if(useWebGL&&glEnable){ASSERT(!!glContext,"WebGL is not enabled!");if(screenSpace)[pos,size,angle]=screenToWorldTransform(pos,size,angle);glSetTexture(textureInfo.glTexture);glDraw(pos.x,pos.y,size.x,size.y,angle,0,0,wrapCount.x,wrapCount.y,color.rgbaInt(),additiveColor&&additiveColor.rgbaInt());return}++drawCount;++primitiveCount;if(!screenSpace){pos=worldToScreen(pos);size=size.scale(cameraScale);angle-=cameraAngle}const noTint=!canvasColorTiles||(additiveColor?isWhite(color.add(additiveColor))&&additiveColor.a<=0:isWhite(color));const alphaBaked=!noTint&&additiveColor&&!isBlack(additiveColor);const source=noTint?textureInfo.image:bakeTintedImage(textureInfo.image,color,additiveColor);context=context||drawContext;context.save();context.translate(pos.x+.5,pos.y+.5);context.rotate(angle);context.globalAlpha=alphaBaked?1:color.a;const pattern=context.createPattern(source,"repeat");const m=(new DOMMatrix).translate(-size.x/2,-size.y/2).scale(size.x/(wrapCount.x*source.width),size.y/(wrapCount.y*source.height));pattern.setTransform(m);context.fillStyle=pattern;context.fillRect(-size.x/2,-size.y/2,size.x,size.y);context.globalAlpha=1;context.restore()}function drawLineList(points,width=.1,color=WHITE,wrap=false,pos=vec2(),angle=0,useWebGL=glEnable,screenSpace=false,context){ASSERT(isArray(points),"points must be an array");ASSERT(isNumber(width),"width must be a number");ASSERT(isColor(color),"color is invalid");ASSERT(isVector2(pos),"pos must be a vec2");ASSERT(isNumber(angle),"angle must be a number");ASSERT(!context||!useWebGL,"context only supported in canvas 2D mode");if(useWebGL&&glEnable){ASSERT(!!glContext,"WebGL is not enabled!");let size=vec2(1);if(screenSpace)[pos,size,angle]=screenToWorldTransform(pos,size,angle);glDrawOutlineTransform(points,color.rgbaInt(),width,pos.x,pos.y,size.x,size.y,angle,wrap)}else{++drawCount;++primitiveCount;drawCanvas2D(pos,vec2(1),angle,false,context=>{context.strokeStyle=color.toString();context.lineWidth=width;context.beginPath();for(let i=0;i<points.length;++i){const point=points[i];context.lineTo(point.x,point.y)}wrap&&context.closePath();context.stroke()},screenSpace,context)}}function drawLine(posA,posB,width=.1,color=WHITE,pos=vec2(),angle=0,useWebGL=glEnable,screenSpace=false,context){const halfDelta=vec2((posB.x-posA.x)/2,(posB.y-posA.y)/2);const size=vec2(width,halfDelta.length()*2);pos=pos.add(posA.add(halfDelta));if(screenSpace)halfDelta.y*=-1;angle+=halfDelta.angle();drawRect(pos,size,color,angle,useWebGL,screenSpace,context)}function drawRegularPoly(pos,size=vec2(1),sides=3,color=WHITE,lineWidth=0,lineColor=BLACK,angle=0,useWebGL=glEnable,screenSpace=false,context){ASSERT(isVector2(size),"size must be a vec2");ASSERT(isNumber(sides),"sides must be a number");const points=[];const sizeX=size.x/2,sizeY=size.y/2;for(let i=sides;i--;){const a=i/sides*PI*2;points.push(vec2(sin(a)*sizeX,cos(a)*sizeY))}drawPoly(points,color,lineWidth,lineColor,pos,angle,useWebGL,screenSpace,context)}function drawPoly(points,color=WHITE,lineWidth=0,lineColor=BLACK,pos=vec2(),angle=0,useWebGL=glEnable,screenSpace=false,context=undefined){ASSERT(isVector2(pos),"pos must be a vec2");ASSERT(isArray(points),"points must be an array");ASSERT(isColor(color)&&isColor(lineColor),"color is invalid");ASSERT(isNumber(lineWidth),"lineWidth must be a number");ASSERT(isNumber(angle),"angle must be a number");ASSERT(!context||!useWebGL,"context only supported in canvas 2D mode");if(useWebGL&&glEnable){ASSERT(!!glContext,"WebGL is not enabled!");let size=vec2(1);if(screenSpace)[pos,size,angle]=screenToWorldTransform(pos,size,angle);glDrawPointsTransform(points,color.rgbaInt(),pos.x,pos.y,size.x,size.y,angle);if(lineWidth>0)glDrawOutlineTransform(points,lineColor.rgbaInt(),lineWidth,pos.x,pos.y,size.x,size.y,angle)}else{drawCanvas2D(pos,vec2(1),angle,false,context=>{context.fillStyle=color.toString();context.beginPath();for(const point of points)context.lineTo(point.x,point.y);context.closePath();context.fill();if(lineWidth){context.strokeStyle=lineColor.toString();context.lineWidth=lineWidth;context.stroke()}},screenSpace,context)}}function drawEllipse(pos,size=vec2(1),color=WHITE,angle=0,lineWidth=0,lineColor=BLACK,useWebGL=glEnable,screenSpace=false,context){ASSERT(isVector2(pos),"pos must be a vec2");ASSERT(isVector2(size),"size must be a vec2");ASSERT(isColor(color)&&isColor(lineColor),"color is invalid");ASSERT(isNumber(angle),"angle must be a number");ASSERT(isNumber(lineWidth),"lineWidth must be a number");ASSERT(lineWidth>=0,"lineWidth must be a positive value or 0");ASSERT(!context||!useWebGL,"context only supported in canvas 2D mode");lineWidth=clamp(lineWidth,0,min(size.x,size.y));if(useWebGL&&glEnable){const sides=glCircleSides;drawRegularPoly(pos,size,sides,color,lineWidth,lineColor,angle,useWebGL,screenSpace,context)}else{drawCanvas2D(pos,vec2(1),angle,false,context=>{context.fillStyle=color.toString();context.beginPath();context.ellipse(0,0,size.x/2,size.y/2,0,0,9);context.fill();if(lineWidth){context.strokeStyle=lineColor.toString();context.lineWidth=lineWidth;context.stroke()}},screenSpace,context)}}function drawCircle(pos,size=1,color=WHITE,lineWidth=0,lineColor=BLACK,useWebGL=glEnable,screenSpace=false,context){ASSERT(isNumber(size),"size must be a number");drawEllipse(pos,vec2(size),color,0,lineWidth,lineColor,useWebGL,screenSpace,context)}let drawEllipseGradientOffset=0;function drawEllipseGradient(pos,size=vec2(1),colorInner=WHITE,colorOuter=CLEAR_WHITE,angle=0,useWebGL=glEnable,screenSpace=false,context){ASSERT(isVector2(pos),"pos must be a vec2");ASSERT(isVector2(size),"size must be a vec2");ASSERT(isColor(colorInner)&&isColor(colorOuter),"color is invalid");ASSERT(isNumber(angle),"angle must be a number");ASSERT(!context||!useWebGL,"context only supported in canvas 2D mode");if(headlessMode)return;if(useWebGL&&glEnable){ASSERT(!!glContext,"WebGL is not enabled!");if(screenSpace){pos=screenToWorld(pos);size=size.scale(1/cameraScale);angle+=cameraAngle}const sides=glCircleSides;const radiusX=size.x/2,radiusY=size.y/2;const innerInt=colorInner.rgbaInt();const outerInt=colorOuter.rgbaInt();const offset=drawEllipseGradientOffset++;const c=cos(-angle),s=sin(-angle);const rim=a=>{const lx=sin(a)*radiusX,ly=cos(a)*radiusY;return vec2(pos.x+lx*c-ly*s,pos.y+lx*s+ly*c)};const startA=offset%sides/sides*PI*2;const points=[rim(startA)];const colors=[outerInt];for(let i=sides;i--;){const a=(i+offset)%sides/sides*PI*2;points.push(pos);colors.push(innerInt);points.push(rim(a));colors.push(outerInt)}glDrawColoredPoints(points,colors)}else{++drawCount;++primitiveCount;drawCanvas2D(pos,size,angle,false,context=>{const gradient=context.createRadialGradient(0,0,0,0,0,.5);gradient.addColorStop(0,colorInner.toString());gradient.addColorStop(1,colorOuter.toString());context.fillStyle=gradient;context.beginPath();context.ellipse(0,0,.5,.5,0,0,9);context.fill()},screenSpace,context)}}function drawCircleGradient(pos,size=1,colorInner=WHITE,colorOuter=CLEAR_WHITE,useWebGL=glEnable,screenSpace=false,context){ASSERT(isNumber(size),"size must be a number");drawEllipseGradient(pos,vec2(size),colorInner,colorOuter,0,useWebGL,screenSpace,context)}function drawCanvas2D(pos,size,angle=0,mirror=false,drawFunction,screenSpace=false,context=drawContext){ASSERT(isVector2(pos),"pos must be a vec2");ASSERT(isVector2(size),"size must be a vec2");ASSERT(isNumber(angle),"angle must be a number");ASSERT(typeof drawFunction==="function","drawFunction must be a function");if(!screenSpace){pos=worldToScreen(pos);size=size.scale(cameraScale);angle-=cameraAngle}context.save();context.translate(pos.x+.5,pos.y+.5);context.rotate(angle);context.scale(mirror?-size.x:size.x,-size.y);drawFunction(context);context.restore()}function drawText(text,pos,size=1,color=WHITE,lineWidth=0,lineColor=BLACK,textAlign="center",font=fontDefault,fontStyle="",maxWidth,angle=0,context=drawContext){pos=worldToScreen(pos);size*=cameraScale;lineWidth*=cameraScale;angle-=cameraAngle;angle*=-1;drawTextScreen(text,pos,size,color,lineWidth,lineColor,textAlign,font,fontStyle,maxWidth,angle,context)}function drawTextScreen(text,pos,size,color=WHITE,lineWidth=0,lineColor=BLACK,textAlign="center",font=fontDefault,fontStyle="",maxWidth,angle=0,context=drawContext){ASSERT(isStringLike(text),"text must be a string");ASSERT(isVector2(pos),"pos must be a vec2");ASSERT(isNumber(size),"size must be a number");ASSERT(isColor(color),"color must be a color");ASSERT(isNumber(lineWidth),"lineWidth must be a number");ASSERT(isColor(lineColor),"lineColor must be a color");ASSERT(["left","center","right"].includes(textAlign),"align must be left, center, or right");ASSERT(isStringLike(font),"font must be a string");ASSERT(isStringLike(fontStyle),"fontStyle must be a string");ASSERT(isNumber(angle),"angle must be a number");const lines=(text+"").split("\n");const posY=pos.y-(lines.length-1)*size/2;context.save();context.fillStyle=color.toString();context.strokeStyle=lineColor.toString();context.lineWidth=lineWidth;context.textAlign=textAlign;context.font=fontStyle+" "+size+"px "+font;context.textBaseline="middle";context.translate(pos.x,posY);context.rotate(-angle);let yOffset=0;lines.forEach(line=>{lineWidth&&context.strokeText(line,0,yOffset,maxWidth);context.fillText(line,0,yOffset,maxWidth);yOffset+=size});context.restore()}async function loadTexture(textureIndex,src){ASSERT(isNumber(textureIndex),"textureIndex must be a number");ASSERT(!textureInfos[textureIndex],"textureIndex is already loaded!");ASSERT(!src||isStringLike(src),"image src must be a string");const image=new Image;if(src){await new Promise(resolve=>{image.onerror=image.onload=resolve;image.crossOrigin="anonymous";image.src=src})}textureInfos[textureIndex]=new TextureInfo(image)}function screenToWorld(screenPos){ASSERT(isVector2(screenPos),"screenPos must be a vec2");let x=(screenPos.x-mainCanvasSize.x/2+.5)/cameraScale;let y=(screenPos.y-mainCanvasSize.y/2+.5)/-cameraScale;if(cameraAngle){const c=cos(-cameraAngle),s=sin(-cameraAngle);const xr=x*c-y*s,yr=x*s+y*c;x=xr;y=yr}return new Vector2(x+cameraPos.x,y+cameraPos.y)}function worldToScreen(worldPos){ASSERT(isVector2(worldPos),"worldPos must be a vec2");let x=worldPos.x-cameraPos.x;let y=worldPos.y-cameraPos.y;if(cameraAngle){const c=cos(cameraAngle),s=sin(cameraAngle);const xr=x*c-y*s,yr=x*s+y*c;x=xr;y=yr}return new Vector2(x*cameraScale+mainCanvasSize.x/2-.5,y*-cameraScale+mainCanvasSize.y/2-.5)}function screenToWorldDelta(screenDelta){ASSERT(isVector2(screenDelta),"screenDelta must be a vec2");let x=screenDelta.x/cameraScale;let y=screenDelta.y/-cameraScale;if(cameraAngle){const c=cos(-cameraAngle),s=sin(-cameraAngle);const xr=x*c-y*s,yr=x*s+y*c;x=xr;y=yr}return new Vector2(x,y)}function worldToScreenDelta(worldDelta){ASSERT(isVector2(worldDelta),"worldDelta must be a vec2");let x=worldDelta.x;let y=worldDelta.y;if(cameraAngle){const c=cos(cameraAngle),s=sin(cameraAngle);const xr=x*c-y*s,yr=x*s+y*c;x=xr;y=yr}return new Vector2(x*cameraScale,y*-cameraScale)}function screenToWorldTransform(screenPos,screenSize,screenAngle=0){ASSERT(isVector2(screenPos),"screenPos must be a vec2");ASSERT(isVector2(screenSize),"screenSize must be a vec2");ASSERT(isNumber(screenAngle),"screenAngle must be a number");return[screenToWorld(screenPos),screenSize.scale(1/cameraScale),screenAngle+cameraAngle]}function getCameraSize(){return mainCanvasSize.scale(1/cameraScale)}function cameraFit(center,size,worldMargin,screenInset){ASSERT(isVector2(center),"center must be a vec2");ASSERT(isVector2(size),"size must be a vec2");const margin=padSides(worldMargin);const inset=padSides(screenInset);const worldW=size.x+margin.left+margin.right;const worldH=size.y+margin.top+margin.bottom;const viewW=mainCanvasSize.x-inset.left-inset.right;const viewH=mainCanvasSize.y-inset.top-inset.bottom;if(!(worldW>0&&worldH>0&&viewW>0&&viewH>0))return cameraScale;cameraScale=min(viewW/worldW,viewH/worldH);const marginVector=vec2(margin.right-margin.left,margin.top-margin.bottom).scale(.5);const insetVector=vec2(inset.right-inset.left,inset.top-inset.bottom).scale(.5/cameraScale);cameraPos=center.add(marginVector).add(insetVector);return cameraScale;function padSides(p){if(p===undefined||isNumber(p))p=vec2(p);if(isVector2(p))return{top:p.y,right:p.x,bottom:p.y,left:p.x};return{top:p.top||0,right:p.right||0,bottom:p.bottom||0,left:p.left||0}}}function isOnScreen(pos,size=0){ASSERT(isVector2(pos),"pos must be a vec2");ASSERT(isVector2(size)||isNumber(size),"size must be a vec2 or number");if(!cameraScale)return false;let x=pos.x-cameraPos.x;let y=pos.y-cameraPos.y;if(cameraAngle){const c=cos(cameraAngle),s=sin(cameraAngle);const xr=x*c-y*s,yr=x*s+y*c;x=xr;y=yr}x*=cameraScale*2;y*=-cameraScale*2;if(size instanceof Vector2)size=size.length();size*=cameraScale;const w=mainCanvasSize.x,h=mainCanvasSize.y;return x+size>-w&&x-size<w&&y+size>-h&&y-size<h}function setAdditiveBlendMode(additive=true){glAdditive=additive;drawContext.globalCompositeOperation=additive?"lighter":"source-over"}function setBackgroundCanvas(canvas){backgroundCanvas=canvas}function combineCanvases(){const w=mainCanvasSize.x,h=mainCanvasSize.y;workCanvas.width=w;workCanvas.height=h;workContext.fillStyle="#000";workContext.fillRect(0,0,w,h);if(backgroundCanvas)workContext.drawImage(backgroundCanvas,0,0,w,h);glCopyToContext(workContext);workContext.drawImage(mainCanvas,0,0);mainContext.drawImage(workCanvas,0,0)}function bakeTintedImage(image,color,additiveColor){const w=image.width|0,h=image.height|0;workReadCanvas.width=w;workReadCanvas.height=h;workReadContext.drawImage(image,0,0);const imageData=workReadContext.getImageData(0,0,w,h);const data=imageData.data;if(additiveColor&&!isBlack(additiveColor)){const colorMultiply=[color.r,color.g,color.b,color.a];const colorAdd=[additiveColor.r*255,additiveColor.g*255,additiveColor.b*255,additiveColor.a*255];for(let i=0;i<data.length;++i)data[i]=data[i]*colorMultiply[i&3]+colorAdd[i&3]|0}else{for(let i=0;i<data.length;i+=4){data[i]*=color.r;data[i+1]*=color.g;data[i+2]*=color.b}}workReadContext.putImageData(imageData,0,0);return workReadCanvas}function drawImageColor(context,image,sx,sy,sWidth,sHeight,dx,dy,dWidth,dHeight,color,additiveColor,bleed=0){const sx2=bleed;const sy2=bleed;sWidth=max(1,sWidth|0);sHeight=max(1,sHeight|0);const sWidth2=sWidth-2*bleed;const sHeight2=sHeight-2*bleed;if(!canvasColorTiles||(additiveColor?isWhite(color.add(additiveColor))&&additiveColor.a<=0:isWhite(color))){context.globalAlpha=color.a;context.drawImage(image,sx+sx2,sy+sy2,sWidth2,sHeight2,dx,dy,dWidth,dHeight);context.globalAlpha=1}else{workReadCanvas.width=sWidth;workReadCanvas.height=sHeight;workReadContext.drawImage(image,sx|0,sy|0,sWidth,sHeight,0,0,sWidth,sHeight);const imageData=workReadContext.getImageData(0,0,sWidth,sHeight);const data=imageData.data;if(additiveColor&&!isBlack(additiveColor)){const colorMultiply=[color.r,color.g,color.b,color.a];const colorAdd=[additiveColor.r*255,additiveColor.g*255,additiveColor.b*255,additiveColor.a*255];for(let i=0;i<data.length;++i)data[i]=data[i]*colorMultiply[i&3]+colorAdd[i&3]|0;workReadContext.putImageData(imageData,0,0);context.drawImage(workReadCanvas,sx2,sy2,sWidth2,sHeight2,dx,dy,dWidth,dHeight)}else{for(let i=0;i<data.length;i+=4){data[i]*=color.r;data[i+1]*=color.g;data[i+2]*=color.b}workReadContext.putImageData(imageData,0,0);context.globalAlpha=color.a;context.drawImage(workReadCanvas,sx2,sy2,sWidth2,sHeight2,dx,dy,dWidth,dHeight);context.globalAlpha=1}}}function isFullscreen(){return!!document.fullscreenElement}function toggleFullscreen(){const rootElement=mainCanvas.parentElement;if(isFullscreen()){if(document.exitFullscreen)document.exitFullscreen()}else if(rootElement.requestFullscreen)rootElement.requestFullscreen()}function setCursor(cursorStyle="auto"){const rootElement=mainCanvas.parentElement;rootElement.style.cursor=cursorStyle}let engineImageFont;class ImageFont{constructor(tileInfo){ASSERT(!!tileInfo,"tileInfo is required for ImageFont");this.tileInfo=tileInfo.frame(0)}drawText(text,pos,size=1,center,color,useWebGL,context){ASSERT(isVector2(size)||typeof size==="number","size must be a vec2 or number");if(typeof size==="number"){ASSERT(size>0);size*=cameraScale;size=new Vector2(size,size)}else size=size.scale(cameraScale);this.drawTextScreen(text,worldToScreen(pos),size,center,color,useWebGL,context)}drawTextScreen(text,pos,size,center=true,color=WHITE,useWebGL=glEnable,context){ASSERT(isStringLike(text),"text must be a string");ASSERT(isVector2(pos),"pos must be a vec2");ASSERT(isVector2(size)||typeof size==="number","size must be a vec2 or number");ASSERT(isColor(color),"color must be a color");size=typeof size==="number"?new Vector2(size,size):size;const drawPos=new Vector2;const tileInfo=this.tileInfo;const padding=tileInfo.padding;const sizePaddedX=tileInfo.size.x+padding*2;const sizePaddedY=tileInfo.size.y+padding*2;const cols=tileInfo.textureInfo.size.x/sizePaddedX|0;(text+"").split("\n").forEach((line,j)=>{const centerOffset=center?(line.length-1)*size.x/2:0;for(let i=line.length;i--;){const charCode=line.charCodeAt(i);const index=charCode<32||charCode>127?95:charCode-32;const x=index%cols;const y=index/cols|0;tileInfo.pos.x=x*sizePaddedX+padding;tileInfo.pos.y=y*sizePaddedY+padding;drawPos.x=ceil(pos.x+i*size.x-centerOffset-size.x/2)+size.x/2-.5;drawPos.y=ceil(pos.y+j*size.y-size.y/2)+size.y/2-.5;drawTile(drawPos,size,tileInfo,color,0,false,undefined,useWebGL,true,context)}})}}async function imageFontInit(){const image=new Image;await new Promise(resolve=>{image.onerror=image.onload=resolve;image.crossOrigin="anonymous";image.src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAUAAAAAeAQMAAABnrVXaAAAABlBMVEUAAAD///+l2Z/dAAAAAXRSTlMAQObYZgAAAjpJREFUOMu9kzFu2zAUhn+CAROgqrk+B2l0BWYxMjlXeYaAtFtbdA1sGgHqRQfI0CNkSG5AwYB0BQ8d5Bsomwah6CPVeGg6tEPzAxLwyI+P78cP4u9lNO9OoMKnLMOobG5020/yaj/MrRcCGh1gBbyiLTPJEYaIiom5KM9Jq7KgynMGtb6L4GL4MF2H4LQKCXTvDVw2I4MsgZT7QLExdiutH+D08VOP3INXRrWX1/mmpbkNgAPYRVANb4xpcegYvhiNbIXauQICEjBuYLfMakaakWQeXxiZ0VDtuJCKs3ztMV59QtsHJNcRxDzfdL21ty3PrfIcXTN+E+GFAv6T5nbT9jd50/WFxb5ksdAv49qS6ouymG66ji08UMT6moykYLAo+V0j23GN4m829ZySAD5K7QsBfQTvOG8eE+gTeGYRAmnNAubN3hf5Zv9tJWDHp/VTuaSm7SN4fyINQqaNO3RMVxvpSPXnOChnRNvFcGY0gnwiPswYwTKVPE0zVtX3mTEIOoFzaqLrGuJaV+Uqumb71fVk/VoOH3cdLNQP/FHi8hV0CQNoqBZsUPlLPMsdCJro9QAaQQ0woDy9BJm0eTxCFnO9srcYlhNVlfR2EyTrph1uUtbUtAJifwRgrKuYdXVHeb0YI3QpawohQHkloI3J5FuVwI5ORxC9k2Tuz9Ir1IjgeIPGMHYkAZe2RuYkmWFmt3gGbTPOmBUWVTmRmHtGrfpzG/yuQNOKa6gBB/WA9khitPgl6/GP+gl2Af6tCbvaygAAAABJRU5ErkJggg=="});const tilePos=vec2(),tileSize=vec2(8),padding=1,bleed=0;const textureInfo=new TextureInfo(image);const tileInfo=new TileInfo(tilePos,tileSize,textureInfo,padding,bleed);engineImageFont=new ImageFont(tileInfo)}let mousePos=vec2();let mousePosScreen=vec2();let mouseDelta=vec2();let mouseDeltaScreen=vec2();let mouseWheel=0;let mouseInWindow=true;let isUsingGamepad=false;let lastInputDevice="mouse";let inputMouseMoveThreshold=6;let inputPreventDefault=true;let gamepadPrimary=0;const isTouchDevice=!headlessMode&&window.ontouchstart!==undefined;function setInputPreventDefault(preventDefault=true){inputPreventDefault=preventDefault}function setInputMouseMoveThreshold(threshold){inputMouseMoveThreshold=threshold}function usingMouseInput(){return lastInputDevice==="mouse"}function usingKeyboardInput(){return lastInputDevice==="keyboard"}function usingGamepadInput(){return lastInputDevice==="gamepad"}function inputClearKey(key,device=0,clearDown=true,clearPressed=true,clearReleased=true){if(!inputData[device])return;inputData[device][key]&=~((clearDown?1:0)|(clearPressed?2:0)|(clearReleased?4:0))}function inputClear(){inputData.length=0;inputData[0]=[];touchGamepadButtons.length=0;touchGamepadSticks.length=0;touchGamepadStickPointerId.length=0;gamepadStickData.length=0;gamepadDpadData.length=0;gamepadAxisCentered.length=0}function keyIsDown(key,device=0){ASSERT(isStringLike(key),"key must be a number or string");ASSERT(device>0||typeof key!=="number"||key<3,"use code string for keyboard");return!!(inputData[device]?.[key]&1)}function keyWasPressed(key,device=0){ASSERT(isStringLike(key),"key must be a number or string");ASSERT(device>0||typeof key!=="number"||key<3,"use code string for keyboard");return!!(inputData[device]?.[key]&2)}function keyWasReleased(key,device=0){ASSERT(isStringLike(key),"key must be a number or string");ASSERT(device>0||typeof key!=="number"||key<3,"use code string for keyboard");return!!(inputData[device]?.[key]&4)}function keyDirection(up="ArrowUp",down="ArrowDown",left="ArrowLeft",right="ArrowRight"){ASSERT(isStringLike(up),"up key must be a string");ASSERT(isStringLike(down),"down key must be a string");ASSERT(isStringLike(left),"left key must be a string");ASSERT(isStringLike(right),"right key must be a string");const k=key=>keyIsDown(key)?1:0;return vec2(k(right)-k(left),k(up)-k(down))}function mouseIsDown(button){ASSERT(isNumber(button),"mouse button must be a number");return keyIsDown(button)}function mouseWasPressed(button){ASSERT(isNumber(button),"mouse button must be a number");return keyWasPressed(button)}function mouseWasReleased(button){ASSERT(isNumber(button),"mouse button must be a number");return keyWasReleased(button)}function gamepadIsDown(button,gamepad=gamepadPrimary){ASSERT(isNumber(button),"button must be a number");ASSERT(isNumber(gamepad),"gamepad must be a number");return keyIsDown(button,gamepad+1)}function gamepadWasPressed(button,gamepad=gamepadPrimary){ASSERT(isNumber(button),"button must be a number");ASSERT(isNumber(gamepad),"gamepad must be a number");return keyWasPressed(button,gamepad+1)}function gamepadWasReleased(button,gamepad=gamepadPrimary){ASSERT(isNumber(button),"button must be a number");ASSERT(isNumber(gamepad),"gamepad must be a number");return keyWasReleased(button,gamepad+1)}function gamepadStick(stick,gamepad=gamepadPrimary){ASSERT(isNumber(stick),"stick must be a number");ASSERT(isNumber(gamepad),"gamepad must be a number");return gamepadStickData[gamepad]?.[stick]??vec2()}function gamepadDpad(gamepad=gamepadPrimary){ASSERT(isNumber(gamepad),"gamepad must be a number");return gamepadDpadData[gamepad]??vec2()}function gamepadConnected(gamepad=gamepadPrimary){ASSERT(isNumber(gamepad),"gamepad must be a number");return!!inputData[gamepad+1]}function gamepadStickCount(gamepad=gamepadPrimary){ASSERT(isNumber(gamepad),"gamepad must be a number");return gamepadStickData[gamepad]?.length??0}function gamepadVibrate(gamepad=gamepadPrimary,duration=200,strongMagnitude=1,weakMagnitude=1,startDelay=0){ASSERT(isNumber(gamepad),"gamepad must be a number");if(!vibrateEnable||headlessMode)return;const pad=navigator?.getGamepads?.()[gamepad];pad?.vibrationActuator?.playEffect?.("dual-rumble",{duration:duration,strongMagnitude:strongMagnitude,weakMagnitude:weakMagnitude,startDelay:startDelay})}function gamepadVibrateStop(gamepad=gamepadPrimary){ASSERT(isNumber(gamepad),"gamepad must be a number");if(!vibrateEnable||headlessMode)return;const pad=navigator?.getGamepads?.()[gamepad];pad?.vibrationActuator?.reset?.()}function vibrate(pattern=100){ASSERT(isNumber(pattern)||isArray(pattern),"pattern must be a number or array");vibrateEnable&&!headlessMode&&navigator?.vibrate?.(pattern)}function vibrateStop(){vibrate(0)}function pointerLockRequest(){!isTouchDevice&&mainCanvas.requestPointerLock?.()}function pointerLockExit(){document.exitPointerLock?.()}function pointerLockIsActive(){return document.pointerLockElement===mainCanvas}const inputData=[[]];const gamepadStickData=[],gamepadDpadData=[],gamepadHadInput=[];const gamepadAxisCentered=[];const gamepadAxisCenteredFrames=15;const touchGamepadTimer=new Timer,touchGamepadButtons=[],touchGamepadSticks=[];const touchGamepadStickAnchors=[],touchGamepadStickPointerId=[];const touchGamepadPointerRole=new Map;let touchGamepadOverlay,touchGamepadStage,touchGamepadSvg,touchGamepadSvgEls;let touchGamepadSideZones=[],touchGamepadZoneC;let touchGamepadNeedRelayout=true,touchGamepadLastLayout;function inputInit(){if(headlessMode)return;document.addEventListener("keydown",onKeyDown);document.addEventListener("keyup",onKeyUp);document.addEventListener("mousedown",onMouseDown);document.addEventListener("mouseup",onMouseUp);document.addEventListener("mousemove",onMouseMove);document.addEventListener("mouseleave",onMouseLeave);document.addEventListener("wheel",onMouseWheel,{passive:false});document.addEventListener("contextmenu",onContextMenu);document.addEventListener("blur",onBlur);if(isTouchDevice&&touchInputEnable)touchInputInit();function onKeyDown(e){if(!e.repeat){inputData[0][e.code]=3;if(inputWASDEmulateDirection)inputData[0][remapKey(e.code)]=3}if(!inputPreventDefault||!e.cancelable||!document.hasFocus())return;if(e.ctrlKey||e.metaKey||e.altKey)return;if(isTextInput(e.target)||isTextInput(document.activeElement))return;const printable=typeof e.key==="string"&&e.key.length===1;const preventDefaultKeys=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Space","Tab","Backspace"];if(preventDefaultKeys.includes(e.code)||printable)e.preventDefault();function isTextInput(element){const tag=element?.tagName;const editable=element?.isContentEditable;return editable||["INPUT","TEXTAREA","SELECT"].includes(tag)}}function onKeyUp(e){inputData[0][e.code]=inputData[0][e.code]&2|4;if(inputWASDEmulateDirection){const remap=remapKey(e.code);inputData[0][remap]=inputData[0][remap]&2|4}}function remapKey(k){return inputWASDEmulateDirection?k==="KeyW"?"ArrowUp":k==="KeyS"?"ArrowDown":k==="KeyA"?"ArrowLeft":k==="KeyD"?"ArrowRight":k:k}function onMouseDown(e){if(isTouchDevice&&touchInputEnable)return;if(soundEnable&&!headlessMode&&audioContext&&!audioIsRunning())audioContext.resume();inputData[0][e.button]=3;const mousePosScreenLast=mousePosScreen;mousePosScreen=mouseEventToScreen(vec2(e.x,e.y));mouseDeltaScreen=mouseDeltaScreen.add(mousePosScreen.subtract(mousePosScreenLast));if(inputPreventDefault&&e.cancelable&&document.hasFocus())e.preventDefault()}function onMouseUp(e){if(isTouchDevice&&touchInputEnable)return;inputData[0][e.button]=inputData[0][e.button]&2|4}function onMouseMove(e){mouseInWindow=true;const mousePosScreenLast=mousePosScreen;mousePosScreen=mouseEventToScreen(vec2(e.x,e.y));const movement=pointerLockIsActive()?vec2(e.movementX,e.movementY):mousePosScreen.subtract(mousePosScreenLast);mouseDeltaScreen=mouseDeltaScreen.add(movement)}function onMouseLeave(){mouseInWindow=false}function onMouseWheel(e){if(!e.ctrlKey)mouseWheel+=sign(e.deltaY);if(inputPreventDefault&&e.cancelable&&document.hasFocus())e.preventDefault()}function onContextMenu(e){e.preventDefault()}function onBlur(){inputClear();touchGamepadPointerRole.clear();touchGamepadButtons.length=0;touchGamepadSticks.length=0;touchGamepadStickPointerId.length=0}function touchInputInit(){document.addEventListener("touchstart",e=>handleTouch(e),{passive:false});document.addEventListener("touchmove",e=>handleTouch(e),{passive:false});document.addEventListener("touchend",e=>handleTouch(e),{passive:false});let wasTouching,touchIdentifier;function handleTouch(e){if(!touchInputEnable)return;if(soundEnable&&!headlessMode&&audioContext&&!audioIsRunning())audioContext.resume();if(!touchGamepadEnable||touchGamepadPassthrough){const isGamepadTouch=t=>touchGamepadSideZones.includes(t.target)||t.target===touchGamepadZoneC;const gameTouches=[];for(const t of e.touches)if(!isGamepadTouch(t))gameTouches.push(t);const touching=gameTouches.length;const button=0;if(touching){const pos=vec2(gameTouches[0].clientX,gameTouches[0].clientY);const mousePosScreenLast=mousePosScreen;mousePosScreen=mouseEventToScreen(pos);if(wasTouching&&gameTouches[0].identifier===touchIdentifier)mouseDeltaScreen=mouseDeltaScreen.add(mousePosScreen.subtract(mousePosScreenLast));else if(!wasTouching)inputData[0][button]=3;touchIdentifier=gameTouches[0].identifier}else if(wasTouching)inputData[0][button]=inputData[0][button]&2|4;wasTouching=touching}if(inputPreventDefault&&e.cancelable&&document.hasFocus())e.preventDefault();return true}}function mouseEventToScreen(mousePos){const rect=mainCanvas.getBoundingClientRect();const px=percent(mousePos.x,rect.left,rect.right);const py=percent(mousePos.y,rect.top,rect.bottom);return vec2(px*mainCanvas.width,py*mainCanvas.height)}}function inputUpdate(){if(headlessMode)return;if(!(touchInputEnable&&isTouchDevice)&&!document.hasFocus())inputClear();mousePos=screenToWorld(mousePosScreen);mouseDelta=screenToWorldDelta(mouseDeltaScreen);touchGamepadInit();gamepadsUpdate();updateLastInputDevice();function updateLastInputDevice(){const mouseActive=mouseIsDown(0)||mouseIsDown(1)||mouseIsDown(2)||mouseDeltaScreen.length()>inputMouseMoveThreshold;let gamepadActive=false;for(let s=gamepadStickCount();s--&&!gamepadActive;)gamepadActive=gamepadStick(s).lengthSquared()>.2;for(let b=17;b--&&!gamepadActive;)gamepadActive=gamepadIsDown(b);let keyboardActive=false;for(const k in inputData[0])if(isNaN(+k)&&inputData[0][k]&1){keyboardActive=true;break}if(gamepadActive)lastInputDevice="gamepad";else if(mouseActive)lastInputDevice="mouse";else if(keyboardActive)lastInputDevice="keyboard";isUsingGamepad=lastInputDevice==="gamepad"}function gamepadsUpdate(){const deadZoneMin=.3,deadZoneMax=.8;const applyDeadZones=v=>{const deadZone=v=>v>deadZoneMin?percent(v,deadZoneMin,deadZoneMax):v<-deadZoneMin?-percent(-v,deadZoneMin,deadZoneMax):0;return vec2(deadZone(v.x),deadZone(-v.y)).clampLength()};if(touchGamepadEnable&&isTouchDevice){ASSERT(!touchGamepadLeftStick||!touchGamepadLeftButtonCount,"set touchGamepadLeftStick or touchGamepadLeftButtonCount, not both");ASSERT(!touchGamepadRightStick||!touchGamepadButtonCount,"set touchGamepadRightStick or touchGamepadButtonCount, not both");if(!touchGamepadTimer.isSet())return;gamepadPrimary=0;const sticks=gamepadStickData[0]??(gamepadStickData[0]=[]);const dpad=gamepadDpadData[0]??(gamepadDpadData[0]=vec2());sticks.length=0;dpad.set();for(let side=0;side<2;side++){if(!touchGamepadSideStick(side))continue;const out=touchGamepadStickOut(side);sticks[out]=vec2();const touchStick=touchGamepadSticks[side]??vec2();if(touchGamepadAnalog)sticks[out]=applyDeadZones(touchStick);else if(touchStick.lengthSquared()>.3){const x=clamp(round(touchStick.x),-1,1);const y=clamp(round(touchStick.y),-1,1);sticks[out]=vec2(x,-y).clampLength();if(!out)dpad.set(x,-y)}}const data=inputData[1]??(inputData[1]=[]);for(let i=12;i--;){const wasDown=gamepadIsDown(i,0);data[i]=touchGamepadButtons[i]?wasDown?1:3:wasDown?4:0;if(touchGamepadVibration&&data[i]===3&&(i===9||touchGamepadIsFaceButton(i)))vibrate(touchGamepadVibration)}return}try{if(!gamepadsEnable||!navigator?.getGamepads)return}catch(e){return}if(!debug&&!document.hasFocus())return;const maxGamepads=8;const gamepads=navigator.getGamepads();const gamepadCount=min(maxGamepads,gamepads.length);for(let i=0;i<gamepadCount;++i){const gamepad=gamepads[i];if(!gamepad){inputData[i+1]=undefined;gamepadStickData[i]=undefined;gamepadDpadData[i]=undefined;gamepadHadInput[i]=undefined;gamepadAxisCentered[i]=undefined;continue}const data=inputData[i+1]??(inputData[i+1]=[]);const sticks=gamepadStickData[i]??(gamepadStickData[i]=[]);const dpad=gamepadDpadData[i]??(gamepadDpadData[i]=vec2());const isStandard=gamepad.mapping==="standard";const centered=gamepadAxisCentered[i]??(gamepadAxisCentered[i]=[]);const readAxis=j=>{const v=gamepad.axes[j];if(isStandard&&j<4)return v;if(!gamepadAxisFilterEnable)return v;const frames=centered[j]|0;if(frames>gamepadAxisCenteredFrames)return v;centered[j]=abs(v)<deadZoneMin?frames+1:0;return 0};for(let j=0;j<gamepad.axes.length-1;j+=2)sticks[j>>1]=applyDeadZones(vec2(readAxis(j),readAxis(j+1)));let hadInput=false;for(let j=gamepad.buttons.length;j--;){const button=gamepad.buttons[j];const wasDown=gamepadIsDown(j,i);data[j]=button.pressed?wasDown?1:3:wasDown?4:0;if(button.pressed&&(!button.value||button.value>.9))hadInput=true}if(hadInput){gamepadHadInput[i]=true;if(!gamepadHadInput[gamepadPrimary])gamepadPrimary=i}if(gamepad.mapping==="standard"){dpad.set((gamepadIsDown(15,i)&&1)-(gamepadIsDown(14,i)&&1),(gamepadIsDown(12,i)&&1)-(gamepadIsDown(13,i)&&1))}if(gamepadDirectionEmulateStick&&(dpad.x||dpad.y))sticks[0]=dpad.clampLength()}touchGamepadEnable&&isUsingGamepad&&touchGamepadTimer.unset()}}function inputUpdatePost(){if(headlessMode)return;for(const deviceInputData of inputData)for(const i in deviceInputData)deviceInputData[i]&=1;mouseWheel=0;mouseDelta=vec2();mouseDeltaScreen=vec2()}function inputRender(){touchGamepadRender()}const touchGamepadSvgNS="http://www.w3.org/2000/svg";function touchGamepadInit(){if(touchGamepadOverlay||!touchGamepadEnable||!isTouchDevice||headlessMode||!document.body)return;const overlay=touchGamepadOverlay=document.createElement("div");overlay.style.cssText="position:fixed;inset:0;z-index:50;pointer-events:none;opacity:0;"+"touch-action:none;user-select:none;-webkit-user-select:none;"+"-webkit-touch-callout:none;transition:opacity .2s;box-sizing:border-box;"+"padding:env(safe-area-inset-top) env(safe-area-inset-right) "+"env(safe-area-inset-bottom) env(safe-area-inset-left)";const stage=touchGamepadStage=document.createElement("div");stage.style.cssText="position:relative;width:100%;height:100%;pointer-events:none";overlay.appendChild(stage);const svg=touchGamepadSvg=document.createElementNS(touchGamepadSvgNS,"svg");svg.style.cssText="position:absolute;inset:0;width:100%;height:100%;"+"pointer-events:none;overflow:visible;fill:none;stroke:#fff;stroke-width:3";stage.appendChild(svg);const makeZone=()=>{const z=document.createElement("div");z.style.cssText="position:absolute;pointer-events:auto;touch-action:none";z.addEventListener("pointerdown",e=>touchGamepadPointerDown(e,z));z.addEventListener("pointermove",e=>touchGamepadPointerMove(e));z.addEventListener("pointerup",e=>touchGamepadPointerUp(e));z.addEventListener("pointercancel",e=>touchGamepadPointerUp(e));stage.appendChild(z);return z};touchGamepadSideZones[0]=makeZone();touchGamepadSideZones[1]=makeZone();touchGamepadZoneC=makeZone();addEventListener("resize",()=>touchGamepadNeedRelayout=true);document.body.appendChild(overlay);touchGamepadNeedRelayout=true}function touchGamepadStageRect(){return touchGamepadStage.getBoundingClientRect()}function touchGamepadSideStick(side){return side?touchGamepadRightStick:touchGamepadLeftStick}function touchGamepadSideButtonCount(side){return side?touchGamepadButtonCount:touchGamepadLeftButtonCount}function touchGamepadSideButtonBase(side){return side?0:4}function touchGamepadStickOut(side){return side&&touchGamepadLeftStick?1:0}function touchGamepadSideHasControl(side){return touchGamepadSideStick(side)||touchGamepadSideButtonCount(side)>0}function touchGamepadIsFaceButton(i){for(let side=0;side<2;side++){const base=touchGamepadSideButtonBase(side);if(!touchGamepadSideStick(side)&&i>=base&&i<base+touchGamepadSideButtonCount(side))return true}return false}function touchGamepadSideCenter(side,W,H){if(touchGamepadFloating&&touchGamepadSideStick(side)&&touchGamepadStickAnchors[side])return touchGamepadStickAnchors[side];let y=H-touchGamepadSize;const count=touchGamepadSideButtonCount(side);if(!touchGamepadSideStick(side)&&(count===2||count===3))y-=touchGamepadSize/4;return vec2(side?W-touchGamepadSize:touchGamepadSize,y)}function touchGamepadRelayout(){if(!touchGamepadOverlay)return;const r=touchGamepadStageRect();const W=r.width,H=r.height,S=touchGamepadSize;const setZone=(z,css)=>z.style.cssText="position:absolute;pointer-events:auto;touch-action:none;"+css;if(paused){for(const zone of touchGamepadSideZones)zone.style.display="none";if(touchGamepadCenterButtonSize){setZone(touchGamepadZoneC,"inset:0");touchGamepadZoneC.style.display=""}else touchGamepadZoneC.style.display="none"}else{for(let side=0;side<2;side++){const zone=touchGamepadSideZones[side],edge=side?"right":"left";zone.style.display=touchGamepadSideHasControl(side)?"":"none";if(touchGamepadFloating){const width=touchGamepadSideHasControl(side?0:1)?"50%":"100%";setZone(zone,`${edge}:0;bottom:0;width:${width};height:60%`)}else setZone(zone,`${edge}:0;bottom:0;width:${3*S}px;height:${3*S}px`)}touchGamepadZoneC.style.display=touchGamepadCenterButtonSize?"":"none";const c=touchGamepadCenterButtonSize;setZone(touchGamepadZoneC,`left:50%;top:50%;width:${2*c}px;height:${2*c}px;transform:translate(-50%,-50%)`)}touchGamepadBuildSvg(W,H);touchGamepadNeedRelayout=false}function touchGamepadBuildSvg(W,H){const svg=touchGamepadSvg;while(svg.firstChild)svg.removeChild(svg.firstChild);const els=touchGamepadSvgEls={face:[],thumb:[]};const S=touchGamepadSize;const circle=(cx,cy,rr,fill)=>{const c=document.createElementNS(touchGamepadSvgNS,"circle");c.setAttribute("cx",cx);c.setAttribute("cy",cy);c.setAttribute("r",rr);if(fill)c.setAttribute("fill",fill);svg.appendChild(c);return c};const cross=ctr=>{const a=S*.18,b=S*.5,x=ctr.x,y=ctr.y;const p=document.createElementNS(touchGamepadSvgNS,"path");p.setAttribute("d",`M ${x-a} ${y-b} H ${x+a} V ${y-a} H ${x+b} V ${y+a} H ${x+a} `+`V ${y+b} H ${x-a} V ${y+a} H ${x-b} V ${y-a} H ${x-a} Z`);svg.appendChild(p)};for(let side=0;side<2;side++){const count=touchGamepadSideButtonCount(side);const base=touchGamepadSideButtonBase(side);const ctr=touchGamepadSideCenter(side,W,H);if(touchGamepadSideStick(side)){if(touchGamepadAnalog)circle(ctr.x,ctr.y,S/2);else cross(ctr);els.thumb[side]=circle(ctr.x,ctr.y,S/4,"#fff")}else if(count===1)els.face[base]=circle(ctr.x,ctr.y,S/2,"#000");else for(let i=0;i<count;i++){const j=mod(i-1,4);let button=count>2?j:min(j,count-1);button=button===3?2:button===2?3:button;const offset=vec2().setDirection(j,S/2);if(count===2)offset.x*=-1;if(!side)offset.x*=-1;const pos=ctr.add(offset);els.face[base+button]=circle(pos.x,pos.y,S/4,"#000")}}if(debug&&debugGamepads)touchGamepadBuildDebug(W,H)}function touchGamepadBuildDebug(W,H){const S=touchGamepadSize,svg=touchGamepadSvg;const shape=(tag,attrs,stroke)=>{const el=document.createElementNS(touchGamepadSvgNS,tag);for(const k in attrs)el.setAttribute(k,attrs[k]);el.setAttribute("stroke",stroke);el.setAttribute("stroke-width",2);el.setAttribute("fill","none");svg.appendChild(el)};const ring=(c,rr,stroke)=>shape("circle",{cx:c.x,cy:c.y,r:rr},stroke);shape("line",{x1:W/2,y1:0,x2:W/2,y2:H},"#0f0");for(let side=0;side<2;side++){if(touchGamepadSideStick(side)){if(touchGamepadFloating){const top=H*.4,full=!touchGamepadSideHasControl(side?0:1);const x=full?0:side?W/2:0;shape("rect",{x:x,y:top,width:full?W:W/2,height:H-top},"#0ff")}else ring(touchGamepadSideCenter(side,W,H),2*S,"#0ff")}else if(touchGamepadSideButtonCount(side)>=1)ring(touchGamepadSideCenter(side,W,H),S,"#0ff")}if(touchGamepadCenterButtonSize){ring(vec2(W/2,H/2),touchGamepadCenterButtonSize,"#ff0");for(let side=0;side<2;side++)if(touchGamepadSideHasControl(side))ring(touchGamepadSideCenter(side,W,H),2*S,"#f0f")}}function touchGamepadRender(){if(!touchGamepadOverlay||headlessMode)return;if(!touchGamepadEnable||!isTouchDevice){if(touchGamepadOverlay.style.display!=="none"){touchGamepadOverlay.style.display="none";touchGamepadPointerRole.clear();touchGamepadButtons.length=0;touchGamepadSticks.length=0;touchGamepadStickPointerId.length=0}return}touchGamepadOverlay.style.display="";const dbg=debug&&debugGamepads;const layout=[touchGamepadButtonCount,touchGamepadLeftButtonCount,touchGamepadLeftStick,touchGamepadRightStick,touchGamepadAnalog,touchGamepadSize,touchGamepadFloating,touchGamepadCenterButtonSize,paused,dbg].join();if(layout!==touchGamepadLastLayout){touchGamepadLastLayout=layout;touchGamepadNeedRelayout=true}if(touchGamepadNeedRelayout)touchGamepadRelayout();const fade=touchGamepadDisplayTime?percent(touchGamepadTimer.get(),touchGamepadDisplayTime+1,touchGamepadDisplayTime):1;const visible=dbg||touchGamepadTimer.isSet()&&fade>0&&!paused;touchGamepadOverlay.style.opacity=!visible?0:dbg?1:fade*touchGamepadAlpha;if(!visible)return;const r=touchGamepadStageRect();const W=r.width,H=r.height,S=touchGamepadSize;const els=touchGamepadSvgEls;if(!els)return;for(let side=0;side<2;side++)if(touchGamepadSideStick(side)&&els.thumb[side]){const ctr=touchGamepadSideCenter(side,W,H);const t=ctr.add((touchGamepadSticks[side]??vec2()).scale(S/2));els.thumb[side].setAttribute("cx",t.x);els.thumb[side].setAttribute("cy",t.y)}for(let i=0;i<els.face.length;i++)if(els.face[i])els.face[i].setAttribute("fill",touchGamepadButtons[i]?"#fff":"#000")}function touchGamepadEventPos(e){const r=touchGamepadStageRect();return vec2(e.clientX-r.left,e.clientY-r.top)}function touchGamepadApplyStick(side,p){const delta=p.subtract(touchGamepadStickAnchors[side]);touchGamepadSticks[side]=delta.scale(2/touchGamepadSize).clampLength();touchGamepadButtons[touchGamepadStickOut(side)?11:10]=1}function touchGamepadFaceButtonAt(side,p,W,H){const count=touchGamepadSideButtonCount(side);const base=touchGamepadSideButtonBase(side);const bc=touchGamepadSideCenter(side,W,H);if(bc.distance(p)>=touchGamepadSize)return-1;if(count===1)return base;const d=bc.subtract(p);if(!side)d.x*=-1;let button=count===2?d.x<d.y?1:0:mod(d.direction()+2,4);button=button===3?2:button===2?3:button;return button<count?base+button:-1}function touchGamepadControlAt(p,W,H){const S=touchGamepadSize;const leftHalf=p.x<W/2;const floatTop=H*.4;for(let side=0;side<2;side++){const onHalf=side?!leftHalf:leftHalf;if(touchGamepadSideStick(side)){const otherControl=touchGamepadSideHasControl(side?0:1);const grab=touchGamepadFloating?(!otherControl||onHalf)&&p.y>floatTop:onHalf&&touchGamepadSideCenter(side,W,H).distance(p)<2*S;if(grab)return{role:"stick",side:side}}else if(touchGamepadSideButtonCount(side)>=1){const btn=touchGamepadFaceButtonAt(side,p,W,H);if(btn>=0)return{role:"face",btn:btn}}}if(touchGamepadCenterButtonSize){for(let side=0;side<2;side++)if(touchGamepadSideHasControl(side)&&touchGamepadSideCenter(side,W,H).distance(p)<2*S)return;if(vec2(W/2,H/2).distance(p)<touchGamepadCenterButtonSize)return{role:"start"}}}function touchGamepadPointerDown(e,zone){if(!touchGamepadEnable)return;e.preventDefault();zone.setPointerCapture(e.pointerId);touchGamepadTimer.set();if(soundEnable&&!headlessMode&&audioContext&&!audioIsRunning())audioContext.resume();if(paused){if(touchGamepadCenterButtonSize){touchGamepadButtons[9]=1;touchGamepadPointerRole.set(e.pointerId,"start")}return}const r=touchGamepadStageRect();const W=r.width,H=r.height;const p=vec2(e.clientX-r.left,e.clientY-r.top);const hit=touchGamepadControlAt(p,W,H);if(!hit)return;if(hit.role==="stick"){const side=hit.side;touchGamepadStickAnchors[side]=touchGamepadFloating?p:touchGamepadSideCenter(side,W,H);touchGamepadStickPointerId[side]=e.pointerId;touchGamepadPointerRole.set(e.pointerId,"stick"+side);touchGamepadNeedRelayout=true;touchGamepadApplyStick(side,p)}else if(hit.role==="face"){touchGamepadButtons[hit.btn]=1;touchGamepadPointerRole.set(e.pointerId,"face"+hit.btn)}else{touchGamepadButtons[9]=1;touchGamepadPointerRole.set(e.pointerId,"start")}}function touchGamepadPointerMove(e){const role=touchGamepadPointerRole.get(e.pointerId);if(!role)return;e.preventDefault();const p=touchGamepadEventPos(e);if(role==="stick0"||role==="stick1")touchGamepadApplyStick(role==="stick1"?1:0,p)}function touchGamepadPointerUp(e){const role=touchGamepadPointerRole.get(e.pointerId);if(!role)return;touchGamepadPointerRole.delete(e.pointerId);if(role==="stick0"||role==="stick1"){const side=role==="stick1"?1:0;touchGamepadStickPointerId[side]=undefined;touchGamepadSticks[side]=vec2();delete touchGamepadButtons[touchGamepadStickOut(side)?11:10]}else if(role==="start")delete touchGamepadButtons[9];else delete touchGamepadButtons[+role.slice(4)];touchGamepadTimer.set()}let audioContext=new AudioContext;let audioMasterGain;const audioDefaultSampleRate=44100;function audioIsRunning(){return audioContext.state==="running"}function audioInit(){if(!soundEnable||headlessMode)return;audioMasterGain=audioContext.createGain();audioMasterGain.connect(audioContext.destination);audioMasterGain.gain.value=soundVolume}class Sound{constructor(asset,randomness,range=soundDefaultRange,taper=soundDefaultTaper,onloadCallback){if(!soundEnable||headlessMode)return;ASSERT(!asset||isArray(asset)||isStringLike(asset),"asset must be a file name or zzfx array");ASSERT(randomness===undefined||isNumber(randomness),"randomness must be a number");ASSERT(randomness===undefined||randomness>=0&&randomness<=1,"randomness must be between 0 and 1");ASSERT(isNumber(range),"range must be a number");ASSERT(isNumber(taper),"taper must be a number");this.range=range;this.taper=taper;this.randomness=randomness??0;this.sampleRate=audioDefaultSampleRate;this.sampleLength=0;this.sampleBuffer=undefined;this._sampleChannels=undefined;this.loadedPercent=0;this.onloadCallback=onloadCallback;if(isArray(asset)){const zzfxSound=asset.slice();const defaultRandomness=randomness??.05;const randomnessIndex=1;this.randomness=zzfxSound[randomnessIndex]??defaultRandomness;zzfxSound[randomnessIndex]=0;this.sampleChannels=[zzfxG(...zzfxSound)];this.buildSampleBuffer();this.loadedPercent=1;onloadCallback?.(this)}else if(typeof asset==="string"){const filename=asset;this.loadSound(filename).catch(e=>LOG("Sound load failed for",filename,"-",e.message))}}get sampleChannels(){const buffer=this.sampleBuffer;if(!this._sampleChannels&&buffer){const channels=[];for(let i=0;i<buffer.numberOfChannels;i++)channels.push(buffer.getChannelData(i).slice());this._sampleChannels=channels}return this._sampleChannels}set sampleChannels(sampleChannels){this._sampleChannels=sampleChannels;this.sampleBuffer=undefined;this.sampleLength=sampleChannels?.[0]?.length||0}buildSampleBuffer(){if(this.sampleBuffer||!this._sampleChannels||headlessMode)return;this.sampleBuffer=createAudioBuffer(this._sampleChannels,this.sampleRate);this._sampleChannels=undefined}play(pos,volume=1,pitch=1,randomnessScale=1,loop=false,paused=false){ASSERT(!pos||isVector2(pos),"pos must be a vec2");ASSERT(isNumber(volume),"volume must be a number");ASSERT(isNumber(pitch),"pitch must be a number");ASSERT(isNumber(randomnessScale),"randomnessScale must be a number");if(!soundEnable||headlessMode)return;if(!this.sampleBuffer&&!this._sampleChannels)return;let pan;if(pos){const range=this.range;if(range){const lengthSquared=cameraPos.distanceSquared(pos);if(lengthSquared>range*range)return;volume*=percent(lengthSquared**.5,range,range*this.taper)}pan=worldToScreen(pos).x*2/mainCanvas.width-1}const rate=pitch+pitch*this.randomness*randomnessScale*rand(-1,1);const instance=new SoundInstance(this,volume,rate,pan,loop,paused);if(debug&&debugSound&&pos){debugCircle(pos,.5,"#0ff",.5,true);if(this.range){debugCircle(pos,2*this.range,"#0ff",.5);debugCircle(pos,2*this.range*this.taper,"#0ff",.5)}debugText("vol "+volume.toFixed(2)+" pitch "+rate.toFixed(2),pos,.5,"#0ff",.5)}return instance}playMusic(volume=1,loop=true,paused=false){return this.play(undefined,volume,1,0,loop,paused)}playNote(semitoneOffset=0,pos,volume){ASSERT(isNumber(semitoneOffset),"semitoneOffset must be a number");const pitch=getNoteFrequency(semitoneOffset,1);return this.play(pos,volume,pitch,0)}getDuration(){return this.sampleLength/this.sampleRate||0}isLoaded(){return this.loadedPercent===1}async loadSound(filename){const response=await fetch(filename);if(!response.ok)throw new Error(`Failed to load sound from ${filename}: ${response.status} ${response.statusText}`);const arrayBuffer=await response.arrayBuffer();const audioBuffer=await audioContext.decodeAudioData(arrayBuffer);this.sampleRate=audioBuffer.sampleRate;this.sampleLength=audioBuffer.length;this.sampleBuffer=audioBuffer;this.loadedPercent=1;this.onloadCallback?.(this)}}class SoundInstance{constructor(sound,volume=1,rate=1,pan=0,loop=false,paused=false){ASSERT(sound instanceof Sound,"SoundInstance requires a valid Sound object");ASSERT(volume>=0,"Sound volume must be positive or zero");ASSERT(rate>=0,"Sound rate must be positive or zero");ASSERT(isNumber(pan),"Sound pan must be a number");this.sound=sound;this.volume=volume;this.rate=rate;this.pan=pan;this.loop=loop;this.pausedTime=0;this.startTime=undefined;this.gainNode=undefined;this.source=undefined;this.onendedCallback=source=>{if(source===this.source)this.source=undefined};if(!paused)this.start()}start(offset=0){ASSERT(offset>=0,"Sound start offset must be positive or zero");if(this.isPlaying())this.stop();this.gainNode=audioContext.createGain();this.sound.buildSampleBuffer();this.source=this.sound.sampleBuffer?playAudioBuffer(this.sound.sampleBuffer,this.volume,this.rate,this.pan,this.loop,this.gainNode,offset,this.onendedCallback):playSamples(this.sound.sampleChannels,this.volume,this.rate,this.pan,this.loop,this.sound.sampleRate,this.gainNode,offset,this.onendedCallback);if(this.source){this.startTime=audioContext.currentTime-offset;this.pausedTime=undefined}else{this.startTime=undefined;this.pausedTime=0}}setVolume(volume){ASSERT(volume>=0,"Sound volume must be positive or zero");this.volume=volume;if(this.gainNode)this.gainNode.gain.value=volume}stop(fadeTime=0){ASSERT(fadeTime>=0,"Sound fade time must be positive or zero");if(this.isPlaying()){if(fadeTime){const startFade=audioContext.currentTime;const endFade=startFade+fadeTime;this.gainNode.gain.cancelScheduledValues(startFade);this.gainNode.gain.setValueAtTime(this.volume,startFade);this.gainNode.gain.linearRampToValueAtTime(0,endFade);this.source.stop(endFade)}else this.source.stop()}this.pausedTime=0;this.source=undefined;this.startTime=undefined}pause(){if(this.isPaused())return;this.pausedTime=this.getCurrentTime();this.source.stop();this.source=undefined;this.startTime=undefined}resume(){if(!this.isPaused())return;this.start(this.pausedTime)}isPlaying(){return!!this.source}isPaused(){return!this.isPlaying()}getCurrentTime(){if(!this.isPlaying())return this.pausedTime;const duration=this.getDuration();return duration?mod(audioContext.currentTime-this.startTime,duration):0}getDuration(){return this.rate?this.sound.getDuration()/this.rate:0}getSource(){return this.source}}function speak(text,volume=1,rate=1,pitch=1,language=""){ASSERT(typeof volume!=="string","speak() signature changed: language is now the last parameter, after pitch");if(!soundEnable||headlessMode)return;if(typeof speechSynthesis==="undefined")return;const utterance=new SpeechSynthesisUtterance(text);utterance.lang=language;utterance.volume=volume*soundVolume;utterance.rate=rate;utterance.pitch=pitch;speechSynthesis.speak(utterance);return utterance}function speakStop(){if(typeof speechSynthesis!=="undefined")speechSynthesis.cancel()}function getNoteFrequency(semitoneOffset,rootFrequency=220){return rootFrequency*2**(semitoneOffset/12)}function playSamples(sampleChannels,volume=1,rate=1,pan=0,loop=false,sampleRate=audioDefaultSampleRate,gainNode,offset=0,onended){if(!soundEnable||headlessMode)return;if(!audioIsRunning()){audioContext.resume();return}const buffer=createAudioBuffer(sampleChannels,sampleRate);return playAudioBuffer(buffer,volume,rate,pan,loop,gainNode,offset,onended)}function createAudioBuffer(sampleChannels,sampleRate=audioDefaultSampleRate){const channelCount=sampleChannels.length;const sampleLength=sampleChannels[0].length;const buffer=audioContext.createBuffer(channelCount,sampleLength,sampleRate);sampleChannels.forEach((c,i)=>buffer.getChannelData(i).set(c));return buffer}function playAudioBuffer(buffer,volume=1,rate=1,pan=0,loop=false,gainNode,offset=0,onended){if(!soundEnable||headlessMode)return;if(!audioIsRunning()){audioContext.resume();return}const source=audioContext.createBufferSource();source.buffer=buffer;source.playbackRate.value=rate;source.loop=loop;gainNode=gainNode||audioContext.createGain();gainNode.gain.value=volume;gainNode.connect(audioMasterGain);const pannerNode=new StereoPannerNode(audioContext,{pan:clamp(pan,-1,1)});source.connect(pannerNode).connect(gainNode);source.addEventListener("ended",()=>{gainNode.disconnect();pannerNode.disconnect();if(onended)onended(source)});const startOffset=offset*rate;source.start(0,startOffset);if(debug&&debugSound)LOG("sound","vol",volume.toFixed(2),"rate",rate.toFixed(2),"pan",pan.toFixed(2),loop?"loop":"");return source}function zzfx(...zzfxSound){return playSamples([zzfxG(...zzfxSound)])}function zzfxG(volume=1,randomness=.05,frequency=220,attack=0,sustain=0,release=.1,shape=0,shapeCurve=1,slide=0,deltaSlide=0,pitchJump=0,pitchJumpTime=0,repeatTime=0,noise=0,modulation=0,bitCrush=0,delay=0,sustainVolume=1,decay=0,tremolo=0,filter=0){let sampleRate=audioDefaultSampleRate,PI2=PI*2,startSlide=slide*=500*PI2/sampleRate/sampleRate,startFrequency=frequency*=(1+rand(randomness,-randomness))*PI2/sampleRate,modOffset=0,repeat=0,crush=0,jump=1,length,b=[],t=0,i=0,s=0,f,quality=2,w=PI2*abs(filter)*2/sampleRate,cosw=cos(w),alpha=sin(w)/2/quality,a0=1+alpha,a1=-2*cosw/a0,a2=(1-alpha)/a0,b0=(1+sign(filter)*cosw)/2/a0,b1=-(sign(filter)+cosw)/a0,b2=b0,x2=0,x1=0,y2=0,y1=0;const minAttack=9;attack=attack*sampleRate||minAttack;decay*=sampleRate;sustain*=sampleRate;release*=sampleRate;delay*=sampleRate;deltaSlide*=500*PI2/sampleRate**3;modulation*=PI2/sampleRate;pitchJump*=PI2/sampleRate;pitchJumpTime*=sampleRate;repeatTime=repeatTime*sampleRate|0;for(length=attack+decay+sustain+release+delay|0;i<length;b[i++]=s*volume){if(!(++crush%(bitCrush*100|0))){s=shape?shape>1?shape>2?shape>3?shape>4?t/PI2%1<shapeCurve/2?1:-1:sin(t**3):max(min(tan(t),1),-1):1-(2*t/PI2%2+2)%2:1-4*abs(round(t/PI2)-t/PI2):sin(t);s=(repeatTime?1-tremolo+tremolo*sin(PI2*i/repeatTime):1)*(shape>4?s:sign(s)*abs(s)**shapeCurve)*(i<attack?i/attack:i<attack+decay?1-(i-attack)/decay*(1-sustainVolume):i<attack+decay+sustain?sustainVolume:i<length-delay?(length-i-delay)/release*sustainVolume:0);s=delay?s/2+(delay>i?0:(i<length-delay?1:(length-i)/delay)*b[i-delay|0]/2/volume):s;if(filter)s=y1=b2*x2+b1*(x2=x1)+b0*(x1=s)-a2*y2-a1*(y2=y1)}f=(frequency+=slide+=deltaSlide)*cos(modulation*modOffset++);t+=f+f*noise*sin(i**5);if(jump&&++jump>pitchJumpTime){frequency+=pitchJump;startFrequency+=pitchJump;jump=0}if(repeatTime&&!(++repeat%repeatTime)){frequency=startFrequency;slide=startSlide;jump||=1}}return b}const tileCollisionLayers=[];function tileCollisionGetData(pos,solidOnly=true){for(const layer of tileCollisionLayers)if(!solidOnly||layer.isSolid){const layerPos=pos.subtract(layer.pos);if(layerPos.arrayCheck(layer.size)){const data=layer.getCollisionData(layerPos);if(data)return data}}return 0}function tileCollisionTest(pos,size=vec2(),callbackObject,solidOnly=true){for(const layer of tileCollisionLayers){if(!solidOnly||layer.isSolid)if(layer.collisionTest(pos,size,callbackObject))return layer}}function tileCollisionRaycast(posStart,posEnd,callbackObject,normal,solidOnly=true){let closestHit,closestDistSq,closestNormal;const scratchNormal=normal&&vec2();for(const layer of tileCollisionLayers){if(!solidOnly||layer.isSolid){const hitPos=layer.collisionRaycast(posStart,posEnd,callbackObject,scratchNormal);if(hitPos){const d=posStart.distanceSquared(hitPos);if(closestHit===undefined||d<closestDistSq){closestHit=hitPos;closestDistSq=d;if(normal)closestNormal=scratchNormal.copy()}}}}if(closestHit&&normal)normal.setFrom(closestNormal);return closestHit}function tileLayersLoad(tileMapData,tileInfo=tile(),renderOrder=0,collisionLayer,draw=true){if(!tileMapData){const s=50;tileMapData={};tileMapData.height=tileMapData.width=s;tileMapData.layers=[{}];tileMapData.layers[0].data=new Array(s*s).fill(0)}ASSERT(tileMapData.width&&tileMapData.height);ASSERT(tileMapData.layers&&tileMapData.layers.length);const tileLayers=[];const levelSize=vec2(tileMapData.width,tileMapData.height);const layerCount=tileMapData.layers.length;for(let layerIndex=layerCount;layerIndex--;){const dataLayer=tileMapData.layers[layerIndex];ASSERT(dataLayer.data&&dataLayer.data.length);ASSERT(levelSize.area()===dataLayer.data.length);const layerRenderOrder=renderOrder-(layerCount-1-layerIndex);const tileLayer=new TileCollisionLayer(vec2(),levelSize,tileInfo,layerRenderOrder);tileLayers[layerIndex]=tileLayer;const layerColor=dataLayer.tintcolor?(new Color).setHex(dataLayer.tintcolor):dataLayer.color||WHITE;ASSERT(isColor(layerColor),"layer color is not a color");for(let x=levelSize.x;x--;)for(let y=levelSize.y;y--;){const pos=vec2(x,levelSize.y-1-y);const data=dataLayer.data[x+y*levelSize.x];if(data){const layerData=new TileLayerData(data-1,0,false,layerColor);tileLayer.setData(pos,layerData);if(layerIndex===collisionLayer)tileLayer.setCollisionData(pos,1)}}if(draw)tileLayer.redraw()}return tileLayers}class TileLayerData{constructor(tile,direction=0,mirror=false,color=new Color){this.tile=tile;this.direction=direction;this.mirror=mirror;this.color=color.copy()}clear(){this.tile=this.direction=0;this.mirror=false;this.color=new Color}}class CanvasLayer extends EngineObject{constructor(pos,size,angle=0,renderOrder=0,canvasSize=vec2(512),useWebGL=true){ASSERT(isVector2(canvasSize),"canvasSize must be a Vector2");super(pos,size,undefined,angle,WHITE,renderOrder);this.canvas=headlessMode?undefined:new OffscreenCanvas(canvasSize.x,canvasSize.y);this.context=this.canvas?.getContext("2d");this.textureInfo=new TextureInfo(this.canvas,useWebGL);this.mass=0}destroy(){if(this.destroyed)return;this.textureInfo.destroyWebGLTexture();super.destroy()}render(){this.draw(this.pos,this.size,this.color,this.angle,this.mirror,this.additiveColor)}draw(pos,size,color=WHITE,angle=0,mirror=false,additiveColor,screenSpace=false,context){const tileInfo=(new TileInfo).setFullImage(this.textureInfo);const useWebGL=this.hasWebGL();drawTile(pos,size,tileInfo,color,angle,mirror,additiveColor,useWebGL,screenSpace,context)}updateWebGL(){this.textureInfo.createWebGLTexture()}hasWebGL(){return glEnable&&this.textureInfo.hasWebGL()}}class TileLayer extends CanvasLayer{constructor(pos,size,tileInfo=tile(),renderOrder=0,useWebGL=true){const canvasSize=tileInfo?size.multiply(tileInfo.size):size;super(pos,size,0,renderOrder,canvasSize,useWebGL);this.tileInfo=undefined;this.data=[];this.isUsingWebGL=false;if(headlessMode){this.render=()=>{};this.redraw=()=>{};this.redrawStart=()=>{};this.redrawEnd=()=>{};this.drawTileData=()=>{};this.redrawTileData=()=>{};this.drawLayerTile=()=>{};this.drawLayerRect=()=>{};this.drawTile=()=>{};this.drawRect=()=>{};this.clearLayerRect=()=>{};return}if(tileInfo){this.tileInfo=tileInfo.frame(0);this.tileInfo.bleed=0}for(let j=this.size.area();j--;)this.data.push(new TileLayerData)}setData(layerPos,data,redraw=false){layerPos=layerPos.floor();ASSERT(isVector2(layerPos),"layerPos must be a Vector2");ASSERT(data instanceof TileLayerData,"data must be a TileLayerData");if(!layerPos.arrayCheck(this.size))return;this.data[(layerPos.y|0)*this.size.x+(layerPos.x|0)]=data;if(!redraw)return;const isRedraw=drawContext===this.context;isRedraw?this.drawTileData(layerPos):this.redrawTileData(layerPos)}clearData(layerPos,redraw=false){this.setData(layerPos,new TileLayerData,redraw)}getData(layerPos){ASSERT(isVector2(layerPos),"layerPos must be a Vector2");return layerPos.arrayCheck(this.size)?this.data[(layerPos.y|0)*this.size.x+(layerPos.x|0)]:undefined}update(){if(!glEnable&&this.isUsingWebGL){this.isUsingWebGL=false;this.redraw()}}render(){ASSERT(drawContext!==this.context,"must call redrawEnd() after drawing tiles!");const size=this.drawSize||this.size;const pos=this.pos.add(size.scale(.5));this.draw(pos,size,this.color,this.angle,this.mirror,this.additiveColor)}onRedraw(){}redraw(){this.redrawStart(true);for(let x=this.size.x;x--;)for(let y=this.size.y;y--;)this.drawTileData(vec2(x,y),false);this.isUsingWebGL&&glFlush();this.onRedraw();this.redrawEnd()}redrawStart(clear=false){if(!this.context)return;ASSERT(drawContext!==this.context);this.savedRenderSettings=[drawContext,mainCanvasSize,cameraPos,cameraScale,canvasClearColor];drawContext=this.context;const tileSize=this.tileInfo?.size??vec2(1);mainCanvasSize=this.size.multiply(tileSize);canvasClearColor=CLEAR_BLACK;cameraPos=this.size.multiply(tileSize).scale(.5);cameraScale=1;this.isUsingWebGL=this.hasWebGL();if(this.isUsingWebGL)glSetRenderTarget(this.textureInfo.glTexture,clear);else{this.context.imageSmoothingEnabled=!tilesPixelated;if(clear){this.canvas.width=mainCanvasSize.x;this.canvas.height=mainCanvasSize.y}}}redrawEnd(){if(!this.context)return;ASSERT(drawContext===this.context);if(this.isUsingWebGL)glSetRenderTarget();[drawContext,mainCanvasSize,cameraPos,cameraScale,canvasClearColor]=this.savedRenderSettings}drawTileData(layerPos,clear=true){if(!this.context)return;ASSERT(drawContext===this.context,"must call redrawStart() before drawing tiles");const drawSize=this.tileInfo?.size??vec2(1);const drawPos=layerPos.multiply(drawSize);clear&&this.clearLayerRect(drawPos,drawSize);const d=this.getData(layerPos);if(!d||!d.tile)return;const tileInfo=this.tileInfo&&this.tileInfo.index(d.tile);this.drawLayerTile(drawPos,drawSize,tileInfo,d.color,d.direction*PI/2,d.mirror)}redrawTileData(layerPos,clear=true){if(!this.context)return;ASSERT(drawContext!==this.context,"redrawStart() should not be active when calling redrawTileData(), instead use drawTileData()");this.redrawStart();this.drawTileData(layerPos,clear);this.redrawEnd()}drawLayerTile(pos,size=vec2(1),tileInfo,color=WHITE,angle=0,mirror,additiveColor){const drawPos=pos.add(size.scale(.5));drawTile(drawPos,size,tileInfo,color,angle,mirror,additiveColor,this.isUsingWebGL)}drawLayerRect(pos,size,color,angle=0){this.drawLayerTile(pos,size,undefined,color,angle)}drawTile(pos,size=vec2(1),tileInfo,color=new Color,angle=0,mirror=false){pos=pos.subtract(this.pos).multiply(this.tileInfo.size);size=size.multiply(this.tileInfo.size);pos.y=this.canvas.height-pos.y;const oldMainCanvasSize=mainCanvasSize;mainCanvasSize=vec2(this.canvas.width,this.canvas.height);const useWebGL=this.hasWebGL();useWebGL&&glSetRenderTarget(this.textureInfo.glTexture);const drawContext=useWebGL?undefined:this.context;drawTile(pos,size,tileInfo,color,angle,mirror,undefined,useWebGL,true,drawContext);useWebGL&&glSetRenderTarget();mainCanvasSize=oldMainCanvasSize}drawRect(pos,size,color,angle){this.drawTile(pos,size,undefined,color,angle)}clearLayerRect(pos,size){ASSERT(drawContext===this.context,"must call redrawStart() before clearing tiles");const x=pos.x,y=this.canvas.height-pos.y-size.y;const useWebGL=this.hasWebGL();if(useWebGL)glClearRect(x,y,size.x,size.y);else this.context.clearRect(x,y,size.x,size.y)}}class TileCollisionLayer extends TileLayer{constructor(pos,size,tileInfo=tile(),renderOrder=0,useWebGL=true){super(pos,size.floor(),tileInfo,renderOrder,useWebGL);this.collisionData=[];this.initCollision(this.size);tileCollisionLayers.push(this);this.isSolid=true}destroy(){if(this.destroyed)return;const index=tileCollisionLayers.indexOf(this);ASSERT(index>=0,"tile collision layer not found in array");index>=0&&tileCollisionLayers.splice(index,1);super.destroy()}initCollision(size){ASSERT(isVector2(size),"size must be a Vector2");this.size=size.floor();this.collisionData=[];this.collisionData.length=size.area();this.collisionData.fill(0)}setCollisionData(layerPos,data=1){ASSERT(isVector2(layerPos),"layerPos must be a Vector2");const i=(layerPos.y|0)*this.size.x+(layerPos.x|0);layerPos.arrayCheck(this.size)&&(this.collisionData[i]=data)}clearCollisionData(layerPos){this.setCollisionData(layerPos,0)}getCollisionData(layerPos){ASSERT(isVector2(layerPos),"layerPos must be a Vector2");const i=(layerPos.y|0)*this.size.x+(layerPos.x|0);return layerPos.arrayCheck(this.size)?this.collisionData[i]:0}collisionTest(pos,size=new Vector2,callbackObject){ASSERT(isVector2(pos)&&isVector2(size),"pos and size must be Vector2s");ASSERT(!callbackObject||typeof callbackObject==="function"||callbackObject instanceof EngineObject,"callbackObject must be a function or EngineObject");const collisionTest=callbackObject?typeof callbackObject==="function"?(tileData,pos)=>callbackObject(tileData,pos):(tileData,pos)=>callbackObject.collideWithTile(tileData,pos):()=>true;const posX=pos.x-this.pos.x;const posY=pos.y-this.pos.y;if(posX+size.x/2<0||posX-size.x/2>this.size.x)return false;if(posY+size.y/2<0||posY-size.y/2>this.size.y)return false;const minX=max(posX-size.x/2|0,0);const minY=max(posY-size.y/2|0,0);const maxX=min(max(posX+size.x/2,minX+1),this.size.x);const maxY=min(max(posY+size.y/2,minY+1),this.size.y);const hitPos=new Vector2;for(let y=minY;y<maxY;++y)for(let x=minX;x<maxX;++x){const tileData=this.collisionData[y*this.size.x+x];if(tileData&&collisionTest(tileData,hitPos.set(x+this.pos.x,y+this.pos.y)))return true}return false}collisionRaycast(posStart,posEnd,callbackObject,normal){ASSERT(isVector2(posStart)&&isVector2(posEnd),"positions must be Vector2s");ASSERT(!callbackObject||typeof callbackObject==="function"||callbackObject instanceof EngineObject,"callbackObject must be a function or EngineObject");const collisionTest=callbackObject?typeof callbackObject==="function"?(tileData,pos)=>callbackObject(tileData,pos):(tileData,pos)=>callbackObject.collideWithTile(tileData,pos):tileData=>tileData>0;const testFunction=pos=>{const tileData=this.getCollisionData(localPos.set(pos.x-this.pos.x,pos.y-this.pos.y));return tileData&&collisionTest(tileData,pos)};const localPos=new Vector2;const hitPos=lineTest(posStart,posEnd,testFunction,normal);if(debugRaycast&&hitPos){const tilePos=hitPos.floor().add(vec2(.5));debugRect(tilePos,vec2(1),"#f008");debugLine(posStart,posEnd,"#00f",.02);debugLine(posStart,hitPos,"#f00",.02);debugPoint(hitPos,"#0f0");normal&&debugLine(hitPos,hitPos.add(normal),"#ff0",.02)}return hitPos}}class ParticleEmitter extends EngineObject{constructor(pos,angle,emitSize=0,emitTime=0,emitRate=100,emitConeAngle=PI,tileInfo,colorStartA=WHITE,colorStartB=WHITE,colorEndA=CLEAR_WHITE,colorEndB=CLEAR_WHITE,particleTime=.5,sizeStart=.1,sizeEnd=1,speed=.1,angleSpeed=.05,damping=1,angleDamping=1,gravityScale=0,particleConeAngle=PI,fadeRate=.1,randomness=.2,collideTiles=false,additive=false,randomColorLinear=true,renderOrder=additive?1e9:0,localSpace=false){super(pos,vec2(),tileInfo,angle,undefined,renderOrder);this.emitCircle=typeof emitSize==="number";this.emitSize=typeof emitSize==="number"?vec2(emitSize):emitSize.copy();this.emitTime=emitTime;this.emitRate=emitRate;this.emitConeAngle=emitConeAngle;this.colorStartA=colorStartA.copy();this.colorStartB=colorStartB.copy();this.colorEndA=colorEndA.copy();this.colorEndB=colorEndB.copy();this.randomColorLinear=randomColorLinear;this.particleTime=particleTime;this.sizeStart=sizeStart;this.sizeEnd=sizeEnd;this.speed=speed;this.angleSpeed=angleSpeed;this.damping=damping;this.angleDamping=angleDamping;this.gravityScale=gravityScale;this.particleConeAngle=particleConeAngle;this.fadeRate=fadeRate;this.randomness=randomness;this.collideTiles=collideTiles;this.additive=additive;this.localSpace=localSpace;this.trailScale=0;this.particleCreateCallback=undefined;this.particleDestroyCallback=undefined;this.particleCollideCallback=undefined;this.velocityInheritance=0;this.emitTimeBuffer=0;this.particles=[];this.previousAngle=this.angle;this.previousPos=this.pos.copy()}update(){ASSERT(this.angleDamping>=0&&this.angleDamping<=1);ASSERT(this.damping>=0&&this.damping<=1);if(this.velocityInheritance){const p=this.velocityInheritance;this.velocity.x=p*(this.pos.x-this.previousPos.x);this.velocity.y=p*(this.pos.y-this.previousPos.y);this.angleVelocity=p*(this.angle-this.previousAngle);this.previousAngle=this.angle;this.previousPos.x=this.pos.x;this.previousPos.y=this.pos.y}if(this.isActive()){if(this.emitRate&&particleEmitRateScale){const rate=1/this.emitRate/particleEmitRateScale;for(this.emitTimeBuffer+=timeDelta;this.emitTimeBuffer>0;this.emitTimeBuffer-=rate)this.emitParticle()}}else if(this.particles.length===0)this.destroy(true);const particles=this.particles;let alive=0;for(let i=0;i<particles.length;++i){const p=particles[i];p.update();if(!p.destroyed)particles[alive++]=p}particles.length=alive;if(debugParticles){if(this.emitCircle)debugCircle(this.pos,this.emitSize.x/2,"#0f0");else debugRect(this.pos,this.emitSize,"#0f0",0,this.angle)}}emitParticle(){let pos=this.emitCircle?randInCircle(this.emitSize.x/2):vec2(rand(-.5,.5),rand(-.5,.5)).multiply(this.emitSize).rotate(this.angle);let angle=rand(this.particleConeAngle,-this.particleConeAngle);if(!this.localSpace){pos.x+=this.pos.x;pos.y+=this.pos.y;angle+=this.angle}const randomness=this.randomness;const randomizeScale=v=>v+v*rand(randomness,-randomness);const particleTime=randomizeScale(this.particleTime);const sizeStart=randomizeScale(this.sizeStart);const sizeEnd=randomizeScale(this.sizeEnd);const speed=randomizeScale(this.speed);const angleSpeed=randomizeScale(this.angleSpeed)*randSign();const coneAngle=rand(this.emitConeAngle,-this.emitConeAngle);const colorStart=randColor(this.colorStartA,this.colorStartB,this.randomColorLinear);const colorEnd=randColor(this.colorEndA,this.colorEndB,this.randomColorLinear);const velocityAngle=this.localSpace?coneAngle:this.angle+coneAngle;const velocity=vec2(speed*sin(velocityAngle),speed*cos(velocityAngle));let angleVelocity=angleSpeed;if(!this.localSpace&&this.velocityInheritance>0){velocity.x+=this.velocity.x;velocity.y+=this.velocity.y;angleVelocity+=this.angleVelocity}const particle=new Particle(this,pos,angle,colorStart,colorEnd,particleTime,sizeStart,sizeEnd,velocity,angleVelocity);this.particles.push(particle);this.particleCreateCallback?.(particle);return particle}updatePhysics(){}render(){for(const particle of this.particles)particle.render()}isActive(){return!this.emitTime||this.getAliveTime()<this.emitTime}destroy(immediate=false){if(this.destroyed)return;super.destroy(immediate);if(!immediate&&this.particles.length>0){this.destroyed=false;this.emitTime=-1}}}const particleDrawPos=new Vector2;class Particle{constructor(emitter,pos,angle,colorStart,colorEnd,lifeTime,sizeStart,sizeEnd,velocity=vec2(),angleVelocity=0){this.emitter=emitter;this.pos=pos;this.angle=angle;this.size=vec2(sizeStart);this.color=colorStart.copy();this.colorStart=colorStart;this.colorEnd=colorEnd;this.lifeTime=lifeTime;this.sizeStart=sizeStart;this.sizeEnd=sizeEnd;this.velocity=velocity;this.angleVelocity=angleVelocity;this.spawnTime=time;this.mirror=randBool();this.groundObject=undefined;this.destroyed=false;this.tileInfo=emitter.tileInfo}update(){const emitter=this.emitter;const damping=emitter.damping;const angleDamping=emitter.angleDamping;const restitution=emitter.restitution;const friction=emitter.friction;const gravityScale=emitter.gravityScale;const collideTiles=emitter.collideTiles;const collideCallback=emitter.particleCollideCallback;if(this.lifeTime>0&&time-this.spawnTime>this.lifeTime){this.destroy();return}const oldPos=this.pos.copy();this.velocity.x*=damping;this.velocity.y*=damping;this.pos.x+=this.velocity.x+=gravity.x*gravityScale;this.pos.y+=this.velocity.y+=gravity.y*gravityScale;this.angle+=this.angleVelocity*=angleDamping;if(!enablePhysicsSolver||!collideTiles)return;const length2=this.velocity.lengthSquared();if(length2>objectMaxSpeed*objectMaxSpeed){const s=objectMaxSpeed/length2**.5;this.velocity.x*=s;this.velocity.y*=s}this.groundObject=undefined;const testCollision=collideCallback?pos=>{const data=tileCollisionGetData(pos);return data&&collideCallback(this,data,pos)}:pos=>tileCollisionGetData(pos)>0;if(testCollision(this.pos)){const hitLayer=tileCollisionTest(this.pos);if(!testCollision(oldPos)){const isBlockedX=testCollision(vec2(this.pos.x,oldPos.y));const isBlockedY=testCollision(vec2(oldPos.x,this.pos.y));const hitRestitution=hitLayer?max(restitution,hitLayer.restitution):restitution;const hitFriction=hitLayer?max(friction,hitLayer.friction):friction;if(isBlockedX){this.pos.x=oldPos.x;this.velocity.x*=-hitRestitution;this.velocity.y*=hitFriction}if(isBlockedY||!isBlockedX){const wasFalling=this.velocity.y<0&&gravity.y<0||this.velocity.y>0&&gravity.y>0;if(wasFalling)this.groundObject=hitLayer;this.pos.y=oldPos.y;this.velocity.y*=-hitRestitution;this.velocity.x*=hitFriction}debugPhysics&&debugRect(this.pos,this.size,"#f00")}}}destroy(){const destroyCallback=this.emitter.particleDestroyCallback;const c=this.colorEnd;this.color.set(c.r,c.g,c.b,c.a);this.size.set(this.sizeEnd,this.sizeEnd);this.destroyed=true;destroyCallback?.(this)}render(){const emitter=this.emitter;const localSpace=emitter.localSpace;const additive=emitter.additive;const trailScale=emitter.trailScale;const fadeRate=emitter.fadeRate/2;const p1=this.lifeTime>0?min((time-this.spawnTime)/this.lifeTime,1):1,p2=1-p1;const radius=p2*this.sizeStart+p1*this.sizeEnd;const size=vec2(radius);const alphaFade=p1<fadeRate?p1/fadeRate:p1>1-fadeRate?(1-p1)/fadeRate:1;this.color.r=p2*this.colorStart.r+p1*this.colorEnd.r;this.color.g=p2*this.colorStart.g+p1*this.colorEnd.g;this.color.b=p2*this.colorStart.b+p1*this.colorEnd.b;this.color.a=(p2*this.colorStart.a+p1*this.colorEnd.a)*alphaFade;const pos=particleDrawPos.set(this.pos.x,this.pos.y);let angle=this.angle;if(localSpace){const a=emitter.angle;const c=cos(-a),s=sin(-a);pos.set(emitter.pos.x+pos.x*c-pos.y*s,emitter.pos.y+pos.x*s+pos.y*c);angle+=a}additive&&setAdditiveBlendMode();if(trailScale){const velocity=localSpace?this.velocity.rotate(emitter.angle):this.velocity;const speed=velocity.length();if(speed){const trailLength=speed*trailScale;size.y=max(size.x,trailLength);angle=atan2(velocity.x,velocity.y);drawTile(pos,size,this.tileInfo,this.color,angle,this.mirror)}}else drawTile(pos,size,this.tileInfo,this.color,angle,this.mirror);additive&&setAdditiveBlendMode(false);debugParticles&&debugRect(pos,size,"#f005",0,angle)}}let glCanvas;let glContext;let glAntialias=true;let glShader,glPolyShader,glPolyMode,glAdditive,glBatchAdditive,glActiveTexture,glArrayBuffer,glGeometryBuffer,glPositionData,glColorData,glBatchCount,glTextureInfos,glInstancedVAO,glPolyVAO,glFramebuffer,glRenderTarget,glCanBeEnabled=true;const gl_ARRAY_BUFFER_SIZE=5e5;const gl_INDICES_PER_INSTANCE=11;const gl_INSTANCE_BYTE_STRIDE=gl_INDICES_PER_INSTANCE*4;const gl_MAX_INSTANCES=gl_ARRAY_BUFFER_SIZE/gl_INSTANCE_BYTE_STRIDE|0;const gl_INDICES_PER_POLY_VERTEX=3;const gl_POLY_VERTEX_BYTE_STRIDE=gl_INDICES_PER_POLY_VERTEX*4;const gl_MAX_POLY_VERTEXES=gl_ARRAY_BUFFER_SIZE/gl_POLY_VERTEX_BYTE_STRIDE|0;function glInit(rootElement){glTextureInfos=new Set;if(!glEnable||headlessMode){glCanBeEnabled=false;return}glCanvas=document.createElement("canvas");glContext=glCanvas.getContext("webgl2",{antialias:glAntialias});if(!glContext){console.warn("WebGL2 not supported, falling back to 2D canvas rendering!");glCanvas=glContext=undefined;glEnable=false;glCanBeEnabled=false;return}rootElement.appendChild(glCanvas);initWebGL();glCanvas.addEventListener("webglcontextlost",e=>{glEnable=false;glCanvas.style.display="none";e.preventDefault();LOG("WebGL context lost! Switching to Canvas2d rendering.");for(const info of glTextureInfos)info.glTexture=undefined;glActiveTexture=undefined;glBatchCount=0;glPolyMode=false;pluginList.forEach(plugin=>plugin.glContextLost?.())});glCanvas.addEventListener("webglcontextrestored",()=>{glEnable=true;glCanvas.style.display="";LOG("WebGL context restored, reinitializing...");initWebGL();for(const info of glTextureInfos)info.glTexture=glCreateTexture(info.image,info.wrap);pluginList.forEach(plugin=>plugin.glContextRestored?.())});function initWebGL(){glShader=glCreateProgram("#version 300 es\n"+"precision highp float;"+"uniform mat4 m;"+"in vec2 g;"+"in vec4 p,u,c,a;"+"in float r;"+"out vec2 v;"+"out vec4 d,e;"+"void main(){"+"vec2 s=(g-.5)*p.zw;"+"gl_Position=m*vec4(p.xy+s*cos(r)-vec2(-s.y,s)*sin(r),1,1);"+"v=mix(u.xw,u.zy,g);"+"d=c;e=a;"+"}","#version 300 es\n"+"precision highp float;"+"uniform sampler2D s;"+"in vec2 v;"+"in vec4 d,e;"+"out vec4 c;"+"void main(){"+"c=texture(s,v)*d+e;"+"}");glPolyShader=glCreateProgram("#version 300 es\n"+"precision highp float;"+"uniform mat4 m;"+"in vec2 p;"+"in vec4 c;"+"out vec4 d;"+"void main(){"+"gl_Position=m*vec4(p,1,1);"+"d=c;"+"}","#version 300 es\n"+"precision highp float;"+"in vec4 d;"+"out vec4 c;"+"void main(){"+"c=d;"+"}");const glInstanceData=new ArrayBuffer(gl_ARRAY_BUFFER_SIZE);glPositionData=new Float32Array(glInstanceData);glColorData=new Uint32Array(glInstanceData);glArrayBuffer=glContext.createBuffer();glGeometryBuffer=glContext.createBuffer();glFramebuffer=glContext.createFramebuffer();glBatchCount=0;const geometry=new Float32Array([0,0,1,0,0,1,1,1]);glContext.bindBuffer(glContext.ARRAY_BUFFER,glGeometryBuffer);glContext.bufferData(glContext.ARRAY_BUFFER,geometry,glContext.STATIC_DRAW);let offset,shader,stride;const initVertexAttrib=(name,type,typeSize,size,divisor=0)=>{const location=glContext.getAttribLocation(shader,name);const normalize=typeSize===1;const fixedStride=typeSize&&stride;glContext.enableVertexAttribArray(location);glContext.vertexAttribPointer(location,size,type,normalize,fixedStride,offset);glContext.vertexAttribDivisor(location,divisor);offset+=size*typeSize};glInstancedVAO=glContext.createVertexArray();glContext.bindVertexArray(glInstancedVAO);offset=0,shader=glShader,stride=gl_INSTANCE_BYTE_STRIDE;glContext.bindBuffer(glContext.ARRAY_BUFFER,glGeometryBuffer);initVertexAttrib("g",glContext.FLOAT,0,2);glContext.bindBuffer(glContext.ARRAY_BUFFER,glArrayBuffer);glContext.bufferData(glContext.ARRAY_BUFFER,gl_ARRAY_BUFFER_SIZE,glContext.DYNAMIC_DRAW);initVertexAttrib("p",glContext.FLOAT,4,4,1);initVertexAttrib("u",glContext.FLOAT,4,4,1);initVertexAttrib("c",glContext.UNSIGNED_BYTE,1,4,1);initVertexAttrib("a",glContext.UNSIGNED_BYTE,1,4,1);initVertexAttrib("r",glContext.FLOAT,4,1,1);glPolyVAO=glContext.createVertexArray();glContext.bindVertexArray(glPolyVAO);offset=0,shader=glPolyShader,stride=gl_POLY_VERTEX_BYTE_STRIDE;initVertexAttrib("p",glContext.FLOAT,4,2);initVertexAttrib("c",glContext.UNSIGNED_BYTE,1,4)}}function glSetInstancedMode(force=false){if(!force&&!glPolyMode)return;glFlush();glPolyMode=false;glContext.useProgram(glShader);glContext.bindVertexArray(glInstancedVAO)}function glSetPolyMode(){if(glPolyMode)return;glFlush();glPolyMode=true;glContext.useProgram(glPolyShader);glContext.bindVertexArray(glPolyVAO)}function glPreRender(clear=true){if(!glEnable||!glContext)return;ASSERT(!glBatchCount,"glPreRender called with unflushed batch.");if(!glRenderTarget){glCanvas.width=mainCanvasSize.x;glCanvas.height=mainCanvasSize.y}glContext.viewport(0,0,mainCanvasSize.x,mainCanvasSize.y);clear&&glClearCanvas();const s=vec2(2*cameraScale).divide(mainCanvasSize);if(glRenderTarget)s.y=-s.y;const rotatedCam=cameraPos.rotate(-cameraAngle);const p=vec2(-1).subtract(rotatedCam.multiply(s));const ca=cos(cameraAngle);const sa=sin(cameraAngle);const transform=[s.x*ca,s.y*sa,0,0,-s.x*sa,s.y*ca,0,0,1,1,1,0,p.x,p.y,0,1];const initUniform=(program,uniform,value)=>{glContext.useProgram(program);const location=glContext.getUniformLocation(program,uniform);glContext.uniformMatrix4fv(location,false,value)};initUniform(glPolyShader,"m",transform);initUniform(glShader,"m",transform);glContext.activeTexture(glContext.TEXTURE0);if(textureInfos[0]){glActiveTexture=textureInfos[0].glTexture;glContext.bindTexture(glContext.TEXTURE_2D,glActiveTexture)}glContext.bindBuffer(glContext.ARRAY_BUFFER,glArrayBuffer);glAdditive=glBatchAdditive=false;glSetInstancedMode(true)}function glClearCanvas(){if(!glContext)return;const color=canvasClearColor;glContext.clearColor(color.r,color.g,color.b,color.a);glContext.clear(glContext.COLOR_BUFFER_BIT)}function glSetTexture(texture){if(!glContext||texture===glActiveTexture)return;glFlush();glActiveTexture=texture;glContext.bindTexture(glContext.TEXTURE_2D,glActiveTexture)}function glSetTextureWrap(texture,wrap=true){if(!glContext||!texture)return;const isCurrent=texture===glActiveTexture;if(isCurrent)glFlush();else glContext.bindTexture(glContext.TEXTURE_2D,texture);const wrapMode=wrap?glContext.REPEAT:glContext.CLAMP_TO_EDGE;glContext.texParameteri(glContext.TEXTURE_2D,glContext.TEXTURE_WRAP_S,wrapMode);glContext.texParameteri(glContext.TEXTURE_2D,glContext.TEXTURE_WRAP_T,wrapMode);if(!isCurrent&&glActiveTexture)glContext.bindTexture(glContext.TEXTURE_2D,glActiveTexture)}function glCompileShader(source,type){if(!glContext)return;const shader=glContext.createShader(type);glContext.shaderSource(shader,source);glContext.compileShader(shader);if(debug&&!glContext.getShaderParameter(shader,glContext.COMPILE_STATUS))throw glContext.getShaderInfoLog(shader);return shader}function glCreateProgram(vsSource,fsSource){if(!glContext)return;const program=glContext.createProgram();glContext.attachShader(program,glCompileShader(vsSource,glContext.VERTEX_SHADER));glContext.attachShader(program,glCompileShader(fsSource,glContext.FRAGMENT_SHADER));glContext.linkProgram(program);if(debug&&!glContext.getProgramParameter(program,glContext.LINK_STATUS))throw glContext.getProgramInfoLog(program);return program}function glCreateTexture(image,wrap=false){if(!glContext)return;const texture=glContext.createTexture();let mipMap=false;if(image?.width){glSetTextureData(texture,image);glContext.bindTexture(glContext.TEXTURE_2D,texture);mipMap=!tilesPixelated&&isPowerOfTwo(image.width)&&isPowerOfTwo(image.height)}else{const whitePixel=new Uint8Array([255,255,255,255]);glContext.bindTexture(glContext.TEXTURE_2D,texture);glContext.texImage2D(glContext.TEXTURE_2D,0,glContext.RGBA,1,1,0,glContext.RGBA,glContext.UNSIGNED_BYTE,whitePixel)}const magFilter=tilesPixelated?glContext.NEAREST:glContext.LINEAR;const minFilter=mipMap?glContext.LINEAR_MIPMAP_LINEAR:magFilter;glContext.texParameteri(glContext.TEXTURE_2D,glContext.TEXTURE_MAG_FILTER,magFilter);glContext.texParameteri(glContext.TEXTURE_2D,glContext.TEXTURE_MIN_FILTER,minFilter);const wrapMode=wrap?glContext.REPEAT:glContext.CLAMP_TO_EDGE;glContext.texParameteri(glContext.TEXTURE_2D,glContext.TEXTURE_WRAP_S,wrapMode);glContext.texParameteri(glContext.TEXTURE_2D,glContext.TEXTURE_WRAP_T,wrapMode);if(mipMap)glContext.generateMipmap(glContext.TEXTURE_2D);glContext.bindTexture(glContext.TEXTURE_2D,glActiveTexture);return texture}function glDeleteTexture(texture){if(!glContext)return;glContext.deleteTexture(texture)}function glSetTextureData(texture,image){if(!glContext)return;ASSERT(image?.width>0,"Invalid image data.");glContext.bindTexture(glContext.TEXTURE_2D,texture);glContext.texImage2D(glContext.TEXTURE_2D,0,glContext.RGBA,glContext.RGBA,glContext.UNSIGNED_BYTE,image);if(!tilesPixelated&&isPowerOfTwo(image.width)&&isPowerOfTwo(image.height))glContext.generateMipmap(glContext.TEXTURE_2D);glContext.bindTexture(glContext.TEXTURE_2D,glActiveTexture)}function glRegisterTextureInfo(textureInfo){if(headlessMode)return;glTextureInfos.add(textureInfo);if(!glContext)return;if(textureInfo.glTexture)glSetTextureData(textureInfo.glTexture,textureInfo.image);else textureInfo.glTexture=glCreateTexture(textureInfo.image,textureInfo.wrap)}function glUnregisterTextureInfo(textureInfo){if(headlessMode)return;glTextureInfos.delete(textureInfo);const glTexture=textureInfo.glTexture;textureInfo.glTexture=undefined;glDeleteTexture(glTexture)}function glFlush(){if(glEnable&&glContext&&glBatchCount){const destBlend=glBatchAdditive?glContext.ONE:glContext.ONE_MINUS_SRC_ALPHA;glContext.blendFuncSeparate(glContext.SRC_ALPHA,destBlend,glContext.ONE,destBlend);glContext.enable(glContext.BLEND);const byteLength=glBatchCount*(glPolyMode?gl_INDICES_PER_POLY_VERTEX:gl_INDICES_PER_INSTANCE);glContext.bufferSubData(glContext.ARRAY_BUFFER,0,glPositionData,0,byteLength);if(glPolyMode)glContext.drawArrays(glContext.TRIANGLE_STRIP,0,glBatchCount);else glContext.drawArraysInstanced(glContext.TRIANGLE_STRIP,0,4,glBatchCount);++drawCount;primitiveCount+=glBatchCount;glBatchCount=0}glBatchAdditive=glAdditive}function glCopyToContext(context){if(!glEnable||!glContext)return;glFlush();context.drawImage(glCanvas,0,0)}function glSetAntialias(antialias=true){ASSERT(!glCanvas,"must be called before engineInit");glAntialias=antialias}function glDraw(x,y,sizeX,sizeY,angle=0,uv0X=0,uv0Y=0,uv1X=1,uv1Y=1,rgba=-1,rgbaAdditive=0){if(glBatchCount>=gl_MAX_INSTANCES||glBatchAdditive!==glAdditive)glFlush();glSetInstancedMode();let offset=glBatchCount++*gl_INDICES_PER_INSTANCE;glPositionData[offset++]=x;glPositionData[offset++]=y;glPositionData[offset++]=sizeX;glPositionData[offset++]=sizeY;glPositionData[offset++]=uv0X;glPositionData[offset++]=uv0Y;glPositionData[offset++]=uv1X;glPositionData[offset++]=uv1Y;glColorData[offset++]=rgba;glColorData[offset++]=rgbaAdditive;glPositionData[offset++]=angle}function glDrawUntextured(x,y,sizeX,sizeY,angle,rgba){glDraw(x,y,sizeX,sizeY,angle,0,0,0,0,0,rgba)}function glDrawPointsTransform(points,rgba,x,y,sx,sy,angle,tristrip=true){const pointsOut=[];const sa=sin(-angle);const ca=cos(-angle);for(const p of points){const px=p.x*sx;const py=p.y*sy;pointsOut.push(vec2(x+ca*px-sa*py,y+sa*px+ca*py))}const drawPoints=tristrip?glPolyStrip(pointsOut):pointsOut;glDrawPoints(drawPoints,rgba)}function glDrawOutlineTransform(points,rgba,lineWidth,x,y,sx,sy,angle,wrap=true){const outlinePoints=glMakeOutline(points,lineWidth,wrap);glDrawPointsTransform(outlinePoints,rgba,x,y,sx,sy,angle,false)}function glDrawPoints(points,rgba){if(!glEnable||points.length<3)return;const vertCount=points.length+2;if(glBatchCount+vertCount>=gl_MAX_POLY_VERTEXES||glBatchAdditive!==glAdditive)glFlush();ASSERT(vertCount<gl_MAX_POLY_VERTEXES,"poly exceeds max batch size");if(vertCount>=gl_MAX_POLY_VERTEXES)return;glSetPolyMode();let offset=glBatchCount*gl_INDICES_PER_POLY_VERTEX;for(let i=vertCount;i--;){const j=clamp(i-1,0,vertCount-3);const point=points[j];glPositionData[offset++]=point.x;glPositionData[offset++]=point.y;glColorData[offset++]=rgba}glBatchCount+=vertCount}function glDrawColoredPoints(points,pointColors){if(!glEnable||points.length<3)return;const vertCount=points.length+2;if(glBatchCount+vertCount>=gl_MAX_POLY_VERTEXES||glBatchAdditive!==glAdditive)glFlush();ASSERT(vertCount<gl_MAX_POLY_VERTEXES,"poly exceeds max batch size");if(vertCount>=gl_MAX_POLY_VERTEXES)return;glSetPolyMode();let offset=glBatchCount*gl_INDICES_PER_POLY_VERTEX;for(let i=vertCount;i--;){const j=clamp(i-1,0,vertCount-3);const point=points[j];const color=pointColors[j];glPositionData[offset++]=point.x;glPositionData[offset++]=point.y;glColorData[offset++]=color}glBatchCount+=vertCount}function glSetRenderTarget(texture,clear=false){if(texture){glRenderTarget=texture;glContext.bindFramebuffer(glContext.FRAMEBUFFER,glFramebuffer);glContext.framebufferTexture2D(glContext.FRAMEBUFFER,glContext.COLOR_ATTACHMENT0,glContext.TEXTURE_2D,texture,0);glPreRender(clear)}else{glFlush();glRenderTarget=undefined;glContext.bindFramebuffer(glContext.FRAMEBUFFER,null);glContext.viewport(0,0,mainCanvasSize.x,mainCanvasSize.y)}}function glClearRect(x,y,width,height){if(!glEnable)return;glContext.enable(glContext.SCISSOR_TEST);glContext.scissor(x,y,width,height);glContext.clearColor(0,0,0,0);glContext.clear(glContext.COLOR_BUFFER_BIT);glContext.disable(glContext.SCISSOR_TEST)}function glMakeOutline(points,width,wrap=true){if(points.length<2)return[];const halfWidth=width/2;const strip=[];const n=points.length;const e=1e-6;const miterLimit=10;for(let i=0;i<n;i++){const prev=points[wrap?(i-1+n)%n:max(i-1,0)];const curr=points[i];const next=points[wrap?(i+1)%n:min(i+1,n-1)];const dx1=curr.x-prev.x;const dy1=curr.y-prev.y;const len1=(dx1*dx1+dy1*dy1)**.5;const dx2=next.x-curr.x;const dy2=next.y-curr.y;const len2=(dx2*dx2+dy2*dy2)**.5;if(len1<e&&len2<e)continue;const nx1=len1>e?-dy1/len1:0;const ny1=len1>e?dx1/len1:0;const nx2=len2>e?-dy2/len2:0;const ny2=len2>e?dx2/len2:0;let nx=nx1+nx2;let ny=ny1+ny2;const nlen=(nx*nx+ny*ny)**.5;if(nlen<e){nx=nx1;ny=ny1}else{nx/=nlen;ny/=nlen;const dot=nx1*nx+ny1*ny;if(dot>e){const miterLength=min(1/dot,miterLimit);nx*=miterLength;ny*=miterLength}}const inner=vec2(curr.x-nx*halfWidth,curr.y-ny*halfWidth);const outer=vec2(curr.x+nx*halfWidth,curr.y+ny*halfWidth);strip.push(inner);strip.push(outer)}if(strip.length>1&&wrap){strip.push(strip[0]);strip.push(strip[1])}return strip}function glPolyStrip(points){if(points.length<3)return[];const cross=(a,b,c)=>(b.x-a.x)*(c.y-a.y)-(b.y-a.y)*(c.x-a.x);const signedArea=poly=>{let area=0;for(let i=poly.length;i--;){const j=(i+1)%poly.length;area+=poly[i].cross(poly[j])}return area};if(signedArea(points)<0)points=points.slice().reverse();const e=1e-9;const pointInTriangle=(p,a,b,c)=>{const c1=cross(a,b,p);const c2=cross(b,c,p);const c3=cross(c,a,p);const negative=(c1<-e?1:0)+(c2<-e?1:0)+(c3<-e?1:0);const positive=(c1>e?1:0)+(c2>e?1:0)+(c3>e?1:0);return!(negative&&positive)};const indices=[];for(let i=0;i<points.length;++i)indices[i]=i;const triangles=[];let attempts=0;const maxAttempts=points.length**2+100;while(indices.length>3&&attempts++<maxAttempts){let foundEar=false;for(let i=0;i<indices.length;i++){const i0=indices[(i+indices.length-1)%indices.length];const i1=indices[i];const i2=indices[(i+1)%indices.length];const a=points[i0],b=points[i1],c=points[i2];if(cross(a,b,c)<e)continue;let hasInside=false;for(let j=0;j<indices.length;j++){const k=indices[j];if(k===i0||k===i1||k===i2)continue;const p=points[k];hasInside=pointInTriangle(p,a,b,c);if(hasInside)break}if(hasInside)continue;triangles.push([i0,i1,i2]);indices.splice(i,1);foundEar=true;break}if(!foundEar){let worstIndex=-1,worstValue=Infinity;for(let i=0;i<indices.length;i++){const i0=indices[(i+indices.length-1)%indices.length];const i1=indices[i];const i2=indices[(i+1)%indices.length];const value=abs(cross(points[i0],points[i1],points[i2]));if(value<worstValue){worstValue=value;worstIndex=i}}if(worstIndex<0)break;const i0=indices[(worstIndex+indices.length-1)%indices.length];const i1=indices[worstIndex];const i2=indices[(worstIndex+1)%indices.length];triangles.push([i0,i1,i2]);indices.splice(worstIndex,1)}}if(indices.length===3)triangles.push([indices[0],indices[1],indices[2]]);if(!triangles.length)return[];const strip=[];let[a0,b0,c0]=triangles[0];strip.push(points[a0],points[b0],points[c0]);for(let i=1;i<triangles.length;i++){const[a,b,c]=triangles[i];strip.push(points[c0],points[a]);strip.push(points[a],points[b],points[c]);c0=c}return strip}function drawEngineLogo(t){const blackAndWhite=0;const showName=1;const x=mainContext;const dpr=canvasPixelRatio??(devicePixelRatio||1);const w=mainCanvas.width=innerWidth*dpr;const h=mainCanvas.height=innerHeight*dpr;{const p3=percent(t,1,.8);const p4=percent(t,0,.5);const g=x.createRadialGradient(w/2,h/2,0,w/2,h/2,hypot(w,h)*.6);g.addColorStop(0,hsl(0,0,lerp(0,p3/2,p4),p3).toString());g.addColorStop(1,hsl(0,0,0,p3).toString());x.save();x.fillStyle=g;x.fillRect(0,0,w,h)}const gradient=(X1,Y1,X2,Y2,C,S=1)=>{if(C>=0){if(blackAndWhite)x.fillStyle="#fff";else{const g=x.fillStyle=x.createLinearGradient(X1,Y1,X2,Y2);g.addColorStop(0,color(C,2));g.addColorStop(1,color(C,1))}}else x.fillStyle="#000";C>=-1?(x.fill(),S&&x.stroke()):x.stroke()};const circle=(X,Y,R,A=0,B=2*PI,C,S)=>{x.beginPath();x.arc(X,Y,R,p*A,p*B);gradient(X,Y-R,X,Y+R,C,S)};const rect=(X,Y,W,H,C)=>{x.beginPath();x.rect(X,Y,W,H*p);gradient(X,Y+H,X+W,Y,C)};const poly=(points,C,Y,H)=>{x.beginPath();for(const p of points)x.lineTo(p.x,p.y);x.closePath();gradient(0,Y,0,Y+H,C)};const color=(c,l)=>l?`hsl(${[.95,.56,.13][c%3]*360} 99%${[0,50,75][l]}%)`:"#000";const alpha=oscillate(1,1,t);const p=percent(alpha,.1,.5);const size=min(6,min(w,h)/99);x.translate(w/2,h/2);x.scale(size,size);x.translate(-40,-35);p<1&&x.setLineDash([99*p,99]);x.lineJoin=x.lineCap="round";x.lineWidth=.1+p*1.9;if(showName){const Y=54;const s="LittleJS";x.font="900 15.5px arial";x.lineWidth=.1+p*3.9;x.textAlign="center";x.textBaseline="top";rect(11,Y+1,59,8*p,-1);x.beginPath();let w2=0;for(let i=0;i<s.length;++i)w2+=x.measureText(s[i]).width;for(let j=2;j--;)for(let i=0,X=40-w2/2;i<s.length;++i){const w=x.measureText(s[i]).width,X2=X+w/2;gradient(X2,Y,X2+2,Y+13,i>5?1:0);x[j?"strokeText":"fillText"](s[i],X2,Y+.5,17*p);X+=w}x.lineWidth=.1+p*1.9;rect(3,Y,73,0)}rect(7,15,26,-7,0);rect(25,15,8,25,-1);rect(10,40,15,-25,1);rect(14,21,7,9,2);rect(38,20,6,-6,2);rect(49,20,10,-6,0);const stackPoints=[vec2(44,8),vec2(64,8),vec2(59,8+6*p),vec2(49,8+6*p)];poly(stackPoints,2,8,6*p);rect(44,8,20,-7,0);for(let i=5;i--;)circle(59-i*6*p,30,10,0,2*PI,1,0);circle(59,30,4,0,7,2);rect(35,20,24,0);circle(59,30,10);circle(47,30,10,PI/2,PI*3/2);circle(35,30,10,PI/2,PI*3/2);rect(7,40,13,7,-1);rect(17,40,43,14,-1);for(let i=3;i--;)for(let j=2;j--;)circle(17+15*i,47,j?7:1,0,2*PI,2);for(let i=2;i--;){let w=6,s=7,o=53+w*p*i;const points=[vec2(o+s,54),vec2(o,40),vec2(o+w*p,40),vec2(o+s+w*p,54)];poly(points,0,40,14)}x.restore()}let debugMedals=false;let medalDisplayTime=5;let medalDisplaySlideTime=.5;let medalDisplaySize=vec2(640,80);let medalsPreventUnlock=false;const medals={};let medalsDisplayQueue=[],medalsSaveName,medalsDisplayTimeLast;function medalsInit(saveName){medalsSaveName=saveName;if(!debugMedals){let saved={};try{saved=JSON.parse(localStorage[saveName]||"{}")}catch(e){saved={}}medalsForEach(medal=>{medal.unlocked=!!(saved[medal.id]&&saved[medal.id].unlocked)});medalsSave()}engineAddPlugin(undefined,medalsRender);function medalsRender(){if(!medalsDisplayQueue.length)return;const medal=medalsDisplayQueue[0];const time=timeReal-medalsDisplayTimeLast;if(!medalsDisplayTimeLast)medalsDisplayTimeLast=timeReal;else if(time>medalDisplayTime){medalsDisplayTimeLast=0;medalsDisplayQueue.shift()}else{const slideOffTime=medalDisplayTime-medalDisplaySlideTime;const hidePercent=time<medalDisplaySlideTime?1-time/medalDisplaySlideTime:time>slideOffTime?(time-slideOffTime)/medalDisplaySlideTime:0;medal.render(hidePercent)}}}function medalsForEach(callback){Object.values(medals).forEach(medal=>callback(medal))}function medalsReset(){medalsForEach(medal=>medal.unlocked=false);medalsSave()}function medalsSave(){if(!medalsSaveName)return;const data={};medalsForEach(medal=>{const entry={name:medal.name,description:medal.description,icon:medal.icon,unlocked:medal.unlocked};if(medal.image)entry.src=medal.image.src;data[medal.id]=entry});localStorage[medalsSaveName]=JSON.stringify(data)}class Medal{constructor(id,name,description="",icon="🏆",src){ASSERT(id>=0&&!medals[id]);this.id=id;this.name=name;this.description=description;this.icon=icon;this.unlocked=false;this.image=undefined;if(src)(this.image=new Image).src=src;medals[id]=this}unlock(){if(medalsPreventUnlock||this.unlocked)return;ASSERT(medalsSaveName,"save name must be set");this.unlocked=true;medalsSave();medalsDisplayQueue.push(this)}render(hidePercent=0){const context=mainContext;const width=min(medalDisplaySize.x,mainCanvas.width);const height=medalDisplaySize.y;const x=mainCanvas.width-width;const y=-height*hidePercent;const backgroundColor=hsl(0,0,.9);context.save();context.beginPath();context.fillStyle=backgroundColor.toString();context.strokeStyle=BLACK.toString();context.lineWidth=3;context.rect(x,y,width,height);context.fill();context.stroke();context.clip();const gap=vec2(.1,.05).scale(height);const medalDisplayIconSize=height-2*gap.x;this.renderIcon(vec2(x+gap.x+medalDisplayIconSize/2,y+height/2),medalDisplayIconSize);const nameSize=height*.5;const descriptionSize=height*.3;const pos=vec2(x+medalDisplayIconSize+2*gap.x,y+gap.y*2+nameSize/2);const textWidth=width-medalDisplayIconSize-3*gap.x;drawTextScreen(this.name,pos,nameSize,BLACK,0,undefined,"left",undefined,undefined,textWidth);pos.y=y+height-gap.y*2-descriptionSize/2;drawTextScreen(this.description,pos,descriptionSize,BLACK,0,undefined,"left",undefined,undefined,textWidth);context.restore()}renderIcon(pos,size){if(this.image)mainContext.drawImage(this.image,pos.x-size/2,pos.y-size/2,size,size);else drawTextScreen(this.icon,pos,size*.7,BLACK)}}function setMedalDisplayTime(time){medalDisplayTime=time}function setMedalDisplaySlideTime(time){medalDisplaySlideTime=time}function setMedalDisplaySize(size){medalDisplaySize=size.copy()}function setMedalsPreventUnlock(preventUnlock){medalsPreventUnlock=preventUnlock}let newgrounds;class NewgroundsMedal extends Medal{constructor(id,name,description,icon,src){super(id,name,description,icon,src)}unlock(){super.unlock();newgrounds&&newgrounds.unlockMedal(this.id)}}class NewgroundsPlugin{constructor(app_id,cipher,cryptoJS){ASSERT(!newgrounds,"there can only be one newgrounds object");ASSERT(!cipher||cryptoJS,"must provide cryptojs if there is a cipher");newgrounds=this;this.app_id=app_id;this.cipher=cipher;this.cryptoJS=cryptoJS;this.host=location?location.hostname:"";const url=new URL(location.href);this.session_id=url.searchParams.get("ngio_session_id");if(!this.session_id)return;const medalsResult=this.call("Medal.getList");if(!medalsResult||!medalsResult.result||medalsResult.result.error){debugMedals&&LOG("Newgrounds session unavailable; skipping plugin init");this.medals=[];this.scoreboards=[];return}this.medals=medalsResult.result.data?.["medals"]||[];debugMedals&&LOG(this.medals);for(const newgroundsMedal of this.medals){const medal=medals[newgroundsMedal["id"]];if(medal){medal.image=new Image;medal.image.src=newgroundsMedal["icon"];medal.name=newgroundsMedal["name"];medal.description=newgroundsMedal["description"];medal.unlocked=newgroundsMedal["unlocked"];medal.difficulty=newgroundsMedal["difficulty"];medal.value=newgroundsMedal["value"];if(medal.value)medal.description=medal.description+` (${medal.value})`}}const scoreboardResult=this.call("ScoreBoard.getBoards");this.scoreboards=scoreboardResult?.result?.data?.scoreboards||[];debugMedals&&LOG(this.scoreboards);const keepAliveMS=60*1e3;setInterval(()=>this.call("Gateway.ping",0,true),keepAliveMS)}unlockMedal(id){return this.call("Medal.unlock",{id:id},true)}postScore(id,value){return this.call("ScoreBoard.postScore",{id:id,value:value},true)}getScores(id,user,social=0,skip=0,limit=10){return this.call("ScoreBoard.getScores",{id:id,user:user,social:social,skip:skip,limit:limit})}logView(){return this.call("App.logView",{host:this.host},true)}call(component,parameters,async=false){const call={component:component,parameters:parameters};if(this.cipher){const cryptoJS=this.cryptoJS;const aesKey=cryptoJS["enc"]["Base64"]["parse"](this.cipher);const iv=cryptoJS["lib"]["WordArray"]["random"](16);const encrypted=cryptoJS["AES"]["encrypt"](JSON.stringify(call),aesKey,{iv:iv});call["secure"]=cryptoJS["enc"]["Base64"]["stringify"](iv.concat(encrypted["ciphertext"]));call["parameters"]=0}const input={app_id:this.app_id,session_id:this.session_id,call:call};const formData=new FormData;formData.append("input",JSON.stringify(input));const xmlHttp=new XMLHttpRequest;const url="https://newgrounds.io/gateway_v3.php";xmlHttp.open("POST",url,!debugMedals&&async);try{xmlHttp.send(formData)}catch(e){debugMedals&&LOG("newgrounds call failed",e);return}debugMedals&&LOG(xmlHttp.responseText);try{return xmlHttp.responseText&&JSON.parse(xmlHttp.responseText)}catch(e){debugMedals&&LOG("newgrounds response is not valid JSON",e)}}}let postProcess;class PostProcessPlugin{constructor(shaderCode,includeMainCanvas=false,feedbackTexture=false){ASSERT(!postProcess,"Post process already initialized");ASSERT(!(includeMainCanvas&&feedbackTexture),"Post process cannot both include main canvas and use feedback texture");postProcess=this;if(!shaderCode)shaderCode="void mainImage(out vec4 c,vec2 p){c=texture(iChannel0,p/iResolution.xy);}";this.shader=undefined;this.texture=undefined;this.vao=undefined;initPostProcess();engineAddPlugin(undefined,postProcessRender,postProcessContextLost,postProcessContextRestored);function initPostProcess(){if(headlessMode)return;if(!glEnable){console.warn("PostProcessPlugin: WebGL not enabled!");return}postProcess.texture=glCreateTexture();postProcess.shader=glCreateProgram("#version 300 es\n"+"precision highp float;"+"in vec2 p;"+"void main(){"+"gl_Position=vec4(p+p-1.,1,1);"+"}","#version 300 es\n"+"precision highp float;"+"uniform sampler2D iChannel0;"+"uniform vec3 iResolution;"+"uniform float iTime;"+"out vec4 c;"+"\n"+shaderCode+"\n"+"void main(){"+"mainImage(c,gl_FragCoord.xy);"+"c.a=1.;"+"}");postProcess.vao=glContext.createVertexArray();glContext.bindVertexArray(postProcess.vao);glContext.bindBuffer(glContext.ARRAY_BUFFER,glGeometryBuffer);const vertexByteStride=8;const pLocation=glContext.getAttribLocation(postProcess.shader,"p");glContext.enableVertexAttribArray(pLocation);glContext.vertexAttribPointer(pLocation,2,glContext.FLOAT,false,vertexByteStride,0)}function postProcessContextLost(){postProcess.shader=undefined;postProcess.texture=undefined;LOG("PostProcessPlugin: WebGL context lost")}function postProcessContextRestored(){initPostProcess();LOG("PostProcessPlugin: WebGL context restored")}function postProcessRender(){if(headlessMode||!glEnable)return;glFlush();glContext.bindFramebuffer(glContext.FRAMEBUFFER,null);glContext.useProgram(postProcess.shader);glContext.bindVertexArray(postProcess.vao);glContext.pixelStorei(glContext.UNPACK_FLIP_Y_WEBGL,true);glContext.disable(glContext.BLEND);glContext.activeTexture(glContext.TEXTURE0);glContext.bindTexture(glContext.TEXTURE_2D,postProcess.texture);if(includeMainCanvas){workCanvas.width=mainCanvasSize.x;workCanvas.height=mainCanvasSize.y;glCopyToContext(workContext);workContext.drawImage(mainCanvas,0,0);mainCanvas.width|=0;glContext.texImage2D(glContext.TEXTURE_2D,0,glContext.RGBA,glContext.RGBA,glContext.UNSIGNED_BYTE,workCanvas)}else if(!feedbackTexture){glContext.texImage2D(glContext.TEXTURE_2D,0,glContext.RGBA,glContext.RGBA,glContext.UNSIGNED_BYTE,glCanvas)}const uniformLocation=name=>glContext.getUniformLocation(postProcess.shader,name);glContext.uniform1i(uniformLocation("iChannel0"),0);glContext.uniform1f(uniformLocation("iTime"),time);glContext.uniform3f(uniformLocation("iResolution"),mainCanvas.width,mainCanvas.height,1);glContext.drawArrays(glContext.TRIANGLE_STRIP,0,4);if(feedbackTexture){glContext.texImage2D(glContext.TEXTURE_2D,0,glContext.RGBA,glContext.RGBA,glContext.UNSIGNED_BYTE,glCanvas)}glContext.pixelStorei(glContext.UNPACK_FLIP_Y_WEBGL,false);glSetInstancedMode(true)}}}let lightSystem;class LightSystemPlugin{constructor(textureSize,ambientColor){ASSERT(!lightSystem,"LightSystemPlugin already initialized");ASSERT(!postProcess,"LightSystemPlugin must be created before PostProcessPlugin");lightSystem=this;this.enabled=true;this.ambientColor=(ambientColor||BLACK).copy();this.textureSize=textureSize?textureSize.copy():undefined;this.texture=undefined;this.lightShader=undefined;this.compositeShader=undefined;this.lightVAO=undefined;this.compositeVAO=undefined;initLightSystem();engineAddPlugin(undefined,lightSystemRender,lightSystemContextLost,lightSystemContextRestored);function initLightSystem(){if(headlessMode)return;if(!glEnable){console.warn("LightSystemPlugin: WebGL not enabled!");return}if(!lightSystem.textureSize)lightSystem.textureSize=mainCanvasSize.copy();lightSystem.texture=glContext.createTexture();glContext.bindTexture(glContext.TEXTURE_2D,lightSystem.texture);glContext.texImage2D(glContext.TEXTURE_2D,0,glContext.RGBA,lightSystem.textureSize.x,lightSystem.textureSize.y,0,glContext.RGBA,glContext.UNSIGNED_BYTE,null);glContext.texParameteri(glContext.TEXTURE_2D,glContext.TEXTURE_MAG_FILTER,glContext.LINEAR);glContext.texParameteri(glContext.TEXTURE_2D,glContext.TEXTURE_MIN_FILTER,glContext.LINEAR);glContext.texParameteri(glContext.TEXTURE_2D,glContext.TEXTURE_WRAP_S,glContext.CLAMP_TO_EDGE);glContext.texParameteri(glContext.TEXTURE_2D,glContext.TEXTURE_WRAP_T,glContext.CLAMP_TO_EDGE);lightSystem.lightShader=glCreateProgram("#version 300 es\n"+"precision highp float;"+"uniform mat4 m;"+"uniform vec2 lightPos;"+"uniform float radius;"+"in vec2 g;"+"out vec2 vWorldPos;"+"void main(){"+"vec2 worldP=lightPos+(g-.5)*2.*radius;"+"gl_Position=m*vec4(worldP,1,1);"+"vWorldPos=worldP;"+"}","#version 300 es\n"+"precision highp float;"+"uniform vec2 lightPos;"+"uniform float radius;"+"uniform float fadeRange;"+"uniform vec4 color;"+"in vec2 vWorldPos;"+"out vec4 c;"+"void main(){"+"float dist=distance(vWorldPos,lightPos);"+"float t=clamp((radius-dist)/max(fadeRange,1e-6),0.,1.);"+"c=vec4(color.rgb*t*color.a,1.);"+"}");lightSystem.compositeShader=glCreateProgram("#version 300 es\n"+"precision highp float;"+"in vec2 p;"+"void main(){"+"gl_Position=vec4(p+p-1.,1,1);"+"}","#version 300 es\n"+"precision highp float;"+"uniform sampler2D s;"+"uniform vec3 iResolution;"+"out vec4 c;"+"void main(){"+"vec2 uv=gl_FragCoord.xy/iResolution.xy;"+"c=vec4(texture(s,uv).rgb,1.);"+"}");lightSystem.lightVAO=glContext.createVertexArray();glContext.bindVertexArray(lightSystem.lightVAO);glContext.bindBuffer(glContext.ARRAY_BUFFER,glGeometryBuffer);const gLight=glContext.getAttribLocation(lightSystem.lightShader,"g");glContext.enableVertexAttribArray(gLight);glContext.vertexAttribPointer(gLight,2,glContext.FLOAT,false,8,0);lightSystem.compositeVAO=glContext.createVertexArray();glContext.bindVertexArray(lightSystem.compositeVAO);glContext.bindBuffer(glContext.ARRAY_BUFFER,glGeometryBuffer);const pComp=glContext.getAttribLocation(lightSystem.compositeShader,"p");glContext.enableVertexAttribArray(pComp);glContext.vertexAttribPointer(pComp,2,glContext.FLOAT,false,8,0)}function lightSystemRender(){if(headlessMode||!glEnable)return;if(!lightSystem.enabled)return;if(!lightSystem.texture)return;glFlush();const prevAdditive=glAdditive;const ac=lightSystem.ambientColor;glContext.bindFramebuffer(glContext.FRAMEBUFFER,glFramebuffer);glContext.framebufferTexture2D(glContext.FRAMEBUFFER,glContext.COLOR_ATTACHMENT0,glContext.TEXTURE_2D,lightSystem.texture,0);glContext.viewport(0,0,lightSystem.textureSize.x,lightSystem.textureSize.y);glContext.clearColor(ac.r,ac.g,ac.b,ac.a);glContext.clear(glContext.COLOR_BUFFER_BIT);setAdditiveBlendMode();glContext.enable(glContext.BLEND);glContext.blendFunc(glContext.ONE,glContext.ONE);for(const o of engineObjects)o.destroyed||o.renderLight();glFlush();glContext.bindFramebuffer(glContext.FRAMEBUFFER,null);glContext.viewport(0,0,mainCanvasSize.x,mainCanvasSize.y);glContext.useProgram(lightSystem.compositeShader);glContext.bindVertexArray(lightSystem.compositeVAO);glContext.activeTexture(glContext.TEXTURE0);glContext.bindTexture(glContext.TEXTURE_2D,lightSystem.texture);const cs=lightSystem.compositeShader;glContext.uniform1i(glContext.getUniformLocation(cs,"s"),0);glContext.uniform3f(glContext.getUniformLocation(cs,"iResolution"),mainCanvas.width,mainCanvas.height,1);glContext.blendFunc(glContext.DST_COLOR,glContext.ZERO);glContext.drawArrays(glContext.TRIANGLE_STRIP,0,4);if(glActiveTexture)glContext.bindTexture(glContext.TEXTURE_2D,glActiveTexture);setAdditiveBlendMode(prevAdditive);glSetInstancedMode(true)}function lightSystemContextLost(){lightSystem.texture=undefined;lightSystem.lightShader=undefined;lightSystem.compositeShader=undefined;lightSystem.lightVAO=undefined;lightSystem.compositeVAO=undefined;LOG("LightSystemPlugin: WebGL context lost")}function lightSystemContextRestored(){initLightSystem();LOG("LightSystemPlugin: WebGL context restored")}}drawLight(light){if(headlessMode||!glEnable||!this.lightShader)return;glFlush();glContext.useProgram(this.lightShader);glContext.bindVertexArray(this.lightVAO);const s=vec2(2*cameraScale).divide(mainCanvasSize);const rotatedCam=cameraPos.rotate(-cameraAngle);const p=vec2(-1).subtract(rotatedCam.multiply(s));const ca=cos(cameraAngle);const sa=sin(cameraAngle);const transform=[s.x*ca,s.y*sa,0,0,-s.x*sa,s.y*ca,0,0,1,1,1,0,p.x,p.y,0,1];const ls=this.lightShader;glContext.uniformMatrix4fv(glContext.getUniformLocation(ls,"m"),false,transform);glContext.uniform2f(glContext.getUniformLocation(ls,"lightPos"),light.pos.x,light.pos.y);glContext.uniform1f(glContext.getUniformLocation(ls,"radius"),light.radius);glContext.uniform1f(glContext.getUniformLocation(ls,"fadeRange"),light.fadeRange);const c=light.color;glContext.uniform4f(glContext.getUniformLocation(ls,"color"),c.r,c.g,c.b,c.a);glContext.drawArrays(glContext.TRIANGLE_STRIP,0,4);glSetInstancedMode(true)}}class Light extends EngineObject{constructor(pos,radius,color,fadeRange){super(pos,vec2(1),undefined,0,color);ASSERT(isNumber(radius)&&radius>=0,"Light radius must be a non-negative number");ASSERT(fadeRange===undefined||isNumber(fadeRange)&&fadeRange>=0,"Light fadeRange must be a non-negative number when provided");this.radius=radius;this.fadeRange=fadeRange===undefined?radius:fadeRange}render(){}renderLight(){lightSystem&&lightSystem.drawLight(this)}}class ZzFXMusic extends Sound{constructor(zzfxMusic){super(undefined);if(!soundEnable||headlessMode)return;this.randomness=0;this.sampleChannels=zzfxM(...zzfxMusic);this.sampleRate=audioDefaultSampleRate}playMusic(volume=1,loop=true){return super.play(undefined,volume,1,0,loop)}}function zzfxM(instruments,patterns,sequence,BPM=125){let i,j,k;let instrumentParameters;let note;let sample;let patternChannel;let notFirstBeat;let stop;let instrument;let attenuation;let outSampleOffset;let isSequenceEnd;let sampleOffset=0;let nextSampleOffset;let sampleBuffer=[];let leftChannelBuffer=[];let rightChannelBuffer=[];let channelIndex=0;let panning=0;let hasMore=1;let sampleCache={};let beatLength=audioDefaultSampleRate/BPM*60>>2;for(;hasMore;channelIndex++){sampleBuffer=[hasMore=notFirstBeat=outSampleOffset=0];sequence.forEach((patternIndex,sequenceIndex)=>{patternChannel=patterns[patternIndex][channelIndex]||[0,0,0];hasMore|=patterns[patternIndex][channelIndex]&&1;nextSampleOffset=outSampleOffset+(patterns[patternIndex][0].length-2-(notFirstBeat?0:1))*beatLength;isSequenceEnd=sequenceIndex===sequence.length-1;for(i=2,k=outSampleOffset;i<patternChannel.length+isSequenceEnd;notFirstBeat=++i){note=patternChannel[i];stop=i===patternChannel.length+isSequenceEnd-1&&isSequenceEnd||instrument!==(patternChannel[0]||0)||note|0;for(j=0;j<beatLength&¬FirstBeat;j++>beatLength-99&&stop&&attenuation<1?attenuation+=1/99:0){sample=(1-attenuation)*sampleBuffer[sampleOffset++]/2||0;leftChannelBuffer[k]=(leftChannelBuffer[k]||0)-sample*panning+sample;rightChannelBuffer[k]=(rightChannelBuffer[k++]||0)+sample*panning+sample}if(note){attenuation=note%1;panning=patternChannel[1]||0;if(note|=0){sampleBuffer=sampleCache[[instrument=patternChannel[sampleOffset=0]||0,note]]=sampleCache[[instrument,note]]||(instrumentParameters=[...instruments[instrument]],instrumentParameters[2]=(instrumentParameters[2]||220)*2**(note/12-1),note>0?zzfxG(...instrumentParameters):[])}}}outSampleOffset=nextSampleOffset})}return[leftChannelBuffer,rightChannelBuffer]}let uiSystem;let uiDebug=0;function uiSetDebug(debugMode){uiDebug=typeof debugMode==="boolean"?debugMode?1:0:debugMode}class UISystemPlugin{constructor(context=mainContext){ASSERT(!uiSystem,"UI system already initialized");uiSystem=this;this.activateOnPress=false;this.defaultColor=WHITE;this.defaultLineColor=BLACK;this.defaultTextColor=BLACK;this.defaultButtonColor=hsl(0,0,.7);this.defaultHoverColor=hsl(0,0,.9);this.defaultDisabledColor=hsl(0,0,.3);this.defaultGradientColor=undefined;this.defaultLineWidth=4;this.defaultCornerRadius=0;this.defaultTextFitScale=.8;this.defaultFont=fontDefault;this.defaultSoundPress=undefined;this.defaultSoundRelease=undefined;this.defaultSoundClick=undefined;this.defaultShadowColor=CLEAR_BLACK;this.defaultShadowBlur=5;this.defaultShadowOffset=vec2(5);this.nativeHeight=0;this.navigationObject=undefined;this.navigationTimer=new Timer(undefined,true);this.navigationDelay=.2;this.navigationDirection=1;this.navigationMode=false;this.uiObjects=[];this.uiContext=context;this.activeObject=undefined;this.hoverObject=undefined;this.lastHoverObject=undefined;this.confirmDialog=undefined;this._keyInputObject=undefined;this._onKeyDown=e=>this._keyInputObject?.onKeyDown(e);engineAddPlugin(uiUpdate,uiRender);function updateTransforms(o){let targetPos,targetSize;if(o.parent){targetPos=o.parent.nativePos;targetSize=o.parent.size}else{targetPos=uiSystem.screenToNative(mainCanvasSize.scale(.5));targetSize=uiSystem.nativeHeight?vec2(mainCanvasSize.x*uiSystem.nativeHeight/mainCanvasSize.y,uiSystem.nativeHeight):mainCanvasSize}const a=o.anchor;o.nativePos=targetPos.add(targetSize.multiply(a).scale(.5)).subtract(o.size.multiply(a).scale(.5)).add(o.localPos)}function uiUpdate(){if(uiSystem.activeObject&&!uiSystem.activeObject.visible)uiSystem.activeObject=undefined;uiSystem.lastHoverObject=uiSystem.hoverObject;uiSystem.hoverObject=undefined;if(mouseWasPressed(0)){uiSystem.navigationMode=false;uiSystem.navigationObject=undefined}if(uiSystem.keyInputObject){uiSystem.activeObject=uiSystem.keyInputObject;uiSystem.hoverObject=uiSystem.keyInputObject;uiSystem.navigationMode=false;uiSystem.navigationObject=undefined}const navigableObjects=uiSystem.getNavigableObjects();if(!navigableObjects.length)uiSystem.navigationObject=undefined;else if(!uiSystem.keyInputObject){if(!navigableObjects.includes(uiSystem.navigationObject))uiSystem.navigationObject=undefined;if(!isTouchDevice)if(uiSystem.navigationMode&&!uiSystem.navigationObject){uiSystem.navigationObject=navigableObjects.find(o=>o.navigationAutoSelect)}if(!uiSystem.navigationTimer.active()){const direction=sign(uiSystem.getNavigationDirection());if(direction){let newNavigationObject;if(!uiSystem.navigationObject){newNavigationObject=navigableObjects.find(o=>o.navigationAutoSelect);if(!newNavigationObject){const newIndex=direction>0?0:navigableObjects.length-1;newNavigationObject=navigableObjects[newIndex]}}else{const currentIndex=navigableObjects.indexOf(uiSystem.navigationObject);const newIndex=mod(currentIndex+direction,navigableObjects.length);newNavigationObject=navigableObjects[newIndex]}if(uiSystem.navigationObject!==newNavigationObject){uiSystem.navigationMode=true;uiSystem.hoverObject=undefined;uiSystem.navigationObject=newNavigationObject;uiSystem.navigationTimer.set(uiSystem.navigationDelay);newNavigationObject.soundPress&&newNavigationObject.soundPress.play()}}}if(uiSystem.navigationObject)if(uiSystem.getNavigationWasPressed())uiSystem.navigationObject.navigatePressed()}for(let i=uiSystem.uiObjects.length;i--;){const o=uiSystem.uiObjects[i];o.parent||updateObject(o)}uiSystem.uiObjects=uiSystem.uiObjects.filter(o=>!o.destroyed);function updateObject(o){if(o.destroyed||!o.visible)return;updateTransforms(o);for(let i=o.children.length;i--;){const child=o.children[i];child&&updateObject(child)}if(!o.destroyed)o.update()}}function uiRender(){const context=uiSystem.uiContext;context.save();if(uiSystem.nativeHeight){const s=mainCanvasSize.y/uiSystem.nativeHeight;context.translate(-s*mainCanvasSize.x/2,0);context.scale(s,s);context.translate(mainCanvasSize.x/2/s,0)}function renderObject(o){if(!o.visible)return;updateTransforms(o);o.render();for(const c of o.children)renderObject(c)}uiSystem.uiObjects.forEach(o=>o.parent||renderObject(o));if(uiDebug>0){function renderDebug(o,visible=true){visible&&=!!o.visible;updateTransforms(o);o.renderDebug(visible);for(const c of o.children)renderDebug(c,visible)}uiSystem.uiObjects.forEach(o=>o.parent||renderDebug(o))}context.restore()}}drawRect(pos,size,color=WHITE,lineWidth=0,lineColor=BLACK,cornerRadius=0,gradientColor,shadowColor=BLACK,shadowBlur=0,shadowOffset=vec2()){ASSERT(isVector2(pos),"pos must be a vec2");ASSERT(isVector2(size),"size must be a vec2");ASSERT(isColor(color),"color must be a color");ASSERT(isNumber(lineWidth),"lineWidth must be a number");ASSERT(isColor(lineColor),"lineColor must be a color");ASSERT(isNumber(cornerRadius),"cornerRadius must be a number");const context=uiSystem.uiContext;if(gradientColor){const g=context.createLinearGradient(pos.x,pos.y-size.y/2,pos.x,pos.y+size.y/2);const c=color.toString();g.addColorStop(0,c);g.addColorStop(.5,gradientColor.toString());g.addColorStop(1,c);context.fillStyle=g}else context.fillStyle=color.toString();if(shadowBlur||shadowOffset.x||shadowOffset.y)if(shadowColor.a>0){context.shadowColor=shadowColor.toString();context.shadowBlur=shadowBlur;context.shadowOffsetX=shadowOffset.x;context.shadowOffsetY=shadowOffset.y}context.beginPath();if(cornerRadius&&context["roundRect"])context["roundRect"](pos.x-size.x/2,pos.y-size.y/2,size.x,size.y,cornerRadius);else context.rect(pos.x-size.x/2,pos.y-size.y/2,size.x,size.y);context.fill();context.shadowColor="#0000";if(lineWidth&&lineColor.a>0){context.strokeStyle=lineColor.toString();context.lineWidth=lineWidth;context.stroke()}}drawLine(posA,posB,lineWidth=uiSystem.defaultLineWidth,lineColor=uiSystem.defaultLineColor){ASSERT(isVector2(posA),"posA must be a vec2");ASSERT(isVector2(posB),"posB must be a vec2");ASSERT(isNumber(lineWidth),"lineWidth must be a number");ASSERT(isColor(lineColor),"lineColor must be a color");const context=uiSystem.uiContext;context.strokeStyle=lineColor.toString();context.lineWidth=lineWidth;context.beginPath();context.lineTo(posA.x,posA.y);context.lineTo(posB.x,posB.y);context.stroke()}drawTile(pos,size,tileInfo,color=uiSystem.defaultColor,angle=0,mirror=false,shadowColor=BLACK,shadowBlur=0,shadowOffset=vec2()){const context=uiSystem.uiContext;if(shadowBlur||shadowOffset.x||shadowOffset.y)if(shadowColor.a>0){context.shadowColor=shadowColor.toString();context.shadowBlur=shadowBlur;context.shadowOffsetX=shadowOffset.x;context.shadowOffsetY=shadowOffset.y}drawTile(pos,size,tileInfo,color,angle,mirror,CLEAR_BLACK,false,true,context);context.shadowColor="#0000"}drawText(text,pos,size,color=uiSystem.defaultColor,lineWidth=uiSystem.defaultLineWidth,lineColor=uiSystem.defaultLineColor,align="center",font=uiSystem.defaultFont,fontStyle="",applyMaxWidth=true,textShadow=undefined,shadowColor=BLACK,shadowBlur=0,shadowOffset=vec2()){const context=uiSystem.uiContext;if(shadowColor.a>0){if(textShadow)drawTextScreen(text,pos.add(textShadow),size.y,shadowColor,lineWidth,lineColor,align,font,fontStyle,applyMaxWidth?size.x:undefined,0,context);if(shadowBlur||shadowOffset.x||shadowOffset.y){context.shadowColor=shadowColor.toString();context.shadowBlur=shadowBlur;context.shadowOffsetX=shadowOffset.x;context.shadowOffsetY=shadowOffset.y}}drawTextScreen(text,pos,size.y,color,lineWidth,lineColor,align,font,fontStyle,applyMaxWidth?size.x:undefined,0,context);context.shadowColor="#0000"}setupDragAndDrop(onDrop,onDragEnter,onDragLeave,onDragOver){if(this._dragListeners)for(const[type,listener]of this._dragListeners)document.removeEventListener(type,listener);this._dragListeners=[];const setCallback=(callback,listenerType)=>{const listener=e=>{e.preventDefault();callback&&callback(e)};document.addEventListener(listenerType,listener);this._dragListeners.push([listenerType,listener])};setCallback(onDrop,"drop");setCallback(onDragEnter,"dragenter");setCallback(onDragLeave,"dragleave");setCallback(onDragOver,"dragover")}screenToNative(pos){if(!uiSystem.nativeHeight)return pos;const s=mainCanvasSize.y/uiSystem.nativeHeight;const sInv=1/s;const p=pos.copy();p.x+=s*mainCanvasSize.x/2;p.x*=sInv;p.y*=sInv;p.x-=sInv*mainCanvasSize.x/2;return p}get keyInputObject(){return this._keyInputObject}set keyInputObject(obj){const had=!!this._keyInputObject;this._keyInputObject=obj;if(!had&&obj)document.addEventListener("keydown",this._onKeyDown);else if(had&&!obj)document.removeEventListener("keydown",this._onKeyDown)}destroyObjects(){for(const o of this.uiObjects)o.parent||o.destroy();this.uiObjects=this.uiObjects.filter(o=>!o.destroyed);this.activeObject=undefined;this.hoverObject=undefined;this.lastHoverObject=undefined;this.keyInputObject=undefined}getNavigableObjects(){function getNavigableRecursive(o){if(!o.visible||o.disabled)return;if(o.isInteractive()&&o.navigationIndex!==undefined)objects.push(o);for(let i=o.children.length;i--;)getNavigableRecursive(o.children[i])}let objects=[];for(let i=uiSystem.uiObjects.length;i--;){const o=uiSystem.uiObjects[i];if(uiSystem.confirmDialog&&o!==uiSystem.confirmDialog)continue;o.parent||getNavigableRecursive(o)}objects.sort((a,b)=>a.navigationIndex-b.navigationIndex);return objects}getNavigationDirection(){const vertical=uiSystem.navigationDirection===1;const both=uiSystem.navigationDirection===2;if(isUsingGamepad){const stick=gamepadStick(0,gamepadPrimary);const dpad=gamepadDpad(gamepadPrimary);if(both)return-(stick.y||dpad.y)||(stick.x||dpad.x);return vertical?-(stick.y||dpad.y):stick.x||dpad.x}const up="ArrowUp",down="ArrowDown",left="ArrowLeft",right="ArrowRight";if(both){return keyIsDown(up)||keyIsDown(left)?-1:keyIsDown(down)||keyIsDown(right)?1:0}const back=vertical?up:left;const forward=vertical?down:right;return keyIsDown(back)?-1:keyIsDown(forward)?1:0}getNavigationOtherDirection(){if(uiSystem.navigationDirection===2)return 0;const vertical=uiSystem.navigationDirection===1;if(isUsingGamepad){const stick=gamepadStick(0,gamepadPrimary);const dpad=gamepadDpad(gamepadPrimary);return!vertical?stick.y||dpad.y:stick.x||dpad.x}const back=!vertical?"ArrowUp":"ArrowLeft";const forward=!vertical?"ArrowDown":"ArrowRight";return keyIsDown(back)?-1:keyIsDown(forward)?1:0}getNavigationWasPressed(){return isUsingGamepad?gamepadWasPressed(0,gamepadPrimary):keyWasPressed("Space")||keyWasPressed("Enter")}showConfirmDialog(text="Are you sure?",yesCallback,noCallback,size=vec2(500,250),exitKey="Escape"){ASSERT(!uiSystem.confirmDialog);const savedNavigationDirection=uiSystem.navigationDirection;uiSystem.navigationDirection=2;const confirmMenu=new UIObject(vec2(),size);uiSystem.confirmDialog=confirmMenu;confirmMenu.onRender=()=>{const backgroundColor=hsl(0,0,0,.7);uiSystem.drawRect(vec2(),vec2(1e9),backgroundColor)};confirmMenu.onUpdate=()=>{if(keyWasPressed(exitKey))closeMenu()};confirmMenu.isMouseOverlapping=()=>true;const gap=50;const textTitle=new UIText(vec2(0,-50),vec2(size.x-gap,70),text);confirmMenu.addChild(textTitle);const buttonYes=new UIButton(vec2(-80,50),vec2(120,70),"Yes");buttonYes.textHeight=40;buttonYes.navigationIndex=1;buttonYes.hoverColor=hsl(0,1,.5);buttonYes.onClick=()=>{closeMenu();yesCallback&&yesCallback()};confirmMenu.addChild(buttonYes);const buttonNo=new UIButton(vec2(80,50),vec2(120,70),"No");buttonNo.textHeight=40;buttonNo.navigationIndex=2;buttonNo.navigationAutoSelect=true;buttonNo.onClick=()=>{closeMenu();noCallback&&noCallback()};confirmMenu.addChild(buttonNo);function closeMenu(){ASSERT(uiSystem.confirmDialog===confirmMenu);confirmMenu.destroy();uiSystem.confirmDialog=undefined;uiSystem.navigationDirection=savedNavigationDirection;inputClear()}return confirmMenu}}class UIObject{constructor(pos=vec2(),size=vec2()){ASSERT(isVector2(pos),"ui object pos must be a vec2");ASSERT(isVector2(size),"ui object size must be a vec2");this.localPos=pos.copy();this.nativePos=pos.copy();this.size=size.copy();this.color=uiSystem.defaultColor.copy();this.activeColor=undefined;this.text=undefined;this.disabledColor=uiSystem.defaultDisabledColor.copy();this.disabled=false;this.textColor=uiSystem.defaultTextColor.copy();this.hoverColor=uiSystem.defaultHoverColor.copy();this.lineColor=uiSystem.defaultLineColor.copy();this.gradientColor=uiSystem.defaultGradientColor?uiSystem.defaultGradientColor.copy():undefined;this.lineWidth=uiSystem.defaultLineWidth;this.cornerRadius=uiSystem.defaultCornerRadius;this.font=uiSystem.defaultFont;this.fontStyle=undefined;this.textWidth=undefined;this.textHeight=undefined;this.textFitScale=uiSystem.defaultTextFitScale;this.textShadow=undefined;this.textLineColor=uiSystem.defaultLineColor.copy();this.textLineWidth=0;this.visible=true;this.children=[];this.parent=undefined;this.extraTouchSize=0;this.soundPress=uiSystem.defaultSoundPress;this.soundRelease=uiSystem.defaultSoundRelease;this.soundClick=uiSystem.defaultSoundClick;this.interactive=false;this.dragActivate=false;this.canBeHover=true;this.shadowColor=uiSystem.defaultShadowColor?.copy();this.shadowBlur=uiSystem.defaultShadowBlur;this.shadowOffset=uiSystem.defaultShadowOffset?.copy();this.navigationIndex=undefined;this.navigationAutoSelect=false;this.anchor=vec2();uiSystem.uiObjects.push(this)}addChild(child){ASSERT(!child.parent&&!this.children.includes(child));this.children.push(child);child.parent=this;return child}removeChild(child){ASSERT(child.parent===this&&this.children.includes(child));this.children.splice(this.children.indexOf(child),1);child.parent=undefined}destroy(){if(this.destroyed)return;if(uiSystem.activeObject===this)uiSystem.activeObject=undefined;if(uiSystem.hoverObject===this)uiSystem.hoverObject=undefined;if(uiSystem.lastHoverObject===this)uiSystem.lastHoverObject=undefined;if(uiSystem.navigationObject===this)uiSystem.navigationObject=undefined;if(uiSystem.keyInputObject===this)uiSystem.keyInputObject=undefined;this.destroyed=1;this.parent?.removeChild(this);for(const child of this.children){child.parent=undefined;child.destroy()}this.children.length=0}isMouseOverlapping(){if(!mouseInWindow)return false;const size=!isTouchDevice?this.size:this.size.add(vec2(this.extraTouchSize||0));const pos=uiSystem.screenToNative(mousePosScreen);return isOverlapping(this.nativePos,size,pos)}update(){this.onUpdate();if(this.disabled){if(this===uiSystem.activeObject)uiSystem.activeObject=undefined;if(this===uiSystem.keyInputObject)uiSystem.keyInputObject=undefined}if(uiSystem.keyInputObject)return;const wasHover=uiSystem.lastHoverObject===this;const isActive=this.isActiveObject();const mouseDown=mouseIsDown(0);const mousePress=this.dragActivate?mouseDown:mouseWasPressed(0);if(this.canBeHover)if(!uiSystem.navigationMode)if(mousePress||isActive||!mouseDown&&!isTouchDevice)if(!uiSystem.hoverObject&&this.isMouseOverlapping())uiSystem.hoverObject=this;if(this.isHoverObject()){if(!this.disabled){if(mousePress){if(this.interactive){if(!this.dragActivate||(!wasHover||mouseWasPressed(0)))this.onPress();this.soundPress&&this.soundPress.play();if(uiSystem.activeObject&&!isActive)uiSystem.activeObject.onRelease();uiSystem.activeObject=this;if(uiSystem.activateOnPress)this.click(!this.soundPress)}}if(!uiSystem.activateOnPress)if(!mouseDown&&this.isActiveObject()&&this.interactive)this.click()}mousePress&&inputClearKey(0,0,0,1,0)}if(isActive)if(!mouseDown||this.dragActivate&&!this.isHoverObject()){this.onRelease();this.soundRelease&&this.soundRelease.play();uiSystem.activeObject=undefined}if(this.isHoverObject()!==wasHover)this.isHoverObject()?this.onEnter():this.onLeave()}render(){this.onRender();if(!this.size.x||!this.size.y)return;const isNavigationObject=this.isNavigationObject();const lineColor=isNavigationObject?this.color:this.interactive&&this.isActiveObject()&&!this.disabled?this.color:this.lineColor;const color=isNavigationObject?this.hoverColor:this.disabled?this.disabledColor:this.interactive?this.isActiveObject()?this.activeColor||this.hoverColor:this.isHoverObject()?this.hoverColor:this.color:this.color;const lineWidth=this.lineWidth*(isNavigationObject?1.5:1);uiSystem.drawRect(this.nativePos,this.size,color,lineWidth,lineColor,this.cornerRadius,this.gradientColor,this.shadowColor,this.shadowBlur,this.shadowOffset)}getTextSize(){return vec2(this.textWidth||this.textFitScale*this.size.x,this.textHeight||this.textFitScale*this.size.y)}navigatePressed(){this.click()}isHoverObject(){return uiSystem.hoverObject===this}isActiveObject(){return uiSystem.activeObject===this}isNavigationObject(){return uiSystem.navigationObject===this}isKeyInputObject(){return uiSystem.keyInputObject===this}isInteractive(){return this.interactive&&this.visible&&!this.disabled}toString(){let text="type = "+this.constructor.name;if(this.text)text+="\ntext = "+this.text;if(this.nativePos.x||this.nativePos.y)text+="\nnativePos = "+this.nativePos;if(this.localPos.x||this.localPos.y)text+="\nlocalPos = "+this.localPos;if(this.size.x||this.size.y)text+="\nsize = "+this.size;if(this.color)text+="\ncolor = "+this.color;return text}renderDebug(visible=true){const color=!visible?GREEN:this.isHoverObject()?YELLOW:this.disabled?PURPLE:this.interactive?RED:BLUE;uiSystem.drawRect(this.nativePos,this.size,CLEAR_BLACK,4,color)}click(playSound=true){this.onClick();if(playSound&&this.soundClick)this.soundClick.play()}onUpdate(){}onRender(){}onEnter(){}onLeave(){}onPress(){}onRelease(){}onClick(){}onChange(){}}class UIText extends UIObject{constructor(pos,size,text="",align="center",font=uiSystem.defaultFont){super(pos,size);ASSERT(isStringLike(text),"ui text must be a string");ASSERT(["left","center","right"].includes(align),"ui text align must be left, center, or right");ASSERT(isStringLike(font),"ui text font must be a string");this.text=text;this.align=align;this.font=font;this.canBeHover=false;this.color=CLEAR_BLACK;this.shadowColor=CLEAR_BLACK;this.gradientColor=undefined;this.lineWidth=0;this.textFitScale=1}render(){super.render();const textSize=this.getTextSize();uiSystem.drawText(this.text,this.nativePos,textSize,this.textColor,this.textLineWidth,this.textLineColor,this.align,this.font,this.fontStyle,true,this.textShadow,this.shadowColor,this.shadowBlur,this.shadowOffset)}}class UITextInput extends UIObject{constructor(pos,size,text=""){super(pos,size);ASSERT(isStringLike(text),"ui text must be a string");this.maxLength=0;this.text=text;this.interactive=true;this.canBeHover=true}click(){uiSystem.keyInputObject=this;this.onClick()}stopEditing(){if(!this.isKeyInputObject())return;if(this.soundRelease)this.soundRelease.play();uiSystem.activeObject=undefined;uiSystem.keyInputObject=undefined;this.onChange()}onKeyDown(e){const code=e.code,key=e.key;if(code==="Backspace")this.text=this.text.slice(0,-1);else if(code==="Enter"||code==="Escape")this.stopEditing();else if(key.length===1){if(!this.maxLength||this.text.length<this.maxLength)this.text+=key}}update(){super.update();if(!this.isKeyInputObject())return;if(mouseWasPressed(0)&&!this.isMouseOverlapping()||gamepadWasPressed(0,gamepadPrimary)){this.stopEditing();inputClearKey(0,0)}}render(){super.render();const textSize=this.getTextSize();let text=this.text;if(this.isKeyInputObject())text+=timeReal%1<.5?"█":"░";uiSystem.drawText(text,this.nativePos,textSize,this.textColor,this.textLineWidth,this.textLineColor,this.align,this.font,this.fontStyle,true,this.textShadow)}}class UITile extends UIObject{constructor(pos,size,tileInfo,color=WHITE,angle=0,mirror=false){super(pos,size);ASSERT(tileInfo instanceof TileInfo,"ui tile tileInfo must be a TileInfo");ASSERT(isColor(color),"ui tile color must be a color");ASSERT(isNumber(angle),"ui tile angle must be a number");this.tileInfo=tileInfo;this.angle=angle;this.mirror=mirror;this.color=color.copy();this.shadowColor=CLEAR_BLACK}render(){uiSystem.drawTile(this.nativePos,this.size,this.tileInfo,this.color,this.angle,this.mirror,this.shadowColor,this.shadowBlur,this.shadowOffset)}}class UIButton extends UIObject{constructor(pos,size,text="",color=uiSystem.defaultButtonColor){super(pos,size);ASSERT(isStringLike(text),"ui button must be a string");ASSERT(isColor(color),"ui button color must be a color");this.textOffset=vec2();this.text=text;this.color=color.copy();this.interactive=true}render(){super.render();const textSize=this.getTextSize();uiSystem.drawText(this.text,this.nativePos.add(this.textOffset),textSize,this.textColor,this.textLineWidth,this.textLineColor,this.align,this.font,this.fontStyle,true,this.textShadow)}}class UICheckbox extends UIObject{constructor(pos,size,checked=false,text="",color=uiSystem.defaultButtonColor){super(pos,size);ASSERT(isStringLike(text),"ui checkbox must be a string");ASSERT(isColor(color),"ui checkbox color must be a color");this.checked=checked;this.text=text;this.color=color.copy();this.interactive=true}click(){this.checked=!this.checked;this.onClick();this.onChange()}render(){super.render();if(this.checked){const p=this.cornerRadius/min(this.size.x,this.size.y)*2;const length=lerp(1,2**.5/2,p)/2;let s=this.size.scale(length);uiSystem.drawLine(this.nativePos.add(s.multiply(vec2(-1))),this.nativePos.add(s.multiply(vec2(1))),this.lineWidth,this.lineColor);uiSystem.drawLine(this.nativePos.add(s.multiply(vec2(-1,1))),this.nativePos.add(s.multiply(vec2(1,-1))),this.lineWidth,this.lineColor)}const textSize=this.getTextSize();const pos=this.nativePos.add(vec2(this.size.x,0));uiSystem.drawText(this.text,pos,textSize,this.textColor,this.textLineWidth,this.textLineColor,"left",this.font,this.fontStyle,false,this.textShadow)}}class UISlider extends UIObject{constructor(pos,size,value=.5,text="",color=uiSystem.defaultButtonColor,handleColor=WHITE){super(pos,size);ASSERT(isNumber(value),"ui slider value must be a number");ASSERT(isStringLike(text),"ui slider must be a string");ASSERT(isColor(color),"ui slider color must be a color");ASSERT(isColor(handleColor),"ui slider handleColor must be a color");this.value=value;this.handleColor=handleColor.copy();this.fillMode=false;this.text=text;this.color=color.copy();this.interactive=true}update(){super.update();if(!this.interactive)return;const oldValue=this.value;if(this.isActiveObject()){const isHorizontal=this.size.x>this.size.y;const handleSize=isHorizontal?this.size.y:this.size.x;const barSize=isHorizontal?this.size.x:this.size.y;const centerPos=isHorizontal?this.nativePos.x:this.nativePos.y;const handleWidth=barSize-handleSize;const p1=centerPos-handleWidth/2;const p2=centerPos+handleWidth/2;const p=uiSystem.screenToNative(mousePosScreen);this.value=isHorizontal?percent(p.x,p1,p2):percent(p.y,p2,p1)}else if(this.isNavigationObject()){const direction=uiSystem.getNavigationOtherDirection();if(!uiSystem.navigationTimer.active())this.value=clamp(this.value+direction*.01)}this.value===oldValue||this.onChange()}render(){super.render();const isHorizontal=this.size.x>this.size.y;const barWidth=isHorizontal?this.size.x:this.size.y;const handleWidth=isHorizontal?this.size.y:this.size.x;if(this.fillMode){const minWidth=min(handleWidth,this.cornerRadius*2);const progressWidth=lerp(minWidth,barWidth,this.value);const p=(progressWidth-barWidth)*(isHorizontal?.5:-.5);const pos=this.nativePos.add(isHorizontal?vec2(p,0):vec2(0,p));const color=this.disabled?this.disabledColor:this.handleColor;const drawSize=isHorizontal?vec2(progressWidth,this.size.y):vec2(this.size.x,progressWidth);uiSystem.drawRect(pos,drawSize,color,this.lineWidth,this.lineColor,this.cornerRadius,this.gradientColor)}else{const value=clamp(isHorizontal?this.value:1-this.value);const p=(barWidth-handleWidth)*(value-.5);const pos=this.nativePos.add(isHorizontal?vec2(p,0):vec2(0,p));const color=this.disabled?this.disabledColor:this.handleColor;const drawSize=vec2(handleWidth);uiSystem.drawRect(pos,drawSize,color,this.lineWidth,this.lineColor,this.cornerRadius,this.gradientColor)}const textSize=this.getTextSize();uiSystem.drawText(this.text,this.nativePos,textSize,this.textColor,this.textLineWidth,this.textLineColor,this.align,this.font,this.fontStyle,true,this.textShadow)}navigatePressed(){this.value=this.value?0:1;this.onChange();this.onRelease();super.navigatePressed()}}class UIVideo extends UIObject{constructor(pos,size,src,autoplay=false,loop=false,volume=1){super(pos,size||vec2());ASSERT(isStringLike(src),"video src must be a string");ASSERT(isNumber(volume),"video volume must be a number");this.color=BLACK;this.cornerRadius=0;this.volume=volume;this.video=document.createElement("video");this.video.loop=loop;this.video.volume=clamp(volume*soundVolume);this.video.muted=!soundEnable;this.video.style.display="none";this.video.src=src;document.body.appendChild(this.video);autoplay&&this.play()}async play(){try{await this.video.play()}catch(e){}}pause(){this.video.pause()}stop(){this.video.pause();this.video.currentTime=0}isLoading(){return this.video.readyState<this.video.HAVE_CURRENT_DATA}isPaused(){return this.video.paused}isPlaying(){return!this.isPaused()&&!this.hasEnded()&&!this.isLoading()}hasEnded(){return this.video.ended}setVolume(volume){this.volume=volume;this.video.volume=clamp(volume*soundVolume)}setPlaybackRate(rate){this.video.playbackRate=rate}getCurrentTime(){return this.video.currentTime||0}getDuration(){return this.video.duration||0}getVideoSize(){return vec2(this.video.videoWidth,this.video.videoHeight)}setTime(time){this.video.currentTime=clamp(time,0,this.getDuration())}update(){super.update();this.video.volume=clamp(this.volume*soundVolume)}render(){super.render();if(this.isLoading())return;const context=uiSystem.uiContext;const s=this.size;context.save();context.translate(this.nativePos.x,this.nativePos.y);context.drawImage(this.video,-s.x/2,-s.y/2,s.x,s.y);context.restore()}destroy(){if(this.destroyed)return;this.video.pause();this.video.remove();super.destroy()}}class UILayout extends UIObject{constructor(pos,columns=1,gap=10,padding=10,transparent=false){super(pos);ASSERT(isNumber(columns)&&columns>=1,"ui layout columns must be a number >= 1");ASSERT(isNumber(gap),"ui layout gap must be a number");ASSERT(isNumber(padding),"ui layout padding must be a number");this.columns=columns;this.gap=gap;this.padding=padding;if(transparent){this.color=CLEAR_BLACK;this.gradientColor=undefined;this.lineWidth=0;this.shadowColor=CLEAR_BLACK}this.relayout()}addChild(child){super.addChild(child);this.relayout();return child}removeChild(child){super.removeChild(child);this.relayout()}relayout(){const n=this.children.length;if(!n){this.size=vec2(this.padding*2);return}const cols=this.columns;const rows=ceil(n/cols);const colWidths=new Array(cols).fill(0);const rowHeights=new Array(rows).fill(0);for(let i=0;i<n;++i){const col=i%cols;const row=floor(i/cols);const child=this.children[i];colWidths[col]=max(colWidths[col],child.size.x);rowHeights[row]=max(rowHeights[row],child.size.y)}let contentWidth=this.gap*(cols-1);for(const w of colWidths)contentWidth+=w;let contentHeight=this.gap*(rows-1);for(const h of rowHeights)contentHeight+=h;const colOffsets=new Array(cols);let xAcc=0;for(let c=0;c<cols;++c){colOffsets[c]=xAcc;xAcc+=colWidths[c]}const rowOffsets=new Array(rows);let yAcc=0;for(let r=0;r<rows;++r){rowOffsets[r]=yAcc;yAcc+=rowHeights[r]}for(let i=0;i<n;++i){const col=i%cols;const row=floor(i/cols);const x=-contentWidth/2+colOffsets[col]+this.gap*col+colWidths[col]/2;const y=-contentHeight/2+rowOffsets[row]+this.gap*row+rowHeights[row]/2;this.children[i].localPos=vec2(x,y)}this.size=vec2(contentWidth+this.padding*2,contentHeight+this.padding*2)}}let box2d;let box2dDebug=false;function box2dSetDebug(enable){box2dDebug=enable}class Box2dObject extends EngineObject{constructor(pos=vec2(),size=vec2(),tileInfo,angle=0,color,bodyType=box2d.bodyTypeDynamic,renderOrder=0){super(pos,size,tileInfo,angle,color,renderOrder);const bodyDef=new box2d.instance.b2BodyDef;bodyDef.set_type(bodyType);bodyDef.set_position(box2d.vec2dTo(pos));bodyDef.set_angle(-angle);this.body=box2d.world.CreateBody(bodyDef);this.lineColor=BLACK;this.edgeLists=[];this.edgeLoops=[];this.body.object=this;box2d.objects.push(this)}destroy(){if(this.destroyed)return;ASSERT(this.body,"Box2dObject has no body to destroy");box2d.world.DestroyBody(this.body);const i=box2d.objects.indexOf(this);if(i>=0)box2d.objects.splice(i,1);super.destroy()}updatePhysics(){}render(){if(this.tileInfo)super.render();else this.drawFixtures(this.color,this.lineColor,this.lineWidth)}renderDebugInfo(){const isAsleep=!this.getIsAwake();const isStatic=this.getBodyType()===box2d.bodyTypeStatic;const color=rgb(isAsleep?1:0,isAsleep?1:0,isStatic?1:0,.5);this.drawFixtures(color)}drawFixtures(color=WHITE,lineColor=BLACK,lineWidth=.1,useWebGL,context){this.getFixtureList().forEach(fixture=>{const shape=box2d.castShapeObject(fixture.GetShape());if(shape.GetType()!==box2d.instance.b2Shape.e_edge){box2d.drawFixture(fixture,this.pos,this.angle,color,lineColor,lineWidth,useWebGL,context)}});this.edgeLists.forEach(points=>drawLineList(points,lineWidth,lineColor,false,this.pos,this.angle));this.edgeLoops.forEach(points=>drawLineList(points,lineWidth,lineColor,true,this.pos,this.angle))}beginContact(otherObject){}endContact(otherObject){}addShape(shape,density=1,friction=.2,restitution=0,isSensor=false){ASSERT(isNumber(density),"density must be a number");ASSERT(isNumber(friction),"friction must be a number");ASSERT(isNumber(restitution),"restitution must be a number");const fd=new box2d.instance.b2FixtureDef;fd.set_shape(shape);fd.set_density(density);fd.set_friction(friction);fd.set_restitution(restitution);fd.set_isSensor(isSensor);return this.body.CreateFixture(fd)}addBox(size=vec2(1),offset=vec2(),angle=0,density,friction,restitution,isSensor){ASSERT(isVector2(size),"size must be a Vector2");ASSERT(size.x>0&&size.y>0,"size must be positive");ASSERT(isVector2(offset),"offset must be a Vector2");ASSERT(isNumber(angle),"angle must be a number");const shape=new box2d.instance.b2PolygonShape;shape.SetAsBox(size.x/2,size.y/2,box2d.vec2dTo(offset),-angle);return this.addShape(shape,density,friction,restitution,isSensor)}addPoly(points,density,friction,restitution,isSensor){ASSERT(isArray(points),"points must be an array");function box2dCreatePolygonShape(points){ASSERT(3<=points.length&&points.length<=8);const buffer=box2d.instance._malloc(points.length*8);for(let i=0,offset=0;i<points.length;++i){box2d.instance.HEAPF32[buffer+offset>>2]=points[i].x;offset+=4;box2d.instance.HEAPF32[buffer+offset>>2]=points[i].y;offset+=4}const box2dPoints=box2d.instance.wrapPointer(buffer,box2d.instance.b2Vec2);const shape=new box2d.instance.b2PolygonShape;shape.Set(box2dPoints,points.length);box2d.instance._free(buffer);return shape}const shape=box2dCreatePolygonShape(points);return this.addShape(shape,density,friction,restitution,isSensor)}addRegularPoly(diameter=1,sides=8,density,friction,restitution,isSensor){ASSERT(isNumber(diameter)&&diameter>0,"diameter must be a positive number");ASSERT(isNumber(sides)&&sides>2,"sides must be a positive number greater than 2");const points=[];const radius=diameter/2;for(let i=sides;i--;)points.push(vec2(radius,0).rotate((i+.5)/sides*PI*2));return this.addPoly(points,density,friction,restitution,isSensor)}addRandomPoly(diameter=1,density,friction,restitution,isSensor){ASSERT(isNumber(diameter)&&diameter>0,"diameter must be a positive number");const sides=randInt(3,9);const points=[];const radius=diameter/2;for(let i=sides;i--;)points.push(vec2(rand(radius/2,radius*1.5),0).rotate(i/sides*PI*2));return this.addPoly(points,density,friction,restitution,isSensor)}addCircle(diameter=1,offset=vec2(),density,friction,restitution,isSensor){ASSERT(isNumber(diameter)&&diameter>0,"diameter must be a positive number");ASSERT(isVector2(offset),"offset must be a Vector2");const shape=new box2d.instance.b2CircleShape;shape.set_m_p(box2d.vec2dTo(offset));shape.set_m_radius(diameter/2);return this.addShape(shape,density,friction,restitution,isSensor)}addEdge(point1,point2,density,friction,restitution,isSensor){ASSERT(isVector2(point1),"point1 must be a Vector2");ASSERT(isVector2(point2),"point2 must be a Vector2");const shape=new box2d.instance.b2EdgeShape;shape.Set(box2d.vec2dTo(point1),box2d.vec2dTo(point2));return this.addShape(shape,density,friction,restitution,isSensor)}addEdgeList(points,density,friction,restitution,isSensor){ASSERT(isArray(points),"points must be an array");const fixtures=[],edgePoints=[];for(let i=0;i<points.length-1;++i){const shape=new box2d.instance.b2EdgeShape;points[i-1]&&shape.set_m_vertex0(box2d.vec2dTo(points[i-1]));points[i+0]&&shape.set_m_vertex1(box2d.vec2dTo(points[i+0]));points[i+1]&&shape.set_m_vertex2(box2d.vec2dTo(points[i+1]));points[i+2]&&shape.set_m_vertex3(box2d.vec2dTo(points[i+2]));const f=this.addShape(shape,density,friction,restitution,isSensor);fixtures.push(f);edgePoints.push(points[i].copy())}edgePoints.push(points[points.length-1].copy());this.edgeLists.push(edgePoints);return fixtures}addEdgeLoop(points,density,friction,restitution,isSensor){ASSERT(isArray(points),"points must be an array");const fixtures=[],edgePoints=[];const getPoint=i=>points[mod(i,points.length)];for(let i=0;i<points.length;++i){const shape=new box2d.instance.b2EdgeShape;shape.set_m_vertex0(box2d.vec2dTo(getPoint(i-1)));shape.set_m_vertex1(box2d.vec2dTo(getPoint(i+0)));shape.set_m_vertex2(box2d.vec2dTo(getPoint(i+1)));shape.set_m_vertex3(box2d.vec2dTo(getPoint(i+2)));const f=this.addShape(shape,density,friction,restitution,isSensor);fixtures.push(f);edgePoints.push(points[i].copy())}this.edgeLoops.push(edgePoints);return fixtures}destroyFixture(fixture){this.body.DestroyFixture(fixture)}destroyAllFixtures(){this.getFixtureList().forEach(fixture=>this.destroyFixture(fixture))}getCenterOfMass(){return box2d.vec2From(this.body.GetWorldCenter())}getLinearVelocity(){return box2d.vec2From(this.body.GetLinearVelocity())}getAngularVelocity(){return this.body.GetAngularVelocity()}getMass(){return this.body.GetMass()}getInertia(){return this.body.GetInertia()}getIsAwake(){return this.body.IsAwake()}getBodyType(){return this.body.GetType()}getSpeed(){return this.getLinearVelocity().length()}setTransform(pos,angle){this.pos=pos;this.angle=angle;this.body.SetTransform(box2d.vec2dTo(pos),-angle)}setPosition(pos){this.setTransform(pos,-this.body.GetAngle())}setAngle(angle){this.setTransform(box2d.vec2From(this.body.GetPosition()),angle)}setLinearVelocity(velocity){this.body.SetLinearVelocity(box2d.vec2dTo(velocity))}setAngularVelocity(angularVelocity){this.body.SetAngularVelocity(angularVelocity)}setLinearDamping(damping){this.body.SetLinearDamping(damping)}setAngularDamping(damping){this.body.SetAngularDamping(damping)}setGravityScale(scale=1){this.body.SetGravityScale(this.gravityScale=scale)}setBullet(isBullet=true){this.body.SetBullet(isBullet)}setAwake(isAwake=true){this.body.SetAwake(isAwake)}setBodyType(type){this.body.SetType(type)}setSleepingAllowed(isAllowed=true){this.body.SetSleepingAllowed(isAllowed)}setFixedRotation(isFixed=true){this.body.SetFixedRotation(isFixed)}setCenterOfMass(center){this.setMassData(center)}setMass(mass){this.setMassData(undefined,mass)}setMomentOfInertia(momentOfInertia){this.setMassData(undefined,undefined,momentOfInertia)}resetMassData(){this.body.ResetMassData()}setMassData(localCenter,mass,momentOfInertia){const data=new box2d.instance.b2MassData;this.body.GetMassData(data);if(localCenter!==undefined)data.set_center(box2d.vec2dTo(localCenter));if(mass!==undefined)data.set_mass(mass);if(momentOfInertia!==undefined)data.set_I(momentOfInertia);this.body.SetMassData(data)}setFilterData(categoryBits=0,ignoreCategoryBits=0,groupIndex=0){this.getFixtureList().forEach(fixture=>{const filter=fixture.GetFilterData();filter.set_categoryBits(categoryBits);filter.set_maskBits(65535&~ignoreCategoryBits);filter.set_groupIndex(groupIndex);fixture.SetFilterData(filter)})}setSensor(isSensor=true){this.getFixtureList().forEach(f=>f.SetSensor(isSensor))}applyForce(force,pos){pos||=this.getCenterOfMass();this.setAwake();this.body.ApplyForce(box2d.vec2dTo(force),box2d.vec2dTo(pos))}applyAcceleration(acceleration,pos){pos||=this.getCenterOfMass();this.setAwake();const impulse=acceleration.scale(this.getMass());this.body.ApplyLinearImpulse(box2d.vec2dTo(impulse),box2d.vec2dTo(pos))}applyImpulse(impulse,pos){pos||=this.getCenterOfMass();this.setAwake();this.body.ApplyLinearImpulse(box2d.vec2dTo(impulse),box2d.vec2dTo(pos))}applyTorque(torque){this.setAwake();this.body.ApplyTorque(torque)}applyAngularAcceleration(acceleration){this.setAwake();this.body.ApplyAngularImpulse(acceleration*this.getInertia())}applyAngularImpulse(impulse){this.setAwake();this.body.ApplyAngularImpulse(impulse)}hasFixtures(){return!box2d.isNull(this.body.GetFixtureList())}getFixtureList(){const fixtures=[];for(let fixture=this.body.GetFixtureList();!box2d.isNull(fixture);){fixtures.push(fixture);fixture=fixture.GetNext()}return fixtures}hasJoints(){return!box2d.isNull(this.body.GetJointList())}getJointList(){const joints=[];for(let joint=this.body.GetJointList();!box2d.isNull(joint);){joints.push(joint);joint=joint.get_next()}return joints}}class Box2dStaticObject extends Box2dObject{constructor(pos,size,tileInfo,angle=0,color,renderOrder=0){const bodyType=box2d.bodyTypeStatic;super(pos,size,tileInfo,angle,color,bodyType,renderOrder)}}class Box2dKinematicObject extends Box2dObject{constructor(pos,size,tileInfo,angle=0,color,renderOrder=0){const bodyType=box2d.bodyTypeKinematic;super(pos,size,tileInfo,angle,color,bodyType,renderOrder)}}class Box2dTileLayer extends Box2dStaticObject{constructor(tileLayer){ASSERT(tileLayer instanceof TileCollisionLayer,"tileLayer must be a TileCollisionLayer");super(tileLayer.pos,tileLayer.size);this.tileLayer=tileLayer;this.addChild(tileLayer)}render(){}buildCollision(friction=.2,restitution=0){this.destroyAllFixtures();this.pos=this.tileLayer.pos.copy();this.size=this.tileLayer.size.copy();const processed=[];const getIndex=(x,y)=>x+y*this.size.x;const isSolidUnprocessed=(x,y)=>!processed[getIndex(x,y)]&&this.tileLayer.getCollisionData(vec2(x,y))>0;for(let x=0;x<this.size.x;++x)for(let y=0;y<this.size.y;++y){if(!isSolidUnprocessed(x,y))continue;let width=1,height=1,canExpand=true;while(isSolidUnprocessed(x+width,y))++width;while(canExpand){for(let checkX=0;checkX<width;++checkX){if(!isSolidUnprocessed(x+checkX,y+height)){canExpand=false;break}}if(canExpand)++height}for(let rectX=width;rectX--;)for(let rectY=height;rectY--;)processed[getIndex(x+rectX,y+rectY)]=true;const shapeSize=vec2(width,height);const offset=vec2(x+width/2,y+height/2);this.addBox(shapeSize,offset,0,0,friction,restitution)}}}class Box2dRaycastResult{constructor(fixture,point,normal,fraction){this.object=fixture.GetBody().object;this.fixture=fixture;this.point=point;this.normal=normal;this.fraction=fraction}}class Box2dJoint{constructor(jointDef){this.box2dJoint=box2d.castJointObject(box2d.world.CreateJoint(jointDef))}destroy(){box2d.world.DestroyJoint(this.box2dJoint);this.box2dJoint=0}getObjectA(){return this.box2dJoint.GetBodyA().object}getObjectB(){return this.box2dJoint.GetBodyB().object}getAnchorA(){return box2d.vec2From(this.box2dJoint.GetAnchorA())}getAnchorB(){return box2d.vec2From(this.box2dJoint.GetAnchorB())}getReactionForce(time){return box2d.vec2From(this.box2dJoint.GetReactionForce(1/time))}getReactionTorque(time){return this.box2dJoint.GetReactionTorque(1/time)}getCollideConnected(){return this.box2dJoint.GetCollideConnected()}isActive(){return this.box2dJoint.IsActive()}}class Box2dTargetJoint extends Box2dJoint{constructor(object,fixedObject,worldPos){object.setAwake();const jointDef=new box2d.instance.b2MouseJointDef;jointDef.set_bodyA(fixedObject.body);jointDef.set_bodyB(object.body);jointDef.set_target(box2d.vec2dTo(worldPos));jointDef.set_maxForce(2e3*object.getMass());super(jointDef)}setTarget(pos){this.box2dJoint.SetTarget(box2d.vec2dTo(pos))}getTarget(){return box2d.vec2From(this.box2dJoint.GetTarget())}setMaxForce(force){this.box2dJoint.SetMaxForce(force)}getMaxForce(){return this.box2dJoint.GetMaxForce()}setFrequency(hz){this.box2dJoint.SetFrequency(hz)}getFrequency(){return this.box2dJoint.GetFrequency()}}class Box2dDistanceJoint extends Box2dJoint{constructor(objectA,objectB,anchorA,anchorB,collide=false){anchorA||=box2d.vec2From(objectA.body.GetPosition());anchorB||=box2d.vec2From(objectB.body.GetPosition());const localAnchorA=objectA.worldToLocal(anchorA);const localAnchorB=objectB.worldToLocal(anchorB);const jointDef=new box2d.instance.b2DistanceJointDef;jointDef.set_bodyA(objectA.body);jointDef.set_bodyB(objectB.body);jointDef.set_localAnchorA(box2d.vec2dTo(localAnchorA));jointDef.set_localAnchorB(box2d.vec2dTo(localAnchorB));jointDef.set_length(anchorA.distance(anchorB));jointDef.set_collideConnected(collide);super(jointDef)}getLocalAnchorA(){return box2d.vec2From(this.box2dJoint.GetLocalAnchorA())}getLocalAnchorB(){return box2d.vec2From(this.box2dJoint.GetLocalAnchorB())}setLength(length){this.box2dJoint.SetLength(length)}getLength(){return this.box2dJoint.GetLength()}setFrequency(hz){this.box2dJoint.SetFrequency(hz)}getFrequency(){return this.box2dJoint.GetFrequency()}setDampingRatio(ratio){this.box2dJoint.SetDampingRatio(ratio)}getDampingRatio(){return this.box2dJoint.GetDampingRatio()}}class Box2dPinJoint extends Box2dDistanceJoint{constructor(objectA,objectB,pos=objectA.pos,collide=false){super(objectA,objectB,undefined,pos,collide)}}class Box2dRopeJoint extends Box2dJoint{constructor(objectA,objectB,anchorA,anchorB,extraLength=0,collide=false){anchorA||=box2d.vec2From(objectA.body.GetPosition());anchorB||=box2d.vec2From(objectB.body.GetPosition());const localAnchorA=objectA.worldToLocal(anchorA);const localAnchorB=objectB.worldToLocal(anchorB);const jointDef=new box2d.instance.b2RopeJointDef;jointDef.set_bodyA(objectA.body);jointDef.set_bodyB(objectB.body);jointDef.set_localAnchorA(box2d.vec2dTo(localAnchorA));jointDef.set_localAnchorB(box2d.vec2dTo(localAnchorB));jointDef.set_maxLength(anchorA.distance(anchorB)+extraLength);jointDef.set_collideConnected(collide);super(jointDef)}getLocalAnchorA(){return box2d.vec2From(this.box2dJoint.GetLocalAnchorA())}getLocalAnchorB(){return box2d.vec2From(this.box2dJoint.GetLocalAnchorB())}setMaxLength(length){this.box2dJoint.SetMaxLength(length)}getMaxLength(){return this.box2dJoint.GetMaxLength()}}class Box2dRevoluteJoint extends Box2dJoint{constructor(objectA,objectB,anchor,collide=false){anchor||=box2d.vec2From(objectB.body.GetPosition());const localAnchorA=objectA.worldToLocal(anchor);const localAnchorB=objectB.worldToLocal(anchor);const jointDef=new box2d.instance.b2RevoluteJointDef;jointDef.set_bodyA(objectA.body);jointDef.set_bodyB(objectB.body);jointDef.set_localAnchorA(box2d.vec2dTo(localAnchorA));jointDef.set_localAnchorB(box2d.vec2dTo(localAnchorB));jointDef.set_referenceAngle(objectB.body.GetAngle()-objectA.body.GetAngle());jointDef.set_collideConnected(collide);super(jointDef)}getLocalAnchorA(){return box2d.vec2From(this.box2dJoint.GetLocalAnchorA())}getLocalAnchorB(){return box2d.vec2From(this.box2dJoint.GetLocalAnchorB())}getReferenceAngle(){return this.box2dJoint.GetReferenceAngle()}getJointAngle(){return this.box2dJoint.GetJointAngle()}getJointSpeed(){return this.box2dJoint.GetJointSpeed()}isLimitEnabled(){return this.box2dJoint.IsLimitEnabled()}enableLimit(enable=true){return this.box2dJoint.EnableLimit(enable)}getLowerLimit(){return this.box2dJoint.GetLowerLimit()}getUpperLimit(){return this.box2dJoint.GetUpperLimit()}setLimits(min,max){return this.box2dJoint.SetLimits(min,max)}isMotorEnabled(){return this.box2dJoint.IsMotorEnabled()}enableMotor(enable=true){return this.box2dJoint.EnableMotor(enable)}setMotorSpeed(speed){return this.box2dJoint.SetMotorSpeed(speed)}getMotorSpeed(){return this.box2dJoint.GetMotorSpeed()}setMaxMotorTorque(torque){return this.box2dJoint.SetMaxMotorTorque(torque)}getMaxMotorTorque(){return this.box2dJoint.GetMaxMotorTorque()}getMotorTorque(time){return this.box2dJoint.GetMotorTorque(1/time)}}class Box2dGearJoint extends Box2dJoint{constructor(objectA,objectB,joint1,joint2,ratio=1){const jointDef=new box2d.instance.b2GearJointDef;jointDef.set_bodyA(objectA.body);jointDef.set_bodyB(objectB.body);jointDef.set_joint1(joint1.box2dJoint);jointDef.set_joint2(joint2.box2dJoint);jointDef.set_ratio(ratio);super(jointDef);this.joint1=joint1;this.joint2=joint2}getJoint1(){return this.joint1}getJoint2(){return this.joint2}setRatio(ratio){return this.box2dJoint.SetRatio(ratio)}getRatio(){return this.box2dJoint.GetRatio()}}class Box2dPrismaticJoint extends Box2dJoint{constructor(objectA,objectB,anchor,worldAxis=vec2(0,1),collide=false){anchor||=box2d.vec2From(objectB.body.GetPosition());const localAnchorA=objectA.worldToLocal(anchor);const localAnchorB=objectB.worldToLocal(anchor);const localAxisA=objectA.worldToLocalVector(worldAxis);const jointDef=new box2d.instance.b2PrismaticJointDef;jointDef.set_bodyA(objectA.body);jointDef.set_bodyB(objectB.body);jointDef.set_localAnchorA(box2d.vec2dTo(localAnchorA));jointDef.set_localAnchorB(box2d.vec2dTo(localAnchorB));jointDef.set_localAxisA(box2d.vec2dTo(localAxisA));jointDef.set_referenceAngle(objectB.body.GetAngle()-objectA.body.GetAngle());jointDef.set_collideConnected(collide);super(jointDef)}getLocalAnchorA(){return box2d.vec2From(this.box2dJoint.GetLocalAnchorA())}getLocalAnchorB(){return box2d.vec2From(this.box2dJoint.GetLocalAnchorB())}getLocalAxisA(){return box2d.vec2From(this.box2dJoint.GetLocalAxisA())}getReferenceAngle(){return this.box2dJoint.GetReferenceAngle()}getJointTranslation(){return this.box2dJoint.GetJointTranslation()}getJointSpeed(){return this.box2dJoint.GetJointSpeed()}isLimitEnabled(){return this.box2dJoint.IsLimitEnabled()}enableLimit(enable=true){return this.box2dJoint.EnableLimit(enable)}getLowerLimit(){return this.box2dJoint.GetLowerLimit()}getUpperLimit(){return this.box2dJoint.GetUpperLimit()}setLimits(min,max){return this.box2dJoint.SetLimits(min,max)}isMotorEnabled(){return this.box2dJoint.IsMotorEnabled()}enableMotor(enable=true){return this.box2dJoint.EnableMotor(enable)}setMotorSpeed(speed){return this.box2dJoint.SetMotorSpeed(speed)}getMotorSpeed(){return this.box2dJoint.GetMotorSpeed()}setMaxMotorForce(force){return this.box2dJoint.SetMaxMotorForce(force)}getMaxMotorForce(){return this.box2dJoint.GetMaxMotorForce()}getMotorForce(time){return this.box2dJoint.GetMotorForce(1/time)}}class Box2dWheelJoint extends Box2dJoint{constructor(objectA,objectB,anchor,worldAxis=vec2(0,1),collide=false){anchor||=box2d.vec2From(objectB.body.GetPosition());const localAnchorA=objectA.worldToLocal(anchor);const localAnchorB=objectB.worldToLocal(anchor);const localAxisA=objectA.worldToLocalVector(worldAxis);const jointDef=new box2d.instance.b2WheelJointDef;jointDef.set_bodyA(objectA.body);jointDef.set_bodyB(objectB.body);jointDef.set_localAnchorA(box2d.vec2dTo(localAnchorA));jointDef.set_localAnchorB(box2d.vec2dTo(localAnchorB));jointDef.set_localAxisA(box2d.vec2dTo(localAxisA));jointDef.set_collideConnected(collide);super(jointDef)}getLocalAnchorA(){return box2d.vec2From(this.box2dJoint.GetLocalAnchorA())}getLocalAnchorB(){return box2d.vec2From(this.box2dJoint.GetLocalAnchorB())}getLocalAxisA(){return box2d.vec2From(this.box2dJoint.GetLocalAxisA())}getJointTranslation(){return this.box2dJoint.GetJointTranslation()}getJointSpeed(){return this.box2dJoint.GetJointSpeed()}isMotorEnabled(){return this.box2dJoint.IsMotorEnabled()}enableMotor(enable=true){return this.box2dJoint.EnableMotor(enable)}setMotorSpeed(speed){return this.box2dJoint.SetMotorSpeed(speed)}getMotorSpeed(){return this.box2dJoint.GetMotorSpeed()}setMaxMotorTorque(torque){return this.box2dJoint.SetMaxMotorTorque(torque)}getMaxMotorTorque(){return this.box2dJoint.GetMaxMotorTorque()}getMotorTorque(time){return this.box2dJoint.GetMotorTorque(1/time)}setSpringFrequencyHz(hz){return this.box2dJoint.SetSpringFrequencyHz(hz)}getSpringFrequencyHz(){return this.box2dJoint.GetSpringFrequencyHz()}setSpringDampingRatio(ratio){return this.box2dJoint.SetSpringDampingRatio(ratio)}getSpringDampingRatio(){return this.box2dJoint.GetSpringDampingRatio()}}class Box2dWeldJoint extends Box2dJoint{constructor(objectA,objectB,anchor,collide=false){anchor||=box2d.vec2From(objectB.body.GetPosition());const localAnchorA=objectA.worldToLocal(anchor);const localAnchorB=objectB.worldToLocal(anchor);const jointDef=new box2d.instance.b2WeldJointDef;jointDef.set_bodyA(objectA.body);jointDef.set_bodyB(objectB.body);jointDef.set_localAnchorA(box2d.vec2dTo(localAnchorA));jointDef.set_localAnchorB(box2d.vec2dTo(localAnchorB));jointDef.set_referenceAngle(objectB.body.GetAngle()-objectA.body.GetAngle());jointDef.set_collideConnected(collide);super(jointDef)}getLocalAnchorA(){return box2d.vec2From(this.box2dJoint.GetLocalAnchorA())}getLocalAnchorB(){return box2d.vec2From(this.box2dJoint.GetLocalAnchorB())}getReferenceAngle(){return this.box2dJoint.GetReferenceAngle()}setFrequency(hz){return this.box2dJoint.SetFrequency(hz)}getFrequency(){return this.box2dJoint.GetFrequency()}setSpringDampingRatio(ratio){return this.box2dJoint.SetSpringDampingRatio(ratio)}getSpringDampingRatio(){return this.box2dJoint.GetSpringDampingRatio()}}class Box2dFrictionJoint extends Box2dJoint{constructor(objectA,objectB,anchor,collide=false){anchor||=box2d.vec2From(objectB.body.GetPosition());const localAnchorA=objectA.worldToLocal(anchor);const localAnchorB=objectB.worldToLocal(anchor);const jointDef=new box2d.instance.b2FrictionJointDef;jointDef.set_bodyA(objectA.body);jointDef.set_bodyB(objectB.body);jointDef.set_localAnchorA(box2d.vec2dTo(localAnchorA));jointDef.set_localAnchorB(box2d.vec2dTo(localAnchorB));jointDef.set_collideConnected(collide);super(jointDef)}getLocalAnchorA(){return box2d.vec2From(this.box2dJoint.GetLocalAnchorA())}getLocalAnchorB(){return box2d.vec2From(this.box2dJoint.GetLocalAnchorB())}setMaxForce(force){this.box2dJoint.SetMaxForce(force)}getMaxForce(){return this.box2dJoint.GetMaxForce()}setMaxTorque(torque){this.box2dJoint.SetMaxTorque(torque)}getMaxTorque(){return this.box2dJoint.GetMaxTorque()}}class Box2dPulleyJoint extends Box2dJoint{constructor(objectA,objectB,groundAnchorA,groundAnchorB,anchorA,anchorB,ratio=1,collide=false){anchorA||=box2d.vec2From(objectA.body.GetPosition());anchorB||=box2d.vec2From(objectB.body.GetPosition());const localAnchorA=objectA.worldToLocal(anchorA);const localAnchorB=objectB.worldToLocal(anchorB);const jointDef=new box2d.instance.b2PulleyJointDef;jointDef.set_bodyA(objectA.body);jointDef.set_bodyB(objectB.body);jointDef.set_groundAnchorA(box2d.vec2dTo(groundAnchorA));jointDef.set_groundAnchorB(box2d.vec2dTo(groundAnchorB));jointDef.set_localAnchorA(box2d.vec2dTo(localAnchorA));jointDef.set_localAnchorB(box2d.vec2dTo(localAnchorB));jointDef.set_ratio(ratio);jointDef.set_lengthA(groundAnchorA.distance(anchorA));jointDef.set_lengthB(groundAnchorB.distance(anchorB));jointDef.set_collideConnected(collide);super(jointDef)}getGroundAnchorA(){return box2d.vec2From(this.box2dJoint.GetGroundAnchorA())}getGroundAnchorB(){return box2d.vec2From(this.box2dJoint.GetGroundAnchorB())}getLengthA(){return this.box2dJoint.GetLengthA()}getLengthB(){return this.box2dJoint.GetLengthB()}getRatio(){return this.box2dJoint.GetRatio()}getCurrentLengthA(){return this.box2dJoint.GetCurrentLengthA()}getCurrentLengthB(){return this.box2dJoint.GetCurrentLengthB()}}class Box2dMotorJoint extends Box2dJoint{constructor(objectA,objectB){const linearOffset=objectA.worldToLocal(box2d.vec2From(objectB.body.GetPosition()));const angularOffset=objectB.body.GetAngle()-objectA.body.GetAngle();const jointDef=new box2d.instance.b2MotorJointDef;jointDef.set_bodyA(objectA.body);jointDef.set_bodyB(objectB.body);jointDef.set_linearOffset(box2d.vec2dTo(linearOffset));jointDef.set_angularOffset(angularOffset);super(jointDef)}setLinearOffset(offset){this.box2dJoint.SetLinearOffset(box2d.vec2dTo(offset))}getLinearOffset(){return box2d.vec2From(this.box2dJoint.GetLinearOffset())}setAngularOffset(offset){this.box2dJoint.SetAngularOffset(offset)}getAngularOffset(){return this.box2dJoint.GetAngularOffset()}setMaxForce(force){this.box2dJoint.SetMaxForce(force)}getMaxForce(){return this.box2dJoint.GetMaxForce()}setMaxTorque(torque){this.box2dJoint.SetMaxTorque(torque)}getMaxTorque(){return this.box2dJoint.GetMaxTorque()}setCorrectionFactor(factor){this.box2dJoint.SetCorrectionFactor(factor)}getCorrectionFactor(){return this.box2dJoint.GetCorrectionFactor()}}class Box2dPlugin{constructor(instance){ASSERT(!box2d,"Box2D already initialized");box2d=this;this.instance=instance;this.world=new box2d.instance.b2World;this.objects=[];this.velocityIterations=8;this.positionIterations=3;this.bodyTypeStatic=instance.b2_staticBody;this.bodyTypeKinematic=instance.b2_kinematicBody;this.bodyTypeDynamic=instance.b2_dynamicBody;const listener=new box2d.instance.JSContactListener;listener.BeginContact=function(contactPtr){const contact=box2d.instance.wrapPointer(contactPtr,box2d.instance.b2Contact);const fixtureA=contact.GetFixtureA();const fixtureB=contact.GetFixtureB();const objectA=fixtureA.GetBody().object;const objectB=fixtureB.GetBody().object;if(!objectA||!objectB)return;objectA.beginContact(objectB);objectB.beginContact(objectA)};listener.EndContact=function(contactPtr){const contact=box2d.instance.wrapPointer(contactPtr,box2d.instance.b2Contact);const fixtureA=contact.GetFixtureA();const fixtureB=contact.GetFixtureB();const objectA=fixtureA.GetBody().object;const objectB=fixtureB.GetBody().object;if(!objectA||!objectB)return;objectA.endContact(objectB);objectB.endContact(objectA)};listener.PreSolve=function(){};listener.PostSolve=function(){};box2d.world.SetContactListener(listener)}step(frames=1){box2d.world.SetGravity(box2d.vec2dTo(gravity));for(let i=frames;i--;)box2d.world.Step(timeDelta,this.velocityIterations,this.positionIterations)}raycastAll(start,end){const raycastCallback=new box2d.instance.JSRayCastCallback;raycastCallback.ReportFixture=function(fixturePointer,point,normal,fraction){const fixture=box2d.instance.wrapPointer(fixturePointer,box2d.instance.b2Fixture);point=box2d.vec2FromPointer(point);normal=box2d.vec2FromPointer(normal);raycastResults.push(new Box2dRaycastResult(fixture,point,normal,fraction));return 1};const raycastResults=[];box2d.world.RayCast(raycastCallback,box2d.vec2dTo(start),box2d.vec2dTo(end));debugRaycast&&debugLine(start,end,raycastResults.length?"#f00":"#00f",.02);return raycastResults}raycast(start,end){const raycastResults=box2d.raycastAll(start,end);if(!raycastResults.length)return undefined;return raycastResults.reduce((a,b)=>a.fraction<b.fraction?a:b)}boxCastAll(pos,size){const queryCallback=new box2d.instance.JSQueryCallback;queryCallback.ReportFixture=function(fixturePointer){const fixture=box2d.instance.wrapPointer(fixturePointer,box2d.instance.b2Fixture);const o=fixture.GetBody().object;if(!queryObjects.includes(o))queryObjects.push(o);return true};const aabb=new box2d.instance.b2AABB;aabb.set_lowerBound(box2d.vec2dTo(pos.subtract(size.scale(.5))));aabb.set_upperBound(box2d.vec2dTo(pos.add(size.scale(.5))));let queryObjects=[];box2d.world.QueryAABB(queryCallback,aabb);debugRaycast&&debugRect(pos,size,queryObjects.length?"#f00":"#00f",.02);return queryObjects}boxCast(pos,size){const queryCallback=new box2d.instance.JSQueryCallback;queryCallback.ReportFixture=function(fixturePointer){const fixture=box2d.instance.wrapPointer(fixturePointer,box2d.instance.b2Fixture);queryObject=fixture.GetBody().object;return false};const aabb=new box2d.instance.b2AABB;aabb.set_lowerBound(box2d.vec2dTo(pos.subtract(size.scale(.5))));aabb.set_upperBound(box2d.vec2dTo(pos.add(size.scale(.5))));let queryObject;box2d.world.QueryAABB(queryCallback,aabb);debugRaycast&&debugRect(pos,size,queryObject?"#f00":"#00f",.02);return queryObject}circleCastAll(pos,diameter){const radius2=(diameter/2)**2;const results=box2d.boxCastAll(pos,vec2(diameter));return results.filter(o=>o.pos.distanceSquared(pos)<radius2)}circleCast(pos,diameter){const radius2=(diameter/2)**2;let results=box2d.boxCastAll(pos,vec2(diameter));let bestResult,bestDistance2;for(const result of results){const distance2=result.pos.distanceSquared(pos);if(distance2<radius2&&(!bestResult||distance2<bestDistance2)){bestResult=result;bestDistance2=distance2}}return bestResult}pointCast(pos,dynamicOnly=true){const queryCallback=new box2d.instance.JSQueryCallback;queryCallback.ReportFixture=function(fixturePointer){const fixture=box2d.instance.wrapPointer(fixturePointer,box2d.instance.b2Fixture);if(dynamicOnly&&fixture.GetBody().GetType()!==box2d.instance.b2_dynamicBody)return true;if(!fixture.TestPoint(box2d.vec2dTo(pos)))return true;queryObject=fixture.GetBody().object;return false};const aabb=new box2d.instance.b2AABB;aabb.set_lowerBound(box2d.vec2dTo(pos));aabb.set_upperBound(box2d.vec2dTo(pos));let queryObject;box2d.world.QueryAABB(queryCallback,aabb);debugRaycast&&debugRect(pos,vec2(),queryObject?"#f00":"#00f",.02);return queryObject}drawFixture(fixture,pos,angle,color=WHITE,lineColor=BLACK,lineWidth=.1,useWebGL,context){const shape=box2d.castShapeObject(fixture.GetShape());switch(shape.GetType()){case box2d.instance.b2Shape.e_polygon:{let points=[];for(let i=shape.GetVertexCount();i--;)points.push(box2d.vec2From(shape.GetVertex(i)));drawPoly(points,color,lineWidth,lineColor,pos,angle,useWebGL,false,context);break}case box2d.instance.b2Shape.e_circle:{const radius=shape.get_m_radius();drawCircle(pos,radius*2,color,lineWidth,lineColor,useWebGL,false,context);break}case box2d.instance.b2Shape.e_edge:{const v1=box2d.vec2From(shape.get_m_vertex1());const v2=box2d.vec2From(shape.get_m_vertex2());drawLine(v1,v2,lineWidth,lineColor,pos,angle,useWebGL,false,context);break}}}vec2From(v){ASSERT(v instanceof box2d.instance.b2Vec2);return new Vector2(v.get_x(),v.get_y())}vec2FromPointer(vp){const v=box2d.instance.wrapPointer(vp,box2d.instance.b2Vec2);return box2d.vec2From(v)}vec2dTo(v){ASSERT(isVector2(v));return new box2d.instance.b2Vec2(v.x,v.y)}isNull(o){return!box2d.instance.getPointer(o)}castShapeObject(o){switch(o.GetType()){case box2d.instance.b2Shape.e_circle:return box2d.instance.castObject(o,box2d.instance.b2CircleShape);case box2d.instance.b2Shape.e_edge:return box2d.instance.castObject(o,box2d.instance.b2EdgeShape);case box2d.instance.b2Shape.e_polygon:return box2d.instance.castObject(o,box2d.instance.b2PolygonShape);case box2d.instance.b2Shape.e_chain:return box2d.instance.castObject(o,box2d.instance.b2ChainShape)}ASSERT(false,"Unknown box2d object type")}castJointObject(o){switch(o.GetType()){case box2d.instance.e_revoluteJoint:return box2d.instance.castObject(o,box2d.instance.b2RevoluteJoint);case box2d.instance.e_prismaticJoint:return box2d.instance.castObject(o,box2d.instance.b2PrismaticJoint);case box2d.instance.e_distanceJoint:return box2d.instance.castObject(o,box2d.instance.b2DistanceJoint);case box2d.instance.e_pulleyJoint:return box2d.instance.castObject(o,box2d.instance.b2PulleyJoint);case box2d.instance.e_mouseJoint:return box2d.instance.castObject(o,box2d.instance.b2MouseJoint);case box2d.instance.e_gearJoint:return box2d.instance.castObject(o,box2d.instance.b2GearJoint);case box2d.instance.e_wheelJoint:return box2d.instance.castObject(o,box2d.instance.b2WheelJoint);case box2d.instance.e_weldJoint:return box2d.instance.castObject(o,box2d.instance.b2WeldJoint);case box2d.instance.e_frictionJoint:return box2d.instance.castObject(o,box2d.instance.b2FrictionJoint);case box2d.instance.e_ropeJoint:return box2d.instance.castObject(o,box2d.instance.b2RopeJoint);case box2d.instance.e_motorJoint:return box2d.instance.castObject(o,box2d.instance.b2MotorJoint)}ASSERT(false,"Unknown box2d object type")}}async function box2dInit(){new Box2dPlugin(await Box2D());setupDebugDraw();engineAddPlugin(box2dUpdate,box2dRender);return box2d;function box2dUpdate(){if(paused)return;box2d.step();box2d.objects=box2d.objects.filter(o=>!o.destroyed);for(const o of box2d.objects){if(o.body){o.pos=box2d.vec2From(o.body.GetPosition());o.angle=-o.body.GetAngle()}}}function box2dRender(){if(box2dDebug||debugPhysics)box2d.world.DrawDebugData()}function setupDebugDraw(){const debugLineWidth=.1;const debugDraw=new box2d.instance.JSDraw;const box2dColor=c=>new Color(c.get_r(),c.get_g(),c.get_b());const box2dColorPointer=c=>box2dColor(box2d.instance.wrapPointer(c,box2d.instance.b2Color));const getDebugColor=color=>box2dColorPointer(color).scale(1,.8);const getPointsList=(vertices,vertexCount)=>{const points=[];for(let i=vertexCount;i--;)points.push(box2d.vec2FromPointer(vertices+i*8));return points};debugDraw.DrawSegment=function(point1,point2,color){color=getDebugColor(color);point1=box2d.vec2FromPointer(point1);point2=box2d.vec2FromPointer(point2);drawLine(point1,point2,debugLineWidth,color,vec2(),0,false)};debugDraw.DrawPolygon=function(vertices,vertexCount,color){color=getDebugColor(color);const points=getPointsList(vertices,vertexCount);drawPoly(points,CLEAR_WHITE,debugLineWidth,color,vec2(),0,false)};debugDraw.DrawSolidPolygon=function(vertices,vertexCount,color){color=getDebugColor(color);const points=getPointsList(vertices,vertexCount);drawPoly(points,color,0,color,vec2(),0,false)};debugDraw.DrawCircle=function(center,radius,color){color=getDebugColor(color);center=box2d.vec2FromPointer(center);drawCircle(center,radius*2,CLEAR_WHITE,debugLineWidth,color,false)};debugDraw.DrawSolidCircle=function(center,radius,axis,color){color=getDebugColor(color);center=box2d.vec2FromPointer(center);axis=box2d.vec2FromPointer(axis).scale(radius);drawCircle(center,radius*2,color,debugLineWidth,color,false);drawLine(vec2(),axis,debugLineWidth,color,center,0,false)};debugDraw.DrawTransform=function(transform){transform=box2d.instance.wrapPointer(transform,box2d.instance.b2Transform);const pos=box2d.vec2From(transform.get_p());const angle=-transform.get_q().GetAngle();const p1=vec2(1,0),c1=rgb(.75,0,0,.8);const p2=vec2(0,1),c2=rgb(0,.75,0,.8);drawLine(vec2(),p1,debugLineWidth,c1,pos,angle,false);drawLine(vec2(),p2,debugLineWidth,c2,pos,angle,false)};debugDraw.AppendFlags(box2d.instance.b2Draw.e_shapeBit);debugDraw.AppendFlags(box2d.instance.b2Draw.e_jointBit);box2d.world.SetDebugDraw(debugDraw)}}function drawNineSliceScreen(pos,size,startTile,borderSize=32,extraSpace=2,angle=0){drawNineSlice(pos,size,startTile,WHITE,borderSize,BLACK,extraSpace,angle,false,true)}function drawNineSlice(pos,size,startTile,color,borderSize=1,additiveColor,extraSpace=.05,angle=0,useWebGL=glEnable,screenSpace,context){const centerTile=startTile.offset(startTile.size);const centerSize=size.add(vec2(extraSpace-borderSize*2));const cornerSize=vec2(borderSize);const cornerOffset=size.scale(.5).subtract(cornerSize.scale(.5));const flip=screenSpace?-1:1;const rotateAngle=screenSpace?-angle:angle;drawTile(pos,centerSize,centerTile,color,angle,false,additiveColor,useWebGL,screenSpace,context);for(let i=4;i--;){const horizontal=i%2;const sidePos=cornerOffset.multiply(vec2(horizontal?i===1?1:-1:0,horizontal?0:i?-1:1));const sideSize=vec2(horizontal?borderSize:centerSize.x,horizontal?centerSize.y:borderSize);const sideTile=centerTile.offset(startTile.size.multiply(vec2(i===1?1:i===3?-1:0,i===0?-flip:i===2?flip:0)));drawTile(pos.add(sidePos.rotate(rotateAngle)),sideSize,sideTile,color,angle,false,additiveColor,useWebGL,screenSpace,context)}for(let i=4;i--;){const flipX=i>1;const flipY=i&&i<3;const cornerPos=cornerOffset.multiply(vec2(flipX?-1:1,flipY?-1:1));const cornerTile=centerTile.offset(startTile.size.multiply(vec2(flipX?-1:1,flipY?flip:-flip)));drawTile(pos.add(cornerPos.rotate(rotateAngle)),cornerSize,cornerTile,color,angle,false,additiveColor,useWebGL,screenSpace,context)}}function drawThreeSliceScreen(pos,size,startTile,borderSize=32,extraSpace=2,angle=0){drawThreeSlice(pos,size,startTile,WHITE,borderSize,BLACK,extraSpace,angle,false,true)}function drawThreeSlice(pos,size,startTile,color,borderSize=1,additiveColor,extraSpace=.05,angle=0,useWebGL=glEnable,screenSpace,context){const cornerTile=startTile.frame(0);const sideTile=startTile.frame(1);const centerTile=startTile.frame(2);const centerSize=size.add(vec2(extraSpace-borderSize*2));const cornerSize=vec2(borderSize);const cornerOffset=size.scale(.5).subtract(cornerSize.scale(.5));const flip=screenSpace?-1:1;const rotateAngle=screenSpace?-angle:angle;drawTile(pos,centerSize,centerTile,color,angle,false,additiveColor,useWebGL,screenSpace,context);for(let i=4;i--;){const a=angle+i*PI/2;const horizontal=i%2;const sidePos=cornerOffset.multiply(vec2(horizontal?i===1?1:-1:0,horizontal?0:i?-flip:flip));const sideSize=vec2(horizontal?centerSize.y:centerSize.x,borderSize);drawTile(pos.add(sidePos.rotate(rotateAngle)),sideSize,sideTile,color,a,false,additiveColor,useWebGL,screenSpace,context)}for(let i=4;i--;){const a=angle+i*PI/2;const flipX=!i||i>2;const flipY=i>1;const cornerPos=cornerOffset.multiply(vec2(flipX?-1:1,flipY?-flip:flip));drawTile(pos.add(cornerPos.rotate(rotateAngle)),cornerSize,cornerTile,color,a,false,additiveColor,useWebGL,screenSpace,context)}}function drawCrescent(pos,size=1,percent=0,color=WHITE,angle=0,invert=false,lineWidth=0,lineColor=BLACK,useWebGL=glEnable,screenSpace=false,context){const points=getCrescentPoints(vec2(),size,percent,0,invert);drawPoly(points,color,lineWidth,lineColor,pos,angle,useWebGL,screenSpace,context)}function getCrescentPoints(pos,size=1,percent=0,angle=0,invert=false,sides=glCircleSides){ASSERT(isVector2(pos),"pos must be a vec2");ASSERT(isNumber(size)&&isNumber(percent),"size and percent must be numbers");let p=mod(percent*4,4);if(p>=2)angle+=PI;p=p<=2?p-1:3-p;if(invert){p=-p;angle+=PI}const points=[];const segs=max(3,sides>>1);const radius=size/2;for(let i=0;i<=segs;i++){const t=i/segs*PI;points.push(vec2(radius*cos(t),radius*sin(t)).rotate(angle).add(pos))}for(let i=segs;i>=0;i--){const t=i/segs*PI;points.push(vec2(radius*cos(t),-radius*p*sin(t)).rotate(angle).add(pos))}return points}let textureSheetSize=2048;let textureSheetPadding=1;let textureSheets=[];let textureSheetQueue=Promise.resolve();let textureSheetPendingCount=0;class TextureSheet{constructor(size=textureSheetSize){ASSERT(size>0,"texture sheet size must be positive");this.size=size;this.canvas=headlessMode?undefined:new OffscreenCanvas(size,size);this.context=this.canvas?.getContext("2d");this.textureInfo=new TextureInfo(this.canvas);this.cursor=vec2();this.rowHeight=0;this.glDirty=false;if(headlessMode){this.textureInfo.size=vec2(size);this.textureInfo.sizeInverse=vec2(1/size)}}tryAdd(imageSize,frameSize=imageSize,padding=textureSheetPadding,sourcePadding=0){ASSERT(isVector2(imageSize)&&isVector2(frameSize),"sizes must be vec2");ASSERT(frameSize.x>0&&frameSize.y>0,"frame size must be positive");if(isNumber(sourcePadding))sourcePadding=vec2(sourcePadding);ASSERT(isVector2(sourcePadding)&&sourcePadding.x>=0&&sourcePadding.y>=0,"sourcePadding must be a number or vec2 >= 0");const sourceCellWidth=frameSize.x+sourcePadding.x*2;const sourceCellHeight=frameSize.y+sourcePadding.y*2;ASSERT(imageSize.x%sourceCellWidth===0&&imageSize.y%sourceCellHeight===0,"image size must be a multiple of the padded frame size");const cellWidth=frameSize.x+padding*2;const cellHeight=frameSize.y+padding*2;const maxColumns=this.size/cellWidth|0;ASSERT(maxColumns>0,"frame is too wide to fit on a texture sheet");const sourceColumns=imageSize.x/sourceCellWidth;const frameCount=sourceColumns*(imageSize.y/sourceCellHeight);const columns=min(sourceColumns,maxColumns);const blockWidth=columns*cellWidth;const blockHeight=ceil(frameCount/columns)*cellHeight;let x=this.cursor.x,y=this.cursor.y,rowHeight=this.rowHeight;if(x+blockWidth>this.size){x=0;y+=rowHeight;rowHeight=0}if(y+blockHeight>this.size)return undefined;this.cursor.x=x+blockWidth;this.cursor.y=y;this.rowHeight=max(rowHeight,blockHeight);return new TileInfo(vec2(x+padding,y+padding),frameSize,this.textureInfo,padding,0,columns)}drawImage(image,tileInfo,update=true,sourcePadding=0){ASSERT(!!this.context,"texture sheet has no canvas");if(isNumber(sourcePadding))sourcePadding=vec2(sourcePadding);const frameSize=tileInfo.size;const sourceCellWidth=frameSize.x+sourcePadding.x*2;const sourceCellHeight=frameSize.y+sourcePadding.y*2;const sourceColumns=image.width/sourceCellWidth;const frameCount=sourceColumns*(image.height/sourceCellHeight);const columns=tileInfo.columns||frameCount;const cellWidth=frameSize.x+tileInfo.padding*2;const cellHeight=frameSize.y+tileInfo.padding*2;for(let i=frameCount;i--;){const sourceX=i%sourceColumns*sourceCellWidth+sourcePadding.x;const sourceY=(i/sourceColumns|0)*sourceCellHeight+sourcePadding.y;this.context.drawImage(image,sourceX,sourceY,frameSize.x,frameSize.y,tileInfo.pos.x+i%columns*cellWidth,tileInfo.pos.y+(i/columns|0)*cellHeight,frameSize.x,frameSize.y)}this.glDirty=true;update&&this.updateTexture()}updateTexture(){if(!this.glDirty)return;this.glDirty=false;this.textureInfo.createWebGLTexture()}}function loadSprite(src,frameSize,padding=textureSheetPadding,sourcePadding=0){ASSERT(isStringLike(src),"image src must be a string");ASSERT(!frameSize||isVector2(frameSize)||isNumber(frameSize),"frameSize must be a vec2 or number");ASSERT(isNumber(padding),"padding must be a number");ASSERT(isNumber(sourcePadding)||isVector2(sourcePadding),"sourcePadding must be a number or vec2");if(isNumber(frameSize))frameSize=vec2(frameSize);const tileInfo=new TileInfo(vec2(),vec2(),undefined,padding,0);if(headlessMode)return tileInfo;tileInfo.textureInfo=(textureSheets[0]||textureSheetCreate()).textureInfo;const image=new Image;const imagePromise=new Promise(resolve=>{image.onerror=image.onload=resolve;image.crossOrigin="anonymous";image.src=src});++textureSheetPendingCount;textureSheetQueue=textureSheetQueue.then(async()=>{await imagePromise;if(image.width){const imageSize=vec2(image.width,image.height);const{sheet,tile}=textureSheetAdd(imageSize,frameSize,padding,sourcePadding);Object.assign(tileInfo,tile);sheet.drawImage(image,tileInfo,false,sourcePadding)}else{LOG("loadSprite failed to load image:",src)}if(!--textureSheetPendingCount)textureSheets.forEach(s=>s.updateTexture())});return tileInfo}function loadAtlas(imageSrc,jsonSrc,padding=textureSheetPadding){ASSERT(isStringLike(imageSrc),"atlas image src must be a string");ASSERT(isStringLike(jsonSrc)||typeof jsonSrc==="object","atlas json must be a path or object");ASSERT(isNumber(padding),"padding must be a number");const atlas={};if(headlessMode)return atlas;const jsonPromise=typeof jsonSrc==="object"?Promise.resolve(jsonSrc):fetch(jsonSrc).then(r=>r.ok&&r.json()).catch(()=>undefined);const image=new Image;const imagePromise=new Promise(resolve=>{image.onerror=image.onload=resolve;image.crossOrigin="anonymous";image.src=imageSrc});++textureSheetPendingCount;textureSheetQueue=textureSheetQueue.then(async()=>{const data=await jsonPromise;await imagePromise;if(image.width&&data){for(const group of parseAtlas(data)){const sourceSize=group.frames[0].sourceSize;const blockSize=vec2(sourceSize.x*group.frames.length,sourceSize.y);const{sheet,tile}=textureSheetAdd(blockSize,sourceSize,padding);const context=sheet.context;const cellWidth=sourceSize.x+padding*2;const cellHeight=sourceSize.y+padding*2;group.frames.forEach((f,i)=>{const x=tile.pos.x+i%tile.columns*cellWidth+f.offset.x;const y=tile.pos.y+(i/tile.columns|0)*cellHeight+f.offset.y;if(f.rotated){context.save();context.translate(x,y);context.rotate(-PI/2);context.drawImage(image,f.pos.x,f.pos.y,f.size.y,f.size.x,-f.size.y,0,f.size.y,f.size.x);context.restore()}else context.drawImage(image,f.pos.x,f.pos.y,f.size.x,f.size.y,x,y,f.size.x,f.size.y)});sheet.glDirty=true;atlas[group.name]=tile}}else{LOG("loadAtlas failed to load:",imageSrc,jsonSrc)}if(!--textureSheetPendingCount)textureSheets.forEach(s=>s.updateTexture())});return atlas}function parseAtlas(data){ASSERT(!!data?.frames,"unrecognized atlas format, expected TexturePacker or Aseprite json");const frames=(isArray(data.frames)?data.frames.map(f=>[f.filename,f]):Object.entries(data.frames)).map(([name,f])=>({name:name.replace(/\.[^.\\/]+$/,""),pos:vec2(f.frame.x,f.frame.y),size:vec2(f.frame.w,f.frame.h),offset:vec2(f.spriteSourceSize?.x??0,f.spriteSourceSize?.y??0),sourceSize:vec2(f.sourceSize?.w??f.frame.w,f.sourceSize?.h??f.frame.h),rotated:!!f.rotated}));const groups=[];const tags=data.meta?.frameTags;if(tags?.length){const tagged=new Set;for(const tag of tags){groups.push({name:tag.name,frames:frames.slice(tag.from,tag.to+1)});for(let i=tag.from;i<=tag.to;++i)tagged.add(i)}frames.forEach((f,i)=>tagged.has(i)||groups.push({name:f.name,frames:[f]}));return groups}const stems=new Map;for(const f of frames){let match=f.name.match(/^(.+?)([-_ ])?(\d+)$/);if(match&&!match[2]&&/\d$/.test(match[1]))match=undefined;const stem=match?match[1]:f.name;f.groupIndex=match?Number(match[3]):undefined;stems.has(stem)||stems.set(stem,[]);stems.get(stem).push(f)}for(const[stem,list]of stems){list.sort((a,b)=>a.groupIndex-b.groupIndex);const grouped=list.length>1&&list.every((f,i)=>f.groupIndex===list[0].groupIndex+i)&&list.every(f=>f.sourceSize.x===list[0].sourceSize.x&&f.sourceSize.y===list[0].sourceSize.y);if(grouped)groups.push({name:stem,frames:list});else list.forEach(f=>groups.push({name:f.name,frames:[f]}))}return groups}async function spritesReady(){while(textureSheetPendingCount)await textureSheetQueue}function textureSheetCreate(){const sheet=new TextureSheet;textureSheets.push(sheet);return sheet}function textureSheetAdd(imageSize,frameSize,padding,sourcePadding){let sheet,tile;for(sheet of textureSheets)if(tile=sheet.tryAdd(imageSize,frameSize,padding,sourcePadding))break;if(!tile){sheet=textureSheetCreate();tile=sheet.tryAdd(imageSize,frameSize,padding,sourcePadding);ASSERT(!!tile,"image is too large to fit on a texture sheet")}return{sheet:sheet,tile:tile}}function setTextureSheetSize(size){textureSheetSize=size}function setTextureSheetPadding(padding){textureSheetPadding=padding}const tweenActive=[];let lastTime=0;let lastTimeReal=0;function isLerpable(v){return v&&typeof v.lerp==="function"}class Tween{constructor(callback,start=0,end=1,duration=1,options={}){ASSERT(typeof callback==="function","Tween callback must be a function");if(isLerpable(start)){ASSERT(start.constructor===end.constructor,"Tween start and end must be the same type")}else{ASSERT(isNumber(start),"Tween start must be a number or have a .lerp method");ASSERT(isNumber(end),"Tween end must be a number when start is a number")}ASSERT(isNumber(duration)&&duration>0,"Tween duration must be > 0");this.callback=callback;this.start=start;this.end=end;this.duration=duration;this.life=duration;this.ease=options.ease||Ease.LINEAR;this.useRealTime=!!options.useRealTime;this.paused=!!options.paused;this.thenCallback=undefined;this.loopRemaining=0;tweenActive.push(this);callback(this.interp(duration))}setEase(easeFn){this.ease=easeFn;return this}then(callback){this.thenCallback=callback;this.loopRemaining=0;return this}loop(count=Infinity){this.loopRemaining=count;this.thenCallback=()=>loopContinuation(this);return this}pingPong(count=Infinity){this.loopRemaining=count;this.thenCallback=()=>pingPongContinuation(this);return this}pause(){this.paused=true}resume(){this.paused=false}restart(){this.life=this.duration;this.paused=false;if(tweenActive.indexOf(this)<0)tweenActive.push(this);this.callback(this.interp(this.duration))}isActive(){return!this.paused&&tweenActive.indexOf(this)>=0}getPercent(){return percent(this.duration-this.life,0,this.duration)}getValue(){return this.interp(this.life)}interp(life){const x=this.ease((this.duration-life)/this.duration);if(isLerpable(this.start))return this.start.lerp(this.end,x);return this.start+(this.end-this.start)*x}stop(){const i=tweenActive.indexOf(this);if(i>=0)tweenActive.splice(i,1);this.thenCallback=undefined}}const Ease={LINEAR:x=>x,POWER:n=>x=>x**n,SINE:x=>1-cos(x*(PI/2)),CIRC:x=>1-(1-x*x)**.5,EXPO:x=>x===0?0:2**(10*x-10),BACK:x=>x*x*(2.70158*x-1.70158),ELASTIC:x=>x===0?0:x===1?1:-(2**(10*x-10))*sin((37-40*x)*PI/6),SPRING:x=>1-(sin(PI*(1-x)*(.2+2.5*(1-x)**3))*x**2.2+(1-x))*(1+1.2*x),BOUNCE:x=>{let t=1-x,f;if(t<4/11)f=7.5625*t*t;else if(t<8/11)f=7.5625*(t-=6/11)*t+.75;else if(t<10/11)f=7.5625*(t-=9/11)*t+.9375;else f=7.5625*(t-=10.5/11)*t+.984375;return 1-f},IN:f=>f,OUT:f=>x=>1-f(1-x),IN_OUT:f=>Ease.PIECEWISE(f,Ease.OUT(f)),PIECEWISE:(...fns)=>{const n=fns.length;return x=>{const i=x*n-1e-9>>0;return(fns[i]((x-i/n)*n)+i)/n}},BEZIER:(x1,y1,x2,y2)=>{const curve=t=>{const u=1-t;const c1=3*u*u*t;const c2=3*u*t*t;const t3=t**3;return[c1*x1+c2*x2+t3,c1*y1+c2*y2+t3]};return x=>{let t0=0,t1=1;for(let i=0;i<128;i++){const tMid=(t0+t1)/2;const[bx,by]=curve(tMid);if(abs(bx-x)<1e-5)return by;if(bx<x)t0=tMid;else t1=tMid}return curve((t0+t1)/2)[1]}}};function tweenProperty(target,propertyPath,start,end,duration=1,options={}){ASSERT(target!=null&&typeof target==="object","tweenProperty target must be an object");ASSERT(isStringLike(propertyPath)&&propertyPath.length>0,"tweenProperty propertyPath must be a non-empty string");const parts=propertyPath.split(".");const lastKey=parts.pop();const callback=value=>{let obj=target;for(const k of parts){obj=obj[k];ASSERT(obj!=null,"tweenProperty path does not resolve: "+propertyPath)}obj[lastKey]=value};return new Tween(callback,start,end,duration,options)}function loopContinuation(tween){if(tween.loopRemaining!==Infinity&&tween.loopRemaining<=1)return;if(tween.loopRemaining!==Infinity)tween.loopRemaining-=1;tween.life=tween.duration;tween.thenCallback=()=>loopContinuation(tween);tweenActive.push(tween);tween.callback(tween.interp(tween.duration))}function pingPongContinuation(tween){if(tween.loopRemaining!==Infinity&&tween.loopRemaining<=1)return;if(tween.loopRemaining!==Infinity)tween.loopRemaining-=1;const tmp=tween.start;tween.start=tween.end;tween.end=tmp;tween.life=tween.duration;tween.thenCallback=()=>pingPongContinuation(tween);tweenActive.push(tween);tween.callback(tween.interp(tween.duration))}function tweenUpdate(gameDelta,realDelta){if(gameDelta===undefined){gameDelta=time-lastTime;realDelta=timeReal-lastTimeReal;lastTime=time;lastTimeReal=timeReal}else if(realDelta===undefined){realDelta=gameDelta}for(let i=tweenActive.length;i--;){const t=tweenActive[i];if(t.paused)continue;const dt=t.useRealTime?realDelta:gameDelta;if(dt<=0)continue;t.life-=dt;if(t.life>0){t.callback(t.interp(t.life))}else{t.callback(t.interp(0));tweenActive.splice(i,1);const cb=t.thenCallback;t.thenCallback=undefined;if(cb)cb()}}}function tweenStopAll(){for(const t of tweenActive)t.thenCallback=undefined;tweenActive.length=0}engineAddPlugin(tweenUpdate);const PATHFINDER_DIAGONAL_COST=Math.SQRT2;const PATHFINDER_TILE_VEC=vec2(1);class PathFinderNode{constructor(x,y){this.pos=vec2(x,y);this.posWorld=vec2();this.walkable=false;this.cost=0;this.g=0;this.f=0;this.parent=null;this.isOpen=false;this.isClosed=false}reset(){this.walkable=false;this.cost=0;this.g=0;this.f=0;this.parent=null;this.isOpen=false;this.isClosed=false}isClear(){return this.walkable&&this.cost===0}}class PathFinder{constructor(source){if(isVector2(source)){this.size=source.floor();this.tileLayer=undefined}else{ASSERT(source&&isVector2(source.size)&&typeof source.getCollisionData==="function","PathFinder requires a Vector2 size or a TileCollisionLayer");this.size=source.size;this.tileLayer=source}this.heuristicWeight=1;this.maxLoop=1e3;this.smoothPath=true;this.debug=false;this.debugTime=1;this.nodes=new Array(this.size.x*this.size.y);for(let y=0;y<this.size.y;++y)for(let x=0;x<this.size.x;++x)this.nodes[x+y*this.size.x]=new PathFinderNode(x,y);this.collisionScratch=vec2()}isWalkable(x,y){if(!this.tileLayer)return true;return!this.tileLayer.getCollisionData(this.collisionScratch.set(x,y))}getCost(x,y){return 0}getNode(x,y){if(x<0||y<0||x>=this.size.x||y>=this.size.y)return null;return this.nodes[x+y*this.size.x]}worldToTile(worldPos){const ox=this.tileLayer?this.tileLayer.pos.x:0;const oy=this.tileLayer?this.tileLayer.pos.y:0;return vec2(floor(worldPos.x-ox),floor(worldPos.y-oy))}tileToWorld(x,y){const ox=this.tileLayer?this.tileLayer.pos.x:0;const oy=this.tileLayer?this.tileLayer.pos.y:0;return vec2(x+.5+ox,y+.5+oy)}buildNodeData(){const w=this.size.x;const h=this.size.y;const ox=this.tileLayer?this.tileLayer.pos.x:0;const oy=this.tileLayer?this.tileLayer.pos.y:0;for(let y=0;y<h;++y)for(let x=0;x<w;++x){const node=this.nodes[x+y*w];node.reset();const walkable=!!this.isWalkable(x,y);const cost=walkable?max(0,this.getCost(x,y)):0;node.walkable=walkable;node.cost=cost;node.posWorld.set(x+.5+ox,y+.5+oy);if(this.debug&&this.debugTime>0){if(!walkable)debugRect(node.posWorld,PATHFINDER_TILE_VEC,rgb(1,0,0,.25),this.debugTime);else if(cost>0)debugRect(node.posWorld,PATHFINDER_TILE_VEC,rgb(1,0,0,min(.2,cost*.05)),this.debugTime)}}}aStarSearch(startNode,endNode){ASSERT(startNode&&endNode,"aStarSearch needs both endpoints");ASSERT(startNode!==endNode,"aStarSearch: start and end must differ — caller should handle trivial case");ASSERT(startNode.walkable&&endNode.walkable,"aStarSearch: endpoints must be walkable");const openList=[startNode];startNode.isOpen=true;let loopCount=0;while(openList.length>0){let bestIndex=0;let bestF=openList[0].f;for(let i=1;i<openList.length;++i){if(openList[i].f<bestF){bestF=openList[i].f;bestIndex=i}}const current=openList[bestIndex];if(current===endNode)break;if(++loopCount>this.maxLoop)break;current.isOpen=false;openList.splice(bestIndex,1);current.isClosed=true;if(this.debug&&this.debugTime>0)debugRect(current.posWorld,PATHFINDER_TILE_VEC,rgb(1,1,1,.05),this.debugTime);for(let dy=-1;dy<=1;++dy)for(let dx=-1;dx<=1;++dx){if(dx===0&&dy===0)continue;const neighbor=this.getNode(current.pos.x+dx,current.pos.y+dy);if(!neighbor||!neighbor.walkable||neighbor.isClosed)continue;let stepCost=1;if(dx!==0&&dy!==0){const card1=this.getNode(current.pos.x+dx,current.pos.y);if(!card1||!card1.walkable)continue;const card2=this.getNode(current.pos.x,current.pos.y+dy);if(!card2||!card2.walkable)continue;stepCost=PATHFINDER_DIAGONAL_COST}const tentativeG=current.g+stepCost+neighbor.cost;if(!neighbor.isOpen){neighbor.isOpen=true;openList.push(neighbor)}else if(tentativeG>=neighbor.g){continue}neighbor.parent=current;neighbor.g=tentativeG;const adx=abs(endNode.pos.x-neighbor.pos.x);const ady=abs(endNode.pos.y-neighbor.pos.y);const h=max(adx,ady)+(Math.SQRT2-1)*min(adx,ady);neighbor.f=neighbor.g+h*this.heuristicWeight}}return endNode.parent!==null}getNearestClearNode(worldPos,searchRange=10,rebuild=true){ASSERT(isVector2(worldPos),"worldPos must be a Vector2");if(rebuild)this.buildNodeData();const ox=this.tileLayer?this.tileLayer.pos.x:0;const oy=this.tileLayer?this.tileLayer.pos.y:0;const centerX=floor(worldPos.x-ox);const centerY=floor(worldPos.y-oy);for(let offset=0;offset<=searchRange;++offset){let nearest=null;let nearestDistSq=0;for(let dy=-offset;dy<=offset;++dy)for(let dx=-offset;dx<=offset;++dx){if(offset>0&&abs(dx)!==offset&&abs(dy)!==offset)continue;const node=this.getNode(centerX+dx,centerY+dy);if(!node||!node.isClear())continue;const ddx=node.posWorld.x-worldPos.x;const ddy=node.posWorld.y-worldPos.y;const distSq=ddx*ddx+ddy*ddy;if(!nearest||distSq<nearestDistSq){nearest=node;nearestDistSq=distSq}}if(nearest)return nearest}return null}smoothPathCorners(path){if(path.length<=2)return;let i=1;while(i<path.length-1){const prev=path[i-1];const node=path[i];const next=path[i+1];const dx=next.pos.x-prev.pos.x;const dy=next.pos.y-prev.pos.y;const lenSq=dx*dx+dy*dy;const stepDx=node.pos.x-prev.pos.x;const stepDy=node.pos.y-prev.pos.y;const stepDxNext=next.pos.x-node.pos.x;const stepDyNext=next.pos.y-node.pos.y;if(lenSq===1){if(this.debug&&this.debugTime>0)debugCircle(node.posWorld,.3,rgb(.5,0,.5,.5),this.debugTime);path.splice(i,1);i=max(1,i-1);continue}else if(lenSq===2){if(this.debug&&this.debugTime>0)debugCircle(node.posWorld,.3,rgb(1,0,0,.5),this.debugTime);let sx,sy;if(prev.pos.y===node.pos.y&&next.pos.x===node.pos.x){sx=prev.pos.x;sy=next.pos.y}else{sx=next.pos.x;sy=prev.pos.y}const shortcut=this.getNode(sx,sy);if(shortcut&&shortcut.isClear()){path.splice(i,1);i=max(1,i-1);continue}}else if(lenSq===5){if(this.debug&&this.debugTime>0)debugCircle(node.posWorld,.3,rgb(1,1,0,.5),this.debugTime);const prevPrev=i>=2?path[i-2]:prev;let s1x,s1y,s2x,s2y;if(stepDx===0||stepDxNext===0){s1x=next.pos.x;s1y=node.pos.y;s2x=prev.pos.x;s2y=node.pos.y}else{s1x=node.pos.x;s1y=next.pos.y;s2x=node.pos.x;s2y=prev.pos.y}const dd1x=s1x-prevPrev.pos.x;const dd1y=s1y-prevPrev.pos.y;const dd2x=s2x-prevPrev.pos.x;const dd2y=s2y-prevPrev.pos.y;const dist1Sq=dd1x*dd1x+dd1y*dd1y;const dist2Sq=dd2x*dd2x+dd2y*dd2y;const sx=dist1Sq<dist2Sq?s1x:s1x===s2x&&s1y===s2y?s1x:s2x;const sy=dist1Sq<dist2Sq?s1y:s1x===s2x&&s1y===s2y?s1y:s2y;const shortcut=this.getNode(sx,sy);if(shortcut&&shortcut!==node&&shortcut.isClear()){const ccx=next.pos.x+s2x-s1x;const ccy=next.pos.y+s2y-s1y;const cutCorner=this.getNode(ccx,ccy);if(cutCorner&&cutCorner.isClear()){path[i]=shortcut;i=max(1,i-1);continue}}}else if(lenSq===4||lenSq===8){if(this.debug&&this.debugTime>0)debugCircle(node.posWorld,.3,rgb(0,1,0,.5),this.debugTime);if(stepDx===stepDxNext&&stepDy===stepDyNext){++i;continue}else{let sx,sy;if(prev.pos.y===next.pos.y){sx=node.pos.x;sy=prev.pos.y}else{sx=prev.pos.x;sy=node.pos.y}const shortcut=this.getNode(sx,sy);if(shortcut&&shortcut.isClear()){path[i]=shortcut;i=max(1,i-1);continue}}}++i}}smoothPathStringPull(path){if(path.length<=2)return;for(const n of path){if(!n.isClear())return}const original=path.slice();path.length=0;path.push(original[0]);let searchIndex=0;for(let i=1;i<original.length;++i){const node=original[i];{const a=original[searchIndex];const b=original[i-1];if(a!==b){const cross=(b.pos.x-a.pos.x)*(node.pos.y-a.pos.y)-(b.pos.y-a.pos.y)*(node.pos.x-a.pos.x);if(cross===0)continue}}if(!this.isLineClear(node.pos,path[path.length-1].pos)){let foundClearAfter=false;for(let j=i+1;j<original.length;++j){if(this.isLineClear(original[j].pos,path[path.length-1].pos)){foundClearAfter=true;break}}if(foundClearAfter){if(this.debug&&this.debugTime>0)debugLine(node.posWorld,path[path.length-1].posWorld,rgb(0,0,1,.3),.02,this.debugTime);continue}for(;searchIndex<original.length;++searchIndex){const cand=original[searchIndex];if(this.isLineClear(node.pos,cand.pos)){path.push(cand);i=searchIndex;break}}ASSERT(searchIndex<original.length,"smoothPathStringPull: ran out of candidates")}}path.push(original[original.length-1])}dropCollinearNodes(path){for(let i=path.length-2;i>=1;--i){const a=path[i-1],b=path[i],c=path[i+1];if((b.pos.x-a.pos.x)*(c.pos.y-a.pos.y)===(b.pos.y-a.pos.y)*(c.pos.x-a.pos.x))path.splice(i,1)}}isNodeClear(x,y){const n=this.getNode(x,y);return n!==null&&n.isClear()}isLineClear(startPos,endPos){ASSERT(isVector2(startPos)&&isVector2(endPos),"isLineClear needs Vector2 endpoints");ASSERT(this.isNodeClear(startPos.x,startPos.y)&&this.isNodeClear(endPos.x,endPos.y),"isLineClear endpoints must be in-bounds and clear");const dx=endPos.x-startPos.x;const dy=endPos.y-startPos.y;const adx=abs(dx);const ady=abs(dy);const sx=sign(dx);const sy=sign(dy);let x=startPos.x;let y=startPos.y;if(ady===adx){while(x!==endPos.x){if(x!==startPos.x){if(!this.isNodeClear(x,y))return false;if(!this.isNodeClear(x,y-sy))return false}if(!this.isNodeClear(x,y+sy))return false;x+=sx;y+=sy}if(!this.isNodeClear(endPos.x,endPos.y-sy))return false}else if(ady<adx){if(dy===0){x+=sx;while(x!==endPos.x){if(!this.isNodeClear(x,y))return false;x+=sx}}else{let lastY=startPos.y;while(x!==endPos.x){y=startPos.y+Math.trunc(dy*(x-startPos.x)/dx);if(lastY!==y){if(!this.isNodeClear(x-sx,y+sy))return false;if(!this.isNodeClear(x,y-sy))return false}lastY=y;if(x!==startPos.x){if(!this.isNodeClear(x,y))return false}y+=sy;if(!this.isNodeClear(x,y))return false;x+=sx}const finalY=endPos.y-sy;if(!this.isNodeClear(endPos.x,finalY))return false}}else{if(dx===0){y+=sy;while(y!==endPos.y){if(!this.isNodeClear(x,y))return false;y+=sy}}else{let lastX=startPos.x;while(y!==endPos.y){x=startPos.x+Math.trunc(dx*(y-startPos.y)/dy);if(lastX!==x){if(!this.isNodeClear(x+sx,y-sy))return false;if(!this.isNodeClear(x-sx,y))return false}lastX=x;if(y!==startPos.y){if(!this.isNodeClear(x,y))return false}x+=sx;if(!this.isNodeClear(x,y))return false;y+=sy}const finalX=endPos.x-sx;if(!this.isNodeClear(finalX,endPos.y))return false}}return true}findPath(startPos,endPos){ASSERT(isVector2(startPos)&&isVector2(endPos),"findPath needs Vector2 endpoints");this.buildNodeData();const startNode=this.getNearestClearNode(startPos,10,false);const endNode=this.getNearestClearNode(endPos,10,false);if(!startNode||!endNode)return[];if(startNode===endNode)return[startNode.posWorld.copy()];if(!this.aStarSearch(startNode,endNode))return[];const nodePath=[];for(let n=endNode;n;n=n.parent)nodePath.push(n);nodePath.reverse();if(this.smoothPath){this.smoothPathCorners(nodePath);this.smoothPathStringPull(nodePath);this.dropCollinearNodes(nodePath)}const result=nodePath.map(n=>n.posWorld.copy());if(this.debug&&this.debugTime>0&&result.length>0){for(let i=1;i<result.length;++i)debugLine(result[i-1],result[i],RED,.1,this.debugTime);for(const p of result)debugCircle(p,.5,rgb(1,0,0,.3),this.debugTime);debugCircle(result[0],.5,rgb(0,1,0,.5),this.debugTime);debugCircle(result[result.length-1],.5,rgb(0,1,0,.5),this.debugTime)}return result}}let threeJS;class ThreeJSPlugin{constructor(THREE,cameraFOV=60){ASSERT(!threeJS,"ThreeJS plugin already initialized");threeJS=this;if(headlessMode)return;ASSERT(mainCanvas,"ThreeJS plugin must be created after engineInit, call in gameInit");ASSERT(THREE&&THREE.WebGLRenderer,"three.js module must be passed in");this.THREE=THREE;this.renderer=new THREE.WebGLRenderer({antialias:true});this.scene=new THREE.Scene;this.camera=new THREE.PerspectiveCamera(cameraFOV,1,.1,1e3);this.cameraAlign2D=true;const threeCanvas=this.renderer.domElement;const rootElement=mainCanvas.parentElement;rootElement.insertBefore(threeCanvas,rootElement.firstChild);threeCanvas.style.cssText=mainCanvas.style.cssText;setBackgroundCanvas(threeCanvas);engineAddPlugin(undefined,()=>this.render())}alignCamera2D(){const halfHeight=mainCanvasSize.y/2/cameraScale;const distance=halfHeight/tan(this.camera.fov/2*PI/180);this.camera.position.set(cameraPos.x,cameraPos.y,distance);this.camera.rotation.set(0,0,-cameraAngle)}render(){if(!this.renderer)return;const threeCanvas=this.renderer.domElement;if(threeCanvas.width!=mainCanvasSize.x||threeCanvas.height!=mainCanvasSize.y){this.renderer.setSize(mainCanvasSize.x,mainCanvasSize.y,false);this.camera.aspect=mainCanvasSize.x/mainCanvasSize.y;this.camera.updateProjectionMatrix()}if(threeCanvas.style.cssText!=mainCanvas.style.cssText)threeCanvas.style.cssText=mainCanvas.style.cssText;if(this.cameraAlign2D)this.alignCamera2D();this.renderer.render(this.scene,this.camera)}}class ThreeJSObject extends EngineObject{constructor(pos,size,mesh,z=0){super(pos,size);ASSERT(threeJS,"ThreeJS plugin must be initialized first");this.mesh=mesh;this.z=z;if(mesh){threeJS.scene.add(mesh);this.syncMesh()}}update(){super.update();this.syncMesh()}syncMesh(){if(!this.mesh)return;this.mesh.position.set(this.pos.x,this.pos.y,this.z);this.mesh.rotation.z=-this.angle}render(){}destroy(immediate){if(this.destroyed)return;this.mesh&&threeJS.scene.remove(this.mesh);super.destroy(immediate)}}export{engineName,engineVersion,frameRate,timeDelta,engineObjects,engineObjectsCollide,frame,time,timeReal,paused,getPaused,setPaused,engineInit,engineStep,engineObjectsUpdate,engineObjectsDestroy,engineObjectsCollect,engineObjectsCallback,engineObjectsRaycast,engineAddPlugin,debug,debugOverlay,debugWatermark,ASSERT,LOG,debugPointSize,debugRect,debugPoly,debugCircle,debugPoint,debugLine,debugOverlap,debugText,debugClear,debugScreenshot,debugShowErrors,debugVideoCaptureStart,debugVideoCaptureStop,debugVideoCaptureIsActive,cameraPos,cameraAngle,cameraScale,timeScale,canvasColorTiles,canvasClearColor,canvasMaxSize,canvasMinAspect,canvasMaxAspect,canvasFixedSize,canvasPixelated,tilesPixelated,canvasPixelRatio,fontDefault,showSplashScreen,headlessMode,engineManualStep,tileDefaultSize,tileDefaultPadding,tileDefaultBleed,enablePhysicsSolver,objectDefaultMass,objectDefaultDamping,objectDefaultAngleDamping,objectDefaultRestitution,objectDefaultFriction,objectMaxSpeed,gravity,particleEmitRateScale,glEnable,glCircleSides,gamepadsEnable,gamepadDirectionEmulateStick,gamepadAxisFilterEnable,inputWASDEmulateDirection,touchInputEnable,touchGamepadEnable,touchGamepadPassthrough,touchGamepadCenterButtonSize,touchGamepadButtonCount,touchGamepadLeftStick,touchGamepadLeftButtonCount,touchGamepadRightStick,touchGamepadAnalog,touchGamepadFloating,touchGamepadSize,touchGamepadAlpha,touchGamepadDisplayTime,touchGamepadVibration,vibrateEnable,soundEnable,soundVolume,soundDefaultRange,soundDefaultTaper,setCameraPos,setCameraAngle,setCameraScale,setTimeScale,setCanvasColorTiles,setCanvasClearColor,setCanvasMaxSize,setCanvasMinAspect,setCanvasMaxAspect,setCanvasFixedSize,setCanvasPixelated,setTilesPixelated,setCanvasPixelRatio,setFontDefault,setShowSplashScreen,setHeadlessMode,setEngineManualStep,setGLEnable,setTileDefaultSize,setTileDefaultPadding,setTileDefaultBleed,setEnablePhysicsSolver,setObjectDefaultMass,setObjectDefaultDamping,setObjectDefaultAngleDamping,setObjectDefaultRestitution,setObjectDefaultFriction,setObjectMaxSpeed,setGravity,setParticleEmitRateScale,setGLCircleSides,setTouchInputEnable,setGamepadsEnable,setGamepadDirectionEmulateStick,setGamepadAxisFilterEnable,setInputWASDEmulateDirection,setTouchGamepadEnable,setTouchGamepadPassthrough,setTouchGamepadCenterButtonSize,setTouchGamepadButtonCount,setTouchGamepadLeftStick,setTouchGamepadLeftButtonCount,setTouchGamepadRightStick,setTouchGamepadAnalog,setTouchGamepadFloating,setTouchGamepadSize,setTouchGamepadAlpha,setTouchGamepadDisplayTime,setTouchGamepadVibration,setVibrateEnable,setSoundEnable,setSoundVolume,setSoundDefaultRange,setSoundDefaultTaper,setDebugWatermark,setDebugKey,PI,abs,floor,ceil,round,min,max,sign,hypot,log2,sin,cos,tan,atan2,mod,clamp,percent,distanceWrap,lerpWrap,distanceAngle,lerpAngle,lerp,percentLerp,smoothStep,nearestPowerOfTwo,isPowerOfTwo,isOverlapping,isIntersecting,lineTest,oscillate,formatTime,fetchJSON,saveText,saveCanvas,saveDataURL,shareURL,readSaveData,writeSaveData,noise1D,noise2D,rand,randInt,randBool,randSign,randInCircle,randVec2,randColor,RandomGenerator,Vector2,Color,Timer,vec2,rgb,hsl,isColor,isVector2,isNumber,isStringLike,isArray,WHITE,CLEAR_WHITE,BLACK,CLEAR_BLACK,GRAY,RED,ORANGE,YELLOW,GREEN,CYAN,BLUE,PURPLE,MAGENTA,tile,TileInfo,TextureInfo,mainCanvas,mainContext,drawContext,workCanvas,workContext,workReadCanvas,workReadContext,backgroundCanvas,mainCanvasSize,textureInfos,drawCount,primitiveCount,screenToWorld,worldToScreen,screenToWorldDelta,worldToScreenDelta,screenToWorldTransform,drawTile,drawRect,drawRectGradient,drawTextureWrapped,drawLineList,drawLine,drawPoly,drawRegularPoly,drawEllipse,drawCircle,drawEllipseGradient,drawCircleGradient,drawCanvas2D,drawText,drawTextScreen,setAdditiveBlendMode,setBackgroundCanvas,combineCanvases,engineImageFont,ImageFont,isFullscreen,toggleFullscreen,setCursor,getCameraSize,cameraFit,isOnScreen,glCanvas,glContext,glAntialias,glClearCanvas,glSetTexture,glSetTextureWrap,glCompileShader,glCreateProgram,glCreateTexture,glDeleteTexture,glSetTextureData,glFlush,glCopyToContext,glSetAntialias,glDraw,glDrawUntextured,glDrawPointsTransform,glDrawOutlineTransform,glDrawPoints,glDrawColoredPoints,glSetRenderTarget,glClearRect,keyIsDown,keyWasPressed,keyWasReleased,keyDirection,inputClear,inputClearKey,mouseIsDown,mouseWasPressed,mouseWasReleased,mousePos,mousePosScreen,mouseDelta,mouseDeltaScreen,mouseWheel,mouseInWindow,isUsingGamepad,lastInputDevice,inputMouseMoveThreshold,inputPreventDefault,gamepadPrimary,isTouchDevice,setInputPreventDefault,setInputMouseMoveThreshold,usingMouseInput,usingKeyboardInput,usingGamepadInput,gamepadIsDown,gamepadWasPressed,gamepadWasReleased,gamepadStick,gamepadStickCount,gamepadDpad,gamepadConnected,gamepadVibrate,gamepadVibrateStop,vibrate,vibrateStop,pointerLockRequest,pointerLockExit,pointerLockIsActive,audioContext,audioMasterGain,audioDefaultSampleRate,audioIsRunning,Sound,SoundInstance,speak,speakStop,getNoteFrequency,playSamples,playAudioBuffer,createAudioBuffer,zzfx,zzfxG,EngineObject,tileCollisionLayers,tileCollisionGetData,tileCollisionTest,tileCollisionRaycast,tileLayersLoad,TileLayerData,CanvasLayer,TileLayer,TileCollisionLayer,ParticleEmitter,Particle};export{medals,medalsPreventUnlock,medalDisplayTime,medalDisplaySlideTime,medalDisplaySize,medalsInit,medalsForEach,medalsReset,setMedalDisplayTime,setMedalDisplaySlideTime,setMedalDisplaySize,setMedalsPreventUnlock,Medal,newgrounds,NewgroundsPlugin,NewgroundsMedal,postProcess,PostProcessPlugin,lightSystem,LightSystemPlugin,Light,ZzFXMusic,zzfxM,uiSystem,uiDebug,uiSetDebug,UISystemPlugin,UIObject,UIText,UITextInput,UITile,UIButton,UICheckbox,UISlider,UIVideo,UILayout,box2d,box2dDebug,box2dSetDebug,box2dInit,Box2dPlugin,Box2dObject,Box2dStaticObject,Box2dKinematicObject,Box2dTileLayer,Box2dRaycastResult,Box2dJoint,Box2dTargetJoint,Box2dDistanceJoint,Box2dPinJoint,Box2dRopeJoint,Box2dRevoluteJoint,Box2dGearJoint,Box2dPrismaticJoint,Box2dWheelJoint,Box2dWeldJoint,Box2dFrictionJoint,Box2dPulleyJoint,Box2dMotorJoint,drawNineSlice,drawNineSliceScreen,drawThreeSlice,drawThreeSliceScreen,drawCrescent,getCrescentPoints,Tween,tweenProperty,tweenStopAll,tweenUpdate,Ease,PathFinder,PathFinderNode,threeJS,ThreeJSPlugin,ThreeJSObject,textureSheetSize,textureSheetPadding,setTextureSheetSize,setTextureSheetPadding,textureSheets,TextureSheet,loadSprite,loadAtlas,parseAtlas,spritesReady};
|
|
4
|
+
"use strict";const engineName="LittleJS";const engineVersion="1.19.3";const frameRate=60;const timeDelta=1/frameRate;let engineObjects=[];let engineObjectsCollide=[];let frame=0;let time=0;let timeReal=0;let paused=false;function getPaused(){return paused}function setPaused(isPaused=true){paused=isPaused}let frameTimeLastMS=0,frameTimeBufferMS=0,averageFPS=0;let windowWidthLast=0,windowHeightLast=0,windowPixelRatioLast=0;let engineUpdateInternal;let showEngineVersion=true;const pluginList=[];class EnginePlugin{constructor(update,render,glContextLost,glContextRestored,preRender){this.update=update;this.render=render;this.glContextLost=glContextLost;this.glContextRestored=glContextRestored;this.preRender=preRender}}function engineAddPlugin(update,render,glContextLost,glContextRestored,preRender){ASSERT(!pluginList.find(p=>p.update===update&&p.render===render&&p.glContextLost===glContextLost&&p.glContextRestored===glContextRestored&&p.preRender===preRender));const plugin=new EnginePlugin(update,render,glContextLost,glContextRestored,preRender);pluginList.push(plugin)}async function engineInit(gameInit,gameUpdate,gameUpdatePost,gameRender,gameRenderPost,imageSources=[],rootElement){showEngineVersion&&console.log(`${engineName} Engine v${engineVersion}`);ASSERT(!mainContext,"engine already initialized");if(mainContext)return;ASSERT(isArray(imageSources),"pass in images as array");if(!document.body)document.documentElement.appendChild(document.createElement("body"));rootElement||=document.body;gameInit||=()=>{};gameUpdate||=()=>{};gameUpdatePost||=()=>{};gameRender||=()=>{};gameRenderPost||=()=>{};function enginePreRender(){mainContext.imageSmoothingEnabled=!tilesPixelated;glPreRender();pluginList.forEach(plugin=>plugin.preRender?.())}function engineUpdate(frameTimeMS=0){let frameTimeDeltaMS=frameTimeMS-frameTimeLastMS;if(!frameTimeLastMS)frameTimeDeltaMS=0;frameTimeLastMS=frameTimeMS;if(debug||debugWatermark)averageFPS=lerp(averageFPS,1e3/(frameTimeDeltaMS||1),.05);const debugSpeedUp=debug&&keyIsDown("Equal");const debugSpeedDown=debug&&keyIsDown("Minus");const debugScale=debugSpeedUp?10:debugSpeedDown?.1:1;const frameTimeDeltaUnscaledMS=frameTimeDeltaMS;timeReal+=frameTimeDeltaMS*debugScale/1e3;const combinedScale=timeScale*debugScale;frameTimeDeltaMS*=combinedScale;frameTimeBufferMS+=paused?frameTimeDeltaUnscaledMS:frameTimeDeltaMS;if(paused||combinedScale<=1)frameTimeBufferMS=min(frameTimeBufferMS,50);let wasUpdated=false,deltaSmooth=0;if(frameTimeBufferMS<0&&frameTimeBufferMS>-9){deltaSmooth=frameTimeBufferMS;frameTimeBufferMS=0}for(;frameTimeBufferMS>=0;frameTimeBufferMS-=1e3/frameRate){if(!paused)time=frame++/frameRate;wasUpdated=true;engineUpdateCanvas();inputUpdate();if(!paused)gameUpdate();pluginList.forEach(plugin=>plugin.update?.());if(paused){for(const o of engineObjects)o.parent||o.updateTransforms()}else engineObjectsUpdate();debugUpdate();gameUpdatePost();inputUpdatePost();if(debugVideoCaptureIsActive())renderFrame()}frameTimeBufferMS+=deltaSmooth;let windowChanged=false;if(!headlessMode){const dpr=devicePixelRatio;windowChanged=windowWidthLast!==innerWidth||windowHeightLast!==innerHeight||windowPixelRatioLast!==dpr;windowWidthLast=innerWidth;windowHeightLast=innerHeight;windowPixelRatioLast=dpr}if(!debugVideoCaptureIsActive()&&(wasUpdated||windowChanged))renderFrame();if(!engineManualStep)requestAnimationFrame(engineUpdate);function renderFrame(){if(headlessMode)return;if(!wasUpdated)engineUpdateCanvas();enginePreRender();gameRender();engineObjects.sort((a,b)=>a.renderOrder-b.renderOrder);for(const o of engineObjects){if(o.destroyed)continue;setShader(o.shader);o.render()}setShader();gameRenderPost();pluginList.forEach(plugin=>plugin.render?.());inputRender();debugRender();glFlush();debugRenderPost();drawCount=0;primitiveCount=0}}engineUpdateInternal=engineUpdate;if(headlessMode)return startEngine();glInit(rootElement);const styleRoot="margin:0;"+"overflow:hidden;"+"background:#000;"+"user-select:none;"+"-webkit-user-select:none;"+"touch-action:none;"+"-webkit-touch-callout:none";rootElement.style.cssText=styleRoot;mainCanvas=rootElement.appendChild(document.createElement("canvas"));drawContext=mainContext=mainCanvas.getContext("2d");inputInit();audioInit();debugInit();const styleCanvas="position:absolute;"+"top:50%;left:50%;transform:translate(-50%,-50%)";mainCanvas.style.cssText=styleCanvas;if(glCanvas)glCanvas.style.cssText=styleCanvas;setCanvasPixelated(canvasPixelated);engineUpdateCanvas();glPreRender();workContext=createCanvasContext(64);workCanvas=workContext.canvas;workReadContext=createCanvasContext(64,64,true);workReadCanvas=workReadContext.canvas;const promises=imageSources.map((src,i)=>loadTexture(i,src));if(!imageSources.length)promises.push(loadTexture(0));promises.push(imageFontInit());if(showSplashScreen){promises.push(new Promise(resolve=>{let t=0;updateSplash();function updateSplash(){inputClear();drawEngineLogo(t+=.01);t>1?resolve():setTimeout(updateSplash,16)}}))}await Promise.all(promises);return startEngine();async function startEngine(){await gameInit();engineManualStep||engineUpdate()}}function engineUpdateCanvas(){if(headlessMode)return;const dpr=getCanvasPixelRatio();if(canvasFixedSize.x){mainCanvasSize=canvasFixedSize.copy();const innerAspect=innerWidth/innerHeight;const fixedAspect=canvasFixedSize.x/canvasFixedSize.y;const w=innerAspect<fixedAspect?"100%":"";const h=innerAspect<fixedAspect?"":"100%";mainCanvas.style.width=w;mainCanvas.style.height=h;if(glCanvas){glCanvas.style.width=w;glCanvas.style.height=h}}else{mainCanvasSize.x=min(innerWidth,canvasMaxSize.x)|0;mainCanvasSize.y=min(innerHeight,canvasMaxSize.y)|0;const innerAspect=innerWidth/innerHeight;ASSERT(canvasMinAspect<=canvasMaxAspect);if(canvasMaxAspect&&innerAspect>canvasMaxAspect){const w=mainCanvasSize.y*canvasMaxAspect|0;mainCanvasSize.x=min(w,canvasMaxSize.x)}else if(innerAspect<canvasMinAspect){const h=mainCanvasSize.x/canvasMinAspect|0;mainCanvasSize.y=min(h,canvasMaxSize.y)}mainCanvas.style.width=mainCanvasSize.x+"px";mainCanvas.style.height=mainCanvasSize.y+"px";if(glCanvas){glCanvas.style.width=mainCanvasSize.x+"px";glCanvas.style.height=mainCanvasSize.y+"px"}}const bufferSizeX=mainCanvasSize.x*dpr|0;const bufferSizeY=mainCanvasSize.y*dpr|0;if(mainCanvas.width!==bufferSizeX||mainCanvas.height!==bufferSizeY){mainCanvas.width=bufferSizeX;mainCanvas.height=bufferSizeY}else{mainContext.setTransform(1,0,0,1,0,0);mainContext.globalCompositeOperation="source-over";mainContext.clearRect(0,0,bufferSizeX,bufferSizeY)}mainContext.setTransform(dpr,0,0,dpr,0,0);if(canvasClearColor.a>0&&!glEnable){mainContext.fillStyle=canvasClearColor.toString();mainContext.fillRect(0,0,mainCanvasSize.x,mainCanvasSize.y);mainContext.fillStyle=BLACK.toString()}mainContext.lineJoin="round";mainContext.lineCap="round"}const engineStepMaxFrames=36e3;function engineStep(frames=1){ASSERT(engineManualStep,"engineStep requires setEngineManualStep(true) before engineInit");ASSERT(engineUpdateInternal,"engineStep requires engineInit to complete");if(!engineManualStep||!engineUpdateInternal)return;ASSERT(Number.isInteger(frames)&&frames>=0&&frames<=engineStepMaxFrames,"engineStep requires a whole frame count from 0 to "+engineStepMaxFrames);frames=min(frames,engineStepMaxFrames);for(let i=frames;i>0;--i)engineUpdateInternal(frameTimeLastMS+1e3/frameRate)}function engineObjectsUpdate(){engineObjectsCollide=engineObjects.filter(o=>o.collideSolidObjects);for(const o of engineObjects)if(!o.parent&&!o.destroyed)o.updatePhysics();function updateChildObject(o){if(o.destroyed)return;o.update();for(const child of o.children)updateChildObject(child)}for(const o of engineObjects){if(o.parent||o.destroyed)continue;o.update();for(const child of o.children)updateChildObject(child);o.updateTransforms()}engineObjects=engineObjects.filter(o=>!o.destroyed)}function engineObjectsDestroy(immediate=true){for(const o of engineObjects)o.parent||o.persistent||o.destroy(immediate);engineObjects=engineObjects.filter(o=>!o.destroyed)}function engineObjectsCollect(pos,size,objects=engineObjects){const collectedObjects=[];if(!pos){for(const o of objects)collectedObjects.push(o)}else if(size instanceof Vector2){for(const o of objects)o.isOverlapping(pos,size)&&collectedObjects.push(o)}else{const sizeSquared=size*size;for(const o of objects)pos.distanceSquared(o.pos)<sizeSquared&&collectedObjects.push(o)}return collectedObjects}function engineObjectsCallback(pos,size,callbackFunction,objects=engineObjects){engineObjectsCollect(pos,size,objects).forEach(o=>callbackFunction(o))}function engineObjectsRaycast(start,end,objects=engineObjects){const hitObjects=[];for(const o of objects){if(o.collideRaycast&&isIntersecting(start,end,o.pos,o.size)){debugRaycast&&debugRect(o.pos,o.size,"#f00");hitObjects.push(o)}}debugRaycast&&debugLine(start,end,hitObjects.length?"#f00":"#00f",.02);return hitObjects}let debugWatermark=0;let debugKey="";const debug=0;const debugOverlay=0;const debugPhysics=0;const debugParticles=0;const debugRaycast=0;const debugGamepads=0;const debugSound=0;const debugPointSize=.5;function ASSERT(){}function LOG(){}function debugInit(){}function debugUpdate(){}function debugRender(){}function debugRenderPost(){}function debugRect(){}function debugPoly(){}function debugCircle(){}function debugPoint(){}function debugLine(){}function debugOverlap(){}function debugText(){}function debugClear(){}function debugScreenshot(){}function debugShowErrors(){}function debugVideoCaptureIsActive(){return false}function debugVideoCaptureStart(){}function debugVideoCaptureStop(){}function debugVideoCaptureUpdate(){}function debugProtectConstant(o){return o}const PI=Math.PI;const abs=Math.abs;const floor=Math.floor;const ceil=Math.ceil;const round=Math.round;const min=Math.min;const max=Math.max;const sign=x=>Math.sign(x);const hypot=(...values)=>Math.hypot(...values);const log2=x=>Math.log2(x);const sin=Math.sin;const cos=Math.cos;const tan=Math.tan;const atan2=Math.atan2;function mod(dividend,divisor=1){return(dividend%divisor+divisor)%divisor}function clamp(value,min=0,max=1){return value<min?min:value>max?max:value}function percent(value,valueA,valueB){return(valueB-=valueA)?clamp((value-valueA)/valueB):0}function lerp(valueA,valueB,percent){return valueA+clamp(percent)*(valueB-valueA)}function percentLerp(value,percentA,percentB,lerpA,lerpB){return lerp(lerpA,lerpB,percent(value,percentA,percentB))}function distanceWrap(valueA,valueB,wrapSize=1){ASSERT(wrapSize>0,"distanceWrap wrapSize must be > 0");const d=(valueA-valueB)%wrapSize;return d*2%wrapSize-d}function lerpWrap(valueA,valueB,percent,wrapSize=1){return valueA+clamp(percent)*distanceWrap(valueB,valueA,wrapSize)}function distanceAngle(angleA,angleB){return distanceWrap(angleA,angleB,2*PI)}function lerpAngle(angleA,angleB,percent){return lerpWrap(angleA,angleB,percent,2*PI)}function smoothStep(percent){return percent*percent*(3-2*percent)}function isPowerOfTwo(value){return value>0&&!(value&value-1)}function nearestPowerOfTwo(value){return 2**ceil(log2(value))}function isOverlapping(posA,sizeA,posB,sizeB=vec2()){const dx=(posA.x-posB.x)*2;const dy=(posA.y-posB.y)*2;const sx=sizeA.x+sizeB.x;const sy=sizeA.y+sizeB.y;return abs(dx)<sx&&abs(dy)<sy}function isIntersecting(start,end,pos,size){const boxMin=pos.subtract(size.scale(.5));const boxMax=boxMin.add(size);const delta=end.subtract(start);const a=start.subtract(boxMin);const b=start.subtract(boxMax);const p=[-delta.x,delta.x,-delta.y,delta.y];const q=[a.x,-b.x,a.y,-b.y];let tMin=0,tMax=1;for(let i=4;i--;){if(p[i]){const t=q[i]/p[i];if(p[i]<0){if(t>tMax)return false;tMin=max(t,tMin)}else{if(t<tMin)return false;tMax=min(t,tMax)}}else if(q[i]<0)return false}return true}function collideCircleCircle(posA,radiusA,posB,radiusB){const d=posA.subtract(posB);const r=radiusA+radiusB;const dist=d.length();if(dist>=r)return undefined;return d.normalize(r-dist)}function collideCircleBox(pos,radius,boxPos,boxSize){const h=boxSize.scale(.5);const closest=vec2(clamp(pos.x,boxPos.x-h.x,boxPos.x+h.x),clamp(pos.y,boxPos.y-h.y,boxPos.y+h.y));const d=pos.subtract(closest),distSq=d.lengthSquared();if(distSq)return distSq>=radius*radius?undefined:d.normalize(radius-distSq**.5);const offset=pos.subtract(boxPos);return pushOutAxis(offset,h.x-abs(offset.x),h.y-abs(offset.y),radius)}function collideBoxBox(posA,sizeA,posB,sizeB){const d=posA.subtract(posB);const overlapX=(sizeA.x+sizeB.x)/2-abs(d.x);const overlapY=(sizeA.y+sizeB.y)/2-abs(d.y);if(overlapX<=0||overlapY<=0)return undefined;return pushOutAxis(d,overlapX,overlapY)}function pushOutAxis(d,penX,penY,extra=0){const s=v=>v>=0?1:-1;return penX<=penY?vec2(s(d.x)*(penX+extra),0):vec2(0,s(d.y)*(penY+extra))}function oscillate(frequency=1,amplitude=1,t=time,offset=0,type=0){const phase=mod(offset+t*frequency,1);let value;if(type===1)value=2*abs(2*phase-1)-1;else if(type===2)value=phase<.5?-1:1;else if(type===3)value=2*phase-1;else value=-cos(phase*2*PI);return amplitude/2*(value+1)}function isNumber(n){return typeof n==="number"&&!isNaN(n)}function isStringLike(s){return s!=null&&typeof s?.toString()==="string"}function isArray(a){return Array.isArray(a)}function lineTest(posStart,posEnd,testFunction,normal){ASSERT(isVector2(posStart),"posStart must be a vec2");ASSERT(isVector2(posEnd),"posEnd must be a vec2");ASSERT(typeof testFunction==="function","testFunction must be a function");ASSERT(!normal||isVector2(normal),"normal must be a vec2");const dx=posEnd.x-posStart.x;const dy=posEnd.y-posStart.y;const totalLength=(dx*dx+dy*dy)**.5;if(!totalLength)return;const pos=posStart.floor();const dirX=dx/totalLength;const dirY=dy/totalLength;const stepX=sign(dirX);const stepY=sign(dirY);const tDeltaX=dirX?abs(1/dirX):Infinity;const tDeltaY=dirY?abs(1/dirY):Infinity;const nextGridX=stepX>0?pos.x+1:pos.x;const nextGridY=stepY>0?pos.y+1:pos.y;const tMaxX=dirX?(nextGridX-posStart.x)/dirX:Infinity;const tMaxY=dirY?(nextGridY-posStart.y)/dirY:Infinity;let t=0,tX=tMaxX,tY=tMaxY,wasX=tDeltaX<tDeltaY;while(t<totalLength){if(testFunction(pos)){const hitPos=vec2(posStart.x+dirX*t,posStart.y+dirY*t);const e=1e-9;const hitPosFloor=hitPos.floor();if(hitPosFloor.x<pos.x)hitPos.x=pos.x;else if(hitPosFloor.x>pos.x)hitPos.x=pos.x+1-e;if(hitPosFloor.y<pos.y)hitPos.y=pos.y;else if(hitPosFloor.y>pos.y)hitPos.y=pos.y+1-e;if(normal)wasX?normal.set(-stepX,0):normal.set(0,-stepY);return hitPos}if(wasX=tX<tY){pos.x+=stepX;t=tX;tX+=tDeltaX}else{pos.y+=stepY;t=tY;tY+=tDeltaY}}}function rand(valueA=1,valueB=0){return valueB+Math.random()*(valueA-valueB)}function randInt(valueA,valueB=0){return floor(rand(valueA,valueB))}function randBool(chance=.5){return rand()<chance}function randSign(){return randInt(2)*2-1}function randVec2(length=1){return(new Vector2).setAngle(rand(2*PI),length)}function randInCircle(radius=1,minRadius=0){if(radius<=0)return new Vector2;const ratio=clamp(minRadius/radius);return randVec2(radius*rand(ratio*ratio,1)**.5)}function randColor(colorA=new Color,colorB=new Color(0,0,0,1),linear=false){return linear?colorA.lerp(colorB,rand()):new Color(rand(colorA.r,colorB.r),rand(colorA.g,colorB.g),rand(colorA.b,colorB.b),rand(colorA.a,colorB.a))}class RandomGenerator{constructor(seed=123456789){ASSERT(seed!==0,"RandomGenerator seed must be non-zero (xorshift is fixed at 0)");this.seed=seed}float(valueA=1,valueB=0){this.seed^=this.seed<<13;this.seed^=this.seed>>>17;this.seed^=this.seed<<5;return valueB+(valueA-valueB)*((this.seed>>>0)/2**32)}int(valueA,valueB=0){return floor(this.float(valueA,valueB))}bool(chance=.5){return this.float()<chance}sign(){return this.float()>.5?1:-1}floatSign(valueA=1,valueB=0){const lo=min(valueA,valueB);const hi=max(valueA,valueB);const d=hi-lo;const e=this.float(d*2);return e<d?lo+e:d-lo-e}angle(){return this.float(-PI,PI)}vec2(valueA=1,valueB=0){return vec2(this.float(valueA,valueB),this.float(valueA,valueB))}randColor(colorA=new Color,colorB=new Color(0,0,0,1),linear=false){return linear?colorA.lerp(colorB,this.float()):new Color(this.float(colorA.r,colorB.r),this.float(colorA.g,colorB.g),this.float(colorA.b,colorB.b),this.float(colorA.a,colorB.a))}mutateColor(color,amount=.05,alphaAmount=0){ASSERT_NUMBER_VALID(amount);ASSERT_NUMBER_VALID(alphaAmount);return new Color(color.r+this.float(amount,-amount),color.g+this.float(amount,-amount),color.b+this.float(amount,-amount),color.a+this.float(alphaAmount,-alphaAmount)).clamp()}}function vec2(x=0,y){return new Vector2(x,y??x)}function isVector2(v){return v instanceof Vector2&&v.isValid()}function ASSERT_VECTOR2_VALID(v){ASSERT(isVector2(v),"Vector2 is invalid.",v)}function ASSERT_NUMBER_VALID(n){ASSERT(isNumber(n),"Number is invalid.",n)}function ASSERT_VECTOR2_NORMAL(v){ASSERT_VECTOR2_VALID(v);ASSERT(abs(v.lengthSquared()-1)<.01,"Vector2 is not normal.",v)}class Vector2{constructor(x=0,y=0){this.x=x;this.y=y;ASSERT(this.isValid(),"Constructed Vector2 is invalid.",this)}set(x=0,y=0){this.x=x;this.y=y;ASSERT_VECTOR2_VALID(this);return this}setFrom(v){return this.set(v.x,v.y)}copy(){return new Vector2(this.x,this.y)}add(v){return new Vector2(this.x+v.x,this.y+v.y)}subtract(v){return new Vector2(this.x-v.x,this.y-v.y)}multiply(v){return new Vector2(this.x*v.x,this.y*v.y)}divide(v){return new Vector2(this.x/v.x,this.y/v.y)}scale(s){return new Vector2(this.x*s,this.y*s)}length(){return this.lengthSquared()**.5}lengthSquared(){return this.x**2+this.y**2}distance(v){return this.distanceSquared(v)**.5}distanceSquared(v){return(this.x-v.x)**2+(this.y-v.y)**2}normalize(length=1){const l=this.length();return l?this.scale(length/l):new Vector2(0,length)}clampLength(length=1){const l=this.length();return l>length?this.scale(length/l):this.copy()}dot(v){return this.x*v.x+this.y*v.y}cross(v){return this.x*v.y-this.y*v.x}reflect(normal,restitution=1){return this.subtract(normal.scale((1+restitution)*this.dot(normal)))}angle(){return atan2(this.x,this.y)}setAngle(angle=0,length=1){ASSERT_NUMBER_VALID(angle);ASSERT_NUMBER_VALID(length);this.x=length*sin(angle);this.y=length*cos(angle);return this}rotate(angle){ASSERT_NUMBER_VALID(angle);const c=cos(-angle),s=sin(-angle);return new Vector2(this.x*c-this.y*s,this.x*s+this.y*c)}setDirection(direction,length=1){ASSERT_NUMBER_VALID(direction);ASSERT_NUMBER_VALID(length);direction=mod(direction,4);ASSERT(direction===0||direction===1||direction===2||direction===3,"Vector2.setDirection() direction must be an integer between 0 and 3.");this.x=direction%2?direction-1?-length:length:0;this.y=direction%2?0:direction?-length:length;return this}direction(){return abs(this.x)>abs(this.y)?this.x<0?3:1:this.y<0?2:0}abs(){return new Vector2(abs(this.x),abs(this.y))}floor(){return new Vector2(floor(this.x),floor(this.y))}snap(grid){ASSERT_NUMBER_VALID(grid);return new Vector2(floor(this.x*grid)/grid,floor(this.y*grid)/grid)}mod(divisor=1){return new Vector2(mod(this.x,divisor),mod(this.y,divisor))}area(){return abs(this.x*this.y)}lerp(v,percent){ASSERT_VECTOR2_VALID(v);ASSERT_NUMBER_VALID(percent);const p=clamp(percent);return new Vector2(v.x*p+this.x*(1-p),v.y*p+this.y*(1-p))}arrayCheck(arraySize){return this.x>=0&&this.y>=0&&this.x<arraySize.x&&this.y<arraySize.y}toString(digits=3){ASSERT_NUMBER_VALID(digits);if(this.isValid())return`(${(this.x<0?"":" ")+this.x.toFixed(digits)},${(this.y<0?"":" ")+this.y.toFixed(digits)} )`;else return`(${this.x}, ${this.y})`}isValid(){return isNumber(this.x)&&isNumber(this.y)}}function rgb(r,g,b,a){return new Color(r,g,b,a)}function hsl(h,s,l,a){return(new Color).setHSLA(h,s,l,a)}function isColor(c){return c instanceof Color&&c.isValid()}function ASSERT_COLOR_VALID(c){ASSERT(isColor(c),"Color is invalid.",c)}class Color{constructor(r=1,g=1,b=1,a=1){this.r=r;this.g=g;this.b=b;this.a=a;ASSERT(this.isValid(),"Constructed Color is invalid.",this)}set(r=1,g=1,b=1,a=1){this.r=r;this.g=g;this.b=b;this.a=a;ASSERT_COLOR_VALID(this);return this}setFrom(c){return this.set(c.r,c.g,c.b,c.a)}setAlpha(a=1){this.a=a;ASSERT_COLOR_VALID(this);return this}copy(){return new Color(this.r,this.g,this.b,this.a)}withAlpha(a=1){return new Color(this.r,this.g,this.b,a)}add(c){return new Color(this.r+c.r,this.g+c.g,this.b+c.b,this.a+c.a)}subtract(c){return new Color(this.r-c.r,this.g-c.g,this.b-c.b,this.a-c.a)}multiply(c){return new Color(this.r*c.r,this.g*c.g,this.b*c.b,this.a*c.a)}divide(c){return new Color(this.r/c.r,this.g/c.g,this.b/c.b,this.a/c.a)}scale(scale,alphaScale=scale){return new Color(this.r*scale,this.g*scale,this.b*scale,this.a*alphaScale)}clamp(){return new Color(clamp(this.r),clamp(this.g),clamp(this.b),clamp(this.a))}lerp(c,percent){ASSERT_COLOR_VALID(c);ASSERT_NUMBER_VALID(percent);const p=clamp(percent);return new Color(c.r*p+this.r*(1-p),c.g*p+this.g*(1-p),c.b*p+this.b*(1-p),c.a*p+this.a*(1-p))}setHSLA(h=0,s=0,l=1,a=1){h=mod(h,1);s=clamp(s);l=clamp(l);const q=l<.5?l*(1+s):l+s-l*s,p=2*l-q,f=(p,q,t)=>(t=mod(t,1))*6<1?p+(q-p)*6*t:t*2<1?q:t*3<2?p+(q-p)*(4-t*6):p;this.r=f(p,q,h+1/3);this.g=f(p,q,h);this.b=f(p,q,h-1/3);this.a=a;ASSERT_COLOR_VALID(this);return this}HSLA(){const r=clamp(this.r);const g=clamp(this.g);const b=clamp(this.b);const a=clamp(this.a);const maxC=max(r,g,b);const minC=min(r,g,b);const l=(maxC+minC)/2;let h=0,s=0;if(maxC!==minC){let d=maxC-minC;s=l>.5?d/(2-maxC-minC):d/(maxC+minC);if(r===maxC)h=(g-b)/d+(g<b?6:0);else if(g===maxC)h=(b-r)/d+2;else if(b===maxC)h=(r-g)/d+4}return[h/6,s,l,a]}mutate(amount=.05,alphaAmount=0){ASSERT_NUMBER_VALID(amount);ASSERT_NUMBER_VALID(alphaAmount);return new Color(this.r+rand(amount,-amount),this.g+rand(amount,-amount),this.b+rand(amount,-amount),this.a+rand(alphaAmount,-alphaAmount)).clamp()}toString(useAlpha=true){if(debug&&!this.isValid())return"#000";const toHex=c=>((c=clamp(c)*255|0)<16?"0":"")+c.toString(16);return"#"+toHex(this.r)+toHex(this.g)+toHex(this.b)+(useAlpha?toHex(this.a):"")}setHex(hex){ASSERT(isStringLike(hex),"Color hex code must be a string");ASSERT(hex[0]==="#","Color hex code must start with #");ASSERT([4,5,7,9].includes(hex.length),"Invalid hex");if(hex.length<6){const fromHex=c=>clamp(parseInt(hex[c],16)/15);this.r=fromHex(1);this.g=fromHex(2);this.b=fromHex(3);this.a=hex.length===5?fromHex(4):1}else{const fromHex=c=>clamp(parseInt(hex.slice(c,c+2),16)/255);this.r=fromHex(1);this.g=fromHex(3);this.b=fromHex(5);this.a=hex.length===9?fromHex(7):1}ASSERT_COLOR_VALID(this);return this}rgbaInt(){const r=clamp(this.r)*255|0;const g=clamp(this.g)*255<<8;const b=clamp(this.b)*255<<16;const a=clamp(this.a)*255<<24;return r+g+b+a}isValid(){return isNumber(this.r)&&isNumber(this.g)&&isNumber(this.b)&&isNumber(this.a)}}const WHITE=debugProtectConstant(rgb());const CLEAR_WHITE=debugProtectConstant(rgb(1,1,1,0));const BLACK=debugProtectConstant(rgb(0,0,0));const CLEAR_BLACK=debugProtectConstant(rgb(0,0,0,0));const GRAY=debugProtectConstant(rgb(.5,.5,.5));const RED=debugProtectConstant(rgb(1,0,0));const ORANGE=debugProtectConstant(rgb(1,.5,0));const YELLOW=debugProtectConstant(rgb(1,1,0));const GREEN=debugProtectConstant(rgb(0,1,0));const CYAN=debugProtectConstant(rgb(0,1,1));const BLUE=debugProtectConstant(rgb(0,0,1));const PURPLE=debugProtectConstant(rgb(.5,0,1));const MAGENTA=debugProtectConstant(rgb(1,0,1));class Timer{constructor(timeLeft,useRealTime=false){ASSERT(timeLeft===undefined||isNumber(timeLeft),"Constructed Timer is invalid.",timeLeft);this.useRealTime=useRealTime;const globalTime=this.getGlobalTime();this.time=timeLeft===undefined?undefined:globalTime+timeLeft;this.setTime=timeLeft}set(timeLeft=0){ASSERT(isNumber(timeLeft),"Timer is invalid.",timeLeft);const globalTime=this.getGlobalTime();this.time=globalTime+timeLeft;this.setTime=timeLeft}setUseRealTime(useRealTime=true){ASSERT(!this.isSet(),"Cannot change global time setting while timer is set.");this.useRealTime=useRealTime}unset(){this.time=undefined}isSet(){return this.time!==undefined}active(){return this.getGlobalTime()<this.time}elapsed(){return this.getGlobalTime()>=this.time}get(){return this.isSet()?this.getGlobalTime()-this.time:0}getPercent(){if(!this.isSet())return 0;if(!this.setTime)return 1;return 1-percent(this.time-this.getGlobalTime(),0,this.setTime)}getSetTime(){return this.isSet()?this.setTime:0}getGlobalTime(){return this.useRealTime?timeReal:time}toString(){return this.isSet()?abs(this.get())+" seconds "+(this.get()<0?"before":"after"):"unset"}valueOf(){return this.get()}}function formatTime(t){const signStr=t<0?"-":"";t=abs(t)|0;return signStr+(t/60|0)+":"+(t%60<10?"0":"")+t%60}async function fetchJSON(url){const response=await fetch(url);if(!response.ok)throw new Error(`Failed to fetch JSON from ${url}: ${response.status} ${response.statusText}`);return response.json()}function saveText(text,filename="text",type="text/plain"){saveDataURL(URL.createObjectURL(new Blob([text],{type:type})),filename)}function createCanvasContext(width,height=width,willReadFrequently=false){ASSERT(isNumber(width)&&isNumber(height),"canvas width and height must be numbers",width,height);return new OffscreenCanvas(width,height).getContext("2d",{willReadFrequently:willReadFrequently})}function saveCanvas(canvas,filename="screenshot",type="image/png"){if(canvas instanceof OffscreenCanvas){const saveCanvas=document.createElement("canvas");saveCanvas.width=canvas.width;saveCanvas.height=canvas.height;saveCanvas.getContext("2d").drawImage(canvas,0,0);saveDataURL(saveCanvas.toDataURL(type),filename)}else saveDataURL(canvas.toDataURL(type),filename)}function saveDataURL(url,filename="download",revokeTime){ASSERT(isStringLike(url),"saveDataURL requires url string");ASSERT(isStringLike(filename),"saveDataURL requires filename string");const link=document.createElement("a");link.download=filename;link.href=url;link.click();if(revokeTime!==undefined)setTimeout(()=>URL.revokeObjectURL(url),revokeTime)}function shareURL(title,url,callback){ASSERT(isStringLike(title),"shareURL requires title string");ASSERT(isStringLike(url),"shareURL requires url string");navigator.share?.({title:title,url:url}).then(()=>callback?.())}function readSaveData(saveName,defaultSaveData){ASSERT(isStringLike(saveName),"readSaveData requires saveName string");ASSERT(defaultSaveData===undefined||typeof defaultSaveData==="object"&&defaultSaveData!==null,"readSaveData: default must be an object - the result is "+"{...default, ...loaded}, so a scalar default yields {}. "+"Use readSaveData(key, {best:0}).best");let loadedData={};try{const data=localStorage[saveName];if(data){try{loadedData=JSON.parse(data)}catch{LOG("readSaveData: corrupt JSON for",saveName,"— using defaults")}}}catch{LOG("readSaveData: localStorage unavailable — using defaults")}return{...defaultSaveData,...loadedData}}function writeSaveData(saveName,saveData){ASSERT(isStringLike(saveName),"writeSaveData requires saveName string");try{localStorage[saveName]=JSON.stringify(saveData)}catch{LOG("writeSaveData: failed to write",saveName)}}function noiseHash(i){let h=(i|0)^2654435769;h=Math.imul(h^h>>>16,2246822507);h=Math.imul(h^h>>>13,3266489909);h^=h>>>16;return(h>>>0)/2**32}function noise1D(x){const i=floor(x);return lerp(noiseHash(i),noiseHash(i+1),smoothStep(x-i))}function noise2D(x,y){const ix=floor(x),iy=floor(y);const fx=smoothStep(x-ix),fy=smoothStep(y-iy);const h=(a,b)=>noiseHash(a+b*374761393);return lerp(lerp(h(ix,iy),h(ix+1,iy),fx),lerp(h(ix,iy+1),h(ix+1,iy+1),fx),fy)}let cameraPos=vec2();let cameraAngle=0;let cameraScale=32;let timeScale=1;let canvasColorTiles=true;let canvasClearColor=CLEAR_BLACK;let canvasMaxSize=vec2(3840,2160);let canvasMinAspect=0;let canvasMaxAspect=0;let canvasFixedSize=vec2();let canvasPixelated=false;let tilesPixelated=true;let canvasPixelRatio=1;let fontDefault="arial";let showSplashScreen=false;let headlessMode=false;let engineManualStep=false;let glEnable=true;let glCircleSides=32;let tileDefaultSize=vec2(16);let tileDefaultPadding=0;let tileDefaultBleed=0;let enablePhysicsSolver=true;let objectDefaultMass=1;let objectDefaultDamping=1;let objectDefaultAngleDamping=1;let objectDefaultRestitution=0;let objectDefaultFriction=.8;let objectMaxSpeed=1;let gravity=vec2();let particleEmitRateScale=1;let gamepadsEnable=true;let gamepadDirectionEmulateStick=true;let gamepadAxisFilterEnable=true;let inputWASDEmulateDirection=true;let touchInputEnable=true;let touchGamepadEnable=false;let touchGamepadPassthrough=false;let touchGamepadCenterButtonSize=0;let touchGamepadButtonCount=4;let touchGamepadLeftStick=true;let touchGamepadLeftButtonCount=0;let touchGamepadRightStick=false;let touchGamepadAnalog=true;let touchGamepadFloating=false;let touchGamepadSize=100;let touchGamepadAlpha=.3;let touchGamepadDisplayTime=3;let touchGamepadVibration=0;let vibrateEnable=true;let soundEnable=true;let soundVolume=.3;let soundDefaultRange=40;let soundDefaultTaper=.7;let soundPauseWhenHidden=true;function setCameraPos(pos){cameraPos=pos.copy()}function setCameraAngle(angle){cameraAngle=angle}function setCameraScale(scale){cameraScale=scale}function setTimeScale(scale){timeScale=scale}function setCanvasColorTiles(colorTiles){canvasColorTiles=colorTiles}function setCanvasClearColor(color){canvasClearColor=color.copy()}function setCanvasMaxSize(size){canvasMaxSize=size.copy()}function setCanvasMinAspect(aspect){canvasMinAspect=aspect}function setCanvasMaxAspect(aspect){canvasMaxAspect=aspect}function setCanvasFixedSize(size){canvasFixedSize=size.copy()}function setCanvasPixelated(pixelated){canvasPixelated=pixelated;if(mainCanvas)mainCanvas.style.imageRendering=pixelated?"pixelated":"";if(glCanvas)glCanvas.style.imageRendering=pixelated?"pixelated":""}function setTilesPixelated(pixelated){tilesPixelated=pixelated}function setCanvasPixelRatio(pixelRatio){canvasPixelRatio=pixelRatio}function getCanvasPixelRatio(){return canvasPixelRatio??(devicePixelRatio||1)}function setFontDefault(font){fontDefault=font}function setShowSplashScreen(show){showSplashScreen=show}function setHeadlessMode(headless){headlessMode=headless}function setEngineManualStep(enable=true){engineManualStep=enable}function setGLEnable(enable){if(enable&&!glCanBeEnabled){console.warn("Can not enable WebGL if it was disabled on start.");return}glEnable=enable;if(glCanvas)glCanvas.style.display=enable?"":"none"}function setGLCircleSides(sides){glCircleSides=sides}function setTileDefaultSize(size){tileDefaultSize=size.copy()}function setTileDefaultPadding(padding){tileDefaultPadding=padding}function setTileDefaultBleed(bleed){tileDefaultBleed=bleed}function setEnablePhysicsSolver(enable){enablePhysicsSolver=enable}function setObjectDefaultMass(mass){objectDefaultMass=mass}function setObjectDefaultDamping(damp){objectDefaultDamping=damp}function setObjectDefaultAngleDamping(damp){objectDefaultAngleDamping=damp}function setObjectDefaultRestitution(restitution){objectDefaultRestitution=restitution}function setObjectDefaultFriction(friction){objectDefaultFriction=friction}function setObjectMaxSpeed(speed){objectMaxSpeed=speed}function setGravity(newGravity){gravity=newGravity.copy()}function setParticleEmitRateScale(scale){particleEmitRateScale=scale}function setGamepadsEnable(enable){gamepadsEnable=enable}function setGamepadDirectionEmulateStick(enable){gamepadDirectionEmulateStick=enable}function setGamepadAxisFilterEnable(enable){gamepadAxisFilterEnable=enable}function setInputWASDEmulateDirection(enable){inputWASDEmulateDirection=enable}function setTouchInputEnable(enable){touchInputEnable=enable}function setTouchGamepadEnable(enable){touchGamepadEnable=enable}function setTouchGamepadPassthrough(passthrough){touchGamepadPassthrough=passthrough}function setTouchGamepadCenterButtonSize(size){touchGamepadCenterButtonSize=size}function setTouchGamepadButtonCount(count){touchGamepadButtonCount=count;if(count>0)touchGamepadRightStick=false}function setTouchGamepadLeftStick(enable){touchGamepadLeftStick=enable;if(enable)touchGamepadLeftButtonCount=0}function setTouchGamepadLeftButtonCount(count){touchGamepadLeftButtonCount=count;if(count>0)touchGamepadLeftStick=false}function setTouchGamepadRightStick(rightStick){touchGamepadRightStick=rightStick;if(rightStick)touchGamepadButtonCount=0}function setTouchGamepadAnalog(analog){touchGamepadAnalog=analog}function setTouchGamepadFloating(floating){touchGamepadFloating=floating}function setTouchGamepadSize(size){touchGamepadSize=size}function setTouchGamepadAlpha(alpha){touchGamepadAlpha=alpha}function setTouchGamepadDisplayTime(time){touchGamepadDisplayTime=time}function setTouchGamepadVibration(ms){touchGamepadVibration=ms}function setVibrateEnable(enable){vibrateEnable=enable}function setSoundEnable(enable){soundEnable=enable}function setSoundVolume(volume){soundVolume=volume;if(soundEnable&&!headlessMode&&audioMasterGain)audioMasterGain.gain.value=volume}function setSoundDefaultRange(range){soundDefaultRange=range}function setSoundDefaultTaper(taper){soundDefaultTaper=taper}function setSoundPauseWhenHidden(pause){soundPauseWhenHidden=pause}function setDebugWatermark(show){debugWatermark=show}function setDebugKey(key){debugKey=key}class EngineObject{constructor(pos=vec2(),size=vec2(1),tileInfo,angle=0,color=WHITE,renderOrder=0){ASSERT(isVector2(pos),"object pos must be a vec2");ASSERT(isVector2(size),"object size must be a vec2");ASSERT(!tileInfo||tileInfo instanceof TileInfo,"object tileInfo should be a TileInfo or undefined");ASSERT(typeof angle==="number"&&isFinite(angle),"object angle should be a number");ASSERT(isColor(color),"object color should be a valid rgba color");ASSERT(typeof renderOrder==="number","object renderOrder should be a number");this.pos=pos.copy();this.size=size.copy();this.drawSize=undefined;this.tileInfo=tileInfo;this.angle=angle;this.color=color.copy();this.additiveColor=undefined;this.shader=undefined;this.mirror=false;this.destroyed=false;this.mass=objectDefaultMass;this.damping=objectDefaultDamping;this.angleDamping=objectDefaultAngleDamping;this.restitution=objectDefaultRestitution;this.friction=objectDefaultFriction;this.gravityScale=1;this.renderOrder=renderOrder;this.velocity=vec2();this.angleVelocity=0;this.spawnTime=time;this.children=[];this.clampSpeed=true;this.groundObject=undefined;this.parent=undefined;this.localPos=vec2();this.localAngle=0;this.collideTiles=false;this.collideSolidObjects=false;this.isSolid=false;this.collideRaycast=false;this.persistent=false;engineObjects.push(this)}updateTransforms(){const parent=this.parent;if(parent){const mirror=parent.getMirrorSign();const lp=this.localPos,pp=parent.pos;const lx=lp.x*mirror,ly=lp.y,pa=parent.angle;if(pa){const c=cos(-pa),s=sin(-pa);this.pos.set(lx*c-ly*s+pp.x,lx*s+ly*c+pp.y)}else this.pos.set(lx+pp.x,ly+pp.y);this.angle=mirror*this.localAngle+pa}for(const child of this.children)child.updateTransforms()}updatePhysics(){ASSERT(!this.parent);if(this.destroyed)return;if(this.clampSpeed){this.velocity.x=clamp(this.velocity.x,-objectMaxSpeed,objectMaxSpeed);this.velocity.y=clamp(this.velocity.y,-objectMaxSpeed,objectMaxSpeed)}const oldPos=this.pos.copy();this.velocity.x*=this.damping;this.velocity.y*=this.damping;if(this.mass){this.velocity.x+=gravity.x*this.gravityScale;this.velocity.y+=gravity.y*this.gravityScale}this.pos.x+=this.velocity.x;this.pos.y+=this.velocity.y;this.angle+=this.angleVelocity*=this.angleDamping;ASSERT(this.angleDamping>=0&&this.angleDamping<=1);ASSERT(this.damping>=0&&this.damping<=1);if(!enablePhysicsSolver||!this.mass)return;const wasFalling=this.velocity.y<0&&gravity.y<0||this.velocity.y>0&&gravity.y>0;if(this.groundObject){const friction=max(this.friction,this.groundObject.friction);const groundSpeed=this.groundObject.velocity.x;this.velocity.x=groundSpeed+(this.velocity.x-groundSpeed)*friction;this.groundObject=undefined}if(this.collideSolidObjects&&this.size.x&&this.size.y){const epsilon=.001;for(const o of engineObjectsCollide){if(o.destroyed||o.parent||o===this||!o.size.x||!o.size.y)continue;if(!this.isSolid&&!o.isSolid)continue;if(!this.isOverlappingObject(o))continue;const collide1=this.collideWithObject(o);const collide2=o.collideWithObject(this);if(!collide1||!collide2)continue;if(isOverlapping(oldPos,this.size,o.pos,o.size)){const deltaPos=oldPos.subtract(o.pos);const length=deltaPos.length();const pushAwayAccel=.001;const velocity=length<.001?vec2(0,1):deltaPos.scale(pushAwayAccel/length);this.velocity=this.velocity.add(velocity);if(o.mass)o.velocity=o.velocity.subtract(velocity);debugPhysics&&debugOverlap(this.pos,this.size,o.pos,o.size,"#f00");continue}const sizeBoth=this.size.add(o.size);const smallStepUp=(oldPos.y-o.pos.y)*2>sizeBoth.y+gravity.y;const isBlockedX=abs(oldPos.y-o.pos.y)*2<sizeBoth.y;const isBlockedY=abs(oldPos.x-o.pos.x)*2<sizeBoth.x;const restitution=max(this.restitution,o.restitution);if(smallStepUp||isBlockedY||!isBlockedX){this.pos.y=o.pos.y+(sizeBoth.y/2+epsilon)*sign(oldPos.y-o.pos.y);if(o.groundObject&&wasFalling||!o.mass){if(wasFalling)this.groundObject=o;this.velocity.y*=-restitution}else if(o.mass){const inelastic=(this.mass*this.velocity.y+o.mass*o.velocity.y)/(this.mass+o.mass);const elastic0=this.velocity.y*(this.mass-o.mass)/(this.mass+o.mass)+o.velocity.y*2*o.mass/(this.mass+o.mass);const elastic1=o.velocity.y*(o.mass-this.mass)/(this.mass+o.mass)+this.velocity.y*2*this.mass/(this.mass+o.mass);this.velocity.y=lerp(inelastic,elastic0,restitution);o.velocity.y=lerp(inelastic,elastic1,restitution)}}if(!smallStepUp&&isBlockedX){this.pos.x=o.pos.x+(sizeBoth.x/2+epsilon)*sign(oldPos.x-o.pos.x);if(o.mass){const inelastic=(this.mass*this.velocity.x+o.mass*o.velocity.x)/(this.mass+o.mass);const elastic0=this.velocity.x*(this.mass-o.mass)/(this.mass+o.mass)+o.velocity.x*2*o.mass/(this.mass+o.mass);const elastic1=o.velocity.x*(o.mass-this.mass)/(this.mass+o.mass)+this.velocity.x*2*this.mass/(this.mass+o.mass);this.velocity.x=lerp(inelastic,elastic0,restitution);o.velocity.x=lerp(inelastic,elastic1,restitution)}else this.velocity.x*=-restitution}debugPhysics&&debugOverlap(this.pos,this.size,o.pos,o.size,"#f0f")}}if(this.collideTiles){const hitLayer=tileCollisionTest(this.pos,this.size,this);if(hitLayer){if(!tileCollisionTest(oldPos,this.size,this)){const isBlockedX=tileCollisionTest(vec2(this.pos.x,oldPos.y),this.size,this);const isBlockedY=tileCollisionTest(vec2(oldPos.x,this.pos.y),this.size,this);const restitution=max(this.restitution,hitLayer.restitution);if(isBlockedX){const epsilon=.001;const maxMove=.1;const gravitySign=gravity.y>0?-1:1;const y=gravitySign>0?floor(oldPos.y-this.size.y/2+1)+this.size.y/2+epsilon:ceil(oldPos.y+this.size.y/2-1)-this.size.y/2-epsilon;const delta=abs(y-this.pos.y);if(delta<maxMove)if(!tileCollisionTest(vec2(this.pos.x,y),this.size,this)){this.pos.y=y;debugPhysics&&debugRect(this.pos,this.size,"#ff0");return}this.pos.x=oldPos.x;this.velocity.x*=-restitution}if(isBlockedY||!isBlockedX){if(wasFalling){const epsilon=1e-4;const offset=this.size.y/2+epsilon;this.pos.y=gravity.y<0?floor(oldPos.y-this.size.y/2)+offset:ceil(oldPos.y+this.size.y/2)-offset;this.groundObject=hitLayer}else{this.pos.y=oldPos.y;this.groundObject=undefined}this.velocity.y*=-restitution}debugPhysics&&debugRect(this.pos,this.size,"#f00")}}}}update(){}render(){drawTile(this.pos,this.drawSize||this.size,this.tileInfo,this.color,this.angle,this.mirror,this.additiveColor)}renderLight(){}destroy(immediate=false){if(this.destroyed)return;this.destroyed=true;this.parent?.removeChild(this);for(const child of this.children){child.parent=undefined;child.destroy(immediate)}}localToWorld(pos){return this.pos.add(pos.rotate(this.angle))}worldToLocal(pos){return pos.subtract(this.pos).rotate(-this.angle)}localToWorldVector(vec){return vec.rotate(this.angle)}worldToLocalVector(vec){return vec.rotate(-this.angle)}collideWithTile(tileData,pos){return tileData>0}collideWithObject(object,push){return true}getUp(scale=1){return vec2().setAngle(this.angle,scale)}getRight(scale=1){return vec2().setAngle(this.angle+PI/2,scale)}getAliveTime(){return time-this.spawnTime}getSpeed(){return this.velocity.length()}applyAcceleration(acceleration){if(this.mass)this.velocity=this.velocity.add(acceleration)}applyAngularAcceleration(acceleration){if(this.mass)this.angleVelocity+=acceleration}applyForce(force){if(this.mass)this.applyAcceleration(force.scale(1/this.mass))}getMirrorSign(){return this.mirror?-1:1}addChild(child,localPos=vec2(),localAngle=0){ASSERT(!this.destroyed,"cannot add child to destroyed object");if(this.destroyed)return child;ASSERT(!child.parent&&!this.children.includes(child));ASSERT(child instanceof EngineObject,"child must be an EngineObject");ASSERT(child!==this,"cannot add self as child");this.children.push(child);child.parent=this;child.localPos=localPos.copy();child.localAngle=localAngle;child.updateTransforms();return child}removeChild(child){ASSERT(child.parent===this&&this.children.includes(child));this.children.splice(this.children.indexOf(child),1);child.parent=undefined}isOverlappingObject(object){return this.isOverlapping(object.pos,object.size)}isOverlapping(pos,size=vec2()){return isOverlapping(this.pos,this.size,pos,size)}setCollision(collideSolidObjects=true,isSolid=true,collideTiles=true,collideRaycast=true){ASSERT(collideSolidObjects||!isSolid,"solid objects must be set to collide");this.collideSolidObjects=collideSolidObjects;this.isSolid=isSolid;this.collideTiles=collideTiles;this.collideRaycast=collideRaycast}toString(){let text="type = "+this.constructor.name;if(this.pos.x||this.pos.y)text+="\npos = "+this.pos;if(this.velocity.x||this.velocity.y)text+="\nvelocity = "+this.velocity;if(this.size.x||this.size.y)text+="\nsize = "+this.size;if(this.angle)text+="\nangle = "+this.angle.toFixed(3);if(this.color)text+="\ncolor = "+this.color;return text}renderDebugInfo(){if(!debug)return;const hasPhysics=this.collideTiles||this.collideSolidObjects||this.isSolid;if(!hasPhysics&&!this.parent)return;const size=vec2(max(this.size.x,.2),max(this.size.y,.2));const color=rgb(this.collideTiles?1:0,this.collideSolidObjects?1:0,this.isSolid?1:0,.5);debugRect(this.pos,size,color,0,this.angle,hasPhysics);if(this.parent)debugRect(this.pos,size.scale(.8),rgb(1,1,1,.5),0,this.angle);this.parent&&debugLine(this.pos,this.parent.pos,rgb(1,1,1,.5),.5)}}let mainCanvas;let mainContext;let drawContext;let workCanvas;let workContext;let workReadCanvas;let workReadContext;let backgroundCanvas;let mainCanvasSize=vec2();let textureInfos=[];let drawCount;let primitiveCount;function isWhite(c){return c.r>=1&&c.g>=1&&c.b>=1}function isBlack(c){return c.r<=0&&c.g<=0&&c.b<=0&&c.a<=0}function tile(index=0,size=tileDefaultSize,texture=0,padding=tileDefaultPadding,bleed=tileDefaultBleed){ASSERT(isVector2(index)||typeof index==="number","index must be a vec2 or number");ASSERT(isVector2(size)||typeof size==="number","size must be a vec2 or number");ASSERT(isNumber(texture)||texture instanceof TextureInfo,"texture must be a number or TextureInfo");ASSERT(isNumber(padding),"padding must be a number");if(headlessMode)return new TileInfo;if(typeof size==="number"){ASSERT(size>0);size=new Vector2(size,size)}const textureInfo=typeof texture==="number"?textureInfos[texture]:texture;ASSERT(textureInfo instanceof TextureInfo,"tile texture is not loaded");ASSERT(textureInfo.size.x>0,"tile texture is not loaded");const sizePaddedX=size.x+padding*2;const sizePaddedY=size.y+padding*2;let x,y;if(typeof index==="number"){const cols=textureInfo.size.x/sizePaddedX|0;x=index%cols;y=index/cols|0}else{x=index.x;y=index.y}const pos=new Vector2(x*sizePaddedX+padding,y*sizePaddedY+padding);return new TileInfo(pos,size,textureInfo,padding,bleed)}class TileInfo{constructor(pos=vec2(),size=tileDefaultSize,textureInfo=textureInfos[0],padding=tileDefaultPadding,bleed=tileDefaultBleed,columns=0){this.pos=pos.copy();this.size=size.copy();this.padding=padding;this.textureInfo=textureInfo;this.bleed=bleed;this.columns=columns}offset(offset){return new TileInfo(this.pos.add(offset),this.size,this.textureInfo,this.padding,this.bleed,this.columns)}frame(frame){ASSERT(typeof frame==="number");const w=this.size.x+this.padding*2;const h=this.size.y+this.padding*2;const x=(this.columns?frame%this.columns:frame)*w;const y=(this.columns?frame/this.columns|0:0)*h;ASSERT(this.pos.x+x+this.size.x<=this.textureInfo.size.x,"frame extends beyond texture width!");ASSERT(this.pos.y+y+this.size.y<=this.textureInfo.size.y,"frame extends beyond texture height!");return this.offset(new Vector2(x,y))}setColumns(columns=0){ASSERT(isNumber(columns)&&columns>=0,"columns must be a number >= 0");this.columns=columns;return this}index(index){return tile(index,this.size,this.textureInfo,this.padding,this.bleed).setColumns(this.columns)}setFullImage(textureInfo=this.textureInfo){this.textureInfo=textureInfo;this.pos=new Vector2;this.size=textureInfo.size.copy();this.bleed=this.padding=this.columns=0;return this}}class TextureInfo{constructor(image,useWebGL=true,wrap=false){this.image=image;this.size=image?vec2(image.width,image.height):vec2();this.sizeInverse=image?vec2(1/image.width,1/image.height):vec2();this.glTexture=undefined;this.wrap=wrap;useWebGL&&this.createWebGLTexture()}createWebGLTexture(){glRegisterTextureInfo(this)}destroyWebGLTexture(){glUnregisterTextureInfo(this)}hasWebGL(){return!!this.glTexture}setWrap(wrap=true){this.wrap=wrap;glSetTextureWrap(this.glTexture,wrap)}}class SpriteAnimation{constructor(tileInfo,frameCount,frameTime=.1){ASSERT(tileInfo instanceof TileInfo,"the first frame must be a TileInfo");ASSERT(frameCount>=1&&frameTime>0,"an animation needs at least one frame and a positive frame time");this.firstTile=tileInfo;this.frameCount=frameCount;this.frameTime=frameTime;this.speed=1;this.mode="loop";this.startTime=time;this.heldFrame=undefined}loop(){return this.restart("loop")}play(){return this.restart("once")}pingPong(){return this.restart("pingPong")}stop(){this.heldFrame=this.frame;return this}restart(mode=this.mode){this.mode=mode;this.startTime=time;this.heldFrame=undefined;return this}get elapsedFrames(){return(time-this.startTime)*this.speed/this.frameTime}get frame(){if(this.heldFrame!==undefined)return this.heldFrame;const n=this.frameCount,f=floor(this.elapsedFrames);if(this.mode=="once")return min(f,n-1);if(this.mode=="loop")return f%n;const period=max(2*n-2,1),k=f%period;return k<n?k:period-k}get tileInfo(){return this.firstTile.frame(this.frame)}get isDone(){return this.mode=="once"&&this.heldFrame===undefined&&this.elapsedFrames>=this.frameCount}}class Shader{constructor(fragmentCode){ASSERT(isStringLike(fragmentCode)&&String(fragmentCode).includes("mainImage"),"a Shader needs fragment code that defines mainImage");this.fragmentCode=String(fragmentCode);this.program=undefined;this.program3D=undefined;glShaderObjects.push(this)}}function drawTile(pos,size=vec2(1),tileInfo,color=WHITE,angle=0,mirror,additiveColor,useWebGL=glEnable,screenSpace=false,context){ASSERT(isVector2(pos),"pos must be a vec2");ASSERT(isVector2(size),"size must be a vec2");ASSERT(isColor(color),"color is invalid");ASSERT(isNumber(angle),"angle must be a number");ASSERT(!additiveColor||isColor(additiveColor),"additiveColor must be a color");ASSERT(!context||!useWebGL,"context only supported in canvas 2D mode");const textureInfo=tileInfo?.textureInfo;const bleed=tileInfo?.bleed??0;if(useWebGL&&glEnable){ASSERT(!!glContext,"WebGL is not enabled!");if(screenSpace)[pos,size,angle]=screenToWorldTransform(pos,size,angle);if(textureInfo){const sizeInverse=textureInfo.sizeInverse;const x=tileInfo.pos.x*sizeInverse.x;const y=tileInfo.pos.y*sizeInverse.y;const w=tileInfo.size.x*sizeInverse.x;const h=tileInfo.size.y*sizeInverse.y;glSetTexture(textureInfo.glTexture);if(bleed){const bleedX=sizeInverse.x*bleed;const bleedY=sizeInverse.y*bleed;glDraw(pos.x,pos.y,mirror?-size.x:size.x,size.y,angle,x+bleedX,y+bleedY,x-bleedX+w,y-bleedY+h,color.rgbaInt(),additiveColor&&additiveColor.rgbaInt())}else{glDraw(pos.x,pos.y,mirror?-size.x:size.x,size.y,angle,x,y,x+w,y+h,color.rgbaInt(),additiveColor&&additiveColor.rgbaInt())}}else{const combined=additiveColor?color.add(additiveColor):color;glDrawUntextured(pos.x,pos.y,size.x,size.y,angle,combined.rgbaInt())}}else{++drawCount;++primitiveCount;drawCanvas2D(pos,size,angle,mirror,context=>{if(textureInfo){context.scale(1,-1);const x=tileInfo.pos.x,y=tileInfo.pos.y;const w=tileInfo.size.x,h=tileInfo.size.y;drawImageColor(context,textureInfo.image,x,y,w,h,-.5,-.5,1,1,color,additiveColor,bleed)}else{const c=additiveColor?color.add(additiveColor):color;context.fillStyle=c.toString();context.fillRect(-.5,-.5,1,1)}},screenSpace,context)}}function drawRect(pos,size,color,angle,useWebGL,screenSpace,context){drawTile(pos,size,undefined,color,angle,false,undefined,useWebGL,screenSpace,context)}function drawRectGradient(pos,size,colorTop=WHITE,colorBottom=CLEAR_WHITE,angle=0,useWebGL=glEnable,screenSpace=false,context){ASSERT(isVector2(pos),"pos must be a vec2");ASSERT(isVector2(size),"size must be a vec2");ASSERT(isColor(colorTop)&&isColor(colorBottom),"color is invalid");ASSERT(isNumber(angle),"angle must be a number");ASSERT(!context||!useWebGL,"context only supported in canvas 2D mode");if(useWebGL&&glEnable){ASSERT(!!glContext,"WebGL is not enabled!");if(screenSpace){pos=screenToWorld(pos);size=size.scale(1/cameraScale);angle+=cameraAngle}const points=[],colors=[];const halfSizeX=size.x/2,halfSizeY=size.y/2;const colorTopInt=colorTop.rgbaInt();const colorBottomInt=colorBottom.rgbaInt();const c=cos(-angle),s=sin(-angle);for(let i=4;i--;){const x=i&1?halfSizeX:-halfSizeX;const y=i&2?halfSizeY:-halfSizeY;const rx=x*c-y*s;const ry=x*s+y*c;const color=i&2?colorTopInt:colorBottomInt;points.push(vec2(pos.x+rx,pos.y+ry));colors.push(color)}glDrawColoredPoints(points,colors)}else{++drawCount;++primitiveCount;drawCanvas2D(pos,size,angle,false,context=>{const gradient=context.createLinearGradient(0,.5,0,-.5);gradient.addColorStop(0,colorTop.toString());gradient.addColorStop(1,colorBottom.toString());context.fillStyle=gradient;context.fillRect(-.5,-.5,1,1)},screenSpace,context)}}function drawTextureWrapped(pos,size,wrapCount,texture=0,color=WHITE,angle=0,additiveColor,useWebGL=glEnable,screenSpace=false,context){ASSERT(isVector2(pos),"pos must be a vec2");ASSERT(isVector2(size),"size must be a vec2");ASSERT(isVector2(wrapCount),"wrapCount must be a vec2");ASSERT(isColor(color),"color is invalid");ASSERT(isNumber(angle),"angle must be a number");ASSERT(!additiveColor||isColor(additiveColor),"additiveColor must be a color");ASSERT(!context||!useWebGL,"context only supported in canvas 2D mode");ASSERT(!(texture instanceof TileInfo),"pass a TextureInfo or texture index, not a TileInfo — use tileInfo.textureInfo");if(headlessMode)return;const textureInfo=typeof texture==="number"?textureInfos[texture]:texture;ASSERT(textureInfo instanceof TextureInfo,"texture not loaded");ASSERT(textureInfo.size.x>0,"texture not loaded");ASSERT(textureInfo.wrap,"drawTextureWrapped requires a wrap-enabled texture; call textureInfo.setWrap(true) first");if(useWebGL&&glEnable){ASSERT(!!glContext,"WebGL is not enabled!");if(screenSpace)[pos,size,angle]=screenToWorldTransform(pos,size,angle);glSetTexture(textureInfo.glTexture);glDraw(pos.x,pos.y,size.x,size.y,angle,0,0,wrapCount.x,wrapCount.y,color.rgbaInt(),additiveColor&&additiveColor.rgbaInt());return}++drawCount;++primitiveCount;if(!screenSpace){pos=worldToScreen(pos);size=size.scale(cameraScale);angle-=cameraAngle}const noTint=!canvasColorTiles||(additiveColor?isWhite(color.add(additiveColor))&&additiveColor.a<=0:isWhite(color));const alphaBaked=!noTint&&additiveColor&&!isBlack(additiveColor);const source=noTint?textureInfo.image:bakeTintedImage(textureInfo.image,color,additiveColor);context=context||drawContext;context.save();context.translate(pos.x+.5,pos.y+.5);context.rotate(angle);context.globalAlpha=alphaBaked?1:color.a;const pattern=context.createPattern(source,"repeat");const m=(new DOMMatrix).translate(-size.x/2,-size.y/2).scale(size.x/(wrapCount.x*source.width),size.y/(wrapCount.y*source.height));pattern.setTransform(m);context.fillStyle=pattern;context.fillRect(-size.x/2,-size.y/2,size.x,size.y);context.globalAlpha=1;context.restore()}function drawLineList(points,width=.1,color=WHITE,wrap=false,pos=vec2(),angle=0,useWebGL=glEnable,screenSpace=false,context){ASSERT(isArray(points),"points must be an array");ASSERT(isNumber(width),"width must be a number");ASSERT(isColor(color),"color is invalid");ASSERT(isVector2(pos),"pos must be a vec2");ASSERT(isNumber(angle),"angle must be a number");ASSERT(!context||!useWebGL,"context only supported in canvas 2D mode");if(useWebGL&&glEnable){ASSERT(!!glContext,"WebGL is not enabled!");let size=vec2(1);if(screenSpace)[pos,size,angle]=screenToWorldTransform(pos,size,angle);glDrawOutlineTransform(points,color.rgbaInt(),width,pos.x,pos.y,size.x,size.y,angle,wrap)}else{++drawCount;++primitiveCount;drawCanvas2D(pos,vec2(1),angle,false,context=>{context.strokeStyle=color.toString();context.lineWidth=width;context.beginPath();for(let i=0;i<points.length;++i){const point=points[i];context.lineTo(point.x,point.y)}wrap&&context.closePath();context.stroke()},screenSpace,context)}}function drawLine(posA,posB,width=.1,color=WHITE,pos=vec2(),angle=0,useWebGL=glEnable,screenSpace=false,context){const halfDelta=vec2((posB.x-posA.x)/2,(posB.y-posA.y)/2);const size=vec2(width,halfDelta.length()*2);pos=pos.add(posA.add(halfDelta));if(screenSpace)halfDelta.y*=-1;angle+=halfDelta.angle();drawRect(pos,size,color,angle,useWebGL,screenSpace,context)}function drawRegularPoly(pos,size=vec2(1),sides=3,color=WHITE,lineWidth=0,lineColor=BLACK,angle=0,useWebGL=glEnable,screenSpace=false,context){ASSERT(isVector2(size),"size must be a vec2");ASSERT(isNumber(sides),"sides must be a number");const points=[];const sizeX=size.x/2,sizeY=size.y/2;for(let i=sides;i--;){const a=i/sides*PI*2;points.push(vec2(sin(a)*sizeX,cos(a)*sizeY))}drawPoly(points,color,lineWidth,lineColor,pos,angle,useWebGL,screenSpace,context)}function drawPoly(points,color=WHITE,lineWidth=0,lineColor=BLACK,pos=vec2(),angle=0,useWebGL=glEnable,screenSpace=false,context=undefined){ASSERT(isVector2(pos),"pos must be a vec2");ASSERT(isArray(points),"points must be an array");ASSERT(isColor(color)&&isColor(lineColor),"color is invalid");ASSERT(isNumber(lineWidth),"lineWidth must be a number");ASSERT(isNumber(angle),"angle must be a number");ASSERT(!context||!useWebGL,"context only supported in canvas 2D mode");if(useWebGL&&glEnable){ASSERT(!!glContext,"WebGL is not enabled!");let size=vec2(1);if(screenSpace)[pos,size,angle]=screenToWorldTransform(pos,size,angle);glDrawPointsTransform(points,color.rgbaInt(),pos.x,pos.y,size.x,size.y,angle);if(lineWidth>0)glDrawOutlineTransform(points,lineColor.rgbaInt(),lineWidth,pos.x,pos.y,size.x,size.y,angle)}else{drawCanvas2D(pos,vec2(1),angle,false,context=>{context.fillStyle=color.toString();context.beginPath();for(const point of points)context.lineTo(point.x,point.y);context.closePath();context.fill();if(lineWidth){context.strokeStyle=lineColor.toString();context.lineWidth=lineWidth;context.stroke()}},screenSpace,context)}}function drawEllipse(pos,size=vec2(1),color=WHITE,angle=0,lineWidth=0,lineColor=BLACK,useWebGL=glEnable,screenSpace=false,context){ASSERT(isVector2(pos),"pos must be a vec2");ASSERT(isVector2(size),"size must be a vec2");ASSERT(isColor(color)&&isColor(lineColor),"color is invalid");ASSERT(isNumber(angle),"angle must be a number");ASSERT(isNumber(lineWidth),"lineWidth must be a number");ASSERT(lineWidth>=0,"lineWidth must be a positive value or 0");ASSERT(!context||!useWebGL,"context only supported in canvas 2D mode");lineWidth=clamp(lineWidth,0,min(size.x,size.y));if(useWebGL&&glEnable){const sides=glCircleSides;drawRegularPoly(pos,size,sides,color,lineWidth,lineColor,angle,useWebGL,screenSpace,context)}else{drawCanvas2D(pos,vec2(1),angle,false,context=>{context.fillStyle=color.toString();context.beginPath();context.ellipse(0,0,size.x/2,size.y/2,0,0,9);context.fill();if(lineWidth){context.strokeStyle=lineColor.toString();context.lineWidth=lineWidth;context.stroke()}},screenSpace,context)}}function drawCircle(pos,size=1,color=WHITE,lineWidth=0,lineColor=BLACK,useWebGL=glEnable,screenSpace=false,context){ASSERT(isNumber(size),"size must be a number");drawEllipse(pos,vec2(size),color,0,lineWidth,lineColor,useWebGL,screenSpace,context)}let drawEllipseGradientOffset=0;function drawEllipseGradient(pos,size=vec2(1),colorInner=WHITE,colorOuter=CLEAR_WHITE,angle=0,useWebGL=glEnable,screenSpace=false,context){ASSERT(isVector2(pos),"pos must be a vec2");ASSERT(isVector2(size),"size must be a vec2");ASSERT(isColor(colorInner)&&isColor(colorOuter),"color is invalid");ASSERT(isNumber(angle),"angle must be a number");ASSERT(!context||!useWebGL,"context only supported in canvas 2D mode");if(headlessMode)return;if(useWebGL&&glEnable){ASSERT(!!glContext,"WebGL is not enabled!");if(screenSpace){pos=screenToWorld(pos);size=size.scale(1/cameraScale);angle+=cameraAngle}const sides=glCircleSides;const radiusX=size.x/2,radiusY=size.y/2;const innerInt=colorInner.rgbaInt();const outerInt=colorOuter.rgbaInt();const offset=drawEllipseGradientOffset++;const c=cos(-angle),s=sin(-angle);const rim=a=>{const lx=sin(a)*radiusX,ly=cos(a)*radiusY;return vec2(pos.x+lx*c-ly*s,pos.y+lx*s+ly*c)};const startA=offset%sides/sides*PI*2;const points=[rim(startA)];const colors=[outerInt];for(let i=sides;i--;){const a=(i+offset)%sides/sides*PI*2;points.push(pos);colors.push(innerInt);points.push(rim(a));colors.push(outerInt)}glDrawColoredPoints(points,colors)}else{++drawCount;++primitiveCount;drawCanvas2D(pos,size,angle,false,context=>{const gradient=context.createRadialGradient(0,0,0,0,0,.5);gradient.addColorStop(0,colorInner.toString());gradient.addColorStop(1,colorOuter.toString());context.fillStyle=gradient;context.beginPath();context.ellipse(0,0,.5,.5,0,0,9);context.fill()},screenSpace,context)}}function drawCircleGradient(pos,size=1,colorInner=WHITE,colorOuter=CLEAR_WHITE,useWebGL=glEnable,screenSpace=false,context){ASSERT(isNumber(size),"size must be a number");drawEllipseGradient(pos,vec2(size),colorInner,colorOuter,0,useWebGL,screenSpace,context)}function drawCanvas2D(pos,size,angle=0,mirror=false,drawFunction,screenSpace=false,context=drawContext){ASSERT(isVector2(pos),"pos must be a vec2");ASSERT(isVector2(size),"size must be a vec2");ASSERT(isNumber(angle),"angle must be a number");ASSERT(typeof drawFunction==="function","drawFunction must be a function");if(!screenSpace){pos=worldToScreen(pos);size=size.scale(cameraScale);angle-=cameraAngle}context.save();context.translate(pos.x+.5,pos.y+.5);context.rotate(angle);context.scale(mirror?-size.x:size.x,-size.y);drawFunction(context);context.restore()}function drawText(text,pos,size=1,color=WHITE,lineWidth=0,lineColor=BLACK,textAlign="center",font=fontDefault,fontStyle="",maxWidth,angle=0,context=drawContext){pos=worldToScreen(pos);size*=cameraScale;lineWidth*=cameraScale;angle-=cameraAngle;angle*=-1;drawTextScreen(text,pos,size,color,lineWidth,lineColor,textAlign,font,fontStyle,maxWidth,angle,context)}function drawTextScreen(text,pos,size,color=WHITE,lineWidth=0,lineColor=BLACK,textAlign="center",font=fontDefault,fontStyle="",maxWidth,angle=0,context=drawContext){ASSERT(isStringLike(text),"text must be a string");ASSERT(isVector2(pos),"pos must be a vec2");ASSERT(isNumber(size),"size must be a number");ASSERT(isColor(color),"color must be a color");ASSERT(isNumber(lineWidth),"lineWidth must be a number");ASSERT(isColor(lineColor),"lineColor must be a color");ASSERT(["left","center","right"].includes(textAlign),"align must be left, center, or right");ASSERT(isStringLike(font),"font must be a string");ASSERT(isStringLike(fontStyle),"fontStyle must be a string");ASSERT(isNumber(angle),"angle must be a number");const lines=(text+"").split("\n");const posY=pos.y-(lines.length-1)*size/2;context.save();context.fillStyle=color.toString();context.strokeStyle=lineColor.toString();context.lineWidth=lineWidth;context.textAlign=textAlign;context.font=fontStyle+" "+size+"px "+font;context.textBaseline="middle";context.translate(pos.x,posY);context.rotate(-angle);let yOffset=0;lines.forEach(line=>{lineWidth&&context.strokeText(line,0,yOffset,maxWidth);context.fillText(line,0,yOffset,maxWidth);yOffset+=size});context.restore()}async function loadTexture(textureIndex,src){ASSERT(isNumber(textureIndex),"textureIndex must be a number");ASSERT(!textureInfos[textureIndex],"textureIndex is already loaded!");ASSERT(!src||isStringLike(src),"image src must be a string");const image=new Image;if(src){await new Promise(resolve=>{image.onerror=image.onload=resolve;image.crossOrigin="anonymous";image.src=src})}textureInfos[textureIndex]=new TextureInfo(image)}function screenToWorld(screenPos){ASSERT(isVector2(screenPos),"screenPos must be a vec2");let x=(screenPos.x-mainCanvasSize.x/2+.5)/cameraScale;let y=(screenPos.y-mainCanvasSize.y/2+.5)/-cameraScale;if(cameraAngle){const c=cos(-cameraAngle),s=sin(-cameraAngle);const xr=x*c-y*s,yr=x*s+y*c;x=xr;y=yr}return new Vector2(x+cameraPos.x,y+cameraPos.y)}function worldToScreen(worldPos){ASSERT(isVector2(worldPos),"worldPos must be a vec2");let x=worldPos.x-cameraPos.x;let y=worldPos.y-cameraPos.y;if(cameraAngle){const c=cos(cameraAngle),s=sin(cameraAngle);const xr=x*c-y*s,yr=x*s+y*c;x=xr;y=yr}return new Vector2(x*cameraScale+mainCanvasSize.x/2-.5,y*-cameraScale+mainCanvasSize.y/2-.5)}function screenToWorldDelta(screenDelta){ASSERT(isVector2(screenDelta),"screenDelta must be a vec2");let x=screenDelta.x/cameraScale;let y=screenDelta.y/-cameraScale;if(cameraAngle){const c=cos(-cameraAngle),s=sin(-cameraAngle);const xr=x*c-y*s,yr=x*s+y*c;x=xr;y=yr}return new Vector2(x,y)}function worldToScreenDelta(worldDelta){ASSERT(isVector2(worldDelta),"worldDelta must be a vec2");let x=worldDelta.x;let y=worldDelta.y;if(cameraAngle){const c=cos(cameraAngle),s=sin(cameraAngle);const xr=x*c-y*s,yr=x*s+y*c;x=xr;y=yr}return new Vector2(x*cameraScale,y*-cameraScale)}function screenToWorldTransform(screenPos,screenSize,screenAngle=0){ASSERT(isVector2(screenPos),"screenPos must be a vec2");ASSERT(isVector2(screenSize),"screenSize must be a vec2");ASSERT(isNumber(screenAngle),"screenAngle must be a number");return[screenToWorld(screenPos),screenSize.scale(1/cameraScale),screenAngle+cameraAngle]}function getCameraSize(){return mainCanvasSize.scale(1/cameraScale)}function cameraFit(center,size,worldMargin,screenInset){ASSERT(isVector2(center),"center must be a vec2");ASSERT(isVector2(size),"size must be a vec2");const margin=padSides(worldMargin);const inset=padSides(screenInset);const worldW=size.x+margin.left+margin.right;const worldH=size.y+margin.top+margin.bottom;const viewW=mainCanvasSize.x-inset.left-inset.right;const viewH=mainCanvasSize.y-inset.top-inset.bottom;if(!(worldW>0&&worldH>0&&viewW>0&&viewH>0))return cameraScale;cameraScale=min(viewW/worldW,viewH/worldH);const marginVector=vec2(margin.right-margin.left,margin.top-margin.bottom).scale(.5);const insetVector=vec2(inset.right-inset.left,inset.top-inset.bottom).scale(.5/cameraScale);cameraPos=center.add(marginVector).add(insetVector);return cameraScale;function padSides(p){if(p===undefined||isNumber(p))p=vec2(p);if(isVector2(p))return{top:p.y,right:p.x,bottom:p.y,left:p.x};return{top:p.top||0,right:p.right||0,bottom:p.bottom||0,left:p.left||0}}}function isOnScreen(pos,size=0){ASSERT(isVector2(pos),"pos must be a vec2");ASSERT(isVector2(size)||isNumber(size),"size must be a vec2 or number");if(!cameraScale)return false;let x=pos.x-cameraPos.x;let y=pos.y-cameraPos.y;if(cameraAngle){const c=cos(cameraAngle),s=sin(cameraAngle);const xr=x*c-y*s,yr=x*s+y*c;x=xr;y=yr}x*=cameraScale*2;y*=-cameraScale*2;if(size instanceof Vector2)size=size.length();size*=cameraScale;const w=mainCanvasSize.x,h=mainCanvasSize.y;return x+size>-w&&x-size<w&&y+size>-h&&y-size<h}function setAdditiveBlendMode(additive=true){glAdditive=additive;drawContext.globalCompositeOperation=additive?"lighter":"source-over"}function setShader(shader){ASSERT(!shader||shader instanceof Shader,"shader must be a Shader");glCustomShader=shader||undefined}function setBackgroundCanvas(canvas){backgroundCanvas=canvas}function combineCanvases(){const w=mainCanvas.width,h=mainCanvas.height;workCanvas.width=w;workCanvas.height=h;workContext.fillStyle="#000";workContext.fillRect(0,0,w,h);if(backgroundCanvas)workContext.drawImage(backgroundCanvas,0,0,w,h);glCopyToContext(workContext);workContext.drawImage(mainCanvas,0,0);mainContext.save();mainContext.setTransform(1,0,0,1,0,0);mainContext.drawImage(workCanvas,0,0);mainContext.restore()}function bakeTintedImage(image,color,additiveColor){const w=image.width|0,h=image.height|0;workReadCanvas.width=w;workReadCanvas.height=h;workReadContext.drawImage(image,0,0);const imageData=workReadContext.getImageData(0,0,w,h);const data=imageData.data;if(additiveColor&&!isBlack(additiveColor)){const colorMultiply=[color.r,color.g,color.b,color.a];const colorAdd=[additiveColor.r*255,additiveColor.g*255,additiveColor.b*255,additiveColor.a*255];for(let i=0;i<data.length;++i)data[i]=data[i]*colorMultiply[i&3]+colorAdd[i&3]|0}else{for(let i=0;i<data.length;i+=4){data[i]*=color.r;data[i+1]*=color.g;data[i+2]*=color.b}}workReadContext.putImageData(imageData,0,0);return workReadCanvas}function drawImageColor(context,image,sx,sy,sWidth,sHeight,dx,dy,dWidth,dHeight,color,additiveColor,bleed=0){const sx2=bleed;const sy2=bleed;sWidth=max(1,sWidth|0);sHeight=max(1,sHeight|0);const sWidth2=sWidth-2*bleed;const sHeight2=sHeight-2*bleed;if(!canvasColorTiles||(additiveColor?isWhite(color.add(additiveColor))&&additiveColor.a<=0:isWhite(color))){context.globalAlpha=color.a;context.drawImage(image,sx+sx2,sy+sy2,sWidth2,sHeight2,dx,dy,dWidth,dHeight);context.globalAlpha=1}else{workReadCanvas.width=sWidth;workReadCanvas.height=sHeight;workReadContext.drawImage(image,sx|0,sy|0,sWidth,sHeight,0,0,sWidth,sHeight);const imageData=workReadContext.getImageData(0,0,sWidth,sHeight);const data=imageData.data;if(additiveColor&&!isBlack(additiveColor)){const colorMultiply=[color.r,color.g,color.b,color.a];const colorAdd=[additiveColor.r*255,additiveColor.g*255,additiveColor.b*255,additiveColor.a*255];for(let i=0;i<data.length;++i)data[i]=data[i]*colorMultiply[i&3]+colorAdd[i&3]|0;workReadContext.putImageData(imageData,0,0);context.drawImage(workReadCanvas,sx2,sy2,sWidth2,sHeight2,dx,dy,dWidth,dHeight)}else{for(let i=0;i<data.length;i+=4){data[i]*=color.r;data[i+1]*=color.g;data[i+2]*=color.b}workReadContext.putImageData(imageData,0,0);context.globalAlpha=color.a;context.drawImage(workReadCanvas,sx2,sy2,sWidth2,sHeight2,dx,dy,dWidth,dHeight);context.globalAlpha=1}}}function isFullscreen(){return!!document.fullscreenElement}function toggleFullscreen(){const rootElement=mainCanvas.parentElement;if(isFullscreen()){if(document.exitFullscreen)document.exitFullscreen()}else if(rootElement.requestFullscreen)rootElement.requestFullscreen()}function setCursor(cursorStyle="auto"){const rootElement=mainCanvas.parentElement;rootElement.style.cursor=cursorStyle}let engineImageFont;class ImageFont{constructor(tileInfo){ASSERT(!!tileInfo,"tileInfo is required for ImageFont");this.tileInfo=tileInfo.frame(0)}drawText(text,pos,size=1,center,color,useWebGL,context){ASSERT(isVector2(size)||typeof size==="number","size must be a vec2 or number");if(typeof size==="number"){ASSERT(size>0);size*=cameraScale;size=new Vector2(size,size)}else size=size.scale(cameraScale);this.drawTextScreen(text,worldToScreen(pos),size,center,color,useWebGL,context)}drawTextScreen(text,pos,size,center=true,color=WHITE,useWebGL=glEnable,context){ASSERT(isStringLike(text),"text must be a string");ASSERT(isVector2(pos),"pos must be a vec2");ASSERT(isVector2(size)||typeof size==="number","size must be a vec2 or number");ASSERT(isColor(color),"color must be a color");size=typeof size==="number"?new Vector2(size,size):size;const drawPos=new Vector2;const tileInfo=this.tileInfo;const padding=tileInfo.padding;const sizePaddedX=tileInfo.size.x+padding*2;const sizePaddedY=tileInfo.size.y+padding*2;const cols=tileInfo.textureInfo.size.x/sizePaddedX|0;(text+"").split("\n").forEach((line,j)=>{const centerOffset=center?(line.length-1)*size.x/2:0;for(let i=line.length;i--;){const charCode=line.charCodeAt(i);const index=charCode<32||charCode>127?95:charCode-32;const x=index%cols;const y=index/cols|0;tileInfo.pos.x=x*sizePaddedX+padding;tileInfo.pos.y=y*sizePaddedY+padding;drawPos.x=ceil(pos.x+i*size.x-centerOffset-size.x/2)+size.x/2-.5;drawPos.y=ceil(pos.y+j*size.y-size.y/2)+size.y/2-.5;drawTile(drawPos,size,tileInfo,color,0,false,undefined,useWebGL,true,context)}})}}async function imageFontInit(){const image=new Image;await new Promise(resolve=>{image.onerror=image.onload=resolve;image.crossOrigin="anonymous";image.src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAUAAAAAeAQMAAABnrVXaAAAABlBMVEUAAAD///+l2Z/dAAAAAXRSTlMAQObYZgAAAjpJREFUOMu9kzFu2zAUhn+CAROgqrk+B2l0BWYxMjlXeYaAtFtbdA1sGgHqRQfI0CNkSG5AwYB0BQ8d5Bsomwah6CPVeGg6tEPzAxLwyI+P78cP4u9lNO9OoMKnLMOobG5020/yaj/MrRcCGh1gBbyiLTPJEYaIiom5KM9Jq7KgynMGtb6L4GL4MF2H4LQKCXTvDVw2I4MsgZT7QLExdiutH+D08VOP3INXRrWX1/mmpbkNgAPYRVANb4xpcegYvhiNbIXauQICEjBuYLfMakaakWQeXxiZ0VDtuJCKs3ztMV59QtsHJNcRxDzfdL21ty3PrfIcXTN+E+GFAv6T5nbT9jd50/WFxb5ksdAv49qS6ouymG66ji08UMT6moykYLAo+V0j23GN4m829ZySAD5K7QsBfQTvOG8eE+gTeGYRAmnNAubN3hf5Zv9tJWDHp/VTuaSm7SN4fyINQqaNO3RMVxvpSPXnOChnRNvFcGY0gnwiPswYwTKVPE0zVtX3mTEIOoFzaqLrGuJaV+Uqumb71fVk/VoOH3cdLNQP/FHi8hV0CQNoqBZsUPlLPMsdCJro9QAaQQ0woDy9BJm0eTxCFnO9srcYlhNVlfR2EyTrph1uUtbUtAJifwRgrKuYdXVHeb0YI3QpawohQHkloI3J5FuVwI5ORxC9k2Tuz9Ir1IjgeIPGMHYkAZe2RuYkmWFmt3gGbTPOmBUWVTmRmHtGrfpzG/yuQNOKa6gBB/WA9khitPgl6/GP+gl2Af6tCbvaygAAAABJRU5ErkJggg=="});const tilePos=vec2(),tileSize=vec2(8),padding=1,bleed=0;const textureInfo=new TextureInfo(image);const tileInfo=new TileInfo(tilePos,tileSize,textureInfo,padding,bleed);engineImageFont=new ImageFont(tileInfo)}let mousePos=vec2();let mousePosScreen=vec2();let mouseDelta=vec2();let mouseDeltaScreen=vec2();let mouseWheel=0;let mouseInWindow=true;let isUsingGamepad=false;let lastInputDevice="mouse";let inputMouseMoveThreshold=6;let inputPreventDefault=true;let gamepadPrimary=0;const isTouchDevice=!headlessMode&&window.ontouchstart!==undefined;function setInputPreventDefault(preventDefault=true){inputPreventDefault=preventDefault}function setInputMouseMoveThreshold(threshold){inputMouseMoveThreshold=threshold}function usingMouseInput(){return lastInputDevice==="mouse"}function usingKeyboardInput(){return lastInputDevice==="keyboard"}function usingGamepadInput(){return lastInputDevice==="gamepad"}function inputClearKey(key,device=0,clearDown=true,clearPressed=true,clearReleased=true){if(!inputData[device])return;inputData[device][key]&=~((clearDown?1:0)|(clearPressed?2:0)|(clearReleased?4:0))}function inputClear(){inputData.length=0;inputData[0]=[];touchGamepadButtons.length=0;touchGamepadSticks.length=0;touchGamepadStickPointerId.length=0;gamepadStickData.length=0;gamepadDpadData.length=0;gamepadAxisCentered.length=0}function keyIsDown(key,device=0){ASSERT(isStringLike(key),"key must be a number or string");ASSERT(device>0||typeof key!=="number"||key<3,"use code string for keyboard");return!!(inputData[device]?.[key]&1)}function keyWasPressed(key,device=0){ASSERT(isStringLike(key),"key must be a number or string");ASSERT(device>0||typeof key!=="number"||key<3,"use code string for keyboard");return!!(inputData[device]?.[key]&2)}function keyWasReleased(key,device=0){ASSERT(isStringLike(key),"key must be a number or string");ASSERT(device>0||typeof key!=="number"||key<3,"use code string for keyboard");return!!(inputData[device]?.[key]&4)}function keyDirection(up="ArrowUp",down="ArrowDown",left="ArrowLeft",right="ArrowRight"){ASSERT(isStringLike(up),"up key must be a string");ASSERT(isStringLike(down),"down key must be a string");ASSERT(isStringLike(left),"left key must be a string");ASSERT(isStringLike(right),"right key must be a string");const k=key=>keyIsDown(key)?1:0;return vec2(k(right)-k(left),k(up)-k(down))}function mouseIsDown(button){ASSERT(isNumber(button),"mouse button must be a number");return keyIsDown(button)}function mouseWasPressed(button){ASSERT(isNumber(button),"mouse button must be a number");return keyWasPressed(button)}function mouseWasReleased(button){ASSERT(isNumber(button),"mouse button must be a number");return keyWasReleased(button)}function gamepadIsDown(button,gamepad=gamepadPrimary){ASSERT(isNumber(button),"button must be a number");ASSERT(isNumber(gamepad),"gamepad must be a number");return keyIsDown(button,gamepad+1)}function gamepadWasPressed(button,gamepad=gamepadPrimary){ASSERT(isNumber(button),"button must be a number");ASSERT(isNumber(gamepad),"gamepad must be a number");return keyWasPressed(button,gamepad+1)}function gamepadWasReleased(button,gamepad=gamepadPrimary){ASSERT(isNumber(button),"button must be a number");ASSERT(isNumber(gamepad),"gamepad must be a number");return keyWasReleased(button,gamepad+1)}function gamepadStick(stick,gamepad=gamepadPrimary){ASSERT(isNumber(stick),"stick must be a number");ASSERT(isNumber(gamepad),"gamepad must be a number");return gamepadStickData[gamepad]?.[stick]??vec2()}function gamepadDpad(gamepad=gamepadPrimary){ASSERT(isNumber(gamepad),"gamepad must be a number");return gamepadDpadData[gamepad]??vec2()}function gamepadConnected(gamepad=gamepadPrimary){ASSERT(isNumber(gamepad),"gamepad must be a number");return!!inputData[gamepad+1]}function gamepadStickCount(gamepad=gamepadPrimary){ASSERT(isNumber(gamepad),"gamepad must be a number");return gamepadStickData[gamepad]?.length??0}function gamepadVibrate(gamepad=gamepadPrimary,duration=200,strongMagnitude=1,weakMagnitude=1,startDelay=0){ASSERT(isNumber(gamepad),"gamepad must be a number");if(!vibrateEnable||headlessMode)return;const pad=navigator?.getGamepads?.()[gamepad];pad?.vibrationActuator?.playEffect?.("dual-rumble",{duration:duration,strongMagnitude:strongMagnitude,weakMagnitude:weakMagnitude,startDelay:startDelay})}function gamepadVibrateStop(gamepad=gamepadPrimary){ASSERT(isNumber(gamepad),"gamepad must be a number");if(!vibrateEnable||headlessMode)return;const pad=navigator?.getGamepads?.()[gamepad];pad?.vibrationActuator?.reset?.()}function vibrate(pattern=100){ASSERT(isNumber(pattern)||isArray(pattern),"pattern must be a number or array");vibrateEnable&&!headlessMode&&navigator?.vibrate?.(pattern)}function vibrateStop(){vibrate(0)}function pointerLockRequest(){!isTouchDevice&&mainCanvas.requestPointerLock?.()}function pointerLockExit(){document.exitPointerLock?.()}function pointerLockIsActive(){return document.pointerLockElement===mainCanvas}const inputData=[[]];const gamepadStickData=[],gamepadDpadData=[],gamepadHadInput=[];const gamepadAxisCentered=[];const gamepadAxisCenteredFrames=15;const touchGamepadTimer=new Timer,touchGamepadButtons=[],touchGamepadSticks=[];const touchGamepadStickAnchors=[],touchGamepadStickPointerId=[];const touchGamepadPointerRole=new Map;let touchGamepadOverlay,touchGamepadStage,touchGamepadSvg,touchGamepadSvgEls;let touchGamepadSideZones=[],touchGamepadZoneC;let touchGamepadNeedRelayout=true,touchGamepadLastLayout;function inputInit(){if(headlessMode)return;document.addEventListener("keydown",onKeyDown);document.addEventListener("keyup",onKeyUp);document.addEventListener("mousedown",onMouseDown);document.addEventListener("mouseup",onMouseUp);document.addEventListener("mousemove",onMouseMove);document.addEventListener("mouseleave",onMouseLeave);document.addEventListener("wheel",onMouseWheel,{passive:false});document.addEventListener("contextmenu",onContextMenu);document.addEventListener("blur",onBlur);if(isTouchDevice&&touchInputEnable)touchInputInit();function onKeyDown(e){if(!e.repeat){inputData[0][e.code]=3;if(inputWASDEmulateDirection)inputData[0][remapKey(e.code)]=3}if(!inputPreventDefault||!e.cancelable||!document.hasFocus())return;if(e.ctrlKey||e.metaKey||e.altKey)return;if(isTextInput(e.target)||isTextInput(document.activeElement))return;const printable=typeof e.key==="string"&&e.key.length===1;const preventDefaultKeys=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Space","Tab","Backspace"];if(preventDefaultKeys.includes(e.code)||printable)e.preventDefault();function isTextInput(element){const tag=element?.tagName;const editable=element?.isContentEditable;return editable||["INPUT","TEXTAREA","SELECT"].includes(tag)}}function onKeyUp(e){inputData[0][e.code]=inputData[0][e.code]&2|4;if(inputWASDEmulateDirection){const remap=remapKey(e.code);inputData[0][remap]=inputData[0][remap]&2|4}}function remapKey(k){return inputWASDEmulateDirection?k==="KeyW"?"ArrowUp":k==="KeyS"?"ArrowDown":k==="KeyA"?"ArrowLeft":k==="KeyD"?"ArrowRight":k:k}function onMouseDown(e){if(isTouchDevice&&touchInputEnable)return;if(soundEnable&&!headlessMode&&audioContext&&!audioIsRunning())audioContext.resume();inputData[0][e.button]=3;const mousePosScreenLast=mousePosScreen;mousePosScreen=mouseEventToScreen(vec2(e.x,e.y));mouseDeltaScreen=mouseDeltaScreen.add(mousePosScreen.subtract(mousePosScreenLast));if(inputPreventDefault&&e.cancelable&&document.hasFocus())e.preventDefault()}function onMouseUp(e){if(isTouchDevice&&touchInputEnable)return;inputData[0][e.button]=inputData[0][e.button]&2|4}function onMouseMove(e){mouseInWindow=true;const mousePosScreenLast=mousePosScreen;mousePosScreen=mouseEventToScreen(vec2(e.x,e.y));const movement=pointerLockIsActive()?vec2(e.movementX,e.movementY):mousePosScreen.subtract(mousePosScreenLast);mouseDeltaScreen=mouseDeltaScreen.add(movement)}function onMouseLeave(){mouseInWindow=false}function onMouseWheel(e){if(!e.ctrlKey)mouseWheel+=sign(e.deltaY);if(inputPreventDefault&&e.cancelable&&document.hasFocus())e.preventDefault()}function onContextMenu(e){e.preventDefault()}function onBlur(){inputClear();touchGamepadPointerRole.clear();touchGamepadButtons.length=0;touchGamepadSticks.length=0;touchGamepadStickPointerId.length=0}function touchInputInit(){document.addEventListener("touchstart",e=>handleTouch(e),{passive:false});document.addEventListener("touchmove",e=>handleTouch(e),{passive:false});document.addEventListener("touchend",e=>handleTouch(e),{passive:false});let wasTouching,touchIdentifier;function handleTouch(e){if(!touchInputEnable)return;if(soundEnable&&!headlessMode&&audioContext&&!audioIsRunning())audioContext.resume();if(!touchGamepadEnable||touchGamepadPassthrough){const isGamepadTouch=t=>touchGamepadSideZones.includes(t.target)||t.target===touchGamepadZoneC;const gameTouches=[];for(const t of e.touches)if(!isGamepadTouch(t))gameTouches.push(t);const touching=gameTouches.length;const button=0;if(touching){const pos=vec2(gameTouches[0].clientX,gameTouches[0].clientY);const mousePosScreenLast=mousePosScreen;mousePosScreen=mouseEventToScreen(pos);if(wasTouching&&gameTouches[0].identifier===touchIdentifier)mouseDeltaScreen=mouseDeltaScreen.add(mousePosScreen.subtract(mousePosScreenLast));else if(!wasTouching)inputData[0][button]=3;touchIdentifier=gameTouches[0].identifier}else if(wasTouching)inputData[0][button]=inputData[0][button]&2|4;wasTouching=touching}if(inputPreventDefault&&e.cancelable&&document.hasFocus())e.preventDefault();return true}}function mouseEventToScreen(mousePos){const rect=mainCanvas.getBoundingClientRect();const px=percent(mousePos.x,rect.left,rect.right);const py=percent(mousePos.y,rect.top,rect.bottom);return vec2(px*mainCanvasSize.x,py*mainCanvasSize.y)}}function inputUpdate(){if(headlessMode)return;if(!(touchInputEnable&&isTouchDevice)&&!document.hasFocus())inputClear();mousePos=screenToWorld(mousePosScreen);mouseDelta=screenToWorldDelta(mouseDeltaScreen);touchGamepadInit();gamepadsUpdate();updateLastInputDevice();function updateLastInputDevice(){const mouseActive=mouseIsDown(0)||mouseIsDown(1)||mouseIsDown(2)||mouseDeltaScreen.length()>inputMouseMoveThreshold;let gamepadActive=false;for(let s=gamepadStickCount();s--&&!gamepadActive;)gamepadActive=gamepadStick(s).lengthSquared()>.2;for(let b=17;b--&&!gamepadActive;)gamepadActive=gamepadIsDown(b);let keyboardActive=false;for(const k in inputData[0])if(isNaN(+k)&&inputData[0][k]&1){keyboardActive=true;break}if(gamepadActive)lastInputDevice="gamepad";else if(mouseActive)lastInputDevice="mouse";else if(keyboardActive)lastInputDevice="keyboard";isUsingGamepad=lastInputDevice==="gamepad"}function gamepadsUpdate(){const deadZoneMin=.3,deadZoneMax=.8;const applyDeadZones=v=>{const deadZone=v=>v>deadZoneMin?percent(v,deadZoneMin,deadZoneMax):v<-deadZoneMin?-percent(-v,deadZoneMin,deadZoneMax):0;return vec2(deadZone(v.x),deadZone(-v.y)).clampLength()};if(touchGamepadEnable&&isTouchDevice){ASSERT(!touchGamepadLeftStick||!touchGamepadLeftButtonCount,"set touchGamepadLeftStick or touchGamepadLeftButtonCount, not both");ASSERT(!touchGamepadRightStick||!touchGamepadButtonCount,"set touchGamepadRightStick or touchGamepadButtonCount, not both");if(!touchGamepadTimer.isSet())return;gamepadPrimary=0;const sticks=gamepadStickData[0]??(gamepadStickData[0]=[]);const dpad=gamepadDpadData[0]??(gamepadDpadData[0]=vec2());sticks.length=0;dpad.set();for(let side=0;side<2;side++){if(!touchGamepadSideStick(side))continue;const out=touchGamepadStickOut(side);sticks[out]=vec2();const touchStick=touchGamepadSticks[side]??vec2();if(touchGamepadAnalog)sticks[out]=applyDeadZones(touchStick);else if(touchStick.lengthSquared()>.3){const x=clamp(round(touchStick.x),-1,1);const y=clamp(round(touchStick.y),-1,1);sticks[out]=vec2(x,-y).clampLength();if(!out)dpad.set(x,-y)}}const data=inputData[1]??(inputData[1]=[]);for(let i=12;i--;){const wasDown=gamepadIsDown(i,0);data[i]=touchGamepadButtons[i]?wasDown?1:3:wasDown?4:0;if(touchGamepadVibration&&data[i]===3&&(i===9||touchGamepadIsFaceButton(i)))vibrate(touchGamepadVibration)}return}try{if(!gamepadsEnable||!navigator?.getGamepads)return}catch(e){return}if(!debug&&!document.hasFocus())return;const maxGamepads=8;const gamepads=navigator.getGamepads();const gamepadCount=min(maxGamepads,gamepads.length);for(let i=0;i<gamepadCount;++i){const gamepad=gamepads[i];if(!gamepad){inputData[i+1]=undefined;gamepadStickData[i]=undefined;gamepadDpadData[i]=undefined;gamepadHadInput[i]=undefined;gamepadAxisCentered[i]=undefined;continue}const data=inputData[i+1]??(inputData[i+1]=[]);const sticks=gamepadStickData[i]??(gamepadStickData[i]=[]);const dpad=gamepadDpadData[i]??(gamepadDpadData[i]=vec2());const isStandard=gamepad.mapping==="standard";const centered=gamepadAxisCentered[i]??(gamepadAxisCentered[i]=[]);const readAxis=j=>{const v=gamepad.axes[j];if(isStandard&&j<4)return v;if(!gamepadAxisFilterEnable)return v;const frames=centered[j]|0;if(frames>gamepadAxisCenteredFrames)return v;centered[j]=abs(v)<deadZoneMin?frames+1:0;return 0};for(let j=0;j<gamepad.axes.length-1;j+=2)sticks[j>>1]=applyDeadZones(vec2(readAxis(j),readAxis(j+1)));let hadInput=false;for(let j=gamepad.buttons.length;j--;){const button=gamepad.buttons[j];const wasDown=gamepadIsDown(j,i);data[j]=button.pressed?wasDown?1:3:wasDown?4:0;if(button.pressed&&(!button.value||button.value>.9))hadInput=true}if(hadInput){gamepadHadInput[i]=true;if(!gamepadHadInput[gamepadPrimary])gamepadPrimary=i}if(gamepad.mapping==="standard"){dpad.set((gamepadIsDown(15,i)&&1)-(gamepadIsDown(14,i)&&1),(gamepadIsDown(12,i)&&1)-(gamepadIsDown(13,i)&&1))}if(gamepadDirectionEmulateStick&&(dpad.x||dpad.y))sticks[0]=dpad.clampLength()}touchGamepadEnable&&isUsingGamepad&&touchGamepadTimer.unset()}}function inputUpdatePost(){if(headlessMode)return;for(const deviceInputData of inputData)for(const i in deviceInputData)deviceInputData[i]&=1;mouseWheel=0;mouseDelta=vec2();mouseDeltaScreen=vec2()}function inputRender(){touchGamepadRender()}const touchGamepadSvgNS="http://www.w3.org/2000/svg";function touchGamepadInit(){if(touchGamepadOverlay||!touchGamepadEnable||!isTouchDevice||headlessMode||!document.body)return;const overlay=touchGamepadOverlay=document.createElement("div");overlay.style.cssText="position:fixed;inset:0;z-index:50;pointer-events:none;opacity:0;"+"touch-action:none;user-select:none;-webkit-user-select:none;"+"-webkit-touch-callout:none;transition:opacity .2s;box-sizing:border-box;"+"padding:env(safe-area-inset-top) env(safe-area-inset-right) "+"env(safe-area-inset-bottom) env(safe-area-inset-left)";const stage=touchGamepadStage=document.createElement("div");stage.style.cssText="position:relative;width:100%;height:100%;pointer-events:none";overlay.appendChild(stage);const svg=touchGamepadSvg=document.createElementNS(touchGamepadSvgNS,"svg");svg.style.cssText="position:absolute;inset:0;width:100%;height:100%;"+"pointer-events:none;overflow:visible;fill:none;stroke:#fff;stroke-width:3";stage.appendChild(svg);const makeZone=()=>{const z=document.createElement("div");z.style.cssText="position:absolute;pointer-events:auto;touch-action:none";z.addEventListener("pointerdown",e=>touchGamepadPointerDown(e,z));z.addEventListener("pointermove",e=>touchGamepadPointerMove(e));z.addEventListener("pointerup",e=>touchGamepadPointerUp(e));z.addEventListener("pointercancel",e=>touchGamepadPointerUp(e));stage.appendChild(z);return z};touchGamepadSideZones[0]=makeZone();touchGamepadSideZones[1]=makeZone();touchGamepadZoneC=makeZone();addEventListener("resize",()=>touchGamepadNeedRelayout=true);document.body.appendChild(overlay);touchGamepadNeedRelayout=true}function touchGamepadStageRect(){return touchGamepadStage.getBoundingClientRect()}function touchGamepadSideStick(side){return side?touchGamepadRightStick:touchGamepadLeftStick}function touchGamepadSideButtonCount(side){return side?touchGamepadButtonCount:touchGamepadLeftButtonCount}function touchGamepadSideButtonBase(side){return side?0:4}function touchGamepadStickOut(side){return side&&touchGamepadLeftStick?1:0}function touchGamepadSideHasControl(side){return touchGamepadSideStick(side)||touchGamepadSideButtonCount(side)>0}function touchGamepadIsFaceButton(i){for(let side=0;side<2;side++){const base=touchGamepadSideButtonBase(side);if(!touchGamepadSideStick(side)&&i>=base&&i<base+touchGamepadSideButtonCount(side))return true}return false}function touchGamepadSideCenter(side,W,H){if(touchGamepadFloating&&touchGamepadSideStick(side)&&touchGamepadStickAnchors[side])return touchGamepadStickAnchors[side];let y=H-touchGamepadSize;const count=touchGamepadSideButtonCount(side);if(!touchGamepadSideStick(side)&&(count===2||count===3))y-=touchGamepadSize/4;return vec2(side?W-touchGamepadSize:touchGamepadSize,y)}function touchGamepadRelayout(){if(!touchGamepadOverlay)return;const r=touchGamepadStageRect();const W=r.width,H=r.height,S=touchGamepadSize;const setZone=(z,css)=>z.style.cssText="position:absolute;pointer-events:auto;touch-action:none;"+css;if(paused){for(const zone of touchGamepadSideZones)zone.style.display="none";if(touchGamepadCenterButtonSize){setZone(touchGamepadZoneC,"inset:0");touchGamepadZoneC.style.display=""}else touchGamepadZoneC.style.display="none"}else{for(let side=0;side<2;side++){const zone=touchGamepadSideZones[side],edge=side?"right":"left";zone.style.display=touchGamepadSideHasControl(side)?"":"none";if(touchGamepadFloating){const width=touchGamepadSideHasControl(side?0:1)?"50%":"100%";setZone(zone,`${edge}:0;bottom:0;width:${width};height:60%`)}else setZone(zone,`${edge}:0;bottom:0;width:${3*S}px;height:${3*S}px`)}touchGamepadZoneC.style.display=touchGamepadCenterButtonSize?"":"none";const c=touchGamepadCenterButtonSize;setZone(touchGamepadZoneC,`left:50%;top:50%;width:${2*c}px;height:${2*c}px;transform:translate(-50%,-50%)`)}touchGamepadBuildSvg(W,H);touchGamepadNeedRelayout=false}function touchGamepadBuildSvg(W,H){const svg=touchGamepadSvg;while(svg.firstChild)svg.removeChild(svg.firstChild);const els=touchGamepadSvgEls={face:[],thumb:[]};const S=touchGamepadSize;const circle=(cx,cy,rr,fill)=>{const c=document.createElementNS(touchGamepadSvgNS,"circle");c.setAttribute("cx",cx);c.setAttribute("cy",cy);c.setAttribute("r",rr);if(fill)c.setAttribute("fill",fill);svg.appendChild(c);return c};const cross=ctr=>{const a=S*.18,b=S*.5,x=ctr.x,y=ctr.y;const p=document.createElementNS(touchGamepadSvgNS,"path");p.setAttribute("d",`M ${x-a} ${y-b} H ${x+a} V ${y-a} H ${x+b} V ${y+a} H ${x+a} `+`V ${y+b} H ${x-a} V ${y+a} H ${x-b} V ${y-a} H ${x-a} Z`);svg.appendChild(p)};for(let side=0;side<2;side++){const count=touchGamepadSideButtonCount(side);const base=touchGamepadSideButtonBase(side);const ctr=touchGamepadSideCenter(side,W,H);if(touchGamepadSideStick(side)){if(touchGamepadAnalog)circle(ctr.x,ctr.y,S/2);else cross(ctr);els.thumb[side]=circle(ctr.x,ctr.y,S/4,"#fff")}else if(count===1)els.face[base]=circle(ctr.x,ctr.y,S/2,"#000");else for(let i=0;i<count;i++){const j=mod(i-1,4);let button=count>2?j:min(j,count-1);button=button===3?2:button===2?3:button;const offset=vec2().setDirection(j,S/2);if(count===2)offset.x*=-1;if(!side)offset.x*=-1;const pos=ctr.add(offset);els.face[base+button]=circle(pos.x,pos.y,S/4,"#000")}}if(debug&&debugGamepads)touchGamepadBuildDebug(W,H)}function touchGamepadBuildDebug(W,H){const S=touchGamepadSize,svg=touchGamepadSvg;const shape=(tag,attrs,stroke)=>{const el=document.createElementNS(touchGamepadSvgNS,tag);for(const k in attrs)el.setAttribute(k,attrs[k]);el.setAttribute("stroke",stroke);el.setAttribute("stroke-width",2);el.setAttribute("fill","none");svg.appendChild(el)};const ring=(c,rr,stroke)=>shape("circle",{cx:c.x,cy:c.y,r:rr},stroke);shape("line",{x1:W/2,y1:0,x2:W/2,y2:H},"#0f0");for(let side=0;side<2;side++){if(touchGamepadSideStick(side)){if(touchGamepadFloating){const top=H*.4,full=!touchGamepadSideHasControl(side?0:1);const x=full?0:side?W/2:0;shape("rect",{x:x,y:top,width:full?W:W/2,height:H-top},"#0ff")}else ring(touchGamepadSideCenter(side,W,H),2*S,"#0ff")}else if(touchGamepadSideButtonCount(side)>=1)ring(touchGamepadSideCenter(side,W,H),S,"#0ff")}if(touchGamepadCenterButtonSize){ring(vec2(W/2,H/2),touchGamepadCenterButtonSize,"#ff0");for(let side=0;side<2;side++)if(touchGamepadSideHasControl(side))ring(touchGamepadSideCenter(side,W,H),2*S,"#f0f")}}function touchGamepadRender(){if(!touchGamepadOverlay||headlessMode)return;if(!touchGamepadEnable||!isTouchDevice){if(touchGamepadOverlay.style.display!=="none"){touchGamepadOverlay.style.display="none";touchGamepadPointerRole.clear();touchGamepadButtons.length=0;touchGamepadSticks.length=0;touchGamepadStickPointerId.length=0}return}touchGamepadOverlay.style.display="";const dbg=debug&&debugGamepads;const layout=[touchGamepadButtonCount,touchGamepadLeftButtonCount,touchGamepadLeftStick,touchGamepadRightStick,touchGamepadAnalog,touchGamepadSize,touchGamepadFloating,touchGamepadCenterButtonSize,paused,dbg].join();if(layout!==touchGamepadLastLayout){touchGamepadLastLayout=layout;touchGamepadNeedRelayout=true}if(touchGamepadNeedRelayout)touchGamepadRelayout();const fade=touchGamepadDisplayTime?percent(touchGamepadTimer.get(),touchGamepadDisplayTime+1,touchGamepadDisplayTime):1;const visible=dbg||touchGamepadTimer.isSet()&&fade>0&&!paused;touchGamepadOverlay.style.opacity=!visible?0:dbg?1:fade*touchGamepadAlpha;if(!visible)return;const r=touchGamepadStageRect();const W=r.width,H=r.height,S=touchGamepadSize;const els=touchGamepadSvgEls;if(!els)return;for(let side=0;side<2;side++)if(touchGamepadSideStick(side)&&els.thumb[side]){const ctr=touchGamepadSideCenter(side,W,H);const t=ctr.add((touchGamepadSticks[side]??vec2()).scale(S/2));els.thumb[side].setAttribute("cx",t.x);els.thumb[side].setAttribute("cy",t.y)}for(let i=0;i<els.face.length;i++)if(els.face[i])els.face[i].setAttribute("fill",touchGamepadButtons[i]?"#fff":"#000")}function touchGamepadEventPos(e){const r=touchGamepadStageRect();return vec2(e.clientX-r.left,e.clientY-r.top)}function touchGamepadApplyStick(side,p){const delta=p.subtract(touchGamepadStickAnchors[side]);touchGamepadSticks[side]=delta.scale(2/touchGamepadSize).clampLength();touchGamepadButtons[touchGamepadStickOut(side)?11:10]=1}function touchGamepadFaceButtonAt(side,p,W,H){const count=touchGamepadSideButtonCount(side);const base=touchGamepadSideButtonBase(side);const bc=touchGamepadSideCenter(side,W,H);if(bc.distance(p)>=touchGamepadSize)return-1;if(count===1)return base;const d=bc.subtract(p);if(!side)d.x*=-1;let button=count===2?d.x<d.y?1:0:mod(d.direction()+2,4);button=button===3?2:button===2?3:button;return button<count?base+button:-1}function touchGamepadControlAt(p,W,H){const S=touchGamepadSize;const leftHalf=p.x<W/2;const floatTop=H*.4;for(let side=0;side<2;side++){const onHalf=side?!leftHalf:leftHalf;if(touchGamepadSideStick(side)){const otherControl=touchGamepadSideHasControl(side?0:1);const grab=touchGamepadFloating?(!otherControl||onHalf)&&p.y>floatTop:onHalf&&touchGamepadSideCenter(side,W,H).distance(p)<2*S;if(grab)return{role:"stick",side:side}}else if(touchGamepadSideButtonCount(side)>=1){const btn=touchGamepadFaceButtonAt(side,p,W,H);if(btn>=0)return{role:"face",btn:btn}}}if(touchGamepadCenterButtonSize){for(let side=0;side<2;side++)if(touchGamepadSideHasControl(side)&&touchGamepadSideCenter(side,W,H).distance(p)<2*S)return;if(vec2(W/2,H/2).distance(p)<touchGamepadCenterButtonSize)return{role:"start"}}}function touchGamepadPointerDown(e,zone){if(!touchGamepadEnable)return;e.preventDefault();zone.setPointerCapture(e.pointerId);touchGamepadTimer.set();if(soundEnable&&!headlessMode&&audioContext&&!audioIsRunning())audioContext.resume();if(paused){if(touchGamepadCenterButtonSize){touchGamepadButtons[9]=1;touchGamepadPointerRole.set(e.pointerId,"start")}return}const r=touchGamepadStageRect();const W=r.width,H=r.height;const p=vec2(e.clientX-r.left,e.clientY-r.top);const hit=touchGamepadControlAt(p,W,H);if(!hit)return;if(hit.role==="stick"){const side=hit.side;touchGamepadStickAnchors[side]=touchGamepadFloating?p:touchGamepadSideCenter(side,W,H);touchGamepadStickPointerId[side]=e.pointerId;touchGamepadPointerRole.set(e.pointerId,"stick"+side);touchGamepadNeedRelayout=true;touchGamepadApplyStick(side,p)}else if(hit.role==="face"){touchGamepadButtons[hit.btn]=1;touchGamepadPointerRole.set(e.pointerId,"face"+hit.btn)}else{touchGamepadButtons[9]=1;touchGamepadPointerRole.set(e.pointerId,"start")}}function touchGamepadPointerMove(e){const role=touchGamepadPointerRole.get(e.pointerId);if(!role)return;e.preventDefault();const p=touchGamepadEventPos(e);if(role==="stick0"||role==="stick1")touchGamepadApplyStick(role==="stick1"?1:0,p)}function touchGamepadPointerUp(e){const role=touchGamepadPointerRole.get(e.pointerId);if(!role)return;touchGamepadPointerRole.delete(e.pointerId);if(role==="stick0"||role==="stick1"){const side=role==="stick1"?1:0;touchGamepadStickPointerId[side]=undefined;touchGamepadSticks[side]=vec2();delete touchGamepadButtons[touchGamepadStickOut(side)?11:10]}else if(role==="start")delete touchGamepadButtons[9];else delete touchGamepadButtons[+role.slice(4)];touchGamepadTimer.set()}let audioContext=new AudioContext;let audioMasterGain=audioContext.createGain();audioMasterGain.connect(audioContext.destination);audioMasterGain.gain.value=soundVolume;let audioMasterEffectInput,audioMasterEffectOutput,audioMasterEffectOutputIsEffect;const audioDefaultSampleRate=44100;function audioIsRunning(){return audioContext.state==="running"}function audioInit(){if(!soundEnable||headlessMode)return;document.addEventListener("visibilitychange",audioVisibilityChange)}let audioSuspendedWhenHidden=false;function audioVisibilityChange(){if(document.hidden){if(!soundPauseWhenHidden||audioContext.state!="running")return;audioSuspendedWhenHidden=true;audioContext.suspend()}else if(audioSuspendedWhenHidden){audioSuspendedWhenHidden=false;audioContext.resume()}}function setAudioMasterEffect(input,output){const outputArg=output||input;const outputIsEffect=!!outputArg&&"input"in outputArg;output=audioEffectNode(output,"output")||audioEffectNode(input,"output");input=audioEffectNode(input,"input");ASSERT(!input||typeof input.connect==="function","input must be an AudioNode or an effect with input and output nodes");ASSERT(!output||typeof output.connect==="function","output must be an AudioNode or an effect with input and output nodes");audioMasterGain.disconnect(audioMasterEffectInput||audioContext.destination);audioMasterEffectOutput?.disconnect();if(audioMasterEffectOutputIsEffect)audioMasterEffectOutput.connect(audioMasterGain);audioMasterEffectInput=input;audioMasterEffectOutput=output;audioMasterEffectOutputIsEffect=outputIsEffect;if(input){audioMasterGain.connect(input);output.disconnect();output.connect(audioContext.destination)}else audioMasterGain.connect(audioContext.destination)}function audioEffectNode(effectOrNode,key){if(effectOrNode&&"input"in effectOrNode)return effectOrNode[key];return effectOrNode}class Sound{constructor(asset,randomness,range=soundDefaultRange,taper=soundDefaultTaper,onloadCallback){if(!soundEnable||headlessMode)return;ASSERT(!asset||isArray(asset)||isStringLike(asset),"asset must be a file name or zzfx array");ASSERT(randomness===undefined||isNumber(randomness),"randomness must be a number");ASSERT(randomness===undefined||randomness>=0&&randomness<=1,"randomness must be between 0 and 1");ASSERT(isNumber(range),"range must be a number");ASSERT(isNumber(taper),"taper must be a number");this.range=range;this.taper=taper;this.randomness=randomness??0;this.sampleRate=audioDefaultSampleRate;this.sampleLength=0;this.sampleBuffer=undefined;this._sampleChannels=undefined;this.loadedPercent=0;this.onloadCallback=onloadCallback;this.output=undefined;if(isArray(asset)){const zzfxSound=asset.slice();const defaultRandomness=randomness??.05;const randomnessIndex=1;this.randomness=zzfxSound[randomnessIndex]??defaultRandomness;zzfxSound[randomnessIndex]=0;this.sampleChannels=[zzfxG(...zzfxSound)];this.buildSampleBuffer();this.loadedPercent=1;onloadCallback?.(this)}else if(typeof asset==="string"){const filename=asset;this.loadSound(filename).catch(e=>LOG("Sound load failed for",filename,"-",e.message))}}get sampleChannels(){const buffer=this.sampleBuffer;if(!this._sampleChannels&&buffer){const channels=[];for(let i=0;i<buffer.numberOfChannels;i++)channels.push(buffer.getChannelData(i).slice());this._sampleChannels=channels}return this._sampleChannels}set sampleChannels(sampleChannels){this._sampleChannels=sampleChannels;this.sampleBuffer=undefined;this.sampleLength=sampleChannels?.[0]?.length||0}buildSampleBuffer(){if(this.sampleBuffer||!this._sampleChannels||headlessMode)return;this.sampleBuffer=createAudioBuffer(this._sampleChannels,this.sampleRate);this._sampleChannels=undefined}play(pos,volume=1,pitch=1,randomnessScale=1,loop=false,paused=false){ASSERT(!pos||isVector2(pos),"pos must be a vec2");ASSERT(isNumber(volume),"volume must be a number");ASSERT(isNumber(pitch),"pitch must be a number");ASSERT(isNumber(randomnessScale),"randomnessScale must be a number");if(!soundEnable||headlessMode)return;if(!this.sampleBuffer&&!this._sampleChannels)return;let pan;if(pos){const range=this.range;if(range){const lengthSquared=cameraPos.distanceSquared(pos);if(lengthSquared>range*range)return;volume*=percent(lengthSquared**.5,range,range*this.taper)}pan=worldToScreen(pos).x*2/mainCanvasSize.x-1}const rate=pitch+pitch*this.randomness*randomnessScale*rand(-1,1);const instance=new SoundInstance(this,volume,rate,pan,loop,paused);if(debug&&debugSound&&pos){debugCircle(pos,.5,"#0ff",.5,true);if(this.range){debugCircle(pos,2*this.range,"#0ff",.5);debugCircle(pos,2*this.range*this.taper,"#0ff",.5)}debugText("vol "+volume.toFixed(2)+" pitch "+rate.toFixed(2),pos,.5,"#0ff",.5)}return instance}playLoop(pos,volume=1,pitch=1,randomnessScale=1,paused=false){return this.play(pos,volume,pitch,randomnessScale,true,paused)}playMusic(volume=1,loop=true,paused=false){return this.play(undefined,volume,1,0,loop,paused)}playNote(semitoneOffset=0,pos,volume){ASSERT(isNumber(semitoneOffset),"semitoneOffset must be a number");const pitch=getNoteFrequency(semitoneOffset,1);return this.play(pos,volume,pitch,0)}getDuration(){return this.sampleLength/this.sampleRate||0}isLoaded(){return this.loadedPercent===1}async loadSound(filename){const response=await fetch(filename);if(!response.ok)throw new Error(`Failed to load sound from ${filename}: ${response.status} ${response.statusText}`);const arrayBuffer=await response.arrayBuffer();const audioBuffer=await audioContext.decodeAudioData(arrayBuffer);this.sampleRate=audioBuffer.sampleRate;this.sampleLength=audioBuffer.length;this.sampleBuffer=audioBuffer;this.loadedPercent=1;this.onloadCallback?.(this)}}class SoundInstance{constructor(sound,volume=1,rate=1,pan=0,loop=false,paused=false){ASSERT(sound instanceof Sound,"SoundInstance requires a valid Sound object");ASSERT(volume>=0,"Sound volume must be positive or zero");ASSERT(rate>=0,"Sound rate must be positive or zero");ASSERT(isNumber(pan),"Sound pan must be a number");this.sound=sound;this.volume=volume;this.rate=rate;this.pan=pan;this.loop=loop;this.pausedTime=0;this.startTime=undefined;this.gainNode=undefined;this.source=undefined;this.output=sound.output;this.onendedCallback=source=>{if(source===this.source){this.source=undefined;this.startTime=undefined;this.pausedTime=0}};if(!paused)this.start()}start(offset=0){ASSERT(offset>=0,"Sound start offset must be positive or zero");if(this.isPlaying())this.stop();this.gainNode=audioContext.createGain();this.sound.buildSampleBuffer();this.source=this.sound.sampleBuffer?playAudioBuffer(this.sound.sampleBuffer,this.volume,this.rate,this.pan,this.loop,this.gainNode,offset,this.onendedCallback,this.output):playSamples(this.sound.sampleChannels,this.volume,this.rate,this.pan,this.loop,this.sound.sampleRate,this.gainNode,offset,this.onendedCallback,this.output);if(this.source){this.startTime=audioContext.currentTime-offset;this.pausedTime=undefined}else{this.startTime=undefined;this.pausedTime=offset}}setVolume(volume,fadeTime=0){ASSERT(volume>=0,"Sound volume must be positive or zero");ASSERT(fadeTime>=0,"Sound fade time must be positive or zero");this.volume=volume;if(!this.gainNode)return;const gain=this.gainNode.gain;const startFade=audioContext.currentTime;gain.cancelScheduledValues(startFade);if(fadeTime){gain.setValueAtTime(gain.value,startFade);gain.linearRampToValueAtTime(volume,startFade+fadeTime)}else gain.value=volume}setRate(rate){ASSERT(rate>=0,"Sound rate must be positive or zero");if(this.isPlaying()&&rate)this.startTime=audioContext.currentTime-this.getCurrentTime()*this.rate/rate;this.rate=rate;if(this.source)this.source.playbackRate.value=rate}stop(fadeTime=0){ASSERT(fadeTime>=0,"Sound fade time must be positive or zero");if(this.isPlaying()){if(fadeTime){const gain=this.gainNode.gain;const startFade=audioContext.currentTime;const endFade=startFade+fadeTime;gain.cancelScheduledValues(startFade);gain.setValueAtTime(gain.value,startFade);gain.linearRampToValueAtTime(0,endFade);this.source.stop(endFade)}else this.source.stop()}this.pausedTime=0;this.source=undefined;this.startTime=undefined}pause(){if(this.isPaused())return;this.pausedTime=this.getCurrentTime();this.source.stop();this.source=undefined;this.startTime=undefined}resume(){if(!this.isPaused())return;this.start(this.pausedTime)}isPlaying(){return!!this.source}isPaused(){return!this.isPlaying()}getCurrentTime(){if(!this.isPlaying())return this.pausedTime;const duration=this.getDuration();return duration?mod(audioContext.currentTime-this.startTime,duration):0}getDuration(){return this.rate?this.sound.getDuration()/this.rate:0}getSource(){return this.source}}function speak(text,volume=1,rate=1,pitch=1,language=""){ASSERT(typeof volume!=="string","speak() signature changed: language is now the last parameter, after pitch");if(!soundEnable||headlessMode)return;if(typeof speechSynthesis==="undefined")return;const utterance=new SpeechSynthesisUtterance(text);utterance.lang=language;utterance.volume=clamp(volume*soundVolume);utterance.rate=rate;utterance.pitch=pitch;speechSynthesis.speak(utterance);return utterance}function speakStop(){if(typeof speechSynthesis!=="undefined")speechSynthesis.cancel()}function getNoteFrequency(semitoneOffset,rootFrequency=220){return rootFrequency*2**(semitoneOffset/12)}function playSamples(sampleChannels,volume=1,rate=1,pan=0,loop=false,sampleRate=audioDefaultSampleRate,gainNode,offset=0,onended,output){if(!soundEnable||headlessMode)return;if(!audioIsRunning()){audioContext.resume();return}const buffer=createAudioBuffer(sampleChannels,sampleRate);return playAudioBuffer(buffer,volume,rate,pan,loop,gainNode,offset,onended,output)}function createAudioBuffer(sampleChannels,sampleRate=audioDefaultSampleRate){const channelCount=sampleChannels.length;const sampleLength=sampleChannels[0].length;const buffer=audioContext.createBuffer(channelCount,sampleLength,sampleRate);sampleChannels.forEach((c,i)=>buffer.getChannelData(i).set(c));return buffer}function playAudioBuffer(buffer,volume=1,rate=1,pan=0,loop=false,gainNode,offset=0,onended,output){if(!soundEnable||headlessMode)return;if(!audioIsRunning()){audioContext.resume();return}const source=audioContext.createBufferSource();source.buffer=buffer;source.playbackRate.value=rate;source.loop=loop;gainNode=gainNode||audioContext.createGain();gainNode.gain.value=volume;const outputNode=audioEffectNode(output,"input")||audioMasterGain;ASSERT(typeof outputNode.connect==="function","output must be an AudioNode or an effect with input and output nodes");gainNode.connect(outputNode);const pannerNode=new StereoPannerNode(audioContext,{pan:clamp(pan,-1,1)});source.connect(pannerNode).connect(gainNode);source.addEventListener("ended",()=>{gainNode.disconnect();pannerNode.disconnect();if(onended)onended(source)});const startOffset=offset*rate;source.start(0,startOffset);if(debug&&debugSound)LOG("sound","vol",volume.toFixed(2),"rate",rate.toFixed(2),"pan",pan.toFixed(2),loop?"loop":"");return source}function zzfx(...zzfxSound){return playSamples([zzfxG(...zzfxSound)])}function zzfxG(volume=1,randomness=.05,frequency=220,attack=0,sustain=0,release=.1,shape=0,shapeCurve=1,slide=0,deltaSlide=0,pitchJump=0,pitchJumpTime=0,repeatTime=0,noise=0,modulation=0,bitCrush=0,delay=0,sustainVolume=1,decay=0,tremolo=0,filter=0){let sampleRate=audioDefaultSampleRate,PI2=PI*2,startSlide=slide*=500*PI2/sampleRate/sampleRate,startFrequency=frequency*=(1+rand(randomness,-randomness))*PI2/sampleRate,modOffset=0,repeat=0,crush=0,jump=1,length,b=[],t=0,i=0,s=0,f,quality=2,w=PI2*abs(filter)*2/sampleRate,cosw=cos(w),alpha=sin(w)/2/quality,a0=1+alpha,a1=-2*cosw/a0,a2=(1-alpha)/a0,b0=(1+sign(filter)*cosw)/2/a0,b1=-(sign(filter)+cosw)/a0,b2=b0,x2=0,x1=0,y2=0,y1=0;const minAttack=9;attack=attack*sampleRate||minAttack;decay*=sampleRate;sustain*=sampleRate;release*=sampleRate;delay*=sampleRate;deltaSlide*=500*PI2/sampleRate**3;modulation*=PI2/sampleRate;pitchJump*=PI2/sampleRate;pitchJumpTime*=sampleRate;repeatTime=repeatTime*sampleRate|0;for(length=attack+decay+sustain+release+delay|0;i<length;b[i++]=s*volume){if(!(++crush%(bitCrush*100|0))){s=shape?shape>1?shape>2?shape>3?shape>4?t/PI2%1<shapeCurve/2?1:-1:sin(t**3):max(min(tan(t),1),-1):1-(2*t/PI2%2+2)%2:1-4*abs(round(t/PI2)-t/PI2):sin(t);s=(repeatTime?1-tremolo+tremolo*sin(PI2*i/repeatTime):1)*(shape>4?s:sign(s)*abs(s)**shapeCurve)*(i<attack?i/attack:i<attack+decay?1-(i-attack)/decay*(1-sustainVolume):i<attack+decay+sustain?sustainVolume:i<length-delay?(length-i-delay)/release*sustainVolume:0);s=delay?s/2+(delay>i?0:(i<length-delay?1:(length-i)/delay)*b[i-delay|0]/2/volume):s;if(filter)s=y1=b2*x2+b1*(x2=x1)+b0*(x1=s)-a2*y2-a1*(y2=y1)}f=(frequency+=slide+=deltaSlide)*cos(modulation*modOffset++);t+=f+f*noise*sin(i**5);if(jump&&++jump>pitchJumpTime){frequency+=pitchJump;startFrequency+=pitchJump;jump=0}if(repeatTime&&!(++repeat%repeatTime)){frequency=startFrequency;slide=startSlide;jump||=1}}return b}const tileCollisionLayers=[];function tileCollisionGetData(pos,solidOnly=true){for(const layer of tileCollisionLayers)if(!solidOnly||layer.isSolid){const layerPos=pos.subtract(layer.pos);if(layerPos.arrayCheck(layer.size)){const data=layer.getCollisionData(layerPos);if(data)return data}}return 0}function tileCollisionTest(pos,size=vec2(),callbackObject,solidOnly=true){for(const layer of tileCollisionLayers){if(!solidOnly||layer.isSolid)if(layer.collisionTest(pos,size,callbackObject))return layer}}function tileCollisionRaycast(posStart,posEnd,callbackObject,normal,solidOnly=true){let closestHit,closestDistSq,closestNormal;const scratchNormal=normal&&vec2();for(const layer of tileCollisionLayers){if(!solidOnly||layer.isSolid){const hitPos=layer.collisionRaycast(posStart,posEnd,callbackObject,scratchNormal);if(hitPos){const d=posStart.distanceSquared(hitPos);if(closestHit===undefined||d<closestDistSq){closestHit=hitPos;closestDistSq=d;if(normal)closestNormal=scratchNormal.copy()}}}}if(closestHit&&normal)normal.setFrom(closestNormal);return closestHit}function tileLayersLoad(tileMapData,tileInfo=tile(),renderOrder=0,collisionLayer,draw=true){if(!tileMapData){const s=50;tileMapData={};tileMapData.height=tileMapData.width=s;tileMapData.layers=[{}];tileMapData.layers[0].data=new Array(s*s).fill(0)}ASSERT(tileMapData.width&&tileMapData.height);ASSERT(tileMapData.layers&&tileMapData.layers.length);const tileLayers=[];const levelSize=vec2(tileMapData.width,tileMapData.height);const layerCount=tileMapData.layers.length;for(let layerIndex=layerCount;layerIndex--;){const dataLayer=tileMapData.layers[layerIndex];ASSERT(dataLayer.data&&dataLayer.data.length);ASSERT(levelSize.area()===dataLayer.data.length);const layerRenderOrder=renderOrder-(layerCount-1-layerIndex);const tileLayer=new TileCollisionLayer(vec2(),levelSize,tileInfo,layerRenderOrder);tileLayers[layerIndex]=tileLayer;const layerColor=dataLayer.tintcolor?(new Color).setHex(dataLayer.tintcolor):dataLayer.color||WHITE;ASSERT(isColor(layerColor),"layer color is not a color");for(let x=levelSize.x;x--;)for(let y=levelSize.y;y--;){const pos=vec2(x,levelSize.y-1-y);const data=dataLayer.data[x+y*levelSize.x];if(data){const layerData=new TileLayerData(data-1,0,false,layerColor);tileLayer.setData(pos,layerData);if(layerIndex===collisionLayer)tileLayer.setCollisionData(pos,1)}}if(draw)tileLayer.redraw()}return tileLayers}class TileLayerData{constructor(tile,direction=0,mirror=false,color=new Color){this.tile=tile;this.direction=direction;this.mirror=mirror;this.color=color.copy()}clear(){this.tile=this.direction=0;this.mirror=false;this.color=new Color}}class CanvasLayer extends EngineObject{constructor(pos,size,angle=0,renderOrder=0,canvasSize=vec2(512),useWebGL=true){ASSERT(isVector2(canvasSize),"canvasSize must be a Vector2");super(pos,size,undefined,angle,WHITE,renderOrder);this.context=headlessMode?undefined:createCanvasContext(canvasSize.x,canvasSize.y);this.canvas=this.context?.canvas;this.textureInfo=new TextureInfo(this.canvas,useWebGL);this.mass=0}destroy(){if(this.destroyed)return;this.textureInfo.destroyWebGLTexture();super.destroy()}render(){this.draw(this.pos,this.size,this.color,this.angle,this.mirror,this.additiveColor)}draw(pos,size,color=WHITE,angle=0,mirror=false,additiveColor,screenSpace=false,context){const tileInfo=(new TileInfo).setFullImage(this.textureInfo);const useWebGL=this.hasWebGL();drawTile(pos,size,tileInfo,color,angle,mirror,additiveColor,useWebGL,screenSpace,context)}updateWebGL(){this.textureInfo.createWebGLTexture()}hasWebGL(){return glEnable&&this.textureInfo.hasWebGL()}}class TileLayer extends CanvasLayer{constructor(pos,size,tileInfo=tile(),renderOrder=0,useWebGL=true){const canvasSize=tileInfo?size.multiply(tileInfo.size):size;super(pos,size,0,renderOrder,canvasSize,useWebGL);this.tileInfo=undefined;this.data=[];this.isUsingWebGL=false;if(headlessMode){this.render=()=>{};this.redraw=()=>{};this.redrawStart=()=>{};this.redrawEnd=()=>{};this.drawTileData=()=>{};this.redrawTileData=()=>{};this.drawLayerTile=()=>{};this.drawLayerRect=()=>{};this.drawTile=()=>{};this.drawRect=()=>{};this.clearLayerRect=()=>{};return}if(tileInfo){this.tileInfo=tileInfo.frame(0);this.tileInfo.bleed=0}for(let j=this.size.area();j--;)this.data.push(new TileLayerData)}setData(layerPos,data,redraw=false){layerPos=layerPos.floor();ASSERT(isVector2(layerPos),"layerPos must be a Vector2");ASSERT(data instanceof TileLayerData,"data must be a TileLayerData");if(!layerPos.arrayCheck(this.size))return;this.data[(layerPos.y|0)*this.size.x+(layerPos.x|0)]=data;if(!redraw)return;const isRedraw=drawContext===this.context;isRedraw?this.drawTileData(layerPos):this.redrawTileData(layerPos)}clearData(layerPos,redraw=false){this.setData(layerPos,new TileLayerData,redraw)}getData(layerPos){ASSERT(isVector2(layerPos),"layerPos must be a Vector2");return layerPos.arrayCheck(this.size)?this.data[(layerPos.y|0)*this.size.x+(layerPos.x|0)]:undefined}update(){if(!glEnable&&this.isUsingWebGL){this.isUsingWebGL=false;this.redraw()}}render(){ASSERT(drawContext!==this.context,"must call redrawEnd() after drawing tiles!");const size=this.drawSize||this.size;const pos=this.pos.add(size.scale(.5));this.draw(pos,size,this.color,this.angle,this.mirror,this.additiveColor)}onRedraw(){}redraw(){this.redrawStart(true);for(let x=this.size.x;x--;)for(let y=this.size.y;y--;)this.drawTileData(vec2(x,y),false);this.isUsingWebGL&&glFlush();this.onRedraw();this.redrawEnd()}redrawStart(clear=false){if(!this.context)return;ASSERT(drawContext!==this.context);this.savedRenderSettings=[drawContext,mainCanvasSize,cameraPos,cameraScale,canvasClearColor];drawContext=this.context;const tileSize=this.tileInfo?.size??vec2(1);mainCanvasSize=this.size.multiply(tileSize);canvasClearColor=CLEAR_BLACK;cameraPos=this.size.multiply(tileSize).scale(.5);cameraScale=1;this.isUsingWebGL=this.hasWebGL();if(this.isUsingWebGL)glSetRenderTarget(this.textureInfo.glTexture,clear);else{this.context.imageSmoothingEnabled=!tilesPixelated;if(clear){this.canvas.width=mainCanvasSize.x;this.canvas.height=mainCanvasSize.y}}}redrawEnd(){if(!this.context)return;ASSERT(drawContext===this.context);if(this.isUsingWebGL)glSetRenderTarget();[drawContext,mainCanvasSize,cameraPos,cameraScale,canvasClearColor]=this.savedRenderSettings}drawTileData(layerPos,clear=true){if(!this.context)return;ASSERT(drawContext===this.context,"must call redrawStart() before drawing tiles");const drawSize=this.tileInfo?.size??vec2(1);const drawPos=layerPos.multiply(drawSize);clear&&this.clearLayerRect(drawPos,drawSize);const d=this.getData(layerPos);if(!d||!d.tile)return;const tileInfo=this.tileInfo&&this.tileInfo.index(d.tile);this.drawLayerTile(drawPos,drawSize,tileInfo,d.color,d.direction*PI/2,d.mirror)}redrawTileData(layerPos,clear=true){if(!this.context)return;ASSERT(drawContext!==this.context,"redrawStart() should not be active when calling redrawTileData(), instead use drawTileData()");this.redrawStart();this.drawTileData(layerPos,clear);this.redrawEnd()}drawLayerTile(pos,size=vec2(1),tileInfo,color=WHITE,angle=0,mirror,additiveColor){const drawPos=pos.add(size.scale(.5));drawTile(drawPos,size,tileInfo,color,angle,mirror,additiveColor,this.isUsingWebGL)}drawLayerRect(pos,size,color,angle=0){this.drawLayerTile(pos,size,undefined,color,angle)}drawTile(pos,size=vec2(1),tileInfo,color=new Color,angle=0,mirror=false){pos=pos.subtract(this.pos).multiply(this.tileInfo.size);size=size.multiply(this.tileInfo.size);pos.y=this.canvas.height-pos.y;const oldMainCanvasSize=mainCanvasSize;mainCanvasSize=vec2(this.canvas.width,this.canvas.height);const useWebGL=this.hasWebGL();useWebGL&&glSetRenderTarget(this.textureInfo.glTexture);const drawContext=useWebGL?undefined:this.context;drawTile(pos,size,tileInfo,color,angle,mirror,undefined,useWebGL,true,drawContext);useWebGL&&glSetRenderTarget();mainCanvasSize=oldMainCanvasSize}drawRect(pos,size,color,angle){this.drawTile(pos,size,undefined,color,angle)}clearLayerRect(pos,size){ASSERT(drawContext===this.context,"must call redrawStart() before clearing tiles");const x=pos.x,y=this.canvas.height-pos.y-size.y;const useWebGL=this.hasWebGL();if(useWebGL)glClearRect(x,y,size.x,size.y);else this.context.clearRect(x,y,size.x,size.y)}}class TileCollisionLayer extends TileLayer{constructor(pos,size,tileInfo=tile(),renderOrder=0,useWebGL=true){super(pos,size.floor(),tileInfo,renderOrder,useWebGL);this.collisionData=[];this.initCollision(this.size);tileCollisionLayers.push(this);this.isSolid=true}destroy(){if(this.destroyed)return;const index=tileCollisionLayers.indexOf(this);ASSERT(index>=0,"tile collision layer not found in array");index>=0&&tileCollisionLayers.splice(index,1);super.destroy()}initCollision(size){ASSERT(isVector2(size),"size must be a Vector2");this.size=size.floor();this.collisionData=[];this.collisionData.length=size.area();this.collisionData.fill(0)}setCollisionData(layerPos,data=1){ASSERT(isVector2(layerPos),"layerPos must be a Vector2");const i=(layerPos.y|0)*this.size.x+(layerPos.x|0);layerPos.arrayCheck(this.size)&&(this.collisionData[i]=data)}clearCollisionData(layerPos){this.setCollisionData(layerPos,0)}getCollisionData(layerPos){ASSERT(isVector2(layerPos),"layerPos must be a Vector2");const i=(layerPos.y|0)*this.size.x+(layerPos.x|0);return layerPos.arrayCheck(this.size)?this.collisionData[i]:0}collisionTest(pos,size=new Vector2,callbackObject){ASSERT(isVector2(pos)&&isVector2(size),"pos and size must be Vector2s");ASSERT(!callbackObject||typeof callbackObject==="function"||callbackObject instanceof EngineObject,"callbackObject must be a function or EngineObject");const collisionTest=callbackObject?typeof callbackObject==="function"?(tileData,pos)=>callbackObject(tileData,pos):(tileData,pos)=>callbackObject.collideWithTile(tileData,pos):()=>true;const posX=pos.x-this.pos.x;const posY=pos.y-this.pos.y;if(posX+size.x/2<0||posX-size.x/2>this.size.x)return false;if(posY+size.y/2<0||posY-size.y/2>this.size.y)return false;const minX=max(posX-size.x/2|0,0);const minY=max(posY-size.y/2|0,0);const maxX=min(max(posX+size.x/2,minX+1),this.size.x);const maxY=min(max(posY+size.y/2,minY+1),this.size.y);const hitPos=new Vector2;for(let y=minY;y<maxY;++y)for(let x=minX;x<maxX;++x){const tileData=this.collisionData[y*this.size.x+x];if(tileData&&collisionTest(tileData,hitPos.set(x+this.pos.x,y+this.pos.y)))return true}return false}collisionRaycast(posStart,posEnd,callbackObject,normal){ASSERT(isVector2(posStart)&&isVector2(posEnd),"positions must be Vector2s");ASSERT(!callbackObject||typeof callbackObject==="function"||callbackObject instanceof EngineObject,"callbackObject must be a function or EngineObject");const collisionTest=callbackObject?typeof callbackObject==="function"?(tileData,pos)=>callbackObject(tileData,pos):(tileData,pos)=>callbackObject.collideWithTile(tileData,pos):tileData=>tileData>0;const testFunction=pos=>{const tileData=this.getCollisionData(localPos.set(pos.x-this.pos.x,pos.y-this.pos.y));return tileData&&collisionTest(tileData,pos)};const localPos=new Vector2;const hitPos=lineTest(posStart,posEnd,testFunction,normal);if(debugRaycast&&hitPos){const tilePos=hitPos.floor().add(vec2(.5));debugRect(tilePos,vec2(1),"#f008");debugLine(posStart,posEnd,"#00f",.02);debugLine(posStart,hitPos,"#f00",.02);debugPoint(hitPos,"#0f0");normal&&debugLine(hitPos,hitPos.add(normal),"#ff0",.02)}return hitPos}}class ParticleEmitter extends EngineObject{constructor(pos,angle,emitSize=0,emitTime=0,emitRate=100,emitConeAngle=PI,tileInfo,colorStartA=WHITE,colorStartB=WHITE,colorEndA=CLEAR_WHITE,colorEndB=CLEAR_WHITE,particleTime=.5,sizeStart=.1,sizeEnd=1,speed=.1,angleSpeed=.05,damping=1,angleDamping=1,gravityScale=0,particleConeAngle=PI,fadeRate=.1,randomness=.2,collideTiles=false,additive=false,randomColorLinear=true,renderOrder=additive?1e9:0,localSpace=false){super(pos,vec2(),tileInfo,angle,undefined,renderOrder);this.emitCircle=typeof emitSize==="number";this.emitSize=typeof emitSize==="number"?vec2(emitSize):emitSize.copy();this.emitTime=emitTime;this.emitRate=emitRate;this.emitConeAngle=emitConeAngle;this.colorStartA=colorStartA.copy();this.colorStartB=colorStartB.copy();this.colorEndA=colorEndA.copy();this.colorEndB=colorEndB.copy();this.randomColorLinear=randomColorLinear;this.particleTime=particleTime;this.sizeStart=sizeStart;this.sizeEnd=sizeEnd;this.speed=speed;this.angleSpeed=angleSpeed;this.damping=damping;this.angleDamping=angleDamping;this.gravityScale=gravityScale;this.particleConeAngle=particleConeAngle;this.fadeRate=fadeRate;this.randomness=randomness;this.collideTiles=collideTiles;this.additive=additive;this.localSpace=localSpace;this.trailScale=0;this.particleCreateCallback=undefined;this.particleDestroyCallback=undefined;this.particleCollideCallback=undefined;this.velocityInheritance=0;this.emitTimeBuffer=0;this.particles=[];this.previousAngle=this.angle;this.previousPos=this.pos.copy()}update(){ASSERT(this.angleDamping>=0&&this.angleDamping<=1);ASSERT(this.damping>=0&&this.damping<=1);if(this.velocityInheritance){const p=this.velocityInheritance;this.velocity.x=p*(this.pos.x-this.previousPos.x);this.velocity.y=p*(this.pos.y-this.previousPos.y);this.angleVelocity=p*(this.angle-this.previousAngle);this.previousAngle=this.angle;this.previousPos.x=this.pos.x;this.previousPos.y=this.pos.y}if(this.isActive()){if(this.emitRate&&particleEmitRateScale){const rate=1/this.emitRate/particleEmitRateScale;for(this.emitTimeBuffer+=timeDelta;this.emitTimeBuffer>0;this.emitTimeBuffer-=rate)this.emitParticle()}}else if(this.particles.length===0)this.destroy(true);const particles=this.particles;let alive=0;for(let i=0;i<particles.length;++i){const p=particles[i];p.update();if(!p.destroyed)particles[alive++]=p}particles.length=alive;if(debugParticles){if(this.emitCircle)debugCircle(this.pos,this.emitSize.x/2,"#0f0");else debugRect(this.pos,this.emitSize,"#0f0",0,this.angle)}}emitParticle(){let pos=this.emitCircle?randInCircle(this.emitSize.x/2):vec2(rand(-.5,.5),rand(-.5,.5)).multiply(this.emitSize).rotate(this.angle);let angle=rand(this.particleConeAngle,-this.particleConeAngle);if(!this.localSpace){pos.x+=this.pos.x;pos.y+=this.pos.y;angle+=this.angle}const randomness=this.randomness;const randomizeScale=v=>v+v*rand(randomness,-randomness);const particleTime=randomizeScale(this.particleTime);const sizeStart=randomizeScale(this.sizeStart);const sizeEnd=randomizeScale(this.sizeEnd);const speed=randomizeScale(this.speed);const angleSpeed=randomizeScale(this.angleSpeed)*randSign();const coneAngle=rand(this.emitConeAngle,-this.emitConeAngle);const colorStart=randColor(this.colorStartA,this.colorStartB,this.randomColorLinear);const colorEnd=randColor(this.colorEndA,this.colorEndB,this.randomColorLinear);const velocityAngle=this.localSpace?coneAngle:this.angle+coneAngle;const velocity=vec2(speed*sin(velocityAngle),speed*cos(velocityAngle));let angleVelocity=angleSpeed;if(!this.localSpace&&this.velocityInheritance>0){velocity.x+=this.velocity.x;velocity.y+=this.velocity.y;angleVelocity+=this.angleVelocity}const particle=new Particle(this,pos,angle,colorStart,colorEnd,particleTime,sizeStart,sizeEnd,velocity,angleVelocity);this.particles.push(particle);this.particleCreateCallback?.(particle);return particle}updatePhysics(){}render(){for(const particle of this.particles)particle.render()}isActive(){return!this.emitTime||this.getAliveTime()<this.emitTime}destroy(immediate=false){if(this.destroyed)return;super.destroy(immediate);if(!immediate&&this.particles.length>0){this.destroyed=false;this.emitTime=-1}}}const particleDrawPos=new Vector2;class Particle{constructor(emitter,pos,angle,colorStart,colorEnd,lifeTime,sizeStart,sizeEnd,velocity=vec2(),angleVelocity=0){this.emitter=emitter;this.pos=pos;this.angle=angle;this.size=vec2(sizeStart);this.color=colorStart.copy();this.colorStart=colorStart;this.colorEnd=colorEnd;this.lifeTime=lifeTime;this.sizeStart=sizeStart;this.sizeEnd=sizeEnd;this.velocity=velocity;this.angleVelocity=angleVelocity;this.spawnTime=time;this.mirror=randBool();this.groundObject=undefined;this.destroyed=false;this.tileInfo=emitter.tileInfo}update(){const emitter=this.emitter;const damping=emitter.damping;const angleDamping=emitter.angleDamping;const restitution=emitter.restitution;const friction=emitter.friction;const gravityScale=emitter.gravityScale;const collideTiles=emitter.collideTiles;const collideCallback=emitter.particleCollideCallback;if(this.lifeTime>0&&time-this.spawnTime>this.lifeTime){this.destroy();return}const oldPos=this.pos.copy();this.velocity.x*=damping;this.velocity.y*=damping;this.pos.x+=this.velocity.x+=gravity.x*gravityScale;this.pos.y+=this.velocity.y+=gravity.y*gravityScale;this.angle+=this.angleVelocity*=angleDamping;if(!enablePhysicsSolver||!collideTiles)return;const length2=this.velocity.lengthSquared();if(length2>objectMaxSpeed*objectMaxSpeed){const s=objectMaxSpeed/length2**.5;this.velocity.x*=s;this.velocity.y*=s}this.groundObject=undefined;const testCollision=collideCallback?pos=>{const data=tileCollisionGetData(pos);return data&&collideCallback(this,data,pos)}:pos=>tileCollisionGetData(pos)>0;if(testCollision(this.pos)){const hitLayer=tileCollisionTest(this.pos);if(!testCollision(oldPos)){const isBlockedX=testCollision(vec2(this.pos.x,oldPos.y));const isBlockedY=testCollision(vec2(oldPos.x,this.pos.y));const hitRestitution=hitLayer?max(restitution,hitLayer.restitution):restitution;const hitFriction=hitLayer?max(friction,hitLayer.friction):friction;if(isBlockedX){this.pos.x=oldPos.x;this.velocity.x*=-hitRestitution;this.velocity.y*=hitFriction}if(isBlockedY||!isBlockedX){const wasFalling=this.velocity.y<0&&gravity.y<0||this.velocity.y>0&&gravity.y>0;if(wasFalling)this.groundObject=hitLayer;this.pos.y=oldPos.y;this.velocity.y*=-hitRestitution;this.velocity.x*=hitFriction}debugPhysics&&debugRect(this.pos,this.size,"#f00")}}}destroy(){const destroyCallback=this.emitter.particleDestroyCallback;const c=this.colorEnd;this.color.set(c.r,c.g,c.b,c.a);this.size.set(this.sizeEnd,this.sizeEnd);this.destroyed=true;destroyCallback?.(this)}render(){const emitter=this.emitter;const localSpace=emitter.localSpace;const additive=emitter.additive;const trailScale=emitter.trailScale;const fadeRate=emitter.fadeRate/2;const p1=this.lifeTime>0?min((time-this.spawnTime)/this.lifeTime,1):1,p2=1-p1;const radius=p2*this.sizeStart+p1*this.sizeEnd;const size=vec2(radius);const alphaFade=p1<fadeRate?p1/fadeRate:p1>1-fadeRate?(1-p1)/fadeRate:1;this.color.r=p2*this.colorStart.r+p1*this.colorEnd.r;this.color.g=p2*this.colorStart.g+p1*this.colorEnd.g;this.color.b=p2*this.colorStart.b+p1*this.colorEnd.b;this.color.a=(p2*this.colorStart.a+p1*this.colorEnd.a)*alphaFade;const pos=particleDrawPos.set(this.pos.x,this.pos.y);let angle=this.angle;if(localSpace){const a=emitter.angle;const c=cos(-a),s=sin(-a);pos.set(emitter.pos.x+pos.x*c-pos.y*s,emitter.pos.y+pos.x*s+pos.y*c);angle+=a}additive&&setAdditiveBlendMode();if(trailScale){const velocity=localSpace?this.velocity.rotate(emitter.angle):this.velocity;const speed=velocity.length();if(speed){const trailLength=speed*trailScale;size.y=max(size.x,trailLength);angle=atan2(velocity.x,velocity.y);drawTile(pos,size,this.tileInfo,this.color,angle,this.mirror)}}else drawTile(pos,size,this.tileInfo,this.color,angle,this.mirror);additive&&setAdditiveBlendMode(false);debugParticles&&debugRect(pos,size,"#f005",0,angle)}}let glCanvas;let glContext;let glAntialias=true;let glShader,glPolyShader,glPolyMode,glAdditive,glBatchAdditive,glActiveTexture,glArrayBuffer,glGeometryBuffer,glPositionData,glColorData,glBatchCount,glTextureInfos,glInstancedVAO,glPolyVAO,glFramebuffer,glRenderTarget,glShaderObjects=[],glCustomShader,glBatchShader,glProgramCustom,glTransform,glUniformLocations=new Map,glCanBeEnabled=true;const gl_ARRAY_BUFFER_SIZE=5e5;const gl_INDICES_PER_INSTANCE=11;const gl_INSTANCE_BYTE_STRIDE=gl_INDICES_PER_INSTANCE*4;const gl_MAX_INSTANCES=gl_ARRAY_BUFFER_SIZE/gl_INSTANCE_BYTE_STRIDE|0;const gl_INDICES_PER_POLY_VERTEX=3;const gl_POLY_VERTEX_BYTE_STRIDE=gl_INDICES_PER_POLY_VERTEX*4;const gl_MAX_POLY_VERTEXES=gl_ARRAY_BUFFER_SIZE/gl_POLY_VERTEX_BYTE_STRIDE|0;const gl_VERTEX_SOURCE="#version 300 es\n"+"precision highp float;"+"uniform mat4 m;"+"layout(location=0) in vec2 g;"+"layout(location=1) in vec4 p;"+"layout(location=2) in vec4 u;"+"layout(location=3) in vec4 c;"+"layout(location=4) in vec4 a;"+"layout(location=5) in float r;"+"out vec2 v,l;"+"out vec4 d,e;"+"void main(){"+"vec2 s=(g-.5)*p.zw;"+"gl_Position=m*vec4(p.xy+s*cos(r)-vec2(-s.y,s)*sin(r),1,1);"+"v=mix(u.xw,u.zy,g);"+"l=g;d=c;e=a;"+"}";function glInit(rootElement){glTextureInfos=new Set;if(!glEnable||headlessMode){glCanBeEnabled=false;return}glCanvas=document.createElement("canvas");glContext=glCanvas.getContext("webgl2",{antialias:glAntialias});if(!glContext){console.warn("WebGL2 not supported, falling back to 2D canvas rendering!");glCanvas=glContext=undefined;glEnable=false;glCanBeEnabled=false;return}rootElement.appendChild(glCanvas);initWebGL();glCanvas.addEventListener("webglcontextlost",e=>{glEnable=false;glCanvas.style.display="none";e.preventDefault();LOG("WebGL context lost! Switching to Canvas2d rendering.");for(const info of glTextureInfos)info.glTexture=undefined;glActiveTexture=undefined;for(const shader of glShaderObjects)shader.program=undefined;glBatchShader=undefined;glProgramCustom=true;glUniformLocations=new Map;glBatchCount=0;glPolyMode=false;pluginList.forEach(plugin=>plugin.glContextLost?.())});glCanvas.addEventListener("webglcontextrestored",()=>{glEnable=true;glCanvas.style.display="";LOG("WebGL context restored, reinitializing...");initWebGL();for(const info of glTextureInfos)info.glTexture=glCreateTexture(info.image,info.wrap);pluginList.forEach(plugin=>plugin.glContextRestored?.())});function initWebGL(){glShader=glCreateProgram(gl_VERTEX_SOURCE,"#version 300 es\n"+"precision highp float;"+"uniform sampler2D s;"+"in vec2 v;"+"in vec4 d,e;"+"out vec4 c;"+"void main(){"+"c=texture(s,v)*d+e;"+"}");glPolyShader=glCreateProgram("#version 300 es\n"+"precision highp float;"+"uniform mat4 m;"+"in vec2 p;"+"in vec4 c;"+"out vec4 d;"+"void main(){"+"gl_Position=m*vec4(p,1,1);"+"d=c;"+"}","#version 300 es\n"+"precision highp float;"+"in vec4 d;"+"out vec4 c;"+"void main(){"+"c=d;"+"}");const glInstanceData=new ArrayBuffer(gl_ARRAY_BUFFER_SIZE);glPositionData=new Float32Array(glInstanceData);glColorData=new Uint32Array(glInstanceData);glArrayBuffer=glContext.createBuffer();glGeometryBuffer=glContext.createBuffer();glFramebuffer=glContext.createFramebuffer();glBatchCount=0;const geometry=new Float32Array([0,0,1,0,0,1,1,1]);glContext.bindBuffer(glContext.ARRAY_BUFFER,glGeometryBuffer);glContext.bufferData(glContext.ARRAY_BUFFER,geometry,glContext.STATIC_DRAW);let offset,shader,stride;const initVertexAttrib=(name,type,typeSize,size,divisor=0)=>{const location=glContext.getAttribLocation(shader,name);const normalize=typeSize===1;const fixedStride=typeSize&&stride;glContext.enableVertexAttribArray(location);glContext.vertexAttribPointer(location,size,type,normalize,fixedStride,offset);glContext.vertexAttribDivisor(location,divisor);offset+=size*typeSize};glInstancedVAO=glContext.createVertexArray();glContext.bindVertexArray(glInstancedVAO);offset=0,shader=glShader,stride=gl_INSTANCE_BYTE_STRIDE;glContext.bindBuffer(glContext.ARRAY_BUFFER,glGeometryBuffer);initVertexAttrib("g",glContext.FLOAT,0,2);glContext.bindBuffer(glContext.ARRAY_BUFFER,glArrayBuffer);glContext.bufferData(glContext.ARRAY_BUFFER,gl_ARRAY_BUFFER_SIZE,glContext.DYNAMIC_DRAW);initVertexAttrib("p",glContext.FLOAT,4,4,1);initVertexAttrib("u",glContext.FLOAT,4,4,1);initVertexAttrib("c",glContext.UNSIGNED_BYTE,1,4,1);initVertexAttrib("a",glContext.UNSIGNED_BYTE,1,4,1);initVertexAttrib("r",glContext.FLOAT,4,1,1);glPolyVAO=glContext.createVertexArray();glContext.bindVertexArray(glPolyVAO);offset=0,shader=glPolyShader,stride=gl_POLY_VERTEX_BYTE_STRIDE;initVertexAttrib("p",glContext.FLOAT,4,2);initVertexAttrib("c",glContext.UNSIGNED_BYTE,1,4)}}function glSetInstancedMode(force=false){if(!force&&!glPolyMode)return;glFlush();glPolyMode=false;glContext.useProgram(glShader);glContext.bindVertexArray(glInstancedVAO)}function glSetPolyMode(){if(glPolyMode)return;glFlush();glPolyMode=true;glContext.useProgram(glPolyShader);glContext.bindVertexArray(glPolyVAO)}function glPreRender(clear=true){if(!glEnable||!glContext)return;ASSERT(!glBatchCount,"glPreRender called with unflushed batch.");const dpr=glRenderTarget?1:getCanvasPixelRatio();const bufferSizeX=mainCanvasSize.x*dpr|0;const bufferSizeY=mainCanvasSize.y*dpr|0;if(!glRenderTarget){if(glCanvas.width!==bufferSizeX||glCanvas.height!==bufferSizeY){glCanvas.width=bufferSizeX;glCanvas.height=bufferSizeY}}glContext.viewport(0,0,bufferSizeX,bufferSizeY);clear&&glClearCanvas();const s=vec2(2*cameraScale).divide(mainCanvasSize);if(glRenderTarget)s.y=-s.y;const rotatedCam=cameraPos.rotate(-cameraAngle);const p=vec2(-1).subtract(rotatedCam.multiply(s));const ca=cos(cameraAngle);const sa=sin(cameraAngle);const transform=[s.x*ca,s.y*sa,0,0,-s.x*sa,s.y*ca,0,0,1,1,1,0,p.x,p.y,0,1];glTransform=transform;const initUniform=(program,uniform,value)=>{glContext.useProgram(program);const location=glContext.getUniformLocation(program,uniform);glContext.uniformMatrix4fv(location,false,value)};initUniform(glPolyShader,"m",transform);initUniform(glShader,"m",transform);glContext.activeTexture(glContext.TEXTURE0);if(textureInfos[0]){glActiveTexture=textureInfos[0].glTexture;glContext.bindTexture(glContext.TEXTURE_2D,glActiveTexture)}glContext.bindBuffer(glContext.ARRAY_BUFFER,glArrayBuffer);glAdditive=glBatchAdditive=false;glSetInstancedMode(true)}function glClearCanvas(){if(!glContext)return;const color=canvasClearColor;glContext.clearColor(color.r,color.g,color.b,color.a);glContext.clear(glContext.COLOR_BUFFER_BIT)}function glSetTexture(texture){if(!glContext||texture===glActiveTexture)return;glFlush();glActiveTexture=texture;glContext.bindTexture(glContext.TEXTURE_2D,glActiveTexture)}function glSetTextureWrap(texture,wrap=true){if(!glContext||!texture)return;const isCurrent=texture===glActiveTexture;if(isCurrent)glFlush();else glContext.bindTexture(glContext.TEXTURE_2D,texture);const wrapMode=wrap?glContext.REPEAT:glContext.CLAMP_TO_EDGE;glContext.texParameteri(glContext.TEXTURE_2D,glContext.TEXTURE_WRAP_S,wrapMode);glContext.texParameteri(glContext.TEXTURE_2D,glContext.TEXTURE_WRAP_T,wrapMode);if(!isCurrent&&glActiveTexture)glContext.bindTexture(glContext.TEXTURE_2D,glActiveTexture)}function glCompileShader(source,type){if(!glContext)return;const shader=glContext.createShader(type);glContext.shaderSource(shader,source);glContext.compileShader(shader);if(debug&&!glContext.getShaderParameter(shader,glContext.COMPILE_STATUS))throw glContext.getShaderInfoLog(shader);return shader}function glCreateProgram(vsSource,fsSource){if(!glContext)return;const program=glContext.createProgram();glContext.attachShader(program,glCompileShader(vsSource,glContext.VERTEX_SHADER));glContext.attachShader(program,glCompileShader(fsSource,glContext.FRAGMENT_SHADER));glContext.linkProgram(program);if(debug&&!glContext.getProgramParameter(program,glContext.LINK_STATUS))throw glContext.getProgramInfoLog(program);return program}function glUniformLocation(program,name){let cache=glUniformLocations.get(program);cache||glUniformLocations.set(program,cache={});return cache[name]??=glContext.getUniformLocation(program,name)}function glShaderProgram(shader){return shader.program||=glCreateProgram(gl_VERTEX_SOURCE,"#version 300 es\n"+"precision highp float;"+"uniform sampler2D iChannel0;"+"uniform vec3 iResolution;"+"uniform float iTime;"+"in vec2 v,l;in vec4 d,e;out vec4 c;\n"+"#define localUV l\n"+shader.fragmentCode+"\n"+"void main(){vec4 t;mainImage(t,v);c=t*d+e;}")}function glCreateTexture(image,wrap=false){if(!glContext)return;const texture=glContext.createTexture();let mipMap=false;if(image?.width){glSetTextureData(texture,image);glContext.bindTexture(glContext.TEXTURE_2D,texture);mipMap=!tilesPixelated&&isPowerOfTwo(image.width)&&isPowerOfTwo(image.height)}else{const whitePixel=new Uint8Array([255,255,255,255]);glContext.bindTexture(glContext.TEXTURE_2D,texture);glContext.texImage2D(glContext.TEXTURE_2D,0,glContext.RGBA,1,1,0,glContext.RGBA,glContext.UNSIGNED_BYTE,whitePixel)}const magFilter=tilesPixelated?glContext.NEAREST:glContext.LINEAR;const minFilter=mipMap?glContext.LINEAR_MIPMAP_LINEAR:magFilter;glContext.texParameteri(glContext.TEXTURE_2D,glContext.TEXTURE_MAG_FILTER,magFilter);glContext.texParameteri(glContext.TEXTURE_2D,glContext.TEXTURE_MIN_FILTER,minFilter);const wrapMode=wrap?glContext.REPEAT:glContext.CLAMP_TO_EDGE;glContext.texParameteri(glContext.TEXTURE_2D,glContext.TEXTURE_WRAP_S,wrapMode);glContext.texParameteri(glContext.TEXTURE_2D,glContext.TEXTURE_WRAP_T,wrapMode);if(mipMap)glContext.generateMipmap(glContext.TEXTURE_2D);glContext.bindTexture(glContext.TEXTURE_2D,glActiveTexture);return texture}function glDeleteTexture(texture){if(!glContext)return;glContext.deleteTexture(texture)}function glSetTextureData(texture,image){if(!glContext)return;ASSERT(image?.width>0,"Invalid image data.");glContext.bindTexture(glContext.TEXTURE_2D,texture);glContext.texImage2D(glContext.TEXTURE_2D,0,glContext.RGBA,glContext.RGBA,glContext.UNSIGNED_BYTE,image);if(!tilesPixelated&&isPowerOfTwo(image.width)&&isPowerOfTwo(image.height))glContext.generateMipmap(glContext.TEXTURE_2D);glContext.bindTexture(glContext.TEXTURE_2D,glActiveTexture)}function glRegisterTextureInfo(textureInfo){if(headlessMode)return;glTextureInfos.add(textureInfo);if(!glContext)return;if(textureInfo.glTexture)glSetTextureData(textureInfo.glTexture,textureInfo.image);else textureInfo.glTexture=glCreateTexture(textureInfo.image,textureInfo.wrap)}function glUnregisterTextureInfo(textureInfo){if(headlessMode)return;glTextureInfos.delete(textureInfo);const glTexture=textureInfo.glTexture;textureInfo.glTexture=undefined;glDeleteTexture(glTexture)}function glFlush(){if(glEnable&&glContext&&glBatchCount){const destBlend=glBatchAdditive?glContext.ONE:glContext.ONE_MINUS_SRC_ALPHA;glContext.blendFuncSeparate(glContext.SRC_ALPHA,destBlend,glContext.ONE,destBlend);glContext.enable(glContext.BLEND);if(!glPolyMode&&(glBatchShader||glProgramCustom)){const program=glBatchShader?glShaderProgram(glBatchShader):glShader;glContext.useProgram(program);glProgramCustom=!!glBatchShader;if(glBatchShader){const uniform=name=>glUniformLocation(program,name);glContext.uniformMatrix4fv(uniform("m"),false,glTransform);glContext.uniform1f(uniform("iTime"),time);glContext.uniform3f(uniform("iResolution"),glCanvas.width,glCanvas.height,1)}}const byteLength=glBatchCount*(glPolyMode?gl_INDICES_PER_POLY_VERTEX:gl_INDICES_PER_INSTANCE);glContext.bufferSubData(glContext.ARRAY_BUFFER,0,glPositionData,0,byteLength);if(glPolyMode)glContext.drawArrays(glContext.TRIANGLE_STRIP,0,glBatchCount);else glContext.drawArraysInstanced(glContext.TRIANGLE_STRIP,0,4,glBatchCount);++drawCount;primitiveCount+=glBatchCount;glBatchCount=0}glBatchAdditive=glAdditive;glBatchShader=glCustomShader}function glCopyToContext(context){if(!glEnable||!glContext)return;glFlush();context.drawImage(glCanvas,0,0)}function glSetAntialias(antialias=true){ASSERT(!glCanvas,"must be called before engineInit");glAntialias=antialias}function glDraw(x,y,sizeX,sizeY,angle=0,uv0X=0,uv0Y=0,uv1X=1,uv1Y=1,rgba=-1,rgbaAdditive=0){if(glBatchCount>=gl_MAX_INSTANCES||glBatchAdditive!==glAdditive||glBatchShader!==glCustomShader)glFlush();glSetInstancedMode();let offset=glBatchCount++*gl_INDICES_PER_INSTANCE;glPositionData[offset++]=x;glPositionData[offset++]=y;glPositionData[offset++]=sizeX;glPositionData[offset++]=sizeY;glPositionData[offset++]=uv0X;glPositionData[offset++]=uv0Y;glPositionData[offset++]=uv1X;glPositionData[offset++]=uv1Y;glColorData[offset++]=rgba;glColorData[offset++]=rgbaAdditive;glPositionData[offset++]=angle}function glDrawUntextured(x,y,sizeX,sizeY,angle,rgba){glDraw(x,y,sizeX,sizeY,angle,0,0,0,0,0,rgba)}function glDrawPointsTransform(points,rgba,x,y,sx,sy,angle,tristrip=true){const pointsOut=[];const sa=sin(-angle);const ca=cos(-angle);for(const p of points){const px=p.x*sx;const py=p.y*sy;pointsOut.push(vec2(x+ca*px-sa*py,y+sa*px+ca*py))}const drawPoints=tristrip?glPolyStrip(pointsOut):pointsOut;glDrawPoints(drawPoints,rgba)}function glDrawOutlineTransform(points,rgba,lineWidth,x,y,sx,sy,angle,wrap=true){const outlinePoints=glMakeOutline(points,lineWidth,wrap);glDrawPointsTransform(outlinePoints,rgba,x,y,sx,sy,angle,false)}function glDrawPoints(points,rgba){if(!glEnable||points.length<3)return;const vertCount=points.length+2;if(glBatchCount+vertCount>=gl_MAX_POLY_VERTEXES||glBatchAdditive!==glAdditive)glFlush();ASSERT(vertCount<gl_MAX_POLY_VERTEXES,"poly exceeds max batch size");if(vertCount>=gl_MAX_POLY_VERTEXES)return;glSetPolyMode();let offset=glBatchCount*gl_INDICES_PER_POLY_VERTEX;for(let i=vertCount;i--;){const j=clamp(i-1,0,vertCount-3);const point=points[j];glPositionData[offset++]=point.x;glPositionData[offset++]=point.y;glColorData[offset++]=rgba}glBatchCount+=vertCount}function glDrawColoredPoints(points,pointColors){if(!glEnable||points.length<3)return;const vertCount=points.length+2;if(glBatchCount+vertCount>=gl_MAX_POLY_VERTEXES||glBatchAdditive!==glAdditive)glFlush();ASSERT(vertCount<gl_MAX_POLY_VERTEXES,"poly exceeds max batch size");if(vertCount>=gl_MAX_POLY_VERTEXES)return;glSetPolyMode();let offset=glBatchCount*gl_INDICES_PER_POLY_VERTEX;for(let i=vertCount;i--;){const j=clamp(i-1,0,vertCount-3);const point=points[j];const color=pointColors[j];glPositionData[offset++]=point.x;glPositionData[offset++]=point.y;glColorData[offset++]=color}glBatchCount+=vertCount}function glSetRenderTarget(texture,clear=false){if(texture){glRenderTarget=texture;glContext.bindFramebuffer(glContext.FRAMEBUFFER,glFramebuffer);glContext.framebufferTexture2D(glContext.FRAMEBUFFER,glContext.COLOR_ATTACHMENT0,glContext.TEXTURE_2D,texture,0);glPreRender(clear)}else{glFlush();glRenderTarget=undefined;glContext.bindFramebuffer(glContext.FRAMEBUFFER,null);glContext.viewport(0,0,glCanvas.width,glCanvas.height)}}function glClearRect(x,y,width,height){if(!glEnable)return;glContext.enable(glContext.SCISSOR_TEST);glContext.scissor(x,y,width,height);glContext.clearColor(0,0,0,0);glContext.clear(glContext.COLOR_BUFFER_BIT);glContext.disable(glContext.SCISSOR_TEST)}function glMakeOutline(points,width,wrap=true){if(points.length<2)return[];const halfWidth=width/2;const strip=[];const n=points.length;const e=1e-6;const miterLimit=10;for(let i=0;i<n;i++){const prev=points[wrap?(i-1+n)%n:max(i-1,0)];const curr=points[i];const next=points[wrap?(i+1)%n:min(i+1,n-1)];const dx1=curr.x-prev.x;const dy1=curr.y-prev.y;const len1=(dx1*dx1+dy1*dy1)**.5;const dx2=next.x-curr.x;const dy2=next.y-curr.y;const len2=(dx2*dx2+dy2*dy2)**.5;if(len1<e&&len2<e)continue;const nx1=len1>e?-dy1/len1:0;const ny1=len1>e?dx1/len1:0;const nx2=len2>e?-dy2/len2:0;const ny2=len2>e?dx2/len2:0;let nx=nx1+nx2;let ny=ny1+ny2;const nlen=(nx*nx+ny*ny)**.5;if(nlen<e){nx=nx1;ny=ny1}else{nx/=nlen;ny/=nlen;const dot=nx1*nx+ny1*ny;if(dot>e){const miterLength=min(1/dot,miterLimit);nx*=miterLength;ny*=miterLength}}const inner=vec2(curr.x-nx*halfWidth,curr.y-ny*halfWidth);const outer=vec2(curr.x+nx*halfWidth,curr.y+ny*halfWidth);strip.push(inner);strip.push(outer)}if(strip.length>1&&wrap){strip.push(strip[0]);strip.push(strip[1])}return strip}function glPolyStrip(points){if(points.length<3)return[];const cross=(a,b,c)=>(b.x-a.x)*(c.y-a.y)-(b.y-a.y)*(c.x-a.x);const signedArea=poly=>{let area=0;for(let i=poly.length;i--;){const j=(i+1)%poly.length;area+=poly[i].cross(poly[j])}return area};if(signedArea(points)<0)points=points.slice().reverse();const e=1e-9;const pointInTriangle=(p,a,b,c)=>{const c1=cross(a,b,p);const c2=cross(b,c,p);const c3=cross(c,a,p);const negative=(c1<-e?1:0)+(c2<-e?1:0)+(c3<-e?1:0);const positive=(c1>e?1:0)+(c2>e?1:0)+(c3>e?1:0);return!(negative&&positive)};const indices=[];for(let i=0;i<points.length;++i)indices[i]=i;const triangles=[];let attempts=0;const maxAttempts=points.length**2+100;while(indices.length>3&&attempts++<maxAttempts){let foundEar=false;for(let i=0;i<indices.length;i++){const i0=indices[(i+indices.length-1)%indices.length];const i1=indices[i];const i2=indices[(i+1)%indices.length];const a=points[i0],b=points[i1],c=points[i2];if(cross(a,b,c)<e)continue;let hasInside=false;for(let j=0;j<indices.length;j++){const k=indices[j];if(k===i0||k===i1||k===i2)continue;const p=points[k];hasInside=pointInTriangle(p,a,b,c);if(hasInside)break}if(hasInside)continue;triangles.push([i0,i1,i2]);indices.splice(i,1);foundEar=true;break}if(!foundEar){let worstIndex=-1,worstValue=Infinity;for(let i=0;i<indices.length;i++){const i0=indices[(i+indices.length-1)%indices.length];const i1=indices[i];const i2=indices[(i+1)%indices.length];const value=abs(cross(points[i0],points[i1],points[i2]));if(value<worstValue){worstValue=value;worstIndex=i}}if(worstIndex<0)break;const i0=indices[(worstIndex+indices.length-1)%indices.length];const i1=indices[worstIndex];const i2=indices[(worstIndex+1)%indices.length];triangles.push([i0,i1,i2]);indices.splice(worstIndex,1)}}if(indices.length===3)triangles.push([indices[0],indices[1],indices[2]]);if(!triangles.length)return[];const strip=[];let[a0,b0,c0]=triangles[0];strip.push(points[a0],points[b0],points[c0]);for(let i=1;i<triangles.length;i++){const[a,b,c]=triangles[i];strip.push(points[c0],points[a]);strip.push(points[a],points[b],points[c]);c0=c}return strip}function drawEngineLogo(t){const blackAndWhite=0;const showName=1;engineUpdateCanvas();const x=mainContext;const w=mainCanvasSize.x;const h=mainCanvasSize.y;{const p3=percent(t,1,.8);const p4=percent(t,0,.5);const g=x.createRadialGradient(w/2,h/2,0,w/2,h/2,hypot(w,h)*.6);g.addColorStop(0,hsl(0,0,lerp(0,p3/2,p4),p3).toString());g.addColorStop(1,hsl(0,0,0,p3).toString());x.save();x.fillStyle=g;x.fillRect(0,0,w,h)}const gradient=(X1,Y1,X2,Y2,C,S=1)=>{if(C>=0){if(blackAndWhite)x.fillStyle="#fff";else{const g=x.fillStyle=x.createLinearGradient(X1,Y1,X2,Y2);g.addColorStop(0,color(C,2));g.addColorStop(1,color(C,1))}}else x.fillStyle="#000";C>=-1?(x.fill(),S&&x.stroke()):x.stroke()};const circle=(X,Y,R,A=0,B=2*PI,C,S)=>{x.beginPath();x.arc(X,Y,R,p*A,p*B);gradient(X,Y-R,X,Y+R,C,S)};const rect=(X,Y,W,H,C)=>{x.beginPath();x.rect(X,Y,W,H*p);gradient(X,Y+H,X+W,Y,C)};const poly=(points,C,Y,H)=>{x.beginPath();for(const p of points)x.lineTo(p.x,p.y);x.closePath();gradient(0,Y,0,Y+H,C)};const color=(c,l)=>l?`hsl(${[.95,.56,.13][c%3]*360} 99%${[0,50,75][l]}%)`:"#000";const alpha=oscillate(1,1,t);const p=percent(alpha,.1,.5);const size=min(6,min(w,h)/99);x.translate(w/2,h/2);x.scale(size,size);x.translate(-40,-35);p<1&&x.setLineDash([99*p,99]);x.lineJoin=x.lineCap="round";x.lineWidth=.1+p*1.9;if(showName){const Y=54;const s="LittleJS";x.font="900 15.5px arial";x.lineWidth=.1+p*3.9;x.textAlign="center";x.textBaseline="top";rect(11,Y+1,59,8*p,-1);x.beginPath();let w2=0;for(let i=0;i<s.length;++i)w2+=x.measureText(s[i]).width;for(let j=2;j--;)for(let i=0,X=40-w2/2;i<s.length;++i){const w=x.measureText(s[i]).width,X2=X+w/2;gradient(X2,Y,X2+2,Y+13,i>5?1:0);x[j?"strokeText":"fillText"](s[i],X2,Y+.5,17*p);X+=w}x.lineWidth=.1+p*1.9;rect(3,Y,73,0)}rect(7,15,26,-7,0);rect(25,15,8,25,-1);rect(10,40,15,-25,1);rect(14,21,7,9,2);rect(38,20,6,-6,2);rect(49,20,10,-6,0);const stackPoints=[vec2(44,8),vec2(64,8),vec2(59,8+6*p),vec2(49,8+6*p)];poly(stackPoints,2,8,6*p);rect(44,8,20,-7,0);for(let i=5;i--;)circle(59-i*6*p,30,10,0,2*PI,1,0);circle(59,30,4,0,7,2);rect(35,20,24,0);circle(59,30,10);circle(47,30,10,PI/2,PI*3/2);circle(35,30,10,PI/2,PI*3/2);rect(7,40,13,7,-1);rect(17,40,43,14,-1);for(let i=3;i--;)for(let j=2;j--;)circle(17+15*i,47,j?7:1,0,2*PI,2);for(let i=2;i--;){let w=6,s=7,o=53+w*p*i;const points=[vec2(o+s,54),vec2(o,40),vec2(o+w*p,40),vec2(o+s+w*p,54)];poly(points,0,40,14)}x.restore()}let debugMedals=false;let medalDisplayTime=5;let medalDisplaySlideTime=.5;let medalDisplaySize=vec2(640,80);let medalsPreventUnlock=false;const medals={};let medalsDisplayQueue=[],medalsSaveName,medalsDisplayTimeLast;function medalsInit(saveName){medalsSaveName=saveName;if(!debugMedals){let saved={};try{saved=JSON.parse(localStorage[saveName]||"{}")}catch(e){saved={}}medalsForEach(medal=>{medal.unlocked=!!(saved[medal.id]&&saved[medal.id].unlocked)});medalsSave()}engineAddPlugin(undefined,medalsRender);function medalsRender(){if(!medalsDisplayQueue.length)return;const medal=medalsDisplayQueue[0];const time=timeReal-medalsDisplayTimeLast;if(!medalsDisplayTimeLast)medalsDisplayTimeLast=timeReal;else if(time>medalDisplayTime){medalsDisplayTimeLast=0;medalsDisplayQueue.shift()}else{const slideOffTime=medalDisplayTime-medalDisplaySlideTime;const hidePercent=time<medalDisplaySlideTime?1-time/medalDisplaySlideTime:time>slideOffTime?(time-slideOffTime)/medalDisplaySlideTime:0;medal.render(hidePercent)}}}function medalsForEach(callback){Object.values(medals).forEach(medal=>callback(medal))}function medalsReset(){medalsForEach(medal=>medal.unlocked=false);medalsSave()}function medalsSave(){if(!medalsSaveName)return;const data={};medalsForEach(medal=>{const entry={name:medal.name,description:medal.description,icon:medal.icon,unlocked:medal.unlocked};if(medal.image)entry.src=medal.image.src;data[medal.id]=entry});localStorage[medalsSaveName]=JSON.stringify(data)}class Medal{constructor(id,name,description="",icon="🏆",src){ASSERT(id>=0&&!medals[id]);this.id=id;this.name=name;this.description=description;this.icon=icon;this.unlocked=false;this.image=undefined;if(src)(this.image=new Image).src=src;medals[id]=this}unlock(){if(medalsPreventUnlock||this.unlocked)return;ASSERT(medalsSaveName,"save name must be set");this.unlocked=true;medalsSave();medalsDisplayQueue.push(this)}render(hidePercent=0){const context=mainContext;const width=min(medalDisplaySize.x,mainCanvasSize.x);const height=medalDisplaySize.y;const x=mainCanvasSize.x-width;const y=-height*hidePercent;const backgroundColor=hsl(0,0,.9);context.save();context.beginPath();context.fillStyle=backgroundColor.toString();context.strokeStyle=BLACK.toString();context.lineWidth=3;context.rect(x,y,width,height);context.fill();context.stroke();context.clip();const gap=vec2(.1,.05).scale(height);const medalDisplayIconSize=height-2*gap.x;this.renderIcon(vec2(x+gap.x+medalDisplayIconSize/2,y+height/2),medalDisplayIconSize);const nameSize=height*.5;const descriptionSize=height*.3;const pos=vec2(x+medalDisplayIconSize+2*gap.x,y+gap.y*2+nameSize/2);const textWidth=width-medalDisplayIconSize-3*gap.x;drawTextScreen(this.name,pos,nameSize,BLACK,0,undefined,"left",undefined,undefined,textWidth);pos.y=y+height-gap.y*2-descriptionSize/2;drawTextScreen(this.description,pos,descriptionSize,BLACK,0,undefined,"left",undefined,undefined,textWidth);context.restore()}renderIcon(pos,size){if(this.image)mainContext.drawImage(this.image,pos.x-size/2,pos.y-size/2,size,size);else drawTextScreen(this.icon,pos,size*.7,BLACK)}}function setMedalDisplayTime(time){medalDisplayTime=time}function setMedalDisplaySlideTime(time){medalDisplaySlideTime=time}function setMedalDisplaySize(size){medalDisplaySize=size.copy()}function setMedalsPreventUnlock(preventUnlock){medalsPreventUnlock=preventUnlock}let newgrounds;class NewgroundsMedal extends Medal{constructor(id,name,description,icon,src){super(id,name,description,icon,src)}unlock(){super.unlock();newgrounds&&newgrounds.unlockMedal(this.id)}}class NewgroundsPlugin{constructor(app_id,cipher,cryptoJS){ASSERT(!newgrounds,"there can only be one newgrounds object");ASSERT(!cipher||cryptoJS,"must provide cryptojs if there is a cipher");newgrounds=this;this.app_id=app_id;this.cipher=cipher;this.cryptoJS=cryptoJS;this.host=location?location.hostname:"";const url=new URL(location.href);this.session_id=url.searchParams.get("ngio_session_id");if(!this.session_id)return;const medalsResult=this.call("Medal.getList");if(!medalsResult||!medalsResult.result||medalsResult.result.error){debugMedals&&LOG("Newgrounds session unavailable; skipping plugin init");this.medals=[];this.scoreboards=[];return}this.medals=medalsResult.result.data?.["medals"]||[];debugMedals&&LOG(this.medals);for(const newgroundsMedal of this.medals){const medal=medals[newgroundsMedal["id"]];if(medal){medal.image=new Image;medal.image.src=newgroundsMedal["icon"];medal.name=newgroundsMedal["name"];medal.description=newgroundsMedal["description"];medal.unlocked=newgroundsMedal["unlocked"];medal.difficulty=newgroundsMedal["difficulty"];medal.value=newgroundsMedal["value"];if(medal.value)medal.description=medal.description+` (${medal.value})`}}const scoreboardResult=this.call("ScoreBoard.getBoards");this.scoreboards=scoreboardResult?.result?.data?.scoreboards||[];debugMedals&&LOG(this.scoreboards);const keepAliveMS=60*1e3;setInterval(()=>this.call("Gateway.ping",0,true),keepAliveMS)}unlockMedal(id){return this.call("Medal.unlock",{id:id},true)}postScore(id,value){return this.call("ScoreBoard.postScore",{id:id,value:value},true)}getScores(id,user,social=0,skip=0,limit=10){return this.call("ScoreBoard.getScores",{id:id,user:user,social:social,skip:skip,limit:limit})}logView(){return this.call("App.logView",{host:this.host},true)}call(component,parameters,async=false){const call={component:component,parameters:parameters};if(this.cipher){const cryptoJS=this.cryptoJS;const aesKey=cryptoJS["enc"]["Base64"]["parse"](this.cipher);const iv=cryptoJS["lib"]["WordArray"]["random"](16);const encrypted=cryptoJS["AES"]["encrypt"](JSON.stringify(call),aesKey,{iv:iv});call["secure"]=cryptoJS["enc"]["Base64"]["stringify"](iv.concat(encrypted["ciphertext"]));call["parameters"]=0}const input={app_id:this.app_id,session_id:this.session_id,call:call};const formData=new FormData;formData.append("input",JSON.stringify(input));const xmlHttp=new XMLHttpRequest;const url="https://newgrounds.io/gateway_v3.php";xmlHttp.open("POST",url,!debugMedals&&async);try{xmlHttp.send(formData)}catch(e){debugMedals&&LOG("newgrounds call failed",e);return}debugMedals&&LOG(xmlHttp.responseText);try{return xmlHttp.responseText&&JSON.parse(xmlHttp.responseText)}catch(e){debugMedals&&LOG("newgrounds response is not valid JSON",e)}}}let postProcess;class PostProcessPlugin{constructor(shaderCode,includeMainCanvas=false,feedbackTexture=false){ASSERT(!postProcess,"Post process already initialized");ASSERT(!(includeMainCanvas&&feedbackTexture),"Post process cannot both include main canvas and use feedback texture");postProcess=this;if(!shaderCode)shaderCode="void mainImage(out vec4 c,vec2 p){c=texture(iChannel0,p/iResolution.xy);}";this.shader=undefined;this.texture=undefined;this.vao=undefined;initPostProcess();engineAddPlugin(undefined,postProcessRender,postProcessContextLost,postProcessContextRestored);function initPostProcess(){if(headlessMode)return;if(!glEnable){console.warn("PostProcessPlugin: WebGL not enabled!");return}postProcess.texture=glCreateTexture();postProcess.shader=glCreateProgram("#version 300 es\n"+"precision highp float;"+"in vec2 p;"+"void main(){"+"gl_Position=vec4(p+p-1.,1,1);"+"}","#version 300 es\n"+"precision highp float;"+"uniform sampler2D iChannel0;"+"uniform vec3 iResolution;"+"uniform float iTime;"+"out vec4 c;"+"\n"+shaderCode+"\n"+"void main(){"+"mainImage(c,gl_FragCoord.xy);"+"c.a=1.;"+"}");postProcess.vao=glContext.createVertexArray();glContext.bindVertexArray(postProcess.vao);glContext.bindBuffer(glContext.ARRAY_BUFFER,glGeometryBuffer);const vertexByteStride=8;const pLocation=glContext.getAttribLocation(postProcess.shader,"p");glContext.enableVertexAttribArray(pLocation);glContext.vertexAttribPointer(pLocation,2,glContext.FLOAT,false,vertexByteStride,0)}function postProcessContextLost(){postProcess.shader=undefined;postProcess.texture=undefined;LOG("PostProcessPlugin: WebGL context lost")}function postProcessContextRestored(){initPostProcess();LOG("PostProcessPlugin: WebGL context restored")}function postProcessRender(){if(headlessMode||!glEnable)return;glFlush();glContext.bindFramebuffer(glContext.FRAMEBUFFER,null);glContext.useProgram(postProcess.shader);glContext.bindVertexArray(postProcess.vao);glContext.pixelStorei(glContext.UNPACK_FLIP_Y_WEBGL,true);glContext.disable(glContext.BLEND);glContext.activeTexture(glContext.TEXTURE0);glContext.bindTexture(glContext.TEXTURE_2D,postProcess.texture);if(includeMainCanvas){workCanvas.width=mainCanvas.width;workCanvas.height=mainCanvas.height;glCopyToContext(workContext);workContext.drawImage(mainCanvas,0,0);mainCanvas.width|=0;const dpr=getCanvasPixelRatio();mainContext.setTransform(dpr,0,0,dpr,0,0);glContext.texImage2D(glContext.TEXTURE_2D,0,glContext.RGBA,glContext.RGBA,glContext.UNSIGNED_BYTE,workCanvas)}else if(!feedbackTexture){glContext.texImage2D(glContext.TEXTURE_2D,0,glContext.RGBA,glContext.RGBA,glContext.UNSIGNED_BYTE,glCanvas)}const uniformLocation=name=>glContext.getUniformLocation(postProcess.shader,name);glContext.uniform1i(uniformLocation("iChannel0"),0);glContext.uniform1f(uniformLocation("iTime"),time);glContext.uniform3f(uniformLocation("iResolution"),mainCanvas.width,mainCanvas.height,1);glContext.drawArrays(glContext.TRIANGLE_STRIP,0,4);if(feedbackTexture){glContext.texImage2D(glContext.TEXTURE_2D,0,glContext.RGBA,glContext.RGBA,glContext.UNSIGNED_BYTE,glCanvas)}glContext.pixelStorei(glContext.UNPACK_FLIP_Y_WEBGL,false);glSetInstancedMode(true)}}}function postProcessBloomShader(threshold=.6,strength=1,size=6){ASSERT(isNumber(threshold)&&isNumber(strength)&&isNumber(size),"bloom settings must be numbers");ASSERT(size>0,"bloom size must be above zero");ASSERT(size<=32,"a bloom this wide takes a sample every few pixels of every ring, which is hundreds of samples a pixel",size);const rings=3;let code="",taps=0;for(let j=0;j<rings;++j){const radius=((j+.5)/rings)**.5*size;const count=max(5+2*j,round(2*radius))|1;taps+=count;code+=`
|
|
5
|
+
for (int k = 0; k < ${count}; ++k)
|
|
6
|
+
{
|
|
7
|
+
float a = float(k) * ${(2*PI/count).toFixed(7)}${j?" + "+(j*2.3999632).toFixed(7):""};
|
|
8
|
+
glow += max(vec3(0), texture(iChannel0, uv + vec2(cos(a), sin(a)) * ${radius.toFixed(4)} / iResolution.xy).rgb - ${threshold.toFixed(4)});
|
|
9
|
+
}`}return`
|
|
10
|
+
void mainImage(out vec4 color, vec2 pixel)
|
|
11
|
+
{
|
|
12
|
+
vec2 uv = pixel / iResolution.xy;
|
|
13
|
+
color = texture(iChannel0, uv);
|
|
14
|
+
vec3 glow = vec3(0);${code}
|
|
15
|
+
color.rgb += glow * ${(strength/taps).toFixed(6)};
|
|
16
|
+
}`}function postProcessBloom(threshold=.6,strength=1,size=6,includeMainCanvas=false){return new PostProcessPlugin(postProcessBloomShader(threshold,strength,size),includeMainCanvas)}let lightSystem;class LightSystemPlugin{constructor(textureSize,ambientColor){ASSERT(!lightSystem,"LightSystemPlugin already initialized");ASSERT(!postProcess,"LightSystemPlugin must be created before PostProcessPlugin");lightSystem=this;this.enabled=true;this.ambientColor=(ambientColor||BLACK).copy();this.textureSize=textureSize?textureSize.copy():undefined;this.texture=undefined;this.lightShader=undefined;this.compositeShader=undefined;this.lightVAO=undefined;this.compositeVAO=undefined;initLightSystem();engineAddPlugin(undefined,lightSystemRender,lightSystemContextLost,lightSystemContextRestored);function initLightSystem(){if(headlessMode)return;if(!glEnable){console.warn("LightSystemPlugin: WebGL not enabled!");return}if(!lightSystem.textureSize)lightSystem.textureSize=mainCanvasSize.copy();lightSystem.texture=glContext.createTexture();glContext.bindTexture(glContext.TEXTURE_2D,lightSystem.texture);glContext.texImage2D(glContext.TEXTURE_2D,0,glContext.RGBA,lightSystem.textureSize.x,lightSystem.textureSize.y,0,glContext.RGBA,glContext.UNSIGNED_BYTE,null);glContext.texParameteri(glContext.TEXTURE_2D,glContext.TEXTURE_MAG_FILTER,glContext.LINEAR);glContext.texParameteri(glContext.TEXTURE_2D,glContext.TEXTURE_MIN_FILTER,glContext.LINEAR);glContext.texParameteri(glContext.TEXTURE_2D,glContext.TEXTURE_WRAP_S,glContext.CLAMP_TO_EDGE);glContext.texParameteri(glContext.TEXTURE_2D,glContext.TEXTURE_WRAP_T,glContext.CLAMP_TO_EDGE);lightSystem.lightShader=glCreateProgram("#version 300 es\n"+"precision highp float;"+"uniform mat4 m;"+"uniform vec2 lightPos;"+"uniform float radius;"+"in vec2 g;"+"out vec2 vWorldPos;"+"void main(){"+"vec2 worldP=lightPos+(g-.5)*2.*radius;"+"gl_Position=m*vec4(worldP,1,1);"+"vWorldPos=worldP;"+"}","#version 300 es\n"+"precision highp float;"+"uniform vec2 lightPos;"+"uniform float radius;"+"uniform float fadeRange;"+"uniform vec4 color;"+"in vec2 vWorldPos;"+"out vec4 c;"+"void main(){"+"float dist=distance(vWorldPos,lightPos);"+"float t=clamp((radius-dist)/max(fadeRange,1e-6),0.,1.);"+"c=vec4(color.rgb*t*color.a,1.);"+"}");lightSystem.compositeShader=glCreateProgram("#version 300 es\n"+"precision highp float;"+"in vec2 p;"+"void main(){"+"gl_Position=vec4(p+p-1.,1,1);"+"}","#version 300 es\n"+"precision highp float;"+"uniform sampler2D s;"+"uniform vec3 iResolution;"+"out vec4 c;"+"void main(){"+"vec2 uv=gl_FragCoord.xy/iResolution.xy;"+"c=vec4(texture(s,uv).rgb,1.);"+"}");lightSystem.lightVAO=glContext.createVertexArray();glContext.bindVertexArray(lightSystem.lightVAO);glContext.bindBuffer(glContext.ARRAY_BUFFER,glGeometryBuffer);const gLight=glContext.getAttribLocation(lightSystem.lightShader,"g");glContext.enableVertexAttribArray(gLight);glContext.vertexAttribPointer(gLight,2,glContext.FLOAT,false,8,0);lightSystem.compositeVAO=glContext.createVertexArray();glContext.bindVertexArray(lightSystem.compositeVAO);glContext.bindBuffer(glContext.ARRAY_BUFFER,glGeometryBuffer);const pComp=glContext.getAttribLocation(lightSystem.compositeShader,"p");glContext.enableVertexAttribArray(pComp);glContext.vertexAttribPointer(pComp,2,glContext.FLOAT,false,8,0)}function lightSystemRender(){if(headlessMode||!glEnable)return;if(!lightSystem.enabled)return;if(!lightSystem.texture)return;glFlush();const prevAdditive=glAdditive;const ac=lightSystem.ambientColor;glContext.bindFramebuffer(glContext.FRAMEBUFFER,glFramebuffer);glContext.framebufferTexture2D(glContext.FRAMEBUFFER,glContext.COLOR_ATTACHMENT0,glContext.TEXTURE_2D,lightSystem.texture,0);glContext.viewport(0,0,lightSystem.textureSize.x,lightSystem.textureSize.y);glContext.clearColor(ac.r,ac.g,ac.b,ac.a);glContext.clear(glContext.COLOR_BUFFER_BIT);setAdditiveBlendMode();glContext.enable(glContext.BLEND);glContext.blendFunc(glContext.ONE,glContext.ONE);for(const o of engineObjects)o.destroyed||o.renderLight();glFlush();glContext.bindFramebuffer(glContext.FRAMEBUFFER,null);glContext.viewport(0,0,glCanvas.width,glCanvas.height);glContext.useProgram(lightSystem.compositeShader);glContext.bindVertexArray(lightSystem.compositeVAO);glContext.activeTexture(glContext.TEXTURE0);glContext.bindTexture(glContext.TEXTURE_2D,lightSystem.texture);const cs=lightSystem.compositeShader;glContext.uniform1i(glContext.getUniformLocation(cs,"s"),0);glContext.uniform3f(glContext.getUniformLocation(cs,"iResolution"),mainCanvas.width,mainCanvas.height,1);glContext.blendFunc(glContext.DST_COLOR,glContext.ZERO);glContext.drawArrays(glContext.TRIANGLE_STRIP,0,4);if(glActiveTexture)glContext.bindTexture(glContext.TEXTURE_2D,glActiveTexture);setAdditiveBlendMode(prevAdditive);glSetInstancedMode(true)}function lightSystemContextLost(){lightSystem.texture=undefined;lightSystem.lightShader=undefined;lightSystem.compositeShader=undefined;lightSystem.lightVAO=undefined;lightSystem.compositeVAO=undefined;LOG("LightSystemPlugin: WebGL context lost")}function lightSystemContextRestored(){initLightSystem();LOG("LightSystemPlugin: WebGL context restored")}}drawLight(light){if(headlessMode||!glEnable||!this.lightShader)return;glFlush();glContext.useProgram(this.lightShader);glContext.bindVertexArray(this.lightVAO);const s=vec2(2*cameraScale).divide(mainCanvasSize);const rotatedCam=cameraPos.rotate(-cameraAngle);const p=vec2(-1).subtract(rotatedCam.multiply(s));const ca=cos(cameraAngle);const sa=sin(cameraAngle);const transform=[s.x*ca,s.y*sa,0,0,-s.x*sa,s.y*ca,0,0,1,1,1,0,p.x,p.y,0,1];const ls=this.lightShader;glContext.uniformMatrix4fv(glContext.getUniformLocation(ls,"m"),false,transform);glContext.uniform2f(glContext.getUniformLocation(ls,"lightPos"),light.pos.x,light.pos.y);glContext.uniform1f(glContext.getUniformLocation(ls,"radius"),light.radius);glContext.uniform1f(glContext.getUniformLocation(ls,"fadeRange"),light.fadeRange);const c=light.color;glContext.uniform4f(glContext.getUniformLocation(ls,"color"),c.r,c.g,c.b,c.a);glContext.drawArrays(glContext.TRIANGLE_STRIP,0,4);glSetInstancedMode(true)}}class Light extends EngineObject{constructor(pos,radius,color,fadeRange){super(pos,vec2(1),undefined,0,color);ASSERT(isNumber(radius)&&radius>=0,"Light radius must be a non-negative number");ASSERT(fadeRange===undefined||isNumber(fadeRange)&&fadeRange>=0,"Light fadeRange must be a non-negative number when provided");this.radius=radius;this.fadeRange=fadeRange===undefined?radius:fadeRange}render(){}renderLight(){lightSystem&&lightSystem.drawLight(this)}}class ZzFXMusic extends Sound{constructor(zzfxMusic){super(undefined);if(!soundEnable||headlessMode)return;this.randomness=0;super.sampleChannels=zzfxM(...zzfxMusic);this.loadedPercent=1;this.onloadCallback?.(this)}}function zzfxM(instruments,patterns,sequence,BPM=125){let i,j,k;let instrumentParameters;let note;let sample;let patternChannel;let notFirstBeat;let stop;let instrument;let attenuation;let outSampleOffset;let isSequenceEnd;let sampleOffset=0;let nextSampleOffset;let sampleBuffer=[];let leftChannelBuffer=[];let rightChannelBuffer=[];let channelIndex=0;let panning=0;let hasMore=1;let sampleCache={};let beatLength=audioDefaultSampleRate/BPM*60>>2;for(;hasMore;channelIndex++){sampleBuffer=[hasMore=notFirstBeat=outSampleOffset=0];sequence.forEach((patternIndex,sequenceIndex)=>{patternChannel=patterns[patternIndex][channelIndex]||[0,0,0];hasMore|=patterns[patternIndex][channelIndex]&&1;nextSampleOffset=outSampleOffset+(patterns[patternIndex][0].length-2-(notFirstBeat?0:1))*beatLength;isSequenceEnd=sequenceIndex===sequence.length-1;for(i=2,k=outSampleOffset;i<patternChannel.length+isSequenceEnd;notFirstBeat=++i){note=patternChannel[i];stop=i===patternChannel.length+isSequenceEnd-1&&isSequenceEnd||instrument!==(patternChannel[0]||0)||note|0;for(j=0;j<beatLength&¬FirstBeat;j++>beatLength-99&&stop&&attenuation<1?attenuation+=1/99:0){sample=(1-attenuation)*sampleBuffer[sampleOffset++]/2||0;leftChannelBuffer[k]=(leftChannelBuffer[k]||0)-sample*panning+sample;rightChannelBuffer[k]=(rightChannelBuffer[k++]||0)+sample*panning+sample}if(note){attenuation=note%1;panning=patternChannel[1]||0;if(note|=0){sampleBuffer=sampleCache[[instrument=patternChannel[sampleOffset=0]||0,note]]=sampleCache[[instrument,note]]||(instrumentParameters=[...instruments[instrument]],instrumentParameters[2]=(instrumentParameters[2]||220)*2**(note/12-1),note>0?zzfxG(...instrumentParameters):[])}}}outSampleOffset=nextSampleOffset})}return[leftChannelBuffer,rightChannelBuffer]}function audioParamRamp(param,value,fadeTime=0){ASSERT(fadeTime>=0,"fadeTime must be positive or zero");const startTime=audioContext.currentTime;param.cancelScheduledValues(startTime);if(fadeTime){param.setValueAtTime(param.value,startTime);param.linearRampToValueAtTime(value,startTime+fadeTime)}else param.value=value}class AudioEffect{constructor(mix=1){ASSERT(isNumber(mix),"mix must be a number");this.input=audioContext.createGain();this.output=audioContext.createGain();this.dryGain=audioContext.createGain();this.wetGain=audioContext.createGain();this.mix=mix;this.input.connect(this.dryGain).connect(this.output);this.wetGain.connect(this.output);this.setMix(mix);this.output.connect(audioMasterGain)}setMix(mix,fadeTime=0){ASSERT(isNumber(mix),"mix must be a number");this.mix=mix=clamp(mix);this.rampParam(this.dryGain.gain,1-mix,fadeTime);this.rampParam(this.wetGain.gain,mix,fadeTime)}rampParam(param,value,fadeTime=0){audioParamRamp(param,value,fadeTime);if(!fadeTime)return;const keepAlive=new ConstantSourceNode(audioContext,{offset:0});keepAlive.connect(this.input);keepAlive.onended=()=>keepAlive.disconnect();keepAlive.start();keepAlive.stop(audioContext.currentTime+fadeTime)}connect(target){const node=target&&"input"in target?target.input:target;ASSERT(node&&typeof node.connect==="function","target must be an AudioEffect or AudioNode");this.output.disconnect();this.output.connect(node);return target}disconnect(){this.output.disconnect()}connectEffect(first,last=first){this.input.connect(first);last.connect(this.wetGain)}}class AudioFilter extends AudioEffect{constructor(type="lowpass",frequency=1e3,q=1,mix=1){super(mix);ASSERT(isNumber(frequency)&&frequency>=0,"frequency must be positive or zero");ASSERT(isNumber(q),"q must be a number");this.node=audioContext.createBiquadFilter();this.node.type=type;this.node.frequency.value=frequency;this.node.Q.value=q;this.connectEffect(this.node)}setFrequency(frequency,fadeTime=0){ASSERT(isNumber(frequency)&&frequency>=0,"frequency must be positive or zero");this.rampParam(this.node.frequency,frequency,fadeTime)}setQ(q,fadeTime=0){ASSERT(isNumber(q),"q must be a number");this.rampParam(this.node.Q,q,fadeTime)}}class AudioReverb extends AudioEffect{constructor(duration=2,decay=2,mix=.5){super(mix);this.node=audioContext.createConvolver();this.setRoom(duration,decay);this.connectEffect(this.node)}setRoom(duration,decay=2){ASSERT(isNumber(duration)&&duration>0,"duration must be positive");ASSERT(isNumber(decay)&&decay>0,"decay must be positive");this.node.buffer=this.createImpulse(duration,decay)}createImpulse(duration,decay){const sampleRate=audioContext.sampleRate;const length=max(1,sampleRate*duration|0);const buffer=audioContext.createBuffer(2,length,sampleRate);for(let channel=2;channel--;){const samples=buffer.getChannelData(channel);for(let i=length;i--;)samples[i]=rand(-1,1)*(1-i/length)**decay}return buffer}}class AudioDelay extends AudioEffect{constructor(time=.3,feedback=.4,mix=.5){super(mix);this.node=audioContext.createDelay(5);this.feedbackGain=audioContext.createGain();this.node.connect(this.feedbackGain).connect(this.node);this.connectEffect(this.node);this.setTime(time);this.setFeedback(feedback)}setTime(time,fadeTime=0){ASSERT(isNumber(time)&&time>=0&&time<=5,"time must be between 0 and 5");this.rampParam(this.node.delayTime,time,fadeTime)}setFeedback(feedback,fadeTime=0){ASSERT(isNumber(feedback),"feedback must be a number");this.rampParam(this.feedbackGain.gain,clamp(feedback,0,.95),fadeTime)}}class AudioDistortion extends AudioEffect{constructor(amount=.5,mix=1){super(mix);this.node=audioContext.createWaveShaper();this.node.oversample="2x";this.amount=amount;this.setAmount(amount);this.connectEffect(this.node)}setAmount(amount){ASSERT(isNumber(amount),"amount must be a number");this.amount=amount=clamp(amount);const drive=100*amount*amount;const samples=1024;const curve=new Float32Array(samples);for(let i=samples;i--;){const x=i*2/(samples-1)-1;curve[i]=(1+drive)*x/(1+drive*abs(x))}this.node.curve=curve}}class AudioCompressor extends AudioEffect{constructor(threshold=-24,ratio=12,mix=1){super(mix);ASSERT(isNumber(threshold),"threshold must be a number");ASSERT(isNumber(ratio)&&ratio>=1,"ratio must be 1 or more");this.node=audioContext.createDynamicsCompressor();this.node.threshold.value=threshold;this.node.ratio.value=ratio;this.connectEffect(this.node)}setThreshold(threshold,fadeTime=0){ASSERT(isNumber(threshold),"threshold must be a number");this.rampParam(this.node.threshold,threshold,fadeTime)}setRatio(ratio,fadeTime=0){ASSERT(isNumber(ratio)&&ratio>=1,"ratio must be 1 or more");this.rampParam(this.node.ratio,ratio,fadeTime)}}let uiSystem;let uiDebug=0;function uiSetDebug(debugMode){uiDebug=typeof debugMode==="boolean"?debugMode?1:0:debugMode}class UISystemPlugin{constructor(context=mainContext){ASSERT(!uiSystem,"UI system already initialized");uiSystem=this;this.activateOnPress=false;this.defaultColor=WHITE;this.defaultLineColor=BLACK;this.defaultTextColor=BLACK;this.defaultButtonColor=hsl(0,0,.7);this.defaultHoverColor=hsl(0,0,.9);this.defaultDisabledColor=hsl(0,0,.3);this.defaultGradientColor=undefined;this.defaultLineWidth=4;this.defaultCornerRadius=0;this.defaultTextFitScale=.8;this.defaultFont=fontDefault;this.defaultSoundPress=undefined;this.defaultSoundRelease=undefined;this.defaultSoundClick=undefined;this.defaultShadowColor=CLEAR_BLACK;this.defaultShadowBlur=5;this.defaultShadowOffset=vec2(5);this.nativeHeight=0;this.navigationObject=undefined;this.navigationTimer=new Timer(undefined,true);this.navigationDelay=.2;this.navigationDirection=1;this.navigationMode=false;this.uiObjects=[];this.uiContext=context;this.activeObject=undefined;this.hoverObject=undefined;this.lastHoverObject=undefined;this.confirmDialog=undefined;this._keyInputObject=undefined;this._onKeyDown=e=>this._keyInputObject?.onKeyDown(e);engineAddPlugin(uiUpdate,uiRender);function updateTransforms(o){let targetPos,targetSize;if(o.parent){targetPos=o.parent.nativePos;targetSize=o.parent.size}else{targetPos=uiSystem.screenToNative(mainCanvasSize.scale(.5));targetSize=uiSystem.nativeHeight?vec2(mainCanvasSize.x*uiSystem.nativeHeight/mainCanvasSize.y,uiSystem.nativeHeight):mainCanvasSize}const a=o.anchor;o.nativePos=targetPos.add(targetSize.multiply(a).scale(.5)).subtract(o.size.multiply(a).scale(.5)).add(o.localPos)}function uiUpdate(){if(uiSystem.activeObject&&!uiSystem.activeObject.visible)uiSystem.activeObject=undefined;uiSystem.lastHoverObject=uiSystem.hoverObject;uiSystem.hoverObject=undefined;if(mouseWasPressed(0)){uiSystem.navigationMode=false;uiSystem.navigationObject=undefined}if(uiSystem.keyInputObject){uiSystem.activeObject=uiSystem.keyInputObject;uiSystem.hoverObject=uiSystem.keyInputObject;uiSystem.navigationMode=false;uiSystem.navigationObject=undefined}const navigableObjects=uiSystem.getNavigableObjects();if(!navigableObjects.length)uiSystem.navigationObject=undefined;else if(!uiSystem.keyInputObject){if(!navigableObjects.includes(uiSystem.navigationObject))uiSystem.navigationObject=undefined;if(!isTouchDevice)if(uiSystem.navigationMode&&!uiSystem.navigationObject){uiSystem.navigationObject=navigableObjects.find(o=>o.navigationAutoSelect)}if(!uiSystem.navigationTimer.active()){const direction=sign(uiSystem.getNavigationDirection());if(direction){let newNavigationObject;if(!uiSystem.navigationObject){newNavigationObject=navigableObjects.find(o=>o.navigationAutoSelect);if(!newNavigationObject){const newIndex=direction>0?0:navigableObjects.length-1;newNavigationObject=navigableObjects[newIndex]}}else{const currentIndex=navigableObjects.indexOf(uiSystem.navigationObject);const newIndex=mod(currentIndex+direction,navigableObjects.length);newNavigationObject=navigableObjects[newIndex]}if(uiSystem.navigationObject!==newNavigationObject){uiSystem.navigationMode=true;uiSystem.hoverObject=undefined;uiSystem.navigationObject=newNavigationObject;uiSystem.navigationTimer.set(uiSystem.navigationDelay);newNavigationObject.soundPress&&newNavigationObject.soundPress.play()}}}if(uiSystem.navigationObject)if(uiSystem.getNavigationWasPressed())uiSystem.navigationObject.navigatePressed()}for(let i=uiSystem.uiObjects.length;i--;){const o=uiSystem.uiObjects[i];o.parent||updateObject(o)}uiSystem.uiObjects=uiSystem.uiObjects.filter(o=>!o.destroyed);function updateObject(o){if(o.destroyed||!o.visible)return;updateTransforms(o);for(let i=o.children.length;i--;){const child=o.children[i];child&&updateObject(child)}if(!o.destroyed)o.update()}}function uiRender(){const context=uiSystem.uiContext;context.save();if(uiSystem.nativeHeight){const s=mainCanvasSize.y/uiSystem.nativeHeight;context.translate(-s*mainCanvasSize.x/2,0);context.scale(s,s);context.translate(mainCanvasSize.x/2/s,0)}function renderObject(o){if(!o.visible)return;updateTransforms(o);o.render();for(const c of o.children)renderObject(c)}uiSystem.uiObjects.forEach(o=>o.parent||renderObject(o));if(uiDebug>0){function renderDebug(o,visible=true){visible&&=!!o.visible;updateTransforms(o);o.renderDebug(visible);for(const c of o.children)renderDebug(c,visible)}uiSystem.uiObjects.forEach(o=>o.parent||renderDebug(o))}context.restore()}}drawRect(pos,size,color=WHITE,lineWidth=0,lineColor=BLACK,cornerRadius=0,gradientColor,shadowColor=BLACK,shadowBlur=0,shadowOffset=vec2()){ASSERT(isVector2(pos),"pos must be a vec2");ASSERT(isVector2(size),"size must be a vec2");ASSERT(isColor(color),"color must be a color");ASSERT(isNumber(lineWidth),"lineWidth must be a number");ASSERT(isColor(lineColor),"lineColor must be a color");ASSERT(isNumber(cornerRadius),"cornerRadius must be a number");const context=uiSystem.uiContext;if(gradientColor){const g=context.createLinearGradient(pos.x,pos.y-size.y/2,pos.x,pos.y+size.y/2);const c=color.toString();g.addColorStop(0,c);g.addColorStop(.5,gradientColor.toString());g.addColorStop(1,c);context.fillStyle=g}else context.fillStyle=color.toString();if(shadowBlur||shadowOffset.x||shadowOffset.y)if(shadowColor.a>0){context.shadowColor=shadowColor.toString();context.shadowBlur=shadowBlur;context.shadowOffsetX=shadowOffset.x;context.shadowOffsetY=shadowOffset.y}context.beginPath();if(cornerRadius&&context["roundRect"])context["roundRect"](pos.x-size.x/2,pos.y-size.y/2,size.x,size.y,cornerRadius);else context.rect(pos.x-size.x/2,pos.y-size.y/2,size.x,size.y);context.fill();context.shadowColor="#0000";if(lineWidth&&lineColor.a>0){context.strokeStyle=lineColor.toString();context.lineWidth=lineWidth;context.stroke()}}drawLine(posA,posB,lineWidth=uiSystem.defaultLineWidth,lineColor=uiSystem.defaultLineColor){ASSERT(isVector2(posA),"posA must be a vec2");ASSERT(isVector2(posB),"posB must be a vec2");ASSERT(isNumber(lineWidth),"lineWidth must be a number");ASSERT(isColor(lineColor),"lineColor must be a color");const context=uiSystem.uiContext;context.strokeStyle=lineColor.toString();context.lineWidth=lineWidth;context.beginPath();context.lineTo(posA.x,posA.y);context.lineTo(posB.x,posB.y);context.stroke()}drawTile(pos,size,tileInfo,color=uiSystem.defaultColor,angle=0,mirror=false,shadowColor=BLACK,shadowBlur=0,shadowOffset=vec2()){const context=uiSystem.uiContext;if(shadowBlur||shadowOffset.x||shadowOffset.y)if(shadowColor.a>0){context.shadowColor=shadowColor.toString();context.shadowBlur=shadowBlur;context.shadowOffsetX=shadowOffset.x;context.shadowOffsetY=shadowOffset.y}drawTile(pos,size,tileInfo,color,angle,mirror,CLEAR_BLACK,false,true,context);context.shadowColor="#0000"}drawText(text,pos,size,color=uiSystem.defaultColor,lineWidth=uiSystem.defaultLineWidth,lineColor=uiSystem.defaultLineColor,align="center",font=uiSystem.defaultFont,fontStyle="",applyMaxWidth=true,textShadow=undefined,shadowColor=BLACK,shadowBlur=0,shadowOffset=vec2()){const context=uiSystem.uiContext;if(shadowColor.a>0){if(textShadow)drawTextScreen(text,pos.add(textShadow),size.y,shadowColor,lineWidth,lineColor,align,font,fontStyle,applyMaxWidth?size.x:undefined,0,context);if(shadowBlur||shadowOffset.x||shadowOffset.y){context.shadowColor=shadowColor.toString();context.shadowBlur=shadowBlur;context.shadowOffsetX=shadowOffset.x;context.shadowOffsetY=shadowOffset.y}}drawTextScreen(text,pos,size.y,color,lineWidth,lineColor,align,font,fontStyle,applyMaxWidth?size.x:undefined,0,context);context.shadowColor="#0000"}setupDragAndDrop(onDrop,onDragEnter,onDragLeave,onDragOver){if(this._dragListeners)for(const[type,listener]of this._dragListeners)document.removeEventListener(type,listener);this._dragListeners=[];const setCallback=(callback,listenerType)=>{const listener=e=>{e.preventDefault();callback&&callback(e)};document.addEventListener(listenerType,listener);this._dragListeners.push([listenerType,listener])};setCallback(onDrop,"drop");setCallback(onDragEnter,"dragenter");setCallback(onDragLeave,"dragleave");setCallback(onDragOver,"dragover")}screenToNative(pos){if(!uiSystem.nativeHeight)return pos;const s=mainCanvasSize.y/uiSystem.nativeHeight;const sInv=1/s;const p=pos.copy();p.x+=s*mainCanvasSize.x/2;p.x*=sInv;p.y*=sInv;p.x-=sInv*mainCanvasSize.x/2;return p}get keyInputObject(){return this._keyInputObject}set keyInputObject(obj){const had=!!this._keyInputObject;this._keyInputObject=obj;if(!had&&obj)document.addEventListener("keydown",this._onKeyDown);else if(had&&!obj)document.removeEventListener("keydown",this._onKeyDown)}destroyObjects(){for(const o of this.uiObjects)o.parent||o.destroy();this.uiObjects=this.uiObjects.filter(o=>!o.destroyed);this.activeObject=undefined;this.hoverObject=undefined;this.lastHoverObject=undefined;this.keyInputObject=undefined}getNavigableObjects(){function getNavigableRecursive(o){if(!o.visible||o.disabled)return;if(o.isInteractive()&&o.navigationIndex!==undefined)objects.push(o);for(let i=o.children.length;i--;)getNavigableRecursive(o.children[i])}let objects=[];for(let i=uiSystem.uiObjects.length;i--;){const o=uiSystem.uiObjects[i];if(uiSystem.confirmDialog&&o!==uiSystem.confirmDialog)continue;o.parent||getNavigableRecursive(o)}objects.sort((a,b)=>a.navigationIndex-b.navigationIndex);return objects}getNavigationDirection(){const vertical=uiSystem.navigationDirection===1;const both=uiSystem.navigationDirection===2;if(isUsingGamepad){const stick=gamepadStick(0,gamepadPrimary);const dpad=gamepadDpad(gamepadPrimary);if(both)return-(stick.y||dpad.y)||(stick.x||dpad.x);return vertical?-(stick.y||dpad.y):stick.x||dpad.x}const up="ArrowUp",down="ArrowDown",left="ArrowLeft",right="ArrowRight";if(both){return keyIsDown(up)||keyIsDown(left)?-1:keyIsDown(down)||keyIsDown(right)?1:0}const back=vertical?up:left;const forward=vertical?down:right;return keyIsDown(back)?-1:keyIsDown(forward)?1:0}getNavigationOtherDirection(){if(uiSystem.navigationDirection===2)return 0;const vertical=uiSystem.navigationDirection===1;if(isUsingGamepad){const stick=gamepadStick(0,gamepadPrimary);const dpad=gamepadDpad(gamepadPrimary);return!vertical?stick.y||dpad.y:stick.x||dpad.x}const back=!vertical?"ArrowUp":"ArrowLeft";const forward=!vertical?"ArrowDown":"ArrowRight";return keyIsDown(back)?-1:keyIsDown(forward)?1:0}getNavigationWasPressed(){return isUsingGamepad?gamepadWasPressed(0,gamepadPrimary):keyWasPressed("Space")||keyWasPressed("Enter")}showConfirmDialog(text="Are you sure?",yesCallback,noCallback,size=vec2(500,250),exitKey="Escape"){ASSERT(!uiSystem.confirmDialog);const savedNavigationDirection=uiSystem.navigationDirection;uiSystem.navigationDirection=2;const confirmMenu=new UIObject(vec2(),size);uiSystem.confirmDialog=confirmMenu;confirmMenu.onRender=()=>{const backgroundColor=hsl(0,0,0,.7);uiSystem.drawRect(vec2(),vec2(1e9),backgroundColor)};confirmMenu.onUpdate=()=>{if(keyWasPressed(exitKey))closeMenu()};confirmMenu.isMouseOverlapping=()=>true;const gap=50;const textTitle=new UIText(vec2(0,-50),vec2(size.x-gap,70),text);confirmMenu.addChild(textTitle);const buttonYes=new UIButton(vec2(-80,50),vec2(120,70),"Yes");buttonYes.textHeight=40;buttonYes.navigationIndex=1;buttonYes.hoverColor=hsl(0,1,.5);buttonYes.onClick=()=>{closeMenu();yesCallback&&yesCallback()};confirmMenu.addChild(buttonYes);const buttonNo=new UIButton(vec2(80,50),vec2(120,70),"No");buttonNo.textHeight=40;buttonNo.navigationIndex=2;buttonNo.navigationAutoSelect=true;buttonNo.onClick=()=>{closeMenu();noCallback&&noCallback()};confirmMenu.addChild(buttonNo);function closeMenu(){ASSERT(uiSystem.confirmDialog===confirmMenu);confirmMenu.destroy();uiSystem.confirmDialog=undefined;uiSystem.navigationDirection=savedNavigationDirection;inputClear()}return confirmMenu}}class UIObject{constructor(pos=vec2(),size=vec2()){ASSERT(isVector2(pos),"ui object pos must be a vec2");ASSERT(isVector2(size),"ui object size must be a vec2");this.localPos=pos.copy();this.nativePos=pos.copy();this.size=size.copy();this.color=uiSystem.defaultColor.copy();this.activeColor=undefined;this.text=undefined;this.disabledColor=uiSystem.defaultDisabledColor.copy();this.disabled=false;this.textColor=uiSystem.defaultTextColor.copy();this.hoverColor=uiSystem.defaultHoverColor.copy();this.lineColor=uiSystem.defaultLineColor.copy();this.gradientColor=uiSystem.defaultGradientColor?uiSystem.defaultGradientColor.copy():undefined;this.lineWidth=uiSystem.defaultLineWidth;this.cornerRadius=uiSystem.defaultCornerRadius;this.font=uiSystem.defaultFont;this.fontStyle=undefined;this.textWidth=undefined;this.textHeight=undefined;this.textFitScale=uiSystem.defaultTextFitScale;this.textShadow=undefined;this.textLineColor=uiSystem.defaultLineColor.copy();this.textLineWidth=0;this.visible=true;this.children=[];this.parent=undefined;this.extraTouchSize=0;this.soundPress=uiSystem.defaultSoundPress;this.soundRelease=uiSystem.defaultSoundRelease;this.soundClick=uiSystem.defaultSoundClick;this.interactive=false;this.dragActivate=false;this.canBeHover=true;this.shadowColor=uiSystem.defaultShadowColor?.copy();this.shadowBlur=uiSystem.defaultShadowBlur;this.shadowOffset=uiSystem.defaultShadowOffset?.copy();this.navigationIndex=undefined;this.navigationAutoSelect=false;this.anchor=vec2();uiSystem.uiObjects.push(this)}addChild(child){ASSERT(!child.parent&&!this.children.includes(child));this.children.push(child);child.parent=this;return child}removeChild(child){ASSERT(child.parent===this&&this.children.includes(child));this.children.splice(this.children.indexOf(child),1);child.parent=undefined}destroy(){if(this.destroyed)return;if(uiSystem.activeObject===this)uiSystem.activeObject=undefined;if(uiSystem.hoverObject===this)uiSystem.hoverObject=undefined;if(uiSystem.lastHoverObject===this)uiSystem.lastHoverObject=undefined;if(uiSystem.navigationObject===this)uiSystem.navigationObject=undefined;if(uiSystem.keyInputObject===this)uiSystem.keyInputObject=undefined;this.destroyed=1;this.parent?.removeChild(this);for(const child of this.children){child.parent=undefined;child.destroy()}this.children.length=0}isMouseOverlapping(){if(!mouseInWindow)return false;const size=!isTouchDevice?this.size:this.size.add(vec2(this.extraTouchSize||0));const pos=uiSystem.screenToNative(mousePosScreen);return isOverlapping(this.nativePos,size,pos)}update(){this.onUpdate();if(this.disabled){if(this===uiSystem.activeObject)uiSystem.activeObject=undefined;if(this===uiSystem.keyInputObject)uiSystem.keyInputObject=undefined}if(uiSystem.keyInputObject)return;const wasHover=uiSystem.lastHoverObject===this;const isActive=this.isActiveObject();const mouseDown=mouseIsDown(0);const mousePress=this.dragActivate?mouseDown:mouseWasPressed(0);if(this.canBeHover)if(!uiSystem.navigationMode)if(mousePress||isActive||!mouseDown&&!isTouchDevice)if(!uiSystem.hoverObject&&this.isMouseOverlapping())uiSystem.hoverObject=this;if(this.isHoverObject()){if(!this.disabled){if(mousePress){if(this.interactive){if(!this.dragActivate||(!wasHover||mouseWasPressed(0)))this.onPress();this.soundPress&&this.soundPress.play();if(uiSystem.activeObject&&!isActive)uiSystem.activeObject.onRelease();uiSystem.activeObject=this;if(uiSystem.activateOnPress)this.click(!this.soundPress)}}if(!uiSystem.activateOnPress)if(!mouseDown&&this.isActiveObject()&&this.interactive)this.click()}mousePress&&inputClearKey(0,0,0,1,0)}if(isActive)if(!mouseDown||this.dragActivate&&!this.isHoverObject()){this.onRelease();this.soundRelease&&this.soundRelease.play();uiSystem.activeObject=undefined}if(this.isHoverObject()!==wasHover)this.isHoverObject()?this.onEnter():this.onLeave()}render(){this.onRender();if(!this.size.x||!this.size.y)return;const isNavigationObject=this.isNavigationObject();const lineColor=isNavigationObject?this.color:this.interactive&&this.isActiveObject()&&!this.disabled?this.color:this.lineColor;const color=isNavigationObject?this.hoverColor:this.disabled?this.disabledColor:this.interactive?this.isActiveObject()?this.activeColor||this.hoverColor:this.isHoverObject()?this.hoverColor:this.color:this.color;const lineWidth=this.lineWidth*(isNavigationObject?1.5:1);uiSystem.drawRect(this.nativePos,this.size,color,lineWidth,lineColor,this.cornerRadius,this.gradientColor,this.shadowColor,this.shadowBlur,this.shadowOffset)}getTextSize(){return vec2(this.textWidth||this.textFitScale*this.size.x,this.textHeight||this.textFitScale*this.size.y)}navigatePressed(){this.click()}isHoverObject(){return uiSystem.hoverObject===this}isActiveObject(){return uiSystem.activeObject===this}isNavigationObject(){return uiSystem.navigationObject===this}isKeyInputObject(){return uiSystem.keyInputObject===this}isInteractive(){return this.interactive&&this.visible&&!this.disabled}toString(){let text="type = "+this.constructor.name;if(this.text)text+="\ntext = "+this.text;if(this.nativePos.x||this.nativePos.y)text+="\nnativePos = "+this.nativePos;if(this.localPos.x||this.localPos.y)text+="\nlocalPos = "+this.localPos;if(this.size.x||this.size.y)text+="\nsize = "+this.size;if(this.color)text+="\ncolor = "+this.color;return text}renderDebug(visible=true){const color=!visible?GREEN:this.isHoverObject()?YELLOW:this.disabled?PURPLE:this.interactive?RED:BLUE;uiSystem.drawRect(this.nativePos,this.size,CLEAR_BLACK,4,color)}click(playSound=true){this.onClick();if(playSound&&this.soundClick)this.soundClick.play()}onUpdate(){}onRender(){}onEnter(){}onLeave(){}onPress(){}onRelease(){}onClick(){}onChange(){}}class UIText extends UIObject{constructor(pos,size,text="",align="center",font=uiSystem.defaultFont){super(pos,size);ASSERT(isStringLike(text),"ui text must be a string");ASSERT(["left","center","right"].includes(align),"ui text align must be left, center, or right");ASSERT(isStringLike(font),"ui text font must be a string");this.text=text;this.align=align;this.font=font;this.canBeHover=false;this.color=CLEAR_BLACK;this.shadowColor=CLEAR_BLACK;this.gradientColor=undefined;this.lineWidth=0;this.textFitScale=1}render(){super.render();const textSize=this.getTextSize();uiSystem.drawText(this.text,this.nativePos,textSize,this.textColor,this.textLineWidth,this.textLineColor,this.align,this.font,this.fontStyle,true,this.textShadow,this.shadowColor,this.shadowBlur,this.shadowOffset)}}class UITextInput extends UIObject{constructor(pos,size,text=""){super(pos,size);ASSERT(isStringLike(text),"ui text must be a string");this.maxLength=0;this.text=text;this.interactive=true;this.canBeHover=true}click(){uiSystem.keyInputObject=this;this.onClick()}stopEditing(){if(!this.isKeyInputObject())return;if(this.soundRelease)this.soundRelease.play();uiSystem.activeObject=undefined;uiSystem.keyInputObject=undefined;this.onChange()}onKeyDown(e){const code=e.code,key=e.key;if(code==="Backspace")this.text=this.text.slice(0,-1);else if(code==="Enter"||code==="Escape")this.stopEditing();else if(key.length===1){if(!this.maxLength||this.text.length<this.maxLength)this.text+=key}}update(){super.update();if(!this.isKeyInputObject())return;if(mouseWasPressed(0)&&!this.isMouseOverlapping()||gamepadWasPressed(0,gamepadPrimary)){this.stopEditing();inputClearKey(0,0)}}render(){super.render();const textSize=this.getTextSize();let text=this.text;if(this.isKeyInputObject())text+=timeReal%1<.5?"█":"░";uiSystem.drawText(text,this.nativePos,textSize,this.textColor,this.textLineWidth,this.textLineColor,this.align,this.font,this.fontStyle,true,this.textShadow)}}class UITile extends UIObject{constructor(pos,size,tileInfo,color=WHITE,angle=0,mirror=false){super(pos,size);ASSERT(tileInfo instanceof TileInfo,"ui tile tileInfo must be a TileInfo");ASSERT(isColor(color),"ui tile color must be a color");ASSERT(isNumber(angle),"ui tile angle must be a number");this.tileInfo=tileInfo;this.angle=angle;this.mirror=mirror;this.color=color.copy();this.shadowColor=CLEAR_BLACK}render(){uiSystem.drawTile(this.nativePos,this.size,this.tileInfo,this.color,this.angle,this.mirror,this.shadowColor,this.shadowBlur,this.shadowOffset)}}class UIButton extends UIObject{constructor(pos,size,text="",color=uiSystem.defaultButtonColor){super(pos,size);ASSERT(isStringLike(text),"ui button must be a string");ASSERT(isColor(color),"ui button color must be a color");this.textOffset=vec2();this.text=text;this.color=color.copy();this.interactive=true}render(){super.render();const textSize=this.getTextSize();uiSystem.drawText(this.text,this.nativePos.add(this.textOffset),textSize,this.textColor,this.textLineWidth,this.textLineColor,this.align,this.font,this.fontStyle,true,this.textShadow)}}class UICheckbox extends UIObject{constructor(pos,size,checked=false,text="",color=uiSystem.defaultButtonColor){super(pos,size);ASSERT(isStringLike(text),"ui checkbox must be a string");ASSERT(isColor(color),"ui checkbox color must be a color");this.checked=checked;this.text=text;this.color=color.copy();this.interactive=true}click(){this.checked=!this.checked;this.onClick();this.onChange()}render(){super.render();if(this.checked){const p=this.cornerRadius/min(this.size.x,this.size.y)*2;const length=lerp(1,2**.5/2,p)/2;let s=this.size.scale(length);uiSystem.drawLine(this.nativePos.add(s.multiply(vec2(-1))),this.nativePos.add(s.multiply(vec2(1))),this.lineWidth,this.lineColor);uiSystem.drawLine(this.nativePos.add(s.multiply(vec2(-1,1))),this.nativePos.add(s.multiply(vec2(1,-1))),this.lineWidth,this.lineColor)}const textSize=this.getTextSize();const pos=this.nativePos.add(vec2(this.size.x,0));uiSystem.drawText(this.text,pos,textSize,this.textColor,this.textLineWidth,this.textLineColor,"left",this.font,this.fontStyle,false,this.textShadow)}}class UISlider extends UIObject{constructor(pos,size,value=.5,text="",color=uiSystem.defaultButtonColor,handleColor=WHITE){super(pos,size);ASSERT(isNumber(value),"ui slider value must be a number");ASSERT(isStringLike(text),"ui slider must be a string");ASSERT(isColor(color),"ui slider color must be a color");ASSERT(isColor(handleColor),"ui slider handleColor must be a color");this.value=value;this.handleColor=handleColor.copy();this.fillMode=false;this.text=text;this.color=color.copy();this.interactive=true}update(){super.update();if(!this.interactive)return;const oldValue=this.value;if(this.isActiveObject()){const isHorizontal=this.size.x>this.size.y;const handleSize=isHorizontal?this.size.y:this.size.x;const barSize=isHorizontal?this.size.x:this.size.y;const centerPos=isHorizontal?this.nativePos.x:this.nativePos.y;const handleWidth=barSize-handleSize;const p1=centerPos-handleWidth/2;const p2=centerPos+handleWidth/2;const p=uiSystem.screenToNative(mousePosScreen);this.value=isHorizontal?percent(p.x,p1,p2):percent(p.y,p2,p1)}else if(this.isNavigationObject()){const direction=uiSystem.getNavigationOtherDirection();if(!uiSystem.navigationTimer.active())this.value=clamp(this.value+direction*.01)}this.value===oldValue||this.onChange()}render(){super.render();const isHorizontal=this.size.x>this.size.y;const barWidth=isHorizontal?this.size.x:this.size.y;const handleWidth=isHorizontal?this.size.y:this.size.x;if(this.fillMode){const minWidth=min(handleWidth,this.cornerRadius*2);const progressWidth=lerp(minWidth,barWidth,this.value);const p=(progressWidth-barWidth)*(isHorizontal?.5:-.5);const pos=this.nativePos.add(isHorizontal?vec2(p,0):vec2(0,p));const color=this.disabled?this.disabledColor:this.handleColor;const drawSize=isHorizontal?vec2(progressWidth,this.size.y):vec2(this.size.x,progressWidth);uiSystem.drawRect(pos,drawSize,color,this.lineWidth,this.lineColor,this.cornerRadius,this.gradientColor)}else{const value=clamp(isHorizontal?this.value:1-this.value);const p=(barWidth-handleWidth)*(value-.5);const pos=this.nativePos.add(isHorizontal?vec2(p,0):vec2(0,p));const color=this.disabled?this.disabledColor:this.handleColor;const drawSize=vec2(handleWidth);uiSystem.drawRect(pos,drawSize,color,this.lineWidth,this.lineColor,this.cornerRadius,this.gradientColor)}const textSize=this.getTextSize();uiSystem.drawText(this.text,this.nativePos,textSize,this.textColor,this.textLineWidth,this.textLineColor,this.align,this.font,this.fontStyle,true,this.textShadow)}navigatePressed(){this.value=this.value?0:1;this.onChange();this.onRelease();super.navigatePressed()}}class UIVideo extends UIObject{constructor(pos,size,src,autoplay=false,loop=false,volume=1){super(pos,size||vec2());ASSERT(isStringLike(src),"video src must be a string");ASSERT(isNumber(volume),"video volume must be a number");this.color=BLACK;this.cornerRadius=0;this.volume=volume;this.video=document.createElement("video");this.video.loop=loop;this.video.volume=clamp(volume*soundVolume);this.video.muted=!soundEnable;this.video.style.display="none";this.video.src=src;document.body.appendChild(this.video);autoplay&&this.play()}async play(){try{await this.video.play()}catch(e){}}pause(){this.video.pause()}stop(){this.video.pause();this.video.currentTime=0}isLoading(){return this.video.readyState<this.video.HAVE_CURRENT_DATA}isPaused(){return this.video.paused}isPlaying(){return!this.isPaused()&&!this.hasEnded()&&!this.isLoading()}hasEnded(){return this.video.ended}setVolume(volume){this.volume=volume;this.video.volume=clamp(volume*soundVolume)}setPlaybackRate(rate){this.video.playbackRate=rate}getCurrentTime(){return this.video.currentTime||0}getDuration(){return this.video.duration||0}getVideoSize(){return vec2(this.video.videoWidth,this.video.videoHeight)}setTime(time){this.video.currentTime=clamp(time,0,this.getDuration())}update(){super.update();this.video.volume=clamp(this.volume*soundVolume)}render(){super.render();if(this.isLoading())return;const context=uiSystem.uiContext;const s=this.size;context.save();context.translate(this.nativePos.x,this.nativePos.y);context.drawImage(this.video,-s.x/2,-s.y/2,s.x,s.y);context.restore()}destroy(){if(this.destroyed)return;this.video.pause();this.video.remove();super.destroy()}}class UILayout extends UIObject{constructor(pos,columns=1,gap=10,padding=10,transparent=false){super(pos);ASSERT(isNumber(columns)&&columns>=1,"ui layout columns must be a number >= 1");ASSERT(isNumber(gap),"ui layout gap must be a number");ASSERT(isNumber(padding),"ui layout padding must be a number");this.columns=columns;this.gap=gap;this.padding=padding;if(transparent){this.color=CLEAR_BLACK;this.gradientColor=undefined;this.lineWidth=0;this.shadowColor=CLEAR_BLACK}this.relayout()}addChild(child){super.addChild(child);this.relayout();return child}removeChild(child){super.removeChild(child);this.relayout()}relayout(){const n=this.children.length;if(!n){this.size=vec2(this.padding*2);return}const cols=this.columns;const rows=ceil(n/cols);const colWidths=new Array(cols).fill(0);const rowHeights=new Array(rows).fill(0);for(let i=0;i<n;++i){const col=i%cols;const row=floor(i/cols);const child=this.children[i];colWidths[col]=max(colWidths[col],child.size.x);rowHeights[row]=max(rowHeights[row],child.size.y)}let contentWidth=this.gap*(cols-1);for(const w of colWidths)contentWidth+=w;let contentHeight=this.gap*(rows-1);for(const h of rowHeights)contentHeight+=h;const colOffsets=new Array(cols);let xAcc=0;for(let c=0;c<cols;++c){colOffsets[c]=xAcc;xAcc+=colWidths[c]}const rowOffsets=new Array(rows);let yAcc=0;for(let r=0;r<rows;++r){rowOffsets[r]=yAcc;yAcc+=rowHeights[r]}for(let i=0;i<n;++i){const col=i%cols;const row=floor(i/cols);const x=-contentWidth/2+colOffsets[col]+this.gap*col+colWidths[col]/2;const y=-contentHeight/2+rowOffsets[row]+this.gap*row+rowHeights[row]/2;this.children[i].localPos=vec2(x,y)}this.size=vec2(contentWidth+this.padding*2,contentHeight+this.padding*2)}}let box2d;let box2dDebug=false;function box2dSetDebug(enable){box2dDebug=enable}class Box2dObject extends EngineObject{constructor(pos=vec2(),size=vec2(),tileInfo,angle=0,color,bodyType=box2d.bodyTypeDynamic,renderOrder=0){super(pos,size,tileInfo,angle,color,renderOrder);const bodyDef=new box2d.instance.b2BodyDef;bodyDef.set_type(bodyType);bodyDef.set_position(box2d.vec2dTo(pos));bodyDef.set_angle(-angle);this.body=box2d.world.CreateBody(bodyDef);this.lineColor=BLACK;this.edgeLists=[];this.edgeLoops=[];this.body.object=this;box2d.objects.push(this)}destroy(){if(this.destroyed)return;ASSERT(this.body,"Box2dObject has no body to destroy");box2d.world.DestroyBody(this.body);const i=box2d.objects.indexOf(this);if(i>=0)box2d.objects.splice(i,1);super.destroy()}updatePhysics(){}render(){if(this.tileInfo)super.render();else this.drawFixtures(this.color,this.lineColor,this.lineWidth)}renderDebugInfo(){const isAsleep=!this.getIsAwake();const isStatic=this.getBodyType()===box2d.bodyTypeStatic;const color=rgb(isAsleep?1:0,isAsleep?1:0,isStatic?1:0,.5);this.drawFixtures(color)}drawFixtures(color=WHITE,lineColor=BLACK,lineWidth=.1,useWebGL,context){this.getFixtureList().forEach(fixture=>{const shape=box2d.castShapeObject(fixture.GetShape());if(shape.GetType()!==box2d.instance.b2Shape.e_edge){box2d.drawFixture(fixture,this.pos,this.angle,color,lineColor,lineWidth,useWebGL,context)}});this.edgeLists.forEach(points=>drawLineList(points,lineWidth,lineColor,false,this.pos,this.angle));this.edgeLoops.forEach(points=>drawLineList(points,lineWidth,lineColor,true,this.pos,this.angle))}beginContact(otherObject){}endContact(otherObject){}addShape(shape,density=1,friction=.2,restitution=0,isSensor=false){ASSERT(isNumber(density),"density must be a number");ASSERT(isNumber(friction),"friction must be a number");ASSERT(isNumber(restitution),"restitution must be a number");const fd=new box2d.instance.b2FixtureDef;fd.set_shape(shape);fd.set_density(density);fd.set_friction(friction);fd.set_restitution(restitution);fd.set_isSensor(isSensor);return this.body.CreateFixture(fd)}addBox(size=vec2(1),offset=vec2(),angle=0,density,friction,restitution,isSensor){ASSERT(isVector2(size),"size must be a Vector2");ASSERT(size.x>0&&size.y>0,"size must be positive");ASSERT(isVector2(offset),"offset must be a Vector2");ASSERT(isNumber(angle),"angle must be a number");const shape=new box2d.instance.b2PolygonShape;shape.SetAsBox(size.x/2,size.y/2,box2d.vec2dTo(offset),-angle);return this.addShape(shape,density,friction,restitution,isSensor)}addPoly(points,density,friction,restitution,isSensor){ASSERT(isArray(points),"points must be an array");function box2dCreatePolygonShape(points){ASSERT(3<=points.length&&points.length<=8);const buffer=box2d.instance._malloc(points.length*8);for(let i=0,offset=0;i<points.length;++i){box2d.instance.HEAPF32[buffer+offset>>2]=points[i].x;offset+=4;box2d.instance.HEAPF32[buffer+offset>>2]=points[i].y;offset+=4}const box2dPoints=box2d.instance.wrapPointer(buffer,box2d.instance.b2Vec2);const shape=new box2d.instance.b2PolygonShape;shape.Set(box2dPoints,points.length);box2d.instance._free(buffer);return shape}const shape=box2dCreatePolygonShape(points);return this.addShape(shape,density,friction,restitution,isSensor)}addRegularPoly(diameter=1,sides=8,density,friction,restitution,isSensor){ASSERT(isNumber(diameter)&&diameter>0,"diameter must be a positive number");ASSERT(isNumber(sides)&&sides>2,"sides must be a positive number greater than 2");const points=[];const radius=diameter/2;for(let i=sides;i--;)points.push(vec2(radius,0).rotate((i+.5)/sides*PI*2));return this.addPoly(points,density,friction,restitution,isSensor)}addRandomPoly(diameter=1,density,friction,restitution,isSensor){ASSERT(isNumber(diameter)&&diameter>0,"diameter must be a positive number");const sides=randInt(3,9);const points=[];const radius=diameter/2;for(let i=sides;i--;)points.push(vec2(rand(radius/2,radius*1.5),0).rotate(i/sides*PI*2));return this.addPoly(points,density,friction,restitution,isSensor)}addCircle(diameter=1,offset=vec2(),density,friction,restitution,isSensor){ASSERT(isNumber(diameter)&&diameter>0,"diameter must be a positive number");ASSERT(isVector2(offset),"offset must be a Vector2");const shape=new box2d.instance.b2CircleShape;shape.set_m_p(box2d.vec2dTo(offset));shape.set_m_radius(diameter/2);return this.addShape(shape,density,friction,restitution,isSensor)}addEdge(point1,point2,density,friction,restitution,isSensor){ASSERT(isVector2(point1),"point1 must be a Vector2");ASSERT(isVector2(point2),"point2 must be a Vector2");const shape=new box2d.instance.b2EdgeShape;shape.Set(box2d.vec2dTo(point1),box2d.vec2dTo(point2));return this.addShape(shape,density,friction,restitution,isSensor)}addEdgeList(points,density,friction,restitution,isSensor){ASSERT(isArray(points),"points must be an array");const fixtures=[],edgePoints=[];for(let i=0;i<points.length-1;++i){const shape=new box2d.instance.b2EdgeShape;points[i-1]&&shape.set_m_vertex0(box2d.vec2dTo(points[i-1]));points[i+0]&&shape.set_m_vertex1(box2d.vec2dTo(points[i+0]));points[i+1]&&shape.set_m_vertex2(box2d.vec2dTo(points[i+1]));points[i+2]&&shape.set_m_vertex3(box2d.vec2dTo(points[i+2]));const f=this.addShape(shape,density,friction,restitution,isSensor);fixtures.push(f);edgePoints.push(points[i].copy())}edgePoints.push(points[points.length-1].copy());this.edgeLists.push(edgePoints);return fixtures}addEdgeLoop(points,density,friction,restitution,isSensor){ASSERT(isArray(points),"points must be an array");const fixtures=[],edgePoints=[];const getPoint=i=>points[mod(i,points.length)];for(let i=0;i<points.length;++i){const shape=new box2d.instance.b2EdgeShape;shape.set_m_vertex0(box2d.vec2dTo(getPoint(i-1)));shape.set_m_vertex1(box2d.vec2dTo(getPoint(i+0)));shape.set_m_vertex2(box2d.vec2dTo(getPoint(i+1)));shape.set_m_vertex3(box2d.vec2dTo(getPoint(i+2)));const f=this.addShape(shape,density,friction,restitution,isSensor);fixtures.push(f);edgePoints.push(points[i].copy())}this.edgeLoops.push(edgePoints);return fixtures}destroyFixture(fixture){this.body.DestroyFixture(fixture)}destroyAllFixtures(){this.getFixtureList().forEach(fixture=>this.destroyFixture(fixture))}getCenterOfMass(){return box2d.vec2From(this.body.GetWorldCenter())}getLinearVelocity(){return box2d.vec2From(this.body.GetLinearVelocity())}getAngularVelocity(){return this.body.GetAngularVelocity()}getMass(){return this.body.GetMass()}getInertia(){return this.body.GetInertia()}getIsAwake(){return this.body.IsAwake()}getBodyType(){return this.body.GetType()}getSpeed(){return this.getLinearVelocity().length()}setTransform(pos,angle){this.pos=pos;this.angle=angle;this.body.SetTransform(box2d.vec2dTo(pos),-angle)}setPosition(pos){this.setTransform(pos,-this.body.GetAngle())}setAngle(angle){this.setTransform(box2d.vec2From(this.body.GetPosition()),angle)}setLinearVelocity(velocity){this.body.SetLinearVelocity(box2d.vec2dTo(velocity))}setAngularVelocity(angularVelocity){this.body.SetAngularVelocity(angularVelocity)}setLinearDamping(damping){this.body.SetLinearDamping(damping)}setAngularDamping(damping){this.body.SetAngularDamping(damping)}setGravityScale(scale=1){this.body.SetGravityScale(this.gravityScale=scale)}setBullet(isBullet=true){this.body.SetBullet(isBullet)}setAwake(isAwake=true){this.body.SetAwake(isAwake)}setBodyType(type){this.body.SetType(type)}setSleepingAllowed(isAllowed=true){this.body.SetSleepingAllowed(isAllowed)}setFixedRotation(isFixed=true){this.body.SetFixedRotation(isFixed)}setCenterOfMass(center){this.setMassData(center)}setMass(mass){this.setMassData(undefined,mass)}setMomentOfInertia(momentOfInertia){this.setMassData(undefined,undefined,momentOfInertia)}resetMassData(){this.body.ResetMassData()}setMassData(localCenter,mass,momentOfInertia){const data=new box2d.instance.b2MassData;this.body.GetMassData(data);if(localCenter!==undefined)data.set_center(box2d.vec2dTo(localCenter));if(mass!==undefined)data.set_mass(mass);if(momentOfInertia!==undefined)data.set_I(momentOfInertia);this.body.SetMassData(data)}setFilterData(categoryBits=0,ignoreCategoryBits=0,groupIndex=0){this.getFixtureList().forEach(fixture=>{const filter=fixture.GetFilterData();filter.set_categoryBits(categoryBits);filter.set_maskBits(65535&~ignoreCategoryBits);filter.set_groupIndex(groupIndex);fixture.SetFilterData(filter)})}setSensor(isSensor=true){this.getFixtureList().forEach(f=>f.SetSensor(isSensor))}applyForce(force,pos){pos||=this.getCenterOfMass();this.setAwake();this.body.ApplyForce(box2d.vec2dTo(force),box2d.vec2dTo(pos))}applyAcceleration(acceleration,pos){pos||=this.getCenterOfMass();this.setAwake();const impulse=acceleration.scale(this.getMass());this.body.ApplyLinearImpulse(box2d.vec2dTo(impulse),box2d.vec2dTo(pos))}applyImpulse(impulse,pos){pos||=this.getCenterOfMass();this.setAwake();this.body.ApplyLinearImpulse(box2d.vec2dTo(impulse),box2d.vec2dTo(pos))}applyTorque(torque){this.setAwake();this.body.ApplyTorque(torque)}applyAngularAcceleration(acceleration){this.setAwake();this.body.ApplyAngularImpulse(acceleration*this.getInertia())}applyAngularImpulse(impulse){this.setAwake();this.body.ApplyAngularImpulse(impulse)}hasFixtures(){return!box2d.isNull(this.body.GetFixtureList())}getFixtureList(){const fixtures=[];for(let fixture=this.body.GetFixtureList();!box2d.isNull(fixture);){fixtures.push(fixture);fixture=fixture.GetNext()}return fixtures}hasJoints(){return!box2d.isNull(this.body.GetJointList())}getJointList(){const joints=[];for(let joint=this.body.GetJointList();!box2d.isNull(joint);){joints.push(joint);joint=joint.get_next()}return joints}}class Box2dStaticObject extends Box2dObject{constructor(pos,size,tileInfo,angle=0,color,renderOrder=0){const bodyType=box2d.bodyTypeStatic;super(pos,size,tileInfo,angle,color,bodyType,renderOrder)}}class Box2dKinematicObject extends Box2dObject{constructor(pos,size,tileInfo,angle=0,color,renderOrder=0){const bodyType=box2d.bodyTypeKinematic;super(pos,size,tileInfo,angle,color,bodyType,renderOrder)}}class Box2dTileLayer extends Box2dStaticObject{constructor(tileLayer){ASSERT(tileLayer instanceof TileCollisionLayer,"tileLayer must be a TileCollisionLayer");super(tileLayer.pos,tileLayer.size);this.tileLayer=tileLayer;this.addChild(tileLayer)}render(){}buildCollision(friction=.2,restitution=0){this.destroyAllFixtures();this.pos=this.tileLayer.pos.copy();this.size=this.tileLayer.size.copy();const processed=[];const getIndex=(x,y)=>x+y*this.size.x;const isSolidUnprocessed=(x,y)=>!processed[getIndex(x,y)]&&this.tileLayer.getCollisionData(vec2(x,y))>0;for(let x=0;x<this.size.x;++x)for(let y=0;y<this.size.y;++y){if(!isSolidUnprocessed(x,y))continue;let width=1,height=1,canExpand=true;while(isSolidUnprocessed(x+width,y))++width;while(canExpand){for(let checkX=0;checkX<width;++checkX){if(!isSolidUnprocessed(x+checkX,y+height)){canExpand=false;break}}if(canExpand)++height}for(let rectX=width;rectX--;)for(let rectY=height;rectY--;)processed[getIndex(x+rectX,y+rectY)]=true;const shapeSize=vec2(width,height);const offset=vec2(x+width/2,y+height/2);this.addBox(shapeSize,offset,0,0,friction,restitution)}}}class Box2dRaycastResult{constructor(fixture,point,normal,fraction){this.object=fixture.GetBody().object;this.fixture=fixture;this.point=point;this.normal=normal;this.fraction=fraction}}class Box2dJoint{constructor(jointDef){this.box2dJoint=box2d.castJointObject(box2d.world.CreateJoint(jointDef))}destroy(){box2d.world.DestroyJoint(this.box2dJoint);this.box2dJoint=0}getObjectA(){return this.box2dJoint.GetBodyA().object}getObjectB(){return this.box2dJoint.GetBodyB().object}getAnchorA(){return box2d.vec2From(this.box2dJoint.GetAnchorA())}getAnchorB(){return box2d.vec2From(this.box2dJoint.GetAnchorB())}getReactionForce(time){return box2d.vec2From(this.box2dJoint.GetReactionForce(1/time))}getReactionTorque(time){return this.box2dJoint.GetReactionTorque(1/time)}getCollideConnected(){return this.box2dJoint.GetCollideConnected()}isActive(){return this.box2dJoint.IsActive()}}class Box2dTargetJoint extends Box2dJoint{constructor(object,fixedObject,worldPos){object.setAwake();const jointDef=new box2d.instance.b2MouseJointDef;jointDef.set_bodyA(fixedObject.body);jointDef.set_bodyB(object.body);jointDef.set_target(box2d.vec2dTo(worldPos));jointDef.set_maxForce(2e3*object.getMass());super(jointDef)}setTarget(pos){this.box2dJoint.SetTarget(box2d.vec2dTo(pos))}getTarget(){return box2d.vec2From(this.box2dJoint.GetTarget())}setMaxForce(force){this.box2dJoint.SetMaxForce(force)}getMaxForce(){return this.box2dJoint.GetMaxForce()}setFrequency(hz){this.box2dJoint.SetFrequency(hz)}getFrequency(){return this.box2dJoint.GetFrequency()}}class Box2dDistanceJoint extends Box2dJoint{constructor(objectA,objectB,anchorA,anchorB,collide=false){anchorA||=box2d.vec2From(objectA.body.GetPosition());anchorB||=box2d.vec2From(objectB.body.GetPosition());const localAnchorA=objectA.worldToLocal(anchorA);const localAnchorB=objectB.worldToLocal(anchorB);const jointDef=new box2d.instance.b2DistanceJointDef;jointDef.set_bodyA(objectA.body);jointDef.set_bodyB(objectB.body);jointDef.set_localAnchorA(box2d.vec2dTo(localAnchorA));jointDef.set_localAnchorB(box2d.vec2dTo(localAnchorB));jointDef.set_length(anchorA.distance(anchorB));jointDef.set_collideConnected(collide);super(jointDef)}getLocalAnchorA(){return box2d.vec2From(this.box2dJoint.GetLocalAnchorA())}getLocalAnchorB(){return box2d.vec2From(this.box2dJoint.GetLocalAnchorB())}setLength(length){this.box2dJoint.SetLength(length)}getLength(){return this.box2dJoint.GetLength()}setFrequency(hz){this.box2dJoint.SetFrequency(hz)}getFrequency(){return this.box2dJoint.GetFrequency()}setDampingRatio(ratio){this.box2dJoint.SetDampingRatio(ratio)}getDampingRatio(){return this.box2dJoint.GetDampingRatio()}}class Box2dPinJoint extends Box2dDistanceJoint{constructor(objectA,objectB,pos=objectA.pos,collide=false){super(objectA,objectB,undefined,pos,collide)}}class Box2dRopeJoint extends Box2dJoint{constructor(objectA,objectB,anchorA,anchorB,extraLength=0,collide=false){anchorA||=box2d.vec2From(objectA.body.GetPosition());anchorB||=box2d.vec2From(objectB.body.GetPosition());const localAnchorA=objectA.worldToLocal(anchorA);const localAnchorB=objectB.worldToLocal(anchorB);const jointDef=new box2d.instance.b2RopeJointDef;jointDef.set_bodyA(objectA.body);jointDef.set_bodyB(objectB.body);jointDef.set_localAnchorA(box2d.vec2dTo(localAnchorA));jointDef.set_localAnchorB(box2d.vec2dTo(localAnchorB));jointDef.set_maxLength(anchorA.distance(anchorB)+extraLength);jointDef.set_collideConnected(collide);super(jointDef)}getLocalAnchorA(){return box2d.vec2From(this.box2dJoint.GetLocalAnchorA())}getLocalAnchorB(){return box2d.vec2From(this.box2dJoint.GetLocalAnchorB())}setMaxLength(length){this.box2dJoint.SetMaxLength(length)}getMaxLength(){return this.box2dJoint.GetMaxLength()}}class Box2dRevoluteJoint extends Box2dJoint{constructor(objectA,objectB,anchor,collide=false){anchor||=box2d.vec2From(objectB.body.GetPosition());const localAnchorA=objectA.worldToLocal(anchor);const localAnchorB=objectB.worldToLocal(anchor);const jointDef=new box2d.instance.b2RevoluteJointDef;jointDef.set_bodyA(objectA.body);jointDef.set_bodyB(objectB.body);jointDef.set_localAnchorA(box2d.vec2dTo(localAnchorA));jointDef.set_localAnchorB(box2d.vec2dTo(localAnchorB));jointDef.set_referenceAngle(objectB.body.GetAngle()-objectA.body.GetAngle());jointDef.set_collideConnected(collide);super(jointDef)}getLocalAnchorA(){return box2d.vec2From(this.box2dJoint.GetLocalAnchorA())}getLocalAnchorB(){return box2d.vec2From(this.box2dJoint.GetLocalAnchorB())}getReferenceAngle(){return this.box2dJoint.GetReferenceAngle()}getJointAngle(){return this.box2dJoint.GetJointAngle()}getJointSpeed(){return this.box2dJoint.GetJointSpeed()}isLimitEnabled(){return this.box2dJoint.IsLimitEnabled()}enableLimit(enable=true){return this.box2dJoint.EnableLimit(enable)}getLowerLimit(){return this.box2dJoint.GetLowerLimit()}getUpperLimit(){return this.box2dJoint.GetUpperLimit()}setLimits(min,max){return this.box2dJoint.SetLimits(min,max)}isMotorEnabled(){return this.box2dJoint.IsMotorEnabled()}enableMotor(enable=true){return this.box2dJoint.EnableMotor(enable)}setMotorSpeed(speed){return this.box2dJoint.SetMotorSpeed(speed)}getMotorSpeed(){return this.box2dJoint.GetMotorSpeed()}setMaxMotorTorque(torque){return this.box2dJoint.SetMaxMotorTorque(torque)}getMaxMotorTorque(){return this.box2dJoint.GetMaxMotorTorque()}getMotorTorque(time){return this.box2dJoint.GetMotorTorque(1/time)}}class Box2dGearJoint extends Box2dJoint{constructor(objectA,objectB,joint1,joint2,ratio=1){const jointDef=new box2d.instance.b2GearJointDef;jointDef.set_bodyA(objectA.body);jointDef.set_bodyB(objectB.body);jointDef.set_joint1(joint1.box2dJoint);jointDef.set_joint2(joint2.box2dJoint);jointDef.set_ratio(ratio);super(jointDef);this.joint1=joint1;this.joint2=joint2}getJoint1(){return this.joint1}getJoint2(){return this.joint2}setRatio(ratio){return this.box2dJoint.SetRatio(ratio)}getRatio(){return this.box2dJoint.GetRatio()}}class Box2dPrismaticJoint extends Box2dJoint{constructor(objectA,objectB,anchor,worldAxis=vec2(0,1),collide=false){anchor||=box2d.vec2From(objectB.body.GetPosition());const localAnchorA=objectA.worldToLocal(anchor);const localAnchorB=objectB.worldToLocal(anchor);const localAxisA=objectA.worldToLocalVector(worldAxis);const jointDef=new box2d.instance.b2PrismaticJointDef;jointDef.set_bodyA(objectA.body);jointDef.set_bodyB(objectB.body);jointDef.set_localAnchorA(box2d.vec2dTo(localAnchorA));jointDef.set_localAnchorB(box2d.vec2dTo(localAnchorB));jointDef.set_localAxisA(box2d.vec2dTo(localAxisA));jointDef.set_referenceAngle(objectB.body.GetAngle()-objectA.body.GetAngle());jointDef.set_collideConnected(collide);super(jointDef)}getLocalAnchorA(){return box2d.vec2From(this.box2dJoint.GetLocalAnchorA())}getLocalAnchorB(){return box2d.vec2From(this.box2dJoint.GetLocalAnchorB())}getLocalAxisA(){return box2d.vec2From(this.box2dJoint.GetLocalAxisA())}getReferenceAngle(){return this.box2dJoint.GetReferenceAngle()}getJointTranslation(){return this.box2dJoint.GetJointTranslation()}getJointSpeed(){return this.box2dJoint.GetJointSpeed()}isLimitEnabled(){return this.box2dJoint.IsLimitEnabled()}enableLimit(enable=true){return this.box2dJoint.EnableLimit(enable)}getLowerLimit(){return this.box2dJoint.GetLowerLimit()}getUpperLimit(){return this.box2dJoint.GetUpperLimit()}setLimits(min,max){return this.box2dJoint.SetLimits(min,max)}isMotorEnabled(){return this.box2dJoint.IsMotorEnabled()}enableMotor(enable=true){return this.box2dJoint.EnableMotor(enable)}setMotorSpeed(speed){return this.box2dJoint.SetMotorSpeed(speed)}getMotorSpeed(){return this.box2dJoint.GetMotorSpeed()}setMaxMotorForce(force){return this.box2dJoint.SetMaxMotorForce(force)}getMaxMotorForce(){return this.box2dJoint.GetMaxMotorForce()}getMotorForce(time){return this.box2dJoint.GetMotorForce(1/time)}}class Box2dWheelJoint extends Box2dJoint{constructor(objectA,objectB,anchor,worldAxis=vec2(0,1),collide=false){anchor||=box2d.vec2From(objectB.body.GetPosition());const localAnchorA=objectA.worldToLocal(anchor);const localAnchorB=objectB.worldToLocal(anchor);const localAxisA=objectA.worldToLocalVector(worldAxis);const jointDef=new box2d.instance.b2WheelJointDef;jointDef.set_bodyA(objectA.body);jointDef.set_bodyB(objectB.body);jointDef.set_localAnchorA(box2d.vec2dTo(localAnchorA));jointDef.set_localAnchorB(box2d.vec2dTo(localAnchorB));jointDef.set_localAxisA(box2d.vec2dTo(localAxisA));jointDef.set_collideConnected(collide);super(jointDef)}getLocalAnchorA(){return box2d.vec2From(this.box2dJoint.GetLocalAnchorA())}getLocalAnchorB(){return box2d.vec2From(this.box2dJoint.GetLocalAnchorB())}getLocalAxisA(){return box2d.vec2From(this.box2dJoint.GetLocalAxisA())}getJointTranslation(){return this.box2dJoint.GetJointTranslation()}getJointSpeed(){return this.box2dJoint.GetJointSpeed()}isMotorEnabled(){return this.box2dJoint.IsMotorEnabled()}enableMotor(enable=true){return this.box2dJoint.EnableMotor(enable)}setMotorSpeed(speed){return this.box2dJoint.SetMotorSpeed(speed)}getMotorSpeed(){return this.box2dJoint.GetMotorSpeed()}setMaxMotorTorque(torque){return this.box2dJoint.SetMaxMotorTorque(torque)}getMaxMotorTorque(){return this.box2dJoint.GetMaxMotorTorque()}getMotorTorque(time){return this.box2dJoint.GetMotorTorque(1/time)}setSpringFrequencyHz(hz){return this.box2dJoint.SetSpringFrequencyHz(hz)}getSpringFrequencyHz(){return this.box2dJoint.GetSpringFrequencyHz()}setSpringDampingRatio(ratio){return this.box2dJoint.SetSpringDampingRatio(ratio)}getSpringDampingRatio(){return this.box2dJoint.GetSpringDampingRatio()}}class Box2dWeldJoint extends Box2dJoint{constructor(objectA,objectB,anchor,collide=false){anchor||=box2d.vec2From(objectB.body.GetPosition());const localAnchorA=objectA.worldToLocal(anchor);const localAnchorB=objectB.worldToLocal(anchor);const jointDef=new box2d.instance.b2WeldJointDef;jointDef.set_bodyA(objectA.body);jointDef.set_bodyB(objectB.body);jointDef.set_localAnchorA(box2d.vec2dTo(localAnchorA));jointDef.set_localAnchorB(box2d.vec2dTo(localAnchorB));jointDef.set_referenceAngle(objectB.body.GetAngle()-objectA.body.GetAngle());jointDef.set_collideConnected(collide);super(jointDef)}getLocalAnchorA(){return box2d.vec2From(this.box2dJoint.GetLocalAnchorA())}getLocalAnchorB(){return box2d.vec2From(this.box2dJoint.GetLocalAnchorB())}getReferenceAngle(){return this.box2dJoint.GetReferenceAngle()}setFrequency(hz){return this.box2dJoint.SetFrequency(hz)}getFrequency(){return this.box2dJoint.GetFrequency()}setSpringDampingRatio(ratio){return this.box2dJoint.SetSpringDampingRatio(ratio)}getSpringDampingRatio(){return this.box2dJoint.GetSpringDampingRatio()}}class Box2dFrictionJoint extends Box2dJoint{constructor(objectA,objectB,anchor,collide=false){anchor||=box2d.vec2From(objectB.body.GetPosition());const localAnchorA=objectA.worldToLocal(anchor);const localAnchorB=objectB.worldToLocal(anchor);const jointDef=new box2d.instance.b2FrictionJointDef;jointDef.set_bodyA(objectA.body);jointDef.set_bodyB(objectB.body);jointDef.set_localAnchorA(box2d.vec2dTo(localAnchorA));jointDef.set_localAnchorB(box2d.vec2dTo(localAnchorB));jointDef.set_collideConnected(collide);super(jointDef)}getLocalAnchorA(){return box2d.vec2From(this.box2dJoint.GetLocalAnchorA())}getLocalAnchorB(){return box2d.vec2From(this.box2dJoint.GetLocalAnchorB())}setMaxForce(force){this.box2dJoint.SetMaxForce(force)}getMaxForce(){return this.box2dJoint.GetMaxForce()}setMaxTorque(torque){this.box2dJoint.SetMaxTorque(torque)}getMaxTorque(){return this.box2dJoint.GetMaxTorque()}}class Box2dPulleyJoint extends Box2dJoint{constructor(objectA,objectB,groundAnchorA,groundAnchorB,anchorA,anchorB,ratio=1,collide=false){anchorA||=box2d.vec2From(objectA.body.GetPosition());anchorB||=box2d.vec2From(objectB.body.GetPosition());const localAnchorA=objectA.worldToLocal(anchorA);const localAnchorB=objectB.worldToLocal(anchorB);const jointDef=new box2d.instance.b2PulleyJointDef;jointDef.set_bodyA(objectA.body);jointDef.set_bodyB(objectB.body);jointDef.set_groundAnchorA(box2d.vec2dTo(groundAnchorA));jointDef.set_groundAnchorB(box2d.vec2dTo(groundAnchorB));jointDef.set_localAnchorA(box2d.vec2dTo(localAnchorA));jointDef.set_localAnchorB(box2d.vec2dTo(localAnchorB));jointDef.set_ratio(ratio);jointDef.set_lengthA(groundAnchorA.distance(anchorA));jointDef.set_lengthB(groundAnchorB.distance(anchorB));jointDef.set_collideConnected(collide);super(jointDef)}getGroundAnchorA(){return box2d.vec2From(this.box2dJoint.GetGroundAnchorA())}getGroundAnchorB(){return box2d.vec2From(this.box2dJoint.GetGroundAnchorB())}getLengthA(){return this.box2dJoint.GetLengthA()}getLengthB(){return this.box2dJoint.GetLengthB()}getRatio(){return this.box2dJoint.GetRatio()}getCurrentLengthA(){return this.box2dJoint.GetCurrentLengthA()}getCurrentLengthB(){return this.box2dJoint.GetCurrentLengthB()}}class Box2dMotorJoint extends Box2dJoint{constructor(objectA,objectB){const linearOffset=objectA.worldToLocal(box2d.vec2From(objectB.body.GetPosition()));const angularOffset=objectB.body.GetAngle()-objectA.body.GetAngle();const jointDef=new box2d.instance.b2MotorJointDef;jointDef.set_bodyA(objectA.body);jointDef.set_bodyB(objectB.body);jointDef.set_linearOffset(box2d.vec2dTo(linearOffset));jointDef.set_angularOffset(angularOffset);super(jointDef)}setLinearOffset(offset){this.box2dJoint.SetLinearOffset(box2d.vec2dTo(offset))}getLinearOffset(){return box2d.vec2From(this.box2dJoint.GetLinearOffset())}setAngularOffset(offset){this.box2dJoint.SetAngularOffset(offset)}getAngularOffset(){return this.box2dJoint.GetAngularOffset()}setMaxForce(force){this.box2dJoint.SetMaxForce(force)}getMaxForce(){return this.box2dJoint.GetMaxForce()}setMaxTorque(torque){this.box2dJoint.SetMaxTorque(torque)}getMaxTorque(){return this.box2dJoint.GetMaxTorque()}setCorrectionFactor(factor){this.box2dJoint.SetCorrectionFactor(factor)}getCorrectionFactor(){return this.box2dJoint.GetCorrectionFactor()}}class Box2dPlugin{constructor(instance){ASSERT(!box2d,"Box2D already initialized");box2d=this;this.instance=instance;this.world=new box2d.instance.b2World;this.objects=[];this.velocityIterations=8;this.positionIterations=3;this.bodyTypeStatic=instance.b2_staticBody;this.bodyTypeKinematic=instance.b2_kinematicBody;this.bodyTypeDynamic=instance.b2_dynamicBody;const listener=new box2d.instance.JSContactListener;listener.BeginContact=function(contactPtr){const contact=box2d.instance.wrapPointer(contactPtr,box2d.instance.b2Contact);const fixtureA=contact.GetFixtureA();const fixtureB=contact.GetFixtureB();const objectA=fixtureA.GetBody().object;const objectB=fixtureB.GetBody().object;if(!objectA||!objectB)return;objectA.beginContact(objectB);objectB.beginContact(objectA)};listener.EndContact=function(contactPtr){const contact=box2d.instance.wrapPointer(contactPtr,box2d.instance.b2Contact);const fixtureA=contact.GetFixtureA();const fixtureB=contact.GetFixtureB();const objectA=fixtureA.GetBody().object;const objectB=fixtureB.GetBody().object;if(!objectA||!objectB)return;objectA.endContact(objectB);objectB.endContact(objectA)};listener.PreSolve=function(){};listener.PostSolve=function(){};box2d.world.SetContactListener(listener)}step(frames=1){box2d.world.SetGravity(box2d.vec2dTo(gravity));for(let i=frames;i--;)box2d.world.Step(timeDelta,this.velocityIterations,this.positionIterations)}raycastAll(start,end){const raycastCallback=new box2d.instance.JSRayCastCallback;raycastCallback.ReportFixture=function(fixturePointer,point,normal,fraction){const fixture=box2d.instance.wrapPointer(fixturePointer,box2d.instance.b2Fixture);point=box2d.vec2FromPointer(point);normal=box2d.vec2FromPointer(normal);raycastResults.push(new Box2dRaycastResult(fixture,point,normal,fraction));return 1};const raycastResults=[];box2d.world.RayCast(raycastCallback,box2d.vec2dTo(start),box2d.vec2dTo(end));debugRaycast&&debugLine(start,end,raycastResults.length?"#f00":"#00f",.02);return raycastResults}raycast(start,end){const raycastResults=box2d.raycastAll(start,end);if(!raycastResults.length)return undefined;return raycastResults.reduce((a,b)=>a.fraction<b.fraction?a:b)}boxCastAll(pos,size){const queryCallback=new box2d.instance.JSQueryCallback;queryCallback.ReportFixture=function(fixturePointer){const fixture=box2d.instance.wrapPointer(fixturePointer,box2d.instance.b2Fixture);const o=fixture.GetBody().object;if(!queryObjects.includes(o))queryObjects.push(o);return true};const aabb=new box2d.instance.b2AABB;aabb.set_lowerBound(box2d.vec2dTo(pos.subtract(size.scale(.5))));aabb.set_upperBound(box2d.vec2dTo(pos.add(size.scale(.5))));let queryObjects=[];box2d.world.QueryAABB(queryCallback,aabb);debugRaycast&&debugRect(pos,size,queryObjects.length?"#f00":"#00f",.02);return queryObjects}boxCast(pos,size){const queryCallback=new box2d.instance.JSQueryCallback;queryCallback.ReportFixture=function(fixturePointer){const fixture=box2d.instance.wrapPointer(fixturePointer,box2d.instance.b2Fixture);queryObject=fixture.GetBody().object;return false};const aabb=new box2d.instance.b2AABB;aabb.set_lowerBound(box2d.vec2dTo(pos.subtract(size.scale(.5))));aabb.set_upperBound(box2d.vec2dTo(pos.add(size.scale(.5))));let queryObject;box2d.world.QueryAABB(queryCallback,aabb);debugRaycast&&debugRect(pos,size,queryObject?"#f00":"#00f",.02);return queryObject}circleCastAll(pos,diameter){const radius2=(diameter/2)**2;const results=box2d.boxCastAll(pos,vec2(diameter));return results.filter(o=>o.pos.distanceSquared(pos)<radius2)}circleCast(pos,diameter){const radius2=(diameter/2)**2;let results=box2d.boxCastAll(pos,vec2(diameter));let bestResult,bestDistance2;for(const result of results){const distance2=result.pos.distanceSquared(pos);if(distance2<radius2&&(!bestResult||distance2<bestDistance2)){bestResult=result;bestDistance2=distance2}}return bestResult}pointCast(pos,dynamicOnly=true){const queryCallback=new box2d.instance.JSQueryCallback;queryCallback.ReportFixture=function(fixturePointer){const fixture=box2d.instance.wrapPointer(fixturePointer,box2d.instance.b2Fixture);if(dynamicOnly&&fixture.GetBody().GetType()!==box2d.instance.b2_dynamicBody)return true;if(!fixture.TestPoint(box2d.vec2dTo(pos)))return true;queryObject=fixture.GetBody().object;return false};const aabb=new box2d.instance.b2AABB;aabb.set_lowerBound(box2d.vec2dTo(pos));aabb.set_upperBound(box2d.vec2dTo(pos));let queryObject;box2d.world.QueryAABB(queryCallback,aabb);debugRaycast&&debugRect(pos,vec2(),queryObject?"#f00":"#00f",.02);return queryObject}drawFixture(fixture,pos,angle,color=WHITE,lineColor=BLACK,lineWidth=.1,useWebGL,context){const shape=box2d.castShapeObject(fixture.GetShape());switch(shape.GetType()){case box2d.instance.b2Shape.e_polygon:{let points=[];for(let i=shape.GetVertexCount();i--;)points.push(box2d.vec2From(shape.GetVertex(i)));drawPoly(points,color,lineWidth,lineColor,pos,angle,useWebGL,false,context);break}case box2d.instance.b2Shape.e_circle:{const radius=shape.get_m_radius();drawCircle(pos,radius*2,color,lineWidth,lineColor,useWebGL,false,context);break}case box2d.instance.b2Shape.e_edge:{const v1=box2d.vec2From(shape.get_m_vertex1());const v2=box2d.vec2From(shape.get_m_vertex2());drawLine(v1,v2,lineWidth,lineColor,pos,angle,useWebGL,false,context);break}}}vec2From(v){ASSERT(v instanceof box2d.instance.b2Vec2);return new Vector2(v.get_x(),v.get_y())}vec2FromPointer(vp){const v=box2d.instance.wrapPointer(vp,box2d.instance.b2Vec2);return box2d.vec2From(v)}vec2dTo(v){ASSERT(isVector2(v));return new box2d.instance.b2Vec2(v.x,v.y)}isNull(o){return!box2d.instance.getPointer(o)}castShapeObject(o){switch(o.GetType()){case box2d.instance.b2Shape.e_circle:return box2d.instance.castObject(o,box2d.instance.b2CircleShape);case box2d.instance.b2Shape.e_edge:return box2d.instance.castObject(o,box2d.instance.b2EdgeShape);case box2d.instance.b2Shape.e_polygon:return box2d.instance.castObject(o,box2d.instance.b2PolygonShape);case box2d.instance.b2Shape.e_chain:return box2d.instance.castObject(o,box2d.instance.b2ChainShape)}ASSERT(false,"Unknown box2d object type")}castJointObject(o){switch(o.GetType()){case box2d.instance.e_revoluteJoint:return box2d.instance.castObject(o,box2d.instance.b2RevoluteJoint);case box2d.instance.e_prismaticJoint:return box2d.instance.castObject(o,box2d.instance.b2PrismaticJoint);case box2d.instance.e_distanceJoint:return box2d.instance.castObject(o,box2d.instance.b2DistanceJoint);case box2d.instance.e_pulleyJoint:return box2d.instance.castObject(o,box2d.instance.b2PulleyJoint);case box2d.instance.e_mouseJoint:return box2d.instance.castObject(o,box2d.instance.b2MouseJoint);case box2d.instance.e_gearJoint:return box2d.instance.castObject(o,box2d.instance.b2GearJoint);case box2d.instance.e_wheelJoint:return box2d.instance.castObject(o,box2d.instance.b2WheelJoint);case box2d.instance.e_weldJoint:return box2d.instance.castObject(o,box2d.instance.b2WeldJoint);case box2d.instance.e_frictionJoint:return box2d.instance.castObject(o,box2d.instance.b2FrictionJoint);case box2d.instance.e_ropeJoint:return box2d.instance.castObject(o,box2d.instance.b2RopeJoint);case box2d.instance.e_motorJoint:return box2d.instance.castObject(o,box2d.instance.b2MotorJoint)}ASSERT(false,"Unknown box2d object type")}}async function box2dInit(){new Box2dPlugin(await Box2D());setupDebugDraw();engineAddPlugin(box2dUpdate,box2dRender);return box2d;function box2dUpdate(){if(paused)return;box2d.step();box2d.objects=box2d.objects.filter(o=>!o.destroyed);for(const o of box2d.objects){if(o.body){o.pos=box2d.vec2From(o.body.GetPosition());o.angle=-o.body.GetAngle()}}}function box2dRender(){if(box2dDebug||debugPhysics)box2d.world.DrawDebugData()}function setupDebugDraw(){const debugLineWidth=.1;const debugDraw=new box2d.instance.JSDraw;const box2dColor=c=>new Color(c.get_r(),c.get_g(),c.get_b());const box2dColorPointer=c=>box2dColor(box2d.instance.wrapPointer(c,box2d.instance.b2Color));const getDebugColor=color=>box2dColorPointer(color).scale(1,.8);const getPointsList=(vertices,vertexCount)=>{const points=[];for(let i=vertexCount;i--;)points.push(box2d.vec2FromPointer(vertices+i*8));return points};debugDraw.DrawSegment=function(point1,point2,color){color=getDebugColor(color);point1=box2d.vec2FromPointer(point1);point2=box2d.vec2FromPointer(point2);drawLine(point1,point2,debugLineWidth,color,vec2(),0,false)};debugDraw.DrawPolygon=function(vertices,vertexCount,color){color=getDebugColor(color);const points=getPointsList(vertices,vertexCount);drawPoly(points,CLEAR_WHITE,debugLineWidth,color,vec2(),0,false)};debugDraw.DrawSolidPolygon=function(vertices,vertexCount,color){color=getDebugColor(color);const points=getPointsList(vertices,vertexCount);drawPoly(points,color,0,color,vec2(),0,false)};debugDraw.DrawCircle=function(center,radius,color){color=getDebugColor(color);center=box2d.vec2FromPointer(center);drawCircle(center,radius*2,CLEAR_WHITE,debugLineWidth,color,false)};debugDraw.DrawSolidCircle=function(center,radius,axis,color){color=getDebugColor(color);center=box2d.vec2FromPointer(center);axis=box2d.vec2FromPointer(axis).scale(radius);drawCircle(center,radius*2,color,debugLineWidth,color,false);drawLine(vec2(),axis,debugLineWidth,color,center,0,false)};debugDraw.DrawTransform=function(transform){transform=box2d.instance.wrapPointer(transform,box2d.instance.b2Transform);const pos=box2d.vec2From(transform.get_p());const angle=-transform.get_q().GetAngle();const p1=vec2(1,0),c1=rgb(.75,0,0,.8);const p2=vec2(0,1),c2=rgb(0,.75,0,.8);drawLine(vec2(),p1,debugLineWidth,c1,pos,angle,false);drawLine(vec2(),p2,debugLineWidth,c2,pos,angle,false)};debugDraw.AppendFlags(box2d.instance.b2Draw.e_shapeBit);debugDraw.AppendFlags(box2d.instance.b2Draw.e_jointBit);box2d.world.SetDebugDraw(debugDraw)}}function drawNineSliceScreen(pos,size,startTile,borderSize=32,extraSpace=2,angle=0){drawNineSlice(pos,size,startTile,WHITE,borderSize,BLACK,extraSpace,angle,false,true)}function drawNineSlice(pos,size,startTile,color,borderSize=1,additiveColor,extraSpace=.05,angle=0,useWebGL=glEnable,screenSpace,context){const centerTile=startTile.offset(startTile.size);const centerSize=size.add(vec2(extraSpace-borderSize*2));const cornerSize=vec2(borderSize);const cornerOffset=size.scale(.5).subtract(cornerSize.scale(.5));const flip=screenSpace?-1:1;const rotateAngle=screenSpace?-angle:angle;drawTile(pos,centerSize,centerTile,color,angle,false,additiveColor,useWebGL,screenSpace,context);for(let i=4;i--;){const horizontal=i%2;const sidePos=cornerOffset.multiply(vec2(horizontal?i===1?1:-1:0,horizontal?0:i?-1:1));const sideSize=vec2(horizontal?borderSize:centerSize.x,horizontal?centerSize.y:borderSize);const sideTile=centerTile.offset(startTile.size.multiply(vec2(i===1?1:i===3?-1:0,i===0?-flip:i===2?flip:0)));drawTile(pos.add(sidePos.rotate(rotateAngle)),sideSize,sideTile,color,angle,false,additiveColor,useWebGL,screenSpace,context)}for(let i=4;i--;){const flipX=i>1;const flipY=i&&i<3;const cornerPos=cornerOffset.multiply(vec2(flipX?-1:1,flipY?-1:1));const cornerTile=centerTile.offset(startTile.size.multiply(vec2(flipX?-1:1,flipY?flip:-flip)));drawTile(pos.add(cornerPos.rotate(rotateAngle)),cornerSize,cornerTile,color,angle,false,additiveColor,useWebGL,screenSpace,context)}}function drawThreeSliceScreen(pos,size,startTile,borderSize=32,extraSpace=2,angle=0){drawThreeSlice(pos,size,startTile,WHITE,borderSize,BLACK,extraSpace,angle,false,true)}function drawThreeSlice(pos,size,startTile,color,borderSize=1,additiveColor,extraSpace=.05,angle=0,useWebGL=glEnable,screenSpace,context){const cornerTile=startTile.frame(0);const sideTile=startTile.frame(1);const centerTile=startTile.frame(2);const centerSize=size.add(vec2(extraSpace-borderSize*2));const cornerSize=vec2(borderSize);const cornerOffset=size.scale(.5).subtract(cornerSize.scale(.5));const flip=screenSpace?-1:1;const rotateAngle=screenSpace?-angle:angle;drawTile(pos,centerSize,centerTile,color,angle,false,additiveColor,useWebGL,screenSpace,context);for(let i=4;i--;){const a=angle+i*PI/2;const horizontal=i%2;const sidePos=cornerOffset.multiply(vec2(horizontal?i===1?1:-1:0,horizontal?0:i?-flip:flip));const sideSize=vec2(horizontal?centerSize.y:centerSize.x,borderSize);drawTile(pos.add(sidePos.rotate(rotateAngle)),sideSize,sideTile,color,a,false,additiveColor,useWebGL,screenSpace,context)}for(let i=4;i--;){const a=angle+i*PI/2;const flipX=!i||i>2;const flipY=i>1;const cornerPos=cornerOffset.multiply(vec2(flipX?-1:1,flipY?-flip:flip));drawTile(pos.add(cornerPos.rotate(rotateAngle)),cornerSize,cornerTile,color,a,false,additiveColor,useWebGL,screenSpace,context)}}function drawCrescent(pos,size=1,percent=0,color=WHITE,angle=0,invert=false,lineWidth=0,lineColor=BLACK,useWebGL=glEnable,screenSpace=false,context){const points=getCrescentPoints(vec2(),size,percent,0,invert);drawPoly(points,color,lineWidth,lineColor,pos,angle,useWebGL,screenSpace,context)}function getCrescentPoints(pos,size=1,percent=0,angle=0,invert=false,sides=glCircleSides){ASSERT(isVector2(pos),"pos must be a vec2");ASSERT(isNumber(size)&&isNumber(percent),"size and percent must be numbers");let p=mod(percent*4,4);if(p>=2)angle+=PI;p=p<=2?p-1:3-p;if(invert){p=-p;angle+=PI}const points=[];const segs=max(3,sides>>1);const radius=size/2;for(let i=0;i<=segs;i++){const t=i/segs*PI;points.push(vec2(radius*cos(t),radius*sin(t)).rotate(angle).add(pos))}for(let i=segs;i>=0;i--){const t=i/segs*PI;points.push(vec2(radius*cos(t),-radius*p*sin(t)).rotate(angle).add(pos))}return points}let textureSheetSize=2048;let textureSheetPadding=1;let textureSheets=[];let textureSheetQueue=Promise.resolve();let textureSheetPendingCount=0;class TextureSheet{constructor(size=textureSheetSize){ASSERT(size>0,"texture sheet size must be positive");this.size=size;this.context=headlessMode?undefined:createCanvasContext(size);this.canvas=this.context?.canvas;this.textureInfo=new TextureInfo(this.canvas);this.cursor=vec2();this.rowHeight=0;this.glDirty=false;if(headlessMode){this.textureInfo.size=vec2(size);this.textureInfo.sizeInverse=vec2(1/size)}}tryAdd(imageSize,frameSize=imageSize,padding=textureSheetPadding,sourcePadding=0){ASSERT(isVector2(imageSize)&&isVector2(frameSize),"sizes must be vec2");ASSERT(frameSize.x>0&&frameSize.y>0,"frame size must be positive");if(isNumber(sourcePadding))sourcePadding=vec2(sourcePadding);ASSERT(isVector2(sourcePadding)&&sourcePadding.x>=0&&sourcePadding.y>=0,"sourcePadding must be a number or vec2 >= 0");const sourceCellWidth=frameSize.x+sourcePadding.x*2;const sourceCellHeight=frameSize.y+sourcePadding.y*2;ASSERT(imageSize.x%sourceCellWidth===0&&imageSize.y%sourceCellHeight===0,"image size must be a multiple of the padded frame size");const cellWidth=frameSize.x+padding*2;const cellHeight=frameSize.y+padding*2;const maxColumns=this.size/cellWidth|0;ASSERT(maxColumns>0,"frame is too wide to fit on a texture sheet");const sourceColumns=imageSize.x/sourceCellWidth;const frameCount=sourceColumns*(imageSize.y/sourceCellHeight);const columns=min(sourceColumns,maxColumns);const blockWidth=columns*cellWidth;const blockHeight=ceil(frameCount/columns)*cellHeight;let x=this.cursor.x,y=this.cursor.y,rowHeight=this.rowHeight;if(x+blockWidth>this.size){x=0;y+=rowHeight;rowHeight=0}if(y+blockHeight>this.size)return undefined;this.cursor.x=x+blockWidth;this.cursor.y=y;this.rowHeight=max(rowHeight,blockHeight);return new TileInfo(vec2(x+padding,y+padding),frameSize,this.textureInfo,padding,0,columns)}drawImage(image,tileInfo,update=true,sourcePadding=0){ASSERT(!!this.context,"texture sheet has no canvas");if(isNumber(sourcePadding))sourcePadding=vec2(sourcePadding);const frameSize=tileInfo.size;const sourceCellWidth=frameSize.x+sourcePadding.x*2;const sourceCellHeight=frameSize.y+sourcePadding.y*2;const sourceColumns=image.width/sourceCellWidth;const frameCount=sourceColumns*(image.height/sourceCellHeight);const columns=tileInfo.columns||frameCount;const cellWidth=frameSize.x+tileInfo.padding*2;const cellHeight=frameSize.y+tileInfo.padding*2;for(let i=frameCount;i--;){const sourceX=i%sourceColumns*sourceCellWidth+sourcePadding.x;const sourceY=(i/sourceColumns|0)*sourceCellHeight+sourcePadding.y;this.context.drawImage(image,sourceX,sourceY,frameSize.x,frameSize.y,tileInfo.pos.x+i%columns*cellWidth,tileInfo.pos.y+(i/columns|0)*cellHeight,frameSize.x,frameSize.y)}this.glDirty=true;update&&this.updateTexture()}updateTexture(){if(!this.glDirty)return;this.glDirty=false;this.textureInfo.createWebGLTexture()}}function loadSprite(src,frameSize,padding=textureSheetPadding,sourcePadding=0){ASSERT(isStringLike(src),"image src must be a string");ASSERT(!frameSize||isVector2(frameSize)||isNumber(frameSize),"frameSize must be a vec2 or number");ASSERT(isNumber(padding),"padding must be a number");ASSERT(isNumber(sourcePadding)||isVector2(sourcePadding),"sourcePadding must be a number or vec2");if(isNumber(frameSize))frameSize=vec2(frameSize);const tileInfo=new TileInfo(vec2(),vec2(),undefined,padding,0);if(headlessMode)return tileInfo;tileInfo.textureInfo=(textureSheets[0]||textureSheetCreate()).textureInfo;const image=new Image;const imagePromise=new Promise(resolve=>{image.onerror=image.onload=resolve;image.crossOrigin="anonymous";image.src=src});++textureSheetPendingCount;textureSheetQueue=textureSheetQueue.then(async()=>{await imagePromise;if(image.width){const imageSize=vec2(image.width,image.height);const{sheet,tile}=textureSheetAdd(imageSize,frameSize,padding,sourcePadding);Object.assign(tileInfo,tile);sheet.drawImage(image,tileInfo,false,sourcePadding)}else{LOG("loadSprite failed to load image:",src)}if(!--textureSheetPendingCount)textureSheets.forEach(s=>s.updateTexture())});return tileInfo}function loadAtlas(imageSrc,jsonSrc,padding=textureSheetPadding){ASSERT(isStringLike(imageSrc),"atlas image src must be a string");ASSERT(isStringLike(jsonSrc)||typeof jsonSrc==="object","atlas json must be a path or object");ASSERT(isNumber(padding),"padding must be a number");const atlas={};if(headlessMode)return atlas;const jsonPromise=typeof jsonSrc==="object"?Promise.resolve(jsonSrc):fetch(jsonSrc).then(r=>r.ok&&r.json()).catch(()=>undefined);const image=new Image;const imagePromise=new Promise(resolve=>{image.onerror=image.onload=resolve;image.crossOrigin="anonymous";image.src=imageSrc});++textureSheetPendingCount;textureSheetQueue=textureSheetQueue.then(async()=>{const data=await jsonPromise;await imagePromise;if(image.width&&data){for(const group of parseAtlas(data)){const sourceSize=group.frames[0].sourceSize;const blockSize=vec2(sourceSize.x*group.frames.length,sourceSize.y);const{sheet,tile}=textureSheetAdd(blockSize,sourceSize,padding);const context=sheet.context;const cellWidth=sourceSize.x+padding*2;const cellHeight=sourceSize.y+padding*2;group.frames.forEach((f,i)=>{const x=tile.pos.x+i%tile.columns*cellWidth+f.offset.x;const y=tile.pos.y+(i/tile.columns|0)*cellHeight+f.offset.y;if(f.rotated){context.save();context.translate(x,y);context.rotate(-PI/2);context.drawImage(image,f.pos.x,f.pos.y,f.size.y,f.size.x,-f.size.y,0,f.size.y,f.size.x);context.restore()}else context.drawImage(image,f.pos.x,f.pos.y,f.size.x,f.size.y,x,y,f.size.x,f.size.y)});sheet.glDirty=true;atlas[group.name]=tile}}else{LOG("loadAtlas failed to load:",imageSrc,jsonSrc)}if(!--textureSheetPendingCount)textureSheets.forEach(s=>s.updateTexture())});return atlas}function parseAtlas(data){ASSERT(!!data?.frames,"unrecognized atlas format, expected TexturePacker or Aseprite json");const frames=(isArray(data.frames)?data.frames.map(f=>[f.filename,f]):Object.entries(data.frames)).map(([name,f])=>({name:name.replace(/\.[^.\\/]+$/,""),pos:vec2(f.frame.x,f.frame.y),size:vec2(f.frame.w,f.frame.h),offset:vec2(f.spriteSourceSize?.x??0,f.spriteSourceSize?.y??0),sourceSize:vec2(f.sourceSize?.w??f.frame.w,f.sourceSize?.h??f.frame.h),rotated:!!f.rotated}));const groups=[];const tags=data.meta?.frameTags;if(tags?.length){const tagged=new Set;for(const tag of tags){groups.push({name:tag.name,frames:frames.slice(tag.from,tag.to+1)});for(let i=tag.from;i<=tag.to;++i)tagged.add(i)}frames.forEach((f,i)=>tagged.has(i)||groups.push({name:f.name,frames:[f]}));return groups}const stems=new Map;for(const f of frames){let match=f.name.match(/^(.+?)([-_ ])?(\d+)$/);if(match&&!match[2]&&/\d$/.test(match[1]))match=undefined;const stem=match?match[1]:f.name;f.groupIndex=match?Number(match[3]):undefined;stems.has(stem)||stems.set(stem,[]);stems.get(stem).push(f)}for(const[stem,list]of stems){list.sort((a,b)=>a.groupIndex-b.groupIndex);const grouped=list.length>1&&list.every((f,i)=>f.groupIndex===list[0].groupIndex+i)&&list.every(f=>f.sourceSize.x===list[0].sourceSize.x&&f.sourceSize.y===list[0].sourceSize.y);if(grouped)groups.push({name:stem,frames:list});else list.forEach(f=>groups.push({name:f.name,frames:[f]}))}return groups}async function spritesReady(){while(textureSheetPendingCount)await textureSheetQueue}function textureSheetCreate(){const sheet=new TextureSheet;textureSheets.push(sheet);return sheet}function textureSheetAdd(imageSize,frameSize,padding,sourcePadding){let sheet,tile;for(sheet of textureSheets)if(tile=sheet.tryAdd(imageSize,frameSize,padding,sourcePadding))break;if(!tile){sheet=textureSheetCreate();tile=sheet.tryAdd(imageSize,frameSize,padding,sourcePadding);ASSERT(!!tile,"image is too large to fit on a texture sheet")}return{sheet:sheet,tile:tile}}function setTextureSheetSize(size){textureSheetSize=size}function setTextureSheetPadding(padding){textureSheetPadding=padding}const tweenActive=[];let lastTime=0;let lastTimeReal=0;function isLerpable(v){return v&&typeof v.lerp==="function"}class Tween{constructor(callback,start=0,end=1,duration=1,options={}){ASSERT(typeof callback==="function","Tween callback must be a function");if(isLerpable(start)){ASSERT(start.constructor===end.constructor,"Tween start and end must be the same type")}else{ASSERT(isNumber(start),"Tween start must be a number or have a .lerp method");ASSERT(isNumber(end),"Tween end must be a number when start is a number")}ASSERT(isNumber(duration)&&duration>0,"Tween duration must be > 0");this.callback=callback;this.start=start;this.end=end;this.duration=duration;this.life=duration;this.ease=options.ease||Ease.LINEAR;this.useRealTime=!!options.useRealTime;this.paused=!!options.paused;this.thenCallback=undefined;this.loopRemaining=0;tweenActive.push(this);callback(this.interp(duration))}setEase(easeFn){this.ease=easeFn;return this}then(callback){this.thenCallback=callback;this.loopRemaining=0;return this}loop(count=Infinity){this.loopRemaining=count;this.thenCallback=()=>loopContinuation(this);return this}pingPong(count=Infinity){this.loopRemaining=count;this.thenCallback=()=>pingPongContinuation(this);return this}pause(){this.paused=true}resume(){this.paused=false}restart(){this.life=this.duration;this.paused=false;if(tweenActive.indexOf(this)<0)tweenActive.push(this);this.callback(this.interp(this.duration))}isActive(){return!this.paused&&tweenActive.indexOf(this)>=0}getPercent(){return percent(this.duration-this.life,0,this.duration)}getValue(){return this.interp(this.life)}interp(life){const x=this.ease((this.duration-life)/this.duration);if(isLerpable(this.start))return this.start.lerp(this.end,x);return this.start+(this.end-this.start)*x}stop(){const i=tweenActive.indexOf(this);if(i>=0)tweenActive.splice(i,1);this.thenCallback=undefined}}const Ease={LINEAR:x=>x,POWER:n=>x=>x**n,SINE:x=>1-cos(x*(PI/2)),CIRC:x=>1-(1-x*x)**.5,EXPO:x=>x===0?0:2**(10*x-10),BACK:x=>x*x*(2.70158*x-1.70158),ELASTIC:x=>x===0?0:x===1?1:-(2**(10*x-10))*sin((37-40*x)*PI/6),SPRING:x=>1-(sin(PI*(1-x)*(.2+2.5*(1-x)**3))*x**2.2+(1-x))*(1+1.2*x),BOUNCE:x=>{let t=1-x,f;if(t<4/11)f=7.5625*t*t;else if(t<8/11)f=7.5625*(t-=6/11)*t+.75;else if(t<10/11)f=7.5625*(t-=9/11)*t+.9375;else f=7.5625*(t-=10.5/11)*t+.984375;return 1-f},IN:f=>f,OUT:f=>x=>1-f(1-x),IN_OUT:f=>Ease.PIECEWISE(f,Ease.OUT(f)),PIECEWISE:(...fns)=>{const n=fns.length;return x=>{const i=x*n-1e-9>>0;return(fns[i]((x-i/n)*n)+i)/n}},BEZIER:(x1,y1,x2,y2)=>{const curve=t=>{const u=1-t;const c1=3*u*u*t;const c2=3*u*t*t;const t3=t**3;return[c1*x1+c2*x2+t3,c1*y1+c2*y2+t3]};return x=>{let t0=0,t1=1;for(let i=0;i<128;i++){const tMid=(t0+t1)/2;const[bx,by]=curve(tMid);if(abs(bx-x)<1e-5)return by;if(bx<x)t0=tMid;else t1=tMid}return curve((t0+t1)/2)[1]}}};function tweenProperty(target,propertyPath,start,end,duration=1,options={}){ASSERT(target!=null&&typeof target==="object","tweenProperty target must be an object");ASSERT(isStringLike(propertyPath)&&propertyPath.length>0,"tweenProperty propertyPath must be a non-empty string");const parts=propertyPath.split(".");const lastKey=parts.pop();const callback=value=>{let obj=target;for(const k of parts){obj=obj[k];ASSERT(obj!=null,"tweenProperty path does not resolve: "+propertyPath)}obj[lastKey]=value};return new Tween(callback,start,end,duration,options)}function loopContinuation(tween){if(tween.loopRemaining!==Infinity&&tween.loopRemaining<=1)return;if(tween.loopRemaining!==Infinity)tween.loopRemaining-=1;tween.life=tween.duration;tween.thenCallback=()=>loopContinuation(tween);tweenActive.push(tween);tween.callback(tween.interp(tween.duration))}function pingPongContinuation(tween){if(tween.loopRemaining!==Infinity&&tween.loopRemaining<=1)return;if(tween.loopRemaining!==Infinity)tween.loopRemaining-=1;const tmp=tween.start;tween.start=tween.end;tween.end=tmp;tween.life=tween.duration;tween.thenCallback=()=>pingPongContinuation(tween);tweenActive.push(tween);tween.callback(tween.interp(tween.duration))}function tweenUpdate(gameDelta,realDelta){if(gameDelta===undefined){gameDelta=time-lastTime;realDelta=timeReal-lastTimeReal;lastTime=time;lastTimeReal=timeReal}else if(realDelta===undefined){realDelta=gameDelta}for(let i=tweenActive.length;i--;){const t=tweenActive[i];if(t.paused)continue;const dt=t.useRealTime?realDelta:gameDelta;if(dt<=0)continue;t.life-=dt;if(t.life>0){t.callback(t.interp(t.life))}else{t.callback(t.interp(0));tweenActive.splice(i,1);const cb=t.thenCallback;t.thenCallback=undefined;if(cb)cb()}}}function tweenStopAll(){for(const t of tweenActive)t.thenCallback=undefined;tweenActive.length=0}engineAddPlugin(tweenUpdate);const PATHFINDER_DIAGONAL_COST=Math.SQRT2;const PATHFINDER_TILE_VEC=vec2(1);class PathFinderNode{constructor(x,y){this.pos=vec2(x,y);this.posWorld=vec2();this.walkable=false;this.cost=0;this.g=0;this.f=0;this.parent=null;this.isOpen=false;this.isClosed=false}reset(){this.walkable=false;this.cost=0;this.g=0;this.f=0;this.parent=null;this.isOpen=false;this.isClosed=false}isClear(){return this.walkable&&this.cost===0}}class PathFinder{constructor(source){if(isVector2(source)){this.size=source.floor();this.tileLayer=undefined}else{ASSERT(source&&isVector2(source.size)&&typeof source.getCollisionData==="function","PathFinder requires a Vector2 size or a TileCollisionLayer");this.size=source.size;this.tileLayer=source}this.heuristicWeight=1;this.maxLoop=1e3;this.smoothPath=true;this.debug=false;this.debugTime=1;this.nodes=new Array(this.size.x*this.size.y);for(let y=0;y<this.size.y;++y)for(let x=0;x<this.size.x;++x)this.nodes[x+y*this.size.x]=new PathFinderNode(x,y);this.collisionScratch=vec2()}isWalkable(x,y){if(!this.tileLayer)return true;return!this.tileLayer.getCollisionData(this.collisionScratch.set(x,y))}getCost(x,y){return 0}getNode(x,y){if(x<0||y<0||x>=this.size.x||y>=this.size.y)return null;return this.nodes[x+y*this.size.x]}worldToTile(worldPos){const ox=this.tileLayer?this.tileLayer.pos.x:0;const oy=this.tileLayer?this.tileLayer.pos.y:0;return vec2(floor(worldPos.x-ox),floor(worldPos.y-oy))}tileToWorld(x,y){const ox=this.tileLayer?this.tileLayer.pos.x:0;const oy=this.tileLayer?this.tileLayer.pos.y:0;return vec2(x+.5+ox,y+.5+oy)}buildNodeData(){const w=this.size.x;const h=this.size.y;const ox=this.tileLayer?this.tileLayer.pos.x:0;const oy=this.tileLayer?this.tileLayer.pos.y:0;for(let y=0;y<h;++y)for(let x=0;x<w;++x){const node=this.nodes[x+y*w];node.reset();const walkable=!!this.isWalkable(x,y);const cost=walkable?max(0,this.getCost(x,y)):0;node.walkable=walkable;node.cost=cost;node.posWorld.set(x+.5+ox,y+.5+oy);if(this.debug&&this.debugTime>0){if(!walkable)debugRect(node.posWorld,PATHFINDER_TILE_VEC,rgb(1,0,0,.25),this.debugTime);else if(cost>0)debugRect(node.posWorld,PATHFINDER_TILE_VEC,rgb(1,0,0,min(.2,cost*.05)),this.debugTime)}}}aStarSearch(startNode,endNode){ASSERT(startNode&&endNode,"aStarSearch needs both endpoints");ASSERT(startNode!==endNode,"aStarSearch: start and end must differ — caller should handle trivial case");ASSERT(startNode.walkable&&endNode.walkable,"aStarSearch: endpoints must be walkable");const openList=[startNode];startNode.isOpen=true;let loopCount=0;while(openList.length>0){let bestIndex=0;let bestF=openList[0].f;for(let i=1;i<openList.length;++i){if(openList[i].f<bestF){bestF=openList[i].f;bestIndex=i}}const current=openList[bestIndex];if(current===endNode)break;if(++loopCount>this.maxLoop)break;current.isOpen=false;openList.splice(bestIndex,1);current.isClosed=true;if(this.debug&&this.debugTime>0)debugRect(current.posWorld,PATHFINDER_TILE_VEC,rgb(1,1,1,.05),this.debugTime);for(let dy=-1;dy<=1;++dy)for(let dx=-1;dx<=1;++dx){if(dx===0&&dy===0)continue;const neighbor=this.getNode(current.pos.x+dx,current.pos.y+dy);if(!neighbor||!neighbor.walkable||neighbor.isClosed)continue;let stepCost=1;if(dx!==0&&dy!==0){const card1=this.getNode(current.pos.x+dx,current.pos.y);if(!card1||!card1.walkable)continue;const card2=this.getNode(current.pos.x,current.pos.y+dy);if(!card2||!card2.walkable)continue;stepCost=PATHFINDER_DIAGONAL_COST}const tentativeG=current.g+stepCost+neighbor.cost;if(!neighbor.isOpen){neighbor.isOpen=true;openList.push(neighbor)}else if(tentativeG>=neighbor.g){continue}neighbor.parent=current;neighbor.g=tentativeG;const adx=abs(endNode.pos.x-neighbor.pos.x);const ady=abs(endNode.pos.y-neighbor.pos.y);const h=max(adx,ady)+(Math.SQRT2-1)*min(adx,ady);neighbor.f=neighbor.g+h*this.heuristicWeight}}return endNode.parent!==null}getNearestClearNode(worldPos,searchRange=10,rebuild=true){ASSERT(isVector2(worldPos),"worldPos must be a Vector2");if(rebuild)this.buildNodeData();const ox=this.tileLayer?this.tileLayer.pos.x:0;const oy=this.tileLayer?this.tileLayer.pos.y:0;const centerX=floor(worldPos.x-ox);const centerY=floor(worldPos.y-oy);for(let offset=0;offset<=searchRange;++offset){let nearest=null;let nearestDistSq=0;for(let dy=-offset;dy<=offset;++dy)for(let dx=-offset;dx<=offset;++dx){if(offset>0&&abs(dx)!==offset&&abs(dy)!==offset)continue;const node=this.getNode(centerX+dx,centerY+dy);if(!node||!node.isClear())continue;const ddx=node.posWorld.x-worldPos.x;const ddy=node.posWorld.y-worldPos.y;const distSq=ddx*ddx+ddy*ddy;if(!nearest||distSq<nearestDistSq){nearest=node;nearestDistSq=distSq}}if(nearest)return nearest}return null}smoothPathCorners(path){if(path.length<=2)return;let i=1;while(i<path.length-1){const prev=path[i-1];const node=path[i];const next=path[i+1];const dx=next.pos.x-prev.pos.x;const dy=next.pos.y-prev.pos.y;const lenSq=dx*dx+dy*dy;const stepDx=node.pos.x-prev.pos.x;const stepDy=node.pos.y-prev.pos.y;const stepDxNext=next.pos.x-node.pos.x;const stepDyNext=next.pos.y-node.pos.y;if(lenSq===1){if(this.debug&&this.debugTime>0)debugCircle(node.posWorld,.3,rgb(.5,0,.5,.5),this.debugTime);path.splice(i,1);i=max(1,i-1);continue}else if(lenSq===2){if(this.debug&&this.debugTime>0)debugCircle(node.posWorld,.3,rgb(1,0,0,.5),this.debugTime);let sx,sy;if(prev.pos.y===node.pos.y&&next.pos.x===node.pos.x){sx=prev.pos.x;sy=next.pos.y}else{sx=next.pos.x;sy=prev.pos.y}const shortcut=this.getNode(sx,sy);if(shortcut&&shortcut.isClear()){path.splice(i,1);i=max(1,i-1);continue}}else if(lenSq===5){if(this.debug&&this.debugTime>0)debugCircle(node.posWorld,.3,rgb(1,1,0,.5),this.debugTime);const prevPrev=i>=2?path[i-2]:prev;let s1x,s1y,s2x,s2y;if(stepDx===0||stepDxNext===0){s1x=next.pos.x;s1y=node.pos.y;s2x=prev.pos.x;s2y=node.pos.y}else{s1x=node.pos.x;s1y=next.pos.y;s2x=node.pos.x;s2y=prev.pos.y}const dd1x=s1x-prevPrev.pos.x;const dd1y=s1y-prevPrev.pos.y;const dd2x=s2x-prevPrev.pos.x;const dd2y=s2y-prevPrev.pos.y;const dist1Sq=dd1x*dd1x+dd1y*dd1y;const dist2Sq=dd2x*dd2x+dd2y*dd2y;const sx=dist1Sq<dist2Sq?s1x:s1x===s2x&&s1y===s2y?s1x:s2x;const sy=dist1Sq<dist2Sq?s1y:s1x===s2x&&s1y===s2y?s1y:s2y;const shortcut=this.getNode(sx,sy);if(shortcut&&shortcut!==node&&shortcut.isClear()){const ccx=next.pos.x+s2x-s1x;const ccy=next.pos.y+s2y-s1y;const cutCorner=this.getNode(ccx,ccy);if(cutCorner&&cutCorner.isClear()){path[i]=shortcut;i=max(1,i-1);continue}}}else if(lenSq===4||lenSq===8){if(this.debug&&this.debugTime>0)debugCircle(node.posWorld,.3,rgb(0,1,0,.5),this.debugTime);if(stepDx===stepDxNext&&stepDy===stepDyNext){++i;continue}else{let sx,sy;if(prev.pos.y===next.pos.y){sx=node.pos.x;sy=prev.pos.y}else{sx=prev.pos.x;sy=node.pos.y}const shortcut=this.getNode(sx,sy);if(shortcut&&shortcut.isClear()){path[i]=shortcut;i=max(1,i-1);continue}}}++i}}smoothPathStringPull(path){if(path.length<=2)return;for(const n of path){if(!n.isClear())return}const original=path.slice();path.length=0;path.push(original[0]);let searchIndex=0;for(let i=1;i<original.length;++i){const node=original[i];{const a=original[searchIndex];const b=original[i-1];if(a!==b){const cross=(b.pos.x-a.pos.x)*(node.pos.y-a.pos.y)-(b.pos.y-a.pos.y)*(node.pos.x-a.pos.x);if(cross===0)continue}}if(!this.isLineClear(node.pos,path[path.length-1].pos)){let foundClearAfter=false;for(let j=i+1;j<original.length;++j){if(this.isLineClear(original[j].pos,path[path.length-1].pos)){foundClearAfter=true;break}}if(foundClearAfter){if(this.debug&&this.debugTime>0)debugLine(node.posWorld,path[path.length-1].posWorld,rgb(0,0,1,.3),.02,this.debugTime);continue}for(;searchIndex<original.length;++searchIndex){const cand=original[searchIndex];if(this.isLineClear(node.pos,cand.pos)){path.push(cand);i=searchIndex;break}}ASSERT(searchIndex<original.length,"smoothPathStringPull: ran out of candidates")}}path.push(original[original.length-1])}dropCollinearNodes(path){for(let i=path.length-2;i>=1;--i){const a=path[i-1],b=path[i],c=path[i+1];if((b.pos.x-a.pos.x)*(c.pos.y-a.pos.y)===(b.pos.y-a.pos.y)*(c.pos.x-a.pos.x))path.splice(i,1)}}isNodeClear(x,y){const n=this.getNode(x,y);return n!==null&&n.isClear()}isLineClear(startPos,endPos){ASSERT(isVector2(startPos)&&isVector2(endPos),"isLineClear needs Vector2 endpoints");ASSERT(this.isNodeClear(startPos.x,startPos.y)&&this.isNodeClear(endPos.x,endPos.y),"isLineClear endpoints must be in-bounds and clear");const dx=endPos.x-startPos.x;const dy=endPos.y-startPos.y;const adx=abs(dx);const ady=abs(dy);const sx=sign(dx);const sy=sign(dy);let x=startPos.x;let y=startPos.y;if(ady===adx){while(x!==endPos.x){if(x!==startPos.x){if(!this.isNodeClear(x,y))return false;if(!this.isNodeClear(x,y-sy))return false}if(!this.isNodeClear(x,y+sy))return false;x+=sx;y+=sy}if(!this.isNodeClear(endPos.x,endPos.y-sy))return false}else if(ady<adx){if(dy===0){x+=sx;while(x!==endPos.x){if(!this.isNodeClear(x,y))return false;x+=sx}}else{let lastY=startPos.y;while(x!==endPos.x){y=startPos.y+Math.trunc(dy*(x-startPos.x)/dx);if(lastY!==y){if(!this.isNodeClear(x-sx,y+sy))return false;if(!this.isNodeClear(x,y-sy))return false}lastY=y;if(x!==startPos.x){if(!this.isNodeClear(x,y))return false}y+=sy;if(!this.isNodeClear(x,y))return false;x+=sx}const finalY=endPos.y-sy;if(!this.isNodeClear(endPos.x,finalY))return false}}else{if(dx===0){y+=sy;while(y!==endPos.y){if(!this.isNodeClear(x,y))return false;y+=sy}}else{let lastX=startPos.x;while(y!==endPos.y){x=startPos.x+Math.trunc(dx*(y-startPos.y)/dy);if(lastX!==x){if(!this.isNodeClear(x+sx,y-sy))return false;if(!this.isNodeClear(x-sx,y))return false}lastX=x;if(y!==startPos.y){if(!this.isNodeClear(x,y))return false}x+=sx;if(!this.isNodeClear(x,y))return false;y+=sy}const finalX=endPos.x-sx;if(!this.isNodeClear(finalX,endPos.y))return false}}return true}findPath(startPos,endPos){ASSERT(isVector2(startPos)&&isVector2(endPos),"findPath needs Vector2 endpoints");this.buildNodeData();const startNode=this.getNearestClearNode(startPos,10,false);const endNode=this.getNearestClearNode(endPos,10,false);if(!startNode||!endNode)return[];if(startNode===endNode)return[startNode.posWorld.copy()];if(!this.aStarSearch(startNode,endNode))return[];const nodePath=[];for(let n=endNode;n;n=n.parent)nodePath.push(n);nodePath.reverse();if(this.smoothPath){this.smoothPathCorners(nodePath);this.smoothPathStringPull(nodePath);this.dropCollinearNodes(nodePath)}const result=nodePath.map(n=>n.posWorld.copy());if(this.debug&&this.debugTime>0&&result.length>0){for(let i=1;i<result.length;++i)debugLine(result[i-1],result[i],RED,.1,this.debugTime);for(const p of result)debugCircle(p,.5,rgb(1,0,0,.3),this.debugTime);debugCircle(result[0],.5,rgb(0,1,0,.5),this.debugTime);debugCircle(result[result.length-1],.5,rgb(0,1,0,.5),this.debugTime)}return result}}function vec3(x=0,y,z){return y===undefined?new Vector3(x,x,x):new Vector3(x,y,z===undefined?0:z)}function isVector3(v){return v instanceof Vector3&&v.isValid()}function ASSERT_VECTOR3_VALID(v){ASSERT(isVector3(v),"Vector3 is invalid.",v)}function randVector3(length=1,coneAngle=PI){const y=rand(cos(coneAngle),1),s=(1-y*y)**.5,a=rand(2*PI);return new Vector3(s*cos(a)*length,y*length,s*sin(a)*length)}function randInSphere(radius=1,minRadius=0){if(radius<=0)return new Vector3;const ratio=clamp(minRadius/radius);return randVector3(radius*rand(ratio**3,1)**(1/3))}class Vector3{constructor(x=0,y=0,z=0){ASSERT(isNumber(x)&&isNumber(y)&&isNumber(z),"Vector3 components must be numbers");this.x=x;this.y=y;this.z=z}set(x=0,y=0,z=0){this.x=x;this.y=y;this.z=z;ASSERT_VECTOR3_VALID(this);return this}setFrom(v){return this.set(v.x,v.y,v.z)}copy(){return new Vector3(this.x,this.y,this.z)}add(v){return new Vector3(this.x+v.x,this.y+v.y,this.z+v.z)}subtract(v){return new Vector3(this.x-v.x,this.y-v.y,this.z-v.z)}multiply(v){return new Vector3(this.x*v.x,this.y*v.y,this.z*v.z)}divide(v){return new Vector3(this.x/v.x,this.y/v.y,this.z/v.z)}scale(s){return new Vector3(this.x*s,this.y*s,this.z*s)}length(){return this.lengthSquared()**.5}lengthSquared(){return this.x**2+this.y**2+this.z**2}reflect(normal,restitution=1){return this.subtract(normal.scale((1+restitution)*this.dot(normal)))}distance(v){return this.distanceSquared(v)**.5}distanceSquared(v){return(this.x-v.x)**2+(this.y-v.y)**2+(this.z-v.z)**2}normalize(length=1){const l=this.length();return l?this.scale(length/l):new Vector3}clampLength(length=1){const l=this.length();return l>length?this.scale(length/l):this.copy()}dot(v){return this.x*v.x+this.y*v.y+this.z*v.z}cross(v){return new Vector3(this.y*v.z-this.z*v.y,this.z*v.x-this.x*v.z,this.x*v.y-this.y*v.x)}lerp(v,percent){ASSERT_VECTOR3_VALID(v);return this.add(v.subtract(this).scale(clamp(percent)))}rotate(axis,angle){ASSERT_VECTOR3_VALID(axis);const c=cos(angle),s=sin(angle),d=axis.dot(this)*(1-c);return this.scale(c).add(axis.cross(this).scale(s)).add(axis.scale(d))}rotateX(angle){const c=cos(angle),s=sin(angle);return new Vector3(this.x,this.y*c-this.z*s,this.y*s+this.z*c)}rotateY(angle){const c=cos(angle),s=sin(angle);return new Vector3(this.x*c+this.z*s,this.y,this.z*c-this.x*s)}rotateZ(angle){const c=cos(angle),s=sin(angle);return new Vector3(this.x*c-this.y*s,this.x*s+this.y*c,this.z)}abs(){return new Vector3(abs(this.x),abs(this.y),abs(this.z))}floor(){return new Vector3(floor(this.x),floor(this.y),floor(this.z))}round(){return new Vector3(round(this.x),round(this.y),round(this.z))}snap(grid){ASSERT_NUMBER_VALID(grid);return new Vector3(floor(this.x*grid)/grid,floor(this.y*grid)/grid,floor(this.z*grid)/grid)}transform(matrix){return matrix.transformPoint(this)}transformDirection(matrix){return matrix.transformDirection(this)}isValid(){return isNumber(this.x)&&isNumber(this.y)&&isNumber(this.z)}toString(digits=3){if(!this.isValid())return`(${this.x},${this.y},${this.z})`;const f=v=>(v<0?"":" ")+v.toFixed(digits);return`(${f(this.x)},${f(this.y)},${f(this.z)} )`}}const matrix4Scratch=new Float32Array(16);class Matrix4{constructor(m){this.m=new Float32Array(16);ASSERT(!m||m.length==16,"Matrix4 takes 16 values, use copy() to duplicate a matrix");if(m)this.m.set(m);else this.m[0]=this.m[5]=this.m[10]=this.m[15]=1}static identity(){return new Matrix4}static translation(v){ASSERT_VECTOR3_VALID(v);const r=new Matrix4;r.m[12]=v.x;r.m[13]=v.y;r.m[14]=v.z;return r}static rotation(euler){ASSERT_VECTOR3_VALID(euler);const cx=cos(euler.x),sx=sin(euler.x);const cy=cos(euler.y),sy=sin(euler.y);const cz=cos(euler.z),sz=sin(euler.z);const r=new Matrix4;const m=r.m;m[0]=cy*cz+sy*sx*sz;m[1]=cx*sz;m[2]=-sy*cz+cy*sx*sz;m[4]=-cy*sz+sy*sx*cz;m[5]=cx*cz;m[6]=sy*sz+cy*sx*cz;m[8]=sy*cx;m[9]=-sx;m[10]=cy*cx;return r}static scaling(v){ASSERT_VECTOR3_VALID(v);const r=new Matrix4;r.m[0]=v.x;r.m[5]=v.y;r.m[10]=v.z;return r}static perspective(fov,aspect,near,far){ASSERT(near>0&&far>near,"a perspective projection needs 0 < near < far, or nothing is visible",near,far);const f=1/tan(fov/2);const r=new Matrix4;const m=r.m;m[0]=f/aspect;m[5]=f;m[10]=far==Infinity?-1:(far+near)/(near-far);m[11]=-1;m[14]=far==Infinity?-2*near:2*far*near/(near-far);m[15]=0;return r}static orthographic(left,right,bottom,top,near,far){ASSERT(far>near&&far!=Infinity,"an orthographic projection needs a real far plane past near, Infinity is perspective only",near,far);const r=new Matrix4;const m=r.m;m[0]=2/(right-left);m[5]=2/(top-bottom);m[10]=-2/(far-near);m[12]=-(right+left)/(right-left);m[13]=-(top+bottom)/(top-bottom);m[14]=-(far+near)/(far-near);return r}static lookAt(eye,target,up=vec3(0,1,0)){let z=eye.subtract(target).normalize();if(!z.lengthSquared())z=vec3(0,0,1);let x=up.cross(z).normalize();if(!x.lengthSquared())x=(abs(z.y)>.99?vec3(0,0,1):vec3(0,1,0)).cross(z).normalize();const y=z.cross(x);return new Matrix4([x.x,x.y,x.z,0,y.x,y.y,y.z,0,z.x,z.y,z.z,0,eye.x,eye.y,eye.z,1])}copy(){return new Matrix4(this.m)}multiply(matrix){const a=this.m,b=matrix.m,r=matrix4Scratch;for(let j=0;j<4;++j)for(let i=0;i<4;++i)r[j*4+i]=a[i]*b[j*4]+a[4+i]*b[j*4+1]+a[8+i]*b[j*4+2]+a[12+i]*b[j*4+3];this.m.set(r);return this}translate(v){return this.multiply(Matrix4.translation(v))}rotate(euler){return this.multiply(Matrix4.rotation(euler))}scale(v){return this.multiply(Matrix4.scaling(v))}transpose(){const m=this.m;for(let i=0;i<4;++i)for(let j=i+1;j<4;++j){const t=m[i*4+j];m[i*4+j]=m[j*4+i];m[j*4+i]=t}return this}invert(){const m=this.m;const[a00,a01,a02,a03,a10,a11,a12,a13,a20,a21,a22,a23,a30,a31,a32,a33]=m;const b00=a00*a11-a01*a10,b01=a00*a12-a02*a10,b02=a00*a13-a03*a10;const b03=a01*a12-a02*a11,b04=a01*a13-a03*a11,b05=a02*a13-a03*a12;const b06=a20*a31-a21*a30,b07=a20*a32-a22*a30,b08=a20*a33-a23*a30;const b09=a21*a32-a22*a31,b10=a21*a33-a23*a31,b11=a22*a33-a23*a32;let det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;if(!det)return this;det=1/det;m[0]=(a11*b11-a12*b10+a13*b09)*det;m[1]=(a02*b10-a01*b11-a03*b09)*det;m[2]=(a31*b05-a32*b04+a33*b03)*det;m[3]=(a22*b04-a21*b05-a23*b03)*det;m[4]=(a12*b08-a10*b11-a13*b07)*det;m[5]=(a00*b11-a02*b08+a03*b07)*det;m[6]=(a32*b02-a30*b05-a33*b01)*det;m[7]=(a20*b05-a22*b02+a23*b01)*det;m[8]=(a10*b10-a11*b08+a13*b06)*det;m[9]=(a01*b08-a00*b10-a03*b06)*det;m[10]=(a30*b04-a31*b02+a33*b00)*det;m[11]=(a21*b02-a20*b04-a23*b00)*det;m[12]=(a11*b07-a10*b09-a12*b06)*det;m[13]=(a00*b09-a01*b07+a02*b06)*det;m[14]=(a31*b01-a30*b03-a32*b00)*det;m[15]=(a20*b03-a21*b01+a22*b00)*det;return this}transformPoint(v){const m=this.m;return new Vector3(m[0]*v.x+m[4]*v.y+m[8]*v.z+m[12],m[1]*v.x+m[5]*v.y+m[9]*v.z+m[13],m[2]*v.x+m[6]*v.y+m[10]*v.z+m[14])}transformDirection(v){const m=this.m;return new Vector3(m[0]*v.x+m[4]*v.y+m[8]*v.z,m[1]*v.x+m[5]*v.y+m[9]*v.z,m[2]*v.x+m[6]*v.y+m[10]*v.z)}getTranslation(){return new Vector3(this.m[12],this.m[13],this.m[14])}toString(){const m=this.m,f=i=>m[i].toFixed(2).padStart(7);let s="";for(let row=0;row<4;++row)s+=`[${f(row)} ${f(4+row)} ${f(8+row)} ${f(12+row)} ]\n`;return s}}function buildMatrix(pos,rotation,scale){ASSERT(!pos||isVector3(pos),"pos must be a Vector3",pos);ASSERT(!scale||isVector3(scale),"scale must be a Vector3",scale);const turned=rotation&&(rotation.x||rotation.y||rotation.z);const matrix=turned?Matrix4.rotation(rotation):new Matrix4,m=matrix.m;if(scale){m[0]*=scale.x;m[1]*=scale.x;m[2]*=scale.x;m[4]*=scale.y;m[5]*=scale.y;m[6]*=scale.y;m[8]*=scale.z;m[9]*=scale.z;m[10]*=scale.z}if(pos)m[12]=pos.x,m[13]=pos.y,m[14]=pos.z;return matrix}class Ray3D{constructor(origin=vec3(),direction=vec3(0,0,-1)){ASSERT_VECTOR3_VALID(origin);ASSERT_VECTOR3_VALID(direction);this.origin=origin;this.direction=direction}getPosition(distance){return this.origin.add(this.direction.scale(distance))}copy(){return new Ray3D(this.origin.copy(),this.direction.copy())}}function isPointInBox3D(point,pos,size){return abs(point.x-pos.x)<=size.x/2&&abs(point.y-pos.y)<=size.y/2&&abs(point.z-pos.z)<=size.z/2}function isOverlapping3D(posA,sizeA,posB,sizeB=vec3()){const d=posA.subtract(posB);return abs(d.x)<(sizeA.x+sizeB.x)/2&&abs(d.y)<(sizeA.y+sizeB.y)/2&&abs(d.z)<(sizeA.z+sizeB.z)/2}function collideSphereSphere(posA,radiusA,posB,radiusB){const d=posA.subtract(posB);const r=radiusA+radiusB;const dist=d.length();if(dist>=r)return undefined;if(!dist)return vec3(0,r,0);return d.normalize(r-dist)}function collideSphereBox(pos,radius,boxPos,boxSize){const h=boxSize.scale(.5);const closest=vec3(clamp(pos.x,boxPos.x-h.x,boxPos.x+h.x),clamp(pos.y,boxPos.y-h.y,boxPos.y+h.y),clamp(pos.z,boxPos.z-h.z,boxPos.z+h.z));const d=pos.subtract(closest),distSq=d.lengthSquared();if(distSq)return distSq>=radius*radius?undefined:d.normalize(radius-distSq**.5);const offset=pos.subtract(boxPos);return pushOutAxis3D(offset,h.x-abs(offset.x),h.y-abs(offset.y),h.z-abs(offset.z),radius)}function collideSphereInBox(pos,radius,boxPos,boxSize){const x=max(0,boxSize.x/2-radius),y=max(0,boxSize.y/2-radius),z=max(0,boxSize.z/2-radius);const push=vec3(clamp(pos.x,boxPos.x-x,boxPos.x+x)-pos.x,clamp(pos.y,boxPos.y-y,boxPos.y+y)-pos.y,clamp(pos.z,boxPos.z-z,boxPos.z+z)-pos.z);return push.lengthSquared()?push:undefined}function pushOutAxis3D(d,penX,penY,penZ,extra=0){const s=v=>v>=0?1:-1;if(penX<=penY&&penX<=penZ)return vec3(s(d.x)*(penX+extra),0,0);if(penY<=penZ)return vec3(0,s(d.y)*(penY+extra),0);return vec3(0,0,s(d.z)*(penZ+extra))}function collideSphereCylinder(pos,radius,cylinderPos,cylinderRadius,cylinderHeight){const halfHeight=cylinderHeight/2;const offsetX=pos.x-cylinderPos.x;const offsetZ=pos.z-cylinderPos.z;const offsetY=pos.y-cylinderPos.y;const radialDist=(offsetX**2+offsetZ**2)**.5;const radialScale=radialDist?min(radialDist,cylinderRadius)/radialDist:0;const closest=vec3(cylinderPos.x+offsetX*radialScale,clamp(pos.y,cylinderPos.y-halfHeight,cylinderPos.y+halfHeight),cylinderPos.z+offsetZ*radialScale);const d=pos.subtract(closest),distSq=d.lengthSquared();if(distSq)return distSq>=radius*radius?undefined:d.normalize(radius-distSq**.5);const sidePen=cylinderRadius-radialDist;const capPen=halfHeight-abs(offsetY);if(sidePen<=capPen){const dir=radialDist?vec3(offsetX/radialDist,0,offsetZ/radialDist):vec3(1,0,0);return dir.scale(sidePen+radius)}return vec3(0,(offsetY>=0?1:-1)*(capPen+radius),0)}function collideBoxBox3D(posA,sizeA,posB,sizeB){const d=posA.subtract(posB);const overlapX=(sizeA.x+sizeB.x)/2-abs(d.x);const overlapY=(sizeA.y+sizeB.y)/2-abs(d.y);const overlapZ=(sizeA.z+sizeB.z)/2-abs(d.z);if(overlapX<=0||overlapY<=0||overlapZ<=0)return undefined;return pushOutAxis3D(d,overlapX,overlapY,overlapZ)}function raycastSphere(ray,pos,radius){const{origin,direction}=ray;const oc=origin.subtract(pos);const a=direction.dot(direction);if(!a)return undefined;const c=oc.dot(oc)-radius*radius;if(c<0)return 0;const b=2*oc.dot(direction);const discriminant=b*b-4*a*c;if(discriminant<0)return undefined;const t=(-b-discriminant**.5)/(2*a);return t>=0?t:undefined}function raycastPlane(ray,planePos,planeNormal){const{origin,direction}=ray;const denominator=direction.dot(planeNormal);if(abs(denominator)<1e-9)return undefined;const t=planePos.subtract(origin).dot(planeNormal)/denominator;return t<0?undefined:t}function raycastBox(ray,pos,size){const{origin,direction}=ray;const h=size.scale(.5);const boxMin=pos.subtract(h),boxMax=pos.add(h);let tMin=0,tMax=Infinity;for(const axis of"xyz"){const o=origin[axis],d=direction[axis];const mn=boxMin[axis],mx=boxMax[axis];if(!d){if(o<mn||o>mx)return undefined;continue}let t0=(mn-o)/d;let t1=(mx-o)/d;if(t0>t1)[t0,t1]=[t1,t0];tMin=max(tMin,t0);tMax=min(tMax,t1);if(tMin>tMax)return undefined}return tMin}let render3D;const RENDER3D_VERTEX_FLOATS=9;const RENDER3D_VERTEX_BYTES=RENDER3D_VERTEX_FLOATS*4;const RENDER3D_INSTANCE_FLOATS=33;const RENDER3D_INSTANCE_BYTES=RENDER3D_INSTANCE_FLOATS*4;const RENDER3D_INSTANCE_ATTRIBS=[[4,4,0],[5,4,16],[6,4,32],[7,4,48],[8,3,64],[9,3,76],[10,3,88],[11,4,100],[12,4,116]];const RENDER3D_VERTEX_INPUTS="layout(location=0) in vec3 p;layout(location=1) in vec3 n;layout(location=2) in vec2 t;layout(location=3) in vec4 c;"+"layout(location=4) in vec4 m0;layout(location=5) in vec4 m1;layout(location=6) in vec4 m2;layout(location=7) in vec4 m3;"+"layout(location=8) in vec3 n0;layout(location=9) in vec3 n1;layout(location=10) in vec3 n2;"+"layout(location=11) in vec4 tint;layout(location=12) in vec4 uvRect;";const RENDER3D_MAX_STREAM_VERTS=32768;const RENDER3D_MAX_LIGHTS=8;const RENDER3D_QUAD_UVS=Object.freeze([vec2(0,0),vec2(0,1),vec2(1,0),vec2(1,1)].map(uv=>Object.freeze(uv)));const RENDER3D_FULL_UV_RECT=Object.freeze({x:0,y:0,w:1,h:1});const RENDER3D_DEFAULT_NORMAL=Object.freeze(vec3(0,1,0));const RENDER3D_DEFAULT_UV=Object.freeze(vec2());const RENDER3D_SHADOW_COLOR=Object.freeze(hsl(0,0,0,.5));const RENDER3D_IDENTITY=new Matrix4;const RENDER3D_DEBUG_WIDTH=.05;const RENDER3D_TEXT_LEADING=1.3;function render3DFaceNormal(a,b,c,d=a){const n=c.subtract(a).cross(d.subtract(b));return n.lengthSquared()?n.normalize():RENDER3D_DEFAULT_NORMAL}function render3DQuadStrip(a,b,c,d){return[a,b,d,c]}function render3DQuadValues(v){return isArray(v)?render3DQuadStrip(...v):v}function render3DCanDraw(){if(!render3D.program)return false;ASSERT(render3D.isRendering,"3D draws are only valid during the 3D pass, draw from an EngineObject3D or render3D.onRenderOpaque");return render3D.isRendering}const RENDER3D_STATE_FIELDS=["blend","additive","depthTest","depthWrite","cullBackFaces","mirrored","lighting","emissive","receiveShadow","specular","pixelated","shader"];function render3DCaptureBatchState(){const state={};for(const field of RENDER3D_STATE_FIELDS)state[field]=render3D[field];return state}function render3DStateChanged(state){for(const field of RENDER3D_STATE_FIELDS)if(render3D[field]!==state[field])return true;return false}function render3DWithState(fields,fn){const r=render3D,saved={};for(const key in fields)saved[key]=r[key],r[key]=fields[key];try{return fn()}finally{Object.assign(r,saved)}}function render3DIsAfter2D(o){return!!(o.renderAfter2D??render3D.renderAfter2D)}function render3DSize3(size){return isNumber(size)?vec3(size):size}function render3DMatrix(matrix){if(matrix instanceof Vector3)return buildMatrix(matrix);ASSERT(matrix instanceof Matrix4,"takes a Matrix4, or a Vector3 for a position");return matrix}function render3DNormalMatrix(matrix){return matrix.copy().invert().transpose()}function render3DAxis(m,i){return vec3(m[i],m[i+1],m[i+2])}function render3DSlopeNormal(heightFunction,x,z,ex,ez,halfX,halfZ){const x0=max(x-ex,-halfX),x1=min(x+ex,halfX),z0=max(z-ez,-halfZ),z1=min(z+ez,halfZ);const dx=(heightFunction(x1,z)-heightFunction(x0,z))/(x1-x0||1);const dz=(heightFunction(x,z1)-heightFunction(x,z0))/(z1-z0||1);return vec3(-dx,1,-dz).normalize()}function render3DMaxScale(m){return max(m[0]*m[0]+m[1]*m[1]+m[2]*m[2],m[4]*m[4]+m[5]*m[5]+m[6]*m[6],m[8]*m[8]+m[9]*m[9]+m[10]*m[10])**.5}function render3DQuadAxes(center,right,up){return[center.subtract(right).add(up),center.subtract(right).subtract(up),center.add(right).add(up),center.add(right).subtract(up)]}function render3DSetObjectState(o){const r=render3D;const emissive=o?.emissive||0;ASSERT(isNumber(emissive)&&emissive>=0,"emissive must be a number, 0 or more",emissive);r.lighting=true;r.emissive=emissive;r.additive=!!o?.additive;r.specular=o?.specular||0;r.receiveShadow=!o||o.receiveShadow;r.cullBackFaces=r.mirrored=false;r.pixelated=!!o?.pixelated;ASSERT(!o?.shader||o.shader instanceof Shader,"shader must be a Shader, not the snippet itself");r.shader=o?.shader||undefined;r.depthTest=true}function render3DDrawObjects(objects){for(const o of objects){render3DSetObjectState(o);o.render3D()}render3DSetObjectState()}function render3DDetach(o){if(o.parent)o.pos3D=o.getWorldPos3D(),o.parent.removeChild(o);else if(o.worldPos3D)o.pos3D=o.worldPos3D}function render3DInstance(mesh,matrix,tileInfo,color){const r=render3D,textureInfo=tileInfo instanceof TileInfo?tileInfo.textureInfo:tileInfo;if(mesh.instanceCount&&(mesh.instanceTextureInfo!==textureInfo||render3DStateChanged(mesh.instanceState)))render3DFlushInstances(mesh);if(!mesh.instanceCount){mesh.instanceTextureInfo=textureInfo;mesh.instanceState=render3DCaptureBatchState();r.instanceMeshes.push(mesh)}let data=mesh.instanceData;const k=mesh.instanceCount++*RENDER3D_INSTANCE_FLOATS;if(!data||data.length<k+RENDER3D_INSTANCE_FLOATS){const grown=new Float32Array(max(64*RENDER3D_INSTANCE_FLOATS,data?data.length*2:0));data&&grown.set(data);mesh.instanceData=data=grown}data.set(matrix.m,k);render3DNormalMatrix3(matrix.m,data,k+16);data[k+25]=color.r;data[k+26]=color.g;data[k+27]=color.b;data[k+28]=color.a;const uv=render3DGetTileUVs(tileInfo);data[k+29]=uv.x;data[k+30]=uv.y;data[k+31]=uv.w;data[k+32]=uv.h}function render3DFlushInstances(only){const r=render3D,gl=glContext;for(const mesh of only?[only]:r.instanceMeshes){const count=mesh.instanceCount;mesh.instanceCount=0;if(!count||!mesh.buffer)continue;const buffers=r.instanceBuffers;gl.bindBuffer(gl.ARRAY_BUFFER,buffers[r.instanceBufferIndex=(r.instanceBufferIndex+1)%buffers.length]);gl.bufferData(gl.ARRAY_BUFFER,mesh.instanceData,gl.DYNAMIC_DRAW,0,count*RENDER3D_INSTANCE_FLOATS);for(const[location,size,offset]of RENDER3D_INSTANCE_ATTRIBS){gl.vertexAttribPointer(location,size,gl.FLOAT,false,RENDER3D_INSTANCE_BYTES,offset);gl.enableVertexAttribArray(location)}render3DSetDrawUniforms(RENDER3D_IDENTITY,mesh.instanceTextureInfo,WHITE,RENDER3D_FULL_UV_RECT,mesh.instanceState);render3DBindVertexBuffer(mesh.buffer);gl.drawArraysInstanced(gl.TRIANGLE_STRIP,0,mesh.bufferCount,count);for(const[location]of RENDER3D_INSTANCE_ATTRIBS)gl.disableVertexAttribArray(location);++drawCount;primitiveCount+=mesh.bufferCount*count}if(!only)r.instanceMeshes.length=0;else{const i=r.instanceMeshes.indexOf(only);i<0||r.instanceMeshes.splice(i,1)}}function render3DClearInstances(){for(const mesh of render3D.instanceMeshes)mesh.instanceCount=0;render3D.instanceMeshes.length=0}function render3DLayerObjects(after2D){return engineObjects.filter(o=>!o.destroyed&&o instanceof EngineObject3D&&render3DIsAfter2D(o)===after2D)}function render3DCollectLights(){const lights=engineObjects.filter(o=>!o.destroyed&&o instanceof Light3D&&o.color.a>0&&o.intensity>0&&(o.directional||o.radius>0));if(lights.length>RENDER3D_MAX_LIGHTS){const cameraPos=render3D.camera.pos,distances=new Map;for(const light of lights)distances.set(light,light.directional?-1:light.getWorldPos3D().distanceSquared(cameraPos));lights.sort((a,b)=>distances.get(a)-distances.get(b));lights.length=RENDER3D_MAX_LIGHTS}return lights}const render3DCircleCache=new Map;function render3DCircle(sides){sides|=0;let circle=render3DCircleCache.get(sides);if(!circle){circle=new Float32Array(sides*2+2);for(let i=0;i<=sides;++i){const a=i/sides*2*PI;circle[i*2]=cos(a),circle[i*2+1]=sin(a)}render3DCircleCache.set(sides,circle)}return circle}let render3DSoftDotTexture;function render3DSoftDot(){if(render3DSoftDotTexture||!glContext||typeof OffscreenCanvas=="undefined")return render3DSoftDotTexture;const size=32,context=createCanvasContext(size);const gradient=context.createRadialGradient(size/2,size/2,0,size/2,size/2,size/2);for(const[stop,alpha]of[[0,1],[.33,.9],[.67,.7],[1,0]])gradient.addColorStop(stop,"rgba(255,255,255,"+alpha+")");context.fillStyle=gradient;context.fillRect(0,0,size,size);return render3DSoftDotTexture=new TextureInfo(context.canvas)}function render3DLookRotation(direction,current){const d=direction.normalize();if(!d.lengthSquared())return current;if(abs(d.x)+abs(d.z)<1e-9)return vec3(d.y>0?PI/2:-PI/2,current.y,0);return vec3(Math.asin(clamp(d.y,-1,1)),atan2(-d.x,-d.z),0)}class Render3DPlugin{constructor(){ASSERT(!render3D,"Render3D plugin already initialized");render3D=this;this.camera=new Camera3D;this.sunDirection=vec3(-.3,1,.5);this.sunColor=WHITE.copy();this.ambientColor=hsl(0,0,.3);this.fogColor=undefined;this.fogStart=0;this.fogEnd=0;this.gravity=vec3();this.softShadowHeight=0;this.smoothShading=false;this.shadows=false;this.shadowMapSize=1024;this.shadowRange=40;this.shadowCenter=undefined;this.shadowBias=.003;this.shadowSoftness=1;this.lighting=true;this.emissive=0;this.additive=false;this.depthTest=true;this.depthWrite=true;this.cullBackFaces=false;this.mirrored=false;this.specular=0;this.shader=undefined;this.receiveShadow=true;this.onRenderOpaque=undefined;this.onRenderTransparent=undefined;this.sky=undefined;this.renderAfter2D=false;this.sortTransparent=true;this.frustumCulling=true;this.instancing=true;this.mipmaps=true;this.pixelated=false;this.anisotropy=4;this.boxMesh=buildBox();this.sphereMesh=buildSphere(1,16,8,true);this.planeMesh=buildGrid();this.planeMesh.doubleSided=false;this.planeMeshDoubleSided=buildGrid();this.isRendering=false;this.shadowPass=false;this.viewMatrix=new Matrix4;this.projectionMatrix=new Matrix4;this.viewProjection=new Matrix4;this.shadowMatrix=new Matrix4;this.cameraRight=vec3(1,0,0);this.cameraUp=vec3(0,1,0);this.cameraForward=vec3(0,0,-1);this.cameraBack=vec3(0,0,1);this.blend=false;this.frustumPlanes=[];this.shadowPlanes=[];this.program=undefined;this.currentProgram=undefined;this.lightCount=0;this.shadowShader=undefined;this.vao=undefined;this.whiteTexture=undefined;this.samplers=[];this.samplerKey=undefined;this.mipmapped=new WeakSet;this.shadowTexture=undefined;this.shadowFramebuffer=undefined;this.shadowTextureSize=0;this.contextGeneration=0;this.uniforms=new Map;this.uniformValues={};this.shadowMapDrawn=false;this.passIsDefault=true;this.lightPositions=new Float32Array(RENDER3D_MAX_LIGHTS*4);this.lightColors=new Float32Array(RENDER3D_MAX_LIGHTS*4);this.streamBuffer=undefined;this.instanceBuffers=[];this.instanceBufferIndex=0;this.instanceMeshes=[];this.attribValues=[];this.streamData=new ArrayBuffer(RENDER3D_MAX_STREAM_VERTS*RENDER3D_VERTEX_BYTES);this.streamFloats=new Float32Array(this.streamData);this.streamInts=new Uint32Array(this.streamData);this.streamCount=0;this.streamTileInfo=undefined;this.streamState=undefined;this.capture=undefined;this.transparentQueue=undefined;render3DInitGL();engineAddPlugin(undefined,render3DRender,render3DContextLost,render3DContextRestored,render3DPreRender)}updateMatrices(aspect=mainCanvasSize.y?mainCanvasSize.x/mainCanvasSize.y:1){const camera=this.camera;if(camera.align2D)camera.update2D();const cameraMatrix=camera.getMatrix();this.viewMatrix=cameraMatrix.copy().invert();this.projectionMatrix=camera.getProjectionMatrix(aspect);this.viewProjection=this.projectionMatrix.copy().multiply(this.viewMatrix);const m=cameraMatrix.m;this.cameraRight=render3DAxis(m,0);this.cameraUp=render3DAxis(m,4);this.cameraBack=render3DAxis(m,8);this.cameraForward=this.cameraBack.scale(-1);this.frustumPlanes=render3DFrustumPlanes(this.viewProjection)}worldToClip(pos){const m=this.viewProjection.m;const w=m[3]*pos.x+m[7]*pos.y+m[11]*pos.z+m[15];const z=(m[2]*pos.x+m[6]*pos.y+m[10]*pos.z+m[14])/w;if(w<=0||z<-1)return;return vec3((m[0]*pos.x+m[4]*pos.y+m[8]*pos.z+m[12])/w,(m[1]*pos.x+m[5]*pos.y+m[9]*pos.z+m[13])/w,z)}worldToScreen(pos,canvasSize=mainCanvasSize){const clip=this.worldToClip(pos);if(!clip)return;return vec2((clip.x+1)/2*canvasSize.x,(1-clip.y)/2*canvasSize.y)}screenToRay(screenPos,canvasSize=mainCanvasSize){const width=canvasSize.x||1,height=canvasSize.y||1;const aspect=width/height,camera=this.camera;this.updateMatrices(aspect);const clipX=screenPos.x/width*2-1;const clipY=1-screenPos.y/height*2;const h=camera.orthographic?camera.orthographic/2:tan(camera.fov/2);const offset=this.cameraRight.scale(clipX*h*aspect).add(this.cameraUp.scale(clipY*h));return camera.orthographic?new Ray3D(camera.pos.add(offset),this.cameraForward.copy()):new Ray3D(camera.pos.copy(),this.cameraForward.add(offset).normalize())}screenToGround(screenPos,groundHeight=0,canvasSize=mainCanvasSize){const ray=this.screenToRay(screenPos,canvasSize);const t=raycastPlane(ray,vec3(0,groundHeight,0),RENDER3D_DEFAULT_NORMAL);return t===undefined?undefined:ray.getPosition(t)}pick(from,objects=engineObjects){const ray=from instanceof Ray3D?from:this.screenToRay(from);let nearest;for(const o of objects){const distance=render3DRaycastObject(ray,o);if(distance!==undefined&&(!nearest||distance<nearest.distance))nearest={object:o,distance:distance}}return nearest}playSound(sound,pos3D,volume=1,pitch=1,randomnessScale=1,loop=false){ASSERT(sound instanceof Sound,"sound must be a Sound");ASSERT(isVector3(pos3D),"pos3D must be a vec3");if(!soundEnable||headlessMode)return;if(!sound.sampleBuffer&&!sound._sampleChannels)return;const offset=pos3D.subtract(this.camera.pos),range=sound.range;if(range){const distance=offset.length();if(distance>range)return;volume*=percent(distance,range,range*sound.taper)}const pan=offset.normalize().dot(this.cameraRight);const rate=pitch+pitch*sound.randomness*randomnessScale*rand(-1,1);return new SoundInstance(sound,volume,rate,pan,loop)}playSoundLoop(sound,pos3D,volume=1,pitch=1,randomnessScale=1){return this.playSound(sound,pos3D,volume,pitch,randomnessScale,true)}isSphereVisible(center,radius){for(const p of this.shadowPass?this.shadowPlanes:this.frustumPlanes)if(p[0]*center.x+p[1]*center.y+p[2]*center.z+p[3]<-radius)return false;return true}drawMesh(mesh,matrix=RENDER3D_IDENTITY,tileInfo,color=WHITE){matrix=render3DMatrix(matrix);ASSERT(!tileInfo||tileInfo instanceof TileInfo||tileInfo instanceof TextureInfo,"tileInfo must be a TileInfo or TextureInfo, it comes before color");ASSERT(isColor(color),"color must be a Color");if(this.capture)return void this.capture.combine(mesh,matrix,color);if(this.transparentQueue)return this.queueTransparent(matrix.getTranslation(),()=>this.drawMesh(mesh,matrix,tileInfo,color));if(!render3DCanDraw())return;if(this.shadowPass&&!this.lighting)return;if(!mesh.buffer||mesh.dirty||mesh.contextGeneration!==this.contextGeneration)mesh.upload();if(!mesh.bufferCount)return;if(this.frustumCulling&&!this.isSphereVisible(matrix.getTranslation(),mesh.radius*render3DMaxScale(matrix.m)))return;const m=matrix.m,cullBackFaces=this.cullBackFaces,mirrored=this.mirrored;this.cullBackFaces=!mesh.doubleSided;this.mirrored=m[0]*(m[5]*m[10]-m[6]*m[9])-m[4]*(m[1]*m[10]-m[2]*m[9])+m[8]*(m[1]*m[6]-m[2]*m[5])<0;if(!this.blend&&this.depthTest&&(mesh.instanced??this.instancing))render3DInstance(mesh,matrix,tileInfo,color);else{this.flush();render3DSetDrawUniforms(matrix,tileInfo,color);render3DBindVertexBuffer(mesh.buffer);glContext.drawArrays(glContext.TRIANGLE_STRIP,0,mesh.bufferCount);++drawCount;primitiveCount+=mesh.bufferCount}this.cullBackFaces=cullBackFaces,this.mirrored=mirrored}drawStrip(points,normals,uvs,colors,tileInfo){if(this.capture){this.capture.addStrip(points,normals,uvs,colors);return}if(this.transparentQueue){let x=0,y=0,z=0;for(const p of points)x+=p.x,y+=p.y,z+=p.z;return this.queueTransparent(vec3(x,y,z).scale(1/points.length),()=>this.drawStrip(points,normals,uvs,colors,tileInfo))}ASSERT(isArray(points)&&points.length>2,"strip needs at least 3 points");const n=points.length,count=render3DStripCount(n);const uvRect=render3DBeginStrip(count,tileInfo);if(!uvRect)return;const floats=this.streamFloats,ints=this.streamInts;const normalArray=isArray(normals),uvArray=isArray(uvs),colorArray=isArray(colors);const rgba=colorArray?0:(colors||WHITE).rgbaInt();for(let k=0;k<count;++k){const i=render3DStripIndex(k,n);const uv=uvArray?uvs[i]:uvs||RENDER3D_DEFAULT_UV;render3DWriteVertex(floats,ints,this.streamCount++*RENDER3D_VERTEX_FLOATS,points[i],normalArray?normals[i]:normals||RENDER3D_DEFAULT_NORMAL,uvRect.x+uv.x*uvRect.w,uvRect.y+uv.y*uvRect.h,colorArray?colors[i].rgbaInt():rgba)}}drawStripUnlit(points,normals,uvs,colors,tileInfo){render3DWithState({lighting:false},()=>this.drawStrip(points,normals,uvs,colors,tileInfo))}flush(){if(!this.streamCount||!render3DCanDraw())return;const gl=glContext;render3DSetDrawUniforms(RENDER3D_IDENTITY,this.streamTileInfo,WHITE,RENDER3D_FULL_UV_RECT,this.streamState);render3DBindVertexBuffer(this.streamBuffer);gl.bufferSubData(gl.ARRAY_BUFFER,0,this.streamFloats,0,this.streamCount*RENDER3D_VERTEX_FLOATS);gl.drawArrays(gl.TRIANGLE_STRIP,0,this.streamCount);++drawCount;primitiveCount+=this.streamCount;this.streamCount=0}bake(drawFunction){this.flush();ASSERT(!this.capture,"bake cannot be nested");const mesh=this.capture=new Mesh;try{drawFunction()}finally{this.capture=undefined}return mesh}renderStages(objects,isDefault=true){const opaque=[],transparent=[];for(const o of objects)(o.transparent||o.additive?transparent:opaque).push(o);isDefault&&this.sky&&this.drawSky();this.blend=false;this.depthWrite=true;const byOrder=(a,b)=>a.renderOrder-b.renderOrder;opaque.sort(byOrder);transparent.sort(byOrder);render3DDrawObjects(opaque);isDefault&&this.onRenderOpaque?.();this.flush();render3DFlushInstances();this.blend=true;this.depthWrite=false;this.transparentQueue=this.sortTransparent?[]:undefined;try{render3DDrawObjects(transparent);for(const o of objects)if(o.softShadow){const m=o.getMatrix();this.drawSoftShadow(m.getTranslation(),o.softShadow*render3DMaxScale(m.m),this.softShadowHeight)}isDefault&&this.onRenderTransparent?.()}finally{this.flushTransparentQueue()}isDefault&&render3DRenderDebug();this.flush();render3DSetObjectState();this.blend=false;this.depthWrite=true}queueTransparent(pos,draw){if(!this.transparentQueue)return draw();this.transparentQueue.push({distance:pos.distanceSquared(this.camera.pos),state:render3DCaptureBatchState(),draw:draw})}flushTransparentQueue(){const queue=this.transparentQueue;if(!queue)return;this.transparentQueue=undefined;queue.sort((a,b)=>b.distance-a.distance);for(const item of queue)render3DWithState(item.state,item.draw)}drawSky(){this.flush();const{near,far}=this.camera;const radius=far==Infinity?near*1e4:(near+far)/2;render3DWithState({lighting:false,blend:false,depthTest:false,depthWrite:false,fogEnd:0,shader:undefined},()=>this.drawMesh(this.sky,buildMatrix(this.camera.pos,undefined,vec3(radius))))}updateShadowMatrix(){ASSERT(this.shadowRange>0,"shadowRange must be positive");const range=this.shadowRange>0?this.shadowRange:1,half=range/2;const toSun=this.sunDirection.normalize();const center=this.shadowCenter||this.camera.pos.add(this.cameraForward.scale(half*.8));const view=Matrix4.lookAt(center.add(toSun.scale(range)),center).invert();const texel=range/(this.shadowTextureSize||this.shadowMapSize),m=view.m;m[12]=round(m[12]/texel)*texel;m[13]=round(m[13]/texel)*texel;this.shadowMatrix=Matrix4.orthographic(-half,half,-half,half,0,range*2).multiply(view);this.shadowPlanes=render3DFrustumPlanes(this.shadowMatrix)}setSky(topColor,horizonColor=hsl(.6,1,.9),bottomColor){this.sky?.dispose();this.sky=buildSky(topColor,horizonColor,bottomColor);this.fogColor=horizonColor.copy();return this.sky}setFog(fogStart,fogEnd,fogColor){this.fogStart=fogStart;this.fogEnd=fogEnd;if(fogColor)this.fogColor=fogColor.copy()}drawBox(pos,size=1,color=WHITE,rotation){this.drawMesh(this.boxMesh,buildMatrix(pos,rotation,render3DSize3(size)),undefined,color)}drawSphere(pos,size=1,color=WHITE){this.drawMesh(this.sphereMesh,buildMatrix(pos,undefined,vec3(size)),undefined,color)}drawBillboard(pos,size=vec2(1),tileInfo,color=WHITE,angle=0,upright=false){if(this.capture)return this.drawStripUnlit(render3DBillboardCorners(pos,size,angle,upright),this.cameraBack,RENDER3D_QUAD_UVS,color,tileInfo);if(this.transparentQueue)return this.queueTransparent(pos,()=>this.drawBillboard(pos,size,tileInfo,color,angle,upright));const count=render3DStripCount(4);const lighting=this.shadowPass&&this.lighting;const uvRect=render3DWithState({lighting:lighting},()=>render3DBeginStrip(count,tileInfo));if(!uvRect)return;const corners=render3DBillboardCorners(pos,size,angle,upright),rgba=color.rgbaInt();const floats=this.streamFloats,ints=this.streamInts;for(let k=0;k<count;++k){const i=render3DStripIndex(k,4),uv=RENDER3D_QUAD_UVS[i];render3DWriteVertex(floats,ints,this.streamCount++*RENDER3D_VERTEX_FLOATS,corners[i],this.cameraBack,uvRect.x+uv.x*uvRect.w,uvRect.y+uv.y*uvRect.h,rgba)}}drawQuad(a,b,c,d,tileInfo,color=WHITE){this.drawStrip(render3DQuadStrip(a,b,c,d),render3DFaceNormal(a,b,c,d),RENDER3D_QUAD_UVS,render3DQuadValues(color),tileInfo)}drawTriangle(a,b,c,color=WHITE){this.drawStrip([a,b,c],render3DFaceNormal(a,b,c),undefined,color)}drawLine(posA,posB,width=.1,color=WHITE){this.drawRibbon([posA,posB],width,undefined,color)}drawRibbon(points,width=.1,tileInfo,color=WHITE,side){const count=points.length;ASSERT(count>1,"a ribbon needs at least two points");ASSERT(!tileInfo||tileInfo instanceof TileInfo||tileInfo instanceof TextureInfo,"tileInfo must be a TileInfo or TextureInfo, it comes before color");const strip=[],uvs=tileInfo?[]:undefined,colors=[],forward=this.cameraForward;let across=vec3(1,0,0);const loop=count>2&&points[0].distanceSquared(points[count-1])<1e-12;for(let i=0;i<count;++i){const p=points[i];const w=isArray(width)?width[i]:width;const c=isArray(color)?color[i]:color;const s=side&&(isArray(side)?side[i]:side);const next=points[i<count-1?i+1:loop?1:i];const last=points[i>0?i-1:loop?count-2:i];const dir=s||next.subtract(last).cross(forward);if(dir.lengthSquared()>1e-12)across=dir.normalize();const half=across.scale(w/2);strip.push(p.add(half),p.subtract(half));uvs?.push(vec2(i/(count-1),0),vec2(i/(count-1),1));colors.push(c,c)}render3DWithState({lighting:false,cullBackFaces:false},()=>this.drawStrip(strip,forward.scale(-1),uvs,colors,tileInfo))}drawSoftDisc(pos,size=1,color=WHITE,normal=this.cameraBack,sides=16){render3DAssertBlending();if(this.transparentQueue&&!this.capture)return this.queueTransparent(pos,()=>this.drawSoftDisc(pos,size,color,normal,sides));const n=normal.normalize();const helper=abs(n.y)<.9?vec3(0,1,0):vec3(1,0,0);const u=helper.cross(n).normalize(),w=u.cross(n);render3DDrawSoftDisc(size/2,color,sides,n,(c,s,r)=>vec3(pos.x+(u.x*c+w.x*s)*r,pos.y+(u.y*c+w.y*s)*r,pos.z+(u.z*c+w.z*s)*r))}drawSoftShadow(pos,size=1,floorHeight=0,color=RENDER3D_SHADOW_COLOR,lift=.02){render3DAssertBlending();const height=isNumber(floorHeight)?()=>floorHeight:floorHeight instanceof HeightMap?(x,z)=>floorHeight.getHeight(x,z):floorHeight;if(this.transparentQueue&&!this.capture)return this.queueTransparent(vec3(pos.x,height(pos.x,pos.z)+lift,pos.z),()=>this.drawSoftShadow(pos,size,floorHeight,color,lift));render3DDrawSoftDisc(size/2,color,16,RENDER3D_DEFAULT_NORMAL,(c,s,r)=>{const x=pos.x+c*r,z=pos.z+s*r;return vec3(x,height(x,z)+lift,z)})}}function render3DAssertBlending(){const r=render3D;ASSERT(r.blend||r.capture||r.shadowPass||!r.isRendering,"soft discs and shadows need blending: set the object transparent or draw from onRenderTransparent")}function render3DDrawSoftDisc(radius,color,sides,normal,pointAt){const alpha=[1,.9,.7,0],circle=render3DCircle(sides);for(let k=0;k<3;++k){const points=[],colors=[];const c0=color.withAlpha(color.a*alpha[k]),c1=color.withAlpha(color.a*alpha[k+1]);const r0=radius*k/3,r1=radius*(k+1)/3;for(let i=0;i<=sides;++i){const c=circle[i*2],s=circle[i*2+1];points.push(pointAt(c,s,r1),pointAt(c,s,r0));colors.push(c1,c0)}render3D.drawStripUnlit(points,normal,undefined,colors)}}let render3DDebugPrimitives=[];function render3DRenderDebug(){if(!render3DDebugPrimitives.length)return;render3DWithState({lighting:false,depthTest:false,receiveShadow:false,additive:false,shader:undefined},()=>{for(const p of render3DDebugPrimitives)p.draw()});render3DDebugPrimitives=render3DDebugPrimitives.filter(p=>p.timer<0)}function render3DDebugPush(duration,draw){ASSERT(isNumber(duration),"duration must be a number");debug&&render3D?.program&&render3DDebugPrimitives.push({timer:new Timer(duration),draw:draw})}function debugBox3D(pos,size=1,color=WHITE,time=0,rotation){const matrix=buildMatrix(pos,rotation,render3DSize3(size));const corner=i=>matrix.transformPoint(vec3(i&1?.5:-.5,i&2?.5:-.5,i&4?.5:-.5));render3DDebugPush(time,()=>{for(let i=0;i<8;++i)for(const bit of[1,2,4])if(!(i&bit))render3D.drawLine(corner(i),corner(i|bit),RENDER3D_DEBUG_WIDTH,color)})}function debugSphere3D(pos,size=1,color=WHITE,time=0){const circle=render3DCircle(24),r=size/2;render3DDebugPush(time,()=>{for(const ring of[(c,s)=>vec3(c,s,0),(c,s)=>vec3(c,0,s),(c,s)=>vec3(0,c,s)]){const points=[];for(let i=0;i<=24;++i)points.push(pos.add(ring(circle[i*2],circle[i*2+1]).scale(r)));render3D.drawRibbon(points,RENDER3D_DEBUG_WIDTH,undefined,color)}})}function debugLine3D(posA,posB,color=WHITE,width=RENDER3D_DEBUG_WIDTH,time=0){render3DDebugPush(time,()=>render3D.drawLine(posA,posB,width,color))}function debugPoint3D(pos,color=WHITE,time=0,size=.2){render3DDebugPush(time,()=>{for(const axis of[vec3(size/2,0,0),vec3(0,size/2,0),vec3(0,0,size/2)])render3D.drawLine(pos.subtract(axis),pos.add(axis),RENDER3D_DEBUG_WIDTH,color)})}class Camera3D{constructor(){this.pos=vec3(0,0,10);this.rotation=vec3();this.fov=PI/3;this.near=.1;this.far=1e3;this.orthographic=0;this.align2D=false}getMatrix(){return buildMatrix(this.pos,this.rotation)}getViewMatrix(){return this.getMatrix().invert()}getProjectionMatrix(aspect){const h=this.orthographic/2,w=h*aspect;return h?Matrix4.orthographic(-w,w,-h,h,this.near,this.far):Matrix4.perspective(this.fov,aspect,this.near,this.far)}getForward(){return render3DAxis(this.getMatrix().m,8).scale(-1)}getRight(){return render3DAxis(this.getMatrix().m,0)}getUp(){return render3DAxis(this.getMatrix().m,4)}lookAt(target){this.rotation=render3DLookRotation(target.subtract(this.pos),this.rotation)}orbit(target,distance,yaw,pitch=.5){const r=cos(pitch)*distance;this.pos=target.add(vec3(sin(yaw)*r,sin(pitch)*distance,cos(yaw)*r));this.lookAt(target)}follow(target,offset,percent=1){this.pos=this.pos.lerp(target.add(offset),percent);this.lookAt(target)}update2D(canvasHeight=mainCanvasSize.y){const halfHeight=canvasHeight/2/cameraScale;const distance=halfHeight/tan(this.fov/2);ASSERT(!canvasHeight||distance<this.far,"align2D needs this camera distance to match the 2D view, raise camera.far past it",distance);this.orthographic&&=halfHeight*2;this.pos=vec3(cameraPos.x,cameraPos.y,distance);this.rotation=vec3(0,0,-cameraAngle)}}const RENDER3D_ATTRIBS=[[0,3,5126,false,0],[1,3,5126,false,12],[2,2,5126,false,24],[3,4,5121,true,32]];const RENDER3D_VERTEX_SOURCE="#version 300 es\n"+"precision highp float;"+"uniform mat4 viewProj,lightViewProj;"+RENDER3D_VERTEX_INPUTS+"out vec3 P,N;out vec2 T,L;out vec4 C,S;"+"void main(){"+"vec4 w=mat4(m0,m1,m2,m3)*vec4(p,1.);"+"gl_Position=viewProj*w;"+"P=w.xyz;"+"N=mat3(n0,n1,n2)*n;"+"T=uvRect.xy+t*uvRect.zw;"+"L=t;"+"C=c*tint;"+"S=lightViewProj*w;"+"}";const RENDER3D_SNIPPET_NAMES="uniform float iTime;uniform vec3 iResolution;\n"+"#define iChannel0 tex\n"+"#define localUV L\n"+"#define worldPos P\n"+"#define worldNormal N\n"+"#define sunDirection (-lightDir.xyz)\n"+"#define sunColor lightColor.rgb\n"+"#define ambientColor ambientFog.rgb\n"+"#define lightCount extraLightCount\n"+"#define lights extraLights\n"+"#define lightColors extraLightColors\n";function render3DFragmentSource(fragmentCode){return"#version 300 es\n"+"precision highp float;"+"uniform vec4 lightDir,lightColor,ambientFog,fogColor,shadowParams;"+"uniform vec4 extraLights["+RENDER3D_MAX_LIGHTS+"],extraLightColors["+RENDER3D_MAX_LIGHTS+"];"+"uniform int extraLightCount;"+"uniform vec3 cameraPos;"+"uniform sampler2D tex;"+"uniform highp sampler2DShadow shadowMap;"+"in vec3 P,N;in vec2 T,L;in vec4 C,S;"+"out vec4 o;"+"float shadow(){"+"if(shadowParams.x<=0.)return 1.;"+"vec3 q=S.xyz/S.w*.5+.5;"+"if(any(greaterThanEqual(abs(q-.5),vec3(.5))))return 1.;"+"q.z-=shadowParams.y;"+"float s=0.;"+"for(int x=-1;x<=1;++x)for(int y=-1;y<=1;++y)"+"s+=texture(shadowMap,vec3(q.xy+vec2(x,y)*shadowParams.z,q.z));"+"return s/9.;}"+(fragmentCode?RENDER3D_SNIPPET_NAMES+fragmentCode+"\n":"")+"void main(){"+(fragmentCode?"vec4 t;mainImage(t,T);":"vec4 t=texture(tex,T);")+"if(shadowParams.w>0.&&t.a<.5)discard;"+"vec4 c=C*t;"+"float e=lightDir.w;"+"if(e<1.){"+"vec3 n=dot(N,N)>0.?normalize(N):vec3(0,1,0);"+"if(!gl_FrontFacing)n=-n;"+"float nl=dot(n,-lightDir.xyz);"+"float s=shadow();"+"vec3 l=ambientFog.rgb+lightColor.rgb*max(nl,0.)*s;"+"for(int i=0;i<"+RENDER3D_MAX_LIGHTS+";++i){"+"if(i>=extraLightCount)break;"+"vec4 L=extraLights[i];"+"bool directional=L.w<0.;"+"vec3 v=directional?L.xyz:L.xyz-P;"+"float d=length(v);"+"float a=directional?1.:max(0.,1.-d/L.w);"+"l+=extraLightColors[i].rgb*extraLightColors[i].a*a*a*max(0.,dot(n,v/max(d,1e-6)));"+"}"+"c.rgb*=l*(1.-e)+e;"+"if(lightColor.a>0.){"+"vec3 v=normalize(cameraPos-P);"+"vec3 r=reflect(lightDir.xyz,n);"+"c.rgb+=lightColor.rgb*pow(max(dot(r,v),0.),16.)*lightColor.a*step(0.,nl)*s*(1.-e);"+"}}else c.rgb*=e;"+"if(ambientFog.a>0.){"+"float z=distance(cameraPos,P);"+"c.rgb=mix(c.rgb,shadowParams.w<0.?vec3(0):fogColor.rgb,smoothstep(fogColor.a,ambientFog.a,z));"+"}"+"o=vec4(c.rgb,shadowParams.w>0.?1.:c.a);"+"}"}function render3DShaderProgram(shader){ASSERT(shader instanceof Shader,"render3D.shader must be a Shader, not the snippet itself");return shader.program3D||=glCreateProgram(RENDER3D_VERTEX_SOURCE,render3DFragmentSource(shader.fragmentCode))}function render3DUseProgram(program){const gl=glContext,r=render3D;gl.useProgram(r.currentProgram=program);r.uniformValues={};gl.uniformMatrix4fv(render3DUniform("viewProj"),false,r.viewProjection.m);gl.uniformMatrix4fv(render3DUniform("lightViewProj"),false,r.shadowMatrix.m);gl.uniform1i(render3DUniform("tex"),0);gl.uniform1i(render3DUniform("shadowMap"),1);const c=r.camera.pos;gl.uniform3f(render3DUniform("cameraPos"),c.x,c.y,c.z);gl.uniform1i(render3DUniform("extraLightCount"),r.lightCount);if(r.lightCount){gl.uniform4fv(render3DUniform("extraLights"),r.lightPositions,0,r.lightCount*4);gl.uniform4fv(render3DUniform("extraLightColors"),r.lightColors,0,r.lightCount*4)}if(program!==r.program){gl.uniform1f(render3DUniform("iTime"),time);gl.uniform3f(render3DUniform("iResolution"),glCanvas.width,glCanvas.height,1)}}function render3DInitGL(){if(headlessMode)return;if(!glEnable||!glContext){console.warn("Render3DPlugin: WebGL not enabled, construct the plugin in gameInit with glEnable set");return}const gl=glContext,r=render3D;r.uniforms=new Map;r.uniformValues={};r.attribValues=[];r.program=glCreateProgram(RENDER3D_VERTEX_SOURCE,render3DFragmentSource());r.shadowShader=glCreateProgram("#version 300 es\n"+"precision highp float;"+"uniform mat4 viewProj;"+RENDER3D_VERTEX_INPUTS+"out vec2 T;"+"void main(){T=uvRect.xy+t*uvRect.zw;gl_Position=viewProj*mat4(m0,m1,m2,m3)*vec4(p,1.);}","#version 300 es\n"+"precision highp float;"+"uniform sampler2D tex;"+"in vec2 T;"+"void main(){if(texture(tex,T).a<.5)discard;}");r.vao=gl.createVertexArray();gl.bindVertexArray(r.vao);for(const[location]of RENDER3D_ATTRIBS)gl.enableVertexAttribArray(location);for(const[location]of RENDER3D_INSTANCE_ATTRIBS)gl.vertexAttribDivisor(location,1);r.streamBuffer=gl.createBuffer();gl.bindBuffer(gl.ARRAY_BUFFER,r.streamBuffer);gl.bufferData(gl.ARRAY_BUFFER,r.streamData.byteLength,gl.DYNAMIC_DRAW);r.streamCount=0;r.instanceBuffers=[gl.createBuffer(),gl.createBuffer(),gl.createBuffer()];r.whiteTexture=glCreateTexture();r.mipmapped=new WeakSet;r.samplers=[];r.samplerKey=undefined;render3DUpdateShadowMap(1);gl.bindBuffer(gl.ARRAY_BUFFER,glArrayBuffer);glSetInstancedMode(true)}function render3DContextLost(){const r=render3D;r.program=r.currentProgram=r.shadowShader=r.vao=r.streamBuffer=r.whiteTexture=undefined;for(const shader of glShaderObjects)shader.program3D=undefined;r.lightCount=0;r.instanceBuffers=r.samplers=[];r.samplerKey=undefined;render3DClearInstances();r.shadowFramebuffer=r.shadowTexture=undefined;r.shadowTextureSize=0;r.streamCount=0;++r.contextGeneration}function render3DContextRestored(){render3DInitGL()}function render3DUniform(name,program=render3D.currentProgram){const u=render3D.uniforms;let cache=u.get(program);cache||u.set(program,cache={});return cache[name]??=glContext.getUniformLocation(program,name)}const render3DNormalScratch=new Float32Array(9);function render3DDrawAttribs(m,tint,uvRect){const gl=glContext;gl.vertexAttrib4f(4,m[0],m[1],m[2],m[3]);gl.vertexAttrib4f(5,m[4],m[5],m[6],m[7]);gl.vertexAttrib4f(6,m[8],m[9],m[10],m[11]);gl.vertexAttrib4f(7,m[12],m[13],m[14],m[15]);if(!render3D.shadowPass){const n=render3DNormalMatrix3(m,render3DNormalScratch,0);gl.vertexAttrib3f(8,n[0],n[1],n[2]);gl.vertexAttrib3f(9,n[3],n[4],n[5]);gl.vertexAttrib3f(10,n[6],n[7],n[8])}render3DAttrib4f(11,tint.r,tint.g,tint.b,tint.a);render3DAttrib4f(12,uvRect.x,uvRect.y,uvRect.w,uvRect.h)}function render3DAttrib4f(location,x,y,z,w){const values=render3D.attribValues,last=values[location];if(last&&last[0]===x&&last[1]===y&&last[2]===z&&last[3]===w)return;values[location]=[x,y,z,w];glContext.vertexAttrib4f(location,x,y,z,w)}function render3DNormalMatrix3(m,out,offset){const a=m[0],b=m[1],c=m[2],d=m[4],e=m[5],f=m[6],g=m[8],h=m[9],i=m[10];const c00=e*i-h*f,c01=h*c-b*i,c02=b*f-e*c;const det=a*c00+d*c01+g*c02;if(abs(det)<1e-12){out[offset]=a;out[offset+1]=b;out[offset+2]=c;out[offset+3]=d;out[offset+4]=e;out[offset+5]=f;out[offset+6]=g;out[offset+7]=h;out[offset+8]=i;return out}const s=1/det;out[offset]=c00*s;out[offset+1]=(g*f-d*i)*s;out[offset+2]=(d*h-g*e)*s;out[offset+3]=c01*s;out[offset+4]=(a*i-g*c)*s;out[offset+5]=(g*b-a*h)*s;out[offset+6]=c02*s;out[offset+7]=(d*c-a*f)*s;out[offset+8]=(a*e-d*b)*s;return out}function render3DUpdateSamplers(){const gl=glContext,r=render3D,key=tilesPixelated+" "+r.anisotropy;if(r.samplerKey===key)return;r.samplerKey=key;for(const sampler of r.samplers)gl.deleteSampler(sampler);const anisotropy=gl.getExtension("EXT_texture_filter_anisotropic");r.samplers=[false,true].flatMap(pixelated=>[gl.CLAMP_TO_EDGE,gl.REPEAT].map(wrap=>{const sampler=gl.createSampler();const sharp=pixelated||tilesPixelated;gl.samplerParameteri(sampler,gl.TEXTURE_MAG_FILTER,sharp?gl.NEAREST:gl.LINEAR);gl.samplerParameteri(sampler,gl.TEXTURE_MIN_FILTER,pixelated?gl.NEAREST:tilesPixelated?gl.NEAREST_MIPMAP_LINEAR:gl.LINEAR_MIPMAP_LINEAR);gl.samplerParameteri(sampler,gl.TEXTURE_WRAP_S,wrap);gl.samplerParameteri(sampler,gl.TEXTURE_WRAP_T,wrap);if(anisotropy&&!pixelated){const most=gl.getParameter(anisotropy.MAX_TEXTURE_MAX_ANISOTROPY_EXT);gl.samplerParameterf(sampler,anisotropy.TEXTURE_MAX_ANISOTROPY_EXT,clamp(r.anisotropy,1,most))}return sampler}))}function render3DBindTexture(tileInfo,state=render3D){const gl=glContext,r=render3D;const textureInfo=tileInfo instanceof TileInfo?tileInfo.textureInfo:tileInfo;const texture=textureInfo?.glTexture||r.whiteTexture;gl.bindTexture(gl.TEXTURE_2D,texture);if(!r.mipmaps&&!state.pixelated)return gl.bindSampler(0,null);gl.bindSampler(0,r.samplers[(textureInfo?.wrap?1:0)+(state.pixelated?2:0)]);if(!state.pixelated&&!r.mipmapped.has(texture)){r.mipmapped.add(texture);gl.generateMipmap(gl.TEXTURE_2D)}}function render3DUniform4f(name,x,y,z,w){const values=render3D.uniformValues,last=values[name];if(last&&last[0]===x&&last[1]===y&&last[2]===z&&last[3]===w)return;values[name]=[x,y,z,w];glContext.uniform4f(render3DUniform(name),x,y,z,w)}function render3DBindVertexBuffer(buffer){const gl=glContext;gl.bindBuffer(gl.ARRAY_BUFFER,buffer);for(const a of RENDER3D_ATTRIBS)gl.vertexAttribPointer(a[0],a[1],a[2],a[3],RENDER3D_VERTEX_BYTES,a[4])}const render3DTileUVRect={x:0,y:0,w:1,h:1};function render3DGetTileUVs(tileInfo){if(!(tileInfo instanceof TileInfo))return RENDER3D_FULL_UV_RECT;const inv=tileInfo.textureInfo.sizeInverse,rect=render3DTileUVRect;const bleedX=inv.x*tileInfo.bleed,bleedY=inv.y*tileInfo.bleed;rect.x=tileInfo.pos.x*inv.x+bleedX;rect.y=tileInfo.pos.y*inv.y+bleedY;rect.w=tileInfo.size.x*inv.x-2*bleedX;rect.h=tileInfo.size.y*inv.y-2*bleedY;return rect}function render3DSetDrawUniforms(matrix,tileInfo,tint,uvRect,state=render3D){const gl=glContext,r=render3D;uvRect||=render3DGetTileUVs(tileInfo);render3DDrawAttribs(matrix.m,tint,uvRect);render3DBindTexture(tileInfo,state);if(r.shadowPass)return;const program=state.shader?render3DShaderProgram(state.shader):r.program;program===r.currentProgram||render3DUseProgram(program);if(state.blend){gl.enable(gl.BLEND);const destBlend=state.additive?gl.ONE:gl.ONE_MINUS_SRC_ALPHA;gl.blendFuncSeparate(gl.SRC_ALPHA,destBlend,gl.ONE,destBlend)}else gl.disable(gl.BLEND);state.depthTest?gl.enable(gl.DEPTH_TEST):gl.disable(gl.DEPTH_TEST);gl.depthMask(state.depthWrite);state.cullBackFaces?gl.enable(gl.CULL_FACE):gl.disable(gl.CULL_FACE);gl.frontFace(state.mirrored?gl.CCW:gl.CW);const s=r.sunDirection,sl=-(s.length()||1),lc=r.sunColor,ac=r.ambientColor,fc=r.fogColor||canvasClearColor;render3DUniform4f("lightDir",s.x/sl,s.y/sl,s.z/sl,state.lighting?state.emissive:1);render3DUniform4f("lightColor",lc.r,lc.g,lc.b,state.specular);render3DUniform4f("ambientFog",ac.r,ac.g,ac.b,r.fogEnd);render3DUniform4f("fogColor",fc.r,fc.g,fc.b,r.fogStart);const blendMode=state.blend?state.additive?-1:0:1;render3DUniform4f("shadowParams",r.shadows&&r.passIsDefault&&state.receiveShadow?1:0,r.shadowBias,r.shadowSoftness/r.shadowTextureSize,blendMode)}function render3DFrustumPlanes(matrix){const m=matrix.m,planes=[];for(let i=0;i<3;++i)for(const sign of[1,-1]){const p=[m[3]+sign*m[i],m[7]+sign*m[4+i],m[11]+sign*m[8+i],m[15]+sign*m[12+i]];const l=hypot(p[0],p[1],p[2])||1;planes.push(p.map(v=>v/l))}return planes}function render3DPreRender(){const r=render3D;r.updateMatrices();r.shadowMapDrawn=false;render3DRenderPass(false)}function render3DRender(){render3DRenderPass(true)}function render3DRenderPass(after2D){const gl=glContext,r=render3D;if(!r.program)return;render3DUpdateSamplers();ASSERT(!r.fogEnd||r.fogStart<r.fogEnd,"fogStart must be less than fogEnd");ASSERT(!glRenderTarget,"the 3D pass needs the canvas depth buffer, it can not draw into a render target");const isDefault=after2D===!!r.renderAfter2D,objects=render3DLayerObjects(after2D);if(!isDefault&&!objects.length)return;r.passIsDefault=isDefault;after2D&&glFlush();r.streamCount=0;r.capture=r.transparentQueue=undefined;render3DClearInstances();gl.bindVertexArray(r.vao);gl.frontFace(gl.CW);gl.activeTexture(gl.TEXTURE0);gl.depthMask(true);gl.clear(gl.DEPTH_BUFFER_BIT);const lights=render3DCollectLights();r.lightCount=lights.length;const positions=r.lightPositions,colors=r.lightColors;lights.forEach((light,i)=>{const p=light.directional?light.getWorldPos3D().normalize():light.getWorldPos3D();ASSERT(!light.directional||p.lengthSquared(),"a directional light shines from its position toward the origin, so it cannot sit on the origin");const c=light.color,k=i*4;positions[k]=p.x,positions[k+1]=p.y,positions[k+2]=p.z;positions[k+3]=light.directional?-1:max(0,light.radius);colors[k]=c.r,colors[k+1]=c.g,colors[k+2]=c.b,colors[k+3]=c.a*light.intensity});r.isRendering=true;try{if(r.shadows&&!r.shadowMapDrawn){render3DRenderShadowMap();r.shadowMapDrawn=true}render3DUseProgram(r.program);r.renderStages(objects,isDefault)}finally{r.isRendering=false;r.currentProgram=undefined;r.streamCount=0;r.capture=r.transparentQueue=undefined;gl.disable(gl.DEPTH_TEST);gl.disable(gl.CULL_FACE);gl.depthMask(true);gl.frontFace(gl.CCW);gl.bindSampler(0,null);if(glActiveTexture)gl.bindTexture(gl.TEXTURE_2D,glActiveTexture);gl.bindBuffer(gl.ARRAY_BUFFER,glArrayBuffer);glSetInstancedMode(true)}}function render3DUpdateShadowMap(size){const gl=glContext,r=render3D;ASSERT(size>0,"shadowMapSize must be positive");if(r.shadowTexture&&r.shadowTextureSize===size)return;r.shadowTexture&&gl.deleteTexture(r.shadowTexture);r.shadowFramebuffer&&gl.deleteFramebuffer(r.shadowFramebuffer);const texture=r.shadowTexture=gl.createTexture();gl.activeTexture(gl.TEXTURE1);gl.bindTexture(gl.TEXTURE_2D,texture);gl.texImage2D(gl.TEXTURE_2D,0,gl.DEPTH_COMPONENT24,size,size,0,gl.DEPTH_COMPONENT,gl.UNSIGNED_INT,null);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MIN_FILTER,gl.LINEAR);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MAG_FILTER,gl.LINEAR);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_S,gl.CLAMP_TO_EDGE);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_T,gl.CLAMP_TO_EDGE);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_COMPARE_MODE,gl.COMPARE_REF_TO_TEXTURE);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_COMPARE_FUNC,gl.LEQUAL);gl.activeTexture(gl.TEXTURE0);const framebuffer=r.shadowFramebuffer=gl.createFramebuffer();gl.bindFramebuffer(gl.FRAMEBUFFER,framebuffer);gl.framebufferTexture2D(gl.FRAMEBUFFER,gl.DEPTH_ATTACHMENT,gl.TEXTURE_2D,texture,0);gl.drawBuffers([gl.NONE]);gl.readBuffer(gl.NONE);ASSERT(gl.checkFramebufferStatus(gl.FRAMEBUFFER)==gl.FRAMEBUFFER_COMPLETE,"shadow map framebuffer is incomplete, try a smaller shadowMapSize");gl.bindFramebuffer(gl.FRAMEBUFFER,null);r.shadowTextureSize=size}function render3DRenderShadowMap(){const gl=glContext,r=render3D;render3DUpdateShadowMap(r.shadowMapSize|0);r.updateShadowMatrix();gl.activeTexture(gl.TEXTURE1);gl.bindTexture(gl.TEXTURE_2D,null);gl.activeTexture(gl.TEXTURE0);gl.bindFramebuffer(gl.FRAMEBUFFER,r.shadowFramebuffer);gl.viewport(0,0,r.shadowTextureSize,r.shadowTextureSize);gl.clear(gl.DEPTH_BUFFER_BIT);gl.useProgram(r.shadowShader);gl.uniformMatrix4fv(render3DUniform("viewProj",r.shadowShader),false,r.shadowMatrix.m);gl.enable(gl.DEPTH_TEST);gl.depthMask(true);gl.disable(gl.BLEND);gl.disable(gl.CULL_FACE);r.shadowPass=true;try{const casters=render3DLayerObjects(!!r.renderAfter2D).filter(o=>o.castShadow&&!o.additive&&(!o.transparent||o.tileInfo));render3DDrawObjects(casters);r.onRenderOpaque?.();r.flush();render3DFlushInstances()}finally{r.shadowPass=false;gl.bindFramebuffer(gl.FRAMEBUFFER,null);gl.viewport(0,0,glCanvas.width,glCanvas.height);gl.activeTexture(gl.TEXTURE1);gl.bindTexture(gl.TEXTURE_2D,r.shadowTexture);gl.activeTexture(gl.TEXTURE0)}}function render3DBeginStrip(count,tileInfo){const r=render3D;if(!render3DCanDraw())return;if(r.shadowPass&&!r.lighting)return;ASSERT(count<=RENDER3D_MAX_STREAM_VERTS,"strip is too large for the stream, bake it into a mesh");if(count>RENDER3D_MAX_STREAM_VERTS)return;const textureInfo=tileInfo instanceof TileInfo?tileInfo.textureInfo:tileInfo;if(r.streamCount&&(textureInfo!==r.streamTileInfo||render3DStateChanged(r.streamState)||r.streamCount+count>RENDER3D_MAX_STREAM_VERTS))r.flush();if(!r.streamCount)r.streamState=render3DCaptureBatchState();r.streamTileInfo=textureInfo;return render3DGetTileUVs(tileInfo)}function render3DBillboardCorners(pos,size,angle,upright){let r=render3D.cameraRight,u=render3D.cameraUp;if(upright){const flat=vec3(r.x,0,r.z);r=flat.lengthSquared()?flat.normalize():vec3(1,0,0);u=RENDER3D_DEFAULT_NORMAL}const c=cos(angle),s=sin(angle),w=size.x/2,h=size.y/2;const rx=(r.x*c+u.x*s)*w,ry=(r.y*c+u.y*s)*w,rz=(r.z*c+u.z*s)*w;const ux=(u.x*c-r.x*s)*h,uy=(u.y*c-r.y*s)*h,uz=(u.z*c-r.z*s)*h;return[vec3(pos.x-rx+ux,pos.y-ry+uy,pos.z-rz+uz),vec3(pos.x-rx-ux,pos.y-ry-uy,pos.z-rz-uz),vec3(pos.x+rx+ux,pos.y+ry+uy,pos.z+rz+uz),vec3(pos.x+rx-ux,pos.y+ry-uy,pos.z+rz-uz)]}function render3DStripCount(n){return n+2+(n&1)}function render3DStripIndex(k,n){return k<1?0:k<=n?k-1:n-1}function render3DForEachStripVertex(points,normals,uvs,colors,callback){ASSERT(isArray(points)&&points.length>2,"strip needs at least 3 points");const n=points.length,count=render3DStripCount(n);const normalArray=isArray(normals),uvArray=isArray(uvs),colorArray=isArray(colors);for(let k=0;k<count;++k){const i=render3DStripIndex(k,n);callback(points[i],normalArray?normals[i]:normals||RENDER3D_DEFAULT_NORMAL,uvArray?uvs[i]:uvs||RENDER3D_DEFAULT_UV,colorArray?colors[i]:colors||WHITE)}}function render3DWriteVertex(floats,ints,j,p,n,u,v,rgba){floats[j]=p.x;floats[j+1]=p.y;floats[j+2]=p.z;floats[j+3]=n.x;floats[j+4]=n.y;floats[j+5]=n.z;floats[j+6]=u;floats[j+7]=v;ints[j+8]=rgba}function render3DPolygonStrip(points){const strip=[points[0]];for(let i=1,j=points.length-1;i<=j;++i,--j){strip.push(points[i]);if(i!==j)strip.push(points[j])}return strip}const render3DMeshBuffers=typeof FinalizationRegistry=="undefined"?undefined:new FinalizationRegistry(({buffer,generation})=>generation===render3D?.contextGeneration&&glContext?.deleteBuffer(buffer));class Mesh{constructor(){this.points=[];this.normals=[];this.uvs=[];this.colors=[];this.buffer=undefined;this.bufferCount=0;this.dirty=false;this.instanced=undefined;this.doubleSided=false;this.instanceCount=0;this.instanceData=undefined;this.radius=0;this.contextGeneration=0}get vertexCount(){return this.points.length}addStrip(points,normals,uvs,colors){render3DForEachStripVertex(points,normals,uvs,colors,(p,n,uv,c)=>{this.points.push(p);this.normals.push(n);this.uvs.push(uv);this.colors.push(c)});this.dirty=true;return this}addQuad(a,b,c,d,color,uvs){return this.addStrip(render3DQuadStrip(a,b,c,d),render3DFaceNormal(a,b,c,d),uvs?render3DQuadValues(uvs):RENDER3D_QUAD_UVS,render3DQuadValues(color))}combine(mesh,matrix=RENDER3D_IDENTITY,color=WHITE){matrix=render3DMatrix(matrix);const normalMatrix=render3DNormalMatrix(matrix);for(let i=0;i<mesh.points.length;++i){this.points.push(matrix.transformPoint(mesh.points[i]));this.normals.push(normalMatrix.transformDirection(mesh.normals[i]||RENDER3D_DEFAULT_NORMAL).normalize());this.uvs.push((mesh.uvs[i]||RENDER3D_DEFAULT_UV).copy());this.colors.push((mesh.colors[i]||WHITE).multiply(color))}this.doubleSided||=mesh.doubleSided;this.dirty=true;return this}scaleUVs(scale){const s=isNumber(scale)?vec2(scale):scale;this.uvs=this.uvs.map(uv=>vec2(uv.x*s.x,uv.y*s.y));this.dirty=true;return this}transform(matrix){matrix=render3DMatrix(matrix);const normalMatrix=render3DNormalMatrix(matrix);for(let i=0;i<this.points.length;++i){this.points[i]=matrix.transformPoint(this.points[i]);this.normals[i]&&=normalMatrix.transformDirection(this.normals[i]).normalize()}this.dirty=true;return this}flipNormals(){for(const key of["points","normals","uvs","colors"]){const a=this[key];if(a.length)a.unshift(a[0]),a.push(a[a.length-1])}this.normals=this.normals.map(n=>n.scale(-1));this.dirty=true;return this}setColor(color){this.colors=this.points.map(()=>color);this.dirty=true;return this}getBounds(){if(!this.points.length)return{min:vec3(),max:vec3()};const lo=vec3(Infinity),hi=vec3(-Infinity);for(const p of this.points){lo.x=min(lo.x,p.x);lo.y=min(lo.y,p.y);lo.z=min(lo.z,p.z);hi.x=max(hi.x,p.x);hi.y=max(hi.y,p.y);hi.z=max(hi.z,p.z)}return{min:lo,max:hi}}center(){const bounds=this.getBounds();return this.transform(bounds.min.add(bounds.max).scale(-.5))}fit(size=1){const bounds=this.getBounds();const extent=bounds.max.subtract(bounds.min);const scale=size/(max(extent.x,extent.y,extent.z)||1);return this.transform(Matrix4.scaling(vec3(scale)))}computeRadius(){let r=0;for(const p of this.points)r=max(r,p.lengthSquared());return this.radius=r**.5}computeNormals(smooth=false){const points=this.points,n=points.length;const faceNormals=[];for(let i=0;i+2<n;++i){const a=points[i],b=points[i+1],c=points[i+2];const normal=b.subtract(a).cross(c.subtract(a));faceNormals.push(normal.lengthSquared()?normal.normalize(i&1?1:-1):undefined)}const normals=points.map(()=>RENDER3D_DEFAULT_NORMAL);if(smooth){const sums=new Map;const key=p=>`${round(p.x*1e5)},${round(p.y*1e5)},${round(p.z*1e5)}`;faceNormals.forEach((f,i)=>f&&[0,1,2].forEach(j=>{const a=points[i+j],u=points[i+(j+1)%3].subtract(a),v=points[i+(j+2)%3].subtract(a);const angle=Math.acos(clamp(u.dot(v)/(u.length()*v.length()||1),-1,1));const k=key(a);sums.set(k,(sums.get(k)||vec3()).add(f.scale(angle)))}));for(let i=0;i<n;++i)normals[i]=(sums.get(key(points[i]))||RENDER3D_DEFAULT_NORMAL).normalize()}else faceNormals.forEach((f,i)=>f&&(normals[i]=normals[i+1]=normals[i+2]=f));this.normals=normals;this.dirty=true;return this}upload(){this.computeRadius();if(!render3D?.program)return this;this.dispose();const count=this.points.length;const data=new ArrayBuffer(count*RENDER3D_VERTEX_BYTES);const floats=new Float32Array(data),ints=new Uint32Array(data);for(let i=0;i<count;++i){const uv=this.uvs[i]||RENDER3D_DEFAULT_UV;render3DWriteVertex(floats,ints,i*RENDER3D_VERTEX_FLOATS,this.points[i],this.normals[i]||RENDER3D_DEFAULT_NORMAL,uv.x,uv.y,(this.colors[i]||WHITE).rgbaInt())}const gl=glContext;this.buffer=gl.createBuffer();this.bufferCount=count;this.dirty=false;gl.bindBuffer(gl.ARRAY_BUFFER,this.buffer);gl.bufferData(gl.ARRAY_BUFFER,data,gl.STATIC_DRAW);this.contextGeneration=render3D.contextGeneration;render3DMeshBuffers?.register(this,{buffer:this.buffer,generation:this.contextGeneration},this);gl.bindBuffer(gl.ARRAY_BUFFER,glArrayBuffer);return this}render(matrix,tileInfo,color){render3D?.drawMesh(this,matrix,tileInfo,color)}dispose(){if(!this.buffer)return;render3DMeshBuffers?.unregister(this);if(this.contextGeneration===render3D?.contextGeneration)glContext?.deleteBuffer(this.buffer);this.buffer=undefined;this.bufferCount=0}}function buildLathe(profile,sides=16,smooth=render3D?.smoothShading,capped=true){ASSERT(isArray(profile)&&profile.length>1,"lathe profile needs at least 2 points");sides|=0;ASSERT(sides>2,"lathe needs at least 3 sides");const mesh=new Mesh;const rings=profile.length;const point=(i,a)=>vec3(sin(a)*profile[i][0],profile[i][1],cos(a)*profile[i][0]);const segmentNormal=i=>{const[r0,y0]=profile[i],[r1,y1]=profile[i+1];const n=vec2(y1-y0,r0-r1);return n.length()?n.normalize():vec2(1,0)};const closed=rings>2&&abs(profile[0][0]-profile[rings-1][0])<1e-9&&abs(profile[0][1]-profile[rings-1][1])<1e-9;const segmentLength=i=>hypot(profile[i+1][0]-profile[i][0],profile[i+1][1]-profile[i][1]);const vertexNormal=i=>{if(!closed&&(!i||i==rings-1)&&abs(profile[i][0])<1e-9)return vec2(0,i?1:-1);let n=vec2();const add=s=>n=n.add(segmentNormal(s).scale(segmentLength(s)));if(i>0)add(i-1);else if(closed)add(rings-2);if(i<rings-1)add(i);else if(closed)add(0);return n.length()?n.normalize():vec2(1,0)};const normal3D=(n,a)=>vec3(sin(a)*n.x,n.y,cos(a)*n.x);const lengths=[0];for(let i=1;i<rings;++i)lengths[i]=lengths[i-1]+hypot(profile[i][0]-profile[i-1][0],profile[i][1]-profile[i-1][1]);const total=lengths[rings-1]||1;const v=i=>1-lengths[i]/total;for(let i=0;i+1<rings;++i){if(smooth){const points=[],normals=[],uvs=[];const n0=vertexNormal(i),n1=vertexNormal(i+1);for(let j=0;j<=sides;++j){const a=j/sides*2*PI,u=j/sides;points.push(point(i+1,a),point(i,a));normals.push(normal3D(n1,a),normal3D(n0,a));uvs.push(vec2(u,v(i+1)),vec2(u,v(i)))}mesh.addStrip(points,normals,uvs)}else{const n=segmentNormal(i);for(let j=0;j<sides;++j){const a0=j/sides*2*PI,a1=(j+1)/sides*2*PI;const u0=j/sides,u1=(j+1)/sides;mesh.addStrip([point(i+1,a0),point(i,a0),point(i+1,a1),point(i,a1)],normal3D(n,(a0+a1)/2),[vec2(u0,v(i+1)),vec2(u0,v(i)),vec2(u1,v(i+1)),vec2(u1,v(i))])}}}if(capped&&!closed)for(const[i,up]of[[0,false],[rings-1,true]]){if(abs(profile[i][0])<1e-9)continue;const points=[],uvs=[];for(let j=0;j<sides;++j){const a=(up?j:-j)/sides*2*PI;points.push(point(i,a));uvs.push(vec2(sin(a)*.5+.5,cos(a)*.5+.5))}mesh.addStrip(render3DPolygonStrip(points),vec3(0,up?1:-1,0),render3DPolygonStrip(uvs))}mesh.doubleSided=!closed&&!capped&&(abs(profile[0][0])>1e-9||abs(profile[rings-1][0])>1e-9);return mesh}function buildCylinder(size=1,height=1,sides=16,smooth=render3D?.smoothShading,capped=true){return buildLathe([[size/2,-height/2],[size/2,height/2]],sides,smooth,capped)}function buildCone(size=1,height=1,sides=16,smooth=render3D?.smoothShading,capped=true){return buildLathe([[size/2,-height/2],[0,height/2]],sides,smooth,capped)}function buildSphere(size=1,sides=16,rings=8,smooth=render3D?.smoothShading){ASSERT(rings>1,"sphere needs at least 2 rings");const profile=[];for(let i=0;i<=rings;++i){const a=i/rings*PI-PI/2;profile.push([cos(a)*size/2,sin(a)*size/2])}return buildLathe(profile,sides,smooth)}function buildCapsule(size=1,height=1,sides=16,rings=4,smooth=render3D?.smoothShading){ASSERT(height>=size,"a capsule is at least as tall as it is wide, the ends take up the size",size,height);const profile=[],r=size/2,straight=max(0,height-size)/2;for(let i=0;i<=rings;++i){const a=i/rings*PI/2;profile.push([r*sin(a),-straight-r*cos(a)])}for(let i=0;i<=rings;++i){const a=i/rings*PI/2;profile.push([r*cos(a),straight+r*sin(a)])}return buildLathe(profile,sides,smooth)}function buildTorus(size=1,tubeSize=.3,sides=16,tubeSides=8,smooth=render3D?.smoothShading){ASSERT(tubeSize<=size,"the tube must fit inside the torus");const profile=[],radius=(size-tubeSize)/2,tubeRadius=tubeSize/2;for(let i=0;i<=tubeSides;++i){const a=i/tubeSides*2*PI;profile.push([radius+tubeRadius*cos(a),tubeRadius*sin(a)])}return buildLathe(profile,sides,smooth)}function buildBox(size=1){const mesh=new Mesh;const half=render3DSize3(size).scale(.5);const faces=[[vec3(0,0,1),vec3(1,0,0),vec3(0,1,0)],[vec3(0,0,-1),vec3(-1,0,0),vec3(0,1,0)],[vec3(1,0,0),vec3(0,0,-1),vec3(0,1,0)],[vec3(-1,0,0),vec3(0,0,1),vec3(0,1,0)],[vec3(0,1,0),vec3(1,0,0),vec3(0,0,-1)],[vec3(0,-1,0),vec3(1,0,0),vec3(0,0,1)]];for(const[n,r,u]of faces){const center=n.multiply(half);const right=r.multiply(half),up=u.multiply(half);mesh.addStrip(render3DQuadAxes(center,right,up),n,RENDER3D_QUAD_UVS)}return mesh}function buildRibbon(points,width=1,color=WHITE,closed=false,up=vec3(0,1,0)){ASSERT(isArray(points)&&points.length>1,"ribbon needs at least 2 points");const mesh=new Mesh,count=points.length,edges=[];let across=(abs(up.y)<.9?vec3(0,1,0):vec3(1,0,0)).cross(up).normalize();for(let i=0;i<count;++i){const next=points[closed?(i+1)%count:min(i+1,count-1)];const last=points[closed?(i+count-1)%count:max(i-1,0)];const dir=next.subtract(last).cross(up);if(dir.lengthSquared()>1e-12)across=dir.normalize();const half=across.scale((isArray(width)?width[i]:width)/2);edges.push([points[i].subtract(half),points[i].add(half)])}for(let i=0;i+1<count+(closed?1:0);++i){const j=(i+1)%count,a=edges[i],b=edges[j];const c=isArray(color)?[color[i],color[i],color[j],color[j]]:color;mesh.addQuad(a[0],a[1],b[1],b[0],c)}mesh.doubleSided=true;return mesh}function buildGrid(size=vec2(1),segments=1,color,heightFunction=()=>0,smooth=render3D?.smoothShading){if(isNumber(segments))segments=vec2(segments);ASSERT(segments.x>0&&segments.y>0&&segments.x%1===0&&segments.y%1===0,"grid segments must be whole numbers above zero");const mesh=new Mesh;const segmentsX=segments.x,segmentsZ=segments.y;const cellX=size.x/segmentsX,cellZ=size.y/segmentsZ;const px=i=>i*cellX-size.x/2,pz=j=>j*cellZ-size.y/2;const point=(i,j)=>{const x=px(i),z=pz(j);return vec3(x,heightFunction(x,z),z)};const normal=(i,j)=>render3DSlopeNormal(heightFunction,px(i),pz(j),cellX/2,cellZ/2,size.x/2,size.y/2);const uv=(i,j)=>vec2(i/segmentsX,j/segmentsZ);const cellColor=(i,j)=>!color?WHITE:isColor(color)?color:color(px(i),pz(j));for(let j=0;j<segmentsZ;++j){if(smooth){const points=[],normals=[],uvs=[],colors=[];for(let i=0;i<=segmentsX;++i){points.push(point(i,j),point(i,j+1));normals.push(normal(i,j),normal(i,j+1));uvs.push(uv(i,j),uv(i,j+1));colors.push(cellColor(i,j),cellColor(i,j+1))}mesh.addStrip(points,normals,uvs,colors)}else{for(let i=0;i<segmentsX;++i)mesh.addQuad(point(i,j),point(i,j+1),point(i+1,j+1),point(i+1,j),cellColor(i+.5,j+.5),[uv(i,j),uv(i,j+1),uv(i+1,j+1),uv(i+1,j)])}}mesh.doubleSided=true;return mesh}function buildLoft(stations){ASSERT(isArray(stations)&&stations.length>1,"loft needs at least 2 stations");ASSERT(stations[0][0]>stations[stations.length-1][0],"loft stations go nose first, from the largest z to the smallest");const mesh=new Mesh;const section=([z,w,t,b,m=.5])=>[vec3(-w/2,lerp(b,t,m),z),vec3(0,t,z),vec3(w/2,lerp(b,t,m),z),vec3(0,b,z)];for(let i=0;i+1<stations.length;++i){const s1=section(stations[i]),s2=section(stations[i+1]);for(let k=0;k<4;++k)mesh.addQuad(s1[k],s1[(k+1)%4],s2[(k+1)%4],s2[k])}const tail=section(stations[stations.length-1]),nose=section(stations[0]);mesh.addQuad(tail[0],tail[1],tail[2],tail[3]);mesh.addQuad(nose[3],nose[2],nose[1],nose[0]);return mesh}function buildSky(topColor=hsl(.6,.8,.55),horizonColor=hsl(.6,1,.9),bottomColor=horizonColor,sides=16,rings=8){const mesh=new Mesh;const point=(i,a)=>{const e=i/rings*PI-PI/2;return vec3(sin(a)*cos(e),sin(e),cos(a)*cos(e))};const color=i=>{const y=point(i,0).y;return y<0?horizonColor.lerp(bottomColor,-y):horizonColor.lerp(topColor,y)};for(let i=0;i<rings;++i){const points=[],colors=[];for(let j=0;j<=sides;++j){const a=j/sides*2*PI;points.push(point(i,a),point(i+1,a));colors.push(color(i),color(i+1))}mesh.addStrip(points,undefined,undefined,colors)}return mesh}function buildExtrude(pixels,size=vec2(1),depth=1){let rows=pixels,width,height;if(pixels instanceof TileInfo){const image=render3DReadPixels(pixels.textureInfo),data=image.data;const x0=pixels.pos.x|0,y0=pixels.pos.y|0;width=pixels.size.x|0,height=pixels.size.y|0;rows=[];for(let y=0;y<height;++y){const row=rows[y]=[];for(let x=0;x<width;++x){const k=((y0+y)*image.width+x0+x)*4;row.push(data[k+3]>127?rgb(data[k]/255,data[k+1]/255,data[k+2]/255):undefined)}}}else{ASSERT(isArray(pixels)&&pixels.length,"pixels must be a TileInfo or rows of pixels");height=rows.length,width=rows[0].length}const solid=(x,y)=>{if(x<0||y<0||x>=width||y>=height)return;const c=rows[y]&&rows[y][x];if(!c)return;return isColor(c)?c.a>.5?c:undefined:WHITE};const same=(a,b)=>a===b||!!a&&!!b&&a.rgbaInt()===b.rgbaInt();const runs=(count,colorAt,emit)=>{let start=0,color;for(let i=0;i<=count;++i){const c=i<count?colorAt(i):undefined;if(same(c,color))continue;if(color)emit(start,i,color);start=i,color=c}};const mesh=new Mesh,sx=size.x/width,sy=size.y/height,hz=depth/2;const px=x=>x*sx-size.x/2,py=y=>size.y/2-y*sy;const quad=(origin,right,up,normal,color)=>mesh.addStrip(render3DQuadAxes(origin.add(right.scale(.5)).add(up.scale(.5)),right.scale(.5),up.scale(.5)),normal,RENDER3D_QUAD_UVS,color);const X=vec3(1,0,0),Y=vec3(0,1,0),Z=vec3(0,0,1);for(let y=0;y<height;++y){runs(width,x=>solid(x,y),(a,b,c)=>{const w=X.scale((b-a)*sx),h=Y.scale(sy);quad(vec3(px(a),py(y+1),hz),w,h,Z,c);quad(vec3(px(b),py(y+1),-hz),w.scale(-1),h,Z.scale(-1),c)});runs(width,x=>solid(x,y-1)?undefined:solid(x,y),(a,b,c)=>quad(vec3(px(a),py(y),hz),X.scale((b-a)*sx),Z.scale(-depth),Y,c));runs(width,x=>solid(x,y+1)?undefined:solid(x,y),(a,b,c)=>quad(vec3(px(a),py(y+1),-hz),X.scale((b-a)*sx),Z.scale(depth),Y.scale(-1),c))}for(let x=0;x<width;++x){runs(height,y=>solid(x-1,y)?undefined:solid(x,y),(a,b,c)=>quad(vec3(px(x),py(b),-hz),Z.scale(depth),Y.scale((b-a)*sy),X.scale(-1),c));runs(height,y=>solid(x+1,y)?undefined:solid(x,y),(a,b,c)=>quad(vec3(px(x+1),py(b),hz),Z.scale(-depth),Y.scale((b-a)*sy),X,c))}return mesh}function buildText3D(text,size=1,depth=.2,font=engineImageFont){ASSERT(font instanceof ImageFont,"font must be an ImageFont, the engine font loads before gameInit");const tileInfo=font.tileInfo,padding=tileInfo.padding;const paddedX=tileInfo.size.x+padding*2,paddedY=tileInfo.size.y+padding*2;const columns=tileInfo.textureInfo.size.x/paddedX|0;let glyphs=render3DGlyphCache.get(font);glyphs||render3DGlyphCache.set(font,glyphs=new Map);const charSize=vec2(size*tileInfo.size.x/tileInfo.size.y,size);const mesh=new Mesh,lines=(text+"").split("\n");lines.forEach((line,j)=>{const y=((lines.length-1)/2-j)*charSize.y*RENDER3D_TEXT_LEADING;for(let i=0;i<line.length;++i){const charCode=line.charCodeAt(i);const index=charCode<32||charCode>127?95:charCode-32;if(!index)continue;let glyph=glyphs.get(index);if(!glyph){const pos=vec2(index%columns*paddedX+padding,(index/columns|0)*paddedY+padding);glyphs.set(index,glyph=buildExtrude(new TileInfo(pos,tileInfo.size,tileInfo.textureInfo)))}const x=(i-(line.length-1)/2)*charSize.x;mesh.combine(glyph,buildMatrix(vec3(x,y,0),undefined,vec3(charSize.x,charSize.y,depth)))}});return mesh}class HeightMap{constructor(heights,size=vec2(1),height=1,colors){if(!isArray(heights))heights=render3DImageToArray(heights,r=>r/255);if(colors&&!isArray(colors))colors=render3DImageToArray(colors,(r,g,b,a)=>rgb(r/255,g/255,b/255,a/255));ASSERT(isArray(heights)&&heights.length>1&&isArray(heights[0])&&heights[0].length>1,"height map needs at least 2 rows and 2 columns");ASSERT(size.x>0&&size.y>0,"height map size must be positive, a zero size has nowhere to look things up");this.heights=heights;this.colors=colors;this.size=size.copy();this.height=height}get rows(){return this.heights.length}get columns(){return this.heights[0].length}getHeight(x,z){if(x instanceof Vector3)z=x.z,x=x.x;const columns=this.columns,rows=this.rows,h=this.heights;const u=clamp((x/this.size.x+.5)*(columns-1),0,columns-1);const v=clamp((z/this.size.y+.5)*(rows-1),0,rows-1);const i=min(floor(u),columns-2),j=min(floor(v),rows-2);const fu=u-i,fv=v-j;const a=h[j][i],b=h[j+1][i],c=h[j+1][i+1],d=h[j][i+1];const height=fu+fv<=1?a+fu*(d-a)+fv*(b-a):c+(1-fu)*(b-c)+(1-fv)*(d-c);return height*this.height}getNormal(x,z){if(x instanceof Vector3)z=x.z,x=x.x;const ex=this.size.x/(this.columns-1)/2,ez=this.size.y/(this.rows-1)/2;return render3DSlopeNormal((x,z)=>this.getHeight(x,z),x,z,ex,ez,this.size.x/2,this.size.y/2)}getColor(x,z){if(x instanceof Vector3)z=x.z,x=x.x;const c=this.colors;if(!c)return WHITE;const columns=c[0].length,rows=c.length;const i=clamp(round((x/this.size.x+.5)*(columns-1)),0,columns-1);const j=clamp(round((z/this.size.y+.5)*(rows-1)),0,rows-1);return c[j][i]}raycast(ray){const{origin,direction}=ray;const size=this.size,height=this.height,length=direction.length();if(!length)return;let t=raycastBox(ray,vec3(0,height/2,0),vec3(size.x,abs(height)+.001,size.y));if(t===undefined)return;const cell=min(size.x/(this.columns-1),size.y/(this.rows-1));const step=cell/2/length,end=t+hypot(size.x,size.y,height)/length;if(!(step>0))return;const under=at=>{const p=origin.add(direction.scale(at));if(abs(p.x)>size.x/2||abs(p.z)>size.y/2)return;return p.y<=this.getHeight(p.x,p.z)};const startUnder=under(t);if(startUnder===undefined)return;for(;t<end;t+=step){const u=under(t+step);if(u===undefined)return;if(u===startUnder)continue;let a=t,b=t+step;for(let i=0;i<16;++i){const mid=(a+b)/2;under(mid)===startUnder?a=mid:b=mid}return b}}buildMesh(smooth=render3D?.smoothShading){return buildGrid(this.size,vec2(this.columns-1,this.rows-1),this.colors&&((x,z)=>this.getColor(x,z)),(x,z)=>this.getHeight(x,z),smooth)}}function render3DImageData(image){if(image instanceof TextureInfo)image=image.image;ASSERT(image&&image.width&&image.height,"image is not loaded");ASSERT(workReadCanvas,"reading an image needs a canvas, pass arrays in headless mode");const width=image.width,height=image.height;workReadCanvas.width=width;workReadCanvas.height=height;workReadContext.drawImage(image,0,0);return workReadContext.getImageData(0,0,width,height)}function render3DImageToArray(image,sample){const{data,width,height}=render3DImageData(image);const rows=[];for(let y=0;y<height;++y){const row=rows[y]=[];for(let x=0;x<width;++x){const k=(y*width+x)*4;row.push(sample(data[k],data[k+1],data[k+2],data[k+3]))}}return rows}const render3DGlyphCache=new WeakMap,render3DPixelCache=new WeakMap;function render3DReadPixels(textureInfo){const image=textureInfo.image;let pixels=render3DPixelCache.get(image);if(!pixels)render3DPixelCache.set(image,pixels=render3DImageData(image));return pixels}class EngineObject3D extends EngineObject{constructor(pos3D=vec3(),mesh,tileInfo,color=WHITE){ASSERT(!tileInfo||tileInfo instanceof TileInfo||tileInfo instanceof TextureInfo,"tileInfo must be a TileInfo or TextureInfo, it comes before color");if(tileInfo instanceof TextureInfo)tileInfo=new TileInfo(vec2(),tileInfo.size,tileInfo,0,0);super(vec2(),vec2(),tileInfo,0,color);ASSERT(isVector3(pos3D),"pos3D must be a vec3");ASSERT(!mesh||mesh instanceof Mesh,"mesh must be a Mesh or undefined");this.mass=0;this.pos3D=pos3D.copy();this.rotation3D=vec3();this.scale3D=vec3(1);this.velocity3D=vec3();this.angleVelocity3D=vec3();this.mesh=mesh;this.size3D=vec3(1);this.softShadow=0;this.upright=false;this.pixelated=false;this.sync2D=false;this.transparent=!mesh&&!!tileInfo;this.additive=false;this.emissive=0;this.specular=0;this.castShadow=true;this.collideAsSphere3D=false;this.receiveShadow=true;this.renderAfter2D=undefined}updatePhysics(){ASSERT(!this.sync2D||!this.collideSolidObjects||this.size.x&&this.size.y,"a sync2D object collides in 2D, so give it a 2D size as well as a size3D",this.size);if(this.sync2D)super.updatePhysics();render3DMove(this);if(this.collideSolidObjects&&!this.sync2D)render3DCollideSolid(this)}updateTransforms(){if(!paused){this.parent&&render3DMove(this);if(this.sync2D)this.pos3D.x=this.pos.x,this.pos3D.y=this.pos.y,this.rotation3D.z=-this.angle}super.updateTransforms()}setCollision(collideSolidObjects=true,isSolid=true,collideTiles=false,collideRaycast=false){super.setCollision(collideSolidObjects,isSolid,collideTiles,collideRaycast)}getWorldPos3D(){return this.getMatrix().getTranslation()}getForward3D(){return render3DAxis(this.getMatrix().m,8).normalize(-1)}getRight3D(){return render3DAxis(this.getMatrix().m,0).normalize()}getUp3D(){return render3DAxis(this.getMatrix().m,4).normalize()}getMatrix(){const matrix=buildMatrix(this.pos3D,this.rotation3D,this.scale3D);return this.parent instanceof EngineObject3D?this.parent.getMatrix().multiply(matrix):matrix}lookAt(target){const parent=this.parent instanceof EngineObject3D?this.parent:undefined;const local=parent?parent.getMatrix().invert().transformPoint(target):target;this.rotation3D=render3DLookRotation(local.subtract(this.pos3D),this.rotation3D)}setMesh(mesh){ASSERT(!mesh||mesh instanceof Mesh,"mesh must be a Mesh or undefined");const old=this.mesh;this.mesh=mesh;if(old&&old!==mesh&&old.buffer&&!engineObjects.some(o=>o.mesh===old))old.dispose();return mesh}render(){}render3D(){ASSERT(this.transparent||this.additive||this.color.a>=1,"an object that fades needs its transparent flag, an opaque draw ignores the color alpha",this.color);if(this.mesh)render3D.drawMesh(this.mesh,this.getMatrix(),this.tileInfo,this.color);else if(this.tileInfo){const m=this.getMatrix().m;render3D.drawBillboard(vec3(m[12],m[13],m[14]),vec2(this.size3D.x*hypot(m[0],m[1],m[2]),this.size3D.y*hypot(m[4],m[5],m[6])),this.tileInfo,this.color,this.rotation3D.z,this.upright)}}}function render3DMove(o){if(o.mass&&!o.sync2D){const v=o.velocity3D,g=render3D.gravity,s=o.gravityScale,d=o.damping;o.velocity3D=vec3(v.x*d+g.x*s,v.y*d+g.y*s,v.z*d+g.z*s)}o.pos3D=o.pos3D.add(o.velocity3D);o.rotation3D=o.rotation3D.add(o.angleVelocity3D)}function render3DSolidShape(o){ASSERT(!o.parent,"a child rides along with its parent, it has no world pos3D of its own to collide with");const s=o.size3D,k=o.scale3D;const kx=abs(k.x),ky=abs(k.y),kz=abs(k.z);if(o.collideAsSphere3D)return{pos:o.pos3D.copy(),radius:max(s.x,s.y,s.z)/2*max(kx,ky,kz)};return{pos:o.pos3D.copy(),size:vec3(s.x*kx,s.y*ky,s.z*kz)}}function render3DSolidReach(o){const s=o.size3D,k=o.scale3D;const kx=abs(k.x),ky=abs(k.y),kz=abs(k.z);if(o.collideAsSphere3D)return max(s.x,s.y,s.z)/2*max(kx,ky,kz);return hypot(s.x*kx,s.y*ky,s.z*kz)/2}function render3DSolidPush(a,b){if(!a.size)return b.size?collideSphereBox(a.pos,a.radius,b.pos,b.size):collideSphereSphere(a.pos,a.radius,b.pos,b.radius);if(!b.size){const push=collideSphereBox(b.pos,b.radius,a.pos,a.size);return push&&push.scale(-1)}return collideBoxBox3D(a.pos,a.size,b.pos,b.size)}function render3DCollideSolid(a){let shapeA=render3DSolidShape(a);const reachA=render3DSolidReach(a);for(const b of engineObjectsCollide){if(b===a)break;if(b.destroyed||b.parent||b.sync2D||!(b instanceof EngineObject3D))continue;if(!a.isSolid&&!b.isSolid)continue;const p=shapeA.pos,q=b.pos3D,reach=reachA+render3DSolidReach(b);const dx=p.x-q.x,dy=p.y-q.y,dz=p.z-q.z;if(dx*dx+dy*dy+dz*dz>reach*reach)continue;const push=render3DSolidPush(shapeA,render3DSolidShape(b));if(!push)continue;const resolveA=a.collideWithObject(b,push);const resolveB=b.collideWithObject(a,push.scale(-1));if(!resolveA||!resolveB)continue;const total=a.mass+b.mass;const weightA=!a.mass?0:!b.mass?1:b.mass/total;const weightB=!b.mass?0:!a.mass?1:a.mass/total;a.pos3D=a.pos3D.add(push.scale(weightA));b.pos3D=b.pos3D.subtract(push.scale(weightB));if(weightA)shapeA=render3DSolidShape(a);const normal=push.normalize();if(a.velocity3D.dot(normal)<0)a.velocity3D=a.velocity3D.reflect(normal,a.restitution);if(b.velocity3D.dot(normal)>0)b.velocity3D=b.velocity3D.reflect(normal,b.restitution)}}function engineObjectsCollect3D(pos,size,objects=engineObjects){size=render3DSize3(size);const collected=[];for(const o of objects){if(!(o instanceof EngineObject3D)||o.destroyed)continue;const m=o.getMatrix().m,s=o.size3D;if(!(s.x||s.y||s.z))continue;const worldSize=vec3(s.x*hypot(m[0],m[1],m[2]),s.y*hypot(m[4],m[5],m[6]),s.z*hypot(m[8],m[9],m[10]));if(isOverlapping3D(pos,size,vec3(m[12],m[13],m[14]),worldSize))collected.push(o)}return collected}function render3DRaycastObject(ray,o){if(o.destroyed||!(o instanceof EngineObject3D)||!(o.mesh||o.tileInfo))return;const matrix=o.getMatrix(),mesh=o.mesh;const radius=(mesh?mesh.radius||mesh.computeRadius():hypot(o.size3D.x,o.size3D.y)/2)*render3DMaxScale(matrix.m);if(!(radius>0))return;return raycastSphere(ray,matrix.getTranslation(),radius)}function engineObjectsRaycast3D(ray,objects=engineObjects){const hits=[];for(const o of objects){const distance=render3DRaycastObject(ray,o);if(distance!==undefined)hits.push({o:o,distance:distance})}return hits.sort((a,b)=>a.distance-b.distance).map(hit=>hit.o)}function engineObjectsCallback3D(pos,size,callback,objects=engineObjects){engineObjectsCollect3D(pos,size,objects).forEach(callback)}class Light3D extends EngineObject3D{constructor(pos3D=vec3(),radius=5,color=WHITE,intensity=1){super(pos3D,undefined,undefined,color);ASSERT(radius>=0,"light radius cannot be negative, 0 is an off switch like an alpha of 0");ASSERT(intensity>=0,"light intensity cannot be negative, 0 is an off switch");this.size3D=vec3();this.radius=radius;this.intensity=intensity;this.directional=false}render3D(){}}class DirectionalLight3D extends Light3D{constructor(pos3D=vec3(0,1,0),color=WHITE,intensity=1){super(pos3D,0,color,intensity);this.directional=true}}class CameraControl3D extends EngineObject3D{constructor(target=vec3(),distance=10,pitch=.4,idleSpin=0){super(target);this.size3D=vec3();this.distance=distance;this.pitch=pitch;this.idleSpin=idleSpin;this.yaw=0;this.dragButton=0;this.dragSpeed=.01;this.zoomSpeed=.1;this.zoomRange=vec2(distance/4,distance*3);this.pitchRange=vec2(-.2,1.4)}update(){if(mouseIsDown(this.dragButton)){this.yaw-=mouseDeltaScreen.x*this.dragSpeed;this.pitch+=mouseDeltaScreen.y*this.dragSpeed}else this.yaw+=this.idleSpin;this.pitch=clamp(this.pitch,this.pitchRange.x,this.pitchRange.y);if(this.zoomSpeed&&mouseWheel)this.distance=clamp(this.distance*(1+sign(mouseWheel)*this.zoomSpeed),this.zoomRange.x,this.zoomRange.y);render3D.camera.orbit(this.getWorldPos3D(),this.distance,this.yaw,this.pitch)}render3D(){}}class FirstPersonCamera3D extends EngineObject3D{constructor(pos3D=render3D.camera.pos,yaw=render3D.camera.rotation.y,pitch=render3D.camera.rotation.x){super(pos3D);this.size3D=vec3();this.mass=1;this.yaw=yaw;this.pitch=pitch;this.moveSpeed=.1;this.lookSpeed=.003;this.pitchRange=vec2(-1.5,1.5);this.fly=false;this.lockPointer=true}update(){if(this.lockPointer&&mouseWasPressed(0))pointerLockRequest();if(pointerLockIsActive()||mouseIsDown(0)){this.yaw-=mouseDeltaScreen.x*this.lookSpeed;this.pitch-=mouseDeltaScreen.y*this.lookSpeed}this.pitch=clamp(this.pitch,this.pitchRange.x,this.pitchRange.y);const input=keyDirection();const move=vec3(input.x,0,-input.y).clampLength(1).scale(this.moveSpeed).rotateX(this.fly?this.pitch:0).rotateY(this.yaw);this.velocity3D=this.fly?move:vec3(move.x,this.velocity3D.y,move.z);render3D.camera.pos=this.getWorldPos3D();render3D.camera.rotation=vec3(this.pitch,this.yaw,0)}destroy(immediate){this.lockPointer&&pointerLockIsActive()&&pointerLockExit();super.destroy(immediate)}render3D(){}}class ParticleEmitter3D extends EngineObject3D{constructor(pos3D=vec3(),emitSize=0,emitTime=0,emitRate=100,emitConeAngle=PI,tileInfo,colorStartA=WHITE,colorStartB=WHITE,colorEndA=CLEAR_WHITE,colorEndB=CLEAR_WHITE,particleTime=.5,sizeStart=.1,sizeEnd=1,speed=.1,damping=1,gravity=0,fadeRate=.1,randomness=.2,additive=false){super(pos3D,undefined,tileInfo);this.transparent=true;this.castShadow=false;this.size3D=vec3();this.emitSize=emitSize;this.emitTime=emitTime;this.emitRate=emitRate;this.emitConeAngle=emitConeAngle;this.colorStartA=colorStartA.copy();this.colorStartB=colorStartB.copy();this.colorEndA=colorEndA.copy();this.colorEndB=colorEndB.copy();this.particleTime=particleTime;this.sizeStart=sizeStart;this.sizeEnd=sizeEnd;this.speed=speed;this.damping=damping;this.gravity=gravity;this.fadeRate=fadeRate;this.randomness=randomness;this.additive=additive;this.trailTime=0;this.angleSpeed=0;this.angleDamping=1;this.particles=[];this.emitTimeBuffer=0}update(){const matrix=this.getMatrix();this.worldPos3D=matrix.getTranslation();const scale=render3DMaxScale(matrix.m);if(!this.emitTime||this.getAliveTime()<=this.emitTime){if(this.emitRate&&particleEmitRateScale){this.emitTimeBuffer+=this.emitRate*particleEmitRateScale*timeDelta;for(;this.emitTimeBuffer>=1;--this.emitTimeBuffer)this.emitParticle()}}else if(!this.particles.length)this.destroy();const particles=this.particles;for(let i=particles.length;i--;){const p=particles[i],v=p.velocity;v.x*=this.damping,v.y*=this.damping,v.z*=this.damping;v.y+=this.gravity*scale;p.pos=p.pos.add(v);p.angle+=p.angleVelocity*=this.angleDamping;if(this.trailTime){const trail=p.trail||(p.trail=[]);trail.push(p.pos);const extra=trail.length-this.trailTime/timeDelta;extra>0&&trail.splice(0,extra)}if((p.age+=timeDelta)>=p.life)particles[i]=particles[particles.length-1],particles.pop()}}destroy(immediate){if(immediate||!this.particles.length||this.destroyed)return super.destroy(immediate);this.emitTime=-1;render3DDetach(this)}emitParticle(){const random=()=>rand(1-this.randomness,1+this.randomness);const matrix=this.getMatrix();const scale=render3DMaxScale(matrix.m);const size=this.emitSize;const offset=isVector3(size)?vec3(rand(-.5,.5)*size.x,rand(-.5,.5)*size.y,rand(-.5,.5)*size.z):randInSphere(size/2);const direction=matrix.transformDirection(randVector3(1,this.emitConeAngle)).normalize();this.particles.push({pos:matrix.transformPoint(offset),velocity:direction.scale(this.speed*random()*scale),colorStart:randColor(this.colorStartA,this.colorStartB,true),colorEnd:randColor(this.colorEndA,this.colorEndB,true),sizeStart:this.sizeStart*random()*scale,sizeEnd:this.sizeEnd*random()*scale,life:this.particleTime*random(),angle:this.angleSpeed?rand(2*PI):0,angleVelocity:this.angleSpeed?this.angleSpeed*random()*randSign():0,age:0})}render3D(){if(render3D.transparentQueue)return render3D.queueTransparent(this.getWorldPos3D(),()=>this.render3D());const fade=this.fadeRate/2,texture=this.tileInfo||render3DSoftDot();for(const p of this.particles){const t=p.age/p.life;const alpha=t<fade?t/fade:t>1-fade?(1-t)/fade:1;const color=p.colorStart.lerp(p.colorEnd,t),size=lerp(p.sizeStart,p.sizeEnd,t);color.a*=alpha;const trail=p.trail;if(trail&&trail.length>1){const widths=[],colors=[];for(let i=0;i<trail.length;++i){const s=(i+1)/trail.length;widths.push(size*s);colors.push(color.scale(1,s))}render3D.drawRibbon(trail,widths,this.tileInfo,colors)}else if(texture)render3D.drawBillboard(p.pos,vec2(size),texture,color,p.angle);else render3D.drawSoftDisc(p.pos,size,color,undefined,8)}}}class Trail3D extends EngineObject3D{constructor(pos3D=vec3(),lifeTime=1,width=.2,tileInfo,color=WHITE,colorEnd=CLEAR_WHITE,additive=false){super(pos3D,undefined,tileInfo,color);this.transparent=true;this.additive=additive;this.castShadow=false;this.size3D=vec3();this.finishing=false;this.lifeTime=lifeTime;this.width=width;this.colorEnd=colorEnd.copy();this.side=undefined;this.samples=[]}clear(){this.samples.length=0}destroy(immediate){if(immediate||!this.samples.length||this.destroyed||this.lifeTime==Infinity)return super.destroy(immediate);this.finishing=true;render3DDetach(this)}update(){const samples=this.samples;if(!this.finishing){const pos=this.worldPos3D=this.getWorldPos3D(),last=samples[samples.length-1];if(!last||pos.distanceSquared(last.pos)>1e-8)samples.push({pos:pos,side:this.side?.copy(),time:time})}while(samples.length&&time-samples[0].time>this.lifeTime)samples.shift();this.finishing&&!samples.length&&this.destroy()}render3D(){const samples=this.samples;if(samples.length<2)return;const points=[],widths=[],colors=[],sides=this.side?[]:undefined;for(const s of samples){const age=clamp((time-s.time)/this.lifeTime);points.push(s.pos);widths.push(this.width*(1-age));colors.push(this.color.lerp(this.colorEnd,age));sides?.push(s.side)}render3D.drawRibbon(points,widths,this.tileInfo,colors,sides)}}function parseOBJ(text,smooth=render3D?.smoothShading){const positions=[],normals=[],uvs=[],mesh=new Mesh;let fileNormals=false;const lookup=(s,list)=>{const i=parseInt(s);return list[i<0?list.length+i:i-1]};for(const line of text.split("\n")){const parts=line.trim().split(/\s+/);switch(parts[0]){case"v":positions.push(vec3(+parts[1],+parts[2],+parts[3]));break;case"vn":normals.push(vec3(+parts[1],+parts[2],+parts[3]));break;case"vt":uvs.push(vec2(+parts[1],1-+parts[2]));break;case"f":{const corners=parts.slice(1).map(c=>c.split("/"));if(corners.length<3)break;const points=corners.map(c=>lookup(c[0],positions));ASSERT(points.every(isVector3),"OBJ face uses a vertex index the file does not have",line);const uv=corners.map(c=>c[1]?lookup(c[1],uvs):RENDER3D_DEFAULT_UV);const hasNormals=corners.every(c=>c[2]);fileNormals||=hasNormals;const n=hasNormals?render3DPolygonStrip(corners.map(c=>lookup(c[2],normals))):render3DFaceNormal(points[0],points[1],points[2],points[3]);mesh.addStrip(render3DPolygonStrip(points),n,render3DPolygonStrip(uv))}}}if(!fileNormals&&smooth)mesh.computeNormals(true);return mesh}async function loadOBJ(url,smooth=render3D?.smoothShading){const response=await fetch(url);if(!response.ok)throw new Error("loadOBJ failed: "+url);return parseOBJ(await response.text(),smooth)}let threeJS;class ThreeJSPlugin{constructor(THREE,cameraFOV=60){ASSERT(!threeJS,"ThreeJS plugin already initialized");threeJS=this;if(headlessMode)return;ASSERT(mainCanvas,"ThreeJS plugin must be created after engineInit, call in gameInit");ASSERT(THREE&&THREE.WebGLRenderer,"three.js module must be passed in");this.THREE=THREE;this.renderer=new THREE.WebGLRenderer({antialias:true});this.scene=new THREE.Scene;this.camera=new THREE.PerspectiveCamera(cameraFOV,1,.1,1e3);this.cameraAlign2D=true;const threeCanvas=this.renderer.domElement;const rootElement=mainCanvas.parentElement;rootElement.insertBefore(threeCanvas,rootElement.firstChild);threeCanvas.style.cssText=mainCanvas.style.cssText;setBackgroundCanvas(threeCanvas);engineAddPlugin(undefined,()=>this.render())}alignCamera2D(){const halfHeight=mainCanvasSize.y/2/cameraScale;const distance=halfHeight/tan(this.camera.fov/2*PI/180);this.camera.position.set(cameraPos.x,cameraPos.y,distance);this.camera.rotation.set(0,0,-cameraAngle)}render(){if(!this.renderer)return;const threeCanvas=this.renderer.domElement;const dpr=getCanvasPixelRatio();const bufferSizeX=mainCanvasSize.x*dpr|0;const bufferSizeY=mainCanvasSize.y*dpr|0;if(threeCanvas.width!=bufferSizeX||threeCanvas.height!=bufferSizeY){this.renderer.setPixelRatio(dpr);this.renderer.setSize(mainCanvasSize.x,mainCanvasSize.y,false);this.camera.aspect=mainCanvasSize.x/mainCanvasSize.y;this.camera.updateProjectionMatrix()}if(threeCanvas.style.cssText!=mainCanvas.style.cssText)threeCanvas.style.cssText=mainCanvas.style.cssText;if(this.cameraAlign2D)this.alignCamera2D();this.renderer.render(this.scene,this.camera)}}class ThreeJSObject extends EngineObject{constructor(pos,size,mesh,z=0){super(pos,size);ASSERT(threeJS,"ThreeJS plugin must be initialized first");this.mesh=mesh;this.z=z;if(mesh){threeJS.scene.add(mesh);this.syncMesh()}}update(){super.update();this.syncMesh()}syncMesh(){if(!this.mesh)return;this.mesh.position.set(this.pos.x,this.pos.y,this.z);this.mesh.rotation.z=-this.angle}render(){}destroy(immediate){if(this.destroyed)return;this.mesh&&threeJS.scene.remove(this.mesh);super.destroy(immediate)}}export{engineName,engineVersion,frameRate,timeDelta,engineObjects,engineObjectsCollide,frame,time,timeReal,paused,getPaused,setPaused,engineInit,engineStep,engineObjectsUpdate,engineObjectsDestroy,engineObjectsCollect,engineObjectsCallback,engineObjectsRaycast,engineAddPlugin,debug,debugOverlay,debugWatermark,ASSERT,LOG,debugPointSize,debugRect,debugPoly,debugCircle,debugPoint,debugLine,debugOverlap,debugText,debugClear,debugScreenshot,debugShowErrors,debugVideoCaptureStart,debugVideoCaptureStop,debugVideoCaptureIsActive,cameraPos,cameraAngle,cameraScale,timeScale,canvasColorTiles,canvasClearColor,canvasMaxSize,canvasMinAspect,canvasMaxAspect,canvasFixedSize,canvasPixelated,tilesPixelated,canvasPixelRatio,fontDefault,showSplashScreen,headlessMode,engineManualStep,tileDefaultSize,tileDefaultPadding,tileDefaultBleed,enablePhysicsSolver,objectDefaultMass,objectDefaultDamping,objectDefaultAngleDamping,objectDefaultRestitution,objectDefaultFriction,objectMaxSpeed,gravity,particleEmitRateScale,glEnable,glCircleSides,gamepadsEnable,gamepadDirectionEmulateStick,gamepadAxisFilterEnable,inputWASDEmulateDirection,touchInputEnable,touchGamepadEnable,touchGamepadPassthrough,touchGamepadCenterButtonSize,touchGamepadButtonCount,touchGamepadLeftStick,touchGamepadLeftButtonCount,touchGamepadRightStick,touchGamepadAnalog,touchGamepadFloating,touchGamepadSize,touchGamepadAlpha,touchGamepadDisplayTime,touchGamepadVibration,vibrateEnable,soundEnable,soundVolume,soundDefaultRange,soundDefaultTaper,soundPauseWhenHidden,setCameraPos,setCameraAngle,setCameraScale,setTimeScale,setCanvasColorTiles,setCanvasClearColor,setCanvasMaxSize,setCanvasMinAspect,setCanvasMaxAspect,setCanvasFixedSize,setCanvasPixelated,setTilesPixelated,setCanvasPixelRatio,getCanvasPixelRatio,setFontDefault,setShowSplashScreen,setHeadlessMode,setEngineManualStep,setGLEnable,setTileDefaultSize,setTileDefaultPadding,setTileDefaultBleed,setEnablePhysicsSolver,setObjectDefaultMass,setObjectDefaultDamping,setObjectDefaultAngleDamping,setObjectDefaultRestitution,setObjectDefaultFriction,setObjectMaxSpeed,setGravity,setParticleEmitRateScale,setGLCircleSides,setTouchInputEnable,setGamepadsEnable,setGamepadDirectionEmulateStick,setGamepadAxisFilterEnable,setInputWASDEmulateDirection,setTouchGamepadEnable,setTouchGamepadPassthrough,setTouchGamepadCenterButtonSize,setTouchGamepadButtonCount,setTouchGamepadLeftStick,setTouchGamepadLeftButtonCount,setTouchGamepadRightStick,setTouchGamepadAnalog,setTouchGamepadFloating,setTouchGamepadSize,setTouchGamepadAlpha,setTouchGamepadDisplayTime,setTouchGamepadVibration,setVibrateEnable,setSoundEnable,setSoundVolume,setSoundDefaultRange,setSoundDefaultTaper,setSoundPauseWhenHidden,setDebugWatermark,setDebugKey,PI,abs,floor,ceil,round,min,max,sign,hypot,log2,sin,cos,tan,atan2,mod,clamp,percent,distanceWrap,lerpWrap,distanceAngle,lerpAngle,lerp,percentLerp,smoothStep,nearestPowerOfTwo,isPowerOfTwo,isOverlapping,isIntersecting,collideCircleCircle,collideCircleBox,collideBoxBox,lineTest,oscillate,formatTime,fetchJSON,saveText,createCanvasContext,saveCanvas,saveDataURL,shareURL,readSaveData,writeSaveData,noise1D,noise2D,rand,randInt,randBool,randSign,randInCircle,randVec2,randColor,RandomGenerator,Vector2,Color,Timer,vec2,rgb,hsl,isColor,isVector2,isNumber,isStringLike,isArray,WHITE,CLEAR_WHITE,BLACK,CLEAR_BLACK,GRAY,RED,ORANGE,YELLOW,GREEN,CYAN,BLUE,PURPLE,MAGENTA,tile,TileInfo,TextureInfo,SpriteAnimation,Shader,mainCanvas,mainContext,drawContext,workCanvas,workContext,workReadCanvas,workReadContext,backgroundCanvas,mainCanvasSize,textureInfos,drawCount,primitiveCount,screenToWorld,worldToScreen,screenToWorldDelta,worldToScreenDelta,screenToWorldTransform,drawTile,drawRect,drawRectGradient,drawTextureWrapped,drawLineList,drawLine,drawPoly,drawRegularPoly,drawEllipse,drawCircle,drawEllipseGradient,drawCircleGradient,drawCanvas2D,drawText,drawTextScreen,setAdditiveBlendMode,setShader,setBackgroundCanvas,combineCanvases,engineImageFont,ImageFont,isFullscreen,toggleFullscreen,setCursor,getCameraSize,cameraFit,isOnScreen,glCanvas,glContext,glAntialias,glClearCanvas,glSetTexture,glSetTextureWrap,glCompileShader,glCreateProgram,glCreateTexture,glDeleteTexture,glSetTextureData,glFlush,glCopyToContext,glSetAntialias,glDraw,glDrawUntextured,glDrawPointsTransform,glDrawOutlineTransform,glDrawPoints,glDrawColoredPoints,glSetRenderTarget,glClearRect,keyIsDown,keyWasPressed,keyWasReleased,keyDirection,inputClear,inputClearKey,mouseIsDown,mouseWasPressed,mouseWasReleased,mousePos,mousePosScreen,mouseDelta,mouseDeltaScreen,mouseWheel,mouseInWindow,isUsingGamepad,lastInputDevice,inputMouseMoveThreshold,inputPreventDefault,gamepadPrimary,isTouchDevice,setInputPreventDefault,setInputMouseMoveThreshold,usingMouseInput,usingKeyboardInput,usingGamepadInput,gamepadIsDown,gamepadWasPressed,gamepadWasReleased,gamepadStick,gamepadStickCount,gamepadDpad,gamepadConnected,gamepadVibrate,gamepadVibrateStop,vibrate,vibrateStop,pointerLockRequest,pointerLockExit,pointerLockIsActive,audioContext,audioMasterGain,setAudioMasterEffect,audioDefaultSampleRate,audioIsRunning,Sound,SoundInstance,speak,speakStop,getNoteFrequency,playSamples,playAudioBuffer,createAudioBuffer,zzfx,zzfxG,EngineObject,tileCollisionLayers,tileCollisionGetData,tileCollisionTest,tileCollisionRaycast,tileLayersLoad,TileLayerData,CanvasLayer,TileLayer,TileCollisionLayer,ParticleEmitter,Particle};export{medals,medalsPreventUnlock,medalDisplayTime,medalDisplaySlideTime,medalDisplaySize,medalsInit,medalsForEach,medalsReset,setMedalDisplayTime,setMedalDisplaySlideTime,setMedalDisplaySize,setMedalsPreventUnlock,Medal,newgrounds,NewgroundsPlugin,NewgroundsMedal,postProcess,PostProcessPlugin,postProcessBloom,postProcessBloomShader,lightSystem,LightSystemPlugin,Light,ZzFXMusic,zzfxM,AudioEffect,AudioFilter,AudioReverb,AudioDelay,AudioDistortion,AudioCompressor,uiSystem,uiDebug,uiSetDebug,UISystemPlugin,UIObject,UIText,UITextInput,UITile,UIButton,UICheckbox,UISlider,UIVideo,UILayout,box2d,box2dDebug,box2dSetDebug,box2dInit,Box2dPlugin,Box2dObject,Box2dStaticObject,Box2dKinematicObject,Box2dTileLayer,Box2dRaycastResult,Box2dJoint,Box2dTargetJoint,Box2dDistanceJoint,Box2dPinJoint,Box2dRopeJoint,Box2dRevoluteJoint,Box2dGearJoint,Box2dPrismaticJoint,Box2dWheelJoint,Box2dWeldJoint,Box2dFrictionJoint,Box2dPulleyJoint,Box2dMotorJoint,drawNineSlice,drawNineSliceScreen,drawThreeSlice,drawThreeSliceScreen,drawCrescent,getCrescentPoints,Tween,tweenProperty,tweenStopAll,tweenUpdate,Ease,PathFinder,PathFinderNode,vec3,isVector3,randVector3,randInSphere,Vector3,Matrix4,Ray3D,buildMatrix,isPointInBox3D,isOverlapping3D,collideSphereSphere,collideSphereBox,collideSphereInBox,collideSphereCylinder,collideBoxBox3D,raycastSphere,raycastPlane,raycastBox,render3D,Render3DPlugin,Camera3D,EngineObject3D,Mesh,buildLathe,buildCylinder,buildSphere,buildCone,buildCapsule,buildTorus,buildBox,buildGrid,buildRibbon,buildLoft,buildSky,buildExtrude,buildText3D,HeightMap,Light3D,DirectionalLight3D,CameraControl3D,FirstPersonCamera3D,ParticleEmitter3D,Trail3D,engineObjectsCollect3D,engineObjectsCallback3D,engineObjectsRaycast3D,parseOBJ,loadOBJ,debugBox3D,debugSphere3D,debugLine3D,debugPoint3D,threeJS,ThreeJSPlugin,ThreeJSObject,textureSheetSize,textureSheetPadding,setTextureSheetSize,setTextureSheetPadding,textureSheets,TextureSheet,loadSprite,loadAtlas,parseAtlas,spritesReady};
|