@kayelaa/canvas 0.2.7 → 0.2.8
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/dist/index.cjs +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/jsx-dev-runtime.cjs +1 -1
- package/dist/jsx-dev-runtime.d.cts +2 -2
- package/dist/jsx-dev-runtime.d.ts +2 -2
- package/dist/jsx-dev-runtime.js +1 -1
- package/dist/jsx-runtime.cjs +1 -1
- package/dist/jsx-runtime.d.cts +2 -2
- package/dist/jsx-runtime.d.ts +2 -2
- package/dist/jsx-runtime.js +1 -1
- package/dist/{kayla-internals-Ajxdtt0s.d.ts → kayla-internals-BIKaIho5.d.ts} +1 -1
- package/dist/{kayla-internals-D4Wr4S0V.d.cts → kayla-internals-jEHH2NbT.d.cts} +1 -1
- package/dist/kayla.cjs +1 -1
- package/dist/kayla.d.cts +3 -3
- package/dist/kayla.d.ts +3 -3
- package/dist/kayla.js +1 -1
- package/dist/{lea-B1DIEiLR.d.cts → lea-BaZkxo5L.d.cts} +9 -8
- package/dist/{lea-B1DIEiLR.d.ts → lea-BaZkxo5L.d.ts} +9 -8
- package/dist/lea.cjs +1 -1
- package/dist/lea.d.cts +1 -1
- package/dist/lea.d.ts +1 -1
- package/dist/lea.js +1 -1
- package/package.json +1 -1
package/dist/jsx-dev-runtime.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var ce=Object.defineProperty;var Fe=Object.getOwnPropertyDescriptor;var Me=Object.getOwnPropertyNames;var Ae=Object.prototype.hasOwnProperty;var Ke=(r,e)=>{for(var n in e)ce(r,n,{get:e[n],enumerable:!0})},Le=(r,e,n,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of Me(e))!Ae.call(r,a)&&a!==n&&ce(r,a,{get:()=>e[a],enumerable:!(s=Fe(e,a))||s.enumerable});return r};var _e=r=>Le(ce({},"__esModule",{value:!0}),r);var dt={};Ke(dt,{Fragment:()=>ct,jsx:()=>ut,jsxDEV:()=>ht,jsxs:()=>Ie});module.exports=_e(dt);var Ee={};Ke(Ee,{JSX:()=>Se,KMatrix2D:()=>ge,KaylaContext:()=>te,KaylaFragment:()=>Ce,KaylaInternals:()=>G,KaylaRect:()=>L,Layer:()=>ot,createContext:()=>Ne,createElement:()=>ne,createGame:()=>Ue,createReassignableObject:()=>it,createRenderer:()=>Oe,createScene:()=>$e,createUseHook:()=>at,self:()=>be,setLogLevel:()=>st,useClick:()=>je,useContext:()=>nt,useCurrentGame:()=>Ze,useCurrentRenderer:()=>et,useCurrentScene:()=>Pe,useCurrentTicker:()=>tt,useDisposableRef:()=>rt,useEffect:()=>re,useEntity:()=>Je,useExports:()=>oe,useFiber:()=>ve,useFiberControl:()=>xe,useGlobalClick:()=>Te,useGlobalPointer:()=>We,useInitialization:()=>ie,useNextStack:()=>we,usePaint:()=>ae,usePointer:()=>Ye,useRect:()=>se,useRef:()=>ye,useSelf:()=>D,useShouldRefresh:()=>qe,useState:()=>Xe,useTick:()=>Qe,useViewportEffect:()=>Be});var I=class{#e=new Map;constructor(){this.#e=new Map}on(e,n){let s=this.#e.get(e)||[];return s.push(n),this.#e.set(e,s),this}once(e,n){let s=(...a)=>{this.off(e,s),n(...a)};return this.on(e,s),this}off(e,n){let s=this.#e.get(e);if(!s)return this;let a=s.indexOf(n);return a>=0&&s.splice(a,1),this}emit(e,...n){let s=this.#e.get(e);if(!s||s.length===0){if(e==="error")throw n[0];return!1}return s.slice().forEach(a=>a(...n)),!0}removeAllListeners(e){return e?this.#e.delete(e):this.#e.clear(),this}listenerCount(e){return this.#e.get(e)?.length??0}},Q=class extends I{canvas;ctx;running;_rafId;_fps;_frameCount;_fpsTimer;_lastFrameTime;constructor(e,{viewportWidth:n,viewportHeight:s,cameraWidth:a,cameraHeight:l}={}){if(!k)throw new Error("Web-Only");super(),this.canvas=e,this.ctx=e.getContext("2d"),this.automatic=!0,this.#e=n??e.width,this.#t=s??e.height,this.#n=a??e.width,this.#r=l??e.height,this.running=!1,this._rafId=null,this._loop=this._loop.bind(this),this.updateCanvasResolution(),this._fps=60,this._frameCount=0,this._fpsTimer=0}automatic;retransform(){this.ctx.setTransform(1,0,0,1,0,0);let e=this.#n/this.#e,n=this.#r/this.#t;this.ctx.translate(this.#n/2,this.#r/2),this.ctx.scale(e,n),this.ctx.translate(-this.#e/2,-this.#t/2)}#e=0;#t=0;#n=0;#r=0;get viewportWidth(){return this.#e}set viewportWidth(e){this.#e=e,this.retransform(),this.emitViewportUpdate()}get width(){return this.#e}get height(){return this.#t}get centerX(){return this.#e/2}get centerY(){return this.#t/2}get left(){return 0}get top(){return 0}get right(){return this.#e}get bottom(){return this.#t}get viewportHeight(){return this.#t}set viewportHeight(e){this.#t=e,this.retransform(),this.emitViewportUpdate()}get cameraWidth(){return this.#n}set cameraWidth(e){this.#n=e,this.updateCanvasResolution(),this.retransform()}get cameraHeight(){return this.#r}set cameraHeight(e){this.#r=e,this.updateCanvasResolution(),this.retransform()}updateCanvasResolution(){this.canvas.width=this.#n,this.canvas.height=this.#r}emitViewportUpdate(){this.emit("viewport_update",{width:this.viewportWidth,height:this.viewportHeight})}applyTransform(){this.retransform()}get FPS(){return this._fps}_loop(){this.automatic&&this.update(),this._rafId=requestAnimationFrame(this._loop)}update(){if(!this.running||!k)return;let e=performance.now(),n=(e-(this._lastFrameTime??e))/1e3;this._lastFrameTime=e,this._frameCount++,this._fpsTimer+=n,this._fpsTimer>=1&&(this._fps=Math.round(this._frameCount/this._fpsTimer),this._frameCount=0,this._fpsTimer=0),this.ctx.clearRect(0,0,this.#n,this.#r),this.emit("draw",this.ctx)}start(){if(!this.running){if(!k||typeof globalThis.requestAnimationFrame>"u")throw new Error("Raf is not supported");this.running=!0,this._rafId=requestAnimationFrame(this._loop)}}stop(){if(!k||typeof globalThis.requestAnimationFrame>"u")throw new Error("Raf is not supported");this.running=!1,this._rafId!==null&&(cancelAnimationFrame(this._rafId),this._rafId=null)}},de=class extends I{setNow(e){this.#e=e}#e=0;__intervalId=null;__lastTime=0;constructor(e=16){super(),this.#t=e,this.speedHackDT=1}speedHackDT;get isRaf(){return this.tickInterval===1/0}#t=15;get tickInterval(){return this.#t}set tickInterval(e){this.#t=e,this.__intervalId&&(this.stop(),this.start())}now(){return this.#e}__tick(){let e=performance.now(),n=(e-this.__lastTime)/1e3*this.speedHackDT;this.__lastTime=e,!(k&&typeof this.__intervalId=="function"&&document.hidden)&&(this.#e+=n*1e3,this.emit("tick",n))}createTimeout(e){return new pe(e,this)}createTween(e,n=()=>{}){let s=new fe(e),a=(l=0)=>{if(s.finished){this.off("tick",a);return}s.update(l)};return s.on("finish",()=>{this.off("tick",a)}),s.on("delta",l=>{n(l)}),this.on("tick",a),s}start(){this.__intervalId===null&&(this.__lastTime=performance.now(),this.__intervalId=k&&!isFinite(this.tickInterval)?ze(()=>this.__tick()).clear:setInterval(()=>this.__tick(),this.tickInterval))}stop(){this.__intervalId!==null&&(typeof this.__intervalId=="function"?this.__intervalId():clearInterval(this.__intervalId)),this.__intervalId=null}getSineMod(e,n=0){return .5+.5*Math.sin((this.now()%e/e+n)*2*Math.PI)}},Ve;(t=>{function r(i){return i===!0?1:0}t.booleanExport=r;function e(i){return i===0?!1:i===1}t.booleanImport=e;function n(i){return`${i.x}|${i.y}`}t.vec2Export=n;function s(i){let[o,u]=i.split("|"),y=parseFloat(o),b=parseFloat(u);if(isNaN(y)||isNaN(b))throw new Error(`Invalid Vector2 string: ${i}`);return new M(y,b)}t.vec2Import=s,t.booleanMap={mapExport:r,mapImport:e};function l(i){return o=>Number(o.toFixed(i))}t.createRounder=l;function d(i=10){return{mapExport(o){return Math.round(o/i)},mapImport(o){return o*i}}}t.createLowPrecision=d;function f(i){return Math.round(i)}t.lightWeightRounder=f;function h(i=100){return{mapExport(o){return Math.round(o*i)},mapImport(o){return o/i}}}t.createPercent=h;function c(i){let o=new Map(Object.entries(i));return{mapExport:u=>o.get(u)??null,mapImport:u=>Array.from(o.entries()).find(([y,b])=>b===u)?.[0]??null}}t.createLookup=c;function p(i){let o=i*(180/Math.PI);return Math.round((o%360+360)%360)}t.radToDeg=p;function g(i){return i*(Math.PI/180)}t.degToRad=g,t.angleRadToDeg={mapExport:p,mapImport:g};function v(i=10){let o=d(i);return{mapExport(u){return o.mapExport(p(u))},mapImport(u){return o.mapImport(g(u))}}}t.createLowPrecisionRadToDeg=v})(Ve||={});var N=class r extends I{name="";scaleRotate=0;scale=1;constructor(e,n=0,s=0){super(),this.autoTranslate=!1,this.name=e,this.z=0,this.___pos=new M(n,s),this.nonSerializableProperties=[],this.nonSerializableProperties.push("___pos","autoTranslate","arraySerializeMap"),this.forceSerializableProperties=[],this.forceSerializableProperties.push("x","y")}arraySerializeMap;autoTranslate;z;___pos;nonSerializableProperties;forceSerializableProperties;get pos(){return this.___pos}get x(){return this.pos.x}get y(){return this.pos.y}set x(e){this.pos.x=e}set y(e){this.pos.y=e}handleUpdate(e){if(this.update)try{this.emit("update",e),this.update(e)}catch(n){this.emit("error",n)}}handleDraw(e){if(!(U||!this.draw)){e.save(),this.autoTranslate&&e.translate(this.x,this.y);try{this.emit("draw",e),this.draw(e)}catch(n){this.emit("error",n)}e.restore()}}serialize(){if(Array.isArray(this.arraySerializeMap))return this.arraySerializeMap.map(([a,{mapExport:l}])=>{let d=Reflect.get(this,a);return l?l(d):d});let e=["_events","_eventsCount","_maxListeners","nonSerializableProperties","forceSerializableProperties"],n=[...Reflect.ownKeys(this),...this.forceSerializableProperties].filter(a=>!this.nonSerializableProperties.includes(a)&&!e.includes(a.toString())),s=Object.fromEntries(n.map(a=>{let l=Reflect.get(this,a);if(U&&typeof l=="number"){let d=l.toString().split("."),h=(d[1]?d[1].length:0)>2?Number(l.toFixed(2)):l;return[a,h]}return[a,l]}));return JSON.parse(JSON.stringify(s))}toLocal(e){return e.subtract(this.pos)}toWorld(e){return e.add(this.pos)}deserializeArray(e){return r.deserializeArray(this.arraySerializeMap,e)}static deserializeArray(e,n){if(!e||!Array.isArray(n))return n;let s={};for(let a=0;a<n.length;a++){let l=e[a];if(!l)break;let[d,{mapImport:f}]=l,h=n[a];if(f&&(h=f(h)),typeof d!="string")break;try{Reflect.set(s,d,h)}catch(c){console.error(c)}}return s}},J=class extends I{name="";entities=new Map;paused=!0;constructor(e){super(),this.name=e}handleUpdate(e){if(!this.paused){this.emit("update",e);for(let n of this.entities.values())n.handleUpdate(e)}}handleDraw(e){if(!U&&!this.paused){this.emit("draw",e);for(let n of[...this.entities.values()].sort((s,a)=>s.z-a.z))n.handleDraw(e)}}addEntity(e){if(!(e instanceof N))throw new Error("invalid entity");if(!e.name)throw new Error("Entity must have a name.");this.entities.set(e.name,e)}removeEntity(e){if(!(e instanceof N))throw new Error("invalid entity");this.entities.delete(e.name)}getEntity(e){return this.entities.get(e)}},Z=class{scenes;ticker;get centerX(){return this.width/2}get centerY(){return this.height/2}get left(){return 0}get top(){return 0}get right(){return this.width}get bottom(){return this.height}width;height;constructor(e,n,s=16){this.ticker=new de(s),this.scenes=new Map,this.width=e,this.height=n,this.ticker.on("tick",a=>{for(let l of this.scenes.values())l.paused||l.handleUpdate(a)})}addScene(e){if(!e.name)throw new Error("Scene must have a name.");e.paused=!1,this.scenes.set(e.name,e)}removeScene(e){e&&(e.paused=!0),this.scenes.delete(e.name)}now(){return this.ticker.now()}start(){this.ticker.start()}stop(){this.ticker.stop()}},P={lerp(r,e,n){return r+(e-r)*n},clamp(r,e,n){return Math.min(n,Math.max(e,r))},clamp01(r){return Math.min(1,Math.max(0,r))},easeLinear(r){return r},easeInQuad(r){return r*r},easeOutQuad(r){return 1-(1-r)*(1-r)},easeInOutQuad(r){return r<.5?2*r*r:1-Math.pow(-2*r+2,2)/2},easeInSine(r){return 1-Math.cos(r*Math.PI/2)},easeOutSine(r){return Math.sin(r*Math.PI/2)},easeInOutSine(r){return-(Math.cos(Math.PI*r)-1)/2},easeInExpo(r){return r===0?0:Math.pow(2,10*r-10)},easeOutExpo(r){return r===1?1:1-Math.pow(2,-10*r)},easeInOutExpo(r){return r===0?0:r===1?1:r<.5?Math.pow(2,20*r-10)/2:(2-Math.pow(2,-20*r+10))/2},smoothstep(r){return r=P.clamp(r,0,1),r*r*(3-2*r)},randomLerp(r,e){return P.lerp(r,e,Math.random())},randomInt(r,e){return Math.floor(Math.random()*(e-r+1))+r},randomArrayValue(r){return r[P.randomInt(0,r.length-1)]},createBezier(r,e,n,s){function a(f,h,c,p,g){let x=1-f;return x*x*x*h+3*x*x*f*c+3*x*f*f*p+f*f*f*g}function l(f,h,c,p,g){let x=1-f;return 3*x*x*(c-h)+6*x*f*(p-c)+3*f*f*(g-p)}function d(f){let h=f;for(let c=0;c<6;c++){let p=a(h,0,r,n,1),g=l(h,0,r,n,1);if(g===0)break;h-=(p-f)/g}return P.clamp(h,0,1)}return function(h){h=P.clamp(h,0,1);let c=d(h);return a(c,0,e,s,1)}},lengthSquared(...r){return r.reduce((e,n)=>e+n*n,0)},normalizeRad(r){let e=2*Math.PI;return r=r%e,r<0&&(r+=e),r},angleInvertY(r){return P.normalizeRad(-r)},degToRadFlipY(r){return P.angleInvertY(r*Math.PI/180)},minimalAngularDirection(r,e){r=P.normalizeRad(r),e=P.normalizeRad(e);let n=P.normalizeRad(e-r),s=P.normalizeRad(r-e);return n<=s?1:-1}},fe=class extends I{constructor({delta:e,ms:n,easing:s}){super(),this.delta=e,this.duration=n,this.elapsed=0,this.easing=s??(a=>a),this.lastValue=0,this.finished=!1}delta;duration;elapsed;lastValue;finished;easing;update(e){this.elapsed+=e*1e3;let n=P.clamp(this.elapsed/this.duration,0,1),s=this.easing(n),a=this.delta*s,l=a-this.lastValue;this.lastValue=a,this.emit("delta",l),n>=1&&(this.finished=!0,this.emit("finish",void 0))}},ee=class extends N{constructor(e,n=0,s=0,a=50,l=50){super(e,n,s),this.width=a,this.height=l}width;height;get left(){return this.x-this.width/2}set left(e){this.x=e+this.width/2}get right(){return this.x+this.width/2}set right(e){this.x=e-this.width/2}get top(){return this.y-this.height/2}set top(e){this.y=e+this.height/2}get bottom(){return this.y+this.height/2}set bottom(e){this.y=e-this.height/2}get lx(){return 0}get ly(){return 0}get lleft(){return-this.width/2}get lright(){return this.width/2}get ltop(){return-this.height/2}get lbottom(){return this.height/2}isCollidingWith(e){return!(this.right<e.left||this.left>e.right||this.bottom<e.top||this.top>e.bottom)}color="rgba(0, 0, 255, 0.3)";draw(e){e.translate(this.x,this.y),e.rotate(this.scaleRotate),e.fillStyle=this.color,e.fillRect(-this.width/2,-this.height/2,this.width,this.height)}},pe=class extends I{duration;ticker;elapsed;finished;_resolve;promise;_timeoutId;constructor(e,n=null){super(),this.duration=e,this.ticker=n,this.elapsed=0,this.finished=!1,this._resolve=null,this.promise=new Promise(s=>this._resolve=s),this.update=this.update.bind(this),this.ticker&&this.ticker.on("tick",this.update)}update(e=0){this.finished||(this.elapsed+=e*1e3,this.elapsed>=this.duration&&this.finish())}finish(){this.finished||(this.finished=!0,this.emit("finish",void 0),this._resolve&&this._resolve(),this.ticker&&this.ticker.off("tick",this.update))}start(){return this.ticker||(this._timeoutId=setTimeout(()=>this.finish(),this.duration)),this}cancel(){this.finished||(this.finished=!0,!this.ticker&&this._timeoutId!=null&&clearTimeout(this._timeoutId),this.ticker&&this.ticker.off("tick",this.update))}then(e,n){return this.promise.then(e,n)}after(e,n){return this.promise.then(e,n)}},M=class r{constructor(e=0,n=0){this.x=e,this.y=n}x;y;toJSON(){return{x:this.x,y:this.y,vec2:!0}}static isVec2(e){return e&&typeof e=="object"&&"x"in e&&"y"in e&&e.vec2===!0}static fromSerialized(e){return this.isVec2(e)?new this(e.x,e.y):null}rotate(e){let n=Math.cos(e),s=Math.sin(e);return new r(this.x*n-this.y*s,this.x*s+this.y*n)}static from(e){return new r(Math.cos(e),Math.sin(e))}isEmpty(){return Math.abs(this.x)<.01&&Math.abs(this.y)<.01}get angle(){return Math.atan2(this.y,this.x)}angleTo(e){return Math.atan2(e.y-this.y,e.x-this.x)}get length(){return Math.hypot(this.x,this.y)}get lengthSquared(){return this.x*this.x+this.y*this.y}normalized(){let e=this.length;return e===0?new r(0,0):new r(this.x/e,this.y/e)}consume(e){let n=this.length;n<=e?(this.x=0,this.y=0):this.overwite(this.scale((n-e)/n))}project(e){return e.scale(this.dotNormalized(e))}reflect(e){let n=this.dot(e);return this.subtract(e.scale(2*n))}dotNormalized(e){let n=this.normalized(),s=e.normalized();return n.x*s.x+n.y*s.y}lengthSquaredTo(e){let n=this.x-e.x,s=this.y-e.y;return n*n+s*s}dot(e){return this.x*e.x+this.y*e.y}distanceTo(e){return Math.hypot(this.x-e.x,this.y-e.y)}distanceToCheap(e){let n=this.x-e.x,s=this.y-e.y;return n*n+s*s}directionTo(e){return new r(e.x-this.x,e.y-this.y).normalized()}add(e){return new r(this.x+e.x,this.y+e.y)}addRaw(e){return new r(this.x+e,this.y+e)}overwite(e){this.x=e.x,this.y=e.y}subtract(e){return new r(this.x-e.x,this.y-e.y)}scale(e){return new r(this.x*e,this.y*e)}toString(){return`Vector2(${this.x}, ${this.y})`}clone(){return new r(this.x,this.y)}};function De(){return typeof process<"u"&&process.release?.name==="node"?"node":typeof window<"u"||typeof self<"u"?"web":"unknown"}var Re=De(),U=Re==="node",k=Re==="web",X=class r{static unlock(){k&&this.audioCtx.state!=="running"&&this.audioCtx.resume()}static audioCtx=k?new AudioContext:null;static masterGain=k?this.audioCtx.createGain():null;static musicGain=k?this.audioCtx.createGain():null;static sfxGain=k?this.audioCtx.createGain():null;static{k&&(this.masterGain.gain.value=1,this.musicGain.gain.value=1,this.sfxGain.gain.value=1,this.sfxGain.connect(this.masterGain),this.musicGain.connect(this.masterGain),this.masterGain.connect(this.audioCtx.destination))}static get SFX_VOLUME(){return this.sfxGain.gain.value}static get MUSIC_VOLUME(){return this.musicGain.gain.value}static get VOLUME(){return this.masterGain.gain.value}static set SFX_VOLUME(e){this.sfxGain.gain.value=e}static set MUSIC_VOLUME(e){this.musicGain.gain.value=e}static set VOLUME(e){this.masterGain.gain.value=e}static noteToHz(e){return this.tuningFreq*Math.pow(2,(e-9)/12)}static tuningFreq=440;static audioBufferCache=new Map;static loops=new Map;static sfsx=new Map;static loopIdCounter=0;static CACHE_NAME="lia-audio-cache-v1";static async preLoad(e){if(this.audioBufferCache.has(e))return this.audioBufferCache.get(e);let n=r.CACHE_NAME,s,a;if(typeof caches<"u"&&(a=await caches.open(n),s=await a.match(e)),!s){if(s=await fetch(e),!s.ok)throw new Error(`Failed to fetch ${e}`);a&&await a.put(e,s.clone())}let l=await s.arrayBuffer(),d=await this.audioCtx.decodeAudioData(l);return this.audioBufferCache.set(e,d),d}static async getOnlyDownloadedCache(e){let n=r.CACHE_NAME;return await(await caches.open(n)).match(e)}static getCached(e){return this.audioBufferCache.get(e)||null}static async playSound(e,n=.2,s=1,a=!0){try{this.sfsx.has(e)&&this.sfsx.get(e).source.stop(),this.audioBufferCache.has(e)||await this.preLoad(e);let l=this.getCached(e);if(!l)return;let d=new O(l);d.buffer=l;let f=1-.12,h=1+.12;d.playbackRate=s??f+Math.random()*(h-f);let c=this.audioCtx.createGain();c.gain.value=n,d.tempGain=c,d.connect(c),c.connect(this.sfxGain),d.onended=()=>{d.disconnect(),c.disconnect()},d.start(),a&&this.sfsx.set(e,{source:d,gain:c})}catch(l){console.error(l)}}static async playLoop(e,n=1,{loopStart:s=0,loopEnd:a=null,exclusive:l=!0,skipMS:d=0}={}){if(l)for(let g of this.loops.keys())this.stopLoop(g);this.audioBufferCache.has(e)||await this.preLoad(e);let f=this.getCached(e);if(!f)return;let h=new O(f);h.buffer=f,h.loop=!0,typeof s=="number"&&(h.loopStart=s),typeof a=="number"&&(h.loopEnd=a);let c=this.audioCtx.createGain();c.gain.value=n,h.tempGain=c,h.playbackRate=1,h.onended=()=>{h.disconnect(),c.disconnect()},h.connect(c),c.connect(this.musicGain),h.start(0,d/1e3);let p=++this.loopIdCounter;return this.loops.set(p,{source:h,gain:c}),p}static stopLoop(e){let n=this.loops.get(e);n&&(n.source.stop(),n.source.notIndependent||(n.source.disconnect(),n.gain.disconnect()),this.loops.delete(e))}static async createLiaSource(e,{volume:n=1,speed:s=1,loop:a=!1,loopStart:l=0,loopEnd:d=null,isMusic:f=!1,gain:h=null}={}){try{this.audioBufferCache.has(e)||await this.preLoad(e);let c=this.getCached(e);if(!c)return null;let p=new O(c);p.loop=a,p.loopStart=l,p.loopEnd=typeof d=="number"?d:c.duration,p.playbackRate=s;let g=this.audioCtx.createGain();return g.gain.value=n,p.connect(g),p.tempGain=g,g.connect(h||(f?this.musicGain:this.sfxGain)),p.onended=()=>{p.disconnect(),g.disconnect()},p}catch(c){return console.error("Failed to create LiaAudioSrc:",c),null}}};var O=class{numberOfInputs;numberOfOutputs;constructor(e,n=X.audioCtx){this.context=n,this.buffer=e,this.source=null,this.startTime=0,this.pauseTime=0,this.playbackRate=1,this.isPlaying=!1,this.loop=!1,this.output=k?n.createGain():null,this.output.gain.value=1,this.channelCount=2,this.channelCountMode="max",this.channelInterpretation="speakers",this.numberOfInputs=0,this.numberOfOutputs=1,this.onended=null}channelCount;channelCountMode;channelInterpretation;onended;source;buffer;context;_createSource(){this.source&&(this.source.onended=null);let e=this.context.createBufferSource();return e.buffer=this.buffer,e.playbackRate.value=this.playbackRate,e.loop=this.loop,e.loopStart=this.loopStart,e.loopEnd=this.loopEnd>0?this.loopEnd:this.buffer.duration,e.connect(this.output),this.source=e,e.onended=()=>{this.source===e&&(this.isPlaying&&!this.loop&&(this.isPlaying=!1,this.pauseTime=0),typeof this.onended=="function"&&this.onended())},e}play({fadeIn:e=0,offset:n=null}={}){let s=n!==null?n:this.pauseTime;if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.source=this._createSource(),this.startTime=this.context.currentTime-s/this.playbackRate,this.source.start(0,s),e>0?(this.output.gain.setValueAtTime(0,this.context.currentTime),this.output.gain.linearRampToValueAtTime(1,this.context.currentTime+e)):this.output.gain.setValueAtTime(1,this.context.currentTime),this.isPlaying=!0}start(e=0,n=0,s){this.isPlaying||(this.source=this._createSource(),this.startTime=this.context.currentTime+e-n/this.playbackRate,s!==void 0?this.source.start(this.context.currentTime+e,n,s):this.source.start(this.context.currentTime+e,n),this.pauseTime=n,this.isPlaying=!0)}pause({fadeOut:e=0}={}){if(!this.isPlaying)return;let n=this.getElapsed()/1e3;if(this.loop&&this.loopEnd>this.loopStart){let s=this.loopEnd-this.loopStart;n=this.loopStart+(n-this.loopStart)%s}if(this.isPlaying=!1,e>0){let s=this.context.currentTime;this.output.gain.setValueAtTime(this.output.gain.value,s),this.output.gain.linearRampToValueAtTime(0,s+e),setTimeout(()=>{if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.pauseTime=n,this.output.gain.setValueAtTime(1,this.context.currentTime)},e*1e3)}else{if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.pauseTime=n}}getElapsed(){return this.isPlaying?(this.context.currentTime-this.startTime)*this.playbackRate*1e3:this.pauseTime*1e3}setSpeed(e){if(e<=0)throw new Error("Playback rate must be positive");let n=this.getElapsed()/1e3;this.playbackRate=e,this.isPlaying&&(this.pause(),this.pauseTime=n,this.play())}setLoop(e=!0){this.loop=e,this.source&&(this.source.loop=e)}loop;playbackRate;startTime;tempGain=null;connect(e,n=0,s=0){if("value"in e)this.output.connect(e,n);else return this.output.connect(e,n,s),e}disconnect(e,n,s){e===void 0?this.output.disconnect():this.output.disconnect(e,n,s)}output;stop(e=0){if(this.notIndependent)return this.pause();if(!this.source)return;let n=this.context.currentTime+e;this.source.stop(n),this.isPlaying=!1,this.notIndependent||(this.pauseTime=0)}pauseTime;isPlaying;notIndependent=!1;loopStart=0;loopEnd=0},Ge={osc:{enabled:!0,type:"sine",freq:440,detune:0},noise:{enabled:!1,level:.5},ampEnv:{attack:.005,decay:.1,sustain:0,release:.1,volume:.3},pitchEnv:{amount:0,decay:.2},filter:{enabled:!1,type:"lowpass",freq:1200,Q:1,envAmount:0,decay:.2},lfo:{enabled:!1,target:"freq",rate:8,depth:20},duration:.4},V=class r{constructor(e={}){this.ctx=X.audioCtx,this.cfg=structuredClone(Ge),Object.assign(this.cfg,e)}ctx;cfg;play(e=X.sfxGain){let n=this.ctx,s=n.currentTime,a=this.cfg,l=n.createGain();l.gain.setValueAtTime(1e-4,s);let d=a.ampEnv;l.gain.exponentialRampToValueAtTime(d.volume,s+d.attack),l.gain.exponentialRampToValueAtTime(Math.max(1e-4,d.sustain*d.volume),s+d.attack+d.decay),l.gain.exponentialRampToValueAtTime(1e-4,s+a.duration+d.release);let f=l,h;a.filter.enabled&&(h=n.createBiquadFilter(),h.type=a.filter.type,h.frequency.value=a.filter.freq,h.Q.value=a.filter.Q,h.connect(l),f=h);let c;if(a.osc.enabled){if(c=n.createOscillator(),c.type=a.osc.type,c.frequency.value=a.osc.freq,c.detune.value=a.osc.detune,a.pitchEnv.amount!==0){let i=Math.pow(2,a.pitchEnv.amount/12);c.frequency.exponentialRampToValueAtTime(a.osc.freq*i,s+a.pitchEnv.decay)}c.connect(f),c.start(s),c.stop(s+a.duration+d.release)}let p;if(a.noise.enabled){let i=n.sampleRate*a.duration,o=n.createBuffer(1,i,n.sampleRate),u=o.getChannelData(0);for(let y=0;y<i;y++)u[y]=(Math.random()*2-1)*a.noise.level;p=n.createBufferSource(),p.buffer=o,p.connect(f),p.start(s),p.stop(s+a.duration+d.release)}let g,x;a.lfo.enabled&&c&&(g=n.createOscillator(),g.frequency.value=a.lfo.rate,x=n.createGain(),x.gain.value=a.lfo.depth,g.connect(x),a.lfo.target==="freq"?x.connect(c.frequency):a.lfo.target==="gain"?x.connect(l.gain):a.lfo.target==="filter"&&h&&x.connect(h.frequency),g.start(s),g.stop(s+a.duration)),l.connect(e);let v=[c,p,g,x,h,l],t=s+a.duration+d.release;setTimeout(()=>{v.forEach(i=>i?.disconnect())},(t-n.currentTime)*1e3)}getConfig(){return structuredClone(this.cfg)}setConfig(e){return Object.assign(this.cfg,e),this}getKey(e){return this.cfg[e]}setKey(e,n){return Object.assign(this.cfg[e],n),this}setFreq(e){return this.cfg.osc.freq=e,this}setWave(e){return this.cfg.osc.type=e,this}setVolume(e){return this.cfg.ampEnv.volume=e,this}setAmpEnv(e,n,s,a){return Object.assign(this.cfg.ampEnv,{attack:e,decay:n,sustain:s,release:a}),this}setPitchEnv(e,n){return Object.assign(this.cfg.pitchEnv,{amount:e,decay:n}),this}setNoiseEnabled(e){return this.cfg.noise.enabled=e,this}setNoiseLevel(e){return this.cfg.noise.level=e,this}setFilterEnabled(e){return this.cfg.filter.enabled=e,this}setFilter(e,n,s){return Object.assign(this.cfg.filter,{type:e,freq:n,Q:s,enabled:!0}),this}setLFOEnabled(e){return this.cfg.lfo.enabled=e,this}setLFO(e,n,s){return Object.assign(this.cfg.lfo,{target:e,rate:n,depth:s,enabled:!0}),this}setDuration(e){return this.cfg.duration=e,this}clone(){return new r(structuredClone(this.cfg))}},mt=new V({osc:{enabled:!0,type:"square",freq:900,detune:0},ampEnv:{attack:.002,decay:.04,sustain:0,release:.02,volume:.15},duration:.05}),yt=new V({osc:{enabled:!0,type:"sine",freq:600,detune:0},ampEnv:{attack:.01,decay:.08,sustain:0,release:.04,volume:.12},duration:.1}),bt=new V({osc:{enabled:!0,type:"triangle",freq:500,detune:0},pitchEnv:{amount:12,decay:.15},ampEnv:{attack:.01,decay:.12,sustain:0,release:.05,volume:.25},duration:.18}),gt=new V({osc:{enabled:!0,type:"sawtooth",freq:1200,detune:0},pitchEnv:{amount:-24,decay:.3},ampEnv:{attack:.005,decay:.25,sustain:0,release:.05,volume:.3},duration:.35}),xt=new V({osc:{enabled:!0,type:"square",freq:180,detune:0},noise:{enabled:!0,level:.4},ampEnv:{attack:.002,decay:.15,sustain:0,release:.05,volume:.35},duration:.2});function me(r=12){let e=Date.now().toString(36),n=crypto.getRandomValues(new Uint8Array(4)),s=Array.from(n).map(a=>a.toString(36).padStart(2,"0")).join("");return(e+s).slice(0,r)}function ze(r){let e=!0;function n(){e&&(r(),requestAnimationFrame(n))}return requestAnimationFrame(n),{clear:()=>e=!1}}function He(){return U?!1:/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)}var vt=He();function Ue({width:r,height:e,updateHz:n="frames"}){return new G.KaylaGame(r,e,n==="frames"?1/0:n)}function $e(r){let e=new J(r);return new G.KaylaScene(e)}function Oe(r){return new G.KaylaRenderer(r)}function ne(r,e){if(typeof r!="function")throw new Error("Invalid Element Type.");let n=e??{};return n.key??=r.name+"_"+me(),{type:r,props:n}}var L;(s=>{function r(a,l){return!(a.right<l.left||a.left>l.right||a.bottom<l.top||a.top>l.bottom)}s.rawCollision=r;function e(a,l,d){let f=l*Math.PI/180,h=Math.cos(f),c=Math.sin(f),p=1/0;return h>0&&(p=Math.min(p,(d.right-a.x)/h)),h<0&&(p=Math.min(p,(d.left-a.x)/h)),c>0&&(p=Math.min(p,(d.bottom-a.y)/c)),c<0&&(p=Math.min(p,(d.top-a.y)/c)),M.from(l).scale(p)}s.getCurrToBound=e;function n(a){let{left:l,right:d,top:f,bottom:h,width:c,height:p,x:g=0,y:x=0}=a;if(c===null||p===null)throw new Error("width and height are required");let v,t;if(l!=null&&d!=null){if(Math.abs(d-l-c)>1e-6)throw new Error("left, right, and width mismatch");v=l}else g!=null?v=g-c/2:l!=null?v=l:d!=null?v=d-c:v=0;if(f!=null&&h!=null){if(Math.abs(h-f-p)>1e-6)throw new Error("top, bottom, and height mismatch");t=f}else x!=null?t=x-p/2:f!=null?t=f:h!=null?t=h-p:t=0;return{left:v,right:v+c,top:t,bottom:t+p,width:c,height:p,x:v+c/2,y:t+p/2}}s.createRawRect=n})(L||={});var G;(x=>{class r extends Z{#e;#t;constructor(t,i,o){super(t,i,o),this.#e=new Set,this.#t=!1}delay(t){return this.ticker.createTimeout(t)}get started(){return this.#t}start(){if(!this.#t){for(let t of this.#e)t.start();this.#t=!0,super.start()}}stop(){if(this.#t){for(let t of this.#e)t.stop();this.#t=!1,super.stop()}}addRenderer(t){this.#e.has(t)||(this.#e.add(t),this.#t&&t.start(),t.game=this)}get mainRenderer(){return[...this.#e].at(0)}getRenderers(){return[...this.#e]}deleteRenderer(t){this.#e.has(t)&&(this.#e.delete(t),this.#t&&t.stop(),delete t.game)}}x.KaylaGame=r;class e extends Q{game;pointerX;pointerY;pointerEvents;onPointerDown;onPointerUp;onPointerCancel;onPointerMove;constructor(t){super(t),this.useDraw=this.useDraw.bind(this),this.on("draw",i=>{if(this.game)for(let o of this.game.scenes.values())o.handleDraw(i)}),this.pointerX=0,this.pointerY=0,this.pointerEvents=new I,this.pointerPosUpdater=this.pointerPosUpdater.bind(this),this.onPointerDown=i=>this.onPointerAll(i,"down"),this.onPointerUp=i=>this.onPointerAll(i,"up"),this.onPointerCancel=i=>this.onPointerAll(i,"cancel"),this.onPointerMove=i=>this.onPointerAll(i,"move")}pointerPosUpdater(t){this.pointerX=t.clientX,this.pointerY=t.clientY}onPointerAll(t,i){this.pointerPosUpdater(t);let o=e.getClickType(t);if(o!=="invalid"||i==="move"||i==="cancel"){t.preventDefault();let u=this.getMousePos();this.pointerEvents.emit("action",u,o,i)}}static getClickType(t){switch(t.button){case 0:return"left";case 1:return"middle";case 2:return"right";default:return"invalid"}}listenPointerUpdates(){this.canvas.addEventListener("pointermove",this.pointerPosUpdater),this.canvas.addEventListener("pointerdown",this.onPointerDown),this.canvas.addEventListener("pointerup",this.onPointerUp),this.canvas.addEventListener("pointercancel",this.onPointerCancel),this.canvas.addEventListener("pointermove",this.onPointerMove)}unlistenPointerUpdates(){this.canvas.removeEventListener("pointermove",this.pointerPosUpdater),this.canvas.removeEventListener("pointerdown",this.onPointerDown),this.canvas.removeEventListener("pointerup",this.onPointerUp),this.canvas.removeEventListener("pointermove",this.onPointerMove)}pointerPosToWorldPos(t,i){let o=this.canvas.getBoundingClientRect(),u=(t-o.left)/o.width,y=(i-o.top)/o.height,b=u*this.viewportWidth*this.cameraWidth/o.width,C=y*this.viewportHeight*this.cameraHeight/o.height;return new M(b,C)}getMousePos(){return this.pointerPosToWorldPos(this.pointerX,this.pointerY)}useDraw(t){let i=o=>{t(o,new s)};return this.on("draw",i),()=>{this.off("draw",i)}}attachTo(t){t.addRenderer(this),this.game=t}detach(){this.game&&this.game.deleteRenderer(this)}}x.KaylaRenderer=e;class n{current;saves;constructor(){this.saves=[]}useTick(t){if(!this.current)throw new Error("Hook 'useTick' must be executed in the top level scope of a component.");this.current.onTick[this.current.useStepCallIndex]=t,this.current.useStepCallIndex++}usePaint(t){if(!this.current)throw new Error("Hook 'usePaint' must be executed in the top level scope of a component.");this.current.onPaint[this.current.useDrawCallIndex]=t,this.current.useDrawCallIndex++}useEntity(){if(!this.current)throw new Error("Hook 'useEntity' must be executed in the top level scope of a component.");return ye(be)}useSelf(t){if(!this.current)throw new Error("Hook 'useSelf' must be executed in the top level scope of a component.");let i=ye(null);return(i.current===null||i.current===void 0)&&(i.current=t()),i.current}useInitialization(t){if(!this.current)throw new Error("Hook 'useInitialization' must be executed in the top level scope of a component.");let i=this.current;i.onInits[this.current.useInitCallIndex]=t,i.useInitCallIndex++}useRect(){if(!this.current)throw new Error("Hook 'useRect' must be executed in the top level scope of a component.");return D(()=>new x.KaylaInternalRect(this.current))}useFiber(){if(!this.current)throw new Error("Hook 'useFiber' must be executed in the top level scope of a component.");return D(()=>this.current)}useFiberControl(){if(!this.current)throw new Error("Hook 'useFiberControl' must be executed in the top level scope of a component.");let t=this.current;return D(()=>({refresh:()=>t.refresh(),get childrenCount(){return t.lastChildren.length},setMaxChildren:i=>{t.setMaxChildren(i)},getMaxChildren:()=>t.getMaxChildren(),get maxSafeChildren(){return t.maxSafeChildren},get key(){return t.key},get getChildrenEntities(){return t.getChildrenEntities.bind(t)},get getEntityChain(){return t.getEntityChain.bind(t)},get getFiberChain(){return t.getFiberChain.bind(t)}}))}useCurrentTicker(){if(!this.current)throw new Error("Hook 'useCurrentTicker' must be executed in the top level scope of a component.");return this.current.getAttachedGame().ticker}useCurrentRenderer(){if(!this.current)throw new Error("Hook 'useCurrentRenderer' must be executed in the top level scope of a component.");return this.current.getAttachedGame().mainRenderer}useCurrentGame(){if(!this.current)throw new Error("Hook 'useCurrentGame' must be executed in the top level scope of a component.");return this.current.getAttachedGame()}useCurrentScene(){if(!this.current)throw new Error("Hook 'useCurrentScene' must be executed in the top level scope of a component.");return this.current.scene}useState(t,{alwaysRecall:i=!1}={}){if(!this.current)throw new Error("Hook 'useState' must be executed in the top level scope of a component.");let u=this.current.state[this.current.useStateCallIndex]??new a(this.current,t,{alwaysRecall:i});return this.current.state[this.current.useStateCallIndex]=u,this.current.useStateCallIndex++,u}useShouldRefresh(t){let i=this.current;if(!i)throw new Error("useShouldRefresh must be called inside a component");i.watchedDeps&&console.warn("useShouldRefresh called multiple times \u2014 using the last call"),i.watchedDeps=t}useRef(t){if(!this.current)throw new Error("Hook 'useRef' must be executed in the top level scope of a component.");let o=this.current.refs[this.current.useRefCallIndex]??d(t??null);return this.current.refs[this.current.useRefCallIndex]=o,this.current.useRefCallIndex++,o}useEffect(t){if(!this.current)throw new Error("Hook 'useEffect' must be executed in the top level scope of a component.");this.current.onEffect[this.current.useEffectCallIndex]=t,this.current.useEffectCallIndex++}useViewportEffect(t){if(!this.current)throw new Error("Hook 'useViewport' must be executed in the top level scope of a component.");this.current.onViewportEffect[this.current.useViewCallIndex]=t,this.current.useViewCallIndex++}useExports(t,i){if(!this.current)throw new Error("Hook 'useExports' must be executed in the top level scope of a component.");this.current.onExport=i}useGlobalPointer(t,i){if(!this.current)throw new Error("Hook 'useGlobalPointer/useGlobalClick' must be executed in the top level scope of a component.");i??={},this.current.onGlobalPointer[this.current.useGlobalClickCallIndex]={handler:t,config:i},this.current.useGlobalClickCallIndex++}usePointer(t,i){if(!this.current)throw new Error("Hook 'usePointer/useClick' must be executed in the top level scope of a component.");i??={};let o=this.current;Te((u,y,b)=>{let C=o.entity;if(!C)return;let E=C.getRawRect(),z=L.createRawRect({x:u.x,y:u.y,width:3,height:3});L.rawCollision(E,z)&&t(u,y,b)},i)}useContext(t){if(!this.current)throw new Error("Hook 'useContext' must be executed in the top level scope of a component.");return this.current.findContextValueFromInst(t)}save(){this.saves.push({current:this.current})}restore(){let t=this.saves.pop();if(!t)throw new Error("Cannot restore without saving.");this.current=t.current}logLevel="warn";logger={debug:(...t)=>{this.logLevel==="debug"&&console.debug(...t)},info:(...t)=>{["info","warn","debug"].includes(this.logLevel)&&console.info(...t)},warn:(...t)=>{["warn","debug"].includes(this.logLevel)&&console.warn(...t)},error:(...t)=>console.error(...t),withFiber:(t,i,o,...u)=>{let y=t?.fc?.name||"anonymous",b=t?.key?` key=${t.key}`:"";this.logger[i](`${o} <${y}${b}>`,...u)}}}x.GlobalKayla=n;class s{preventDefault(){this.#e=!0}#e=!1;isPrevented(){return this.#e}}x.KaylaEvent=s;class a{#e;#t;#n;alwaysRecall;constructor(t,i,{alwaysRecall:o=!1}={}){this.#t=t,this.#e=i??void 0,this.#n=Date.now(),this.alwaysRecall=o}get(){return this.#e}*[Symbol.iterator](){throw new Error(`Hey! KaylaState is NOT an array / iterable like useState in React.
|
|
1
|
+
"use strict";var ce=Object.defineProperty;var Fe=Object.getOwnPropertyDescriptor;var Me=Object.getOwnPropertyNames;var Ae=Object.prototype.hasOwnProperty;var Ke=(r,e)=>{for(var n in e)ce(r,n,{get:e[n],enumerable:!0})},Le=(r,e,n,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of Me(e))!Ae.call(r,a)&&a!==n&&ce(r,a,{get:()=>e[a],enumerable:!(s=Fe(e,a))||s.enumerable});return r};var _e=r=>Le(ce({},"__esModule",{value:!0}),r);var dt={};Ke(dt,{Fragment:()=>ct,jsx:()=>ut,jsxDEV:()=>ht,jsxs:()=>Ie});module.exports=_e(dt);var Ee={};Ke(Ee,{JSX:()=>Se,KMatrix2D:()=>ge,KaylaContext:()=>te,KaylaFragment:()=>Ce,KaylaInternals:()=>G,KaylaRect:()=>L,Layer:()=>ot,createContext:()=>Ne,createElement:()=>ne,createGame:()=>Ue,createReassignableObject:()=>it,createRenderer:()=>Oe,createScene:()=>$e,createUseHook:()=>at,self:()=>be,setLogLevel:()=>st,useClick:()=>je,useContext:()=>nt,useCurrentGame:()=>Ze,useCurrentRenderer:()=>et,useCurrentScene:()=>Pe,useCurrentTicker:()=>tt,useDisposableRef:()=>rt,useEffect:()=>re,useEntity:()=>Je,useExports:()=>oe,useFiber:()=>ve,useFiberControl:()=>xe,useGlobalClick:()=>Te,useGlobalPointer:()=>We,useInitialization:()=>ie,useNextStack:()=>we,usePaint:()=>ae,usePointer:()=>Ye,useRect:()=>se,useRef:()=>ye,useSelf:()=>D,useShouldRefresh:()=>qe,useState:()=>Xe,useTick:()=>Qe,useViewportEffect:()=>Be});var I=class{#e=new Map;constructor(){this.#e=new Map}on(e,n){let s=this.#e.get(e)||[];return s.push(n),this.#e.set(e,s),this}once(e,n){let s=(...a)=>{this.off(e,s),n(...a)};return this.on(e,s),this}off(e,n){let s=this.#e.get(e);if(!s)return this;let a=s.indexOf(n);return a>=0&&s.splice(a,1),this}emit(e,...n){let s=this.#e.get(e);if(!s||s.length===0){if(e==="error")throw n[0];return!1}return s.slice().forEach(a=>a(...n)),!0}removeAllListeners(e){return e?this.#e.delete(e):this.#e.clear(),this}listenerCount(e){return this.#e.get(e)?.length??0}},Q=class extends I{#e;#t;running;_rafId;_fps;_frameCount;_fpsTimer;_lastFrameTime;get canvas(){return this.#e}get ctx(){return this.#t}set canvas(e){this.#e=e,this.#t=e.getContext("2d"),this.updateCanvasResolution()}constructor(e,{viewportWidth:n,viewportHeight:s,cameraWidth:a,cameraHeight:l}={}){if(!k)throw new Error("Web-Only");super(),this.canvas=e,this.automatic=!0,this.#n=n??e.width,this.#r=s??e.height,this.#i=a??e.width,this.#s=l??e.height,this.running=!1,this._rafId=null,this._loop=this._loop.bind(this),this.updateCanvasResolution(),this._fps=60,this._frameCount=0,this._fpsTimer=0}automatic;retransform(){this.ctx.setTransform(1,0,0,1,0,0);let e=this.#i/this.#n,n=this.#s/this.#r;this.ctx.translate(this.#i/2,this.#s/2),this.ctx.scale(e,n),this.ctx.translate(-this.#n/2,-this.#r/2)}#n=0;#r=0;#i=0;#s=0;get viewportWidth(){return this.#n}set viewportWidth(e){this.#n=e,this.retransform(),this.emitViewportUpdate()}get width(){return this.#n}get height(){return this.#r}get centerX(){return this.#n/2}get centerY(){return this.#r/2}get left(){return 0}get top(){return 0}get right(){return this.#n}get bottom(){return this.#r}get viewportHeight(){return this.#r}set viewportHeight(e){this.#r=e,this.retransform(),this.emitViewportUpdate()}get cameraWidth(){return this.#i}set cameraWidth(e){this.#i=e,this.updateCanvasResolution(),this.retransform()}get cameraHeight(){return this.#s}set cameraHeight(e){this.#s=e,this.updateCanvasResolution(),this.retransform()}updateCanvasResolution(){this.canvas.width=this.#i,this.canvas.height=this.#s}emitViewportUpdate(){this.emit("viewport_update",{width:this.viewportWidth,height:this.viewportHeight})}applyTransform(){this.retransform()}get FPS(){return this._fps}_loop(){this.automatic&&this.update(),this._rafId=requestAnimationFrame(this._loop)}update(){if(!this.running||!k)return;let e=performance.now(),n=(e-(this._lastFrameTime??e))/1e3;this._lastFrameTime=e,this._frameCount++,this._fpsTimer+=n,this._fpsTimer>=1&&(this._fps=Math.round(this._frameCount/this._fpsTimer),this._frameCount=0,this._fpsTimer=0),this.ctx.clearRect(0,0,this.#i,this.#s),this.emit("draw",this.ctx)}start(){if(!this.running){if(!k||typeof globalThis.requestAnimationFrame>"u")throw new Error("Raf is not supported");this.running=!0,this._rafId=requestAnimationFrame(this._loop)}}stop(){if(!k||typeof globalThis.requestAnimationFrame>"u")throw new Error("Raf is not supported");this.running=!1,this._rafId!==null&&(cancelAnimationFrame(this._rafId),this._rafId=null)}},de=class extends I{setNow(e){this.#e=e}#e=0;__intervalId=null;__lastTime=0;constructor(e=16){super(),this.#t=e,this.speedHackDT=1}speedHackDT;get isRaf(){return this.tickInterval===1/0}#t=15;get tickInterval(){return this.#t}set tickInterval(e){this.#t=e,this.__intervalId&&(this.stop(),this.start())}now(){return this.#e}__tick(){let e=performance.now(),n=(e-this.__lastTime)/1e3*this.speedHackDT;this.__lastTime=e,!(k&&typeof this.__intervalId=="function"&&document.hidden)&&(this.#e+=n*1e3,this.emit("tick",n))}createTimeout(e){return new pe(e,this)}createTween(e,n=()=>{}){let s=new fe(e),a=(l=0)=>{if(s.finished){this.off("tick",a);return}s.update(l)};return s.on("finish",()=>{this.off("tick",a)}),s.on("delta",l=>{n(l)}),this.on("tick",a),s}start(){this.__intervalId===null&&(this.__lastTime=performance.now(),this.__intervalId=k&&!isFinite(this.tickInterval)?ze(()=>this.__tick()).clear:setInterval(()=>this.__tick(),this.tickInterval))}stop(){this.__intervalId!==null&&(typeof this.__intervalId=="function"?this.__intervalId():clearInterval(this.__intervalId)),this.__intervalId=null}getSineMod(e,n=0){return .5+.5*Math.sin((this.now()%e/e+n)*2*Math.PI)}},Ve;(t=>{function r(i){return i===!0?1:0}t.booleanExport=r;function e(i){return i===0?!1:i===1}t.booleanImport=e;function n(i){return`${i.x}|${i.y}`}t.vec2Export=n;function s(i){let[o,u]=i.split("|"),y=parseFloat(o),b=parseFloat(u);if(isNaN(y)||isNaN(b))throw new Error(`Invalid Vector2 string: ${i}`);return new M(y,b)}t.vec2Import=s,t.booleanMap={mapExport:r,mapImport:e};function l(i){return o=>Number(o.toFixed(i))}t.createRounder=l;function d(i=10){return{mapExport(o){return Math.round(o/i)},mapImport(o){return o*i}}}t.createLowPrecision=d;function f(i){return Math.round(i)}t.lightWeightRounder=f;function h(i=100){return{mapExport(o){return Math.round(o*i)},mapImport(o){return o/i}}}t.createPercent=h;function c(i){let o=new Map(Object.entries(i));return{mapExport:u=>o.get(u)??null,mapImport:u=>Array.from(o.entries()).find(([y,b])=>b===u)?.[0]??null}}t.createLookup=c;function p(i){let o=i*(180/Math.PI);return Math.round((o%360+360)%360)}t.radToDeg=p;function g(i){return i*(Math.PI/180)}t.degToRad=g,t.angleRadToDeg={mapExport:p,mapImport:g};function v(i=10){let o=d(i);return{mapExport(u){return o.mapExport(p(u))},mapImport(u){return o.mapImport(g(u))}}}t.createLowPrecisionRadToDeg=v})(Ve||={});var N=class r extends I{name="";scaleRotate=0;scale=1;constructor(e,n=0,s=0){super(),this.autoTranslate=!1,this.name=e,this.z=0,this.___pos=new M(n,s),this.nonSerializableProperties=[],this.nonSerializableProperties.push("___pos","autoTranslate","arraySerializeMap"),this.forceSerializableProperties=[],this.forceSerializableProperties.push("x","y")}arraySerializeMap;autoTranslate;z;___pos;nonSerializableProperties;forceSerializableProperties;get pos(){return this.___pos}get x(){return this.pos.x}get y(){return this.pos.y}set x(e){this.pos.x=e}set y(e){this.pos.y=e}handleUpdate(e){if(this.update)try{this.emit("update",e),this.update(e)}catch(n){this.emit("error",n)}}handleDraw(e){if(!(U||!this.draw)){e.save(),this.autoTranslate&&e.translate(this.x,this.y);try{this.emit("draw",e),this.draw(e)}catch(n){this.emit("error",n)}e.restore()}}serialize(){if(Array.isArray(this.arraySerializeMap))return this.arraySerializeMap.map(([a,{mapExport:l}])=>{let d=Reflect.get(this,a);return l?l(d):d});let e=["_events","_eventsCount","_maxListeners","nonSerializableProperties","forceSerializableProperties"],n=[...Reflect.ownKeys(this),...this.forceSerializableProperties].filter(a=>!this.nonSerializableProperties.includes(a)&&!e.includes(a.toString())),s=Object.fromEntries(n.map(a=>{let l=Reflect.get(this,a);if(U&&typeof l=="number"){let d=l.toString().split("."),h=(d[1]?d[1].length:0)>2?Number(l.toFixed(2)):l;return[a,h]}return[a,l]}));return JSON.parse(JSON.stringify(s))}toLocal(e){return e.subtract(this.pos)}toWorld(e){return e.add(this.pos)}deserializeArray(e){return r.deserializeArray(this.arraySerializeMap,e)}static deserializeArray(e,n){if(!e||!Array.isArray(n))return n;let s={};for(let a=0;a<n.length;a++){let l=e[a];if(!l)break;let[d,{mapImport:f}]=l,h=n[a];if(f&&(h=f(h)),typeof d!="string")break;try{Reflect.set(s,d,h)}catch(c){console.error(c)}}return s}},J=class extends I{name="";entities=new Map;paused=!0;constructor(e){super(),this.name=e}handleUpdate(e){if(!this.paused){this.emit("update",e);for(let n of this.entities.values())n.handleUpdate(e)}}handleDraw(e){if(!U&&!this.paused){this.emit("draw",e);for(let n of[...this.entities.values()].sort((s,a)=>s.z-a.z))n.handleDraw(e)}}addEntity(e){if(!(e instanceof N))throw new Error("invalid entity");if(!e.name)throw new Error("Entity must have a name.");this.entities.set(e.name,e)}removeEntity(e){if(!(e instanceof N))throw new Error("invalid entity");this.entities.delete(e.name)}getEntity(e){return this.entities.get(e)}},Z=class{scenes;ticker;get centerX(){return this.width/2}get centerY(){return this.height/2}get left(){return 0}get top(){return 0}get right(){return this.width}get bottom(){return this.height}width;height;constructor(e,n,s=16){this.ticker=new de(s),this.scenes=new Map,this.width=e,this.height=n,this.ticker.on("tick",a=>{for(let l of this.scenes.values())l.paused||l.handleUpdate(a)})}addScene(e){if(!e.name)throw new Error("Scene must have a name.");e.paused=!1,this.scenes.set(e.name,e)}removeScene(e){e&&(e.paused=!0),this.scenes.delete(e.name)}now(){return this.ticker.now()}start(){this.ticker.start()}stop(){this.ticker.stop()}},P={lerp(r,e,n){return r+(e-r)*n},clamp(r,e,n){return Math.min(n,Math.max(e,r))},clamp01(r){return Math.min(1,Math.max(0,r))},easeLinear(r){return r},easeInQuad(r){return r*r},easeOutQuad(r){return 1-(1-r)*(1-r)},easeInOutQuad(r){return r<.5?2*r*r:1-Math.pow(-2*r+2,2)/2},easeInSine(r){return 1-Math.cos(r*Math.PI/2)},easeOutSine(r){return Math.sin(r*Math.PI/2)},easeInOutSine(r){return-(Math.cos(Math.PI*r)-1)/2},easeInExpo(r){return r===0?0:Math.pow(2,10*r-10)},easeOutExpo(r){return r===1?1:1-Math.pow(2,-10*r)},easeInOutExpo(r){return r===0?0:r===1?1:r<.5?Math.pow(2,20*r-10)/2:(2-Math.pow(2,-20*r+10))/2},smoothstep(r){return r=P.clamp(r,0,1),r*r*(3-2*r)},randomLerp(r,e){return P.lerp(r,e,Math.random())},randomInt(r,e){return Math.floor(Math.random()*(e-r+1))+r},randomArrayValue(r){return r[P.randomInt(0,r.length-1)]},createBezier(r,e,n,s){function a(f,h,c,p,g){let x=1-f;return x*x*x*h+3*x*x*f*c+3*x*f*f*p+f*f*f*g}function l(f,h,c,p,g){let x=1-f;return 3*x*x*(c-h)+6*x*f*(p-c)+3*f*f*(g-p)}function d(f){let h=f;for(let c=0;c<6;c++){let p=a(h,0,r,n,1),g=l(h,0,r,n,1);if(g===0)break;h-=(p-f)/g}return P.clamp(h,0,1)}return function(h){h=P.clamp(h,0,1);let c=d(h);return a(c,0,e,s,1)}},lengthSquared(...r){return r.reduce((e,n)=>e+n*n,0)},normalizeRad(r){let e=2*Math.PI;return r=r%e,r<0&&(r+=e),r},angleInvertY(r){return P.normalizeRad(-r)},degToRadFlipY(r){return P.angleInvertY(r*Math.PI/180)},minimalAngularDirection(r,e){r=P.normalizeRad(r),e=P.normalizeRad(e);let n=P.normalizeRad(e-r),s=P.normalizeRad(r-e);return n<=s?1:-1}},fe=class extends I{constructor({delta:e,ms:n,easing:s}){super(),this.delta=e,this.duration=n,this.elapsed=0,this.easing=s??(a=>a),this.lastValue=0,this.finished=!1}delta;duration;elapsed;lastValue;finished;easing;update(e){this.elapsed+=e*1e3;let n=P.clamp(this.elapsed/this.duration,0,1),s=this.easing(n),a=this.delta*s,l=a-this.lastValue;this.lastValue=a,this.emit("delta",l),n>=1&&(this.finished=!0,this.emit("finish",void 0))}},ee=class extends N{constructor(e,n=0,s=0,a=50,l=50){super(e,n,s),this.width=a,this.height=l}width;height;get left(){return this.x-this.width/2}set left(e){this.x=e+this.width/2}get right(){return this.x+this.width/2}set right(e){this.x=e-this.width/2}get top(){return this.y-this.height/2}set top(e){this.y=e+this.height/2}get bottom(){return this.y+this.height/2}set bottom(e){this.y=e-this.height/2}get lx(){return 0}get ly(){return 0}get lleft(){return-this.width/2}get lright(){return this.width/2}get ltop(){return-this.height/2}get lbottom(){return this.height/2}isCollidingWith(e){return!(this.right<e.left||this.left>e.right||this.bottom<e.top||this.top>e.bottom)}color="rgba(0, 0, 255, 0.3)";draw(e){e.translate(this.x,this.y),e.rotate(this.scaleRotate),e.fillStyle=this.color,e.fillRect(-this.width/2,-this.height/2,this.width,this.height)}},pe=class extends I{duration;ticker;elapsed;finished;_resolve;promise;_timeoutId;constructor(e,n=null){super(),this.duration=e,this.ticker=n,this.elapsed=0,this.finished=!1,this._resolve=null,this.promise=new Promise(s=>this._resolve=s),this.update=this.update.bind(this),this.ticker&&this.ticker.on("tick",this.update)}update(e=0){this.finished||(this.elapsed+=e*1e3,this.elapsed>=this.duration&&this.finish())}finish(){this.finished||(this.finished=!0,this.emit("finish",void 0),this._resolve&&this._resolve(),this.ticker&&this.ticker.off("tick",this.update))}start(){return this.ticker||(this._timeoutId=setTimeout(()=>this.finish(),this.duration)),this}cancel(){this.finished||(this.finished=!0,!this.ticker&&this._timeoutId!=null&&clearTimeout(this._timeoutId),this.ticker&&this.ticker.off("tick",this.update))}then(e,n){return this.promise.then(e,n)}after(e,n){return this.promise.then(e,n)}},M=class r{constructor(e=0,n=0){this.x=e,this.y=n}x;y;toJSON(){return{x:this.x,y:this.y,vec2:!0}}static isVec2(e){return e&&typeof e=="object"&&"x"in e&&"y"in e&&e.vec2===!0}static fromSerialized(e){return this.isVec2(e)?new this(e.x,e.y):null}rotate(e){let n=Math.cos(e),s=Math.sin(e);return new r(this.x*n-this.y*s,this.x*s+this.y*n)}static from(e){return new r(Math.cos(e),Math.sin(e))}isEmpty(){return Math.abs(this.x)<.01&&Math.abs(this.y)<.01}get angle(){return Math.atan2(this.y,this.x)}angleTo(e){return Math.atan2(e.y-this.y,e.x-this.x)}get length(){return Math.hypot(this.x,this.y)}get lengthSquared(){return this.x*this.x+this.y*this.y}normalized(){let e=this.length;return e===0?new r(0,0):new r(this.x/e,this.y/e)}consume(e){let n=this.length;n<=e?(this.x=0,this.y=0):this.overwite(this.scale((n-e)/n))}project(e){return e.scale(this.dotNormalized(e))}reflect(e){let n=this.dot(e);return this.subtract(e.scale(2*n))}dotNormalized(e){let n=this.normalized(),s=e.normalized();return n.x*s.x+n.y*s.y}lengthSquaredTo(e){let n=this.x-e.x,s=this.y-e.y;return n*n+s*s}dot(e){return this.x*e.x+this.y*e.y}distanceTo(e){return Math.hypot(this.x-e.x,this.y-e.y)}distanceToCheap(e){let n=this.x-e.x,s=this.y-e.y;return n*n+s*s}directionTo(e){return new r(e.x-this.x,e.y-this.y).normalized()}add(e){return new r(this.x+e.x,this.y+e.y)}addRaw(e){return new r(this.x+e,this.y+e)}overwite(e){this.x=e.x,this.y=e.y}subtract(e){return new r(this.x-e.x,this.y-e.y)}scale(e){return new r(this.x*e,this.y*e)}toString(){return`Vector2(${this.x}, ${this.y})`}clone(){return new r(this.x,this.y)}};function De(){return typeof process<"u"&&process.release?.name==="node"?"node":typeof window<"u"||typeof self<"u"?"web":"unknown"}var Re=De(),U=Re==="node",k=Re==="web",X=class r{static unlock(){k&&this.audioCtx.state!=="running"&&this.audioCtx.resume()}static audioCtx=k?new AudioContext:null;static masterGain=k?this.audioCtx.createGain():null;static musicGain=k?this.audioCtx.createGain():null;static sfxGain=k?this.audioCtx.createGain():null;static{k&&(this.masterGain.gain.value=1,this.musicGain.gain.value=1,this.sfxGain.gain.value=1,this.sfxGain.connect(this.masterGain),this.musicGain.connect(this.masterGain),this.masterGain.connect(this.audioCtx.destination))}static get SFX_VOLUME(){return this.sfxGain.gain.value}static get MUSIC_VOLUME(){return this.musicGain.gain.value}static get VOLUME(){return this.masterGain.gain.value}static set SFX_VOLUME(e){this.sfxGain.gain.value=e}static set MUSIC_VOLUME(e){this.musicGain.gain.value=e}static set VOLUME(e){this.masterGain.gain.value=e}static noteToHz(e){return this.tuningFreq*Math.pow(2,(e-9)/12)}static tuningFreq=440;static audioBufferCache=new Map;static loops=new Map;static sfsx=new Map;static loopIdCounter=0;static CACHE_NAME="lia-audio-cache-v1";static async preLoad(e){if(this.audioBufferCache.has(e))return this.audioBufferCache.get(e);let n=r.CACHE_NAME,s,a;if(typeof caches<"u"&&(a=await caches.open(n),s=await a.match(e)),!s){if(s=await fetch(e),!s.ok)throw new Error(`Failed to fetch ${e}`);a&&await a.put(e,s.clone())}let l=await s.arrayBuffer(),d=await this.audioCtx.decodeAudioData(l);return this.audioBufferCache.set(e,d),d}static async getOnlyDownloadedCache(e){let n=r.CACHE_NAME;return await(await caches.open(n)).match(e)}static getCached(e){return this.audioBufferCache.get(e)||null}static async playSound(e,n=.2,s=1,a=!0){try{this.sfsx.has(e)&&this.sfsx.get(e).source.stop(),this.audioBufferCache.has(e)||await this.preLoad(e);let l=this.getCached(e);if(!l)return;let d=new O(l);d.buffer=l;let f=1-.12,h=1+.12;d.playbackRate=s??f+Math.random()*(h-f);let c=this.audioCtx.createGain();c.gain.value=n,d.tempGain=c,d.connect(c),c.connect(this.sfxGain),d.onended=()=>{d.disconnect(),c.disconnect()},d.start(),a&&this.sfsx.set(e,{source:d,gain:c})}catch(l){console.error(l)}}static async playLoop(e,n=1,{loopStart:s=0,loopEnd:a=null,exclusive:l=!0,skipMS:d=0}={}){if(l)for(let g of this.loops.keys())this.stopLoop(g);this.audioBufferCache.has(e)||await this.preLoad(e);let f=this.getCached(e);if(!f)return;let h=new O(f);h.buffer=f,h.loop=!0,typeof s=="number"&&(h.loopStart=s),typeof a=="number"&&(h.loopEnd=a);let c=this.audioCtx.createGain();c.gain.value=n,h.tempGain=c,h.playbackRate=1,h.onended=()=>{h.disconnect(),c.disconnect()},h.connect(c),c.connect(this.musicGain),h.start(0,d/1e3);let p=++this.loopIdCounter;return this.loops.set(p,{source:h,gain:c}),p}static stopLoop(e){let n=this.loops.get(e);n&&(n.source.stop(),n.source.notIndependent||(n.source.disconnect(),n.gain.disconnect()),this.loops.delete(e))}static async createLiaSource(e,{volume:n=1,speed:s=1,loop:a=!1,loopStart:l=0,loopEnd:d=null,isMusic:f=!1,gain:h=null}={}){try{this.audioBufferCache.has(e)||await this.preLoad(e);let c=this.getCached(e);if(!c)return null;let p=new O(c);p.loop=a,p.loopStart=l,p.loopEnd=typeof d=="number"?d:c.duration,p.playbackRate=s;let g=this.audioCtx.createGain();return g.gain.value=n,p.connect(g),p.tempGain=g,g.connect(h||(f?this.musicGain:this.sfxGain)),p.onended=()=>{p.disconnect(),g.disconnect()},p}catch(c){return console.error("Failed to create LiaAudioSrc:",c),null}}};var O=class{numberOfInputs;numberOfOutputs;constructor(e,n=X.audioCtx){this.context=n,this.buffer=e,this.source=null,this.startTime=0,this.pauseTime=0,this.playbackRate=1,this.isPlaying=!1,this.loop=!1,this.output=k?n.createGain():null,this.output.gain.value=1,this.channelCount=2,this.channelCountMode="max",this.channelInterpretation="speakers",this.numberOfInputs=0,this.numberOfOutputs=1,this.onended=null}channelCount;channelCountMode;channelInterpretation;onended;source;buffer;context;_createSource(){this.source&&(this.source.onended=null);let e=this.context.createBufferSource();return e.buffer=this.buffer,e.playbackRate.value=this.playbackRate,e.loop=this.loop,e.loopStart=this.loopStart,e.loopEnd=this.loopEnd>0?this.loopEnd:this.buffer.duration,e.connect(this.output),this.source=e,e.onended=()=>{this.source===e&&(this.isPlaying&&!this.loop&&(this.isPlaying=!1,this.pauseTime=0),typeof this.onended=="function"&&this.onended())},e}play({fadeIn:e=0,offset:n=null}={}){let s=n!==null?n:this.pauseTime;if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.source=this._createSource(),this.startTime=this.context.currentTime-s/this.playbackRate,this.source.start(0,s),e>0?(this.output.gain.setValueAtTime(0,this.context.currentTime),this.output.gain.linearRampToValueAtTime(1,this.context.currentTime+e)):this.output.gain.setValueAtTime(1,this.context.currentTime),this.isPlaying=!0}start(e=0,n=0,s){this.isPlaying||(this.source=this._createSource(),this.startTime=this.context.currentTime+e-n/this.playbackRate,s!==void 0?this.source.start(this.context.currentTime+e,n,s):this.source.start(this.context.currentTime+e,n),this.pauseTime=n,this.isPlaying=!0)}pause({fadeOut:e=0}={}){if(!this.isPlaying)return;let n=this.getElapsed()/1e3;if(this.loop&&this.loopEnd>this.loopStart){let s=this.loopEnd-this.loopStart;n=this.loopStart+(n-this.loopStart)%s}if(this.isPlaying=!1,e>0){let s=this.context.currentTime;this.output.gain.setValueAtTime(this.output.gain.value,s),this.output.gain.linearRampToValueAtTime(0,s+e),setTimeout(()=>{if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.pauseTime=n,this.output.gain.setValueAtTime(1,this.context.currentTime)},e*1e3)}else{if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.pauseTime=n}}getElapsed(){return this.isPlaying?(this.context.currentTime-this.startTime)*this.playbackRate*1e3:this.pauseTime*1e3}setSpeed(e){if(e<=0)throw new Error("Playback rate must be positive");let n=this.getElapsed()/1e3;this.playbackRate=e,this.isPlaying&&(this.pause(),this.pauseTime=n,this.play())}setLoop(e=!0){this.loop=e,this.source&&(this.source.loop=e)}loop;playbackRate;startTime;tempGain=null;connect(e,n=0,s=0){if("value"in e)this.output.connect(e,n);else return this.output.connect(e,n,s),e}disconnect(e,n,s){e===void 0?this.output.disconnect():this.output.disconnect(e,n,s)}output;stop(e=0){if(this.notIndependent)return this.pause();if(!this.source)return;let n=this.context.currentTime+e;this.source.stop(n),this.isPlaying=!1,this.notIndependent||(this.pauseTime=0)}pauseTime;isPlaying;notIndependent=!1;loopStart=0;loopEnd=0},Ge={osc:{enabled:!0,type:"sine",freq:440,detune:0},noise:{enabled:!1,level:.5},ampEnv:{attack:.005,decay:.1,sustain:0,release:.1,volume:.3},pitchEnv:{amount:0,decay:.2},filter:{enabled:!1,type:"lowpass",freq:1200,Q:1,envAmount:0,decay:.2},lfo:{enabled:!1,target:"freq",rate:8,depth:20},duration:.4},V=class r{constructor(e={}){this.ctx=X.audioCtx,this.cfg=structuredClone(Ge),Object.assign(this.cfg,e)}ctx;cfg;play(e=X.sfxGain){let n=this.ctx,s=n.currentTime,a=this.cfg,l=n.createGain();l.gain.setValueAtTime(1e-4,s);let d=a.ampEnv;l.gain.exponentialRampToValueAtTime(d.volume,s+d.attack),l.gain.exponentialRampToValueAtTime(Math.max(1e-4,d.sustain*d.volume),s+d.attack+d.decay),l.gain.exponentialRampToValueAtTime(1e-4,s+a.duration+d.release);let f=l,h;a.filter.enabled&&(h=n.createBiquadFilter(),h.type=a.filter.type,h.frequency.value=a.filter.freq,h.Q.value=a.filter.Q,h.connect(l),f=h);let c;if(a.osc.enabled){if(c=n.createOscillator(),c.type=a.osc.type,c.frequency.value=a.osc.freq,c.detune.value=a.osc.detune,a.pitchEnv.amount!==0){let i=Math.pow(2,a.pitchEnv.amount/12);c.frequency.exponentialRampToValueAtTime(a.osc.freq*i,s+a.pitchEnv.decay)}c.connect(f),c.start(s),c.stop(s+a.duration+d.release)}let p;if(a.noise.enabled){let i=n.sampleRate*a.duration,o=n.createBuffer(1,i,n.sampleRate),u=o.getChannelData(0);for(let y=0;y<i;y++)u[y]=(Math.random()*2-1)*a.noise.level;p=n.createBufferSource(),p.buffer=o,p.connect(f),p.start(s),p.stop(s+a.duration+d.release)}let g,x;a.lfo.enabled&&c&&(g=n.createOscillator(),g.frequency.value=a.lfo.rate,x=n.createGain(),x.gain.value=a.lfo.depth,g.connect(x),a.lfo.target==="freq"?x.connect(c.frequency):a.lfo.target==="gain"?x.connect(l.gain):a.lfo.target==="filter"&&h&&x.connect(h.frequency),g.start(s),g.stop(s+a.duration)),l.connect(e);let v=[c,p,g,x,h,l],t=s+a.duration+d.release;setTimeout(()=>{v.forEach(i=>i?.disconnect())},(t-n.currentTime)*1e3)}getConfig(){return structuredClone(this.cfg)}setConfig(e){return Object.assign(this.cfg,e),this}getKey(e){return this.cfg[e]}setKey(e,n){return Object.assign(this.cfg[e],n),this}setFreq(e){return this.cfg.osc.freq=e,this}setWave(e){return this.cfg.osc.type=e,this}setVolume(e){return this.cfg.ampEnv.volume=e,this}setAmpEnv(e,n,s,a){return Object.assign(this.cfg.ampEnv,{attack:e,decay:n,sustain:s,release:a}),this}setPitchEnv(e,n){return Object.assign(this.cfg.pitchEnv,{amount:e,decay:n}),this}setNoiseEnabled(e){return this.cfg.noise.enabled=e,this}setNoiseLevel(e){return this.cfg.noise.level=e,this}setFilterEnabled(e){return this.cfg.filter.enabled=e,this}setFilter(e,n,s){return Object.assign(this.cfg.filter,{type:e,freq:n,Q:s,enabled:!0}),this}setLFOEnabled(e){return this.cfg.lfo.enabled=e,this}setLFO(e,n,s){return Object.assign(this.cfg.lfo,{target:e,rate:n,depth:s,enabled:!0}),this}setDuration(e){return this.cfg.duration=e,this}clone(){return new r(structuredClone(this.cfg))}},mt=new V({osc:{enabled:!0,type:"square",freq:900,detune:0},ampEnv:{attack:.002,decay:.04,sustain:0,release:.02,volume:.15},duration:.05}),yt=new V({osc:{enabled:!0,type:"sine",freq:600,detune:0},ampEnv:{attack:.01,decay:.08,sustain:0,release:.04,volume:.12},duration:.1}),bt=new V({osc:{enabled:!0,type:"triangle",freq:500,detune:0},pitchEnv:{amount:12,decay:.15},ampEnv:{attack:.01,decay:.12,sustain:0,release:.05,volume:.25},duration:.18}),gt=new V({osc:{enabled:!0,type:"sawtooth",freq:1200,detune:0},pitchEnv:{amount:-24,decay:.3},ampEnv:{attack:.005,decay:.25,sustain:0,release:.05,volume:.3},duration:.35}),xt=new V({osc:{enabled:!0,type:"square",freq:180,detune:0},noise:{enabled:!0,level:.4},ampEnv:{attack:.002,decay:.15,sustain:0,release:.05,volume:.35},duration:.2});function me(r=12){let e=Date.now().toString(36),n=crypto.getRandomValues(new Uint8Array(4)),s=Array.from(n).map(a=>a.toString(36).padStart(2,"0")).join("");return(e+s).slice(0,r)}function ze(r){let e=!0;function n(){e&&(r(),requestAnimationFrame(n))}return requestAnimationFrame(n),{clear:()=>e=!1}}function He(){return U?!1:/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)}var vt=He();function Ue({width:r,height:e,updateHz:n="frames"}){return new G.KaylaGame(r,e,n==="frames"?1/0:n)}function $e(r){let e=new J(r);return new G.KaylaScene(e)}function Oe(r){return new G.KaylaRenderer(r)}function ne(r,e){if(typeof r!="function")throw new Error("Invalid Element Type.");let n=e??{};return n.key??=r.name+"_"+me(),{type:r,props:n}}var L;(s=>{function r(a,l){return!(a.right<l.left||a.left>l.right||a.bottom<l.top||a.top>l.bottom)}s.rawCollision=r;function e(a,l,d){let f=l*Math.PI/180,h=Math.cos(f),c=Math.sin(f),p=1/0;return h>0&&(p=Math.min(p,(d.right-a.x)/h)),h<0&&(p=Math.min(p,(d.left-a.x)/h)),c>0&&(p=Math.min(p,(d.bottom-a.y)/c)),c<0&&(p=Math.min(p,(d.top-a.y)/c)),M.from(l).scale(p)}s.getCurrToBound=e;function n(a){let{left:l,right:d,top:f,bottom:h,width:c,height:p,x:g=0,y:x=0}=a;if(c===null||p===null)throw new Error("width and height are required");let v,t;if(l!=null&&d!=null){if(Math.abs(d-l-c)>1e-6)throw new Error("left, right, and width mismatch");v=l}else g!=null?v=g-c/2:l!=null?v=l:d!=null?v=d-c:v=0;if(f!=null&&h!=null){if(Math.abs(h-f-p)>1e-6)throw new Error("top, bottom, and height mismatch");t=f}else x!=null?t=x-p/2:f!=null?t=f:h!=null?t=h-p:t=0;return{left:v,right:v+c,top:t,bottom:t+p,width:c,height:p,x:v+c/2,y:t+p/2}}s.createRawRect=n})(L||={});var G;(x=>{class r extends Z{#e;#t;constructor(t,i,o){super(t,i,o),this.#e=new Set,this.#t=!1}delay(t){return this.ticker.createTimeout(t)}get started(){return this.#t}start(){if(!this.#t){for(let t of this.#e)t.start();this.#t=!0,super.start()}}stop(){if(this.#t){for(let t of this.#e)t.stop();this.#t=!1,super.stop()}}addRenderer(t){this.#e.has(t)||(this.#e.add(t),this.#t&&t.start(),t.game=this)}get mainRenderer(){return[...this.#e].at(0)}getRenderers(){return[...this.#e]}deleteRenderer(t){this.#e.has(t)&&(this.#e.delete(t),this.#t&&t.stop(),delete t.game)}}x.KaylaGame=r;class e extends Q{game;pointerX;pointerY;pointerEvents;onPointerDown;onPointerUp;onPointerCancel;onPointerMove;constructor(t){super(t),this.useDraw=this.useDraw.bind(this),this.on("draw",i=>{if(this.game)for(let o of this.game.scenes.values())o.handleDraw(i)}),this.pointerX=0,this.pointerY=0,this.pointerEvents=new I,this.pointerPosUpdater=this.pointerPosUpdater.bind(this),this.onPointerDown=i=>this.onPointerAll(i,"down"),this.onPointerUp=i=>this.onPointerAll(i,"up"),this.onPointerCancel=i=>this.onPointerAll(i,"cancel"),this.onPointerMove=i=>this.onPointerAll(i,"move")}pointerPosUpdater(t){this.pointerX=t.clientX,this.pointerY=t.clientY}onPointerAll(t,i){this.pointerPosUpdater(t);let o=e.getClickType(t);if(o!=="invalid"||i==="move"||i==="cancel"){t.preventDefault();let u=this.getMousePos();this.pointerEvents.emit("action",u,o,i)}}static getClickType(t){switch(t.button){case 0:return"left";case 1:return"middle";case 2:return"right";default:return"invalid"}}listenPointerUpdates(){this.canvas.addEventListener("pointermove",this.pointerPosUpdater),this.canvas.addEventListener("pointerdown",this.onPointerDown),this.canvas.addEventListener("pointerup",this.onPointerUp),this.canvas.addEventListener("pointercancel",this.onPointerCancel),this.canvas.addEventListener("pointermove",this.onPointerMove)}unlistenPointerUpdates(){this.canvas.removeEventListener("pointermove",this.pointerPosUpdater),this.canvas.removeEventListener("pointerdown",this.onPointerDown),this.canvas.removeEventListener("pointerup",this.onPointerUp),this.canvas.removeEventListener("pointermove",this.onPointerMove)}pointerPosToWorldPos(t,i){let o=this.canvas.getBoundingClientRect(),u=(t-o.left)/o.width,y=(i-o.top)/o.height,b=u*this.viewportWidth*this.cameraWidth/o.width,C=y*this.viewportHeight*this.cameraHeight/o.height;return new M(b,C)}getMousePos(){return this.pointerPosToWorldPos(this.pointerX,this.pointerY)}useDraw(t){let i=o=>{t(o,new s)};return this.on("draw",i),()=>{this.off("draw",i)}}attachTo(t){t.addRenderer(this),this.game=t}detach(){this.game&&this.game.deleteRenderer(this)}}x.KaylaRenderer=e;class n{current;saves;constructor(){this.saves=[]}useTick(t){if(!this.current)throw new Error("Hook 'useTick' must be executed in the top level scope of a component.");this.current.onTick[this.current.useStepCallIndex]=t,this.current.useStepCallIndex++}usePaint(t){if(!this.current)throw new Error("Hook 'usePaint' must be executed in the top level scope of a component.");this.current.onPaint[this.current.useDrawCallIndex]=t,this.current.useDrawCallIndex++}useEntity(){if(!this.current)throw new Error("Hook 'useEntity' must be executed in the top level scope of a component.");return ye(be)}useSelf(t){if(!this.current)throw new Error("Hook 'useSelf' must be executed in the top level scope of a component.");let i=ye(null);return(i.current===null||i.current===void 0)&&(i.current=t()),i.current}useInitialization(t){if(!this.current)throw new Error("Hook 'useInitialization' must be executed in the top level scope of a component.");let i=this.current;i.onInits[this.current.useInitCallIndex]=t,i.useInitCallIndex++}useRect(){if(!this.current)throw new Error("Hook 'useRect' must be executed in the top level scope of a component.");return D(()=>new x.KaylaInternalRect(this.current))}useFiber(){if(!this.current)throw new Error("Hook 'useFiber' must be executed in the top level scope of a component.");return D(()=>this.current)}useFiberControl(){if(!this.current)throw new Error("Hook 'useFiberControl' must be executed in the top level scope of a component.");let t=this.current;return D(()=>({refresh:()=>t.refresh(),get childrenCount(){return t.lastChildren.length},setMaxChildren:i=>{t.setMaxChildren(i)},getMaxChildren:()=>t.getMaxChildren(),get maxSafeChildren(){return t.maxSafeChildren},get key(){return t.key},get getChildrenEntities(){return t.getChildrenEntities.bind(t)},get getEntityChain(){return t.getEntityChain.bind(t)},get getFiberChain(){return t.getFiberChain.bind(t)}}))}useCurrentTicker(){if(!this.current)throw new Error("Hook 'useCurrentTicker' must be executed in the top level scope of a component.");return this.current.getAttachedGame().ticker}useCurrentRenderer(){if(!this.current)throw new Error("Hook 'useCurrentRenderer' must be executed in the top level scope of a component.");return this.current.getAttachedGame().mainRenderer}useCurrentGame(){if(!this.current)throw new Error("Hook 'useCurrentGame' must be executed in the top level scope of a component.");return this.current.getAttachedGame()}useCurrentScene(){if(!this.current)throw new Error("Hook 'useCurrentScene' must be executed in the top level scope of a component.");return this.current.scene}useState(t,{alwaysRecall:i=!1}={}){if(!this.current)throw new Error("Hook 'useState' must be executed in the top level scope of a component.");let u=this.current.state[this.current.useStateCallIndex]??new a(this.current,t,{alwaysRecall:i});return this.current.state[this.current.useStateCallIndex]=u,this.current.useStateCallIndex++,u}useShouldRefresh(t){let i=this.current;if(!i)throw new Error("useShouldRefresh must be called inside a component");i.watchedDeps&&console.warn("useShouldRefresh called multiple times \u2014 using the last call"),i.watchedDeps=t}useRef(t){if(!this.current)throw new Error("Hook 'useRef' must be executed in the top level scope of a component.");let o=this.current.refs[this.current.useRefCallIndex]??d(t??null);return this.current.refs[this.current.useRefCallIndex]=o,this.current.useRefCallIndex++,o}useEffect(t){if(!this.current)throw new Error("Hook 'useEffect' must be executed in the top level scope of a component.");this.current.onEffect[this.current.useEffectCallIndex]=t,this.current.useEffectCallIndex++}useViewportEffect(t){if(!this.current)throw new Error("Hook 'useViewport' must be executed in the top level scope of a component.");this.current.onViewportEffect[this.current.useViewCallIndex]=t,this.current.useViewCallIndex++}useExports(t,i){if(!this.current)throw new Error("Hook 'useExports' must be executed in the top level scope of a component.");this.current.onExport=i}useGlobalPointer(t,i){if(!this.current)throw new Error("Hook 'useGlobalPointer/useGlobalClick' must be executed in the top level scope of a component.");i??={},this.current.onGlobalPointer[this.current.useGlobalClickCallIndex]={handler:t,config:i},this.current.useGlobalClickCallIndex++}usePointer(t,i){if(!this.current)throw new Error("Hook 'usePointer/useClick' must be executed in the top level scope of a component.");i??={};let o=this.current;Te((u,y,b)=>{let C=o.entity;if(!C)return;let E=C.getRawRect(),z=L.createRawRect({x:u.x,y:u.y,width:3,height:3});L.rawCollision(E,z)&&t(u,y,b)},i)}useContext(t){if(!this.current)throw new Error("Hook 'useContext' must be executed in the top level scope of a component.");return this.current.findContextValueFromInst(t)}save(){this.saves.push({current:this.current})}restore(){let t=this.saves.pop();if(!t)throw new Error("Cannot restore without saving.");this.current=t.current}logLevel="warn";logger={debug:(...t)=>{this.logLevel==="debug"&&console.debug(...t)},info:(...t)=>{["info","warn","debug"].includes(this.logLevel)&&console.info(...t)},warn:(...t)=>{["warn","debug"].includes(this.logLevel)&&console.warn(...t)},error:(...t)=>console.error(...t),withFiber:(t,i,o,...u)=>{let y=t?.fc?.name||"anonymous",b=t?.key?` key=${t.key}`:"";this.logger[i](`${o} <${y}${b}>`,...u)}}}x.GlobalKayla=n;class s{preventDefault(){this.#e=!0}#e=!1;isPrevented(){return this.#e}}x.KaylaEvent=s;class a{#e;#t;#n;alwaysRecall;constructor(t,i,{alwaysRecall:o=!1}={}){this.#t=t,this.#e=i??void 0,this.#n=Date.now(),this.alwaysRecall=o}get(){return this.#e}*[Symbol.iterator](){throw new Error(`Hey! KaylaState is NOT an array / iterable like useState in React.
|
|
2
2
|
You probably wrote: const [value, setValue] = useState(...)
|
|
3
3
|
|
|
4
4
|
\u2192 In Kayla write: const value = useState(...);
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
export { Fragment, jsx, jsxDEV, jsxs } from './jsx-runtime.cjs';
|
|
2
|
-
import './kayla-internals-
|
|
3
|
-
import './lea-
|
|
2
|
+
import './kayla-internals-jEHH2NbT.cjs';
|
|
3
|
+
import './lea-BaZkxo5L.cjs';
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
export { Fragment, jsx, jsxDEV, jsxs } from './jsx-runtime.js';
|
|
2
|
-
import './kayla-internals-
|
|
3
|
-
import './lea-
|
|
2
|
+
import './kayla-internals-BIKaIho5.js';
|
|
3
|
+
import './lea-BaZkxo5L.js';
|
package/dist/jsx-dev-runtime.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var Pe=Object.defineProperty;var Se=(i,e)=>{for(var n in e)Pe(i,n,{get:e[n],enumerable:!0})};var Ce={};Se(Ce,{JSX:()=>Te,KMatrix2D:()=>be,KaylaContext:()=>te,KaylaFragment:()=>we,KaylaInternals:()=>G,KaylaRect:()=>L,Layer:()=>tt,createContext:()=>Ge,createElement:()=>ne,createGame:()=>_e,createReassignableObject:()=>Je,createRenderer:()=>De,createScene:()=>Ve,createUseHook:()=>et,self:()=>ye,setLogLevel:()=>Ze,useClick:()=>Oe,useContext:()=>Ye,useCurrentGame:()=>Be,useCurrentRenderer:()=>We,useCurrentScene:()=>ke,useCurrentTicker:()=>je,useDisposableRef:()=>Qe,useEffect:()=>re,useEntity:()=>qe,useExports:()=>oe,useFiber:()=>xe,useFiberControl:()=>ge,useGlobalClick:()=>Re,useGlobalPointer:()=>$e,useInitialization:()=>ie,useNextStack:()=>ve,usePaint:()=>ae,usePointer:()=>Ne,useRect:()=>se,useRef:()=>me,useSelf:()=>D,useShouldRefresh:()=>He,useState:()=>ze,useTick:()=>Xe,useViewportEffect:()=>Ue});var I=class{#e=new Map;constructor(){this.#e=new Map}on(e,n){let s=this.#e.get(e)||[];return s.push(n),this.#e.set(e,s),this}once(e,n){let s=(...a)=>{this.off(e,s),n(...a)};return this.on(e,s),this}off(e,n){let s=this.#e.get(e);if(!s)return this;let a=s.indexOf(n);return a>=0&&s.splice(a,1),this}emit(e,...n){let s=this.#e.get(e);if(!s||s.length===0){if(e==="error")throw n[0];return!1}return s.slice().forEach(a=>a(...n)),!0}removeAllListeners(e){return e?this.#e.delete(e):this.#e.clear(),this}listenerCount(e){return this.#e.get(e)?.length??0}},Q=class extends I{canvas;ctx;running;_rafId;_fps;_frameCount;_fpsTimer;_lastFrameTime;constructor(e,{viewportWidth:n,viewportHeight:s,cameraWidth:a,cameraHeight:l}={}){if(!k)throw new Error("Web-Only");super(),this.canvas=e,this.ctx=e.getContext("2d"),this.automatic=!0,this.#e=n??e.width,this.#t=s??e.height,this.#n=a??e.width,this.#r=l??e.height,this.running=!1,this._rafId=null,this._loop=this._loop.bind(this),this.updateCanvasResolution(),this._fps=60,this._frameCount=0,this._fpsTimer=0}automatic;retransform(){this.ctx.setTransform(1,0,0,1,0,0);let e=this.#n/this.#e,n=this.#r/this.#t;this.ctx.translate(this.#n/2,this.#r/2),this.ctx.scale(e,n),this.ctx.translate(-this.#e/2,-this.#t/2)}#e=0;#t=0;#n=0;#r=0;get viewportWidth(){return this.#e}set viewportWidth(e){this.#e=e,this.retransform(),this.emitViewportUpdate()}get width(){return this.#e}get height(){return this.#t}get centerX(){return this.#e/2}get centerY(){return this.#t/2}get left(){return 0}get top(){return 0}get right(){return this.#e}get bottom(){return this.#t}get viewportHeight(){return this.#t}set viewportHeight(e){this.#t=e,this.retransform(),this.emitViewportUpdate()}get cameraWidth(){return this.#n}set cameraWidth(e){this.#n=e,this.updateCanvasResolution(),this.retransform()}get cameraHeight(){return this.#r}set cameraHeight(e){this.#r=e,this.updateCanvasResolution(),this.retransform()}updateCanvasResolution(){this.canvas.width=this.#n,this.canvas.height=this.#r}emitViewportUpdate(){this.emit("viewport_update",{width:this.viewportWidth,height:this.viewportHeight})}applyTransform(){this.retransform()}get FPS(){return this._fps}_loop(){this.automatic&&this.update(),this._rafId=requestAnimationFrame(this._loop)}update(){if(!this.running||!k)return;let e=performance.now(),n=(e-(this._lastFrameTime??e))/1e3;this._lastFrameTime=e,this._frameCount++,this._fpsTimer+=n,this._fpsTimer>=1&&(this._fps=Math.round(this._frameCount/this._fpsTimer),this._frameCount=0,this._fpsTimer=0),this.ctx.clearRect(0,0,this.#n,this.#r),this.emit("draw",this.ctx)}start(){if(!this.running){if(!k||typeof globalThis.requestAnimationFrame>"u")throw new Error("Raf is not supported");this.running=!0,this._rafId=requestAnimationFrame(this._loop)}}stop(){if(!k||typeof globalThis.requestAnimationFrame>"u")throw new Error("Raf is not supported");this.running=!1,this._rafId!==null&&(cancelAnimationFrame(this._rafId),this._rafId=null)}},ce=class extends I{setNow(e){this.#e=e}#e=0;__intervalId=null;__lastTime=0;constructor(e=16){super(),this.#t=e,this.speedHackDT=1}speedHackDT;get isRaf(){return this.tickInterval===1/0}#t=15;get tickInterval(){return this.#t}set tickInterval(e){this.#t=e,this.__intervalId&&(this.stop(),this.start())}now(){return this.#e}__tick(){let e=performance.now(),n=(e-this.__lastTime)/1e3*this.speedHackDT;this.__lastTime=e,!(k&&typeof this.__intervalId=="function"&&document.hidden)&&(this.#e+=n*1e3,this.emit("tick",n))}createTimeout(e){return new fe(e,this)}createTween(e,n=()=>{}){let s=new de(e),a=(l=0)=>{if(s.finished){this.off("tick",a);return}s.update(l)};return s.on("finish",()=>{this.off("tick",a)}),s.on("delta",l=>{n(l)}),this.on("tick",a),s}start(){this.__intervalId===null&&(this.__lastTime=performance.now(),this.__intervalId=k&&!isFinite(this.tickInterval)?Ae(()=>this.__tick()).clear:setInterval(()=>this.__tick(),this.tickInterval))}stop(){this.__intervalId!==null&&(typeof this.__intervalId=="function"?this.__intervalId():clearInterval(this.__intervalId)),this.__intervalId=null}getSineMod(e,n=0){return .5+.5*Math.sin((this.now()%e/e+n)*2*Math.PI)}},Ie;(t=>{function i(r){return r===!0?1:0}t.booleanExport=i;function e(r){return r===0?!1:r===1}t.booleanImport=e;function n(r){return`${r.x}|${r.y}`}t.vec2Export=n;function s(r){let[o,u]=r.split("|"),y=parseFloat(o),b=parseFloat(u);if(isNaN(y)||isNaN(b))throw new Error(`Invalid Vector2 string: ${r}`);return new M(y,b)}t.vec2Import=s,t.booleanMap={mapExport:i,mapImport:e};function l(r){return o=>Number(o.toFixed(r))}t.createRounder=l;function d(r=10){return{mapExport(o){return Math.round(o/r)},mapImport(o){return o*r}}}t.createLowPrecision=d;function f(r){return Math.round(r)}t.lightWeightRounder=f;function h(r=100){return{mapExport(o){return Math.round(o*r)},mapImport(o){return o/r}}}t.createPercent=h;function c(r){let o=new Map(Object.entries(r));return{mapExport:u=>o.get(u)??null,mapImport:u=>Array.from(o.entries()).find(([y,b])=>b===u)?.[0]??null}}t.createLookup=c;function p(r){let o=r*(180/Math.PI);return Math.round((o%360+360)%360)}t.radToDeg=p;function g(r){return r*(Math.PI/180)}t.degToRad=g,t.angleRadToDeg={mapExport:p,mapImport:g};function v(r=10){let o=d(r);return{mapExport(u){return o.mapExport(p(u))},mapImport(u){return o.mapImport(g(u))}}}t.createLowPrecisionRadToDeg=v})(Ie||={});var N=class i extends I{name="";scaleRotate=0;scale=1;constructor(e,n=0,s=0){super(),this.autoTranslate=!1,this.name=e,this.z=0,this.___pos=new M(n,s),this.nonSerializableProperties=[],this.nonSerializableProperties.push("___pos","autoTranslate","arraySerializeMap"),this.forceSerializableProperties=[],this.forceSerializableProperties.push("x","y")}arraySerializeMap;autoTranslate;z;___pos;nonSerializableProperties;forceSerializableProperties;get pos(){return this.___pos}get x(){return this.pos.x}get y(){return this.pos.y}set x(e){this.pos.x=e}set y(e){this.pos.y=e}handleUpdate(e){if(this.update)try{this.emit("update",e),this.update(e)}catch(n){this.emit("error",n)}}handleDraw(e){if(!(U||!this.draw)){e.save(),this.autoTranslate&&e.translate(this.x,this.y);try{this.emit("draw",e),this.draw(e)}catch(n){this.emit("error",n)}e.restore()}}serialize(){if(Array.isArray(this.arraySerializeMap))return this.arraySerializeMap.map(([a,{mapExport:l}])=>{let d=Reflect.get(this,a);return l?l(d):d});let e=["_events","_eventsCount","_maxListeners","nonSerializableProperties","forceSerializableProperties"],n=[...Reflect.ownKeys(this),...this.forceSerializableProperties].filter(a=>!this.nonSerializableProperties.includes(a)&&!e.includes(a.toString())),s=Object.fromEntries(n.map(a=>{let l=Reflect.get(this,a);if(U&&typeof l=="number"){let d=l.toString().split("."),h=(d[1]?d[1].length:0)>2?Number(l.toFixed(2)):l;return[a,h]}return[a,l]}));return JSON.parse(JSON.stringify(s))}toLocal(e){return e.subtract(this.pos)}toWorld(e){return e.add(this.pos)}deserializeArray(e){return i.deserializeArray(this.arraySerializeMap,e)}static deserializeArray(e,n){if(!e||!Array.isArray(n))return n;let s={};for(let a=0;a<n.length;a++){let l=e[a];if(!l)break;let[d,{mapImport:f}]=l,h=n[a];if(f&&(h=f(h)),typeof d!="string")break;try{Reflect.set(s,d,h)}catch(c){console.error(c)}}return s}},J=class extends I{name="";entities=new Map;paused=!0;constructor(e){super(),this.name=e}handleUpdate(e){if(!this.paused){this.emit("update",e);for(let n of this.entities.values())n.handleUpdate(e)}}handleDraw(e){if(!U&&!this.paused){this.emit("draw",e);for(let n of[...this.entities.values()].sort((s,a)=>s.z-a.z))n.handleDraw(e)}}addEntity(e){if(!(e instanceof N))throw new Error("invalid entity");if(!e.name)throw new Error("Entity must have a name.");this.entities.set(e.name,e)}removeEntity(e){if(!(e instanceof N))throw new Error("invalid entity");this.entities.delete(e.name)}getEntity(e){return this.entities.get(e)}},Z=class{scenes;ticker;get centerX(){return this.width/2}get centerY(){return this.height/2}get left(){return 0}get top(){return 0}get right(){return this.width}get bottom(){return this.height}width;height;constructor(e,n,s=16){this.ticker=new ce(s),this.scenes=new Map,this.width=e,this.height=n,this.ticker.on("tick",a=>{for(let l of this.scenes.values())l.paused||l.handleUpdate(a)})}addScene(e){if(!e.name)throw new Error("Scene must have a name.");e.paused=!1,this.scenes.set(e.name,e)}removeScene(e){e&&(e.paused=!0),this.scenes.delete(e.name)}now(){return this.ticker.now()}start(){this.ticker.start()}stop(){this.ticker.stop()}},P={lerp(i,e,n){return i+(e-i)*n},clamp(i,e,n){return Math.min(n,Math.max(e,i))},clamp01(i){return Math.min(1,Math.max(0,i))},easeLinear(i){return i},easeInQuad(i){return i*i},easeOutQuad(i){return 1-(1-i)*(1-i)},easeInOutQuad(i){return i<.5?2*i*i:1-Math.pow(-2*i+2,2)/2},easeInSine(i){return 1-Math.cos(i*Math.PI/2)},easeOutSine(i){return Math.sin(i*Math.PI/2)},easeInOutSine(i){return-(Math.cos(Math.PI*i)-1)/2},easeInExpo(i){return i===0?0:Math.pow(2,10*i-10)},easeOutExpo(i){return i===1?1:1-Math.pow(2,-10*i)},easeInOutExpo(i){return i===0?0:i===1?1:i<.5?Math.pow(2,20*i-10)/2:(2-Math.pow(2,-20*i+10))/2},smoothstep(i){return i=P.clamp(i,0,1),i*i*(3-2*i)},randomLerp(i,e){return P.lerp(i,e,Math.random())},randomInt(i,e){return Math.floor(Math.random()*(e-i+1))+i},randomArrayValue(i){return i[P.randomInt(0,i.length-1)]},createBezier(i,e,n,s){function a(f,h,c,p,g){let x=1-f;return x*x*x*h+3*x*x*f*c+3*x*f*f*p+f*f*f*g}function l(f,h,c,p,g){let x=1-f;return 3*x*x*(c-h)+6*x*f*(p-c)+3*f*f*(g-p)}function d(f){let h=f;for(let c=0;c<6;c++){let p=a(h,0,i,n,1),g=l(h,0,i,n,1);if(g===0)break;h-=(p-f)/g}return P.clamp(h,0,1)}return function(h){h=P.clamp(h,0,1);let c=d(h);return a(c,0,e,s,1)}},lengthSquared(...i){return i.reduce((e,n)=>e+n*n,0)},normalizeRad(i){let e=2*Math.PI;return i=i%e,i<0&&(i+=e),i},angleInvertY(i){return P.normalizeRad(-i)},degToRadFlipY(i){return P.angleInvertY(i*Math.PI/180)},minimalAngularDirection(i,e){i=P.normalizeRad(i),e=P.normalizeRad(e);let n=P.normalizeRad(e-i),s=P.normalizeRad(i-e);return n<=s?1:-1}},de=class extends I{constructor({delta:e,ms:n,easing:s}){super(),this.delta=e,this.duration=n,this.elapsed=0,this.easing=s??(a=>a),this.lastValue=0,this.finished=!1}delta;duration;elapsed;lastValue;finished;easing;update(e){this.elapsed+=e*1e3;let n=P.clamp(this.elapsed/this.duration,0,1),s=this.easing(n),a=this.delta*s,l=a-this.lastValue;this.lastValue=a,this.emit("delta",l),n>=1&&(this.finished=!0,this.emit("finish",void 0))}},ee=class extends N{constructor(e,n=0,s=0,a=50,l=50){super(e,n,s),this.width=a,this.height=l}width;height;get left(){return this.x-this.width/2}set left(e){this.x=e+this.width/2}get right(){return this.x+this.width/2}set right(e){this.x=e-this.width/2}get top(){return this.y-this.height/2}set top(e){this.y=e+this.height/2}get bottom(){return this.y+this.height/2}set bottom(e){this.y=e-this.height/2}get lx(){return 0}get ly(){return 0}get lleft(){return-this.width/2}get lright(){return this.width/2}get ltop(){return-this.height/2}get lbottom(){return this.height/2}isCollidingWith(e){return!(this.right<e.left||this.left>e.right||this.bottom<e.top||this.top>e.bottom)}color="rgba(0, 0, 255, 0.3)";draw(e){e.translate(this.x,this.y),e.rotate(this.scaleRotate),e.fillStyle=this.color,e.fillRect(-this.width/2,-this.height/2,this.width,this.height)}},fe=class extends I{duration;ticker;elapsed;finished;_resolve;promise;_timeoutId;constructor(e,n=null){super(),this.duration=e,this.ticker=n,this.elapsed=0,this.finished=!1,this._resolve=null,this.promise=new Promise(s=>this._resolve=s),this.update=this.update.bind(this),this.ticker&&this.ticker.on("tick",this.update)}update(e=0){this.finished||(this.elapsed+=e*1e3,this.elapsed>=this.duration&&this.finish())}finish(){this.finished||(this.finished=!0,this.emit("finish",void 0),this._resolve&&this._resolve(),this.ticker&&this.ticker.off("tick",this.update))}start(){return this.ticker||(this._timeoutId=setTimeout(()=>this.finish(),this.duration)),this}cancel(){this.finished||(this.finished=!0,!this.ticker&&this._timeoutId!=null&&clearTimeout(this._timeoutId),this.ticker&&this.ticker.off("tick",this.update))}then(e,n){return this.promise.then(e,n)}after(e,n){return this.promise.then(e,n)}},M=class i{constructor(e=0,n=0){this.x=e,this.y=n}x;y;toJSON(){return{x:this.x,y:this.y,vec2:!0}}static isVec2(e){return e&&typeof e=="object"&&"x"in e&&"y"in e&&e.vec2===!0}static fromSerialized(e){return this.isVec2(e)?new this(e.x,e.y):null}rotate(e){let n=Math.cos(e),s=Math.sin(e);return new i(this.x*n-this.y*s,this.x*s+this.y*n)}static from(e){return new i(Math.cos(e),Math.sin(e))}isEmpty(){return Math.abs(this.x)<.01&&Math.abs(this.y)<.01}get angle(){return Math.atan2(this.y,this.x)}angleTo(e){return Math.atan2(e.y-this.y,e.x-this.x)}get length(){return Math.hypot(this.x,this.y)}get lengthSquared(){return this.x*this.x+this.y*this.y}normalized(){let e=this.length;return e===0?new i(0,0):new i(this.x/e,this.y/e)}consume(e){let n=this.length;n<=e?(this.x=0,this.y=0):this.overwite(this.scale((n-e)/n))}project(e){return e.scale(this.dotNormalized(e))}reflect(e){let n=this.dot(e);return this.subtract(e.scale(2*n))}dotNormalized(e){let n=this.normalized(),s=e.normalized();return n.x*s.x+n.y*s.y}lengthSquaredTo(e){let n=this.x-e.x,s=this.y-e.y;return n*n+s*s}dot(e){return this.x*e.x+this.y*e.y}distanceTo(e){return Math.hypot(this.x-e.x,this.y-e.y)}distanceToCheap(e){let n=this.x-e.x,s=this.y-e.y;return n*n+s*s}directionTo(e){return new i(e.x-this.x,e.y-this.y).normalized()}add(e){return new i(this.x+e.x,this.y+e.y)}addRaw(e){return new i(this.x+e,this.y+e)}overwite(e){this.x=e.x,this.y=e.y}subtract(e){return new i(this.x-e.x,this.y-e.y)}scale(e){return new i(this.x*e,this.y*e)}toString(){return`Vector2(${this.x}, ${this.y})`}clone(){return new i(this.x,this.y)}};function Fe(){return typeof process<"u"&&process.release?.name==="node"?"node":typeof window<"u"||typeof self<"u"?"web":"unknown"}var Ee=Fe(),U=Ee==="node",k=Ee==="web",X=class i{static unlock(){k&&this.audioCtx.state!=="running"&&this.audioCtx.resume()}static audioCtx=k?new AudioContext:null;static masterGain=k?this.audioCtx.createGain():null;static musicGain=k?this.audioCtx.createGain():null;static sfxGain=k?this.audioCtx.createGain():null;static{k&&(this.masterGain.gain.value=1,this.musicGain.gain.value=1,this.sfxGain.gain.value=1,this.sfxGain.connect(this.masterGain),this.musicGain.connect(this.masterGain),this.masterGain.connect(this.audioCtx.destination))}static get SFX_VOLUME(){return this.sfxGain.gain.value}static get MUSIC_VOLUME(){return this.musicGain.gain.value}static get VOLUME(){return this.masterGain.gain.value}static set SFX_VOLUME(e){this.sfxGain.gain.value=e}static set MUSIC_VOLUME(e){this.musicGain.gain.value=e}static set VOLUME(e){this.masterGain.gain.value=e}static noteToHz(e){return this.tuningFreq*Math.pow(2,(e-9)/12)}static tuningFreq=440;static audioBufferCache=new Map;static loops=new Map;static sfsx=new Map;static loopIdCounter=0;static CACHE_NAME="lia-audio-cache-v1";static async preLoad(e){if(this.audioBufferCache.has(e))return this.audioBufferCache.get(e);let n=i.CACHE_NAME,s,a;if(typeof caches<"u"&&(a=await caches.open(n),s=await a.match(e)),!s){if(s=await fetch(e),!s.ok)throw new Error(`Failed to fetch ${e}`);a&&await a.put(e,s.clone())}let l=await s.arrayBuffer(),d=await this.audioCtx.decodeAudioData(l);return this.audioBufferCache.set(e,d),d}static async getOnlyDownloadedCache(e){let n=i.CACHE_NAME;return await(await caches.open(n)).match(e)}static getCached(e){return this.audioBufferCache.get(e)||null}static async playSound(e,n=.2,s=1,a=!0){try{this.sfsx.has(e)&&this.sfsx.get(e).source.stop(),this.audioBufferCache.has(e)||await this.preLoad(e);let l=this.getCached(e);if(!l)return;let d=new O(l);d.buffer=l;let f=1-.12,h=1+.12;d.playbackRate=s??f+Math.random()*(h-f);let c=this.audioCtx.createGain();c.gain.value=n,d.tempGain=c,d.connect(c),c.connect(this.sfxGain),d.onended=()=>{d.disconnect(),c.disconnect()},d.start(),a&&this.sfsx.set(e,{source:d,gain:c})}catch(l){console.error(l)}}static async playLoop(e,n=1,{loopStart:s=0,loopEnd:a=null,exclusive:l=!0,skipMS:d=0}={}){if(l)for(let g of this.loops.keys())this.stopLoop(g);this.audioBufferCache.has(e)||await this.preLoad(e);let f=this.getCached(e);if(!f)return;let h=new O(f);h.buffer=f,h.loop=!0,typeof s=="number"&&(h.loopStart=s),typeof a=="number"&&(h.loopEnd=a);let c=this.audioCtx.createGain();c.gain.value=n,h.tempGain=c,h.playbackRate=1,h.onended=()=>{h.disconnect(),c.disconnect()},h.connect(c),c.connect(this.musicGain),h.start(0,d/1e3);let p=++this.loopIdCounter;return this.loops.set(p,{source:h,gain:c}),p}static stopLoop(e){let n=this.loops.get(e);n&&(n.source.stop(),n.source.notIndependent||(n.source.disconnect(),n.gain.disconnect()),this.loops.delete(e))}static async createLiaSource(e,{volume:n=1,speed:s=1,loop:a=!1,loopStart:l=0,loopEnd:d=null,isMusic:f=!1,gain:h=null}={}){try{this.audioBufferCache.has(e)||await this.preLoad(e);let c=this.getCached(e);if(!c)return null;let p=new O(c);p.loop=a,p.loopStart=l,p.loopEnd=typeof d=="number"?d:c.duration,p.playbackRate=s;let g=this.audioCtx.createGain();return g.gain.value=n,p.connect(g),p.tempGain=g,g.connect(h||(f?this.musicGain:this.sfxGain)),p.onended=()=>{p.disconnect(),g.disconnect()},p}catch(c){return console.error("Failed to create LiaAudioSrc:",c),null}}};var O=class{numberOfInputs;numberOfOutputs;constructor(e,n=X.audioCtx){this.context=n,this.buffer=e,this.source=null,this.startTime=0,this.pauseTime=0,this.playbackRate=1,this.isPlaying=!1,this.loop=!1,this.output=k?n.createGain():null,this.output.gain.value=1,this.channelCount=2,this.channelCountMode="max",this.channelInterpretation="speakers",this.numberOfInputs=0,this.numberOfOutputs=1,this.onended=null}channelCount;channelCountMode;channelInterpretation;onended;source;buffer;context;_createSource(){this.source&&(this.source.onended=null);let e=this.context.createBufferSource();return e.buffer=this.buffer,e.playbackRate.value=this.playbackRate,e.loop=this.loop,e.loopStart=this.loopStart,e.loopEnd=this.loopEnd>0?this.loopEnd:this.buffer.duration,e.connect(this.output),this.source=e,e.onended=()=>{this.source===e&&(this.isPlaying&&!this.loop&&(this.isPlaying=!1,this.pauseTime=0),typeof this.onended=="function"&&this.onended())},e}play({fadeIn:e=0,offset:n=null}={}){let s=n!==null?n:this.pauseTime;if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.source=this._createSource(),this.startTime=this.context.currentTime-s/this.playbackRate,this.source.start(0,s),e>0?(this.output.gain.setValueAtTime(0,this.context.currentTime),this.output.gain.linearRampToValueAtTime(1,this.context.currentTime+e)):this.output.gain.setValueAtTime(1,this.context.currentTime),this.isPlaying=!0}start(e=0,n=0,s){this.isPlaying||(this.source=this._createSource(),this.startTime=this.context.currentTime+e-n/this.playbackRate,s!==void 0?this.source.start(this.context.currentTime+e,n,s):this.source.start(this.context.currentTime+e,n),this.pauseTime=n,this.isPlaying=!0)}pause({fadeOut:e=0}={}){if(!this.isPlaying)return;let n=this.getElapsed()/1e3;if(this.loop&&this.loopEnd>this.loopStart){let s=this.loopEnd-this.loopStart;n=this.loopStart+(n-this.loopStart)%s}if(this.isPlaying=!1,e>0){let s=this.context.currentTime;this.output.gain.setValueAtTime(this.output.gain.value,s),this.output.gain.linearRampToValueAtTime(0,s+e),setTimeout(()=>{if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.pauseTime=n,this.output.gain.setValueAtTime(1,this.context.currentTime)},e*1e3)}else{if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.pauseTime=n}}getElapsed(){return this.isPlaying?(this.context.currentTime-this.startTime)*this.playbackRate*1e3:this.pauseTime*1e3}setSpeed(e){if(e<=0)throw new Error("Playback rate must be positive");let n=this.getElapsed()/1e3;this.playbackRate=e,this.isPlaying&&(this.pause(),this.pauseTime=n,this.play())}setLoop(e=!0){this.loop=e,this.source&&(this.source.loop=e)}loop;playbackRate;startTime;tempGain=null;connect(e,n=0,s=0){if("value"in e)this.output.connect(e,n);else return this.output.connect(e,n,s),e}disconnect(e,n,s){e===void 0?this.output.disconnect():this.output.disconnect(e,n,s)}output;stop(e=0){if(this.notIndependent)return this.pause();if(!this.source)return;let n=this.context.currentTime+e;this.source.stop(n),this.isPlaying=!1,this.notIndependent||(this.pauseTime=0)}pauseTime;isPlaying;notIndependent=!1;loopStart=0;loopEnd=0},Me={osc:{enabled:!0,type:"sine",freq:440,detune:0},noise:{enabled:!1,level:.5},ampEnv:{attack:.005,decay:.1,sustain:0,release:.1,volume:.3},pitchEnv:{amount:0,decay:.2},filter:{enabled:!1,type:"lowpass",freq:1200,Q:1,envAmount:0,decay:.2},lfo:{enabled:!1,target:"freq",rate:8,depth:20},duration:.4},V=class i{constructor(e={}){this.ctx=X.audioCtx,this.cfg=structuredClone(Me),Object.assign(this.cfg,e)}ctx;cfg;play(e=X.sfxGain){let n=this.ctx,s=n.currentTime,a=this.cfg,l=n.createGain();l.gain.setValueAtTime(1e-4,s);let d=a.ampEnv;l.gain.exponentialRampToValueAtTime(d.volume,s+d.attack),l.gain.exponentialRampToValueAtTime(Math.max(1e-4,d.sustain*d.volume),s+d.attack+d.decay),l.gain.exponentialRampToValueAtTime(1e-4,s+a.duration+d.release);let f=l,h;a.filter.enabled&&(h=n.createBiquadFilter(),h.type=a.filter.type,h.frequency.value=a.filter.freq,h.Q.value=a.filter.Q,h.connect(l),f=h);let c;if(a.osc.enabled){if(c=n.createOscillator(),c.type=a.osc.type,c.frequency.value=a.osc.freq,c.detune.value=a.osc.detune,a.pitchEnv.amount!==0){let r=Math.pow(2,a.pitchEnv.amount/12);c.frequency.exponentialRampToValueAtTime(a.osc.freq*r,s+a.pitchEnv.decay)}c.connect(f),c.start(s),c.stop(s+a.duration+d.release)}let p;if(a.noise.enabled){let r=n.sampleRate*a.duration,o=n.createBuffer(1,r,n.sampleRate),u=o.getChannelData(0);for(let y=0;y<r;y++)u[y]=(Math.random()*2-1)*a.noise.level;p=n.createBufferSource(),p.buffer=o,p.connect(f),p.start(s),p.stop(s+a.duration+d.release)}let g,x;a.lfo.enabled&&c&&(g=n.createOscillator(),g.frequency.value=a.lfo.rate,x=n.createGain(),x.gain.value=a.lfo.depth,g.connect(x),a.lfo.target==="freq"?x.connect(c.frequency):a.lfo.target==="gain"?x.connect(l.gain):a.lfo.target==="filter"&&h&&x.connect(h.frequency),g.start(s),g.stop(s+a.duration)),l.connect(e);let v=[c,p,g,x,h,l],t=s+a.duration+d.release;setTimeout(()=>{v.forEach(r=>r?.disconnect())},(t-n.currentTime)*1e3)}getConfig(){return structuredClone(this.cfg)}setConfig(e){return Object.assign(this.cfg,e),this}getKey(e){return this.cfg[e]}setKey(e,n){return Object.assign(this.cfg[e],n),this}setFreq(e){return this.cfg.osc.freq=e,this}setWave(e){return this.cfg.osc.type=e,this}setVolume(e){return this.cfg.ampEnv.volume=e,this}setAmpEnv(e,n,s,a){return Object.assign(this.cfg.ampEnv,{attack:e,decay:n,sustain:s,release:a}),this}setPitchEnv(e,n){return Object.assign(this.cfg.pitchEnv,{amount:e,decay:n}),this}setNoiseEnabled(e){return this.cfg.noise.enabled=e,this}setNoiseLevel(e){return this.cfg.noise.level=e,this}setFilterEnabled(e){return this.cfg.filter.enabled=e,this}setFilter(e,n,s){return Object.assign(this.cfg.filter,{type:e,freq:n,Q:s,enabled:!0}),this}setLFOEnabled(e){return this.cfg.lfo.enabled=e,this}setLFO(e,n,s){return Object.assign(this.cfg.lfo,{target:e,rate:n,depth:s,enabled:!0}),this}setDuration(e){return this.cfg.duration=e,this}clone(){return new i(structuredClone(this.cfg))}},at=new V({osc:{enabled:!0,type:"square",freq:900,detune:0},ampEnv:{attack:.002,decay:.04,sustain:0,release:.02,volume:.15},duration:.05}),ot=new V({osc:{enabled:!0,type:"sine",freq:600,detune:0},ampEnv:{attack:.01,decay:.08,sustain:0,release:.04,volume:.12},duration:.1}),lt=new V({osc:{enabled:!0,type:"triangle",freq:500,detune:0},pitchEnv:{amount:12,decay:.15},ampEnv:{attack:.01,decay:.12,sustain:0,release:.05,volume:.25},duration:.18}),ut=new V({osc:{enabled:!0,type:"sawtooth",freq:1200,detune:0},pitchEnv:{amount:-24,decay:.3},ampEnv:{attack:.005,decay:.25,sustain:0,release:.05,volume:.3},duration:.35}),ht=new V({osc:{enabled:!0,type:"square",freq:180,detune:0},noise:{enabled:!0,level:.4},ampEnv:{attack:.002,decay:.15,sustain:0,release:.05,volume:.35},duration:.2});function pe(i=12){let e=Date.now().toString(36),n=crypto.getRandomValues(new Uint8Array(4)),s=Array.from(n).map(a=>a.toString(36).padStart(2,"0")).join("");return(e+s).slice(0,i)}function Ae(i){let e=!0;function n(){e&&(i(),requestAnimationFrame(n))}return requestAnimationFrame(n),{clear:()=>e=!1}}function Le(){return U?!1:/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)}var ct=Le();function _e({width:i,height:e,updateHz:n="frames"}){return new G.KaylaGame(i,e,n==="frames"?1/0:n)}function Ve(i){let e=new J(i);return new G.KaylaScene(e)}function De(i){return new G.KaylaRenderer(i)}function ne(i,e){if(typeof i!="function")throw new Error("Invalid Element Type.");let n=e??{};return n.key??=i.name+"_"+pe(),{type:i,props:n}}var L;(s=>{function i(a,l){return!(a.right<l.left||a.left>l.right||a.bottom<l.top||a.top>l.bottom)}s.rawCollision=i;function e(a,l,d){let f=l*Math.PI/180,h=Math.cos(f),c=Math.sin(f),p=1/0;return h>0&&(p=Math.min(p,(d.right-a.x)/h)),h<0&&(p=Math.min(p,(d.left-a.x)/h)),c>0&&(p=Math.min(p,(d.bottom-a.y)/c)),c<0&&(p=Math.min(p,(d.top-a.y)/c)),M.from(l).scale(p)}s.getCurrToBound=e;function n(a){let{left:l,right:d,top:f,bottom:h,width:c,height:p,x:g=0,y:x=0}=a;if(c===null||p===null)throw new Error("width and height are required");let v,t;if(l!=null&&d!=null){if(Math.abs(d-l-c)>1e-6)throw new Error("left, right, and width mismatch");v=l}else g!=null?v=g-c/2:l!=null?v=l:d!=null?v=d-c:v=0;if(f!=null&&h!=null){if(Math.abs(h-f-p)>1e-6)throw new Error("top, bottom, and height mismatch");t=f}else x!=null?t=x-p/2:f!=null?t=f:h!=null?t=h-p:t=0;return{left:v,right:v+c,top:t,bottom:t+p,width:c,height:p,x:v+c/2,y:t+p/2}}s.createRawRect=n})(L||={});var G;(x=>{class i extends Z{#e;#t;constructor(t,r,o){super(t,r,o),this.#e=new Set,this.#t=!1}delay(t){return this.ticker.createTimeout(t)}get started(){return this.#t}start(){if(!this.#t){for(let t of this.#e)t.start();this.#t=!0,super.start()}}stop(){if(this.#t){for(let t of this.#e)t.stop();this.#t=!1,super.stop()}}addRenderer(t){this.#e.has(t)||(this.#e.add(t),this.#t&&t.start(),t.game=this)}get mainRenderer(){return[...this.#e].at(0)}getRenderers(){return[...this.#e]}deleteRenderer(t){this.#e.has(t)&&(this.#e.delete(t),this.#t&&t.stop(),delete t.game)}}x.KaylaGame=i;class e extends Q{game;pointerX;pointerY;pointerEvents;onPointerDown;onPointerUp;onPointerCancel;onPointerMove;constructor(t){super(t),this.useDraw=this.useDraw.bind(this),this.on("draw",r=>{if(this.game)for(let o of this.game.scenes.values())o.handleDraw(r)}),this.pointerX=0,this.pointerY=0,this.pointerEvents=new I,this.pointerPosUpdater=this.pointerPosUpdater.bind(this),this.onPointerDown=r=>this.onPointerAll(r,"down"),this.onPointerUp=r=>this.onPointerAll(r,"up"),this.onPointerCancel=r=>this.onPointerAll(r,"cancel"),this.onPointerMove=r=>this.onPointerAll(r,"move")}pointerPosUpdater(t){this.pointerX=t.clientX,this.pointerY=t.clientY}onPointerAll(t,r){this.pointerPosUpdater(t);let o=e.getClickType(t);if(o!=="invalid"||r==="move"||r==="cancel"){t.preventDefault();let u=this.getMousePos();this.pointerEvents.emit("action",u,o,r)}}static getClickType(t){switch(t.button){case 0:return"left";case 1:return"middle";case 2:return"right";default:return"invalid"}}listenPointerUpdates(){this.canvas.addEventListener("pointermove",this.pointerPosUpdater),this.canvas.addEventListener("pointerdown",this.onPointerDown),this.canvas.addEventListener("pointerup",this.onPointerUp),this.canvas.addEventListener("pointercancel",this.onPointerCancel),this.canvas.addEventListener("pointermove",this.onPointerMove)}unlistenPointerUpdates(){this.canvas.removeEventListener("pointermove",this.pointerPosUpdater),this.canvas.removeEventListener("pointerdown",this.onPointerDown),this.canvas.removeEventListener("pointerup",this.onPointerUp),this.canvas.removeEventListener("pointermove",this.onPointerMove)}pointerPosToWorldPos(t,r){let o=this.canvas.getBoundingClientRect(),u=(t-o.left)/o.width,y=(r-o.top)/o.height,b=u*this.viewportWidth*this.cameraWidth/o.width,C=y*this.viewportHeight*this.cameraHeight/o.height;return new M(b,C)}getMousePos(){return this.pointerPosToWorldPos(this.pointerX,this.pointerY)}useDraw(t){let r=o=>{t(o,new s)};return this.on("draw",r),()=>{this.off("draw",r)}}attachTo(t){t.addRenderer(this),this.game=t}detach(){this.game&&this.game.deleteRenderer(this)}}x.KaylaRenderer=e;class n{current;saves;constructor(){this.saves=[]}useTick(t){if(!this.current)throw new Error("Hook 'useTick' must be executed in the top level scope of a component.");this.current.onTick[this.current.useStepCallIndex]=t,this.current.useStepCallIndex++}usePaint(t){if(!this.current)throw new Error("Hook 'usePaint' must be executed in the top level scope of a component.");this.current.onPaint[this.current.useDrawCallIndex]=t,this.current.useDrawCallIndex++}useEntity(){if(!this.current)throw new Error("Hook 'useEntity' must be executed in the top level scope of a component.");return me(ye)}useSelf(t){if(!this.current)throw new Error("Hook 'useSelf' must be executed in the top level scope of a component.");let r=me(null);return(r.current===null||r.current===void 0)&&(r.current=t()),r.current}useInitialization(t){if(!this.current)throw new Error("Hook 'useInitialization' must be executed in the top level scope of a component.");let r=this.current;r.onInits[this.current.useInitCallIndex]=t,r.useInitCallIndex++}useRect(){if(!this.current)throw new Error("Hook 'useRect' must be executed in the top level scope of a component.");return D(()=>new x.KaylaInternalRect(this.current))}useFiber(){if(!this.current)throw new Error("Hook 'useFiber' must be executed in the top level scope of a component.");return D(()=>this.current)}useFiberControl(){if(!this.current)throw new Error("Hook 'useFiberControl' must be executed in the top level scope of a component.");let t=this.current;return D(()=>({refresh:()=>t.refresh(),get childrenCount(){return t.lastChildren.length},setMaxChildren:r=>{t.setMaxChildren(r)},getMaxChildren:()=>t.getMaxChildren(),get maxSafeChildren(){return t.maxSafeChildren},get key(){return t.key},get getChildrenEntities(){return t.getChildrenEntities.bind(t)},get getEntityChain(){return t.getEntityChain.bind(t)},get getFiberChain(){return t.getFiberChain.bind(t)}}))}useCurrentTicker(){if(!this.current)throw new Error("Hook 'useCurrentTicker' must be executed in the top level scope of a component.");return this.current.getAttachedGame().ticker}useCurrentRenderer(){if(!this.current)throw new Error("Hook 'useCurrentRenderer' must be executed in the top level scope of a component.");return this.current.getAttachedGame().mainRenderer}useCurrentGame(){if(!this.current)throw new Error("Hook 'useCurrentGame' must be executed in the top level scope of a component.");return this.current.getAttachedGame()}useCurrentScene(){if(!this.current)throw new Error("Hook 'useCurrentScene' must be executed in the top level scope of a component.");return this.current.scene}useState(t,{alwaysRecall:r=!1}={}){if(!this.current)throw new Error("Hook 'useState' must be executed in the top level scope of a component.");let u=this.current.state[this.current.useStateCallIndex]??new a(this.current,t,{alwaysRecall:r});return this.current.state[this.current.useStateCallIndex]=u,this.current.useStateCallIndex++,u}useShouldRefresh(t){let r=this.current;if(!r)throw new Error("useShouldRefresh must be called inside a component");r.watchedDeps&&console.warn("useShouldRefresh called multiple times \u2014 using the last call"),r.watchedDeps=t}useRef(t){if(!this.current)throw new Error("Hook 'useRef' must be executed in the top level scope of a component.");let o=this.current.refs[this.current.useRefCallIndex]??d(t??null);return this.current.refs[this.current.useRefCallIndex]=o,this.current.useRefCallIndex++,o}useEffect(t){if(!this.current)throw new Error("Hook 'useEffect' must be executed in the top level scope of a component.");this.current.onEffect[this.current.useEffectCallIndex]=t,this.current.useEffectCallIndex++}useViewportEffect(t){if(!this.current)throw new Error("Hook 'useViewport' must be executed in the top level scope of a component.");this.current.onViewportEffect[this.current.useViewCallIndex]=t,this.current.useViewCallIndex++}useExports(t,r){if(!this.current)throw new Error("Hook 'useExports' must be executed in the top level scope of a component.");this.current.onExport=r}useGlobalPointer(t,r){if(!this.current)throw new Error("Hook 'useGlobalPointer/useGlobalClick' must be executed in the top level scope of a component.");r??={},this.current.onGlobalPointer[this.current.useGlobalClickCallIndex]={handler:t,config:r},this.current.useGlobalClickCallIndex++}usePointer(t,r){if(!this.current)throw new Error("Hook 'usePointer/useClick' must be executed in the top level scope of a component.");r??={};let o=this.current;Re((u,y,b)=>{let C=o.entity;if(!C)return;let E=C.getRawRect(),z=L.createRawRect({x:u.x,y:u.y,width:3,height:3});L.rawCollision(E,z)&&t(u,y,b)},r)}useContext(t){if(!this.current)throw new Error("Hook 'useContext' must be executed in the top level scope of a component.");return this.current.findContextValueFromInst(t)}save(){this.saves.push({current:this.current})}restore(){let t=this.saves.pop();if(!t)throw new Error("Cannot restore without saving.");this.current=t.current}logLevel="warn";logger={debug:(...t)=>{this.logLevel==="debug"&&console.debug(...t)},info:(...t)=>{["info","warn","debug"].includes(this.logLevel)&&console.info(...t)},warn:(...t)=>{["warn","debug"].includes(this.logLevel)&&console.warn(...t)},error:(...t)=>console.error(...t),withFiber:(t,r,o,...u)=>{let y=t?.fc?.name||"anonymous",b=t?.key?` key=${t.key}`:"";this.logger[r](`${o} <${y}${b}>`,...u)}}}x.GlobalKayla=n;class s{preventDefault(){this.#e=!0}#e=!1;isPrevented(){return this.#e}}x.KaylaEvent=s;class a{#e;#t;#n;alwaysRecall;constructor(t,r,{alwaysRecall:o=!1}={}){this.#t=t,this.#e=r??void 0,this.#n=Date.now(),this.alwaysRecall=o}get(){return this.#e}*[Symbol.iterator](){throw new Error(`Hey! KaylaState is NOT an array / iterable like useState in React.
|
|
1
|
+
var Pe=Object.defineProperty;var Se=(i,e)=>{for(var n in e)Pe(i,n,{get:e[n],enumerable:!0})};var Ce={};Se(Ce,{JSX:()=>Te,KMatrix2D:()=>be,KaylaContext:()=>te,KaylaFragment:()=>we,KaylaInternals:()=>G,KaylaRect:()=>L,Layer:()=>tt,createContext:()=>Ge,createElement:()=>ne,createGame:()=>_e,createReassignableObject:()=>Je,createRenderer:()=>De,createScene:()=>Ve,createUseHook:()=>et,self:()=>ye,setLogLevel:()=>Ze,useClick:()=>Oe,useContext:()=>Ye,useCurrentGame:()=>Be,useCurrentRenderer:()=>We,useCurrentScene:()=>ke,useCurrentTicker:()=>je,useDisposableRef:()=>Qe,useEffect:()=>re,useEntity:()=>qe,useExports:()=>oe,useFiber:()=>xe,useFiberControl:()=>ge,useGlobalClick:()=>Re,useGlobalPointer:()=>$e,useInitialization:()=>ie,useNextStack:()=>ve,usePaint:()=>ae,usePointer:()=>Ne,useRect:()=>se,useRef:()=>me,useSelf:()=>D,useShouldRefresh:()=>He,useState:()=>ze,useTick:()=>Xe,useViewportEffect:()=>Ue});var I=class{#e=new Map;constructor(){this.#e=new Map}on(e,n){let s=this.#e.get(e)||[];return s.push(n),this.#e.set(e,s),this}once(e,n){let s=(...a)=>{this.off(e,s),n(...a)};return this.on(e,s),this}off(e,n){let s=this.#e.get(e);if(!s)return this;let a=s.indexOf(n);return a>=0&&s.splice(a,1),this}emit(e,...n){let s=this.#e.get(e);if(!s||s.length===0){if(e==="error")throw n[0];return!1}return s.slice().forEach(a=>a(...n)),!0}removeAllListeners(e){return e?this.#e.delete(e):this.#e.clear(),this}listenerCount(e){return this.#e.get(e)?.length??0}},Q=class extends I{#e;#t;running;_rafId;_fps;_frameCount;_fpsTimer;_lastFrameTime;get canvas(){return this.#e}get ctx(){return this.#t}set canvas(e){this.#e=e,this.#t=e.getContext("2d"),this.updateCanvasResolution()}constructor(e,{viewportWidth:n,viewportHeight:s,cameraWidth:a,cameraHeight:l}={}){if(!k)throw new Error("Web-Only");super(),this.canvas=e,this.automatic=!0,this.#n=n??e.width,this.#r=s??e.height,this.#i=a??e.width,this.#s=l??e.height,this.running=!1,this._rafId=null,this._loop=this._loop.bind(this),this.updateCanvasResolution(),this._fps=60,this._frameCount=0,this._fpsTimer=0}automatic;retransform(){this.ctx.setTransform(1,0,0,1,0,0);let e=this.#i/this.#n,n=this.#s/this.#r;this.ctx.translate(this.#i/2,this.#s/2),this.ctx.scale(e,n),this.ctx.translate(-this.#n/2,-this.#r/2)}#n=0;#r=0;#i=0;#s=0;get viewportWidth(){return this.#n}set viewportWidth(e){this.#n=e,this.retransform(),this.emitViewportUpdate()}get width(){return this.#n}get height(){return this.#r}get centerX(){return this.#n/2}get centerY(){return this.#r/2}get left(){return 0}get top(){return 0}get right(){return this.#n}get bottom(){return this.#r}get viewportHeight(){return this.#r}set viewportHeight(e){this.#r=e,this.retransform(),this.emitViewportUpdate()}get cameraWidth(){return this.#i}set cameraWidth(e){this.#i=e,this.updateCanvasResolution(),this.retransform()}get cameraHeight(){return this.#s}set cameraHeight(e){this.#s=e,this.updateCanvasResolution(),this.retransform()}updateCanvasResolution(){this.canvas.width=this.#i,this.canvas.height=this.#s}emitViewportUpdate(){this.emit("viewport_update",{width:this.viewportWidth,height:this.viewportHeight})}applyTransform(){this.retransform()}get FPS(){return this._fps}_loop(){this.automatic&&this.update(),this._rafId=requestAnimationFrame(this._loop)}update(){if(!this.running||!k)return;let e=performance.now(),n=(e-(this._lastFrameTime??e))/1e3;this._lastFrameTime=e,this._frameCount++,this._fpsTimer+=n,this._fpsTimer>=1&&(this._fps=Math.round(this._frameCount/this._fpsTimer),this._frameCount=0,this._fpsTimer=0),this.ctx.clearRect(0,0,this.#i,this.#s),this.emit("draw",this.ctx)}start(){if(!this.running){if(!k||typeof globalThis.requestAnimationFrame>"u")throw new Error("Raf is not supported");this.running=!0,this._rafId=requestAnimationFrame(this._loop)}}stop(){if(!k||typeof globalThis.requestAnimationFrame>"u")throw new Error("Raf is not supported");this.running=!1,this._rafId!==null&&(cancelAnimationFrame(this._rafId),this._rafId=null)}},ce=class extends I{setNow(e){this.#e=e}#e=0;__intervalId=null;__lastTime=0;constructor(e=16){super(),this.#t=e,this.speedHackDT=1}speedHackDT;get isRaf(){return this.tickInterval===1/0}#t=15;get tickInterval(){return this.#t}set tickInterval(e){this.#t=e,this.__intervalId&&(this.stop(),this.start())}now(){return this.#e}__tick(){let e=performance.now(),n=(e-this.__lastTime)/1e3*this.speedHackDT;this.__lastTime=e,!(k&&typeof this.__intervalId=="function"&&document.hidden)&&(this.#e+=n*1e3,this.emit("tick",n))}createTimeout(e){return new fe(e,this)}createTween(e,n=()=>{}){let s=new de(e),a=(l=0)=>{if(s.finished){this.off("tick",a);return}s.update(l)};return s.on("finish",()=>{this.off("tick",a)}),s.on("delta",l=>{n(l)}),this.on("tick",a),s}start(){this.__intervalId===null&&(this.__lastTime=performance.now(),this.__intervalId=k&&!isFinite(this.tickInterval)?Ae(()=>this.__tick()).clear:setInterval(()=>this.__tick(),this.tickInterval))}stop(){this.__intervalId!==null&&(typeof this.__intervalId=="function"?this.__intervalId():clearInterval(this.__intervalId)),this.__intervalId=null}getSineMod(e,n=0){return .5+.5*Math.sin((this.now()%e/e+n)*2*Math.PI)}},Ie;(t=>{function i(r){return r===!0?1:0}t.booleanExport=i;function e(r){return r===0?!1:r===1}t.booleanImport=e;function n(r){return`${r.x}|${r.y}`}t.vec2Export=n;function s(r){let[o,u]=r.split("|"),y=parseFloat(o),b=parseFloat(u);if(isNaN(y)||isNaN(b))throw new Error(`Invalid Vector2 string: ${r}`);return new M(y,b)}t.vec2Import=s,t.booleanMap={mapExport:i,mapImport:e};function l(r){return o=>Number(o.toFixed(r))}t.createRounder=l;function d(r=10){return{mapExport(o){return Math.round(o/r)},mapImport(o){return o*r}}}t.createLowPrecision=d;function f(r){return Math.round(r)}t.lightWeightRounder=f;function h(r=100){return{mapExport(o){return Math.round(o*r)},mapImport(o){return o/r}}}t.createPercent=h;function c(r){let o=new Map(Object.entries(r));return{mapExport:u=>o.get(u)??null,mapImport:u=>Array.from(o.entries()).find(([y,b])=>b===u)?.[0]??null}}t.createLookup=c;function p(r){let o=r*(180/Math.PI);return Math.round((o%360+360)%360)}t.radToDeg=p;function g(r){return r*(Math.PI/180)}t.degToRad=g,t.angleRadToDeg={mapExport:p,mapImport:g};function v(r=10){let o=d(r);return{mapExport(u){return o.mapExport(p(u))},mapImport(u){return o.mapImport(g(u))}}}t.createLowPrecisionRadToDeg=v})(Ie||={});var N=class i extends I{name="";scaleRotate=0;scale=1;constructor(e,n=0,s=0){super(),this.autoTranslate=!1,this.name=e,this.z=0,this.___pos=new M(n,s),this.nonSerializableProperties=[],this.nonSerializableProperties.push("___pos","autoTranslate","arraySerializeMap"),this.forceSerializableProperties=[],this.forceSerializableProperties.push("x","y")}arraySerializeMap;autoTranslate;z;___pos;nonSerializableProperties;forceSerializableProperties;get pos(){return this.___pos}get x(){return this.pos.x}get y(){return this.pos.y}set x(e){this.pos.x=e}set y(e){this.pos.y=e}handleUpdate(e){if(this.update)try{this.emit("update",e),this.update(e)}catch(n){this.emit("error",n)}}handleDraw(e){if(!(U||!this.draw)){e.save(),this.autoTranslate&&e.translate(this.x,this.y);try{this.emit("draw",e),this.draw(e)}catch(n){this.emit("error",n)}e.restore()}}serialize(){if(Array.isArray(this.arraySerializeMap))return this.arraySerializeMap.map(([a,{mapExport:l}])=>{let d=Reflect.get(this,a);return l?l(d):d});let e=["_events","_eventsCount","_maxListeners","nonSerializableProperties","forceSerializableProperties"],n=[...Reflect.ownKeys(this),...this.forceSerializableProperties].filter(a=>!this.nonSerializableProperties.includes(a)&&!e.includes(a.toString())),s=Object.fromEntries(n.map(a=>{let l=Reflect.get(this,a);if(U&&typeof l=="number"){let d=l.toString().split("."),h=(d[1]?d[1].length:0)>2?Number(l.toFixed(2)):l;return[a,h]}return[a,l]}));return JSON.parse(JSON.stringify(s))}toLocal(e){return e.subtract(this.pos)}toWorld(e){return e.add(this.pos)}deserializeArray(e){return i.deserializeArray(this.arraySerializeMap,e)}static deserializeArray(e,n){if(!e||!Array.isArray(n))return n;let s={};for(let a=0;a<n.length;a++){let l=e[a];if(!l)break;let[d,{mapImport:f}]=l,h=n[a];if(f&&(h=f(h)),typeof d!="string")break;try{Reflect.set(s,d,h)}catch(c){console.error(c)}}return s}},J=class extends I{name="";entities=new Map;paused=!0;constructor(e){super(),this.name=e}handleUpdate(e){if(!this.paused){this.emit("update",e);for(let n of this.entities.values())n.handleUpdate(e)}}handleDraw(e){if(!U&&!this.paused){this.emit("draw",e);for(let n of[...this.entities.values()].sort((s,a)=>s.z-a.z))n.handleDraw(e)}}addEntity(e){if(!(e instanceof N))throw new Error("invalid entity");if(!e.name)throw new Error("Entity must have a name.");this.entities.set(e.name,e)}removeEntity(e){if(!(e instanceof N))throw new Error("invalid entity");this.entities.delete(e.name)}getEntity(e){return this.entities.get(e)}},Z=class{scenes;ticker;get centerX(){return this.width/2}get centerY(){return this.height/2}get left(){return 0}get top(){return 0}get right(){return this.width}get bottom(){return this.height}width;height;constructor(e,n,s=16){this.ticker=new ce(s),this.scenes=new Map,this.width=e,this.height=n,this.ticker.on("tick",a=>{for(let l of this.scenes.values())l.paused||l.handleUpdate(a)})}addScene(e){if(!e.name)throw new Error("Scene must have a name.");e.paused=!1,this.scenes.set(e.name,e)}removeScene(e){e&&(e.paused=!0),this.scenes.delete(e.name)}now(){return this.ticker.now()}start(){this.ticker.start()}stop(){this.ticker.stop()}},P={lerp(i,e,n){return i+(e-i)*n},clamp(i,e,n){return Math.min(n,Math.max(e,i))},clamp01(i){return Math.min(1,Math.max(0,i))},easeLinear(i){return i},easeInQuad(i){return i*i},easeOutQuad(i){return 1-(1-i)*(1-i)},easeInOutQuad(i){return i<.5?2*i*i:1-Math.pow(-2*i+2,2)/2},easeInSine(i){return 1-Math.cos(i*Math.PI/2)},easeOutSine(i){return Math.sin(i*Math.PI/2)},easeInOutSine(i){return-(Math.cos(Math.PI*i)-1)/2},easeInExpo(i){return i===0?0:Math.pow(2,10*i-10)},easeOutExpo(i){return i===1?1:1-Math.pow(2,-10*i)},easeInOutExpo(i){return i===0?0:i===1?1:i<.5?Math.pow(2,20*i-10)/2:(2-Math.pow(2,-20*i+10))/2},smoothstep(i){return i=P.clamp(i,0,1),i*i*(3-2*i)},randomLerp(i,e){return P.lerp(i,e,Math.random())},randomInt(i,e){return Math.floor(Math.random()*(e-i+1))+i},randomArrayValue(i){return i[P.randomInt(0,i.length-1)]},createBezier(i,e,n,s){function a(f,h,c,p,g){let x=1-f;return x*x*x*h+3*x*x*f*c+3*x*f*f*p+f*f*f*g}function l(f,h,c,p,g){let x=1-f;return 3*x*x*(c-h)+6*x*f*(p-c)+3*f*f*(g-p)}function d(f){let h=f;for(let c=0;c<6;c++){let p=a(h,0,i,n,1),g=l(h,0,i,n,1);if(g===0)break;h-=(p-f)/g}return P.clamp(h,0,1)}return function(h){h=P.clamp(h,0,1);let c=d(h);return a(c,0,e,s,1)}},lengthSquared(...i){return i.reduce((e,n)=>e+n*n,0)},normalizeRad(i){let e=2*Math.PI;return i=i%e,i<0&&(i+=e),i},angleInvertY(i){return P.normalizeRad(-i)},degToRadFlipY(i){return P.angleInvertY(i*Math.PI/180)},minimalAngularDirection(i,e){i=P.normalizeRad(i),e=P.normalizeRad(e);let n=P.normalizeRad(e-i),s=P.normalizeRad(i-e);return n<=s?1:-1}},de=class extends I{constructor({delta:e,ms:n,easing:s}){super(),this.delta=e,this.duration=n,this.elapsed=0,this.easing=s??(a=>a),this.lastValue=0,this.finished=!1}delta;duration;elapsed;lastValue;finished;easing;update(e){this.elapsed+=e*1e3;let n=P.clamp(this.elapsed/this.duration,0,1),s=this.easing(n),a=this.delta*s,l=a-this.lastValue;this.lastValue=a,this.emit("delta",l),n>=1&&(this.finished=!0,this.emit("finish",void 0))}},ee=class extends N{constructor(e,n=0,s=0,a=50,l=50){super(e,n,s),this.width=a,this.height=l}width;height;get left(){return this.x-this.width/2}set left(e){this.x=e+this.width/2}get right(){return this.x+this.width/2}set right(e){this.x=e-this.width/2}get top(){return this.y-this.height/2}set top(e){this.y=e+this.height/2}get bottom(){return this.y+this.height/2}set bottom(e){this.y=e-this.height/2}get lx(){return 0}get ly(){return 0}get lleft(){return-this.width/2}get lright(){return this.width/2}get ltop(){return-this.height/2}get lbottom(){return this.height/2}isCollidingWith(e){return!(this.right<e.left||this.left>e.right||this.bottom<e.top||this.top>e.bottom)}color="rgba(0, 0, 255, 0.3)";draw(e){e.translate(this.x,this.y),e.rotate(this.scaleRotate),e.fillStyle=this.color,e.fillRect(-this.width/2,-this.height/2,this.width,this.height)}},fe=class extends I{duration;ticker;elapsed;finished;_resolve;promise;_timeoutId;constructor(e,n=null){super(),this.duration=e,this.ticker=n,this.elapsed=0,this.finished=!1,this._resolve=null,this.promise=new Promise(s=>this._resolve=s),this.update=this.update.bind(this),this.ticker&&this.ticker.on("tick",this.update)}update(e=0){this.finished||(this.elapsed+=e*1e3,this.elapsed>=this.duration&&this.finish())}finish(){this.finished||(this.finished=!0,this.emit("finish",void 0),this._resolve&&this._resolve(),this.ticker&&this.ticker.off("tick",this.update))}start(){return this.ticker||(this._timeoutId=setTimeout(()=>this.finish(),this.duration)),this}cancel(){this.finished||(this.finished=!0,!this.ticker&&this._timeoutId!=null&&clearTimeout(this._timeoutId),this.ticker&&this.ticker.off("tick",this.update))}then(e,n){return this.promise.then(e,n)}after(e,n){return this.promise.then(e,n)}},M=class i{constructor(e=0,n=0){this.x=e,this.y=n}x;y;toJSON(){return{x:this.x,y:this.y,vec2:!0}}static isVec2(e){return e&&typeof e=="object"&&"x"in e&&"y"in e&&e.vec2===!0}static fromSerialized(e){return this.isVec2(e)?new this(e.x,e.y):null}rotate(e){let n=Math.cos(e),s=Math.sin(e);return new i(this.x*n-this.y*s,this.x*s+this.y*n)}static from(e){return new i(Math.cos(e),Math.sin(e))}isEmpty(){return Math.abs(this.x)<.01&&Math.abs(this.y)<.01}get angle(){return Math.atan2(this.y,this.x)}angleTo(e){return Math.atan2(e.y-this.y,e.x-this.x)}get length(){return Math.hypot(this.x,this.y)}get lengthSquared(){return this.x*this.x+this.y*this.y}normalized(){let e=this.length;return e===0?new i(0,0):new i(this.x/e,this.y/e)}consume(e){let n=this.length;n<=e?(this.x=0,this.y=0):this.overwite(this.scale((n-e)/n))}project(e){return e.scale(this.dotNormalized(e))}reflect(e){let n=this.dot(e);return this.subtract(e.scale(2*n))}dotNormalized(e){let n=this.normalized(),s=e.normalized();return n.x*s.x+n.y*s.y}lengthSquaredTo(e){let n=this.x-e.x,s=this.y-e.y;return n*n+s*s}dot(e){return this.x*e.x+this.y*e.y}distanceTo(e){return Math.hypot(this.x-e.x,this.y-e.y)}distanceToCheap(e){let n=this.x-e.x,s=this.y-e.y;return n*n+s*s}directionTo(e){return new i(e.x-this.x,e.y-this.y).normalized()}add(e){return new i(this.x+e.x,this.y+e.y)}addRaw(e){return new i(this.x+e,this.y+e)}overwite(e){this.x=e.x,this.y=e.y}subtract(e){return new i(this.x-e.x,this.y-e.y)}scale(e){return new i(this.x*e,this.y*e)}toString(){return`Vector2(${this.x}, ${this.y})`}clone(){return new i(this.x,this.y)}};function Fe(){return typeof process<"u"&&process.release?.name==="node"?"node":typeof window<"u"||typeof self<"u"?"web":"unknown"}var Ee=Fe(),U=Ee==="node",k=Ee==="web",X=class i{static unlock(){k&&this.audioCtx.state!=="running"&&this.audioCtx.resume()}static audioCtx=k?new AudioContext:null;static masterGain=k?this.audioCtx.createGain():null;static musicGain=k?this.audioCtx.createGain():null;static sfxGain=k?this.audioCtx.createGain():null;static{k&&(this.masterGain.gain.value=1,this.musicGain.gain.value=1,this.sfxGain.gain.value=1,this.sfxGain.connect(this.masterGain),this.musicGain.connect(this.masterGain),this.masterGain.connect(this.audioCtx.destination))}static get SFX_VOLUME(){return this.sfxGain.gain.value}static get MUSIC_VOLUME(){return this.musicGain.gain.value}static get VOLUME(){return this.masterGain.gain.value}static set SFX_VOLUME(e){this.sfxGain.gain.value=e}static set MUSIC_VOLUME(e){this.musicGain.gain.value=e}static set VOLUME(e){this.masterGain.gain.value=e}static noteToHz(e){return this.tuningFreq*Math.pow(2,(e-9)/12)}static tuningFreq=440;static audioBufferCache=new Map;static loops=new Map;static sfsx=new Map;static loopIdCounter=0;static CACHE_NAME="lia-audio-cache-v1";static async preLoad(e){if(this.audioBufferCache.has(e))return this.audioBufferCache.get(e);let n=i.CACHE_NAME,s,a;if(typeof caches<"u"&&(a=await caches.open(n),s=await a.match(e)),!s){if(s=await fetch(e),!s.ok)throw new Error(`Failed to fetch ${e}`);a&&await a.put(e,s.clone())}let l=await s.arrayBuffer(),d=await this.audioCtx.decodeAudioData(l);return this.audioBufferCache.set(e,d),d}static async getOnlyDownloadedCache(e){let n=i.CACHE_NAME;return await(await caches.open(n)).match(e)}static getCached(e){return this.audioBufferCache.get(e)||null}static async playSound(e,n=.2,s=1,a=!0){try{this.sfsx.has(e)&&this.sfsx.get(e).source.stop(),this.audioBufferCache.has(e)||await this.preLoad(e);let l=this.getCached(e);if(!l)return;let d=new O(l);d.buffer=l;let f=1-.12,h=1+.12;d.playbackRate=s??f+Math.random()*(h-f);let c=this.audioCtx.createGain();c.gain.value=n,d.tempGain=c,d.connect(c),c.connect(this.sfxGain),d.onended=()=>{d.disconnect(),c.disconnect()},d.start(),a&&this.sfsx.set(e,{source:d,gain:c})}catch(l){console.error(l)}}static async playLoop(e,n=1,{loopStart:s=0,loopEnd:a=null,exclusive:l=!0,skipMS:d=0}={}){if(l)for(let g of this.loops.keys())this.stopLoop(g);this.audioBufferCache.has(e)||await this.preLoad(e);let f=this.getCached(e);if(!f)return;let h=new O(f);h.buffer=f,h.loop=!0,typeof s=="number"&&(h.loopStart=s),typeof a=="number"&&(h.loopEnd=a);let c=this.audioCtx.createGain();c.gain.value=n,h.tempGain=c,h.playbackRate=1,h.onended=()=>{h.disconnect(),c.disconnect()},h.connect(c),c.connect(this.musicGain),h.start(0,d/1e3);let p=++this.loopIdCounter;return this.loops.set(p,{source:h,gain:c}),p}static stopLoop(e){let n=this.loops.get(e);n&&(n.source.stop(),n.source.notIndependent||(n.source.disconnect(),n.gain.disconnect()),this.loops.delete(e))}static async createLiaSource(e,{volume:n=1,speed:s=1,loop:a=!1,loopStart:l=0,loopEnd:d=null,isMusic:f=!1,gain:h=null}={}){try{this.audioBufferCache.has(e)||await this.preLoad(e);let c=this.getCached(e);if(!c)return null;let p=new O(c);p.loop=a,p.loopStart=l,p.loopEnd=typeof d=="number"?d:c.duration,p.playbackRate=s;let g=this.audioCtx.createGain();return g.gain.value=n,p.connect(g),p.tempGain=g,g.connect(h||(f?this.musicGain:this.sfxGain)),p.onended=()=>{p.disconnect(),g.disconnect()},p}catch(c){return console.error("Failed to create LiaAudioSrc:",c),null}}};var O=class{numberOfInputs;numberOfOutputs;constructor(e,n=X.audioCtx){this.context=n,this.buffer=e,this.source=null,this.startTime=0,this.pauseTime=0,this.playbackRate=1,this.isPlaying=!1,this.loop=!1,this.output=k?n.createGain():null,this.output.gain.value=1,this.channelCount=2,this.channelCountMode="max",this.channelInterpretation="speakers",this.numberOfInputs=0,this.numberOfOutputs=1,this.onended=null}channelCount;channelCountMode;channelInterpretation;onended;source;buffer;context;_createSource(){this.source&&(this.source.onended=null);let e=this.context.createBufferSource();return e.buffer=this.buffer,e.playbackRate.value=this.playbackRate,e.loop=this.loop,e.loopStart=this.loopStart,e.loopEnd=this.loopEnd>0?this.loopEnd:this.buffer.duration,e.connect(this.output),this.source=e,e.onended=()=>{this.source===e&&(this.isPlaying&&!this.loop&&(this.isPlaying=!1,this.pauseTime=0),typeof this.onended=="function"&&this.onended())},e}play({fadeIn:e=0,offset:n=null}={}){let s=n!==null?n:this.pauseTime;if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.source=this._createSource(),this.startTime=this.context.currentTime-s/this.playbackRate,this.source.start(0,s),e>0?(this.output.gain.setValueAtTime(0,this.context.currentTime),this.output.gain.linearRampToValueAtTime(1,this.context.currentTime+e)):this.output.gain.setValueAtTime(1,this.context.currentTime),this.isPlaying=!0}start(e=0,n=0,s){this.isPlaying||(this.source=this._createSource(),this.startTime=this.context.currentTime+e-n/this.playbackRate,s!==void 0?this.source.start(this.context.currentTime+e,n,s):this.source.start(this.context.currentTime+e,n),this.pauseTime=n,this.isPlaying=!0)}pause({fadeOut:e=0}={}){if(!this.isPlaying)return;let n=this.getElapsed()/1e3;if(this.loop&&this.loopEnd>this.loopStart){let s=this.loopEnd-this.loopStart;n=this.loopStart+(n-this.loopStart)%s}if(this.isPlaying=!1,e>0){let s=this.context.currentTime;this.output.gain.setValueAtTime(this.output.gain.value,s),this.output.gain.linearRampToValueAtTime(0,s+e),setTimeout(()=>{if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.pauseTime=n,this.output.gain.setValueAtTime(1,this.context.currentTime)},e*1e3)}else{if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.pauseTime=n}}getElapsed(){return this.isPlaying?(this.context.currentTime-this.startTime)*this.playbackRate*1e3:this.pauseTime*1e3}setSpeed(e){if(e<=0)throw new Error("Playback rate must be positive");let n=this.getElapsed()/1e3;this.playbackRate=e,this.isPlaying&&(this.pause(),this.pauseTime=n,this.play())}setLoop(e=!0){this.loop=e,this.source&&(this.source.loop=e)}loop;playbackRate;startTime;tempGain=null;connect(e,n=0,s=0){if("value"in e)this.output.connect(e,n);else return this.output.connect(e,n,s),e}disconnect(e,n,s){e===void 0?this.output.disconnect():this.output.disconnect(e,n,s)}output;stop(e=0){if(this.notIndependent)return this.pause();if(!this.source)return;let n=this.context.currentTime+e;this.source.stop(n),this.isPlaying=!1,this.notIndependent||(this.pauseTime=0)}pauseTime;isPlaying;notIndependent=!1;loopStart=0;loopEnd=0},Me={osc:{enabled:!0,type:"sine",freq:440,detune:0},noise:{enabled:!1,level:.5},ampEnv:{attack:.005,decay:.1,sustain:0,release:.1,volume:.3},pitchEnv:{amount:0,decay:.2},filter:{enabled:!1,type:"lowpass",freq:1200,Q:1,envAmount:0,decay:.2},lfo:{enabled:!1,target:"freq",rate:8,depth:20},duration:.4},V=class i{constructor(e={}){this.ctx=X.audioCtx,this.cfg=structuredClone(Me),Object.assign(this.cfg,e)}ctx;cfg;play(e=X.sfxGain){let n=this.ctx,s=n.currentTime,a=this.cfg,l=n.createGain();l.gain.setValueAtTime(1e-4,s);let d=a.ampEnv;l.gain.exponentialRampToValueAtTime(d.volume,s+d.attack),l.gain.exponentialRampToValueAtTime(Math.max(1e-4,d.sustain*d.volume),s+d.attack+d.decay),l.gain.exponentialRampToValueAtTime(1e-4,s+a.duration+d.release);let f=l,h;a.filter.enabled&&(h=n.createBiquadFilter(),h.type=a.filter.type,h.frequency.value=a.filter.freq,h.Q.value=a.filter.Q,h.connect(l),f=h);let c;if(a.osc.enabled){if(c=n.createOscillator(),c.type=a.osc.type,c.frequency.value=a.osc.freq,c.detune.value=a.osc.detune,a.pitchEnv.amount!==0){let r=Math.pow(2,a.pitchEnv.amount/12);c.frequency.exponentialRampToValueAtTime(a.osc.freq*r,s+a.pitchEnv.decay)}c.connect(f),c.start(s),c.stop(s+a.duration+d.release)}let p;if(a.noise.enabled){let r=n.sampleRate*a.duration,o=n.createBuffer(1,r,n.sampleRate),u=o.getChannelData(0);for(let y=0;y<r;y++)u[y]=(Math.random()*2-1)*a.noise.level;p=n.createBufferSource(),p.buffer=o,p.connect(f),p.start(s),p.stop(s+a.duration+d.release)}let g,x;a.lfo.enabled&&c&&(g=n.createOscillator(),g.frequency.value=a.lfo.rate,x=n.createGain(),x.gain.value=a.lfo.depth,g.connect(x),a.lfo.target==="freq"?x.connect(c.frequency):a.lfo.target==="gain"?x.connect(l.gain):a.lfo.target==="filter"&&h&&x.connect(h.frequency),g.start(s),g.stop(s+a.duration)),l.connect(e);let v=[c,p,g,x,h,l],t=s+a.duration+d.release;setTimeout(()=>{v.forEach(r=>r?.disconnect())},(t-n.currentTime)*1e3)}getConfig(){return structuredClone(this.cfg)}setConfig(e){return Object.assign(this.cfg,e),this}getKey(e){return this.cfg[e]}setKey(e,n){return Object.assign(this.cfg[e],n),this}setFreq(e){return this.cfg.osc.freq=e,this}setWave(e){return this.cfg.osc.type=e,this}setVolume(e){return this.cfg.ampEnv.volume=e,this}setAmpEnv(e,n,s,a){return Object.assign(this.cfg.ampEnv,{attack:e,decay:n,sustain:s,release:a}),this}setPitchEnv(e,n){return Object.assign(this.cfg.pitchEnv,{amount:e,decay:n}),this}setNoiseEnabled(e){return this.cfg.noise.enabled=e,this}setNoiseLevel(e){return this.cfg.noise.level=e,this}setFilterEnabled(e){return this.cfg.filter.enabled=e,this}setFilter(e,n,s){return Object.assign(this.cfg.filter,{type:e,freq:n,Q:s,enabled:!0}),this}setLFOEnabled(e){return this.cfg.lfo.enabled=e,this}setLFO(e,n,s){return Object.assign(this.cfg.lfo,{target:e,rate:n,depth:s,enabled:!0}),this}setDuration(e){return this.cfg.duration=e,this}clone(){return new i(structuredClone(this.cfg))}},at=new V({osc:{enabled:!0,type:"square",freq:900,detune:0},ampEnv:{attack:.002,decay:.04,sustain:0,release:.02,volume:.15},duration:.05}),ot=new V({osc:{enabled:!0,type:"sine",freq:600,detune:0},ampEnv:{attack:.01,decay:.08,sustain:0,release:.04,volume:.12},duration:.1}),lt=new V({osc:{enabled:!0,type:"triangle",freq:500,detune:0},pitchEnv:{amount:12,decay:.15},ampEnv:{attack:.01,decay:.12,sustain:0,release:.05,volume:.25},duration:.18}),ut=new V({osc:{enabled:!0,type:"sawtooth",freq:1200,detune:0},pitchEnv:{amount:-24,decay:.3},ampEnv:{attack:.005,decay:.25,sustain:0,release:.05,volume:.3},duration:.35}),ht=new V({osc:{enabled:!0,type:"square",freq:180,detune:0},noise:{enabled:!0,level:.4},ampEnv:{attack:.002,decay:.15,sustain:0,release:.05,volume:.35},duration:.2});function pe(i=12){let e=Date.now().toString(36),n=crypto.getRandomValues(new Uint8Array(4)),s=Array.from(n).map(a=>a.toString(36).padStart(2,"0")).join("");return(e+s).slice(0,i)}function Ae(i){let e=!0;function n(){e&&(i(),requestAnimationFrame(n))}return requestAnimationFrame(n),{clear:()=>e=!1}}function Le(){return U?!1:/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)}var ct=Le();function _e({width:i,height:e,updateHz:n="frames"}){return new G.KaylaGame(i,e,n==="frames"?1/0:n)}function Ve(i){let e=new J(i);return new G.KaylaScene(e)}function De(i){return new G.KaylaRenderer(i)}function ne(i,e){if(typeof i!="function")throw new Error("Invalid Element Type.");let n=e??{};return n.key??=i.name+"_"+pe(),{type:i,props:n}}var L;(s=>{function i(a,l){return!(a.right<l.left||a.left>l.right||a.bottom<l.top||a.top>l.bottom)}s.rawCollision=i;function e(a,l,d){let f=l*Math.PI/180,h=Math.cos(f),c=Math.sin(f),p=1/0;return h>0&&(p=Math.min(p,(d.right-a.x)/h)),h<0&&(p=Math.min(p,(d.left-a.x)/h)),c>0&&(p=Math.min(p,(d.bottom-a.y)/c)),c<0&&(p=Math.min(p,(d.top-a.y)/c)),M.from(l).scale(p)}s.getCurrToBound=e;function n(a){let{left:l,right:d,top:f,bottom:h,width:c,height:p,x:g=0,y:x=0}=a;if(c===null||p===null)throw new Error("width and height are required");let v,t;if(l!=null&&d!=null){if(Math.abs(d-l-c)>1e-6)throw new Error("left, right, and width mismatch");v=l}else g!=null?v=g-c/2:l!=null?v=l:d!=null?v=d-c:v=0;if(f!=null&&h!=null){if(Math.abs(h-f-p)>1e-6)throw new Error("top, bottom, and height mismatch");t=f}else x!=null?t=x-p/2:f!=null?t=f:h!=null?t=h-p:t=0;return{left:v,right:v+c,top:t,bottom:t+p,width:c,height:p,x:v+c/2,y:t+p/2}}s.createRawRect=n})(L||={});var G;(x=>{class i extends Z{#e;#t;constructor(t,r,o){super(t,r,o),this.#e=new Set,this.#t=!1}delay(t){return this.ticker.createTimeout(t)}get started(){return this.#t}start(){if(!this.#t){for(let t of this.#e)t.start();this.#t=!0,super.start()}}stop(){if(this.#t){for(let t of this.#e)t.stop();this.#t=!1,super.stop()}}addRenderer(t){this.#e.has(t)||(this.#e.add(t),this.#t&&t.start(),t.game=this)}get mainRenderer(){return[...this.#e].at(0)}getRenderers(){return[...this.#e]}deleteRenderer(t){this.#e.has(t)&&(this.#e.delete(t),this.#t&&t.stop(),delete t.game)}}x.KaylaGame=i;class e extends Q{game;pointerX;pointerY;pointerEvents;onPointerDown;onPointerUp;onPointerCancel;onPointerMove;constructor(t){super(t),this.useDraw=this.useDraw.bind(this),this.on("draw",r=>{if(this.game)for(let o of this.game.scenes.values())o.handleDraw(r)}),this.pointerX=0,this.pointerY=0,this.pointerEvents=new I,this.pointerPosUpdater=this.pointerPosUpdater.bind(this),this.onPointerDown=r=>this.onPointerAll(r,"down"),this.onPointerUp=r=>this.onPointerAll(r,"up"),this.onPointerCancel=r=>this.onPointerAll(r,"cancel"),this.onPointerMove=r=>this.onPointerAll(r,"move")}pointerPosUpdater(t){this.pointerX=t.clientX,this.pointerY=t.clientY}onPointerAll(t,r){this.pointerPosUpdater(t);let o=e.getClickType(t);if(o!=="invalid"||r==="move"||r==="cancel"){t.preventDefault();let u=this.getMousePos();this.pointerEvents.emit("action",u,o,r)}}static getClickType(t){switch(t.button){case 0:return"left";case 1:return"middle";case 2:return"right";default:return"invalid"}}listenPointerUpdates(){this.canvas.addEventListener("pointermove",this.pointerPosUpdater),this.canvas.addEventListener("pointerdown",this.onPointerDown),this.canvas.addEventListener("pointerup",this.onPointerUp),this.canvas.addEventListener("pointercancel",this.onPointerCancel),this.canvas.addEventListener("pointermove",this.onPointerMove)}unlistenPointerUpdates(){this.canvas.removeEventListener("pointermove",this.pointerPosUpdater),this.canvas.removeEventListener("pointerdown",this.onPointerDown),this.canvas.removeEventListener("pointerup",this.onPointerUp),this.canvas.removeEventListener("pointermove",this.onPointerMove)}pointerPosToWorldPos(t,r){let o=this.canvas.getBoundingClientRect(),u=(t-o.left)/o.width,y=(r-o.top)/o.height,b=u*this.viewportWidth*this.cameraWidth/o.width,C=y*this.viewportHeight*this.cameraHeight/o.height;return new M(b,C)}getMousePos(){return this.pointerPosToWorldPos(this.pointerX,this.pointerY)}useDraw(t){let r=o=>{t(o,new s)};return this.on("draw",r),()=>{this.off("draw",r)}}attachTo(t){t.addRenderer(this),this.game=t}detach(){this.game&&this.game.deleteRenderer(this)}}x.KaylaRenderer=e;class n{current;saves;constructor(){this.saves=[]}useTick(t){if(!this.current)throw new Error("Hook 'useTick' must be executed in the top level scope of a component.");this.current.onTick[this.current.useStepCallIndex]=t,this.current.useStepCallIndex++}usePaint(t){if(!this.current)throw new Error("Hook 'usePaint' must be executed in the top level scope of a component.");this.current.onPaint[this.current.useDrawCallIndex]=t,this.current.useDrawCallIndex++}useEntity(){if(!this.current)throw new Error("Hook 'useEntity' must be executed in the top level scope of a component.");return me(ye)}useSelf(t){if(!this.current)throw new Error("Hook 'useSelf' must be executed in the top level scope of a component.");let r=me(null);return(r.current===null||r.current===void 0)&&(r.current=t()),r.current}useInitialization(t){if(!this.current)throw new Error("Hook 'useInitialization' must be executed in the top level scope of a component.");let r=this.current;r.onInits[this.current.useInitCallIndex]=t,r.useInitCallIndex++}useRect(){if(!this.current)throw new Error("Hook 'useRect' must be executed in the top level scope of a component.");return D(()=>new x.KaylaInternalRect(this.current))}useFiber(){if(!this.current)throw new Error("Hook 'useFiber' must be executed in the top level scope of a component.");return D(()=>this.current)}useFiberControl(){if(!this.current)throw new Error("Hook 'useFiberControl' must be executed in the top level scope of a component.");let t=this.current;return D(()=>({refresh:()=>t.refresh(),get childrenCount(){return t.lastChildren.length},setMaxChildren:r=>{t.setMaxChildren(r)},getMaxChildren:()=>t.getMaxChildren(),get maxSafeChildren(){return t.maxSafeChildren},get key(){return t.key},get getChildrenEntities(){return t.getChildrenEntities.bind(t)},get getEntityChain(){return t.getEntityChain.bind(t)},get getFiberChain(){return t.getFiberChain.bind(t)}}))}useCurrentTicker(){if(!this.current)throw new Error("Hook 'useCurrentTicker' must be executed in the top level scope of a component.");return this.current.getAttachedGame().ticker}useCurrentRenderer(){if(!this.current)throw new Error("Hook 'useCurrentRenderer' must be executed in the top level scope of a component.");return this.current.getAttachedGame().mainRenderer}useCurrentGame(){if(!this.current)throw new Error("Hook 'useCurrentGame' must be executed in the top level scope of a component.");return this.current.getAttachedGame()}useCurrentScene(){if(!this.current)throw new Error("Hook 'useCurrentScene' must be executed in the top level scope of a component.");return this.current.scene}useState(t,{alwaysRecall:r=!1}={}){if(!this.current)throw new Error("Hook 'useState' must be executed in the top level scope of a component.");let u=this.current.state[this.current.useStateCallIndex]??new a(this.current,t,{alwaysRecall:r});return this.current.state[this.current.useStateCallIndex]=u,this.current.useStateCallIndex++,u}useShouldRefresh(t){let r=this.current;if(!r)throw new Error("useShouldRefresh must be called inside a component");r.watchedDeps&&console.warn("useShouldRefresh called multiple times \u2014 using the last call"),r.watchedDeps=t}useRef(t){if(!this.current)throw new Error("Hook 'useRef' must be executed in the top level scope of a component.");let o=this.current.refs[this.current.useRefCallIndex]??d(t??null);return this.current.refs[this.current.useRefCallIndex]=o,this.current.useRefCallIndex++,o}useEffect(t){if(!this.current)throw new Error("Hook 'useEffect' must be executed in the top level scope of a component.");this.current.onEffect[this.current.useEffectCallIndex]=t,this.current.useEffectCallIndex++}useViewportEffect(t){if(!this.current)throw new Error("Hook 'useViewport' must be executed in the top level scope of a component.");this.current.onViewportEffect[this.current.useViewCallIndex]=t,this.current.useViewCallIndex++}useExports(t,r){if(!this.current)throw new Error("Hook 'useExports' must be executed in the top level scope of a component.");this.current.onExport=r}useGlobalPointer(t,r){if(!this.current)throw new Error("Hook 'useGlobalPointer/useGlobalClick' must be executed in the top level scope of a component.");r??={},this.current.onGlobalPointer[this.current.useGlobalClickCallIndex]={handler:t,config:r},this.current.useGlobalClickCallIndex++}usePointer(t,r){if(!this.current)throw new Error("Hook 'usePointer/useClick' must be executed in the top level scope of a component.");r??={};let o=this.current;Re((u,y,b)=>{let C=o.entity;if(!C)return;let E=C.getRawRect(),z=L.createRawRect({x:u.x,y:u.y,width:3,height:3});L.rawCollision(E,z)&&t(u,y,b)},r)}useContext(t){if(!this.current)throw new Error("Hook 'useContext' must be executed in the top level scope of a component.");return this.current.findContextValueFromInst(t)}save(){this.saves.push({current:this.current})}restore(){let t=this.saves.pop();if(!t)throw new Error("Cannot restore without saving.");this.current=t.current}logLevel="warn";logger={debug:(...t)=>{this.logLevel==="debug"&&console.debug(...t)},info:(...t)=>{["info","warn","debug"].includes(this.logLevel)&&console.info(...t)},warn:(...t)=>{["warn","debug"].includes(this.logLevel)&&console.warn(...t)},error:(...t)=>console.error(...t),withFiber:(t,r,o,...u)=>{let y=t?.fc?.name||"anonymous",b=t?.key?` key=${t.key}`:"";this.logger[r](`${o} <${y}${b}>`,...u)}}}x.GlobalKayla=n;class s{preventDefault(){this.#e=!0}#e=!1;isPrevented(){return this.#e}}x.KaylaEvent=s;class a{#e;#t;#n;alwaysRecall;constructor(t,r,{alwaysRecall:o=!1}={}){this.#t=t,this.#e=r??void 0,this.#n=Date.now(),this.alwaysRecall=o}get(){return this.#e}*[Symbol.iterator](){throw new Error(`Hey! KaylaState is NOT an array / iterable like useState in React.
|
|
2
2
|
You probably wrote: const [value, setValue] = useState(...)
|
|
3
3
|
|
|
4
4
|
\u2192 In Kayla write: const value = useState(...);
|
package/dist/jsx-runtime.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var ce=Object.defineProperty;var Fe=Object.getOwnPropertyDescriptor;var Me=Object.getOwnPropertyNames;var Ae=Object.prototype.hasOwnProperty;var Ke=(r,e)=>{for(var n in e)ce(r,n,{get:e[n],enumerable:!0})},Le=(r,e,n,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of Me(e))!Ae.call(r,a)&&a!==n&&ce(r,a,{get:()=>e[a],enumerable:!(s=Fe(e,a))||s.enumerable});return r};var _e=r=>Le(ce({},"__esModule",{value:!0}),r);var dt={};Ke(dt,{Fragment:()=>ct,jsx:()=>ut,jsxDEV:()=>ht,jsxs:()=>Ie});module.exports=_e(dt);var Ee={};Ke(Ee,{JSX:()=>Se,KMatrix2D:()=>ge,KaylaContext:()=>te,KaylaFragment:()=>Ce,KaylaInternals:()=>G,KaylaRect:()=>L,Layer:()=>ot,createContext:()=>Ne,createElement:()=>ne,createGame:()=>Ue,createReassignableObject:()=>it,createRenderer:()=>Oe,createScene:()=>$e,createUseHook:()=>at,self:()=>be,setLogLevel:()=>st,useClick:()=>je,useContext:()=>nt,useCurrentGame:()=>Ze,useCurrentRenderer:()=>et,useCurrentScene:()=>Pe,useCurrentTicker:()=>tt,useDisposableRef:()=>rt,useEffect:()=>re,useEntity:()=>Je,useExports:()=>oe,useFiber:()=>ve,useFiberControl:()=>xe,useGlobalClick:()=>Te,useGlobalPointer:()=>We,useInitialization:()=>ie,useNextStack:()=>we,usePaint:()=>ae,usePointer:()=>Ye,useRect:()=>se,useRef:()=>ye,useSelf:()=>D,useShouldRefresh:()=>qe,useState:()=>Xe,useTick:()=>Qe,useViewportEffect:()=>Be});var I=class{#e=new Map;constructor(){this.#e=new Map}on(e,n){let s=this.#e.get(e)||[];return s.push(n),this.#e.set(e,s),this}once(e,n){let s=(...a)=>{this.off(e,s),n(...a)};return this.on(e,s),this}off(e,n){let s=this.#e.get(e);if(!s)return this;let a=s.indexOf(n);return a>=0&&s.splice(a,1),this}emit(e,...n){let s=this.#e.get(e);if(!s||s.length===0){if(e==="error")throw n[0];return!1}return s.slice().forEach(a=>a(...n)),!0}removeAllListeners(e){return e?this.#e.delete(e):this.#e.clear(),this}listenerCount(e){return this.#e.get(e)?.length??0}},Q=class extends I{canvas;ctx;running;_rafId;_fps;_frameCount;_fpsTimer;_lastFrameTime;constructor(e,{viewportWidth:n,viewportHeight:s,cameraWidth:a,cameraHeight:l}={}){if(!k)throw new Error("Web-Only");super(),this.canvas=e,this.ctx=e.getContext("2d"),this.automatic=!0,this.#e=n??e.width,this.#t=s??e.height,this.#n=a??e.width,this.#r=l??e.height,this.running=!1,this._rafId=null,this._loop=this._loop.bind(this),this.updateCanvasResolution(),this._fps=60,this._frameCount=0,this._fpsTimer=0}automatic;retransform(){this.ctx.setTransform(1,0,0,1,0,0);let e=this.#n/this.#e,n=this.#r/this.#t;this.ctx.translate(this.#n/2,this.#r/2),this.ctx.scale(e,n),this.ctx.translate(-this.#e/2,-this.#t/2)}#e=0;#t=0;#n=0;#r=0;get viewportWidth(){return this.#e}set viewportWidth(e){this.#e=e,this.retransform(),this.emitViewportUpdate()}get width(){return this.#e}get height(){return this.#t}get centerX(){return this.#e/2}get centerY(){return this.#t/2}get left(){return 0}get top(){return 0}get right(){return this.#e}get bottom(){return this.#t}get viewportHeight(){return this.#t}set viewportHeight(e){this.#t=e,this.retransform(),this.emitViewportUpdate()}get cameraWidth(){return this.#n}set cameraWidth(e){this.#n=e,this.updateCanvasResolution(),this.retransform()}get cameraHeight(){return this.#r}set cameraHeight(e){this.#r=e,this.updateCanvasResolution(),this.retransform()}updateCanvasResolution(){this.canvas.width=this.#n,this.canvas.height=this.#r}emitViewportUpdate(){this.emit("viewport_update",{width:this.viewportWidth,height:this.viewportHeight})}applyTransform(){this.retransform()}get FPS(){return this._fps}_loop(){this.automatic&&this.update(),this._rafId=requestAnimationFrame(this._loop)}update(){if(!this.running||!k)return;let e=performance.now(),n=(e-(this._lastFrameTime??e))/1e3;this._lastFrameTime=e,this._frameCount++,this._fpsTimer+=n,this._fpsTimer>=1&&(this._fps=Math.round(this._frameCount/this._fpsTimer),this._frameCount=0,this._fpsTimer=0),this.ctx.clearRect(0,0,this.#n,this.#r),this.emit("draw",this.ctx)}start(){if(!this.running){if(!k||typeof globalThis.requestAnimationFrame>"u")throw new Error("Raf is not supported");this.running=!0,this._rafId=requestAnimationFrame(this._loop)}}stop(){if(!k||typeof globalThis.requestAnimationFrame>"u")throw new Error("Raf is not supported");this.running=!1,this._rafId!==null&&(cancelAnimationFrame(this._rafId),this._rafId=null)}},de=class extends I{setNow(e){this.#e=e}#e=0;__intervalId=null;__lastTime=0;constructor(e=16){super(),this.#t=e,this.speedHackDT=1}speedHackDT;get isRaf(){return this.tickInterval===1/0}#t=15;get tickInterval(){return this.#t}set tickInterval(e){this.#t=e,this.__intervalId&&(this.stop(),this.start())}now(){return this.#e}__tick(){let e=performance.now(),n=(e-this.__lastTime)/1e3*this.speedHackDT;this.__lastTime=e,!(k&&typeof this.__intervalId=="function"&&document.hidden)&&(this.#e+=n*1e3,this.emit("tick",n))}createTimeout(e){return new pe(e,this)}createTween(e,n=()=>{}){let s=new fe(e),a=(l=0)=>{if(s.finished){this.off("tick",a);return}s.update(l)};return s.on("finish",()=>{this.off("tick",a)}),s.on("delta",l=>{n(l)}),this.on("tick",a),s}start(){this.__intervalId===null&&(this.__lastTime=performance.now(),this.__intervalId=k&&!isFinite(this.tickInterval)?ze(()=>this.__tick()).clear:setInterval(()=>this.__tick(),this.tickInterval))}stop(){this.__intervalId!==null&&(typeof this.__intervalId=="function"?this.__intervalId():clearInterval(this.__intervalId)),this.__intervalId=null}getSineMod(e,n=0){return .5+.5*Math.sin((this.now()%e/e+n)*2*Math.PI)}},Ve;(t=>{function r(i){return i===!0?1:0}t.booleanExport=r;function e(i){return i===0?!1:i===1}t.booleanImport=e;function n(i){return`${i.x}|${i.y}`}t.vec2Export=n;function s(i){let[o,u]=i.split("|"),y=parseFloat(o),b=parseFloat(u);if(isNaN(y)||isNaN(b))throw new Error(`Invalid Vector2 string: ${i}`);return new M(y,b)}t.vec2Import=s,t.booleanMap={mapExport:r,mapImport:e};function l(i){return o=>Number(o.toFixed(i))}t.createRounder=l;function d(i=10){return{mapExport(o){return Math.round(o/i)},mapImport(o){return o*i}}}t.createLowPrecision=d;function f(i){return Math.round(i)}t.lightWeightRounder=f;function h(i=100){return{mapExport(o){return Math.round(o*i)},mapImport(o){return o/i}}}t.createPercent=h;function c(i){let o=new Map(Object.entries(i));return{mapExport:u=>o.get(u)??null,mapImport:u=>Array.from(o.entries()).find(([y,b])=>b===u)?.[0]??null}}t.createLookup=c;function p(i){let o=i*(180/Math.PI);return Math.round((o%360+360)%360)}t.radToDeg=p;function g(i){return i*(Math.PI/180)}t.degToRad=g,t.angleRadToDeg={mapExport:p,mapImport:g};function v(i=10){let o=d(i);return{mapExport(u){return o.mapExport(p(u))},mapImport(u){return o.mapImport(g(u))}}}t.createLowPrecisionRadToDeg=v})(Ve||={});var N=class r extends I{name="";scaleRotate=0;scale=1;constructor(e,n=0,s=0){super(),this.autoTranslate=!1,this.name=e,this.z=0,this.___pos=new M(n,s),this.nonSerializableProperties=[],this.nonSerializableProperties.push("___pos","autoTranslate","arraySerializeMap"),this.forceSerializableProperties=[],this.forceSerializableProperties.push("x","y")}arraySerializeMap;autoTranslate;z;___pos;nonSerializableProperties;forceSerializableProperties;get pos(){return this.___pos}get x(){return this.pos.x}get y(){return this.pos.y}set x(e){this.pos.x=e}set y(e){this.pos.y=e}handleUpdate(e){if(this.update)try{this.emit("update",e),this.update(e)}catch(n){this.emit("error",n)}}handleDraw(e){if(!(U||!this.draw)){e.save(),this.autoTranslate&&e.translate(this.x,this.y);try{this.emit("draw",e),this.draw(e)}catch(n){this.emit("error",n)}e.restore()}}serialize(){if(Array.isArray(this.arraySerializeMap))return this.arraySerializeMap.map(([a,{mapExport:l}])=>{let d=Reflect.get(this,a);return l?l(d):d});let e=["_events","_eventsCount","_maxListeners","nonSerializableProperties","forceSerializableProperties"],n=[...Reflect.ownKeys(this),...this.forceSerializableProperties].filter(a=>!this.nonSerializableProperties.includes(a)&&!e.includes(a.toString())),s=Object.fromEntries(n.map(a=>{let l=Reflect.get(this,a);if(U&&typeof l=="number"){let d=l.toString().split("."),h=(d[1]?d[1].length:0)>2?Number(l.toFixed(2)):l;return[a,h]}return[a,l]}));return JSON.parse(JSON.stringify(s))}toLocal(e){return e.subtract(this.pos)}toWorld(e){return e.add(this.pos)}deserializeArray(e){return r.deserializeArray(this.arraySerializeMap,e)}static deserializeArray(e,n){if(!e||!Array.isArray(n))return n;let s={};for(let a=0;a<n.length;a++){let l=e[a];if(!l)break;let[d,{mapImport:f}]=l,h=n[a];if(f&&(h=f(h)),typeof d!="string")break;try{Reflect.set(s,d,h)}catch(c){console.error(c)}}return s}},J=class extends I{name="";entities=new Map;paused=!0;constructor(e){super(),this.name=e}handleUpdate(e){if(!this.paused){this.emit("update",e);for(let n of this.entities.values())n.handleUpdate(e)}}handleDraw(e){if(!U&&!this.paused){this.emit("draw",e);for(let n of[...this.entities.values()].sort((s,a)=>s.z-a.z))n.handleDraw(e)}}addEntity(e){if(!(e instanceof N))throw new Error("invalid entity");if(!e.name)throw new Error("Entity must have a name.");this.entities.set(e.name,e)}removeEntity(e){if(!(e instanceof N))throw new Error("invalid entity");this.entities.delete(e.name)}getEntity(e){return this.entities.get(e)}},Z=class{scenes;ticker;get centerX(){return this.width/2}get centerY(){return this.height/2}get left(){return 0}get top(){return 0}get right(){return this.width}get bottom(){return this.height}width;height;constructor(e,n,s=16){this.ticker=new de(s),this.scenes=new Map,this.width=e,this.height=n,this.ticker.on("tick",a=>{for(let l of this.scenes.values())l.paused||l.handleUpdate(a)})}addScene(e){if(!e.name)throw new Error("Scene must have a name.");e.paused=!1,this.scenes.set(e.name,e)}removeScene(e){e&&(e.paused=!0),this.scenes.delete(e.name)}now(){return this.ticker.now()}start(){this.ticker.start()}stop(){this.ticker.stop()}},P={lerp(r,e,n){return r+(e-r)*n},clamp(r,e,n){return Math.min(n,Math.max(e,r))},clamp01(r){return Math.min(1,Math.max(0,r))},easeLinear(r){return r},easeInQuad(r){return r*r},easeOutQuad(r){return 1-(1-r)*(1-r)},easeInOutQuad(r){return r<.5?2*r*r:1-Math.pow(-2*r+2,2)/2},easeInSine(r){return 1-Math.cos(r*Math.PI/2)},easeOutSine(r){return Math.sin(r*Math.PI/2)},easeInOutSine(r){return-(Math.cos(Math.PI*r)-1)/2},easeInExpo(r){return r===0?0:Math.pow(2,10*r-10)},easeOutExpo(r){return r===1?1:1-Math.pow(2,-10*r)},easeInOutExpo(r){return r===0?0:r===1?1:r<.5?Math.pow(2,20*r-10)/2:(2-Math.pow(2,-20*r+10))/2},smoothstep(r){return r=P.clamp(r,0,1),r*r*(3-2*r)},randomLerp(r,e){return P.lerp(r,e,Math.random())},randomInt(r,e){return Math.floor(Math.random()*(e-r+1))+r},randomArrayValue(r){return r[P.randomInt(0,r.length-1)]},createBezier(r,e,n,s){function a(f,h,c,p,g){let x=1-f;return x*x*x*h+3*x*x*f*c+3*x*f*f*p+f*f*f*g}function l(f,h,c,p,g){let x=1-f;return 3*x*x*(c-h)+6*x*f*(p-c)+3*f*f*(g-p)}function d(f){let h=f;for(let c=0;c<6;c++){let p=a(h,0,r,n,1),g=l(h,0,r,n,1);if(g===0)break;h-=(p-f)/g}return P.clamp(h,0,1)}return function(h){h=P.clamp(h,0,1);let c=d(h);return a(c,0,e,s,1)}},lengthSquared(...r){return r.reduce((e,n)=>e+n*n,0)},normalizeRad(r){let e=2*Math.PI;return r=r%e,r<0&&(r+=e),r},angleInvertY(r){return P.normalizeRad(-r)},degToRadFlipY(r){return P.angleInvertY(r*Math.PI/180)},minimalAngularDirection(r,e){r=P.normalizeRad(r),e=P.normalizeRad(e);let n=P.normalizeRad(e-r),s=P.normalizeRad(r-e);return n<=s?1:-1}},fe=class extends I{constructor({delta:e,ms:n,easing:s}){super(),this.delta=e,this.duration=n,this.elapsed=0,this.easing=s??(a=>a),this.lastValue=0,this.finished=!1}delta;duration;elapsed;lastValue;finished;easing;update(e){this.elapsed+=e*1e3;let n=P.clamp(this.elapsed/this.duration,0,1),s=this.easing(n),a=this.delta*s,l=a-this.lastValue;this.lastValue=a,this.emit("delta",l),n>=1&&(this.finished=!0,this.emit("finish",void 0))}},ee=class extends N{constructor(e,n=0,s=0,a=50,l=50){super(e,n,s),this.width=a,this.height=l}width;height;get left(){return this.x-this.width/2}set left(e){this.x=e+this.width/2}get right(){return this.x+this.width/2}set right(e){this.x=e-this.width/2}get top(){return this.y-this.height/2}set top(e){this.y=e+this.height/2}get bottom(){return this.y+this.height/2}set bottom(e){this.y=e-this.height/2}get lx(){return 0}get ly(){return 0}get lleft(){return-this.width/2}get lright(){return this.width/2}get ltop(){return-this.height/2}get lbottom(){return this.height/2}isCollidingWith(e){return!(this.right<e.left||this.left>e.right||this.bottom<e.top||this.top>e.bottom)}color="rgba(0, 0, 255, 0.3)";draw(e){e.translate(this.x,this.y),e.rotate(this.scaleRotate),e.fillStyle=this.color,e.fillRect(-this.width/2,-this.height/2,this.width,this.height)}},pe=class extends I{duration;ticker;elapsed;finished;_resolve;promise;_timeoutId;constructor(e,n=null){super(),this.duration=e,this.ticker=n,this.elapsed=0,this.finished=!1,this._resolve=null,this.promise=new Promise(s=>this._resolve=s),this.update=this.update.bind(this),this.ticker&&this.ticker.on("tick",this.update)}update(e=0){this.finished||(this.elapsed+=e*1e3,this.elapsed>=this.duration&&this.finish())}finish(){this.finished||(this.finished=!0,this.emit("finish",void 0),this._resolve&&this._resolve(),this.ticker&&this.ticker.off("tick",this.update))}start(){return this.ticker||(this._timeoutId=setTimeout(()=>this.finish(),this.duration)),this}cancel(){this.finished||(this.finished=!0,!this.ticker&&this._timeoutId!=null&&clearTimeout(this._timeoutId),this.ticker&&this.ticker.off("tick",this.update))}then(e,n){return this.promise.then(e,n)}after(e,n){return this.promise.then(e,n)}},M=class r{constructor(e=0,n=0){this.x=e,this.y=n}x;y;toJSON(){return{x:this.x,y:this.y,vec2:!0}}static isVec2(e){return e&&typeof e=="object"&&"x"in e&&"y"in e&&e.vec2===!0}static fromSerialized(e){return this.isVec2(e)?new this(e.x,e.y):null}rotate(e){let n=Math.cos(e),s=Math.sin(e);return new r(this.x*n-this.y*s,this.x*s+this.y*n)}static from(e){return new r(Math.cos(e),Math.sin(e))}isEmpty(){return Math.abs(this.x)<.01&&Math.abs(this.y)<.01}get angle(){return Math.atan2(this.y,this.x)}angleTo(e){return Math.atan2(e.y-this.y,e.x-this.x)}get length(){return Math.hypot(this.x,this.y)}get lengthSquared(){return this.x*this.x+this.y*this.y}normalized(){let e=this.length;return e===0?new r(0,0):new r(this.x/e,this.y/e)}consume(e){let n=this.length;n<=e?(this.x=0,this.y=0):this.overwite(this.scale((n-e)/n))}project(e){return e.scale(this.dotNormalized(e))}reflect(e){let n=this.dot(e);return this.subtract(e.scale(2*n))}dotNormalized(e){let n=this.normalized(),s=e.normalized();return n.x*s.x+n.y*s.y}lengthSquaredTo(e){let n=this.x-e.x,s=this.y-e.y;return n*n+s*s}dot(e){return this.x*e.x+this.y*e.y}distanceTo(e){return Math.hypot(this.x-e.x,this.y-e.y)}distanceToCheap(e){let n=this.x-e.x,s=this.y-e.y;return n*n+s*s}directionTo(e){return new r(e.x-this.x,e.y-this.y).normalized()}add(e){return new r(this.x+e.x,this.y+e.y)}addRaw(e){return new r(this.x+e,this.y+e)}overwite(e){this.x=e.x,this.y=e.y}subtract(e){return new r(this.x-e.x,this.y-e.y)}scale(e){return new r(this.x*e,this.y*e)}toString(){return`Vector2(${this.x}, ${this.y})`}clone(){return new r(this.x,this.y)}};function De(){return typeof process<"u"&&process.release?.name==="node"?"node":typeof window<"u"||typeof self<"u"?"web":"unknown"}var Re=De(),U=Re==="node",k=Re==="web",X=class r{static unlock(){k&&this.audioCtx.state!=="running"&&this.audioCtx.resume()}static audioCtx=k?new AudioContext:null;static masterGain=k?this.audioCtx.createGain():null;static musicGain=k?this.audioCtx.createGain():null;static sfxGain=k?this.audioCtx.createGain():null;static{k&&(this.masterGain.gain.value=1,this.musicGain.gain.value=1,this.sfxGain.gain.value=1,this.sfxGain.connect(this.masterGain),this.musicGain.connect(this.masterGain),this.masterGain.connect(this.audioCtx.destination))}static get SFX_VOLUME(){return this.sfxGain.gain.value}static get MUSIC_VOLUME(){return this.musicGain.gain.value}static get VOLUME(){return this.masterGain.gain.value}static set SFX_VOLUME(e){this.sfxGain.gain.value=e}static set MUSIC_VOLUME(e){this.musicGain.gain.value=e}static set VOLUME(e){this.masterGain.gain.value=e}static noteToHz(e){return this.tuningFreq*Math.pow(2,(e-9)/12)}static tuningFreq=440;static audioBufferCache=new Map;static loops=new Map;static sfsx=new Map;static loopIdCounter=0;static CACHE_NAME="lia-audio-cache-v1";static async preLoad(e){if(this.audioBufferCache.has(e))return this.audioBufferCache.get(e);let n=r.CACHE_NAME,s,a;if(typeof caches<"u"&&(a=await caches.open(n),s=await a.match(e)),!s){if(s=await fetch(e),!s.ok)throw new Error(`Failed to fetch ${e}`);a&&await a.put(e,s.clone())}let l=await s.arrayBuffer(),d=await this.audioCtx.decodeAudioData(l);return this.audioBufferCache.set(e,d),d}static async getOnlyDownloadedCache(e){let n=r.CACHE_NAME;return await(await caches.open(n)).match(e)}static getCached(e){return this.audioBufferCache.get(e)||null}static async playSound(e,n=.2,s=1,a=!0){try{this.sfsx.has(e)&&this.sfsx.get(e).source.stop(),this.audioBufferCache.has(e)||await this.preLoad(e);let l=this.getCached(e);if(!l)return;let d=new O(l);d.buffer=l;let f=1-.12,h=1+.12;d.playbackRate=s??f+Math.random()*(h-f);let c=this.audioCtx.createGain();c.gain.value=n,d.tempGain=c,d.connect(c),c.connect(this.sfxGain),d.onended=()=>{d.disconnect(),c.disconnect()},d.start(),a&&this.sfsx.set(e,{source:d,gain:c})}catch(l){console.error(l)}}static async playLoop(e,n=1,{loopStart:s=0,loopEnd:a=null,exclusive:l=!0,skipMS:d=0}={}){if(l)for(let g of this.loops.keys())this.stopLoop(g);this.audioBufferCache.has(e)||await this.preLoad(e);let f=this.getCached(e);if(!f)return;let h=new O(f);h.buffer=f,h.loop=!0,typeof s=="number"&&(h.loopStart=s),typeof a=="number"&&(h.loopEnd=a);let c=this.audioCtx.createGain();c.gain.value=n,h.tempGain=c,h.playbackRate=1,h.onended=()=>{h.disconnect(),c.disconnect()},h.connect(c),c.connect(this.musicGain),h.start(0,d/1e3);let p=++this.loopIdCounter;return this.loops.set(p,{source:h,gain:c}),p}static stopLoop(e){let n=this.loops.get(e);n&&(n.source.stop(),n.source.notIndependent||(n.source.disconnect(),n.gain.disconnect()),this.loops.delete(e))}static async createLiaSource(e,{volume:n=1,speed:s=1,loop:a=!1,loopStart:l=0,loopEnd:d=null,isMusic:f=!1,gain:h=null}={}){try{this.audioBufferCache.has(e)||await this.preLoad(e);let c=this.getCached(e);if(!c)return null;let p=new O(c);p.loop=a,p.loopStart=l,p.loopEnd=typeof d=="number"?d:c.duration,p.playbackRate=s;let g=this.audioCtx.createGain();return g.gain.value=n,p.connect(g),p.tempGain=g,g.connect(h||(f?this.musicGain:this.sfxGain)),p.onended=()=>{p.disconnect(),g.disconnect()},p}catch(c){return console.error("Failed to create LiaAudioSrc:",c),null}}};var O=class{numberOfInputs;numberOfOutputs;constructor(e,n=X.audioCtx){this.context=n,this.buffer=e,this.source=null,this.startTime=0,this.pauseTime=0,this.playbackRate=1,this.isPlaying=!1,this.loop=!1,this.output=k?n.createGain():null,this.output.gain.value=1,this.channelCount=2,this.channelCountMode="max",this.channelInterpretation="speakers",this.numberOfInputs=0,this.numberOfOutputs=1,this.onended=null}channelCount;channelCountMode;channelInterpretation;onended;source;buffer;context;_createSource(){this.source&&(this.source.onended=null);let e=this.context.createBufferSource();return e.buffer=this.buffer,e.playbackRate.value=this.playbackRate,e.loop=this.loop,e.loopStart=this.loopStart,e.loopEnd=this.loopEnd>0?this.loopEnd:this.buffer.duration,e.connect(this.output),this.source=e,e.onended=()=>{this.source===e&&(this.isPlaying&&!this.loop&&(this.isPlaying=!1,this.pauseTime=0),typeof this.onended=="function"&&this.onended())},e}play({fadeIn:e=0,offset:n=null}={}){let s=n!==null?n:this.pauseTime;if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.source=this._createSource(),this.startTime=this.context.currentTime-s/this.playbackRate,this.source.start(0,s),e>0?(this.output.gain.setValueAtTime(0,this.context.currentTime),this.output.gain.linearRampToValueAtTime(1,this.context.currentTime+e)):this.output.gain.setValueAtTime(1,this.context.currentTime),this.isPlaying=!0}start(e=0,n=0,s){this.isPlaying||(this.source=this._createSource(),this.startTime=this.context.currentTime+e-n/this.playbackRate,s!==void 0?this.source.start(this.context.currentTime+e,n,s):this.source.start(this.context.currentTime+e,n),this.pauseTime=n,this.isPlaying=!0)}pause({fadeOut:e=0}={}){if(!this.isPlaying)return;let n=this.getElapsed()/1e3;if(this.loop&&this.loopEnd>this.loopStart){let s=this.loopEnd-this.loopStart;n=this.loopStart+(n-this.loopStart)%s}if(this.isPlaying=!1,e>0){let s=this.context.currentTime;this.output.gain.setValueAtTime(this.output.gain.value,s),this.output.gain.linearRampToValueAtTime(0,s+e),setTimeout(()=>{if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.pauseTime=n,this.output.gain.setValueAtTime(1,this.context.currentTime)},e*1e3)}else{if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.pauseTime=n}}getElapsed(){return this.isPlaying?(this.context.currentTime-this.startTime)*this.playbackRate*1e3:this.pauseTime*1e3}setSpeed(e){if(e<=0)throw new Error("Playback rate must be positive");let n=this.getElapsed()/1e3;this.playbackRate=e,this.isPlaying&&(this.pause(),this.pauseTime=n,this.play())}setLoop(e=!0){this.loop=e,this.source&&(this.source.loop=e)}loop;playbackRate;startTime;tempGain=null;connect(e,n=0,s=0){if("value"in e)this.output.connect(e,n);else return this.output.connect(e,n,s),e}disconnect(e,n,s){e===void 0?this.output.disconnect():this.output.disconnect(e,n,s)}output;stop(e=0){if(this.notIndependent)return this.pause();if(!this.source)return;let n=this.context.currentTime+e;this.source.stop(n),this.isPlaying=!1,this.notIndependent||(this.pauseTime=0)}pauseTime;isPlaying;notIndependent=!1;loopStart=0;loopEnd=0},Ge={osc:{enabled:!0,type:"sine",freq:440,detune:0},noise:{enabled:!1,level:.5},ampEnv:{attack:.005,decay:.1,sustain:0,release:.1,volume:.3},pitchEnv:{amount:0,decay:.2},filter:{enabled:!1,type:"lowpass",freq:1200,Q:1,envAmount:0,decay:.2},lfo:{enabled:!1,target:"freq",rate:8,depth:20},duration:.4},V=class r{constructor(e={}){this.ctx=X.audioCtx,this.cfg=structuredClone(Ge),Object.assign(this.cfg,e)}ctx;cfg;play(e=X.sfxGain){let n=this.ctx,s=n.currentTime,a=this.cfg,l=n.createGain();l.gain.setValueAtTime(1e-4,s);let d=a.ampEnv;l.gain.exponentialRampToValueAtTime(d.volume,s+d.attack),l.gain.exponentialRampToValueAtTime(Math.max(1e-4,d.sustain*d.volume),s+d.attack+d.decay),l.gain.exponentialRampToValueAtTime(1e-4,s+a.duration+d.release);let f=l,h;a.filter.enabled&&(h=n.createBiquadFilter(),h.type=a.filter.type,h.frequency.value=a.filter.freq,h.Q.value=a.filter.Q,h.connect(l),f=h);let c;if(a.osc.enabled){if(c=n.createOscillator(),c.type=a.osc.type,c.frequency.value=a.osc.freq,c.detune.value=a.osc.detune,a.pitchEnv.amount!==0){let i=Math.pow(2,a.pitchEnv.amount/12);c.frequency.exponentialRampToValueAtTime(a.osc.freq*i,s+a.pitchEnv.decay)}c.connect(f),c.start(s),c.stop(s+a.duration+d.release)}let p;if(a.noise.enabled){let i=n.sampleRate*a.duration,o=n.createBuffer(1,i,n.sampleRate),u=o.getChannelData(0);for(let y=0;y<i;y++)u[y]=(Math.random()*2-1)*a.noise.level;p=n.createBufferSource(),p.buffer=o,p.connect(f),p.start(s),p.stop(s+a.duration+d.release)}let g,x;a.lfo.enabled&&c&&(g=n.createOscillator(),g.frequency.value=a.lfo.rate,x=n.createGain(),x.gain.value=a.lfo.depth,g.connect(x),a.lfo.target==="freq"?x.connect(c.frequency):a.lfo.target==="gain"?x.connect(l.gain):a.lfo.target==="filter"&&h&&x.connect(h.frequency),g.start(s),g.stop(s+a.duration)),l.connect(e);let v=[c,p,g,x,h,l],t=s+a.duration+d.release;setTimeout(()=>{v.forEach(i=>i?.disconnect())},(t-n.currentTime)*1e3)}getConfig(){return structuredClone(this.cfg)}setConfig(e){return Object.assign(this.cfg,e),this}getKey(e){return this.cfg[e]}setKey(e,n){return Object.assign(this.cfg[e],n),this}setFreq(e){return this.cfg.osc.freq=e,this}setWave(e){return this.cfg.osc.type=e,this}setVolume(e){return this.cfg.ampEnv.volume=e,this}setAmpEnv(e,n,s,a){return Object.assign(this.cfg.ampEnv,{attack:e,decay:n,sustain:s,release:a}),this}setPitchEnv(e,n){return Object.assign(this.cfg.pitchEnv,{amount:e,decay:n}),this}setNoiseEnabled(e){return this.cfg.noise.enabled=e,this}setNoiseLevel(e){return this.cfg.noise.level=e,this}setFilterEnabled(e){return this.cfg.filter.enabled=e,this}setFilter(e,n,s){return Object.assign(this.cfg.filter,{type:e,freq:n,Q:s,enabled:!0}),this}setLFOEnabled(e){return this.cfg.lfo.enabled=e,this}setLFO(e,n,s){return Object.assign(this.cfg.lfo,{target:e,rate:n,depth:s,enabled:!0}),this}setDuration(e){return this.cfg.duration=e,this}clone(){return new r(structuredClone(this.cfg))}},mt=new V({osc:{enabled:!0,type:"square",freq:900,detune:0},ampEnv:{attack:.002,decay:.04,sustain:0,release:.02,volume:.15},duration:.05}),yt=new V({osc:{enabled:!0,type:"sine",freq:600,detune:0},ampEnv:{attack:.01,decay:.08,sustain:0,release:.04,volume:.12},duration:.1}),bt=new V({osc:{enabled:!0,type:"triangle",freq:500,detune:0},pitchEnv:{amount:12,decay:.15},ampEnv:{attack:.01,decay:.12,sustain:0,release:.05,volume:.25},duration:.18}),gt=new V({osc:{enabled:!0,type:"sawtooth",freq:1200,detune:0},pitchEnv:{amount:-24,decay:.3},ampEnv:{attack:.005,decay:.25,sustain:0,release:.05,volume:.3},duration:.35}),xt=new V({osc:{enabled:!0,type:"square",freq:180,detune:0},noise:{enabled:!0,level:.4},ampEnv:{attack:.002,decay:.15,sustain:0,release:.05,volume:.35},duration:.2});function me(r=12){let e=Date.now().toString(36),n=crypto.getRandomValues(new Uint8Array(4)),s=Array.from(n).map(a=>a.toString(36).padStart(2,"0")).join("");return(e+s).slice(0,r)}function ze(r){let e=!0;function n(){e&&(r(),requestAnimationFrame(n))}return requestAnimationFrame(n),{clear:()=>e=!1}}function He(){return U?!1:/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)}var vt=He();function Ue({width:r,height:e,updateHz:n="frames"}){return new G.KaylaGame(r,e,n==="frames"?1/0:n)}function $e(r){let e=new J(r);return new G.KaylaScene(e)}function Oe(r){return new G.KaylaRenderer(r)}function ne(r,e){if(typeof r!="function")throw new Error("Invalid Element Type.");let n=e??{};return n.key??=r.name+"_"+me(),{type:r,props:n}}var L;(s=>{function r(a,l){return!(a.right<l.left||a.left>l.right||a.bottom<l.top||a.top>l.bottom)}s.rawCollision=r;function e(a,l,d){let f=l*Math.PI/180,h=Math.cos(f),c=Math.sin(f),p=1/0;return h>0&&(p=Math.min(p,(d.right-a.x)/h)),h<0&&(p=Math.min(p,(d.left-a.x)/h)),c>0&&(p=Math.min(p,(d.bottom-a.y)/c)),c<0&&(p=Math.min(p,(d.top-a.y)/c)),M.from(l).scale(p)}s.getCurrToBound=e;function n(a){let{left:l,right:d,top:f,bottom:h,width:c,height:p,x:g=0,y:x=0}=a;if(c===null||p===null)throw new Error("width and height are required");let v,t;if(l!=null&&d!=null){if(Math.abs(d-l-c)>1e-6)throw new Error("left, right, and width mismatch");v=l}else g!=null?v=g-c/2:l!=null?v=l:d!=null?v=d-c:v=0;if(f!=null&&h!=null){if(Math.abs(h-f-p)>1e-6)throw new Error("top, bottom, and height mismatch");t=f}else x!=null?t=x-p/2:f!=null?t=f:h!=null?t=h-p:t=0;return{left:v,right:v+c,top:t,bottom:t+p,width:c,height:p,x:v+c/2,y:t+p/2}}s.createRawRect=n})(L||={});var G;(x=>{class r extends Z{#e;#t;constructor(t,i,o){super(t,i,o),this.#e=new Set,this.#t=!1}delay(t){return this.ticker.createTimeout(t)}get started(){return this.#t}start(){if(!this.#t){for(let t of this.#e)t.start();this.#t=!0,super.start()}}stop(){if(this.#t){for(let t of this.#e)t.stop();this.#t=!1,super.stop()}}addRenderer(t){this.#e.has(t)||(this.#e.add(t),this.#t&&t.start(),t.game=this)}get mainRenderer(){return[...this.#e].at(0)}getRenderers(){return[...this.#e]}deleteRenderer(t){this.#e.has(t)&&(this.#e.delete(t),this.#t&&t.stop(),delete t.game)}}x.KaylaGame=r;class e extends Q{game;pointerX;pointerY;pointerEvents;onPointerDown;onPointerUp;onPointerCancel;onPointerMove;constructor(t){super(t),this.useDraw=this.useDraw.bind(this),this.on("draw",i=>{if(this.game)for(let o of this.game.scenes.values())o.handleDraw(i)}),this.pointerX=0,this.pointerY=0,this.pointerEvents=new I,this.pointerPosUpdater=this.pointerPosUpdater.bind(this),this.onPointerDown=i=>this.onPointerAll(i,"down"),this.onPointerUp=i=>this.onPointerAll(i,"up"),this.onPointerCancel=i=>this.onPointerAll(i,"cancel"),this.onPointerMove=i=>this.onPointerAll(i,"move")}pointerPosUpdater(t){this.pointerX=t.clientX,this.pointerY=t.clientY}onPointerAll(t,i){this.pointerPosUpdater(t);let o=e.getClickType(t);if(o!=="invalid"||i==="move"||i==="cancel"){t.preventDefault();let u=this.getMousePos();this.pointerEvents.emit("action",u,o,i)}}static getClickType(t){switch(t.button){case 0:return"left";case 1:return"middle";case 2:return"right";default:return"invalid"}}listenPointerUpdates(){this.canvas.addEventListener("pointermove",this.pointerPosUpdater),this.canvas.addEventListener("pointerdown",this.onPointerDown),this.canvas.addEventListener("pointerup",this.onPointerUp),this.canvas.addEventListener("pointercancel",this.onPointerCancel),this.canvas.addEventListener("pointermove",this.onPointerMove)}unlistenPointerUpdates(){this.canvas.removeEventListener("pointermove",this.pointerPosUpdater),this.canvas.removeEventListener("pointerdown",this.onPointerDown),this.canvas.removeEventListener("pointerup",this.onPointerUp),this.canvas.removeEventListener("pointermove",this.onPointerMove)}pointerPosToWorldPos(t,i){let o=this.canvas.getBoundingClientRect(),u=(t-o.left)/o.width,y=(i-o.top)/o.height,b=u*this.viewportWidth*this.cameraWidth/o.width,C=y*this.viewportHeight*this.cameraHeight/o.height;return new M(b,C)}getMousePos(){return this.pointerPosToWorldPos(this.pointerX,this.pointerY)}useDraw(t){let i=o=>{t(o,new s)};return this.on("draw",i),()=>{this.off("draw",i)}}attachTo(t){t.addRenderer(this),this.game=t}detach(){this.game&&this.game.deleteRenderer(this)}}x.KaylaRenderer=e;class n{current;saves;constructor(){this.saves=[]}useTick(t){if(!this.current)throw new Error("Hook 'useTick' must be executed in the top level scope of a component.");this.current.onTick[this.current.useStepCallIndex]=t,this.current.useStepCallIndex++}usePaint(t){if(!this.current)throw new Error("Hook 'usePaint' must be executed in the top level scope of a component.");this.current.onPaint[this.current.useDrawCallIndex]=t,this.current.useDrawCallIndex++}useEntity(){if(!this.current)throw new Error("Hook 'useEntity' must be executed in the top level scope of a component.");return ye(be)}useSelf(t){if(!this.current)throw new Error("Hook 'useSelf' must be executed in the top level scope of a component.");let i=ye(null);return(i.current===null||i.current===void 0)&&(i.current=t()),i.current}useInitialization(t){if(!this.current)throw new Error("Hook 'useInitialization' must be executed in the top level scope of a component.");let i=this.current;i.onInits[this.current.useInitCallIndex]=t,i.useInitCallIndex++}useRect(){if(!this.current)throw new Error("Hook 'useRect' must be executed in the top level scope of a component.");return D(()=>new x.KaylaInternalRect(this.current))}useFiber(){if(!this.current)throw new Error("Hook 'useFiber' must be executed in the top level scope of a component.");return D(()=>this.current)}useFiberControl(){if(!this.current)throw new Error("Hook 'useFiberControl' must be executed in the top level scope of a component.");let t=this.current;return D(()=>({refresh:()=>t.refresh(),get childrenCount(){return t.lastChildren.length},setMaxChildren:i=>{t.setMaxChildren(i)},getMaxChildren:()=>t.getMaxChildren(),get maxSafeChildren(){return t.maxSafeChildren},get key(){return t.key},get getChildrenEntities(){return t.getChildrenEntities.bind(t)},get getEntityChain(){return t.getEntityChain.bind(t)},get getFiberChain(){return t.getFiberChain.bind(t)}}))}useCurrentTicker(){if(!this.current)throw new Error("Hook 'useCurrentTicker' must be executed in the top level scope of a component.");return this.current.getAttachedGame().ticker}useCurrentRenderer(){if(!this.current)throw new Error("Hook 'useCurrentRenderer' must be executed in the top level scope of a component.");return this.current.getAttachedGame().mainRenderer}useCurrentGame(){if(!this.current)throw new Error("Hook 'useCurrentGame' must be executed in the top level scope of a component.");return this.current.getAttachedGame()}useCurrentScene(){if(!this.current)throw new Error("Hook 'useCurrentScene' must be executed in the top level scope of a component.");return this.current.scene}useState(t,{alwaysRecall:i=!1}={}){if(!this.current)throw new Error("Hook 'useState' must be executed in the top level scope of a component.");let u=this.current.state[this.current.useStateCallIndex]??new a(this.current,t,{alwaysRecall:i});return this.current.state[this.current.useStateCallIndex]=u,this.current.useStateCallIndex++,u}useShouldRefresh(t){let i=this.current;if(!i)throw new Error("useShouldRefresh must be called inside a component");i.watchedDeps&&console.warn("useShouldRefresh called multiple times \u2014 using the last call"),i.watchedDeps=t}useRef(t){if(!this.current)throw new Error("Hook 'useRef' must be executed in the top level scope of a component.");let o=this.current.refs[this.current.useRefCallIndex]??d(t??null);return this.current.refs[this.current.useRefCallIndex]=o,this.current.useRefCallIndex++,o}useEffect(t){if(!this.current)throw new Error("Hook 'useEffect' must be executed in the top level scope of a component.");this.current.onEffect[this.current.useEffectCallIndex]=t,this.current.useEffectCallIndex++}useViewportEffect(t){if(!this.current)throw new Error("Hook 'useViewport' must be executed in the top level scope of a component.");this.current.onViewportEffect[this.current.useViewCallIndex]=t,this.current.useViewCallIndex++}useExports(t,i){if(!this.current)throw new Error("Hook 'useExports' must be executed in the top level scope of a component.");this.current.onExport=i}useGlobalPointer(t,i){if(!this.current)throw new Error("Hook 'useGlobalPointer/useGlobalClick' must be executed in the top level scope of a component.");i??={},this.current.onGlobalPointer[this.current.useGlobalClickCallIndex]={handler:t,config:i},this.current.useGlobalClickCallIndex++}usePointer(t,i){if(!this.current)throw new Error("Hook 'usePointer/useClick' must be executed in the top level scope of a component.");i??={};let o=this.current;Te((u,y,b)=>{let C=o.entity;if(!C)return;let E=C.getRawRect(),z=L.createRawRect({x:u.x,y:u.y,width:3,height:3});L.rawCollision(E,z)&&t(u,y,b)},i)}useContext(t){if(!this.current)throw new Error("Hook 'useContext' must be executed in the top level scope of a component.");return this.current.findContextValueFromInst(t)}save(){this.saves.push({current:this.current})}restore(){let t=this.saves.pop();if(!t)throw new Error("Cannot restore without saving.");this.current=t.current}logLevel="warn";logger={debug:(...t)=>{this.logLevel==="debug"&&console.debug(...t)},info:(...t)=>{["info","warn","debug"].includes(this.logLevel)&&console.info(...t)},warn:(...t)=>{["warn","debug"].includes(this.logLevel)&&console.warn(...t)},error:(...t)=>console.error(...t),withFiber:(t,i,o,...u)=>{let y=t?.fc?.name||"anonymous",b=t?.key?` key=${t.key}`:"";this.logger[i](`${o} <${y}${b}>`,...u)}}}x.GlobalKayla=n;class s{preventDefault(){this.#e=!0}#e=!1;isPrevented(){return this.#e}}x.KaylaEvent=s;class a{#e;#t;#n;alwaysRecall;constructor(t,i,{alwaysRecall:o=!1}={}){this.#t=t,this.#e=i??void 0,this.#n=Date.now(),this.alwaysRecall=o}get(){return this.#e}*[Symbol.iterator](){throw new Error(`Hey! KaylaState is NOT an array / iterable like useState in React.
|
|
1
|
+
"use strict";var ce=Object.defineProperty;var Fe=Object.getOwnPropertyDescriptor;var Me=Object.getOwnPropertyNames;var Ae=Object.prototype.hasOwnProperty;var Ke=(r,e)=>{for(var n in e)ce(r,n,{get:e[n],enumerable:!0})},Le=(r,e,n,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of Me(e))!Ae.call(r,a)&&a!==n&&ce(r,a,{get:()=>e[a],enumerable:!(s=Fe(e,a))||s.enumerable});return r};var _e=r=>Le(ce({},"__esModule",{value:!0}),r);var dt={};Ke(dt,{Fragment:()=>ct,jsx:()=>ut,jsxDEV:()=>ht,jsxs:()=>Ie});module.exports=_e(dt);var Ee={};Ke(Ee,{JSX:()=>Se,KMatrix2D:()=>ge,KaylaContext:()=>te,KaylaFragment:()=>Ce,KaylaInternals:()=>G,KaylaRect:()=>L,Layer:()=>ot,createContext:()=>Ne,createElement:()=>ne,createGame:()=>Ue,createReassignableObject:()=>it,createRenderer:()=>Oe,createScene:()=>$e,createUseHook:()=>at,self:()=>be,setLogLevel:()=>st,useClick:()=>je,useContext:()=>nt,useCurrentGame:()=>Ze,useCurrentRenderer:()=>et,useCurrentScene:()=>Pe,useCurrentTicker:()=>tt,useDisposableRef:()=>rt,useEffect:()=>re,useEntity:()=>Je,useExports:()=>oe,useFiber:()=>ve,useFiberControl:()=>xe,useGlobalClick:()=>Te,useGlobalPointer:()=>We,useInitialization:()=>ie,useNextStack:()=>we,usePaint:()=>ae,usePointer:()=>Ye,useRect:()=>se,useRef:()=>ye,useSelf:()=>D,useShouldRefresh:()=>qe,useState:()=>Xe,useTick:()=>Qe,useViewportEffect:()=>Be});var I=class{#e=new Map;constructor(){this.#e=new Map}on(e,n){let s=this.#e.get(e)||[];return s.push(n),this.#e.set(e,s),this}once(e,n){let s=(...a)=>{this.off(e,s),n(...a)};return this.on(e,s),this}off(e,n){let s=this.#e.get(e);if(!s)return this;let a=s.indexOf(n);return a>=0&&s.splice(a,1),this}emit(e,...n){let s=this.#e.get(e);if(!s||s.length===0){if(e==="error")throw n[0];return!1}return s.slice().forEach(a=>a(...n)),!0}removeAllListeners(e){return e?this.#e.delete(e):this.#e.clear(),this}listenerCount(e){return this.#e.get(e)?.length??0}},Q=class extends I{#e;#t;running;_rafId;_fps;_frameCount;_fpsTimer;_lastFrameTime;get canvas(){return this.#e}get ctx(){return this.#t}set canvas(e){this.#e=e,this.#t=e.getContext("2d"),this.updateCanvasResolution()}constructor(e,{viewportWidth:n,viewportHeight:s,cameraWidth:a,cameraHeight:l}={}){if(!k)throw new Error("Web-Only");super(),this.canvas=e,this.automatic=!0,this.#n=n??e.width,this.#r=s??e.height,this.#i=a??e.width,this.#s=l??e.height,this.running=!1,this._rafId=null,this._loop=this._loop.bind(this),this.updateCanvasResolution(),this._fps=60,this._frameCount=0,this._fpsTimer=0}automatic;retransform(){this.ctx.setTransform(1,0,0,1,0,0);let e=this.#i/this.#n,n=this.#s/this.#r;this.ctx.translate(this.#i/2,this.#s/2),this.ctx.scale(e,n),this.ctx.translate(-this.#n/2,-this.#r/2)}#n=0;#r=0;#i=0;#s=0;get viewportWidth(){return this.#n}set viewportWidth(e){this.#n=e,this.retransform(),this.emitViewportUpdate()}get width(){return this.#n}get height(){return this.#r}get centerX(){return this.#n/2}get centerY(){return this.#r/2}get left(){return 0}get top(){return 0}get right(){return this.#n}get bottom(){return this.#r}get viewportHeight(){return this.#r}set viewportHeight(e){this.#r=e,this.retransform(),this.emitViewportUpdate()}get cameraWidth(){return this.#i}set cameraWidth(e){this.#i=e,this.updateCanvasResolution(),this.retransform()}get cameraHeight(){return this.#s}set cameraHeight(e){this.#s=e,this.updateCanvasResolution(),this.retransform()}updateCanvasResolution(){this.canvas.width=this.#i,this.canvas.height=this.#s}emitViewportUpdate(){this.emit("viewport_update",{width:this.viewportWidth,height:this.viewportHeight})}applyTransform(){this.retransform()}get FPS(){return this._fps}_loop(){this.automatic&&this.update(),this._rafId=requestAnimationFrame(this._loop)}update(){if(!this.running||!k)return;let e=performance.now(),n=(e-(this._lastFrameTime??e))/1e3;this._lastFrameTime=e,this._frameCount++,this._fpsTimer+=n,this._fpsTimer>=1&&(this._fps=Math.round(this._frameCount/this._fpsTimer),this._frameCount=0,this._fpsTimer=0),this.ctx.clearRect(0,0,this.#i,this.#s),this.emit("draw",this.ctx)}start(){if(!this.running){if(!k||typeof globalThis.requestAnimationFrame>"u")throw new Error("Raf is not supported");this.running=!0,this._rafId=requestAnimationFrame(this._loop)}}stop(){if(!k||typeof globalThis.requestAnimationFrame>"u")throw new Error("Raf is not supported");this.running=!1,this._rafId!==null&&(cancelAnimationFrame(this._rafId),this._rafId=null)}},de=class extends I{setNow(e){this.#e=e}#e=0;__intervalId=null;__lastTime=0;constructor(e=16){super(),this.#t=e,this.speedHackDT=1}speedHackDT;get isRaf(){return this.tickInterval===1/0}#t=15;get tickInterval(){return this.#t}set tickInterval(e){this.#t=e,this.__intervalId&&(this.stop(),this.start())}now(){return this.#e}__tick(){let e=performance.now(),n=(e-this.__lastTime)/1e3*this.speedHackDT;this.__lastTime=e,!(k&&typeof this.__intervalId=="function"&&document.hidden)&&(this.#e+=n*1e3,this.emit("tick",n))}createTimeout(e){return new pe(e,this)}createTween(e,n=()=>{}){let s=new fe(e),a=(l=0)=>{if(s.finished){this.off("tick",a);return}s.update(l)};return s.on("finish",()=>{this.off("tick",a)}),s.on("delta",l=>{n(l)}),this.on("tick",a),s}start(){this.__intervalId===null&&(this.__lastTime=performance.now(),this.__intervalId=k&&!isFinite(this.tickInterval)?ze(()=>this.__tick()).clear:setInterval(()=>this.__tick(),this.tickInterval))}stop(){this.__intervalId!==null&&(typeof this.__intervalId=="function"?this.__intervalId():clearInterval(this.__intervalId)),this.__intervalId=null}getSineMod(e,n=0){return .5+.5*Math.sin((this.now()%e/e+n)*2*Math.PI)}},Ve;(t=>{function r(i){return i===!0?1:0}t.booleanExport=r;function e(i){return i===0?!1:i===1}t.booleanImport=e;function n(i){return`${i.x}|${i.y}`}t.vec2Export=n;function s(i){let[o,u]=i.split("|"),y=parseFloat(o),b=parseFloat(u);if(isNaN(y)||isNaN(b))throw new Error(`Invalid Vector2 string: ${i}`);return new M(y,b)}t.vec2Import=s,t.booleanMap={mapExport:r,mapImport:e};function l(i){return o=>Number(o.toFixed(i))}t.createRounder=l;function d(i=10){return{mapExport(o){return Math.round(o/i)},mapImport(o){return o*i}}}t.createLowPrecision=d;function f(i){return Math.round(i)}t.lightWeightRounder=f;function h(i=100){return{mapExport(o){return Math.round(o*i)},mapImport(o){return o/i}}}t.createPercent=h;function c(i){let o=new Map(Object.entries(i));return{mapExport:u=>o.get(u)??null,mapImport:u=>Array.from(o.entries()).find(([y,b])=>b===u)?.[0]??null}}t.createLookup=c;function p(i){let o=i*(180/Math.PI);return Math.round((o%360+360)%360)}t.radToDeg=p;function g(i){return i*(Math.PI/180)}t.degToRad=g,t.angleRadToDeg={mapExport:p,mapImport:g};function v(i=10){let o=d(i);return{mapExport(u){return o.mapExport(p(u))},mapImport(u){return o.mapImport(g(u))}}}t.createLowPrecisionRadToDeg=v})(Ve||={});var N=class r extends I{name="";scaleRotate=0;scale=1;constructor(e,n=0,s=0){super(),this.autoTranslate=!1,this.name=e,this.z=0,this.___pos=new M(n,s),this.nonSerializableProperties=[],this.nonSerializableProperties.push("___pos","autoTranslate","arraySerializeMap"),this.forceSerializableProperties=[],this.forceSerializableProperties.push("x","y")}arraySerializeMap;autoTranslate;z;___pos;nonSerializableProperties;forceSerializableProperties;get pos(){return this.___pos}get x(){return this.pos.x}get y(){return this.pos.y}set x(e){this.pos.x=e}set y(e){this.pos.y=e}handleUpdate(e){if(this.update)try{this.emit("update",e),this.update(e)}catch(n){this.emit("error",n)}}handleDraw(e){if(!(U||!this.draw)){e.save(),this.autoTranslate&&e.translate(this.x,this.y);try{this.emit("draw",e),this.draw(e)}catch(n){this.emit("error",n)}e.restore()}}serialize(){if(Array.isArray(this.arraySerializeMap))return this.arraySerializeMap.map(([a,{mapExport:l}])=>{let d=Reflect.get(this,a);return l?l(d):d});let e=["_events","_eventsCount","_maxListeners","nonSerializableProperties","forceSerializableProperties"],n=[...Reflect.ownKeys(this),...this.forceSerializableProperties].filter(a=>!this.nonSerializableProperties.includes(a)&&!e.includes(a.toString())),s=Object.fromEntries(n.map(a=>{let l=Reflect.get(this,a);if(U&&typeof l=="number"){let d=l.toString().split("."),h=(d[1]?d[1].length:0)>2?Number(l.toFixed(2)):l;return[a,h]}return[a,l]}));return JSON.parse(JSON.stringify(s))}toLocal(e){return e.subtract(this.pos)}toWorld(e){return e.add(this.pos)}deserializeArray(e){return r.deserializeArray(this.arraySerializeMap,e)}static deserializeArray(e,n){if(!e||!Array.isArray(n))return n;let s={};for(let a=0;a<n.length;a++){let l=e[a];if(!l)break;let[d,{mapImport:f}]=l,h=n[a];if(f&&(h=f(h)),typeof d!="string")break;try{Reflect.set(s,d,h)}catch(c){console.error(c)}}return s}},J=class extends I{name="";entities=new Map;paused=!0;constructor(e){super(),this.name=e}handleUpdate(e){if(!this.paused){this.emit("update",e);for(let n of this.entities.values())n.handleUpdate(e)}}handleDraw(e){if(!U&&!this.paused){this.emit("draw",e);for(let n of[...this.entities.values()].sort((s,a)=>s.z-a.z))n.handleDraw(e)}}addEntity(e){if(!(e instanceof N))throw new Error("invalid entity");if(!e.name)throw new Error("Entity must have a name.");this.entities.set(e.name,e)}removeEntity(e){if(!(e instanceof N))throw new Error("invalid entity");this.entities.delete(e.name)}getEntity(e){return this.entities.get(e)}},Z=class{scenes;ticker;get centerX(){return this.width/2}get centerY(){return this.height/2}get left(){return 0}get top(){return 0}get right(){return this.width}get bottom(){return this.height}width;height;constructor(e,n,s=16){this.ticker=new de(s),this.scenes=new Map,this.width=e,this.height=n,this.ticker.on("tick",a=>{for(let l of this.scenes.values())l.paused||l.handleUpdate(a)})}addScene(e){if(!e.name)throw new Error("Scene must have a name.");e.paused=!1,this.scenes.set(e.name,e)}removeScene(e){e&&(e.paused=!0),this.scenes.delete(e.name)}now(){return this.ticker.now()}start(){this.ticker.start()}stop(){this.ticker.stop()}},P={lerp(r,e,n){return r+(e-r)*n},clamp(r,e,n){return Math.min(n,Math.max(e,r))},clamp01(r){return Math.min(1,Math.max(0,r))},easeLinear(r){return r},easeInQuad(r){return r*r},easeOutQuad(r){return 1-(1-r)*(1-r)},easeInOutQuad(r){return r<.5?2*r*r:1-Math.pow(-2*r+2,2)/2},easeInSine(r){return 1-Math.cos(r*Math.PI/2)},easeOutSine(r){return Math.sin(r*Math.PI/2)},easeInOutSine(r){return-(Math.cos(Math.PI*r)-1)/2},easeInExpo(r){return r===0?0:Math.pow(2,10*r-10)},easeOutExpo(r){return r===1?1:1-Math.pow(2,-10*r)},easeInOutExpo(r){return r===0?0:r===1?1:r<.5?Math.pow(2,20*r-10)/2:(2-Math.pow(2,-20*r+10))/2},smoothstep(r){return r=P.clamp(r,0,1),r*r*(3-2*r)},randomLerp(r,e){return P.lerp(r,e,Math.random())},randomInt(r,e){return Math.floor(Math.random()*(e-r+1))+r},randomArrayValue(r){return r[P.randomInt(0,r.length-1)]},createBezier(r,e,n,s){function a(f,h,c,p,g){let x=1-f;return x*x*x*h+3*x*x*f*c+3*x*f*f*p+f*f*f*g}function l(f,h,c,p,g){let x=1-f;return 3*x*x*(c-h)+6*x*f*(p-c)+3*f*f*(g-p)}function d(f){let h=f;for(let c=0;c<6;c++){let p=a(h,0,r,n,1),g=l(h,0,r,n,1);if(g===0)break;h-=(p-f)/g}return P.clamp(h,0,1)}return function(h){h=P.clamp(h,0,1);let c=d(h);return a(c,0,e,s,1)}},lengthSquared(...r){return r.reduce((e,n)=>e+n*n,0)},normalizeRad(r){let e=2*Math.PI;return r=r%e,r<0&&(r+=e),r},angleInvertY(r){return P.normalizeRad(-r)},degToRadFlipY(r){return P.angleInvertY(r*Math.PI/180)},minimalAngularDirection(r,e){r=P.normalizeRad(r),e=P.normalizeRad(e);let n=P.normalizeRad(e-r),s=P.normalizeRad(r-e);return n<=s?1:-1}},fe=class extends I{constructor({delta:e,ms:n,easing:s}){super(),this.delta=e,this.duration=n,this.elapsed=0,this.easing=s??(a=>a),this.lastValue=0,this.finished=!1}delta;duration;elapsed;lastValue;finished;easing;update(e){this.elapsed+=e*1e3;let n=P.clamp(this.elapsed/this.duration,0,1),s=this.easing(n),a=this.delta*s,l=a-this.lastValue;this.lastValue=a,this.emit("delta",l),n>=1&&(this.finished=!0,this.emit("finish",void 0))}},ee=class extends N{constructor(e,n=0,s=0,a=50,l=50){super(e,n,s),this.width=a,this.height=l}width;height;get left(){return this.x-this.width/2}set left(e){this.x=e+this.width/2}get right(){return this.x+this.width/2}set right(e){this.x=e-this.width/2}get top(){return this.y-this.height/2}set top(e){this.y=e+this.height/2}get bottom(){return this.y+this.height/2}set bottom(e){this.y=e-this.height/2}get lx(){return 0}get ly(){return 0}get lleft(){return-this.width/2}get lright(){return this.width/2}get ltop(){return-this.height/2}get lbottom(){return this.height/2}isCollidingWith(e){return!(this.right<e.left||this.left>e.right||this.bottom<e.top||this.top>e.bottom)}color="rgba(0, 0, 255, 0.3)";draw(e){e.translate(this.x,this.y),e.rotate(this.scaleRotate),e.fillStyle=this.color,e.fillRect(-this.width/2,-this.height/2,this.width,this.height)}},pe=class extends I{duration;ticker;elapsed;finished;_resolve;promise;_timeoutId;constructor(e,n=null){super(),this.duration=e,this.ticker=n,this.elapsed=0,this.finished=!1,this._resolve=null,this.promise=new Promise(s=>this._resolve=s),this.update=this.update.bind(this),this.ticker&&this.ticker.on("tick",this.update)}update(e=0){this.finished||(this.elapsed+=e*1e3,this.elapsed>=this.duration&&this.finish())}finish(){this.finished||(this.finished=!0,this.emit("finish",void 0),this._resolve&&this._resolve(),this.ticker&&this.ticker.off("tick",this.update))}start(){return this.ticker||(this._timeoutId=setTimeout(()=>this.finish(),this.duration)),this}cancel(){this.finished||(this.finished=!0,!this.ticker&&this._timeoutId!=null&&clearTimeout(this._timeoutId),this.ticker&&this.ticker.off("tick",this.update))}then(e,n){return this.promise.then(e,n)}after(e,n){return this.promise.then(e,n)}},M=class r{constructor(e=0,n=0){this.x=e,this.y=n}x;y;toJSON(){return{x:this.x,y:this.y,vec2:!0}}static isVec2(e){return e&&typeof e=="object"&&"x"in e&&"y"in e&&e.vec2===!0}static fromSerialized(e){return this.isVec2(e)?new this(e.x,e.y):null}rotate(e){let n=Math.cos(e),s=Math.sin(e);return new r(this.x*n-this.y*s,this.x*s+this.y*n)}static from(e){return new r(Math.cos(e),Math.sin(e))}isEmpty(){return Math.abs(this.x)<.01&&Math.abs(this.y)<.01}get angle(){return Math.atan2(this.y,this.x)}angleTo(e){return Math.atan2(e.y-this.y,e.x-this.x)}get length(){return Math.hypot(this.x,this.y)}get lengthSquared(){return this.x*this.x+this.y*this.y}normalized(){let e=this.length;return e===0?new r(0,0):new r(this.x/e,this.y/e)}consume(e){let n=this.length;n<=e?(this.x=0,this.y=0):this.overwite(this.scale((n-e)/n))}project(e){return e.scale(this.dotNormalized(e))}reflect(e){let n=this.dot(e);return this.subtract(e.scale(2*n))}dotNormalized(e){let n=this.normalized(),s=e.normalized();return n.x*s.x+n.y*s.y}lengthSquaredTo(e){let n=this.x-e.x,s=this.y-e.y;return n*n+s*s}dot(e){return this.x*e.x+this.y*e.y}distanceTo(e){return Math.hypot(this.x-e.x,this.y-e.y)}distanceToCheap(e){let n=this.x-e.x,s=this.y-e.y;return n*n+s*s}directionTo(e){return new r(e.x-this.x,e.y-this.y).normalized()}add(e){return new r(this.x+e.x,this.y+e.y)}addRaw(e){return new r(this.x+e,this.y+e)}overwite(e){this.x=e.x,this.y=e.y}subtract(e){return new r(this.x-e.x,this.y-e.y)}scale(e){return new r(this.x*e,this.y*e)}toString(){return`Vector2(${this.x}, ${this.y})`}clone(){return new r(this.x,this.y)}};function De(){return typeof process<"u"&&process.release?.name==="node"?"node":typeof window<"u"||typeof self<"u"?"web":"unknown"}var Re=De(),U=Re==="node",k=Re==="web",X=class r{static unlock(){k&&this.audioCtx.state!=="running"&&this.audioCtx.resume()}static audioCtx=k?new AudioContext:null;static masterGain=k?this.audioCtx.createGain():null;static musicGain=k?this.audioCtx.createGain():null;static sfxGain=k?this.audioCtx.createGain():null;static{k&&(this.masterGain.gain.value=1,this.musicGain.gain.value=1,this.sfxGain.gain.value=1,this.sfxGain.connect(this.masterGain),this.musicGain.connect(this.masterGain),this.masterGain.connect(this.audioCtx.destination))}static get SFX_VOLUME(){return this.sfxGain.gain.value}static get MUSIC_VOLUME(){return this.musicGain.gain.value}static get VOLUME(){return this.masterGain.gain.value}static set SFX_VOLUME(e){this.sfxGain.gain.value=e}static set MUSIC_VOLUME(e){this.musicGain.gain.value=e}static set VOLUME(e){this.masterGain.gain.value=e}static noteToHz(e){return this.tuningFreq*Math.pow(2,(e-9)/12)}static tuningFreq=440;static audioBufferCache=new Map;static loops=new Map;static sfsx=new Map;static loopIdCounter=0;static CACHE_NAME="lia-audio-cache-v1";static async preLoad(e){if(this.audioBufferCache.has(e))return this.audioBufferCache.get(e);let n=r.CACHE_NAME,s,a;if(typeof caches<"u"&&(a=await caches.open(n),s=await a.match(e)),!s){if(s=await fetch(e),!s.ok)throw new Error(`Failed to fetch ${e}`);a&&await a.put(e,s.clone())}let l=await s.arrayBuffer(),d=await this.audioCtx.decodeAudioData(l);return this.audioBufferCache.set(e,d),d}static async getOnlyDownloadedCache(e){let n=r.CACHE_NAME;return await(await caches.open(n)).match(e)}static getCached(e){return this.audioBufferCache.get(e)||null}static async playSound(e,n=.2,s=1,a=!0){try{this.sfsx.has(e)&&this.sfsx.get(e).source.stop(),this.audioBufferCache.has(e)||await this.preLoad(e);let l=this.getCached(e);if(!l)return;let d=new O(l);d.buffer=l;let f=1-.12,h=1+.12;d.playbackRate=s??f+Math.random()*(h-f);let c=this.audioCtx.createGain();c.gain.value=n,d.tempGain=c,d.connect(c),c.connect(this.sfxGain),d.onended=()=>{d.disconnect(),c.disconnect()},d.start(),a&&this.sfsx.set(e,{source:d,gain:c})}catch(l){console.error(l)}}static async playLoop(e,n=1,{loopStart:s=0,loopEnd:a=null,exclusive:l=!0,skipMS:d=0}={}){if(l)for(let g of this.loops.keys())this.stopLoop(g);this.audioBufferCache.has(e)||await this.preLoad(e);let f=this.getCached(e);if(!f)return;let h=new O(f);h.buffer=f,h.loop=!0,typeof s=="number"&&(h.loopStart=s),typeof a=="number"&&(h.loopEnd=a);let c=this.audioCtx.createGain();c.gain.value=n,h.tempGain=c,h.playbackRate=1,h.onended=()=>{h.disconnect(),c.disconnect()},h.connect(c),c.connect(this.musicGain),h.start(0,d/1e3);let p=++this.loopIdCounter;return this.loops.set(p,{source:h,gain:c}),p}static stopLoop(e){let n=this.loops.get(e);n&&(n.source.stop(),n.source.notIndependent||(n.source.disconnect(),n.gain.disconnect()),this.loops.delete(e))}static async createLiaSource(e,{volume:n=1,speed:s=1,loop:a=!1,loopStart:l=0,loopEnd:d=null,isMusic:f=!1,gain:h=null}={}){try{this.audioBufferCache.has(e)||await this.preLoad(e);let c=this.getCached(e);if(!c)return null;let p=new O(c);p.loop=a,p.loopStart=l,p.loopEnd=typeof d=="number"?d:c.duration,p.playbackRate=s;let g=this.audioCtx.createGain();return g.gain.value=n,p.connect(g),p.tempGain=g,g.connect(h||(f?this.musicGain:this.sfxGain)),p.onended=()=>{p.disconnect(),g.disconnect()},p}catch(c){return console.error("Failed to create LiaAudioSrc:",c),null}}};var O=class{numberOfInputs;numberOfOutputs;constructor(e,n=X.audioCtx){this.context=n,this.buffer=e,this.source=null,this.startTime=0,this.pauseTime=0,this.playbackRate=1,this.isPlaying=!1,this.loop=!1,this.output=k?n.createGain():null,this.output.gain.value=1,this.channelCount=2,this.channelCountMode="max",this.channelInterpretation="speakers",this.numberOfInputs=0,this.numberOfOutputs=1,this.onended=null}channelCount;channelCountMode;channelInterpretation;onended;source;buffer;context;_createSource(){this.source&&(this.source.onended=null);let e=this.context.createBufferSource();return e.buffer=this.buffer,e.playbackRate.value=this.playbackRate,e.loop=this.loop,e.loopStart=this.loopStart,e.loopEnd=this.loopEnd>0?this.loopEnd:this.buffer.duration,e.connect(this.output),this.source=e,e.onended=()=>{this.source===e&&(this.isPlaying&&!this.loop&&(this.isPlaying=!1,this.pauseTime=0),typeof this.onended=="function"&&this.onended())},e}play({fadeIn:e=0,offset:n=null}={}){let s=n!==null?n:this.pauseTime;if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.source=this._createSource(),this.startTime=this.context.currentTime-s/this.playbackRate,this.source.start(0,s),e>0?(this.output.gain.setValueAtTime(0,this.context.currentTime),this.output.gain.linearRampToValueAtTime(1,this.context.currentTime+e)):this.output.gain.setValueAtTime(1,this.context.currentTime),this.isPlaying=!0}start(e=0,n=0,s){this.isPlaying||(this.source=this._createSource(),this.startTime=this.context.currentTime+e-n/this.playbackRate,s!==void 0?this.source.start(this.context.currentTime+e,n,s):this.source.start(this.context.currentTime+e,n),this.pauseTime=n,this.isPlaying=!0)}pause({fadeOut:e=0}={}){if(!this.isPlaying)return;let n=this.getElapsed()/1e3;if(this.loop&&this.loopEnd>this.loopStart){let s=this.loopEnd-this.loopStart;n=this.loopStart+(n-this.loopStart)%s}if(this.isPlaying=!1,e>0){let s=this.context.currentTime;this.output.gain.setValueAtTime(this.output.gain.value,s),this.output.gain.linearRampToValueAtTime(0,s+e),setTimeout(()=>{if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.pauseTime=n,this.output.gain.setValueAtTime(1,this.context.currentTime)},e*1e3)}else{if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.pauseTime=n}}getElapsed(){return this.isPlaying?(this.context.currentTime-this.startTime)*this.playbackRate*1e3:this.pauseTime*1e3}setSpeed(e){if(e<=0)throw new Error("Playback rate must be positive");let n=this.getElapsed()/1e3;this.playbackRate=e,this.isPlaying&&(this.pause(),this.pauseTime=n,this.play())}setLoop(e=!0){this.loop=e,this.source&&(this.source.loop=e)}loop;playbackRate;startTime;tempGain=null;connect(e,n=0,s=0){if("value"in e)this.output.connect(e,n);else return this.output.connect(e,n,s),e}disconnect(e,n,s){e===void 0?this.output.disconnect():this.output.disconnect(e,n,s)}output;stop(e=0){if(this.notIndependent)return this.pause();if(!this.source)return;let n=this.context.currentTime+e;this.source.stop(n),this.isPlaying=!1,this.notIndependent||(this.pauseTime=0)}pauseTime;isPlaying;notIndependent=!1;loopStart=0;loopEnd=0},Ge={osc:{enabled:!0,type:"sine",freq:440,detune:0},noise:{enabled:!1,level:.5},ampEnv:{attack:.005,decay:.1,sustain:0,release:.1,volume:.3},pitchEnv:{amount:0,decay:.2},filter:{enabled:!1,type:"lowpass",freq:1200,Q:1,envAmount:0,decay:.2},lfo:{enabled:!1,target:"freq",rate:8,depth:20},duration:.4},V=class r{constructor(e={}){this.ctx=X.audioCtx,this.cfg=structuredClone(Ge),Object.assign(this.cfg,e)}ctx;cfg;play(e=X.sfxGain){let n=this.ctx,s=n.currentTime,a=this.cfg,l=n.createGain();l.gain.setValueAtTime(1e-4,s);let d=a.ampEnv;l.gain.exponentialRampToValueAtTime(d.volume,s+d.attack),l.gain.exponentialRampToValueAtTime(Math.max(1e-4,d.sustain*d.volume),s+d.attack+d.decay),l.gain.exponentialRampToValueAtTime(1e-4,s+a.duration+d.release);let f=l,h;a.filter.enabled&&(h=n.createBiquadFilter(),h.type=a.filter.type,h.frequency.value=a.filter.freq,h.Q.value=a.filter.Q,h.connect(l),f=h);let c;if(a.osc.enabled){if(c=n.createOscillator(),c.type=a.osc.type,c.frequency.value=a.osc.freq,c.detune.value=a.osc.detune,a.pitchEnv.amount!==0){let i=Math.pow(2,a.pitchEnv.amount/12);c.frequency.exponentialRampToValueAtTime(a.osc.freq*i,s+a.pitchEnv.decay)}c.connect(f),c.start(s),c.stop(s+a.duration+d.release)}let p;if(a.noise.enabled){let i=n.sampleRate*a.duration,o=n.createBuffer(1,i,n.sampleRate),u=o.getChannelData(0);for(let y=0;y<i;y++)u[y]=(Math.random()*2-1)*a.noise.level;p=n.createBufferSource(),p.buffer=o,p.connect(f),p.start(s),p.stop(s+a.duration+d.release)}let g,x;a.lfo.enabled&&c&&(g=n.createOscillator(),g.frequency.value=a.lfo.rate,x=n.createGain(),x.gain.value=a.lfo.depth,g.connect(x),a.lfo.target==="freq"?x.connect(c.frequency):a.lfo.target==="gain"?x.connect(l.gain):a.lfo.target==="filter"&&h&&x.connect(h.frequency),g.start(s),g.stop(s+a.duration)),l.connect(e);let v=[c,p,g,x,h,l],t=s+a.duration+d.release;setTimeout(()=>{v.forEach(i=>i?.disconnect())},(t-n.currentTime)*1e3)}getConfig(){return structuredClone(this.cfg)}setConfig(e){return Object.assign(this.cfg,e),this}getKey(e){return this.cfg[e]}setKey(e,n){return Object.assign(this.cfg[e],n),this}setFreq(e){return this.cfg.osc.freq=e,this}setWave(e){return this.cfg.osc.type=e,this}setVolume(e){return this.cfg.ampEnv.volume=e,this}setAmpEnv(e,n,s,a){return Object.assign(this.cfg.ampEnv,{attack:e,decay:n,sustain:s,release:a}),this}setPitchEnv(e,n){return Object.assign(this.cfg.pitchEnv,{amount:e,decay:n}),this}setNoiseEnabled(e){return this.cfg.noise.enabled=e,this}setNoiseLevel(e){return this.cfg.noise.level=e,this}setFilterEnabled(e){return this.cfg.filter.enabled=e,this}setFilter(e,n,s){return Object.assign(this.cfg.filter,{type:e,freq:n,Q:s,enabled:!0}),this}setLFOEnabled(e){return this.cfg.lfo.enabled=e,this}setLFO(e,n,s){return Object.assign(this.cfg.lfo,{target:e,rate:n,depth:s,enabled:!0}),this}setDuration(e){return this.cfg.duration=e,this}clone(){return new r(structuredClone(this.cfg))}},mt=new V({osc:{enabled:!0,type:"square",freq:900,detune:0},ampEnv:{attack:.002,decay:.04,sustain:0,release:.02,volume:.15},duration:.05}),yt=new V({osc:{enabled:!0,type:"sine",freq:600,detune:0},ampEnv:{attack:.01,decay:.08,sustain:0,release:.04,volume:.12},duration:.1}),bt=new V({osc:{enabled:!0,type:"triangle",freq:500,detune:0},pitchEnv:{amount:12,decay:.15},ampEnv:{attack:.01,decay:.12,sustain:0,release:.05,volume:.25},duration:.18}),gt=new V({osc:{enabled:!0,type:"sawtooth",freq:1200,detune:0},pitchEnv:{amount:-24,decay:.3},ampEnv:{attack:.005,decay:.25,sustain:0,release:.05,volume:.3},duration:.35}),xt=new V({osc:{enabled:!0,type:"square",freq:180,detune:0},noise:{enabled:!0,level:.4},ampEnv:{attack:.002,decay:.15,sustain:0,release:.05,volume:.35},duration:.2});function me(r=12){let e=Date.now().toString(36),n=crypto.getRandomValues(new Uint8Array(4)),s=Array.from(n).map(a=>a.toString(36).padStart(2,"0")).join("");return(e+s).slice(0,r)}function ze(r){let e=!0;function n(){e&&(r(),requestAnimationFrame(n))}return requestAnimationFrame(n),{clear:()=>e=!1}}function He(){return U?!1:/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)}var vt=He();function Ue({width:r,height:e,updateHz:n="frames"}){return new G.KaylaGame(r,e,n==="frames"?1/0:n)}function $e(r){let e=new J(r);return new G.KaylaScene(e)}function Oe(r){return new G.KaylaRenderer(r)}function ne(r,e){if(typeof r!="function")throw new Error("Invalid Element Type.");let n=e??{};return n.key??=r.name+"_"+me(),{type:r,props:n}}var L;(s=>{function r(a,l){return!(a.right<l.left||a.left>l.right||a.bottom<l.top||a.top>l.bottom)}s.rawCollision=r;function e(a,l,d){let f=l*Math.PI/180,h=Math.cos(f),c=Math.sin(f),p=1/0;return h>0&&(p=Math.min(p,(d.right-a.x)/h)),h<0&&(p=Math.min(p,(d.left-a.x)/h)),c>0&&(p=Math.min(p,(d.bottom-a.y)/c)),c<0&&(p=Math.min(p,(d.top-a.y)/c)),M.from(l).scale(p)}s.getCurrToBound=e;function n(a){let{left:l,right:d,top:f,bottom:h,width:c,height:p,x:g=0,y:x=0}=a;if(c===null||p===null)throw new Error("width and height are required");let v,t;if(l!=null&&d!=null){if(Math.abs(d-l-c)>1e-6)throw new Error("left, right, and width mismatch");v=l}else g!=null?v=g-c/2:l!=null?v=l:d!=null?v=d-c:v=0;if(f!=null&&h!=null){if(Math.abs(h-f-p)>1e-6)throw new Error("top, bottom, and height mismatch");t=f}else x!=null?t=x-p/2:f!=null?t=f:h!=null?t=h-p:t=0;return{left:v,right:v+c,top:t,bottom:t+p,width:c,height:p,x:v+c/2,y:t+p/2}}s.createRawRect=n})(L||={});var G;(x=>{class r extends Z{#e;#t;constructor(t,i,o){super(t,i,o),this.#e=new Set,this.#t=!1}delay(t){return this.ticker.createTimeout(t)}get started(){return this.#t}start(){if(!this.#t){for(let t of this.#e)t.start();this.#t=!0,super.start()}}stop(){if(this.#t){for(let t of this.#e)t.stop();this.#t=!1,super.stop()}}addRenderer(t){this.#e.has(t)||(this.#e.add(t),this.#t&&t.start(),t.game=this)}get mainRenderer(){return[...this.#e].at(0)}getRenderers(){return[...this.#e]}deleteRenderer(t){this.#e.has(t)&&(this.#e.delete(t),this.#t&&t.stop(),delete t.game)}}x.KaylaGame=r;class e extends Q{game;pointerX;pointerY;pointerEvents;onPointerDown;onPointerUp;onPointerCancel;onPointerMove;constructor(t){super(t),this.useDraw=this.useDraw.bind(this),this.on("draw",i=>{if(this.game)for(let o of this.game.scenes.values())o.handleDraw(i)}),this.pointerX=0,this.pointerY=0,this.pointerEvents=new I,this.pointerPosUpdater=this.pointerPosUpdater.bind(this),this.onPointerDown=i=>this.onPointerAll(i,"down"),this.onPointerUp=i=>this.onPointerAll(i,"up"),this.onPointerCancel=i=>this.onPointerAll(i,"cancel"),this.onPointerMove=i=>this.onPointerAll(i,"move")}pointerPosUpdater(t){this.pointerX=t.clientX,this.pointerY=t.clientY}onPointerAll(t,i){this.pointerPosUpdater(t);let o=e.getClickType(t);if(o!=="invalid"||i==="move"||i==="cancel"){t.preventDefault();let u=this.getMousePos();this.pointerEvents.emit("action",u,o,i)}}static getClickType(t){switch(t.button){case 0:return"left";case 1:return"middle";case 2:return"right";default:return"invalid"}}listenPointerUpdates(){this.canvas.addEventListener("pointermove",this.pointerPosUpdater),this.canvas.addEventListener("pointerdown",this.onPointerDown),this.canvas.addEventListener("pointerup",this.onPointerUp),this.canvas.addEventListener("pointercancel",this.onPointerCancel),this.canvas.addEventListener("pointermove",this.onPointerMove)}unlistenPointerUpdates(){this.canvas.removeEventListener("pointermove",this.pointerPosUpdater),this.canvas.removeEventListener("pointerdown",this.onPointerDown),this.canvas.removeEventListener("pointerup",this.onPointerUp),this.canvas.removeEventListener("pointermove",this.onPointerMove)}pointerPosToWorldPos(t,i){let o=this.canvas.getBoundingClientRect(),u=(t-o.left)/o.width,y=(i-o.top)/o.height,b=u*this.viewportWidth*this.cameraWidth/o.width,C=y*this.viewportHeight*this.cameraHeight/o.height;return new M(b,C)}getMousePos(){return this.pointerPosToWorldPos(this.pointerX,this.pointerY)}useDraw(t){let i=o=>{t(o,new s)};return this.on("draw",i),()=>{this.off("draw",i)}}attachTo(t){t.addRenderer(this),this.game=t}detach(){this.game&&this.game.deleteRenderer(this)}}x.KaylaRenderer=e;class n{current;saves;constructor(){this.saves=[]}useTick(t){if(!this.current)throw new Error("Hook 'useTick' must be executed in the top level scope of a component.");this.current.onTick[this.current.useStepCallIndex]=t,this.current.useStepCallIndex++}usePaint(t){if(!this.current)throw new Error("Hook 'usePaint' must be executed in the top level scope of a component.");this.current.onPaint[this.current.useDrawCallIndex]=t,this.current.useDrawCallIndex++}useEntity(){if(!this.current)throw new Error("Hook 'useEntity' must be executed in the top level scope of a component.");return ye(be)}useSelf(t){if(!this.current)throw new Error("Hook 'useSelf' must be executed in the top level scope of a component.");let i=ye(null);return(i.current===null||i.current===void 0)&&(i.current=t()),i.current}useInitialization(t){if(!this.current)throw new Error("Hook 'useInitialization' must be executed in the top level scope of a component.");let i=this.current;i.onInits[this.current.useInitCallIndex]=t,i.useInitCallIndex++}useRect(){if(!this.current)throw new Error("Hook 'useRect' must be executed in the top level scope of a component.");return D(()=>new x.KaylaInternalRect(this.current))}useFiber(){if(!this.current)throw new Error("Hook 'useFiber' must be executed in the top level scope of a component.");return D(()=>this.current)}useFiberControl(){if(!this.current)throw new Error("Hook 'useFiberControl' must be executed in the top level scope of a component.");let t=this.current;return D(()=>({refresh:()=>t.refresh(),get childrenCount(){return t.lastChildren.length},setMaxChildren:i=>{t.setMaxChildren(i)},getMaxChildren:()=>t.getMaxChildren(),get maxSafeChildren(){return t.maxSafeChildren},get key(){return t.key},get getChildrenEntities(){return t.getChildrenEntities.bind(t)},get getEntityChain(){return t.getEntityChain.bind(t)},get getFiberChain(){return t.getFiberChain.bind(t)}}))}useCurrentTicker(){if(!this.current)throw new Error("Hook 'useCurrentTicker' must be executed in the top level scope of a component.");return this.current.getAttachedGame().ticker}useCurrentRenderer(){if(!this.current)throw new Error("Hook 'useCurrentRenderer' must be executed in the top level scope of a component.");return this.current.getAttachedGame().mainRenderer}useCurrentGame(){if(!this.current)throw new Error("Hook 'useCurrentGame' must be executed in the top level scope of a component.");return this.current.getAttachedGame()}useCurrentScene(){if(!this.current)throw new Error("Hook 'useCurrentScene' must be executed in the top level scope of a component.");return this.current.scene}useState(t,{alwaysRecall:i=!1}={}){if(!this.current)throw new Error("Hook 'useState' must be executed in the top level scope of a component.");let u=this.current.state[this.current.useStateCallIndex]??new a(this.current,t,{alwaysRecall:i});return this.current.state[this.current.useStateCallIndex]=u,this.current.useStateCallIndex++,u}useShouldRefresh(t){let i=this.current;if(!i)throw new Error("useShouldRefresh must be called inside a component");i.watchedDeps&&console.warn("useShouldRefresh called multiple times \u2014 using the last call"),i.watchedDeps=t}useRef(t){if(!this.current)throw new Error("Hook 'useRef' must be executed in the top level scope of a component.");let o=this.current.refs[this.current.useRefCallIndex]??d(t??null);return this.current.refs[this.current.useRefCallIndex]=o,this.current.useRefCallIndex++,o}useEffect(t){if(!this.current)throw new Error("Hook 'useEffect' must be executed in the top level scope of a component.");this.current.onEffect[this.current.useEffectCallIndex]=t,this.current.useEffectCallIndex++}useViewportEffect(t){if(!this.current)throw new Error("Hook 'useViewport' must be executed in the top level scope of a component.");this.current.onViewportEffect[this.current.useViewCallIndex]=t,this.current.useViewCallIndex++}useExports(t,i){if(!this.current)throw new Error("Hook 'useExports' must be executed in the top level scope of a component.");this.current.onExport=i}useGlobalPointer(t,i){if(!this.current)throw new Error("Hook 'useGlobalPointer/useGlobalClick' must be executed in the top level scope of a component.");i??={},this.current.onGlobalPointer[this.current.useGlobalClickCallIndex]={handler:t,config:i},this.current.useGlobalClickCallIndex++}usePointer(t,i){if(!this.current)throw new Error("Hook 'usePointer/useClick' must be executed in the top level scope of a component.");i??={};let o=this.current;Te((u,y,b)=>{let C=o.entity;if(!C)return;let E=C.getRawRect(),z=L.createRawRect({x:u.x,y:u.y,width:3,height:3});L.rawCollision(E,z)&&t(u,y,b)},i)}useContext(t){if(!this.current)throw new Error("Hook 'useContext' must be executed in the top level scope of a component.");return this.current.findContextValueFromInst(t)}save(){this.saves.push({current:this.current})}restore(){let t=this.saves.pop();if(!t)throw new Error("Cannot restore without saving.");this.current=t.current}logLevel="warn";logger={debug:(...t)=>{this.logLevel==="debug"&&console.debug(...t)},info:(...t)=>{["info","warn","debug"].includes(this.logLevel)&&console.info(...t)},warn:(...t)=>{["warn","debug"].includes(this.logLevel)&&console.warn(...t)},error:(...t)=>console.error(...t),withFiber:(t,i,o,...u)=>{let y=t?.fc?.name||"anonymous",b=t?.key?` key=${t.key}`:"";this.logger[i](`${o} <${y}${b}>`,...u)}}}x.GlobalKayla=n;class s{preventDefault(){this.#e=!0}#e=!1;isPrevented(){return this.#e}}x.KaylaEvent=s;class a{#e;#t;#n;alwaysRecall;constructor(t,i,{alwaysRecall:o=!1}={}){this.#t=t,this.#e=i??void 0,this.#n=Date.now(),this.alwaysRecall=o}get(){return this.#e}*[Symbol.iterator](){throw new Error(`Hey! KaylaState is NOT an array / iterable like useState in React.
|
|
2
2
|
You probably wrote: const [value, setValue] = useState(...)
|
|
3
3
|
|
|
4
4
|
\u2192 In Kayla write: const value = useState(...);
|
package/dist/jsx-runtime.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { b as FC, F as FCProps, j as KaylaExportables, h as KaylaElement } from './kayla-internals-
|
|
2
|
-
import './lea-
|
|
1
|
+
import { b as FC, F as FCProps, j as KaylaExportables, h as KaylaElement } from './kayla-internals-jEHH2NbT.cjs';
|
|
2
|
+
import './lea-BaZkxo5L.cjs';
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* jsx stuff
|
package/dist/jsx-runtime.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { b as FC, F as FCProps, j as KaylaExportables, h as KaylaElement } from './kayla-internals-
|
|
2
|
-
import './lea-
|
|
1
|
+
import { b as FC, F as FCProps, j as KaylaExportables, h as KaylaElement } from './kayla-internals-BIKaIho5.js';
|
|
2
|
+
import './lea-BaZkxo5L.js';
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* jsx stuff
|