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.
Files changed (131) hide show
  1. package/design/00-process/README.md +49 -0
  2. package/design/00-process/composition.md +148 -0
  3. package/design/00-process/core-loop.md +146 -0
  4. package/design/00-process/intent-to-brief.md +128 -0
  5. package/design/00-process/pillars.md +139 -0
  6. package/design/00-process/refine-and-handoff.md +156 -0
  7. package/design/00-process/the-twist.md +108 -0
  8. package/design/10-anchors/README.md +99 -0
  9. package/design/10-anchors/age-of-empires.md +103 -0
  10. package/design/10-anchors/baba-is-you.md +127 -0
  11. package/design/10-anchors/balatro.md +132 -0
  12. package/design/10-anchors/celeste.md +136 -0
  13. package/design/10-anchors/civilization.md +101 -0
  14. package/design/10-anchors/dead-cells.md +125 -0
  15. package/design/10-anchors/factorio.md +100 -0
  16. package/design/10-anchors/hades.md +127 -0
  17. package/design/10-anchors/into-the-breach.md +125 -0
  18. package/design/10-anchors/it-takes-two.md +104 -0
  19. package/design/10-anchors/loop-hero.md +131 -0
  20. package/design/10-anchors/nuclear-throne.md +130 -0
  21. package/design/10-anchors/outer-wilds.md +107 -0
  22. package/design/10-anchors/overcooked.md +102 -0
  23. package/design/10-anchors/peggle.md +133 -0
  24. package/design/10-anchors/reigns.md +99 -0
  25. package/design/10-anchors/return-of-the-obra-dinn.md +108 -0
  26. package/design/10-anchors/rimworld.md +101 -0
  27. package/design/10-anchors/shadow-of-mordor.md +106 -0
  28. package/design/10-anchors/slay-the-spire.md +127 -0
  29. package/design/10-anchors/starcraft.md +98 -0
  30. package/design/10-anchors/stardew-valley.md +103 -0
  31. package/design/10-anchors/tetris.md +122 -0
  32. package/design/10-anchors/vampire-survivors.md +122 -0
  33. package/design/20-genres/README.md +62 -0
  34. package/design/20-genres/action-adventure.md +126 -0
  35. package/design/20-genres/auto-battler.md +121 -0
  36. package/design/20-genres/bullet-hell.md +123 -0
  37. package/design/20-genres/city-builder.md +124 -0
  38. package/design/20-genres/coop-chaos.md +124 -0
  39. package/design/20-genres/deckbuilder.md +122 -0
  40. package/design/20-genres/exploration.md +131 -0
  41. package/design/20-genres/farming-sim.md +122 -0
  42. package/design/20-genres/grid-puzzle.md +126 -0
  43. package/design/20-genres/horde-survival.md +128 -0
  44. package/design/20-genres/incremental.md +120 -0
  45. package/design/20-genres/match3.md +120 -0
  46. package/design/20-genres/metroidvania.md +132 -0
  47. package/design/20-genres/narrative-decisions.md +122 -0
  48. package/design/20-genres/physics-arcade.md +124 -0
  49. package/design/20-genres/precision-platformer.md +127 -0
  50. package/design/20-genres/racing.md +126 -0
  51. package/design/20-genres/rhythm.md +125 -0
  52. package/design/20-genres/roguelike.md +122 -0
  53. package/design/20-genres/rts.md +169 -0
  54. package/design/20-genres/stealth.md +125 -0
  55. package/design/20-genres/survival-horror.md +124 -0
  56. package/design/20-genres/tactics.md +123 -0
  57. package/design/20-genres/tower-defense.md +120 -0
  58. package/design/30-systems/README.md +69 -0
  59. package/design/30-systems/accessibility.md +110 -0
  60. package/design/30-systems/boss-design.md +126 -0
  61. package/design/30-systems/build-diversity.md +120 -0
  62. package/design/30-systems/collectibles.md +108 -0
  63. package/design/30-systems/combat-model.md +113 -0
  64. package/design/30-systems/coop-and-competition.md +118 -0
  65. package/design/30-systems/counter-systems.md +115 -0
  66. package/design/30-systems/crafting.md +115 -0
  67. package/design/30-systems/difficulty-and-dda.md +114 -0
  68. package/design/30-systems/economy.md +117 -0
  69. package/design/30-systems/emergent-systems.md +114 -0
  70. package/design/30-systems/encounter-design.md +107 -0
  71. package/design/30-systems/enemy-ai.md +121 -0
  72. package/design/30-systems/enemy-archetypes.md +117 -0
  73. package/design/30-systems/faction-asymmetry.md +144 -0
  74. package/design/30-systems/grace.md +124 -0
  75. package/design/30-systems/mastery-curve.md +116 -0
  76. package/design/30-systems/meta-progression.md +114 -0
  77. package/design/30-systems/onboarding.md +115 -0
  78. package/design/30-systems/procgen-design.md +118 -0
  79. package/design/30-systems/progression.md +120 -0
  80. package/design/30-systems/resource-loops.md +112 -0
  81. package/design/30-systems/reward-schedules.md +124 -0
  82. package/design/30-systems/save-and-checkpoint.md +113 -0
  83. package/design/30-systems/session-structure.md +113 -0
  84. package/design/30-systems/skill-trees.md +111 -0
  85. package/design/30-systems/status-effects.md +111 -0
  86. package/design/30-systems/tech-tree.md +112 -0
  87. package/design/30-systems/telegraphs.md +106 -0
  88. package/design/30-systems/unit-rosters.md +123 -0
  89. package/design/40-worldbuilding/README.md +49 -0
  90. package/design/40-worldbuilding/aesthetic-direction.md +155 -0
  91. package/design/40-worldbuilding/faction-identity.md +136 -0
  92. package/design/40-worldbuilding/naming-and-tone.md +130 -0
  93. package/design/40-worldbuilding/narrative-delivery.md +129 -0
  94. package/design/40-worldbuilding/theme-vectors.md +134 -0
  95. package/design/40-worldbuilding/worldbuilding-scaffold.md +132 -0
  96. package/design/50-patterns/README.md +54 -0
  97. package/design/50-patterns/anti-frustration.md +121 -0
  98. package/design/50-patterns/emergence.md +121 -0
  99. package/design/50-patterns/feedback-loops.md +121 -0
  100. package/design/50-patterns/juice-choreography.md +124 -0
  101. package/design/50-patterns/mastery-and-flow.md +121 -0
  102. package/design/50-patterns/pacing-and-tension.md +120 -0
  103. package/design/50-patterns/readability.md +121 -0
  104. package/design/50-patterns/risk-reward.md +120 -0
  105. package/design/CONTRIBUTING.md +183 -0
  106. package/design/INDEX.md +133 -0
  107. package/design/README.md +86 -0
  108. package/design/_TEMPLATE.md +69 -0
  109. package/design/index.json +2720 -0
  110. package/dist/anim/blend.d.ts +68 -0
  111. package/dist/anim/clip.d.ts +87 -0
  112. package/dist/anim/ik.d.ts +40 -0
  113. package/dist/anim/skeleton.d.ts +64 -0
  114. package/dist/hayao.global.js +12 -12
  115. package/dist/index.d.ts +11 -1
  116. package/dist/index.js +1683 -516
  117. package/dist/index.js.map +4 -4
  118. package/dist/index.min.js +12 -12
  119. package/dist/render/canvas2d-core.d.ts +4 -0
  120. package/dist/render/commands.d.ts +19 -0
  121. package/dist/render/lightRun.d.ts +35 -0
  122. package/dist/render/svgString.d.ts +8 -3
  123. package/dist/scene/clipPlayer.d.ts +58 -0
  124. package/dist/scene/ikTarget.d.ts +25 -0
  125. package/dist/scene/light.d.ts +80 -0
  126. package/dist/scene/shadow2d.d.ts +25 -0
  127. package/dist/scene/skeletonDebug.d.ts +28 -0
  128. package/dist/verify/gates.d.ts +25 -0
  129. package/docs/API.md +66 -8
  130. package/docs/CONVENTIONS.md +56 -0
  131. package/package.json +2 -1
package/dist/index.min.js CHANGED
@@ -1,4 +1,4 @@
1
- var Fi=.6366197723675814,Ai=1.5707963267341256,Ni=6077100506506192e-26,Li=-.16666666666666632,$i=.00833333333332249,Wi=-.0001984126982985795,zi=27557313707070068e-22,Bi=-25050760253406863e-24,_i=158969099521155e-24,Gi=.0416666666666666,Oi=-.001388888888887411,Vi=2480158728947673e-20,Hi=-27557314351390663e-23,qi=2087572321298175e-24,ji=-11359647557788195e-27;function Dt(t){let e=t*t;return t+t*e*(Li+e*($i+e*(Wi+e*(zi+e*(Bi+e*_i)))))}function It(t){let e=t*t;return 1-.5*e+e*e*(Gi+e*(Oi+e*(Vi+e*(Hi+e*(qi+e*ji)))))}function or(t){let e=Math.round(t*Fi),n=t-e*Ai-e*Ni;return{n:(e%4+4)%4,r:n}}function H(t){if(!Number.isFinite(t))return NaN;let{n:e,r:n}=or(t);switch(e){case 0:return Dt(n);case 1:return It(n);case 2:return-Dt(n);default:return-It(n)}}function J(t){if(!Number.isFinite(t))return NaN;let{n:e,r:n}=or(t);switch(e){case 0:return It(n);case 1:return-Dt(n);case 2:return-It(n);default:return Dt(n)}}var Et=[.4636476090008061,.7853981633974483,.982793723247329,1.5707963267948966],rr=[22698777452961687e-33,3061616997868383e-32,13903311031230998e-33,6123233995736766e-32],ye=[.3333333333333293,-.19999999999876483,.14285714272503466,-.11111110405462356,.09090887133436507,-.0769187620504483,.06661073137387531,-.058335701337905735,.049768779946159324,-.036531572744216916,.016285820115365782];function Ui(t){if(Number.isNaN(t))return NaN;if(!Number.isFinite(t))return t>0?Et[3]:-Et[3];let e=t<0||Object.is(t,-0)?-1:1,n=Math.abs(t);if(n>=1e19)return e*(Et[3]+rr[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*(ye[0]+i*(ye[2]+i*(ye[4]+i*(ye[6]+i*(ye[8]+i*ye[10]))))),a=i*(ye[1]+i*(ye[3]+i*(ye[5]+i*(ye[7]+i*ye[9]))));if(r<0)return e*(n-n*(s+a));let u=Et[r]-(n*(s+a)-rr[r]-n);return e*u}var Se=3.141592653589793;function Ft(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)?-Se:Se:Object.is(t,-0)?-0:0;if(e===0||!Number.isFinite(t)&&Number.isFinite(e))return t>0?Se/2:-Se/2;if(!Number.isFinite(e)){if(!Number.isFinite(t)){let r=e>0?Se/4:3*Se/4;return t>0?r:-r}return e>0?t<0||Object.is(t,-0)?-0:0:t<0||Object.is(t,-0)?-Se:Se}let n=Ui(t/e);return e>0?n:t<0||Object.is(t,-0)?n-Se:n+Se}var Xi=.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)*Xi,r=1,o=1;for(let i=1;i<=13;i++)r=r*n/i,o+=r;return o*2**e}function _e(t){return pe(t*sr)}function K(t,e){return Math.sqrt(t*t+e*e)}var $e=new DataView(new ArrayBuffer(8)),Ji=.6931471803691238,Yi=19082149292705877e-26;function ir(t){if(Number.isNaN(t)||t<0)return NaN;if(t===0)return-1/0;if(!Number.isFinite(t))return 1/0;$e.setFloat64(0,t);let e=($e.getUint32(0)>>>20&2047)-1023;e===-1023&&($e.setFloat64(0,t*0x40000000000000),e=($e.getUint32(0)>>>20&2047)-1023-54),$e.setUint32(0,$e.getUint32(0)&1048575|1023<<20);let n=$e.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*Ji+(2*r*i+e*Yi)}var Ki=.4342944819032518,sr=1.4426950408889634,At=t=>ir(t)*Ki,ot=t=>ir(t)*sr;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?pe(e*ot(t)):t===0?e>0?0:1/0:NaN}var il=(t=0,e=0)=>({x:t,y:e}),sl=(t,e)=>({x:t.x+e.x,y:t.y+e.y}),al=(t,e)=>({x:t.x-e.x,y:t.y-e.y}),ul=(t,e)=>({x:t.x*e,y:t.y*e}),ll=(t,e)=>t.x*e.x+t.y*e.y,Qi=t=>K(t.x,t.y),cl=(t,e)=>K(t.x-e.x,t.y-e.y);function ml(t){let e=Qi(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,Ie=(t,e,n)=>t+(e-t)*n,ar=(t,e,n)=>t===e?0:(n-t)/(e-t),dl=(t,e,n,r,o)=>Ie(r,o,ar(e,n,t)),ur=(t,e,n)=>{let r=ee(t===e?n<t?0:1:ar(t,e,n),0,1);return r*r*(3-2*r)},Z=Math.PI*2,hl=t=>t*Math.PI/180,pl=t=>t*180/Math.PI;function fl(t,e){return e.x>=t.x&&e.x<=t.x+t.w&&e.y>=t.y&&e.y<=t.y+t.h}function bl(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 Ge(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 it(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 xn(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 st(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 yl(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 Zi(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 ce=class t{s0;s1;s2;s3;constructor(e=0){if(typeof e=="number"){let n=Zi(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}},wn=new DataView(new ArrayBuffer(8));function xl(...t){let e=2654435769;for(let n of t)wn.setFloat64(0,n),e=Math.imul(e^wn.getUint32(0),2246822507)>>>0,e=(e^e>>>13)>>>0,e=Math.imul(e^wn.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 lr(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 Nt=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 at=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}},Lt=class{signals=new Map;signalFor(e){let n=this.signals.get(e);return n||(n=new at,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 es(t){return Number.isNaN(t)?"NaN":t===1/0?"Inf":t===-1/0?"-Inf":t===0?"0":t.toString()}function $t(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("#"+es(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 cr=0;function mr(t=0){cr=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${cr++}`,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 at,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=it(this.pos,this.rotation,this.scale);return this.pivot?Ge(e,it({x:-this.pivot.x,y:-this.pivot.y},0,{x:1,y:1})):e}worldTransform(){let e=this.localTransform();return this.parent?Ge(this.parent.worldTransform(),e):e}collectDraw(e,n=ue){if(!this.visible)return;let r=Ge(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 kn(t,e){return[0,-e/2,t/2,0,0,e/2,-t/2,0]}function ts(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,H(i)*e)}return r}var Wt=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:kn(this.shape.w,this.shape.h),closed:!0,...o});break;case"regularPoly":e.push({kind:"poly",points:ts(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)}},zt=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)}},Bt=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)}},_t=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 dr(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 hr=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:dr(this.fill,.65)},l=this.rightPaint??{fill:dr(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=kn(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)}},pr=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 fr=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=Ie(e.pos.x,n.x,r),e.pos.y=Ie(e.pos.y,n.y,r)}};var br=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 gr=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 Hl=(t,e,n,r)=>Ie(e,t,_e(-n*r)),ns=(t=0)=>({value:t,vel:0});function rs(t,e,n,r){let o=_e(-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 ql(t=0,e=.25){let n=4/Math.max(1e-4,e),r=ns(t);return(o,i)=>rs(r,o,n,i).value}var yr=t=>t*t,Sn=t=>t*t*t,vr={linear:t=>t,quadIn:t=>t*t,quadOut:t=>1-(1-t)*(1-t),quadInOut:t=>t<.5?2*t*t:1-yr(-2*t+2)/2,cubicIn:t=>t*t*t,cubicOut:t=>1-Sn(1-t),cubicInOut:t=>t<.5?4*t*t*t:1-Sn(-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*Sn(t-1)+1.70158*yr(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},Gt=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:vr[i]??vr.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 xr=class extends V{type="Particles";pool=[];rng;maxParticles;constructor(e={}){super(e),this.cosmetic=!0,this.rng=new ce(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),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=os.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}},os={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 is(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)*ur(r.time,o.time,t)}return e[e.length-1].intensity}var wr=class extends V{type="AmbientField";rng;field=[];time=0;style;width;height;envelope;constructor(e){super(e),this.cosmetic=!0,this.rng=new ce(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?is(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*Z+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}},Kl={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})},kr=class extends V{type="Shaker";rng;trauma=0;amplitude;decay;constructor(e={}){super(e),this.cosmetic=!0,this.rng=new ce(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 Sr=class extends V{type="FloatingText";pool=[];rng;maxPopups;constructor(e={}){super(e),this.cosmetic=!0,this.rng=new ce(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}},nc={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 Mr=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 Ft(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=st(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 Tr=new Map;function Oe(t,e){Tr.set(t,e)}Oe("Node",()=>new V);Oe("Sprite",()=>new Wt({shape:{kind:"rect",w:1,h:1}}));Oe("Text",()=>new zt({text:""}));Oe("Camera2D",()=>new Bt);Oe("Timer",()=>new _t({duration:1}));Oe("AnimationPlayer",()=>new Gt);function Mn(t){let e=Tr.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(Mn(r));return n}var Ot=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 Ve(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 Rr(t,e){let n=Math.PI*2/e;return Math.round(t/n)*n}function Pr(t,e){let n=[];for(let r in t)t[r].some(o=>e.has(o))&&n.push(r);return n.sort()}var Cr=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 ut(t,e){return t.frames[e]??[]}function lt(t,e){return t.axes?.[e]}var Tn={up:["ArrowUp","KeyW"],down:["ArrowDown","KeyS"],left:["ArrowLeft","KeyA"],right:["ArrowRight","KeyD"],confirm:["Enter","Space"],cancel:["Escape","Backspace"],action:["KeyZ","KeyJ"],action2:["KeyX","KeyK"],undo:["KeyU"],restart:["KeyR"]};var He=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=Pr(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)}},Er=["mouse.left","mouse.right","mouse.middle"],Vt=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(Er),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 Er)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 Dr=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??ss,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=>Ve(d,this.stickBuckets,-1,1),a=d=>Ve(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()}},ss={0:"confirm",1:"cancel",2:"action2",3:"action",9:"confirm",12:"up",13:"down",14:"left",15:"right"};var Y={EMPTY:0,SOLID:1,ONEWAY:2,HAZARD:3},Ir={"#":Y.SOLID,"-":Y.ONEWAY,"^":Y.HAZARD};function Fr(t,e=32,n=Ir){let r=t.length,o=Math.max(...t.map(s=>s.length)),i=new Array(o*r).fill(Y.EMPTY);return t.forEach((s,a)=>{for(let u=0;u<s.length;u++)i[a*o+u]=n[s[u]]??Y.EMPTY}),{cols:o,rows:r,tileSize:e,tiles:i}}function yc(t,e=32,n=Ir){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?Y.SOLID:t.tiles[n*t.cols+e]}function vc(t,e,n){return fe(t,Math.floor(e/t.tileSize),Math.floor(n/t.tileSize))}var xc=t=>t.cols*t.tileSize,wc=t=>t.rows*t.tileSize;var j=1e-6,We=(t,e,n)=>[Math.floor(t/n),Math.floor((e-j)/n)];function ze(t,e,n,r,o,i=[]){let s=t.tileSize,[a,u]=We(e,e+r,s),[l,c]=We(n,n+o,s);for(let m=l;m<=c;m++)for(let d=a;d<=u;d++)if(fe(t,d,m)===Y.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 Ht(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]=We(u,u+c,i);if(n>0){let w=a+n,[S,D]=[Math.floor((a+l)/i),Math.floor((a+l+n-j)/i)];for(let R=S;R<=D;R++)for(let k=y;k<=f;k++)fe(t,R,k)===Y.SOLID&&(w=Math.min(w,R*i-l));for(let R of s)!R.oneway&&R.y<u+c-j&&R.y+R.h>u+j&&R.x>=a+l-j&&(w=Math.min(w,R.x-l));w<a+n-j&&(m=!0,p=!0),a=Math.min(a+n,w)}else{let w=a+n,[S,D]=[Math.floor((a-j)/i),Math.floor((a+n)/i)];for(let R=S;R>=D;R--)for(let k=y;k<=f;k++)fe(t,R,k)===Y.SOLID&&(w=Math.max(w,(R+1)*i));for(let R of s)!R.oneway&&R.y<u+c-j&&R.y+R.h>u+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 b=u+c,v=!1,M=!1,x=-1;if(r!==0){let[y,f]=We(a,a+l,i);if(r>0){let w=u+r,[S,D]=[Math.floor(b/i),Math.floor((b+r-j)/i)];for(let R=S;R<=D;R++)for(let k=y;k<=f;k++){let T=fe(t,k,R);(T===Y.SOLID||T===Y.ONEWAY&&!o.dropThrough&&b<=R*i+j)&&(w=Math.min(w,R*i-c))}for(let R=0;R<s.length;R++){let k=s[R];!(k.x<a+l-j&&k.x+k.w>a+j)||k.y<b-j||k.oneway&&(o.dropThrough||b>k.y+j)||k.y-c<w&&(w=k.y-c,x=R)}w<u+r-j?(d=!0,v=!0):x=-1,u=Math.min(u+r,w)}else{let w=u+r,[S,D]=[Math.floor((u-j)/i),Math.floor((u+r)/i)];for(let R=S;R>=D;R--)for(let k=y;k<=f;k++)fe(t,k,R)===Y.SOLID&&(w=Math.max(w,(R+1)*i));for(let R of s)!R.oneway&&R.x<a+l-j&&R.x+R.w>a+j&&R.y+R.h<=u+j&&(w=Math.max(w,R.y+R.h));w>u+r+j&&(d=!0,M=!0),u=Math.max(u+r,w)}}if(!v){let y=as(t,a,u,l,c,s,o.dropThrough??!1);v=y.grounded,x=y.solid}let C=3,I=!1;{let[y,f]=We(a+C,a+l-C,i),[w,S]=We(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)===Y.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 as(t,e,n,r,o,i=[],s=!1){let a=t.tileSize,u=n+o,[l,c]=We(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===Y.SOLID)return{grounded:!0,solid:-1};if(h===Y.ONEWAY&&!s&&Math.abs(u-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&&u<=h.y+1+j&&u>=h.y-1-j)return{grounded:!0,solid:d}}return{grounded:!1,solid:-1}}var ct={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},Rc={moveX:0,moveY:0,jumpHeld:!1,jumpPressed:!1,dashPressed:!1};function Pc(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 us=(t,e,n)=>t<e?Math.min(t+n,e):Math.max(t-n,e);function Ec(t,e,n,r,o=ct,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=us(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=Ht(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=ms(r,i,m.x,m.y,o.width,o.height,c,o.jumpCornerNudge);d!==null&&(m=Ht(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=ds(r,i,m.x,m.y,o.width,o.height,l,o.dashCornerNudge);d!==null&&(m=Ht(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:hs(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 Dc(t=ct){return t.jumpVelocity*t.jumpVelocity/(2*t.gravity)}function ls(t=ct){return 2*t.jumpVelocity/t.gravity}function cs(t=ct){return t.runSpeed*ls(t)}function Ic(t=ct){return cs(t)+(t.dashSpeed-t.runSpeed)*t.dashTime}function ms(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(!ze(t,c,r+s,o,i,e)&&!ze(t,c,r,o,i,e))return c}return null}function ds(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(!ze(t,n+s,c,o,i,e)&&!ze(t,n,c,o,i,e))return c}return null}function hs(t,e,n,r,o,i){return ze(t,n+1,r,o,i,e)?1:ze(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 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 ps(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)===Y.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 fs(t,e,n,r,o){return!ps(t,e,n,r,o).blocked}function $c(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:fs(t,e,n,a,u)}function Bc(t={}){return{gravityX:t.gravityX??0,gravityY:t.gravityY??900,iterations:t.iterations??16,cellSize:t.cellSize??96,nextId:1,bodies:[],joints:[],warm:{}}}function bs(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 gs=1e-4;function _c(t,e){let n=e.kind??"dynamic",r=e.density??1,{area:o,unitI:i}=bs(e.shape),s=n==="dynamic"?Math.max(o*r*gs,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 ve(t,e){let n=t.bodies;for(let r=0;r<n.length;r++)if(n[r].id===e)return n[r]}function Gc(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 xe(t){t.sleeping=!1,t.sleepTime=0}function Oc(t,e,n,r,o,i){let s=ve(t,e);!s||s.invM===0||(xe(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 Me(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 Cn(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=Me(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 Vc(t,e){let n=t/2,r=e/2;return{kind:"poly",points:[-n,-r,n,-r,n,r,-n,r]}}function ys(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 Ar(t,e){if(t.shape.kind!=="poly"||e.shape.kind!=="circle")return null;let n=Me(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,U=(e.x-n[D*2])*O+(e.y-n[D*2+1])*A;U>i&&(i=U,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 Nr(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 vs(t,e){let n=Me(t),r=Me(e),[o,i]=Nr(n,r);if(o>0)return null;let[s,a]=Nr(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 z=(_+1)%h,q=l[z*2]-l[_*2],ie=l[z*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],U=u[p*2+1];for(let _=0;_<2;_++){let z=_===0?F:A,q=_===0?O:U,ie=_===0?I:-I,se=_===0?y:-y,re=(D-z)*ie+(R-q)*se,ae=(k-z)*ie+(T-q)*se;if(re<0&&ae<0)return null;if(re<0){let le=re/(re-ae);D=D+(k-D)*le,R=R+(T-R)*le}else if(ae<0){let le=ae/(ae-re);k=k+(D-k)*le,T=T+(R-T)*le}}let X=m?-x:x,te=m?-C:C,Q=[],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&&Q.push({px:D,py:R,pen:oe,feature:L*2}),E>0&&Q.push({px:k,py:T,pen:E,feature:L*2+1}),Q.length===0?null:{a:t,b:e,nx:X,ny:te,points:Q}}function Lr(t,e){let n=t.shape.kind,r=e.shape.kind;if(n==="circle"&&r==="circle")return ys(t,e);if(n==="poly"&&r==="poly")return vs(t,e);if(n==="poly"&&r==="circle")return Ar(t,e);let o=Ar(e,t);return o?{a:t,b:e,nx:-o.nx,ny:-o.ny,points:o.points}:null}function $r(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 jt(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 Yc(t,e){let n=ve(t,e.a),r=ve(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]=jt(n,o,i),[c,m]=jt(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),xe(n),xe(r),d.id}function Kc(t,e){let n=ve(t,e.a),r=ve(t,e.b);if(!n||!r)throw new Error(`revolute joint: missing body ${e.a}/${e.b}`);let[o,i]=$r(n,e.px,e.py),[s,a]=$r(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),xe(n),xe(r),u.id}function Qc(t,e){for(let n of t.joints)if(n.id===e)return n}function Zc(t,e){t.joints=t.joints.filter(n=>n.id!==e)}function Wr(t,e,n,r,o){let[i,s]=jt(e,t.ax,t.ay),[a,u]=jt(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,U=e.vy+e.w*l,X=n.vx-n.w*d,te=n.vy+n.w*m,Q=(X-A)*k+(te-U)*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,z=-(Q+_)/L;t.rope&&z>0&&(z=0);let q=k*z,ie=T*z;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 U=o.motorImpulse-A;e.w-=U*e.invI,n.w+=U*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 xs=.5,ws=.2,ks=40,Ss=64,Ms=8,Ts=.5,zr=100;function Br(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 sm(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 qt(t.cellSize),i=new Map;for(let y=0;y<n.length;y++)o.insert(n[y],Cn(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(Cn(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))||!Br(f,S))continue;let R=!f.sleeping&&f.kind!=="static",k=!S.sleeping&&S.kind!=="static";if(!R&&!k)continue;let T=Lr(f,S);if(!T)continue;let F=(X,te)=>{X.sleeping&&(te.vx*te.vx+te.vy*te.vy>zr||te.kind==="kinematic")&&xe(X)};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,U=T.nx;for(let X of T.points){let te=X.px-f.x,Q=X.py-f.y,oe=X.px-S.x,E=X.py-S.y,L=te*T.ny-Q*T.nx,_=oe*T.ny-E*T.nx,z=f.invM+S.invM+f.invI*L*L+S.invI*_*_,q=te*U-Q*A,ie=oe*U-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*Q,ae=S.vy+S.w*oe-f.vy-f.w*te,le=re*T.nx+ae*T.ny,ge=Math.max(f.restitution,S.restitution),Le=`${f.id}:${S.id}:${X.feature}`,ke=t.warm[Le],Ii={rax:te,ray:Q,rbx:oe,rby:E,pen:X.pen,massN:z>1e-12?1/z:0,massT:se>1e-12?1/se:0,restBias:le<-ks?-ge*le:0,posBias:ws/e*Math.max(0,X.pen-xs),pn:ke?ke[0]:0,pt:ke?ke[1]:0,pb:0,key:Le};O.push(Ii)}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=ve(t,w.a),D=ve(t,w.b);!S||!D||S.sleeping&&D.sleeping||(S.sleeping&&xe(S),D.sleeping&&xe(D),Wr(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 U=S.vx-S.w*A.rby-w.vx+w.w*A.ray,X=S.vy+S.w*A.rbx-w.vy-w.w*A.rax,te=U*D+X*R,Q=A.massN*(A.restBias-te),oe=A.pn;A.pn=Math.max(oe+Q,0),Q=A.pn-oe;let E=D*Q,L=R*Q;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,U=S.vx-S.w*A.rby-w.vx+w.w*A.ray,X=S.vy+S.w*A.rbx-w.vy-w.w*A.rax;let _=U*F+X*O,z=A.massT*-_,q=f.friction*A.pn,ie=A.pt;if(A.pt=Math.min(Math.max(ie+z,-q),q),z=A.pt-ie,E=F*z,L=O*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,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 le=D*re,ge=R*re;l[k]-=le*w.invM,c[k]-=ge*w.invM,l[T]+=le*S.invM,c[T]+=ge*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||!Br(f,k))continue;let T=Cs(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=ve(t,y.a),w=ve(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>zr&&xe(f);continue}if(!f.canSleep||!b.has(f.id)){f.sleepTime=0;continue}f.sleepTime=w<Ss&&Math.abs(f.w)*f.sleepR<Ms?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)>=Ts&&(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 Cs(t,e,n,r,o,i){if(i.shape.kind==="circle")return _r(t,e,n,r,i.x,i.y,o+i.shape.r);let s=Me(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=Rs(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=_r(t,e,n,r,m,d,o);y>=0&&(u<0||y<u)&&(u=y)}return u}function _r(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 Rs(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 Ps(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=Me(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 cm(t,e,n,r=65535){let o;for(let i of t.bodies)(i.layer&r)!==0&&Ps(i,e,n)&&(o=i);return o}function Es(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 mm(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=Es(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=Me(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 Ut(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 we=t=>Number.isInteger(t)?String(t):(Math.round(t*1e3)/1e3).toString();function Or(t){let e=Math.max(1,t.length-1);return t.map((n,r)=>typeof n=="string"?{offset:r/e,color:n}:n)}function fm(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:Or(t)}}function bm(t,e={}){return{type:"radial",cx:e.cx??.5,cy:e.cy??.5,r:e.r??.5,stops:Or(t)}}function gm(t,e){return{color:t,blur:e}}function ym(t,e,n=0,r=0){return{color:t,blur:e,dx:n,dy:r}}function Ds(t){return`<stop offset="${we(t.offset)}" stop-color="${t.color}"/>`}function Vr(t,e){let n=t.stops.map(Ds).join("");return t.type==="linear"?`<linearGradient id="${e}" x1="${we(t.x1)}" y1="${we(t.y1)}" x2="${we(t.x2)}" y2="${we(t.y2)}">${n}</linearGradient>`:`<radialGradient id="${e}" cx="${we(t.cx)}" cy="${we(t.cy)}" r="${we(t.r)}">${n}</radialGradient>`}function Hr(t,e){return`<filter id="${e}" x="-60%" y="-60%" width="220%" height="220%"><feDropShadow dx="${we(t.dx??0)}" dy="${we(t.dy??0)}" stdDeviation="${we(t.blur/2)}" flood-color="${t.color}"/></filter>`}function qr(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 Xt(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 Gr=new Set;function mt(t,e,n){let r=`${t}:${e}`;Gr.has(r)||(Gr.add(r),console.warn(`hayao/render: skipped '${t}' command \u2014 ${e}`,n))}function jr(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 Is(t){return`matrix(${W(t.a)} ${W(t.b)} ${W(t.c)} ${W(t.d)} ${W(t.e)} ${W(t.f)})`}function Fs(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 As(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Ns(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%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+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 Ls(t,e,n){let r=`transform="${Is(t.transform)}"`,o,i;if(t.gradient){let a=`${n}g`;e.push(Vr(t.gradient,a)),o=`url(#${a})`}t.shadow&&(i=`${n}s`,e.push(Hr(t.shadow,i)));let s=Fs(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="${Ns(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}>${As(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=Ut(t).map((o,i)=>{let s=Xt(o);return s?(mt(o.kind,s,o),""):Ls(o,n,`${e}${i}`)}).join("");return(n.length?`<defs>${n.join("")}</defs>`:"")+r}function Jt(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 Rn="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(Rn,"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(Rn,"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(Rn,"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 Ur(t,e){let n=e;if(n.gradient){let r=qr(e);if(r&&r.w>0&&r.h>0)return jr(t,n.gradient,r);let o=n.gradient.stops;return o.length?o[o.length-1].color:n.fill}return n.fill}function dt(t,e){let n=Ur(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 $s(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 Ws(t,e){switch(e.kind){case"rect":t.beginPath(),e.r?$s(t,e.x,e.y,e.w,e.h,e.r):t.rect(e.x,e.y,e.w,e.h),dt(t,e);break;case"circle":t.beginPath(),t.arc(e.cx,e.cy,e.radius,0,Math.PI*2),dt(t,e);break;case"ellipse":t.beginPath(),t.ellipse(e.cx,e.cy,e.rx,e.ry,0,0,Math.PI*2),dt(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(),dt(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(),dt(t,e);break;case"path":{let n=new Path2D(e.d),r=Ur(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 Yt(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 Ut(e)){let a=Xt(s);if(a){mt(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),Ws(t,s)}catch(u){mt(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){Yt(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 zs=`#version 300 es
1
+ var gs=.6366197723675814,ys=1.5707963267341256,xs=6077100506506192e-26,vs=-.16666666666666632,ws=.00833333333332249,ks=-.0001984126982985795,Ss=27557313707070068e-22,Cs=-25050760253406863e-24,Ts=158969099521155e-24,Ms=.0416666666666666,Rs=-.001388888888887411,Ps=2480158728947673e-20,Ds=-27557314351390663e-23,Es=2087572321298175e-24,Is=-11359647557788195e-27;function Ht(t){let e=t*t;return t+t*e*(vs+e*(ws+e*(ks+e*(Ss+e*(Cs+e*Ts)))))}function qt(t){let e=t*t;return 1-.5*e+e*e*(Ms+e*(Rs+e*(Ps+e*(Ds+e*(Es+e*Is)))))}function Pr(t){let e=Math.round(t*gs),n=t-e*ys-e*xs;return{n:(e%4+4)%4,r:n}}function q(t){if(!Number.isFinite(t))return NaN;let{n:e,r:n}=Pr(t);switch(e){case 0:return Ht(n);case 1:return qt(n);case 2:return-Ht(n);default:return-qt(n)}}function U(t){if(!Number.isFinite(t))return NaN;let{n:e,r:n}=Pr(t);switch(e){case 0:return qt(n);case 1:return-Ht(n);case 2:return-qt(n);default:return Ht(n)}}var Vt=[.4636476090008061,.7853981633974483,.982793723247329,1.5707963267948966],Rr=[22698777452961687e-33,3061616997868383e-32,13903311031230998e-33,6123233995736766e-32],ye=[.3333333333333293,-.19999999999876483,.14285714272503466,-.11111110405462356,.09090887133436507,-.0769187620504483,.06661073137387531,-.058335701337905735,.049768779946159324,-.036531572744216916,.016285820115365782];function Ls(t){if(Number.isNaN(t))return NaN;if(!Number.isFinite(t))return t>0?Vt[3]:-Vt[3];let e=t<0||Object.is(t,-0)?-1:1,n=Math.abs(t);if(n>=1e19)return e*(Vt[3]+Rr[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*(ye[0]+i*(ye[2]+i*(ye[4]+i*(ye[6]+i*(ye[8]+i*ye[10]))))),a=i*(ye[1]+i*(ye[3]+i*(ye[5]+i*(ye[7]+i*ye[9]))));if(r<0)return e*(n-n*(s+a));let l=Vt[r]-(n*(s+a)-Rr[r]-n);return e*l}var Se=3.141592653589793;function $e(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)?-Se:Se:Object.is(t,-0)?-0:0;if(e===0||!Number.isFinite(t)&&Number.isFinite(e))return t>0?Se/2:-Se/2;if(!Number.isFinite(e)){if(!Number.isFinite(t)){let r=e>0?Se/4:3*Se/4;return t>0?r:-r}return e>0?t<0||Object.is(t,-0)?-0:0:t<0||Object.is(t,-0)?-Se:Se}let n=Ls(t/e);return e>0?n:t<0||Object.is(t,-0)?n-Se:n+Se}var $s=.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)*$s,r=1,o=1;for(let i=1;i<=13;i++)r=r*n/i,o+=r;return o*2**e}function Ye(t){return fe(t*Er)}function G(t,e){return Math.sqrt(t*t+e*e)}var He=new DataView(new ArrayBuffer(8)),Ns=.6931471803691238,Fs=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;He.setFloat64(0,t);let e=(He.getUint32(0)>>>20&2047)-1023;e===-1023&&(He.setFloat64(0,t*0x40000000000000),e=(He.getUint32(0)>>>20&2047)-1023-54),He.setUint32(0,He.getUint32(0)&1048575|1023<<20);let n=He.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*Ns+(2*r*i+e*Fs)}var As=.4342944819032518,Er=1.4426950408889634,jt=t=>Dr(t)*As,bt=t=>Dr(t)*Er;function De(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*bt(t)):t===0?e>0?0:1/0:NaN}var Ku=(t=0,e=0)=>({x:t,y:e}),Qu=(t,e)=>({x:t.x+e.x,y:t.y+e.y}),Zu=(t,e)=>({x:t.x-e.x,y:t.y-e.y}),ec=(t,e)=>({x:t.x*e,y:t.y*e}),tc=(t,e)=>t.x*e.x+t.y*e.y,Ws=t=>G(t.x,t.y),nc=(t,e)=>G(t.x-e.x,t.y-e.y);function rc(t){let e=Ws(t);return e===0?{x:0,y:0}:{x:t.x/e,y:t.y/e}}var Z=(t,e,n)=>t<e?e:t>n?n:t,Ne=(t,e,n)=>t+(e-t)*n,Ir=(t,e,n)=>t===e?0:(n-t)/(e-t),oc=(t,e,n,r,o)=>Ne(r,o,Ir(e,n,t)),Lr=(t,e,n)=>{let r=Z(t===e?n<t?0:1:Ir(t,e,n),0,1);return r*r*(3-2*r)},ee=Math.PI*2,ic=t=>t*Math.PI/180,sc=t=>t*180/Math.PI;function ac(t,e){return e.x>=t.x&&e.x<=t.x+t.w&&e.y>=t.y&&e.y<=t.y+t.h}function lc(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 ae={a:1,b:0,c:0,d:1,e:0,f:0};function Fe(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 qe(t,e,n){let r=U(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 gt(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 Ee(t){let e=t.a*t.d-t.b*t.c;if(e===0)return{...ae};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 cc(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 Bs(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=Bs(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}},Fn=new DataView(new ArrayBuffer(8));function dc(...t){let e=2654435769;for(let n of t)Fn.setFloat64(0,n),e=Math.imul(e^Fn.getUint32(0),2246822507)>>>0,e=(e^e>>>13)>>>0,e=Math.imul(e^Fn.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 $r(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 Ut=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 yt=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}},Xt=class{signals=new Map;signalFor(e){let n=this.signals.get(e);return n||(n=new yt,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 zs(t){return Number.isNaN(t)?"NaN":t===1/0?"Inf":t===-1/0?"-Inf":t===0?"0":t.toString()}function Jt(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("#"+zs(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 Nr=0;function Fr(t=0){Nr=t}var O=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${Nr++}`,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 yt,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=qe(this.pos,this.rotation,this.scale);return this.pivot?Fe(e,qe({x:-this.pivot.x,y:-this.pivot.y},0,{x:1,y:1})):e}worldTransform(){let e=this.localTransform();return this.parent?Fe(this.parent.worldTransform(),e):e}collectDraw(e,n=ae){if(!this.visible)return;let r=Fe(this.screenSpace?ae: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 An(t,e){return[0,-e/2,t/2,0,0,e/2,-t/2,0]}function _s(t,e,n=0){let r=[];for(let o=0;o<t;o++){let i=n-ee/4+ee*o/t;r.push(U(i)*e,q(i)*e)}return r}var Yt=class extends O{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:An(this.shape.w,this.shape.h),closed:!0,...o});break;case"regularPoly":e.push({kind:"poly",points:_s(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)}},Kt=class extends O{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)}},Qt=class extends O{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)}},Zt=class extends O{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 Ar(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 Wr=class extends O{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:Ar(this.fill,.65)},u=this.rightPaint??{fill:Ar(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=An(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)}},Br=class extends O{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 zr=class extends O{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:Z(o,m,d),i=h>p?(this.bounds.minY+this.bounds.maxY)/2:Z(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=Z(this.smooth,0,1);e.pos.x=Ne(e.pos.x,n.x,r),e.pos.y=Ne(e.pos.y,n.y,r)}};var _r=class extends O{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 Or=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 Ac=(t,e,n,r)=>Ne(e,t,Ye(-n*r)),Os=(t=0)=>({value:t,vel:0});function Gs(t,e,n,r){let o=Ye(-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 Wc(t=0,e=.25){let n=4/Math.max(1e-4,e),r=Os(t);return(o,i)=>Gs(r,o,n,i).value}var Gr=t=>t*t,Wn=t=>t*t*t,Ae={linear:t=>t,quadIn:t=>t*t,quadOut:t=>1-(1-t)*(1-t),quadInOut:t=>t<.5?2*t*t:1-Gr(-2*t+2)/2,cubicIn:t=>t*t*t,cubicOut:t=>1-Wn(1-t),cubicInOut:t=>t<.5?4*t*t*t:1-Wn(-2*t+2)/2,sineIn:t=>1-U(t*Math.PI/2),sineOut:t=>q(t*Math.PI/2),sineInOut:t=>-(U(Math.PI*t)-1)/2,backOut:t=>1+2.70158*Wn(t-1)+1.70158*Gr(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},en=class extends O{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:Ae[i]??Ae.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=Z(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 Vr=class extends O{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()*ee,a=r.speedMin+o.float()*(r.speedMax-r.speedMin),l={x:n.x,y:n.y,vx:U(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=Vs.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}},Vs={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 Hs(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)*Lr(r.time,o.time,t)}return e[e.length-1].intensity}var Hr=class extends O{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()*ee,depth:.5+this.rng.float()*.5})}intensity(){return this.envelope?Hs(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*ee+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}},Vc={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})},qr=class extends O{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 jr=class extends O{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:Z(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:Z(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}},Xc={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 Ur=class extends O{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 $e(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=Ee(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 qs=["x","y","rotation","scaleX","scaleY","opacity"];function We(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 Bn(t,e){return t.loop==="once"&&t.duration>0&&e>=t.duration}function Ke(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=Ae[i.ease??"linear"]??Ae.linear;return s.v+(i.v-s.v)*u(l)}function tm(t,e){let n=We(t,e);return t.tracks.map(r=>({target:r.target,channel:r.channel,value:Ke(r.keys,n)}))}function Xr(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=We(t,e),u=We(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 nm(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(qs.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 Ae)&&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 tn=(t,e)=>`${t}/${e}`;function zn(t,e){let n=We(t,e*t.duration),r={};for(let o of t.tracks)r[tn(o.target,o.channel)]=Ke(o.keys,n);return r}function _n(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 Jr=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=zn(r[0].clip,n);return r.length===2&&(o=_n(o,zn(r[1].clip,n),r[1].weight)),o}},Yr=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:Z(((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=zn(s,r);for(let u in l)i[u]=(i[u]??0)+l[u]*a}return i}};function sm(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 je=class extends O{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)}},On=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 je&&e.push(n);return e}};function Gn(t){return new On(t)}function Vn(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 Hn(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":js(t,n);break}}function js(t,e){let n=t;n.paint&&(n.paint.opacity=e)}var nn=class extends O{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?Vn(n,this.ensureSkeleton()):[]}),this}rebind(e){if(e&&(this.rig=e),!!this.rig){this.skeleton=Gn(this.rig);for(let[,n]of this.clips)n.tracks=Vn(n.def,this.skeleton)}}ensureSkeleton(){return!this.skeleton&&this.rig&&(this.skeleton=Gn(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=Ae.quadInOut(i),a=this.clips.get(this.prevName);a&&this.samplePose(a,this.prevElapsed,this.poseA),this.samplePose(r,this.elapsed,this.poseB),_n(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=Xr(r.def,o,this.elapsed);for(let s of i)this.emit("event",s)}Bn(r.def,this.elapsed)&&!Bn(r.def,o)&&this.emit("finished",n)}applyDirect(e,n){let r=We(e.def,n),o=e.tracks;for(let i=0;i<o.length;i++){let s=o[i];Hn(s.node,s.channel,Ke(s.keys,r))}}samplePose(e,n,r){for(let s in r)delete r[s];let o=We(e.def,n),i=e.tracks;for(let s=0;s<i.length;s++){let a=i[s];r[tn(a.target,a.channel)]=Ke(a.keys,o)}}applyPose(e,n){let r=e.tracks;for(let o=0;o<r.length;o++){let i=r[o],s=n[tn(i.target,i.channel)];s!==void 0&&Hn(i.node,i.channel,s)}}};function eo(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=$e(s,i),d=Kr((e*e+a*a-n*n)/(2*e*a)),h=Qr(d),p=Kr((e*e+n*n-a*a)/(2*e*n)),f=Qr(p),g=m-o*h,k=g+o*(Math.PI-f);return{angle0:g,angle1:k,reachable:c}}function Kr(t){return t<-1?-1:t>1?1:t}function Qr(t){return $e(Math.sqrt(1-t*t),t)}function to(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:Zr(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:Zr(l),reachable:!0,iterations:c}}function Zr(t){let e=[];for(let n=0;n<t.length-1;n++)e.push($e(t[n+1].y-t[n].y,t[n+1].x-t[n].x));return e}var no=class extends O{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=Ee(a),u=Us(l,s),c={x:r.pos.x,y:r.pos.y};if(n.length===2){let f=eo(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=to(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+=U(r)*s.length,i+=q(r)*s.length,n.push({x:o,y:i});return n}};function Us(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 ro=class extends O{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 je){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=Fe(r,qe({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 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"},Xs={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},qn={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},Js={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},Em={meadow:Xs,dusk:qn,paper:Js};function Im(t,e,n){let r=Qe(t),o=Qe(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 xt(i,s,a)}function Lm(t,e){let[n,r,o]=Qe(t);return`rgba(${n}, ${r}, ${o}, ${e})`}function Qe(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 xt(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 so=t=>(t%360+360)%360,vt=t=>t<0?0:t>1?1:t;function Ys(t,e,n){if(t=so(t)/360,e=vt(e),n=vt(n),e===0){let s=n*255;return xt(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 xt(i(t+1/3)*255,i(t)*255,i(t-1/3)*255)}function $m(t,e,n){t=so(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,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],xt((s+i)*255,(a+i)*255,(l+i)*255)}function Ks(t){let[e,n,r]=Qe(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 Nm(t,e,n={}){let r=Ks(e),o=n.hue??0,i=n.sat??0,s=n.light??0;return Ys(r.h+t.range(-o,o),r.s+t.range(-i,i),r.l+t.range(-s,s))}var oo=t=>t<=.04045?t/12.92:De((t+.055)/1.055,2.4),Qs=t=>t<=.0031308?t*12.92:1.055*De(t,1/2.4)-.055;function wt(t,e,n){let r=Qe(t),o=Qe(e),i=s=>{let a=oo(r[s]/255),l=oo(o[s]/255);return Qs(a+(l-a)*n)*255};return xt(i(0),i(1),i(2))}function io(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 wt(t[o],t[o+1],r-o)}function Fm(t,e){return e<=0?[]:e===1?[io(t,0)]:Array.from({length:e},(n,r)=>io(t,r/(e-1)))}var Wm=0,Be=.5,Bm=1;function Ze(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 Om(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 ao(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 Gm(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 et={Isolated:0,Cap:1,Straight:2,Bend:3,Tee:4,Cross:5};function Zs(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 ea=(()=>{let t=[[et.Isolated,0],[et.Cap,ne.N],[et.Straight,ne.N|ne.S],[et.Bend,ne.N|ne.E],[et.Tee,ne.N|ne.E|ne.S],[et.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=Zs(o)}return e})();function ta(t){return ea[t&15]}function Vm(t){return t.map((e,n)=>e.map((r,o)=>r?ta(ao(t,o,n)):null))}function na(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 ra=[[],[["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 jn(t,e={}){let n=e.cell??1,r=e.x??0,o=e.y??0,i=na(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 ra[i[l][u]])s.push({a:a(d,c,m),b:a(h,c,m)})}return s}function Hm(t,e={}){let n=e.tile??8,r=e.x??0,o=e.y??0,i=e.z??0,s=e.transform??ae,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=ao(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 qm(t,e={}){let n=e.tile??8,r=e.transform??ae,o=e.z??0,i=e.edge??e.fill??"#333",s=e.edgeWidth??Math.max(1,n/8);return jn(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 X={EMPTY:0,SOLID:1,ONEWAY:2,HAZARD:3},lo={"#":X.SOLID,"-":X.ONEWAY,"^":X.HAZARD};function uo(t,e=32,n=lo){let r=t.length,o=Math.max(...t.map(s=>s.length)),i=new Array(o*r).fill(X.EMPTY);return t.forEach((s,a)=>{for(let l=0;l<s.length;l++)i[a*o+l]=n[s[l]]??X.EMPTY}),{cols:o,rows:r,tileSize:e,tiles:i}}function Um(t,e=32,n=lo){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?X.SOLID:t.tiles[n*t.cols+e]}function Xm(t,e,n){return pe(t,Math.floor(e/t.tileSize),Math.floor(n/t.tileSize))}var Jm=t=>t.cols*t.tileSize,Ym=t=>t.rows*t.tileSize;function td(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)===X.SOLID);e.push(r)}return jn(e,{cell:t.tileSize})}function co(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||oa(t,i)<=o)&&r.push(i)}return r}function oa(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 mo(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 kt=class extends O{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{}}},rn=class extends O{type="LightLayer";ambient;softShadows;width;height;occluders=[];constructor(e={}){super(e),this.cosmetic=!0,this.ambient={color:e.ambient?.color??qn.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":wt(this.ambient.color,"#ffffff",ho(this.ambient.level)),o={kind:"rect",x:0,y:0,w:this.width,h:this.height,fill:r,blend:"multiply",transform:ae,z:0,layer:.5};e.push(o);for(let i of this.children){if(!(i instanceof kt)||!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=wt("#000000",m,c),h=wt("#000000",m,c*.5),p="#000000",f=ho(.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=co({x:a,y:l},u,this.occluders),v=mo({x:a,y:l},u,k);for(let M of v)e.push(po(M,r,n,1)),this.softShadows&&e.push(po(ia(M),r,n,.5))}}}},ho=t=>t<0?0:t>1?1:t;function po(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 ia(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 fo=new Map;function Ce(t,e){fo.set(t,e)}Ce("Node",()=>new O);Ce("Sprite",()=>new Yt({shape:{kind:"rect",w:1,h:1}}));Ce("Text",()=>new Kt({text:""}));Ce("Camera2D",()=>new Qt);Ce("Timer",()=>new Zt({duration:1}));Ce("AnimationPlayer",()=>new en);Ce("Bone2D",()=>new je);Ce("ClipPlayer",()=>new nn);Ce("PointLight",()=>new kt);Ce("LightLayer",()=>new rn);function Un(t){let e=fo.get(t.type);if(!e)throw new Error(`hayao: unknown node type "${t.type}" (register it first)`);let n=e();n.name=t.name,n.pos={...t.pos},n.rotation=t.rotation,n.scale={...t.scale},n.z=t.z,n.visible=t.visible,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(Un(r));return n}var on=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 tt(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 go(t,e){let n=Math.PI*2/e;return Math.round(t/n)*n}function yo(t,e){let n=[];for(let r in t)t[r].some(o=>e.has(o))&&n.push(r);return n.sort()}var bo=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 St(t,e){return t.frames[e]??[]}function Ct(t,e){return t.axes?.[e]}var Xn={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 nt=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=yo(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)}},xo=["mouse.left","mouse.right","mouse.middle"],sn=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(xo),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 xo)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 vo=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??sa,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=>tt(d,this.stickBuckets,-1,1),a=d=>tt(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()}},sa={0:"confirm",1:"cancel",2:"action2",3:"action",9:"confirm",12:"up",13:"down",14:"left",15:"right"};var J=1e-6,Ue=(t,e,n)=>[Math.floor(t/n),Math.floor((e-J)/n)];function Xe(t,e,n,r,o,i=[]){let s=t.tileSize,[a,l]=Ue(e,e+r,s),[u,c]=Ue(n,n+o,s);for(let m=u;m<=c;m++)for(let d=a;d<=l;d++)if(pe(t,d,m)===X.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 an(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]=Ue(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)===X.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)===X.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]=Ue(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===X.SOLID||T===X.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)===X.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=aa(t,a,l,u,c,s,o.dropThrough??!1);g=x.grounded,v=x.solid}let M=3,I=!1;{let[x,b]=Ue(a+M,a+u-M,i),[w,C]=Ue(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)===X.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 aa(t,e,n,r,o,i=[],s=!1){let a=t.tileSize,l=n+o,[u,c]=Ue(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===X.SOLID)return{grounded:!0,solid:-1};if(h===X.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 Tt={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},Pd={moveX:0,moveY:0,jumpHeld:!1,jumpPressed:!1,dashPressed:!1};function Dd(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 la=(t,e,n)=>t<e?Math.min(t+n,e):Math.max(t-n,e);function Ed(t,e,n,r,o=Tt,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=la(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=an(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=ma(r,i,m.x,m.y,o.width,o.height,c,o.jumpCornerNudge);d!==null&&(m=an(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=da(r,i,m.x,m.y,o.width,o.height,u,o.dashCornerNudge);d!==null&&(m=an(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:ha(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 Id(t=Tt){return t.jumpVelocity*t.jumpVelocity/(2*t.gravity)}function ua(t=Tt){return 2*t.jumpVelocity/t.gravity}function ca(t=Tt){return t.runSpeed*ua(t)}function Ld(t=Tt){return ca(t)+(t.dashSpeed-t.runSpeed)*t.dashTime}function ma(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(!Xe(t,c,r+s,o,i,e)&&!Xe(t,c,r,o,i,e))return c}return null}function da(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(!Xe(t,n+s,c,o,i,e)&&!Xe(t,n,c,o,i,e))return c}return null}function ha(t,e,n,r,o,i){return Xe(t,n+1,r,o,i,e)?1:Xe(t,n-1,r,o,i,e)?-1:0}var ln=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 pa(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)===X.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 fa(t,e,n,r,o){return!pa(t,e,n,r,o).blocked}function Wd(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<U(i/2)?!1:fa(t,e,n,a,l)}function _d(t={}){return{gravityX:t.gravityX??0,gravityY:t.gravityY??900,iterations:t.iterations??16,cellSize:t.cellSize??96,nextId:1,bodies:[],joints:[],warm:{}}}function ba(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 ga=1e-4;function Od(t,e){let n=e.kind??"dynamic",r=e.density??1,{area:o,unitI:i}=ba(e.shape),s=n==="dynamic"?Math.max(o*r*ga,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 xe(t,e){let n=t.bodies;for(let r=0;r<n.length;r++)if(n[r].id===e)return n[r]}function Gd(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 ve(t){t.sleeping=!1,t.sleepTime=0}function Vd(t,e,n,r,o,i){let s=xe(t,e);!s||s.invM===0||(ve(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 Te(t){if(t.shape.kind!=="poly")return[];let e=U(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 Jn(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=Te(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 Hd(t,e){let n=t/2,r=e/2;return{kind:"poly",points:[-n,-r,n,-r,n,r,-n,r]}}function ya(t,e){if(t.shape.kind!=="circle"||e.shape.kind!=="circle")return null;let n=e.x-t.x,r=e.y-t.y,o=t.shape.r+e.shape.r,i=n*n+r*r;if(i>=o*o)return null;let s=Math.sqrt(i),a=s>1e-9?n/s:1,l=s>1e-9?r/s:0;return{a:t,b:e,nx:a,ny:l,points:[{px:t.x+a*t.shape.r,py:t.y+l*t.shape.r,pen:o-s,feature:0}]}}function wo(t,e){if(t.shape.kind!=="poly"||e.shape.kind!=="circle")return null;let n=Te(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 ko(t,e){let n=t.length/2,r=e.length/2,o=-1/0,i=0;for(let s=0;s<n;s++){let a=(s+1)%n,l=t[a*2]-t[s*2],u=t[a*2+1]-t[s*2+1],c=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 xa(t,e){let n=Te(t),r=Te(e),[o,i]=ko(n,r);if(o>0)return null;let[s,a]=ko(r,n);if(s>0)return null;let l,u,c,m;s>o+1e-4?(l=r,u=n,c=a,m=!0):(l=n,u=r,c=i,m=!1);let d=l.length/2,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 _=0;_<h;_++){let B=(_+1)%h,j=u[B*2]-u[_*2],ie=u[B*2+1]-u[_*2+1],se=G(j,ie)||1,re=ie/se*v+-j/se*M;re<w&&(w=re,b=_)}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 _=0;_<2;_++){let B=_===0?L:$,j=_===0?H:Y,ie=_===0?I:-I,se=_===0?x:-x,re=(E-B)*ie+(R-j)*se,le=(S-B)*ie+(T-j)*se;if(re<0&&le<0)return null;if(re<0){let ce=re/(re-le);E=E+(S-E)*ce,R=R+(T-R)*ce}else if(le<0){let ce=le/(le-re);S=S+(E-S)*ce,T=T+(R-T)*ce}}let K=m?-v:v,te=m?-M:M,Q=[],oe=-((E-L)*v+(R-H)*M),D=-((S-L)*v+(T-H)*M),A=((m?1:0)*64+c)*64+b;return oe>0&&Q.push({px:E,py:R,pen:oe,feature:A*2}),D>0&&Q.push({px:S,py:T,pen:D,feature:A*2+1}),Q.length===0?null:{a:t,b:e,nx:K,ny:te,points:Q}}function So(t,e){let n=t.shape.kind,r=e.shape.kind;if(n==="circle"&&r==="circle")return ya(t,e);if(n==="poly"&&r==="poly")return xa(t,e);if(n==="poly"&&r==="circle")return wo(t,e);let o=wo(e,t);return o?{a:t,b:e,nx:-o.nx,ny:-o.ny,points:o.points}:null}function Co(t,e,n){let r=U(t.a),o=q(t.a),i=e-t.x,s=n-t.y;return[i*r+s*o,-i*o+s*r]}function un(t,e,n){let r=U(t.a),o=q(t.a);return[t.x+e*r-n*o,t.y+e*o+n*r]}function Kd(t,e){let n=xe(t,e.a),r=xe(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]=un(n,o,i),[c,m]=un(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),ve(n),ve(r),d.id}function Qd(t,e){let n=xe(t,e.a),r=xe(t,e.b);if(!n||!r)throw new Error(`revolute joint: missing body ${e.a}/${e.b}`);let[o,i]=Co(n,e.px,e.py),[s,a]=Co(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),ve(n),ve(r),l.id}function Zd(t,e){for(let n of t.joints)if(n.id===e)return n}function eh(t,e){t.joints=t.joints.filter(n=>n.id!==e)}function To(t,e,n,r,o){let[i,s]=un(e,t.ax,t.ay),[a,l]=un(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,Q=(K-$)*S+(te-Y)*T,oe=u*T-c*S,D=m*T-d*S,A=e.invM+n.invM+e.invI*oe*oe+n.invI*D*D;if(A<1e-12)return;let _=.2/r*H,B=-(Q+_)/A;t.rope&&B>0&&(B=0);let j=S*B,ie=T*B;e.vx-=j*e.invM,e.vy-=ie*e.invM,e.w-=(u*ie-c*j)*e.invI,n.vx+=j*n.invM,n.vy+=ie*n.invM,n.w+=(m*ie-d*j)*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 va=.5,wa=.2,ka=40,Sa=64,Ca=8,Ta=.5,Mo=100;function Ro(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 ah(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 ln(t.cellSize),i=new Map;for(let x=0;x<n.length;x++)o.insert(n[x],Jn(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(Jn(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))||!Ro(b,C))continue;let R=!b.sleeping&&b.kind!=="static",S=!C.sleeping&&C.kind!=="static";if(!R&&!S)continue;let T=So(b,C);if(!T)continue;let L=(K,te)=>{K.sleeping&&(te.vx*te.vx+te.vy*te.vy>Mo||te.kind==="kinematic")&&ve(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,Q=K.py-b.y,oe=K.px-C.x,D=K.py-C.y,A=te*T.ny-Q*T.nx,_=oe*T.ny-D*T.nx,B=b.invM+C.invM+b.invI*A*A+C.invI*_*_,j=te*Y-Q*$,ie=oe*Y-D*$,se=b.invM+C.invM+b.invI*j*j+C.invI*ie*ie,re=C.vx-C.w*D-b.vx+b.w*Q,le=C.vy+C.w*oe-b.vy-b.w*te,ce=re*T.nx+le*T.ny,ge=Math.max(b.restitution,C.restitution),Ve=`${b.id}:${C.id}:${K.feature}`,ke=t.warm[Ve],bs={rax:te,ray:Q,rbx:oe,rby:D,pen:K.pen,massN:B>1e-12?1/B:0,massT:se>1e-12?1/se:0,restBias:ce<-ka?-ge*ce:0,posBias:wa/e*Math.max(0,K.pen-va),pn:ke?ke[0]:0,pt:ke?ke[1]:0,pb:0,key:Ve};H.push(bs)}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=xe(t,w.a),E=xe(t,w.b);!C||!E||C.sleeping&&E.sleeping||(C.sleeping&&ve(C),E.sleeping&&ve(E),To(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,Q=$.massN*($.restBias-te),oe=$.pn;$.pn=Math.max(oe+Q,0),Q=$.pn-oe;let D=E*Q,A=R*Q;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 _=Y*L+K*H,B=$.massT*-_,j=b.friction*$.pn,ie=$.pt;if($.pt=Math.min(Math.max(ie+B,-j),j),B=$.pt-ie,D=L*B,A=H*B,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 se=(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-se),le=$.pb;$.pb=Math.max(le+re,0),re=$.pb-le;let ce=E*re,ge=R*re;u[S]-=ce*w.invM,c[S]-=ge*w.invM,u[T]+=ce*C.invM,c[T]+=ge*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||!Ro(b,S))continue;let T=Ma(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=xe(t,x.a),w=xe(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>Mo&&ve(b);continue}if(!b.canSleep||!f.has(b.id)){b.sleepTime=0;continue}b.sleepTime=w<Sa&&Math.abs(b.w)*b.sleepR<Ca?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)>=Ta&&(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 Ma(t,e,n,r,o,i){if(i.shape.kind==="circle")return Po(t,e,n,r,i.x,i.y,o+i.shape.r);let s=Te(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=Ra(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=Po(t,e,n,r,m,d,o);x>=0&&(l<0||x<l)&&(l=x)}return l}function Po(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 Ra(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 Pa(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=Te(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 mh(t,e,n,r=65535){let o;for(let i of t.bodies)(i.layer&r)!==0&&Pa(i,e,n)&&(o=i);return o}function Da(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 dh(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=Da(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=Te(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 we=t=>Number.isInteger(t)?String(t):(Math.round(t*1e3)/1e3).toString();function Eo(t){let e=Math.max(1,t.length-1);return t.map((n,r)=>typeof n=="string"?{offset:r/e,color:n}:n)}function fh(t,e=90){let n=e*Math.PI/180,r=U(n)*.5,o=q(n)*.5;return{type:"linear",x1:.5-r,y1:.5-o,x2:.5+r,y2:.5+o,stops:Eo(t)}}function bh(t,e={}){return{type:"radial",cx:e.cx??.5,cy:e.cy??.5,r:e.r??.5,stops:Eo(t)}}function gh(t,e){return{color:t,blur:e}}function yh(t,e,n=0,r=0){return{color:t,blur:e,dx:n,dy:r}}function Ea(t){return`<stop offset="${we(t.offset)}" stop-color="${t.color}"/>`}function Yn(t,e){let n=t.stops.map(Ea).join("");return t.type==="linear"?`<linearGradient id="${e}" x1="${we(t.x1)}" y1="${we(t.y1)}" x2="${we(t.x2)}" y2="${we(t.y2)}">${n}</linearGradient>`:`<radialGradient id="${e}" cx="${we(t.cx)}" cy="${we(t.cy)}" r="${we(t.r)}">${n}</radialGradient>`}function Io(t,e){return`<filter id="${e}" x="-60%" y="-60%" width="220%" height="220%"><feDropShadow dx="${we(t.dx??0)}" dy="${we(t.dy??0)}" stdDeviation="${we(t.blur/2)}" flood-color="${t.color}"/></filter>`}function Lo(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 cn(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 Do=new Set;function Mt(t,e,n){let r=`${t}:${e}`;Do.has(r)||(Do.add(r),console.warn(`hayao/render: skipped '${t}' command \u2014 ${e}`,n))}function $o(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 rt(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 ot(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 wh=t=>(t.layer??0)===.5;function it(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 st(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 mn(t){return`matrix(${N(t.a)} ${N(t.b)} ${N(t.c)} ${N(t.d)} ${N(t.e)} ${N(t.f)})`}function Ia(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 La(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function $a(t){let e=t.radius,n=t.cx+U(t.start)*e,r=t.cy+q(t.start)*e,o=t.end-t.start,i=(o%ee+ee)%ee;if(i===0&&o!==0&&(i=ee),i>=ee-1e-9){let c=t.cx+U(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+U(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 Na(t,e,n){let r=`transform="${mn(t.transform)}"`,o,i;if(t.gradient){let a=`${n}g`;e.push(Yn(t.gradient,a)),o=`url(#${a})`}t.shadow&&(i=`${n}s`,e.push(Io(t.shadow,i)));let s=Ia(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="${$a(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}>${La(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 Fa(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 Aa(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="${mn(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(Yn(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="${mn(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="${Fa(g)}" transform="${mn(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 at(t,e="h",n=1280,r=720){let o=[],i=Ze(t),{below:s,light:a,above:l}=rt(i),u=a.length?ot(a):null,c=u?[...s,...l]:i,m=(h,p)=>h.map((f,g)=>{let k=cn(f);return k?(Mt(f.kind,k,f),""):Na(f,o,`${e}${p+g}`)}).join(""),d;return u?d=m(s,0)+Aa(u,o,e,n,r)+m(l,s.length):d=m(c,0),(o.length?`<defs>${o.join("")}</defs>`:"")+d}function dn(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}"/>`+at(t,"h",e,n)+"</svg>"}var Kn="http://www.w3.org/2000/svg",lt=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(Kn,"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(Kn,"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(Kn,"g"),this.svg.appendChild(this.layer)}mount(e){e.appendChild(this.svg)}draw(e){this.layer.innerHTML=at(e)}setBackground(e){this.background=e,this.bg.setAttribute("fill",e)}get element(){return this.svg}toDesign(e,n){return it(this.svg.getBoundingClientRect(),this.width,this.height,e,n)}viewport(){return st(this.svg.getBoundingClientRect(),this.width,this.height)}dispose(){this.svg.remove()}};function Ao(t,e){let n=e;if(n.gradient){let r=Lo(e);if(r&&r.w>0&&r.h>0)return $o(t,n.gradient,r);let o=n.gradient.stops;return o.length?o[o.length-1].color:n.fill}return n.fill}function Rt(t,e){let n=Ao(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 Wa(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 Wo(t,e){switch(e.kind){case"rect":t.beginPath(),e.r?Wa(t,e.x,e.y,e.w,e.h,e.r):t.rect(e.x,e.y,e.w,e.h),Rt(t,e);break;case"circle":t.beginPath(),t.arc(e.cx,e.cy,e.radius,0,Math.PI*2),Rt(t,e);break;case"ellipse":t.beginPath(),t.ellipse(e.cx,e.cy,e.rx,e.ry,0,0,Math.PI*2),Rt(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(),Rt(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(),Rt(t,e);break;case"path":{let n=new Path2D(e.d),r=Ao(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 Pt(t,e){let n=cn(e);if(n){Mt(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),Wo(t,e)}catch(r){Mt(e.kind,"paint threw",r)}t.restore()}var No=new WeakMap;function Fo(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 Ba(t,e,n){let r=No.get(t);if(r&&r.w===e&&r.h===n)return r;let o=Fo(t,e,n),i=Fo(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 No.set(t,s),s}function za(t,e,n,r,o){let i=Math.max(1,Math.round(n*o)),s=Math.max(1,Math.round(r*o)),a=Ba(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),Pt(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),Pt(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,Wo(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 hn(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=Ze(e),{below:a,light:l,above:u}=rt(s);for(let c of a)Pt(t,c);if(l.length){let c=ot(l);if(!(c?za(t,c,n,r,i):!1)){t.setTransform(i,0,0,i,0,0);for(let d of l)Pt(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)Pt(t,c)}var ut=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){hn(this.ctx,e,this.width,this.height,this.background,this.dpr)}get element(){return this.canvas}toDesign(e,n){return it(this.canvas.getBoundingClientRect(),this.width,this.height,e,n)}viewport(){return st(this.canvas.getBoundingClientRect(),this.width,this.height)}dispose(){this.canvas.remove()}};var _a=`#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
- }`,Qt=`#version 300 es
14
+ }`,fn=`#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); }`,Kt={passthrough:Qt,pixelate:`#version 300 es
20
+ void main() { fragColor = texture(u_prev, v_uv); }`,pn={passthrough:fn,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
- }`},Wm=[{shader:Kt.bloomBrightpass},{shader:Kt.bloomHBlur},{shader:Kt.bloomVBlur},{shader:Kt.bloomComposite}];function Xr(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 Bs(t,e){let n=Xr(t,t.VERTEX_SHADER,zs),r=Xr(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 Jr(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 _s(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 Zt=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??Qt}])}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(Bs(n,i.shader)),this.passUniforms.push(i.uniforms??{});for(let i=0;i<e.length-1;i++)this.fbos.push(_s(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;Yt(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)Jr(n,u,c,m);for(let[c,m]of Object.entries(this.passUniforms[a]))Jr(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:Qt}]),this}setPostProcess(e){return this.setPipeline([{shader:e}])}clearPostProcess(){return this.setPostProcess(Qt)}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 Yr=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 Jt(this.last,this.width,this.height,this.background)}};function Om(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 Vm={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 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"},Gs={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},Os={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},Vs={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},jm={meadow:Gs,dusk:Os,paper:Vs};function Um(t,e,n){let r=Ye(t),o=Ye(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 ht(i,s,a)}function Xm(t,e){let[n,r,o]=Ye(t);return`rgba(${n}, ${r}, ${o}, ${e})`}function Ye(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 ht(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 Zr=t=>(t%360+360)%360,pt=t=>t<0?0:t>1?1:t;function Hs(t,e,n){if(t=Zr(t)/360,e=pt(e),n=pt(n),e===0){let s=n*255;return ht(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 ht(i(t+1/3)*255,i(t)*255,i(t-1/3)*255)}function Jm(t,e,n){t=Zr(t)/60,e=pt(e),n=pt(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],ht((s+i)*255,(a+i)*255,(u+i)*255)}function qs(t){let[e,n,r]=Ye(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 Ym(t,e,n={}){let r=qs(e),o=n.hue??0,i=n.sat??0,s=n.light??0;return Hs(r.h+t.range(-o,o),r.s+t.range(-i,i),r.l+t.range(-s,s))}var Kr=t=>t<=.04045?t/12.92:Pe((t+.055)/1.055,2.4),js=t=>t<=.0031308?t*12.92:1.055*Pe(t,1/2.4)-.055;function Us(t,e,n){let r=Ye(t),o=Ye(e),i=s=>{let a=Kr(r[s]/255),u=Kr(o[s]/255);return js(a+(u-a)*n)*255};return ht(i(0),i(1),i(2))}function Qr(t,e){if(t.length===0)return"#000000";if(t.length===1)return t[0];let r=pt(e)*(t.length-1),o=Math.min(t.length-2,Math.floor(r));return Us(t[o],t[o+1],r-o)}function Km(t,e){return e<=0?[]:e===1?[Qr(t,0)]:Array.from({length:e},(n,r)=>Qr(t,r/(e-1)))}function td(t,e,n=0){let r=[];for(let o=0;o<t;o++){let i=n+o/t*Z;r.push(J(i)*e,H(i)*e)}return r}function nd(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,H(a)*s)}return o}function rd(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:H(s)*a})}return Xs(o)}function Xs(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 od(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 ft=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 to(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 ud(t,e,n){let r=to(t),o=e*n,i=new ft(e,n);for(let s=0;s<o;s++)i.data[s]=Number(r>>BigInt(o-1-s)&1n);return i}function ld(t,e,n){let r=to(t),o=e*n,i=new ft(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 cd(t,e,n){let r=new ft(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 md(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 Js(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 eo=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 Js(this.buffer,this.palette,{cell:r,x:o,y:i,z:this.z,transform:n}))e.push(s)}};var Ys={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:Ys};function Ks(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 oo(t,e){if(e===" "||e===`
174
- `)return e;let n=e.toUpperCase();return t.glyphs[n]?n:t.glyphs[e]?e:t.glyphs["?"]?"?":" "}function io(t,e){if(e===" ")return t.spaceWidth;let n=t.glyphs[e];return n?n[0].length:t.spaceWidth}function bt(t,e){let n=0;for(let r=0;r<e.length;r++)n+=io(t,e[r].ch),r<e.length-1&&(n+=t.tracking);return n}function gd(t,e){return bt(t,[...e].map((n,r)=>({ch:oo(t,n),i:r})))}function Qs(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:oo(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&&bt(t,d)+b+bt(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,bt(t,m));let l=n.maxWidth??u,c=0;for(let m of s){let d=bt(t,m),h=n.align==="center"?Math.floor((l-d)/2):n.align==="right"?l-d:0;for(let p of m){let b=io(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 Zs(t,e,n){if(n<=0)return t;let r=Math.floor(e*n);return r<0?0:r>t?t:r}function ea(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 ro=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??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=Ks(this.text,this.colorMap);return Qs(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=Zs(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 ea(this.font,r,{cell:this.cell,x:i,y:s,z:this.z,color:this.color,transform:n,reveal:o}))e.push(a)}};function xd(t,e="#"){return t.map(n=>[...n].map(r=>e.includes(r)))}function Ee(t,e,n){return n>=0&&n<t.length&&e>=0&&e<t[n].length&&t[n][e]}var ne={N:1,E:2,S:4,W:8};function so(t,e,n){return(Ee(t,e,n-1)?ne.N:0)|(Ee(t,e+1,n)?ne.E:0)|(Ee(t,e,n+1)?ne.S:0)|(Ee(t,e-1,n)?ne.W:0)}function wd(t,e,n){let r=0,o=[[0,-1],[1,-1],[1,0],[1,1],[0,1],[-1,1],[-1,0],[-1,-1]];for(let i=0;i<8;i++)Ee(t,e+o[i][0],n+o[i][1])&&(r|=1<<i);return r}var Ke={Isolated:0,Cap:1,Straight:2,Bend:3,Tee:4,Cross:5};function ta(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 na=(()=>{let t=[[Ke.Isolated,0],[Ke.Cap,ne.N],[Ke.Straight,ne.N|ne.S],[Ke.Bend,ne.N|ne.E],[Ke.Tee,ne.N|ne.E|ne.S],[Ke.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=ta(o)}return e})();function ra(t){return na[t&15]}function kd(t){return t.map((e,n)=>e.map((r,o)=>r?ra(so(t,o,n)):null))}function oa(t){let e=t.length,n=e?t[0].length:0,r=[];for(let o=0;o<e-1;o++){let i=[];for(let s=0;s<n-1;s++)i.push((Ee(t,s,o)?1:0)|(Ee(t,s+1,o)?2:0)|(Ee(t,s+1,o+1)?4:0)|(Ee(t,s,o+1)?8:0));r.push(i)}return r}var ia=[[],[["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 sa(t,e={}){let n=e.cell??1,r=e.x??0,o=e.y??0,i=oa(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 ia[i[u][l]])s.push({a:a(d,c,m),b:a(h,c,m)})}return s}function Sd(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=so(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 Md(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 sa(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 gt(t,e,n=0){return{cols:t,rows:e,cells:new Array(t*e).fill(n)}}function aa(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 ao(t,e,n){let r=0;for(let o=-1;o<=1;o++)for(let i=-1;i<=1;i++)i===0&&o===0||aa(t,e+i,n+o)===1&&r++;return r}function Rd(t,e=32){let n=t.cells.map(r=>r===1?Y.SOLID:Y.EMPTY);return{cols:t.cols,rows:t.rows,tileSize:e,tiles:n}}function ua(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 Qe(t,e,n=0){return ua(t,e,n)/4294967296}function Ed(t,e,n,r=0){return Math.floor(Qe(t,e,r)*n)}function la(t,e,n,r=0){return Qe(t,e,r)<n}function Dd(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++)la(u,a,o,i)&&s.push({x:u,y:a});return s}var uo=t=>t*t*(3-2*t);function ca(t,e,n=0){let r=Math.floor(t),o=Math.floor(e),i=uo(t-r),s=uo(e-o),a=Qe(r,o,n),u=Qe(r+1,o,n),l=Qe(r,o+1,n),c=Qe(r+1,o+1,n),m=a+(u-a)*i,d=l+(c-l)*i;return m+(d-m)*s}function lo(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*ca(t*u,e*u,n+m),c+=a,a*=s,u*=i;return c===0?0:l/c}function Ad(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=gt(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=gt(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=ao(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 co(t,e){let n=e.scale??.08,r=e.seed??0,o=lo(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 Wd(t,e,n){let r=new Array(e);for(let o=0;o<e;o++)r[o]=co(t+o,n);return r}function zd(t,e,n){return e>=co(t,n)}function mo(t){return{x:Math.floor(t.x+t.w/2),y:Math.floor(t.y+t.h/2)}}function ma(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 da(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 ho(t,e,n,r){for(let o=Math.min(e,n);o<=Math.max(e,n);o++)Fe(t,o,r,0)}function po(t,e,n,r){for(let o=Math.min(e,n);o<=Math.max(e,n);o++)Fe(t,r,o,0)}function Gd(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=gt(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=>ma(b,v))){if(da(u,b),l.length>0){let v=mo(l[l.length-1]),M=mo(b);t.chance(.5)?(ho(u,v.x,M.x,v.y),po(u,v.y,M.y,M.x)):(po(u,v.y,M.y,v.x),ho(u,v.x,M.x,M.y))}l.push(b)}}return{rooms:l,grid:u}}var be=44100;function bo(t,e=be){let n=Math.max(0,Math.round(t*e));return{sampleRate:e,left:new Float32Array(n),right:new Float32Array(n)}}function qd(t){return t.left.length}function jd(t){return t.left.length/t.sampleRate}function ha(t){let n=(ee(t,-1,1)+1)*.5*(Math.PI/2);return{l:J(n),r:H(n)}}function go(t,e,n,r=1,o=0){let{l:i,r:s}=ha(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 pa(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 fo(t){return t/Math.sqrt(1+t*t)}function yo(t){let{left:e,right:n}=t;for(let r=0;r<e.length;r++)e[r]=fo(e[r]),n[r]=fo(n[r])}function vo(t,e=.89){let n=pa(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 Ud(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 Xd(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 fa(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 en(t){return pe(t/12)}function xo(t,e,n,r){switch(t){case"sine":return H(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 tn(t,e={}){let n=fa(t),r=e.sampleRate??be,o=e.rng??new ce(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?en(n.detune/100):1,b=0,v=0,M=0,x=0,C=n.lowpass>0?wo(n.lowpass,r):1,I=n.highpass>0?1-wo(n.highpass,r):0,y=r*.5;for(let f=0;f<u;f++){let w=f*c,S=ba(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(Z*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*en(n.slide*R+n.slideAccel*R*R);n.pitchJump!==0&&D>=n.pitchJumpTime&&(k*=en(n.pitchJump)),n.vibrato>0&&(k*=en(n.vibrato*H(Z*n.vibratoFreq*w))),n.fm>0&&(k+=n.fm*H(Z*n.fmFreq*w)),k<0?k=0:k>y&&(k=y),m+=k*c,m-=Math.floor(m);let T=xo(n.wave,m,n.duty,o);n.detune!==0&&(d+=k*p*c,d-=Math.floor(d),T=(T+xo(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(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*=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 wo(t,e){let n=Z*t*(1/e);return n/(n+1)}function ba(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 ga={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},ya=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];function me(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=ga[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 nh(t){let e=(t%12+12)%12,n=Math.floor(t/12)-1;return ya[e]+n}function va(t,e=440){return e*pe((t-69)/12)}function ko(t,e=440){return va(typeof t=="number"?t:me(t),e)}var So={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 Pn(t,e="major",n=1){let r=So[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 Mo(t,e="major"){let n=(t%12+12)%12;return new Set(So[e].map(r=>(n+r)%12))}function xa(t,e,n,r=3){let o=(n%7+7)%7,i=Pn(t,e,3),s=[];for(let a=0;a<r;a++)s.push(i[o+a*2]);return s}var wa={i:0,ii:1,iii:2,iv:3,v:4,vi:5,vii:6};function Ze(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=wa[o[1].toLowerCase()];if(i===void 0)throw new Error(`bad roman numeral: ${JSON.stringify(r)}`);return xa(t,e,i,o[2]?4:3)})}function rh(t,e){return t.map(n=>n+e)}function En(t){return t.length<2?t.slice():[t[0]-12,...t.slice(1)].sort((e,n)=>e-n)}function yt(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 ka=[1116,1188,1277,1356,1422,1491,1557,1617],Sa=[556,441,341,225],Ma=23,Ta=.015,Dn=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}},In=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 To(t,e,n,r){let o=t/44100,i=ka.map(a=>new Dn(Math.round((a+r)*o),e,n)),s=Sa.map(a=>new In(Math.round((a+r)*o),.5));return{combs:i,aps:s}}function Co(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=To(s,i,o,0),u=To(s,i,o,Ma),l=t.left.length;for(let c=0;c<l;c++){let m=(t.left[c]+t.right[c])*Ta,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 Ca(t){let e=0;for(let n of t)e+=n.beats;return e}function Ra(t){let e=0;for(let n of t.sequence)e+=Ca(t.patterns[n]??[]);return e}function Pa(t){let e=0;for(let n of t.tracks)e=Math.max(e,Ra(n));return e}function Fn(t){return Pa(t)*60/t.bpm}function Po(t,e={}){let n=e.sampleRate??be,r=t.a4??440,o=60/t.bpm,i=t.tailSec??2,s=Fn(t)+i,a=bo(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 ce(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),U=m.instrument.lowpass,X=U&&c>0?U*(1-c*(1-k)):U;for(let te of T){let Q={...m.instrument,freq:ko(te,r),sustain:A,volume:(m.instrument.volume??.5)*k,...X!==void 0?{lowpass:X}:{}},oe=tn(Q,{rng:b,sampleRate:n});go(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;Ia(a,d,m)}return t.reverb&&Co(a,t.reverb),t.master&&Da(a,t.master),t.master?.compress&&Ea(a,t.master.compress),yo(a),vo(a,e.normalizePeak??.89),a}function Ea(t,e){let n=Math.max(0,Math.min(1,e)),r=t.sampleRate,o=Ro(-20),i=2+n*3,s=_e(-1/(r*.005)),a=_e(-1/(r*.15)),u=Ro(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*Pe(M,1/i)/l}let v=b*u;c[d]*=v,m[d]*=v}}function Ro(t){return pe(t/6.020599913)}function Da(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),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 Ia(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 Fa={master:.7,music:.6,sfx:.8,muted:!1},An=class{_ctx=null;master=null;musicGain=null;sfxGain=null;vol={...Fa};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=tn(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=Po(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=Fn(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)}},Be=new An;function Nn(t){let e=t<0?-t:t;return e<1e-12?-1/0:20*At(e)}function vt(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 Eo(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 Aa(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 Na(t){let e=1;for(;e*2<=t;)e*=2;return e}function La(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=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 xt(t){let e=Na(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}La(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 $a(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=xt(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 Do(t,e=1024,n=512){let r=[],o=null;for(let i=0;i+e<=t.length;i+=n){let s=xt(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 Wa(t,e=be){let r=Do(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 za(t,e=be){let r=Do(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 Io(t){let e=vt(t);return e<1e-9?0:Nn(Eo(t))-Nn(e)}function Fo(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=xt(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 wt(t,e=be){return{durationSec:t.length/e,rms:vt(t),peakDb:Nn(Eo(t)),centroidHz:$a(t,e),zcr:Aa(t,e),onsetDensity:Wa(t,e),tempoBpm:za(t,e)}}var Ba={"":[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 Te(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=Ba[a];if(!u)throw new Error(`unknown chord quality ${JSON.stringify(a)} in ${JSON.stringify(t)}`);let l=me(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=me(d+(e-1));for(;h>=c[0];)h-=12;c.unshift(h)}}return c}function nn(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 Sh(t,e=4){return t.map(n=>Te(n,e))}function Ao(t){try{return typeof t=="number"?t:me(t)}catch{return null}}function _a(t){return t.pitch===null||t.pitch===void 0?[]:Array.isArray(t.pitch)?t.pitch:[t.pitch]}function Ch(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?Mo(Ao(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 _a(p)){let v=Ao(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 Rh(t){return t.length===0?!1:(r=>r.trim().toLowerCase().replace(/7$/,""))(t[t.length-1])==="i"}var Ga={tempoBpm:20,centroidHz:1200,rms:.1,zcr:1500,onsetDensity:4,peakDb:6},Oa={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 Va(t,e,n={}){let r={...Ga,...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]=Oa[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 Eh(t,e){let n=Va(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
+ }`},Gh=[{shader:pn.bloomBrightpass},{shader:pn.bloomHBlur},{shader:pn.bloomVBlur},{shader:pn.bloomComposite}];function Bo(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 Oa(t,e){let n=Bo(t,t.VERTEX_SHADER,_a),r=Bo(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 zo(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 Ga(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 bn=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??fn}])}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(Oa(n,i.shader)),this.passUniforms.push(i.uniforms??{});for(let i=0;i<e.length-1;i++)this.fbos.push(Ga(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;hn(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)zo(n,l,c,m);for(let[c,m]of Object.entries(this.passUniforms[a]))zo(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:fn}]),this}setPostProcess(e){return this.setPipeline([{shader:e}])}clearPostProcess(){return this.setPostProcess(fn)}get element(){return this.glCanvas}toDesign(e,n){return it(this.glCanvas.getBoundingClientRect(),this.width,this.height,e,n)}viewport(){return st(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 _o=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 dn(this.last,this.width,this.height,this.background)}};function Uh(t,e,n=0,r=ae){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 Xh={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 Qh(t,e,n=0){let r=[];for(let o=0;o<t;o++){let i=n+o/t*ee;r.push(U(i)*e,q(i)*e)}return r}function Zh(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)*ee;o.push(U(a)*s,q(a)*s)}return o}function ep(t,e,n=.25,r=7){let o=[];for(let i=0;i<r;i++){let s=i/r*ee,a=e*(1-n+t.float()*n*2);o.push({x:U(s)*a,y:q(s)*a})}return Va(o)}function Va(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 tp(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 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 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 Go(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 ip(t,e,n){let r=Go(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 sp(t,e,n){let r=Go(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 ap(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 l=0;l<s&&o<r.data.length;l++)r.data[o++]=a}return r}function lp(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 Ha(t,e,n={}){let r=n.cell??1,o=n.x??0,i=n.y??0,s=n.z??0,a=n.transform??ae,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 Oo=class extends O{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 Ha(this.buffer,this.palette,{cell:r,x:o,y:i,z:this.z,transform:n}))e.push(s)}};var qa={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:[".#.","#.#",".##","..#","##."],".":[".",".",".",".","#"],",":["..","..","..",".#","#."],"!":["#","#","#",".","#"],"?":["##.","..#",".#.","...",".#."],":":[".","#",".","#","."],";":["..",".#","..",".#","#."],"-":["...","...","###","...","..."],"+":["...",".#.","###",".#.","..."],"=":["...","###","...","###","..."],"/":["..#","..#",".#.","#..","#.."],"'":["#","#",".",".","."],'"':["#.#","#.#","...","...","..."],"(":[".#","#.","#.","#.",".#"],")":["#.",".#",".#",".#","#."],"<":["..#",".#.","#..",".#.","..#"],">":["#..",".#.","..#",".#.","#.."],"%":["#.#","..#",".#.","#..","#.#"],"*":["...","#.#",".#.","#.#","..."],"#":["#.#","###","#.#","###","#.#"]},Vo={height:5,tracking:1,spaceWidth:3,glyphs:qa};function ja(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 qo(t,e){if(e===" "||e===`
174
+ `)return e;let n=e.toUpperCase();return t.glyphs[n]?n:t.glyphs[e]?e:t.glyphs["?"]?"?":" "}function jo(t,e){if(e===" ")return t.spaceWidth;let n=t.glyphs[e];return n?n[0].length:t.spaceWidth}function Et(t,e){let n=0;for(let r=0;r<e.length;r++)n+=jo(t,e[r].ch),r<e.length-1&&(n+=t.tracking);return n}function pp(t,e){return Et(t,[...e].map((n,r)=>({ch:qo(t,n),i:r})))}function Ua(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:qo(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&&Et(t,d)+f+Et(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,Et(t,m));let u=n.maxWidth??l,c=0;for(let m of s){let d=Et(t,m),h=n.align==="center"?Math.floor((u-d)/2):n.align==="right"?u-d:0;for(let p of m){let f=jo(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 Xa(t,e,n){if(n<=0)return t;let r=Math.floor(e*n);return r<0?0:r>t?t:r}function Ja(t,e,n={}){let r=n.cell??2,o=n.x??0,i=n.y??0,s=n.z??0,a=n.transform??ae,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 Ho=class extends O{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??Vo,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=ja(this.text,this.colorMap);return Ua(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=Xa(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 Ja(this.font,r,{cell:this.cell,x:i,y:s,z:this.z,color:this.color,transform:n,reveal:o}))e.push(a)}};function It(t,e,n=0){return{cols:t,rows:e,cells:new Array(t*e).fill(n)}}function Ya(t,e,n){return e<0||n<0||e>=t.cols||n>=t.rows?1:t.cells[n*t.cols+e]}function ze(t,e,n,r){e<0||n<0||e>=t.cols||n>=t.rows||(t.cells[n*t.cols+e]=r)}function Uo(t,e,n){let r=0;for(let o=-1;o<=1;o++)for(let i=-1;i<=1;i++)i===0&&o===0||Ya(t,e+i,n+o)===1&&r++;return r}function gp(t,e=32){let n=t.cells.map(r=>r===1?X.SOLID:X.EMPTY);return{cols:t.cols,rows:t.rows,tileSize:e,tiles:n}}function Ka(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 ct(t,e,n=0){return Ka(t,e,n)/4294967296}function xp(t,e,n,r=0){return Math.floor(ct(t,e,r)*n)}function Qa(t,e,n,r=0){return ct(t,e,r)<n}function vp(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++)Qa(l,a,o,i)&&s.push({x:l,y:a});return s}var Xo=t=>t*t*(3-2*t);function Za(t,e,n=0){let r=Math.floor(t),o=Math.floor(e),i=Xo(t-r),s=Xo(e-o),a=ct(r,o,n),l=ct(r+1,o,n),u=ct(r,o+1,n),c=ct(r+1,o+1,n),m=a+(l-a)*i,d=u+(c-u)*i;return m+(d-m)*s}function Jo(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*Za(t*l,e*l,n+m),c+=a,a*=s,l*=i;return c===0?0:u/c}function Sp(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=It(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);ze(u,m,c,d||t.chance(o)?1:0)}for(let c=0;c<i;c++){let m=It(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)){ze(m,h,d,1);continue}let p=Uo(u,h,d),f=u.cells[d*n+h]===1;ze(m,h,d,(f?p>=a:p>=s)?1:0)}u=m}return u}function Yo(t,e){let n=e.scale??.08,r=e.seed??0,o=Jo(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=Z(i,e.minRow??-1/0,e.maxRow??1/0)),i}function Rp(t,e,n){let r=new Array(e);for(let o=0;o<e;o++)r[o]=Yo(t+o,n);return r}function Pp(t,e,n){return e>=Yo(t,n)}function Ko(t){return{x:Math.floor(t.x+t.w/2),y:Math.floor(t.y+t.h/2)}}function el(t,e){return t.x<=e.x+e.w&&t.x+t.w>=e.x&&t.y<=e.y+e.h&&t.y+t.h>=e.y}function tl(t,e){for(let n=e.y;n<e.y+e.h;n++)for(let r=e.x;r<e.x+e.w;r++)ze(t,r,n,0)}function Qo(t,e,n,r){for(let o=Math.min(e,n);o<=Math.max(e,n);o++)ze(t,o,r,0)}function Zo(t,e,n,r){for(let o=Math.min(e,n);o<=Math.max(e,n);o++)ze(t,r,o,0)}function Ip(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=It(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=>el(f,g))){if(tl(l,f),u.length>0){let g=Ko(u[u.length-1]),k=Ko(f);t.chance(.5)?(Qo(l,g.x,k.x,g.y),Zo(l,g.y,k.y,k.x)):(Zo(l,g.y,k.y,g.x),Qo(l,g.x,k.x,k.y))}u.push(f)}}return{rooms:u,grid:l}}var be=44100;function ti(t,e=be){let n=Math.max(0,Math.round(t*e));return{sampleRate:e,left:new Float32Array(n),right:new Float32Array(n)}}function Fp(t){return t.left.length}function Ap(t){return t.left.length/t.sampleRate}function nl(t){let n=(Z(t,-1,1)+1)*.5*(Math.PI/2);return{l:U(n),r:q(n)}}function ni(t,e,n,r=1,o=0){let{l:i,r:s}=nl(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 rl(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 ei(t){return t/Math.sqrt(1+t*t)}function ri(t){let{left:e,right:n}=t;for(let r=0;r<e.length;r++)e[r]=ei(e[r]),n[r]=ei(n[r])}function oi(t,e=.89){let n=rl(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 Wp(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=Z(e[h],-1,1),f=Z(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 Bp(t){let e=2166136261;for(let n=0;n<t.length;n++){let r=Z(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 ol(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 ii(t,e,n,r){switch(t){case"sine":return q(ee*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 yn(t,e={}){let n=ol(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?si(n.lowpass,r):1,I=n.highpass>0?1-si(n.highpass,r):0,x=r*.5;for(let b=0;b<l;b++){let w=b*c,C=il(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(ee*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(ee*n.vibratoFreq*w))),n.fm>0&&(S+=n.fm*q(ee*n.fmFreq*w)),S<0?S=0:S>x&&(S=x),m+=S*c,m-=Math.floor(m);let T=ii(n.wave,m,n.duty,o);n.detune!==0&&(d+=S*p*c,d-=Math.floor(d),T=(T+ii(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(ee*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)*De(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 si(t,e){let n=ee*t*(1/e);return n/(n+1)}function il(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 sl={C:0,"C#":1,Db:1,D:2,"D#":3,Eb:3,E:4,Fb:4,"E#":5,F:5,"F#":6,Gb:6,G:7,"G#":8,Ab:8,A:9,"A#":10,Bb:10,B:11,Cb:11,"B#":0},al=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];function me(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=sl[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 jp(t){let e=(t%12+12)%12,n=Math.floor(t/12)-1;return al[e]+n}function ll(t,e=440){return e*fe((t-69)/12)}function ai(t,e=440){return ll(typeof t=="number"?t:me(t),e)}var li={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 Qn(t,e="major",n=1){let r=li[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 ui(t,e="major"){let n=(t%12+12)%12;return new Set(li[e].map(r=>(n+r)%12))}function ul(t,e,n,r=3){let o=(n%7+7)%7,i=Qn(t,e,3),s=[];for(let a=0;a<r;a++)s.push(i[o+a*2]);return s}var cl={i:0,ii:1,iii:2,iv:3,v:4,vi:5,vii:6};function mt(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=cl[o[1].toLowerCase()];if(i===void 0)throw new Error(`bad roman numeral: ${JSON.stringify(r)}`);return ul(t,e,i,o[2]?4:3)})}function Up(t,e){return t.map(n=>n+e)}function Zn(t){return t.length<2?t.slice():[t[0]-12,...t.slice(1)].sort((e,n)=>e-n)}function Lt(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 ml=[1116,1188,1277,1356,1422,1491,1557,1617],dl=[556,441,341,225],hl=23,pl=.015,er=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}},tr=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 ci(t,e,n,r){let o=t/44100,i=ml.map(a=>new er(Math.round((a+r)*o),e,n)),s=dl.map(a=>new tr(Math.round((a+r)*o),.5));return{combs:i,aps:s}}function mi(t,e={}){let n=Z(e.wet??.25,0,1),r=Z(e.roomSize??.7,0,1),o=Z(e.damp??.5,0,1)*.4,i=.7+r*.28,s=t.sampleRate,a=ci(s,i,o,0),l=ci(s,i,o,hl),u=t.left.length;for(let c=0;c<u;c++){let m=(t.left[c]+t.right[c])*pl,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 fl(t){let e=0;for(let n of t)e+=n.beats;return e}function bl(t){let e=0;for(let n of t.sequence)e+=fl(t.patterns[n]??[]);return e}function gl(t){let e=0;for(let n of t.tracks)e=Math.max(e,bl(n));return e}function nr(t){return gl(t)*60/t.bpm}function hi(t,e={}){let n=e.sampleRate??be,r=t.a4??440,o=60/t.bpm,i=t.tailSec??2,s=nr(t)+i,a=ti(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 Q={...m.instrument,freq:ai(te,r),sustain:$,volume:(m.instrument.volume??.5)*S,...K!==void 0?{lowpass:K}:{}},oe=yn(Q,{rng:f,sampleRate:n});ni(a,oe,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;vl(a,d,m)}return t.reverb&&mi(a,t.reverb),t.master&&xl(a,t.master),t.master?.compress&&yl(a,t.master.compress),ri(a),oi(a,e.normalizePeak??.89),a}function yl(t,e){let n=Math.max(0,Math.min(1,e)),r=t.sampleRate,o=di(-20),i=2+n*3,s=Ye(-1/(r*.005)),a=Ye(-1/(r*.15)),l=di(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*De(k,1/i)/u}let g=f*l;c[d]*=g,m[d]*=g}}function di(t){return fe(t/6.020599913)}function xl(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=ee*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 vl(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 wl={master:.7,music:.6,sfx:.8,muted:!1},rr=class{_ctx=null;master=null;musicGain=null;sfxGain=null;vol={...wl};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=yn(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=hi(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=nr(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 rr;function or(t){let e=t<0?-t:t;return e<1e-12?-1/0:20*jt(e)}function $t(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 pi(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 kl(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 Sl(t){let e=1;for(;e*2<=t;)e*=2;return e}function Cl(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=-ee/r,i=U(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 Nt(t){let e=Sl(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*U(ee*s/(e-1));n[s]=t[s]*a}Cl(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 Tl(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=Nt(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 fi(t,e=1024,n=512){let r=[],o=null;for(let i=0;i+e<=t.length;i+=n){let s=Nt(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 Ml(t,e=be){let r=fi(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 Rl(t,e=be){let r=fi(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 bi(t){let e=$t(t);return e<1e-9?0:or(pi(t))-or(e)}function gi(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=Nt(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 Ft(t,e=be){return{durationSec:t.length/e,rms:$t(t),peakDb:or(pi(t)),centroidHz:Tl(t,e),zcr:kl(t,e),onsetDensity:Ml(t,e),tempoBpm:Rl(t,e)}}var Pl={"":[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 Me(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=Pl[a];if(!l)throw new Error(`unknown chord quality ${JSON.stringify(a)} in ${JSON.stringify(t)}`);let u=me(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=me(d+(e-1));for(;h>=c[0];)h-=12;c.unshift(h)}}return c}function xn(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 pf(t,e=4){return t.map(n=>Me(n,e))}function yi(t){try{return typeof t=="number"?t:me(t)}catch{return null}}function Dl(t){return t.pitch===null||t.pitch===void 0?[]:Array.isArray(t.pitch)?t.pitch:[t.pitch]}function gf(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?ui(yi(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 Dl(p)){let g=yi(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 yf(t){return t.length===0?!1:(r=>r.trim().toLowerCase().replace(/7$/,""))(t[t.length-1])==="i"}var El={tempoBpm:20,centroidHz:1200,rms:.1,zcr:1500,onsetDensity:4,peakDb:6},Il={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 Ll(t,e,n={}){let r={...El,...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]=Il[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 vf(t,e){let n=Ll(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 Ah(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 Ha(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*ot(s/i))}}}function qa(t,e=400){return ee(t/e,-1,1)}function Nh(t,e,n=600,r=1){let o=Math.sqrt(t*t+e*e);return o>n?{gain:0,pan:0,audible:!1}:{gain:Ha("inverse",o,n*.15,n,r),pan:qa(t,n*.7),audible:!0}}function Lh(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 $h(t,e=-12){return t?pe(e/6.0206):1}function ja(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=vt(n);return o<1e-9?0:vt(r)/o}var Bh={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 Ce(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 _h(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=wt(n),o=Io(n),i=Fo(n),s=ja(t),a=i.lowMid,u=i.high+i.air,l=i.sub+i.bass,c={loudness:Ce(r.rms,e.rms),headroom:r.peakDb<=-.5?r.peakDb>=-3?1:Ce(r.peakDb,[-3,-.5]):0,dynamics:Ce(o,e.crestDb),width:Ce(s,e.width),brightness:Ce(r.centroidHz,e.centroid),density:Ce(r.onsetDensity,e.onsets),tempo:Ce(r.tempoBpm,e.tempo),lowEnd:Ce(l,[.12,.7]),clarity:Ce(a,[0,e.maxMud??.34]),smoothness:Ce(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 No(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 Ua(t,e,n=1){return Array.from({length:e},()=>P(t,1,n))}function Xa(){let t=Ze(me("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:[Ua("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=>No([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 Ja(){let t=me("C4"),e=yt(Ze(t,"major",["IV7","iii7","ii7","I7"]).map(En)),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 Ya(){let t=me("A3"),e=yt(Ze(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 Ka(){let t=me("D3"),e=yt(Ze(t,"minor",["i","VI","III","VII","VI","VII","i","i"])),n=Pn(me("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=>No([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 Qa(){let t=me("C4"),e=Ze(t,"major",["ii7","V7","I7","vi7"]),n=yt(e.map(En)),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 Za=[{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:Xa},{id:"lofi",name:"Lo-fi Beats",description:"Swung, dusty jazz sevenths on a Rhodes with warm bass, brushed drums and vinyl crackle.",make:Ja},{id:"piano",name:"Melancholic Piano",description:"Slow, sad A-minor piano with space and rubato over a string bed in a big room.",make:Ya},{id:"orchestral",name:"Epic Orchestral",description:"Uplifting D-minor with a soaring brass theme, arpeggiated strings, choir, timpani and glockenspiel.",make:Ka},{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:Qa}];function Hh(t){return Za.find(e=>e.id===t)}var Lo=["sine","triangle","saw","square","noise"],Ln=new Set;function rn(t,e){Ln.has(t)||(Ln.add(t),console.warn(`[hayao] specFromZzfx: ${t} ${e}`))}function Uh(){Ln.clear()}function Xh(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(Lo.length-1,Math.round(a)));if(w.wave=Lo[S],Math.round(a)===3&&rn("shape=3 (tan)","has no hayao wave; approximated as a hard square."),u!==1&&(w.shapeCurve=u),n!==0&&rn("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*ot(D/r),w.pitchJumpTime=d):rn("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&&(rn("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 $n(t,e=2){return t.map((n,r)=>{let o=Te(n,e),i=o[0],s=o[1]??i+3,a=o[2]??i+7,u=Te(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 sn(t,e=4,n="F4",r=.66){let o=me(n);return t.map((i,s)=>{let a=nn(Te(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 eu(t,e=4,n="F4",r=.6){let o=me(n);return t.map(i=>[g(nn(Te(i,e),o),4,r)])}var tu=()=>[g("C6",1,.55),g("C6",.5,.35),g("C6",.5,.5),g("C6",1,.55),g("C6",.5,.35),g("C6",.5,.5)],nu=()=>[N(1),g("C6",1,.5),N(1),g("C6",1,.5)];function kt(t=.42,e=8){return{name:"ride",instrument:$.ride,gain:t,pan:.12,patterns:[tu()],sequence:Array(e).fill(0)}}function Wn(t=.4,e=8){return{name:"hat",instrument:{...$.hat,highpass:5e3,volume:.2},gain:t,pan:-.1,patterns:[nu()],sequence:Array(e).fill(0)}}function an(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 on=["F5","Gb5","Bb5","Ab5"];function ru(){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)],...$n(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:sn(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(on[0],.5,.85),g(on[1],.5,.7),g(on[2],1,.9),g(on[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,kt(.42),Wn(.35)],swing:.6,humanize:.32,velBrightness:.6,reverb:{wet:.17,roomSize:.6,damp:.5},master:{lowCut:.24,presence:.14,air:.04,compress:.45}}}function ou(){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=Te(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:eu(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:[an(.3),e,n,r,o,kt(.24)],swing:.5,humanize:.4,velBrightness:.6,reverb:{wet:.34,roomSize:.85,damp:.55},master:{lowCut:.24,presence:.16,air:.05,compress:.65}}}function iu(){let t=["Cm9","Cm9","Fm9","Dm7b5","G7alt","Cm9","Ab13","G7alt"],e={name:"bass",instrument:{...$.uprightBass,volume:.48},gain:.68,patterns:$n(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:sn(t,4,"Eb4",.5),sequence:[0,1,2,3,4,5,6,7]};return{bpm:96,tracks:[an(.28),e,r,n,kt(.3),Wn(.28)],swing:.62,humanize:.34,velBrightness:.6,reverb:{wet:.22,roomSize:.65,damp:.5},master:{lowCut:.24,presence:.13,air:.04,compress:.45}}}function su(){let t={name:"bass",instrument:{...$.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=>nn(Te(a,4),me("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 au(){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=Te(s,2)[0],l=Te(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:sn(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:[an(.32),e,n,r,o,i,kt(.28),Wn(.24)],swing:.56,humanize:.3,velBrightness:.62,reverb:{wet:.26,roomSize:.72,damp:.55},master:{lowCut:.24,presence:.14,air:.04,compress:.45}}}function uu(){let t=["Dm7","G13","Cmaj9","A7b9","Dm7","G7","Cmaj9","Cmaj9"],e={name:"bass",instrument:{...$.uprightBass,volume:.5},gain:.66,patterns:$n(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:sn(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:[an(.3),e,n,r,o,kt(.26)],swing:.56,humanize:.36,velBrightness:.6,reverb:{wet:.3,roomSize:.8,damp:.5},master:{lowCut:.38,presence:.28,air:.09,compress:.65}}}var lu={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:ru},{id:"rain-avenue",title:"Rain on the Avenue",intent:"A smoky, slow torch ballad. Muted trumpet in the rain.",make:ou},{id:"stakeout",title:"Stakeout",intent:"Minimal, nervous cool-jazz. Watching, waiting, unresolved.",make:iu},{id:"the-chase",title:"The Chase",intent:"Driving F-minor funk \u2014 clav, horn stabs, a hard pulse.",make:su},{id:"smoke-mirrors",title:"Smoke & Mirrors",intent:"Slinky half-time noir; altered colours, nothing as it seems.",make:au},{id:"last-call",title:"Last Call",intent:"The warm closer \u2014 a ii\u2013V\u2013I that finally lands, the motif resolved.",make:uu}]};function Zh(t){return lu.tracks.find(e=>e.id===t)}var un=null,$o="hayao-overlay-style",cu=`
177
+ `):" (all features within tolerance)")}function Cf(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 $l(t,e,n=1,r=1e4,o=1){let i=Math.max(1e-6,n);switch(t){case"linear":{let s=Z(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*bt(s/i))}}}function Nl(t,e=400){return Z(t/e,-1,1)}function Tf(t,e,n=600,r=1){let o=Math.sqrt(t*t+e*e);return o>n?{gain:0,pan:0,audible:!1}:{gain:$l("inverse",o,n*.15,n,r),pan:Nl(t,n*.7),audible:!0}}function Mf(t,e){let n={};for(let r of t){let o=Math.max(1e-6,r.full-r.fadeIn),i=Z((e-r.fadeIn)/o,0,1)*(r.maxGain??1);n[r.name]=i}return n}function Rf(t,e=-12){return t?fe(e/6.0206):1}function Fl(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=$t(n);return o<1e-9?0:$t(r)/o}var Ef={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 Re(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 If(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=Ft(n),o=bi(n),i=gi(n),s=Fl(t),a=i.lowMid,l=i.high+i.air,u=i.sub+i.bass,c={loudness:Re(r.rms,e.rms),headroom:r.peakDb<=-.5?r.peakDb>=-3?1:Re(r.peakDb,[-3,-.5]):0,dynamics:Re(o,e.crestDb),width:Re(s,e.width),brightness:Re(r.centroidHz,e.centroid),density:Re(r.onsetDensity,e.onsets),tempo:Re(r.tempoBpm,e.tempo),lowEnd:Re(u,[.12,.7]),clarity:Re(a,[0,e.maxMud??.34]),smoothness:Re(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 xi(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 Al(t,e,n=1){return Array.from({length:e},()=>P(t,1,n))}function Wl(){let t=mt(me("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:[Al("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=>xi([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 Bl(){let t=me("C4"),e=Lt(mt(t,"major",["IV7","iii7","ii7","I7"]).map(Zn)),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 zl(){let t=me("A3"),e=Lt(mt(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 _l(){let t=me("D3"),e=Lt(mt(t,"minor",["i","VI","III","VII","VI","VII","i","i"])),n=Qn(me("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=>xi([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 Ol(){let t=me("C4"),e=mt(t,"major",["ii7","V7","I7","vi7"]),n=Lt(e.map(Zn)),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 Gl=[{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:Wl},{id:"lofi",name:"Lo-fi Beats",description:"Swung, dusty jazz sevenths on a Rhodes with warm bass, brushed drums and vinyl crackle.",make:Bl},{id:"piano",name:"Melancholic Piano",description:"Slow, sad A-minor piano with space and rubato over a string bed in a big room.",make:zl},{id:"orchestral",name:"Epic Orchestral",description:"Uplifting D-minor with a soaring brass theme, arpeggiated strings, choir, timpani and glockenspiel.",make:_l},{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:Ol}];function Ff(t){return Gl.find(e=>e.id===t)}var vi=["sine","triangle","saw","square","noise"],ir=new Set;function vn(t,e){ir.has(t)||(ir.add(t),console.warn(`[hayao] specFromZzfx: ${t} ${e}`))}function Bf(){ir.clear()}function zf(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(vi.length-1,Math.round(a)));if(w.wave=vi[C],Math.round(a)===3&&vn("shape=3 (tan)","has no hayao wave; approximated as a hard square."),l!==1&&(w.shapeCurve=l),n!==0&&vn("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*bt(E/r),w.pitchJumpTime=d):vn("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&&(vn("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 sr(t,e=2){return t.map((n,r)=>{let o=Me(n,e),i=o[0],s=o[1]??i+3,a=o[2]??i+7,l=Me(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 kn(t,e=4,n="F4",r=.66){let o=me(n);return t.map((i,s)=>{let a=xn(Me(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 Vl(t,e=4,n="F4",r=.6){let o=me(n);return t.map(i=>[y(xn(Me(i,e),o),4,r)])}var Hl=()=>[y("C6",1,.55),y("C6",.5,.35),y("C6",.5,.5),y("C6",1,.55),y("C6",.5,.35),y("C6",.5,.5)],ql=()=>[F(1),y("C6",1,.5),F(1),y("C6",1,.5)];function At(t=.42,e=8){return{name:"ride",instrument:W.ride,gain:t,pan:.12,patterns:[Hl()],sequence:Array(e).fill(0)}}function ar(t=.4,e=8){return{name:"hat",instrument:{...W.hat,highpass:5e3,volume:.2},gain:t,pan:-.1,patterns:[ql()],sequence:Array(e).fill(0)}}function Sn(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 wn=["F5","Gb5","Bb5","Ab5"];function jl(){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)],...sr(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:kn(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(wn[0],.5,.85),y(wn[1],.5,.7),y(wn[2],1,.9),y(wn[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,At(.42),ar(.35)],swing:.6,humanize:.32,velBrightness:.6,reverb:{wet:.17,roomSize:.6,damp:.5},master:{lowCut:.24,presence:.14,air:.04,compress:.45}}}function Ul(){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=Me(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:Vl(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:[Sn(.3),e,n,r,o,At(.24)],swing:.5,humanize:.4,velBrightness:.6,reverb:{wet:.34,roomSize:.85,damp:.55},master:{lowCut:.24,presence:.16,air:.05,compress:.65}}}function Xl(){let t=["Cm9","Cm9","Fm9","Dm7b5","G7alt","Cm9","Ab13","G7alt"],e={name:"bass",instrument:{...W.uprightBass,volume:.48},gain:.68,patterns:sr(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:kn(t,4,"Eb4",.5),sequence:[0,1,2,3,4,5,6,7]};return{bpm:96,tracks:[Sn(.28),e,r,n,At(.3),ar(.28)],swing:.62,humanize:.34,velBrightness:.6,reverb:{wet:.22,roomSize:.65,damp:.5},master:{lowCut:.24,presence:.13,air:.04,compress:.45}}}function Jl(){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=>xn(Me(a,4),me("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 Yl(){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=Me(s,2)[0],u=Me(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:kn(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:[Sn(.32),e,n,r,o,i,At(.28),ar(.24)],swing:.56,humanize:.3,velBrightness:.62,reverb:{wet:.26,roomSize:.72,damp:.55},master:{lowCut:.24,presence:.14,air:.04,compress:.45}}}function Kl(){let t=["Dm7","G13","Cmaj9","A7b9","Dm7","G7","Cmaj9","Cmaj9"],e={name:"bass",instrument:{...W.uprightBass,volume:.5},gain:.66,patterns:sr(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:kn(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:[Sn(.3),e,n,r,o,At(.26)],swing:.56,humanize:.36,velBrightness:.6,reverb:{wet:.3,roomSize:.8,damp:.5},master:{lowCut:.38,presence:.28,air:.09,compress:.65}}}var Ql={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:jl},{id:"rain-avenue",title:"Rain on the Avenue",intent:"A smoky, slow torch ballad. Muted trumpet in the rain.",make:Ul},{id:"stakeout",title:"Stakeout",intent:"Minimal, nervous cool-jazz. Watching, waiting, unresolved.",make:Xl},{id:"the-chase",title:"The Chase",intent:"Driving F-minor funk \u2014 clav, horn stabs, a hard pulse.",make:Jl},{id:"smoke-mirrors",title:"Smoke & Mirrors",intent:"Slinky half-time noir; altered colours, nothing as it seems.",make:Yl},{id:"last-call",title:"Last Call",intent:"The warm closer \u2014 a ii\u2013V\u2013I that finally lands, the motif resolved.",make:Kl}]};function Hf(t){return Ql.tracks.find(e=>e.id===t)}var Cn=null,wi="hayao-overlay-style",Zl=`
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 Jr(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 mu(){if(typeof document>"u"||document.getElementById($o))return;let t=document.createElement("style");t.id=$o,t.textContent=cu,document.head.appendChild(t)}var Wo=null;function ln(t){Wo=t}var zn=null;function Bn(t){zn=t}function zo(t){if(typeof document>"u")return{close(){},element:null};mu(),cn(),zn?.("show",t.title);let e=document.createElement("div");e.className=`hy-scrim${t.dim===!1?"":" dim"}${t.className?" "+t.className:""}`;let n=document.createElement("div");if(n.className="hy-card",t.title){let l=document.createElement("h1");l.textContent=t.title,n.appendChild(l)}if(t.body){let l=document.createElement("div");l.className="hy-body",l.innerHTML=t.body,n.appendChild(l)}let r=t.actions??[],o=Math.max(0,r.findIndex(l=>l.primary));o<0&&(o=0);let i=[];if(r.length){let l=document.createElement("div");l.className="hy-menu",r.forEach((c,m)=>{let d=document.createElement("button");d.className=`hy-item${c.primary?" primary":""}`,d.textContent=c.label,d.addEventListener("click",()=>c.onSelect()),d.addEventListener("mouseenter",()=>s(m)),l.appendChild(d),i.push(d)}),n.appendChild(l)}function s(l){o=(l+i.length)%i.length,i.forEach((c,m)=>c.classList.toggle("sel",m===o))}i.length&&s(o);let a=l=>{i.length&&(l.code==="ArrowDown"?(s(o+1),l.preventDefault()):l.code==="ArrowUp"?(s(o-1),l.preventDefault()):(l.code==="Enter"||l.code==="Space")&&(r[o]?.onSelect(),l.preventDefault()))};document.addEventListener("keydown",a),e.appendChild(n),(Wo??document.body).appendChild(e);let u={element:e,close(){document.removeEventListener("keydown",a),e.remove(),un===u&&(un=null,zn?.("hide",t.title))}};return un=u,u}function cn(){un?.close()}var Bo="hayao.settings.v1",_o={master:.7,music:.6,sfx:.8,muted:!1,colorblind:!1,reducedMotion:!1},_n=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(){Be.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(Bo);if(e)return{..._o,...JSON.parse(e)}}catch{}return{..._o}}save(){try{localStorage.setItem(Bo,JSON.stringify(this.state))}catch{}}},Ae=new _n;function Go(){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,Be.blip(440),this.opts.onPause?.(!0),this.render())}resume(){this.paused&&(this.paused=!1,cn(),this.opts.onPause?.(!1))}render(){let e=Ae.get(),n=(r,o)=>`${r}: ${Math.round(o*100)}`;zo({title:this.opts.title??"Paused",body:`<div style="font-size:13px;text-align:left;line-height:1.9">${n("Master",e.master)} \xB7 ${n("Music",e.music)} \xB7 ${n("Sfx",e.sfx)}<br/><span style="opacity:.7">Use the menu, or keys: M mute \xB7 F fullscreen</span></div>`,actions:[{label:"Resume",primary:!0,onSelect:()=>this.resume()},{label:e.muted?"Unmute (M)":"Mute (M)",onSelect:()=>{Ae.set({muted:!Ae.get().muted}),this.render()}},{label:"Music \u2212/+",onSelect:()=>{let r=Math.min(1,Ae.get().music+.1)%1.05;Ae.set({music:r>1?0:r}),this.render()}},{label:"Fullscreen (F)",onSelect:()=>Go()},...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 Oo="hayao-touch-style",du=`
187
+ `;function eu(){if(typeof document>"u"||document.getElementById(wi))return;let t=document.createElement("style");t.id=wi,t.textContent=Zl,document.head.appendChild(t)}var ki=null;function Tn(t){ki=t}var lr=null;function ur(t){lr=t}function Si(t){if(typeof document>"u")return{close(){},element:null};eu(),Mn(),lr?.("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),(ki??document.body).appendChild(e);let l={element:e,close(){document.removeEventListener("keydown",a),e.remove(),Cn===l&&(Cn=null,lr?.("hide",t.title))}};return Cn=l,l}function Mn(){Cn?.close()}var Ci="hayao.settings.v1",Ti={master:.7,music:.6,sfx:.8,muted:!1,colorblind:!1,reducedMotion:!1},cr=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(Ci);if(e)return{...Ti,...JSON.parse(e)}}catch{}return{...Ti}}save(){try{localStorage.setItem(Ci,JSON.stringify(this.state))}catch{}}},_e=new cr;function Mi(){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 Rn=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,Mn(),this.opts.onPause?.(!1))}render(){let e=_e.get(),n=(r,o)=>`${r}: ${Math.round(o*100)}`;Si({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:()=>{_e.set({muted:!_e.get().muted}),this.render()}},{label:"Music \u2212/+",onSelect:()=>{let r=Math.min(1,_e.get().music+.1)%1.05;_e.set({music:r>1?0:r}),this.render()}},{label:"Fullscreen (F)",onSelect:()=>Mi()},...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),Mn()}};var Ri="hayao-touch-style",tu=`
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 Jr(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 hu(){if(typeof document>"u"||document.getElementById(Oo))return;let t=document.createElement("style");t.id=Oo,t.textContent=du,document.head.appendChild(t)}function pu(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 Vo=class{handle;root;disposers=[];owned=new Set;constructor(e,n){this.handle=e,hu();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=Ho(n.left),s=Ho(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=pu(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`,Ve(v,a)),x.set(`${s}y`,Ve(M,a)),x.set(`${s}angle`,v===0&&M===0?0:Rr(Ft(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 Ho(t){if(t)return Array.isArray(t)?{dirs:t}:t}var fu=[0,8,2,10,12,4,14,6,3,11,1,9,15,7,13,5],bu=t=>t*t*(3-2*t),Gn=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=Ie(n.from,n.to,bu(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++)(fu[(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})}},qo=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 hp(t,e={}){let n=new Gn({z:1e4,...e});return t.addChild(n)}function pp(t,e={}){return{name:e.name??"wipe",enter:()=>t.wipe(e),until:()=>!t.busy}}var fp=(t,e)=>({x:0,y:0,w:t,h:e});function et(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 gp(t,e={}){let n=et(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 jo(t,e){let n=t(),r=[];for(let o=0;o<e.frames.length;o++)n.step(ut(e,o),lt(e,o)),r.push(n.hash());return{finalHash:n.hash(),hashes:r}}function gu(t,e){let n=jo(t,e),r=jo(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 xp(t,e){let n=gu(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 wp(t,e,n){let r=t();for(let u=0;u<n;u++)r.step(ut(e,u),lt(e,u));let o=r.snapshot(),i=t();i.restore(o);for(let u=n;u<e.frames.length;u++)r.step(ut(e,u),lt(e,u)),i.step(ut(e,u),lt(e,u));let s=r.hash(),a=i.hash();return{ok:s===a,hashA:s,hashB:a}}function Sp(t,e){return{actions:t,frames:e}}function Mp(t){return{actions:[],frames:t}}function Tp(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 Cp(t,e,n=[]){for(let r=0;r<e;r++)t.step(n)}function Uo(){return typeof location<"u"&&new URLSearchParams(location.search).has("capture")}function Xo(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 yu(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 Ep(t,e,n){let r=0;for(let o of yu(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 Ip(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 Fp(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 Mt=t=>[...new Set(t)];function vu(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 Lp(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)`),Mt(r)}function xu(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 Mt(u)}function dn(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 St(t,e){let n=dn(t),r=dn(e),o=Math.max(n,r),i=Math.min(n,r);return(o+.05)/(i+.05)}var wu=t=>t.kind==="text"?void 0:t.fill;function ku(t,e,n,r={}){let o=r.minBackgroundContrast??3,i=r.minSalienceFactor??1.15,s=[],a=St(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=wu(l);c&&c!=="none"&&c!==e&&u.push(St(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 Mt(s)}function $p(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 Mt(r)}function Su(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 Mt(i)}function Mu(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 Wp(t,e={}){let n=[],r=[],o=t.background??e.background??"#ffffff";if(t.forgiveness&&n.push({gate:"forgiveness",issues:vu(t.forgiveness)}),t.feedback&&n.push({gate:"feedback",issues:xu(t.feedback.contract,t.feedback.events)}),t.avatarFill&&(e.commands?n.push({gate:"salience",issues:ku(e.commands,t.avatarFill,o)}):r.push("salience (no rendered frame)")),t.scrolls)if(e.camSamples&&e.camSamples.length>=3){let i=Su(e.camSamples,{dt:e.dt});e.targetSamples&&i.push(...Mu(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 Tu(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 Jo(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 Yo=(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,Ko=(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,Cu=t=>t.transient===!0,Qo=t=>{let e=t.fill;if(!(!e||e==="none")&&!t.gradient)return e};function _p(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=>!Cu(c)),l=[];for(let c of u)c.kind==="text"&&c.text.trim().length&&l.push(Tu(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=Jo(b);if(!v||!Ko(v,c))continue;let M=b.opacity===void 0||b.opacity>=.6,x=b.z??0;M&&x<=m&&x>=h&&(h=x,p=Qo(b)??p),x>m&&(b.opacity===void 0||b.opacity>=.9)&&a.push(`text "${Tt(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=Jo(b);v&&Yo(d,v)&&!Ko(v,c)&&a.push(`text "${Tt(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=St(b,p??o);v<s&&a.push(`text "${Tt(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=Qo(c);if(!m)continue;let d=St(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++)Yo(l[c],l[m])&&a.push(`texts "${Tt(l[c].cmd.text)}" and "${Tt(l[m].cmd.text)}" overlap`);return Zo(a)}var Tt=t=>t.length>28?t.slice(0,25)+"\u2026":t,Zo=t=>[...new Set(t)];function Ru(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 Gp(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(Ru)].some(o)||r.push(i)}return Zo(r)}function Vp(t,e){let n=[t.probe()];for(let r of e)t.step(r),n.push(t.probe());return n}function Hp(t,e){for(let n=0;n<t.length;n++)if(e(t[n]))return n;return-1}function qp(t,e){return t.map(n=>n[e])}function jp(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 Up(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 Xp(t){return t.length===0?0:t.filter(e=>e.length>0).length/t.length}function Jp(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 Pu=t=>[...new Set(t)];function Eu(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 Du(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=Eu(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`),Pu(a)}function Kp(t,e={}){let n=Du(t,e);if(n.length)throw new Error(`hayao: difficulty ramp is ill-shaped \u2014 ${n[0]}`)}function ef(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 On(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 ei(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 sf(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=wt(On(t)),d=ei(t.left,r,s,a,a/2),h=ei(t.right,r,s,a,a/2),p=On(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=xt(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 Q=0;Q<k;Q++)F+=R[T*k+Q]??0;let O=F>1e-6?20*At(F):-120,A=Math.max(0,Math.min(1,(O+60)/60));if(A<.03)continue;let U=i+S*M,X=i*3+a*2+u-(T+1)*x,te=Iu(A);C+=`<rect x="${U.toFixed(1)}" y="${X.toFixed(1)}" width="${(M+.6).toFixed(1)}" height="${(x+.6).toFixed(1)}" fill="${te}"/>`}}let I=Fu(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">${Au(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 Iu(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 Fu(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 Au(t){return t.replace(/[<>&]/g,e=>e==="<"?"&lt;":e===">"?"&gt;":"&amp;")}function af(t,e){let n=wt(On(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 hn=class{rng;clock;input=new Ot;events=new Lt;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 ce(this.seed),this.clock=new Nt(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 nu(){if(typeof document>"u"||document.getElementById(Ri))return;let t=document.createElement("style");t.id=Ri,t.textContent=tu,document.head.appendChild(t)}function ru(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 Pi=class{handle;root;disposers=[];owned=new Set;constructor(e,n){this.handle=e,nu();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=Di(n.left),s=Di(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=ru(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`,tt(g,a)),v.set(`${s}y`,tt(k,a)),v.set(`${s}angle`,g===0&&k===0?0:go($e(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 Di(t){if(t)return Array.isArray(t)?{dirs:t}:t}var ou=[0,8,2,10,12,4,14,6,3,11,1,9,15,7,13,5],iu=t=>t*t*(3-2*t),mr=class extends O{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=Z(n.elapsed/n.dur,0,1);if(this.coverage=Ne(n.from,n.to,iu(r)),r>=1){this.coverage=n.to;let o=n.onEnd;this.queue.shift(),o?.()}}draw(e,n){let r=this.coverage;if(r<=0)return;let o=this.z;if(this.kind==="fade"){e.push({kind:"rect",x:0,y:0,w:this.screenW,h:this.screenH,fill:this.color,opacity:r,transform:ae,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:ae,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++)(ou[(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:ae,z:o})}},Ei=class extends O{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 o0(t,e={}){let n=new mr({z:1e4,...e});return t.addChild(n)}function i0(t,e={}){return{name:e.name??"wipe",enter:()=>t.wipe(e),until:()=>!t.busy}}var s0=(t,e)=>({x:0,y:0,w:t,h:e});function dt(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 l0(t,e={}){let n=dt(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 Ii(t,e){let n=t(),r=[];for(let o=0;o<e.frames.length;o++)n.step(St(e,o),Ct(e,o)),r.push(n.hash());return{finalHash:n.hash(),hashes:r}}function su(t,e){let n=Ii(t,e),r=Ii(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 m0(t,e){let n=su(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 d0(t,e,n){let r=t();for(let l=0;l<n;l++)r.step(St(e,l),Ct(e,l));let o=r.snapshot(),i=t();i.restore(o);for(let l=n;l<e.frames.length;l++)r.step(St(e,l),Ct(e,l)),i.step(St(e,l),Ct(e,l));let s=r.hash(),a=i.hash();return{ok:s===a,hashA:s,hashB:a}}function p0(t,e){return{actions:t,frames:e}}function f0(t){return{actions:[],frames:t}}function b0(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 g0(t,e,n=[]){for(let r=0;r<e;r++)t.step(n)}function Li(){return typeof location<"u"&&new URLSearchParams(location.search).has("capture")}function $i(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 au(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 v0(t,e,n){let r=0;for(let o of au(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 k0(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 S0(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 Bt=t=>[...new Set(t)];function lu(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 D0(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)`),Bt(r)}function uu(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 Bt(l)}function Oe(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:De((i+.055)/1.055,2.4)};return .2126*r(n>>16&255)+.7152*r(n>>8&255)+.0722*r(n&255)}function Wt(t,e){let n=Oe(t),r=Oe(e),o=Math.max(n,r),i=Math.min(n,r);return(o+.05)/(i+.05)}var cu=t=>t.kind==="text"?void 0:t.fill;function mu(t,e,n,r={}){let o=r.minBackgroundContrast??3,i=r.minSalienceFactor??1.15,s=[],a=Wt(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=cu(u);c&&c!=="none"&&c!==e&&l.push(Wt(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 Bt(s)}function E0(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 Bt(r)}var du=(t,e)=>Oe(t)*e;function hu(t,e,n,r={}){let o=r.minLitLevel??.35,{light:i}=rt(Ze(t)),s=i.length?ot(i):null;if(!s)return[];let a=Oe(s.ambient.fill??"#000000");for(let u of s.lights){let c=u.circle,m=gt(Ee(c.transform),n),d=G(m.x-c.cx,m.y-c.cy);if(d>=c.radius)continue;let h=pu(c),p=1-d/c.radius;a=Math.min(1,a+h*p)}let l=[];if(a<o){let u=du(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 pu(t){let e=t.gradient;if(e&&e.stops.length){let r=0;for(let o of e.stops)r=Math.max(r,Oe(o.color));return r}let n=t.fill;return n?Oe(n):1}function fu(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 Bt(i)}function bu(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 I0(t,e={}){let n=[],r=[],o=t.background??e.background??"#ffffff";if(t.forgiveness&&n.push({gate:"forgiveness",issues:lu(t.forgiveness)}),t.feedback&&n.push({gate:"feedback",issues:uu(t.feedback.contract,t.feedback.events)}),t.avatarFill&&(e.commands?n.push({gate:"salience",issues:mu(e.commands,t.avatarFill,o)}):r.push("salience (no rendered frame)")),t.lit&&(t.avatarFill&&e.commands&&e.avatarWorld?n.push({gate:"lighting",issues:hu(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=fu(e.camSamples,{dt:e.dt});e.targetSamples&&i.push(...bu(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 gu(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 Ni(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 Fi=(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,Ai=(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,yu=t=>t.transient===!0,Wi=t=>{let e=t.fill;if(!(!e||e==="none")&&!t.gradient)return e};function N0(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=>!yu(c)),u=[];for(let c of l)c.kind==="text"&&c.text.trim().length&&u.push(gu(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=Ni(f);if(!g||!Ai(g,c))continue;let k=f.opacity===void 0||f.opacity>=.6,v=f.z??0;k&&v<=m&&v>=h&&(h=v,p=Wi(f)??p),v>m&&(f.opacity===void 0||f.opacity>=.9)&&a.push(`text "${zt(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=Ni(f);g&&Fi(d,g)&&!Ai(g,c)&&a.push(`text "${zt(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=Wt(f,p??o);g<s&&a.push(`text "${zt(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=Wi(c);if(!m)continue;let d=Wt(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++)Fi(u[c],u[m])&&a.push(`texts "${zt(u[c].cmd.text)}" and "${zt(u[m].cmd.text)}" overlap`);return Bi(a)}var zt=t=>t.length>28?t.slice(0,25)+"\u2026":t,Bi=t=>[...new Set(t)];function xu(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 F0(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(xu)].some(o)||r.push(i)}return Bi(r)}function W0(t,e){let n=[t.probe()];for(let r of e)t.step(r),n.push(t.probe());return n}function B0(t,e){for(let n=0;n<t.length;n++)if(e(t[n]))return n;return-1}function z0(t,e){return t.map(n=>n[e])}function _0(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 O0(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 G0(t){return t.length===0?0:t.filter(e=>e.length>0).length/t.length}function V0(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 vu=t=>[...new Set(t)];function wu(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 ku(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=wu(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`),vu(a)}function q0(t,e={}){let n=ku(t,e);if(n.length)throw new Error(`hayao: difficulty ramp is ill-shaped \u2014 ${n[0]}`)}function X0(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:at(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:at(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 dr(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 zi(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 Z0(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=Ft(dr(t)),d=zi(t.left,r,s,a,a/2),h=zi(t.right,r,s,a,a/2),p=dr(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=Nt(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 Q=0;Q<S;Q++)L+=R[T*S+Q]??0;let H=L>1e-6?20*jt(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=Su($);M+=`<rect x="${Y.toFixed(1)}" y="${K.toFixed(1)}" width="${(k+.6).toFixed(1)}" height="${(v+.6).toFixed(1)}" fill="${te}"/>`}}let I=Cu(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">${Tu(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 Su(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 Cu(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 Tu(t){return t.replace(/[<>&]/g,e=>e==="<"?"&lt;":e===">"?"&gt;":"&amp;")}function eb(t,e){let n=Ft(dr(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 on;events=new Xt;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 Ut(e.clock),this.width=e.width??1280,this.height=e.height??720,this.tuningValues={...e.tuning??{}},this.guardDeterminism=e.guardDeterminism??!1,this.root=new O({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 Ge(it({x:this.width/2,y:this.height/2},0,{x:e.zoom,y:e.zoom}),st(n))}worldToScreen(e){return xn(this.viewTransform(),e)}screenToWorld(e){return xn(st(this.viewTransform()),e)}render(){this.ensureStarted();let e=[];return this.root.collectDraw(e,this.viewTransform()),e}hash(){return $t({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,mr(1e6),this.setRoot(Mn(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 yf={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 pn(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 Sf(t){return{width:1280,height:720,seed:1,background:"#f3ecdb",inputMap:Tn,...t}}function Re(t,e){let n=typeof e=="number"?{seed:e}:e??{},r=new hn({seed:n.seed??t.seed??1,width:t.width??1280,height:t.height??720,clock:t.clock,tuning:pn(t.tuning,n.tuning)});return r.setRoot(t.build(r)),t.probe&&(r.probe=()=>t.probe(r)),r}function Mf(t){return t.inputMap??Tn}function Tf(t,e){let n=Re(t),r=e?.frames??[];for(let o of r)n.step(o);return{world:n,hash:n.hash(),steps:r.length}}function ti(t,e,n){let r=typeof n=="number"?{toFrame:n}:n??{},o=Re(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 ni(t){let{frame:e,time:n,hash:r,...o}=t;return JSON.stringify(o)}function Nu(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 Lu(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 $u=(t,e)=>e.some(([n,r])=>t>=n&&t<r);function Df(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=Lu(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&&!$u(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=ti(t,e,{onWorld:k=>{k.events.on("death",()=>M.push({frame:C+1,pos:Nu(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)),U=v.get(Math.min(a.length-1,O+o));A&&U&&ni(A)===ni(U)&&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 Wu(t,e,n,r){let o=t.palette?.bg??"#141821",i=t.palette?.fg??(dn(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 fn(t,e,n={}){let r=t.width??1280,o=t.height??720,i=t.background??"#f3ecdb",s=Re(t,n.world),a=n.renderer==="canvas"?new Je({width:r,height:o,background:i}):n.renderer==="webgl"?new Zt({width:r,height:o,background:i}):new Xe({width:r,height:o,background:i});e.style.position=e.style.position||"relative",a.mount?.(e),ln(e);let u=new He(t.inputMap??{},document),l=new Vt(a,{keyboard:u}),c=[...n.sources??[]],m=Uo(),d=()=>s.input.declareActions(u.actionNames());d();let h=()=>{Be.start();let E=Ae.get();Be.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=Re(t,n.world),d(),p()},v=n.shell===!1?null:new mn({title:t.title,onRestart:n.onRestart??b,onPause:E=>n.onPause?.(E)}),M=t.splash===!1?null:t.splash??{},x=M&&!m?Wu(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 z of c)z.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,U=()=>{k!==0&&(cancelAnimationFrame(k),k=0),T!==void 0&&(clearTimeout(T),T=void 0)},X=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&&(U(),F=null,X(E))};document.addEventListener("visibilitychange",te);let Q=E=>{if(C){x&&a.draw(x),X(Q);return}let L=E-S;S=E,R(L),X(Q)};if(X(Q),C){let E=M?.minDurationMs??0,L=t.preload?Promise.resolve().then(()=>t.preload(s)):Promise.resolve(),_=new Promise(z=>setTimeout(z,Math.max(0,E-(performance.now()-w))));Promise.all([L,_]).then(D).catch(z=>{console.error("hayao: preload failed \u2014",z),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,U(),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&&Xo({get world(){return s},stepOnce:(E=[])=>{s.step(E),p()},renderSVG:()=>Jt(s.render(),r,o,i),setPaused:()=>{}}),oe}function Vn(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 jf(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=fn(t,r,{shell:!1,isHeld:()=>!0}),i=o.canvas;return{handle:o,touchDown(s,a,u=1){i?.dispatchEvent(Vn("pointerdown",s,a,u))},touchMove(s,a,u=1){i?.dispatchEvent(Vn("pointermove",s,a,u))},touchUp(s=1){globalThis.dispatchEvent?.(Vn("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 ri=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}},oi=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 Jf(t){return{kind:"sleep",left:t}}function Yf(t){return{kind:"cond",cond:t}}function Kf(){return{kind:"next"}}function Qf(...t){return{kind:"race",waits:t}}function Zf(...t){return{kind:"all",waits:t}}var si=1e-9;function Hn(t,e){if(ai(t))return t.done?0:-1;switch(t.kind){case"sleep":return t.left-=e,t.left<=si?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++)Hn(t.waits[r],e)>=0&&n<0&&(n=r);return n}case"all":{let n=!0;for(let r of t.waits)qn(r)||Hn(r,e)<0&&(n=!1);return n?0:-1}}}function qn(t){if(ai(t))return t.done;switch(t.kind){case"sleep":return t.left<=si;case"cond":return t.met===!0;case"next":return t.passed===!0;case"race":return t.waits.some(qn);case"all":return t.waits.every(qn)}}function ai(t){return t instanceof bn}var bn=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{}}}},ii=class{runners=[];pending=[];nextId=0;start(e,n){let r=new bn(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=Hn(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 zu(t){let e=0;for(let n of t)e+=n>0?n:0;return e}function li(t,e){let n=zu(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 t0(t,e,n){if(e.length!==n.length)throw new Error("hayao: weightedPick items/weights length mismatch");return e[li(t,n)]}function ci(t,e){return e[li(t,e.map(n=>n.weight))].value}var ui=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 Bu(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 o0(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 _u(t,e,n,r,o={}){let i=o.heuristic??(()=>0),s=o.maxNodes??1e6,a=new Map,u=new Map,l=new jn,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:Gu(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 Gu(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 jn=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}],Un=[...gn,{x:1,y:-1},{x:1,y:1},{x:-1,y:1},{x:-1,y:-1}],mi=t=>`${t.x},${t.y}`;function Ou(t,e,n,r){let o=r?Un:gn;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 di(t,e,n){if(!e(t.x,t.y))return[];let r=Ou(e,n.cols,n.rows,n.diagonal??!1);return Bu(t,r,mi).order}function i0(t,e,n,r=!1){let o=new Array(t*e).fill(-1),i=[],s=r?Un:gn;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 s0(t,e,n,r){let o=r.diagonal??!1,i=o?Un:gn,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=_u(t,m=>m.x===e.x&&m.y===e.y,u,mi,{heuristic:l,maxNodes:r.maxNodes});return c?c.path:null}function a0(t){return(e,n)=>fe(t,e,n)!==Y.SOLID}function Vu(t){return structuredClone(t)}var hi=class{history=[];cursor=-1;limit;clone;constructor(e={}){this.limit=Math.max(1,e.limit??64),this.clone=e.clone??Vu}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}},pi=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 Xn=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()]}},fi=class{get(e){return null}set(e,n){}remove(e){}keys(){return[]}},Jn=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 bi(t){try{if(typeof localStorage<"u"){let e="__hayao_probe__";return localStorage.setItem(e,"1"),localStorage.removeItem(e),new Jn(t)}}catch{}return new Xn}function m0(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 d0(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 Yn="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",gi={};for(let t=0;t<Yn.length;t++)gi[Yn[t]]=t;function h0(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+=Yn[o]}while(r>0)}return e}function p0(t){let e=[],n=0,r=1;for(let o of t){let i=gi[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 xi=1;function Hu(t){return JSON.stringify({v:xi,snap:t})}function yi(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!==xi||!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 vi=class{constructor(e,n=bi()){this.world=e;this.storage=n}world;storage;save(e="auto"){this.storage.set(e,Hu(this.world.snapshot()))}load(e="auto"){let n=yi(this.storage.get(e));return n?(this.world.restore(n),!0):!1}has(e="auto"){return yi(this.storage.get(e))!==null}delete(e="auto"){this.storage.remove(e)}slots(){return this.storage.keys()}};function v0(t){return{next:t.map(e=>e.time)}}function x0(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=ci(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 w0(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 qu=new Set(["#","-","^","."," "]),Ct=t=>t===Y.SOLID,ju=t=>t===Y.HAZARD,Uu=(t,e,n)=>({x:(t+.5)*n,y:(e+.5)*n});function T0(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=Uu(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 C0(t){let e=[],n=Kn(t),r=o=>n.tiles[o.y*n.cols+o.x]??Y.EMPTY;return t.rows.forEach((o,i)=>{for(let s=0;s<o.length;s++){let a=o[s];a==="S"||a==="G"||qu.has(a)||a in t.legend||e.push(`unknown glyph '${a}' at (${s},${i}) \u2014 add it to the legend or use terrain '#/-/^/.'`)}}),Ct(r(t.spawn))&&e.push(`spawn (${t.spawn.x},${t.spawn.y}) is inside a solid tile`),Ct(r(t.goal))&&e.push(`goal (${t.goal.x},${t.goal.y}) is inside a solid tile`),[...new Set(e)]}function Kn(t){return Fr(t.rows,t.tileSize)}function R0(t,e={}){let n=Kn(t),r=(u,l)=>n.tiles[l*n.cols+u]??Y.EMPTY,o=e.passable??((u,l)=>!Ct(r(u,l))),i=di(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 P0(t,e){let n=Kn(t),{cols:r,rows:o}=n,i=(x,C)=>x<0||C<0||x>=r||C>=o?Y.SOLID:n.tiles[C*r+x],s=(x,C)=>{let I=i(x,C+1);return I===Y.SOLID||I===Y.ONEWAY},a=(x,C)=>!Ct(i(x,C))&&!ju(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=!Ct(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 E0(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 Xu(t,e){return lr(`hayao/gen:${t>>>0}:${e}`)}var Ju=(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 Yu(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=Xu(n,l),m=t(new ce(c)),d=et(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(!Ju(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 wi(t,e){let n=Yu(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 A0(t,e){return t(new ce(e))}function $0(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=wi(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 Ku(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 ki(t,e){return(t.requires??[]).every(n=>e.has(n))}function Si(t,e,n){let r=[];for(let o of t.edges)o.from===e&&ki(o,n)?r.push(o.to):!o.oneWay&&o.to===e&&ki(o,n)&&r.push(o.from);return r}function Qn(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=Ku(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 Si(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 Mi={maxDepth:2e3,nodeCap:5e6};function B0(t){return et(Qn(t,"complete"),Mi)}function _0(t){return et(Qn(t,"full"),Mi)}function Qu(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 Si(t,i,n))r.has(s)||(r.add(s),o.push(s))}return[...r]}function G0(t,e="complete"){let n=Qn(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 O0(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(Qu(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 H0(t){let e=[];for(let n=1;n<=t;n++)e.push(`p${n}`);return e}var yn=(t,e)=>`${t}:${e}`;function Rt(t,e){let n=[];for(let r of t){let o=e.get(r)??[];for(let i of o)n.push(yn(r,i))}return n.sort()}var Zn=class{constructor(e,n){this.world=e;this.player=n}world;player;isDown(e){return this.world.input.isDown(yn(this.player,e))}justPressed(e){return this.world.input.justPressed(yn(this.player,e))}justReleased(e){return this.world.input.justReleased(yn(this.player,e))}},q0=(t,e)=>new Zn(t,e);var U0=1,tt={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 Ti=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 er(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}},er=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)}},Ci=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 J0(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 nt=class{frames=new Map;contiguous=new Map;addPlayer(e){this.frames.has(e)||(this.frames.set(e,new Map),this.contiguous.set(e,-1))}removePlayer(e){this.frames.delete(e),this.contiguous.delete(e)}players(){return[...this.frames.keys()]}set(e,n,r){let o=this.frames.get(e);if(!o||o.has(n))return!1;o.set(n,[...r].sort());let i=this.contiguous.get(e)??-1;for(;o.has(i+1);)i++;return this.contiguous.set(e,i),!0}has(e,n){return this.frames.get(e)?.has(n)??!1}get(e,n){return this.frames.get(e)?.get(n)}latestAt(e,n){let r=this.frames.get(e);if(!r)return[];for(let o=n;o>=0;o--){let i=r.get(o);if(i)return i}return[]}contiguousThrough(e){return this.contiguous.get(e)??-1}confirmedFrame(){let e=1/0;for(let n of this.contiguous.values())e=Math.min(e,n);return e===1/0?-1:e}clearFrom(e,n){let r=this.frames.get(e);if(!r)return;for(let i of r.keys())i>=n&&r.delete(i);let o=this.contiguous.get(e)??-1;o>=n&&(o=n-1),this.contiguous.set(e,o)}prune(e){for(let n of this.frames.values())for(let r of n.keys())r<e&&n.delete(r)}};var De=class{world;localPlayer;config;startFrame;transport;buffer=new nt;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={...tt,...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=Rt(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 vn=class{world;localPlayer;config;transport;players;buffer=new nt;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={...tt,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(Rt(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(Rt(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=$t(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 Zu(){return globalThis.crypto.randomUUID()}function Ri(t,e,n,r,o,i,s,a,u){return t==="rollback"?new vn({world:e,transport:n,localPlayer:r,players:o,config:s,attach:a,onDesync:u.onDesync}):new De({world:e,transport:n,localPlayer:r,players:o,startFrame:i,config:s,onDesync:u.onDesync})}function Pi(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 tr=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={...tt,...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=Ri(this.config.mode,e,this.transport,this.localPlayer,this.players,0,this.config,this.attach,this.callbacks);return n instanceof De&&n.onAfterStep(r=>this.serviceSnapshots(r,e)),this.transport.send(de(he({t:"start",players:[...this.players]}))),this.game=Pi(e,n,this.localPlayer,this.players,()=>this.unsubscribe()),this.game}dropPlayer(e){let n=this.game?.session;if(!n)return;let r=n instanceof De?Math.max(n.frame,n.confirmedFrame+1):n.lastKnownFrame(e)+1;this.transport.send(de(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 Ei(t){let e=Zu(),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=Ri(i.config.mode,h,n,i.player,d,i.startFrame,i.config,t.attach,t);if(i.joins&&p instanceof De)for(let M of i.joins)p.addPlayer(M.player,M.atFrame);for(let M of l)M.t==="join"&&p instanceof De&&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 De?(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=Pi(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 Di(t){return new tr(t)}function gb(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),ln(e);let a=new He(t.inputMap??{},document),u=b=>Re(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=Di({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"),Ei({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 el=0;function tl(t,e){return`${t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"game"}-${e.replace(/[:.]/g,"-").toLowerCase()}-${(el++).toString(36)}`}var rt=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??tl(e.game,this.startedAt),this.buildRef=e.buildRef??"unknown"}get frame(){return this.frames.length}get liveInputFrames(){return this.frames}get liveAxesLog(){return this.axesLog}get liveKnobEvents(){return this.knobEvents}step(e,n){if(n)for(let[r,o]of n)this.lastAxes.get(r)!==o&&(this.axesLog.push([this.frames.length,r,o]),this.lastAxes.set(r,o));this.frames.push([...e].sort())}knob(e,n){this.knobEvents.push({frame:this.frames.length,key:e,value:n}),this.screen("knob",`${e}=${n}`)}screen(e,n){this.screenEvents.push({frame:this.frames.length,kind:e,...n!==void 0?{detail:n}:{}})}mark(e,n){this.wallClockMarks.push({frame:this.frames.length,t:n,kind:e})}annotate(e,n){this.annotations.push({frame:this.frames.length,tag:e,...n!==void 0?{note:n}:{}})}truncate(e){if(!(e>=this.frames.length)){this.frames.length=e,this.axesLog=this.axesLog.filter(([n])=>n<e),this.lastAxes.clear();for(let[n,r,o]of this.axesLog)n<e&&this.lastAxes.set(r,o);this.knobEvents=this.knobEvents.filter(n=>n.frame<=e),this.screenEvents=this.screenEvents.filter(n=>n.frame<=e),this.wallClockMarks=this.wallClockMarks.filter(n=>n.frame<=e),this.annotations=this.annotations.filter(n=>n.frame<=e)}}toSession(e){return{id:this.id,game:this.init.game,startedAt:this.startedAt,buildRef:this.buildRef,seed:this.init.seed,variant:this.init.variant??{name:"dev",kind:"dev"},tuningValues:{...this.init.tuningValues},...this.init.startSnapshot?{startSnapshot:this.init.startSnapshot}:{},knobEvents:this.knobEvents.slice(),inputLog:{frames:this.frames.map(n=>n.slice())},axesLog:this.axesLog.slice(),screenEvents:this.screenEvents.slice(),wallClockMarks:this.wallClockMarks.slice(),annotations:this.annotations.slice(),endReason:e}}};var Pt=class{constructor(e=30,n=240){this.stride=e;this.cap=n}stride;cap;entries=[];push(e,n){e%this.stride===0&&(this.entries.push({frame:e,snap:n.snapshot()}),this.entries.length>this.cap&&this.entries.shift())}nearest(e){let n=null;for(let r of this.entries)r.frame<=e&&(!n||r.frame>n.frame)&&(n=r);return n}get minFrame(){return this.entries.length>0?this.entries[0].frame:0}truncate(e){this.entries=this.entries.filter(n=>n.frame<=e)}clear(){this.entries=[]}};function nr(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 nl(){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 Rb(t,e,n={}){let r=nl(),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=pn(s.tuning,l),m={...c},d=typeof performance<"u"?performance.now():0,h=new rt({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 Pt,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=fn(s,e,{...n,world:{seed:u,tuning:l},isHeld:()=>y||(n.isHeld?.()??!1),onAdvance:(E,L,_)=>{for(let z=0;z<L;z++)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 rt({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 rt({game:s.title,seed:u,tuningValues:{...m},variant:a,startSnapshot:E}),h.screen("hot-swap")}n.hot?.dispose(E=>{E.hayaoSnap=S.world.snapshot(),Q("hot-swap")}),I.push(0,S.world);async function R(E,L){let _=await fetch(`/__studio/session/${encodeURIComponent(E)}`);if(!_.ok)return;let z=await _.json();y=!0;let q=S.world,ie=Re(s,{seed:z.seed,tuning:z.tuningValues});q.restore(z.startSnapshot?structuredClone(z.startSnapshot):ie.snapshot()),s.attach?.(q),q.input.axes.clear();let se=z.inputLog.frames,re=Math.max(30,Math.ceil(se.length/220/30)*30);I=new Pt(re),I.push(0,q);let ae=0,le=0;for(let ge=0;ge<se.length;ge++){for(;le<z.knobEvents.length&&z.knobEvents[le].frame===ge;){let Le=z.knobEvents[le++],ke=q.snapshot();ke.tuning={...ke.tuning,[Le.key]:Le.value},q.restore(ke),s.attach?.(q)}for(;ae<z.axesLog.length&&z.axesLog[ae][0]===ge;){let[,Le,ke]=z.axesLog[ae++];q.input.axes.set(Le,ke)}q.step(se[ge]),I.push(ge+1,q)}x={session:z,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(),z=Math.min(120,Math.floor((_-L)/(1e3/60)));if(z<=0)return;L=_;let q=S.world;for(let ie=0;ie<z;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,le]of E.axesLog)re===se&&q.input.axes.set(ae,le);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(()=>{}),Bn((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()),U=()=>h.mark("focus",F()),X=()=>v("quit",!0);document.addEventListener("visibilitychange",O),window.addEventListener("blur",A),window.addEventListener("focus",U),window.addEventListener("pagehide",X);let te=window.setInterval(()=>v("idle"),1e4),Q=E=>{T(),v(E,E==="hot-swap"),document.removeEventListener("visibilitychange",O),window.removeEventListener("blur",A),window.removeEventListener("focus",U),window.removeEventListener("pagehide",X),window.clearInterval(te),Bn(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 z of Object.keys(m))z in _&&(m[z]=_[z])}y=!1},frozen:()=>x?C===null:y,scrub(E){if(x){T();let _=x.session,z=nr(S.world,s,I,_.inputLog.frames,_.axesLog,_.knobEvents,E);return z!==null&&(x.pos=z),z}y=!0;let L=nr(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:()=>Q("navigate")};return window.__studio=oe,oe}var Eb="0.4.0";export{lu as ALBUM,Kl as AMBIENT_PRESETS,wr as AmbientField,Gt as AnimationPlayer,An as AudioBus,Wm as BLOOM_PIPELINE,ro as BitmapText,Ci as BroadcastChannelTransport,Bt as Camera2D,fr as CameraController,Je as Canvas2DRenderer,qo as CinematicPlayer,Nt as Clock,ii as Coroutines,ss as DEFAULT_GAMEPAD_MAP,Tn as DEFAULT_INPUT_MAP,ct as DEFAULT_PLATFORMER,tt as DEFAULT_SESSION_CONFIG,Ir as DEFAULT_TILE_CHARS,Os as DUSK,pr as DepthSort,vr as EASINGS,ne as Edge,Lt as EventBus,nc as FLOAT_PRESETS,no as FONT_5,Sr as FloatingText,ri as Fsm,Za as GENRES,Bh as GENRE_PROFILES,Dr as GamepadSource,Yr as HeadlessRenderer,ue as IDENTITY,$ as INSTRUMENTS,nt as InputBuffer,Cr as InputRecorder,Ot as InputState,hr as IsoPrism,B as KENTO,He as KeyboardSource,Jn as LocalStorageAdapter,De as LockstepSession,Ti as LoopbackHub,er as LoopbackTransport,ui as LootTable,Gs as MEADOW,Er as MOUSE_ACTIONS,Xn as MemoryStorage,gn as NEIGHBORS_4,Un as NEIGHBORS_8,U0 as NET_PROTOCOL_VERSION,V as Node,V as Node2D,gr as NodePool,fi as NullStorage,Rc as PAD_NEUTRAL,jm as PALETTES,Vm as PANEL_PRESETS,Vs as PAPER,os as PARTICLE_PRESETS,br as ParallaxLayer,xr as Particles,oi as PhaseClock,ft as PixelBuffer,Zn as PlayerInput,Vt as PointerSource,pi as RingBuffer,ce as Rng,vn as RollbackSession,tr as RoomHost,be as SAMPLE_RATE,xi as SAVE_FORMAT_VERSION,So as SCALES,vi as SaveManager,Gn as ScreenTransition,rt as SessionRecorder,kr as Shaker,mn as Shell,at as Signal,Pt as SnapshotRing,qt as SpatialHash,Wt as Sprite,Xe as SvgRenderer,Z as TAU,Y as TILE,zt as Text,eo as TextureSprite,_t as Timer,Vo as TouchControls,hi as UndoStack,Eb as VERSION,Mr as VerletChain,Kt as WEBGL_EFFECTS,Ke as WangFrame,Zt as WebGL2Renderer,hn as World,Ku as abilitiesOf,_c as addBody,Yc as addDistanceJoint,Kc as addRevoluteJoint,hp as addTransition,Zh as albumTrack,Zf as all,Df as analyzePlaytest,Oc as applyImpulse,Co as applyReverb,xn as applyTransform,yc as asciiEntities,af as assertAudio,xp as assertDeterministic,Kp as assertRamp,wp as assertSnapshotStable,gp as assertSolvable,_u as astar,s0 as astarGrid,Be as audio,kd as autotile4,Sd as autotileToCommands,w0 as availableUpgrades,Fo as bandBalance,Bu as bfs,rd as blobPath,Cn as bodyAABB,Ps as bodyContains,jf as bootDom,Rh as cadenceResolves,Su as cameraIssues,jr as canvasGradient,Qe as cellFloat,ua as cellHash,Ed as cellInt,jp as changeFrames,gu as checkDeterministic,Sh as chordChanges,Te as chordNotes,ee as clamp,qe as clientToDesign,Lr as collide,Ue as commandsToSVGInner,$0 as composeCampaign,Ge as composeTransform,J0 as connectWebSocket,i0 as connectedComponents,Md as contourToCommands,St as contrastRatio,Ip as createPlanBot,Pc as createPlatformerState,Bc as createRigidWorld,bo as createStereo,Re as createWorld,Io as crestFactorDb,Ic as dashJumpDistance,Ui as datan,Ft as datan2,Nn as dbfs,J as dcos,ld as decode2bit,ud as decodeBits,Ne as decodeMessage,cd as decodeRLE,bi as defaultStorage,Sf as defineGame,T0 as defineLevel,hl as deg2rad,Mn as deserializeNode,_e as dexp,pe as dexp2,K as dhypot,kn as diamondPoints,xa as diatonicChord,E0 as diffLevels,Ha as distanceGain,ir as dlog,At as dlog10,ot as dlog2,Pe as dpow,Ep as drive,ym as dropShadow,H as dsin,$h as duckGain,de as encodeMessage,md as encodeRLE,Ud as encodeWav,za as estimateTempo,Ah as evalCurve,Va as featureDistance,wt as features,xu as feedbackIssues,La as fft,G0 as findSoftlocks,Hp as firstFrame,je as fitViewport,di as floodFill,Do as fluxEnvelope,vu as forgivenessIssues,lo as fractalNoise,ut as frameActions,lt as frameAxes,Mf as gameInputMap,Ad as generateCave,Gd as generateDungeon,wi as generateLevels,Yu as generateLevelsReport,Hh as genre,ve as getBody,Qc as getJoint,gm as glow,Lp as graceWindowIssues,Km as gradient,Vr as gradientDef,aa as gridAt,xd as gridFromRows,Fe as gridSet,Rd as gridToTilemap,as as groundAt,xl as hashNoise,lr as hashString,$t as hashValue,qs as hexToHsl,cn as hideScreen,Sp as hold,Di as hostRoom,Hs as hsl,Jm as hsv,$c as inVisionCone,v0 as initDirector,Xp as inputDensity,Xo as installCapture,ar as invLerp,Xt as invalidCommandReason,st as invertTransform,Uo as isCaptureMode,zd as isGround,Up as isMonotonic,yl as iso,Ei as joinRoom,ls as jumpAirtime,cs as jumpDistance,Dc as jumpHeight,Ru as keyMentions,Pr as keysToActions,yf as knob,Lh as layerGains,_p as layoutIssues,Qs as layoutText,Ie as lerp,Hl as lerpDamp,A0 as levelFromSeed,C0 as levelIssues,R0 as levelReachable,Kn as levelToTilemap,fs as lineOfSight,fm as linearGradient,Ch as lintSong,Jp as longestLull,Mu as lookAheadIssues,xt as magnitudeSpectrum,gt as makeGrid,ql as makeReach,it as makeTransform,wc as mapHeight,xc as mapWidth,oa as marchingSquaresCases,sa as marchingSquaresContours,so as mask4,wd as mask8,Eh as matchReport,bt as measureLine,gd as measureText,Rt as mergePlayerFrames,va as midiToFreq,nh as midiToName,Gp as missingControlHints,Um as mix,Us as mixLinear,go as mixMono,Ht as moveRect,Ym as mutateColor,he as netMessage,Kf as nextStep,Om as nineSlice,vo as normalize,me as noteToMidi,Wa as onsetDensity,En as openVoicing,h0 as packVarints,qa as panFromOffset,ha as panGains,Ks as parseRich,yi as parseSnapshot,a0 as passableFromTilemap,pa as peak,Eo as peakAmp,ci as pickEntry,ko as pitchToFreq,Js as pixelsToCommands,P0 as platformerReachable,yn as playerAction,H0 as playerIds,q0 as playerInput,cm as pointQuery,x0 as pollDirector,Vc as polygonBox,Ze as progression,Qn as progressionPuzzle,B0 as proveCompletable,_0 as proveFullCompletion,Cp as pump,Rr as quantizeAngle,Qf as race,pl as rad2deg,bm as radialGradient,Du as rampIssues,Eu as rampStats,mm as rayCastRigid,ps as raycastTiles,Qu as reachableRegions,o0 as reconstructPath,Vp as recordTimeline,ze as rectBlocked,fl as rectContains,bl as rectsOverlap,Oe as registerNode,ts as regularPolyPoints,td as regularPolygon,dn as relLuminance,dl as remap,Gc as removeBody,Zc as removeJoint,sf as renderAudioFilmstrip,ef as renderFilmstrip,Po as renderSong,tn as renderSound,Jt as renderToSVGString,jo as replay,ti as replaySession,mr as resetNodeIds,Uh as resetZzfxWarnings,pn as resolveTuning,sm as rigidStep,d0 as rleDecode,m0 as rleEncode,vt as rms,mo as roomCenter,nn as rootless,fn as runBrowser,gb as runBrowserNet,Wp as runFeelGates,Tf as runHeadless,Rb as runStudio,ku as salienceIssues,Qr as sampleGradient,Pn as scaleMidis,Mo as scalePitchClasses,la as scatter,Dd as scatterCells,_h as scoreTrack,fp as screenRect,yu as scriptToFrames,Tp as scriptedPlaythrough,nr as scrubTo,Hu as serializeSnapshot,qp as series,ln as setOverlayHost,Bn as setScreenObserver,Ae as settings,dr as shadeHex,Hr as shadowDef,qr as shapeBBox,Jo as shapeBox,zo as showScreen,Xd as signalHash,Jf as sleep,Xs as smoothClosedPath,od as smoothOpenPath,ur as smoothstep,Ve as snapAxis,fo as softClip,yo as softClipInPlace,ao as solidNeighbours,et as solve,Wr as solveJoint,Pa as songBeats,Fn as songDuration,Ut as sortCommands,Nh as spatialMix,Xh as specFromZzfx,$a as spectralCentroid,ns as spring,rs as springStep,nd as star,Fp as steer2D,Ec as stepPlatformer,jd as stereoDuration,qd as stereoFrames,ja as stereoWidth,Xu as subSeed,$p as telegraphIssues,co as terrainHeight,Wd as terrainSlice,Tu as textBox,ea as textToCommands,fe as tileAt,vc as tileAtPoint,Uu as tileCenter,Fr as tilemapFromAscii,Go as toggleFullscreen,rh as transpose,Zs as typewriterCount,p0 as unpackVarints,sl as vadd,O0 as validateWorld,ca as valueNoise,cl as vdist,ll as vdot,il as vec2,Qi as vlen,ml as vnorm,yt as voiceLead,ul as vscale,al as vsub,Mp as wait,Yf as waitFor,xe as wakeBody,ra as wangTile,mt as warnCommandOnce,is as weatherEnvelope,li as weightedIndex,t0 as weightedPick,pp as wipeStep,Xm as withAlpha,Me as worldPoints,Aa as zcr};
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 ae;let e=this.activeCamera,n=e.worldTransform();return Fe(qe({x:this.width/2,y:this.height/2},0,{x:e.zoom,y:e.zoom}),Ee(n))}worldToScreen(e){return gt(this.viewTransform(),e)}screenToWorld(e){return gt(Ee(this.viewTransform()),e)}render(){this.ensureStarted();let e=[];return this.root.collectDraw(e,this.viewTransform()),e}hash(){return Jt({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,Fr(1e6),this.setRoot(Un(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 mb={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 Dn(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 bb(t){return{width:1280,height:720,seed:1,background:"#f3ecdb",inputMap:Xn,...t}}function Pe(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:Dn(t.tuning,n.tuning)});return r.setRoot(t.build(r)),t.probe&&(r.probe=()=>t.probe(r)),r}function gb(t){return t.inputMap??Xn}function yb(t,e){let n=Pe(t),r=e?.frames??[];for(let o of r)n.step(o);return{world:n,hash:n.hash(),steps:r.length}}function _i(t,e,n){let r=typeof n=="number"?{toFrame:n}:n??{},o=Pe(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 Oi(t){let{frame:e,time:n,hash:r,...o}=t;return JSON.stringify(o)}function Mu(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 Ru(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 Pu=(t,e)=>e.some(([n,r])=>t>=n&&t<r);function Sb(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=Ru(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&&!Pu(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=_i(t,e,{onWorld:S=>{S.events.on("death",()=>k.push({frame:M+1,pos:Mu(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&&Oi($)===Oi(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 Du(t,e,n,r){let o=t.palette?.bg??"#141821",i=t.palette?.fg??(Oe(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 En(t,e,n={}){let r=t.width??1280,o=t.height??720,i=t.background??"#f3ecdb",s=Pe(t,n.world),a=n.renderer==="canvas"?new ut({width:r,height:o,background:i}):n.renderer==="webgl"?new bn({width:r,height:o,background:i}):new lt({width:r,height:o,background:i});e.style.position=e.style.position||"relative",a.mount?.(e),Tn(e);let l=new nt(t.inputMap??{},document),u=new sn(a,{keyboard:l}),c=[...n.sources??[]],m=Li(),d=()=>s.input.declareActions(l.actionNames());d();let h=()=>{Je.start();let D=_e.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=Pe(t,n.world),d(),p()},g=n.shell===!1?null:new Rn({title:t.title,onRestart:n.onRestart??f,onPause:D=>n.onPause?.(D)}),k=t.splash===!1?null:t.splash??{},v=k&&!m?Du(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 B of c)B.sample(s.input);let A=l.currentActions(),_=s.advance(D,A);_>0&&(l.clearPressed(),n.onAdvance?.(s,_,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 Q=D=>{if(M){v&&a.draw(v),K(Q);return}let A=D-C;C=D,R(A),K(Q)};if(K(Q),M){let D=k?.minDurationMs??0,A=t.preload?Promise.resolve().then(()=>t.preload(s)):Promise.resolve(),_=new Promise(B=>setTimeout(B,Math.max(0,D-(performance.now()-w))));Promise.all([A,_]).then(E).catch(B=>{console.error("hayao: preload failed \u2014",B),E()})}else x();let oe={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&&$i({get world(){return s},stepOnce:(D=[])=>{s.step(D),p()},renderSVG:()=>dn(s.render(),r,o,i),setPaused:()=>{}}),oe}function hr(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 zb(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=En(t,r,{shell:!1,isHeld:()=>!0}),i=o.canvas;return{handle:o,touchDown(s,a,l=1){i?.dispatchEvent(hr("pointerdown",s,a,l))},touchMove(s,a,l=1){i?.dispatchEvent(hr("pointermove",s,a,l))},touchUp(s=1){globalThis.dispatchEvent?.(hr("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 Gi=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}},Vi=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 Gb(t){return{kind:"sleep",left:t}}function Vb(t){return{kind:"cond",cond:t}}function Hb(){return{kind:"next"}}function qb(...t){return{kind:"race",waits:t}}function jb(...t){return{kind:"all",waits:t}}var qi=1e-9;function pr(t,e){if(ji(t))return t.done?0:-1;switch(t.kind){case"sleep":return t.left-=e,t.left<=qi?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++)pr(t.waits[r],e)>=0&&n<0&&(n=r);return n}case"all":{let n=!0;for(let r of t.waits)fr(r)||pr(r,e)<0&&(n=!1);return n?0:-1}}}function fr(t){if(ji(t))return t.done;switch(t.kind){case"sleep":return t.left<=qi;case"cond":return t.met===!0;case"next":return t.passed===!0;case"race":return t.waits.some(fr);case"all":return t.waits.every(fr)}}function ji(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{}}}},Hi=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=pr(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 Eu(t){let e=0;for(let n of t)e+=n>0?n:0;return e}function Xi(t,e){let n=Eu(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 Xb(t,e,n){if(e.length!==n.length)throw new Error("hayao: weightedPick items/weights length mismatch");return e[Xi(t,n)]}function Ji(t,e){return e[Xi(t,e.map(n=>n.weight))].value}var Ui=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 Iu(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 Kb(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 Lu(t,e,n,r,o={}){let i=o.heuristic??(()=>0),s=o.maxNodes??1e6,a=new Map,l=new Map,u=new br,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:$u(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 $u(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 br=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]]}},Ln=[{x:0,y:-1},{x:1,y:0},{x:0,y:1},{x:-1,y:0}],gr=[...Ln,{x:1,y:-1},{x:1,y:1},{x:-1,y:1},{x:-1,y:-1}],Yi=t=>`${t.x},${t.y}`;function Nu(t,e,n,r){let o=r?gr:Ln;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 Ki(t,e,n){if(!e(t.x,t.y))return[];let r=Nu(e,n.cols,n.rows,n.diagonal??!1);return Iu(t,r,Yi).order}function Qb(t,e,n,r=!1){let o=new Array(t*e).fill(-1),i=[],s=r?gr:Ln;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 Zb(t,e,n,r){let o=r.diagonal??!1,i=o?gr:Ln,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=Lu(t,m=>m.x===e.x&&m.y===e.y,l,Yi,{heuristic:u,maxNodes:r.maxNodes});return c?c.path:null}function eg(t){return(e,n)=>pe(t,e,n)!==X.SOLID}function Fu(t){return structuredClone(t)}var Qi=class{history=[];cursor=-1;limit;clone;constructor(e={}){this.limit=Math.max(1,e.limit??64),this.clone=e.clone??Fu}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}},Zi=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 yr=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()]}},es=class{get(e){return null}set(e,n){}remove(e){}keys(){return[]}},xr=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 ts(t){try{if(typeof localStorage<"u"){let e="__hayao_probe__";return localStorage.setItem(e,"1"),localStorage.removeItem(e),new xr(t)}}catch{}return new yr}function og(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 ig(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 vr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",ns={};for(let t=0;t<vr.length;t++)ns[vr[t]]=t;function sg(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+=vr[o]}while(r>0)}return e}function ag(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 is=1;function Au(t){return JSON.stringify({v:is,snap:t})}function rs(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!==is||!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 os=class{constructor(e,n=ts()){this.world=e;this.storage=n}world;storage;save(e="auto"){this.storage.set(e,Au(this.world.snapshot()))}load(e="auto"){let n=rs(this.storage.get(e));return n?(this.world.restore(n),!0):!1}has(e="auto"){return rs(this.storage.get(e))!==null}delete(e="auto"){this.storage.remove(e)}slots(){return this.storage.keys()}};function dg(t){return{next:t.map(e=>e.time)}}function hg(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=Ji(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 pg(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 Wu=new Set(["#","-","^","."," "]),_t=t=>t===X.SOLID,Bu=t=>t===X.HAZARD,zu=(t,e,n)=>({x:(t+.5)*n,y:(e+.5)*n});function yg(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=zu(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 xg(t){let e=[],n=wr(t),r=o=>n.tiles[o.y*n.cols+o.x]??X.EMPTY;return t.rows.forEach((o,i)=>{for(let s=0;s<o.length;s++){let a=o[s];a==="S"||a==="G"||Wu.has(a)||a in t.legend||e.push(`unknown glyph '${a}' at (${s},${i}) \u2014 add it to the legend or use terrain '#/-/^/.'`)}}),_t(r(t.spawn))&&e.push(`spawn (${t.spawn.x},${t.spawn.y}) is inside a solid tile`),_t(r(t.goal))&&e.push(`goal (${t.goal.x},${t.goal.y}) is inside a solid tile`),[...new Set(e)]}function wr(t){return uo(t.rows,t.tileSize)}function vg(t,e={}){let n=wr(t),r=(l,u)=>n.tiles[u*n.cols+l]??X.EMPTY,o=e.passable??((l,u)=>!_t(r(l,u))),i=Ki(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 wg(t,e){let n=wr(t),{cols:r,rows:o}=n,i=(v,M)=>v<0||M<0||v>=r||M>=o?X.SOLID:n.tiles[M*r+v],s=(v,M)=>{let I=i(v,M+1);return I===X.SOLID||I===X.ONEWAY},a=(v,M)=>!_t(i(v,M))&&!Bu(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=!_t(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 kg(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 _u(t,e){return $r(`hayao/gen:${t>>>0}:${e}`)}var Ou=(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 Gu(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=_u(n,u),m=t(new ue(c)),d=dt(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(!Ou(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 ss(t,e){let n=Gu(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 Mg(t,e){return t(new ue(e))}function Dg(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=ss(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 Vu(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 as(t,e){return(t.requires??[]).every(n=>e.has(n))}function ls(t,e,n){let r=[];for(let o of t.edges)o.from===e&&as(o,n)?r.push(o.to):!o.oneWay&&o.to===e&&as(o,n)&&r.push(o.from);return r}function kr(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=Vu(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 ls(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 us={maxDepth:2e3,nodeCap:5e6};function Lg(t){return dt(kr(t,"complete"),us)}function $g(t){return dt(kr(t,"full"),us)}function Hu(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 ls(t,i,n))r.has(s)||(r.add(s),o.push(s))}return[...r]}function Ng(t,e="complete"){let n=kr(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 Fg(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(Hu(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 Wg(t){let e=[];for(let n=1;n<=t;n++)e.push(`p${n}`);return e}var $n=(t,e)=>`${t}:${e}`;function Ot(t,e){let n=[];for(let r of t){let o=e.get(r)??[];for(let i of o)n.push($n(r,i))}return n.sort()}var Sr=class{constructor(e,n){this.world=e;this.player=n}world;player;isDown(e){return this.world.input.isDown($n(this.player,e))}justPressed(e){return this.world.input.justPressed($n(this.player,e))}justReleased(e){return this.world.input.justReleased($n(this.player,e))}},Bg=(t,e)=>new Sr(t,e);var _g=1,ht={mode:"lockstep",inputDelay:2,hashInterval:20,maxRollback:12,redundancy:3};function de(t){return JSON.stringify(t)}function Ge(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 cs=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 Cr(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}},Cr=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)}},ms=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 Gg(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 pt=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 Le=class{world;localPlayer;config;startFrame;transport;buffer=new pt;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={...ht,...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=Ot(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=Ge(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 Nn=class{world;localPlayer;config;transport;players;buffer=new pt;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={...ht,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(Ot(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(Ot(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=Ge(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=Jt(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 qu(){return globalThis.crypto.randomUUID()}function ds(t,e,n,r,o,i,s,a,l){return t==="rollback"?new Nn({world:e,transport:n,localPlayer:r,players:o,config:s,attach:a,onDesync:l.onDesync}):new Le({world:e,transport:n,localPlayer:r,players:o,startFrame:i,config:s,onDesync:l.onDesync})}function hs(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 Tr=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={...ht,...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=ds(this.config.mode,e,this.transport,this.localPlayer,this.players,0,this.config,this.attach,this.callbacks);return n instanceof Le&&n.onAfterStep(r=>this.serviceSnapshots(r,e)),this.transport.send(de(he({t:"start",players:[...this.players]}))),this.game=hs(e,n,this.localPlayer,this.players,()=>this.unsubscribe()),this.game}dropPlayer(e){let n=this.game?.session;if(!n)return;let r=n instanceof Le?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=Ge(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 ps(t){let e=qu(),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=ds(i.config.mode,h,n,i.player,d,i.startFrame,i.config,t.attach,t);if(i.joins&&p instanceof Le)for(let k of i.joins)p.addPlayer(k.player,k.atFrame);for(let k of u)k.t==="join"&&p instanceof Le&&p.addPlayer(k.player,k.atFrame),k.t==="leave"&&p.removePlayer(k.player,k.atFrame);let f=n.onMessage(k=>{let v=Ge(k);v&&(v.t==="join"&&p instanceof Le?(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=hs(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=Ge(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 fs(t){return new Tr(t)}function cy(t,e,n){let r=t.width??1280,o=t.height??720,i=t.background??"#f3ecdb",s=n.renderer==="canvas"?new ut({width:r,height:o,background:i}):new lt({width:r,height:o,background:i});e.style.position=e.style.position||"relative",s.mount?.(e),Tn(e);let a=new nt(t.inputMap??{},document),l=f=>Pe(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=fs({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"),ps({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 ju=0;function Uu(t,e){return`${t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"game"}-${e.replace(/[:.]/g,"-").toLowerCase()}-${(ju++).toString(36)}`}var ft=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??Uu(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 Gt=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 Mr(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 Xu(){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 vy(t,e,n={}){let r=Xu(),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=Dn(s.tuning,u),m={...c},d=typeof performance<"u"?performance.now():0,h=new ft({game:s.title,seed:l,tuningValues:c,variant:a}),p=!1,f=(D,A)=>{let _=JSON.stringify(D);if(A&&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(()=>{})},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 Gt,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=En(s,e,{...n,world:{seed:l,tuning:u},isHeld:()=>x||(n.isHeld?.()??!1),onAdvance:(D,A,_)=>{for(let B=0;B<A;B++)h.step(_,D.input.axes),I.push(h.frame,D);n.onAdvance?.(D,A,_)},onPause:D=>{h.screen(D?"pause":"resume"),n.onPause?.(D)},onRestart:()=>{g("restart"),h=new ft({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 ft({game:s.title,seed:l,tuningValues:{...m},variant:a,startSnapshot:D}),h.screen("hot-swap")}n.hot?.dispose(D=>{D.hayaoSnap=C.world.snapshot(),Q("hot-swap")}),I.push(0,C.world);async function R(D,A){let _=await fetch(`/__studio/session/${encodeURIComponent(D)}`);if(!_.ok)return;let B=await _.json();x=!0;let j=C.world,ie=Pe(s,{seed:B.seed,tuning:B.tuningValues});j.restore(B.startSnapshot?structuredClone(B.startSnapshot):ie.snapshot()),s.attach?.(j),j.input.axes.clear();let se=B.inputLog.frames,re=Math.max(30,Math.ceil(se.length/220/30)*30);I=new Gt(re),I.push(0,j);let le=0,ce=0;for(let ge=0;ge<se.length;ge++){for(;ce<B.knobEvents.length&&B.knobEvents[ce].frame===ge;){let Ve=B.knobEvents[ce++],ke=j.snapshot();ke.tuning={...ke.tuning,[Ve.key]:Ve.value},j.restore(ke),s.attach?.(j)}for(;le<B.axesLog.length&&B.axesLog[le][0]===ge;){let[,Ve,ke]=B.axesLog[le++];j.input.axes.set(Ve,ke)}j.step(se[ge]),I.push(ge+1,j)}v={session:B,pos:se.length},oe.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 _=performance.now(),B=Math.min(120,Math.floor((_-A)/(1e3/60)));if(B<=0)return;A=_;let j=C.world;for(let ie=0;ie<B;ie++){let se=v.pos;if(se>=D.inputLog.frames.length){T();return}for(let re of D.knobEvents)if(re.frame===se){let le=j.snapshot();le.tuning={...le.tuning,[re.key]:re.value},j.restore(le),s.attach?.(j)}for(let[re,le,ce]of D.axesLog)re===se&&j.input.axes.set(le,ce);j.step(D.inputLog.frames[se]),v.pos=se+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(()=>{}),ur((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),Q=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),ur(null),C.stop()},oe={...C,get world(){return C.world},setKnob(D,A){if(v)return;w(),m[D]=A;let _=C.world.snapshot();_.tuning={...m},C.world.restore(_),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 _=C.world.snapshot().tuning??{};for(let B of Object.keys(m))B in _&&(m[B]=_[B])}x=!1},frozen:()=>v?M===null:x,scrub(D){if(v){T();let _=v.session,B=Mr(C.world,s,I,_.inputLog.frames,_.axesLog,_.knobEvents,D);return B!==null&&(v.pos=B),B}x=!0;let A=Mr(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:()=>Q("navigate")};return window.__studio=oe,oe}var ky="0.4.1";export{Ql as ALBUM,Vc as AMBIENT_PRESETS,Hr as AmbientField,en as AnimationPlayer,rr as AudioBus,Gh as BLOOM_PIPELINE,Ho as BitmapText,Jr as Blend1D,Yr as Blend2D,je as Bone2D,ms as BroadcastChannelTransport,qs as CLIP_CHANNELS,Qt as Camera2D,zr as CameraController,ut as Canvas2DRenderer,Ei as CinematicPlayer,nn as ClipPlayer,Ut as Clock,Hi as Coroutines,sa as DEFAULT_GAMEPAD_MAP,Xn as DEFAULT_INPUT_MAP,Tt as DEFAULT_PLATFORMER,ht as DEFAULT_SESSION_CONFIG,lo as DEFAULT_TILE_CHARS,qn as DUSK,Br as DepthSort,Ae as EASINGS,ne as Edge,Xt as EventBus,Xc as FLOAT_PRESETS,Vo as FONT_5,jr as FloatingText,Gi as Fsm,Gl as GENRES,Ef as GENRE_PROFILES,vo as GamepadSource,_o as HeadlessRenderer,ae as IDENTITY,W as INSTRUMENTS,no as IkTarget,pt as InputBuffer,bo as InputRecorder,on as InputState,Wr as IsoPrism,z as KENTO,nt as KeyboardSource,Bm as LAYER_HUD,Be as LAYER_LIGHT,Wm as LAYER_WORLD,rn as LightLayer,xr as LocalStorageAdapter,Le as LockstepSession,cs as LoopbackHub,Cr as LoopbackTransport,Ui as LootTable,Xs as MEADOW,xo as MOUSE_ACTIONS,yr as MemoryStorage,Ln as NEIGHBORS_4,gr as NEIGHBORS_8,_g as NET_PROTOCOL_VERSION,O as Node,O as Node2D,Or as NodePool,es as NullStorage,Pd as PAD_NEUTRAL,Em as PALETTES,Xh as PANEL_PRESETS,Js as PAPER,Vs as PARTICLE_PRESETS,_r as ParallaxLayer,Vr as Particles,Vi as PhaseClock,Dt as PixelBuffer,Sr as PlayerInput,kt as PointLight,sn as PointerSource,Zi as RingBuffer,ue as Rng,Nn as RollbackSession,Tr as RoomHost,be as SAMPLE_RATE,is as SAVE_FORMAT_VERSION,li as SCALES,os as SaveManager,mr as ScreenTransition,ft as SessionRecorder,qr as Shaker,Rn as Shell,yt as Signal,On as Skeleton,ro as SkeletonDebug,Gt as SnapshotRing,ln as SpatialHash,Yt as Sprite,lt as SvgRenderer,ee as TAU,X as TILE,Kt as Text,Oo as TextureSprite,Zt as Timer,Pi as TouchControls,Qi as UndoStack,ky as VERSION,Ur as VerletChain,pn as WEBGL_EFFECTS,et as WangFrame,bn as WebGL2Renderer,Pn as World,Vu as abilitiesOf,Od as addBody,Kd as addDistanceJoint,Qd as addRevoluteJoint,o0 as addTransition,Hf as albumTrack,jb as all,Sb as analyzePlaytest,Hn as applyChannel,Vd as applyImpulse,mi as applyReverb,gt as applyTransform,Um as asciiEntities,eb as assertAudio,m0 as assertDeterministic,q0 as assertRamp,d0 as assertSnapshotStable,l0 as assertSolvable,Lu as astar,Zb as astarGrid,Je as audio,Vm as autotile4,Hm as autotileToCommands,pg as availableUpgrades,gi as bandBalance,Iu as bfs,sm as blendIssues,ep as blobPath,Jn as bodyAABB,Pa as bodyContains,zb as bootDom,Gn as buildSkeleton,yf as cadenceResolves,fu as cameraIssues,$o as canvasGradient,ct as cellFloat,Ka as cellHash,xp as cellInt,_0 as changeFrames,su as checkDeterministic,pf as chordChanges,Me as chordNotes,Z as clamp,it as clientToDesign,Xr as clipEvents,Bn as clipFinished,nm as clipIssues,We as clipTime,So as collide,at as commandsToSVGInner,Dg as composeCampaign,Fe as composeTransform,Gg as connectWebSocket,Qb as connectedComponents,qm as contourToCommands,Wt as contrastRatio,k0 as createPlanBot,Dd as createPlatformerState,_d as createRigidWorld,ti as createStereo,Pe as createWorld,bi as crestFactorDb,co as cullSegments,Ld as dashJumpDistance,Ls as datan,$e as datan2,or as dbfs,U as dcos,sp as decode2bit,ip as decodeBits,Ge as decodeMessage,ap as decodeRLE,ts as defaultStorage,bb as defineGame,yg as defineLevel,ic as deg2rad,Un as deserializeNode,Ye as dexp,fe as dexp2,G as dhypot,An as diamondPoints,ul as diatonicChord,kg as diffLevels,$l as distanceGain,Dr as dlog,jt as dlog10,bt as dlog2,De as dpow,v0 as drive,yh as dropShadow,q as dsin,Rf as duckGain,de as encodeMessage,lp as encodeRLE,Wp as encodeWav,Rl as estimateTempo,Cf as evalCurve,Ll as featureDistance,Ft as features,uu as feedbackIssues,Cl as fft,Ng as findSoftlocks,B0 as firstFrame,st as fitViewport,Ki as floodFill,fi as fluxEnvelope,lu as forgivenessIssues,Jo as fractalNoise,St as frameActions,Ct as frameAxes,gb as gameInputMap,Sp as generateCave,Ip as generateDungeon,ss as generateLevels,Gu as generateLevelsReport,Ff as genre,xe as getBody,Zd as getJoint,gh as glow,D0 as graceWindowIssues,Fm as gradient,Yn as gradientDef,Ya as gridAt,Om as gridFromRows,ze as gridSet,gp as gridToTilemap,aa as groundAt,dc as hashNoise,$r as hashString,Jt as hashValue,Ks as hexToHsl,Mn as hideScreen,p0 as hold,fs as hostRoom,Ys as hsl,$m as hsv,Wd as inVisionCone,dg as initDirector,G0 as inputDensity,$i as installCapture,Ir as invLerp,cn as invalidCommandReason,Ee as invertTransform,Li as isCaptureMode,Pp as isGround,wh as isLightCommand,O0 as isMonotonic,cc as iso,ps as joinRoom,ua as jumpAirtime,ca as jumpDistance,Id as jumpHeight,xu as keyMentions,yo as keysToActions,mb as knob,Mf as layerGains,N0 as layoutIssues,Ua as layoutText,Ne as lerp,Ac as lerpDamp,Mg as levelFromSeed,xg as levelIssues,vg as levelReachable,wr as levelToTilemap,hu as lightingIssues,fa as lineOfSight,fh as linearGradient,gf as lintSong,V0 as longestLull,bu as lookAheadIssues,Nt as magnitudeSpectrum,It as makeGrid,Wc as makeReach,qe as makeTransform,Ym as mapHeight,Jm as mapWidth,na as marchingSquaresCases,jn as marchingSquaresContours,ao as mask4,Gm as mask8,vf as matchReport,Et as measureLine,pp as measureText,Ot as mergePlayerFrames,ll as midiToFreq,jp as midiToName,F0 as missingControlHints,Im as mix,wt as mixLinear,ni as mixMono,_n as mixPose,an as moveRect,Nm as mutateColor,he as netMessage,Hb as nextStep,Uh as nineSlice,oi as normalize,me as noteToMidi,td as occludersFromTilemap,Ml as onsetDensity,Zn as openVoicing,sg as packVarints,Nl as panFromOffset,nl as panGains,ot as parseLightRun,ja as parseRich,rs as parseSnapshot,eg as passableFromTilemap,rl as peak,pi as peakAmp,Ji as pickEntry,ai as pitchToFreq,Ha as pixelsToCommands,wg as platformerReachable,$n as playerAction,Wg as playerIds,Bg as playerInput,mh as pointQuery,hg as pollDirector,Hd as polygonBox,tn as poseKey,mt as progression,kr as progressionPuzzle,Lg as proveCompletable,$g as proveFullCompletion,g0 as pump,go as quantizeAngle,qb as race,sc as rad2deg,bh as radialGradient,ku as rampIssues,wu as rampStats,dh as rayCastRigid,pa as raycastTiles,Hu as reachableRegions,Kb as reconstructPath,W0 as recordTimeline,Xe as rectBlocked,ac as rectContains,lc as rectsOverlap,Ce as registerNode,_s as regularPolyPoints,Qh as regularPolygon,Oe as relLuminance,oc as remap,Gd as removeBody,eh as removeJoint,Z0 as renderAudioFilmstrip,X0 as renderFilmstrip,hi as renderSong,yn as renderSound,dn as renderToSVGString,Ii as replay,_i as replaySession,Fr as resetNodeIds,Bf as resetZzfxWarnings,Vn as resolveTracks,Dn as resolveTuning,ah as rigidStep,ig as rleDecode,og as rleEncode,$t as rms,Ko as roomCenter,xn as rootless,En as runBrowser,cy as runBrowserNet,I0 as runFeelGates,yb as runHeadless,vy as runStudio,mu as salienceIssues,tm as sampleClip,io as sampleGradient,zn as samplePose,Ke as sampleTrack,Qn as scaleMidis,ui as scalePitchClasses,Qa as scatter,vp as scatterCells,If as scoreTrack,s0 as screenRect,au as scriptToFrames,b0 as scriptedPlaythrough,Mr as scrubTo,Au as serializeSnapshot,z0 as series,Tn as setOverlayHost,ur as setScreenObserver,_e as settings,Ar as shadeHex,Io as shadowDef,mo as shadowQuads,Lo as shapeBBox,Ni as shapeBox,Si as showScreen,Bp as signalHash,Gb as sleep,Va as smoothClosedPath,tp as smoothOpenPath,Lr as smoothstep,tt as snapAxis,ei as softClip,ri as softClipInPlace,Uo as solidNeighbours,dt as solve,to as solveFabrik,To as solveJoint,eo as solveTwoBoneIK,gl as songBeats,nr as songDuration,Ze as sortCommands,Tf as spatialMix,zf as specFromZzfx,Tl as spectralCentroid,rt as splitByLightLayer,Os as spring,Gs as springStep,Zh as star,S0 as steer2D,Ed as stepPlatformer,Ap as stereoDuration,Fp as stereoFrames,Fl as stereoWidth,_u as subSeed,E0 as telegraphIssues,Yo as terrainHeight,Rp as terrainSlice,gu as textBox,Ja as textToCommands,pe as tileAt,Xm as tileAtPoint,zu as tileCenter,uo as tilemapFromAscii,Mi as toggleFullscreen,Up as transpose,Xa as typewriterCount,ag as unpackVarints,Qu as vadd,Fg as validateWorld,Za as valueNoise,nc as vdist,tc as vdot,Ku as vec2,Ws as vlen,rc as vnorm,Lt as voiceLead,ec as vscale,Zu as vsub,f0 as wait,Vb as waitFor,ve as wakeBody,ta as wangTile,Mt as warnCommandOnce,Hs as weatherEnvelope,Xi as weightedIndex,Xb as weightedPick,i0 as wipeStep,Lm as withAlpha,Te as worldPoints,kl as zcr};