hayao 0.3.0 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +10 -0
- package/bin/create-hayao.mjs +1 -1
- package/dist/anim/blend.d.ts +68 -0
- package/dist/anim/clip.d.ts +87 -0
- package/dist/anim/ik.d.ts +40 -0
- package/dist/anim/skeleton.d.ts +64 -0
- package/dist/app/browser.d.ts +33 -3
- package/dist/app/game.d.ts +15 -11
- package/dist/audio/audio.d.ts +18 -1
- package/dist/audio/synth.d.ts +7 -0
- package/dist/audio/zzfx.d.ts +14 -0
- package/dist/core/clock.d.ts +1 -1
- package/dist/core/projection.d.ts +36 -0
- package/dist/core/rng.d.ts +9 -0
- package/dist/hayao.global.js +190 -5
- package/dist/index.d.ts +20 -1
- package/dist/index.js +4159 -979
- package/dist/index.js.map +4 -4
- package/dist/index.min.js +190 -5
- package/dist/input/actions.d.ts +60 -6
- package/dist/input/gamepad.d.ts +101 -0
- package/dist/input/source.d.ts +85 -4
- package/dist/logic/coroutine.d.ts +68 -0
- package/dist/render/canvas.d.ts +3 -7
- package/dist/render/canvas2d-core.d.ts +13 -0
- package/dist/render/commands.d.ts +55 -2
- package/dist/render/lightRun.d.ts +35 -0
- package/dist/render/paint.d.ts +8 -0
- package/dist/render/renderer.d.ts +25 -0
- package/dist/render/svg.d.ts +2 -1
- package/dist/render/svgString.d.ts +8 -3
- package/dist/render/webgl.d.ts +176 -0
- package/dist/scene/clipPlayer.d.ts +58 -0
- package/dist/scene/ikTarget.d.ts +25 -0
- package/dist/scene/iso.d.ts +73 -0
- package/dist/scene/light.d.ts +80 -0
- package/dist/scene/node.d.ts +81 -2
- package/dist/scene/nodes.d.ts +34 -0
- package/dist/scene/particles.d.ts +19 -0
- package/dist/scene/shadow2d.d.ts +25 -0
- package/dist/scene/skeletonDebug.d.ts +28 -0
- package/dist/scene/verletChain.d.ts +76 -0
- package/dist/ui/touch.d.ts +51 -0
- package/dist/verify/dom.d.ts +26 -0
- package/dist/verify/gates.d.ts +25 -0
- package/dist/world.d.ts +72 -7
- package/docs/API.md +138 -27
- package/docs/CONVENTIONS.md +346 -2
- package/docs/EMBED.md +5 -0
- package/docs/QUICKSTART.md +13 -1
- package/docs/VERIFICATION.md +34 -4
- package/package.json +2 -1
package/dist/hayao.global.js
CHANGED
|
@@ -1,8 +1,180 @@
|
|
|
1
|
-
"use strict";var hayao=(()=>{var Tn=Object.defineProperty;var as=Object.getOwnPropertyDescriptor;var ls=Object.getOwnPropertyNames;var us=Object.prototype.hasOwnProperty;var cs=(t,e)=>{for(var n in e)Tn(t,n,{get:e[n],enumerable:!0})},ms=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of ls(e))!us.call(t,o)&&o!==n&&Tn(t,o,{get:()=>e[o],enumerable:!(r=as(e,o))||r.enumerable});return t};var ds=t=>ms(Tn({},"__esModule",{value:!0}),t);var am={};cs(am,{ALBUM:()=>Si,AMBIENT_PRESETS:()=>Ys,AmbientField:()=>Wn,AnimationPlayer:()=>St,AudioBus:()=>un,BitmapText:()=>nr,BroadcastChannelTransport:()=>eo,Camera2D:()=>wt,CameraController:()=>Fn,Canvas2DRenderer:()=>He,CinematicPlayer:()=>Ir,Clock:()=>bt,DEFAULT_INPUT_MAP:()=>tn,DEFAULT_PLATFORMER:()=>nt,DEFAULT_SESSION_CONFIG:()=>Ye,DEFAULT_TILE_CHARS:()=>qn,DUSK:()=>Eo,EASINGS:()=>Ln,Edge:()=>ee,EventBus:()=>gt,FLOAT_PRESETS:()=>Xs,FONT_5:()=>tr,FloatingText:()=>On,Fsm:()=>zr,GENRES:()=>ki,GENRE_PROFILES:()=>lu,HeadlessRenderer:()=>Qn,IDENTITY:()=>le,INSTRUMENTS:()=>A,InputBuffer:()=>Xe,InputRecorder:()=>Gn,InputState:()=>Mt,KENTO:()=>L,KeyboardSource:()=>Ge,LocalStorageAdapter:()=>xn,LockstepSession:()=>De,LoopbackHub:()=>Zr,LoopbackTransport:()=>Sn,LootTable:()=>Br,MEADOW:()=>Io,MemoryStorage:()=>yn,NEIGHBORS_4:()=>jt,NEIGHBORS_8:()=>gn,NET_PROTOCOL_VERSION:()=>ff,Node:()=>q,Node2D:()=>q,NodePool:()=>$n,NullStorage:()=>_r,PAD_NEUTRAL:()=>na,PALETTES:()=>Ua,PANEL_PRESETS:()=>Ja,PAPER:()=>Fo,PARTICLE_PRESETS:()=>Ks,ParallaxLayer:()=>Nn,Particles:()=>zn,PhaseClock:()=>Wr,PixelBuffer:()=>ot,PlayerInput:()=>kn,PointerSource:()=>Ct,RingBuffer:()=>Hr,Rng:()=>ue,RollbackSession:()=>Jt,RoomHost:()=>Mn,SAMPLE_RATE:()=>be,SAVE_FORMAT_VERSION:()=>Xr,SCALES:()=>hr,SaveManager:()=>Yr,ScreenTransition:()=>bn,SessionRecorder:()=>Qe,Shaker:()=>Bn,Shell:()=>Wt,Signal:()=>et,SnapshotRing:()=>pt,SpatialHash:()=>Rt,Sprite:()=>xt,SvgRenderer:()=>je,TAU:()=>ie,TILE:()=>j,Text:()=>vt,TextureSprite:()=>er,Timer:()=>kt,UndoStack:()=>jr,VERSION:()=>sm,WangFrame:()=>_e,World:()=>Vt,abilitiesOf:()=>es,addBody:()=>fa,addDistanceJoint:()=>wa,addRevoluteJoint:()=>ka,addTransition:()=>Eu,albumTrack:()=>Tu,analyzePlaytest:()=>xc,applyImpulse:()=>ga,applyReverb:()=>yr,applyTransform:()=>Qt,asciiEntities:()=>Qs,assertAudio:()=>mc,assertDeterministic:()=>Au,assertRamp:()=>ic,assertSnapshotStable:()=>Lu,assertSolvable:()=>$u,astar:()=>_i,astarGrid:()=>Tc,audio:()=>Le,autotile4:()=>fl,autotileToCommands:()=>gl,availableUpgrades:()=>Ac,bandBalance:()=>Sr,bfs:()=>Hi,blobPath:()=>rl,bodyAABB:()=>nn,bodyContains:()=>Ro,cadenceResolves:()=>eu,cameraIssues:()=>Ni,canvasGradient:()=>Yn,cellFloat:()=>Je,cellHash:()=>Xo,cellInt:()=>vl,changeFrames:()=>ec,checkDeterministic:()=>Pi,chordChanges:()=>Xl,chordNotes:()=>Se,clamp:()=>U,clientToDesign:()=>Dt,collide:()=>Hn,commandsToSVGInner:()=>qe,composeCampaign:()=>Hc,composeTransform:()=>Ze,connectWebSocket:()=>Qc,connectedComponents:()=>Cc,contourToCommands:()=>yl,contrastRatio:()=>mt,createPlanBot:()=>Vu,createPlatformerState:()=>ra,createRigidWorld:()=>da,createStereo:()=>ur,createWorld:()=>Me,crestFactorDb:()=>kr,dashJumpDistance:()=>aa,datan:()=>so,datan2:()=>Ps,dbfs:()=>cn,dcos:()=>X,decode2bit:()=>sl,decodeBits:()=>il,decodeMessage:()=>$e,decodeRLE:()=>al,defaultStorage:()=>Jr,defineGame:()=>pc,defineLevel:()=>Wc,deg2rad:()=>Gs,deserializeNode:()=>en,dexp:()=>Be,dexp2:()=>he,dhypot:()=>Q,diatonicChord:()=>ai,diffLevels:()=>Vc,distanceGain:()=>yi,dlog:()=>Rn,dlog10:()=>ht,dlog2:()=>Xt,dpow:()=>Re,drive:()=>Gu,dropShadow:()=>Oa,dsin:()=>_,duckGain:()=>au,encodeMessage:()=>de,encodeRLE:()=>ll,encodeWav:()=>Il,estimateTempo:()=>fi,evalCurve:()=>ou,featureDistance:()=>gi,features:()=>ct,feedbackIssues:()=>Ei,fft:()=>di,findSoftlocks:()=>Uc,firstFrame:()=>Qu,floodFill:()=>qr,fluxEnvelope:()=>wr,forgivenessIssues:()=>Ii,fractalNoise:()=>ir,frameActions:()=>tt,gameInputMap:()=>hc,generateCave:()=>kl,generateDungeon:()=>Rl,generateLevels:()=>Qr,generateLevelsReport:()=>Qi,genre:()=>bu,getBody:()=>ge,getJoint:()=>Sa,glow:()=>Ba,graceWindowIssues:()=>ju,gradient:()=>el,gradientDef:()=>Jn,gridAt:()=>Ko,gridFromRows:()=>ml,gridSet:()=>Fe,gridToTilemap:()=>xl,groundAt:()=>bo,hashString:()=>In,hashValue:()=>yt,hexToHsl:()=>Ao,hideScreen:()=>zt,hold:()=>zu,hostRoom:()=>no,hsl:()=>$o,hsv:()=>Xa,inVisionCone:()=>ma,initDirector:()=>Nc,inputDensity:()=>nc,installCapture:()=>Nr,invLerp:()=>Pn,invertTransform:()=>Zt,isCaptureMode:()=>Fr,isGround:()=>Ml,isMonotonic:()=>tc,joinRoom:()=>to,jumpAirtime:()=>go,jumpDistance:()=>yo,jumpHeight:()=>sa,keyMentions:()=>Oi,keysToActions:()=>Vn,knob:()=>dc,layerGains:()=>su,layoutIssues:()=>Ku,layoutText:()=>qo,lerp:()=>Ie,lerpDamp:()=>Js,levelFromSeed:()=>jc,levelIssues:()=>Bc,levelReachable:()=>Oc,levelToTilemap:()=>vn,lineOfSight:()=>vo,linearGradient:()=>za,lintSong:()=>Zl,longestLull:()=>rc,lookAheadIssues:()=>$i,magnitudeSpectrum:()=>ut,makeGrid:()=>st,makeReach:()=>Us,makeTransform:()=>ft,mapHeight:()=>ta,mapWidth:()=>ea,marchingSquaresCases:()=>Jo,marchingSquaresContours:()=>Uo,mask4:()=>rr,mask8:()=>dl,matchReport:()=>ru,measureLine:()=>it,measureText:()=>cl,mergePlayerFrames:()=>dt,midiToFreq:()=>si,midiToName:()=>Ll,missingControlHints:()=>Yu,mix:()=>Ka,mixLinear:()=>Lo,mixMono:()=>cr,moveRect:()=>Tt,mutateColor:()=>Qa,netMessage:()=>pe,nineSlice:()=>_a,normalize:()=>dr,noteToMidi:()=>ce,onsetDensity:()=>hi,openVoicing:()=>an,packVarints:()=>Ec,panFromOffset:()=>xi,panGains:()=>ni,parseRich:()=>Oo,parseSnapshot:()=>Kr,passableFromTilemap:()=>Rc,peak:()=>ri,peakAmp:()=>vr,pickEntry:()=>Gr,pitchToFreq:()=>pr,pixelsToCommands:()=>Bo,platformerReachable:()=>Gc,playerAction:()=>_t,playerIds:()=>Yc,playerInput:()=>Xc,pointQuery:()=>$a,pollDirector:()=>$c,polygonBox:()=>ya,progression:()=>Ue,progressionPuzzle:()=>wn,proveCompletable:()=>_c,proveFullCompletion:()=>Jc,pump:()=>Ou,rad2deg:()=>Vs,radialGradient:()=>Wa,rampIssues:()=>Vi,rampStats:()=>Gi,rayCastRigid:()=>La,raycastTiles:()=>xo,reachableRegions:()=>rs,reconstructPath:()=>kc,recordTimeline:()=>Xu,rectBlocked:()=>Ae,rectContains:()=>qs,rectsOverlap:()=>js,registerNode:()=>Oe,regularPolygon:()=>tl,relLuminance:()=>Bt,remap:()=>Os,removeBody:()=>ba,removeJoint:()=>Ma,renderAudioFilmstrip:()=>ac,renderFilmstrip:()=>sc,renderSong:()=>xr,renderSound:()=>Nt,renderToSVGString:()=>It,replay:()=>Er,replaySession:()=>Lr,resetNodeIds:()=>En,resolveTuning:()=>qt,rigidStep:()=>Ea,rleDecode:()=>Ic,rleEncode:()=>Dc,rms:()=>lt,roomCenter:()=>ar,rootless:()=>$t,runBrowser:()=>ro,runBrowserNet:()=>em,runFeelGates:()=>Ju,runHeadless:()=>fc,runStudio:()=>im,salienceIssues:()=>Fi,sampleGradient:()=>Zn,scaleMidis:()=>sn,scalePitchClasses:()=>fr,scatter:()=>Qo,scatterCells:()=>wl,scoreTrack:()=>uu,screenRect:()=>Nu,scriptToFrames:()=>Di,scriptedPlaythrough:()=>Bu,scrubTo:()=>Cn,serializeSnapshot:()=>Ki,series:()=>Zu,setOverlayHost:()=>Lt,setScreenObserver:()=>fn,settings:()=>Ne,shadowDef:()=>Un,shapeBBox:()=>Kn,shapeBox:()=>$r,showScreen:()=>Rr,signalHash:()=>El,smoothClosedPath:()=>zo,smoothOpenPath:()=>ol,smoothstep:()=>Dn,softClip:()=>lr,softClipInPlace:()=>mr,solidNeighbours:()=>or,solve:()=>Ke,solveJoint:()=>_n,songBeats:()=>ci,songDuration:()=>ln,sortCommands:()=>Pt,spatialMix:()=>iu,spectralCentroid:()=>pi,spring:()=>mo,springStep:()=>po,star:()=>nl,steer2D:()=>qu,stepPlatformer:()=>ia,stereoDuration:()=>Dl,stereoFrames:()=>Pl,stereoWidth:()=>vi,subSeed:()=>Xi,telegraphIssues:()=>_u,terrainHeight:()=>sr,terrainSlice:()=>Sl,textBox:()=>Wi,textToCommands:()=>Ho,tileAt:()=>fe,tileAtPoint:()=>Zs,tileCenter:()=>Yi,tilemapFromAscii:()=>jn,toggleFullscreen:()=>Dr,transpose:()=>Wl,typewriterCount:()=>jo,unpackVarints:()=>Fc,vadd:()=>$s,validateWorld:()=>Kc,valueNoise:()=>Zo,vdist:()=>Ws,vdot:()=>zs,vec2:()=>Ns,vlen:()=>lo,vnorm:()=>Bs,voiceLead:()=>at,vscale:()=>Ls,vsub:()=>As,wait:()=>Wu,wakeBody:()=>ye,wangTile:()=>_o,weatherEnvelope:()=>ho,weightedIndex:()=>Or,weightedPick:()=>wc,wipeStep:()=>Fu,withAlpha:()=>Ya,worldPoints:()=>we,zcr:()=>mi});var ps=.6366197723675814,hs=1.5707963267341256,fs=6077100506506192e-26,bs=-.16666666666666632,gs=.00833333333332249,ys=-.0001984126982985795,xs=27557313707070068e-22,vs=-25050760253406863e-24,ws=158969099521155e-24,ks=.0416666666666666,Ss=-.001388888888887411,Ms=2480158728947673e-20,Cs=-27557314351390663e-23,Ts=2087572321298175e-24,Rs=-11359647557788195e-27;function Kt(t){let e=t*t;return t+t*e*(bs+e*(gs+e*(ys+e*(xs+e*(vs+e*ws)))))}function Yt(t){let e=t*t;return 1-.5*e+e*e*(ks+e*(Ss+e*(Ms+e*(Cs+e*(Ts+e*Rs)))))}function io(t){let e=Math.round(t*ps),n=t-e*hs-e*fs;return{n:(e%4+4)%4,r:n}}function _(t){if(!Number.isFinite(t))return NaN;let{n:e,r:n}=io(t);switch(e){case 0:return Kt(n);case 1:return Yt(n);case 2:return-Kt(n);default:return-Yt(n)}}function X(t){if(!Number.isFinite(t))return NaN;let{n:e,r:n}=io(t);switch(e){case 0:return Yt(n);case 1:return-Kt(n);case 2:return-Yt(n);default:return Kt(n)}}var Ut=[.4636476090008061,.7853981633974483,.982793723247329,1.5707963267948966],oo=[22698777452961687e-33,3061616997868383e-32,13903311031230998e-33,6123233995736766e-32],ve=[.3333333333333293,-.19999999999876483,.14285714272503466,-.11111110405462356,.09090887133436507,-.0769187620504483,.06661073137387531,-.058335701337905735,.049768779946159324,-.036531572744216916,.016285820115365782];function so(t){if(Number.isNaN(t))return NaN;if(!Number.isFinite(t))return t>0?Ut[3]:-Ut[3];let e=t<0||Object.is(t,-0)?-1:1,n=Math.abs(t);if(n>=1e19)return e*(Ut[3]+oo[3]);let r=-1;if(n<.4375){if(n<1e-9)return t}else n<.6875?(r=0,n=(2*n-1)/(2+n)):n<1.1875?(r=1,n=(n-1)/(n+1)):n<2.4375?(r=2,n=(n-1.5)/(1+1.5*n)):(r=3,n=-1/n);let o=n*n,i=o*o,s=o*(ve[0]+i*(ve[2]+i*(ve[4]+i*(ve[6]+i*(ve[8]+i*ve[10]))))),a=i*(ve[1]+i*(ve[3]+i*(ve[5]+i*(ve[7]+i*ve[9]))));if(r<0)return e*(n-n*(s+a));let l=Ut[r]-(n*(s+a)-oo[r]-n);return e*l}var Te=3.141592653589793;function Ps(t,e){if(Number.isNaN(e)||Number.isNaN(t))return NaN;if(t===0&&e===0)return Object.is(e,-0)?Object.is(t,-0)?-Te:Te:Object.is(t,-0)?-0:0;if(e===0||!Number.isFinite(t)&&Number.isFinite(e))return t>0?Te/2:-Te/2;if(!Number.isFinite(e)){if(!Number.isFinite(t)){let r=e>0?Te/4:3*Te/4;return t>0?r:-r}return e>0?t<0||Object.is(t,-0)?-0:0:t<0||Object.is(t,-0)?-Te:Te}let n=so(t/e);return e>0?n:t<0||Object.is(t,-0)?n-Te:n+Te}var Ds=.6931471805599453;function he(t){if(Number.isNaN(t))return NaN;if(t>=1024)return 1/0;if(t<=-1075)return 0;let e=Math.round(t),n=(t-e)*Ds,r=1,o=1;for(let i=1;i<=13;i++)r=r*n/i,o+=r;return o*2**e}function Be(t){return he(t*ao)}function Q(t,e){return Math.sqrt(t*t+e*e)}var We=new DataView(new ArrayBuffer(8)),Is=.6931471803691238,Es=19082149292705877e-26;function Rn(t){if(Number.isNaN(t)||t<0)return NaN;if(t===0)return-1/0;if(!Number.isFinite(t))return 1/0;We.setFloat64(0,t);let e=(We.getUint32(0)>>>20&2047)-1023;e===-1023&&(We.setFloat64(0,t*0x40000000000000),e=(We.getUint32(0)>>>20&2047)-1023-54),We.setUint32(0,We.getUint32(0)&1048575|1023<<20);let n=We.getFloat64(0);n>1.4142135623730951&&(n*=.5,e+=1);let r=(n-1)/(n+1),o=r*r,i=1+o*(.3333333333333333+o*(.2+o*(.14285714285714285+o*(.1111111111111111+o*(.09090909090909091+o*(.07692307692307693+o*(.06666666666666667+o*(.058823529411764705+o*.05263157894736842))))))));return e*Is+(2*r*i+e*Es)}var Fs=.4342944819032518,ao=1.4426950408889634,ht=t=>Rn(t)*Fs,Xt=t=>Rn(t)*ao;function Re(t,e){if(Number.isNaN(t)||Number.isNaN(e))return NaN;if(e===0)return 1;if(e===1)return t;if(Number.isInteger(e)&&Math.abs(e)<=1024){let n=Math.abs(e),r=t,o=1;for(;n>0;)n&1&&(o*=r),n>>=1,n>0&&(r*=r);return e<0?1/o:o}return t>0?he(e*Xt(t)):t===0?e>0?0:1/0:NaN}var Ns=(t=0,e=0)=>({x:t,y:e}),$s=(t,e)=>({x:t.x+e.x,y:t.y+e.y}),As=(t,e)=>({x:t.x-e.x,y:t.y-e.y}),Ls=(t,e)=>({x:t.x*e,y:t.y*e}),zs=(t,e)=>t.x*e.x+t.y*e.y,lo=t=>Q(t.x,t.y),Ws=(t,e)=>Q(t.x-e.x,t.y-e.y);function Bs(t){let e=lo(t);return e===0?{x:0,y:0}:{x:t.x/e,y:t.y/e}}var U=(t,e,n)=>t<e?e:t>n?n:t,Ie=(t,e,n)=>t+(e-t)*n,Pn=(t,e,n)=>t===e?0:(n-t)/(e-t),Os=(t,e,n,r,o)=>Ie(r,o,Pn(e,n,t)),Dn=(t,e,n)=>{let r=U(t===e?n<t?0:1:Pn(t,e,n),0,1);return r*r*(3-2*r)},ie=Math.PI*2,Gs=t=>t*Math.PI/180,Vs=t=>t*180/Math.PI;function qs(t,e){return e.x>=t.x&&e.x<=t.x+t.w&&e.y>=t.y&&e.y<=t.y+t.h}function js(t,e){return t.x<e.x+e.w&&t.x+t.w>e.x&&t.y<e.y+e.h&&t.y+t.h>e.y}var le={a:1,b:0,c:0,d:1,e:0,f:0};function Ze(t,e){return{a:t.a*e.a+t.c*e.b,b:t.b*e.a+t.d*e.b,c:t.a*e.c+t.c*e.d,d:t.b*e.c+t.d*e.d,e:t.a*e.e+t.c*e.f+t.e,f:t.b*e.e+t.d*e.f+t.f}}function ft(t,e,n){let r=X(e),o=_(e);return{a:r*n.x,b:o*n.x,c:-o*n.y,d:r*n.y,e:t.x,f:t.y}}function Qt(t,e){return{x:t.a*e.x+t.c*e.y+t.e,y:t.b*e.x+t.d*e.y+t.f}}function Zt(t){let e=t.a*t.d-t.b*t.c;if(e===0)return{...le};let n=1/e;return{a:t.d*n,b:-t.b*n,c:-t.c*n,d:t.a*n,e:(t.c*t.f-t.d*t.e)*n,f:(t.b*t.e-t.a*t.f)*n}}function Hs(t){let e=t>>>0;return()=>{e=e+2654435769>>>0;let n=e;return n=Math.imul(n^n>>>16,569420461),n=Math.imul(n^n>>>15,1935289751),(n^n>>>15)>>>0}}var ue=class t{s0;s1;s2;s3;constructor(e=0){if(typeof e=="number"){let n=Hs(e===0?305441741:e);this.s0=n(),this.s1=n(),this.s2=n(),this.s3=n()}else[this.s0,this.s1,this.s2,this.s3]=e.s}next(){let e=Math.imul(this.rotl(Math.imul(this.s1,5),7),9)>>>0,n=this.s1<<9>>>0;return this.s2^=this.s0,this.s3^=this.s1,this.s1^=this.s2,this.s0^=this.s3,this.s2=(this.s2^n)>>>0,this.s3=this.rotl(this.s3,11),e>>>0}rotl(e,n){return(e<<n|e>>>32-n)>>>0}float(){return this.next()/4294967296}range(e,n){return e+this.float()*(n-e)}int(e){return Math.floor(this.float()*e)}intRange(e,n){return e+this.int(n-e+1)}chance(e){return this.float()<e}pick(e){return e[this.int(e.length)]}shuffle(e){for(let n=e.length-1;n>0;n--){let r=this.int(n+1);[e[n],e[r]]=[e[r],e[n]]}return e}split(e=0){let n=(this.s0^Math.imul(e+1,2654435769))>>>0,r=new t(n^this.s3);return this.next(),r}getState(){return{s:[this.s0,this.s1,this.s2,this.s3]}}setState(e){[this.s0,this.s1,this.s2,this.s3]=e.s}};function In(t){let e=2166136261;for(let n=0;n<t.length;n++)e^=t.charCodeAt(n),e=Math.imul(e,16777619);return e>>>0}var bt=class{stepMs;dt;maxFrameMs;accumulator=0;_frame=0;_simTimeMs=0;constructor(e={}){let n=e.hz??60;this.stepMs=1e3/n,this.dt=1/n,this.maxFrameMs=e.maxFrameMs??250}advance(e){this.accumulator+=Math.min(e,this.maxFrameMs);let n=0;for(;this.accumulator>=this.stepMs;)this.accumulator-=this.stepMs,n++;return n}tick(){this._frame++,this._simTimeMs+=this.stepMs}get alpha(){return this.accumulator/this.stepMs}get frame(){return this._frame}get simTimeMs(){return this._simTimeMs}get simTimeSec(){return this._simTimeMs/1e3}getState(){return{accumulator:this.accumulator,frame:this._frame,simTimeMs:this._simTimeMs}}setState(e){this.accumulator=e.accumulator,this._frame=e.frame,this._simTimeMs=e.simTimeMs}};var et=class{listeners=[];connect(e){return this.listeners.push(e),()=>this.disconnect(e)}once(e){let n=this.connect(r=>{n(),e(r)});return n}disconnect(e){let n=this.listeners.indexOf(e);n>=0&&this.listeners.splice(n,1)}emit(e){for(let n of this.listeners.slice())n(e)}get count(){return this.listeners.length}clear(){this.listeners.length=0}},gt=class{signals=new Map;signalFor(e){let n=this.signals.get(e);return n||(n=new et,this.signals.set(e,n)),n}on(e,n){return this.signalFor(e).connect(n)}once(e,n){return this.signalFor(e).once(n)}emit(e,n){this.signalFor(e).emit(n)}clear(){this.signals.clear()}};function _s(t){return Number.isNaN(t)?"NaN":t===1/0?"Inf":t===-1/0?"-Inf":t===0?"0":t.toString()}function yt(t){let e=2166136261,n=2166136261,r=s=>{for(let a=0;a<s.length;a++){let l=s.charCodeAt(a);e=Math.imul(e^l,16777619)>>>0,n=Math.imul(n^(l<<3|l>>>5),2246822519)>>>0}},o=s=>{if(s===null)return r("n");if(s===void 0)return r("u");switch(typeof s){case"number":return r("#"+_s(s));case"boolean":return r(s?"t":"f");case"string":return r('"'+s);case"object":{if(Array.isArray(s)){r("[");for(let u of s)o(u);r("]");return}let a=s,l=Object.keys(a).filter(u=>a[u]!==void 0).sort();r("{");for(let u of l)r(u+":"),o(a[u]);r("}");return}default:r("?")}};o(t);let i=s=>s.toString(16).padStart(8,"0");return i(e)+i(n)}var uo=0;function En(t=0){uo=t}var q=class{id;name;type="Node";pos;rotation;scale;z;visible;cosmetic=!1;parent=null;children=[];world=null;onUpdate;behaviors=[];signals=new Map;_ready=!1;_freed=!1;constructor(e={}){this.id=`n${uo++}`,this.name=e.name??this.constructor.name,this.pos=e.pos?{...e.pos}:{x:0,y:0},this.rotation=e.rotation??0,this.scale=e.scale?{...e.scale}:{x:1,y:1},this.z=e.z??0,this.visible=e.visible??!0}addChild(e){return e.parent=this,this.children.push(e),this.world&&this._ready&&e.enterTree(this.world),e}removeChild(e){let n=this.children.indexOf(e);n>=0&&(this.children.splice(n,1),e.parent=null)}free(){this.world?.requestFree(this)}find(e){if(this.name===e)return this;for(let n of this.children){let r=n.find(e);if(r)return r}return null}query(e,n=[]){this.type===e&&n.push(this);for(let r of this.children)r.query(e,n);return n}addBehavior(e){return this.behaviors.push(e),this._ready&&e.ready?.(this),this}signal(e){let n=this.signals.get(e);return n||(n=new et,this.signals.set(e,n)),n}emit(e,n){this.signals.get(e)?.emit(n)}enterTree(e){if(this.world=e,!this._ready){this._ready=!0,this.onReady();for(let n of this.behaviors)n.ready?.(this)}for(let n of this.children)n.enterTree(e)}updateTree(e){if(this._freed)return;let n=this.world;for(let r of this.behaviors)r.update?.(this,e,n);this.onUpdate?.(this,e,n),this.onProcess(e);for(let r of this.children.slice())r.updateTree(e)}exitTree(){for(let e of this.behaviors)e.exit?.(this);this.onExit();for(let e of this.children.slice())e.exitTree();this._freed=!0}get isFreed(){return this._freed}localTransform(){return ft(this.pos,this.rotation,this.scale)}worldTransform(){let e=this.localTransform();return this.parent?Ze(this.parent.worldTransform(),e):e}collectDraw(e,n=le){if(!this.visible)return;let r=Ze(n,this.localTransform());this.draw(e,r);for(let o of this.children)o.collectDraw(e,r)}draw(e,n){}onReady(){}onProcess(e){}onExit(){}serialize(){return{type:this.type,name:this.name,pos:{...this.pos},rotation:this.rotation,scale:{...this.scale},z:this.z,visible:this.visible,props:this.serializeProps(),children:this.children.filter(e=>!e.cosmetic).map(e=>e.serialize())}}serializeProps(){return{}}applyProps(e){}};var xt=class extends q{type="Sprite";shape;paint;constructor(e){super(e),this.shape=e.shape,this.paint={fill:e.fill,stroke:e.stroke,strokeWidth:e.strokeWidth,opacity:e.opacity,round:e.round,gradient:e.gradient,shadow:e.shadow}}draw(e,n){let r=this.paint,o={transform:n,z:this.z,...r};switch(this.shape.kind){case"rect":{let i=this.shape.anchor==="topLeft";e.push({kind:"rect",x:i?0:-this.shape.w/2,y:i?0:-this.shape.h/2,w:this.shape.w,h:this.shape.h,r:this.shape.r,...o});break}case"circle":e.push({kind:"circle",cx:0,cy:0,radius:this.shape.radius,...o});break;case"poly":e.push({kind:"poly",points:this.shape.points,closed:this.shape.closed??!0,...o});break;case"path":e.push({kind:"path",d:this.shape.d,...o});break;case"glyph":e.push({kind:"text",text:this.shape.char,x:0,y:0,size:this.shape.size,align:"center",...o});break}}serializeProps(){return{shape:this.shape,paint:this.paint}}applyProps(e){e.shape&&(this.shape=e.shape),e.paint&&(this.paint=e.paint)}},vt=class extends q{type="Text";text;size;font;align;weight;paint;constructor(e){super(e),this.text=e.text,this.size=e.size??24,this.font=e.font,this.align=e.align??"left",this.weight=e.weight,this.paint={fill:e.fill??"#000",stroke:e.stroke,strokeWidth:e.strokeWidth,opacity:e.opacity}}draw(e,n){e.push({kind:"text",text:this.text,x:0,y:0,size:this.size,font:this.font,align:this.align,weight:this.weight,transform:n,z:this.z,...this.paint})}serializeProps(){return{text:this.text,size:this.size,align:this.align,paint:this.paint}}applyProps(e){typeof e.text=="string"&&(this.text=e.text),typeof e.size=="number"&&(this.size=e.size),e.align&&(this.align=e.align),e.paint&&(this.paint=e.paint)}},wt=class extends q{type="Camera2D";zoom;current;constructor(e={}){super(e),this.zoom=e.zoom??1,this.current=e.current??!0}onReady(){this.current&&(this.world.activeCamera=this)}serializeProps(){return{zoom:this.zoom,current:this.current}}applyProps(e){typeof e.zoom=="number"&&(this.zoom=e.zoom),typeof e.current=="boolean"&&(this.current=e.current)}},kt=class extends q{type="Timer";duration;oneShot;remaining;running;constructor(e){super(e),this.duration=e.duration,this.oneShot=e.oneShot??!0,this.remaining=e.duration,this.running=e.autostart??!0}start(e){e!==void 0&&(this.duration=e),this.remaining=this.duration,this.running=!0}stop(){this.running=!1}get timeLeft(){return this.remaining}onProcess(e){this.running&&(this.remaining-=e,this.remaining<=0&&(this.emit("timeout",void 0),this.oneShot?this.running=!1:this.remaining+=this.duration))}get timeout(){return this.signal("timeout")}serializeProps(){return{duration:this.duration,oneShot:this.oneShot,remaining:this.remaining,running:this.running}}applyProps(e){typeof e.duration=="number"&&(this.duration=e.duration),typeof e.oneShot=="boolean"&&(this.oneShot=e.oneShot),typeof e.remaining=="number"&&(this.remaining=e.remaining),typeof e.running=="boolean"&&(this.running=e.running)}};var Fn=class extends q{type="CameraController";cosmetic=!0;target;cameraRef;deadzone;smooth;bounds;constructor(e={}){super(e),this.target=e.target??null,this.cameraRef=e.camera??null;let n=e.deadzone??0;this.deadzone=typeof n=="number"?{x:n,y:n}:{...n},this.smooth=e.smooth??.15,this.bounds=e.bounds?{...e.bounds}:null}follow(e){return this.target=e,this}host(){return this.world??null}camera(){return this.cameraRef??this.host()?.activeCamera??null}desired(e){let n=this.host(),r=this.target.worldTransform(),o=e.pos.x,i=e.pos.y,s=r.e-e.pos.x,a=r.f-e.pos.y;if(Math.abs(s)>this.deadzone.x&&(o=r.e-Math.sign(s)*this.deadzone.x),Math.abs(a)>this.deadzone.y&&(i=r.f-Math.sign(a)*this.deadzone.y),this.bounds){let l=e.zoom||1,u=n.width/2/l,c=n.height/2/l,m=this.bounds.minX+u,d=this.bounds.maxX-u,p=this.bounds.minY+c,h=this.bounds.maxY-c;o=m>d?(this.bounds.minX+this.bounds.maxX)/2:U(o,m,d),i=p>h?(this.bounds.minY+this.bounds.maxY)/2:U(i,p,h)}return{x:o,y:i}}snap(){let e=this.camera();if(!e||!this.target||!this.host())return;let n=this.desired(e);e.pos.x=n.x,e.pos.y=n.y}onReady(){this.snap()}onProcess(){let e=this.camera();if(!e||!this.target||!this.host())return;let n=this.desired(e),r=U(this.smooth,0,1);e.pos.x=Ie(e.pos.x,n.x,r),e.pos.y=Ie(e.pos.y,n.y,r)}};var Nn=class extends q{type="ParallaxLayer";cosmetic=!0;factor;constructor(e){super(e),this.factor=e.factor}sync(){let e=this.world?.activeCamera;e&&(this.pos.x=e.pos.x*(1-this.factor),this.pos.y=e.pos.y*(1-this.factor))}onReady(){this.sync()}onProcess(){this.sync()}};var $n=class{constructor(e,n){this.parent=e;this.make=n}parent;make;items=[];used=0;begin(){this.used=0}get(){this.used===this.items.length&&this.items.push(this.parent.addChild(this.make()));let e=this.items[this.used++];return e.visible=!0,e}end(){for(let e=this.used;e<this.items.length;e++)this.items[e].visible=!1}get liveCount(){return this.used}};var Js=(t,e,n,r)=>Ie(e,t,Be(-n*r)),mo=(t=0)=>({value:t,vel:0});function po(t,e,n,r){let o=Be(-n*r),i=t.value-e,s=t.vel+n*i;return t.value=e+(i+s*r)*o,t.vel=(t.vel-s*n*r)*o,t}function Us(t=0,e=.25){let n=4/Math.max(1e-4,e),r=mo(t);return(o,i)=>po(r,o,n,i).value}var co=t=>t*t,An=t=>t*t*t,Ln={linear:t=>t,quadIn:t=>t*t,quadOut:t=>1-(1-t)*(1-t),quadInOut:t=>t<.5?2*t*t:1-co(-2*t+2)/2,cubicIn:t=>t*t*t,cubicOut:t=>1-An(1-t),cubicInOut:t=>t<.5?4*t*t*t:1-An(-2*t+2)/2,sineIn:t=>1-X(t*Math.PI/2),sineOut:t=>_(t*Math.PI/2),sineInOut:t=>-(X(Math.PI*t)-1)/2,backOut:t=>1+2.70158*An(t-1)+1.70158*co(t-1),elasticOut:t=>{let e=2*Math.PI/3;return t===0?0:t===1?1:he(-10*t)*_((t*10-.75)*e)+1},bounceOut:t=>t<1/2.75?7.5625*t*t:t<2/2.75?7.5625*(t-=1.5/2.75)*t+.75:t<2.5/2.75?7.5625*(t-=2.25/2.75)*t+.9375:7.5625*(t-=2.625/2.75)*t+.984375},St=class extends q{type="AnimationPlayer";tracks=[];to(e,n,r,o,i="cubicOut",s={}){return this.tracks.push({apply:e,from:n,to:r,duration:Math.max(1e-6,o),elapsed:0,ease:typeof i=="function"?i:Ln[i]??Ln.linear,delay:s.delay??0,onDone:s.onDone}),this}get active(){return this.tracks.length>0}get finished(){return this.signal("finished")}onProcess(e){if(this.tracks.length!==0){for(let n=this.tracks.length-1;n>=0;n--){let r=this.tracks[n];if(r.delay>0){r.delay-=e;continue}r.elapsed+=e;let o=U(r.elapsed/r.duration,0,1);r.apply(r.from+(r.to-r.from)*r.ease(o)),o>=1&&(r.onDone?.(),this.tracks.splice(n,1))}this.tracks.length===0&&this.emit("finished",void 0)}}};var zn=class extends q{type="Particles";pool=[];rng;maxParticles;constructor(e={}){super(e),this.cosmetic=!0,this.rng=new ue(e.seed??7),this.maxParticles=e.maxParticles??512}burst(e,n,r){let o=this.rng;for(let i=0;i<e;i++){let s=r.angle!==void 0?r.angle+(o.float()-.5)*(r.spread??.6):o.float()*ie,a=r.speedMin+o.float()*(r.speedMax-r.speedMin),l={x:n.x,y:n.y,vx:X(s)*a,vy:_(s)*a,life:0,maxLife:r.lifeMin+o.float()*(r.lifeMax-r.lifeMin),size:r.sizeMin+o.float()*(r.sizeMax-r.sizeMin),color:r.colors[o.int(r.colors.length)]};this.pool.length>=this.maxParticles&&this.pool.shift(),this.pool.push(l)}this.gravity=r.gravity??0,this.drag=r.drag??0,this.shrink=r.shrink??!0}gravity=0;drag=0;shrink=!0;onProcess(e){let n=Math.max(0,1-this.drag*e),r=0;for(let o of this.pool)o.life+=e,!(o.life>=o.maxLife)&&(o.vy+=this.gravity*e,o.vx*=n,o.vy*=n,o.x+=o.vx*e,o.y+=o.vy*e,this.pool[r++]=o);this.pool.length=r}draw(e,n){for(let r of this.pool){let o=1-r.life/r.maxLife;e.push({kind:"circle",cx:r.x,cy:r.y,radius:this.shrink?r.size*o:r.size,fill:r.color,opacity:Math.min(1,o*2),transform:n,z:this.z,transient:!0})}}get liveCount(){return this.pool.length}},Ks={dust:(t=["#c8c2b6","#a09a8c"])=>({colors:t,sizeMin:2,sizeMax:4,speedMin:30,speedMax:90,lifeMin:.2,lifeMax:.45,gravity:300,drag:3,shrink:!0}),burst:(t=["#ffd75e","#ff9d47","#fff2c9"])=>({colors:t,sizeMin:2,sizeMax:5,speedMin:120,speedMax:320,lifeMin:.25,lifeMax:.6,drag:4,shrink:!0}),hit:(t=["#ff5e5e","#ffd0d0"])=>({colors:t,sizeMin:2,sizeMax:4,speedMin:160,speedMax:380,lifeMin:.15,lifeMax:.35,drag:6,shrink:!0}),sparkle:(t=["#9ef7ff","#e8fdff","#4ed8e8"])=>({colors:t,sizeMin:1.5,sizeMax:3.5,speedMin:20,speedMax:70,lifeMin:.4,lifeMax:.9,gravity:-40,drag:2,shrink:!0})};function ho(t,e){if(e.length===0)return 1;if(t<=e[0].time)return e[0].intensity;for(let n=1;n<e.length;n++)if(t<=e[n].time){let r=e[n-1],o=e[n];return r.intensity+(o.intensity-r.intensity)*Dn(r.time,o.time,t)}return e[e.length-1].intensity}var Wn=class extends q{type="AmbientField";rng;field=[];time=0;style;width;height;envelope;constructor(e){super(e),this.cosmetic=!0,this.rng=new ue(e.seed??11),this.width=e.width,this.height=e.height,this.style=e.style,this.envelope=e.envelope;let n=e.count??120,r=this.style;for(let o=0;o<n;o++)this.field.push({x:this.rng.float()*this.width,y:this.rng.float()*this.height,size:r.sizeMin+this.rng.float()*(r.sizeMax-r.sizeMin),color:r.colors[this.rng.int(r.colors.length)],phase:this.rng.float()*ie,depth:.5+this.rng.float()*.5})}intensity(){return this.envelope?ho(this.time,this.envelope):1}onProcess(e){this.time+=e;let n=this.style,r=n.windX??0,o=this.width,i=this.height;for(let s of this.field)s.y+=n.fallY*s.depth*e,s.x+=r*e,s.y>i?s.y-=i:s.y<0&&(s.y+=i),s.x>o?s.x-=o:s.x<0&&(s.x+=o)}draw(e,n){let r=this.style,o=this.intensity();if(o<=0)return;let i=Math.round(this.field.length*o),s=r.swayAmp??0,a=r.swayFreq??0;for(let l=0;l<i;l++){let u=this.field[l],c=s!==0?_(this.time*a*ie+u.phase)*s:0,m=u.x+c;if(r.streak){let d=r.streakLen??r.fallY*.03;e.push({kind:"poly",points:[m,u.y,m,u.y+d],closed:!1,stroke:u.color,strokeWidth:u.size,opacity:o,transform:n,z:this.z,transient:!0})}else e.push({kind:"circle",cx:m,cy:u.y,radius:u.size,fill:u.color,opacity:o,transform:n,z:this.z,transient:!0})}}get liveCount(){return this.field.length}},Ys={snow:(t=["#ffffff","#e8f0f8","#cdd9e6"])=>({colors:t,sizeMin:1.5,sizeMax:3.5,windX:8,fallY:42,swayAmp:14,swayFreq:.25}),rain:(t=["#9fb4c8","#c3d2e0"])=>({colors:t,sizeMin:1,sizeMax:1.8,windX:-40,fallY:620,streak:!0,streakLen:16}),ash:(t=["#6b6b6b","#8a8580","#3d3a36"])=>({colors:t,sizeMin:1,sizeMax:2.5,windX:14,fallY:26,swayAmp:20,swayFreq:.18})},Bn=class extends q{type="Shaker";rng;trauma=0;amplitude;decay;constructor(e={}){super(e),this.cosmetic=!0,this.rng=new ue(e.seed??99),this.amplitude=e.amplitude??14,this.decay=e.decay??2.6}addTrauma(e){this.trauma=Math.min(1,this.trauma+e)}onProcess(e){this.trauma=Math.max(0,this.trauma-this.decay*e);let n=this.trauma*this.trauma*this.amplitude;this.pos.x=(this.rng.float()*2-1)*n,this.pos.y=(this.rng.float()*2-1)*n}};var On=class extends q{type="FloatingText";pool=[];rng;maxPopups;constructor(e={}){super(e),this.cosmetic=!0,this.rng=new ue(e.seed??31),this.maxPopups=e.maxPopups??128}pop(e,n,r){let o=r.jitter??0,i={x:n.x+(this.rng.float()-.5)*o*.1,y:n.y,vx:(this.rng.float()-.5)*o,vy:-(r.rise??60),life:0,maxLife:Math.max(.05,r.life??.9),text:e,color:r.color,size:r.size??20,font:r.font,weight:r.weight,align:r.align??"center",fade:U(r.fade??.4,0,1)};this.gravity=r.gravity??0,this.pool.length>=this.maxPopups&&this.pool.shift(),this.pool.push(i)}gravity=0;onProcess(e){let n=0;for(let r of this.pool)r.life+=e,!(r.life>=r.maxLife)&&(r.vy+=this.gravity*e,r.x+=r.vx*e,r.y+=r.vy*e,this.pool[n++]=r);this.pool.length=n}draw(e,n){for(let r of this.pool){let o=r.life/r.maxLife,i=1-r.fade,s=o<i?1:U(1-(o-i)/Math.max(1e-4,r.fade),0,1);e.push({kind:"text",text:r.text,x:r.x,y:r.y,size:r.size,font:r.font,weight:r.weight,align:r.align,fill:r.color,opacity:s,transform:n,z:this.z,transient:!0})}}get liveCount(){return this.pool.length}},Xs={damage:(t="#e14b4b")=>({color:t,size:22,weight:700,rise:70,gravity:120,life:.8,jitter:40,fade:.4}),crit:(t="#ffb020")=>({color:t,size:32,weight:800,rise:100,gravity:160,life:1,jitter:60,fade:.35}),heal:(t="#4bb06a")=>({color:t,size:20,weight:700,rise:55,gravity:40,life:1,jitter:20,fade:.5}),label:(t="#3d3323")=>({color:t,size:18,weight:600,rise:40,gravity:0,life:1.2,jitter:0,fade:.5})};var fo=new Map;function Oe(t,e){fo.set(t,e)}Oe("Node",()=>new q);Oe("Sprite",()=>new xt({shape:{kind:"rect",w:1,h:1}}));Oe("Text",()=>new vt({text:""}));Oe("Camera2D",()=>new wt);Oe("Timer",()=>new kt({duration:1}));Oe("AnimationPlayer",()=>new St);function en(t){let e=fo.get(t.type);if(!e)throw new Error(`hayao: unknown node type "${t.type}" (register it first)`);let n=e();n.name=t.name,n.pos={...t.pos},n.rotation=t.rotation,n.scale={...t.scale},n.z=t.z,n.visible=t.visible,n.applyProps(t.props);for(let r of t.children)n.addChild(en(r));return n}var Mt=class{down=new Set;prev=new Set;axes=new Map;beginFrame(e){this.prev=new Set(this.down),this.down=new Set(e)}isDown(e){return this.down.has(e)}justPressed(e){return this.down.has(e)&&!this.prev.has(e)}justReleased(e){return!this.down.has(e)&&this.prev.has(e)}axis(e){return this.axes.get(e)??0}snapshot(){return[...this.down].sort()}getState(){return{down:[...this.down].sort(),prev:[...this.prev].sort()}}setState(e){this.down=new Set(e.down),this.prev=new Set(e.prev)}};function Vn(t,e){let n=[];for(let r in t)t[r].some(o=>e.has(o))&&n.push(r);return n.sort()}var Gn=class{frames=[];record(e){this.frames.push(e.slice().sort())}get length(){return this.frames.length}toLog(){return{frames:this.frames.map(e=>e.slice())}}};function tt(t,e){return t.frames[e]??[]}var tn={up:["ArrowUp","KeyW"],down:["ArrowDown","KeyS"],left:["ArrowLeft","KeyA"],right:["ArrowRight","KeyD"],confirm:["Enter","Space"],cancel:["Escape","Backspace"],action:["KeyZ","KeyJ"],action2:["KeyX","KeyK"],undo:["KeyU"],restart:["KeyR"]};var Ge=class{keysDown=new Set;pressed=new Set;map;target;onDown;onUp;onBlur;constructor(e,n=document){this.map=e,this.target=n,this.onDown=r=>{this.keysDown.add(r.code),(r.code.startsWith("Arrow")||r.code==="Space")&&r.preventDefault()},this.onUp=r=>this.keysDown.delete(r.code),this.onBlur=()=>this.keysDown.clear(),n.addEventListener("keydown",this.onDown),n.addEventListener("keyup",this.onUp),globalThis.addEventListener?.("blur",this.onBlur)}currentActions(){let e=Vn(this.map,this.keysDown);if(this.pressed.size===0)return e;let n=new Set(e);for(let r of this.pressed)n.add(r);return[...n].sort()}press(e){this.pressed.add(e)}clearPressed(){this.pressed.clear()}setMap(e){this.map=e}dispose(){this.target.removeEventListener("keydown",this.onDown),this.target.removeEventListener("keyup",this.onUp),globalThis.removeEventListener?.("blur",this.onBlur)}},Ct=class{clientX=0;clientY=0;isDown=!1;seen=!1;target;el;onMove;onDown;onUp;constructor(e){this.target=e,this.el=e.element,this.onMove=n=>{this.clientX=n.clientX,this.clientY=n.clientY,this.seen=!0},this.onDown=n=>{this.clientX=n.clientX,this.clientY=n.clientY,this.isDown=!0,this.seen=!0},this.onUp=()=>{this.isDown=!1},this.el?.addEventListener("pointermove",this.onMove),this.el?.addEventListener("pointerdown",this.onDown),globalThis.addEventListener?.("pointerup",this.onUp),globalThis.addEventListener?.("pointercancel",this.onUp)}read(){let e=this.target.toDesign?.(this.clientX,this.clientY)??{x:0,y:0};return{x:e.x,y:e.y,down:this.isDown,active:this.seen}}sample(e){let n=this.read(),r=o=>Math.round(o*8)/8;e.axes.set("pointer.x",r(n.x)),e.axes.set("pointer.y",r(n.y)),e.axes.set("pointer.down",n.down?1:0)}dispose(){this.el?.removeEventListener("pointermove",this.onMove),this.el?.removeEventListener("pointerdown",this.onDown),globalThis.removeEventListener?.("pointerup",this.onUp),globalThis.removeEventListener?.("pointercancel",this.onUp)}};var j={EMPTY:0,SOLID:1,ONEWAY:2,HAZARD:3},qn={"#":j.SOLID,"-":j.ONEWAY,"^":j.HAZARD};function jn(t,e=32,n=qn){let r=t.length,o=Math.max(...t.map(s=>s.length)),i=new Array(o*r).fill(j.EMPTY);return t.forEach((s,a)=>{for(let l=0;l<s.length;l++)i[a*o+l]=n[s[l]]??j.EMPTY}),{cols:o,rows:r,tileSize:e,tiles:i}}function Qs(t,e=32,n=qn){let r=[];return t.forEach((o,i)=>{for(let s=0;s<o.length;s++){let a=o[s];a===" "||a==="."||n[a]!==void 0||r.push({char:a,tx:s,ty:i,x:(s+.5)*e,y:(i+.5)*e})}}),r}function fe(t,e,n){return e<0||n<0||e>=t.cols||n>=t.rows?j.SOLID:t.tiles[n*t.cols+e]}function Zs(t,e,n){return fe(t,Math.floor(e/t.tileSize),Math.floor(n/t.tileSize))}var ea=t=>t.cols*t.tileSize,ta=t=>t.rows*t.tileSize;var H=1e-6,Ve=(t,e,n)=>[Math.floor(t/n),Math.floor((e-H)/n)];function Ae(t,e,n,r,o,i=[]){let s=t.tileSize,[a,l]=Ve(e,e+r,s),[u,c]=Ve(n,n+o,s);for(let m=u;m<=c;m++)for(let d=a;d<=l;d++)if(fe(t,d,m)===j.SOLID)return!0;for(let m of i)if(!m.oneway&&e<m.x+m.w-H&&e+r>m.x+H&&n<m.y+m.h-H&&n+o>m.y+H)return!0;return!1}function Tt(t,e,n,r,o={}){let i=t.tileSize,s=o.solids??[],{x:a,y:l}=e,{w:u,h:c}=e,m=!1,d=!1,p=!1,h=!1;if(n!==0){let[v,f]=Ve(l,l+c,i);if(n>0){let M=a+n,[S,D]=[Math.floor((a+u)/i),Math.floor((a+u+n-H)/i)];for(let C=S;C<=D;C++)for(let y=v;y<=f;y++)fe(t,C,y)===j.SOLID&&(M=Math.min(M,C*i-u));for(let C of s)!C.oneway&&C.y<l+c-H&&C.y+C.h>l+H&&C.x>=a+u-H&&(M=Math.min(M,C.x-u));M<a+n-H&&(m=!0,h=!0),a=Math.min(a+n,M)}else{let M=a+n,[S,D]=[Math.floor((a-H)/i),Math.floor((a+n)/i)];for(let C=S;C>=D;C--)for(let y=v;y<=f;y++)fe(t,C,y)===j.SOLID&&(M=Math.max(M,(C+1)*i));for(let C of s)!C.oneway&&C.y<l+c-H&&C.y+C.h>l+H&&C.x+C.w<=a+H&&(M=Math.max(M,C.x+C.w));M>a+n+H&&(m=!0,p=!0),a=Math.max(a+n,M)}}let g=l+c,x=!1,k=!1,w=-1;if(r!==0){let[v,f]=Ve(a,a+u,i);if(r>0){let M=l+r,[S,D]=[Math.floor(g/i),Math.floor((g+r-H)/i)];for(let C=S;C<=D;C++)for(let y=v;y<=f;y++){let T=fe(t,y,C);(T===j.SOLID||T===j.ONEWAY&&!o.dropThrough&&g<=C*i+H)&&(M=Math.min(M,C*i-c))}for(let C=0;C<s.length;C++){let y=s[C];!(y.x<a+u-H&&y.x+y.w>a+H)||y.y<g-H||y.oneway&&(o.dropThrough||g>y.y+H)||y.y-c<M&&(M=y.y-c,w=C)}M<l+r-H?(d=!0,x=!0):w=-1,l=Math.min(l+r,M)}else{let M=l+r,[S,D]=[Math.floor((l-H)/i),Math.floor((l+r)/i)];for(let C=S;C>=D;C--)for(let y=v;y<=f;y++)fe(t,y,C)===j.SOLID&&(M=Math.max(M,(C+1)*i));for(let C of s)!C.oneway&&C.x<a+u-H&&C.x+C.w>a+H&&C.y+C.h<=l+H&&(M=Math.max(M,C.y+C.h));M>l+r+H&&(d=!0,k=!0),l=Math.max(l+r,M)}}if(!x){let v=bo(t,a,l,u,c,s,o.dropThrough??!1);x=v.grounded,w=v.solid}let P=3,$=!1;{let[v,f]=Ve(a+P,a+u-P,i),[M,S]=Ve(l+P,l+c-P,i);for(let D=M;D<=S&&!$;D++)for(let C=v;C<=f&&!$;C++)fe(t,C,D)===j.HAZARD&&($=!0)}return{x:a,y:l,hitX:m,hitY:d,onFloor:x,onCeiling:k,onWallLeft:p,onWallRight:h,hazard:$,floorSolid:w}}function bo(t,e,n,r,o,i=[],s=!1){let a=t.tileSize,l=n+o,[u,c]=Ve(e,e+r,a),m=Math.floor((l+1)/a);for(let d=u;d<=c;d++){let p=fe(t,d,m);if(p===j.SOLID)return{grounded:!0,solid:-1};if(p===j.ONEWAY&&!s&&Math.abs(l-m*a)<=1+H)return{grounded:!0,solid:-1}}for(let d=0;d<i.length;d++){let p=i[d];if(p.x<e+r-H&&p.x+p.w>e+H&&l<=p.y+1+H&&l>=p.y-1-H)return{grounded:!0,solid:d}}return{grounded:!1,solid:-1}}var nt={width:22,height:28,runSpeed:340,groundAccel:3800,groundFriction:4200,airAccel:2600,airFriction:260,gravity:2300,maxFall:660,apexThreshold:60,apexGravityMult:.5,jumpVelocity:650,jumpCutMult:.4,coyoteTime:.1,jumpBuffer:.12,jumpCornerNudge:10,dashCornerNudge:12,airJumps:0,airJumpMult:.92,dashSpeed:640,dashTime:.14,dashCooldown:.25,dashCharges:1,wallSlideMaxFall:150,wallJumpVelX:360,wallJumpVelY:600,wallJumpLock:.13},na={moveX:0,moveY:0,jumpHeld:!1,jumpPressed:!1,dashPressed:!1};function ra(t,e){return{x:t,y:e,vx:0,vy:0,facing:1,onGround:!1,onWall:0,coyote:0,buffer:0,jumping:!1,wallLock:0,airJumpsLeft:0,dashing:0,dashCd:0,dashesLeft:1,dashVx:0,dashVy:0,carryVx:0,carryVy:0,dead:!1}}var oa=(t,e,n)=>t<e?Math.min(t+n,e):Math.max(t-n,e);function ia(t,e,n,r,o=nt,i=[]){let s={jumped:!1,wallJumped:!1,airJumped:!1,dashed:!1,landed:!1,died:!1};if(t.dead)return s;let a=t.onGround;if(t.coyote=Math.max(0,t.coyote-n),t.buffer=Math.max(0,t.buffer-n),t.wallLock=Math.max(0,t.wallLock-n),t.dashCd=Math.max(0,t.dashCd-n),e.jumpPressed&&(t.buffer=o.jumpBuffer),e.dashPressed&&t.dashing<=0&&t.dashCd<=0&&t.dashesLeft>0){let d=e.moveX,p=e.moveY;d===0&&p===0&&(d=t.facing);let h=1/Q(d,p);t.dashing=o.dashTime,t.dashCd=o.dashCooldown,t.dashesLeft--,t.dashVx=d*h*o.dashSpeed,t.dashVy=p*h*o.dashSpeed,t.jumping=!1,s.dashed=!0}if(t.dashing>0)t.vx=t.dashVx,t.vy=t.dashVy,t.dashing-=n;else if(t.wallLock<=0){let d=e.moveX*o.runSpeed,p=t.onGround?e.moveX!==0?o.groundAccel:o.groundFriction:e.moveX!==0?o.airAccel:o.airFriction;t.vx=oa(t.vx,d,p*n),e.moveX!==0&&(t.facing=e.moveX>0?1:-1)}if(t.dashing<=0&&!t.onGround){let d=o.gravity;Math.abs(t.vy)<o.apexThreshold&&e.jumpHeld&&t.jumping&&(d*=o.apexGravityMult),t.vy=Math.min(t.vy+d*n,o.maxFall),t.onWall!==0&&t.vy>o.wallSlideMaxFall&&e.moveX===t.onWall&&(t.vy=o.wallSlideMaxFall)}t.jumping&&!e.jumpHeld&&t.vy<0&&(t.vy*=o.jumpCutMult,t.jumping=!1),t.buffer>0&&t.dashing<=0&&(t.onGround||t.coyote>0?(t.vy=-o.jumpVelocity,t.vx+=t.carryVx,t.carryVy<0&&(t.vy+=t.carryVy),t.jumping=!0,t.buffer=0,t.coyote=0,t.onGround=!1,s.jumped=!0):t.onWall!==0&&o.wallJumpVelY>0?(t.vx=-t.onWall*o.wallJumpVelX,t.vy=-o.wallJumpVelY,t.facing=-t.onWall,t.jumping=!0,t.buffer=0,t.wallLock=o.wallJumpLock,s.wallJumped=!0,s.jumped=!0):t.airJumpsLeft>0&&(t.vy=-o.jumpVelocity*o.airJumpMult,t.airJumpsLeft--,t.jumping=!0,t.buffer=0,s.jumped=!0,s.airJumped=!0));let l=e.moveY>0&&t.buffer<=0,u=t.vx*n+t.carryVx*n*(t.onGround?1:0),c=t.vy*n+Math.max(0,t.carryVy)*n*(t.onGround?1:0),m=Tt(r,{x:t.x,y:t.y,w:o.width,h:o.height},u,c,{solids:i,dropThrough:l});if(m.onCeiling&&t.vy<0&&t.dashing<=0){let d=la(r,i,m.x,m.y,o.width,o.height,c,o.jumpCornerNudge);d!==null&&(m=Tt(r,{x:d,y:m.y,w:o.width,h:o.height},0,c,{solids:i,dropThrough:l}),m.x=d)}if(m.hitX&&t.dashing>0&&Math.abs(t.dashVy)<1){let d=ua(r,i,m.x,m.y,o.width,o.height,u,o.dashCornerNudge);d!==null&&(m=Tt(r,{x:m.x,y:d,w:o.width,h:o.height},u,0,{solids:i,dropThrough:l}),m.y=d)}if(t.x=m.x,t.y=m.y,m.hitY&&t.vy>0&&(t.vy=0),m.onCeiling&&(t.vy=Math.max(t.vy,0),t.jumping=!1),m.hitX&&t.dashing<=0&&(t.vx=0),t.onWall=m.onWallLeft?-1:m.onWallRight?1:ca(r,i,t.x,t.y,o.width,o.height),t.onGround=m.onFloor,t.onGround){if(t.coyote=o.coyoteTime,t.dashesLeft=o.dashCharges,t.airJumpsLeft=o.airJumps,a||(s.landed=!0),m.floorSolid>=0){let d=i[m.floorSolid];t.carryVx=d.vx,t.carryVy=d.vy,t.y=d.y-o.height}else t.carryVx=0,t.carryVy=0;t.vy>0&&(t.vy=0),t.jumping=!1}else a&&t.carryVy;return m.hazard&&(t.dead=!0,s.died=!0),s}function sa(t=nt){return t.jumpVelocity*t.jumpVelocity/(2*t.gravity)}function go(t=nt){return 2*t.jumpVelocity/t.gravity}function yo(t=nt){return t.runSpeed*go(t)}function aa(t=nt){return yo(t)+(t.dashSpeed-t.runSpeed)*t.dashTime}function la(t,e,n,r,o,i,s,a){for(let l=1;l<=a;l++)for(let u of[1,-1]){let c=n+u*l;if(!Ae(t,c,r+s,o,i,e)&&!Ae(t,c,r,o,i,e))return c}return null}function ua(t,e,n,r,o,i,s,a){for(let l=1;l<=a;l++)for(let u of[-1,1]){let c=r+u*l;if(!Ae(t,n+s,c,o,i,e)&&!Ae(t,n,c,o,i,e))return c}return null}function ca(t,e,n,r,o,i){return Ae(t,n+1,r,o,i,e)?1:Ae(t,n-1,r,o,i,e)?-1:0}var Rt=class{cells=new Map;bounds=new Map;cellSize;constructor(e=64){this.cellSize=e}clear(){this.cells.clear(),this.bounds.clear()}get size(){return this.bounds.size}key(e,n){return(e+32768)*65536+(n+32768)}insert(e,n){this.bounds.set(e,n);let r=this.cellSize,o=Math.floor(n.x/r),i=Math.floor((n.x+n.w)/r),s=Math.floor(n.y/r),a=Math.floor((n.y+n.h)/r);for(let l=s;l<=a;l++)for(let u=o;u<=i;u++){let c=this.key(u,l),m=this.cells.get(c);m?m.push(e):this.cells.set(c,[e])}}query(e){let n=this.cellSize,r=Math.floor(e.x/n),o=Math.floor((e.x+e.w)/n),i=Math.floor(e.y/n),s=Math.floor((e.y+e.h)/n),a=new Set,l=[];for(let u=i;u<=s;u++)for(let c=r;c<=o;c++){let m=this.cells.get(this.key(c,u));if(m)for(let d of m){if(a.has(d))continue;a.add(d);let p=this.bounds.get(d);p.x<e.x+e.w&&p.x+p.w>e.x&&p.y<e.y+e.h&&p.y+p.h>e.y&&l.push(d)}}return l}queryCircle(e,n,r){return this.query({x:e-r,y:n-r,w:r*2,h:r*2}).filter(i=>{let s=this.bounds.get(i),a=Math.max(s.x,Math.min(e,s.x+s.w)),l=Math.max(s.y,Math.min(n,s.y+s.h));return(e-a)*(e-a)+(n-l)*(n-l)<=r*r})}};function xo(t,e,n,r,o){let i=t.tileSize,s=r-e,a=o-n,l=Q(s,a);if(l===0)return{blocked:!1,x:r,y:o,dist:0};let u=s/l,c=a/l,m=Math.floor(e/i),d=Math.floor(n/i),p=u>0?1:-1,h=c>0?1:-1,g=u!==0?Math.abs(i/u):1/0,x=c!==0?Math.abs(i/c):1/0,k=u!==0?(u>0?(m+1)*i-e:e-m*i)/Math.abs(u):1/0,w=c!==0?(c>0?(d+1)*i-n:n-d*i)/Math.abs(c):1/0,P=0;for(let $=0;$<512;$++){if(k<w?(P=k,k+=g,m+=p):(P=w,w+=x,d+=h),P>=l)return{blocked:!1,x:r,y:o,dist:l};if(fe(t,m,d)===j.SOLID)return{blocked:!0,x:e+u*P,y:n+c*P,dist:P}}return{blocked:!0,x:e+u*P,y:n+c*P,dist:P}}function vo(t,e,n,r,o){return!xo(t,e,n,r,o).blocked}function ma(t,e,n,r,o,i,s,a,l){let u=a-e,c=l-n,m=Q(u,c);return m>s||m===0||(u*r+c*o)/m<X(i/2)?!1:vo(t,e,n,a,l)}function da(t={}){return{gravityX:t.gravityX??0,gravityY:t.gravityY??900,iterations:t.iterations??16,cellSize:t.cellSize??96,nextId:1,bodies:[],joints:[],warm:{}}}function pa(t){if(t.kind==="circle")return{area:Math.PI*t.r*t.r,unitI:t.r*t.r/2};let e=t.points,n=e.length/2,r=0,o=0;for(let i=0;i<n;i++){let s=e[i*2],a=e[i*2+1],l=(i+1)%n,u=e[l*2],c=e[l*2+1],m=s*c-u*a;r+=m/2,o+=m*(s*s+s*u+u*u+a*a+a*c+c*c)/12}return{area:Math.abs(r),unitI:r!==0?Math.abs(o)/Math.abs(r):0}}var ha=1e-4;function fa(t,e){let n=e.kind??"dynamic",r=e.density??1,{area:o,unitI:i}=pa(e.shape),s=n==="dynamic"?Math.max(o*r*ha,1e-6):0,a=n==="dynamic"&&!e.fixedRotation?s*i:0,l={id:t.nextId++,kind:n,shape:e.shape,x:e.x??0,y:e.y??0,a:e.a??0,vx:e.vx??0,vy:e.vy??0,w:e.w??0,m:s,invM:s>0?1/s:0,i:a,invI:a>0?1/a:0,restitution:e.restitution??.1,friction:e.friction??.4,linDamp:e.linDamp??0,angDamp:e.angDamp??.6,gravityScale:e.gravityScale??1,bullet:e.bullet??!1,sensor:e.sensor??!1,layer:e.layer??1,mask:e.mask??65535,canSleep:e.canSleep??!0,sleeping:!1,sleepTime:0,sleepR:e.shape.kind==="circle"?e.shape.r:Math.sqrt(e.shape.points.reduce((u,c,m,d)=>m%2?u:Math.max(u,d[m]*d[m]+d[m+1]*d[m+1]),0)),fx:0,fy:0,torque:0};return t.bodies.push(l),l.id}function ge(t,e){let n=t.bodies;for(let r=0;r<n.length;r++)if(n[r].id===e)return n[r]}function ba(t,e){let n=t.bodies.findIndex(r=>r.id===e);n>=0&&t.bodies.splice(n,1),t.joints=t.joints.filter(r=>r.a!==e&&r.b!==e)}function ye(t){t.sleeping=!1,t.sleepTime=0}function ga(t,e,n,r,o,i){let s=ge(t,e);!s||s.invM===0||(ye(s),s.vx+=n*s.invM,s.vy+=r*s.invM,o!==void 0&&i!==void 0&&(s.w+=((o-s.x)*r-(i-s.y)*n)*s.invI))}function we(t){if(t.shape.kind!=="poly")return[];let e=X(t.a),n=_(t.a),r=t.shape.points,o=new Array(r.length);for(let i=0;i<r.length;i+=2)o[i]=t.x+r[i]*e-r[i+1]*n,o[i+1]=t.y+r[i]*n+r[i+1]*e;return o}function nn(t){if(t.shape.kind==="circle"){let s=t.shape.r;return{x:t.x-s,y:t.y-s,w:s*2,h:s*2}}let e=we(t),n=1/0,r=1/0,o=-1/0,i=-1/0;for(let s=0;s<e.length;s+=2)e[s]<n&&(n=e[s]),e[s]>o&&(o=e[s]),e[s+1]<r&&(r=e[s+1]),e[s+1]>i&&(i=e[s+1]);return{x:n,y:r,w:o-n,h:i-r}}function ya(t,e){let n=t/2,r=e/2;return{kind:"poly",points:[-n,-r,n,-r,n,r,-n,r]}}function xa(t,e){if(t.shape.kind!=="circle"||e.shape.kind!=="circle")return null;let n=e.x-t.x,r=e.y-t.y,o=t.shape.r+e.shape.r,i=n*n+r*r;if(i>=o*o)return null;let s=Math.sqrt(i),a=s>1e-9?n/s:1,l=s>1e-9?r/s:0;return{a:t,b:e,nx:a,ny:l,points:[{px:t.x+a*t.shape.r,py:t.y+l*t.shape.r,pen:o-s,feature:0}]}}function wo(t,e){if(t.shape.kind!=="poly"||e.shape.kind!=="circle")return null;let n=we(t),r=n.length/2,o=e.shape.r,i=-1/0,s=0;for(let D=0;D<r;D++){let C=(D+1)%r,y=n[C*2]-n[D*2],T=n[C*2+1]-n[D*2+1],E=Q(y,T)||1,O=T/E,F=-y/E,J=(e.x-n[D*2])*O+(e.y-n[D*2+1])*F;J>i&&(i=J,s=D)}if(i>o)return null;let a=s,l=(s+1)%r,u=n[a*2],c=n[a*2+1],m=n[l*2],d=n[l*2+1];if(i<1e-9){let D=m-u,C=d-c,y=Q(D,C)||1,T=C/y,E=-D/y;return{a:t,b:e,nx:T,ny:E,points:[{px:e.x-T*o,py:e.y-E*o,pen:o-i,feature:s}]}}let p=m-u,h=d-c,g=p*p+h*h||1,x=((e.x-u)*p+(e.y-c)*h)/g;x=x<0?0:x>1?1:x;let k=u+p*x,w=c+h*x,P=e.x-k,$=e.y-w,v=P*P+$*$;if(v>=o*o)return null;let f=Math.sqrt(v)||1e-9,M=P/f,S=$/f;return{a:t,b:e,nx:M,ny:S,points:[{px:k,py:w,pen:o-f,feature:s}]}}function ko(t,e){let n=t.length/2,r=e.length/2,o=-1/0,i=0;for(let s=0;s<n;s++){let a=(s+1)%n,l=t[a*2]-t[s*2],u=t[a*2+1]-t[s*2+1],c=Q(l,u)||1,m=u/c,d=-l/c,p=1/0;for(let h=0;h<r;h++){let g=(e[h*2]-t[s*2])*m+(e[h*2+1]-t[s*2+1])*d;g<p&&(p=g)}p>o&&(o=p,i=s)}return[o,i]}function va(t,e){let n=we(t),r=we(e),[o,i]=ko(n,r);if(o>0)return null;let[s,a]=ko(r,n);if(s>0)return null;let l,u,c,m;s>o+1e-4?(l=r,u=n,c=a,m=!0):(l=n,u=r,c=i,m=!1);let d=l.length/2,p=u.length/2,h=(c+1)%d,g=l[h*2]-l[c*2],x=l[h*2+1]-l[c*2+1],k=Q(g,x)||1,w=x/k,P=-g/k,$=g/k,v=x/k,f=0,M=1/0;for(let B=0;B<p;B++){let W=(B+1)%p,V=u[W*2]-u[B*2],re=u[W*2+1]-u[B*2+1],oe=Q(V,re)||1,te=re/oe*w+-V/oe*P;te<M&&(M=te,f=B)}let S=(f+1)%p,D=u[f*2],C=u[f*2+1],y=u[S*2],T=u[S*2+1],E=l[c*2],O=l[c*2+1],F=l[h*2],J=l[h*2+1];for(let B=0;B<2;B++){let W=B===0?E:F,V=B===0?O:J,re=B===0?$:-$,oe=B===0?v:-v,te=(D-W)*re+(C-V)*oe,se=(y-W)*re+(T-V)*oe;if(te<0&&se<0)return null;if(te<0){let me=te/(te-se);D=D+(y-D)*me,C=C+(T-C)*me}else if(se<0){let me=se/(se-te);y=y+(D-y)*me,T=T+(C-T)*me}}let Y=m?-w:w,ne=m?-P:P,Z=[],ae=-((D-E)*w+(C-O)*P),I=-((y-E)*w+(T-O)*P),z=((m?1:0)*64+c)*64+f;return ae>0&&Z.push({px:D,py:C,pen:ae,feature:z*2}),I>0&&Z.push({px:y,py:T,pen:I,feature:z*2+1}),Z.length===0?null:{a:t,b:e,nx:Y,ny:ne,points:Z}}function Hn(t,e){let n=t.shape.kind,r=e.shape.kind;if(n==="circle"&&r==="circle")return xa(t,e);if(n==="poly"&&r==="poly")return va(t,e);if(n==="poly"&&r==="circle")return wo(t,e);let o=wo(e,t);return o?{a:t,b:e,nx:-o.nx,ny:-o.ny,points:o.points}:null}function So(t,e,n){let r=X(t.a),o=_(t.a),i=e-t.x,s=n-t.y;return[i*r+s*o,-i*o+s*r]}function rn(t,e,n){let r=X(t.a),o=_(t.a);return[t.x+e*r-n*o,t.y+e*o+n*r]}function wa(t,e){let n=ge(t,e.a),r=ge(t,e.b);if(!n||!r)throw new Error(`distance joint: missing body ${e.a}/${e.b}`);let o=e.ax??0,i=e.ay??0,s=e.bx??0,a=e.by??0,[l,u]=rn(n,o,i),[c,m]=rn(r,s,a),d={kind:"distance",id:t.nextId++,a:e.a,b:e.b,ax:o,ay:i,bx:s,by:a,length:e.length??Q(c-l,m-u),rope:e.rope??!1};return t.joints.push(d),ye(n),ye(r),d.id}function ka(t,e){let n=ge(t,e.a),r=ge(t,e.b);if(!n||!r)throw new Error(`revolute joint: missing body ${e.a}/${e.b}`);let[o,i]=So(n,e.px,e.py),[s,a]=So(r,e.px,e.py),l={kind:"revolute",id:t.nextId++,a:e.a,b:e.b,ax:o,ay:i,bx:s,by:a,motorSpeed:e.motorSpeed??0,maxMotorTorque:e.maxMotorTorque??0,limitLower:e.limitLower??0,limitUpper:e.limitUpper??0,limitEnabled:e.limitLower!==void 0||e.limitUpper!==void 0,refAngle:r.a-n.a};return t.joints.push(l),ye(n),ye(r),l.id}function Sa(t,e){for(let n of t.joints)if(n.id===e)return n}function Ma(t,e){t.joints=t.joints.filter(n=>n.id!==e)}function _n(t,e,n,r,o){let[i,s]=rn(e,t.ax,t.ay),[a,l]=rn(n,t.bx,t.by),u=i-e.x,c=s-e.y,m=a-n.x,d=l-n.y;if(t.kind==="distance"){let y=a-i,T=l-s,E=Q(y,T);if(E<1e-9)return;y/=E,T/=E;let O=E-t.length;if(t.rope&&O<=0)return;let F=e.vx-e.w*c,J=e.vy+e.w*u,Y=n.vx-n.w*d,ne=n.vy+n.w*m,Z=(Y-F)*y+(ne-J)*T,ae=u*T-c*y,I=m*T-d*y,z=e.invM+n.invM+e.invI*ae*ae+n.invI*I*I;if(z<1e-12)return;let B=.2/r*O,W=-(Z+B)/z;t.rope&&W>0&&(W=0);let V=y*W,re=T*W;e.vx-=V*e.invM,e.vy-=re*e.invM,e.w-=(u*re-c*V)*e.invI,n.vx+=V*n.invM,n.vy+=re*n.invM,n.w+=(m*re-d*V)*n.invI;return}if(t.maxMotorTorque>0){let y=e.invI+n.invI;if(y>1e-12){let E=-(n.w-e.w-t.motorSpeed)/y,O=t.maxMotorTorque*r,F=o.motorImpulse;o.motorImpulse=Math.min(Math.max(F+E,-O),O);let J=o.motorImpulse-F;e.w-=J*e.invI,n.w+=J*n.invI}}if(t.limitEnabled){let y=e.invI+n.invI;if(y>1e-12){let T=n.a-e.a-t.refAngle,E=0;if(T<t.limitLower?E=T-t.limitLower:T>t.limitUpper&&(E=T-t.limitUpper),E!==0){let F=-(n.w-e.w+.2/r*E)/y;(E<0&&F>0||E>0&&F<0)&&(e.w-=F*e.invI,n.w+=F*n.invI)}}}let p=e.vx-e.w*c,h=e.vy+e.w*u,g=n.vx-n.w*d,x=n.vy+n.w*m,k=a-i,w=l-s,P=g-p+.2/r*k,$=x-h+.2/r*w,v=e.invM+n.invM+e.invI*c*c+n.invI*d*d,f=-e.invI*u*c-n.invI*m*d,M=e.invM+n.invM+e.invI*u*u+n.invI*m*m,S=v*M-f*f;if(Math.abs(S)<1e-12)return;let D=-(M*P-f*$)/S,C=-(v*$-f*P)/S;e.vx-=D*e.invM,e.vy-=C*e.invM,e.w-=(u*C-c*D)*e.invI,n.vx+=D*n.invM,n.vy+=C*n.invM,n.w+=(m*C-d*D)*n.invI}var Ca=.5,Ta=.2,Ra=40,Pa=64,Da=8,Ia=.5,Mo=100;function Co(t,e){return t.invM===0&&e.invM===0&&t.kind!=="kinematic"&&e.kind!=="kinematic"&&!t.sensor&&!e.sensor?!1:(t.mask&e.layer)!==0&&(e.mask&t.layer)!==0}function Ea(t,e){let n=t.bodies,r=[];if(e<=0)return r;for(let v=0;v<n.length;v++){let f=n[v];if(f.kind!=="dynamic"||f.sleeping){f.fx=0,f.fy=0,f.torque=0;continue}f.vx+=(t.gravityX*f.gravityScale+f.fx*f.invM)*e,f.vy+=(t.gravityY*f.gravityScale+f.fy*f.invM)*e,f.w+=f.torque*f.invI*e;let M=1/(1+f.linDamp*e);f.vx*=M,f.vy*=M,f.w*=1/(1+f.angDamp*e),f.fx=0,f.fy=0,f.torque=0}let o=new Rt(t.cellSize),i=new Map;for(let v=0;v<n.length;v++)o.insert(n[v],nn(n[v])),i.set(n[v],v);let s=[],a=new Set,l=new Set;for(let v of t.joints){let f=Math.min(v.a,v.b),M=Math.max(v.a,v.b);l.add(f*1048576+M)}for(let v=0;v<n.length;v++){let f=n[v],M=o.query(nn(f));for(let S of M){if(S.id<=f.id)continue;let D=f.id*1048576+S.id;if(a.has(D)||(a.add(D),l.has(D))||!Co(f,S))continue;let C=!f.sleeping&&f.kind!=="static",y=!S.sleeping&&S.kind!=="static";if(!C&&!y)continue;let T=Hn(f,S);if(!T)continue;let E=(Y,ne)=>{Y.sleeping&&(ne.vx*ne.vx+ne.vy*ne.vy>Mo||ne.kind==="kinematic")&&ye(Y)};if(E(f,S),E(S,f),f.sensor||S.sensor){r.push({a:f.id,b:S.id,px:T.points[0].px,py:T.points[0].py,nx:T.nx,ny:T.ny,impulse:0,sensor:!0});continue}let O=[],F=-T.ny,J=T.nx;for(let Y of T.points){let ne=Y.px-f.x,Z=Y.py-f.y,ae=Y.px-S.x,I=Y.py-S.y,z=ne*T.ny-Z*T.nx,B=ae*T.ny-I*T.nx,W=f.invM+S.invM+f.invI*z*z+S.invI*B*B,V=ne*J-Z*F,re=ae*J-I*F,oe=f.invM+S.invM+f.invI*V*V+S.invI*re*re,te=S.vx-S.w*I-f.vx+f.w*Z,se=S.vy+S.w*ae-f.vy-f.w*ne,me=te*T.nx+se*T.ny,xe=Math.max(f.restitution,S.restitution),ze=`${f.id}:${S.id}:${Y.feature}`,Ce=t.warm[ze],ss={rax:ne,ray:Z,rbx:ae,rby:I,pen:Y.pen,massN:W>1e-12?1/W:0,massT:oe>1e-12?1/oe:0,restBias:me<-Ra?-xe*me:0,posBias:Ta/e*Math.max(0,Y.pen-Ca),pn:Ce?Ce[0]:0,pt:Ce?Ce[1]:0,pb:0,key:ze};O.push(ss)}s.push({m:T,ia:v,ib:i.get(S),points:O,friction:Math.sqrt(f.friction*S.friction)})}}for(let v of s){let{a:f,b:M,nx:S,ny:D}=v.m,C=-D,y=S;for(let T of v.points){if(T.pn===0&&T.pt===0)continue;let E=S*T.pn+C*T.pt,O=D*T.pn+y*T.pt;f.vx-=E*f.invM,f.vy-=O*f.invM,f.w-=(T.rax*O-T.ray*E)*f.invI,M.vx+=E*M.invM,M.vy+=O*M.invM,M.w+=(T.rbx*O-T.rby*E)*M.invI}}s.sort((v,f)=>{let M=v.m.a.invM===0||v.m.b.invM===0?0:1,S=f.m.a.invM===0||f.m.b.invM===0?0:1;if(M!==S)return M-S;let D=Math.max(v.m.a.y,v.m.b.y),C=Math.max(f.m.a.y,f.m.b.y);return D!==C?C-D:v.m.a.id!==f.m.a.id?v.m.a.id-f.m.a.id:v.m.b.id-f.m.b.id});let u=new Float64Array(n.length),c=new Float64Array(n.length),m=new Float64Array(n.length),d=t.joints.map(()=>({motorImpulse:0}));for(let v=0;v<t.iterations;v++){for(let f=0;f<t.joints.length;f++){let M=t.joints[f],S=ge(t,M.a),D=ge(t,M.b);!S||!D||S.sleeping&&D.sleeping||(S.sleeping&&ye(S),D.sleeping&&ye(D),_n(M,S,D,e,d[f]))}for(let f of s){let{a:M,b:S,nx:D,ny:C}=f.m,{ia:y,ib:T}=f,E=-C,O=D;for(let F of f.points){let J=S.vx-S.w*F.rby-M.vx+M.w*F.ray,Y=S.vy+S.w*F.rbx-M.vy-M.w*F.rax,ne=J*D+Y*C,Z=F.massN*(F.restBias-ne),ae=F.pn;F.pn=Math.max(ae+Z,0),Z=F.pn-ae;let I=D*Z,z=C*Z;M.vx-=I*M.invM,M.vy-=z*M.invM,M.w-=(F.rax*z-F.ray*I)*M.invI,S.vx+=I*S.invM,S.vy+=z*S.invM,S.w+=(F.rbx*z-F.rby*I)*S.invI,J=S.vx-S.w*F.rby-M.vx+M.w*F.ray,Y=S.vy+S.w*F.rbx-M.vy-M.w*F.rax;let B=J*E+Y*O,W=F.massT*-B,V=f.friction*F.pn,re=F.pt;if(F.pt=Math.min(Math.max(re+W,-V),V),W=F.pt-re,I=E*W,z=O*W,M.vx-=I*M.invM,M.vy-=z*M.invM,M.w-=(F.rax*z-F.ray*I)*M.invI,S.vx+=I*S.invM,S.vy+=z*S.invM,S.w+=(F.rbx*z-F.rby*I)*S.invI,F.posBias>0){let oe=(u[T]-m[T]*F.rby-u[y]+m[y]*F.ray)*D+(c[T]+m[T]*F.rbx-c[y]-m[y]*F.rax)*C,te=F.massN*(F.posBias-oe),se=F.pb;F.pb=Math.max(se+te,0),te=F.pb-se;let me=D*te,xe=C*te;u[y]-=me*M.invM,c[y]-=xe*M.invM,u[T]+=me*S.invM,c[T]+=xe*S.invM}}}}let p=[],h=[];for(let v=0;v<n.length;v++){let f=n[v];p.push(f.x),h.push(f.y),!(f.invM===0&&f.kind!=="kinematic")&&(f.sleeping||(f.x+=(f.vx+u[v])*e,f.y+=(f.vy+c[v])*e,f.a+=(f.w+m[v])*e))}for(let v=0;v<n.length;v++){let f=n[v];if(!f.bullet||f.shape.kind!=="circle"||f.sleeping)continue;let M=f.x-p[v],S=f.y-h[v];if(M*M+S*S<1)continue;let D=1;for(let C=0;C<n.length;C++){let y=n[C];if(y===f||y.bullet||y.sensor||!Co(f,y))continue;let T=Fa(p[v],h[v],M,S,f.shape.r,y);T>=0&&T<D&&(D=T)}if(D<1){let C=Q(M,S)||1;f.x=p[v]+M*D+M/C*.4,f.y=h[v]+S*D+S/C*.4}}let g=new Set,x=[];for(let v=0;v<n.length;v++)x.push(v);let k=v=>{for(;x[v]!==v;)x[v]=x[x[v]],v=x[v];return v},w=(v,f)=>{x[k(v)]=k(f)};for(let v of s)g.add(v.m.a.id),g.add(v.m.b.id),v.m.a.kind==="dynamic"&&v.m.b.kind==="dynamic"&&w(v.ia,v.ib);for(let v of t.joints){g.add(v.a),g.add(v.b);let f=ge(t,v.a),M=ge(t,v.b);f?.kind==="dynamic"&&M?.kind==="dynamic"&&w(i.get(f),i.get(M))}for(let v=0;v<n.length;v++){let f=n[v];if(f.kind!=="dynamic")continue;let M=f.vx*f.vx+f.vy*f.vy;if(f.sleeping){M>Mo&&ye(f);continue}if(!f.canSleep||!g.has(f.id)){f.sleepTime=0;continue}f.sleepTime=M<Pa&&Math.abs(f.w)*f.sleepR<Da?f.sleepTime+e:0}let P=new Map;for(let v=0;v<n.length;v++){let f=n[v];if(f.kind!=="dynamic"||f.sleeping)continue;let M=k(v),S=!f.canSleep||!g.has(f.id)?-1:f.sleepTime,D=P.get(M);P.set(M,D===void 0?S:Math.min(D,S))}for(let v=0;v<n.length;v++){let f=n[v];f.kind!=="dynamic"||f.sleeping||(P.get(k(v))??-1)>=Ia&&(f.sleeping=!0,f.vx=0,f.vy=0,f.w=0)}let $={};for(let v of s){let f=0;for(let S of v.points)f+=S.pn,(S.pn!==0||S.pt!==0)&&($[S.key]=[S.pn,S.pt]);let M=v.m.points[0];r.push({a:v.m.a.id,b:v.m.b.id,px:M.px,py:M.py,nx:v.m.nx,ny:v.m.ny,impulse:f,sensor:!1})}return t.warm=$,r}function Fa(t,e,n,r,o,i){if(i.shape.kind==="circle")return To(t,e,n,r,i.x,i.y,o+i.shape.r);let s=we(i),a=s.length/2,l=-1;for(let u=0;u<a;u++){let c=(u+1)%a,m=s[u*2],d=s[u*2+1],p=s[c*2],h=s[c*2+1],g=p-m,x=h-d,k=Q(g,x)||1,w=x/k,P=-g/k,$=(t-m)*w+(e-d)*P-o;if(n*w+r*P<0&&$>.5){let f=Na(t,e,n,r,m+w*o,d+P*o,p+w*o,h+P*o);f>=0&&(l<0||f<l)&&(l=f)}let v=To(t,e,n,r,m,d,o);v>=0&&(l<0||v<l)&&(l=v)}return l}function To(t,e,n,r,o,i,s){let a=t-o,l=e-i,u=n*n+r*r;if(u<1e-12)return-1;let c=2*(a*n+l*r);if(a*a+l*l<(s+.5)*(s+.5))return-1;let m=a*a+l*l-s*s,d=c*c-4*u*m;if(d<0)return-1;let p=(-c-Math.sqrt(d))/(2*u);return p>=0&&p<=1?p:-1}function Na(t,e,n,r,o,i,s,a){let l=s-o,u=a-i,c=n*u-r*l;if(Math.abs(c)<1e-12)return-1;let m=((o-t)*u-(i-e)*l)/c,d=((o-t)*r-(i-e)*n)/c;return m>=0&&m<=1&&d>=0&&d<=1?m:-1}function Ro(t,e,n){if(t.shape.kind==="circle"){let i=e-t.x,s=n-t.y;return i*i+s*s<=t.shape.r*t.shape.r}let r=we(t),o=r.length/2;for(let i=0;i<o;i++){let s=(i+1)%o,a=r[s*2]-r[i*2],l=r[s*2+1]-r[i*2+1];if((e-r[i*2])*l-(n-r[i*2+1])*a>0)return!1}return!0}function $a(t,e,n,r=65535){let o;for(let i of t.bodies)(i.layer&r)!==0&&Ro(i,e,n)&&(o=i);return o}function Aa(t,e,n,r,o,i,s){let a=t-o,l=e-i,u=n*n+r*r;if(u<1e-12)return-1;let c=2*(a*n+l*r),m=a*a+l*l-s*s,d=c*c-4*u*m;if(d<0)return-1;let p=(-c-Math.sqrt(d))/(2*u);return p>=0&&p<=1?p:-1}function La(t,e,n,r,o,i=65535){let s=r-e,a=o-n,l=null;for(let u of t.bodies){if((u.layer&i)===0)continue;if(u.shape.kind==="circle"){let d=Aa(e,n,s,a,u.x,u.y,u.shape.r);if(d>=0&&(!l||d<l.t)){let p=e+s*d,h=n+a*d,g=Q(p-u.x,h-u.y)||1;l={id:u.id,t:d,x:p,y:h,nx:(p-u.x)/g,ny:(h-u.y)/g}}continue}let c=we(u),m=c.length/2;for(let d=0;d<m;d++){let p=(d+1)%m,h=c[d*2],g=c[d*2+1],x=c[p*2]-h,k=c[p*2+1]-g,w=s*k-a*x;if(Math.abs(w)<1e-12)continue;let P=((h-e)*k-(g-n)*x)/w,$=((h-e)*a-(g-n)*s)/w;if(!(P<0||P>1||$<0||$>1)&&(!l||P<l.t)){let v=Q(x,k)||1;l={id:u.id,t:P,x:e+s*P,y:n+a*P,nx:k/v,ny:-x/v}}}}return l}function Pt(t){return t.map((e,n)=>[e,n]).sort((e,n)=>e[0].z-n[0].z||e[1]-n[1]).map(([e])=>e)}var ke=t=>Number.isInteger(t)?String(t):(Math.round(t*1e3)/1e3).toString();function Po(t){let e=Math.max(1,t.length-1);return t.map((n,r)=>typeof n=="string"?{offset:r/e,color:n}:n)}function za(t,e=90){let n=e*Math.PI/180,r=X(n)*.5,o=_(n)*.5;return{type:"linear",x1:.5-r,y1:.5-o,x2:.5+r,y2:.5+o,stops:Po(t)}}function Wa(t,e={}){return{type:"radial",cx:e.cx??.5,cy:e.cy??.5,r:e.r??.5,stops:Po(t)}}function Ba(t,e){return{color:t,blur:e}}function Oa(t,e,n=0,r=0){return{color:t,blur:e,dx:n,dy:r}}function Ga(t){return`<stop offset="${ke(t.offset)}" stop-color="${t.color}"/>`}function Jn(t,e){let n=t.stops.map(Ga).join("");return t.type==="linear"?`<linearGradient id="${e}" x1="${ke(t.x1)}" y1="${ke(t.y1)}" x2="${ke(t.x2)}" y2="${ke(t.y2)}">${n}</linearGradient>`:`<radialGradient id="${e}" cx="${ke(t.cx)}" cy="${ke(t.cy)}" r="${ke(t.r)}">${n}</radialGradient>`}function Un(t,e){return`<filter id="${e}" x="-60%" y="-60%" width="220%" height="220%"><feDropShadow dx="${ke(t.dx??0)}" dy="${ke(t.dy??0)}" stdDeviation="${ke(t.blur/2)}" flood-color="${t.color}"/></filter>`}function Kn(t){switch(t.kind){case"rect":return{x:t.x,y:t.y,w:t.w,h:t.h};case"circle":return{x:t.cx-t.radius,y:t.cy-t.radius,w:t.radius*2,h:t.radius*2};case"poly":{if(t.points.length<2)return null;let e=t.points[0],n=t.points[0],r=t.points[1],o=t.points[1];for(let i=0;i<t.points.length;i+=2)e=Math.min(e,t.points[i]),n=Math.max(n,t.points[i]),r=Math.min(r,t.points[i+1]),o=Math.max(o,t.points[i+1]);return{x:e,y:r,w:n-e,h:o-r}}default:return null}}function Yn(t,e,n){let r=s=>n.x+s*n.w,o=s=>n.y+s*n.h,i;if(e.type==="linear")i=t.createLinearGradient(r(e.x1),o(e.y1),r(e.x2),o(e.y2));else{let s=e.r*Math.max(n.w,n.h);i=t.createRadialGradient(r(e.cx),o(e.cy),0,r(e.cx),o(e.cy),s)}for(let s of e.stops)i.addColorStop(Math.max(0,Math.min(1,s.offset)),s.color);return i}function Dt(t,e,n,r,o){let i=Math.min(t.width/e,t.height/n)||1,s=(t.width-e*i)/2,a=(t.height-n*i)/2;return{x:(r-t.left-s)/i,y:(o-t.top-a)/i}}var K=t=>Number.isInteger(t)?String(t):(Math.round(t*1e3)/1e3).toString();function Va(t){return`matrix(${K(t.a)} ${K(t.b)} ${K(t.c)} ${K(t.d)} ${K(t.e)} ${K(t.f)})`}function qa(t,e,n){let r=[];return r.push(`fill="${e??t.fill??"none"}"`),t.stroke&&(r.push(`stroke="${t.stroke}"`),r.push(`stroke-width="${K(t.strokeWidth??1)}"`),t.round&&r.push('stroke-linejoin="round" stroke-linecap="round"')),t.opacity!==void 0&&t.opacity!==1&&r.push(`opacity="${K(t.opacity)}"`),n&&r.push(`filter="url(#${n})"`),r.join(" ")}function ja(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function Ha(t,e,n){let r=`transform="${Va(t.transform)}"`,o,i;if(t.gradient){let a=`${n}g`;e.push(Jn(t.gradient,a)),o=`url(#${a})`}t.shadow&&(i=`${n}s`,e.push(Un(t.shadow,i)));let s=qa(t,o,i);switch(t.kind){case"rect":return`<rect x="${K(t.x)}" y="${K(t.y)}" width="${K(t.w)}" height="${K(t.h)}"${t.r?` rx="${K(t.r)}"`:""} ${r} ${s}/>`;case"circle":return`<circle cx="${K(t.cx)}" cy="${K(t.cy)}" r="${K(t.radius)}" ${r} ${s}/>`;case"poly":{let a=[];for(let u=0;u<t.points.length;u+=2)a.push(`${K(t.points[u])},${K(t.points[u+1])}`);return`<${t.closed?"polygon":"polyline"} points="${a.join(" ")}" ${r} ${s}/>`}case"path":return`<path d="${t.d}" ${r} ${s}/>`;case"text":{let a=t.align==="center"?"middle":t.align==="right"?"end":"start",l=t.font?` font-family="${t.font}"`:"",u=t.weight?` font-weight="${t.weight}"`:"",c=o??t.fill??"#000",m=i?` filter="url(#${i})"`:"",d=t.stroke?` stroke="${t.stroke}" stroke-width="${K(t.strokeWidth??1)}" paint-order="stroke"${t.round?' stroke-linejoin="round"':""}`:"",p=t.opacity!==void 0&&t.opacity!==1?` opacity="${K(t.opacity)}"`:"";return`<text x="${K(t.x)}" y="${K(t.y)}" font-size="${K(t.size)}" text-anchor="${a}" dominant-baseline="middle"${l}${u} fill="${c}"${d}${p}${m} ${r}>${ja(t.text)}</text>`}case"image":{let a=i?` filter="url(#${i})"`:"";return`<image href="${t.href}" x="${K(t.x)}" y="${K(t.y)}" width="${K(t.w)}" height="${K(t.h)}" ${r}${t.opacity!==void 0&&t.opacity!==1?` opacity="${K(t.opacity)}"`:""}${a}/>`}}}function qe(t,e="h"){let n=[],r=Pt(t).map((o,i)=>Ha(o,n,`${e}${i}`)).join("");return(n.length?`<defs>${n.join("")}</defs>`:"")+r}function It(t,e,n,r="#ffffff"){return`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${e} ${n}" width="${e}" height="${n}"><rect x="0" y="0" width="${e}" height="${n}" fill="${r}"/>`+qe(t)+"</svg>"}var Xn="http://www.w3.org/2000/svg",je=class{width;height;background;svg;bg;layer;constructor(e){this.width=e.width,this.height=e.height,this.background=e.background??"#ffffff",this.svg=document.createElementNS(Xn,"svg"),this.svg.setAttribute("viewBox",`0 0 ${this.width} ${this.height}`),this.svg.setAttribute("preserveAspectRatio","xMidYMid meet"),this.svg.style.width="100%",this.svg.style.height="100%",this.svg.style.display="block",this.bg=document.createElementNS(Xn,"rect"),this.bg.setAttribute("x","0"),this.bg.setAttribute("y","0"),this.bg.setAttribute("width",String(this.width)),this.bg.setAttribute("height",String(this.height)),this.bg.setAttribute("fill",this.background),this.svg.appendChild(this.bg),this.layer=document.createElementNS(Xn,"g"),this.svg.appendChild(this.layer)}mount(e){e.appendChild(this.svg)}draw(e){this.layer.innerHTML=qe(e)}setBackground(e){this.background=e,this.bg.setAttribute("fill",e)}get element(){return this.svg}toDesign(e,n){return Dt(this.svg.getBoundingClientRect(),this.width,this.height,e,n)}dispose(){this.svg.remove()}};var He=class{width;height;background;canvas;ctx;dpr=1;constructor(e){this.width=e.width,this.height=e.height,this.background=e.background??"#ffffff",this.canvas=document.createElement("canvas"),this.canvas.style.width="100%",this.canvas.style.height="100%",this.canvas.style.objectFit="contain",this.canvas.style.display="block";let n=this.canvas.getContext("2d");if(!n)throw new Error("hayao: 2D canvas context unavailable");this.ctx=n,this.resize()}mount(e){e.appendChild(this.canvas),this.resize()}resize(){this.dpr=Math.min(3,globalThis.devicePixelRatio||1),this.canvas.width=Math.round(this.width*this.dpr),this.canvas.height=Math.round(this.height*this.dpr)}draw(e){let n=this.ctx;n.setTransform(this.dpr,0,0,this.dpr,0,0),n.fillStyle=this.background,n.fillRect(0,0,this.width,this.height);for(let r of Pt(e)){n.save();let o=r.transform;n.transform(o.a,o.b,o.c,o.d,o.e,o.f),n.globalAlpha=r.opacity??1;let i=r.shadow;i&&(n.shadowColor=i.color,n.shadowBlur=i.blur,n.shadowOffsetX=i.dx??0,n.shadowOffsetY=i.dy??0),this.paint(n,r),n.restore()}}fillFor(e,n){let r=n;if(r.gradient){let o=Kn(n);if(o&&o.w>0&&o.h>0)return Yn(e,r.gradient,o);let i=r.gradient.stops;return i.length?i[i.length-1].color:r.fill}return r.fill}stroke(e,n){let r=this.fillFor(e,n);r&&r!=="none"&&(e.fillStyle=r,e.fill()),n.stroke&&(e.strokeStyle=n.stroke,e.lineWidth=n.strokeWidth??1,n.round&&(e.lineJoin="round",e.lineCap="round"),e.stroke())}paint(e,n){switch(n.kind){case"rect":e.beginPath(),n.r?this.roundRect(e,n.x,n.y,n.w,n.h,n.r):e.rect(n.x,n.y,n.w,n.h),this.stroke(e,n);break;case"circle":e.beginPath(),e.arc(n.cx,n.cy,n.radius,0,Math.PI*2),this.stroke(e,n);break;case"poly":e.beginPath();for(let r=0;r<n.points.length;r+=2)r===0?e.moveTo(n.points[r],n.points[r+1]):e.lineTo(n.points[r],n.points[r+1]);n.closed&&e.closePath(),this.stroke(e,n);break;case"path":{let r=new Path2D(n.d),o=this.fillFor(e,n);o&&o!=="none"&&(e.fillStyle=o,e.fill(r)),n.stroke&&(e.strokeStyle=n.stroke,e.lineWidth=n.strokeWidth??1,n.round&&(e.lineJoin="round",e.lineCap="round"),e.stroke(r))}break;case"text":e.font=`${n.weight??400} ${n.size}px ${n.font??"sans-serif"}`,e.textAlign=n.align??"left",e.textBaseline="middle",n.stroke&&(e.strokeStyle=n.stroke,e.lineWidth=n.strokeWidth??1,e.lineJoin="round",e.lineCap="round",e.strokeText(n.text,n.x,n.y)),e.fillStyle=n.fill??"#000",e.fillText(n.text,n.x,n.y);break;case"image":break}}roundRect(e,n,r,o,i,s){let a=Math.min(s,o/2,i/2);e.moveTo(n+a,r),e.arcTo(n+o,r,n+o,r+i,a),e.arcTo(n+o,r+i,n,r+i,a),e.arcTo(n,r+i,n,r,a),e.arcTo(n,r,n+o,r,a),e.closePath()}get element(){return this.canvas}toDesign(e,n){return Dt(this.canvas.getBoundingClientRect(),this.width,this.height,e,n)}dispose(){this.canvas.remove()}};var Qn=class{width;height;background;last=[];frameCount=0;constructor(e){this.width=e.width,this.height=e.height,this.background=e.background??"#ffffff"}draw(e){this.last=e,this.frameCount++}get commands(){return this.last}count(e){return this.last.filter(n=>n.kind===e).length}toSVGString(){return It(this.last,this.width,this.height,this.background)}};function _a(t,e,n=0,r=le){let o=Math.max(0,Math.min(e.border,t.w/2,t.h/2)),i=e.fill??"#fbf6ea",s=e.edge??i,a=e.corner??s,l=[],u=t.x,c=t.x+o,m=t.x+t.w-o,d=t.y,p=t.y+o,h=t.y+t.h-o,g=t.w-2*o,x=t.h-2*o,k=(P,$,v,f,M,S)=>{v<=0||f<=0||l.push({kind:"rect",x:P,y:$,w:v,h:f,r:S,fill:M,transform:r,z:n})};k(c,p,g,x,i),k(c,d,g,o,e.highlight??s),k(c,h,g,o,e.shadow??s),k(u,p,o,x,e.highlight??s),k(m,p,o,x,e.shadow??s);let w=e.radius;return k(u,d,o,o,a,w),k(m,d,o,o,a,w),k(u,h,o,o,a,w),k(m,h,o,o,a,w),e.stroke&&l.push({kind:"rect",x:t.x,y:t.y,w:t.w,h:t.h,r:e.radius,fill:"none",stroke:e.stroke,strokeWidth:e.strokeWidth??2,transform:r,z:n+.001}),l}var Ja={parchment:()=>({border:10,fill:"#fbf6ea",edge:"#efe4c8",corner:"#e2d3a8",highlight:"#fdfaf0",shadow:"#d9c79c",stroke:"#b8a06a",strokeWidth:2,radius:4}),slate:()=>({border:8,fill:"#2c3040",edge:"#363c4f",corner:"#454c63",highlight:"#4a5268",shadow:"#20242f",stroke:"#151821",strokeWidth:2,radius:3})};var L={gofun:"#f7f1e2",washi:"#efe7d3",kinu:"#e4d8bd",line:"#d8cbac",kinako:"#b9a882",stone:"#6c6252",sumiSoft:"#494133",sumi:"#23201a",kuro:"#181820",yohaku:"#12121a",darkLine:"#2c2c36",shuDeep:"#b23a24",shu:"#d9583c",kakiDeep:"#bf6a1c",kaki:"#e79a49",koDeep:"#94741d",ko:"#e3c054",matsuDeep:"#4a7a3a",matsu:"#8bad52",asagiDeep:"#2c7a90",asagi:"#57bad2",aiDeep:"#2b4257",ai:"#5a86ad",fujiDeep:"#63548c",fuji:"#a091cf",sakuDeep:"#b0506e",saku:"#e097ac"},Io={name:"meadow",bg:L.washi,ink:L.sumi,inkSoft:L.sumiSoft,line:L.line,accent:L.shuDeep,accent2:L.aiDeep,good:L.matsuDeep,warn:L.kakiDeep,ramp:[L.shuDeep,L.kakiDeep,L.koDeep,L.matsuDeep,L.asagiDeep,L.aiDeep,L.fujiDeep,L.sakuDeep],swatches:L},Eo={name:"dusk",bg:L.kuro,ink:L.gofun,inkSoft:L.kinako,line:L.darkLine,accent:L.shu,accent2:L.asagi,good:L.matsu,warn:L.ko,ramp:[L.shu,L.kaki,L.ko,L.matsu,L.asagi,L.ai,L.fuji,L.saku],swatches:L},Fo={name:"paper",bg:L.gofun,ink:L.sumi,inkSoft:L.stone,line:L.kinu,accent:L.sakuDeep,accent2:L.asagiDeep,good:L.matsuDeep,warn:L.kakiDeep,ramp:[L.sakuDeep,L.kakiDeep,L.koDeep,L.matsuDeep,L.asagiDeep,L.aiDeep,L.fujiDeep,L.shuDeep],swatches:L},Ua={meadow:Io,dusk:Eo,paper:Fo};function Ka(t,e,n){let r=rt(t),o=rt(e),i=Math.round(r[0]+(o[0]-r[0])*n),s=Math.round(r[1]+(o[1]-r[1])*n),a=Math.round(r[2]+(o[2]-r[2])*n);return Et(i,s,a)}function Ya(t,e){let[n,r,o]=rt(t);return`rgba(${n}, ${r}, ${o}, ${e})`}function rt(t){let e=t.replace("#","");e.length===3&&(e=e.split("").map(r=>r+r).join(""));let n=parseInt(e,16);return[n>>16&255,n>>8&255,n&255]}function Et(t,e,n){return"#"+[t,e,n].map(r=>Math.max(0,Math.min(255,Math.round(r))).toString(16).padStart(2,"0")).join("")}var No=t=>(t%360+360)%360,Ft=t=>t<0?0:t>1?1:t;function $o(t,e,n){if(t=No(t)/360,e=Ft(e),n=Ft(n),e===0){let s=n*255;return Et(s,s,s)}let r=n<.5?n*(1+e):n+e-n*e,o=2*n-r,i=s=>(s=s<0?s+1:s>1?s-1:s,s<1/6?o+(r-o)*6*s:s<1/2?r:s<2/3?o+(r-o)*(2/3-s)*6:o);return Et(i(t+1/3)*255,i(t)*255,i(t-1/3)*255)}function Xa(t,e,n){t=No(t)/60,e=Ft(e),n=Ft(n);let r=n*e,o=r*(1-Math.abs(t%2-1)),i=n-r,s=0,a=0,l=0;return t<1?[s,a,l]=[r,o,0]:t<2?[s,a,l]=[o,r,0]:t<3?[s,a,l]=[0,r,o]:t<4?[s,a,l]=[0,o,r]:t<5?[s,a,l]=[o,0,r]:[s,a,l]=[r,0,o],Et((s+i)*255,(a+i)*255,(l+i)*255)}function Ao(t){let[e,n,r]=rt(t),o=e/255,i=n/255,s=r/255,a=Math.max(o,i,s),l=Math.min(o,i,s),u=(a+l)/2,c=a-l;if(c===0)return{h:0,s:0,l:u};let m=u>.5?c/(2-a-l):c/(a+l),d;return a===o?d=(i-s)/c+(i<s?6:0):a===i?d=(s-o)/c+2:d=(o-i)/c+4,{h:d*60,s:m,l:u}}function Qa(t,e,n={}){let r=Ao(e),o=n.hue??0,i=n.sat??0,s=n.light??0;return $o(r.h+t.range(-o,o),r.s+t.range(-i,i),r.l+t.range(-s,s))}var Do=t=>t<=.04045?t/12.92:Re((t+.055)/1.055,2.4),Za=t=>t<=.0031308?t*12.92:1.055*Re(t,1/2.4)-.055;function Lo(t,e,n){let r=rt(t),o=rt(e),i=s=>{let a=Do(r[s]/255),l=Do(o[s]/255);return Za(a+(l-a)*n)*255};return Et(i(0),i(1),i(2))}function Zn(t,e){if(t.length===0)return"#000000";if(t.length===1)return t[0];let r=Ft(e)*(t.length-1),o=Math.min(t.length-2,Math.floor(r));return Lo(t[o],t[o+1],r-o)}function el(t,e){return e<=0?[]:e===1?[Zn(t,0)]:Array.from({length:e},(n,r)=>Zn(t,r/(e-1)))}function tl(t,e,n=0){let r=[];for(let o=0;o<t;o++){let i=n+o/t*ie;r.push(X(i)*e,_(i)*e)}return r}function nl(t,e,n,r=-Math.PI/2){let o=[];for(let i=0;i<t*2;i++){let s=i%2===0?e:n,a=r+i/(t*2)*ie;o.push(X(a)*s,_(a)*s)}return o}function rl(t,e,n=.25,r=7){let o=[];for(let i=0;i<r;i++){let s=i/r*ie,a=e*(1-n+t.float()*n*2);o.push({x:X(s)*a,y:_(s)*a})}return zo(o)}function zo(t,e=1){let n=t.length;if(n<3)return"";let r=s=>t[(s%n+n)%n],o=s=>Math.round(s*100)/100,i=`M ${o(r(0).x)} ${o(r(0).y)}`;for(let s=0;s<n;s++){let a=r(s-1),l=r(s),u=r(s+1),c=r(s+2),m=l.x+(u.x-a.x)/6*e,d=l.y+(u.y-a.y)/6*e,p=u.x-(c.x-l.x)/6*e,h=u.y-(c.y-l.y)/6*e;i+=` C ${o(m)} ${o(d)}, ${o(p)} ${o(h)}, ${o(u.x)} ${o(u.y)}`}return i+" Z"}function ol(t,e=1){let n=t.length;if(n<2)return"";let r=i=>Math.round(i*100)/100,o=`M ${r(t[0].x)} ${r(t[0].y)}`;for(let i=0;i<n-1;i++){let s=t[Math.max(0,i-1)],a=t[i],l=t[i+1],u=t[Math.min(n-1,i+2)],c=a.x+(l.x-s.x)/6*e,m=a.y+(l.y-s.y)/6*e,d=l.x-(u.x-a.x)/6*e,p=l.y-(u.y-a.y)/6*e;o+=` C ${r(c)} ${r(m)}, ${r(d)} ${r(p)}, ${r(l.x)} ${r(l.y)}`}return o}var ot=class t{width;height;data;constructor(e,n,r){this.width=e,this.height=n,this.data=r??new Uint8Array(e*n)}get(e,n){return e<0||n<0||e>=this.width||n>=this.height?0:this.data[n*this.width+e]}set(e,n,r){e<0||n<0||e>=this.width||n>=this.height||(this.data[n*this.width+e]=r)}static fromRows(e,n){let r=e.length,o=e.reduce((s,a)=>Math.max(s,a.length),0),i=new t(o,r);for(let s=0;s<r;s++){let a=e[s];for(let l=0;l<a.length;l++)i.data[s*o+l]=n[a[l]]??0}return i}remap(e){let n=new Uint8Array(this.data.length);for(let r=0;r<this.data.length;r++)n[r]=e[this.data[r]]??0;return new t(this.width,this.height,n)}};function Wo(t){if(typeof t=="bigint")return t;let e=t.trim();return e.startsWith("0x")||e.startsWith("0b")||e.startsWith("0o")?BigInt(e):BigInt("0x"+e)}function il(t,e,n){let r=Wo(t),o=e*n,i=new ot(e,n);for(let s=0;s<o;s++)i.data[s]=Number(r>>BigInt(o-1-s)&1n);return i}function sl(t,e,n){let r=Wo(t),o=e*n,i=new ot(e,n);for(let s=0;s<o;s++){let a=BigInt((o-1-s)*2);i.data[s]=Number(r>>a&3n)}return i}function al(t,e,n){let r=new ot(e,n),o=0;for(let i=0;i+1<t.length;i+=2){let s=t[i],a=t[i+1];for(let l=0;l<s&&o<r.data.length;l++)r.data[o++]=a}return r}function ll(t){let e=[],n=t.data;for(let r=0;r<n.length;){let o=n[r],i=1;for(;r+i<n.length&&n[r+i]===o;)i++;e.push(i,o),r+=i}return e}function Bo(t,e,n={}){let r=n.cell??1,o=n.x??0,i=n.y??0,s=n.z??0,a=n.transform??le,l=[];for(let u=0;u<t.height;u++){let c=0;for(;c<t.width;){let m=t.get(c,u),d=e[m];if(d==null){c++;continue}let p=1;for(;c+p<t.width&&t.get(c+p,u)===m;)p++;l.push({kind:"rect",x:o+c*r,y:i+u*r,w:p*r,h:r,transform:a,z:s,fill:d}),c+=p}}return l}var er=class extends q{type="TextureSprite";buffer;palette;cell;center;constructor(e){super(e),this.buffer=e.buffer,this.palette=e.palette,this.cell=e.cell??1,this.center=e.center??!0,this.cosmetic=!0}draw(e,n){let r=this.cell,o=this.center?-(this.buffer.width*r)/2:0,i=this.center?-(this.buffer.height*r)/2:0;for(let s of Bo(this.buffer,this.palette,{cell:r,x:o,y:i,z:this.z,transform:n}))e.push(s)}};var ul={A:[".#.","#.#","###","#.#","#.#"],B:["##.","#.#","##.","#.#","##."],C:[".##","#..","#..","#..",".##"],D:["##.","#.#","#.#","#.#","##."],E:["###","#..","##.","#..","###"],F:["###","#..","##.","#..","#.."],G:[".##","#..","#.#","#.#",".##"],H:["#.#","#.#","###","#.#","#.#"],I:["#","#","#","#","#"],J:["..#","..#","..#","#.#",".#."],K:["#.#","##.","#..","##.","#.#"],L:["#..","#..","#..","#..","###"],M:["#...#","##.##","#.#.#","#...#","#...#"],N:["#...#","##..#","#.#.#","#..##","#...#"],O:[".#.","#.#","#.#","#.#",".#."],P:["##.","#.#","##.","#..","#.."],Q:[".#.","#.#","#.#","#.#",".##"],R:["##.","#.#","##.","#.#","#.#"],S:[".##","#..",".#.","..#","##."],T:["###",".#.",".#.",".#.",".#."],U:["#.#","#.#","#.#","#.#","###"],V:["#.#","#.#","#.#","#.#",".#."],W:["#...#","#...#","#.#.#","##.##","#...#"],X:["#.#","#.#",".#.","#.#","#.#"],Y:["#.#","#.#",".#.",".#.",".#."],Z:["###","..#",".#.","#..","###"],0:[".#.","#.#","#.#","#.#",".#."],1:[".#.","##.",".#.",".#.","###"],2:["##.","..#",".#.","#..","###"],3:["##.","..#",".#.","..#","##."],4:["#.#","#.#","###","..#","..#"],5:["###","#..","##.","..#","##."],6:[".##","#..","##.","#.#",".#."],7:["###","..#",".#.",".#.",".#."],8:[".#.","#.#",".#.","#.#",".#."],9:[".#.","#.#",".##","..#","##."],".":[".",".",".",".","#"],",":["..","..","..",".#","#."],"!":["#","#","#",".","#"],"?":["##.","..#",".#.","...",".#."],":":[".","#",".","#","."],";":["..",".#","..",".#","#."],"-":["...","...","###","...","..."],"+":["...",".#.","###",".#.","..."],"=":["...","###","...","###","..."],"/":["..#","..#",".#.","#..","#.."],"'":["#","#",".",".","."],'"':["#.#","#.#","...","...","..."],"(":[".#","#.","#.","#.",".#"],")":["#.",".#",".#",".#","#."],"<":["..#",".#.","#..",".#.","..#"],">":["#..",".#.","..#",".#.","#.."],"%":["#.#","..#",".#.","#..","#.#"],"*":["...","#.#",".#.","#.#","..."],"#":["#.#","###","#.#","###","#.#"]},tr={height:5,tracking:1,spaceWidth:3,glyphs:ul};function Oo(t,e={}){let n=[],r=[],o=0,i=0;for(;o<t.length;){let s=t[o];if(s==="{"&&t[o+1]==="{"){n.push({ch:"{",color:r[r.length-1],i:i++}),o+=2;continue}if(s==="{"){let a=t.indexOf("}",o);if(a===-1){n.push({ch:s,color:r[r.length-1],i:i++}),o++;continue}let l=t.slice(o+1,a);l==="/"?r.pop():r.push(l[0]==="#"?l:e[l]??l),o=a+1;continue}n.push({ch:s,color:r[r.length-1],i:i++}),o++}return n}function Go(t,e){if(e===" "||e===`
|
|
2
|
-
|
|
3
|
-
`?i.push([]):i[i.length-1].push({...m,ch:Go(t,m.ch)});let s=[];for(let m of i){if(n.maxWidth===void 0){s.push(m);continue}let d=[],p=[],h=()=>{if(p.length===0)return;let g=d.length?t.spaceWidth+t.tracking:0;d.length&&it(t,d)+g+it(t,p)>n.maxWidth&&(s.push(d),d=[]),d.length&&d.push({ch:" ",i:-1}),d.push(...p),p=[]};for(let g of m)g.ch===" "?h():p.push(g);h(),s.push(d)}let a=[],l=0;for(let m of s)l=Math.max(l,it(t,m));let u=n.maxWidth??l,c=0;for(let m of s){let d=it(t,m),p=n.align==="center"?Math.floor((u-d)/2):n.align==="right"?u-d:0;for(let h of m){let g=Vo(t,h.ch);h.ch!==" "&&a.push({ch:h.ch,color:h.color,i:h.i,x:p,y:c,w:g}),p+=g+t.tracking}c+=t.height+r}return{glyphs:a,width:u,height:s.length*(t.height+r)-r,lines:s.length}}function jo(t,e,n){if(n<=0)return t;let r=Math.floor(e*n);return r<0?0:r>t?t:r}function Ho(t,e,n={}){let r=n.cell??2,o=n.x??0,i=n.y??0,s=n.z??0,a=n.transform??le,l=n.color??"#000",u=n.reveal,c=[];for(let m of e.glyphs){if(u!==void 0&&m.i>=u)continue;let d=t.glyphs[m.ch];if(!d)continue;let p=m.color??l;for(let h=0;h<d.length;h++){let g=d[h],x=0;for(;x<g.length;){if(g[x]!=="#"){x++;continue}let k=1;for(;x+k<g.length&&g[x+k]==="#";)k++;c.push({kind:"rect",x:o+(m.x+x)*r,y:i+(m.y+h)*r,w:k*r,h:r,transform:a,z:s,fill:p}),x+=k}}}return c}var nr=class extends q{type="BitmapText";text;font;cell;color;colorMap;maxWidth;lineSpacing;align;charsPerSec;center;startTime=0;constructor(e){super(e),this.text=e.text,this.font=e.font??tr,this.cell=e.cell??2,this.color=e.color??"#000",this.colorMap=e.colorMap??{},this.maxWidth=e.maxWidth,this.lineSpacing=e.lineSpacing??1,this.align=e.align??"left",this.charsPerSec=e.charsPerSec,this.center=e.center??!1,this.cosmetic=!0}onReady(){this.startTime=this.world?.time??0}restartReveal(){this.startTime=this.world?.time??0}buildLayout(){let e=Oo(this.text,this.colorMap);return qo(this.font,e,{maxWidth:this.maxWidth,lineSpacing:this.lineSpacing,align:this.align})}draw(e,n){let r=this.buildLayout(),o;if(this.charsPerSec!==void 0){let a=(this.world?.time??0)-this.startTime;o=jo(this.text.length,a,this.charsPerSec)}let i=this.center?-(r.width*this.cell)/2:0,s=this.center?-(r.height*this.cell)/2:0;for(let a of Ho(this.font,r,{cell:this.cell,x:i,y:s,z:this.z,color:this.color,transform:n,reveal:o}))e.push(a)}};function ml(t,e="#"){return t.map(n=>[...n].map(r=>e.includes(r)))}function Ee(t,e,n){return n>=0&&n<t.length&&e>=0&&e<t[n].length&&t[n][e]}var ee={N:1,E:2,S:4,W:8};function rr(t,e,n){return(Ee(t,e,n-1)?ee.N:0)|(Ee(t,e+1,n)?ee.E:0)|(Ee(t,e,n+1)?ee.S:0)|(Ee(t,e-1,n)?ee.W:0)}function dl(t,e,n){let r=0,o=[[0,-1],[1,-1],[1,0],[1,1],[0,1],[-1,1],[-1,0],[-1,-1]];for(let i=0;i<8;i++)Ee(t,e+o[i][0],n+o[i][1])&&(r|=1<<i);return r}var _e={Isolated:0,Cap:1,Straight:2,Bend:3,Tee:4,Cross:5};function pl(t){let e=0;return t&ee.N&&(e|=ee.E),t&ee.E&&(e|=ee.S),t&ee.S&&(e|=ee.W),t&ee.W&&(e|=ee.N),e}var hl=(()=>{let t=[[_e.Isolated,0],[_e.Cap,ee.N],[_e.Straight,ee.N|ee.S],[_e.Bend,ee.N|ee.E],[_e.Tee,ee.N|ee.E|ee.S],[_e.Cross,15]],e=new Array(16);for(let[n,r]of t){let o=r;for(let i=0;i<4;i++)e[o]===void 0&&(e[o]={mask:o,frame:n,rotation:i}),o=pl(o)}return e})();function _o(t){return hl[t&15]}function fl(t){return t.map((e,n)=>e.map((r,o)=>r?_o(rr(t,o,n)):null))}function Jo(t){let e=t.length,n=e?t[0].length:0,r=[];for(let o=0;o<e-1;o++){let i=[];for(let s=0;s<n-1;s++)i.push((Ee(t,s,o)?1:0)|(Ee(t,s+1,o)?2:0)|(Ee(t,s+1,o+1)?4:0)|(Ee(t,s,o+1)?8:0));r.push(i)}return r}var bl=[[],[["L","T"]],[["T","R"]],[["L","R"]],[["R","B"]],[["L","T"],["R","B"]],[["T","B"]],[["L","B"]],[["B","L"]],[["T","B"]],[["T","R"],["B","L"]],[["R","B"]],[["L","R"]],[["T","R"]],[["L","T"]],[]];function Uo(t,e={}){let n=e.cell??1,r=e.x??0,o=e.y??0,i=Jo(t),s=[],a=(l,u,c)=>{switch(l){case"T":return{x:u+n/2,y:c};case"R":return{x:u+n,y:c+n/2};case"B":return{x:u+n/2,y:c+n};case"L":return{x:u,y:c+n/2}}};for(let l=0;l<i.length;l++)for(let u=0;u<i[l].length;u++){let c=r+u*n,m=o+l*n;for(let[d,p]of bl[i[l][u]])s.push({a:a(d,c,m),b:a(p,c,m)})}return s}function gl(t,e={}){let n=e.tile??8,r=e.x??0,o=e.y??0,i=e.z??0,s=e.transform??le,a=e.fill??"#888",l=e.edge,u=e.edgeWidth??Math.max(1,n/8),c=[];for(let m=0;m<t.length;m++)for(let d=0;d<t[m].length;d++){if(!t[m][d])continue;let p=r+d*n,h=o+m*n;if(c.push({kind:"rect",x:p,y:h,w:n,h:n,transform:s,z:i,fill:a}),!l)continue;let g=rr(t,d,m),x=k=>c.push({kind:"poly",points:k,closed:!1,transform:s,z:i+1,stroke:l,strokeWidth:u});g&ee.N||x([p,h,p+n,h]),g&ee.E||x([p+n,h,p+n,h+n]),g&ee.S||x([p,h+n,p+n,h+n]),g&ee.W||x([p,h,p,h+n])}return c}function yl(t,e={}){let n=e.tile??8,r=e.transform??le,o=e.z??0,i=e.edge??e.fill??"#333",s=e.edgeWidth??Math.max(1,n/8);return Uo(t,{cell:n,x:e.x??0,y:e.y??0}).map(l=>({kind:"poly",points:[l.a.x,l.a.y,l.b.x,l.b.y],closed:!1,transform:r,z:o,stroke:i,strokeWidth:s,round:!0}))}function st(t,e,n=0){return{cols:t,rows:e,cells:new Array(t*e).fill(n)}}function Ko(t,e,n){return e<0||n<0||e>=t.cols||n>=t.rows?1:t.cells[n*t.cols+e]}function Fe(t,e,n,r){e<0||n<0||e>=t.cols||n>=t.rows||(t.cells[n*t.cols+e]=r)}function or(t,e,n){let r=0;for(let o=-1;o<=1;o++)for(let i=-1;i<=1;i++)i===0&&o===0||Ko(t,e+i,n+o)===1&&r++;return r}function xl(t,e=32){let n=t.cells.map(r=>r===1?j.SOLID:j.EMPTY);return{cols:t.cols,rows:t.rows,tileSize:e,tiles:n}}function Xo(t,e,n=0){let r=(n^2654435769)>>>0;return r=Math.imul(r^(t|0),2246822507)>>>0,r=Math.imul(r^(e|0),3266489909)>>>0,r^=r>>>13,r=Math.imul(r,668265263)>>>0,r^=r>>>15,r>>>0}function Je(t,e,n=0){return Xo(t,e,n)/4294967296}function vl(t,e,n,r=0){return Math.floor(Je(t,e,r)*n)}function Qo(t,e,n,r=0){return Je(t,e,r)<n}function wl(t,e,n,r,o,i=0){let s=[];for(let a=e;a<e+r;a++)for(let l=t;l<t+n;l++)Qo(l,a,o,i)&&s.push({x:l,y:a});return s}var Yo=t=>t*t*(3-2*t);function Zo(t,e,n=0){let r=Math.floor(t),o=Math.floor(e),i=Yo(t-r),s=Yo(e-o),a=Je(r,o,n),l=Je(r+1,o,n),u=Je(r,o+1,n),c=Je(r+1,o+1,n),m=a+(l-a)*i,d=u+(c-u)*i;return m+(d-m)*s}function ir(t,e,n=0,r={}){let o=r.octaves??4,i=r.lacunarity??2,s=r.gain??.5,a=1,l=1,u=0,c=0;for(let m=0;m<o;m++)u+=a*Zo(t*l,e*l,n+m),c+=a,a*=s,l*=i;return c===0?0:u/c}function kl(t,e){let{cols:n,rows:r}=e,o=e.fill??.45,i=e.steps??4,s=e.birth??5,a=e.survive??4,l=e.border??!0,u=st(n,r,0);for(let c=0;c<r;c++)for(let m=0;m<n;m++){let d=l&&(m===0||c===0||m===n-1||c===r-1);Fe(u,m,c,d||t.chance(o)?1:0)}for(let c=0;c<i;c++){let m=st(n,r,0);for(let d=0;d<r;d++)for(let p=0;p<n;p++){if(l&&(p===0||d===0||p===n-1||d===r-1)){Fe(m,p,d,1);continue}let h=or(u,p,d),g=u.cells[d*n+p]===1;Fe(m,p,d,(g?h>=a:h>=s)?1:0)}u=m}return u}function sr(t,e){let n=e.scale??.08,r=e.seed??0,o=ir(t*n,0,r,e.fractal)*2-1,i=Math.round(e.base+o*e.amplitude);return(e.minRow!==void 0||e.maxRow!==void 0)&&(i=U(i,e.minRow??-1/0,e.maxRow??1/0)),i}function Sl(t,e,n){let r=new Array(e);for(let o=0;o<e;o++)r[o]=sr(t+o,n);return r}function Ml(t,e,n){return e>=sr(t,n)}function ar(t){return{x:Math.floor(t.x+t.w/2),y:Math.floor(t.y+t.h/2)}}function Cl(t,e){return t.x<=e.x+e.w&&t.x+t.w>=e.x&&t.y<=e.y+e.h&&t.y+t.h>=e.y}function Tl(t,e){for(let n=e.y;n<e.y+e.h;n++)for(let r=e.x;r<e.x+e.w;r++)Fe(t,r,n,0)}function ei(t,e,n,r){for(let o=Math.min(e,n);o<=Math.max(e,n);o++)Fe(t,o,r,0)}function ti(t,e,n,r){for(let o=Math.min(e,n);o<=Math.max(e,n);o++)Fe(t,r,o,0)}function Rl(t,e){let{cols:n,rows:r}=e,o=e.attempts??12,i=e.minSize??4,s=e.maxSize??8,a=e.border??!0?1:0,l=st(n,r,1),u=[];for(let c=0;c<o;c++){let m=t.intRange(i,s),d=t.intRange(i,s),p=t.intRange(a,n-m-a-1),h=t.intRange(a,r-d-a-1);if(p<a||h<a)continue;let g={x:p,y:h,w:m,h:d};if(!u.some(x=>Cl(g,x))){if(Tl(l,g),u.length>0){let x=ar(u[u.length-1]),k=ar(g);t.chance(.5)?(ei(l,x.x,k.x,x.y),ti(l,x.y,k.y,k.x)):(ti(l,x.y,k.y,x.x),ei(l,x.x,k.x,k.y))}u.push(g)}}return{rooms:u,grid:l}}var be=44100;function ur(t,e=be){let n=Math.max(0,Math.round(t*e));return{sampleRate:e,left:new Float32Array(n),right:new Float32Array(n)}}function Pl(t){return t.left.length}function Dl(t){return t.left.length/t.sampleRate}function ni(t){let n=(U(t,-1,1)+1)*.5*(Math.PI/2);return{l:X(n),r:_(n)}}function cr(t,e,n,r=1,o=0){let{l:i,r:s}=ni(o),a=r*i,l=r*s,u=t.left.length,c=Math.round(n);for(let m=0;m<e.length;m++){let d=c+m;if(d<0)continue;if(d>=u)break;let p=e[m];t.left[d]+=p*a,t.right[d]+=p*l}}function ri(t){let e=0,{left:n,right:r}=t;for(let o=0;o<n.length;o++){let i=n[o]<0?-n[o]:n[o];i>e&&(e=i);let s=r[o]<0?-r[o]:r[o];s>e&&(e=s)}return e}function lr(t){return t/Math.sqrt(1+t*t)}function mr(t){let{left:e,right:n}=t;for(let r=0;r<e.length;r++)e[r]=lr(e[r]),n[r]=lr(n[r])}function dr(t,e=.89){let n=ri(t);if(n<1e-9)return;let r=e/n,{left:o,right:i}=t;for(let s=0;s<o.length;s++)o[s]*=r,i[s]*=r}function Il(t){let{left:e,right:n,sampleRate:r}=t,o=e.length,i=2,a=i*2,l=o*a,u=new Uint8Array(44+l),c=new DataView(u.buffer),m=(p,h)=>{for(let g=0;g<h.length;g++)c.setUint8(p+g,h.charCodeAt(g))};m(0,"RIFF"),c.setUint32(4,36+l,!0),m(8,"WAVE"),m(12,"fmt "),c.setUint32(16,16,!0),c.setUint16(20,1,!0),c.setUint16(22,i,!0),c.setUint32(24,r,!0),c.setUint32(28,r*a,!0),c.setUint16(32,a,!0),c.setUint16(34,16,!0),m(36,"data"),c.setUint32(40,l,!0);let d=44;for(let p=0;p<o;p++){let h=U(e[p],-1,1),g=U(n[p],-1,1);c.setInt16(d,(h<0?h*32768:h*32767)|0,!0),c.setInt16(d+2,(g<0?g*32768:g*32767)|0,!0),d+=4}return u}function El(t){let e=2166136261;for(let n=0;n<t.length;n++){let r=U(t[n],-1,1)*32767|0;e^=r&255,e=Math.imul(e,16777619),e^=r>>8&255,e=Math.imul(e,16777619)}return e>>>0}function Fl(t){return{freq:t.freq??220,wave:t.wave??"sine",duty:t.duty??.5,attack:Math.max(0,t.attack??.005),decay:Math.max(0,t.decay??0),sustain:Math.max(0,t.sustain??.08),release:Math.max(0,t.release??.1),sustainLevel:t.sustainLevel??1,punch:t.punch??0,volume:t.volume??.5,slide:t.slide??0,slideAccel:t.slideAccel??0,pitchJump:t.pitchJump??0,pitchJumpTime:t.pitchJumpTime??0,vibrato:t.vibrato??0,vibratoFreq:t.vibratoFreq??6,detune:t.detune??0,sub:Math.max(0,t.sub??0),noise:t.noise??0,shapeCurve:Math.max(.01,t.shapeCurve??1),fm:t.fm??0,fmFreq:t.fmFreq??0,tremolo:t.tremolo??0,tremoloFreq:t.tremoloFreq??8,bitCrush:Math.max(0,Math.floor(t.bitCrush??0)),lowpass:t.lowpass??0,highpass:t.highpass??0,delay:Math.max(0,t.delay??0),delayFeedback:Math.min(.95,Math.max(0,t.delayFeedback??0))}}function on(t){return he(t/12)}function oi(t,e,n,r){switch(t){case"sine":return _(ie*e);case"saw":return 2*e-1;case"square":return e<n?1:-1;case"triangle":return(e<.5?e*2:2-e*2)*2-1;case"noise":return r.float()*2-1}}function Nt(t,e={}){let n=Fl(t),r=e.sampleRate??be,o=e.rng??new ue(24301),i=n.attack+n.decay+n.sustain+n.release,s=n.delay>0?n.delay*6:0,a=i+s+.01,l=Math.max(1,Math.round(a*r)),u=new Float32Array(l),c=1/r,m=0,d=0,p=0,h=n.detune!==0?on(n.detune/100):1,g=0,x=0,k=0,w=0,P=n.lowpass>0?ii(n.lowpass,r):1,$=n.highpass>0?1-ii(n.highpass,r):0,v=r*.5;for(let f=0;f<l;f++){let M=f*c,S=Nl(M,n);n.punch>0&&(S*=1+n.punch*Math.max(0,1-M/Math.max(1e-4,n.attack+n.decay))),n.tremolo>0&&(S*=1-n.tremolo*.5*(1-_(ie*n.tremoloFreq*M)));let D=i>0?M/i:0,C=n.freq*on(n.slide*D+n.slideAccel*D*D);n.pitchJump!==0&&M>=n.pitchJumpTime&&(C*=on(n.pitchJump)),n.vibrato>0&&(C*=on(n.vibrato*_(ie*n.vibratoFreq*M))),n.fm>0&&(C+=n.fm*_(ie*n.fmFreq*M)),C<0?C=0:C>v&&(C=v),m+=C*c,m-=Math.floor(m);let y=oi(n.wave,m,n.duty,o);n.detune!==0&&(d+=C*h*c,d-=Math.floor(d),y=(y+oi(n.wave,d,n.duty,o))*.5),n.sub>0&&(p+=C*.5*c,p-=Math.floor(p),y=y*(1-n.sub*.5)+_(ie*p)*n.sub),n.noise>0&&(y=y*(1-n.noise)+(o.float()*2-1)*n.noise),n.shapeCurve!==1&&(y=(y<0?-1:1)*Re(y<0?-y:y,n.shapeCurve)),y*=S*n.volume,n.bitCrush>0&&(f%n.bitCrush===0&&(g=y),y=g),u[f]=y}if(n.lowpass>0)for(let f=0;f<l;f++)x+=P*(u[f]-x),u[f]=x;if(n.highpass>0)for(let f=0;f<l;f++)k=$*(k+u[f]-w),w=u[f],u[f]=k;if(n.delay>0){let f=Math.max(1,Math.round(n.delay*r));for(let M=f;M<l;M++)u[M]+=u[M-f]*n.delayFeedback}return u}function ii(t,e){let n=ie*t*(1/e);return n/(n+1)}function Nl(t,e){let n=e.attack,r=e.decay,o=e.sustain,i=e.release;if(t<n)return n>0?t/n:1;if(t<n+r)return r>0?1+(e.sustainLevel-1)*((t-n)/r):e.sustainLevel;if(t<n+r+o)return e.sustainLevel;let s=t-n-r-o;return s<i&&i>0?e.sustainLevel*(1-s/i):0}var $l={C:0,"C#":1,Db:1,D:2,"D#":3,Eb:3,E:4,Fb:4,"E#":5,F:5,"F#":6,Gb:6,G:7,"G#":8,Ab:8,A:9,"A#":10,Bb:10,B:11,Cb:11,"B#":0},Al=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];function ce(t){let e=/^([A-Ga-g])([#b]?)(-?\d+)$/.exec(t.trim());if(!e)throw new Error(`bad note name: ${JSON.stringify(t)}`);let n=e[1].toUpperCase(),r=$l[n+(e[2]||"")];if(r===void 0)throw new Error(`bad note name: ${JSON.stringify(t)}`);let o=parseInt(e[3],10);return r+(o+1)*12}function Ll(t){let e=(t%12+12)%12,n=Math.floor(t/12)-1;return Al[e]+n}function si(t,e=440){return e*he((t-69)/12)}function pr(t,e=440){return si(typeof t=="number"?t:ce(t),e)}var hr={major:[0,2,4,5,7,9,11],minor:[0,2,3,5,7,8,10],harmonicMinor:[0,2,3,5,7,8,11],melodicMinor:[0,2,3,5,7,9,11],dorian:[0,2,3,5,7,9,10],phrygian:[0,1,3,5,7,8,10],lydian:[0,2,4,6,7,9,11],mixolydian:[0,2,4,5,7,9,10],locrian:[0,1,3,5,6,8,10],majorPentatonic:[0,2,4,7,9],minorPentatonic:[0,3,5,7,10],blues:[0,3,5,6,7,10],chromatic:[0,1,2,3,4,5,6,7,8,9,10,11]};function sn(t,e="major",n=1){let r=hr[e],o=[];for(let i=0;i<n;i++)for(let s of r)o.push(t+i*12+s);return o.push(t+n*12),o}function fr(t,e="major"){let n=(t%12+12)%12;return new Set(hr[e].map(r=>(n+r)%12))}function ai(t,e,n,r=3){let o=(n%7+7)%7,i=sn(t,e,3),s=[];for(let a=0;a<r;a++)s.push(i[o+a*2]);return s}var zl={i:0,ii:1,iii:2,iv:3,v:4,vi:5,vii:6};function Ue(t,e,n){return n.map(r=>{let o=/^([iv]+|[IV]+)(7)?/i.exec(r.trim());if(!o)throw new Error(`bad roman numeral: ${JSON.stringify(r)}`);let i=zl[o[1].toLowerCase()];if(i===void 0)throw new Error(`bad roman numeral: ${JSON.stringify(r)}`);return ai(t,e,i,o[2]?4:3)})}function Wl(t,e){return t.map(n=>n+e)}function an(t){return t.length<2?t.slice():[t[0]-12,...t.slice(1)].sort((e,n)=>e-n)}function at(t){if(t.length===0)return[];let e=[t[0].slice().sort((n,r)=>n-r)];for(let n=1;n<t.length;n++){let r=e[n-1],o=r.reduce((s,a)=>s+a,0)/r.length,i=t[n].map(s=>{let a=s;for(;a-o>6;)a-=12;for(;o-a>6;)a+=12;return a}).sort((s,a)=>s-a);e.push(i)}return e}var Bl=[1116,1188,1277,1356,1422,1491,1557,1617],Ol=[556,441,341,225],Gl=23,Vl=.015,br=class{constructor(e,n,r){this.feedback=n;this.damp=r;this.buf=new Float32Array(Math.max(1,e))}feedback;damp;buf;idx=0;store=0;process(e){let n=this.buf[this.idx];return this.store=n*(1-this.damp)+this.store*this.damp,this.buf[this.idx]=e+this.store*this.feedback,this.idx=(this.idx+1)%this.buf.length,n}},gr=class{constructor(e,n=.5){this.feedback=n;this.buf=new Float32Array(Math.max(1,e))}feedback;buf;idx=0;process(e){let n=this.buf[this.idx],r=-e+n;return this.buf[this.idx]=e+n*this.feedback,this.idx=(this.idx+1)%this.buf.length,r}};function li(t,e,n,r){let o=t/44100,i=Bl.map(a=>new br(Math.round((a+r)*o),e,n)),s=Ol.map(a=>new gr(Math.round((a+r)*o),.5));return{combs:i,aps:s}}function yr(t,e={}){let n=U(e.wet??.25,0,1),r=U(e.roomSize??.7,0,1),o=U(e.damp??.5,0,1)*.4,i=.7+r*.28,s=t.sampleRate,a=li(s,i,o,0),l=li(s,i,o,Gl),u=t.left.length;for(let c=0;c<u;c++){let m=(t.left[c]+t.right[c])*Vl,d=0;for(let h of a.combs)d+=h.process(m);for(let h of a.aps)d=h.process(d);let p=0;for(let h of l.combs)p+=h.process(m);for(let h of l.aps)p=h.process(p);t.left[c]=t.left[c]*(1-n)+d*n,t.right[c]=t.right[c]*(1-n)+p*n}}function ql(t){let e=0;for(let n of t)e+=n.beats;return e}function jl(t){let e=0;for(let n of t.sequence)e+=ql(t.patterns[n]??[]);return e}function ci(t){let e=0;for(let n of t.tracks)e=Math.max(e,jl(n));return e}function ln(t){return ci(t)*60/t.bpm}function xr(t,e={}){let n=e.sampleRate??be,r=t.a4??440,o=60/t.bpm,i=t.tailSec??2,s=ln(t)+i,a=ur(s,n),l=Math.max(0,Math.min(1,t.swing??0)),u=Math.max(0,Math.min(1,t.humanize??0)),c=Math.max(0,Math.min(1,t.velBrightness??.5));if(t.tracks.forEach((m,d)=>{let p=m.gain??.7,h=m.pan??0,g=new ue(5292449^(d+1)*2654435769),x=0;for(let k of m.sequence){let w=m.patterns[k];if(w)for(let P of w){if(P.pitch!==null&&P.pitch!==void 0){let $=Math.round(x*2),f=Math.abs(x*2-$)<1e-4&&$%2===1?x+l*.2:x,M=u>0?g.range(-1,1)*u*.012:0,S=Math.round((f*o+M)*n),D=P.beats*o,C=u>0?g.range(-1,1)*u*.12:0,y=Math.max(.05,Math.min(1,(P.vel??1)+C)),T=Array.isArray(P.pitch)?P.pitch:[P.pitch],E=m.instrument.attack??.005,O=m.instrument.decay??0,F=Math.max(.01,D-E-O),J=m.instrument.lowpass,Y=J&&c>0?J*(1-c*(1-y)):J;for(let ne of T){let Z={...m.instrument,freq:pr(ne,r),sustain:F,volume:(m.instrument.volume??.5)*y,...Y!==void 0?{lowpass:Y}:{}},ae=Nt(Z,{rng:g,sampleRate:n});cr(a,ae,Math.max(0,S),p,h)}}x+=P.beats}}}),t.sidechain){let m=Math.max(0,Math.min(1,t.sidechain.depth??.5)),d=(t.sidechain.beatsPerCycle??1)*o;Jl(a,d,m)}return t.reverb&&yr(a,t.reverb),t.master&&_l(a,t.master),t.master?.compress&&Hl(a,t.master.compress),mr(a),dr(a,e.normalizePeak??.89),a}function Hl(t,e){let n=Math.max(0,Math.min(1,e)),r=t.sampleRate,o=ui(-20),i=2+n*3,s=Be(-1/(r*.005)),a=Be(-1/(r*.15)),l=ui(n*6),u=0,c=t.left,m=t.right;for(let d=0;d<c.length;d++){let p=Math.max(Math.abs(c[d]),Math.abs(m[d])),h=p>u?s:a;u=h*u+(1-h)*p;let g=1;if(u>o){let k=u/o;g=o*Re(k,1/i)/u}let x=g*l;c[d]*=x,m[d]*=x}}function ui(t){return he(t/6.020599913)}function _l(t,e){let n=t.sampleRate,r=Math.max(0,e.lowCut??0),o=Math.max(0,e.presence??0),i=Math.max(0,e.air??0),s=c=>{let m=ie*c*(1/n);return m/(m+1)},a=s(240),l=1-s(3200),u=1-s(9e3);for(let c of[t.left,t.right]){let m=0,d=0,p=0,h=0,g=0;for(let x=0;x<c.length;x++){let k=c[x];m+=a*(k-m),d=l*(d+k-p),p=k,h=u*(h+k-g),g=k,c[x]=k-r*m+o*d+i*h}}}function Jl(t,e,n){let r=t.sampleRate,o=Math.max(1,e*r);for(let i=0;i<t.left.length;i++){let a=1-i%o/o,l=1-n*a*a;t.left[i]*=l,t.right[i]*=l}}var A={lead:{wave:"square",duty:.5,attack:.008,release:.08,volume:.4,lowpass:4e3,detune:6},pluck:{wave:"triangle",attack:.002,decay:.06,sustainLevel:.3,release:.12,volume:.42},pad:{wave:"saw",attack:.12,release:.5,volume:.26,lowpass:2200,vibrato:.08,vibratoFreq:4,detune:14},bell:{wave:"sine",attack:.002,decay:.3,sustainLevel:.2,release:.5,volume:.4,fm:3,fmFreq:220},piano:{wave:"triangle",attack:.002,decay:.5,sustainLevel:.12,release:.35,volume:.42,lowpass:3600,detune:4},rhodes:{wave:"sine",attack:.003,decay:.45,sustainLevel:.35,release:.4,volume:.4,fm:2.2,fmFreq:440,detune:5},strings:{wave:"saw",attack:.16,decay:.2,sustainLevel:.85,release:.6,volume:.24,lowpass:2600,detune:16,vibrato:.07,vibratoFreq:5},brass:{wave:"saw",attack:.04,decay:.1,sustainLevel:.8,release:.16,volume:.3,lowpass:3200,detune:8,punch:.3},organ:{wave:"sine",attack:.006,release:.05,sustainLevel:1,volume:.32,sub:.5,detune:3},choir:{wave:"triangle",attack:.28,release:.9,sustainLevel:.9,volume:.22,lowpass:2e3,detune:20,vibrato:.1,vibratoFreq:4.5},glocken:{wave:"sine",attack:.001,decay:.6,sustainLevel:0,release:.4,volume:.34,fm:4,fmFreq:1600},vibraphone:{wave:"sine",attack:.002,decay:.5,sustainLevel:.25,release:.7,volume:.4,fm:2,fmFreq:880,tremolo:.25,tremoloFreq:5},clav:{wave:"square",duty:.35,attack:.001,decay:.08,sustainLevel:.25,release:.08,volume:.32,lowpass:3800,detune:4},uprightBass:{wave:"triangle",attack:.004,decay:.12,sustainLevel:.5,release:.1,volume:.5,lowpass:1100,sub:.35},mutedTrumpet:{wave:"saw",attack:.03,decay:.08,sustainLevel:.75,release:.14,volume:.3,lowpass:2600,detune:4,vibrato:.09,vibratoFreq:6},jazzGuitar:{wave:"triangle",attack:.004,decay:.35,sustainLevel:.2,release:.25,volume:.34,lowpass:2400,detune:5},horns:{wave:"saw",attack:.02,decay:.08,sustainLevel:.7,release:.12,volume:.3,lowpass:3600,detune:10,punch:.4},bass:{wave:"saw",attack:.006,release:.06,volume:.5,lowpass:900,detune:6,sub:.3},subBass:{wave:"sine",attack:.004,release:.08,volume:.6,lowpass:400,sub:.5,punch:.2},kick:{wave:"sine",attack:.001,decay:.06,sustainLevel:0,release:.08,slide:-24,volume:.7,sub:.3},snare:{wave:"noise",attack:.001,decay:.05,sustainLevel:.2,release:.12,highpass:1200,volume:.5},hat:{wave:"noise",attack:.001,release:.04,highpass:6e3,volume:.28},rimshot:{wave:"noise",attack:.001,release:.03,highpass:3e3,lowpass:7e3,volume:.3},ride:{wave:"noise",attack:.001,decay:.1,sustainLevel:.14,release:.32,volume:.2,highpass:1600,lowpass:7e3}};var Ul={master:.7,music:.6,sfx:.8,muted:!1},un=class{ctx=null;master=null;musicGain=null;sfxGain=null;vol={...Ul};padOn=!1;get available(){return typeof globalThis.AudioContext<"u"||"webkitAudioContext"in globalThis}get started(){return!!this.ctx}start(){if(this.ctx){this.ctx.resume();return}if(!this.available)return;let e=globalThis.AudioContext||globalThis.webkitAudioContext;this.ctx=new e,this.master=this.ctx.createGain(),this.musicGain=this.ctx.createGain(),this.sfxGain=this.ctx.createGain(),this.musicGain.connect(this.master),this.sfxGain.connect(this.master),this.master.connect(this.ctx.destination),this.applyVolumes()}setVolumes(e){this.vol={...this.vol,...e},this.applyVolumes()}getVolumes(){return{...this.vol}}applyVolumes(){if(!this.ctx||!this.master||!this.musicGain||!this.sfxGain)return;let e=this.ctx.currentTime;this.master.gain.setTargetAtTime(this.vol.muted?0:this.vol.master,e,.04),this.musicGain.gain.setTargetAtTime(this.vol.music*.5,e,.04),this.sfxGain.gain.setTargetAtTime(this.vol.sfx,e,.04)}tone(e){if(!this.ctx||!this.sfxGain)return;let{freq:n,duration:r,type:o="sine",gain:i=.2,delay:s=0,pan:a}=e,l=this.ctx.currentTime+s,u=this.ctx.createOscillator();u.type=o,u.frequency.value=n;let c=this.ctx.createGain();if(c.gain.setValueAtTime(0,l),c.gain.linearRampToValueAtTime(i,l+.008),c.gain.exponentialRampToValueAtTime(1e-4,l+r),u.connect(c),a!==void 0&&typeof this.ctx.createStereoPanner=="function"){let m=this.ctx.createStereoPanner();m.pan.value=Math.max(-1,Math.min(1,a)),c.connect(m),m.connect(this.sfxGain)}else c.connect(this.sfxGain);u.start(l),u.stop(l+r+.05)}spatial(e,n,r,o=600,i=.18,s="sawtooth"){if(r>o)return;let a=1-r/o;this.tone({freq:e,duration:i,type:s,gain:.04+a*a*.3,pan:Math.max(-1,Math.min(1,n/(o*.6)))})}play(e){for(let n of e)this.tone(n)}playSpec(e,n={}){if(!this.ctx||!this.sfxGain)return;let r=Nt(e,{sampleRate:this.ctx.sampleRate}),o=this.ctx.createBuffer(1,r.length,this.ctx.sampleRate);o.copyToChannel(new Float32Array(r),0);let i=this.ctx.createBufferSource();i.buffer=o;let s=this.ctx.createGain();if(s.gain.value=n.gain??1,i.connect(s),n.pan!==void 0&&typeof this.ctx.createStereoPanner=="function"){let a=this.ctx.createStereoPanner();a.pan.value=Math.max(-1,Math.min(1,n.pan)),s.connect(a),a.connect(this.sfxGain)}else s.connect(this.sfxGain);i.start(this.ctx.currentTime+(n.when??0))}playSong(e,n={}){if(!this.ctx||!this.musicGain)return()=>{};let r=xr(e,{sampleRate:this.ctx.sampleRate}),o=this.ctx.createBuffer(2,r.left.length,this.ctx.sampleRate);o.copyToChannel(new Float32Array(r.left),0),o.copyToChannel(new Float32Array(r.right),1);let i=this.ctx.createBufferSource();return i.buffer=o,n.loop&&(i.loop=!0,i.loopStart=0,i.loopEnd=ln(e)),i.connect(this.musicGain),i.start(),()=>{try{i.stop()}catch{}}}blip(e=520){this.tone({freq:e,duration:.06,type:"sine",gain:.18})}chime(){[523.25,659.25,783.99].forEach((e,n)=>this.tone({freq:e,duration:.9-n*.15,type:"sine",gain:.15,delay:n*.04}))}success(){[392,493.88,587.33,783.99].forEach((e,n)=>this.tone({freq:e,duration:.4,type:"triangle",gain:.15,delay:n*.08}))}thud(){this.tone({freq:130,duration:.14,type:"sine",gain:.22})}startAmbient(e=110,n=[1,1.5,2,2.5]){if(!this.ctx||!this.musicGain||this.padOn)return;this.padOn=!0;let r=this.ctx.createBiquadFilter();r.type="lowpass",r.frequency.value=900,r.connect(this.musicGain);let o=this.ctx.createGain();o.gain.value=0,o.connect(r);for(let i of n){let s=this.ctx.createOscillator();s.type="triangle",s.frequency.value=e*i;let a=this.ctx.createGain();a.gain.value=.1/n.length,s.connect(a),a.connect(o),s.start()}o.gain.setTargetAtTime(.9,this.ctx.currentTime,3)}},Le=new un;function cn(t){let e=t<0?-t:t;return e<1e-12?-1/0:20*ht(e)}function lt(t){if(t.length===0)return 0;let e=0;for(let n=0;n<t.length;n++)e+=t[n]*t[n];return Math.sqrt(e/t.length)}function vr(t){let e=0;for(let n=0;n<t.length;n++){let r=t[n]<0?-t[n]:t[n];r>e&&(e=r)}return e}function mi(t,e=be){if(t.length<2)return 0;let n=0;for(let r=1;r<t.length;r++)(t[r-1]<0&&t[r]>=0||t[r-1]>=0&&t[r]<0)&&n++;return n*e/t.length}function Kl(t){let e=1;for(;e*2<=t;)e*=2;return e}function di(t,e){let n=t.length;for(let r=1,o=0;r<n;r++){let i=n>>1;for(;o&i;i>>=1)o^=i;if(o^=i,r<o){let s=t[r];t[r]=t[o],t[o]=s;let a=e[r];e[r]=e[o],e[o]=a}}for(let r=2;r<=n;r<<=1){let o=-ie/r,i=X(o),s=_(o);for(let a=0;a<n;a+=r){let l=1,u=0;for(let c=0;c<r/2;c++){let m=a+c,d=m+r/2,p=l*t[d]-u*e[d],h=l*e[d]+u*t[d];t[d]=t[m]-p,e[d]=e[m]-h,t[m]+=p,e[m]+=h;let g=l*i-u*s;u=l*s+u*i,l=g}}}}function ut(t){let e=Kl(t.length);if(e<2)return new Float32Array(0);let n=new Float32Array(e),r=new Float32Array(e);for(let s=0;s<e;s++){let a=.5-.5*X(ie*s/(e-1));n[s]=t[s]*a}di(n,r);let o=e>>1,i=new Float32Array(o);for(let s=0;s<o;s++)i[s]=Math.sqrt(n[s]*n[s]+r[s]*r[s]);return i}function pi(t,e=be){if(t.length<64)return 0;let r=2048,o=0,i=0;for(let s=0;s+64<=t.length;s+=r){let a=t.subarray(s,Math.min(s+2048,t.length)),l=ut(a),u=e/(l.length*2);for(let c=0;c<l.length;c++)o+=c*u*l[c],i+=l[c]}return i<1e-9?0:o/i}function wr(t,e=1024,n=512){let r=[],o=null;for(let i=0;i+e<=t.length;i+=n){let s=ut(t.subarray(i,i+e)),a=0;if(o){let l=Math.min(s.length,o.length);for(let u=0;u<l;u++){let c=s[u]-o[u];c>0&&(a+=c)}}r.push(a),o=s}return Float32Array.from(r)}function hi(t,e=be){let r=wr(t,1024,512);if(r.length<3)return 0;let o=0;for(let l=0;l<r.length;l++)o+=r[l];o/=r.length;let i=o*1.5,s=0;for(let l=1;l<r.length-1;l++)r[l]>i&&r[l]>=r[l-1]&&r[l]>r[l+1]&&s++;let a=t.length/e;return a<1e-6?0:s/a}function fi(t,e=be){let r=wr(t,1024,512);if(r.length<8)return 0;let o=e/512,i=Math.max(1,Math.ceil(o*60/200)),s=Math.min(r.length-1,Math.floor(o*60/60)),a=0,l=-1;for(let c=i;c<=s;c++){let m=0;for(let d=c;d<r.length;d++)m+=r[d]*r[d-c];m/=r.length-c,m>l&&(l=m,a=c)}if(a===0)return 0;let u=60*o/a;for(;u>150;)u/=2;for(;u>0&&u<70;)u*=2;return u}function kr(t){let e=lt(t);return e<1e-9?0:cn(vr(t))-cn(e)}function Sr(t,e=be){let r=[20,60,250,800,2500,8e3,e/2],o=new Float64Array(6);if(t.length>=64)for(let s=0;s+64<=t.length;s+=2048){let a=ut(t.subarray(s,Math.min(s+2048,t.length))),l=e/(a.length*2);for(let u=0;u<a.length;u++){let c=u*l,m=a[u]*a[u];for(let d=0;d<6;d++)if(c>=r[d]&&c<r[d+1]){o[d]+=m;break}}}let i=o.reduce((s,a)=>s+a,0)||1;return{sub:o[0]/i,bass:o[1]/i,lowMid:o[2]/i,mid:o[3]/i,high:o[4]/i,air:o[5]/i}}function ct(t,e=be){return{durationSec:t.length/e,rms:lt(t),peakDb:cn(vr(t)),centroidHz:pi(t,e),zcr:mi(t,e),onsetDensity:hi(t,e),tempoBpm:fi(t,e)}}var Yl={"":[0,4,7],maj:[0,4,7],M:[0,4,7],m:[0,3,7],min:[0,3,7],"-":[0,3,7],dim:[0,3,6],aug:[0,4,8],"+":[0,4,8],6:[0,4,7,9],m6:[0,3,7,9],"-6":[0,3,7,9],69:[0,4,7,9,14],"6/9":[0,4,7,9,14],maj7:[0,4,7,11],M7:[0,4,7,11],maj9:[0,4,7,11,14],"maj7#11":[0,4,7,11,18],maj13:[0,4,7,11,14,21],7:[0,4,7,10],9:[0,4,7,10,14],11:[0,7,10,14,17],13:[0,4,7,10,14,21],"7b9":[0,4,7,10,13],"7#9":[0,4,7,10,15],"7#11":[0,4,7,10,18],"7b13":[0,4,7,10,20],"7b5":[0,4,6,10],"7#5":[0,4,8,10],"13b9":[0,4,7,10,13,21],"13#11":[0,4,7,10,18,21],"9#11":[0,4,7,10,14,18],"7alt":[0,4,10,13,20],m7:[0,3,7,10],min7:[0,3,7,10],"-7":[0,3,7,10],m9:[0,3,7,10,14],m11:[0,3,7,10,14,17],m13:[0,3,7,10,14,21],m7b5:[0,3,6,10],\u00F8:[0,3,6,10],\u00F87:[0,3,6,10],dim7:[0,3,6,9],mMaj7:[0,3,7,11],"m(maj7)":[0,3,7,11],mMaj9:[0,3,7,11,14],sus4:[0,5,7],sus2:[0,2,7],"7sus4":[0,5,7,10],"9sus4":[0,5,7,10,14],add9:[0,4,7,14],madd9:[0,3,7,14]};function Se(t,e=4){let r=t.trim().split("/"),o=r[0],i=/^([A-Ga-g][#b]?)(.*)$/.exec(o);if(!i)throw new Error(`bad chord symbol: ${JSON.stringify(t)}`);let s=i[1][0].toUpperCase()+(i[1][1]??""),a=i[2],l=Yl[a];if(!l)throw new Error(`unknown chord quality ${JSON.stringify(a)} in ${JSON.stringify(t)}`);let u=ce(s+e),c=l.map(m=>u+m);if(r.length===2){let m=/^([A-Ga-g][#b]?)$/.exec(r[1].trim());if(m){let d=m[1][0].toUpperCase()+(m[1][1]??""),p=ce(d+(e-1));for(;p>=c[0];)p-=12;c.unshift(p)}}return c}function $t(t,e){let n=t.slice(1);if(e===void 0||n.length===0)return n;let r=n.reduce((i,s)=>i+s,0)/n.length,o=Math.round((e-r)/12)*12;return n.map(i=>i+o).sort((i,s)=>i-s)}function Xl(t,e=4){return t.map(n=>Se(n,e))}function bi(t){try{return typeof t=="number"?t:ce(t)}catch{return null}}function Ql(t){return t.pitch===null||t.pitch===void 0?[]:Array.isArray(t.pitch)?t.pitch:[t.pitch]}function Zl(t,e={}){let n=[],r=[];(!(t.bpm>0)||t.bpm<20||t.bpm>400)&&n.push(`bpm ${t.bpm} out of sane range [20,400]`),(!t.tracks||t.tracks.length===0)&&n.push("song has no tracks");let o=e.key?fr(bi(e.key.tonic)??0,e.key.mode):null,i=0,s=0,a=new Map;if(t.tracks.forEach((u,c)=>{let m=u.name??`track ${c}`;(!u.patterns||u.patterns.length===0)&&n.push(`${m}: no patterns`),(!u.sequence||u.sequence.length===0)&&n.push(`${m}: empty sequence`),u.pan!==void 0&&(u.pan<-1||u.pan>1)&&n.push(`${m}: pan ${u.pan} out of [-1,1]`);for(let d of u.sequence??[]){if(d<0||d>=(u.patterns?.length??0)){n.push(`${m}: sequence references missing pattern ${d}`);continue}let p=`${c}:${d}`;a.set(p,(a.get(p)??0)+1);for(let h of u.patterns[d]){h.beats>0||n.push(`${m}: note with non-positive beats ${h.beats}`),h.vel!==void 0&&(h.vel<0||h.vel>1)&&n.push(`${m}: velocity ${h.vel} out of [0,1]`);for(let g of Ql(h)){let x=bi(g);if(x===null){n.push(`${m}: unparseable pitch ${JSON.stringify(g)}`);continue}(x<0||x>127)&&n.push(`${m}: pitch ${g} outside MIDI 0..127`),i++,o&&!o.has((x%12+12)%12)&&s++}}}}),o&&i>0){let u=s/i,c=e.maxOutOfKey??1,m=`${s}/${i} notes (${Math.round(u*100)}%) out of key`;u>c?n.push(m):s>0&&r.push(m)}return![...a.values()].some(u=>u>1)&&t.tracks.length>0&&r.push("no pattern is reused \u2014 piece may lack structure/repetition"),{ok:n.length===0,errors:n,warnings:r}}function eu(t){return t.length===0?!1:(r=>r.trim().toLowerCase().replace(/7$/,""))(t[t.length-1])==="i"}var tu={tempoBpm:20,centroidHz:1200,rms:.1,zcr:1500,onsetDensity:4,peakDb:6},nu={tempoBpm:["too slow","too fast"],centroidHz:["too dark / muffled","too bright / harsh"],rms:["too quiet","too loud"],zcr:["too smooth / tonal","too noisy / gritty"],onsetDensity:["too sparse","too busy"],peakDb:["more headroom than reference","hotter / less headroom than reference"]};function gi(t,e,n={}){let r={...tu,...n},o=Object.keys(r),i=[],s=0;for(let c of o){let m=t[c],d=e[c],p=Number.isFinite(m)?m:0,h=Number.isFinite(d)?d:0,g=(h-p)/r[c];s+=g*g;let[x,k]=nu[c],w=Math.abs(g)<.25?"ok":g<0?x:k;i.push({feature:c,reference:p,candidate:h,normalized:g,note:w})}i.sort((c,m)=>Math.abs(m.normalized)-Math.abs(c.normalized));let a=Math.sqrt(s/o.length),l=i[0],u=Math.abs(l.normalized)<.25?"close match":`${l.feature}: ${l.note}`;return{distance:a,deltas:i,headline:u}}function ru(t,e){let n=gi(t,e),r=n.deltas.filter(o=>o.note!=="ok").map(o=>` ${o.feature.padEnd(13)} ${o.candidate.toFixed(1)} vs ${o.reference.toFixed(1)} \u2192 ${o.note}`);return`match distance ${n.distance.toFixed(3)} \u2014 ${n.headline}
|
|
1
|
+
"use strict";var hayao=(()=>{var mr=Object.defineProperty;var Ia=Object.getOwnPropertyDescriptor;var La=Object.getOwnPropertyNames;var $a=Object.prototype.hasOwnProperty;var Na=(t,e)=>{for(var n in e)mr(t,n,{get:e[n],enumerable:!0})},Fa=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of La(e))!$a.call(t,o)&&o!==n&&mr(t,o,{get:()=>e[o],enumerable:!(r=Ia(e,o))||r.enumerable});return t};var Aa=t=>Fa(mr({},"__esModule",{value:!0}),t);var lh={};Na(lh,{ALBUM:()=>Gs,AMBIENT_PRESETS:()=>vl,AmbientField:()=>Mr,AnimationPlayer:()=>Vt,AudioBus:()=>jn,BLOOM_PIPELINE:()=>ju,BitmapText:()=>ro,Blend1D:()=>Ir,Blend2D:()=>Lr,Bone2D:()=>Ve,BroadcastChannelTransport:()=>ai,CLIP_CHANNELS:()=>ki,Camera2D:()=>Ot,CameraController:()=>wr,Canvas2DRenderer:()=>lt,CinematicPlayer:()=>$o,ClipPlayer:()=>qt,Clock:()=>At,Coroutines:()=>qo,DEFAULT_GAMEPAD_MAP:()=>Wi,DEFAULT_INPUT_MAP:()=>Fn,DEFAULT_PLATFORMER:()=>St,DEFAULT_SESSION_CONFIG:()=>dt,DEFAULT_TILE_CHARS:()=>zr,DUSK:()=>Ln,DepthSort:()=>vr,EASINGS:()=>Fe,Edge:()=>ne,EventBus:()=>Wt,FLOAT_PRESETS:()=>wl,FONT_5:()=>no,FloatingText:()=>Pr,Fsm:()=>Oo,GENRES:()=>_s,GENRE_PROFILES:()=>Yc,GamepadSource:()=>Ur,HeadlessRenderer:()=>eo,IDENTITY:()=>oe,INSTRUMENTS:()=>W,IkTarget:()=>Fr,InputBuffer:()=>ht,InputRecorder:()=>Vr,InputState:()=>Jt,IsoPrism:()=>xr,KENTO:()=>B,KeyboardSource:()=>et,LAYER_HUD:()=>Mp,LAYER_LIGHT:()=>He,LAYER_WORLD:()=>Tp,LightLayer:()=>Xt,LocalStorageAdapter:()=>or,LockstepSession:()=>Ie,LoopbackHub:()=>si,LoopbackTransport:()=>lr,LootTable:()=>jo,MEADOW:()=>Ri,MOUSE_ACTIONS:()=>jr,MemoryStorage:()=>rr,NEIGHBORS_4:()=>gn,NEIGHBORS_8:()=>nr,NET_PROTOCOL_VERSION:()=>Zg,Node:()=>_,Node2D:()=>_,NodePool:()=>Sr,NullStorage:()=>Zo,PAD_NEUTRAL:()=>Jl,PALETTES:()=>Rl,PANEL_PRESETS:()=>Yu,PAPER:()=>Pi,PARTICLE_PRESETS:()=>vi,ParallaxLayer:()=>kr,Particles:()=>Tr,PhaseClock:()=>Go,PixelBuffer:()=>Tt,PlayerInput:()=>ar,PointLight:()=>vt,PointerSource:()=>Yt,RingBuffer:()=>Qo,Rng:()=>ue,RollbackSession:()=>vn,RoomHost:()=>ur,SAMPLE_RATE:()=>be,SAVE_FORMAT_VERSION:()=>oi,SCALES:()=>fo,SaveManager:()=>ri,ScreenTransition:()=>er,SessionRecorder:()=>pt,Shaker:()=>Rr,Shell:()=>mn,Signal:()=>gt,Skeleton:()=>Pn,SkeletonDebug:()=>Ar,SnapshotRing:()=>Nt,SpatialHash:()=>Qt,Sprite:()=>zt,SvgRenderer:()=>at,TAU:()=>Z,TILE:()=>U,Text:()=>_t,TextureSprite:()=>to,Timer:()=>Gt,TouchControls:()=>Lo,UndoStack:()=>Ko,VERSION:()=>ah,VerletChain:()=>Dr,WEBGL_EFFECTS:()=>rn,WangFrame:()=>Qe,WebGL2Renderer:()=>on,World:()=>pn,abilitiesOf:()=>Ca,addBody:()=>lu,addDistanceJoint:()=>pu,addRevoluteJoint:()=>fu,addTransition:()=>Cm,albumTrack:()=>bm,all:()=>wd,analyzePlaytest:()=>pd,applyChannel:()=>In,applyImpulse:()=>cu,applyReverb:()=>xo,applyTransform:()=>bt,asciiEntities:()=>Gl,assertAudio:()=>sd,assertDeterministic:()=>Pm,assertRamp:()=>ed,assertSnapshotStable:()=>Dm,assertSolvable:()=>Rm,astar:()=>ba,astarGrid:()=>Pd,audio:()=>je,autotile4:()=>Bl,autotileToCommands:()=>_l,availableUpgrades:()=>Wd,bandBalance:()=>Co,bfs:()=>fa,blendIssues:()=>Cl,blobPath:()=>Zu,bodyAABB:()=>An,bodyContains:()=>Ji,bootDom:()=>bd,buildSkeleton:()=>Dn,cadenceResolves:()=>Gc,cameraIssues:()=>ta,canvasGradient:()=>Qr,cellFloat:()=>ut,cellHash:()=>fs,cellInt:()=>lc,changeFrames:()=>Jm,checkDeterministic:()=>Js,chordChanges:()=>zc,chordNotes:()=>Ce,clamp:()=>Q,clientToDesign:()=>ot,clipEvents:()=>Er,clipFinished:()=>Tn,clipIssues:()=>Sl,clipTime:()=>Ae,collide:()=>Xr,commandsToSVGInner:()=>st,composeCampaign:()=>Ud,composeTransform:()=>Ne,connectWebSocket:()=>eh,connectedComponents:()=>Rd,contourToCommands:()=>Ol,contrastRatio:()=>Lt,createPlanBot:()=>Fm,createPlatformerState:()=>Yl,createRigidWorld:()=>iu,createStereo:()=>uo,createWorld:()=>Te,crestFactorDb:()=>So,cullSegments:()=>Or,dashJumpDistance:()=>eu,datan:()=>di,datan2:()=>Le,dbfs:()=>Un,dcos:()=>j,decode2bit:()=>nc,decodeBits:()=>tc,decodeMessage:()=>Oe,decodeRLE:()=>rc,defaultStorage:()=>ei,defineGame:()=>ld,defineLevel:()=>_d,deg2rad:()=>cl,deserializeNode:()=>Nn,dexp:()=>Je,dexp2:()=>fe,dhypot:()=>G,diamondPoints:()=>Cn,diatonicChord:()=>Ts,diffLevels:()=>Hd,distanceGain:()=>As,dlog:()=>dr,dlog10:()=>Ft,dlog2:()=>ft,dpow:()=>Pe,drive:()=>Nm,dropShadow:()=>$u,dsin:()=>q,duckGain:()=>Jc,encodeMessage:()=>de,encodeRLE:()=>oc,encodeWav:()=>yc,estimateTempo:()=>$s,evalCurve:()=>jc,featureDistance:()=>Fs,features:()=>It,feedbackIssues:()=>Qs,fft:()=>Es,findSoftlocks:()=>Yd,firstFrame:()=>Um,fitViewport:()=>it,floodFill:()=>Yo,fluxEnvelope:()=>ko,forgivenessIssues:()=>Ks,fractalNoise:()=>io,frameActions:()=>wt,frameAxes:()=>kt,gameInputMap:()=>ud,generateCave:()=>cc,generateDungeon:()=>fc,generateLevels:()=>ii,generateLevelsReport:()=>ka,genre:()=>om,getBody:()=>ge,getJoint:()=>bu,glow:()=>Lu,graceWindowIssues:()=>Wm,gradient:()=>$l,gradientDef:()=>Bn,gridAt:()=>hs,gridFromRows:()=>Nl,gridSet:()=>Be,gridToTilemap:()=>ac,groundAt:()=>Bi,hashNoise:()=>bl,hashString:()=>br,hashValue:()=>Bt,hexToHsl:()=>Ii,hideScreen:()=>cn,hold:()=>Em,hostRoom:()=>ui,hsl:()=>Ei,hsv:()=>El,inVisionCone:()=>ou,initDirector:()=>Fd,inputDensity:()=>Km,installCapture:()=>Ao,invLerp:()=>hr,invalidCommandReason:()=>Zt,invertTransform:()=>De,isCaptureMode:()=>Fo,isGround:()=>dc,isLightCommand:()=>Fu,isMonotonic:()=>Ym,iso:()=>pl,joinRoom:()=>li,jumpAirtime:()=>zi,jumpDistance:()=>_i,jumpHeight:()=>Zl,keyMentions:()=>la,keysToActions:()=>qr,knob:()=>ad,layerGains:()=>Xc,layoutIssues:()=>Hm,layoutText:()=>cs,lerp:()=>$e,lerpDamp:()=>yl,levelFromSeed:()=>jd,levelIssues:()=>Od,levelReachable:()=>Gd,levelToTilemap:()=>ir,lightingIssues:()=>ea,lineOfSight:()=>Gi,linearGradient:()=>Eu,lintSong:()=>Oc,longestLull:()=>Qm,lookAheadIssues:()=>na,magnitudeSpectrum:()=>Et,makeGrid:()=>Rt,makeReach:()=>xl,makeTransform:()=>Ge,mapHeight:()=>ql,mapWidth:()=>Hl,marchingSquaresCases:()=>$i,marchingSquaresContours:()=>$n,mask4:()=>Br,mask8:()=>Fl,matchReport:()=>qc,measureLine:()=>Mt,measureText:()=>sc,mergePlayerFrames:()=>$t,midiToFreq:()=>Cs,midiToName:()=>Cc,missingControlHints:()=>qm,mix:()=>Pl,mixLinear:()=>xt,mixMono:()=>co,mixPose:()=>Rn,moveRect:()=>Kt,mutateColor:()=>Il,netMessage:()=>he,nextStep:()=>xd,nineSlice:()=>Ju,normalize:()=>ho,noteToMidi:()=>ce,occludersFromTilemap:()=>jl,onsetDensity:()=>Ls,openVoicing:()=>Hn,packVarints:()=>$d,panFromOffset:()=>Ws,panGains:()=>vs,parseLightRun:()=>rt,parseRich:()=>as,parseSnapshot:()=>ni,passableFromTilemap:()=>Dd,peak:()=>ws,peakAmp:()=>wo,pickEntry:()=>Xo,pitchToFreq:()=>po,pixelsToCommands:()=>ss,platformerReachable:()=>Vd,playerAction:()=>xn,playerIds:()=>Qd,playerInput:()=>Zd,pointQuery:()=>Ru,pollDirector:()=>Ad,polygonBox:()=>mu,poseKey:()=>Ht,progression:()=>ct,progressionPuzzle:()=>sr,proveCompletable:()=>Xd,proveFullCompletion:()=>Jd,pump:()=>$m,quantizeAngle:()=>Hr,race:()=>vd,rad2deg:()=>ml,radialGradient:()=>Iu,rampIssues:()=>ca,rampStats:()=>ua,rayCastRigid:()=>Du,raycastTiles:()=>Oi,reachableRegions:()=>Ra,reconstructPath:()=>Cd,recordTimeline:()=>jm,rectBlocked:()=>qe,rectContains:()=>dl,rectsOverlap:()=>hl,registerNode:()=>we,regularPolyPoints:()=>bi,regularPolygon:()=>Ku,relLuminance:()=>_e,remap:()=>ul,removeBody:()=>uu,removeJoint:()=>gu,renderAudioFilmstrip:()=>nd,renderFilmstrip:()=>td,renderSong:()=>vo,renderSound:()=>sn,renderToSVGString:()=>en,replay:()=>No,replaySession:()=>zo,resetNodeIds:()=>gr,resetZzfxWarnings:()=>im,resolveTracks:()=>En,resolveTuning:()=>fn,rigidStep:()=>Cu,rleDecode:()=>Ld,rleEncode:()=>Id,rms:()=>Dt,roomCenter:()=>ao,rootless:()=>an,runBrowser:()=>bn,runBrowserNet:()=>nh,runFeelGates:()=>Gm,runHeadless:()=>cd,runStudio:()=>sh,salienceIssues:()=>Zs,sampleClip:()=>kl,sampleGradient:()=>Wr,samplePose:()=>Mn,sampleTrack:()=>Ye,scaleMidis:()=>Vn,scalePitchClasses:()=>bo,scatter:()=>bs,scatterCells:()=>uc,scoreTrack:()=>Kc,screenRect:()=>Mm,scriptToFrames:()=>Ys,scriptedPlaythrough:()=>Lm,scrubTo:()=>cr,serializeSnapshot:()=>xa,series:()=>Xm,setOverlayHost:()=>un,setScreenObserver:()=>Zn,settings:()=>ze,shadeHex:()=>yr,shadowDef:()=>Yr,shadowQuads:()=>Gr,shapeBBox:()=>Kr,shapeBox:()=>Wo,showScreen:()=>Do,signalHash:()=>xc,sleep:()=>gd,smoothClosedPath:()=>os,smoothOpenPath:()=>ec,smoothstep:()=>pr,snapAxis:()=>Ze,softClip:()=>lo,softClipInPlace:()=>mo,solidNeighbours:()=>oo,solve:()=>mt,solveFabrik:()=>Nr,solveJoint:()=>Jr,solveTwoBoneIK:()=>$r,songBeats:()=>Ps,songDuration:()=>qn,sortCommands:()=>Ke,spatialMix:()=>Uc,specFromZzfx:()=>sm,spectralCentroid:()=>Is,splitByLightLayer:()=>nt,spring:()=>yi,springStep:()=>xi,star:()=>Qu,steer2D:()=>Am,stepPlatformer:()=>Ql,stereoDuration:()=>gc,stereoFrames:()=>bc,stereoWidth:()=>Bs,subSeed:()=>wa,telegraphIssues:()=>zm,terrainHeight:()=>so,terrainSlice:()=>mc,textBox:()=>sa,textToCommands:()=>ds,tileAt:()=>pe,tileAtPoint:()=>Vl,tileCenter:()=>va,tilemapFromAscii:()=>_r,toggleFullscreen:()=>Io,transpose:()=>Mc,typewriterCount:()=>ms,unpackVarints:()=>Nd,vadd:()=>rl,validateWorld:()=>Kd,valueNoise:()=>gs,vdist:()=>al,vdot:()=>sl,vec2:()=>nl,vlen:()=>pi,vnorm:()=>ll,voiceLead:()=>Pt,vscale:()=>il,vsub:()=>ol,wait:()=>Im,waitFor:()=>yd,wakeBody:()=>ye,wangTile:()=>Li,warnCommandOnce:()=>Ct,weatherEnvelope:()=>wi,weightedIndex:()=>Uo,weightedPick:()=>Sd,wipeStep:()=>Tm,withAlpha:()=>Dl,worldPoints:()=>ke,zcr:()=>Ds});var Wa=.6366197723675814,Ba=1.5707963267341256,za=6077100506506192e-26,_a=-.16666666666666632,Oa=.00833333333332249,Ga=-.0001984126982985795,Va=27557313707070068e-22,Ha=-25050760253406863e-24,qa=158969099521155e-24,ja=.0416666666666666,Ua=-.001388888888887411,Xa=2480158728947673e-20,Ja=-27557314351390663e-23,Ya=2087572321298175e-24,Ka=-11359647557788195e-27;function kn(t){let e=t*t;return t+t*e*(_a+e*(Oa+e*(Ga+e*(Va+e*(Ha+e*qa)))))}function Sn(t){let e=t*t;return 1-.5*e+e*e*(ja+e*(Ua+e*(Xa+e*(Ja+e*(Ya+e*Ka)))))}function mi(t){let e=Math.round(t*Wa),n=t-e*Ba-e*za;return{n:(e%4+4)%4,r:n}}function q(t){if(!Number.isFinite(t))return NaN;let{n:e,r:n}=mi(t);switch(e){case 0:return kn(n);case 1:return Sn(n);case 2:return-kn(n);default:return-Sn(n)}}function j(t){if(!Number.isFinite(t))return NaN;let{n:e,r:n}=mi(t);switch(e){case 0:return Sn(n);case 1:return-kn(n);case 2:return-Sn(n);default:return kn(n)}}var wn=[.4636476090008061,.7853981633974483,.982793723247329,1.5707963267948966],ci=[22698777452961687e-33,3061616997868383e-32,13903311031230998e-33,6123233995736766e-32],ve=[.3333333333333293,-.19999999999876483,.14285714272503466,-.11111110405462356,.09090887133436507,-.0769187620504483,.06661073137387531,-.058335701337905735,.049768779946159324,-.036531572744216916,.016285820115365782];function di(t){if(Number.isNaN(t))return NaN;if(!Number.isFinite(t))return t>0?wn[3]:-wn[3];let e=t<0||Object.is(t,-0)?-1:1,n=Math.abs(t);if(n>=1e19)return e*(wn[3]+ci[3]);let r=-1;if(n<.4375){if(n<1e-9)return t}else n<.6875?(r=0,n=(2*n-1)/(2+n)):n<1.1875?(r=1,n=(n-1)/(n+1)):n<2.4375?(r=2,n=(n-1.5)/(1+1.5*n)):(r=3,n=-1/n);let o=n*n,i=o*o,s=o*(ve[0]+i*(ve[2]+i*(ve[4]+i*(ve[6]+i*(ve[8]+i*ve[10]))))),a=i*(ve[1]+i*(ve[3]+i*(ve[5]+i*(ve[7]+i*ve[9]))));if(r<0)return e*(n-n*(s+a));let l=wn[r]-(n*(s+a)-ci[r]-n);return e*l}var Re=3.141592653589793;function Le(t,e){if(Number.isNaN(e)||Number.isNaN(t))return NaN;if(t===0&&e===0)return Object.is(e,-0)?Object.is(t,-0)?-Re:Re:Object.is(t,-0)?-0:0;if(e===0||!Number.isFinite(t)&&Number.isFinite(e))return t>0?Re/2:-Re/2;if(!Number.isFinite(e)){if(!Number.isFinite(t)){let r=e>0?Re/4:3*Re/4;return t>0?r:-r}return e>0?t<0||Object.is(t,-0)?-0:0:t<0||Object.is(t,-0)?-Re:Re}let n=di(t/e);return e>0?n:t<0||Object.is(t,-0)?n-Re:n+Re}var Qa=.6931471805599453;function fe(t){if(Number.isNaN(t))return NaN;if(t>=1024)return 1/0;if(t<=-1075)return 0;let e=Math.round(t),n=(t-e)*Qa,r=1,o=1;for(let i=1;i<=13;i++)r=r*n/i,o+=r;return o*2**e}function Je(t){return fe(t*hi)}function G(t,e){return Math.sqrt(t*t+e*e)}var Xe=new DataView(new ArrayBuffer(8)),Za=.6931471803691238,el=19082149292705877e-26;function dr(t){if(Number.isNaN(t)||t<0)return NaN;if(t===0)return-1/0;if(!Number.isFinite(t))return 1/0;Xe.setFloat64(0,t);let e=(Xe.getUint32(0)>>>20&2047)-1023;e===-1023&&(Xe.setFloat64(0,t*0x40000000000000),e=(Xe.getUint32(0)>>>20&2047)-1023-54),Xe.setUint32(0,Xe.getUint32(0)&1048575|1023<<20);let n=Xe.getFloat64(0);n>1.4142135623730951&&(n*=.5,e+=1);let r=(n-1)/(n+1),o=r*r,i=1+o*(.3333333333333333+o*(.2+o*(.14285714285714285+o*(.1111111111111111+o*(.09090909090909091+o*(.07692307692307693+o*(.06666666666666667+o*(.058823529411764705+o*.05263157894736842))))))));return e*Za+(2*r*i+e*el)}var tl=.4342944819032518,hi=1.4426950408889634,Ft=t=>dr(t)*tl,ft=t=>dr(t)*hi;function Pe(t,e){if(Number.isNaN(t)||Number.isNaN(e))return NaN;if(e===0)return 1;if(e===1)return t;if(Number.isInteger(e)&&Math.abs(e)<=1024){let n=Math.abs(e),r=t,o=1;for(;n>0;)n&1&&(o*=r),n>>=1,n>0&&(r*=r);return e<0?1/o:o}return t>0?fe(e*ft(t)):t===0?e>0?0:1/0:NaN}var nl=(t=0,e=0)=>({x:t,y:e}),rl=(t,e)=>({x:t.x+e.x,y:t.y+e.y}),ol=(t,e)=>({x:t.x-e.x,y:t.y-e.y}),il=(t,e)=>({x:t.x*e,y:t.y*e}),sl=(t,e)=>t.x*e.x+t.y*e.y,pi=t=>G(t.x,t.y),al=(t,e)=>G(t.x-e.x,t.y-e.y);function ll(t){let e=pi(t);return e===0?{x:0,y:0}:{x:t.x/e,y:t.y/e}}var Q=(t,e,n)=>t<e?e:t>n?n:t,$e=(t,e,n)=>t+(e-t)*n,hr=(t,e,n)=>t===e?0:(n-t)/(e-t),ul=(t,e,n,r,o)=>$e(r,o,hr(e,n,t)),pr=(t,e,n)=>{let r=Q(t===e?n<t?0:1:hr(t,e,n),0,1);return r*r*(3-2*r)},Z=Math.PI*2,cl=t=>t*Math.PI/180,ml=t=>t*180/Math.PI;function dl(t,e){return e.x>=t.x&&e.x<=t.x+t.w&&e.y>=t.y&&e.y<=t.y+t.h}function hl(t,e){return t.x<e.x+e.w&&t.x+t.w>e.x&&t.y<e.y+e.h&&t.y+t.h>e.y}var oe={a:1,b:0,c:0,d:1,e:0,f:0};function Ne(t,e){return{a:t.a*e.a+t.c*e.b,b:t.b*e.a+t.d*e.b,c:t.a*e.c+t.c*e.d,d:t.b*e.c+t.d*e.d,e:t.a*e.e+t.c*e.f+t.e,f:t.b*e.e+t.d*e.f+t.f}}function Ge(t,e,n){let r=j(e),o=q(e);return{a:r*n.x,b:o*n.x,c:-o*n.y,d:r*n.y,e:t.x,f:t.y}}function bt(t,e){return{x:t.a*e.x+t.c*e.y+t.e,y:t.b*e.x+t.d*e.y+t.f}}function De(t){let e=t.a*t.d-t.b*t.c;if(e===0)return{...oe};let n=1/e;return{a:t.d*n,b:-t.b*n,c:-t.c*n,d:t.a*n,e:(t.c*t.f-t.d*t.e)*n,f:(t.b*t.e-t.a*t.f)*n}}function pl(t){let{tileW:e,tileH:n}=t,r=t.origin?{x:t.origin.x,y:t.origin.y}:{x:0,y:0},o=t.elevStep??n,i=e/2,s=n/2;return{tileW:e,tileH:n,origin:r,elevStep:o,toScreen(a,l,u=0){return{x:r.x+(a-l)*i,y:r.y+(a+l)*s-u*o}},toGrid(a,l){let u=(a-r.x)/i,c=(l-r.y)/s;return{x:(u+c)/2,y:(c-u)/2}}}}function fl(t){let e=t>>>0;return()=>{e=e+2654435769>>>0;let n=e;return n=Math.imul(n^n>>>16,569420461),n=Math.imul(n^n>>>15,1935289751),(n^n>>>15)>>>0}}var ue=class t{s0;s1;s2;s3;constructor(e=0){if(typeof e=="number"){let n=fl(e===0?305441741:e);this.s0=n(),this.s1=n(),this.s2=n(),this.s3=n()}else[this.s0,this.s1,this.s2,this.s3]=e.s}next(){let e=Math.imul(this.rotl(Math.imul(this.s1,5),7),9)>>>0,n=this.s1<<9>>>0;return this.s2^=this.s0,this.s3^=this.s1,this.s1^=this.s2,this.s0^=this.s3,this.s2=(this.s2^n)>>>0,this.s3=this.rotl(this.s3,11),e>>>0}rotl(e,n){return(e<<n|e>>>32-n)>>>0}float(){return this.next()/4294967296}range(e,n){return e+this.float()*(n-e)}int(e){return Math.floor(this.float()*e)}intRange(e,n){return e+this.int(n-e+1)}chance(e){return this.float()<e}pick(e){return e[this.int(e.length)]}shuffle(e){for(let n=e.length-1;n>0;n--){let r=this.int(n+1);[e[n],e[r]]=[e[r],e[n]]}return e}split(e=0){let n=(this.s0^Math.imul(e+1,2654435769))>>>0,r=new t(n^this.s3);return this.next(),r}getState(){return{s:[this.s0,this.s1,this.s2,this.s3]}}setState(e){[this.s0,this.s1,this.s2,this.s3]=e.s}},fr=new DataView(new ArrayBuffer(8));function bl(...t){let e=2654435769;for(let n of t)fr.setFloat64(0,n),e=Math.imul(e^fr.getUint32(0),2246822507)>>>0,e=(e^e>>>13)>>>0,e=Math.imul(e^fr.getUint32(4),3266489909)>>>0,e=(e^e>>>16)>>>0;return e=Math.imul(e^e>>>16,2246822507)>>>0,e=Math.imul(e^e>>>13,3266489909)>>>0,e=(e^e>>>16)>>>0,e/4294967296}function br(t){let e=2166136261;for(let n=0;n<t.length;n++)e^=t.charCodeAt(n),e=Math.imul(e,16777619);return e>>>0}var At=class{stepMs;dt;maxFrameMs;accumulator=0;_frame=0;_simTimeMs=0;constructor(e={}){let n=e.hz??60;this.stepMs=1e3/n,this.dt=1/n,this.maxFrameMs=e.maxFrameMs??250}advance(e){this.accumulator+=Math.min(e,this.maxFrameMs);let n=0;for(;this.accumulator>=this.stepMs;)this.accumulator-=this.stepMs,n++;return n}tick(){this._frame++,this._simTimeMs+=this.stepMs}get alpha(){return this.accumulator/this.stepMs}get frame(){return this._frame}get simTimeMs(){return this._simTimeMs}get simTimeSec(){return this._simTimeMs/1e3}getState(){return{accumulator:this.accumulator,frame:this._frame,simTimeMs:this._simTimeMs}}setState(e){this.accumulator=e.accumulator,this._frame=e.frame,this._simTimeMs=e.simTimeMs}};var gt=class{listeners=[];connect(e){return this.listeners.push(e),()=>this.disconnect(e)}once(e){let n=this.connect(r=>{n(),e(r)});return n}disconnect(e){let n=this.listeners.indexOf(e);n>=0&&this.listeners.splice(n,1)}emit(e){for(let n of this.listeners.slice())n(e)}get count(){return this.listeners.length}clear(){this.listeners.length=0}},Wt=class{signals=new Map;signalFor(e){let n=this.signals.get(e);return n||(n=new gt,this.signals.set(e,n)),n}on(e,n){return this.signalFor(e).connect(n)}once(e,n){return this.signalFor(e).once(n)}emit(e,n){this.signalFor(e).emit(n)}clear(){this.signals.clear()}};function gl(t){return Number.isNaN(t)?"NaN":t===1/0?"Inf":t===-1/0?"-Inf":t===0?"0":t.toString()}function Bt(t){let e=2166136261,n=2166136261,r=s=>{for(let a=0;a<s.length;a++){let l=s.charCodeAt(a);e=Math.imul(e^l,16777619)>>>0,n=Math.imul(n^(l<<3|l>>>5),2246822519)>>>0}},o=s=>{if(s===null)return r("n");if(s===void 0)return r("u");switch(typeof s){case"number":return r("#"+gl(s));case"boolean":return r(s?"t":"f");case"string":return r('"'+s);case"object":{if(Array.isArray(s)){r("[");for(let u of s)o(u);r("]");return}let a=s,l=Object.keys(a).filter(u=>a[u]!==void 0).sort();r("{");for(let u of l)r(u+":"),o(a[u]);r("}");return}default:r("?")}};o(t);let i=s=>s.toString(16).padStart(8,"0");return i(e)+i(n)}var fi=0;function gr(t=0){fi=t}var _=class{id;name;type="Node";pos;rotation;scale;z;visible;cosmetic=!1;pauseMode="inherit";screenSpace=!1;pivot;parent=null;children=[];world=null;onUpdate;behaviors=[];signals=new Map;_ready=!1;_freed=!1;constructor(e={}){this.id=`n${fi++}`,this.name=e.name??this.constructor.name,this.pos=e.pos?{...e.pos}:{x:0,y:0},this.rotation=e.rotation??0,this.scale=e.scale?{...e.scale}:{x:1,y:1},this.z=e.z??0,this.visible=e.visible??!0}get x(){return this.pos.x}set x(e){this.pos.x=e}get y(){return this.pos.y}set y(e){this.pos.y=e}addChild(e){return e.parent=this,this.children.push(e),this.world&&this._ready&&e.enterTree(this.world),e}removeChild(e){let n=this.children.indexOf(e);n>=0&&(this.children.splice(n,1),e.parent=null)}free(){this.world?.requestFree(this)}clearChildren(){for(let e of this.children.slice())e.exitTree(),this.removeChild(e)}find(e){if(this.name===e)return this;for(let n of this.children){let r=n.find(e);if(r)return r}return null}findOfType(e){if(this instanceof e)return this;for(let n of this.children){let r=n.findOfType(e);if(r)return r}return null}query(e,n=[]){this.type===e&&n.push(this);for(let r of this.children)r.query(e,n);return n}addBehavior(e){return this.behaviors.push(e),this._ready&&e.ready?.(this),this}signal(e){let n=this.signals.get(e);return n||(n=new gt,this.signals.set(e,n)),n}emit(e,n){this.signals.get(e)?.emit(n)}enterTree(e){if(this.world=e,!this._ready){this._ready=!0,this.onReady();for(let n of this.behaviors)n.ready?.(this)}for(let n of this.children)n.enterTree(e)}updateTree(e,n=e,r="pausable",o=!1){if(this._freed)return;let i=this.pauseMode==="inherit"?r:this.pauseMode;if(i==="always"||i==="pausable"&&!o){let a=this.world,l=i==="always"?n:e;for(let u of this.behaviors)u.update?.(this,l,a);this.onUpdate?.(this,l,a),this.onProcess(l)}for(let a of this.children.slice())a.updateTree(e,n,i,o)}exitTree(){for(let e of this.behaviors)e.exit?.(this);this.onExit();for(let e of this.children.slice())e.exitTree();this._freed=!0}get isFreed(){return this._freed}localTransform(){let e=Ge(this.pos,this.rotation,this.scale);return this.pivot?Ne(e,Ge({x:-this.pivot.x,y:-this.pivot.y},0,{x:1,y:1})):e}worldTransform(){let e=this.localTransform();return this.parent?Ne(this.parent.worldTransform(),e):e}collectDraw(e,n=oe){if(!this.visible)return;let r=Ne(this.screenSpace?oe:n,this.localTransform()),o=e.length;this.draw(e,r);for(let i of this.children)i.collectDraw(e,r);if(this.screenSpace)for(let i=o;i<e.length;i++){let s=e[i];(s.layer??0)<1&&(s.layer=1)}}draw(e,n){}onReady(){}onProcess(e){}onExit(){}serialize(){return{type:this.type,name:this.name,pos:{...this.pos},rotation:this.rotation,scale:{...this.scale},z:this.z,visible:this.visible,...this.pivot?{pivot:{...this.pivot}}:{},props:{...this.serializeProps(),...this.pauseMode!=="inherit"?{pauseMode:this.pauseMode}:{},...this.screenSpace?{screenSpace:!0}:{}},children:this.children.filter(e=>!e.cosmetic).map(e=>e.serialize())}}serializeProps(){return{}}applyProps(e){}};function Cn(t,e){return[0,-e/2,t/2,0,0,e/2,-t/2,0]}function bi(t,e,n=0){let r=[];for(let o=0;o<t;o++){let i=n-Z/4+Z*o/t;r.push(j(i)*e,q(i)*e)}return r}var zt=class extends _{type="Sprite";shape;paint;constructor(e){super(e),this.shape=e.shape,this.paint={fill:e.fill,stroke:e.stroke,strokeWidth:e.strokeWidth,opacity:e.opacity,round:e.round,gradient:e.gradient,shadow:e.shadow,lineDash:e.lineDash}}draw(e,n){let r=this.paint,o={transform:n,z:this.z,...r};switch(this.shape.kind){case"rect":{let i=this.shape.anchor==="topLeft";e.push({kind:"rect",x:i?0:-this.shape.w/2,y:i?0:-this.shape.h/2,w:this.shape.w,h:this.shape.h,r:this.shape.r,...o});break}case"circle":e.push({kind:"circle",cx:0,cy:0,radius:this.shape.radius,...o});break;case"ellipse":e.push({kind:"ellipse",cx:0,cy:0,rx:this.shape.rx,ry:this.shape.ry,...o});break;case"arc":e.push({kind:"arc",cx:0,cy:0,radius:this.shape.radius,start:this.shape.start,end:this.shape.end,sector:this.shape.sector,...o});break;case"poly":e.push({kind:"poly",points:this.shape.points,closed:this.shape.closed??!0,...o});break;case"path":e.push({kind:"path",d:this.shape.d,...o});break;case"glyph":e.push({kind:"text",text:this.shape.char,x:0,y:0,size:this.shape.size,align:"center",...o});break;case"diamond":e.push({kind:"poly",points:Cn(this.shape.w,this.shape.h),closed:!0,...o});break;case"regularPoly":e.push({kind:"poly",points:bi(this.shape.sides,this.shape.r,this.shape.rotation??0),closed:!0,...o});break}}serializeProps(){return{shape:this.shape,paint:this.paint}}applyProps(e){e.shape&&(this.shape=e.shape),e.paint&&(this.paint=e.paint)}},_t=class extends _{type="Text";text;size;font;align;weight;paint;constructor(e){super(e),this.text=e.text,this.size=e.size??24,this.font=e.font,this.align=e.align??"left",this.weight=e.weight,this.paint={fill:e.fill??"#000",stroke:e.stroke,strokeWidth:e.strokeWidth,opacity:e.opacity}}draw(e,n){e.push({kind:"text",text:this.text,x:0,y:0,size:this.size,font:this.font,align:this.align,weight:this.weight,transform:n,z:this.z,...this.paint})}serializeProps(){return{text:this.text,size:this.size,align:this.align,paint:this.paint}}applyProps(e){typeof e.text=="string"&&(this.text=e.text),typeof e.size=="number"&&(this.size=e.size),e.align&&(this.align=e.align),e.paint&&(this.paint=e.paint)}},Ot=class extends _{type="Camera2D";zoom;current;constructor(e={}){super(e),this.zoom=e.zoom??1,this.current=e.current??!0}onReady(){this.current&&(this.world.activeCamera=this)}serializeProps(){return{zoom:this.zoom,current:this.current}}applyProps(e){typeof e.zoom=="number"&&(this.zoom=e.zoom),typeof e.current=="boolean"&&(this.current=e.current)}},Gt=class extends _{type="Timer";duration;oneShot;remaining;running;constructor(e){super(e),this.duration=e.duration,this.oneShot=e.oneShot??!0,this.remaining=e.duration,this.running=e.autostart??!0}start(e){e!==void 0&&(this.duration=e),this.remaining=this.duration,this.running=!0}stop(){this.running=!1}get timeLeft(){return this.remaining}onProcess(e){this.running&&(this.remaining-=e,this.remaining<=0&&(this.emit("timeout",void 0),this.oneShot?this.running=!1:this.remaining+=this.duration))}get timeout(){return this.signal("timeout")}serializeProps(){return{duration:this.duration,oneShot:this.oneShot,remaining:this.remaining,running:this.running}}applyProps(e){typeof e.duration=="number"&&(this.duration=e.duration),typeof e.oneShot=="boolean"&&(this.oneShot=e.oneShot),typeof e.remaining=="number"&&(this.remaining=e.remaining),typeof e.running=="boolean"&&(this.running=e.running)}};function yr(t,e){let n=t.replace("#","");if(n.length===3&&(n=n[0]+n[0]+n[1]+n[1]+n[2]+n[2]),n.length!==6)return t;let r=o=>Math.round(Math.min(255,Math.max(0,parseInt(n.slice(o,o+2),16)*e))).toString(16).padStart(2,"0");return`#${r(0)}${r(2)}${r(4)}`}var xr=class extends _{type="IsoPrism";tileW;tileH;height;fill;topPaint;leftPaint;rightPaint;stroke;strokeWidth;opacity;constructor(e){super(e),this.tileW=e.tileW,this.tileH=e.tileH,this.height=e.height,this.fill=e.fill,this.topPaint=e.top,this.leftPaint=e.left,this.rightPaint=e.right,this.stroke=e.stroke,this.strokeWidth=e.strokeWidth,this.opacity=e.opacity}draw(e,n){let r=this.tileW,o=this.tileH,i=this.height,s={stroke:this.stroke,strokeWidth:this.strokeWidth,opacity:this.opacity},a=this.topPaint??{fill:this.fill},l=this.leftPaint??{fill:yr(this.fill,.65)},u=this.rightPaint??{fill:yr(this.fill,.85)},c={transform:n,z:this.z};i>0&&(e.push({kind:"poly",closed:!0,points:[-r/2,0,0,o/2,0,o/2-i,-r/2,-i],...s,...l,...c}),e.push({kind:"poly",closed:!0,points:[0,o/2,r/2,0,r/2,-i,0,o/2-i],...s,...u,...c}));let m=Cn(r,o).map((d,h)=>h%2===1?d-i:d);e.push({kind:"poly",closed:!0,points:m,...s,...a,...c})}serializeProps(){return{tileW:this.tileW,tileH:this.tileH,height:this.height,fill:this.fill}}applyProps(e){typeof e.tileW=="number"&&(this.tileW=e.tileW),typeof e.tileH=="number"&&(this.tileH=e.tileH),typeof e.height=="number"&&(this.height=e.height),typeof e.fill=="string"&&(this.fill=e.fill)}},vr=class extends _{type="DepthSort";key;depthScale;cosmetic=!0;constructor(e){super(e),this.key=e.key,this.depthScale=e.depthScale??1}collectDraw(e,n){for(let r of this.children)r.z=this.key(r)*this.depthScale;super.collectDraw(e,n)}};var wr=class extends _{type="CameraController";cosmetic=!0;target;cameraRef;deadzone;smooth;bounds;constructor(e={}){super(e),this.target=e.target??null,this.cameraRef=e.camera??null;let n=e.deadzone??0;this.deadzone=typeof n=="number"?{x:n,y:n}:{...n},this.smooth=e.smooth??.15,this.bounds=e.bounds?{...e.bounds}:null}follow(e){return this.target=e,this}host(){return this.world??null}camera(){return this.cameraRef??this.host()?.activeCamera??null}desired(e){let n=this.host(),r=this.target.worldTransform(),o=e.pos.x,i=e.pos.y,s=r.e-e.pos.x,a=r.f-e.pos.y;if(Math.abs(s)>this.deadzone.x&&(o=r.e-Math.sign(s)*this.deadzone.x),Math.abs(a)>this.deadzone.y&&(i=r.f-Math.sign(a)*this.deadzone.y),this.bounds){let l=e.zoom||1,u=n.width/2/l,c=n.height/2/l,m=this.bounds.minX+u,d=this.bounds.maxX-u,h=this.bounds.minY+c,p=this.bounds.maxY-c;o=m>d?(this.bounds.minX+this.bounds.maxX)/2:Q(o,m,d),i=h>p?(this.bounds.minY+this.bounds.maxY)/2:Q(i,h,p)}return{x:o,y:i}}snap(){let e=this.camera();if(!e||!this.target||!this.host())return;let n=this.desired(e);e.pos.x=n.x,e.pos.y=n.y}onReady(){this.snap()}onProcess(){let e=this.camera();if(!e||!this.target||!this.host())return;let n=this.desired(e),r=Q(this.smooth,0,1);e.pos.x=$e(e.pos.x,n.x,r),e.pos.y=$e(e.pos.y,n.y,r)}};var kr=class extends _{type="ParallaxLayer";cosmetic=!0;factor;constructor(e){super(e),this.factor=e.factor}sync(){let e=this.world?.activeCamera;e&&(this.pos.x=e.pos.x*(1-this.factor),this.pos.y=e.pos.y*(1-this.factor))}onReady(){this.sync()}onProcess(){this.sync()}};var Sr=class{constructor(e,n){this.parent=e;this.make=n}parent;make;items=[];used=0;begin(){this.used=0}get(){this.used===this.items.length&&this.items.push(this.parent.addChild(this.make()));let e=this.items[this.used++];return e.visible=!0,e}end(){for(let e=this.used;e<this.items.length;e++)this.items[e].visible=!1}get liveCount(){return this.used}};var yl=(t,e,n,r)=>$e(e,t,Je(-n*r)),yi=(t=0)=>({value:t,vel:0});function xi(t,e,n,r){let o=Je(-n*r),i=t.value-e,s=t.vel+n*i;return t.value=e+(i+s*r)*o,t.vel=(t.vel-s*n*r)*o,t}function xl(t=0,e=.25){let n=4/Math.max(1e-4,e),r=yi(t);return(o,i)=>xi(r,o,n,i).value}var gi=t=>t*t,Cr=t=>t*t*t,Fe={linear:t=>t,quadIn:t=>t*t,quadOut:t=>1-(1-t)*(1-t),quadInOut:t=>t<.5?2*t*t:1-gi(-2*t+2)/2,cubicIn:t=>t*t*t,cubicOut:t=>1-Cr(1-t),cubicInOut:t=>t<.5?4*t*t*t:1-Cr(-2*t+2)/2,sineIn:t=>1-j(t*Math.PI/2),sineOut:t=>q(t*Math.PI/2),sineInOut:t=>-(j(Math.PI*t)-1)/2,backOut:t=>1+2.70158*Cr(t-1)+1.70158*gi(t-1),elasticOut:t=>{let e=2*Math.PI/3;return t===0?0:t===1?1:fe(-10*t)*q((t*10-.75)*e)+1},bounceOut:t=>t<1/2.75?7.5625*t*t:t<2/2.75?7.5625*(t-=1.5/2.75)*t+.75:t<2.5/2.75?7.5625*(t-=2.25/2.75)*t+.9375:7.5625*(t-=2.625/2.75)*t+.984375},Vt=class extends _{type="AnimationPlayer";tracks=[];to(e,n,r,o,i="cubicOut",s={}){return this.tracks.push({apply:e,from:n,to:r,duration:Math.max(1e-6,o),elapsed:0,ease:typeof i=="function"?i:Fe[i]??Fe.linear,delay:s.delay??0,onDone:s.onDone}),this}get active(){return this.tracks.length>0}get finished(){return this.signal("finished")}onProcess(e){if(this.tracks.length!==0){for(let n=this.tracks.length-1;n>=0;n--){let r=this.tracks[n];if(r.delay>0){r.delay-=e;continue}r.elapsed+=e;let o=Q(r.elapsed/r.duration,0,1);r.apply(r.from+(r.to-r.from)*r.ease(o)),o>=1&&(r.onDone?.(),this.tracks.splice(n,1))}this.tracks.length===0&&this.emit("finished",void 0)}}};var Tr=class extends _{type="Particles";pool=[];rng;maxParticles;constructor(e={}){super(e),this.cosmetic=!0,this.rng=new ue(e.seed??7),this.maxParticles=e.maxParticles??512}burst(e,n,r){let o=this.rng;for(let i=0;i<e;i++){let s=r.angle!==void 0?r.angle+(o.float()-.5)*(r.spread??.6):o.float()*Z,a=r.speedMin+o.float()*(r.speedMax-r.speedMin),l={x:n.x,y:n.y,vx:j(s)*a,vy:q(s)*a,life:0,maxLife:r.lifeMin+o.float()*(r.lifeMax-r.lifeMin),size:r.sizeMin+o.float()*(r.sizeMax-r.sizeMin),color:r.colors[o.int(r.colors.length)]};this.pool.length>=this.maxParticles&&this.pool.shift(),this.pool.push(l)}this.gravity=r.gravity??0,this.drag=r.drag??0,this.shrink=r.shrink??!0}gravity=0;drag=0;shrink=!0;emitRate=0;emitAcc=0;emitStyle=null;emitOrigin={x:0,y:0};emit(e,n){if(typeof e=="string"){super.emit(e,n);return}this.emitRate=e,this.emitAcc=0;let r=n;if(r){let{at:o,...i}=r;this.emitStyle=i,this.emitOrigin=o?{x:o.x,y:o.y}:{x:0,y:0}}else this.emitStyle||(this.emitStyle=vi.burst())}stopEmit(){this.emitRate=0,this.emitAcc=0}onProcess(e){let n=Math.max(0,1-this.drag*e),r=0;for(let o of this.pool)o.life+=e,!(o.life>=o.maxLife)&&(o.vy+=this.gravity*e,o.vx*=n,o.vy*=n,o.x+=o.vx*e,o.y+=o.vy*e,this.pool[r++]=o);if(this.pool.length=r,this.emitRate>0&&this.emitStyle){this.emitAcc+=this.emitRate*e;let o=Math.floor(this.emitAcc);o>0&&(this.emitAcc-=o,this.burst(o,this.emitOrigin,this.emitStyle))}}draw(e,n){for(let r of this.pool){let o=1-r.life/r.maxLife;e.push({kind:"circle",cx:r.x,cy:r.y,radius:this.shrink?r.size*o:r.size,fill:r.color,opacity:Math.min(1,o*2),transform:n,z:this.z,transient:!0})}}get liveCount(){return this.pool.length}},vi={dust:(t=["#c8c2b6","#a09a8c"])=>({colors:t,sizeMin:2,sizeMax:4,speedMin:30,speedMax:90,lifeMin:.2,lifeMax:.45,gravity:300,drag:3,shrink:!0}),burst:(t=["#ffd75e","#ff9d47","#fff2c9"])=>({colors:t,sizeMin:2,sizeMax:5,speedMin:120,speedMax:320,lifeMin:.25,lifeMax:.6,drag:4,shrink:!0}),hit:(t=["#ff5e5e","#ffd0d0"])=>({colors:t,sizeMin:2,sizeMax:4,speedMin:160,speedMax:380,lifeMin:.15,lifeMax:.35,drag:6,shrink:!0}),sparkle:(t=["#9ef7ff","#e8fdff","#4ed8e8"])=>({colors:t,sizeMin:1.5,sizeMax:3.5,speedMin:20,speedMax:70,lifeMin:.4,lifeMax:.9,gravity:-40,drag:2,shrink:!0})};function wi(t,e){if(e.length===0)return 1;if(t<=e[0].time)return e[0].intensity;for(let n=1;n<e.length;n++)if(t<=e[n].time){let r=e[n-1],o=e[n];return r.intensity+(o.intensity-r.intensity)*pr(r.time,o.time,t)}return e[e.length-1].intensity}var Mr=class extends _{type="AmbientField";rng;field=[];time=0;style;width;height;envelope;constructor(e){super(e),this.cosmetic=!0,this.rng=new ue(e.seed??11),this.width=e.width,this.height=e.height,this.style=e.style,this.envelope=e.envelope;let n=e.count??120,r=this.style;for(let o=0;o<n;o++)this.field.push({x:this.rng.float()*this.width,y:this.rng.float()*this.height,size:r.sizeMin+this.rng.float()*(r.sizeMax-r.sizeMin),color:r.colors[this.rng.int(r.colors.length)],phase:this.rng.float()*Z,depth:.5+this.rng.float()*.5})}intensity(){return this.envelope?wi(this.time,this.envelope):1}onProcess(e){this.time+=e;let n=this.style,r=n.windX??0,o=this.width,i=this.height;for(let s of this.field)s.y+=n.fallY*s.depth*e,s.x+=r*e,s.y>i?s.y-=i:s.y<0&&(s.y+=i),s.x>o?s.x-=o:s.x<0&&(s.x+=o)}draw(e,n){let r=this.style,o=this.intensity();if(o<=0)return;let i=Math.round(this.field.length*o),s=r.swayAmp??0,a=r.swayFreq??0;for(let l=0;l<i;l++){let u=this.field[l],c=s!==0?q(this.time*a*Z+u.phase)*s:0,m=u.x+c;if(r.streak){let d=r.streakLen??r.fallY*.03;e.push({kind:"poly",points:[m,u.y,m,u.y+d],closed:!1,stroke:u.color,strokeWidth:u.size,opacity:o,transform:n,z:this.z,transient:!0})}else e.push({kind:"circle",cx:m,cy:u.y,radius:u.size,fill:u.color,opacity:o,transform:n,z:this.z,transient:!0})}}get liveCount(){return this.field.length}},vl={snow:(t=["#ffffff","#e8f0f8","#cdd9e6"])=>({colors:t,sizeMin:1.5,sizeMax:3.5,windX:8,fallY:42,swayAmp:14,swayFreq:.25}),rain:(t=["#9fb4c8","#c3d2e0"])=>({colors:t,sizeMin:1,sizeMax:1.8,windX:-40,fallY:620,streak:!0,streakLen:16}),ash:(t=["#6b6b6b","#8a8580","#3d3a36"])=>({colors:t,sizeMin:1,sizeMax:2.5,windX:14,fallY:26,swayAmp:20,swayFreq:.18})},Rr=class extends _{type="Shaker";rng;trauma=0;amplitude;decay;constructor(e={}){super(e),this.cosmetic=!0,this.rng=new ue(e.seed??99),this.amplitude=e.amplitude??14,this.decay=e.decay??2.6}addTrauma(e){this.trauma=Math.min(1,this.trauma+e)}onProcess(e){this.trauma=Math.max(0,this.trauma-this.decay*e);let n=this.trauma*this.trauma*this.amplitude;this.pos.x=(this.rng.float()*2-1)*n,this.pos.y=(this.rng.float()*2-1)*n}};var Pr=class extends _{type="FloatingText";pool=[];rng;maxPopups;constructor(e={}){super(e),this.cosmetic=!0,this.rng=new ue(e.seed??31),this.maxPopups=e.maxPopups??128}pop(e,n,r){let o=r.jitter??0,i={x:n.x+(this.rng.float()-.5)*o*.1,y:n.y,vx:(this.rng.float()-.5)*o,vy:-(r.rise??60),life:0,maxLife:Math.max(.05,r.life??.9),text:e,color:r.color,size:r.size??20,font:r.font,weight:r.weight,align:r.align??"center",fade:Q(r.fade??.4,0,1)};this.gravity=r.gravity??0,this.pool.length>=this.maxPopups&&this.pool.shift(),this.pool.push(i)}gravity=0;onProcess(e){let n=0;for(let r of this.pool)r.life+=e,!(r.life>=r.maxLife)&&(r.vy+=this.gravity*e,r.x+=r.vx*e,r.y+=r.vy*e,this.pool[n++]=r);this.pool.length=n}draw(e,n){for(let r of this.pool){let o=r.life/r.maxLife,i=1-r.fade,s=o<i?1:Q(1-(o-i)/Math.max(1e-4,r.fade),0,1);e.push({kind:"text",text:r.text,x:r.x,y:r.y,size:r.size,font:r.font,weight:r.weight,align:r.align,fill:r.color,opacity:s,transform:n,z:this.z,transient:!0})}}get liveCount(){return this.pool.length}},wl={damage:(t="#e14b4b")=>({color:t,size:22,weight:700,rise:70,gravity:120,life:.8,jitter:40,fade:.4}),crit:(t="#ffb020")=>({color:t,size:32,weight:800,rise:100,gravity:160,life:1,jitter:60,fade:.35}),heal:(t="#4bb06a")=>({color:t,size:20,weight:700,rise:55,gravity:40,life:1,jitter:20,fade:.5}),label:(t="#3d3323")=>({color:t,size:18,weight:600,rise:40,gravity:0,life:1.2,jitter:0,fade:.5})};var Dr=class extends _{type="VerletChain";gravity;damping;iterations;pinTail;stroke;strokeWidth;taper;tailTarget=null;segments;segmentLength;px;py;prevx;prevy;local;initialized=!1;impX=0;impY=0;constructor(e){super(e),this.cosmetic=!0,this.segments=Math.max(1,Math.floor(e.segments)),this.segmentLength=e.length/this.segments,this.gravity=e.gravity?{...e.gravity}:{x:0,y:600},this.damping=e.damping??.985,this.iterations=Math.max(1,e.iterations??3),this.pinTail=e.pinTail??!1,this.stroke=e.stroke??"#333",this.strokeWidth=e.strokeWidth??3,this.taper=e.taper??!1;let n=this.segments+1;this.px=new Float64Array(n),this.py=new Float64Array(n),this.prevx=new Float64Array(n),this.prevy=new Float64Array(n),this.local=[];for(let r=0;r<n;r++)this.local.push({x:0,y:r*this.segmentLength})}get points(){return this.local}segmentAngle(e){let n=this.local[e],r=this.local[e+1];return Le(r.y-n.y,r.x-n.x)}impulse(e){this.impX+=e.x,this.impY+=e.y}onProcess(e){let n=this.worldTransform(),r=n.e,o=n.f,i=this.segments+1,s=this.px,a=this.py,l=this.prevx,u=this.prevy;if(!this.initialized){for(let x=0;x<i;x++)s[x]=r,a[x]=o+x*this.segmentLength,l[x]=s[x],u[x]=a[x];this.initialized=!0}let c=this.pinTail&&this.tailTarget!==null,m=0,d=0;if(c){let x=this.tailTarget;m=n.a*x.x+n.c*x.y+n.e,d=n.b*x.x+n.d*x.y+n.f}let h=this.gravity.x*e*e,p=this.gravity.y*e*e,f=this.impX*e,g=this.impY*e,k=this.damping,v=i-1;for(let x=1;x<i;x++){if(c&&x===v)continue;let b=s[x],w=a[x];s[x]=b+(b-l[x])*k+h+f,a[x]=w+(w-u[x])*k+p+g,l[x]=b,u[x]=w}this.impX=0,this.impY=0;let M=this.segmentLength;for(let x=0;x<this.iterations;x++){s[0]=r,a[0]=o,c&&(s[v]=m,a[v]=d);for(let b=0;b<v;b++){let w=s[b+1]-s[b],C=a[b+1]-a[b],E=Math.sqrt(w*w+C*C);if(E===0)continue;let R=(E-M)/E,S=b===0,T=c&&b+1===v;if(S&&T)continue;let L=S?0:T?1:.5,H=T?0:S?1:.5;s[b]+=w*R*L,a[b]+=C*R*L,s[b+1]-=w*R*H,a[b+1]-=C*R*H}}s[0]=r,a[0]=o,c&&(s[v]=m,a[v]=d);let I=De(n);for(let x=0;x<i;x++){let b=this.local[x],w=s[x],C=a[x];b.x=I.a*w+I.c*C+I.e,b.y=I.b*w+I.d*C+I.f}}draw(e,n){let r=this.local.length;if(r<2)return;if(this.taper){for(let i=0;i<r-1;i++){let s=this.local[i],a=this.local[i+1],l=1-i/(r-1);e.push({kind:"poly",points:[s.x,s.y,a.x,a.y],closed:!1,stroke:this.stroke,strokeWidth:Math.max(.5,this.strokeWidth*l),round:!0,transform:n,z:this.z,transient:!0})}return}let o=[];for(let i of this.local)o.push(i.x,i.y);e.push({kind:"poly",points:o,closed:!1,stroke:this.stroke,strokeWidth:this.strokeWidth,round:!0,transform:n,z:this.z,transient:!0})}};var ki=["x","y","rotation","scaleX","scaleY","opacity"];function Ae(t,e){let n=t.duration;if(n<=0)return 0;if(t.loop==="once")return e<0?0:e>n?n:e;if(t.loop==="loop"){let i=e%n;return i<0?i+n:i}let r=2*n,o=e%r;return o<0&&(o+=r),o<=n?o:r-o}function Tn(t,e){return t.loop==="once"&&t.duration>0&&e>=t.duration}function Ye(t,e){let n=t.length;if(n===0)return 0;if(n===1||e<=t[0].t)return t[0].v;if(e>=t[n-1].t)return t[n-1].v;let r=0,o=n-1;for(;r<o;){let c=r+o>>1;t[c].t<e?r=c+1:o=c}let i=t[o],s=t[o-1],a=i.t-s.t;if(a<=0)return i.v;let l=(e-s.t)/a,u=Fe[i.ease??"linear"]??Fe.linear;return s.v+(i.v-s.v)*u(l)}function kl(t,e){let n=Ae(t,e);return t.tracks.map(r=>({target:r.target,channel:r.channel,value:Ye(r.keys,n)}))}function Er(t,e,n){let r=t.events;if(!r||r.length===0||n<=e)return[];let o=t.duration,i=[],s=(d,h,p)=>d>h&&d<=p,a=(d,h)=>{for(let p of r)s(p.t,d,h)&&i.push(p.name)};if(t.loop==="once"||o<=0){let d=e<0?0:e>o?o:e,h=n<0?0:n>o?o:n;return a(d,h),i}let l=Ae(t,e),u=Ae(t,n),c=t.loop==="pingpong"?2*o:o,m=Math.floor(n/c)-Math.floor(e/c);return t.loop==="pingpong"?(m===0&&u>=l?a(l,u):m===0?a(u,l):(a(Math.min(l,u),o),a(0,Math.max(l,u))),i):(m===0&&u>=l?a(l,u):(a(l,o),a(0,u)),i)}function Sl(t,e){let n=[];t.duration>0||n.push(`duration must be > 0 (got ${t.duration})`),t.loop!=="loop"&&t.loop!=="once"&&t.loop!=="pingpong"&&n.push(`loop must be 'loop' | 'once' | 'pingpong' (got '${String(t.loop)}')`),(!t.tracks||t.tracks.length===0)&&n.push("clip has no tracks");let r=e?new Set(e):null;return(t.tracks??[]).forEach((o,i)=>{let s=`track ${i} (${o.target}/${o.channel})`;if(ki.includes(o.channel)||n.push(`${s}: unknown channel '${o.channel}'`),r&&!r.has(o.target)&&n.push(`${s}: target '${o.target}' is not in the rig`),!o.keys||o.keys.length===0)n.push(`${s}: no keyframes`);else for(let a=0;a<o.keys.length;a++){let l=o.keys[a];(!Number.isFinite(l.t)||!Number.isFinite(l.v))&&n.push(`${s}: key ${a} has non-finite t/v`),(l.t<0||l.t>t.duration)&&n.push(`${s}: key ${a} time ${l.t} is outside [0, ${t.duration}]`),a>0&&l.t<o.keys[a-1].t&&n.push(`${s}: keys must be ascending in t (key ${a} = ${l.t} < ${o.keys[a-1].t})`),l.ease!==void 0&&!(l.ease in Fe)&&n.push(`${s}: key ${a} unknown ease '${String(l.ease)}'`)}}),(t.events??[]).forEach((o,i)=>{(!Number.isFinite(o.t)||o.t<0||o.t>t.duration)&&n.push(`event ${i} ('${o.name}') time ${o.t} is outside [0, ${t.duration}]`),o.name||n.push(`event ${i} has no name`)}),[...new Set(n)]}var Ht=(t,e)=>`${t}/${e}`;function Mn(t,e){let n=Ae(t,e*t.duration),r={};for(let o of t.tracks)r[Ht(o.target,o.channel)]=Ye(o.keys,n);return r}function Rn(t,e,n,r={}){for(let o in r)delete r[o];for(let o in t)r[o]=o in e?t[o]+(e[o]-t[o])*n:t[o];for(let o in e)o in t||(r[o]=e[o]);return r}var Ir=class{samples;constructor(e){this.samples=e.slice().sort((n,r)=>n.x-r.x)}weights(e){let n=this.samples;if(n.length===0)return[];if(n.length===1||e<=n[0].x)return[{clip:n[0].clip,weight:1}];if(e>=n[n.length-1].x)return[{clip:n[n.length-1].clip,weight:1}];let r=0;for(;r<n.length-1&&n[r+1].x<=e;)r++;let o=n[r],i=n[r+1],s=i.x-o.x,a=s<=0?0:(e-o.x)/s;return[{clip:o.clip,weight:1-a},{clip:i.clip,weight:a}]}sample(e,n){let r=this.weights(e);if(r.length===0)return{};let o=Mn(r[0].clip,n);return r.length===2&&(o=Rn(o,Mn(r[1].clip,n),r[1].weight)),o}},Lr=class{samples;constructor(e){this.samples=e.map(n=>({clip:n.clip,x:n.x,y:n.y??0}))}weights(e,n){let r=this.samples;if(r.length===0)return[];if(r.length<=3)return this.barycentric(r,e,n);let o=r.map((i,s)=>s);return o.sort((i,s)=>{let a=(r[i].x-e)**2+(r[i].y-n)**2,l=(r[s].x-e)**2+(r[s].y-n)**2;return a-l||i-s}),this.barycentric([r[o[0]],r[o[1]],r[o[2]]],e,n)}barycentric(e,n,r){if(e.length===1)return[{clip:e[0].clip,weight:1}];if(e.length===2){let[d,h]=e,p=h.x-d.x,f=h.y-d.y,g=p*p+f*f,k=g<=0?0:Q(((n-d.x)*p+(r-d.y)*f)/g,0,1);return[{clip:d.clip,weight:1-k},{clip:h.clip,weight:k}]}let[o,i,s]=e,a=(i.y-s.y)*(o.x-s.x)+(s.x-i.x)*(o.y-s.y),l,u;a===0?l=u=1/3:(l=((i.y-s.y)*(n-s.x)+(s.x-i.x)*(r-s.y))/a,u=((s.y-o.y)*(n-s.x)+(o.x-s.x)*(r-s.y))/a);let c=1-l-u;l=l<0?0:l,u=u<0?0:u,c=c<0?0:c;let m=l+u+c;return m<=0?[{clip:o.clip,weight:1}]:[{clip:o.clip,weight:l/m},{clip:i.clip,weight:u/m},{clip:s.clip,weight:c/m}]}sample(e,n,r){let o=this.weights(e,n);if(o.length===0)return{};let i={};for(let{clip:s,weight:a}of o){if(a===0)continue;let l=Mn(s,r);for(let u in l)i[u]=(i[u]??0)+l[u]*a}return i}};function Cl(t,e=1){let n=[];if(!t||t.length===0)return n.push("blend space has no samples"),n;t.forEach((o,i)=>{Number.isFinite(o.x)||n.push(`sample ${i}: x is not finite`),e===2&&!Number.isFinite(o.y??0)&&n.push(`sample ${i}: y is not finite`),o.clip||n.push(`sample ${i}: missing clip`)});let r=new Map;return t.forEach((o,i)=>{let s=e===2?`${o.x},${o.y??0}`:`${o.x}`;r.has(s)?n.push(`sample ${i} duplicates the position of sample ${r.get(s)} (${s})`):r.set(s,i)}),[...new Set(n)]}var Ve=class extends _{type="Bone2D";length;constructor(e={}){super(e),this.length=e.length??0}get tip(){return{x:this.length,y:0}}serializeProps(){return{length:this.length}}applyProps(e){typeof e.length=="number"&&(this.length=e.length)}},Pn=class{constructor(e){this.root=e;this.index(e,"")}root;byPath=new Map;index(e,n){n!==""&&this.byPath.set(n,e);for(let r of e.children){let o=n===""?r.name:`${n}/${r.name}`;this.index(r,o)}}resolve(e){return this.byPath.get(e)??null}targets(){return[...this.byPath.keys()]}bones(){let e=[];for(let n of this.byPath.values())n instanceof Ve&&e.push(n);return e}};function Dn(t){return new Pn(t)}function En(t,e){let n=[];for(let r of t.tracks){let o=e.resolve(r.target);o&&n.push({node:o,channel:r.channel,keys:r.keys,target:r.target})}return n}function In(t,e,n){switch(e){case"x":t.pos.x=n;break;case"y":t.pos.y=n;break;case"rotation":t.rotation=n;break;case"scaleX":t.scale.x=n;break;case"scaleY":t.scale.y=n;break;case"opacity":Tl(t,n);break}}function Tl(t,e){let n=t;n.paint&&(n.paint.opacity=e)}var qt=class extends _{type="ClipPlayer";rig;skeleton=null;clips=new Map;currentName=null;elapsed=0;prevName=null;prevElapsed=0;fadeDur=0;fadeT=0;poseA={};poseB={};poseMix={};constructor(e={}){super(e),this.cosmetic=!0,this.rig=e.rig??null}onReady(){this.rig||(this.rig=this.parent),this.rebind()}add(e,n){return this.clips.set(e,{def:n,tracks:this.rig?En(n,this.ensureSkeleton()):[]}),this}rebind(e){if(e&&(this.rig=e),!!this.rig){this.skeleton=Dn(this.rig);for(let[,n]of this.clips)n.tracks=En(n.def,this.skeleton)}}ensureSkeleton(){return!this.skeleton&&this.rig&&(this.skeleton=Dn(this.rig)),this.skeleton}play(e,n={}){if(!this.clips.has(e))return;let r=n.fade??0;r>0&&this.currentName&&this.currentName!==e?(this.prevName=this.currentName,this.prevElapsed=this.elapsed,this.fadeDur=r,this.fadeT=0):(this.prevName=null,this.fadeDur=0,this.fadeT=0),this.currentName=e,this.elapsed=0}stop(){this.currentName=null,this.prevName=null,this.fadeDur=0}get time(){return this.elapsed}get current(){return this.currentName}get event(){return this.signal("event")}get finished(){return this.signal("finished")}onProcess(e){let n=this.currentName;if(!n)return;let r=this.clips.get(n);if(!r)return;let o=this.elapsed;if(this.elapsed+=e,this.fadeDur>0&&this.prevName){this.fadeT+=e;let i=this.fadeT>=this.fadeDur?1:this.fadeT/this.fadeDur,s=Fe.quadInOut(i),a=this.clips.get(this.prevName);a&&this.samplePose(a,this.prevElapsed,this.poseA),this.samplePose(r,this.elapsed,this.poseB),Rn(this.poseA,this.poseB,s,this.poseMix),this.applyPose(r,this.poseMix),i>=1&&(this.prevName=null,this.fadeDur=0)}else this.applyDirect(r,this.elapsed);if(r.def.events&&r.def.events.length>0){let i=Er(r.def,o,this.elapsed);for(let s of i)this.emit("event",s)}Tn(r.def,this.elapsed)&&!Tn(r.def,o)&&this.emit("finished",n)}applyDirect(e,n){let r=Ae(e.def,n),o=e.tracks;for(let i=0;i<o.length;i++){let s=o[i];In(s.node,s.channel,Ye(s.keys,r))}}samplePose(e,n,r){for(let s in r)delete r[s];let o=Ae(e.def,n),i=e.tracks;for(let s=0;s<i.length;s++){let a=i[s];r[Ht(a.target,a.channel)]=Ye(a.keys,o)}}applyPose(e,n){let r=e.tracks;for(let o=0;o<r.length;o++){let i=r[o],s=n[Ht(i.target,i.channel)];s!==void 0&&In(i.node,i.channel,s)}}};function $r(t,e,n,r,o=1){let i=r.x-t.x,s=r.y-t.y,a=G(i,s),l=e+n,u=Math.abs(e-n),c=!0;a>l?(a=l,c=!1):a<u&&(a=u||1e-9,c=!1),a<1e-9&&(a=1e-9);let m=Le(s,i),d=Si((e*e+a*a-n*n)/(2*e*a)),h=Ci(d),p=Si((e*e+n*n-a*a)/(2*e*n)),f=Ci(p),g=m-o*h,k=g+o*(Math.PI-f);return{angle0:g,angle1:k,reachable:c}}function Si(t){return t<-1?-1:t>1?1:t}function Ci(t){return Le(Math.sqrt(1-t*t),t)}function Nr(t,e,n,r={}){let o=e.length,i=r.maxIter??16,s=r.tolerance??1e-4,a=e.reduce((m,d)=>m+d,0),l=[];for(let m=0;m<=o;m++){let d=r.initial?.[m];l.push(d?{x:d.x,y:d.y}:{x:t.x+(m===0?0:1e-6*m),y:t.y})}l[0]={x:t.x,y:t.y};let u=G(n.x-t.x,n.y-t.y);if(u>a){let m=(n.x-t.x)/(u||1),d=(n.y-t.y)/(u||1),h=t.x,p=t.y;l[0]={x:h,y:p};for(let f=0;f<o;f++)h+=m*e[f],p+=d*e[f],l[f+1]={x:h,y:p};return{joints:l,angles:Ti(l),reachable:!1,iterations:0}}let c=0;for(;c<i;c++){let m=l[o];if(G(m.x-n.x,m.y-n.y)<=s)break;l[o]={x:n.x,y:n.y};for(let d=o-1;d>=0;d--){let h=l[d],p=l[d+1],f=G(h.x-p.x,h.y-p.y)||1e-9,g=e[d]/f;l[d]={x:p.x+(h.x-p.x)*g,y:p.y+(h.y-p.y)*g}}l[0]={x:t.x,y:t.y};for(let d=0;d<o;d++){let h=l[d],p=l[d+1],f=G(h.x-p.x,h.y-p.y)||1e-9,g=e[d]/f;l[d+1]={x:h.x+(p.x-h.x)*g,y:h.y+(p.y-h.y)*g}}}return{joints:l,angles:Ti(l),reachable:!0,iterations:c}}function Ti(t){let e=[];for(let n=0;n<t.length-1;n++)e.push(Le(t[n+1].y-t[n].y,t[n+1].x-t[n].x));return e}var Fr=class extends _{type="IkTarget";bones;bendDir;maxIter;reached=!0;constructor(e={}){super(e),this.cosmetic=!0,this.bones=e.bones??[],this.bendDir=e.bendDir??1,this.maxIter=e.maxIter??16}setBones(e){this.bones=e}onProcess(e){let n=this.bones;if(n.length<1)return;let r=n[0],o=r.parent;if(!o)return;let i=this.worldTransform(),s={x:i.e,y:i.f},a=o.worldTransform(),l=De(a),u=Ml(l,s),c={x:r.pos.x,y:r.pos.y};if(n.length===2){let f=$r(c,n[0].length,n[1].length,u,this.bendDir);this.reached=f.reachable,n[0].rotation=f.angle0,n[1].rotation=f.angle1-f.angle0;return}let m=n.map(f=>f.length),d=this.currentJoints(c),h=Nr(c,m,u,{maxIter:this.maxIter,initial:d});this.reached=h.reachable;let p=0;for(let f=0;f<n.length;f++)n[f].rotation=h.angles[f]-p,p=h.angles[f]}currentJoints(e){let n=[{x:e.x,y:e.y}],r=0,o=e.x,i=e.y;for(let s of this.bones)r+=s.rotation,o+=j(r)*s.length,i+=q(r)*s.length,n.push({x:o,y:i});return n}};function Ml(t,e){return{x:t.a*e.x+t.c*e.y+t.e,y:t.b*e.x+t.d*e.y+t.f}}var Ar=class extends _{type="SkeletonDebug";rig;boneColor;pivotColor;pivotRadius;strokeWidth;constructor(e={}){super(e),this.cosmetic=!0,this.rig=e.rig??null,this.boneColor=e.boneColor??"#e0483b",this.pivotColor=e.pivotColor??"#f4d35e",this.pivotRadius=e.pivotRadius??3,this.strokeWidth=e.strokeWidth??2}onReady(){this.rig||(this.rig=this.parent)}draw(e,n){let r=this.rig;r&&this.emitFor(r,e)}emitFor(e,n){if(e instanceof Ve){let r=e.worldTransform();if(n.push({kind:"poly",points:[0,0,e.length,0],closed:!1,stroke:this.boneColor,strokeWidth:this.strokeWidth,round:!0,transform:r,z:this.z,transient:!0}),n.push({kind:"circle",cx:0,cy:0,radius:this.pivotRadius,fill:this.pivotColor,transform:r,z:this.z,transient:!0}),e.pivot){let o=Ne(r,Ge({x:e.pivot.x,y:e.pivot.y},0,{x:1,y:1}));n.push({kind:"circle",cx:0,cy:0,radius:this.pivotRadius*.6,stroke:this.pivotColor,strokeWidth:1,transform:o,z:this.z,transient:!0})}}for(let r of e.children)this.emitFor(r,n)}};var B={gofun:"#f7f1e2",washi:"#efe7d3",kinu:"#e4d8bd",line:"#d8cbac",kinako:"#b9a882",stone:"#6c6252",sumiSoft:"#494133",sumi:"#23201a",kuro:"#181820",yohaku:"#12121a",darkLine:"#2c2c36",shuDeep:"#b23a24",shu:"#d9583c",kakiDeep:"#bf6a1c",kaki:"#e79a49",koDeep:"#94741d",ko:"#e3c054",matsuDeep:"#4a7a3a",matsu:"#8bad52",asagiDeep:"#2c7a90",asagi:"#57bad2",aiDeep:"#2b4257",ai:"#5a86ad",fujiDeep:"#63548c",fuji:"#a091cf",sakuDeep:"#b0506e",saku:"#e097ac"},Ri={name:"meadow",bg:B.washi,ink:B.sumi,inkSoft:B.sumiSoft,line:B.line,accent:B.shuDeep,accent2:B.aiDeep,good:B.matsuDeep,warn:B.kakiDeep,ramp:[B.shuDeep,B.kakiDeep,B.koDeep,B.matsuDeep,B.asagiDeep,B.aiDeep,B.fujiDeep,B.sakuDeep],swatches:B},Ln={name:"dusk",bg:B.kuro,ink:B.gofun,inkSoft:B.kinako,line:B.darkLine,accent:B.shu,accent2:B.asagi,good:B.matsu,warn:B.ko,ramp:[B.shu,B.kaki,B.ko,B.matsu,B.asagi,B.ai,B.fuji,B.saku],swatches:B},Pi={name:"paper",bg:B.gofun,ink:B.sumi,inkSoft:B.stone,line:B.kinu,accent:B.sakuDeep,accent2:B.asagiDeep,good:B.matsuDeep,warn:B.kakiDeep,ramp:[B.sakuDeep,B.kakiDeep,B.koDeep,B.matsuDeep,B.asagiDeep,B.aiDeep,B.fujiDeep,B.shuDeep],swatches:B},Rl={meadow:Ri,dusk:Ln,paper:Pi};function Pl(t,e,n){let r=yt(t),o=yt(e),i=Math.round(r[0]+(o[0]-r[0])*n),s=Math.round(r[1]+(o[1]-r[1])*n),a=Math.round(r[2]+(o[2]-r[2])*n);return jt(i,s,a)}function Dl(t,e){let[n,r,o]=yt(t);return`rgba(${n}, ${r}, ${o}, ${e})`}function yt(t){let e=t.replace("#","");e.length===3&&(e=e.split("").map(r=>r+r).join(""));let n=parseInt(e,16);return[n>>16&255,n>>8&255,n&255]}function jt(t,e,n){return"#"+[t,e,n].map(r=>Math.max(0,Math.min(255,Math.round(r))).toString(16).padStart(2,"0")).join("")}var Di=t=>(t%360+360)%360,Ut=t=>t<0?0:t>1?1:t;function Ei(t,e,n){if(t=Di(t)/360,e=Ut(e),n=Ut(n),e===0){let s=n*255;return jt(s,s,s)}let r=n<.5?n*(1+e):n+e-n*e,o=2*n-r,i=s=>(s=s<0?s+1:s>1?s-1:s,s<1/6?o+(r-o)*6*s:s<1/2?r:s<2/3?o+(r-o)*(2/3-s)*6:o);return jt(i(t+1/3)*255,i(t)*255,i(t-1/3)*255)}function El(t,e,n){t=Di(t)/60,e=Ut(e),n=Ut(n);let r=n*e,o=r*(1-Math.abs(t%2-1)),i=n-r,s=0,a=0,l=0;return t<1?[s,a,l]=[r,o,0]:t<2?[s,a,l]=[o,r,0]:t<3?[s,a,l]=[0,r,o]:t<4?[s,a,l]=[0,o,r]:t<5?[s,a,l]=[o,0,r]:[s,a,l]=[r,0,o],jt((s+i)*255,(a+i)*255,(l+i)*255)}function Ii(t){let[e,n,r]=yt(t),o=e/255,i=n/255,s=r/255,a=Math.max(o,i,s),l=Math.min(o,i,s),u=(a+l)/2,c=a-l;if(c===0)return{h:0,s:0,l:u};let m=u>.5?c/(2-a-l):c/(a+l),d;return a===o?d=(i-s)/c+(i<s?6:0):a===i?d=(s-o)/c+2:d=(o-i)/c+4,{h:d*60,s:m,l:u}}function Il(t,e,n={}){let r=Ii(e),o=n.hue??0,i=n.sat??0,s=n.light??0;return Ei(r.h+t.range(-o,o),r.s+t.range(-i,i),r.l+t.range(-s,s))}var Mi=t=>t<=.04045?t/12.92:Pe((t+.055)/1.055,2.4),Ll=t=>t<=.0031308?t*12.92:1.055*Pe(t,1/2.4)-.055;function xt(t,e,n){let r=yt(t),o=yt(e),i=s=>{let a=Mi(r[s]/255),l=Mi(o[s]/255);return Ll(a+(l-a)*n)*255};return jt(i(0),i(1),i(2))}function Wr(t,e){if(t.length===0)return"#000000";if(t.length===1)return t[0];let r=Ut(e)*(t.length-1),o=Math.min(t.length-2,Math.floor(r));return xt(t[o],t[o+1],r-o)}function $l(t,e){return e<=0?[]:e===1?[Wr(t,0)]:Array.from({length:e},(n,r)=>Wr(t,r/(e-1)))}var Tp=0,He=.5,Mp=1;function Ke(t){return t.map((e,n)=>[e,n]).sort((e,n)=>(e[0].layer??0)-(n[0].layer??0)||e[0].z-n[0].z||e[1]-n[1]).map(([e])=>e)}function Nl(t,e="#"){return t.map(n=>[...n].map(r=>e.includes(r)))}function We(t,e,n){return n>=0&&n<t.length&&e>=0&&e<t[n].length&&t[n][e]}var ne={N:1,E:2,S:4,W:8};function Br(t,e,n){return(We(t,e,n-1)?ne.N:0)|(We(t,e+1,n)?ne.E:0)|(We(t,e,n+1)?ne.S:0)|(We(t,e-1,n)?ne.W:0)}function Fl(t,e,n){let r=0,o=[[0,-1],[1,-1],[1,0],[1,1],[0,1],[-1,1],[-1,0],[-1,-1]];for(let i=0;i<8;i++)We(t,e+o[i][0],n+o[i][1])&&(r|=1<<i);return r}var Qe={Isolated:0,Cap:1,Straight:2,Bend:3,Tee:4,Cross:5};function Al(t){let e=0;return t&ne.N&&(e|=ne.E),t&ne.E&&(e|=ne.S),t&ne.S&&(e|=ne.W),t&ne.W&&(e|=ne.N),e}var Wl=(()=>{let t=[[Qe.Isolated,0],[Qe.Cap,ne.N],[Qe.Straight,ne.N|ne.S],[Qe.Bend,ne.N|ne.E],[Qe.Tee,ne.N|ne.E|ne.S],[Qe.Cross,15]],e=new Array(16);for(let[n,r]of t){let o=r;for(let i=0;i<4;i++)e[o]===void 0&&(e[o]={mask:o,frame:n,rotation:i}),o=Al(o)}return e})();function Li(t){return Wl[t&15]}function Bl(t){return t.map((e,n)=>e.map((r,o)=>r?Li(Br(t,o,n)):null))}function $i(t){let e=t.length,n=e?t[0].length:0,r=[];for(let o=0;o<e-1;o++){let i=[];for(let s=0;s<n-1;s++)i.push((We(t,s,o)?1:0)|(We(t,s+1,o)?2:0)|(We(t,s+1,o+1)?4:0)|(We(t,s,o+1)?8:0));r.push(i)}return r}var zl=[[],[["L","T"]],[["T","R"]],[["L","R"]],[["R","B"]],[["L","T"],["R","B"]],[["T","B"]],[["L","B"]],[["B","L"]],[["T","B"]],[["T","R"],["B","L"]],[["R","B"]],[["L","R"]],[["T","R"]],[["L","T"]],[]];function $n(t,e={}){let n=e.cell??1,r=e.x??0,o=e.y??0,i=$i(t),s=[],a=(l,u,c)=>{switch(l){case"T":return{x:u+n/2,y:c};case"R":return{x:u+n,y:c+n/2};case"B":return{x:u+n/2,y:c+n};case"L":return{x:u,y:c+n/2}}};for(let l=0;l<i.length;l++)for(let u=0;u<i[l].length;u++){let c=r+u*n,m=o+l*n;for(let[d,h]of zl[i[l][u]])s.push({a:a(d,c,m),b:a(h,c,m)})}return s}function _l(t,e={}){let n=e.tile??8,r=e.x??0,o=e.y??0,i=e.z??0,s=e.transform??oe,a=e.fill??"#888",l=e.edge,u=e.edgeWidth??Math.max(1,n/8),c=[];for(let m=0;m<t.length;m++)for(let d=0;d<t[m].length;d++){if(!t[m][d])continue;let h=r+d*n,p=o+m*n;if(c.push({kind:"rect",x:h,y:p,w:n,h:n,transform:s,z:i,fill:a}),!l)continue;let f=Br(t,d,m),g=k=>c.push({kind:"poly",points:k,closed:!1,transform:s,z:i+1,stroke:l,strokeWidth:u});f&ne.N||g([h,p,h+n,p]),f&ne.E||g([h+n,p,h+n,p+n]),f&ne.S||g([h,p+n,h+n,p+n]),f&ne.W||g([h,p,h,p+n])}return c}function Ol(t,e={}){let n=e.tile??8,r=e.transform??oe,o=e.z??0,i=e.edge??e.fill??"#333",s=e.edgeWidth??Math.max(1,n/8);return $n(t,{cell:n,x:e.x??0,y:e.y??0}).map(l=>({kind:"poly",points:[l.a.x,l.a.y,l.b.x,l.b.y],closed:!1,transform:r,z:o,stroke:i,strokeWidth:s,round:!0}))}var U={EMPTY:0,SOLID:1,ONEWAY:2,HAZARD:3},zr={"#":U.SOLID,"-":U.ONEWAY,"^":U.HAZARD};function _r(t,e=32,n=zr){let r=t.length,o=Math.max(...t.map(s=>s.length)),i=new Array(o*r).fill(U.EMPTY);return t.forEach((s,a)=>{for(let l=0;l<s.length;l++)i[a*o+l]=n[s[l]]??U.EMPTY}),{cols:o,rows:r,tileSize:e,tiles:i}}function Gl(t,e=32,n=zr){let r=[];return t.forEach((o,i)=>{for(let s=0;s<o.length;s++){let a=o[s];a===" "||a==="."||n[a]!==void 0||r.push({char:a,tx:s,ty:i,x:(s+.5)*e,y:(i+.5)*e})}}),r}function pe(t,e,n){return e<0||n<0||e>=t.cols||n>=t.rows?U.SOLID:t.tiles[n*t.cols+e]}function Vl(t,e,n){return pe(t,Math.floor(e/t.tileSize),Math.floor(n/t.tileSize))}var Hl=t=>t.cols*t.tileSize,ql=t=>t.rows*t.tileSize;function jl(t){let e=[];for(let n=0;n<t.rows;n++){let r=[];for(let o=0;o<t.cols;o++)r.push(pe(t,o,n)===U.SOLID);e.push(r)}return $n(e,{cell:t.tileSize})}function Or(t,e,n){let r=[],o=e*e;for(let i of n){let s=i.a.x-t.x,a=i.a.y-t.y,l=i.b.x-t.x,u=i.b.y-t.y,c=s*s+a*a,m=l*l+u*u;(c<=o||m<=o||Ul(t,i)<=o)&&r.push(i)}return r}function Ul(t,e){let n=e.b.x-e.a.x,r=e.b.y-e.a.y,o=n*n+r*r;if(o===0){let c=t.x-e.a.x,m=t.y-e.a.y;return c*c+m*m}let i=((t.x-e.a.x)*n+(t.y-e.a.y)*r)/o;i=i<0?0:i>1?1:i;let s=e.a.x+n*i,a=e.a.y+r*i,l=t.x-s,u=t.y-a;return l*l+u*u}function Gr(t,e,n){let r=2*e,o=[];for(let i of n){let s=i.a.x,a=i.a.y,l=i.b.x,u=i.b.y,c=s-t.x,m=a-t.y,d=l-t.x,h=u-t.y,p=G(c,m),f=G(d,h);if(p===0||f===0)continue;let g=s+c/p*r,k=a+m/p*r,v=l+d/f*r,M=u+h/f*r;o.push([s,a,l,u,v,M,g,k])}return o}var vt=class extends _{type="PointLight";radius;color;intensity;falloff;flicker;litIntensity;rng;phase=0;constructor(e={}){super(e),this.cosmetic=!0,this.radius=e.radius??160,this.color=e.color??"#ffe6b0",this.intensity=e.intensity??1,this.falloff=e.falloff??1,this.flicker=e.flicker??{amount:0,speed:0},this.litIntensity=this.intensity,this.rng=new ue(e.seed??43)}onProcess(e){if(this.flicker.amount<=0){this.litIntensity=this.intensity;return}this.phase+=e*this.flicker.speed;let r=1+(q(this.phase)*.5+(this.rng.float()-.5))*this.flicker.amount;this.litIntensity=Math.max(0,this.intensity*r)}serializeProps(){return{}}},Xt=class extends _{type="LightLayer";ambient;softShadows;width;height;occluders=[];constructor(e={}){super(e),this.cosmetic=!0,this.ambient={color:e.ambient?.color??Ln.bg,level:e.ambient?.level??0},this.softShadows=e.softShadows??!1,this.width=e.width??1280,this.height=e.height??720}setOccluders(e){this.occluders=e}draw(e,n){let r=this.ambient.level>=1?"#ffffff":xt(this.ambient.color,"#ffffff",Ni(this.ambient.level)),o={kind:"rect",x:0,y:0,w:this.width,h:this.height,fill:r,blend:"multiply",transform:oe,z:0,layer:.5};e.push(o);for(let i of this.children){if(!(i instanceof vt)||!i.visible)continue;let s=i.localTransform(),a=s.e,l=s.f,u=i.radius,c=Math.max(0,Math.min(1,i.litIntensity)),m=i.color,d=xt("#000000",m,c),h=xt("#000000",m,c*.5),p="#000000",f=Ni(.6/Math.max(.01,i.falloff)),g={kind:"circle",cx:a,cy:l,radius:u,gradient:{type:"radial",cx:.5,cy:.5,r:.5,stops:[{offset:0,color:d},{offset:f,color:h},{offset:1,color:p}]},blend:"screen",transform:n,z:0,layer:.5};if(e.push(g),this.occluders.length){let k=Or({x:a,y:l},u,this.occluders),v=Gr({x:a,y:l},u,k);for(let M of v)e.push(Fi(M,r,n,1)),this.softShadows&&e.push(Fi(Xl(M),r,n,.5))}}}},Ni=t=>t<0?0:t>1?1:t;function Fi(t,e,n,r){let o={kind:"poly",points:t,closed:!0,fill:e,blend:"multiply",transform:n,z:0,layer:.5};return r!==1&&(o.opacity=r),o}function Xl(t){let e=(t[0]+t[2])/2,n=(t[1]+t[3])/2,r=(l,u)=>{let c=l-e,m=u-n,d=G(c,m);if(d===0)return[l,u];let h=-m/d,p=c/d,f=d*.08;return[l+h*f,u+p*f]},[o,i]=r(t[6],t[7]),[s,a]=r(t[4],t[5]);return[t[0],t[1],t[2],t[3],s,a,o,i]}var Ai=new Map;function we(t,e){Ai.set(t,e)}we("Node",()=>new _);we("Sprite",()=>new zt({shape:{kind:"rect",w:1,h:1}}));we("Text",()=>new _t({text:""}));we("Camera2D",()=>new Ot);we("Timer",()=>new Gt({duration:1}));we("AnimationPlayer",()=>new Vt);we("Bone2D",()=>new Ve);we("ClipPlayer",()=>new qt);we("PointLight",()=>new vt);we("LightLayer",()=>new Xt);function Nn(t){let e=Ai.get(t.type);if(!e)throw new Error(`hayao: unknown node type "${t.type}" (register it first)`);let n=e();n.name=t.name,n.pos={...t.pos},n.rotation=t.rotation,n.scale={...t.scale},n.z=t.z,n.visible=t.visible,t.pivot&&(n.pivot={...t.pivot}),(t.props.pauseMode==="always"||t.props.pauseMode==="stopped")&&(n.pauseMode=t.props.pauseMode),t.props.screenSpace===!0&&(n.screenSpace=!0),n.applyProps(t.props);for(let r of t.children)n.addChild(Nn(r));return n}var Jt=class{down=new Set;prev=new Set;axes=new Map;logged=new Map;declared=null;warned=new Set;declareActions(e){this.declared??=new Set;for(let n of e)this.declared.add(n)}checkDeclared(e){this.declared===null||this.declared.has(e)||this.warned.has(e)||(this.warned.add(e),console.warn(`hayao: input action "${e}" is not declared by any input source \u2014 declared actions: ${[...this.declared].sort().join(", ")||"(none)"}`))}beginFrame(e,n){if(this.prev=new Set(this.down),this.down=new Set(e),this.declared!==null)for(let r of this.down)this.declared.add(r);if(this.logged.clear(),n)for(let r in n)this.logged.set(r,n[r]),this.axes.set(r,n[r])}isDown(e){return this.checkDeclared(e),this.down.has(e)}justPressed(e){return this.checkDeclared(e),this.down.has(e)&&!this.prev.has(e)}justReleased(e){return this.checkDeclared(e),!this.down.has(e)&&this.prev.has(e)}axis(e){return this.axes.get(e)??0}snapshot(){return[...this.down].sort()}getState(){let e={down:[...this.down].sort(),prev:[...this.prev].sort()};return this.logged.size>0&&(e.axes=[...this.logged].sort((n,r)=>n[0]<r[0]?-1:n[0]>r[0]?1:0)),e}setState(e){if(this.down=new Set(e.down),this.prev=new Set(e.prev),this.logged.clear(),e.axes)for(let[n,r]of e.axes)this.logged.set(n,r),this.axes.set(n,r)}};function Ze(t,e,n=-1,r=1){if(e<2||r===n)return t;let o=Math.min(1,Math.max(0,(t-n)/(r-n))),i=Math.round(o*(e-1));return n+i/(e-1)*(r-n)}function Hr(t,e){let n=Math.PI*2/e;return Math.round(t/n)*n}function qr(t,e){let n=[];for(let r in t)t[r].some(o=>e.has(o))&&n.push(r);return n.sort()}var Vr=class{frames=[];axes=[];anyAxes=!1;record(e,n){this.frames.push(e.slice().sort()),n&&Object.keys(n).length>0?(this.axes.push({...n}),this.anyAxes=!0):this.axes.push(void 0)}get length(){return this.frames.length}toLog(){let e={frames:this.frames.map(n=>n.slice())};return this.anyAxes&&(e.axes=this.axes.map(n=>n?{...n}:void 0)),e}};function wt(t,e){return t.frames[e]??[]}function kt(t,e){return t.axes?.[e]}var Fn={up:["ArrowUp","KeyW"],down:["ArrowDown","KeyS"],left:["ArrowLeft","KeyA"],right:["ArrowRight","KeyD"],confirm:["Enter","Space"],cancel:["Escape","Backspace"],action:["KeyZ","KeyJ"],action2:["KeyX","KeyK"],undo:["KeyU"],restart:["KeyR"]};var et=class{keysDown=new Set;pressed=new Set;held=new Set;map;target;onDown;onUp;onBlur;constructor(e,n=document){this.map=e,this.target=n,this.onDown=r=>{this.keysDown.add(r.code),(r.code.startsWith("Arrow")||r.code==="Space")&&r.preventDefault()},this.onUp=r=>this.keysDown.delete(r.code),this.onBlur=()=>this.keysDown.clear(),n.addEventListener("keydown",this.onDown),n.addEventListener("keyup",this.onUp),globalThis.addEventListener?.("blur",this.onBlur)}currentActions(){let e=this.held.size===0?this.keysDown:new Set([...this.keysDown,...this.held]),n=qr(this.map,e);if(this.pressed.size===0&&this.held.size===0)return n;let r=new Set(n);for(let o of this.pressed)r.add(o);for(let o of this.held)r.add(o);return[...r].sort()}actionNames(){return Object.keys(this.map)}press(e){this.pressed.add(e)}clearPressed(){this.pressed.clear()}setHeld(e,n=!0){n?this.held.add(e):this.held.delete(e)}releaseHeld(e){this.held.delete(e)}clearHeld(){this.held.clear()}setMap(e){this.map=e}dispose(){this.target.removeEventListener("keydown",this.onDown),this.target.removeEventListener("keyup",this.onUp),globalThis.removeEventListener?.("blur",this.onBlur)}},jr=["mouse.left","mouse.right","mouse.middle"],Yt=class{clientX=0;clientY=0;isDown=!1;rightDown=!1;middleDown=!1;seen=!1;touches=new Map;target;el;keyboard;onMove;onDown;onUp;onCtx;constructor(e,n={}){this.target=e,this.el=e.element,this.keyboard=n.keyboard;let r=o=>typeof o.buttons!="number"?!1:(this.isDown=(o.buttons&1)!==0,this.rightDown=(o.buttons&2)!==0,this.middleDown=(o.buttons&4)!==0,!0);this.onMove=o=>{this.clientX=o.clientX,this.clientY=o.clientY,this.seen=!0,typeof o.buttons=="number"&&o.buttons!==0&&r(o);let i=this.touches.get(o.pointerId);i&&(i.clientX=o.clientX,i.clientY=o.clientY)},this.onDown=o=>{this.clientX=o.clientX,this.clientY=o.clientY,this.seen=!0,r(o)||(o.button===2?this.rightDown=!0:o.button===1?this.middleDown=!0:this.isDown=!0),this.touches.set(o.pointerId,{clientX:o.clientX,clientY:o.clientY})},this.onUp=o=>{r(o)||(this.isDown=!1,o.button===2?this.rightDown=!1:o.button===1?this.middleDown=!1:(this.rightDown=!1,this.middleDown=!1)),this.touches.delete(o?.pointerId)},this.onCtx=o=>o.preventDefault(),this.el?.addEventListener("pointermove",this.onMove),this.el?.addEventListener("pointerdown",this.onDown),this.el?.addEventListener("pointerup",this.onUp),this.el?.addEventListener("pointercancel",this.onUp),n.contextMenu||this.el?.addEventListener("contextmenu",this.onCtx),globalThis.addEventListener?.("pointerup",this.onUp),globalThis.addEventListener?.("pointercancel",this.onUp)}read(){let e=this.target.toDesign?.(this.clientX,this.clientY)??{x:0,y:0};return{x:e.x,y:e.y,down:this.isDown,active:this.seen}}readAll(){return[...this.touches.keys()].sort((n,r)=>n-r).map(n=>{let r=this.touches.get(n),o=this.target.toDesign?.(r.clientX,r.clientY)??{x:0,y:0};return{x:o.x,y:o.y,down:!0,active:!0,id:n}})}sample(e){let n=this.read(),r=o=>Math.round(o*8)/8;e.axes.set("pointer.x",r(n.x)),e.axes.set("pointer.y",r(n.y)),e.axes.set("pointer.down",n.down?1:0),e.axes.set("pointer.right",this.rightDown?1:0),e.axes.set("pointer.middle",this.middleDown?1:0),this.keyboard&&(e.declareActions(jr),this.keyboard.setHeld("mouse.left",this.isDown),this.keyboard.setHeld("mouse.right",this.rightDown),this.keyboard.setHeld("mouse.middle",this.middleDown))}dispose(){if(this.keyboard)for(let e of jr)this.keyboard.releaseHeld(e);this.el?.removeEventListener("pointermove",this.onMove),this.el?.removeEventListener("pointerdown",this.onDown),this.el?.removeEventListener("pointerup",this.onUp),this.el?.removeEventListener("pointercancel",this.onUp),this.el?.removeEventListener("contextmenu",this.onCtx),globalThis.removeEventListener?.("pointerup",this.onUp),globalThis.removeEventListener?.("pointercancel",this.onUp)}};var Ur=class{index;stickBuckets;triggerBuckets;deadzone;buttonMap;keyboard;prevPressed=new Map;constructor(e={}){this.index=e.index??0,this.stickBuckets=e.stickBuckets??128,this.triggerBuckets=e.triggerBuckets??64,this.deadzone=e.deadzone??.12,this.buttonMap=e.buttonMap??Wi,this.keyboard=e.keyboard}sample(e){let n=navigator.getGamepads?.()[this.index]??null;if(!n)return;let r=(d,h)=>{let p=G(d,h);if(p<this.deadzone)return{x:0,y:0};let f=(p-this.deadzone)/(1-this.deadzone),g=Math.min(f,1);return{x:d/p*g,y:h/p*g}},o=r(n.axes[0]??0,n.axes[1]??0),i=r(n.axes[2]??0,n.axes[3]??0),s=d=>Ze(d,this.stickBuckets,-1,1),a=d=>Ze(d,this.triggerBuckets,0,1);e.axes.set("gamepad.lx",s(o.x)),e.axes.set("gamepad.ly",s(o.y)),e.axes.set("gamepad.rx",s(i.x)),e.axes.set("gamepad.ry",s(i.y)),e.axes.set("gamepad.lt",a(n.buttons[6]?.value??0)),e.axes.set("gamepad.rt",a(n.buttons[7]?.value??0));let l=n.buttons[12]?.pressed?1:0,u=n.buttons[13]?.pressed?1:0,c=n.buttons[14]?.pressed?1:0,m=n.buttons[15]?.pressed?1:0;if(e.axes.set("gamepad.dpad.x",m-c),e.axes.set("gamepad.dpad.y",u-l),this.keyboard)for(let[d,h]of Object.entries(this.buttonMap)){let p=Number(d),f=n.buttons[p]?.pressed??!1;this.keyboard.setHeld(h,f),this.prevPressed.set(p,f)}}dispose(){if(this.keyboard)for(let e of Object.values(this.buttonMap))this.keyboard.releaseHeld(e);this.prevPressed.clear()}},Wi={0:"confirm",1:"cancel",2:"action2",3:"action",9:"confirm",12:"up",13:"down",14:"left",15:"right"};var J=1e-6,tt=(t,e,n)=>[Math.floor(t/n),Math.floor((e-J)/n)];function qe(t,e,n,r,o,i=[]){let s=t.tileSize,[a,l]=tt(e,e+r,s),[u,c]=tt(n,n+o,s);for(let m=u;m<=c;m++)for(let d=a;d<=l;d++)if(pe(t,d,m)===U.SOLID)return!0;for(let m of i)if(!m.oneway&&e<m.x+m.w-J&&e+r>m.x+J&&n<m.y+m.h-J&&n+o>m.y+J)return!0;return!1}function Kt(t,e,n,r,o={}){let i=t.tileSize,s=o.solids??[],{x:a,y:l}=e,{w:u,h:c}=e,m=!1,d=!1,h=!1,p=!1;if(n!==0){let[x,b]=tt(l,l+c,i);if(n>0){let w=a+n,[C,E]=[Math.floor((a+u)/i),Math.floor((a+u+n-J)/i)];for(let R=C;R<=E;R++)for(let S=x;S<=b;S++)pe(t,R,S)===U.SOLID&&(w=Math.min(w,R*i-u));for(let R of s)!R.oneway&&R.y<l+c-J&&R.y+R.h>l+J&&R.x>=a+u-J&&(w=Math.min(w,R.x-u));w<a+n-J&&(m=!0,p=!0),a=Math.min(a+n,w)}else{let w=a+n,[C,E]=[Math.floor((a-J)/i),Math.floor((a+n)/i)];for(let R=C;R>=E;R--)for(let S=x;S<=b;S++)pe(t,R,S)===U.SOLID&&(w=Math.max(w,(R+1)*i));for(let R of s)!R.oneway&&R.y<l+c-J&&R.y+R.h>l+J&&R.x+R.w<=a+J&&(w=Math.max(w,R.x+R.w));w>a+n+J&&(m=!0,h=!0),a=Math.max(a+n,w)}}let f=l+c,g=!1,k=!1,v=-1;if(r!==0){let[x,b]=tt(a,a+u,i);if(r>0){let w=l+r,[C,E]=[Math.floor(f/i),Math.floor((f+r-J)/i)];for(let R=C;R<=E;R++)for(let S=x;S<=b;S++){let T=pe(t,S,R);(T===U.SOLID||T===U.ONEWAY&&!o.dropThrough&&f<=R*i+J)&&(w=Math.min(w,R*i-c))}for(let R=0;R<s.length;R++){let S=s[R];!(S.x<a+u-J&&S.x+S.w>a+J)||S.y<f-J||S.oneway&&(o.dropThrough||f>S.y+J)||S.y-c<w&&(w=S.y-c,v=R)}w<l+r-J?(d=!0,g=!0):v=-1,l=Math.min(l+r,w)}else{let w=l+r,[C,E]=[Math.floor((l-J)/i),Math.floor((l+r)/i)];for(let R=C;R>=E;R--)for(let S=x;S<=b;S++)pe(t,S,R)===U.SOLID&&(w=Math.max(w,(R+1)*i));for(let R of s)!R.oneway&&R.x<a+u-J&&R.x+R.w>a+J&&R.y+R.h<=l+J&&(w=Math.max(w,R.y+R.h));w>l+r+J&&(d=!0,k=!0),l=Math.max(l+r,w)}}if(!g){let x=Bi(t,a,l,u,c,s,o.dropThrough??!1);g=x.grounded,v=x.solid}let M=3,I=!1;{let[x,b]=tt(a+M,a+u-M,i),[w,C]=tt(l+M,l+c-M,i);for(let E=w;E<=C&&!I;E++)for(let R=x;R<=b&&!I;R++)pe(t,R,E)===U.HAZARD&&(I=!0)}return{x:a,y:l,hitX:m,hitY:d,onFloor:g,onCeiling:k,onWallLeft:h,onWallRight:p,hazard:I,floorSolid:v}}function Bi(t,e,n,r,o,i=[],s=!1){let a=t.tileSize,l=n+o,[u,c]=tt(e,e+r,a),m=Math.floor((l+1)/a);for(let d=u;d<=c;d++){let h=pe(t,d,m);if(h===U.SOLID)return{grounded:!0,solid:-1};if(h===U.ONEWAY&&!s&&Math.abs(l-m*a)<=1+J)return{grounded:!0,solid:-1}}for(let d=0;d<i.length;d++){let h=i[d];if(h.x<e+r-J&&h.x+h.w>e+J&&l<=h.y+1+J&&l>=h.y-1-J)return{grounded:!0,solid:d}}return{grounded:!1,solid:-1}}var St={width:22,height:28,runSpeed:340,groundAccel:3800,groundFriction:4200,airAccel:2600,airFriction:260,gravity:2300,maxFall:660,apexThreshold:60,apexGravityMult:.5,jumpVelocity:650,jumpCutMult:.4,coyoteTime:.1,jumpBuffer:.12,jumpCornerNudge:10,dashCornerNudge:12,airJumps:0,airJumpMult:.92,dashSpeed:640,dashTime:.14,dashCooldown:.25,dashCharges:1,wallSlideMaxFall:150,wallJumpVelX:360,wallJumpVelY:600,wallJumpLock:.13},Jl={moveX:0,moveY:0,jumpHeld:!1,jumpPressed:!1,dashPressed:!1};function Yl(t,e){return{x:t,y:e,vx:0,vy:0,facing:1,onGround:!1,onWall:0,coyote:0,buffer:0,jumping:!1,wallLock:0,airJumpsLeft:0,dashing:0,dashCd:0,dashesLeft:1,dashVx:0,dashVy:0,carryVx:0,carryVy:0,dead:!1}}var Kl=(t,e,n)=>t<e?Math.min(t+n,e):Math.max(t-n,e);function Ql(t,e,n,r,o=St,i=[]){let s={jumped:!1,wallJumped:!1,airJumped:!1,dashed:!1,landed:!1,died:!1};if(t.dead)return s;let a=t.onGround;if(t.coyote=Math.max(0,t.coyote-n),t.buffer=Math.max(0,t.buffer-n),t.wallLock=Math.max(0,t.wallLock-n),t.dashCd=Math.max(0,t.dashCd-n),e.jumpPressed&&(t.buffer=o.jumpBuffer),e.dashPressed&&t.dashing<=0&&t.dashCd<=0&&t.dashesLeft>0){let d=e.moveX,h=e.moveY;d===0&&h===0&&(d=t.facing);let p=1/G(d,h);t.dashing=o.dashTime,t.dashCd=o.dashCooldown,t.dashesLeft--,t.dashVx=d*p*o.dashSpeed,t.dashVy=h*p*o.dashSpeed,t.jumping=!1,s.dashed=!0}if(t.dashing>0)t.vx=t.dashVx,t.vy=t.dashVy,t.dashing-=n;else if(t.wallLock<=0){let d=e.moveX*o.runSpeed,h=t.onGround?e.moveX!==0?o.groundAccel:o.groundFriction:e.moveX!==0?o.airAccel:o.airFriction;t.vx=Kl(t.vx,d,h*n),e.moveX!==0&&(t.facing=e.moveX>0?1:-1)}if(t.dashing<=0&&!t.onGround){let d=o.gravity;Math.abs(t.vy)<o.apexThreshold&&e.jumpHeld&&t.jumping&&(d*=o.apexGravityMult),t.vy=Math.min(t.vy+d*n,o.maxFall),t.onWall!==0&&t.vy>o.wallSlideMaxFall&&e.moveX===t.onWall&&(t.vy=o.wallSlideMaxFall)}t.jumping&&!e.jumpHeld&&t.vy<0&&(t.vy*=o.jumpCutMult,t.jumping=!1),t.buffer>0&&t.dashing<=0&&(t.onGround||t.coyote>0?(t.vy=-o.jumpVelocity,t.vx+=t.carryVx,t.carryVy<0&&(t.vy+=t.carryVy),t.jumping=!0,t.buffer=0,t.coyote=0,t.onGround=!1,s.jumped=!0):t.onWall!==0&&o.wallJumpVelY>0?(t.vx=-t.onWall*o.wallJumpVelX,t.vy=-o.wallJumpVelY,t.facing=-t.onWall,t.jumping=!0,t.buffer=0,t.wallLock=o.wallJumpLock,s.wallJumped=!0,s.jumped=!0):t.airJumpsLeft>0&&(t.vy=-o.jumpVelocity*o.airJumpMult,t.airJumpsLeft--,t.jumping=!0,t.buffer=0,s.jumped=!0,s.airJumped=!0));let l=e.moveY>0&&t.buffer<=0,u=t.vx*n+t.carryVx*n*(t.onGround?1:0),c=t.vy*n+Math.max(0,t.carryVy)*n*(t.onGround?1:0),m=Kt(r,{x:t.x,y:t.y,w:o.width,h:o.height},u,c,{solids:i,dropThrough:l});if(m.onCeiling&&t.vy<0&&t.dashing<=0){let d=tu(r,i,m.x,m.y,o.width,o.height,c,o.jumpCornerNudge);d!==null&&(m=Kt(r,{x:d,y:m.y,w:o.width,h:o.height},0,c,{solids:i,dropThrough:l}),m.x=d)}if(m.hitX&&t.dashing>0&&Math.abs(t.dashVy)<1){let d=nu(r,i,m.x,m.y,o.width,o.height,u,o.dashCornerNudge);d!==null&&(m=Kt(r,{x:m.x,y:d,w:o.width,h:o.height},u,0,{solids:i,dropThrough:l}),m.y=d)}if(t.x=m.x,t.y=m.y,m.hitY&&t.vy>0&&(t.vy=0),m.onCeiling&&(t.vy=Math.max(t.vy,0),t.jumping=!1),m.hitX&&t.dashing<=0&&(t.vx=0),t.onWall=m.onWallLeft?-1:m.onWallRight?1:ru(r,i,t.x,t.y,o.width,o.height),t.onGround=m.onFloor,t.onGround){if(t.coyote=o.coyoteTime,t.dashesLeft=o.dashCharges,t.airJumpsLeft=o.airJumps,a||(s.landed=!0),m.floorSolid>=0){let d=i[m.floorSolid];t.carryVx=d.vx,t.carryVy=d.vy,t.y=d.y-o.height}else t.carryVx=0,t.carryVy=0;t.vy>0&&(t.vy=0),t.jumping=!1}else a&&t.carryVy;return m.hazard&&(t.dead=!0,s.died=!0),s}function Zl(t=St){return t.jumpVelocity*t.jumpVelocity/(2*t.gravity)}function zi(t=St){return 2*t.jumpVelocity/t.gravity}function _i(t=St){return t.runSpeed*zi(t)}function eu(t=St){return _i(t)+(t.dashSpeed-t.runSpeed)*t.dashTime}function tu(t,e,n,r,o,i,s,a){for(let l=1;l<=a;l++)for(let u of[1,-1]){let c=n+u*l;if(!qe(t,c,r+s,o,i,e)&&!qe(t,c,r,o,i,e))return c}return null}function nu(t,e,n,r,o,i,s,a){for(let l=1;l<=a;l++)for(let u of[-1,1]){let c=r+u*l;if(!qe(t,n+s,c,o,i,e)&&!qe(t,n,c,o,i,e))return c}return null}function ru(t,e,n,r,o,i){return qe(t,n+1,r,o,i,e)?1:qe(t,n-1,r,o,i,e)?-1:0}var Qt=class{cells=new Map;bounds=new Map;cellSize;constructor(e=64){this.cellSize=e}clear(){this.cells.clear(),this.bounds.clear()}get size(){return this.bounds.size}key(e,n){return(e+32768)*65536+(n+32768)}insert(e,n){this.bounds.set(e,n);let r=this.cellSize,o=Math.floor(n.x/r),i=Math.floor((n.x+n.w)/r),s=Math.floor(n.y/r),a=Math.floor((n.y+n.h)/r);for(let l=s;l<=a;l++)for(let u=o;u<=i;u++){let c=this.key(u,l),m=this.cells.get(c);m?m.push(e):this.cells.set(c,[e])}}query(e){let n=this.cellSize,r=Math.floor(e.x/n),o=Math.floor((e.x+e.w)/n),i=Math.floor(e.y/n),s=Math.floor((e.y+e.h)/n),a=new Set,l=[];for(let u=i;u<=s;u++)for(let c=r;c<=o;c++){let m=this.cells.get(this.key(c,u));if(m)for(let d of m){if(a.has(d))continue;a.add(d);let h=this.bounds.get(d);h.x<e.x+e.w&&h.x+h.w>e.x&&h.y<e.y+e.h&&h.y+h.h>e.y&&l.push(d)}}return l}queryCircle(e,n,r){return this.query({x:e-r,y:n-r,w:r*2,h:r*2}).filter(i=>{let s=this.bounds.get(i),a=Math.max(s.x,Math.min(e,s.x+s.w)),l=Math.max(s.y,Math.min(n,s.y+s.h));return(e-a)*(e-a)+(n-l)*(n-l)<=r*r})}};function Oi(t,e,n,r,o){let i=t.tileSize,s=r-e,a=o-n,l=G(s,a);if(l===0)return{blocked:!1,x:r,y:o,dist:0};let u=s/l,c=a/l,m=Math.floor(e/i),d=Math.floor(n/i),h=u>0?1:-1,p=c>0?1:-1,f=u!==0?Math.abs(i/u):1/0,g=c!==0?Math.abs(i/c):1/0,k=u!==0?(u>0?(m+1)*i-e:e-m*i)/Math.abs(u):1/0,v=c!==0?(c>0?(d+1)*i-n:n-d*i)/Math.abs(c):1/0,M=0;for(let I=0;I<512;I++){if(k<v?(M=k,k+=f,m+=h):(M=v,v+=g,d+=p),M>=l)return{blocked:!1,x:r,y:o,dist:l};if(pe(t,m,d)===U.SOLID)return{blocked:!0,x:e+u*M,y:n+c*M,dist:M}}return{blocked:!0,x:e+u*M,y:n+c*M,dist:M}}function Gi(t,e,n,r,o){return!Oi(t,e,n,r,o).blocked}function ou(t,e,n,r,o,i,s,a,l){let u=a-e,c=l-n,m=G(u,c);return m>s||m===0||(u*r+c*o)/m<j(i/2)?!1:Gi(t,e,n,a,l)}function iu(t={}){return{gravityX:t.gravityX??0,gravityY:t.gravityY??900,iterations:t.iterations??16,cellSize:t.cellSize??96,nextId:1,bodies:[],joints:[],warm:{}}}function su(t){if(t.kind==="circle")return{area:Math.PI*t.r*t.r,unitI:t.r*t.r/2};let e=t.points,n=e.length/2,r=0,o=0;for(let i=0;i<n;i++){let s=e[i*2],a=e[i*2+1],l=(i+1)%n,u=e[l*2],c=e[l*2+1],m=s*c-u*a;r+=m/2,o+=m*(s*s+s*u+u*u+a*a+a*c+c*c)/12}return{area:Math.abs(r),unitI:r!==0?Math.abs(o)/Math.abs(r):0}}var au=1e-4;function lu(t,e){let n=e.kind??"dynamic",r=e.density??1,{area:o,unitI:i}=su(e.shape),s=n==="dynamic"?Math.max(o*r*au,1e-6):0,a=n==="dynamic"&&!e.fixedRotation?s*i:0,l={id:t.nextId++,kind:n,shape:e.shape,x:e.x??0,y:e.y??0,a:e.a??0,vx:e.vx??0,vy:e.vy??0,w:e.w??0,m:s,invM:s>0?1/s:0,i:a,invI:a>0?1/a:0,restitution:e.restitution??.1,friction:e.friction??.4,linDamp:e.linDamp??0,angDamp:e.angDamp??.6,gravityScale:e.gravityScale??1,bullet:e.bullet??!1,sensor:e.sensor??!1,layer:e.layer??1,mask:e.mask??65535,canSleep:e.canSleep??!0,sleeping:!1,sleepTime:0,sleepR:e.shape.kind==="circle"?e.shape.r:Math.sqrt(e.shape.points.reduce((u,c,m,d)=>m%2?u:Math.max(u,d[m]*d[m]+d[m+1]*d[m+1]),0)),fx:0,fy:0,torque:0};return t.bodies.push(l),l.id}function ge(t,e){let n=t.bodies;for(let r=0;r<n.length;r++)if(n[r].id===e)return n[r]}function uu(t,e){let n=t.bodies.findIndex(r=>r.id===e);n>=0&&t.bodies.splice(n,1),t.joints=t.joints.filter(r=>r.a!==e&&r.b!==e)}function ye(t){t.sleeping=!1,t.sleepTime=0}function cu(t,e,n,r,o,i){let s=ge(t,e);!s||s.invM===0||(ye(s),s.vx+=n*s.invM,s.vy+=r*s.invM,o!==void 0&&i!==void 0&&(s.w+=((o-s.x)*r-(i-s.y)*n)*s.invI))}function ke(t){if(t.shape.kind!=="poly")return[];let e=j(t.a),n=q(t.a),r=t.shape.points,o=new Array(r.length);for(let i=0;i<r.length;i+=2)o[i]=t.x+r[i]*e-r[i+1]*n,o[i+1]=t.y+r[i]*n+r[i+1]*e;return o}function An(t){if(t.shape.kind==="circle"){let s=t.shape.r;return{x:t.x-s,y:t.y-s,w:s*2,h:s*2}}let e=ke(t),n=1/0,r=1/0,o=-1/0,i=-1/0;for(let s=0;s<e.length;s+=2)e[s]<n&&(n=e[s]),e[s]>o&&(o=e[s]),e[s+1]<r&&(r=e[s+1]),e[s+1]>i&&(i=e[s+1]);return{x:n,y:r,w:o-n,h:i-r}}function mu(t,e){let n=t/2,r=e/2;return{kind:"poly",points:[-n,-r,n,-r,n,r,-n,r]}}function du(t,e){if(t.shape.kind!=="circle"||e.shape.kind!=="circle")return null;let n=e.x-t.x,r=e.y-t.y,o=t.shape.r+e.shape.r,i=n*n+r*r;if(i>=o*o)return null;let s=Math.sqrt(i),a=s>1e-9?n/s:1,l=s>1e-9?r/s:0;return{a:t,b:e,nx:a,ny:l,points:[{px:t.x+a*t.shape.r,py:t.y+l*t.shape.r,pen:o-s,feature:0}]}}function Vi(t,e){if(t.shape.kind!=="poly"||e.shape.kind!=="circle")return null;let n=ke(t),r=n.length/2,o=e.shape.r,i=-1/0,s=0;for(let E=0;E<r;E++){let R=(E+1)%r,S=n[R*2]-n[E*2],T=n[R*2+1]-n[E*2+1],L=G(S,T)||1,H=T/L,$=-S/L,Y=(e.x-n[E*2])*H+(e.y-n[E*2+1])*$;Y>i&&(i=Y,s=E)}if(i>o)return null;let a=s,l=(s+1)%r,u=n[a*2],c=n[a*2+1],m=n[l*2],d=n[l*2+1];if(i<1e-9){let E=m-u,R=d-c,S=G(E,R)||1,T=R/S,L=-E/S;return{a:t,b:e,nx:T,ny:L,points:[{px:e.x-T*o,py:e.y-L*o,pen:o-i,feature:s}]}}let h=m-u,p=d-c,f=h*h+p*p||1,g=((e.x-u)*h+(e.y-c)*p)/f;g=g<0?0:g>1?1:g;let k=u+h*g,v=c+p*g,M=e.x-k,I=e.y-v,x=M*M+I*I;if(x>=o*o)return null;let b=Math.sqrt(x)||1e-9,w=M/b,C=I/b;return{a:t,b:e,nx:w,ny:C,points:[{px:k,py:v,pen:o-b,feature:s}]}}function Hi(t,e){let n=t.length/2,r=e.length/2,o=-1/0,i=0;for(let s=0;s<n;s++){let a=(s+1)%n,l=t[a*2]-t[s*2],u=t[a*2+1]-t[s*2+1],c=G(l,u)||1,m=u/c,d=-l/c,h=1/0;for(let p=0;p<r;p++){let f=(e[p*2]-t[s*2])*m+(e[p*2+1]-t[s*2+1])*d;f<h&&(h=f)}h>o&&(o=h,i=s)}return[o,i]}function hu(t,e){let n=ke(t),r=ke(e),[o,i]=Hi(n,r);if(o>0)return null;let[s,a]=Hi(r,n);if(s>0)return null;let l,u,c,m;s>o+1e-4?(l=r,u=n,c=a,m=!0):(l=n,u=r,c=i,m=!1);let d=l.length/2,h=u.length/2,p=(c+1)%d,f=l[p*2]-l[c*2],g=l[p*2+1]-l[c*2+1],k=G(f,g)||1,v=g/k,M=-f/k,I=f/k,x=g/k,b=0,w=1/0;for(let O=0;O<h;O++){let z=(O+1)%h,X=u[z*2]-u[O*2],se=u[z*2+1]-u[O*2+1],ae=G(X,se)||1,re=se/ae*v+-X/ae*M;re<w&&(w=re,b=O)}let C=(b+1)%h,E=u[b*2],R=u[b*2+1],S=u[C*2],T=u[C*2+1],L=l[c*2],H=l[c*2+1],$=l[p*2],Y=l[p*2+1];for(let O=0;O<2;O++){let z=O===0?L:$,X=O===0?H:Y,se=O===0?I:-I,ae=O===0?x:-x,re=(E-z)*se+(R-X)*ae,le=(S-z)*se+(T-X)*ae;if(re<0&&le<0)return null;if(re<0){let me=re/(re-le);E=E+(S-E)*me,R=R+(T-R)*me}else if(le<0){let me=le/(le-re);S=S+(E-S)*me,T=T+(R-T)*me}}let K=m?-v:v,te=m?-M:M,ee=[],ie=-((E-L)*v+(R-H)*M),D=-((S-L)*v+(T-H)*M),A=((m?1:0)*64+c)*64+b;return ie>0&&ee.push({px:E,py:R,pen:ie,feature:A*2}),D>0&&ee.push({px:S,py:T,pen:D,feature:A*2+1}),ee.length===0?null:{a:t,b:e,nx:K,ny:te,points:ee}}function Xr(t,e){let n=t.shape.kind,r=e.shape.kind;if(n==="circle"&&r==="circle")return du(t,e);if(n==="poly"&&r==="poly")return hu(t,e);if(n==="poly"&&r==="circle")return Vi(t,e);let o=Vi(e,t);return o?{a:t,b:e,nx:-o.nx,ny:-o.ny,points:o.points}:null}function qi(t,e,n){let r=j(t.a),o=q(t.a),i=e-t.x,s=n-t.y;return[i*r+s*o,-i*o+s*r]}function Wn(t,e,n){let r=j(t.a),o=q(t.a);return[t.x+e*r-n*o,t.y+e*o+n*r]}function pu(t,e){let n=ge(t,e.a),r=ge(t,e.b);if(!n||!r)throw new Error(`distance joint: missing body ${e.a}/${e.b}`);let o=e.ax??0,i=e.ay??0,s=e.bx??0,a=e.by??0,[l,u]=Wn(n,o,i),[c,m]=Wn(r,s,a),d={kind:"distance",id:t.nextId++,a:e.a,b:e.b,ax:o,ay:i,bx:s,by:a,length:e.length??G(c-l,m-u),rope:e.rope??!1};return t.joints.push(d),ye(n),ye(r),d.id}function fu(t,e){let n=ge(t,e.a),r=ge(t,e.b);if(!n||!r)throw new Error(`revolute joint: missing body ${e.a}/${e.b}`);let[o,i]=qi(n,e.px,e.py),[s,a]=qi(r,e.px,e.py),l={kind:"revolute",id:t.nextId++,a:e.a,b:e.b,ax:o,ay:i,bx:s,by:a,motorSpeed:e.motorSpeed??0,maxMotorTorque:e.maxMotorTorque??0,limitLower:e.limitLower??0,limitUpper:e.limitUpper??0,limitEnabled:e.limitLower!==void 0||e.limitUpper!==void 0,refAngle:r.a-n.a};return t.joints.push(l),ye(n),ye(r),l.id}function bu(t,e){for(let n of t.joints)if(n.id===e)return n}function gu(t,e){t.joints=t.joints.filter(n=>n.id!==e)}function Jr(t,e,n,r,o){let[i,s]=Wn(e,t.ax,t.ay),[a,l]=Wn(n,t.bx,t.by),u=i-e.x,c=s-e.y,m=a-n.x,d=l-n.y;if(t.kind==="distance"){let S=a-i,T=l-s,L=G(S,T);if(L<1e-9)return;S/=L,T/=L;let H=L-t.length;if(t.rope&&H<=0)return;let $=e.vx-e.w*c,Y=e.vy+e.w*u,K=n.vx-n.w*d,te=n.vy+n.w*m,ee=(K-$)*S+(te-Y)*T,ie=u*T-c*S,D=m*T-d*S,A=e.invM+n.invM+e.invI*ie*ie+n.invI*D*D;if(A<1e-12)return;let O=.2/r*H,z=-(ee+O)/A;t.rope&&z>0&&(z=0);let X=S*z,se=T*z;e.vx-=X*e.invM,e.vy-=se*e.invM,e.w-=(u*se-c*X)*e.invI,n.vx+=X*n.invM,n.vy+=se*n.invM,n.w+=(m*se-d*X)*n.invI;return}if(t.maxMotorTorque>0){let S=e.invI+n.invI;if(S>1e-12){let L=-(n.w-e.w-t.motorSpeed)/S,H=t.maxMotorTorque*r,$=o.motorImpulse;o.motorImpulse=Math.min(Math.max($+L,-H),H);let Y=o.motorImpulse-$;e.w-=Y*e.invI,n.w+=Y*n.invI}}if(t.limitEnabled){let S=e.invI+n.invI;if(S>1e-12){let T=n.a-e.a-t.refAngle,L=0;if(T<t.limitLower?L=T-t.limitLower:T>t.limitUpper&&(L=T-t.limitUpper),L!==0){let $=-(n.w-e.w+.2/r*L)/S;(L<0&&$>0||L>0&&$<0)&&(e.w-=$*e.invI,n.w+=$*n.invI)}}}let h=e.vx-e.w*c,p=e.vy+e.w*u,f=n.vx-n.w*d,g=n.vy+n.w*m,k=a-i,v=l-s,M=f-h+.2/r*k,I=g-p+.2/r*v,x=e.invM+n.invM+e.invI*c*c+n.invI*d*d,b=-e.invI*u*c-n.invI*m*d,w=e.invM+n.invM+e.invI*u*u+n.invI*m*m,C=x*w-b*b;if(Math.abs(C)<1e-12)return;let E=-(w*M-b*I)/C,R=-(x*I-b*M)/C;e.vx-=E*e.invM,e.vy-=R*e.invM,e.w-=(u*R-c*E)*e.invI,n.vx+=E*n.invM,n.vy+=R*n.invM,n.w+=(m*R-d*E)*n.invI}var yu=.5,xu=.2,vu=40,wu=64,ku=8,Su=.5,ji=100;function Ui(t,e){return t.invM===0&&e.invM===0&&t.kind!=="kinematic"&&e.kind!=="kinematic"&&!t.sensor&&!e.sensor?!1:(t.mask&e.layer)!==0&&(e.mask&t.layer)!==0}function Cu(t,e){let n=t.bodies,r=[];if(e<=0)return r;for(let x=0;x<n.length;x++){let b=n[x];if(b.kind!=="dynamic"||b.sleeping){b.fx=0,b.fy=0,b.torque=0;continue}b.vx+=(t.gravityX*b.gravityScale+b.fx*b.invM)*e,b.vy+=(t.gravityY*b.gravityScale+b.fy*b.invM)*e,b.w+=b.torque*b.invI*e;let w=1/(1+b.linDamp*e);b.vx*=w,b.vy*=w,b.w*=1/(1+b.angDamp*e),b.fx=0,b.fy=0,b.torque=0}let o=new Qt(t.cellSize),i=new Map;for(let x=0;x<n.length;x++)o.insert(n[x],An(n[x])),i.set(n[x],x);let s=[],a=new Set,l=new Set;for(let x of t.joints){let b=Math.min(x.a,x.b),w=Math.max(x.a,x.b);l.add(b*1048576+w)}for(let x=0;x<n.length;x++){let b=n[x],w=o.query(An(b));for(let C of w){if(C.id<=b.id)continue;let E=b.id*1048576+C.id;if(a.has(E)||(a.add(E),l.has(E))||!Ui(b,C))continue;let R=!b.sleeping&&b.kind!=="static",S=!C.sleeping&&C.kind!=="static";if(!R&&!S)continue;let T=Xr(b,C);if(!T)continue;let L=(K,te)=>{K.sleeping&&(te.vx*te.vx+te.vy*te.vy>ji||te.kind==="kinematic")&&ye(K)};if(L(b,C),L(C,b),b.sensor||C.sensor){r.push({a:b.id,b:C.id,px:T.points[0].px,py:T.points[0].py,nx:T.nx,ny:T.ny,impulse:0,sensor:!0});continue}let H=[],$=-T.ny,Y=T.nx;for(let K of T.points){let te=K.px-b.x,ee=K.py-b.y,ie=K.px-C.x,D=K.py-C.y,A=te*T.ny-ee*T.nx,O=ie*T.ny-D*T.nx,z=b.invM+C.invM+b.invI*A*A+C.invI*O*O,X=te*Y-ee*$,se=ie*Y-D*$,ae=b.invM+C.invM+b.invI*X*X+C.invI*se*se,re=C.vx-C.w*D-b.vx+b.w*ee,le=C.vy+C.w*ie-b.vy-b.w*te,me=re*T.nx+le*T.ny,xe=Math.max(b.restitution,C.restitution),Ue=`${b.id}:${C.id}:${K.feature}`,Me=t.warm[Ue],Ea={rax:te,ray:ee,rbx:ie,rby:D,pen:K.pen,massN:z>1e-12?1/z:0,massT:ae>1e-12?1/ae:0,restBias:me<-vu?-xe*me:0,posBias:xu/e*Math.max(0,K.pen-yu),pn:Me?Me[0]:0,pt:Me?Me[1]:0,pb:0,key:Ue};H.push(Ea)}s.push({m:T,ia:x,ib:i.get(C),points:H,friction:Math.sqrt(b.friction*C.friction)})}}for(let x of s){let{a:b,b:w,nx:C,ny:E}=x.m,R=-E,S=C;for(let T of x.points){if(T.pn===0&&T.pt===0)continue;let L=C*T.pn+R*T.pt,H=E*T.pn+S*T.pt;b.vx-=L*b.invM,b.vy-=H*b.invM,b.w-=(T.rax*H-T.ray*L)*b.invI,w.vx+=L*w.invM,w.vy+=H*w.invM,w.w+=(T.rbx*H-T.rby*L)*w.invI}}s.sort((x,b)=>{let w=x.m.a.invM===0||x.m.b.invM===0?0:1,C=b.m.a.invM===0||b.m.b.invM===0?0:1;if(w!==C)return w-C;let E=Math.max(x.m.a.y,x.m.b.y),R=Math.max(b.m.a.y,b.m.b.y);return E!==R?R-E:x.m.a.id!==b.m.a.id?x.m.a.id-b.m.a.id:x.m.b.id-b.m.b.id});let u=new Float64Array(n.length),c=new Float64Array(n.length),m=new Float64Array(n.length),d=t.joints.map(()=>({motorImpulse:0}));for(let x=0;x<t.iterations;x++){for(let b=0;b<t.joints.length;b++){let w=t.joints[b],C=ge(t,w.a),E=ge(t,w.b);!C||!E||C.sleeping&&E.sleeping||(C.sleeping&&ye(C),E.sleeping&&ye(E),Jr(w,C,E,e,d[b]))}for(let b of s){let{a:w,b:C,nx:E,ny:R}=b.m,{ia:S,ib:T}=b,L=-R,H=E;for(let $ of b.points){let Y=C.vx-C.w*$.rby-w.vx+w.w*$.ray,K=C.vy+C.w*$.rbx-w.vy-w.w*$.rax,te=Y*E+K*R,ee=$.massN*($.restBias-te),ie=$.pn;$.pn=Math.max(ie+ee,0),ee=$.pn-ie;let D=E*ee,A=R*ee;w.vx-=D*w.invM,w.vy-=A*w.invM,w.w-=($.rax*A-$.ray*D)*w.invI,C.vx+=D*C.invM,C.vy+=A*C.invM,C.w+=($.rbx*A-$.rby*D)*C.invI,Y=C.vx-C.w*$.rby-w.vx+w.w*$.ray,K=C.vy+C.w*$.rbx-w.vy-w.w*$.rax;let O=Y*L+K*H,z=$.massT*-O,X=b.friction*$.pn,se=$.pt;if($.pt=Math.min(Math.max(se+z,-X),X),z=$.pt-se,D=L*z,A=H*z,w.vx-=D*w.invM,w.vy-=A*w.invM,w.w-=($.rax*A-$.ray*D)*w.invI,C.vx+=D*C.invM,C.vy+=A*C.invM,C.w+=($.rbx*A-$.rby*D)*C.invI,$.posBias>0){let ae=(u[T]-m[T]*$.rby-u[S]+m[S]*$.ray)*E+(c[T]+m[T]*$.rbx-c[S]-m[S]*$.rax)*R,re=$.massN*($.posBias-ae),le=$.pb;$.pb=Math.max(le+re,0),re=$.pb-le;let me=E*re,xe=R*re;u[S]-=me*w.invM,c[S]-=xe*w.invM,u[T]+=me*C.invM,c[T]+=xe*C.invM}}}}let h=[],p=[];for(let x=0;x<n.length;x++){let b=n[x];h.push(b.x),p.push(b.y),!(b.invM===0&&b.kind!=="kinematic")&&(b.sleeping||(b.x+=(b.vx+u[x])*e,b.y+=(b.vy+c[x])*e,b.a+=(b.w+m[x])*e))}for(let x=0;x<n.length;x++){let b=n[x];if(!b.bullet||b.shape.kind!=="circle"||b.sleeping)continue;let w=b.x-h[x],C=b.y-p[x];if(w*w+C*C<1)continue;let E=1;for(let R=0;R<n.length;R++){let S=n[R];if(S===b||S.bullet||S.sensor||!Ui(b,S))continue;let T=Tu(h[x],p[x],w,C,b.shape.r,S);T>=0&&T<E&&(E=T)}if(E<1){let R=G(w,C)||1;b.x=h[x]+w*E+w/R*.4,b.y=p[x]+C*E+C/R*.4}}let f=new Set,g=[];for(let x=0;x<n.length;x++)g.push(x);let k=x=>{for(;g[x]!==x;)g[x]=g[g[x]],x=g[x];return x},v=(x,b)=>{g[k(x)]=k(b)};for(let x of s)f.add(x.m.a.id),f.add(x.m.b.id),x.m.a.kind==="dynamic"&&x.m.b.kind==="dynamic"&&v(x.ia,x.ib);for(let x of t.joints){f.add(x.a),f.add(x.b);let b=ge(t,x.a),w=ge(t,x.b);b?.kind==="dynamic"&&w?.kind==="dynamic"&&v(i.get(b),i.get(w))}for(let x=0;x<n.length;x++){let b=n[x];if(b.kind!=="dynamic")continue;let w=b.vx*b.vx+b.vy*b.vy;if(b.sleeping){w>ji&&ye(b);continue}if(!b.canSleep||!f.has(b.id)){b.sleepTime=0;continue}b.sleepTime=w<wu&&Math.abs(b.w)*b.sleepR<ku?b.sleepTime+e:0}let M=new Map;for(let x=0;x<n.length;x++){let b=n[x];if(b.kind!=="dynamic"||b.sleeping)continue;let w=k(x),C=!b.canSleep||!f.has(b.id)?-1:b.sleepTime,E=M.get(w);M.set(w,E===void 0?C:Math.min(E,C))}for(let x=0;x<n.length;x++){let b=n[x];b.kind!=="dynamic"||b.sleeping||(M.get(k(x))??-1)>=Su&&(b.sleeping=!0,b.vx=0,b.vy=0,b.w=0)}let I={};for(let x of s){let b=0;for(let C of x.points)b+=C.pn,(C.pn!==0||C.pt!==0)&&(I[C.key]=[C.pn,C.pt]);let w=x.m.points[0];r.push({a:x.m.a.id,b:x.m.b.id,px:w.px,py:w.py,nx:x.m.nx,ny:x.m.ny,impulse:b,sensor:!1})}return t.warm=I,r}function Tu(t,e,n,r,o,i){if(i.shape.kind==="circle")return Xi(t,e,n,r,i.x,i.y,o+i.shape.r);let s=ke(i),a=s.length/2,l=-1;for(let u=0;u<a;u++){let c=(u+1)%a,m=s[u*2],d=s[u*2+1],h=s[c*2],p=s[c*2+1],f=h-m,g=p-d,k=G(f,g)||1,v=g/k,M=-f/k,I=(t-m)*v+(e-d)*M-o;if(n*v+r*M<0&&I>.5){let b=Mu(t,e,n,r,m+v*o,d+M*o,h+v*o,p+M*o);b>=0&&(l<0||b<l)&&(l=b)}let x=Xi(t,e,n,r,m,d,o);x>=0&&(l<0||x<l)&&(l=x)}return l}function Xi(t,e,n,r,o,i,s){let a=t-o,l=e-i,u=n*n+r*r;if(u<1e-12)return-1;let c=2*(a*n+l*r);if(a*a+l*l<(s+.5)*(s+.5))return-1;let m=a*a+l*l-s*s,d=c*c-4*u*m;if(d<0)return-1;let h=(-c-Math.sqrt(d))/(2*u);return h>=0&&h<=1?h:-1}function Mu(t,e,n,r,o,i,s,a){let l=s-o,u=a-i,c=n*u-r*l;if(Math.abs(c)<1e-12)return-1;let m=((o-t)*u-(i-e)*l)/c,d=((o-t)*r-(i-e)*n)/c;return m>=0&&m<=1&&d>=0&&d<=1?m:-1}function Ji(t,e,n){if(t.shape.kind==="circle"){let i=e-t.x,s=n-t.y;return i*i+s*s<=t.shape.r*t.shape.r}let r=ke(t),o=r.length/2;for(let i=0;i<o;i++){let s=(i+1)%o,a=r[s*2]-r[i*2],l=r[s*2+1]-r[i*2+1];if((e-r[i*2])*l-(n-r[i*2+1])*a>0)return!1}return!0}function Ru(t,e,n,r=65535){let o;for(let i of t.bodies)(i.layer&r)!==0&&Ji(i,e,n)&&(o=i);return o}function Pu(t,e,n,r,o,i,s){let a=t-o,l=e-i,u=n*n+r*r;if(u<1e-12)return-1;let c=2*(a*n+l*r),m=a*a+l*l-s*s,d=c*c-4*u*m;if(d<0)return-1;let h=(-c-Math.sqrt(d))/(2*u);return h>=0&&h<=1?h:-1}function Du(t,e,n,r,o,i=65535){let s=r-e,a=o-n,l=null;for(let u of t.bodies){if((u.layer&i)===0)continue;if(u.shape.kind==="circle"){let d=Pu(e,n,s,a,u.x,u.y,u.shape.r);if(d>=0&&(!l||d<l.t)){let h=e+s*d,p=n+a*d,f=G(h-u.x,p-u.y)||1;l={id:u.id,t:d,x:h,y:p,nx:(h-u.x)/f,ny:(p-u.y)/f}}continue}let c=ke(u),m=c.length/2;for(let d=0;d<m;d++){let h=(d+1)%m,p=c[d*2],f=c[d*2+1],g=c[h*2]-p,k=c[h*2+1]-f,v=s*k-a*g;if(Math.abs(v)<1e-12)continue;let M=((p-e)*k-(f-n)*g)/v,I=((p-e)*a-(f-n)*s)/v;if(!(M<0||M>1||I<0||I>1)&&(!l||M<l.t)){let x=G(g,k)||1;l={id:u.id,t:M,x:e+s*M,y:n+a*M,nx:k/x,ny:-g/x}}}}return l}var Se=t=>Number.isInteger(t)?String(t):(Math.round(t*1e3)/1e3).toString();function Ki(t){let e=Math.max(1,t.length-1);return t.map((n,r)=>typeof n=="string"?{offset:r/e,color:n}:n)}function Eu(t,e=90){let n=e*Math.PI/180,r=j(n)*.5,o=q(n)*.5;return{type:"linear",x1:.5-r,y1:.5-o,x2:.5+r,y2:.5+o,stops:Ki(t)}}function Iu(t,e={}){return{type:"radial",cx:e.cx??.5,cy:e.cy??.5,r:e.r??.5,stops:Ki(t)}}function Lu(t,e){return{color:t,blur:e}}function $u(t,e,n=0,r=0){return{color:t,blur:e,dx:n,dy:r}}function Nu(t){return`<stop offset="${Se(t.offset)}" stop-color="${t.color}"/>`}function Bn(t,e){let n=t.stops.map(Nu).join("");return t.type==="linear"?`<linearGradient id="${e}" x1="${Se(t.x1)}" y1="${Se(t.y1)}" x2="${Se(t.x2)}" y2="${Se(t.y2)}">${n}</linearGradient>`:`<radialGradient id="${e}" cx="${Se(t.cx)}" cy="${Se(t.cy)}" r="${Se(t.r)}">${n}</radialGradient>`}function Yr(t,e){return`<filter id="${e}" x="-60%" y="-60%" width="220%" height="220%"><feDropShadow dx="${Se(t.dx??0)}" dy="${Se(t.dy??0)}" stdDeviation="${Se(t.blur/2)}" flood-color="${t.color}"/></filter>`}function Kr(t){switch(t.kind){case"rect":return{x:t.x,y:t.y,w:t.w,h:t.h};case"circle":return{x:t.cx-t.radius,y:t.cy-t.radius,w:t.radius*2,h:t.radius*2};case"ellipse":return{x:t.cx-t.rx,y:t.cy-t.ry,w:t.rx*2,h:t.ry*2};case"arc":return{x:t.cx-t.radius,y:t.cy-t.radius,w:t.radius*2,h:t.radius*2};case"poly":{if(t.points.length<2)return null;let e=t.points[0],n=t.points[0],r=t.points[1],o=t.points[1];for(let i=0;i<t.points.length;i+=2)e=Math.min(e,t.points[i]),n=Math.max(n,t.points[i]),r=Math.min(r,t.points[i+1]),o=Math.max(o,t.points[i+1]);return{x:e,y:r,w:n-e,h:o-r}}default:return null}}function Zt(t){switch(t.kind){case"rect":return!Number.isFinite(t.x)||!Number.isFinite(t.y)||!Number.isFinite(t.w)||!Number.isFinite(t.h)?"non-finite x/y/w/h":null;case"circle":return!Number.isFinite(t.cx)||!Number.isFinite(t.cy)?"non-finite center":Number.isFinite(t.radius)?t.radius<0?"negative radius":null:"non-finite radius";case"ellipse":return!Number.isFinite(t.cx)||!Number.isFinite(t.cy)?"non-finite center":!Number.isFinite(t.rx)||!Number.isFinite(t.ry)?"non-finite rx/ry":t.rx<0||t.ry<0?"negative rx/ry":null;case"arc":return!Number.isFinite(t.cx)||!Number.isFinite(t.cy)?"non-finite center":Number.isFinite(t.radius)?t.radius<0?"negative radius":!Number.isFinite(t.start)||!Number.isFinite(t.end)?"non-finite start/end":null:"non-finite radius";default:return null}}var Yi=new Set;function Ct(t,e,n){let r=`${t}:${e}`;Yi.has(r)||(Yi.add(r),console.warn(`hayao/render: skipped '${t}' command \u2014 ${e}`,n))}function Qr(t,e,n){let r=s=>n.x+s*n.w,o=s=>n.y+s*n.h,i;if(e.type==="linear")i=t.createLinearGradient(r(e.x1),o(e.y1),r(e.x2),o(e.y2));else{let s=e.r*Math.max(n.w,n.h);i=t.createRadialGradient(r(e.cx),o(e.cy),0,r(e.cx),o(e.cy),s)}for(let s of e.stops)i.addColorStop(Math.max(0,Math.min(1,s.offset)),s.color);return i}function nt(t){let e=[],n=[],r=[];for(let o of t){let i=o.layer??0;i===.5?n.push(o):i<.5?e.push(o):r.push(o)}return{below:e,light:n,above:r}}function rt(t){if(t.length===0)return null;let e=t[0];if(e.kind!=="rect"||e.blend!=="multiply")return null;let n=e,r=[],o=1;for(;o<t.length;){let i=t[o];if(i.kind!=="circle"||i.blend!=="screen")return null;let s={circle:i,shadows:[]};for(o++;o<t.length&&t[o].kind==="poly"&&t[o].blend==="multiply";)s.shadows.push(t[o]),o++;r.push(s)}return{ambient:n,lights:r}}var Fu=t=>(t.layer??0)===.5;function ot(t,e,n,r,o){let i=Math.min(t.width/e,t.height/n)||1,s=(t.width-e*i)/2,a=(t.height-n*i)/2;return{x:(r-t.left-s)/i,y:(o-t.top-a)/i}}function it(t,e,n){let r=Math.min(t.width/e,t.height/n)||1;return{x:(t.width-e*r)/2,y:(t.height-n*r)/2,width:e*r,height:n*r,scale:r}}var N=t=>Number.isInteger(t)?String(t):(Math.round(t*1e3)/1e3).toString();function zn(t){return`matrix(${N(t.a)} ${N(t.b)} ${N(t.c)} ${N(t.d)} ${N(t.e)} ${N(t.f)})`}function Au(t,e,n){let r=[];return r.push(`fill="${e??t.fill??"none"}"`),t.stroke&&(r.push(`stroke="${t.stroke}"`),r.push(`stroke-width="${N(t.strokeWidth??1)}"`),t.round&&r.push('stroke-linejoin="round" stroke-linecap="round"'),t.lineDash&&t.lineDash.length&&r.push(`stroke-dasharray="${t.lineDash.map(N).join(" ")}"`)),t.opacity!==void 0&&t.opacity!==1&&r.push(`opacity="${N(t.opacity)}"`),n&&r.push(`filter="url(#${n})"`),t.blend&&r.push(`style="mix-blend-mode:${t.blend}"`),r.join(" ")}function Wu(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function Bu(t){let e=t.radius,n=t.cx+j(t.start)*e,r=t.cy+q(t.start)*e,o=t.end-t.start,i=(o%Z+Z)%Z;if(i===0&&o!==0&&(i=Z),i>=Z-1e-9){let c=t.cx+j(t.start+Math.PI)*e,m=t.cy+q(t.start+Math.PI)*e;return`M ${N(n)} ${N(r)} A ${N(e)} ${N(e)} 0 1 1 ${N(c)} ${N(m)} A ${N(e)} ${N(e)} 0 1 1 ${N(n)} ${N(r)} Z`}let s=t.cx+j(t.start+i)*e,a=t.cy+q(t.start+i)*e,l=i>Math.PI?1:0,u=`A ${N(e)} ${N(e)} 0 ${l} 1 ${N(s)} ${N(a)}`;return t.sector?`M ${N(t.cx)} ${N(t.cy)} L ${N(n)} ${N(r)} ${u} Z`:`M ${N(n)} ${N(r)} ${u}`}function zu(t,e,n){let r=`transform="${zn(t.transform)}"`,o,i;if(t.gradient){let a=`${n}g`;e.push(Bn(t.gradient,a)),o=`url(#${a})`}t.shadow&&(i=`${n}s`,e.push(Yr(t.shadow,i)));let s=Au(t,o,i);switch(t.kind){case"rect":return`<rect x="${N(t.x)}" y="${N(t.y)}" width="${N(t.w)}" height="${N(t.h)}"${t.r?` rx="${N(t.r)}"`:""} ${r} ${s}/>`;case"circle":return`<circle cx="${N(t.cx)}" cy="${N(t.cy)}" r="${N(t.radius)}" ${r} ${s}/>`;case"ellipse":return`<ellipse cx="${N(t.cx)}" cy="${N(t.cy)}" rx="${N(t.rx)}" ry="${N(t.ry)}" ${r} ${s}/>`;case"arc":return`<path d="${Bu(t)}" ${r} ${s}/>`;case"poly":{let a=[];for(let u=0;u<t.points.length;u+=2)a.push(`${N(t.points[u])},${N(t.points[u+1])}`);return`<${t.closed?"polygon":"polyline"} points="${a.join(" ")}" ${r} ${s}/>`}case"path":return`<path d="${t.d}" ${r} ${s}/>`;case"text":{let a=t.align==="center"?"middle":t.align==="right"?"end":"start",l=t.font?` font-family="${t.font}"`:"",u=t.weight?` font-weight="${t.weight}"`:"",c=o??t.fill??"#000",m=i?` filter="url(#${i})"`:"",d=t.stroke?` stroke="${t.stroke}" stroke-width="${N(t.strokeWidth??1)}" paint-order="stroke"${t.round?' stroke-linejoin="round"':""}`:"",h=t.opacity!==void 0&&t.opacity!==1?` opacity="${N(t.opacity)}"`:"";return`<text x="${N(t.x)}" y="${N(t.y)}" font-size="${N(t.size)}" text-anchor="${a}" dominant-baseline="middle"${l}${u} fill="${c}"${d}${h}${m} ${r}>${Wu(t.text)}</text>`}case"image":{let a=i?` filter="url(#${i})"`:"";return`<image href="${t.href}" x="${N(t.x)}" y="${N(t.y)}" width="${N(t.w)}" height="${N(t.h)}" ${r}${t.opacity!==void 0&&t.opacity!==1?` opacity="${N(t.opacity)}"`:""}${a}/>`}}}function _u(t){let e=[];for(let n=0;n<t.points.length;n+=2)e.push(`${N(t.points[n])},${N(t.points[n+1])}`);return e.join(" ")}function Ou(t,e,n,r,o){let i=t.ambient,s=`<rect x="${N(i.x)}" y="${N(i.y)}" width="${N(i.w)}" height="${N(i.h)}" transform="${zn(i.transform)}" fill="${i.fill??"#000"}"/>`,a=[];return t.lights.forEach((l,u)=>{let c=l.circle,m=`${n}lg${u}`;c.gradient&&e.push(Bn(c.gradient,m));let d=c.gradient?`url(#${m})`:c.fill??"#fff",h=`<circle cx="${N(c.cx)}" cy="${N(c.cy)}" r="${N(c.radius)}" transform="${zn(c.transform)}" fill="${d}"/>`,p=`${n}lm${u}`,f=l.shadows.map(g=>{let v=`#${(g.opacity!==void 0&&g.opacity!==1?Math.round((1-g.opacity)*255):0).toString(16).padStart(2,"0").repeat(3)}`;return`<polygon points="${_u(g)}" transform="${zn(g.transform)}" fill="${v}"/>`}).join("");l.shadows.length?(e.push(`<mask id="${p}"><rect x="0" y="0" width="${N(r)}" height="${N(o)}" fill="#ffffff"/>${f}</mask>`),a.push(`<g style="mix-blend-mode:screen" mask="url(#${p})">${h}</g>`)):a.push(`<g style="mix-blend-mode:screen">${h}</g>`)}),`<g style="mix-blend-mode:multiply; isolation:isolate">${s}${a.join("")}</g>`}function st(t,e="h",n=1280,r=720){let o=[],i=Ke(t),{below:s,light:a,above:l}=nt(i),u=a.length?rt(a):null,c=u?[...s,...l]:i,m=(h,p)=>h.map((f,g)=>{let k=Zt(f);return k?(Ct(f.kind,k,f),""):zu(f,o,`${e}${p+g}`)}).join(""),d;return u?d=m(s,0)+Ou(u,o,e,n,r)+m(l,s.length):d=m(c,0),(o.length?`<defs>${o.join("")}</defs>`:"")+d}function en(t,e,n,r="#ffffff"){return`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${e} ${n}" width="${e}" height="${n}"><rect x="0" y="0" width="${e}" height="${n}" fill="${r}"/>`+st(t,"h",e,n)+"</svg>"}var Zr="http://www.w3.org/2000/svg",at=class{width;height;background;svg;bg;layer;constructor(e){this.width=e.width,this.height=e.height,this.background=e.background??"#ffffff",this.svg=document.createElementNS(Zr,"svg"),this.svg.setAttribute("viewBox",`0 0 ${this.width} ${this.height}`),this.svg.setAttribute("preserveAspectRatio","xMidYMid meet"),this.svg.style.width="100%",this.svg.style.height="100%",this.svg.style.display="block",this.bg=document.createElementNS(Zr,"rect"),this.bg.setAttribute("x","0"),this.bg.setAttribute("y","0"),this.bg.setAttribute("width",String(this.width)),this.bg.setAttribute("height",String(this.height)),this.bg.setAttribute("fill",this.background),this.svg.appendChild(this.bg),this.layer=document.createElementNS(Zr,"g"),this.svg.appendChild(this.layer)}mount(e){e.appendChild(this.svg)}draw(e){this.layer.innerHTML=st(e)}setBackground(e){this.background=e,this.bg.setAttribute("fill",e)}get element(){return this.svg}toDesign(e,n){return ot(this.svg.getBoundingClientRect(),this.width,this.height,e,n)}viewport(){return it(this.svg.getBoundingClientRect(),this.width,this.height)}dispose(){this.svg.remove()}};function es(t,e){let n=e;if(n.gradient){let r=Kr(e);if(r&&r.w>0&&r.h>0)return Qr(t,n.gradient,r);let o=n.gradient.stops;return o.length?o[o.length-1].color:n.fill}return n.fill}function tn(t,e){let n=es(t,e);n&&n!=="none"&&(t.fillStyle=n,t.fill()),e.stroke&&(t.strokeStyle=e.stroke,t.lineWidth=e.strokeWidth??1,e.round&&(t.lineJoin="round",t.lineCap="round"),t.stroke())}function Gu(t,e,n,r,o,i){let s=Math.min(i,r/2,o/2);t.moveTo(e+s,n),t.arcTo(e+r,n,e+r,n+o,s),t.arcTo(e+r,n+o,e,n+o,s),t.arcTo(e,n+o,e,n,s),t.arcTo(e,n,e+r,n,s),t.closePath()}function ts(t,e){switch(e.kind){case"rect":t.beginPath(),e.r?Gu(t,e.x,e.y,e.w,e.h,e.r):t.rect(e.x,e.y,e.w,e.h),tn(t,e);break;case"circle":t.beginPath(),t.arc(e.cx,e.cy,e.radius,0,Math.PI*2),tn(t,e);break;case"ellipse":t.beginPath(),t.ellipse(e.cx,e.cy,e.rx,e.ry,0,0,Math.PI*2),tn(t,e);break;case"arc":t.beginPath(),e.sector&&t.moveTo(e.cx,e.cy),t.arc(e.cx,e.cy,e.radius,e.start,e.end),e.sector&&t.closePath(),tn(t,e);break;case"poly":t.beginPath();for(let n=0;n<e.points.length;n+=2)n===0?t.moveTo(e.points[n],e.points[n+1]):t.lineTo(e.points[n],e.points[n+1]);e.closed&&t.closePath(),tn(t,e);break;case"path":{let n=new Path2D(e.d),r=es(t,e);r&&r!=="none"&&(t.fillStyle=r,t.fill(n)),e.stroke&&(t.strokeStyle=e.stroke,t.lineWidth=e.strokeWidth??1,e.round&&(t.lineJoin="round",t.lineCap="round"),t.stroke(n));break}case"text":t.font=`${e.weight??400} ${e.size}px ${e.font??"sans-serif"}`,t.textAlign=e.align??"left",t.textBaseline="middle",e.stroke&&(t.strokeStyle=e.stroke,t.lineWidth=e.strokeWidth??1,t.lineJoin="round",t.lineCap="round",t.strokeText(e.text,e.x,e.y)),t.fillStyle=e.fill??"#000",t.fillText(e.text,e.x,e.y);break;case"image":break}}function nn(t,e){let n=Zt(e);if(n){Ct(e.kind,n,e);return}t.save();try{let r=e.transform;t.transform(r.a,r.b,r.c,r.d,r.e,r.f),t.globalAlpha=e.opacity??1;let o=e.shadow;o&&(t.shadowColor=o.color,t.shadowBlur=o.blur,t.shadowOffsetX=o.dx??0,t.shadowOffsetY=o.dy??0);let i=e.lineDash;i&&i.length&&t.setLineDash(i),e.blend&&(t.globalCompositeOperation=e.blend),ts(t,e)}catch(r){Ct(e.kind,"paint threw",r)}t.restore()}var Qi=new WeakMap;function Zi(t,e,n){if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(e,n);let r=t.canvas.ownerDocument;if(r&&typeof r.createElement=="function"){let o=r.createElement("canvas");return o.width=e,o.height=n,o}return null}function Vu(t,e,n){let r=Qi.get(t);if(r&&r.w===e&&r.h===n)return r;let o=Zi(t,e,n),i=Zi(t,e,n);if(!o||!i)return null;o.width=e,o.height=n,i.width=e,i.height=n;let s={buffer:o,scratch:i,w:e,h:n};return Qi.set(t,s),s}function Hu(t,e,n,r,o){let i=Math.max(1,Math.round(n*o)),s=Math.max(1,Math.round(r*o)),a=Vu(t,i,s);if(!a)return!1;let l=a.buffer.getContext("2d"),u=a.scratch.getContext("2d");if(!l||!u)return!1;l.setTransform(1,0,0,1,0,0),l.globalCompositeOperation="source-over",l.clearRect(0,0,i,s),l.setTransform(o,0,0,o,0,0),nn(l,{...e.ambient,blend:void 0});for(let c of e.lights){u.setTransform(1,0,0,1,0,0),u.globalCompositeOperation="source-over",u.clearRect(0,0,i,s),u.setTransform(o,0,0,o,0,0),nn(u,{...c.circle,blend:void 0});for(let m of c.shadows){u.save();let d=m.transform;u.setTransform(o,0,0,o,0,0),u.transform(d.a,d.b,d.c,d.d,d.e,d.f),u.globalCompositeOperation="destination-out",u.globalAlpha=m.opacity??1,ts(u,{...m,blend:void 0,fill:"#000000"}),u.restore()}l.setTransform(1,0,0,1,0,0),l.globalCompositeOperation="lighter",l.globalAlpha=1,l.drawImage(a.scratch,0,0)}return t.save(),t.setTransform(1,0,0,1,0,0),t.globalCompositeOperation="multiply",t.globalAlpha=1,t.drawImage(a.buffer,0,0),t.restore(),t.setTransform(o,0,0,o,0,0),t.globalCompositeOperation="source-over",!0}function _n(t,e,n,r,o,i){t.setTransform(i,0,0,i,0,0),t.globalCompositeOperation="source-over",t.fillStyle=o,t.fillRect(0,0,n,r);let s=Ke(e),{below:a,light:l,above:u}=nt(s);for(let c of a)nn(t,c);if(l.length){let c=rt(l);if(!(c?Hu(t,c,n,r,i):!1)){t.setTransform(i,0,0,i,0,0);for(let d of l)nn(t,d);t.setTransform(i,0,0,i,0,0),t.globalCompositeOperation="source-over"}}t.setTransform(i,0,0,i,0,0);for(let c of u)nn(t,c)}var lt=class{width;height;background;canvas;ctx;dpr=1;constructor(e){this.width=e.width,this.height=e.height,this.background=e.background??"#ffffff",this.canvas=document.createElement("canvas"),this.canvas.style.width="100%",this.canvas.style.height="100%",this.canvas.style.objectFit="contain",this.canvas.style.display="block";let n=this.canvas.getContext("2d");if(!n)throw new Error("hayao: 2D canvas context unavailable");this.ctx=n,this.resize()}mount(e){e.appendChild(this.canvas),this.resize()}resize(){this.dpr=Math.min(3,globalThis.devicePixelRatio||1),this.canvas.width=Math.round(this.width*this.dpr),this.canvas.height=Math.round(this.height*this.dpr)}draw(e){_n(this.ctx,e,this.width,this.height,this.background,this.dpr)}get element(){return this.canvas}toDesign(e,n){return ot(this.canvas.getBoundingClientRect(),this.width,this.height,e,n)}viewport(){return it(this.canvas.getBoundingClientRect(),this.width,this.height)}dispose(){this.canvas.remove()}};var qu=`#version 300 es
|
|
2
|
+
out vec2 v_uv;
|
|
3
|
+
void main() {
|
|
4
|
+
const vec2 CORNERS[4] = vec2[](
|
|
5
|
+
vec2(-1.0, -1.0), vec2(1.0, -1.0),
|
|
6
|
+
vec2(-1.0, 1.0), vec2(1.0, 1.0)
|
|
7
|
+
);
|
|
8
|
+
const vec2 UVS[4] = vec2[](
|
|
9
|
+
vec2(0.0, 1.0), vec2(1.0, 1.0),
|
|
10
|
+
vec2(0.0, 0.0), vec2(1.0, 0.0)
|
|
11
|
+
);
|
|
12
|
+
v_uv = UVS[gl_VertexID];
|
|
13
|
+
gl_Position = vec4(CORNERS[gl_VertexID], 0.0, 1.0);
|
|
14
|
+
}`,On=`#version 300 es
|
|
15
|
+
precision mediump float;
|
|
16
|
+
in vec2 v_uv;
|
|
17
|
+
uniform sampler2D u_scene;
|
|
18
|
+
uniform sampler2D u_prev;
|
|
19
|
+
out vec4 fragColor;
|
|
20
|
+
void main() { fragColor = texture(u_prev, v_uv); }`,rn={passthrough:On,pixelate:`#version 300 es
|
|
21
|
+
precision mediump float;
|
|
22
|
+
in vec2 v_uv;
|
|
23
|
+
uniform sampler2D u_prev;
|
|
24
|
+
uniform vec2 u_resolution;
|
|
25
|
+
uniform float u_block;
|
|
26
|
+
out vec4 fragColor;
|
|
27
|
+
void main() {
|
|
28
|
+
float block = max(1.0, u_block > 0.0 ? u_block : 4.0);
|
|
29
|
+
vec2 px = floor(v_uv * u_resolution / block) * block / u_resolution;
|
|
30
|
+
fragColor = texture(u_prev, px);
|
|
31
|
+
}`,vignette:`#version 300 es
|
|
32
|
+
precision mediump float;
|
|
33
|
+
in vec2 v_uv;
|
|
34
|
+
uniform sampler2D u_prev;
|
|
35
|
+
uniform float u_vignette;
|
|
36
|
+
out vec4 fragColor;
|
|
37
|
+
void main() {
|
|
38
|
+
vec4 col = texture(u_prev, v_uv);
|
|
39
|
+
vec2 uv = v_uv - 0.5;
|
|
40
|
+
float d = dot(uv, uv);
|
|
41
|
+
float strength = u_vignette > 0.0 ? u_vignette : 0.4;
|
|
42
|
+
fragColor = col * (1.0 - d * strength * 4.0);
|
|
43
|
+
}`,crt:`#version 300 es
|
|
44
|
+
precision mediump float;
|
|
45
|
+
in vec2 v_uv;
|
|
46
|
+
uniform sampler2D u_prev;
|
|
47
|
+
uniform vec2 u_resolution;
|
|
48
|
+
uniform float u_time;
|
|
49
|
+
uniform float u_crt_lines; // scanline density, default 600
|
|
50
|
+
uniform float u_crt_warp; // barrel strength, default 0.08
|
|
51
|
+
out vec4 fragColor;
|
|
52
|
+
void main() {
|
|
53
|
+
float lines = u_crt_lines > 0.0 ? u_crt_lines : 600.0;
|
|
54
|
+
float warp = u_crt_warp > 0.0 ? u_crt_warp : 0.08;
|
|
55
|
+
// barrel distortion
|
|
56
|
+
vec2 uv = v_uv - 0.5;
|
|
57
|
+
float r2 = dot(uv, uv);
|
|
58
|
+
uv *= 1.0 + warp * r2;
|
|
59
|
+
uv += 0.5;
|
|
60
|
+
if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0) {
|
|
61
|
+
fragColor = vec4(0.0, 0.0, 0.0, 1.0);
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
vec4 col = texture(u_prev, uv);
|
|
65
|
+
// rolling scanlines
|
|
66
|
+
float scan = sin((uv.y * lines + u_time * 40.0) * 3.14159) * 0.5 + 0.5;
|
|
67
|
+
col.rgb *= 0.75 + 0.25 * scan;
|
|
68
|
+
// slight green phosphor tint
|
|
69
|
+
col.rgb = mix(col.rgb, col.rgb * vec3(0.9, 1.05, 0.85), 0.3);
|
|
70
|
+
fragColor = col;
|
|
71
|
+
}`,chromaticAberration:`#version 300 es
|
|
72
|
+
precision mediump float;
|
|
73
|
+
in vec2 v_uv;
|
|
74
|
+
uniform sampler2D u_prev;
|
|
75
|
+
uniform float u_aberration;
|
|
76
|
+
out vec4 fragColor;
|
|
77
|
+
void main() {
|
|
78
|
+
float amt = u_aberration > 0.0 ? u_aberration : 0.004;
|
|
79
|
+
vec2 dir = v_uv - 0.5;
|
|
80
|
+
float r = texture(u_prev, v_uv + dir * amt * 2.0).r;
|
|
81
|
+
float g = texture(u_prev, v_uv).g;
|
|
82
|
+
float b = texture(u_prev, v_uv - dir * amt * 2.0).b;
|
|
83
|
+
fragColor = vec4(r, g, b, 1.0);
|
|
84
|
+
}`,hueRotate:`#version 300 es
|
|
85
|
+
precision mediump float;
|
|
86
|
+
in vec2 v_uv;
|
|
87
|
+
uniform sampler2D u_prev;
|
|
88
|
+
uniform float u_hue_shift; // radians; if 0 uses u_time
|
|
89
|
+
uniform float u_time;
|
|
90
|
+
out vec4 fragColor;
|
|
91
|
+
void main() {
|
|
92
|
+
float angle = u_hue_shift != 0.0 ? u_hue_shift : u_time * 0.5;
|
|
93
|
+
vec4 col = texture(u_prev, v_uv);
|
|
94
|
+
// Hue rotate via Rodrigues in YIQ-ish space
|
|
95
|
+
float c = cos(angle), s = sin(angle);
|
|
96
|
+
mat3 m = mat3(
|
|
97
|
+
0.299+0.701*c+0.168*s, 0.587-0.587*c+0.330*s, 0.114-0.114*c-0.497*s,
|
|
98
|
+
0.299-0.299*c-0.328*s, 0.587+0.413*c+0.035*s, 0.114-0.114*c+0.292*s,
|
|
99
|
+
0.299-0.300*c+1.250*s, 0.587-0.588*c-1.050*s, 0.114+0.886*c-0.203*s
|
|
100
|
+
);
|
|
101
|
+
fragColor = vec4(m * col.rgb, col.a);
|
|
102
|
+
}`,wave:`#version 300 es
|
|
103
|
+
precision mediump float;
|
|
104
|
+
in vec2 v_uv;
|
|
105
|
+
uniform sampler2D u_prev;
|
|
106
|
+
uniform float u_time;
|
|
107
|
+
uniform float u_wave_amp;
|
|
108
|
+
uniform float u_wave_freq;
|
|
109
|
+
out vec4 fragColor;
|
|
110
|
+
void main() {
|
|
111
|
+
float amp = u_wave_amp > 0.0 ? u_wave_amp : 0.003;
|
|
112
|
+
float freq = u_wave_freq > 0.0 ? u_wave_freq : 8.0;
|
|
113
|
+
vec2 uv = v_uv;
|
|
114
|
+
uv.x += sin(uv.y * freq + u_time * 2.5) * amp;
|
|
115
|
+
uv.y += cos(uv.x * freq + u_time * 2.5) * amp;
|
|
116
|
+
fragColor = texture(u_prev, clamp(uv, 0.0, 1.0));
|
|
117
|
+
}`,bloomBrightpass:`#version 300 es
|
|
118
|
+
precision mediump float;
|
|
119
|
+
in vec2 v_uv;
|
|
120
|
+
uniform sampler2D u_prev;
|
|
121
|
+
uniform float u_bloom_threshold;
|
|
122
|
+
out vec4 fragColor;
|
|
123
|
+
void main() {
|
|
124
|
+
vec4 col = texture(u_prev, v_uv);
|
|
125
|
+
float lum = dot(col.rgb, vec3(0.2126, 0.7152, 0.0722));
|
|
126
|
+
float thresh = u_bloom_threshold > 0.0 ? u_bloom_threshold : 0.55;
|
|
127
|
+
float weight = smoothstep(thresh - 0.05, thresh + 0.05, lum);
|
|
128
|
+
fragColor = col * weight;
|
|
129
|
+
}`,bloomHBlur:`#version 300 es
|
|
130
|
+
precision mediump float;
|
|
131
|
+
in vec2 v_uv;
|
|
132
|
+
uniform sampler2D u_prev;
|
|
133
|
+
uniform vec2 u_resolution;
|
|
134
|
+
uniform float u_bloom_spread;
|
|
135
|
+
out vec4 fragColor;
|
|
136
|
+
void main() {
|
|
137
|
+
float spread = u_bloom_spread > 0.0 ? u_bloom_spread : 1.0;
|
|
138
|
+
vec2 texel = vec2(spread / u_resolution.x, 0.0);
|
|
139
|
+
const float W[7] = float[](0.0625, 0.125, 0.1875, 0.25, 0.1875, 0.125, 0.0625);
|
|
140
|
+
vec4 sum = vec4(0.0);
|
|
141
|
+
for (int i = 0; i < 7; i++)
|
|
142
|
+
sum += texture(u_prev, clamp(v_uv + float(i-3) * texel, 0.0, 1.0)) * W[i];
|
|
143
|
+
fragColor = sum;
|
|
144
|
+
}`,bloomVBlur:`#version 300 es
|
|
145
|
+
precision mediump float;
|
|
146
|
+
in vec2 v_uv;
|
|
147
|
+
uniform sampler2D u_prev;
|
|
148
|
+
uniform vec2 u_resolution;
|
|
149
|
+
uniform float u_bloom_spread;
|
|
150
|
+
out vec4 fragColor;
|
|
151
|
+
void main() {
|
|
152
|
+
float spread = u_bloom_spread > 0.0 ? u_bloom_spread : 1.0;
|
|
153
|
+
vec2 texel = vec2(0.0, spread / u_resolution.y);
|
|
154
|
+
const float W[7] = float[](0.0625, 0.125, 0.1875, 0.25, 0.1875, 0.125, 0.0625);
|
|
155
|
+
vec4 sum = vec4(0.0);
|
|
156
|
+
for (int i = 0; i < 7; i++)
|
|
157
|
+
sum += texture(u_prev, clamp(v_uv + float(i-3) * texel, 0.0, 1.0)) * W[i];
|
|
158
|
+
fragColor = sum;
|
|
159
|
+
}`,bloomComposite:`#version 300 es
|
|
160
|
+
precision mediump float;
|
|
161
|
+
in vec2 v_uv;
|
|
162
|
+
uniform sampler2D u_scene;
|
|
163
|
+
uniform sampler2D u_prev;
|
|
164
|
+
uniform float u_bloom_intensity;
|
|
165
|
+
out vec4 fragColor;
|
|
166
|
+
void main() {
|
|
167
|
+
vec4 scene = texture(u_scene, v_uv);
|
|
168
|
+
vec4 bloom = texture(u_prev, v_uv);
|
|
169
|
+
float intensity = u_bloom_intensity > 0.0 ? u_bloom_intensity : 0.8;
|
|
170
|
+
fragColor = vec4(scene.rgb + bloom.rgb * intensity, scene.a);
|
|
171
|
+
}`},ju=[{shader:rn.bloomBrightpass},{shader:rn.bloomHBlur},{shader:rn.bloomVBlur},{shader:rn.bloomComposite}];function ns(t,e,n){let r=t.createShader(e);if(!r)throw new Error("hayao/webgl: createShader failed");if(t.shaderSource(r,n),t.compileShader(r),!t.getShaderParameter(r,t.COMPILE_STATUS)){let o=t.getShaderInfoLog(r);throw t.deleteShader(r),new Error(`hayao/webgl: shader compile error
|
|
172
|
+
${o}`)}return r}function Uu(t,e){let n=ns(t,t.VERTEX_SHADER,qu),r=ns(t,t.FRAGMENT_SHADER,e),o=t.createProgram();if(!o)throw new Error("hayao/webgl: createProgram failed");if(t.attachShader(o,n),t.attachShader(o,r),t.linkProgram(o),t.deleteShader(n),t.deleteShader(r),!t.getProgramParameter(o,t.LINK_STATUS)){let i=t.getProgramInfoLog(o);throw t.deleteProgram(o),new Error(`hayao/webgl: program link error
|
|
173
|
+
${i}`)}return o}function rs(t,e,n,r){let o=t.getUniformLocation(e,n);o!==null&&(typeof r=="number"?t.uniform1f(o,r):r.length===2?t.uniform2f(o,r[0],r[1]):r.length===3?t.uniform3f(o,r[0],r[1],r[2]):t.uniform4f(o,r[0],r[1],r[2],r[3]))}function Xu(t,e,n){let r=t.createTexture();t.bindTexture(t.TEXTURE_2D,r),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,e,n,0,t.RGBA,t.UNSIGNED_BYTE,null),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE);let o=t.createFramebuffer();return t.bindFramebuffer(t.FRAMEBUFFER,o),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,r,0),t.bindFramebuffer(t.FRAMEBUFFER,null),{fbo:o,tex:r}}var on=class{width;height;background;glCanvas;gl;offscreen;ctx2d;dpr=1;sceneTex;fbos=[];programs=[];passUniforms=[];vao;framesDrawn=0;uniforms=new Map;constructor(e){this.width=e.width,this.height=e.height,this.background=e.background??"#ffffff",this.glCanvas=document.createElement("canvas"),this.glCanvas.style.width="100%",this.glCanvas.style.height="100%",this.glCanvas.style.objectFit="contain",this.glCanvas.style.display="block";let n=this.glCanvas.getContext("webgl2",{alpha:!1,antialias:!1,preserveDrawingBuffer:!1});if(!n)throw new Error("hayao/webgl: WebGL2 unavailable \u2014 fall back to Canvas2DRenderer");this.gl=n,this.offscreen=document.createElement("canvas");let r=this.offscreen.getContext("2d");if(!r)throw new Error("hayao/webgl: Canvas2D unavailable for rasterization");this.ctx2d=r,this.resize();let o=n.createVertexArray();if(!o)throw new Error("hayao/webgl: createVertexArray failed");this.vao=o;let i=n.createTexture();if(!i)throw new Error("hayao/webgl: createTexture failed");this.sceneTex=i,n.bindTexture(n.TEXTURE_2D,i),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,n.LINEAR),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,n.LINEAR),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE),this.buildPipeline([{shader:e.postProcess??On}])}mount(e){e.appendChild(this.glCanvas),this.resize()}resize(){this.dpr=Math.min(3,globalThis.devicePixelRatio||1);let e=Math.round(this.width*this.dpr),n=Math.round(this.height*this.dpr);this.glCanvas.width=e,this.glCanvas.height=n,this.offscreen.width=e,this.offscreen.height=n,this.gl.viewport(0,0,e,n);for(let r of this.fbos)this.gl.bindTexture(this.gl.TEXTURE_2D,r.tex),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,e,n,0,this.gl.RGBA,this.gl.UNSIGNED_BYTE,null)}buildPipeline(e){let n=this.gl,r=this.glCanvas.width||Math.round(this.width*this.dpr),o=this.glCanvas.height||Math.round(this.height*this.dpr);for(let i of this.programs)n.deleteProgram(i);for(let i of this.fbos)n.deleteFramebuffer(i.fbo),n.deleteTexture(i.tex);this.programs=[],this.fbos=[],this.passUniforms=[];for(let i of e)this.programs.push(Uu(n,i.shader)),this.passUniforms.push(i.uniforms??{});for(let i=0;i<e.length-1;i++)this.fbos.push(Xu(n,r,o))}draw(e){let n=this.gl,r=this.programs.length,o=this.framesDrawn++/60,i=this.glCanvas.width,s=this.glCanvas.height;_n(this.ctx2d,e,this.width,this.height,this.background,this.dpr),n.activeTexture(n.TEXTURE0),n.bindTexture(n.TEXTURE_2D,this.sceneTex),n.texImage2D(n.TEXTURE_2D,0,n.RGBA,n.RGBA,n.UNSIGNED_BYTE,this.offscreen),n.bindVertexArray(this.vao);for(let a=0;a<r;a++){let l=this.programs[a];a===r-1?(n.bindFramebuffer(n.FRAMEBUFFER,null),n.viewport(0,0,i,s)):(n.bindFramebuffer(n.FRAMEBUFFER,this.fbos[a].fbo),n.viewport(0,0,i,s)),n.useProgram(l),n.uniform1i(n.getUniformLocation(l,"u_scene"),0),n.activeTexture(n.TEXTURE1),a===0?n.bindTexture(n.TEXTURE_2D,this.sceneTex):n.bindTexture(n.TEXTURE_2D,this.fbos[a-1].tex),n.uniform1i(n.getUniformLocation(l,"u_prev"),1),n.activeTexture(n.TEXTURE0),n.uniform1f(n.getUniformLocation(l,"u_time"),o),n.uniform2f(n.getUniformLocation(l,"u_resolution"),i,s);for(let[c,m]of this.uniforms)rs(n,l,c,m);for(let[c,m]of Object.entries(this.passUniforms[a]))rs(n,l,c,m);n.drawArrays(n.TRIANGLE_STRIP,0,4)}}setUniform(e,n){return this.uniforms.set(e,n),this}clearUniform(e){return this.uniforms.delete(e),this}setPipeline(e){return this.buildPipeline(e.length?e:[{shader:On}]),this}setPostProcess(e){return this.setPipeline([{shader:e}])}clearPostProcess(){return this.setPostProcess(On)}get element(){return this.glCanvas}toDesign(e,n){return ot(this.glCanvas.getBoundingClientRect(),this.width,this.height,e,n)}viewport(){return it(this.glCanvas.getBoundingClientRect(),this.width,this.height)}dispose(){let e=this.gl;e.deleteTexture(this.sceneTex);for(let n of this.programs)e.deleteProgram(n);for(let n of this.fbos)e.deleteFramebuffer(n.fbo),e.deleteTexture(n.tex);e.deleteVertexArray(this.vao),this.glCanvas.remove()}};var eo=class{width;height;background;last=[];frameCount=0;constructor(e){this.width=e.width,this.height=e.height,this.background=e.background??"#ffffff"}draw(e){this.last=e,this.frameCount++}get commands(){return this.last}count(e){return this.last.filter(n=>n.kind===e).length}toSVGString(){return en(this.last,this.width,this.height,this.background)}};function Ju(t,e,n=0,r=oe){let o=Math.max(0,Math.min(e.border,t.w/2,t.h/2)),i=e.fill??"#fbf6ea",s=e.edge??i,a=e.corner??s,l=[],u=t.x,c=t.x+o,m=t.x+t.w-o,d=t.y,h=t.y+o,p=t.y+t.h-o,f=t.w-2*o,g=t.h-2*o,k=(M,I,x,b,w,C)=>{x<=0||b<=0||l.push({kind:"rect",x:M,y:I,w:x,h:b,r:C,fill:w,transform:r,z:n})};k(c,h,f,g,i),k(c,d,f,o,e.highlight??s),k(c,p,f,o,e.shadow??s),k(u,h,o,g,e.highlight??s),k(m,h,o,g,e.shadow??s);let v=e.radius;return k(u,d,o,o,a,v),k(m,d,o,o,a,v),k(u,p,o,o,a,v),k(m,p,o,o,a,v),e.stroke&&l.push({kind:"rect",x:t.x,y:t.y,w:t.w,h:t.h,r:e.radius,fill:"none",stroke:e.stroke,strokeWidth:e.strokeWidth??2,transform:r,z:n+.001}),l}var Yu={parchment:()=>({border:10,fill:"#fbf6ea",edge:"#efe4c8",corner:"#e2d3a8",highlight:"#fdfaf0",shadow:"#d9c79c",stroke:"#b8a06a",strokeWidth:2,radius:4}),slate:()=>({border:8,fill:"#2c3040",edge:"#363c4f",corner:"#454c63",highlight:"#4a5268",shadow:"#20242f",stroke:"#151821",strokeWidth:2,radius:3})};function Ku(t,e,n=0){let r=[];for(let o=0;o<t;o++){let i=n+o/t*Z;r.push(j(i)*e,q(i)*e)}return r}function Qu(t,e,n,r=-Math.PI/2){let o=[];for(let i=0;i<t*2;i++){let s=i%2===0?e:n,a=r+i/(t*2)*Z;o.push(j(a)*s,q(a)*s)}return o}function Zu(t,e,n=.25,r=7){let o=[];for(let i=0;i<r;i++){let s=i/r*Z,a=e*(1-n+t.float()*n*2);o.push({x:j(s)*a,y:q(s)*a})}return os(o)}function os(t,e=1){let n=t.length;if(n<3)return"";let r=s=>t[(s%n+n)%n],o=s=>Math.round(s*100)/100,i=`M ${o(r(0).x)} ${o(r(0).y)}`;for(let s=0;s<n;s++){let a=r(s-1),l=r(s),u=r(s+1),c=r(s+2),m=l.x+(u.x-a.x)/6*e,d=l.y+(u.y-a.y)/6*e,h=u.x-(c.x-l.x)/6*e,p=u.y-(c.y-l.y)/6*e;i+=` C ${o(m)} ${o(d)}, ${o(h)} ${o(p)}, ${o(u.x)} ${o(u.y)}`}return i+" Z"}function ec(t,e=1){let n=t.length;if(n<2)return"";let r=i=>Math.round(i*100)/100,o=`M ${r(t[0].x)} ${r(t[0].y)}`;for(let i=0;i<n-1;i++){let s=t[Math.max(0,i-1)],a=t[i],l=t[i+1],u=t[Math.min(n-1,i+2)],c=a.x+(l.x-s.x)/6*e,m=a.y+(l.y-s.y)/6*e,d=l.x-(u.x-a.x)/6*e,h=l.y-(u.y-a.y)/6*e;o+=` C ${r(c)} ${r(m)}, ${r(d)} ${r(h)}, ${r(l.x)} ${r(l.y)}`}return o}var Tt=class t{width;height;data;constructor(e,n,r){this.width=e,this.height=n,this.data=r??new Uint8Array(e*n)}get(e,n){return e<0||n<0||e>=this.width||n>=this.height?0:this.data[n*this.width+e]}set(e,n,r){e<0||n<0||e>=this.width||n>=this.height||(this.data[n*this.width+e]=r)}static fromRows(e,n){let r=e.length,o=e.reduce((s,a)=>Math.max(s,a.length),0),i=new t(o,r);for(let s=0;s<r;s++){let a=e[s];for(let l=0;l<a.length;l++)i.data[s*o+l]=n[a[l]]??0}return i}remap(e){let n=new Uint8Array(this.data.length);for(let r=0;r<this.data.length;r++)n[r]=e[this.data[r]]??0;return new t(this.width,this.height,n)}};function is(t){if(typeof t=="bigint")return t;let e=t.trim();return e.startsWith("0x")||e.startsWith("0b")||e.startsWith("0o")?BigInt(e):BigInt("0x"+e)}function tc(t,e,n){let r=is(t),o=e*n,i=new Tt(e,n);for(let s=0;s<o;s++)i.data[s]=Number(r>>BigInt(o-1-s)&1n);return i}function nc(t,e,n){let r=is(t),o=e*n,i=new Tt(e,n);for(let s=0;s<o;s++){let a=BigInt((o-1-s)*2);i.data[s]=Number(r>>a&3n)}return i}function rc(t,e,n){let r=new Tt(e,n),o=0;for(let i=0;i+1<t.length;i+=2){let s=t[i],a=t[i+1];for(let l=0;l<s&&o<r.data.length;l++)r.data[o++]=a}return r}function oc(t){let e=[],n=t.data;for(let r=0;r<n.length;){let o=n[r],i=1;for(;r+i<n.length&&n[r+i]===o;)i++;e.push(i,o),r+=i}return e}function ss(t,e,n={}){let r=n.cell??1,o=n.x??0,i=n.y??0,s=n.z??0,a=n.transform??oe,l=[];for(let u=0;u<t.height;u++){let c=0;for(;c<t.width;){let m=t.get(c,u),d=e[m];if(d==null){c++;continue}let h=1;for(;c+h<t.width&&t.get(c+h,u)===m;)h++;l.push({kind:"rect",x:o+c*r,y:i+u*r,w:h*r,h:r,transform:a,z:s,fill:d}),c+=h}}return l}var to=class extends _{type="TextureSprite";buffer;palette;cell;center;constructor(e){super(e),this.buffer=e.buffer,this.palette=e.palette,this.cell=e.cell??1,this.center=e.center??!0,this.cosmetic=!0}draw(e,n){let r=this.cell,o=this.center?-(this.buffer.width*r)/2:0,i=this.center?-(this.buffer.height*r)/2:0;for(let s of ss(this.buffer,this.palette,{cell:r,x:o,y:i,z:this.z,transform:n}))e.push(s)}};var ic={A:[".#.","#.#","###","#.#","#.#"],B:["##.","#.#","##.","#.#","##."],C:[".##","#..","#..","#..",".##"],D:["##.","#.#","#.#","#.#","##."],E:["###","#..","##.","#..","###"],F:["###","#..","##.","#..","#.."],G:[".##","#..","#.#","#.#",".##"],H:["#.#","#.#","###","#.#","#.#"],I:["#","#","#","#","#"],J:["..#","..#","..#","#.#",".#."],K:["#.#","##.","#..","##.","#.#"],L:["#..","#..","#..","#..","###"],M:["#...#","##.##","#.#.#","#...#","#...#"],N:["#...#","##..#","#.#.#","#..##","#...#"],O:[".#.","#.#","#.#","#.#",".#."],P:["##.","#.#","##.","#..","#.."],Q:[".#.","#.#","#.#","#.#",".##"],R:["##.","#.#","##.","#.#","#.#"],S:[".##","#..",".#.","..#","##."],T:["###",".#.",".#.",".#.",".#."],U:["#.#","#.#","#.#","#.#","###"],V:["#.#","#.#","#.#","#.#",".#."],W:["#...#","#...#","#.#.#","##.##","#...#"],X:["#.#","#.#",".#.","#.#","#.#"],Y:["#.#","#.#",".#.",".#.",".#."],Z:["###","..#",".#.","#..","###"],0:[".#.","#.#","#.#","#.#",".#."],1:[".#.","##.",".#.",".#.","###"],2:["##.","..#",".#.","#..","###"],3:["##.","..#",".#.","..#","##."],4:["#.#","#.#","###","..#","..#"],5:["###","#..","##.","..#","##."],6:[".##","#..","##.","#.#",".#."],7:["###","..#",".#.",".#.",".#."],8:[".#.","#.#",".#.","#.#",".#."],9:[".#.","#.#",".##","..#","##."],".":[".",".",".",".","#"],",":["..","..","..",".#","#."],"!":["#","#","#",".","#"],"?":["##.","..#",".#.","...",".#."],":":[".","#",".","#","."],";":["..",".#","..",".#","#."],"-":["...","...","###","...","..."],"+":["...",".#.","###",".#.","..."],"=":["...","###","...","###","..."],"/":["..#","..#",".#.","#..","#.."],"'":["#","#",".",".","."],'"':["#.#","#.#","...","...","..."],"(":[".#","#.","#.","#.",".#"],")":["#.",".#",".#",".#","#."],"<":["..#",".#.","#..",".#.","..#"],">":["#..",".#.","..#",".#.","#.."],"%":["#.#","..#",".#.","#..","#.#"],"*":["...","#.#",".#.","#.#","..."],"#":["#.#","###","#.#","###","#.#"]},no={height:5,tracking:1,spaceWidth:3,glyphs:ic};function as(t,e={}){let n=[],r=[],o=0,i=0;for(;o<t.length;){let s=t[o];if(s==="{"&&t[o+1]==="{"){n.push({ch:"{",color:r[r.length-1],i:i++}),o+=2;continue}if(s==="{"){let a=t.indexOf("}",o);if(a===-1){n.push({ch:s,color:r[r.length-1],i:i++}),o++;continue}let l=t.slice(o+1,a);l==="/"?r.pop():r.push(l[0]==="#"?l:e[l]??l),o=a+1;continue}n.push({ch:s,color:r[r.length-1],i:i++}),o++}return n}function ls(t,e){if(e===" "||e===`
|
|
174
|
+
`)return e;let n=e.toUpperCase();return t.glyphs[n]?n:t.glyphs[e]?e:t.glyphs["?"]?"?":" "}function us(t,e){if(e===" ")return t.spaceWidth;let n=t.glyphs[e];return n?n[0].length:t.spaceWidth}function Mt(t,e){let n=0;for(let r=0;r<e.length;r++)n+=us(t,e[r].ch),r<e.length-1&&(n+=t.tracking);return n}function sc(t,e){return Mt(t,[...e].map((n,r)=>({ch:ls(t,n),i:r})))}function cs(t,e,n={}){let r=n.lineSpacing??1,o=typeof e=="string"?[...e].map((m,d)=>({ch:m,i:d})):e.map(m=>({...m})),i=[[]];for(let m of o)m.ch===`
|
|
175
|
+
`?i.push([]):i[i.length-1].push({...m,ch:ls(t,m.ch)});let s=[];for(let m of i){if(n.maxWidth===void 0){s.push(m);continue}let d=[],h=[],p=()=>{if(h.length===0)return;let f=d.length?t.spaceWidth+t.tracking:0;d.length&&Mt(t,d)+f+Mt(t,h)>n.maxWidth&&(s.push(d),d=[]),d.length&&d.push({ch:" ",i:-1}),d.push(...h),h=[]};for(let f of m)f.ch===" "?p():h.push(f);p(),s.push(d)}let a=[],l=0;for(let m of s)l=Math.max(l,Mt(t,m));let u=n.maxWidth??l,c=0;for(let m of s){let d=Mt(t,m),h=n.align==="center"?Math.floor((u-d)/2):n.align==="right"?u-d:0;for(let p of m){let f=us(t,p.ch);p.ch!==" "&&a.push({ch:p.ch,color:p.color,i:p.i,x:h,y:c,w:f}),h+=f+t.tracking}c+=t.height+r}return{glyphs:a,width:u,height:s.length*(t.height+r)-r,lines:s.length}}function ms(t,e,n){if(n<=0)return t;let r=Math.floor(e*n);return r<0?0:r>t?t:r}function ds(t,e,n={}){let r=n.cell??2,o=n.x??0,i=n.y??0,s=n.z??0,a=n.transform??oe,l=n.color??"#000",u=n.reveal,c=[];for(let m of e.glyphs){if(u!==void 0&&m.i>=u)continue;let d=t.glyphs[m.ch];if(!d)continue;let h=m.color??l;for(let p=0;p<d.length;p++){let f=d[p],g=0;for(;g<f.length;){if(f[g]!=="#"){g++;continue}let k=1;for(;g+k<f.length&&f[g+k]==="#";)k++;c.push({kind:"rect",x:o+(m.x+g)*r,y:i+(m.y+p)*r,w:k*r,h:r,transform:a,z:s,fill:h}),g+=k}}}return c}var ro=class extends _{type="BitmapText";text;font;cell;color;colorMap;maxWidth;lineSpacing;align;charsPerSec;center;startTime=0;constructor(e){super(e),this.text=e.text,this.font=e.font??no,this.cell=e.cell??2,this.color=e.color??"#000",this.colorMap=e.colorMap??{},this.maxWidth=e.maxWidth,this.lineSpacing=e.lineSpacing??1,this.align=e.align??"left",this.charsPerSec=e.charsPerSec,this.center=e.center??!1,this.cosmetic=!0}onReady(){this.startTime=this.world?.time??0}restartReveal(){this.startTime=this.world?.time??0}buildLayout(){let e=as(this.text,this.colorMap);return cs(this.font,e,{maxWidth:this.maxWidth,lineSpacing:this.lineSpacing,align:this.align})}draw(e,n){let r=this.buildLayout(),o;if(this.charsPerSec!==void 0){let a=(this.world?.time??0)-this.startTime;o=ms(this.text.length,a,this.charsPerSec)}let i=this.center?-(r.width*this.cell)/2:0,s=this.center?-(r.height*this.cell)/2:0;for(let a of ds(this.font,r,{cell:this.cell,x:i,y:s,z:this.z,color:this.color,transform:n,reveal:o}))e.push(a)}};function Rt(t,e,n=0){return{cols:t,rows:e,cells:new Array(t*e).fill(n)}}function hs(t,e,n){return e<0||n<0||e>=t.cols||n>=t.rows?1:t.cells[n*t.cols+e]}function Be(t,e,n,r){e<0||n<0||e>=t.cols||n>=t.rows||(t.cells[n*t.cols+e]=r)}function oo(t,e,n){let r=0;for(let o=-1;o<=1;o++)for(let i=-1;i<=1;i++)i===0&&o===0||hs(t,e+i,n+o)===1&&r++;return r}function ac(t,e=32){let n=t.cells.map(r=>r===1?U.SOLID:U.EMPTY);return{cols:t.cols,rows:t.rows,tileSize:e,tiles:n}}function fs(t,e,n=0){let r=(n^2654435769)>>>0;return r=Math.imul(r^(t|0),2246822507)>>>0,r=Math.imul(r^(e|0),3266489909)>>>0,r^=r>>>13,r=Math.imul(r,668265263)>>>0,r^=r>>>15,r>>>0}function ut(t,e,n=0){return fs(t,e,n)/4294967296}function lc(t,e,n,r=0){return Math.floor(ut(t,e,r)*n)}function bs(t,e,n,r=0){return ut(t,e,r)<n}function uc(t,e,n,r,o,i=0){let s=[];for(let a=e;a<e+r;a++)for(let l=t;l<t+n;l++)bs(l,a,o,i)&&s.push({x:l,y:a});return s}var ps=t=>t*t*(3-2*t);function gs(t,e,n=0){let r=Math.floor(t),o=Math.floor(e),i=ps(t-r),s=ps(e-o),a=ut(r,o,n),l=ut(r+1,o,n),u=ut(r,o+1,n),c=ut(r+1,o+1,n),m=a+(l-a)*i,d=u+(c-u)*i;return m+(d-m)*s}function io(t,e,n=0,r={}){let o=r.octaves??4,i=r.lacunarity??2,s=r.gain??.5,a=1,l=1,u=0,c=0;for(let m=0;m<o;m++)u+=a*gs(t*l,e*l,n+m),c+=a,a*=s,l*=i;return c===0?0:u/c}function cc(t,e){let{cols:n,rows:r}=e,o=e.fill??.45,i=e.steps??4,s=e.birth??5,a=e.survive??4,l=e.border??!0,u=Rt(n,r,0);for(let c=0;c<r;c++)for(let m=0;m<n;m++){let d=l&&(m===0||c===0||m===n-1||c===r-1);Be(u,m,c,d||t.chance(o)?1:0)}for(let c=0;c<i;c++){let m=Rt(n,r,0);for(let d=0;d<r;d++)for(let h=0;h<n;h++){if(l&&(h===0||d===0||h===n-1||d===r-1)){Be(m,h,d,1);continue}let p=oo(u,h,d),f=u.cells[d*n+h]===1;Be(m,h,d,(f?p>=a:p>=s)?1:0)}u=m}return u}function so(t,e){let n=e.scale??.08,r=e.seed??0,o=io(t*n,0,r,e.fractal)*2-1,i=Math.round(e.base+o*e.amplitude);return(e.minRow!==void 0||e.maxRow!==void 0)&&(i=Q(i,e.minRow??-1/0,e.maxRow??1/0)),i}function mc(t,e,n){let r=new Array(e);for(let o=0;o<e;o++)r[o]=so(t+o,n);return r}function dc(t,e,n){return e>=so(t,n)}function ao(t){return{x:Math.floor(t.x+t.w/2),y:Math.floor(t.y+t.h/2)}}function hc(t,e){return t.x<=e.x+e.w&&t.x+t.w>=e.x&&t.y<=e.y+e.h&&t.y+t.h>=e.y}function pc(t,e){for(let n=e.y;n<e.y+e.h;n++)for(let r=e.x;r<e.x+e.w;r++)Be(t,r,n,0)}function ys(t,e,n,r){for(let o=Math.min(e,n);o<=Math.max(e,n);o++)Be(t,o,r,0)}function xs(t,e,n,r){for(let o=Math.min(e,n);o<=Math.max(e,n);o++)Be(t,r,o,0)}function fc(t,e){let{cols:n,rows:r}=e,o=e.attempts??12,i=e.minSize??4,s=e.maxSize??8,a=e.border??!0?1:0,l=Rt(n,r,1),u=[];for(let c=0;c<o;c++){let m=t.intRange(i,s),d=t.intRange(i,s),h=t.intRange(a,n-m-a-1),p=t.intRange(a,r-d-a-1);if(h<a||p<a)continue;let f={x:h,y:p,w:m,h:d};if(!u.some(g=>hc(f,g))){if(pc(l,f),u.length>0){let g=ao(u[u.length-1]),k=ao(f);t.chance(.5)?(ys(l,g.x,k.x,g.y),xs(l,g.y,k.y,k.x)):(xs(l,g.y,k.y,g.x),ys(l,g.x,k.x,k.y))}u.push(f)}}return{rooms:u,grid:l}}var be=44100;function uo(t,e=be){let n=Math.max(0,Math.round(t*e));return{sampleRate:e,left:new Float32Array(n),right:new Float32Array(n)}}function bc(t){return t.left.length}function gc(t){return t.left.length/t.sampleRate}function vs(t){let n=(Q(t,-1,1)+1)*.5*(Math.PI/2);return{l:j(n),r:q(n)}}function co(t,e,n,r=1,o=0){let{l:i,r:s}=vs(o),a=r*i,l=r*s,u=t.left.length,c=Math.round(n);for(let m=0;m<e.length;m++){let d=c+m;if(d<0)continue;if(d>=u)break;let h=e[m];t.left[d]+=h*a,t.right[d]+=h*l}}function ws(t){let e=0,{left:n,right:r}=t;for(let o=0;o<n.length;o++){let i=n[o]<0?-n[o]:n[o];i>e&&(e=i);let s=r[o]<0?-r[o]:r[o];s>e&&(e=s)}return e}function lo(t){return t/Math.sqrt(1+t*t)}function mo(t){let{left:e,right:n}=t;for(let r=0;r<e.length;r++)e[r]=lo(e[r]),n[r]=lo(n[r])}function ho(t,e=.89){let n=ws(t);if(n<1e-9)return;let r=e/n,{left:o,right:i}=t;for(let s=0;s<o.length;s++)o[s]*=r,i[s]*=r}function yc(t){let{left:e,right:n,sampleRate:r}=t,o=e.length,i=2,a=i*2,l=o*a,u=new Uint8Array(44+l),c=new DataView(u.buffer),m=(h,p)=>{for(let f=0;f<p.length;f++)c.setUint8(h+f,p.charCodeAt(f))};m(0,"RIFF"),c.setUint32(4,36+l,!0),m(8,"WAVE"),m(12,"fmt "),c.setUint32(16,16,!0),c.setUint16(20,1,!0),c.setUint16(22,i,!0),c.setUint32(24,r,!0),c.setUint32(28,r*a,!0),c.setUint16(32,a,!0),c.setUint16(34,16,!0),m(36,"data"),c.setUint32(40,l,!0);let d=44;for(let h=0;h<o;h++){let p=Q(e[h],-1,1),f=Q(n[h],-1,1);c.setInt16(d,(p<0?p*32768:p*32767)|0,!0),c.setInt16(d+2,(f<0?f*32768:f*32767)|0,!0),d+=4}return u}function xc(t){let e=2166136261;for(let n=0;n<t.length;n++){let r=Q(t[n],-1,1)*32767|0;e^=r&255,e=Math.imul(e,16777619),e^=r>>8&255,e=Math.imul(e,16777619)}return e>>>0}function vc(t){return{freq:t.freq??220,wave:t.wave??"sine",duty:t.duty??.5,attack:Math.max(0,t.attack??.005),decay:Math.max(0,t.decay??0),sustain:Math.max(0,t.sustain??.08),release:Math.max(0,t.release??.1),sustainLevel:t.sustainLevel??1,punch:t.punch??0,volume:t.volume??.5,slide:t.slide??0,slideAccel:t.slideAccel??0,pitchJump:t.pitchJump??0,pitchJumpTime:t.pitchJumpTime??0,vibrato:t.vibrato??0,vibratoFreq:t.vibratoFreq??6,repeat:Math.max(0,t.repeat??0),detune:t.detune??0,sub:Math.max(0,t.sub??0),noise:t.noise??0,shapeCurve:Math.max(.01,t.shapeCurve??1),fm:t.fm??0,fmFreq:t.fmFreq??0,tremolo:t.tremolo??0,tremoloFreq:t.tremoloFreq??8,bitCrush:Math.max(0,Math.floor(t.bitCrush??0)),lowpass:t.lowpass??0,highpass:t.highpass??0,delay:Math.max(0,t.delay??0),delayFeedback:Math.min(.95,Math.max(0,t.delayFeedback??0))}}function Gn(t){return fe(t/12)}function ks(t,e,n,r){switch(t){case"sine":return q(Z*e);case"saw":return 2*e-1;case"square":return e<n?1:-1;case"triangle":return(e<.5?e*2:2-e*2)*2-1;case"noise":return r.float()*2-1}}function sn(t,e={}){let n=vc(t),r=e.sampleRate??be,o=e.rng??new ue(24301),i=n.attack+n.decay+n.sustain+n.release,s=n.delay>0?n.delay*6:0,a=i+s+.01,l=Math.max(1,Math.round(a*r)),u=new Float32Array(l),c=1/r,m=0,d=0,h=0,p=n.detune!==0?Gn(n.detune/100):1,f=0,g=0,k=0,v=0,M=n.lowpass>0?Ss(n.lowpass,r):1,I=n.highpass>0?1-Ss(n.highpass,r):0,x=r*.5;for(let b=0;b<l;b++){let w=b*c,C=wc(w,n);n.punch>0&&(C*=1+n.punch*Math.max(0,1-w/Math.max(1e-4,n.attack+n.decay))),n.tremolo>0&&(C*=1-n.tremolo*.5*(1-q(Z*n.tremoloFreq*w)));let E=n.repeat>0?w-Math.floor(w/n.repeat)*n.repeat:w,R=i>0?E/i:0,S=n.freq*Gn(n.slide*R+n.slideAccel*R*R);n.pitchJump!==0&&E>=n.pitchJumpTime&&(S*=Gn(n.pitchJump)),n.vibrato>0&&(S*=Gn(n.vibrato*q(Z*n.vibratoFreq*w))),n.fm>0&&(S+=n.fm*q(Z*n.fmFreq*w)),S<0?S=0:S>x&&(S=x),m+=S*c,m-=Math.floor(m);let T=ks(n.wave,m,n.duty,o);n.detune!==0&&(d+=S*p*c,d-=Math.floor(d),T=(T+ks(n.wave,d,n.duty,o))*.5),n.sub>0&&(h+=S*.5*c,h-=Math.floor(h),T=T*(1-n.sub*.5)+q(Z*h)*n.sub),n.noise>0&&(T=T*(1-n.noise)+(o.float()*2-1)*n.noise),n.shapeCurve!==1&&(T=(T<0?-1:1)*Pe(T<0?-T:T,n.shapeCurve)),T*=C*n.volume,n.bitCrush>0&&(b%n.bitCrush===0&&(f=T),T=f),u[b]=T}if(n.lowpass>0)for(let b=0;b<l;b++)g+=M*(u[b]-g),u[b]=g;if(n.highpass>0)for(let b=0;b<l;b++)k=I*(k+u[b]-v),v=u[b],u[b]=k;if(n.delay>0){let b=Math.max(1,Math.round(n.delay*r));for(let w=b;w<l;w++)u[w]+=u[w-b]*n.delayFeedback}return u}function Ss(t,e){let n=Z*t*(1/e);return n/(n+1)}function wc(t,e){let n=e.attack,r=e.decay,o=e.sustain,i=e.release;if(t<n)return n>0?t/n:1;if(t<n+r)return r>0?1+(e.sustainLevel-1)*((t-n)/r):e.sustainLevel;if(t<n+r+o)return e.sustainLevel;let s=t-n-r-o;return s<i&&i>0?e.sustainLevel*(1-s/i):0}var kc={C:0,"C#":1,Db:1,D:2,"D#":3,Eb:3,E:4,Fb:4,"E#":5,F:5,"F#":6,Gb:6,G:7,"G#":8,Ab:8,A:9,"A#":10,Bb:10,B:11,Cb:11,"B#":0},Sc=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];function ce(t){let e=/^([A-Ga-g])([#b]?)(-?\d+)$/.exec(t.trim());if(!e)throw new Error(`bad note name: ${JSON.stringify(t)}`);let n=e[1].toUpperCase(),r=kc[n+(e[2]||"")];if(r===void 0)throw new Error(`bad note name: ${JSON.stringify(t)}`);let o=parseInt(e[3],10);return r+(o+1)*12}function Cc(t){let e=(t%12+12)%12,n=Math.floor(t/12)-1;return Sc[e]+n}function Cs(t,e=440){return e*fe((t-69)/12)}function po(t,e=440){return Cs(typeof t=="number"?t:ce(t),e)}var fo={major:[0,2,4,5,7,9,11],minor:[0,2,3,5,7,8,10],harmonicMinor:[0,2,3,5,7,8,11],melodicMinor:[0,2,3,5,7,9,11],dorian:[0,2,3,5,7,9,10],phrygian:[0,1,3,5,7,8,10],lydian:[0,2,4,6,7,9,11],mixolydian:[0,2,4,5,7,9,10],locrian:[0,1,3,5,6,8,10],majorPentatonic:[0,2,4,7,9],minorPentatonic:[0,3,5,7,10],blues:[0,3,5,6,7,10],chromatic:[0,1,2,3,4,5,6,7,8,9,10,11]};function Vn(t,e="major",n=1){let r=fo[e],o=[];for(let i=0;i<n;i++)for(let s of r)o.push(t+i*12+s);return o.push(t+n*12),o}function bo(t,e="major"){let n=(t%12+12)%12;return new Set(fo[e].map(r=>(n+r)%12))}function Ts(t,e,n,r=3){let o=(n%7+7)%7,i=Vn(t,e,3),s=[];for(let a=0;a<r;a++)s.push(i[o+a*2]);return s}var Tc={i:0,ii:1,iii:2,iv:3,v:4,vi:5,vii:6};function ct(t,e,n){return n.map(r=>{let o=/^([iv]+|[IV]+)(7)?/i.exec(r.trim());if(!o)throw new Error(`bad roman numeral: ${JSON.stringify(r)}`);let i=Tc[o[1].toLowerCase()];if(i===void 0)throw new Error(`bad roman numeral: ${JSON.stringify(r)}`);return Ts(t,e,i,o[2]?4:3)})}function Mc(t,e){return t.map(n=>n+e)}function Hn(t){return t.length<2?t.slice():[t[0]-12,...t.slice(1)].sort((e,n)=>e-n)}function Pt(t){if(t.length===0)return[];let e=[t[0].slice().sort((n,r)=>n-r)];for(let n=1;n<t.length;n++){let r=e[n-1],o=r.reduce((s,a)=>s+a,0)/r.length,i=t[n].map(s=>{let a=s;for(;a-o>6;)a-=12;for(;o-a>6;)a+=12;return a}).sort((s,a)=>s-a);e.push(i)}return e}var Rc=[1116,1188,1277,1356,1422,1491,1557,1617],Pc=[556,441,341,225],Dc=23,Ec=.015,go=class{constructor(e,n,r){this.feedback=n;this.damp=r;this.buf=new Float32Array(Math.max(1,e))}feedback;damp;buf;idx=0;store=0;process(e){let n=this.buf[this.idx];return this.store=n*(1-this.damp)+this.store*this.damp,this.buf[this.idx]=e+this.store*this.feedback,this.idx=(this.idx+1)%this.buf.length,n}},yo=class{constructor(e,n=.5){this.feedback=n;this.buf=new Float32Array(Math.max(1,e))}feedback;buf;idx=0;process(e){let n=this.buf[this.idx],r=-e+n;return this.buf[this.idx]=e+n*this.feedback,this.idx=(this.idx+1)%this.buf.length,r}};function Ms(t,e,n,r){let o=t/44100,i=Rc.map(a=>new go(Math.round((a+r)*o),e,n)),s=Pc.map(a=>new yo(Math.round((a+r)*o),.5));return{combs:i,aps:s}}function xo(t,e={}){let n=Q(e.wet??.25,0,1),r=Q(e.roomSize??.7,0,1),o=Q(e.damp??.5,0,1)*.4,i=.7+r*.28,s=t.sampleRate,a=Ms(s,i,o,0),l=Ms(s,i,o,Dc),u=t.left.length;for(let c=0;c<u;c++){let m=(t.left[c]+t.right[c])*Ec,d=0;for(let p of a.combs)d+=p.process(m);for(let p of a.aps)d=p.process(d);let h=0;for(let p of l.combs)h+=p.process(m);for(let p of l.aps)h=p.process(h);t.left[c]=t.left[c]*(1-n)+d*n,t.right[c]=t.right[c]*(1-n)+h*n}}function Ic(t){let e=0;for(let n of t)e+=n.beats;return e}function Lc(t){let e=0;for(let n of t.sequence)e+=Ic(t.patterns[n]??[]);return e}function Ps(t){let e=0;for(let n of t.tracks)e=Math.max(e,Lc(n));return e}function qn(t){return Ps(t)*60/t.bpm}function vo(t,e={}){let n=e.sampleRate??be,r=t.a4??440,o=60/t.bpm,i=t.tailSec??2,s=qn(t)+i,a=uo(s,n),l=Math.max(0,Math.min(1,t.swing??0)),u=Math.max(0,Math.min(1,t.humanize??0)),c=Math.max(0,Math.min(1,t.velBrightness??.5));if(t.tracks.forEach((m,d)=>{let h=m.gain??.7,p=m.pan??0,f=new ue(5292449^(d+1)*2654435769),g=0;for(let k of m.sequence){let v=m.patterns[k];if(v)for(let M of v){if(M.pitch!==null&&M.pitch!==void 0){let I=Math.round(g*2),b=Math.abs(g*2-I)<1e-4&&I%2===1?g+l*.2:g,w=u>0?f.range(-1,1)*u*.012:0,C=Math.round((b*o+w)*n),E=M.beats*o,R=u>0?f.range(-1,1)*u*.12:0,S=Math.max(.05,Math.min(1,(M.vel??1)+R)),T=Array.isArray(M.pitch)?M.pitch:[M.pitch],L=m.instrument.attack??.005,H=m.instrument.decay??0,$=Math.max(.01,E-L-H),Y=m.instrument.lowpass,K=Y&&c>0?Y*(1-c*(1-S)):Y;for(let te of T){let ee={...m.instrument,freq:po(te,r),sustain:$,volume:(m.instrument.volume??.5)*S,...K!==void 0?{lowpass:K}:{}},ie=sn(ee,{rng:f,sampleRate:n});co(a,ie,Math.max(0,C),h,p)}}g+=M.beats}}}),t.sidechain){let m=Math.max(0,Math.min(1,t.sidechain.depth??.5)),d=(t.sidechain.beatsPerCycle??1)*o;Fc(a,d,m)}return t.reverb&&xo(a,t.reverb),t.master&&Nc(a,t.master),t.master?.compress&&$c(a,t.master.compress),mo(a),ho(a,e.normalizePeak??.89),a}function $c(t,e){let n=Math.max(0,Math.min(1,e)),r=t.sampleRate,o=Rs(-20),i=2+n*3,s=Je(-1/(r*.005)),a=Je(-1/(r*.15)),l=Rs(n*6),u=0,c=t.left,m=t.right;for(let d=0;d<c.length;d++){let h=Math.max(Math.abs(c[d]),Math.abs(m[d])),p=h>u?s:a;u=p*u+(1-p)*h;let f=1;if(u>o){let k=u/o;f=o*Pe(k,1/i)/u}let g=f*l;c[d]*=g,m[d]*=g}}function Rs(t){return fe(t/6.020599913)}function Nc(t,e){let n=t.sampleRate,r=Math.max(0,e.lowCut??0),o=Math.max(0,e.presence??0),i=Math.max(0,e.air??0),s=c=>{let m=Z*c*(1/n);return m/(m+1)},a=s(240),l=1-s(3200),u=1-s(9e3);for(let c of[t.left,t.right]){let m=0,d=0,h=0,p=0,f=0;for(let g=0;g<c.length;g++){let k=c[g];m+=a*(k-m),d=l*(d+k-h),h=k,p=u*(p+k-f),f=k,c[g]=k-r*m+o*d+i*p}}}function Fc(t,e,n){let r=t.sampleRate,o=Math.max(1,e*r);for(let i=0;i<t.left.length;i++){let a=1-i%o/o,l=1-n*a*a;t.left[i]*=l,t.right[i]*=l}}var W={lead:{wave:"square",duty:.5,attack:.008,release:.08,volume:.4,lowpass:4e3,detune:6},pluck:{wave:"triangle",attack:.002,decay:.06,sustainLevel:.3,release:.12,volume:.42},pad:{wave:"saw",attack:.12,release:.5,volume:.26,lowpass:2200,vibrato:.08,vibratoFreq:4,detune:14},bell:{wave:"sine",attack:.002,decay:.3,sustainLevel:.2,release:.5,volume:.4,fm:3,fmFreq:220},piano:{wave:"triangle",attack:.002,decay:.5,sustainLevel:.12,release:.35,volume:.42,lowpass:3600,detune:4},rhodes:{wave:"sine",attack:.003,decay:.45,sustainLevel:.35,release:.4,volume:.4,fm:2.2,fmFreq:440,detune:5},strings:{wave:"saw",attack:.16,decay:.2,sustainLevel:.85,release:.6,volume:.24,lowpass:2600,detune:16,vibrato:.07,vibratoFreq:5},brass:{wave:"saw",attack:.04,decay:.1,sustainLevel:.8,release:.16,volume:.3,lowpass:3200,detune:8,punch:.3},organ:{wave:"sine",attack:.006,release:.05,sustainLevel:1,volume:.32,sub:.5,detune:3},choir:{wave:"triangle",attack:.28,release:.9,sustainLevel:.9,volume:.22,lowpass:2e3,detune:20,vibrato:.1,vibratoFreq:4.5},glocken:{wave:"sine",attack:.001,decay:.6,sustainLevel:0,release:.4,volume:.34,fm:4,fmFreq:1600},vibraphone:{wave:"sine",attack:.002,decay:.5,sustainLevel:.25,release:.7,volume:.4,fm:2,fmFreq:880,tremolo:.25,tremoloFreq:5},clav:{wave:"square",duty:.35,attack:.001,decay:.08,sustainLevel:.25,release:.08,volume:.32,lowpass:3800,detune:4},uprightBass:{wave:"triangle",attack:.004,decay:.12,sustainLevel:.5,release:.1,volume:.5,lowpass:1100,sub:.35},mutedTrumpet:{wave:"saw",attack:.03,decay:.08,sustainLevel:.75,release:.14,volume:.3,lowpass:2600,detune:4,vibrato:.09,vibratoFreq:6},jazzGuitar:{wave:"triangle",attack:.004,decay:.35,sustainLevel:.2,release:.25,volume:.34,lowpass:2400,detune:5},horns:{wave:"saw",attack:.02,decay:.08,sustainLevel:.7,release:.12,volume:.3,lowpass:3600,detune:10,punch:.4},bass:{wave:"saw",attack:.006,release:.06,volume:.5,lowpass:900,detune:6,sub:.3},subBass:{wave:"sine",attack:.004,release:.08,volume:.6,lowpass:400,sub:.5,punch:.2},kick:{wave:"sine",attack:.001,decay:.06,sustainLevel:0,release:.08,slide:-24,volume:.7,sub:.3},snare:{wave:"noise",attack:.001,decay:.05,sustainLevel:.2,release:.12,highpass:1200,volume:.5},hat:{wave:"noise",attack:.001,release:.04,highpass:6e3,volume:.28},rimshot:{wave:"noise",attack:.001,release:.03,highpass:3e3,lowpass:7e3,volume:.3},ride:{wave:"noise",attack:.001,decay:.1,sustainLevel:.14,release:.32,volume:.2,highpass:1600,lowpass:7e3}};var Ac={master:.7,music:.6,sfx:.8,muted:!1},jn=class{_ctx=null;master=null;musicGain=null;sfxGain=null;vol={...Ac};padOn=!1;get ctx(){return this._ctx}get sfxBus(){return this.sfxGain}get musicBus(){return this.musicGain}get available(){return typeof globalThis.AudioContext<"u"||"webkitAudioContext"in globalThis}get started(){return!!this._ctx}start(){if(this._ctx){this._ctx.resume();return}if(!this.available)return;let e=globalThis.AudioContext||globalThis.webkitAudioContext;this._ctx=new e,this.master=this._ctx.createGain(),this.musicGain=this._ctx.createGain(),this.sfxGain=this._ctx.createGain(),this.musicGain.connect(this.master),this.sfxGain.connect(this.master),this.master.connect(this._ctx.destination),this.applyVolumes()}setVolumes(e){this.vol={...this.vol,...e},this.applyVolumes()}getVolumes(){return{...this.vol}}applyVolumes(){if(!this._ctx||!this.master||!this.musicGain||!this.sfxGain)return;let e=this._ctx.currentTime;this.master.gain.setTargetAtTime(this.vol.muted?0:this.vol.master,e,.04),this.musicGain.gain.setTargetAtTime(this.vol.music*.5,e,.04),this.sfxGain.gain.setTargetAtTime(this.vol.sfx,e,.04)}tone(e){if(!this._ctx||!this.sfxGain)return;let{freq:n,duration:r,type:o="sine",gain:i=.2,delay:s=0,pan:a}=e,l=this._ctx.currentTime+s,u=this._ctx.createOscillator();u.type=o,u.frequency.value=n;let c=this._ctx.createGain();if(c.gain.setValueAtTime(0,l),c.gain.linearRampToValueAtTime(i,l+.008),c.gain.exponentialRampToValueAtTime(1e-4,l+r),u.connect(c),a!==void 0&&typeof this._ctx.createStereoPanner=="function"){let m=this._ctx.createStereoPanner();m.pan.value=Math.max(-1,Math.min(1,a)),c.connect(m),m.connect(this.sfxGain)}else c.connect(this.sfxGain);u.start(l),u.stop(l+r+.05)}spatial(e,n,r,o=600,i=.18,s="sawtooth"){if(r>o)return;let a=1-r/o;this.tone({freq:e,duration:i,type:s,gain:.04+a*a*.3,pan:Math.max(-1,Math.min(1,n/(o*.6)))})}play(e){for(let n of e)this.tone(n)}playSpec(e,n={}){if(!this._ctx||!this.sfxGain)return;let r=sn(e,{sampleRate:this._ctx.sampleRate}),o=this._ctx.createBuffer(1,r.length,this._ctx.sampleRate);o.copyToChannel(new Float32Array(r),0);let i=this._ctx.createBufferSource();i.buffer=o;let s=this._ctx.createGain();if(s.gain.value=n.gain??1,i.connect(s),n.pan!==void 0&&typeof this._ctx.createStereoPanner=="function"){let a=this._ctx.createStereoPanner();a.pan.value=Math.max(-1,Math.min(1,n.pan)),s.connect(a),a.connect(this.sfxGain)}else s.connect(this.sfxGain);i.start(this._ctx.currentTime+(n.when??0))}playSong(e,n={}){if(!this._ctx||!this.musicGain)return()=>{};let r=vo(e,{sampleRate:this._ctx.sampleRate}),o=this._ctx.createBuffer(2,r.left.length,this._ctx.sampleRate);o.copyToChannel(new Float32Array(r.left),0),o.copyToChannel(new Float32Array(r.right),1);let i=this._ctx.createBufferSource();return i.buffer=o,n.loop&&(i.loop=!0,i.loopStart=0,i.loopEnd=qn(e)),i.connect(this.musicGain),i.start(),()=>{try{i.stop()}catch{}}}blip(e=520){this.tone({freq:e,duration:.06,type:"sine",gain:.18})}chime(){[523.25,659.25,783.99].forEach((e,n)=>this.tone({freq:e,duration:.9-n*.15,type:"sine",gain:.15,delay:n*.04}))}success(){[392,493.88,587.33,783.99].forEach((e,n)=>this.tone({freq:e,duration:.4,type:"triangle",gain:.15,delay:n*.08}))}thud(){this.tone({freq:130,duration:.14,type:"sine",gain:.22})}startAmbient(e=110,n=[1,1.5,2,2.5]){if(!this._ctx||!this.musicGain||this.padOn)return;this.padOn=!0;let r=this._ctx.createBiquadFilter();r.type="lowpass",r.frequency.value=900,r.connect(this.musicGain);let o=this._ctx.createGain();o.gain.value=0,o.connect(r);for(let i of n){let s=this._ctx.createOscillator();s.type="triangle",s.frequency.value=e*i;let a=this._ctx.createGain();a.gain.value=.1/n.length,s.connect(a),a.connect(o),s.start()}o.gain.setTargetAtTime(.9,this._ctx.currentTime,3)}},je=new jn;function Un(t){let e=t<0?-t:t;return e<1e-12?-1/0:20*Ft(e)}function Dt(t){if(t.length===0)return 0;let e=0;for(let n=0;n<t.length;n++)e+=t[n]*t[n];return Math.sqrt(e/t.length)}function wo(t){let e=0;for(let n=0;n<t.length;n++){let r=t[n]<0?-t[n]:t[n];r>e&&(e=r)}return e}function Ds(t,e=be){if(t.length<2)return 0;let n=0;for(let r=1;r<t.length;r++)(t[r-1]<0&&t[r]>=0||t[r-1]>=0&&t[r]<0)&&n++;return n*e/t.length}function Wc(t){let e=1;for(;e*2<=t;)e*=2;return e}function Es(t,e){let n=t.length;for(let r=1,o=0;r<n;r++){let i=n>>1;for(;o&i;i>>=1)o^=i;if(o^=i,r<o){let s=t[r];t[r]=t[o],t[o]=s;let a=e[r];e[r]=e[o],e[o]=a}}for(let r=2;r<=n;r<<=1){let o=-Z/r,i=j(o),s=q(o);for(let a=0;a<n;a+=r){let l=1,u=0;for(let c=0;c<r/2;c++){let m=a+c,d=m+r/2,h=l*t[d]-u*e[d],p=l*e[d]+u*t[d];t[d]=t[m]-h,e[d]=e[m]-p,t[m]+=h,e[m]+=p;let f=l*i-u*s;u=l*s+u*i,l=f}}}}function Et(t){let e=Wc(t.length);if(e<2)return new Float32Array(0);let n=new Float32Array(e),r=new Float32Array(e);for(let s=0;s<e;s++){let a=.5-.5*j(Z*s/(e-1));n[s]=t[s]*a}Es(n,r);let o=e>>1,i=new Float32Array(o);for(let s=0;s<o;s++)i[s]=Math.sqrt(n[s]*n[s]+r[s]*r[s]);return i}function Is(t,e=be){if(t.length<64)return 0;let r=2048,o=0,i=0;for(let s=0;s+64<=t.length;s+=r){let a=t.subarray(s,Math.min(s+2048,t.length)),l=Et(a),u=e/(l.length*2);for(let c=0;c<l.length;c++)o+=c*u*l[c],i+=l[c]}return i<1e-9?0:o/i}function ko(t,e=1024,n=512){let r=[],o=null;for(let i=0;i+e<=t.length;i+=n){let s=Et(t.subarray(i,i+e)),a=0;if(o){let l=Math.min(s.length,o.length);for(let u=0;u<l;u++){let c=s[u]-o[u];c>0&&(a+=c)}}r.push(a),o=s}return Float32Array.from(r)}function Ls(t,e=be){let r=ko(t,1024,512);if(r.length<3)return 0;let o=0;for(let l=0;l<r.length;l++)o+=r[l];o/=r.length;let i=o*1.5,s=0;for(let l=1;l<r.length-1;l++)r[l]>i&&r[l]>=r[l-1]&&r[l]>r[l+1]&&s++;let a=t.length/e;return a<1e-6?0:s/a}function $s(t,e=be){let r=ko(t,1024,512);if(r.length<8)return 0;let o=e/512,i=Math.max(1,Math.ceil(o*60/200)),s=Math.min(r.length-1,Math.floor(o*60/60)),a=0,l=-1;for(let c=i;c<=s;c++){let m=0;for(let d=c;d<r.length;d++)m+=r[d]*r[d-c];m/=r.length-c,m>l&&(l=m,a=c)}if(a===0)return 0;let u=60*o/a;for(;u>150;)u/=2;for(;u>0&&u<70;)u*=2;return u}function So(t){let e=Dt(t);return e<1e-9?0:Un(wo(t))-Un(e)}function Co(t,e=be){let r=[20,60,250,800,2500,8e3,e/2],o=new Float64Array(6);if(t.length>=64)for(let s=0;s+64<=t.length;s+=2048){let a=Et(t.subarray(s,Math.min(s+2048,t.length))),l=e/(a.length*2);for(let u=0;u<a.length;u++){let c=u*l,m=a[u]*a[u];for(let d=0;d<6;d++)if(c>=r[d]&&c<r[d+1]){o[d]+=m;break}}}let i=o.reduce((s,a)=>s+a,0)||1;return{sub:o[0]/i,bass:o[1]/i,lowMid:o[2]/i,mid:o[3]/i,high:o[4]/i,air:o[5]/i}}function It(t,e=be){return{durationSec:t.length/e,rms:Dt(t),peakDb:Un(wo(t)),centroidHz:Is(t,e),zcr:Ds(t,e),onsetDensity:Ls(t,e),tempoBpm:$s(t,e)}}var Bc={"":[0,4,7],maj:[0,4,7],M:[0,4,7],m:[0,3,7],min:[0,3,7],"-":[0,3,7],dim:[0,3,6],aug:[0,4,8],"+":[0,4,8],6:[0,4,7,9],m6:[0,3,7,9],"-6":[0,3,7,9],69:[0,4,7,9,14],"6/9":[0,4,7,9,14],maj7:[0,4,7,11],M7:[0,4,7,11],maj9:[0,4,7,11,14],"maj7#11":[0,4,7,11,18],maj13:[0,4,7,11,14,21],7:[0,4,7,10],9:[0,4,7,10,14],11:[0,7,10,14,17],13:[0,4,7,10,14,21],"7b9":[0,4,7,10,13],"7#9":[0,4,7,10,15],"7#11":[0,4,7,10,18],"7b13":[0,4,7,10,20],"7b5":[0,4,6,10],"7#5":[0,4,8,10],"13b9":[0,4,7,10,13,21],"13#11":[0,4,7,10,18,21],"9#11":[0,4,7,10,14,18],"7alt":[0,4,10,13,20],m7:[0,3,7,10],min7:[0,3,7,10],"-7":[0,3,7,10],m9:[0,3,7,10,14],m11:[0,3,7,10,14,17],m13:[0,3,7,10,14,21],m7b5:[0,3,6,10],\u00F8:[0,3,6,10],\u00F87:[0,3,6,10],dim7:[0,3,6,9],mMaj7:[0,3,7,11],"m(maj7)":[0,3,7,11],mMaj9:[0,3,7,11,14],sus4:[0,5,7],sus2:[0,2,7],"7sus4":[0,5,7,10],"9sus4":[0,5,7,10,14],add9:[0,4,7,14],madd9:[0,3,7,14]};function Ce(t,e=4){let r=t.trim().split("/"),o=r[0],i=/^([A-Ga-g][#b]?)(.*)$/.exec(o);if(!i)throw new Error(`bad chord symbol: ${JSON.stringify(t)}`);let s=i[1][0].toUpperCase()+(i[1][1]??""),a=i[2],l=Bc[a];if(!l)throw new Error(`unknown chord quality ${JSON.stringify(a)} in ${JSON.stringify(t)}`);let u=ce(s+e),c=l.map(m=>u+m);if(r.length===2){let m=/^([A-Ga-g][#b]?)$/.exec(r[1].trim());if(m){let d=m[1][0].toUpperCase()+(m[1][1]??""),h=ce(d+(e-1));for(;h>=c[0];)h-=12;c.unshift(h)}}return c}function an(t,e){let n=t.slice(1);if(e===void 0||n.length===0)return n;let r=n.reduce((i,s)=>i+s,0)/n.length,o=Math.round((e-r)/12)*12;return n.map(i=>i+o).sort((i,s)=>i-s)}function zc(t,e=4){return t.map(n=>Ce(n,e))}function Ns(t){try{return typeof t=="number"?t:ce(t)}catch{return null}}function _c(t){return t.pitch===null||t.pitch===void 0?[]:Array.isArray(t.pitch)?t.pitch:[t.pitch]}function Oc(t,e={}){let n=[],r=[];(!(t.bpm>0)||t.bpm<20||t.bpm>400)&&n.push(`bpm ${t.bpm} out of sane range [20,400]`),(!t.tracks||t.tracks.length===0)&&n.push("song has no tracks");let o=e.key?bo(Ns(e.key.tonic)??0,e.key.mode):null,i=0,s=0,a=new Map;if(t.tracks.forEach((u,c)=>{let m=u.name??`track ${c}`;(!u.patterns||u.patterns.length===0)&&n.push(`${m}: no patterns`),(!u.sequence||u.sequence.length===0)&&n.push(`${m}: empty sequence`),u.pan!==void 0&&(u.pan<-1||u.pan>1)&&n.push(`${m}: pan ${u.pan} out of [-1,1]`);for(let d of u.sequence??[]){if(d<0||d>=(u.patterns?.length??0)){n.push(`${m}: sequence references missing pattern ${d}`);continue}let h=`${c}:${d}`;a.set(h,(a.get(h)??0)+1);for(let p of u.patterns[d]){p.beats>0||n.push(`${m}: note with non-positive beats ${p.beats}`),p.vel!==void 0&&(p.vel<0||p.vel>1)&&n.push(`${m}: velocity ${p.vel} out of [0,1]`);for(let f of _c(p)){let g=Ns(f);if(g===null){n.push(`${m}: unparseable pitch ${JSON.stringify(f)}`);continue}(g<0||g>127)&&n.push(`${m}: pitch ${f} outside MIDI 0..127`),i++,o&&!o.has((g%12+12)%12)&&s++}}}}),o&&i>0){let u=s/i,c=e.maxOutOfKey??1,m=`${s}/${i} notes (${Math.round(u*100)}%) out of key`;u>c?n.push(m):s>0&&r.push(m)}return![...a.values()].some(u=>u>1)&&t.tracks.length>0&&r.push("no pattern is reused \u2014 piece may lack structure/repetition"),{ok:n.length===0,errors:n,warnings:r}}function Gc(t){return t.length===0?!1:(r=>r.trim().toLowerCase().replace(/7$/,""))(t[t.length-1])==="i"}var Vc={tempoBpm:20,centroidHz:1200,rms:.1,zcr:1500,onsetDensity:4,peakDb:6},Hc={tempoBpm:["too slow","too fast"],centroidHz:["too dark / muffled","too bright / harsh"],rms:["too quiet","too loud"],zcr:["too smooth / tonal","too noisy / gritty"],onsetDensity:["too sparse","too busy"],peakDb:["more headroom than reference","hotter / less headroom than reference"]};function Fs(t,e,n={}){let r={...Vc,...n},o=Object.keys(r),i=[],s=0;for(let c of o){let m=t[c],d=e[c],h=Number.isFinite(m)?m:0,p=Number.isFinite(d)?d:0,f=(p-h)/r[c];s+=f*f;let[g,k]=Hc[c],v=Math.abs(f)<.25?"ok":f<0?g:k;i.push({feature:c,reference:h,candidate:p,normalized:f,note:v})}i.sort((c,m)=>Math.abs(m.normalized)-Math.abs(c.normalized));let a=Math.sqrt(s/o.length),l=i[0],u=Math.abs(l.normalized)<.25?"close match":`${l.feature}: ${l.note}`;return{distance:a,deltas:i,headline:u}}function qc(t,e){let n=Fs(t,e),r=n.deltas.filter(o=>o.note!=="ok").map(o=>` ${o.feature.padEnd(13)} ${o.candidate.toFixed(1)} vs ${o.reference.toFixed(1)} \u2192 ${o.note}`);return`match distance ${n.distance.toFixed(3)} \u2014 ${n.headline}
|
|
4
176
|
`+(r.length?r.join(`
|
|
5
|
-
`):" (all features within tolerance)")}function ou(t,e){if(t.length===0)return 0;let n=t.length>1?[...t].sort((r,o)=>r.x-o.x):t;if(e<=n[0].x)return n[0].y;if(e>=n[n.length-1].x)return n[n.length-1].y;for(let r=1;r<n.length;r++)if(e<=n[r].x){let o=n[r-1],i=n[r],s=i.x===o.x?0:(e-o.x)/(i.x-o.x);return o.y+(i.y-o.y)*s}return n[n.length-1].y}function yi(t,e,n=1,r=1e4,o=1){let i=Math.max(1e-6,n);switch(t){case"linear":{let s=U(e,i,r);return 1-o*(s-i)/Math.max(1e-6,r-i)}case"inverse":{let s=Math.max(e,i);return i/(i+o*(Math.max(s,i)-i))}case"exponential":{let s=Math.max(e,i);return he(-o*Xt(s/i))}}}function xi(t,e=400){return U(t/e,-1,1)}function iu(t,e,n=600,r=1){let o=Math.sqrt(t*t+e*e);return o>n?{gain:0,pan:0,audible:!1}:{gain:yi("inverse",o,n*.15,n,r),pan:xi(t,n*.7),audible:!0}}function su(t,e){let n={};for(let r of t){let o=Math.max(1e-6,r.full-r.fadeIn),i=U((e-r.fadeIn)/o,0,1)*(r.maxGain??1);n[r.name]=i}return n}function au(t,e=-12){return t?he(e/6.0206):1}function vi(t){let e=t.left.length,n=new Float32Array(e),r=new Float32Array(e);for(let i=0;i<e;i++)n[i]=(t.left[i]+t.right[i])*.5,r[i]=(t.left[i]-t.right[i])*.5;let o=lt(n);return o<1e-9?0:lt(r)/o}var lu={electronic:{tempo:[118,132],centroid:[3e3,7200],onsets:[7,15],rms:[.16,.27],crestDb:[6,15],width:[.03,.6],maxMud:.34},lofi:{tempo:[70,88],centroid:[1600,4300],onsets:[5,13],rms:[.12,.24],crestDb:[7,17],width:[.04,.6],maxMud:.5},piano:{tempo:[58,100],centroid:[700,2100],onsets:[3,11],rms:[.1,.22],crestDb:[9,22],width:[.04,.7],maxMud:.42},orchestral:{tempo:[80,96],centroid:[1100,3e3],onsets:[4,12],rms:[.11,.22],crestDb:[8,21],width:[.05,.7],maxMud:.4},jazzfunk:{tempo:[106,126],centroid:[2200,5600],onsets:[6,16],rms:[.13,.25],crestDb:[7,18],width:[.04,.6],maxMud:.4}};function Pe(t,[e,n]){if(t>=e&&t<=n)return 1;let r=Math.max(1e-6,n-e),o=t<e?e-t:t-n;return Math.max(0,1-o/(r*.6))}function uu(t,e){let n=new Float32Array(t.left.length);for(let k=0;k<n.length;k++)n[k]=(t.left[k]+t.right[k])*.5;let r=ct(n),o=kr(n),i=Sr(n),s=vi(t),a=i.lowMid,l=i.high+i.air,u=i.sub+i.bass,c={loudness:Pe(r.rms,e.rms),headroom:r.peakDb<=-.5?r.peakDb>=-3?1:Pe(r.peakDb,[-3,-.5]):0,dynamics:Pe(o,e.crestDb),width:Pe(s,e.width),brightness:Pe(r.centroidHz,e.centroid),density:Pe(r.onsetDensity,e.onsets),tempo:Pe(r.tempoBpm,e.tempo),lowEnd:Pe(u,[.12,.7]),clarity:Pe(a,[0,e.maxMud??.34]),smoothness:Pe(l,[0,.4])},m={loudness:1.2,headroom:1.4,dynamics:1,width:.7,brightness:1.1,density:.9,tempo:.7,lowEnd:1,clarity:1.2,smoothness:1.1},d=0,p=0;for(let k of Object.keys(c))d+=c[k]*m[k],p+=m[k];let h=Math.round(d/p*100),g=[],x=(k,w)=>{c[k]<.75&&g.push(`${k}: ${w}`)};return x("loudness",`rms ${r.rms.toFixed(3)} (target ${e.rms.join("\u2013")})`),x("headroom",`peak ${r.peakDb.toFixed(1)}dB (want \u2264 \u22120.5, \u2265 \u22123)`),x("dynamics",`crest ${o.toFixed(1)}dB (target ${e.crestDb.join("\u2013")})`),x("width",`width ${s.toFixed(2)} (target ${e.width.join("\u2013")})`),x("brightness",`centroid ${Math.round(r.centroidHz)}Hz (target ${e.centroid.join("\u2013")})`),x("density",`onsets ${r.onsetDensity.toFixed(1)}/s (target ${e.onsets.join("\u2013")})`),x("tempo",`tempo ${Math.round(r.tempoBpm)} (target ${e.tempo.join("\u2013")})`),x("lowEnd",`low-end fraction ${u.toFixed(2)} (want 0.12\u20130.62)`),x("clarity",`low-mid mud ${a.toFixed(2)} (want \u2264 ${(e.maxMud??.34).toFixed(2)})`),x("smoothness",`high/air ${l.toFixed(2)} (want \u2264 0.40)`),{score:h,dims:c,notes:g}}var R=(t,e,n=1)=>({pitch:t,beats:e,vel:n}),G=t=>({pitch:null,beats:t});function wi(t,e,n,r=.9){let o=[];for(let i=0;i<e;i++)o.push(R(t[i%t.length]+Math.floor(i/t.length)*12,n,r));return o}function cu(t,e,n=1){return Array.from({length:e},()=>R(t,1,n))}function mu(){let t=Ue(ce("A3"),"minor",["i","VI","III","VII"]),e=t.map(a=>a[0]-12),n={name:"sub",instrument:A.subBass,gain:.6,patterns:e.map(a=>[R(a,.5,1),R(a,.5,.6),R(a,.5,.85),R(a,.5,.6),R(a,.5,1),R(a,.5,.6),R(a,.5,.85),R(a,.5,.7)]),sequence:[0,1,2,3,0,1,2,3]},r={name:"kick",instrument:A.kick,gain:.82,patterns:[cu("A1",4)],sequence:Array(8).fill(0)},o={name:"hat",instrument:A.hat,gain:.42,pan:.15,patterns:[[G(.5),R("A6",.5,.7),G(.5),R("A6",.5,.5)]],sequence:Array(16).fill(0)},i={name:"pluck",instrument:{...A.pluck,release:.16,lowpass:2400},gain:.62,pan:-.2,patterns:t.map(a=>wi([a[0],a[1],a[2]],4,1,.7)),sequence:[0,1,2,3,0,1,2,3]},s={name:"lead",instrument:{...A.lead,detune:8,lowpass:2800},gain:.52,pan:.1,patterns:[[R(t[0][2]+12,.75),R(t[0][2]+14,.25),R(t[0][0]+12,1),R(t[0][1]+12,2)],[R(t[1][2]+12,1),R(t[1][1]+12,.5),R(t[1][2]+12,.5),R(t[1][0]+24,2)],[R(t[2][2]+12,.75),R(t[2][1]+12,.25),R(t[2][0]+12,1),R(t[2][2]+12,2)],[R(t[3][0]+24,1),R(t[3][2]+12,.5),R(t[3][1]+12,.5),R(t[3][0]+12,2)]],sequence:[0,1,2,3]};return{bpm:126,tracks:[r,n,o,i,s],reverb:{wet:.15,roomSize:.6,damp:.5},humanize:.05,sidechain:{depth:.55,beatsPerCycle:1},master:{lowCut:.35,presence:.2,air:.08}}}function du(){let t=ce("C4"),e=at(Ue(t,"major",["IV7","iii7","ii7","I7"]).map(an)),n=e.map(c=>c[0]-12),r={name:"rhodes",instrument:{...A.rhodes,volume:.42,lowpass:2600,fm:1.6},gain:.66,pan:-.1,patterns:e.map(c=>[R(c.map(m=>m),3.5,.75),G(.5)]),sequence:[0,1,2,3,0,1,2,3]},o={name:"bass",instrument:{...A.bass,lowpass:650,sub:.28},gain:.72,pan:.05,patterns:n.map(c=>[R(c,1.5,.9),G(.5),R(c+7,1,.7),R(c+5,1,.6)]),sequence:[0,1,2,3,0,1,2,3]},i={name:"kick",instrument:{...A.kick,volume:.75},gain:.82,patterns:[[R("C2",1,.9),G(1),R("C2",.5,.6),G(.5),R("C2",.5,.4),G(.5)]],sequence:Array(8).fill(0)},s={name:"snare",instrument:{...A.rimshot,volume:.24,lowpass:4e3},gain:.6,patterns:[[G(1),R("C4",1,.7),G(1),R("C4",1,.7)]],sequence:Array(8).fill(0)},a={name:"hat",instrument:{...A.hat,volume:.14,highpass:2500,lowpass:6e3},gain:.45,pan:.2,patterns:[[R("C6",.5,.5),R("C6",.5,.3)]],sequence:Array(16).fill(0)},l={name:"vinyl",instrument:{wave:"noise",attack:.5,release:.5,sustainLevel:1,volume:.022,lowpass:2800,highpass:400},gain:.3,patterns:[[R("C4",16,1)]],sequence:[0]},u={name:"keys",instrument:{...A.piano,volume:.3,lowpass:2800},gain:.48,pan:.15,patterns:[[R(e[0][2]+12,1,.7),G(1),R(e[0][1]+12,.5,.55),R(e[0][2]+12,.5,.5),G(1)],[G(.5),R(e[1][2]+12,1,.7),G(.5),R(e[1][1]+12,2,.55)],[R(e[2][2]+12,1.5,.7),R(e[2][1]+12,.5,.5),G(2)],[G(1),R(e[3][2]+12,1,.7),R(e[3][1]+12,1,.55),G(1)]],sequence:[0,1,2,3,0,1,2,3]};return{bpm:78,tracks:[l,r,o,i,s,a,u],swing:.75,humanize:.4,velBrightness:.7,reverb:{wet:.24,roomSize:.7,damp:.65},master:{lowCut:.26,presence:.22,air:.05}}}function pu(){let t=ce("A3"),e=at(Ue(t,"minor",["i","VI","III","VII"])),n=[a=>[R(a[0],1,.85),R(a[2],1,.55),G(2)],a=>[R(a[2],1.5,.8),G(.5),R(a[1],2,.5)],a=>[G(1),R(a[1]+12,1.5,.7),G(1.5)],a=>[R(a[0],2,.8),R(a[2],1,.55),G(1)]],r={name:"piano",instrument:{...A.piano,volume:.46},gain:.78,pan:-.05,patterns:e.map((a,l)=>n[l%n.length](a)),sequence:[0,1,2,3,0,1,2,3]},o={name:"strings",instrument:{...A.strings,attack:.4},gain:.5,pan:.1,patterns:e.map(a=>[R(a.map(l=>l-12),4,.65)]),sequence:[0,1,2,3,0,1,2,3]},i={name:"sub",instrument:{...A.subBass,volume:.4,attack:.03},gain:.55,patterns:e.map(a=>[R(a[0]-24,4,.6)]),sequence:[0,1,2,3,0,1,2,3]},s={name:"melody",instrument:{...A.piano,volume:.4,lowpass:3e3},gain:.5,pan:.12,patterns:[[G(2),R(e[0][2]+12,1,.75),R(e[0][1]+12,1,.55)],[R(e[1][2]+12,2,.8),R(e[1][1]+12,1,.55),G(1)],[G(1.5),R(e[2][2]+12,1.5,.75),R(e[2][1]+12,1,.55)],[R(e[3][1]+12,1.5,.7),R(e[3][0]+12,2.5,.6)]],sequence:[0,1,2,3,0,1,2,3]};return{bpm:66,tracks:[i,o,r,s],humanize:.5,velBrightness:.75,reverb:{wet:.38,roomSize:.86,damp:.55},master:{lowCut:.4,presence:.28,air:.12}}}function hu(){let t=ce("D3"),e=at(Ue(t,"minor",["i","VI","III","VII","VI","VII","i","i"])),n=sn(ce("D4"),"minor",3),r=m=>n[(m%n.length+n.length)%n.length],o={name:"strings",instrument:{...A.strings,volume:.24},gain:.7,pan:-.15,patterns:e.map(m=>wi([m[0],m[1],m[2],m[0]+12],8,.5,.75)),sequence:[0,1,2,3,4,5,6,7]},i=[[R(r(0),2,.9),R(r(1),1,.8),R(r(2),1,.85)],[R(r(4),3,.95),R(r(2),1,.8)],[R(r(1),2,.85),R(r(0),1,.8),R(r(1),1,.8)],[R(r(4),2,.9),R(r(5),2,.95)],[R(r(5),2,.95),R(r(4),1,.85),R(r(2),1,.8)],[R(r(4),2,.9),R(r(6),2,.95)],[R(r(7),3,1),R(r(6),1,.85)],[R(r(7),4,1)]],s=[G(4)],a={name:"brass",instrument:{...A.brass,volume:.32},gain:.62,pan:.15,patterns:[s,...i],sequence:[0,0,1,2,3,4,5,6]},l={name:"choir",instrument:{...A.choir,volume:.18},gain:.5,pan:.05,patterns:e.map(m=>[R([m[2]+12,m[0]+24],4,.6)]),sequence:[0,1,2,3,4,5,6,7]},u={name:"timpani",instrument:{...A.kick,decay:.14,release:.25,slide:-12,volume:.85,sub:.5},gain:.82,patterns:[[R("D2",1,1),R("D2",1,.6),R("D2",.5,.85),R("D2",.5,.6),R("D2",1,.9)]],sequence:Array(8).fill(0)},c={name:"glocken",instrument:A.glocken,gain:.32,pan:.25,patterns:[s,...e.map(m=>[G(1),R(m[2]+24,1,.55),G(1),R(m[1]+24,1,.5)])],sequence:[0,0,3,4,5,6,7,8]};return{bpm:88,tracks:[u,o,a,l,c],humanize:.14,velBrightness:.5,reverb:{wet:.32,roomSize:.9,damp:.4},master:{lowCut:.4,presence:.32,air:.14}}}function fu(){let t=ce("C4"),e=Ue(t,"major",["ii7","V7","I7","vi7"]),n=at(e.map(an)),r=e.map((c,m)=>{let d=e[(m+1)%e.length][0]-24,p=c[0]-24,h=c[1]-24,g=c[2]-24,x=d+(p<d?-1:1);return[R(p,1,.95),R(h,1,.75),R(g,1,.8),R(x,1,.7)]}),o={name:"bass",instrument:{...A.bass,lowpass:1e3,sub:.35,release:.12},gain:.74,patterns:r,sequence:[0,1,2,3,0,1,2,3]},i={name:"rhodes",instrument:{...A.rhodes,volume:.3},gain:.62,pan:-.15,patterns:n.map(c=>[G(.5),R(c.map(m=>m),.75,.7),G(.75),R(c.map(m=>m),.5,.55),G(1.5)]),sequence:[0,1,2,3,0,1,2,3]},s={name:"brass",instrument:{...A.brass,release:.1,volume:.24},gain:.55,pan:.2,patterns:[[G(2),R(n[0].map(c=>c+12),.5,.85),G(1.5)],[G(3),R(n[1].map(c=>c+12),.5,.85),G(.5)],[R(n[2].map(c=>c+12),.5,.8),G(3.5)],[G(2.5),R(n[3].map(c=>c+12),.5,.8),G(1)]],sequence:[0,1,2,3,0,1,2,3]},a={name:"ride",instrument:{...A.hat,volume:.13,highpass:3e3,lowpass:9e3,release:.08},gain:.5,pan:.1,patterns:[[R("C6",.5,.6),R("C6",.5,.35),R("C6",.5,.5),R("C6",.5,.35)]],sequence:Array(16).fill(0)},l={name:"snare",instrument:{...A.snare,volume:.28,highpass:900},gain:.5,patterns:[[G(1),R("D4",1,.6),G(1),R("D4",1,.7)]],sequence:Array(8).fill(0)},u={name:"kick",instrument:{...A.kick,volume:.55},gain:.62,patterns:[[R("C2",1,.85),G(1.5),R("C2",.5,.6),G(1)]],sequence:Array(8).fill(0)};return{bpm:116,tracks:[o,i,s,u,l,a],swing:.66,humanize:.35,velBrightness:.6,reverb:{wet:.16,roomSize:.55,damp:.5},master:{lowCut:.5,presence:.18,air:.07}}}var ki=[{id:"electronic",name:"Minimal Electronic",description:"Bass-driven four-on-the-floor in A minor \u2014 pulsing sidechained sub, offbeat hats, a synth hook.",make:mu},{id:"lofi",name:"Lo-fi Beats",description:"Swung, dusty jazz sevenths on a Rhodes with warm bass, brushed drums and vinyl crackle.",make:du},{id:"piano",name:"Melancholic Piano",description:"Slow, sad A-minor piano with space and rubato over a string bed in a big room.",make:pu},{id:"orchestral",name:"Epic Orchestral",description:"Uplifting D-minor with a soaring brass theme, arpeggiated strings, choir, timpani and glockenspiel.",make:hu},{id:"jazzfunk",name:"Jazz Funk",description:"Swung ii\u2013V\u2013I with a walking bass that chromatically approaches each chord, Rhodes comping and brass stabs.",make:fu}];function bu(t){return ki.find(e=>e.id===t)}var b=(t,e,n=1)=>({pitch:t,beats:e,vel:n}),N=t=>({pitch:null,beats:t});function Mr(t,e=2){return t.map((n,r)=>{let o=Se(n,e),i=o[0],s=o[1]??i+3,a=o[2]??i+7,l=Se(t[(r+1)%t.length],e)[0],u=l+(i<=l?-1:1);return[b(i,1,.92),b(s,1,.72),b(a,1,.78),b(u,1,.7)]})}function dn(t,e=4,n="F4",r=.66){let o=ce(n);return t.map((i,s)=>{let a=$t(Se(i,e),o);return s%2===0?[b(a,1,r),N(.5),b(a,.5,r*.8),N(2)]:[N(1.5),b(a,.5,r*.85),N(1),b(a,.5,r*.7),N(.5)]})}function gu(t,e=4,n="F4",r=.6){let o=ce(n);return t.map(i=>[b($t(Se(i,e),o),4,r)])}var yu=()=>[b("C6",1,.55),b("C6",.5,.35),b("C6",.5,.5),b("C6",1,.55),b("C6",.5,.35),b("C6",.5,.5)],xu=()=>[N(1),b("C6",1,.5),N(1),b("C6",1,.5)];function At(t=.42,e=8){return{name:"ride",instrument:A.ride,gain:t,pan:.12,patterns:[yu()],sequence:Array(e).fill(0)}}function Cr(t=.4,e=8){return{name:"hat",instrument:{...A.hat,highpass:5e3,volume:.2},gain:t,pan:-.1,patterns:[xu()],sequence:Array(e).fill(0)}}function pn(t=.32,e=8){return{name:"vinyl",instrument:{wave:"noise",attack:.6,release:.6,sustainLevel:1,volume:.03,lowpass:3e3,highpass:380},gain:t,patterns:[[b("C4",e*4,1)]],sequence:[0]}}var mn=["F5","Gb5","Bb5","Ab5"];function vu(){let t=["Bbm9","Bbm9","Ebm9","Ab13","Dbmaj7","Gm7b5","C7alt","Fm7"],n={name:"bass",instrument:{...A.uprightBass,volume:.5},gain:.7,patterns:[[b("Bb1",.75,.95),b("Bb1",.25,.5),N(.5),b("Db2",.5,.7),b("F2",.5,.75),b("Ab1",.5,.6),b("Bb1",1,.7)],...Mr(t.slice(2),2)],sequence:[0,0,1,2,3,4,5,6]},r={name:"rhodes",instrument:{...A.rhodes,volume:.32},gain:.6,pan:-.18,patterns:dn(t,4,"Ab4",.62),sequence:[0,1,2,3,4,5,6,7]},o={name:"trumpet",instrument:{...A.mutedTrumpet,volume:.34},gain:.62,pan:.14,patterns:[[b(mn[0],.5,.85),b(mn[1],.5,.7),b(mn[2],1,.9),b(mn[3],.5,.75),N(1.5)],[b("F5",.5,.8),b("Db5",.5,.7),b("Bb4",1.5,.85),N(1.5)],[b("C5",.5,.85),b("Db5",.5,.72),b("F5",1,.9),b("Eb5",.5,.75),N(1.5)],[b("Db5",1,.8),b("C5",.5,.7),b("Bb4",.5,.7),b("Ab4",2,.72)],[b("Db5",.5,.8),b("F5",.5,.8),b("Ab5",1.5,.85),b("Gb5",1.5,.75)],[b("D5",1,.8),b("F5",1,.8),b("Ab5",1,.85),N(1)],[b("E5",.5,.85),b("Eb5",.5,.8),b("Db5",1,.8),b("C5",2,.78)],[b("F5",1,.85),b("Ab5",1,.8),b("C6",2,.9)]],sequence:[0,1,2,3,4,5,6,7]},i={name:"kick",instrument:{...A.kick,volume:.5},gain:.6,patterns:[[b("Bb1",1,.8),N(1.5),b("Bb1",.5,.55),N(1)]],sequence:Array(8).fill(0)},s={name:"snare",instrument:{...A.snare,volume:.3,highpass:1e3},gain:.5,patterns:[[N(1),b("D4",1,.7),N(1),b("D4",1,.75)]],sequence:Array(8).fill(0)};return{bpm:100,tracks:[n,r,o,i,s,At(.42),Cr(.35)],swing:.6,humanize:.32,velBrightness:.6,reverb:{wet:.17,roomSize:.6,damp:.5},master:{lowCut:.24,presence:.14,air:.04,compress:.45}}}function wu(){let t=["Ebmaj7","Cm7","Fm7","Bb13","Gm7","C7b9","Fm7","Bb7alt"],e={name:"bass",instrument:{...A.uprightBass,volume:.54,release:.2},gain:.74,patterns:t.map(i=>{let s=Se(i,2)[0];return[b(s,2,.85),b(s+7,1,.6),b(s+12,1,.55)]}),sequence:[0,1,2,3,4,5,6,7]},n={name:"rhodes",instrument:{...A.rhodes,volume:.34,release:.6},gain:.62,pan:-.15,patterns:gu(t,4,"G4",.62),sequence:[0,1,2,3,4,5,6,7]},r={name:"trumpet",instrument:{...A.mutedTrumpet,volume:.36,attack:.05,vibrato:.11},gain:.62,pan:.12,patterns:[[N(1),b("G4",1.5,.7),b("Bb4",1,.75),b("G4",.5,.6)],[b("Eb4",2,.7),b("G4",1,.65),N(1)],[N(.5),b("Ab4",1.5,.72),b("C5",1,.75),b("Ab4",1,.62)],[b("D5",2.5,.78),b("Bb4",1.5,.65)],[b("Bb4",1.5,.7),b("G4",1,.65),b("D5",1.5,.72)],[b("Db5",2,.75),b("C5",1,.68),b("Bb4",1,.62)],[b("Ab4",2,.72),b("F4",1,.62),N(1)],[b("Ab4",1,.72),b("Db5",1,.7),b("D5",2,.72)]],sequence:[0,1,2,3,4,5,6,7]},o={name:"brush",instrument:{...A.snare,volume:.12,highpass:1500,release:.16},gain:.4,patterns:[[N(1),b("D4",1,.4),N(1),b("D4",1,.45)]],sequence:Array(8).fill(0)};return{bpm:62,tracks:[pn(.3),e,n,r,o,At(.24)],swing:.5,humanize:.4,velBrightness:.6,reverb:{wet:.34,roomSize:.85,damp:.55},master:{lowCut:.24,presence:.16,air:.05,compress:.65}}}function ku(){let t=["Cm9","Cm9","Fm9","Dm7b5","G7alt","Cm9","Ab13","G7alt"],e={name:"bass",instrument:{...A.uprightBass,volume:.48},gain:.68,patterns:Mr(t,2),sequence:[0,1,2,3,4,5,6,7]},n={name:"vibes",instrument:{...A.vibraphone,volume:.34},gain:.6,pan:.1,patterns:[[b("G4",1,.7),N(1),b("Eb5",1,.65),N(1)],[N(2),b("D5",1,.68),b("C5",1,.6)],[b("Ab4",1,.7),N(1.5),b("F5",1.5,.6)],[b("F4",1,.7),b("Ab4",1,.6),N(2)],[N(1),b("B4",1,.72),b("Ab4",1,.6),b("F4",1,.55)],[b("Eb5",2,.68),b("C5",2,.6)],[b("C5",1,.7),b("Gb5",1,.68),N(2)],[b("B4",1,.7),b("Db5",1,.62),b("Ab4",2,.58)]],sequence:[0,1,2,3,4,5,6,7]},r={name:"guitar",instrument:{...A.jazzGuitar,volume:.22},gain:.5,pan:-.2,patterns:dn(t,4,"Eb4",.5),sequence:[0,1,2,3,4,5,6,7]};return{bpm:96,tracks:[pn(.28),e,r,n,At(.3),Cr(.28)],swing:.62,humanize:.34,velBrightness:.6,reverb:{wet:.22,roomSize:.65,damp:.5},master:{lowCut:.24,presence:.13,air:.04,compress:.45}}}function Su(){let t={name:"bass",instrument:{...A.bass,volume:.52,lowpass:1e3,sub:.35},gain:.75,patterns:[[b("F1",.5,.95),b("F1",.5,.6),N(.5),b("F1",.5,.7),b("Ab1",.5,.7),b("C2",.5,.7),b("F1",.5,.65),b("Eb2",.5,.7)],[b("Bb1",.5,.9),b("Bb1",.5,.6),N(.5),b("Bb1",.5,.7),b("Db2",.5,.7),b("F2",.5,.7),b("Bb1",1,.65)],[b("C2",.5,.9),b("C2",.5,.6),b("Eb2",.5,.7),b("D2",.5,.7),b("C2",.5,.7),b("Bb1",.5,.7),b("G1",1,.7)]],sequence:[0,0,1,2]},e={name:"clav",instrument:{...A.clav,volume:.3,lowpass:2700},gain:.55,pan:-.16,patterns:[[b("F4",.25,.8),N(.25),b("Ab4",.25,.6),N(.25),b("F4",.25,.7),b("C5",.25,.6),N(.5),b("Eb5",.5,.7),N(1)],[b("Bb3",.25,.8),N(.25),b("Db4",.25,.6),N(.25),b("F4",.5,.7),N(.5),b("Bb4",.5,.65),N(1)],[b("C4",.25,.8),b("Eb4",.25,.6),b("G4",.5,.7),N(.5),b("C5",.5,.7),b("Bb4",.5,.65),N(1)]],sequence:[0,0,1,2]},n=a=>$t(Se(a,4),ce("C5")),r={name:"horns",instrument:{...A.horns,volume:.26},gain:.55,pan:.15,patterns:[[N(1.5),b(n("Fm7"),.5,.8),N(1.5),b(n("Fm7"),.5,.9)],[N(1.5),b(n("Fm7"),.5,.8),N(1.5),b(n("Bbm7"),.5,.9)],[N(2),b(n("Bbm7"),.5,.82),N(1),b(n("Bbm7"),.5,.88)],[b(n("C7#9"),.5,.92),N(1),b(n("C7#9"),.5,.82),N(1),b(n("C7#9"),.5,.9)]],sequence:[0,1,2,3]},o={name:"kick",instrument:A.kick,gain:.85,patterns:[[b("F1",1,.95),b("F1",.5,.6),N(.5),b("F1",.5,.7),N(.5),b("F1",1,.8)]],sequence:Array(4).fill(0)},i={name:"snare",instrument:{...A.snare,volume:.42},gain:.6,patterns:[[N(1),b("D4",1,.85),N(1),b("D4",1,.9)]],sequence:Array(4).fill(0)},s={name:"hat",instrument:{...A.hat,volume:.18,highpass:5e3,lowpass:9e3},gain:.38,pan:.1,patterns:[[b("C6",.5,.6),b("C6",.5,.35)]],sequence:Array(8).fill(0)};return{bpm:128,tracks:[o,t,e,r,i,s],humanize:.14,velBrightness:.55,sidechain:{depth:.5,beatsPerCycle:1},reverb:{wet:.12,roomSize:.5,damp:.5},master:{lowCut:.3,presence:.16,air:.05,compress:.4}}}function Mu(){let t=["Abmaj7#11","Db9","Bbm7","Eb7alt","Cm7","F7b9","Bbm7","Eb13"],e={name:"bass",instrument:{...A.uprightBass,volume:.5,sub:.4},gain:.72,patterns:t.map((s,a)=>{let l=Se(s,2)[0],u=Se(t[(a+1)%t.length],2)[0],c=u+(l<=u?-1:1);return[b(l,1.5,.9),N(.5),b(l+7,1,.62),b(c,1,.62)]}),sequence:[0,1,2,3,4,5,6,7]},n={name:"rhodes",instrument:{...A.rhodes,volume:.28},gain:.55,pan:-.18,patterns:dn(t,4,"Ab4",.6),sequence:[0,1,2,3,4,5,6,7]},r={name:"vibes",instrument:{...A.vibraphone,volume:.3},gain:.55,pan:.18,patterns:[[N(1),b("C5",1,.7),b("D5",1,.65),b("Eb5",1,.62)],[b("F5",2,.7),b("Eb5",1,.62),b("C5",1,.58)],[b("Db5",1.5,.7),b("F5",1.5,.65),b("Ab5",1,.62)],[b("G5",1,.72),b("Gb5",1,.66),b("Db5",2,.6)],[N(1),b("Eb5",1.5,.68),b("G5",1.5,.62)],[b("Ab5",1,.72),b("Gb5",1,.66),b("F5",2,.6)],[b("Db5",2,.68),b("Bb4",2,.6)],[b("C5",1,.7),b("G5",1,.66),b("Eb5",2,.6)]],sequence:[0,1,2,3,4,5,6,7]},o={name:"kick",instrument:{...A.kick,volume:.55},gain:.62,patterns:[[b("Ab1",1,.85),N(2),b("Ab1",.5,.55),N(.5)]],sequence:Array(8).fill(0)},i={name:"snare",instrument:{...A.rimshot,volume:.22},gain:.5,patterns:[[N(2),b("D4",1,.7),N(1)]],sequence:Array(8).fill(0)};return{bpm:84,tracks:[pn(.32),e,n,r,o,i,At(.28),Cr(.24)],swing:.56,humanize:.3,velBrightness:.62,reverb:{wet:.26,roomSize:.72,damp:.55},master:{lowCut:.24,presence:.14,air:.04,compress:.45}}}function Cu(){let t=["Dm7","G13","Cmaj9","A7b9","Dm7","G7","Cmaj9","Cmaj9"],e={name:"bass",instrument:{...A.uprightBass,volume:.5},gain:.66,patterns:Mr(t,2),sequence:[0,1,2,3,4,5,6,7]},n={name:"rhodes",instrument:{...A.rhodes,volume:.32,release:.5},gain:.6,pan:-.14,patterns:dn(t,4,"E4",.6),sequence:[0,1,2,3,4,5,6,7]},r={name:"trumpet",instrument:{...A.mutedTrumpet,volume:.36,vibrato:.1},gain:.62,pan:.12,patterns:[[N(1),b("A4",1,.72),b("C5",1,.75),b("D5",1,.7)],[b("B4",2,.75),b("G4",1,.65),b("F4",1,.6)],[b("E5",2,.78),b("G4",1,.62),b("E4",1,.6)],[b("C5",1,.72),b("Bb4",1,.68),b("A4",1,.65),b("D5",1,.62)],[b("G4",.5,.78),b("A4",.5,.72),b("C5",1,.82),b("B4",.5,.7),N(1.5)],[b("D5",1,.75),b("B4",1,.68),b("G4",2,.62)],[b("E5",2,.8),b("C5",2,.72)],[b("E4",4,.6)]],sequence:[0,1,2,3,4,5,6,7]},o={name:"brush",instrument:{...A.snare,volume:.12,highpass:1500,release:.15},gain:.42,patterns:[[N(1),b("D4",1,.42),N(1),b("D4",1,.46)]],sequence:Array(8).fill(0)};return{bpm:76,tracks:[pn(.3),e,n,r,o,At(.26)],swing:.56,humanize:.36,velBrightness:.6,reverb:{wet:.3,roomSize:.8,damp:.5},master:{lowCut:.38,presence:.28,air:.09,compress:.65}}}var Si={title:"Neon Precinct",subtitle:"Original Soundtrack",concept:"The score to an imaginary neo-noir detective game. You work the night beat in a rain-slicked retro-future city \u2014 jazz-funk with a noir heart. Six cues, one motif, a long night.",tracks:[{id:"neon-precinct",title:"Neon Precinct",intent:"Main theme \u2014 swaggering medium funk, the city announcing itself.",make:vu},{id:"rain-avenue",title:"Rain on the Avenue",intent:"A smoky, slow torch ballad. Muted trumpet in the rain.",make:wu},{id:"stakeout",title:"Stakeout",intent:"Minimal, nervous cool-jazz. Watching, waiting, unresolved.",make:ku},{id:"the-chase",title:"The Chase",intent:"Driving F-minor funk \u2014 clav, horn stabs, a hard pulse.",make:Su},{id:"smoke-mirrors",title:"Smoke & Mirrors",intent:"Slinky half-time noir; altered colours, nothing as it seems.",make:Mu},{id:"last-call",title:"Last Call",intent:"The warm closer \u2014 a ii\u2013V\u2013I that finally lands, the motif resolved.",make:Cu}]};function Tu(t){return Si.tracks.find(e=>e.id===t)}var hn=null,Mi="hayao-overlay-style",Ru=`
|
|
177
|
+
`):" (all features within tolerance)")}function jc(t,e){if(t.length===0)return 0;let n=t.length>1?[...t].sort((r,o)=>r.x-o.x):t;if(e<=n[0].x)return n[0].y;if(e>=n[n.length-1].x)return n[n.length-1].y;for(let r=1;r<n.length;r++)if(e<=n[r].x){let o=n[r-1],i=n[r],s=i.x===o.x?0:(e-o.x)/(i.x-o.x);return o.y+(i.y-o.y)*s}return n[n.length-1].y}function As(t,e,n=1,r=1e4,o=1){let i=Math.max(1e-6,n);switch(t){case"linear":{let s=Q(e,i,r);return 1-o*(s-i)/Math.max(1e-6,r-i)}case"inverse":{let s=Math.max(e,i);return i/(i+o*(Math.max(s,i)-i))}case"exponential":{let s=Math.max(e,i);return fe(-o*ft(s/i))}}}function Ws(t,e=400){return Q(t/e,-1,1)}function Uc(t,e,n=600,r=1){let o=Math.sqrt(t*t+e*e);return o>n?{gain:0,pan:0,audible:!1}:{gain:As("inverse",o,n*.15,n,r),pan:Ws(t,n*.7),audible:!0}}function Xc(t,e){let n={};for(let r of t){let o=Math.max(1e-6,r.full-r.fadeIn),i=Q((e-r.fadeIn)/o,0,1)*(r.maxGain??1);n[r.name]=i}return n}function Jc(t,e=-12){return t?fe(e/6.0206):1}function Bs(t){let e=t.left.length,n=new Float32Array(e),r=new Float32Array(e);for(let i=0;i<e;i++)n[i]=(t.left[i]+t.right[i])*.5,r[i]=(t.left[i]-t.right[i])*.5;let o=Dt(n);return o<1e-9?0:Dt(r)/o}var Yc={electronic:{tempo:[118,132],centroid:[3e3,7200],onsets:[7,15],rms:[.16,.27],crestDb:[6,15],width:[.03,.6],maxMud:.34},lofi:{tempo:[70,88],centroid:[1600,4300],onsets:[5,13],rms:[.12,.24],crestDb:[7,17],width:[.04,.6],maxMud:.5},piano:{tempo:[58,100],centroid:[700,2100],onsets:[3,11],rms:[.1,.22],crestDb:[9,22],width:[.04,.7],maxMud:.42},orchestral:{tempo:[80,96],centroid:[1100,3e3],onsets:[4,12],rms:[.11,.22],crestDb:[8,21],width:[.05,.7],maxMud:.4},jazzfunk:{tempo:[106,126],centroid:[2200,5600],onsets:[6,16],rms:[.13,.25],crestDb:[7,18],width:[.04,.6],maxMud:.4}};function Ee(t,[e,n]){if(t>=e&&t<=n)return 1;let r=Math.max(1e-6,n-e),o=t<e?e-t:t-n;return Math.max(0,1-o/(r*.6))}function Kc(t,e){let n=new Float32Array(t.left.length);for(let k=0;k<n.length;k++)n[k]=(t.left[k]+t.right[k])*.5;let r=It(n),o=So(n),i=Co(n),s=Bs(t),a=i.lowMid,l=i.high+i.air,u=i.sub+i.bass,c={loudness:Ee(r.rms,e.rms),headroom:r.peakDb<=-.5?r.peakDb>=-3?1:Ee(r.peakDb,[-3,-.5]):0,dynamics:Ee(o,e.crestDb),width:Ee(s,e.width),brightness:Ee(r.centroidHz,e.centroid),density:Ee(r.onsetDensity,e.onsets),tempo:Ee(r.tempoBpm,e.tempo),lowEnd:Ee(u,[.12,.7]),clarity:Ee(a,[0,e.maxMud??.34]),smoothness:Ee(l,[0,.4])},m={loudness:1.2,headroom:1.4,dynamics:1,width:.7,brightness:1.1,density:.9,tempo:.7,lowEnd:1,clarity:1.2,smoothness:1.1},d=0,h=0;for(let k of Object.keys(c))d+=c[k]*m[k],h+=m[k];let p=Math.round(d/h*100),f=[],g=(k,v)=>{c[k]<.75&&f.push(`${k}: ${v}`)};return g("loudness",`rms ${r.rms.toFixed(3)} (target ${e.rms.join("\u2013")})`),g("headroom",`peak ${r.peakDb.toFixed(1)}dB (want \u2264 \u22120.5, \u2265 \u22123)`),g("dynamics",`crest ${o.toFixed(1)}dB (target ${e.crestDb.join("\u2013")})`),g("width",`width ${s.toFixed(2)} (target ${e.width.join("\u2013")})`),g("brightness",`centroid ${Math.round(r.centroidHz)}Hz (target ${e.centroid.join("\u2013")})`),g("density",`onsets ${r.onsetDensity.toFixed(1)}/s (target ${e.onsets.join("\u2013")})`),g("tempo",`tempo ${Math.round(r.tempoBpm)} (target ${e.tempo.join("\u2013")})`),g("lowEnd",`low-end fraction ${u.toFixed(2)} (want 0.12\u20130.62)`),g("clarity",`low-mid mud ${a.toFixed(2)} (want \u2264 ${(e.maxMud??.34).toFixed(2)})`),g("smoothness",`high/air ${l.toFixed(2)} (want \u2264 0.40)`),{score:p,dims:c,notes:f}}var P=(t,e,n=1)=>({pitch:t,beats:e,vel:n}),V=t=>({pitch:null,beats:t});function zs(t,e,n,r=.9){let o=[];for(let i=0;i<e;i++)o.push(P(t[i%t.length]+Math.floor(i/t.length)*12,n,r));return o}function Qc(t,e,n=1){return Array.from({length:e},()=>P(t,1,n))}function Zc(){let t=ct(ce("A3"),"minor",["i","VI","III","VII"]),e=t.map(a=>a[0]-12),n={name:"sub",instrument:W.subBass,gain:.6,patterns:e.map(a=>[P(a,.5,1),P(a,.5,.6),P(a,.5,.85),P(a,.5,.6),P(a,.5,1),P(a,.5,.6),P(a,.5,.85),P(a,.5,.7)]),sequence:[0,1,2,3,0,1,2,3]},r={name:"kick",instrument:W.kick,gain:.82,patterns:[Qc("A1",4)],sequence:Array(8).fill(0)},o={name:"hat",instrument:W.hat,gain:.42,pan:.15,patterns:[[V(.5),P("A6",.5,.7),V(.5),P("A6",.5,.5)]],sequence:Array(16).fill(0)},i={name:"pluck",instrument:{...W.pluck,release:.16,lowpass:2400},gain:.62,pan:-.2,patterns:t.map(a=>zs([a[0],a[1],a[2]],4,1,.7)),sequence:[0,1,2,3,0,1,2,3]},s={name:"lead",instrument:{...W.lead,detune:8,lowpass:2800},gain:.52,pan:.1,patterns:[[P(t[0][2]+12,.75),P(t[0][2]+14,.25),P(t[0][0]+12,1),P(t[0][1]+12,2)],[P(t[1][2]+12,1),P(t[1][1]+12,.5),P(t[1][2]+12,.5),P(t[1][0]+24,2)],[P(t[2][2]+12,.75),P(t[2][1]+12,.25),P(t[2][0]+12,1),P(t[2][2]+12,2)],[P(t[3][0]+24,1),P(t[3][2]+12,.5),P(t[3][1]+12,.5),P(t[3][0]+12,2)]],sequence:[0,1,2,3]};return{bpm:126,tracks:[r,n,o,i,s],reverb:{wet:.15,roomSize:.6,damp:.5},humanize:.05,sidechain:{depth:.55,beatsPerCycle:1},master:{lowCut:.35,presence:.2,air:.08}}}function em(){let t=ce("C4"),e=Pt(ct(t,"major",["IV7","iii7","ii7","I7"]).map(Hn)),n=e.map(c=>c[0]-12),r={name:"rhodes",instrument:{...W.rhodes,volume:.42,lowpass:2600,fm:1.6},gain:.66,pan:-.1,patterns:e.map(c=>[P(c.map(m=>m),3.5,.75),V(.5)]),sequence:[0,1,2,3,0,1,2,3]},o={name:"bass",instrument:{...W.bass,lowpass:650,sub:.28},gain:.72,pan:.05,patterns:n.map(c=>[P(c,1.5,.9),V(.5),P(c+7,1,.7),P(c+5,1,.6)]),sequence:[0,1,2,3,0,1,2,3]},i={name:"kick",instrument:{...W.kick,volume:.75},gain:.82,patterns:[[P("C2",1,.9),V(1),P("C2",.5,.6),V(.5),P("C2",.5,.4),V(.5)]],sequence:Array(8).fill(0)},s={name:"snare",instrument:{...W.rimshot,volume:.24,lowpass:4e3},gain:.6,patterns:[[V(1),P("C4",1,.7),V(1),P("C4",1,.7)]],sequence:Array(8).fill(0)},a={name:"hat",instrument:{...W.hat,volume:.14,highpass:2500,lowpass:6e3},gain:.45,pan:.2,patterns:[[P("C6",.5,.5),P("C6",.5,.3)]],sequence:Array(16).fill(0)},l={name:"vinyl",instrument:{wave:"noise",attack:.5,release:.5,sustainLevel:1,volume:.022,lowpass:2800,highpass:400},gain:.3,patterns:[[P("C4",16,1)]],sequence:[0]},u={name:"keys",instrument:{...W.piano,volume:.3,lowpass:2800},gain:.48,pan:.15,patterns:[[P(e[0][2]+12,1,.7),V(1),P(e[0][1]+12,.5,.55),P(e[0][2]+12,.5,.5),V(1)],[V(.5),P(e[1][2]+12,1,.7),V(.5),P(e[1][1]+12,2,.55)],[P(e[2][2]+12,1.5,.7),P(e[2][1]+12,.5,.5),V(2)],[V(1),P(e[3][2]+12,1,.7),P(e[3][1]+12,1,.55),V(1)]],sequence:[0,1,2,3,0,1,2,3]};return{bpm:78,tracks:[l,r,o,i,s,a,u],swing:.75,humanize:.4,velBrightness:.7,reverb:{wet:.24,roomSize:.7,damp:.65},master:{lowCut:.26,presence:.22,air:.05}}}function tm(){let t=ce("A3"),e=Pt(ct(t,"minor",["i","VI","III","VII"])),n=[a=>[P(a[0],1,.85),P(a[2],1,.55),V(2)],a=>[P(a[2],1.5,.8),V(.5),P(a[1],2,.5)],a=>[V(1),P(a[1]+12,1.5,.7),V(1.5)],a=>[P(a[0],2,.8),P(a[2],1,.55),V(1)]],r={name:"piano",instrument:{...W.piano,volume:.46},gain:.78,pan:-.05,patterns:e.map((a,l)=>n[l%n.length](a)),sequence:[0,1,2,3,0,1,2,3]},o={name:"strings",instrument:{...W.strings,attack:.4},gain:.5,pan:.1,patterns:e.map(a=>[P(a.map(l=>l-12),4,.65)]),sequence:[0,1,2,3,0,1,2,3]},i={name:"sub",instrument:{...W.subBass,volume:.4,attack:.03},gain:.55,patterns:e.map(a=>[P(a[0]-24,4,.6)]),sequence:[0,1,2,3,0,1,2,3]},s={name:"melody",instrument:{...W.piano,volume:.4,lowpass:3e3},gain:.5,pan:.12,patterns:[[V(2),P(e[0][2]+12,1,.75),P(e[0][1]+12,1,.55)],[P(e[1][2]+12,2,.8),P(e[1][1]+12,1,.55),V(1)],[V(1.5),P(e[2][2]+12,1.5,.75),P(e[2][1]+12,1,.55)],[P(e[3][1]+12,1.5,.7),P(e[3][0]+12,2.5,.6)]],sequence:[0,1,2,3,0,1,2,3]};return{bpm:66,tracks:[i,o,r,s],humanize:.5,velBrightness:.75,reverb:{wet:.38,roomSize:.86,damp:.55},master:{lowCut:.4,presence:.28,air:.12}}}function nm(){let t=ce("D3"),e=Pt(ct(t,"minor",["i","VI","III","VII","VI","VII","i","i"])),n=Vn(ce("D4"),"minor",3),r=m=>n[(m%n.length+n.length)%n.length],o={name:"strings",instrument:{...W.strings,volume:.24},gain:.7,pan:-.15,patterns:e.map(m=>zs([m[0],m[1],m[2],m[0]+12],8,.5,.75)),sequence:[0,1,2,3,4,5,6,7]},i=[[P(r(0),2,.9),P(r(1),1,.8),P(r(2),1,.85)],[P(r(4),3,.95),P(r(2),1,.8)],[P(r(1),2,.85),P(r(0),1,.8),P(r(1),1,.8)],[P(r(4),2,.9),P(r(5),2,.95)],[P(r(5),2,.95),P(r(4),1,.85),P(r(2),1,.8)],[P(r(4),2,.9),P(r(6),2,.95)],[P(r(7),3,1),P(r(6),1,.85)],[P(r(7),4,1)]],s=[V(4)],a={name:"brass",instrument:{...W.brass,volume:.32},gain:.62,pan:.15,patterns:[s,...i],sequence:[0,0,1,2,3,4,5,6]},l={name:"choir",instrument:{...W.choir,volume:.18},gain:.5,pan:.05,patterns:e.map(m=>[P([m[2]+12,m[0]+24],4,.6)]),sequence:[0,1,2,3,4,5,6,7]},u={name:"timpani",instrument:{...W.kick,decay:.14,release:.25,slide:-12,volume:.85,sub:.5},gain:.82,patterns:[[P("D2",1,1),P("D2",1,.6),P("D2",.5,.85),P("D2",.5,.6),P("D2",1,.9)]],sequence:Array(8).fill(0)},c={name:"glocken",instrument:W.glocken,gain:.32,pan:.25,patterns:[s,...e.map(m=>[V(1),P(m[2]+24,1,.55),V(1),P(m[1]+24,1,.5)])],sequence:[0,0,3,4,5,6,7,8]};return{bpm:88,tracks:[u,o,a,l,c],humanize:.14,velBrightness:.5,reverb:{wet:.32,roomSize:.9,damp:.4},master:{lowCut:.4,presence:.32,air:.14}}}function rm(){let t=ce("C4"),e=ct(t,"major",["ii7","V7","I7","vi7"]),n=Pt(e.map(Hn)),r=e.map((c,m)=>{let d=e[(m+1)%e.length][0]-24,h=c[0]-24,p=c[1]-24,f=c[2]-24,g=d+(h<d?-1:1);return[P(h,1,.95),P(p,1,.75),P(f,1,.8),P(g,1,.7)]}),o={name:"bass",instrument:{...W.bass,lowpass:1e3,sub:.35,release:.12},gain:.74,patterns:r,sequence:[0,1,2,3,0,1,2,3]},i={name:"rhodes",instrument:{...W.rhodes,volume:.3},gain:.62,pan:-.15,patterns:n.map(c=>[V(.5),P(c.map(m=>m),.75,.7),V(.75),P(c.map(m=>m),.5,.55),V(1.5)]),sequence:[0,1,2,3,0,1,2,3]},s={name:"brass",instrument:{...W.brass,release:.1,volume:.24},gain:.55,pan:.2,patterns:[[V(2),P(n[0].map(c=>c+12),.5,.85),V(1.5)],[V(3),P(n[1].map(c=>c+12),.5,.85),V(.5)],[P(n[2].map(c=>c+12),.5,.8),V(3.5)],[V(2.5),P(n[3].map(c=>c+12),.5,.8),V(1)]],sequence:[0,1,2,3,0,1,2,3]},a={name:"ride",instrument:{...W.hat,volume:.13,highpass:3e3,lowpass:9e3,release:.08},gain:.5,pan:.1,patterns:[[P("C6",.5,.6),P("C6",.5,.35),P("C6",.5,.5),P("C6",.5,.35)]],sequence:Array(16).fill(0)},l={name:"snare",instrument:{...W.snare,volume:.28,highpass:900},gain:.5,patterns:[[V(1),P("D4",1,.6),V(1),P("D4",1,.7)]],sequence:Array(8).fill(0)},u={name:"kick",instrument:{...W.kick,volume:.55},gain:.62,patterns:[[P("C2",1,.85),V(1.5),P("C2",.5,.6),V(1)]],sequence:Array(8).fill(0)};return{bpm:116,tracks:[o,i,s,u,l,a],swing:.66,humanize:.35,velBrightness:.6,reverb:{wet:.16,roomSize:.55,damp:.5},master:{lowCut:.5,presence:.18,air:.07}}}var _s=[{id:"electronic",name:"Minimal Electronic",description:"Bass-driven four-on-the-floor in A minor \u2014 pulsing sidechained sub, offbeat hats, a synth hook.",make:Zc},{id:"lofi",name:"Lo-fi Beats",description:"Swung, dusty jazz sevenths on a Rhodes with warm bass, brushed drums and vinyl crackle.",make:em},{id:"piano",name:"Melancholic Piano",description:"Slow, sad A-minor piano with space and rubato over a string bed in a big room.",make:tm},{id:"orchestral",name:"Epic Orchestral",description:"Uplifting D-minor with a soaring brass theme, arpeggiated strings, choir, timpani and glockenspiel.",make:nm},{id:"jazzfunk",name:"Jazz Funk",description:"Swung ii\u2013V\u2013I with a walking bass that chromatically approaches each chord, Rhodes comping and brass stabs.",make:rm}];function om(t){return _s.find(e=>e.id===t)}var Os=["sine","triangle","saw","square","noise"],To=new Set;function Xn(t,e){To.has(t)||(To.add(t),console.warn(`[hayao] specFromZzfx: ${t} ${e}`))}function im(){To.clear()}function sm(t){let e=t[0]??1,n=t[1]??.05,r=t[2]??220,o=t[3]??0,i=t[4]??0,s=t[5]??.1,a=t[6]??0,l=t[7]??1,u=t[8]??0,c=t[9]??0,m=t[10]??0,d=t[11]??0,h=t[12]??0,p=t[13]??0,f=t[14]??0,g=t[15]??0,k=t[16]??0,v=t[17]??1,M=t[18]??0,I=t[19]??0,x=t[20]??0,b=o+M+i+s,w={freq:r,volume:e,attack:o,decay:M,sustain:i,release:s,sustainLevel:v},C=Math.max(0,Math.min(Os.length-1,Math.round(a)));if(w.wave=Os[C],Math.round(a)===3&&Xn("shape=3 (tan)","has no hayao wave; approximated as a hard square."),l!==1&&(w.shapeCurve=l),n!==0&&Xn("randomness","is dropped: hayao specs are deterministic (same spec \u2192 same samples)."),u!==0&&(w.slide=u*b),c!==0&&(w.slideAccel=c*b*b/2),m!==0){let E=r+m;E>0&&r>0?(w.pitchJump=12*ft(E/r),w.pitchJumpTime=d):Xn("pitchJump","would drive frequency to \u2264 0 Hz; dropped.")}return h>0&&(w.repeat=h),p!==0&&(w.noise=Math.max(0,Math.min(1,p))),f!==0&&(Xn("modulation","is approximated as vibrato (pitch LFO at |modulation| Hz)."),w.vibrato=.6,w.vibratoFreq=Math.abs(f)),g>0&&(w.bitCrush=Math.max(1,Math.round(g*100))),I!==0&&(w.tremolo=Math.max(0,Math.min(1,I))),k>0&&(w.delay=k,w.delayFeedback=.5),x>0?w.lowpass=x:x<0&&(w.highpass=-x),w}var y=(t,e,n=1)=>({pitch:t,beats:e,vel:n}),F=t=>({pitch:null,beats:t});function Mo(t,e=2){return t.map((n,r)=>{let o=Ce(n,e),i=o[0],s=o[1]??i+3,a=o[2]??i+7,l=Ce(t[(r+1)%t.length],e)[0],u=l+(i<=l?-1:1);return[y(i,1,.92),y(s,1,.72),y(a,1,.78),y(u,1,.7)]})}function Yn(t,e=4,n="F4",r=.66){let o=ce(n);return t.map((i,s)=>{let a=an(Ce(i,e),o);return s%2===0?[y(a,1,r),F(.5),y(a,.5,r*.8),F(2)]:[F(1.5),y(a,.5,r*.85),F(1),y(a,.5,r*.7),F(.5)]})}function am(t,e=4,n="F4",r=.6){let o=ce(n);return t.map(i=>[y(an(Ce(i,e),o),4,r)])}var lm=()=>[y("C6",1,.55),y("C6",.5,.35),y("C6",.5,.5),y("C6",1,.55),y("C6",.5,.35),y("C6",.5,.5)],um=()=>[F(1),y("C6",1,.5),F(1),y("C6",1,.5)];function ln(t=.42,e=8){return{name:"ride",instrument:W.ride,gain:t,pan:.12,patterns:[lm()],sequence:Array(e).fill(0)}}function Ro(t=.4,e=8){return{name:"hat",instrument:{...W.hat,highpass:5e3,volume:.2},gain:t,pan:-.1,patterns:[um()],sequence:Array(e).fill(0)}}function Kn(t=.32,e=8){return{name:"vinyl",instrument:{wave:"noise",attack:.6,release:.6,sustainLevel:1,volume:.03,lowpass:3e3,highpass:380},gain:t,patterns:[[y("C4",e*4,1)]],sequence:[0]}}var Jn=["F5","Gb5","Bb5","Ab5"];function cm(){let t=["Bbm9","Bbm9","Ebm9","Ab13","Dbmaj7","Gm7b5","C7alt","Fm7"],n={name:"bass",instrument:{...W.uprightBass,volume:.5},gain:.7,patterns:[[y("Bb1",.75,.95),y("Bb1",.25,.5),F(.5),y("Db2",.5,.7),y("F2",.5,.75),y("Ab1",.5,.6),y("Bb1",1,.7)],...Mo(t.slice(2),2)],sequence:[0,0,1,2,3,4,5,6]},r={name:"rhodes",instrument:{...W.rhodes,volume:.32},gain:.6,pan:-.18,patterns:Yn(t,4,"Ab4",.62),sequence:[0,1,2,3,4,5,6,7]},o={name:"trumpet",instrument:{...W.mutedTrumpet,volume:.34},gain:.62,pan:.14,patterns:[[y(Jn[0],.5,.85),y(Jn[1],.5,.7),y(Jn[2],1,.9),y(Jn[3],.5,.75),F(1.5)],[y("F5",.5,.8),y("Db5",.5,.7),y("Bb4",1.5,.85),F(1.5)],[y("C5",.5,.85),y("Db5",.5,.72),y("F5",1,.9),y("Eb5",.5,.75),F(1.5)],[y("Db5",1,.8),y("C5",.5,.7),y("Bb4",.5,.7),y("Ab4",2,.72)],[y("Db5",.5,.8),y("F5",.5,.8),y("Ab5",1.5,.85),y("Gb5",1.5,.75)],[y("D5",1,.8),y("F5",1,.8),y("Ab5",1,.85),F(1)],[y("E5",.5,.85),y("Eb5",.5,.8),y("Db5",1,.8),y("C5",2,.78)],[y("F5",1,.85),y("Ab5",1,.8),y("C6",2,.9)]],sequence:[0,1,2,3,4,5,6,7]},i={name:"kick",instrument:{...W.kick,volume:.5},gain:.6,patterns:[[y("Bb1",1,.8),F(1.5),y("Bb1",.5,.55),F(1)]],sequence:Array(8).fill(0)},s={name:"snare",instrument:{...W.snare,volume:.3,highpass:1e3},gain:.5,patterns:[[F(1),y("D4",1,.7),F(1),y("D4",1,.75)]],sequence:Array(8).fill(0)};return{bpm:100,tracks:[n,r,o,i,s,ln(.42),Ro(.35)],swing:.6,humanize:.32,velBrightness:.6,reverb:{wet:.17,roomSize:.6,damp:.5},master:{lowCut:.24,presence:.14,air:.04,compress:.45}}}function mm(){let t=["Ebmaj7","Cm7","Fm7","Bb13","Gm7","C7b9","Fm7","Bb7alt"],e={name:"bass",instrument:{...W.uprightBass,volume:.54,release:.2},gain:.74,patterns:t.map(i=>{let s=Ce(i,2)[0];return[y(s,2,.85),y(s+7,1,.6),y(s+12,1,.55)]}),sequence:[0,1,2,3,4,5,6,7]},n={name:"rhodes",instrument:{...W.rhodes,volume:.34,release:.6},gain:.62,pan:-.15,patterns:am(t,4,"G4",.62),sequence:[0,1,2,3,4,5,6,7]},r={name:"trumpet",instrument:{...W.mutedTrumpet,volume:.36,attack:.05,vibrato:.11},gain:.62,pan:.12,patterns:[[F(1),y("G4",1.5,.7),y("Bb4",1,.75),y("G4",.5,.6)],[y("Eb4",2,.7),y("G4",1,.65),F(1)],[F(.5),y("Ab4",1.5,.72),y("C5",1,.75),y("Ab4",1,.62)],[y("D5",2.5,.78),y("Bb4",1.5,.65)],[y("Bb4",1.5,.7),y("G4",1,.65),y("D5",1.5,.72)],[y("Db5",2,.75),y("C5",1,.68),y("Bb4",1,.62)],[y("Ab4",2,.72),y("F4",1,.62),F(1)],[y("Ab4",1,.72),y("Db5",1,.7),y("D5",2,.72)]],sequence:[0,1,2,3,4,5,6,7]},o={name:"brush",instrument:{...W.snare,volume:.12,highpass:1500,release:.16},gain:.4,patterns:[[F(1),y("D4",1,.4),F(1),y("D4",1,.45)]],sequence:Array(8).fill(0)};return{bpm:62,tracks:[Kn(.3),e,n,r,o,ln(.24)],swing:.5,humanize:.4,velBrightness:.6,reverb:{wet:.34,roomSize:.85,damp:.55},master:{lowCut:.24,presence:.16,air:.05,compress:.65}}}function dm(){let t=["Cm9","Cm9","Fm9","Dm7b5","G7alt","Cm9","Ab13","G7alt"],e={name:"bass",instrument:{...W.uprightBass,volume:.48},gain:.68,patterns:Mo(t,2),sequence:[0,1,2,3,4,5,6,7]},n={name:"vibes",instrument:{...W.vibraphone,volume:.34},gain:.6,pan:.1,patterns:[[y("G4",1,.7),F(1),y("Eb5",1,.65),F(1)],[F(2),y("D5",1,.68),y("C5",1,.6)],[y("Ab4",1,.7),F(1.5),y("F5",1.5,.6)],[y("F4",1,.7),y("Ab4",1,.6),F(2)],[F(1),y("B4",1,.72),y("Ab4",1,.6),y("F4",1,.55)],[y("Eb5",2,.68),y("C5",2,.6)],[y("C5",1,.7),y("Gb5",1,.68),F(2)],[y("B4",1,.7),y("Db5",1,.62),y("Ab4",2,.58)]],sequence:[0,1,2,3,4,5,6,7]},r={name:"guitar",instrument:{...W.jazzGuitar,volume:.22},gain:.5,pan:-.2,patterns:Yn(t,4,"Eb4",.5),sequence:[0,1,2,3,4,5,6,7]};return{bpm:96,tracks:[Kn(.28),e,r,n,ln(.3),Ro(.28)],swing:.62,humanize:.34,velBrightness:.6,reverb:{wet:.22,roomSize:.65,damp:.5},master:{lowCut:.24,presence:.13,air:.04,compress:.45}}}function hm(){let t={name:"bass",instrument:{...W.bass,volume:.52,lowpass:1e3,sub:.35},gain:.75,patterns:[[y("F1",.5,.95),y("F1",.5,.6),F(.5),y("F1",.5,.7),y("Ab1",.5,.7),y("C2",.5,.7),y("F1",.5,.65),y("Eb2",.5,.7)],[y("Bb1",.5,.9),y("Bb1",.5,.6),F(.5),y("Bb1",.5,.7),y("Db2",.5,.7),y("F2",.5,.7),y("Bb1",1,.65)],[y("C2",.5,.9),y("C2",.5,.6),y("Eb2",.5,.7),y("D2",.5,.7),y("C2",.5,.7),y("Bb1",.5,.7),y("G1",1,.7)]],sequence:[0,0,1,2]},e={name:"clav",instrument:{...W.clav,volume:.3,lowpass:2700},gain:.55,pan:-.16,patterns:[[y("F4",.25,.8),F(.25),y("Ab4",.25,.6),F(.25),y("F4",.25,.7),y("C5",.25,.6),F(.5),y("Eb5",.5,.7),F(1)],[y("Bb3",.25,.8),F(.25),y("Db4",.25,.6),F(.25),y("F4",.5,.7),F(.5),y("Bb4",.5,.65),F(1)],[y("C4",.25,.8),y("Eb4",.25,.6),y("G4",.5,.7),F(.5),y("C5",.5,.7),y("Bb4",.5,.65),F(1)]],sequence:[0,0,1,2]},n=a=>an(Ce(a,4),ce("C5")),r={name:"horns",instrument:{...W.horns,volume:.26},gain:.55,pan:.15,patterns:[[F(1.5),y(n("Fm7"),.5,.8),F(1.5),y(n("Fm7"),.5,.9)],[F(1.5),y(n("Fm7"),.5,.8),F(1.5),y(n("Bbm7"),.5,.9)],[F(2),y(n("Bbm7"),.5,.82),F(1),y(n("Bbm7"),.5,.88)],[y(n("C7#9"),.5,.92),F(1),y(n("C7#9"),.5,.82),F(1),y(n("C7#9"),.5,.9)]],sequence:[0,1,2,3]},o={name:"kick",instrument:W.kick,gain:.85,patterns:[[y("F1",1,.95),y("F1",.5,.6),F(.5),y("F1",.5,.7),F(.5),y("F1",1,.8)]],sequence:Array(4).fill(0)},i={name:"snare",instrument:{...W.snare,volume:.42},gain:.6,patterns:[[F(1),y("D4",1,.85),F(1),y("D4",1,.9)]],sequence:Array(4).fill(0)},s={name:"hat",instrument:{...W.hat,volume:.18,highpass:5e3,lowpass:9e3},gain:.38,pan:.1,patterns:[[y("C6",.5,.6),y("C6",.5,.35)]],sequence:Array(8).fill(0)};return{bpm:128,tracks:[o,t,e,r,i,s],humanize:.14,velBrightness:.55,sidechain:{depth:.5,beatsPerCycle:1},reverb:{wet:.12,roomSize:.5,damp:.5},master:{lowCut:.3,presence:.16,air:.05,compress:.4}}}function pm(){let t=["Abmaj7#11","Db9","Bbm7","Eb7alt","Cm7","F7b9","Bbm7","Eb13"],e={name:"bass",instrument:{...W.uprightBass,volume:.5,sub:.4},gain:.72,patterns:t.map((s,a)=>{let l=Ce(s,2)[0],u=Ce(t[(a+1)%t.length],2)[0],c=u+(l<=u?-1:1);return[y(l,1.5,.9),F(.5),y(l+7,1,.62),y(c,1,.62)]}),sequence:[0,1,2,3,4,5,6,7]},n={name:"rhodes",instrument:{...W.rhodes,volume:.28},gain:.55,pan:-.18,patterns:Yn(t,4,"Ab4",.6),sequence:[0,1,2,3,4,5,6,7]},r={name:"vibes",instrument:{...W.vibraphone,volume:.3},gain:.55,pan:.18,patterns:[[F(1),y("C5",1,.7),y("D5",1,.65),y("Eb5",1,.62)],[y("F5",2,.7),y("Eb5",1,.62),y("C5",1,.58)],[y("Db5",1.5,.7),y("F5",1.5,.65),y("Ab5",1,.62)],[y("G5",1,.72),y("Gb5",1,.66),y("Db5",2,.6)],[F(1),y("Eb5",1.5,.68),y("G5",1.5,.62)],[y("Ab5",1,.72),y("Gb5",1,.66),y("F5",2,.6)],[y("Db5",2,.68),y("Bb4",2,.6)],[y("C5",1,.7),y("G5",1,.66),y("Eb5",2,.6)]],sequence:[0,1,2,3,4,5,6,7]},o={name:"kick",instrument:{...W.kick,volume:.55},gain:.62,patterns:[[y("Ab1",1,.85),F(2),y("Ab1",.5,.55),F(.5)]],sequence:Array(8).fill(0)},i={name:"snare",instrument:{...W.rimshot,volume:.22},gain:.5,patterns:[[F(2),y("D4",1,.7),F(1)]],sequence:Array(8).fill(0)};return{bpm:84,tracks:[Kn(.32),e,n,r,o,i,ln(.28),Ro(.24)],swing:.56,humanize:.3,velBrightness:.62,reverb:{wet:.26,roomSize:.72,damp:.55},master:{lowCut:.24,presence:.14,air:.04,compress:.45}}}function fm(){let t=["Dm7","G13","Cmaj9","A7b9","Dm7","G7","Cmaj9","Cmaj9"],e={name:"bass",instrument:{...W.uprightBass,volume:.5},gain:.66,patterns:Mo(t,2),sequence:[0,1,2,3,4,5,6,7]},n={name:"rhodes",instrument:{...W.rhodes,volume:.32,release:.5},gain:.6,pan:-.14,patterns:Yn(t,4,"E4",.6),sequence:[0,1,2,3,4,5,6,7]},r={name:"trumpet",instrument:{...W.mutedTrumpet,volume:.36,vibrato:.1},gain:.62,pan:.12,patterns:[[F(1),y("A4",1,.72),y("C5",1,.75),y("D5",1,.7)],[y("B4",2,.75),y("G4",1,.65),y("F4",1,.6)],[y("E5",2,.78),y("G4",1,.62),y("E4",1,.6)],[y("C5",1,.72),y("Bb4",1,.68),y("A4",1,.65),y("D5",1,.62)],[y("G4",.5,.78),y("A4",.5,.72),y("C5",1,.82),y("B4",.5,.7),F(1.5)],[y("D5",1,.75),y("B4",1,.68),y("G4",2,.62)],[y("E5",2,.8),y("C5",2,.72)],[y("E4",4,.6)]],sequence:[0,1,2,3,4,5,6,7]},o={name:"brush",instrument:{...W.snare,volume:.12,highpass:1500,release:.15},gain:.42,patterns:[[F(1),y("D4",1,.42),F(1),y("D4",1,.46)]],sequence:Array(8).fill(0)};return{bpm:76,tracks:[Kn(.3),e,n,r,o,ln(.26)],swing:.56,humanize:.36,velBrightness:.6,reverb:{wet:.3,roomSize:.8,damp:.5},master:{lowCut:.38,presence:.28,air:.09,compress:.65}}}var Gs={title:"Neon Precinct",subtitle:"Original Soundtrack",concept:"The score to an imaginary neo-noir detective game. You work the night beat in a rain-slicked retro-future city \u2014 jazz-funk with a noir heart. Six cues, one motif, a long night.",tracks:[{id:"neon-precinct",title:"Neon Precinct",intent:"Main theme \u2014 swaggering medium funk, the city announcing itself.",make:cm},{id:"rain-avenue",title:"Rain on the Avenue",intent:"A smoky, slow torch ballad. Muted trumpet in the rain.",make:mm},{id:"stakeout",title:"Stakeout",intent:"Minimal, nervous cool-jazz. Watching, waiting, unresolved.",make:dm},{id:"the-chase",title:"The Chase",intent:"Driving F-minor funk \u2014 clav, horn stabs, a hard pulse.",make:hm},{id:"smoke-mirrors",title:"Smoke & Mirrors",intent:"Slinky half-time noir; altered colours, nothing as it seems.",make:pm},{id:"last-call",title:"Last Call",intent:"The warm closer \u2014 a ii\u2013V\u2013I that finally lands, the motif resolved.",make:fm}]};function bm(t){return Gs.tracks.find(e=>e.id===t)}var Qn=null,Vs="hayao-overlay-style",gm=`
|
|
6
178
|
.hy-scrim{position:absolute;inset:0;display:grid;place-items:center;z-index:50;font-family:var(--hy-serif,Georgia,serif)}
|
|
7
179
|
.hy-scrim.dim{background:rgba(30,24,14,.5);backdrop-filter:blur(2px)}
|
|
8
180
|
.hy-card{background:var(--hy-paper,#fbf6ea);color:var(--hy-ink,#3d3323);border:1px solid var(--hy-line,#d9ccae);border-radius:14px;box-shadow:0 14px 44px rgba(40,30,15,.3);padding:26px 30px;max-width:440px;text-align:center}
|
|
@@ -12,4 +184,17 @@
|
|
|
12
184
|
.hy-item{font:inherit;font-size:16px;padding:9px 16px;border-radius:9px;border:1px solid var(--hy-line,#d9ccae);background:transparent;color:inherit;cursor:pointer;transition:transform .1s,background .1s}
|
|
13
185
|
.hy-item:hover,.hy-item.sel{background:var(--hy-accent,#a11d3a);color:#fdf3ee;border-color:transparent;transform:translateY(-1px)}
|
|
14
186
|
.hy-item.primary{background:var(--hy-accent,#a11d3a);color:#fdf3ee;border-color:transparent}
|
|
15
|
-
`;function Pu(){if(typeof document>"u"||document.getElementById(Mi))return;let t=document.createElement("style");t.id=Mi,t.textContent=Ru,document.head.appendChild(t)}var Ci=null;function Lt(t){Ci=t}var Tr=null;function fn(t){Tr=t}function Rr(t){if(typeof document>"u")return{close(){},element:null};Pu(),zt(),Tr?.("show",t.title);let e=document.createElement("div");e.className=`hy-scrim${t.dim===!1?"":" dim"}${t.className?" "+t.className:""}`;let n=document.createElement("div");if(n.className="hy-card",t.title){let u=document.createElement("h1");u.textContent=t.title,n.appendChild(u)}if(t.body){let u=document.createElement("div");u.className="hy-body",u.innerHTML=t.body,n.appendChild(u)}let r=t.actions??[],o=Math.max(0,r.findIndex(u=>u.primary));o<0&&(o=0);let i=[];if(r.length){let u=document.createElement("div");u.className="hy-menu",r.forEach((c,m)=>{let d=document.createElement("button");d.className=`hy-item${c.primary?" primary":""}`,d.textContent=c.label,d.addEventListener("click",()=>c.onSelect()),d.addEventListener("mouseenter",()=>s(m)),u.appendChild(d),i.push(d)}),n.appendChild(u)}function s(u){o=(u+i.length)%i.length,i.forEach((c,m)=>c.classList.toggle("sel",m===o))}i.length&&s(o);let a=u=>{i.length&&(u.code==="ArrowDown"?(s(o+1),u.preventDefault()):u.code==="ArrowUp"?(s(o-1),u.preventDefault()):(u.code==="Enter"||u.code==="Space")&&(r[o]?.onSelect(),u.preventDefault()))};document.addEventListener("keydown",a),e.appendChild(n),(Ci??document.body).appendChild(e);let l={element:e,close(){document.removeEventListener("keydown",a),e.remove(),hn===l&&(hn=null,Tr?.("hide",t.title))}};return hn=l,l}function zt(){hn?.close()}var Ti="hayao.settings.v1",Ri={master:.7,music:.6,sfx:.8,muted:!1,colorblind:!1,reducedMotion:!1},Pr=class{state;subs=new Set;constructor(){this.state=this.load(),this.pushToAudio()}get(){return{...this.state}}set(e){this.state={...this.state,...e},this.save(),this.pushToAudio();for(let n of this.subs)n(this.get())}subscribe(e){return this.subs.add(e),()=>this.subs.delete(e)}pushToAudio(){Le.setVolumes({master:this.state.master,music:this.state.music,sfx:this.state.sfx,muted:this.state.muted})}load(){try{let e=typeof localStorage<"u"&&localStorage.getItem(Ti);if(e)return{...Ri,...JSON.parse(e)}}catch{}return{...Ri}}save(){try{localStorage.setItem(Ti,JSON.stringify(this.state))}catch{}}},Ne=new Pr;function Dr(){if(typeof document>"u")return;let t=document,e=document.documentElement;document.fullscreenElement||t.webkitFullscreenElement?(document.exitFullscreen??t.webkitExitFullscreen)?.call(document):(e.requestFullscreen??e.webkitRequestFullscreen)?.call(e)}var Wt=class{paused=!1;opts;keyHandler;constructor(e={}){this.opts=e,this.keyHandler=n=>{n.code==="Escape"&&(n.preventDefault(),this.toggle())},typeof document<"u"&&document.addEventListener("keydown",this.keyHandler)}get isPaused(){return this.paused}toggle(){this.paused?this.resume():this.pause()}pause(){this.paused||(this.paused=!0,Le.blip(440),this.opts.onPause?.(!0),this.render())}resume(){this.paused&&(this.paused=!1,zt(),this.opts.onPause?.(!1))}render(){let e=Ne.get(),n=(r,o)=>`${r}: ${Math.round(o*100)}`;Rr({title:this.opts.title??"Paused",body:`<div style="font-size:13px;text-align:left;line-height:1.9">${n("Master",e.master)} \xB7 ${n("Music",e.music)} \xB7 ${n("Sfx",e.sfx)}<br/><span style="opacity:.7">Use the menu, or keys: M mute \xB7 F fullscreen</span></div>`,actions:[{label:"Resume",primary:!0,onSelect:()=>this.resume()},{label:e.muted?"Unmute (M)":"Mute (M)",onSelect:()=>{Ne.set({muted:!Ne.get().muted}),this.render()}},{label:"Music \u2212/+",onSelect:()=>{let r=Math.min(1,Ne.get().music+.1)%1.05;Ne.set({music:r>1?0:r}),this.render()}},{label:"Fullscreen (F)",onSelect:()=>Dr()},...this.opts.onRestart?[{label:"Restart",onSelect:()=>{this.resume(),this.opts.onRestart()}}]:[],...this.opts.onQuit?[{label:"Quit",onSelect:()=>{this.resume(),this.opts.onQuit()}}]:[]]})}dispose(){typeof document<"u"&&document.removeEventListener("keydown",this.keyHandler),zt()}};var Du=[0,8,2,10,12,4,14,6,3,11,1,9,15,7,13,5],Iu=t=>t*t*(3-2*t),bn=class extends q{type="ScreenTransition";kind;color;screenW;screenH;cell;coverage=0;queue=[];constructor(e={}){super(e),this.cosmetic=!0,this.kind=e.kind??"fade",this.color=e.color??"#1a1410",this.screenW=e.width??1280,this.screenH=e.height??720,this.cell=e.cell??28}get busy(){return this.queue.length>0}enqueue(e,n,r){this.queue.push({from:void 0,to:e,dur:Math.max(1e-4,n),elapsed:0,onEnd:r})}cover(e=.4,n){return this.enqueue(1,e,n),this}reveal(e=.4,n){return this.enqueue(0,e,n),this}hold(e,n){let r=this.queue.length?this.queue[this.queue.length-1].to:this.coverage;return this.enqueue(r,e,n),this}wipe(e={}){let n=e.cover??.4;return this.cover(n,()=>{this.emit("covered",void 0),e.onMidpoint?.()}),e.hold&&this.hold(e.hold),this.reveal(e.reveal??n,()=>{this.emit("done",void 0),e.onDone?.()}),this}get covered(){return this.signal("covered")}get done(){return this.signal("done")}onProcess(e){let n=this.queue[0];if(!n)return;n.from===void 0&&(n.from=this.coverage),n.elapsed+=e;let r=U(n.elapsed/n.dur,0,1);if(this.coverage=Ie(n.from,n.to,Iu(r)),r>=1){this.coverage=n.to;let o=n.onEnd;this.queue.shift(),o?.()}}draw(e,n){let r=this.coverage;if(r<=0)return;let o=this.z;if(this.kind==="fade"){e.push({kind:"rect",x:0,y:0,w:this.screenW,h:this.screenH,fill:this.color,opacity:r,transform:le,z:o});return}if(this.kind==="circle"){let a=this.screenW/2,l=this.screenH/2,u=Math.sqrt(a*a+l*l);e.push({kind:"circle",cx:a,cy:l,radius:r*u,fill:this.color,transform:le,z:o});return}let i=Math.ceil(this.screenW/this.cell),s=Math.ceil(this.screenH/this.cell);for(let a=0;a<s;a++)for(let l=0;l<i;l++)(Du[(l&3)+((a&3)<<2)]+.5)/16<r&&e.push({kind:"rect",x:l*this.cell,y:a*this.cell,w:this.cell,h:this.cell,fill:this.color,transform:le,z:o})}},Ir=class extends q{type="CinematicPlayer";steps=[];index=-1;elapsed=0;running=!1;onFinish;constructor(e={}){super(e),this.cosmetic=!0}play(e,n){return this.steps=e,this.onFinish=n,this.index=-1,this.elapsed=0,this.running=e.length>0,this.advance(),this}get active(){return this.running}get step(){return this.index}get finished(){return this.signal("finished")}advance(){if(this.index++,this.elapsed=0,this.index>=this.steps.length){this.running=!1,this.index=-1,this.emit("finished",void 0),this.onFinish?.();return}this.steps[this.index].enter?.()}stop(){this.running=!1,this.index=-1,this.steps=[]}onProcess(e){if(!this.running)return;this.elapsed+=e;let n=this.steps[this.index],r=this.elapsed>=(n.duration??0),o=n.until?n.until():!0;r&&o&&this.advance()}};function Eu(t,e={}){let n=new bn({z:1e4,...e});return t.addChild(n)}function Fu(t,e={}){return{name:e.name??"wipe",enter:()=>t.wipe(e),until:()=>!t.busy}}var Nu=(t,e)=>({x:0,y:0,w:t,h:e});function Ke(t,e={}){let n=e.maxDepth??60,r=e.nodeCap??1e6,o=t.initial(e.level);if(t.isWin(o))return{solvable:!0,path:[],depth:0,nodes:0,exhausted:!1};let i=[{state:o,path:[]}],s=new Set([t.key(o)]),a=0;for(let l=0;l<n&&i.length>0;l++){let u=[];for(let{state:c,path:m}of i)for(let d of t.moves(c)){if(a>=r)return{solvable:!1,nodes:a,exhausted:!0};a++;let p=t.apply(c,d);if(t.isDead?.(p))continue;if(t.isWin(p))return{solvable:!0,path:[...m,d],depth:l+1,nodes:a,exhausted:!1};let h=t.key(p);s.has(h)||(s.add(h),u.push({state:p,path:[...m,d]}))}i=u}return{solvable:!1,nodes:a,exhausted:i.length>0}}function $u(t,e={}){let n=Ke(t,e);if(!n.solvable)throw new Error(`hayao: level ${e.level??0} is NOT winnable (expanded ${n.nodes} nodes${n.exhausted?", search capped \u2014 raise nodeCap/maxDepth":""}).`);return n}function Er(t,e){let n=t(),r=[];for(let o=0;o<e.frames.length;o++)n.step(tt(e,o)),r.push(n.hash());return{finalHash:n.hash(),hashes:r}}function Pi(t,e){let n=Er(t,e),r=Er(t,e),o=-1;for(let i=0;i<n.hashes.length;i++)if(n.hashes[i]!==r.hashes[i]){o=i;break}return{ok:o===-1&&n.finalHash===r.finalHash,frames:e.frames.length,divergedAt:o,finalHash:n.finalHash}}function Au(t,e){let n=Pi(t,e);if(!n.ok)throw new Error(`hayao: sim is NON-deterministic \u2014 runs diverged at frame ${n.divergedAt} of ${n.frames}. Check for Math.random/Date.now/Set-iteration/unordered-map in the sim.`);return n}function Lu(t,e,n){let r=t();for(let l=0;l<n;l++)r.step(tt(e,l));let o=r.snapshot(),i=t();i.restore(o);for(let l=n;l<e.frames.length;l++)r.step(tt(e,l)),i.step(tt(e,l));let s=r.hash(),a=i.hash();return{ok:s===a,hashA:s,hashB:a}}function zu(t,e){return{actions:t,frames:e}}function Wu(t){return{actions:[],frames:t}}function Bu(t,e){let n=[],r=0;for(let o of e){for(let i=0;i<o.frames;i++)t.step(o.actions??[]);r+=o.frames,n.push(t.probe())}return{totalFrames:r,finalHash:t.hash(),probes:n}}function Ou(t,e,n=[]){for(let r=0;r<e;r++)t.step(n)}function Fr(){return typeof location<"u"&&new URLSearchParams(location.search).has("capture")}function Nr(t){let e={pump(n,r=[]){t.setPaused(!0);for(let o=0;o<n;o++)t.stepOnce(r);return t.world.probe()},probe:()=>t.world.probe(),hash:()=>t.world.hash(),shot:()=>t.renderSVG(),async save(n){let r=t.renderSVG();try{return(await fetch("/__shot",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({path:n,svg:r})})).ok}catch{return!1}},key(n,r){document.dispatchEvent(new KeyboardEvent(n,{code:r,bubbles:!0}))},get world(){return t.world}};return globalThis.__hayao=e,e}function Di(t){let e=[];for(let n of t){let r=n.frames??1,o=n.hold??[];for(let i=0;i<r;i++)e.push(i===0&&n.press?[...o,...n.press]:[...o])}return e}function Gu(t,e,n){let r=0;for(let o of Di(e)){if(n&&n(t.probe()))return{frames:r,matched:!0};t.step(o),r++}return{frames:r,matched:n?n(t.probe()):!1}}function Vu(t,e){let n=0,r=0,o={},s=a=>{let l=[],u=t[n];if(!u)return l;r++;let c={get frames(){return r},mem:o,next(){n++,r=0,o={}},retry(){r=0,o={}}},m=e[u.kind];if(!m)throw new Error(`plan bot: no executor for step kind "${u.kind}"`);return m(u,a,l,c),l};return s.stepIndex=()=>n,s.done=()=>n>=t.length,s}function qu(t,e,n,r,o,i=8){t<n-i?o.push("right"):t>n+i&&o.push("left"),e<r-i?o.push("down"):e>r+i&&o.push("up")}var Ot=t=>[...new Set(t)];function Ii(t,e={}){let n=e.minCoyote??.05,r=e.minBuffer??.05,o=e.requireCornerNudge??!0,i=[];return t.coyoteTime>=n||i.push(`coyote time ${t.coyoteTime}s is below the ${n}s floor \u2014 late jumps off a ledge will be dropped`),t.jumpBuffer>=r||i.push(`jump buffer ${t.jumpBuffer}s is below the ${r}s floor \u2014 early jumps before landing will be swallowed`),o&&!((t.jumpCornerNudge??0)>0)&&i.push("no jump corner nudge \u2014 clipping a ceiling edge kills upward momentum instead of slipping past"),i}function ju(t,e,n){let r=[];for(let o=0;o<=e;o++)n(o)||r.push(`${t}: input ${o} frame(s) into the window was refused \u2014 grace window is shorter than the specced ${e}`);return n(e+1)&&r.push(`${t}: input ${e+1} frame(s) in (past the window) was still accepted \u2014 grace window is longer than specced (unfair leniency)`),Ot(r)}function Ei(t,e,n={}){let r=n.minChannels??2,[o,i]=n.shake??[0,1],[s,a]=n.hitstop??[0,12],l=[];for(let u of e){let c=t[u];if(!c){l.push(`event "${u}" has no feedback response \u2014 it happens silently`);continue}let m=new Set(c.channels).size;m<r&&l.push(`event "${u}" answers on ${m} channel(s) (${c.channels.join("+")||"none"}) \u2014 needs \u2265 ${r} (e.g. sfx + particles)`),c.shake!==void 0&&(c.shake<o||c.shake>i)&&l.push(`event "${u}" shake ${c.shake} is outside the [${o}, ${i}] envelope`),c.hitstopFrames!==void 0&&(c.hitstopFrames<s||c.hitstopFrames>a)&&l.push(`event "${u}" hit-stop ${c.hitstopFrames}f is outside the [${s}, ${a}]f envelope`)}return Ot(l)}function Bt(t){let e=t.replace("#","");e.length===3&&(e=e.split("").map(o=>o+o).join(""));let n=parseInt(e,16),r=o=>{let i=o/255;return i<=.03928?i/12.92:Re((i+.055)/1.055,2.4)};return .2126*r(n>>16&255)+.7152*r(n>>8&255)+.0722*r(n&255)}function mt(t,e){let n=Bt(t),r=Bt(e),o=Math.max(n,r),i=Math.min(n,r);return(o+.05)/(i+.05)}var Hu=t=>t.kind==="text"?void 0:t.fill;function Fi(t,e,n,r={}){let o=r.minBackgroundContrast??3,i=r.minSalienceFactor??1.15,s=[],a=mt(e,n);a<o&&s.push(`avatar (${e}) contrast vs background is ${a.toFixed(2)}:1 (needs \u2265 ${o}:1) \u2014 it sinks into the ground`);let l=[];for(let u of t){let c=Hu(u);c&&c!=="none"&&c!==e&&l.push(mt(c,n))}if(l.length){l.sort((c,m)=>c-m);let u=l[Math.floor(l.length/2)];a<u*i&&s.push(`avatar (${e}, ${a.toFixed(2)}:1) does not pop from the scenery (median ${u.toFixed(2)}:1) \u2014 it needs \u2265 ${i}\xD7 the median contrast`)}return Ot(s)}function _u(t,e,n="threat"){let r=[],o=0;for(let i=0;i<t.length;i++){let s=t[i];s.active&&(i===0||!t[i-1].active)&&o<e&&r.push(`${n}: hitbox went live at frame ${i} after only ${o} telegraph frame(s) \u2014 needs \u2265 ${e} of wind-up`),o=s.active?0:s.telegraphing?o+1:0}return Ot(r)}function Ni(t,e={}){let n=e.dt??.016666666666666666,r=e.maxSpeed??1800,o=e.maxAccel??9e4;if(t.length<3)return[];let i=[],s=[];for(let a=1;a<t.length;a++){let l=t[a].x-t[a-1].x,u=t[a].y-t[a-1].y,c=Q(l,u)/n;s.push(c),c>r&&i.push(`camera snapped at frame ${a}: ${Math.round(c)}px/s exceeds the ${r}px/s ceiling`)}for(let a=1;a<s.length;a++){let l=Math.abs(s[a]-s[a-1])/n;l>o&&i.push(`camera jerked at frame ${a+1}: ${Math.round(l)}px/s\xB2 exceeds the ${o}px/s\xB2 ceiling`)}return Ot(i)}function $i(t,e,n=0){if(t.length<2||t.length!==e.length)return[];let r=t[t.length-1].x-t[0].x,o=e[e.length-1].x-e[0].x,i=t[t.length-1].y-t[0].y,s=e[e.length-1].y-e[0].y,a=[];return Math.abs(o)>n&&Math.sign(r)!==0&&Math.sign(r)!==Math.sign(o)&&a.push("camera drifts opposite the target on X \u2014 the view lags behind instead of leading"),Math.abs(s)>n&&Math.sign(i)!==0&&Math.sign(i)!==Math.sign(s)&&a.push("camera drifts opposite the target on Y \u2014 the view lags behind instead of leading"),a}function Ju(t,e={}){let n=[],r=[],o=t.background??e.background??"#ffffff";if(t.forgiveness&&n.push({gate:"forgiveness",issues:Ii(t.forgiveness)}),t.feedback&&n.push({gate:"feedback",issues:Ei(t.feedback.contract,t.feedback.events)}),t.avatarFill&&(e.commands?n.push({gate:"salience",issues:Fi(e.commands,t.avatarFill,o)}):r.push("salience (no rendered frame)")),t.scrolls)if(e.camSamples&&e.camSamples.length>=3){let i=Ni(e.camSamples,{dt:e.dt});e.targetSamples&&i.push(...$i(e.camSamples,e.targetSamples)),n.push({gate:"camera",issues:i})}else r.push("camera (no sampled positions)");return{ok:n.every(i=>i.issues.length===0),sections:n,skipped:r}}function Wi(t){let e=t.text.length*t.size*.56,n=t.size*1.25,r=t.transform.e+t.x,o=t.transform.f+t.y,i=t.align==="center"?r-e/2:t.align==="right"?r-e:r;return{cmd:t,x:i,y:o-t.size,w:e,h:n}}function $r(t){let e=t.transform.e,n=t.transform.f;switch(t.kind){case"rect":return{x:e+t.x,y:n+t.y,w:t.w,h:t.h};case"circle":return{x:e+t.cx-t.radius,y:n+t.cy-t.radius,w:t.radius*2,h:t.radius*2};case"poly":{let r=1/0,o=1/0,i=-1/0,s=-1/0;for(let a=0;a<t.points.length;a+=2)r=Math.min(r,t.points[a]),i=Math.max(i,t.points[a]),o=Math.min(o,t.points[a+1]),s=Math.max(s,t.points[a+1]);return{x:e+r,y:n+o,w:i-r,h:s-o}}default:return null}}var Ai=(t,e)=>t.x<e.x+e.w&&t.x+t.w>e.x&&t.y<e.y+e.h&&t.y+t.h>e.y,Li=(t,e,n=2)=>t.x-n<=e.x&&t.y-n<=e.y&&t.x+t.w+n>=e.x+e.w&&t.y+t.h+n>=e.y+e.h,Uu=t=>t.transient===!0,zi=t=>{let e=t.fill;if(!(!e||e==="none")&&!t.gradient)return e};function Ku(t,e={}){let n=e.backgroundZ??1,r=e.margin??0,o=e.background,i=e.minContrast??1.5,s=e.minTextContrast??4.5,a=[],l=e.includeTransient?t:t.filter(c=>!Uu(c)),u=[];for(let c of l)c.kind==="text"&&c.text.trim().length&&u.push(Wi(c));for(let c of u){let m=c.cmd.z??0,d={x:c.x-r,y:c.y-r,w:c.w+r*2,h:c.h+r*2},p=-1/0,h=o;for(let g of l){if(g.kind==="text")continue;let x=$r(g);if(!x||!Li(x,c))continue;let k=g.opacity===void 0||g.opacity>=.6,w=g.z??0;k&&w<=m&&w>=p&&(p=w,h=zi(g)??h),w>m&&(g.opacity===void 0||g.opacity>=.9)&&a.push(`text "${Gt(c.cmd.text)}" is hidden behind a ${g.kind} (z${w} > text z${m}) that fully covers it \u2014 give the text a higher z, or the shape a lower one`)}for(let g of l){if(g.kind==="text"||(g.z??0)<=n||(g.z??0)<=p||g.opacity!==void 0&&g.opacity<.25)continue;let x=$r(g);x&&Ai(d,x)&&!Li(x,c)&&a.push(`text "${Gt(c.cmd.text)}" collides with a ${g.kind} (z${g.z}) at ~(${Math.round(x.x)},${Math.round(x.y)}) \u2014 back it with a panel, or stay clear`)}if(o&&s>0){let g=c.cmd.fill;if(g&&g!=="none"&&(c.cmd.opacity===void 0||c.cmd.opacity>=.6)){let x=mt(g,h??o);x<s&&a.push(`text "${Gt(c.cmd.text)}" (${g}) contrast is ${x.toFixed(2)}:1 on its backing (needs \u2265 ${s}:1) \u2014 barely readable`)}}}if(o)for(let c of l){if(c.kind==="text"||(c.z??0)<=n||c.opacity!==void 0&&c.opacity<.6)continue;let m=zi(c);if(!m)continue;let d=mt(m,o);d<i&&a.push(`${c.kind} (${m}, z${c.z}) contrast is ${d.toFixed(2)}:1 vs background ${o} (needs \u2265 ${i}:1) \u2014 it vanishes into the ground`)}for(let c=0;c<u.length;c++)for(let m=c+1;m<u.length;m++)Ai(u[c],u[m])&&a.push(`texts "${Gt(u[c].cmd.text)}" and "${Gt(u[m].cmd.text)}" overlap`);return Bi(a)}var Gt=t=>t.length>28?t.slice(0,25)+"\u2026":t,Bi=t=>[...new Set(t)];function Oi(t){return t.startsWith("Digit")?[t.slice(5)]:t.startsWith("Key")?[t.slice(3).toLowerCase()]:t.startsWith("Arrow")?["arrow","\u2190","\u2192","\u2191","\u2193",t.slice(5).toLowerCase()]:t.startsWith("Shift")?["shift"]:t==="Space"?["space"]:t==="Enter"?["enter"]:t==="Period"?["."]:[t.toLowerCase()]}function Yu(t,e){let n=t.render().filter(i=>i.kind==="text").map(i=>i.text.toLowerCase()).join(" \xB7 "),r=[],o=i=>i.length?i.length<=2&&/^[a-z0-9.]+$/.test(i)?new RegExp(`(^|[^a-z0-9])${i.replace(".","\\.")}($|[^a-z0-9])`).test(n):n.includes(i):!1;for(let[i,s]of Object.entries(e)){if(i==="restart")continue;[i.toLowerCase().replace(/-\d+$/,""),...s.flatMap(Oi)].some(o)||r.push(i)}return Bi(r)}function Xu(t,e){let n=[t.probe()];for(let r of e)t.step(r),n.push(t.probe());return n}function Qu(t,e){for(let n=0;n<t.length;n++)if(e(t[n]))return n;return-1}function Zu(t,e){return t.map(n=>n[e])}function ec(t,e){let n=[];for(let r=1;r<t.length;r++)t[r][e]!==t[r-1][e]&&n.push(r);return n}function tc(t,e,n=0){for(let r=1;r<t.length;r++)if(e==="up"?t[r]<t[r-1]-n:t[r]>t[r-1]+n)return!1;return!0}function nc(t){return t.length===0?0:t.filter(e=>e.length>0).length/t.length}function rc(t,e){let n=[0,...t,e],r=0;for(let o=1;o<n.length;o++)r=Math.max(r,n[o]-n[o-1]);return r}var oc=t=>[...new Set(t)];function Gi(t){let e=t.length;if(e===0)return{count:0,min:0,max:0,mean:0,distinct:0,maxJump:0,forwardFraction:1};let n=t[0],r=t[0],o=0,i=0,s=0;for(let a=0;a<e;a++){let l=t[a];if(l<n&&(n=l),l>r&&(r=l),o+=l,a>0){let u=l-t[a-1];u>i&&(i=u),u>=0&&s++}}return{count:e,min:n,max:r,mean:o/e,distinct:new Set(t).size,maxJump:i,forwardFraction:e>1?s/(e-1):1}}function Vi(t,e={}){let n=e.maxJumpFactor??3,r=e.minJumpAllowance??2,o=e.minForwardFraction??.6,i=e.minDistinct??3,s=e.finaleFraction??.8,a=[],l=t.length;if(l<2)return a.push(`ramp has ${l} level(s) \u2014 need at least 2 to form a curve`),a;let u=Gi(t);t[l-1]<t[0]&&a.push(`curve descends overall: finale (${t[l-1]}) is easier than the opener (${t[0]}) \u2014 the game gets EASIER`),u.max>0&&t[l-1]<u.max*s&&a.push(`finale (${t[l-1]}) is well below the peak (${u.max}) \u2014 the hardest level is buried mid-campaign, so it ends on an anticlimax`);let c=0,m=0;for(let h=1;h<l;h++){let g=t[h]-t[h-1];g>0&&(c+=g,m++)}let d=m>0?c/m:0,p=Math.max(r,d*n);for(let h=1;h<l;h++){let g=t[h]-t[h-1];g>p&&a.push(`difficulty cliff at level ${h+1}: jumps ${t[h-1]}\u2192${t[h]} (+${g}), past the +${p.toFixed(1)} envelope \u2014 smooth it with an intermediate level`)}return u.forwardFraction<o&&a.push(`only ${(u.forwardFraction*100).toFixed(0)}% of steps make progress (need \u2265 ${(o*100).toFixed(0)}%) \u2014 the curve wanders/descends instead of building`),u.distinct<i&&a.push(`only ${u.distinct} distinct difficulty value(s) across ${l} levels (need \u2265 ${i}) \u2014 the curve is flat; levels don't actually differ in challenge`),oc(a)}function ic(t,e={}){let n=Vi(t,e);if(n.length)throw new Error(`hayao: difficulty ramp is ill-shaped \u2014 ${n[0]}`)}function sc(t,e,n){let r=Math.max(2,n.panels??12),o=Math.max(1,Math.ceil(e.length/(r-1))),i=[{frame:0,inner:qe(t.render(),"p0")}];for(let w=0;w<e.length;w++)t.step(e[w]),((w+1)%o===0||w===e.length-1)&&i.push({frame:w+1,inner:qe(t.render(),`p${i.length}`)});let s=Math.max(1,n.cols??4),a=n.panelWidth??320,l=Math.round(a*n.height/n.width),u=18,c=8,m=a+c,d=l+u+c,p=Math.ceil(i.length/s),h=s*m+c,g=p*d+c,x=n.background??"#ffffff",k=i.map((w,P)=>{let $=c+P%s*m,v=c+Math.floor(P/s)*d;return`<g transform="translate(${$} ${v})"><svg width="${a}" height="${l}" viewBox="0 0 ${n.width} ${n.height}"><rect x="0" y="0" width="${n.width}" height="${n.height}" fill="${x}"/>`+w.inner+`</svg><rect x="0" y="0" width="${a}" height="${l}" fill="none" stroke="#999" stroke-width="1"/><text x="${a/2}" y="${l+13}" font-size="11" font-family="monospace" text-anchor="middle" fill="#555">f ${w.frame} \xB7 ${(w.frame/60).toFixed(1)}s</text></g>`}).join("");return`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${h} ${g}" width="${h}" height="${g}"><rect x="0" y="0" width="${h}" height="${g}" fill="#f4f4f2"/>`+k+"</svg>"}function Ar(t){let e=t.left.length,n=new Float32Array(e);for(let r=0;r<e;r++)n[r]=(t.left[r]+t.right[r])*.5;return n}function qi(t,e,n,r,o){let i=Math.max(1,Math.floor(t.length/e)),s=`M0 ${o}`,a="";for(let l=0;l<e;l++){let u=0,c=0,m=l*i;for(let p=0;p<i&&m+p<t.length;p++){let h=t[m+p];h>c&&(c=h),h<u&&(u=h)}let d=l/e*n;s+=` L${d.toFixed(1)} ${(o-c*(r/2)).toFixed(1)}`,a=` L${d.toFixed(1)} ${(o-u*(r/2)).toFixed(1)}`+a}return s+a+" Z"}function ac(t,e={}){let n=e.width??900,r=e.timeBins??220,o=e.freqBands??64,i=16,s=n-i*2,a=70,l=200,u=84,c=i*5+a*2+l+u,m=ct(Ar(t)),d=qi(t.left,r,s,a,a/2),p=qi(t.right,r,s,a,a/2),h=Ar(t),g=2048,x=Math.max(1,Math.floor(h.length/r)),k=s/r,w=l/o,P="";for(let S=0;S<r;S++){let D=S*x;if(D+64>=h.length)break;let C=ut(h.subarray(D,Math.min(D+g,h.length)));if(C.length===0)continue;let y=Math.max(1,Math.floor(C.length/o));for(let T=0;T<o;T++){let E=0;for(let Z=0;Z<y;Z++)E+=C[T*y+Z]??0;let O=E>1e-6?20*ht(E):-120,F=Math.max(0,Math.min(1,(O+60)/60));if(F<.03)continue;let J=i+S*k,Y=i*3+a*2+l-(T+1)*w,ne=lc(F);P+=`<rect x="${J.toFixed(1)}" y="${Y.toFixed(1)}" width="${(k+.6).toFixed(1)}" height="${(w+.6).toFixed(1)}" fill="${ne}"/>`}}let $=uc(m).map((S,D)=>`<text x="${i+4}" y="${c-u+20+D*18}" font-family="monospace" font-size="12" fill="#e8e4d8">${S}</text>`).join(""),v=i,f=i*2+a,M=(S,D)=>`<text x="${i}" y="${D-3}" font-family="monospace" font-size="10" fill="#8a8474">${S}</text>`;return`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${n} ${c}" width="${n}" height="${c}"><rect width="${n}" height="${c}" fill="#1a1814"/>`+(e.title?`<text x="${i}" y="${i-3}" font-family="monospace" font-size="12" fill="#d8b25a">${cc(e.title)}</text>`:"")+M("L",v)+`<g transform="translate(${i} ${v})"><rect width="${s}" height="${a}" fill="#211e18"/><path d="${d}" fill="#5a9ac4" opacity="0.9"/></g>`+M("R",f)+`<g transform="translate(${i} ${f})"><rect width="${s}" height="${a}" fill="#211e18"/><path d="${p}" fill="#5ac48f" opacity="0.9"/></g><rect x="${i}" y="${i*3+a*2}" width="${s}" height="${l}" fill="#0d0c0a"/>`+P+`<rect x="${i}" y="${c-u}" width="${s}" height="${u-i}" fill="#211e18"/>`+$+"</svg>"}function lc(t){let e=Math.round(40+t*200),n=Math.round(20+t*t*150),r=Math.round(30+t*40);return`rgb(${e},${n},${r})`}function uc(t){return[`dur ${t.durationSec.toFixed(2)}s peak ${t.peakDb.toFixed(1)} dBFS rms ${t.rms.toFixed(3)}`,`centroid ${Math.round(t.centroidHz)} Hz zcr ${Math.round(t.zcr)}/s`,`tempo ~${Math.round(t.tempoBpm)} bpm onsets ${t.onsetDensity.toFixed(1)}/s`]}function cc(t){return t.replace(/[<>&]/g,e=>e==="<"?"<":e===">"?">":"&")}function mc(t,e){let n=ct(Ar(t)),r=[],o=(i,s)=>{i||r.push(s)};if(e.minDurationSec!==void 0&&o(n.durationSec>=e.minDurationSec,`duration ${n.durationSec.toFixed(2)}s < min ${e.minDurationSec}`),e.maxDurationSec!==void 0&&o(n.durationSec<=e.maxDurationSec,`duration ${n.durationSec.toFixed(2)}s > max ${e.maxDurationSec}`),e.maxPeakDb!==void 0&&o(n.peakDb<=e.maxPeakDb,`peak ${n.peakDb.toFixed(1)}dB > max ${e.maxPeakDb}`),e.minRms!==void 0&&o(n.rms>=e.minRms,`rms ${n.rms.toFixed(3)} < min ${e.minRms} (too quiet?)`),e.minCentroidHz!==void 0&&o(n.centroidHz>=e.minCentroidHz,`centroid ${Math.round(n.centroidHz)}Hz < min ${e.minCentroidHz}`),e.maxCentroidHz!==void 0&&o(n.centroidHz<=e.maxCentroidHz,`centroid ${Math.round(n.centroidHz)}Hz > max ${e.maxCentroidHz}`),e.tempoBpm!==void 0){let i=e.tempoToleranceBpm??12;o(Math.abs(n.tempoBpm-e.tempoBpm)<=i,`tempo ${Math.round(n.tempoBpm)}bpm not within ${i} of ${e.tempoBpm}`)}return{ok:r.length===0,failures:r,features:n}}var Vt=class{rng;clock;input=new Mt;events=new gt;resources=new Map;state={};width;height;root;activeCamera=null;seed;freeQueue=[];started=!1;tuningValues;constructor(e={}){this.seed=e.seed??1,this.rng=new ue(this.seed),this.clock=new bt(e.clock),this.width=e.width??1280,this.height=e.height??720,this.tuningValues={...e.tuning??{}},this.root=new q({name:"root"})}tune(e){let n=this.tuningValues[e];if(n===void 0)throw new Error(`tune('${e}'): no such knob declared in the game's tuning spec`);return n}get time(){return this.clock.simTimeSec}get frame(){return this.clock.frame}setRoot(e){this.root&&this.root.exitTree(),this.root=e,this.started=!1}requestFree(e){this.freeQueue.push(e)}ensureStarted(){this.started||(this.root.enterTree(this),this.started=!0)}step(e=[]){this.ensureStarted(),this.input.beginFrame(e),this.root.updateTree(this.clock.dt),this.flushFree(),this.clock.tick()}advance(e,n=[]){let r=this.clock.advance(e);for(let o=0;o<r;o++)this.step(n);return r}runSteps(e,n){for(let r=0;r<e;r++)this.step(n?n(r):[])}flushFree(){if(this.freeQueue.length===0)return;let e=this.freeQueue;this.freeQueue=[];for(let n of e)n.exitTree(),n.parent?.removeChild(n),this.activeCamera===n&&(this.activeCamera=null)}viewTransform(){if(!this.activeCamera)return le;let e=this.activeCamera,n=e.worldTransform();return Ze(ft({x:this.width/2,y:this.height/2},0,{x:e.zoom,y:e.zoom}),Zt(n))}worldToScreen(e){return Qt(this.viewTransform(),e)}screenToWorld(e){return Qt(Zt(this.viewTransform()),e)}render(){this.ensureStarted();let e=[];return this.root.collectDraw(e,this.viewTransform()),e}hash(){return yt({seed:this.seed,rng:this.rng.getState(),clock:this.clock.getState(),input:this.input.getState(),state:this.state,tree:this.root.serialize(),...Object.keys(this.tuningValues).length>0?{tuning:this.tuningValues}:{}})}snapshot(){return{seed:this.seed,rng:this.rng.getState(),clock:this.clock.getState(),input:this.input.getState(),state:structuredClone(this.state),tree:this.root.serialize(),tuning:{...this.tuningValues}}}restore(e){this.seed=e.seed,this.rng.setState(e.rng),this.clock.setState(e.clock),this.input.setState(e.input),this.state=structuredClone(e.state),e.tuning&&(this.tuningValues={...e.tuning}),En(1e6),this.setRoot(en(e.tree)),this.ensureStarted()}probe(){return{frame:this.frame,time:this.time,hash:this.hash(),nodes:this.root.query("Sprite").length+this.root.query("Text").length}}};var dc={num(t,e){return{key:t,type:"number",...e}},color(t,e){return{key:t,type:"color",cosmetic:!0,...e}},enumOf(t,e){return{key:t,type:"enum",...e}}};function qt(t,e){let n={};if(!t)return n;for(let r of t.knobs){n[r.key]=r.default;let o=e?.[r.key];if(o!==void 0)if(r.type==="number"){let i=typeof o=="number"?o:Number(o);if(!Number.isFinite(i))continue;let s=r.min??-1/0,a=r.max??1/0;n[r.key]=Math.min(a,Math.max(s,i))}else r.type==="enum"?typeof o=="string"&&(r.options??[]).includes(o)&&(n[r.key]=o):typeof o=="string"&&(n[r.key]=o)}return n}function pc(t){return{width:1280,height:720,seed:1,background:"#f3ecdb",inputMap:tn,...t}}function Me(t,e){let n=typeof e=="number"?{seed:e}:e??{},r=new Vt({seed:n.seed??t.seed??1,width:t.width??1280,height:t.height??720,clock:t.clock,tuning:qt(t.tuning,n.tuning)});return r.setRoot(t.build(r)),t.probe&&(r.probe=()=>t.probe(r)),r}function hc(t){return t.inputMap??tn}function fc(t,e){let n=Me(t),r=e?.frames??[];for(let o of r)n.step(o);return{world:n,hash:n.hash(),steps:r.length}}function Lr(t,e,n){let r=typeof n=="number"?{toFrame:n}:n??{},o=Me(t,{seed:e.seed,tuning:e.tuningValues});e.startSnapshot&&(o.restore(structuredClone(e.startSnapshot)),t.attach?.(o)),r.onWorld?.(o);let i=Math.min(r.toFrame??e.inputLog.frames.length,e.inputLog.frames.length),s=0,a=0,l={...e.tuningValues};for(let u=0;u<i;u++){for(;a<e.knobEvents.length&&e.knobEvents[a].frame===u;){let c=e.knobEvents[a++];l[c.key]=c.value;let m=o.snapshot();m.tuning={...l},o.restore(m),t.attach?.(o)}for(;s<e.axesLog.length&&e.axesLog[s][0]===u;){let[,c,m]=e.axesLog[s++];o.input.axes.set(c,m)}o.step(e.inputLog.frames[u]),r.onFrame?.(o,u)}return o}function ji(t){let{frame:e,time:n,hash:r,...o}=t;return JSON.stringify(o)}function bc(t){let e=t.px??t.x,n=t.py??t.y;return typeof e=="number"&&typeof n=="number"?{x:e,y:n}:null}function gc(t){let e=[],n=null;for(let o of t.wallClockMarks)o.kind==="visibility-hidden"&&n===null&&(n=o.frame),o.kind==="visibility-visible"&&n!==null&&(e.push([n,o.frame]),n=null);n!==null&&e.push([n,t.inputLog.frames.length]);let r=null;for(let o of t.screenEvents)(o.kind==="overlay-show"||o.kind==="pause")&&r===null&&(r=o.frame),(o.kind==="overlay-hide"||o.kind==="resume")&&r!==null&&(e.push([r,o.frame]),r=null);return e}var yc=(t,e)=>e.some(([n,r])=>t>=n&&t<r);function xc(t,e,n={}){let r=n.hesitationFrames??45,o=n.futileWindow??30,i=n.quitWindow??300,s=n.clusterPx??64,a=e.inputLog.frames,l=gc(e),u=new Set(e.axesLog.map(([y])=>y)),c=[],m=null;for(let y=0;y<=a.length;y++){let T=y<a.length&&a[y].length===0&&!u.has(y);if(T&&m===null&&(m=y),!T&&m!==null){let E=y-m;E>=r&&!yc(m,l)&&c.push({startFrame:m,frames:E}),m=null}}let d=new Map;for(let y=0;y<a.length;y++){let T=y>0?a[y-1]:[];for(let E of a[y])T.includes(E)||(d.has(E)||d.set(E,[]),d.get(E).push(y))}let h=Object.keys(t.inputMap??{}).filter(y=>!d.has(y)),g=new Set;for(let y of c)g.add(y.startFrame);for(let y of e.annotations)g.add(Math.max(0,Math.min(y.frame,a.length-1)));for(let[,y]of d)for(let T of y)g.add(Math.max(0,T-1)),g.add(Math.min(a.length-1,T+o));a.length>0&&g.add(a.length-1);let x=new Map,k=[],w=!1,P=-1,$=Lr(t,e,{onWorld:y=>{y.events.on("death",()=>k.push({frame:P+1,pos:bc(y.probe())})),y.events.on("goal",()=>w=!0)},onFrame:(y,T)=>{P=T,g.has(T)&&x.set(T,y.probe())}}),v=a.length>0?x.get(a.length-1)??$.probe():$.probe();v.won===!0&&(w=!0);let f=c.map(y=>({...y,probe:x.get(y.startFrame)??{}})),M=new Map;for(let y of k){let T=y.pos?`${Math.round(y.pos.x/s)}:${Math.round(y.pos.y/s)}`:"unknown",E=M.get(T)??{x:y.pos?.x??0,y:y.pos?.y??0,count:0,frames:[]};E.count++,E.frames.push(y.frame),M.set(T,E)}let S=[];for(let[y,T]of d){let E=[];for(let O of T){let F=x.get(Math.max(0,O-1)),J=x.get(Math.min(a.length-1,O+o));F&&J&&ji(F)===ji(J)&&E.push(O)}E.length>0&&S.push({action:y,futilePresses:E.length,totalPresses:T.length,frames:E})}let D=e.annotations.map(y=>{let T=Math.max(0,Math.min(y.frame,a.length-1));return{frame:y.frame,tag:y.tag,...y.note!==void 0?{note:y.note}:{},probe:x.get(T)??{}}}),C={sessionId:e.id,game:e.game,buildRef:e.buildRef,seed:e.seed,variant:e.variant,frames:a.length,simSeconds:$.time,reachedGoal:w,deaths:k.length,hesitations:f,deathClusters:[...M.values()].sort((y,T)=>T.count-y.count),futileVerbs:S.sort((y,T)=>T.futilePresses-y.futilePresses),annotations:D,knobEvents:e.knobEvents,unusedActions:h};if(!w&&a.length>0){let y=Math.max(0,a.length-i);C.quit={frame:a.length-1,probe:v,recentDeaths:k.filter(T=>T.frame>=y).length,recentHesitations:f.filter(T=>T.startFrame>=y).length,endReason:e.endReason}}return C}var zr=class{constructor(e,n,r,o){this.states=e;this.transitions=n;this.ctx=o;this.current=r,this.states[r]?.onEnter?.(o)}states;transitions;ctx;current;update(e){for(let n of this.transitions)if((n.from==="*"||n.from===this.current)&&n.when(this.ctx)){this.go(n.to);break}this.states[this.current]?.onUpdate?.(this.ctx,e)}go(e){e!==this.current&&(this.states[this.current]?.onLeave?.(this.ctx),this.current=e,this.states[e]?.onEnter?.(this.ctx))}is(...e){return e.includes(this.current)}getState(){return this.current}setState(e){this.current=e}},Wr=class{constructor(e,n){this.defs=e;if(!e[n])throw new Error(`hayao: PhaseClock has no phase '${n}'`);this.phase=n}defs;phase;elapsed=0;get duration(){return this.defs[this.phase]?.duration??0}progress(e=n=>n){let n=this.duration,r=n>0?this.elapsed/n:1;return e(r<0?0:r>1?1:r)}get done(){return this.elapsed>=this.duration}update(e){this.elapsed+=e;let n=!1,r=0;for(;this.elapsed>=this.duration&&this.defs[this.phase]?.next!==void 0&&r++<1024;){let o=this.elapsed-this.duration;this.phase=this.defs[this.phase].next,this.elapsed=o,n=!0}return n}to(e){if(!this.defs[e])throw new Error(`hayao: PhaseClock has no phase '${e}'`);this.phase=e,this.elapsed=0}getState(){return{phase:this.phase,elapsed:this.elapsed}}setState(e){this.phase=e.phase,this.elapsed=e.elapsed}};function vc(t){let e=0;for(let n of t)e+=n>0?n:0;return e}function Or(t,e){let n=vc(e);if(n<=0)throw new Error("hayao: weightedIndex needs at least one positive weight");let r=t.float()*n;for(let o=0;o<e.length;o++){let i=e[o]>0?e[o]:0;if(r<i)return o;r-=i}for(let o=e.length-1;o>=0;o--)if(e[o]>0)return o;return e.length-1}function wc(t,e,n){if(e.length!==n.length)throw new Error("hayao: weightedPick items/weights length mismatch");return e[Or(t,n)]}function Gr(t,e){return e[Or(t,e.map(n=>n.weight))].value}var Br=class{values;cumulative;total;constructor(e){if(e.length===0)throw new Error("hayao: LootTable needs at least one entry");let n=[],r=[],o=0;for(let i of e)o+=i.weight>0?i.weight:0,n.push(i.value),r.push(o);if(o<=0)throw new Error("hayao: LootTable needs at least one positive weight");this.values=n,this.cumulative=r,this.total=o}roll(e){let n=e.float()*this.total;for(let r=0;r<this.cumulative.length;r++)if(n<this.cumulative[r])return this.values[r];return this.values[this.values.length-1]}rollMany(e,n){let r=[];for(let o=0;o<n;o++)r.push(this.roll(e));return r}};function Hi(t,e,n,r={}){let o=r.maxNodes??1e6,i=[],s=new Map,a=new Map,l=n(t);a.set(l,0);let u=[t];if(i.push(t),r.goal?.(t))return{order:i,cameFrom:s,dist:a};let c=0;for(;u.length>0&&c<o;){let m=[];for(let d of u){let p=a.get(n(d))??0;for(let h of e(d)){let g=n(h);if(!a.has(g)){if(a.set(g,p+1),s.set(g,d),i.push(h),c++,r.goal?.(h))return{order:i,cameFrom:s,dist:a};m.push(h)}}}u=m}return{order:i,cameFrom:s,dist:a}}function kc(t,e,n,r){let o=[r],i=r,s=e(n);for(;e(i)!==s;){let a=t.get(e(i));if(a===void 0)return[];i=a,o.push(i)}return o.reverse(),o}function _i(t,e,n,r,o={}){let i=o.heuristic??(()=>0),s=o.maxNodes??1e6,a=new Map,l=new Map,u=new Vr,c=r(t);l.set(c,0),u.push(t,i(t));let m=0;for(;u.size>0&&m<s;){let{item:d,priority:p}=u.pop(),h=r(d),g=l.get(h)??1/0;if(!(p>g+i(d)+1e-9)){if(e(d))return{path:Sc(a,r,d),cost:g};m++;for(let x of n(d)){let k=r(x.node),w=g+x.cost;w<(l.get(k)??1/0)&&(l.set(k,w),a.set(k,d),u.push(x.node,w+i(x.node)))}}}return null}function Sc(t,e,n){let r=[n],o=n,i=t.get(e(o));for(;i!==void 0;)o=i,r.push(o),i=t.get(e(o));return r.reverse(),r}var Vr=class{items=[];prio=[];seq=[];counter=0;get size(){return this.items.length}push(e,n){this.items.push(e),this.prio.push(n),this.seq.push(this.counter++),this.bubbleUp(this.items.length-1)}pop(){let e=this.items[0],n=this.prio[0],r=this.items.length-1;return this.swap(0,r),this.items.pop(),this.prio.pop(),this.seq.pop(),this.items.length>0&&this.bubbleDown(0),{item:e,priority:n}}less(e,n){return this.prio[e]<this.prio[n]||this.prio[e]===this.prio[n]&&this.seq[e]<this.seq[n]}bubbleUp(e){for(;e>0;){let n=e-1>>1;if(!this.less(e,n))break;this.swap(e,n),e=n}}bubbleDown(e){let n=this.items.length;for(;;){let r=2*e+1,o=2*e+2,i=e;if(r<n&&this.less(r,i)&&(i=r),o<n&&this.less(o,i)&&(i=o),i===e)break;this.swap(e,i),e=i}}swap(e,n){[this.items[e],this.items[n]]=[this.items[n],this.items[e]],[this.prio[e],this.prio[n]]=[this.prio[n],this.prio[e]],[this.seq[e],this.seq[n]]=[this.seq[n],this.seq[e]]}},jt=[{x:0,y:-1},{x:1,y:0},{x:0,y:1},{x:-1,y:0}],gn=[...jt,{x:1,y:-1},{x:1,y:1},{x:-1,y:1},{x:-1,y:-1}],Ji=t=>`${t.x},${t.y}`;function Mc(t,e,n,r){let o=r?gn:jt;return i=>{let s=[];for(let a of o){let l=i.x+a.x,u=i.y+a.y;l<0||u<0||l>=e||u>=n||t(l,u)&&s.push({x:l,y:u})}return s}}function qr(t,e,n){if(!e(t.x,t.y))return[];let r=Mc(e,n.cols,n.rows,n.diagonal??!1);return Hi(t,r,Ji).order}function Cc(t,e,n,r=!1){let o=new Array(t*e).fill(-1),i=[],s=r?gn:jt;for(let a=0;a<e;a++)for(let l=0;l<t;l++){if(o[a*t+l]!==-1||!n(l,a))continue;let u=i.length,c=[],m=[{x:l,y:a}];for(o[a*t+l]=u;m.length>0;){let d=[];for(let p of m){c.push(p);for(let h of s){let g=p.x+h.x,x=p.y+h.y;if(g<0||x<0||g>=t||x>=e)continue;let k=x*t+g;o[k]!==-1||!n(g,x)||(o[k]=u,d.push({x:g,y:x}))}}m=d}i.push(c)}return{labels:o,cells:i}}function Tc(t,e,n,r){let o=r.diagonal??!1,i=o?gn:jt,s=r.cost??(()=>1),a=1.4142135623730951,l=m=>{let d=[];for(let p of i){let h=m.x+p.x,g=m.y+p.y;if(h<0||g<0||h>=r.cols||g>=r.rows||!n(h,g))continue;let x=p.x!==0&&p.y!==0;d.push({node:{x:h,y:g},cost:s(h,g)*(x?a:1)})}return d},u=m=>{let d=Math.abs(m.x-e.x),p=Math.abs(m.y-e.y);if(!o)return d+p;let h=Math.min(d,p);return d+p-(2-a)*h};if(!n(e.x,e.y))return null;let c=_i(t,m=>m.x===e.x&&m.y===e.y,l,Ji,{heuristic:u,maxNodes:r.maxNodes});return c?c.path:null}function Rc(t){return(e,n)=>fe(t,e,n)!==j.SOLID}function Pc(t){return structuredClone(t)}var jr=class{history=[];cursor=-1;limit;clone;constructor(e={}){this.limit=Math.max(1,e.limit??64),this.clone=e.clone??Pc}record(e){if(this.history.length=this.cursor+1,this.history.push(this.clone(e)),this.cursor=this.history.length-1,this.history.length>this.limit){let n=this.history.length-this.limit;this.history.splice(0,n),this.cursor-=n}}undo(){if(!(this.cursor<=0))return this.cursor--,this.clone(this.history[this.cursor])}redo(){if(!(this.cursor>=this.history.length-1))return this.cursor++,this.clone(this.history[this.cursor])}current(){return this.cursor>=0?this.clone(this.history[this.cursor]):void 0}get canUndo(){return this.cursor>0}get canRedo(){return this.cursor<this.history.length-1}get size(){return this.history.length}clear(){this.history.length=0,this.cursor=-1}},Hr=class{constructor(e){this.capacity=e;if(!Number.isInteger(e)||e<1)throw new Error("hayao: RingBuffer capacity must be a positive integer");this.buf=new Array(e)}capacity;buf;start=0;count=0;push(e){let n=(this.start+this.count)%this.capacity;this.buf[n]=e,this.count<this.capacity?this.count++:this.start=(this.start+1)%this.capacity}get length(){return this.count}get isFull(){return this.count===this.capacity}at(e){if(!(e<0||e>=this.count))return this.buf[(this.start+e)%this.capacity]}latest(){return this.at(this.count-1)}toArray(){let e=[];for(let n=0;n<this.count;n++)e.push(this.buf[(this.start+n)%this.capacity]);return e}clear(){this.start=0,this.count=0,this.buf.fill(void 0)}};var yn=class{map=new Map;get(e){return this.map.has(e)?this.map.get(e):null}set(e,n){this.map.set(e,n)}remove(e){this.map.delete(e)}keys(){return[...this.map.keys()]}},_r=class{get(e){return null}set(e,n){}remove(e){}keys(){return[]}},xn=class{constructor(e="hayao.save."){this.prefix=e}prefix;ls(){try{return typeof localStorage<"u"?localStorage:null}catch{return null}}get(e){try{return this.ls()?.getItem(this.prefix+e)??null}catch{return null}}set(e,n){try{this.ls()?.setItem(this.prefix+e,n)}catch{}}remove(e){try{this.ls()?.removeItem(this.prefix+e)}catch{}}keys(){let e=this.ls();if(!e)return[];let n=[];try{for(let r=0;r<e.length;r++){let o=e.key(r);o&&o.startsWith(this.prefix)&&n.push(o.slice(this.prefix.length))}}catch{}return n}};function Jr(t){try{if(typeof localStorage<"u"){let e="__hayao_probe__";return localStorage.setItem(e,"1"),localStorage.removeItem(e),new xn(t)}}catch{}return new yn}function Dc(t){let e="",n=0;for(;n<t.length;){let r=t[n],o=1;for(;n+o<t.length&&t[n+o]===r;)o++;o>=4||r==="~"?e+="~"+r+o.toString(36)+"~":e+=r.repeat(o),n+=o}return e}function Ic(t){let e="",n=0;for(;n<t.length;)if(t[n]==="~"){let r=t[n+1],o=t.indexOf("~",n+2);if(r===void 0||o<0)throw new Error("hayao: malformed RLE stream");let i=parseInt(t.slice(n+2,o),36);if(!Number.isFinite(i)||i<1)throw new Error("hayao: malformed RLE count");e+=r.repeat(i),n=o+1}else e+=t[n],n++;return e}var Ur="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",Ui={};for(let t=0;t<Ur.length;t++)Ui[Ur[t]]=t;function Ec(t){let e="";for(let n of t){if(!Number.isInteger(n)||n<0)throw new Error(`hayao: packVarints expects non-negative integers, got ${n}`);let r=n;do{let o=r&31;r=Math.floor(r/32),r>0&&(o|=32),e+=Ur[o]}while(r>0)}return e}function Fc(t){let e=[],n=0,r=1;for(let o of t){let i=Ui[o];if(i===void 0)throw new Error(`hayao: unpackVarints saw invalid char "${o}"`);n+=(i&31)*r,i&32?r*=32:(e.push(n),n=0,r=1)}if(r!==1)throw new Error("hayao: unpackVarints hit a truncated stream");return e}var Xr=1;function Ki(t){return JSON.stringify({v:Xr,snap:t})}function Kr(t){if(!t)return null;let e;try{e=JSON.parse(t)}catch{return null}if(!e||typeof e!="object")return null;let n=e;if(n.v!==Xr||!n.snap||typeof n.snap!="object")return null;let r=n.snap;return typeof r.seed!="number"||!r.rng||!r.clock||!r.input||!r.state||!r.tree?null:r}var Yr=class{constructor(e,n=Jr()){this.world=e;this.storage=n}world;storage;save(e="auto"){this.storage.set(e,Ki(this.world.snapshot()))}load(e="auto"){let n=Kr(this.storage.get(e));return n?(this.world.restore(n),!0):!1}has(e="auto"){return Kr(this.storage.get(e))!==null}delete(e="auto"){this.storage.remove(e)}slots(){return this.storage.keys()}};function Nc(t){return{next:t.map(e=>e.time)}}function $c(t,e,n,r){let o=[];for(let i=0;i<t.length;i++){let s=t[i],a=e.next[i]??s.time;for(;a<=n;){let l;if(typeof s.spawn=="string")l=s.spawn;else{if(!r)throw new Error("hayao: pollDirector needs an Rng to roll a weighted wave");l=Gr(r,s.spawn)}if(o.push({spawn:l,count:s.count??1,wave:i}),s.every&&s.every>0){if(a+=s.every,s.end!==void 0&&a>=s.end){a=1/0;break}}else{a=1/0;break}}e.next[i]=a}return o}function Ac(t,e){let n=new Map;for(let o of e)n.set(o,(n.get(o)??0)+1);let r=o=>(n.get(o)??0)>0;return t.filter(o=>(n.get(o.id)??0)>=(o.maxStacks??1)?!1:(o.requires??[]).every(r))}var Lc=new Set(["#","-","^","."," "]),Ht=t=>t===j.SOLID,zc=t=>t===j.HAZARD,Yi=(t,e,n)=>({x:(t+.5)*n,y:(e+.5)*n});function Wc(t){let e=t.tileSize??32,n=t.legend??{},r=t.rows,o=Math.max(0,...r.map(l=>l.length)),i=null,s=null,a=[];if(r.forEach((l,u)=>{for(let c=0;c<l.length;c++){let m=l[c];if(m==="S")i={x:c,y:u};else if(m==="G")s={x:c,y:u};else if(m in n){let d=Yi(c,u,e);a.push({kind:n[m],tx:c,ty:u,x:d.x,y:d.y})}}}),!i)throw new Error(`level "${t.name}": no spawn marker 'S'`);if(!s)throw new Error(`level "${t.name}": no goal marker 'G'`);return{name:t.name,tileSize:e,rows:r,legend:n,cols:o,rowCount:r.length,spawn:i,goal:s,entities:a}}function Bc(t){let e=[],n=vn(t),r=o=>n.tiles[o.y*n.cols+o.x]??j.EMPTY;return t.rows.forEach((o,i)=>{for(let s=0;s<o.length;s++){let a=o[s];a==="S"||a==="G"||Lc.has(a)||a in t.legend||e.push(`unknown glyph '${a}' at (${s},${i}) \u2014 add it to the legend or use terrain '#/-/^/.'`)}}),Ht(r(t.spawn))&&e.push(`spawn (${t.spawn.x},${t.spawn.y}) is inside a solid tile`),Ht(r(t.goal))&&e.push(`goal (${t.goal.x},${t.goal.y}) is inside a solid tile`),[...new Set(e)]}function vn(t){return jn(t.rows,t.tileSize)}function Oc(t,e={}){let n=vn(t),r=(l,u)=>n.tiles[u*n.cols+l]??j.EMPTY,o=e.passable??((l,u)=>!Ht(r(l,u))),i=qr(t.spawn,o,{cols:n.cols,rows:n.rows,diagonal:e.diagonal}),s=new Set(i.map(l=>`${l.x},${l.y}`)),a=[];s.has(`${t.goal.x},${t.goal.y}`)||a.push("goal");for(let l of t.entities)s.has(`${l.tx},${l.ty}`)||a.push(`entity@${l.tx},${l.ty}`);return{ok:a.length===0,unreachable:a,reached:i.length}}function Gc(t,e){let n=vn(t),{cols:r,rows:o}=n,i=(w,P)=>w<0||P<0||w>=r||P>=o?j.SOLID:n.tiles[P*r+w],s=(w,P)=>{let $=i(w,P+1);return $===j.SOLID||$===j.ONEWAY},a=(w,P)=>!Ht(i(w,P))&&!zc(i(w,P))&&s(w,P),u=(w=>{for(let P=w.y;P<o;P++)if(a(w.x,P))return{x:w.x,y:P};return null})(t.spawn);if(!u)return{ok:!1,unreachable:["goal"],reached:0};let c=(w,P)=>Math.abs(P.x-w.x)<=e.runTiles&&w.y-P.y<=e.jumpTiles,m=[];for(let w=0;w<o;w++)for(let P=0;P<r;P++)a(P,w)&&m.push({x:P,y:w});let d=w=>`${w.x},${w.y}`,p=new Set([d(u)]),h=[u];for(;h.length;){let w=h.shift();for(let P of m){let $=d(P);!p.has($)&&c(w,P)&&(p.add($),h.push(P))}}let g=[...p].map(w=>{let[P,$]=w.split(",").map(Number);return{x:P,y:$}}),k=!Ht(i(t.goal.x,t.goal.y))&&(p.has(d(t.goal))||g.some(w=>c(w,t.goal)))?[]:["goal"];return{ok:k.length===0,unreachable:k,reached:p.size}}function Vc(t,e){let n=[],r=Math.max(t.rowCount,e.rowCount),o=Math.max(t.cols,e.cols),i=(u,c,m)=>u.rows[m]?.[c]??" ";for(let u=0;u<r;u++)for(let c=0;c<o;c++){let m=i(t,c,u),d=i(e,c,u);m!==d&&n.push({kind:"tile",detail:`(${c},${u}) '${m}' \u2192 '${d}'`})}let s=u=>`${u.kind}@${u.tx},${u.ty}`,a=new Set(t.entities.map(s)),l=new Set(e.entities.map(s));for(let u of e.entities)a.has(s(u))||n.push({kind:"entity+",detail:s(u)});for(let u of t.entities)l.has(s(u))||n.push({kind:"entity-",detail:s(u)});return(t.spawn.x!==e.spawn.x||t.spawn.y!==e.spawn.y)&&n.push({kind:"spawn",detail:`(${t.spawn.x},${t.spawn.y}) \u2192 (${e.spawn.x},${e.spawn.y})`}),(t.goal.x!==e.goal.x||t.goal.y!==e.goal.y)&&n.push({kind:"goal",detail:`(${t.goal.x},${t.goal.y}) \u2192 (${e.goal.x},${e.goal.y})`}),n}function Xi(t,e){return In(`hayao/gen:${t>>>0}:${e}`)}var qc=(t,e,n)=>(n.minDepth===void 0||t>=n.minDepth)&&(n.maxDepth===void 0||t<=n.maxDepth)&&(n.minNodes===void 0||e>=n.minNodes)&&(n.maxNodes===void 0||e<=n.maxNodes);function Qi(t,e){let n=e.seed??1,r=e.maxAttempts??e.count*60,o=e.dedupeKey??(u=>u.key(u.initial())),i=[],s=new Set,a=0,l=0;for(let u=0;u<r&&i.length<e.count;u++){a++;let c=Xi(n,u),m=t(new ue(c)),d=Ke(m,e.solve);if(!d.solvable||d.exhausted||d.depth===void 0)continue;l++;let p={path:d.path??[],depth:d.depth,nodes:d.nodes};if(!qc(p.depth,p.nodes,e))continue;let h=o(m,p);s.has(h)||e.reject?.(m,p,c)||(s.add(h),i.push({...p,index:0,seed:c,puzzle:m}))}return i.sort((u,c)=>u.depth-c.depth||u.nodes-c.nodes||u.seed-c.seed),i.forEach((u,c)=>u.index=c),{levels:i,attempts:a,solvable:l,complete:i.length>=e.count,seeds:i.map(u=>u.seed)}}function Qr(t,e){let n=Qi(t,e);if(!n.complete)throw new Error(`hayao: generator found only ${n.levels.length}/${e.count} in-band levels in ${n.attempts} attempts (${n.solvable} solvable). Widen the band [depth ${e.minDepth??0}..${e.maxDepth??"\u221E"}] or raise maxAttempts.`);return n.levels}function jc(t,e){return t(new ue(e))}function Hc(t){let e=t.seed??1,n=t.minutesPerLevel??1.5,r=[],o=[];return t.acts.forEach((i,s)=>{let a=i.factory??t.factory;if(!a)throw new Error(`hayao: act "${i.name}" has no factory and the campaign has no default`);let l=(e^(s+1)*2654435769)>>>0,u=Qr(a,{count:i.count,seed:l,minDepth:i.minDepth,maxDepth:i.maxDepth,minNodes:i.minNodes,maxNodes:i.maxNodes,solve:i.solve??t.solve,maxAttempts:i.maxAttempts}),c=r.length;u.forEach((m,d)=>{r.push({...m,index:r.length,act:s,actName:i.name,actIndex:d})}),o.push({name:i.name,from:c,to:r.length-1})}),{levels:r,acts:o,difficulty:r.map(i=>i.depth),seeds:r.map(i=>i.seed),estMinutes:r.length*n}}function es(t,e){let n=new Map(t.pickups.map(o=>[o.id,o.grants])),r=new Set;for(let o of e){let i=n.get(o);i&&r.add(i)}return r}function Zi(t,e){return(t.requires??[]).every(n=>e.has(n))}function ts(t,e,n){let r=[];for(let o of t.edges)o.from===e&&Zi(o,n)?r.push(o.to):!o.oneWay&&o.to===e&&Zi(o,n)&&r.push(o.from);return r}function wn(t,e="complete"){let n=o=>t.pickups.filter(i=>i.region===o),r=t.pickups.length;return{initial:()=>({region:t.start,taken:[]}),moves:o=>{let i=es(t,o.taken),s=[];for(let l of n(o.region))o.taken.includes(l.id)||s.push({kind:"take",pickup:l.id});let a=new Set;for(let l of ts(t,o.region,i))a.has(l)||(a.add(l),s.push({kind:"move",to:l}));return s},apply:(o,i)=>{if(i.kind==="move")return{region:i.to,taken:o.taken};let s=[...o.taken,i.pickup].sort();return{region:o.region,taken:s}},isWin:o=>o.region===t.goal&&(e==="complete"||o.taken.length===r),key:o=>`${o.region}|${o.taken.join(",")}`}}var ns={maxDepth:2e3,nodeCap:5e6};function _c(t){return Ke(wn(t,"complete"),ns)}function Jc(t){return Ke(wn(t,"full"),ns)}function rs(t,e){let n=new Set(e),r=new Set([t.start]),o=[t.start];for(;o.length;){let i=o.shift();for(let s of ts(t,i,n))r.has(s)||(r.add(s),o.push(s))}return[...r]}function Uc(t,e="complete"){let n=wn(t,e),r=n.initial(),o=n.key(r),i=new Map([[o,r]]),s=new Map,a=new Set,l=[r];for(n.isWin(r)&&a.add(o);l.length;){let p=l.shift(),h=n.key(p),g=[];for(let x of n.moves(p)){let k=n.apply(p,x),w=n.key(k);g.push(w),i.has(w)||(i.set(w,k),n.isWin(k)&&a.add(w),l.push(k))}s.set(h,g)}let u=new Map;for(let[p,h]of s)for(let g of h)(u.get(g)??u.set(g,[]).get(g)).push(p);let c=new Set(a),m=[...a];for(;m.length;){let p=m.shift();for(let h of u.get(p)??[])c.has(h)||(c.add(h),m.push(h))}let d=[...i.keys()].filter(p=>!c.has(p)).sort();return{ok:d.length===0,deadEnds:d,statesExplored:i.size}}function Kc(t){let e=[],n=new Set;for(let a of t.regions)n.has(a.id)&&e.push(`duplicate region id "${a.id}"`),n.add(a.id);let r=a=>n.has(a);r(t.start)||e.push(`start region "${t.start}" is not defined`),r(t.goal)||e.push(`goal region "${t.goal}" is not defined`);for(let a of t.edges)r(a.from)||e.push(`edge references unknown region "${a.from}"`),r(a.to)||e.push(`edge references unknown region "${a.to}"`);let o=new Set;for(let a of t.pickups)o.has(a.id)&&e.push(`duplicate pickup id "${a.id}"`),o.add(a.id),r(a.region)||e.push(`pickup "${a.id}" is in unknown region "${a.region}"`);let i=t.pickups.map(a=>a.grants),s=new Set(rs(t,i));for(let a of t.regions)s.has(a.id)||e.push(`region "${a.id}" is unreachable even with every ability`);return e}function Yc(t){let e=[];for(let n=1;n<=t;n++)e.push(`p${n}`);return e}var _t=(t,e)=>`${t}:${e}`;function dt(t,e){let n=[];for(let r of t){let o=e.get(r)??[];for(let i of o)n.push(_t(r,i))}return n.sort()}var kn=class{constructor(e,n){this.world=e;this.player=n}world;player;isDown(e){return this.world.input.isDown(_t(this.player,e))}justPressed(e){return this.world.input.justPressed(_t(this.player,e))}justReleased(e){return this.world.input.justReleased(_t(this.player,e))}},Xc=(t,e)=>new kn(t,e);var ff=1,Ye={mode:"lockstep",inputDelay:2,hashInterval:20,maxRollback:12,redundancy:3};function de(t){return JSON.stringify(t)}function $e(t){try{let e=JSON.parse(t);return!e||typeof e!="object"||e.v!==1||typeof e.t!="string"?null:e}catch{return null}}function pe(t){return{v:1,...t}}var Zr=class{peers=[];queue=[];tickCount=0;seq=0;sent=0;delay;dropEvery;constructor(e={}){this.delay=e.delay??0,this.dropEvery=e.dropEvery??0}connect(){let e=new Sn(this,this.peers.length);return this.peers.push(e),e}enqueue(e,n){this.sent++,!(this.dropEvery>0&&this.sent%this.dropEvery===0)&&this.queue.push({data:e,from:n,dueTick:this.tickCount+this.delay,seq:this.seq++})}tick(){let e=this.queue.filter(n=>n.dueTick<=this.tickCount).sort((n,r)=>n.seq-r.seq);this.queue=this.queue.filter(n=>n.dueTick>this.tickCount),this.tickCount++;for(let n of e)for(let r of this.peers)r.peerIndex!==n.from&&r.isOpen&&r.deliver(n.data)}flush(){for(;this.queue.length>0;)this.tick()}get pending(){return this.queue.length}},Sn=class{constructor(e,n){this.hub=e;this.peerIndex=n}hub;peerIndex;listeners=[];closeListeners=[];open=!0;send(e){this.open&&this.hub.enqueue(e,this.peerIndex)}onMessage(e){return this.listeners.push(e),()=>{this.listeners=this.listeners.filter(n=>n!==e)}}onClose(e){return this.closeListeners.push(e),()=>{this.closeListeners=this.closeListeners.filter(n=>n!==e)}}close(){if(this.open){this.open=!1;for(let e of this.closeListeners)e()}}get isOpen(){return this.open}deliver(e){for(let n of this.listeners)n(e)}},eo=class{channel;listeners=[];closeListeners=[];open=!0;constructor(e){this.channel=new BroadcastChannel(`hayao-net:${e}`),this.channel.onmessage=n=>{if(typeof n.data=="string")for(let r of this.listeners)r(n.data)}}send(e){this.open&&this.channel.postMessage(e)}onMessage(e){return this.listeners.push(e),()=>{this.listeners=this.listeners.filter(n=>n!==e)}}onClose(e){return this.closeListeners.push(e),()=>{this.closeListeners=this.closeListeners.filter(n=>n!==e)}}close(){if(this.open){this.open=!1,this.channel.close();for(let e of this.closeListeners)e()}}get isOpen(){return this.open}};function Qc(t){return new Promise((e,n)=>{let r=new WebSocket(t),o=[],i=[],s=!1,a={send(l){s&&r.send(l)},onMessage(l){return o.push(l),()=>{let u=o.indexOf(l);u>=0&&o.splice(u,1)}},onClose(l){return i.push(l),()=>{let u=i.indexOf(l);u>=0&&i.splice(u,1)}},close(){s=!1,r.close()},get isOpen(){return s}};r.onopen=()=>{s=!0,e(a)},r.onmessage=l=>{if(typeof l.data=="string")for(let u of o)u(l.data)},r.onclose=()=>{let l=s;if(s=!1,l)for(let u of i)u()},r.onerror=()=>{s||n(new Error(`hayao-net: could not connect to ${t}`))}})}var Xe=class{frames=new Map;contiguous=new Map;addPlayer(e){this.frames.has(e)||(this.frames.set(e,new Map),this.contiguous.set(e,-1))}removePlayer(e){this.frames.delete(e),this.contiguous.delete(e)}players(){return[...this.frames.keys()]}set(e,n,r){let o=this.frames.get(e);if(!o||o.has(n))return!1;o.set(n,[...r].sort());let i=this.contiguous.get(e)??-1;for(;o.has(i+1);)i++;return this.contiguous.set(e,i),!0}has(e,n){return this.frames.get(e)?.has(n)??!1}get(e,n){return this.frames.get(e)?.get(n)}latestAt(e,n){let r=this.frames.get(e);if(!r)return[];for(let o=n;o>=0;o--){let i=r.get(o);if(i)return i}return[]}contiguousThrough(e){return this.contiguous.get(e)??-1}confirmedFrame(){let e=1/0;for(let n of this.contiguous.values())e=Math.min(e,n);return e===1/0?-1:e}clearFrom(e,n){let r=this.frames.get(e);if(!r)return;for(let i of r.keys())i>=n&&r.delete(i);let o=this.contiguous.get(e)??-1;o>=n&&(o=n-1),this.contiguous.set(e,o)}prune(e){for(let n of this.frames.values())for(let r of n.keys())r<e&&n.delete(r)}};var De=class{world;localPlayer;config;startFrame;transport;buffer=new Xe;roster=[];mergedLog=[];localHashes=new Map;pendingRemoteHashes=[];sentThrough;stallCount=0;desynced=!1;afterStepListeners=[];unsubscribe;onDesync;onStall;constructor(e){this.world=e.world,this.transport=e.transport,this.localPlayer=e.localPlayer,this.config={...Ye,...e.config,mode:"lockstep"},this.startFrame=e.startFrame??0,this.onDesync=e.onDesync,this.onStall=e.onStall;for(let n of e.players)if(this.roster.push({player:n,from:this.startFrame,until:1/0}),this.buffer.addPlayer(n),this.startFrame===0||n===this.localPlayer)for(let r=this.startFrame;r<this.startFrame+this.config.inputDelay;r++)this.buffer.set(n,r,[]);this.sentThrough=this.startFrame+this.config.inputDelay-1,this.unsubscribe=this.transport.onMessage(n=>this.receive(n))}activePlayers(e){return this.roster.filter(n=>n.from<=e&&e<n.until).map(n=>n.player)}addPlayer(e,n){if(!this.roster.some(r=>r.player===e&&r.until===1/0)){this.roster.push({player:e,from:n,until:1/0}),this.buffer.addPlayer(e);for(let r=n;r<n+this.config.inputDelay;r++)this.buffer.set(e,r,[])}}removePlayer(e,n){let r=this.roster.find(o=>o.player===e&&o.until===1/0);r&&(r.until=n),this.buffer.clearFrom(e,n)}get frame(){return this.world.frame}get confirmedFrame(){let e=1/0;for(let n of this.activePlayers(this.world.frame))e=Math.min(e,this.buffer.contiguousThrough(n));return e===1/0?-1:e}get stalls(){return this.stallCount}tick(e=[]){if(this.desynced)return 0;let n=this.world.frame;this.scheduleLocal(e);let r=this.activePlayers(n);for(let s of r)if(!this.buffer.has(s,n))return this.stallCount++,this.onStall?.(s,n),0;let o=new Map;for(let s of r)o.set(s,this.buffer.get(s,n));let i=dt(r,o);return this.world.step(i),this.mergedLog.push(i),this.afterStep(this.world.frame),1}advance(e,n=[]){let r=0,o=this.world.clock.advance(e);for(let s=0;s<o&&this.tick(n)!==0;s++)r++;let i=0;for(;i++<8&&this.world.frame<this.remoteFrameEstimate()&&this.tick(n)===1;)r++;return r}inputLog(){return{frames:this.mergedLog.map(e=>e.slice())}}dispose(){this.unsubscribe()}deliver(e){this.receive(e)}onAfterStep(e){return this.afterStepListeners.push(e),()=>{this.afterStepListeners=this.afterStepListeners.filter(n=>n!==e)}}scheduleLocal(e){let n=this.world.frame+this.config.inputDelay;if(this.sentThrough>=n)return;for(;this.sentThrough<n;)this.sentThrough++,this.buffer.set(this.localPlayer,this.sentThrough,e);let r=Math.max(this.startFrame,n-this.config.redundancy+1),o=[];for(let i=r;i<=n;i++)o.push(this.buffer.get(this.localPlayer,i)??[]);this.transport.send(de(pe({t:"input",player:this.localPlayer,from:r,frames:o})))}afterStep(e){if(e%this.config.hashInterval===0){let n=this.world.hash();this.localHashes.set(e,n),this.transport.send(de(pe({t:"hash",player:this.localPlayer,frame:e,hash:n}))),this.checkPendingHashes()}if(e%64===0){this.buffer.prune(e-128);for(let n of this.localHashes.keys())n<e-512&&this.localHashes.delete(n)}for(let n of this.afterStepListeners)n(e)}receive(e){let n=$e(e);if(n)if(n.t==="input"&&n.player!==this.localPlayer)for(let r=0;r<n.frames.length;r++)this.buffer.set(n.player,n.from+r,n.frames[r]);else n.t==="hash"&&n.player!==this.localPlayer&&(this.pendingRemoteHashes.push({player:n.player,frame:n.frame,hash:n.hash}),this.checkPendingHashes())}checkPendingHashes(){let e=[];for(let n of this.pendingRemoteHashes){let r=this.localHashes.get(n.frame);if(r===void 0){n.frame>this.world.frame-512&&e.push(n);continue}r!==n.hash&&!this.desynced&&(this.desynced=!0,this.onDesync?.({frame:n.frame,player:n.player,localHash:r,remoteHash:n.hash,log:this.inputLog(),startFrame:this.startFrame}))}this.pendingRemoteHashes=e}remoteFrameEstimate(){let e=-1;for(let n of this.roster)n.player===this.localPlayer||n.until!==1/0||(e=Math.max(e,this.buffer.contiguousThrough(n.player)-this.config.inputDelay));return e}};var Jt=class{world;localPlayer;config;transport;players;buffer=new Xe;attach;onDesync;onRollbackOverflow;ring;usedInputs=new Map;earliestBad=1/0;rollbackCount=0;resimulatedFrames=0;localHashes=new Map;dropped=new Map;pendingRemoteHashes=[];hashedThrough=-1;desynced=!1;overflowed=!1;unsubscribe;constructor(e){this.world=e.world,this.transport=e.transport,this.localPlayer=e.localPlayer,this.players=[...e.players],this.config={...Ye,mode:"rollback",inputDelay:0,...e.config},this.attach=e.attach,this.onDesync=e.onDesync,this.onRollbackOverflow=e.onRollbackOverflow,this.ring=new Array(this.config.maxRollback+1).fill(null);for(let n of this.players)this.buffer.addPlayer(n);this.unsubscribe=this.transport.onMessage(n=>this.receive(n))}get frame(){return this.world.frame}get confirmedFrame(){let e=1/0;for(let n of this.players){let r=this.dropped.get(n),o=this.buffer.contiguousThrough(n);r!==void 0&&o>=r-1&&(o=1/0),e=Math.min(e,o)}return e===1/0?-1:e}lastKnownFrame(e){return this.buffer.contiguousThrough(e)}removePlayer(e,n){if(!(e===this.localPlayer||this.dropped.has(e))){this.dropped.set(e,n),this.buffer.clearFrom(e,n);for(let r=n;r<this.world.frame;r++){let o=this.usedInputs.get(r)?.get(e);o!==void 0&&o!=="[]"&&(this.earliestBad=Math.min(this.earliestBad,r))}this.settleHashes()}}get stats(){return{rollbacks:this.rollbackCount,resimulatedFrames:this.resimulatedFrames}}tick(e=[]){if(this.desynced||this.overflowed)return 0;let n=this.world.frame;return n-(this.confirmedFrame+1)>=this.config.maxRollback||(this.publishLocal(n,e),!this.resolveCorrections())?0:(this.storeSnapshot(n),this.stepFrame(n),this.settleHashes(),n%64===0&&this.pruneOld(n),1)}advance(e,n=[]){let r=0,o=this.world.clock.advance(e);for(let i=0;i<o&&this.tick(n)!==0;i++)r++;return r}inputLog(){let e=[],n=this.confirmedFrame;for(let r=0;r<=n;r++){let o=new Map;for(let i of this.players)o.set(i,this.buffer.get(i,r)??[]);e.push(dt(this.players,o))}return{frames:e}}dispose(){this.unsubscribe()}deliver(e){this.receive(e)}publishLocal(e,n){if(!this.buffer.set(this.localPlayer,e,n))return;let r=Math.max(0,e-this.config.redundancy+1),o=[];for(let i=r;i<=e;i++)o.push(this.buffer.get(this.localPlayer,i)??[]);this.transport.send(de(pe({t:"input",player:this.localPlayer,from:r,frames:o})))}inputsFor(e){let n=new Map;for(let r of this.players){let o=this.dropped.get(r);o!==void 0&&e>=o?n.set(r,[]):n.set(r,this.buffer.get(r,e)??this.buffer.latestAt(r,e))}return n}stepFrame(e){let n=this.inputsFor(e),r=new Map;for(let o of this.players)r.set(o,JSON.stringify(n.get(o)));this.usedInputs.set(e,r),this.world.step(dt(this.players,n))}resolveCorrections(){if(this.earliestBad===1/0)return!0;let e=this.world.frame,n=this.earliestBad;this.earliestBad=1/0;let r=this.ring[n%this.ring.length];if(!r||r.frame!==n)return this.overflowed=!0,this.onRollbackOverflow?.(n),!1;this.rollbackCount++,this.world.restore(r.snap),this.attach?.(this.world);for(let o=n;o<e;o++)this.storeSnapshot(o),this.stepFrame(o),this.resimulatedFrames++;return!0}storeSnapshot(e){this.ring[e%this.ring.length]={frame:e,snap:this.world.snapshot()}}receive(e){let n=$e(e);if(n)if(n.t==="input"&&n.player!==this.localPlayer){let r=this.dropped.get(n.player);for(let o=0;o<n.frames.length;o++){let i=n.from+o;if(!(r!==void 0&&i>=r)&&this.buffer.set(n.player,i,n.frames[o])&&i<this.world.frame){let s=this.usedInputs.get(i)?.get(n.player),a=JSON.stringify([...n.frames[o]].sort());s!==void 0&&s!==a&&(this.earliestBad=Math.min(this.earliestBad,i))}}this.settleHashes()}else n.t==="hash"&&n.player!==this.localPlayer&&(this.pendingRemoteHashes.push({player:n.player,frame:n.frame,hash:n.hash}),this.compareHashes())}settleHashes(){let e=Math.min(this.confirmedFrame+1,this.world.frame,this.earliestBad===1/0?1/0:this.earliestBad),n=this.config.hashInterval,r=(Math.floor(this.hashedThrough/n)+1)*n;for(;r<=e;r+=n){let o=this.ring[r%this.ring.length];if(!o||o.frame!==r)continue;let i=yt(o.snap);this.localHashes.set(r,i),this.hashedThrough=r,this.transport.send(de(pe({t:"hash",player:this.localPlayer,frame:r,hash:i})))}this.compareHashes()}compareHashes(){let e=[];for(let n of this.pendingRemoteHashes){let r=this.localHashes.get(n.frame);if(r===void 0){n.frame>this.hashedThrough-512&&e.push(n);continue}r!==n.hash&&!this.desynced&&(this.desynced=!0,this.onDesync?.({frame:n.frame,player:n.player,localHash:r,remoteHash:n.hash,log:this.inputLog(),startFrame:0}))}this.pendingRemoteHashes=e}pruneOld(e){this.buffer.prune(e-128);for(let n of this.usedInputs.keys())n<e-128&&this.usedInputs.delete(n);for(let n of this.localHashes.keys())n<e-512&&this.localHashes.delete(n)}};function Zc(){return globalThis.crypto.randomUUID()}function os(t,e,n,r,o,i,s,a,l){return t==="rollback"?new Jt({world:e,transport:n,localPlayer:r,players:o,config:s,attach:a,onDesync:l.onDesync}):new De({world:e,transport:n,localPlayer:r,players:o,startFrame:i,config:s,onDesync:l.onDesync})}function is(t,e,n,r,o){return{world:t,session:e,localPlayer:n,players:r,advance:(i,s=[])=>e.advance(i,s),dispose:()=>{e.dispose(),o?.()}}}var Mn=class{localPlayer="p1";seed;config;transport;makeWorld;maxPlayers;joinMargin;attach;callbacks;players=["p1"];uidToPlayer=new Map;nextPlayerIndex=2;started=!1;game=null;pendingSnapshots=[];unsubscribe;constructor(e){this.transport=e.transport,this.makeWorld=e.makeWorld,this.seed=e.seed??1,this.config={...Ye,...e.config},this.maxPlayers=e.maxPlayers??4,this.joinMargin=e.joinMargin??30,this.attach=e.attach,this.callbacks=e,this.unsubscribe=this.transport.onMessage(n=>this.receive(n))}get roster(){return[...this.players]}get isStarted(){return this.started}start(){if(this.game)return this.game;this.started=!0;let e=this.makeWorld(this.seed),n=os(this.config.mode,e,this.transport,this.localPlayer,this.players,0,this.config,this.attach,this.callbacks);return n instanceof De&&n.onAfterStep(r=>this.serviceSnapshots(r,e)),this.transport.send(de(pe({t:"start",players:[...this.players]}))),this.game=is(e,n,this.localPlayer,this.players,()=>this.unsubscribe()),this.game}dropPlayer(e){let n=this.game?.session;if(!n)return;let r=n instanceof De?Math.max(n.frame,n.confirmedFrame+1):n.lastKnownFrame(e)+1;this.transport.send(de(pe({t:"leave",player:e,atFrame:r}))),n.removePlayer(e,r),this.players=this.players.filter(o=>o!==e),this.callbacks.onPlayerLeave?.(e,r)}dispose(){this.unsubscribe(),this.game?.dispose()}receive(e){let n=$e(e);if(n){if(n.t==="hello")this.handleHello(n);else if(n.t==="bye"){let r=this.uidToPlayer.get(n.uid);r&&this.started?this.dropPlayer(r):r&&(this.players=this.players.filter(o=>o!==r),this.uidToPlayer.delete(n.uid))}}}handleHello(e){if(this.uidToPlayer.has(e.uid))return;if(this.players.length>=this.maxPlayers){this.transport.send(de(pe({t:"deny",to:e.uid,reason:"room full"})));return}if(this.started&&this.config.mode==="rollback"){this.transport.send(de(pe({t:"deny",to:e.uid,reason:"rollback rooms cannot be joined mid-game"})));return}let n=`p${this.nextPlayerIndex++}`;if(this.uidToPlayer.set(e.uid,n),this.players.push(n),!this.started){this.transport.send(de(pe({t:"welcome",to:e.uid,player:n,players:[...this.players],seed:this.seed,config:this.config,startFrame:0}))),this.callbacks.onPlayerJoin?.(n,0);return}let r=this.game.session,o=r.frame+this.joinMargin;this.transport.send(de(pe({t:"join",player:n,atFrame:o}))),r.addPlayer(n,o),this.pendingSnapshots.push({uid:e.uid,player:n,atFrame:o}),this.callbacks.onPlayerJoin?.(n,o)}serviceSnapshots(e,n){if(this.pendingSnapshots.length===0)return;let r=this.pendingSnapshots.filter(i=>i.atFrame===e);if(r.length===0)return;this.pendingSnapshots=this.pendingSnapshots.filter(i=>i.atFrame!==e);let o=n.snapshot();for(let i of r){let s=this.pendingSnapshots.filter(l=>l.player!==i.player),a=new Set(s.map(l=>l.player));this.transport.send(de(pe({t:"welcome",to:i.uid,player:i.player,players:this.players.filter(l=>!a.has(l)),seed:this.seed,config:this.config,startFrame:e,snapshot:o,joins:s.map(l=>({player:l.player,atFrame:l.atFrame}))})))}}};function to(t){let e=Zc(),n=t.transport;return new Promise((r,o)=>{let i=null,s=!1,a=null,l=[],u=[],c=()=>{if(!i||!s)return;m();let d=a??i.players,p=t.makeWorld(i.seed);i.snapshot&&(p.restore(i.snapshot),t.attach?.(p));let h=os(i.config.mode,p,n,i.player,d,i.startFrame,i.config,t.attach,t);if(i.joins&&h instanceof De)for(let k of i.joins)h.addPlayer(k.player,k.atFrame);for(let k of u)k.t==="join"&&h instanceof De&&h.addPlayer(k.player,k.atFrame),k.t==="leave"&&h.removePlayer(k.player,k.atFrame);let g=n.onMessage(k=>{let w=$e(k);w&&(w.t==="join"&&h instanceof De?(h.addPlayer(w.player,w.atFrame),t.onPlayerJoin?.(w.player,w.atFrame)):w.t==="leave"&&(h.removePlayer(w.player,w.atFrame),t.onPlayerLeave?.(w.player,w.atFrame)))}),x=is(p,h,i.player,d,()=>{g(),n.send(de(pe({t:"bye",uid:e})))});for(let k of l)h.deliver(k);r(x)},m=n.onMessage(d=>{let p=$e(d);if(p)switch(p.t){case"welcome":p.to===e&&(i=p,(p.snapshot||p.startFrame>0)&&(s=!0),c());break;case"deny":p.to===e&&(m(),o(new Error(`hayao-net: join denied \u2014 ${p.reason}`)));break;case"start":s=!0,a=p.players,c();break;case"join":case"leave":u.push(p);break;case"input":case"hash":l.push(d);break}});n.send(de(pe({t:"hello",uid:e,name:t.name})))})}function no(t){return new Mn(t)}function em(t,e,n){let r=t.width??1280,o=t.height??720,i=t.background??"#f3ecdb",s=n.renderer==="canvas"?new He({width:r,height:o,background:i}):new je({width:r,height:o,background:i});e.style.position=e.style.position||"relative",s.mount?.(e),Lt(e);let a=new Ge(t.inputMap??{},document),l=g=>Me(t,g),u=null,c=null,m=0,d=!1,p=g=>x=>{!d&&u&&(u.advance(x-g,a.currentActions())>0&&a.clearPressed(),s.draw(u.world.render())),m=requestAnimationFrame(p(x))},h=g=>{u=g,n.onStatus?.(`playing as ${g.localPlayer} (${g.players.length} players)`),m=requestAnimationFrame(p(performance.now()))};return n.role==="host"?(c=no({transport:n.transport,makeWorld:l,seed:n.seed??t.seed??1,config:n.config,maxPlayers:n.maxPlayers,attach:n.attach,onDesync:n.onDesync,onPlayerJoin:(g,x)=>{n.onStatus?.(`${g} joined`),n.onPlayerJoin?.(g,x)},onPlayerLeave:n.onPlayerLeave}),n.onStatus?.("hosting \u2014 waiting for players")):(n.onStatus?.("joining\u2026"),to({transport:n.transport,makeWorld:l,attach:n.attach,onDesync:n.onDesync,onPlayerJoin:n.onPlayerJoin,onPlayerLeave:n.onPlayerLeave}).then(h).catch(g=>n.onStatus?.(g.message))),{start(){c&&!u&&h(c.start())},get game(){return u},get localPlayer(){return u?.localPlayer??(n.role==="host"?"p1":null)},get roster(){return c?.roster??u?.players??[]},input:a,stop(){d=!0,cancelAnimationFrame(m),u?.dispose(),c?.dispose(),a.dispose(),s.dispose?.()}}}function tm(t,e,n,r){let o=t.palette?.bg??"#141821",i=t.palette?.fg??(Bt(o)>.4?"#14171f":"#f4efe3"),s=t.title??e.title,a={a:1,b:0,c:0,d:1,e:0,f:0};return[{kind:"rect",x:0,y:0,w:n,h:r,fill:o,transform:a,z:0},{kind:"text",text:s,x:n/2,y:r/2,size:Math.round(r*.06),align:"center",weight:700,fill:i,transform:a,z:1},{kind:"text",text:"loading\u2026",x:n/2,y:r/2+r*.08,size:Math.round(r*.03),align:"center",fill:i,opacity:.7,transform:a,z:1}]}function ro(t,e,n={}){let r=t.width??1280,o=t.height??720,i=t.background??"#f3ecdb",s=Me(t,n.world),a=n.renderer==="canvas"?new He({width:r,height:o,background:i}):new je({width:r,height:o,background:i});e.style.position=e.style.position||"relative",a.mount?.(e),Lt(e);let l=new Ge(t.inputMap??{},document),u=new Ct(a),c=Fr(),m=()=>{Le.start();let y=Ne.get();Le.setVolumes(y),window.removeEventListener("pointerdown",m),window.removeEventListener("keydown",m)};window.addEventListener("pointerdown",m),window.addEventListener("keydown",m);let d=()=>a.draw(s.render()),p=()=>{s=Me(t,n.world),d()},h=n.shell===!1?null:new Wt({title:t.title,onRestart:n.onRestart??p,onPause:y=>n.onPause?.(y)}),g=t.splash===!1?null:t.splash??{},x=g&&!c?tm(g,t,r,o):null,k=!c,w=[],P,$=new Promise(y=>P=y),v=performance.now(),f=0,M=performance.now(),S=()=>{if(k){k=!1,M=performance.now(),d(),P();for(let y of w.splice(0))y()}},D=y=>{if(k){x&&a.draw(x),f=requestAnimationFrame(D);return}let T=y-M;if(M=y,!c&&!h?.isPaused&&!n.isHeld?.()){u.sample(s.input);let E=l.currentActions(),O=s.advance(T,E);O>0&&(l.clearPressed(),n.onAdvance?.(s,O,E))}d(),f=requestAnimationFrame(D)};if(f=requestAnimationFrame(D),k){let y=g?.minDurationMs??0,T=t.preload?Promise.resolve().then(()=>t.preload(s)):Promise.resolve(),E=new Promise(O=>setTimeout(O,Math.max(0,y-(performance.now()-v))));Promise.all([T,E]).then(S).catch(O=>{console.error("hayao: preload failed \u2014",O),S()})}else P();let C={get world(){return s},renderer:a,input:l,pointer:u,canvas:a.element,toDesign:(y,T)=>a.toDesign?.(y,T)??{x:y,y:T},ready:$,onReady(y){k?w.push(y):y()},stop(){cancelAnimationFrame(f),l.dispose(),u.dispose(),h?.dispose(),a.dispose?.()},restart:p};return c&&Nr({get world(){return s},stepOnce:(y=[])=>{s.step(y),d()},renderSVG:()=>It(s.render(),r,o,i),setPaused:()=>{}}),C}var nm=0;function rm(t,e){return`${t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"game"}-${e.replace(/[:.]/g,"-").toLowerCase()}-${(nm++).toString(36)}`}var Qe=class{frames=[];axesLog=[];lastAxes=new Map;knobEvents=[];screenEvents=[];wallClockMarks=[];annotations=[];init;startedAt;id;buildRef;constructor(e){this.init=e,this.startedAt=e.startedAt??new Date().toISOString(),this.id=e.id??rm(e.game,this.startedAt),this.buildRef=e.buildRef??"unknown"}get frame(){return this.frames.length}get liveInputFrames(){return this.frames}get liveAxesLog(){return this.axesLog}get liveKnobEvents(){return this.knobEvents}step(e,n){if(n)for(let[r,o]of n)this.lastAxes.get(r)!==o&&(this.axesLog.push([this.frames.length,r,o]),this.lastAxes.set(r,o));this.frames.push([...e].sort())}knob(e,n){this.knobEvents.push({frame:this.frames.length,key:e,value:n}),this.screen("knob",`${e}=${n}`)}screen(e,n){this.screenEvents.push({frame:this.frames.length,kind:e,...n!==void 0?{detail:n}:{}})}mark(e,n){this.wallClockMarks.push({frame:this.frames.length,t:n,kind:e})}annotate(e,n){this.annotations.push({frame:this.frames.length,tag:e,...n!==void 0?{note:n}:{}})}truncate(e){if(!(e>=this.frames.length)){this.frames.length=e,this.axesLog=this.axesLog.filter(([n])=>n<e),this.lastAxes.clear();for(let[n,r,o]of this.axesLog)n<e&&this.lastAxes.set(r,o);this.knobEvents=this.knobEvents.filter(n=>n.frame<=e),this.screenEvents=this.screenEvents.filter(n=>n.frame<=e),this.wallClockMarks=this.wallClockMarks.filter(n=>n.frame<=e),this.annotations=this.annotations.filter(n=>n.frame<=e)}}toSession(e){return{id:this.id,game:this.init.game,startedAt:this.startedAt,buildRef:this.buildRef,seed:this.init.seed,variant:this.init.variant??{name:"dev",kind:"dev"},tuningValues:{...this.init.tuningValues},...this.init.startSnapshot?{startSnapshot:this.init.startSnapshot}:{},knobEvents:this.knobEvents.slice(),inputLog:{frames:this.frames.map(n=>n.slice())},axesLog:this.axesLog.slice(),screenEvents:this.screenEvents.slice(),wallClockMarks:this.wallClockMarks.slice(),annotations:this.annotations.slice(),endReason:e}}};var pt=class{constructor(e=30,n=240){this.stride=e;this.cap=n}stride;cap;entries=[];push(e,n){e%this.stride===0&&(this.entries.push({frame:e,snap:n.snapshot()}),this.entries.length>this.cap&&this.entries.shift())}nearest(e){let n=null;for(let r of this.entries)r.frame<=e&&(!n||r.frame>n.frame)&&(n=r);return n}get minFrame(){return this.entries.length>0?this.entries[0].frame:0}truncate(e){this.entries=this.entries.filter(n=>n.frame<=e)}clear(){this.entries=[]}};function Cn(t,e,n,r,o,i,s){let a=Math.max(n.minFrame,Math.min(s,r.length)),l=n.nearest(a);if(!l)return null;t.restore(structuredClone(l.snap)),e.attach?.(t),t.input.axes.clear();let u=new Map,c=0;for(;c<o.length&&o[c][0]<l.frame;){let[,d,p]=o[c++];u.set(d,p)}for(let[d,p]of u)t.input.axes.set(d,p);let m=i.findIndex(d=>d.frame>=l.frame);m<0&&(m=i.length);for(let d=l.frame;d<a;d++){for(;m<i.length&&i[m].frame===d;){let p=i[m++],h=t.snapshot();h.tuning={...h.tuning,[p.key]:p.value},t.restore(h),e.attach?.(t)}for(;c<o.length&&o[c][0]===d;){let[,p,h]=o[c++];t.input.axes.set(p,h)}t.step(r[d])}return a}function om(){if(typeof location>"u")return{};let t=new URLSearchParams(location.search),e={},n=t.get("seed");n!==null&&Number.isFinite(Number(n))&&(e.seed=Number(n));let r=t.get("tuning");if(r)try{let o=JSON.parse(atob(r));o&&typeof o=="object"&&(e.tuning=o)}catch{}return e}function im(t,e,n={}){let r=om(),o=typeof location<"u"?new URLSearchParams(location.search).get("variant"):null,i=o?n.variants?.[o]:void 0,s=i?.patch?i.patch(t):t,a=n.variant??(i&&o?{name:o,kind:"module"}:{name:"dev",kind:"dev"}),l=n.world?.seed??r.seed??s.seed??1,u={...i?.tuning,...r.tuning,...n.world?.tuning},c=qt(s.tuning,u),m={...c},d=typeof performance<"u"?performance.now():0,p=new Qe({game:s.title,seed:l,tuningValues:c,variant:a}),h=!1,g=(I,z)=>{let B=JSON.stringify(I);if(z&&typeof navigator<"u"&&navigator.sendBeacon){navigator.sendBeacon("/__studio/session",new Blob([B],{type:"application/json"}));return}fetch("/__studio/session",{method:"POST",headers:{"content-type":"application/json"},body:B}).catch(()=>{})},x=(I="quit",z=!1)=>{w||p.frame===0&&h||(g(p.toSession(I),z),h=!0)},k=typeof location<"u"?new URLSearchParams(location.search).get("session"):null,w=null,P=null,$=new pt,v=!1,f=null,M=()=>{if(f===null||f>=p.frame){f=null;return}p.truncate(f),$.truncate(f),p.screen("scrub",`forked@${f}`),f=null},S=ro(s,e,{...n,world:{seed:l,tuning:u},isHeld:()=>v||(n.isHeld?.()??!1),onAdvance:(I,z,B)=>{for(let W=0;W<z;W++)p.step(B,I.input.axes),$.push(p.frame,I);n.onAdvance?.(I,z,B)},onPause:I=>{p.screen(I?"pause":"resume"),n.onPause?.(I)},onRestart:()=>{x("restart"),p=new Qe({game:s.title,seed:l,tuningValues:{...m},variant:a,buildRef:p.buildRef}),(n.onRestart??S.restart)()}}),D=n.hot?.data.hayaoSnap;if(D){delete n.hot.data.hayaoSnap;let I=structuredClone(D);I.tuning={...m},S.world.restore(I),s.attach?.(S.world),p=new Qe({game:s.title,seed:l,tuningValues:{...m},variant:a,startSnapshot:I}),p.screen("hot-swap")}n.hot?.dispose(I=>{I.hayaoSnap=S.world.snapshot(),Z("hot-swap")}),$.push(0,S.world);async function C(I,z){let B=await fetch(`/__studio/session/${encodeURIComponent(I)}`);if(!B.ok)return;let W=await B.json();v=!0;let V=S.world,re=Me(s,{seed:W.seed,tuning:W.tuningValues});V.restore(W.startSnapshot?structuredClone(W.startSnapshot):re.snapshot()),s.attach?.(V),V.input.axes.clear();let oe=W.inputLog.frames,te=Math.max(30,Math.ceil(oe.length/220/30)*30);$=new pt(te),$.push(0,V);let se=0,me=0;for(let xe=0;xe<oe.length;xe++){for(;me<W.knobEvents.length&&W.knobEvents[me].frame===xe;){let ze=W.knobEvents[me++],Ce=V.snapshot();Ce.tuning={...Ce.tuning,[ze.key]:ze.value},V.restore(Ce),s.attach?.(V)}for(;se<W.axesLog.length&&W.axesLog[se][0]===xe;){let[,ze,Ce]=W.axesLog[se++];V.input.axes.set(ze,Ce)}V.step(oe[xe]),$.push(xe+1,V)}w={session:W,pos:oe.length},ae.scrub(Number.isFinite(z)?z:0)}function y(){if(!w||P!==null)return;let I=w.session,z=performance.now();P=window.setInterval(()=>{if(!w)return;let B=performance.now(),W=Math.min(120,Math.floor((B-z)/(1e3/60)));if(W<=0)return;z=B;let V=S.world;for(let re=0;re<W;re++){let oe=w.pos;if(oe>=I.inputLog.frames.length){T();return}for(let te of I.knobEvents)if(te.frame===oe){let se=V.snapshot();se.tuning={...se.tuning,[te.key]:te.value},V.restore(se),s.attach?.(V)}for(let[te,se,me]of I.axesLog)te===oe&&V.input.axes.set(se,me);V.step(I.inputLog.frames[oe]),w.pos=oe+1}},1e3/60)}function T(){P!==null&&(window.clearInterval(P),P=null)}k&&C(k,Number(new URLSearchParams(location.search).get("at")??"NaN")),fetch("/__studio/state").then(I=>I.ok?I.json():null).then(I=>{I?.buildRef&&(p.buildRef=I.buildRef)}).catch(()=>{}),fn((I,z)=>p.screen(I==="show"?"overlay-show":"overlay-hide",z));let E=()=>typeof performance<"u"?performance.now()-d:0,O=()=>p.mark(document.hidden?"visibility-hidden":"visibility-visible",E()),F=()=>p.mark("blur",E()),J=()=>p.mark("focus",E()),Y=()=>x("quit",!0);document.addEventListener("visibilitychange",O),window.addEventListener("blur",F),window.addEventListener("focus",J),window.addEventListener("pagehide",Y);let ne=window.setInterval(()=>x("idle"),1e4),Z=I=>{T(),x(I,I==="hot-swap"),document.removeEventListener("visibilitychange",O),window.removeEventListener("blur",F),window.removeEventListener("focus",J),window.removeEventListener("pagehide",Y),window.clearInterval(ne),fn(null),S.stop()},ae={...S,get world(){return S.world},setKnob(I,z){if(w)return;M(),m[I]=z;let B=S.world.snapshot();B.tuning={...m},S.world.restore(B),s.attach?.(S.world),p.knob(I,z)},knobValues:()=>({...m}),tuningSpec:()=>s.tuning,variants:()=>Object.fromEntries(Object.entries(n.variants??{}).map(([I,z])=>[I,z.label])),activeVariant:()=>({...a}),title:()=>s.title,annotate:(I,z)=>{w||p.annotate(I,z)},setFrozen(I){if(w){I?T():y();return}if(I===v)return;if(I){v=!0;return}let z=f!==null;if(M(),z){let B=S.world.snapshot().tuning??{};for(let W of Object.keys(m))W in B&&(m[W]=B[W])}v=!1},frozen:()=>w?P===null:v,scrub(I){if(w){T();let B=w.session,W=Cn(S.world,s,$,B.inputLog.frames,B.axesLog,B.knobEvents,I);return W!==null&&(w.pos=W),W}v=!0;let z=Cn(S.world,s,$,p.liveInputFrames,p.liveAxesLog,p.liveKnobEvents,I);return z!==null&&(f=z<p.frame?z:null),z},timeline:()=>w?{min:$.minFrame,frame:w.pos,max:w.session.inputLog.frames.length}:{min:$.minFrame,frame:f??p.frame,max:p.frame},mode:()=>w?"replay":"live",flush:(I="idle")=>x(I),session:()=>p.toSession("idle"),stop:()=>Z("navigate")};return window.__studio=ae,ae}var sm="0.3.0";return ds(am);})();
|
|
187
|
+
`;function ym(){if(typeof document>"u"||document.getElementById(Vs))return;let t=document.createElement("style");t.id=Vs,t.textContent=gm,document.head.appendChild(t)}var Hs=null;function un(t){Hs=t}var Po=null;function Zn(t){Po=t}function Do(t){if(typeof document>"u")return{close(){},element:null};ym(),cn(),Po?.("show",t.title);let e=document.createElement("div");e.className=`hy-scrim${t.dim===!1?"":" dim"}${t.className?" "+t.className:""}`;let n=document.createElement("div");if(n.className="hy-card",t.title){let u=document.createElement("h1");u.textContent=t.title,n.appendChild(u)}if(t.body){let u=document.createElement("div");u.className="hy-body",u.innerHTML=t.body,n.appendChild(u)}let r=t.actions??[],o=Math.max(0,r.findIndex(u=>u.primary));o<0&&(o=0);let i=[];if(r.length){let u=document.createElement("div");u.className="hy-menu",r.forEach((c,m)=>{let d=document.createElement("button");d.className=`hy-item${c.primary?" primary":""}`,d.textContent=c.label,d.addEventListener("click",()=>c.onSelect()),d.addEventListener("mouseenter",()=>s(m)),u.appendChild(d),i.push(d)}),n.appendChild(u)}function s(u){o=(u+i.length)%i.length,i.forEach((c,m)=>c.classList.toggle("sel",m===o))}i.length&&s(o);let a=u=>{i.length&&(u.code==="ArrowDown"?(s(o+1),u.preventDefault()):u.code==="ArrowUp"?(s(o-1),u.preventDefault()):(u.code==="Enter"||u.code==="Space")&&(r[o]?.onSelect(),u.preventDefault()))};document.addEventListener("keydown",a),e.appendChild(n),(Hs??document.body).appendChild(e);let l={element:e,close(){document.removeEventListener("keydown",a),e.remove(),Qn===l&&(Qn=null,Po?.("hide",t.title))}};return Qn=l,l}function cn(){Qn?.close()}var qs="hayao.settings.v1",js={master:.7,music:.6,sfx:.8,muted:!1,colorblind:!1,reducedMotion:!1},Eo=class{state;subs=new Set;constructor(){this.state=this.load(),this.pushToAudio()}get(){return{...this.state}}set(e){this.state={...this.state,...e},this.save(),this.pushToAudio();for(let n of this.subs)n(this.get())}subscribe(e){return this.subs.add(e),()=>this.subs.delete(e)}pushToAudio(){je.setVolumes({master:this.state.master,music:this.state.music,sfx:this.state.sfx,muted:this.state.muted})}load(){try{let e=typeof localStorage<"u"&&localStorage.getItem(qs);if(e)return{...js,...JSON.parse(e)}}catch{}return{...js}}save(){try{localStorage.setItem(qs,JSON.stringify(this.state))}catch{}}},ze=new Eo;function Io(){if(typeof document>"u")return;let t=document,e=document.documentElement;document.fullscreenElement||t.webkitFullscreenElement?(document.exitFullscreen??t.webkitExitFullscreen)?.call(document):(e.requestFullscreen??e.webkitRequestFullscreen)?.call(e)}var mn=class{paused=!1;opts;keyHandler;constructor(e={}){this.opts=e,this.keyHandler=n=>{n.code==="Escape"&&(n.preventDefault(),this.toggle())},typeof document<"u"&&document.addEventListener("keydown",this.keyHandler)}get isPaused(){return this.paused}toggle(){this.paused?this.resume():this.pause()}pause(){this.paused||(this.paused=!0,je.blip(440),this.opts.onPause?.(!0),this.render())}resume(){this.paused&&(this.paused=!1,cn(),this.opts.onPause?.(!1))}render(){let e=ze.get(),n=(r,o)=>`${r}: ${Math.round(o*100)}`;Do({title:this.opts.title??"Paused",body:`<div style="font-size:13px;text-align:left;line-height:1.9">${n("Master",e.master)} \xB7 ${n("Music",e.music)} \xB7 ${n("Sfx",e.sfx)}<br/><span style="opacity:.7">Use the menu, or keys: M mute \xB7 F fullscreen</span></div>`,actions:[{label:"Resume",primary:!0,onSelect:()=>this.resume()},{label:e.muted?"Unmute (M)":"Mute (M)",onSelect:()=>{ze.set({muted:!ze.get().muted}),this.render()}},{label:"Music \u2212/+",onSelect:()=>{let r=Math.min(1,ze.get().music+.1)%1.05;ze.set({music:r>1?0:r}),this.render()}},{label:"Fullscreen (F)",onSelect:()=>Io()},...this.opts.onRestart?[{label:"Restart",onSelect:()=>{this.resume(),this.opts.onRestart()}}]:[],...this.opts.onQuit?[{label:"Quit",onSelect:()=>{this.resume(),this.opts.onQuit()}}]:[]]})}dispose(){typeof document<"u"&&document.removeEventListener("keydown",this.keyHandler),cn()}};var Us="hayao-touch-style",xm=`
|
|
188
|
+
.hy-touch{position:absolute;inset:0;z-index:40;pointer-events:none;touch-action:none;-webkit-user-select:none;user-select:none}
|
|
189
|
+
.hy-stick{position:absolute;bottom:6%;width:120px;height:120px;border-radius:50%;pointer-events:auto;background:rgba(20,16,10,.16);border:2px solid rgba(250,244,230,.35);box-shadow:inset 0 0 20px rgba(0,0,0,.12)}
|
|
190
|
+
.hy-stick.left{left:5%}
|
|
191
|
+
.hy-stick.right{right:5%}
|
|
192
|
+
.hy-knob{position:absolute;left:50%;top:50%;width:52px;height:52px;margin:-26px 0 0 -26px;border-radius:50%;background:rgba(250,244,230,.6);border:2px solid rgba(20,16,10,.25);transition:transform .04s linear}
|
|
193
|
+
.hy-btns{position:absolute;right:5%;bottom:26%;display:flex;flex-direction:column-reverse;gap:12px;pointer-events:none}
|
|
194
|
+
.hy-btn{pointer-events:auto;width:66px;height:66px;border-radius:50%;font:600 15px/1 var(--hy-serif,Georgia,serif);color:#fbf6ea;background:var(--hy-accent,#a11d3a);border:2px solid rgba(250,244,230,.4);box-shadow:0 4px 12px rgba(30,20,10,.3);display:grid;place-items:center;text-transform:capitalize}
|
|
195
|
+
.hy-btn:active,.hy-btn.on{transform:translateY(2px);filter:brightness(1.15)}
|
|
196
|
+
`;function vm(){if(typeof document>"u"||document.getElementById(Us))return;let t=document.createElement("style");t.id=Us,t.textContent=xm,document.head.appendChild(t)}function wm(t){if(t.dirs)return Array.isArray(t.dirs)?{up:t.dirs[0],down:t.dirs[1],left:t.dirs[2],right:t.dirs[3]}:t.dirs}var Lo=class{handle;root;disposers=[];owned=new Set;constructor(e,n){this.handle=e,vm();let r=typeof matchMedia<"u"&&matchMedia("(pointer: coarse)").matches,o=e.canvas?.parentElement??void 0;this.root=document.createElement("div"),this.root.className="hy-touch",o&&(n.touchOnly===!1||r)&&o.appendChild(this.root);let i=Xs(n.left),s=Xs(n.right);i&&this.addStick("left",i),s&&this.addStick("right",s),n.buttons?.length&&this.addButtons(n.buttons)}addStick(e,n){let r=document.createElement("div");r.className=`hy-stick ${e}`;let o=document.createElement("div");o.className="hy-knob",r.appendChild(o),this.root.appendChild(r);let i=wm(n),s=n.prefix,a=n.buckets??32,l=n.deadzone??.28,u=null,c=(g,k)=>{if(!s)return;let v=this.handle.world.input.axes;v.set(`${s}x`,Ze(g,a)),v.set(`${s}y`,Ze(k,a)),v.set(`${s}angle`,g===0&&k===0?0:Hr(Le(k,g),a))},m=()=>{if(i)for(let g of[i.up,i.down,i.left,i.right])this.hold(g,!1);c(0,0),o.style.transform="translate(0,0)",u=null},d=(g,k)=>{let v=r.getBoundingClientRect(),M=v.width/2,I=(g-(v.left+M))/M,x=(k-(v.top+M))/M,b=G(I,x);b>1&&(I/=b,x/=b),o.style.transform=`translate(${I*M*.6}px,${x*M*.6}px)`;let w=G(I,x);i&&(this.hold(i.left,I<-l),this.hold(i.right,I>l),this.hold(i.up,x<-l),this.hold(i.down,x>l)),c(w<l?0:I,w<l?0:x)},h=g=>{u===null&&(u=g.pointerId,r.setPointerCapture?.(g.pointerId),d(g.clientX,g.clientY),g.preventDefault())},p=g=>{g.pointerId===u&&d(g.clientX,g.clientY)},f=g=>{g.pointerId===u&&m()};r.addEventListener("pointerdown",h),r.addEventListener("pointermove",p),r.addEventListener("pointerup",f),r.addEventListener("pointercancel",f),this.disposers.push(()=>{m(),r.remove()})}addButtons(e){let n=document.createElement("div");n.className="hy-btns",this.root.appendChild(n);for(let r of e){let o=document.createElement("button");o.className="hy-btn",o.textContent=r.label??r.action,n.appendChild(o);let i=r.hold??!0,s=l=>{o.classList.add("on"),i?this.hold(r.action,!0):this.handle.input.press(r.action),o.setPointerCapture?.(l.pointerId),l.preventDefault()},a=()=>{o.classList.remove("on"),i&&this.hold(r.action,!1)};o.addEventListener("pointerdown",s),o.addEventListener("pointerup",a),o.addEventListener("pointercancel",a),this.disposers.push(()=>{a(),o.remove()})}this.disposers.push(()=>n.remove())}hold(e,n){this.handle.input.setHeld(e,n),n&&this.owned.add(e)}dispose(){for(let e of this.disposers.splice(0))e();for(let e of this.owned)this.handle.input.setHeld(e,!1);this.owned.clear(),this.root.remove()}};function Xs(t){if(t)return Array.isArray(t)?{dirs:t}:t}var km=[0,8,2,10,12,4,14,6,3,11,1,9,15,7,13,5],Sm=t=>t*t*(3-2*t),er=class extends _{type="ScreenTransition";kind;color;screenW;screenH;cell;coverage=0;queue=[];constructor(e={}){super(e),this.cosmetic=!0,this.kind=e.kind??"fade",this.color=e.color??"#1a1410",this.screenW=e.width??1280,this.screenH=e.height??720,this.cell=e.cell??28}get busy(){return this.queue.length>0}enqueue(e,n,r){this.queue.push({from:void 0,to:e,dur:Math.max(1e-4,n),elapsed:0,onEnd:r})}cover(e=.4,n){return this.enqueue(1,e,n),this}reveal(e=.4,n){return this.enqueue(0,e,n),this}hold(e,n){let r=this.queue.length?this.queue[this.queue.length-1].to:this.coverage;return this.enqueue(r,e,n),this}wipe(e={}){let n=e.cover??.4;return this.cover(n,()=>{this.emit("covered",void 0),e.onMidpoint?.()}),e.hold&&this.hold(e.hold),this.reveal(e.reveal??n,()=>{this.emit("done",void 0),e.onDone?.()}),this}get covered(){return this.signal("covered")}get done(){return this.signal("done")}onProcess(e){let n=this.queue[0];if(!n)return;n.from===void 0&&(n.from=this.coverage),n.elapsed+=e;let r=Q(n.elapsed/n.dur,0,1);if(this.coverage=$e(n.from,n.to,Sm(r)),r>=1){this.coverage=n.to;let o=n.onEnd;this.queue.shift(),o?.()}}draw(e,n){let r=this.coverage;if(r<=0)return;let o=this.z;if(this.kind==="fade"){e.push({kind:"rect",x:0,y:0,w:this.screenW,h:this.screenH,fill:this.color,opacity:r,transform:oe,z:o});return}if(this.kind==="circle"){let a=this.screenW/2,l=this.screenH/2,u=Math.sqrt(a*a+l*l);e.push({kind:"circle",cx:a,cy:l,radius:r*u,fill:this.color,transform:oe,z:o});return}let i=Math.ceil(this.screenW/this.cell),s=Math.ceil(this.screenH/this.cell);for(let a=0;a<s;a++)for(let l=0;l<i;l++)(km[(l&3)+((a&3)<<2)]+.5)/16<r&&e.push({kind:"rect",x:l*this.cell,y:a*this.cell,w:this.cell,h:this.cell,fill:this.color,transform:oe,z:o})}},$o=class extends _{type="CinematicPlayer";steps=[];index=-1;elapsed=0;running=!1;onFinish;constructor(e={}){super(e),this.cosmetic=!0}play(e,n){return this.steps=e,this.onFinish=n,this.index=-1,this.elapsed=0,this.running=e.length>0,this.advance(),this}get active(){return this.running}get step(){return this.index}get finished(){return this.signal("finished")}advance(){if(this.index++,this.elapsed=0,this.index>=this.steps.length){this.running=!1,this.index=-1,this.emit("finished",void 0),this.onFinish?.();return}this.steps[this.index].enter?.()}stop(){this.running=!1,this.index=-1,this.steps=[]}onProcess(e){if(!this.running)return;this.elapsed+=e;let n=this.steps[this.index],r=this.elapsed>=(n.duration??0),o=n.until?n.until():!0;r&&o&&this.advance()}};function Cm(t,e={}){let n=new er({z:1e4,...e});return t.addChild(n)}function Tm(t,e={}){return{name:e.name??"wipe",enter:()=>t.wipe(e),until:()=>!t.busy}}var Mm=(t,e)=>({x:0,y:0,w:t,h:e});function mt(t,e={}){let n=e.maxDepth??60,r=e.nodeCap??1e6,o=t.initial(e.level);if(t.isWin(o))return{solvable:!0,path:[],depth:0,nodes:0,exhausted:!1};let i=[{state:o,path:[]}],s=new Set([t.key(o)]),a=0;for(let l=0;l<n&&i.length>0;l++){let u=[];for(let{state:c,path:m}of i)for(let d of t.moves(c)){if(a>=r)return{solvable:!1,nodes:a,exhausted:!0};a++;let h=t.apply(c,d);if(t.isDead?.(h))continue;if(t.isWin(h))return{solvable:!0,path:[...m,d],depth:l+1,nodes:a,exhausted:!1};let p=t.key(h);s.has(p)||(s.add(p),u.push({state:h,path:[...m,d]}))}i=u}return{solvable:!1,nodes:a,exhausted:i.length>0}}function Rm(t,e={}){let n=mt(t,e);if(!n.solvable)throw new Error(`hayao: level ${e.level??0} is NOT winnable (expanded ${n.nodes} nodes${n.exhausted?", search capped \u2014 raise nodeCap/maxDepth":""}).`);return n}function No(t,e){let n=t(),r=[];for(let o=0;o<e.frames.length;o++)n.step(wt(e,o),kt(e,o)),r.push(n.hash());return{finalHash:n.hash(),hashes:r}}function Js(t,e){let n=No(t,e),r=No(t,e),o=-1;for(let i=0;i<n.hashes.length;i++)if(n.hashes[i]!==r.hashes[i]){o=i;break}return{ok:o===-1&&n.finalHash===r.finalHash,frames:e.frames.length,divergedAt:o,finalHash:n.finalHash}}function Pm(t,e){let n=Js(t,e);if(!n.ok)throw new Error(`hayao: sim is NON-deterministic \u2014 runs diverged at frame ${n.divergedAt} of ${n.frames}. Check for Math.random/Date.now/Set-iteration/unordered-map in the sim.`);return n}function Dm(t,e,n){let r=t();for(let l=0;l<n;l++)r.step(wt(e,l),kt(e,l));let o=r.snapshot(),i=t();i.restore(o);for(let l=n;l<e.frames.length;l++)r.step(wt(e,l),kt(e,l)),i.step(wt(e,l),kt(e,l));let s=r.hash(),a=i.hash();return{ok:s===a,hashA:s,hashB:a}}function Em(t,e){return{actions:t,frames:e}}function Im(t){return{actions:[],frames:t}}function Lm(t,e){let n=[],r=0;for(let o of e){for(let i=0;i<o.frames;i++)t.step(o.actions??[]);r+=o.frames,n.push(t.probe())}return{totalFrames:r,finalHash:t.hash(),probes:n}}function $m(t,e,n=[]){for(let r=0;r<e;r++)t.step(n)}function Fo(){return typeof location<"u"&&new URLSearchParams(location.search).has("capture")}function Ao(t){let e={pump(n,r=[]){t.setPaused(!0);for(let o=0;o<n;o++)t.stepOnce(r);return t.world.probe()},probe:()=>t.world.probe(),hash:()=>t.world.hash(),shot:()=>t.renderSVG(),async save(n){let r=t.renderSVG();try{return(await fetch("/__shot",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({path:n,svg:r})})).ok}catch{return!1}},key(n,r){document.dispatchEvent(new KeyboardEvent(n,{code:r,bubbles:!0}))},get world(){return t.world}};return globalThis.__hayao=e,e}function Ys(t){let e=[];for(let n of t){let r=n.frames??1,o=n.hold??[];for(let i=0;i<r;i++)e.push(i===0&&n.press?[...o,...n.press]:[...o])}return e}function Nm(t,e,n){let r=0;for(let o of Ys(e)){if(n&&n(t.probe()))return{frames:r,matched:!0};t.step(o),r++}return{frames:r,matched:n?n(t.probe()):!1}}function Fm(t,e){let n=0,r=0,o={},s=a=>{let l=[],u=t[n];if(!u)return l;r++;let c={get frames(){return r},mem:o,next(){n++,r=0,o={}},retry(){r=0,o={}}},m=e[u.kind];if(!m)throw new Error(`plan bot: no executor for step kind "${u.kind}"`);return m(u,a,l,c),l};return s.stepIndex=()=>n,s.done=()=>n>=t.length,s}function Am(t,e,n,r,o,i=8){t<n-i?o.push("right"):t>n+i&&o.push("left"),e<r-i?o.push("down"):e>r+i&&o.push("up")}var dn=t=>[...new Set(t)];function Ks(t,e={}){let n=e.minCoyote??.05,r=e.minBuffer??.05,o=e.requireCornerNudge??!0,i=[];return t.coyoteTime>=n||i.push(`coyote time ${t.coyoteTime}s is below the ${n}s floor \u2014 late jumps off a ledge will be dropped`),t.jumpBuffer>=r||i.push(`jump buffer ${t.jumpBuffer}s is below the ${r}s floor \u2014 early jumps before landing will be swallowed`),o&&!((t.jumpCornerNudge??0)>0)&&i.push("no jump corner nudge \u2014 clipping a ceiling edge kills upward momentum instead of slipping past"),i}function Wm(t,e,n){let r=[];for(let o=0;o<=e;o++)n(o)||r.push(`${t}: input ${o} frame(s) into the window was refused \u2014 grace window is shorter than the specced ${e}`);return n(e+1)&&r.push(`${t}: input ${e+1} frame(s) in (past the window) was still accepted \u2014 grace window is longer than specced (unfair leniency)`),dn(r)}function Qs(t,e,n={}){let r=n.minChannels??2,[o,i]=n.shake??[0,1],[s,a]=n.hitstop??[0,12],l=[];for(let u of e){let c=t[u];if(!c){l.push(`event "${u}" has no feedback response \u2014 it happens silently`);continue}let m=new Set(c.channels).size;m<r&&l.push(`event "${u}" answers on ${m} channel(s) (${c.channels.join("+")||"none"}) \u2014 needs \u2265 ${r} (e.g. sfx + particles)`),c.shake!==void 0&&(c.shake<o||c.shake>i)&&l.push(`event "${u}" shake ${c.shake} is outside the [${o}, ${i}] envelope`),c.hitstopFrames!==void 0&&(c.hitstopFrames<s||c.hitstopFrames>a)&&l.push(`event "${u}" hit-stop ${c.hitstopFrames}f is outside the [${s}, ${a}]f envelope`)}return dn(l)}function _e(t){let e=t.replace("#","");e.length===3&&(e=e.split("").map(o=>o+o).join(""));let n=parseInt(e,16),r=o=>{let i=o/255;return i<=.03928?i/12.92:Pe((i+.055)/1.055,2.4)};return .2126*r(n>>16&255)+.7152*r(n>>8&255)+.0722*r(n&255)}function Lt(t,e){let n=_e(t),r=_e(e),o=Math.max(n,r),i=Math.min(n,r);return(o+.05)/(i+.05)}var Bm=t=>t.kind==="text"?void 0:t.fill;function Zs(t,e,n,r={}){let o=r.minBackgroundContrast??3,i=r.minSalienceFactor??1.15,s=[],a=Lt(e,n);a<o&&s.push(`avatar (${e}) contrast vs background is ${a.toFixed(2)}:1 (needs \u2265 ${o}:1) \u2014 it sinks into the ground`);let l=[];for(let u of t){let c=Bm(u);c&&c!=="none"&&c!==e&&l.push(Lt(c,n))}if(l.length){l.sort((c,m)=>c-m);let u=l[Math.floor(l.length/2)];a<u*i&&s.push(`avatar (${e}, ${a.toFixed(2)}:1) does not pop from the scenery (median ${u.toFixed(2)}:1) \u2014 it needs \u2265 ${i}\xD7 the median contrast`)}return dn(s)}function zm(t,e,n="threat"){let r=[],o=0;for(let i=0;i<t.length;i++){let s=t[i];s.active&&(i===0||!t[i-1].active)&&o<e&&r.push(`${n}: hitbox went live at frame ${i} after only ${o} telegraph frame(s) \u2014 needs \u2265 ${e} of wind-up`),o=s.active?0:s.telegraphing?o+1:0}return dn(r)}var _m=(t,e)=>_e(t)*e;function ea(t,e,n,r={}){let o=r.minLitLevel??.35,{light:i}=nt(Ke(t)),s=i.length?rt(i):null;if(!s)return[];let a=_e(s.ambient.fill??"#000000");for(let u of s.lights){let c=u.circle,m=bt(De(c.transform),n),d=G(m.x-c.cx,m.y-c.cy);if(d>=c.radius)continue;let h=Om(c),p=1-d/c.radius;a=Math.min(1,a+h*p)}let l=[];if(a<o){let u=_m(e,a);l.push(`avatar (${e}) sits in light level ${a.toFixed(2)} (needs \u2265 ${o}) \u2014 it sinks into the ambient darkness (effective luminance ${u.toFixed(3)}); add a pool over it or raise ambient level`)}return l}function Om(t){let e=t.gradient;if(e&&e.stops.length){let r=0;for(let o of e.stops)r=Math.max(r,_e(o.color));return r}let n=t.fill;return n?_e(n):1}function ta(t,e={}){let n=e.dt??.016666666666666666,r=e.maxSpeed??1800,o=e.maxAccel??9e4;if(t.length<3)return[];let i=[],s=[];for(let a=1;a<t.length;a++){let l=t[a].x-t[a-1].x,u=t[a].y-t[a-1].y,c=G(l,u)/n;s.push(c),c>r&&i.push(`camera snapped at frame ${a}: ${Math.round(c)}px/s exceeds the ${r}px/s ceiling`)}for(let a=1;a<s.length;a++){let l=Math.abs(s[a]-s[a-1])/n;l>o&&i.push(`camera jerked at frame ${a+1}: ${Math.round(l)}px/s\xB2 exceeds the ${o}px/s\xB2 ceiling`)}return dn(i)}function na(t,e,n=0){if(t.length<2||t.length!==e.length)return[];let r=t[t.length-1].x-t[0].x,o=e[e.length-1].x-e[0].x,i=t[t.length-1].y-t[0].y,s=e[e.length-1].y-e[0].y,a=[];return Math.abs(o)>n&&Math.sign(r)!==0&&Math.sign(r)!==Math.sign(o)&&a.push("camera drifts opposite the target on X \u2014 the view lags behind instead of leading"),Math.abs(s)>n&&Math.sign(i)!==0&&Math.sign(i)!==Math.sign(s)&&a.push("camera drifts opposite the target on Y \u2014 the view lags behind instead of leading"),a}function Gm(t,e={}){let n=[],r=[],o=t.background??e.background??"#ffffff";if(t.forgiveness&&n.push({gate:"forgiveness",issues:Ks(t.forgiveness)}),t.feedback&&n.push({gate:"feedback",issues:Qs(t.feedback.contract,t.feedback.events)}),t.avatarFill&&(e.commands?n.push({gate:"salience",issues:Zs(e.commands,t.avatarFill,o)}):r.push("salience (no rendered frame)")),t.lit&&(t.avatarFill&&e.commands&&e.avatarWorld?n.push({gate:"lighting",issues:ea(e.commands,t.avatarFill,e.avatarWorld)}):r.push("lighting (needs avatarFill + rendered frame + avatarWorld)")),t.scrolls)if(e.camSamples&&e.camSamples.length>=3){let i=ta(e.camSamples,{dt:e.dt});e.targetSamples&&i.push(...na(e.camSamples,e.targetSamples)),n.push({gate:"camera",issues:i})}else r.push("camera (no sampled positions)");return{ok:n.every(i=>i.issues.length===0),sections:n,skipped:r}}function sa(t){let e=t.text.length*t.size*.56,n=t.size*1.25,r=t.transform.e+t.x,o=t.transform.f+t.y,i=t.align==="center"?r-e/2:t.align==="right"?r-e:r;return{cmd:t,x:i,y:o-t.size,w:e,h:n}}function Wo(t){let e=t.transform.e,n=t.transform.f;switch(t.kind){case"rect":return{x:e+t.x,y:n+t.y,w:t.w,h:t.h};case"circle":return{x:e+t.cx-t.radius,y:n+t.cy-t.radius,w:t.radius*2,h:t.radius*2};case"poly":{let r=1/0,o=1/0,i=-1/0,s=-1/0;for(let a=0;a<t.points.length;a+=2)r=Math.min(r,t.points[a]),i=Math.max(i,t.points[a]),o=Math.min(o,t.points[a+1]),s=Math.max(s,t.points[a+1]);return{x:e+r,y:n+o,w:i-r,h:s-o}}default:return null}}var ra=(t,e)=>t.x<e.x+e.w&&t.x+t.w>e.x&&t.y<e.y+e.h&&t.y+t.h>e.y,oa=(t,e,n=2)=>t.x-n<=e.x&&t.y-n<=e.y&&t.x+t.w+n>=e.x+e.w&&t.y+t.h+n>=e.y+e.h,Vm=t=>t.transient===!0,ia=t=>{let e=t.fill;if(!(!e||e==="none")&&!t.gradient)return e};function Hm(t,e={}){let n=e.backgroundZ??1,r=e.margin??0,o=e.background,i=e.minContrast??1.5,s=e.minTextContrast??4.5,a=[],l=e.includeTransient?t:t.filter(c=>!Vm(c)),u=[];for(let c of l)c.kind==="text"&&c.text.trim().length&&u.push(sa(c));for(let c of u){let m=c.cmd.z??0,d={x:c.x-r,y:c.y-r,w:c.w+r*2,h:c.h+r*2},h=-1/0,p=o;for(let f of l){if(f.kind==="text")continue;let g=Wo(f);if(!g||!oa(g,c))continue;let k=f.opacity===void 0||f.opacity>=.6,v=f.z??0;k&&v<=m&&v>=h&&(h=v,p=ia(f)??p),v>m&&(f.opacity===void 0||f.opacity>=.9)&&a.push(`text "${hn(c.cmd.text)}" is hidden behind a ${f.kind} (z${v} > text z${m}) that fully covers it \u2014 give the text a higher z, or the shape a lower one`)}for(let f of l){if(f.kind==="text"||(f.z??0)<=n||(f.z??0)<=h||f.opacity!==void 0&&f.opacity<.25)continue;let g=Wo(f);g&&ra(d,g)&&!oa(g,c)&&a.push(`text "${hn(c.cmd.text)}" collides with a ${f.kind} (z${f.z}) at ~(${Math.round(g.x)},${Math.round(g.y)}) \u2014 back it with a panel, or stay clear`)}if(o&&s>0){let f=c.cmd.fill;if(f&&f!=="none"&&(c.cmd.opacity===void 0||c.cmd.opacity>=.6)){let g=Lt(f,p??o);g<s&&a.push(`text "${hn(c.cmd.text)}" (${f}) contrast is ${g.toFixed(2)}:1 on its backing (needs \u2265 ${s}:1) \u2014 barely readable`)}}}if(o)for(let c of l){if(c.kind==="text"||(c.z??0)<=n||c.opacity!==void 0&&c.opacity<.6)continue;let m=ia(c);if(!m)continue;let d=Lt(m,o);d<i&&a.push(`${c.kind} (${m}, z${c.z}) contrast is ${d.toFixed(2)}:1 vs background ${o} (needs \u2265 ${i}:1) \u2014 it vanishes into the ground`)}for(let c=0;c<u.length;c++)for(let m=c+1;m<u.length;m++)ra(u[c],u[m])&&a.push(`texts "${hn(u[c].cmd.text)}" and "${hn(u[m].cmd.text)}" overlap`);return aa(a)}var hn=t=>t.length>28?t.slice(0,25)+"\u2026":t,aa=t=>[...new Set(t)];function la(t){return t.startsWith("Digit")?[t.slice(5)]:t.startsWith("Key")?[t.slice(3).toLowerCase()]:t.startsWith("Arrow")?["arrow","\u2190","\u2192","\u2191","\u2193",t.slice(5).toLowerCase()]:t.startsWith("Shift")?["shift"]:t==="Space"?["space"]:t==="Enter"?["enter"]:t==="Period"?["."]:[t.toLowerCase()]}function qm(t,e){let n=t.render().filter(i=>i.kind==="text").map(i=>i.text.toLowerCase()).join(" \xB7 "),r=[],o=i=>i.length?i.length<=2&&/^[a-z0-9.]+$/.test(i)?new RegExp(`(^|[^a-z0-9])${i.replace(".","\\.")}($|[^a-z0-9])`).test(n):n.includes(i):!1;for(let[i,s]of Object.entries(e)){if(i==="restart")continue;[i.toLowerCase().replace(/-\d+$/,""),...s.flatMap(la)].some(o)||r.push(i)}return aa(r)}function jm(t,e){let n=[t.probe()];for(let r of e)t.step(r),n.push(t.probe());return n}function Um(t,e){for(let n=0;n<t.length;n++)if(e(t[n]))return n;return-1}function Xm(t,e){return t.map(n=>n[e])}function Jm(t,e){let n=[];for(let r=1;r<t.length;r++)t[r][e]!==t[r-1][e]&&n.push(r);return n}function Ym(t,e,n=0){for(let r=1;r<t.length;r++)if(e==="up"?t[r]<t[r-1]-n:t[r]>t[r-1]+n)return!1;return!0}function Km(t){return t.length===0?0:t.filter(e=>e.length>0).length/t.length}function Qm(t,e){let n=[0,...t,e],r=0;for(let o=1;o<n.length;o++)r=Math.max(r,n[o]-n[o-1]);return r}var Zm=t=>[...new Set(t)];function ua(t){let e=t.length;if(e===0)return{count:0,min:0,max:0,mean:0,distinct:0,maxJump:0,forwardFraction:1};let n=t[0],r=t[0],o=0,i=0,s=0;for(let a=0;a<e;a++){let l=t[a];if(l<n&&(n=l),l>r&&(r=l),o+=l,a>0){let u=l-t[a-1];u>i&&(i=u),u>=0&&s++}}return{count:e,min:n,max:r,mean:o/e,distinct:new Set(t).size,maxJump:i,forwardFraction:e>1?s/(e-1):1}}function ca(t,e={}){let n=e.maxJumpFactor??3,r=e.minJumpAllowance??2,o=e.minForwardFraction??.6,i=e.minDistinct??3,s=e.finaleFraction??.8,a=[],l=t.length;if(l<2)return a.push(`ramp has ${l} level(s) \u2014 need at least 2 to form a curve`),a;let u=ua(t);t[l-1]<t[0]&&a.push(`curve descends overall: finale (${t[l-1]}) is easier than the opener (${t[0]}) \u2014 the game gets EASIER`),u.max>0&&t[l-1]<u.max*s&&a.push(`finale (${t[l-1]}) is well below the peak (${u.max}) \u2014 the hardest level is buried mid-campaign, so it ends on an anticlimax`);let c=0,m=0;for(let p=1;p<l;p++){let f=t[p]-t[p-1];f>0&&(c+=f,m++)}let d=m>0?c/m:0,h=Math.max(r,d*n);for(let p=1;p<l;p++){let f=t[p]-t[p-1];f>h&&a.push(`difficulty cliff at level ${p+1}: jumps ${t[p-1]}\u2192${t[p]} (+${f}), past the +${h.toFixed(1)} envelope \u2014 smooth it with an intermediate level`)}return u.forwardFraction<o&&a.push(`only ${(u.forwardFraction*100).toFixed(0)}% of steps make progress (need \u2265 ${(o*100).toFixed(0)}%) \u2014 the curve wanders/descends instead of building`),u.distinct<i&&a.push(`only ${u.distinct} distinct difficulty value(s) across ${l} levels (need \u2265 ${i}) \u2014 the curve is flat; levels don't actually differ in challenge`),Zm(a)}function ed(t,e={}){let n=ca(t,e);if(n.length)throw new Error(`hayao: difficulty ramp is ill-shaped \u2014 ${n[0]}`)}function td(t,e,n){let r=Math.max(2,n.panels??12),o=Math.max(1,Math.ceil(e.length/(r-1))),i=[{frame:0,inner:st(t.render(),"p0")}];for(let v=0;v<e.length;v++)t.step(e[v]),((v+1)%o===0||v===e.length-1)&&i.push({frame:v+1,inner:st(t.render(),`p${i.length}`)});let s=Math.max(1,n.cols??4),a=n.panelWidth??320,l=Math.round(a*n.height/n.width),u=18,c=8,m=a+c,d=l+u+c,h=Math.ceil(i.length/s),p=s*m+c,f=h*d+c,g=n.background??"#ffffff",k=i.map((v,M)=>{let I=c+M%s*m,x=c+Math.floor(M/s)*d;return`<g transform="translate(${I} ${x})"><svg width="${a}" height="${l}" viewBox="0 0 ${n.width} ${n.height}"><rect x="0" y="0" width="${n.width}" height="${n.height}" fill="${g}"/>`+v.inner+`</svg><rect x="0" y="0" width="${a}" height="${l}" fill="none" stroke="#999" stroke-width="1"/><text x="${a/2}" y="${l+13}" font-size="11" font-family="monospace" text-anchor="middle" fill="#555">f ${v.frame} \xB7 ${(v.frame/60).toFixed(1)}s</text></g>`}).join("");return`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${p} ${f}" width="${p}" height="${f}"><rect x="0" y="0" width="${p}" height="${f}" fill="#f4f4f2"/>`+k+"</svg>"}function Bo(t){let e=t.left.length,n=new Float32Array(e);for(let r=0;r<e;r++)n[r]=(t.left[r]+t.right[r])*.5;return n}function ma(t,e,n,r,o){let i=Math.max(1,Math.floor(t.length/e)),s=`M0 ${o}`,a="";for(let l=0;l<e;l++){let u=0,c=0,m=l*i;for(let h=0;h<i&&m+h<t.length;h++){let p=t[m+h];p>c&&(c=p),p<u&&(u=p)}let d=l/e*n;s+=` L${d.toFixed(1)} ${(o-c*(r/2)).toFixed(1)}`,a=` L${d.toFixed(1)} ${(o-u*(r/2)).toFixed(1)}`+a}return s+a+" Z"}function nd(t,e={}){let n=e.width??900,r=e.timeBins??220,o=e.freqBands??64,i=16,s=n-i*2,a=70,l=200,u=84,c=i*5+a*2+l+u,m=It(Bo(t)),d=ma(t.left,r,s,a,a/2),h=ma(t.right,r,s,a,a/2),p=Bo(t),f=2048,g=Math.max(1,Math.floor(p.length/r)),k=s/r,v=l/o,M="";for(let C=0;C<r;C++){let E=C*g;if(E+64>=p.length)break;let R=Et(p.subarray(E,Math.min(E+f,p.length)));if(R.length===0)continue;let S=Math.max(1,Math.floor(R.length/o));for(let T=0;T<o;T++){let L=0;for(let ee=0;ee<S;ee++)L+=R[T*S+ee]??0;let H=L>1e-6?20*Ft(L):-120,$=Math.max(0,Math.min(1,(H+60)/60));if($<.03)continue;let Y=i+C*k,K=i*3+a*2+l-(T+1)*v,te=rd($);M+=`<rect x="${Y.toFixed(1)}" y="${K.toFixed(1)}" width="${(k+.6).toFixed(1)}" height="${(v+.6).toFixed(1)}" fill="${te}"/>`}}let I=od(m).map((C,E)=>`<text x="${i+4}" y="${c-u+20+E*18}" font-family="monospace" font-size="12" fill="#e8e4d8">${C}</text>`).join(""),x=i,b=i*2+a,w=(C,E)=>`<text x="${i}" y="${E-3}" font-family="monospace" font-size="10" fill="#8a8474">${C}</text>`;return`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${n} ${c}" width="${n}" height="${c}"><rect width="${n}" height="${c}" fill="#1a1814"/>`+(e.title?`<text x="${i}" y="${i-3}" font-family="monospace" font-size="12" fill="#d8b25a">${id(e.title)}</text>`:"")+w("L",x)+`<g transform="translate(${i} ${x})"><rect width="${s}" height="${a}" fill="#211e18"/><path d="${d}" fill="#5a9ac4" opacity="0.9"/></g>`+w("R",b)+`<g transform="translate(${i} ${b})"><rect width="${s}" height="${a}" fill="#211e18"/><path d="${h}" fill="#5ac48f" opacity="0.9"/></g><rect x="${i}" y="${i*3+a*2}" width="${s}" height="${l}" fill="#0d0c0a"/>`+M+`<rect x="${i}" y="${c-u}" width="${s}" height="${u-i}" fill="#211e18"/>`+I+"</svg>"}function rd(t){let e=Math.round(40+t*200),n=Math.round(20+t*t*150),r=Math.round(30+t*40);return`rgb(${e},${n},${r})`}function od(t){return[`dur ${t.durationSec.toFixed(2)}s peak ${t.peakDb.toFixed(1)} dBFS rms ${t.rms.toFixed(3)}`,`centroid ${Math.round(t.centroidHz)} Hz zcr ${Math.round(t.zcr)}/s`,`tempo ~${Math.round(t.tempoBpm)} bpm onsets ${t.onsetDensity.toFixed(1)}/s`]}function id(t){return t.replace(/[<>&]/g,e=>e==="<"?"<":e===">"?">":"&")}function sd(t,e){let n=It(Bo(t)),r=[],o=(i,s)=>{i||r.push(s)};if(e.minDurationSec!==void 0&&o(n.durationSec>=e.minDurationSec,`duration ${n.durationSec.toFixed(2)}s < min ${e.minDurationSec}`),e.maxDurationSec!==void 0&&o(n.durationSec<=e.maxDurationSec,`duration ${n.durationSec.toFixed(2)}s > max ${e.maxDurationSec}`),e.maxPeakDb!==void 0&&o(n.peakDb<=e.maxPeakDb,`peak ${n.peakDb.toFixed(1)}dB > max ${e.maxPeakDb}`),e.minRms!==void 0&&o(n.rms>=e.minRms,`rms ${n.rms.toFixed(3)} < min ${e.minRms} (too quiet?)`),e.minCentroidHz!==void 0&&o(n.centroidHz>=e.minCentroidHz,`centroid ${Math.round(n.centroidHz)}Hz < min ${e.minCentroidHz}`),e.maxCentroidHz!==void 0&&o(n.centroidHz<=e.maxCentroidHz,`centroid ${Math.round(n.centroidHz)}Hz > max ${e.maxCentroidHz}`),e.tempoBpm!==void 0){let i=e.tempoToleranceBpm??12;o(Math.abs(n.tempoBpm-e.tempoBpm)<=i,`tempo ${Math.round(n.tempoBpm)}bpm not within ${i} of ${e.tempoBpm}`)}return{ok:r.length===0,failures:r,features:n}}var pn=class{rng;clock;input=new Jt;events=new Wt;resources=new Map;state={};width;height;paused=!1;timeScale=1;root;activeCamera=null;seed;freeQueue=[];started=!1;tuningValues;guardDeterminism;warnedClamp=!1;warnedNondet=!1;constructor(e={}){this.seed=e.seed??1,this.rng=new ue(this.seed),this.clock=new At(e.clock),this.width=e.width??1280,this.height=e.height??720,this.tuningValues={...e.tuning??{}},this.guardDeterminism=e.guardDeterminism??!1,this.root=new _({name:"root"})}tune(e){let n=this.tuningValues[e];if(n===void 0)throw new Error(`tune('${e}'): no such knob declared in the game's tuning spec`);return n}resource(e){if(!this.resources.has(e)){let n=[...this.resources.keys()].join(", ")||"(none)";throw new Error(`resource('${e}'): not set. Available: ${n}`)}return this.resources.get(e)}get time(){return this.clock.simTimeSec}get frame(){return this.clock.frame}setRoot(e){this.root&&this.root.exitTree(),this.root=e,this.started=!1}requestFree(e){this.freeQueue.push(e)}ensureStarted(){this.started||(this.root.enterTree(this),this.started=!0)}step(e=[],n){if(typeof e=="string"||typeof e[Symbol.iterator]!="function")throw new TypeError(`step(actionsDown): pass an array/iterable of action names, got ${typeof e=="string"?`the string '${e}'`:typeof e}`);this.ensureStarted();let r=this.guardDeterminism?this.installGuard():null;try{this.input.beginFrame(e,n),this.root.updateTree(this.clock.dt*this.timeScale,this.clock.dt,"pausable",this.paused),this.flushFree(),this.clock.tick()}finally{r?.()}}installGuard(){let e=globalThis.Math,n=e.random,r=globalThis.Date.now,o=i=>{if(this.warnedNondet)return;this.warnedNondet=!0;let s=new Error().stack?.split(`
|
|
197
|
+
`).slice(2,5).join(`
|
|
198
|
+
`)??"";console.warn(`hayao: ${i} called during step() \u2014 nondeterministic. Use world.rng / ctx.time instead.
|
|
199
|
+
${s}`)};return e.random=()=>(o("Math.random"),n.call(e)),globalThis.Date.now=()=>(o("Date.now"),r.call(globalThis.Date)),()=>{e.random=n,globalThis.Date.now=r}}advance(e,n=[],r){e>this.clock.maxFrameMs&&!this.warnedClamp&&(this.warnedClamp=!0,console.warn(`hayao: advance(${e}) exceeds maxFrameMs (${this.clock.maxFrameMs}) and is clamped \u2014 a realtime driver must never spiral. To fast-forward an exact number of steps, use runSteps(n).`));let o=this.clock.advance(e);for(let i=0;i<o;i++)this.step(n,r);return o}runSteps(e,n,r){for(let o=0;o<e;o++)this.step(n?n(o):[],r?.(o))}flushFree(){if(this.freeQueue.length===0)return;let e=this.freeQueue;this.freeQueue=[];for(let n of e)n.exitTree(),n.parent?.removeChild(n),this.activeCamera===n&&(this.activeCamera=null)}walk(e){let n=r=>{e(r);for(let o of r.children)n(o)};n(this.root)}get nodeCount(){let e=0;return this.walk(()=>e++),e}debugTree(){let e=[],n=(r,o)=>{let i=[];r.cosmetic&&i.push("cosmetic"),r.screenSpace&&i.push("screenSpace"),r.pauseMode!=="inherit"&&i.push(r.pauseMode),r.visible||i.push("!visible"),e.push(`${" ".repeat(o)}${r.name} (${r.type})${i.length>0?` [${i.join(" ")}]`:""} @${r.pos.x},${r.pos.y}`);for(let s of r.children)n(s,o+1)};return n(this.root,0),e.join(`
|
|
200
|
+
`)}camera(){if(!this.activeCamera)return null;let e=this.activeCamera.worldTransform();return{pos:{x:e.e,y:e.f},zoom:this.activeCamera.zoom}}viewTransform(){if(!this.activeCamera)return oe;let e=this.activeCamera,n=e.worldTransform();return Ne(Ge({x:this.width/2,y:this.height/2},0,{x:e.zoom,y:e.zoom}),De(n))}worldToScreen(e){return bt(this.viewTransform(),e)}screenToWorld(e){return bt(De(this.viewTransform()),e)}render(){this.ensureStarted();let e=[];return this.root.collectDraw(e,this.viewTransform()),e}hash(){return Bt({seed:this.seed,rng:this.rng.getState(),clock:this.clock.getState(),input:this.input.getState(),state:this.state,tree:this.root.serialize(),...Object.keys(this.tuningValues).length>0?{tuning:this.tuningValues}:{},...this.paused?{paused:!0}:{},...this.timeScale!==1?{timeScale:this.timeScale}:{}})}snapshot(){return{seed:this.seed,rng:this.rng.getState(),clock:this.clock.getState(),input:this.input.getState(),state:structuredClone(this.state),tree:this.root.serialize(),tuning:{...this.tuningValues},...this.paused?{paused:!0}:{},...this.timeScale!==1?{timeScale:this.timeScale}:{}}}restore(e){this.seed=e.seed,this.rng.setState(e.rng),this.clock.setState(e.clock),this.input.setState(e.input),this.state=structuredClone(e.state),e.tuning&&(this.tuningValues={...e.tuning}),this.paused=e.paused??!1,this.timeScale=e.timeScale??1,gr(1e6),this.setRoot(Nn(e.tree)),this.ensureStarted()}probe(){return{frame:this.frame,time:this.time,hash:this.hash(),nodes:this.root.query("Sprite").length+this.root.query("Text").length}}};var ad={num(t,e){return{key:t,type:"number",...e}},color(t,e){return{key:t,type:"color",cosmetic:!0,...e}},enumOf(t,e){return{key:t,type:"enum",...e}}};function fn(t,e){let n={};if(!t)return n;for(let r of t.knobs){n[r.key]=r.default;let o=e?.[r.key];if(o!==void 0)if(r.type==="number"){let i=typeof o=="number"?o:Number(o);if(!Number.isFinite(i))continue;let s=r.min??-1/0,a=r.max??1/0;n[r.key]=Math.min(a,Math.max(s,i))}else r.type==="enum"?typeof o=="string"&&(r.options??[]).includes(o)&&(n[r.key]=o):typeof o=="string"&&(n[r.key]=o)}return n}function ld(t){return{width:1280,height:720,seed:1,background:"#f3ecdb",inputMap:Fn,...t}}function Te(t,e){let n=typeof e=="number"?{seed:e}:e??{},r=new pn({seed:n.seed??t.seed??1,width:t.width??1280,height:t.height??720,clock:t.clock,tuning:fn(t.tuning,n.tuning)});return r.setRoot(t.build(r)),t.probe&&(r.probe=()=>t.probe(r)),r}function ud(t){return t.inputMap??Fn}function cd(t,e){let n=Te(t),r=e?.frames??[];for(let o of r)n.step(o);return{world:n,hash:n.hash(),steps:r.length}}function zo(t,e,n){let r=typeof n=="number"?{toFrame:n}:n??{},o=Te(t,{seed:e.seed,tuning:e.tuningValues});e.startSnapshot&&(o.restore(structuredClone(e.startSnapshot)),t.attach?.(o)),r.onWorld?.(o);let i=Math.min(r.toFrame??e.inputLog.frames.length,e.inputLog.frames.length),s=0,a=0,l={...e.tuningValues};for(let u=0;u<i;u++){for(;a<e.knobEvents.length&&e.knobEvents[a].frame===u;){let c=e.knobEvents[a++];l[c.key]=c.value;let m=o.snapshot();m.tuning={...l},o.restore(m),t.attach?.(o)}for(;s<e.axesLog.length&&e.axesLog[s][0]===u;){let[,c,m]=e.axesLog[s++];o.input.axes.set(c,m)}o.step(e.inputLog.frames[u]),r.onFrame?.(o,u)}return o}function da(t){let{frame:e,time:n,hash:r,...o}=t;return JSON.stringify(o)}function md(t){let e=t.px??t.x,n=t.py??t.y;return typeof e=="number"&&typeof n=="number"?{x:e,y:n}:null}function dd(t){let e=[],n=null;for(let o of t.wallClockMarks)o.kind==="visibility-hidden"&&n===null&&(n=o.frame),o.kind==="visibility-visible"&&n!==null&&(e.push([n,o.frame]),n=null);n!==null&&e.push([n,t.inputLog.frames.length]);let r=null;for(let o of t.screenEvents)(o.kind==="overlay-show"||o.kind==="pause")&&r===null&&(r=o.frame),(o.kind==="overlay-hide"||o.kind==="resume")&&r!==null&&(e.push([r,o.frame]),r=null);return e}var hd=(t,e)=>e.some(([n,r])=>t>=n&&t<r);function pd(t,e,n={}){let r=n.hesitationFrames??45,o=n.futileWindow??30,i=n.quitWindow??300,s=n.clusterPx??64,a=e.inputLog.frames,l=dd(e),u=new Set(e.axesLog.map(([S])=>S)),c=[],m=null;for(let S=0;S<=a.length;S++){let T=S<a.length&&a[S].length===0&&!u.has(S);if(T&&m===null&&(m=S),!T&&m!==null){let L=S-m;L>=r&&!hd(m,l)&&c.push({startFrame:m,frames:L}),m=null}}let d=new Map;for(let S=0;S<a.length;S++){let T=S>0?a[S-1]:[];for(let L of a[S])T.includes(L)||(d.has(L)||d.set(L,[]),d.get(L).push(S))}let p=Object.keys(t.inputMap??{}).filter(S=>!d.has(S)),f=new Set;for(let S of c)f.add(S.startFrame);for(let S of e.annotations)f.add(Math.max(0,Math.min(S.frame,a.length-1)));for(let[,S]of d)for(let T of S)f.add(Math.max(0,T-1)),f.add(Math.min(a.length-1,T+o));a.length>0&&f.add(a.length-1);let g=new Map,k=[],v=!1,M=-1,I=zo(t,e,{onWorld:S=>{S.events.on("death",()=>k.push({frame:M+1,pos:md(S.probe())})),S.events.on("goal",()=>v=!0)},onFrame:(S,T)=>{M=T,f.has(T)&&g.set(T,S.probe())}}),x=a.length>0?g.get(a.length-1)??I.probe():I.probe();x.won===!0&&(v=!0);let b=c.map(S=>({...S,probe:g.get(S.startFrame)??{}})),w=new Map;for(let S of k){let T=S.pos?`${Math.round(S.pos.x/s)}:${Math.round(S.pos.y/s)}`:"unknown",L=w.get(T)??{x:S.pos?.x??0,y:S.pos?.y??0,count:0,frames:[]};L.count++,L.frames.push(S.frame),w.set(T,L)}let C=[];for(let[S,T]of d){let L=[];for(let H of T){let $=g.get(Math.max(0,H-1)),Y=g.get(Math.min(a.length-1,H+o));$&&Y&&da($)===da(Y)&&L.push(H)}L.length>0&&C.push({action:S,futilePresses:L.length,totalPresses:T.length,frames:L})}let E=e.annotations.map(S=>{let T=Math.max(0,Math.min(S.frame,a.length-1));return{frame:S.frame,tag:S.tag,...S.note!==void 0?{note:S.note}:{},probe:g.get(T)??{}}}),R={sessionId:e.id,game:e.game,buildRef:e.buildRef,seed:e.seed,variant:e.variant,frames:a.length,simSeconds:I.time,reachedGoal:v,deaths:k.length,hesitations:b,deathClusters:[...w.values()].sort((S,T)=>T.count-S.count),futileVerbs:C.sort((S,T)=>T.futilePresses-S.futilePresses),annotations:E,knobEvents:e.knobEvents,unusedActions:p};if(!v&&a.length>0){let S=Math.max(0,a.length-i);R.quit={frame:a.length-1,probe:x,recentDeaths:k.filter(T=>T.frame>=S).length,recentHesitations:b.filter(T=>T.startFrame>=S).length,endReason:e.endReason}}return R}function fd(t,e,n,r){let o=t.palette?.bg??"#141821",i=t.palette?.fg??(_e(o)>.4?"#14171f":"#f4efe3"),s=t.title??e.title,a={a:1,b:0,c:0,d:1,e:0,f:0};return[{kind:"rect",x:0,y:0,w:n,h:r,fill:o,transform:a,z:0},{kind:"text",text:s,x:n/2,y:r/2,size:Math.round(r*.06),align:"center",weight:700,fill:i,transform:a,z:1},{kind:"text",text:"loading\u2026",x:n/2,y:r/2+r*.08,size:Math.round(r*.03),align:"center",fill:i,opacity:.7,transform:a,z:1}]}function bn(t,e,n={}){let r=t.width??1280,o=t.height??720,i=t.background??"#f3ecdb",s=Te(t,n.world),a=n.renderer==="canvas"?new lt({width:r,height:o,background:i}):n.renderer==="webgl"?new on({width:r,height:o,background:i}):new at({width:r,height:o,background:i});e.style.position=e.style.position||"relative",a.mount?.(e),un(e);let l=new et(t.inputMap??{},document),u=new Yt(a,{keyboard:l}),c=[...n.sources??[]],m=Fo(),d=()=>s.input.declareActions(l.actionNames());d();let h=()=>{je.start();let D=ze.get();je.setVolumes(D),window.removeEventListener("pointerdown",h),window.removeEventListener("keydown",h)};window.addEventListener("pointerdown",h),window.addEventListener("keydown",h);let p=()=>a.draw(s.render()),f=()=>{s=Te(t,n.world),d(),p()},g=n.shell===!1?null:new mn({title:t.title,onRestart:n.onRestart??f,onPause:D=>n.onPause?.(D)}),k=t.splash===!1?null:t.splash??{},v=k&&!m?fd(k,t,r,o):null,M=!m,I=[],x,b=new Promise(D=>x=D),w=performance.now(),C=performance.now(),E=()=>{if(M){M=!1,C=performance.now(),p(),x();for(let D of I.splice(0))D()}},R=D=>{if(!m&&!g?.isPaused&&!n.isHeld?.()){u.sample(s.input);for(let z of c)z.sample(s.input);let A=l.currentActions(),O=s.advance(D,A);O>0&&(l.clearPressed(),n.onAdvance?.(s,O,A))}p()},S=0,T,L=null,H=!1,$=16,Y=()=>{S!==0&&(cancelAnimationFrame(S),S=0),T!==void 0&&(clearTimeout(T),T=void 0)},K=D=>{H||(L=D,document.hidden?T=setTimeout(()=>{T=void 0,L=null,D(performance.now())},$):S=requestAnimationFrame(A=>{S=0,L=null,D(A)}))},te=()=>{let D=L;D!==null&&(Y(),L=null,K(D))};document.addEventListener("visibilitychange",te);let ee=D=>{if(M){v&&a.draw(v),K(ee);return}let A=D-C;C=D,R(A),K(ee)};if(K(ee),M){let D=k?.minDurationMs??0,A=t.preload?Promise.resolve().then(()=>t.preload(s)):Promise.resolve(),O=new Promise(z=>setTimeout(z,Math.max(0,D-(performance.now()-w))));Promise.all([A,O]).then(E).catch(z=>{console.error("hayao: preload failed \u2014",z),E()})}else x();let ie={get world(){return s},renderer:a,input:l,pointer:u,canvas:a.element,toDesign:(D,A)=>a.toDesign?.(D,A)??{x:D,y:A},viewport:()=>a.viewport?.(),ready:b,onReady(D){M?I.push(D):D()},addSource(D){return c.push(D),()=>{let A=c.indexOf(D);A!==-1&&c.splice(A,1),D.dispose?.()}},tick(D){R(D??s.clock.stepMs)},stop(){H=!0,L=null,Y(),document.removeEventListener("visibilitychange",te),l.dispose(),u.dispose();for(let D of c)D.dispose?.();c.length=0,g?.dispose(),a.dispose?.()},restart:f};return m&&Ao({get world(){return s},stepOnce:(D=[])=>{s.step(D),p()},renderSVG:()=>en(s.render(),r,o,i),setPaused:()=>{}}),ie}function _o(t,e,n,r){let o=new Event(t,{bubbles:!0});return o.clientX=e,o.clientY=n,o.pointerId=r,o.button=0,o}function bd(t,e){if(typeof document>"u")throw new Error("verify/dom: no DOM found \u2014 set the test's environment to jsdom (// @vitest-environment jsdom).");let n=!e,r=e??document.createElement("div");n&&document.body.appendChild(r);let o=bn(t,r,{shell:!1,isHeld:()=>!0}),i=o.canvas;return{handle:o,touchDown(s,a,l=1){i?.dispatchEvent(_o("pointerdown",s,a,l))},touchMove(s,a,l=1){i?.dispatchEvent(_o("pointermove",s,a,l))},touchUp(s=1){globalThis.dispatchEvent?.(_o("pointerup",0,0,s))},step(s=1,a){for(let l=0;l<s;l++)o.pointer.sample(o.world.input),o.world.step(o.input.currentActions(),a),o.input.clearPressed()},dispose(){o.stop(),n&&r.remove()}}}var Oo=class{constructor(e,n,r,o){this.states=e;this.transitions=n;this.ctx=o;this.current=r,this.states[r]?.onEnter?.(o)}states;transitions;ctx;current;update(e){for(let n of this.transitions)if((n.from==="*"||n.from===this.current)&&n.when(this.ctx)){this.go(n.to);break}this.states[this.current]?.onUpdate?.(this.ctx,e)}go(e){e!==this.current&&(this.states[this.current]?.onLeave?.(this.ctx),this.current=e,this.states[e]?.onEnter?.(this.ctx))}is(...e){return e.includes(this.current)}getState(){return this.current}setState(e){this.current=e}},Go=class{constructor(e,n){this.defs=e;if(!e[n])throw new Error(`hayao: PhaseClock has no phase '${n}'`);this.phase=n}defs;phase;elapsed=0;get duration(){return this.defs[this.phase]?.duration??0}progress(e=n=>n){let n=this.duration,r=n>0?this.elapsed/n:1;return e(r<0?0:r>1?1:r)}get done(){return this.elapsed>=this.duration}update(e){this.elapsed+=e;let n=!1,r=0;for(;this.elapsed>=this.duration&&this.defs[this.phase]?.next!==void 0&&r++<1024;){let o=this.elapsed-this.duration;this.phase=this.defs[this.phase].next,this.elapsed=o,n=!0}return n}to(e){if(!this.defs[e])throw new Error(`hayao: PhaseClock has no phase '${e}'`);this.phase=e,this.elapsed=0}getState(){return{phase:this.phase,elapsed:this.elapsed}}setState(e){this.phase=e.phase,this.elapsed=e.elapsed}};function gd(t){return{kind:"sleep",left:t}}function yd(t){return{kind:"cond",cond:t}}function xd(){return{kind:"next"}}function vd(...t){return{kind:"race",waits:t}}function wd(...t){return{kind:"all",waits:t}}var ha=1e-9;function Vo(t,e){if(pa(t))return t.done?0:-1;switch(t.kind){case"sleep":return t.left-=e,t.left<=ha?0:-1;case"cond":return!t.met&&t.cond()&&(t.met=!0),t.met?0:-1;case"next":return t.passed=!0,0;case"race":{let n=-1;for(let r=0;r<t.waits.length;r++)Vo(t.waits[r],e)>=0&&n<0&&(n=r);return n}case"all":{let n=!0;for(let r of t.waits)Ho(r)||Vo(r,e)<0&&(n=!1);return n?0:-1}}}function Ho(t){if(pa(t))return t.done;switch(t.kind){case"sleep":return t.left<=ha;case"cond":return t.met===!0;case"next":return t.passed===!0;case"race":return t.waits.some(Ho);case"all":return t.waits.every(Ho)}}function pa(t){return t instanceof tr}var tr=class{name;done=!1;wait=null;gen;constructor(e,n){this.name=n,this.gen=e()}resume(e){try{let n=this.gen.next(e);n.done?this.done=!0:this.wait=n.value}catch(n){this.done=!0,console.warn(`[hayao] coroutine "${this.name}" threw and was stopped:`,n)}}stop(){if(!this.done){this.done=!0;try{this.gen.return(void 0)}catch{}}}},qo=class{runners=[];pending=[];nextId=0;start(e,n){let r=new tr(e,n??`co${this.nextId}`);return this.nextId++,this.pending.push(r),r}step(e){this.pending.length>0&&(this.runners.push(...this.pending),this.pending.length=0);for(let r of this.runners){if(r.done)continue;if(r.wait===null){r.resume(0);continue}let o=Vo(r.wait,e);o>=0&&(r.wait=null,r.resume(o))}let n=0;for(let r of this.runners)r.done||(this.runners[n++]=r);this.runners.length=n}stopAll(){for(let e of this.runners)e.stop();for(let e of this.pending)e.stop();this.runners.length=0,this.pending.length=0}get active(){let e=0;for(let n of this.runners)n.done||e++;for(let n of this.pending)n.done||e++;return e}};function kd(t){let e=0;for(let n of t)e+=n>0?n:0;return e}function Uo(t,e){let n=kd(e);if(n<=0)throw new Error("hayao: weightedIndex needs at least one positive weight");let r=t.float()*n;for(let o=0;o<e.length;o++){let i=e[o]>0?e[o]:0;if(r<i)return o;r-=i}for(let o=e.length-1;o>=0;o--)if(e[o]>0)return o;return e.length-1}function Sd(t,e,n){if(e.length!==n.length)throw new Error("hayao: weightedPick items/weights length mismatch");return e[Uo(t,n)]}function Xo(t,e){return e[Uo(t,e.map(n=>n.weight))].value}var jo=class{values;cumulative;total;constructor(e){if(e.length===0)throw new Error("hayao: LootTable needs at least one entry");let n=[],r=[],o=0;for(let i of e)o+=i.weight>0?i.weight:0,n.push(i.value),r.push(o);if(o<=0)throw new Error("hayao: LootTable needs at least one positive weight");this.values=n,this.cumulative=r,this.total=o}roll(e){let n=e.float()*this.total;for(let r=0;r<this.cumulative.length;r++)if(n<this.cumulative[r])return this.values[r];return this.values[this.values.length-1]}rollMany(e,n){let r=[];for(let o=0;o<n;o++)r.push(this.roll(e));return r}};function fa(t,e,n,r={}){let o=r.maxNodes??1e6,i=[],s=new Map,a=new Map,l=n(t);a.set(l,0);let u=[t];if(i.push(t),r.goal?.(t))return{order:i,cameFrom:s,dist:a};let c=0;for(;u.length>0&&c<o;){let m=[];for(let d of u){let h=a.get(n(d))??0;for(let p of e(d)){let f=n(p);if(!a.has(f)){if(a.set(f,h+1),s.set(f,d),i.push(p),c++,r.goal?.(p))return{order:i,cameFrom:s,dist:a};m.push(p)}}}u=m}return{order:i,cameFrom:s,dist:a}}function Cd(t,e,n,r){let o=[r],i=r,s=e(n);for(;e(i)!==s;){let a=t.get(e(i));if(a===void 0)return[];i=a,o.push(i)}return o.reverse(),o}function ba(t,e,n,r,o={}){let i=o.heuristic??(()=>0),s=o.maxNodes??1e6,a=new Map,l=new Map,u=new Jo,c=r(t);l.set(c,0),u.push(t,i(t));let m=0;for(;u.size>0&&m<s;){let{item:d,priority:h}=u.pop(),p=r(d),f=l.get(p)??1/0;if(!(h>f+i(d)+1e-9)){if(e(d))return{path:Td(a,r,d),cost:f};m++;for(let g of n(d)){let k=r(g.node),v=f+g.cost;v<(l.get(k)??1/0)&&(l.set(k,v),a.set(k,d),u.push(g.node,v+i(g.node)))}}}return null}function Td(t,e,n){let r=[n],o=n,i=t.get(e(o));for(;i!==void 0;)o=i,r.push(o),i=t.get(e(o));return r.reverse(),r}var Jo=class{items=[];prio=[];seq=[];counter=0;get size(){return this.items.length}push(e,n){this.items.push(e),this.prio.push(n),this.seq.push(this.counter++),this.bubbleUp(this.items.length-1)}pop(){let e=this.items[0],n=this.prio[0],r=this.items.length-1;return this.swap(0,r),this.items.pop(),this.prio.pop(),this.seq.pop(),this.items.length>0&&this.bubbleDown(0),{item:e,priority:n}}less(e,n){return this.prio[e]<this.prio[n]||this.prio[e]===this.prio[n]&&this.seq[e]<this.seq[n]}bubbleUp(e){for(;e>0;){let n=e-1>>1;if(!this.less(e,n))break;this.swap(e,n),e=n}}bubbleDown(e){let n=this.items.length;for(;;){let r=2*e+1,o=2*e+2,i=e;if(r<n&&this.less(r,i)&&(i=r),o<n&&this.less(o,i)&&(i=o),i===e)break;this.swap(e,i),e=i}}swap(e,n){[this.items[e],this.items[n]]=[this.items[n],this.items[e]],[this.prio[e],this.prio[n]]=[this.prio[n],this.prio[e]],[this.seq[e],this.seq[n]]=[this.seq[n],this.seq[e]]}},gn=[{x:0,y:-1},{x:1,y:0},{x:0,y:1},{x:-1,y:0}],nr=[...gn,{x:1,y:-1},{x:1,y:1},{x:-1,y:1},{x:-1,y:-1}],ga=t=>`${t.x},${t.y}`;function Md(t,e,n,r){let o=r?nr:gn;return i=>{let s=[];for(let a of o){let l=i.x+a.x,u=i.y+a.y;l<0||u<0||l>=e||u>=n||t(l,u)&&s.push({x:l,y:u})}return s}}function Yo(t,e,n){if(!e(t.x,t.y))return[];let r=Md(e,n.cols,n.rows,n.diagonal??!1);return fa(t,r,ga).order}function Rd(t,e,n,r=!1){let o=new Array(t*e).fill(-1),i=[],s=r?nr:gn;for(let a=0;a<e;a++)for(let l=0;l<t;l++){if(o[a*t+l]!==-1||!n(l,a))continue;let u=i.length,c=[],m=[{x:l,y:a}];for(o[a*t+l]=u;m.length>0;){let d=[];for(let h of m){c.push(h);for(let p of s){let f=h.x+p.x,g=h.y+p.y;if(f<0||g<0||f>=t||g>=e)continue;let k=g*t+f;o[k]!==-1||!n(f,g)||(o[k]=u,d.push({x:f,y:g}))}}m=d}i.push(c)}return{labels:o,cells:i}}function Pd(t,e,n,r){let o=r.diagonal??!1,i=o?nr:gn,s=r.cost??(()=>1),a=1.4142135623730951,l=m=>{let d=[];for(let h of i){let p=m.x+h.x,f=m.y+h.y;if(p<0||f<0||p>=r.cols||f>=r.rows||!n(p,f))continue;let g=h.x!==0&&h.y!==0;d.push({node:{x:p,y:f},cost:s(p,f)*(g?a:1)})}return d},u=m=>{let d=Math.abs(m.x-e.x),h=Math.abs(m.y-e.y);if(!o)return d+h;let p=Math.min(d,h);return d+h-(2-a)*p};if(!n(e.x,e.y))return null;let c=ba(t,m=>m.x===e.x&&m.y===e.y,l,ga,{heuristic:u,maxNodes:r.maxNodes});return c?c.path:null}function Dd(t){return(e,n)=>pe(t,e,n)!==U.SOLID}function Ed(t){return structuredClone(t)}var Ko=class{history=[];cursor=-1;limit;clone;constructor(e={}){this.limit=Math.max(1,e.limit??64),this.clone=e.clone??Ed}record(e){if(this.history.length=this.cursor+1,this.history.push(this.clone(e)),this.cursor=this.history.length-1,this.history.length>this.limit){let n=this.history.length-this.limit;this.history.splice(0,n),this.cursor-=n}}undo(){if(!(this.cursor<=0))return this.cursor--,this.clone(this.history[this.cursor])}redo(){if(!(this.cursor>=this.history.length-1))return this.cursor++,this.clone(this.history[this.cursor])}current(){return this.cursor>=0?this.clone(this.history[this.cursor]):void 0}get canUndo(){return this.cursor>0}get canRedo(){return this.cursor<this.history.length-1}get size(){return this.history.length}clear(){this.history.length=0,this.cursor=-1}},Qo=class{constructor(e){this.capacity=e;if(!Number.isInteger(e)||e<1)throw new Error("hayao: RingBuffer capacity must be a positive integer");this.buf=new Array(e)}capacity;buf;start=0;count=0;push(e){let n=(this.start+this.count)%this.capacity;this.buf[n]=e,this.count<this.capacity?this.count++:this.start=(this.start+1)%this.capacity}get length(){return this.count}get isFull(){return this.count===this.capacity}at(e){if(!(e<0||e>=this.count))return this.buf[(this.start+e)%this.capacity]}latest(){return this.at(this.count-1)}toArray(){let e=[];for(let n=0;n<this.count;n++)e.push(this.buf[(this.start+n)%this.capacity]);return e}clear(){this.start=0,this.count=0,this.buf.fill(void 0)}};var rr=class{map=new Map;get(e){return this.map.has(e)?this.map.get(e):null}set(e,n){this.map.set(e,n)}remove(e){this.map.delete(e)}keys(){return[...this.map.keys()]}},Zo=class{get(e){return null}set(e,n){}remove(e){}keys(){return[]}},or=class{constructor(e="hayao.save."){this.prefix=e}prefix;ls(){try{return typeof localStorage<"u"?localStorage:null}catch{return null}}get(e){try{return this.ls()?.getItem(this.prefix+e)??null}catch{return null}}set(e,n){try{this.ls()?.setItem(this.prefix+e,n)}catch{}}remove(e){try{this.ls()?.removeItem(this.prefix+e)}catch{}}keys(){let e=this.ls();if(!e)return[];let n=[];try{for(let r=0;r<e.length;r++){let o=e.key(r);o&&o.startsWith(this.prefix)&&n.push(o.slice(this.prefix.length))}}catch{}return n}};function ei(t){try{if(typeof localStorage<"u"){let e="__hayao_probe__";return localStorage.setItem(e,"1"),localStorage.removeItem(e),new or(t)}}catch{}return new rr}function Id(t){let e="",n=0;for(;n<t.length;){let r=t[n],o=1;for(;n+o<t.length&&t[n+o]===r;)o++;o>=4||r==="~"?e+="~"+r+o.toString(36)+"~":e+=r.repeat(o),n+=o}return e}function Ld(t){let e="",n=0;for(;n<t.length;)if(t[n]==="~"){let r=t[n+1],o=t.indexOf("~",n+2);if(r===void 0||o<0)throw new Error("hayao: malformed RLE stream");let i=parseInt(t.slice(n+2,o),36);if(!Number.isFinite(i)||i<1)throw new Error("hayao: malformed RLE count");e+=r.repeat(i),n=o+1}else e+=t[n],n++;return e}var ti="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",ya={};for(let t=0;t<ti.length;t++)ya[ti[t]]=t;function $d(t){let e="";for(let n of t){if(!Number.isInteger(n)||n<0)throw new Error(`hayao: packVarints expects non-negative integers, got ${n}`);let r=n;do{let o=r&31;r=Math.floor(r/32),r>0&&(o|=32),e+=ti[o]}while(r>0)}return e}function Nd(t){let e=[],n=0,r=1;for(let o of t){let i=ya[o];if(i===void 0)throw new Error(`hayao: unpackVarints saw invalid char "${o}"`);n+=(i&31)*r,i&32?r*=32:(e.push(n),n=0,r=1)}if(r!==1)throw new Error("hayao: unpackVarints hit a truncated stream");return e}var oi=1;function xa(t){return JSON.stringify({v:oi,snap:t})}function ni(t){if(!t)return null;let e;try{e=JSON.parse(t)}catch{return null}if(!e||typeof e!="object")return null;let n=e;if(n.v!==oi||!n.snap||typeof n.snap!="object")return null;let r=n.snap;return typeof r.seed!="number"||!r.rng||!r.clock||!r.input||!r.state||!r.tree?null:r}var ri=class{constructor(e,n=ei()){this.world=e;this.storage=n}world;storage;save(e="auto"){this.storage.set(e,xa(this.world.snapshot()))}load(e="auto"){let n=ni(this.storage.get(e));return n?(this.world.restore(n),!0):!1}has(e="auto"){return ni(this.storage.get(e))!==null}delete(e="auto"){this.storage.remove(e)}slots(){return this.storage.keys()}};function Fd(t){return{next:t.map(e=>e.time)}}function Ad(t,e,n,r){let o=[];for(let i=0;i<t.length;i++){let s=t[i],a=e.next[i]??s.time;for(;a<=n;){let l;if(typeof s.spawn=="string")l=s.spawn;else{if(!r)throw new Error("hayao: pollDirector needs an Rng to roll a weighted wave");l=Xo(r,s.spawn)}if(o.push({spawn:l,count:s.count??1,wave:i}),s.every&&s.every>0){if(a+=s.every,s.end!==void 0&&a>=s.end){a=1/0;break}}else{a=1/0;break}}e.next[i]=a}return o}function Wd(t,e){let n=new Map;for(let o of e)n.set(o,(n.get(o)??0)+1);let r=o=>(n.get(o)??0)>0;return t.filter(o=>(n.get(o.id)??0)>=(o.maxStacks??1)?!1:(o.requires??[]).every(r))}var Bd=new Set(["#","-","^","."," "]),yn=t=>t===U.SOLID,zd=t=>t===U.HAZARD,va=(t,e,n)=>({x:(t+.5)*n,y:(e+.5)*n});function _d(t){let e=t.tileSize??32,n=t.legend??{},r=t.rows,o=Math.max(0,...r.map(l=>l.length)),i=null,s=null,a=[];if(r.forEach((l,u)=>{for(let c=0;c<l.length;c++){let m=l[c];if(m==="S")i={x:c,y:u};else if(m==="G")s={x:c,y:u};else if(m in n){let d=va(c,u,e);a.push({kind:n[m],tx:c,ty:u,x:d.x,y:d.y})}}}),!i)throw new Error(`level "${t.name}": no spawn marker 'S'`);if(!s)throw new Error(`level "${t.name}": no goal marker 'G'`);return{name:t.name,tileSize:e,rows:r,legend:n,cols:o,rowCount:r.length,spawn:i,goal:s,entities:a}}function Od(t){let e=[],n=ir(t),r=o=>n.tiles[o.y*n.cols+o.x]??U.EMPTY;return t.rows.forEach((o,i)=>{for(let s=0;s<o.length;s++){let a=o[s];a==="S"||a==="G"||Bd.has(a)||a in t.legend||e.push(`unknown glyph '${a}' at (${s},${i}) \u2014 add it to the legend or use terrain '#/-/^/.'`)}}),yn(r(t.spawn))&&e.push(`spawn (${t.spawn.x},${t.spawn.y}) is inside a solid tile`),yn(r(t.goal))&&e.push(`goal (${t.goal.x},${t.goal.y}) is inside a solid tile`),[...new Set(e)]}function ir(t){return _r(t.rows,t.tileSize)}function Gd(t,e={}){let n=ir(t),r=(l,u)=>n.tiles[u*n.cols+l]??U.EMPTY,o=e.passable??((l,u)=>!yn(r(l,u))),i=Yo(t.spawn,o,{cols:n.cols,rows:n.rows,diagonal:e.diagonal}),s=new Set(i.map(l=>`${l.x},${l.y}`)),a=[];s.has(`${t.goal.x},${t.goal.y}`)||a.push("goal");for(let l of t.entities)s.has(`${l.tx},${l.ty}`)||a.push(`entity@${l.tx},${l.ty}`);return{ok:a.length===0,unreachable:a,reached:i.length}}function Vd(t,e){let n=ir(t),{cols:r,rows:o}=n,i=(v,M)=>v<0||M<0||v>=r||M>=o?U.SOLID:n.tiles[M*r+v],s=(v,M)=>{let I=i(v,M+1);return I===U.SOLID||I===U.ONEWAY},a=(v,M)=>!yn(i(v,M))&&!zd(i(v,M))&&s(v,M),u=(v=>{for(let M=v.y;M<o;M++)if(a(v.x,M))return{x:v.x,y:M};return null})(t.spawn);if(!u)return{ok:!1,unreachable:["goal"],reached:0};let c=(v,M)=>Math.abs(M.x-v.x)<=e.runTiles&&v.y-M.y<=e.jumpTiles,m=[];for(let v=0;v<o;v++)for(let M=0;M<r;M++)a(M,v)&&m.push({x:M,y:v});let d=v=>`${v.x},${v.y}`,h=new Set([d(u)]),p=[u];for(;p.length;){let v=p.shift();for(let M of m){let I=d(M);!h.has(I)&&c(v,M)&&(h.add(I),p.push(M))}}let f=[...h].map(v=>{let[M,I]=v.split(",").map(Number);return{x:M,y:I}}),k=!yn(i(t.goal.x,t.goal.y))&&(h.has(d(t.goal))||f.some(v=>c(v,t.goal)))?[]:["goal"];return{ok:k.length===0,unreachable:k,reached:h.size}}function Hd(t,e){let n=[],r=Math.max(t.rowCount,e.rowCount),o=Math.max(t.cols,e.cols),i=(u,c,m)=>u.rows[m]?.[c]??" ";for(let u=0;u<r;u++)for(let c=0;c<o;c++){let m=i(t,c,u),d=i(e,c,u);m!==d&&n.push({kind:"tile",detail:`(${c},${u}) '${m}' \u2192 '${d}'`})}let s=u=>`${u.kind}@${u.tx},${u.ty}`,a=new Set(t.entities.map(s)),l=new Set(e.entities.map(s));for(let u of e.entities)a.has(s(u))||n.push({kind:"entity+",detail:s(u)});for(let u of t.entities)l.has(s(u))||n.push({kind:"entity-",detail:s(u)});return(t.spawn.x!==e.spawn.x||t.spawn.y!==e.spawn.y)&&n.push({kind:"spawn",detail:`(${t.spawn.x},${t.spawn.y}) \u2192 (${e.spawn.x},${e.spawn.y})`}),(t.goal.x!==e.goal.x||t.goal.y!==e.goal.y)&&n.push({kind:"goal",detail:`(${t.goal.x},${t.goal.y}) \u2192 (${e.goal.x},${e.goal.y})`}),n}function wa(t,e){return br(`hayao/gen:${t>>>0}:${e}`)}var qd=(t,e,n)=>(n.minDepth===void 0||t>=n.minDepth)&&(n.maxDepth===void 0||t<=n.maxDepth)&&(n.minNodes===void 0||e>=n.minNodes)&&(n.maxNodes===void 0||e<=n.maxNodes);function ka(t,e){let n=e.seed??1,r=e.maxAttempts??e.count*60,o=e.dedupeKey??(u=>u.key(u.initial())),i=[],s=new Set,a=0,l=0;for(let u=0;u<r&&i.length<e.count;u++){a++;let c=wa(n,u),m=t(new ue(c)),d=mt(m,e.solve);if(!d.solvable||d.exhausted||d.depth===void 0)continue;l++;let h={path:d.path??[],depth:d.depth,nodes:d.nodes};if(!qd(h.depth,h.nodes,e))continue;let p=o(m,h);s.has(p)||e.reject?.(m,h,c)||(s.add(p),i.push({...h,index:0,seed:c,puzzle:m}))}return i.sort((u,c)=>u.depth-c.depth||u.nodes-c.nodes||u.seed-c.seed),i.forEach((u,c)=>u.index=c),{levels:i,attempts:a,solvable:l,complete:i.length>=e.count,seeds:i.map(u=>u.seed)}}function ii(t,e){let n=ka(t,e);if(!n.complete)throw new Error(`hayao: generator found only ${n.levels.length}/${e.count} in-band levels in ${n.attempts} attempts (${n.solvable} solvable). Widen the band [depth ${e.minDepth??0}..${e.maxDepth??"\u221E"}] or raise maxAttempts.`);return n.levels}function jd(t,e){return t(new ue(e))}function Ud(t){let e=t.seed??1,n=t.minutesPerLevel??1.5,r=[],o=[];return t.acts.forEach((i,s)=>{let a=i.factory??t.factory;if(!a)throw new Error(`hayao: act "${i.name}" has no factory and the campaign has no default`);let l=(e^(s+1)*2654435769)>>>0,u=ii(a,{count:i.count,seed:l,minDepth:i.minDepth,maxDepth:i.maxDepth,minNodes:i.minNodes,maxNodes:i.maxNodes,solve:i.solve??t.solve,maxAttempts:i.maxAttempts}),c=r.length;u.forEach((m,d)=>{r.push({...m,index:r.length,act:s,actName:i.name,actIndex:d})}),o.push({name:i.name,from:c,to:r.length-1})}),{levels:r,acts:o,difficulty:r.map(i=>i.depth),seeds:r.map(i=>i.seed),estMinutes:r.length*n}}function Ca(t,e){let n=new Map(t.pickups.map(o=>[o.id,o.grants])),r=new Set;for(let o of e){let i=n.get(o);i&&r.add(i)}return r}function Sa(t,e){return(t.requires??[]).every(n=>e.has(n))}function Ta(t,e,n){let r=[];for(let o of t.edges)o.from===e&&Sa(o,n)?r.push(o.to):!o.oneWay&&o.to===e&&Sa(o,n)&&r.push(o.from);return r}function sr(t,e="complete"){let n=o=>t.pickups.filter(i=>i.region===o),r=t.pickups.length;return{initial:()=>({region:t.start,taken:[]}),moves:o=>{let i=Ca(t,o.taken),s=[];for(let l of n(o.region))o.taken.includes(l.id)||s.push({kind:"take",pickup:l.id});let a=new Set;for(let l of Ta(t,o.region,i))a.has(l)||(a.add(l),s.push({kind:"move",to:l}));return s},apply:(o,i)=>{if(i.kind==="move")return{region:i.to,taken:o.taken};let s=[...o.taken,i.pickup].sort();return{region:o.region,taken:s}},isWin:o=>o.region===t.goal&&(e==="complete"||o.taken.length===r),key:o=>`${o.region}|${o.taken.join(",")}`}}var Ma={maxDepth:2e3,nodeCap:5e6};function Xd(t){return mt(sr(t,"complete"),Ma)}function Jd(t){return mt(sr(t,"full"),Ma)}function Ra(t,e){let n=new Set(e),r=new Set([t.start]),o=[t.start];for(;o.length;){let i=o.shift();for(let s of Ta(t,i,n))r.has(s)||(r.add(s),o.push(s))}return[...r]}function Yd(t,e="complete"){let n=sr(t,e),r=n.initial(),o=n.key(r),i=new Map([[o,r]]),s=new Map,a=new Set,l=[r];for(n.isWin(r)&&a.add(o);l.length;){let h=l.shift(),p=n.key(h),f=[];for(let g of n.moves(h)){let k=n.apply(h,g),v=n.key(k);f.push(v),i.has(v)||(i.set(v,k),n.isWin(k)&&a.add(v),l.push(k))}s.set(p,f)}let u=new Map;for(let[h,p]of s)for(let f of p)(u.get(f)??u.set(f,[]).get(f)).push(h);let c=new Set(a),m=[...a];for(;m.length;){let h=m.shift();for(let p of u.get(h)??[])c.has(p)||(c.add(p),m.push(p))}let d=[...i.keys()].filter(h=>!c.has(h)).sort();return{ok:d.length===0,deadEnds:d,statesExplored:i.size}}function Kd(t){let e=[],n=new Set;for(let a of t.regions)n.has(a.id)&&e.push(`duplicate region id "${a.id}"`),n.add(a.id);let r=a=>n.has(a);r(t.start)||e.push(`start region "${t.start}" is not defined`),r(t.goal)||e.push(`goal region "${t.goal}" is not defined`);for(let a of t.edges)r(a.from)||e.push(`edge references unknown region "${a.from}"`),r(a.to)||e.push(`edge references unknown region "${a.to}"`);let o=new Set;for(let a of t.pickups)o.has(a.id)&&e.push(`duplicate pickup id "${a.id}"`),o.add(a.id),r(a.region)||e.push(`pickup "${a.id}" is in unknown region "${a.region}"`);let i=t.pickups.map(a=>a.grants),s=new Set(Ra(t,i));for(let a of t.regions)s.has(a.id)||e.push(`region "${a.id}" is unreachable even with every ability`);return e}function Qd(t){let e=[];for(let n=1;n<=t;n++)e.push(`p${n}`);return e}var xn=(t,e)=>`${t}:${e}`;function $t(t,e){let n=[];for(let r of t){let o=e.get(r)??[];for(let i of o)n.push(xn(r,i))}return n.sort()}var ar=class{constructor(e,n){this.world=e;this.player=n}world;player;isDown(e){return this.world.input.isDown(xn(this.player,e))}justPressed(e){return this.world.input.justPressed(xn(this.player,e))}justReleased(e){return this.world.input.justReleased(xn(this.player,e))}},Zd=(t,e)=>new ar(t,e);var Zg=1,dt={mode:"lockstep",inputDelay:2,hashInterval:20,maxRollback:12,redundancy:3};function de(t){return JSON.stringify(t)}function Oe(t){try{let e=JSON.parse(t);return!e||typeof e!="object"||e.v!==1||typeof e.t!="string"?null:e}catch{return null}}function he(t){return{v:1,...t}}var si=class{peers=[];queue=[];tickCount=0;seq=0;sent=0;delay;dropEvery;constructor(e={}){this.delay=e.delay??0,this.dropEvery=e.dropEvery??0}connect(){let e=new lr(this,this.peers.length);return this.peers.push(e),e}enqueue(e,n){this.sent++,!(this.dropEvery>0&&this.sent%this.dropEvery===0)&&this.queue.push({data:e,from:n,dueTick:this.tickCount+this.delay,seq:this.seq++})}tick(){let e=this.queue.filter(n=>n.dueTick<=this.tickCount).sort((n,r)=>n.seq-r.seq);this.queue=this.queue.filter(n=>n.dueTick>this.tickCount),this.tickCount++;for(let n of e)for(let r of this.peers)r.peerIndex!==n.from&&r.isOpen&&r.deliver(n.data)}flush(){for(;this.queue.length>0;)this.tick()}get pending(){return this.queue.length}},lr=class{constructor(e,n){this.hub=e;this.peerIndex=n}hub;peerIndex;listeners=[];closeListeners=[];open=!0;send(e){this.open&&this.hub.enqueue(e,this.peerIndex)}onMessage(e){return this.listeners.push(e),()=>{this.listeners=this.listeners.filter(n=>n!==e)}}onClose(e){return this.closeListeners.push(e),()=>{this.closeListeners=this.closeListeners.filter(n=>n!==e)}}close(){if(this.open){this.open=!1;for(let e of this.closeListeners)e()}}get isOpen(){return this.open}deliver(e){for(let n of this.listeners)n(e)}},ai=class{channel;listeners=[];closeListeners=[];open=!0;constructor(e){this.channel=new BroadcastChannel(`hayao-net:${e}`),this.channel.onmessage=n=>{if(typeof n.data=="string")for(let r of this.listeners)r(n.data)}}send(e){this.open&&this.channel.postMessage(e)}onMessage(e){return this.listeners.push(e),()=>{this.listeners=this.listeners.filter(n=>n!==e)}}onClose(e){return this.closeListeners.push(e),()=>{this.closeListeners=this.closeListeners.filter(n=>n!==e)}}close(){if(this.open){this.open=!1,this.channel.close();for(let e of this.closeListeners)e()}}get isOpen(){return this.open}};function eh(t){return new Promise((e,n)=>{let r=new WebSocket(t),o=[],i=[],s=!1,a={send(l){s&&r.send(l)},onMessage(l){return o.push(l),()=>{let u=o.indexOf(l);u>=0&&o.splice(u,1)}},onClose(l){return i.push(l),()=>{let u=i.indexOf(l);u>=0&&i.splice(u,1)}},close(){s=!1,r.close()},get isOpen(){return s}};r.onopen=()=>{s=!0,e(a)},r.onmessage=l=>{if(typeof l.data=="string")for(let u of o)u(l.data)},r.onclose=()=>{let l=s;if(s=!1,l)for(let u of i)u()},r.onerror=()=>{s||n(new Error(`hayao-net: could not connect to ${t}`))}})}var ht=class{frames=new Map;contiguous=new Map;addPlayer(e){this.frames.has(e)||(this.frames.set(e,new Map),this.contiguous.set(e,-1))}removePlayer(e){this.frames.delete(e),this.contiguous.delete(e)}players(){return[...this.frames.keys()]}set(e,n,r){let o=this.frames.get(e);if(!o||o.has(n))return!1;o.set(n,[...r].sort());let i=this.contiguous.get(e)??-1;for(;o.has(i+1);)i++;return this.contiguous.set(e,i),!0}has(e,n){return this.frames.get(e)?.has(n)??!1}get(e,n){return this.frames.get(e)?.get(n)}latestAt(e,n){let r=this.frames.get(e);if(!r)return[];for(let o=n;o>=0;o--){let i=r.get(o);if(i)return i}return[]}contiguousThrough(e){return this.contiguous.get(e)??-1}confirmedFrame(){let e=1/0;for(let n of this.contiguous.values())e=Math.min(e,n);return e===1/0?-1:e}clearFrom(e,n){let r=this.frames.get(e);if(!r)return;for(let i of r.keys())i>=n&&r.delete(i);let o=this.contiguous.get(e)??-1;o>=n&&(o=n-1),this.contiguous.set(e,o)}prune(e){for(let n of this.frames.values())for(let r of n.keys())r<e&&n.delete(r)}};var Ie=class{world;localPlayer;config;startFrame;transport;buffer=new ht;roster=[];mergedLog=[];localHashes=new Map;pendingRemoteHashes=[];sentThrough;stallCount=0;desynced=!1;afterStepListeners=[];unsubscribe;onDesync;onStall;constructor(e){this.world=e.world,this.transport=e.transport,this.localPlayer=e.localPlayer,this.config={...dt,...e.config,mode:"lockstep"},this.startFrame=e.startFrame??0,this.onDesync=e.onDesync,this.onStall=e.onStall;for(let n of e.players)if(this.roster.push({player:n,from:this.startFrame,until:1/0}),this.buffer.addPlayer(n),this.startFrame===0||n===this.localPlayer)for(let r=this.startFrame;r<this.startFrame+this.config.inputDelay;r++)this.buffer.set(n,r,[]);this.sentThrough=this.startFrame+this.config.inputDelay-1,this.unsubscribe=this.transport.onMessage(n=>this.receive(n))}activePlayers(e){return this.roster.filter(n=>n.from<=e&&e<n.until).map(n=>n.player)}addPlayer(e,n){if(!this.roster.some(r=>r.player===e&&r.until===1/0)){this.roster.push({player:e,from:n,until:1/0}),this.buffer.addPlayer(e);for(let r=n;r<n+this.config.inputDelay;r++)this.buffer.set(e,r,[])}}removePlayer(e,n){let r=this.roster.find(o=>o.player===e&&o.until===1/0);r&&(r.until=n),this.buffer.clearFrom(e,n)}get frame(){return this.world.frame}get confirmedFrame(){let e=1/0;for(let n of this.activePlayers(this.world.frame))e=Math.min(e,this.buffer.contiguousThrough(n));return e===1/0?-1:e}get stalls(){return this.stallCount}tick(e=[]){if(this.desynced)return 0;let n=this.world.frame;this.scheduleLocal(e);let r=this.activePlayers(n);for(let s of r)if(!this.buffer.has(s,n))return this.stallCount++,this.onStall?.(s,n),0;let o=new Map;for(let s of r)o.set(s,this.buffer.get(s,n));let i=$t(r,o);return this.world.step(i),this.mergedLog.push(i),this.afterStep(this.world.frame),1}advance(e,n=[]){let r=0,o=this.world.clock.advance(e);for(let s=0;s<o&&this.tick(n)!==0;s++)r++;let i=0;for(;i++<8&&this.world.frame<this.remoteFrameEstimate()&&this.tick(n)===1;)r++;return r}inputLog(){return{frames:this.mergedLog.map(e=>e.slice())}}dispose(){this.unsubscribe()}deliver(e){this.receive(e)}onAfterStep(e){return this.afterStepListeners.push(e),()=>{this.afterStepListeners=this.afterStepListeners.filter(n=>n!==e)}}scheduleLocal(e){let n=this.world.frame+this.config.inputDelay;if(this.sentThrough>=n)return;for(;this.sentThrough<n;)this.sentThrough++,this.buffer.set(this.localPlayer,this.sentThrough,e);let r=Math.max(this.startFrame,n-this.config.redundancy+1),o=[];for(let i=r;i<=n;i++)o.push(this.buffer.get(this.localPlayer,i)??[]);this.transport.send(de(he({t:"input",player:this.localPlayer,from:r,frames:o})))}afterStep(e){if(e%this.config.hashInterval===0){let n=this.world.hash();this.localHashes.set(e,n),this.transport.send(de(he({t:"hash",player:this.localPlayer,frame:e,hash:n}))),this.checkPendingHashes()}if(e%64===0){this.buffer.prune(e-128);for(let n of this.localHashes.keys())n<e-512&&this.localHashes.delete(n)}for(let n of this.afterStepListeners)n(e)}receive(e){let n=Oe(e);if(n)if(n.t==="input"&&n.player!==this.localPlayer)for(let r=0;r<n.frames.length;r++)this.buffer.set(n.player,n.from+r,n.frames[r]);else n.t==="hash"&&n.player!==this.localPlayer&&(this.pendingRemoteHashes.push({player:n.player,frame:n.frame,hash:n.hash}),this.checkPendingHashes())}checkPendingHashes(){let e=[];for(let n of this.pendingRemoteHashes){let r=this.localHashes.get(n.frame);if(r===void 0){n.frame>this.world.frame-512&&e.push(n);continue}r!==n.hash&&!this.desynced&&(this.desynced=!0,this.onDesync?.({frame:n.frame,player:n.player,localHash:r,remoteHash:n.hash,log:this.inputLog(),startFrame:this.startFrame}))}this.pendingRemoteHashes=e}remoteFrameEstimate(){let e=-1;for(let n of this.roster)n.player===this.localPlayer||n.until!==1/0||(e=Math.max(e,this.buffer.contiguousThrough(n.player)-this.config.inputDelay));return e}};var vn=class{world;localPlayer;config;transport;players;buffer=new ht;attach;onDesync;onRollbackOverflow;ring;usedInputs=new Map;earliestBad=1/0;rollbackCount=0;resimulatedFrames=0;localHashes=new Map;dropped=new Map;pendingRemoteHashes=[];hashedThrough=-1;desynced=!1;overflowed=!1;unsubscribe;constructor(e){this.world=e.world,this.transport=e.transport,this.localPlayer=e.localPlayer,this.players=[...e.players],this.config={...dt,mode:"rollback",inputDelay:0,...e.config},this.attach=e.attach,this.onDesync=e.onDesync,this.onRollbackOverflow=e.onRollbackOverflow,this.ring=new Array(this.config.maxRollback+1).fill(null);for(let n of this.players)this.buffer.addPlayer(n);this.unsubscribe=this.transport.onMessage(n=>this.receive(n))}get frame(){return this.world.frame}get confirmedFrame(){let e=1/0;for(let n of this.players){let r=this.dropped.get(n),o=this.buffer.contiguousThrough(n);r!==void 0&&o>=r-1&&(o=1/0),e=Math.min(e,o)}return e===1/0?-1:e}lastKnownFrame(e){return this.buffer.contiguousThrough(e)}removePlayer(e,n){if(!(e===this.localPlayer||this.dropped.has(e))){this.dropped.set(e,n),this.buffer.clearFrom(e,n);for(let r=n;r<this.world.frame;r++){let o=this.usedInputs.get(r)?.get(e);o!==void 0&&o!=="[]"&&(this.earliestBad=Math.min(this.earliestBad,r))}this.settleHashes()}}get stats(){return{rollbacks:this.rollbackCount,resimulatedFrames:this.resimulatedFrames}}tick(e=[]){if(this.desynced||this.overflowed)return 0;let n=this.world.frame;return n-(this.confirmedFrame+1)>=this.config.maxRollback||(this.publishLocal(n,e),!this.resolveCorrections())?0:(this.storeSnapshot(n),this.stepFrame(n),this.settleHashes(),n%64===0&&this.pruneOld(n),1)}advance(e,n=[]){let r=0,o=this.world.clock.advance(e);for(let i=0;i<o&&this.tick(n)!==0;i++)r++;return r}inputLog(){let e=[],n=this.confirmedFrame;for(let r=0;r<=n;r++){let o=new Map;for(let i of this.players)o.set(i,this.buffer.get(i,r)??[]);e.push($t(this.players,o))}return{frames:e}}dispose(){this.unsubscribe()}deliver(e){this.receive(e)}publishLocal(e,n){if(!this.buffer.set(this.localPlayer,e,n))return;let r=Math.max(0,e-this.config.redundancy+1),o=[];for(let i=r;i<=e;i++)o.push(this.buffer.get(this.localPlayer,i)??[]);this.transport.send(de(he({t:"input",player:this.localPlayer,from:r,frames:o})))}inputsFor(e){let n=new Map;for(let r of this.players){let o=this.dropped.get(r);o!==void 0&&e>=o?n.set(r,[]):n.set(r,this.buffer.get(r,e)??this.buffer.latestAt(r,e))}return n}stepFrame(e){let n=this.inputsFor(e),r=new Map;for(let o of this.players)r.set(o,JSON.stringify(n.get(o)));this.usedInputs.set(e,r),this.world.step($t(this.players,n))}resolveCorrections(){if(this.earliestBad===1/0)return!0;let e=this.world.frame,n=this.earliestBad;this.earliestBad=1/0;let r=this.ring[n%this.ring.length];if(!r||r.frame!==n)return this.overflowed=!0,this.onRollbackOverflow?.(n),!1;this.rollbackCount++,this.world.restore(r.snap),this.attach?.(this.world);for(let o=n;o<e;o++)this.storeSnapshot(o),this.stepFrame(o),this.resimulatedFrames++;return!0}storeSnapshot(e){this.ring[e%this.ring.length]={frame:e,snap:this.world.snapshot()}}receive(e){let n=Oe(e);if(n)if(n.t==="input"&&n.player!==this.localPlayer){let r=this.dropped.get(n.player);for(let o=0;o<n.frames.length;o++){let i=n.from+o;if(!(r!==void 0&&i>=r)&&this.buffer.set(n.player,i,n.frames[o])&&i<this.world.frame){let s=this.usedInputs.get(i)?.get(n.player),a=JSON.stringify([...n.frames[o]].sort());s!==void 0&&s!==a&&(this.earliestBad=Math.min(this.earliestBad,i))}}this.settleHashes()}else n.t==="hash"&&n.player!==this.localPlayer&&(this.pendingRemoteHashes.push({player:n.player,frame:n.frame,hash:n.hash}),this.compareHashes())}settleHashes(){let e=Math.min(this.confirmedFrame+1,this.world.frame,this.earliestBad===1/0?1/0:this.earliestBad),n=this.config.hashInterval,r=(Math.floor(this.hashedThrough/n)+1)*n;for(;r<=e;r+=n){let o=this.ring[r%this.ring.length];if(!o||o.frame!==r)continue;let i=Bt(o.snap);this.localHashes.set(r,i),this.hashedThrough=r,this.transport.send(de(he({t:"hash",player:this.localPlayer,frame:r,hash:i})))}this.compareHashes()}compareHashes(){let e=[];for(let n of this.pendingRemoteHashes){let r=this.localHashes.get(n.frame);if(r===void 0){n.frame>this.hashedThrough-512&&e.push(n);continue}r!==n.hash&&!this.desynced&&(this.desynced=!0,this.onDesync?.({frame:n.frame,player:n.player,localHash:r,remoteHash:n.hash,log:this.inputLog(),startFrame:0}))}this.pendingRemoteHashes=e}pruneOld(e){this.buffer.prune(e-128);for(let n of this.usedInputs.keys())n<e-128&&this.usedInputs.delete(n);for(let n of this.localHashes.keys())n<e-512&&this.localHashes.delete(n)}};function th(){return globalThis.crypto.randomUUID()}function Pa(t,e,n,r,o,i,s,a,l){return t==="rollback"?new vn({world:e,transport:n,localPlayer:r,players:o,config:s,attach:a,onDesync:l.onDesync}):new Ie({world:e,transport:n,localPlayer:r,players:o,startFrame:i,config:s,onDesync:l.onDesync})}function Da(t,e,n,r,o){return{world:t,session:e,localPlayer:n,players:r,advance:(i,s=[])=>e.advance(i,s),dispose:()=>{e.dispose(),o?.()}}}var ur=class{localPlayer="p1";seed;config;transport;makeWorld;maxPlayers;joinMargin;attach;callbacks;players=["p1"];uidToPlayer=new Map;nextPlayerIndex=2;started=!1;game=null;pendingSnapshots=[];unsubscribe;constructor(e){this.transport=e.transport,this.makeWorld=e.makeWorld,this.seed=e.seed??1,this.config={...dt,...e.config},this.maxPlayers=e.maxPlayers??4,this.joinMargin=e.joinMargin??30,this.attach=e.attach,this.callbacks=e,this.unsubscribe=this.transport.onMessage(n=>this.receive(n))}get roster(){return[...this.players]}get isStarted(){return this.started}start(){if(this.game)return this.game;this.started=!0;let e=this.makeWorld(this.seed),n=Pa(this.config.mode,e,this.transport,this.localPlayer,this.players,0,this.config,this.attach,this.callbacks);return n instanceof Ie&&n.onAfterStep(r=>this.serviceSnapshots(r,e)),this.transport.send(de(he({t:"start",players:[...this.players]}))),this.game=Da(e,n,this.localPlayer,this.players,()=>this.unsubscribe()),this.game}dropPlayer(e){let n=this.game?.session;if(!n)return;let r=n instanceof Ie?Math.max(n.frame,n.confirmedFrame+1):n.lastKnownFrame(e)+1;this.transport.send(de(he({t:"leave",player:e,atFrame:r}))),n.removePlayer(e,r),this.players=this.players.filter(o=>o!==e),this.callbacks.onPlayerLeave?.(e,r)}dispose(){this.unsubscribe(),this.game?.dispose()}receive(e){let n=Oe(e);if(n){if(n.t==="hello")this.handleHello(n);else if(n.t==="bye"){let r=this.uidToPlayer.get(n.uid);r&&this.started?this.dropPlayer(r):r&&(this.players=this.players.filter(o=>o!==r),this.uidToPlayer.delete(n.uid))}}}handleHello(e){if(this.uidToPlayer.has(e.uid))return;if(this.players.length>=this.maxPlayers){this.transport.send(de(he({t:"deny",to:e.uid,reason:"room full"})));return}if(this.started&&this.config.mode==="rollback"){this.transport.send(de(he({t:"deny",to:e.uid,reason:"rollback rooms cannot be joined mid-game"})));return}let n=`p${this.nextPlayerIndex++}`;if(this.uidToPlayer.set(e.uid,n),this.players.push(n),!this.started){this.transport.send(de(he({t:"welcome",to:e.uid,player:n,players:[...this.players],seed:this.seed,config:this.config,startFrame:0}))),this.callbacks.onPlayerJoin?.(n,0);return}let r=this.game.session,o=r.frame+this.joinMargin;this.transport.send(de(he({t:"join",player:n,atFrame:o}))),r.addPlayer(n,o),this.pendingSnapshots.push({uid:e.uid,player:n,atFrame:o}),this.callbacks.onPlayerJoin?.(n,o)}serviceSnapshots(e,n){if(this.pendingSnapshots.length===0)return;let r=this.pendingSnapshots.filter(i=>i.atFrame===e);if(r.length===0)return;this.pendingSnapshots=this.pendingSnapshots.filter(i=>i.atFrame!==e);let o=n.snapshot();for(let i of r){let s=this.pendingSnapshots.filter(l=>l.player!==i.player),a=new Set(s.map(l=>l.player));this.transport.send(de(he({t:"welcome",to:i.uid,player:i.player,players:this.players.filter(l=>!a.has(l)),seed:this.seed,config:this.config,startFrame:e,snapshot:o,joins:s.map(l=>({player:l.player,atFrame:l.atFrame}))})))}}};function li(t){let e=th(),n=t.transport;return new Promise((r,o)=>{let i=null,s=!1,a=null,l=[],u=[],c=()=>{if(!i||!s)return;m();let d=a??i.players,h=t.makeWorld(i.seed);i.snapshot&&(h.restore(i.snapshot),t.attach?.(h));let p=Pa(i.config.mode,h,n,i.player,d,i.startFrame,i.config,t.attach,t);if(i.joins&&p instanceof Ie)for(let k of i.joins)p.addPlayer(k.player,k.atFrame);for(let k of u)k.t==="join"&&p instanceof Ie&&p.addPlayer(k.player,k.atFrame),k.t==="leave"&&p.removePlayer(k.player,k.atFrame);let f=n.onMessage(k=>{let v=Oe(k);v&&(v.t==="join"&&p instanceof Ie?(p.addPlayer(v.player,v.atFrame),t.onPlayerJoin?.(v.player,v.atFrame)):v.t==="leave"&&(p.removePlayer(v.player,v.atFrame),t.onPlayerLeave?.(v.player,v.atFrame)))}),g=Da(h,p,i.player,d,()=>{f(),n.send(de(he({t:"bye",uid:e})))});for(let k of l)p.deliver(k);r(g)},m=n.onMessage(d=>{let h=Oe(d);if(h)switch(h.t){case"welcome":h.to===e&&(i=h,(h.snapshot||h.startFrame>0)&&(s=!0),c());break;case"deny":h.to===e&&(m(),o(new Error(`hayao-net: join denied \u2014 ${h.reason}`)));break;case"start":s=!0,a=h.players,c();break;case"join":case"leave":u.push(h);break;case"input":case"hash":l.push(d);break}});n.send(de(he({t:"hello",uid:e,name:t.name})))})}function ui(t){return new ur(t)}function nh(t,e,n){let r=t.width??1280,o=t.height??720,i=t.background??"#f3ecdb",s=n.renderer==="canvas"?new lt({width:r,height:o,background:i}):new at({width:r,height:o,background:i});e.style.position=e.style.position||"relative",s.mount?.(e),un(e);let a=new et(t.inputMap??{},document),l=f=>Te(t,f),u=null,c=null,m=0,d=!1,h=f=>g=>{!d&&u&&(u.advance(g-f,a.currentActions())>0&&a.clearPressed(),s.draw(u.world.render())),m=requestAnimationFrame(h(g))},p=f=>{u=f,n.onStatus?.(`playing as ${f.localPlayer} (${f.players.length} players)`),m=requestAnimationFrame(h(performance.now()))};return n.role==="host"?(c=ui({transport:n.transport,makeWorld:l,seed:n.seed??t.seed??1,config:n.config,maxPlayers:n.maxPlayers,attach:n.attach,onDesync:n.onDesync,onPlayerJoin:(f,g)=>{n.onStatus?.(`${f} joined`),n.onPlayerJoin?.(f,g)},onPlayerLeave:n.onPlayerLeave}),n.onStatus?.("hosting \u2014 waiting for players")):(n.onStatus?.("joining\u2026"),li({transport:n.transport,makeWorld:l,attach:n.attach,onDesync:n.onDesync,onPlayerJoin:n.onPlayerJoin,onPlayerLeave:n.onPlayerLeave}).then(p).catch(f=>n.onStatus?.(f.message))),{start(){c&&!u&&p(c.start())},get game(){return u},get localPlayer(){return u?.localPlayer??(n.role==="host"?"p1":null)},get roster(){return c?.roster??u?.players??[]},input:a,stop(){d=!0,cancelAnimationFrame(m),u?.dispose(),c?.dispose(),a.dispose(),s.dispose?.()}}}var rh=0;function oh(t,e){return`${t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"game"}-${e.replace(/[:.]/g,"-").toLowerCase()}-${(rh++).toString(36)}`}var pt=class{frames=[];axesLog=[];lastAxes=new Map;knobEvents=[];screenEvents=[];wallClockMarks=[];annotations=[];init;startedAt;id;buildRef;constructor(e){this.init=e,this.startedAt=e.startedAt??new Date().toISOString(),this.id=e.id??oh(e.game,this.startedAt),this.buildRef=e.buildRef??"unknown"}get frame(){return this.frames.length}get liveInputFrames(){return this.frames}get liveAxesLog(){return this.axesLog}get liveKnobEvents(){return this.knobEvents}step(e,n){if(n)for(let[r,o]of n)this.lastAxes.get(r)!==o&&(this.axesLog.push([this.frames.length,r,o]),this.lastAxes.set(r,o));this.frames.push([...e].sort())}knob(e,n){this.knobEvents.push({frame:this.frames.length,key:e,value:n}),this.screen("knob",`${e}=${n}`)}screen(e,n){this.screenEvents.push({frame:this.frames.length,kind:e,...n!==void 0?{detail:n}:{}})}mark(e,n){this.wallClockMarks.push({frame:this.frames.length,t:n,kind:e})}annotate(e,n){this.annotations.push({frame:this.frames.length,tag:e,...n!==void 0?{note:n}:{}})}truncate(e){if(!(e>=this.frames.length)){this.frames.length=e,this.axesLog=this.axesLog.filter(([n])=>n<e),this.lastAxes.clear();for(let[n,r,o]of this.axesLog)n<e&&this.lastAxes.set(r,o);this.knobEvents=this.knobEvents.filter(n=>n.frame<=e),this.screenEvents=this.screenEvents.filter(n=>n.frame<=e),this.wallClockMarks=this.wallClockMarks.filter(n=>n.frame<=e),this.annotations=this.annotations.filter(n=>n.frame<=e)}}toSession(e){return{id:this.id,game:this.init.game,startedAt:this.startedAt,buildRef:this.buildRef,seed:this.init.seed,variant:this.init.variant??{name:"dev",kind:"dev"},tuningValues:{...this.init.tuningValues},...this.init.startSnapshot?{startSnapshot:this.init.startSnapshot}:{},knobEvents:this.knobEvents.slice(),inputLog:{frames:this.frames.map(n=>n.slice())},axesLog:this.axesLog.slice(),screenEvents:this.screenEvents.slice(),wallClockMarks:this.wallClockMarks.slice(),annotations:this.annotations.slice(),endReason:e}}};var Nt=class{constructor(e=30,n=240){this.stride=e;this.cap=n}stride;cap;entries=[];push(e,n){e%this.stride===0&&(this.entries.push({frame:e,snap:n.snapshot()}),this.entries.length>this.cap&&this.entries.shift())}nearest(e){let n=null;for(let r of this.entries)r.frame<=e&&(!n||r.frame>n.frame)&&(n=r);return n}get minFrame(){return this.entries.length>0?this.entries[0].frame:0}truncate(e){this.entries=this.entries.filter(n=>n.frame<=e)}clear(){this.entries=[]}};function cr(t,e,n,r,o,i,s){let a=Math.max(n.minFrame,Math.min(s,r.length)),l=n.nearest(a);if(!l)return null;t.restore(structuredClone(l.snap)),e.attach?.(t),t.input.axes.clear();let u=new Map,c=0;for(;c<o.length&&o[c][0]<l.frame;){let[,d,h]=o[c++];u.set(d,h)}for(let[d,h]of u)t.input.axes.set(d,h);let m=i.findIndex(d=>d.frame>=l.frame);m<0&&(m=i.length);for(let d=l.frame;d<a;d++){for(;m<i.length&&i[m].frame===d;){let h=i[m++],p=t.snapshot();p.tuning={...p.tuning,[h.key]:h.value},t.restore(p),e.attach?.(t)}for(;c<o.length&&o[c][0]===d;){let[,h,p]=o[c++];t.input.axes.set(h,p)}t.step(r[d])}return a}function ih(){if(typeof location>"u")return{};let t=new URLSearchParams(location.search),e={},n=t.get("seed");n!==null&&Number.isFinite(Number(n))&&(e.seed=Number(n));let r=t.get("tuning");if(r)try{let o=JSON.parse(atob(r));o&&typeof o=="object"&&(e.tuning=o)}catch{}return e}function sh(t,e,n={}){let r=ih(),o=typeof location<"u"?new URLSearchParams(location.search).get("variant"):null,i=o?n.variants?.[o]:void 0,s=i?.patch?i.patch(t):t,a=n.variant??(i&&o?{name:o,kind:"module"}:{name:"dev",kind:"dev"}),l=n.world?.seed??r.seed??s.seed??1,u={...i?.tuning,...r.tuning,...n.world?.tuning},c=fn(s.tuning,u),m={...c},d=typeof performance<"u"?performance.now():0,h=new pt({game:s.title,seed:l,tuningValues:c,variant:a}),p=!1,f=(D,A)=>{let O=JSON.stringify(D);if(A&&typeof navigator<"u"&&navigator.sendBeacon){navigator.sendBeacon("/__studio/session",new Blob([O],{type:"application/json"}));return}fetch("/__studio/session",{method:"POST",headers:{"content-type":"application/json"},body:O}).catch(()=>{})},g=(D="quit",A=!1)=>{v||h.frame===0&&p||(f(h.toSession(D),A),p=!0)},k=typeof location<"u"?new URLSearchParams(location.search).get("session"):null,v=null,M=null,I=new Nt,x=!1,b=null,w=()=>{if(b===null||b>=h.frame){b=null;return}h.truncate(b),I.truncate(b),h.screen("scrub",`forked@${b}`),b=null},C=bn(s,e,{...n,world:{seed:l,tuning:u},isHeld:()=>x||(n.isHeld?.()??!1),onAdvance:(D,A,O)=>{for(let z=0;z<A;z++)h.step(O,D.input.axes),I.push(h.frame,D);n.onAdvance?.(D,A,O)},onPause:D=>{h.screen(D?"pause":"resume"),n.onPause?.(D)},onRestart:()=>{g("restart"),h=new pt({game:s.title,seed:l,tuningValues:{...m},variant:a,buildRef:h.buildRef}),(n.onRestart??C.restart)()}}),E=n.hot?.data.hayaoSnap;if(E){delete n.hot.data.hayaoSnap;let D=structuredClone(E);D.tuning={...m},C.world.restore(D),s.attach?.(C.world),h=new pt({game:s.title,seed:l,tuningValues:{...m},variant:a,startSnapshot:D}),h.screen("hot-swap")}n.hot?.dispose(D=>{D.hayaoSnap=C.world.snapshot(),ee("hot-swap")}),I.push(0,C.world);async function R(D,A){let O=await fetch(`/__studio/session/${encodeURIComponent(D)}`);if(!O.ok)return;let z=await O.json();x=!0;let X=C.world,se=Te(s,{seed:z.seed,tuning:z.tuningValues});X.restore(z.startSnapshot?structuredClone(z.startSnapshot):se.snapshot()),s.attach?.(X),X.input.axes.clear();let ae=z.inputLog.frames,re=Math.max(30,Math.ceil(ae.length/220/30)*30);I=new Nt(re),I.push(0,X);let le=0,me=0;for(let xe=0;xe<ae.length;xe++){for(;me<z.knobEvents.length&&z.knobEvents[me].frame===xe;){let Ue=z.knobEvents[me++],Me=X.snapshot();Me.tuning={...Me.tuning,[Ue.key]:Ue.value},X.restore(Me),s.attach?.(X)}for(;le<z.axesLog.length&&z.axesLog[le][0]===xe;){let[,Ue,Me]=z.axesLog[le++];X.input.axes.set(Ue,Me)}X.step(ae[xe]),I.push(xe+1,X)}v={session:z,pos:ae.length},ie.scrub(Number.isFinite(A)?A:0)}function S(){if(!v||M!==null)return;let D=v.session,A=performance.now();M=window.setInterval(()=>{if(!v)return;let O=performance.now(),z=Math.min(120,Math.floor((O-A)/(1e3/60)));if(z<=0)return;A=O;let X=C.world;for(let se=0;se<z;se++){let ae=v.pos;if(ae>=D.inputLog.frames.length){T();return}for(let re of D.knobEvents)if(re.frame===ae){let le=X.snapshot();le.tuning={...le.tuning,[re.key]:re.value},X.restore(le),s.attach?.(X)}for(let[re,le,me]of D.axesLog)re===ae&&X.input.axes.set(le,me);X.step(D.inputLog.frames[ae]),v.pos=ae+1}},1e3/60)}function T(){M!==null&&(window.clearInterval(M),M=null)}k&&R(k,Number(new URLSearchParams(location.search).get("at")??"NaN")),fetch("/__studio/state").then(D=>D.ok?D.json():null).then(D=>{D?.buildRef&&(h.buildRef=D.buildRef)}).catch(()=>{}),Zn((D,A)=>h.screen(D==="show"?"overlay-show":"overlay-hide",A));let L=()=>typeof performance<"u"?performance.now()-d:0,H=()=>h.mark(document.hidden?"visibility-hidden":"visibility-visible",L()),$=()=>h.mark("blur",L()),Y=()=>h.mark("focus",L()),K=()=>g("quit",!0);document.addEventListener("visibilitychange",H),window.addEventListener("blur",$),window.addEventListener("focus",Y),window.addEventListener("pagehide",K);let te=window.setInterval(()=>g("idle"),1e4),ee=D=>{T(),g(D,D==="hot-swap"),document.removeEventListener("visibilitychange",H),window.removeEventListener("blur",$),window.removeEventListener("focus",Y),window.removeEventListener("pagehide",K),window.clearInterval(te),Zn(null),C.stop()},ie={...C,get world(){return C.world},setKnob(D,A){if(v)return;w(),m[D]=A;let O=C.world.snapshot();O.tuning={...m},C.world.restore(O),s.attach?.(C.world),h.knob(D,A)},knobValues:()=>({...m}),tuningSpec:()=>s.tuning,variants:()=>Object.fromEntries(Object.entries(n.variants??{}).map(([D,A])=>[D,A.label])),activeVariant:()=>({...a}),title:()=>s.title,annotate:(D,A)=>{v||h.annotate(D,A)},setFrozen(D){if(v){D?T():S();return}if(D===x)return;if(D){x=!0;return}let A=b!==null;if(w(),A){let O=C.world.snapshot().tuning??{};for(let z of Object.keys(m))z in O&&(m[z]=O[z])}x=!1},frozen:()=>v?M===null:x,scrub(D){if(v){T();let O=v.session,z=cr(C.world,s,I,O.inputLog.frames,O.axesLog,O.knobEvents,D);return z!==null&&(v.pos=z),z}x=!0;let A=cr(C.world,s,I,h.liveInputFrames,h.liveAxesLog,h.liveKnobEvents,D);return A!==null&&(b=A<h.frame?A:null),A},timeline:()=>v?{min:I.minFrame,frame:v.pos,max:v.session.inputLog.frames.length}:{min:I.minFrame,frame:b??h.frame,max:h.frame},mode:()=>v?"replay":"live",flush:(D="idle")=>g(D),session:()=>h.toSession("idle"),stop:()=>ee("navigate")};return window.__studio=ie,ie}var ah="0.4.1";return Aa(lh);})();
|