@kayelaa/canvas 0.2.10 → 0.2.15

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.
@@ -1,4 +1,4 @@
1
- var Fe=Object.defineProperty;var Ae=(i,e)=>{for(var n in e)Fe(i,n,{get:e[n],enumerable:!0})};var Re={};Ae(Re,{JSX:()=>Ke,KMatrix2D:()=>ve,KaylaContext:()=>le,KaylaElement:()=>W,KaylaFragment:()=>Ee,KaylaInternals:()=>G,KaylaRect:()=>_,Layer:()=>it,Rect:()=>at,Text:()=>Ie,createContext:()=>He,createElement:()=>Y,createGame:()=>Ge,createReassignableObject:()=>tt,createRenderer:()=>$e,createScene:()=>ze,createUseHook:()=>rt,safeValueRepresentation:()=>j,self:()=>xe,setLogLevel:()=>nt,tinyUID:()=>st,useClick:()=>qe,useContext:()=>Ze,useCurrentGame:()=>Ye,useCurrentRenderer:()=>Je,useCurrentScene:()=>Se,useCurrentTicker:()=>Qe,useDisposableRef:()=>et,useEffect:()=>J,useEntity:()=>je,useExports:()=>he,useFiber:()=>Ce,useFiberControl:()=>we,useGlobalClick:()=>Pe,useGlobalPointer:()=>Xe,useInitialization:()=>ue,useNextStack:()=>ce,usePaint:()=>Q,usePointer:()=>Be,useRect:()=>U,useRef:()=>be,useSelf:()=>H,useShouldRefresh:()=>Oe,useState:()=>Ue,useTick:()=>We,useViewportEffect:()=>Ne});var F=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}},ie=class extends F{#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(!T)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||!T)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(!T||typeof globalThis.requestAnimationFrame>"u")throw new Error("Raf is not supported");this.running=!0,this._rafId=requestAnimationFrame(this._loop)}}stop(){if(!T||typeof globalThis.requestAnimationFrame>"u")throw new Error("Raf is not supported");this.running=!1,this._rafId!==null&&(cancelAnimationFrame(this._rafId),this._rafId=null)}},me=class extends F{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,!(T&&typeof this.__intervalId=="function"&&document.hidden)&&(this.#e+=n*1e3,this.emit("tick",n))}createTimeout(e){return new ge(e,this)}createTween(e,n=()=>{}){let s=new ye(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=T&&!isFinite(this.tickInterval)?Ve(()=>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)}getLoopMod(e,n=0){return(this.now()+n*e)%e/e}},Me;(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),g=parseFloat(u);if(isNaN(y)||isNaN(g))throw new Error(`Invalid Vector2 string: ${r}`);return new L(y,g)}t.vec2Import=s,t.booleanMap={mapExport:i,mapImport:e};function l(r){return o=>Number(o.toFixed(r))}t.createRounder=l;function c(r=10){return{mapExport(o){return Math.round(o/r)},mapImport(o){return o*r}}}t.createLowPrecision=c;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 d(r){let o=new Map(Object.entries(r));return{mapExport:u=>o.get(u)??null,mapImport:u=>Array.from(o.entries()).find(([y,g])=>g===u)?.[0]??null}}t.createLookup=d;function p(r){let o=r*(180/Math.PI);return Math.round((o%360+360)%360)}t.radToDeg=p;function b(r){return r*(Math.PI/180)}t.degToRad=b,t.angleRadToDeg={mapExport:p,mapImport:b};function v(r=10){let o=c(r);return{mapExport(u){return o.mapExport(p(u))},mapImport(u){return o.mapImport(b(u))}}}t.createLowPrecisionRadToDeg=v})(Me||={});var X=class i extends F{name="";scaleRotate=0;scale=1;constructor(e,n=0,s=0){super(),this.autoTranslate=!1,this.name=e,this.z=0,this.___pos=new L(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(!($||!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 c=Reflect.get(this,a);return l?l(c):c});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($&&typeof l=="number"){let c=l.toString().split("."),h=(c[1]?c[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[c,{mapImport:f}]=l,h=n[a];if(f&&(h=f(h)),typeof c!="string")break;try{Reflect.set(s,c,h)}catch(d){console.error(d)}}return s}},se=class extends F{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(!$&&!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 X))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 X))throw new Error("invalid entity");this.entities.delete(e.name)}getEntity(e){return this.entities.get(e)}},ae=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 me(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()}},S={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=S.clamp(i,0,1),i*i*(3-2*i)},randomLerp(i,e){return S.lerp(i,e,Math.random())},randomInt(i,e){return Math.floor(Math.random()*(e-i+1))+i},randomArrayValue(i){return i[S.randomInt(0,i.length-1)]},createBezier(i,e,n,s){function a(f,h,d,p,b){let x=1-f;return x*x*x*h+3*x*x*f*d+3*x*f*f*p+f*f*f*b}function l(f,h,d,p,b){let x=1-f;return 3*x*x*(d-h)+6*x*f*(p-d)+3*f*f*(b-p)}function c(f){let h=f;for(let d=0;d<6;d++){let p=a(h,0,i,n,1),b=l(h,0,i,n,1);if(b===0)break;h-=(p-f)/b}return S.clamp(h,0,1)}return function(h){h=S.clamp(h,0,1);let d=c(h);return a(d,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 S.normalizeRad(-i)},degToRadFlipY(i){return S.angleInvertY(i*Math.PI/180)},minimalAngularDirection(i,e){i=S.normalizeRad(i),e=S.normalizeRad(e);let n=S.normalizeRad(e-i),s=S.normalizeRad(i-e);return n<=s?1:-1}},ye=class extends F{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=S.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))}},oe=class extends X{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)}},ge=class extends F{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)}},L=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 Le(){return typeof process<"u"&&process.release?.name==="node"?"node":typeof window<"u"||typeof self<"u"?"web":"unknown"}var ke=Le(),$=ke==="node",T=ke==="web",q=class i{static unlock(){T&&this.audioCtx.state!=="running"&&this.audioCtx.resume()}static audioCtx=T?new AudioContext:null;static masterGain=T?this.audioCtx.createGain():null;static musicGain=T?this.audioCtx.createGain():null;static sfxGain=T?this.audioCtx.createGain():null;static{T&&(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(),c=await this.audioCtx.decodeAudioData(l);return this.audioBufferCache.set(e,c),c}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 c=new N(l);c.buffer=l;let f=1-.12,h=1+.12;c.playbackRate=s??f+Math.random()*(h-f);let d=this.audioCtx.createGain();d.gain.value=n,c.tempGain=d,c.connect(d),d.connect(this.sfxGain),c.onended=()=>{c.disconnect(),d.disconnect()},c.start(),a&&this.sfsx.set(e,{source:c,gain:d})}catch(l){console.error(l)}}static async playLoop(e,n=1,{loopStart:s=0,loopEnd:a=null,exclusive:l=!0,skipMS:c=0}={}){if(l)for(let b of this.loops.keys())this.stopLoop(b);this.audioBufferCache.has(e)||await this.preLoad(e);let f=this.getCached(e);if(!f)return;let h=new N(f);h.buffer=f,h.loop=!0,typeof s=="number"&&(h.loopStart=s),typeof a=="number"&&(h.loopEnd=a);let d=this.audioCtx.createGain();d.gain.value=n,h.tempGain=d,h.playbackRate=1,h.onended=()=>{h.disconnect(),d.disconnect()},h.connect(d),d.connect(this.musicGain),h.start(0,c/1e3);let p=++this.loopIdCounter;return this.loops.set(p,{source:h,gain:d}),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:c=null,isMusic:f=!1,gain:h=null}={}){try{this.audioBufferCache.has(e)||await this.preLoad(e);let d=this.getCached(e);if(!d)return null;let p=new N(d);p.loop=a,p.loopStart=l,p.loopEnd=typeof c=="number"?c:d.duration,p.playbackRate=s;let b=this.audioCtx.createGain();return b.gain.value=n,p.connect(b),p.tempGain=b,b.connect(h||(f?this.musicGain:this.sfxGain)),p.onended=()=>{p.disconnect(),b.disconnect()},p}catch(d){return console.error("Failed to create LiaAudioSrc:",d),null}}};var N=class{numberOfInputs;numberOfOutputs;constructor(e,n=q.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=T?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},_e={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},D=class i{constructor(e={}){this.ctx=q.audioCtx,this.cfg=structuredClone(_e),Object.assign(this.cfg,e)}ctx;cfg;play(e=q.sfxGain){let n=this.ctx,s=n.currentTime,a=this.cfg,l=n.createGain();l.gain.setValueAtTime(1e-4,s);let c=a.ampEnv;l.gain.exponentialRampToValueAtTime(c.volume,s+c.attack),l.gain.exponentialRampToValueAtTime(Math.max(1e-4,c.sustain*c.volume),s+c.attack+c.decay),l.gain.exponentialRampToValueAtTime(1e-4,s+a.duration+c.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 d;if(a.osc.enabled){if(d=n.createOscillator(),d.type=a.osc.type,d.frequency.value=a.osc.freq,d.detune.value=a.osc.detune,a.pitchEnv.amount!==0){let r=Math.pow(2,a.pitchEnv.amount/12);d.frequency.exponentialRampToValueAtTime(a.osc.freq*r,s+a.pitchEnv.decay)}d.connect(f),d.start(s),d.stop(s+a.duration+c.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+c.release)}let b,x;a.lfo.enabled&&d&&(b=n.createOscillator(),b.frequency.value=a.lfo.rate,x=n.createGain(),x.gain.value=a.lfo.depth,b.connect(x),a.lfo.target==="freq"?x.connect(d.frequency):a.lfo.target==="gain"?x.connect(l.gain):a.lfo.target==="filter"&&h&&x.connect(h.frequency),b.start(s),b.stop(s+a.duration)),l.connect(e);let v=[d,p,b,x,h,l],t=s+a.duration+c.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))}},ct=new D({osc:{enabled:!0,type:"square",freq:900,detune:0},ampEnv:{attack:.002,decay:.04,sustain:0,release:.02,volume:.15},duration:.05}),dt=new D({osc:{enabled:!0,type:"sine",freq:600,detune:0},ampEnv:{attack:.01,decay:.08,sustain:0,release:.04,volume:.12},duration:.1}),ft=new D({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}),pt=new D({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}),mt=new D({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 B(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 Ve(i){let e=!0;function n(){e&&(i(),requestAnimationFrame(n))}return requestAnimationFrame(n),{clear:()=>e=!1}}function De(){return $?!1:/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)}var yt=De();function Ge({width:i,height:e,updateHz:n="frames"}){return new G.KaylaGame(i,e,n==="frames"?1/0:n)}function ze(i){let e=new se(i);return new G.KaylaScene(e)}function $e(i){return new G.KaylaRenderer(i)}function Y(i,e){if(typeof i!="function")throw new Error("Invalid Element Type.");let n=e??{};n.key??=i.name+"_"+B();let s=Array.isArray(e.children)?[...e.children]:e.children?[e.children]:[];for(let l=0;l<s.length;l++){let c=s[l];if(typeof c!="object"||!(c instanceof W))if(typeof c=="string")s[l]=Y(Ie,{color:"white",label:c,parentRect:null,x:0,y:0,size:20,align:"center"});else throw new Error("Invalid JSX Child Parameter.")}n.children=s;let a=new W;return a.type=i,a.props=n,a}var W=class{type;props},_;(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,c){let f=l*Math.PI/180,h=Math.cos(f),d=Math.sin(f),p=1/0;return h>0&&(p=Math.min(p,(c.right-a.x)/h)),h<0&&(p=Math.min(p,(c.left-a.x)/h)),d>0&&(p=Math.min(p,(c.bottom-a.y)/d)),d<0&&(p=Math.min(p,(c.top-a.y)/d)),L.from(l).scale(p)}s.getCurrToBound=e;function n(a){let{left:l,right:c,top:f,bottom:h,width:d,height:p,x:b=0,y:x=0}=a;if(d===null||p===null)throw new Error("width and height are required");let v,t;if(l!=null&&c!=null){if(Math.abs(c-l-d)>1e-6)throw new Error("left, right, and width mismatch");v=l}else b!=null?v=b-d/2:l!=null?v=l:c!=null?v=c-d: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+d,top:t,bottom:t+p,width:d,height:p,x:v+d/2,y:t+p/2}}s.createRawRect=n})(_||={});var G;(x=>{class i extends ae{#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 ie{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 F,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,g=u*this.viewportWidth*this.cameraWidth/o.width,w=y*this.viewportHeight*this.cameraHeight/o.height;return new L(g,w)}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 be(xe)}useSelf(t){if(!this.current)throw new Error("Hook 'useSelf' must be executed in the top level scope of a component.");let r=be(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(t="self"){if(!this.current)throw new Error("Hook 'useRect' must be executed in the top level scope of a component.");if(t==="disposableSelf")return new x.KaylaInternalRect(this.current);let r=null;if(t==="self"&&(r=this.current),t==="parent"&&(r=this.current.detectedParent),!r)throw new Error("Missing valid target fiber.");return H(()=>new x.KaylaInternalRect(r))}useFiber(){if(!this.current)throw new Error("Hook 'useFiber' must be executed in the top level scope of a component.");return H(()=>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 H(()=>({refresh:()=>t.refresh(),toString(){return t.toString()},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]??c(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;Pe((u,y,g)=>{let w=o.entity;if(!w)return;let C=w.getRawRect(),P=_.createRawRect({x:u.x,y:u.y,width:3,height:3});_.rawCollision(C,P)&&t(u,y,g)},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",g=t?.key?` key=${t.key}`:"";this.logger[r](`${o} <${y}${g}>`,...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}get 0(){return this.get()}1(t){this.set(t,{recall:!0})}legacy(){return[this[0],this[1].bind(this)]}add(t,{recall:r}={}){this.set(this.get()+t,{recall:r})}multiply(t,{recall:r}={}){this.set(this.get()*t,{recall:r})}set(t,{recall:r=!1}={}){let o=this.#e;if(t===o)return;this.#e=t;let y=Date.now()-this.#n;r&&y<67&&this.#t.global.logger.warn(`Hot structural state change <${this.#t.fc?.name||"anonymous"}> delta=${y}ms`),(r||this.alwaysRecall)&&this.#t.refresh(),this.#n=Date.now()}get value(){return this.#e}get lastChanged(){return this.#n}}x.KaylaInternalState=a;class l{#e;constructor(t){this.#e=t??void 0}#t;setSetter(t){this.#t=t}get current(){return this.#e}set current(t){this.#e=t,this.#t&&this.#t(this.#e)}}x.KaylaInternalRef=l;function c(v){return new l(v)}x.createReassignableRef=c;class f{state;refs;global;callProps;scene;exports;detectedParent;contextInfo;lastLayer;get childrenCount(){return this.lastChildren.length}maxSafeChildren;dynamicChildren;constructor(t,r,o){if(!o)throw new Error("Empty element");this.maxSafeChildren=40,this.scene=r,this.state=[],this.refs=[],this.onInits=[],this.onUnInits=[],this.fc=o.type,this.callProps=o.props??{},this.global=t,this.lastStateDeps=[],this.entity=null,this.lastChildren=[],this.onEffect=[],this.onUnEffect=[],this.onPaint=[],this.onTick=[],this.onGlobalPointer=[],this.pointerHook=this.pointerHook.bind(this),this.resizeHook=this.resizeHook.bind(this),this.contextInfo=null,this.detectedParent=null,this.dynamicChildren=[],this.key??=this.fc.name+"_"+B(),this.onViewportEffect=[],this.lastLayer=null}getCorrectMousePos(t){return t??=this.getAttachedRenderer().getMousePos(),this.lastLayer?.transform?this.lastLayer.transform.inverseV(t):t}getChildrenEntities(){return this.lastChildren.map(t=>t.entity)}pointerHook(t,r,o){t=this.getCorrectMousePos(t);try{for(let{handler:u,config:y}of this.onGlobalPointer)y.type??="any",y.action??="down",!(y.action!=="any"&&y.action!==o||y.type!=="any"&&y.type!==r)&&u(t,r,o)}catch(u){this.global.logger.error(u)}}resizeHook({width:t,height:r}){try{for(let o of this.onViewportEffect)o(this.getAttachedRenderer(),t,r)}catch(o){this.global.logger.error(o)}}bindEvents(){for(let t of[this.getAttachedRenderer()])t&&(t.pointerEvents.on("action",this.pointerHook),t.on("viewport_update",this.resizeHook))}unbindEvents(){for(let t of[this.getAttachedRenderer()])t&&(t.pointerEvents.off("action",this.pointerHook),t.off("viewport_update",this.resizeHook))}get key(){return this.callProps.key}set key(t){this.callProps.key=t}get children(){let t=this.callProps.children;return Array.isArray(t)?t:[t]}set children(t){this.callProps.children=t}entity;onExport=()=>({});onEffect;onViewportEffect;onGlobalPointer;onInits;onUnInits;onUnEffect;onEffectDeps;onPaint;onTick;fc;useStateCallIndex=0;useEffectCallIndex=0;useGlobalClickCallIndex=0;useDrawCallIndex=0;useStepCallIndex=0;useRefCallIndex=0;useInitCallIndex=0;useViewCallIndex=0;lastStateDeps;watchedDeps;lastDepStamps=[];getAttachedRenderer(){return this.getAttachedGame().mainRenderer}getAttachedGame(){return this.scene.getGame()}setMaxChildren(t){if(this.maxSafeChildren=Math.max(0,t),this.global.logger.debug(`Max children limit updated to ${t} for <${this.fc?.name||"anonymous"} key=${this.key}>`),this.lastChildren.length>this.maxSafeChildren){let r=this.lastChildren.length-this.maxSafeChildren;this.global.logger.warn(`Child limit exceeded (${this.lastChildren.length} > ${this.maxSafeChildren}) \u2014 removing ${r} oldest children <${this.fc?.name||"anonymous"} key=${this.key}>`);let o=this.lastChildren.slice(0,this.maxSafeChildren),u=this.lastChildren.slice(this.maxSafeChildren);this.lastChildren=o;for(let y of u)y.unuse()}}getMaxChildren(){return this.maxSafeChildren??1/0}getFiberChain(){let t=[],r=this.detectedParent;for(;r;)t.push(r),r=r?.detectedParent;return t}getAllChildrenNestedFlattened(){let t=[],r=(o=[])=>{for(let u of o)t.push(u),u.lastChildren?.length&&r(u.lastChildren)};return r(this.lastChildren),t}getContextChain(){return this.getFiberChain().map(t=>t.contextInfo).filter(Boolean)}findContextValueFromInst(t){return this.getContextChain().find(r=>r.instance===t)?.value}getEntityChain(){return this.getFiberChain().map(t=>t.entity)}shouldFullRefresh(){if(this.isFirstUse||!this.watchedDeps||this.watchedDeps.length===0)return!0;for(let t=0;t<this.watchedDeps.length;t++){let r=this.watchedDeps[t],o=this.lastDepStamps[t]??0;if(r.lastChanged>o)return!0}return!1}captureDepStamps(){this.watchedDeps&&(this.lastDepStamps=this.watchedDeps.map(t=>t.lastChanged))}refresh(){if(!this.shouldFullRefresh())return;let t=this.fc?.name||"anonymous";if(!this.shouldFullRefresh()){this.global.logger.debug(`Refresh skipped <${t} key=${this.key}>`);return}this.global.logger.debug(`Refresh executed <${t} key=${this.key}> reason=${this.isFirstUse?"first":"deps-changed"}`),this.lastChildren.length>this.maxSafeChildren&&this.global.logger.warn(`High child count <${t} key=${this.key}> children=${this.lastChildren.length}`);let r;this.global.save(),this.global.current=this,this.useStateCallIndex=0,this.useRefCallIndex=0,this.useInitCallIndex=0,this.useViewCallIndex=0,this.useStateCallIndex=0,this.useDrawCallIndex=0,this.useStepCallIndex=0,this.useEffectCallIndex=0,this.useGlobalClickCallIndex=0;let o=[];try{let u=this.fc(this.callProps)??[];if(u&&!Array.isArray(u)&&(u=[u]),!Array.isArray(u))throw new Error("Non array or non undefined children received.");for(let y of u);o=u}catch(u){r=u}if(this.global.restore(),this.updateChildren(o,!0),r)throw r}updateChildren(t,r){try{let o=[...t,...this.dynamicChildren],u=[],y=[];for(let g of o){let w=g.props?.key,C;w!=null&&(C=this.lastChildren.find(P=>P.key===w)),C||(C=new f(this.global,this.scene,g)),C.callProps=g.props,C.key=w??`${g.type?.name??""}_${B()}`,C.detectedParent=this,y.push(C),u.push(C)}for(let g of this.lastChildren)u.includes(g)||g.unuse();this.lastChildren=y,this.captureDepStamps(),this.use();for(let g of this.lastChildren)try{g.refresh()}catch(w){console.error(w)}}catch(o){console.error(o)}}toString(){return this.getStringRepresentation(0," ")}lastChildren;isFirstUse=!0;use(){try{let t=!0;if(this.lastStateDeps??=[],Array.isArray(this.onEffectDeps)&&(t=!0),t||this.isFirstUse){this.global.logger.debug(`Using <${this.fc?.name||"anonymous"} key=${this.key}> count=${this.onEffect.length}`);let r=this.isFirstUse;this.isFirstUse=!1,Array.isArray(this.onEffectDeps)&&(this.lastStateDeps=this.onEffectDeps.map(u=>({stamp:u.lastChanged,stateRef:u}))),this.entity&&this.scene.getScene().removeEntity(this.entity),this.entity&&this.entity.name!==this.key&&(this.entity=null),this.entity=this.entity??new h(this,this.key);for(let u of this.refs)u.current===xe&&(u.current=this.entity);if(this.callProps.ref instanceof l&&(this.callProps.ref.current=this.entity),this.exports=this.onExport(),this.callProps.exportsRef instanceof l&&(this.callProps.exportsRef.current=this.exports),this.entity&&this.entity!==this.entity&&this.global.logger.warn(`Entity name mismatch during refresh <${this.fc?.name} key=${this.key}>`),this.scene.getScene().addEntity(this.entity),r){this.onUnInits=[];for(let u of this.onInits){this.bindEvents();try{let y=u();typeof y=="function"&&this.onUnInits.push(y)}catch(y){throw this.global.logger.error("Initialization failed",this.fc?.name||"anonymous",y),y}}}try{for(let u of this.onUnEffect??[])u()}catch(u){console.error(u)}let o=this.onEffect.map(u=>u()).filter(u=>u!==void 0);this.onUnEffect=o}}catch(t){throw this.global.logger.error(`use() failed <${this.fc?.name||"anonymous"} key=${this.key}>`,t),t}}unuse(){this.global.logger.debug(`unuse called <${this.fc?.name||"anonymous"} key=${this.key}> children=${this.lastChildren.length}`),this.detectedParent=null,this.watchedDeps=void 0,this.lastDepStamps=[],this.unbindEvents();try{for(let t of this.onUnInits)t();for(let t of this.onUnEffect)t()}catch(t){this.global.logger.error(`Cleanup failed in unuse <${this.fc?.name||"anonymous"} key=${this.key}>`,t)}this.scene.getScene().removeEntity(this.entity);for(let t of this.lastChildren)t.unuse();this.lastChildren.length=0}getStringRepresentation(t=0,r=" "){let o=r.repeat(t),u=this,y="",g=Object.entries(this.callProps);for(let P=0;P<g.length;P++){let[K,R]=g[P];if(["children"].includes(K))continue;y+=` ${K}=${typeof R=="string"?`${j(R)}`:`{${j(R,0)}}`}`}let w=Array.from(u.lastChildren).map(P=>P.getStringRepresentation(t+1,r)).join(""),C=u.fc.displayName??u.fc.name.replaceAll(" ","-");return w&&w.length>0?`${o}<${C}${y}>
2
- ${w}${o}</${C}>
3
- `:`${o}<${C}${y}/>
4
- `}}x.KaylaFiber=f;class h extends oe{#e;flags;getRawRect(){return _.createRawRect({x:this.x,y:this.y,width:this.width,height:this.height})}getFiber(){return this.#e}constructor(t,r){super(r,0,0,0,0),this.#e=t,this.flags=new Map,this.color="transparent"}setFlag(t,r){return this.flags.set(t,r)}getFlag(t){return this.flags.get(t)}removeFlag(t){return this.flags.delete(t)}update(t){ce(()=>{let r=new s;if(this.#e&&this.#e.onTick)for(let o of this.#e.onTick)o(t,r);r.isPrevented()})}draw(t){let r=new s;if(this.#e&&this.#e.onPaint)for(let o of this.#e.onPaint)o(t,r);r.isPrevented()||super.draw(t)}getRect(){return new d(this.getFiber())}}x.KaylaRectEntity=h;class d{#e;constructor(t){this.#e=t}get color(){return this.#t(),this.entity.color}set color(t){this.#t(),this.entity.color=t}getRaw(){return _.createRawRect({x:this.x,y:this.y,width:this.width,height:this.height})}get entity(){return this.#e.entity??null}#t(){if(!this.#e)throw new Error("No fibers found.");if(!this.entity)throw new Error("The entity does NOT exist yet.")}isCollidingWith(t){return this.#t(),this.entity.isCollidingWith(t.entity)}get setFlag(){return this.#t(),this.entity.setFlag.bind(this.entity)}get getFlag(){return this.#t(),this.entity.getFlag.bind(this.entity)}get removeFlag(){return this.#t(),this.entity.removeFlag.bind(this.entity)}isHovered(){let t=this.getRaw(),r=this.#e.getCorrectMousePos(),o=_.createRawRect({x:r.x,y:r.y,width:3,height:3});return _.rawCollision(t,o)}get pos(){return this.#t(),this.entity.pos}get x(){return this.#t(),this.pos.x}set x(t){this.#t(),this.pos.x=t}get y(){return this.#t(),this.pos.y}set y(t){this.#t(),this.pos.y=t}get width(){return this.#t(),this.entity.width}set width(t){this.#t(),this.entity.width=t}get height(){return this.#t(),this.entity.height}set height(t){this.#t(),this.entity.height=t}get z(){return this.#t(),this.entity.z}set z(t){this.#t(),this.entity.z=t}get left(){return this.#t(),this.entity.left}set left(t){this.#t(),this.entity.left=t}get right(){return this.#t(),this.entity.right}set right(t){this.#t(),this.entity.right=t}get top(){return this.#t(),this.entity.top}set top(t){this.#t(),this.entity.top=t}get bottom(){return this.#t(),this.entity.bottom}set bottom(t){this.#t(),this.entity.bottom=t}get toLocal(){return this.entity.toLocal.bind(this.entity)}get toWorld(){return this.entity.toWorld.bind(this.entity)}}x.KaylaInternalRect=d;class p{#e;#t;constructor(t){this.#r=t,this.#n=null,this.#e=new Map,t.on("update",this.tickHandler.bind(this)),this.drawHandler=this.drawHandler.bind(this),t.handleDraw=this.drawHandler,this.#t=null}getLayers(){return this.#e}#n;#r;getFibers(){return this.getEntities().map(t=>t.getFiber())}getEntities(){return Array.from(this.getScene().entities.values())}getScene(){return this.#r}getGame(){return this.#n}getOrCreateLayer(t,r=0){return this.#e.has(t)||this.#e.set(t,{name:t,z:r,visible:!0,rootFiber:null}),this.#e.get(t)}getSortedLayers(){return Array.from(this.#e.values()).filter(t=>t.visible).sort((t,r)=>t.z-r.z)}setLayerVisible(t,r){let o=this.#e.get(t);o&&(o.visible=r)}handleDraw(t){if($)return;let r=this.getScene();if(r.paused)return;r.emit("draw",t);let o=this.getSortedLayers(),u=[];for(let g of o){if(!g.visible)continue;let w=g.rootFiber;if(!w)continue;let C=w.getAllChildrenNestedFlattened().flat().map(K=>K.entity).filter(Boolean);if(u.push(...C),t.save(),g.transform){let K=g.transform;t.setTransform(K.a,K.b,K.c,K.d,K.e,K.f)}g.blendMode&&(t.globalCompositeOperation=g.blendMode??"source-over");let P=Array.from(C).sort((K,R)=>K.z-R.z);for(let K of P)K.getFiber().lastLayer=g,K.handleDraw(t);t.restore()}let y=[...r.entities.values()].filter(g=>!u.includes(g));for(let g of y.sort((w,C)=>w.z-C.z))g.getFiber().lastLayer=null,g.handleDraw(t)}drawHandler(t){return this.handleDraw(t)}attachTo(t){t.addScene(this.#r),this.#n=t}async spawn(t){this.#t&&(this.#t.unuse(),this.#t=null);let r=this.createFiber(t);this.#t=r,await this.#n.delay(0),r.refresh()}getRoot(){return this.#t??null}createFiber(t){return new f(x.singleGlobalInstance,this,t)}detach(){this.#n&&this.#n.removeScene(this.#r)}tickHandler(){}}x.KaylaScene=p,x.singleGlobalInstance=new x.GlobalKayla})(G||={});var le=class{#e;constructor(e){this.Provider=this.#t.bind(this),this.#e=e,this.Provider.displayName="[[ KaylaContext ]].Provider"}get defaultValue(){return this.#e}#t({value:e=this.defaultValue,children:n}){let s=Ce();return J(()=>{s.contextInfo={instance:this,value:e}}),he(this.Provider,()=>({value:e})),n}Provider;Consumer};function He(i){return new le(i)}var m=G.singleGlobalInstance,Ue=m.useState.bind(m),be=m.useRef.bind(m),Oe=m.useShouldRefresh.bind(m),J=m.useEffect.bind(m),Ne=m.useViewportEffect.bind(m),Pe=m.useGlobalPointer.bind(m),Xe=m.useGlobalPointer.bind(m),qe=m.usePointer.bind(m),Be=m.usePointer.bind(m),ue=m.useInitialization.bind(m),U=m.useRect.bind(m),We=m.useTick.bind(m),Q=m.usePaint.bind(m),he=m.useExports.bind(m),H=m.useSelf.bind(m),we=m.useFiberControl.bind(m),Ce=m.useFiber.bind(m),je=m.useEntity.bind(m),Ye=m.useCurrentGame.bind(m),Je=m.useCurrentRenderer.bind(m),Se=m.useCurrentScene.bind(m),Qe=m.useCurrentTicker.bind(m),Ze=m.useContext.bind(m),xe=Symbol("self_ref");var ce=i=>{Promise.resolve(1).then(()=>{try{i()}catch(e){console.error(e)}})},Ee=({children:i})=>Array.isArray(i)?[...i]:i;function et(i){return G.createReassignableRef(i)}function tt(i){if(typeof i!="object"||typeof i=="function"||i===null)return i;let e={current:i};return new Proxy({},{get(s,a,l){return a==="reassignSelf"?c=>{e.current=c}:Reflect.get(e.current,a,l)},set(s,a,l,c){return Reflect.set(e.current,a,l,c)},has(s,a){return Reflect.has(e.current,a)},ownKeys(s){return Reflect.ownKeys(e.current)},getOwnPropertyDescriptor(s,a){return Reflect.getOwnPropertyDescriptor(e.current,a)},deleteProperty(s,a){return Reflect.deleteProperty(e.current,a)}})}function nt(i){m.logLevel=i}function rt(i){let e=i.name||"anonymous-custom-hook";function n(...s){let a=m.current;if(!a)throw new Error(`Custom hook '${e}' must be called inside a Kayla component`);let l=s??[];return a.global.logLevel==="debug"&&a.global.logger.debug(`Custom hook '${e}' running (non-memoized) <${a.fc?.name||"anonymous"} key=${a.key||"no-key"}>`),i.onUse(a,m,...l)}return n.name=i.name,n}var it=({name:i,z:e=0,blend:n,visible:s=!0,children:a,transform:l})=>{let c=Se(),f=Ce();return ue(()=>{let h=c.getOrCreateLayer(i,e);return h.blendMode=n,h.visible=s,h.rootFiber=f,h.transform=l??null,()=>{c.getLayers().delete(i)}}),a},ve=class extends DOMMatrix{#e;constructor(){super(),this.#e=new DOMPoint}transformV(e){this.#e.x=e.x,this.#e.y=e.y;let n=this.#e.matrixTransform(this);return new L(n.x,n.y)}inverseV(e){let n=this.inverse();this.#e.x=e.x,this.#e.y=e.y;let s=this.#e.matrixTransform(n);return new L(s.x,s.y)}},j=(i,e=0)=>{try{if(Array.isArray(i))return`[ ${i.map(n=>j(n,e)).join(", ")} ]`;if(typeof i=="object"&&i!==null){let n=i.constructor?.name;return n!=="Object"&&n?`[[ ${n} ]]`:`{ ${Object.entries(i).map(([s,a])=>`${s}: ${j(a,e)}`).join(", ")} }`}return JSON.stringify(i,null,e)}catch{return"[[ Non-serializable ]]"}},Ke;(e=>e.id="kayla")(Ke||={});var st=B,at=({color:i,cx:e,cy:n,height:s,width:a,children:l})=>{let c=U();return J(()=>{c.color=i??"red",c.x=e??0,c.y=n??0,c.width=a??1,c.height=s??1}),l},Ie=({label:i,size:e,align:n="center",parentRect:s,color:a,x:l,y:c,ox:f=0,oy:h=0})=>{s??=U("parent"),Q(d=>{d.fillStyle=a,d.font=`${e}px sans-serif`,d.textBaseline="middle",d.textAlign=n,d.fillText(i.toString(),(s?.x??l)+f,(s?.y??c)+h)})};Reflect.set(globalThis,"Kayla",Re);var ot;(n=>(n.Flex=({align:s="stretch",children:a,direction:l="row",gap:c=0,justify:f="start",wrap:h="nowrap",getHeight:d,getWidth:p,getCenterX:b,getCenterY:x,color:v})=>{let t=we(),r=U(),o=H(()=>({recalc(){let u=Number(c)||0,y=b(),g=x(),w=p(),C=d();r.x=y,r.y=g,r.width=w,r.height=C;let K=t.getChildrenEntities().filter(Boolean).map(E=>E.getRect()).filter(E=>E.getFlag("flex-ignored")!==!0),R=l==="row",A=R?r.width:r.height,ut=R?r.height:r.width,de=0,O=0,fe=[],Z=[];K.forEach(E=>{let ee=R?E.width:E.height;de+ee>A&&h==="wrap"?(fe.push({height:O,items:Z}),Z=[E],de=ee,O=R?E.height:E.width):(Z.push(E),de+=ee+u,O=Math.max(O,R?E.height:E.width))}),fe.push({height:O,items:Z});let pe=0;fe.forEach((E,ee)=>{let M=E.items,V=M.reduce((k,te)=>k+(R?te.width:te.height),0)+u*(M.length-1),I=0;f==="center"&&(I=(A-V)/2),f==="end"&&(I=A-V),f==="space-between"&&(I=0),f==="space-around"&&(I=(A-V)/(M.length*2)),f==="space-evenly"&&(I=(A-V)/(M.length+1)),M.forEach((k,te)=>{k.z=r.z+1;let z=R?k.width:k.height,ne=R?k.height:k.width,re=0;s==="center"&&(re=(E.height-ne)/2),s==="end"&&(re=E.height-ne),s==="stretch"&&(R?k.height=E.height:k.width=E.height),R?(k.x=I+z/2,k.y=pe+re+ne/2):(k.x=pe+re+ne/2,k.y=I+z/2),f==="space-between"&&te<M.length-1?I+=z+u+(A-V)/(M.length-1):f==="space-around"?I+=z+u+(A-V)/M.length:f==="space-evenly"?I+=z+u+(A-V)/(M.length+1):I+=z+u}),pe+=E.height+u})}}));return Q((u,y)=>{y.preventDefault(),u.fillStyle=v,u.fillRect(r.left,r.top,r.width,r.height)}),J(()=>{ce(()=>{o.recalc()})}),he(n.Flex,()=>({controls:o})),a},n.GenericBox=({color:s,width:a=20,height:l=20,x:c=0,y:f=0})=>{let h=U();ue(()=>{h.width=a,h.height=l,h.x=c,h.y=f}),Q((d,p)=>{p.preventDefault(),d.fillStyle=s,d.fillRect(h.left,h.top,h.width,h.height)})}))(ot||={});function Et(i,e,n,...s){if(typeof i=="string")throw new Error("Cannot use intrinsic elements.");return Y(i,{...e,key:e.key??n,children:e.children??s})}function lt(i,e,n,...s){if(typeof i=="string")throw new Error("Cannot use intrinsic elements.");return Y(i,{...e,key:e.key??n,children:e.children??s})}function Kt(i,e,n){return lt(i,e,n)}var Rt=Ee;export{Rt as Fragment,Ke as JSX,Et as jsx,Kt as jsxDEV,lt as jsxs};
1
+ var Me=Object.defineProperty;var Le=(r,e)=>{for(var n in e)Me(r,n,{get:e[n],enumerable:!0})};var Se={};Le(Se,{JSX:()=>ke,KMatrix2D:()=>Ce,KaylaContext:()=>ce,KaylaElement:()=>Y,KaylaFragment:()=>Re,KaylaInternals:()=>H,KaylaRect:()=>D,Layer:()=>ot,Rect:()=>ut,Text:()=>Ae,createContext:()=>Oe,createElement:()=>Q,createGame:()=>He,createReassignableObject:()=>it,createRenderer:()=>Ue,createScene:()=>$e,createUseHook:()=>at,safeValueRepresentation:()=>J,self:()=>ve,setLogLevel:()=>st,tinyUID:()=>lt,useClick:()=>We,useContext:()=>tt,useCurrentGame:()=>Qe,useCurrentRenderer:()=>Ze,useCurrentScene:()=>Fe,useCurrentTicker:()=>et,useDisposableRef:()=>rt,useEffect:()=>Z,useEntity:()=>Je,useExports:()=>pe,useFiber:()=>Ke,useFiberControl:()=>Ee,useGlobalClick:()=>Ie,useGlobalPointer:()=>Be,useInitialization:()=>de,useNextStack:()=>fe,usePaint:()=>ee,usePointer:()=>je,useRect:()=>O,useRef:()=>we,useSelf:()=>z,useShouldRefresh:()=>Xe,useState:()=>Ne,useSubstep:()=>nt,useTick:()=>Ye,useUsing:()=>ht,useViewportEffect:()=>qe});var M=class{#e=new Map;constructor(){this.#e=new Map}on(e,n){let i=this.#e.get(e)||[];return i.push(n),this.#e.set(e,i),this}once(e,n){let i=(...a)=>{this.off(e,i),n(...a)};return this.on(e,i),this}off(e,n){let i=this.#e.get(e);if(!i)return this;let a=i.indexOf(n);return a>=0&&i.splice(a,1),this}emit(e,...n){let i=this.#e.get(e);if(!i||i.length===0){if(e==="error")throw n[0];return!1}return i.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}},oe=class extends M{#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:i,cameraWidth:a,cameraHeight:l}={}){if(!P)throw new Error("Web-Only");super(),this.canvas=e,this.automatic=!0,this.#n=n??e.width,this.#r=i??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||!P)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(!P||typeof globalThis.requestAnimationFrame>"u")throw new Error("Raf is not supported");this.running=!0,this._rafId=requestAnimationFrame(this._loop)}}stop(){if(!P||typeof globalThis.requestAnimationFrame>"u")throw new Error("Raf is not supported");this.running=!1,this._rafId!==null&&(cancelAnimationFrame(this._rafId),this._rafId=null)}},be=class extends M{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,!(P&&typeof this.__intervalId=="function"&&document.hidden)&&(this.#e+=n*1e3,this.emit("tick",n))}createTimeout(e){return new xe(e,this)}createTween(e,n=()=>{}){let i=new ge(e),a=(l=0)=>{if(i.finished){this.off("tick",a);return}i.update(l)};return i.on("finish",()=>{this.off("tick",a)}),i.on("delta",l=>{n(l)}),this.on("tick",a),i}start(){this.__intervalId===null&&(this.__lastTime=performance.now(),this.__intervalId=P&&!isFinite(this.tickInterval)?Ge(()=>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)}getLoopMod(e,n=0){return(this.now()+n*e)%e/e}},_e;(R=>{function r(f){return f===!0?1:0}R.booleanExport=r;function e(f){return f===0?!1:f===1}R.booleanImport=e;function n(f){return`${f.x}|${f.y}`}R.vec2Export=n;function i(f){let[t,s]=f.split("|"),o=parseFloat(t),u=parseFloat(s);if(isNaN(o)||isNaN(u))throw new Error(`Invalid Vector2 string: ${f}`);return new A(o,u)}R.vec2Import=i,R.booleanMap={mapExport:r,mapImport:e};function l(f){return t=>Number(t.toFixed(f))}R.createRounder=l;function c(f=10){return{mapExport(t){return Math.round(t/f)},mapImport(t){return t*f}}}R.createLowPrecision=c;function p(f){return Math.round(f)}R.lightWeightRounder=p;function h(f=100){return{mapExport(t){return Math.round(t*f)},mapImport(t){return t/f}}}R.createPercent=h;function d(f){let t=new Map(Object.entries(f));return{mapExport:s=>t.get(s)??null,mapImport:s=>Array.from(t.entries()).find(([o,u])=>u===s)?.[0]??null}}R.createLookup=d;function m(f){let t=f*(180/Math.PI);return Math.round((t%360+360)%360)}R.radToDeg=m;function x(f){return f*(Math.PI/180)}R.degToRad=x,R.angleRadToDeg={mapExport:m,mapImport:x};function S(f=10){let t=c(f);return{mapExport(s){return t.mapExport(m(s))},mapImport(s){return t.mapImport(x(s))}}}R.createLowPrecisionRadToDeg=S})(_e||={});var q=class r extends M{name="";scaleRotate=0;scale=1;constructor(e,n=0,i=0){super(),this.autoTranslate=!1,this.name=e,this.z=0,this.___pos=new A(n,i),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(!(_||!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 c=Reflect.get(this,a);return l?l(c):c});let e=["_events","_eventsCount","_maxListeners","nonSerializableProperties","forceSerializableProperties"],n=[...Reflect.ownKeys(this),...this.forceSerializableProperties].filter(a=>!this.nonSerializableProperties.includes(a)&&!e.includes(a.toString())),i=Object.fromEntries(n.map(a=>{let l=Reflect.get(this,a);if(_&&typeof l=="number"){let c=l.toString().split("."),h=(c[1]?c[1].length:0)>2?Number(l.toFixed(2)):l;return[a,h]}return[a,l]}));return JSON.parse(JSON.stringify(i))}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 i={};for(let a=0;a<n.length;a++){let l=e[a];if(!l)break;let[c,{mapImport:p}]=l,h=n[a];if(p&&(h=p(h)),typeof c!="string")break;try{Reflect.set(i,c,h)}catch(d){console.error(d)}}return i}},le=class extends M{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(!_&&!this.paused){this.emit("draw",e);for(let n of[...this.entities.values()].sort((i,a)=>i.z-a.z))n.handleDraw(e)}}addEntity(e){if(!(e instanceof q))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 q))throw new Error("invalid entity");this.entities.delete(e.name)}getEntity(e){return this.entities.get(e)}},ue=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,i=16){this.ticker=new be(i),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()}},I={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=I.clamp(r,0,1),r*r*(3-2*r)},randomLerp(r,e){return I.lerp(r,e,Math.random())},randomInt(r,e){return Math.floor(Math.random()*(e-r+1))+r},randomArrayValue(r){return r[I.randomInt(0,r.length-1)]},createBezier(r,e,n,i){function a(p,h,d,m,x){let v=1-p;return v*v*v*h+3*v*v*p*d+3*v*p*p*m+p*p*p*x}function l(p,h,d,m,x){let v=1-p;return 3*v*v*(d-h)+6*v*p*(m-d)+3*p*p*(x-m)}function c(p){let h=p;for(let d=0;d<6;d++){let m=a(h,0,r,n,1),x=l(h,0,r,n,1);if(x===0)break;h-=(m-p)/x}return I.clamp(h,0,1)}return function(h){h=I.clamp(h,0,1);let d=c(h);return a(d,0,e,i,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 I.normalizeRad(-r)},degToRadFlipY(r){return I.angleInvertY(r*Math.PI/180)},minimalAngularDirection(r,e){r=I.normalizeRad(r),e=I.normalizeRad(e);let n=I.normalizeRad(e-r),i=I.normalizeRad(r-e);return n<=i?1:-1}},ge=class extends M{constructor({delta:e,ms:n,easing:i}){super(),this.delta=e,this.duration=n,this.elapsed=0,this.easing=i??(a=>a),this.lastValue=0,this.finished=!1}delta;duration;elapsed;lastValue;finished;easing;update(e){this.elapsed+=e*1e3;let n=I.clamp(this.elapsed/this.duration,0,1),i=this.easing(n),a=this.delta*i,l=a-this.lastValue;this.lastValue=a,this.emit("delta",l),n>=1&&(this.finished=!0,this.emit("finish",void 0))}},he=class extends q{constructor(e,n=0,i=0,a=50,l=50){super(e,n,i),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)}},xe=class extends M{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(i=>this._resolve=i),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)}},A=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),i=Math.sin(e);return new r(this.x*n-this.y*i,this.x*i+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(),i=e.normalized();return n.x*i.x+n.y*i.y}lengthSquaredTo(e){let n=this.x-e.x,i=this.y-e.y;return n*n+i*i}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,i=this.y-e.y;return n*n+i*i}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 Te=De(),_=Te==="node",P=Te==="web",B=class r{static unlock(){P&&this.audioCtx.state!=="running"&&this.audioCtx.resume()}static audioCtx=P?new AudioContext:null;static masterGain=P?this.audioCtx.createGain():null;static musicGain=P?this.audioCtx.createGain():null;static sfxGain=P?this.audioCtx.createGain():null;static{P&&(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,i,a;if(typeof caches<"u"&&(a=await caches.open(n),i=await a.match(e)),!i){if(i=await fetch(e),!i.ok)throw new Error(`Failed to fetch ${e}`);a&&await a.put(e,i.clone())}let l=await i.arrayBuffer(),c=await this.audioCtx.decodeAudioData(l);return this.audioBufferCache.set(e,c),c}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,i=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 c=new X(l);c.buffer=l;let p=1-.12,h=1+.12;c.playbackRate=i??p+Math.random()*(h-p);let d=this.audioCtx.createGain();d.gain.value=n,c.tempGain=d,c.connect(d),d.connect(this.sfxGain),c.onended=()=>{c.disconnect(),d.disconnect()},c.start(),a&&this.sfsx.set(e,{source:c,gain:d})}catch(l){console.error(l)}}static async playLoop(e,n=1,{loopStart:i=0,loopEnd:a=null,exclusive:l=!0,skipMS:c=0}={}){if(l)for(let x of this.loops.keys())this.stopLoop(x);this.audioBufferCache.has(e)||await this.preLoad(e);let p=this.getCached(e);if(!p)return;let h=new X(p);h.buffer=p,h.loop=!0,typeof i=="number"&&(h.loopStart=i),typeof a=="number"&&(h.loopEnd=a);let d=this.audioCtx.createGain();d.gain.value=n,h.tempGain=d,h.playbackRate=1,h.onended=()=>{h.disconnect(),d.disconnect()},h.connect(d),d.connect(this.musicGain),h.start(0,c/1e3);let m=++this.loopIdCounter;return this.loops.set(m,{source:h,gain:d}),m}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:i=1,loop:a=!1,loopStart:l=0,loopEnd:c=null,isMusic:p=!1,gain:h=null}={}){try{this.audioBufferCache.has(e)||await this.preLoad(e);let d=this.getCached(e);if(!d)return null;let m=new X(d);m.loop=a,m.loopStart=l,m.loopEnd=typeof c=="number"?c:d.duration,m.playbackRate=i;let x=this.audioCtx.createGain();return x.gain.value=n,m.connect(x),m.tempGain=x,x.connect(h||(p?this.musicGain:this.sfxGain)),m.onended=()=>{m.disconnect(),x.disconnect()},m}catch(d){return console.error("Failed to create LiaAudioSrc:",d),null}}};var X=class{numberOfInputs;numberOfOutputs;constructor(e,n=B.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=P?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 i=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-i/this.playbackRate,this.source.start(0,i),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,i){this.isPlaying||(this.source=this._createSource(),this.startTime=this.context.currentTime+e-n/this.playbackRate,i!==void 0?this.source.start(this.context.currentTime+e,n,i):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 i=this.loopEnd-this.loopStart;n=this.loopStart+(n-this.loopStart)%i}if(this.isPlaying=!1,e>0){let i=this.context.currentTime;this.output.gain.setValueAtTime(this.output.gain.value,i),this.output.gain.linearRampToValueAtTime(0,i+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,i=0){if("value"in e)this.output.connect(e,n);else return this.output.connect(e,n,i),e}disconnect(e,n,i){e===void 0?this.output.disconnect():this.output.disconnect(e,n,i)}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},Ve={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},G=class r{constructor(e={}){if(_)return this;this.ctx=B.audioCtx,this.cfg=structuredClone(Ve),Object.assign(this.cfg,e)}ctx;cfg;play(e=B.sfxGain){if(_)throw new Error("Cannot use Web APIs on node.");let n=this.ctx,i=n.currentTime,a=this.cfg,l=n.createGain();l.gain.setValueAtTime(1e-4,i);let c=a.ampEnv;l.gain.exponentialRampToValueAtTime(c.volume,i+c.attack),l.gain.exponentialRampToValueAtTime(Math.max(1e-4,c.sustain*c.volume),i+c.attack+c.decay),l.gain.exponentialRampToValueAtTime(1e-4,i+a.duration+c.release);let p=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),p=h);let d;if(a.osc.enabled){if(d=n.createOscillator(),d.type=a.osc.type,d.frequency.value=a.osc.freq,d.detune.value=a.osc.detune,a.pitchEnv.amount!==0){let f=Math.pow(2,a.pitchEnv.amount/12);d.frequency.exponentialRampToValueAtTime(a.osc.freq*f,i+a.pitchEnv.decay)}d.connect(p),d.start(i),d.stop(i+a.duration+c.release)}let m;if(a.noise.enabled){let f=n.sampleRate*a.duration,t=n.createBuffer(1,f,n.sampleRate),s=t.getChannelData(0);for(let o=0;o<f;o++)s[o]=(Math.random()*2-1)*a.noise.level;m=n.createBufferSource(),m.buffer=t,m.connect(p),m.start(i),m.stop(i+a.duration+c.release)}let x,v;a.lfo.enabled&&d&&(x=n.createOscillator(),x.frequency.value=a.lfo.rate,v=n.createGain(),v.gain.value=a.lfo.depth,x.connect(v),a.lfo.target==="freq"?v.connect(d.frequency):a.lfo.target==="gain"?v.connect(l.gain):a.lfo.target==="filter"&&h&&v.connect(h.frequency),x.start(i),x.stop(i+a.duration)),l.connect(e);let S=[d,m,x,v,h,l],R=i+a.duration+c.release;setTimeout(()=>{S.forEach(f=>f?.disconnect())},(R-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,i,a){return Object.assign(this.cfg.ampEnv,{attack:e,decay:n,sustain:i,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,i){return Object.assign(this.cfg.filter,{type:e,freq:n,Q:i,enabled:!0}),this}setLFOEnabled(e){return this.cfg.lfo.enabled=e,this}setLFO(e,n,i){return Object.assign(this.cfg.lfo,{target:e,rate:n,depth:i,enabled:!0}),this}setDuration(e){return this.cfg.duration=e,this}clone(){return new r(structuredClone(this.cfg))}},ft=new G({osc:{enabled:!0,type:"square",freq:900,detune:0},ampEnv:{attack:.002,decay:.04,sustain:0,release:.02,volume:.15},duration:.05}),mt=new G({osc:{enabled:!0,type:"sine",freq:600,detune:0},ampEnv:{attack:.01,decay:.08,sustain:0,release:.04,volume:.12},duration:.1}),yt=new G({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}),bt=new G({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}),gt=new G({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 j(r=12){let e=Date.now().toString(36),n=crypto.getRandomValues(new Uint8Array(4)),i=Array.from(n).map(a=>a.toString(36).padStart(2,"0")).join("");return(e+i).slice(0,r)}function Ge(r){let e=!0;function n(){e&&(r(),requestAnimationFrame(n))}return requestAnimationFrame(n),{clear:()=>e=!1}}function ze(){return _?!1:/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)}var xt=ze(),W=class r{static defaultInterval=1e3/60;handler;interval;accumulated;constructor(e=r.defaultInterval,n){this.handler=n??null,this.interval=e,this.accumulated=0}update(e){if(!this.handler)throw new Error("Missing handler.");if(this.interval<=.001){this.handler(this,0);return}this.accumulated+=e*1e3;let n=0;for(;this.accumulated>=this.interval;)this.accumulated-=this.interval,this.handler(this,n),n++}};function He({width:r,height:e,updateHz:n="frames"}){return new H.KaylaGame(r,e,n==="frames"?1/0:n)}function $e(r){let e=new le(r);return new H.KaylaScene(e)}function Ue(r,e){return new H.KaylaRenderer(r,e)}function Q(r,e){if(typeof r!="function")throw new Error("Invalid Element Type.");let n=e??{};n.key??=r.name+"_"+j();let i=Array.isArray(e.children)?[...e.children]:e.children?[e.children]:[];for(let l=0;l<i.length;l++){let c=i[l];if(typeof c!="object"||!(c instanceof Y))if(typeof c=="string")i[l]=Q(Ae,{color:"white",label:c,parentRect:null,x:0,y:0,size:20,align:"center"});else throw new Error("Invalid JSX Child Parameter.")}n.children=i;let a=new Y;return a.type=r,a.props=n,a}var Y=class{type;props},D;(i=>{function r(a,l){return!(a.right<l.left||a.left>l.right||a.bottom<l.top||a.top>l.bottom)}i.rawCollision=r;function e(a,l,c){let p=l*Math.PI/180,h=Math.cos(p),d=Math.sin(p),m=1/0;return h>0&&(m=Math.min(m,(c.right-a.x)/h)),h<0&&(m=Math.min(m,(c.left-a.x)/h)),d>0&&(m=Math.min(m,(c.bottom-a.y)/d)),d<0&&(m=Math.min(m,(c.top-a.y)/d)),A.from(l).scale(m)}i.getCurrToBound=e;function n(a){let{left:l,right:c,top:p,bottom:h,width:d,height:m,x=0,y:v=0}=a;if(d===null||m===null)throw new Error("width and height are required");let S,R;if(l!=null&&c!=null){if(Math.abs(c-l-d)>1e-6)throw new Error("left, right, and width mismatch");S=l}else x!=null?S=x-d/2:l!=null?S=l:c!=null?S=c-d:S=0;if(p!=null&&h!=null){if(Math.abs(h-p-m)>1e-6)throw new Error("top, bottom, and height mismatch");R=p}else v!=null?R=v-m/2:p!=null?R=p:h!=null?R=h-m:R=0;return{left:S,right:S+d,top:R,bottom:R+m,width:d,height:m,x:S+d/2,y:R+m/2}}i.createRawRect=n})(D||={});var H;(R=>{class r extends ue{#e;#t;constructor(t,s,o){super(t,s,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)}}R.KaylaGame=r;class e extends oe{game;pointerX;pointerY;pointerEvents;onPointerDown;onPointerUp;onPointerCancel;onPointerMove;isKaylaDisabled;constructor(t,s={}){super(t),this.isKaylaDisabled=s.disableKaylaBehavior,this.useDraw=this.useDraw.bind(this),this.on("draw",o=>{if(!s.noAutoDraw&&this.game)for(let u of this.game.scenes.values())u.handleDraw(o)}),this.pointerX=0,this.pointerY=0,this.pointerEvents=new M,this.pointerPosUpdater=this.pointerPosUpdater.bind(this),this.onPointerDown=o=>this.onPointerAll(o,"down"),this.onPointerUp=o=>this.onPointerAll(o,"up"),this.onPointerCancel=o=>this.onPointerAll(o,"cancel"),this.onPointerMove=o=>this.onPointerAll(o,"move")}pointerPosUpdater(t){this.pointerX=t.clientX,this.pointerY=t.clientY}onPointerAll(t,s){this.pointerPosUpdater(t);let o=e.getClickType(t);if(o!=="invalid"||s==="move"||s==="cancel"){t.preventDefault();let u=this.getMousePos();this.pointerEvents.emit("action",u,o,s)}}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,s){let o=this.canvas.getBoundingClientRect(),u=(t-o.left)/o.width,b=(s-o.top)/o.height,g=this.cameraWidth/o.width,w=this.cameraHeight/o.height,K=u*this.viewportWidth*this.cameraWidth/o.width/g,E=b*this.viewportHeight*this.cameraHeight/o.height/w;return new A(K,E)}camToViewportPos(t,s){let o=t/this.cameraWidth*this.viewportWidth,u=s/this.cameraHeight*this.viewportHeight;return new A(o,u)}pointerPosToWorldPosOLD(t,s){let o=this.canvas.getBoundingClientRect(),u=(t-o.left)/o.width,b=(s-o.top)/o.height,g=u*this.viewportWidth*this.cameraWidth/o.width,w=b*this.viewportHeight*this.cameraHeight/o.height;return new A(g,w)}getMousePos(){return this.pointerPosToWorldPos(this.pointerX,this.pointerY)}useDraw(t){let s=o=>{t(o,new l)};return this.on("draw",s),()=>{this.off("draw",s)}}attachTo(t){t.addRenderer(this),this.game=t}detach(){this.game&&this.game.deleteRenderer(this)}}R.KaylaRenderer=e;let n=Symbol("unlock_substepper");class i{#e;constructor(t){this.#e=t}[n](){return this.#e}get interval(){return this.#e.interval}}class a{current;saves;constructor(){this.saves=[]}useTick(t,s=null){if(!this.current)throw new Error("Hook 'useTick' must be executed in the top level scope of a component.");let o=t;this.current.onTick[this.current.useStepCallIndex]=o,this.current.onTickSubsteps[this.current.useStepCallIndex]=s,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 we(ve)}useSelf(t){if(!this.current)throw new Error("Hook 'useSelf' must be executed in the top level scope of a component.");let s=we(null);return(s.current===null||s.current===void 0)&&(s.current=t()),s.current}useInitialization(t){if(!this.current)throw new Error("Hook 'useInitialization' must be executed in the top level scope of a component.");let s=this.current;s.onInits[this.current.useInitCallIndex]=t,s.useInitCallIndex++}useRect(t="self"){if(!this.current)throw new Error("Hook 'useRect' must be executed in the top level scope of a component.");if(t==="disposableSelf")return new R.KaylaInternalRect(this.current);let s=null;if(t==="self"&&(s=this.current),t==="parent"&&(s=this.current.detectedParent),!s)throw new Error("Missing valid target fiber.");return z(()=>new R.KaylaInternalRect(s))}useSubstep(t){t==="default"&&(t=W.defaultInterval);let s=z(()=>{let u=new W(0);return new i(u)}),o=s[n]();return o.interval=t,s}useFiber(){if(!this.current)throw new Error("Hook 'useFiber' must be executed in the top level scope of a component.");return z(()=>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 z(()=>({refresh:()=>t.refresh(),toString(){return t.toString()},get childrenCount(){return t.lastChildren.length},setMaxChildren:s=>{t.setMaxChildren(s)},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:s=!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 c(this.current,t,{alwaysRecall:s});return this.current.state[this.current.useStateCallIndex]=u,this.current.useStateCallIndex++,u}useShouldRefresh(t){let s=this.current;if(!s)throw new Error("useShouldRefresh must be called inside a component");s.watchedDeps&&console.warn("useShouldRefresh called multiple times \u2014 using the last call"),s.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]??h(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,s){if(!this.current)throw new Error("Hook 'useExports' must be executed in the top level scope of a component.");this.current.onExport=s}useGlobalPointer(t,s){if(!this.current)throw new Error("Hook 'useGlobalPointer/useGlobalClick' must be executed in the top level scope of a component.");s??={},this.current.onGlobalPointer[this.current.useGlobalClickCallIndex]={handler:t,config:s},this.current.useGlobalClickCallIndex++}usePointer(t,s){if(!this.current)throw new Error("Hook 'usePointer/useClick' must be executed in the top level scope of a component.");s??={};let o=this.current;Ie((u,b,g)=>{let w=o.entity;if(!w)return;let K=w.getRawRect(),E=D.createRawRect({x:u.x,y:u.y,width:3,height:3});D.rawCollision(K,E)&&t(u,b,g)},s)}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,s,o,...u)=>{let b=t?.fc?.name||"anonymous",g=t?.key?` key=${t.key}`:"";this.logger[s](`${o} <${b}${g}>`,...u)}}}R.GlobalKayla=a;class l{preventDefault(){this.#e=!0}#e=!1;isPrevented(){return this.#e}}R.KaylaEvent=l;class c{#e;#t;#n;alwaysRecall;constructor(t,s,{alwaysRecall:o=!1}={}){this.#t=t,this.#e=s??void 0,this.#n=Date.now(),this.alwaysRecall=o}get(){return this.#e}get 0(){return this.get()}1(t){this.set(t,{recall:!0})}legacy(){return[this[0],this[1].bind(this)]}add(t,{recall:s}={}){this.set(this.get()+t,{recall:s})}multiply(t,{recall:s}={}){this.set(this.get()*t,{recall:s})}set(t,{recall:s=!1}={}){let o=this.#e;if(t===o)return;this.#e=t;let b=Date.now()-this.#n;s&&b<67&&this.#t.global.logger.warn(`Hot structural state change <${this.#t.fc?.name||"anonymous"}> delta=${b}ms`),(s||this.alwaysRecall)&&this.#t.refresh(),this.#n=Date.now()}get value(){return this.#e}get lastChanged(){return this.#n}}R.KaylaInternalState=c;class p{#e;constructor(t){this.#e=t??void 0}#t;setSetter(t){this.#t=t}get current(){return this.#e}set current(t){this.#e=t,this.#t&&this.#t(this.#e)}}R.KaylaInternalRef=p;function h(f){return new p(f)}R.createReassignableRef=h;class d{state;refs;global;callProps;scene;exports;detectedParent;contextInfo;lastLayer;get childrenCount(){return this.lastChildren.length}maxSafeChildren;dynamicChildren;constructor(t,s,o){if(!o)throw new Error("Empty element");this.maxSafeChildren=40,this.scene=s,this.state=[],this.refs=[],this.onInits=[],this.onUnInits=[],this.fc=o.type,this.callProps=o.props??{},this.global=t,this.lastStateDeps=[],this.entity=null,this.lastChildren=[],this.onEffect=[],this.onUnEffect=[],this.onPaint=[],this.onTick=[],this.onTickSubsteps=[],this.onGlobalPointer=[],this.pointerHook=this.pointerHook.bind(this),this.resizeHook=this.resizeHook.bind(this),this.contextInfo=null,this.detectedParent=null,this.dynamicChildren=[],this.key??=this.fc.name+"_"+j(),this.onViewportEffect=[],this.lastLayer=null}getCorrectMousePos(t){return t??=this.getAttachedRenderer().getMousePos(),this.lastLayer?.transform?this.lastLayer.transform.inverseV(t):t}getChildrenEntities(){return this.lastChildren.map(t=>t.entity)}pointerHook(t,s,o){t=this.getCorrectMousePos(t);try{for(let{handler:u,config:b}of this.onGlobalPointer)b.type??="any",b.action??="down",!(b.action!=="any"&&b.action!==o||b.type!=="any"&&b.type!==s)&&u(t,s,o)}catch(u){this.global.logger.error(u)}}resizeHook({width:t,height:s}){try{for(let o of this.onViewportEffect)o(this.getAttachedRenderer(),t,s)}catch(o){this.global.logger.error(o)}}bindEvents(){for(let t of[this.getAttachedRenderer()])t&&(t.pointerEvents.on("action",this.pointerHook),t.on("viewport_update",this.resizeHook))}unbindEvents(){for(let t of[this.getAttachedRenderer()])t&&(t.pointerEvents.off("action",this.pointerHook),t.off("viewport_update",this.resizeHook))}get key(){return this.callProps.key}set key(t){this.callProps.key=t}get children(){let t=this.callProps.children;return Array.isArray(t)?t:[t]}set children(t){this.callProps.children=t}entity;onExport=()=>({});onEffect;onViewportEffect;onGlobalPointer;onInits;onUnInits;onUnEffect;onEffectDeps;onPaint;onTick;onTickSubsteps;fc;useStateCallIndex=0;useEffectCallIndex=0;useGlobalClickCallIndex=0;useDrawCallIndex=0;useStepCallIndex=0;useRefCallIndex=0;useInitCallIndex=0;useViewCallIndex=0;lastStateDeps;watchedDeps;lastDepStamps=[];getAttachedRenderer(){return this.getAttachedGame().mainRenderer}getAttachedGame(){return this.scene.getGame()}setMaxChildren(t){if(this.maxSafeChildren=Math.max(0,t),this.global.logger.debug(`Max children limit updated to ${t} for <${this.fc?.name||"anonymous"} key=${this.key}>`),this.lastChildren.length>this.maxSafeChildren){let s=this.lastChildren.length-this.maxSafeChildren;this.global.logger.warn(`Child limit exceeded (${this.lastChildren.length} > ${this.maxSafeChildren}) \u2014 removing ${s} oldest children <${this.fc?.name||"anonymous"} key=${this.key}>`);let o=this.lastChildren.slice(0,this.maxSafeChildren),u=this.lastChildren.slice(this.maxSafeChildren);this.lastChildren=o;for(let b of u)b.unuse()}}getMaxChildren(){return this.maxSafeChildren??1/0}getFiberChain(){let t=[],s=this.detectedParent;for(;s;)t.push(s),s=s?.detectedParent;return t}getAllChildrenNestedFlattened(){let t=[],s=(o=[])=>{for(let u of o)t.push(u),u.lastChildren?.length&&s(u.lastChildren)};return s(this.lastChildren),t}getContextChain(){return this.getFiberChain().map(t=>t.contextInfo).filter(Boolean)}findContextValueFromInst(t){return this.getContextChain().find(s=>s.instance===t)?.value}getEntityChain(){return this.getFiberChain().map(t=>t.entity)}shouldFullRefresh(){if(this.isFirstUse||!this.watchedDeps||this.watchedDeps.length===0)return!0;for(let t=0;t<this.watchedDeps.length;t++){let s=this.watchedDeps[t],o=this.lastDepStamps[t]??0;if(s.lastChanged>o)return!0}return!1}captureDepStamps(){this.watchedDeps&&(this.lastDepStamps=this.watchedDeps.map(t=>t.lastChanged))}refresh(){if(!this.shouldFullRefresh())return;let t=this.fc?.name||"anonymous";if(!this.shouldFullRefresh()){this.global.logger.debug(`Refresh skipped <${t} key=${this.key}>`);return}this.global.logger.debug(`Refresh executed <${t} key=${this.key}> reason=${this.isFirstUse?"first":"deps-changed"}`),this.lastChildren.length>this.maxSafeChildren&&this.global.logger.warn(`High child count <${t} key=${this.key}> children=${this.lastChildren.length}`);let s;this.global.save(),this.global.current=this,this.useStateCallIndex=0,this.useRefCallIndex=0,this.useInitCallIndex=0,this.useViewCallIndex=0,this.useStateCallIndex=0,this.useDrawCallIndex=0,this.useStepCallIndex=0,this.useEffectCallIndex=0,this.useGlobalClickCallIndex=0;let o=[];try{let u=this.fc(this.callProps)??[];if(u&&!Array.isArray(u)&&(u=[u]),!Array.isArray(u))throw new Error("Non array or non undefined children received.");for(let b of u);o=u}catch(u){s=u}if(this.global.restore(),this.updateChildren(o,!0),s)throw s}updateChildren(t,s){try{let o=[...t,...this.dynamicChildren],u=[],b=[];for(let g of o){let w=g.props?.key,K;w!=null&&(K=this.lastChildren.find(E=>E.key===w)),K||(K=new d(this.global,this.scene,g)),K.callProps=g.props,K.key=w??`${g.type?.name??""}_${j()}`,K.detectedParent=this,b.push(K),u.push(K)}for(let g of this.lastChildren)u.includes(g)||g.unuse();this.lastChildren=b,this.captureDepStamps(),this.use();for(let g of this.lastChildren)try{g.refresh()}catch(w){console.error(w)}}catch(o){console.error(o)}}toString(){return this.getStringRepresentation(0," ")}lastChildren;isFirstUse=!0;use(){try{let t=!0;if(this.lastStateDeps??=[],Array.isArray(this.onEffectDeps)&&(t=!0),t||this.isFirstUse){this.global.logger.debug(`Using <${this.fc?.name||"anonymous"} key=${this.key}> count=${this.onEffect.length}`);let s=this.isFirstUse;this.isFirstUse=!1,Array.isArray(this.onEffectDeps)&&(this.lastStateDeps=this.onEffectDeps.map(u=>({stamp:u.lastChanged,stateRef:u}))),this.entity&&this.scene.getScene().removeEntity(this.entity),this.entity&&this.entity.name!==this.key&&(this.entity=null),this.entity=this.entity??new m(this,this.key);for(let u of this.refs)u.current===ve&&(u.current=this.entity);if(this.callProps.ref instanceof p&&(this.callProps.ref.current=this.entity),this.exports=this.onExport(),this.callProps.exportsRef instanceof p&&(this.callProps.exportsRef.current=this.exports),this.entity&&this.entity!==this.entity&&this.global.logger.warn(`Entity name mismatch during refresh <${this.fc?.name} key=${this.key}>`),this.scene.getScene().addEntity(this.entity),s){this.onUnInits=[];for(let u of this.onInits){this.bindEvents();try{let b=u();typeof b=="function"&&this.onUnInits.push(b)}catch(b){throw this.global.logger.error("Initialization failed",this.fc?.name||"anonymous",b),b}}}try{for(let u of this.onUnEffect??[])u()}catch(u){console.error(u)}let o=this.onEffect.map(u=>u()).filter(u=>u!==void 0);this.onUnEffect=o}}catch(t){throw this.global.logger.error(`use() failed <${this.fc?.name||"anonymous"} key=${this.key}>`,t),t}}unuse(){this.global.logger.debug(`unuse called <${this.fc?.name||"anonymous"} key=${this.key}> children=${this.lastChildren.length}`),this.detectedParent=null,this.watchedDeps=void 0,this.lastDepStamps=[],this.unbindEvents();try{for(let t of this.onUnInits)t();for(let t of this.onUnEffect)t()}catch(t){this.global.logger.error(`Cleanup failed in unuse <${this.fc?.name||"anonymous"} key=${this.key}>`,t)}this.scene.getScene().removeEntity(this.entity);for(let t of this.lastChildren)t.unuse();this.lastChildren.length=0}getStringRepresentation(t=0,s=" "){let o=s.repeat(t),u=this,b="",g=Object.entries(this.callProps);for(let E=0;E<g.length;E++){let[C,$]=g[E];if(["children"].includes(C))continue;b+=` ${C}=${typeof $=="string"?`${J($)}`:`{${J($,0)}}`}`}let w=Array.from(u.lastChildren).map(E=>E.getStringRepresentation(t+1,s)).join(""),K=u.fc.displayName??u.fc.name.replaceAll(" ","-");return w&&w.length>0?`${o}<${K}${b}>
2
+ ${w}${o}</${K}>
3
+ `:`${o}<${K}${b}/>
4
+ `}}R.KaylaFiber=d;class m extends he{#e;flags;getRawRect(){return D.createRawRect({x:this.x,y:this.y,width:this.width,height:this.height})}getFiber(){return this.#e}constructor(t,s){super(s,0,0,0,0),this.#e=t,this.flags=new Map,this.color="transparent"}setFlag(t,s){return this.flags.set(t,s)}getFlag(t){return this.flags.get(t)}removeFlag(t){return this.flags.delete(t)}update(t){fe(()=>{let s=new l;if(this.#e&&this.#e.onTick){let o=0;for(let u of this.#e.onTick){let b=this.#e.onTickSubsteps.at(o)??null;if(b){let g=b[n]();g.handler=()=>{u(g.interval/1e3,s)},g.update(t)}else u(t,s);o++}}s.isPrevented()})}draw(t){let s=new l;if(this.#e&&this.#e.onPaint)for(let o of this.#e.onPaint)o(t,s);s.isPrevented()||super.draw(t)}getRect(){return new x(this.getFiber())}}R.KaylaRectEntity=m;class x{#e;constructor(t){this.#e=t}get color(){return this.#t(),this.entity.color}set color(t){this.#t(),this.entity.color=t}getRaw(){return D.createRawRect({x:this.x,y:this.y,width:this.width,height:this.height})}get entity(){return this.#e.entity??null}#t(){if(!this.#e)throw new Error("No fibers found.");if(!this.entity)throw new Error("The entity does NOT exist yet.")}isCollidingWith(t){return this.#t(),this.entity.isCollidingWith(t.entity)}get setFlag(){return this.#t(),this.entity.setFlag.bind(this.entity)}get getFlag(){return this.#t(),this.entity.getFlag.bind(this.entity)}get removeFlag(){return this.#t(),this.entity.removeFlag.bind(this.entity)}isHovered(){let t=this.getRaw(),s=this.#e.getCorrectMousePos(),o=D.createRawRect({x:s.x,y:s.y,width:3,height:3});return D.rawCollision(t,o)}get pos(){return this.#t(),this.entity.pos}get x(){return this.#t(),this.pos.x}set x(t){this.#t(),this.pos.x=t}get y(){return this.#t(),this.pos.y}set y(t){this.#t(),this.pos.y=t}get width(){return this.#t(),this.entity.width}set width(t){this.#t(),this.entity.width=t}get height(){return this.#t(),this.entity.height}set height(t){this.#t(),this.entity.height=t}get z(){return this.#t(),this.entity.z}set z(t){this.#t(),this.entity.z=t}get left(){return this.#t(),this.entity.left}set left(t){this.#t(),this.entity.left=t}get right(){return this.#t(),this.entity.right}set right(t){this.#t(),this.entity.right=t}get top(){return this.#t(),this.entity.top}set top(t){this.#t(),this.entity.top=t}get bottom(){return this.#t(),this.entity.bottom}set bottom(t){this.#t(),this.entity.bottom=t}get toLocal(){return this.entity.toLocal.bind(this.entity)}get toWorld(){return this.entity.toWorld.bind(this.entity)}}R.KaylaInternalRect=x;class v{#e;#t;constructor(t){this.#r=t,this.#n=null,this.#e=new Map,t.on("update",this.tickHandler.bind(this)),this.drawHandler=this.drawHandler.bind(this),t.handleDraw=this.drawHandler,this.#t=null}getLayers(){return this.#e}#n;#r;getFibers(){return this.getEntities().map(t=>t.getFiber())}getEntities(){return Array.from(this.getScene().entities.values())}getScene(){return this.#r}getGame(){return this.#n}getOrCreateLayer(t,s=0){return this.#e.has(t)||this.#e.set(t,{name:t,z:s,visible:!0,rootFiber:null}),this.#e.get(t)}getSortedLayers(){return Array.from(this.#e.values()).filter(t=>t.visible).sort((t,s)=>t.z-s.z)}setLayerVisible(t,s){let o=this.#e.get(t);o&&(o.visible=s)}handleDraw(t){if(_)return;let s=this.getScene();if(s.paused)return;s.emit("draw",t);let o=this.getSortedLayers(),u=[];for(let g of o){if(!g.visible)continue;let w=g.rootFiber;if(!w)continue;let K=w.getAllChildrenNestedFlattened().flat().map(C=>C.entity).filter(Boolean);if(u.push(...K),t.save(),g.transform){let C=g.transform;t.setTransform(C.a,C.b,C.c,C.d,C.e,C.f)}g.blendMode&&(t.globalCompositeOperation=g.blendMode??"source-over");let E=Array.from(K).sort((C,$)=>C.z-$.z);for(let C of E)C.getFiber().lastLayer=g,C.handleDraw(t);t.restore()}let b=[...s.entities.values()].filter(g=>!u.includes(g));for(let g of b.sort((w,K)=>w.z-K.z)){let w=g instanceof m?g.getFiber():null;w&&(w.lastLayer=null),g.handleDraw(t)}}drawHandler(t){return this.handleDraw(t)}attachTo(t){t.addScene(this.#r),this.#n=t}async spawn(t){this.#t&&(this.#t.unuse(),this.#t=null);let s=this.createFiber(t);this.#t=s,await this.#n.delay(0),s.refresh()}getRoot(){return this.#t??null}createFiber(t){return new d(R.singleGlobalInstance,this,t)}detach(){this.#n&&this.#n.removeScene(this.#r)}tickHandler(){}}R.KaylaScene=v,R.singleGlobalInstance=new R.GlobalKayla})(H||={});var ce=class{#e;constructor(e){this.Provider=this.#t.bind(this),this.#e=e,this.Provider.displayName="[[ KaylaContext ]].Provider"}get defaultValue(){return this.#e}#t({value:e=this.defaultValue,children:n}){let i=Ke();return Z(()=>{i.contextInfo={instance:this,value:e}}),pe(this.Provider,()=>({value:e})),n}Provider;Consumer};function Oe(r){return new ce(r)}var y=H.singleGlobalInstance,Ne=y.useState.bind(y),we=y.useRef.bind(y),Xe=y.useShouldRefresh.bind(y),Z=y.useEffect.bind(y),qe=y.useViewportEffect.bind(y),Ie=y.useGlobalPointer.bind(y),Be=y.useGlobalPointer.bind(y),We=y.usePointer.bind(y),je=y.usePointer.bind(y),de=y.useInitialization.bind(y),O=y.useRect.bind(y),Ye=y.useTick.bind(y),ee=y.usePaint.bind(y),pe=y.useExports.bind(y),z=y.useSelf.bind(y),Ee=y.useFiberControl.bind(y),Ke=y.useFiber.bind(y),Je=y.useEntity.bind(y),Qe=y.useCurrentGame.bind(y),Ze=y.useCurrentRenderer.bind(y),Fe=y.useCurrentScene.bind(y),et=y.useCurrentTicker.bind(y),tt=y.useContext.bind(y),nt=y.useSubstep.bind(y),ve=Symbol("self_ref");var fe=r=>{Promise.resolve(1).then(()=>{try{r()}catch(e){console.error(e)}})},Re=({children:r})=>Array.isArray(r)?[...r]:r;function rt(r){return H.createReassignableRef(r)}function it(r){if(typeof r!="object"||typeof r=="function"||r===null)return r;let e={current:r};return new Proxy({},{get(i,a,l){return a==="reassignSelf"?c=>{e.current=c}:Reflect.get(e.current,a,l)},set(i,a,l,c){return Reflect.set(e.current,a,l,c)},has(i,a){return Reflect.has(e.current,a)},ownKeys(i){return Reflect.ownKeys(e.current)},getOwnPropertyDescriptor(i,a){return Reflect.getOwnPropertyDescriptor(e.current,a)},deleteProperty(i,a){return Reflect.deleteProperty(e.current,a)}})}function st(r){y.logLevel=r}function at(r){let e=r.name||"anonymous-custom-hook";function n(...i){let a=y.current;if(!a)throw new Error(`Custom hook '${e}' must be called inside a Kayla component`);let l=i??[];return a.global.logLevel==="debug"&&a.global.logger.debug(`Custom hook '${e}' running (non-memoized) <${a.fc?.name||"anonymous"} key=${a.key||"no-key"}>`),r.onUse(a,y,...l)}return n.name=r.name,n}var ot=({name:r,z:e=0,blend:n,visible:i=!0,children:a,transform:l})=>{let c=Fe(),p=Ke();return de(()=>{let h=c.getOrCreateLayer(r,e);return h.blendMode=n,h.visible=i,h.rootFiber=p,h.transform=l??null,()=>{c.getLayers().delete(r)}}),a},Ce=class extends DOMMatrix{#e;constructor(){super(),this.#e=new DOMPoint}transformV(e){this.#e.x=e.x,this.#e.y=e.y;let n=this.#e.matrixTransform(this);return new A(n.x,n.y)}inverseV(e){let n=this.inverse();this.#e.x=e.x,this.#e.y=e.y;let i=this.#e.matrixTransform(n);return new A(i.x,i.y)}},J=(r,e=0)=>{try{if(Array.isArray(r))return`[ ${r.map(n=>J(n,e)).join(", ")} ]`;if(typeof r=="object"&&r!==null){let n=r.constructor?.name;return n!=="Object"&&n?`[[ ${n} ]]`:`{ ${Object.entries(r).map(([i,a])=>`${i}: ${J(a,e)}`).join(", ")} }`}return JSON.stringify(r,null,e)}catch{return"[[ Non-serializable ]]"}},ke;(e=>e.id="kayla")(ke||={});var lt=j,ut=({color:r,cx:e,cy:n,height:i,width:a,children:l})=>{let c=O();return Z(()=>{c.color=r??"red",c.x=e??0,c.y=n??0,c.width=a??1,c.height=i??1}),l},Ae=({label:r,size:e,align:n="center",parentRect:i,color:a,x:l,y:c,ox:p=0,oy:h=0})=>{i??=O("parent"),ee(d=>{d.fillStyle=a,d.font=`${e}px sans-serif`,d.textBaseline="middle",d.textAlign=n,d.fillText(r.toString(),(i?.x??l)+p,(i?.y??c)+h)})};function ht(r){switch(r){case"use":{y.current.use();break}case"unuse":{y.current.unuse();break}}}Reflect.set(globalThis,"Kayla",Se);var ct;(n=>(n.Flex=({align:i="stretch",children:a,direction:l="row",gap:c=0,justify:p="start",wrap:h="nowrap",getHeight:d,getWidth:m,getCenterX:x,getCenterY:v,color:S})=>{let R=Ee(),f=O(),t=z(()=>({recalc(){let s=Number(c)||0,o=x(),u=v(),b=m(),g=d();f.x=o,f.y=u,f.width=b,f.height=g;let K=R.getChildrenEntities().filter(Boolean).map(k=>k.getRect()).filter(k=>k.getFlag("flex-ignored")!==!0),E=l==="row",C=E?f.width:f.height,$=E?f.height:f.width,te=0,N=0,me=[],ne=[];K.forEach(k=>{let re=E?k.width:k.height;te+re>C&&h==="wrap"?(me.push({height:N,items:ne}),ne=[k],te=re,N=E?k.height:k.width):(ne.push(k),te+=re+s,N=Math.max(N,E?k.height:k.width))}),me.push({height:N,items:ne});let ye=0;me.forEach((k,re)=>{let L=k.items,V=L.reduce((T,ie)=>T+(E?ie.width:ie.height),0)+s*(L.length-1),F=0;p==="center"&&(F=(C-V)/2),p==="end"&&(F=C-V),p==="space-between"&&(F=0),p==="space-around"&&(F=(C-V)/(L.length*2)),p==="space-evenly"&&(F=(C-V)/(L.length+1)),L.forEach((T,ie)=>{T.z=f.z+1;let U=E?T.width:T.height,se=E?T.height:T.width,ae=0;i==="center"&&(ae=(k.height-se)/2),i==="end"&&(ae=k.height-se),i==="stretch"&&(E?T.height=k.height:T.width=k.height),E?(T.x=F+U/2,T.y=ye+ae+se/2):(T.x=ye+ae+se/2,T.y=F+U/2),p==="space-between"&&ie<L.length-1?F+=U+s+(C-V)/(L.length-1):p==="space-around"?F+=U+s+(C-V)/L.length:p==="space-evenly"?F+=U+s+(C-V)/(L.length+1):F+=U+s}),ye+=k.height+s})}}));return ee((s,o)=>{o.preventDefault(),s.fillStyle=S,s.fillRect(f.left,f.top,f.width,f.height)}),Z(()=>{fe(()=>{t.recalc()})}),pe(n.Flex,()=>({controls:t})),a},n.GenericBox=({color:i,width:a=20,height:l=20,x:c=0,y:p=0})=>{let h=O();de(()=>{h.width=a,h.height=l,h.x=c,h.y=p}),ee((d,m)=>{m.preventDefault(),d.fillStyle=i,d.fillRect(h.left,h.top,h.width,h.height)})}))(ct||={});function kt(r,e,n,...i){if(typeof r=="string")throw new Error("Cannot use intrinsic elements.");return Q(r,{...e,key:e.key??n,children:e.children??i})}function dt(r,e,n,...i){if(typeof r=="string")throw new Error("Cannot use intrinsic elements.");return Q(r,{...e,key:e.key??n,children:e.children??i})}function St(r,e,n){return dt(r,e,n)}var Tt=Re;export{Tt as Fragment,ke as JSX,kt as jsx,St as jsxDEV,dt as jsxs};
@@ -1,4 +1,4 @@
1
- import { a as LeaGameII, b as LeaTimeout, c as LeaRendererII, d as LeaEventEmitter, V as Vector2, e as LeaTickerII, R as RectLeaEntity, f as LeaSceneII, t as tinyUID$1 } from './lea-RdPmM_ci.cjs';
1
+ import { g as LeaGameII, l as LeaTimeout, h as LeaRendererII, f as LeaEventEmitter, V as Vector2, w as Substepper, k as LeaTickerII, u as RectLeaEntity, i as LeaSceneII, a1 as tinyUID$1 } from './lea-C5CjP5X2.js';
2
2
 
3
3
  /**
4
4
  * Base props that every Kayla functional component can receive.
@@ -95,7 +95,7 @@ declare function createScene(name: string): KaylaInternals.KaylaScene;
95
95
  * const renderer = createRenderer(canvas);
96
96
  * renderer.start();
97
97
  */
98
- declare function createRenderer(canvas: HTMLCanvasElement): KaylaRenderer;
98
+ declare function createRenderer(canvas: HTMLCanvasElement, config?: ConstructorParameters<typeof KaylaInternals.KaylaRenderer>[1]): KaylaRenderer;
99
99
  /**
100
100
  * Creates a Kayla element descriptor (virtual representation of an entity/component).
101
101
  *
@@ -172,6 +172,8 @@ interface KaylaScene extends KaylaInternals.KaylaScene {
172
172
  */
173
173
  interface KaylaRenderer extends KaylaInternals.KaylaRenderer {
174
174
  }
175
+ interface KaylaSubstepper extends KaylaInternals.KaylaSubstepper {
176
+ }
175
177
  /**
176
178
  * A convenient facade for the rectangle entity associated with the current Kayla component.
177
179
  *
@@ -235,7 +237,7 @@ declare namespace KaylaInternals {
235
237
  *
236
238
  * @extends LeaGameII
237
239
  */
238
- class KaylaGame extends LeaGameII {
240
+ export class KaylaGame extends LeaGameII {
239
241
  #private;
240
242
  constructor(width: number, height: number, hz: typeof Infinity | number);
241
243
  /**
@@ -288,7 +290,7 @@ declare namespace KaylaInternals {
288
290
  *
289
291
  * @extends LeaRendererII
290
292
  */
291
- class KaylaRenderer extends LeaRendererII {
293
+ export class KaylaRenderer extends LeaRendererII {
292
294
  /**
293
295
  * The attached game instance (set via `attachTo`).
294
296
  */
@@ -311,7 +313,11 @@ declare namespace KaylaInternals {
311
313
  onPointerUp: (e: PointerEvent) => void;
312
314
  onPointerCancel: (e: PointerEvent) => void;
313
315
  onPointerMove: (e: PointerEvent) => void;
314
- constructor(canvas: HTMLCanvasElement);
316
+ isKaylaDisabled: boolean;
317
+ constructor(canvas: HTMLCanvasElement, config?: {
318
+ noAutoDraw?: boolean;
319
+ disableKaylaBehavior?: boolean;
320
+ });
315
321
  protected pointerPosUpdater(e: PointerEvent): void;
316
322
  protected onPointerAll(e: PointerEvent, action: KaylaPointerAction): void;
317
323
  static getClickType(e: PointerEvent): KaylaClickType;
@@ -325,6 +331,8 @@ declare namespace KaylaInternals {
325
331
  * @returns World-space position
326
332
  */
327
333
  pointerPosToWorldPos(mx: number, my: number): Vector2;
334
+ camToViewportPos(camX: number, camY: number): Vector2;
335
+ pointerPosToWorldPosOLD(mx: number, my: number): Vector2;
328
336
  /**
329
337
  * Returns the current pointer position in world coordinates.
330
338
  *
@@ -353,18 +361,28 @@ declare namespace KaylaInternals {
353
361
  */
354
362
  detach(): void;
355
363
  }
356
- class GlobalKayla {
364
+ const SubstepperSymbol: unique symbol;
365
+ class KaylaSubstepperClass {
366
+ #private;
367
+ constructor(val: Substepper);
368
+ [SubstepperSymbol](): Substepper;
369
+ get interval(): number;
370
+ }
371
+ export interface KaylaSubstepper extends KaylaSubstepperClass {
372
+ }
373
+ export class GlobalKayla {
357
374
  current?: KaylaFiber;
358
375
  saves: {
359
376
  current?: GlobalKayla["current"];
360
377
  }[];
361
378
  constructor();
362
- useTick(onTick: KaylaFiber["onTick"][number]): void;
379
+ useTick(onTick: KaylaFiber["onTick"][number], substepper?: KaylaSubstepper): void;
363
380
  usePaint(onPaint: KaylaFiber["onPaint"][number]): void;
364
381
  useEntity(): KaylaElementRef;
365
382
  useSelf<T>(init: () => T): T;
366
383
  useInitialization(init: KaylaFiber["onInits"][number]): void;
367
384
  useRect(type?: "self" | "parent" | "disposableSelf"): KaylaRect;
385
+ useSubstep(interval: number | "default"): KaylaSubstepper;
368
386
  useFiber(): UnsafeKaylaFiber;
369
387
  useFiberControl(): KaylaFiberControl;
370
388
  useCurrentTicker(): LeaTickerII;
@@ -397,7 +415,7 @@ declare namespace KaylaInternals {
397
415
  withFiber: (fiber: KaylaFiber | null, level: "debug" | "info" | "warn" | "error", msg: string, ...extra: any[]) => void;
398
416
  };
399
417
  }
400
- class KaylaEvent {
418
+ export class KaylaEvent {
401
419
  #private;
402
420
  preventDefault(): void;
403
421
  isPrevented(): boolean;
@@ -417,7 +435,7 @@ declare namespace KaylaInternals {
417
435
  * @see {@link useState}
418
436
  * @see {@link useSelf} – recommended for most game loop data
419
437
  */
420
- class KaylaInternalState<T> {
438
+ export class KaylaInternalState<T> {
421
439
  #private;
422
440
  alwaysRecall: boolean;
423
441
  constructor(current: KaylaFiber<any>, initialValue?: T, { alwaysRecall }?: {
@@ -496,7 +514,7 @@ declare namespace KaylaInternals {
496
514
  *
497
515
  * @template T - Type of the referenced value
498
516
  */
499
- interface KaylaInternalRefIm<T> {
517
+ export interface KaylaInternalRefIm<T> {
500
518
  /**
501
519
  * The mutable value held by the ref.
502
520
  *
@@ -511,15 +529,15 @@ declare namespace KaylaInternals {
511
529
  get current(): T;
512
530
  set current(s: T);
513
531
  }
514
- class KaylaInternalRef<T> implements KaylaInternalRefIm<T> {
532
+ export class KaylaInternalRef<T> implements KaylaInternalRefIm<T> {
515
533
  #private;
516
534
  constructor(initialValue?: T);
517
535
  protected setSetter(setter: Reassignable<T>["reassignSelf"]): void;
518
536
  get current(): T;
519
537
  set current(s: T);
520
538
  }
521
- function createReassignableRef<T>(initial: T): KaylaRef<T>;
522
- interface KaylaFiberControlIm {
539
+ export function createReassignableRef<T>(initial: T): KaylaRef<T>;
540
+ export interface KaylaFiberControlIm {
523
541
  toString(): string;
524
542
  /**
525
543
  * Current number of direct child fibers (readonly).
@@ -579,7 +597,7 @@ declare namespace KaylaInternals {
579
597
  /**
580
598
  * @private
581
599
  */
582
- class KaylaFiber<Props extends FCProps = {}, Exports extends FCExports = FCExports> implements KaylaFiberControlIm {
600
+ export class KaylaFiber<Props extends FCProps = {}, Exports extends FCExports = FCExports> implements KaylaFiberControlIm {
583
601
  state: KaylaState<any>[];
584
602
  refs: KaylaRef<unknown>[];
585
603
  global: GlobalKayla;
@@ -623,6 +641,7 @@ declare namespace KaylaInternals {
623
641
  onEffectDeps?: KaylaState<any>[] | undefined;
624
642
  onPaint: Array<(ctx: CanvasRenderingContext2D, event: KaylaEvent) => void>;
625
643
  onTick: Array<(deltaS: number, event: KaylaEvent) => void>;
644
+ onTickSubsteps: Array<KaylaSubstepper | null>;
626
645
  fc?: FC<any>;
627
646
  useStateCallIndex: number;
628
647
  useEffectCallIndex: number;
@@ -670,7 +689,7 @@ declare namespace KaylaInternals {
670
689
  * @extends LEA.RectLeaEntity
671
690
  * @internal
672
691
  */
673
- class KaylaRectEntity extends RectLeaEntity {
692
+ export class KaylaRectEntity extends RectLeaEntity {
674
693
  #private;
675
694
  flags: Map<string, unknown>;
676
695
  getRawRect(): KaylaRect.RawKaylaRect;
@@ -710,7 +729,7 @@ declare namespace KaylaInternals {
710
729
  * rect.y += 5;
711
730
  * ```
712
731
  */
713
- class KaylaInternalRect {
732
+ export class KaylaInternalRect {
714
733
  #private;
715
734
  constructor(fiber: KaylaFiber<any, any>);
716
735
  /**
@@ -854,7 +873,7 @@ declare namespace KaylaInternals {
854
873
  */
855
874
  get toWorld(): (localVec: Vector2) => Vector2;
856
875
  }
857
- class KaylaScene {
876
+ export class KaylaScene {
858
877
  #private;
859
878
  constructor(scene: LeaSceneII);
860
879
  getLayers(): Map<string, KaylaLayerInfo>;
@@ -910,7 +929,8 @@ declare namespace KaylaInternals {
910
929
  detach(): void;
911
930
  private tickHandler;
912
931
  }
913
- const singleGlobalInstance: GlobalKayla;
932
+ export const singleGlobalInstance: GlobalKayla;
933
+ export { };
914
934
  }
915
935
  declare namespace KaylaContext {
916
936
  interface ProviderProps<Context> extends FCProps {
@@ -1277,7 +1297,7 @@ declare const useRect: (type?: "self" | "parent" | "disposableSelf") => KaylaRec
1277
1297
  * }
1278
1298
  * });
1279
1299
  */
1280
- declare const useTick: (onTick: KaylaInternals.KaylaFiber["onTick"][number]) => void;
1300
+ declare const useTick: (onTick: KaylaInternals.KaylaFiber["onTick"][number], substepper?: KaylaInternals.KaylaSubstepper) => void;
1281
1301
  /**
1282
1302
  * Registers a function that runs on **every render frame** (paint phase).
1283
1303
  *
@@ -1549,6 +1569,7 @@ declare const useCurrentTicker: () => LeaTickerII;
1549
1569
  * @see {@link createContext} — to create the context object
1550
1570
  */
1551
1571
  declare const useContext: <T>(context: KaylaContext<T>) => T;
1572
+ declare const useSubstep: (interval: number | "default") => KaylaInternals.KaylaSubstepper;
1552
1573
  /**
1553
1574
  * Special symbol used with `useRef` to get a stable reference to the current entity's underlying LEA `KaylaRectEntity`.
1554
1575
  *
@@ -1875,6 +1896,18 @@ declare const Text: FC<{
1875
1896
  ox?: number;
1876
1897
  oy?: number;
1877
1898
  }>;
1899
+ /**
1900
+ * This function is **NOT** a joke.
1901
+ *
1902
+ * "use" will execute the fiber's use mechanism (useEffect, useInitialization, etc) without triggering a full rerender.
1903
+ *
1904
+ * "unuse" will temporarily force a fiber to get removed as if it didn't exist next render.
1905
+ *
1906
+ * This hook MUST be called at the top level of a component function — never inside loops, conditions, nested functions, or callbacks.**
1907
+ * The call order of all hooks is **strictly fixed** across every refresh; reordering calls will corrupt internal state.
1908
+ *
1909
+ */
1910
+ declare function useUsing(type: "use" | "unuse"): void;
1878
1911
 
1879
1912
  type Kayla_ExportsOfFC<T extends FC<any, any>> = ExportsOfFC<T>;
1880
1913
  type Kayla_FC<Props extends FCProps = FCProps, Exports extends FCExports = FCExports> = FC<Props, Exports>;
@@ -1905,6 +1938,7 @@ type Kayla_KaylaRef<T> = KaylaRef<T>;
1905
1938
  type Kayla_KaylaRenderer = KaylaRenderer;
1906
1939
  type Kayla_KaylaScene = KaylaScene;
1907
1940
  type Kayla_KaylaState<T> = KaylaState<T>;
1941
+ type Kayla_KaylaSubstepper = KaylaSubstepper;
1908
1942
  declare const Kayla_Layer: typeof Layer;
1909
1943
  type Kayla_PropOfFC<T extends FC<any, any>> = PropOfFC<T>;
1910
1944
  type Kayla_Reassignable<T extends Record<any, any>> = Reassignable<T>;
@@ -1944,10 +1978,12 @@ declare const Kayla_useRef: typeof useRef;
1944
1978
  declare const Kayla_useSelf: typeof useSelf;
1945
1979
  declare const Kayla_useShouldRefresh: typeof useShouldRefresh;
1946
1980
  declare const Kayla_useState: typeof useState;
1981
+ declare const Kayla_useSubstep: typeof useSubstep;
1947
1982
  declare const Kayla_useTick: typeof useTick;
1983
+ declare const Kayla_useUsing: typeof useUsing;
1948
1984
  declare const Kayla_useViewportEffect: typeof useViewportEffect;
1949
1985
  declare namespace Kayla {
1950
- export { type Kayla_ExportsOfFC as ExportsOfFC, type Kayla_FC as FC, type Kayla_FCExports as FCExports, type Kayla_FCProps as FCProps, Kayla_JSX as JSX, Kayla_KMatrix2D as KMatrix2D, type Kayla_KaylaClickConfig as KaylaClickConfig, type Kayla_KaylaClickType as KaylaClickType, Kayla_KaylaContext as KaylaContext, type Kayla_KaylaCustomHookConfig as KaylaCustomHookConfig, Kayla_KaylaElement as KaylaElement, type Kayla_KaylaElementRef as KaylaElementRef, type Kayla_KaylaExportables as KaylaExportables, type Kayla_KaylaExports as KaylaExports, type Kayla_KaylaFiberControl as KaylaFiberControl, Kayla_KaylaFragment as KaylaFragment, type Kayla_KaylaGame as KaylaGame, Kayla_KaylaInternals as KaylaInternals, type Kayla_KaylaLayerInfo as KaylaLayerInfo, type Kayla_KaylaLayerProps as KaylaLayerProps, type Kayla_KaylaPointerAction as KaylaPointerAction, Kayla_KaylaRect as KaylaRect, type Kayla_KaylaRef as KaylaRef, type Kayla_KaylaRenderer as KaylaRenderer, type Kayla_KaylaScene as KaylaScene, type Kayla_KaylaState as KaylaState, Kayla_Layer as Layer, type Kayla_PropOfFC as PropOfFC, type Kayla_Reassignable as Reassignable, Kayla_Rect as Rect, Kayla_Text as Text, type Kayla_UnsafeKaylaFiber as UnsafeKaylaFiber, Kayla_createContext as createContext, Kayla_createElement as createElement, Kayla_createGame as createGame, Kayla_createReassignableObject as createReassignableObject, Kayla_createRenderer as createRenderer, Kayla_createScene as createScene, Kayla_createUseHook as createUseHook, Kayla_safeValueRepresentation as safeValueRepresentation, selfSym as self, Kayla_setLogLevel as setLogLevel, Kayla_tinyUID as tinyUID, Kayla_useClick as useClick, Kayla_useContext as useContext, Kayla_useCurrentGame as useCurrentGame, Kayla_useCurrentRenderer as useCurrentRenderer, Kayla_useCurrentScene as useCurrentScene, Kayla_useCurrentTicker as useCurrentTicker, Kayla_useDisposableRef as useDisposableRef, Kayla_useEffect as useEffect, Kayla_useEntity as useEntity, Kayla_useExports as useExports, Kayla_useFiber as useFiber, Kayla_useFiberControl as useFiberControl, Kayla_useGlobalClick as useGlobalClick, Kayla_useGlobalPointer as useGlobalPointer, Kayla_useInitialization as useInitialization, Kayla_useNextStack as useNextStack, Kayla_usePaint as usePaint, Kayla_usePointer as usePointer, Kayla_useRect as useRect, Kayla_useRef as useRef, Kayla_useSelf as useSelf, Kayla_useShouldRefresh as useShouldRefresh, Kayla_useState as useState, Kayla_useTick as useTick, Kayla_useViewportEffect as useViewportEffect };
1986
+ export { type Kayla_ExportsOfFC as ExportsOfFC, type Kayla_FC as FC, type Kayla_FCExports as FCExports, type Kayla_FCProps as FCProps, Kayla_JSX as JSX, Kayla_KMatrix2D as KMatrix2D, type Kayla_KaylaClickConfig as KaylaClickConfig, type Kayla_KaylaClickType as KaylaClickType, Kayla_KaylaContext as KaylaContext, type Kayla_KaylaCustomHookConfig as KaylaCustomHookConfig, Kayla_KaylaElement as KaylaElement, type Kayla_KaylaElementRef as KaylaElementRef, type Kayla_KaylaExportables as KaylaExportables, type Kayla_KaylaExports as KaylaExports, type Kayla_KaylaFiberControl as KaylaFiberControl, Kayla_KaylaFragment as KaylaFragment, type Kayla_KaylaGame as KaylaGame, Kayla_KaylaInternals as KaylaInternals, type Kayla_KaylaLayerInfo as KaylaLayerInfo, type Kayla_KaylaLayerProps as KaylaLayerProps, type Kayla_KaylaPointerAction as KaylaPointerAction, Kayla_KaylaRect as KaylaRect, type Kayla_KaylaRef as KaylaRef, type Kayla_KaylaRenderer as KaylaRenderer, type Kayla_KaylaScene as KaylaScene, type Kayla_KaylaState as KaylaState, type Kayla_KaylaSubstepper as KaylaSubstepper, Kayla_Layer as Layer, type Kayla_PropOfFC as PropOfFC, type Kayla_Reassignable as Reassignable, Kayla_Rect as Rect, Kayla_Text as Text, type Kayla_UnsafeKaylaFiber as UnsafeKaylaFiber, Kayla_createContext as createContext, Kayla_createElement as createElement, Kayla_createGame as createGame, Kayla_createReassignableObject as createReassignableObject, Kayla_createRenderer as createRenderer, Kayla_createScene as createScene, Kayla_createUseHook as createUseHook, Kayla_safeValueRepresentation as safeValueRepresentation, selfSym as self, Kayla_setLogLevel as setLogLevel, Kayla_tinyUID as tinyUID, Kayla_useClick as useClick, Kayla_useContext as useContext, Kayla_useCurrentGame as useCurrentGame, Kayla_useCurrentRenderer as useCurrentRenderer, Kayla_useCurrentScene as useCurrentScene, Kayla_useCurrentTicker as useCurrentTicker, Kayla_useDisposableRef as useDisposableRef, Kayla_useEffect as useEffect, Kayla_useEntity as useEntity, Kayla_useExports as useExports, Kayla_useFiber as useFiber, Kayla_useFiberControl as useFiberControl, Kayla_useGlobalClick as useGlobalClick, Kayla_useGlobalPointer as useGlobalPointer, Kayla_useInitialization as useInitialization, Kayla_useNextStack as useNextStack, Kayla_usePaint as usePaint, Kayla_usePointer as usePointer, Kayla_useRect as useRect, Kayla_useRef as useRef, Kayla_useSelf as useSelf, Kayla_useShouldRefresh as useShouldRefresh, Kayla_useState as useState, Kayla_useSubstep as useSubstep, Kayla_useTick as useTick, Kayla_useUsing as useUsing, Kayla_useViewportEffect as useViewportEffect };
1951
1987
  }
1952
1988
 
1953
- export { useExports as $, createGame as A, createReassignableObject as B, createRenderer as C, createScene as D, type ExportsOfFC as E, type FCProps as F, createUseHook as G, safeValueRepresentation as H, selfSym as I, JSX as J, Kayla as K, Layer as L, setLogLevel as M, tinyUID as N, useClick as O, type PropOfFC as P, useContext as Q, type Reassignable as R, useCurrentGame as S, Text as T, type UnsafeKaylaFiber as U, useCurrentRenderer as V, useCurrentScene as W, useCurrentTicker as X, useDisposableRef as Y, useEffect as Z, useEntity as _, type FCExports as a, useFiber as a0, useFiberControl as a1, useGlobalClick as a2, useGlobalPointer as a3, useInitialization as a4, useNextStack as a5, usePaint as a6, usePointer as a7, useRect as a8, useRef as a9, useSelf as aa, useShouldRefresh as ab, useState as ac, useTick as ad, useViewportEffect as ae, type FC as b, KMatrix2D as c, type KaylaClickConfig as d, type KaylaClickType as e, KaylaContext as f, type KaylaCustomHookConfig as g, KaylaElement as h, type KaylaElementRef as i, type KaylaExportables as j, type KaylaExports as k, type KaylaFiberControl as l, KaylaFragment as m, KaylaGame as n, KaylaInternals as o, type KaylaLayerInfo as p, type KaylaLayerProps as q, type KaylaPointerAction as r, KaylaRect as s, type KaylaRef as t, KaylaRenderer as u, KaylaScene as v, type KaylaState as w, Rect as x, createContext as y, createElement as z };
1989
+ export { useEntity as $, createElement as A, createGame as B, createReassignableObject as C, createRenderer as D, type ExportsOfFC as E, type FC as F, createScene as G, createUseHook as H, safeValueRepresentation as I, JSX as J, Kayla as K, Layer as L, selfSym as M, setLogLevel as N, tinyUID as O, type PropOfFC as P, useClick as Q, type Reassignable as R, useContext as S, Text as T, type UnsafeKaylaFiber as U, useCurrentGame as V, useCurrentRenderer as W, useCurrentScene as X, useCurrentTicker as Y, useDisposableRef as Z, useEffect as _, type FCExports as a, useExports as a0, useFiber as a1, useFiberControl as a2, useGlobalClick as a3, useGlobalPointer as a4, useInitialization as a5, useNextStack as a6, usePaint as a7, usePointer as a8, useRect as a9, useRef as aa, useSelf as ab, useShouldRefresh as ac, useState as ad, useSubstep as ae, useTick as af, useUsing as ag, useViewportEffect as ah, type FCProps as b, KMatrix2D as c, type KaylaClickConfig as d, type KaylaClickType as e, KaylaContext as f, type KaylaCustomHookConfig as g, KaylaElement as h, type KaylaElementRef as i, type KaylaExportables as j, type KaylaExports as k, type KaylaFiberControl as l, KaylaFragment as m, KaylaGame as n, KaylaInternals as o, type KaylaLayerInfo as p, type KaylaLayerProps as q, type KaylaPointerAction as r, KaylaRect as s, type KaylaRef as t, KaylaRenderer as u, KaylaScene as v, type KaylaState as w, type KaylaSubstepper as x, Rect as y, createContext as z };