hayao 0.2.0 → 0.4.0

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.
Files changed (83) hide show
  1. package/README.md +123 -24
  2. package/bin/create-hayao.mjs +380 -0
  3. package/bin/hayao-mcp-cli.mjs +11 -0
  4. package/dist/app/browser.d.ts +65 -4
  5. package/dist/app/game.d.ts +59 -10
  6. package/dist/app/tuning.d.ts +68 -0
  7. package/dist/art/palette.d.ts +41 -0
  8. package/dist/audio/adaptive.d.ts +58 -0
  9. package/dist/audio/album.d.ts +16 -0
  10. package/dist/audio/analysis.d.ts +59 -0
  11. package/dist/audio/audio.d.ts +39 -1
  12. package/dist/audio/chord.d.ts +17 -0
  13. package/dist/audio/genres.d.ts +11 -0
  14. package/dist/audio/lint.d.ts +29 -0
  15. package/dist/audio/match.d.ts +38 -0
  16. package/dist/audio/music.d.ts +88 -0
  17. package/dist/audio/pcm.d.ts +54 -0
  18. package/dist/audio/quality.d.ts +28 -0
  19. package/dist/audio/reverb.d.ts +15 -0
  20. package/dist/audio/synth.d.ts +63 -0
  21. package/dist/audio/theory.d.ts +64 -0
  22. package/dist/audio/zzfx.d.ts +14 -0
  23. package/dist/content/campaign.d.ts +69 -0
  24. package/dist/content/generate.d.ts +78 -0
  25. package/dist/content/level.d.ts +93 -0
  26. package/dist/content/worldgraph.d.ts +73 -0
  27. package/dist/core/clock.d.ts +1 -1
  28. package/dist/core/dmath.d.ts +2 -0
  29. package/dist/core/projection.d.ts +36 -0
  30. package/dist/core/rng.d.ts +9 -0
  31. package/dist/hayao.global.js +200 -0
  32. package/dist/index.d.ts +39 -1
  33. package/dist/index.js +6558 -686
  34. package/dist/index.js.map +4 -4
  35. package/dist/index.min.js +200 -0
  36. package/dist/input/actions.d.ts +60 -6
  37. package/dist/input/gamepad.d.ts +101 -0
  38. package/dist/input/source.d.ts +133 -1
  39. package/dist/logic/coroutine.d.ts +68 -0
  40. package/dist/mcp.js +31225 -0
  41. package/dist/rasterize-worker-lite.mjs +13 -0
  42. package/dist/render/canvas.d.ts +6 -5
  43. package/dist/render/canvas2d-core.d.ts +9 -0
  44. package/dist/render/commands.d.ts +82 -2
  45. package/dist/render/paint.d.ts +41 -0
  46. package/dist/render/renderer.d.ts +47 -0
  47. package/dist/render/svg.d.ts +5 -1
  48. package/dist/render/svgString.d.ts +6 -2
  49. package/dist/render/webgl.d.ts +176 -0
  50. package/dist/scene/cameraController.d.ts +42 -0
  51. package/dist/scene/iso.d.ts +73 -0
  52. package/dist/scene/node.d.ts +98 -6
  53. package/dist/scene/nodes.d.ts +48 -0
  54. package/dist/scene/parallax.d.ts +15 -0
  55. package/dist/scene/particles.d.ts +19 -0
  56. package/dist/scene/verletChain.d.ts +76 -0
  57. package/dist/studio/mcpMain.d.ts +1 -0
  58. package/dist/studio/mcpServer.d.ts +2 -0
  59. package/dist/studio/record.d.ts +54 -0
  60. package/dist/studio/run.d.ts +78 -0
  61. package/dist/studio/session.d.ts +80 -0
  62. package/dist/studio/timeline.d.ts +35 -0
  63. package/dist/studio/vitePlugin.d.ts +6 -0
  64. package/dist/studio-plugin.js +228 -0
  65. package/dist/ui/overlay.d.ts +6 -0
  66. package/dist/ui/touch.d.ts +51 -0
  67. package/dist/verify/audioFilmstrip.d.ts +39 -0
  68. package/dist/verify/dom.d.ts +26 -0
  69. package/dist/verify/ethnography.d.ts +67 -0
  70. package/dist/verify/gates.d.ts +160 -0
  71. package/dist/verify/layout.d.ts +30 -3
  72. package/dist/verify/ramp.d.ts +40 -0
  73. package/dist/world.d.ts +109 -8
  74. package/dist-studio/assets/index-C7tty_Wo.js +109 -0
  75. package/dist-studio/assets/index-CM3tjRQo.css +1 -0
  76. package/dist-studio/index.html +18 -0
  77. package/docs/API.md +300 -23
  78. package/docs/CONVENTIONS.md +511 -0
  79. package/docs/EMBED.md +90 -0
  80. package/docs/QUICKSTART.md +141 -0
  81. package/docs/STUDIO.md +97 -0
  82. package/docs/VERIFICATION.md +256 -0
  83. package/package.json +40 -6
@@ -0,0 +1,200 @@
1
+ "use strict";var hayao=(()=>{var Gn=Object.defineProperty;var Us=Object.getOwnPropertyDescriptor;var Xs=Object.getOwnPropertyNames;var Js=Object.prototype.hasOwnProperty;var Ys=(t,e)=>{for(var n in e)Gn(t,n,{get:e[n],enumerable:!0})},Ks=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Xs(e))!Js.call(t,o)&&o!==n&&Gn(t,o,{get:()=>e[o],enumerable:!(r=Us(e,o))||r.enumerable});return t};var Qs=t=>Ks(Gn({},"__esModule",{value:!0}),t);var md={};Ys(md,{ALBUM:()=>is,AMBIENT_PRESETS:()=>$a,AmbientField:()=>rr,AnimationPlayer:()=>It,AudioBus:()=>kn,BLOOM_PIPELINE:()=>$u,BitmapText:()=>Tr,BroadcastChannelTransport:()=>Do,Camera2D:()=>Et,CameraController:()=>Kn,Canvas2DRenderer:()=>Je,CinematicPlayer:()=>to,Clock:()=>Mt,Coroutines:()=>po,DEFAULT_GAMEPAD_MAP:()=>jo,DEFAULT_INPUT_MAP:()=>hn,DEFAULT_PLATFORMER:()=>lt,DEFAULT_SESSION_CONFIG:()=>et,DEFAULT_TILE_CHARS:()=>dr,DUSK:()=>di,DepthSort:()=>Yn,EASINGS:()=>tr,Edge:()=>ne,EventBus:()=>Tt,FLOAT_PRESETS:()=>Wa,FONT_5:()=>Mr,FloatingText:()=>ir,Fsm:()=>lo,GENRES:()=>rs,GENRE_PROFILES:()=>tc,GamepadSource:()=>mr,HeadlessRenderer:()=>wr,IDENTITY:()=>ue,INSTRUMENTS:()=>$,InputBuffer:()=>tt,InputRecorder:()=>ar,InputState:()=>Ft,IsoPrism:()=>Jn,KENTO:()=>z,KeyboardSource:()=>Ve,LocalStorageAdapter:()=>Nn,LockstepSession:()=>Ee,LoopbackHub:()=>Eo,LoopbackTransport:()=>zn,LootTable:()=>fo,MEADOW:()=>mi,MOUSE_ACTIONS:()=>cr,MemoryStorage:()=>An,NEIGHBORS_4:()=>nn,NEIGHBORS_8:()=>Fn,NET_PROTOCOL_VERSION:()=>sb,Node:()=>V,Node2D:()=>V,NodePool:()=>Zn,NullStorage:()=>ko,PAD_NEUTRAL:()=>Oa,PALETTES:()=>Gu,PANEL_PRESETS:()=>_u,PAPER:()=>hi,PARTICLE_PRESETS:()=>Vo,ParallaxLayer:()=>Qn,Particles:()=>nr,PhaseClock:()=>co,PixelBuffer:()=>dt,PlayerInput:()=>Wn,PointerSource:()=>At,RingBuffer:()=>wo,Rng:()=>le,RollbackSession:()=>sn,RoomHost:()=>Bn,SAMPLE_RATE:()=>be,SAVE_FORMAT_VERSION:()=>Ro,SCALES:()=>Wr,SaveManager:()=>Co,ScreenTransition:()=>Dn,SessionRecorder:()=>nt,Shaker:()=>or,Shell:()=>Jt,Signal:()=>st,SnapshotRing:()=>wt,SpatialHash:()=>Lt,Sprite:()=>Rt,SvgRenderer:()=>Xe,TAU:()=>Q,TILE:()=>U,Text:()=>Pt,TextureSprite:()=>Sr,Timer:()=>Dt,TouchControls:()=>eo,UndoStack:()=>xo,VERSION:()=>cd,VerletChain:()=>sr,WEBGL_EFFECTS:()=>_t,WangFrame:()=>Ye,WebGL2Renderer:()=>Gt,World:()=>Zt,abilitiesOf:()=>_s,addBody:()=>tu,addDistanceJoint:()=>au,addRevoluteJoint:()=>uu,addTransition:()=>Ec,albumTrack:()=>wc,all:()=>Mm,analyzePlaytest:()=>gm,applyImpulse:()=>ru,applyReverb:()=>Gr,applyTransform:()=>cn,asciiEntities:()=>za,assertAudio:()=>lm,assertDeterministic:()=>Ac,assertRamp:()=>rm,assertSnapshotStable:()=>Nc,assertSolvable:()=>Fc,astar:()=>Fs,astarGrid:()=>Im,audio:()=>$e,autotile4:()=>ul,autotileToCommands:()=>cl,availableUpgrades:()=>_m,bandBalance:()=>jr,bfs:()=>Is,blobPath:()=>Yu,bodyAABB:()=>pn,bodyContains:()=>oi,bootDom:()=>vm,cadenceResolves:()=>Ul,cameraIssues:()=>gs,canvasGradient:()=>vr,cellFloat:()=>Ke,cellHash:()=>Fi,cellInt:()=>hl,changeFrames:()=>Qc,checkDeterministic:()=>ds,chordChanges:()=>Hl,chordNotes:()=>Se,clamp:()=>ee,clientToDesign:()=>qe,collide:()=>pr,commandsToSVGInner:()=>Ue,composeCampaign:()=>Ym,composeTransform:()=>_e,connectWebSocket:()=>rd,connectedComponents:()=>Dm,contourToCommands:()=>ml,contrastRatio:()=>vt,createPlanBot:()=>_c,createPlatformerState:()=>Va,createRigidWorld:()=>Qa,createStereo:()=>Fr,createWorld:()=>Me,crestFactorDb:()=>qr,dashJumpDistance:()=>Ua,datan:()=>Lo,datan2:()=>kt,dbfs:()=>Sn,dcos:()=>j,decode2bit:()=>Zu,decodeBits:()=>Qu,decodeMessage:()=>Ne,decodeRLE:()=>el,defaultStorage:()=>So,defineGame:()=>mm,defineLevel:()=>Vm,deg2rad:()=>Ca,deserializeNode:()=>dn,dexp:()=>Be,dexp2:()=>pe,dhypot:()=>K,diamondPoints:()=>mn,diatonicChord:()=>Oi,diffLevels:()=>Um,distanceGain:()=>Zi,dlog:()=>On,dlog10:()=>St,dlog2:()=>rt,dpow:()=>Re,drive:()=>Bc,dropShadow:()=>Cu,dsin:()=>H,duckGain:()=>ec,encodeMessage:()=>de,encodeRLE:()=>tl,encodeWav:()=>Sl,estimateTempo:()=>Yi,evalCurve:()=>Kl,featureDistance:()=>Qi,features:()=>yt,feedbackIssues:()=>fs,fft:()=>Ui,findSoftlocks:()=>Zm,firstFrame:()=>Yc,fitViewport:()=>je,floodFill:()=>vo,fluxEnvelope:()=>Hr,forgivenessIssues:()=>ps,fractalNoise:()=>Pr,frameActions:()=>at,frameAxes:()=>ut,gameInputMap:()=>dm,generateCave:()=>fl,generateDungeon:()=>xl,generateLevels:()=>Po,generateLevelsReport:()=>zs,genre:()=>lc,getBody:()=>ge,getJoint:()=>lu,glow:()=>Tu,graceWindowIssues:()=>Oc,gradient:()=>Uu,gradientDef:()=>br,gridAt:()=>Di,gridFromRows:()=>ol,gridSet:()=>Fe,gridToTilemap:()=>dl,groundAt:()=>Uo,hashNoise:()=>Fa,hashString:()=>jn,hashValue:()=>Ct,hexToHsl:()=>bi,hideScreen:()=>Xt,hold:()=>Lc,hostRoom:()=>Fo,hsl:()=>fi,hsv:()=>Hu,inVisionCone:()=>Ka,initDirector:()=>zm,inputDensity:()=>em,installCapture:()=>oo,invLerp:()=>Vn,invalidCommandReason:()=>Wt,invertTransform:()=>it,isCaptureMode:()=>ro,isGround:()=>gl,isMonotonic:()=>Zc,iso:()=>Da,joinRoom:()=>Io,jumpAirtime:()=>Xo,jumpDistance:()=>Jo,jumpHeight:()=>ja,keyMentions:()=>Ms,keysToActions:()=>lr,knob:()=>cm,layerGains:()=>Zl,layoutIssues:()=>Uc,layoutText:()=>Mi,lerp:()=>De,lerpDamp:()=>Na,levelFromSeed:()=>Jm,levelIssues:()=>Hm,levelReachable:()=>qm,levelToTilemap:()=>Ln,lineOfSight:()=>Ko,linearGradient:()=>Su,lintSong:()=>jl,longestLull:()=>tm,lookAheadIssues:()=>ys,magnitudeSpectrum:()=>gt,makeGrid:()=>pt,makeReach:()=>La,makeTransform:()=>ot,mapHeight:()=>Ga,mapWidth:()=>_a,marchingSquaresCases:()=>Pi,marchingSquaresContours:()=>Ei,mask4:()=>Cr,mask8:()=>il,matchReport:()=>Yl,measureLine:()=>ht,measureText:()=>rl,mergePlayerFrames:()=>xt,midiToFreq:()=>Gi,midiToName:()=>El,missingControlHints:()=>Xc,mix:()=>Ou,mixLinear:()=>gi,mixMono:()=>Ar,moveRect:()=>Nt,mutateColor:()=>qu,netMessage:()=>he,nextStep:()=>km,nineSlice:()=>Bu,normalize:()=>Lr,noteToMidi:()=>ce,onsetDensity:()=>Ji,openVoicing:()=>xn,packVarints:()=>$m,panFromOffset:()=>es,panGains:()=>Wi,parseRich:()=>wi,parseSnapshot:()=>To,passableFromTilemap:()=>Fm,peak:()=>zi,peakAmp:()=>Vr,pickEntry:()=>go,pitchToFreq:()=>$r,pixelsToCommands:()=>xi,platformerReachable:()=>jm,playerAction:()=>on,playerIds:()=>td,playerInput:()=>nd,pointQuery:()=>xu,pollDirector:()=>Bm,polygonBox:()=>ou,progression:()=>Qe,progressionPuzzle:()=>$n,proveCompletable:()=>Km,proveFullCompletion:()=>Qm,pump:()=>zc,quantizeAngle:()=>ur,race:()=>Sm,rad2deg:()=>Ra,radialGradient:()=>Mu,rampIssues:()=>Cs,rampStats:()=>Ts,rayCastRigid:()=>ku,raycastTiles:()=>Yo,reachableRegions:()=>Vs,reconstructPath:()=>Rm,recordTimeline:()=>Jc,rectBlocked:()=>Le,rectContains:()=>Pa,rectsOverlap:()=>Ea,registerNode:()=>Ge,regularPolyPoints:()=>Bo,regularPolygon:()=>Xu,relLuminance:()=>Yt,remap:()=>Ta,removeBody:()=>nu,removeJoint:()=>cu,renderAudioFilmstrip:()=>im,renderFilmstrip:()=>om,renderSong:()=>Or,renderSound:()=>Ht,renderToSVGString:()=>zt,replay:()=>no,replaySession:()=>ao,resetNodeIds:()=>Un,resetZzfxWarnings:()=>cc,resolveTuning:()=>en,rigidStep:()=>gu,rleDecode:()=>Lm,rleEncode:()=>Nm,rms:()=>bt,roomCenter:()=>Dr,rootless:()=>qt,runBrowser:()=>tn,runBrowserNet:()=>id,runFeelGates:()=>qc,runHeadless:()=>hm,runStudio:()=>ld,salienceIssues:()=>bs,sampleGradient:()=>kr,scaleMidis:()=>vn,scalePitchClasses:()=>zr,scatter:()=>Ai,scatterCells:()=>pl,scoreTrack:()=>nc,screenRect:()=>Ic,scriptToFrames:()=>hs,scriptedPlaythrough:()=>Wc,scrubTo:()=>_n,serializeSnapshot:()=>Ls,series:()=>Kc,setOverlayHost:()=>Ut,setScreenObserver:()=>En,settings:()=>Ae,shadeHex:()=>Xn,shadowDef:()=>gr,shapeBBox:()=>yr,shapeBox:()=>io,showScreen:()=>Kr,signalHash:()=>Ml,sleep:()=>xm,smoothClosedPath:()=>yi,smoothOpenPath:()=>Ku,smoothstep:()=>Hn,snapAxis:()=>Oe,softClip:()=>Ir,softClipInPlace:()=>Nr,solidNeighbours:()=>Rr,solve:()=>Ze,solveJoint:()=>fr,songBeats:()=>qi,songDuration:()=>wn,sortCommands:()=>$t,spatialMix:()=>Ql,specFromZzfx:()=>mc,spectralCentroid:()=>Xi,spring:()=>Go,springStep:()=>Oo,star:()=>Ju,steer2D:()=>Gc,stepPlatformer:()=>qa,stereoDuration:()=>kl,stereoFrames:()=>wl,stereoWidth:()=>ts,subSeed:()=>Ws,telegraphIssues:()=>Hc,terrainHeight:()=>Er,terrainSlice:()=>bl,textBox:()=>ks,textToCommands:()=>Ci,tileAt:()=>fe,tileAtPoint:()=>Ba,tileCenter:()=>$s,tilemapFromAscii:()=>hr,toggleFullscreen:()=>Zr,transpose:()=>Il,typewriterCount:()=>Ti,unpackVarints:()=>Wm,vadd:()=>va,validateWorld:()=>ed,valueNoise:()=>Ni,vdist:()=>Sa,vdot:()=>ka,vec2:()=>ya,vlen:()=>Wo,vnorm:()=>Ma,voiceLead:()=>ft,vscale:()=>wa,vsub:()=>xa,wait:()=>$c,waitFor:()=>wm,wakeBody:()=>ye,wangTile:()=>Ri,warnCommandOnce:()=>ct,weatherEnvelope:()=>Ho,weightedIndex:()=>bo,weightedPick:()=>Cm,wipeStep:()=>Dc,withAlpha:()=>Vu,worldPoints:()=>we,zcr:()=>ji});var Zs=.6366197723675814,ea=1.5707963267341256,ta=6077100506506192e-26,na=-.16666666666666632,ra=.00833333333332249,oa=-.0001984126982985795,ia=27557313707070068e-22,sa=-25050760253406863e-24,aa=158969099521155e-24,ua=.0416666666666666,la=-.001388888888887411,ca=2480158728947673e-20,ma=-27557314351390663e-23,da=2087572321298175e-24,ha=-11359647557788195e-27;function un(t){let e=t*t;return t+t*e*(na+e*(ra+e*(oa+e*(ia+e*(sa+e*aa)))))}function ln(t){let e=t*t;return 1-.5*e+e*e*(ua+e*(la+e*(ca+e*(ma+e*(da+e*ha)))))}function No(t){let e=Math.round(t*Zs),n=t-e*ea-e*ta;return{n:(e%4+4)%4,r:n}}function H(t){if(!Number.isFinite(t))return NaN;let{n:e,r:n}=No(t);switch(e){case 0:return un(n);case 1:return ln(n);case 2:return-un(n);default:return-ln(n)}}function j(t){if(!Number.isFinite(t))return NaN;let{n:e,r:n}=No(t);switch(e){case 0:return ln(n);case 1:return-un(n);case 2:return-ln(n);default:return un(n)}}var an=[.4636476090008061,.7853981633974483,.982793723247329,1.5707963267948966],Ao=[22698777452961687e-33,3061616997868383e-32,13903311031230998e-33,6123233995736766e-32],xe=[.3333333333333293,-.19999999999876483,.14285714272503466,-.11111110405462356,.09090887133436507,-.0769187620504483,.06661073137387531,-.058335701337905735,.049768779946159324,-.036531572744216916,.016285820115365782];function Lo(t){if(Number.isNaN(t))return NaN;if(!Number.isFinite(t))return t>0?an[3]:-an[3];let e=t<0||Object.is(t,-0)?-1:1,n=Math.abs(t);if(n>=1e19)return e*(an[3]+Ao[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*(xe[0]+i*(xe[2]+i*(xe[4]+i*(xe[6]+i*(xe[8]+i*xe[10]))))),a=i*(xe[1]+i*(xe[3]+i*(xe[5]+i*(xe[7]+i*xe[9]))));if(r<0)return e*(n-n*(s+a));let u=an[r]-(n*(s+a)-Ao[r]-n);return e*u}var Ce=3.141592653589793;function kt(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)?-Ce:Ce:Object.is(t,-0)?-0:0;if(e===0||!Number.isFinite(t)&&Number.isFinite(e))return t>0?Ce/2:-Ce/2;if(!Number.isFinite(e)){if(!Number.isFinite(t)){let r=e>0?Ce/4:3*Ce/4;return t>0?r:-r}return e>0?t<0||Object.is(t,-0)?-0:0:t<0||Object.is(t,-0)?-Ce:Ce}let n=Lo(t/e);return e>0?n:t<0||Object.is(t,-0)?n-Ce:n+Ce}var pa=.6931471805599453;function pe(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)*pa,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 pe(t*$o)}function K(t,e){return Math.sqrt(t*t+e*e)}var ze=new DataView(new ArrayBuffer(8)),fa=.6931471803691238,ba=19082149292705877e-26;function On(t){if(Number.isNaN(t)||t<0)return NaN;if(t===0)return-1/0;if(!Number.isFinite(t))return 1/0;ze.setFloat64(0,t);let e=(ze.getUint32(0)>>>20&2047)-1023;e===-1023&&(ze.setFloat64(0,t*0x40000000000000),e=(ze.getUint32(0)>>>20&2047)-1023-54),ze.setUint32(0,ze.getUint32(0)&1048575|1023<<20);let n=ze.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*fa+(2*r*i+e*ba)}var ga=.4342944819032518,$o=1.4426950408889634,St=t=>On(t)*ga,rt=t=>On(t)*$o;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?pe(e*rt(t)):t===0?e>0?0:1/0:NaN}var ya=(t=0,e=0)=>({x:t,y:e}),va=(t,e)=>({x:t.x+e.x,y:t.y+e.y}),xa=(t,e)=>({x:t.x-e.x,y:t.y-e.y}),wa=(t,e)=>({x:t.x*e,y:t.y*e}),ka=(t,e)=>t.x*e.x+t.y*e.y,Wo=t=>K(t.x,t.y),Sa=(t,e)=>K(t.x-e.x,t.y-e.y);function Ma(t){let e=Wo(t);return e===0?{x:0,y:0}:{x:t.x/e,y:t.y/e}}var ee=(t,e,n)=>t<e?e:t>n?n:t,De=(t,e,n)=>t+(e-t)*n,Vn=(t,e,n)=>t===e?0:(n-t)/(e-t),Ta=(t,e,n,r,o)=>De(r,o,Vn(e,n,t)),Hn=(t,e,n)=>{let r=ee(t===e?n<t?0:1:Vn(t,e,n),0,1);return r*r*(3-2*r)},Q=Math.PI*2,Ca=t=>t*Math.PI/180,Ra=t=>t*180/Math.PI;function Pa(t,e){return e.x>=t.x&&e.x<=t.x+t.w&&e.y>=t.y&&e.y<=t.y+t.h}function Ea(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 ue={a:1,b:0,c:0,d:1,e:0,f:0};function _e(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 ot(t,e,n){let r=j(e),o=H(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 cn(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 it(t){let e=t.a*t.d-t.b*t.c;if(e===0)return{...ue};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 Da(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,u,l=0){return{x:r.x+(a-u)*i,y:r.y+(a+u)*s-l*o}},toGrid(a,u){let l=(a-r.x)/i,c=(u-r.y)/s;return{x:(l+c)/2,y:(c-l)/2}}}}function Ia(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 le=class t{s0;s1;s2;s3;constructor(e=0){if(typeof e=="number"){let n=Ia(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}},qn=new DataView(new ArrayBuffer(8));function Fa(...t){let e=2654435769;for(let n of t)qn.setFloat64(0,n),e=Math.imul(e^qn.getUint32(0),2246822507)>>>0,e=(e^e>>>13)>>>0,e=Math.imul(e^qn.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 jn(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 Mt=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 st=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}},Tt=class{signals=new Map;signalFor(e){let n=this.signals.get(e);return n||(n=new st,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 Aa(t){return Number.isNaN(t)?"NaN":t===1/0?"Inf":t===-1/0?"-Inf":t===0?"0":t.toString()}function Ct(t){let e=2166136261,n=2166136261,r=s=>{for(let a=0;a<s.length;a++){let u=s.charCodeAt(a);e=Math.imul(e^u,16777619)>>>0,n=Math.imul(n^(u<<3|u>>>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("#"+Aa(s));case"boolean":return r(s?"t":"f");case"string":return r('"'+s);case"object":{if(Array.isArray(s)){r("[");for(let l of s)o(l);r("]");return}let a=s,u=Object.keys(a).filter(l=>a[l]!==void 0).sort();r("{");for(let l of u)r(l+":"),o(a[l]);r("}");return}default:r("?")}};o(t);let i=s=>s.toString(16).padStart(8,"0");return i(e)+i(n)}var zo=0;function Un(t=0){zo=t}var V=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${zo++}`,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 st,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,u=i==="always"?n:e;for(let l of this.behaviors)l.update?.(this,u,a);this.onUpdate?.(this,u,a),this.onProcess(u)}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=ot(this.pos,this.rotation,this.scale);return this.pivot?_e(e,ot({x:-this.pivot.x,y:-this.pivot.y},0,{x:1,y:1})):e}worldTransform(){let e=this.localTransform();return this.parent?_e(this.parent.worldTransform(),e):e}collectDraw(e,n=ue){if(!this.visible)return;let r=_e(this.screenSpace?ue: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 mn(t,e){return[0,-e/2,t/2,0,0,e/2,-t/2,0]}function Bo(t,e,n=0){let r=[];for(let o=0;o<t;o++){let i=n-Q/4+Q*o/t;r.push(j(i)*e,H(i)*e)}return r}var Rt=class extends V{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:mn(this.shape.w,this.shape.h),closed:!0,...o});break;case"regularPoly":e.push({kind:"poly",points:Bo(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)}},Pt=class extends V{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)}},Et=class extends V{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)}},Dt=class extends V{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 Xn(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 Jn=class extends V{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},u=this.leftPaint??{fill:Xn(this.fill,.65)},l=this.rightPaint??{fill:Xn(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,...u,...c}),e.push({kind:"poly",closed:!0,points:[0,o/2,r/2,0,r/2,-i,0,o/2-i],...s,...l,...c}));let m=mn(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)}},Yn=class extends V{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 Kn=class extends V{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 u=e.zoom||1,l=n.width/2/u,c=n.height/2/u,m=this.bounds.minX+l,d=this.bounds.maxX-l,h=this.bounds.minY+c,p=this.bounds.maxY-c;o=m>d?(this.bounds.minX+this.bounds.maxX)/2:ee(o,m,d),i=h>p?(this.bounds.minY+this.bounds.maxY)/2:ee(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=ee(this.smooth,0,1);e.pos.x=De(e.pos.x,n.x,r),e.pos.y=De(e.pos.y,n.y,r)}};var Qn=class extends V{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 Zn=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 Na=(t,e,n,r)=>De(e,t,Be(-n*r)),Go=(t=0)=>({value:t,vel:0});function Oo(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 La(t=0,e=.25){let n=4/Math.max(1e-4,e),r=Go(t);return(o,i)=>Oo(r,o,n,i).value}var _o=t=>t*t,er=t=>t*t*t,tr={linear:t=>t,quadIn:t=>t*t,quadOut:t=>1-(1-t)*(1-t),quadInOut:t=>t<.5?2*t*t:1-_o(-2*t+2)/2,cubicIn:t=>t*t*t,cubicOut:t=>1-er(1-t),cubicInOut:t=>t<.5?4*t*t*t:1-er(-2*t+2)/2,sineIn:t=>1-j(t*Math.PI/2),sineOut:t=>H(t*Math.PI/2),sineInOut:t=>-(j(Math.PI*t)-1)/2,backOut:t=>1+2.70158*er(t-1)+1.70158*_o(t-1),elasticOut:t=>{let e=2*Math.PI/3;return t===0?0:t===1?1:pe(-10*t)*H((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},It=class extends V{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:tr[i]??tr.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=ee(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 nr=class extends V{type="Particles";pool=[];rng;maxParticles;constructor(e={}){super(e),this.cosmetic=!0,this.rng=new le(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()*Q,a=r.speedMin+o.float()*(r.speedMax-r.speedMin),u={x:n.x,y:n.y,vx:j(s)*a,vy:H(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(u)}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=Vo.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}},Vo={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)*Hn(r.time,o.time,t)}return e[e.length-1].intensity}var rr=class extends V{type="AmbientField";rng;field=[];time=0;style;width;height;envelope;constructor(e){super(e),this.cosmetic=!0,this.rng=new le(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()*Q,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 u=0;u<i;u++){let l=this.field[u],c=s!==0?H(this.time*a*Q+l.phase)*s:0,m=l.x+c;if(r.streak){let d=r.streakLen??r.fallY*.03;e.push({kind:"poly",points:[m,l.y,m,l.y+d],closed:!1,stroke:l.color,strokeWidth:l.size,opacity:o,transform:n,z:this.z,transient:!0})}else e.push({kind:"circle",cx:m,cy:l.y,radius:l.size,fill:l.color,opacity:o,transform:n,z:this.z,transient:!0})}}get liveCount(){return this.field.length}},$a={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})},or=class extends V{type="Shaker";rng;trauma=0;amplitude;decay;constructor(e={}){super(e),this.cosmetic=!0,this.rng=new le(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 ir=class extends V{type="FloatingText";pool=[];rng;maxPopups;constructor(e={}){super(e),this.cosmetic=!0,this.rng=new le(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:ee(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:ee(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}},Wa={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 sr=class extends V{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 kt(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,u=this.prevx,l=this.prevy;if(!this.initialized){for(let y=0;y<i;y++)s[y]=r,a[y]=o+y*this.segmentLength,u[y]=s[y],l[y]=a[y];this.initialized=!0}let c=this.pinTail&&this.tailTarget!==null,m=0,d=0;if(c){let y=this.tailTarget;m=n.a*y.x+n.c*y.y+n.e,d=n.b*y.x+n.d*y.y+n.f}let h=this.gravity.x*e*e,p=this.gravity.y*e*e,b=this.impX*e,v=this.impY*e,M=this.damping,x=i-1;for(let y=1;y<i;y++){if(c&&y===x)continue;let f=s[y],w=a[y];s[y]=f+(f-u[y])*M+h+b,a[y]=w+(w-l[y])*M+p+v,u[y]=f,l[y]=w}this.impX=0,this.impY=0;let C=this.segmentLength;for(let y=0;y<this.iterations;y++){s[0]=r,a[0]=o,c&&(s[x]=m,a[x]=d);for(let f=0;f<x;f++){let w=s[f+1]-s[f],S=a[f+1]-a[f],D=Math.sqrt(w*w+S*S);if(D===0)continue;let R=(D-C)/D,k=f===0,T=c&&f+1===x;if(k&&T)continue;let F=k?0:T?1:.5,O=T?0:k?1:.5;s[f]+=w*R*F,a[f]+=S*R*F,s[f+1]-=w*R*O,a[f+1]-=S*R*O}}s[0]=r,a[0]=o,c&&(s[x]=m,a[x]=d);let I=it(n);for(let y=0;y<i;y++){let f=this.local[y],w=s[y],S=a[y];f.x=I.a*w+I.c*S+I.e,f.y=I.b*w+I.d*S+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],u=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*u),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 qo=new Map;function Ge(t,e){qo.set(t,e)}Ge("Node",()=>new V);Ge("Sprite",()=>new Rt({shape:{kind:"rect",w:1,h:1}}));Ge("Text",()=>new Pt({text:""}));Ge("Camera2D",()=>new Et);Ge("Timer",()=>new Dt({duration:1}));Ge("AnimationPlayer",()=>new It);function dn(t){let e=qo.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(dn(r));return n}var Ft=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 Oe(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 ur(t,e){let n=Math.PI*2/e;return Math.round(t/n)*n}function lr(t,e){let n=[];for(let r in t)t[r].some(o=>e.has(o))&&n.push(r);return n.sort()}var ar=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 at(t,e){return t.frames[e]??[]}function ut(t,e){return t.axes?.[e]}var hn={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 Ve=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=lr(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)}},cr=["mouse.left","mouse.right","mouse.middle"],At=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(cr),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 cr)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 mr=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??jo,this.keyboard=e.keyboard}sample(e){let n=navigator.getGamepads?.()[this.index]??null;if(!n)return;let r=(d,h)=>{let p=K(d,h);if(p<this.deadzone)return{x:0,y:0};let b=(p-this.deadzone)/(1-this.deadzone),v=Math.min(b,1);return{x:d/p*v,y:h/p*v}},o=r(n.axes[0]??0,n.axes[1]??0),i=r(n.axes[2]??0,n.axes[3]??0),s=d=>Oe(d,this.stickBuckets,-1,1),a=d=>Oe(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 u=n.buttons[12]?.pressed?1:0,l=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",l-u),this.keyboard)for(let[d,h]of Object.entries(this.buttonMap)){let p=Number(d),b=n.buttons[p]?.pressed??!1;this.keyboard.setHeld(h,b),this.prevPressed.set(p,b)}}dispose(){if(this.keyboard)for(let e of Object.values(this.buttonMap))this.keyboard.releaseHeld(e);this.prevPressed.clear()}},jo={0:"confirm",1:"cancel",2:"action2",3:"action",9:"confirm",12:"up",13:"down",14:"left",15:"right"};var U={EMPTY:0,SOLID:1,ONEWAY:2,HAZARD:3},dr={"#":U.SOLID,"-":U.ONEWAY,"^":U.HAZARD};function hr(t,e=32,n=dr){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 u=0;u<s.length;u++)i[a*o+u]=n[s[u]]??U.EMPTY}),{cols:o,rows:r,tileSize:e,tiles:i}}function za(t,e=32,n=dr){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?U.SOLID:t.tiles[n*t.cols+e]}function Ba(t,e,n){return fe(t,Math.floor(e/t.tileSize),Math.floor(n/t.tileSize))}var _a=t=>t.cols*t.tileSize,Ga=t=>t.rows*t.tileSize;var X=1e-6,He=(t,e,n)=>[Math.floor(t/n),Math.floor((e-X)/n)];function Le(t,e,n,r,o,i=[]){let s=t.tileSize,[a,u]=He(e,e+r,s),[l,c]=He(n,n+o,s);for(let m=l;m<=c;m++)for(let d=a;d<=u;d++)if(fe(t,d,m)===U.SOLID)return!0;for(let m of i)if(!m.oneway&&e<m.x+m.w-X&&e+r>m.x+X&&n<m.y+m.h-X&&n+o>m.y+X)return!0;return!1}function Nt(t,e,n,r,o={}){let i=t.tileSize,s=o.solids??[],{x:a,y:u}=e,{w:l,h:c}=e,m=!1,d=!1,h=!1,p=!1;if(n!==0){let[y,f]=He(u,u+c,i);if(n>0){let w=a+n,[S,D]=[Math.floor((a+l)/i),Math.floor((a+l+n-X)/i)];for(let R=S;R<=D;R++)for(let k=y;k<=f;k++)fe(t,R,k)===U.SOLID&&(w=Math.min(w,R*i-l));for(let R of s)!R.oneway&&R.y<u+c-X&&R.y+R.h>u+X&&R.x>=a+l-X&&(w=Math.min(w,R.x-l));w<a+n-X&&(m=!0,p=!0),a=Math.min(a+n,w)}else{let w=a+n,[S,D]=[Math.floor((a-X)/i),Math.floor((a+n)/i)];for(let R=S;R>=D;R--)for(let k=y;k<=f;k++)fe(t,R,k)===U.SOLID&&(w=Math.max(w,(R+1)*i));for(let R of s)!R.oneway&&R.y<u+c-X&&R.y+R.h>u+X&&R.x+R.w<=a+X&&(w=Math.max(w,R.x+R.w));w>a+n+X&&(m=!0,h=!0),a=Math.max(a+n,w)}}let b=u+c,v=!1,M=!1,x=-1;if(r!==0){let[y,f]=He(a,a+l,i);if(r>0){let w=u+r,[S,D]=[Math.floor(b/i),Math.floor((b+r-X)/i)];for(let R=S;R<=D;R++)for(let k=y;k<=f;k++){let T=fe(t,k,R);(T===U.SOLID||T===U.ONEWAY&&!o.dropThrough&&b<=R*i+X)&&(w=Math.min(w,R*i-c))}for(let R=0;R<s.length;R++){let k=s[R];!(k.x<a+l-X&&k.x+k.w>a+X)||k.y<b-X||k.oneway&&(o.dropThrough||b>k.y+X)||k.y-c<w&&(w=k.y-c,x=R)}w<u+r-X?(d=!0,v=!0):x=-1,u=Math.min(u+r,w)}else{let w=u+r,[S,D]=[Math.floor((u-X)/i),Math.floor((u+r)/i)];for(let R=S;R>=D;R--)for(let k=y;k<=f;k++)fe(t,k,R)===U.SOLID&&(w=Math.max(w,(R+1)*i));for(let R of s)!R.oneway&&R.x<a+l-X&&R.x+R.w>a+X&&R.y+R.h<=u+X&&(w=Math.max(w,R.y+R.h));w>u+r+X&&(d=!0,M=!0),u=Math.max(u+r,w)}}if(!v){let y=Uo(t,a,u,l,c,s,o.dropThrough??!1);v=y.grounded,x=y.solid}let C=3,I=!1;{let[y,f]=He(a+C,a+l-C,i),[w,S]=He(u+C,u+c-C,i);for(let D=w;D<=S&&!I;D++)for(let R=y;R<=f&&!I;R++)fe(t,R,D)===U.HAZARD&&(I=!0)}return{x:a,y:u,hitX:m,hitY:d,onFloor:v,onCeiling:M,onWallLeft:h,onWallRight:p,hazard:I,floorSolid:x}}function Uo(t,e,n,r,o,i=[],s=!1){let a=t.tileSize,u=n+o,[l,c]=He(e,e+r,a),m=Math.floor((u+1)/a);for(let d=l;d<=c;d++){let h=fe(t,d,m);if(h===U.SOLID)return{grounded:!0,solid:-1};if(h===U.ONEWAY&&!s&&Math.abs(u-m*a)<=1+X)return{grounded:!0,solid:-1}}for(let d=0;d<i.length;d++){let h=i[d];if(h.x<e+r-X&&h.x+h.w>e+X&&u<=h.y+1+X&&u>=h.y-1-X)return{grounded:!0,solid:d}}return{grounded:!1,solid:-1}}var lt={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},Oa={moveX:0,moveY:0,jumpHeld:!1,jumpPressed:!1,dashPressed:!1};function Va(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 Ha=(t,e,n)=>t<e?Math.min(t+n,e):Math.max(t-n,e);function qa(t,e,n,r,o=lt,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/K(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=Ha(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 u=e.moveY>0&&t.buffer<=0,l=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=Nt(r,{x:t.x,y:t.y,w:o.width,h:o.height},l,c,{solids:i,dropThrough:u});if(m.onCeiling&&t.vy<0&&t.dashing<=0){let d=Xa(r,i,m.x,m.y,o.width,o.height,c,o.jumpCornerNudge);d!==null&&(m=Nt(r,{x:d,y:m.y,w:o.width,h:o.height},0,c,{solids:i,dropThrough:u}),m.x=d)}if(m.hitX&&t.dashing>0&&Math.abs(t.dashVy)<1){let d=Ja(r,i,m.x,m.y,o.width,o.height,l,o.dashCornerNudge);d!==null&&(m=Nt(r,{x:m.x,y:d,w:o.width,h:o.height},l,0,{solids:i,dropThrough:u}),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:Ya(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 ja(t=lt){return t.jumpVelocity*t.jumpVelocity/(2*t.gravity)}function Xo(t=lt){return 2*t.jumpVelocity/t.gravity}function Jo(t=lt){return t.runSpeed*Xo(t)}function Ua(t=lt){return Jo(t)+(t.dashSpeed-t.runSpeed)*t.dashTime}function Xa(t,e,n,r,o,i,s,a){for(let u=1;u<=a;u++)for(let l of[1,-1]){let c=n+l*u;if(!Le(t,c,r+s,o,i,e)&&!Le(t,c,r,o,i,e))return c}return null}function Ja(t,e,n,r,o,i,s,a){for(let u=1;u<=a;u++)for(let l of[-1,1]){let c=r+l*u;if(!Le(t,n+s,c,o,i,e)&&!Le(t,n,c,o,i,e))return c}return null}function Ya(t,e,n,r,o,i){return Le(t,n+1,r,o,i,e)?1:Le(t,n-1,r,o,i,e)?-1:0}var Lt=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 u=s;u<=a;u++)for(let l=o;l<=i;l++){let c=this.key(l,u),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,u=[];for(let l=i;l<=s;l++)for(let c=r;c<=o;c++){let m=this.cells.get(this.key(c,l));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&&u.push(d)}}return u}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)),u=Math.max(s.y,Math.min(n,s.y+s.h));return(e-a)*(e-a)+(n-u)*(n-u)<=r*r})}};function Yo(t,e,n,r,o){let i=t.tileSize,s=r-e,a=o-n,u=K(s,a);if(u===0)return{blocked:!1,x:r,y:o,dist:0};let l=s/u,c=a/u,m=Math.floor(e/i),d=Math.floor(n/i),h=l>0?1:-1,p=c>0?1:-1,b=l!==0?Math.abs(i/l):1/0,v=c!==0?Math.abs(i/c):1/0,M=l!==0?(l>0?(m+1)*i-e:e-m*i)/Math.abs(l):1/0,x=c!==0?(c>0?(d+1)*i-n:n-d*i)/Math.abs(c):1/0,C=0;for(let I=0;I<512;I++){if(M<x?(C=M,M+=b,m+=h):(C=x,x+=v,d+=p),C>=u)return{blocked:!1,x:r,y:o,dist:u};if(fe(t,m,d)===U.SOLID)return{blocked:!0,x:e+l*C,y:n+c*C,dist:C}}return{blocked:!0,x:e+l*C,y:n+c*C,dist:C}}function Ko(t,e,n,r,o){return!Yo(t,e,n,r,o).blocked}function Ka(t,e,n,r,o,i,s,a,u){let l=a-e,c=u-n,m=K(l,c);return m>s||m===0||(l*r+c*o)/m<j(i/2)?!1:Ko(t,e,n,a,u)}function Qa(t={}){return{gravityX:t.gravityX??0,gravityY:t.gravityY??900,iterations:t.iterations??16,cellSize:t.cellSize??96,nextId:1,bodies:[],joints:[],warm:{}}}function Za(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],u=(i+1)%n,l=e[u*2],c=e[u*2+1],m=s*c-l*a;r+=m/2,o+=m*(s*s+s*l+l*l+a*a+a*c+c*c)/12}return{area:Math.abs(r),unitI:r!==0?Math.abs(o)/Math.abs(r):0}}var eu=1e-4;function tu(t,e){let n=e.kind??"dynamic",r=e.density??1,{area:o,unitI:i}=Za(e.shape),s=n==="dynamic"?Math.max(o*r*eu,1e-6):0,a=n==="dynamic"&&!e.fixedRotation?s*i:0,u={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((l,c,m,d)=>m%2?l:Math.max(l,d[m]*d[m]+d[m+1]*d[m+1]),0)),fx:0,fy:0,torque:0};return t.bodies.push(u),u.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 nu(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 ru(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=j(t.a),n=H(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 pn(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 ou(t,e){let n=t/2,r=e/2;return{kind:"poly",points:[-n,-r,n,-r,n,r,-n,r]}}function iu(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,u=s>1e-9?r/s:0;return{a:t,b:e,nx:a,ny:u,points:[{px:t.x+a*t.shape.r,py:t.y+u*t.shape.r,pen:o-s,feature:0}]}}function Qo(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 R=(D+1)%r,k=n[R*2]-n[D*2],T=n[R*2+1]-n[D*2+1],F=K(k,T)||1,O=T/F,A=-k/F,J=(e.x-n[D*2])*O+(e.y-n[D*2+1])*A;J>i&&(i=J,s=D)}if(i>o)return null;let a=s,u=(s+1)%r,l=n[a*2],c=n[a*2+1],m=n[u*2],d=n[u*2+1];if(i<1e-9){let D=m-l,R=d-c,k=K(D,R)||1,T=R/k,F=-D/k;return{a:t,b:e,nx:T,ny:F,points:[{px:e.x-T*o,py:e.y-F*o,pen:o-i,feature:s}]}}let h=m-l,p=d-c,b=h*h+p*p||1,v=((e.x-l)*h+(e.y-c)*p)/b;v=v<0?0:v>1?1:v;let M=l+h*v,x=c+p*v,C=e.x-M,I=e.y-x,y=C*C+I*I;if(y>=o*o)return null;let f=Math.sqrt(y)||1e-9,w=C/f,S=I/f;return{a:t,b:e,nx:w,ny:S,points:[{px:M,py:x,pen:o-f,feature:s}]}}function Zo(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,u=t[a*2]-t[s*2],l=t[a*2+1]-t[s*2+1],c=K(u,l)||1,m=l/c,d=-u/c,h=1/0;for(let p=0;p<r;p++){let b=(e[p*2]-t[s*2])*m+(e[p*2+1]-t[s*2+1])*d;b<h&&(h=b)}h>o&&(o=h,i=s)}return[o,i]}function su(t,e){let n=we(t),r=we(e),[o,i]=Zo(n,r);if(o>0)return null;let[s,a]=Zo(r,n);if(s>0)return null;let u,l,c,m;s>o+1e-4?(u=r,l=n,c=a,m=!0):(u=n,l=r,c=i,m=!1);let d=u.length/2,h=l.length/2,p=(c+1)%d,b=u[p*2]-u[c*2],v=u[p*2+1]-u[c*2+1],M=K(b,v)||1,x=v/M,C=-b/M,I=b/M,y=v/M,f=0,w=1/0;for(let _=0;_<h;_++){let B=(_+1)%h,q=l[B*2]-l[_*2],ie=l[B*2+1]-l[_*2+1],se=K(q,ie)||1,re=ie/se*x+-q/se*C;re<w&&(w=re,f=_)}let S=(f+1)%h,D=l[f*2],R=l[f*2+1],k=l[S*2],T=l[S*2+1],F=u[c*2],O=u[c*2+1],A=u[p*2],J=u[p*2+1];for(let _=0;_<2;_++){let B=_===0?F:A,q=_===0?O:J,ie=_===0?I:-I,se=_===0?y:-y,re=(D-B)*ie+(R-q)*se,ae=(k-B)*ie+(T-q)*se;if(re<0&&ae<0)return null;if(re<0){let me=re/(re-ae);D=D+(k-D)*me,R=R+(T-R)*me}else if(ae<0){let me=ae/(ae-re);k=k+(D-k)*me,T=T+(R-T)*me}}let Y=m?-x:x,te=m?-C:C,Z=[],oe=-((D-F)*x+(R-O)*C),E=-((k-F)*x+(T-O)*C),L=((m?1:0)*64+c)*64+f;return oe>0&&Z.push({px:D,py:R,pen:oe,feature:L*2}),E>0&&Z.push({px:k,py:T,pen:E,feature:L*2+1}),Z.length===0?null:{a:t,b:e,nx:Y,ny:te,points:Z}}function pr(t,e){let n=t.shape.kind,r=e.shape.kind;if(n==="circle"&&r==="circle")return iu(t,e);if(n==="poly"&&r==="poly")return su(t,e);if(n==="poly"&&r==="circle")return Qo(t,e);let o=Qo(e,t);return o?{a:t,b:e,nx:-o.nx,ny:-o.ny,points:o.points}:null}function ei(t,e,n){let r=j(t.a),o=H(t.a),i=e-t.x,s=n-t.y;return[i*r+s*o,-i*o+s*r]}function fn(t,e,n){let r=j(t.a),o=H(t.a);return[t.x+e*r-n*o,t.y+e*o+n*r]}function au(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,[u,l]=fn(n,o,i),[c,m]=fn(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??K(c-u,m-l),rope:e.rope??!1};return t.joints.push(d),ye(n),ye(r),d.id}function uu(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]=ei(n,e.px,e.py),[s,a]=ei(r,e.px,e.py),u={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(u),ye(n),ye(r),u.id}function lu(t,e){for(let n of t.joints)if(n.id===e)return n}function cu(t,e){t.joints=t.joints.filter(n=>n.id!==e)}function fr(t,e,n,r,o){let[i,s]=fn(e,t.ax,t.ay),[a,u]=fn(n,t.bx,t.by),l=i-e.x,c=s-e.y,m=a-n.x,d=u-n.y;if(t.kind==="distance"){let k=a-i,T=u-s,F=K(k,T);if(F<1e-9)return;k/=F,T/=F;let O=F-t.length;if(t.rope&&O<=0)return;let A=e.vx-e.w*c,J=e.vy+e.w*l,Y=n.vx-n.w*d,te=n.vy+n.w*m,Z=(Y-A)*k+(te-J)*T,oe=l*T-c*k,E=m*T-d*k,L=e.invM+n.invM+e.invI*oe*oe+n.invI*E*E;if(L<1e-12)return;let _=.2/r*O,B=-(Z+_)/L;t.rope&&B>0&&(B=0);let q=k*B,ie=T*B;e.vx-=q*e.invM,e.vy-=ie*e.invM,e.w-=(l*ie-c*q)*e.invI,n.vx+=q*n.invM,n.vy+=ie*n.invM,n.w+=(m*ie-d*q)*n.invI;return}if(t.maxMotorTorque>0){let k=e.invI+n.invI;if(k>1e-12){let F=-(n.w-e.w-t.motorSpeed)/k,O=t.maxMotorTorque*r,A=o.motorImpulse;o.motorImpulse=Math.min(Math.max(A+F,-O),O);let J=o.motorImpulse-A;e.w-=J*e.invI,n.w+=J*n.invI}}if(t.limitEnabled){let k=e.invI+n.invI;if(k>1e-12){let T=n.a-e.a-t.refAngle,F=0;if(T<t.limitLower?F=T-t.limitLower:T>t.limitUpper&&(F=T-t.limitUpper),F!==0){let A=-(n.w-e.w+.2/r*F)/k;(F<0&&A>0||F>0&&A<0)&&(e.w-=A*e.invI,n.w+=A*n.invI)}}}let h=e.vx-e.w*c,p=e.vy+e.w*l,b=n.vx-n.w*d,v=n.vy+n.w*m,M=a-i,x=u-s,C=b-h+.2/r*M,I=v-p+.2/r*x,y=e.invM+n.invM+e.invI*c*c+n.invI*d*d,f=-e.invI*l*c-n.invI*m*d,w=e.invM+n.invM+e.invI*l*l+n.invI*m*m,S=y*w-f*f;if(Math.abs(S)<1e-12)return;let D=-(w*C-f*I)/S,R=-(y*I-f*C)/S;e.vx-=D*e.invM,e.vy-=R*e.invM,e.w-=(l*R-c*D)*e.invI,n.vx+=D*n.invM,n.vy+=R*n.invM,n.w+=(m*R-d*D)*n.invI}var mu=.5,du=.2,hu=40,pu=64,fu=8,bu=.5,ti=100;function ni(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 gu(t,e){let n=t.bodies,r=[];if(e<=0)return r;for(let y=0;y<n.length;y++){let f=n[y];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 w=1/(1+f.linDamp*e);f.vx*=w,f.vy*=w,f.w*=1/(1+f.angDamp*e),f.fx=0,f.fy=0,f.torque=0}let o=new Lt(t.cellSize),i=new Map;for(let y=0;y<n.length;y++)o.insert(n[y],pn(n[y])),i.set(n[y],y);let s=[],a=new Set,u=new Set;for(let y of t.joints){let f=Math.min(y.a,y.b),w=Math.max(y.a,y.b);u.add(f*1048576+w)}for(let y=0;y<n.length;y++){let f=n[y],w=o.query(pn(f));for(let S of w){if(S.id<=f.id)continue;let D=f.id*1048576+S.id;if(a.has(D)||(a.add(D),u.has(D))||!ni(f,S))continue;let R=!f.sleeping&&f.kind!=="static",k=!S.sleeping&&S.kind!=="static";if(!R&&!k)continue;let T=pr(f,S);if(!T)continue;let F=(Y,te)=>{Y.sleeping&&(te.vx*te.vx+te.vy*te.vy>ti||te.kind==="kinematic")&&ye(Y)};if(F(f,S),F(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=[],A=-T.ny,J=T.nx;for(let Y of T.points){let te=Y.px-f.x,Z=Y.py-f.y,oe=Y.px-S.x,E=Y.py-S.y,L=te*T.ny-Z*T.nx,_=oe*T.ny-E*T.nx,B=f.invM+S.invM+f.invI*L*L+S.invI*_*_,q=te*J-Z*A,ie=oe*J-E*A,se=f.invM+S.invM+f.invI*q*q+S.invI*ie*ie,re=S.vx-S.w*E-f.vx+f.w*Z,ae=S.vy+S.w*oe-f.vy-f.w*te,me=re*T.nx+ae*T.ny,ve=Math.max(f.restitution,S.restitution),We=`${f.id}:${S.id}:${Y.feature}`,Te=t.warm[We],js={rax:te,ray:Z,rbx:oe,rby:E,pen:Y.pen,massN:B>1e-12?1/B:0,massT:se>1e-12?1/se:0,restBias:me<-hu?-ve*me:0,posBias:du/e*Math.max(0,Y.pen-mu),pn:Te?Te[0]:0,pt:Te?Te[1]:0,pb:0,key:We};O.push(js)}s.push({m:T,ia:y,ib:i.get(S),points:O,friction:Math.sqrt(f.friction*S.friction)})}}for(let y of s){let{a:f,b:w,nx:S,ny:D}=y.m,R=-D,k=S;for(let T of y.points){if(T.pn===0&&T.pt===0)continue;let F=S*T.pn+R*T.pt,O=D*T.pn+k*T.pt;f.vx-=F*f.invM,f.vy-=O*f.invM,f.w-=(T.rax*O-T.ray*F)*f.invI,w.vx+=F*w.invM,w.vy+=O*w.invM,w.w+=(T.rbx*O-T.rby*F)*w.invI}}s.sort((y,f)=>{let w=y.m.a.invM===0||y.m.b.invM===0?0:1,S=f.m.a.invM===0||f.m.b.invM===0?0:1;if(w!==S)return w-S;let D=Math.max(y.m.a.y,y.m.b.y),R=Math.max(f.m.a.y,f.m.b.y);return D!==R?R-D:y.m.a.id!==f.m.a.id?y.m.a.id-f.m.a.id:y.m.b.id-f.m.b.id});let l=new Float64Array(n.length),c=new Float64Array(n.length),m=new Float64Array(n.length),d=t.joints.map(()=>({motorImpulse:0}));for(let y=0;y<t.iterations;y++){for(let f=0;f<t.joints.length;f++){let w=t.joints[f],S=ge(t,w.a),D=ge(t,w.b);!S||!D||S.sleeping&&D.sleeping||(S.sleeping&&ye(S),D.sleeping&&ye(D),fr(w,S,D,e,d[f]))}for(let f of s){let{a:w,b:S,nx:D,ny:R}=f.m,{ia:k,ib:T}=f,F=-R,O=D;for(let A of f.points){let J=S.vx-S.w*A.rby-w.vx+w.w*A.ray,Y=S.vy+S.w*A.rbx-w.vy-w.w*A.rax,te=J*D+Y*R,Z=A.massN*(A.restBias-te),oe=A.pn;A.pn=Math.max(oe+Z,0),Z=A.pn-oe;let E=D*Z,L=R*Z;w.vx-=E*w.invM,w.vy-=L*w.invM,w.w-=(A.rax*L-A.ray*E)*w.invI,S.vx+=E*S.invM,S.vy+=L*S.invM,S.w+=(A.rbx*L-A.rby*E)*S.invI,J=S.vx-S.w*A.rby-w.vx+w.w*A.ray,Y=S.vy+S.w*A.rbx-w.vy-w.w*A.rax;let _=J*F+Y*O,B=A.massT*-_,q=f.friction*A.pn,ie=A.pt;if(A.pt=Math.min(Math.max(ie+B,-q),q),B=A.pt-ie,E=F*B,L=O*B,w.vx-=E*w.invM,w.vy-=L*w.invM,w.w-=(A.rax*L-A.ray*E)*w.invI,S.vx+=E*S.invM,S.vy+=L*S.invM,S.w+=(A.rbx*L-A.rby*E)*S.invI,A.posBias>0){let se=(l[T]-m[T]*A.rby-l[k]+m[k]*A.ray)*D+(c[T]+m[T]*A.rbx-c[k]-m[k]*A.rax)*R,re=A.massN*(A.posBias-se),ae=A.pb;A.pb=Math.max(ae+re,0),re=A.pb-ae;let me=D*re,ve=R*re;l[k]-=me*w.invM,c[k]-=ve*w.invM,l[T]+=me*S.invM,c[T]+=ve*S.invM}}}}let h=[],p=[];for(let y=0;y<n.length;y++){let f=n[y];h.push(f.x),p.push(f.y),!(f.invM===0&&f.kind!=="kinematic")&&(f.sleeping||(f.x+=(f.vx+l[y])*e,f.y+=(f.vy+c[y])*e,f.a+=(f.w+m[y])*e))}for(let y=0;y<n.length;y++){let f=n[y];if(!f.bullet||f.shape.kind!=="circle"||f.sleeping)continue;let w=f.x-h[y],S=f.y-p[y];if(w*w+S*S<1)continue;let D=1;for(let R=0;R<n.length;R++){let k=n[R];if(k===f||k.bullet||k.sensor||!ni(f,k))continue;let T=yu(h[y],p[y],w,S,f.shape.r,k);T>=0&&T<D&&(D=T)}if(D<1){let R=K(w,S)||1;f.x=h[y]+w*D+w/R*.4,f.y=p[y]+S*D+S/R*.4}}let b=new Set,v=[];for(let y=0;y<n.length;y++)v.push(y);let M=y=>{for(;v[y]!==y;)v[y]=v[v[y]],y=v[y];return y},x=(y,f)=>{v[M(y)]=M(f)};for(let y of s)b.add(y.m.a.id),b.add(y.m.b.id),y.m.a.kind==="dynamic"&&y.m.b.kind==="dynamic"&&x(y.ia,y.ib);for(let y of t.joints){b.add(y.a),b.add(y.b);let f=ge(t,y.a),w=ge(t,y.b);f?.kind==="dynamic"&&w?.kind==="dynamic"&&x(i.get(f),i.get(w))}for(let y=0;y<n.length;y++){let f=n[y];if(f.kind!=="dynamic")continue;let w=f.vx*f.vx+f.vy*f.vy;if(f.sleeping){w>ti&&ye(f);continue}if(!f.canSleep||!b.has(f.id)){f.sleepTime=0;continue}f.sleepTime=w<pu&&Math.abs(f.w)*f.sleepR<fu?f.sleepTime+e:0}let C=new Map;for(let y=0;y<n.length;y++){let f=n[y];if(f.kind!=="dynamic"||f.sleeping)continue;let w=M(y),S=!f.canSleep||!b.has(f.id)?-1:f.sleepTime,D=C.get(w);C.set(w,D===void 0?S:Math.min(D,S))}for(let y=0;y<n.length;y++){let f=n[y];f.kind!=="dynamic"||f.sleeping||(C.get(M(y))??-1)>=bu&&(f.sleeping=!0,f.vx=0,f.vy=0,f.w=0)}let I={};for(let y of s){let f=0;for(let S of y.points)f+=S.pn,(S.pn!==0||S.pt!==0)&&(I[S.key]=[S.pn,S.pt]);let w=y.m.points[0];r.push({a:y.m.a.id,b:y.m.b.id,px:w.px,py:w.py,nx:y.m.nx,ny:y.m.ny,impulse:f,sensor:!1})}return t.warm=I,r}function yu(t,e,n,r,o,i){if(i.shape.kind==="circle")return ri(t,e,n,r,i.x,i.y,o+i.shape.r);let s=we(i),a=s.length/2,u=-1;for(let l=0;l<a;l++){let c=(l+1)%a,m=s[l*2],d=s[l*2+1],h=s[c*2],p=s[c*2+1],b=h-m,v=p-d,M=K(b,v)||1,x=v/M,C=-b/M,I=(t-m)*x+(e-d)*C-o;if(n*x+r*C<0&&I>.5){let f=vu(t,e,n,r,m+x*o,d+C*o,h+x*o,p+C*o);f>=0&&(u<0||f<u)&&(u=f)}let y=ri(t,e,n,r,m,d,o);y>=0&&(u<0||y<u)&&(u=y)}return u}function ri(t,e,n,r,o,i,s){let a=t-o,u=e-i,l=n*n+r*r;if(l<1e-12)return-1;let c=2*(a*n+u*r);if(a*a+u*u<(s+.5)*(s+.5))return-1;let m=a*a+u*u-s*s,d=c*c-4*l*m;if(d<0)return-1;let h=(-c-Math.sqrt(d))/(2*l);return h>=0&&h<=1?h:-1}function vu(t,e,n,r,o,i,s,a){let u=s-o,l=a-i,c=n*l-r*u;if(Math.abs(c)<1e-12)return-1;let m=((o-t)*l-(i-e)*u)/c,d=((o-t)*r-(i-e)*n)/c;return m>=0&&m<=1&&d>=0&&d<=1?m:-1}function oi(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],u=r[s*2+1]-r[i*2+1];if((e-r[i*2])*u-(n-r[i*2+1])*a>0)return!1}return!0}function xu(t,e,n,r=65535){let o;for(let i of t.bodies)(i.layer&r)!==0&&oi(i,e,n)&&(o=i);return o}function wu(t,e,n,r,o,i,s){let a=t-o,u=e-i,l=n*n+r*r;if(l<1e-12)return-1;let c=2*(a*n+u*r),m=a*a+u*u-s*s,d=c*c-4*l*m;if(d<0)return-1;let h=(-c-Math.sqrt(d))/(2*l);return h>=0&&h<=1?h:-1}function ku(t,e,n,r,o,i=65535){let s=r-e,a=o-n,u=null;for(let l of t.bodies){if((l.layer&i)===0)continue;if(l.shape.kind==="circle"){let d=wu(e,n,s,a,l.x,l.y,l.shape.r);if(d>=0&&(!u||d<u.t)){let h=e+s*d,p=n+a*d,b=K(h-l.x,p-l.y)||1;u={id:l.id,t:d,x:h,y:p,nx:(h-l.x)/b,ny:(p-l.y)/b}}continue}let c=we(l),m=c.length/2;for(let d=0;d<m;d++){let h=(d+1)%m,p=c[d*2],b=c[d*2+1],v=c[h*2]-p,M=c[h*2+1]-b,x=s*M-a*v;if(Math.abs(x)<1e-12)continue;let C=((p-e)*M-(b-n)*v)/x,I=((p-e)*a-(b-n)*s)/x;if(!(C<0||C>1||I<0||I>1)&&(!u||C<u.t)){let y=K(v,M)||1;u={id:l.id,t:C,x:e+s*C,y:n+a*C,nx:M/y,ny:-v/y}}}}return u}function $t(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)}var ke=t=>Number.isInteger(t)?String(t):(Math.round(t*1e3)/1e3).toString();function si(t){let e=Math.max(1,t.length-1);return t.map((n,r)=>typeof n=="string"?{offset:r/e,color:n}:n)}function Su(t,e=90){let n=e*Math.PI/180,r=j(n)*.5,o=H(n)*.5;return{type:"linear",x1:.5-r,y1:.5-o,x2:.5+r,y2:.5+o,stops:si(t)}}function Mu(t,e={}){return{type:"radial",cx:e.cx??.5,cy:e.cy??.5,r:e.r??.5,stops:si(t)}}function Tu(t,e){return{color:t,blur:e}}function Cu(t,e,n=0,r=0){return{color:t,blur:e,dx:n,dy:r}}function Ru(t){return`<stop offset="${ke(t.offset)}" stop-color="${t.color}"/>`}function br(t,e){let n=t.stops.map(Ru).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 gr(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 yr(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 Wt(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 ii=new Set;function ct(t,e,n){let r=`${t}:${e}`;ii.has(r)||(ii.add(r),console.warn(`hayao/render: skipped '${t}' command \u2014 ${e}`,n))}function vr(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 qe(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 je(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 W=t=>Number.isInteger(t)?String(t):(Math.round(t*1e3)/1e3).toString();function Pu(t){return`matrix(${W(t.a)} ${W(t.b)} ${W(t.c)} ${W(t.d)} ${W(t.e)} ${W(t.f)})`}function Eu(t,e,n){let r=[];return r.push(`fill="${e??t.fill??"none"}"`),t.stroke&&(r.push(`stroke="${t.stroke}"`),r.push(`stroke-width="${W(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(W).join(" ")}"`)),t.opacity!==void 0&&t.opacity!==1&&r.push(`opacity="${W(t.opacity)}"`),n&&r.push(`filter="url(#${n})"`),r.join(" ")}function Du(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Iu(t){let e=t.radius,n=t.cx+j(t.start)*e,r=t.cy+H(t.start)*e,o=t.end-t.start,i=(o%Q+Q)%Q;if(i===0&&o!==0&&(i=Q),i>=Q-1e-9){let c=t.cx+j(t.start+Math.PI)*e,m=t.cy+H(t.start+Math.PI)*e;return`M ${W(n)} ${W(r)} A ${W(e)} ${W(e)} 0 1 1 ${W(c)} ${W(m)} A ${W(e)} ${W(e)} 0 1 1 ${W(n)} ${W(r)} Z`}let s=t.cx+j(t.start+i)*e,a=t.cy+H(t.start+i)*e,u=i>Math.PI?1:0,l=`A ${W(e)} ${W(e)} 0 ${u} 1 ${W(s)} ${W(a)}`;return t.sector?`M ${W(t.cx)} ${W(t.cy)} L ${W(n)} ${W(r)} ${l} Z`:`M ${W(n)} ${W(r)} ${l}`}function Fu(t,e,n){let r=`transform="${Pu(t.transform)}"`,o,i;if(t.gradient){let a=`${n}g`;e.push(br(t.gradient,a)),o=`url(#${a})`}t.shadow&&(i=`${n}s`,e.push(gr(t.shadow,i)));let s=Eu(t,o,i);switch(t.kind){case"rect":return`<rect x="${W(t.x)}" y="${W(t.y)}" width="${W(t.w)}" height="${W(t.h)}"${t.r?` rx="${W(t.r)}"`:""} ${r} ${s}/>`;case"circle":return`<circle cx="${W(t.cx)}" cy="${W(t.cy)}" r="${W(t.radius)}" ${r} ${s}/>`;case"ellipse":return`<ellipse cx="${W(t.cx)}" cy="${W(t.cy)}" rx="${W(t.rx)}" ry="${W(t.ry)}" ${r} ${s}/>`;case"arc":return`<path d="${Iu(t)}" ${r} ${s}/>`;case"poly":{let a=[];for(let l=0;l<t.points.length;l+=2)a.push(`${W(t.points[l])},${W(t.points[l+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",u=t.font?` font-family="${t.font}"`:"",l=t.weight?` font-weight="${t.weight}"`:"",c=o??t.fill??"#000",m=i?` filter="url(#${i})"`:"",d=t.stroke?` stroke="${t.stroke}" stroke-width="${W(t.strokeWidth??1)}" paint-order="stroke"${t.round?' stroke-linejoin="round"':""}`:"",h=t.opacity!==void 0&&t.opacity!==1?` opacity="${W(t.opacity)}"`:"";return`<text x="${W(t.x)}" y="${W(t.y)}" font-size="${W(t.size)}" text-anchor="${a}" dominant-baseline="middle"${u}${l} fill="${c}"${d}${h}${m} ${r}>${Du(t.text)}</text>`}case"image":{let a=i?` filter="url(#${i})"`:"";return`<image href="${t.href}" x="${W(t.x)}" y="${W(t.y)}" width="${W(t.w)}" height="${W(t.h)}" ${r}${t.opacity!==void 0&&t.opacity!==1?` opacity="${W(t.opacity)}"`:""}${a}/>`}}}function Ue(t,e="h"){let n=[],r=$t(t).map((o,i)=>{let s=Wt(o);return s?(ct(o.kind,s,o),""):Fu(o,n,`${e}${i}`)}).join("");return(n.length?`<defs>${n.join("")}</defs>`:"")+r}function zt(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}"/>`+Ue(t)+"</svg>"}var xr="http://www.w3.org/2000/svg",Xe=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(xr,"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(xr,"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(xr,"g"),this.svg.appendChild(this.layer)}mount(e){e.appendChild(this.svg)}draw(e){this.layer.innerHTML=Ue(e)}setBackground(e){this.background=e,this.bg.setAttribute("fill",e)}get element(){return this.svg}toDesign(e,n){return qe(this.svg.getBoundingClientRect(),this.width,this.height,e,n)}viewport(){return je(this.svg.getBoundingClientRect(),this.width,this.height)}dispose(){this.svg.remove()}};function ai(t,e){let n=e;if(n.gradient){let r=yr(e);if(r&&r.w>0&&r.h>0)return vr(t,n.gradient,r);let o=n.gradient.stops;return o.length?o[o.length-1].color:n.fill}return n.fill}function Bt(t,e){let n=ai(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 Au(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 Nu(t,e){switch(e.kind){case"rect":t.beginPath(),e.r?Au(t,e.x,e.y,e.w,e.h,e.r):t.rect(e.x,e.y,e.w,e.h),Bt(t,e);break;case"circle":t.beginPath(),t.arc(e.cx,e.cy,e.radius,0,Math.PI*2),Bt(t,e);break;case"ellipse":t.beginPath(),t.ellipse(e.cx,e.cy,e.rx,e.ry,0,0,Math.PI*2),Bt(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(),Bt(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(),Bt(t,e);break;case"path":{let n=new Path2D(e.d),r=ai(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 bn(t,e,n,r,o,i){t.setTransform(i,0,0,i,0,0),t.fillStyle=o,t.fillRect(0,0,n,r);for(let s of $t(e)){let a=Wt(s);if(a){ct(s.kind,a,s);continue}t.save();try{let u=s.transform;t.transform(u.a,u.b,u.c,u.d,u.e,u.f),t.globalAlpha=s.opacity??1;let l=s.shadow;l&&(t.shadowColor=l.color,t.shadowBlur=l.blur,t.shadowOffsetX=l.dx??0,t.shadowOffsetY=l.dy??0);let c=s.lineDash;c&&c.length&&t.setLineDash(c),Nu(t,s)}catch(u){ct(s.kind,"paint threw",u)}t.restore()}}var Je=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){bn(this.ctx,e,this.width,this.height,this.background,this.dpr)}get element(){return this.canvas}toDesign(e,n){return qe(this.canvas.getBoundingClientRect(),this.width,this.height,e,n)}viewport(){return je(this.canvas.getBoundingClientRect(),this.width,this.height)}dispose(){this.canvas.remove()}};var Lu=`#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
+ }`,gn=`#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); }`,_t={passthrough:gn,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
+ }`},$u=[{shader:_t.bloomBrightpass},{shader:_t.bloomHBlur},{shader:_t.bloomVBlur},{shader:_t.bloomComposite}];function ui(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 Wu(t,e){let n=ui(t,t.VERTEX_SHADER,Lu),r=ui(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 li(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 zu(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 Gt=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??gn}])}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(Wu(n,i.shader)),this.passUniforms.push(i.uniforms??{});for(let i=0;i<e.length-1;i++)this.fbos.push(zu(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;bn(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 u=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(u),n.uniform1i(n.getUniformLocation(u,"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(u,"u_prev"),1),n.activeTexture(n.TEXTURE0),n.uniform1f(n.getUniformLocation(u,"u_time"),o),n.uniform2f(n.getUniformLocation(u,"u_resolution"),i,s);for(let[c,m]of this.uniforms)li(n,u,c,m);for(let[c,m]of Object.entries(this.passUniforms[a]))li(n,u,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:gn}]),this}setPostProcess(e){return this.setPipeline([{shader:e}])}clearPostProcess(){return this.setPostProcess(gn)}get element(){return this.glCanvas}toDesign(e,n){return qe(this.glCanvas.getBoundingClientRect(),this.width,this.height,e,n)}viewport(){return je(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 wr=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 zt(this.last,this.width,this.height,this.background)}};function Bu(t,e,n=0,r=ue){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,u=[],l=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,b=t.w-2*o,v=t.h-2*o,M=(C,I,y,f,w,S)=>{y<=0||f<=0||u.push({kind:"rect",x:C,y:I,w:y,h:f,r:S,fill:w,transform:r,z:n})};M(c,h,b,v,i),M(c,d,b,o,e.highlight??s),M(c,p,b,o,e.shadow??s),M(l,h,o,v,e.highlight??s),M(m,h,o,v,e.shadow??s);let x=e.radius;return M(l,d,o,o,a,x),M(m,d,o,o,a,x),M(l,p,o,o,a,x),M(m,p,o,o,a,x),e.stroke&&u.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}),u}var _u={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 z={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"},mi={name:"meadow",bg:z.washi,ink:z.sumi,inkSoft:z.sumiSoft,line:z.line,accent:z.shuDeep,accent2:z.aiDeep,good:z.matsuDeep,warn:z.kakiDeep,ramp:[z.shuDeep,z.kakiDeep,z.koDeep,z.matsuDeep,z.asagiDeep,z.aiDeep,z.fujiDeep,z.sakuDeep],swatches:z},di={name:"dusk",bg:z.kuro,ink:z.gofun,inkSoft:z.kinako,line:z.darkLine,accent:z.shu,accent2:z.asagi,good:z.matsu,warn:z.ko,ramp:[z.shu,z.kaki,z.ko,z.matsu,z.asagi,z.ai,z.fuji,z.saku],swatches:z},hi={name:"paper",bg:z.gofun,ink:z.sumi,inkSoft:z.stone,line:z.kinu,accent:z.sakuDeep,accent2:z.asagiDeep,good:z.matsuDeep,warn:z.kakiDeep,ramp:[z.sakuDeep,z.kakiDeep,z.koDeep,z.matsuDeep,z.asagiDeep,z.aiDeep,z.fujiDeep,z.shuDeep],swatches:z},Gu={meadow:mi,dusk:di,paper:hi};function Ou(t,e,n){let r=mt(t),o=mt(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 Ot(i,s,a)}function Vu(t,e){let[n,r,o]=mt(t);return`rgba(${n}, ${r}, ${o}, ${e})`}function mt(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 Ot(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 pi=t=>(t%360+360)%360,Vt=t=>t<0?0:t>1?1:t;function fi(t,e,n){if(t=pi(t)/360,e=Vt(e),n=Vt(n),e===0){let s=n*255;return Ot(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 Ot(i(t+1/3)*255,i(t)*255,i(t-1/3)*255)}function Hu(t,e,n){t=pi(t)/60,e=Vt(e),n=Vt(n);let r=n*e,o=r*(1-Math.abs(t%2-1)),i=n-r,s=0,a=0,u=0;return t<1?[s,a,u]=[r,o,0]:t<2?[s,a,u]=[o,r,0]:t<3?[s,a,u]=[0,r,o]:t<4?[s,a,u]=[0,o,r]:t<5?[s,a,u]=[o,0,r]:[s,a,u]=[r,0,o],Ot((s+i)*255,(a+i)*255,(u+i)*255)}function bi(t){let[e,n,r]=mt(t),o=e/255,i=n/255,s=r/255,a=Math.max(o,i,s),u=Math.min(o,i,s),l=(a+u)/2,c=a-u;if(c===0)return{h:0,s:0,l};let m=l>.5?c/(2-a-u):c/(a+u),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}}function qu(t,e,n={}){let r=bi(e),o=n.hue??0,i=n.sat??0,s=n.light??0;return fi(r.h+t.range(-o,o),r.s+t.range(-i,i),r.l+t.range(-s,s))}var ci=t=>t<=.04045?t/12.92:Re((t+.055)/1.055,2.4),ju=t=>t<=.0031308?t*12.92:1.055*Re(t,1/2.4)-.055;function gi(t,e,n){let r=mt(t),o=mt(e),i=s=>{let a=ci(r[s]/255),u=ci(o[s]/255);return ju(a+(u-a)*n)*255};return Ot(i(0),i(1),i(2))}function kr(t,e){if(t.length===0)return"#000000";if(t.length===1)return t[0];let r=Vt(e)*(t.length-1),o=Math.min(t.length-2,Math.floor(r));return gi(t[o],t[o+1],r-o)}function Uu(t,e){return e<=0?[]:e===1?[kr(t,0)]:Array.from({length:e},(n,r)=>kr(t,r/(e-1)))}function Xu(t,e,n=0){let r=[];for(let o=0;o<t;o++){let i=n+o/t*Q;r.push(j(i)*e,H(i)*e)}return r}function Ju(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)*Q;o.push(j(a)*s,H(a)*s)}return o}function Yu(t,e,n=.25,r=7){let o=[];for(let i=0;i<r;i++){let s=i/r*Q,a=e*(1-n+t.float()*n*2);o.push({x:j(s)*a,y:H(s)*a})}return yi(o)}function yi(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),u=r(s),l=r(s+1),c=r(s+2),m=u.x+(l.x-a.x)/6*e,d=u.y+(l.y-a.y)/6*e,h=l.x-(c.x-u.x)/6*e,p=l.y-(c.y-u.y)/6*e;i+=` C ${o(m)} ${o(d)}, ${o(h)} ${o(p)}, ${o(l.x)} ${o(l.y)}`}return i+" Z"}function Ku(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],u=t[i+1],l=t[Math.min(n-1,i+2)],c=a.x+(u.x-s.x)/6*e,m=a.y+(u.y-s.y)/6*e,d=u.x-(l.x-a.x)/6*e,h=u.y-(l.y-a.y)/6*e;o+=` C ${r(c)} ${r(m)}, ${r(d)} ${r(h)}, ${r(u.x)} ${r(u.y)}`}return o}var dt=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 u=0;u<a.length;u++)i.data[s*o+u]=n[a[u]]??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 vi(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 Qu(t,e,n){let r=vi(t),o=e*n,i=new dt(e,n);for(let s=0;s<o;s++)i.data[s]=Number(r>>BigInt(o-1-s)&1n);return i}function Zu(t,e,n){let r=vi(t),o=e*n,i=new dt(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 el(t,e,n){let r=new dt(e,n),o=0;for(let i=0;i+1<t.length;i+=2){let s=t[i],a=t[i+1];for(let u=0;u<s&&o<r.data.length;u++)r.data[o++]=a}return r}function tl(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 xi(t,e,n={}){let r=n.cell??1,o=n.x??0,i=n.y??0,s=n.z??0,a=n.transform??ue,u=[];for(let l=0;l<t.height;l++){let c=0;for(;c<t.width;){let m=t.get(c,l),d=e[m];if(d==null){c++;continue}let h=1;for(;c+h<t.width&&t.get(c+h,l)===m;)h++;u.push({kind:"rect",x:o+c*r,y:i+l*r,w:h*r,h:r,transform:a,z:s,fill:d}),c+=h}}return u}var Sr=class extends V{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 xi(this.buffer,this.palette,{cell:r,x:o,y:i,z:this.z,transform:n}))e.push(s)}};var nl={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:[".#.","#.#",".##","..#","##."],".":[".",".",".",".","#"],",":["..","..","..",".#","#."],"!":["#","#","#",".","#"],"?":["##.","..#",".#.","...",".#."],":":[".","#",".","#","."],";":["..",".#","..",".#","#."],"-":["...","...","###","...","..."],"+":["...",".#.","###",".#.","..."],"=":["...","###","...","###","..."],"/":["..#","..#",".#.","#..","#.."],"'":["#","#",".",".","."],'"':["#.#","#.#","...","...","..."],"(":[".#","#.","#.","#.",".#"],")":["#.",".#",".#",".#","#."],"<":["..#",".#.","#..",".#.","..#"],">":["#..",".#.","..#",".#.","#.."],"%":["#.#","..#",".#.","#..","#.#"],"*":["...","#.#",".#.","#.#","..."],"#":["#.#","###","#.#","###","#.#"]},Mr={height:5,tracking:1,spaceWidth:3,glyphs:nl};function wi(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 u=t.slice(o+1,a);u==="/"?r.pop():r.push(u[0]==="#"?u:e[u]??u),o=a+1;continue}n.push({ch:s,color:r[r.length-1],i:i++}),o++}return n}function ki(t,e){if(e===" "||e===`
174
+ `)return e;let n=e.toUpperCase();return t.glyphs[n]?n:t.glyphs[e]?e:t.glyphs["?"]?"?":" "}function Si(t,e){if(e===" ")return t.spaceWidth;let n=t.glyphs[e];return n?n[0].length:t.spaceWidth}function ht(t,e){let n=0;for(let r=0;r<e.length;r++)n+=Si(t,e[r].ch),r<e.length-1&&(n+=t.tracking);return n}function rl(t,e){return ht(t,[...e].map((n,r)=>({ch:ki(t,n),i:r})))}function Mi(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:ki(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 b=d.length?t.spaceWidth+t.tracking:0;d.length&&ht(t,d)+b+ht(t,h)>n.maxWidth&&(s.push(d),d=[]),d.length&&d.push({ch:" ",i:-1}),d.push(...h),h=[]};for(let b of m)b.ch===" "?p():h.push(b);p(),s.push(d)}let a=[],u=0;for(let m of s)u=Math.max(u,ht(t,m));let l=n.maxWidth??u,c=0;for(let m of s){let d=ht(t,m),h=n.align==="center"?Math.floor((l-d)/2):n.align==="right"?l-d:0;for(let p of m){let b=Si(t,p.ch);p.ch!==" "&&a.push({ch:p.ch,color:p.color,i:p.i,x:h,y:c,w:b}),h+=b+t.tracking}c+=t.height+r}return{glyphs:a,width:l,height:s.length*(t.height+r)-r,lines:s.length}}function Ti(t,e,n){if(n<=0)return t;let r=Math.floor(e*n);return r<0?0:r>t?t:r}function Ci(t,e,n={}){let r=n.cell??2,o=n.x??0,i=n.y??0,s=n.z??0,a=n.transform??ue,u=n.color??"#000",l=n.reveal,c=[];for(let m of e.glyphs){if(l!==void 0&&m.i>=l)continue;let d=t.glyphs[m.ch];if(!d)continue;let h=m.color??u;for(let p=0;p<d.length;p++){let b=d[p],v=0;for(;v<b.length;){if(b[v]!=="#"){v++;continue}let M=1;for(;v+M<b.length&&b[v+M]==="#";)M++;c.push({kind:"rect",x:o+(m.x+v)*r,y:i+(m.y+p)*r,w:M*r,h:r,transform:a,z:s,fill:h}),v+=M}}}return c}var Tr=class extends V{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??Mr,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=wi(this.text,this.colorMap);return Mi(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=Ti(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 Ci(this.font,r,{cell:this.cell,x:i,y:s,z:this.z,color:this.color,transform:n,reveal:o}))e.push(a)}};function ol(t,e="#"){return t.map(n=>[...n].map(r=>e.includes(r)))}function Ie(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 Cr(t,e,n){return(Ie(t,e,n-1)?ne.N:0)|(Ie(t,e+1,n)?ne.E:0)|(Ie(t,e,n+1)?ne.S:0)|(Ie(t,e-1,n)?ne.W:0)}function il(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++)Ie(t,e+o[i][0],n+o[i][1])&&(r|=1<<i);return r}var Ye={Isolated:0,Cap:1,Straight:2,Bend:3,Tee:4,Cross:5};function sl(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 al=(()=>{let t=[[Ye.Isolated,0],[Ye.Cap,ne.N],[Ye.Straight,ne.N|ne.S],[Ye.Bend,ne.N|ne.E],[Ye.Tee,ne.N|ne.E|ne.S],[Ye.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=sl(o)}return e})();function Ri(t){return al[t&15]}function ul(t){return t.map((e,n)=>e.map((r,o)=>r?Ri(Cr(t,o,n)):null))}function Pi(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((Ie(t,s,o)?1:0)|(Ie(t,s+1,o)?2:0)|(Ie(t,s+1,o+1)?4:0)|(Ie(t,s,o+1)?8:0));r.push(i)}return r}var ll=[[],[["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 Ei(t,e={}){let n=e.cell??1,r=e.x??0,o=e.y??0,i=Pi(t),s=[],a=(u,l,c)=>{switch(u){case"T":return{x:l+n/2,y:c};case"R":return{x:l+n,y:c+n/2};case"B":return{x:l+n/2,y:c+n};case"L":return{x:l,y:c+n/2}}};for(let u=0;u<i.length;u++)for(let l=0;l<i[u].length;l++){let c=r+l*n,m=o+u*n;for(let[d,h]of ll[i[u][l]])s.push({a:a(d,c,m),b:a(h,c,m)})}return s}function cl(t,e={}){let n=e.tile??8,r=e.x??0,o=e.y??0,i=e.z??0,s=e.transform??ue,a=e.fill??"#888",u=e.edge,l=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}),!u)continue;let b=Cr(t,d,m),v=M=>c.push({kind:"poly",points:M,closed:!1,transform:s,z:i+1,stroke:u,strokeWidth:l});b&ne.N||v([h,p,h+n,p]),b&ne.E||v([h+n,p,h+n,p+n]),b&ne.S||v([h,p+n,h+n,p+n]),b&ne.W||v([h,p,h,p+n])}return c}function ml(t,e={}){let n=e.tile??8,r=e.transform??ue,o=e.z??0,i=e.edge??e.fill??"#333",s=e.edgeWidth??Math.max(1,n/8);return Ei(t,{cell:n,x:e.x??0,y:e.y??0}).map(u=>({kind:"poly",points:[u.a.x,u.a.y,u.b.x,u.b.y],closed:!1,transform:r,z:o,stroke:i,strokeWidth:s,round:!0}))}function pt(t,e,n=0){return{cols:t,rows:e,cells:new Array(t*e).fill(n)}}function Di(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 Rr(t,e,n){let r=0;for(let o=-1;o<=1;o++)for(let i=-1;i<=1;i++)i===0&&o===0||Di(t,e+i,n+o)===1&&r++;return r}function dl(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 Fi(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 Ke(t,e,n=0){return Fi(t,e,n)/4294967296}function hl(t,e,n,r=0){return Math.floor(Ke(t,e,r)*n)}function Ai(t,e,n,r=0){return Ke(t,e,r)<n}function pl(t,e,n,r,o,i=0){let s=[];for(let a=e;a<e+r;a++)for(let u=t;u<t+n;u++)Ai(u,a,o,i)&&s.push({x:u,y:a});return s}var Ii=t=>t*t*(3-2*t);function Ni(t,e,n=0){let r=Math.floor(t),o=Math.floor(e),i=Ii(t-r),s=Ii(e-o),a=Ke(r,o,n),u=Ke(r+1,o,n),l=Ke(r,o+1,n),c=Ke(r+1,o+1,n),m=a+(u-a)*i,d=l+(c-l)*i;return m+(d-m)*s}function Pr(t,e,n=0,r={}){let o=r.octaves??4,i=r.lacunarity??2,s=r.gain??.5,a=1,u=1,l=0,c=0;for(let m=0;m<o;m++)l+=a*Ni(t*u,e*u,n+m),c+=a,a*=s,u*=i;return c===0?0:l/c}function fl(t,e){let{cols:n,rows:r}=e,o=e.fill??.45,i=e.steps??4,s=e.birth??5,a=e.survive??4,u=e.border??!0,l=pt(n,r,0);for(let c=0;c<r;c++)for(let m=0;m<n;m++){let d=u&&(m===0||c===0||m===n-1||c===r-1);Fe(l,m,c,d||t.chance(o)?1:0)}for(let c=0;c<i;c++){let m=pt(n,r,0);for(let d=0;d<r;d++)for(let h=0;h<n;h++){if(u&&(h===0||d===0||h===n-1||d===r-1)){Fe(m,h,d,1);continue}let p=Rr(l,h,d),b=l.cells[d*n+h]===1;Fe(m,h,d,(b?p>=a:p>=s)?1:0)}l=m}return l}function Er(t,e){let n=e.scale??.08,r=e.seed??0,o=Pr(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=ee(i,e.minRow??-1/0,e.maxRow??1/0)),i}function bl(t,e,n){let r=new Array(e);for(let o=0;o<e;o++)r[o]=Er(t+o,n);return r}function gl(t,e,n){return e>=Er(t,n)}function Dr(t){return{x:Math.floor(t.x+t.w/2),y:Math.floor(t.y+t.h/2)}}function yl(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 vl(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 Li(t,e,n,r){for(let o=Math.min(e,n);o<=Math.max(e,n);o++)Fe(t,o,r,0)}function $i(t,e,n,r){for(let o=Math.min(e,n);o<=Math.max(e,n);o++)Fe(t,r,o,0)}function xl(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,u=pt(n,r,1),l=[];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 b={x:h,y:p,w:m,h:d};if(!l.some(v=>yl(b,v))){if(vl(u,b),l.length>0){let v=Dr(l[l.length-1]),M=Dr(b);t.chance(.5)?(Li(u,v.x,M.x,v.y),$i(u,v.y,M.y,M.x)):($i(u,v.y,M.y,v.x),Li(u,v.x,M.x,M.y))}l.push(b)}}return{rooms:l,grid:u}}var be=44100;function Fr(t,e=be){let n=Math.max(0,Math.round(t*e));return{sampleRate:e,left:new Float32Array(n),right:new Float32Array(n)}}function wl(t){return t.left.length}function kl(t){return t.left.length/t.sampleRate}function Wi(t){let n=(ee(t,-1,1)+1)*.5*(Math.PI/2);return{l:j(n),r:H(n)}}function Ar(t,e,n,r=1,o=0){let{l:i,r:s}=Wi(o),a=r*i,u=r*s,l=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>=l)break;let h=e[m];t.left[d]+=h*a,t.right[d]+=h*u}}function zi(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 Ir(t){return t/Math.sqrt(1+t*t)}function Nr(t){let{left:e,right:n}=t;for(let r=0;r<e.length;r++)e[r]=Ir(e[r]),n[r]=Ir(n[r])}function Lr(t,e=.89){let n=zi(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 Sl(t){let{left:e,right:n,sampleRate:r}=t,o=e.length,i=2,a=i*2,u=o*a,l=new Uint8Array(44+u),c=new DataView(l.buffer),m=(h,p)=>{for(let b=0;b<p.length;b++)c.setUint8(h+b,p.charCodeAt(b))};m(0,"RIFF"),c.setUint32(4,36+u,!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,u,!0);let d=44;for(let h=0;h<o;h++){let p=ee(e[h],-1,1),b=ee(n[h],-1,1);c.setInt16(d,(p<0?p*32768:p*32767)|0,!0),c.setInt16(d+2,(b<0?b*32768:b*32767)|0,!0),d+=4}return l}function Ml(t){let e=2166136261;for(let n=0;n<t.length;n++){let r=ee(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 Tl(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 yn(t){return pe(t/12)}function Bi(t,e,n,r){switch(t){case"sine":return H(Q*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 Ht(t,e={}){let n=Tl(t),r=e.sampleRate??be,o=e.rng??new le(24301),i=n.attack+n.decay+n.sustain+n.release,s=n.delay>0?n.delay*6:0,a=i+s+.01,u=Math.max(1,Math.round(a*r)),l=new Float32Array(u),c=1/r,m=0,d=0,h=0,p=n.detune!==0?yn(n.detune/100):1,b=0,v=0,M=0,x=0,C=n.lowpass>0?_i(n.lowpass,r):1,I=n.highpass>0?1-_i(n.highpass,r):0,y=r*.5;for(let f=0;f<u;f++){let w=f*c,S=Cl(w,n);n.punch>0&&(S*=1+n.punch*Math.max(0,1-w/Math.max(1e-4,n.attack+n.decay))),n.tremolo>0&&(S*=1-n.tremolo*.5*(1-H(Q*n.tremoloFreq*w)));let D=n.repeat>0?w-Math.floor(w/n.repeat)*n.repeat:w,R=i>0?D/i:0,k=n.freq*yn(n.slide*R+n.slideAccel*R*R);n.pitchJump!==0&&D>=n.pitchJumpTime&&(k*=yn(n.pitchJump)),n.vibrato>0&&(k*=yn(n.vibrato*H(Q*n.vibratoFreq*w))),n.fm>0&&(k+=n.fm*H(Q*n.fmFreq*w)),k<0?k=0:k>y&&(k=y),m+=k*c,m-=Math.floor(m);let T=Bi(n.wave,m,n.duty,o);n.detune!==0&&(d+=k*p*c,d-=Math.floor(d),T=(T+Bi(n.wave,d,n.duty,o))*.5),n.sub>0&&(h+=k*.5*c,h-=Math.floor(h),T=T*(1-n.sub*.5)+H(Q*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)*Re(T<0?-T:T,n.shapeCurve)),T*=S*n.volume,n.bitCrush>0&&(f%n.bitCrush===0&&(b=T),T=b),l[f]=T}if(n.lowpass>0)for(let f=0;f<u;f++)v+=C*(l[f]-v),l[f]=v;if(n.highpass>0)for(let f=0;f<u;f++)M=I*(M+l[f]-x),x=l[f],l[f]=M;if(n.delay>0){let f=Math.max(1,Math.round(n.delay*r));for(let w=f;w<u;w++)l[w]+=l[w-f]*n.delayFeedback}return l}function _i(t,e){let n=Q*t*(1/e);return n/(n+1)}function Cl(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 Rl={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},Pl=["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=Rl[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 El(t){let e=(t%12+12)%12,n=Math.floor(t/12)-1;return Pl[e]+n}function Gi(t,e=440){return e*pe((t-69)/12)}function $r(t,e=440){return Gi(typeof t=="number"?t:ce(t),e)}var Wr={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=Wr[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 zr(t,e="major"){let n=(t%12+12)%12;return new Set(Wr[e].map(r=>(n+r)%12))}function Oi(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 Dl={i:0,ii:1,iii:2,iv:3,v:4,vi:5,vii:6};function Qe(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=Dl[o[1].toLowerCase()];if(i===void 0)throw new Error(`bad roman numeral: ${JSON.stringify(r)}`);return Oi(t,e,i,o[2]?4:3)})}function Il(t,e){return t.map(n=>n+e)}function xn(t){return t.length<2?t.slice():[t[0]-12,...t.slice(1)].sort((e,n)=>e-n)}function ft(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 Fl=[1116,1188,1277,1356,1422,1491,1557,1617],Al=[556,441,341,225],Nl=23,Ll=.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}},_r=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 Vi(t,e,n,r){let o=t/44100,i=Fl.map(a=>new Br(Math.round((a+r)*o),e,n)),s=Al.map(a=>new _r(Math.round((a+r)*o),.5));return{combs:i,aps:s}}function Gr(t,e={}){let n=ee(e.wet??.25,0,1),r=ee(e.roomSize??.7,0,1),o=ee(e.damp??.5,0,1)*.4,i=.7+r*.28,s=t.sampleRate,a=Vi(s,i,o,0),u=Vi(s,i,o,Nl),l=t.left.length;for(let c=0;c<l;c++){let m=(t.left[c]+t.right[c])*Ll,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 u.combs)h+=p.process(m);for(let p of u.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 $l(t){let e=0;for(let n of t)e+=n.beats;return e}function Wl(t){let e=0;for(let n of t.sequence)e+=$l(t.patterns[n]??[]);return e}function qi(t){let e=0;for(let n of t.tracks)e=Math.max(e,Wl(n));return e}function wn(t){return qi(t)*60/t.bpm}function Or(t,e={}){let n=e.sampleRate??be,r=t.a4??440,o=60/t.bpm,i=t.tailSec??2,s=wn(t)+i,a=Fr(s,n),u=Math.max(0,Math.min(1,t.swing??0)),l=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,b=new le(5292449^(d+1)*2654435769),v=0;for(let M of m.sequence){let x=m.patterns[M];if(x)for(let C of x){if(C.pitch!==null&&C.pitch!==void 0){let I=Math.round(v*2),f=Math.abs(v*2-I)<1e-4&&I%2===1?v+u*.2:v,w=l>0?b.range(-1,1)*l*.012:0,S=Math.round((f*o+w)*n),D=C.beats*o,R=l>0?b.range(-1,1)*l*.12:0,k=Math.max(.05,Math.min(1,(C.vel??1)+R)),T=Array.isArray(C.pitch)?C.pitch:[C.pitch],F=m.instrument.attack??.005,O=m.instrument.decay??0,A=Math.max(.01,D-F-O),J=m.instrument.lowpass,Y=J&&c>0?J*(1-c*(1-k)):J;for(let te of T){let Z={...m.instrument,freq:$r(te,r),sustain:A,volume:(m.instrument.volume??.5)*k,...Y!==void 0?{lowpass:Y}:{}},oe=Ht(Z,{rng:b,sampleRate:n});Ar(a,oe,Math.max(0,S),h,p)}}v+=C.beats}}}),t.sidechain){let m=Math.max(0,Math.min(1,t.sidechain.depth??.5)),d=(t.sidechain.beatsPerCycle??1)*o;_l(a,d,m)}return t.reverb&&Gr(a,t.reverb),t.master&&Bl(a,t.master),t.master?.compress&&zl(a,t.master.compress),Nr(a),Lr(a,e.normalizePeak??.89),a}function zl(t,e){let n=Math.max(0,Math.min(1,e)),r=t.sampleRate,o=Hi(-20),i=2+n*3,s=Be(-1/(r*.005)),a=Be(-1/(r*.15)),u=Hi(n*6),l=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>l?s:a;l=p*l+(1-p)*h;let b=1;if(l>o){let M=l/o;b=o*Re(M,1/i)/l}let v=b*u;c[d]*=v,m[d]*=v}}function Hi(t){return pe(t/6.020599913)}function Bl(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=Q*c*(1/n);return m/(m+1)},a=s(240),u=1-s(3200),l=1-s(9e3);for(let c of[t.left,t.right]){let m=0,d=0,h=0,p=0,b=0;for(let v=0;v<c.length;v++){let M=c[v];m+=a*(M-m),d=u*(d+M-h),h=M,p=l*(p+M-b),b=M,c[v]=M-r*m+o*d+i*p}}}function _l(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,u=1-n*a*a;t.left[i]*=u,t.right[i]*=u}}var $={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 Gl={master:.7,music:.6,sfx:.8,muted:!1},kn=class{_ctx=null;master=null;musicGain=null;sfxGain=null;vol={...Gl};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,u=this._ctx.currentTime+s,l=this._ctx.createOscillator();l.type=o,l.frequency.value=n;let c=this._ctx.createGain();if(c.gain.setValueAtTime(0,u),c.gain.linearRampToValueAtTime(i,u+.008),c.gain.exponentialRampToValueAtTime(1e-4,u+r),l.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);l.start(u),l.stop(u+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=Ht(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=Or(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=wn(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)}},$e=new kn;function Sn(t){let e=t<0?-t:t;return e<1e-12?-1/0:20*St(e)}function bt(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 ji(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 Ol(t){let e=1;for(;e*2<=t;)e*=2;return e}function Ui(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=-Q/r,i=j(o),s=H(o);for(let a=0;a<n;a+=r){let u=1,l=0;for(let c=0;c<r/2;c++){let m=a+c,d=m+r/2,h=u*t[d]-l*e[d],p=u*e[d]+l*t[d];t[d]=t[m]-h,e[d]=e[m]-p,t[m]+=h,e[m]+=p;let b=u*i-l*s;l=u*s+l*i,u=b}}}}function gt(t){let e=Ol(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(Q*s/(e-1));n[s]=t[s]*a}Ui(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 Xi(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)),u=gt(a),l=e/(u.length*2);for(let c=0;c<u.length;c++)o+=c*l*u[c],i+=u[c]}return i<1e-9?0:o/i}function Hr(t,e=1024,n=512){let r=[],o=null;for(let i=0;i+e<=t.length;i+=n){let s=gt(t.subarray(i,i+e)),a=0;if(o){let u=Math.min(s.length,o.length);for(let l=0;l<u;l++){let c=s[l]-o[l];c>0&&(a+=c)}}r.push(a),o=s}return Float32Array.from(r)}function Ji(t,e=be){let r=Hr(t,1024,512);if(r.length<3)return 0;let o=0;for(let u=0;u<r.length;u++)o+=r[u];o/=r.length;let i=o*1.5,s=0;for(let u=1;u<r.length-1;u++)r[u]>i&&r[u]>=r[u-1]&&r[u]>r[u+1]&&s++;let a=t.length/e;return a<1e-6?0:s/a}function Yi(t,e=be){let r=Hr(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,u=-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>u&&(u=m,a=c)}if(a===0)return 0;let l=60*o/a;for(;l>150;)l/=2;for(;l>0&&l<70;)l*=2;return l}function qr(t){let e=bt(t);return e<1e-9?0:Sn(Vr(t))-Sn(e)}function jr(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=gt(t.subarray(s,Math.min(s+2048,t.length))),u=e/(a.length*2);for(let l=0;l<a.length;l++){let c=l*u,m=a[l]*a[l];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 yt(t,e=be){return{durationSec:t.length/e,rms:bt(t),peakDb:Sn(Vr(t)),centroidHz:Xi(t,e),zcr:ji(t,e),onsetDensity:Ji(t,e),tempoBpm:Yi(t,e)}}var Vl={"":[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],u=Vl[a];if(!u)throw new Error(`unknown chord quality ${JSON.stringify(a)} in ${JSON.stringify(t)}`);let l=ce(s+e),c=u.map(m=>l+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 qt(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 Hl(t,e=4){return t.map(n=>Se(n,e))}function Ki(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 jl(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?zr(Ki(e.key.tonic)??0,e.key.mode):null,i=0,s=0,a=new Map;if(t.tracks.forEach((l,c)=>{let m=l.name??`track ${c}`;(!l.patterns||l.patterns.length===0)&&n.push(`${m}: no patterns`),(!l.sequence||l.sequence.length===0)&&n.push(`${m}: empty sequence`),l.pan!==void 0&&(l.pan<-1||l.pan>1)&&n.push(`${m}: pan ${l.pan} out of [-1,1]`);for(let d of l.sequence??[]){if(d<0||d>=(l.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 l.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 b of ql(p)){let v=Ki(b);if(v===null){n.push(`${m}: unparseable pitch ${JSON.stringify(b)}`);continue}(v<0||v>127)&&n.push(`${m}: pitch ${b} outside MIDI 0..127`),i++,o&&!o.has((v%12+12)%12)&&s++}}}}),o&&i>0){let l=s/i,c=e.maxOutOfKey??1,m=`${s}/${i} notes (${Math.round(l*100)}%) out of key`;l>c?n.push(m):s>0&&r.push(m)}return![...a.values()].some(l=>l>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 Ul(t){return t.length===0?!1:(r=>r.trim().toLowerCase().replace(/7$/,""))(t[t.length-1])==="i"}var Xl={tempoBpm:20,centroidHz:1200,rms:.1,zcr:1500,onsetDensity:4,peakDb:6},Jl={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 Qi(t,e,n={}){let r={...Xl,...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,b=(p-h)/r[c];s+=b*b;let[v,M]=Jl[c],x=Math.abs(b)<.25?"ok":b<0?v:M;i.push({feature:c,reference:h,candidate:p,normalized:b,note:x})}i.sort((c,m)=>Math.abs(m.normalized)-Math.abs(c.normalized));let a=Math.sqrt(s/o.length),u=i[0],l=Math.abs(u.normalized)<.25?"close match":`${u.feature}: ${u.note}`;return{distance:a,deltas:i,headline:l}}function Yl(t,e){let n=Qi(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}
176
+ `+(r.length?r.join(`
177
+ `):" (all features within tolerance)")}function Kl(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 Zi(t,e,n=1,r=1e4,o=1){let i=Math.max(1e-6,n);switch(t){case"linear":{let s=ee(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 pe(-o*rt(s/i))}}}function es(t,e=400){return ee(t/e,-1,1)}function Ql(t,e,n=600,r=1){let o=Math.sqrt(t*t+e*e);return o>n?{gain:0,pan:0,audible:!1}:{gain:Zi("inverse",o,n*.15,n,r),pan:es(t,n*.7),audible:!0}}function Zl(t,e){let n={};for(let r of t){let o=Math.max(1e-6,r.full-r.fadeIn),i=ee((e-r.fadeIn)/o,0,1)*(r.maxGain??1);n[r.name]=i}return n}function ec(t,e=-12){return t?pe(e/6.0206):1}function ts(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=bt(n);return o<1e-9?0:bt(r)/o}var tc={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 nc(t,e){let n=new Float32Array(t.left.length);for(let M=0;M<n.length;M++)n[M]=(t.left[M]+t.right[M])*.5;let r=yt(n),o=qr(n),i=jr(n),s=ts(t),a=i.lowMid,u=i.high+i.air,l=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(l,[.12,.7]),clarity:Pe(a,[0,e.maxMud??.34]),smoothness:Pe(u,[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 M of Object.keys(c))d+=c[M]*m[M],h+=m[M];let p=Math.round(d/h*100),b=[],v=(M,x)=>{c[M]<.75&&b.push(`${M}: ${x}`)};return v("loudness",`rms ${r.rms.toFixed(3)} (target ${e.rms.join("\u2013")})`),v("headroom",`peak ${r.peakDb.toFixed(1)}dB (want \u2264 \u22120.5, \u2265 \u22123)`),v("dynamics",`crest ${o.toFixed(1)}dB (target ${e.crestDb.join("\u2013")})`),v("width",`width ${s.toFixed(2)} (target ${e.width.join("\u2013")})`),v("brightness",`centroid ${Math.round(r.centroidHz)}Hz (target ${e.centroid.join("\u2013")})`),v("density",`onsets ${r.onsetDensity.toFixed(1)}/s (target ${e.onsets.join("\u2013")})`),v("tempo",`tempo ${Math.round(r.tempoBpm)} (target ${e.tempo.join("\u2013")})`),v("lowEnd",`low-end fraction ${l.toFixed(2)} (want 0.12\u20130.62)`),v("clarity",`low-mid mud ${a.toFixed(2)} (want \u2264 ${(e.maxMud??.34).toFixed(2)})`),v("smoothness",`high/air ${u.toFixed(2)} (want \u2264 0.40)`),{score:p,dims:c,notes:b}}var P=(t,e,n=1)=>({pitch:t,beats:e,vel:n}),G=t=>({pitch:null,beats:t});function ns(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 rc(t,e,n=1){return Array.from({length:e},()=>P(t,1,n))}function oc(){let t=Qe(ce("A3"),"minor",["i","VI","III","VII"]),e=t.map(a=>a[0]-12),n={name:"sub",instrument:$.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:$.kick,gain:.82,patterns:[rc("A1",4)],sequence:Array(8).fill(0)},o={name:"hat",instrument:$.hat,gain:.42,pan:.15,patterns:[[G(.5),P("A6",.5,.7),G(.5),P("A6",.5,.5)]],sequence:Array(16).fill(0)},i={name:"pluck",instrument:{...$.pluck,release:.16,lowpass:2400},gain:.62,pan:-.2,patterns:t.map(a=>ns([a[0],a[1],a[2]],4,1,.7)),sequence:[0,1,2,3,0,1,2,3]},s={name:"lead",instrument:{...$.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 ic(){let t=ce("C4"),e=ft(Qe(t,"major",["IV7","iii7","ii7","I7"]).map(xn)),n=e.map(c=>c[0]-12),r={name:"rhodes",instrument:{...$.rhodes,volume:.42,lowpass:2600,fm:1.6},gain:.66,pan:-.1,patterns:e.map(c=>[P(c.map(m=>m),3.5,.75),G(.5)]),sequence:[0,1,2,3,0,1,2,3]},o={name:"bass",instrument:{...$.bass,lowpass:650,sub:.28},gain:.72,pan:.05,patterns:n.map(c=>[P(c,1.5,.9),G(.5),P(c+7,1,.7),P(c+5,1,.6)]),sequence:[0,1,2,3,0,1,2,3]},i={name:"kick",instrument:{...$.kick,volume:.75},gain:.82,patterns:[[P("C2",1,.9),G(1),P("C2",.5,.6),G(.5),P("C2",.5,.4),G(.5)]],sequence:Array(8).fill(0)},s={name:"snare",instrument:{...$.rimshot,volume:.24,lowpass:4e3},gain:.6,patterns:[[G(1),P("C4",1,.7),G(1),P("C4",1,.7)]],sequence:Array(8).fill(0)},a={name:"hat",instrument:{...$.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)},u={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]},l={name:"keys",instrument:{...$.piano,volume:.3,lowpass:2800},gain:.48,pan:.15,patterns:[[P(e[0][2]+12,1,.7),G(1),P(e[0][1]+12,.5,.55),P(e[0][2]+12,.5,.5),G(1)],[G(.5),P(e[1][2]+12,1,.7),G(.5),P(e[1][1]+12,2,.55)],[P(e[2][2]+12,1.5,.7),P(e[2][1]+12,.5,.5),G(2)],[G(1),P(e[3][2]+12,1,.7),P(e[3][1]+12,1,.55),G(1)]],sequence:[0,1,2,3,0,1,2,3]};return{bpm:78,tracks:[u,r,o,i,s,a,l],swing:.75,humanize:.4,velBrightness:.7,reverb:{wet:.24,roomSize:.7,damp:.65},master:{lowCut:.26,presence:.22,air:.05}}}function sc(){let t=ce("A3"),e=ft(Qe(t,"minor",["i","VI","III","VII"])),n=[a=>[P(a[0],1,.85),P(a[2],1,.55),G(2)],a=>[P(a[2],1.5,.8),G(.5),P(a[1],2,.5)],a=>[G(1),P(a[1]+12,1.5,.7),G(1.5)],a=>[P(a[0],2,.8),P(a[2],1,.55),G(1)]],r={name:"piano",instrument:{...$.piano,volume:.46},gain:.78,pan:-.05,patterns:e.map((a,u)=>n[u%n.length](a)),sequence:[0,1,2,3,0,1,2,3]},o={name:"strings",instrument:{...$.strings,attack:.4},gain:.5,pan:.1,patterns:e.map(a=>[P(a.map(u=>u-12),4,.65)]),sequence:[0,1,2,3,0,1,2,3]},i={name:"sub",instrument:{...$.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:{...$.piano,volume:.4,lowpass:3e3},gain:.5,pan:.12,patterns:[[G(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),G(1)],[G(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 ac(){let t=ce("D3"),e=ft(Qe(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:{...$.strings,volume:.24},gain:.7,pan:-.15,patterns:e.map(m=>ns([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=[G(4)],a={name:"brass",instrument:{...$.brass,volume:.32},gain:.62,pan:.15,patterns:[s,...i],sequence:[0,0,1,2,3,4,5,6]},u={name:"choir",instrument:{...$.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]},l={name:"timpani",instrument:{...$.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:$.glocken,gain:.32,pan:.25,patterns:[s,...e.map(m=>[G(1),P(m[2]+24,1,.55),G(1),P(m[1]+24,1,.5)])],sequence:[0,0,3,4,5,6,7,8]};return{bpm:88,tracks:[l,o,a,u,c],humanize:.14,velBrightness:.5,reverb:{wet:.32,roomSize:.9,damp:.4},master:{lowCut:.4,presence:.32,air:.14}}}function uc(){let t=ce("C4"),e=Qe(t,"major",["ii7","V7","I7","vi7"]),n=ft(e.map(xn)),r=e.map((c,m)=>{let d=e[(m+1)%e.length][0]-24,h=c[0]-24,p=c[1]-24,b=c[2]-24,v=d+(h<d?-1:1);return[P(h,1,.95),P(p,1,.75),P(b,1,.8),P(v,1,.7)]}),o={name:"bass",instrument:{...$.bass,lowpass:1e3,sub:.35,release:.12},gain:.74,patterns:r,sequence:[0,1,2,3,0,1,2,3]},i={name:"rhodes",instrument:{...$.rhodes,volume:.3},gain:.62,pan:-.15,patterns:n.map(c=>[G(.5),P(c.map(m=>m),.75,.7),G(.75),P(c.map(m=>m),.5,.55),G(1.5)]),sequence:[0,1,2,3,0,1,2,3]},s={name:"brass",instrument:{...$.brass,release:.1,volume:.24},gain:.55,pan:.2,patterns:[[G(2),P(n[0].map(c=>c+12),.5,.85),G(1.5)],[G(3),P(n[1].map(c=>c+12),.5,.85),G(.5)],[P(n[2].map(c=>c+12),.5,.8),G(3.5)],[G(2.5),P(n[3].map(c=>c+12),.5,.8),G(1)]],sequence:[0,1,2,3,0,1,2,3]},a={name:"ride",instrument:{...$.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)},u={name:"snare",instrument:{...$.snare,volume:.28,highpass:900},gain:.5,patterns:[[G(1),P("D4",1,.6),G(1),P("D4",1,.7)]],sequence:Array(8).fill(0)},l={name:"kick",instrument:{...$.kick,volume:.55},gain:.62,patterns:[[P("C2",1,.85),G(1.5),P("C2",.5,.6),G(1)]],sequence:Array(8).fill(0)};return{bpm:116,tracks:[o,i,s,l,u,a],swing:.66,humanize:.35,velBrightness:.6,reverb:{wet:.16,roomSize:.55,damp:.5},master:{lowCut:.5,presence:.18,air:.07}}}var rs=[{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:oc},{id:"lofi",name:"Lo-fi Beats",description:"Swung, dusty jazz sevenths on a Rhodes with warm bass, brushed drums and vinyl crackle.",make:ic},{id:"piano",name:"Melancholic Piano",description:"Slow, sad A-minor piano with space and rubato over a string bed in a big room.",make:sc},{id:"orchestral",name:"Epic Orchestral",description:"Uplifting D-minor with a soaring brass theme, arpeggiated strings, choir, timpani and glockenspiel.",make:ac},{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:uc}];function lc(t){return rs.find(e=>e.id===t)}var os=["sine","triangle","saw","square","noise"],Ur=new Set;function Mn(t,e){Ur.has(t)||(Ur.add(t),console.warn(`[hayao] specFromZzfx: ${t} ${e}`))}function cc(){Ur.clear()}function mc(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,u=t[7]??1,l=t[8]??0,c=t[9]??0,m=t[10]??0,d=t[11]??0,h=t[12]??0,p=t[13]??0,b=t[14]??0,v=t[15]??0,M=t[16]??0,x=t[17]??1,C=t[18]??0,I=t[19]??0,y=t[20]??0,f=o+C+i+s,w={freq:r,volume:e,attack:o,decay:C,sustain:i,release:s,sustainLevel:x},S=Math.max(0,Math.min(os.length-1,Math.round(a)));if(w.wave=os[S],Math.round(a)===3&&Mn("shape=3 (tan)","has no hayao wave; approximated as a hard square."),u!==1&&(w.shapeCurve=u),n!==0&&Mn("randomness","is dropped: hayao specs are deterministic (same spec \u2192 same samples)."),l!==0&&(w.slide=l*f),c!==0&&(w.slideAccel=c*f*f/2),m!==0){let D=r+m;D>0&&r>0?(w.pitchJump=12*rt(D/r),w.pitchJumpTime=d):Mn("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))),b!==0&&(Mn("modulation","is approximated as vibrato (pitch LFO at |modulation| Hz)."),w.vibrato=.6,w.vibratoFreq=Math.abs(b)),v>0&&(w.bitCrush=Math.max(1,Math.round(v*100))),I!==0&&(w.tremolo=Math.max(0,Math.min(1,I))),M>0&&(w.delay=M,w.delayFeedback=.5),y>0?w.lowpass=y:y<0&&(w.highpass=-y),w}var g=(t,e,n=1)=>({pitch:t,beats:e,vel:n}),N=t=>({pitch:null,beats:t});function Xr(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,u=Se(t[(r+1)%t.length],e)[0],l=u+(i<=u?-1:1);return[g(i,1,.92),g(s,1,.72),g(a,1,.78),g(l,1,.7)]})}function Cn(t,e=4,n="F4",r=.66){let o=ce(n);return t.map((i,s)=>{let a=qt(Se(i,e),o);return s%2===0?[g(a,1,r),N(.5),g(a,.5,r*.8),N(2)]:[N(1.5),g(a,.5,r*.85),N(1),g(a,.5,r*.7),N(.5)]})}function dc(t,e=4,n="F4",r=.6){let o=ce(n);return t.map(i=>[g(qt(Se(i,e),o),4,r)])}var hc=()=>[g("C6",1,.55),g("C6",.5,.35),g("C6",.5,.5),g("C6",1,.55),g("C6",.5,.35),g("C6",.5,.5)],pc=()=>[N(1),g("C6",1,.5),N(1),g("C6",1,.5)];function jt(t=.42,e=8){return{name:"ride",instrument:$.ride,gain:t,pan:.12,patterns:[hc()],sequence:Array(e).fill(0)}}function Jr(t=.4,e=8){return{name:"hat",instrument:{...$.hat,highpass:5e3,volume:.2},gain:t,pan:-.1,patterns:[pc()],sequence:Array(e).fill(0)}}function Rn(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:[[g("C4",e*4,1)]],sequence:[0]}}var Tn=["F5","Gb5","Bb5","Ab5"];function fc(){let t=["Bbm9","Bbm9","Ebm9","Ab13","Dbmaj7","Gm7b5","C7alt","Fm7"],n={name:"bass",instrument:{...$.uprightBass,volume:.5},gain:.7,patterns:[[g("Bb1",.75,.95),g("Bb1",.25,.5),N(.5),g("Db2",.5,.7),g("F2",.5,.75),g("Ab1",.5,.6),g("Bb1",1,.7)],...Xr(t.slice(2),2)],sequence:[0,0,1,2,3,4,5,6]},r={name:"rhodes",instrument:{...$.rhodes,volume:.32},gain:.6,pan:-.18,patterns:Cn(t,4,"Ab4",.62),sequence:[0,1,2,3,4,5,6,7]},o={name:"trumpet",instrument:{...$.mutedTrumpet,volume:.34},gain:.62,pan:.14,patterns:[[g(Tn[0],.5,.85),g(Tn[1],.5,.7),g(Tn[2],1,.9),g(Tn[3],.5,.75),N(1.5)],[g("F5",.5,.8),g("Db5",.5,.7),g("Bb4",1.5,.85),N(1.5)],[g("C5",.5,.85),g("Db5",.5,.72),g("F5",1,.9),g("Eb5",.5,.75),N(1.5)],[g("Db5",1,.8),g("C5",.5,.7),g("Bb4",.5,.7),g("Ab4",2,.72)],[g("Db5",.5,.8),g("F5",.5,.8),g("Ab5",1.5,.85),g("Gb5",1.5,.75)],[g("D5",1,.8),g("F5",1,.8),g("Ab5",1,.85),N(1)],[g("E5",.5,.85),g("Eb5",.5,.8),g("Db5",1,.8),g("C5",2,.78)],[g("F5",1,.85),g("Ab5",1,.8),g("C6",2,.9)]],sequence:[0,1,2,3,4,5,6,7]},i={name:"kick",instrument:{...$.kick,volume:.5},gain:.6,patterns:[[g("Bb1",1,.8),N(1.5),g("Bb1",.5,.55),N(1)]],sequence:Array(8).fill(0)},s={name:"snare",instrument:{...$.snare,volume:.3,highpass:1e3},gain:.5,patterns:[[N(1),g("D4",1,.7),N(1),g("D4",1,.75)]],sequence:Array(8).fill(0)};return{bpm:100,tracks:[n,r,o,i,s,jt(.42),Jr(.35)],swing:.6,humanize:.32,velBrightness:.6,reverb:{wet:.17,roomSize:.6,damp:.5},master:{lowCut:.24,presence:.14,air:.04,compress:.45}}}function bc(){let t=["Ebmaj7","Cm7","Fm7","Bb13","Gm7","C7b9","Fm7","Bb7alt"],e={name:"bass",instrument:{...$.uprightBass,volume:.54,release:.2},gain:.74,patterns:t.map(i=>{let s=Se(i,2)[0];return[g(s,2,.85),g(s+7,1,.6),g(s+12,1,.55)]}),sequence:[0,1,2,3,4,5,6,7]},n={name:"rhodes",instrument:{...$.rhodes,volume:.34,release:.6},gain:.62,pan:-.15,patterns:dc(t,4,"G4",.62),sequence:[0,1,2,3,4,5,6,7]},r={name:"trumpet",instrument:{...$.mutedTrumpet,volume:.36,attack:.05,vibrato:.11},gain:.62,pan:.12,patterns:[[N(1),g("G4",1.5,.7),g("Bb4",1,.75),g("G4",.5,.6)],[g("Eb4",2,.7),g("G4",1,.65),N(1)],[N(.5),g("Ab4",1.5,.72),g("C5",1,.75),g("Ab4",1,.62)],[g("D5",2.5,.78),g("Bb4",1.5,.65)],[g("Bb4",1.5,.7),g("G4",1,.65),g("D5",1.5,.72)],[g("Db5",2,.75),g("C5",1,.68),g("Bb4",1,.62)],[g("Ab4",2,.72),g("F4",1,.62),N(1)],[g("Ab4",1,.72),g("Db5",1,.7),g("D5",2,.72)]],sequence:[0,1,2,3,4,5,6,7]},o={name:"brush",instrument:{...$.snare,volume:.12,highpass:1500,release:.16},gain:.4,patterns:[[N(1),g("D4",1,.4),N(1),g("D4",1,.45)]],sequence:Array(8).fill(0)};return{bpm:62,tracks:[Rn(.3),e,n,r,o,jt(.24)],swing:.5,humanize:.4,velBrightness:.6,reverb:{wet:.34,roomSize:.85,damp:.55},master:{lowCut:.24,presence:.16,air:.05,compress:.65}}}function gc(){let t=["Cm9","Cm9","Fm9","Dm7b5","G7alt","Cm9","Ab13","G7alt"],e={name:"bass",instrument:{...$.uprightBass,volume:.48},gain:.68,patterns:Xr(t,2),sequence:[0,1,2,3,4,5,6,7]},n={name:"vibes",instrument:{...$.vibraphone,volume:.34},gain:.6,pan:.1,patterns:[[g("G4",1,.7),N(1),g("Eb5",1,.65),N(1)],[N(2),g("D5",1,.68),g("C5",1,.6)],[g("Ab4",1,.7),N(1.5),g("F5",1.5,.6)],[g("F4",1,.7),g("Ab4",1,.6),N(2)],[N(1),g("B4",1,.72),g("Ab4",1,.6),g("F4",1,.55)],[g("Eb5",2,.68),g("C5",2,.6)],[g("C5",1,.7),g("Gb5",1,.68),N(2)],[g("B4",1,.7),g("Db5",1,.62),g("Ab4",2,.58)]],sequence:[0,1,2,3,4,5,6,7]},r={name:"guitar",instrument:{...$.jazzGuitar,volume:.22},gain:.5,pan:-.2,patterns:Cn(t,4,"Eb4",.5),sequence:[0,1,2,3,4,5,6,7]};return{bpm:96,tracks:[Rn(.28),e,r,n,jt(.3),Jr(.28)],swing:.62,humanize:.34,velBrightness:.6,reverb:{wet:.22,roomSize:.65,damp:.5},master:{lowCut:.24,presence:.13,air:.04,compress:.45}}}function yc(){let t={name:"bass",instrument:{...$.bass,volume:.52,lowpass:1e3,sub:.35},gain:.75,patterns:[[g("F1",.5,.95),g("F1",.5,.6),N(.5),g("F1",.5,.7),g("Ab1",.5,.7),g("C2",.5,.7),g("F1",.5,.65),g("Eb2",.5,.7)],[g("Bb1",.5,.9),g("Bb1",.5,.6),N(.5),g("Bb1",.5,.7),g("Db2",.5,.7),g("F2",.5,.7),g("Bb1",1,.65)],[g("C2",.5,.9),g("C2",.5,.6),g("Eb2",.5,.7),g("D2",.5,.7),g("C2",.5,.7),g("Bb1",.5,.7),g("G1",1,.7)]],sequence:[0,0,1,2]},e={name:"clav",instrument:{...$.clav,volume:.3,lowpass:2700},gain:.55,pan:-.16,patterns:[[g("F4",.25,.8),N(.25),g("Ab4",.25,.6),N(.25),g("F4",.25,.7),g("C5",.25,.6),N(.5),g("Eb5",.5,.7),N(1)],[g("Bb3",.25,.8),N(.25),g("Db4",.25,.6),N(.25),g("F4",.5,.7),N(.5),g("Bb4",.5,.65),N(1)],[g("C4",.25,.8),g("Eb4",.25,.6),g("G4",.5,.7),N(.5),g("C5",.5,.7),g("Bb4",.5,.65),N(1)]],sequence:[0,0,1,2]},n=a=>qt(Se(a,4),ce("C5")),r={name:"horns",instrument:{...$.horns,volume:.26},gain:.55,pan:.15,patterns:[[N(1.5),g(n("Fm7"),.5,.8),N(1.5),g(n("Fm7"),.5,.9)],[N(1.5),g(n("Fm7"),.5,.8),N(1.5),g(n("Bbm7"),.5,.9)],[N(2),g(n("Bbm7"),.5,.82),N(1),g(n("Bbm7"),.5,.88)],[g(n("C7#9"),.5,.92),N(1),g(n("C7#9"),.5,.82),N(1),g(n("C7#9"),.5,.9)]],sequence:[0,1,2,3]},o={name:"kick",instrument:$.kick,gain:.85,patterns:[[g("F1",1,.95),g("F1",.5,.6),N(.5),g("F1",.5,.7),N(.5),g("F1",1,.8)]],sequence:Array(4).fill(0)},i={name:"snare",instrument:{...$.snare,volume:.42},gain:.6,patterns:[[N(1),g("D4",1,.85),N(1),g("D4",1,.9)]],sequence:Array(4).fill(0)},s={name:"hat",instrument:{...$.hat,volume:.18,highpass:5e3,lowpass:9e3},gain:.38,pan:.1,patterns:[[g("C6",.5,.6),g("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 vc(){let t=["Abmaj7#11","Db9","Bbm7","Eb7alt","Cm7","F7b9","Bbm7","Eb13"],e={name:"bass",instrument:{...$.uprightBass,volume:.5,sub:.4},gain:.72,patterns:t.map((s,a)=>{let u=Se(s,2)[0],l=Se(t[(a+1)%t.length],2)[0],c=l+(u<=l?-1:1);return[g(u,1.5,.9),N(.5),g(u+7,1,.62),g(c,1,.62)]}),sequence:[0,1,2,3,4,5,6,7]},n={name:"rhodes",instrument:{...$.rhodes,volume:.28},gain:.55,pan:-.18,patterns:Cn(t,4,"Ab4",.6),sequence:[0,1,2,3,4,5,6,7]},r={name:"vibes",instrument:{...$.vibraphone,volume:.3},gain:.55,pan:.18,patterns:[[N(1),g("C5",1,.7),g("D5",1,.65),g("Eb5",1,.62)],[g("F5",2,.7),g("Eb5",1,.62),g("C5",1,.58)],[g("Db5",1.5,.7),g("F5",1.5,.65),g("Ab5",1,.62)],[g("G5",1,.72),g("Gb5",1,.66),g("Db5",2,.6)],[N(1),g("Eb5",1.5,.68),g("G5",1.5,.62)],[g("Ab5",1,.72),g("Gb5",1,.66),g("F5",2,.6)],[g("Db5",2,.68),g("Bb4",2,.6)],[g("C5",1,.7),g("G5",1,.66),g("Eb5",2,.6)]],sequence:[0,1,2,3,4,5,6,7]},o={name:"kick",instrument:{...$.kick,volume:.55},gain:.62,patterns:[[g("Ab1",1,.85),N(2),g("Ab1",.5,.55),N(.5)]],sequence:Array(8).fill(0)},i={name:"snare",instrument:{...$.rimshot,volume:.22},gain:.5,patterns:[[N(2),g("D4",1,.7),N(1)]],sequence:Array(8).fill(0)};return{bpm:84,tracks:[Rn(.32),e,n,r,o,i,jt(.28),Jr(.24)],swing:.56,humanize:.3,velBrightness:.62,reverb:{wet:.26,roomSize:.72,damp:.55},master:{lowCut:.24,presence:.14,air:.04,compress:.45}}}function xc(){let t=["Dm7","G13","Cmaj9","A7b9","Dm7","G7","Cmaj9","Cmaj9"],e={name:"bass",instrument:{...$.uprightBass,volume:.5},gain:.66,patterns:Xr(t,2),sequence:[0,1,2,3,4,5,6,7]},n={name:"rhodes",instrument:{...$.rhodes,volume:.32,release:.5},gain:.6,pan:-.14,patterns:Cn(t,4,"E4",.6),sequence:[0,1,2,3,4,5,6,7]},r={name:"trumpet",instrument:{...$.mutedTrumpet,volume:.36,vibrato:.1},gain:.62,pan:.12,patterns:[[N(1),g("A4",1,.72),g("C5",1,.75),g("D5",1,.7)],[g("B4",2,.75),g("G4",1,.65),g("F4",1,.6)],[g("E5",2,.78),g("G4",1,.62),g("E4",1,.6)],[g("C5",1,.72),g("Bb4",1,.68),g("A4",1,.65),g("D5",1,.62)],[g("G4",.5,.78),g("A4",.5,.72),g("C5",1,.82),g("B4",.5,.7),N(1.5)],[g("D5",1,.75),g("B4",1,.68),g("G4",2,.62)],[g("E5",2,.8),g("C5",2,.72)],[g("E4",4,.6)]],sequence:[0,1,2,3,4,5,6,7]},o={name:"brush",instrument:{...$.snare,volume:.12,highpass:1500,release:.15},gain:.42,patterns:[[N(1),g("D4",1,.42),N(1),g("D4",1,.46)]],sequence:Array(8).fill(0)};return{bpm:76,tracks:[Rn(.3),e,n,r,o,jt(.26)],swing:.56,humanize:.36,velBrightness:.6,reverb:{wet:.3,roomSize:.8,damp:.5},master:{lowCut:.38,presence:.28,air:.09,compress:.65}}}var is={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:fc},{id:"rain-avenue",title:"Rain on the Avenue",intent:"A smoky, slow torch ballad. Muted trumpet in the rain.",make:bc},{id:"stakeout",title:"Stakeout",intent:"Minimal, nervous cool-jazz. Watching, waiting, unresolved.",make:gc},{id:"the-chase",title:"The Chase",intent:"Driving F-minor funk \u2014 clav, horn stabs, a hard pulse.",make:yc},{id:"smoke-mirrors",title:"Smoke & Mirrors",intent:"Slinky half-time noir; altered colours, nothing as it seems.",make:vc},{id:"last-call",title:"Last Call",intent:"The warm closer \u2014 a ii\u2013V\u2013I that finally lands, the motif resolved.",make:xc}]};function wc(t){return is.tracks.find(e=>e.id===t)}var Pn=null,ss="hayao-overlay-style",kc=`
178
+ .hy-scrim{position:absolute;inset:0;display:grid;place-items:center;z-index:50;font-family:var(--hy-serif,Georgia,serif)}
179
+ .hy-scrim.dim{background:rgba(30,24,14,.5);backdrop-filter:blur(2px)}
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}
181
+ .hy-card h1{margin:0 0 6px;font-size:30px}
182
+ .hy-card .hy-body{color:var(--hy-ink-soft,#6f6047);font-size:15px;line-height:1.5;margin-bottom:18px}
183
+ .hy-menu{display:flex;flex-direction:column;gap:8px;align-items:stretch}
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}
185
+ .hy-item:hover,.hy-item.sel{background:var(--hy-accent,#a11d3a);color:#fdf3ee;border-color:transparent;transform:translateY(-1px)}
186
+ .hy-item.primary{background:var(--hy-accent,#a11d3a);color:#fdf3ee;border-color:transparent}
187
+ `;function Sc(){if(typeof document>"u"||document.getElementById(ss))return;let t=document.createElement("style");t.id=ss,t.textContent=kc,document.head.appendChild(t)}var as=null;function Ut(t){as=t}var Yr=null;function En(t){Yr=t}function Kr(t){if(typeof document>"u")return{close(){},element:null};Sc(),Xt(),Yr?.("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 l=document.createElement("h1");l.textContent=t.title,n.appendChild(l)}if(t.body){let l=document.createElement("div");l.className="hy-body",l.innerHTML=t.body,n.appendChild(l)}let r=t.actions??[],o=Math.max(0,r.findIndex(l=>l.primary));o<0&&(o=0);let i=[];if(r.length){let l=document.createElement("div");l.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)),l.appendChild(d),i.push(d)}),n.appendChild(l)}function s(l){o=(l+i.length)%i.length,i.forEach((c,m)=>c.classList.toggle("sel",m===o))}i.length&&s(o);let a=l=>{i.length&&(l.code==="ArrowDown"?(s(o+1),l.preventDefault()):l.code==="ArrowUp"?(s(o-1),l.preventDefault()):(l.code==="Enter"||l.code==="Space")&&(r[o]?.onSelect(),l.preventDefault()))};document.addEventListener("keydown",a),e.appendChild(n),(as??document.body).appendChild(e);let u={element:e,close(){document.removeEventListener("keydown",a),e.remove(),Pn===u&&(Pn=null,Yr?.("hide",t.title))}};return Pn=u,u}function Xt(){Pn?.close()}var us="hayao.settings.v1",ls={master:.7,music:.6,sfx:.8,muted:!1,colorblind:!1,reducedMotion:!1},Qr=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(){$e.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(us);if(e)return{...ls,...JSON.parse(e)}}catch{}return{...ls}}save(){try{localStorage.setItem(us,JSON.stringify(this.state))}catch{}}},Ae=new Qr;function Zr(){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 Jt=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,$e.blip(440),this.opts.onPause?.(!0),this.render())}resume(){this.paused&&(this.paused=!1,Xt(),this.opts.onPause?.(!1))}render(){let e=Ae.get(),n=(r,o)=>`${r}: ${Math.round(o*100)}`;Kr({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:()=>{Ae.set({muted:!Ae.get().muted}),this.render()}},{label:"Music \u2212/+",onSelect:()=>{let r=Math.min(1,Ae.get().music+.1)%1.05;Ae.set({music:r>1?0:r}),this.render()}},{label:"Fullscreen (F)",onSelect:()=>Zr()},...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),Xt()}};var cs="hayao-touch-style",Mc=`
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 Tc(){if(typeof document>"u"||document.getElementById(cs))return;let t=document.createElement("style");t.id=cs,t.textContent=Mc,document.head.appendChild(t)}function Cc(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 eo=class{handle;root;disposers=[];owned=new Set;constructor(e,n){this.handle=e,Tc();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=ms(n.left),s=ms(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=Cc(n),s=n.prefix,a=n.buckets??32,u=n.deadzone??.28,l=null,c=(v,M)=>{if(!s)return;let x=this.handle.world.input.axes;x.set(`${s}x`,Oe(v,a)),x.set(`${s}y`,Oe(M,a)),x.set(`${s}angle`,v===0&&M===0?0:ur(kt(M,v),a))},m=()=>{if(i)for(let v of[i.up,i.down,i.left,i.right])this.hold(v,!1);c(0,0),o.style.transform="translate(0,0)",l=null},d=(v,M)=>{let x=r.getBoundingClientRect(),C=x.width/2,I=(v-(x.left+C))/C,y=(M-(x.top+C))/C,f=K(I,y);f>1&&(I/=f,y/=f),o.style.transform=`translate(${I*C*.6}px,${y*C*.6}px)`;let w=K(I,y);i&&(this.hold(i.left,I<-u),this.hold(i.right,I>u),this.hold(i.up,y<-u),this.hold(i.down,y>u)),c(w<u?0:I,w<u?0:y)},h=v=>{l===null&&(l=v.pointerId,r.setPointerCapture?.(v.pointerId),d(v.clientX,v.clientY),v.preventDefault())},p=v=>{v.pointerId===l&&d(v.clientX,v.clientY)},b=v=>{v.pointerId===l&&m()};r.addEventListener("pointerdown",h),r.addEventListener("pointermove",p),r.addEventListener("pointerup",b),r.addEventListener("pointercancel",b),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=u=>{o.classList.add("on"),i?this.hold(r.action,!0):this.handle.input.press(r.action),o.setPointerCapture?.(u.pointerId),u.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 ms(t){if(t)return Array.isArray(t)?{dirs:t}:t}var Rc=[0,8,2,10,12,4,14,6,3,11,1,9,15,7,13,5],Pc=t=>t*t*(3-2*t),Dn=class extends V{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=ee(n.elapsed/n.dur,0,1);if(this.coverage=De(n.from,n.to,Pc(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:ue,z:o});return}if(this.kind==="circle"){let a=this.screenW/2,u=this.screenH/2,l=Math.sqrt(a*a+u*u);e.push({kind:"circle",cx:a,cy:u,radius:r*l,fill:this.color,transform:ue,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 u=0;u<i;u++)(Rc[(u&3)+((a&3)<<2)]+.5)/16<r&&e.push({kind:"rect",x:u*this.cell,y:a*this.cell,w:this.cell,h:this.cell,fill:this.color,transform:ue,z:o})}},to=class extends V{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 Ec(t,e={}){let n=new Dn({z:1e4,...e});return t.addChild(n)}function Dc(t,e={}){return{name:e.name??"wipe",enter:()=>t.wipe(e),until:()=>!t.busy}}var Ic=(t,e)=>({x:0,y:0,w:t,h:e});function Ze(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 u=0;u<n&&i.length>0;u++){let l=[];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:u+1,nodes:a,exhausted:!1};let p=t.key(h);s.has(p)||(s.add(p),l.push({state:h,path:[...m,d]}))}i=l}return{solvable:!1,nodes:a,exhausted:i.length>0}}function Fc(t,e={}){let n=Ze(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(at(e,o),ut(e,o)),r.push(n.hash());return{finalHash:n.hash(),hashes:r}}function ds(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 Ac(t,e){let n=ds(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 Nc(t,e,n){let r=t();for(let u=0;u<n;u++)r.step(at(e,u),ut(e,u));let o=r.snapshot(),i=t();i.restore(o);for(let u=n;u<e.frames.length;u++)r.step(at(e,u),ut(e,u)),i.step(at(e,u),ut(e,u));let s=r.hash(),a=i.hash();return{ok:s===a,hashA:s,hashB:a}}function Lc(t,e){return{actions:t,frames:e}}function $c(t){return{actions:[],frames:t}}function Wc(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 zc(t,e,n=[]){for(let r=0;r<e;r++)t.step(n)}function ro(){return typeof location<"u"&&new URLSearchParams(location.search).has("capture")}function oo(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 hs(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 Bc(t,e,n){let r=0;for(let o of hs(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 _c(t,e){let n=0,r=0,o={},s=a=>{let u=[],l=t[n];if(!l)return u;r++;let c={get frames(){return r},mem:o,next(){n++,r=0,o={}},retry(){r=0,o={}}},m=e[l.kind];if(!m)throw new Error(`plan bot: no executor for step kind "${l.kind}"`);return m(l,a,u,c),u};return s.stepIndex=()=>n,s.done=()=>n>=t.length,s}function Gc(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 Kt=t=>[...new Set(t)];function ps(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 Oc(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)`),Kt(r)}function fs(t,e,n={}){let r=n.minChannels??2,[o,i]=n.shake??[0,1],[s,a]=n.hitstop??[0,12],u=[];for(let l of e){let c=t[l];if(!c){u.push(`event "${l}" has no feedback response \u2014 it happens silently`);continue}let m=new Set(c.channels).size;m<r&&u.push(`event "${l}" 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)&&u.push(`event "${l}" shake ${c.shake} is outside the [${o}, ${i}] envelope`),c.hitstopFrames!==void 0&&(c.hitstopFrames<s||c.hitstopFrames>a)&&u.push(`event "${l}" hit-stop ${c.hitstopFrames}f is outside the [${s}, ${a}]f envelope`)}return Kt(u)}function Yt(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 vt(t,e){let n=Yt(t),r=Yt(e),o=Math.max(n,r),i=Math.min(n,r);return(o+.05)/(i+.05)}var Vc=t=>t.kind==="text"?void 0:t.fill;function bs(t,e,n,r={}){let o=r.minBackgroundContrast??3,i=r.minSalienceFactor??1.15,s=[],a=vt(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 u=[];for(let l of t){let c=Vc(l);c&&c!=="none"&&c!==e&&u.push(vt(c,n))}if(u.length){u.sort((c,m)=>c-m);let l=u[Math.floor(u.length/2)];a<l*i&&s.push(`avatar (${e}, ${a.toFixed(2)}:1) does not pop from the scenery (median ${l.toFixed(2)}:1) \u2014 it needs \u2265 ${i}\xD7 the median contrast`)}return Kt(s)}function Hc(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 Kt(r)}function gs(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 u=t[a].x-t[a-1].x,l=t[a].y-t[a-1].y,c=K(u,l)/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 u=Math.abs(s[a]-s[a-1])/n;u>o&&i.push(`camera jerked at frame ${a+1}: ${Math.round(u)}px/s\xB2 exceeds the ${o}px/s\xB2 ceiling`)}return Kt(i)}function ys(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 qc(t,e={}){let n=[],r=[],o=t.background??e.background??"#ffffff";if(t.forgiveness&&n.push({gate:"forgiveness",issues:ps(t.forgiveness)}),t.feedback&&n.push({gate:"feedback",issues:fs(t.feedback.contract,t.feedback.events)}),t.avatarFill&&(e.commands?n.push({gate:"salience",issues:bs(e.commands,t.avatarFill,o)}):r.push("salience (no rendered frame)")),t.scrolls)if(e.camSamples&&e.camSamples.length>=3){let i=gs(e.camSamples,{dt:e.dt});e.targetSamples&&i.push(...ys(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 ks(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 io(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 vs=(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,xs=(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,jc=t=>t.transient===!0,ws=t=>{let e=t.fill;if(!(!e||e==="none")&&!t.gradient)return e};function Uc(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=[],u=e.includeTransient?t:t.filter(c=>!jc(c)),l=[];for(let c of u)c.kind==="text"&&c.text.trim().length&&l.push(ks(c));for(let c of l){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 b of u){if(b.kind==="text")continue;let v=io(b);if(!v||!xs(v,c))continue;let M=b.opacity===void 0||b.opacity>=.6,x=b.z??0;M&&x<=m&&x>=h&&(h=x,p=ws(b)??p),x>m&&(b.opacity===void 0||b.opacity>=.9)&&a.push(`text "${Qt(c.cmd.text)}" is hidden behind a ${b.kind} (z${x} > text z${m}) that fully covers it \u2014 give the text a higher z, or the shape a lower one`)}for(let b of u){if(b.kind==="text"||(b.z??0)<=n||(b.z??0)<=h||b.opacity!==void 0&&b.opacity<.25)continue;let v=io(b);v&&vs(d,v)&&!xs(v,c)&&a.push(`text "${Qt(c.cmd.text)}" collides with a ${b.kind} (z${b.z}) at ~(${Math.round(v.x)},${Math.round(v.y)}) \u2014 back it with a panel, or stay clear`)}if(o&&s>0){let b=c.cmd.fill;if(b&&b!=="none"&&(c.cmd.opacity===void 0||c.cmd.opacity>=.6)){let v=vt(b,p??o);v<s&&a.push(`text "${Qt(c.cmd.text)}" (${b}) contrast is ${v.toFixed(2)}:1 on its backing (needs \u2265 ${s}:1) \u2014 barely readable`)}}}if(o)for(let c of u){if(c.kind==="text"||(c.z??0)<=n||c.opacity!==void 0&&c.opacity<.6)continue;let m=ws(c);if(!m)continue;let d=vt(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<l.length;c++)for(let m=c+1;m<l.length;m++)vs(l[c],l[m])&&a.push(`texts "${Qt(l[c].cmd.text)}" and "${Qt(l[m].cmd.text)}" overlap`);return Ss(a)}var Qt=t=>t.length>28?t.slice(0,25)+"\u2026":t,Ss=t=>[...new Set(t)];function Ms(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 Xc(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(Ms)].some(o)||r.push(i)}return Ss(r)}function Jc(t,e){let n=[t.probe()];for(let r of e)t.step(r),n.push(t.probe());return n}function Yc(t,e){for(let n=0;n<t.length;n++)if(e(t[n]))return n;return-1}function Kc(t,e){return t.map(n=>n[e])}function Qc(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 Zc(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 em(t){return t.length===0?0:t.filter(e=>e.length>0).length/t.length}function tm(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 nm=t=>[...new Set(t)];function Ts(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 u=t[a];if(u<n&&(n=u),u>r&&(r=u),o+=u,a>0){let l=u-t[a-1];l>i&&(i=l),l>=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 Cs(t,e={}){let n=e.maxJumpFactor??3,r=e.minJumpAllowance??2,o=e.minForwardFraction??.6,i=e.minDistinct??3,s=e.finaleFraction??.8,a=[],u=t.length;if(u<2)return a.push(`ramp has ${u} level(s) \u2014 need at least 2 to form a curve`),a;let l=Ts(t);t[u-1]<t[0]&&a.push(`curve descends overall: finale (${t[u-1]}) is easier than the opener (${t[0]}) \u2014 the game gets EASIER`),l.max>0&&t[u-1]<l.max*s&&a.push(`finale (${t[u-1]}) is well below the peak (${l.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<u;p++){let b=t[p]-t[p-1];b>0&&(c+=b,m++)}let d=m>0?c/m:0,h=Math.max(r,d*n);for(let p=1;p<u;p++){let b=t[p]-t[p-1];b>h&&a.push(`difficulty cliff at level ${p+1}: jumps ${t[p-1]}\u2192${t[p]} (+${b}), past the +${h.toFixed(1)} envelope \u2014 smooth it with an intermediate level`)}return l.forwardFraction<o&&a.push(`only ${(l.forwardFraction*100).toFixed(0)}% of steps make progress (need \u2265 ${(o*100).toFixed(0)}%) \u2014 the curve wanders/descends instead of building`),l.distinct<i&&a.push(`only ${l.distinct} distinct difficulty value(s) across ${u} levels (need \u2265 ${i}) \u2014 the curve is flat; levels don't actually differ in challenge`),nm(a)}function rm(t,e={}){let n=Cs(t,e);if(n.length)throw new Error(`hayao: difficulty ramp is ill-shaped \u2014 ${n[0]}`)}function om(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:Ue(t.render(),"p0")}];for(let x=0;x<e.length;x++)t.step(e[x]),((x+1)%o===0||x===e.length-1)&&i.push({frame:x+1,inner:Ue(t.render(),`p${i.length}`)});let s=Math.max(1,n.cols??4),a=n.panelWidth??320,u=Math.round(a*n.height/n.width),l=18,c=8,m=a+c,d=u+l+c,h=Math.ceil(i.length/s),p=s*m+c,b=h*d+c,v=n.background??"#ffffff",M=i.map((x,C)=>{let I=c+C%s*m,y=c+Math.floor(C/s)*d;return`<g transform="translate(${I} ${y})"><svg width="${a}" height="${u}" viewBox="0 0 ${n.width} ${n.height}"><rect x="0" y="0" width="${n.width}" height="${n.height}" fill="${v}"/>`+x.inner+`</svg><rect x="0" y="0" width="${a}" height="${u}" fill="none" stroke="#999" stroke-width="1"/><text x="${a/2}" y="${u+13}" font-size="11" font-family="monospace" text-anchor="middle" fill="#555">f ${x.frame} \xB7 ${(x.frame/60).toFixed(1)}s</text></g>`}).join("");return`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${p} ${b}" width="${p}" height="${b}"><rect x="0" y="0" width="${p}" height="${b}" fill="#f4f4f2"/>`+M+"</svg>"}function so(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 Rs(t,e,n,r,o){let i=Math.max(1,Math.floor(t.length/e)),s=`M0 ${o}`,a="";for(let u=0;u<e;u++){let l=0,c=0,m=u*i;for(let h=0;h<i&&m+h<t.length;h++){let p=t[m+h];p>c&&(c=p),p<l&&(l=p)}let d=u/e*n;s+=` L${d.toFixed(1)} ${(o-c*(r/2)).toFixed(1)}`,a=` L${d.toFixed(1)} ${(o-l*(r/2)).toFixed(1)}`+a}return s+a+" Z"}function im(t,e={}){let n=e.width??900,r=e.timeBins??220,o=e.freqBands??64,i=16,s=n-i*2,a=70,u=200,l=84,c=i*5+a*2+u+l,m=yt(so(t)),d=Rs(t.left,r,s,a,a/2),h=Rs(t.right,r,s,a,a/2),p=so(t),b=2048,v=Math.max(1,Math.floor(p.length/r)),M=s/r,x=u/o,C="";for(let S=0;S<r;S++){let D=S*v;if(D+64>=p.length)break;let R=gt(p.subarray(D,Math.min(D+b,p.length)));if(R.length===0)continue;let k=Math.max(1,Math.floor(R.length/o));for(let T=0;T<o;T++){let F=0;for(let Z=0;Z<k;Z++)F+=R[T*k+Z]??0;let O=F>1e-6?20*St(F):-120,A=Math.max(0,Math.min(1,(O+60)/60));if(A<.03)continue;let J=i+S*M,Y=i*3+a*2+u-(T+1)*x,te=sm(A);C+=`<rect x="${J.toFixed(1)}" y="${Y.toFixed(1)}" width="${(M+.6).toFixed(1)}" height="${(x+.6).toFixed(1)}" fill="${te}"/>`}}let I=am(m).map((S,D)=>`<text x="${i+4}" y="${c-l+20+D*18}" font-family="monospace" font-size="12" fill="#e8e4d8">${S}</text>`).join(""),y=i,f=i*2+a,w=(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">${um(e.title)}</text>`:"")+w("L",y)+`<g transform="translate(${i} ${y})"><rect width="${s}" height="${a}" fill="#211e18"/><path d="${d}" fill="#5a9ac4" opacity="0.9"/></g>`+w("R",f)+`<g transform="translate(${i} ${f})"><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="${u}" fill="#0d0c0a"/>`+C+`<rect x="${i}" y="${c-l}" width="${s}" height="${l-i}" fill="#211e18"/>`+I+"</svg>"}function sm(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 am(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 um(t){return t.replace(/[<>&]/g,e=>e==="<"?"&lt;":e===">"?"&gt;":"&amp;")}function lm(t,e){let n=yt(so(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 Zt=class{rng;clock;input=new Ft;events=new Tt;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 le(this.seed),this.clock=new Mt(e.clock),this.width=e.width??1280,this.height=e.height??720,this.tuningValues={...e.tuning??{}},this.guardDeterminism=e.guardDeterminism??!1,this.root=new V({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 ue;let e=this.activeCamera,n=e.worldTransform();return _e(ot({x:this.width/2,y:this.height/2},0,{x:e.zoom,y:e.zoom}),it(n))}worldToScreen(e){return cn(this.viewTransform(),e)}screenToWorld(e){return cn(it(this.viewTransform()),e)}render(){this.ensureStarted();let e=[];return this.root.collectDraw(e,this.viewTransform()),e}hash(){return Ct({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,Un(1e6),this.setRoot(dn(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 cm={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 en(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 mm(t){return{width:1280,height:720,seed:1,background:"#f3ecdb",inputMap:hn,...t}}function Me(t,e){let n=typeof e=="number"?{seed:e}:e??{},r=new Zt({seed:n.seed??t.seed??1,width:t.width??1280,height:t.height??720,clock:t.clock,tuning:en(t.tuning,n.tuning)});return r.setRoot(t.build(r)),t.probe&&(r.probe=()=>t.probe(r)),r}function dm(t){return t.inputMap??hn}function hm(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 ao(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,u={...e.tuningValues};for(let l=0;l<i;l++){for(;a<e.knobEvents.length&&e.knobEvents[a].frame===l;){let c=e.knobEvents[a++];u[c.key]=c.value;let m=o.snapshot();m.tuning={...u},o.restore(m),t.attach?.(o)}for(;s<e.axesLog.length&&e.axesLog[s][0]===l;){let[,c,m]=e.axesLog[s++];o.input.axes.set(c,m)}o.step(e.inputLog.frames[l]),r.onFrame?.(o,l)}return o}function Ps(t){let{frame:e,time:n,hash:r,...o}=t;return JSON.stringify(o)}function pm(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 fm(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 bm=(t,e)=>e.some(([n,r])=>t>=n&&t<r);function gm(t,e,n={}){let r=n.hesitationFrames??45,o=n.futileWindow??30,i=n.quitWindow??300,s=n.clusterPx??64,a=e.inputLog.frames,u=fm(e),l=new Set(e.axesLog.map(([k])=>k)),c=[],m=null;for(let k=0;k<=a.length;k++){let T=k<a.length&&a[k].length===0&&!l.has(k);if(T&&m===null&&(m=k),!T&&m!==null){let F=k-m;F>=r&&!bm(m,u)&&c.push({startFrame:m,frames:F}),m=null}}let d=new Map;for(let k=0;k<a.length;k++){let T=k>0?a[k-1]:[];for(let F of a[k])T.includes(F)||(d.has(F)||d.set(F,[]),d.get(F).push(k))}let p=Object.keys(t.inputMap??{}).filter(k=>!d.has(k)),b=new Set;for(let k of c)b.add(k.startFrame);for(let k of e.annotations)b.add(Math.max(0,Math.min(k.frame,a.length-1)));for(let[,k]of d)for(let T of k)b.add(Math.max(0,T-1)),b.add(Math.min(a.length-1,T+o));a.length>0&&b.add(a.length-1);let v=new Map,M=[],x=!1,C=-1,I=ao(t,e,{onWorld:k=>{k.events.on("death",()=>M.push({frame:C+1,pos:pm(k.probe())})),k.events.on("goal",()=>x=!0)},onFrame:(k,T)=>{C=T,b.has(T)&&v.set(T,k.probe())}}),y=a.length>0?v.get(a.length-1)??I.probe():I.probe();y.won===!0&&(x=!0);let f=c.map(k=>({...k,probe:v.get(k.startFrame)??{}})),w=new Map;for(let k of M){let T=k.pos?`${Math.round(k.pos.x/s)}:${Math.round(k.pos.y/s)}`:"unknown",F=w.get(T)??{x:k.pos?.x??0,y:k.pos?.y??0,count:0,frames:[]};F.count++,F.frames.push(k.frame),w.set(T,F)}let S=[];for(let[k,T]of d){let F=[];for(let O of T){let A=v.get(Math.max(0,O-1)),J=v.get(Math.min(a.length-1,O+o));A&&J&&Ps(A)===Ps(J)&&F.push(O)}F.length>0&&S.push({action:k,futilePresses:F.length,totalPresses:T.length,frames:F})}let D=e.annotations.map(k=>{let T=Math.max(0,Math.min(k.frame,a.length-1));return{frame:k.frame,tag:k.tag,...k.note!==void 0?{note:k.note}:{},probe:v.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:x,deaths:M.length,hesitations:f,deathClusters:[...w.values()].sort((k,T)=>T.count-k.count),futileVerbs:S.sort((k,T)=>T.futilePresses-k.futilePresses),annotations:D,knobEvents:e.knobEvents,unusedActions:p};if(!x&&a.length>0){let k=Math.max(0,a.length-i);R.quit={frame:a.length-1,probe:y,recentDeaths:M.filter(T=>T.frame>=k).length,recentHesitations:f.filter(T=>T.startFrame>=k).length,endReason:e.endReason}}return R}function ym(t,e,n,r){let o=t.palette?.bg??"#141821",i=t.palette?.fg??(Yt(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 tn(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 Je({width:r,height:o,background:i}):n.renderer==="webgl"?new Gt({width:r,height:o,background:i}):new Xe({width:r,height:o,background:i});e.style.position=e.style.position||"relative",a.mount?.(e),Ut(e);let u=new Ve(t.inputMap??{},document),l=new At(a,{keyboard:u}),c=[...n.sources??[]],m=ro(),d=()=>s.input.declareActions(u.actionNames());d();let h=()=>{$e.start();let E=Ae.get();$e.setVolumes(E),window.removeEventListener("pointerdown",h),window.removeEventListener("keydown",h)};window.addEventListener("pointerdown",h),window.addEventListener("keydown",h);let p=()=>a.draw(s.render()),b=()=>{s=Me(t,n.world),d(),p()},v=n.shell===!1?null:new Jt({title:t.title,onRestart:n.onRestart??b,onPause:E=>n.onPause?.(E)}),M=t.splash===!1?null:t.splash??{},x=M&&!m?ym(M,t,r,o):null,C=!m,I=[],y,f=new Promise(E=>y=E),w=performance.now(),S=performance.now(),D=()=>{if(C){C=!1,S=performance.now(),p(),y();for(let E of I.splice(0))E()}},R=E=>{if(!m&&!v?.isPaused&&!n.isHeld?.()){l.sample(s.input);for(let B of c)B.sample(s.input);let L=u.currentActions(),_=s.advance(E,L);_>0&&(u.clearPressed(),n.onAdvance?.(s,_,L))}p()},k=0,T,F=null,O=!1,A=16,J=()=>{k!==0&&(cancelAnimationFrame(k),k=0),T!==void 0&&(clearTimeout(T),T=void 0)},Y=E=>{O||(F=E,document.hidden?T=setTimeout(()=>{T=void 0,F=null,E(performance.now())},A):k=requestAnimationFrame(L=>{k=0,F=null,E(L)}))},te=()=>{let E=F;E!==null&&(J(),F=null,Y(E))};document.addEventListener("visibilitychange",te);let Z=E=>{if(C){x&&a.draw(x),Y(Z);return}let L=E-S;S=E,R(L),Y(Z)};if(Y(Z),C){let E=M?.minDurationMs??0,L=t.preload?Promise.resolve().then(()=>t.preload(s)):Promise.resolve(),_=new Promise(B=>setTimeout(B,Math.max(0,E-(performance.now()-w))));Promise.all([L,_]).then(D).catch(B=>{console.error("hayao: preload failed \u2014",B),D()})}else y();let oe={get world(){return s},renderer:a,input:u,pointer:l,canvas:a.element,toDesign:(E,L)=>a.toDesign?.(E,L)??{x:E,y:L},viewport:()=>a.viewport?.(),ready:f,onReady(E){C?I.push(E):E()},addSource(E){return c.push(E),()=>{let L=c.indexOf(E);L!==-1&&c.splice(L,1),E.dispose?.()}},tick(E){R(E??s.clock.stepMs)},stop(){O=!0,F=null,J(),document.removeEventListener("visibilitychange",te),u.dispose(),l.dispose();for(let E of c)E.dispose?.();c.length=0,v?.dispose(),a.dispose?.()},restart:b};return m&&oo({get world(){return s},stepOnce:(E=[])=>{s.step(E),p()},renderSVG:()=>zt(s.render(),r,o,i),setPaused:()=>{}}),oe}function uo(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 vm(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=tn(t,r,{shell:!1,isHeld:()=>!0}),i=o.canvas;return{handle:o,touchDown(s,a,u=1){i?.dispatchEvent(uo("pointerdown",s,a,u))},touchMove(s,a,u=1){i?.dispatchEvent(uo("pointermove",s,a,u))},touchUp(s=1){globalThis.dispatchEvent?.(uo("pointerup",0,0,s))},step(s=1,a){for(let u=0;u<s;u++)o.pointer.sample(o.world.input),o.world.step(o.input.currentActions(),a),o.input.clearPressed()},dispose(){o.stop(),n&&r.remove()}}}var lo=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}},co=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 xm(t){return{kind:"sleep",left:t}}function wm(t){return{kind:"cond",cond:t}}function km(){return{kind:"next"}}function Sm(...t){return{kind:"race",waits:t}}function Mm(...t){return{kind:"all",waits:t}}var Es=1e-9;function mo(t,e){if(Ds(t))return t.done?0:-1;switch(t.kind){case"sleep":return t.left-=e,t.left<=Es?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++)mo(t.waits[r],e)>=0&&n<0&&(n=r);return n}case"all":{let n=!0;for(let r of t.waits)ho(r)||mo(r,e)<0&&(n=!1);return n?0:-1}}}function ho(t){if(Ds(t))return t.done;switch(t.kind){case"sleep":return t.left<=Es;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 Ds(t){return t instanceof In}var In=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{}}}},po=class{runners=[];pending=[];nextId=0;start(e,n){let r=new In(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=mo(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 Tm(t){let e=0;for(let n of t)e+=n>0?n:0;return e}function bo(t,e){let n=Tm(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 Cm(t,e,n){if(e.length!==n.length)throw new Error("hayao: weightedPick items/weights length mismatch");return e[bo(t,n)]}function go(t,e){return e[bo(t,e.map(n=>n.weight))].value}var fo=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 Is(t,e,n,r={}){let o=r.maxNodes??1e6,i=[],s=new Map,a=new Map,u=n(t);a.set(u,0);let l=[t];if(i.push(t),r.goal?.(t))return{order:i,cameFrom:s,dist:a};let c=0;for(;l.length>0&&c<o;){let m=[];for(let d of l){let h=a.get(n(d))??0;for(let p of e(d)){let b=n(p);if(!a.has(b)){if(a.set(b,h+1),s.set(b,d),i.push(p),c++,r.goal?.(p))return{order:i,cameFrom:s,dist:a};m.push(p)}}}l=m}return{order:i,cameFrom:s,dist:a}}function Rm(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 Fs(t,e,n,r,o={}){let i=o.heuristic??(()=>0),s=o.maxNodes??1e6,a=new Map,u=new Map,l=new yo,c=r(t);u.set(c,0),l.push(t,i(t));let m=0;for(;l.size>0&&m<s;){let{item:d,priority:h}=l.pop(),p=r(d),b=u.get(p)??1/0;if(!(h>b+i(d)+1e-9)){if(e(d))return{path:Pm(a,r,d),cost:b};m++;for(let v of n(d)){let M=r(v.node),x=b+v.cost;x<(u.get(M)??1/0)&&(u.set(M,x),a.set(M,d),l.push(v.node,x+i(v.node)))}}}return null}function Pm(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 yo=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]]}},nn=[{x:0,y:-1},{x:1,y:0},{x:0,y:1},{x:-1,y:0}],Fn=[...nn,{x:1,y:-1},{x:1,y:1},{x:-1,y:1},{x:-1,y:-1}],As=t=>`${t.x},${t.y}`;function Em(t,e,n,r){let o=r?Fn:nn;return i=>{let s=[];for(let a of o){let u=i.x+a.x,l=i.y+a.y;u<0||l<0||u>=e||l>=n||t(u,l)&&s.push({x:u,y:l})}return s}}function vo(t,e,n){if(!e(t.x,t.y))return[];let r=Em(e,n.cols,n.rows,n.diagonal??!1);return Is(t,r,As).order}function Dm(t,e,n,r=!1){let o=new Array(t*e).fill(-1),i=[],s=r?Fn:nn;for(let a=0;a<e;a++)for(let u=0;u<t;u++){if(o[a*t+u]!==-1||!n(u,a))continue;let l=i.length,c=[],m=[{x:u,y:a}];for(o[a*t+u]=l;m.length>0;){let d=[];for(let h of m){c.push(h);for(let p of s){let b=h.x+p.x,v=h.y+p.y;if(b<0||v<0||b>=t||v>=e)continue;let M=v*t+b;o[M]!==-1||!n(b,v)||(o[M]=l,d.push({x:b,y:v}))}}m=d}i.push(c)}return{labels:o,cells:i}}function Im(t,e,n,r){let o=r.diagonal??!1,i=o?Fn:nn,s=r.cost??(()=>1),a=1.4142135623730951,u=m=>{let d=[];for(let h of i){let p=m.x+h.x,b=m.y+h.y;if(p<0||b<0||p>=r.cols||b>=r.rows||!n(p,b))continue;let v=h.x!==0&&h.y!==0;d.push({node:{x:p,y:b},cost:s(p,b)*(v?a:1)})}return d},l=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=Fs(t,m=>m.x===e.x&&m.y===e.y,u,As,{heuristic:l,maxNodes:r.maxNodes});return c?c.path:null}function Fm(t){return(e,n)=>fe(t,e,n)!==U.SOLID}function Am(t){return structuredClone(t)}var xo=class{history=[];cursor=-1;limit;clone;constructor(e={}){this.limit=Math.max(1,e.limit??64),this.clone=e.clone??Am}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}},wo=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 An=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()]}},ko=class{get(e){return null}set(e,n){}remove(e){}keys(){return[]}},Nn=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 So(t){try{if(typeof localStorage<"u"){let e="__hayao_probe__";return localStorage.setItem(e,"1"),localStorage.removeItem(e),new Nn(t)}}catch{}return new An}function Nm(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 Lm(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 Mo="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",Ns={};for(let t=0;t<Mo.length;t++)Ns[Mo[t]]=t;function $m(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+=Mo[o]}while(r>0)}return e}function Wm(t){let e=[],n=0,r=1;for(let o of t){let i=Ns[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 Ro=1;function Ls(t){return JSON.stringify({v:Ro,snap:t})}function To(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!==Ro||!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 Co=class{constructor(e,n=So()){this.world=e;this.storage=n}world;storage;save(e="auto"){this.storage.set(e,Ls(this.world.snapshot()))}load(e="auto"){let n=To(this.storage.get(e));return n?(this.world.restore(n),!0):!1}has(e="auto"){return To(this.storage.get(e))!==null}delete(e="auto"){this.storage.remove(e)}slots(){return this.storage.keys()}};function zm(t){return{next:t.map(e=>e.time)}}function Bm(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 u;if(typeof s.spawn=="string")u=s.spawn;else{if(!r)throw new Error("hayao: pollDirector needs an Rng to roll a weighted wave");u=go(r,s.spawn)}if(o.push({spawn:u,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 _m(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 Gm=new Set(["#","-","^","."," "]),rn=t=>t===U.SOLID,Om=t=>t===U.HAZARD,$s=(t,e,n)=>({x:(t+.5)*n,y:(e+.5)*n});function Vm(t){let e=t.tileSize??32,n=t.legend??{},r=t.rows,o=Math.max(0,...r.map(u=>u.length)),i=null,s=null,a=[];if(r.forEach((u,l)=>{for(let c=0;c<u.length;c++){let m=u[c];if(m==="S")i={x:c,y:l};else if(m==="G")s={x:c,y:l};else if(m in n){let d=$s(c,l,e);a.push({kind:n[m],tx:c,ty:l,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 Hm(t){let e=[],n=Ln(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"||Gm.has(a)||a in t.legend||e.push(`unknown glyph '${a}' at (${s},${i}) \u2014 add it to the legend or use terrain '#/-/^/.'`)}}),rn(r(t.spawn))&&e.push(`spawn (${t.spawn.x},${t.spawn.y}) is inside a solid tile`),rn(r(t.goal))&&e.push(`goal (${t.goal.x},${t.goal.y}) is inside a solid tile`),[...new Set(e)]}function Ln(t){return hr(t.rows,t.tileSize)}function qm(t,e={}){let n=Ln(t),r=(u,l)=>n.tiles[l*n.cols+u]??U.EMPTY,o=e.passable??((u,l)=>!rn(r(u,l))),i=vo(t.spawn,o,{cols:n.cols,rows:n.rows,diagonal:e.diagonal}),s=new Set(i.map(u=>`${u.x},${u.y}`)),a=[];s.has(`${t.goal.x},${t.goal.y}`)||a.push("goal");for(let u of t.entities)s.has(`${u.tx},${u.ty}`)||a.push(`entity@${u.tx},${u.ty}`);return{ok:a.length===0,unreachable:a,reached:i.length}}function jm(t,e){let n=Ln(t),{cols:r,rows:o}=n,i=(x,C)=>x<0||C<0||x>=r||C>=o?U.SOLID:n.tiles[C*r+x],s=(x,C)=>{let I=i(x,C+1);return I===U.SOLID||I===U.ONEWAY},a=(x,C)=>!rn(i(x,C))&&!Om(i(x,C))&&s(x,C),l=(x=>{for(let C=x.y;C<o;C++)if(a(x.x,C))return{x:x.x,y:C};return null})(t.spawn);if(!l)return{ok:!1,unreachable:["goal"],reached:0};let c=(x,C)=>Math.abs(C.x-x.x)<=e.runTiles&&x.y-C.y<=e.jumpTiles,m=[];for(let x=0;x<o;x++)for(let C=0;C<r;C++)a(C,x)&&m.push({x:C,y:x});let d=x=>`${x.x},${x.y}`,h=new Set([d(l)]),p=[l];for(;p.length;){let x=p.shift();for(let C of m){let I=d(C);!h.has(I)&&c(x,C)&&(h.add(I),p.push(C))}}let b=[...h].map(x=>{let[C,I]=x.split(",").map(Number);return{x:C,y:I}}),M=!rn(i(t.goal.x,t.goal.y))&&(h.has(d(t.goal))||b.some(x=>c(x,t.goal)))?[]:["goal"];return{ok:M.length===0,unreachable:M,reached:h.size}}function Um(t,e){let n=[],r=Math.max(t.rowCount,e.rowCount),o=Math.max(t.cols,e.cols),i=(l,c,m)=>l.rows[m]?.[c]??" ";for(let l=0;l<r;l++)for(let c=0;c<o;c++){let m=i(t,c,l),d=i(e,c,l);m!==d&&n.push({kind:"tile",detail:`(${c},${l}) '${m}' \u2192 '${d}'`})}let s=l=>`${l.kind}@${l.tx},${l.ty}`,a=new Set(t.entities.map(s)),u=new Set(e.entities.map(s));for(let l of e.entities)a.has(s(l))||n.push({kind:"entity+",detail:s(l)});for(let l of t.entities)u.has(s(l))||n.push({kind:"entity-",detail:s(l)});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 Ws(t,e){return jn(`hayao/gen:${t>>>0}:${e}`)}var Xm=(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 zs(t,e){let n=e.seed??1,r=e.maxAttempts??e.count*60,o=e.dedupeKey??(l=>l.key(l.initial())),i=[],s=new Set,a=0,u=0;for(let l=0;l<r&&i.length<e.count;l++){a++;let c=Ws(n,l),m=t(new le(c)),d=Ze(m,e.solve);if(!d.solvable||d.exhausted||d.depth===void 0)continue;u++;let h={path:d.path??[],depth:d.depth,nodes:d.nodes};if(!Xm(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((l,c)=>l.depth-c.depth||l.nodes-c.nodes||l.seed-c.seed),i.forEach((l,c)=>l.index=c),{levels:i,attempts:a,solvable:u,complete:i.length>=e.count,seeds:i.map(l=>l.seed)}}function Po(t,e){let n=zs(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 Jm(t,e){return t(new le(e))}function Ym(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 u=(e^(s+1)*2654435769)>>>0,l=Po(a,{count:i.count,seed:u,minDepth:i.minDepth,maxDepth:i.maxDepth,minNodes:i.minNodes,maxNodes:i.maxNodes,solve:i.solve??t.solve,maxAttempts:i.maxAttempts}),c=r.length;l.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 _s(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 Bs(t,e){return(t.requires??[]).every(n=>e.has(n))}function Gs(t,e,n){let r=[];for(let o of t.edges)o.from===e&&Bs(o,n)?r.push(o.to):!o.oneWay&&o.to===e&&Bs(o,n)&&r.push(o.from);return r}function $n(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=_s(t,o.taken),s=[];for(let u of n(o.region))o.taken.includes(u.id)||s.push({kind:"take",pickup:u.id});let a=new Set;for(let u of Gs(t,o.region,i))a.has(u)||(a.add(u),s.push({kind:"move",to:u}));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 Os={maxDepth:2e3,nodeCap:5e6};function Km(t){return Ze($n(t,"complete"),Os)}function Qm(t){return Ze($n(t,"full"),Os)}function Vs(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 Gs(t,i,n))r.has(s)||(r.add(s),o.push(s))}return[...r]}function Zm(t,e="complete"){let n=$n(t,e),r=n.initial(),o=n.key(r),i=new Map([[o,r]]),s=new Map,a=new Set,u=[r];for(n.isWin(r)&&a.add(o);u.length;){let h=u.shift(),p=n.key(h),b=[];for(let v of n.moves(h)){let M=n.apply(h,v),x=n.key(M);b.push(x),i.has(x)||(i.set(x,M),n.isWin(M)&&a.add(x),u.push(M))}s.set(p,b)}let l=new Map;for(let[h,p]of s)for(let b of p)(l.get(b)??l.set(b,[]).get(b)).push(h);let c=new Set(a),m=[...a];for(;m.length;){let h=m.shift();for(let p of l.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 ed(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(Vs(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 td(t){let e=[];for(let n=1;n<=t;n++)e.push(`p${n}`);return e}var on=(t,e)=>`${t}:${e}`;function xt(t,e){let n=[];for(let r of t){let o=e.get(r)??[];for(let i of o)n.push(on(r,i))}return n.sort()}var Wn=class{constructor(e,n){this.world=e;this.player=n}world;player;isDown(e){return this.world.input.isDown(on(this.player,e))}justPressed(e){return this.world.input.justPressed(on(this.player,e))}justReleased(e){return this.world.input.justReleased(on(this.player,e))}},nd=(t,e)=>new Wn(t,e);var sb=1,et={mode:"lockstep",inputDelay:2,hashInterval:20,maxRollback:12,redundancy:3};function de(t){return JSON.stringify(t)}function Ne(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 Eo=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 zn(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}},zn=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)}},Do=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 rd(t){return new Promise((e,n)=>{let r=new WebSocket(t),o=[],i=[],s=!1,a={send(u){s&&r.send(u)},onMessage(u){return o.push(u),()=>{let l=o.indexOf(u);l>=0&&o.splice(l,1)}},onClose(u){return i.push(u),()=>{let l=i.indexOf(u);l>=0&&i.splice(l,1)}},close(){s=!1,r.close()},get isOpen(){return s}};r.onopen=()=>{s=!0,e(a)},r.onmessage=u=>{if(typeof u.data=="string")for(let l of o)l(u.data)},r.onclose=()=>{let u=s;if(s=!1,u)for(let l of i)l()},r.onerror=()=>{s||n(new Error(`hayao-net: could not connect to ${t}`))}})}var tt=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 Ee=class{world;localPlayer;config;startFrame;transport;buffer=new tt;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={...et,...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=xt(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=Ne(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 sn=class{world;localPlayer;config;transport;players;buffer=new tt;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={...et,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(xt(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(xt(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=Ne(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=Ct(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 od(){return globalThis.crypto.randomUUID()}function Hs(t,e,n,r,o,i,s,a,u){return t==="rollback"?new sn({world:e,transport:n,localPlayer:r,players:o,config:s,attach:a,onDesync:u.onDesync}):new Ee({world:e,transport:n,localPlayer:r,players:o,startFrame:i,config:s,onDesync:u.onDesync})}function qs(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 Bn=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={...et,...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=Hs(this.config.mode,e,this.transport,this.localPlayer,this.players,0,this.config,this.attach,this.callbacks);return n instanceof Ee&&n.onAfterStep(r=>this.serviceSnapshots(r,e)),this.transport.send(de(he({t:"start",players:[...this.players]}))),this.game=qs(e,n,this.localPlayer,this.players,()=>this.unsubscribe()),this.game}dropPlayer(e){let n=this.game?.session;if(!n)return;let r=n instanceof Ee?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=Ne(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(u=>u.player!==i.player),a=new Set(s.map(u=>u.player));this.transport.send(de(he({t:"welcome",to:i.uid,player:i.player,players:this.players.filter(u=>!a.has(u)),seed:this.seed,config:this.config,startFrame:e,snapshot:o,joins:s.map(u=>({player:u.player,atFrame:u.atFrame}))})))}}};function Io(t){let e=od(),n=t.transport;return new Promise((r,o)=>{let i=null,s=!1,a=null,u=[],l=[],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=Hs(i.config.mode,h,n,i.player,d,i.startFrame,i.config,t.attach,t);if(i.joins&&p instanceof Ee)for(let M of i.joins)p.addPlayer(M.player,M.atFrame);for(let M of l)M.t==="join"&&p instanceof Ee&&p.addPlayer(M.player,M.atFrame),M.t==="leave"&&p.removePlayer(M.player,M.atFrame);let b=n.onMessage(M=>{let x=Ne(M);x&&(x.t==="join"&&p instanceof Ee?(p.addPlayer(x.player,x.atFrame),t.onPlayerJoin?.(x.player,x.atFrame)):x.t==="leave"&&(p.removePlayer(x.player,x.atFrame),t.onPlayerLeave?.(x.player,x.atFrame)))}),v=qs(h,p,i.player,d,()=>{b(),n.send(de(he({t:"bye",uid:e})))});for(let M of u)p.deliver(M);r(v)},m=n.onMessage(d=>{let h=Ne(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":l.push(h);break;case"input":case"hash":u.push(d);break}});n.send(de(he({t:"hello",uid:e,name:t.name})))})}function Fo(t){return new Bn(t)}function id(t,e,n){let r=t.width??1280,o=t.height??720,i=t.background??"#f3ecdb",s=n.renderer==="canvas"?new Je({width:r,height:o,background:i}):new Xe({width:r,height:o,background:i});e.style.position=e.style.position||"relative",s.mount?.(e),Ut(e);let a=new Ve(t.inputMap??{},document),u=b=>Me(t,b),l=null,c=null,m=0,d=!1,h=b=>v=>{!d&&l&&(l.advance(v-b,a.currentActions())>0&&a.clearPressed(),s.draw(l.world.render())),m=requestAnimationFrame(h(v))},p=b=>{l=b,n.onStatus?.(`playing as ${b.localPlayer} (${b.players.length} players)`),m=requestAnimationFrame(h(performance.now()))};return n.role==="host"?(c=Fo({transport:n.transport,makeWorld:u,seed:n.seed??t.seed??1,config:n.config,maxPlayers:n.maxPlayers,attach:n.attach,onDesync:n.onDesync,onPlayerJoin:(b,v)=>{n.onStatus?.(`${b} joined`),n.onPlayerJoin?.(b,v)},onPlayerLeave:n.onPlayerLeave}),n.onStatus?.("hosting \u2014 waiting for players")):(n.onStatus?.("joining\u2026"),Io({transport:n.transport,makeWorld:u,attach:n.attach,onDesync:n.onDesync,onPlayerJoin:n.onPlayerJoin,onPlayerLeave:n.onPlayerLeave}).then(p).catch(b=>n.onStatus?.(b.message))),{start(){c&&!l&&p(c.start())},get game(){return l},get localPlayer(){return l?.localPlayer??(n.role==="host"?"p1":null)},get roster(){return c?.roster??l?.players??[]},input:a,stop(){d=!0,cancelAnimationFrame(m),l?.dispose(),c?.dispose(),a.dispose(),s.dispose?.()}}}var sd=0;function ad(t,e){return`${t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"game"}-${e.replace(/[:.]/g,"-").toLowerCase()}-${(sd++).toString(36)}`}var nt=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??ad(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 wt=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 _n(t,e,n,r,o,i,s){let a=Math.max(n.minFrame,Math.min(s,r.length)),u=n.nearest(a);if(!u)return null;t.restore(structuredClone(u.snap)),e.attach?.(t),t.input.axes.clear();let l=new Map,c=0;for(;c<o.length&&o[c][0]<u.frame;){let[,d,h]=o[c++];l.set(d,h)}for(let[d,h]of l)t.input.axes.set(d,h);let m=i.findIndex(d=>d.frame>=u.frame);m<0&&(m=i.length);for(let d=u.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 ud(){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 ld(t,e,n={}){let r=ud(),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"}),u=n.world?.seed??r.seed??s.seed??1,l={...i?.tuning,...r.tuning,...n.world?.tuning},c=en(s.tuning,l),m={...c},d=typeof performance<"u"?performance.now():0,h=new nt({game:s.title,seed:u,tuningValues:c,variant:a}),p=!1,b=(E,L)=>{let _=JSON.stringify(E);if(L&&typeof navigator<"u"&&navigator.sendBeacon){navigator.sendBeacon("/__studio/session",new Blob([_],{type:"application/json"}));return}fetch("/__studio/session",{method:"POST",headers:{"content-type":"application/json"},body:_}).catch(()=>{})},v=(E="quit",L=!1)=>{x||h.frame===0&&p||(b(h.toSession(E),L),p=!0)},M=typeof location<"u"?new URLSearchParams(location.search).get("session"):null,x=null,C=null,I=new wt,y=!1,f=null,w=()=>{if(f===null||f>=h.frame){f=null;return}h.truncate(f),I.truncate(f),h.screen("scrub",`forked@${f}`),f=null},S=tn(s,e,{...n,world:{seed:u,tuning:l},isHeld:()=>y||(n.isHeld?.()??!1),onAdvance:(E,L,_)=>{for(let B=0;B<L;B++)h.step(_,E.input.axes),I.push(h.frame,E);n.onAdvance?.(E,L,_)},onPause:E=>{h.screen(E?"pause":"resume"),n.onPause?.(E)},onRestart:()=>{v("restart"),h=new nt({game:s.title,seed:u,tuningValues:{...m},variant:a,buildRef:h.buildRef}),(n.onRestart??S.restart)()}}),D=n.hot?.data.hayaoSnap;if(D){delete n.hot.data.hayaoSnap;let E=structuredClone(D);E.tuning={...m},S.world.restore(E),s.attach?.(S.world),h=new nt({game:s.title,seed:u,tuningValues:{...m},variant:a,startSnapshot:E}),h.screen("hot-swap")}n.hot?.dispose(E=>{E.hayaoSnap=S.world.snapshot(),Z("hot-swap")}),I.push(0,S.world);async function R(E,L){let _=await fetch(`/__studio/session/${encodeURIComponent(E)}`);if(!_.ok)return;let B=await _.json();y=!0;let q=S.world,ie=Me(s,{seed:B.seed,tuning:B.tuningValues});q.restore(B.startSnapshot?structuredClone(B.startSnapshot):ie.snapshot()),s.attach?.(q),q.input.axes.clear();let se=B.inputLog.frames,re=Math.max(30,Math.ceil(se.length/220/30)*30);I=new wt(re),I.push(0,q);let ae=0,me=0;for(let ve=0;ve<se.length;ve++){for(;me<B.knobEvents.length&&B.knobEvents[me].frame===ve;){let We=B.knobEvents[me++],Te=q.snapshot();Te.tuning={...Te.tuning,[We.key]:We.value},q.restore(Te),s.attach?.(q)}for(;ae<B.axesLog.length&&B.axesLog[ae][0]===ve;){let[,We,Te]=B.axesLog[ae++];q.input.axes.set(We,Te)}q.step(se[ve]),I.push(ve+1,q)}x={session:B,pos:se.length},oe.scrub(Number.isFinite(L)?L:0)}function k(){if(!x||C!==null)return;let E=x.session,L=performance.now();C=window.setInterval(()=>{if(!x)return;let _=performance.now(),B=Math.min(120,Math.floor((_-L)/(1e3/60)));if(B<=0)return;L=_;let q=S.world;for(let ie=0;ie<B;ie++){let se=x.pos;if(se>=E.inputLog.frames.length){T();return}for(let re of E.knobEvents)if(re.frame===se){let ae=q.snapshot();ae.tuning={...ae.tuning,[re.key]:re.value},q.restore(ae),s.attach?.(q)}for(let[re,ae,me]of E.axesLog)re===se&&q.input.axes.set(ae,me);q.step(E.inputLog.frames[se]),x.pos=se+1}},1e3/60)}function T(){C!==null&&(window.clearInterval(C),C=null)}M&&R(M,Number(new URLSearchParams(location.search).get("at")??"NaN")),fetch("/__studio/state").then(E=>E.ok?E.json():null).then(E=>{E?.buildRef&&(h.buildRef=E.buildRef)}).catch(()=>{}),En((E,L)=>h.screen(E==="show"?"overlay-show":"overlay-hide",L));let F=()=>typeof performance<"u"?performance.now()-d:0,O=()=>h.mark(document.hidden?"visibility-hidden":"visibility-visible",F()),A=()=>h.mark("blur",F()),J=()=>h.mark("focus",F()),Y=()=>v("quit",!0);document.addEventListener("visibilitychange",O),window.addEventListener("blur",A),window.addEventListener("focus",J),window.addEventListener("pagehide",Y);let te=window.setInterval(()=>v("idle"),1e4),Z=E=>{T(),v(E,E==="hot-swap"),document.removeEventListener("visibilitychange",O),window.removeEventListener("blur",A),window.removeEventListener("focus",J),window.removeEventListener("pagehide",Y),window.clearInterval(te),En(null),S.stop()},oe={...S,get world(){return S.world},setKnob(E,L){if(x)return;w(),m[E]=L;let _=S.world.snapshot();_.tuning={...m},S.world.restore(_),s.attach?.(S.world),h.knob(E,L)},knobValues:()=>({...m}),tuningSpec:()=>s.tuning,variants:()=>Object.fromEntries(Object.entries(n.variants??{}).map(([E,L])=>[E,L.label])),activeVariant:()=>({...a}),title:()=>s.title,annotate:(E,L)=>{x||h.annotate(E,L)},setFrozen(E){if(x){E?T():k();return}if(E===y)return;if(E){y=!0;return}let L=f!==null;if(w(),L){let _=S.world.snapshot().tuning??{};for(let B of Object.keys(m))B in _&&(m[B]=_[B])}y=!1},frozen:()=>x?C===null:y,scrub(E){if(x){T();let _=x.session,B=_n(S.world,s,I,_.inputLog.frames,_.axesLog,_.knobEvents,E);return B!==null&&(x.pos=B),B}y=!0;let L=_n(S.world,s,I,h.liveInputFrames,h.liveAxesLog,h.liveKnobEvents,E);return L!==null&&(f=L<h.frame?L:null),L},timeline:()=>x?{min:I.minFrame,frame:x.pos,max:x.session.inputLog.frames.length}:{min:I.minFrame,frame:f??h.frame,max:h.frame},mode:()=>x?"replay":"live",flush:(E="idle")=>v(E),session:()=>h.toSession("idle"),stop:()=>Z("navigate")};return window.__studio=oe,oe}var cd="0.4.0";return Qs(md);})();