hayao 0.4.0 → 0.4.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/design/00-process/README.md +49 -0
- package/design/00-process/composition.md +148 -0
- package/design/00-process/core-loop.md +146 -0
- package/design/00-process/intent-to-brief.md +128 -0
- package/design/00-process/pillars.md +139 -0
- package/design/00-process/refine-and-handoff.md +156 -0
- package/design/00-process/the-twist.md +108 -0
- package/design/10-anchors/README.md +99 -0
- package/design/10-anchors/age-of-empires.md +103 -0
- package/design/10-anchors/baba-is-you.md +127 -0
- package/design/10-anchors/balatro.md +132 -0
- package/design/10-anchors/celeste.md +136 -0
- package/design/10-anchors/civilization.md +101 -0
- package/design/10-anchors/dead-cells.md +125 -0
- package/design/10-anchors/factorio.md +100 -0
- package/design/10-anchors/hades.md +127 -0
- package/design/10-anchors/into-the-breach.md +125 -0
- package/design/10-anchors/it-takes-two.md +104 -0
- package/design/10-anchors/loop-hero.md +131 -0
- package/design/10-anchors/nuclear-throne.md +130 -0
- package/design/10-anchors/outer-wilds.md +107 -0
- package/design/10-anchors/overcooked.md +102 -0
- package/design/10-anchors/peggle.md +133 -0
- package/design/10-anchors/reigns.md +99 -0
- package/design/10-anchors/return-of-the-obra-dinn.md +108 -0
- package/design/10-anchors/rimworld.md +101 -0
- package/design/10-anchors/shadow-of-mordor.md +106 -0
- package/design/10-anchors/slay-the-spire.md +127 -0
- package/design/10-anchors/starcraft.md +98 -0
- package/design/10-anchors/stardew-valley.md +103 -0
- package/design/10-anchors/tetris.md +122 -0
- package/design/10-anchors/vampire-survivors.md +122 -0
- package/design/20-genres/README.md +62 -0
- package/design/20-genres/action-adventure.md +126 -0
- package/design/20-genres/auto-battler.md +121 -0
- package/design/20-genres/bullet-hell.md +123 -0
- package/design/20-genres/city-builder.md +124 -0
- package/design/20-genres/coop-chaos.md +124 -0
- package/design/20-genres/deckbuilder.md +122 -0
- package/design/20-genres/exploration.md +131 -0
- package/design/20-genres/farming-sim.md +122 -0
- package/design/20-genres/grid-puzzle.md +126 -0
- package/design/20-genres/horde-survival.md +128 -0
- package/design/20-genres/incremental.md +120 -0
- package/design/20-genres/match3.md +120 -0
- package/design/20-genres/metroidvania.md +132 -0
- package/design/20-genres/narrative-decisions.md +122 -0
- package/design/20-genres/physics-arcade.md +124 -0
- package/design/20-genres/precision-platformer.md +127 -0
- package/design/20-genres/racing.md +126 -0
- package/design/20-genres/rhythm.md +125 -0
- package/design/20-genres/roguelike.md +122 -0
- package/design/20-genres/rts.md +169 -0
- package/design/20-genres/stealth.md +125 -0
- package/design/20-genres/survival-horror.md +124 -0
- package/design/20-genres/tactics.md +123 -0
- package/design/20-genres/tower-defense.md +120 -0
- package/design/30-systems/README.md +69 -0
- package/design/30-systems/accessibility.md +110 -0
- package/design/30-systems/boss-design.md +126 -0
- package/design/30-systems/build-diversity.md +120 -0
- package/design/30-systems/collectibles.md +108 -0
- package/design/30-systems/combat-model.md +113 -0
- package/design/30-systems/coop-and-competition.md +118 -0
- package/design/30-systems/counter-systems.md +115 -0
- package/design/30-systems/crafting.md +115 -0
- package/design/30-systems/difficulty-and-dda.md +114 -0
- package/design/30-systems/economy.md +117 -0
- package/design/30-systems/emergent-systems.md +114 -0
- package/design/30-systems/encounter-design.md +107 -0
- package/design/30-systems/enemy-ai.md +121 -0
- package/design/30-systems/enemy-archetypes.md +117 -0
- package/design/30-systems/faction-asymmetry.md +144 -0
- package/design/30-systems/grace.md +124 -0
- package/design/30-systems/mastery-curve.md +116 -0
- package/design/30-systems/meta-progression.md +114 -0
- package/design/30-systems/onboarding.md +115 -0
- package/design/30-systems/procgen-design.md +118 -0
- package/design/30-systems/progression.md +120 -0
- package/design/30-systems/resource-loops.md +112 -0
- package/design/30-systems/reward-schedules.md +124 -0
- package/design/30-systems/save-and-checkpoint.md +113 -0
- package/design/30-systems/session-structure.md +113 -0
- package/design/30-systems/skill-trees.md +111 -0
- package/design/30-systems/status-effects.md +111 -0
- package/design/30-systems/tech-tree.md +112 -0
- package/design/30-systems/telegraphs.md +106 -0
- package/design/30-systems/unit-rosters.md +123 -0
- package/design/40-worldbuilding/README.md +49 -0
- package/design/40-worldbuilding/aesthetic-direction.md +155 -0
- package/design/40-worldbuilding/faction-identity.md +136 -0
- package/design/40-worldbuilding/naming-and-tone.md +130 -0
- package/design/40-worldbuilding/narrative-delivery.md +129 -0
- package/design/40-worldbuilding/theme-vectors.md +134 -0
- package/design/40-worldbuilding/worldbuilding-scaffold.md +132 -0
- package/design/50-patterns/README.md +54 -0
- package/design/50-patterns/anti-frustration.md +121 -0
- package/design/50-patterns/emergence.md +121 -0
- package/design/50-patterns/feedback-loops.md +121 -0
- package/design/50-patterns/juice-choreography.md +124 -0
- package/design/50-patterns/mastery-and-flow.md +121 -0
- package/design/50-patterns/pacing-and-tension.md +120 -0
- package/design/50-patterns/readability.md +121 -0
- package/design/50-patterns/risk-reward.md +120 -0
- package/design/CONTRIBUTING.md +183 -0
- package/design/INDEX.md +133 -0
- package/design/README.md +86 -0
- package/design/_TEMPLATE.md +69 -0
- package/design/index.json +2720 -0
- package/dist/anim/blend.d.ts +68 -0
- package/dist/anim/clip.d.ts +87 -0
- package/dist/anim/ik.d.ts +40 -0
- package/dist/anim/skeleton.d.ts +64 -0
- package/dist/hayao.global.js +12 -12
- package/dist/index.d.ts +11 -1
- package/dist/index.js +1683 -516
- package/dist/index.js.map +4 -4
- package/dist/index.min.js +12 -12
- package/dist/render/canvas2d-core.d.ts +4 -0
- package/dist/render/commands.d.ts +19 -0
- package/dist/render/lightRun.d.ts +35 -0
- package/dist/render/svgString.d.ts +8 -3
- package/dist/scene/clipPlayer.d.ts +58 -0
- package/dist/scene/ikTarget.d.ts +25 -0
- package/dist/scene/light.d.ts +80 -0
- package/dist/scene/shadow2d.d.ts +25 -0
- package/dist/scene/skeletonDebug.d.ts +28 -0
- package/dist/verify/gates.d.ts +25 -0
- package/docs/API.md +66 -8
- package/docs/CONVENTIONS.md +56 -0
- package/package.json +2 -1
package/dist/hayao.global.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
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,"&").replace(/</g,"<").replace(/>/g,">")}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
|
|
1
|
+
"use strict";var hayao=(()=>{var mr=Object.defineProperty;var Ia=Object.getOwnPropertyDescriptor;var La=Object.getOwnPropertyNames;var $a=Object.prototype.hasOwnProperty;var Na=(t,e)=>{for(var n in e)mr(t,n,{get:e[n],enumerable:!0})},Fa=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of La(e))!$a.call(t,o)&&o!==n&&mr(t,o,{get:()=>e[o],enumerable:!(r=Ia(e,o))||r.enumerable});return t};var Aa=t=>Fa(mr({},"__esModule",{value:!0}),t);var lh={};Na(lh,{ALBUM:()=>Gs,AMBIENT_PRESETS:()=>vl,AmbientField:()=>Mr,AnimationPlayer:()=>Vt,AudioBus:()=>jn,BLOOM_PIPELINE:()=>ju,BitmapText:()=>ro,Blend1D:()=>Ir,Blend2D:()=>Lr,Bone2D:()=>Ve,BroadcastChannelTransport:()=>ai,CLIP_CHANNELS:()=>ki,Camera2D:()=>Ot,CameraController:()=>wr,Canvas2DRenderer:()=>lt,CinematicPlayer:()=>$o,ClipPlayer:()=>qt,Clock:()=>At,Coroutines:()=>qo,DEFAULT_GAMEPAD_MAP:()=>Wi,DEFAULT_INPUT_MAP:()=>Fn,DEFAULT_PLATFORMER:()=>St,DEFAULT_SESSION_CONFIG:()=>dt,DEFAULT_TILE_CHARS:()=>zr,DUSK:()=>Ln,DepthSort:()=>vr,EASINGS:()=>Fe,Edge:()=>ne,EventBus:()=>Wt,FLOAT_PRESETS:()=>wl,FONT_5:()=>no,FloatingText:()=>Pr,Fsm:()=>Oo,GENRES:()=>_s,GENRE_PROFILES:()=>Yc,GamepadSource:()=>Ur,HeadlessRenderer:()=>eo,IDENTITY:()=>oe,INSTRUMENTS:()=>W,IkTarget:()=>Fr,InputBuffer:()=>ht,InputRecorder:()=>Vr,InputState:()=>Jt,IsoPrism:()=>xr,KENTO:()=>B,KeyboardSource:()=>et,LAYER_HUD:()=>Mp,LAYER_LIGHT:()=>He,LAYER_WORLD:()=>Tp,LightLayer:()=>Xt,LocalStorageAdapter:()=>or,LockstepSession:()=>Ie,LoopbackHub:()=>si,LoopbackTransport:()=>lr,LootTable:()=>jo,MEADOW:()=>Ri,MOUSE_ACTIONS:()=>jr,MemoryStorage:()=>rr,NEIGHBORS_4:()=>gn,NEIGHBORS_8:()=>nr,NET_PROTOCOL_VERSION:()=>Zg,Node:()=>_,Node2D:()=>_,NodePool:()=>Sr,NullStorage:()=>Zo,PAD_NEUTRAL:()=>Jl,PALETTES:()=>Rl,PANEL_PRESETS:()=>Yu,PAPER:()=>Pi,PARTICLE_PRESETS:()=>vi,ParallaxLayer:()=>kr,Particles:()=>Tr,PhaseClock:()=>Go,PixelBuffer:()=>Tt,PlayerInput:()=>ar,PointLight:()=>vt,PointerSource:()=>Yt,RingBuffer:()=>Qo,Rng:()=>ue,RollbackSession:()=>vn,RoomHost:()=>ur,SAMPLE_RATE:()=>be,SAVE_FORMAT_VERSION:()=>oi,SCALES:()=>fo,SaveManager:()=>ri,ScreenTransition:()=>er,SessionRecorder:()=>pt,Shaker:()=>Rr,Shell:()=>mn,Signal:()=>gt,Skeleton:()=>Pn,SkeletonDebug:()=>Ar,SnapshotRing:()=>Nt,SpatialHash:()=>Qt,Sprite:()=>zt,SvgRenderer:()=>at,TAU:()=>Z,TILE:()=>U,Text:()=>_t,TextureSprite:()=>to,Timer:()=>Gt,TouchControls:()=>Lo,UndoStack:()=>Ko,VERSION:()=>ah,VerletChain:()=>Dr,WEBGL_EFFECTS:()=>rn,WangFrame:()=>Qe,WebGL2Renderer:()=>on,World:()=>pn,abilitiesOf:()=>Ca,addBody:()=>lu,addDistanceJoint:()=>pu,addRevoluteJoint:()=>fu,addTransition:()=>Cm,albumTrack:()=>bm,all:()=>wd,analyzePlaytest:()=>pd,applyChannel:()=>In,applyImpulse:()=>cu,applyReverb:()=>xo,applyTransform:()=>bt,asciiEntities:()=>Gl,assertAudio:()=>sd,assertDeterministic:()=>Pm,assertRamp:()=>ed,assertSnapshotStable:()=>Dm,assertSolvable:()=>Rm,astar:()=>ba,astarGrid:()=>Pd,audio:()=>je,autotile4:()=>Bl,autotileToCommands:()=>_l,availableUpgrades:()=>Wd,bandBalance:()=>Co,bfs:()=>fa,blendIssues:()=>Cl,blobPath:()=>Zu,bodyAABB:()=>An,bodyContains:()=>Ji,bootDom:()=>bd,buildSkeleton:()=>Dn,cadenceResolves:()=>Gc,cameraIssues:()=>ta,canvasGradient:()=>Qr,cellFloat:()=>ut,cellHash:()=>fs,cellInt:()=>lc,changeFrames:()=>Jm,checkDeterministic:()=>Js,chordChanges:()=>zc,chordNotes:()=>Ce,clamp:()=>Q,clientToDesign:()=>ot,clipEvents:()=>Er,clipFinished:()=>Tn,clipIssues:()=>Sl,clipTime:()=>Ae,collide:()=>Xr,commandsToSVGInner:()=>st,composeCampaign:()=>Ud,composeTransform:()=>Ne,connectWebSocket:()=>eh,connectedComponents:()=>Rd,contourToCommands:()=>Ol,contrastRatio:()=>Lt,createPlanBot:()=>Fm,createPlatformerState:()=>Yl,createRigidWorld:()=>iu,createStereo:()=>uo,createWorld:()=>Te,crestFactorDb:()=>So,cullSegments:()=>Or,dashJumpDistance:()=>eu,datan:()=>di,datan2:()=>Le,dbfs:()=>Un,dcos:()=>j,decode2bit:()=>nc,decodeBits:()=>tc,decodeMessage:()=>Oe,decodeRLE:()=>rc,defaultStorage:()=>ei,defineGame:()=>ld,defineLevel:()=>_d,deg2rad:()=>cl,deserializeNode:()=>Nn,dexp:()=>Je,dexp2:()=>fe,dhypot:()=>G,diamondPoints:()=>Cn,diatonicChord:()=>Ts,diffLevels:()=>Hd,distanceGain:()=>As,dlog:()=>dr,dlog10:()=>Ft,dlog2:()=>ft,dpow:()=>Pe,drive:()=>Nm,dropShadow:()=>$u,dsin:()=>q,duckGain:()=>Jc,encodeMessage:()=>de,encodeRLE:()=>oc,encodeWav:()=>yc,estimateTempo:()=>$s,evalCurve:()=>jc,featureDistance:()=>Fs,features:()=>It,feedbackIssues:()=>Qs,fft:()=>Es,findSoftlocks:()=>Yd,firstFrame:()=>Um,fitViewport:()=>it,floodFill:()=>Yo,fluxEnvelope:()=>ko,forgivenessIssues:()=>Ks,fractalNoise:()=>io,frameActions:()=>wt,frameAxes:()=>kt,gameInputMap:()=>ud,generateCave:()=>cc,generateDungeon:()=>fc,generateLevels:()=>ii,generateLevelsReport:()=>ka,genre:()=>om,getBody:()=>ge,getJoint:()=>bu,glow:()=>Lu,graceWindowIssues:()=>Wm,gradient:()=>$l,gradientDef:()=>Bn,gridAt:()=>hs,gridFromRows:()=>Nl,gridSet:()=>Be,gridToTilemap:()=>ac,groundAt:()=>Bi,hashNoise:()=>bl,hashString:()=>br,hashValue:()=>Bt,hexToHsl:()=>Ii,hideScreen:()=>cn,hold:()=>Em,hostRoom:()=>ui,hsl:()=>Ei,hsv:()=>El,inVisionCone:()=>ou,initDirector:()=>Fd,inputDensity:()=>Km,installCapture:()=>Ao,invLerp:()=>hr,invalidCommandReason:()=>Zt,invertTransform:()=>De,isCaptureMode:()=>Fo,isGround:()=>dc,isLightCommand:()=>Fu,isMonotonic:()=>Ym,iso:()=>pl,joinRoom:()=>li,jumpAirtime:()=>zi,jumpDistance:()=>_i,jumpHeight:()=>Zl,keyMentions:()=>la,keysToActions:()=>qr,knob:()=>ad,layerGains:()=>Xc,layoutIssues:()=>Hm,layoutText:()=>cs,lerp:()=>$e,lerpDamp:()=>yl,levelFromSeed:()=>jd,levelIssues:()=>Od,levelReachable:()=>Gd,levelToTilemap:()=>ir,lightingIssues:()=>ea,lineOfSight:()=>Gi,linearGradient:()=>Eu,lintSong:()=>Oc,longestLull:()=>Qm,lookAheadIssues:()=>na,magnitudeSpectrum:()=>Et,makeGrid:()=>Rt,makeReach:()=>xl,makeTransform:()=>Ge,mapHeight:()=>ql,mapWidth:()=>Hl,marchingSquaresCases:()=>$i,marchingSquaresContours:()=>$n,mask4:()=>Br,mask8:()=>Fl,matchReport:()=>qc,measureLine:()=>Mt,measureText:()=>sc,mergePlayerFrames:()=>$t,midiToFreq:()=>Cs,midiToName:()=>Cc,missingControlHints:()=>qm,mix:()=>Pl,mixLinear:()=>xt,mixMono:()=>co,mixPose:()=>Rn,moveRect:()=>Kt,mutateColor:()=>Il,netMessage:()=>he,nextStep:()=>xd,nineSlice:()=>Ju,normalize:()=>ho,noteToMidi:()=>ce,occludersFromTilemap:()=>jl,onsetDensity:()=>Ls,openVoicing:()=>Hn,packVarints:()=>$d,panFromOffset:()=>Ws,panGains:()=>vs,parseLightRun:()=>rt,parseRich:()=>as,parseSnapshot:()=>ni,passableFromTilemap:()=>Dd,peak:()=>ws,peakAmp:()=>wo,pickEntry:()=>Xo,pitchToFreq:()=>po,pixelsToCommands:()=>ss,platformerReachable:()=>Vd,playerAction:()=>xn,playerIds:()=>Qd,playerInput:()=>Zd,pointQuery:()=>Ru,pollDirector:()=>Ad,polygonBox:()=>mu,poseKey:()=>Ht,progression:()=>ct,progressionPuzzle:()=>sr,proveCompletable:()=>Xd,proveFullCompletion:()=>Jd,pump:()=>$m,quantizeAngle:()=>Hr,race:()=>vd,rad2deg:()=>ml,radialGradient:()=>Iu,rampIssues:()=>ca,rampStats:()=>ua,rayCastRigid:()=>Du,raycastTiles:()=>Oi,reachableRegions:()=>Ra,reconstructPath:()=>Cd,recordTimeline:()=>jm,rectBlocked:()=>qe,rectContains:()=>dl,rectsOverlap:()=>hl,registerNode:()=>we,regularPolyPoints:()=>bi,regularPolygon:()=>Ku,relLuminance:()=>_e,remap:()=>ul,removeBody:()=>uu,removeJoint:()=>gu,renderAudioFilmstrip:()=>nd,renderFilmstrip:()=>td,renderSong:()=>vo,renderSound:()=>sn,renderToSVGString:()=>en,replay:()=>No,replaySession:()=>zo,resetNodeIds:()=>gr,resetZzfxWarnings:()=>im,resolveTracks:()=>En,resolveTuning:()=>fn,rigidStep:()=>Cu,rleDecode:()=>Ld,rleEncode:()=>Id,rms:()=>Dt,roomCenter:()=>ao,rootless:()=>an,runBrowser:()=>bn,runBrowserNet:()=>nh,runFeelGates:()=>Gm,runHeadless:()=>cd,runStudio:()=>sh,salienceIssues:()=>Zs,sampleClip:()=>kl,sampleGradient:()=>Wr,samplePose:()=>Mn,sampleTrack:()=>Ye,scaleMidis:()=>Vn,scalePitchClasses:()=>bo,scatter:()=>bs,scatterCells:()=>uc,scoreTrack:()=>Kc,screenRect:()=>Mm,scriptToFrames:()=>Ys,scriptedPlaythrough:()=>Lm,scrubTo:()=>cr,serializeSnapshot:()=>xa,series:()=>Xm,setOverlayHost:()=>un,setScreenObserver:()=>Zn,settings:()=>ze,shadeHex:()=>yr,shadowDef:()=>Yr,shadowQuads:()=>Gr,shapeBBox:()=>Kr,shapeBox:()=>Wo,showScreen:()=>Do,signalHash:()=>xc,sleep:()=>gd,smoothClosedPath:()=>os,smoothOpenPath:()=>ec,smoothstep:()=>pr,snapAxis:()=>Ze,softClip:()=>lo,softClipInPlace:()=>mo,solidNeighbours:()=>oo,solve:()=>mt,solveFabrik:()=>Nr,solveJoint:()=>Jr,solveTwoBoneIK:()=>$r,songBeats:()=>Ps,songDuration:()=>qn,sortCommands:()=>Ke,spatialMix:()=>Uc,specFromZzfx:()=>sm,spectralCentroid:()=>Is,splitByLightLayer:()=>nt,spring:()=>yi,springStep:()=>xi,star:()=>Qu,steer2D:()=>Am,stepPlatformer:()=>Ql,stereoDuration:()=>gc,stereoFrames:()=>bc,stereoWidth:()=>Bs,subSeed:()=>wa,telegraphIssues:()=>zm,terrainHeight:()=>so,terrainSlice:()=>mc,textBox:()=>sa,textToCommands:()=>ds,tileAt:()=>pe,tileAtPoint:()=>Vl,tileCenter:()=>va,tilemapFromAscii:()=>_r,toggleFullscreen:()=>Io,transpose:()=>Mc,typewriterCount:()=>ms,unpackVarints:()=>Nd,vadd:()=>rl,validateWorld:()=>Kd,valueNoise:()=>gs,vdist:()=>al,vdot:()=>sl,vec2:()=>nl,vlen:()=>pi,vnorm:()=>ll,voiceLead:()=>Pt,vscale:()=>il,vsub:()=>ol,wait:()=>Im,waitFor:()=>yd,wakeBody:()=>ye,wangTile:()=>Li,warnCommandOnce:()=>Ct,weatherEnvelope:()=>wi,weightedIndex:()=>Uo,weightedPick:()=>Sd,wipeStep:()=>Tm,withAlpha:()=>Dl,worldPoints:()=>ke,zcr:()=>Ds});var Wa=.6366197723675814,Ba=1.5707963267341256,za=6077100506506192e-26,_a=-.16666666666666632,Oa=.00833333333332249,Ga=-.0001984126982985795,Va=27557313707070068e-22,Ha=-25050760253406863e-24,qa=158969099521155e-24,ja=.0416666666666666,Ua=-.001388888888887411,Xa=2480158728947673e-20,Ja=-27557314351390663e-23,Ya=2087572321298175e-24,Ka=-11359647557788195e-27;function kn(t){let e=t*t;return t+t*e*(_a+e*(Oa+e*(Ga+e*(Va+e*(Ha+e*qa)))))}function Sn(t){let e=t*t;return 1-.5*e+e*e*(ja+e*(Ua+e*(Xa+e*(Ja+e*(Ya+e*Ka)))))}function mi(t){let e=Math.round(t*Wa),n=t-e*Ba-e*za;return{n:(e%4+4)%4,r:n}}function q(t){if(!Number.isFinite(t))return NaN;let{n:e,r:n}=mi(t);switch(e){case 0:return kn(n);case 1:return Sn(n);case 2:return-kn(n);default:return-Sn(n)}}function j(t){if(!Number.isFinite(t))return NaN;let{n:e,r:n}=mi(t);switch(e){case 0:return Sn(n);case 1:return-kn(n);case 2:return-Sn(n);default:return kn(n)}}var wn=[.4636476090008061,.7853981633974483,.982793723247329,1.5707963267948966],ci=[22698777452961687e-33,3061616997868383e-32,13903311031230998e-33,6123233995736766e-32],ve=[.3333333333333293,-.19999999999876483,.14285714272503466,-.11111110405462356,.09090887133436507,-.0769187620504483,.06661073137387531,-.058335701337905735,.049768779946159324,-.036531572744216916,.016285820115365782];function di(t){if(Number.isNaN(t))return NaN;if(!Number.isFinite(t))return t>0?wn[3]:-wn[3];let e=t<0||Object.is(t,-0)?-1:1,n=Math.abs(t);if(n>=1e19)return e*(wn[3]+ci[3]);let r=-1;if(n<.4375){if(n<1e-9)return t}else n<.6875?(r=0,n=(2*n-1)/(2+n)):n<1.1875?(r=1,n=(n-1)/(n+1)):n<2.4375?(r=2,n=(n-1.5)/(1+1.5*n)):(r=3,n=-1/n);let o=n*n,i=o*o,s=o*(ve[0]+i*(ve[2]+i*(ve[4]+i*(ve[6]+i*(ve[8]+i*ve[10]))))),a=i*(ve[1]+i*(ve[3]+i*(ve[5]+i*(ve[7]+i*ve[9]))));if(r<0)return e*(n-n*(s+a));let l=wn[r]-(n*(s+a)-ci[r]-n);return e*l}var Re=3.141592653589793;function Le(t,e){if(Number.isNaN(e)||Number.isNaN(t))return NaN;if(t===0&&e===0)return Object.is(e,-0)?Object.is(t,-0)?-Re:Re:Object.is(t,-0)?-0:0;if(e===0||!Number.isFinite(t)&&Number.isFinite(e))return t>0?Re/2:-Re/2;if(!Number.isFinite(e)){if(!Number.isFinite(t)){let r=e>0?Re/4:3*Re/4;return t>0?r:-r}return e>0?t<0||Object.is(t,-0)?-0:0:t<0||Object.is(t,-0)?-Re:Re}let n=di(t/e);return e>0?n:t<0||Object.is(t,-0)?n-Re:n+Re}var Qa=.6931471805599453;function fe(t){if(Number.isNaN(t))return NaN;if(t>=1024)return 1/0;if(t<=-1075)return 0;let e=Math.round(t),n=(t-e)*Qa,r=1,o=1;for(let i=1;i<=13;i++)r=r*n/i,o+=r;return o*2**e}function Je(t){return fe(t*hi)}function G(t,e){return Math.sqrt(t*t+e*e)}var Xe=new DataView(new ArrayBuffer(8)),Za=.6931471803691238,el=19082149292705877e-26;function dr(t){if(Number.isNaN(t)||t<0)return NaN;if(t===0)return-1/0;if(!Number.isFinite(t))return 1/0;Xe.setFloat64(0,t);let e=(Xe.getUint32(0)>>>20&2047)-1023;e===-1023&&(Xe.setFloat64(0,t*0x40000000000000),e=(Xe.getUint32(0)>>>20&2047)-1023-54),Xe.setUint32(0,Xe.getUint32(0)&1048575|1023<<20);let n=Xe.getFloat64(0);n>1.4142135623730951&&(n*=.5,e+=1);let r=(n-1)/(n+1),o=r*r,i=1+o*(.3333333333333333+o*(.2+o*(.14285714285714285+o*(.1111111111111111+o*(.09090909090909091+o*(.07692307692307693+o*(.06666666666666667+o*(.058823529411764705+o*.05263157894736842))))))));return e*Za+(2*r*i+e*el)}var tl=.4342944819032518,hi=1.4426950408889634,Ft=t=>dr(t)*tl,ft=t=>dr(t)*hi;function Pe(t,e){if(Number.isNaN(t)||Number.isNaN(e))return NaN;if(e===0)return 1;if(e===1)return t;if(Number.isInteger(e)&&Math.abs(e)<=1024){let n=Math.abs(e),r=t,o=1;for(;n>0;)n&1&&(o*=r),n>>=1,n>0&&(r*=r);return e<0?1/o:o}return t>0?fe(e*ft(t)):t===0?e>0?0:1/0:NaN}var nl=(t=0,e=0)=>({x:t,y:e}),rl=(t,e)=>({x:t.x+e.x,y:t.y+e.y}),ol=(t,e)=>({x:t.x-e.x,y:t.y-e.y}),il=(t,e)=>({x:t.x*e,y:t.y*e}),sl=(t,e)=>t.x*e.x+t.y*e.y,pi=t=>G(t.x,t.y),al=(t,e)=>G(t.x-e.x,t.y-e.y);function ll(t){let e=pi(t);return e===0?{x:0,y:0}:{x:t.x/e,y:t.y/e}}var Q=(t,e,n)=>t<e?e:t>n?n:t,$e=(t,e,n)=>t+(e-t)*n,hr=(t,e,n)=>t===e?0:(n-t)/(e-t),ul=(t,e,n,r,o)=>$e(r,o,hr(e,n,t)),pr=(t,e,n)=>{let r=Q(t===e?n<t?0:1:hr(t,e,n),0,1);return r*r*(3-2*r)},Z=Math.PI*2,cl=t=>t*Math.PI/180,ml=t=>t*180/Math.PI;function dl(t,e){return e.x>=t.x&&e.x<=t.x+t.w&&e.y>=t.y&&e.y<=t.y+t.h}function hl(t,e){return t.x<e.x+e.w&&t.x+t.w>e.x&&t.y<e.y+e.h&&t.y+t.h>e.y}var oe={a:1,b:0,c:0,d:1,e:0,f:0};function Ne(t,e){return{a:t.a*e.a+t.c*e.b,b:t.b*e.a+t.d*e.b,c:t.a*e.c+t.c*e.d,d:t.b*e.c+t.d*e.d,e:t.a*e.e+t.c*e.f+t.e,f:t.b*e.e+t.d*e.f+t.f}}function Ge(t,e,n){let r=j(e),o=q(e);return{a:r*n.x,b:o*n.x,c:-o*n.y,d:r*n.y,e:t.x,f:t.y}}function bt(t,e){return{x:t.a*e.x+t.c*e.y+t.e,y:t.b*e.x+t.d*e.y+t.f}}function De(t){let e=t.a*t.d-t.b*t.c;if(e===0)return{...oe};let n=1/e;return{a:t.d*n,b:-t.b*n,c:-t.c*n,d:t.a*n,e:(t.c*t.f-t.d*t.e)*n,f:(t.b*t.e-t.a*t.f)*n}}function pl(t){let{tileW:e,tileH:n}=t,r=t.origin?{x:t.origin.x,y:t.origin.y}:{x:0,y:0},o=t.elevStep??n,i=e/2,s=n/2;return{tileW:e,tileH:n,origin:r,elevStep:o,toScreen(a,l,u=0){return{x:r.x+(a-l)*i,y:r.y+(a+l)*s-u*o}},toGrid(a,l){let u=(a-r.x)/i,c=(l-r.y)/s;return{x:(u+c)/2,y:(c-u)/2}}}}function fl(t){let e=t>>>0;return()=>{e=e+2654435769>>>0;let n=e;return n=Math.imul(n^n>>>16,569420461),n=Math.imul(n^n>>>15,1935289751),(n^n>>>15)>>>0}}var ue=class t{s0;s1;s2;s3;constructor(e=0){if(typeof e=="number"){let n=fl(e===0?305441741:e);this.s0=n(),this.s1=n(),this.s2=n(),this.s3=n()}else[this.s0,this.s1,this.s2,this.s3]=e.s}next(){let e=Math.imul(this.rotl(Math.imul(this.s1,5),7),9)>>>0,n=this.s1<<9>>>0;return this.s2^=this.s0,this.s3^=this.s1,this.s1^=this.s2,this.s0^=this.s3,this.s2=(this.s2^n)>>>0,this.s3=this.rotl(this.s3,11),e>>>0}rotl(e,n){return(e<<n|e>>>32-n)>>>0}float(){return this.next()/4294967296}range(e,n){return e+this.float()*(n-e)}int(e){return Math.floor(this.float()*e)}intRange(e,n){return e+this.int(n-e+1)}chance(e){return this.float()<e}pick(e){return e[this.int(e.length)]}shuffle(e){for(let n=e.length-1;n>0;n--){let r=this.int(n+1);[e[n],e[r]]=[e[r],e[n]]}return e}split(e=0){let n=(this.s0^Math.imul(e+1,2654435769))>>>0,r=new t(n^this.s3);return this.next(),r}getState(){return{s:[this.s0,this.s1,this.s2,this.s3]}}setState(e){[this.s0,this.s1,this.s2,this.s3]=e.s}},fr=new DataView(new ArrayBuffer(8));function bl(...t){let e=2654435769;for(let n of t)fr.setFloat64(0,n),e=Math.imul(e^fr.getUint32(0),2246822507)>>>0,e=(e^e>>>13)>>>0,e=Math.imul(e^fr.getUint32(4),3266489909)>>>0,e=(e^e>>>16)>>>0;return e=Math.imul(e^e>>>16,2246822507)>>>0,e=Math.imul(e^e>>>13,3266489909)>>>0,e=(e^e>>>16)>>>0,e/4294967296}function br(t){let e=2166136261;for(let n=0;n<t.length;n++)e^=t.charCodeAt(n),e=Math.imul(e,16777619);return e>>>0}var At=class{stepMs;dt;maxFrameMs;accumulator=0;_frame=0;_simTimeMs=0;constructor(e={}){let n=e.hz??60;this.stepMs=1e3/n,this.dt=1/n,this.maxFrameMs=e.maxFrameMs??250}advance(e){this.accumulator+=Math.min(e,this.maxFrameMs);let n=0;for(;this.accumulator>=this.stepMs;)this.accumulator-=this.stepMs,n++;return n}tick(){this._frame++,this._simTimeMs+=this.stepMs}get alpha(){return this.accumulator/this.stepMs}get frame(){return this._frame}get simTimeMs(){return this._simTimeMs}get simTimeSec(){return this._simTimeMs/1e3}getState(){return{accumulator:this.accumulator,frame:this._frame,simTimeMs:this._simTimeMs}}setState(e){this.accumulator=e.accumulator,this._frame=e.frame,this._simTimeMs=e.simTimeMs}};var gt=class{listeners=[];connect(e){return this.listeners.push(e),()=>this.disconnect(e)}once(e){let n=this.connect(r=>{n(),e(r)});return n}disconnect(e){let n=this.listeners.indexOf(e);n>=0&&this.listeners.splice(n,1)}emit(e){for(let n of this.listeners.slice())n(e)}get count(){return this.listeners.length}clear(){this.listeners.length=0}},Wt=class{signals=new Map;signalFor(e){let n=this.signals.get(e);return n||(n=new gt,this.signals.set(e,n)),n}on(e,n){return this.signalFor(e).connect(n)}once(e,n){return this.signalFor(e).once(n)}emit(e,n){this.signalFor(e).emit(n)}clear(){this.signals.clear()}};function gl(t){return Number.isNaN(t)?"NaN":t===1/0?"Inf":t===-1/0?"-Inf":t===0?"0":t.toString()}function Bt(t){let e=2166136261,n=2166136261,r=s=>{for(let a=0;a<s.length;a++){let l=s.charCodeAt(a);e=Math.imul(e^l,16777619)>>>0,n=Math.imul(n^(l<<3|l>>>5),2246822519)>>>0}},o=s=>{if(s===null)return r("n");if(s===void 0)return r("u");switch(typeof s){case"number":return r("#"+gl(s));case"boolean":return r(s?"t":"f");case"string":return r('"'+s);case"object":{if(Array.isArray(s)){r("[");for(let u of s)o(u);r("]");return}let a=s,l=Object.keys(a).filter(u=>a[u]!==void 0).sort();r("{");for(let u of l)r(u+":"),o(a[u]);r("}");return}default:r("?")}};o(t);let i=s=>s.toString(16).padStart(8,"0");return i(e)+i(n)}var fi=0;function gr(t=0){fi=t}var _=class{id;name;type="Node";pos;rotation;scale;z;visible;cosmetic=!1;pauseMode="inherit";screenSpace=!1;pivot;parent=null;children=[];world=null;onUpdate;behaviors=[];signals=new Map;_ready=!1;_freed=!1;constructor(e={}){this.id=`n${fi++}`,this.name=e.name??this.constructor.name,this.pos=e.pos?{...e.pos}:{x:0,y:0},this.rotation=e.rotation??0,this.scale=e.scale?{...e.scale}:{x:1,y:1},this.z=e.z??0,this.visible=e.visible??!0}get x(){return this.pos.x}set x(e){this.pos.x=e}get y(){return this.pos.y}set y(e){this.pos.y=e}addChild(e){return e.parent=this,this.children.push(e),this.world&&this._ready&&e.enterTree(this.world),e}removeChild(e){let n=this.children.indexOf(e);n>=0&&(this.children.splice(n,1),e.parent=null)}free(){this.world?.requestFree(this)}clearChildren(){for(let e of this.children.slice())e.exitTree(),this.removeChild(e)}find(e){if(this.name===e)return this;for(let n of this.children){let r=n.find(e);if(r)return r}return null}findOfType(e){if(this instanceof e)return this;for(let n of this.children){let r=n.findOfType(e);if(r)return r}return null}query(e,n=[]){this.type===e&&n.push(this);for(let r of this.children)r.query(e,n);return n}addBehavior(e){return this.behaviors.push(e),this._ready&&e.ready?.(this),this}signal(e){let n=this.signals.get(e);return n||(n=new gt,this.signals.set(e,n)),n}emit(e,n){this.signals.get(e)?.emit(n)}enterTree(e){if(this.world=e,!this._ready){this._ready=!0,this.onReady();for(let n of this.behaviors)n.ready?.(this)}for(let n of this.children)n.enterTree(e)}updateTree(e,n=e,r="pausable",o=!1){if(this._freed)return;let i=this.pauseMode==="inherit"?r:this.pauseMode;if(i==="always"||i==="pausable"&&!o){let a=this.world,l=i==="always"?n:e;for(let u of this.behaviors)u.update?.(this,l,a);this.onUpdate?.(this,l,a),this.onProcess(l)}for(let a of this.children.slice())a.updateTree(e,n,i,o)}exitTree(){for(let e of this.behaviors)e.exit?.(this);this.onExit();for(let e of this.children.slice())e.exitTree();this._freed=!0}get isFreed(){return this._freed}localTransform(){let e=Ge(this.pos,this.rotation,this.scale);return this.pivot?Ne(e,Ge({x:-this.pivot.x,y:-this.pivot.y},0,{x:1,y:1})):e}worldTransform(){let e=this.localTransform();return this.parent?Ne(this.parent.worldTransform(),e):e}collectDraw(e,n=oe){if(!this.visible)return;let r=Ne(this.screenSpace?oe:n,this.localTransform()),o=e.length;this.draw(e,r);for(let i of this.children)i.collectDraw(e,r);if(this.screenSpace)for(let i=o;i<e.length;i++){let s=e[i];(s.layer??0)<1&&(s.layer=1)}}draw(e,n){}onReady(){}onProcess(e){}onExit(){}serialize(){return{type:this.type,name:this.name,pos:{...this.pos},rotation:this.rotation,scale:{...this.scale},z:this.z,visible:this.visible,...this.pivot?{pivot:{...this.pivot}}:{},props:{...this.serializeProps(),...this.pauseMode!=="inherit"?{pauseMode:this.pauseMode}:{},...this.screenSpace?{screenSpace:!0}:{}},children:this.children.filter(e=>!e.cosmetic).map(e=>e.serialize())}}serializeProps(){return{}}applyProps(e){}};function Cn(t,e){return[0,-e/2,t/2,0,0,e/2,-t/2,0]}function bi(t,e,n=0){let r=[];for(let o=0;o<t;o++){let i=n-Z/4+Z*o/t;r.push(j(i)*e,q(i)*e)}return r}var zt=class extends _{type="Sprite";shape;paint;constructor(e){super(e),this.shape=e.shape,this.paint={fill:e.fill,stroke:e.stroke,strokeWidth:e.strokeWidth,opacity:e.opacity,round:e.round,gradient:e.gradient,shadow:e.shadow,lineDash:e.lineDash}}draw(e,n){let r=this.paint,o={transform:n,z:this.z,...r};switch(this.shape.kind){case"rect":{let i=this.shape.anchor==="topLeft";e.push({kind:"rect",x:i?0:-this.shape.w/2,y:i?0:-this.shape.h/2,w:this.shape.w,h:this.shape.h,r:this.shape.r,...o});break}case"circle":e.push({kind:"circle",cx:0,cy:0,radius:this.shape.radius,...o});break;case"ellipse":e.push({kind:"ellipse",cx:0,cy:0,rx:this.shape.rx,ry:this.shape.ry,...o});break;case"arc":e.push({kind:"arc",cx:0,cy:0,radius:this.shape.radius,start:this.shape.start,end:this.shape.end,sector:this.shape.sector,...o});break;case"poly":e.push({kind:"poly",points:this.shape.points,closed:this.shape.closed??!0,...o});break;case"path":e.push({kind:"path",d:this.shape.d,...o});break;case"glyph":e.push({kind:"text",text:this.shape.char,x:0,y:0,size:this.shape.size,align:"center",...o});break;case"diamond":e.push({kind:"poly",points:Cn(this.shape.w,this.shape.h),closed:!0,...o});break;case"regularPoly":e.push({kind:"poly",points:bi(this.shape.sides,this.shape.r,this.shape.rotation??0),closed:!0,...o});break}}serializeProps(){return{shape:this.shape,paint:this.paint}}applyProps(e){e.shape&&(this.shape=e.shape),e.paint&&(this.paint=e.paint)}},_t=class extends _{type="Text";text;size;font;align;weight;paint;constructor(e){super(e),this.text=e.text,this.size=e.size??24,this.font=e.font,this.align=e.align??"left",this.weight=e.weight,this.paint={fill:e.fill??"#000",stroke:e.stroke,strokeWidth:e.strokeWidth,opacity:e.opacity}}draw(e,n){e.push({kind:"text",text:this.text,x:0,y:0,size:this.size,font:this.font,align:this.align,weight:this.weight,transform:n,z:this.z,...this.paint})}serializeProps(){return{text:this.text,size:this.size,align:this.align,paint:this.paint}}applyProps(e){typeof e.text=="string"&&(this.text=e.text),typeof e.size=="number"&&(this.size=e.size),e.align&&(this.align=e.align),e.paint&&(this.paint=e.paint)}},Ot=class extends _{type="Camera2D";zoom;current;constructor(e={}){super(e),this.zoom=e.zoom??1,this.current=e.current??!0}onReady(){this.current&&(this.world.activeCamera=this)}serializeProps(){return{zoom:this.zoom,current:this.current}}applyProps(e){typeof e.zoom=="number"&&(this.zoom=e.zoom),typeof e.current=="boolean"&&(this.current=e.current)}},Gt=class extends _{type="Timer";duration;oneShot;remaining;running;constructor(e){super(e),this.duration=e.duration,this.oneShot=e.oneShot??!0,this.remaining=e.duration,this.running=e.autostart??!0}start(e){e!==void 0&&(this.duration=e),this.remaining=this.duration,this.running=!0}stop(){this.running=!1}get timeLeft(){return this.remaining}onProcess(e){this.running&&(this.remaining-=e,this.remaining<=0&&(this.emit("timeout",void 0),this.oneShot?this.running=!1:this.remaining+=this.duration))}get timeout(){return this.signal("timeout")}serializeProps(){return{duration:this.duration,oneShot:this.oneShot,remaining:this.remaining,running:this.running}}applyProps(e){typeof e.duration=="number"&&(this.duration=e.duration),typeof e.oneShot=="boolean"&&(this.oneShot=e.oneShot),typeof e.remaining=="number"&&(this.remaining=e.remaining),typeof e.running=="boolean"&&(this.running=e.running)}};function yr(t,e){let n=t.replace("#","");if(n.length===3&&(n=n[0]+n[0]+n[1]+n[1]+n[2]+n[2]),n.length!==6)return t;let r=o=>Math.round(Math.min(255,Math.max(0,parseInt(n.slice(o,o+2),16)*e))).toString(16).padStart(2,"0");return`#${r(0)}${r(2)}${r(4)}`}var xr=class extends _{type="IsoPrism";tileW;tileH;height;fill;topPaint;leftPaint;rightPaint;stroke;strokeWidth;opacity;constructor(e){super(e),this.tileW=e.tileW,this.tileH=e.tileH,this.height=e.height,this.fill=e.fill,this.topPaint=e.top,this.leftPaint=e.left,this.rightPaint=e.right,this.stroke=e.stroke,this.strokeWidth=e.strokeWidth,this.opacity=e.opacity}draw(e,n){let r=this.tileW,o=this.tileH,i=this.height,s={stroke:this.stroke,strokeWidth:this.strokeWidth,opacity:this.opacity},a=this.topPaint??{fill:this.fill},l=this.leftPaint??{fill:yr(this.fill,.65)},u=this.rightPaint??{fill:yr(this.fill,.85)},c={transform:n,z:this.z};i>0&&(e.push({kind:"poly",closed:!0,points:[-r/2,0,0,o/2,0,o/2-i,-r/2,-i],...s,...l,...c}),e.push({kind:"poly",closed:!0,points:[0,o/2,r/2,0,r/2,-i,0,o/2-i],...s,...u,...c}));let m=Cn(r,o).map((d,h)=>h%2===1?d-i:d);e.push({kind:"poly",closed:!0,points:m,...s,...a,...c})}serializeProps(){return{tileW:this.tileW,tileH:this.tileH,height:this.height,fill:this.fill}}applyProps(e){typeof e.tileW=="number"&&(this.tileW=e.tileW),typeof e.tileH=="number"&&(this.tileH=e.tileH),typeof e.height=="number"&&(this.height=e.height),typeof e.fill=="string"&&(this.fill=e.fill)}},vr=class extends _{type="DepthSort";key;depthScale;cosmetic=!0;constructor(e){super(e),this.key=e.key,this.depthScale=e.depthScale??1}collectDraw(e,n){for(let r of this.children)r.z=this.key(r)*this.depthScale;super.collectDraw(e,n)}};var wr=class extends _{type="CameraController";cosmetic=!0;target;cameraRef;deadzone;smooth;bounds;constructor(e={}){super(e),this.target=e.target??null,this.cameraRef=e.camera??null;let n=e.deadzone??0;this.deadzone=typeof n=="number"?{x:n,y:n}:{...n},this.smooth=e.smooth??.15,this.bounds=e.bounds?{...e.bounds}:null}follow(e){return this.target=e,this}host(){return this.world??null}camera(){return this.cameraRef??this.host()?.activeCamera??null}desired(e){let n=this.host(),r=this.target.worldTransform(),o=e.pos.x,i=e.pos.y,s=r.e-e.pos.x,a=r.f-e.pos.y;if(Math.abs(s)>this.deadzone.x&&(o=r.e-Math.sign(s)*this.deadzone.x),Math.abs(a)>this.deadzone.y&&(i=r.f-Math.sign(a)*this.deadzone.y),this.bounds){let l=e.zoom||1,u=n.width/2/l,c=n.height/2/l,m=this.bounds.minX+u,d=this.bounds.maxX-u,h=this.bounds.minY+c,p=this.bounds.maxY-c;o=m>d?(this.bounds.minX+this.bounds.maxX)/2:Q(o,m,d),i=h>p?(this.bounds.minY+this.bounds.maxY)/2:Q(i,h,p)}return{x:o,y:i}}snap(){let e=this.camera();if(!e||!this.target||!this.host())return;let n=this.desired(e);e.pos.x=n.x,e.pos.y=n.y}onReady(){this.snap()}onProcess(){let e=this.camera();if(!e||!this.target||!this.host())return;let n=this.desired(e),r=Q(this.smooth,0,1);e.pos.x=$e(e.pos.x,n.x,r),e.pos.y=$e(e.pos.y,n.y,r)}};var kr=class extends _{type="ParallaxLayer";cosmetic=!0;factor;constructor(e){super(e),this.factor=e.factor}sync(){let e=this.world?.activeCamera;e&&(this.pos.x=e.pos.x*(1-this.factor),this.pos.y=e.pos.y*(1-this.factor))}onReady(){this.sync()}onProcess(){this.sync()}};var Sr=class{constructor(e,n){this.parent=e;this.make=n}parent;make;items=[];used=0;begin(){this.used=0}get(){this.used===this.items.length&&this.items.push(this.parent.addChild(this.make()));let e=this.items[this.used++];return e.visible=!0,e}end(){for(let e=this.used;e<this.items.length;e++)this.items[e].visible=!1}get liveCount(){return this.used}};var yl=(t,e,n,r)=>$e(e,t,Je(-n*r)),yi=(t=0)=>({value:t,vel:0});function xi(t,e,n,r){let o=Je(-n*r),i=t.value-e,s=t.vel+n*i;return t.value=e+(i+s*r)*o,t.vel=(t.vel-s*n*r)*o,t}function xl(t=0,e=.25){let n=4/Math.max(1e-4,e),r=yi(t);return(o,i)=>xi(r,o,n,i).value}var gi=t=>t*t,Cr=t=>t*t*t,Fe={linear:t=>t,quadIn:t=>t*t,quadOut:t=>1-(1-t)*(1-t),quadInOut:t=>t<.5?2*t*t:1-gi(-2*t+2)/2,cubicIn:t=>t*t*t,cubicOut:t=>1-Cr(1-t),cubicInOut:t=>t<.5?4*t*t*t:1-Cr(-2*t+2)/2,sineIn:t=>1-j(t*Math.PI/2),sineOut:t=>q(t*Math.PI/2),sineInOut:t=>-(j(Math.PI*t)-1)/2,backOut:t=>1+2.70158*Cr(t-1)+1.70158*gi(t-1),elasticOut:t=>{let e=2*Math.PI/3;return t===0?0:t===1?1:fe(-10*t)*q((t*10-.75)*e)+1},bounceOut:t=>t<1/2.75?7.5625*t*t:t<2/2.75?7.5625*(t-=1.5/2.75)*t+.75:t<2.5/2.75?7.5625*(t-=2.25/2.75)*t+.9375:7.5625*(t-=2.625/2.75)*t+.984375},Vt=class extends _{type="AnimationPlayer";tracks=[];to(e,n,r,o,i="cubicOut",s={}){return this.tracks.push({apply:e,from:n,to:r,duration:Math.max(1e-6,o),elapsed:0,ease:typeof i=="function"?i:Fe[i]??Fe.linear,delay:s.delay??0,onDone:s.onDone}),this}get active(){return this.tracks.length>0}get finished(){return this.signal("finished")}onProcess(e){if(this.tracks.length!==0){for(let n=this.tracks.length-1;n>=0;n--){let r=this.tracks[n];if(r.delay>0){r.delay-=e;continue}r.elapsed+=e;let o=Q(r.elapsed/r.duration,0,1);r.apply(r.from+(r.to-r.from)*r.ease(o)),o>=1&&(r.onDone?.(),this.tracks.splice(n,1))}this.tracks.length===0&&this.emit("finished",void 0)}}};var Tr=class extends _{type="Particles";pool=[];rng;maxParticles;constructor(e={}){super(e),this.cosmetic=!0,this.rng=new ue(e.seed??7),this.maxParticles=e.maxParticles??512}burst(e,n,r){let o=this.rng;for(let i=0;i<e;i++){let s=r.angle!==void 0?r.angle+(o.float()-.5)*(r.spread??.6):o.float()*Z,a=r.speedMin+o.float()*(r.speedMax-r.speedMin),l={x:n.x,y:n.y,vx:j(s)*a,vy:q(s)*a,life:0,maxLife:r.lifeMin+o.float()*(r.lifeMax-r.lifeMin),size:r.sizeMin+o.float()*(r.sizeMax-r.sizeMin),color:r.colors[o.int(r.colors.length)]};this.pool.length>=this.maxParticles&&this.pool.shift(),this.pool.push(l)}this.gravity=r.gravity??0,this.drag=r.drag??0,this.shrink=r.shrink??!0}gravity=0;drag=0;shrink=!0;emitRate=0;emitAcc=0;emitStyle=null;emitOrigin={x:0,y:0};emit(e,n){if(typeof e=="string"){super.emit(e,n);return}this.emitRate=e,this.emitAcc=0;let r=n;if(r){let{at:o,...i}=r;this.emitStyle=i,this.emitOrigin=o?{x:o.x,y:o.y}:{x:0,y:0}}else this.emitStyle||(this.emitStyle=vi.burst())}stopEmit(){this.emitRate=0,this.emitAcc=0}onProcess(e){let n=Math.max(0,1-this.drag*e),r=0;for(let o of this.pool)o.life+=e,!(o.life>=o.maxLife)&&(o.vy+=this.gravity*e,o.vx*=n,o.vy*=n,o.x+=o.vx*e,o.y+=o.vy*e,this.pool[r++]=o);if(this.pool.length=r,this.emitRate>0&&this.emitStyle){this.emitAcc+=this.emitRate*e;let o=Math.floor(this.emitAcc);o>0&&(this.emitAcc-=o,this.burst(o,this.emitOrigin,this.emitStyle))}}draw(e,n){for(let r of this.pool){let o=1-r.life/r.maxLife;e.push({kind:"circle",cx:r.x,cy:r.y,radius:this.shrink?r.size*o:r.size,fill:r.color,opacity:Math.min(1,o*2),transform:n,z:this.z,transient:!0})}}get liveCount(){return this.pool.length}},vi={dust:(t=["#c8c2b6","#a09a8c"])=>({colors:t,sizeMin:2,sizeMax:4,speedMin:30,speedMax:90,lifeMin:.2,lifeMax:.45,gravity:300,drag:3,shrink:!0}),burst:(t=["#ffd75e","#ff9d47","#fff2c9"])=>({colors:t,sizeMin:2,sizeMax:5,speedMin:120,speedMax:320,lifeMin:.25,lifeMax:.6,drag:4,shrink:!0}),hit:(t=["#ff5e5e","#ffd0d0"])=>({colors:t,sizeMin:2,sizeMax:4,speedMin:160,speedMax:380,lifeMin:.15,lifeMax:.35,drag:6,shrink:!0}),sparkle:(t=["#9ef7ff","#e8fdff","#4ed8e8"])=>({colors:t,sizeMin:1.5,sizeMax:3.5,speedMin:20,speedMax:70,lifeMin:.4,lifeMax:.9,gravity:-40,drag:2,shrink:!0})};function wi(t,e){if(e.length===0)return 1;if(t<=e[0].time)return e[0].intensity;for(let n=1;n<e.length;n++)if(t<=e[n].time){let r=e[n-1],o=e[n];return r.intensity+(o.intensity-r.intensity)*pr(r.time,o.time,t)}return e[e.length-1].intensity}var Mr=class extends _{type="AmbientField";rng;field=[];time=0;style;width;height;envelope;constructor(e){super(e),this.cosmetic=!0,this.rng=new ue(e.seed??11),this.width=e.width,this.height=e.height,this.style=e.style,this.envelope=e.envelope;let n=e.count??120,r=this.style;for(let o=0;o<n;o++)this.field.push({x:this.rng.float()*this.width,y:this.rng.float()*this.height,size:r.sizeMin+this.rng.float()*(r.sizeMax-r.sizeMin),color:r.colors[this.rng.int(r.colors.length)],phase:this.rng.float()*Z,depth:.5+this.rng.float()*.5})}intensity(){return this.envelope?wi(this.time,this.envelope):1}onProcess(e){this.time+=e;let n=this.style,r=n.windX??0,o=this.width,i=this.height;for(let s of this.field)s.y+=n.fallY*s.depth*e,s.x+=r*e,s.y>i?s.y-=i:s.y<0&&(s.y+=i),s.x>o?s.x-=o:s.x<0&&(s.x+=o)}draw(e,n){let r=this.style,o=this.intensity();if(o<=0)return;let i=Math.round(this.field.length*o),s=r.swayAmp??0,a=r.swayFreq??0;for(let l=0;l<i;l++){let u=this.field[l],c=s!==0?q(this.time*a*Z+u.phase)*s:0,m=u.x+c;if(r.streak){let d=r.streakLen??r.fallY*.03;e.push({kind:"poly",points:[m,u.y,m,u.y+d],closed:!1,stroke:u.color,strokeWidth:u.size,opacity:o,transform:n,z:this.z,transient:!0})}else e.push({kind:"circle",cx:m,cy:u.y,radius:u.size,fill:u.color,opacity:o,transform:n,z:this.z,transient:!0})}}get liveCount(){return this.field.length}},vl={snow:(t=["#ffffff","#e8f0f8","#cdd9e6"])=>({colors:t,sizeMin:1.5,sizeMax:3.5,windX:8,fallY:42,swayAmp:14,swayFreq:.25}),rain:(t=["#9fb4c8","#c3d2e0"])=>({colors:t,sizeMin:1,sizeMax:1.8,windX:-40,fallY:620,streak:!0,streakLen:16}),ash:(t=["#6b6b6b","#8a8580","#3d3a36"])=>({colors:t,sizeMin:1,sizeMax:2.5,windX:14,fallY:26,swayAmp:20,swayFreq:.18})},Rr=class extends _{type="Shaker";rng;trauma=0;amplitude;decay;constructor(e={}){super(e),this.cosmetic=!0,this.rng=new ue(e.seed??99),this.amplitude=e.amplitude??14,this.decay=e.decay??2.6}addTrauma(e){this.trauma=Math.min(1,this.trauma+e)}onProcess(e){this.trauma=Math.max(0,this.trauma-this.decay*e);let n=this.trauma*this.trauma*this.amplitude;this.pos.x=(this.rng.float()*2-1)*n,this.pos.y=(this.rng.float()*2-1)*n}};var Pr=class extends _{type="FloatingText";pool=[];rng;maxPopups;constructor(e={}){super(e),this.cosmetic=!0,this.rng=new ue(e.seed??31),this.maxPopups=e.maxPopups??128}pop(e,n,r){let o=r.jitter??0,i={x:n.x+(this.rng.float()-.5)*o*.1,y:n.y,vx:(this.rng.float()-.5)*o,vy:-(r.rise??60),life:0,maxLife:Math.max(.05,r.life??.9),text:e,color:r.color,size:r.size??20,font:r.font,weight:r.weight,align:r.align??"center",fade:Q(r.fade??.4,0,1)};this.gravity=r.gravity??0,this.pool.length>=this.maxPopups&&this.pool.shift(),this.pool.push(i)}gravity=0;onProcess(e){let n=0;for(let r of this.pool)r.life+=e,!(r.life>=r.maxLife)&&(r.vy+=this.gravity*e,r.x+=r.vx*e,r.y+=r.vy*e,this.pool[n++]=r);this.pool.length=n}draw(e,n){for(let r of this.pool){let o=r.life/r.maxLife,i=1-r.fade,s=o<i?1:Q(1-(o-i)/Math.max(1e-4,r.fade),0,1);e.push({kind:"text",text:r.text,x:r.x,y:r.y,size:r.size,font:r.font,weight:r.weight,align:r.align,fill:r.color,opacity:s,transform:n,z:this.z,transient:!0})}}get liveCount(){return this.pool.length}},wl={damage:(t="#e14b4b")=>({color:t,size:22,weight:700,rise:70,gravity:120,life:.8,jitter:40,fade:.4}),crit:(t="#ffb020")=>({color:t,size:32,weight:800,rise:100,gravity:160,life:1,jitter:60,fade:.35}),heal:(t="#4bb06a")=>({color:t,size:20,weight:700,rise:55,gravity:40,life:1,jitter:20,fade:.5}),label:(t="#3d3323")=>({color:t,size:18,weight:600,rise:40,gravity:0,life:1.2,jitter:0,fade:.5})};var Dr=class extends _{type="VerletChain";gravity;damping;iterations;pinTail;stroke;strokeWidth;taper;tailTarget=null;segments;segmentLength;px;py;prevx;prevy;local;initialized=!1;impX=0;impY=0;constructor(e){super(e),this.cosmetic=!0,this.segments=Math.max(1,Math.floor(e.segments)),this.segmentLength=e.length/this.segments,this.gravity=e.gravity?{...e.gravity}:{x:0,y:600},this.damping=e.damping??.985,this.iterations=Math.max(1,e.iterations??3),this.pinTail=e.pinTail??!1,this.stroke=e.stroke??"#333",this.strokeWidth=e.strokeWidth??3,this.taper=e.taper??!1;let n=this.segments+1;this.px=new Float64Array(n),this.py=new Float64Array(n),this.prevx=new Float64Array(n),this.prevy=new Float64Array(n),this.local=[];for(let r=0;r<n;r++)this.local.push({x:0,y:r*this.segmentLength})}get points(){return this.local}segmentAngle(e){let n=this.local[e],r=this.local[e+1];return Le(r.y-n.y,r.x-n.x)}impulse(e){this.impX+=e.x,this.impY+=e.y}onProcess(e){let n=this.worldTransform(),r=n.e,o=n.f,i=this.segments+1,s=this.px,a=this.py,l=this.prevx,u=this.prevy;if(!this.initialized){for(let x=0;x<i;x++)s[x]=r,a[x]=o+x*this.segmentLength,l[x]=s[x],u[x]=a[x];this.initialized=!0}let c=this.pinTail&&this.tailTarget!==null,m=0,d=0;if(c){let x=this.tailTarget;m=n.a*x.x+n.c*x.y+n.e,d=n.b*x.x+n.d*x.y+n.f}let h=this.gravity.x*e*e,p=this.gravity.y*e*e,f=this.impX*e,g=this.impY*e,k=this.damping,v=i-1;for(let x=1;x<i;x++){if(c&&x===v)continue;let b=s[x],w=a[x];s[x]=b+(b-l[x])*k+h+f,a[x]=w+(w-u[x])*k+p+g,l[x]=b,u[x]=w}this.impX=0,this.impY=0;let M=this.segmentLength;for(let x=0;x<this.iterations;x++){s[0]=r,a[0]=o,c&&(s[v]=m,a[v]=d);for(let b=0;b<v;b++){let w=s[b+1]-s[b],C=a[b+1]-a[b],E=Math.sqrt(w*w+C*C);if(E===0)continue;let R=(E-M)/E,S=b===0,T=c&&b+1===v;if(S&&T)continue;let L=S?0:T?1:.5,H=T?0:S?1:.5;s[b]+=w*R*L,a[b]+=C*R*L,s[b+1]-=w*R*H,a[b+1]-=C*R*H}}s[0]=r,a[0]=o,c&&(s[v]=m,a[v]=d);let I=De(n);for(let x=0;x<i;x++){let b=this.local[x],w=s[x],C=a[x];b.x=I.a*w+I.c*C+I.e,b.y=I.b*w+I.d*C+I.f}}draw(e,n){let r=this.local.length;if(r<2)return;if(this.taper){for(let i=0;i<r-1;i++){let s=this.local[i],a=this.local[i+1],l=1-i/(r-1);e.push({kind:"poly",points:[s.x,s.y,a.x,a.y],closed:!1,stroke:this.stroke,strokeWidth:Math.max(.5,this.strokeWidth*l),round:!0,transform:n,z:this.z,transient:!0})}return}let o=[];for(let i of this.local)o.push(i.x,i.y);e.push({kind:"poly",points:o,closed:!1,stroke:this.stroke,strokeWidth:this.strokeWidth,round:!0,transform:n,z:this.z,transient:!0})}};var ki=["x","y","rotation","scaleX","scaleY","opacity"];function Ae(t,e){let n=t.duration;if(n<=0)return 0;if(t.loop==="once")return e<0?0:e>n?n:e;if(t.loop==="loop"){let i=e%n;return i<0?i+n:i}let r=2*n,o=e%r;return o<0&&(o+=r),o<=n?o:r-o}function Tn(t,e){return t.loop==="once"&&t.duration>0&&e>=t.duration}function Ye(t,e){let n=t.length;if(n===0)return 0;if(n===1||e<=t[0].t)return t[0].v;if(e>=t[n-1].t)return t[n-1].v;let r=0,o=n-1;for(;r<o;){let c=r+o>>1;t[c].t<e?r=c+1:o=c}let i=t[o],s=t[o-1],a=i.t-s.t;if(a<=0)return i.v;let l=(e-s.t)/a,u=Fe[i.ease??"linear"]??Fe.linear;return s.v+(i.v-s.v)*u(l)}function kl(t,e){let n=Ae(t,e);return t.tracks.map(r=>({target:r.target,channel:r.channel,value:Ye(r.keys,n)}))}function Er(t,e,n){let r=t.events;if(!r||r.length===0||n<=e)return[];let o=t.duration,i=[],s=(d,h,p)=>d>h&&d<=p,a=(d,h)=>{for(let p of r)s(p.t,d,h)&&i.push(p.name)};if(t.loop==="once"||o<=0){let d=e<0?0:e>o?o:e,h=n<0?0:n>o?o:n;return a(d,h),i}let l=Ae(t,e),u=Ae(t,n),c=t.loop==="pingpong"?2*o:o,m=Math.floor(n/c)-Math.floor(e/c);return t.loop==="pingpong"?(m===0&&u>=l?a(l,u):m===0?a(u,l):(a(Math.min(l,u),o),a(0,Math.max(l,u))),i):(m===0&&u>=l?a(l,u):(a(l,o),a(0,u)),i)}function Sl(t,e){let n=[];t.duration>0||n.push(`duration must be > 0 (got ${t.duration})`),t.loop!=="loop"&&t.loop!=="once"&&t.loop!=="pingpong"&&n.push(`loop must be 'loop' | 'once' | 'pingpong' (got '${String(t.loop)}')`),(!t.tracks||t.tracks.length===0)&&n.push("clip has no tracks");let r=e?new Set(e):null;return(t.tracks??[]).forEach((o,i)=>{let s=`track ${i} (${o.target}/${o.channel})`;if(ki.includes(o.channel)||n.push(`${s}: unknown channel '${o.channel}'`),r&&!r.has(o.target)&&n.push(`${s}: target '${o.target}' is not in the rig`),!o.keys||o.keys.length===0)n.push(`${s}: no keyframes`);else for(let a=0;a<o.keys.length;a++){let l=o.keys[a];(!Number.isFinite(l.t)||!Number.isFinite(l.v))&&n.push(`${s}: key ${a} has non-finite t/v`),(l.t<0||l.t>t.duration)&&n.push(`${s}: key ${a} time ${l.t} is outside [0, ${t.duration}]`),a>0&&l.t<o.keys[a-1].t&&n.push(`${s}: keys must be ascending in t (key ${a} = ${l.t} < ${o.keys[a-1].t})`),l.ease!==void 0&&!(l.ease in Fe)&&n.push(`${s}: key ${a} unknown ease '${String(l.ease)}'`)}}),(t.events??[]).forEach((o,i)=>{(!Number.isFinite(o.t)||o.t<0||o.t>t.duration)&&n.push(`event ${i} ('${o.name}') time ${o.t} is outside [0, ${t.duration}]`),o.name||n.push(`event ${i} has no name`)}),[...new Set(n)]}var Ht=(t,e)=>`${t}/${e}`;function Mn(t,e){let n=Ae(t,e*t.duration),r={};for(let o of t.tracks)r[Ht(o.target,o.channel)]=Ye(o.keys,n);return r}function Rn(t,e,n,r={}){for(let o in r)delete r[o];for(let o in t)r[o]=o in e?t[o]+(e[o]-t[o])*n:t[o];for(let o in e)o in t||(r[o]=e[o]);return r}var Ir=class{samples;constructor(e){this.samples=e.slice().sort((n,r)=>n.x-r.x)}weights(e){let n=this.samples;if(n.length===0)return[];if(n.length===1||e<=n[0].x)return[{clip:n[0].clip,weight:1}];if(e>=n[n.length-1].x)return[{clip:n[n.length-1].clip,weight:1}];let r=0;for(;r<n.length-1&&n[r+1].x<=e;)r++;let o=n[r],i=n[r+1],s=i.x-o.x,a=s<=0?0:(e-o.x)/s;return[{clip:o.clip,weight:1-a},{clip:i.clip,weight:a}]}sample(e,n){let r=this.weights(e);if(r.length===0)return{};let o=Mn(r[0].clip,n);return r.length===2&&(o=Rn(o,Mn(r[1].clip,n),r[1].weight)),o}},Lr=class{samples;constructor(e){this.samples=e.map(n=>({clip:n.clip,x:n.x,y:n.y??0}))}weights(e,n){let r=this.samples;if(r.length===0)return[];if(r.length<=3)return this.barycentric(r,e,n);let o=r.map((i,s)=>s);return o.sort((i,s)=>{let a=(r[i].x-e)**2+(r[i].y-n)**2,l=(r[s].x-e)**2+(r[s].y-n)**2;return a-l||i-s}),this.barycentric([r[o[0]],r[o[1]],r[o[2]]],e,n)}barycentric(e,n,r){if(e.length===1)return[{clip:e[0].clip,weight:1}];if(e.length===2){let[d,h]=e,p=h.x-d.x,f=h.y-d.y,g=p*p+f*f,k=g<=0?0:Q(((n-d.x)*p+(r-d.y)*f)/g,0,1);return[{clip:d.clip,weight:1-k},{clip:h.clip,weight:k}]}let[o,i,s]=e,a=(i.y-s.y)*(o.x-s.x)+(s.x-i.x)*(o.y-s.y),l,u;a===0?l=u=1/3:(l=((i.y-s.y)*(n-s.x)+(s.x-i.x)*(r-s.y))/a,u=((s.y-o.y)*(n-s.x)+(o.x-s.x)*(r-s.y))/a);let c=1-l-u;l=l<0?0:l,u=u<0?0:u,c=c<0?0:c;let m=l+u+c;return m<=0?[{clip:o.clip,weight:1}]:[{clip:o.clip,weight:l/m},{clip:i.clip,weight:u/m},{clip:s.clip,weight:c/m}]}sample(e,n,r){let o=this.weights(e,n);if(o.length===0)return{};let i={};for(let{clip:s,weight:a}of o){if(a===0)continue;let l=Mn(s,r);for(let u in l)i[u]=(i[u]??0)+l[u]*a}return i}};function Cl(t,e=1){let n=[];if(!t||t.length===0)return n.push("blend space has no samples"),n;t.forEach((o,i)=>{Number.isFinite(o.x)||n.push(`sample ${i}: x is not finite`),e===2&&!Number.isFinite(o.y??0)&&n.push(`sample ${i}: y is not finite`),o.clip||n.push(`sample ${i}: missing clip`)});let r=new Map;return t.forEach((o,i)=>{let s=e===2?`${o.x},${o.y??0}`:`${o.x}`;r.has(s)?n.push(`sample ${i} duplicates the position of sample ${r.get(s)} (${s})`):r.set(s,i)}),[...new Set(n)]}var Ve=class extends _{type="Bone2D";length;constructor(e={}){super(e),this.length=e.length??0}get tip(){return{x:this.length,y:0}}serializeProps(){return{length:this.length}}applyProps(e){typeof e.length=="number"&&(this.length=e.length)}},Pn=class{constructor(e){this.root=e;this.index(e,"")}root;byPath=new Map;index(e,n){n!==""&&this.byPath.set(n,e);for(let r of e.children){let o=n===""?r.name:`${n}/${r.name}`;this.index(r,o)}}resolve(e){return this.byPath.get(e)??null}targets(){return[...this.byPath.keys()]}bones(){let e=[];for(let n of this.byPath.values())n instanceof Ve&&e.push(n);return e}};function Dn(t){return new Pn(t)}function En(t,e){let n=[];for(let r of t.tracks){let o=e.resolve(r.target);o&&n.push({node:o,channel:r.channel,keys:r.keys,target:r.target})}return n}function In(t,e,n){switch(e){case"x":t.pos.x=n;break;case"y":t.pos.y=n;break;case"rotation":t.rotation=n;break;case"scaleX":t.scale.x=n;break;case"scaleY":t.scale.y=n;break;case"opacity":Tl(t,n);break}}function Tl(t,e){let n=t;n.paint&&(n.paint.opacity=e)}var qt=class extends _{type="ClipPlayer";rig;skeleton=null;clips=new Map;currentName=null;elapsed=0;prevName=null;prevElapsed=0;fadeDur=0;fadeT=0;poseA={};poseB={};poseMix={};constructor(e={}){super(e),this.cosmetic=!0,this.rig=e.rig??null}onReady(){this.rig||(this.rig=this.parent),this.rebind()}add(e,n){return this.clips.set(e,{def:n,tracks:this.rig?En(n,this.ensureSkeleton()):[]}),this}rebind(e){if(e&&(this.rig=e),!!this.rig){this.skeleton=Dn(this.rig);for(let[,n]of this.clips)n.tracks=En(n.def,this.skeleton)}}ensureSkeleton(){return!this.skeleton&&this.rig&&(this.skeleton=Dn(this.rig)),this.skeleton}play(e,n={}){if(!this.clips.has(e))return;let r=n.fade??0;r>0&&this.currentName&&this.currentName!==e?(this.prevName=this.currentName,this.prevElapsed=this.elapsed,this.fadeDur=r,this.fadeT=0):(this.prevName=null,this.fadeDur=0,this.fadeT=0),this.currentName=e,this.elapsed=0}stop(){this.currentName=null,this.prevName=null,this.fadeDur=0}get time(){return this.elapsed}get current(){return this.currentName}get event(){return this.signal("event")}get finished(){return this.signal("finished")}onProcess(e){let n=this.currentName;if(!n)return;let r=this.clips.get(n);if(!r)return;let o=this.elapsed;if(this.elapsed+=e,this.fadeDur>0&&this.prevName){this.fadeT+=e;let i=this.fadeT>=this.fadeDur?1:this.fadeT/this.fadeDur,s=Fe.quadInOut(i),a=this.clips.get(this.prevName);a&&this.samplePose(a,this.prevElapsed,this.poseA),this.samplePose(r,this.elapsed,this.poseB),Rn(this.poseA,this.poseB,s,this.poseMix),this.applyPose(r,this.poseMix),i>=1&&(this.prevName=null,this.fadeDur=0)}else this.applyDirect(r,this.elapsed);if(r.def.events&&r.def.events.length>0){let i=Er(r.def,o,this.elapsed);for(let s of i)this.emit("event",s)}Tn(r.def,this.elapsed)&&!Tn(r.def,o)&&this.emit("finished",n)}applyDirect(e,n){let r=Ae(e.def,n),o=e.tracks;for(let i=0;i<o.length;i++){let s=o[i];In(s.node,s.channel,Ye(s.keys,r))}}samplePose(e,n,r){for(let s in r)delete r[s];let o=Ae(e.def,n),i=e.tracks;for(let s=0;s<i.length;s++){let a=i[s];r[Ht(a.target,a.channel)]=Ye(a.keys,o)}}applyPose(e,n){let r=e.tracks;for(let o=0;o<r.length;o++){let i=r[o],s=n[Ht(i.target,i.channel)];s!==void 0&&In(i.node,i.channel,s)}}};function $r(t,e,n,r,o=1){let i=r.x-t.x,s=r.y-t.y,a=G(i,s),l=e+n,u=Math.abs(e-n),c=!0;a>l?(a=l,c=!1):a<u&&(a=u||1e-9,c=!1),a<1e-9&&(a=1e-9);let m=Le(s,i),d=Si((e*e+a*a-n*n)/(2*e*a)),h=Ci(d),p=Si((e*e+n*n-a*a)/(2*e*n)),f=Ci(p),g=m-o*h,k=g+o*(Math.PI-f);return{angle0:g,angle1:k,reachable:c}}function Si(t){return t<-1?-1:t>1?1:t}function Ci(t){return Le(Math.sqrt(1-t*t),t)}function Nr(t,e,n,r={}){let o=e.length,i=r.maxIter??16,s=r.tolerance??1e-4,a=e.reduce((m,d)=>m+d,0),l=[];for(let m=0;m<=o;m++){let d=r.initial?.[m];l.push(d?{x:d.x,y:d.y}:{x:t.x+(m===0?0:1e-6*m),y:t.y})}l[0]={x:t.x,y:t.y};let u=G(n.x-t.x,n.y-t.y);if(u>a){let m=(n.x-t.x)/(u||1),d=(n.y-t.y)/(u||1),h=t.x,p=t.y;l[0]={x:h,y:p};for(let f=0;f<o;f++)h+=m*e[f],p+=d*e[f],l[f+1]={x:h,y:p};return{joints:l,angles:Ti(l),reachable:!1,iterations:0}}let c=0;for(;c<i;c++){let m=l[o];if(G(m.x-n.x,m.y-n.y)<=s)break;l[o]={x:n.x,y:n.y};for(let d=o-1;d>=0;d--){let h=l[d],p=l[d+1],f=G(h.x-p.x,h.y-p.y)||1e-9,g=e[d]/f;l[d]={x:p.x+(h.x-p.x)*g,y:p.y+(h.y-p.y)*g}}l[0]={x:t.x,y:t.y};for(let d=0;d<o;d++){let h=l[d],p=l[d+1],f=G(h.x-p.x,h.y-p.y)||1e-9,g=e[d]/f;l[d+1]={x:h.x+(p.x-h.x)*g,y:h.y+(p.y-h.y)*g}}}return{joints:l,angles:Ti(l),reachable:!0,iterations:c}}function Ti(t){let e=[];for(let n=0;n<t.length-1;n++)e.push(Le(t[n+1].y-t[n].y,t[n+1].x-t[n].x));return e}var Fr=class extends _{type="IkTarget";bones;bendDir;maxIter;reached=!0;constructor(e={}){super(e),this.cosmetic=!0,this.bones=e.bones??[],this.bendDir=e.bendDir??1,this.maxIter=e.maxIter??16}setBones(e){this.bones=e}onProcess(e){let n=this.bones;if(n.length<1)return;let r=n[0],o=r.parent;if(!o)return;let i=this.worldTransform(),s={x:i.e,y:i.f},a=o.worldTransform(),l=De(a),u=Ml(l,s),c={x:r.pos.x,y:r.pos.y};if(n.length===2){let f=$r(c,n[0].length,n[1].length,u,this.bendDir);this.reached=f.reachable,n[0].rotation=f.angle0,n[1].rotation=f.angle1-f.angle0;return}let m=n.map(f=>f.length),d=this.currentJoints(c),h=Nr(c,m,u,{maxIter:this.maxIter,initial:d});this.reached=h.reachable;let p=0;for(let f=0;f<n.length;f++)n[f].rotation=h.angles[f]-p,p=h.angles[f]}currentJoints(e){let n=[{x:e.x,y:e.y}],r=0,o=e.x,i=e.y;for(let s of this.bones)r+=s.rotation,o+=j(r)*s.length,i+=q(r)*s.length,n.push({x:o,y:i});return n}};function Ml(t,e){return{x:t.a*e.x+t.c*e.y+t.e,y:t.b*e.x+t.d*e.y+t.f}}var Ar=class extends _{type="SkeletonDebug";rig;boneColor;pivotColor;pivotRadius;strokeWidth;constructor(e={}){super(e),this.cosmetic=!0,this.rig=e.rig??null,this.boneColor=e.boneColor??"#e0483b",this.pivotColor=e.pivotColor??"#f4d35e",this.pivotRadius=e.pivotRadius??3,this.strokeWidth=e.strokeWidth??2}onReady(){this.rig||(this.rig=this.parent)}draw(e,n){let r=this.rig;r&&this.emitFor(r,e)}emitFor(e,n){if(e instanceof Ve){let r=e.worldTransform();if(n.push({kind:"poly",points:[0,0,e.length,0],closed:!1,stroke:this.boneColor,strokeWidth:this.strokeWidth,round:!0,transform:r,z:this.z,transient:!0}),n.push({kind:"circle",cx:0,cy:0,radius:this.pivotRadius,fill:this.pivotColor,transform:r,z:this.z,transient:!0}),e.pivot){let o=Ne(r,Ge({x:e.pivot.x,y:e.pivot.y},0,{x:1,y:1}));n.push({kind:"circle",cx:0,cy:0,radius:this.pivotRadius*.6,stroke:this.pivotColor,strokeWidth:1,transform:o,z:this.z,transient:!0})}}for(let r of e.children)this.emitFor(r,n)}};var B={gofun:"#f7f1e2",washi:"#efe7d3",kinu:"#e4d8bd",line:"#d8cbac",kinako:"#b9a882",stone:"#6c6252",sumiSoft:"#494133",sumi:"#23201a",kuro:"#181820",yohaku:"#12121a",darkLine:"#2c2c36",shuDeep:"#b23a24",shu:"#d9583c",kakiDeep:"#bf6a1c",kaki:"#e79a49",koDeep:"#94741d",ko:"#e3c054",matsuDeep:"#4a7a3a",matsu:"#8bad52",asagiDeep:"#2c7a90",asagi:"#57bad2",aiDeep:"#2b4257",ai:"#5a86ad",fujiDeep:"#63548c",fuji:"#a091cf",sakuDeep:"#b0506e",saku:"#e097ac"},Ri={name:"meadow",bg:B.washi,ink:B.sumi,inkSoft:B.sumiSoft,line:B.line,accent:B.shuDeep,accent2:B.aiDeep,good:B.matsuDeep,warn:B.kakiDeep,ramp:[B.shuDeep,B.kakiDeep,B.koDeep,B.matsuDeep,B.asagiDeep,B.aiDeep,B.fujiDeep,B.sakuDeep],swatches:B},Ln={name:"dusk",bg:B.kuro,ink:B.gofun,inkSoft:B.kinako,line:B.darkLine,accent:B.shu,accent2:B.asagi,good:B.matsu,warn:B.ko,ramp:[B.shu,B.kaki,B.ko,B.matsu,B.asagi,B.ai,B.fuji,B.saku],swatches:B},Pi={name:"paper",bg:B.gofun,ink:B.sumi,inkSoft:B.stone,line:B.kinu,accent:B.sakuDeep,accent2:B.asagiDeep,good:B.matsuDeep,warn:B.kakiDeep,ramp:[B.sakuDeep,B.kakiDeep,B.koDeep,B.matsuDeep,B.asagiDeep,B.aiDeep,B.fujiDeep,B.shuDeep],swatches:B},Rl={meadow:Ri,dusk:Ln,paper:Pi};function Pl(t,e,n){let r=yt(t),o=yt(e),i=Math.round(r[0]+(o[0]-r[0])*n),s=Math.round(r[1]+(o[1]-r[1])*n),a=Math.round(r[2]+(o[2]-r[2])*n);return jt(i,s,a)}function Dl(t,e){let[n,r,o]=yt(t);return`rgba(${n}, ${r}, ${o}, ${e})`}function yt(t){let e=t.replace("#","");e.length===3&&(e=e.split("").map(r=>r+r).join(""));let n=parseInt(e,16);return[n>>16&255,n>>8&255,n&255]}function jt(t,e,n){return"#"+[t,e,n].map(r=>Math.max(0,Math.min(255,Math.round(r))).toString(16).padStart(2,"0")).join("")}var Di=t=>(t%360+360)%360,Ut=t=>t<0?0:t>1?1:t;function Ei(t,e,n){if(t=Di(t)/360,e=Ut(e),n=Ut(n),e===0){let s=n*255;return jt(s,s,s)}let r=n<.5?n*(1+e):n+e-n*e,o=2*n-r,i=s=>(s=s<0?s+1:s>1?s-1:s,s<1/6?o+(r-o)*6*s:s<1/2?r:s<2/3?o+(r-o)*(2/3-s)*6:o);return jt(i(t+1/3)*255,i(t)*255,i(t-1/3)*255)}function El(t,e,n){t=Di(t)/60,e=Ut(e),n=Ut(n);let r=n*e,o=r*(1-Math.abs(t%2-1)),i=n-r,s=0,a=0,l=0;return t<1?[s,a,l]=[r,o,0]:t<2?[s,a,l]=[o,r,0]:t<3?[s,a,l]=[0,r,o]:t<4?[s,a,l]=[0,o,r]:t<5?[s,a,l]=[o,0,r]:[s,a,l]=[r,0,o],jt((s+i)*255,(a+i)*255,(l+i)*255)}function Ii(t){let[e,n,r]=yt(t),o=e/255,i=n/255,s=r/255,a=Math.max(o,i,s),l=Math.min(o,i,s),u=(a+l)/2,c=a-l;if(c===0)return{h:0,s:0,l:u};let m=u>.5?c/(2-a-l):c/(a+l),d;return a===o?d=(i-s)/c+(i<s?6:0):a===i?d=(s-o)/c+2:d=(o-i)/c+4,{h:d*60,s:m,l:u}}function Il(t,e,n={}){let r=Ii(e),o=n.hue??0,i=n.sat??0,s=n.light??0;return Ei(r.h+t.range(-o,o),r.s+t.range(-i,i),r.l+t.range(-s,s))}var Mi=t=>t<=.04045?t/12.92:Pe((t+.055)/1.055,2.4),Ll=t=>t<=.0031308?t*12.92:1.055*Pe(t,1/2.4)-.055;function xt(t,e,n){let r=yt(t),o=yt(e),i=s=>{let a=Mi(r[s]/255),l=Mi(o[s]/255);return Ll(a+(l-a)*n)*255};return jt(i(0),i(1),i(2))}function Wr(t,e){if(t.length===0)return"#000000";if(t.length===1)return t[0];let r=Ut(e)*(t.length-1),o=Math.min(t.length-2,Math.floor(r));return xt(t[o],t[o+1],r-o)}function $l(t,e){return e<=0?[]:e===1?[Wr(t,0)]:Array.from({length:e},(n,r)=>Wr(t,r/(e-1)))}var Tp=0,He=.5,Mp=1;function Ke(t){return t.map((e,n)=>[e,n]).sort((e,n)=>(e[0].layer??0)-(n[0].layer??0)||e[0].z-n[0].z||e[1]-n[1]).map(([e])=>e)}function Nl(t,e="#"){return t.map(n=>[...n].map(r=>e.includes(r)))}function We(t,e,n){return n>=0&&n<t.length&&e>=0&&e<t[n].length&&t[n][e]}var ne={N:1,E:2,S:4,W:8};function Br(t,e,n){return(We(t,e,n-1)?ne.N:0)|(We(t,e+1,n)?ne.E:0)|(We(t,e,n+1)?ne.S:0)|(We(t,e-1,n)?ne.W:0)}function Fl(t,e,n){let r=0,o=[[0,-1],[1,-1],[1,0],[1,1],[0,1],[-1,1],[-1,0],[-1,-1]];for(let i=0;i<8;i++)We(t,e+o[i][0],n+o[i][1])&&(r|=1<<i);return r}var Qe={Isolated:0,Cap:1,Straight:2,Bend:3,Tee:4,Cross:5};function Al(t){let e=0;return t&ne.N&&(e|=ne.E),t&ne.E&&(e|=ne.S),t&ne.S&&(e|=ne.W),t&ne.W&&(e|=ne.N),e}var Wl=(()=>{let t=[[Qe.Isolated,0],[Qe.Cap,ne.N],[Qe.Straight,ne.N|ne.S],[Qe.Bend,ne.N|ne.E],[Qe.Tee,ne.N|ne.E|ne.S],[Qe.Cross,15]],e=new Array(16);for(let[n,r]of t){let o=r;for(let i=0;i<4;i++)e[o]===void 0&&(e[o]={mask:o,frame:n,rotation:i}),o=Al(o)}return e})();function Li(t){return Wl[t&15]}function Bl(t){return t.map((e,n)=>e.map((r,o)=>r?Li(Br(t,o,n)):null))}function $i(t){let e=t.length,n=e?t[0].length:0,r=[];for(let o=0;o<e-1;o++){let i=[];for(let s=0;s<n-1;s++)i.push((We(t,s,o)?1:0)|(We(t,s+1,o)?2:0)|(We(t,s+1,o+1)?4:0)|(We(t,s,o+1)?8:0));r.push(i)}return r}var zl=[[],[["L","T"]],[["T","R"]],[["L","R"]],[["R","B"]],[["L","T"],["R","B"]],[["T","B"]],[["L","B"]],[["B","L"]],[["T","B"]],[["T","R"],["B","L"]],[["R","B"]],[["L","R"]],[["T","R"]],[["L","T"]],[]];function $n(t,e={}){let n=e.cell??1,r=e.x??0,o=e.y??0,i=$i(t),s=[],a=(l,u,c)=>{switch(l){case"T":return{x:u+n/2,y:c};case"R":return{x:u+n,y:c+n/2};case"B":return{x:u+n/2,y:c+n};case"L":return{x:u,y:c+n/2}}};for(let l=0;l<i.length;l++)for(let u=0;u<i[l].length;u++){let c=r+u*n,m=o+l*n;for(let[d,h]of zl[i[l][u]])s.push({a:a(d,c,m),b:a(h,c,m)})}return s}function _l(t,e={}){let n=e.tile??8,r=e.x??0,o=e.y??0,i=e.z??0,s=e.transform??oe,a=e.fill??"#888",l=e.edge,u=e.edgeWidth??Math.max(1,n/8),c=[];for(let m=0;m<t.length;m++)for(let d=0;d<t[m].length;d++){if(!t[m][d])continue;let h=r+d*n,p=o+m*n;if(c.push({kind:"rect",x:h,y:p,w:n,h:n,transform:s,z:i,fill:a}),!l)continue;let f=Br(t,d,m),g=k=>c.push({kind:"poly",points:k,closed:!1,transform:s,z:i+1,stroke:l,strokeWidth:u});f&ne.N||g([h,p,h+n,p]),f&ne.E||g([h+n,p,h+n,p+n]),f&ne.S||g([h,p+n,h+n,p+n]),f&ne.W||g([h,p,h,p+n])}return c}function Ol(t,e={}){let n=e.tile??8,r=e.transform??oe,o=e.z??0,i=e.edge??e.fill??"#333",s=e.edgeWidth??Math.max(1,n/8);return $n(t,{cell:n,x:e.x??0,y:e.y??0}).map(l=>({kind:"poly",points:[l.a.x,l.a.y,l.b.x,l.b.y],closed:!1,transform:r,z:o,stroke:i,strokeWidth:s,round:!0}))}var U={EMPTY:0,SOLID:1,ONEWAY:2,HAZARD:3},zr={"#":U.SOLID,"-":U.ONEWAY,"^":U.HAZARD};function _r(t,e=32,n=zr){let r=t.length,o=Math.max(...t.map(s=>s.length)),i=new Array(o*r).fill(U.EMPTY);return t.forEach((s,a)=>{for(let l=0;l<s.length;l++)i[a*o+l]=n[s[l]]??U.EMPTY}),{cols:o,rows:r,tileSize:e,tiles:i}}function Gl(t,e=32,n=zr){let r=[];return t.forEach((o,i)=>{for(let s=0;s<o.length;s++){let a=o[s];a===" "||a==="."||n[a]!==void 0||r.push({char:a,tx:s,ty:i,x:(s+.5)*e,y:(i+.5)*e})}}),r}function pe(t,e,n){return e<0||n<0||e>=t.cols||n>=t.rows?U.SOLID:t.tiles[n*t.cols+e]}function Vl(t,e,n){return pe(t,Math.floor(e/t.tileSize),Math.floor(n/t.tileSize))}var Hl=t=>t.cols*t.tileSize,ql=t=>t.rows*t.tileSize;function jl(t){let e=[];for(let n=0;n<t.rows;n++){let r=[];for(let o=0;o<t.cols;o++)r.push(pe(t,o,n)===U.SOLID);e.push(r)}return $n(e,{cell:t.tileSize})}function Or(t,e,n){let r=[],o=e*e;for(let i of n){let s=i.a.x-t.x,a=i.a.y-t.y,l=i.b.x-t.x,u=i.b.y-t.y,c=s*s+a*a,m=l*l+u*u;(c<=o||m<=o||Ul(t,i)<=o)&&r.push(i)}return r}function Ul(t,e){let n=e.b.x-e.a.x,r=e.b.y-e.a.y,o=n*n+r*r;if(o===0){let c=t.x-e.a.x,m=t.y-e.a.y;return c*c+m*m}let i=((t.x-e.a.x)*n+(t.y-e.a.y)*r)/o;i=i<0?0:i>1?1:i;let s=e.a.x+n*i,a=e.a.y+r*i,l=t.x-s,u=t.y-a;return l*l+u*u}function Gr(t,e,n){let r=2*e,o=[];for(let i of n){let s=i.a.x,a=i.a.y,l=i.b.x,u=i.b.y,c=s-t.x,m=a-t.y,d=l-t.x,h=u-t.y,p=G(c,m),f=G(d,h);if(p===0||f===0)continue;let g=s+c/p*r,k=a+m/p*r,v=l+d/f*r,M=u+h/f*r;o.push([s,a,l,u,v,M,g,k])}return o}var vt=class extends _{type="PointLight";radius;color;intensity;falloff;flicker;litIntensity;rng;phase=0;constructor(e={}){super(e),this.cosmetic=!0,this.radius=e.radius??160,this.color=e.color??"#ffe6b0",this.intensity=e.intensity??1,this.falloff=e.falloff??1,this.flicker=e.flicker??{amount:0,speed:0},this.litIntensity=this.intensity,this.rng=new ue(e.seed??43)}onProcess(e){if(this.flicker.amount<=0){this.litIntensity=this.intensity;return}this.phase+=e*this.flicker.speed;let r=1+(q(this.phase)*.5+(this.rng.float()-.5))*this.flicker.amount;this.litIntensity=Math.max(0,this.intensity*r)}serializeProps(){return{}}},Xt=class extends _{type="LightLayer";ambient;softShadows;width;height;occluders=[];constructor(e={}){super(e),this.cosmetic=!0,this.ambient={color:e.ambient?.color??Ln.bg,level:e.ambient?.level??0},this.softShadows=e.softShadows??!1,this.width=e.width??1280,this.height=e.height??720}setOccluders(e){this.occluders=e}draw(e,n){let r=this.ambient.level>=1?"#ffffff":xt(this.ambient.color,"#ffffff",Ni(this.ambient.level)),o={kind:"rect",x:0,y:0,w:this.width,h:this.height,fill:r,blend:"multiply",transform:oe,z:0,layer:.5};e.push(o);for(let i of this.children){if(!(i instanceof vt)||!i.visible)continue;let s=i.localTransform(),a=s.e,l=s.f,u=i.radius,c=Math.max(0,Math.min(1,i.litIntensity)),m=i.color,d=xt("#000000",m,c),h=xt("#000000",m,c*.5),p="#000000",f=Ni(.6/Math.max(.01,i.falloff)),g={kind:"circle",cx:a,cy:l,radius:u,gradient:{type:"radial",cx:.5,cy:.5,r:.5,stops:[{offset:0,color:d},{offset:f,color:h},{offset:1,color:p}]},blend:"screen",transform:n,z:0,layer:.5};if(e.push(g),this.occluders.length){let k=Or({x:a,y:l},u,this.occluders),v=Gr({x:a,y:l},u,k);for(let M of v)e.push(Fi(M,r,n,1)),this.softShadows&&e.push(Fi(Xl(M),r,n,.5))}}}},Ni=t=>t<0?0:t>1?1:t;function Fi(t,e,n,r){let o={kind:"poly",points:t,closed:!0,fill:e,blend:"multiply",transform:n,z:0,layer:.5};return r!==1&&(o.opacity=r),o}function Xl(t){let e=(t[0]+t[2])/2,n=(t[1]+t[3])/2,r=(l,u)=>{let c=l-e,m=u-n,d=G(c,m);if(d===0)return[l,u];let h=-m/d,p=c/d,f=d*.08;return[l+h*f,u+p*f]},[o,i]=r(t[6],t[7]),[s,a]=r(t[4],t[5]);return[t[0],t[1],t[2],t[3],s,a,o,i]}var Ai=new Map;function we(t,e){Ai.set(t,e)}we("Node",()=>new _);we("Sprite",()=>new zt({shape:{kind:"rect",w:1,h:1}}));we("Text",()=>new _t({text:""}));we("Camera2D",()=>new Ot);we("Timer",()=>new Gt({duration:1}));we("AnimationPlayer",()=>new Vt);we("Bone2D",()=>new Ve);we("ClipPlayer",()=>new qt);we("PointLight",()=>new vt);we("LightLayer",()=>new Xt);function Nn(t){let e=Ai.get(t.type);if(!e)throw new Error(`hayao: unknown node type "${t.type}" (register it first)`);let n=e();n.name=t.name,n.pos={...t.pos},n.rotation=t.rotation,n.scale={...t.scale},n.z=t.z,n.visible=t.visible,t.pivot&&(n.pivot={...t.pivot}),(t.props.pauseMode==="always"||t.props.pauseMode==="stopped")&&(n.pauseMode=t.props.pauseMode),t.props.screenSpace===!0&&(n.screenSpace=!0),n.applyProps(t.props);for(let r of t.children)n.addChild(Nn(r));return n}var Jt=class{down=new Set;prev=new Set;axes=new Map;logged=new Map;declared=null;warned=new Set;declareActions(e){this.declared??=new Set;for(let n of e)this.declared.add(n)}checkDeclared(e){this.declared===null||this.declared.has(e)||this.warned.has(e)||(this.warned.add(e),console.warn(`hayao: input action "${e}" is not declared by any input source \u2014 declared actions: ${[...this.declared].sort().join(", ")||"(none)"}`))}beginFrame(e,n){if(this.prev=new Set(this.down),this.down=new Set(e),this.declared!==null)for(let r of this.down)this.declared.add(r);if(this.logged.clear(),n)for(let r in n)this.logged.set(r,n[r]),this.axes.set(r,n[r])}isDown(e){return this.checkDeclared(e),this.down.has(e)}justPressed(e){return this.checkDeclared(e),this.down.has(e)&&!this.prev.has(e)}justReleased(e){return this.checkDeclared(e),!this.down.has(e)&&this.prev.has(e)}axis(e){return this.axes.get(e)??0}snapshot(){return[...this.down].sort()}getState(){let e={down:[...this.down].sort(),prev:[...this.prev].sort()};return this.logged.size>0&&(e.axes=[...this.logged].sort((n,r)=>n[0]<r[0]?-1:n[0]>r[0]?1:0)),e}setState(e){if(this.down=new Set(e.down),this.prev=new Set(e.prev),this.logged.clear(),e.axes)for(let[n,r]of e.axes)this.logged.set(n,r),this.axes.set(n,r)}};function Ze(t,e,n=-1,r=1){if(e<2||r===n)return t;let o=Math.min(1,Math.max(0,(t-n)/(r-n))),i=Math.round(o*(e-1));return n+i/(e-1)*(r-n)}function Hr(t,e){let n=Math.PI*2/e;return Math.round(t/n)*n}function qr(t,e){let n=[];for(let r in t)t[r].some(o=>e.has(o))&&n.push(r);return n.sort()}var Vr=class{frames=[];axes=[];anyAxes=!1;record(e,n){this.frames.push(e.slice().sort()),n&&Object.keys(n).length>0?(this.axes.push({...n}),this.anyAxes=!0):this.axes.push(void 0)}get length(){return this.frames.length}toLog(){let e={frames:this.frames.map(n=>n.slice())};return this.anyAxes&&(e.axes=this.axes.map(n=>n?{...n}:void 0)),e}};function wt(t,e){return t.frames[e]??[]}function kt(t,e){return t.axes?.[e]}var Fn={up:["ArrowUp","KeyW"],down:["ArrowDown","KeyS"],left:["ArrowLeft","KeyA"],right:["ArrowRight","KeyD"],confirm:["Enter","Space"],cancel:["Escape","Backspace"],action:["KeyZ","KeyJ"],action2:["KeyX","KeyK"],undo:["KeyU"],restart:["KeyR"]};var et=class{keysDown=new Set;pressed=new Set;held=new Set;map;target;onDown;onUp;onBlur;constructor(e,n=document){this.map=e,this.target=n,this.onDown=r=>{this.keysDown.add(r.code),(r.code.startsWith("Arrow")||r.code==="Space")&&r.preventDefault()},this.onUp=r=>this.keysDown.delete(r.code),this.onBlur=()=>this.keysDown.clear(),n.addEventListener("keydown",this.onDown),n.addEventListener("keyup",this.onUp),globalThis.addEventListener?.("blur",this.onBlur)}currentActions(){let e=this.held.size===0?this.keysDown:new Set([...this.keysDown,...this.held]),n=qr(this.map,e);if(this.pressed.size===0&&this.held.size===0)return n;let r=new Set(n);for(let o of this.pressed)r.add(o);for(let o of this.held)r.add(o);return[...r].sort()}actionNames(){return Object.keys(this.map)}press(e){this.pressed.add(e)}clearPressed(){this.pressed.clear()}setHeld(e,n=!0){n?this.held.add(e):this.held.delete(e)}releaseHeld(e){this.held.delete(e)}clearHeld(){this.held.clear()}setMap(e){this.map=e}dispose(){this.target.removeEventListener("keydown",this.onDown),this.target.removeEventListener("keyup",this.onUp),globalThis.removeEventListener?.("blur",this.onBlur)}},jr=["mouse.left","mouse.right","mouse.middle"],Yt=class{clientX=0;clientY=0;isDown=!1;rightDown=!1;middleDown=!1;seen=!1;touches=new Map;target;el;keyboard;onMove;onDown;onUp;onCtx;constructor(e,n={}){this.target=e,this.el=e.element,this.keyboard=n.keyboard;let r=o=>typeof o.buttons!="number"?!1:(this.isDown=(o.buttons&1)!==0,this.rightDown=(o.buttons&2)!==0,this.middleDown=(o.buttons&4)!==0,!0);this.onMove=o=>{this.clientX=o.clientX,this.clientY=o.clientY,this.seen=!0,typeof o.buttons=="number"&&o.buttons!==0&&r(o);let i=this.touches.get(o.pointerId);i&&(i.clientX=o.clientX,i.clientY=o.clientY)},this.onDown=o=>{this.clientX=o.clientX,this.clientY=o.clientY,this.seen=!0,r(o)||(o.button===2?this.rightDown=!0:o.button===1?this.middleDown=!0:this.isDown=!0),this.touches.set(o.pointerId,{clientX:o.clientX,clientY:o.clientY})},this.onUp=o=>{r(o)||(this.isDown=!1,o.button===2?this.rightDown=!1:o.button===1?this.middleDown=!1:(this.rightDown=!1,this.middleDown=!1)),this.touches.delete(o?.pointerId)},this.onCtx=o=>o.preventDefault(),this.el?.addEventListener("pointermove",this.onMove),this.el?.addEventListener("pointerdown",this.onDown),this.el?.addEventListener("pointerup",this.onUp),this.el?.addEventListener("pointercancel",this.onUp),n.contextMenu||this.el?.addEventListener("contextmenu",this.onCtx),globalThis.addEventListener?.("pointerup",this.onUp),globalThis.addEventListener?.("pointercancel",this.onUp)}read(){let e=this.target.toDesign?.(this.clientX,this.clientY)??{x:0,y:0};return{x:e.x,y:e.y,down:this.isDown,active:this.seen}}readAll(){return[...this.touches.keys()].sort((n,r)=>n-r).map(n=>{let r=this.touches.get(n),o=this.target.toDesign?.(r.clientX,r.clientY)??{x:0,y:0};return{x:o.x,y:o.y,down:!0,active:!0,id:n}})}sample(e){let n=this.read(),r=o=>Math.round(o*8)/8;e.axes.set("pointer.x",r(n.x)),e.axes.set("pointer.y",r(n.y)),e.axes.set("pointer.down",n.down?1:0),e.axes.set("pointer.right",this.rightDown?1:0),e.axes.set("pointer.middle",this.middleDown?1:0),this.keyboard&&(e.declareActions(jr),this.keyboard.setHeld("mouse.left",this.isDown),this.keyboard.setHeld("mouse.right",this.rightDown),this.keyboard.setHeld("mouse.middle",this.middleDown))}dispose(){if(this.keyboard)for(let e of jr)this.keyboard.releaseHeld(e);this.el?.removeEventListener("pointermove",this.onMove),this.el?.removeEventListener("pointerdown",this.onDown),this.el?.removeEventListener("pointerup",this.onUp),this.el?.removeEventListener("pointercancel",this.onUp),this.el?.removeEventListener("contextmenu",this.onCtx),globalThis.removeEventListener?.("pointerup",this.onUp),globalThis.removeEventListener?.("pointercancel",this.onUp)}};var Ur=class{index;stickBuckets;triggerBuckets;deadzone;buttonMap;keyboard;prevPressed=new Map;constructor(e={}){this.index=e.index??0,this.stickBuckets=e.stickBuckets??128,this.triggerBuckets=e.triggerBuckets??64,this.deadzone=e.deadzone??.12,this.buttonMap=e.buttonMap??Wi,this.keyboard=e.keyboard}sample(e){let n=navigator.getGamepads?.()[this.index]??null;if(!n)return;let r=(d,h)=>{let p=G(d,h);if(p<this.deadzone)return{x:0,y:0};let f=(p-this.deadzone)/(1-this.deadzone),g=Math.min(f,1);return{x:d/p*g,y:h/p*g}},o=r(n.axes[0]??0,n.axes[1]??0),i=r(n.axes[2]??0,n.axes[3]??0),s=d=>Ze(d,this.stickBuckets,-1,1),a=d=>Ze(d,this.triggerBuckets,0,1);e.axes.set("gamepad.lx",s(o.x)),e.axes.set("gamepad.ly",s(o.y)),e.axes.set("gamepad.rx",s(i.x)),e.axes.set("gamepad.ry",s(i.y)),e.axes.set("gamepad.lt",a(n.buttons[6]?.value??0)),e.axes.set("gamepad.rt",a(n.buttons[7]?.value??0));let l=n.buttons[12]?.pressed?1:0,u=n.buttons[13]?.pressed?1:0,c=n.buttons[14]?.pressed?1:0,m=n.buttons[15]?.pressed?1:0;if(e.axes.set("gamepad.dpad.x",m-c),e.axes.set("gamepad.dpad.y",u-l),this.keyboard)for(let[d,h]of Object.entries(this.buttonMap)){let p=Number(d),f=n.buttons[p]?.pressed??!1;this.keyboard.setHeld(h,f),this.prevPressed.set(p,f)}}dispose(){if(this.keyboard)for(let e of Object.values(this.buttonMap))this.keyboard.releaseHeld(e);this.prevPressed.clear()}},Wi={0:"confirm",1:"cancel",2:"action2",3:"action",9:"confirm",12:"up",13:"down",14:"left",15:"right"};var J=1e-6,tt=(t,e,n)=>[Math.floor(t/n),Math.floor((e-J)/n)];function qe(t,e,n,r,o,i=[]){let s=t.tileSize,[a,l]=tt(e,e+r,s),[u,c]=tt(n,n+o,s);for(let m=u;m<=c;m++)for(let d=a;d<=l;d++)if(pe(t,d,m)===U.SOLID)return!0;for(let m of i)if(!m.oneway&&e<m.x+m.w-J&&e+r>m.x+J&&n<m.y+m.h-J&&n+o>m.y+J)return!0;return!1}function Kt(t,e,n,r,o={}){let i=t.tileSize,s=o.solids??[],{x:a,y:l}=e,{w:u,h:c}=e,m=!1,d=!1,h=!1,p=!1;if(n!==0){let[x,b]=tt(l,l+c,i);if(n>0){let w=a+n,[C,E]=[Math.floor((a+u)/i),Math.floor((a+u+n-J)/i)];for(let R=C;R<=E;R++)for(let S=x;S<=b;S++)pe(t,R,S)===U.SOLID&&(w=Math.min(w,R*i-u));for(let R of s)!R.oneway&&R.y<l+c-J&&R.y+R.h>l+J&&R.x>=a+u-J&&(w=Math.min(w,R.x-u));w<a+n-J&&(m=!0,p=!0),a=Math.min(a+n,w)}else{let w=a+n,[C,E]=[Math.floor((a-J)/i),Math.floor((a+n)/i)];for(let R=C;R>=E;R--)for(let S=x;S<=b;S++)pe(t,R,S)===U.SOLID&&(w=Math.max(w,(R+1)*i));for(let R of s)!R.oneway&&R.y<l+c-J&&R.y+R.h>l+J&&R.x+R.w<=a+J&&(w=Math.max(w,R.x+R.w));w>a+n+J&&(m=!0,h=!0),a=Math.max(a+n,w)}}let f=l+c,g=!1,k=!1,v=-1;if(r!==0){let[x,b]=tt(a,a+u,i);if(r>0){let w=l+r,[C,E]=[Math.floor(f/i),Math.floor((f+r-J)/i)];for(let R=C;R<=E;R++)for(let S=x;S<=b;S++){let T=pe(t,S,R);(T===U.SOLID||T===U.ONEWAY&&!o.dropThrough&&f<=R*i+J)&&(w=Math.min(w,R*i-c))}for(let R=0;R<s.length;R++){let S=s[R];!(S.x<a+u-J&&S.x+S.w>a+J)||S.y<f-J||S.oneway&&(o.dropThrough||f>S.y+J)||S.y-c<w&&(w=S.y-c,v=R)}w<l+r-J?(d=!0,g=!0):v=-1,l=Math.min(l+r,w)}else{let w=l+r,[C,E]=[Math.floor((l-J)/i),Math.floor((l+r)/i)];for(let R=C;R>=E;R--)for(let S=x;S<=b;S++)pe(t,S,R)===U.SOLID&&(w=Math.max(w,(R+1)*i));for(let R of s)!R.oneway&&R.x<a+u-J&&R.x+R.w>a+J&&R.y+R.h<=l+J&&(w=Math.max(w,R.y+R.h));w>l+r+J&&(d=!0,k=!0),l=Math.max(l+r,w)}}if(!g){let x=Bi(t,a,l,u,c,s,o.dropThrough??!1);g=x.grounded,v=x.solid}let M=3,I=!1;{let[x,b]=tt(a+M,a+u-M,i),[w,C]=tt(l+M,l+c-M,i);for(let E=w;E<=C&&!I;E++)for(let R=x;R<=b&&!I;R++)pe(t,R,E)===U.HAZARD&&(I=!0)}return{x:a,y:l,hitX:m,hitY:d,onFloor:g,onCeiling:k,onWallLeft:h,onWallRight:p,hazard:I,floorSolid:v}}function Bi(t,e,n,r,o,i=[],s=!1){let a=t.tileSize,l=n+o,[u,c]=tt(e,e+r,a),m=Math.floor((l+1)/a);for(let d=u;d<=c;d++){let h=pe(t,d,m);if(h===U.SOLID)return{grounded:!0,solid:-1};if(h===U.ONEWAY&&!s&&Math.abs(l-m*a)<=1+J)return{grounded:!0,solid:-1}}for(let d=0;d<i.length;d++){let h=i[d];if(h.x<e+r-J&&h.x+h.w>e+J&&l<=h.y+1+J&&l>=h.y-1-J)return{grounded:!0,solid:d}}return{grounded:!1,solid:-1}}var St={width:22,height:28,runSpeed:340,groundAccel:3800,groundFriction:4200,airAccel:2600,airFriction:260,gravity:2300,maxFall:660,apexThreshold:60,apexGravityMult:.5,jumpVelocity:650,jumpCutMult:.4,coyoteTime:.1,jumpBuffer:.12,jumpCornerNudge:10,dashCornerNudge:12,airJumps:0,airJumpMult:.92,dashSpeed:640,dashTime:.14,dashCooldown:.25,dashCharges:1,wallSlideMaxFall:150,wallJumpVelX:360,wallJumpVelY:600,wallJumpLock:.13},Jl={moveX:0,moveY:0,jumpHeld:!1,jumpPressed:!1,dashPressed:!1};function Yl(t,e){return{x:t,y:e,vx:0,vy:0,facing:1,onGround:!1,onWall:0,coyote:0,buffer:0,jumping:!1,wallLock:0,airJumpsLeft:0,dashing:0,dashCd:0,dashesLeft:1,dashVx:0,dashVy:0,carryVx:0,carryVy:0,dead:!1}}var Kl=(t,e,n)=>t<e?Math.min(t+n,e):Math.max(t-n,e);function Ql(t,e,n,r,o=St,i=[]){let s={jumped:!1,wallJumped:!1,airJumped:!1,dashed:!1,landed:!1,died:!1};if(t.dead)return s;let a=t.onGround;if(t.coyote=Math.max(0,t.coyote-n),t.buffer=Math.max(0,t.buffer-n),t.wallLock=Math.max(0,t.wallLock-n),t.dashCd=Math.max(0,t.dashCd-n),e.jumpPressed&&(t.buffer=o.jumpBuffer),e.dashPressed&&t.dashing<=0&&t.dashCd<=0&&t.dashesLeft>0){let d=e.moveX,h=e.moveY;d===0&&h===0&&(d=t.facing);let p=1/G(d,h);t.dashing=o.dashTime,t.dashCd=o.dashCooldown,t.dashesLeft--,t.dashVx=d*p*o.dashSpeed,t.dashVy=h*p*o.dashSpeed,t.jumping=!1,s.dashed=!0}if(t.dashing>0)t.vx=t.dashVx,t.vy=t.dashVy,t.dashing-=n;else if(t.wallLock<=0){let d=e.moveX*o.runSpeed,h=t.onGround?e.moveX!==0?o.groundAccel:o.groundFriction:e.moveX!==0?o.airAccel:o.airFriction;t.vx=Kl(t.vx,d,h*n),e.moveX!==0&&(t.facing=e.moveX>0?1:-1)}if(t.dashing<=0&&!t.onGround){let d=o.gravity;Math.abs(t.vy)<o.apexThreshold&&e.jumpHeld&&t.jumping&&(d*=o.apexGravityMult),t.vy=Math.min(t.vy+d*n,o.maxFall),t.onWall!==0&&t.vy>o.wallSlideMaxFall&&e.moveX===t.onWall&&(t.vy=o.wallSlideMaxFall)}t.jumping&&!e.jumpHeld&&t.vy<0&&(t.vy*=o.jumpCutMult,t.jumping=!1),t.buffer>0&&t.dashing<=0&&(t.onGround||t.coyote>0?(t.vy=-o.jumpVelocity,t.vx+=t.carryVx,t.carryVy<0&&(t.vy+=t.carryVy),t.jumping=!0,t.buffer=0,t.coyote=0,t.onGround=!1,s.jumped=!0):t.onWall!==0&&o.wallJumpVelY>0?(t.vx=-t.onWall*o.wallJumpVelX,t.vy=-o.wallJumpVelY,t.facing=-t.onWall,t.jumping=!0,t.buffer=0,t.wallLock=o.wallJumpLock,s.wallJumped=!0,s.jumped=!0):t.airJumpsLeft>0&&(t.vy=-o.jumpVelocity*o.airJumpMult,t.airJumpsLeft--,t.jumping=!0,t.buffer=0,s.jumped=!0,s.airJumped=!0));let l=e.moveY>0&&t.buffer<=0,u=t.vx*n+t.carryVx*n*(t.onGround?1:0),c=t.vy*n+Math.max(0,t.carryVy)*n*(t.onGround?1:0),m=Kt(r,{x:t.x,y:t.y,w:o.width,h:o.height},u,c,{solids:i,dropThrough:l});if(m.onCeiling&&t.vy<0&&t.dashing<=0){let d=tu(r,i,m.x,m.y,o.width,o.height,c,o.jumpCornerNudge);d!==null&&(m=Kt(r,{x:d,y:m.y,w:o.width,h:o.height},0,c,{solids:i,dropThrough:l}),m.x=d)}if(m.hitX&&t.dashing>0&&Math.abs(t.dashVy)<1){let d=nu(r,i,m.x,m.y,o.width,o.height,u,o.dashCornerNudge);d!==null&&(m=Kt(r,{x:m.x,y:d,w:o.width,h:o.height},u,0,{solids:i,dropThrough:l}),m.y=d)}if(t.x=m.x,t.y=m.y,m.hitY&&t.vy>0&&(t.vy=0),m.onCeiling&&(t.vy=Math.max(t.vy,0),t.jumping=!1),m.hitX&&t.dashing<=0&&(t.vx=0),t.onWall=m.onWallLeft?-1:m.onWallRight?1:ru(r,i,t.x,t.y,o.width,o.height),t.onGround=m.onFloor,t.onGround){if(t.coyote=o.coyoteTime,t.dashesLeft=o.dashCharges,t.airJumpsLeft=o.airJumps,a||(s.landed=!0),m.floorSolid>=0){let d=i[m.floorSolid];t.carryVx=d.vx,t.carryVy=d.vy,t.y=d.y-o.height}else t.carryVx=0,t.carryVy=0;t.vy>0&&(t.vy=0),t.jumping=!1}else a&&t.carryVy;return m.hazard&&(t.dead=!0,s.died=!0),s}function Zl(t=St){return t.jumpVelocity*t.jumpVelocity/(2*t.gravity)}function zi(t=St){return 2*t.jumpVelocity/t.gravity}function _i(t=St){return t.runSpeed*zi(t)}function eu(t=St){return _i(t)+(t.dashSpeed-t.runSpeed)*t.dashTime}function tu(t,e,n,r,o,i,s,a){for(let l=1;l<=a;l++)for(let u of[1,-1]){let c=n+u*l;if(!qe(t,c,r+s,o,i,e)&&!qe(t,c,r,o,i,e))return c}return null}function nu(t,e,n,r,o,i,s,a){for(let l=1;l<=a;l++)for(let u of[-1,1]){let c=r+u*l;if(!qe(t,n+s,c,o,i,e)&&!qe(t,n,c,o,i,e))return c}return null}function ru(t,e,n,r,o,i){return qe(t,n+1,r,o,i,e)?1:qe(t,n-1,r,o,i,e)?-1:0}var Qt=class{cells=new Map;bounds=new Map;cellSize;constructor(e=64){this.cellSize=e}clear(){this.cells.clear(),this.bounds.clear()}get size(){return this.bounds.size}key(e,n){return(e+32768)*65536+(n+32768)}insert(e,n){this.bounds.set(e,n);let r=this.cellSize,o=Math.floor(n.x/r),i=Math.floor((n.x+n.w)/r),s=Math.floor(n.y/r),a=Math.floor((n.y+n.h)/r);for(let l=s;l<=a;l++)for(let u=o;u<=i;u++){let c=this.key(u,l),m=this.cells.get(c);m?m.push(e):this.cells.set(c,[e])}}query(e){let n=this.cellSize,r=Math.floor(e.x/n),o=Math.floor((e.x+e.w)/n),i=Math.floor(e.y/n),s=Math.floor((e.y+e.h)/n),a=new Set,l=[];for(let u=i;u<=s;u++)for(let c=r;c<=o;c++){let m=this.cells.get(this.key(c,u));if(m)for(let d of m){if(a.has(d))continue;a.add(d);let h=this.bounds.get(d);h.x<e.x+e.w&&h.x+h.w>e.x&&h.y<e.y+e.h&&h.y+h.h>e.y&&l.push(d)}}return l}queryCircle(e,n,r){return this.query({x:e-r,y:n-r,w:r*2,h:r*2}).filter(i=>{let s=this.bounds.get(i),a=Math.max(s.x,Math.min(e,s.x+s.w)),l=Math.max(s.y,Math.min(n,s.y+s.h));return(e-a)*(e-a)+(n-l)*(n-l)<=r*r})}};function Oi(t,e,n,r,o){let i=t.tileSize,s=r-e,a=o-n,l=G(s,a);if(l===0)return{blocked:!1,x:r,y:o,dist:0};let u=s/l,c=a/l,m=Math.floor(e/i),d=Math.floor(n/i),h=u>0?1:-1,p=c>0?1:-1,f=u!==0?Math.abs(i/u):1/0,g=c!==0?Math.abs(i/c):1/0,k=u!==0?(u>0?(m+1)*i-e:e-m*i)/Math.abs(u):1/0,v=c!==0?(c>0?(d+1)*i-n:n-d*i)/Math.abs(c):1/0,M=0;for(let I=0;I<512;I++){if(k<v?(M=k,k+=f,m+=h):(M=v,v+=g,d+=p),M>=l)return{blocked:!1,x:r,y:o,dist:l};if(pe(t,m,d)===U.SOLID)return{blocked:!0,x:e+u*M,y:n+c*M,dist:M}}return{blocked:!0,x:e+u*M,y:n+c*M,dist:M}}function Gi(t,e,n,r,o){return!Oi(t,e,n,r,o).blocked}function ou(t,e,n,r,o,i,s,a,l){let u=a-e,c=l-n,m=G(u,c);return m>s||m===0||(u*r+c*o)/m<j(i/2)?!1:Gi(t,e,n,a,l)}function iu(t={}){return{gravityX:t.gravityX??0,gravityY:t.gravityY??900,iterations:t.iterations??16,cellSize:t.cellSize??96,nextId:1,bodies:[],joints:[],warm:{}}}function su(t){if(t.kind==="circle")return{area:Math.PI*t.r*t.r,unitI:t.r*t.r/2};let e=t.points,n=e.length/2,r=0,o=0;for(let i=0;i<n;i++){let s=e[i*2],a=e[i*2+1],l=(i+1)%n,u=e[l*2],c=e[l*2+1],m=s*c-u*a;r+=m/2,o+=m*(s*s+s*u+u*u+a*a+a*c+c*c)/12}return{area:Math.abs(r),unitI:r!==0?Math.abs(o)/Math.abs(r):0}}var au=1e-4;function lu(t,e){let n=e.kind??"dynamic",r=e.density??1,{area:o,unitI:i}=su(e.shape),s=n==="dynamic"?Math.max(o*r*au,1e-6):0,a=n==="dynamic"&&!e.fixedRotation?s*i:0,l={id:t.nextId++,kind:n,shape:e.shape,x:e.x??0,y:e.y??0,a:e.a??0,vx:e.vx??0,vy:e.vy??0,w:e.w??0,m:s,invM:s>0?1/s:0,i:a,invI:a>0?1/a:0,restitution:e.restitution??.1,friction:e.friction??.4,linDamp:e.linDamp??0,angDamp:e.angDamp??.6,gravityScale:e.gravityScale??1,bullet:e.bullet??!1,sensor:e.sensor??!1,layer:e.layer??1,mask:e.mask??65535,canSleep:e.canSleep??!0,sleeping:!1,sleepTime:0,sleepR:e.shape.kind==="circle"?e.shape.r:Math.sqrt(e.shape.points.reduce((u,c,m,d)=>m%2?u:Math.max(u,d[m]*d[m]+d[m+1]*d[m+1]),0)),fx:0,fy:0,torque:0};return t.bodies.push(l),l.id}function ge(t,e){let n=t.bodies;for(let r=0;r<n.length;r++)if(n[r].id===e)return n[r]}function uu(t,e){let n=t.bodies.findIndex(r=>r.id===e);n>=0&&t.bodies.splice(n,1),t.joints=t.joints.filter(r=>r.a!==e&&r.b!==e)}function ye(t){t.sleeping=!1,t.sleepTime=0}function cu(t,e,n,r,o,i){let s=ge(t,e);!s||s.invM===0||(ye(s),s.vx+=n*s.invM,s.vy+=r*s.invM,o!==void 0&&i!==void 0&&(s.w+=((o-s.x)*r-(i-s.y)*n)*s.invI))}function ke(t){if(t.shape.kind!=="poly")return[];let e=j(t.a),n=q(t.a),r=t.shape.points,o=new Array(r.length);for(let i=0;i<r.length;i+=2)o[i]=t.x+r[i]*e-r[i+1]*n,o[i+1]=t.y+r[i]*n+r[i+1]*e;return o}function An(t){if(t.shape.kind==="circle"){let s=t.shape.r;return{x:t.x-s,y:t.y-s,w:s*2,h:s*2}}let e=ke(t),n=1/0,r=1/0,o=-1/0,i=-1/0;for(let s=0;s<e.length;s+=2)e[s]<n&&(n=e[s]),e[s]>o&&(o=e[s]),e[s+1]<r&&(r=e[s+1]),e[s+1]>i&&(i=e[s+1]);return{x:n,y:r,w:o-n,h:i-r}}function mu(t,e){let n=t/2,r=e/2;return{kind:"poly",points:[-n,-r,n,-r,n,r,-n,r]}}function du(t,e){if(t.shape.kind!=="circle"||e.shape.kind!=="circle")return null;let n=e.x-t.x,r=e.y-t.y,o=t.shape.r+e.shape.r,i=n*n+r*r;if(i>=o*o)return null;let s=Math.sqrt(i),a=s>1e-9?n/s:1,l=s>1e-9?r/s:0;return{a:t,b:e,nx:a,ny:l,points:[{px:t.x+a*t.shape.r,py:t.y+l*t.shape.r,pen:o-s,feature:0}]}}function Vi(t,e){if(t.shape.kind!=="poly"||e.shape.kind!=="circle")return null;let n=ke(t),r=n.length/2,o=e.shape.r,i=-1/0,s=0;for(let E=0;E<r;E++){let R=(E+1)%r,S=n[R*2]-n[E*2],T=n[R*2+1]-n[E*2+1],L=G(S,T)||1,H=T/L,$=-S/L,Y=(e.x-n[E*2])*H+(e.y-n[E*2+1])*$;Y>i&&(i=Y,s=E)}if(i>o)return null;let a=s,l=(s+1)%r,u=n[a*2],c=n[a*2+1],m=n[l*2],d=n[l*2+1];if(i<1e-9){let E=m-u,R=d-c,S=G(E,R)||1,T=R/S,L=-E/S;return{a:t,b:e,nx:T,ny:L,points:[{px:e.x-T*o,py:e.y-L*o,pen:o-i,feature:s}]}}let h=m-u,p=d-c,f=h*h+p*p||1,g=((e.x-u)*h+(e.y-c)*p)/f;g=g<0?0:g>1?1:g;let k=u+h*g,v=c+p*g,M=e.x-k,I=e.y-v,x=M*M+I*I;if(x>=o*o)return null;let b=Math.sqrt(x)||1e-9,w=M/b,C=I/b;return{a:t,b:e,nx:w,ny:C,points:[{px:k,py:v,pen:o-b,feature:s}]}}function Hi(t,e){let n=t.length/2,r=e.length/2,o=-1/0,i=0;for(let s=0;s<n;s++){let a=(s+1)%n,l=t[a*2]-t[s*2],u=t[a*2+1]-t[s*2+1],c=G(l,u)||1,m=u/c,d=-l/c,h=1/0;for(let p=0;p<r;p++){let f=(e[p*2]-t[s*2])*m+(e[p*2+1]-t[s*2+1])*d;f<h&&(h=f)}h>o&&(o=h,i=s)}return[o,i]}function hu(t,e){let n=ke(t),r=ke(e),[o,i]=Hi(n,r);if(o>0)return null;let[s,a]=Hi(r,n);if(s>0)return null;let l,u,c,m;s>o+1e-4?(l=r,u=n,c=a,m=!0):(l=n,u=r,c=i,m=!1);let d=l.length/2,h=u.length/2,p=(c+1)%d,f=l[p*2]-l[c*2],g=l[p*2+1]-l[c*2+1],k=G(f,g)||1,v=g/k,M=-f/k,I=f/k,x=g/k,b=0,w=1/0;for(let O=0;O<h;O++){let z=(O+1)%h,X=u[z*2]-u[O*2],se=u[z*2+1]-u[O*2+1],ae=G(X,se)||1,re=se/ae*v+-X/ae*M;re<w&&(w=re,b=O)}let C=(b+1)%h,E=u[b*2],R=u[b*2+1],S=u[C*2],T=u[C*2+1],L=l[c*2],H=l[c*2+1],$=l[p*2],Y=l[p*2+1];for(let O=0;O<2;O++){let z=O===0?L:$,X=O===0?H:Y,se=O===0?I:-I,ae=O===0?x:-x,re=(E-z)*se+(R-X)*ae,le=(S-z)*se+(T-X)*ae;if(re<0&&le<0)return null;if(re<0){let me=re/(re-le);E=E+(S-E)*me,R=R+(T-R)*me}else if(le<0){let me=le/(le-re);S=S+(E-S)*me,T=T+(R-T)*me}}let K=m?-v:v,te=m?-M:M,ee=[],ie=-((E-L)*v+(R-H)*M),D=-((S-L)*v+(T-H)*M),A=((m?1:0)*64+c)*64+b;return ie>0&&ee.push({px:E,py:R,pen:ie,feature:A*2}),D>0&&ee.push({px:S,py:T,pen:D,feature:A*2+1}),ee.length===0?null:{a:t,b:e,nx:K,ny:te,points:ee}}function Xr(t,e){let n=t.shape.kind,r=e.shape.kind;if(n==="circle"&&r==="circle")return du(t,e);if(n==="poly"&&r==="poly")return hu(t,e);if(n==="poly"&&r==="circle")return Vi(t,e);let o=Vi(e,t);return o?{a:t,b:e,nx:-o.nx,ny:-o.ny,points:o.points}:null}function qi(t,e,n){let r=j(t.a),o=q(t.a),i=e-t.x,s=n-t.y;return[i*r+s*o,-i*o+s*r]}function Wn(t,e,n){let r=j(t.a),o=q(t.a);return[t.x+e*r-n*o,t.y+e*o+n*r]}function pu(t,e){let n=ge(t,e.a),r=ge(t,e.b);if(!n||!r)throw new Error(`distance joint: missing body ${e.a}/${e.b}`);let o=e.ax??0,i=e.ay??0,s=e.bx??0,a=e.by??0,[l,u]=Wn(n,o,i),[c,m]=Wn(r,s,a),d={kind:"distance",id:t.nextId++,a:e.a,b:e.b,ax:o,ay:i,bx:s,by:a,length:e.length??G(c-l,m-u),rope:e.rope??!1};return t.joints.push(d),ye(n),ye(r),d.id}function fu(t,e){let n=ge(t,e.a),r=ge(t,e.b);if(!n||!r)throw new Error(`revolute joint: missing body ${e.a}/${e.b}`);let[o,i]=qi(n,e.px,e.py),[s,a]=qi(r,e.px,e.py),l={kind:"revolute",id:t.nextId++,a:e.a,b:e.b,ax:o,ay:i,bx:s,by:a,motorSpeed:e.motorSpeed??0,maxMotorTorque:e.maxMotorTorque??0,limitLower:e.limitLower??0,limitUpper:e.limitUpper??0,limitEnabled:e.limitLower!==void 0||e.limitUpper!==void 0,refAngle:r.a-n.a};return t.joints.push(l),ye(n),ye(r),l.id}function bu(t,e){for(let n of t.joints)if(n.id===e)return n}function gu(t,e){t.joints=t.joints.filter(n=>n.id!==e)}function Jr(t,e,n,r,o){let[i,s]=Wn(e,t.ax,t.ay),[a,l]=Wn(n,t.bx,t.by),u=i-e.x,c=s-e.y,m=a-n.x,d=l-n.y;if(t.kind==="distance"){let S=a-i,T=l-s,L=G(S,T);if(L<1e-9)return;S/=L,T/=L;let H=L-t.length;if(t.rope&&H<=0)return;let $=e.vx-e.w*c,Y=e.vy+e.w*u,K=n.vx-n.w*d,te=n.vy+n.w*m,ee=(K-$)*S+(te-Y)*T,ie=u*T-c*S,D=m*T-d*S,A=e.invM+n.invM+e.invI*ie*ie+n.invI*D*D;if(A<1e-12)return;let O=.2/r*H,z=-(ee+O)/A;t.rope&&z>0&&(z=0);let X=S*z,se=T*z;e.vx-=X*e.invM,e.vy-=se*e.invM,e.w-=(u*se-c*X)*e.invI,n.vx+=X*n.invM,n.vy+=se*n.invM,n.w+=(m*se-d*X)*n.invI;return}if(t.maxMotorTorque>0){let S=e.invI+n.invI;if(S>1e-12){let L=-(n.w-e.w-t.motorSpeed)/S,H=t.maxMotorTorque*r,$=o.motorImpulse;o.motorImpulse=Math.min(Math.max($+L,-H),H);let Y=o.motorImpulse-$;e.w-=Y*e.invI,n.w+=Y*n.invI}}if(t.limitEnabled){let S=e.invI+n.invI;if(S>1e-12){let T=n.a-e.a-t.refAngle,L=0;if(T<t.limitLower?L=T-t.limitLower:T>t.limitUpper&&(L=T-t.limitUpper),L!==0){let $=-(n.w-e.w+.2/r*L)/S;(L<0&&$>0||L>0&&$<0)&&(e.w-=$*e.invI,n.w+=$*n.invI)}}}let h=e.vx-e.w*c,p=e.vy+e.w*u,f=n.vx-n.w*d,g=n.vy+n.w*m,k=a-i,v=l-s,M=f-h+.2/r*k,I=g-p+.2/r*v,x=e.invM+n.invM+e.invI*c*c+n.invI*d*d,b=-e.invI*u*c-n.invI*m*d,w=e.invM+n.invM+e.invI*u*u+n.invI*m*m,C=x*w-b*b;if(Math.abs(C)<1e-12)return;let E=-(w*M-b*I)/C,R=-(x*I-b*M)/C;e.vx-=E*e.invM,e.vy-=R*e.invM,e.w-=(u*R-c*E)*e.invI,n.vx+=E*n.invM,n.vy+=R*n.invM,n.w+=(m*R-d*E)*n.invI}var yu=.5,xu=.2,vu=40,wu=64,ku=8,Su=.5,ji=100;function Ui(t,e){return t.invM===0&&e.invM===0&&t.kind!=="kinematic"&&e.kind!=="kinematic"&&!t.sensor&&!e.sensor?!1:(t.mask&e.layer)!==0&&(e.mask&t.layer)!==0}function Cu(t,e){let n=t.bodies,r=[];if(e<=0)return r;for(let x=0;x<n.length;x++){let b=n[x];if(b.kind!=="dynamic"||b.sleeping){b.fx=0,b.fy=0,b.torque=0;continue}b.vx+=(t.gravityX*b.gravityScale+b.fx*b.invM)*e,b.vy+=(t.gravityY*b.gravityScale+b.fy*b.invM)*e,b.w+=b.torque*b.invI*e;let w=1/(1+b.linDamp*e);b.vx*=w,b.vy*=w,b.w*=1/(1+b.angDamp*e),b.fx=0,b.fy=0,b.torque=0}let o=new Qt(t.cellSize),i=new Map;for(let x=0;x<n.length;x++)o.insert(n[x],An(n[x])),i.set(n[x],x);let s=[],a=new Set,l=new Set;for(let x of t.joints){let b=Math.min(x.a,x.b),w=Math.max(x.a,x.b);l.add(b*1048576+w)}for(let x=0;x<n.length;x++){let b=n[x],w=o.query(An(b));for(let C of w){if(C.id<=b.id)continue;let E=b.id*1048576+C.id;if(a.has(E)||(a.add(E),l.has(E))||!Ui(b,C))continue;let R=!b.sleeping&&b.kind!=="static",S=!C.sleeping&&C.kind!=="static";if(!R&&!S)continue;let T=Xr(b,C);if(!T)continue;let L=(K,te)=>{K.sleeping&&(te.vx*te.vx+te.vy*te.vy>ji||te.kind==="kinematic")&&ye(K)};if(L(b,C),L(C,b),b.sensor||C.sensor){r.push({a:b.id,b:C.id,px:T.points[0].px,py:T.points[0].py,nx:T.nx,ny:T.ny,impulse:0,sensor:!0});continue}let H=[],$=-T.ny,Y=T.nx;for(let K of T.points){let te=K.px-b.x,ee=K.py-b.y,ie=K.px-C.x,D=K.py-C.y,A=te*T.ny-ee*T.nx,O=ie*T.ny-D*T.nx,z=b.invM+C.invM+b.invI*A*A+C.invI*O*O,X=te*Y-ee*$,se=ie*Y-D*$,ae=b.invM+C.invM+b.invI*X*X+C.invI*se*se,re=C.vx-C.w*D-b.vx+b.w*ee,le=C.vy+C.w*ie-b.vy-b.w*te,me=re*T.nx+le*T.ny,xe=Math.max(b.restitution,C.restitution),Ue=`${b.id}:${C.id}:${K.feature}`,Me=t.warm[Ue],Ea={rax:te,ray:ee,rbx:ie,rby:D,pen:K.pen,massN:z>1e-12?1/z:0,massT:ae>1e-12?1/ae:0,restBias:me<-vu?-xe*me:0,posBias:xu/e*Math.max(0,K.pen-yu),pn:Me?Me[0]:0,pt:Me?Me[1]:0,pb:0,key:Ue};H.push(Ea)}s.push({m:T,ia:x,ib:i.get(C),points:H,friction:Math.sqrt(b.friction*C.friction)})}}for(let x of s){let{a:b,b:w,nx:C,ny:E}=x.m,R=-E,S=C;for(let T of x.points){if(T.pn===0&&T.pt===0)continue;let L=C*T.pn+R*T.pt,H=E*T.pn+S*T.pt;b.vx-=L*b.invM,b.vy-=H*b.invM,b.w-=(T.rax*H-T.ray*L)*b.invI,w.vx+=L*w.invM,w.vy+=H*w.invM,w.w+=(T.rbx*H-T.rby*L)*w.invI}}s.sort((x,b)=>{let w=x.m.a.invM===0||x.m.b.invM===0?0:1,C=b.m.a.invM===0||b.m.b.invM===0?0:1;if(w!==C)return w-C;let E=Math.max(x.m.a.y,x.m.b.y),R=Math.max(b.m.a.y,b.m.b.y);return E!==R?R-E:x.m.a.id!==b.m.a.id?x.m.a.id-b.m.a.id:x.m.b.id-b.m.b.id});let u=new Float64Array(n.length),c=new Float64Array(n.length),m=new Float64Array(n.length),d=t.joints.map(()=>({motorImpulse:0}));for(let x=0;x<t.iterations;x++){for(let b=0;b<t.joints.length;b++){let w=t.joints[b],C=ge(t,w.a),E=ge(t,w.b);!C||!E||C.sleeping&&E.sleeping||(C.sleeping&&ye(C),E.sleeping&&ye(E),Jr(w,C,E,e,d[b]))}for(let b of s){let{a:w,b:C,nx:E,ny:R}=b.m,{ia:S,ib:T}=b,L=-R,H=E;for(let $ of b.points){let Y=C.vx-C.w*$.rby-w.vx+w.w*$.ray,K=C.vy+C.w*$.rbx-w.vy-w.w*$.rax,te=Y*E+K*R,ee=$.massN*($.restBias-te),ie=$.pn;$.pn=Math.max(ie+ee,0),ee=$.pn-ie;let D=E*ee,A=R*ee;w.vx-=D*w.invM,w.vy-=A*w.invM,w.w-=($.rax*A-$.ray*D)*w.invI,C.vx+=D*C.invM,C.vy+=A*C.invM,C.w+=($.rbx*A-$.rby*D)*C.invI,Y=C.vx-C.w*$.rby-w.vx+w.w*$.ray,K=C.vy+C.w*$.rbx-w.vy-w.w*$.rax;let O=Y*L+K*H,z=$.massT*-O,X=b.friction*$.pn,se=$.pt;if($.pt=Math.min(Math.max(se+z,-X),X),z=$.pt-se,D=L*z,A=H*z,w.vx-=D*w.invM,w.vy-=A*w.invM,w.w-=($.rax*A-$.ray*D)*w.invI,C.vx+=D*C.invM,C.vy+=A*C.invM,C.w+=($.rbx*A-$.rby*D)*C.invI,$.posBias>0){let ae=(u[T]-m[T]*$.rby-u[S]+m[S]*$.ray)*E+(c[T]+m[T]*$.rbx-c[S]-m[S]*$.rax)*R,re=$.massN*($.posBias-ae),le=$.pb;$.pb=Math.max(le+re,0),re=$.pb-le;let me=E*re,xe=R*re;u[S]-=me*w.invM,c[S]-=xe*w.invM,u[T]+=me*C.invM,c[T]+=xe*C.invM}}}}let h=[],p=[];for(let x=0;x<n.length;x++){let b=n[x];h.push(b.x),p.push(b.y),!(b.invM===0&&b.kind!=="kinematic")&&(b.sleeping||(b.x+=(b.vx+u[x])*e,b.y+=(b.vy+c[x])*e,b.a+=(b.w+m[x])*e))}for(let x=0;x<n.length;x++){let b=n[x];if(!b.bullet||b.shape.kind!=="circle"||b.sleeping)continue;let w=b.x-h[x],C=b.y-p[x];if(w*w+C*C<1)continue;let E=1;for(let R=0;R<n.length;R++){let S=n[R];if(S===b||S.bullet||S.sensor||!Ui(b,S))continue;let T=Tu(h[x],p[x],w,C,b.shape.r,S);T>=0&&T<E&&(E=T)}if(E<1){let R=G(w,C)||1;b.x=h[x]+w*E+w/R*.4,b.y=p[x]+C*E+C/R*.4}}let f=new Set,g=[];for(let x=0;x<n.length;x++)g.push(x);let k=x=>{for(;g[x]!==x;)g[x]=g[g[x]],x=g[x];return x},v=(x,b)=>{g[k(x)]=k(b)};for(let x of s)f.add(x.m.a.id),f.add(x.m.b.id),x.m.a.kind==="dynamic"&&x.m.b.kind==="dynamic"&&v(x.ia,x.ib);for(let x of t.joints){f.add(x.a),f.add(x.b);let b=ge(t,x.a),w=ge(t,x.b);b?.kind==="dynamic"&&w?.kind==="dynamic"&&v(i.get(b),i.get(w))}for(let x=0;x<n.length;x++){let b=n[x];if(b.kind!=="dynamic")continue;let w=b.vx*b.vx+b.vy*b.vy;if(b.sleeping){w>ji&&ye(b);continue}if(!b.canSleep||!f.has(b.id)){b.sleepTime=0;continue}b.sleepTime=w<wu&&Math.abs(b.w)*b.sleepR<ku?b.sleepTime+e:0}let M=new Map;for(let x=0;x<n.length;x++){let b=n[x];if(b.kind!=="dynamic"||b.sleeping)continue;let w=k(x),C=!b.canSleep||!f.has(b.id)?-1:b.sleepTime,E=M.get(w);M.set(w,E===void 0?C:Math.min(E,C))}for(let x=0;x<n.length;x++){let b=n[x];b.kind!=="dynamic"||b.sleeping||(M.get(k(x))??-1)>=Su&&(b.sleeping=!0,b.vx=0,b.vy=0,b.w=0)}let I={};for(let x of s){let b=0;for(let C of x.points)b+=C.pn,(C.pn!==0||C.pt!==0)&&(I[C.key]=[C.pn,C.pt]);let w=x.m.points[0];r.push({a:x.m.a.id,b:x.m.b.id,px:w.px,py:w.py,nx:x.m.nx,ny:x.m.ny,impulse:b,sensor:!1})}return t.warm=I,r}function Tu(t,e,n,r,o,i){if(i.shape.kind==="circle")return Xi(t,e,n,r,i.x,i.y,o+i.shape.r);let s=ke(i),a=s.length/2,l=-1;for(let u=0;u<a;u++){let c=(u+1)%a,m=s[u*2],d=s[u*2+1],h=s[c*2],p=s[c*2+1],f=h-m,g=p-d,k=G(f,g)||1,v=g/k,M=-f/k,I=(t-m)*v+(e-d)*M-o;if(n*v+r*M<0&&I>.5){let b=Mu(t,e,n,r,m+v*o,d+M*o,h+v*o,p+M*o);b>=0&&(l<0||b<l)&&(l=b)}let x=Xi(t,e,n,r,m,d,o);x>=0&&(l<0||x<l)&&(l=x)}return l}function Xi(t,e,n,r,o,i,s){let a=t-o,l=e-i,u=n*n+r*r;if(u<1e-12)return-1;let c=2*(a*n+l*r);if(a*a+l*l<(s+.5)*(s+.5))return-1;let m=a*a+l*l-s*s,d=c*c-4*u*m;if(d<0)return-1;let h=(-c-Math.sqrt(d))/(2*u);return h>=0&&h<=1?h:-1}function Mu(t,e,n,r,o,i,s,a){let l=s-o,u=a-i,c=n*u-r*l;if(Math.abs(c)<1e-12)return-1;let m=((o-t)*u-(i-e)*l)/c,d=((o-t)*r-(i-e)*n)/c;return m>=0&&m<=1&&d>=0&&d<=1?m:-1}function Ji(t,e,n){if(t.shape.kind==="circle"){let i=e-t.x,s=n-t.y;return i*i+s*s<=t.shape.r*t.shape.r}let r=ke(t),o=r.length/2;for(let i=0;i<o;i++){let s=(i+1)%o,a=r[s*2]-r[i*2],l=r[s*2+1]-r[i*2+1];if((e-r[i*2])*l-(n-r[i*2+1])*a>0)return!1}return!0}function Ru(t,e,n,r=65535){let o;for(let i of t.bodies)(i.layer&r)!==0&&Ji(i,e,n)&&(o=i);return o}function Pu(t,e,n,r,o,i,s){let a=t-o,l=e-i,u=n*n+r*r;if(u<1e-12)return-1;let c=2*(a*n+l*r),m=a*a+l*l-s*s,d=c*c-4*u*m;if(d<0)return-1;let h=(-c-Math.sqrt(d))/(2*u);return h>=0&&h<=1?h:-1}function Du(t,e,n,r,o,i=65535){let s=r-e,a=o-n,l=null;for(let u of t.bodies){if((u.layer&i)===0)continue;if(u.shape.kind==="circle"){let d=Pu(e,n,s,a,u.x,u.y,u.shape.r);if(d>=0&&(!l||d<l.t)){let h=e+s*d,p=n+a*d,f=G(h-u.x,p-u.y)||1;l={id:u.id,t:d,x:h,y:p,nx:(h-u.x)/f,ny:(p-u.y)/f}}continue}let c=ke(u),m=c.length/2;for(let d=0;d<m;d++){let h=(d+1)%m,p=c[d*2],f=c[d*2+1],g=c[h*2]-p,k=c[h*2+1]-f,v=s*k-a*g;if(Math.abs(v)<1e-12)continue;let M=((p-e)*k-(f-n)*g)/v,I=((p-e)*a-(f-n)*s)/v;if(!(M<0||M>1||I<0||I>1)&&(!l||M<l.t)){let x=G(g,k)||1;l={id:u.id,t:M,x:e+s*M,y:n+a*M,nx:k/x,ny:-g/x}}}}return l}var Se=t=>Number.isInteger(t)?String(t):(Math.round(t*1e3)/1e3).toString();function Ki(t){let e=Math.max(1,t.length-1);return t.map((n,r)=>typeof n=="string"?{offset:r/e,color:n}:n)}function Eu(t,e=90){let n=e*Math.PI/180,r=j(n)*.5,o=q(n)*.5;return{type:"linear",x1:.5-r,y1:.5-o,x2:.5+r,y2:.5+o,stops:Ki(t)}}function Iu(t,e={}){return{type:"radial",cx:e.cx??.5,cy:e.cy??.5,r:e.r??.5,stops:Ki(t)}}function Lu(t,e){return{color:t,blur:e}}function $u(t,e,n=0,r=0){return{color:t,blur:e,dx:n,dy:r}}function Nu(t){return`<stop offset="${Se(t.offset)}" stop-color="${t.color}"/>`}function Bn(t,e){let n=t.stops.map(Nu).join("");return t.type==="linear"?`<linearGradient id="${e}" x1="${Se(t.x1)}" y1="${Se(t.y1)}" x2="${Se(t.x2)}" y2="${Se(t.y2)}">${n}</linearGradient>`:`<radialGradient id="${e}" cx="${Se(t.cx)}" cy="${Se(t.cy)}" r="${Se(t.r)}">${n}</radialGradient>`}function Yr(t,e){return`<filter id="${e}" x="-60%" y="-60%" width="220%" height="220%"><feDropShadow dx="${Se(t.dx??0)}" dy="${Se(t.dy??0)}" stdDeviation="${Se(t.blur/2)}" flood-color="${t.color}"/></filter>`}function Kr(t){switch(t.kind){case"rect":return{x:t.x,y:t.y,w:t.w,h:t.h};case"circle":return{x:t.cx-t.radius,y:t.cy-t.radius,w:t.radius*2,h:t.radius*2};case"ellipse":return{x:t.cx-t.rx,y:t.cy-t.ry,w:t.rx*2,h:t.ry*2};case"arc":return{x:t.cx-t.radius,y:t.cy-t.radius,w:t.radius*2,h:t.radius*2};case"poly":{if(t.points.length<2)return null;let e=t.points[0],n=t.points[0],r=t.points[1],o=t.points[1];for(let i=0;i<t.points.length;i+=2)e=Math.min(e,t.points[i]),n=Math.max(n,t.points[i]),r=Math.min(r,t.points[i+1]),o=Math.max(o,t.points[i+1]);return{x:e,y:r,w:n-e,h:o-r}}default:return null}}function Zt(t){switch(t.kind){case"rect":return!Number.isFinite(t.x)||!Number.isFinite(t.y)||!Number.isFinite(t.w)||!Number.isFinite(t.h)?"non-finite x/y/w/h":null;case"circle":return!Number.isFinite(t.cx)||!Number.isFinite(t.cy)?"non-finite center":Number.isFinite(t.radius)?t.radius<0?"negative radius":null:"non-finite radius";case"ellipse":return!Number.isFinite(t.cx)||!Number.isFinite(t.cy)?"non-finite center":!Number.isFinite(t.rx)||!Number.isFinite(t.ry)?"non-finite rx/ry":t.rx<0||t.ry<0?"negative rx/ry":null;case"arc":return!Number.isFinite(t.cx)||!Number.isFinite(t.cy)?"non-finite center":Number.isFinite(t.radius)?t.radius<0?"negative radius":!Number.isFinite(t.start)||!Number.isFinite(t.end)?"non-finite start/end":null:"non-finite radius";default:return null}}var Yi=new Set;function Ct(t,e,n){let r=`${t}:${e}`;Yi.has(r)||(Yi.add(r),console.warn(`hayao/render: skipped '${t}' command \u2014 ${e}`,n))}function Qr(t,e,n){let r=s=>n.x+s*n.w,o=s=>n.y+s*n.h,i;if(e.type==="linear")i=t.createLinearGradient(r(e.x1),o(e.y1),r(e.x2),o(e.y2));else{let s=e.r*Math.max(n.w,n.h);i=t.createRadialGradient(r(e.cx),o(e.cy),0,r(e.cx),o(e.cy),s)}for(let s of e.stops)i.addColorStop(Math.max(0,Math.min(1,s.offset)),s.color);return i}function nt(t){let e=[],n=[],r=[];for(let o of t){let i=o.layer??0;i===.5?n.push(o):i<.5?e.push(o):r.push(o)}return{below:e,light:n,above:r}}function rt(t){if(t.length===0)return null;let e=t[0];if(e.kind!=="rect"||e.blend!=="multiply")return null;let n=e,r=[],o=1;for(;o<t.length;){let i=t[o];if(i.kind!=="circle"||i.blend!=="screen")return null;let s={circle:i,shadows:[]};for(o++;o<t.length&&t[o].kind==="poly"&&t[o].blend==="multiply";)s.shadows.push(t[o]),o++;r.push(s)}return{ambient:n,lights:r}}var Fu=t=>(t.layer??0)===.5;function ot(t,e,n,r,o){let i=Math.min(t.width/e,t.height/n)||1,s=(t.width-e*i)/2,a=(t.height-n*i)/2;return{x:(r-t.left-s)/i,y:(o-t.top-a)/i}}function it(t,e,n){let r=Math.min(t.width/e,t.height/n)||1;return{x:(t.width-e*r)/2,y:(t.height-n*r)/2,width:e*r,height:n*r,scale:r}}var N=t=>Number.isInteger(t)?String(t):(Math.round(t*1e3)/1e3).toString();function zn(t){return`matrix(${N(t.a)} ${N(t.b)} ${N(t.c)} ${N(t.d)} ${N(t.e)} ${N(t.f)})`}function Au(t,e,n){let r=[];return r.push(`fill="${e??t.fill??"none"}"`),t.stroke&&(r.push(`stroke="${t.stroke}"`),r.push(`stroke-width="${N(t.strokeWidth??1)}"`),t.round&&r.push('stroke-linejoin="round" stroke-linecap="round"'),t.lineDash&&t.lineDash.length&&r.push(`stroke-dasharray="${t.lineDash.map(N).join(" ")}"`)),t.opacity!==void 0&&t.opacity!==1&&r.push(`opacity="${N(t.opacity)}"`),n&&r.push(`filter="url(#${n})"`),t.blend&&r.push(`style="mix-blend-mode:${t.blend}"`),r.join(" ")}function Wu(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function Bu(t){let e=t.radius,n=t.cx+j(t.start)*e,r=t.cy+q(t.start)*e,o=t.end-t.start,i=(o%Z+Z)%Z;if(i===0&&o!==0&&(i=Z),i>=Z-1e-9){let c=t.cx+j(t.start+Math.PI)*e,m=t.cy+q(t.start+Math.PI)*e;return`M ${N(n)} ${N(r)} A ${N(e)} ${N(e)} 0 1 1 ${N(c)} ${N(m)} A ${N(e)} ${N(e)} 0 1 1 ${N(n)} ${N(r)} Z`}let s=t.cx+j(t.start+i)*e,a=t.cy+q(t.start+i)*e,l=i>Math.PI?1:0,u=`A ${N(e)} ${N(e)} 0 ${l} 1 ${N(s)} ${N(a)}`;return t.sector?`M ${N(t.cx)} ${N(t.cy)} L ${N(n)} ${N(r)} ${u} Z`:`M ${N(n)} ${N(r)} ${u}`}function zu(t,e,n){let r=`transform="${zn(t.transform)}"`,o,i;if(t.gradient){let a=`${n}g`;e.push(Bn(t.gradient,a)),o=`url(#${a})`}t.shadow&&(i=`${n}s`,e.push(Yr(t.shadow,i)));let s=Au(t,o,i);switch(t.kind){case"rect":return`<rect x="${N(t.x)}" y="${N(t.y)}" width="${N(t.w)}" height="${N(t.h)}"${t.r?` rx="${N(t.r)}"`:""} ${r} ${s}/>`;case"circle":return`<circle cx="${N(t.cx)}" cy="${N(t.cy)}" r="${N(t.radius)}" ${r} ${s}/>`;case"ellipse":return`<ellipse cx="${N(t.cx)}" cy="${N(t.cy)}" rx="${N(t.rx)}" ry="${N(t.ry)}" ${r} ${s}/>`;case"arc":return`<path d="${Bu(t)}" ${r} ${s}/>`;case"poly":{let a=[];for(let u=0;u<t.points.length;u+=2)a.push(`${N(t.points[u])},${N(t.points[u+1])}`);return`<${t.closed?"polygon":"polyline"} points="${a.join(" ")}" ${r} ${s}/>`}case"path":return`<path d="${t.d}" ${r} ${s}/>`;case"text":{let a=t.align==="center"?"middle":t.align==="right"?"end":"start",l=t.font?` font-family="${t.font}"`:"",u=t.weight?` font-weight="${t.weight}"`:"",c=o??t.fill??"#000",m=i?` filter="url(#${i})"`:"",d=t.stroke?` stroke="${t.stroke}" stroke-width="${N(t.strokeWidth??1)}" paint-order="stroke"${t.round?' stroke-linejoin="round"':""}`:"",h=t.opacity!==void 0&&t.opacity!==1?` opacity="${N(t.opacity)}"`:"";return`<text x="${N(t.x)}" y="${N(t.y)}" font-size="${N(t.size)}" text-anchor="${a}" dominant-baseline="middle"${l}${u} fill="${c}"${d}${h}${m} ${r}>${Wu(t.text)}</text>`}case"image":{let a=i?` filter="url(#${i})"`:"";return`<image href="${t.href}" x="${N(t.x)}" y="${N(t.y)}" width="${N(t.w)}" height="${N(t.h)}" ${r}${t.opacity!==void 0&&t.opacity!==1?` opacity="${N(t.opacity)}"`:""}${a}/>`}}}function _u(t){let e=[];for(let n=0;n<t.points.length;n+=2)e.push(`${N(t.points[n])},${N(t.points[n+1])}`);return e.join(" ")}function Ou(t,e,n,r,o){let i=t.ambient,s=`<rect x="${N(i.x)}" y="${N(i.y)}" width="${N(i.w)}" height="${N(i.h)}" transform="${zn(i.transform)}" fill="${i.fill??"#000"}"/>`,a=[];return t.lights.forEach((l,u)=>{let c=l.circle,m=`${n}lg${u}`;c.gradient&&e.push(Bn(c.gradient,m));let d=c.gradient?`url(#${m})`:c.fill??"#fff",h=`<circle cx="${N(c.cx)}" cy="${N(c.cy)}" r="${N(c.radius)}" transform="${zn(c.transform)}" fill="${d}"/>`,p=`${n}lm${u}`,f=l.shadows.map(g=>{let v=`#${(g.opacity!==void 0&&g.opacity!==1?Math.round((1-g.opacity)*255):0).toString(16).padStart(2,"0").repeat(3)}`;return`<polygon points="${_u(g)}" transform="${zn(g.transform)}" fill="${v}"/>`}).join("");l.shadows.length?(e.push(`<mask id="${p}"><rect x="0" y="0" width="${N(r)}" height="${N(o)}" fill="#ffffff"/>${f}</mask>`),a.push(`<g style="mix-blend-mode:screen" mask="url(#${p})">${h}</g>`)):a.push(`<g style="mix-blend-mode:screen">${h}</g>`)}),`<g style="mix-blend-mode:multiply; isolation:isolate">${s}${a.join("")}</g>`}function st(t,e="h",n=1280,r=720){let o=[],i=Ke(t),{below:s,light:a,above:l}=nt(i),u=a.length?rt(a):null,c=u?[...s,...l]:i,m=(h,p)=>h.map((f,g)=>{let k=Zt(f);return k?(Ct(f.kind,k,f),""):zu(f,o,`${e}${p+g}`)}).join(""),d;return u?d=m(s,0)+Ou(u,o,e,n,r)+m(l,s.length):d=m(c,0),(o.length?`<defs>${o.join("")}</defs>`:"")+d}function en(t,e,n,r="#ffffff"){return`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${e} ${n}" width="${e}" height="${n}"><rect x="0" y="0" width="${e}" height="${n}" fill="${r}"/>`+st(t,"h",e,n)+"</svg>"}var Zr="http://www.w3.org/2000/svg",at=class{width;height;background;svg;bg;layer;constructor(e){this.width=e.width,this.height=e.height,this.background=e.background??"#ffffff",this.svg=document.createElementNS(Zr,"svg"),this.svg.setAttribute("viewBox",`0 0 ${this.width} ${this.height}`),this.svg.setAttribute("preserveAspectRatio","xMidYMid meet"),this.svg.style.width="100%",this.svg.style.height="100%",this.svg.style.display="block",this.bg=document.createElementNS(Zr,"rect"),this.bg.setAttribute("x","0"),this.bg.setAttribute("y","0"),this.bg.setAttribute("width",String(this.width)),this.bg.setAttribute("height",String(this.height)),this.bg.setAttribute("fill",this.background),this.svg.appendChild(this.bg),this.layer=document.createElementNS(Zr,"g"),this.svg.appendChild(this.layer)}mount(e){e.appendChild(this.svg)}draw(e){this.layer.innerHTML=st(e)}setBackground(e){this.background=e,this.bg.setAttribute("fill",e)}get element(){return this.svg}toDesign(e,n){return ot(this.svg.getBoundingClientRect(),this.width,this.height,e,n)}viewport(){return it(this.svg.getBoundingClientRect(),this.width,this.height)}dispose(){this.svg.remove()}};function es(t,e){let n=e;if(n.gradient){let r=Kr(e);if(r&&r.w>0&&r.h>0)return Qr(t,n.gradient,r);let o=n.gradient.stops;return o.length?o[o.length-1].color:n.fill}return n.fill}function tn(t,e){let n=es(t,e);n&&n!=="none"&&(t.fillStyle=n,t.fill()),e.stroke&&(t.strokeStyle=e.stroke,t.lineWidth=e.strokeWidth??1,e.round&&(t.lineJoin="round",t.lineCap="round"),t.stroke())}function Gu(t,e,n,r,o,i){let s=Math.min(i,r/2,o/2);t.moveTo(e+s,n),t.arcTo(e+r,n,e+r,n+o,s),t.arcTo(e+r,n+o,e,n+o,s),t.arcTo(e,n+o,e,n,s),t.arcTo(e,n,e+r,n,s),t.closePath()}function ts(t,e){switch(e.kind){case"rect":t.beginPath(),e.r?Gu(t,e.x,e.y,e.w,e.h,e.r):t.rect(e.x,e.y,e.w,e.h),tn(t,e);break;case"circle":t.beginPath(),t.arc(e.cx,e.cy,e.radius,0,Math.PI*2),tn(t,e);break;case"ellipse":t.beginPath(),t.ellipse(e.cx,e.cy,e.rx,e.ry,0,0,Math.PI*2),tn(t,e);break;case"arc":t.beginPath(),e.sector&&t.moveTo(e.cx,e.cy),t.arc(e.cx,e.cy,e.radius,e.start,e.end),e.sector&&t.closePath(),tn(t,e);break;case"poly":t.beginPath();for(let n=0;n<e.points.length;n+=2)n===0?t.moveTo(e.points[n],e.points[n+1]):t.lineTo(e.points[n],e.points[n+1]);e.closed&&t.closePath(),tn(t,e);break;case"path":{let n=new Path2D(e.d),r=es(t,e);r&&r!=="none"&&(t.fillStyle=r,t.fill(n)),e.stroke&&(t.strokeStyle=e.stroke,t.lineWidth=e.strokeWidth??1,e.round&&(t.lineJoin="round",t.lineCap="round"),t.stroke(n));break}case"text":t.font=`${e.weight??400} ${e.size}px ${e.font??"sans-serif"}`,t.textAlign=e.align??"left",t.textBaseline="middle",e.stroke&&(t.strokeStyle=e.stroke,t.lineWidth=e.strokeWidth??1,t.lineJoin="round",t.lineCap="round",t.strokeText(e.text,e.x,e.y)),t.fillStyle=e.fill??"#000",t.fillText(e.text,e.x,e.y);break;case"image":break}}function nn(t,e){let n=Zt(e);if(n){Ct(e.kind,n,e);return}t.save();try{let r=e.transform;t.transform(r.a,r.b,r.c,r.d,r.e,r.f),t.globalAlpha=e.opacity??1;let o=e.shadow;o&&(t.shadowColor=o.color,t.shadowBlur=o.blur,t.shadowOffsetX=o.dx??0,t.shadowOffsetY=o.dy??0);let i=e.lineDash;i&&i.length&&t.setLineDash(i),e.blend&&(t.globalCompositeOperation=e.blend),ts(t,e)}catch(r){Ct(e.kind,"paint threw",r)}t.restore()}var Qi=new WeakMap;function Zi(t,e,n){if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(e,n);let r=t.canvas.ownerDocument;if(r&&typeof r.createElement=="function"){let o=r.createElement("canvas");return o.width=e,o.height=n,o}return null}function Vu(t,e,n){let r=Qi.get(t);if(r&&r.w===e&&r.h===n)return r;let o=Zi(t,e,n),i=Zi(t,e,n);if(!o||!i)return null;o.width=e,o.height=n,i.width=e,i.height=n;let s={buffer:o,scratch:i,w:e,h:n};return Qi.set(t,s),s}function Hu(t,e,n,r,o){let i=Math.max(1,Math.round(n*o)),s=Math.max(1,Math.round(r*o)),a=Vu(t,i,s);if(!a)return!1;let l=a.buffer.getContext("2d"),u=a.scratch.getContext("2d");if(!l||!u)return!1;l.setTransform(1,0,0,1,0,0),l.globalCompositeOperation="source-over",l.clearRect(0,0,i,s),l.setTransform(o,0,0,o,0,0),nn(l,{...e.ambient,blend:void 0});for(let c of e.lights){u.setTransform(1,0,0,1,0,0),u.globalCompositeOperation="source-over",u.clearRect(0,0,i,s),u.setTransform(o,0,0,o,0,0),nn(u,{...c.circle,blend:void 0});for(let m of c.shadows){u.save();let d=m.transform;u.setTransform(o,0,0,o,0,0),u.transform(d.a,d.b,d.c,d.d,d.e,d.f),u.globalCompositeOperation="destination-out",u.globalAlpha=m.opacity??1,ts(u,{...m,blend:void 0,fill:"#000000"}),u.restore()}l.setTransform(1,0,0,1,0,0),l.globalCompositeOperation="lighter",l.globalAlpha=1,l.drawImage(a.scratch,0,0)}return t.save(),t.setTransform(1,0,0,1,0,0),t.globalCompositeOperation="multiply",t.globalAlpha=1,t.drawImage(a.buffer,0,0),t.restore(),t.setTransform(o,0,0,o,0,0),t.globalCompositeOperation="source-over",!0}function _n(t,e,n,r,o,i){t.setTransform(i,0,0,i,0,0),t.globalCompositeOperation="source-over",t.fillStyle=o,t.fillRect(0,0,n,r);let s=Ke(e),{below:a,light:l,above:u}=nt(s);for(let c of a)nn(t,c);if(l.length){let c=rt(l);if(!(c?Hu(t,c,n,r,i):!1)){t.setTransform(i,0,0,i,0,0);for(let d of l)nn(t,d);t.setTransform(i,0,0,i,0,0),t.globalCompositeOperation="source-over"}}t.setTransform(i,0,0,i,0,0);for(let c of u)nn(t,c)}var lt=class{width;height;background;canvas;ctx;dpr=1;constructor(e){this.width=e.width,this.height=e.height,this.background=e.background??"#ffffff",this.canvas=document.createElement("canvas"),this.canvas.style.width="100%",this.canvas.style.height="100%",this.canvas.style.objectFit="contain",this.canvas.style.display="block";let n=this.canvas.getContext("2d");if(!n)throw new Error("hayao: 2D canvas context unavailable");this.ctx=n,this.resize()}mount(e){e.appendChild(this.canvas),this.resize()}resize(){this.dpr=Math.min(3,globalThis.devicePixelRatio||1),this.canvas.width=Math.round(this.width*this.dpr),this.canvas.height=Math.round(this.height*this.dpr)}draw(e){_n(this.ctx,e,this.width,this.height,this.background,this.dpr)}get element(){return this.canvas}toDesign(e,n){return ot(this.canvas.getBoundingClientRect(),this.width,this.height,e,n)}viewport(){return it(this.canvas.getBoundingClientRect(),this.width,this.height)}dispose(){this.canvas.remove()}};var qu=`#version 300 es
|
|
2
2
|
out vec2 v_uv;
|
|
3
3
|
void main() {
|
|
4
4
|
const vec2 CORNERS[4] = vec2[](
|
|
@@ -11,13 +11,13 @@ void main() {
|
|
|
11
11
|
);
|
|
12
12
|
v_uv = UVS[gl_VertexID];
|
|
13
13
|
gl_Position = vec4(CORNERS[gl_VertexID], 0.0, 1.0);
|
|
14
|
-
}`,
|
|
14
|
+
}`,On=`#version 300 es
|
|
15
15
|
precision mediump float;
|
|
16
16
|
in vec2 v_uv;
|
|
17
17
|
uniform sampler2D u_scene;
|
|
18
18
|
uniform sampler2D u_prev;
|
|
19
19
|
out vec4 fragColor;
|
|
20
|
-
void main() { fragColor = texture(u_prev, v_uv); }`,
|
|
20
|
+
void main() { fragColor = texture(u_prev, v_uv); }`,rn={passthrough:On,pixelate:`#version 300 es
|
|
21
21
|
precision mediump float;
|
|
22
22
|
in vec2 v_uv;
|
|
23
23
|
uniform sampler2D u_prev;
|
|
@@ -168,13 +168,13 @@ void main() {
|
|
|
168
168
|
vec4 bloom = texture(u_prev, v_uv);
|
|
169
169
|
float intensity = u_bloom_intensity > 0.0 ? u_bloom_intensity : 0.8;
|
|
170
170
|
fragColor = vec4(scene.rgb + bloom.rgb * intensity, scene.a);
|
|
171
|
-
}`}
|
|
172
|
-
${o}`)}return r}function
|
|
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
|
|
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}
|
|
171
|
+
}`},ju=[{shader:rn.bloomBrightpass},{shader:rn.bloomHBlur},{shader:rn.bloomVBlur},{shader:rn.bloomComposite}];function ns(t,e,n){let r=t.createShader(e);if(!r)throw new Error("hayao/webgl: createShader failed");if(t.shaderSource(r,n),t.compileShader(r),!t.getShaderParameter(r,t.COMPILE_STATUS)){let o=t.getShaderInfoLog(r);throw t.deleteShader(r),new Error(`hayao/webgl: shader compile error
|
|
172
|
+
${o}`)}return r}function Uu(t,e){let n=ns(t,t.VERTEX_SHADER,qu),r=ns(t,t.FRAGMENT_SHADER,e),o=t.createProgram();if(!o)throw new Error("hayao/webgl: createProgram failed");if(t.attachShader(o,n),t.attachShader(o,r),t.linkProgram(o),t.deleteShader(n),t.deleteShader(r),!t.getProgramParameter(o,t.LINK_STATUS)){let i=t.getProgramInfoLog(o);throw t.deleteProgram(o),new Error(`hayao/webgl: program link error
|
|
173
|
+
${i}`)}return o}function rs(t,e,n,r){let o=t.getUniformLocation(e,n);o!==null&&(typeof r=="number"?t.uniform1f(o,r):r.length===2?t.uniform2f(o,r[0],r[1]):r.length===3?t.uniform3f(o,r[0],r[1],r[2]):t.uniform4f(o,r[0],r[1],r[2],r[3]))}function Xu(t,e,n){let r=t.createTexture();t.bindTexture(t.TEXTURE_2D,r),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,e,n,0,t.RGBA,t.UNSIGNED_BYTE,null),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE);let o=t.createFramebuffer();return t.bindFramebuffer(t.FRAMEBUFFER,o),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,r,0),t.bindFramebuffer(t.FRAMEBUFFER,null),{fbo:o,tex:r}}var on=class{width;height;background;glCanvas;gl;offscreen;ctx2d;dpr=1;sceneTex;fbos=[];programs=[];passUniforms=[];vao;framesDrawn=0;uniforms=new Map;constructor(e){this.width=e.width,this.height=e.height,this.background=e.background??"#ffffff",this.glCanvas=document.createElement("canvas"),this.glCanvas.style.width="100%",this.glCanvas.style.height="100%",this.glCanvas.style.objectFit="contain",this.glCanvas.style.display="block";let n=this.glCanvas.getContext("webgl2",{alpha:!1,antialias:!1,preserveDrawingBuffer:!1});if(!n)throw new Error("hayao/webgl: WebGL2 unavailable \u2014 fall back to Canvas2DRenderer");this.gl=n,this.offscreen=document.createElement("canvas");let r=this.offscreen.getContext("2d");if(!r)throw new Error("hayao/webgl: Canvas2D unavailable for rasterization");this.ctx2d=r,this.resize();let o=n.createVertexArray();if(!o)throw new Error("hayao/webgl: createVertexArray failed");this.vao=o;let i=n.createTexture();if(!i)throw new Error("hayao/webgl: createTexture failed");this.sceneTex=i,n.bindTexture(n.TEXTURE_2D,i),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,n.LINEAR),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,n.LINEAR),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE),this.buildPipeline([{shader:e.postProcess??On}])}mount(e){e.appendChild(this.glCanvas),this.resize()}resize(){this.dpr=Math.min(3,globalThis.devicePixelRatio||1);let e=Math.round(this.width*this.dpr),n=Math.round(this.height*this.dpr);this.glCanvas.width=e,this.glCanvas.height=n,this.offscreen.width=e,this.offscreen.height=n,this.gl.viewport(0,0,e,n);for(let r of this.fbos)this.gl.bindTexture(this.gl.TEXTURE_2D,r.tex),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,e,n,0,this.gl.RGBA,this.gl.UNSIGNED_BYTE,null)}buildPipeline(e){let n=this.gl,r=this.glCanvas.width||Math.round(this.width*this.dpr),o=this.glCanvas.height||Math.round(this.height*this.dpr);for(let i of this.programs)n.deleteProgram(i);for(let i of this.fbos)n.deleteFramebuffer(i.fbo),n.deleteTexture(i.tex);this.programs=[],this.fbos=[],this.passUniforms=[];for(let i of e)this.programs.push(Uu(n,i.shader)),this.passUniforms.push(i.uniforms??{});for(let i=0;i<e.length-1;i++)this.fbos.push(Xu(n,r,o))}draw(e){let n=this.gl,r=this.programs.length,o=this.framesDrawn++/60,i=this.glCanvas.width,s=this.glCanvas.height;_n(this.ctx2d,e,this.width,this.height,this.background,this.dpr),n.activeTexture(n.TEXTURE0),n.bindTexture(n.TEXTURE_2D,this.sceneTex),n.texImage2D(n.TEXTURE_2D,0,n.RGBA,n.RGBA,n.UNSIGNED_BYTE,this.offscreen),n.bindVertexArray(this.vao);for(let a=0;a<r;a++){let l=this.programs[a];a===r-1?(n.bindFramebuffer(n.FRAMEBUFFER,null),n.viewport(0,0,i,s)):(n.bindFramebuffer(n.FRAMEBUFFER,this.fbos[a].fbo),n.viewport(0,0,i,s)),n.useProgram(l),n.uniform1i(n.getUniformLocation(l,"u_scene"),0),n.activeTexture(n.TEXTURE1),a===0?n.bindTexture(n.TEXTURE_2D,this.sceneTex):n.bindTexture(n.TEXTURE_2D,this.fbos[a-1].tex),n.uniform1i(n.getUniformLocation(l,"u_prev"),1),n.activeTexture(n.TEXTURE0),n.uniform1f(n.getUniformLocation(l,"u_time"),o),n.uniform2f(n.getUniformLocation(l,"u_resolution"),i,s);for(let[c,m]of this.uniforms)rs(n,l,c,m);for(let[c,m]of Object.entries(this.passUniforms[a]))rs(n,l,c,m);n.drawArrays(n.TRIANGLE_STRIP,0,4)}}setUniform(e,n){return this.uniforms.set(e,n),this}clearUniform(e){return this.uniforms.delete(e),this}setPipeline(e){return this.buildPipeline(e.length?e:[{shader:On}]),this}setPostProcess(e){return this.setPipeline([{shader:e}])}clearPostProcess(){return this.setPostProcess(On)}get element(){return this.glCanvas}toDesign(e,n){return ot(this.glCanvas.getBoundingClientRect(),this.width,this.height,e,n)}viewport(){return it(this.glCanvas.getBoundingClientRect(),this.width,this.height)}dispose(){let e=this.gl;e.deleteTexture(this.sceneTex);for(let n of this.programs)e.deleteProgram(n);for(let n of this.fbos)e.deleteFramebuffer(n.fbo),e.deleteTexture(n.tex);e.deleteVertexArray(this.vao),this.glCanvas.remove()}};var eo=class{width;height;background;last=[];frameCount=0;constructor(e){this.width=e.width,this.height=e.height,this.background=e.background??"#ffffff"}draw(e){this.last=e,this.frameCount++}get commands(){return this.last}count(e){return this.last.filter(n=>n.kind===e).length}toSVGString(){return en(this.last,this.width,this.height,this.background)}};function Ju(t,e,n=0,r=oe){let o=Math.max(0,Math.min(e.border,t.w/2,t.h/2)),i=e.fill??"#fbf6ea",s=e.edge??i,a=e.corner??s,l=[],u=t.x,c=t.x+o,m=t.x+t.w-o,d=t.y,h=t.y+o,p=t.y+t.h-o,f=t.w-2*o,g=t.h-2*o,k=(M,I,x,b,w,C)=>{x<=0||b<=0||l.push({kind:"rect",x:M,y:I,w:x,h:b,r:C,fill:w,transform:r,z:n})};k(c,h,f,g,i),k(c,d,f,o,e.highlight??s),k(c,p,f,o,e.shadow??s),k(u,h,o,g,e.highlight??s),k(m,h,o,g,e.shadow??s);let v=e.radius;return k(u,d,o,o,a,v),k(m,d,o,o,a,v),k(u,p,o,o,a,v),k(m,p,o,o,a,v),e.stroke&&l.push({kind:"rect",x:t.x,y:t.y,w:t.w,h:t.h,r:e.radius,fill:"none",stroke:e.stroke,strokeWidth:e.strokeWidth??2,transform:r,z:n+.001}),l}var Yu={parchment:()=>({border:10,fill:"#fbf6ea",edge:"#efe4c8",corner:"#e2d3a8",highlight:"#fdfaf0",shadow:"#d9c79c",stroke:"#b8a06a",strokeWidth:2,radius:4}),slate:()=>({border:8,fill:"#2c3040",edge:"#363c4f",corner:"#454c63",highlight:"#4a5268",shadow:"#20242f",stroke:"#151821",strokeWidth:2,radius:3})};function Ku(t,e,n=0){let r=[];for(let o=0;o<t;o++){let i=n+o/t*Z;r.push(j(i)*e,q(i)*e)}return r}function Qu(t,e,n,r=-Math.PI/2){let o=[];for(let i=0;i<t*2;i++){let s=i%2===0?e:n,a=r+i/(t*2)*Z;o.push(j(a)*s,q(a)*s)}return o}function Zu(t,e,n=.25,r=7){let o=[];for(let i=0;i<r;i++){let s=i/r*Z,a=e*(1-n+t.float()*n*2);o.push({x:j(s)*a,y:q(s)*a})}return os(o)}function os(t,e=1){let n=t.length;if(n<3)return"";let r=s=>t[(s%n+n)%n],o=s=>Math.round(s*100)/100,i=`M ${o(r(0).x)} ${o(r(0).y)}`;for(let s=0;s<n;s++){let a=r(s-1),l=r(s),u=r(s+1),c=r(s+2),m=l.x+(u.x-a.x)/6*e,d=l.y+(u.y-a.y)/6*e,h=u.x-(c.x-l.x)/6*e,p=u.y-(c.y-l.y)/6*e;i+=` C ${o(m)} ${o(d)}, ${o(h)} ${o(p)}, ${o(u.x)} ${o(u.y)}`}return i+" Z"}function ec(t,e=1){let n=t.length;if(n<2)return"";let r=i=>Math.round(i*100)/100,o=`M ${r(t[0].x)} ${r(t[0].y)}`;for(let i=0;i<n-1;i++){let s=t[Math.max(0,i-1)],a=t[i],l=t[i+1],u=t[Math.min(n-1,i+2)],c=a.x+(l.x-s.x)/6*e,m=a.y+(l.y-s.y)/6*e,d=l.x-(u.x-a.x)/6*e,h=l.y-(u.y-a.y)/6*e;o+=` C ${r(c)} ${r(m)}, ${r(d)} ${r(h)}, ${r(l.x)} ${r(l.y)}`}return o}var Tt=class t{width;height;data;constructor(e,n,r){this.width=e,this.height=n,this.data=r??new Uint8Array(e*n)}get(e,n){return e<0||n<0||e>=this.width||n>=this.height?0:this.data[n*this.width+e]}set(e,n,r){e<0||n<0||e>=this.width||n>=this.height||(this.data[n*this.width+e]=r)}static fromRows(e,n){let r=e.length,o=e.reduce((s,a)=>Math.max(s,a.length),0),i=new t(o,r);for(let s=0;s<r;s++){let a=e[s];for(let l=0;l<a.length;l++)i.data[s*o+l]=n[a[l]]??0}return i}remap(e){let n=new Uint8Array(this.data.length);for(let r=0;r<this.data.length;r++)n[r]=e[this.data[r]]??0;return new t(this.width,this.height,n)}};function is(t){if(typeof t=="bigint")return t;let e=t.trim();return e.startsWith("0x")||e.startsWith("0b")||e.startsWith("0o")?BigInt(e):BigInt("0x"+e)}function tc(t,e,n){let r=is(t),o=e*n,i=new Tt(e,n);for(let s=0;s<o;s++)i.data[s]=Number(r>>BigInt(o-1-s)&1n);return i}function nc(t,e,n){let r=is(t),o=e*n,i=new Tt(e,n);for(let s=0;s<o;s++){let a=BigInt((o-1-s)*2);i.data[s]=Number(r>>a&3n)}return i}function rc(t,e,n){let r=new Tt(e,n),o=0;for(let i=0;i+1<t.length;i+=2){let s=t[i],a=t[i+1];for(let l=0;l<s&&o<r.data.length;l++)r.data[o++]=a}return r}function oc(t){let e=[],n=t.data;for(let r=0;r<n.length;){let o=n[r],i=1;for(;r+i<n.length&&n[r+i]===o;)i++;e.push(i,o),r+=i}return e}function ss(t,e,n={}){let r=n.cell??1,o=n.x??0,i=n.y??0,s=n.z??0,a=n.transform??oe,l=[];for(let u=0;u<t.height;u++){let c=0;for(;c<t.width;){let m=t.get(c,u),d=e[m];if(d==null){c++;continue}let h=1;for(;c+h<t.width&&t.get(c+h,u)===m;)h++;l.push({kind:"rect",x:o+c*r,y:i+u*r,w:h*r,h:r,transform:a,z:s,fill:d}),c+=h}}return l}var to=class extends _{type="TextureSprite";buffer;palette;cell;center;constructor(e){super(e),this.buffer=e.buffer,this.palette=e.palette,this.cell=e.cell??1,this.center=e.center??!0,this.cosmetic=!0}draw(e,n){let r=this.cell,o=this.center?-(this.buffer.width*r)/2:0,i=this.center?-(this.buffer.height*r)/2:0;for(let s of ss(this.buffer,this.palette,{cell:r,x:o,y:i,z:this.z,transform:n}))e.push(s)}};var ic={A:[".#.","#.#","###","#.#","#.#"],B:["##.","#.#","##.","#.#","##."],C:[".##","#..","#..","#..",".##"],D:["##.","#.#","#.#","#.#","##."],E:["###","#..","##.","#..","###"],F:["###","#..","##.","#..","#.."],G:[".##","#..","#.#","#.#",".##"],H:["#.#","#.#","###","#.#","#.#"],I:["#","#","#","#","#"],J:["..#","..#","..#","#.#",".#."],K:["#.#","##.","#..","##.","#.#"],L:["#..","#..","#..","#..","###"],M:["#...#","##.##","#.#.#","#...#","#...#"],N:["#...#","##..#","#.#.#","#..##","#...#"],O:[".#.","#.#","#.#","#.#",".#."],P:["##.","#.#","##.","#..","#.."],Q:[".#.","#.#","#.#","#.#",".##"],R:["##.","#.#","##.","#.#","#.#"],S:[".##","#..",".#.","..#","##."],T:["###",".#.",".#.",".#.",".#."],U:["#.#","#.#","#.#","#.#","###"],V:["#.#","#.#","#.#","#.#",".#."],W:["#...#","#...#","#.#.#","##.##","#...#"],X:["#.#","#.#",".#.","#.#","#.#"],Y:["#.#","#.#",".#.",".#.",".#."],Z:["###","..#",".#.","#..","###"],0:[".#.","#.#","#.#","#.#",".#."],1:[".#.","##.",".#.",".#.","###"],2:["##.","..#",".#.","#..","###"],3:["##.","..#",".#.","..#","##."],4:["#.#","#.#","###","..#","..#"],5:["###","#..","##.","..#","##."],6:[".##","#..","##.","#.#",".#."],7:["###","..#",".#.",".#.",".#."],8:[".#.","#.#",".#.","#.#",".#."],9:[".#.","#.#",".##","..#","##."],".":[".",".",".",".","#"],",":["..","..","..",".#","#."],"!":["#","#","#",".","#"],"?":["##.","..#",".#.","...",".#."],":":[".","#",".","#","."],";":["..",".#","..",".#","#."],"-":["...","...","###","...","..."],"+":["...",".#.","###",".#.","..."],"=":["...","###","...","###","..."],"/":["..#","..#",".#.","#..","#.."],"'":["#","#",".",".","."],'"':["#.#","#.#","...","...","..."],"(":[".#","#.","#.","#.",".#"],")":["#.",".#",".#",".#","#."],"<":["..#",".#.","#..",".#.","..#"],">":["#..",".#.","..#",".#.","#.."],"%":["#.#","..#",".#.","#..","#.#"],"*":["...","#.#",".#.","#.#","..."],"#":["#.#","###","#.#","###","#.#"]},no={height:5,tracking:1,spaceWidth:3,glyphs:ic};function as(t,e={}){let n=[],r=[],o=0,i=0;for(;o<t.length;){let s=t[o];if(s==="{"&&t[o+1]==="{"){n.push({ch:"{",color:r[r.length-1],i:i++}),o+=2;continue}if(s==="{"){let a=t.indexOf("}",o);if(a===-1){n.push({ch:s,color:r[r.length-1],i:i++}),o++;continue}let l=t.slice(o+1,a);l==="/"?r.pop():r.push(l[0]==="#"?l:e[l]??l),o=a+1;continue}n.push({ch:s,color:r[r.length-1],i:i++}),o++}return n}function ls(t,e){if(e===" "||e===`
|
|
174
|
+
`)return e;let n=e.toUpperCase();return t.glyphs[n]?n:t.glyphs[e]?e:t.glyphs["?"]?"?":" "}function us(t,e){if(e===" ")return t.spaceWidth;let n=t.glyphs[e];return n?n[0].length:t.spaceWidth}function Mt(t,e){let n=0;for(let r=0;r<e.length;r++)n+=us(t,e[r].ch),r<e.length-1&&(n+=t.tracking);return n}function sc(t,e){return Mt(t,[...e].map((n,r)=>({ch:ls(t,n),i:r})))}function cs(t,e,n={}){let r=n.lineSpacing??1,o=typeof e=="string"?[...e].map((m,d)=>({ch:m,i:d})):e.map(m=>({...m})),i=[[]];for(let m of o)m.ch===`
|
|
175
|
+
`?i.push([]):i[i.length-1].push({...m,ch:ls(t,m.ch)});let s=[];for(let m of i){if(n.maxWidth===void 0){s.push(m);continue}let d=[],h=[],p=()=>{if(h.length===0)return;let f=d.length?t.spaceWidth+t.tracking:0;d.length&&Mt(t,d)+f+Mt(t,h)>n.maxWidth&&(s.push(d),d=[]),d.length&&d.push({ch:" ",i:-1}),d.push(...h),h=[]};for(let f of m)f.ch===" "?p():h.push(f);p(),s.push(d)}let a=[],l=0;for(let m of s)l=Math.max(l,Mt(t,m));let u=n.maxWidth??l,c=0;for(let m of s){let d=Mt(t,m),h=n.align==="center"?Math.floor((u-d)/2):n.align==="right"?u-d:0;for(let p of m){let f=us(t,p.ch);p.ch!==" "&&a.push({ch:p.ch,color:p.color,i:p.i,x:h,y:c,w:f}),h+=f+t.tracking}c+=t.height+r}return{glyphs:a,width:u,height:s.length*(t.height+r)-r,lines:s.length}}function ms(t,e,n){if(n<=0)return t;let r=Math.floor(e*n);return r<0?0:r>t?t:r}function ds(t,e,n={}){let r=n.cell??2,o=n.x??0,i=n.y??0,s=n.z??0,a=n.transform??oe,l=n.color??"#000",u=n.reveal,c=[];for(let m of e.glyphs){if(u!==void 0&&m.i>=u)continue;let d=t.glyphs[m.ch];if(!d)continue;let h=m.color??l;for(let p=0;p<d.length;p++){let f=d[p],g=0;for(;g<f.length;){if(f[g]!=="#"){g++;continue}let k=1;for(;g+k<f.length&&f[g+k]==="#";)k++;c.push({kind:"rect",x:o+(m.x+g)*r,y:i+(m.y+p)*r,w:k*r,h:r,transform:a,z:s,fill:h}),g+=k}}}return c}var ro=class extends _{type="BitmapText";text;font;cell;color;colorMap;maxWidth;lineSpacing;align;charsPerSec;center;startTime=0;constructor(e){super(e),this.text=e.text,this.font=e.font??no,this.cell=e.cell??2,this.color=e.color??"#000",this.colorMap=e.colorMap??{},this.maxWidth=e.maxWidth,this.lineSpacing=e.lineSpacing??1,this.align=e.align??"left",this.charsPerSec=e.charsPerSec,this.center=e.center??!1,this.cosmetic=!0}onReady(){this.startTime=this.world?.time??0}restartReveal(){this.startTime=this.world?.time??0}buildLayout(){let e=as(this.text,this.colorMap);return cs(this.font,e,{maxWidth:this.maxWidth,lineSpacing:this.lineSpacing,align:this.align})}draw(e,n){let r=this.buildLayout(),o;if(this.charsPerSec!==void 0){let a=(this.world?.time??0)-this.startTime;o=ms(this.text.length,a,this.charsPerSec)}let i=this.center?-(r.width*this.cell)/2:0,s=this.center?-(r.height*this.cell)/2:0;for(let a of ds(this.font,r,{cell:this.cell,x:i,y:s,z:this.z,color:this.color,transform:n,reveal:o}))e.push(a)}};function Rt(t,e,n=0){return{cols:t,rows:e,cells:new Array(t*e).fill(n)}}function hs(t,e,n){return e<0||n<0||e>=t.cols||n>=t.rows?1:t.cells[n*t.cols+e]}function Be(t,e,n,r){e<0||n<0||e>=t.cols||n>=t.rows||(t.cells[n*t.cols+e]=r)}function oo(t,e,n){let r=0;for(let o=-1;o<=1;o++)for(let i=-1;i<=1;i++)i===0&&o===0||hs(t,e+i,n+o)===1&&r++;return r}function ac(t,e=32){let n=t.cells.map(r=>r===1?U.SOLID:U.EMPTY);return{cols:t.cols,rows:t.rows,tileSize:e,tiles:n}}function fs(t,e,n=0){let r=(n^2654435769)>>>0;return r=Math.imul(r^(t|0),2246822507)>>>0,r=Math.imul(r^(e|0),3266489909)>>>0,r^=r>>>13,r=Math.imul(r,668265263)>>>0,r^=r>>>15,r>>>0}function ut(t,e,n=0){return fs(t,e,n)/4294967296}function lc(t,e,n,r=0){return Math.floor(ut(t,e,r)*n)}function bs(t,e,n,r=0){return ut(t,e,r)<n}function uc(t,e,n,r,o,i=0){let s=[];for(let a=e;a<e+r;a++)for(let l=t;l<t+n;l++)bs(l,a,o,i)&&s.push({x:l,y:a});return s}var ps=t=>t*t*(3-2*t);function gs(t,e,n=0){let r=Math.floor(t),o=Math.floor(e),i=ps(t-r),s=ps(e-o),a=ut(r,o,n),l=ut(r+1,o,n),u=ut(r,o+1,n),c=ut(r+1,o+1,n),m=a+(l-a)*i,d=u+(c-u)*i;return m+(d-m)*s}function io(t,e,n=0,r={}){let o=r.octaves??4,i=r.lacunarity??2,s=r.gain??.5,a=1,l=1,u=0,c=0;for(let m=0;m<o;m++)u+=a*gs(t*l,e*l,n+m),c+=a,a*=s,l*=i;return c===0?0:u/c}function cc(t,e){let{cols:n,rows:r}=e,o=e.fill??.45,i=e.steps??4,s=e.birth??5,a=e.survive??4,l=e.border??!0,u=Rt(n,r,0);for(let c=0;c<r;c++)for(let m=0;m<n;m++){let d=l&&(m===0||c===0||m===n-1||c===r-1);Be(u,m,c,d||t.chance(o)?1:0)}for(let c=0;c<i;c++){let m=Rt(n,r,0);for(let d=0;d<r;d++)for(let h=0;h<n;h++){if(l&&(h===0||d===0||h===n-1||d===r-1)){Be(m,h,d,1);continue}let p=oo(u,h,d),f=u.cells[d*n+h]===1;Be(m,h,d,(f?p>=a:p>=s)?1:0)}u=m}return u}function so(t,e){let n=e.scale??.08,r=e.seed??0,o=io(t*n,0,r,e.fractal)*2-1,i=Math.round(e.base+o*e.amplitude);return(e.minRow!==void 0||e.maxRow!==void 0)&&(i=Q(i,e.minRow??-1/0,e.maxRow??1/0)),i}function mc(t,e,n){let r=new Array(e);for(let o=0;o<e;o++)r[o]=so(t+o,n);return r}function dc(t,e,n){return e>=so(t,n)}function ao(t){return{x:Math.floor(t.x+t.w/2),y:Math.floor(t.y+t.h/2)}}function hc(t,e){return t.x<=e.x+e.w&&t.x+t.w>=e.x&&t.y<=e.y+e.h&&t.y+t.h>=e.y}function pc(t,e){for(let n=e.y;n<e.y+e.h;n++)for(let r=e.x;r<e.x+e.w;r++)Be(t,r,n,0)}function ys(t,e,n,r){for(let o=Math.min(e,n);o<=Math.max(e,n);o++)Be(t,o,r,0)}function xs(t,e,n,r){for(let o=Math.min(e,n);o<=Math.max(e,n);o++)Be(t,r,o,0)}function fc(t,e){let{cols:n,rows:r}=e,o=e.attempts??12,i=e.minSize??4,s=e.maxSize??8,a=e.border??!0?1:0,l=Rt(n,r,1),u=[];for(let c=0;c<o;c++){let m=t.intRange(i,s),d=t.intRange(i,s),h=t.intRange(a,n-m-a-1),p=t.intRange(a,r-d-a-1);if(h<a||p<a)continue;let f={x:h,y:p,w:m,h:d};if(!u.some(g=>hc(f,g))){if(pc(l,f),u.length>0){let g=ao(u[u.length-1]),k=ao(f);t.chance(.5)?(ys(l,g.x,k.x,g.y),xs(l,g.y,k.y,k.x)):(xs(l,g.y,k.y,g.x),ys(l,g.x,k.x,k.y))}u.push(f)}}return{rooms:u,grid:l}}var be=44100;function uo(t,e=be){let n=Math.max(0,Math.round(t*e));return{sampleRate:e,left:new Float32Array(n),right:new Float32Array(n)}}function bc(t){return t.left.length}function gc(t){return t.left.length/t.sampleRate}function vs(t){let n=(Q(t,-1,1)+1)*.5*(Math.PI/2);return{l:j(n),r:q(n)}}function co(t,e,n,r=1,o=0){let{l:i,r:s}=vs(o),a=r*i,l=r*s,u=t.left.length,c=Math.round(n);for(let m=0;m<e.length;m++){let d=c+m;if(d<0)continue;if(d>=u)break;let h=e[m];t.left[d]+=h*a,t.right[d]+=h*l}}function ws(t){let e=0,{left:n,right:r}=t;for(let o=0;o<n.length;o++){let i=n[o]<0?-n[o]:n[o];i>e&&(e=i);let s=r[o]<0?-r[o]:r[o];s>e&&(e=s)}return e}function lo(t){return t/Math.sqrt(1+t*t)}function mo(t){let{left:e,right:n}=t;for(let r=0;r<e.length;r++)e[r]=lo(e[r]),n[r]=lo(n[r])}function ho(t,e=.89){let n=ws(t);if(n<1e-9)return;let r=e/n,{left:o,right:i}=t;for(let s=0;s<o.length;s++)o[s]*=r,i[s]*=r}function yc(t){let{left:e,right:n,sampleRate:r}=t,o=e.length,i=2,a=i*2,l=o*a,u=new Uint8Array(44+l),c=new DataView(u.buffer),m=(h,p)=>{for(let f=0;f<p.length;f++)c.setUint8(h+f,p.charCodeAt(f))};m(0,"RIFF"),c.setUint32(4,36+l,!0),m(8,"WAVE"),m(12,"fmt "),c.setUint32(16,16,!0),c.setUint16(20,1,!0),c.setUint16(22,i,!0),c.setUint32(24,r,!0),c.setUint32(28,r*a,!0),c.setUint16(32,a,!0),c.setUint16(34,16,!0),m(36,"data"),c.setUint32(40,l,!0);let d=44;for(let h=0;h<o;h++){let p=Q(e[h],-1,1),f=Q(n[h],-1,1);c.setInt16(d,(p<0?p*32768:p*32767)|0,!0),c.setInt16(d+2,(f<0?f*32768:f*32767)|0,!0),d+=4}return u}function xc(t){let e=2166136261;for(let n=0;n<t.length;n++){let r=Q(t[n],-1,1)*32767|0;e^=r&255,e=Math.imul(e,16777619),e^=r>>8&255,e=Math.imul(e,16777619)}return e>>>0}function vc(t){return{freq:t.freq??220,wave:t.wave??"sine",duty:t.duty??.5,attack:Math.max(0,t.attack??.005),decay:Math.max(0,t.decay??0),sustain:Math.max(0,t.sustain??.08),release:Math.max(0,t.release??.1),sustainLevel:t.sustainLevel??1,punch:t.punch??0,volume:t.volume??.5,slide:t.slide??0,slideAccel:t.slideAccel??0,pitchJump:t.pitchJump??0,pitchJumpTime:t.pitchJumpTime??0,vibrato:t.vibrato??0,vibratoFreq:t.vibratoFreq??6,repeat:Math.max(0,t.repeat??0),detune:t.detune??0,sub:Math.max(0,t.sub??0),noise:t.noise??0,shapeCurve:Math.max(.01,t.shapeCurve??1),fm:t.fm??0,fmFreq:t.fmFreq??0,tremolo:t.tremolo??0,tremoloFreq:t.tremoloFreq??8,bitCrush:Math.max(0,Math.floor(t.bitCrush??0)),lowpass:t.lowpass??0,highpass:t.highpass??0,delay:Math.max(0,t.delay??0),delayFeedback:Math.min(.95,Math.max(0,t.delayFeedback??0))}}function Gn(t){return fe(t/12)}function ks(t,e,n,r){switch(t){case"sine":return q(Z*e);case"saw":return 2*e-1;case"square":return e<n?1:-1;case"triangle":return(e<.5?e*2:2-e*2)*2-1;case"noise":return r.float()*2-1}}function sn(t,e={}){let n=vc(t),r=e.sampleRate??be,o=e.rng??new ue(24301),i=n.attack+n.decay+n.sustain+n.release,s=n.delay>0?n.delay*6:0,a=i+s+.01,l=Math.max(1,Math.round(a*r)),u=new Float32Array(l),c=1/r,m=0,d=0,h=0,p=n.detune!==0?Gn(n.detune/100):1,f=0,g=0,k=0,v=0,M=n.lowpass>0?Ss(n.lowpass,r):1,I=n.highpass>0?1-Ss(n.highpass,r):0,x=r*.5;for(let b=0;b<l;b++){let w=b*c,C=wc(w,n);n.punch>0&&(C*=1+n.punch*Math.max(0,1-w/Math.max(1e-4,n.attack+n.decay))),n.tremolo>0&&(C*=1-n.tremolo*.5*(1-q(Z*n.tremoloFreq*w)));let E=n.repeat>0?w-Math.floor(w/n.repeat)*n.repeat:w,R=i>0?E/i:0,S=n.freq*Gn(n.slide*R+n.slideAccel*R*R);n.pitchJump!==0&&E>=n.pitchJumpTime&&(S*=Gn(n.pitchJump)),n.vibrato>0&&(S*=Gn(n.vibrato*q(Z*n.vibratoFreq*w))),n.fm>0&&(S+=n.fm*q(Z*n.fmFreq*w)),S<0?S=0:S>x&&(S=x),m+=S*c,m-=Math.floor(m);let T=ks(n.wave,m,n.duty,o);n.detune!==0&&(d+=S*p*c,d-=Math.floor(d),T=(T+ks(n.wave,d,n.duty,o))*.5),n.sub>0&&(h+=S*.5*c,h-=Math.floor(h),T=T*(1-n.sub*.5)+q(Z*h)*n.sub),n.noise>0&&(T=T*(1-n.noise)+(o.float()*2-1)*n.noise),n.shapeCurve!==1&&(T=(T<0?-1:1)*Pe(T<0?-T:T,n.shapeCurve)),T*=C*n.volume,n.bitCrush>0&&(b%n.bitCrush===0&&(f=T),T=f),u[b]=T}if(n.lowpass>0)for(let b=0;b<l;b++)g+=M*(u[b]-g),u[b]=g;if(n.highpass>0)for(let b=0;b<l;b++)k=I*(k+u[b]-v),v=u[b],u[b]=k;if(n.delay>0){let b=Math.max(1,Math.round(n.delay*r));for(let w=b;w<l;w++)u[w]+=u[w-b]*n.delayFeedback}return u}function Ss(t,e){let n=Z*t*(1/e);return n/(n+1)}function wc(t,e){let n=e.attack,r=e.decay,o=e.sustain,i=e.release;if(t<n)return n>0?t/n:1;if(t<n+r)return r>0?1+(e.sustainLevel-1)*((t-n)/r):e.sustainLevel;if(t<n+r+o)return e.sustainLevel;let s=t-n-r-o;return s<i&&i>0?e.sustainLevel*(1-s/i):0}var kc={C:0,"C#":1,Db:1,D:2,"D#":3,Eb:3,E:4,Fb:4,"E#":5,F:5,"F#":6,Gb:6,G:7,"G#":8,Ab:8,A:9,"A#":10,Bb:10,B:11,Cb:11,"B#":0},Sc=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];function ce(t){let e=/^([A-Ga-g])([#b]?)(-?\d+)$/.exec(t.trim());if(!e)throw new Error(`bad note name: ${JSON.stringify(t)}`);let n=e[1].toUpperCase(),r=kc[n+(e[2]||"")];if(r===void 0)throw new Error(`bad note name: ${JSON.stringify(t)}`);let o=parseInt(e[3],10);return r+(o+1)*12}function Cc(t){let e=(t%12+12)%12,n=Math.floor(t/12)-1;return Sc[e]+n}function Cs(t,e=440){return e*fe((t-69)/12)}function po(t,e=440){return Cs(typeof t=="number"?t:ce(t),e)}var fo={major:[0,2,4,5,7,9,11],minor:[0,2,3,5,7,8,10],harmonicMinor:[0,2,3,5,7,8,11],melodicMinor:[0,2,3,5,7,9,11],dorian:[0,2,3,5,7,9,10],phrygian:[0,1,3,5,7,8,10],lydian:[0,2,4,6,7,9,11],mixolydian:[0,2,4,5,7,9,10],locrian:[0,1,3,5,6,8,10],majorPentatonic:[0,2,4,7,9],minorPentatonic:[0,3,5,7,10],blues:[0,3,5,6,7,10],chromatic:[0,1,2,3,4,5,6,7,8,9,10,11]};function Vn(t,e="major",n=1){let r=fo[e],o=[];for(let i=0;i<n;i++)for(let s of r)o.push(t+i*12+s);return o.push(t+n*12),o}function bo(t,e="major"){let n=(t%12+12)%12;return new Set(fo[e].map(r=>(n+r)%12))}function Ts(t,e,n,r=3){let o=(n%7+7)%7,i=Vn(t,e,3),s=[];for(let a=0;a<r;a++)s.push(i[o+a*2]);return s}var Tc={i:0,ii:1,iii:2,iv:3,v:4,vi:5,vii:6};function ct(t,e,n){return n.map(r=>{let o=/^([iv]+|[IV]+)(7)?/i.exec(r.trim());if(!o)throw new Error(`bad roman numeral: ${JSON.stringify(r)}`);let i=Tc[o[1].toLowerCase()];if(i===void 0)throw new Error(`bad roman numeral: ${JSON.stringify(r)}`);return Ts(t,e,i,o[2]?4:3)})}function Mc(t,e){return t.map(n=>n+e)}function Hn(t){return t.length<2?t.slice():[t[0]-12,...t.slice(1)].sort((e,n)=>e-n)}function Pt(t){if(t.length===0)return[];let e=[t[0].slice().sort((n,r)=>n-r)];for(let n=1;n<t.length;n++){let r=e[n-1],o=r.reduce((s,a)=>s+a,0)/r.length,i=t[n].map(s=>{let a=s;for(;a-o>6;)a-=12;for(;o-a>6;)a+=12;return a}).sort((s,a)=>s-a);e.push(i)}return e}var Rc=[1116,1188,1277,1356,1422,1491,1557,1617],Pc=[556,441,341,225],Dc=23,Ec=.015,go=class{constructor(e,n,r){this.feedback=n;this.damp=r;this.buf=new Float32Array(Math.max(1,e))}feedback;damp;buf;idx=0;store=0;process(e){let n=this.buf[this.idx];return this.store=n*(1-this.damp)+this.store*this.damp,this.buf[this.idx]=e+this.store*this.feedback,this.idx=(this.idx+1)%this.buf.length,n}},yo=class{constructor(e,n=.5){this.feedback=n;this.buf=new Float32Array(Math.max(1,e))}feedback;buf;idx=0;process(e){let n=this.buf[this.idx],r=-e+n;return this.buf[this.idx]=e+n*this.feedback,this.idx=(this.idx+1)%this.buf.length,r}};function Ms(t,e,n,r){let o=t/44100,i=Rc.map(a=>new go(Math.round((a+r)*o),e,n)),s=Pc.map(a=>new yo(Math.round((a+r)*o),.5));return{combs:i,aps:s}}function xo(t,e={}){let n=Q(e.wet??.25,0,1),r=Q(e.roomSize??.7,0,1),o=Q(e.damp??.5,0,1)*.4,i=.7+r*.28,s=t.sampleRate,a=Ms(s,i,o,0),l=Ms(s,i,o,Dc),u=t.left.length;for(let c=0;c<u;c++){let m=(t.left[c]+t.right[c])*Ec,d=0;for(let p of a.combs)d+=p.process(m);for(let p of a.aps)d=p.process(d);let h=0;for(let p of l.combs)h+=p.process(m);for(let p of l.aps)h=p.process(h);t.left[c]=t.left[c]*(1-n)+d*n,t.right[c]=t.right[c]*(1-n)+h*n}}function Ic(t){let e=0;for(let n of t)e+=n.beats;return e}function Lc(t){let e=0;for(let n of t.sequence)e+=Ic(t.patterns[n]??[]);return e}function Ps(t){let e=0;for(let n of t.tracks)e=Math.max(e,Lc(n));return e}function qn(t){return Ps(t)*60/t.bpm}function vo(t,e={}){let n=e.sampleRate??be,r=t.a4??440,o=60/t.bpm,i=t.tailSec??2,s=qn(t)+i,a=uo(s,n),l=Math.max(0,Math.min(1,t.swing??0)),u=Math.max(0,Math.min(1,t.humanize??0)),c=Math.max(0,Math.min(1,t.velBrightness??.5));if(t.tracks.forEach((m,d)=>{let h=m.gain??.7,p=m.pan??0,f=new ue(5292449^(d+1)*2654435769),g=0;for(let k of m.sequence){let v=m.patterns[k];if(v)for(let M of v){if(M.pitch!==null&&M.pitch!==void 0){let I=Math.round(g*2),b=Math.abs(g*2-I)<1e-4&&I%2===1?g+l*.2:g,w=u>0?f.range(-1,1)*u*.012:0,C=Math.round((b*o+w)*n),E=M.beats*o,R=u>0?f.range(-1,1)*u*.12:0,S=Math.max(.05,Math.min(1,(M.vel??1)+R)),T=Array.isArray(M.pitch)?M.pitch:[M.pitch],L=m.instrument.attack??.005,H=m.instrument.decay??0,$=Math.max(.01,E-L-H),Y=m.instrument.lowpass,K=Y&&c>0?Y*(1-c*(1-S)):Y;for(let te of T){let ee={...m.instrument,freq:po(te,r),sustain:$,volume:(m.instrument.volume??.5)*S,...K!==void 0?{lowpass:K}:{}},ie=sn(ee,{rng:f,sampleRate:n});co(a,ie,Math.max(0,C),h,p)}}g+=M.beats}}}),t.sidechain){let m=Math.max(0,Math.min(1,t.sidechain.depth??.5)),d=(t.sidechain.beatsPerCycle??1)*o;Fc(a,d,m)}return t.reverb&&xo(a,t.reverb),t.master&&Nc(a,t.master),t.master?.compress&&$c(a,t.master.compress),mo(a),ho(a,e.normalizePeak??.89),a}function $c(t,e){let n=Math.max(0,Math.min(1,e)),r=t.sampleRate,o=Rs(-20),i=2+n*3,s=Je(-1/(r*.005)),a=Je(-1/(r*.15)),l=Rs(n*6),u=0,c=t.left,m=t.right;for(let d=0;d<c.length;d++){let h=Math.max(Math.abs(c[d]),Math.abs(m[d])),p=h>u?s:a;u=p*u+(1-p)*h;let f=1;if(u>o){let k=u/o;f=o*Pe(k,1/i)/u}let g=f*l;c[d]*=g,m[d]*=g}}function Rs(t){return fe(t/6.020599913)}function Nc(t,e){let n=t.sampleRate,r=Math.max(0,e.lowCut??0),o=Math.max(0,e.presence??0),i=Math.max(0,e.air??0),s=c=>{let m=Z*c*(1/n);return m/(m+1)},a=s(240),l=1-s(3200),u=1-s(9e3);for(let c of[t.left,t.right]){let m=0,d=0,h=0,p=0,f=0;for(let g=0;g<c.length;g++){let k=c[g];m+=a*(k-m),d=l*(d+k-h),h=k,p=u*(p+k-f),f=k,c[g]=k-r*m+o*d+i*p}}}function Fc(t,e,n){let r=t.sampleRate,o=Math.max(1,e*r);for(let i=0;i<t.left.length;i++){let a=1-i%o/o,l=1-n*a*a;t.left[i]*=l,t.right[i]*=l}}var W={lead:{wave:"square",duty:.5,attack:.008,release:.08,volume:.4,lowpass:4e3,detune:6},pluck:{wave:"triangle",attack:.002,decay:.06,sustainLevel:.3,release:.12,volume:.42},pad:{wave:"saw",attack:.12,release:.5,volume:.26,lowpass:2200,vibrato:.08,vibratoFreq:4,detune:14},bell:{wave:"sine",attack:.002,decay:.3,sustainLevel:.2,release:.5,volume:.4,fm:3,fmFreq:220},piano:{wave:"triangle",attack:.002,decay:.5,sustainLevel:.12,release:.35,volume:.42,lowpass:3600,detune:4},rhodes:{wave:"sine",attack:.003,decay:.45,sustainLevel:.35,release:.4,volume:.4,fm:2.2,fmFreq:440,detune:5},strings:{wave:"saw",attack:.16,decay:.2,sustainLevel:.85,release:.6,volume:.24,lowpass:2600,detune:16,vibrato:.07,vibratoFreq:5},brass:{wave:"saw",attack:.04,decay:.1,sustainLevel:.8,release:.16,volume:.3,lowpass:3200,detune:8,punch:.3},organ:{wave:"sine",attack:.006,release:.05,sustainLevel:1,volume:.32,sub:.5,detune:3},choir:{wave:"triangle",attack:.28,release:.9,sustainLevel:.9,volume:.22,lowpass:2e3,detune:20,vibrato:.1,vibratoFreq:4.5},glocken:{wave:"sine",attack:.001,decay:.6,sustainLevel:0,release:.4,volume:.34,fm:4,fmFreq:1600},vibraphone:{wave:"sine",attack:.002,decay:.5,sustainLevel:.25,release:.7,volume:.4,fm:2,fmFreq:880,tremolo:.25,tremoloFreq:5},clav:{wave:"square",duty:.35,attack:.001,decay:.08,sustainLevel:.25,release:.08,volume:.32,lowpass:3800,detune:4},uprightBass:{wave:"triangle",attack:.004,decay:.12,sustainLevel:.5,release:.1,volume:.5,lowpass:1100,sub:.35},mutedTrumpet:{wave:"saw",attack:.03,decay:.08,sustainLevel:.75,release:.14,volume:.3,lowpass:2600,detune:4,vibrato:.09,vibratoFreq:6},jazzGuitar:{wave:"triangle",attack:.004,decay:.35,sustainLevel:.2,release:.25,volume:.34,lowpass:2400,detune:5},horns:{wave:"saw",attack:.02,decay:.08,sustainLevel:.7,release:.12,volume:.3,lowpass:3600,detune:10,punch:.4},bass:{wave:"saw",attack:.006,release:.06,volume:.5,lowpass:900,detune:6,sub:.3},subBass:{wave:"sine",attack:.004,release:.08,volume:.6,lowpass:400,sub:.5,punch:.2},kick:{wave:"sine",attack:.001,decay:.06,sustainLevel:0,release:.08,slide:-24,volume:.7,sub:.3},snare:{wave:"noise",attack:.001,decay:.05,sustainLevel:.2,release:.12,highpass:1200,volume:.5},hat:{wave:"noise",attack:.001,release:.04,highpass:6e3,volume:.28},rimshot:{wave:"noise",attack:.001,release:.03,highpass:3e3,lowpass:7e3,volume:.3},ride:{wave:"noise",attack:.001,decay:.1,sustainLevel:.14,release:.32,volume:.2,highpass:1600,lowpass:7e3}};var Ac={master:.7,music:.6,sfx:.8,muted:!1},jn=class{_ctx=null;master=null;musicGain=null;sfxGain=null;vol={...Ac};padOn=!1;get ctx(){return this._ctx}get sfxBus(){return this.sfxGain}get musicBus(){return this.musicGain}get available(){return typeof globalThis.AudioContext<"u"||"webkitAudioContext"in globalThis}get started(){return!!this._ctx}start(){if(this._ctx){this._ctx.resume();return}if(!this.available)return;let e=globalThis.AudioContext||globalThis.webkitAudioContext;this._ctx=new e,this.master=this._ctx.createGain(),this.musicGain=this._ctx.createGain(),this.sfxGain=this._ctx.createGain(),this.musicGain.connect(this.master),this.sfxGain.connect(this.master),this.master.connect(this._ctx.destination),this.applyVolumes()}setVolumes(e){this.vol={...this.vol,...e},this.applyVolumes()}getVolumes(){return{...this.vol}}applyVolumes(){if(!this._ctx||!this.master||!this.musicGain||!this.sfxGain)return;let e=this._ctx.currentTime;this.master.gain.setTargetAtTime(this.vol.muted?0:this.vol.master,e,.04),this.musicGain.gain.setTargetAtTime(this.vol.music*.5,e,.04),this.sfxGain.gain.setTargetAtTime(this.vol.sfx,e,.04)}tone(e){if(!this._ctx||!this.sfxGain)return;let{freq:n,duration:r,type:o="sine",gain:i=.2,delay:s=0,pan:a}=e,l=this._ctx.currentTime+s,u=this._ctx.createOscillator();u.type=o,u.frequency.value=n;let c=this._ctx.createGain();if(c.gain.setValueAtTime(0,l),c.gain.linearRampToValueAtTime(i,l+.008),c.gain.exponentialRampToValueAtTime(1e-4,l+r),u.connect(c),a!==void 0&&typeof this._ctx.createStereoPanner=="function"){let m=this._ctx.createStereoPanner();m.pan.value=Math.max(-1,Math.min(1,a)),c.connect(m),m.connect(this.sfxGain)}else c.connect(this.sfxGain);u.start(l),u.stop(l+r+.05)}spatial(e,n,r,o=600,i=.18,s="sawtooth"){if(r>o)return;let a=1-r/o;this.tone({freq:e,duration:i,type:s,gain:.04+a*a*.3,pan:Math.max(-1,Math.min(1,n/(o*.6)))})}play(e){for(let n of e)this.tone(n)}playSpec(e,n={}){if(!this._ctx||!this.sfxGain)return;let r=sn(e,{sampleRate:this._ctx.sampleRate}),o=this._ctx.createBuffer(1,r.length,this._ctx.sampleRate);o.copyToChannel(new Float32Array(r),0);let i=this._ctx.createBufferSource();i.buffer=o;let s=this._ctx.createGain();if(s.gain.value=n.gain??1,i.connect(s),n.pan!==void 0&&typeof this._ctx.createStereoPanner=="function"){let a=this._ctx.createStereoPanner();a.pan.value=Math.max(-1,Math.min(1,n.pan)),s.connect(a),a.connect(this.sfxGain)}else s.connect(this.sfxGain);i.start(this._ctx.currentTime+(n.when??0))}playSong(e,n={}){if(!this._ctx||!this.musicGain)return()=>{};let r=vo(e,{sampleRate:this._ctx.sampleRate}),o=this._ctx.createBuffer(2,r.left.length,this._ctx.sampleRate);o.copyToChannel(new Float32Array(r.left),0),o.copyToChannel(new Float32Array(r.right),1);let i=this._ctx.createBufferSource();return i.buffer=o,n.loop&&(i.loop=!0,i.loopStart=0,i.loopEnd=qn(e)),i.connect(this.musicGain),i.start(),()=>{try{i.stop()}catch{}}}blip(e=520){this.tone({freq:e,duration:.06,type:"sine",gain:.18})}chime(){[523.25,659.25,783.99].forEach((e,n)=>this.tone({freq:e,duration:.9-n*.15,type:"sine",gain:.15,delay:n*.04}))}success(){[392,493.88,587.33,783.99].forEach((e,n)=>this.tone({freq:e,duration:.4,type:"triangle",gain:.15,delay:n*.08}))}thud(){this.tone({freq:130,duration:.14,type:"sine",gain:.22})}startAmbient(e=110,n=[1,1.5,2,2.5]){if(!this._ctx||!this.musicGain||this.padOn)return;this.padOn=!0;let r=this._ctx.createBiquadFilter();r.type="lowpass",r.frequency.value=900,r.connect(this.musicGain);let o=this._ctx.createGain();o.gain.value=0,o.connect(r);for(let i of n){let s=this._ctx.createOscillator();s.type="triangle",s.frequency.value=e*i;let a=this._ctx.createGain();a.gain.value=.1/n.length,s.connect(a),a.connect(o),s.start()}o.gain.setTargetAtTime(.9,this._ctx.currentTime,3)}},je=new jn;function Un(t){let e=t<0?-t:t;return e<1e-12?-1/0:20*Ft(e)}function Dt(t){if(t.length===0)return 0;let e=0;for(let n=0;n<t.length;n++)e+=t[n]*t[n];return Math.sqrt(e/t.length)}function wo(t){let e=0;for(let n=0;n<t.length;n++){let r=t[n]<0?-t[n]:t[n];r>e&&(e=r)}return e}function Ds(t,e=be){if(t.length<2)return 0;let n=0;for(let r=1;r<t.length;r++)(t[r-1]<0&&t[r]>=0||t[r-1]>=0&&t[r]<0)&&n++;return n*e/t.length}function Wc(t){let e=1;for(;e*2<=t;)e*=2;return e}function Es(t,e){let n=t.length;for(let r=1,o=0;r<n;r++){let i=n>>1;for(;o&i;i>>=1)o^=i;if(o^=i,r<o){let s=t[r];t[r]=t[o],t[o]=s;let a=e[r];e[r]=e[o],e[o]=a}}for(let r=2;r<=n;r<<=1){let o=-Z/r,i=j(o),s=q(o);for(let a=0;a<n;a+=r){let l=1,u=0;for(let c=0;c<r/2;c++){let m=a+c,d=m+r/2,h=l*t[d]-u*e[d],p=l*e[d]+u*t[d];t[d]=t[m]-h,e[d]=e[m]-p,t[m]+=h,e[m]+=p;let f=l*i-u*s;u=l*s+u*i,l=f}}}}function Et(t){let e=Wc(t.length);if(e<2)return new Float32Array(0);let n=new Float32Array(e),r=new Float32Array(e);for(let s=0;s<e;s++){let a=.5-.5*j(Z*s/(e-1));n[s]=t[s]*a}Es(n,r);let o=e>>1,i=new Float32Array(o);for(let s=0;s<o;s++)i[s]=Math.sqrt(n[s]*n[s]+r[s]*r[s]);return i}function Is(t,e=be){if(t.length<64)return 0;let r=2048,o=0,i=0;for(let s=0;s+64<=t.length;s+=r){let a=t.subarray(s,Math.min(s+2048,t.length)),l=Et(a),u=e/(l.length*2);for(let c=0;c<l.length;c++)o+=c*u*l[c],i+=l[c]}return i<1e-9?0:o/i}function ko(t,e=1024,n=512){let r=[],o=null;for(let i=0;i+e<=t.length;i+=n){let s=Et(t.subarray(i,i+e)),a=0;if(o){let l=Math.min(s.length,o.length);for(let u=0;u<l;u++){let c=s[u]-o[u];c>0&&(a+=c)}}r.push(a),o=s}return Float32Array.from(r)}function Ls(t,e=be){let r=ko(t,1024,512);if(r.length<3)return 0;let o=0;for(let l=0;l<r.length;l++)o+=r[l];o/=r.length;let i=o*1.5,s=0;for(let l=1;l<r.length-1;l++)r[l]>i&&r[l]>=r[l-1]&&r[l]>r[l+1]&&s++;let a=t.length/e;return a<1e-6?0:s/a}function $s(t,e=be){let r=ko(t,1024,512);if(r.length<8)return 0;let o=e/512,i=Math.max(1,Math.ceil(o*60/200)),s=Math.min(r.length-1,Math.floor(o*60/60)),a=0,l=-1;for(let c=i;c<=s;c++){let m=0;for(let d=c;d<r.length;d++)m+=r[d]*r[d-c];m/=r.length-c,m>l&&(l=m,a=c)}if(a===0)return 0;let u=60*o/a;for(;u>150;)u/=2;for(;u>0&&u<70;)u*=2;return u}function So(t){let e=Dt(t);return e<1e-9?0:Un(wo(t))-Un(e)}function Co(t,e=be){let r=[20,60,250,800,2500,8e3,e/2],o=new Float64Array(6);if(t.length>=64)for(let s=0;s+64<=t.length;s+=2048){let a=Et(t.subarray(s,Math.min(s+2048,t.length))),l=e/(a.length*2);for(let u=0;u<a.length;u++){let c=u*l,m=a[u]*a[u];for(let d=0;d<6;d++)if(c>=r[d]&&c<r[d+1]){o[d]+=m;break}}}let i=o.reduce((s,a)=>s+a,0)||1;return{sub:o[0]/i,bass:o[1]/i,lowMid:o[2]/i,mid:o[3]/i,high:o[4]/i,air:o[5]/i}}function It(t,e=be){return{durationSec:t.length/e,rms:Dt(t),peakDb:Un(wo(t)),centroidHz:Is(t,e),zcr:Ds(t,e),onsetDensity:Ls(t,e),tempoBpm:$s(t,e)}}var Bc={"":[0,4,7],maj:[0,4,7],M:[0,4,7],m:[0,3,7],min:[0,3,7],"-":[0,3,7],dim:[0,3,6],aug:[0,4,8],"+":[0,4,8],6:[0,4,7,9],m6:[0,3,7,9],"-6":[0,3,7,9],69:[0,4,7,9,14],"6/9":[0,4,7,9,14],maj7:[0,4,7,11],M7:[0,4,7,11],maj9:[0,4,7,11,14],"maj7#11":[0,4,7,11,18],maj13:[0,4,7,11,14,21],7:[0,4,7,10],9:[0,4,7,10,14],11:[0,7,10,14,17],13:[0,4,7,10,14,21],"7b9":[0,4,7,10,13],"7#9":[0,4,7,10,15],"7#11":[0,4,7,10,18],"7b13":[0,4,7,10,20],"7b5":[0,4,6,10],"7#5":[0,4,8,10],"13b9":[0,4,7,10,13,21],"13#11":[0,4,7,10,18,21],"9#11":[0,4,7,10,14,18],"7alt":[0,4,10,13,20],m7:[0,3,7,10],min7:[0,3,7,10],"-7":[0,3,7,10],m9:[0,3,7,10,14],m11:[0,3,7,10,14,17],m13:[0,3,7,10,14,21],m7b5:[0,3,6,10],\u00F8:[0,3,6,10],\u00F87:[0,3,6,10],dim7:[0,3,6,9],mMaj7:[0,3,7,11],"m(maj7)":[0,3,7,11],mMaj9:[0,3,7,11,14],sus4:[0,5,7],sus2:[0,2,7],"7sus4":[0,5,7,10],"9sus4":[0,5,7,10,14],add9:[0,4,7,14],madd9:[0,3,7,14]};function Ce(t,e=4){let r=t.trim().split("/"),o=r[0],i=/^([A-Ga-g][#b]?)(.*)$/.exec(o);if(!i)throw new Error(`bad chord symbol: ${JSON.stringify(t)}`);let s=i[1][0].toUpperCase()+(i[1][1]??""),a=i[2],l=Bc[a];if(!l)throw new Error(`unknown chord quality ${JSON.stringify(a)} in ${JSON.stringify(t)}`);let u=ce(s+e),c=l.map(m=>u+m);if(r.length===2){let m=/^([A-Ga-g][#b]?)$/.exec(r[1].trim());if(m){let d=m[1][0].toUpperCase()+(m[1][1]??""),h=ce(d+(e-1));for(;h>=c[0];)h-=12;c.unshift(h)}}return c}function an(t,e){let n=t.slice(1);if(e===void 0||n.length===0)return n;let r=n.reduce((i,s)=>i+s,0)/n.length,o=Math.round((e-r)/12)*12;return n.map(i=>i+o).sort((i,s)=>i-s)}function zc(t,e=4){return t.map(n=>Ce(n,e))}function Ns(t){try{return typeof t=="number"?t:ce(t)}catch{return null}}function _c(t){return t.pitch===null||t.pitch===void 0?[]:Array.isArray(t.pitch)?t.pitch:[t.pitch]}function Oc(t,e={}){let n=[],r=[];(!(t.bpm>0)||t.bpm<20||t.bpm>400)&&n.push(`bpm ${t.bpm} out of sane range [20,400]`),(!t.tracks||t.tracks.length===0)&&n.push("song has no tracks");let o=e.key?bo(Ns(e.key.tonic)??0,e.key.mode):null,i=0,s=0,a=new Map;if(t.tracks.forEach((u,c)=>{let m=u.name??`track ${c}`;(!u.patterns||u.patterns.length===0)&&n.push(`${m}: no patterns`),(!u.sequence||u.sequence.length===0)&&n.push(`${m}: empty sequence`),u.pan!==void 0&&(u.pan<-1||u.pan>1)&&n.push(`${m}: pan ${u.pan} out of [-1,1]`);for(let d of u.sequence??[]){if(d<0||d>=(u.patterns?.length??0)){n.push(`${m}: sequence references missing pattern ${d}`);continue}let h=`${c}:${d}`;a.set(h,(a.get(h)??0)+1);for(let p of u.patterns[d]){p.beats>0||n.push(`${m}: note with non-positive beats ${p.beats}`),p.vel!==void 0&&(p.vel<0||p.vel>1)&&n.push(`${m}: velocity ${p.vel} out of [0,1]`);for(let f of _c(p)){let g=Ns(f);if(g===null){n.push(`${m}: unparseable pitch ${JSON.stringify(f)}`);continue}(g<0||g>127)&&n.push(`${m}: pitch ${f} outside MIDI 0..127`),i++,o&&!o.has((g%12+12)%12)&&s++}}}}),o&&i>0){let u=s/i,c=e.maxOutOfKey??1,m=`${s}/${i} notes (${Math.round(u*100)}%) out of key`;u>c?n.push(m):s>0&&r.push(m)}return![...a.values()].some(u=>u>1)&&t.tracks.length>0&&r.push("no pattern is reused \u2014 piece may lack structure/repetition"),{ok:n.length===0,errors:n,warnings:r}}function Gc(t){return t.length===0?!1:(r=>r.trim().toLowerCase().replace(/7$/,""))(t[t.length-1])==="i"}var Vc={tempoBpm:20,centroidHz:1200,rms:.1,zcr:1500,onsetDensity:4,peakDb:6},Hc={tempoBpm:["too slow","too fast"],centroidHz:["too dark / muffled","too bright / harsh"],rms:["too quiet","too loud"],zcr:["too smooth / tonal","too noisy / gritty"],onsetDensity:["too sparse","too busy"],peakDb:["more headroom than reference","hotter / less headroom than reference"]};function Fs(t,e,n={}){let r={...Vc,...n},o=Object.keys(r),i=[],s=0;for(let c of o){let m=t[c],d=e[c],h=Number.isFinite(m)?m:0,p=Number.isFinite(d)?d:0,f=(p-h)/r[c];s+=f*f;let[g,k]=Hc[c],v=Math.abs(f)<.25?"ok":f<0?g:k;i.push({feature:c,reference:h,candidate:p,normalized:f,note:v})}i.sort((c,m)=>Math.abs(m.normalized)-Math.abs(c.normalized));let a=Math.sqrt(s/o.length),l=i[0],u=Math.abs(l.normalized)<.25?"close match":`${l.feature}: ${l.note}`;return{distance:a,deltas:i,headline:u}}function qc(t,e){let n=Fs(t,e),r=n.deltas.filter(o=>o.note!=="ok").map(o=>` ${o.feature.padEnd(13)} ${o.candidate.toFixed(1)} vs ${o.reference.toFixed(1)} \u2192 ${o.note}`);return`match distance ${n.distance.toFixed(3)} \u2014 ${n.headline}
|
|
176
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=`
|
|
177
|
+
`):" (all features within tolerance)")}function jc(t,e){if(t.length===0)return 0;let n=t.length>1?[...t].sort((r,o)=>r.x-o.x):t;if(e<=n[0].x)return n[0].y;if(e>=n[n.length-1].x)return n[n.length-1].y;for(let r=1;r<n.length;r++)if(e<=n[r].x){let o=n[r-1],i=n[r],s=i.x===o.x?0:(e-o.x)/(i.x-o.x);return o.y+(i.y-o.y)*s}return n[n.length-1].y}function As(t,e,n=1,r=1e4,o=1){let i=Math.max(1e-6,n);switch(t){case"linear":{let s=Q(e,i,r);return 1-o*(s-i)/Math.max(1e-6,r-i)}case"inverse":{let s=Math.max(e,i);return i/(i+o*(Math.max(s,i)-i))}case"exponential":{let s=Math.max(e,i);return fe(-o*ft(s/i))}}}function Ws(t,e=400){return Q(t/e,-1,1)}function Uc(t,e,n=600,r=1){let o=Math.sqrt(t*t+e*e);return o>n?{gain:0,pan:0,audible:!1}:{gain:As("inverse",o,n*.15,n,r),pan:Ws(t,n*.7),audible:!0}}function Xc(t,e){let n={};for(let r of t){let o=Math.max(1e-6,r.full-r.fadeIn),i=Q((e-r.fadeIn)/o,0,1)*(r.maxGain??1);n[r.name]=i}return n}function Jc(t,e=-12){return t?fe(e/6.0206):1}function Bs(t){let e=t.left.length,n=new Float32Array(e),r=new Float32Array(e);for(let i=0;i<e;i++)n[i]=(t.left[i]+t.right[i])*.5,r[i]=(t.left[i]-t.right[i])*.5;let o=Dt(n);return o<1e-9?0:Dt(r)/o}var Yc={electronic:{tempo:[118,132],centroid:[3e3,7200],onsets:[7,15],rms:[.16,.27],crestDb:[6,15],width:[.03,.6],maxMud:.34},lofi:{tempo:[70,88],centroid:[1600,4300],onsets:[5,13],rms:[.12,.24],crestDb:[7,17],width:[.04,.6],maxMud:.5},piano:{tempo:[58,100],centroid:[700,2100],onsets:[3,11],rms:[.1,.22],crestDb:[9,22],width:[.04,.7],maxMud:.42},orchestral:{tempo:[80,96],centroid:[1100,3e3],onsets:[4,12],rms:[.11,.22],crestDb:[8,21],width:[.05,.7],maxMud:.4},jazzfunk:{tempo:[106,126],centroid:[2200,5600],onsets:[6,16],rms:[.13,.25],crestDb:[7,18],width:[.04,.6],maxMud:.4}};function Ee(t,[e,n]){if(t>=e&&t<=n)return 1;let r=Math.max(1e-6,n-e),o=t<e?e-t:t-n;return Math.max(0,1-o/(r*.6))}function Kc(t,e){let n=new Float32Array(t.left.length);for(let k=0;k<n.length;k++)n[k]=(t.left[k]+t.right[k])*.5;let r=It(n),o=So(n),i=Co(n),s=Bs(t),a=i.lowMid,l=i.high+i.air,u=i.sub+i.bass,c={loudness:Ee(r.rms,e.rms),headroom:r.peakDb<=-.5?r.peakDb>=-3?1:Ee(r.peakDb,[-3,-.5]):0,dynamics:Ee(o,e.crestDb),width:Ee(s,e.width),brightness:Ee(r.centroidHz,e.centroid),density:Ee(r.onsetDensity,e.onsets),tempo:Ee(r.tempoBpm,e.tempo),lowEnd:Ee(u,[.12,.7]),clarity:Ee(a,[0,e.maxMud??.34]),smoothness:Ee(l,[0,.4])},m={loudness:1.2,headroom:1.4,dynamics:1,width:.7,brightness:1.1,density:.9,tempo:.7,lowEnd:1,clarity:1.2,smoothness:1.1},d=0,h=0;for(let k of Object.keys(c))d+=c[k]*m[k],h+=m[k];let p=Math.round(d/h*100),f=[],g=(k,v)=>{c[k]<.75&&f.push(`${k}: ${v}`)};return g("loudness",`rms ${r.rms.toFixed(3)} (target ${e.rms.join("\u2013")})`),g("headroom",`peak ${r.peakDb.toFixed(1)}dB (want \u2264 \u22120.5, \u2265 \u22123)`),g("dynamics",`crest ${o.toFixed(1)}dB (target ${e.crestDb.join("\u2013")})`),g("width",`width ${s.toFixed(2)} (target ${e.width.join("\u2013")})`),g("brightness",`centroid ${Math.round(r.centroidHz)}Hz (target ${e.centroid.join("\u2013")})`),g("density",`onsets ${r.onsetDensity.toFixed(1)}/s (target ${e.onsets.join("\u2013")})`),g("tempo",`tempo ${Math.round(r.tempoBpm)} (target ${e.tempo.join("\u2013")})`),g("lowEnd",`low-end fraction ${u.toFixed(2)} (want 0.12\u20130.62)`),g("clarity",`low-mid mud ${a.toFixed(2)} (want \u2264 ${(e.maxMud??.34).toFixed(2)})`),g("smoothness",`high/air ${l.toFixed(2)} (want \u2264 0.40)`),{score:p,dims:c,notes:f}}var P=(t,e,n=1)=>({pitch:t,beats:e,vel:n}),V=t=>({pitch:null,beats:t});function zs(t,e,n,r=.9){let o=[];for(let i=0;i<e;i++)o.push(P(t[i%t.length]+Math.floor(i/t.length)*12,n,r));return o}function Qc(t,e,n=1){return Array.from({length:e},()=>P(t,1,n))}function Zc(){let t=ct(ce("A3"),"minor",["i","VI","III","VII"]),e=t.map(a=>a[0]-12),n={name:"sub",instrument:W.subBass,gain:.6,patterns:e.map(a=>[P(a,.5,1),P(a,.5,.6),P(a,.5,.85),P(a,.5,.6),P(a,.5,1),P(a,.5,.6),P(a,.5,.85),P(a,.5,.7)]),sequence:[0,1,2,3,0,1,2,3]},r={name:"kick",instrument:W.kick,gain:.82,patterns:[Qc("A1",4)],sequence:Array(8).fill(0)},o={name:"hat",instrument:W.hat,gain:.42,pan:.15,patterns:[[V(.5),P("A6",.5,.7),V(.5),P("A6",.5,.5)]],sequence:Array(16).fill(0)},i={name:"pluck",instrument:{...W.pluck,release:.16,lowpass:2400},gain:.62,pan:-.2,patterns:t.map(a=>zs([a[0],a[1],a[2]],4,1,.7)),sequence:[0,1,2,3,0,1,2,3]},s={name:"lead",instrument:{...W.lead,detune:8,lowpass:2800},gain:.52,pan:.1,patterns:[[P(t[0][2]+12,.75),P(t[0][2]+14,.25),P(t[0][0]+12,1),P(t[0][1]+12,2)],[P(t[1][2]+12,1),P(t[1][1]+12,.5),P(t[1][2]+12,.5),P(t[1][0]+24,2)],[P(t[2][2]+12,.75),P(t[2][1]+12,.25),P(t[2][0]+12,1),P(t[2][2]+12,2)],[P(t[3][0]+24,1),P(t[3][2]+12,.5),P(t[3][1]+12,.5),P(t[3][0]+12,2)]],sequence:[0,1,2,3]};return{bpm:126,tracks:[r,n,o,i,s],reverb:{wet:.15,roomSize:.6,damp:.5},humanize:.05,sidechain:{depth:.55,beatsPerCycle:1},master:{lowCut:.35,presence:.2,air:.08}}}function em(){let t=ce("C4"),e=Pt(ct(t,"major",["IV7","iii7","ii7","I7"]).map(Hn)),n=e.map(c=>c[0]-12),r={name:"rhodes",instrument:{...W.rhodes,volume:.42,lowpass:2600,fm:1.6},gain:.66,pan:-.1,patterns:e.map(c=>[P(c.map(m=>m),3.5,.75),V(.5)]),sequence:[0,1,2,3,0,1,2,3]},o={name:"bass",instrument:{...W.bass,lowpass:650,sub:.28},gain:.72,pan:.05,patterns:n.map(c=>[P(c,1.5,.9),V(.5),P(c+7,1,.7),P(c+5,1,.6)]),sequence:[0,1,2,3,0,1,2,3]},i={name:"kick",instrument:{...W.kick,volume:.75},gain:.82,patterns:[[P("C2",1,.9),V(1),P("C2",.5,.6),V(.5),P("C2",.5,.4),V(.5)]],sequence:Array(8).fill(0)},s={name:"snare",instrument:{...W.rimshot,volume:.24,lowpass:4e3},gain:.6,patterns:[[V(1),P("C4",1,.7),V(1),P("C4",1,.7)]],sequence:Array(8).fill(0)},a={name:"hat",instrument:{...W.hat,volume:.14,highpass:2500,lowpass:6e3},gain:.45,pan:.2,patterns:[[P("C6",.5,.5),P("C6",.5,.3)]],sequence:Array(16).fill(0)},l={name:"vinyl",instrument:{wave:"noise",attack:.5,release:.5,sustainLevel:1,volume:.022,lowpass:2800,highpass:400},gain:.3,patterns:[[P("C4",16,1)]],sequence:[0]},u={name:"keys",instrument:{...W.piano,volume:.3,lowpass:2800},gain:.48,pan:.15,patterns:[[P(e[0][2]+12,1,.7),V(1),P(e[0][1]+12,.5,.55),P(e[0][2]+12,.5,.5),V(1)],[V(.5),P(e[1][2]+12,1,.7),V(.5),P(e[1][1]+12,2,.55)],[P(e[2][2]+12,1.5,.7),P(e[2][1]+12,.5,.5),V(2)],[V(1),P(e[3][2]+12,1,.7),P(e[3][1]+12,1,.55),V(1)]],sequence:[0,1,2,3,0,1,2,3]};return{bpm:78,tracks:[l,r,o,i,s,a,u],swing:.75,humanize:.4,velBrightness:.7,reverb:{wet:.24,roomSize:.7,damp:.65},master:{lowCut:.26,presence:.22,air:.05}}}function tm(){let t=ce("A3"),e=Pt(ct(t,"minor",["i","VI","III","VII"])),n=[a=>[P(a[0],1,.85),P(a[2],1,.55),V(2)],a=>[P(a[2],1.5,.8),V(.5),P(a[1],2,.5)],a=>[V(1),P(a[1]+12,1.5,.7),V(1.5)],a=>[P(a[0],2,.8),P(a[2],1,.55),V(1)]],r={name:"piano",instrument:{...W.piano,volume:.46},gain:.78,pan:-.05,patterns:e.map((a,l)=>n[l%n.length](a)),sequence:[0,1,2,3,0,1,2,3]},o={name:"strings",instrument:{...W.strings,attack:.4},gain:.5,pan:.1,patterns:e.map(a=>[P(a.map(l=>l-12),4,.65)]),sequence:[0,1,2,3,0,1,2,3]},i={name:"sub",instrument:{...W.subBass,volume:.4,attack:.03},gain:.55,patterns:e.map(a=>[P(a[0]-24,4,.6)]),sequence:[0,1,2,3,0,1,2,3]},s={name:"melody",instrument:{...W.piano,volume:.4,lowpass:3e3},gain:.5,pan:.12,patterns:[[V(2),P(e[0][2]+12,1,.75),P(e[0][1]+12,1,.55)],[P(e[1][2]+12,2,.8),P(e[1][1]+12,1,.55),V(1)],[V(1.5),P(e[2][2]+12,1.5,.75),P(e[2][1]+12,1,.55)],[P(e[3][1]+12,1.5,.7),P(e[3][0]+12,2.5,.6)]],sequence:[0,1,2,3,0,1,2,3]};return{bpm:66,tracks:[i,o,r,s],humanize:.5,velBrightness:.75,reverb:{wet:.38,roomSize:.86,damp:.55},master:{lowCut:.4,presence:.28,air:.12}}}function nm(){let t=ce("D3"),e=Pt(ct(t,"minor",["i","VI","III","VII","VI","VII","i","i"])),n=Vn(ce("D4"),"minor",3),r=m=>n[(m%n.length+n.length)%n.length],o={name:"strings",instrument:{...W.strings,volume:.24},gain:.7,pan:-.15,patterns:e.map(m=>zs([m[0],m[1],m[2],m[0]+12],8,.5,.75)),sequence:[0,1,2,3,4,5,6,7]},i=[[P(r(0),2,.9),P(r(1),1,.8),P(r(2),1,.85)],[P(r(4),3,.95),P(r(2),1,.8)],[P(r(1),2,.85),P(r(0),1,.8),P(r(1),1,.8)],[P(r(4),2,.9),P(r(5),2,.95)],[P(r(5),2,.95),P(r(4),1,.85),P(r(2),1,.8)],[P(r(4),2,.9),P(r(6),2,.95)],[P(r(7),3,1),P(r(6),1,.85)],[P(r(7),4,1)]],s=[V(4)],a={name:"brass",instrument:{...W.brass,volume:.32},gain:.62,pan:.15,patterns:[s,...i],sequence:[0,0,1,2,3,4,5,6]},l={name:"choir",instrument:{...W.choir,volume:.18},gain:.5,pan:.05,patterns:e.map(m=>[P([m[2]+12,m[0]+24],4,.6)]),sequence:[0,1,2,3,4,5,6,7]},u={name:"timpani",instrument:{...W.kick,decay:.14,release:.25,slide:-12,volume:.85,sub:.5},gain:.82,patterns:[[P("D2",1,1),P("D2",1,.6),P("D2",.5,.85),P("D2",.5,.6),P("D2",1,.9)]],sequence:Array(8).fill(0)},c={name:"glocken",instrument:W.glocken,gain:.32,pan:.25,patterns:[s,...e.map(m=>[V(1),P(m[2]+24,1,.55),V(1),P(m[1]+24,1,.5)])],sequence:[0,0,3,4,5,6,7,8]};return{bpm:88,tracks:[u,o,a,l,c],humanize:.14,velBrightness:.5,reverb:{wet:.32,roomSize:.9,damp:.4},master:{lowCut:.4,presence:.32,air:.14}}}function rm(){let t=ce("C4"),e=ct(t,"major",["ii7","V7","I7","vi7"]),n=Pt(e.map(Hn)),r=e.map((c,m)=>{let d=e[(m+1)%e.length][0]-24,h=c[0]-24,p=c[1]-24,f=c[2]-24,g=d+(h<d?-1:1);return[P(h,1,.95),P(p,1,.75),P(f,1,.8),P(g,1,.7)]}),o={name:"bass",instrument:{...W.bass,lowpass:1e3,sub:.35,release:.12},gain:.74,patterns:r,sequence:[0,1,2,3,0,1,2,3]},i={name:"rhodes",instrument:{...W.rhodes,volume:.3},gain:.62,pan:-.15,patterns:n.map(c=>[V(.5),P(c.map(m=>m),.75,.7),V(.75),P(c.map(m=>m),.5,.55),V(1.5)]),sequence:[0,1,2,3,0,1,2,3]},s={name:"brass",instrument:{...W.brass,release:.1,volume:.24},gain:.55,pan:.2,patterns:[[V(2),P(n[0].map(c=>c+12),.5,.85),V(1.5)],[V(3),P(n[1].map(c=>c+12),.5,.85),V(.5)],[P(n[2].map(c=>c+12),.5,.8),V(3.5)],[V(2.5),P(n[3].map(c=>c+12),.5,.8),V(1)]],sequence:[0,1,2,3,0,1,2,3]},a={name:"ride",instrument:{...W.hat,volume:.13,highpass:3e3,lowpass:9e3,release:.08},gain:.5,pan:.1,patterns:[[P("C6",.5,.6),P("C6",.5,.35),P("C6",.5,.5),P("C6",.5,.35)]],sequence:Array(16).fill(0)},l={name:"snare",instrument:{...W.snare,volume:.28,highpass:900},gain:.5,patterns:[[V(1),P("D4",1,.6),V(1),P("D4",1,.7)]],sequence:Array(8).fill(0)},u={name:"kick",instrument:{...W.kick,volume:.55},gain:.62,patterns:[[P("C2",1,.85),V(1.5),P("C2",.5,.6),V(1)]],sequence:Array(8).fill(0)};return{bpm:116,tracks:[o,i,s,u,l,a],swing:.66,humanize:.35,velBrightness:.6,reverb:{wet:.16,roomSize:.55,damp:.5},master:{lowCut:.5,presence:.18,air:.07}}}var _s=[{id:"electronic",name:"Minimal Electronic",description:"Bass-driven four-on-the-floor in A minor \u2014 pulsing sidechained sub, offbeat hats, a synth hook.",make:Zc},{id:"lofi",name:"Lo-fi Beats",description:"Swung, dusty jazz sevenths on a Rhodes with warm bass, brushed drums and vinyl crackle.",make:em},{id:"piano",name:"Melancholic Piano",description:"Slow, sad A-minor piano with space and rubato over a string bed in a big room.",make:tm},{id:"orchestral",name:"Epic Orchestral",description:"Uplifting D-minor with a soaring brass theme, arpeggiated strings, choir, timpani and glockenspiel.",make:nm},{id:"jazzfunk",name:"Jazz Funk",description:"Swung ii\u2013V\u2013I with a walking bass that chromatically approaches each chord, Rhodes comping and brass stabs.",make:rm}];function om(t){return _s.find(e=>e.id===t)}var Os=["sine","triangle","saw","square","noise"],To=new Set;function Xn(t,e){To.has(t)||(To.add(t),console.warn(`[hayao] specFromZzfx: ${t} ${e}`))}function im(){To.clear()}function sm(t){let e=t[0]??1,n=t[1]??.05,r=t[2]??220,o=t[3]??0,i=t[4]??0,s=t[5]??.1,a=t[6]??0,l=t[7]??1,u=t[8]??0,c=t[9]??0,m=t[10]??0,d=t[11]??0,h=t[12]??0,p=t[13]??0,f=t[14]??0,g=t[15]??0,k=t[16]??0,v=t[17]??1,M=t[18]??0,I=t[19]??0,x=t[20]??0,b=o+M+i+s,w={freq:r,volume:e,attack:o,decay:M,sustain:i,release:s,sustainLevel:v},C=Math.max(0,Math.min(Os.length-1,Math.round(a)));if(w.wave=Os[C],Math.round(a)===3&&Xn("shape=3 (tan)","has no hayao wave; approximated as a hard square."),l!==1&&(w.shapeCurve=l),n!==0&&Xn("randomness","is dropped: hayao specs are deterministic (same spec \u2192 same samples)."),u!==0&&(w.slide=u*b),c!==0&&(w.slideAccel=c*b*b/2),m!==0){let E=r+m;E>0&&r>0?(w.pitchJump=12*ft(E/r),w.pitchJumpTime=d):Xn("pitchJump","would drive frequency to \u2264 0 Hz; dropped.")}return h>0&&(w.repeat=h),p!==0&&(w.noise=Math.max(0,Math.min(1,p))),f!==0&&(Xn("modulation","is approximated as vibrato (pitch LFO at |modulation| Hz)."),w.vibrato=.6,w.vibratoFreq=Math.abs(f)),g>0&&(w.bitCrush=Math.max(1,Math.round(g*100))),I!==0&&(w.tremolo=Math.max(0,Math.min(1,I))),k>0&&(w.delay=k,w.delayFeedback=.5),x>0?w.lowpass=x:x<0&&(w.highpass=-x),w}var y=(t,e,n=1)=>({pitch:t,beats:e,vel:n}),F=t=>({pitch:null,beats:t});function Mo(t,e=2){return t.map((n,r)=>{let o=Ce(n,e),i=o[0],s=o[1]??i+3,a=o[2]??i+7,l=Ce(t[(r+1)%t.length],e)[0],u=l+(i<=l?-1:1);return[y(i,1,.92),y(s,1,.72),y(a,1,.78),y(u,1,.7)]})}function Yn(t,e=4,n="F4",r=.66){let o=ce(n);return t.map((i,s)=>{let a=an(Ce(i,e),o);return s%2===0?[y(a,1,r),F(.5),y(a,.5,r*.8),F(2)]:[F(1.5),y(a,.5,r*.85),F(1),y(a,.5,r*.7),F(.5)]})}function am(t,e=4,n="F4",r=.6){let o=ce(n);return t.map(i=>[y(an(Ce(i,e),o),4,r)])}var lm=()=>[y("C6",1,.55),y("C6",.5,.35),y("C6",.5,.5),y("C6",1,.55),y("C6",.5,.35),y("C6",.5,.5)],um=()=>[F(1),y("C6",1,.5),F(1),y("C6",1,.5)];function ln(t=.42,e=8){return{name:"ride",instrument:W.ride,gain:t,pan:.12,patterns:[lm()],sequence:Array(e).fill(0)}}function Ro(t=.4,e=8){return{name:"hat",instrument:{...W.hat,highpass:5e3,volume:.2},gain:t,pan:-.1,patterns:[um()],sequence:Array(e).fill(0)}}function Kn(t=.32,e=8){return{name:"vinyl",instrument:{wave:"noise",attack:.6,release:.6,sustainLevel:1,volume:.03,lowpass:3e3,highpass:380},gain:t,patterns:[[y("C4",e*4,1)]],sequence:[0]}}var Jn=["F5","Gb5","Bb5","Ab5"];function cm(){let t=["Bbm9","Bbm9","Ebm9","Ab13","Dbmaj7","Gm7b5","C7alt","Fm7"],n={name:"bass",instrument:{...W.uprightBass,volume:.5},gain:.7,patterns:[[y("Bb1",.75,.95),y("Bb1",.25,.5),F(.5),y("Db2",.5,.7),y("F2",.5,.75),y("Ab1",.5,.6),y("Bb1",1,.7)],...Mo(t.slice(2),2)],sequence:[0,0,1,2,3,4,5,6]},r={name:"rhodes",instrument:{...W.rhodes,volume:.32},gain:.6,pan:-.18,patterns:Yn(t,4,"Ab4",.62),sequence:[0,1,2,3,4,5,6,7]},o={name:"trumpet",instrument:{...W.mutedTrumpet,volume:.34},gain:.62,pan:.14,patterns:[[y(Jn[0],.5,.85),y(Jn[1],.5,.7),y(Jn[2],1,.9),y(Jn[3],.5,.75),F(1.5)],[y("F5",.5,.8),y("Db5",.5,.7),y("Bb4",1.5,.85),F(1.5)],[y("C5",.5,.85),y("Db5",.5,.72),y("F5",1,.9),y("Eb5",.5,.75),F(1.5)],[y("Db5",1,.8),y("C5",.5,.7),y("Bb4",.5,.7),y("Ab4",2,.72)],[y("Db5",.5,.8),y("F5",.5,.8),y("Ab5",1.5,.85),y("Gb5",1.5,.75)],[y("D5",1,.8),y("F5",1,.8),y("Ab5",1,.85),F(1)],[y("E5",.5,.85),y("Eb5",.5,.8),y("Db5",1,.8),y("C5",2,.78)],[y("F5",1,.85),y("Ab5",1,.8),y("C6",2,.9)]],sequence:[0,1,2,3,4,5,6,7]},i={name:"kick",instrument:{...W.kick,volume:.5},gain:.6,patterns:[[y("Bb1",1,.8),F(1.5),y("Bb1",.5,.55),F(1)]],sequence:Array(8).fill(0)},s={name:"snare",instrument:{...W.snare,volume:.3,highpass:1e3},gain:.5,patterns:[[F(1),y("D4",1,.7),F(1),y("D4",1,.75)]],sequence:Array(8).fill(0)};return{bpm:100,tracks:[n,r,o,i,s,ln(.42),Ro(.35)],swing:.6,humanize:.32,velBrightness:.6,reverb:{wet:.17,roomSize:.6,damp:.5},master:{lowCut:.24,presence:.14,air:.04,compress:.45}}}function mm(){let t=["Ebmaj7","Cm7","Fm7","Bb13","Gm7","C7b9","Fm7","Bb7alt"],e={name:"bass",instrument:{...W.uprightBass,volume:.54,release:.2},gain:.74,patterns:t.map(i=>{let s=Ce(i,2)[0];return[y(s,2,.85),y(s+7,1,.6),y(s+12,1,.55)]}),sequence:[0,1,2,3,4,5,6,7]},n={name:"rhodes",instrument:{...W.rhodes,volume:.34,release:.6},gain:.62,pan:-.15,patterns:am(t,4,"G4",.62),sequence:[0,1,2,3,4,5,6,7]},r={name:"trumpet",instrument:{...W.mutedTrumpet,volume:.36,attack:.05,vibrato:.11},gain:.62,pan:.12,patterns:[[F(1),y("G4",1.5,.7),y("Bb4",1,.75),y("G4",.5,.6)],[y("Eb4",2,.7),y("G4",1,.65),F(1)],[F(.5),y("Ab4",1.5,.72),y("C5",1,.75),y("Ab4",1,.62)],[y("D5",2.5,.78),y("Bb4",1.5,.65)],[y("Bb4",1.5,.7),y("G4",1,.65),y("D5",1.5,.72)],[y("Db5",2,.75),y("C5",1,.68),y("Bb4",1,.62)],[y("Ab4",2,.72),y("F4",1,.62),F(1)],[y("Ab4",1,.72),y("Db5",1,.7),y("D5",2,.72)]],sequence:[0,1,2,3,4,5,6,7]},o={name:"brush",instrument:{...W.snare,volume:.12,highpass:1500,release:.16},gain:.4,patterns:[[F(1),y("D4",1,.4),F(1),y("D4",1,.45)]],sequence:Array(8).fill(0)};return{bpm:62,tracks:[Kn(.3),e,n,r,o,ln(.24)],swing:.5,humanize:.4,velBrightness:.6,reverb:{wet:.34,roomSize:.85,damp:.55},master:{lowCut:.24,presence:.16,air:.05,compress:.65}}}function dm(){let t=["Cm9","Cm9","Fm9","Dm7b5","G7alt","Cm9","Ab13","G7alt"],e={name:"bass",instrument:{...W.uprightBass,volume:.48},gain:.68,patterns:Mo(t,2),sequence:[0,1,2,3,4,5,6,7]},n={name:"vibes",instrument:{...W.vibraphone,volume:.34},gain:.6,pan:.1,patterns:[[y("G4",1,.7),F(1),y("Eb5",1,.65),F(1)],[F(2),y("D5",1,.68),y("C5",1,.6)],[y("Ab4",1,.7),F(1.5),y("F5",1.5,.6)],[y("F4",1,.7),y("Ab4",1,.6),F(2)],[F(1),y("B4",1,.72),y("Ab4",1,.6),y("F4",1,.55)],[y("Eb5",2,.68),y("C5",2,.6)],[y("C5",1,.7),y("Gb5",1,.68),F(2)],[y("B4",1,.7),y("Db5",1,.62),y("Ab4",2,.58)]],sequence:[0,1,2,3,4,5,6,7]},r={name:"guitar",instrument:{...W.jazzGuitar,volume:.22},gain:.5,pan:-.2,patterns:Yn(t,4,"Eb4",.5),sequence:[0,1,2,3,4,5,6,7]};return{bpm:96,tracks:[Kn(.28),e,r,n,ln(.3),Ro(.28)],swing:.62,humanize:.34,velBrightness:.6,reverb:{wet:.22,roomSize:.65,damp:.5},master:{lowCut:.24,presence:.13,air:.04,compress:.45}}}function hm(){let t={name:"bass",instrument:{...W.bass,volume:.52,lowpass:1e3,sub:.35},gain:.75,patterns:[[y("F1",.5,.95),y("F1",.5,.6),F(.5),y("F1",.5,.7),y("Ab1",.5,.7),y("C2",.5,.7),y("F1",.5,.65),y("Eb2",.5,.7)],[y("Bb1",.5,.9),y("Bb1",.5,.6),F(.5),y("Bb1",.5,.7),y("Db2",.5,.7),y("F2",.5,.7),y("Bb1",1,.65)],[y("C2",.5,.9),y("C2",.5,.6),y("Eb2",.5,.7),y("D2",.5,.7),y("C2",.5,.7),y("Bb1",.5,.7),y("G1",1,.7)]],sequence:[0,0,1,2]},e={name:"clav",instrument:{...W.clav,volume:.3,lowpass:2700},gain:.55,pan:-.16,patterns:[[y("F4",.25,.8),F(.25),y("Ab4",.25,.6),F(.25),y("F4",.25,.7),y("C5",.25,.6),F(.5),y("Eb5",.5,.7),F(1)],[y("Bb3",.25,.8),F(.25),y("Db4",.25,.6),F(.25),y("F4",.5,.7),F(.5),y("Bb4",.5,.65),F(1)],[y("C4",.25,.8),y("Eb4",.25,.6),y("G4",.5,.7),F(.5),y("C5",.5,.7),y("Bb4",.5,.65),F(1)]],sequence:[0,0,1,2]},n=a=>an(Ce(a,4),ce("C5")),r={name:"horns",instrument:{...W.horns,volume:.26},gain:.55,pan:.15,patterns:[[F(1.5),y(n("Fm7"),.5,.8),F(1.5),y(n("Fm7"),.5,.9)],[F(1.5),y(n("Fm7"),.5,.8),F(1.5),y(n("Bbm7"),.5,.9)],[F(2),y(n("Bbm7"),.5,.82),F(1),y(n("Bbm7"),.5,.88)],[y(n("C7#9"),.5,.92),F(1),y(n("C7#9"),.5,.82),F(1),y(n("C7#9"),.5,.9)]],sequence:[0,1,2,3]},o={name:"kick",instrument:W.kick,gain:.85,patterns:[[y("F1",1,.95),y("F1",.5,.6),F(.5),y("F1",.5,.7),F(.5),y("F1",1,.8)]],sequence:Array(4).fill(0)},i={name:"snare",instrument:{...W.snare,volume:.42},gain:.6,patterns:[[F(1),y("D4",1,.85),F(1),y("D4",1,.9)]],sequence:Array(4).fill(0)},s={name:"hat",instrument:{...W.hat,volume:.18,highpass:5e3,lowpass:9e3},gain:.38,pan:.1,patterns:[[y("C6",.5,.6),y("C6",.5,.35)]],sequence:Array(8).fill(0)};return{bpm:128,tracks:[o,t,e,r,i,s],humanize:.14,velBrightness:.55,sidechain:{depth:.5,beatsPerCycle:1},reverb:{wet:.12,roomSize:.5,damp:.5},master:{lowCut:.3,presence:.16,air:.05,compress:.4}}}function pm(){let t=["Abmaj7#11","Db9","Bbm7","Eb7alt","Cm7","F7b9","Bbm7","Eb13"],e={name:"bass",instrument:{...W.uprightBass,volume:.5,sub:.4},gain:.72,patterns:t.map((s,a)=>{let l=Ce(s,2)[0],u=Ce(t[(a+1)%t.length],2)[0],c=u+(l<=u?-1:1);return[y(l,1.5,.9),F(.5),y(l+7,1,.62),y(c,1,.62)]}),sequence:[0,1,2,3,4,5,6,7]},n={name:"rhodes",instrument:{...W.rhodes,volume:.28},gain:.55,pan:-.18,patterns:Yn(t,4,"Ab4",.6),sequence:[0,1,2,3,4,5,6,7]},r={name:"vibes",instrument:{...W.vibraphone,volume:.3},gain:.55,pan:.18,patterns:[[F(1),y("C5",1,.7),y("D5",1,.65),y("Eb5",1,.62)],[y("F5",2,.7),y("Eb5",1,.62),y("C5",1,.58)],[y("Db5",1.5,.7),y("F5",1.5,.65),y("Ab5",1,.62)],[y("G5",1,.72),y("Gb5",1,.66),y("Db5",2,.6)],[F(1),y("Eb5",1.5,.68),y("G5",1.5,.62)],[y("Ab5",1,.72),y("Gb5",1,.66),y("F5",2,.6)],[y("Db5",2,.68),y("Bb4",2,.6)],[y("C5",1,.7),y("G5",1,.66),y("Eb5",2,.6)]],sequence:[0,1,2,3,4,5,6,7]},o={name:"kick",instrument:{...W.kick,volume:.55},gain:.62,patterns:[[y("Ab1",1,.85),F(2),y("Ab1",.5,.55),F(.5)]],sequence:Array(8).fill(0)},i={name:"snare",instrument:{...W.rimshot,volume:.22},gain:.5,patterns:[[F(2),y("D4",1,.7),F(1)]],sequence:Array(8).fill(0)};return{bpm:84,tracks:[Kn(.32),e,n,r,o,i,ln(.28),Ro(.24)],swing:.56,humanize:.3,velBrightness:.62,reverb:{wet:.26,roomSize:.72,damp:.55},master:{lowCut:.24,presence:.14,air:.04,compress:.45}}}function fm(){let t=["Dm7","G13","Cmaj9","A7b9","Dm7","G7","Cmaj9","Cmaj9"],e={name:"bass",instrument:{...W.uprightBass,volume:.5},gain:.66,patterns:Mo(t,2),sequence:[0,1,2,3,4,5,6,7]},n={name:"rhodes",instrument:{...W.rhodes,volume:.32,release:.5},gain:.6,pan:-.14,patterns:Yn(t,4,"E4",.6),sequence:[0,1,2,3,4,5,6,7]},r={name:"trumpet",instrument:{...W.mutedTrumpet,volume:.36,vibrato:.1},gain:.62,pan:.12,patterns:[[F(1),y("A4",1,.72),y("C5",1,.75),y("D5",1,.7)],[y("B4",2,.75),y("G4",1,.65),y("F4",1,.6)],[y("E5",2,.78),y("G4",1,.62),y("E4",1,.6)],[y("C5",1,.72),y("Bb4",1,.68),y("A4",1,.65),y("D5",1,.62)],[y("G4",.5,.78),y("A4",.5,.72),y("C5",1,.82),y("B4",.5,.7),F(1.5)],[y("D5",1,.75),y("B4",1,.68),y("G4",2,.62)],[y("E5",2,.8),y("C5",2,.72)],[y("E4",4,.6)]],sequence:[0,1,2,3,4,5,6,7]},o={name:"brush",instrument:{...W.snare,volume:.12,highpass:1500,release:.15},gain:.42,patterns:[[F(1),y("D4",1,.42),F(1),y("D4",1,.46)]],sequence:Array(8).fill(0)};return{bpm:76,tracks:[Kn(.3),e,n,r,o,ln(.26)],swing:.56,humanize:.36,velBrightness:.6,reverb:{wet:.3,roomSize:.8,damp:.5},master:{lowCut:.38,presence:.28,air:.09,compress:.65}}}var Gs={title:"Neon Precinct",subtitle:"Original Soundtrack",concept:"The score to an imaginary neo-noir detective game. You work the night beat in a rain-slicked retro-future city \u2014 jazz-funk with a noir heart. Six cues, one motif, a long night.",tracks:[{id:"neon-precinct",title:"Neon Precinct",intent:"Main theme \u2014 swaggering medium funk, the city announcing itself.",make:cm},{id:"rain-avenue",title:"Rain on the Avenue",intent:"A smoky, slow torch ballad. Muted trumpet in the rain.",make:mm},{id:"stakeout",title:"Stakeout",intent:"Minimal, nervous cool-jazz. Watching, waiting, unresolved.",make:dm},{id:"the-chase",title:"The Chase",intent:"Driving F-minor funk \u2014 clav, horn stabs, a hard pulse.",make:hm},{id:"smoke-mirrors",title:"Smoke & Mirrors",intent:"Slinky half-time noir; altered colours, nothing as it seems.",make:pm},{id:"last-call",title:"Last Call",intent:"The warm closer \u2014 a ii\u2013V\u2013I that finally lands, the motif resolved.",make:fm}]};function bm(t){return Gs.tracks.find(e=>e.id===t)}var Qn=null,Vs="hayao-overlay-style",gm=`
|
|
178
178
|
.hy-scrim{position:absolute;inset:0;display:grid;place-items:center;z-index:50;font-family:var(--hy-serif,Georgia,serif)}
|
|
179
179
|
.hy-scrim.dim{background:rgba(30,24,14,.5);backdrop-filter:blur(2px)}
|
|
180
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}
|
|
@@ -184,7 +184,7 @@ ${i}`)}return o}function li(t,e,n,r){let o=t.getUniformLocation(e,n);o!==null&&(
|
|
|
184
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
185
|
.hy-item:hover,.hy-item.sel{background:var(--hy-accent,#a11d3a);color:#fdf3ee;border-color:transparent;transform:translateY(-1px)}
|
|
186
186
|
.hy-item.primary{background:var(--hy-accent,#a11d3a);color:#fdf3ee;border-color:transparent}
|
|
187
|
-
`;function
|
|
187
|
+
`;function ym(){if(typeof document>"u"||document.getElementById(Vs))return;let t=document.createElement("style");t.id=Vs,t.textContent=gm,document.head.appendChild(t)}var Hs=null;function un(t){Hs=t}var Po=null;function Zn(t){Po=t}function Do(t){if(typeof document>"u")return{close(){},element:null};ym(),cn(),Po?.("show",t.title);let e=document.createElement("div");e.className=`hy-scrim${t.dim===!1?"":" dim"}${t.className?" "+t.className:""}`;let n=document.createElement("div");if(n.className="hy-card",t.title){let u=document.createElement("h1");u.textContent=t.title,n.appendChild(u)}if(t.body){let u=document.createElement("div");u.className="hy-body",u.innerHTML=t.body,n.appendChild(u)}let r=t.actions??[],o=Math.max(0,r.findIndex(u=>u.primary));o<0&&(o=0);let i=[];if(r.length){let u=document.createElement("div");u.className="hy-menu",r.forEach((c,m)=>{let d=document.createElement("button");d.className=`hy-item${c.primary?" primary":""}`,d.textContent=c.label,d.addEventListener("click",()=>c.onSelect()),d.addEventListener("mouseenter",()=>s(m)),u.appendChild(d),i.push(d)}),n.appendChild(u)}function s(u){o=(u+i.length)%i.length,i.forEach((c,m)=>c.classList.toggle("sel",m===o))}i.length&&s(o);let a=u=>{i.length&&(u.code==="ArrowDown"?(s(o+1),u.preventDefault()):u.code==="ArrowUp"?(s(o-1),u.preventDefault()):(u.code==="Enter"||u.code==="Space")&&(r[o]?.onSelect(),u.preventDefault()))};document.addEventListener("keydown",a),e.appendChild(n),(Hs??document.body).appendChild(e);let l={element:e,close(){document.removeEventListener("keydown",a),e.remove(),Qn===l&&(Qn=null,Po?.("hide",t.title))}};return Qn=l,l}function cn(){Qn?.close()}var qs="hayao.settings.v1",js={master:.7,music:.6,sfx:.8,muted:!1,colorblind:!1,reducedMotion:!1},Eo=class{state;subs=new Set;constructor(){this.state=this.load(),this.pushToAudio()}get(){return{...this.state}}set(e){this.state={...this.state,...e},this.save(),this.pushToAudio();for(let n of this.subs)n(this.get())}subscribe(e){return this.subs.add(e),()=>this.subs.delete(e)}pushToAudio(){je.setVolumes({master:this.state.master,music:this.state.music,sfx:this.state.sfx,muted:this.state.muted})}load(){try{let e=typeof localStorage<"u"&&localStorage.getItem(qs);if(e)return{...js,...JSON.parse(e)}}catch{}return{...js}}save(){try{localStorage.setItem(qs,JSON.stringify(this.state))}catch{}}},ze=new Eo;function Io(){if(typeof document>"u")return;let t=document,e=document.documentElement;document.fullscreenElement||t.webkitFullscreenElement?(document.exitFullscreen??t.webkitExitFullscreen)?.call(document):(e.requestFullscreen??e.webkitRequestFullscreen)?.call(e)}var mn=class{paused=!1;opts;keyHandler;constructor(e={}){this.opts=e,this.keyHandler=n=>{n.code==="Escape"&&(n.preventDefault(),this.toggle())},typeof document<"u"&&document.addEventListener("keydown",this.keyHandler)}get isPaused(){return this.paused}toggle(){this.paused?this.resume():this.pause()}pause(){this.paused||(this.paused=!0,je.blip(440),this.opts.onPause?.(!0),this.render())}resume(){this.paused&&(this.paused=!1,cn(),this.opts.onPause?.(!1))}render(){let e=ze.get(),n=(r,o)=>`${r}: ${Math.round(o*100)}`;Do({title:this.opts.title??"Paused",body:`<div style="font-size:13px;text-align:left;line-height:1.9">${n("Master",e.master)} \xB7 ${n("Music",e.music)} \xB7 ${n("Sfx",e.sfx)}<br/><span style="opacity:.7">Use the menu, or keys: M mute \xB7 F fullscreen</span></div>`,actions:[{label:"Resume",primary:!0,onSelect:()=>this.resume()},{label:e.muted?"Unmute (M)":"Mute (M)",onSelect:()=>{ze.set({muted:!ze.get().muted}),this.render()}},{label:"Music \u2212/+",onSelect:()=>{let r=Math.min(1,ze.get().music+.1)%1.05;ze.set({music:r>1?0:r}),this.render()}},{label:"Fullscreen (F)",onSelect:()=>Io()},...this.opts.onRestart?[{label:"Restart",onSelect:()=>{this.resume(),this.opts.onRestart()}}]:[],...this.opts.onQuit?[{label:"Quit",onSelect:()=>{this.resume(),this.opts.onQuit()}}]:[]]})}dispose(){typeof document<"u"&&document.removeEventListener("keydown",this.keyHandler),cn()}};var Us="hayao-touch-style",xm=`
|
|
188
188
|
.hy-touch{position:absolute;inset:0;z-index:40;pointer-events:none;touch-action:none;-webkit-user-select:none;user-select:none}
|
|
189
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
190
|
.hy-stick.left{left:5%}
|
|
@@ -193,8 +193,8 @@ ${i}`)}return o}function li(t,e,n,r){let o=t.getUniformLocation(e,n);o!==null&&(
|
|
|
193
193
|
.hy-btns{position:absolute;right:5%;bottom:26%;display:flex;flex-direction:column-reverse;gap:12px;pointer-events:none}
|
|
194
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
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==="<"?"<":e===">"?">":"&")}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(`
|
|
196
|
+
`;function vm(){if(typeof document>"u"||document.getElementById(Us))return;let t=document.createElement("style");t.id=Us,t.textContent=xm,document.head.appendChild(t)}function wm(t){if(t.dirs)return Array.isArray(t.dirs)?{up:t.dirs[0],down:t.dirs[1],left:t.dirs[2],right:t.dirs[3]}:t.dirs}var Lo=class{handle;root;disposers=[];owned=new Set;constructor(e,n){this.handle=e,vm();let r=typeof matchMedia<"u"&&matchMedia("(pointer: coarse)").matches,o=e.canvas?.parentElement??void 0;this.root=document.createElement("div"),this.root.className="hy-touch",o&&(n.touchOnly===!1||r)&&o.appendChild(this.root);let i=Xs(n.left),s=Xs(n.right);i&&this.addStick("left",i),s&&this.addStick("right",s),n.buttons?.length&&this.addButtons(n.buttons)}addStick(e,n){let r=document.createElement("div");r.className=`hy-stick ${e}`;let o=document.createElement("div");o.className="hy-knob",r.appendChild(o),this.root.appendChild(r);let i=wm(n),s=n.prefix,a=n.buckets??32,l=n.deadzone??.28,u=null,c=(g,k)=>{if(!s)return;let v=this.handle.world.input.axes;v.set(`${s}x`,Ze(g,a)),v.set(`${s}y`,Ze(k,a)),v.set(`${s}angle`,g===0&&k===0?0:Hr(Le(k,g),a))},m=()=>{if(i)for(let g of[i.up,i.down,i.left,i.right])this.hold(g,!1);c(0,0),o.style.transform="translate(0,0)",u=null},d=(g,k)=>{let v=r.getBoundingClientRect(),M=v.width/2,I=(g-(v.left+M))/M,x=(k-(v.top+M))/M,b=G(I,x);b>1&&(I/=b,x/=b),o.style.transform=`translate(${I*M*.6}px,${x*M*.6}px)`;let w=G(I,x);i&&(this.hold(i.left,I<-l),this.hold(i.right,I>l),this.hold(i.up,x<-l),this.hold(i.down,x>l)),c(w<l?0:I,w<l?0:x)},h=g=>{u===null&&(u=g.pointerId,r.setPointerCapture?.(g.pointerId),d(g.clientX,g.clientY),g.preventDefault())},p=g=>{g.pointerId===u&&d(g.clientX,g.clientY)},f=g=>{g.pointerId===u&&m()};r.addEventListener("pointerdown",h),r.addEventListener("pointermove",p),r.addEventListener("pointerup",f),r.addEventListener("pointercancel",f),this.disposers.push(()=>{m(),r.remove()})}addButtons(e){let n=document.createElement("div");n.className="hy-btns",this.root.appendChild(n);for(let r of e){let o=document.createElement("button");o.className="hy-btn",o.textContent=r.label??r.action,n.appendChild(o);let i=r.hold??!0,s=l=>{o.classList.add("on"),i?this.hold(r.action,!0):this.handle.input.press(r.action),o.setPointerCapture?.(l.pointerId),l.preventDefault()},a=()=>{o.classList.remove("on"),i&&this.hold(r.action,!1)};o.addEventListener("pointerdown",s),o.addEventListener("pointerup",a),o.addEventListener("pointercancel",a),this.disposers.push(()=>{a(),o.remove()})}this.disposers.push(()=>n.remove())}hold(e,n){this.handle.input.setHeld(e,n),n&&this.owned.add(e)}dispose(){for(let e of this.disposers.splice(0))e();for(let e of this.owned)this.handle.input.setHeld(e,!1);this.owned.clear(),this.root.remove()}};function Xs(t){if(t)return Array.isArray(t)?{dirs:t}:t}var km=[0,8,2,10,12,4,14,6,3,11,1,9,15,7,13,5],Sm=t=>t*t*(3-2*t),er=class extends _{type="ScreenTransition";kind;color;screenW;screenH;cell;coverage=0;queue=[];constructor(e={}){super(e),this.cosmetic=!0,this.kind=e.kind??"fade",this.color=e.color??"#1a1410",this.screenW=e.width??1280,this.screenH=e.height??720,this.cell=e.cell??28}get busy(){return this.queue.length>0}enqueue(e,n,r){this.queue.push({from:void 0,to:e,dur:Math.max(1e-4,n),elapsed:0,onEnd:r})}cover(e=.4,n){return this.enqueue(1,e,n),this}reveal(e=.4,n){return this.enqueue(0,e,n),this}hold(e,n){let r=this.queue.length?this.queue[this.queue.length-1].to:this.coverage;return this.enqueue(r,e,n),this}wipe(e={}){let n=e.cover??.4;return this.cover(n,()=>{this.emit("covered",void 0),e.onMidpoint?.()}),e.hold&&this.hold(e.hold),this.reveal(e.reveal??n,()=>{this.emit("done",void 0),e.onDone?.()}),this}get covered(){return this.signal("covered")}get done(){return this.signal("done")}onProcess(e){let n=this.queue[0];if(!n)return;n.from===void 0&&(n.from=this.coverage),n.elapsed+=e;let r=Q(n.elapsed/n.dur,0,1);if(this.coverage=$e(n.from,n.to,Sm(r)),r>=1){this.coverage=n.to;let o=n.onEnd;this.queue.shift(),o?.()}}draw(e,n){let r=this.coverage;if(r<=0)return;let o=this.z;if(this.kind==="fade"){e.push({kind:"rect",x:0,y:0,w:this.screenW,h:this.screenH,fill:this.color,opacity:r,transform:oe,z:o});return}if(this.kind==="circle"){let a=this.screenW/2,l=this.screenH/2,u=Math.sqrt(a*a+l*l);e.push({kind:"circle",cx:a,cy:l,radius:r*u,fill:this.color,transform:oe,z:o});return}let i=Math.ceil(this.screenW/this.cell),s=Math.ceil(this.screenH/this.cell);for(let a=0;a<s;a++)for(let l=0;l<i;l++)(km[(l&3)+((a&3)<<2)]+.5)/16<r&&e.push({kind:"rect",x:l*this.cell,y:a*this.cell,w:this.cell,h:this.cell,fill:this.color,transform:oe,z:o})}},$o=class extends _{type="CinematicPlayer";steps=[];index=-1;elapsed=0;running=!1;onFinish;constructor(e={}){super(e),this.cosmetic=!0}play(e,n){return this.steps=e,this.onFinish=n,this.index=-1,this.elapsed=0,this.running=e.length>0,this.advance(),this}get active(){return this.running}get step(){return this.index}get finished(){return this.signal("finished")}advance(){if(this.index++,this.elapsed=0,this.index>=this.steps.length){this.running=!1,this.index=-1,this.emit("finished",void 0),this.onFinish?.();return}this.steps[this.index].enter?.()}stop(){this.running=!1,this.index=-1,this.steps=[]}onProcess(e){if(!this.running)return;this.elapsed+=e;let n=this.steps[this.index],r=this.elapsed>=(n.duration??0),o=n.until?n.until():!0;r&&o&&this.advance()}};function Cm(t,e={}){let n=new er({z:1e4,...e});return t.addChild(n)}function Tm(t,e={}){return{name:e.name??"wipe",enter:()=>t.wipe(e),until:()=>!t.busy}}var Mm=(t,e)=>({x:0,y:0,w:t,h:e});function mt(t,e={}){let n=e.maxDepth??60,r=e.nodeCap??1e6,o=t.initial(e.level);if(t.isWin(o))return{solvable:!0,path:[],depth:0,nodes:0,exhausted:!1};let i=[{state:o,path:[]}],s=new Set([t.key(o)]),a=0;for(let l=0;l<n&&i.length>0;l++){let u=[];for(let{state:c,path:m}of i)for(let d of t.moves(c)){if(a>=r)return{solvable:!1,nodes:a,exhausted:!0};a++;let h=t.apply(c,d);if(t.isDead?.(h))continue;if(t.isWin(h))return{solvable:!0,path:[...m,d],depth:l+1,nodes:a,exhausted:!1};let p=t.key(h);s.has(p)||(s.add(p),u.push({state:h,path:[...m,d]}))}i=u}return{solvable:!1,nodes:a,exhausted:i.length>0}}function Rm(t,e={}){let n=mt(t,e);if(!n.solvable)throw new Error(`hayao: level ${e.level??0} is NOT winnable (expanded ${n.nodes} nodes${n.exhausted?", search capped \u2014 raise nodeCap/maxDepth":""}).`);return n}function No(t,e){let n=t(),r=[];for(let o=0;o<e.frames.length;o++)n.step(wt(e,o),kt(e,o)),r.push(n.hash());return{finalHash:n.hash(),hashes:r}}function Js(t,e){let n=No(t,e),r=No(t,e),o=-1;for(let i=0;i<n.hashes.length;i++)if(n.hashes[i]!==r.hashes[i]){o=i;break}return{ok:o===-1&&n.finalHash===r.finalHash,frames:e.frames.length,divergedAt:o,finalHash:n.finalHash}}function Pm(t,e){let n=Js(t,e);if(!n.ok)throw new Error(`hayao: sim is NON-deterministic \u2014 runs diverged at frame ${n.divergedAt} of ${n.frames}. Check for Math.random/Date.now/Set-iteration/unordered-map in the sim.`);return n}function Dm(t,e,n){let r=t();for(let l=0;l<n;l++)r.step(wt(e,l),kt(e,l));let o=r.snapshot(),i=t();i.restore(o);for(let l=n;l<e.frames.length;l++)r.step(wt(e,l),kt(e,l)),i.step(wt(e,l),kt(e,l));let s=r.hash(),a=i.hash();return{ok:s===a,hashA:s,hashB:a}}function Em(t,e){return{actions:t,frames:e}}function Im(t){return{actions:[],frames:t}}function Lm(t,e){let n=[],r=0;for(let o of e){for(let i=0;i<o.frames;i++)t.step(o.actions??[]);r+=o.frames,n.push(t.probe())}return{totalFrames:r,finalHash:t.hash(),probes:n}}function $m(t,e,n=[]){for(let r=0;r<e;r++)t.step(n)}function Fo(){return typeof location<"u"&&new URLSearchParams(location.search).has("capture")}function Ao(t){let e={pump(n,r=[]){t.setPaused(!0);for(let o=0;o<n;o++)t.stepOnce(r);return t.world.probe()},probe:()=>t.world.probe(),hash:()=>t.world.hash(),shot:()=>t.renderSVG(),async save(n){let r=t.renderSVG();try{return(await fetch("/__shot",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({path:n,svg:r})})).ok}catch{return!1}},key(n,r){document.dispatchEvent(new KeyboardEvent(n,{code:r,bubbles:!0}))},get world(){return t.world}};return globalThis.__hayao=e,e}function Ys(t){let e=[];for(let n of t){let r=n.frames??1,o=n.hold??[];for(let i=0;i<r;i++)e.push(i===0&&n.press?[...o,...n.press]:[...o])}return e}function Nm(t,e,n){let r=0;for(let o of Ys(e)){if(n&&n(t.probe()))return{frames:r,matched:!0};t.step(o),r++}return{frames:r,matched:n?n(t.probe()):!1}}function Fm(t,e){let n=0,r=0,o={},s=a=>{let l=[],u=t[n];if(!u)return l;r++;let c={get frames(){return r},mem:o,next(){n++,r=0,o={}},retry(){r=0,o={}}},m=e[u.kind];if(!m)throw new Error(`plan bot: no executor for step kind "${u.kind}"`);return m(u,a,l,c),l};return s.stepIndex=()=>n,s.done=()=>n>=t.length,s}function Am(t,e,n,r,o,i=8){t<n-i?o.push("right"):t>n+i&&o.push("left"),e<r-i?o.push("down"):e>r+i&&o.push("up")}var dn=t=>[...new Set(t)];function Ks(t,e={}){let n=e.minCoyote??.05,r=e.minBuffer??.05,o=e.requireCornerNudge??!0,i=[];return t.coyoteTime>=n||i.push(`coyote time ${t.coyoteTime}s is below the ${n}s floor \u2014 late jumps off a ledge will be dropped`),t.jumpBuffer>=r||i.push(`jump buffer ${t.jumpBuffer}s is below the ${r}s floor \u2014 early jumps before landing will be swallowed`),o&&!((t.jumpCornerNudge??0)>0)&&i.push("no jump corner nudge \u2014 clipping a ceiling edge kills upward momentum instead of slipping past"),i}function Wm(t,e,n){let r=[];for(let o=0;o<=e;o++)n(o)||r.push(`${t}: input ${o} frame(s) into the window was refused \u2014 grace window is shorter than the specced ${e}`);return n(e+1)&&r.push(`${t}: input ${e+1} frame(s) in (past the window) was still accepted \u2014 grace window is longer than specced (unfair leniency)`),dn(r)}function Qs(t,e,n={}){let r=n.minChannels??2,[o,i]=n.shake??[0,1],[s,a]=n.hitstop??[0,12],l=[];for(let u of e){let c=t[u];if(!c){l.push(`event "${u}" has no feedback response \u2014 it happens silently`);continue}let m=new Set(c.channels).size;m<r&&l.push(`event "${u}" answers on ${m} channel(s) (${c.channels.join("+")||"none"}) \u2014 needs \u2265 ${r} (e.g. sfx + particles)`),c.shake!==void 0&&(c.shake<o||c.shake>i)&&l.push(`event "${u}" shake ${c.shake} is outside the [${o}, ${i}] envelope`),c.hitstopFrames!==void 0&&(c.hitstopFrames<s||c.hitstopFrames>a)&&l.push(`event "${u}" hit-stop ${c.hitstopFrames}f is outside the [${s}, ${a}]f envelope`)}return dn(l)}function _e(t){let e=t.replace("#","");e.length===3&&(e=e.split("").map(o=>o+o).join(""));let n=parseInt(e,16),r=o=>{let i=o/255;return i<=.03928?i/12.92:Pe((i+.055)/1.055,2.4)};return .2126*r(n>>16&255)+.7152*r(n>>8&255)+.0722*r(n&255)}function Lt(t,e){let n=_e(t),r=_e(e),o=Math.max(n,r),i=Math.min(n,r);return(o+.05)/(i+.05)}var Bm=t=>t.kind==="text"?void 0:t.fill;function Zs(t,e,n,r={}){let o=r.minBackgroundContrast??3,i=r.minSalienceFactor??1.15,s=[],a=Lt(e,n);a<o&&s.push(`avatar (${e}) contrast vs background is ${a.toFixed(2)}:1 (needs \u2265 ${o}:1) \u2014 it sinks into the ground`);let l=[];for(let u of t){let c=Bm(u);c&&c!=="none"&&c!==e&&l.push(Lt(c,n))}if(l.length){l.sort((c,m)=>c-m);let u=l[Math.floor(l.length/2)];a<u*i&&s.push(`avatar (${e}, ${a.toFixed(2)}:1) does not pop from the scenery (median ${u.toFixed(2)}:1) \u2014 it needs \u2265 ${i}\xD7 the median contrast`)}return dn(s)}function zm(t,e,n="threat"){let r=[],o=0;for(let i=0;i<t.length;i++){let s=t[i];s.active&&(i===0||!t[i-1].active)&&o<e&&r.push(`${n}: hitbox went live at frame ${i} after only ${o} telegraph frame(s) \u2014 needs \u2265 ${e} of wind-up`),o=s.active?0:s.telegraphing?o+1:0}return dn(r)}var _m=(t,e)=>_e(t)*e;function ea(t,e,n,r={}){let o=r.minLitLevel??.35,{light:i}=nt(Ke(t)),s=i.length?rt(i):null;if(!s)return[];let a=_e(s.ambient.fill??"#000000");for(let u of s.lights){let c=u.circle,m=bt(De(c.transform),n),d=G(m.x-c.cx,m.y-c.cy);if(d>=c.radius)continue;let h=Om(c),p=1-d/c.radius;a=Math.min(1,a+h*p)}let l=[];if(a<o){let u=_m(e,a);l.push(`avatar (${e}) sits in light level ${a.toFixed(2)} (needs \u2265 ${o}) \u2014 it sinks into the ambient darkness (effective luminance ${u.toFixed(3)}); add a pool over it or raise ambient level`)}return l}function Om(t){let e=t.gradient;if(e&&e.stops.length){let r=0;for(let o of e.stops)r=Math.max(r,_e(o.color));return r}let n=t.fill;return n?_e(n):1}function ta(t,e={}){let n=e.dt??.016666666666666666,r=e.maxSpeed??1800,o=e.maxAccel??9e4;if(t.length<3)return[];let i=[],s=[];for(let a=1;a<t.length;a++){let l=t[a].x-t[a-1].x,u=t[a].y-t[a-1].y,c=G(l,u)/n;s.push(c),c>r&&i.push(`camera snapped at frame ${a}: ${Math.round(c)}px/s exceeds the ${r}px/s ceiling`)}for(let a=1;a<s.length;a++){let l=Math.abs(s[a]-s[a-1])/n;l>o&&i.push(`camera jerked at frame ${a+1}: ${Math.round(l)}px/s\xB2 exceeds the ${o}px/s\xB2 ceiling`)}return dn(i)}function na(t,e,n=0){if(t.length<2||t.length!==e.length)return[];let r=t[t.length-1].x-t[0].x,o=e[e.length-1].x-e[0].x,i=t[t.length-1].y-t[0].y,s=e[e.length-1].y-e[0].y,a=[];return Math.abs(o)>n&&Math.sign(r)!==0&&Math.sign(r)!==Math.sign(o)&&a.push("camera drifts opposite the target on X \u2014 the view lags behind instead of leading"),Math.abs(s)>n&&Math.sign(i)!==0&&Math.sign(i)!==Math.sign(s)&&a.push("camera drifts opposite the target on Y \u2014 the view lags behind instead of leading"),a}function Gm(t,e={}){let n=[],r=[],o=t.background??e.background??"#ffffff";if(t.forgiveness&&n.push({gate:"forgiveness",issues:Ks(t.forgiveness)}),t.feedback&&n.push({gate:"feedback",issues:Qs(t.feedback.contract,t.feedback.events)}),t.avatarFill&&(e.commands?n.push({gate:"salience",issues:Zs(e.commands,t.avatarFill,o)}):r.push("salience (no rendered frame)")),t.lit&&(t.avatarFill&&e.commands&&e.avatarWorld?n.push({gate:"lighting",issues:ea(e.commands,t.avatarFill,e.avatarWorld)}):r.push("lighting (needs avatarFill + rendered frame + avatarWorld)")),t.scrolls)if(e.camSamples&&e.camSamples.length>=3){let i=ta(e.camSamples,{dt:e.dt});e.targetSamples&&i.push(...na(e.camSamples,e.targetSamples)),n.push({gate:"camera",issues:i})}else r.push("camera (no sampled positions)");return{ok:n.every(i=>i.issues.length===0),sections:n,skipped:r}}function sa(t){let e=t.text.length*t.size*.56,n=t.size*1.25,r=t.transform.e+t.x,o=t.transform.f+t.y,i=t.align==="center"?r-e/2:t.align==="right"?r-e:r;return{cmd:t,x:i,y:o-t.size,w:e,h:n}}function Wo(t){let e=t.transform.e,n=t.transform.f;switch(t.kind){case"rect":return{x:e+t.x,y:n+t.y,w:t.w,h:t.h};case"circle":return{x:e+t.cx-t.radius,y:n+t.cy-t.radius,w:t.radius*2,h:t.radius*2};case"poly":{let r=1/0,o=1/0,i=-1/0,s=-1/0;for(let a=0;a<t.points.length;a+=2)r=Math.min(r,t.points[a]),i=Math.max(i,t.points[a]),o=Math.min(o,t.points[a+1]),s=Math.max(s,t.points[a+1]);return{x:e+r,y:n+o,w:i-r,h:s-o}}default:return null}}var ra=(t,e)=>t.x<e.x+e.w&&t.x+t.w>e.x&&t.y<e.y+e.h&&t.y+t.h>e.y,oa=(t,e,n=2)=>t.x-n<=e.x&&t.y-n<=e.y&&t.x+t.w+n>=e.x+e.w&&t.y+t.h+n>=e.y+e.h,Vm=t=>t.transient===!0,ia=t=>{let e=t.fill;if(!(!e||e==="none")&&!t.gradient)return e};function Hm(t,e={}){let n=e.backgroundZ??1,r=e.margin??0,o=e.background,i=e.minContrast??1.5,s=e.minTextContrast??4.5,a=[],l=e.includeTransient?t:t.filter(c=>!Vm(c)),u=[];for(let c of l)c.kind==="text"&&c.text.trim().length&&u.push(sa(c));for(let c of u){let m=c.cmd.z??0,d={x:c.x-r,y:c.y-r,w:c.w+r*2,h:c.h+r*2},h=-1/0,p=o;for(let f of l){if(f.kind==="text")continue;let g=Wo(f);if(!g||!oa(g,c))continue;let k=f.opacity===void 0||f.opacity>=.6,v=f.z??0;k&&v<=m&&v>=h&&(h=v,p=ia(f)??p),v>m&&(f.opacity===void 0||f.opacity>=.9)&&a.push(`text "${hn(c.cmd.text)}" is hidden behind a ${f.kind} (z${v} > text z${m}) that fully covers it \u2014 give the text a higher z, or the shape a lower one`)}for(let f of l){if(f.kind==="text"||(f.z??0)<=n||(f.z??0)<=h||f.opacity!==void 0&&f.opacity<.25)continue;let g=Wo(f);g&&ra(d,g)&&!oa(g,c)&&a.push(`text "${hn(c.cmd.text)}" collides with a ${f.kind} (z${f.z}) at ~(${Math.round(g.x)},${Math.round(g.y)}) \u2014 back it with a panel, or stay clear`)}if(o&&s>0){let f=c.cmd.fill;if(f&&f!=="none"&&(c.cmd.opacity===void 0||c.cmd.opacity>=.6)){let g=Lt(f,p??o);g<s&&a.push(`text "${hn(c.cmd.text)}" (${f}) contrast is ${g.toFixed(2)}:1 on its backing (needs \u2265 ${s}:1) \u2014 barely readable`)}}}if(o)for(let c of l){if(c.kind==="text"||(c.z??0)<=n||c.opacity!==void 0&&c.opacity<.6)continue;let m=ia(c);if(!m)continue;let d=Lt(m,o);d<i&&a.push(`${c.kind} (${m}, z${c.z}) contrast is ${d.toFixed(2)}:1 vs background ${o} (needs \u2265 ${i}:1) \u2014 it vanishes into the ground`)}for(let c=0;c<u.length;c++)for(let m=c+1;m<u.length;m++)ra(u[c],u[m])&&a.push(`texts "${hn(u[c].cmd.text)}" and "${hn(u[m].cmd.text)}" overlap`);return aa(a)}var hn=t=>t.length>28?t.slice(0,25)+"\u2026":t,aa=t=>[...new Set(t)];function la(t){return t.startsWith("Digit")?[t.slice(5)]:t.startsWith("Key")?[t.slice(3).toLowerCase()]:t.startsWith("Arrow")?["arrow","\u2190","\u2192","\u2191","\u2193",t.slice(5).toLowerCase()]:t.startsWith("Shift")?["shift"]:t==="Space"?["space"]:t==="Enter"?["enter"]:t==="Period"?["."]:[t.toLowerCase()]}function qm(t,e){let n=t.render().filter(i=>i.kind==="text").map(i=>i.text.toLowerCase()).join(" \xB7 "),r=[],o=i=>i.length?i.length<=2&&/^[a-z0-9.]+$/.test(i)?new RegExp(`(^|[^a-z0-9])${i.replace(".","\\.")}($|[^a-z0-9])`).test(n):n.includes(i):!1;for(let[i,s]of Object.entries(e)){if(i==="restart")continue;[i.toLowerCase().replace(/-\d+$/,""),...s.flatMap(la)].some(o)||r.push(i)}return aa(r)}function jm(t,e){let n=[t.probe()];for(let r of e)t.step(r),n.push(t.probe());return n}function Um(t,e){for(let n=0;n<t.length;n++)if(e(t[n]))return n;return-1}function Xm(t,e){return t.map(n=>n[e])}function Jm(t,e){let n=[];for(let r=1;r<t.length;r++)t[r][e]!==t[r-1][e]&&n.push(r);return n}function Ym(t,e,n=0){for(let r=1;r<t.length;r++)if(e==="up"?t[r]<t[r-1]-n:t[r]>t[r-1]+n)return!1;return!0}function Km(t){return t.length===0?0:t.filter(e=>e.length>0).length/t.length}function Qm(t,e){let n=[0,...t,e],r=0;for(let o=1;o<n.length;o++)r=Math.max(r,n[o]-n[o-1]);return r}var Zm=t=>[...new Set(t)];function ua(t){let e=t.length;if(e===0)return{count:0,min:0,max:0,mean:0,distinct:0,maxJump:0,forwardFraction:1};let n=t[0],r=t[0],o=0,i=0,s=0;for(let a=0;a<e;a++){let l=t[a];if(l<n&&(n=l),l>r&&(r=l),o+=l,a>0){let u=l-t[a-1];u>i&&(i=u),u>=0&&s++}}return{count:e,min:n,max:r,mean:o/e,distinct:new Set(t).size,maxJump:i,forwardFraction:e>1?s/(e-1):1}}function ca(t,e={}){let n=e.maxJumpFactor??3,r=e.minJumpAllowance??2,o=e.minForwardFraction??.6,i=e.minDistinct??3,s=e.finaleFraction??.8,a=[],l=t.length;if(l<2)return a.push(`ramp has ${l} level(s) \u2014 need at least 2 to form a curve`),a;let u=ua(t);t[l-1]<t[0]&&a.push(`curve descends overall: finale (${t[l-1]}) is easier than the opener (${t[0]}) \u2014 the game gets EASIER`),u.max>0&&t[l-1]<u.max*s&&a.push(`finale (${t[l-1]}) is well below the peak (${u.max}) \u2014 the hardest level is buried mid-campaign, so it ends on an anticlimax`);let c=0,m=0;for(let p=1;p<l;p++){let f=t[p]-t[p-1];f>0&&(c+=f,m++)}let d=m>0?c/m:0,h=Math.max(r,d*n);for(let p=1;p<l;p++){let f=t[p]-t[p-1];f>h&&a.push(`difficulty cliff at level ${p+1}: jumps ${t[p-1]}\u2192${t[p]} (+${f}), past the +${h.toFixed(1)} envelope \u2014 smooth it with an intermediate level`)}return u.forwardFraction<o&&a.push(`only ${(u.forwardFraction*100).toFixed(0)}% of steps make progress (need \u2265 ${(o*100).toFixed(0)}%) \u2014 the curve wanders/descends instead of building`),u.distinct<i&&a.push(`only ${u.distinct} distinct difficulty value(s) across ${l} levels (need \u2265 ${i}) \u2014 the curve is flat; levels don't actually differ in challenge`),Zm(a)}function ed(t,e={}){let n=ca(t,e);if(n.length)throw new Error(`hayao: difficulty ramp is ill-shaped \u2014 ${n[0]}`)}function td(t,e,n){let r=Math.max(2,n.panels??12),o=Math.max(1,Math.ceil(e.length/(r-1))),i=[{frame:0,inner:st(t.render(),"p0")}];for(let v=0;v<e.length;v++)t.step(e[v]),((v+1)%o===0||v===e.length-1)&&i.push({frame:v+1,inner:st(t.render(),`p${i.length}`)});let s=Math.max(1,n.cols??4),a=n.panelWidth??320,l=Math.round(a*n.height/n.width),u=18,c=8,m=a+c,d=l+u+c,h=Math.ceil(i.length/s),p=s*m+c,f=h*d+c,g=n.background??"#ffffff",k=i.map((v,M)=>{let I=c+M%s*m,x=c+Math.floor(M/s)*d;return`<g transform="translate(${I} ${x})"><svg width="${a}" height="${l}" viewBox="0 0 ${n.width} ${n.height}"><rect x="0" y="0" width="${n.width}" height="${n.height}" fill="${g}"/>`+v.inner+`</svg><rect x="0" y="0" width="${a}" height="${l}" fill="none" stroke="#999" stroke-width="1"/><text x="${a/2}" y="${l+13}" font-size="11" font-family="monospace" text-anchor="middle" fill="#555">f ${v.frame} \xB7 ${(v.frame/60).toFixed(1)}s</text></g>`}).join("");return`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${p} ${f}" width="${p}" height="${f}"><rect x="0" y="0" width="${p}" height="${f}" fill="#f4f4f2"/>`+k+"</svg>"}function Bo(t){let e=t.left.length,n=new Float32Array(e);for(let r=0;r<e;r++)n[r]=(t.left[r]+t.right[r])*.5;return n}function ma(t,e,n,r,o){let i=Math.max(1,Math.floor(t.length/e)),s=`M0 ${o}`,a="";for(let l=0;l<e;l++){let u=0,c=0,m=l*i;for(let h=0;h<i&&m+h<t.length;h++){let p=t[m+h];p>c&&(c=p),p<u&&(u=p)}let d=l/e*n;s+=` L${d.toFixed(1)} ${(o-c*(r/2)).toFixed(1)}`,a=` L${d.toFixed(1)} ${(o-u*(r/2)).toFixed(1)}`+a}return s+a+" Z"}function nd(t,e={}){let n=e.width??900,r=e.timeBins??220,o=e.freqBands??64,i=16,s=n-i*2,a=70,l=200,u=84,c=i*5+a*2+l+u,m=It(Bo(t)),d=ma(t.left,r,s,a,a/2),h=ma(t.right,r,s,a,a/2),p=Bo(t),f=2048,g=Math.max(1,Math.floor(p.length/r)),k=s/r,v=l/o,M="";for(let C=0;C<r;C++){let E=C*g;if(E+64>=p.length)break;let R=Et(p.subarray(E,Math.min(E+f,p.length)));if(R.length===0)continue;let S=Math.max(1,Math.floor(R.length/o));for(let T=0;T<o;T++){let L=0;for(let ee=0;ee<S;ee++)L+=R[T*S+ee]??0;let H=L>1e-6?20*Ft(L):-120,$=Math.max(0,Math.min(1,(H+60)/60));if($<.03)continue;let Y=i+C*k,K=i*3+a*2+l-(T+1)*v,te=rd($);M+=`<rect x="${Y.toFixed(1)}" y="${K.toFixed(1)}" width="${(k+.6).toFixed(1)}" height="${(v+.6).toFixed(1)}" fill="${te}"/>`}}let I=od(m).map((C,E)=>`<text x="${i+4}" y="${c-u+20+E*18}" font-family="monospace" font-size="12" fill="#e8e4d8">${C}</text>`).join(""),x=i,b=i*2+a,w=(C,E)=>`<text x="${i}" y="${E-3}" font-family="monospace" font-size="10" fill="#8a8474">${C}</text>`;return`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${n} ${c}" width="${n}" height="${c}"><rect width="${n}" height="${c}" fill="#1a1814"/>`+(e.title?`<text x="${i}" y="${i-3}" font-family="monospace" font-size="12" fill="#d8b25a">${id(e.title)}</text>`:"")+w("L",x)+`<g transform="translate(${i} ${x})"><rect width="${s}" height="${a}" fill="#211e18"/><path d="${d}" fill="#5a9ac4" opacity="0.9"/></g>`+w("R",b)+`<g transform="translate(${i} ${b})"><rect width="${s}" height="${a}" fill="#211e18"/><path d="${h}" fill="#5ac48f" opacity="0.9"/></g><rect x="${i}" y="${i*3+a*2}" width="${s}" height="${l}" fill="#0d0c0a"/>`+M+`<rect x="${i}" y="${c-u}" width="${s}" height="${u-i}" fill="#211e18"/>`+I+"</svg>"}function rd(t){let e=Math.round(40+t*200),n=Math.round(20+t*t*150),r=Math.round(30+t*40);return`rgb(${e},${n},${r})`}function od(t){return[`dur ${t.durationSec.toFixed(2)}s peak ${t.peakDb.toFixed(1)} dBFS rms ${t.rms.toFixed(3)}`,`centroid ${Math.round(t.centroidHz)} Hz zcr ${Math.round(t.zcr)}/s`,`tempo ~${Math.round(t.tempoBpm)} bpm onsets ${t.onsetDensity.toFixed(1)}/s`]}function id(t){return t.replace(/[<>&]/g,e=>e==="<"?"<":e===">"?">":"&")}function sd(t,e){let n=It(Bo(t)),r=[],o=(i,s)=>{i||r.push(s)};if(e.minDurationSec!==void 0&&o(n.durationSec>=e.minDurationSec,`duration ${n.durationSec.toFixed(2)}s < min ${e.minDurationSec}`),e.maxDurationSec!==void 0&&o(n.durationSec<=e.maxDurationSec,`duration ${n.durationSec.toFixed(2)}s > max ${e.maxDurationSec}`),e.maxPeakDb!==void 0&&o(n.peakDb<=e.maxPeakDb,`peak ${n.peakDb.toFixed(1)}dB > max ${e.maxPeakDb}`),e.minRms!==void 0&&o(n.rms>=e.minRms,`rms ${n.rms.toFixed(3)} < min ${e.minRms} (too quiet?)`),e.minCentroidHz!==void 0&&o(n.centroidHz>=e.minCentroidHz,`centroid ${Math.round(n.centroidHz)}Hz < min ${e.minCentroidHz}`),e.maxCentroidHz!==void 0&&o(n.centroidHz<=e.maxCentroidHz,`centroid ${Math.round(n.centroidHz)}Hz > max ${e.maxCentroidHz}`),e.tempoBpm!==void 0){let i=e.tempoToleranceBpm??12;o(Math.abs(n.tempoBpm-e.tempoBpm)<=i,`tempo ${Math.round(n.tempoBpm)}bpm not within ${i} of ${e.tempoBpm}`)}return{ok:r.length===0,failures:r,features:n}}var pn=class{rng;clock;input=new Jt;events=new Wt;resources=new Map;state={};width;height;paused=!1;timeScale=1;root;activeCamera=null;seed;freeQueue=[];started=!1;tuningValues;guardDeterminism;warnedClamp=!1;warnedNondet=!1;constructor(e={}){this.seed=e.seed??1,this.rng=new ue(this.seed),this.clock=new At(e.clock),this.width=e.width??1280,this.height=e.height??720,this.tuningValues={...e.tuning??{}},this.guardDeterminism=e.guardDeterminism??!1,this.root=new _({name:"root"})}tune(e){let n=this.tuningValues[e];if(n===void 0)throw new Error(`tune('${e}'): no such knob declared in the game's tuning spec`);return n}resource(e){if(!this.resources.has(e)){let n=[...this.resources.keys()].join(", ")||"(none)";throw new Error(`resource('${e}'): not set. Available: ${n}`)}return this.resources.get(e)}get time(){return this.clock.simTimeSec}get frame(){return this.clock.frame}setRoot(e){this.root&&this.root.exitTree(),this.root=e,this.started=!1}requestFree(e){this.freeQueue.push(e)}ensureStarted(){this.started||(this.root.enterTree(this),this.started=!0)}step(e=[],n){if(typeof e=="string"||typeof e[Symbol.iterator]!="function")throw new TypeError(`step(actionsDown): pass an array/iterable of action names, got ${typeof e=="string"?`the string '${e}'`:typeof e}`);this.ensureStarted();let r=this.guardDeterminism?this.installGuard():null;try{this.input.beginFrame(e,n),this.root.updateTree(this.clock.dt*this.timeScale,this.clock.dt,"pausable",this.paused),this.flushFree(),this.clock.tick()}finally{r?.()}}installGuard(){let e=globalThis.Math,n=e.random,r=globalThis.Date.now,o=i=>{if(this.warnedNondet)return;this.warnedNondet=!0;let s=new Error().stack?.split(`
|
|
197
197
|
`).slice(2,5).join(`
|
|
198
198
|
`)??"";console.warn(`hayao: ${i} called during step() \u2014 nondeterministic. Use world.rng / ctx.time instead.
|
|
199
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);})();
|
|
200
|
+
`)}camera(){if(!this.activeCamera)return null;let e=this.activeCamera.worldTransform();return{pos:{x:e.e,y:e.f},zoom:this.activeCamera.zoom}}viewTransform(){if(!this.activeCamera)return oe;let e=this.activeCamera,n=e.worldTransform();return Ne(Ge({x:this.width/2,y:this.height/2},0,{x:e.zoom,y:e.zoom}),De(n))}worldToScreen(e){return bt(this.viewTransform(),e)}screenToWorld(e){return bt(De(this.viewTransform()),e)}render(){this.ensureStarted();let e=[];return this.root.collectDraw(e,this.viewTransform()),e}hash(){return Bt({seed:this.seed,rng:this.rng.getState(),clock:this.clock.getState(),input:this.input.getState(),state:this.state,tree:this.root.serialize(),...Object.keys(this.tuningValues).length>0?{tuning:this.tuningValues}:{},...this.paused?{paused:!0}:{},...this.timeScale!==1?{timeScale:this.timeScale}:{}})}snapshot(){return{seed:this.seed,rng:this.rng.getState(),clock:this.clock.getState(),input:this.input.getState(),state:structuredClone(this.state),tree:this.root.serialize(),tuning:{...this.tuningValues},...this.paused?{paused:!0}:{},...this.timeScale!==1?{timeScale:this.timeScale}:{}}}restore(e){this.seed=e.seed,this.rng.setState(e.rng),this.clock.setState(e.clock),this.input.setState(e.input),this.state=structuredClone(e.state),e.tuning&&(this.tuningValues={...e.tuning}),this.paused=e.paused??!1,this.timeScale=e.timeScale??1,gr(1e6),this.setRoot(Nn(e.tree)),this.ensureStarted()}probe(){return{frame:this.frame,time:this.time,hash:this.hash(),nodes:this.root.query("Sprite").length+this.root.query("Text").length}}};var ad={num(t,e){return{key:t,type:"number",...e}},color(t,e){return{key:t,type:"color",cosmetic:!0,...e}},enumOf(t,e){return{key:t,type:"enum",...e}}};function fn(t,e){let n={};if(!t)return n;for(let r of t.knobs){n[r.key]=r.default;let o=e?.[r.key];if(o!==void 0)if(r.type==="number"){let i=typeof o=="number"?o:Number(o);if(!Number.isFinite(i))continue;let s=r.min??-1/0,a=r.max??1/0;n[r.key]=Math.min(a,Math.max(s,i))}else r.type==="enum"?typeof o=="string"&&(r.options??[]).includes(o)&&(n[r.key]=o):typeof o=="string"&&(n[r.key]=o)}return n}function ld(t){return{width:1280,height:720,seed:1,background:"#f3ecdb",inputMap:Fn,...t}}function Te(t,e){let n=typeof e=="number"?{seed:e}:e??{},r=new pn({seed:n.seed??t.seed??1,width:t.width??1280,height:t.height??720,clock:t.clock,tuning:fn(t.tuning,n.tuning)});return r.setRoot(t.build(r)),t.probe&&(r.probe=()=>t.probe(r)),r}function ud(t){return t.inputMap??Fn}function cd(t,e){let n=Te(t),r=e?.frames??[];for(let o of r)n.step(o);return{world:n,hash:n.hash(),steps:r.length}}function zo(t,e,n){let r=typeof n=="number"?{toFrame:n}:n??{},o=Te(t,{seed:e.seed,tuning:e.tuningValues});e.startSnapshot&&(o.restore(structuredClone(e.startSnapshot)),t.attach?.(o)),r.onWorld?.(o);let i=Math.min(r.toFrame??e.inputLog.frames.length,e.inputLog.frames.length),s=0,a=0,l={...e.tuningValues};for(let u=0;u<i;u++){for(;a<e.knobEvents.length&&e.knobEvents[a].frame===u;){let c=e.knobEvents[a++];l[c.key]=c.value;let m=o.snapshot();m.tuning={...l},o.restore(m),t.attach?.(o)}for(;s<e.axesLog.length&&e.axesLog[s][0]===u;){let[,c,m]=e.axesLog[s++];o.input.axes.set(c,m)}o.step(e.inputLog.frames[u]),r.onFrame?.(o,u)}return o}function da(t){let{frame:e,time:n,hash:r,...o}=t;return JSON.stringify(o)}function md(t){let e=t.px??t.x,n=t.py??t.y;return typeof e=="number"&&typeof n=="number"?{x:e,y:n}:null}function dd(t){let e=[],n=null;for(let o of t.wallClockMarks)o.kind==="visibility-hidden"&&n===null&&(n=o.frame),o.kind==="visibility-visible"&&n!==null&&(e.push([n,o.frame]),n=null);n!==null&&e.push([n,t.inputLog.frames.length]);let r=null;for(let o of t.screenEvents)(o.kind==="overlay-show"||o.kind==="pause")&&r===null&&(r=o.frame),(o.kind==="overlay-hide"||o.kind==="resume")&&r!==null&&(e.push([r,o.frame]),r=null);return e}var hd=(t,e)=>e.some(([n,r])=>t>=n&&t<r);function pd(t,e,n={}){let r=n.hesitationFrames??45,o=n.futileWindow??30,i=n.quitWindow??300,s=n.clusterPx??64,a=e.inputLog.frames,l=dd(e),u=new Set(e.axesLog.map(([S])=>S)),c=[],m=null;for(let S=0;S<=a.length;S++){let T=S<a.length&&a[S].length===0&&!u.has(S);if(T&&m===null&&(m=S),!T&&m!==null){let L=S-m;L>=r&&!hd(m,l)&&c.push({startFrame:m,frames:L}),m=null}}let d=new Map;for(let S=0;S<a.length;S++){let T=S>0?a[S-1]:[];for(let L of a[S])T.includes(L)||(d.has(L)||d.set(L,[]),d.get(L).push(S))}let p=Object.keys(t.inputMap??{}).filter(S=>!d.has(S)),f=new Set;for(let S of c)f.add(S.startFrame);for(let S of e.annotations)f.add(Math.max(0,Math.min(S.frame,a.length-1)));for(let[,S]of d)for(let T of S)f.add(Math.max(0,T-1)),f.add(Math.min(a.length-1,T+o));a.length>0&&f.add(a.length-1);let g=new Map,k=[],v=!1,M=-1,I=zo(t,e,{onWorld:S=>{S.events.on("death",()=>k.push({frame:M+1,pos:md(S.probe())})),S.events.on("goal",()=>v=!0)},onFrame:(S,T)=>{M=T,f.has(T)&&g.set(T,S.probe())}}),x=a.length>0?g.get(a.length-1)??I.probe():I.probe();x.won===!0&&(v=!0);let b=c.map(S=>({...S,probe:g.get(S.startFrame)??{}})),w=new Map;for(let S of k){let T=S.pos?`${Math.round(S.pos.x/s)}:${Math.round(S.pos.y/s)}`:"unknown",L=w.get(T)??{x:S.pos?.x??0,y:S.pos?.y??0,count:0,frames:[]};L.count++,L.frames.push(S.frame),w.set(T,L)}let C=[];for(let[S,T]of d){let L=[];for(let H of T){let $=g.get(Math.max(0,H-1)),Y=g.get(Math.min(a.length-1,H+o));$&&Y&&da($)===da(Y)&&L.push(H)}L.length>0&&C.push({action:S,futilePresses:L.length,totalPresses:T.length,frames:L})}let E=e.annotations.map(S=>{let T=Math.max(0,Math.min(S.frame,a.length-1));return{frame:S.frame,tag:S.tag,...S.note!==void 0?{note:S.note}:{},probe:g.get(T)??{}}}),R={sessionId:e.id,game:e.game,buildRef:e.buildRef,seed:e.seed,variant:e.variant,frames:a.length,simSeconds:I.time,reachedGoal:v,deaths:k.length,hesitations:b,deathClusters:[...w.values()].sort((S,T)=>T.count-S.count),futileVerbs:C.sort((S,T)=>T.futilePresses-S.futilePresses),annotations:E,knobEvents:e.knobEvents,unusedActions:p};if(!v&&a.length>0){let S=Math.max(0,a.length-i);R.quit={frame:a.length-1,probe:x,recentDeaths:k.filter(T=>T.frame>=S).length,recentHesitations:b.filter(T=>T.startFrame>=S).length,endReason:e.endReason}}return R}function fd(t,e,n,r){let o=t.palette?.bg??"#141821",i=t.palette?.fg??(_e(o)>.4?"#14171f":"#f4efe3"),s=t.title??e.title,a={a:1,b:0,c:0,d:1,e:0,f:0};return[{kind:"rect",x:0,y:0,w:n,h:r,fill:o,transform:a,z:0},{kind:"text",text:s,x:n/2,y:r/2,size:Math.round(r*.06),align:"center",weight:700,fill:i,transform:a,z:1},{kind:"text",text:"loading\u2026",x:n/2,y:r/2+r*.08,size:Math.round(r*.03),align:"center",fill:i,opacity:.7,transform:a,z:1}]}function bn(t,e,n={}){let r=t.width??1280,o=t.height??720,i=t.background??"#f3ecdb",s=Te(t,n.world),a=n.renderer==="canvas"?new lt({width:r,height:o,background:i}):n.renderer==="webgl"?new on({width:r,height:o,background:i}):new at({width:r,height:o,background:i});e.style.position=e.style.position||"relative",a.mount?.(e),un(e);let l=new et(t.inputMap??{},document),u=new Yt(a,{keyboard:l}),c=[...n.sources??[]],m=Fo(),d=()=>s.input.declareActions(l.actionNames());d();let h=()=>{je.start();let D=ze.get();je.setVolumes(D),window.removeEventListener("pointerdown",h),window.removeEventListener("keydown",h)};window.addEventListener("pointerdown",h),window.addEventListener("keydown",h);let p=()=>a.draw(s.render()),f=()=>{s=Te(t,n.world),d(),p()},g=n.shell===!1?null:new mn({title:t.title,onRestart:n.onRestart??f,onPause:D=>n.onPause?.(D)}),k=t.splash===!1?null:t.splash??{},v=k&&!m?fd(k,t,r,o):null,M=!m,I=[],x,b=new Promise(D=>x=D),w=performance.now(),C=performance.now(),E=()=>{if(M){M=!1,C=performance.now(),p(),x();for(let D of I.splice(0))D()}},R=D=>{if(!m&&!g?.isPaused&&!n.isHeld?.()){u.sample(s.input);for(let z of c)z.sample(s.input);let A=l.currentActions(),O=s.advance(D,A);O>0&&(l.clearPressed(),n.onAdvance?.(s,O,A))}p()},S=0,T,L=null,H=!1,$=16,Y=()=>{S!==0&&(cancelAnimationFrame(S),S=0),T!==void 0&&(clearTimeout(T),T=void 0)},K=D=>{H||(L=D,document.hidden?T=setTimeout(()=>{T=void 0,L=null,D(performance.now())},$):S=requestAnimationFrame(A=>{S=0,L=null,D(A)}))},te=()=>{let D=L;D!==null&&(Y(),L=null,K(D))};document.addEventListener("visibilitychange",te);let ee=D=>{if(M){v&&a.draw(v),K(ee);return}let A=D-C;C=D,R(A),K(ee)};if(K(ee),M){let D=k?.minDurationMs??0,A=t.preload?Promise.resolve().then(()=>t.preload(s)):Promise.resolve(),O=new Promise(z=>setTimeout(z,Math.max(0,D-(performance.now()-w))));Promise.all([A,O]).then(E).catch(z=>{console.error("hayao: preload failed \u2014",z),E()})}else x();let ie={get world(){return s},renderer:a,input:l,pointer:u,canvas:a.element,toDesign:(D,A)=>a.toDesign?.(D,A)??{x:D,y:A},viewport:()=>a.viewport?.(),ready:b,onReady(D){M?I.push(D):D()},addSource(D){return c.push(D),()=>{let A=c.indexOf(D);A!==-1&&c.splice(A,1),D.dispose?.()}},tick(D){R(D??s.clock.stepMs)},stop(){H=!0,L=null,Y(),document.removeEventListener("visibilitychange",te),l.dispose(),u.dispose();for(let D of c)D.dispose?.();c.length=0,g?.dispose(),a.dispose?.()},restart:f};return m&&Ao({get world(){return s},stepOnce:(D=[])=>{s.step(D),p()},renderSVG:()=>en(s.render(),r,o,i),setPaused:()=>{}}),ie}function _o(t,e,n,r){let o=new Event(t,{bubbles:!0});return o.clientX=e,o.clientY=n,o.pointerId=r,o.button=0,o}function bd(t,e){if(typeof document>"u")throw new Error("verify/dom: no DOM found \u2014 set the test's environment to jsdom (// @vitest-environment jsdom).");let n=!e,r=e??document.createElement("div");n&&document.body.appendChild(r);let o=bn(t,r,{shell:!1,isHeld:()=>!0}),i=o.canvas;return{handle:o,touchDown(s,a,l=1){i?.dispatchEvent(_o("pointerdown",s,a,l))},touchMove(s,a,l=1){i?.dispatchEvent(_o("pointermove",s,a,l))},touchUp(s=1){globalThis.dispatchEvent?.(_o("pointerup",0,0,s))},step(s=1,a){for(let l=0;l<s;l++)o.pointer.sample(o.world.input),o.world.step(o.input.currentActions(),a),o.input.clearPressed()},dispose(){o.stop(),n&&r.remove()}}}var Oo=class{constructor(e,n,r,o){this.states=e;this.transitions=n;this.ctx=o;this.current=r,this.states[r]?.onEnter?.(o)}states;transitions;ctx;current;update(e){for(let n of this.transitions)if((n.from==="*"||n.from===this.current)&&n.when(this.ctx)){this.go(n.to);break}this.states[this.current]?.onUpdate?.(this.ctx,e)}go(e){e!==this.current&&(this.states[this.current]?.onLeave?.(this.ctx),this.current=e,this.states[e]?.onEnter?.(this.ctx))}is(...e){return e.includes(this.current)}getState(){return this.current}setState(e){this.current=e}},Go=class{constructor(e,n){this.defs=e;if(!e[n])throw new Error(`hayao: PhaseClock has no phase '${n}'`);this.phase=n}defs;phase;elapsed=0;get duration(){return this.defs[this.phase]?.duration??0}progress(e=n=>n){let n=this.duration,r=n>0?this.elapsed/n:1;return e(r<0?0:r>1?1:r)}get done(){return this.elapsed>=this.duration}update(e){this.elapsed+=e;let n=!1,r=0;for(;this.elapsed>=this.duration&&this.defs[this.phase]?.next!==void 0&&r++<1024;){let o=this.elapsed-this.duration;this.phase=this.defs[this.phase].next,this.elapsed=o,n=!0}return n}to(e){if(!this.defs[e])throw new Error(`hayao: PhaseClock has no phase '${e}'`);this.phase=e,this.elapsed=0}getState(){return{phase:this.phase,elapsed:this.elapsed}}setState(e){this.phase=e.phase,this.elapsed=e.elapsed}};function gd(t){return{kind:"sleep",left:t}}function yd(t){return{kind:"cond",cond:t}}function xd(){return{kind:"next"}}function vd(...t){return{kind:"race",waits:t}}function wd(...t){return{kind:"all",waits:t}}var ha=1e-9;function Vo(t,e){if(pa(t))return t.done?0:-1;switch(t.kind){case"sleep":return t.left-=e,t.left<=ha?0:-1;case"cond":return!t.met&&t.cond()&&(t.met=!0),t.met?0:-1;case"next":return t.passed=!0,0;case"race":{let n=-1;for(let r=0;r<t.waits.length;r++)Vo(t.waits[r],e)>=0&&n<0&&(n=r);return n}case"all":{let n=!0;for(let r of t.waits)Ho(r)||Vo(r,e)<0&&(n=!1);return n?0:-1}}}function Ho(t){if(pa(t))return t.done;switch(t.kind){case"sleep":return t.left<=ha;case"cond":return t.met===!0;case"next":return t.passed===!0;case"race":return t.waits.some(Ho);case"all":return t.waits.every(Ho)}}function pa(t){return t instanceof tr}var tr=class{name;done=!1;wait=null;gen;constructor(e,n){this.name=n,this.gen=e()}resume(e){try{let n=this.gen.next(e);n.done?this.done=!0:this.wait=n.value}catch(n){this.done=!0,console.warn(`[hayao] coroutine "${this.name}" threw and was stopped:`,n)}}stop(){if(!this.done){this.done=!0;try{this.gen.return(void 0)}catch{}}}},qo=class{runners=[];pending=[];nextId=0;start(e,n){let r=new tr(e,n??`co${this.nextId}`);return this.nextId++,this.pending.push(r),r}step(e){this.pending.length>0&&(this.runners.push(...this.pending),this.pending.length=0);for(let r of this.runners){if(r.done)continue;if(r.wait===null){r.resume(0);continue}let o=Vo(r.wait,e);o>=0&&(r.wait=null,r.resume(o))}let n=0;for(let r of this.runners)r.done||(this.runners[n++]=r);this.runners.length=n}stopAll(){for(let e of this.runners)e.stop();for(let e of this.pending)e.stop();this.runners.length=0,this.pending.length=0}get active(){let e=0;for(let n of this.runners)n.done||e++;for(let n of this.pending)n.done||e++;return e}};function kd(t){let e=0;for(let n of t)e+=n>0?n:0;return e}function Uo(t,e){let n=kd(e);if(n<=0)throw new Error("hayao: weightedIndex needs at least one positive weight");let r=t.float()*n;for(let o=0;o<e.length;o++){let i=e[o]>0?e[o]:0;if(r<i)return o;r-=i}for(let o=e.length-1;o>=0;o--)if(e[o]>0)return o;return e.length-1}function Sd(t,e,n){if(e.length!==n.length)throw new Error("hayao: weightedPick items/weights length mismatch");return e[Uo(t,n)]}function Xo(t,e){return e[Uo(t,e.map(n=>n.weight))].value}var jo=class{values;cumulative;total;constructor(e){if(e.length===0)throw new Error("hayao: LootTable needs at least one entry");let n=[],r=[],o=0;for(let i of e)o+=i.weight>0?i.weight:0,n.push(i.value),r.push(o);if(o<=0)throw new Error("hayao: LootTable needs at least one positive weight");this.values=n,this.cumulative=r,this.total=o}roll(e){let n=e.float()*this.total;for(let r=0;r<this.cumulative.length;r++)if(n<this.cumulative[r])return this.values[r];return this.values[this.values.length-1]}rollMany(e,n){let r=[];for(let o=0;o<n;o++)r.push(this.roll(e));return r}};function fa(t,e,n,r={}){let o=r.maxNodes??1e6,i=[],s=new Map,a=new Map,l=n(t);a.set(l,0);let u=[t];if(i.push(t),r.goal?.(t))return{order:i,cameFrom:s,dist:a};let c=0;for(;u.length>0&&c<o;){let m=[];for(let d of u){let h=a.get(n(d))??0;for(let p of e(d)){let f=n(p);if(!a.has(f)){if(a.set(f,h+1),s.set(f,d),i.push(p),c++,r.goal?.(p))return{order:i,cameFrom:s,dist:a};m.push(p)}}}u=m}return{order:i,cameFrom:s,dist:a}}function Cd(t,e,n,r){let o=[r],i=r,s=e(n);for(;e(i)!==s;){let a=t.get(e(i));if(a===void 0)return[];i=a,o.push(i)}return o.reverse(),o}function ba(t,e,n,r,o={}){let i=o.heuristic??(()=>0),s=o.maxNodes??1e6,a=new Map,l=new Map,u=new Jo,c=r(t);l.set(c,0),u.push(t,i(t));let m=0;for(;u.size>0&&m<s;){let{item:d,priority:h}=u.pop(),p=r(d),f=l.get(p)??1/0;if(!(h>f+i(d)+1e-9)){if(e(d))return{path:Td(a,r,d),cost:f};m++;for(let g of n(d)){let k=r(g.node),v=f+g.cost;v<(l.get(k)??1/0)&&(l.set(k,v),a.set(k,d),u.push(g.node,v+i(g.node)))}}}return null}function Td(t,e,n){let r=[n],o=n,i=t.get(e(o));for(;i!==void 0;)o=i,r.push(o),i=t.get(e(o));return r.reverse(),r}var Jo=class{items=[];prio=[];seq=[];counter=0;get size(){return this.items.length}push(e,n){this.items.push(e),this.prio.push(n),this.seq.push(this.counter++),this.bubbleUp(this.items.length-1)}pop(){let e=this.items[0],n=this.prio[0],r=this.items.length-1;return this.swap(0,r),this.items.pop(),this.prio.pop(),this.seq.pop(),this.items.length>0&&this.bubbleDown(0),{item:e,priority:n}}less(e,n){return this.prio[e]<this.prio[n]||this.prio[e]===this.prio[n]&&this.seq[e]<this.seq[n]}bubbleUp(e){for(;e>0;){let n=e-1>>1;if(!this.less(e,n))break;this.swap(e,n),e=n}}bubbleDown(e){let n=this.items.length;for(;;){let r=2*e+1,o=2*e+2,i=e;if(r<n&&this.less(r,i)&&(i=r),o<n&&this.less(o,i)&&(i=o),i===e)break;this.swap(e,i),e=i}}swap(e,n){[this.items[e],this.items[n]]=[this.items[n],this.items[e]],[this.prio[e],this.prio[n]]=[this.prio[n],this.prio[e]],[this.seq[e],this.seq[n]]=[this.seq[n],this.seq[e]]}},gn=[{x:0,y:-1},{x:1,y:0},{x:0,y:1},{x:-1,y:0}],nr=[...gn,{x:1,y:-1},{x:1,y:1},{x:-1,y:1},{x:-1,y:-1}],ga=t=>`${t.x},${t.y}`;function Md(t,e,n,r){let o=r?nr:gn;return i=>{let s=[];for(let a of o){let l=i.x+a.x,u=i.y+a.y;l<0||u<0||l>=e||u>=n||t(l,u)&&s.push({x:l,y:u})}return s}}function Yo(t,e,n){if(!e(t.x,t.y))return[];let r=Md(e,n.cols,n.rows,n.diagonal??!1);return fa(t,r,ga).order}function Rd(t,e,n,r=!1){let o=new Array(t*e).fill(-1),i=[],s=r?nr:gn;for(let a=0;a<e;a++)for(let l=0;l<t;l++){if(o[a*t+l]!==-1||!n(l,a))continue;let u=i.length,c=[],m=[{x:l,y:a}];for(o[a*t+l]=u;m.length>0;){let d=[];for(let h of m){c.push(h);for(let p of s){let f=h.x+p.x,g=h.y+p.y;if(f<0||g<0||f>=t||g>=e)continue;let k=g*t+f;o[k]!==-1||!n(f,g)||(o[k]=u,d.push({x:f,y:g}))}}m=d}i.push(c)}return{labels:o,cells:i}}function Pd(t,e,n,r){let o=r.diagonal??!1,i=o?nr:gn,s=r.cost??(()=>1),a=1.4142135623730951,l=m=>{let d=[];for(let h of i){let p=m.x+h.x,f=m.y+h.y;if(p<0||f<0||p>=r.cols||f>=r.rows||!n(p,f))continue;let g=h.x!==0&&h.y!==0;d.push({node:{x:p,y:f},cost:s(p,f)*(g?a:1)})}return d},u=m=>{let d=Math.abs(m.x-e.x),h=Math.abs(m.y-e.y);if(!o)return d+h;let p=Math.min(d,h);return d+h-(2-a)*p};if(!n(e.x,e.y))return null;let c=ba(t,m=>m.x===e.x&&m.y===e.y,l,ga,{heuristic:u,maxNodes:r.maxNodes});return c?c.path:null}function Dd(t){return(e,n)=>pe(t,e,n)!==U.SOLID}function Ed(t){return structuredClone(t)}var Ko=class{history=[];cursor=-1;limit;clone;constructor(e={}){this.limit=Math.max(1,e.limit??64),this.clone=e.clone??Ed}record(e){if(this.history.length=this.cursor+1,this.history.push(this.clone(e)),this.cursor=this.history.length-1,this.history.length>this.limit){let n=this.history.length-this.limit;this.history.splice(0,n),this.cursor-=n}}undo(){if(!(this.cursor<=0))return this.cursor--,this.clone(this.history[this.cursor])}redo(){if(!(this.cursor>=this.history.length-1))return this.cursor++,this.clone(this.history[this.cursor])}current(){return this.cursor>=0?this.clone(this.history[this.cursor]):void 0}get canUndo(){return this.cursor>0}get canRedo(){return this.cursor<this.history.length-1}get size(){return this.history.length}clear(){this.history.length=0,this.cursor=-1}},Qo=class{constructor(e){this.capacity=e;if(!Number.isInteger(e)||e<1)throw new Error("hayao: RingBuffer capacity must be a positive integer");this.buf=new Array(e)}capacity;buf;start=0;count=0;push(e){let n=(this.start+this.count)%this.capacity;this.buf[n]=e,this.count<this.capacity?this.count++:this.start=(this.start+1)%this.capacity}get length(){return this.count}get isFull(){return this.count===this.capacity}at(e){if(!(e<0||e>=this.count))return this.buf[(this.start+e)%this.capacity]}latest(){return this.at(this.count-1)}toArray(){let e=[];for(let n=0;n<this.count;n++)e.push(this.buf[(this.start+n)%this.capacity]);return e}clear(){this.start=0,this.count=0,this.buf.fill(void 0)}};var rr=class{map=new Map;get(e){return this.map.has(e)?this.map.get(e):null}set(e,n){this.map.set(e,n)}remove(e){this.map.delete(e)}keys(){return[...this.map.keys()]}},Zo=class{get(e){return null}set(e,n){}remove(e){}keys(){return[]}},or=class{constructor(e="hayao.save."){this.prefix=e}prefix;ls(){try{return typeof localStorage<"u"?localStorage:null}catch{return null}}get(e){try{return this.ls()?.getItem(this.prefix+e)??null}catch{return null}}set(e,n){try{this.ls()?.setItem(this.prefix+e,n)}catch{}}remove(e){try{this.ls()?.removeItem(this.prefix+e)}catch{}}keys(){let e=this.ls();if(!e)return[];let n=[];try{for(let r=0;r<e.length;r++){let o=e.key(r);o&&o.startsWith(this.prefix)&&n.push(o.slice(this.prefix.length))}}catch{}return n}};function ei(t){try{if(typeof localStorage<"u"){let e="__hayao_probe__";return localStorage.setItem(e,"1"),localStorage.removeItem(e),new or(t)}}catch{}return new rr}function Id(t){let e="",n=0;for(;n<t.length;){let r=t[n],o=1;for(;n+o<t.length&&t[n+o]===r;)o++;o>=4||r==="~"?e+="~"+r+o.toString(36)+"~":e+=r.repeat(o),n+=o}return e}function Ld(t){let e="",n=0;for(;n<t.length;)if(t[n]==="~"){let r=t[n+1],o=t.indexOf("~",n+2);if(r===void 0||o<0)throw new Error("hayao: malformed RLE stream");let i=parseInt(t.slice(n+2,o),36);if(!Number.isFinite(i)||i<1)throw new Error("hayao: malformed RLE count");e+=r.repeat(i),n=o+1}else e+=t[n],n++;return e}var ti="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",ya={};for(let t=0;t<ti.length;t++)ya[ti[t]]=t;function $d(t){let e="";for(let n of t){if(!Number.isInteger(n)||n<0)throw new Error(`hayao: packVarints expects non-negative integers, got ${n}`);let r=n;do{let o=r&31;r=Math.floor(r/32),r>0&&(o|=32),e+=ti[o]}while(r>0)}return e}function Nd(t){let e=[],n=0,r=1;for(let o of t){let i=ya[o];if(i===void 0)throw new Error(`hayao: unpackVarints saw invalid char "${o}"`);n+=(i&31)*r,i&32?r*=32:(e.push(n),n=0,r=1)}if(r!==1)throw new Error("hayao: unpackVarints hit a truncated stream");return e}var oi=1;function xa(t){return JSON.stringify({v:oi,snap:t})}function ni(t){if(!t)return null;let e;try{e=JSON.parse(t)}catch{return null}if(!e||typeof e!="object")return null;let n=e;if(n.v!==oi||!n.snap||typeof n.snap!="object")return null;let r=n.snap;return typeof r.seed!="number"||!r.rng||!r.clock||!r.input||!r.state||!r.tree?null:r}var ri=class{constructor(e,n=ei()){this.world=e;this.storage=n}world;storage;save(e="auto"){this.storage.set(e,xa(this.world.snapshot()))}load(e="auto"){let n=ni(this.storage.get(e));return n?(this.world.restore(n),!0):!1}has(e="auto"){return ni(this.storage.get(e))!==null}delete(e="auto"){this.storage.remove(e)}slots(){return this.storage.keys()}};function Fd(t){return{next:t.map(e=>e.time)}}function Ad(t,e,n,r){let o=[];for(let i=0;i<t.length;i++){let s=t[i],a=e.next[i]??s.time;for(;a<=n;){let l;if(typeof s.spawn=="string")l=s.spawn;else{if(!r)throw new Error("hayao: pollDirector needs an Rng to roll a weighted wave");l=Xo(r,s.spawn)}if(o.push({spawn:l,count:s.count??1,wave:i}),s.every&&s.every>0){if(a+=s.every,s.end!==void 0&&a>=s.end){a=1/0;break}}else{a=1/0;break}}e.next[i]=a}return o}function Wd(t,e){let n=new Map;for(let o of e)n.set(o,(n.get(o)??0)+1);let r=o=>(n.get(o)??0)>0;return t.filter(o=>(n.get(o.id)??0)>=(o.maxStacks??1)?!1:(o.requires??[]).every(r))}var Bd=new Set(["#","-","^","."," "]),yn=t=>t===U.SOLID,zd=t=>t===U.HAZARD,va=(t,e,n)=>({x:(t+.5)*n,y:(e+.5)*n});function _d(t){let e=t.tileSize??32,n=t.legend??{},r=t.rows,o=Math.max(0,...r.map(l=>l.length)),i=null,s=null,a=[];if(r.forEach((l,u)=>{for(let c=0;c<l.length;c++){let m=l[c];if(m==="S")i={x:c,y:u};else if(m==="G")s={x:c,y:u};else if(m in n){let d=va(c,u,e);a.push({kind:n[m],tx:c,ty:u,x:d.x,y:d.y})}}}),!i)throw new Error(`level "${t.name}": no spawn marker 'S'`);if(!s)throw new Error(`level "${t.name}": no goal marker 'G'`);return{name:t.name,tileSize:e,rows:r,legend:n,cols:o,rowCount:r.length,spawn:i,goal:s,entities:a}}function Od(t){let e=[],n=ir(t),r=o=>n.tiles[o.y*n.cols+o.x]??U.EMPTY;return t.rows.forEach((o,i)=>{for(let s=0;s<o.length;s++){let a=o[s];a==="S"||a==="G"||Bd.has(a)||a in t.legend||e.push(`unknown glyph '${a}' at (${s},${i}) \u2014 add it to the legend or use terrain '#/-/^/.'`)}}),yn(r(t.spawn))&&e.push(`spawn (${t.spawn.x},${t.spawn.y}) is inside a solid tile`),yn(r(t.goal))&&e.push(`goal (${t.goal.x},${t.goal.y}) is inside a solid tile`),[...new Set(e)]}function ir(t){return _r(t.rows,t.tileSize)}function Gd(t,e={}){let n=ir(t),r=(l,u)=>n.tiles[u*n.cols+l]??U.EMPTY,o=e.passable??((l,u)=>!yn(r(l,u))),i=Yo(t.spawn,o,{cols:n.cols,rows:n.rows,diagonal:e.diagonal}),s=new Set(i.map(l=>`${l.x},${l.y}`)),a=[];s.has(`${t.goal.x},${t.goal.y}`)||a.push("goal");for(let l of t.entities)s.has(`${l.tx},${l.ty}`)||a.push(`entity@${l.tx},${l.ty}`);return{ok:a.length===0,unreachable:a,reached:i.length}}function Vd(t,e){let n=ir(t),{cols:r,rows:o}=n,i=(v,M)=>v<0||M<0||v>=r||M>=o?U.SOLID:n.tiles[M*r+v],s=(v,M)=>{let I=i(v,M+1);return I===U.SOLID||I===U.ONEWAY},a=(v,M)=>!yn(i(v,M))&&!zd(i(v,M))&&s(v,M),u=(v=>{for(let M=v.y;M<o;M++)if(a(v.x,M))return{x:v.x,y:M};return null})(t.spawn);if(!u)return{ok:!1,unreachable:["goal"],reached:0};let c=(v,M)=>Math.abs(M.x-v.x)<=e.runTiles&&v.y-M.y<=e.jumpTiles,m=[];for(let v=0;v<o;v++)for(let M=0;M<r;M++)a(M,v)&&m.push({x:M,y:v});let d=v=>`${v.x},${v.y}`,h=new Set([d(u)]),p=[u];for(;p.length;){let v=p.shift();for(let M of m){let I=d(M);!h.has(I)&&c(v,M)&&(h.add(I),p.push(M))}}let f=[...h].map(v=>{let[M,I]=v.split(",").map(Number);return{x:M,y:I}}),k=!yn(i(t.goal.x,t.goal.y))&&(h.has(d(t.goal))||f.some(v=>c(v,t.goal)))?[]:["goal"];return{ok:k.length===0,unreachable:k,reached:h.size}}function Hd(t,e){let n=[],r=Math.max(t.rowCount,e.rowCount),o=Math.max(t.cols,e.cols),i=(u,c,m)=>u.rows[m]?.[c]??" ";for(let u=0;u<r;u++)for(let c=0;c<o;c++){let m=i(t,c,u),d=i(e,c,u);m!==d&&n.push({kind:"tile",detail:`(${c},${u}) '${m}' \u2192 '${d}'`})}let s=u=>`${u.kind}@${u.tx},${u.ty}`,a=new Set(t.entities.map(s)),l=new Set(e.entities.map(s));for(let u of e.entities)a.has(s(u))||n.push({kind:"entity+",detail:s(u)});for(let u of t.entities)l.has(s(u))||n.push({kind:"entity-",detail:s(u)});return(t.spawn.x!==e.spawn.x||t.spawn.y!==e.spawn.y)&&n.push({kind:"spawn",detail:`(${t.spawn.x},${t.spawn.y}) \u2192 (${e.spawn.x},${e.spawn.y})`}),(t.goal.x!==e.goal.x||t.goal.y!==e.goal.y)&&n.push({kind:"goal",detail:`(${t.goal.x},${t.goal.y}) \u2192 (${e.goal.x},${e.goal.y})`}),n}function wa(t,e){return br(`hayao/gen:${t>>>0}:${e}`)}var qd=(t,e,n)=>(n.minDepth===void 0||t>=n.minDepth)&&(n.maxDepth===void 0||t<=n.maxDepth)&&(n.minNodes===void 0||e>=n.minNodes)&&(n.maxNodes===void 0||e<=n.maxNodes);function ka(t,e){let n=e.seed??1,r=e.maxAttempts??e.count*60,o=e.dedupeKey??(u=>u.key(u.initial())),i=[],s=new Set,a=0,l=0;for(let u=0;u<r&&i.length<e.count;u++){a++;let c=wa(n,u),m=t(new ue(c)),d=mt(m,e.solve);if(!d.solvable||d.exhausted||d.depth===void 0)continue;l++;let h={path:d.path??[],depth:d.depth,nodes:d.nodes};if(!qd(h.depth,h.nodes,e))continue;let p=o(m,h);s.has(p)||e.reject?.(m,h,c)||(s.add(p),i.push({...h,index:0,seed:c,puzzle:m}))}return i.sort((u,c)=>u.depth-c.depth||u.nodes-c.nodes||u.seed-c.seed),i.forEach((u,c)=>u.index=c),{levels:i,attempts:a,solvable:l,complete:i.length>=e.count,seeds:i.map(u=>u.seed)}}function ii(t,e){let n=ka(t,e);if(!n.complete)throw new Error(`hayao: generator found only ${n.levels.length}/${e.count} in-band levels in ${n.attempts} attempts (${n.solvable} solvable). Widen the band [depth ${e.minDepth??0}..${e.maxDepth??"\u221E"}] or raise maxAttempts.`);return n.levels}function jd(t,e){return t(new ue(e))}function Ud(t){let e=t.seed??1,n=t.minutesPerLevel??1.5,r=[],o=[];return t.acts.forEach((i,s)=>{let a=i.factory??t.factory;if(!a)throw new Error(`hayao: act "${i.name}" has no factory and the campaign has no default`);let l=(e^(s+1)*2654435769)>>>0,u=ii(a,{count:i.count,seed:l,minDepth:i.minDepth,maxDepth:i.maxDepth,minNodes:i.minNodes,maxNodes:i.maxNodes,solve:i.solve??t.solve,maxAttempts:i.maxAttempts}),c=r.length;u.forEach((m,d)=>{r.push({...m,index:r.length,act:s,actName:i.name,actIndex:d})}),o.push({name:i.name,from:c,to:r.length-1})}),{levels:r,acts:o,difficulty:r.map(i=>i.depth),seeds:r.map(i=>i.seed),estMinutes:r.length*n}}function Ca(t,e){let n=new Map(t.pickups.map(o=>[o.id,o.grants])),r=new Set;for(let o of e){let i=n.get(o);i&&r.add(i)}return r}function Sa(t,e){return(t.requires??[]).every(n=>e.has(n))}function Ta(t,e,n){let r=[];for(let o of t.edges)o.from===e&&Sa(o,n)?r.push(o.to):!o.oneWay&&o.to===e&&Sa(o,n)&&r.push(o.from);return r}function sr(t,e="complete"){let n=o=>t.pickups.filter(i=>i.region===o),r=t.pickups.length;return{initial:()=>({region:t.start,taken:[]}),moves:o=>{let i=Ca(t,o.taken),s=[];for(let l of n(o.region))o.taken.includes(l.id)||s.push({kind:"take",pickup:l.id});let a=new Set;for(let l of Ta(t,o.region,i))a.has(l)||(a.add(l),s.push({kind:"move",to:l}));return s},apply:(o,i)=>{if(i.kind==="move")return{region:i.to,taken:o.taken};let s=[...o.taken,i.pickup].sort();return{region:o.region,taken:s}},isWin:o=>o.region===t.goal&&(e==="complete"||o.taken.length===r),key:o=>`${o.region}|${o.taken.join(",")}`}}var Ma={maxDepth:2e3,nodeCap:5e6};function Xd(t){return mt(sr(t,"complete"),Ma)}function Jd(t){return mt(sr(t,"full"),Ma)}function Ra(t,e){let n=new Set(e),r=new Set([t.start]),o=[t.start];for(;o.length;){let i=o.shift();for(let s of Ta(t,i,n))r.has(s)||(r.add(s),o.push(s))}return[...r]}function Yd(t,e="complete"){let n=sr(t,e),r=n.initial(),o=n.key(r),i=new Map([[o,r]]),s=new Map,a=new Set,l=[r];for(n.isWin(r)&&a.add(o);l.length;){let h=l.shift(),p=n.key(h),f=[];for(let g of n.moves(h)){let k=n.apply(h,g),v=n.key(k);f.push(v),i.has(v)||(i.set(v,k),n.isWin(k)&&a.add(v),l.push(k))}s.set(p,f)}let u=new Map;for(let[h,p]of s)for(let f of p)(u.get(f)??u.set(f,[]).get(f)).push(h);let c=new Set(a),m=[...a];for(;m.length;){let h=m.shift();for(let p of u.get(h)??[])c.has(p)||(c.add(p),m.push(p))}let d=[...i.keys()].filter(h=>!c.has(h)).sort();return{ok:d.length===0,deadEnds:d,statesExplored:i.size}}function Kd(t){let e=[],n=new Set;for(let a of t.regions)n.has(a.id)&&e.push(`duplicate region id "${a.id}"`),n.add(a.id);let r=a=>n.has(a);r(t.start)||e.push(`start region "${t.start}" is not defined`),r(t.goal)||e.push(`goal region "${t.goal}" is not defined`);for(let a of t.edges)r(a.from)||e.push(`edge references unknown region "${a.from}"`),r(a.to)||e.push(`edge references unknown region "${a.to}"`);let o=new Set;for(let a of t.pickups)o.has(a.id)&&e.push(`duplicate pickup id "${a.id}"`),o.add(a.id),r(a.region)||e.push(`pickup "${a.id}" is in unknown region "${a.region}"`);let i=t.pickups.map(a=>a.grants),s=new Set(Ra(t,i));for(let a of t.regions)s.has(a.id)||e.push(`region "${a.id}" is unreachable even with every ability`);return e}function Qd(t){let e=[];for(let n=1;n<=t;n++)e.push(`p${n}`);return e}var xn=(t,e)=>`${t}:${e}`;function $t(t,e){let n=[];for(let r of t){let o=e.get(r)??[];for(let i of o)n.push(xn(r,i))}return n.sort()}var ar=class{constructor(e,n){this.world=e;this.player=n}world;player;isDown(e){return this.world.input.isDown(xn(this.player,e))}justPressed(e){return this.world.input.justPressed(xn(this.player,e))}justReleased(e){return this.world.input.justReleased(xn(this.player,e))}},Zd=(t,e)=>new ar(t,e);var Zg=1,dt={mode:"lockstep",inputDelay:2,hashInterval:20,maxRollback:12,redundancy:3};function de(t){return JSON.stringify(t)}function Oe(t){try{let e=JSON.parse(t);return!e||typeof e!="object"||e.v!==1||typeof e.t!="string"?null:e}catch{return null}}function he(t){return{v:1,...t}}var si=class{peers=[];queue=[];tickCount=0;seq=0;sent=0;delay;dropEvery;constructor(e={}){this.delay=e.delay??0,this.dropEvery=e.dropEvery??0}connect(){let e=new lr(this,this.peers.length);return this.peers.push(e),e}enqueue(e,n){this.sent++,!(this.dropEvery>0&&this.sent%this.dropEvery===0)&&this.queue.push({data:e,from:n,dueTick:this.tickCount+this.delay,seq:this.seq++})}tick(){let e=this.queue.filter(n=>n.dueTick<=this.tickCount).sort((n,r)=>n.seq-r.seq);this.queue=this.queue.filter(n=>n.dueTick>this.tickCount),this.tickCount++;for(let n of e)for(let r of this.peers)r.peerIndex!==n.from&&r.isOpen&&r.deliver(n.data)}flush(){for(;this.queue.length>0;)this.tick()}get pending(){return this.queue.length}},lr=class{constructor(e,n){this.hub=e;this.peerIndex=n}hub;peerIndex;listeners=[];closeListeners=[];open=!0;send(e){this.open&&this.hub.enqueue(e,this.peerIndex)}onMessage(e){return this.listeners.push(e),()=>{this.listeners=this.listeners.filter(n=>n!==e)}}onClose(e){return this.closeListeners.push(e),()=>{this.closeListeners=this.closeListeners.filter(n=>n!==e)}}close(){if(this.open){this.open=!1;for(let e of this.closeListeners)e()}}get isOpen(){return this.open}deliver(e){for(let n of this.listeners)n(e)}},ai=class{channel;listeners=[];closeListeners=[];open=!0;constructor(e){this.channel=new BroadcastChannel(`hayao-net:${e}`),this.channel.onmessage=n=>{if(typeof n.data=="string")for(let r of this.listeners)r(n.data)}}send(e){this.open&&this.channel.postMessage(e)}onMessage(e){return this.listeners.push(e),()=>{this.listeners=this.listeners.filter(n=>n!==e)}}onClose(e){return this.closeListeners.push(e),()=>{this.closeListeners=this.closeListeners.filter(n=>n!==e)}}close(){if(this.open){this.open=!1,this.channel.close();for(let e of this.closeListeners)e()}}get isOpen(){return this.open}};function eh(t){return new Promise((e,n)=>{let r=new WebSocket(t),o=[],i=[],s=!1,a={send(l){s&&r.send(l)},onMessage(l){return o.push(l),()=>{let u=o.indexOf(l);u>=0&&o.splice(u,1)}},onClose(l){return i.push(l),()=>{let u=i.indexOf(l);u>=0&&i.splice(u,1)}},close(){s=!1,r.close()},get isOpen(){return s}};r.onopen=()=>{s=!0,e(a)},r.onmessage=l=>{if(typeof l.data=="string")for(let u of o)u(l.data)},r.onclose=()=>{let l=s;if(s=!1,l)for(let u of i)u()},r.onerror=()=>{s||n(new Error(`hayao-net: could not connect to ${t}`))}})}var ht=class{frames=new Map;contiguous=new Map;addPlayer(e){this.frames.has(e)||(this.frames.set(e,new Map),this.contiguous.set(e,-1))}removePlayer(e){this.frames.delete(e),this.contiguous.delete(e)}players(){return[...this.frames.keys()]}set(e,n,r){let o=this.frames.get(e);if(!o||o.has(n))return!1;o.set(n,[...r].sort());let i=this.contiguous.get(e)??-1;for(;o.has(i+1);)i++;return this.contiguous.set(e,i),!0}has(e,n){return this.frames.get(e)?.has(n)??!1}get(e,n){return this.frames.get(e)?.get(n)}latestAt(e,n){let r=this.frames.get(e);if(!r)return[];for(let o=n;o>=0;o--){let i=r.get(o);if(i)return i}return[]}contiguousThrough(e){return this.contiguous.get(e)??-1}confirmedFrame(){let e=1/0;for(let n of this.contiguous.values())e=Math.min(e,n);return e===1/0?-1:e}clearFrom(e,n){let r=this.frames.get(e);if(!r)return;for(let i of r.keys())i>=n&&r.delete(i);let o=this.contiguous.get(e)??-1;o>=n&&(o=n-1),this.contiguous.set(e,o)}prune(e){for(let n of this.frames.values())for(let r of n.keys())r<e&&n.delete(r)}};var Ie=class{world;localPlayer;config;startFrame;transport;buffer=new ht;roster=[];mergedLog=[];localHashes=new Map;pendingRemoteHashes=[];sentThrough;stallCount=0;desynced=!1;afterStepListeners=[];unsubscribe;onDesync;onStall;constructor(e){this.world=e.world,this.transport=e.transport,this.localPlayer=e.localPlayer,this.config={...dt,...e.config,mode:"lockstep"},this.startFrame=e.startFrame??0,this.onDesync=e.onDesync,this.onStall=e.onStall;for(let n of e.players)if(this.roster.push({player:n,from:this.startFrame,until:1/0}),this.buffer.addPlayer(n),this.startFrame===0||n===this.localPlayer)for(let r=this.startFrame;r<this.startFrame+this.config.inputDelay;r++)this.buffer.set(n,r,[]);this.sentThrough=this.startFrame+this.config.inputDelay-1,this.unsubscribe=this.transport.onMessage(n=>this.receive(n))}activePlayers(e){return this.roster.filter(n=>n.from<=e&&e<n.until).map(n=>n.player)}addPlayer(e,n){if(!this.roster.some(r=>r.player===e&&r.until===1/0)){this.roster.push({player:e,from:n,until:1/0}),this.buffer.addPlayer(e);for(let r=n;r<n+this.config.inputDelay;r++)this.buffer.set(e,r,[])}}removePlayer(e,n){let r=this.roster.find(o=>o.player===e&&o.until===1/0);r&&(r.until=n),this.buffer.clearFrom(e,n)}get frame(){return this.world.frame}get confirmedFrame(){let e=1/0;for(let n of this.activePlayers(this.world.frame))e=Math.min(e,this.buffer.contiguousThrough(n));return e===1/0?-1:e}get stalls(){return this.stallCount}tick(e=[]){if(this.desynced)return 0;let n=this.world.frame;this.scheduleLocal(e);let r=this.activePlayers(n);for(let s of r)if(!this.buffer.has(s,n))return this.stallCount++,this.onStall?.(s,n),0;let o=new Map;for(let s of r)o.set(s,this.buffer.get(s,n));let i=$t(r,o);return this.world.step(i),this.mergedLog.push(i),this.afterStep(this.world.frame),1}advance(e,n=[]){let r=0,o=this.world.clock.advance(e);for(let s=0;s<o&&this.tick(n)!==0;s++)r++;let i=0;for(;i++<8&&this.world.frame<this.remoteFrameEstimate()&&this.tick(n)===1;)r++;return r}inputLog(){return{frames:this.mergedLog.map(e=>e.slice())}}dispose(){this.unsubscribe()}deliver(e){this.receive(e)}onAfterStep(e){return this.afterStepListeners.push(e),()=>{this.afterStepListeners=this.afterStepListeners.filter(n=>n!==e)}}scheduleLocal(e){let n=this.world.frame+this.config.inputDelay;if(this.sentThrough>=n)return;for(;this.sentThrough<n;)this.sentThrough++,this.buffer.set(this.localPlayer,this.sentThrough,e);let r=Math.max(this.startFrame,n-this.config.redundancy+1),o=[];for(let i=r;i<=n;i++)o.push(this.buffer.get(this.localPlayer,i)??[]);this.transport.send(de(he({t:"input",player:this.localPlayer,from:r,frames:o})))}afterStep(e){if(e%this.config.hashInterval===0){let n=this.world.hash();this.localHashes.set(e,n),this.transport.send(de(he({t:"hash",player:this.localPlayer,frame:e,hash:n}))),this.checkPendingHashes()}if(e%64===0){this.buffer.prune(e-128);for(let n of this.localHashes.keys())n<e-512&&this.localHashes.delete(n)}for(let n of this.afterStepListeners)n(e)}receive(e){let n=Oe(e);if(n)if(n.t==="input"&&n.player!==this.localPlayer)for(let r=0;r<n.frames.length;r++)this.buffer.set(n.player,n.from+r,n.frames[r]);else n.t==="hash"&&n.player!==this.localPlayer&&(this.pendingRemoteHashes.push({player:n.player,frame:n.frame,hash:n.hash}),this.checkPendingHashes())}checkPendingHashes(){let e=[];for(let n of this.pendingRemoteHashes){let r=this.localHashes.get(n.frame);if(r===void 0){n.frame>this.world.frame-512&&e.push(n);continue}r!==n.hash&&!this.desynced&&(this.desynced=!0,this.onDesync?.({frame:n.frame,player:n.player,localHash:r,remoteHash:n.hash,log:this.inputLog(),startFrame:this.startFrame}))}this.pendingRemoteHashes=e}remoteFrameEstimate(){let e=-1;for(let n of this.roster)n.player===this.localPlayer||n.until!==1/0||(e=Math.max(e,this.buffer.contiguousThrough(n.player)-this.config.inputDelay));return e}};var vn=class{world;localPlayer;config;transport;players;buffer=new ht;attach;onDesync;onRollbackOverflow;ring;usedInputs=new Map;earliestBad=1/0;rollbackCount=0;resimulatedFrames=0;localHashes=new Map;dropped=new Map;pendingRemoteHashes=[];hashedThrough=-1;desynced=!1;overflowed=!1;unsubscribe;constructor(e){this.world=e.world,this.transport=e.transport,this.localPlayer=e.localPlayer,this.players=[...e.players],this.config={...dt,mode:"rollback",inputDelay:0,...e.config},this.attach=e.attach,this.onDesync=e.onDesync,this.onRollbackOverflow=e.onRollbackOverflow,this.ring=new Array(this.config.maxRollback+1).fill(null);for(let n of this.players)this.buffer.addPlayer(n);this.unsubscribe=this.transport.onMessage(n=>this.receive(n))}get frame(){return this.world.frame}get confirmedFrame(){let e=1/0;for(let n of this.players){let r=this.dropped.get(n),o=this.buffer.contiguousThrough(n);r!==void 0&&o>=r-1&&(o=1/0),e=Math.min(e,o)}return e===1/0?-1:e}lastKnownFrame(e){return this.buffer.contiguousThrough(e)}removePlayer(e,n){if(!(e===this.localPlayer||this.dropped.has(e))){this.dropped.set(e,n),this.buffer.clearFrom(e,n);for(let r=n;r<this.world.frame;r++){let o=this.usedInputs.get(r)?.get(e);o!==void 0&&o!=="[]"&&(this.earliestBad=Math.min(this.earliestBad,r))}this.settleHashes()}}get stats(){return{rollbacks:this.rollbackCount,resimulatedFrames:this.resimulatedFrames}}tick(e=[]){if(this.desynced||this.overflowed)return 0;let n=this.world.frame;return n-(this.confirmedFrame+1)>=this.config.maxRollback||(this.publishLocal(n,e),!this.resolveCorrections())?0:(this.storeSnapshot(n),this.stepFrame(n),this.settleHashes(),n%64===0&&this.pruneOld(n),1)}advance(e,n=[]){let r=0,o=this.world.clock.advance(e);for(let i=0;i<o&&this.tick(n)!==0;i++)r++;return r}inputLog(){let e=[],n=this.confirmedFrame;for(let r=0;r<=n;r++){let o=new Map;for(let i of this.players)o.set(i,this.buffer.get(i,r)??[]);e.push($t(this.players,o))}return{frames:e}}dispose(){this.unsubscribe()}deliver(e){this.receive(e)}publishLocal(e,n){if(!this.buffer.set(this.localPlayer,e,n))return;let r=Math.max(0,e-this.config.redundancy+1),o=[];for(let i=r;i<=e;i++)o.push(this.buffer.get(this.localPlayer,i)??[]);this.transport.send(de(he({t:"input",player:this.localPlayer,from:r,frames:o})))}inputsFor(e){let n=new Map;for(let r of this.players){let o=this.dropped.get(r);o!==void 0&&e>=o?n.set(r,[]):n.set(r,this.buffer.get(r,e)??this.buffer.latestAt(r,e))}return n}stepFrame(e){let n=this.inputsFor(e),r=new Map;for(let o of this.players)r.set(o,JSON.stringify(n.get(o)));this.usedInputs.set(e,r),this.world.step($t(this.players,n))}resolveCorrections(){if(this.earliestBad===1/0)return!0;let e=this.world.frame,n=this.earliestBad;this.earliestBad=1/0;let r=this.ring[n%this.ring.length];if(!r||r.frame!==n)return this.overflowed=!0,this.onRollbackOverflow?.(n),!1;this.rollbackCount++,this.world.restore(r.snap),this.attach?.(this.world);for(let o=n;o<e;o++)this.storeSnapshot(o),this.stepFrame(o),this.resimulatedFrames++;return!0}storeSnapshot(e){this.ring[e%this.ring.length]={frame:e,snap:this.world.snapshot()}}receive(e){let n=Oe(e);if(n)if(n.t==="input"&&n.player!==this.localPlayer){let r=this.dropped.get(n.player);for(let o=0;o<n.frames.length;o++){let i=n.from+o;if(!(r!==void 0&&i>=r)&&this.buffer.set(n.player,i,n.frames[o])&&i<this.world.frame){let s=this.usedInputs.get(i)?.get(n.player),a=JSON.stringify([...n.frames[o]].sort());s!==void 0&&s!==a&&(this.earliestBad=Math.min(this.earliestBad,i))}}this.settleHashes()}else n.t==="hash"&&n.player!==this.localPlayer&&(this.pendingRemoteHashes.push({player:n.player,frame:n.frame,hash:n.hash}),this.compareHashes())}settleHashes(){let e=Math.min(this.confirmedFrame+1,this.world.frame,this.earliestBad===1/0?1/0:this.earliestBad),n=this.config.hashInterval,r=(Math.floor(this.hashedThrough/n)+1)*n;for(;r<=e;r+=n){let o=this.ring[r%this.ring.length];if(!o||o.frame!==r)continue;let i=Bt(o.snap);this.localHashes.set(r,i),this.hashedThrough=r,this.transport.send(de(he({t:"hash",player:this.localPlayer,frame:r,hash:i})))}this.compareHashes()}compareHashes(){let e=[];for(let n of this.pendingRemoteHashes){let r=this.localHashes.get(n.frame);if(r===void 0){n.frame>this.hashedThrough-512&&e.push(n);continue}r!==n.hash&&!this.desynced&&(this.desynced=!0,this.onDesync?.({frame:n.frame,player:n.player,localHash:r,remoteHash:n.hash,log:this.inputLog(),startFrame:0}))}this.pendingRemoteHashes=e}pruneOld(e){this.buffer.prune(e-128);for(let n of this.usedInputs.keys())n<e-128&&this.usedInputs.delete(n);for(let n of this.localHashes.keys())n<e-512&&this.localHashes.delete(n)}};function th(){return globalThis.crypto.randomUUID()}function Pa(t,e,n,r,o,i,s,a,l){return t==="rollback"?new vn({world:e,transport:n,localPlayer:r,players:o,config:s,attach:a,onDesync:l.onDesync}):new Ie({world:e,transport:n,localPlayer:r,players:o,startFrame:i,config:s,onDesync:l.onDesync})}function Da(t,e,n,r,o){return{world:t,session:e,localPlayer:n,players:r,advance:(i,s=[])=>e.advance(i,s),dispose:()=>{e.dispose(),o?.()}}}var ur=class{localPlayer="p1";seed;config;transport;makeWorld;maxPlayers;joinMargin;attach;callbacks;players=["p1"];uidToPlayer=new Map;nextPlayerIndex=2;started=!1;game=null;pendingSnapshots=[];unsubscribe;constructor(e){this.transport=e.transport,this.makeWorld=e.makeWorld,this.seed=e.seed??1,this.config={...dt,...e.config},this.maxPlayers=e.maxPlayers??4,this.joinMargin=e.joinMargin??30,this.attach=e.attach,this.callbacks=e,this.unsubscribe=this.transport.onMessage(n=>this.receive(n))}get roster(){return[...this.players]}get isStarted(){return this.started}start(){if(this.game)return this.game;this.started=!0;let e=this.makeWorld(this.seed),n=Pa(this.config.mode,e,this.transport,this.localPlayer,this.players,0,this.config,this.attach,this.callbacks);return n instanceof Ie&&n.onAfterStep(r=>this.serviceSnapshots(r,e)),this.transport.send(de(he({t:"start",players:[...this.players]}))),this.game=Da(e,n,this.localPlayer,this.players,()=>this.unsubscribe()),this.game}dropPlayer(e){let n=this.game?.session;if(!n)return;let r=n instanceof Ie?Math.max(n.frame,n.confirmedFrame+1):n.lastKnownFrame(e)+1;this.transport.send(de(he({t:"leave",player:e,atFrame:r}))),n.removePlayer(e,r),this.players=this.players.filter(o=>o!==e),this.callbacks.onPlayerLeave?.(e,r)}dispose(){this.unsubscribe(),this.game?.dispose()}receive(e){let n=Oe(e);if(n){if(n.t==="hello")this.handleHello(n);else if(n.t==="bye"){let r=this.uidToPlayer.get(n.uid);r&&this.started?this.dropPlayer(r):r&&(this.players=this.players.filter(o=>o!==r),this.uidToPlayer.delete(n.uid))}}}handleHello(e){if(this.uidToPlayer.has(e.uid))return;if(this.players.length>=this.maxPlayers){this.transport.send(de(he({t:"deny",to:e.uid,reason:"room full"})));return}if(this.started&&this.config.mode==="rollback"){this.transport.send(de(he({t:"deny",to:e.uid,reason:"rollback rooms cannot be joined mid-game"})));return}let n=`p${this.nextPlayerIndex++}`;if(this.uidToPlayer.set(e.uid,n),this.players.push(n),!this.started){this.transport.send(de(he({t:"welcome",to:e.uid,player:n,players:[...this.players],seed:this.seed,config:this.config,startFrame:0}))),this.callbacks.onPlayerJoin?.(n,0);return}let r=this.game.session,o=r.frame+this.joinMargin;this.transport.send(de(he({t:"join",player:n,atFrame:o}))),r.addPlayer(n,o),this.pendingSnapshots.push({uid:e.uid,player:n,atFrame:o}),this.callbacks.onPlayerJoin?.(n,o)}serviceSnapshots(e,n){if(this.pendingSnapshots.length===0)return;let r=this.pendingSnapshots.filter(i=>i.atFrame===e);if(r.length===0)return;this.pendingSnapshots=this.pendingSnapshots.filter(i=>i.atFrame!==e);let o=n.snapshot();for(let i of r){let s=this.pendingSnapshots.filter(l=>l.player!==i.player),a=new Set(s.map(l=>l.player));this.transport.send(de(he({t:"welcome",to:i.uid,player:i.player,players:this.players.filter(l=>!a.has(l)),seed:this.seed,config:this.config,startFrame:e,snapshot:o,joins:s.map(l=>({player:l.player,atFrame:l.atFrame}))})))}}};function li(t){let e=th(),n=t.transport;return new Promise((r,o)=>{let i=null,s=!1,a=null,l=[],u=[],c=()=>{if(!i||!s)return;m();let d=a??i.players,h=t.makeWorld(i.seed);i.snapshot&&(h.restore(i.snapshot),t.attach?.(h));let p=Pa(i.config.mode,h,n,i.player,d,i.startFrame,i.config,t.attach,t);if(i.joins&&p instanceof Ie)for(let k of i.joins)p.addPlayer(k.player,k.atFrame);for(let k of u)k.t==="join"&&p instanceof Ie&&p.addPlayer(k.player,k.atFrame),k.t==="leave"&&p.removePlayer(k.player,k.atFrame);let f=n.onMessage(k=>{let v=Oe(k);v&&(v.t==="join"&&p instanceof Ie?(p.addPlayer(v.player,v.atFrame),t.onPlayerJoin?.(v.player,v.atFrame)):v.t==="leave"&&(p.removePlayer(v.player,v.atFrame),t.onPlayerLeave?.(v.player,v.atFrame)))}),g=Da(h,p,i.player,d,()=>{f(),n.send(de(he({t:"bye",uid:e})))});for(let k of l)p.deliver(k);r(g)},m=n.onMessage(d=>{let h=Oe(d);if(h)switch(h.t){case"welcome":h.to===e&&(i=h,(h.snapshot||h.startFrame>0)&&(s=!0),c());break;case"deny":h.to===e&&(m(),o(new Error(`hayao-net: join denied \u2014 ${h.reason}`)));break;case"start":s=!0,a=h.players,c();break;case"join":case"leave":u.push(h);break;case"input":case"hash":l.push(d);break}});n.send(de(he({t:"hello",uid:e,name:t.name})))})}function ui(t){return new ur(t)}function nh(t,e,n){let r=t.width??1280,o=t.height??720,i=t.background??"#f3ecdb",s=n.renderer==="canvas"?new lt({width:r,height:o,background:i}):new at({width:r,height:o,background:i});e.style.position=e.style.position||"relative",s.mount?.(e),un(e);let a=new et(t.inputMap??{},document),l=f=>Te(t,f),u=null,c=null,m=0,d=!1,h=f=>g=>{!d&&u&&(u.advance(g-f,a.currentActions())>0&&a.clearPressed(),s.draw(u.world.render())),m=requestAnimationFrame(h(g))},p=f=>{u=f,n.onStatus?.(`playing as ${f.localPlayer} (${f.players.length} players)`),m=requestAnimationFrame(h(performance.now()))};return n.role==="host"?(c=ui({transport:n.transport,makeWorld:l,seed:n.seed??t.seed??1,config:n.config,maxPlayers:n.maxPlayers,attach:n.attach,onDesync:n.onDesync,onPlayerJoin:(f,g)=>{n.onStatus?.(`${f} joined`),n.onPlayerJoin?.(f,g)},onPlayerLeave:n.onPlayerLeave}),n.onStatus?.("hosting \u2014 waiting for players")):(n.onStatus?.("joining\u2026"),li({transport:n.transport,makeWorld:l,attach:n.attach,onDesync:n.onDesync,onPlayerJoin:n.onPlayerJoin,onPlayerLeave:n.onPlayerLeave}).then(p).catch(f=>n.onStatus?.(f.message))),{start(){c&&!u&&p(c.start())},get game(){return u},get localPlayer(){return u?.localPlayer??(n.role==="host"?"p1":null)},get roster(){return c?.roster??u?.players??[]},input:a,stop(){d=!0,cancelAnimationFrame(m),u?.dispose(),c?.dispose(),a.dispose(),s.dispose?.()}}}var rh=0;function oh(t,e){return`${t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"game"}-${e.replace(/[:.]/g,"-").toLowerCase()}-${(rh++).toString(36)}`}var pt=class{frames=[];axesLog=[];lastAxes=new Map;knobEvents=[];screenEvents=[];wallClockMarks=[];annotations=[];init;startedAt;id;buildRef;constructor(e){this.init=e,this.startedAt=e.startedAt??new Date().toISOString(),this.id=e.id??oh(e.game,this.startedAt),this.buildRef=e.buildRef??"unknown"}get frame(){return this.frames.length}get liveInputFrames(){return this.frames}get liveAxesLog(){return this.axesLog}get liveKnobEvents(){return this.knobEvents}step(e,n){if(n)for(let[r,o]of n)this.lastAxes.get(r)!==o&&(this.axesLog.push([this.frames.length,r,o]),this.lastAxes.set(r,o));this.frames.push([...e].sort())}knob(e,n){this.knobEvents.push({frame:this.frames.length,key:e,value:n}),this.screen("knob",`${e}=${n}`)}screen(e,n){this.screenEvents.push({frame:this.frames.length,kind:e,...n!==void 0?{detail:n}:{}})}mark(e,n){this.wallClockMarks.push({frame:this.frames.length,t:n,kind:e})}annotate(e,n){this.annotations.push({frame:this.frames.length,tag:e,...n!==void 0?{note:n}:{}})}truncate(e){if(!(e>=this.frames.length)){this.frames.length=e,this.axesLog=this.axesLog.filter(([n])=>n<e),this.lastAxes.clear();for(let[n,r,o]of this.axesLog)n<e&&this.lastAxes.set(r,o);this.knobEvents=this.knobEvents.filter(n=>n.frame<=e),this.screenEvents=this.screenEvents.filter(n=>n.frame<=e),this.wallClockMarks=this.wallClockMarks.filter(n=>n.frame<=e),this.annotations=this.annotations.filter(n=>n.frame<=e)}}toSession(e){return{id:this.id,game:this.init.game,startedAt:this.startedAt,buildRef:this.buildRef,seed:this.init.seed,variant:this.init.variant??{name:"dev",kind:"dev"},tuningValues:{...this.init.tuningValues},...this.init.startSnapshot?{startSnapshot:this.init.startSnapshot}:{},knobEvents:this.knobEvents.slice(),inputLog:{frames:this.frames.map(n=>n.slice())},axesLog:this.axesLog.slice(),screenEvents:this.screenEvents.slice(),wallClockMarks:this.wallClockMarks.slice(),annotations:this.annotations.slice(),endReason:e}}};var Nt=class{constructor(e=30,n=240){this.stride=e;this.cap=n}stride;cap;entries=[];push(e,n){e%this.stride===0&&(this.entries.push({frame:e,snap:n.snapshot()}),this.entries.length>this.cap&&this.entries.shift())}nearest(e){let n=null;for(let r of this.entries)r.frame<=e&&(!n||r.frame>n.frame)&&(n=r);return n}get minFrame(){return this.entries.length>0?this.entries[0].frame:0}truncate(e){this.entries=this.entries.filter(n=>n.frame<=e)}clear(){this.entries=[]}};function cr(t,e,n,r,o,i,s){let a=Math.max(n.minFrame,Math.min(s,r.length)),l=n.nearest(a);if(!l)return null;t.restore(structuredClone(l.snap)),e.attach?.(t),t.input.axes.clear();let u=new Map,c=0;for(;c<o.length&&o[c][0]<l.frame;){let[,d,h]=o[c++];u.set(d,h)}for(let[d,h]of u)t.input.axes.set(d,h);let m=i.findIndex(d=>d.frame>=l.frame);m<0&&(m=i.length);for(let d=l.frame;d<a;d++){for(;m<i.length&&i[m].frame===d;){let h=i[m++],p=t.snapshot();p.tuning={...p.tuning,[h.key]:h.value},t.restore(p),e.attach?.(t)}for(;c<o.length&&o[c][0]===d;){let[,h,p]=o[c++];t.input.axes.set(h,p)}t.step(r[d])}return a}function ih(){if(typeof location>"u")return{};let t=new URLSearchParams(location.search),e={},n=t.get("seed");n!==null&&Number.isFinite(Number(n))&&(e.seed=Number(n));let r=t.get("tuning");if(r)try{let o=JSON.parse(atob(r));o&&typeof o=="object"&&(e.tuning=o)}catch{}return e}function sh(t,e,n={}){let r=ih(),o=typeof location<"u"?new URLSearchParams(location.search).get("variant"):null,i=o?n.variants?.[o]:void 0,s=i?.patch?i.patch(t):t,a=n.variant??(i&&o?{name:o,kind:"module"}:{name:"dev",kind:"dev"}),l=n.world?.seed??r.seed??s.seed??1,u={...i?.tuning,...r.tuning,...n.world?.tuning},c=fn(s.tuning,u),m={...c},d=typeof performance<"u"?performance.now():0,h=new pt({game:s.title,seed:l,tuningValues:c,variant:a}),p=!1,f=(D,A)=>{let O=JSON.stringify(D);if(A&&typeof navigator<"u"&&navigator.sendBeacon){navigator.sendBeacon("/__studio/session",new Blob([O],{type:"application/json"}));return}fetch("/__studio/session",{method:"POST",headers:{"content-type":"application/json"},body:O}).catch(()=>{})},g=(D="quit",A=!1)=>{v||h.frame===0&&p||(f(h.toSession(D),A),p=!0)},k=typeof location<"u"?new URLSearchParams(location.search).get("session"):null,v=null,M=null,I=new Nt,x=!1,b=null,w=()=>{if(b===null||b>=h.frame){b=null;return}h.truncate(b),I.truncate(b),h.screen("scrub",`forked@${b}`),b=null},C=bn(s,e,{...n,world:{seed:l,tuning:u},isHeld:()=>x||(n.isHeld?.()??!1),onAdvance:(D,A,O)=>{for(let z=0;z<A;z++)h.step(O,D.input.axes),I.push(h.frame,D);n.onAdvance?.(D,A,O)},onPause:D=>{h.screen(D?"pause":"resume"),n.onPause?.(D)},onRestart:()=>{g("restart"),h=new pt({game:s.title,seed:l,tuningValues:{...m},variant:a,buildRef:h.buildRef}),(n.onRestart??C.restart)()}}),E=n.hot?.data.hayaoSnap;if(E){delete n.hot.data.hayaoSnap;let D=structuredClone(E);D.tuning={...m},C.world.restore(D),s.attach?.(C.world),h=new pt({game:s.title,seed:l,tuningValues:{...m},variant:a,startSnapshot:D}),h.screen("hot-swap")}n.hot?.dispose(D=>{D.hayaoSnap=C.world.snapshot(),ee("hot-swap")}),I.push(0,C.world);async function R(D,A){let O=await fetch(`/__studio/session/${encodeURIComponent(D)}`);if(!O.ok)return;let z=await O.json();x=!0;let X=C.world,se=Te(s,{seed:z.seed,tuning:z.tuningValues});X.restore(z.startSnapshot?structuredClone(z.startSnapshot):se.snapshot()),s.attach?.(X),X.input.axes.clear();let ae=z.inputLog.frames,re=Math.max(30,Math.ceil(ae.length/220/30)*30);I=new Nt(re),I.push(0,X);let le=0,me=0;for(let xe=0;xe<ae.length;xe++){for(;me<z.knobEvents.length&&z.knobEvents[me].frame===xe;){let Ue=z.knobEvents[me++],Me=X.snapshot();Me.tuning={...Me.tuning,[Ue.key]:Ue.value},X.restore(Me),s.attach?.(X)}for(;le<z.axesLog.length&&z.axesLog[le][0]===xe;){let[,Ue,Me]=z.axesLog[le++];X.input.axes.set(Ue,Me)}X.step(ae[xe]),I.push(xe+1,X)}v={session:z,pos:ae.length},ie.scrub(Number.isFinite(A)?A:0)}function S(){if(!v||M!==null)return;let D=v.session,A=performance.now();M=window.setInterval(()=>{if(!v)return;let O=performance.now(),z=Math.min(120,Math.floor((O-A)/(1e3/60)));if(z<=0)return;A=O;let X=C.world;for(let se=0;se<z;se++){let ae=v.pos;if(ae>=D.inputLog.frames.length){T();return}for(let re of D.knobEvents)if(re.frame===ae){let le=X.snapshot();le.tuning={...le.tuning,[re.key]:re.value},X.restore(le),s.attach?.(X)}for(let[re,le,me]of D.axesLog)re===ae&&X.input.axes.set(le,me);X.step(D.inputLog.frames[ae]),v.pos=ae+1}},1e3/60)}function T(){M!==null&&(window.clearInterval(M),M=null)}k&&R(k,Number(new URLSearchParams(location.search).get("at")??"NaN")),fetch("/__studio/state").then(D=>D.ok?D.json():null).then(D=>{D?.buildRef&&(h.buildRef=D.buildRef)}).catch(()=>{}),Zn((D,A)=>h.screen(D==="show"?"overlay-show":"overlay-hide",A));let L=()=>typeof performance<"u"?performance.now()-d:0,H=()=>h.mark(document.hidden?"visibility-hidden":"visibility-visible",L()),$=()=>h.mark("blur",L()),Y=()=>h.mark("focus",L()),K=()=>g("quit",!0);document.addEventListener("visibilitychange",H),window.addEventListener("blur",$),window.addEventListener("focus",Y),window.addEventListener("pagehide",K);let te=window.setInterval(()=>g("idle"),1e4),ee=D=>{T(),g(D,D==="hot-swap"),document.removeEventListener("visibilitychange",H),window.removeEventListener("blur",$),window.removeEventListener("focus",Y),window.removeEventListener("pagehide",K),window.clearInterval(te),Zn(null),C.stop()},ie={...C,get world(){return C.world},setKnob(D,A){if(v)return;w(),m[D]=A;let O=C.world.snapshot();O.tuning={...m},C.world.restore(O),s.attach?.(C.world),h.knob(D,A)},knobValues:()=>({...m}),tuningSpec:()=>s.tuning,variants:()=>Object.fromEntries(Object.entries(n.variants??{}).map(([D,A])=>[D,A.label])),activeVariant:()=>({...a}),title:()=>s.title,annotate:(D,A)=>{v||h.annotate(D,A)},setFrozen(D){if(v){D?T():S();return}if(D===x)return;if(D){x=!0;return}let A=b!==null;if(w(),A){let O=C.world.snapshot().tuning??{};for(let z of Object.keys(m))z in O&&(m[z]=O[z])}x=!1},frozen:()=>v?M===null:x,scrub(D){if(v){T();let O=v.session,z=cr(C.world,s,I,O.inputLog.frames,O.axesLog,O.knobEvents,D);return z!==null&&(v.pos=z),z}x=!0;let A=cr(C.world,s,I,h.liveInputFrames,h.liveAxesLog,h.liveKnobEvents,D);return A!==null&&(b=A<h.frame?A:null),A},timeline:()=>v?{min:I.minFrame,frame:v.pos,max:v.session.inputLog.frames.length}:{min:I.minFrame,frame:b??h.frame,max:h.frame},mode:()=>v?"replay":"live",flush:(D="idle")=>g(D),session:()=>h.toSession("idle"),stop:()=>ee("navigate")};return window.__studio=ie,ie}var ah="0.4.1";return Aa(lh);})();
|