@datamoc/mw_games 0.7.7 → 0.7.8

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 (144) hide show
  1. package/CHANGELOG.md +92 -3
  2. package/README.md +7 -7
  3. package/dist/actors/Shop.d.ts.map +1 -1
  4. package/dist/actors/Shop.js +4 -1
  5. package/dist/actors/Shop.js.map +1 -1
  6. package/dist/ai/Heuristics.d.ts +8 -0
  7. package/dist/ai/Heuristics.d.ts.map +1 -1
  8. package/dist/ai/Heuristics.js.map +1 -1
  9. package/dist/ai/index.d.ts +2 -2
  10. package/dist/ai/index.d.ts.map +1 -1
  11. package/dist/ai/index.js +1 -1
  12. package/dist/ai/index.js.map +1 -1
  13. package/dist/ai/lua.d.ts +21 -0
  14. package/dist/ai/lua.d.ts.map +1 -1
  15. package/dist/ai/lua.js +21 -0
  16. package/dist/ai/lua.js.map +1 -1
  17. package/dist/ai/score.d.ts +36 -0
  18. package/dist/ai/score.d.ts.map +1 -1
  19. package/dist/ai/score.js +26 -0
  20. package/dist/ai/score.js.map +1 -1
  21. package/dist/battle/BattleStats.d.ts.map +1 -1
  22. package/dist/battle/BattleStats.js.map +1 -1
  23. package/dist/board/Classics.d.ts.map +1 -1
  24. package/dist/board/Classics.js +51 -39
  25. package/dist/board/Classics.js.map +1 -1
  26. package/dist/board/HexSkirmish.d.ts.map +1 -1
  27. package/dist/board/HexSkirmish.js +69 -20
  28. package/dist/board/HexSkirmish.js.map +1 -1
  29. package/dist/board/Tactics.d.ts +7 -0
  30. package/dist/board/Tactics.d.ts.map +1 -1
  31. package/dist/board/Tactics.js +2 -2
  32. package/dist/board/Tactics.js.map +1 -1
  33. package/dist/core/Achievements.d.ts.map +1 -1
  34. package/dist/core/Achievements.js +3 -1
  35. package/dist/core/Achievements.js.map +1 -1
  36. package/dist/mw_games.global.js +20 -20
  37. package/dist/mwl/actors.d.ts +46 -2
  38. package/dist/mwl/actors.d.ts.map +1 -1
  39. package/dist/mwl/actors.js +46 -2
  40. package/dist/mwl/actors.js.map +1 -1
  41. package/dist/mwl/carryover.d.ts +7 -0
  42. package/dist/mwl/carryover.d.ts.map +1 -1
  43. package/dist/mwl/carryover.js +7 -0
  44. package/dist/mwl/carryover.js.map +1 -1
  45. package/dist/mwl/catalog.d.ts +10 -1
  46. package/dist/mwl/catalog.d.ts.map +1 -1
  47. package/dist/mwl/catalog.js +10 -1
  48. package/dist/mwl/catalog.js.map +1 -1
  49. package/dist/mwl/compiler.d.ts +70 -3
  50. package/dist/mwl/compiler.d.ts.map +1 -1
  51. package/dist/mwl/compiler.js +70 -3
  52. package/dist/mwl/compiler.js.map +1 -1
  53. package/dist/mwl/conditions.d.ts +10 -1
  54. package/dist/mwl/conditions.d.ts.map +1 -1
  55. package/dist/mwl/conditions.js +10 -1
  56. package/dist/mwl/conditions.js.map +1 -1
  57. package/dist/mwl/content.d.ts +11 -0
  58. package/dist/mwl/content.d.ts.map +1 -1
  59. package/dist/mwl/content.js +11 -0
  60. package/dist/mwl/content.js.map +1 -1
  61. package/dist/mwl/expression.d.ts +21 -0
  62. package/dist/mwl/expression.d.ts.map +1 -1
  63. package/dist/mwl/expression.js +21 -0
  64. package/dist/mwl/expression.js.map +1 -1
  65. package/dist/mwl/fengari.d.ts +12 -1
  66. package/dist/mwl/fengari.d.ts.map +1 -1
  67. package/dist/mwl/fengari.js +12 -1
  68. package/dist/mwl/fengari.js.map +1 -1
  69. package/dist/mwl/grammar.d.ts +45 -1
  70. package/dist/mwl/grammar.d.ts.map +1 -1
  71. package/dist/mwl/grammar.js +45 -1
  72. package/dist/mwl/grammar.js.map +1 -1
  73. package/dist/mwl/hooks.d.ts +45 -1
  74. package/dist/mwl/hooks.d.ts.map +1 -1
  75. package/dist/mwl/hooks.js +45 -1
  76. package/dist/mwl/hooks.js.map +1 -1
  77. package/dist/mwl/index.d.ts +1 -1
  78. package/dist/mwl/index.d.ts.map +1 -1
  79. package/dist/mwl/index.js +1 -1
  80. package/dist/mwl/index.js.map +1 -1
  81. package/dist/mwl/persistence.d.ts +32 -0
  82. package/dist/mwl/persistence.d.ts.map +1 -1
  83. package/dist/mwl/persistence.js +32 -0
  84. package/dist/mwl/persistence.js.map +1 -1
  85. package/dist/mwl/readers.d.ts +24 -2
  86. package/dist/mwl/readers.d.ts.map +1 -1
  87. package/dist/mwl/readers.js +27 -4
  88. package/dist/mwl/readers.js.map +1 -1
  89. package/dist/mwl/report.d.ts +21 -2
  90. package/dist/mwl/report.d.ts.map +1 -1
  91. package/dist/mwl/report.js +21 -2
  92. package/dist/mwl/report.js.map +1 -1
  93. package/dist/mwl/runtime.d.ts +72 -0
  94. package/dist/mwl/runtime.d.ts.map +1 -1
  95. package/dist/mwl/runtime.js +266 -68
  96. package/dist/mwl/runtime.js.map +1 -1
  97. package/dist/mwl/schema.d.ts +57 -1
  98. package/dist/mwl/schema.d.ts.map +1 -1
  99. package/dist/mwl/schema.js +85 -4
  100. package/dist/mwl/schema.js.map +1 -1
  101. package/dist/mwl/scripts.d.ts +12 -1
  102. package/dist/mwl/scripts.d.ts.map +1 -1
  103. package/dist/mwl/scripts.js +12 -1
  104. package/dist/mwl/scripts.js.map +1 -1
  105. package/dist/mwl/utils.d.ts +2 -0
  106. package/dist/mwl/utils.d.ts.map +1 -1
  107. package/dist/mwl/utils.js +4 -1
  108. package/dist/mwl/utils.js.map +1 -1
  109. package/dist/rpg/GameState.d.ts +2 -2
  110. package/dist/rpg/GameState.js +2 -2
  111. package/dist/two-d/render/ColorTransformBatcher.d.ts +7 -1
  112. package/dist/two-d/render/ColorTransformBatcher.d.ts.map +1 -1
  113. package/dist/two-d/render/ColorTransformBatcher.js +10 -1
  114. package/dist/two-d/render/ColorTransformBatcher.js.map +1 -1
  115. package/dist/two-d/render/ImageModifiers.d.ts.map +1 -1
  116. package/dist/two-d/render/ImageModifiers.js +20 -4
  117. package/dist/two-d/render/ImageModifiers.js.map +1 -1
  118. package/dist/two-d/render/TerrainGraphics.d.ts.map +1 -1
  119. package/dist/two-d/render/TerrainGraphics.js.map +1 -1
  120. package/dist/two-d/render/TerrainGraphicsLayer.d.ts +55 -0
  121. package/dist/two-d/render/TerrainGraphicsLayer.d.ts.map +1 -0
  122. package/dist/two-d/render/TerrainGraphicsLayer.js +54 -0
  123. package/dist/two-d/render/TerrainGraphicsLayer.js.map +1 -0
  124. package/dist/two-d/render/TintedSprite.js +2 -2
  125. package/dist/two-d/render/TintedSprite.js.map +1 -1
  126. package/dist/two-d/render/index.d.ts +3 -1
  127. package/dist/two-d/render/index.d.ts.map +1 -1
  128. package/dist/two-d/render/index.js +1 -0
  129. package/dist/two-d/render/index.js.map +1 -1
  130. package/dist/two-d/ui/MarkupText.d.ts +53 -0
  131. package/dist/two-d/ui/MarkupText.d.ts.map +1 -0
  132. package/dist/two-d/ui/MarkupText.js +122 -0
  133. package/dist/two-d/ui/MarkupText.js.map +1 -0
  134. package/dist/two-d/ui/index.d.ts +4 -2
  135. package/dist/two-d/ui/index.d.ts.map +1 -1
  136. package/dist/two-d/ui/index.js +2 -1
  137. package/dist/two-d/ui/index.js.map +1 -1
  138. package/dist/two-d/ui/markup.d.ts +54 -0
  139. package/dist/two-d/ui/markup.d.ts.map +1 -1
  140. package/dist/two-d/ui/markup.js +49 -1
  141. package/dist/two-d/ui/markup.js.map +1 -1
  142. package/dist/version.d.ts +1 -1
  143. package/dist/version.js +1 -1
  144. package/package.json +1 -1
@@ -1,4 +1,4 @@
1
- var mw_games=(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var t=Object.create,n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.getPrototypeOf,o=Object.prototype.hasOwnProperty,s=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(e){throw n=[e],e}},c=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),l=(e,t)=>{let r={};for(var i in e)n(r,i,{get:e[i],enumerable:!0});return t||n(r,Symbol.toStringTag,{value:`Module`}),r},u=(e,t,a,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var c=i(t),l=0,u=c.length,d;l<u;l++)d=c[l],!o.call(e,d)&&d!==a&&n(e,d,{get:(e=>t[e]).bind(null,d),enumerable:!(s=r(t,d))||s.enumerable});return e},d=(e,r,i)=>(i=e==null?{}:t(a(e)),u(r||!e||!e.__esModule||!o.call(e,`default`)?n(i,`default`,{value:e,enumerable:!0}):i,e)),f=`0.7.7`,p=class{constructor(e=!1){this.listeners=[],this.stackMode=e}add(e){this.listeners.includes(e)||(this.stackMode?this.listeners.unshift(e):this.listeners.push(e))}remove(e){let t=this.listeners.indexOf(e);t!==-1&&this.listeners.splice(t,1)}removeAll(){this.listeners.length=0}get size(){return this.listeners.length}dispatch(e){let t=this.listeners.slice();for(let n of t)if(this.listeners.includes(n)&&n(e)===!0)return!0;return!1}},m=class{constructor(){this.onDestroy=new p,this.destroyed=!1}update(e){}resize(e,t){}onSuspend(){}onResume(e){}destroy(){this.destroyed||(this.destroyed=!0,this.onDestroy.dispatch(),this.onDestroy.removeAll(),this.teardown())}teardown(){}get isDestroyed(){return this.destroyed}},h=class{constructor(){this.scenes=[]}get current(){return this.scenes.length===0?null:this.scenes[this.scenes.length-1]}get depth(){return this.scenes.length}replace(e){for(let e of this.scenes)e.destroy();this.scenes=[e],e.create()}push(e){this.current?.onSuspend(),this.scenes.push(e),e.create()}pop(e){if(this.scenes.length<=1)throw Error(`cannot pop the last scene off the stack - switchScene somewhere instead`);this.scenes.pop()?.destroy(),this.current?.onResume(e)}update(e){this.current?.update(e)}resize(e,t){for(let n of this.scenes)n.resize(e,t)}destroy(){for(let e of this.scenes)e.destroy();this.scenes=[]}},g=class{constructor(){this.items=new Map}register(e,t){if(this.items.has(e))throw Error(`"${e}" is already registered`);this.items.set(e,t)}get(e){let t=this.items.get(e);if(t===void 0)throw Error(`no registration named "${e}"`);return t}has(e){return this.items.has(e)}list(){return[...this.items.keys()]}},_=class{constructor(){this.order=[],this.registry=new g}add(e,t){this.registry.register(e.name,e),this.order.push(e),e.create?.(t)}has(e){return this.registry.has(e)}get(e){return this.registry.get(e)}update(e,t){for(let n of this.order)n.update?.(e,t)}resize(e,t,n){for(let r of this.order)r.resize?.(e,t,n)}onSuspend(e){for(let t of this.order)t.onSuspend?.(e)}onResume(e,t){for(let n of this.order)n.onResume?.(e,t)}destroy(e){for(let t=this.order.length-1;t>=0;t--)this.order[t].destroy?.(e);this.order=[],this.registry=new g}},v={debug:0,info:1,warn:2,error:3},y=class{constructor(e,t={}){if(!e)throw Error(`a logger needs a category`);this.category=e,this.level=t.level??`debug`,this.sink=t.sink??b}setLevel(e){this.level=e}debug(e,t){this.write(`debug`,e,t)}info(e,t){this.write(`info`,e,t)}warn(e,t){this.write(`warn`,e,t)}error(e,t){this.write(`error`,e,t)}write(e,t,n){v[e]<v[this.level]||this.sink({level:e,category:this.category,message:t,data:n,time:Date.now()})}};function b(e){let t=`[${e.category}] ${e.message}`;e.level===`debug`?console.debug(t,e.data??``):e.level===`info`?console.info(t,e.data??``):e.level===`warn`?console.warn(t,e.data??``):console.error(t,e.data??``)}var x=class{constructor(){this.hooks=[]}on(e,t,n){this.hooks.push({event:e,handler:t,source:n})}off(e){this.hooks=this.hooks.filter(t=>t.handler!==e)}offSource(e){this.hooks=this.hooks.filter(t=>t.source!==e)}emit(e,...t){for(let n of[...this.hooks])n.event===e&&n.handler(...t)}get size(){return this.hooks.length}clear(){this.hooks=[]}},S=l({Generator:()=>w,MersenneTwister:()=>he,RandomStreams:()=>_e,chance:()=>oe,element:()=>se,float:()=>O,int:()=>k,normalRange:()=>ae,pop:()=>te,push:()=>ee,range:()=>ie,reset:()=>re,shuffle:()=>le,weighted:()=>ce,weightedKey:()=>A,withSeed:()=>ne});function C(e){let t=e>>>0;return()=>{t=t+2654435769>>>0;let e=t;return e=Math.imul(e^e>>>16,569420461),e=Math.imul(e^e>>>15,1935289751),(e^e>>>15)>>>0}}var w=class{constructor(e){this.s0=0,this.s1=0,this.s2=0,this.s3=0,this.seed=e===void 0?Math.random()*4294967296>>>0:e>>>0;let t=C(this.seed);this.s0=t(),this.s1=t(),this.s2=t(),this.s3=t(),(this.s0|this.s1|this.s2|this.s3)===0&&(this.s0=1)}nextUint32(){let e=Math.imul(T(Math.imul(this.s1,5),7),9)>>>0>>>0,t=this.s1<<9>>>0;return this.s2^=this.s0,this.s3^=this.s1,this.s1^=this.s2,this.s0^=this.s3,this.s2^=t,this.s3=T(this.s3,11),e}float(){return this.nextUint32()/4294967296}int(e){if(e<=0)return 0;let t=4294967296-4294967296%e,n=this.nextUint32();for(;n>=t;)n=this.nextUint32();return n%e}getState(){return[this.s0,this.s1,this.s2,this.s3]}setState(e){[this.s0,this.s1,this.s2,this.s3]=e}};function T(e,t){return(e<<t|e>>>32-t)>>>0}var E=[new w],D=()=>E[E.length-1];function ee(e){let t=new w(e);return E.push(t),t}function te(){if(E.length===1)throw Error(`the base random generator cannot be popped`);E.pop()}function ne(e,t){ee(e);try{return t()}finally{te()}}function re(){E.length=0,E.push(new w)}function O(e,t){return e===void 0?D().float():t===void 0?D().float()*e:e+D().float()*(t-e)}function k(e,t){return t===void 0?D().int(e):e+D().int(t-e)}function ie(e,t){return e+D().int(t-e+1)}function ae(e,t){return e+Math.floor((D().float()+D().float())*(t-e+1)/2)}function oe(e){return D().float()<e}function se(e){return e.length>0?e[D().int(e.length)]:null}function ce(e){let t=0;for(let n of e)t+=n;if(t<=0)return null;let n=D().float()*t;for(let t=0;t<e.length;t++)if(n-=e[t],n<0)return t;return e.length-1}function A(e){let t=[...e.keys()],n=ce(t.map(t=>e.get(t)??0));return n===null?null:t[n]}function le(e){for(let t=e.length-1;t>0;t--){let n=D().int(t+1);[e[t],e[n]]=[e[n],e[t]]}return e}var ue=624,de=397,fe=2567483615,pe=2147483648,me=2147483647,he=class{constructor(e=5489){this.state=new Uint32Array(ue),this.index=ue,this.seedValue=5489,this.produced=0,this.seed(e)}seed(e){this.seedValue=e>>>0,this.state[0]=this.seedValue;for(let e=1;e<ue;e++){let t=this.state[e-1]^this.state[e-1]>>>30;this.state[e]=Math.imul(1812433253,t)+e>>>0}this.index=ue,this.produced=0}generate(){for(let e=0;e<ue;e++){let t=this.state[e]&pe|this.state[(e+1)%ue]&me,n=this.state[(e+de)%ue]^t>>>1;t&1&&(n^=fe),this.state[e]=n>>>0}this.index=0}nextUint32(){this.index>=ue&&this.generate();let e=this.state[this.index++];return e^=e>>>11,e^=e<<7&2636928640,e^=e<<15&4022730752,e^=e>>>18,this.produced++,e>>>0}float(){return this.nextUint32()/4294967296}int(e){if(e<=0)return 0;let t=4294967296-4294967296%e,n=this.nextUint32();for(;n>=t;)n=this.nextUint32();return n%e}discard(e){for(let t=0;t<e;t++)this.nextUint32()}get discardCount(){return this.produced}getState(){return{seed:this.seedValue,state:[...this.state],index:this.index,discard:this.produced}}setState(e){this.seedValue=e.seed>>>0;for(let t=0;t<ue;t++)this.state[t]=(e.state[t]??0)>>>0;this.index=e.index,this.produced=e.discard}};function ge(e){let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t=Math.imul(t,16777619)>>>0;return t>>>0}var _e=class{constructor(e=0){this.streams=new Map,this.baseSeed=e>>>0}stream(e){let t=this.streams.get(e);if(!t){let n=(this.baseSeed^ge(e))>>>0;t={seed:n,engine:new he(n)},this.streams.set(e,t)}return t.engine}seedOf(e){return this.streams.get(e)?.seed}reseed(e){this.baseSeed=e>>>0,this.streams.clear()}names(){return[...this.streams.keys()]}getState(){let e={};for(let[t,n]of this.streams)e[t]=n.engine.getState();return e}setState(e){for(let[t,n]of Object.entries(e)){let e=new he(n.seed);e.setState(n),this.streams.set(t,{seed:n.seed,engine:e})}}},ve=l({DEFAULT_BINDINGS:()=>Pe,actionsForKey:()=>Le,attach:()=>vt,attachSwipe:()=>_t,bind:()=>Fe,bindAxis:()=>ct,bindButton:()=>st,bindTouch:()=>ft,detach:()=>yt,dispatchComposition:()=>ke,dispatchText:()=>Oe,endFrame:()=>Ye,exportBindings:()=>Be,gamepadAxisCode:()=>ot,gamepadButtonCode:()=>at,importBindings:()=>Ve,isDown:()=>Ke,justPressed:()=>qe,justReleased:()=>Je,keysFor:()=>ze,onAction:()=>Ce,onComposition:()=>Ee,onKey:()=>we,onText:()=>Te,onWheel:()=>Ae,pollGamepads:()=>lt,pressTouch:()=>pt,releaseTouch:()=>mt,resetBindings:()=>He,rumble:()=>ut,textFromKey:()=>De,touchCode:()=>dt,unbind:()=>Re,wheelActionFor:()=>je}),ye=new Map,be=new Set,xe=new Set,Se=new Set,Ce=new p(!0),we=new p(!0),Te=new p(!0),Ee=new p(!0);function De(e){return e.isComposing||e.ctrlKey||e.metaKey||e.altKey?null:e.key.length===1?e.key:null}function Oe(e){e.length>0&&Te.dispatch(e)}function ke(e){Ee.dispatch({phase:e.phase,text:e.text})}var Ae=new p(!0);function je(e){return e.ctrlKey||e.metaKey?`zoom`:e.shiftKey?`scrollHorizontal`:`scroll`}function Me(e){let t=je(e);t===`zoom`&&e.preventDefault();let n=t===`scrollHorizontal`&&e.deltaX!==0?e.deltaX:e.deltaY;Ae.dispatch({action:t,delta:n})}var Ne=!1,Pe={up:[`ArrowUp`,`KeyW`,`Numpad8`],down:[`ArrowDown`,`KeyS`,`Numpad2`],left:[`ArrowLeft`,`KeyA`,`Numpad4`],right:[`ArrowRight`,`KeyD`,`Numpad6`],upLeft:[`Numpad7`],upRight:[`Numpad9`],downLeft:[`Numpad1`],downRight:[`Numpad3`],wait:[`Numpad5`,`Period`],confirm:[`Enter`,`Space`,`NumpadEnter`],cancel:[`Escape`,`Backspace`],menu:[`KeyI`,`Tab`]};function Fe(e,t){ye.set(e,new Set(t))}function Ie(e,t){let n=ye.get(e)??new Set;for(let e of t)n.add(e);ye.set(e,n)}function Le(e){return Ue(e)}function Re(e){ye.delete(e)}function ze(e){return[...ye.get(e)??[]]}function Be(){let e={};for(let[t,n]of ye)e[t]=[...n];return e}function Ve(e){ye.clear();for(let[t,n]of Object.entries(e))Fe(t,n)}function He(){Ve(Pe)}He();function Ue(e){let t=[];for(let[n,r]of ye)r.has(e)&&t.push(n);return t}function We(e){if(!be.has(e)){be.add(e);for(let t of Ue(e))xe.add(t),Ce.dispatch(t)}}function Ge(e){if(be.has(e)){be.delete(e);for(let t of Ue(e))Se.add(t)}}function Ke(e){let t=ye.get(e);if(!t)return!1;for(let e of t)if(be.has(e))return!0;return!1}function qe(e){return xe.has(e)}function Je(e){return Se.has(e)}function Ye(){xe.clear(),Se.clear()}function Xe(e){let t=De(e);t!==null&&Oe(t)}function Ze(e){if(e.repeat){we.dispatch(e),Xe(e);return}We(e.code),we.dispatch(e),Xe(e)}function Qe(e){Ge(e.code)}function $e(e){ke({phase:`start`,text:e.data??``})}function et(e){ke({phase:`update`,text:e.data??``})}function tt(e){ke({phase:`end`,text:e.data??``})}function nt(){be.clear(),xe.clear(),Se.clear()}var rt=.5,it=new Set;function at(e,t){return`Gamepad${e}Button${t}`}function ot(e,t,n){return`Gamepad${e}Axis${t}${n>0?`+`:`-`}`}function st(e,t,n){Ie(e,n.map(e=>at(t,e)))}function ct(e,t,n,r){Ie(e,[ot(t,n,r)])}function lt(e=typeof navigator?.getGamepads==`function`?navigator.getGamepads():[]){it.clear();for(let t of e)if(t){for(let e=0;e<t.buttons.length;e++)t.buttons[e].pressed&&it.add(at(t.index,e));for(let e=0;e<t.axes.length;e++){let n=t.axes[e];n>=rt?it.add(ot(t.index,e,1)):n<=-.5&&it.add(ot(t.index,e,-1))}}for(let e of it)We(e);for(let e of be)it.has(e)||!e.startsWith(`Gamepad`)||Ge(e)}function ut(e,t,n=typeof navigator?.getGamepads==`function`?navigator.getGamepads():[]){(n[e]?.vibrationActuator)?.playEffect(`dual-rumble`,{duration:t.duration,weakMagnitude:t.weakMagnitude??1,strongMagnitude:t.strongMagnitude??1})}function dt(e){return`Touch:${e}`}function ft(e,t=e){Ie(e,[dt(t)])}function pt(e){We(dt(e))}function mt(e){Ge(dt(e))}var ht={up:`up`,down:`down`,left:`left`,right:`right`,upLeft:`upLeft`,upRight:`upRight`,downLeft:`downLeft`,downRight:`downRight`},gt=[`right`,`downRight`,`down`,`downLeft`,`left`,`upLeft`,`up`,`upRight`];function _t(e,t={}){let n={...ht,...t.actions},r=t.minDistance??24;for(let e of[...gt,`tap`]){let t=n[e];t&&ft(t,`swipe:${e}`)}let i=!1,a=-1,o=0,s=0;function c(e){pt(`swipe:${e}`),mt(`swipe:${e}`)}function l(e){i=!0,a=e.pointerId,o=e.clientX,s=e.clientY}function u(e){if(!i||e.pointerId!==a)return;i=!1;let t=e.clientX-o,l=e.clientY-s;if(Math.hypot(t,l)<r){n.tap&&c(`tap`);return}let u=gt[(Math.round(Math.atan2(l,t)/(Math.PI/4))%8+8)%8];n[u]&&c(u)}return e.addEventListener(`pointerdown`,l),e.addEventListener(`pointerup`,u),e.addEventListener(`pointercancel`,u),()=>{e.removeEventListener(`pointerdown`,l),e.removeEventListener(`pointerup`,u),e.removeEventListener(`pointercancel`,u)}}function vt(e=window){Ne||(Ne=!0,e.addEventListener(`keydown`,Ze),e.addEventListener(`keyup`,Qe),e.addEventListener(`compositionstart`,$e),e.addEventListener(`compositionupdate`,et),e.addEventListener(`compositionend`,tt),window.addEventListener(`blur`,nt),e.addEventListener(`wheel`,Me,{passive:!1}))}function yt(e=window){Ne&&(Ne=!1,e.removeEventListener(`keydown`,Ze),e.removeEventListener(`keyup`,Qe),e.removeEventListener(`compositionstart`,$e),e.removeEventListener(`compositionupdate`,et),e.removeEventListener(`compositionend`,tt),e.removeEventListener(`wheel`,Me),window.removeEventListener(`blur`,nt),nt())}var bt=class{constructor(e,t={}){if(!e)throw Error(`a player needs a non-empty id`);this.id=e,this.padIndex=t.padIndex}scoped(e){return`${this.id}:${e}`}bind(e,t){Fe(this.scoped(e),t)}bindButton(e,t){if(this.padIndex===void 0)throw Error(`player "${this.id}" has no padIndex to bind a gamepad button to`);st(this.scoped(e),this.padIndex,t)}bindAxis(e,t,n){if(this.padIndex===void 0)throw Error(`player "${this.id}" has no padIndex to bind a gamepad axis to`);ct(this.scoped(e),this.padIndex,t,n)}bindTouch(e,t=e){ft(this.scoped(e),`${this.id}:${t}`)}pressTouch(e){pt(`${this.id}:${e}`)}releaseTouch(e){mt(`${this.id}:${e}`)}isDown(e){return Ke(this.scoped(e))}justPressed(e){return qe(this.scoped(e))}justReleased(e){return Je(this.scoped(e))}keysFor(e){return ze(this.scoped(e))}};function xt(e,t){if(!t)throw Error(`scramble needs a non-empty key`);let n=new TextEncoder().encode(e),r=new TextEncoder().encode(t),i=new Uint8Array(n.length);for(let e=0;e<n.length;e++)i[e]=n[e]^r[e%r.length];return Ct(i)}function St(e,t){if(!t)throw Error(`scramble needs a non-empty key`);let n=wt(e),r=new TextEncoder().encode(t),i=new Uint8Array(n.length);for(let e=0;e<n.length;e++)i[e]=n[e]^r[e%r.length];return new TextDecoder(`utf-8`,{fatal:!0}).decode(i)}function Ct(e){let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t)}function wt(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}var Tt=10485760;function Et(e,t={}){let n=t.maxBytes??Tt,r=typeof e==`string`?new TextEncoder().encode(e).length:e.length;if(r>n)throw Error(`inbound data exceeds the ${n}-byte limit (${r} bytes)`)}function Dt(e){for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n!==9&&n!==10&&n!==13&&(n<=31||n===127))throw Error(`inbound data contains a control character (0x${n.toString(16).padStart(2,`0`)}) at index ${t}`)}}function Ot(e,t={}){return Et(e,t),Dt(e),e}var kt=new Set([`__proto__`,`constructor`,`prototype`]);function At(e,t,n=`$`){if(e===void 0){if(t.optional)return;throw Error(`${n} is required`)}switch(t.type){case`string`:if(typeof e!=`string`)throw Error(`${n} must be a string`);return;case`number`:if(typeof e!=`number`||!Number.isFinite(e))throw Error(`${n} must be a finite number`);if(t.min!==void 0&&e<t.min)throw Error(`${n} must be >= ${t.min}`);if(t.max!==void 0&&e>t.max)throw Error(`${n} must be <= ${t.max}`);return;case`boolean`:if(typeof e!=`boolean`)throw Error(`${n} must be a boolean`);return;case`array`:if(!Array.isArray(e))throw Error(`${n} must be an array`);if(t.maxLength!==void 0&&e.length>t.maxLength)throw Error(`${n} exceeds its maximum length of ${t.maxLength}`);e.forEach((e,r)=>At(e,t.items,`${n}[${r}]`));return;case`object`:if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`${n} must be an object`);for(let t of Object.keys(e))if(kt.has(t))throw Error(`${n} contains a forbidden key "${t}"`);for(let[r,i]of Object.entries(t.fields))At(e[r],i,`${n}.${r}`);return}}var jt=class{constructor(){this.data=new Map}read(e){return this.data.get(e)??null}write(e,t){this.data.set(e,t)}remove(e){this.data.delete(e)}keys(){return[...this.data.keys()]}};function Mt(){return typeof localStorage>`u`?new jt:{read:e=>localStorage.getItem(e),write:(e,t)=>localStorage.setItem(e,t),remove:e=>localStorage.removeItem(e),keys:()=>Object.keys(localStorage)}}var Nt=class{constructor(e){this.namespace=e.namespace,this.version=e.version,this.migrations=e.migrations??{},this.storage=e.storage??Mt()}key(e){return`mwg-save:${this.namespace}:${e}`}save(e,t,n){let r={meta:{version:this.version,savedAt:Date.now(),preview:n},state:t};this.storage.write(this.key(e),JSON.stringify(r))}load(e){let t=this.storage.read(this.key(e));if(!t)return null;let n=JSON.parse(t),r=n.state;for(let e=n.meta.version;e<this.version;e++)r=(this.migrations[e]??(e=>e))(r);return{meta:{...n.meta,version:this.version},state:r}}importExternal(e,t,n,r){Et(t);let i=n(t);for(let e=0;e<this.version;e++)i=(this.migrations[e]??(e=>e))(i);let a={meta:{version:this.version,savedAt:Date.now(),preview:r},state:i};this.storage.write(this.key(e),JSON.stringify(a))}delete(e){this.storage.remove(this.key(e))}exportSlot(e,t){let n=this.storage.read(this.key(e));return n===null?null:t?xt(n,t):n}importSlot(e,t,n){Et(t);let r=n?St(t,n):t,i=JSON.parse(Ot(r)),a=i.state;for(let e=i.meta.version;e<this.version;e++)a=(this.migrations[e]??(e=>e))(a);let o={meta:{...i.meta,version:this.version},state:a};this.storage.write(this.key(e),JSON.stringify(o))}list(){let e=`mwg-save:${this.namespace}:`,t=[];for(let n of this.storage.keys()){if(!n.startsWith(e))continue;let r=this.storage.read(n);r&&t.push({slot:n.slice(e.length),meta:JSON.parse(r).meta})}return t}},Pt=class{constructor(){this.extensions=new Map}register(e){if(!/^[A-Za-z_][A-Za-z0-9_.-]*$/.test(e.id))throw Error(`invalid state extension id: ${e.id}`);if(this.extensions.has(e.id))throw Error(`state extension already registered: ${e.id}`);return this.extensions.set(e.id,{id:e.id,capture:()=>e.capture(),restore:t=>e.restore(t),version:e.version??1,migrations:e.migrations,reset:e.reset,remove:e.remove}),()=>this.extensions.delete(e.id)}snapshot(){let e={};for(let[t,n]of this.extensions)e[t]=structuredClone(n.capture());let t={};for(let[e,n]of this.extensions)t[e]=n.version??1;return{extensions:e,versions:t}}restore(e,t={}){let n=this.snapshot(),r=[];try{for(let[n,i]of this.extensions){if(!(n in e.extensions)){t.missing===`reset`?(i.reset&&i.reset(),r.push({extension:n,from:0,to:i.version??1,status:`reset`})):t.missing===`remove`&&(i.remove&&i.remove(),r.push({extension:n,from:0,to:i.version??1,status:`removed`}));continue}let a=e.versions?.[n]??1,o=i.version??1,s=structuredClone(e.extensions[n]);for(let e=a;e<o;e++){let t=i.migrations?.[e+1];if(!t)throw Error(`missing state migration for ${n} to version ${e+1}`);s=t(s)}i.restore(structuredClone(s)),r.push({extension:n,from:a,to:o,status:a===o?`unchanged`:`migrated`})}}catch(e){for(let[e,t]of this.extensions)e in n.extensions&&t.restore(structuredClone(n.extensions[e]));throw e}for(let e of r)t.onDiagnostic?.(e);return r}transaction(e){let t=this.snapshot();try{return e()}catch(e){throw this.restore(t),e}}},Ft=class{constructor(e,t){if(!e.endpoint)throw Error(`${t} endpoint is required`);if(this.endpoint=e.endpoint,this.timeoutMs=e.timeoutMs??1e4,!(this.timeoutMs>0))throw Error(`${t} timeout must be positive`);if(this.fetchFn=e.fetch??globalThis.fetch,!this.fetchFn)throw Error(`fetch is unavailable; provide ${t}Options.fetch`)}async withTimeout(e){let t=new AbortController,n=setTimeout(()=>t.abort(),this.timeoutMs);try{return await e(t.signal)}finally{clearTimeout(n)}}},It=class extends Ft{constructor(e){super(e,`save sync`)}async upload(e,t){if(!e)throw Error(`save sync slot name is required`);if(!t)throw Error(`save sync payload cannot be empty`);return this.withTimeout(async n=>{let r=await this.fetchFn(this.slotUrl(e),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({payload:t}),signal:n});if(!r.ok)throw Error(`save upload failed with HTTP ${r.status}`);return{ok:!0,status:r.status}})}async download(e){if(!e)throw Error(`save sync slot name is required`);return this.withTimeout(async t=>{let n=await this.fetchFn(this.slotUrl(e),{signal:t});if(!n.ok)throw Error(`save download failed with HTTP ${n.status}`);let r=await n.json();if(typeof r.payload!=`string`)throw Error(`save download response missing a string payload`);return r.payload})}async list(){return this.withTimeout(async e=>{let t=await this.fetchFn(this.endpoint,{signal:e});if(!t.ok)throw Error(`save slot list failed with HTTP ${t.status}`);let n=await t.json();if(!Array.isArray(n.slots)||!n.slots.every(e=>typeof e==`string`))throw Error(`save slot list response missing a string array of slots`);return n.slots})}slotUrl(e){let t=this.endpoint.includes(`?`)?`&`:`?`;return`${this.endpoint}${t}slot=${encodeURIComponent(e)}`}},Lt=1,Rt=class{constructor(e){if(this.onWelcome=new p,this.onTick=new p,this.onClose=new p,this.socket=null,this._id=null,!e.url)throw Error(`lockstep client url is required`);this.url=e.url,this.createSocket=e.create??(e=>new WebSocket(e))}get id(){return this._id}get connected(){return this.socket!==null&&this.socket.readyState===Lt}connect(){if(this.socket)throw Error(`lockstep client is already connected`);let e=this.createSocket(this.url);e.onmessage=e=>this.handleMessage(e.data),e.onclose=()=>{this.socket=null,this._id=null,this.onClose.dispatch()},this.socket=e}submitInput(e){this.connected&&this.socket?.send(JSON.stringify({type:`input`,payload:e}))}close(){this.socket?.close()}handleMessage(e){let t=JSON.parse(e);t.type===`welcome`&&t.id!==void 0?(this._id=t.id,this.onWelcome.dispatch({id:t.id})):t.type===`tick`&&t.tick!==void 0&&t.inputs!==void 0&&this.onTick.dispatch({tick:t.tick,inputs:t.inputs})}},zt=class{constructor(e,t){this.storage=e,this.key=t}read(e){let t=this.storage.read(this.key);return t?JSON.parse(t):e}write(e){this.storage.write(this.key,JSON.stringify(e))}remove(){this.storage.remove(this.key)}},Bt=class{constructor(e){this.store=new zt(e.storage??Mt(),`mwg-runs:${e.namespace}`),this.limit=e.limit}readAll(){return this.store.read([])}record(e){let t=this.readAll(),n={id:`${Date.now()}-${t.length}`,endedAt:Date.now(),summary:e};return t.push(n),this.limit!==void 0&&t.length>this.limit&&t.splice(0,t.length-this.limit),this.store.write(t),n}all(){return this.readAll()}ranked(e,t=`desc`){let n=this.readAll(),r=t===`desc`?-1:1;return n.sort((t,n)=>r*(e(t.summary)-e(n.summary)))}clear(){this.store.remove()}},Vt=class{constructor(e){this.store=new zt(e.storage??Mt(),`mwg-stats:${e.namespace}`),this.initial=e.initial,this.combine=e.combine}get(){return this.store.read(this.initial)}record(e){let t=this.combine(this.get(),e);return this.store.write(t),t}reset(){this.store.remove()}},Ht=class extends Ft{constructor(e){super(e,`telemetry`),this.consented=!1}get hasConsent(){return this.consented}setConsent(e){this.consented=e}async send(e){if(!e.name)throw Error(`telemetry event needs a name`);return this.consented?this.withTimeout(async t=>{let n=await this.fetchFn(this.endpoint,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(e),signal:t});if(!n.ok)throw Error(`telemetry request failed with HTTP ${n.status}`);return{ok:!0,status:n.status}}):null}},Ut=class extends Ft{constructor(e){super(e,`news`)}async fetchItems(){return this.withTimeout(async e=>{let t=await this.fetchFn(this.endpoint,{signal:e});if(!t.ok)throw Error(`news request failed with HTTP ${t.status}`);let n=JSON.parse(Ot(await t.text()));if(!Array.isArray(n))throw Error(`news response was not an array`);return n.map((e,t)=>Wt(e,t))})}};function Wt(e,t){if(typeof e!=`object`||!e)throw Error(`news item ${t} was not an object`);let n=e;if(typeof n.id!=`string`||!n.id)throw Error(`news item ${t} is missing a string id`);if(typeof n.title!=`string`)throw Error(`news item ${t} is missing a string title`);if(typeof n.body!=`string`)throw Error(`news item ${t} is missing a string body`);return{id:n.id,title:n.title,body:n.body,publishedAt:typeof n.publishedAt==`number`?n.publishedAt:void 0}}var Gt=class{constructor(e){this.store=new zt(e.storage??Mt(),`mwg-news-seen:${e.namespace}`)}readSeen(){return new Set(this.store.read([]))}isSeen(e){return this.readSeen().has(e)}markSeen(e){let t=this.readSeen();t.add(e),this.store.write([...t])}unseen(e){let t=this.readSeen();return e.filter(e=>!t.has(e.id))}},Kt=class{constructor(e,t={}){if(!e)throw Error(`a collection needs a name`);this.prefix=`mwg-db:${t.namespace??`default`}:${e}:`,this.storage=t.storage??Mt()}get size(){return this.keys().length}all(){return this.keys().map(e=>this.read(e))}get(e){let t=this.storage.read(this.prefix+e);return t===null?void 0:JSON.parse(t)}put(e){if(typeof e!=`object`||!e||Array.isArray(e)||typeof e.id!=`string`||e.id===``)throw Error(`a record must be an object with a string id`);this.storage.write(this.prefix+e.id,JSON.stringify(e))}remove(e){this.storage.remove(this.prefix+e)}where(e){return this.all().filter(e)}clear(){for(let e of this.keys())this.storage.remove(e)}keys(){return this.storage.keys().filter(e=>e.startsWith(this.prefix))}read(e){return JSON.parse(this.storage.read(e))}},qt=class{constructor(e,t){this.frame=0,this.recorded=[],this.actions=e,this.frames=t,this.onAction=e=>{this.recorded.push({frame:this.frame,action:e})},this.onFrame=()=>{this.frame++},e.add(this.onAction),t.add(this.onFrame)}get events(){return this.recorded}toJSON(){return this.recorded.map(e=>({frame:e.frame,action:e.action}))}stop(){this.actions.remove(this.onAction),this.frames.remove(this.onFrame)}},Jt=class{constructor(e,t,n){this.frame=0,this.index=0,this.events=e,this.dispatch=t,this.frames=n,this.onFrame=()=>this.pump(),n.add(this.onFrame)}get done(){return this.index>=this.events.length}stop(){this.frames.remove(this.onFrame)}pump(){for(;this.index<this.events.length&&this.events[this.index].frame<=this.frame;)this.dispatch(this.events[this.index].action),this.index++;this.frame++}};function Yt(e){return JSON.stringify(e)}function Xt(e){let t=JSON.parse(e);if(!Array.isArray(t))throw Error(`a replay must be an array of {frame, action}`);return t.map(e=>{if(typeof e!=`object`||!e||!Number.isInteger(e.frame)||e.frame<0||typeof e.action!=`string`)throw Error(`a replay entry must be {frame: a non-negative integer, action: a string}`);return{frame:e.frame,action:e.action}})}var Zt=class e{constructor(){this.entries=[],this.nextSequence=0}append(e,t=[]){let n={sequence:this.nextSequence++,action:e,events:structuredClone([...t])};return this.entries.push(n),structuredClone(n)}get size(){return this.entries.length}get all(){return structuredClone(this.entries)}mark(){return this.nextSequence}since(e){return structuredClone(this.entries.filter(t=>t.sequence>=e))}truncate(e){this.entries=this.entries.filter(t=>t.sequence<e),this.nextSequence=e}toJSON(){return this.all}static fromJSON(t){let n=new e,r=0;for(let e of t){if(!Number.isSafeInteger(e.sequence)||e.sequence!==r)throw Error(`action journal sequences must be contiguous from zero`);n.entries.push(structuredClone({sequence:e.sequence,action:e.action,events:[...e.events]})),r++}return n.nextSequence=r,n}};function Qt(e){if(e.criteria)return e.criteria;if(e.counter===void 0||e.target===void 0)throw Error(`achievement "${e.id}" needs either counter/target or criteria`);return[{counter:e.counter,target:e.target}]}var $t=class e{constructor(){this.definitions=new Map,this.counts=new Map,this.fresh=[]}define(e){this.definitions.set(e.id,e)}count(e){return this.counts.get(e)??0}increment(e,t=1){let n=this.count(e);this.counts.set(e,n+t);let r=[];for(let t of this.definitions.values()){let i=Qt(t);i.some(t=>t.counter===e)&&(i.every(t=>t.counter===e?n>=t.target:this.count(t.counter)>=t.target)||i.every(e=>this.count(e.counter)>=e.target)&&(r.push(t.id),this.fresh.push(t.id)))}return r}unlocked(e){let t=this.definitions.get(e);if(!t)throw Error(`no such achievement: "${e}"`);return Qt(t).every(e=>this.count(e.counter)>=e.target)}progress(e){let t=this.definitions.get(e);if(!t)throw Error(`no such achievement: "${e}"`);let n=Qt(t);if(n.length!==1)throw Error(`achievement "${e}" has several criteria - use subProgress`);return{count:this.count(n[0].counter),target:n[0].target}}subProgress(e){let t=this.definitions.get(e);if(!t)throw Error(`no such achievement: "${e}"`);return Qt(t).map(e=>{let t=this.count(e.counter);return{counter:e.counter,count:t,target:e.target,met:t>=e.target}})}drainNew(){let e=this.fresh;return this.fresh=[],e}toJSON(){return{counts:[...this.counts]}}static fromJSON(t,n){let r=new e;for(let e of t)r.define(e);for(let[e,t]of n.counts)r.counts.set(e,t);return r}},en=class e{constructor(e=[]){this.active=new Set,this.spent=new Set,this.rules=[...e]}add(e){this.rules.push(e)}remove(e){this.rules=this.rules.filter(t=>t.id!==e),this.active.delete(e)}check(e){let t=[];for(let n of this.rules){if(n.once&&this.spent.has(n.id))continue;let r=n.when(e);r&&!this.active.has(n.id)&&(n.action(e),t.push(n.id),n.once&&this.spent.add(n.id)),r?this.active.add(n.id):this.active.delete(n.id)}return t}isActive(e){return this.active.has(e)}reset(){this.active.clear(),this.spent.clear()}toJSON(){return{active:[...this.active],spent:[...this.spent]}}static fromJSON(t,n){let r=new e(t);for(let e of n.active)r.active.add(e);for(let e of n.spent)r.spent.add(e);return r}},tn=class{constructor(e={}){let t=e.storage??Mt(),n=`mwg-session:${e.namespace??`default`}`,r=Number(t.read(n)??`0`);this.launches=(Number.isFinite(r)?r:0)+1,t.write(n,String(this.launches))}},nn=class extends Ft{constructor(e){super(e,`feedback`)}async submit(e){if(!e.message?.trim())throw Error(`feedback message cannot be empty`);return this.withTimeout(async t=>{let n=await this.fetchFn(this.endpoint,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(e),signal:t});if(!n.ok)throw Error(`feedback request failed with HTTP ${n.status}`);return{ok:!0,status:n.status}})}},rn=class{constructor(e){this.schedule=[],this.cursor=0,this.elapsed=0,this.startedWaves=new Set,this.completed=!1,this.onSpawn=e.onSpawn,this.onWaveStart=e.onWaveStart,this.onComplete=e.onComplete,e.waves.forEach((e,t)=>{let n=e.entries.reduce((e,t)=>e+t.count,0),r=e.duration??0,i=0;for(let a of e.entries)for(let o=0;o<a.count;o++,i++){let o=n>1&&r>0?i/(n-1)*r:0;this.schedule.push({time:e.delay+o,kind:a.kind,waveIndex:t})}}),this.schedule.sort((e,t)=>e.time-t.time),this.schedule.length===0&&(this.completed=!0,this.onComplete?.())}update(e){if(!this.completed){for(this.elapsed+=e;this.cursor<this.schedule.length&&this.schedule[this.cursor].time<=this.elapsed;){let e=this.schedule[this.cursor];this.startedWaves.has(e.waveIndex)||(this.startedWaves.add(e.waveIndex),this.onWaveStart?.(e.waveIndex)),this.onSpawn(e.kind),this.cursor++}this.cursor>=this.schedule.length&&(this.completed=!0,this.onComplete?.())}}get isComplete(){return this.completed}};function an(e,t){let n=e,r=t-(e-(e&1))/2;return{x:n,y:-n-r,z:r}}function on(e){return{x:e.x,y:e.z+(e.x-(e.x&1))/2}}var sn=[{x:1,y:-1,z:0},{x:1,y:0,z:-1},{x:0,y:1,z:-1},{x:-1,y:1,z:0},{x:-1,y:0,z:1},{x:0,y:-1,z:1}];function cn(e,t){let n=an(e,t);return sn.map(e=>on({x:n.x+e.x,y:n.y+e.y,z:n.z+e.z}))}function ln(e,t){let n=an(e.x,e.y),r=an(t.x,t.y);return Math.max(Math.abs(n.x-r.x),Math.abs(n.y-r.y),Math.abs(n.z-r.z))}function un(e){let t=Math.round(e.x),n=Math.round(e.y),r=Math.round(e.z),i=Math.abs(t-e.x),a=Math.abs(n-e.y),o=Math.abs(r-e.z);return i>a&&i>o?t=-n-r:a>o?n=-t-r:r=-t-n,{x:t,y:n,z:r}}function dn(e,t){let n=ln(e,t);if(n===0)return[{x:e.x,y:e.y}];let r=an(e.x,e.y),i=an(t.x,t.y),a=[];for(let e=0;e<=n;e++){let t=e/n;a.push(on(un({x:r.x+(i.x-r.x)*t,y:r.y+(i.y-r.y)*t,z:r.z+(i.z-r.z)*t})))}return a}function fn(e,t){let n=an(e.x,e.y),r=[];for(let e=-t;e<=t;e++)for(let i=Math.max(-t,-e-t);i<=Math.min(t,-e+t);i++){let t=-e-i;r.push(on({x:n.x+e,y:n.y+i,z:n.z+t}))}return r}function pn(e,t,n,r,i={}){let a=+((i.offset??`odd`)===`odd`);return(i.orientation??`flat-top`)===`pointy-top`?{x:e*n+((t&1)===a?n/2:0)+n/2,y:t*r*.75+r/2}:{x:e*n*.75+n/2,y:t*r+((e&1)===a?r/2:0)+r/2}}function mn(e,t,n,r,i={}){let a=(i.orientation??`flat-top`)===`pointy-top`,o=a?n:n*.75,s=a?r*.75:r,c=Math.round((e-n/2)/o),l=Math.round((t-r/2)/s),u={x:c,y:l},d=1/0;for(let a=-2;a<=2;a++)for(let o=-2;o<=2;o++){let s={x:c+a,y:l+o},f=pn(s.x,s.y,n,r,i),p=(f.x-e)**2+(f.y-t)**2;p<d&&(d=p,u=s)}return u}var hn=.12,gn=null,_n,vn=new p;function yn(){if(_n===void 0&&(_n=typeof matchMedia==`function`?matchMedia(`(prefers-reduced-motion: reduce)`):null,_n)){let e=()=>{vn.dispatch(xn())};typeof _n.addEventListener==`function`?_n.addEventListener(`change`,e):typeof _n.addListener==`function`&&_n.addListener(e)}return _n}function bn(){return yn()?.matches??!1}function xn(){return gn??bn()}function Sn(e){gn=e,vn.dispatch(xn())}function Cn(e){return yn(),vn.add(e),()=>vn.remove(e)}function wn(e,t=`decorative`){return xn()?t===`meaningful`?Math.min(e,hn):0:e}var Tn=[[0,-1],[1,0],[0,1],[-1,0]],En=class e{constructor(e,t){this.width=e,this.height=t,this.volume=new Float32Array(e*t)}index(e,t){return e<0||t<0||e>=this.width||t>=this.height?-1:t*this.width+e}volumeAt(e,t){let n=this.index(e,t);return n<0?0:this.volume[n]}total(){let e=0;for(let t=0;t<this.volume.length;t++)e+=this.volume[t];return e}seed(e,t,n){let r=this.index(e,t);r>=0&&(this.volume[r]+=n)}clear(e,t){let n=this.index(e,t);n>=0&&(this.volume[n]=0)}spread(e,t=.25,n=.9){let r=new Float32Array(this.volume.length);for(let n=0;n<this.height;n++)for(let i=0;i<this.width;i++){let a=n*this.width+i,o=this.volume[a];if(o<=0)continue;let s=[];for(let[t,r]of Tn){let a=i+t,o=n+r,c=this.index(a,o);c>=0&&e(a,o)&&s.push(c)}if(s.length===0)r[a]+=o;else{let e=o*t/s.length;r[a]+=o-e*s.length;for(let t of s)r[t]+=e}}let i=[];for(let e=0;e<r.length;e++){let t=r[e]*n,a=t<.001?0:t;a===0&&this.volume[e]>0&&i.push({x:e%this.width,y:Math.floor(e/this.width)}),this.volume[e]=a}return i}cellsAbove(e){let t=[];for(let n=0;n<this.height;n++)for(let r=0;r<this.width;r++){let i=this.volume[n*this.width+r];i>=e&&t.push({x:r,y:n,volume:i})}return t}toJSON(){return{width:this.width,height:this.height,volume:[...this.volume]}}static fromJSON(t){let n=new e(t.width,t.height);return n.volume.set(t.volume.slice(0,n.volume.length)),n}},Dn={linear:e=>e,easeInQuad:e=>e*e,easeOutQuad:e=>e*(2-e),easeInOutQuad:e=>e<.5?2*e*e:1-(-2*e+2)**2/2,easeInCubic:e=>e*e*e,easeOutCubic:e=>1-(1-e)**3,easeInOutCubic:e=>e<.5?4*e*e*e:1-(-2*e+2)**3/2},On=class{constructor(){this.tweens=[]}tween(e,t,n=Dn.linear){let{ease:r=Dn.linear,intent:i=`decorative`,alternate:a}=typeof n==`function`?{ease:n}:n,o=xn()&&a!==void 0,s=o?a:t,c=wn(e,o?`meaningful`:i);return c>0?new Promise(e=>{this.tweens.push({elapsed:0,duration:c,ease:r,apply:s,resolve:e,finishOnReduced:!o&&i===`decorative`})}):(s(1),Promise.resolve())}update(e){if(this.tweens.length!==0)for(let t of[...this.tweens]){if(t.finishOnReduced&&xn()){this.tweens.splice(this.tweens.indexOf(t),1),t.apply(1),t.resolve();continue}t.elapsed+=e;let n=Math.min(1,t.elapsed/t.duration);t.apply(t.ease(n)),n>=1&&(this.tweens.splice(this.tweens.indexOf(t),1),t.resolve())}}get isBusy(){return this.tweens.length>0}clear(){this.tweens=[]}},kn=class{constructor(e={}){this.history=[],this.cursor=-1,this.limit=Math.max(1,e.limit??50)}push(e){this.history.length=this.cursor+1,this.history.push(e),this.history.length>this.limit&&this.history.shift(),this.cursor=this.history.length-1}get canUndo(){return this.cursor>0}get canRedo(){return this.cursor<this.history.length-1}undo(){return this.canUndo?(this.cursor--,this.history[this.cursor]):null}redo(){return this.canRedo?(this.cursor++,this.history[this.cursor]):null}get current(){return this.cursor>=0?this.history[this.cursor]:null}clear(){this.history=[],this.cursor=-1}};function An(e,t){if(!Number.isFinite(t.maxCost)||t.maxCost<0)return new Map;let n=t.key(e),r=new Map([[n,{cell:e,cost:0}]]),i=[{cell:e,key:n,cost:0}];for(;i.length>0;){let e=Mn(i),n=r.get(e.key);if(!(!n||e.cost!==n.cost)&&!t.stop?.(e.cell,e.cost))for(let n of t.neighbors(e.cell)){let a=t.cost(e.cell,n);if(!Number.isFinite(a)||a<0)continue;let o=e.cost+a;if(o>t.maxCost||t.canEnter&&!t.canEnter(n,e.cell,o))continue;let s=t.key(n);if(o>=(r.get(s)?.cost??1/0))continue;let c={cell:n,key:s,cost:o};r.set(s,c),jn(i,c)}}return r}function jn(e,t){e.push(t);let n=e.length-1;for(;n>0;){let t=Math.floor((n-1)/2);if(e[t].cost<=e[n].cost)break;[e[t],e[n]]=[e[n],e[t]],n=t}}function Mn(e){let t=e[0],n=e.pop();if(!t||!n||e.length===0)return t;e[0]=n;let r=0;for(;;){let t=r*2+1,n=t+1,i=r;if(t<e.length&&e[t].cost<e[i].cost&&(i=t),n<e.length&&e[n].cost<e[i].cost&&(i=n),i===r)break;[e[r],e[i]]=[e[i],e[r]],r=i}return t}var Nn=class{constructor(){this.changed=new p,this.tasks=[],this.progress=new Map,this.status_=`idle`,this.current_=null,this.error_=null,this.cancelled=!1}add(e){if(!e.id)throw Error(`load task needs an id`);if(this.tasks.some(t=>t.id===e.id))throw Error(`duplicate load task "${e.id}"`);if(e.weight!==void 0&&!(e.weight>0))throw Error(`load task weight must be positive`);if(this.status_===`loading`)throw Error(`cannot add a task while loading`);return this.tasks.push(e),this.progress.set(e.id,0),this.emit(),this}get snapshot(){let e=this.tasks.reduce((e,t)=>e+(t.weight??1),0),t=this.tasks.reduce((e,t)=>e+(t.weight??1)*(this.progress.get(t.id)??0),0);return{status:this.status_,completed:t,total:e,current:this.current_,error:this.error_}}async start(){if(this.status_===`loading`)throw Error(`load queue is already running`);this.status_=`loading`,this.cancelled=!1,this.error_=null,this.emit();try{for(let e of this.tasks){if(this.cancelled)break;this.current_=e.id,this.emit();let t=this;await e.run({get cancelled(){return t.cancelled},report:t=>this.report(e.id,t)}),this.cancelled||this.report(e.id,1)}this.current_=null,this.status_=this.cancelled?`cancelled`:`ready`,this.emit()}catch(e){throw this.current_=null,this.error_=e,this.status_=`failed`,this.emit(),e}}cancel(){this.status_===`loading`&&(this.cancelled=!0)}retry(){if(this.status_===`loading`)throw Error(`cannot retry while loading`);this.status_=`idle`,this.current_=null,this.error_=null,this.cancelled=!1;for(let e of this.tasks)this.progress.set(e.id,0);this.emit()}report(e,t){if(!Number.isFinite(t))throw Error(`load progress must be finite`);this.progress.set(e,Math.max(0,Math.min(1,t))),this.emit()}emit(){this.changed.dispatch(this.snapshot)}},Pn=class{constructor(){this.entities=new Map,this.ids=new Map,this.sequence=0}add(e,t){let n=this.ids.get(e);if(n!==void 0){if(t!==void 0&&t!==n)throw Error(`entity already has id ${n}`);return n}let r=t;if(r!==void 0){if(r.length===0)throw Error(`entity id must not be empty`);if(this.entities.has(r))throw Error(`entity id already exists: ${r}`)}else do r=`e${this.sequence++}`;while(this.entities.has(r));return this.entities.set(r,e),this.ids.set(e,r),r}get(e){return this.entities.get(e)}idOf(e){return this.ids.get(e)}has(e){return this.entities.has(e)}remove(e){let t=this.entities.get(e);return t!==void 0&&(this.entities.delete(e),this.ids.delete(t),!0)}get size(){return this.entities.size}},Fn=class{constructor(e){this.queue=[],this.busy=!1,this.remaining=0,this.play=e.play}enqueue(e){this.queue.push(...e),this.busy||this.advance()}update(e){this.busy&&(this.remaining-=e,this.remaining<=0&&this.advance())}get isBusy(){return this.busy}clear(){this.queue=[],this.busy=!1,this.remaining=0}advance(){let e=this.queue.shift();if(e===void 0){this.busy=!1,this.remaining=0;return}this.busy=!0;let t=this.play(e)||0;t>0?this.remaining=t:this.advance()}},In=2166136261,Ln=16777619;function Rn(e,t=!1){if(e==null)return`null`;switch(typeof e){case`boolean`:return e?`true`:`false`;case`number`:return Number.isFinite(e)?String(e):`null`;case`string`:return JSON.stringify(e);case`bigint`:return JSON.stringify(e.toString());case`function`:case`symbol`:return t?`null`:`undefined`}return Array.isArray(e)?`[${e.map(e=>Rn(e,!0)).join(`,`)}]`:`{${Object.entries(e).filter(([,e])=>e!==void 0&&typeof e!=`function`&&typeof e!=`symbol`).sort(([e],[t])=>e<t?-1:+(e>t)).map(([e,t])=>`${JSON.stringify(e)}:${Rn(t)}`).join(`,`)}}`}function zn(e){let t=Rn(e),n=In;for(let e=0;e<t.length;e++)n^=t.charCodeAt(e),n=Math.imul(n,Ln)>>>0;return n>>>0}var Bn=class{constructor(){this.reference=new Map,this.desyncTick=null}observe(e,t){let n=this.reference.get(e);return n===void 0?(this.reference.set(e,t),!0):n===t||(this.desyncTick===null&&(this.desyncTick=e),!1)}get divergent(){return this.desyncTick!==null}get atTick(){return this.desyncTick}reset(){this.reference.clear(),this.desyncTick=null}};function Vn(e,t={}){let n=Wn(e);if(n.length===0)return[];let[r,...i]=n,a=t.listDelimiter??`;`,o=t.mapDelimiter??`=`;return i.map((e,n)=>{let i={};return r.forEach((r,s)=>{let c=e[s]??``;c!==``&&(i[r]=Hn(c,t.columns?.[r]??`string`,r,n,a,o))}),i})}function Hn(e,t,n,r,i,a){return Un(e,t,{column:n,rowIndex:r,listDelimiter:i,mapDelimiter:a,error:()=>t===`number`?`CSV row ${r+1}, column "${n}": "${e}" is not a number`:t===`boolean`?`CSV row ${r+1}, column "${n}": "${e}" is not "true" or "false"`:t===`map`?`CSV row ${r+1}, column "${n}": "${e.split(i).map(e=>e.trim()).find(e=>e&&!e.includes(a))??e}" has no "${a}" to split a key from its value`:`CSV row ${r+1}, column "${n}": "${e}" is invalid`})}function Un(e,t,n={}){let r=n.column??`value`,i=n.listDelimiter??`;`,a=n.mapDelimiter??`=`,o=e=>{throw Error(n.error?.(e)??e)};switch(t){case`string`:return e;case`number`:{let t=Number(e);return Number.isFinite(t)||o(`${r} must be a number`),t}case`boolean`:{let t=e.toLowerCase();if(t===`true`)return!0;if(t===`false`)return!1;if(n.acceptYesNo&&t===`yes`)return!0;if(n.acceptYesNo&&t===`no`)return!1;o(`${r} must be true, false${n.acceptYesNo?`, yes, or no`:``}`)}case`list`:return e.split(i).map(e=>e.trim()).filter(e=>e.length>0);case`map`:{let t={};for(let n of e.split(i).map(e=>e.trim()).filter(e=>e.length>0)){let e=n.indexOf(a);e===-1&&o(`${r} map entry must contain ${a}`),t[n.slice(0,e).trim()]=n.slice(e+a.length).trim()}return t}}}function Wn(e){let t=[],n=[],r=``,i=!1,a=0;for(;a<e.length;){let o=e[a];if(i){if(o===`"`){if(e[a+1]===`"`){r+=`"`,a+=2;continue}i=!1,a++;continue}r+=o,a++;continue}if(o===`"`){i=!0,a++;continue}if(o===`,`){n.push(r),r=``,a++;continue}if(o===`\r`){a++;continue}if(o===`
1
+ var mw_games=(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var t=Object.create,n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.getPrototypeOf,o=Object.prototype.hasOwnProperty,s=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(e){throw n=[e],e}},c=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),l=(e,t)=>{let r={};for(var i in e)n(r,i,{get:e[i],enumerable:!0});return t||n(r,Symbol.toStringTag,{value:`Module`}),r},u=(e,t,a,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var c=i(t),l=0,u=c.length,d;l<u;l++)d=c[l],!o.call(e,d)&&d!==a&&n(e,d,{get:(e=>t[e]).bind(null,d),enumerable:!(s=r(t,d))||s.enumerable});return e},d=(e,r,i)=>(i=e==null?{}:t(a(e)),u(r||!e||!e.__esModule||!o.call(e,`default`)?n(i,`default`,{value:e,enumerable:!0}):i,e)),f=`0.7.8`,p=class{constructor(e=!1){this.listeners=[],this.stackMode=e}add(e){this.listeners.includes(e)||(this.stackMode?this.listeners.unshift(e):this.listeners.push(e))}remove(e){let t=this.listeners.indexOf(e);t!==-1&&this.listeners.splice(t,1)}removeAll(){this.listeners.length=0}get size(){return this.listeners.length}dispatch(e){let t=this.listeners.slice();for(let n of t)if(this.listeners.includes(n)&&n(e)===!0)return!0;return!1}},m=class{constructor(){this.onDestroy=new p,this.destroyed=!1}update(e){}resize(e,t){}onSuspend(){}onResume(e){}destroy(){this.destroyed||(this.destroyed=!0,this.onDestroy.dispatch(),this.onDestroy.removeAll(),this.teardown())}teardown(){}get isDestroyed(){return this.destroyed}},h=class{constructor(){this.scenes=[]}get current(){return this.scenes.length===0?null:this.scenes[this.scenes.length-1]}get depth(){return this.scenes.length}replace(e){for(let e of this.scenes)e.destroy();this.scenes=[e],e.create()}push(e){this.current?.onSuspend(),this.scenes.push(e),e.create()}pop(e){if(this.scenes.length<=1)throw Error(`cannot pop the last scene off the stack - switchScene somewhere instead`);this.scenes.pop()?.destroy(),this.current?.onResume(e)}update(e){this.current?.update(e)}resize(e,t){for(let n of this.scenes)n.resize(e,t)}destroy(){for(let e of this.scenes)e.destroy();this.scenes=[]}},g=class{constructor(){this.items=new Map}register(e,t){if(this.items.has(e))throw Error(`"${e}" is already registered`);this.items.set(e,t)}get(e){let t=this.items.get(e);if(t===void 0)throw Error(`no registration named "${e}"`);return t}has(e){return this.items.has(e)}list(){return[...this.items.keys()]}},_=class{constructor(){this.order=[],this.registry=new g}add(e,t){this.registry.register(e.name,e),this.order.push(e),e.create?.(t)}has(e){return this.registry.has(e)}get(e){return this.registry.get(e)}update(e,t){for(let n of this.order)n.update?.(e,t)}resize(e,t,n){for(let r of this.order)r.resize?.(e,t,n)}onSuspend(e){for(let t of this.order)t.onSuspend?.(e)}onResume(e,t){for(let n of this.order)n.onResume?.(e,t)}destroy(e){for(let t=this.order.length-1;t>=0;t--)this.order[t].destroy?.(e);this.order=[],this.registry=new g}},v={debug:0,info:1,warn:2,error:3},y=class{constructor(e,t={}){if(!e)throw Error(`a logger needs a category`);this.category=e,this.level=t.level??`debug`,this.sink=t.sink??b}setLevel(e){this.level=e}debug(e,t){this.write(`debug`,e,t)}info(e,t){this.write(`info`,e,t)}warn(e,t){this.write(`warn`,e,t)}error(e,t){this.write(`error`,e,t)}write(e,t,n){v[e]<v[this.level]||this.sink({level:e,category:this.category,message:t,data:n,time:Date.now()})}};function b(e){let t=`[${e.category}] ${e.message}`;e.level===`debug`?console.debug(t,e.data??``):e.level===`info`?console.info(t,e.data??``):e.level===`warn`?console.warn(t,e.data??``):console.error(t,e.data??``)}var x=class{constructor(){this.hooks=[]}on(e,t,n){this.hooks.push({event:e,handler:t,source:n})}off(e){this.hooks=this.hooks.filter(t=>t.handler!==e)}offSource(e){this.hooks=this.hooks.filter(t=>t.source!==e)}emit(e,...t){for(let n of[...this.hooks])n.event===e&&n.handler(...t)}get size(){return this.hooks.length}clear(){this.hooks=[]}},S=l({Generator:()=>w,MersenneTwister:()=>he,RandomStreams:()=>_e,chance:()=>oe,element:()=>se,float:()=>O,int:()=>k,normalRange:()=>ae,pop:()=>D,push:()=>te,range:()=>ie,reset:()=>re,shuffle:()=>le,weighted:()=>ce,weightedKey:()=>A,withSeed:()=>ne});function C(e){let t=e>>>0;return()=>{t=t+2654435769>>>0;let e=t;return e=Math.imul(e^e>>>16,569420461),e=Math.imul(e^e>>>15,1935289751),(e^e>>>15)>>>0}}var w=class{constructor(e){this.s0=0,this.s1=0,this.s2=0,this.s3=0,this.seed=e===void 0?Math.random()*4294967296>>>0:e>>>0;let t=C(this.seed);this.s0=t(),this.s1=t(),this.s2=t(),this.s3=t(),(this.s0|this.s1|this.s2|this.s3)===0&&(this.s0=1)}nextUint32(){let e=Math.imul(ee(Math.imul(this.s1,5),7),9)>>>0>>>0,t=this.s1<<9>>>0;return this.s2^=this.s0,this.s3^=this.s1,this.s1^=this.s2,this.s0^=this.s3,this.s2^=t,this.s3=ee(this.s3,11),e}float(){return this.nextUint32()/4294967296}int(e){if(e<=0)return 0;let t=4294967296-4294967296%e,n=this.nextUint32();for(;n>=t;)n=this.nextUint32();return n%e}getState(){return[this.s0,this.s1,this.s2,this.s3]}setState(e){[this.s0,this.s1,this.s2,this.s3]=e}};function ee(e,t){return(e<<t|e>>>32-t)>>>0}var T=[new w],E=()=>T[T.length-1];function te(e){let t=new w(e);return T.push(t),t}function D(){if(T.length===1)throw Error(`the base random generator cannot be popped`);T.pop()}function ne(e,t){te(e);try{return t()}finally{D()}}function re(){T.length=0,T.push(new w)}function O(e,t){return e===void 0?E().float():t===void 0?E().float()*e:e+E().float()*(t-e)}function k(e,t){return t===void 0?E().int(e):e+E().int(t-e)}function ie(e,t){return e+E().int(t-e+1)}function ae(e,t){return e+Math.floor((E().float()+E().float())*(t-e+1)/2)}function oe(e){return E().float()<e}function se(e){return e.length>0?e[E().int(e.length)]:null}function ce(e){let t=0;for(let n of e)t+=n;if(t<=0)return null;let n=E().float()*t;for(let t=0;t<e.length;t++)if(n-=e[t],n<0)return t;return e.length-1}function A(e){let t=[...e.keys()],n=ce(t.map(t=>e.get(t)??0));return n===null?null:t[n]}function le(e){for(let t=e.length-1;t>0;t--){let n=E().int(t+1);[e[t],e[n]]=[e[n],e[t]]}return e}var ue=624,de=397,fe=2567483615,pe=2147483648,me=2147483647,he=class{constructor(e=5489){this.state=new Uint32Array(ue),this.index=ue,this.seedValue=5489,this.produced=0,this.seed(e)}seed(e){this.seedValue=e>>>0,this.state[0]=this.seedValue;for(let e=1;e<ue;e++){let t=this.state[e-1]^this.state[e-1]>>>30;this.state[e]=Math.imul(1812433253,t)+e>>>0}this.index=ue,this.produced=0}generate(){for(let e=0;e<ue;e++){let t=this.state[e]&pe|this.state[(e+1)%ue]&me,n=this.state[(e+de)%ue]^t>>>1;t&1&&(n^=fe),this.state[e]=n>>>0}this.index=0}nextUint32(){this.index>=ue&&this.generate();let e=this.state[this.index++];return e^=e>>>11,e^=e<<7&2636928640,e^=e<<15&4022730752,e^=e>>>18,this.produced++,e>>>0}float(){return this.nextUint32()/4294967296}int(e){if(e<=0)return 0;let t=4294967296-4294967296%e,n=this.nextUint32();for(;n>=t;)n=this.nextUint32();return n%e}discard(e){for(let t=0;t<e;t++)this.nextUint32()}get discardCount(){return this.produced}getState(){return{seed:this.seedValue,state:[...this.state],index:this.index,discard:this.produced}}setState(e){this.seedValue=e.seed>>>0;for(let t=0;t<ue;t++)this.state[t]=(e.state[t]??0)>>>0;this.index=e.index,this.produced=e.discard}};function ge(e){let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t=Math.imul(t,16777619)>>>0;return t>>>0}var _e=class{constructor(e=0){this.streams=new Map,this.baseSeed=e>>>0}stream(e){let t=this.streams.get(e);if(!t){let n=(this.baseSeed^ge(e))>>>0;t={seed:n,engine:new he(n)},this.streams.set(e,t)}return t.engine}seedOf(e){return this.streams.get(e)?.seed}reseed(e){this.baseSeed=e>>>0,this.streams.clear()}names(){return[...this.streams.keys()]}getState(){let e={};for(let[t,n]of this.streams)e[t]=n.engine.getState();return e}setState(e){for(let[t,n]of Object.entries(e)){let e=new he(n.seed);e.setState(n),this.streams.set(t,{seed:n.seed,engine:e})}}},ve=l({DEFAULT_BINDINGS:()=>Pe,actionsForKey:()=>Le,attach:()=>vt,attachSwipe:()=>_t,bind:()=>Fe,bindAxis:()=>ct,bindButton:()=>st,bindTouch:()=>ft,detach:()=>yt,dispatchComposition:()=>ke,dispatchText:()=>Oe,endFrame:()=>Ye,exportBindings:()=>Be,gamepadAxisCode:()=>ot,gamepadButtonCode:()=>at,importBindings:()=>Ve,isDown:()=>Ke,justPressed:()=>qe,justReleased:()=>Je,keysFor:()=>ze,onAction:()=>Ce,onComposition:()=>Ee,onKey:()=>we,onText:()=>Te,onWheel:()=>Ae,pollGamepads:()=>lt,pressTouch:()=>pt,releaseTouch:()=>mt,resetBindings:()=>He,rumble:()=>ut,textFromKey:()=>De,touchCode:()=>dt,unbind:()=>Re,wheelActionFor:()=>je}),ye=new Map,be=new Set,xe=new Set,Se=new Set,Ce=new p(!0),we=new p(!0),Te=new p(!0),Ee=new p(!0);function De(e){return e.isComposing||e.ctrlKey||e.metaKey||e.altKey?null:e.key.length===1?e.key:null}function Oe(e){e.length>0&&Te.dispatch(e)}function ke(e){Ee.dispatch({phase:e.phase,text:e.text})}var Ae=new p(!0);function je(e){return e.ctrlKey||e.metaKey?`zoom`:e.shiftKey?`scrollHorizontal`:`scroll`}function Me(e){let t=je(e);t===`zoom`&&e.preventDefault();let n=t===`scrollHorizontal`&&e.deltaX!==0?e.deltaX:e.deltaY;Ae.dispatch({action:t,delta:n})}var Ne=!1,Pe={up:[`ArrowUp`,`KeyW`,`Numpad8`],down:[`ArrowDown`,`KeyS`,`Numpad2`],left:[`ArrowLeft`,`KeyA`,`Numpad4`],right:[`ArrowRight`,`KeyD`,`Numpad6`],upLeft:[`Numpad7`],upRight:[`Numpad9`],downLeft:[`Numpad1`],downRight:[`Numpad3`],wait:[`Numpad5`,`Period`],confirm:[`Enter`,`Space`,`NumpadEnter`],cancel:[`Escape`,`Backspace`],menu:[`KeyI`,`Tab`]};function Fe(e,t){ye.set(e,new Set(t))}function Ie(e,t){let n=ye.get(e)??new Set;for(let e of t)n.add(e);ye.set(e,n)}function Le(e){return Ue(e)}function Re(e){ye.delete(e)}function ze(e){return[...ye.get(e)??[]]}function Be(){let e={};for(let[t,n]of ye)e[t]=[...n];return e}function Ve(e){ye.clear();for(let[t,n]of Object.entries(e))Fe(t,n)}function He(){Ve(Pe)}He();function Ue(e){let t=[];for(let[n,r]of ye)r.has(e)&&t.push(n);return t}function We(e){if(!be.has(e)){be.add(e);for(let t of Ue(e))xe.add(t),Ce.dispatch(t)}}function Ge(e){if(be.has(e)){be.delete(e);for(let t of Ue(e))Se.add(t)}}function Ke(e){let t=ye.get(e);if(!t)return!1;for(let e of t)if(be.has(e))return!0;return!1}function qe(e){return xe.has(e)}function Je(e){return Se.has(e)}function Ye(){xe.clear(),Se.clear()}function Xe(e){let t=De(e);t!==null&&Oe(t)}function Ze(e){if(e.repeat){we.dispatch(e),Xe(e);return}We(e.code),we.dispatch(e),Xe(e)}function Qe(e){Ge(e.code)}function $e(e){ke({phase:`start`,text:e.data??``})}function et(e){ke({phase:`update`,text:e.data??``})}function tt(e){ke({phase:`end`,text:e.data??``})}function nt(){be.clear(),xe.clear(),Se.clear()}var rt=.5,it=new Set;function at(e,t){return`Gamepad${e}Button${t}`}function ot(e,t,n){return`Gamepad${e}Axis${t}${n>0?`+`:`-`}`}function st(e,t,n){Ie(e,n.map(e=>at(t,e)))}function ct(e,t,n,r){Ie(e,[ot(t,n,r)])}function lt(e=typeof navigator?.getGamepads==`function`?navigator.getGamepads():[]){it.clear();for(let t of e)if(t){for(let e=0;e<t.buttons.length;e++)t.buttons[e].pressed&&it.add(at(t.index,e));for(let e=0;e<t.axes.length;e++){let n=t.axes[e];n>=rt?it.add(ot(t.index,e,1)):n<=-.5&&it.add(ot(t.index,e,-1))}}for(let e of it)We(e);for(let e of be)it.has(e)||!e.startsWith(`Gamepad`)||Ge(e)}function ut(e,t,n=typeof navigator?.getGamepads==`function`?navigator.getGamepads():[]){(n[e]?.vibrationActuator)?.playEffect(`dual-rumble`,{duration:t.duration,weakMagnitude:t.weakMagnitude??1,strongMagnitude:t.strongMagnitude??1})}function dt(e){return`Touch:${e}`}function ft(e,t=e){Ie(e,[dt(t)])}function pt(e){We(dt(e))}function mt(e){Ge(dt(e))}var ht={up:`up`,down:`down`,left:`left`,right:`right`,upLeft:`upLeft`,upRight:`upRight`,downLeft:`downLeft`,downRight:`downRight`},gt=[`right`,`downRight`,`down`,`downLeft`,`left`,`upLeft`,`up`,`upRight`];function _t(e,t={}){let n={...ht,...t.actions},r=t.minDistance??24;for(let e of[...gt,`tap`]){let t=n[e];t&&ft(t,`swipe:${e}`)}let i=!1,a=-1,o=0,s=0;function c(e){pt(`swipe:${e}`),mt(`swipe:${e}`)}function l(e){i=!0,a=e.pointerId,o=e.clientX,s=e.clientY}function u(e){if(!i||e.pointerId!==a)return;i=!1;let t=e.clientX-o,l=e.clientY-s;if(Math.hypot(t,l)<r){n.tap&&c(`tap`);return}let u=gt[(Math.round(Math.atan2(l,t)/(Math.PI/4))%8+8)%8];n[u]&&c(u)}return e.addEventListener(`pointerdown`,l),e.addEventListener(`pointerup`,u),e.addEventListener(`pointercancel`,u),()=>{e.removeEventListener(`pointerdown`,l),e.removeEventListener(`pointerup`,u),e.removeEventListener(`pointercancel`,u)}}function vt(e=window){Ne||(Ne=!0,e.addEventListener(`keydown`,Ze),e.addEventListener(`keyup`,Qe),e.addEventListener(`compositionstart`,$e),e.addEventListener(`compositionupdate`,et),e.addEventListener(`compositionend`,tt),window.addEventListener(`blur`,nt),e.addEventListener(`wheel`,Me,{passive:!1}))}function yt(e=window){Ne&&(Ne=!1,e.removeEventListener(`keydown`,Ze),e.removeEventListener(`keyup`,Qe),e.removeEventListener(`compositionstart`,$e),e.removeEventListener(`compositionupdate`,et),e.removeEventListener(`compositionend`,tt),e.removeEventListener(`wheel`,Me),window.removeEventListener(`blur`,nt),nt())}var bt=class{constructor(e,t={}){if(!e)throw Error(`a player needs a non-empty id`);this.id=e,this.padIndex=t.padIndex}scoped(e){return`${this.id}:${e}`}bind(e,t){Fe(this.scoped(e),t)}bindButton(e,t){if(this.padIndex===void 0)throw Error(`player "${this.id}" has no padIndex to bind a gamepad button to`);st(this.scoped(e),this.padIndex,t)}bindAxis(e,t,n){if(this.padIndex===void 0)throw Error(`player "${this.id}" has no padIndex to bind a gamepad axis to`);ct(this.scoped(e),this.padIndex,t,n)}bindTouch(e,t=e){ft(this.scoped(e),`${this.id}:${t}`)}pressTouch(e){pt(`${this.id}:${e}`)}releaseTouch(e){mt(`${this.id}:${e}`)}isDown(e){return Ke(this.scoped(e))}justPressed(e){return qe(this.scoped(e))}justReleased(e){return Je(this.scoped(e))}keysFor(e){return ze(this.scoped(e))}};function xt(e,t){if(!t)throw Error(`scramble needs a non-empty key`);let n=new TextEncoder().encode(e),r=new TextEncoder().encode(t),i=new Uint8Array(n.length);for(let e=0;e<n.length;e++)i[e]=n[e]^r[e%r.length];return Ct(i)}function St(e,t){if(!t)throw Error(`scramble needs a non-empty key`);let n=wt(e),r=new TextEncoder().encode(t),i=new Uint8Array(n.length);for(let e=0;e<n.length;e++)i[e]=n[e]^r[e%r.length];return new TextDecoder(`utf-8`,{fatal:!0}).decode(i)}function Ct(e){let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t)}function wt(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}var Tt=10485760;function Et(e,t={}){let n=t.maxBytes??Tt,r=typeof e==`string`?new TextEncoder().encode(e).length:e.length;if(r>n)throw Error(`inbound data exceeds the ${n}-byte limit (${r} bytes)`)}function Dt(e){for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n!==9&&n!==10&&n!==13&&(n<=31||n===127))throw Error(`inbound data contains a control character (0x${n.toString(16).padStart(2,`0`)}) at index ${t}`)}}function Ot(e,t={}){return Et(e,t),Dt(e),e}var kt=new Set([`__proto__`,`constructor`,`prototype`]);function At(e,t,n=`$`){if(e===void 0){if(t.optional)return;throw Error(`${n} is required`)}switch(t.type){case`string`:if(typeof e!=`string`)throw Error(`${n} must be a string`);return;case`number`:if(typeof e!=`number`||!Number.isFinite(e))throw Error(`${n} must be a finite number`);if(t.min!==void 0&&e<t.min)throw Error(`${n} must be >= ${t.min}`);if(t.max!==void 0&&e>t.max)throw Error(`${n} must be <= ${t.max}`);return;case`boolean`:if(typeof e!=`boolean`)throw Error(`${n} must be a boolean`);return;case`array`:if(!Array.isArray(e))throw Error(`${n} must be an array`);if(t.maxLength!==void 0&&e.length>t.maxLength)throw Error(`${n} exceeds its maximum length of ${t.maxLength}`);e.forEach((e,r)=>At(e,t.items,`${n}[${r}]`));return;case`object`:if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`${n} must be an object`);for(let t of Object.keys(e))if(kt.has(t))throw Error(`${n} contains a forbidden key "${t}"`);for(let[r,i]of Object.entries(t.fields))At(e[r],i,`${n}.${r}`);return}}var jt=class{constructor(){this.data=new Map}read(e){return this.data.get(e)??null}write(e,t){this.data.set(e,t)}remove(e){this.data.delete(e)}keys(){return[...this.data.keys()]}};function Mt(){return typeof localStorage>`u`?new jt:{read:e=>localStorage.getItem(e),write:(e,t)=>localStorage.setItem(e,t),remove:e=>localStorage.removeItem(e),keys:()=>Object.keys(localStorage)}}var Nt=class{constructor(e){this.namespace=e.namespace,this.version=e.version,this.migrations=e.migrations??{},this.storage=e.storage??Mt()}key(e){return`mwg-save:${this.namespace}:${e}`}save(e,t,n){let r={meta:{version:this.version,savedAt:Date.now(),preview:n},state:t};this.storage.write(this.key(e),JSON.stringify(r))}load(e){let t=this.storage.read(this.key(e));if(!t)return null;let n=JSON.parse(t),r=n.state;for(let e=n.meta.version;e<this.version;e++)r=(this.migrations[e]??(e=>e))(r);return{meta:{...n.meta,version:this.version},state:r}}importExternal(e,t,n,r){Et(t);let i=n(t);for(let e=0;e<this.version;e++)i=(this.migrations[e]??(e=>e))(i);let a={meta:{version:this.version,savedAt:Date.now(),preview:r},state:i};this.storage.write(this.key(e),JSON.stringify(a))}delete(e){this.storage.remove(this.key(e))}exportSlot(e,t){let n=this.storage.read(this.key(e));return n===null?null:t?xt(n,t):n}importSlot(e,t,n){Et(t);let r=n?St(t,n):t,i=JSON.parse(Ot(r)),a=i.state;for(let e=i.meta.version;e<this.version;e++)a=(this.migrations[e]??(e=>e))(a);let o={meta:{...i.meta,version:this.version},state:a};this.storage.write(this.key(e),JSON.stringify(o))}list(){let e=`mwg-save:${this.namespace}:`,t=[];for(let n of this.storage.keys()){if(!n.startsWith(e))continue;let r=this.storage.read(n);r&&t.push({slot:n.slice(e.length),meta:JSON.parse(r).meta})}return t}},Pt=class{constructor(){this.extensions=new Map}register(e){if(!/^[A-Za-z_][A-Za-z0-9_.-]*$/.test(e.id))throw Error(`invalid state extension id: ${e.id}`);if(this.extensions.has(e.id))throw Error(`state extension already registered: ${e.id}`);return this.extensions.set(e.id,{id:e.id,capture:()=>e.capture(),restore:t=>e.restore(t),version:e.version??1,migrations:e.migrations,reset:e.reset,remove:e.remove}),()=>this.extensions.delete(e.id)}snapshot(){let e={};for(let[t,n]of this.extensions)e[t]=structuredClone(n.capture());let t={};for(let[e,n]of this.extensions)t[e]=n.version??1;return{extensions:e,versions:t}}restore(e,t={}){let n=this.snapshot(),r=[];try{for(let[n,i]of this.extensions){if(!(n in e.extensions)){t.missing===`reset`?(i.reset&&i.reset(),r.push({extension:n,from:0,to:i.version??1,status:`reset`})):t.missing===`remove`&&(i.remove&&i.remove(),r.push({extension:n,from:0,to:i.version??1,status:`removed`}));continue}let a=e.versions?.[n]??1,o=i.version??1,s=structuredClone(e.extensions[n]);for(let e=a;e<o;e++){let t=i.migrations?.[e+1];if(!t)throw Error(`missing state migration for ${n} to version ${e+1}`);s=t(s)}i.restore(structuredClone(s)),r.push({extension:n,from:a,to:o,status:a===o?`unchanged`:`migrated`})}}catch(e){for(let[e,t]of this.extensions)e in n.extensions&&t.restore(structuredClone(n.extensions[e]));throw e}for(let e of r)t.onDiagnostic?.(e);return r}transaction(e){let t=this.snapshot();try{return e()}catch(e){throw this.restore(t),e}}},Ft=class{constructor(e,t){if(!e.endpoint)throw Error(`${t} endpoint is required`);if(this.endpoint=e.endpoint,this.timeoutMs=e.timeoutMs??1e4,!(this.timeoutMs>0))throw Error(`${t} timeout must be positive`);if(this.fetchFn=e.fetch??globalThis.fetch,!this.fetchFn)throw Error(`fetch is unavailable; provide ${t}Options.fetch`)}async withTimeout(e){let t=new AbortController,n=setTimeout(()=>t.abort(),this.timeoutMs);try{return await e(t.signal)}finally{clearTimeout(n)}}},It=class extends Ft{constructor(e){super(e,`save sync`)}async upload(e,t){if(!e)throw Error(`save sync slot name is required`);if(!t)throw Error(`save sync payload cannot be empty`);return this.withTimeout(async n=>{let r=await this.fetchFn(this.slotUrl(e),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({payload:t}),signal:n});if(!r.ok)throw Error(`save upload failed with HTTP ${r.status}`);return{ok:!0,status:r.status}})}async download(e){if(!e)throw Error(`save sync slot name is required`);return this.withTimeout(async t=>{let n=await this.fetchFn(this.slotUrl(e),{signal:t});if(!n.ok)throw Error(`save download failed with HTTP ${n.status}`);let r=await n.json();if(typeof r.payload!=`string`)throw Error(`save download response missing a string payload`);return r.payload})}async list(){return this.withTimeout(async e=>{let t=await this.fetchFn(this.endpoint,{signal:e});if(!t.ok)throw Error(`save slot list failed with HTTP ${t.status}`);let n=await t.json();if(!Array.isArray(n.slots)||!n.slots.every(e=>typeof e==`string`))throw Error(`save slot list response missing a string array of slots`);return n.slots})}slotUrl(e){let t=this.endpoint.includes(`?`)?`&`:`?`;return`${this.endpoint}${t}slot=${encodeURIComponent(e)}`}},Lt=1,Rt=class{constructor(e){if(this.onWelcome=new p,this.onTick=new p,this.onClose=new p,this.socket=null,this._id=null,!e.url)throw Error(`lockstep client url is required`);this.url=e.url,this.createSocket=e.create??(e=>new WebSocket(e))}get id(){return this._id}get connected(){return this.socket!==null&&this.socket.readyState===Lt}connect(){if(this.socket)throw Error(`lockstep client is already connected`);let e=this.createSocket(this.url);e.onmessage=e=>this.handleMessage(e.data),e.onclose=()=>{this.socket=null,this._id=null,this.onClose.dispatch()},this.socket=e}submitInput(e){this.connected&&this.socket?.send(JSON.stringify({type:`input`,payload:e}))}close(){this.socket?.close()}handleMessage(e){let t=JSON.parse(e);t.type===`welcome`&&t.id!==void 0?(this._id=t.id,this.onWelcome.dispatch({id:t.id})):t.type===`tick`&&t.tick!==void 0&&t.inputs!==void 0&&this.onTick.dispatch({tick:t.tick,inputs:t.inputs})}},zt=class{constructor(e,t){this.storage=e,this.key=t}read(e){let t=this.storage.read(this.key);return t?JSON.parse(t):e}write(e){this.storage.write(this.key,JSON.stringify(e))}remove(){this.storage.remove(this.key)}},Bt=class{constructor(e){this.store=new zt(e.storage??Mt(),`mwg-runs:${e.namespace}`),this.limit=e.limit}readAll(){return this.store.read([])}record(e){let t=this.readAll(),n={id:`${Date.now()}-${t.length}`,endedAt:Date.now(),summary:e};return t.push(n),this.limit!==void 0&&t.length>this.limit&&t.splice(0,t.length-this.limit),this.store.write(t),n}all(){return this.readAll()}ranked(e,t=`desc`){let n=this.readAll(),r=t===`desc`?-1:1;return n.sort((t,n)=>r*(e(t.summary)-e(n.summary)))}clear(){this.store.remove()}},Vt=class{constructor(e){this.store=new zt(e.storage??Mt(),`mwg-stats:${e.namespace}`),this.initial=e.initial,this.combine=e.combine}get(){return this.store.read(this.initial)}record(e){let t=this.combine(this.get(),e);return this.store.write(t),t}reset(){this.store.remove()}},Ht=class extends Ft{constructor(e){super(e,`telemetry`),this.consented=!1}get hasConsent(){return this.consented}setConsent(e){this.consented=e}async send(e){if(!e.name)throw Error(`telemetry event needs a name`);return this.consented?this.withTimeout(async t=>{let n=await this.fetchFn(this.endpoint,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(e),signal:t});if(!n.ok)throw Error(`telemetry request failed with HTTP ${n.status}`);return{ok:!0,status:n.status}}):null}},Ut=class extends Ft{constructor(e){super(e,`news`)}async fetchItems(){return this.withTimeout(async e=>{let t=await this.fetchFn(this.endpoint,{signal:e});if(!t.ok)throw Error(`news request failed with HTTP ${t.status}`);let n=JSON.parse(Ot(await t.text()));if(!Array.isArray(n))throw Error(`news response was not an array`);return n.map((e,t)=>Wt(e,t))})}};function Wt(e,t){if(typeof e!=`object`||!e)throw Error(`news item ${t} was not an object`);let n=e;if(typeof n.id!=`string`||!n.id)throw Error(`news item ${t} is missing a string id`);if(typeof n.title!=`string`)throw Error(`news item ${t} is missing a string title`);if(typeof n.body!=`string`)throw Error(`news item ${t} is missing a string body`);return{id:n.id,title:n.title,body:n.body,publishedAt:typeof n.publishedAt==`number`?n.publishedAt:void 0}}var Gt=class{constructor(e){this.store=new zt(e.storage??Mt(),`mwg-news-seen:${e.namespace}`)}readSeen(){return new Set(this.store.read([]))}isSeen(e){return this.readSeen().has(e)}markSeen(e){let t=this.readSeen();t.add(e),this.store.write([...t])}unseen(e){let t=this.readSeen();return e.filter(e=>!t.has(e.id))}},Kt=class{constructor(e,t={}){if(!e)throw Error(`a collection needs a name`);this.prefix=`mwg-db:${t.namespace??`default`}:${e}:`,this.storage=t.storage??Mt()}get size(){return this.keys().length}all(){return this.keys().map(e=>this.read(e))}get(e){let t=this.storage.read(this.prefix+e);return t===null?void 0:JSON.parse(t)}put(e){if(typeof e!=`object`||!e||Array.isArray(e)||typeof e.id!=`string`||e.id===``)throw Error(`a record must be an object with a string id`);this.storage.write(this.prefix+e.id,JSON.stringify(e))}remove(e){this.storage.remove(this.prefix+e)}where(e){return this.all().filter(e)}clear(){for(let e of this.keys())this.storage.remove(e)}keys(){return this.storage.keys().filter(e=>e.startsWith(this.prefix))}read(e){return JSON.parse(this.storage.read(e))}},qt=class{constructor(e,t){this.frame=0,this.recorded=[],this.actions=e,this.frames=t,this.onAction=e=>{this.recorded.push({frame:this.frame,action:e})},this.onFrame=()=>{this.frame++},e.add(this.onAction),t.add(this.onFrame)}get events(){return this.recorded}toJSON(){return this.recorded.map(e=>({frame:e.frame,action:e.action}))}stop(){this.actions.remove(this.onAction),this.frames.remove(this.onFrame)}},Jt=class{constructor(e,t,n){this.frame=0,this.index=0,this.events=e,this.dispatch=t,this.frames=n,this.onFrame=()=>this.pump(),n.add(this.onFrame)}get done(){return this.index>=this.events.length}stop(){this.frames.remove(this.onFrame)}pump(){for(;this.index<this.events.length&&this.events[this.index].frame<=this.frame;)this.dispatch(this.events[this.index].action),this.index++;this.frame++}};function Yt(e){return JSON.stringify(e)}function Xt(e){let t=JSON.parse(e);if(!Array.isArray(t))throw Error(`a replay must be an array of {frame, action}`);return t.map(e=>{if(typeof e!=`object`||!e||!Number.isInteger(e.frame)||e.frame<0||typeof e.action!=`string`)throw Error(`a replay entry must be {frame: a non-negative integer, action: a string}`);return{frame:e.frame,action:e.action}})}var Zt=class e{constructor(){this.entries=[],this.nextSequence=0}append(e,t=[]){let n={sequence:this.nextSequence++,action:e,events:structuredClone([...t])};return this.entries.push(n),structuredClone(n)}get size(){return this.entries.length}get all(){return structuredClone(this.entries)}mark(){return this.nextSequence}since(e){return structuredClone(this.entries.filter(t=>t.sequence>=e))}truncate(e){this.entries=this.entries.filter(t=>t.sequence<e),this.nextSequence=e}toJSON(){return this.all}static fromJSON(t){let n=new e,r=0;for(let e of t){if(!Number.isSafeInteger(e.sequence)||e.sequence!==r)throw Error(`action journal sequences must be contiguous from zero`);n.entries.push(structuredClone({sequence:e.sequence,action:e.action,events:[...e.events]})),r++}return n.nextSequence=r,n}};function Qt(e){if(e.criteria)return e.criteria;if(e.counter===void 0||e.target===void 0)throw Error(`achievement "${e.id}" needs either counter/target or criteria`);return[{counter:e.counter,target:e.target}]}var $t=class e{constructor(){this.definitions=new Map,this.counts=new Map,this.fresh=[]}define(e){this.definitions.set(e.id,e)}count(e){return this.counts.get(e)??0}increment(e,t=1){let n=this.count(e);this.counts.set(e,n+t);let r=[];for(let t of this.definitions.values()){let i=Qt(t);i.some(t=>t.counter===e)&&(i.every(t=>t.counter===e?n>=t.target:this.count(t.counter)>=t.target)||i.every(e=>this.count(e.counter)>=e.target)&&(r.push(t.id),this.fresh.push(t.id)))}return r}unlocked(e){let t=this.definitions.get(e);if(!t)throw Error(`no such achievement: "${e}"`);return Qt(t).every(e=>this.count(e.counter)>=e.target)}progress(e){let t=this.definitions.get(e);if(!t)throw Error(`no such achievement: "${e}"`);let n=Qt(t);if(n.length!==1)throw Error(`achievement "${e}" has several criteria - use subProgress`);return{count:this.count(n[0].counter),target:n[0].target}}subProgress(e){let t=this.definitions.get(e);if(!t)throw Error(`no such achievement: "${e}"`);return Qt(t).map(e=>{let t=this.count(e.counter);return{counter:e.counter,count:t,target:e.target,met:t>=e.target}})}drainNew(){let e=this.fresh;return this.fresh=[],e}toJSON(){return{counts:[...this.counts]}}static fromJSON(t,n){let r=new e;for(let e of t)r.define(e);for(let[e,t]of n.counts)r.counts.set(e,t);return r}},en=class e{constructor(e=[]){this.active=new Set,this.spent=new Set,this.rules=[...e]}add(e){this.rules.push(e)}remove(e){this.rules=this.rules.filter(t=>t.id!==e),this.active.delete(e)}check(e){let t=[];for(let n of this.rules){if(n.once&&this.spent.has(n.id))continue;let r=n.when(e);r&&!this.active.has(n.id)&&(n.action(e),t.push(n.id),n.once&&this.spent.add(n.id)),r?this.active.add(n.id):this.active.delete(n.id)}return t}isActive(e){return this.active.has(e)}reset(){this.active.clear(),this.spent.clear()}toJSON(){return{active:[...this.active],spent:[...this.spent]}}static fromJSON(t,n){let r=new e(t);for(let e of n.active)r.active.add(e);for(let e of n.spent)r.spent.add(e);return r}},tn=class{constructor(e={}){let t=e.storage??Mt(),n=`mwg-session:${e.namespace??`default`}`,r=Number(t.read(n)??`0`);this.launches=(Number.isFinite(r)?r:0)+1,t.write(n,String(this.launches))}},nn=class extends Ft{constructor(e){super(e,`feedback`)}async submit(e){if(!e.message?.trim())throw Error(`feedback message cannot be empty`);return this.withTimeout(async t=>{let n=await this.fetchFn(this.endpoint,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(e),signal:t});if(!n.ok)throw Error(`feedback request failed with HTTP ${n.status}`);return{ok:!0,status:n.status}})}},rn=class{constructor(e){this.schedule=[],this.cursor=0,this.elapsed=0,this.startedWaves=new Set,this.completed=!1,this.onSpawn=e.onSpawn,this.onWaveStart=e.onWaveStart,this.onComplete=e.onComplete,e.waves.forEach((e,t)=>{let n=e.entries.reduce((e,t)=>e+t.count,0),r=e.duration??0,i=0;for(let a of e.entries)for(let o=0;o<a.count;o++,i++){let o=n>1&&r>0?i/(n-1)*r:0;this.schedule.push({time:e.delay+o,kind:a.kind,waveIndex:t})}}),this.schedule.sort((e,t)=>e.time-t.time),this.schedule.length===0&&(this.completed=!0,this.onComplete?.())}update(e){if(!this.completed){for(this.elapsed+=e;this.cursor<this.schedule.length&&this.schedule[this.cursor].time<=this.elapsed;){let e=this.schedule[this.cursor];this.startedWaves.has(e.waveIndex)||(this.startedWaves.add(e.waveIndex),this.onWaveStart?.(e.waveIndex)),this.onSpawn(e.kind),this.cursor++}this.cursor>=this.schedule.length&&(this.completed=!0,this.onComplete?.())}}get isComplete(){return this.completed}};function an(e,t){let n=e,r=t-(e-(e&1))/2;return{x:n,y:-n-r,z:r}}function on(e){return{x:e.x,y:e.z+(e.x-(e.x&1))/2}}var sn=[{x:1,y:-1,z:0},{x:1,y:0,z:-1},{x:0,y:1,z:-1},{x:-1,y:1,z:0},{x:-1,y:0,z:1},{x:0,y:-1,z:1}];function cn(e,t){let n=an(e,t);return sn.map(e=>on({x:n.x+e.x,y:n.y+e.y,z:n.z+e.z}))}function ln(e,t){let n=an(e.x,e.y),r=an(t.x,t.y);return Math.max(Math.abs(n.x-r.x),Math.abs(n.y-r.y),Math.abs(n.z-r.z))}function un(e){let t=Math.round(e.x),n=Math.round(e.y),r=Math.round(e.z),i=Math.abs(t-e.x),a=Math.abs(n-e.y),o=Math.abs(r-e.z);return i>a&&i>o?t=-n-r:a>o?n=-t-r:r=-t-n,{x:t,y:n,z:r}}function dn(e,t){let n=ln(e,t);if(n===0)return[{x:e.x,y:e.y}];let r=an(e.x,e.y),i=an(t.x,t.y),a=[];for(let e=0;e<=n;e++){let t=e/n;a.push(on(un({x:r.x+(i.x-r.x)*t,y:r.y+(i.y-r.y)*t,z:r.z+(i.z-r.z)*t})))}return a}function fn(e,t){let n=an(e.x,e.y),r=[];for(let e=-t;e<=t;e++)for(let i=Math.max(-t,-e-t);i<=Math.min(t,-e+t);i++){let t=-e-i;r.push(on({x:n.x+e,y:n.y+i,z:n.z+t}))}return r}function pn(e,t,n,r,i={}){let a=+((i.offset??`odd`)===`odd`);return(i.orientation??`flat-top`)===`pointy-top`?{x:e*n+((t&1)===a?n/2:0)+n/2,y:t*r*.75+r/2}:{x:e*n*.75+n/2,y:t*r+((e&1)===a?r/2:0)+r/2}}function mn(e,t,n,r,i={}){let a=(i.orientation??`flat-top`)===`pointy-top`,o=a?n:n*.75,s=a?r*.75:r,c=Math.round((e-n/2)/o),l=Math.round((t-r/2)/s),u={x:c,y:l},d=1/0;for(let a=-2;a<=2;a++)for(let o=-2;o<=2;o++){let s={x:c+a,y:l+o},f=pn(s.x,s.y,n,r,i),p=(f.x-e)**2+(f.y-t)**2;p<d&&(d=p,u=s)}return u}var hn=.12,gn=null,_n,vn=new p;function yn(){if(_n===void 0&&(_n=typeof matchMedia==`function`?matchMedia(`(prefers-reduced-motion: reduce)`):null,_n)){let e=()=>{vn.dispatch(xn())};typeof _n.addEventListener==`function`?_n.addEventListener(`change`,e):typeof _n.addListener==`function`&&_n.addListener(e)}return _n}function bn(){return yn()?.matches??!1}function xn(){return gn??bn()}function Sn(e){gn=e,vn.dispatch(xn())}function Cn(e){return yn(),vn.add(e),()=>vn.remove(e)}function wn(e,t=`decorative`){return xn()?t===`meaningful`?Math.min(e,hn):0:e}var Tn=[[0,-1],[1,0],[0,1],[-1,0]],En=class e{constructor(e,t){this.width=e,this.height=t,this.volume=new Float32Array(e*t)}index(e,t){return e<0||t<0||e>=this.width||t>=this.height?-1:t*this.width+e}volumeAt(e,t){let n=this.index(e,t);return n<0?0:this.volume[n]}total(){let e=0;for(let t=0;t<this.volume.length;t++)e+=this.volume[t];return e}seed(e,t,n){let r=this.index(e,t);r>=0&&(this.volume[r]+=n)}clear(e,t){let n=this.index(e,t);n>=0&&(this.volume[n]=0)}spread(e,t=.25,n=.9){let r=new Float32Array(this.volume.length);for(let n=0;n<this.height;n++)for(let i=0;i<this.width;i++){let a=n*this.width+i,o=this.volume[a];if(o<=0)continue;let s=[];for(let[t,r]of Tn){let a=i+t,o=n+r,c=this.index(a,o);c>=0&&e(a,o)&&s.push(c)}if(s.length===0)r[a]+=o;else{let e=o*t/s.length;r[a]+=o-e*s.length;for(let t of s)r[t]+=e}}let i=[];for(let e=0;e<r.length;e++){let t=r[e]*n,a=t<.001?0:t;a===0&&this.volume[e]>0&&i.push({x:e%this.width,y:Math.floor(e/this.width)}),this.volume[e]=a}return i}cellsAbove(e){let t=[];for(let n=0;n<this.height;n++)for(let r=0;r<this.width;r++){let i=this.volume[n*this.width+r];i>=e&&t.push({x:r,y:n,volume:i})}return t}toJSON(){return{width:this.width,height:this.height,volume:[...this.volume]}}static fromJSON(t){let n=new e(t.width,t.height);return n.volume.set(t.volume.slice(0,n.volume.length)),n}},Dn={linear:e=>e,easeInQuad:e=>e*e,easeOutQuad:e=>e*(2-e),easeInOutQuad:e=>e<.5?2*e*e:1-(-2*e+2)**2/2,easeInCubic:e=>e*e*e,easeOutCubic:e=>1-(1-e)**3,easeInOutCubic:e=>e<.5?4*e*e*e:1-(-2*e+2)**3/2},On=class{constructor(){this.tweens=[]}tween(e,t,n=Dn.linear){let{ease:r=Dn.linear,intent:i=`decorative`,alternate:a}=typeof n==`function`?{ease:n}:n,o=xn()&&a!==void 0,s=o?a:t,c=wn(e,o?`meaningful`:i);return c>0?new Promise(e=>{this.tweens.push({elapsed:0,duration:c,ease:r,apply:s,resolve:e,finishOnReduced:!o&&i===`decorative`})}):(s(1),Promise.resolve())}update(e){if(this.tweens.length!==0)for(let t of[...this.tweens]){if(t.finishOnReduced&&xn()){this.tweens.splice(this.tweens.indexOf(t),1),t.apply(1),t.resolve();continue}t.elapsed+=e;let n=Math.min(1,t.elapsed/t.duration);t.apply(t.ease(n)),n>=1&&(this.tweens.splice(this.tweens.indexOf(t),1),t.resolve())}}get isBusy(){return this.tweens.length>0}clear(){this.tweens=[]}},kn=class{constructor(e={}){this.history=[],this.cursor=-1,this.limit=Math.max(1,e.limit??50)}push(e){this.history.length=this.cursor+1,this.history.push(e),this.history.length>this.limit&&this.history.shift(),this.cursor=this.history.length-1}get canUndo(){return this.cursor>0}get canRedo(){return this.cursor<this.history.length-1}undo(){return this.canUndo?(this.cursor--,this.history[this.cursor]):null}redo(){return this.canRedo?(this.cursor++,this.history[this.cursor]):null}get current(){return this.cursor>=0?this.history[this.cursor]:null}clear(){this.history=[],this.cursor=-1}};function An(e,t){if(!Number.isFinite(t.maxCost)||t.maxCost<0)return new Map;let n=t.key(e),r=new Map([[n,{cell:e,cost:0}]]),i=[{cell:e,key:n,cost:0}];for(;i.length>0;){let e=Mn(i),n=r.get(e.key);if(!(!n||e.cost!==n.cost)&&!t.stop?.(e.cell,e.cost))for(let n of t.neighbors(e.cell)){let a=t.cost(e.cell,n);if(!Number.isFinite(a)||a<0)continue;let o=e.cost+a;if(o>t.maxCost||t.canEnter&&!t.canEnter(n,e.cell,o))continue;let s=t.key(n);if(o>=(r.get(s)?.cost??1/0))continue;let c={cell:n,key:s,cost:o};r.set(s,c),jn(i,c)}}return r}function jn(e,t){e.push(t);let n=e.length-1;for(;n>0;){let t=Math.floor((n-1)/2);if(e[t].cost<=e[n].cost)break;[e[t],e[n]]=[e[n],e[t]],n=t}}function Mn(e){let t=e[0],n=e.pop();if(!t||!n||e.length===0)return t;e[0]=n;let r=0;for(;;){let t=r*2+1,n=t+1,i=r;if(t<e.length&&e[t].cost<e[i].cost&&(i=t),n<e.length&&e[n].cost<e[i].cost&&(i=n),i===r)break;[e[r],e[i]]=[e[i],e[r]],r=i}return t}var Nn=class{constructor(){this.changed=new p,this.tasks=[],this.progress=new Map,this.status_=`idle`,this.current_=null,this.error_=null,this.cancelled=!1}add(e){if(!e.id)throw Error(`load task needs an id`);if(this.tasks.some(t=>t.id===e.id))throw Error(`duplicate load task "${e.id}"`);if(e.weight!==void 0&&!(e.weight>0))throw Error(`load task weight must be positive`);if(this.status_===`loading`)throw Error(`cannot add a task while loading`);return this.tasks.push(e),this.progress.set(e.id,0),this.emit(),this}get snapshot(){let e=this.tasks.reduce((e,t)=>e+(t.weight??1),0),t=this.tasks.reduce((e,t)=>e+(t.weight??1)*(this.progress.get(t.id)??0),0);return{status:this.status_,completed:t,total:e,current:this.current_,error:this.error_}}async start(){if(this.status_===`loading`)throw Error(`load queue is already running`);this.status_=`loading`,this.cancelled=!1,this.error_=null,this.emit();try{for(let e of this.tasks){if(this.cancelled)break;this.current_=e.id,this.emit();let t=this;await e.run({get cancelled(){return t.cancelled},report:t=>this.report(e.id,t)}),this.cancelled||this.report(e.id,1)}this.current_=null,this.status_=this.cancelled?`cancelled`:`ready`,this.emit()}catch(e){throw this.current_=null,this.error_=e,this.status_=`failed`,this.emit(),e}}cancel(){this.status_===`loading`&&(this.cancelled=!0)}retry(){if(this.status_===`loading`)throw Error(`cannot retry while loading`);this.status_=`idle`,this.current_=null,this.error_=null,this.cancelled=!1;for(let e of this.tasks)this.progress.set(e.id,0);this.emit()}report(e,t){if(!Number.isFinite(t))throw Error(`load progress must be finite`);this.progress.set(e,Math.max(0,Math.min(1,t))),this.emit()}emit(){this.changed.dispatch(this.snapshot)}},Pn=class{constructor(){this.entities=new Map,this.ids=new Map,this.sequence=0}add(e,t){let n=this.ids.get(e);if(n!==void 0){if(t!==void 0&&t!==n)throw Error(`entity already has id ${n}`);return n}let r=t;if(r!==void 0){if(r.length===0)throw Error(`entity id must not be empty`);if(this.entities.has(r))throw Error(`entity id already exists: ${r}`)}else do r=`e${this.sequence++}`;while(this.entities.has(r));return this.entities.set(r,e),this.ids.set(e,r),r}get(e){return this.entities.get(e)}idOf(e){return this.ids.get(e)}has(e){return this.entities.has(e)}remove(e){let t=this.entities.get(e);return t!==void 0&&(this.entities.delete(e),this.ids.delete(t),!0)}get size(){return this.entities.size}},Fn=class{constructor(e){this.queue=[],this.busy=!1,this.remaining=0,this.play=e.play}enqueue(e){this.queue.push(...e),this.busy||this.advance()}update(e){this.busy&&(this.remaining-=e,this.remaining<=0&&this.advance())}get isBusy(){return this.busy}clear(){this.queue=[],this.busy=!1,this.remaining=0}advance(){let e=this.queue.shift();if(e===void 0){this.busy=!1,this.remaining=0;return}this.busy=!0;let t=this.play(e)||0;t>0?this.remaining=t:this.advance()}},In=2166136261,Ln=16777619;function Rn(e,t=!1){if(e==null)return`null`;switch(typeof e){case`boolean`:return e?`true`:`false`;case`number`:return Number.isFinite(e)?String(e):`null`;case`string`:return JSON.stringify(e);case`bigint`:return JSON.stringify(e.toString());case`function`:case`symbol`:return t?`null`:`undefined`}return Array.isArray(e)?`[${e.map(e=>Rn(e,!0)).join(`,`)}]`:`{${Object.entries(e).filter(([,e])=>e!==void 0&&typeof e!=`function`&&typeof e!=`symbol`).sort(([e],[t])=>e<t?-1:+(e>t)).map(([e,t])=>`${JSON.stringify(e)}:${Rn(t)}`).join(`,`)}}`}function zn(e){let t=Rn(e),n=In;for(let e=0;e<t.length;e++)n^=t.charCodeAt(e),n=Math.imul(n,Ln)>>>0;return n>>>0}var Bn=class{constructor(){this.reference=new Map,this.desyncTick=null}observe(e,t){let n=this.reference.get(e);return n===void 0?(this.reference.set(e,t),!0):n===t||(this.desyncTick===null&&(this.desyncTick=e),!1)}get divergent(){return this.desyncTick!==null}get atTick(){return this.desyncTick}reset(){this.reference.clear(),this.desyncTick=null}};function Vn(e,t={}){let n=Wn(e);if(n.length===0)return[];let[r,...i]=n,a=t.listDelimiter??`;`,o=t.mapDelimiter??`=`;return i.map((e,n)=>{let i={};return r.forEach((r,s)=>{let c=e[s]??``;c!==``&&(i[r]=Hn(c,t.columns?.[r]??`string`,r,n,a,o))}),i})}function Hn(e,t,n,r,i,a){return Un(e,t,{column:n,rowIndex:r,listDelimiter:i,mapDelimiter:a,error:()=>t===`number`?`CSV row ${r+1}, column "${n}": "${e}" is not a number`:t===`boolean`?`CSV row ${r+1}, column "${n}": "${e}" is not "true" or "false"`:t===`map`?`CSV row ${r+1}, column "${n}": "${e.split(i).map(e=>e.trim()).find(e=>e&&!e.includes(a))??e}" has no "${a}" to split a key from its value`:`CSV row ${r+1}, column "${n}": "${e}" is invalid`})}function Un(e,t,n={}){let r=n.column??`value`,i=n.listDelimiter??`;`,a=n.mapDelimiter??`=`,o=e=>{throw Error(n.error?.(e)??e)};switch(t){case`string`:return e;case`number`:{let t=Number(e);return Number.isFinite(t)||o(`${r} must be a number`),t}case`boolean`:{let t=e.toLowerCase();if(t===`true`)return!0;if(t===`false`)return!1;if(n.acceptYesNo&&t===`yes`)return!0;if(n.acceptYesNo&&t===`no`)return!1;o(`${r} must be true, false${n.acceptYesNo?`, yes, or no`:``}`)}case`list`:return e.split(i).map(e=>e.trim()).filter(e=>e.length>0);case`map`:{let t={};for(let n of e.split(i).map(e=>e.trim()).filter(e=>e.length>0)){let e=n.indexOf(a);e===-1&&o(`${r} map entry must contain ${a}`),t[n.slice(0,e).trim()]=n.slice(e+a.length).trim()}return t}}}function Wn(e){let t=[],n=[],r=``,i=!1,a=0;for(;a<e.length;){let o=e[a];if(i){if(o===`"`){if(e[a+1]===`"`){r+=`"`,a+=2;continue}i=!1,a++;continue}r+=o,a++;continue}if(o===`"`){i=!0,a++;continue}if(o===`,`){n.push(r),r=``,a++;continue}if(o===`\r`){a++;continue}if(o===`
2
2
  `){n.push(r),t.push(n),n=[],r=``,a++;continue}r+=o,a++}return(r.length>0||n.length>0)&&(n.push(r),t.push(n)),t.filter(e=>e.length!==1||e[0]!==``)}var j,Gn,Kn,M,N=s((()=>{j=(e=>(e.Application=`application`,e.WebGLPipes=`webgl-pipes`,e.WebGLPipesAdaptor=`webgl-pipes-adaptor`,e.WebGLSystem=`webgl-system`,e.WebGPUPipes=`webgpu-pipes`,e.WebGPUPipesAdaptor=`webgpu-pipes-adaptor`,e.WebGPUSystem=`webgpu-system`,e.CanvasSystem=`canvas-system`,e.CanvasPipesAdaptor=`canvas-pipes-adaptor`,e.CanvasPipes=`canvas-pipes`,e.Asset=`asset`,e.LoadParser=`load-parser`,e.ResolveParser=`resolve-parser`,e.CacheParser=`cache-parser`,e.DetectionParser=`detection-parser`,e.MaskEffect=`mask-effect`,e.BlendMode=`blend-mode`,e.TextureSource=`texture-source`,e.TextureUploaderWebGL=`texture-uploader-webgl`,e.TextureUploaderWebGPU=`texture-uploader-webgpu`,e.Environment=`environment`,e.ShapeBuilder=`shape-builder`,e.Batcher=`batcher`,e))(j||{}),Gn=e=>{if(typeof e==`function`||typeof e==`object`&&e.extension){if(!e.extension)throw Error(`Extension class must have an extension object`);e={...typeof e.extension==`object`?e.extension:{type:e.extension},ref:e}}if(typeof e==`object`)e={...e};else throw Error(`Invalid extension type`);return typeof e.type==`string`&&(e.type=[e.type]),e},Kn=(e,t)=>Gn(e).priority??t,M={_addHandlers:{},_removeHandlers:{},_queue:{},remove(...e){return e.map(Gn).forEach(e=>{e.type.forEach(t=>this._removeHandlers[t]?.(e))}),this},add(...e){return e.map(Gn).forEach(e=>{e.type.forEach(t=>{let n=this._addHandlers,r=this._queue;n[t]?n[t]?.(e):(r[t]=r[t]||[],r[t]?.push(e))})}),this},handle(e,t,n){let r=this._addHandlers,i=this._removeHandlers;if(r[e]||i[e])throw Error(`Extension type ${e} already has a handler`);r[e]=t,i[e]=n;let a=this._queue;return a[e]&&(a[e]?.forEach(e=>t(e)),delete a[e]),this},handleByMap(e,t){return this.handle(e,e=>{e.name&&(t[e.name]=e.ref)},e=>{e.name&&delete t[e.name]})},handleByNamedList(e,t,n=-1){return this.handle(e,e=>{t.findIndex(t=>t.name===e.name)>=0||(t.push({name:e.name,value:e.ref}),t.sort((e,t)=>Kn(t.value,n)-Kn(e.value,n)))},e=>{let n=t.findIndex(t=>t.name===e.name);n!==-1&&t.splice(n,1)})},handleByList(e,t,n=-1){return this.handle(e,e=>{t.includes(e.ref)||(t.push(e.ref),t.sort((e,t)=>Kn(t,n)-Kn(e,n)))},e=>{let n=t.indexOf(e.ref);n!==-1&&t.splice(n,1)})},mixin(e,...t){for(let n of t)Object.defineProperties(e.prototype,Object.getOwnPropertyDescriptors(n))}}})),qn=c(((e,t)=>{var n=Object.prototype.hasOwnProperty,r=`~`;function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(r=!1));function a(e,t,n){this.fn=e,this.context=t,this.once=n||!1}function o(e,t,n,i,o){if(typeof n!=`function`)throw TypeError(`The listener must be a function`);var s=new a(n,i||e,o),c=r?r+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],s]:e._events[c].push(s):(e._events[c]=s,e._eventsCount++),e}function s(e,t){--e._eventsCount===0?e._events=new i:delete e._events[t]}function c(){this._events=new i,this._eventsCount=0}c.prototype.eventNames=function(){var e=[],t,i;if(this._eventsCount===0)return e;for(i in t=this._events)n.call(t,i)&&e.push(r?i.slice(1):i);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e},c.prototype.listeners=function(e){var t=r?r+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var i=0,a=n.length,o=Array(a);i<a;i++)o[i]=n[i].fn;return o},c.prototype.listenerCount=function(e){var t=r?r+e:e,n=this._events[t];return n?n.fn?1:n.length:0},c.prototype.emit=function(e,t,n,i,a,o){var s=r?r+e:e;if(!this._events[s])return!1;var c=this._events[s],l=arguments.length,u,d;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),l){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,n),!0;case 4:return c.fn.call(c.context,t,n,i),!0;case 5:return c.fn.call(c.context,t,n,i,a),!0;case 6:return c.fn.call(c.context,t,n,i,a,o),!0}for(d=1,u=Array(l-1);d<l;d++)u[d-1]=arguments[d];c.fn.apply(c.context,u)}else{var f=c.length,p;for(d=0;d<f;d++)switch(c[d].once&&this.removeListener(e,c[d].fn,void 0,!0),l){case 1:c[d].fn.call(c[d].context);break;case 2:c[d].fn.call(c[d].context,t);break;case 3:c[d].fn.call(c[d].context,t,n);break;case 4:c[d].fn.call(c[d].context,t,n,i);break;default:if(!u)for(p=1,u=Array(l-1);p<l;p++)u[p-1]=arguments[p];c[d].fn.apply(c[d].context,u)}}return!0},c.prototype.on=function(e,t,n){return o(this,e,t,n,!1)},c.prototype.once=function(e,t,n){return o(this,e,t,n,!0)},c.prototype.removeListener=function(e,t,n,i){var a=r?r+e:e;if(!this._events[a])return this;if(!t)return s(this,a),this;var o=this._events[a];if(o.fn)o.fn===t&&(!i||o.once)&&(!n||o.context===n)&&s(this,a);else{for(var c=0,l=[],u=o.length;c<u;c++)(o[c].fn!==t||i&&!o[c].once||n&&o[c].context!==n)&&l.push(o[c]);l.length?this._events[a]=l.length===1?l[0]:l:s(this,a)}return this},c.prototype.removeAllListeners=function(e){var t;return e?(t=r?r+e:e,this._events[t]&&s(this,t)):(this._events=new i,this._eventsCount=0),this},c.prototype.off=c.prototype.removeListener,c.prototype.addListener=c.prototype.on,c.prefixed=r,c.EventEmitter=c,t!==void 0&&(t.exports=c)})),Jn,Yn,Xn=s((()=>{Jn=d(qn(),1),Yn=Jn.default})),Zn,Qn,$n,er,tr,nr,rr,ir,ar,or,sr,cr,lr,ur,dr,fr,pr,mr,hr,gr,_r,vr,yr,br,xr,Sr,Cr,wr,Tr,Er=s((()=>{Zn={grad:.9,turn:360,rad:360/(2*Math.PI)},Qn=function(e){return typeof e==`string`?e.length>0:typeof e==`number`},$n=function(e,t,n){return t===void 0&&(t=0),n===void 0&&(n=10**t),Math.round(n*e)/n+0},er=function(e,t,n){return t===void 0&&(t=0),n===void 0&&(n=1),e>n?n:e>t?e:t},tr=function(e){return(e=isFinite(e)?e%360:0)>0?e:e+360},nr=function(e){return{r:er(e.r,0,255),g:er(e.g,0,255),b:er(e.b,0,255),a:er(e.a)}},rr=function(e){return{r:$n(e.r),g:$n(e.g),b:$n(e.b),a:$n(e.a,3)}},ir=/^#([0-9a-f]{3,8})$/i,ar=function(e){var t=e.toString(16);return t.length<2?`0`+t:t},or=function(e){var t=e.r,n=e.g,r=e.b,i=e.a,a=Math.max(t,n,r),o=a-Math.min(t,n,r),s=o?a===t?(n-r)/o:a===n?2+(r-t)/o:4+(t-n)/o:0;return{h:60*(s<0?s+6:s),s:a?o/a*100:0,v:a/255*100,a:i}},sr=function(e){var t=e.h,n=e.s,r=e.v,i=e.a;t=t/360*6,n/=100,r/=100;var a=Math.floor(t),o=r*(1-n),s=r*(1-(t-a)*n),c=r*(1-(1-t+a)*n),l=a%6;return{r:255*[r,s,o,o,c,r][l],g:255*[c,r,r,s,o,o][l],b:255*[o,o,c,r,r,s][l],a:i}},cr=function(e){return{h:tr(e.h),s:er(e.s,0,100),l:er(e.l,0,100),a:er(e.a)}},lr=function(e){return{h:$n(e.h),s:$n(e.s),l:$n(e.l),a:$n(e.a,3)}},ur=function(e){return sr((n=(t=e).s,{h:t.h,s:(n*=((r=t.l)<50?r:100-r)/100)>0?2*n/(r+n)*100:0,v:r+n,a:t.a}));var t,n,r},dr=function(e){return{h:(t=or(e)).h,s:(i=(200-(n=t.s))*(r=t.v)/100)>0&&i<200?n*r/100/(i<=100?i:200-i)*100:0,l:i/2,a:t.a};var t,n,r,i},fr=/^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s*,\s*([+-]?\d*\.?\d+)%\s*,\s*([+-]?\d*\.?\d+)%\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,pr=/^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s+([+-]?\d*\.?\d+)%\s+([+-]?\d*\.?\d+)%\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,mr=/^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,hr=/^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,gr={string:[[function(e){var t=ir.exec(e);return t?(e=t[1]).length<=4?{r:parseInt(e[0]+e[0],16),g:parseInt(e[1]+e[1],16),b:parseInt(e[2]+e[2],16),a:e.length===4?$n(parseInt(e[3]+e[3],16)/255,2):1}:e.length===6||e.length===8?{r:parseInt(e.substr(0,2),16),g:parseInt(e.substr(2,2),16),b:parseInt(e.substr(4,2),16),a:e.length===8?$n(parseInt(e.substr(6,2),16)/255,2):1}:null:null},`hex`],[function(e){var t=mr.exec(e)||hr.exec(e);return t?t[2]!==t[4]||t[4]!==t[6]?null:nr({r:Number(t[1])/(t[2]?100/255:1),g:Number(t[3])/(t[4]?100/255:1),b:Number(t[5])/(t[6]?100/255:1),a:t[7]===void 0?1:Number(t[7])/(t[8]?100:1)}):null},`rgb`],[function(e){var t=fr.exec(e)||pr.exec(e);if(!t)return null;var n,r;return ur(cr({h:(n=t[1],r=t[2],r===void 0&&(r=`deg`),Number(n)*(Zn[r]||1)),s:Number(t[3]),l:Number(t[4]),a:t[5]===void 0?1:Number(t[5])/(t[6]?100:1)}))},`hsl`]],object:[[function(e){var t=e.r,n=e.g,r=e.b,i=e.a,a=i===void 0?1:i;return Qn(t)&&Qn(n)&&Qn(r)?nr({r:Number(t),g:Number(n),b:Number(r),a:Number(a)}):null},`rgb`],[function(e){var t=e.h,n=e.s,r=e.l,i=e.a,a=i===void 0?1:i;return!Qn(t)||!Qn(n)||!Qn(r)?null:ur(cr({h:Number(t),s:Number(n),l:Number(r),a:Number(a)}))},`hsl`],[function(e){var t=e.h,n=e.s,r=e.v,i=e.a,a=i===void 0?1:i;return!Qn(t)||!Qn(n)||!Qn(r)?null:sr(function(e){return{h:tr(e.h),s:er(e.s,0,100),v:er(e.v,0,100),a:er(e.a)}}({h:Number(t),s:Number(n),v:Number(r),a:Number(a)}))},`hsv`]]},_r=function(e,t){for(var n=0;n<t.length;n++){var r=t[n][0](e);if(r)return[r,t[n][1]]}return[null,void 0]},vr=function(e){return typeof e==`string`?_r(e.trim(),gr.string):typeof e==`object`&&e?_r(e,gr.object):[null,void 0]},yr=function(e,t){var n=dr(e);return{h:n.h,s:er(n.s+100*t,0,100),l:n.l,a:n.a}},br=function(e){return(299*e.r+587*e.g+114*e.b)/1e3/255},xr=function(e,t){var n=dr(e);return{h:n.h,s:n.s,l:er(n.l+100*t,0,100),a:n.a}},Sr=function(){function e(e){this.parsed=vr(e)[0],this.rgba=this.parsed||{r:0,g:0,b:0,a:1}}return e.prototype.isValid=function(){return this.parsed!==null},e.prototype.brightness=function(){return $n(br(this.rgba),2)},e.prototype.isDark=function(){return br(this.rgba)<.5},e.prototype.isLight=function(){return br(this.rgba)>=.5},e.prototype.toHex=function(){return e=rr(this.rgba),t=e.r,n=e.g,r=e.b,a=(i=e.a)<1?ar($n(255*i)):``,`#`+ar(t)+ar(n)+ar(r)+a;var e,t,n,r,i,a},e.prototype.toRgb=function(){return rr(this.rgba)},e.prototype.toRgbString=function(){return e=rr(this.rgba),t=e.r,n=e.g,r=e.b,(i=e.a)<1?`rgba(`+t+`, `+n+`, `+r+`, `+i+`)`:`rgb(`+t+`, `+n+`, `+r+`)`;var e,t,n,r,i},e.prototype.toHsl=function(){return lr(dr(this.rgba))},e.prototype.toHslString=function(){return e=lr(dr(this.rgba)),t=e.h,n=e.s,r=e.l,(i=e.a)<1?`hsla(`+t+`, `+n+`%, `+r+`%, `+i+`)`:`hsl(`+t+`, `+n+`%, `+r+`%)`;var e,t,n,r,i},e.prototype.toHsv=function(){return e=or(this.rgba),{h:$n(e.h),s:$n(e.s),v:$n(e.v),a:$n(e.a,3)};var e},e.prototype.invert=function(){return Cr({r:255-(e=this.rgba).r,g:255-e.g,b:255-e.b,a:e.a});var e},e.prototype.saturate=function(e){return e===void 0&&(e=.1),Cr(yr(this.rgba,e))},e.prototype.desaturate=function(e){return e===void 0&&(e=.1),Cr(yr(this.rgba,-e))},e.prototype.grayscale=function(){return Cr(yr(this.rgba,-1))},e.prototype.lighten=function(e){return e===void 0&&(e=.1),Cr(xr(this.rgba,e))},e.prototype.darken=function(e){return e===void 0&&(e=.1),Cr(xr(this.rgba,-e))},e.prototype.rotate=function(e){return e===void 0&&(e=15),this.hue(this.hue()+e)},e.prototype.alpha=function(e){return typeof e==`number`?Cr({r:(t=this.rgba).r,g:t.g,b:t.b,a:e}):$n(this.rgba.a,3);var t},e.prototype.hue=function(e){var t=dr(this.rgba);return typeof e==`number`?Cr({h:e,s:t.s,l:t.l,a:t.a}):$n(t.h)},e.prototype.isEqual=function(e){return this.toHex()===Cr(e).toHex()},e}(),Cr=function(e){return e instanceof Sr?e:new Sr(e)},wr=[],Tr=function(e){e.forEach(function(e){wr.indexOf(e)<0&&(e(Sr,gr),wr.push(e))})}}));function Dr(e,t){var n={white:`#ffffff`,bisque:`#ffe4c4`,blue:`#0000ff`,cadetblue:`#5f9ea0`,chartreuse:`#7fff00`,chocolate:`#d2691e`,coral:`#ff7f50`,antiquewhite:`#faebd7`,aqua:`#00ffff`,azure:`#f0ffff`,whitesmoke:`#f5f5f5`,papayawhip:`#ffefd5`,plum:`#dda0dd`,blanchedalmond:`#ffebcd`,black:`#000000`,gold:`#ffd700`,goldenrod:`#daa520`,gainsboro:`#dcdcdc`,cornsilk:`#fff8dc`,cornflowerblue:`#6495ed`,burlywood:`#deb887`,aquamarine:`#7fffd4`,beige:`#f5f5dc`,crimson:`#dc143c`,cyan:`#00ffff`,darkblue:`#00008b`,darkcyan:`#008b8b`,darkgoldenrod:`#b8860b`,darkkhaki:`#bdb76b`,darkgray:`#a9a9a9`,darkgreen:`#006400`,darkgrey:`#a9a9a9`,peachpuff:`#ffdab9`,darkmagenta:`#8b008b`,darkred:`#8b0000`,darkorchid:`#9932cc`,darkorange:`#ff8c00`,darkslateblue:`#483d8b`,gray:`#808080`,darkslategray:`#2f4f4f`,darkslategrey:`#2f4f4f`,deeppink:`#ff1493`,deepskyblue:`#00bfff`,wheat:`#f5deb3`,firebrick:`#b22222`,floralwhite:`#fffaf0`,ghostwhite:`#f8f8ff`,darkviolet:`#9400d3`,magenta:`#ff00ff`,green:`#008000`,dodgerblue:`#1e90ff`,grey:`#808080`,honeydew:`#f0fff0`,hotpink:`#ff69b4`,blueviolet:`#8a2be2`,forestgreen:`#228b22`,lawngreen:`#7cfc00`,indianred:`#cd5c5c`,indigo:`#4b0082`,fuchsia:`#ff00ff`,brown:`#a52a2a`,maroon:`#800000`,mediumblue:`#0000cd`,lightcoral:`#f08080`,darkturquoise:`#00ced1`,lightcyan:`#e0ffff`,ivory:`#fffff0`,lightyellow:`#ffffe0`,lightsalmon:`#ffa07a`,lightseagreen:`#20b2aa`,linen:`#faf0e6`,mediumaquamarine:`#66cdaa`,lemonchiffon:`#fffacd`,lime:`#00ff00`,khaki:`#f0e68c`,mediumseagreen:`#3cb371`,limegreen:`#32cd32`,mediumspringgreen:`#00fa9a`,lightskyblue:`#87cefa`,lightblue:`#add8e6`,midnightblue:`#191970`,lightpink:`#ffb6c1`,mistyrose:`#ffe4e1`,moccasin:`#ffe4b5`,mintcream:`#f5fffa`,lightslategray:`#778899`,lightslategrey:`#778899`,navajowhite:`#ffdead`,navy:`#000080`,mediumvioletred:`#c71585`,powderblue:`#b0e0e6`,palegoldenrod:`#eee8aa`,oldlace:`#fdf5e6`,paleturquoise:`#afeeee`,mediumturquoise:`#48d1cc`,mediumorchid:`#ba55d3`,rebeccapurple:`#663399`,lightsteelblue:`#b0c4de`,mediumslateblue:`#7b68ee`,thistle:`#d8bfd8`,tan:`#d2b48c`,orchid:`#da70d6`,mediumpurple:`#9370db`,purple:`#800080`,pink:`#ffc0cb`,skyblue:`#87ceeb`,springgreen:`#00ff7f`,palegreen:`#98fb98`,red:`#ff0000`,yellow:`#ffff00`,slateblue:`#6a5acd`,lavenderblush:`#fff0f5`,peru:`#cd853f`,palevioletred:`#db7093`,violet:`#ee82ee`,teal:`#008080`,slategray:`#708090`,slategrey:`#708090`,aliceblue:`#f0f8ff`,darkseagreen:`#8fbc8f`,darkolivegreen:`#556b2f`,greenyellow:`#adff2f`,seagreen:`#2e8b57`,seashell:`#fff5ee`,tomato:`#ff6347`,silver:`#c0c0c0`,sienna:`#a0522d`,lavender:`#e6e6fa`,lightgreen:`#90ee90`,orange:`#ffa500`,orangered:`#ff4500`,steelblue:`#4682b4`,royalblue:`#4169e1`,turquoise:`#40e0d0`,yellowgreen:`#9acd32`,salmon:`#fa8072`,saddlebrown:`#8b4513`,sandybrown:`#f4a460`,rosybrown:`#bc8f8f`,darksalmon:`#e9967a`,lightgoldenrodyellow:`#fafad2`,snow:`#fffafa`,lightgrey:`#d3d3d3`,lightgray:`#d3d3d3`,dimgray:`#696969`,dimgrey:`#696969`,olivedrab:`#6b8e23`,olive:`#808000`},r={};for(var i in n)r[n[i]]=i;var a={};e.prototype.toName=function(t){if(!(this.rgba.a||this.rgba.r||this.rgba.g||this.rgba.b))return`transparent`;var i,o,s=r[this.toHex()];if(s)return s;if(t?.closest){var c=this.toRgb(),l=1/0,u=`black`;if(!a.length)for(var d in n)a[d]=new e(n[d]).toRgb();for(var f in n){var p=(i=c,o=a[f],(i.r-o.r)**2+(i.g-o.g)**2+(i.b-o.b)**2);p<l&&(l=p,u=f)}return u}},t.string.push([function(t){var r=t.toLowerCase(),i=r===`transparent`?`#0000`:n[r];return i?new e(i).toRgb():null},`name`])}var Or=s((()=>{})),kr,P,Ar=s((()=>{Er(),Or(),Tr([Dr]),kr=class e{constructor(e=16777215){this._value=null,this._components=new Float32Array(4),this._components.fill(1),this._int=16777215,this.value=e}get red(){return this._components[0]}get green(){return this._components[1]}get blue(){return this._components[2]}get alpha(){return this._components[3]}setValue(e){return this.value=e,this}set value(t){if(t instanceof e)this._value=this._cloneSource(t._value),this._int=t._int,this._components.set(t._components);else if(t===null)throw Error(`Cannot set Color#value to null`);else(this._value===null||!this._isSourceEqual(this._value,t))&&(this._value=this._cloneSource(t),this._normalize(this._value))}get value(){return this._value}_cloneSource(e){return typeof e==`string`||typeof e==`number`||e instanceof Number||e===null?e:Array.isArray(e)||ArrayBuffer.isView(e)?e.slice(0):typeof e==`object`&&e?{...e}:e}_isSourceEqual(e,t){let n=typeof e;if(n!==typeof t)return!1;if(n===`number`||n===`string`||e instanceof Number)return e===t;if(Array.isArray(e)&&Array.isArray(t)||ArrayBuffer.isView(e)&&ArrayBuffer.isView(t))return e.length===t.length&&e.every((e,n)=>e===t[n]);if(e!==null&&t!==null){let n=Object.keys(e),r=Object.keys(t);return n.length===r.length&&n.every(n=>e[n]===t[n])}return e===t}toRgba(){let[e,t,n,r]=this._components;return{r:e,g:t,b:n,a:r}}toRgb(){let[e,t,n]=this._components;return{r:e,g:t,b:n}}toRgbaString(){let[e,t,n]=this.toUint8RgbArray();return`rgba(${e},${t},${n},${this.alpha})`}toUint8RgbArray(e){let[t,n,r]=this._components;return this._arrayRgb||=[],e||=this._arrayRgb,e[0]=Math.round(t*255),e[1]=Math.round(n*255),e[2]=Math.round(r*255),e}toArray(e){this._arrayRgba||=[],e||=this._arrayRgba;let[t,n,r,i]=this._components;return e[0]=t,e[1]=n,e[2]=r,e[3]=i,e}toRgbArray(e){this._arrayRgb||=[],e||=this._arrayRgb;let[t,n,r]=this._components;return e[0]=t,e[1]=n,e[2]=r,e}toNumber(){return this._int}toBgrNumber(){let[e,t,n]=this.toUint8RgbArray();return(n<<16)+(t<<8)+e}toLittleEndianNumber(){let e=this._int;return(e>>16)+(e&65280)+((e&255)<<16)}multiply(t){let[n,r,i,a]=e._temp.setValue(t)._components;return this._components[0]*=n,this._components[1]*=r,this._components[2]*=i,this._components[3]*=a,this._refreshInt(),this._value=null,this}premultiply(e,t=!0){return t&&(this._components[0]*=e,this._components[1]*=e,this._components[2]*=e),this._components[3]=e,this._refreshInt(),this._value=null,this}toPremultiplied(e,t=!0){if(e===1)return(255<<24)+this._int;if(e===0)return t?0:this._int;let n=this._int>>16&255,r=this._int>>8&255,i=this._int&255;return t&&(n=n*e+.5|0,r=r*e+.5|0,i=i*e+.5|0),(e*255<<24)+(n<<16)+(r<<8)+i}toHex(){let e=this._int.toString(16);return`#${`000000`.substring(0,6-e.length)+e}`}toHexa(){let e=Math.round(this._components[3]*255).toString(16);return this.toHex()+`00`.substring(0,2-e.length)+e}setAlpha(e){return this._components[3]=this._clamp(e),this._value=null,this}_normalize(t){let n,r,i,a;if((typeof t==`number`||t instanceof Number)&&t>=0&&t<=16777215){let e=t;n=(e>>16&255)/255,r=(e>>8&255)/255,i=(e&255)/255,a=1}else if((Array.isArray(t)||t instanceof Float32Array)&&t.length>=3&&t.length<=4)t=this._clamp(t),[n,r,i,a=1]=t;else if((t instanceof Uint8Array||t instanceof Uint8ClampedArray)&&t.length>=3&&t.length<=4)t=this._clamp(t,0,255),[n,r,i,a=255]=t,n/=255,r/=255,i/=255,a/=255;else if(typeof t==`string`||typeof t==`object`){if(typeof t==`string`){let n=e.HEX_PATTERN.exec(t);n&&(t=`#${n[2]}`)}let o=Cr(t);o.isValid()&&({r:n,g:r,b:i,a}=o.rgba,n/=255,r/=255,i/=255)}if(n!==void 0)this._components[0]=n,this._components[1]=r,this._components[2]=i,this._components[3]=a,this._refreshInt();else throw Error(`Unable to convert color ${t}`)}_refreshInt(){this._clamp(this._components);let[e,t,n]=this._components;this._int=(e*255<<16)+(t*255<<8)+(n*255|0)}_clamp(e,t=0,n=1){return typeof e==`number`?Math.min(Math.max(e,t),n):(e.forEach((r,i)=>{e[i]=Math.min(Math.max(r,t),n)}),e)}static isColorLike(t){return typeof t==`number`||typeof t==`string`||t instanceof Number||t instanceof e||Array.isArray(t)||t instanceof Uint8Array||t instanceof Uint8ClampedArray||t instanceof Float32Array||t.r!==void 0&&t.g!==void 0&&t.b!==void 0||t.r!==void 0&&t.g!==void 0&&t.b!==void 0&&t.a!==void 0||t.h!==void 0&&t.s!==void 0&&t.l!==void 0||t.h!==void 0&&t.s!==void 0&&t.l!==void 0&&t.a!==void 0||t.h!==void 0&&t.s!==void 0&&t.v!==void 0||t.h!==void 0&&t.s!==void 0&&t.v!==void 0&&t.a!==void 0}},kr.shared=new kr,kr._temp=new kr,kr.HEX_PATTERN=/^(#|0x)?(([a-f0-9]{3}){1,2}([a-f0-9]{2})?)$/i,P=kr})),jr,Mr=s((()=>{jr={cullArea:null,cullable:!1,cullableChildren:!0}})),Nr,Pr,Fr,Ir=s((()=>{Nr=Math.PI*2,Pr=180/Math.PI,Fr=Math.PI/180})),Lr,Rr,zr=s((()=>{Lr=class e{constructor(e=0,t=0){this.x=0,this.y=0,this.x=e,this.y=t}clone(){return new e(this.x,this.y)}copyFrom(e){return this.set(e.x,e.y),this}copyTo(e){return e.set(this.x,this.y),e}equals(e){return e.x===this.x&&e.y===this.y}set(e=0,t=e){return this.x=e,this.y=t,this}toString(){return`[pixi.js/math:Point x=${this.x} y=${this.y}]`}static get shared(){return Rr.x=0,Rr.y=0,Rr}},Rr=new Lr})),F,Br,Vr,I=s((()=>{Ir(),zr(),F=class e{constructor(e=1,t=0,n=0,r=1,i=0,a=0){this.array=null,this.a=e,this.b=t,this.c=n,this.d=r,this.tx=i,this.ty=a}fromArray(e){this.a=e[0],this.b=e[1],this.c=e[3],this.d=e[4],this.tx=e[2],this.ty=e[5]}set(e,t,n,r,i,a){return this.a=e,this.b=t,this.c=n,this.d=r,this.tx=i,this.ty=a,this}toArray(e,t){this.array||=new Float32Array(9);let n=t||this.array;return e?(n[0]=this.a,n[1]=this.b,n[2]=0,n[3]=this.c,n[4]=this.d,n[5]=0,n[6]=this.tx,n[7]=this.ty,n[8]=1):(n[0]=this.a,n[1]=this.c,n[2]=this.tx,n[3]=this.b,n[4]=this.d,n[5]=this.ty,n[6]=0,n[7]=0,n[8]=1),n}apply(e,t){t||=new Lr;let n=e.x,r=e.y;return t.x=this.a*n+this.c*r+this.tx,t.y=this.b*n+this.d*r+this.ty,t}applyInverse(e,t){t||=new Lr;let n=this.a,r=this.b,i=this.c,a=this.d,o=this.tx,s=this.ty,c=1/(n*a+i*-r),l=e.x,u=e.y;return t.x=a*c*l+-i*c*u+(s*i-o*a)*c,t.y=n*c*u+-r*c*l+(-s*n+o*r)*c,t}translate(e,t){return this.tx+=e,this.ty+=t,this}scale(e,t){return this.a*=e,this.d*=t,this.c*=e,this.b*=t,this.tx*=e,this.ty*=t,this}rotate(e){let t=Math.cos(e),n=Math.sin(e),r=this.a,i=this.c,a=this.tx;return this.a=r*t-this.b*n,this.b=r*n+this.b*t,this.c=i*t-this.d*n,this.d=i*n+this.d*t,this.tx=a*t-this.ty*n,this.ty=a*n+this.ty*t,this}append(e){let t=this.a,n=this.b,r=this.c,i=this.d;return this.a=e.a*t+e.b*r,this.b=e.a*n+e.b*i,this.c=e.c*t+e.d*r,this.d=e.c*n+e.d*i,this.tx=e.tx*t+e.ty*r+this.tx,this.ty=e.tx*n+e.ty*i+this.ty,this}appendFrom(e,t){let n=e.a,r=e.b,i=e.c,a=e.d,o=e.tx,s=e.ty,c=t.a,l=t.b,u=t.c,d=t.d;return this.a=n*c+r*u,this.b=n*l+r*d,this.c=i*c+a*u,this.d=i*l+a*d,this.tx=o*c+s*u+t.tx,this.ty=o*l+s*d+t.ty,this}setTransform(e,t,n,r,i,a,o,s,c){return this.a=Math.cos(o+c)*i,this.b=Math.sin(o+c)*i,this.c=-Math.sin(o-s)*a,this.d=Math.cos(o-s)*a,this.tx=e-(n*this.a+r*this.c),this.ty=t-(n*this.b+r*this.d),this}prepend(e){let t=this.tx;if(e.a!==1||e.b!==0||e.c!==0||e.d!==1){let t=this.a,n=this.c;this.a=t*e.a+this.b*e.c,this.b=t*e.b+this.b*e.d,this.c=n*e.a+this.d*e.c,this.d=n*e.b+this.d*e.d}return this.tx=t*e.a+this.ty*e.c+e.tx,this.ty=t*e.b+this.ty*e.d+e.ty,this}decompose(e){let t=this.a,n=this.b,r=this.c,i=this.d,a=e.pivot,o=-Math.atan2(-r,i),s=Math.atan2(n,t),c=Math.abs(o+s);return c<1e-5||Math.abs(Nr-c)<1e-5?(e.rotation=s,e.skew.x=e.skew.y=0):(e.rotation=0,e.skew.x=o,e.skew.y=s),e.scale.x=Math.sqrt(t*t+n*n),e.scale.y=Math.sqrt(r*r+i*i),e.position.x=this.tx+(a.x*t+a.y*r),e.position.y=this.ty+(a.x*n+a.y*i),e}invert(){let e=this.a,t=this.b,n=this.c,r=this.d,i=this.tx,a=e*r-t*n;return this.a=r/a,this.b=-t/a,this.c=-n/a,this.d=e/a,this.tx=(n*this.ty-r*i)/a,this.ty=-(e*this.ty-t*i)/a,this}isIdentity(){return this.a===1&&this.b===0&&this.c===0&&this.d===1&&this.tx===0&&this.ty===0}identity(){return this.a=1,this.b=0,this.c=0,this.d=1,this.tx=0,this.ty=0,this}clone(){let t=new e;return t.a=this.a,t.b=this.b,t.c=this.c,t.d=this.d,t.tx=this.tx,t.ty=this.ty,t}copyTo(e){return e.a=this.a,e.b=this.b,e.c=this.c,e.d=this.d,e.tx=this.tx,e.ty=this.ty,e}copyFrom(e){return this.a=e.a,this.b=e.b,this.c=e.c,this.d=e.d,this.tx=e.tx,this.ty=e.ty,this}equals(e){return e.a===this.a&&e.b===this.b&&e.c===this.c&&e.d===this.d&&e.tx===this.tx&&e.ty===this.ty}toString(){return`[pixi.js:Matrix a=${this.a} b=${this.b} c=${this.c} d=${this.d} tx=${this.tx} ty=${this.ty}]`}static get IDENTITY(){return Vr.identity()}static get shared(){return Br.identity()}},Br=new F,Vr=new F})),Hr,Ur=s((()=>{Hr=class e{constructor(e,t,n){this._x=t||0,this._y=n||0,this._observer=e}clone(t){return new e(t??this._observer,this._x,this._y)}set(e=0,t=e){return(this._x!==e||this._y!==t)&&(this._x=e,this._y=t,this._observer._onUpdate(this)),this}copyFrom(e){return(this._x!==e.x||this._y!==e.y)&&(this._x=e.x,this._y=e.y,this._observer._onUpdate(this)),this}copyTo(e){return e.set(this._x,this._y),e}equals(e){return e.x===this._x&&e.y===this._y}toString(){return`[pixi.js/math:ObservablePoint x=${this._x} y=${this._y} scope=${this._observer}]`}get x(){return this._x}set x(e){this._x!==e&&(this._x=e,this._observer._onUpdate(this))}get y(){return this._y}set y(e){this._y!==e&&(this._y=e,this._observer._onUpdate(this))}}}));function Wr(e=`default`){return Gr[e]===void 0&&(Gr[e]=-1),++Gr[e]}var Gr,Kr=s((()=>{Gr={default:-1}})),qr,L,Jr,Yr,R,Xr=s((()=>{qr=new Set,L=`8.0.0`,Jr=`8.3.4`,Yr={quiet:!1,noColor:!1},R=((e,t,n=3)=>{if(Yr.quiet||qr.has(t))return;let r=Error().stack,i=`${t}
3
3
  Deprecated since v${e}`,a=typeof console.groupCollapsed==`function`&&!Yr.noColor;r===void 0?console.warn(`PixiJS Deprecation Warning: `,i):(r=r.split(`
4
4
  `).splice(n).join(`
@@ -904,11 +904,11 @@ fn mainFragment(
904
904
  cv = cu.value;
905
905
  v = uv["${r}"];
906
906
  ${e};`)}}return Function(`ud`,`uv`,`renderer`,`syncData`,n.join(`
907
- `))}var nb=s((()=>{a_(),bu(),Gg(),eb()})),rb,ib=s((()=>{N(),nb(),rb=class{constructor(e){this._cache={},this._uniformGroupSyncHash={},this._renderer=e,this.gl=null,this._cache={}}contextChange(e){this.gl=e}updateUniformGroup(e,t,n){let r=this._renderer.shader._getProgramData(t);(!e.isStatic||e._dirtyId!==r.uniformDirtyGroups[e.uid])&&(r.uniformDirtyGroups[e.uid]=e._dirtyId,this._getUniformSyncFunction(e,t)(r.uniformData,e.uniforms,this._renderer,n))}_getUniformSyncFunction(e,t){return this._uniformGroupSyncHash[e._signature]?.[t._key]||this._createUniformSyncFunction(e,t)}_createUniformSyncFunction(e,t){let n=this._uniformGroupSyncHash[e._signature]||(this._uniformGroupSyncHash[e._signature]={}),r=this._getSignature(e,t._uniformData,`u`);return this._cache[r]||(this._cache[r]=this._generateUniformsSync(e,t._uniformData)),n[t._key]=this._cache[r],n[t._key]}_generateUniformsSync(e,t){return tb(e,t)}_getSignature(e,t,n){let r=e.uniforms,i=[`${n}-`];for(let e in r)i.push(e),t[e]&&i.push(t[e].type);return i.join(`-`)}destroy(){this._renderer=null,this._cache=null}},rb.extension={type:[j.WebGLSystem],name:`uniformGroup`}}));function ab(e){let t={};if(t.normal=[e.ONE,e.ONE_MINUS_SRC_ALPHA],t.add=[e.ONE,e.ONE],t.multiply=[e.DST_COLOR,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA],t.screen=[e.ONE,e.ONE_MINUS_SRC_COLOR,e.ONE,e.ONE_MINUS_SRC_ALPHA],t.none=[0,0],t[`normal-npm`]=[e.SRC_ALPHA,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA],t[`add-npm`]=[e.SRC_ALPHA,e.ONE,e.ONE,e.ONE],t[`screen-npm`]=[e.SRC_ALPHA,e.ONE_MINUS_SRC_COLOR,e.ONE,e.ONE_MINUS_SRC_ALPHA],t.erase=[e.ZERO,e.ONE_MINUS_SRC_ALPHA],!(e instanceof K.get().getWebGLRenderingContext()))t.min=[e.ONE,e.ONE,e.ONE,e.ONE,e.MIN,e.MIN],t.max=[e.ONE,e.ONE,e.ONE,e.ONE,e.MAX,e.MAX];else{let n=e.getExtension(`EXT_blend_minmax`);n&&(t.min=[e.ONE,e.ONE,e.ONE,e.ONE,n.MIN_EXT,n.MIN_EXT],t.max=[e.ONE,e.ONE,e.ONE,e.ONE,n.MAX_EXT,n.MAX_EXT])}return t}var ob=s((()=>{q()})),sb,cb,lb,ub,db,fb,pb,mb,hb=s((()=>{N(),Nu(),ob(),{BLEND:sb,OFFSET:cb,CULLING:lb,DEPTH_TEST:ub,WINDING:db,DEPTH_MASK:fb}=wu,pb=class e{constructor(e){this._invertFrontFace=!1,this.gl=null,this.stateId=0,this.polygonOffset=0,this.blendMode=`none`,this._blendEq=!1,this.map=[],this.map[sb]=this.setBlend,this.map[cb]=this.setOffset,this.map[lb]=this.setCullFace,this.map[ub]=this.setDepthTest,this.map[db]=this.setFrontFace,this.map[fb]=this.setDepthMask,this.checks=[],this.defaultState=Mu.for2d(),e.renderTarget.onRenderTargetChange.add(this)}onRenderTargetChange(e){this._invertFrontFace=!e.isRoot!=!!e.flipY,this._cullFace?this.setFrontFace(this._frontFace):this._frontFaceDirty=!0}contextChange(e){this.gl=e,this.blendModesMap=ab(e),this.resetState()}set(e){if(e||=this.defaultState,this.stateId!==e.data){let t=this.stateId^e.data,n=0;for(;t;)t&1&&this.map[n].call(this,!!(e.data&1<<n)),t>>=1,n++;this.stateId=e.data}for(let t=0;t<this.checks.length;t++)this.checks[t](this,e)}forceState(e){e||=this.defaultState;for(let t=0;t<this.map.length;t++)this.map[t].call(this,!!(e.data&1<<t));for(let t=0;t<this.checks.length;t++)this.checks[t](this,e);this.stateId=e.data}setBlend(t){this._updateCheck(e._checkBlendMode,t),this.gl[t?`enable`:`disable`](this.gl.BLEND)}setOffset(t){this._updateCheck(e._checkPolygonOffset,t),this.gl[t?`enable`:`disable`](this.gl.POLYGON_OFFSET_FILL)}setDepthTest(e){this.gl[e?`enable`:`disable`](this.gl.DEPTH_TEST)}setDepthMask(e){this.gl.depthMask(e)}get depthMaskEnabled(){return!!(this.stateId&1<<fb)}setCullFace(e){this._cullFace=e,this.gl[e?`enable`:`disable`](this.gl.CULL_FACE),this._cullFace&&this._frontFaceDirty&&this.setFrontFace(this._frontFace)}setFrontFace(e){this._frontFace=e,this._frontFaceDirty=!1;let t=this._invertFrontFace?!e:e;this._glFrontFace!==t&&(this._glFrontFace=t,this.gl.frontFace(this.gl[t?`CW`:`CCW`]))}setBlendMode(e){if(this.blendModesMap[e]||(e=`normal`),e===this.blendMode)return;this.blendMode=e;let t=this.blendModesMap[e],n=this.gl;t.length===2?n.blendFunc(t[0],t[1]):n.blendFuncSeparate(t[0],t[1],t[2],t[3]),t.length===6?(this._blendEq=!0,n.blendEquationSeparate(t[4],t[5])):this._blendEq&&(this._blendEq=!1,n.blendEquationSeparate(n.FUNC_ADD,n.FUNC_ADD))}setPolygonOffset(e,t){this.gl.polygonOffset(e,t)}resetState(){this._glFrontFace=!1,this._frontFace=!1,this._cullFace=!1,this._frontFaceDirty=!1,this._invertFrontFace=!1,this.gl.frontFace(this.gl.CCW),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!1),this.forceState(this.defaultState),this._blendEq=!0,this.blendMode=``,this.setBlendMode(`normal`)}_updateCheck(e,t){let n=this.checks.indexOf(e);t&&n===-1?this.checks.push(e):!t&&n!==-1&&this.checks.splice(n,1)}static _checkBlendMode(e,t){e.setBlendMode(t.blendMode)}static _checkPolygonOffset(e,t){e.setPolygonOffset(1,t.polygonOffset)}destroy(){this.gl=null,this.checks.length=0}},pb.extension={type:[j.WebGLSystem],name:`state`},mb=pb})),gb,_b=s((()=>{Bv(),gb=class{constructor(e){this.target=zv.TEXTURE_2D,this._layerInitMask=0,this.texture=e,this.width=-1,this.height=-1,this.type=Z.UNSIGNED_BYTE,this.internalFormat=Rv.RGBA,this.format=Rv.RGBA,this.samplerType=0}destroy(){}}})),vb,yb=s((()=>{vb={id:`buffer`,upload(e,t,n,r,i,a=!1){let o=i||t.target;!a&&t.width===e.width&&t.height===e.height?n.texSubImage2D(o,0,0,0,e.width,e.height,t.format,t.type,e.resource):n.texImage2D(o,0,t.internalFormat,e.width,e.height,0,t.format,t.type,e.resource),t.width=e.width,t.height=e.height}}})),bb,xb,Sb=s((()=>{bb={"bc1-rgba-unorm":!0,"bc1-rgba-unorm-srgb":!0,"bc2-rgba-unorm":!0,"bc2-rgba-unorm-srgb":!0,"bc3-rgba-unorm":!0,"bc3-rgba-unorm-srgb":!0,"bc4-r-unorm":!0,"bc4-r-snorm":!0,"bc5-rg-unorm":!0,"bc5-rg-snorm":!0,"bc6h-rgb-ufloat":!0,"bc6h-rgb-float":!0,"bc7-rgba-unorm":!0,"bc7-rgba-unorm-srgb":!0,"etc2-rgb8unorm":!0,"etc2-rgb8unorm-srgb":!0,"etc2-rgb8a1unorm":!0,"etc2-rgb8a1unorm-srgb":!0,"etc2-rgba8unorm":!0,"etc2-rgba8unorm-srgb":!0,"eac-r11unorm":!0,"eac-r11snorm":!0,"eac-rg11unorm":!0,"eac-rg11snorm":!0,"astc-4x4-unorm":!0,"astc-4x4-unorm-srgb":!0,"astc-5x4-unorm":!0,"astc-5x4-unorm-srgb":!0,"astc-5x5-unorm":!0,"astc-5x5-unorm-srgb":!0,"astc-6x5-unorm":!0,"astc-6x5-unorm-srgb":!0,"astc-6x6-unorm":!0,"astc-6x6-unorm-srgb":!0,"astc-8x5-unorm":!0,"astc-8x5-unorm-srgb":!0,"astc-8x6-unorm":!0,"astc-8x6-unorm-srgb":!0,"astc-8x8-unorm":!0,"astc-8x8-unorm-srgb":!0,"astc-10x5-unorm":!0,"astc-10x5-unorm-srgb":!0,"astc-10x6-unorm":!0,"astc-10x6-unorm-srgb":!0,"astc-10x8-unorm":!0,"astc-10x8-unorm-srgb":!0,"astc-10x10-unorm":!0,"astc-10x10-unorm-srgb":!0,"astc-12x10-unorm":!0,"astc-12x10-unorm-srgb":!0,"astc-12x12-unorm":!0,"astc-12x12-unorm-srgb":!0},xb={id:`compressed`,upload(e,t,n,r,i,a){let o=i??t.target;n.pixelStorei(n.UNPACK_ALIGNMENT,4);let s=e.pixelWidth,c=e.pixelHeight,l=!!bb[e.format];for(let r=0;r<e.resource.length;r++){let i=e.resource[r];l?n.compressedTexImage2D(o,r,t.internalFormat,s,c,0,i):n.texImage2D(o,r,t.internalFormat,s,c,0,t.format,t.type,i),s=Math.max(s>>1,1),c=Math.max(c>>1,1)}}}}));function Cb(e){return{id:`cube`,upload(t,n,r,i){let a=t.faces;for(let t=0;t<wb.length;t++){let o=a[wb[t]];o.resource&&((e[o.uploadMethodId]||e.image).upload(o,n,r,i,zv.TEXTURE_CUBE_MAP_POSITIVE_X+t,!(n._layerInitMask&1<<t)),n._layerInitMask|=1<<t)}n.width=t.pixelWidth,n.height=t.pixelHeight}}}var wb,Tb=s((()=>{Bv(),wb=[`right`,`left`,`top`,`bottom`,`front`,`back`]}));function Eb(e,t,n,r,i,a,o,s,c,l){if(!l){c&&e.texImage2D(t,0,n.internalFormat,r,i,0,n.format,n.type,null),e.texSubImage2D(t,0,0,0,a,o,n.format,n.type,s);return}if(!c){e.texSubImage2D(t,0,0,0,n.format,n.type,s);return}e.texImage2D(t,0,n.internalFormat,r,i,0,n.format,n.type,s)}function Db(e,t,n,r,i,a,o,s,c,l){if(!l){c&&e.texImage2D(t,0,n.internalFormat,r,i,0,n.format,n.type,null),e.texSubImage2D(t,0,0,0,n.format,n.type,s);return}if(!c){e.texSubImage2D(t,0,0,0,n.format,n.type,s);return}e.texImage2D(t,0,n.internalFormat,n.format,n.type,s)}var Ob,kb=s((()=>{Ob={id:`image`,upload(e,t,n,r,i,a=!1){let o=i||t.target,s=e.pixelWidth,c=e.pixelHeight,l=e.resourceWidth,u=e.resourceHeight,d=r===2,f=a||t.width!==s||t.height!==c,p=l>=s&&u>=c,m=e.resource;(d?Eb:Db)(n,o,t,s,c,l,u,m,f,p),t.width=s,t.height=c}}}));function Ab(){let{userAgent:e}=K.get().getNavigator();return/^((?!chrome|android).)*safari/i.test(e)}var jb=s((()=>{q()})),Mb,Nb,Pb=s((()=>{jb(),kb(),Mb=Ab(),Nb={id:`video`,upload(e,t,n,r,i,a=Mb){if(!e.isValid){let e=i??t.target;n.texImage2D(e,0,t.internalFormat,1,1,0,t.format,t.type,null);return}Ob.upload(e,t,n,r,i,a)}}})),Fb,Ib,Lb,Rb,zb=s((()=>{Fb={linear:9729,nearest:9728},Ib={linear:{linear:9987,nearest:9985},nearest:{linear:9986,nearest:9984}},Lb={"clamp-to-edge":33071,repeat:10497,"mirror-repeat":33648},Rb={never:512,less:513,equal:514,"less-equal":515,greater:516,"not-equal":517,"greater-equal":518,always:519}}));function Bb(e,t,n,r,i,a,o,s){let c=a;if(!s||e.addressModeU!==`repeat`||e.addressModeV!==`repeat`||e.addressModeW!==`repeat`){let n=Lb[o?`clamp-to-edge`:e.addressModeU],r=Lb[o?`clamp-to-edge`:e.addressModeV],a=Lb[o?`clamp-to-edge`:e.addressModeW];t[i](c,t.TEXTURE_WRAP_S,n),t[i](c,t.TEXTURE_WRAP_T,r),t.TEXTURE_WRAP_R&&t[i](c,t.TEXTURE_WRAP_R,a)}if((!s||e.magFilter!==`linear`)&&t[i](c,t.TEXTURE_MAG_FILTER,Fb[e.magFilter]),n){if(!s||e.mipmapFilter!==`linear`){let n=Ib[e.minFilter][e.mipmapFilter];t[i](c,t.TEXTURE_MIN_FILTER,n)}}else t[i](c,t.TEXTURE_MIN_FILTER,Fb[e.minFilter]);if(r&&e.maxAnisotropy>1){let n=Math.min(e.maxAnisotropy,t.getParameter(r.MAX_TEXTURE_MAX_ANISOTROPY_EXT));t[i](c,r.TEXTURE_MAX_ANISOTROPY_EXT,n)}e.compare?(t[i](c,t.TEXTURE_COMPARE_FUNC,Rb[e.compare]),t[i](c,t.TEXTURE_COMPARE_MODE,t.COMPARE_REF_TO_TEXTURE)):s||t[i](c,t.TEXTURE_COMPARE_MODE,t.NONE)}var Vb=s((()=>{zb()}));function Hb(e){return{r8unorm:e.RED,r8snorm:e.RED,r8uint:e.RED,r8sint:e.RED,r16uint:e.RED,r16sint:e.RED,r16float:e.RED,rg8unorm:e.RG,rg8snorm:e.RG,rg8uint:e.RG,rg8sint:e.RG,r32uint:e.RED,r32sint:e.RED,r32float:e.RED,rg16uint:e.RG,rg16sint:e.RG,rg16float:e.RG,rgba8unorm:e.RGBA,"rgba8unorm-srgb":e.RGBA,rgba8snorm:e.RGBA,rgba8uint:e.RGBA,rgba8sint:e.RGBA,bgra8unorm:e.RGBA,"bgra8unorm-srgb":e.RGBA,rgb9e5ufloat:e.RGB,rgb10a2unorm:e.RGBA,rg11b10ufloat:e.RGB,rg32uint:e.RG,rg32sint:e.RG,rg32float:e.RG,rgba16uint:e.RGBA,rgba16sint:e.RGBA,rgba16float:e.RGBA,rgba32uint:e.RGBA,rgba32sint:e.RGBA,rgba32float:e.RGBA,stencil8:e.STENCIL_INDEX8,depth16unorm:e.DEPTH_COMPONENT,depth24plus:e.DEPTH_COMPONENT,"depth24plus-stencil8":e.DEPTH_STENCIL,depth32float:e.DEPTH_COMPONENT,"depth32float-stencil8":e.DEPTH_STENCIL}}var Ub=s((()=>{}));function Wb(e,t){let n={},r=e.RGBA;return e instanceof K.get().getWebGLRenderingContext()?t.srgb&&(n={"rgba8unorm-srgb":t.srgb.SRGB8_ALPHA8_EXT,"bgra8unorm-srgb":t.srgb.SRGB8_ALPHA8_EXT}):(n={"rgba8unorm-srgb":e.SRGB8_ALPHA8,"bgra8unorm-srgb":e.SRGB8_ALPHA8},r=e.RGBA8),{r8unorm:e.R8,r8snorm:e.R8_SNORM,r8uint:e.R8UI,r8sint:e.R8I,r16uint:e.R16UI,r16sint:e.R16I,r16float:e.R16F,rg8unorm:e.RG8,rg8snorm:e.RG8_SNORM,rg8uint:e.RG8UI,rg8sint:e.RG8I,r32uint:e.R32UI,r32sint:e.R32I,r32float:e.R32F,rg16uint:e.RG16UI,rg16sint:e.RG16I,rg16float:e.RG16F,rgba8unorm:e.RGBA,...n,rgba8snorm:e.RGBA8_SNORM,rgba8uint:e.RGBA8UI,rgba8sint:e.RGBA8I,bgra8unorm:r,rgb9e5ufloat:e.RGB9_E5,rgb10a2unorm:e.RGB10_A2,rg11b10ufloat:e.R11F_G11F_B10F,rg32uint:e.RG32UI,rg32sint:e.RG32I,rg32float:e.RG32F,rgba16uint:e.RGBA16UI,rgba16sint:e.RGBA16I,rgba16float:e.RGBA16F,rgba32uint:e.RGBA32UI,rgba32sint:e.RGBA32I,rgba32float:e.RGBA32F,stencil8:e.STENCIL_INDEX8,depth16unorm:e.DEPTH_COMPONENT16,depth24plus:e.DEPTH_COMPONENT24,"depth24plus-stencil8":e.DEPTH24_STENCIL8,depth32float:e.DEPTH_COMPONENT32F,"depth32float-stencil8":e.DEPTH32F_STENCIL8,...t.s3tc?{"bc1-rgba-unorm":t.s3tc.COMPRESSED_RGBA_S3TC_DXT1_EXT,"bc2-rgba-unorm":t.s3tc.COMPRESSED_RGBA_S3TC_DXT3_EXT,"bc3-rgba-unorm":t.s3tc.COMPRESSED_RGBA_S3TC_DXT5_EXT}:{},...t.s3tc_sRGB?{"bc1-rgba-unorm-srgb":t.s3tc_sRGB.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT,"bc2-rgba-unorm-srgb":t.s3tc_sRGB.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT,"bc3-rgba-unorm-srgb":t.s3tc_sRGB.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}:{},...t.rgtc?{"bc4-r-unorm":t.rgtc.COMPRESSED_RED_RGTC1_EXT,"bc4-r-snorm":t.rgtc.COMPRESSED_SIGNED_RED_RGTC1_EXT,"bc5-rg-unorm":t.rgtc.COMPRESSED_RED_GREEN_RGTC2_EXT,"bc5-rg-snorm":t.rgtc.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}:{},...t.bptc?{"bc6h-rgb-float":t.bptc.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT,"bc6h-rgb-ufloat":t.bptc.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT,"bc7-rgba-unorm":t.bptc.COMPRESSED_RGBA_BPTC_UNORM_EXT,"bc7-rgba-unorm-srgb":t.bptc.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT}:{},...t.etc?{"etc2-rgb8unorm":t.etc.COMPRESSED_RGB8_ETC2,"etc2-rgb8unorm-srgb":t.etc.COMPRESSED_SRGB8_ETC2,"etc2-rgb8a1unorm":t.etc.COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2,"etc2-rgb8a1unorm-srgb":t.etc.COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2,"etc2-rgba8unorm":t.etc.COMPRESSED_RGBA8_ETC2_EAC,"etc2-rgba8unorm-srgb":t.etc.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC,"eac-r11unorm":t.etc.COMPRESSED_R11_EAC,"eac-rg11unorm":t.etc.COMPRESSED_SIGNED_RG11_EAC}:{},...t.astc?{"astc-4x4-unorm":t.astc.COMPRESSED_RGBA_ASTC_4x4_KHR,"astc-4x4-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR,"astc-5x4-unorm":t.astc.COMPRESSED_RGBA_ASTC_5x4_KHR,"astc-5x4-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR,"astc-5x5-unorm":t.astc.COMPRESSED_RGBA_ASTC_5x5_KHR,"astc-5x5-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR,"astc-6x5-unorm":t.astc.COMPRESSED_RGBA_ASTC_6x5_KHR,"astc-6x5-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR,"astc-6x6-unorm":t.astc.COMPRESSED_RGBA_ASTC_6x6_KHR,"astc-6x6-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR,"astc-8x5-unorm":t.astc.COMPRESSED_RGBA_ASTC_8x5_KHR,"astc-8x5-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR,"astc-8x6-unorm":t.astc.COMPRESSED_RGBA_ASTC_8x6_KHR,"astc-8x6-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR,"astc-8x8-unorm":t.astc.COMPRESSED_RGBA_ASTC_8x8_KHR,"astc-8x8-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR,"astc-10x5-unorm":t.astc.COMPRESSED_RGBA_ASTC_10x5_KHR,"astc-10x5-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR,"astc-10x6-unorm":t.astc.COMPRESSED_RGBA_ASTC_10x6_KHR,"astc-10x6-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR,"astc-10x8-unorm":t.astc.COMPRESSED_RGBA_ASTC_10x8_KHR,"astc-10x8-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR,"astc-10x10-unorm":t.astc.COMPRESSED_RGBA_ASTC_10x10_KHR,"astc-10x10-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR,"astc-12x10-unorm":t.astc.COMPRESSED_RGBA_ASTC_12x10_KHR,"astc-12x10-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR,"astc-12x12-unorm":t.astc.COMPRESSED_RGBA_ASTC_12x12_KHR,"astc-12x12-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR}:{}}}var Gb=s((()=>{q()}));function Kb(e){return{r8unorm:e.UNSIGNED_BYTE,r8snorm:e.BYTE,r8uint:e.UNSIGNED_BYTE,r8sint:e.BYTE,r16uint:e.UNSIGNED_SHORT,r16sint:e.SHORT,r16float:e.HALF_FLOAT,rg8unorm:e.UNSIGNED_BYTE,rg8snorm:e.BYTE,rg8uint:e.UNSIGNED_BYTE,rg8sint:e.BYTE,r32uint:e.UNSIGNED_INT,r32sint:e.INT,r32float:e.FLOAT,rg16uint:e.UNSIGNED_SHORT,rg16sint:e.SHORT,rg16float:e.HALF_FLOAT,rgba8unorm:e.UNSIGNED_BYTE,"rgba8unorm-srgb":e.UNSIGNED_BYTE,rgba8snorm:e.BYTE,rgba8uint:e.UNSIGNED_BYTE,rgba8sint:e.BYTE,bgra8unorm:e.UNSIGNED_BYTE,"bgra8unorm-srgb":e.UNSIGNED_BYTE,rgb9e5ufloat:e.UNSIGNED_INT_5_9_9_9_REV,rgb10a2unorm:e.UNSIGNED_INT_2_10_10_10_REV,rg11b10ufloat:e.UNSIGNED_INT_10F_11F_11F_REV,rg32uint:e.UNSIGNED_INT,rg32sint:e.INT,rg32float:e.FLOAT,rgba16uint:e.UNSIGNED_SHORT,rgba16sint:e.SHORT,rgba16float:e.HALF_FLOAT,rgba32uint:e.UNSIGNED_INT,rgba32sint:e.INT,rgba32float:e.FLOAT,stencil8:e.UNSIGNED_BYTE,depth16unorm:e.UNSIGNED_SHORT,depth24plus:e.UNSIGNED_INT,"depth24plus-stencil8":e.UNSIGNED_INT_24_8,depth32float:e.FLOAT,"depth32float-stencil8":e.FLOAT_32_UNSIGNED_INT_24_8_REV}}var qb=s((()=>{}));function Jb(e){return{"2d":e.TEXTURE_2D,cube:e.TEXTURE_CUBE_MAP,"1d":null,"3d":e?.TEXTURE_3D||null,"2d-array":e?.TEXTURE_2D_ARRAY||null,"cube-array":e?.TEXTURE_CUBE_MAP_ARRAY||null}}var Yb=s((()=>{})),Xb,Zb,Qb,$b=s((()=>{q(),N(),Tg(),W(),_b(),yb(),Sb(),Tb(),kb(),Pb(),Vb(),Ub(),Gb(),qb(),Yb(),Xb=4,Zb=class e{constructor(t){this._glSamplers=Object.create(null),this._boundTextures=[],this._activeTextureLocation=-1,this._boundSamplers=Object.create(null),this._premultiplyAlpha=!1,this._useSeparateSamplers=!1,this._renderer=t,this._managedTextures=new wg({renderer:t,type:`resource`,onUnload:this.onSourceUnload.bind(this),name:`glTexture`});let n={image:Ob,buffer:vb,video:Nb,compressed:xb,...e.uploadExtensions};this._uploads={...n,cube:Cb(n)}}get managedTextures(){return Object.values(this._managedTextures.items)}contextChange(e){this._gl=e,this._mapFormatToInternalFormat||(this._mapFormatToInternalFormat=Wb(e,this._renderer.context.extensions),this._mapFormatToType=Kb(e),this._mapFormatToFormat=Hb(e),this._mapViewDimensionToGlTarget=Jb(e)),this._managedTextures.removeAll(!0),this._glSamplers=Object.create(null),this._boundSamplers=Object.create(null),this._premultiplyAlpha=!1;for(let e=0;e<16;e++)this.bind(U.EMPTY,e)}initSource(e){this.bind(e)}bind(e,t=0){let n=e.source;e?(this.bindSource(n,t),this._useSeparateSamplers&&this._bindSampler(n.style,t)):(this.bindSource(null,t),this._useSeparateSamplers&&this._bindSampler(null,t))}bindSource(e,t=0){let n=this._gl;if(e._gcLastUsed=this._renderer.gc.now,this._boundTextures[t]!==e){this._boundTextures[t]=e,this._activateLocation(t),e||=U.EMPTY.source;let r=this.getGlSource(e);n.bindTexture(r.target,r.texture)}}_bindSampler(e,t=0){let n=this._gl;if(!e){this._boundSamplers[t]=null,n.bindSampler(t,null);return}let r=this._getGlSampler(e);this._boundSamplers[t]!==r&&(this._boundSamplers[t]=r,n.bindSampler(t,r))}unbind(e){let t=e.source,n=this._boundTextures,r=this._gl;for(let e=0;e<n.length;e++)if(n[e]===t){this._activateLocation(e);let i=this.getGlSource(t);r.bindTexture(i.target,null),n[e]=null}}_activateLocation(e){this._activeTextureLocation!==e&&(this._activeTextureLocation=e,this._gl.activeTexture(this._gl.TEXTURE0+e))}_initSource(e){let t=this._gl,n=new gb(t.createTexture());if(n.type=this._mapFormatToType[e.format],n.internalFormat=this._mapFormatToInternalFormat[e.format],n.format=this._mapFormatToFormat[e.format],n.target=this._mapViewDimensionToGlTarget[e.viewDimension],n.target===null)throw Error(`Unsupported view dimension: ${e.viewDimension} with this webgl version: ${this._renderer.context.webGLVersion}`);if(e.autoGenerateMipmaps&&(this._renderer.context.supports.nonPowOf2mipmaps||e.isPowerOfTwo)){let t=Math.max(e.width,e.height);e.mipLevelCount=Math.floor(Math.log2(t))+1}return e._gpuData[this._renderer.uid]=n,this._managedTextures.add(e)&&(e.on(`update`,this.onSourceUpdate,this),e.on(`resize`,this.onSourceUpdate,this),e.on(`styleChange`,this.onStyleChange,this),e.on(`updateMipmaps`,this.onUpdateMipmaps,this)),this.onSourceUpdate(e),this.updateStyle(e,!1),n}onStyleChange(e){this.updateStyle(e,!1)}updateStyle(e,t){let n=this._gl,r=this.getGlSource(e);n.bindTexture(r.target,r.texture),this._boundTextures[this._activeTextureLocation]=e,Bb(e.style,n,e.mipLevelCount>1,this._renderer.context.extensions.anisotropicFiltering,`texParameteri`,r.target,!this._renderer.context.supports.nonPowOf2wrapping&&!e.isPowerOfTwo,t)}onSourceUnload(e,t=!1){let n=e._gpuData[this._renderer.uid];n&&(t||(this.unbind(e),this._gl.deleteTexture(n.texture)),e.off(`update`,this.onSourceUpdate,this),e.off(`resize`,this.onSourceUpdate,this),e.off(`styleChange`,this.onStyleChange,this),e.off(`updateMipmaps`,this.onUpdateMipmaps,this))}onSourceUpdate(e){let t=this._gl,n=this.getGlSource(e);t.bindTexture(n.target,n.texture),this._boundTextures[this._activeTextureLocation]=e;let r=e.alphaMode===`premultiply-alpha-on-upload`;if(this._premultiplyAlpha!==r&&(this._premultiplyAlpha=r,t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,r)),this._uploads[e.uploadMethodId])this._uploads[e.uploadMethodId].upload(e,n,t,this._renderer.context.webGLVersion);else if(n.target===t.TEXTURE_2D)this._initEmptyTexture2D(n,e);else if(n.target===t.TEXTURE_2D_ARRAY)this._initEmptyTexture2DArray(n,e);else if(n.target===t.TEXTURE_CUBE_MAP)this._initEmptyTextureCube(n,e);else throw Error(`[GlTextureSystem] Unsupported texture target for empty allocation.`);this._applyMipRange(n,e),e.autoGenerateMipmaps&&e.mipLevelCount>1&&this.onUpdateMipmaps(e,!1)}onUpdateMipmaps(e,t=!0){t&&this.bindSource(e,0);let n=this.getGlSource(e);this._gl.generateMipmap(n.target)}_initEmptyTexture2D(e,t){let n=this._gl;n.texImage2D(n.TEXTURE_2D,0,e.internalFormat,t.pixelWidth,t.pixelHeight,0,e.format,e.type,null);let r=Math.max(t.pixelWidth>>1,1),i=Math.max(t.pixelHeight>>1,1);for(let a=1;a<t.mipLevelCount;a++)n.texImage2D(n.TEXTURE_2D,a,e.internalFormat,r,i,0,e.format,e.type,null),r=Math.max(r>>1,1),i=Math.max(i>>1,1)}_initEmptyTexture2DArray(e,t){if(this._renderer.context.webGLVersion!==2)throw Error(`[GlTextureSystem] TEXTURE_2D_ARRAY requires WebGL2.`);let n=this._gl,r=Math.max(t.arrayLayerCount|0,1);n.texImage3D(n.TEXTURE_2D_ARRAY,0,e.internalFormat,t.pixelWidth,t.pixelHeight,r,0,e.format,e.type,null);let i=Math.max(t.pixelWidth>>1,1),a=Math.max(t.pixelHeight>>1,1);for(let o=1;o<t.mipLevelCount;o++)n.texImage3D(n.TEXTURE_2D_ARRAY,o,e.internalFormat,i,a,r,0,e.format,e.type,null),i=Math.max(i>>1,1),a=Math.max(a>>1,1)}_initEmptyTextureCube(e,t){let n=this._gl;for(let r=0;r<6;r++)n.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+r,0,e.internalFormat,t.pixelWidth,t.pixelHeight,0,e.format,e.type,null);let r=Math.max(t.pixelWidth>>1,1),i=Math.max(t.pixelHeight>>1,1);for(let a=1;a<t.mipLevelCount;a++){for(let t=0;t<6;t++)n.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+t,a,e.internalFormat,r,i,0,e.format,e.type,null);r=Math.max(r>>1,1),i=Math.max(i>>1,1)}}_applyMipRange(e,t){if(this._renderer.context.webGLVersion!==2||t.mipLevelCount<=1)return;let n=this._gl,r=Math.max((t.mipLevelCount|0)-1,0);n.texParameteri(e.target,n.TEXTURE_BASE_LEVEL,0),n.texParameteri(e.target,n.TEXTURE_MAX_LEVEL,r)}_initSampler(e){let t=this._gl,n=this._gl.createSampler();return this._glSamplers[e._resourceId]=n,Bb(e,t,this._boundTextures[this._activeTextureLocation].mipLevelCount>1,this._renderer.context.extensions.anisotropicFiltering,`samplerParameteri`,n,!1,!0),this._glSamplers[e._resourceId]}_getGlSampler(e){return this._glSamplers[e._resourceId]||this._initSampler(e)}getGlSource(e){return e._gcLastUsed=this._renderer.gc.now,e._gpuData[this._renderer.uid]||this._initSource(e)}generateCanvas(e){let{pixels:t,width:n,height:r}=this.getPixels(e),i=K.get().createCanvas();i.width=n,i.height=r;let a=i.getContext(`2d`);if(a){let e=a.createImageData(n,r);e.data.set(t),a.putImageData(e,0,0)}return i}getPixels(e){let t=e.source.resolution,n=e.frame,r=Math.max(Math.round(n.width*t),1),i=Math.max(Math.round(n.height*t),1),a=new Uint8Array(Xb*r*i),o=this._renderer,s=o.renderTarget.getRenderTarget(e),c=o.renderTarget.getGpuRenderTarget(s),l=o.gl;return o.renderTarget.adaptor.bindFramebuffer(c.resolveTargetFramebuffer),l.readPixels(Math.round(n.x*t),Math.round(n.y*t),r,i,l.RGBA,l.UNSIGNED_BYTE,a),{pixels:new Uint8ClampedArray(a.buffer),width:r,height:i}}destroy(){this._managedTextures.destroy(),this._glSamplers=null,this._boundTextures=null,this._boundSamplers=null,this._mapFormatToInternalFormat=null,this._mapFormatToType=null,this._mapFormatToFormat=null,this._uploads=null,this._renderer=null}resetState(){this._activeTextureLocation=-1,this._boundTextures.fill(U.EMPTY.source),this._boundSamplers=Object.create(null);let e=this._gl;this._premultiplyAlpha=!1,e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this._premultiplyAlpha)}},Zb.extension={type:[j.WebGLSystem],name:`texture`},Zb.uploadExtensions=Object.create(null),Qb=Zb,M.handleByMap(j.TextureUploaderWebGL,Qb.uploadExtensions)})),ex=l({WebGLRenderer:()=>sx}),tx,nx,rx,ix,ax,ox,sx,cx=s((()=>{N(),wv(),Ev(),Ov(),Tf(),xg(),uu(),Pv(),Lv(),qv(),Zv(),$v(),ty(),ry(),ay(),my(),by(),Zy(),ib(),hb(),$b(),tx=[...yg,py,Xv,Iv,ny,Nv,Qb,yy,Kv,rb,Xy,ey,mb,iy,Qv],nx=[...bg],rx=[Dv,Tv,Cv],ix=[],ax=[],ox=[],M.handleByNamedList(j.WebGLSystem,ix),M.handleByNamedList(j.WebGLPipes,ax),M.handleByNamedList(j.WebGLPipesAdaptor,ox),M.add(...tx,...nx,...rx),sx=class extends wf{constructor(){let e={name:`webgl`,type:lu.WEBGL,systems:ix,renderPipes:ax,renderPipeAdaptors:ox};super(e)}}})),lx,ux,dx=s((()=>{lx=1e-4,ux=1e-4}));function fx(e,t,n,r,i,a,o,s){let c=e-n*i,l=t-r*i,u=e+n*a,d=t+r*a,f,p;o?(f=r,p=-n):(f=-r,p=n);let m=c+f,h=l+p,g=u+f,_=d+p;return s.push(m,h),s.push(g,_),2}function px(e,t,n,r,i,a,o,s){let c=n-e,l=r-t,u=Math.atan2(c,l),d=Math.atan2(i-e,a-t);s&&u<d?u+=Math.PI*2:!s&&u>d&&(d+=Math.PI*2);let f=u,p=d-u,m=Math.abs(p),h=Math.sqrt(c*c+l*l),g=(15*m*Math.sqrt(h)/Math.PI>>0)+1,_=p/g;if(f+=_,s){o.push(e,t),o.push(n,r);for(let n=1,r=f;n<g;n++,r+=_)o.push(e,t),o.push(e+Math.sin(r)*h,t+Math.cos(r)*h);o.push(e,t),o.push(i,a)}else{o.push(n,r),o.push(e,t);for(let n=1,r=f;n<g;n++,r+=_)o.push(e+Math.sin(r)*h,t+Math.cos(r)*h),o.push(e,t);o.push(i,a),o.push(e,t)}return g*2}function mx(e,t,n,r,i,a){let o=lx;if(e.length===0)return;let s=t,c=s.alignment;if(t.alignment!==.5){let t=zc(e);n&&(t*=-1),c=(c-.5)*t+.5}let l=new Lr(e[0],e[1]),u=new Lr(e[e.length-2],e[e.length-1]),d=r,f=Math.abs(l.x-u.x)<o&&Math.abs(l.y-u.y)<o;if(d){e=e.slice(),f&&(e.pop(),e.pop(),u.set(e[e.length-2],e[e.length-1]));let t=(l.x+u.x)*.5,n=(u.y+l.y)*.5;e.unshift(t,n),e.push(t,n)}let p=i,m=e.length/2,h=e.length,g=p.length/2,_=s.width/2,v=_*_,y=s.miterLimit*s.miterLimit,b=e[0],x=e[1],S=e[2],C=e[3],w=0,T=0,E=-(x-C),D=b-S,ee=0,te=0,ne=Math.sqrt(E*E+D*D);E/=ne,D/=ne,E*=_,D*=_;let re=c,O=(1-re)*2,k=re*2;d||(s.cap===`round`?h+=px(b-E*(O-k)*.5,x-D*(O-k)*.5,b-E*O,x-D*O,b+E*k,x+D*k,p,!0)+2:s.cap===`square`&&(h+=fx(b,x,E,D,O,k,!0,p))),p.push(b-E*O,x-D*O),p.push(b+E*k,x+D*k);for(let t=1;t<m-1;++t){b=e[(t-1)*2],x=e[(t-1)*2+1],S=e[t*2],C=e[t*2+1],w=e[(t+1)*2],T=e[(t+1)*2+1],E=-(x-C),D=b-S,ne=Math.sqrt(E*E+D*D),E/=ne,D/=ne,E*=_,D*=_,ee=-(C-T),te=S-w,ne=Math.sqrt(ee*ee+te*te),ee/=ne,te/=ne,ee*=_,te*=_;let n=S-b,r=x-C,i=S-w,a=T-C,o=n*i+r*a,c=r*i-a*n,l=c<0;if(Math.abs(c)<.001*Math.abs(o)){p.push(S-E*O,C-D*O),p.push(S+E*k,C+D*k),o>=0&&(s.join===`round`?h+=px(S,C,S-E*O,C-D*O,S-ee*O,C-te*O,p,!1)+4:h+=2,p.push(S-ee*k,C-te*k),p.push(S+ee*O,C+te*O));continue}let u=(-E+b)*(-D+C)-(-E+S)*(-D+x),d=(-ee+w)*(-te+C)-(-ee+S)*(-te+T),f=(n*d-i*u)/c,m=(a*u-r*d)/c,g=(f-S)*(f-S)+(m-C)*(m-C),re=S+(f-S)*O,ie=C+(m-C)*O,ae=S-(f-S)*k,oe=C-(m-C)*k,se=Math.min(n*n+r*r,i*i+a*a),ce=l?O:k;g<=se+ce*ce*v?s.join===`bevel`||g/v>y?(l?(p.push(re,ie),p.push(S+E*k,C+D*k),p.push(re,ie),p.push(S+ee*k,C+te*k)):(p.push(S-E*O,C-D*O),p.push(ae,oe),p.push(S-ee*O,C-te*O),p.push(ae,oe)),h+=2):s.join===`round`?l?(p.push(re,ie),p.push(S+E*k,C+D*k),h+=px(S,C,S+E*k,C+D*k,S+ee*k,C+te*k,p,!0)+4,p.push(re,ie),p.push(S+ee*k,C+te*k)):(p.push(S-E*O,C-D*O),p.push(ae,oe),h+=px(S,C,S-E*O,C-D*O,S-ee*O,C-te*O,p,!1)+4,p.push(S-ee*O,C-te*O),p.push(ae,oe)):(p.push(re,ie),p.push(ae,oe)):(p.push(S-E*O,C-D*O),p.push(S+E*k,C+D*k),s.join===`round`?h+=l?px(S,C,S+E*k,C+D*k,S+ee*k,C+te*k,p,!0)+2:px(S,C,S-E*O,C-D*O,S-ee*O,C-te*O,p,!1)+2:s.join===`miter`&&g/v<=y&&(l?(p.push(ae,oe),p.push(ae,oe)):(p.push(re,ie),p.push(re,ie)),h+=2),p.push(S-ee*O,C-te*O),p.push(S+ee*k,C+te*k),h+=2)}b=e[(m-2)*2],x=e[(m-2)*2+1],S=e[(m-1)*2],C=e[(m-1)*2+1],E=-(x-C),D=b-S,ne=Math.sqrt(E*E+D*D),E/=ne,D/=ne,E*=_,D*=_,p.push(S-E*O,C-D*O),p.push(S+E*k,C+D*k),d||(s.cap===`round`?h+=px(S-E*(O-k)*.5,C-D*(O-k)*.5,S-E*O,C-D*O,S+E*k,C+D*k,p,!1)+2:s.cap===`square`&&(h+=fx(S,C,E,D,O,k,!1,p)));let ie=ux*ux;for(let e=g;e<h+g-2;++e)b=p[e*2],x=p[e*2+1],S=p[(e+1)*2],C=p[(e+1)*2+1],w=p[(e+2)*2],T=p[(e+2)*2+1],!(Math.abs(b*(C-T)+S*(T-x)+w*(x-C))<ie)&&a.push(e,e+1,e+2)}var hx=s((()=>{Bc(),zr(),dx()}));function gx(e,t){for(let n=0;n<t.length;n++){let r=t[n];e.addColorStop(r.offset,r.color)}}function _x(e,t){let n=K.get().createCanvas(e,t);return{canvas:n,context:n.getContext(`2d`)}}function vx(e){let t=e[0]??{};return(typeof t==`number`||e[1])&&(R(`8.5.2`,`use options object instead`),t={type:`linear`,start:{x:e[0],y:e[1]},end:{x:e[2],y:e[3]},textureSpace:e[4],textureSize:e[5]??xx.defaultLinearOptions.textureSize}),t}var yx,bx,xx,Sx=s((()=>{Ar(),q(),I(),gc(),W(),Kr(),Xr(),pa(),yx=[{offset:0,color:`white`},{offset:1,color:`black`}],bx=class e{constructor(...t){this.uid=Wr(`fillGradient`),this._tick=0,this.type=`linear`,this.colorStops=[];let n=vx(t);n={...n.type===`radial`?e.defaultRadialOptions:e.defaultLinearOptions,...fa(n)},this._textureSize=n.textureSize,this._wrapMode=n.wrapMode,n.type===`radial`?(this.center=n.center,this.outerCenter=n.outerCenter??this.center,this.innerRadius=n.innerRadius,this.outerRadius=n.outerRadius,this.scale=n.scale,this.rotation=n.rotation):(this.start=n.start,this.end=n.end),this.textureSpace=n.textureSpace,this.type=n.type,n.colorStops.forEach(e=>{this.addColorStop(e.offset,e.color)})}addColorStop(e,t){return this.colorStops.push({offset:e,color:P.shared.setValue(t).toHexa()}),this}buildLinearGradient(){if(this.texture)return;let{x:e,y:t}=this.start,{x:n,y:r}=this.end,i=n-e,a=r-t,o=i<0||a<0;if(this._wrapMode===`clamp-to-edge`){if(i<0){let t=e;e=n,n=t,i*=-1}if(a<0){let e=t;t=r,r=e,a*=-1}}let s=this.colorStops.length?this.colorStops:yx,c=this._textureSize,{canvas:l,context:u}=_x(c,1),d=o?u.createLinearGradient(this._textureSize,0,0,0):u.createLinearGradient(0,0,this._textureSize,0);gx(d,s),u.fillStyle=d,u.fillRect(0,0,c,1),this.texture=new U({source:new hc({resource:l,addressMode:this._wrapMode})});let f=Math.sqrt(i*i+a*a),p=Math.atan2(a,i),m=new F;m.scale(f/c,1),m.rotate(p),m.translate(e,t),this.textureSpace===`local`&&m.scale(c,c),this.transform=m}buildGradient(){this.texture||this._tick++,this.type===`linear`?this.buildLinearGradient():this.buildRadialGradient()}buildRadialGradient(){if(this.texture)return;let e=this.colorStops.length?this.colorStops:yx,t=this._textureSize,{canvas:n,context:r}=_x(t,t),{x:i,y:a}=this.center,{x:o,y:s}=this.outerCenter,c=this.innerRadius,l=this.outerRadius,u=o-l,d=s-l,f=t/(l*2),p=(i-u)*f,m=(a-d)*f,h=r.createRadialGradient(p,m,c*f,(o-u)*f,(s-d)*f,l*f);gx(h,e),r.fillStyle=e[e.length-1].color,r.fillRect(0,0,t,t),r.fillStyle=h,r.translate(p,m),r.rotate(this.rotation),r.scale(1,this.scale),r.translate(-p,-m),r.fillRect(0,0,t,t),this.texture=new U({source:new hc({resource:n,addressMode:this._wrapMode})});let g=new F;this.textureSpace===`local`?g.scale(2*l,2*l):g.scale(1/f,1/f),g.translate(u,d),this.transform=g}destroy(){this.texture?.destroy(!0),this.texture=null,this.transform=null,this.colorStops=[],this.start=null,this.end=null,this.center=null,this.outerCenter=null}get styleKey(){return`fill-gradient-${this.uid}-${this._tick}`}},bx.defaultLinearOptions={start:{x:0,y:0},end:{x:0,y:1},colorStops:[],textureSpace:`local`,type:`linear`,textureSize:256,wrapMode:`clamp-to-edge`},bx.defaultRadialOptions={center:{x:.5,y:.5},innerRadius:0,outerRadius:.5,colorStops:[],scale:1,rotation:0,textureSpace:`local`,type:`radial`,textureSize:256,wrapMode:`clamp-to-edge`},xx=bx}));function Cx(e){return e.texture!==void 0}var wx,Tx,Ex=s((()=>{I(),Kr(),wx={repeat:{addressModeU:`repeat`,addressModeV:`repeat`},"repeat-x":{addressModeU:`repeat`,addressModeV:`clamp-to-edge`},"repeat-y":{addressModeU:`clamp-to-edge`,addressModeV:`repeat`},"no-repeat":{addressModeU:`clamp-to-edge`,addressModeV:`clamp-to-edge`}},Tx=class{constructor(e,t){this.uid=Wr(`fillPattern`),this._tick=0,this.transform=new F;let n=Cx(e)?e:{texture:e,repetition:t};this.texture=n.texture,this.textureSpace=n.textureSpace??`global`;let r=n.repetition;r&&(this.texture.source.style.addressModeU=wx[r].addressModeU,this.texture.source.style.addressModeV=wx[r].addressModeV)}setTransform(e){if(e){if(this.transform.equals(e))return;this.transform.copyFrom(e)}else{if(this.transform.isIdentity())return;this.transform.identity()}this._tick++}get texture(){return this._texture}set texture(e){this._texture!==e&&(this._texture=e,this._tick++)}get styleKey(){return`fill-pattern-${this.uid}-${this._tick}`}destroy(){this.texture.destroy(!0),this.texture=null}}}));function Dx(e,t,n,r,i,a,o,s=null){let c=0;n*=t,i*=a;let l=s.a,u=s.b,d=s.c,f=s.d,p=s.tx,m=s.ty;for(;c<o;){let o=e[n],s=e[n+1];r[i]=l*o+d*s+p,r[i+1]=u*o+f*s+m,i+=a,n+=t,c++}}function Ox(e,t,n,r){let i=0;for(t*=n;i<r;)e[t]=0,e[t+1]=0,t+=n,i++}var kx=s((()=>{}));function Ax(e,t,n,r,i){let a=t.a,o=t.b,s=t.c,c=t.d,l=t.tx,u=t.ty;n||=0,r||=2,i||=e.length/r-n;let d=n*r;for(let t=0;t<i;t++){let t=e[d],n=e[d+1];e[d]=a*t+s*n+l,e[d+1]=o*t+c*n+u,d+=r}}var jx=s((()=>{})),Mx,Nx,Px=s((()=>{I(),zi(),Mx=new F,Nx=class{constructor(){this.packAsQuad=!1,this.batcherName=`default`,this.topology=`triangle-list`,this.applyTransform=!0,this.roundPixels=0,this._batcher=null,this._batch=null}get uvs(){return this.geometryData.uvs}get positions(){return this.geometryData.vertices}get indices(){return this.geometryData.indices}get blendMode(){return this.renderable&&this.applyTransform?this.renderable.groupBlendMode:`normal`}get color(){let e=this.baseColor,t=e>>16|e&65280|(e&255)<<16,n=this.renderable;return n?Ri(t,n.groupColor)+(this.alpha*n.groupAlpha*255<<24):t+(this.alpha*255<<24)}get transform(){return this.renderable?.groupTransform||Mx}copyTo(e){e.indexOffset=this.indexOffset,e.indexSize=this.indexSize,e.attributeOffset=this.attributeOffset,e.attributeSize=this.attributeSize,e.baseColor=this.baseColor,e.alpha=this.alpha,e.texture=this.texture,e.geometryData=this.geometryData,e.topology=this.topology}reset(){this.applyTransform=!0,this.renderable=null,this.topology=`triangle-list`}destroy(){this.renderable=null,this.texture=null,this.geometryData=null,this._batcher=null,this._batch=null}}})),Fx,Ix,Lx,Rx=s((()=>{N(),Fx={extension:{type:j.ShapeBuilder,name:`circle`},build(e,t){let n,r,i,a,o,s;if(e.type===`circle`){let t=e;if(o=s=t.radius,o<=0)return!1;n=t.x,r=t.y,i=a=0}else if(e.type===`ellipse`){let t=e;if(o=t.halfWidth,s=t.halfHeight,o<=0||s<=0)return!1;n=t.x,r=t.y,i=a=0}else{let t=e,c=t.width/2,l=t.height/2;n=t.x+c,r=t.y+l,o=s=Math.max(0,Math.min(t.radius,Math.min(c,l))),i=c-o,a=l-s}if(i<0||a<0)return!1;let c=Math.ceil(2.3*Math.sqrt(o+s)),l=c*8+(i?4:0)+(a?4:0);if(l===0)return!1;if(c===0)return t[0]=t[6]=n+i,t[1]=t[3]=r+a,t[2]=t[4]=n-i,t[5]=t[7]=r-a,!0;let u=0,d=c*4+(i?2:0)+2,f=d,p=l,m=i+o,h=a,g=n+m,_=n-m,v=r+h;if(t[u++]=g,t[u++]=v,t[--d]=v,t[--d]=_,a){let e=r-h;t[f++]=_,t[f++]=e,t[--p]=e,t[--p]=g}for(let e=1;e<c;e++){let l=Math.PI/2*(e/c),m=i+Math.cos(l)*o,h=a+Math.sin(l)*s,g=n+m,_=n-m,v=r+h,y=r-h;t[u++]=g,t[u++]=v,t[--d]=v,t[--d]=_,t[f++]=_,t[f++]=y,t[--p]=y,t[--p]=g}m=i,h=a+s,g=n+m,_=n-m,v=r+h;let y=r-h;return t[u++]=g,t[u++]=v,t[--p]=y,t[--p]=g,i&&(t[u++]=_,t[u++]=v,t[--p]=y,t[--p]=_),!0},triangulate(e,t,n,r,i,a){if(e.length===0)return;let o=0,s=0;for(let t=0;t<e.length;t+=2)o+=e[t],s+=e[t+1];o/=e.length/2,s/=e.length/2;let c=r;t[c*n]=o,t[c*n+1]=s;let l=c++;for(let r=0;r<e.length;r+=2)t[c*n]=e[r],t[c*n+1]=e[r+1],r>0&&(i[a++]=c,i[a++]=l,i[a++]=c-1),c++;i[a++]=l+1,i[a++]=l,i[a++]=c-1}},Ix={...Fx,extension:{...Fx.extension,name:`ellipse`}},Lx={...Fx,extension:{...Fx.extension,name:`roundedRectangle`}}}));function zx(e,t,n,r){let i=lx;if(e.length===0)return;let a=e[0],o=e[1],s=e[e.length-2],c=e[e.length-1],l=t||Math.abs(a-s)<i&&Math.abs(o-c)<i,u=n,d=e.length/2,f=u.length/2;for(let t=0;t<d;t++)u.push(e[t*2]),u.push(e[t*2+1]);for(let e=0;e<d-1;e++)r.push(f+e,f+e+1);l&&r.push(f+d-1,f)}var Bx=s((()=>{dx()}));function Vx(e,t,n,r,i,a,o){let s=gf(e,t,2);if(!s)return;for(let e=0;e<s.length;e+=3)a[o++]=s[e]+i,a[o++]=s[e+1]+i,a[o++]=s[e+2]+i;let c=i*r;for(let t=0;t<e.length;t+=2)n[c]=e[t],n[c+1]=e[t+1],c+=r}var Hx=s((()=>{_f()})),Ux,Wx,Gx=s((()=>{N(),Hx(),Ux=[],Wx={extension:{type:j.ShapeBuilder,name:`polygon`},build(e,t){for(let n=0;n<e.points.length;n++)t[n]=e.points[n];return!0},triangulate(e,t,n,r,i,a){Vx(e,Ux,t,n,r,i,a)}}})),Kx,qx=s((()=>{N(),Kx={extension:{type:j.ShapeBuilder,name:`rectangle`},build(e,t){let n=e,r=n.x,i=n.y,a=n.width,o=n.height;return a>0&&o>0&&(t[0]=r,t[1]=i,t[2]=r+a,t[3]=i,t[4]=r+a,t[5]=i+o,t[6]=r,t[7]=i+o,!0)},triangulate(e,t,n,r,i,a){let o=0;r*=n,t[r+o]=e[0],t[r+o+1]=e[1],o+=n,t[r+o]=e[2],t[r+o+1]=e[3],o+=n,t[r+o]=e[6],t[r+o+1]=e[7],o+=n,t[r+o]=e[4],t[r+o+1]=e[5],o+=n;let s=r/n;i[a++]=s,i[a++]=s+1,i[a++]=s+2,i[a++]=s+1,i[a++]=s+3,i[a++]=s+2}}})),Jx,Yx=s((()=>{N(),Jx={extension:{type:j.ShapeBuilder,name:`triangle`},build(e,t){return t[0]=e.x,t[1]=e.y,t[2]=e.x2,t[3]=e.y2,t[4]=e.x3,t[5]=e.y3,!0},triangulate(e,t,n,r,i,a){let o=0;r*=n,t[r+o]=e[0],t[r+o+1]=e[1],o+=n,t[r+o]=e[2],t[r+o+1]=e[3],o+=n,t[r+o]=e[4],t[r+o+1]=e[5];let s=r/n;i[a++]=s,i[a++]=s+1,i[a++]=s+2}}}));function Xx(e,t,n,r){let i=t.matrix?e.copyFrom(t.matrix).invert():e.identity();if(t.textureSpace===`local`){let e=n.getBounds(Qx);t.width&&e.pad(t.width);let{x:r,y:a}=e,o=1/e.width,s=1/e.height,c=-r*o,l=-a*s,u=i.a,d=i.b,f=i.c,p=i.d;i.a*=o,i.b*=o,i.c*=s,i.d*=s,i.tx=c*u+l*f+i.tx,i.ty=c*d+l*p+i.ty}else if(t.texture.rotate){let{uvs:e,orig:n}=t.texture;i.scale(1/n.width,1/n.height),i.prepend($x.set(e.x1-e.x0,e.y1-e.y0,e.x3-e.x0,e.y3-e.y0,e.x0,e.y0))}else i.translate(t.texture.frame.x,t.texture.frame.y),i.scale(1/t.texture.source.width,1/t.texture.source.height);let a=t.texture.source.style;return!(t.fill instanceof xx)&&a.addressMode===`clamp-to-edge`&&(a.addressMode=`repeat`,a.update()),r&&i.append(Zx.copyFrom(r).invert()),i}var Zx,Qx,$x,eS=s((()=>{I(),wi(),Sx(),Zx=new F,Qx=new V,$x=new F}));function tS(e,t){let{geometryData:n,batches:r}=t;r.length=0,n.indices.length=0,n.vertices.length=0,n.uvs.length=0;for(let t=0;t<e.instructions.length;t++){let i=e.instructions[t];if(i.action===`texture`)nS(i.data,r,n);else if(i.action===`fill`||i.action===`stroke`){let e=i.action===`stroke`,t=i.data.path.shapePath,a=i.data.style,o=i.data.hole;e&&o&&rS(o.shapePath,a,!0,r,n),o&&(t.shapePrimitives[t.shapePrimitives.length-1].holes=o.shapePath.shapePrimitives),rS(t,a,e,r,n)}}}function nS(e,t,n){let r=[],i=aS.rectangle,a=oS;a.x=e.dx,a.y=e.dy,a.width=e.dw,a.height=e.dh;let o=e.transform;if(!i.build(a,r))return;let{vertices:s,uvs:c,indices:l}=n,u=l.length,d=s.length/2;o&&Ax(r,o),i.triangulate(r,s,2,d,l,u);let f=e.image,p=f.uvs;c.push(p.x0,p.y0,p.x1,p.y1,p.x3,p.y3,p.x2,p.y2);let m=ii.get(Nx);m.indexOffset=u,m.indexSize=l.length-u,m.attributeOffset=d,m.attributeSize=s.length/2-d,m.baseColor=e.style,m.alpha=e.alpha,m.texture=f,m.geometryData=n,t.push(m)}function rS(e,t,n,r,i){let{vertices:a,uvs:o,indices:s}=i;e.shapePrimitives.forEach(({shape:e,transform:c,holes:l})=>{let u=[],d=aS[e.type];if(!d.build(e,u))return;let f=s.length,p=a.length/2,m=`triangle-list`;if(c&&Ax(u,c),n){let n=e.closePath??!0,r=t;r.pixelLine?(zx(u,n,a,s),m=`line-list`):mx(u,r,!1,n,a,s)}else if(l){let e=[],t=u.slice();iS(l).forEach(n=>{e.push(t.length/2),t.push(...n)}),Vx(t,e,a,2,p,s,f)}else d.triangulate(u,a,2,p,s,f);let h=o.length/2,g=t.texture;if(g!==U.WHITE){let n=Xx(sS,t,e,c);Dx(a,2,p,o,h,2,a.length/2-p,n)}else Ox(o,h,2,a.length/2-p);let _=ii.get(Nx);_.indexOffset=f,_.indexSize=s.length-f,_.attributeOffset=p,_.attributeSize=a.length/2-p,_.baseColor=t.color,_.alpha=t.alpha,_.texture=g,_.geometryData=i,_.topology=m,r.push(_)})}function iS(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n].shape,i=[];aS[r.type].build(r,i)&&t.push(i)}return t}var aS,oS,sS,cS=s((()=>{N(),I(),wi(),kx(),jx(),W(),ai(),Px(),Rx(),hx(),Bx(),Gx(),qx(),Yx(),eS(),Hx(),aS={},M.handleByMap(j.ShapeBuilder,aS),M.add(Kx,Wx,Jx,Fx,Ix,Lx),oS=new V,sS=new F}));function lS(e,t,n){e.beginPath();for(let r=0;r<n.length;r+=3){let i=n[r]*2,a=n[r+1]*2,o=n[r+2]*2;e.moveTo(t[i],t[i+1]),e.lineTo(t[a],t[a+1]),e.lineTo(t[o],t[o+1]),e.closePath()}e.fill()}function uS(e){return`#${(e&16777215).toString(16).padStart(6,`0`)}`}function dS(e,t,n,r,i,a){a=Math.max(0,Math.min(a,Math.min(r,i)/2)),e.moveTo(t+a,n),e.lineTo(t+r-a,n),e.quadraticCurveTo(t+r,n,t+r,n+a),e.lineTo(t+r,n+i-a),e.quadraticCurveTo(t+r,n+i,t+r-a,n+i),e.lineTo(t+a,n+i),e.quadraticCurveTo(t,n+i,t,n+i-a),e.lineTo(t,n+a),e.quadraticCurveTo(t,n,t+a,n)}function fS(e,t){switch(t.type){case`rectangle`:{let n=t;e.rect(n.x,n.y,n.width,n.height);break}case`roundedRectangle`:{let n=t;dS(e,n.x,n.y,n.width,n.height,n.radius);break}case`circle`:{let n=t;e.arc(n.x,n.y,n.radius,0,Math.PI*2);break}case`ellipse`:{let n=t;e.ellipse?e.ellipse(n.x,n.y,n.halfWidth,n.halfHeight,0,0,Math.PI*2):(e.save(),e.translate(n.x,n.y),e.scale(n.halfWidth,n.halfHeight),e.arc(0,0,1,0,Math.PI*2),e.restore());break}case`triangle`:{let n=t;e.moveTo(n.x,n.y),e.lineTo(n.x2,n.y2),e.lineTo(n.x3,n.y3),e.closePath();break}default:{let n=t,r=n.points;if(!r?.length)break;e.moveTo(r[0],r[1]);for(let t=2;t<r.length;t+=2)e.lineTo(r[t],r[t+1]);n.closePath&&e.closePath();break}}}function pS(e,t){if(!t?.length)return!1;for(let n=0;n<t.length;n++){let r=t[n];if(!r?.shape)continue;let i=r.transform,a=i&&!i.isIdentity();a&&(e.save(),e.transform(i.a,i.b,i.c,i.d,i.tx,i.ty)),fS(e,r.shape),a&&e.restore()}return!0}function mS(e,t,n,r){let i=e.fill;if(i instanceof xx){i.buildGradient();let a=i.texture;if(a){let o=Y.getTintedPattern(a,t),s=n?yS.copyFrom(n).scale(a.source.pixelWidth,a.source.pixelHeight):yS.copyFrom(i.transform);return r&&!e.textureSpace&&s.append(r),Y.applyPatternTransform(o,s),o}}if(i instanceof Tx){let e=Y.getTintedPattern(i.texture,t);return Y.applyPatternTransform(e,i.transform,!1),e}let a=e.texture;if(a&&a!==U.WHITE){if(!a.source.resource)return hS;let r=Y.getTintedPattern(a,t),i=e.matrix;if(n){let{resolution:e}=a.source;if(i=yS.copyFrom(n),a.rotate){let{uvs:t,orig:n}=a;i.prepend(bS.set(t.x1-t.x0,t.y1-t.y0,t.x3-t.x0,t.y3-t.y0,t.x0,t.y0).invert()).scale(n.width*e,n.height*e)}else i.scale(a.source.pixelWidth,a.source.pixelHeight).translate(-a.frame.x*e,-a.frame.y*e)}return Y.applyPatternTransform(r,i),r}return uS(t)}var hS,gS,_S,vS,yS,bS,xS,SS=s((()=>{N(),Aa(),I(),Fc(),W(),Gi(),zi(),hx(),Sx(),Ex(),cS(),eS(),hS=`#808080`,gS=new F,_S=new F,vS=new F,yS=new F,bS=new F,xS=class{constructor(){this.shader=null}contextChange(e){}execute(e,t){let n=e.renderer,r=n.canvasContext,i=r.activeContext,a=t.groupTransform,o=n.globalUniforms.globalUniformData?.worldColor??4294967295,s=t.groupColorAlpha,c=(o>>>24&255)/255,l=(s>>>24&255)/255,u=n.filter?.alphaMultiplier??1,d=c*l*u;if(d<=0)return;let f=o&16777215,p=Ui(Ri(s&16777215,f)),m=n._roundPixels|t._roundPixels;i.save(),r.setContextTransform(a,m===1),r.setBlendMode(t.groupBlendMode);let h=t.context.instructions;for(let e=0;e<h.length;e++){let t=h[e];if(t.action===`texture`){let e=t.data,n=e.image,o=n?Y.getCanvasSource(n):null;if(!o)continue;let s=e.alpha*d;if(s<=0)continue;let c=Ri(e.style,p);i.globalAlpha=s;let l=o;c!==16777215&&(l=Y.getTintedCanvas({texture:n},c));let u=n.frame,f=n.source._resolution??n.source.resolution??1,h=u.x*f,g=u.y*f,_=u.width*f,v=u.height*f;l!==o&&(h=0,g=0);let y=e.transform,b=y&&!y.isIdentity(),x=n.rotate;b||x?(gS.copyFrom(a),b&&gS.append(y),x&&H.matrixAppendRotationInv(gS,x,e.dx,e.dy,e.dw,e.dh),r.setContextTransform(gS,m===1)):r.setContextTransform(a,m===1),i.drawImage(l,h,g,l===o?_:l.width,l===o?v:l.height,x?0:e.dx,x?0:e.dy,e.dw,e.dh),(b||x)&&r.setContextTransform(a,m===1);continue}let n=t.data,o=n?.path?.shapePath;if(!o?.shapePrimitives?.length)continue;let s=n.style,c=Ri(s.color,p),l=s.alpha*d;if(l<=0)continue;let u=t.action===`stroke`;if(i.globalAlpha=l,u){let e=s;i.lineWidth=e.width,i.lineCap=e.cap,i.lineJoin=e.join,i.miterLimit=e.miterLimit}let f=o.shapePrimitives;if(!u&&n.hole?.shapePath?.shapePrimitives?.length){let e=f[f.length-1];e.holes=n.hole.shapePath.shapePrimitives}for(let e=0;e<f.length;e++){let t=f[e];if(!t?.shape)continue;let n=t.transform,r=n&&!n.isIdentity(),o=s.texture&&s.texture!==U.WHITE,l=s.textureSpace===`global`?n:null,d=mS(s,c,o?Xx(_S,s,t.shape,l):null,r?vS.copyFrom(a).append(n):a);if(r&&(i.save(),i.transform(n.a,n.b,n.c,n.d,n.tx,n.ty)),u){let e=s;if(e.alignment!==.5&&!e.pixelLine){let n=[],r=[],a=[];aS[t.shape.type]?.build(t.shape,n)?(mx(n,e,!1,t.shape.closePath??!0,r,a),i.fillStyle=d,lS(i,r,a)):(i.strokeStyle=d,i.beginPath(),fS(i,t.shape),i.stroke())}else i.strokeStyle=d,i.beginPath(),fS(i,t.shape),i.stroke()}else i.fillStyle=d,i.beginPath(),fS(i,t.shape),pS(i,t.holes)?i.fill(`evenodd`):i.fill();r&&i.restore()}}i.restore()}destroy(){this.shader=null}},xS.extension={type:[j.CanvasPipesAdaptor],name:`graphics`}})),CS,wS,TS=s((()=>{N(),Aa(),I(),Gi(),zi(),Fc(),CS=class e{static _getPatternRepeat(e,t){let n=e&&e!==`clamp-to-edge`,r=t&&t!==`clamp-to-edge`;return n&&r?`repeat`:n?`repeat-x`:r?`repeat-y`:`no-repeat`}start(e,t,n){}execute(t,n){let r=n.elements;if(!r||!r.length)return;let i=t.renderer,a=i.canvasContext,o=a.activeContext;for(let t=0;t<r.length;t++){let s=r[t];if(!s.packAsQuad)continue;let c=s,l=c.texture,u=l?Y.getCanvasSource(l):null;if(!u)continue;let d=l.source.style,f=a.smoothProperty,p=d.scaleMode!==`nearest`;o[f]!==p&&(o[f]=p),a.setBlendMode(n.blendMode);let m=i.globalUniforms.globalUniformData?.worldColor??4294967295,h=c.color,g=(m>>>24&255)/255,_=(h>>>24&255)/255,v=i.filter?.alphaMultiplier??1,y=g*_*v;if(y<=0)continue;o.globalAlpha=y;let b=m&16777215,x=Ui(Ri(h&16777215,b)),S=l.frame,C=d.addressModeU??d.addressMode,w=d.addressModeV??d.addressMode,T=e._getPatternRepeat(C,w),E=l.source._resolution??l.source.resolution??1,D=c.renderable?.renderGroup?.isCachedAsTexture,ee=S.x*E,te=S.y*E,ne=S.width*E,re=S.height*E,O=c.bounds,k=i.renderTarget.renderTarget.isRoot,ie=O.minX,ae=O.minY,oe=O.maxX-O.minX,se=O.maxY-O.minY,ce=l.rotate,A=l.uvs,le=Math.min(A.x0,A.x1,A.x2,A.x3,A.y0,A.y1,A.y2,A.y3),ue=Math.max(A.x0,A.x1,A.x2,A.x3,A.y0,A.y1,A.y2,A.y3),de=T!==`no-repeat`&&(le<0||ue>1),fe=ce&&!(!de&&(x!==16777215||ce));fe?(e._tempPatternMatrix.copyFrom(c.transform),H.matrixAppendRotationInv(e._tempPatternMatrix,ce,ie,ae,oe,se),a.setContextTransform(e._tempPatternMatrix,c.roundPixels===1,void 0,D&&k)):a.setContextTransform(c.transform,c.roundPixels===1,void 0,D&&k);let pe=oe,me=se,he=fe?0:ie,ge=fe?0:ae;if(!fe&&c.roundPixels===1&&(he|=0,ge|=0),de){let t=u,n=x!==16777215&&!ce,r=S.width<=l.source.width&&S.height<=l.source.height;n&&r&&(t=Y.getTintedCanvas({texture:l},x));let i=o.createPattern(t,T);if(!i)continue;let a=pe,s=me;if(a===0||s===0)continue;let c=1/a,d=1/s,f=(A.x1-A.x0)*c,p=(A.y1-A.y0)*c,m=(A.x3-A.x0)*d,h=(A.y3-A.y0)*d,g=A.x0-f*he-m*ge,_=A.y0-p*he-h*ge,v=l.source.pixelWidth,y=l.source.pixelHeight;e._tempPatternMatrix.set(f*v,p*y,m*v,h*y,g*v,_*y),Y.applyPatternTransform(i,e._tempPatternMatrix),o.fillStyle=i,o.fillRect(he,ge,pe,me)}else{let e=x!==16777215||ce?Y.getTintedCanvas({texture:l},x):u,t=e!==u;o.drawImage(e,t?0:ee,t?0:te,t?e.width:ne,t?e.height:re,he,ge,pe,me)}}}},CS._tempPatternMatrix=new F,CS.extension={type:[j.CanvasPipesAdaptor],name:`batch`},wS=CS})),ES,DS=s((()=>{N(),ES=class{constructor(e){this._colorStack=[],this._colorStackIndex=0,this._currentColor=0,this._renderer=e}buildStart(){this._colorStack[0]=15,this._colorStackIndex=1,this._currentColor=15}push(e,t,n){this._renderer.renderPipes.batch.break(n);let r=this._colorStack;r[this._colorStackIndex]=r[this._colorStackIndex-1]&e.mask;let i=this._colorStack[this._colorStackIndex];i!==this._currentColor&&(this._currentColor=i,n.add({renderPipeId:`colorMask`,colorMask:i,canBundle:!1})),this._colorStackIndex++}pop(e,t,n){this._renderer.renderPipes.batch.break(n);let r=this._colorStack;this._colorStackIndex--;let i=r[this._colorStackIndex-1];i!==this._currentColor&&(this._currentColor=i,n.add({renderPipeId:`colorMask`,colorMask:i,canBundle:!1}))}execute(e){}destroy(){this._renderer=null,this._colorStack=null}},ES.extension={type:[j.CanvasPipes],name:`colorMask`}}));function OS(e){let t=[];return e.replace(jS,(e,n,r)=>{let i=n.toLowerCase(),a=n,o=kS(r);for(i===`m`&&o.length>2&&(t.push([a,...o.splice(0,2)]),i=`l`,a=a===`m`?`l`:`L`);;){if(o.length===AS[i])return t.push([a,...o]),``;if(o.length<AS[i])throw Error(`malformed path data`);t.push([a,...o.splice(0,AS[i])])}}),t}function kS(e){let t=e.match(MS);return t?t.map(Number):[]}var AS,jS,MS,NS=s((()=>{AS={a:7,c:6,h:1,l:2,m:2,q:4,s:4,t:2,v:1,z:0},jS=/([astvzqmhlc])([^astvzqmhlc]*)/gi,MS=/-?[0-9]*\.?[0-9]+(?:e[-+]?\d+)?/gi}));function PS(e,t){let n=OS(e),r=[],i=null,a=0,o=0;for(let e=0;e<n.length;e++){let s=n[e],c=s[0],l=s;switch(c){case`M`:a=l[1],o=l[2],t.moveTo(a,o);break;case`m`:a+=l[1],o+=l[2],t.moveTo(a,o);break;case`H`:a=l[1],t.lineTo(a,o);break;case`h`:a+=l[1],t.lineTo(a,o);break;case`V`:o=l[1],t.lineTo(a,o);break;case`v`:o+=l[1],t.lineTo(a,o);break;case`L`:a=l[1],o=l[2],t.lineTo(a,o);break;case`l`:a+=l[1],o+=l[2],t.lineTo(a,o);break;case`C`:a=l[5],o=l[6],t.bezierCurveTo(l[1],l[2],l[3],l[4],a,o);break;case`c`:t.bezierCurveTo(a+l[1],o+l[2],a+l[3],o+l[4],a+l[5],o+l[6]),a+=l[5],o+=l[6];break;case`S`:a=l[3],o=l[4],t.bezierCurveToShort(l[1],l[2],a,o);break;case`s`:t.bezierCurveToShort(a+l[1],o+l[2],a+l[3],o+l[4]),a+=l[3],o+=l[4];break;case`Q`:a=l[3],o=l[4],t.quadraticCurveTo(l[1],l[2],a,o);break;case`q`:t.quadraticCurveTo(a+l[1],o+l[2],a+l[3],o+l[4]),a+=l[3],o+=l[4];break;case`T`:a=l[1],o=l[2],t.quadraticCurveToShort(a,o);break;case`t`:a+=l[1],o+=l[2],t.quadraticCurveToShort(a,o);break;case`A`:a=l[6],o=l[7],t.arcToSvg(l[1],l[2],l[3],l[4],l[5],a,o);break;case`a`:a+=l[6],o+=l[7],t.arcToSvg(l[1],l[2],l[3],l[4],l[5],a,o);break;case`Z`:case`z`:t.closePath(),r.length>0&&(i=r.pop(),i?(a=i.startX,o=i.startY):(a=0,o=0)),i=null;break;default:z(`Unknown SVG path command: ${c}`)}c!==`Z`&&c!==`z`&&i===null&&(i={startX:a,startY:o},r.push(i))}return t}var FS=s((()=>{NS(),B()})),IS,LS,RS,zS,BS=s((()=>{N(),Nf(),rh(),ca(),Tg(),Xr(),ai(),cS(),IS=class{constructor(){this.batches=[],this.geometryData={vertices:[],uvs:[],indices:[]}}reset(){this.batches&&this.batches.forEach(e=>{ii.return(e)}),this.graphicsData&&ii.return(this.graphicsData),this.isBatchable=!1,this.context=null,this.batches.length=0,this.geometryData.indices.length=0,this.geometryData.vertices.length=0,this.geometryData.uvs.length=0,this.graphicsData=null}destroy(){this.reset(),this.batches=null,this.geometryData=null}},LS=class{constructor(){this.instructions=new sa}init(e){let t=e.maxTextures;this.batcher?this.batcher._updateMaxTextures(t):this.batcher=new nh({maxTextures:t}),this.instructions.reset()}get geometry(){return R(Jr,`GraphicsContextRenderData#geometry is deprecated, please use batcher.geometry instead.`),this.batcher.geometry}destroy(){this.batcher.destroy(),this.instructions.destroy(),this.batcher=null,this.instructions=null}},RS=class e{constructor(e){this._renderer=e,this._managedContexts=new wg({renderer:e,type:`resource`,name:`graphicsContext`})}init(t){e.defaultOptions.bezierSmoothness=t?.bezierSmoothness??e.defaultOptions.bezierSmoothness}getContextRenderData(e){return e._gpuData[this._renderer.uid].graphicsData||this._initContextRenderData(e)}updateGpuContext(e){let t=!!e._gpuData[this._renderer.uid],n=e._gpuData[this._renderer.uid]||this._initContext(e);if(e.dirty||!t){t&&n.reset(),tS(e,n);let r=e.batchMode;n.isBatchable=e.customShader||r===`no-batch`?!1:r!==`auto`||n.geometryData.vertices.length<400,e.dirty=!1}return n}getGpuContext(e){return e._gpuData[this._renderer.uid]||this._initContext(e)}_initContextRenderData(e){let t=ii.get(LS,{maxTextures:this._renderer.limits.maxBatchableTextures}),n=e._gpuData[this._renderer.uid],{batches:r,geometryData:i}=n;n.graphicsData=t;let a=i.vertices.length,o=i.indices.length;for(let e=0;e<r.length;e++)r[e].applyTransform=!1;let s=t.batcher;s.ensureAttributeBuffer(a),s.ensureIndexBuffer(o),s.begin();for(let e=0;e<r.length;e++){let t=r[e];s.add(t)}s.finish(t.instructions);let c=s.geometry;c.indexBuffer.setDataWithSize(s.indexBuffer,s.indexSize,!0),c.buffers[0].setDataWithSize(s.attributeBuffer.float32View,s.attributeSize,!0);let l=s.batches;for(let e=0;e<l.length;e++){let t=l[e];t.bindGroup=Af(t.textures.textures,t.textures.count,this._renderer.limits.maxBatchableTextures)}return t}_initContext(e){let t=new IS;return t.context=e,e._gpuData[this._renderer.uid]=t,this._managedContexts.add(e),t}destroy(){this._managedContexts.destroy(),this._renderer=null}},RS.extension={type:[j.WebGLSystem,j.WebGPUSystem],name:`graphicsContext`},RS.defaultOptions={bezierSmoothness:.5},zS=RS}));function VS(e,t,n,r,i,a,o,s,c,l){let u=Math.min(.99,Math.max(0,l??zS.defaultOptions.bezierSmoothness)),d=(KS-u)/1;return d*=d,HS(t,n,r,i,a,o,s,c,e,d),e}function HS(e,t,n,r,i,a,o,s,c,l){US(e,t,n,r,i,a,o,s,c,l,0),c.push(o,s)}function US(e,t,n,r,i,a,o,s,c,l,u){if(u>WS)return;let d=(e+n)/2,f=(t+r)/2,p=(n+i)/2,m=(r+a)/2,h=(i+o)/2,g=(a+s)/2,_=(d+p)/2,v=(f+m)/2,y=(p+h)/2,b=(m+g)/2,x=(_+y)/2,S=(v+b)/2;if(u>0){let u=o-e,d=s-t,f=Math.abs((n-o)*d-(r-s)*u),p=Math.abs((i-o)*d-(a-s)*u);if(f>GS&&p>GS){if((f+p)*(f+p)<=l*(u*u+d*d)){c.push(x,S);return}}else if(f>GS){if(f*f<=l*(u*u+d*d)){c.push(x,S);return}}else if(p>GS){if(p*p<=l*(u*u+d*d)){c.push(x,S);return}}else if(u=x-(e+o)/2,d=S-(t+s)/2,u*u+d*d<=l){c.push(x,S);return}}US(e,t,d,f,_,v,x,S,c,l,u+1),US(x,S,y,b,h,g,o,s,c,l,u+1)}var WS,GS,KS,qS=s((()=>{BS(),WS=8,GS=1.1920929e-7,KS=1}));function JS(e,t,n,r,i,a,o,s){let c=Math.min(.99,Math.max(0,s??zS.defaultOptions.bezierSmoothness)),l=($S-c)/1;return l*=l,YS(t,n,r,i,a,o,e,l),e}function YS(e,t,n,r,i,a,o,s){XS(o,e,t,n,r,i,a,s,0),o.push(i,a)}function XS(e,t,n,r,i,a,o,s,c){if(c>ZS)return;let l=(t+r)/2,u=(n+i)/2,d=(r+a)/2,f=(i+o)/2,p=(l+d)/2,m=(u+f)/2,h=a-t,g=o-n,_=Math.abs((r-a)*g-(i-o)*h);if(_>QS){if(_*_<=s*(h*h+g*g)){e.push(p,m);return}}else if(h=p-(t+a)/2,g=m-(n+o)/2,h*h+g*g<=s){e.push(p,m);return}XS(e,t,n,l,u,p,m,s,c+1),XS(e,p,m,d,f,a,o,s,c+1)}var ZS,QS,$S,eC=s((()=>{BS(),ZS=8,QS=1.1920929e-7,$S=1}));function tC(e,t,n,r,i,a,o,s){let c=Math.abs(i-a);(!o&&i>a||o&&a>i)&&(c=2*Math.PI-c),s||=Math.max(6,Math.floor(6*r**(1/3)*(c/Math.PI))),s=Math.max(s,3);let l=c/s,u=i;l*=o?-1:1;for(let i=0;i<s+1;i++){let i=Math.cos(u),a=Math.sin(u),o=t+i*r,s=n+a*r;e.push(o,s),u+=l}}var nC=s((()=>{}));function rC(e,t,n,r,i,a){let o=e[e.length-2],s=e[e.length-1]-n,c=o-t,l=i-n,u=r-t,d=Math.abs(s*u-c*l);if(d<1e-8||a===0){(e[e.length-2]!==t||e[e.length-1]!==n)&&e.push(t,n);return}let f=s*s+c*c,p=l*l+u*u,m=s*l+c*u,h=a*Math.sqrt(f)/d,g=a*Math.sqrt(p)/d,_=h*m/f,v=g*m/p,y=h*u+g*c,b=h*l+g*s,x=c*(g+_),S=s*(g+_),C=u*(h+v),w=l*(h+v),T=Math.atan2(S-b,x-y),E=Math.atan2(w-b,C-y);tC(e,y+t,b+n,a,T,E,c*l>u*s)}var iC=s((()=>{nC()}));function aC(e,t){let n=t===-1.5707963267948966?-.551915024494:4/3*Math.tan(t/4),r=t===1.5707963267948966?.551915024494:n,i=Math.cos(e),a=Math.sin(e),o=Math.cos(e+t),s=Math.sin(e+t);return[{x:i-a*r,y:a+i*r},{x:o+s*r,y:s-o*r},{x:o,y:s}]}function oC(e,t,n,r,i,a,o,s=0,c=0,l=0){if(a===0||o===0)return;let u=Math.sin(s*sC/360),d=Math.cos(s*sC/360),f=d*(t-r)/2+u*(n-i)/2,p=-u*(t-r)/2+d*(n-i)/2;if(f===0&&p===0)return;a=Math.abs(a),o=Math.abs(o);let m=f**2/a**2+p**2/o**2;m>1&&(a*=Math.sqrt(m),o*=Math.sqrt(m)),dC(t,n,r,i,a,o,c,l,u,d,f,p,cC);let{ang1:h,ang2:g}=cC,{centerX:_,centerY:v}=cC,y=Math.abs(g)/(sC/4);Math.abs(1-y)<1e-7&&(y=1);let b=Math.max(Math.ceil(y),1);g/=b;let x=e[e.length-2],S=e[e.length-1],C={x:0,y:0};for(let t=0;t<b;t++){let t=aC(h,g),{x:n,y:r}=lC(t[0],a,o,d,u,_,v,C),{x:i,y:s}=lC(t[1],a,o,d,u,_,v,C),{x:c,y:l}=lC(t[2],a,o,d,u,_,v,C);VS(e,x,S,n,r,i,s,c,l),x=c,S=l,h+=g}}var sC,cC,lC,uC,dC,fC=s((()=>{qS(),sC=Math.PI*2,cC={centerX:0,centerY:0,ang1:0,ang2:0},lC=({x:e,y:t},n,r,i,a,o,s,c)=>{e*=n,t*=r;let l=i*e-a*t,u=a*e+i*t;return c.x=l+o,c.y=u+s,c},uC=(e,t,n,r)=>{let i=e*r-t*n<0?-1:1,a=e*n+t*r;return a>1&&(a=1),a<-1&&(a=-1),i*Math.acos(a)},dC=(e,t,n,r,i,a,o,s,c,l,u,d,f)=>{let p=i**2,m=a**2,h=u**2,g=d**2,_=p*m-p*g-m*h;_<0&&(_=0),_/=p*g+m*h,_=Math.sqrt(_)*(o===s?-1:1);let v=_*i/a*d,y=_*-a/i*u,b=l*v-c*y+(e+n)/2,x=c*v+l*y+(t+r)/2,S=(u-v)/i,C=(d-y)/a,w=(-u-v)/i,T=(-d-y)/a,E=uC(1,0,S,C),D=uC(S,C,w,T);s===0&&D>0&&(D-=sC),s===1&&D<0&&(D+=sC),f.centerX=b,f.centerY=x,f.ang1=E,f.ang2=D}}));function pC(e,t,n){let r=(e,t)=>{let n=t.x-e.x,r=t.y-e.y,i=Math.sqrt(n*n+r*r);return{len:i,nx:n/i,ny:r/i}},i=(t,n)=>{t===0?e.moveTo(n.x,n.y):e.lineTo(n.x,n.y)},a=t[t.length-1];for(let o=0;o<t.length;o++){let s=t[o%t.length],c=s.radius??n;if(c<=0){i(o,s),a=s;continue}let l=t[(o+1)%t.length],u=r(s,a),d=r(s,l);if(u.len<1e-4||d.len<1e-4){i(o,s),a=s;continue}let f=Math.asin(u.nx*d.ny-u.ny*d.nx),p=1,m=!1;u.nx*d.nx-u.ny*-d.ny<0?f<0?f=Math.PI+f:(f=Math.PI-f,p=-1,m=!0):f>0&&(p=-1,m=!0);let h=f/2,g,_=Math.abs(Math.cos(h)*c/Math.sin(h));_>Math.min(u.len/2,d.len/2)?(_=Math.min(u.len/2,d.len/2),g=Math.abs(_*Math.sin(h)/Math.cos(h))):g=c;let v=s.x+d.nx*_+-d.ny*g*p,y=s.y+d.ny*_+d.nx*g*p,b=Math.atan2(u.ny,u.nx)+Math.PI/2*p,x=Math.atan2(d.ny,d.nx)-Math.PI/2*p;o===0&&e.moveTo(v+Math.cos(b)*g,y+Math.sin(b)*g),e.arc(v,y,g,b,x,m),a=s}}function mC(e,t,n,r){let i=(e,t)=>Math.sqrt((e.x-t.x)**2+(e.y-t.y)**2),a=(e,t,n)=>({x:e.x+(t.x-e.x)*n,y:e.y+(t.y-e.y)*n}),o=t.length;for(let s=0;s<o;s++){let c=t[(s+1)%o],l=c.radius??n;if(l<=0){s===0?e.moveTo(c.x,c.y):e.lineTo(c.x,c.y);continue}let u=t[s],d=t[(s+2)%o],f=i(u,c),p;p=f<1e-4?c:a(c,u,Math.min(f/2,l)/f);let m=i(d,c),h;h=m<1e-4?c:a(c,d,Math.min(m/2,l)/m),s===0?e.moveTo(p.x,p.y):e.lineTo(p.x,p.y),e.quadraticCurveTo(c.x,c.y,h.x,h.y,r)}}var hC=s((()=>{})),gC,_C,vC=s((()=>{Wc(),Kc(),Xc(),wi(),$c(),Di(),qS(),eC(),nC(),iC(),fC(),hC(),gC=new V,_C=class{constructor(e){this.shapePrimitives=[],this._currentPoly=null,this._bounds=new Ei,this._graphicsPath2D=e,this.signed=e.checkForHoles}moveTo(e,t){return this.startPoly(e,t),this}lineTo(e,t){this._ensurePoly();let n=this._currentPoly.points,r=n[n.length-2],i=n[n.length-1];return(r!==e||i!==t)&&n.push(e,t),this}arc(e,t,n,r,i,a){this._ensurePoly(!1);let o=this._currentPoly.points;return tC(o,e,t,n,r,i,a),this}arcTo(e,t,n,r,i){this._ensurePoly();let a=this._currentPoly.points;return rC(a,e,t,n,r,i),this}arcToSvg(e,t,n,r,i,a,o){let s=this._currentPoly.points;return oC(s,this._currentPoly.lastX,this._currentPoly.lastY,a,o,e,t,n,r,i),this}bezierCurveTo(e,t,n,r,i,a,o){this._ensurePoly();let s=this._currentPoly;return VS(this._currentPoly.points,s.lastX,s.lastY,e,t,n,r,i,a,o),this}quadraticCurveTo(e,t,n,r,i){this._ensurePoly();let a=this._currentPoly;return JS(this._currentPoly.points,a.lastX,a.lastY,e,t,n,r,i),this}closePath(){return this.endPoly(!0),this}addPath(e,t){this.endPoly(),t&&!t.isIdentity()&&(e=e.clone(!0),e.transform(t));let n=this.shapePrimitives,r=n.length;for(let t=0;t<e.instructions.length;t++){let n=e.instructions[t];this[n.action](...n.data)}if(e.checkForHoles&&n.length-r>1){let e=null;for(let t=r;t<n.length;t++){let r=n[t];if(r.shape.type===`polygon`){let i=r.shape,a=e?.shape;a&&a.containsPolygon(i)?(e.holes||(e.holes=[]),e.holes.push(r),n.copyWithin(t,t+1),n.length--,t--):e=r}}}return this}finish(e=!1){this.endPoly(e)}rect(e,t,n,r,i){return this.drawShape(new V(e,t,n,r),i),this}circle(e,t,n,r){return this.drawShape(new Uc(e,t,n),r),this}poly(e,t,n){let r=new Yc(e);return r.closePath=t,this.drawShape(r,n),this}regularPoly(e,t,n,r,i=0,a){r=Math.max(r|0,3);let o=-1*Math.PI/2+i,s=Math.PI*2/r,c=[];for(let i=0;i<r;i++){let r=o-i*s;c.push(e+n*Math.cos(r),t+n*Math.sin(r))}return this.poly(c,!0,a),this}roundPoly(e,t,n,r,i,a=0,o){if(r=Math.max(r|0,3),i<=0)return this.regularPoly(e,t,n,r,a);let s=n*Math.sin(Math.PI/r)-.001;i=Math.min(i,s);let c=-1*Math.PI/2+a,l=Math.PI*2/r,u=(r-2)*Math.PI/r/2;for(let a=0;a<r;a++){let r=a*l+c,s=e+n*Math.cos(r),d=t+n*Math.sin(r),f=r+Math.PI+u,p=r-Math.PI-u,m=s+i*Math.cos(f),h=d+i*Math.sin(f),g=s+i*Math.cos(p),_=d+i*Math.sin(p);a===0?this.moveTo(m,h):this.lineTo(m,h),this.quadraticCurveTo(s,d,g,_,o)}return this.closePath()}roundShape(e,t,n=!1,r){return e.length<3?this:(n?mC(this,e,t,r):pC(this,e,t),this.closePath())}filletRect(e,t,n,r,i){if(i===0)return this.rect(e,t,n,r);let a=Math.min(n,r)/2,o=Math.min(a,Math.max(-a,i)),s=e+n,c=t+r,l=o<0?-o:0,u=Math.abs(o);return this.moveTo(e,t+u).arcTo(e+l,t+l,e+u,t,u).lineTo(s-u,t).arcTo(s-l,t+l,s,t+u,u).lineTo(s,c-u).arcTo(s-l,c-l,e+n-u,c,u).lineTo(e+u,c).arcTo(e+l,c-l,e,c-u,u).closePath()}chamferRect(e,t,n,r,i,a){if(i<=0)return this.rect(e,t,n,r);let o=Math.min(i,Math.min(n,r)/2),s=e+n,c=t+r,l=[e+o,t,s-o,t,s,t+o,s,c-o,s-o,c,e+o,c,e,c-o,e,t+o];for(let e=l.length-1;e>=2;e-=2)l[e]===l[e-2]&&l[e-1]===l[e-3]&&l.splice(e-1,2);return this.poly(l,!0,a)}ellipse(e,t,n,r,i){return this.drawShape(new Gc(e,t,n,r),i),this}roundRect(e,t,n,r,i,a){return this.drawShape(new Qc(e,t,n,r,i),a),this}drawShape(e,t){return this.endPoly(),this.shapePrimitives.push({shape:e,transform:t}),this}startPoly(e,t){let n=this._currentPoly;return n&&this.endPoly(),n=new Yc,n.points.push(e,t),this._currentPoly=n,this}endPoly(e=!1){let t=this._currentPoly;return t&&t.points.length>2&&(t.closePath=e,this.shapePrimitives.push({shape:t})),this._currentPoly=null,this}_ensurePoly(e=!0){if(!this._currentPoly&&(this._currentPoly=new Yc,e)){let e=this.shapePrimitives[this.shapePrimitives.length-1];if(e){let t=e.shape.x,n=e.shape.y;if(e.transform&&!e.transform.isIdentity()){let r=e.transform,i=t;t=r.a*t+r.c*n+r.tx,n=r.b*i+r.d*n+r.ty}this._currentPoly.points.push(t,n)}else this._currentPoly.points.push(0,0)}}buildPath(){let e=this._graphicsPath2D;this.shapePrimitives.length=0,this._currentPoly=null;for(let t=0;t<e.instructions.length;t++){let n=e.instructions[t];this[n.action](...n.data)}this.finish()}get bounds(){let e=this._bounds;e.clear();let t=this.shapePrimitives;for(let n=0;n<t.length;n++){let r=t[n],i=r.shape.getBounds(gC);r.transform?e.addRect(i,r.transform):e.addRect(i)}return e}}}));function yC(e,t){return e?e.prepend(t):t.clone()}var bC,xC=s((()=>{zr(),Kr(),B(),FS(),vC(),bC=class e{constructor(e,t=!1){this.instructions=[],this.uid=Wr(`graphicsPath`),this._dirty=!0,this.checkForHoles=t,typeof e==`string`?PS(e,this):this.instructions=e?.slice()??[]}get shapePath(){return this._shapePath||=new _C(this),this._dirty&&(this._dirty=!1,this._shapePath.buildPath()),this._shapePath}addPath(e,t){return e=e.clone(),this.instructions.push({action:`addPath`,data:[e,t]}),this._dirty=!0,this}arc(...e){return this.instructions.push({action:`arc`,data:e}),this._dirty=!0,this}arcTo(...e){return this.instructions.push({action:`arcTo`,data:e}),this._dirty=!0,this}arcToSvg(...e){return this.instructions.push({action:`arcToSvg`,data:e}),this._dirty=!0,this}bezierCurveTo(...e){return this.instructions.push({action:`bezierCurveTo`,data:e}),this._dirty=!0,this}bezierCurveToShort(e,t,n,r,i){let a=this.instructions[this.instructions.length-1],o=this.getLastPoint(Lr.shared),s=0,c=0;if(!a||a.action!==`bezierCurveTo`)s=o.x,c=o.y;else{s=a.data[2],c=a.data[3];let e=o.x,t=o.y;s=e+(e-s),c=t+(t-c)}return this.instructions.push({action:`bezierCurveTo`,data:[s,c,e,t,n,r,i]}),this._dirty=!0,this}closePath(){return this.instructions.push({action:`closePath`,data:[]}),this._dirty=!0,this}ellipse(...e){return this.instructions.push({action:`ellipse`,data:e}),this._dirty=!0,this}lineTo(...e){return this.instructions.push({action:`lineTo`,data:e}),this._dirty=!0,this}moveTo(...e){return this.instructions.push({action:`moveTo`,data:e}),this}quadraticCurveTo(...e){return this.instructions.push({action:`quadraticCurveTo`,data:e}),this._dirty=!0,this}quadraticCurveToShort(e,t,n){let r=this.instructions[this.instructions.length-1],i=this.getLastPoint(Lr.shared),a=0,o=0;if(!r||r.action!==`quadraticCurveTo`)a=i.x,o=i.y;else{a=r.data[0],o=r.data[1];let e=i.x,t=i.y;a=e+(e-a),o=t+(t-o)}return this.instructions.push({action:`quadraticCurveTo`,data:[a,o,e,t,n]}),this._dirty=!0,this}rect(e,t,n,r,i){return this.instructions.push({action:`rect`,data:[e,t,n,r,i]}),this._dirty=!0,this}circle(e,t,n,r){return this.instructions.push({action:`circle`,data:[e,t,n,r]}),this._dirty=!0,this}roundRect(...e){return this.instructions.push({action:`roundRect`,data:e}),this._dirty=!0,this}poly(...e){return this.instructions.push({action:`poly`,data:e}),this._dirty=!0,this}regularPoly(...e){return this.instructions.push({action:`regularPoly`,data:e}),this._dirty=!0,this}roundPoly(...e){return this.instructions.push({action:`roundPoly`,data:e}),this._dirty=!0,this}roundShape(...e){return this.instructions.push({action:`roundShape`,data:e}),this._dirty=!0,this}filletRect(...e){return this.instructions.push({action:`filletRect`,data:e}),this._dirty=!0,this}chamferRect(...e){return this.instructions.push({action:`chamferRect`,data:e}),this._dirty=!0,this}star(e,t,n,r,i,a,o){i||=r/2;let s=-1*Math.PI/2+a,c=n*2,l=Math.PI*2/c,u=[];for(let n=0;n<c;n++){let a=n%2?i:r,o=n*l+s;u.push(e+a*Math.cos(o),t+a*Math.sin(o))}return this.poly(u,!0,o),this}clone(t=!1){let n=new e;if(n.checkForHoles=this.checkForHoles,!t)n.instructions=this.instructions.slice();else for(let e=0;e<this.instructions.length;e++){let t=this.instructions[e];n.instructions.push({action:t.action,data:t.data.slice()})}return n}clear(){return this.instructions.length=0,this._dirty=!0,this}transform(e){if(e.isIdentity())return this;let t=e.a,n=e.b,r=e.c,i=e.d,a=e.tx,o=e.ty,s=0,c=0,l=0,u=0,d=0,f=0,p=0,m=0;for(let h=0;h<this.instructions.length;h++){let g=this.instructions[h],_=g.data;switch(g.action){case`moveTo`:case`lineTo`:s=_[0],c=_[1],_[0]=t*s+r*c+a,_[1]=n*s+i*c+o;break;case`bezierCurveTo`:l=_[0],u=_[1],d=_[2],f=_[3],s=_[4],c=_[5],_[0]=t*l+r*u+a,_[1]=n*l+i*u+o,_[2]=t*d+r*f+a,_[3]=n*d+i*f+o,_[4]=t*s+r*c+a,_[5]=n*s+i*c+o;break;case`quadraticCurveTo`:l=_[0],u=_[1],s=_[2],c=_[3],_[0]=t*l+r*u+a,_[1]=n*l+i*u+o,_[2]=t*s+r*c+a,_[3]=n*s+i*c+o;break;case`arcToSvg`:s=_[5],c=_[6],p=_[0],m=_[1],_[0]=t*p+r*m,_[1]=n*p+i*m,_[5]=t*s+r*c+a,_[6]=n*s+i*c+o;break;case`circle`:_[4]=yC(_[3],e);break;case`rect`:_[4]=yC(_[4],e);break;case`ellipse`:_[8]=yC(_[8],e);break;case`roundRect`:_[5]=yC(_[5],e);break;case`addPath`:_[0].transform(e);break;case`poly`:_[2]=yC(_[2],e);break;case`regularPoly`:case`chamferRect`:_[5]=yC(_[5],e);break;case`closePath`:break;default:z(`unknown transform action`,g.action)}}return this._dirty=!0,this}get bounds(){return this.shapePath.bounds}getLastPoint(e){let t=this.instructions.length-1,n=this.instructions[t];if(!n)return e.x=0,e.y=0,e;for(;n.action===`closePath`;){if(t--,t<0)return e.x=0,e.y=0,e;n=this.instructions[t]}switch(n.action){case`moveTo`:case`lineTo`:e.x=n.data[0],e.y=n.data[1];break;case`quadraticCurveTo`:e.x=n.data[2],e.y=n.data[3];break;case`bezierCurveTo`:e.x=n.data[4],e.y=n.data[5];break;case`arc`:case`arcToSvg`:e.x=n.data[5],e.y=n.data[6];break;case`addPath`:n.data[0].getLastPoint(e)}return e}}}));function SC(e,t,n){let r=e.getAttribute(t);return r?Number(r):n}var CC=s((()=>{}));function wC(e,t){let n=e.querySelectorAll(`defs`);for(let e=0;e<n.length;e++){let r=n[e];for(let e=0;e<r.children.length;e++){let n=r.children[e];switch(n.nodeName.toLowerCase()){case`lineargradient`:t.defs[n.id]=OC(n);break;case`radialgradient`:t.defs[n.id]=kC(n)}}}}function TC(e,t,n){let r=e.getAttribute(t);if(r?.trim().endsWith(`%`)){let e=Number(r.trim().slice(0,-1));return Number.isNaN(e)?n:e/100}return SC(e,t,n)}function EC(e){return(e.getAttribute(`gradientUnits`)||`objectBoundingBox`)===`objectBoundingBox`?`local`:`global`}function DC(e){let t=[];for(let n=0;n<e.children.length;n++){let r=e.children[n],i=TC(r,`offset`,0),a=P.shared.setValue(r.getAttribute(`stop-color`)).toNumber();t.push({offset:i,color:a})}return t}function OC(e){let t=TC(e,`x1`,0),n=TC(e,`y1`,0),r=TC(e,`x2`,1),i=TC(e,`y2`,0);return new xx({type:`linear`,start:{x:t,y:n},end:{x:r,y:i},textureSpace:EC(e),colorStops:DC(e)})}function kC(e){let t=TC(e,`cx`,.5),n=TC(e,`cy`,.5),r=TC(e,`r`,.5),i=TC(e,`fx`,t),a=TC(e,`fy`,n),o=TC(e,`fr`,0);return new xx({type:`radial`,center:{x:i,y:a},innerRadius:o,outerCenter:{x:t,y:n},outerRadius:r,textureSpace:EC(e),colorStops:DC(e)})}var AC=s((()=>{Ar(),Sx(),CC()}));function jC(e){let t=e.match(/url\s*\(\s*['"]?\s*#([^'"\s)]+)\s*['"]?\s*\)/i);return t?t[1]:``}var MC=s((()=>{}));function NC(e,t){let n=e.getAttribute(`style`),r={},i={},a={strokeStyle:r,fillStyle:i,useFill:!1,useStroke:!1};for(let n in FC){let r=e.getAttribute(n);r&&PC(t,a,n,r.trim())}if(n){let e=n.split(`;`);for(let n=0;n<e.length;n++){let[r,i]=e[n].trim().split(`:`);FC[r]&&PC(t,a,r,i.trim())}}return{strokeStyle:a.useStroke?r:null,fillStyle:a.useFill?i:null,useFill:a.useFill,useStroke:a.useStroke}}function PC(e,t,n,r){switch(n){case`stroke`:if(r!==`none`){if(r.startsWith(`url(`)){let n=jC(r);t.strokeStyle.fill=e.defs[n]}else t.strokeStyle.color=P.shared.setValue(r).toNumber();t.useStroke=!0}break;case`stroke-width`:t.strokeStyle.width=Number(r);break;case`fill`:if(r!==`none`){if(r.startsWith(`url(`)){let n=jC(r);t.fillStyle.fill=e.defs[n]}else t.fillStyle.color=P.shared.setValue(r).toNumber();t.useFill=!0}break;case`fill-opacity`:t.fillStyle.alpha=Number(r);break;case`stroke-opacity`:t.strokeStyle.alpha=Number(r);break;case`opacity`:t.fillStyle.alpha=Number(r),t.strokeStyle.alpha=Number(r)}}var FC,IC=s((()=>{Ar(),MC(),FC={fill:{type:`paint`,default:0},"fill-opacity":{type:`number`,default:1},stroke:{type:`paint`,default:0},"stroke-width":{type:`number`,default:1},"stroke-opacity":{type:`number`,default:1},"stroke-linecap":{type:`string`,default:`butt`},"stroke-linejoin":{type:`string`,default:`miter`},"stroke-miterlimit":{type:`number`,default:10},"stroke-dasharray":{type:`string`,default:`none`},"stroke-dashoffset":{type:`number`,default:0},opacity:{type:`number`,default:1}}}));function LC(e){if(e.length<=2)return!0;let t=e.map(e=>e.area).sort((e,t)=>t-e),[n,r]=t,i=t[t.length-1],a=n/r,o=r/i;return!(a>3&&o<2)}var RC=s((()=>{}));function zC(e){return e.split(/(?=[Mm])/).filter(e=>e.trim().length>0)}function BC(e){let t=e.match(/[-+]?[0-9]*\.?[0-9]+/g);if(!t||t.length<4)return 0;let n=t.map(Number),r=[],i=[];for(let e=0;e<n.length;e+=2)e+1<n.length&&(r.push(n[e]),i.push(n[e+1]));if(r.length===0||i.length===0)return 0;let a=Math.min(...r),o=Math.max(...r),s=Math.min(...i),c=Math.max(...i);return(o-a)*(c-s)}function VC(e,t){let n=new bC(e,!1);for(let e of n.instructions)t.instructions.push(e)}var HC=s((()=>{xC()}));function UC(e,t){if(typeof e==`string`){let t=document.createElement(`div`);t.innerHTML=e.trim(),e=t.querySelector(`svg`)}let n={context:t,defs:{},path:new bC};wC(e,n);let r=e.children,{fillStyle:i,strokeStyle:a}=NC(e,n);for(let e=0;e<r.length;e++){let t=r[e];t.nodeName.toLowerCase()!==`defs`&&WC(t,n,i,a)}return t}function WC(e,t,n,r){let i=e.children,{fillStyle:a,strokeStyle:o}=NC(e,t);a&&n?n={...n,...a}:a&&(n=a),o&&r?r={...r,...o}:o&&(r=o);let s=!n&&!r;s&&(n={color:0});let c,l,u,d,f,p,m,h,g,_,v,y,b,x,S,C,w;switch(e.nodeName.toLowerCase()){case`path`:{x=e.getAttribute(`d`);let i=e.getAttribute(`fill-rule`),a=zC(x),o=i===`evenodd`,s=a.length>1;if(o&&s){let e=a.map(e=>({path:e,area:BC(e)}));if(e.sort((e,t)=>t.area-e.area),a.length>3||!LC(e))for(let i=0;i<e.length;i++){let a=e[i],o=i===0;t.context.beginPath();let s=new bC(void 0,!0);VC(a.path,s),t.context.path(s),o?(n&&t.context.fill(n),r&&t.context.stroke(r)):t.context.cut()}else for(let i=0;i<e.length;i++){let a=e[i],o=i%2==1;t.context.beginPath();let s=new bC(void 0,!0);VC(a.path,s),t.context.path(s),o?t.context.cut():(n&&t.context.fill(n),r&&t.context.stroke(r))}}else S=new bC(x,!i||i===`evenodd`),t.context.path(S),n&&t.context.fill(n),r&&t.context.stroke(r);break}case`circle`:m=SC(e,`cx`,0),h=SC(e,`cy`,0),g=SC(e,`r`,0),t.context.ellipse(m,h,g,g),n&&t.context.fill(n),r&&t.context.stroke(r);break;case`rect`:c=SC(e,`x`,0),l=SC(e,`y`,0),C=SC(e,`width`,0),w=SC(e,`height`,0),_=SC(e,`rx`,0),v=SC(e,`ry`,0),_||v?t.context.roundRect(c,l,C,w,_||v):t.context.rect(c,l,C,w),n&&t.context.fill(n),r&&t.context.stroke(r);break;case`ellipse`:m=SC(e,`cx`,0),h=SC(e,`cy`,0),_=SC(e,`rx`,0),v=SC(e,`ry`,0),t.context.beginPath(),t.context.ellipse(m,h,_,v),n&&t.context.fill(n),r&&t.context.stroke(r);break;case`line`:u=SC(e,`x1`,0),d=SC(e,`y1`,0),f=SC(e,`x2`,0),p=SC(e,`y2`,0),t.context.beginPath(),t.context.moveTo(u,d),t.context.lineTo(f,p),r&&t.context.stroke(r);break;case`polygon`:b=e.getAttribute(`points`),y=b.match(/-?\d+/g).map(e=>parseInt(e,10)),t.context.poly(y,!0),n&&t.context.fill(n),r&&t.context.stroke(r);break;case`polyline`:b=e.getAttribute(`points`),y=b.match(/-?\d+/g).map(e=>parseInt(e,10)),t.context.poly(y,!1),r&&t.context.stroke(r);break;case`g`:case`svg`:break;default:z(`[SVG parser] <${e.nodeName}> elements unsupported`)}s&&(n=null);for(let e=0;e<i.length;e++)WC(i[e],t,n,r)}var GC=s((()=>{B(),xC(),AC(),CC(),IC(),RC(),HC()}));function KC(e){return P.isColorLike(e)}function qC(e){return e instanceof Tx}function JC(e){return e instanceof xx}function YC(e){return e instanceof U}function XC(e,t,n){let r=P.shared.setValue(t??0);return e.color=r.toNumber(),e.alpha=r.alpha===1?n.alpha:r.alpha,e.texture=U.WHITE,{...n,...e}}function ZC(e,t,n){return e.texture=t,{...n,...e}}function QC(e,t,n){return e.fill=t,e.color=16777215,e.texture=t.texture,e.matrix=t.transform,e.textureSpace=t.textureSpace,{...n,...e}}function $C(e,t,n){return t.buildGradient(),e.fill=t,e.color=16777215,e.texture=t.texture,e.matrix=t.transform,e.textureSpace=t.textureSpace,{...n,...e}}function ew(e,t){let n={...t,...e},r=P.shared.setValue(n.color);return n.alpha*=r.alpha,n.color=r.toNumber(),n}function tw(e,t){if(e==null)return null;let n={},r=e;return KC(e)?XC(n,e,t):YC(e)?ZC(n,e,t):qC(e)?QC(n,e,t):JC(e)?$C(n,e,t):r.fill&&qC(r.fill)?QC(r,r.fill,t):r.fill&&JC(r.fill)?$C(r,r.fill,t):ew(r,t)}function nw(e,t){let{width:n,alignment:r,miterLimit:i,cap:a,join:o,pixelLine:s,...c}=t,l=tw(e,c);return l?{width:n,alignment:r,miterLimit:i,cap:a,join:o,pixelLine:s,...l}:null}var rw=s((()=>{Ar(),W(),Sx(),Ex()}));function iw(e,t){let n=1,r=e.shapePath.shapePrimitives;for(let e=0;e<r.length;e++){let i=r[e].shape;if(i.type!==`polygon`)continue;let a=i.points,o=a.length;if(o<6)continue;let s=i.closePath;for(let e=0;e<o;e+=2){if(!s&&(e===0||e===o-2))continue;let r=(e-2+o)%o,i=(e+2)%o,c=a[r],l=a[r+1],u=a[e],d=a[e+1],f=a[i],p=a[i+1],m=c-u,h=l-d,g=f-u,_=p-d,v=m*m+h*h,y=g*g+_*_;if(v<1e-12||y<1e-12)continue;let b=(m*g+h*_)/Math.sqrt(v*y);b<-1?b=-1:b>1&&(b=1);let x=Math.sqrt((1-b)*.5);if(x<1e-6)continue;let S=Math.min(1/x,t);S>n&&(n=S)}}return n}var aw=s((()=>{})),ow,sw,cw,lw,uw=s((()=>{Xn(),Ar(),I(),zr(),W(),Kr(),Xr(),Di(),xC(),GC(),rw(),aw(),ow=new Lr,sw=new F,cw=class e extends Yn{constructor(){super(...arguments),this._gpuData=Object.create(null),this.autoGarbageCollect=!0,this._gcLastUsed=-1,this.uid=Wr(`graphicsContext`),this.dirty=!0,this.batchMode=`auto`,this.instructions=[],this.destroyed=!1,this._activePath=new bC,this._transform=new F,this._fillStyle={...e.defaultFillStyle},this._strokeStyle={...e.defaultStrokeStyle},this._stateStack=[],this._tick=0,this._bounds=new Ei,this._boundsDirty=!0}clone(){let t=new e;return t.batchMode=this.batchMode,t.instructions=this.instructions.slice(),t._activePath=this._activePath.clone(),t._transform=this._transform.clone(),t._fillStyle={...this._fillStyle},t._strokeStyle={...this._strokeStyle},t._stateStack=this._stateStack.slice(),t._bounds=this._bounds.clone(),t._boundsDirty=!0,t}get fillStyle(){return this._fillStyle}set fillStyle(t){this._fillStyle=tw(t,e.defaultFillStyle)}get strokeStyle(){return this._strokeStyle}set strokeStyle(t){this._strokeStyle=nw(t,e.defaultStrokeStyle)}setFillStyle(t){return this._fillStyle=tw(t,e.defaultFillStyle),this}setStrokeStyle(t){return this._strokeStyle=tw(t,e.defaultStrokeStyle),this}texture(e,t,n,r,i,a){return this.instructions.push({action:`texture`,data:{image:e,dx:n||0,dy:r||0,dw:i||e.frame.width,dh:a||e.frame.height,transform:this._transform.clone(),alpha:this._fillStyle.alpha,style:t||t===0?P.shared.setValue(t).toNumber():16777215}}),this.onUpdate(),this}beginPath(){return this._activePath=new bC,this}fill(t,n){let r,i=this.instructions[this.instructions.length-1];return r=this._tick===0&&i?.action===`stroke`?i.data.path:this._activePath.clone(),r?(t!=null&&(n!==void 0&&typeof t==`number`&&(R(L,`GraphicsContext.fill(color, alpha) is deprecated, use GraphicsContext.fill({ color, alpha }) instead`),t={color:t,alpha:n}),this._fillStyle=tw(t,e.defaultFillStyle)),this.instructions.push({action:`fill`,data:{style:this.fillStyle,path:r}}),this.onUpdate(),this._initNextPathLocation(),this._tick=0,this):this}_initNextPathLocation(){let{x:e,y:t}=this._activePath.getLastPoint(Lr.shared);this._activePath.clear(),this._activePath.moveTo(e,t)}stroke(t){let n,r=this.instructions[this.instructions.length-1];return n=this._tick===0&&r?.action===`fill`?r.data.path:this._activePath.clone(),n?(t!=null&&(this._strokeStyle=nw(t,e.defaultStrokeStyle)),this.instructions.push({action:`stroke`,data:{style:this.strokeStyle,path:n}}),this.onUpdate(),this._initNextPathLocation(),this._tick=0,this):this}cut(){for(let e=0;e<2;e++){let t=this.instructions[this.instructions.length-1-e],n=this._activePath.clone();if(t&&(t.action===`stroke`||t.action===`fill`)){if(t.data.hole)t.data.hole.addPath(n);else{t.data.hole=n;break}}}return this._initNextPathLocation(),this}arc(e,t,n,r,i,a){this._tick++;let o=this._transform;return this._activePath.arc(o.a*e+o.c*t+o.tx,o.b*e+o.d*t+o.ty,n,r,i,a),this}arcTo(e,t,n,r,i){this._tick++;let a=this._transform;return this._activePath.arcTo(a.a*e+a.c*t+a.tx,a.b*e+a.d*t+a.ty,a.a*n+a.c*r+a.tx,a.b*n+a.d*r+a.ty,i),this}arcToSvg(e,t,n,r,i,a,o){this._tick++;let s=this._transform;return this._activePath.arcToSvg(e,t,n,r,i,s.a*a+s.c*o+s.tx,s.b*a+s.d*o+s.ty),this}bezierCurveTo(e,t,n,r,i,a,o){this._tick++;let s=this._transform;return this._activePath.bezierCurveTo(s.a*e+s.c*t+s.tx,s.b*e+s.d*t+s.ty,s.a*n+s.c*r+s.tx,s.b*n+s.d*r+s.ty,s.a*i+s.c*a+s.tx,s.b*i+s.d*a+s.ty,o),this}closePath(){return this._tick++,this._activePath?.closePath(),this}ellipse(e,t,n,r){return this._tick++,this._activePath.ellipse(e,t,n,r,this._transform.clone()),this}circle(e,t,n){return this._tick++,this._activePath.circle(e,t,n,this._transform.clone()),this}path(e){return this._tick++,this._activePath.addPath(e,this._transform.clone()),this}lineTo(e,t){this._tick++;let n=this._transform;return this._activePath.lineTo(n.a*e+n.c*t+n.tx,n.b*e+n.d*t+n.ty),this}moveTo(e,t){this._tick++;let n=this._transform,r=this._activePath.instructions,i=n.a*e+n.c*t+n.tx,a=n.b*e+n.d*t+n.ty;return r.length===1&&r[0].action===`moveTo`?(r[0].data[0]=i,r[0].data[1]=a,this):(this._activePath.moveTo(i,a),this)}quadraticCurveTo(e,t,n,r,i){this._tick++;let a=this._transform;return this._activePath.quadraticCurveTo(a.a*e+a.c*t+a.tx,a.b*e+a.d*t+a.ty,a.a*n+a.c*r+a.tx,a.b*n+a.d*r+a.ty,i),this}rect(e,t,n,r){return this._tick++,this._activePath.rect(e,t,n,r,this._transform.clone()),this}roundRect(e,t,n,r,i){return this._tick++,this._activePath.roundRect(e,t,n,r,i,this._transform.clone()),this}poly(e,t){return this._tick++,this._activePath.poly(e,t,this._transform.clone()),this}regularPoly(e,t,n,r,i=0,a){return this._tick++,this._activePath.regularPoly(e,t,n,r,i,a),this}roundPoly(e,t,n,r,i,a){return this._tick++,this._activePath.roundPoly(e,t,n,r,i,a),this}roundShape(e,t,n,r){return this._tick++,this._activePath.roundShape(e,t,n,r),this}filletRect(e,t,n,r,i){return this._tick++,this._activePath.filletRect(e,t,n,r,i),this}chamferRect(e,t,n,r,i,a){return this._tick++,this._activePath.chamferRect(e,t,n,r,i,a),this}star(e,t,n,r,i=0,a=0){return this._tick++,this._activePath.star(e,t,n,r,i,a,this._transform.clone()),this}svg(e){return this._tick++,UC(e,this),this}restore(){let e=this._stateStack.pop();return e&&(this._transform=e.transform,this._fillStyle=e.fillStyle,this._strokeStyle=e.strokeStyle),this}save(){return this._stateStack.push({transform:this._transform.clone(),fillStyle:{...this._fillStyle},strokeStyle:{...this._strokeStyle}}),this}getTransform(){return this._transform}resetTransform(){return this._transform.identity(),this}rotate(e){return this._transform.rotate(e),this}scale(e,t=e){return this._transform.scale(e,t),this}setTransform(e,t,n,r,i,a){return e instanceof F?(this._transform.set(e.a,e.b,e.c,e.d,e.tx,e.ty),this):(this._transform.set(e,t,n,r,i,a),this)}transform(e,t,n,r,i,a){return e instanceof F?(this._transform.append(e),this):(sw.set(e,t,n,r,i,a),this._transform.append(sw),this)}translate(e,t=e){return this._transform.translate(e,t),this}clear(){return this._activePath.clear(),this.instructions.length=0,this.resetTransform(),this.onUpdate(),this}onUpdate(){this._boundsDirty=!0,this.dirty=!0,this.emit(`update`,this,16)}get bounds(){if(!this._boundsDirty)return this._bounds;this._boundsDirty=!1;let e=this._bounds;e.clear();for(let t=0;t<this.instructions.length;t++){let n=this.instructions[t],r=n.action;if(r===`fill`){let t=n.data;e.addBounds(t.path.bounds)}else if(r===`texture`){let t=n.data;e.addFrame(t.dx,t.dy,t.dx+t.dw,t.dy+t.dh,t.transform)}if(r===`stroke`){let t=n.data,r=t.style.alignment,i=t.style.width*(1-r);t.style.join===`miter`&&(i*=iw(t.path,t.style.miterLimit));let a=t.path.bounds;e.addFrame(a.minX-i,a.minY-i,a.maxX+i,a.maxY+i)}}return e.isValid||e.set(0,0,0,0),e}containsPoint(e){if(!this.bounds.containsPoint(e.x,e.y))return!1;let t=this.instructions,n=!1;for(let r=0;r<t.length;r++){let i=t[r],a=i.data,o=a.path;if(!i.action||!o)continue;let s=a.style,c=o.shapePath.shapePrimitives;for(let t=0;t<c.length;t++){let r=c[t].shape;if(!s||!r)continue;let o=c[t].transform,l=o?o.applyInverse(e,ow):e;if(i.action===`fill`)n=r.contains(l.x,l.y);else{let e=s;n=r.strokeContains(l.x,l.y,e.width,e.alignment)}let u=a.hole;if(u){let e=u.shapePath?.shapePrimitives;if(e)for(let t=0;t<e.length;t++)e[t].shape.contains(l.x,l.y)&&(n=!1)}if(n)return!0}}return n}unload(){this.emit(`unload`,this);for(let e in this._gpuData)this._gpuData[e]?.destroy();this._gpuData=Object.create(null)}destroy(e=!1){if(!this.destroyed){if(this.destroyed=!0,this._stateStack.length=0,this._transform=null,this.unload(),this.emit(`destroy`,this),this.removeAllListeners(),typeof e==`boolean`?e:e?.texture){let t=typeof e==`boolean`?e:e?.textureSource;this._fillStyle.texture&&(this._fillStyle.fill&&`uid`in this._fillStyle.fill?this._fillStyle.fill.destroy():this._fillStyle.texture.destroy(t)),this._strokeStyle.texture&&(this._strokeStyle.fill&&`uid`in this._strokeStyle.fill?this._strokeStyle.fill.destroy():this._strokeStyle.texture.destroy(t))}this._fillStyle=null,this._strokeStyle=null,this.instructions=null,this._activePath=null,this._bounds=null,this._stateStack=null,this.customShader=null,this._transform=null}}},cw.defaultFillStyle={color:16777215,alpha:1,texture:U.WHITE,matrix:null,fill:null,textureSpace:`local`},cw.defaultStrokeStyle={width:1,color:16777215,alpha:1,alignment:.5,miterLimit:10,cap:`butt`,join:`miter`,texture:U.WHITE,matrix:null,fill:null,textureSpace:`local`,pixelLine:!1},lw=cw})),dw,fw,pw,mw,hw=s((()=>{N(),ca(),Tg(),dw=class{constructor(){this.isBatchable=!1}reset(){this.isBatchable=!1,this.context=null,this.graphicsData&&=(this.graphicsData.destroy(),null)}destroy(){this.reset()}},fw=class{constructor(){this.instructions=new sa}init(){this.instructions.reset()}destroy(){this.instructions.destroy(),this.instructions=null}},pw=class e{constructor(e){this._renderer=e,this._managedContexts=new wg({renderer:e,type:`resource`,name:`graphicsContext`})}init(t){e.defaultOptions.bezierSmoothness=t?.bezierSmoothness??e.defaultOptions.bezierSmoothness}getContextRenderData(e){return this.getGpuContext(e).graphicsData||this._initContextRenderData(e)}updateGpuContext(e){let t=e._gpuData,n=!!t[this._renderer.uid],r=t[this._renderer.uid]||this._initContext(e);return(e.dirty||!n)&&(n&&r.reset(),r.isBatchable=!1,e.dirty=!1),r}getGpuContext(e){return e._gpuData[this._renderer.uid]||this._initContext(e)}_initContextRenderData(e){let t=new fw,n=this.getGpuContext(e);return n.graphicsData=t,t.init(),t}_initContext(e){let t=new dw;return t.context=e,e._gpuData[this._renderer.uid]=t,this._managedContexts.add(e),t}destroy(){this._managedContexts.destroy(),this._renderer=null}},pw.extension={type:[j.CanvasSystem],name:`graphicsContext`},pw.defaultOptions={bezierSmoothness:.5},mw=pw})),gw,_w=s((()=>{N(),Nu(),Tg(),gw=class{constructor(e,t){this.state=Mu.for2d(),this.renderer=e,this._adaptor=t,this.renderer.runners.contextChange.add(this),this._managedGraphics=new wg({renderer:e,type:`renderable`,priority:-1,name:`graphics`})}contextChange(){this._adaptor.contextChange(this.renderer)}validateRenderable(e){return!1}addRenderable(e,t){this._managedGraphics.add(e),this.renderer.renderPipes.batch.break(t),t.add(e)}updateRenderable(e){}execute(e){e.isRenderable&&this._adaptor.execute(this,e)}destroy(){this._managedGraphics.destroy(),this.renderer=null,this._adaptor.destroy(),this._adaptor=null}},gw.extension={type:[j.CanvasPipes],name:`graphics`}})),vw,yw,bw=s((()=>{N(),Nu(),Tg(),ai(),qh(),Px(),vw=class{constructor(){this.batches=[],this.batched=!1}destroy(){this.batches.forEach(e=>{ii.return(e)}),this.batches.length=0}},yw=class{constructor(e,t){this.state=Mu.for2d(),this.renderer=e,this._adaptor=t,this.renderer.runners.contextChange.add(this),this._managedGraphics=new wg({renderer:e,type:`renderable`,priority:-1,name:`graphics`})}contextChange(){this._adaptor.contextChange(this.renderer)}validateRenderable(e){let t=e.context,n=!!e._gpuData,r=this.renderer.graphicsContext.updateGpuContext(t);return!!(r.isBatchable||n!==r.isBatchable)}addRenderable(e,t){let n=this.renderer.graphicsContext.updateGpuContext(e.context);e.didViewUpdate&&this._rebuild(e),n.isBatchable?this._addToBatcher(e,t):(this.renderer.renderPipes.batch.break(t),t.add(e))}updateRenderable(e){let t=this._getGpuDataForRenderable(e).batches;for(let e=0;e<t.length;e++){let n=t[e];n._batcher.updateElement(n)}}execute(e){if(!e.isRenderable)return;let t=this.renderer,n=e.context;if(!t.graphicsContext.getGpuContext(n).batches.length)return;let r=n.customShader||this._adaptor.shader;this.state.blendMode=e.groupBlendMode;let i=r.resources.localUniforms.uniforms;i.uTransformMatrix=e.groupTransform,i.uRound=t._roundPixels|e._roundPixels,Kh(e.groupColorAlpha,i.uColor,0),this._adaptor.execute(this,e)}_rebuild(e){let t=this._getGpuDataForRenderable(e),n=this.renderer.graphicsContext.updateGpuContext(e.context);t.destroy(),n.isBatchable&&this._updateBatchesForRenderable(e,t)}_addToBatcher(e,t){let n=this.renderer.renderPipes.batch,r=this._getGpuDataForRenderable(e).batches;for(let e=0;e<r.length;e++){let i=r[e];n.addToBatch(i,t)}}_getGpuDataForRenderable(e){return e._gpuData[this.renderer.uid]||this._initGpuDataForRenderable(e)}_initGpuDataForRenderable(e){let t=new vw;return e._gpuData[this.renderer.uid]=t,this._managedGraphics.add(e),t}_updateBatchesForRenderable(e,t){let n=e.context,r=this.renderer.graphicsContext.getGpuContext(n),i=this.renderer._roundPixels|e._roundPixels;t.batches=r.batches.map(t=>{let n=ii.get(Nx);return t.copyTo(n),n.renderable=e,n.roundPixels=i,n})}destroy(){this._managedGraphics.destroy(),this.renderer=null,this._adaptor.destroy(),this._adaptor=null,this.state=null}},yw.extension={type:[j.WebGLPipes,j.WebGPUPipes],name:`graphics`}})),xw=s((()=>{N(),hw(),_w(),BS(),bw(),M.add(gw),M.add(yw),M.add(mw),M.add(zS)})),Sw,Cw=s((()=>{Xr(),Yo(),uw(),xw(),Sw=class e extends Jo{constructor(e){e instanceof lw&&(e={context:e});let{context:t,roundPixels:n,...r}=e||{};super({label:`Graphics`,...r}),this.renderPipeId=`graphics`,t?this.context=t:(this.context=this._ownedContext=new lw,this.context.autoGarbageCollect=this.autoGarbageCollect),this.didViewUpdate=!0,this.allowChildren=!1,this.roundPixels=n??!1}set context(e){e!==this._context&&(this._context&&(this._context.off(`update`,this.onViewUpdate,this),this._context.off(`unload`,this.unload,this)),this._context=e,this._context.on(`update`,this.onViewUpdate,this),this._context.on(`unload`,this.unload,this),this.onViewUpdate())}get context(){return this._context}get bounds(){return this._context.bounds}updateBounds(){}containsPoint(e){return this._context.containsPoint(e)}destroy(e){this._ownedContext&&!e?this._ownedContext.destroy(e):(e===!0||e?.context===!0)&&this._context.destroy(e),this._context?.off(`update`,this.onViewUpdate,this),this._context?.off(`unload`,this.unload,this),this._ownedContext=null,this._context=null,super.destroy(e)}_onTouch(e){this._gcLastUsed=e,this._context._gcLastUsed=e}_callContextMethod(e,t){return this.context[e](...t),this}setFillStyle(...e){return this._callContextMethod(`setFillStyle`,e)}setStrokeStyle(...e){return this._callContextMethod(`setStrokeStyle`,e)}fill(...e){return this._callContextMethod(`fill`,e)}stroke(...e){return this._callContextMethod(`stroke`,e)}texture(...e){return this._callContextMethod(`texture`,e)}beginPath(){return this._callContextMethod(`beginPath`,[])}cut(){return this._callContextMethod(`cut`,[])}arc(...e){return this._callContextMethod(`arc`,e)}arcTo(...e){return this._callContextMethod(`arcTo`,e)}arcToSvg(...e){return this._callContextMethod(`arcToSvg`,e)}bezierCurveTo(...e){return this._callContextMethod(`bezierCurveTo`,e)}closePath(){return this._callContextMethod(`closePath`,[])}ellipse(...e){return this._callContextMethod(`ellipse`,e)}circle(...e){return this._callContextMethod(`circle`,e)}path(...e){return this._callContextMethod(`path`,e)}lineTo(...e){return this._callContextMethod(`lineTo`,e)}moveTo(...e){return this._callContextMethod(`moveTo`,e)}quadraticCurveTo(...e){return this._callContextMethod(`quadraticCurveTo`,e)}rect(...e){return this._callContextMethod(`rect`,e)}roundRect(...e){return this._callContextMethod(`roundRect`,e)}poly(...e){return this._callContextMethod(`poly`,e)}regularPoly(...e){return this._callContextMethod(`regularPoly`,e)}roundPoly(...e){return this._callContextMethod(`roundPoly`,e)}roundShape(...e){return this._callContextMethod(`roundShape`,e)}filletRect(...e){return this._callContextMethod(`filletRect`,e)}chamferRect(...e){return this._callContextMethod(`chamferRect`,e)}star(...e){return this._callContextMethod(`star`,e)}svg(...e){return this._callContextMethod(`svg`,e)}restore(...e){return this._callContextMethod(`restore`,e)}save(){return this._callContextMethod(`save`,[])}getTransform(){return this.context.getTransform()}resetTransform(){return this._callContextMethod(`resetTransform`,[])}rotateTransform(...e){return this._callContextMethod(`rotate`,e)}scaleTransform(...e){return this._callContextMethod(`scale`,e)}setTransform(...e){return this._callContextMethod(`setTransform`,e)}transform(...e){return this._callContextMethod(`transform`,e)}translateTransform(...e){return this._callContextMethod(`translate`,e)}clear(){return this._callContextMethod(`clear`,[])}get fillStyle(){return this._context.fillStyle}set fillStyle(e){this._context.fillStyle=e}get strokeStyle(){return this._context.strokeStyle}set strokeStyle(e){this._context.strokeStyle=e}clone(t=!1){return t?new e(this._context.clone()):(this._ownedContext=null,new e(this._context))}lineStyle(e,t,n){R(L,`Graphics#lineStyle is no longer needed. Use Graphics#setStrokeStyle to set the stroke style.`);let r={};return e&&(r.width=e),t&&(r.color=t),n&&(r.alpha=n),this.context.strokeStyle=r,this}beginFill(e,t){R(L,`Graphics#beginFill is no longer needed. Use Graphics#fill to fill the shape with the desired style.`);let n={};return e!==void 0&&(n.color=e),t!==void 0&&(n.alpha=t),this.context.fillStyle=n,this}endFill(){R(L,`Graphics#endFill is no longer needed. Use Graphics#fill to fill the shape with the desired style.`),this.context.fill();let e=this.context.strokeStyle;return(e.width!==lw.defaultStrokeStyle.width||e.color!==lw.defaultStrokeStyle.color||e.alpha!==lw.defaultStrokeStyle.alpha)&&this.context.stroke(),this}drawCircle(...e){return R(L,`Graphics#drawCircle has been renamed to Graphics#circle`),this._callContextMethod(`circle`,e)}drawEllipse(...e){return R(L,`Graphics#drawEllipse has been renamed to Graphics#ellipse`),this._callContextMethod(`ellipse`,e)}drawPolygon(...e){return R(L,`Graphics#drawPolygon has been renamed to Graphics#poly`),this._callContextMethod(`poly`,e)}drawRect(...e){return R(L,`Graphics#drawRect has been renamed to Graphics#rect`),this._callContextMethod(`rect`,e)}drawRoundedRect(...e){return R(L,`Graphics#drawRoundedRect has been renamed to Graphics#roundRect`),this._callContextMethod(`roundRect`,e)}drawStar(...e){return R(L,`Graphics#drawStar has been renamed to Graphics#star`),this._callContextMethod(`star`,e)}}}));function ww(e,t,n,r,i,a){a=Math.max(0,Math.min(a,Math.min(r,i)/2)),e.moveTo(t+a,n),e.lineTo(t+r-a,n),e.quadraticCurveTo(t+r,n,t+r,n+a),e.lineTo(t+r,n+i-a),e.quadraticCurveTo(t+r,n+i,t+r-a,n+i),e.lineTo(t+a,n+i),e.quadraticCurveTo(t,n+i,t,n+i-a),e.lineTo(t,n+a),e.quadraticCurveTo(t,n,t+a,n)}function Tw(e,t){switch(t.type){case`rectangle`:{let n=t;e.rect(n.x,n.y,n.width,n.height);break}case`roundedRectangle`:{let n=t;ww(e,n.x,n.y,n.width,n.height,n.radius);break}case`circle`:{let n=t;e.moveTo(n.x+n.radius,n.y),e.arc(n.x,n.y,n.radius,0,Math.PI*2);break}case`ellipse`:{let n=t;e.ellipse?(e.moveTo(n.x+n.halfWidth,n.y),e.ellipse(n.x,n.y,n.halfWidth,n.halfHeight,0,0,Math.PI*2)):(e.save(),e.translate(n.x,n.y),e.scale(n.halfWidth,n.halfHeight),e.moveTo(1,0),e.arc(0,0,1,0,Math.PI*2),e.restore());break}case`triangle`:{let n=t;e.moveTo(n.x,n.y),e.lineTo(n.x2,n.y2),e.lineTo(n.x3,n.y3),e.closePath();break}default:{let n=t,r=n.points;if(!r?.length)break;e.moveTo(r[0],r[1]);for(let t=2;t<r.length;t+=2)e.lineTo(r[t],r[t+1]);n.closePath&&e.closePath();break}}}function Ew(e,t,n){let r=[],i=[],a=[];if(!aS[t.type]?.build(t,r))return!1;mx(r,n,!1,t.closePath??!0,i,a);for(let t=0;t<a.length;t+=3){let n=a[t]*2,r=a[t+1]*2,o=a[t+2]*2;e.moveTo(i[n],i[n+1]),e.lineTo(i[r],i[r+1]),e.lineTo(i[o],i[o+1]),e.closePath()}return!0}function Dw(e,t){if(!t?.length)return!1;for(let n=0;n<t.length;n++){let r=t[n];if(!r?.shape)continue;let i=r.transform,a=i&&!i.isIdentity();a&&(e.save(),e.transform(i.a,i.b,i.c,i.d,i.tx,i.ty)),Tw(e,r.shape),a&&e.restore()}return!0}var Ow,kw=s((()=>{N(),hx(),Cw(),cS(),B(),Ow=class{constructor(e){this._warnedMaskTypes=new Set,this._canvasMaskStack=[],this._renderer=e}push(e,t,n){this._renderer.renderPipes.batch.break(n),n.add({renderPipeId:`stencilMask`,action:`pushMaskBegin`,mask:e,inverse:t._maskOptions.inverse,canBundle:!1})}pop(e,t,n){this._renderer.renderPipes.batch.break(n),n.add({renderPipeId:`stencilMask`,action:`popMaskEnd`,mask:e,inverse:t._maskOptions.inverse,canBundle:!1})}execute(e){if(e.action!==`pushMaskBegin`&&e.action!==`popMaskEnd`)return;let t=this._renderer,n=t.canvasContext,r=n?.activeContext;if(!r)return;if(e.action===`popMaskEnd`){this._canvasMaskStack.pop()&&r.restore();return}e.inverse&&this._warnOnce(`inverse`,`CanvasRenderer: inverse masks are not supported on Canvas2D; ignoring inverse flag.`);let i=e.mask.mask;if(!(i instanceof Sw)){this._warnOnce(`nonGraphics`,`CanvasRenderer: only Graphics masks are supported in Canvas2D; skipping mask.`),this._canvasMaskStack.push(!1);return}let a=i,o=a.context?.instructions;if(!o?.length){this._canvasMaskStack.push(!1);return}r.save(),n.setContextTransform(a.groupTransform,(t._roundPixels|a._roundPixels)===1),r.beginPath();let s=!1,c=!1;for(let e=0;e<o.length;e++){let t=o[e],n=t.action;if(n!==`fill`&&n!==`stroke`)continue;let i=t.data,a=i?.path?.shapePath;if(!a?.shapePrimitives?.length)continue;let l=n===`stroke`,u=a.shapePrimitives;for(let e=0;e<u.length;e++){let t=u[e];if(!t?.shape)continue;let n=t.transform,a=n&&!n.isIdentity();a&&(r.save(),r.transform(n.a,n.b,n.c,n.d,n.tx,n.ty)),l&&i.style?s=Ew(r,t.shape,i.style)||s:(Tw(r,t.shape),c=Dw(r,t.holes)||c,s=!0),a&&r.restore()}}if(!s){r.restore(),this._canvasMaskStack.push(!1);return}c?r.clip(`evenodd`):r.clip(),this._canvasMaskStack.push(!0)}destroy(){this._renderer=null,this._warnedMaskTypes=null,this._canvasMaskStack=null}_warnOnce(e,t){this._warnedMaskTypes.has(e)||(this._warnedMaskTypes.add(e),z(t))}},Ow.extension={type:[j.CanvasPipes],name:`stencilMask`}}));function Aw(){let e=Mc(),t=Object.create(null);return t.inherit=jw,t.none=jw,t.normal=`source-over`,t.add=`lighter`,t.multiply=e?`multiply`:jw,t.screen=e?`screen`:jw,t.overlay=e?`overlay`:jw,t.darken=e?`darken`:jw,t.lighten=e?`lighten`:jw,t[`color-dodge`]=e?`color-dodge`:jw,t[`color-burn`]=e?`color-burn`:jw,t[`hard-light`]=e?`hard-light`:jw,t[`soft-light`]=e?`soft-light`:jw,t.difference=e?`difference`:jw,t.exclusion=e?`exclusion`:jw,t.saturation=e?`saturation`:jw,t.color=e?`color`:jw,t.luminosity=e?`luminosity`:jw,t[`linear-burn`]=e?`color-burn`:jw,t[`linear-dodge`]=e?`color-dodge`:jw,t[`linear-light`]=e?`hard-light`:jw,t[`pin-light`]=e?`hard-light`:jw,t[`vivid-light`]=e?`hard-light`:jw,t[`hard-mix`]=jw,t.negation=e?`difference`:jw,t[`normal-npm`]=t.normal,t[`add-npm`]=t.add,t[`screen-npm`]=t.screen,t.erase=`destination-out`,t.subtract=jw,t.divide=jw,t.min=jw,t.max=jw,t}var jw,Mw=s((()=>{Pc(),jw=`source-over`})),Nw,Pw,Fw=s((()=>{Ar(),N(),I(),Mw(),Nw=new F,Pw=class{constructor(e){this.activeResolution=1,this.smoothProperty=`imageSmoothingEnabled`,this.blendModes=Aw(),this._activeBlendMode=`normal`,this._projTransform=null,this._outerBlend=!1,this._warnedBlendModes=new Set,this._renderer=e}resolutionChange(e){this.activeResolution=e}init(){let e=this._renderer.background.alpha<1;if(this.rootContext=this._renderer.canvas.getContext(`2d`,{alpha:e}),this.activeContext=this.rootContext,this.activeResolution=this._renderer.resolution,!this.rootContext.imageSmoothingEnabled){let e=this.rootContext;e.webkitImageSmoothingEnabled?this.smoothProperty=`webkitImageSmoothingEnabled`:e.mozImageSmoothingEnabled?this.smoothProperty=`mozImageSmoothingEnabled`:e.oImageSmoothingEnabled?this.smoothProperty=`oImageSmoothingEnabled`:e.msImageSmoothingEnabled&&(this.smoothProperty=`msImageSmoothingEnabled`)}}setContextTransform(e,t,n,r){let i=r?F.IDENTITY:this._renderer.globalUniforms.globalUniformData?.worldTransformMatrix||F.IDENTITY,a=Nw;a.copyFrom(i),a.append(e);let o=this._projTransform,s=this.activeResolution;if(n||=s,o){let e=F.shared;e.copyFrom(a),e.prepend(o),a=e}t?this.activeContext.setTransform(a.a*n,a.b*n,a.c*n,a.d*n,a.tx*s|0,a.ty*s|0):this.activeContext.setTransform(a.a*n,a.b*n,a.c*n,a.d*n,a.tx*s,a.ty*s)}clear(e,t){let n=this.activeContext,r=this._renderer;if(n.clearRect(0,0,r.width,r.height),e){let i=P.shared.setValue(e);n.globalAlpha=t??i.alpha,n.fillStyle=i.toHex(),n.fillRect(0,0,r.width,r.height),n.globalAlpha=1}}setBlendMode(e){if(this._activeBlendMode===e)return;this._activeBlendMode=e,this._outerBlend=!1;let t=this.blendModes[e];if(!t){this._warnedBlendModes.has(e)||(console.warn(`CanvasRenderer: blend mode "${e}" is not supported in Canvas2D; falling back to "source-over".`),this._warnedBlendModes.add(e)),this.activeContext.globalCompositeOperation=`source-over`;return}this.activeContext.globalCompositeOperation=t}destroy(){this.rootContext=null,this.activeContext=null,this._warnedBlendModes.clear()}},Pw.extension={type:[j.CanvasSystem],name:`canvasContext`}})),Iw,Lw=s((()=>{N(),Iw=class{constructor(){this.maxTextures=16,this.maxBatchableTextures=16,this.maxUniformBindings=0}init(){}},Iw.extension={type:[j.CanvasSystem],name:`limits`}})),Rw,zw=s((()=>{Ar(),q(),B(),mc(),Rw=class{init(e,t){this._renderer=e,this._renderTargetSystem=t}initGpuRenderTarget(e){let t=e.colorTexture,{canvas:n,context:r}=this._ensureCanvas(t);return{canvas:n,context:r,width:n.width,height:n.height}}resizeGpuRenderTarget(e){let t=e.colorTexture,{canvas:n}=this._ensureCanvas(t);n.width=e.pixelWidth,n.height=e.pixelHeight}startRenderPass(e,t,n,r){let i=this._renderTargetSystem.getGpuRenderTarget(e);this._renderer.canvasContext.activeContext=i.context,this._renderer.canvasContext.activeResolution=e.resolution,t&&this.clear(e,t,n,r)}clear(e,t,n,r){let i=this._renderTargetSystem.getGpuRenderTarget(e).context,a=r||{x:0,y:0,width:e.pixelWidth,height:e.pixelHeight};if(i.setTransform(1,0,0,1,0,0),i.clearRect(a.x,a.y,a.width,a.height),n){let e=P.shared.setValue(n);e.alpha>0&&(i.globalAlpha=e.alpha,i.fillStyle=e.toHex(),i.fillRect(a.x,a.y,a.width,a.height),i.globalAlpha=1)}}finishRenderPass(){}copyToTexture(e,t,n,r,i){let a=this._renderTargetSystem.getGpuRenderTarget(e).canvas,o=t.source,{context:s}=this._ensureCanvas(o),c=i?.x??0,l=i?.y??0;return s.drawImage(a,n.x,n.y,r.width,r.height,c,l,r.width,r.height),o.update(),t}copyDepthTexture(e,t,n,r,i){z(`[CanvasRenderTargetAdaptor] copyDepthTexture is not supported in the canvas renderer`)}destroyGpuRenderTarget(e){}_ensureCanvas(e){let t=e.resource;(!t||!pc.test(t))&&(t=K.get().createCanvas(e.pixelWidth,e.pixelHeight),e.resource=t),(t.width!==e.pixelWidth||t.height!==e.pixelHeight)&&(t.width=e.pixelWidth,t.height=e.pixelHeight);let n=t.getContext(`2d`);return{canvas:t,context:n}}}})),Bw,Vw=s((()=>{N(),N_(),zw(),Bw=class extends M_{constructor(e){super(e),this.adaptor=new Rw,this.adaptor.init(e,this)}},Bw.extension={type:[j.CanvasSystem],name:`renderTarget`}})),Hw,Uw=s((()=>{q(),N(),Fc(),Hw=class{constructor(e){}init(){}initSource(e){}generateCanvas(e){let t=K.get().createCanvas(),n=t.getContext(`2d`),r=Y.getCanvasSource(e);if(!r)return t;let i=e.frame,a=e.source._resolution??e.source.resolution??1,o=i.x*a,s=i.y*a,c=i.width*a,l=i.height*a;return t.width=Math.ceil(c),t.height=Math.ceil(l),n.drawImage(r,o,s,c,l,0,0,c,l),t}getPixels(e){let t=this.generateCanvas(e);return{pixels:t.getContext(`2d`,{willReadFrequently:!0}).getImageData(0,0,t.width,t.height).data,width:t.width,height:t.height}}destroy(){}},Hw.extension={type:[j.CanvasSystem],name:`texture`}})),Ww=l({CanvasRenderer:()=>Zw}),Gw,Kw,qw,Jw,Yw,Xw,Zw,Qw=s((()=>{N(),Wp(),Xp(),SS(),fm(),TS(),oh(),vh(),DS(),kw(),Oh(),Tf(),xg(),uu(),Fw(),Lw(),Vw(),Uw(),Gw=[...yg,Pw,Iw,Hw,Bw],Kw=[Dh,ah,dm,Yp,_h,Ow,ES,Up],qw=[wS,xS],Jw=[],Yw=[],Xw=[],M.handleByNamedList(j.CanvasSystem,Jw),M.handleByNamedList(j.CanvasPipes,Yw),M.handleByNamedList(j.CanvasPipesAdaptor,Xw),M.add(...Gw,...Kw,...qw),Zw=class extends wf{constructor(){let e={name:`canvas`,type:lu.CANVAS,systems:Jw,renderPipes:Yw,renderPipeAdaptors:Xw};super(e)}}}));Tf();var $w=[`webgl`,`webgpu`,`canvas`];async function eT(e){let t=[];e.preference?Array.isArray(e.preference)?t=e.preference.slice():(t.push(e.preference),$w.forEach(n=>{n!==e.preference&&t.push(n)})):t=$w.slice();let n,r={};for(let i=0;i<t.length;i++){let a=t[i];if(a===`webgpu`&&await kf()){let{WebGPURenderer:t}=await Promise.resolve().then(()=>(Sv(),mv));n=t,r={...e,...e.webgpu};break}if(a===`webgl`&&Df(e.failIfMajorPerformanceCaveat??wf.defaultOptions.failIfMajorPerformanceCaveat)){let{WebGLRenderer:t}=await Promise.resolve().then(()=>(cx(),ex));n=t,r={...e,...e.webgl};break}if(a===`canvas`){let{CanvasRenderer:t}=await Promise.resolve().then(()=>(Qw(),Ww));n=t,r={...e,...e.canvasOptions};break}}if(delete r.webgpu,delete r.webgl,delete r.canvasOptions,!n)throw Error(`No available renderer for the current environment`);let i=new n;return await i.init(r),i}N();var tT=class{static init(e){Object.defineProperty(this,"resizeTo",{configurable:!0,set(e){globalThis.removeEventListener(`resize`,this.queueResize),this._resizeTo=e,e&&(globalThis.addEventListener(`resize`,this.queueResize),this.resize())},get(){return this._resizeTo}}),this.queueResize=()=>{this._resizeTo&&(this._cancelResize(),this._resizeId=requestAnimationFrame(()=>this.resize()))},this._cancelResize=()=>{this._resizeId&&=(cancelAnimationFrame(this._resizeId),null)},this.resize=()=>{if(!this._resizeTo)return;this._cancelResize();let e,t;if(this._resizeTo===globalThis.window)e=globalThis.innerWidth,t=globalThis.innerHeight;else{let{clientWidth:n,clientHeight:r}=this._resizeTo;e=n,t=r}this.renderer.resize(e,t),this.render()},this._resizeId=null,this._resizeTo=null,this.resizeTo=e.resizeTo||null}static destroy(){globalThis.removeEventListener(`resize`,this.queueResize),this._cancelResize(),this._cancelResize=null,this.queueResize=null,this.resizeTo=null,this.resize=null}};tT.extension=j.Application,N(),Qa(),ro();var nT=class{static init(e){e=Object.assign({autoStart:!0,sharedTicker:!1},e),Object.defineProperty(this,"ticker",{configurable:!0,set(e){this._ticker&&this._ticker.remove(this.render,this),this._ticker=e,e&&e.add(this.render,this,Za.LOW)},get(){return this._ticker}}),this.stop=()=>{this._ticker.stop()},this.start=()=>{this._ticker.start()},this._ticker=null,this.ticker=e.sharedTicker?no.shared:new no,e.autoStart&&this.start()}static destroy(){if(this._ticker){let e=this._ticker;this.ticker=null,e.destroy()}}};nT.extension=j.Application,N(),M.add(tT),M.add(nT),N(),Xa(),_m(),Xr();var rT=class e{constructor(...e){this.stage=new G,e[0]!==void 0&&R(L,`Application constructor options are deprecated, please use Application.init() instead.`)}async init(t){t={...t},this.stage||=new G,this.renderer=await eT(t),e._plugins.forEach(e=>{e.init.call(this,t)})}render(){this.renderer.render({container:this.stage})}get canvas(){return this.renderer.canvas}get view(){return R(L,`Application.view is deprecated, please use Application.canvas instead.`),this.renderer.canvas}get screen(){return this.renderer.screen}get domContainerRoot(){return this.renderer.renderPipes.dom?._domElement}destroy(t=!1,n=!1){let r=e._plugins.slice(0);r.reverse(),r.forEach(e=>{e.destroy.call(this)}),this.stage.destroy(n),this.stage=null,this.renderer.destroy(t),this.renderer=null}};rT._plugins=[];var iT=rT;M.handleByList(j.Application,iT._plugins),M.add(hm);var aT={test(e){return typeof e==`string`&&e.startsWith(`info face=`)},parse(e){let t=e.match(/^[a-z]+\s+.+$/gm),n={info:[],common:[],page:[],char:[],chars:[],kerning:[],kernings:[],distanceField:[]};for(let e in t){let r=t[e].match(/^[a-z]+/gm)[0],i=t[e].match(/[a-zA-Z]+=([^\s"']+|"([^"]*)")/gm),a={};for(let e in i){let t=i[e].split(`=`),n=t[0],r=t[1].replace(/"/gm,``),o=parseFloat(r);a[n]=isNaN(o)?r:o}n[r].push(a)}let r={chars:{},pages:[],lineHeight:0,fontSize:0,fontFamily:``,distanceField:null,baseLineOffset:0},[i]=n.info,[a]=n.common,[o]=n.distanceField??[];o&&(r.distanceField={range:parseInt(o.distanceRange,10),type:o.fieldType}),r.fontSize=parseInt(i.size,10),r.fontFamily=i.face,r.lineHeight=parseInt(a.lineHeight,10);let s=n.page;for(let e=0;e<s.length;e++)r.pages.push({id:parseInt(s[e].id,10)||0,file:s[e].file});let c={};r.baseLineOffset=a.base===void 0?0:r.lineHeight-parseInt(a.base,10);let l=n.char;for(let e=0;e<l.length;e++){let t=l[e],n=parseInt(t.id,10),i=t.letter??t.char??String.fromCharCode(n);i===`space`&&(i=` `),c[n]=i,r.chars[i]={id:n,page:parseInt(t.page,10)||0,x:parseInt(t.x,10),y:parseInt(t.y,10),width:parseInt(t.width,10),height:parseInt(t.height,10),xOffset:parseInt(t.xoffset,10),yOffset:parseInt(t.yoffset,10),xAdvance:parseInt(t.xadvance,10),kerning:{}}}let u=n.kerning||[];for(let e=0;e<u.length;e++){let t=parseInt(u[e].first,10),n=parseInt(u[e].second,10),i=parseInt(u[e].amount,10);r.chars[c[n]]&&(r.chars[c[n]].kerning[c[t]]=i)}return r}},oT={test(e){let t=e;return typeof t!=`string`&&`getElementsByTagName`in t&&t.getElementsByTagName(`page`).length&&t.getElementsByTagName(`info`)[0].getAttribute(`face`)!==null},parse(e){let t={chars:{},pages:[],lineHeight:0,fontSize:0,fontFamily:``,distanceField:null,baseLineOffset:0},n=e.getElementsByTagName(`info`)[0],r=e.getElementsByTagName(`common`)[0],i=e.getElementsByTagName(`distanceField`)[0];i&&(t.distanceField={type:i.getAttribute(`fieldType`),range:parseInt(i.getAttribute(`distanceRange`),10)});let a=e.getElementsByTagName(`page`),o=e.getElementsByTagName(`char`),s=e.getElementsByTagName(`kerning`);t.fontSize=parseInt(n.getAttribute(`size`),10),t.fontFamily=n.getAttribute(`face`),t.lineHeight=parseInt(r.getAttribute(`lineHeight`),10);for(let e=0;e<a.length;e++)t.pages.push({id:parseInt(a[e].getAttribute(`id`),10)||0,file:a[e].getAttribute(`file`)});let c={},l=r.getAttribute(`base`);t.baseLineOffset=l===null?0:t.lineHeight-parseInt(l,10);for(let e=0;e<o.length;e++){let n=o[e],r=parseInt(n.getAttribute(`id`),10),i=n.getAttribute(`letter`)??n.getAttribute(`char`)??String.fromCharCode(r);i===`space`&&(i=` `),c[r]=i,t.chars[i]={id:r,page:parseInt(n.getAttribute(`page`),10)||0,x:parseInt(n.getAttribute(`x`),10),y:parseInt(n.getAttribute(`y`),10),width:parseInt(n.getAttribute(`width`),10),height:parseInt(n.getAttribute(`height`),10),xOffset:parseInt(n.getAttribute(`xoffset`),10),yOffset:parseInt(n.getAttribute(`yoffset`),10),xAdvance:parseInt(n.getAttribute(`xadvance`),10),kerning:{}}}for(let e=0;e<s.length;e++){let n=parseInt(s[e].getAttribute(`first`),10),r=parseInt(s[e].getAttribute(`second`),10),i=parseInt(s[e].getAttribute(`amount`),10);t.chars[c[r]]&&(t.chars[c[r]].kerning[c[n]]=i)}return t}};q();var sT={test(e){return typeof e==`string`&&e.match(/<font(\s|>)/)?oT.test(K.get().parseXML(e)):!1},parse(e){return oT.parse(K.get().parseXML(e))}},cT,lT=s((()=>{Xn(),Xr(),cT=class extends Yn{constructor(){super(...arguments),this.chars=Object.create(null),this.lineHeight=0,this.fontFamily=``,this.fontMetrics={fontSize:0,ascent:0,descent:0},this.baseLineOffset=0,this.distanceField={type:`none`,range:0},this.pages=[],this.applyFillAsTint=!0,this.baseMeasurementFontSize=100,this.baseRenderedFontSize=100}get font(){return R(L,`BitmapFont.font is deprecated, please use BitmapFont.fontFamily instead.`),this.fontFamily}get pageTextures(){return R(L,`BitmapFont.pageTextures is deprecated, please use BitmapFont.pages instead.`),this.pages}get size(){return R(L,`BitmapFont.size is deprecated, please use BitmapFont.fontMetrics.fontSize instead.`),this.fontMetrics.fontSize}get distanceFieldRange(){return R(L,`BitmapFont.distanceFieldRange is deprecated, please use BitmapFont.distanceField.range instead.`),this.distanceField.range}get distanceFieldType(){return R(L,`BitmapFont.distanceFieldType is deprecated, please use BitmapFont.distanceField.type instead.`),this.distanceField.type}destroy(e=!1){this.emit(`destroy`,this),this.removeAllListeners();for(let e in this.chars)this.chars[e].texture?.destroy();this.chars=null,e&&(this.pages.forEach(e=>e.texture.destroy(!0)),this.pages=null)}}}));function uT(e=1e3,t=0,n=!1){if(isNaN(e)||e<0)throw TypeError(`Invalid max value`);if(isNaN(t)||t<0)throw TypeError(`Invalid ttl value`);if(typeof n!=`boolean`)throw TypeError(`Invalid resetTtl value`);return new dT(e,t,n)}var dT,fT=s((()=>{dT=class{constructor(e=0,t=0,n=!1){this.first=null,this.items=Object.create(null),this.last=null,this.max=e,this.resetTtl=n,this.size=0,this.ttl=t}clear(){return this.first=null,this.items=Object.create(null),this.last=null,this.size=0,this}delete(e){if(this.has(e)){let t=this.items[e];delete this.items[e],this.size--,t.prev!==null&&(t.prev.next=t.next),t.next!==null&&(t.next.prev=t.prev),this.first===t&&(this.first=t.next),this.last===t&&(this.last=t.prev)}return this}entries(e=this.keys()){let t=Array(e.length);for(let n=0;n<e.length;n++){let r=e[n];t[n]=[r,this.get(r)]}return t}evict(e=!1){if(e||this.size>0){let e=this.first;delete this.items[e.key],--this.size===0?(this.first=null,this.last=null):(this.first=e.next,this.first.prev=null)}return this}expiresAt(e){let t;return this.has(e)&&(t=this.items[e].expiry),t}get(e){let t=this.items[e];if(t!==void 0){if(this.ttl>0&&t.expiry<=Date.now()){this.delete(e);return}return this.moveToEnd(t),t.value}}has(e){return e in this.items}moveToEnd(e){this.last!==e&&(e.prev!==null&&(e.prev.next=e.next),e.next!==null&&(e.next.prev=e.prev),this.first===e&&(this.first=e.next),e.prev=this.last,e.next=null,this.last!==null&&(this.last.next=e),this.last=e,this.first===null&&(this.first=e))}keys(){let e=Array(this.size),t=this.first,n=0;for(;t!==null;)e[n++]=t.key,t=t.next;return e}setWithEvicted(e,t,n=this.resetTtl){let r=null;if(this.has(e))this.set(e,t,!0,n);else{this.max>0&&this.size===this.max&&(r={...this.first},this.evict(!0));let n=this.items[e]={expiry:this.ttl>0?Date.now()+this.ttl:this.ttl,key:e,prev:this.last,next:null,value:t};++this.size===1?this.first=n:this.last.next=n,this.last=n}return r}set(e,t,n=!1,r=this.resetTtl){let i=this.items[e];return n||i!==void 0?(i.value=t,n===!1&&r&&(i.expiry=this.ttl>0?Date.now()+this.ttl:this.ttl),this.moveToEnd(i)):(this.max>0&&this.size===this.max&&this.evict(!0),i=this.items[e]={expiry:this.ttl>0?Date.now()+this.ttl:this.ttl,key:e,prev:this.last,next:null,value:t},++this.size===1?this.first=i:this.last.next=i,this.last=i),this}values(e=this.keys()){let t=Array(e.length);for(let n=0;n<e.length;n++)t[n]=this.get(e[n]);return t}}}));function pT(e){return!!e.tagStyles&&Object.keys(e.tagStyles).length>0}function mT(e){return e.includes(`<`)}function hT(e,t){return e.clone().assign(t)}function gT(e,t){let n=[],r=t.tagStyles;if(!pT(t)||!mT(e))return n.push({text:e,style:t}),n;let i=[t],a=[],o=``,s=0;for(;s<e.length;){let t=e[s];if(t===`<`){let c=e.indexOf(`>`,s);if(c===-1){o+=t,s++;continue}let l=e.indexOf(`<`,s+1);if(l!==-1&&l<c){o+=t,s++;continue}let u=e.slice(s+1,c);if(u.startsWith(`/`)){let t=u.slice(1).trim();if(a.length>0&&a[a.length-1]===t){o.length>0&&(n.push({text:o,style:i[i.length-1]}),o=``),i.pop(),a.pop(),s=c+1;continue}o+=e.slice(s,c+1),s=c+1;continue}{let t=u.trim();if(r[t]){o.length>0&&(n.push({text:o,style:i[i.length-1]}),o=``);let e=i[i.length-1],l=hT(e,r[t]);i.push(l),a.push(t),s=c+1;continue}o+=e.slice(s,c+1),s=c+1;continue}}o+=t,s++}return o.length>0&&n.push({text:o,style:i[i.length-1]}),n}var _T=s((()=>{}));function vT(e){return typeof e==`string`&&OT.has(e.charCodeAt(0))}function yT(e,t){return typeof e==`string`&&AT.has(e.charCodeAt(0))}function bT(e){return typeof e==`string`&&MT.has(e.charCodeAt(0))}function xT(e){return typeof e==`string`&&PT.has(e.charCodeAt(0))}function ST(e){return e===`normal`||e===`pre-line`}function CT(e){return e===`normal`}function wT(e){if(typeof e!=`string`)return``;let t=e.length-1;for(;t>=0&&yT(e[t]);)t--;return t<e.length-1?e.slice(0,t+1):e}function TT(e){let t=[],n=[];if(typeof e!=`string`)return t;for(let r=0;r<e.length;r++){let i=e[r],a=e[r+1];if(yT(i,a)||vT(i)){n.length>0&&(t.push(n.join(``)),n.length=0),i===`\r`&&a===`
907
+ `))}var nb=s((()=>{a_(),bu(),Gg(),eb()})),rb,ib=s((()=>{N(),nb(),rb=class{constructor(e){this._cache={},this._uniformGroupSyncHash={},this._renderer=e,this.gl=null,this._cache={}}contextChange(e){this.gl=e}updateUniformGroup(e,t,n){let r=this._renderer.shader._getProgramData(t);(!e.isStatic||e._dirtyId!==r.uniformDirtyGroups[e.uid])&&(r.uniformDirtyGroups[e.uid]=e._dirtyId,this._getUniformSyncFunction(e,t)(r.uniformData,e.uniforms,this._renderer,n))}_getUniformSyncFunction(e,t){return this._uniformGroupSyncHash[e._signature]?.[t._key]||this._createUniformSyncFunction(e,t)}_createUniformSyncFunction(e,t){let n=this._uniformGroupSyncHash[e._signature]||(this._uniformGroupSyncHash[e._signature]={}),r=this._getSignature(e,t._uniformData,`u`);return this._cache[r]||(this._cache[r]=this._generateUniformsSync(e,t._uniformData)),n[t._key]=this._cache[r],n[t._key]}_generateUniformsSync(e,t){return tb(e,t)}_getSignature(e,t,n){let r=e.uniforms,i=[`${n}-`];for(let e in r)i.push(e),t[e]&&i.push(t[e].type);return i.join(`-`)}destroy(){this._renderer=null,this._cache=null}},rb.extension={type:[j.WebGLSystem],name:`uniformGroup`}}));function ab(e){let t={};if(t.normal=[e.ONE,e.ONE_MINUS_SRC_ALPHA],t.add=[e.ONE,e.ONE],t.multiply=[e.DST_COLOR,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA],t.screen=[e.ONE,e.ONE_MINUS_SRC_COLOR,e.ONE,e.ONE_MINUS_SRC_ALPHA],t.none=[0,0],t[`normal-npm`]=[e.SRC_ALPHA,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA],t[`add-npm`]=[e.SRC_ALPHA,e.ONE,e.ONE,e.ONE],t[`screen-npm`]=[e.SRC_ALPHA,e.ONE_MINUS_SRC_COLOR,e.ONE,e.ONE_MINUS_SRC_ALPHA],t.erase=[e.ZERO,e.ONE_MINUS_SRC_ALPHA],!(e instanceof K.get().getWebGLRenderingContext()))t.min=[e.ONE,e.ONE,e.ONE,e.ONE,e.MIN,e.MIN],t.max=[e.ONE,e.ONE,e.ONE,e.ONE,e.MAX,e.MAX];else{let n=e.getExtension(`EXT_blend_minmax`);n&&(t.min=[e.ONE,e.ONE,e.ONE,e.ONE,n.MIN_EXT,n.MIN_EXT],t.max=[e.ONE,e.ONE,e.ONE,e.ONE,n.MAX_EXT,n.MAX_EXT])}return t}var ob=s((()=>{q()})),sb,cb,lb,ub,db,fb,pb,mb,hb=s((()=>{N(),Nu(),ob(),{BLEND:sb,OFFSET:cb,CULLING:lb,DEPTH_TEST:ub,WINDING:db,DEPTH_MASK:fb}=wu,pb=class e{constructor(e){this._invertFrontFace=!1,this.gl=null,this.stateId=0,this.polygonOffset=0,this.blendMode=`none`,this._blendEq=!1,this.map=[],this.map[sb]=this.setBlend,this.map[cb]=this.setOffset,this.map[lb]=this.setCullFace,this.map[ub]=this.setDepthTest,this.map[db]=this.setFrontFace,this.map[fb]=this.setDepthMask,this.checks=[],this.defaultState=Mu.for2d(),e.renderTarget.onRenderTargetChange.add(this)}onRenderTargetChange(e){this._invertFrontFace=!e.isRoot!=!!e.flipY,this._cullFace?this.setFrontFace(this._frontFace):this._frontFaceDirty=!0}contextChange(e){this.gl=e,this.blendModesMap=ab(e),this.resetState()}set(e){if(e||=this.defaultState,this.stateId!==e.data){let t=this.stateId^e.data,n=0;for(;t;)t&1&&this.map[n].call(this,!!(e.data&1<<n)),t>>=1,n++;this.stateId=e.data}for(let t=0;t<this.checks.length;t++)this.checks[t](this,e)}forceState(e){e||=this.defaultState;for(let t=0;t<this.map.length;t++)this.map[t].call(this,!!(e.data&1<<t));for(let t=0;t<this.checks.length;t++)this.checks[t](this,e);this.stateId=e.data}setBlend(t){this._updateCheck(e._checkBlendMode,t),this.gl[t?`enable`:`disable`](this.gl.BLEND)}setOffset(t){this._updateCheck(e._checkPolygonOffset,t),this.gl[t?`enable`:`disable`](this.gl.POLYGON_OFFSET_FILL)}setDepthTest(e){this.gl[e?`enable`:`disable`](this.gl.DEPTH_TEST)}setDepthMask(e){this.gl.depthMask(e)}get depthMaskEnabled(){return!!(this.stateId&1<<fb)}setCullFace(e){this._cullFace=e,this.gl[e?`enable`:`disable`](this.gl.CULL_FACE),this._cullFace&&this._frontFaceDirty&&this.setFrontFace(this._frontFace)}setFrontFace(e){this._frontFace=e,this._frontFaceDirty=!1;let t=this._invertFrontFace?!e:e;this._glFrontFace!==t&&(this._glFrontFace=t,this.gl.frontFace(this.gl[t?`CW`:`CCW`]))}setBlendMode(e){if(this.blendModesMap[e]||(e=`normal`),e===this.blendMode)return;this.blendMode=e;let t=this.blendModesMap[e],n=this.gl;t.length===2?n.blendFunc(t[0],t[1]):n.blendFuncSeparate(t[0],t[1],t[2],t[3]),t.length===6?(this._blendEq=!0,n.blendEquationSeparate(t[4],t[5])):this._blendEq&&(this._blendEq=!1,n.blendEquationSeparate(n.FUNC_ADD,n.FUNC_ADD))}setPolygonOffset(e,t){this.gl.polygonOffset(e,t)}resetState(){this._glFrontFace=!1,this._frontFace=!1,this._cullFace=!1,this._frontFaceDirty=!1,this._invertFrontFace=!1,this.gl.frontFace(this.gl.CCW),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!1),this.forceState(this.defaultState),this._blendEq=!0,this.blendMode=``,this.setBlendMode(`normal`)}_updateCheck(e,t){let n=this.checks.indexOf(e);t&&n===-1?this.checks.push(e):!t&&n!==-1&&this.checks.splice(n,1)}static _checkBlendMode(e,t){e.setBlendMode(t.blendMode)}static _checkPolygonOffset(e,t){e.setPolygonOffset(1,t.polygonOffset)}destroy(){this.gl=null,this.checks.length=0}},pb.extension={type:[j.WebGLSystem],name:`state`},mb=pb})),gb,_b=s((()=>{Bv(),gb=class{constructor(e){this.target=zv.TEXTURE_2D,this._layerInitMask=0,this.texture=e,this.width=-1,this.height=-1,this.type=Z.UNSIGNED_BYTE,this.internalFormat=Rv.RGBA,this.format=Rv.RGBA,this.samplerType=0}destroy(){}}})),vb,yb=s((()=>{vb={id:`buffer`,upload(e,t,n,r,i,a=!1){let o=i||t.target;!a&&t.width===e.width&&t.height===e.height?n.texSubImage2D(o,0,0,0,e.width,e.height,t.format,t.type,e.resource):n.texImage2D(o,0,t.internalFormat,e.width,e.height,0,t.format,t.type,e.resource),t.width=e.width,t.height=e.height}}})),bb,xb,Sb=s((()=>{bb={"bc1-rgba-unorm":!0,"bc1-rgba-unorm-srgb":!0,"bc2-rgba-unorm":!0,"bc2-rgba-unorm-srgb":!0,"bc3-rgba-unorm":!0,"bc3-rgba-unorm-srgb":!0,"bc4-r-unorm":!0,"bc4-r-snorm":!0,"bc5-rg-unorm":!0,"bc5-rg-snorm":!0,"bc6h-rgb-ufloat":!0,"bc6h-rgb-float":!0,"bc7-rgba-unorm":!0,"bc7-rgba-unorm-srgb":!0,"etc2-rgb8unorm":!0,"etc2-rgb8unorm-srgb":!0,"etc2-rgb8a1unorm":!0,"etc2-rgb8a1unorm-srgb":!0,"etc2-rgba8unorm":!0,"etc2-rgba8unorm-srgb":!0,"eac-r11unorm":!0,"eac-r11snorm":!0,"eac-rg11unorm":!0,"eac-rg11snorm":!0,"astc-4x4-unorm":!0,"astc-4x4-unorm-srgb":!0,"astc-5x4-unorm":!0,"astc-5x4-unorm-srgb":!0,"astc-5x5-unorm":!0,"astc-5x5-unorm-srgb":!0,"astc-6x5-unorm":!0,"astc-6x5-unorm-srgb":!0,"astc-6x6-unorm":!0,"astc-6x6-unorm-srgb":!0,"astc-8x5-unorm":!0,"astc-8x5-unorm-srgb":!0,"astc-8x6-unorm":!0,"astc-8x6-unorm-srgb":!0,"astc-8x8-unorm":!0,"astc-8x8-unorm-srgb":!0,"astc-10x5-unorm":!0,"astc-10x5-unorm-srgb":!0,"astc-10x6-unorm":!0,"astc-10x6-unorm-srgb":!0,"astc-10x8-unorm":!0,"astc-10x8-unorm-srgb":!0,"astc-10x10-unorm":!0,"astc-10x10-unorm-srgb":!0,"astc-12x10-unorm":!0,"astc-12x10-unorm-srgb":!0,"astc-12x12-unorm":!0,"astc-12x12-unorm-srgb":!0},xb={id:`compressed`,upload(e,t,n,r,i,a){let o=i??t.target;n.pixelStorei(n.UNPACK_ALIGNMENT,4);let s=e.pixelWidth,c=e.pixelHeight,l=!!bb[e.format];for(let r=0;r<e.resource.length;r++){let i=e.resource[r];l?n.compressedTexImage2D(o,r,t.internalFormat,s,c,0,i):n.texImage2D(o,r,t.internalFormat,s,c,0,t.format,t.type,i),s=Math.max(s>>1,1),c=Math.max(c>>1,1)}}}}));function Cb(e){return{id:`cube`,upload(t,n,r,i){let a=t.faces;for(let t=0;t<wb.length;t++){let o=a[wb[t]];o.resource&&((e[o.uploadMethodId]||e.image).upload(o,n,r,i,zv.TEXTURE_CUBE_MAP_POSITIVE_X+t,!(n._layerInitMask&1<<t)),n._layerInitMask|=1<<t)}n.width=t.pixelWidth,n.height=t.pixelHeight}}}var wb,Tb=s((()=>{Bv(),wb=[`right`,`left`,`top`,`bottom`,`front`,`back`]}));function Eb(e,t,n,r,i,a,o,s,c,l){if(!l){c&&e.texImage2D(t,0,n.internalFormat,r,i,0,n.format,n.type,null),e.texSubImage2D(t,0,0,0,a,o,n.format,n.type,s);return}if(!c){e.texSubImage2D(t,0,0,0,n.format,n.type,s);return}e.texImage2D(t,0,n.internalFormat,r,i,0,n.format,n.type,s)}function Db(e,t,n,r,i,a,o,s,c,l){if(!l){c&&e.texImage2D(t,0,n.internalFormat,r,i,0,n.format,n.type,null),e.texSubImage2D(t,0,0,0,n.format,n.type,s);return}if(!c){e.texSubImage2D(t,0,0,0,n.format,n.type,s);return}e.texImage2D(t,0,n.internalFormat,n.format,n.type,s)}var Ob,kb=s((()=>{Ob={id:`image`,upload(e,t,n,r,i,a=!1){let o=i||t.target,s=e.pixelWidth,c=e.pixelHeight,l=e.resourceWidth,u=e.resourceHeight,d=r===2,f=a||t.width!==s||t.height!==c,p=l>=s&&u>=c,m=e.resource;(d?Eb:Db)(n,o,t,s,c,l,u,m,f,p),t.width=s,t.height=c}}}));function Ab(){let{userAgent:e}=K.get().getNavigator();return/^((?!chrome|android).)*safari/i.test(e)}var jb=s((()=>{q()})),Mb,Nb,Pb=s((()=>{jb(),kb(),Mb=Ab(),Nb={id:`video`,upload(e,t,n,r,i,a=Mb){if(!e.isValid){let e=i??t.target;n.texImage2D(e,0,t.internalFormat,1,1,0,t.format,t.type,null);return}Ob.upload(e,t,n,r,i,a)}}})),Fb,Ib,Lb,Rb,zb=s((()=>{Fb={linear:9729,nearest:9728},Ib={linear:{linear:9987,nearest:9985},nearest:{linear:9986,nearest:9984}},Lb={"clamp-to-edge":33071,repeat:10497,"mirror-repeat":33648},Rb={never:512,less:513,equal:514,"less-equal":515,greater:516,"not-equal":517,"greater-equal":518,always:519}}));function Bb(e,t,n,r,i,a,o,s){let c=a;if(!s||e.addressModeU!==`repeat`||e.addressModeV!==`repeat`||e.addressModeW!==`repeat`){let n=Lb[o?`clamp-to-edge`:e.addressModeU],r=Lb[o?`clamp-to-edge`:e.addressModeV],a=Lb[o?`clamp-to-edge`:e.addressModeW];t[i](c,t.TEXTURE_WRAP_S,n),t[i](c,t.TEXTURE_WRAP_T,r),t.TEXTURE_WRAP_R&&t[i](c,t.TEXTURE_WRAP_R,a)}if((!s||e.magFilter!==`linear`)&&t[i](c,t.TEXTURE_MAG_FILTER,Fb[e.magFilter]),n){if(!s||e.mipmapFilter!==`linear`){let n=Ib[e.minFilter][e.mipmapFilter];t[i](c,t.TEXTURE_MIN_FILTER,n)}}else t[i](c,t.TEXTURE_MIN_FILTER,Fb[e.minFilter]);if(r&&e.maxAnisotropy>1){let n=Math.min(e.maxAnisotropy,t.getParameter(r.MAX_TEXTURE_MAX_ANISOTROPY_EXT));t[i](c,r.TEXTURE_MAX_ANISOTROPY_EXT,n)}e.compare?(t[i](c,t.TEXTURE_COMPARE_FUNC,Rb[e.compare]),t[i](c,t.TEXTURE_COMPARE_MODE,t.COMPARE_REF_TO_TEXTURE)):s||t[i](c,t.TEXTURE_COMPARE_MODE,t.NONE)}var Vb=s((()=>{zb()}));function Hb(e){return{r8unorm:e.RED,r8snorm:e.RED,r8uint:e.RED,r8sint:e.RED,r16uint:e.RED,r16sint:e.RED,r16float:e.RED,rg8unorm:e.RG,rg8snorm:e.RG,rg8uint:e.RG,rg8sint:e.RG,r32uint:e.RED,r32sint:e.RED,r32float:e.RED,rg16uint:e.RG,rg16sint:e.RG,rg16float:e.RG,rgba8unorm:e.RGBA,"rgba8unorm-srgb":e.RGBA,rgba8snorm:e.RGBA,rgba8uint:e.RGBA,rgba8sint:e.RGBA,bgra8unorm:e.RGBA,"bgra8unorm-srgb":e.RGBA,rgb9e5ufloat:e.RGB,rgb10a2unorm:e.RGBA,rg11b10ufloat:e.RGB,rg32uint:e.RG,rg32sint:e.RG,rg32float:e.RG,rgba16uint:e.RGBA,rgba16sint:e.RGBA,rgba16float:e.RGBA,rgba32uint:e.RGBA,rgba32sint:e.RGBA,rgba32float:e.RGBA,stencil8:e.STENCIL_INDEX8,depth16unorm:e.DEPTH_COMPONENT,depth24plus:e.DEPTH_COMPONENT,"depth24plus-stencil8":e.DEPTH_STENCIL,depth32float:e.DEPTH_COMPONENT,"depth32float-stencil8":e.DEPTH_STENCIL}}var Ub=s((()=>{}));function Wb(e,t){let n={},r=e.RGBA;return e instanceof K.get().getWebGLRenderingContext()?t.srgb&&(n={"rgba8unorm-srgb":t.srgb.SRGB8_ALPHA8_EXT,"bgra8unorm-srgb":t.srgb.SRGB8_ALPHA8_EXT}):(n={"rgba8unorm-srgb":e.SRGB8_ALPHA8,"bgra8unorm-srgb":e.SRGB8_ALPHA8},r=e.RGBA8),{r8unorm:e.R8,r8snorm:e.R8_SNORM,r8uint:e.R8UI,r8sint:e.R8I,r16uint:e.R16UI,r16sint:e.R16I,r16float:e.R16F,rg8unorm:e.RG8,rg8snorm:e.RG8_SNORM,rg8uint:e.RG8UI,rg8sint:e.RG8I,r32uint:e.R32UI,r32sint:e.R32I,r32float:e.R32F,rg16uint:e.RG16UI,rg16sint:e.RG16I,rg16float:e.RG16F,rgba8unorm:e.RGBA,...n,rgba8snorm:e.RGBA8_SNORM,rgba8uint:e.RGBA8UI,rgba8sint:e.RGBA8I,bgra8unorm:r,rgb9e5ufloat:e.RGB9_E5,rgb10a2unorm:e.RGB10_A2,rg11b10ufloat:e.R11F_G11F_B10F,rg32uint:e.RG32UI,rg32sint:e.RG32I,rg32float:e.RG32F,rgba16uint:e.RGBA16UI,rgba16sint:e.RGBA16I,rgba16float:e.RGBA16F,rgba32uint:e.RGBA32UI,rgba32sint:e.RGBA32I,rgba32float:e.RGBA32F,stencil8:e.STENCIL_INDEX8,depth16unorm:e.DEPTH_COMPONENT16,depth24plus:e.DEPTH_COMPONENT24,"depth24plus-stencil8":e.DEPTH24_STENCIL8,depth32float:e.DEPTH_COMPONENT32F,"depth32float-stencil8":e.DEPTH32F_STENCIL8,...t.s3tc?{"bc1-rgba-unorm":t.s3tc.COMPRESSED_RGBA_S3TC_DXT1_EXT,"bc2-rgba-unorm":t.s3tc.COMPRESSED_RGBA_S3TC_DXT3_EXT,"bc3-rgba-unorm":t.s3tc.COMPRESSED_RGBA_S3TC_DXT5_EXT}:{},...t.s3tc_sRGB?{"bc1-rgba-unorm-srgb":t.s3tc_sRGB.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT,"bc2-rgba-unorm-srgb":t.s3tc_sRGB.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT,"bc3-rgba-unorm-srgb":t.s3tc_sRGB.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}:{},...t.rgtc?{"bc4-r-unorm":t.rgtc.COMPRESSED_RED_RGTC1_EXT,"bc4-r-snorm":t.rgtc.COMPRESSED_SIGNED_RED_RGTC1_EXT,"bc5-rg-unorm":t.rgtc.COMPRESSED_RED_GREEN_RGTC2_EXT,"bc5-rg-snorm":t.rgtc.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}:{},...t.bptc?{"bc6h-rgb-float":t.bptc.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT,"bc6h-rgb-ufloat":t.bptc.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT,"bc7-rgba-unorm":t.bptc.COMPRESSED_RGBA_BPTC_UNORM_EXT,"bc7-rgba-unorm-srgb":t.bptc.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT}:{},...t.etc?{"etc2-rgb8unorm":t.etc.COMPRESSED_RGB8_ETC2,"etc2-rgb8unorm-srgb":t.etc.COMPRESSED_SRGB8_ETC2,"etc2-rgb8a1unorm":t.etc.COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2,"etc2-rgb8a1unorm-srgb":t.etc.COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2,"etc2-rgba8unorm":t.etc.COMPRESSED_RGBA8_ETC2_EAC,"etc2-rgba8unorm-srgb":t.etc.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC,"eac-r11unorm":t.etc.COMPRESSED_R11_EAC,"eac-rg11unorm":t.etc.COMPRESSED_SIGNED_RG11_EAC}:{},...t.astc?{"astc-4x4-unorm":t.astc.COMPRESSED_RGBA_ASTC_4x4_KHR,"astc-4x4-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR,"astc-5x4-unorm":t.astc.COMPRESSED_RGBA_ASTC_5x4_KHR,"astc-5x4-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR,"astc-5x5-unorm":t.astc.COMPRESSED_RGBA_ASTC_5x5_KHR,"astc-5x5-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR,"astc-6x5-unorm":t.astc.COMPRESSED_RGBA_ASTC_6x5_KHR,"astc-6x5-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR,"astc-6x6-unorm":t.astc.COMPRESSED_RGBA_ASTC_6x6_KHR,"astc-6x6-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR,"astc-8x5-unorm":t.astc.COMPRESSED_RGBA_ASTC_8x5_KHR,"astc-8x5-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR,"astc-8x6-unorm":t.astc.COMPRESSED_RGBA_ASTC_8x6_KHR,"astc-8x6-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR,"astc-8x8-unorm":t.astc.COMPRESSED_RGBA_ASTC_8x8_KHR,"astc-8x8-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR,"astc-10x5-unorm":t.astc.COMPRESSED_RGBA_ASTC_10x5_KHR,"astc-10x5-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR,"astc-10x6-unorm":t.astc.COMPRESSED_RGBA_ASTC_10x6_KHR,"astc-10x6-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR,"astc-10x8-unorm":t.astc.COMPRESSED_RGBA_ASTC_10x8_KHR,"astc-10x8-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR,"astc-10x10-unorm":t.astc.COMPRESSED_RGBA_ASTC_10x10_KHR,"astc-10x10-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR,"astc-12x10-unorm":t.astc.COMPRESSED_RGBA_ASTC_12x10_KHR,"astc-12x10-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR,"astc-12x12-unorm":t.astc.COMPRESSED_RGBA_ASTC_12x12_KHR,"astc-12x12-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR}:{}}}var Gb=s((()=>{q()}));function Kb(e){return{r8unorm:e.UNSIGNED_BYTE,r8snorm:e.BYTE,r8uint:e.UNSIGNED_BYTE,r8sint:e.BYTE,r16uint:e.UNSIGNED_SHORT,r16sint:e.SHORT,r16float:e.HALF_FLOAT,rg8unorm:e.UNSIGNED_BYTE,rg8snorm:e.BYTE,rg8uint:e.UNSIGNED_BYTE,rg8sint:e.BYTE,r32uint:e.UNSIGNED_INT,r32sint:e.INT,r32float:e.FLOAT,rg16uint:e.UNSIGNED_SHORT,rg16sint:e.SHORT,rg16float:e.HALF_FLOAT,rgba8unorm:e.UNSIGNED_BYTE,"rgba8unorm-srgb":e.UNSIGNED_BYTE,rgba8snorm:e.BYTE,rgba8uint:e.UNSIGNED_BYTE,rgba8sint:e.BYTE,bgra8unorm:e.UNSIGNED_BYTE,"bgra8unorm-srgb":e.UNSIGNED_BYTE,rgb9e5ufloat:e.UNSIGNED_INT_5_9_9_9_REV,rgb10a2unorm:e.UNSIGNED_INT_2_10_10_10_REV,rg11b10ufloat:e.UNSIGNED_INT_10F_11F_11F_REV,rg32uint:e.UNSIGNED_INT,rg32sint:e.INT,rg32float:e.FLOAT,rgba16uint:e.UNSIGNED_SHORT,rgba16sint:e.SHORT,rgba16float:e.HALF_FLOAT,rgba32uint:e.UNSIGNED_INT,rgba32sint:e.INT,rgba32float:e.FLOAT,stencil8:e.UNSIGNED_BYTE,depth16unorm:e.UNSIGNED_SHORT,depth24plus:e.UNSIGNED_INT,"depth24plus-stencil8":e.UNSIGNED_INT_24_8,depth32float:e.FLOAT,"depth32float-stencil8":e.FLOAT_32_UNSIGNED_INT_24_8_REV}}var qb=s((()=>{}));function Jb(e){return{"2d":e.TEXTURE_2D,cube:e.TEXTURE_CUBE_MAP,"1d":null,"3d":e?.TEXTURE_3D||null,"2d-array":e?.TEXTURE_2D_ARRAY||null,"cube-array":e?.TEXTURE_CUBE_MAP_ARRAY||null}}var Yb=s((()=>{})),Xb,Zb,Qb,$b=s((()=>{q(),N(),Tg(),W(),_b(),yb(),Sb(),Tb(),kb(),Pb(),Vb(),Ub(),Gb(),qb(),Yb(),Xb=4,Zb=class e{constructor(t){this._glSamplers=Object.create(null),this._boundTextures=[],this._activeTextureLocation=-1,this._boundSamplers=Object.create(null),this._premultiplyAlpha=!1,this._useSeparateSamplers=!1,this._renderer=t,this._managedTextures=new wg({renderer:t,type:`resource`,onUnload:this.onSourceUnload.bind(this),name:`glTexture`});let n={image:Ob,buffer:vb,video:Nb,compressed:xb,...e.uploadExtensions};this._uploads={...n,cube:Cb(n)}}get managedTextures(){return Object.values(this._managedTextures.items)}contextChange(e){this._gl=e,this._mapFormatToInternalFormat||(this._mapFormatToInternalFormat=Wb(e,this._renderer.context.extensions),this._mapFormatToType=Kb(e),this._mapFormatToFormat=Hb(e),this._mapViewDimensionToGlTarget=Jb(e)),this._managedTextures.removeAll(!0),this._glSamplers=Object.create(null),this._boundSamplers=Object.create(null),this._premultiplyAlpha=!1;for(let e=0;e<16;e++)this.bind(U.EMPTY,e)}initSource(e){this.bind(e)}bind(e,t=0){let n=e.source;e?(this.bindSource(n,t),this._useSeparateSamplers&&this._bindSampler(n.style,t)):(this.bindSource(null,t),this._useSeparateSamplers&&this._bindSampler(null,t))}bindSource(e,t=0){let n=this._gl;if(e._gcLastUsed=this._renderer.gc.now,this._boundTextures[t]!==e){this._boundTextures[t]=e,this._activateLocation(t),e||=U.EMPTY.source;let r=this.getGlSource(e);n.bindTexture(r.target,r.texture)}}_bindSampler(e,t=0){let n=this._gl;if(!e){this._boundSamplers[t]=null,n.bindSampler(t,null);return}let r=this._getGlSampler(e);this._boundSamplers[t]!==r&&(this._boundSamplers[t]=r,n.bindSampler(t,r))}unbind(e){let t=e.source,n=this._boundTextures,r=this._gl;for(let e=0;e<n.length;e++)if(n[e]===t){this._activateLocation(e);let i=this.getGlSource(t);r.bindTexture(i.target,null),n[e]=null}}_activateLocation(e){this._activeTextureLocation!==e&&(this._activeTextureLocation=e,this._gl.activeTexture(this._gl.TEXTURE0+e))}_initSource(e){let t=this._gl,n=new gb(t.createTexture());if(n.type=this._mapFormatToType[e.format],n.internalFormat=this._mapFormatToInternalFormat[e.format],n.format=this._mapFormatToFormat[e.format],n.target=this._mapViewDimensionToGlTarget[e.viewDimension],n.target===null)throw Error(`Unsupported view dimension: ${e.viewDimension} with this webgl version: ${this._renderer.context.webGLVersion}`);if(e.autoGenerateMipmaps&&(this._renderer.context.supports.nonPowOf2mipmaps||e.isPowerOfTwo)){let t=Math.max(e.width,e.height);e.mipLevelCount=Math.floor(Math.log2(t))+1}return e._gpuData[this._renderer.uid]=n,this._managedTextures.add(e)&&(e.on(`update`,this.onSourceUpdate,this),e.on(`resize`,this.onSourceUpdate,this),e.on(`styleChange`,this.onStyleChange,this),e.on(`updateMipmaps`,this.onUpdateMipmaps,this)),this.onSourceUpdate(e),this.updateStyle(e,!1),n}onStyleChange(e){this.updateStyle(e,!1)}updateStyle(e,t){let n=this._gl,r=this.getGlSource(e);n.bindTexture(r.target,r.texture),this._boundTextures[this._activeTextureLocation]=e,Bb(e.style,n,e.mipLevelCount>1,this._renderer.context.extensions.anisotropicFiltering,`texParameteri`,r.target,!this._renderer.context.supports.nonPowOf2wrapping&&!e.isPowerOfTwo,t)}onSourceUnload(e,t=!1){let n=e._gpuData[this._renderer.uid];n&&(t||(this.unbind(e),this._gl.deleteTexture(n.texture)),e.off(`update`,this.onSourceUpdate,this),e.off(`resize`,this.onSourceUpdate,this),e.off(`styleChange`,this.onStyleChange,this),e.off(`updateMipmaps`,this.onUpdateMipmaps,this))}onSourceUpdate(e){let t=this._gl,n=this.getGlSource(e);t.bindTexture(n.target,n.texture),this._boundTextures[this._activeTextureLocation]=e;let r=e.alphaMode===`premultiply-alpha-on-upload`;if(this._premultiplyAlpha!==r&&(this._premultiplyAlpha=r,t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,r)),this._uploads[e.uploadMethodId])this._uploads[e.uploadMethodId].upload(e,n,t,this._renderer.context.webGLVersion);else if(n.target===t.TEXTURE_2D)this._initEmptyTexture2D(n,e);else if(n.target===t.TEXTURE_2D_ARRAY)this._initEmptyTexture2DArray(n,e);else if(n.target===t.TEXTURE_CUBE_MAP)this._initEmptyTextureCube(n,e);else throw Error(`[GlTextureSystem] Unsupported texture target for empty allocation.`);this._applyMipRange(n,e),e.autoGenerateMipmaps&&e.mipLevelCount>1&&this.onUpdateMipmaps(e,!1)}onUpdateMipmaps(e,t=!0){t&&this.bindSource(e,0);let n=this.getGlSource(e);this._gl.generateMipmap(n.target)}_initEmptyTexture2D(e,t){let n=this._gl;n.texImage2D(n.TEXTURE_2D,0,e.internalFormat,t.pixelWidth,t.pixelHeight,0,e.format,e.type,null);let r=Math.max(t.pixelWidth>>1,1),i=Math.max(t.pixelHeight>>1,1);for(let a=1;a<t.mipLevelCount;a++)n.texImage2D(n.TEXTURE_2D,a,e.internalFormat,r,i,0,e.format,e.type,null),r=Math.max(r>>1,1),i=Math.max(i>>1,1)}_initEmptyTexture2DArray(e,t){if(this._renderer.context.webGLVersion!==2)throw Error(`[GlTextureSystem] TEXTURE_2D_ARRAY requires WebGL2.`);let n=this._gl,r=Math.max(t.arrayLayerCount|0,1);n.texImage3D(n.TEXTURE_2D_ARRAY,0,e.internalFormat,t.pixelWidth,t.pixelHeight,r,0,e.format,e.type,null);let i=Math.max(t.pixelWidth>>1,1),a=Math.max(t.pixelHeight>>1,1);for(let o=1;o<t.mipLevelCount;o++)n.texImage3D(n.TEXTURE_2D_ARRAY,o,e.internalFormat,i,a,r,0,e.format,e.type,null),i=Math.max(i>>1,1),a=Math.max(a>>1,1)}_initEmptyTextureCube(e,t){let n=this._gl;for(let r=0;r<6;r++)n.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+r,0,e.internalFormat,t.pixelWidth,t.pixelHeight,0,e.format,e.type,null);let r=Math.max(t.pixelWidth>>1,1),i=Math.max(t.pixelHeight>>1,1);for(let a=1;a<t.mipLevelCount;a++){for(let t=0;t<6;t++)n.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+t,a,e.internalFormat,r,i,0,e.format,e.type,null);r=Math.max(r>>1,1),i=Math.max(i>>1,1)}}_applyMipRange(e,t){if(this._renderer.context.webGLVersion!==2||t.mipLevelCount<=1)return;let n=this._gl,r=Math.max((t.mipLevelCount|0)-1,0);n.texParameteri(e.target,n.TEXTURE_BASE_LEVEL,0),n.texParameteri(e.target,n.TEXTURE_MAX_LEVEL,r)}_initSampler(e){let t=this._gl,n=this._gl.createSampler();return this._glSamplers[e._resourceId]=n,Bb(e,t,this._boundTextures[this._activeTextureLocation].mipLevelCount>1,this._renderer.context.extensions.anisotropicFiltering,`samplerParameteri`,n,!1,!0),this._glSamplers[e._resourceId]}_getGlSampler(e){return this._glSamplers[e._resourceId]||this._initSampler(e)}getGlSource(e){return e._gcLastUsed=this._renderer.gc.now,e._gpuData[this._renderer.uid]||this._initSource(e)}generateCanvas(e){let{pixels:t,width:n,height:r}=this.getPixels(e),i=K.get().createCanvas();i.width=n,i.height=r;let a=i.getContext(`2d`);if(a){let e=a.createImageData(n,r);e.data.set(t),a.putImageData(e,0,0)}return i}getPixels(e){let t=e.source.resolution,n=e.frame,r=Math.max(Math.round(n.width*t),1),i=Math.max(Math.round(n.height*t),1),a=new Uint8Array(Xb*r*i),o=this._renderer,s=o.renderTarget.getRenderTarget(e),c=o.renderTarget.getGpuRenderTarget(s),l=o.gl;return o.renderTarget.adaptor.bindFramebuffer(c.resolveTargetFramebuffer),l.readPixels(Math.round(n.x*t),Math.round(n.y*t),r,i,l.RGBA,l.UNSIGNED_BYTE,a),{pixels:new Uint8ClampedArray(a.buffer),width:r,height:i}}destroy(){this._managedTextures.destroy(),this._glSamplers=null,this._boundTextures=null,this._boundSamplers=null,this._mapFormatToInternalFormat=null,this._mapFormatToType=null,this._mapFormatToFormat=null,this._uploads=null,this._renderer=null}resetState(){this._activeTextureLocation=-1,this._boundTextures.fill(U.EMPTY.source),this._boundSamplers=Object.create(null);let e=this._gl;this._premultiplyAlpha=!1,e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this._premultiplyAlpha)}},Zb.extension={type:[j.WebGLSystem],name:`texture`},Zb.uploadExtensions=Object.create(null),Qb=Zb,M.handleByMap(j.TextureUploaderWebGL,Qb.uploadExtensions)})),ex=l({WebGLRenderer:()=>sx}),tx,nx,rx,ix,ax,ox,sx,cx=s((()=>{N(),wv(),Ev(),Ov(),Tf(),xg(),uu(),Pv(),Lv(),qv(),Zv(),$v(),ty(),ry(),ay(),my(),by(),Zy(),ib(),hb(),$b(),tx=[...yg,py,Xv,Iv,ny,Nv,Qb,yy,Kv,rb,Xy,ey,mb,iy,Qv],nx=[...bg],rx=[Dv,Tv,Cv],ix=[],ax=[],ox=[],M.handleByNamedList(j.WebGLSystem,ix),M.handleByNamedList(j.WebGLPipes,ax),M.handleByNamedList(j.WebGLPipesAdaptor,ox),M.add(...tx,...nx,...rx),sx=class extends wf{constructor(){let e={name:`webgl`,type:lu.WEBGL,systems:ix,renderPipes:ax,renderPipeAdaptors:ox};super(e)}}})),lx,ux,dx=s((()=>{lx=1e-4,ux=1e-4}));function fx(e,t,n,r,i,a,o,s){let c=e-n*i,l=t-r*i,u=e+n*a,d=t+r*a,f,p;o?(f=r,p=-n):(f=-r,p=n);let m=c+f,h=l+p,g=u+f,_=d+p;return s.push(m,h),s.push(g,_),2}function px(e,t,n,r,i,a,o,s){let c=n-e,l=r-t,u=Math.atan2(c,l),d=Math.atan2(i-e,a-t);s&&u<d?u+=Math.PI*2:!s&&u>d&&(d+=Math.PI*2);let f=u,p=d-u,m=Math.abs(p),h=Math.sqrt(c*c+l*l),g=(15*m*Math.sqrt(h)/Math.PI>>0)+1,_=p/g;if(f+=_,s){o.push(e,t),o.push(n,r);for(let n=1,r=f;n<g;n++,r+=_)o.push(e,t),o.push(e+Math.sin(r)*h,t+Math.cos(r)*h);o.push(e,t),o.push(i,a)}else{o.push(n,r),o.push(e,t);for(let n=1,r=f;n<g;n++,r+=_)o.push(e+Math.sin(r)*h,t+Math.cos(r)*h),o.push(e,t);o.push(i,a),o.push(e,t)}return g*2}function mx(e,t,n,r,i,a){let o=lx;if(e.length===0)return;let s=t,c=s.alignment;if(t.alignment!==.5){let t=zc(e);n&&(t*=-1),c=(c-.5)*t+.5}let l=new Lr(e[0],e[1]),u=new Lr(e[e.length-2],e[e.length-1]),d=r,f=Math.abs(l.x-u.x)<o&&Math.abs(l.y-u.y)<o;if(d){e=e.slice(),f&&(e.pop(),e.pop(),u.set(e[e.length-2],e[e.length-1]));let t=(l.x+u.x)*.5,n=(u.y+l.y)*.5;e.unshift(t,n),e.push(t,n)}let p=i,m=e.length/2,h=e.length,g=p.length/2,_=s.width/2,v=_*_,y=s.miterLimit*s.miterLimit,b=e[0],x=e[1],S=e[2],C=e[3],w=0,ee=0,T=-(x-C),E=b-S,te=0,D=0,ne=Math.sqrt(T*T+E*E);T/=ne,E/=ne,T*=_,E*=_;let re=c,O=(1-re)*2,k=re*2;d||(s.cap===`round`?h+=px(b-T*(O-k)*.5,x-E*(O-k)*.5,b-T*O,x-E*O,b+T*k,x+E*k,p,!0)+2:s.cap===`square`&&(h+=fx(b,x,T,E,O,k,!0,p))),p.push(b-T*O,x-E*O),p.push(b+T*k,x+E*k);for(let t=1;t<m-1;++t){b=e[(t-1)*2],x=e[(t-1)*2+1],S=e[t*2],C=e[t*2+1],w=e[(t+1)*2],ee=e[(t+1)*2+1],T=-(x-C),E=b-S,ne=Math.sqrt(T*T+E*E),T/=ne,E/=ne,T*=_,E*=_,te=-(C-ee),D=S-w,ne=Math.sqrt(te*te+D*D),te/=ne,D/=ne,te*=_,D*=_;let n=S-b,r=x-C,i=S-w,a=ee-C,o=n*i+r*a,c=r*i-a*n,l=c<0;if(Math.abs(c)<.001*Math.abs(o)){p.push(S-T*O,C-E*O),p.push(S+T*k,C+E*k),o>=0&&(s.join===`round`?h+=px(S,C,S-T*O,C-E*O,S-te*O,C-D*O,p,!1)+4:h+=2,p.push(S-te*k,C-D*k),p.push(S+te*O,C+D*O));continue}let u=(-T+b)*(-E+C)-(-T+S)*(-E+x),d=(-te+w)*(-D+C)-(-te+S)*(-D+ee),f=(n*d-i*u)/c,m=(a*u-r*d)/c,g=(f-S)*(f-S)+(m-C)*(m-C),re=S+(f-S)*O,ie=C+(m-C)*O,ae=S-(f-S)*k,oe=C-(m-C)*k,se=Math.min(n*n+r*r,i*i+a*a),ce=l?O:k;g<=se+ce*ce*v?s.join===`bevel`||g/v>y?(l?(p.push(re,ie),p.push(S+T*k,C+E*k),p.push(re,ie),p.push(S+te*k,C+D*k)):(p.push(S-T*O,C-E*O),p.push(ae,oe),p.push(S-te*O,C-D*O),p.push(ae,oe)),h+=2):s.join===`round`?l?(p.push(re,ie),p.push(S+T*k,C+E*k),h+=px(S,C,S+T*k,C+E*k,S+te*k,C+D*k,p,!0)+4,p.push(re,ie),p.push(S+te*k,C+D*k)):(p.push(S-T*O,C-E*O),p.push(ae,oe),h+=px(S,C,S-T*O,C-E*O,S-te*O,C-D*O,p,!1)+4,p.push(S-te*O,C-D*O),p.push(ae,oe)):(p.push(re,ie),p.push(ae,oe)):(p.push(S-T*O,C-E*O),p.push(S+T*k,C+E*k),s.join===`round`?h+=l?px(S,C,S+T*k,C+E*k,S+te*k,C+D*k,p,!0)+2:px(S,C,S-T*O,C-E*O,S-te*O,C-D*O,p,!1)+2:s.join===`miter`&&g/v<=y&&(l?(p.push(ae,oe),p.push(ae,oe)):(p.push(re,ie),p.push(re,ie)),h+=2),p.push(S-te*O,C-D*O),p.push(S+te*k,C+D*k),h+=2)}b=e[(m-2)*2],x=e[(m-2)*2+1],S=e[(m-1)*2],C=e[(m-1)*2+1],T=-(x-C),E=b-S,ne=Math.sqrt(T*T+E*E),T/=ne,E/=ne,T*=_,E*=_,p.push(S-T*O,C-E*O),p.push(S+T*k,C+E*k),d||(s.cap===`round`?h+=px(S-T*(O-k)*.5,C-E*(O-k)*.5,S-T*O,C-E*O,S+T*k,C+E*k,p,!1)+2:s.cap===`square`&&(h+=fx(S,C,T,E,O,k,!1,p)));let ie=ux*ux;for(let e=g;e<h+g-2;++e)b=p[e*2],x=p[e*2+1],S=p[(e+1)*2],C=p[(e+1)*2+1],w=p[(e+2)*2],ee=p[(e+2)*2+1],!(Math.abs(b*(C-ee)+S*(ee-x)+w*(x-C))<ie)&&a.push(e,e+1,e+2)}var hx=s((()=>{Bc(),zr(),dx()}));function gx(e,t){for(let n=0;n<t.length;n++){let r=t[n];e.addColorStop(r.offset,r.color)}}function _x(e,t){let n=K.get().createCanvas(e,t);return{canvas:n,context:n.getContext(`2d`)}}function vx(e){let t=e[0]??{};return(typeof t==`number`||e[1])&&(R(`8.5.2`,`use options object instead`),t={type:`linear`,start:{x:e[0],y:e[1]},end:{x:e[2],y:e[3]},textureSpace:e[4],textureSize:e[5]??xx.defaultLinearOptions.textureSize}),t}var yx,bx,xx,Sx=s((()=>{Ar(),q(),I(),gc(),W(),Kr(),Xr(),pa(),yx=[{offset:0,color:`white`},{offset:1,color:`black`}],bx=class e{constructor(...t){this.uid=Wr(`fillGradient`),this._tick=0,this.type=`linear`,this.colorStops=[];let n=vx(t);n={...n.type===`radial`?e.defaultRadialOptions:e.defaultLinearOptions,...fa(n)},this._textureSize=n.textureSize,this._wrapMode=n.wrapMode,n.type===`radial`?(this.center=n.center,this.outerCenter=n.outerCenter??this.center,this.innerRadius=n.innerRadius,this.outerRadius=n.outerRadius,this.scale=n.scale,this.rotation=n.rotation):(this.start=n.start,this.end=n.end),this.textureSpace=n.textureSpace,this.type=n.type,n.colorStops.forEach(e=>{this.addColorStop(e.offset,e.color)})}addColorStop(e,t){return this.colorStops.push({offset:e,color:P.shared.setValue(t).toHexa()}),this}buildLinearGradient(){if(this.texture)return;let{x:e,y:t}=this.start,{x:n,y:r}=this.end,i=n-e,a=r-t,o=i<0||a<0;if(this._wrapMode===`clamp-to-edge`){if(i<0){let t=e;e=n,n=t,i*=-1}if(a<0){let e=t;t=r,r=e,a*=-1}}let s=this.colorStops.length?this.colorStops:yx,c=this._textureSize,{canvas:l,context:u}=_x(c,1),d=o?u.createLinearGradient(this._textureSize,0,0,0):u.createLinearGradient(0,0,this._textureSize,0);gx(d,s),u.fillStyle=d,u.fillRect(0,0,c,1),this.texture=new U({source:new hc({resource:l,addressMode:this._wrapMode})});let f=Math.sqrt(i*i+a*a),p=Math.atan2(a,i),m=new F;m.scale(f/c,1),m.rotate(p),m.translate(e,t),this.textureSpace===`local`&&m.scale(c,c),this.transform=m}buildGradient(){this.texture||this._tick++,this.type===`linear`?this.buildLinearGradient():this.buildRadialGradient()}buildRadialGradient(){if(this.texture)return;let e=this.colorStops.length?this.colorStops:yx,t=this._textureSize,{canvas:n,context:r}=_x(t,t),{x:i,y:a}=this.center,{x:o,y:s}=this.outerCenter,c=this.innerRadius,l=this.outerRadius,u=o-l,d=s-l,f=t/(l*2),p=(i-u)*f,m=(a-d)*f,h=r.createRadialGradient(p,m,c*f,(o-u)*f,(s-d)*f,l*f);gx(h,e),r.fillStyle=e[e.length-1].color,r.fillRect(0,0,t,t),r.fillStyle=h,r.translate(p,m),r.rotate(this.rotation),r.scale(1,this.scale),r.translate(-p,-m),r.fillRect(0,0,t,t),this.texture=new U({source:new hc({resource:n,addressMode:this._wrapMode})});let g=new F;this.textureSpace===`local`?g.scale(2*l,2*l):g.scale(1/f,1/f),g.translate(u,d),this.transform=g}destroy(){this.texture?.destroy(!0),this.texture=null,this.transform=null,this.colorStops=[],this.start=null,this.end=null,this.center=null,this.outerCenter=null}get styleKey(){return`fill-gradient-${this.uid}-${this._tick}`}},bx.defaultLinearOptions={start:{x:0,y:0},end:{x:0,y:1},colorStops:[],textureSpace:`local`,type:`linear`,textureSize:256,wrapMode:`clamp-to-edge`},bx.defaultRadialOptions={center:{x:.5,y:.5},innerRadius:0,outerRadius:.5,colorStops:[],scale:1,rotation:0,textureSpace:`local`,type:`radial`,textureSize:256,wrapMode:`clamp-to-edge`},xx=bx}));function Cx(e){return e.texture!==void 0}var wx,Tx,Ex=s((()=>{I(),Kr(),wx={repeat:{addressModeU:`repeat`,addressModeV:`repeat`},"repeat-x":{addressModeU:`repeat`,addressModeV:`clamp-to-edge`},"repeat-y":{addressModeU:`clamp-to-edge`,addressModeV:`repeat`},"no-repeat":{addressModeU:`clamp-to-edge`,addressModeV:`clamp-to-edge`}},Tx=class{constructor(e,t){this.uid=Wr(`fillPattern`),this._tick=0,this.transform=new F;let n=Cx(e)?e:{texture:e,repetition:t};this.texture=n.texture,this.textureSpace=n.textureSpace??`global`;let r=n.repetition;r&&(this.texture.source.style.addressModeU=wx[r].addressModeU,this.texture.source.style.addressModeV=wx[r].addressModeV)}setTransform(e){if(e){if(this.transform.equals(e))return;this.transform.copyFrom(e)}else{if(this.transform.isIdentity())return;this.transform.identity()}this._tick++}get texture(){return this._texture}set texture(e){this._texture!==e&&(this._texture=e,this._tick++)}get styleKey(){return`fill-pattern-${this.uid}-${this._tick}`}destroy(){this.texture.destroy(!0),this.texture=null}}}));function Dx(e,t,n,r,i,a,o,s=null){let c=0;n*=t,i*=a;let l=s.a,u=s.b,d=s.c,f=s.d,p=s.tx,m=s.ty;for(;c<o;){let o=e[n],s=e[n+1];r[i]=l*o+d*s+p,r[i+1]=u*o+f*s+m,i+=a,n+=t,c++}}function Ox(e,t,n,r){let i=0;for(t*=n;i<r;)e[t]=0,e[t+1]=0,t+=n,i++}var kx=s((()=>{}));function Ax(e,t,n,r,i){let a=t.a,o=t.b,s=t.c,c=t.d,l=t.tx,u=t.ty;n||=0,r||=2,i||=e.length/r-n;let d=n*r;for(let t=0;t<i;t++){let t=e[d],n=e[d+1];e[d]=a*t+s*n+l,e[d+1]=o*t+c*n+u,d+=r}}var jx=s((()=>{})),Mx,Nx,Px=s((()=>{I(),zi(),Mx=new F,Nx=class{constructor(){this.packAsQuad=!1,this.batcherName=`default`,this.topology=`triangle-list`,this.applyTransform=!0,this.roundPixels=0,this._batcher=null,this._batch=null}get uvs(){return this.geometryData.uvs}get positions(){return this.geometryData.vertices}get indices(){return this.geometryData.indices}get blendMode(){return this.renderable&&this.applyTransform?this.renderable.groupBlendMode:`normal`}get color(){let e=this.baseColor,t=e>>16|e&65280|(e&255)<<16,n=this.renderable;return n?Ri(t,n.groupColor)+(this.alpha*n.groupAlpha*255<<24):t+(this.alpha*255<<24)}get transform(){return this.renderable?.groupTransform||Mx}copyTo(e){e.indexOffset=this.indexOffset,e.indexSize=this.indexSize,e.attributeOffset=this.attributeOffset,e.attributeSize=this.attributeSize,e.baseColor=this.baseColor,e.alpha=this.alpha,e.texture=this.texture,e.geometryData=this.geometryData,e.topology=this.topology}reset(){this.applyTransform=!0,this.renderable=null,this.topology=`triangle-list`}destroy(){this.renderable=null,this.texture=null,this.geometryData=null,this._batcher=null,this._batch=null}}})),Fx,Ix,Lx,Rx=s((()=>{N(),Fx={extension:{type:j.ShapeBuilder,name:`circle`},build(e,t){let n,r,i,a,o,s;if(e.type===`circle`){let t=e;if(o=s=t.radius,o<=0)return!1;n=t.x,r=t.y,i=a=0}else if(e.type===`ellipse`){let t=e;if(o=t.halfWidth,s=t.halfHeight,o<=0||s<=0)return!1;n=t.x,r=t.y,i=a=0}else{let t=e,c=t.width/2,l=t.height/2;n=t.x+c,r=t.y+l,o=s=Math.max(0,Math.min(t.radius,Math.min(c,l))),i=c-o,a=l-s}if(i<0||a<0)return!1;let c=Math.ceil(2.3*Math.sqrt(o+s)),l=c*8+(i?4:0)+(a?4:0);if(l===0)return!1;if(c===0)return t[0]=t[6]=n+i,t[1]=t[3]=r+a,t[2]=t[4]=n-i,t[5]=t[7]=r-a,!0;let u=0,d=c*4+(i?2:0)+2,f=d,p=l,m=i+o,h=a,g=n+m,_=n-m,v=r+h;if(t[u++]=g,t[u++]=v,t[--d]=v,t[--d]=_,a){let e=r-h;t[f++]=_,t[f++]=e,t[--p]=e,t[--p]=g}for(let e=1;e<c;e++){let l=Math.PI/2*(e/c),m=i+Math.cos(l)*o,h=a+Math.sin(l)*s,g=n+m,_=n-m,v=r+h,y=r-h;t[u++]=g,t[u++]=v,t[--d]=v,t[--d]=_,t[f++]=_,t[f++]=y,t[--p]=y,t[--p]=g}m=i,h=a+s,g=n+m,_=n-m,v=r+h;let y=r-h;return t[u++]=g,t[u++]=v,t[--p]=y,t[--p]=g,i&&(t[u++]=_,t[u++]=v,t[--p]=y,t[--p]=_),!0},triangulate(e,t,n,r,i,a){if(e.length===0)return;let o=0,s=0;for(let t=0;t<e.length;t+=2)o+=e[t],s+=e[t+1];o/=e.length/2,s/=e.length/2;let c=r;t[c*n]=o,t[c*n+1]=s;let l=c++;for(let r=0;r<e.length;r+=2)t[c*n]=e[r],t[c*n+1]=e[r+1],r>0&&(i[a++]=c,i[a++]=l,i[a++]=c-1),c++;i[a++]=l+1,i[a++]=l,i[a++]=c-1}},Ix={...Fx,extension:{...Fx.extension,name:`ellipse`}},Lx={...Fx,extension:{...Fx.extension,name:`roundedRectangle`}}}));function zx(e,t,n,r){let i=lx;if(e.length===0)return;let a=e[0],o=e[1],s=e[e.length-2],c=e[e.length-1],l=t||Math.abs(a-s)<i&&Math.abs(o-c)<i,u=n,d=e.length/2,f=u.length/2;for(let t=0;t<d;t++)u.push(e[t*2]),u.push(e[t*2+1]);for(let e=0;e<d-1;e++)r.push(f+e,f+e+1);l&&r.push(f+d-1,f)}var Bx=s((()=>{dx()}));function Vx(e,t,n,r,i,a,o){let s=gf(e,t,2);if(!s)return;for(let e=0;e<s.length;e+=3)a[o++]=s[e]+i,a[o++]=s[e+1]+i,a[o++]=s[e+2]+i;let c=i*r;for(let t=0;t<e.length;t+=2)n[c]=e[t],n[c+1]=e[t+1],c+=r}var Hx=s((()=>{_f()})),Ux,Wx,Gx=s((()=>{N(),Hx(),Ux=[],Wx={extension:{type:j.ShapeBuilder,name:`polygon`},build(e,t){for(let n=0;n<e.points.length;n++)t[n]=e.points[n];return!0},triangulate(e,t,n,r,i,a){Vx(e,Ux,t,n,r,i,a)}}})),Kx,qx=s((()=>{N(),Kx={extension:{type:j.ShapeBuilder,name:`rectangle`},build(e,t){let n=e,r=n.x,i=n.y,a=n.width,o=n.height;return a>0&&o>0&&(t[0]=r,t[1]=i,t[2]=r+a,t[3]=i,t[4]=r+a,t[5]=i+o,t[6]=r,t[7]=i+o,!0)},triangulate(e,t,n,r,i,a){let o=0;r*=n,t[r+o]=e[0],t[r+o+1]=e[1],o+=n,t[r+o]=e[2],t[r+o+1]=e[3],o+=n,t[r+o]=e[6],t[r+o+1]=e[7],o+=n,t[r+o]=e[4],t[r+o+1]=e[5],o+=n;let s=r/n;i[a++]=s,i[a++]=s+1,i[a++]=s+2,i[a++]=s+1,i[a++]=s+3,i[a++]=s+2}}})),Jx,Yx=s((()=>{N(),Jx={extension:{type:j.ShapeBuilder,name:`triangle`},build(e,t){return t[0]=e.x,t[1]=e.y,t[2]=e.x2,t[3]=e.y2,t[4]=e.x3,t[5]=e.y3,!0},triangulate(e,t,n,r,i,a){let o=0;r*=n,t[r+o]=e[0],t[r+o+1]=e[1],o+=n,t[r+o]=e[2],t[r+o+1]=e[3],o+=n,t[r+o]=e[4],t[r+o+1]=e[5];let s=r/n;i[a++]=s,i[a++]=s+1,i[a++]=s+2}}}));function Xx(e,t,n,r){let i=t.matrix?e.copyFrom(t.matrix).invert():e.identity();if(t.textureSpace===`local`){let e=n.getBounds(Qx);t.width&&e.pad(t.width);let{x:r,y:a}=e,o=1/e.width,s=1/e.height,c=-r*o,l=-a*s,u=i.a,d=i.b,f=i.c,p=i.d;i.a*=o,i.b*=o,i.c*=s,i.d*=s,i.tx=c*u+l*f+i.tx,i.ty=c*d+l*p+i.ty}else if(t.texture.rotate){let{uvs:e,orig:n}=t.texture;i.scale(1/n.width,1/n.height),i.prepend($x.set(e.x1-e.x0,e.y1-e.y0,e.x3-e.x0,e.y3-e.y0,e.x0,e.y0))}else i.translate(t.texture.frame.x,t.texture.frame.y),i.scale(1/t.texture.source.width,1/t.texture.source.height);let a=t.texture.source.style;return!(t.fill instanceof xx)&&a.addressMode===`clamp-to-edge`&&(a.addressMode=`repeat`,a.update()),r&&i.append(Zx.copyFrom(r).invert()),i}var Zx,Qx,$x,eS=s((()=>{I(),wi(),Sx(),Zx=new F,Qx=new V,$x=new F}));function tS(e,t){let{geometryData:n,batches:r}=t;r.length=0,n.indices.length=0,n.vertices.length=0,n.uvs.length=0;for(let t=0;t<e.instructions.length;t++){let i=e.instructions[t];if(i.action===`texture`)nS(i.data,r,n);else if(i.action===`fill`||i.action===`stroke`){let e=i.action===`stroke`,t=i.data.path.shapePath,a=i.data.style,o=i.data.hole;e&&o&&rS(o.shapePath,a,!0,r,n),o&&(t.shapePrimitives[t.shapePrimitives.length-1].holes=o.shapePath.shapePrimitives),rS(t,a,e,r,n)}}}function nS(e,t,n){let r=[],i=aS.rectangle,a=oS;a.x=e.dx,a.y=e.dy,a.width=e.dw,a.height=e.dh;let o=e.transform;if(!i.build(a,r))return;let{vertices:s,uvs:c,indices:l}=n,u=l.length,d=s.length/2;o&&Ax(r,o),i.triangulate(r,s,2,d,l,u);let f=e.image,p=f.uvs;c.push(p.x0,p.y0,p.x1,p.y1,p.x3,p.y3,p.x2,p.y2);let m=ii.get(Nx);m.indexOffset=u,m.indexSize=l.length-u,m.attributeOffset=d,m.attributeSize=s.length/2-d,m.baseColor=e.style,m.alpha=e.alpha,m.texture=f,m.geometryData=n,t.push(m)}function rS(e,t,n,r,i){let{vertices:a,uvs:o,indices:s}=i;e.shapePrimitives.forEach(({shape:e,transform:c,holes:l})=>{let u=[],d=aS[e.type];if(!d.build(e,u))return;let f=s.length,p=a.length/2,m=`triangle-list`;if(c&&Ax(u,c),n){let n=e.closePath??!0,r=t;r.pixelLine?(zx(u,n,a,s),m=`line-list`):mx(u,r,!1,n,a,s)}else if(l){let e=[],t=u.slice();iS(l).forEach(n=>{e.push(t.length/2),t.push(...n)}),Vx(t,e,a,2,p,s,f)}else d.triangulate(u,a,2,p,s,f);let h=o.length/2,g=t.texture;if(g!==U.WHITE){let n=Xx(sS,t,e,c);Dx(a,2,p,o,h,2,a.length/2-p,n)}else Ox(o,h,2,a.length/2-p);let _=ii.get(Nx);_.indexOffset=f,_.indexSize=s.length-f,_.attributeOffset=p,_.attributeSize=a.length/2-p,_.baseColor=t.color,_.alpha=t.alpha,_.texture=g,_.geometryData=i,_.topology=m,r.push(_)})}function iS(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n].shape,i=[];aS[r.type].build(r,i)&&t.push(i)}return t}var aS,oS,sS,cS=s((()=>{N(),I(),wi(),kx(),jx(),W(),ai(),Px(),Rx(),hx(),Bx(),Gx(),qx(),Yx(),eS(),Hx(),aS={},M.handleByMap(j.ShapeBuilder,aS),M.add(Kx,Wx,Jx,Fx,Ix,Lx),oS=new V,sS=new F}));function lS(e,t,n){e.beginPath();for(let r=0;r<n.length;r+=3){let i=n[r]*2,a=n[r+1]*2,o=n[r+2]*2;e.moveTo(t[i],t[i+1]),e.lineTo(t[a],t[a+1]),e.lineTo(t[o],t[o+1]),e.closePath()}e.fill()}function uS(e){return`#${(e&16777215).toString(16).padStart(6,`0`)}`}function dS(e,t,n,r,i,a){a=Math.max(0,Math.min(a,Math.min(r,i)/2)),e.moveTo(t+a,n),e.lineTo(t+r-a,n),e.quadraticCurveTo(t+r,n,t+r,n+a),e.lineTo(t+r,n+i-a),e.quadraticCurveTo(t+r,n+i,t+r-a,n+i),e.lineTo(t+a,n+i),e.quadraticCurveTo(t,n+i,t,n+i-a),e.lineTo(t,n+a),e.quadraticCurveTo(t,n,t+a,n)}function fS(e,t){switch(t.type){case`rectangle`:{let n=t;e.rect(n.x,n.y,n.width,n.height);break}case`roundedRectangle`:{let n=t;dS(e,n.x,n.y,n.width,n.height,n.radius);break}case`circle`:{let n=t;e.arc(n.x,n.y,n.radius,0,Math.PI*2);break}case`ellipse`:{let n=t;e.ellipse?e.ellipse(n.x,n.y,n.halfWidth,n.halfHeight,0,0,Math.PI*2):(e.save(),e.translate(n.x,n.y),e.scale(n.halfWidth,n.halfHeight),e.arc(0,0,1,0,Math.PI*2),e.restore());break}case`triangle`:{let n=t;e.moveTo(n.x,n.y),e.lineTo(n.x2,n.y2),e.lineTo(n.x3,n.y3),e.closePath();break}default:{let n=t,r=n.points;if(!r?.length)break;e.moveTo(r[0],r[1]);for(let t=2;t<r.length;t+=2)e.lineTo(r[t],r[t+1]);n.closePath&&e.closePath();break}}}function pS(e,t){if(!t?.length)return!1;for(let n=0;n<t.length;n++){let r=t[n];if(!r?.shape)continue;let i=r.transform,a=i&&!i.isIdentity();a&&(e.save(),e.transform(i.a,i.b,i.c,i.d,i.tx,i.ty)),fS(e,r.shape),a&&e.restore()}return!0}function mS(e,t,n,r){let i=e.fill;if(i instanceof xx){i.buildGradient();let a=i.texture;if(a){let o=Y.getTintedPattern(a,t),s=n?yS.copyFrom(n).scale(a.source.pixelWidth,a.source.pixelHeight):yS.copyFrom(i.transform);return r&&!e.textureSpace&&s.append(r),Y.applyPatternTransform(o,s),o}}if(i instanceof Tx){let e=Y.getTintedPattern(i.texture,t);return Y.applyPatternTransform(e,i.transform,!1),e}let a=e.texture;if(a&&a!==U.WHITE){if(!a.source.resource)return hS;let r=Y.getTintedPattern(a,t),i=e.matrix;if(n){let{resolution:e}=a.source;if(i=yS.copyFrom(n),a.rotate){let{uvs:t,orig:n}=a;i.prepend(bS.set(t.x1-t.x0,t.y1-t.y0,t.x3-t.x0,t.y3-t.y0,t.x0,t.y0).invert()).scale(n.width*e,n.height*e)}else i.scale(a.source.pixelWidth,a.source.pixelHeight).translate(-a.frame.x*e,-a.frame.y*e)}return Y.applyPatternTransform(r,i),r}return uS(t)}var hS,gS,_S,vS,yS,bS,xS,SS=s((()=>{N(),Aa(),I(),Fc(),W(),Gi(),zi(),hx(),Sx(),Ex(),cS(),eS(),hS=`#808080`,gS=new F,_S=new F,vS=new F,yS=new F,bS=new F,xS=class{constructor(){this.shader=null}contextChange(e){}execute(e,t){let n=e.renderer,r=n.canvasContext,i=r.activeContext,a=t.groupTransform,o=n.globalUniforms.globalUniformData?.worldColor??4294967295,s=t.groupColorAlpha,c=(o>>>24&255)/255,l=(s>>>24&255)/255,u=n.filter?.alphaMultiplier??1,d=c*l*u;if(d<=0)return;let f=o&16777215,p=Ui(Ri(s&16777215,f)),m=n._roundPixels|t._roundPixels;i.save(),r.setContextTransform(a,m===1),r.setBlendMode(t.groupBlendMode);let h=t.context.instructions;for(let e=0;e<h.length;e++){let t=h[e];if(t.action===`texture`){let e=t.data,n=e.image,o=n?Y.getCanvasSource(n):null;if(!o)continue;let s=e.alpha*d;if(s<=0)continue;let c=Ri(e.style,p);i.globalAlpha=s;let l=o;c!==16777215&&(l=Y.getTintedCanvas({texture:n},c));let u=n.frame,f=n.source._resolution??n.source.resolution??1,h=u.x*f,g=u.y*f,_=u.width*f,v=u.height*f;l!==o&&(h=0,g=0);let y=e.transform,b=y&&!y.isIdentity(),x=n.rotate;b||x?(gS.copyFrom(a),b&&gS.append(y),x&&H.matrixAppendRotationInv(gS,x,e.dx,e.dy,e.dw,e.dh),r.setContextTransform(gS,m===1)):r.setContextTransform(a,m===1),i.drawImage(l,h,g,l===o?_:l.width,l===o?v:l.height,x?0:e.dx,x?0:e.dy,e.dw,e.dh),(b||x)&&r.setContextTransform(a,m===1);continue}let n=t.data,o=n?.path?.shapePath;if(!o?.shapePrimitives?.length)continue;let s=n.style,c=Ri(s.color,p),l=s.alpha*d;if(l<=0)continue;let u=t.action===`stroke`;if(i.globalAlpha=l,u){let e=s;i.lineWidth=e.width,i.lineCap=e.cap,i.lineJoin=e.join,i.miterLimit=e.miterLimit}let f=o.shapePrimitives;if(!u&&n.hole?.shapePath?.shapePrimitives?.length){let e=f[f.length-1];e.holes=n.hole.shapePath.shapePrimitives}for(let e=0;e<f.length;e++){let t=f[e];if(!t?.shape)continue;let n=t.transform,r=n&&!n.isIdentity(),o=s.texture&&s.texture!==U.WHITE,l=s.textureSpace===`global`?n:null,d=mS(s,c,o?Xx(_S,s,t.shape,l):null,r?vS.copyFrom(a).append(n):a);if(r&&(i.save(),i.transform(n.a,n.b,n.c,n.d,n.tx,n.ty)),u){let e=s;if(e.alignment!==.5&&!e.pixelLine){let n=[],r=[],a=[];aS[t.shape.type]?.build(t.shape,n)?(mx(n,e,!1,t.shape.closePath??!0,r,a),i.fillStyle=d,lS(i,r,a)):(i.strokeStyle=d,i.beginPath(),fS(i,t.shape),i.stroke())}else i.strokeStyle=d,i.beginPath(),fS(i,t.shape),i.stroke()}else i.fillStyle=d,i.beginPath(),fS(i,t.shape),pS(i,t.holes)?i.fill(`evenodd`):i.fill();r&&i.restore()}}i.restore()}destroy(){this.shader=null}},xS.extension={type:[j.CanvasPipesAdaptor],name:`graphics`}})),CS,wS,TS=s((()=>{N(),Aa(),I(),Gi(),zi(),Fc(),CS=class e{static _getPatternRepeat(e,t){let n=e&&e!==`clamp-to-edge`,r=t&&t!==`clamp-to-edge`;return n&&r?`repeat`:n?`repeat-x`:r?`repeat-y`:`no-repeat`}start(e,t,n){}execute(t,n){let r=n.elements;if(!r||!r.length)return;let i=t.renderer,a=i.canvasContext,o=a.activeContext;for(let t=0;t<r.length;t++){let s=r[t];if(!s.packAsQuad)continue;let c=s,l=c.texture,u=l?Y.getCanvasSource(l):null;if(!u)continue;let d=l.source.style,f=a.smoothProperty,p=d.scaleMode!==`nearest`;o[f]!==p&&(o[f]=p),a.setBlendMode(n.blendMode);let m=i.globalUniforms.globalUniformData?.worldColor??4294967295,h=c.color,g=(m>>>24&255)/255,_=(h>>>24&255)/255,v=i.filter?.alphaMultiplier??1,y=g*_*v;if(y<=0)continue;o.globalAlpha=y;let b=m&16777215,x=Ui(Ri(h&16777215,b)),S=l.frame,C=d.addressModeU??d.addressMode,w=d.addressModeV??d.addressMode,ee=e._getPatternRepeat(C,w),T=l.source._resolution??l.source.resolution??1,E=c.renderable?.renderGroup?.isCachedAsTexture,te=S.x*T,D=S.y*T,ne=S.width*T,re=S.height*T,O=c.bounds,k=i.renderTarget.renderTarget.isRoot,ie=O.minX,ae=O.minY,oe=O.maxX-O.minX,se=O.maxY-O.minY,ce=l.rotate,A=l.uvs,le=Math.min(A.x0,A.x1,A.x2,A.x3,A.y0,A.y1,A.y2,A.y3),ue=Math.max(A.x0,A.x1,A.x2,A.x3,A.y0,A.y1,A.y2,A.y3),de=ee!==`no-repeat`&&(le<0||ue>1),fe=ce&&!(!de&&(x!==16777215||ce));fe?(e._tempPatternMatrix.copyFrom(c.transform),H.matrixAppendRotationInv(e._tempPatternMatrix,ce,ie,ae,oe,se),a.setContextTransform(e._tempPatternMatrix,c.roundPixels===1,void 0,E&&k)):a.setContextTransform(c.transform,c.roundPixels===1,void 0,E&&k);let pe=oe,me=se,he=fe?0:ie,ge=fe?0:ae;if(!fe&&c.roundPixels===1&&(he|=0,ge|=0),de){let t=u,n=x!==16777215&&!ce,r=S.width<=l.source.width&&S.height<=l.source.height;n&&r&&(t=Y.getTintedCanvas({texture:l},x));let i=o.createPattern(t,ee);if(!i)continue;let a=pe,s=me;if(a===0||s===0)continue;let c=1/a,d=1/s,f=(A.x1-A.x0)*c,p=(A.y1-A.y0)*c,m=(A.x3-A.x0)*d,h=(A.y3-A.y0)*d,g=A.x0-f*he-m*ge,_=A.y0-p*he-h*ge,v=l.source.pixelWidth,y=l.source.pixelHeight;e._tempPatternMatrix.set(f*v,p*y,m*v,h*y,g*v,_*y),Y.applyPatternTransform(i,e._tempPatternMatrix),o.fillStyle=i,o.fillRect(he,ge,pe,me)}else{let e=x!==16777215||ce?Y.getTintedCanvas({texture:l},x):u,t=e!==u;o.drawImage(e,t?0:te,t?0:D,t?e.width:ne,t?e.height:re,he,ge,pe,me)}}}},CS._tempPatternMatrix=new F,CS.extension={type:[j.CanvasPipesAdaptor],name:`batch`},wS=CS})),ES,DS=s((()=>{N(),ES=class{constructor(e){this._colorStack=[],this._colorStackIndex=0,this._currentColor=0,this._renderer=e}buildStart(){this._colorStack[0]=15,this._colorStackIndex=1,this._currentColor=15}push(e,t,n){this._renderer.renderPipes.batch.break(n);let r=this._colorStack;r[this._colorStackIndex]=r[this._colorStackIndex-1]&e.mask;let i=this._colorStack[this._colorStackIndex];i!==this._currentColor&&(this._currentColor=i,n.add({renderPipeId:`colorMask`,colorMask:i,canBundle:!1})),this._colorStackIndex++}pop(e,t,n){this._renderer.renderPipes.batch.break(n);let r=this._colorStack;this._colorStackIndex--;let i=r[this._colorStackIndex-1];i!==this._currentColor&&(this._currentColor=i,n.add({renderPipeId:`colorMask`,colorMask:i,canBundle:!1}))}execute(e){}destroy(){this._renderer=null,this._colorStack=null}},ES.extension={type:[j.CanvasPipes],name:`colorMask`}}));function OS(e){let t=[];return e.replace(jS,(e,n,r)=>{let i=n.toLowerCase(),a=n,o=kS(r);for(i===`m`&&o.length>2&&(t.push([a,...o.splice(0,2)]),i=`l`,a=a===`m`?`l`:`L`);;){if(o.length===AS[i])return t.push([a,...o]),``;if(o.length<AS[i])throw Error(`malformed path data`);t.push([a,...o.splice(0,AS[i])])}}),t}function kS(e){let t=e.match(MS);return t?t.map(Number):[]}var AS,jS,MS,NS=s((()=>{AS={a:7,c:6,h:1,l:2,m:2,q:4,s:4,t:2,v:1,z:0},jS=/([astvzqmhlc])([^astvzqmhlc]*)/gi,MS=/-?[0-9]*\.?[0-9]+(?:e[-+]?\d+)?/gi}));function PS(e,t){let n=OS(e),r=[],i=null,a=0,o=0;for(let e=0;e<n.length;e++){let s=n[e],c=s[0],l=s;switch(c){case`M`:a=l[1],o=l[2],t.moveTo(a,o);break;case`m`:a+=l[1],o+=l[2],t.moveTo(a,o);break;case`H`:a=l[1],t.lineTo(a,o);break;case`h`:a+=l[1],t.lineTo(a,o);break;case`V`:o=l[1],t.lineTo(a,o);break;case`v`:o+=l[1],t.lineTo(a,o);break;case`L`:a=l[1],o=l[2],t.lineTo(a,o);break;case`l`:a+=l[1],o+=l[2],t.lineTo(a,o);break;case`C`:a=l[5],o=l[6],t.bezierCurveTo(l[1],l[2],l[3],l[4],a,o);break;case`c`:t.bezierCurveTo(a+l[1],o+l[2],a+l[3],o+l[4],a+l[5],o+l[6]),a+=l[5],o+=l[6];break;case`S`:a=l[3],o=l[4],t.bezierCurveToShort(l[1],l[2],a,o);break;case`s`:t.bezierCurveToShort(a+l[1],o+l[2],a+l[3],o+l[4]),a+=l[3],o+=l[4];break;case`Q`:a=l[3],o=l[4],t.quadraticCurveTo(l[1],l[2],a,o);break;case`q`:t.quadraticCurveTo(a+l[1],o+l[2],a+l[3],o+l[4]),a+=l[3],o+=l[4];break;case`T`:a=l[1],o=l[2],t.quadraticCurveToShort(a,o);break;case`t`:a+=l[1],o+=l[2],t.quadraticCurveToShort(a,o);break;case`A`:a=l[6],o=l[7],t.arcToSvg(l[1],l[2],l[3],l[4],l[5],a,o);break;case`a`:a+=l[6],o+=l[7],t.arcToSvg(l[1],l[2],l[3],l[4],l[5],a,o);break;case`Z`:case`z`:t.closePath(),r.length>0&&(i=r.pop(),i?(a=i.startX,o=i.startY):(a=0,o=0)),i=null;break;default:z(`Unknown SVG path command: ${c}`)}c!==`Z`&&c!==`z`&&i===null&&(i={startX:a,startY:o},r.push(i))}return t}var FS=s((()=>{NS(),B()})),IS,LS,RS,zS,BS=s((()=>{N(),Nf(),rh(),ca(),Tg(),Xr(),ai(),cS(),IS=class{constructor(){this.batches=[],this.geometryData={vertices:[],uvs:[],indices:[]}}reset(){this.batches&&this.batches.forEach(e=>{ii.return(e)}),this.graphicsData&&ii.return(this.graphicsData),this.isBatchable=!1,this.context=null,this.batches.length=0,this.geometryData.indices.length=0,this.geometryData.vertices.length=0,this.geometryData.uvs.length=0,this.graphicsData=null}destroy(){this.reset(),this.batches=null,this.geometryData=null}},LS=class{constructor(){this.instructions=new sa}init(e){let t=e.maxTextures;this.batcher?this.batcher._updateMaxTextures(t):this.batcher=new nh({maxTextures:t}),this.instructions.reset()}get geometry(){return R(Jr,`GraphicsContextRenderData#geometry is deprecated, please use batcher.geometry instead.`),this.batcher.geometry}destroy(){this.batcher.destroy(),this.instructions.destroy(),this.batcher=null,this.instructions=null}},RS=class e{constructor(e){this._renderer=e,this._managedContexts=new wg({renderer:e,type:`resource`,name:`graphicsContext`})}init(t){e.defaultOptions.bezierSmoothness=t?.bezierSmoothness??e.defaultOptions.bezierSmoothness}getContextRenderData(e){return e._gpuData[this._renderer.uid].graphicsData||this._initContextRenderData(e)}updateGpuContext(e){let t=!!e._gpuData[this._renderer.uid],n=e._gpuData[this._renderer.uid]||this._initContext(e);if(e.dirty||!t){t&&n.reset(),tS(e,n);let r=e.batchMode;n.isBatchable=e.customShader||r===`no-batch`?!1:r!==`auto`||n.geometryData.vertices.length<400,e.dirty=!1}return n}getGpuContext(e){return e._gpuData[this._renderer.uid]||this._initContext(e)}_initContextRenderData(e){let t=ii.get(LS,{maxTextures:this._renderer.limits.maxBatchableTextures}),n=e._gpuData[this._renderer.uid],{batches:r,geometryData:i}=n;n.graphicsData=t;let a=i.vertices.length,o=i.indices.length;for(let e=0;e<r.length;e++)r[e].applyTransform=!1;let s=t.batcher;s.ensureAttributeBuffer(a),s.ensureIndexBuffer(o),s.begin();for(let e=0;e<r.length;e++){let t=r[e];s.add(t)}s.finish(t.instructions);let c=s.geometry;c.indexBuffer.setDataWithSize(s.indexBuffer,s.indexSize,!0),c.buffers[0].setDataWithSize(s.attributeBuffer.float32View,s.attributeSize,!0);let l=s.batches;for(let e=0;e<l.length;e++){let t=l[e];t.bindGroup=Af(t.textures.textures,t.textures.count,this._renderer.limits.maxBatchableTextures)}return t}_initContext(e){let t=new IS;return t.context=e,e._gpuData[this._renderer.uid]=t,this._managedContexts.add(e),t}destroy(){this._managedContexts.destroy(),this._renderer=null}},RS.extension={type:[j.WebGLSystem,j.WebGPUSystem],name:`graphicsContext`},RS.defaultOptions={bezierSmoothness:.5},zS=RS}));function VS(e,t,n,r,i,a,o,s,c,l){let u=Math.min(.99,Math.max(0,l??zS.defaultOptions.bezierSmoothness)),d=(KS-u)/1;return d*=d,HS(t,n,r,i,a,o,s,c,e,d),e}function HS(e,t,n,r,i,a,o,s,c,l){US(e,t,n,r,i,a,o,s,c,l,0),c.push(o,s)}function US(e,t,n,r,i,a,o,s,c,l,u){if(u>WS)return;let d=(e+n)/2,f=(t+r)/2,p=(n+i)/2,m=(r+a)/2,h=(i+o)/2,g=(a+s)/2,_=(d+p)/2,v=(f+m)/2,y=(p+h)/2,b=(m+g)/2,x=(_+y)/2,S=(v+b)/2;if(u>0){let u=o-e,d=s-t,f=Math.abs((n-o)*d-(r-s)*u),p=Math.abs((i-o)*d-(a-s)*u);if(f>GS&&p>GS){if((f+p)*(f+p)<=l*(u*u+d*d)){c.push(x,S);return}}else if(f>GS){if(f*f<=l*(u*u+d*d)){c.push(x,S);return}}else if(p>GS){if(p*p<=l*(u*u+d*d)){c.push(x,S);return}}else if(u=x-(e+o)/2,d=S-(t+s)/2,u*u+d*d<=l){c.push(x,S);return}}US(e,t,d,f,_,v,x,S,c,l,u+1),US(x,S,y,b,h,g,o,s,c,l,u+1)}var WS,GS,KS,qS=s((()=>{BS(),WS=8,GS=1.1920929e-7,KS=1}));function JS(e,t,n,r,i,a,o,s){let c=Math.min(.99,Math.max(0,s??zS.defaultOptions.bezierSmoothness)),l=($S-c)/1;return l*=l,YS(t,n,r,i,a,o,e,l),e}function YS(e,t,n,r,i,a,o,s){XS(o,e,t,n,r,i,a,s,0),o.push(i,a)}function XS(e,t,n,r,i,a,o,s,c){if(c>ZS)return;let l=(t+r)/2,u=(n+i)/2,d=(r+a)/2,f=(i+o)/2,p=(l+d)/2,m=(u+f)/2,h=a-t,g=o-n,_=Math.abs((r-a)*g-(i-o)*h);if(_>QS){if(_*_<=s*(h*h+g*g)){e.push(p,m);return}}else if(h=p-(t+a)/2,g=m-(n+o)/2,h*h+g*g<=s){e.push(p,m);return}XS(e,t,n,l,u,p,m,s,c+1),XS(e,p,m,d,f,a,o,s,c+1)}var ZS,QS,$S,eC=s((()=>{BS(),ZS=8,QS=1.1920929e-7,$S=1}));function tC(e,t,n,r,i,a,o,s){let c=Math.abs(i-a);(!o&&i>a||o&&a>i)&&(c=2*Math.PI-c),s||=Math.max(6,Math.floor(6*r**(1/3)*(c/Math.PI))),s=Math.max(s,3);let l=c/s,u=i;l*=o?-1:1;for(let i=0;i<s+1;i++){let i=Math.cos(u),a=Math.sin(u),o=t+i*r,s=n+a*r;e.push(o,s),u+=l}}var nC=s((()=>{}));function rC(e,t,n,r,i,a){let o=e[e.length-2],s=e[e.length-1]-n,c=o-t,l=i-n,u=r-t,d=Math.abs(s*u-c*l);if(d<1e-8||a===0){(e[e.length-2]!==t||e[e.length-1]!==n)&&e.push(t,n);return}let f=s*s+c*c,p=l*l+u*u,m=s*l+c*u,h=a*Math.sqrt(f)/d,g=a*Math.sqrt(p)/d,_=h*m/f,v=g*m/p,y=h*u+g*c,b=h*l+g*s,x=c*(g+_),S=s*(g+_),C=u*(h+v),w=l*(h+v),ee=Math.atan2(S-b,x-y),T=Math.atan2(w-b,C-y);tC(e,y+t,b+n,a,ee,T,c*l>u*s)}var iC=s((()=>{nC()}));function aC(e,t){let n=t===-1.5707963267948966?-.551915024494:4/3*Math.tan(t/4),r=t===1.5707963267948966?.551915024494:n,i=Math.cos(e),a=Math.sin(e),o=Math.cos(e+t),s=Math.sin(e+t);return[{x:i-a*r,y:a+i*r},{x:o+s*r,y:s-o*r},{x:o,y:s}]}function oC(e,t,n,r,i,a,o,s=0,c=0,l=0){if(a===0||o===0)return;let u=Math.sin(s*sC/360),d=Math.cos(s*sC/360),f=d*(t-r)/2+u*(n-i)/2,p=-u*(t-r)/2+d*(n-i)/2;if(f===0&&p===0)return;a=Math.abs(a),o=Math.abs(o);let m=f**2/a**2+p**2/o**2;m>1&&(a*=Math.sqrt(m),o*=Math.sqrt(m)),dC(t,n,r,i,a,o,c,l,u,d,f,p,cC);let{ang1:h,ang2:g}=cC,{centerX:_,centerY:v}=cC,y=Math.abs(g)/(sC/4);Math.abs(1-y)<1e-7&&(y=1);let b=Math.max(Math.ceil(y),1);g/=b;let x=e[e.length-2],S=e[e.length-1],C={x:0,y:0};for(let t=0;t<b;t++){let t=aC(h,g),{x:n,y:r}=lC(t[0],a,o,d,u,_,v,C),{x:i,y:s}=lC(t[1],a,o,d,u,_,v,C),{x:c,y:l}=lC(t[2],a,o,d,u,_,v,C);VS(e,x,S,n,r,i,s,c,l),x=c,S=l,h+=g}}var sC,cC,lC,uC,dC,fC=s((()=>{qS(),sC=Math.PI*2,cC={centerX:0,centerY:0,ang1:0,ang2:0},lC=({x:e,y:t},n,r,i,a,o,s,c)=>{e*=n,t*=r;let l=i*e-a*t,u=a*e+i*t;return c.x=l+o,c.y=u+s,c},uC=(e,t,n,r)=>{let i=e*r-t*n<0?-1:1,a=e*n+t*r;return a>1&&(a=1),a<-1&&(a=-1),i*Math.acos(a)},dC=(e,t,n,r,i,a,o,s,c,l,u,d,f)=>{let p=i**2,m=a**2,h=u**2,g=d**2,_=p*m-p*g-m*h;_<0&&(_=0),_/=p*g+m*h,_=Math.sqrt(_)*(o===s?-1:1);let v=_*i/a*d,y=_*-a/i*u,b=l*v-c*y+(e+n)/2,x=c*v+l*y+(t+r)/2,S=(u-v)/i,C=(d-y)/a,w=(-u-v)/i,ee=(-d-y)/a,T=uC(1,0,S,C),E=uC(S,C,w,ee);s===0&&E>0&&(E-=sC),s===1&&E<0&&(E+=sC),f.centerX=b,f.centerY=x,f.ang1=T,f.ang2=E}}));function pC(e,t,n){let r=(e,t)=>{let n=t.x-e.x,r=t.y-e.y,i=Math.sqrt(n*n+r*r);return{len:i,nx:n/i,ny:r/i}},i=(t,n)=>{t===0?e.moveTo(n.x,n.y):e.lineTo(n.x,n.y)},a=t[t.length-1];for(let o=0;o<t.length;o++){let s=t[o%t.length],c=s.radius??n;if(c<=0){i(o,s),a=s;continue}let l=t[(o+1)%t.length],u=r(s,a),d=r(s,l);if(u.len<1e-4||d.len<1e-4){i(o,s),a=s;continue}let f=Math.asin(u.nx*d.ny-u.ny*d.nx),p=1,m=!1;u.nx*d.nx-u.ny*-d.ny<0?f<0?f=Math.PI+f:(f=Math.PI-f,p=-1,m=!0):f>0&&(p=-1,m=!0);let h=f/2,g,_=Math.abs(Math.cos(h)*c/Math.sin(h));_>Math.min(u.len/2,d.len/2)?(_=Math.min(u.len/2,d.len/2),g=Math.abs(_*Math.sin(h)/Math.cos(h))):g=c;let v=s.x+d.nx*_+-d.ny*g*p,y=s.y+d.ny*_+d.nx*g*p,b=Math.atan2(u.ny,u.nx)+Math.PI/2*p,x=Math.atan2(d.ny,d.nx)-Math.PI/2*p;o===0&&e.moveTo(v+Math.cos(b)*g,y+Math.sin(b)*g),e.arc(v,y,g,b,x,m),a=s}}function mC(e,t,n,r){let i=(e,t)=>Math.sqrt((e.x-t.x)**2+(e.y-t.y)**2),a=(e,t,n)=>({x:e.x+(t.x-e.x)*n,y:e.y+(t.y-e.y)*n}),o=t.length;for(let s=0;s<o;s++){let c=t[(s+1)%o],l=c.radius??n;if(l<=0){s===0?e.moveTo(c.x,c.y):e.lineTo(c.x,c.y);continue}let u=t[s],d=t[(s+2)%o],f=i(u,c),p;p=f<1e-4?c:a(c,u,Math.min(f/2,l)/f);let m=i(d,c),h;h=m<1e-4?c:a(c,d,Math.min(m/2,l)/m),s===0?e.moveTo(p.x,p.y):e.lineTo(p.x,p.y),e.quadraticCurveTo(c.x,c.y,h.x,h.y,r)}}var hC=s((()=>{})),gC,_C,vC=s((()=>{Wc(),Kc(),Xc(),wi(),$c(),Di(),qS(),eC(),nC(),iC(),fC(),hC(),gC=new V,_C=class{constructor(e){this.shapePrimitives=[],this._currentPoly=null,this._bounds=new Ei,this._graphicsPath2D=e,this.signed=e.checkForHoles}moveTo(e,t){return this.startPoly(e,t),this}lineTo(e,t){this._ensurePoly();let n=this._currentPoly.points,r=n[n.length-2],i=n[n.length-1];return(r!==e||i!==t)&&n.push(e,t),this}arc(e,t,n,r,i,a){this._ensurePoly(!1);let o=this._currentPoly.points;return tC(o,e,t,n,r,i,a),this}arcTo(e,t,n,r,i){this._ensurePoly();let a=this._currentPoly.points;return rC(a,e,t,n,r,i),this}arcToSvg(e,t,n,r,i,a,o){let s=this._currentPoly.points;return oC(s,this._currentPoly.lastX,this._currentPoly.lastY,a,o,e,t,n,r,i),this}bezierCurveTo(e,t,n,r,i,a,o){this._ensurePoly();let s=this._currentPoly;return VS(this._currentPoly.points,s.lastX,s.lastY,e,t,n,r,i,a,o),this}quadraticCurveTo(e,t,n,r,i){this._ensurePoly();let a=this._currentPoly;return JS(this._currentPoly.points,a.lastX,a.lastY,e,t,n,r,i),this}closePath(){return this.endPoly(!0),this}addPath(e,t){this.endPoly(),t&&!t.isIdentity()&&(e=e.clone(!0),e.transform(t));let n=this.shapePrimitives,r=n.length;for(let t=0;t<e.instructions.length;t++){let n=e.instructions[t];this[n.action](...n.data)}if(e.checkForHoles&&n.length-r>1){let e=null;for(let t=r;t<n.length;t++){let r=n[t];if(r.shape.type===`polygon`){let i=r.shape,a=e?.shape;a&&a.containsPolygon(i)?(e.holes||(e.holes=[]),e.holes.push(r),n.copyWithin(t,t+1),n.length--,t--):e=r}}}return this}finish(e=!1){this.endPoly(e)}rect(e,t,n,r,i){return this.drawShape(new V(e,t,n,r),i),this}circle(e,t,n,r){return this.drawShape(new Uc(e,t,n),r),this}poly(e,t,n){let r=new Yc(e);return r.closePath=t,this.drawShape(r,n),this}regularPoly(e,t,n,r,i=0,a){r=Math.max(r|0,3);let o=-1*Math.PI/2+i,s=Math.PI*2/r,c=[];for(let i=0;i<r;i++){let r=o-i*s;c.push(e+n*Math.cos(r),t+n*Math.sin(r))}return this.poly(c,!0,a),this}roundPoly(e,t,n,r,i,a=0,o){if(r=Math.max(r|0,3),i<=0)return this.regularPoly(e,t,n,r,a);let s=n*Math.sin(Math.PI/r)-.001;i=Math.min(i,s);let c=-1*Math.PI/2+a,l=Math.PI*2/r,u=(r-2)*Math.PI/r/2;for(let a=0;a<r;a++){let r=a*l+c,s=e+n*Math.cos(r),d=t+n*Math.sin(r),f=r+Math.PI+u,p=r-Math.PI-u,m=s+i*Math.cos(f),h=d+i*Math.sin(f),g=s+i*Math.cos(p),_=d+i*Math.sin(p);a===0?this.moveTo(m,h):this.lineTo(m,h),this.quadraticCurveTo(s,d,g,_,o)}return this.closePath()}roundShape(e,t,n=!1,r){return e.length<3?this:(n?mC(this,e,t,r):pC(this,e,t),this.closePath())}filletRect(e,t,n,r,i){if(i===0)return this.rect(e,t,n,r);let a=Math.min(n,r)/2,o=Math.min(a,Math.max(-a,i)),s=e+n,c=t+r,l=o<0?-o:0,u=Math.abs(o);return this.moveTo(e,t+u).arcTo(e+l,t+l,e+u,t,u).lineTo(s-u,t).arcTo(s-l,t+l,s,t+u,u).lineTo(s,c-u).arcTo(s-l,c-l,e+n-u,c,u).lineTo(e+u,c).arcTo(e+l,c-l,e,c-u,u).closePath()}chamferRect(e,t,n,r,i,a){if(i<=0)return this.rect(e,t,n,r);let o=Math.min(i,Math.min(n,r)/2),s=e+n,c=t+r,l=[e+o,t,s-o,t,s,t+o,s,c-o,s-o,c,e+o,c,e,c-o,e,t+o];for(let e=l.length-1;e>=2;e-=2)l[e]===l[e-2]&&l[e-1]===l[e-3]&&l.splice(e-1,2);return this.poly(l,!0,a)}ellipse(e,t,n,r,i){return this.drawShape(new Gc(e,t,n,r),i),this}roundRect(e,t,n,r,i,a){return this.drawShape(new Qc(e,t,n,r,i),a),this}drawShape(e,t){return this.endPoly(),this.shapePrimitives.push({shape:e,transform:t}),this}startPoly(e,t){let n=this._currentPoly;return n&&this.endPoly(),n=new Yc,n.points.push(e,t),this._currentPoly=n,this}endPoly(e=!1){let t=this._currentPoly;return t&&t.points.length>2&&(t.closePath=e,this.shapePrimitives.push({shape:t})),this._currentPoly=null,this}_ensurePoly(e=!0){if(!this._currentPoly&&(this._currentPoly=new Yc,e)){let e=this.shapePrimitives[this.shapePrimitives.length-1];if(e){let t=e.shape.x,n=e.shape.y;if(e.transform&&!e.transform.isIdentity()){let r=e.transform,i=t;t=r.a*t+r.c*n+r.tx,n=r.b*i+r.d*n+r.ty}this._currentPoly.points.push(t,n)}else this._currentPoly.points.push(0,0)}}buildPath(){let e=this._graphicsPath2D;this.shapePrimitives.length=0,this._currentPoly=null;for(let t=0;t<e.instructions.length;t++){let n=e.instructions[t];this[n.action](...n.data)}this.finish()}get bounds(){let e=this._bounds;e.clear();let t=this.shapePrimitives;for(let n=0;n<t.length;n++){let r=t[n],i=r.shape.getBounds(gC);r.transform?e.addRect(i,r.transform):e.addRect(i)}return e}}}));function yC(e,t){return e?e.prepend(t):t.clone()}var bC,xC=s((()=>{zr(),Kr(),B(),FS(),vC(),bC=class e{constructor(e,t=!1){this.instructions=[],this.uid=Wr(`graphicsPath`),this._dirty=!0,this.checkForHoles=t,typeof e==`string`?PS(e,this):this.instructions=e?.slice()??[]}get shapePath(){return this._shapePath||=new _C(this),this._dirty&&(this._dirty=!1,this._shapePath.buildPath()),this._shapePath}addPath(e,t){return e=e.clone(),this.instructions.push({action:`addPath`,data:[e,t]}),this._dirty=!0,this}arc(...e){return this.instructions.push({action:`arc`,data:e}),this._dirty=!0,this}arcTo(...e){return this.instructions.push({action:`arcTo`,data:e}),this._dirty=!0,this}arcToSvg(...e){return this.instructions.push({action:`arcToSvg`,data:e}),this._dirty=!0,this}bezierCurveTo(...e){return this.instructions.push({action:`bezierCurveTo`,data:e}),this._dirty=!0,this}bezierCurveToShort(e,t,n,r,i){let a=this.instructions[this.instructions.length-1],o=this.getLastPoint(Lr.shared),s=0,c=0;if(!a||a.action!==`bezierCurveTo`)s=o.x,c=o.y;else{s=a.data[2],c=a.data[3];let e=o.x,t=o.y;s=e+(e-s),c=t+(t-c)}return this.instructions.push({action:`bezierCurveTo`,data:[s,c,e,t,n,r,i]}),this._dirty=!0,this}closePath(){return this.instructions.push({action:`closePath`,data:[]}),this._dirty=!0,this}ellipse(...e){return this.instructions.push({action:`ellipse`,data:e}),this._dirty=!0,this}lineTo(...e){return this.instructions.push({action:`lineTo`,data:e}),this._dirty=!0,this}moveTo(...e){return this.instructions.push({action:`moveTo`,data:e}),this}quadraticCurveTo(...e){return this.instructions.push({action:`quadraticCurveTo`,data:e}),this._dirty=!0,this}quadraticCurveToShort(e,t,n){let r=this.instructions[this.instructions.length-1],i=this.getLastPoint(Lr.shared),a=0,o=0;if(!r||r.action!==`quadraticCurveTo`)a=i.x,o=i.y;else{a=r.data[0],o=r.data[1];let e=i.x,t=i.y;a=e+(e-a),o=t+(t-o)}return this.instructions.push({action:`quadraticCurveTo`,data:[a,o,e,t,n]}),this._dirty=!0,this}rect(e,t,n,r,i){return this.instructions.push({action:`rect`,data:[e,t,n,r,i]}),this._dirty=!0,this}circle(e,t,n,r){return this.instructions.push({action:`circle`,data:[e,t,n,r]}),this._dirty=!0,this}roundRect(...e){return this.instructions.push({action:`roundRect`,data:e}),this._dirty=!0,this}poly(...e){return this.instructions.push({action:`poly`,data:e}),this._dirty=!0,this}regularPoly(...e){return this.instructions.push({action:`regularPoly`,data:e}),this._dirty=!0,this}roundPoly(...e){return this.instructions.push({action:`roundPoly`,data:e}),this._dirty=!0,this}roundShape(...e){return this.instructions.push({action:`roundShape`,data:e}),this._dirty=!0,this}filletRect(...e){return this.instructions.push({action:`filletRect`,data:e}),this._dirty=!0,this}chamferRect(...e){return this.instructions.push({action:`chamferRect`,data:e}),this._dirty=!0,this}star(e,t,n,r,i,a,o){i||=r/2;let s=-1*Math.PI/2+a,c=n*2,l=Math.PI*2/c,u=[];for(let n=0;n<c;n++){let a=n%2?i:r,o=n*l+s;u.push(e+a*Math.cos(o),t+a*Math.sin(o))}return this.poly(u,!0,o),this}clone(t=!1){let n=new e;if(n.checkForHoles=this.checkForHoles,!t)n.instructions=this.instructions.slice();else for(let e=0;e<this.instructions.length;e++){let t=this.instructions[e];n.instructions.push({action:t.action,data:t.data.slice()})}return n}clear(){return this.instructions.length=0,this._dirty=!0,this}transform(e){if(e.isIdentity())return this;let t=e.a,n=e.b,r=e.c,i=e.d,a=e.tx,o=e.ty,s=0,c=0,l=0,u=0,d=0,f=0,p=0,m=0;for(let h=0;h<this.instructions.length;h++){let g=this.instructions[h],_=g.data;switch(g.action){case`moveTo`:case`lineTo`:s=_[0],c=_[1],_[0]=t*s+r*c+a,_[1]=n*s+i*c+o;break;case`bezierCurveTo`:l=_[0],u=_[1],d=_[2],f=_[3],s=_[4],c=_[5],_[0]=t*l+r*u+a,_[1]=n*l+i*u+o,_[2]=t*d+r*f+a,_[3]=n*d+i*f+o,_[4]=t*s+r*c+a,_[5]=n*s+i*c+o;break;case`quadraticCurveTo`:l=_[0],u=_[1],s=_[2],c=_[3],_[0]=t*l+r*u+a,_[1]=n*l+i*u+o,_[2]=t*s+r*c+a,_[3]=n*s+i*c+o;break;case`arcToSvg`:s=_[5],c=_[6],p=_[0],m=_[1],_[0]=t*p+r*m,_[1]=n*p+i*m,_[5]=t*s+r*c+a,_[6]=n*s+i*c+o;break;case`circle`:_[4]=yC(_[3],e);break;case`rect`:_[4]=yC(_[4],e);break;case`ellipse`:_[8]=yC(_[8],e);break;case`roundRect`:_[5]=yC(_[5],e);break;case`addPath`:_[0].transform(e);break;case`poly`:_[2]=yC(_[2],e);break;case`regularPoly`:case`chamferRect`:_[5]=yC(_[5],e);break;case`closePath`:break;default:z(`unknown transform action`,g.action)}}return this._dirty=!0,this}get bounds(){return this.shapePath.bounds}getLastPoint(e){let t=this.instructions.length-1,n=this.instructions[t];if(!n)return e.x=0,e.y=0,e;for(;n.action===`closePath`;){if(t--,t<0)return e.x=0,e.y=0,e;n=this.instructions[t]}switch(n.action){case`moveTo`:case`lineTo`:e.x=n.data[0],e.y=n.data[1];break;case`quadraticCurveTo`:e.x=n.data[2],e.y=n.data[3];break;case`bezierCurveTo`:e.x=n.data[4],e.y=n.data[5];break;case`arc`:case`arcToSvg`:e.x=n.data[5],e.y=n.data[6];break;case`addPath`:n.data[0].getLastPoint(e)}return e}}}));function SC(e,t,n){let r=e.getAttribute(t);return r?Number(r):n}var CC=s((()=>{}));function wC(e,t){let n=e.querySelectorAll(`defs`);for(let e=0;e<n.length;e++){let r=n[e];for(let e=0;e<r.children.length;e++){let n=r.children[e];switch(n.nodeName.toLowerCase()){case`lineargradient`:t.defs[n.id]=OC(n);break;case`radialgradient`:t.defs[n.id]=kC(n)}}}}function TC(e,t,n){let r=e.getAttribute(t);if(r?.trim().endsWith(`%`)){let e=Number(r.trim().slice(0,-1));return Number.isNaN(e)?n:e/100}return SC(e,t,n)}function EC(e){return(e.getAttribute(`gradientUnits`)||`objectBoundingBox`)===`objectBoundingBox`?`local`:`global`}function DC(e){let t=[];for(let n=0;n<e.children.length;n++){let r=e.children[n],i=TC(r,`offset`,0),a=P.shared.setValue(r.getAttribute(`stop-color`)).toNumber();t.push({offset:i,color:a})}return t}function OC(e){let t=TC(e,`x1`,0),n=TC(e,`y1`,0),r=TC(e,`x2`,1),i=TC(e,`y2`,0);return new xx({type:`linear`,start:{x:t,y:n},end:{x:r,y:i},textureSpace:EC(e),colorStops:DC(e)})}function kC(e){let t=TC(e,`cx`,.5),n=TC(e,`cy`,.5),r=TC(e,`r`,.5),i=TC(e,`fx`,t),a=TC(e,`fy`,n),o=TC(e,`fr`,0);return new xx({type:`radial`,center:{x:i,y:a},innerRadius:o,outerCenter:{x:t,y:n},outerRadius:r,textureSpace:EC(e),colorStops:DC(e)})}var AC=s((()=>{Ar(),Sx(),CC()}));function jC(e){let t=e.match(/url\s*\(\s*['"]?\s*#([^'"\s)]+)\s*['"]?\s*\)/i);return t?t[1]:``}var MC=s((()=>{}));function NC(e,t){let n=e.getAttribute(`style`),r={},i={},a={strokeStyle:r,fillStyle:i,useFill:!1,useStroke:!1};for(let n in FC){let r=e.getAttribute(n);r&&PC(t,a,n,r.trim())}if(n){let e=n.split(`;`);for(let n=0;n<e.length;n++){let[r,i]=e[n].trim().split(`:`);FC[r]&&PC(t,a,r,i.trim())}}return{strokeStyle:a.useStroke?r:null,fillStyle:a.useFill?i:null,useFill:a.useFill,useStroke:a.useStroke}}function PC(e,t,n,r){switch(n){case`stroke`:if(r!==`none`){if(r.startsWith(`url(`)){let n=jC(r);t.strokeStyle.fill=e.defs[n]}else t.strokeStyle.color=P.shared.setValue(r).toNumber();t.useStroke=!0}break;case`stroke-width`:t.strokeStyle.width=Number(r);break;case`fill`:if(r!==`none`){if(r.startsWith(`url(`)){let n=jC(r);t.fillStyle.fill=e.defs[n]}else t.fillStyle.color=P.shared.setValue(r).toNumber();t.useFill=!0}break;case`fill-opacity`:t.fillStyle.alpha=Number(r);break;case`stroke-opacity`:t.strokeStyle.alpha=Number(r);break;case`opacity`:t.fillStyle.alpha=Number(r),t.strokeStyle.alpha=Number(r)}}var FC,IC=s((()=>{Ar(),MC(),FC={fill:{type:`paint`,default:0},"fill-opacity":{type:`number`,default:1},stroke:{type:`paint`,default:0},"stroke-width":{type:`number`,default:1},"stroke-opacity":{type:`number`,default:1},"stroke-linecap":{type:`string`,default:`butt`},"stroke-linejoin":{type:`string`,default:`miter`},"stroke-miterlimit":{type:`number`,default:10},"stroke-dasharray":{type:`string`,default:`none`},"stroke-dashoffset":{type:`number`,default:0},opacity:{type:`number`,default:1}}}));function LC(e){if(e.length<=2)return!0;let t=e.map(e=>e.area).sort((e,t)=>t-e),[n,r]=t,i=t[t.length-1],a=n/r,o=r/i;return!(a>3&&o<2)}var RC=s((()=>{}));function zC(e){return e.split(/(?=[Mm])/).filter(e=>e.trim().length>0)}function BC(e){let t=e.match(/[-+]?[0-9]*\.?[0-9]+/g);if(!t||t.length<4)return 0;let n=t.map(Number),r=[],i=[];for(let e=0;e<n.length;e+=2)e+1<n.length&&(r.push(n[e]),i.push(n[e+1]));if(r.length===0||i.length===0)return 0;let a=Math.min(...r),o=Math.max(...r),s=Math.min(...i),c=Math.max(...i);return(o-a)*(c-s)}function VC(e,t){let n=new bC(e,!1);for(let e of n.instructions)t.instructions.push(e)}var HC=s((()=>{xC()}));function UC(e,t){if(typeof e==`string`){let t=document.createElement(`div`);t.innerHTML=e.trim(),e=t.querySelector(`svg`)}let n={context:t,defs:{},path:new bC};wC(e,n);let r=e.children,{fillStyle:i,strokeStyle:a}=NC(e,n);for(let e=0;e<r.length;e++){let t=r[e];t.nodeName.toLowerCase()!==`defs`&&WC(t,n,i,a)}return t}function WC(e,t,n,r){let i=e.children,{fillStyle:a,strokeStyle:o}=NC(e,t);a&&n?n={...n,...a}:a&&(n=a),o&&r?r={...r,...o}:o&&(r=o);let s=!n&&!r;s&&(n={color:0});let c,l,u,d,f,p,m,h,g,_,v,y,b,x,S,C,w;switch(e.nodeName.toLowerCase()){case`path`:{x=e.getAttribute(`d`);let i=e.getAttribute(`fill-rule`),a=zC(x),o=i===`evenodd`,s=a.length>1;if(o&&s){let e=a.map(e=>({path:e,area:BC(e)}));if(e.sort((e,t)=>t.area-e.area),a.length>3||!LC(e))for(let i=0;i<e.length;i++){let a=e[i],o=i===0;t.context.beginPath();let s=new bC(void 0,!0);VC(a.path,s),t.context.path(s),o?(n&&t.context.fill(n),r&&t.context.stroke(r)):t.context.cut()}else for(let i=0;i<e.length;i++){let a=e[i],o=i%2==1;t.context.beginPath();let s=new bC(void 0,!0);VC(a.path,s),t.context.path(s),o?t.context.cut():(n&&t.context.fill(n),r&&t.context.stroke(r))}}else S=new bC(x,!i||i===`evenodd`),t.context.path(S),n&&t.context.fill(n),r&&t.context.stroke(r);break}case`circle`:m=SC(e,`cx`,0),h=SC(e,`cy`,0),g=SC(e,`r`,0),t.context.ellipse(m,h,g,g),n&&t.context.fill(n),r&&t.context.stroke(r);break;case`rect`:c=SC(e,`x`,0),l=SC(e,`y`,0),C=SC(e,`width`,0),w=SC(e,`height`,0),_=SC(e,`rx`,0),v=SC(e,`ry`,0),_||v?t.context.roundRect(c,l,C,w,_||v):t.context.rect(c,l,C,w),n&&t.context.fill(n),r&&t.context.stroke(r);break;case`ellipse`:m=SC(e,`cx`,0),h=SC(e,`cy`,0),_=SC(e,`rx`,0),v=SC(e,`ry`,0),t.context.beginPath(),t.context.ellipse(m,h,_,v),n&&t.context.fill(n),r&&t.context.stroke(r);break;case`line`:u=SC(e,`x1`,0),d=SC(e,`y1`,0),f=SC(e,`x2`,0),p=SC(e,`y2`,0),t.context.beginPath(),t.context.moveTo(u,d),t.context.lineTo(f,p),r&&t.context.stroke(r);break;case`polygon`:b=e.getAttribute(`points`),y=b.match(/-?\d+/g).map(e=>parseInt(e,10)),t.context.poly(y,!0),n&&t.context.fill(n),r&&t.context.stroke(r);break;case`polyline`:b=e.getAttribute(`points`),y=b.match(/-?\d+/g).map(e=>parseInt(e,10)),t.context.poly(y,!1),r&&t.context.stroke(r);break;case`g`:case`svg`:break;default:z(`[SVG parser] <${e.nodeName}> elements unsupported`)}s&&(n=null);for(let e=0;e<i.length;e++)WC(i[e],t,n,r)}var GC=s((()=>{B(),xC(),AC(),CC(),IC(),RC(),HC()}));function KC(e){return P.isColorLike(e)}function qC(e){return e instanceof Tx}function JC(e){return e instanceof xx}function YC(e){return e instanceof U}function XC(e,t,n){let r=P.shared.setValue(t??0);return e.color=r.toNumber(),e.alpha=r.alpha===1?n.alpha:r.alpha,e.texture=U.WHITE,{...n,...e}}function ZC(e,t,n){return e.texture=t,{...n,...e}}function QC(e,t,n){return e.fill=t,e.color=16777215,e.texture=t.texture,e.matrix=t.transform,e.textureSpace=t.textureSpace,{...n,...e}}function $C(e,t,n){return t.buildGradient(),e.fill=t,e.color=16777215,e.texture=t.texture,e.matrix=t.transform,e.textureSpace=t.textureSpace,{...n,...e}}function ew(e,t){let n={...t,...e},r=P.shared.setValue(n.color);return n.alpha*=r.alpha,n.color=r.toNumber(),n}function tw(e,t){if(e==null)return null;let n={},r=e;return KC(e)?XC(n,e,t):YC(e)?ZC(n,e,t):qC(e)?QC(n,e,t):JC(e)?$C(n,e,t):r.fill&&qC(r.fill)?QC(r,r.fill,t):r.fill&&JC(r.fill)?$C(r,r.fill,t):ew(r,t)}function nw(e,t){let{width:n,alignment:r,miterLimit:i,cap:a,join:o,pixelLine:s,...c}=t,l=tw(e,c);return l?{width:n,alignment:r,miterLimit:i,cap:a,join:o,pixelLine:s,...l}:null}var rw=s((()=>{Ar(),W(),Sx(),Ex()}));function iw(e,t){let n=1,r=e.shapePath.shapePrimitives;for(let e=0;e<r.length;e++){let i=r[e].shape;if(i.type!==`polygon`)continue;let a=i.points,o=a.length;if(o<6)continue;let s=i.closePath;for(let e=0;e<o;e+=2){if(!s&&(e===0||e===o-2))continue;let r=(e-2+o)%o,i=(e+2)%o,c=a[r],l=a[r+1],u=a[e],d=a[e+1],f=a[i],p=a[i+1],m=c-u,h=l-d,g=f-u,_=p-d,v=m*m+h*h,y=g*g+_*_;if(v<1e-12||y<1e-12)continue;let b=(m*g+h*_)/Math.sqrt(v*y);b<-1?b=-1:b>1&&(b=1);let x=Math.sqrt((1-b)*.5);if(x<1e-6)continue;let S=Math.min(1/x,t);S>n&&(n=S)}}return n}var aw=s((()=>{})),ow,sw,cw,lw,uw=s((()=>{Xn(),Ar(),I(),zr(),W(),Kr(),Xr(),Di(),xC(),GC(),rw(),aw(),ow=new Lr,sw=new F,cw=class e extends Yn{constructor(){super(...arguments),this._gpuData=Object.create(null),this.autoGarbageCollect=!0,this._gcLastUsed=-1,this.uid=Wr(`graphicsContext`),this.dirty=!0,this.batchMode=`auto`,this.instructions=[],this.destroyed=!1,this._activePath=new bC,this._transform=new F,this._fillStyle={...e.defaultFillStyle},this._strokeStyle={...e.defaultStrokeStyle},this._stateStack=[],this._tick=0,this._bounds=new Ei,this._boundsDirty=!0}clone(){let t=new e;return t.batchMode=this.batchMode,t.instructions=this.instructions.slice(),t._activePath=this._activePath.clone(),t._transform=this._transform.clone(),t._fillStyle={...this._fillStyle},t._strokeStyle={...this._strokeStyle},t._stateStack=this._stateStack.slice(),t._bounds=this._bounds.clone(),t._boundsDirty=!0,t}get fillStyle(){return this._fillStyle}set fillStyle(t){this._fillStyle=tw(t,e.defaultFillStyle)}get strokeStyle(){return this._strokeStyle}set strokeStyle(t){this._strokeStyle=nw(t,e.defaultStrokeStyle)}setFillStyle(t){return this._fillStyle=tw(t,e.defaultFillStyle),this}setStrokeStyle(t){return this._strokeStyle=tw(t,e.defaultStrokeStyle),this}texture(e,t,n,r,i,a){return this.instructions.push({action:`texture`,data:{image:e,dx:n||0,dy:r||0,dw:i||e.frame.width,dh:a||e.frame.height,transform:this._transform.clone(),alpha:this._fillStyle.alpha,style:t||t===0?P.shared.setValue(t).toNumber():16777215}}),this.onUpdate(),this}beginPath(){return this._activePath=new bC,this}fill(t,n){let r,i=this.instructions[this.instructions.length-1];return r=this._tick===0&&i?.action===`stroke`?i.data.path:this._activePath.clone(),r?(t!=null&&(n!==void 0&&typeof t==`number`&&(R(L,`GraphicsContext.fill(color, alpha) is deprecated, use GraphicsContext.fill({ color, alpha }) instead`),t={color:t,alpha:n}),this._fillStyle=tw(t,e.defaultFillStyle)),this.instructions.push({action:`fill`,data:{style:this.fillStyle,path:r}}),this.onUpdate(),this._initNextPathLocation(),this._tick=0,this):this}_initNextPathLocation(){let{x:e,y:t}=this._activePath.getLastPoint(Lr.shared);this._activePath.clear(),this._activePath.moveTo(e,t)}stroke(t){let n,r=this.instructions[this.instructions.length-1];return n=this._tick===0&&r?.action===`fill`?r.data.path:this._activePath.clone(),n?(t!=null&&(this._strokeStyle=nw(t,e.defaultStrokeStyle)),this.instructions.push({action:`stroke`,data:{style:this.strokeStyle,path:n}}),this.onUpdate(),this._initNextPathLocation(),this._tick=0,this):this}cut(){for(let e=0;e<2;e++){let t=this.instructions[this.instructions.length-1-e],n=this._activePath.clone();if(t&&(t.action===`stroke`||t.action===`fill`)){if(t.data.hole)t.data.hole.addPath(n);else{t.data.hole=n;break}}}return this._initNextPathLocation(),this}arc(e,t,n,r,i,a){this._tick++;let o=this._transform;return this._activePath.arc(o.a*e+o.c*t+o.tx,o.b*e+o.d*t+o.ty,n,r,i,a),this}arcTo(e,t,n,r,i){this._tick++;let a=this._transform;return this._activePath.arcTo(a.a*e+a.c*t+a.tx,a.b*e+a.d*t+a.ty,a.a*n+a.c*r+a.tx,a.b*n+a.d*r+a.ty,i),this}arcToSvg(e,t,n,r,i,a,o){this._tick++;let s=this._transform;return this._activePath.arcToSvg(e,t,n,r,i,s.a*a+s.c*o+s.tx,s.b*a+s.d*o+s.ty),this}bezierCurveTo(e,t,n,r,i,a,o){this._tick++;let s=this._transform;return this._activePath.bezierCurveTo(s.a*e+s.c*t+s.tx,s.b*e+s.d*t+s.ty,s.a*n+s.c*r+s.tx,s.b*n+s.d*r+s.ty,s.a*i+s.c*a+s.tx,s.b*i+s.d*a+s.ty,o),this}closePath(){return this._tick++,this._activePath?.closePath(),this}ellipse(e,t,n,r){return this._tick++,this._activePath.ellipse(e,t,n,r,this._transform.clone()),this}circle(e,t,n){return this._tick++,this._activePath.circle(e,t,n,this._transform.clone()),this}path(e){return this._tick++,this._activePath.addPath(e,this._transform.clone()),this}lineTo(e,t){this._tick++;let n=this._transform;return this._activePath.lineTo(n.a*e+n.c*t+n.tx,n.b*e+n.d*t+n.ty),this}moveTo(e,t){this._tick++;let n=this._transform,r=this._activePath.instructions,i=n.a*e+n.c*t+n.tx,a=n.b*e+n.d*t+n.ty;return r.length===1&&r[0].action===`moveTo`?(r[0].data[0]=i,r[0].data[1]=a,this):(this._activePath.moveTo(i,a),this)}quadraticCurveTo(e,t,n,r,i){this._tick++;let a=this._transform;return this._activePath.quadraticCurveTo(a.a*e+a.c*t+a.tx,a.b*e+a.d*t+a.ty,a.a*n+a.c*r+a.tx,a.b*n+a.d*r+a.ty,i),this}rect(e,t,n,r){return this._tick++,this._activePath.rect(e,t,n,r,this._transform.clone()),this}roundRect(e,t,n,r,i){return this._tick++,this._activePath.roundRect(e,t,n,r,i,this._transform.clone()),this}poly(e,t){return this._tick++,this._activePath.poly(e,t,this._transform.clone()),this}regularPoly(e,t,n,r,i=0,a){return this._tick++,this._activePath.regularPoly(e,t,n,r,i,a),this}roundPoly(e,t,n,r,i,a){return this._tick++,this._activePath.roundPoly(e,t,n,r,i,a),this}roundShape(e,t,n,r){return this._tick++,this._activePath.roundShape(e,t,n,r),this}filletRect(e,t,n,r,i){return this._tick++,this._activePath.filletRect(e,t,n,r,i),this}chamferRect(e,t,n,r,i,a){return this._tick++,this._activePath.chamferRect(e,t,n,r,i,a),this}star(e,t,n,r,i=0,a=0){return this._tick++,this._activePath.star(e,t,n,r,i,a,this._transform.clone()),this}svg(e){return this._tick++,UC(e,this),this}restore(){let e=this._stateStack.pop();return e&&(this._transform=e.transform,this._fillStyle=e.fillStyle,this._strokeStyle=e.strokeStyle),this}save(){return this._stateStack.push({transform:this._transform.clone(),fillStyle:{...this._fillStyle},strokeStyle:{...this._strokeStyle}}),this}getTransform(){return this._transform}resetTransform(){return this._transform.identity(),this}rotate(e){return this._transform.rotate(e),this}scale(e,t=e){return this._transform.scale(e,t),this}setTransform(e,t,n,r,i,a){return e instanceof F?(this._transform.set(e.a,e.b,e.c,e.d,e.tx,e.ty),this):(this._transform.set(e,t,n,r,i,a),this)}transform(e,t,n,r,i,a){return e instanceof F?(this._transform.append(e),this):(sw.set(e,t,n,r,i,a),this._transform.append(sw),this)}translate(e,t=e){return this._transform.translate(e,t),this}clear(){return this._activePath.clear(),this.instructions.length=0,this.resetTransform(),this.onUpdate(),this}onUpdate(){this._boundsDirty=!0,this.dirty=!0,this.emit(`update`,this,16)}get bounds(){if(!this._boundsDirty)return this._bounds;this._boundsDirty=!1;let e=this._bounds;e.clear();for(let t=0;t<this.instructions.length;t++){let n=this.instructions[t],r=n.action;if(r===`fill`){let t=n.data;e.addBounds(t.path.bounds)}else if(r===`texture`){let t=n.data;e.addFrame(t.dx,t.dy,t.dx+t.dw,t.dy+t.dh,t.transform)}if(r===`stroke`){let t=n.data,r=t.style.alignment,i=t.style.width*(1-r);t.style.join===`miter`&&(i*=iw(t.path,t.style.miterLimit));let a=t.path.bounds;e.addFrame(a.minX-i,a.minY-i,a.maxX+i,a.maxY+i)}}return e.isValid||e.set(0,0,0,0),e}containsPoint(e){if(!this.bounds.containsPoint(e.x,e.y))return!1;let t=this.instructions,n=!1;for(let r=0;r<t.length;r++){let i=t[r],a=i.data,o=a.path;if(!i.action||!o)continue;let s=a.style,c=o.shapePath.shapePrimitives;for(let t=0;t<c.length;t++){let r=c[t].shape;if(!s||!r)continue;let o=c[t].transform,l=o?o.applyInverse(e,ow):e;if(i.action===`fill`)n=r.contains(l.x,l.y);else{let e=s;n=r.strokeContains(l.x,l.y,e.width,e.alignment)}let u=a.hole;if(u){let e=u.shapePath?.shapePrimitives;if(e)for(let t=0;t<e.length;t++)e[t].shape.contains(l.x,l.y)&&(n=!1)}if(n)return!0}}return n}unload(){this.emit(`unload`,this);for(let e in this._gpuData)this._gpuData[e]?.destroy();this._gpuData=Object.create(null)}destroy(e=!1){if(!this.destroyed){if(this.destroyed=!0,this._stateStack.length=0,this._transform=null,this.unload(),this.emit(`destroy`,this),this.removeAllListeners(),typeof e==`boolean`?e:e?.texture){let t=typeof e==`boolean`?e:e?.textureSource;this._fillStyle.texture&&(this._fillStyle.fill&&`uid`in this._fillStyle.fill?this._fillStyle.fill.destroy():this._fillStyle.texture.destroy(t)),this._strokeStyle.texture&&(this._strokeStyle.fill&&`uid`in this._strokeStyle.fill?this._strokeStyle.fill.destroy():this._strokeStyle.texture.destroy(t))}this._fillStyle=null,this._strokeStyle=null,this.instructions=null,this._activePath=null,this._bounds=null,this._stateStack=null,this.customShader=null,this._transform=null}}},cw.defaultFillStyle={color:16777215,alpha:1,texture:U.WHITE,matrix:null,fill:null,textureSpace:`local`},cw.defaultStrokeStyle={width:1,color:16777215,alpha:1,alignment:.5,miterLimit:10,cap:`butt`,join:`miter`,texture:U.WHITE,matrix:null,fill:null,textureSpace:`local`,pixelLine:!1},lw=cw})),dw,fw,pw,mw,hw=s((()=>{N(),ca(),Tg(),dw=class{constructor(){this.isBatchable=!1}reset(){this.isBatchable=!1,this.context=null,this.graphicsData&&=(this.graphicsData.destroy(),null)}destroy(){this.reset()}},fw=class{constructor(){this.instructions=new sa}init(){this.instructions.reset()}destroy(){this.instructions.destroy(),this.instructions=null}},pw=class e{constructor(e){this._renderer=e,this._managedContexts=new wg({renderer:e,type:`resource`,name:`graphicsContext`})}init(t){e.defaultOptions.bezierSmoothness=t?.bezierSmoothness??e.defaultOptions.bezierSmoothness}getContextRenderData(e){return this.getGpuContext(e).graphicsData||this._initContextRenderData(e)}updateGpuContext(e){let t=e._gpuData,n=!!t[this._renderer.uid],r=t[this._renderer.uid]||this._initContext(e);return(e.dirty||!n)&&(n&&r.reset(),r.isBatchable=!1,e.dirty=!1),r}getGpuContext(e){return e._gpuData[this._renderer.uid]||this._initContext(e)}_initContextRenderData(e){let t=new fw,n=this.getGpuContext(e);return n.graphicsData=t,t.init(),t}_initContext(e){let t=new dw;return t.context=e,e._gpuData[this._renderer.uid]=t,this._managedContexts.add(e),t}destroy(){this._managedContexts.destroy(),this._renderer=null}},pw.extension={type:[j.CanvasSystem],name:`graphicsContext`},pw.defaultOptions={bezierSmoothness:.5},mw=pw})),gw,_w=s((()=>{N(),Nu(),Tg(),gw=class{constructor(e,t){this.state=Mu.for2d(),this.renderer=e,this._adaptor=t,this.renderer.runners.contextChange.add(this),this._managedGraphics=new wg({renderer:e,type:`renderable`,priority:-1,name:`graphics`})}contextChange(){this._adaptor.contextChange(this.renderer)}validateRenderable(e){return!1}addRenderable(e,t){this._managedGraphics.add(e),this.renderer.renderPipes.batch.break(t),t.add(e)}updateRenderable(e){}execute(e){e.isRenderable&&this._adaptor.execute(this,e)}destroy(){this._managedGraphics.destroy(),this.renderer=null,this._adaptor.destroy(),this._adaptor=null}},gw.extension={type:[j.CanvasPipes],name:`graphics`}})),vw,yw,bw=s((()=>{N(),Nu(),Tg(),ai(),qh(),Px(),vw=class{constructor(){this.batches=[],this.batched=!1}destroy(){this.batches.forEach(e=>{ii.return(e)}),this.batches.length=0}},yw=class{constructor(e,t){this.state=Mu.for2d(),this.renderer=e,this._adaptor=t,this.renderer.runners.contextChange.add(this),this._managedGraphics=new wg({renderer:e,type:`renderable`,priority:-1,name:`graphics`})}contextChange(){this._adaptor.contextChange(this.renderer)}validateRenderable(e){let t=e.context,n=!!e._gpuData,r=this.renderer.graphicsContext.updateGpuContext(t);return!!(r.isBatchable||n!==r.isBatchable)}addRenderable(e,t){let n=this.renderer.graphicsContext.updateGpuContext(e.context);e.didViewUpdate&&this._rebuild(e),n.isBatchable?this._addToBatcher(e,t):(this.renderer.renderPipes.batch.break(t),t.add(e))}updateRenderable(e){let t=this._getGpuDataForRenderable(e).batches;for(let e=0;e<t.length;e++){let n=t[e];n._batcher.updateElement(n)}}execute(e){if(!e.isRenderable)return;let t=this.renderer,n=e.context;if(!t.graphicsContext.getGpuContext(n).batches.length)return;let r=n.customShader||this._adaptor.shader;this.state.blendMode=e.groupBlendMode;let i=r.resources.localUniforms.uniforms;i.uTransformMatrix=e.groupTransform,i.uRound=t._roundPixels|e._roundPixels,Kh(e.groupColorAlpha,i.uColor,0),this._adaptor.execute(this,e)}_rebuild(e){let t=this._getGpuDataForRenderable(e),n=this.renderer.graphicsContext.updateGpuContext(e.context);t.destroy(),n.isBatchable&&this._updateBatchesForRenderable(e,t)}_addToBatcher(e,t){let n=this.renderer.renderPipes.batch,r=this._getGpuDataForRenderable(e).batches;for(let e=0;e<r.length;e++){let i=r[e];n.addToBatch(i,t)}}_getGpuDataForRenderable(e){return e._gpuData[this.renderer.uid]||this._initGpuDataForRenderable(e)}_initGpuDataForRenderable(e){let t=new vw;return e._gpuData[this.renderer.uid]=t,this._managedGraphics.add(e),t}_updateBatchesForRenderable(e,t){let n=e.context,r=this.renderer.graphicsContext.getGpuContext(n),i=this.renderer._roundPixels|e._roundPixels;t.batches=r.batches.map(t=>{let n=ii.get(Nx);return t.copyTo(n),n.renderable=e,n.roundPixels=i,n})}destroy(){this._managedGraphics.destroy(),this.renderer=null,this._adaptor.destroy(),this._adaptor=null,this.state=null}},yw.extension={type:[j.WebGLPipes,j.WebGPUPipes],name:`graphics`}})),xw=s((()=>{N(),hw(),_w(),BS(),bw(),M.add(gw),M.add(yw),M.add(mw),M.add(zS)})),Sw,Cw=s((()=>{Xr(),Yo(),uw(),xw(),Sw=class e extends Jo{constructor(e){e instanceof lw&&(e={context:e});let{context:t,roundPixels:n,...r}=e||{};super({label:`Graphics`,...r}),this.renderPipeId=`graphics`,t?this.context=t:(this.context=this._ownedContext=new lw,this.context.autoGarbageCollect=this.autoGarbageCollect),this.didViewUpdate=!0,this.allowChildren=!1,this.roundPixels=n??!1}set context(e){e!==this._context&&(this._context&&(this._context.off(`update`,this.onViewUpdate,this),this._context.off(`unload`,this.unload,this)),this._context=e,this._context.on(`update`,this.onViewUpdate,this),this._context.on(`unload`,this.unload,this),this.onViewUpdate())}get context(){return this._context}get bounds(){return this._context.bounds}updateBounds(){}containsPoint(e){return this._context.containsPoint(e)}destroy(e){this._ownedContext&&!e?this._ownedContext.destroy(e):(e===!0||e?.context===!0)&&this._context.destroy(e),this._context?.off(`update`,this.onViewUpdate,this),this._context?.off(`unload`,this.unload,this),this._ownedContext=null,this._context=null,super.destroy(e)}_onTouch(e){this._gcLastUsed=e,this._context._gcLastUsed=e}_callContextMethod(e,t){return this.context[e](...t),this}setFillStyle(...e){return this._callContextMethod(`setFillStyle`,e)}setStrokeStyle(...e){return this._callContextMethod(`setStrokeStyle`,e)}fill(...e){return this._callContextMethod(`fill`,e)}stroke(...e){return this._callContextMethod(`stroke`,e)}texture(...e){return this._callContextMethod(`texture`,e)}beginPath(){return this._callContextMethod(`beginPath`,[])}cut(){return this._callContextMethod(`cut`,[])}arc(...e){return this._callContextMethod(`arc`,e)}arcTo(...e){return this._callContextMethod(`arcTo`,e)}arcToSvg(...e){return this._callContextMethod(`arcToSvg`,e)}bezierCurveTo(...e){return this._callContextMethod(`bezierCurveTo`,e)}closePath(){return this._callContextMethod(`closePath`,[])}ellipse(...e){return this._callContextMethod(`ellipse`,e)}circle(...e){return this._callContextMethod(`circle`,e)}path(...e){return this._callContextMethod(`path`,e)}lineTo(...e){return this._callContextMethod(`lineTo`,e)}moveTo(...e){return this._callContextMethod(`moveTo`,e)}quadraticCurveTo(...e){return this._callContextMethod(`quadraticCurveTo`,e)}rect(...e){return this._callContextMethod(`rect`,e)}roundRect(...e){return this._callContextMethod(`roundRect`,e)}poly(...e){return this._callContextMethod(`poly`,e)}regularPoly(...e){return this._callContextMethod(`regularPoly`,e)}roundPoly(...e){return this._callContextMethod(`roundPoly`,e)}roundShape(...e){return this._callContextMethod(`roundShape`,e)}filletRect(...e){return this._callContextMethod(`filletRect`,e)}chamferRect(...e){return this._callContextMethod(`chamferRect`,e)}star(...e){return this._callContextMethod(`star`,e)}svg(...e){return this._callContextMethod(`svg`,e)}restore(...e){return this._callContextMethod(`restore`,e)}save(){return this._callContextMethod(`save`,[])}getTransform(){return this.context.getTransform()}resetTransform(){return this._callContextMethod(`resetTransform`,[])}rotateTransform(...e){return this._callContextMethod(`rotate`,e)}scaleTransform(...e){return this._callContextMethod(`scale`,e)}setTransform(...e){return this._callContextMethod(`setTransform`,e)}transform(...e){return this._callContextMethod(`transform`,e)}translateTransform(...e){return this._callContextMethod(`translate`,e)}clear(){return this._callContextMethod(`clear`,[])}get fillStyle(){return this._context.fillStyle}set fillStyle(e){this._context.fillStyle=e}get strokeStyle(){return this._context.strokeStyle}set strokeStyle(e){this._context.strokeStyle=e}clone(t=!1){return t?new e(this._context.clone()):(this._ownedContext=null,new e(this._context))}lineStyle(e,t,n){R(L,`Graphics#lineStyle is no longer needed. Use Graphics#setStrokeStyle to set the stroke style.`);let r={};return e&&(r.width=e),t&&(r.color=t),n&&(r.alpha=n),this.context.strokeStyle=r,this}beginFill(e,t){R(L,`Graphics#beginFill is no longer needed. Use Graphics#fill to fill the shape with the desired style.`);let n={};return e!==void 0&&(n.color=e),t!==void 0&&(n.alpha=t),this.context.fillStyle=n,this}endFill(){R(L,`Graphics#endFill is no longer needed. Use Graphics#fill to fill the shape with the desired style.`),this.context.fill();let e=this.context.strokeStyle;return(e.width!==lw.defaultStrokeStyle.width||e.color!==lw.defaultStrokeStyle.color||e.alpha!==lw.defaultStrokeStyle.alpha)&&this.context.stroke(),this}drawCircle(...e){return R(L,`Graphics#drawCircle has been renamed to Graphics#circle`),this._callContextMethod(`circle`,e)}drawEllipse(...e){return R(L,`Graphics#drawEllipse has been renamed to Graphics#ellipse`),this._callContextMethod(`ellipse`,e)}drawPolygon(...e){return R(L,`Graphics#drawPolygon has been renamed to Graphics#poly`),this._callContextMethod(`poly`,e)}drawRect(...e){return R(L,`Graphics#drawRect has been renamed to Graphics#rect`),this._callContextMethod(`rect`,e)}drawRoundedRect(...e){return R(L,`Graphics#drawRoundedRect has been renamed to Graphics#roundRect`),this._callContextMethod(`roundRect`,e)}drawStar(...e){return R(L,`Graphics#drawStar has been renamed to Graphics#star`),this._callContextMethod(`star`,e)}}}));function ww(e,t,n,r,i,a){a=Math.max(0,Math.min(a,Math.min(r,i)/2)),e.moveTo(t+a,n),e.lineTo(t+r-a,n),e.quadraticCurveTo(t+r,n,t+r,n+a),e.lineTo(t+r,n+i-a),e.quadraticCurveTo(t+r,n+i,t+r-a,n+i),e.lineTo(t+a,n+i),e.quadraticCurveTo(t,n+i,t,n+i-a),e.lineTo(t,n+a),e.quadraticCurveTo(t,n,t+a,n)}function Tw(e,t){switch(t.type){case`rectangle`:{let n=t;e.rect(n.x,n.y,n.width,n.height);break}case`roundedRectangle`:{let n=t;ww(e,n.x,n.y,n.width,n.height,n.radius);break}case`circle`:{let n=t;e.moveTo(n.x+n.radius,n.y),e.arc(n.x,n.y,n.radius,0,Math.PI*2);break}case`ellipse`:{let n=t;e.ellipse?(e.moveTo(n.x+n.halfWidth,n.y),e.ellipse(n.x,n.y,n.halfWidth,n.halfHeight,0,0,Math.PI*2)):(e.save(),e.translate(n.x,n.y),e.scale(n.halfWidth,n.halfHeight),e.moveTo(1,0),e.arc(0,0,1,0,Math.PI*2),e.restore());break}case`triangle`:{let n=t;e.moveTo(n.x,n.y),e.lineTo(n.x2,n.y2),e.lineTo(n.x3,n.y3),e.closePath();break}default:{let n=t,r=n.points;if(!r?.length)break;e.moveTo(r[0],r[1]);for(let t=2;t<r.length;t+=2)e.lineTo(r[t],r[t+1]);n.closePath&&e.closePath();break}}}function Ew(e,t,n){let r=[],i=[],a=[];if(!aS[t.type]?.build(t,r))return!1;mx(r,n,!1,t.closePath??!0,i,a);for(let t=0;t<a.length;t+=3){let n=a[t]*2,r=a[t+1]*2,o=a[t+2]*2;e.moveTo(i[n],i[n+1]),e.lineTo(i[r],i[r+1]),e.lineTo(i[o],i[o+1]),e.closePath()}return!0}function Dw(e,t){if(!t?.length)return!1;for(let n=0;n<t.length;n++){let r=t[n];if(!r?.shape)continue;let i=r.transform,a=i&&!i.isIdentity();a&&(e.save(),e.transform(i.a,i.b,i.c,i.d,i.tx,i.ty)),Tw(e,r.shape),a&&e.restore()}return!0}var Ow,kw=s((()=>{N(),hx(),Cw(),cS(),B(),Ow=class{constructor(e){this._warnedMaskTypes=new Set,this._canvasMaskStack=[],this._renderer=e}push(e,t,n){this._renderer.renderPipes.batch.break(n),n.add({renderPipeId:`stencilMask`,action:`pushMaskBegin`,mask:e,inverse:t._maskOptions.inverse,canBundle:!1})}pop(e,t,n){this._renderer.renderPipes.batch.break(n),n.add({renderPipeId:`stencilMask`,action:`popMaskEnd`,mask:e,inverse:t._maskOptions.inverse,canBundle:!1})}execute(e){if(e.action!==`pushMaskBegin`&&e.action!==`popMaskEnd`)return;let t=this._renderer,n=t.canvasContext,r=n?.activeContext;if(!r)return;if(e.action===`popMaskEnd`){this._canvasMaskStack.pop()&&r.restore();return}e.inverse&&this._warnOnce(`inverse`,`CanvasRenderer: inverse masks are not supported on Canvas2D; ignoring inverse flag.`);let i=e.mask.mask;if(!(i instanceof Sw)){this._warnOnce(`nonGraphics`,`CanvasRenderer: only Graphics masks are supported in Canvas2D; skipping mask.`),this._canvasMaskStack.push(!1);return}let a=i,o=a.context?.instructions;if(!o?.length){this._canvasMaskStack.push(!1);return}r.save(),n.setContextTransform(a.groupTransform,(t._roundPixels|a._roundPixels)===1),r.beginPath();let s=!1,c=!1;for(let e=0;e<o.length;e++){let t=o[e],n=t.action;if(n!==`fill`&&n!==`stroke`)continue;let i=t.data,a=i?.path?.shapePath;if(!a?.shapePrimitives?.length)continue;let l=n===`stroke`,u=a.shapePrimitives;for(let e=0;e<u.length;e++){let t=u[e];if(!t?.shape)continue;let n=t.transform,a=n&&!n.isIdentity();a&&(r.save(),r.transform(n.a,n.b,n.c,n.d,n.tx,n.ty)),l&&i.style?s=Ew(r,t.shape,i.style)||s:(Tw(r,t.shape),c=Dw(r,t.holes)||c,s=!0),a&&r.restore()}}if(!s){r.restore(),this._canvasMaskStack.push(!1);return}c?r.clip(`evenodd`):r.clip(),this._canvasMaskStack.push(!0)}destroy(){this._renderer=null,this._warnedMaskTypes=null,this._canvasMaskStack=null}_warnOnce(e,t){this._warnedMaskTypes.has(e)||(this._warnedMaskTypes.add(e),z(t))}},Ow.extension={type:[j.CanvasPipes],name:`stencilMask`}}));function Aw(){let e=Mc(),t=Object.create(null);return t.inherit=jw,t.none=jw,t.normal=`source-over`,t.add=`lighter`,t.multiply=e?`multiply`:jw,t.screen=e?`screen`:jw,t.overlay=e?`overlay`:jw,t.darken=e?`darken`:jw,t.lighten=e?`lighten`:jw,t[`color-dodge`]=e?`color-dodge`:jw,t[`color-burn`]=e?`color-burn`:jw,t[`hard-light`]=e?`hard-light`:jw,t[`soft-light`]=e?`soft-light`:jw,t.difference=e?`difference`:jw,t.exclusion=e?`exclusion`:jw,t.saturation=e?`saturation`:jw,t.color=e?`color`:jw,t.luminosity=e?`luminosity`:jw,t[`linear-burn`]=e?`color-burn`:jw,t[`linear-dodge`]=e?`color-dodge`:jw,t[`linear-light`]=e?`hard-light`:jw,t[`pin-light`]=e?`hard-light`:jw,t[`vivid-light`]=e?`hard-light`:jw,t[`hard-mix`]=jw,t.negation=e?`difference`:jw,t[`normal-npm`]=t.normal,t[`add-npm`]=t.add,t[`screen-npm`]=t.screen,t.erase=`destination-out`,t.subtract=jw,t.divide=jw,t.min=jw,t.max=jw,t}var jw,Mw=s((()=>{Pc(),jw=`source-over`})),Nw,Pw,Fw=s((()=>{Ar(),N(),I(),Mw(),Nw=new F,Pw=class{constructor(e){this.activeResolution=1,this.smoothProperty=`imageSmoothingEnabled`,this.blendModes=Aw(),this._activeBlendMode=`normal`,this._projTransform=null,this._outerBlend=!1,this._warnedBlendModes=new Set,this._renderer=e}resolutionChange(e){this.activeResolution=e}init(){let e=this._renderer.background.alpha<1;if(this.rootContext=this._renderer.canvas.getContext(`2d`,{alpha:e}),this.activeContext=this.rootContext,this.activeResolution=this._renderer.resolution,!this.rootContext.imageSmoothingEnabled){let e=this.rootContext;e.webkitImageSmoothingEnabled?this.smoothProperty=`webkitImageSmoothingEnabled`:e.mozImageSmoothingEnabled?this.smoothProperty=`mozImageSmoothingEnabled`:e.oImageSmoothingEnabled?this.smoothProperty=`oImageSmoothingEnabled`:e.msImageSmoothingEnabled&&(this.smoothProperty=`msImageSmoothingEnabled`)}}setContextTransform(e,t,n,r){let i=r?F.IDENTITY:this._renderer.globalUniforms.globalUniformData?.worldTransformMatrix||F.IDENTITY,a=Nw;a.copyFrom(i),a.append(e);let o=this._projTransform,s=this.activeResolution;if(n||=s,o){let e=F.shared;e.copyFrom(a),e.prepend(o),a=e}t?this.activeContext.setTransform(a.a*n,a.b*n,a.c*n,a.d*n,a.tx*s|0,a.ty*s|0):this.activeContext.setTransform(a.a*n,a.b*n,a.c*n,a.d*n,a.tx*s,a.ty*s)}clear(e,t){let n=this.activeContext,r=this._renderer;if(n.clearRect(0,0,r.width,r.height),e){let i=P.shared.setValue(e);n.globalAlpha=t??i.alpha,n.fillStyle=i.toHex(),n.fillRect(0,0,r.width,r.height),n.globalAlpha=1}}setBlendMode(e){if(this._activeBlendMode===e)return;this._activeBlendMode=e,this._outerBlend=!1;let t=this.blendModes[e];if(!t){this._warnedBlendModes.has(e)||(console.warn(`CanvasRenderer: blend mode "${e}" is not supported in Canvas2D; falling back to "source-over".`),this._warnedBlendModes.add(e)),this.activeContext.globalCompositeOperation=`source-over`;return}this.activeContext.globalCompositeOperation=t}destroy(){this.rootContext=null,this.activeContext=null,this._warnedBlendModes.clear()}},Pw.extension={type:[j.CanvasSystem],name:`canvasContext`}})),Iw,Lw=s((()=>{N(),Iw=class{constructor(){this.maxTextures=16,this.maxBatchableTextures=16,this.maxUniformBindings=0}init(){}},Iw.extension={type:[j.CanvasSystem],name:`limits`}})),Rw,zw=s((()=>{Ar(),q(),B(),mc(),Rw=class{init(e,t){this._renderer=e,this._renderTargetSystem=t}initGpuRenderTarget(e){let t=e.colorTexture,{canvas:n,context:r}=this._ensureCanvas(t);return{canvas:n,context:r,width:n.width,height:n.height}}resizeGpuRenderTarget(e){let t=e.colorTexture,{canvas:n}=this._ensureCanvas(t);n.width=e.pixelWidth,n.height=e.pixelHeight}startRenderPass(e,t,n,r){let i=this._renderTargetSystem.getGpuRenderTarget(e);this._renderer.canvasContext.activeContext=i.context,this._renderer.canvasContext.activeResolution=e.resolution,t&&this.clear(e,t,n,r)}clear(e,t,n,r){let i=this._renderTargetSystem.getGpuRenderTarget(e).context,a=r||{x:0,y:0,width:e.pixelWidth,height:e.pixelHeight};if(i.setTransform(1,0,0,1,0,0),i.clearRect(a.x,a.y,a.width,a.height),n){let e=P.shared.setValue(n);e.alpha>0&&(i.globalAlpha=e.alpha,i.fillStyle=e.toHex(),i.fillRect(a.x,a.y,a.width,a.height),i.globalAlpha=1)}}finishRenderPass(){}copyToTexture(e,t,n,r,i){let a=this._renderTargetSystem.getGpuRenderTarget(e).canvas,o=t.source,{context:s}=this._ensureCanvas(o),c=i?.x??0,l=i?.y??0;return s.drawImage(a,n.x,n.y,r.width,r.height,c,l,r.width,r.height),o.update(),t}copyDepthTexture(e,t,n,r,i){z(`[CanvasRenderTargetAdaptor] copyDepthTexture is not supported in the canvas renderer`)}destroyGpuRenderTarget(e){}_ensureCanvas(e){let t=e.resource;(!t||!pc.test(t))&&(t=K.get().createCanvas(e.pixelWidth,e.pixelHeight),e.resource=t),(t.width!==e.pixelWidth||t.height!==e.pixelHeight)&&(t.width=e.pixelWidth,t.height=e.pixelHeight);let n=t.getContext(`2d`);return{canvas:t,context:n}}}})),Bw,Vw=s((()=>{N(),N_(),zw(),Bw=class extends M_{constructor(e){super(e),this.adaptor=new Rw,this.adaptor.init(e,this)}},Bw.extension={type:[j.CanvasSystem],name:`renderTarget`}})),Hw,Uw=s((()=>{q(),N(),Fc(),Hw=class{constructor(e){}init(){}initSource(e){}generateCanvas(e){let t=K.get().createCanvas(),n=t.getContext(`2d`),r=Y.getCanvasSource(e);if(!r)return t;let i=e.frame,a=e.source._resolution??e.source.resolution??1,o=i.x*a,s=i.y*a,c=i.width*a,l=i.height*a;return t.width=Math.ceil(c),t.height=Math.ceil(l),n.drawImage(r,o,s,c,l,0,0,c,l),t}getPixels(e){let t=this.generateCanvas(e);return{pixels:t.getContext(`2d`,{willReadFrequently:!0}).getImageData(0,0,t.width,t.height).data,width:t.width,height:t.height}}destroy(){}},Hw.extension={type:[j.CanvasSystem],name:`texture`}})),Ww=l({CanvasRenderer:()=>Zw}),Gw,Kw,qw,Jw,Yw,Xw,Zw,Qw=s((()=>{N(),Wp(),Xp(),SS(),fm(),TS(),oh(),vh(),DS(),kw(),Oh(),Tf(),xg(),uu(),Fw(),Lw(),Vw(),Uw(),Gw=[...yg,Pw,Iw,Hw,Bw],Kw=[Dh,ah,dm,Yp,_h,Ow,ES,Up],qw=[wS,xS],Jw=[],Yw=[],Xw=[],M.handleByNamedList(j.CanvasSystem,Jw),M.handleByNamedList(j.CanvasPipes,Yw),M.handleByNamedList(j.CanvasPipesAdaptor,Xw),M.add(...Gw,...Kw,...qw),Zw=class extends wf{constructor(){let e={name:`canvas`,type:lu.CANVAS,systems:Jw,renderPipes:Yw,renderPipeAdaptors:Xw};super(e)}}}));Tf();var $w=[`webgl`,`webgpu`,`canvas`];async function eT(e){let t=[];e.preference?Array.isArray(e.preference)?t=e.preference.slice():(t.push(e.preference),$w.forEach(n=>{n!==e.preference&&t.push(n)})):t=$w.slice();let n,r={};for(let i=0;i<t.length;i++){let a=t[i];if(a===`webgpu`&&await kf()){let{WebGPURenderer:t}=await Promise.resolve().then(()=>(Sv(),mv));n=t,r={...e,...e.webgpu};break}if(a===`webgl`&&Df(e.failIfMajorPerformanceCaveat??wf.defaultOptions.failIfMajorPerformanceCaveat)){let{WebGLRenderer:t}=await Promise.resolve().then(()=>(cx(),ex));n=t,r={...e,...e.webgl};break}if(a===`canvas`){let{CanvasRenderer:t}=await Promise.resolve().then(()=>(Qw(),Ww));n=t,r={...e,...e.canvasOptions};break}}if(delete r.webgpu,delete r.webgl,delete r.canvasOptions,!n)throw Error(`No available renderer for the current environment`);let i=new n;return await i.init(r),i}N();var tT=class{static init(e){Object.defineProperty(this,"resizeTo",{configurable:!0,set(e){globalThis.removeEventListener(`resize`,this.queueResize),this._resizeTo=e,e&&(globalThis.addEventListener(`resize`,this.queueResize),this.resize())},get(){return this._resizeTo}}),this.queueResize=()=>{this._resizeTo&&(this._cancelResize(),this._resizeId=requestAnimationFrame(()=>this.resize()))},this._cancelResize=()=>{this._resizeId&&=(cancelAnimationFrame(this._resizeId),null)},this.resize=()=>{if(!this._resizeTo)return;this._cancelResize();let e,t;if(this._resizeTo===globalThis.window)e=globalThis.innerWidth,t=globalThis.innerHeight;else{let{clientWidth:n,clientHeight:r}=this._resizeTo;e=n,t=r}this.renderer.resize(e,t),this.render()},this._resizeId=null,this._resizeTo=null,this.resizeTo=e.resizeTo||null}static destroy(){globalThis.removeEventListener(`resize`,this.queueResize),this._cancelResize(),this._cancelResize=null,this.queueResize=null,this.resizeTo=null,this.resize=null}};tT.extension=j.Application,N(),Qa(),ro();var nT=class{static init(e){e=Object.assign({autoStart:!0,sharedTicker:!1},e),Object.defineProperty(this,"ticker",{configurable:!0,set(e){this._ticker&&this._ticker.remove(this.render,this),this._ticker=e,e&&e.add(this.render,this,Za.LOW)},get(){return this._ticker}}),this.stop=()=>{this._ticker.stop()},this.start=()=>{this._ticker.start()},this._ticker=null,this.ticker=e.sharedTicker?no.shared:new no,e.autoStart&&this.start()}static destroy(){if(this._ticker){let e=this._ticker;this.ticker=null,e.destroy()}}};nT.extension=j.Application,N(),M.add(tT),M.add(nT),N(),Xa(),_m(),Xr();var rT=class e{constructor(...e){this.stage=new G,e[0]!==void 0&&R(L,`Application constructor options are deprecated, please use Application.init() instead.`)}async init(t){t={...t},this.stage||=new G,this.renderer=await eT(t),e._plugins.forEach(e=>{e.init.call(this,t)})}render(){this.renderer.render({container:this.stage})}get canvas(){return this.renderer.canvas}get view(){return R(L,`Application.view is deprecated, please use Application.canvas instead.`),this.renderer.canvas}get screen(){return this.renderer.screen}get domContainerRoot(){return this.renderer.renderPipes.dom?._domElement}destroy(t=!1,n=!1){let r=e._plugins.slice(0);r.reverse(),r.forEach(e=>{e.destroy.call(this)}),this.stage.destroy(n),this.stage=null,this.renderer.destroy(t),this.renderer=null}};rT._plugins=[];var iT=rT;M.handleByList(j.Application,iT._plugins),M.add(hm);var aT={test(e){return typeof e==`string`&&e.startsWith(`info face=`)},parse(e){let t=e.match(/^[a-z]+\s+.+$/gm),n={info:[],common:[],page:[],char:[],chars:[],kerning:[],kernings:[],distanceField:[]};for(let e in t){let r=t[e].match(/^[a-z]+/gm)[0],i=t[e].match(/[a-zA-Z]+=([^\s"']+|"([^"]*)")/gm),a={};for(let e in i){let t=i[e].split(`=`),n=t[0],r=t[1].replace(/"/gm,``),o=parseFloat(r);a[n]=isNaN(o)?r:o}n[r].push(a)}let r={chars:{},pages:[],lineHeight:0,fontSize:0,fontFamily:``,distanceField:null,baseLineOffset:0},[i]=n.info,[a]=n.common,[o]=n.distanceField??[];o&&(r.distanceField={range:parseInt(o.distanceRange,10),type:o.fieldType}),r.fontSize=parseInt(i.size,10),r.fontFamily=i.face,r.lineHeight=parseInt(a.lineHeight,10);let s=n.page;for(let e=0;e<s.length;e++)r.pages.push({id:parseInt(s[e].id,10)||0,file:s[e].file});let c={};r.baseLineOffset=a.base===void 0?0:r.lineHeight-parseInt(a.base,10);let l=n.char;for(let e=0;e<l.length;e++){let t=l[e],n=parseInt(t.id,10),i=t.letter??t.char??String.fromCharCode(n);i===`space`&&(i=` `),c[n]=i,r.chars[i]={id:n,page:parseInt(t.page,10)||0,x:parseInt(t.x,10),y:parseInt(t.y,10),width:parseInt(t.width,10),height:parseInt(t.height,10),xOffset:parseInt(t.xoffset,10),yOffset:parseInt(t.yoffset,10),xAdvance:parseInt(t.xadvance,10),kerning:{}}}let u=n.kerning||[];for(let e=0;e<u.length;e++){let t=parseInt(u[e].first,10),n=parseInt(u[e].second,10),i=parseInt(u[e].amount,10);r.chars[c[n]]&&(r.chars[c[n]].kerning[c[t]]=i)}return r}},oT={test(e){let t=e;return typeof t!=`string`&&`getElementsByTagName`in t&&t.getElementsByTagName(`page`).length&&t.getElementsByTagName(`info`)[0].getAttribute(`face`)!==null},parse(e){let t={chars:{},pages:[],lineHeight:0,fontSize:0,fontFamily:``,distanceField:null,baseLineOffset:0},n=e.getElementsByTagName(`info`)[0],r=e.getElementsByTagName(`common`)[0],i=e.getElementsByTagName(`distanceField`)[0];i&&(t.distanceField={type:i.getAttribute(`fieldType`),range:parseInt(i.getAttribute(`distanceRange`),10)});let a=e.getElementsByTagName(`page`),o=e.getElementsByTagName(`char`),s=e.getElementsByTagName(`kerning`);t.fontSize=parseInt(n.getAttribute(`size`),10),t.fontFamily=n.getAttribute(`face`),t.lineHeight=parseInt(r.getAttribute(`lineHeight`),10);for(let e=0;e<a.length;e++)t.pages.push({id:parseInt(a[e].getAttribute(`id`),10)||0,file:a[e].getAttribute(`file`)});let c={},l=r.getAttribute(`base`);t.baseLineOffset=l===null?0:t.lineHeight-parseInt(l,10);for(let e=0;e<o.length;e++){let n=o[e],r=parseInt(n.getAttribute(`id`),10),i=n.getAttribute(`letter`)??n.getAttribute(`char`)??String.fromCharCode(r);i===`space`&&(i=` `),c[r]=i,t.chars[i]={id:r,page:parseInt(n.getAttribute(`page`),10)||0,x:parseInt(n.getAttribute(`x`),10),y:parseInt(n.getAttribute(`y`),10),width:parseInt(n.getAttribute(`width`),10),height:parseInt(n.getAttribute(`height`),10),xOffset:parseInt(n.getAttribute(`xoffset`),10),yOffset:parseInt(n.getAttribute(`yoffset`),10),xAdvance:parseInt(n.getAttribute(`xadvance`),10),kerning:{}}}for(let e=0;e<s.length;e++){let n=parseInt(s[e].getAttribute(`first`),10),r=parseInt(s[e].getAttribute(`second`),10),i=parseInt(s[e].getAttribute(`amount`),10);t.chars[c[r]]&&(t.chars[c[r]].kerning[c[n]]=i)}return t}};q();var sT={test(e){return typeof e==`string`&&e.match(/<font(\s|>)/)?oT.test(K.get().parseXML(e)):!1},parse(e){return oT.parse(K.get().parseXML(e))}},cT,lT=s((()=>{Xn(),Xr(),cT=class extends Yn{constructor(){super(...arguments),this.chars=Object.create(null),this.lineHeight=0,this.fontFamily=``,this.fontMetrics={fontSize:0,ascent:0,descent:0},this.baseLineOffset=0,this.distanceField={type:`none`,range:0},this.pages=[],this.applyFillAsTint=!0,this.baseMeasurementFontSize=100,this.baseRenderedFontSize=100}get font(){return R(L,`BitmapFont.font is deprecated, please use BitmapFont.fontFamily instead.`),this.fontFamily}get pageTextures(){return R(L,`BitmapFont.pageTextures is deprecated, please use BitmapFont.pages instead.`),this.pages}get size(){return R(L,`BitmapFont.size is deprecated, please use BitmapFont.fontMetrics.fontSize instead.`),this.fontMetrics.fontSize}get distanceFieldRange(){return R(L,`BitmapFont.distanceFieldRange is deprecated, please use BitmapFont.distanceField.range instead.`),this.distanceField.range}get distanceFieldType(){return R(L,`BitmapFont.distanceFieldType is deprecated, please use BitmapFont.distanceField.type instead.`),this.distanceField.type}destroy(e=!1){this.emit(`destroy`,this),this.removeAllListeners();for(let e in this.chars)this.chars[e].texture?.destroy();this.chars=null,e&&(this.pages.forEach(e=>e.texture.destroy(!0)),this.pages=null)}}}));function uT(e=1e3,t=0,n=!1){if(isNaN(e)||e<0)throw TypeError(`Invalid max value`);if(isNaN(t)||t<0)throw TypeError(`Invalid ttl value`);if(typeof n!=`boolean`)throw TypeError(`Invalid resetTtl value`);return new dT(e,t,n)}var dT,fT=s((()=>{dT=class{constructor(e=0,t=0,n=!1){this.first=null,this.items=Object.create(null),this.last=null,this.max=e,this.resetTtl=n,this.size=0,this.ttl=t}clear(){return this.first=null,this.items=Object.create(null),this.last=null,this.size=0,this}delete(e){if(this.has(e)){let t=this.items[e];delete this.items[e],this.size--,t.prev!==null&&(t.prev.next=t.next),t.next!==null&&(t.next.prev=t.prev),this.first===t&&(this.first=t.next),this.last===t&&(this.last=t.prev)}return this}entries(e=this.keys()){let t=Array(e.length);for(let n=0;n<e.length;n++){let r=e[n];t[n]=[r,this.get(r)]}return t}evict(e=!1){if(e||this.size>0){let e=this.first;delete this.items[e.key],--this.size===0?(this.first=null,this.last=null):(this.first=e.next,this.first.prev=null)}return this}expiresAt(e){let t;return this.has(e)&&(t=this.items[e].expiry),t}get(e){let t=this.items[e];if(t!==void 0){if(this.ttl>0&&t.expiry<=Date.now()){this.delete(e);return}return this.moveToEnd(t),t.value}}has(e){return e in this.items}moveToEnd(e){this.last!==e&&(e.prev!==null&&(e.prev.next=e.next),e.next!==null&&(e.next.prev=e.prev),this.first===e&&(this.first=e.next),e.prev=this.last,e.next=null,this.last!==null&&(this.last.next=e),this.last=e,this.first===null&&(this.first=e))}keys(){let e=Array(this.size),t=this.first,n=0;for(;t!==null;)e[n++]=t.key,t=t.next;return e}setWithEvicted(e,t,n=this.resetTtl){let r=null;if(this.has(e))this.set(e,t,!0,n);else{this.max>0&&this.size===this.max&&(r={...this.first},this.evict(!0));let n=this.items[e]={expiry:this.ttl>0?Date.now()+this.ttl:this.ttl,key:e,prev:this.last,next:null,value:t};++this.size===1?this.first=n:this.last.next=n,this.last=n}return r}set(e,t,n=!1,r=this.resetTtl){let i=this.items[e];return n||i!==void 0?(i.value=t,n===!1&&r&&(i.expiry=this.ttl>0?Date.now()+this.ttl:this.ttl),this.moveToEnd(i)):(this.max>0&&this.size===this.max&&this.evict(!0),i=this.items[e]={expiry:this.ttl>0?Date.now()+this.ttl:this.ttl,key:e,prev:this.last,next:null,value:t},++this.size===1?this.first=i:this.last.next=i,this.last=i),this}values(e=this.keys()){let t=Array(e.length);for(let n=0;n<e.length;n++)t[n]=this.get(e[n]);return t}}}));function pT(e){return!!e.tagStyles&&Object.keys(e.tagStyles).length>0}function mT(e){return e.includes(`<`)}function hT(e,t){return e.clone().assign(t)}function gT(e,t){let n=[],r=t.tagStyles;if(!pT(t)||!mT(e))return n.push({text:e,style:t}),n;let i=[t],a=[],o=``,s=0;for(;s<e.length;){let t=e[s];if(t===`<`){let c=e.indexOf(`>`,s);if(c===-1){o+=t,s++;continue}let l=e.indexOf(`<`,s+1);if(l!==-1&&l<c){o+=t,s++;continue}let u=e.slice(s+1,c);if(u.startsWith(`/`)){let t=u.slice(1).trim();if(a.length>0&&a[a.length-1]===t){o.length>0&&(n.push({text:o,style:i[i.length-1]}),o=``),i.pop(),a.pop(),s=c+1;continue}o+=e.slice(s,c+1),s=c+1;continue}{let t=u.trim();if(r[t]){o.length>0&&(n.push({text:o,style:i[i.length-1]}),o=``);let e=i[i.length-1],l=hT(e,r[t]);i.push(l),a.push(t),s=c+1;continue}o+=e.slice(s,c+1),s=c+1;continue}}o+=t,s++}return o.length>0&&n.push({text:o,style:i[i.length-1]}),n}var _T=s((()=>{}));function vT(e){return typeof e==`string`&&OT.has(e.charCodeAt(0))}function yT(e,t){return typeof e==`string`&&AT.has(e.charCodeAt(0))}function bT(e){return typeof e==`string`&&MT.has(e.charCodeAt(0))}function xT(e){return typeof e==`string`&&PT.has(e.charCodeAt(0))}function ST(e){return e===`normal`||e===`pre-line`}function CT(e){return e===`normal`}function wT(e){if(typeof e!=`string`)return``;let t=e.length-1;for(;t>=0&&yT(e[t]);)t--;return t<e.length-1?e.slice(0,t+1):e}function TT(e){let t=[],n=[];if(typeof e!=`string`)return t;for(let r=0;r<e.length;r++){let i=e[r],a=e[r+1];if(yT(i,a)||vT(i)){n.length>0&&(t.push(n.join(``)),n.length=0),i===`\r`&&a===`
908
908
  `?(t.push(`\r
909
909
  `),r++):t.push(i);continue}n.push(i),xT(i)&&a&&!yT(a)&&!vT(a)&&(t.push(n.join(``)),n.length=0)}return n.length>0&&t.push(n.join(``)),t}function ET(e,t,n,r){let i=n(e),a=[];for(let n=0;n<i.length;n++){let o=i[n],s=o,c=1;for(;i[n+c];){let a=i[n+c];if(!r(s,a,e,n,t))o+=a,s=a,c++;else break}n+=c-1,a.push(o)}return a}var DT,OT,kT,AT,jT,MT,NT,PT,FT,IT,LT=s((()=>{DT=[10,13],OT=new Set(DT),kT=[9,32,8192,8193,8194,8195,8196,8197,8198,8200,8201,8202,8287,12288],AT=new Set(kT),jT=[9,32],MT=new Set(jT),NT=[45,8208,8211,8212,173],PT=new Set(NT),FT=/(\r\n|\r|\n)/,IT=/(?:\r\n|\r|\n)/}));function RT(e,t,n,r,i,a,o,s,c){let l=gT(e,t);if(CT(t.whiteSpace))for(let e=0;e<l.length;e++){let t=l[e];l[e]={text:t.text.replace(VT,` `),style:t.style}}let u=[],d=[];for(let e of l){let t=e.text.split(FT);for(let n=0;n<t.length;n++){let r=t[n];r===`\r
910
910
  `||r===`\r`||r===`
911
- `?(u.push(d),d=[]):r.length>0&&d.push({text:r,style:e.style})}}(d.length>0||u.length===0)&&u.push(d);let f=n?zT(u,t,r,a,s,c):u,p=[],m=[],h=[],g=[],_=[],v=0,y=t._fontString,b=o(y);b.fontSize===0&&(b.fontSize=t.fontSize,b.ascent=t.fontSize);let x=``,S=!!t.dropShadow,C=t._stroke?.width||0;for(let e of f){let n=0,a=b.ascent,s=b.descent,c=``;for(let t of e){let e=t.style._fontString,l=o(e);e!==x&&(r.font=e,x=e);let u=i(t.text,t.style.letterSpacing,r);n+=u,a=Math.max(a,l.ascent),s=Math.max(s,l.descent),c+=t.text;let d=t.style._stroke?.width||0;d>C&&(C=d),!S&&t.style.dropShadow&&(S=!0)}e.length===0&&(a=b.ascent,s=b.descent),p.push(n),m.push(a),h.push(s),_.push(c);let l=t.lineHeight||a+s;g.push(l+t.leading),v=Math.max(v,n)}let w=C,T=v+w+(t.dropShadow?t.dropShadow.distance:0),E=0;for(let e=0;e<g.length;e++)E+=g[e];return E=Math.max(E,g[0]+w),{width:T,height:E+(t.dropShadow?t.dropShadow.distance:0),lines:_,lineWidths:p,lineHeight:(t.lineHeight||b.fontSize)+t.leading,maxLineWidth:v,fontProperties:b,runsByLine:f,lineAscents:m,lineDescents:h,lineHeights:g,hasDropShadow:S}}function zT(e,t,n,r,i,a){let{letterSpacing:o,whiteSpace:s,wordWrapWidth:c,breakWords:l}=t,u=ST(s),d=c+o,f={},p=``,m=(e,t)=>{let i=`${e}|${t.styleKey}`,a=f[i];if(a===void 0){let o=t._fontString;o!==p&&(n.font=o,p=o),a=r(e,t.letterSpacing,n)+t.letterSpacing,f[i]=a}return a},h=[];for(let t of e){let e=BT(t),n=h.length,r=t=>{let n=0,r=t;do{let{token:t,style:i}=e[r];n+=m(t,i),r++}while(r<e.length&&e[r].continuesFromPrevious);return n},o=t=>{let n=[],r=t;do n.push({token:e[r].token,style:e[r].style}),r++;while(r<e.length&&e[r].continuesFromPrevious);return n},s=[],c=0,f=!u,p=null,g=()=>{p&&p.text.length>0&&s.push(p),p=null},_=()=>{if(g(),s.length>0){let e=s[s.length-1];e.text=wT(e.text),e.text.length===0&&s.pop()}h.push(s),s=[],c=0,f=!1};for(let t=0;t<e.length;t++){let{token:n,style:v,continuesFromPrevious:y}=e[t],b=m(n,v);if(u){let e=yT(n),t=p?.text[p.text.length-1]??s[s.length-1]?.text.slice(-1)??``,r=t?yT(t):!1;if(e&&r)continue}let x=!y,S=x?r(t):b;if(S>d&&x){if(c>0&&_(),l){let e=o(t);for(let t=0;t<e.length;t++){let n=e[t].token,r=e[t].style,o=ET(n,l,a,i);for(let e of o){let t=m(e,r);t+c>d&&_(),!p||p.style!==r?(g(),p={text:e,style:r}):p.text+=e,c+=t}}t+=e.length-1}else{let e=o(t);g(),h.push(e.map(e=>({text:e.token,style:e.style}))),f=!1,t+=e.length-1}}else if(S+c>d&&x){if(yT(n)){f=!1;continue}_(),p={text:n,style:v},c=b}else if(y&&!l)!p||p.style!==v?(g(),p={text:n,style:v}):p.text+=n,c+=b;else{let e=yT(n);if(c===0&&e&&!f)continue;!p||p.style!==v?(g(),p={text:n,style:v}):p.text+=n,c+=b}}if(g(),s.length>0){let e=s[s.length-1];e.text=wT(e.text),e.text.length===0&&s.pop()}(s.length>0||h.length===n)&&h.push(s)}return h}function BT(e){let t=[],n=!1;for(let r of e){let e=TT(r.text),i=!0;for(let a of e){let e=yT(a)||vT(a),o=i&&n&&!e;t.push({token:a,style:r.style,continuesFromPrevious:o}),n=!e,i=!1}}return t}var VT,HT=s((()=>{_T(),LT(),VT=/\r\n|\r|\n/g}));function UT(e,t,n,r,i){let a=n[e];return typeof a!=`number`&&(a=i(e,t,r)+t,n[e]=a),a}function WT(e,t,n,r,i,a,o){let s=n.getContext(`2d`,GT);s.font=t._fontString;let c=0,l=``,u=[],d=Object.create(null),{letterSpacing:f,whiteSpace:p}=t,m=ST(p),h=CT(p),g=!m,_=t.wordWrapWidth+f,v=TT(e);for(let e=0;e<v.length;e++){let n=v[e];if(vT(n)){if(!h){u.push(wT(l)),g=!m,l=``,c=0;continue}n=` `}if(m){let e=yT(n),t=yT(l[l.length-1]);if(e&&t)continue}let p=UT(n,f,d,s,r);if(p>_){if(l!==``&&(u.push(wT(l)),l=``,c=0),i(n,t.breakWords)){let e=ET(n,t.breakWords,o,a);for(let t of e){let e=UT(t,f,d,s,r);e+c>_&&(u.push(wT(l)),g=!1,l=``,c=0),l+=t,c+=e}}else l.length>0&&(u.push(wT(l)),l=``,c=0),u.push(wT(n)),g=!1,l=``,c=0}else p+c>_&&(g=!1,u.push(wT(l)),l=``,c=0),(l.length>0||!yT(n)||g)&&(l+=n,c+=p)}let y=wT(l);return y.length>0&&u.push(y),u.join(`
911
+ `?(u.push(d),d=[]):r.length>0&&d.push({text:r,style:e.style})}}(d.length>0||u.length===0)&&u.push(d);let f=n?zT(u,t,r,a,s,c):u,p=[],m=[],h=[],g=[],_=[],v=0,y=t._fontString,b=o(y);b.fontSize===0&&(b.fontSize=t.fontSize,b.ascent=t.fontSize);let x=``,S=!!t.dropShadow,C=t._stroke?.width||0;for(let e of f){let n=0,a=b.ascent,s=b.descent,c=``;for(let t of e){let e=t.style._fontString,l=o(e);e!==x&&(r.font=e,x=e);let u=i(t.text,t.style.letterSpacing,r);n+=u,a=Math.max(a,l.ascent),s=Math.max(s,l.descent),c+=t.text;let d=t.style._stroke?.width||0;d>C&&(C=d),!S&&t.style.dropShadow&&(S=!0)}e.length===0&&(a=b.ascent,s=b.descent),p.push(n),m.push(a),h.push(s),_.push(c);let l=t.lineHeight||a+s;g.push(l+t.leading),v=Math.max(v,n)}let w=C,ee=v+w+(t.dropShadow?t.dropShadow.distance:0),T=0;for(let e=0;e<g.length;e++)T+=g[e];return T=Math.max(T,g[0]+w),{width:ee,height:T+(t.dropShadow?t.dropShadow.distance:0),lines:_,lineWidths:p,lineHeight:(t.lineHeight||b.fontSize)+t.leading,maxLineWidth:v,fontProperties:b,runsByLine:f,lineAscents:m,lineDescents:h,lineHeights:g,hasDropShadow:S}}function zT(e,t,n,r,i,a){let{letterSpacing:o,whiteSpace:s,wordWrapWidth:c,breakWords:l}=t,u=ST(s),d=c+o,f={},p=``,m=(e,t)=>{let i=`${e}|${t.styleKey}`,a=f[i];if(a===void 0){let o=t._fontString;o!==p&&(n.font=o,p=o),a=r(e,t.letterSpacing,n)+t.letterSpacing,f[i]=a}return a},h=[];for(let t of e){let e=BT(t),n=h.length,r=t=>{let n=0,r=t;do{let{token:t,style:i}=e[r];n+=m(t,i),r++}while(r<e.length&&e[r].continuesFromPrevious);return n},o=t=>{let n=[],r=t;do n.push({token:e[r].token,style:e[r].style}),r++;while(r<e.length&&e[r].continuesFromPrevious);return n},s=[],c=0,f=!u,p=null,g=()=>{p&&p.text.length>0&&s.push(p),p=null},_=()=>{if(g(),s.length>0){let e=s[s.length-1];e.text=wT(e.text),e.text.length===0&&s.pop()}h.push(s),s=[],c=0,f=!1};for(let t=0;t<e.length;t++){let{token:n,style:v,continuesFromPrevious:y}=e[t],b=m(n,v);if(u){let e=yT(n),t=p?.text[p.text.length-1]??s[s.length-1]?.text.slice(-1)??``,r=t?yT(t):!1;if(e&&r)continue}let x=!y,S=x?r(t):b;if(S>d&&x){if(c>0&&_(),l){let e=o(t);for(let t=0;t<e.length;t++){let n=e[t].token,r=e[t].style,o=ET(n,l,a,i);for(let e of o){let t=m(e,r);t+c>d&&_(),!p||p.style!==r?(g(),p={text:e,style:r}):p.text+=e,c+=t}}t+=e.length-1}else{let e=o(t);g(),h.push(e.map(e=>({text:e.token,style:e.style}))),f=!1,t+=e.length-1}}else if(S+c>d&&x){if(yT(n)){f=!1;continue}_(),p={text:n,style:v},c=b}else if(y&&!l)!p||p.style!==v?(g(),p={text:n,style:v}):p.text+=n,c+=b;else{let e=yT(n);if(c===0&&e&&!f)continue;!p||p.style!==v?(g(),p={text:n,style:v}):p.text+=n,c+=b}}if(g(),s.length>0){let e=s[s.length-1];e.text=wT(e.text),e.text.length===0&&s.pop()}(s.length>0||h.length===n)&&h.push(s)}return h}function BT(e){let t=[],n=!1;for(let r of e){let e=TT(r.text),i=!0;for(let a of e){let e=yT(a)||vT(a),o=i&&n&&!e;t.push({token:a,style:r.style,continuesFromPrevious:o}),n=!e,i=!1}}return t}var VT,HT=s((()=>{_T(),LT(),VT=/\r\n|\r|\n/g}));function UT(e,t,n,r,i){let a=n[e];return typeof a!=`number`&&(a=i(e,t,r)+t,n[e]=a),a}function WT(e,t,n,r,i,a,o){let s=n.getContext(`2d`,GT);s.font=t._fontString;let c=0,l=``,u=[],d=Object.create(null),{letterSpacing:f,whiteSpace:p}=t,m=ST(p),h=CT(p),g=!m,_=t.wordWrapWidth+f,v=TT(e);for(let e=0;e<v.length;e++){let n=v[e];if(vT(n)){if(!h){u.push(wT(l)),g=!m,l=``,c=0;continue}n=` `}if(m){let e=yT(n),t=yT(l[l.length-1]);if(e&&t)continue}let p=UT(n,f,d,s,r);if(p>_){if(l!==``&&(u.push(wT(l)),l=``,c=0),i(n,t.breakWords)){let e=ET(n,t.breakWords,o,a);for(let t of e){let e=UT(t,f,d,s,r);e+c>_&&(u.push(wT(l)),g=!1,l=``,c=0),l+=t,c+=e}}else l.length>0&&(u.push(wT(l)),l=``,c=0),u.push(wT(n)),g=!1,l=``,c=0}else p+c>_&&(g=!1,u.push(wT(l)),l=``,c=0),(l.length>0||!yT(n)||g)&&(l+=n,c+=p)}let y=wT(l);return y.length>0&&u.push(y),u.join(`
912
912
  `)}var GT,KT=s((()=>{LT(),GT={willReadFrequently:!0}})),qT,JT,YT,XT=s((()=>{fT(),q(),HT(),_T(),LT(),KT(),qT={willReadFrequently:!0},JT=class e{static get experimentalLetterSpacingSupported(){let t=e._experimentalLetterSpacingSupported;if(t===void 0){let n=K.get().getCanvasRenderingContext2D().prototype;t=e._experimentalLetterSpacingSupported=`letterSpacing`in n||`textLetterSpacing`in n}return t}constructor(e,t,n,r,i,a,o,s,c,l){this.text=e,this.style=t,this.width=n,this.height=r,this.lines=i,this.lineWidths=a,this.lineHeight=o,this.maxLineWidth=s,this.fontProperties=c,l&&(this.runsByLine=l.runsByLine,this.lineAscents=l.lineAscents,this.lineDescents=l.lineDescents,this.lineHeights=l.lineHeights,this.hasDropShadow=l.hasDropShadow)}static measureText(t=` `,n,r=e._canvas,i=n.wordWrap){let a=`${t}-${n.styleKey}-wordWrap-${i}`;if(e._measurementCache.has(a))return e._measurementCache.get(a);if(pT(n)&&mT(t)){let r=RT(t,n,i,e._context,e._measureText,e._measureTextAdvance,e.measureFont,e.canBreakChars,e.wordWrapSplit),o=new e(t,n,r.width,r.height,r.lines,r.lineWidths,r.lineHeight,r.maxLineWidth,r.fontProperties,{runsByLine:r.runsByLine,lineAscents:r.lineAscents,lineDescents:r.lineDescents,lineHeights:r.lineHeights,hasDropShadow:r.hasDropShadow});return e._measurementCache.set(a,o),o}let o=n._fontString,s=e.measureFont(o);s.fontSize===0&&(s.fontSize=n.fontSize,s.ascent=n.fontSize,s.descent=0);let c=e._context;c.font=o;let l=(i?e._wordWrap(t,n,r):t).split(IT),u=Array(l.length),d=0;for(let t=0;t<l.length;t++){let r=e._measureText(l[t],n.letterSpacing,c);u[t]=r,d=Math.max(d,r)}let f=n._stroke?.width??0,p=n.lineHeight||s.fontSize,m=e._adjustWidthForStyle(d,n),h=Math.max(p,s.fontSize+f)+(l.length-1)*(p+n.leading),g=e._adjustHeightForStyle(h,n),_=new e(t,n,m,g,l,u,p+n.leading,d,s);return e._measurementCache.set(a,_),_}static _adjustWidthForStyle(e,t){let n=e+(t._stroke?.width||0);return t.dropShadow&&(n+=t.dropShadow.distance),n}static _adjustHeightForStyle(e,t){let n=e;return t.dropShadow&&(n+=t.dropShadow.distance),n}static _measureText(t,n,r){let{metricWidth:i,metrics:a,letterSpacingVal:o}=e._measureTextCore(t,n,r),s=-(a.actualBoundingBoxLeft??0),c=(a.actualBoundingBoxRight??0)-s;return a.width>0&&(c+=o),Math.max(i,c)}static _measureTextAdvance(t,n,r){return e._measureTextCore(t,n,r).metricWidth}static _measureTextCore(t,n,r){let i=!1;e.experimentalLetterSpacingSupported&&(e.experimentalLetterSpacing?(r.letterSpacing=`${n}px`,r.textLetterSpacing=`${n}px`,i=!0):(r.letterSpacing=`0px`,r.textLetterSpacing=`0px`));let a=r.measureText(t),o=a.width,s=0;return o>0&&(s=i?-n:(e.graphemeSegmenter(t).length-1)*n,o+=s),{metricWidth:o,metrics:a,letterSpacingVal:s}}static _wordWrap(t,n,r=e._canvas){return WT(t,n,r,e._measureTextAdvance,e.canBreakWords,e.canBreakChars,e.wordWrapSplit)}static isBreakingSpace(e,t){return yT(e,t)}static canBreakWords(e,t){return t}static canBreakChars(e,t,n,r,i){return!0}static wordWrapSplit(t){return e.graphemeSegmenter(t)}static measureFont(t){if(e._fonts[t])return e._fonts[t];let n=e._context;n.font=t;let r=n.measureText(e.METRICS_STRING+e.BASELINE_SYMBOL),i=r.actualBoundingBoxAscent??0,a=r.actualBoundingBoxDescent??0,o={ascent:i,descent:a,fontSize:i+a};return e._fonts[t]=o,o}static clearMetrics(t=``){t?delete e._fonts[t]:e._fonts={}}static get _canvas(){if(!e.__canvas){let t;try{let n=new OffscreenCanvas(0,0);if(n.getContext(`2d`,qT)?.measureText)return e.__canvas=n,n;t=K.get().createCanvas()}catch{t=K.get().createCanvas()}t.width=t.height=10,e.__canvas=t}return e.__canvas}static get _context(){return e.__context||=e._canvas.getContext(`2d`,qT),e.__context}},JT.METRICS_STRING=`|ÉqÅ`,JT.BASELINE_SYMBOL=`M`,JT.BASELINE_MULTIPLIER=1.4,JT.HEIGHT_MULTIPLIER=2,JT.graphemeSegmenter=(()=>{if(typeof Intl?.Segmenter==`function`){let e=new Intl.Segmenter;return t=>{let n=e.segment(t),r=[],i=0;for(let e of n)r[i++]=e.segment;return r}}return e=>[...e]})(),JT.experimentalLetterSpacing=!1,JT._fonts={},JT._measurementCache=uT(1e3),YT=JT}));function ZT(e){let t=typeof e.fontSize==`number`?`${e.fontSize}px`:e.fontSize,n=e.fontFamily;Array.isArray(e.fontFamily)||(n=e.fontFamily.split(`,`));for(let e=n.length-1;e>=0;e--){let t=n[e].trim();!/([\"\'])[^\'\"]+\1/.test(t)&&!QT.includes(t)&&(t=`"${t}"`),n[e]=t}return`${e.fontStyle} ${e.fontVariant} ${e.fontWeight} ${t} ${n.join(`,`)}`}var QT,$T=s((()=>{QT=[`serif`,`sans-serif`,`monospace`,`cursive`,`fantasy`,`system-ui`]}));function eE(e){let t=e;if(typeof t.dropShadow==`boolean`&&t.dropShadow){let n=nE.defaultDropShadow;e.dropShadow={alpha:t.dropShadowAlpha??n.alpha,angle:t.dropShadowAngle??n.angle,blur:t.dropShadowBlur??n.blur,color:t.dropShadowColor??n.color,distance:t.dropShadowDistance??n.distance}}if(t.strokeThickness!==void 0){R(L,`strokeThickness is now a part of stroke`);let n=t.stroke,r={};if(P.isColorLike(n))r.color=n;else if(n instanceof xx||n instanceof Tx)r.fill=n;else if(Object.hasOwnProperty.call(n,`color`)||Object.hasOwnProperty.call(n,`fill`))r=n;else throw Error(`Invalid stroke value.`);e.stroke={...r,width:t.strokeThickness}}if(Array.isArray(t.fillGradientStops)){if(R(L,"gradient fill is now a fill pattern: `new FillGradient(...)`"),!Array.isArray(t.fill)||t.fill.length===0)throw Error(`Invalid fill value. Expected an array of colors for gradient fill.`);t.fill.length!==t.fillGradientStops.length&&z(`The number of fill colors must match the number of fill gradient stops.`);let n=new xx({start:{x:0,y:0},end:{x:0,y:1},textureSpace:`local`}),r=t.fillGradientStops.slice(),i=t.fill.map(e=>P.shared.setValue(e).toNumber());r.forEach((e,t)=>{n.addColorStop(e,i[t])}),e.fill={fill:n}}}var tE,nE,rE=s((()=>{Xn(),Ar(),Kr(),Xr(),B(),Sx(),Ex(),uw(),rw(),$T(),tE=class e extends Yn{constructor(t={}){super(),this.uid=Wr(`textStyle`),this._tick=0,this._cachedFontString=null,eE(t),t instanceof e&&(t=t._toObject());let n={...e.defaultTextStyle,...t};for(let e in n){let t=e;this[t]=n[e]}this._tagStyles=t.tagStyles??void 0,this.update(),this._tick=0}get align(){return this._align}set align(e){this._align!==e&&(this._align=e,this.update())}get breakWords(){return this._breakWords}set breakWords(e){this._breakWords!==e&&(this._breakWords=e,this.update())}get dropShadow(){return this._dropShadow}set dropShadow(t){this._dropShadow!==t&&(this._dropShadow=typeof t==`object`&&t?this._createProxy({...e.defaultDropShadow,...t}):t?this._createProxy({...e.defaultDropShadow}):null,this.update())}get fontFamily(){return this._fontFamily}set fontFamily(e){this._fontFamily!==e&&(this._fontFamily=e,this.update())}get fontSize(){return this._fontSize}set fontSize(e){this._fontSize!==e&&(this._fontSize=typeof e==`string`?parseInt(e,10):e,this.update())}get fontStyle(){return this._fontStyle}set fontStyle(e){this._fontStyle!==e&&(this._fontStyle=e.toLowerCase(),this.update())}get fontVariant(){return this._fontVariant}set fontVariant(e){this._fontVariant!==e&&(this._fontVariant=e,this.update())}get fontWeight(){return this._fontWeight}set fontWeight(e){this._fontWeight!==e&&(this._fontWeight=e,this.update())}get leading(){return this._leading}set leading(e){this._leading!==e&&(this._leading=e,this.update())}get letterSpacing(){return this._letterSpacing}set letterSpacing(e){this._letterSpacing!==e&&(this._letterSpacing=e,this.update())}get lineHeight(){return this._lineHeight}set lineHeight(e){this._lineHeight!==e&&(this._lineHeight=e,this.update())}get padding(){return this._padding}set padding(e){this._padding!==e&&(this._padding=e,this.update())}get filters(){return this._filters}set filters(e){this._filters!==e&&(this._filters=Object.freeze(e),this.update())}get trim(){return this._trim}set trim(e){this._trim!==e&&(this._trim=e,this.update())}get textBaseline(){return this._textBaseline}set textBaseline(e){this._textBaseline!==e&&(this._textBaseline=e,this.update())}get whiteSpace(){return this._whiteSpace}set whiteSpace(e){this._whiteSpace!==e&&(this._whiteSpace=e,this.update())}get wordWrap(){return this._wordWrap}set wordWrap(e){this._wordWrap!==e&&(this._wordWrap=e,this.update())}get wordWrapWidth(){return this._wordWrapWidth}set wordWrapWidth(e){this._wordWrapWidth!==e&&(this._wordWrapWidth=e,this.update())}get fill(){return this._originalFill}set fill(e){e!==this._originalFill&&(this._originalFill=e,this._isFillStyle(e)&&(this._originalFill=this._createProxy({...lw.defaultFillStyle,...e},()=>{this._fill=tw({...this._originalFill},lw.defaultFillStyle)})),this._fill=tw(e===0?`black`:e,lw.defaultFillStyle),this.update())}get stroke(){return this._originalStroke}set stroke(e){e!==this._originalStroke&&(this._originalStroke=e,this._isFillStyle(e)&&(this._originalStroke=this._createProxy({...lw.defaultStrokeStyle,...e},()=>{this._stroke=nw({...this._originalStroke},lw.defaultStrokeStyle)})),this._stroke=nw(e,lw.defaultStrokeStyle),this.update())}get tagStyles(){return this._tagStyles}set tagStyles(e){this._tagStyles!==e&&(this._tagStyles=e??void 0,this.update())}update(){this._tick++,this._cachedFontString=null,this.emit(`update`,this)}reset(){let t=e.defaultTextStyle;for(let e in t)this[e]=t[e]}assign(e){for(let t in e){let n=t;this[n]=e[t]}return this}get styleKey(){return`${this.uid}-${this._tick}`}get _fontString(){return this._cachedFontString===null&&(this._cachedFontString=ZT(this)),this._cachedFontString}_toObject(){return{align:this.align,breakWords:this.breakWords,dropShadow:this._dropShadow?{...this._dropShadow}:null,fill:this._fill?{...this._fill}:void 0,fontFamily:this.fontFamily,fontSize:this.fontSize,fontStyle:this.fontStyle,fontVariant:this.fontVariant,fontWeight:this.fontWeight,leading:this.leading,letterSpacing:this.letterSpacing,lineHeight:this.lineHeight,padding:this.padding,stroke:this._stroke?{...this._stroke}:void 0,textBaseline:this.textBaseline,trim:this.trim,whiteSpace:this.whiteSpace,wordWrap:this.wordWrap,wordWrapWidth:this.wordWrapWidth,filters:this._filters?[...this._filters]:void 0,tagStyles:this._tagStyles?{...this._tagStyles}:void 0}}clone(){return new e(this._toObject())}_getFinalPadding(){let e=0;if(this._filters)for(let t=0;t<this._filters.length;t++)e+=this._filters[t].padding;return Math.max(this._padding,e)}destroy(e=!1){if(this.removeAllListeners(),typeof e==`boolean`?e:e?.texture){let t=typeof e==`boolean`?e:e?.textureSource;this._fill?.texture&&this._fill.texture.destroy(t),this._originalFill?.texture&&this._originalFill.texture.destroy(t),this._stroke?.texture&&this._stroke.texture.destroy(t),this._originalStroke?.texture&&this._originalStroke.texture.destroy(t)}this._fill=null,this._stroke=null,this.dropShadow=null,this._originalStroke=null,this._originalFill=null}_createProxy(e,t){return new Proxy(e,{set:(e,n,r)=>e[n]===r||(e[n]=r,t?.(n,r),this.update(),!0)})}_isFillStyle(e){return(e??null)!==null&&!(P.isColorLike(e)||e instanceof xx||e instanceof Tx)}},tE.defaultDropShadow={alpha:1,angle:Math.PI/6,blur:0,color:`black`,distance:5},tE.defaultTextStyle={align:`left`,breakWords:!1,dropShadow:null,fill:`black`,fontFamily:`Arial`,fontSize:26,fontStyle:`normal`,fontVariant:`normal`,fontWeight:`normal`,leading:0,letterSpacing:0,lineHeight:0,padding:0,stroke:null,textBaseline:`alphabetic`,trim:!1,whiteSpace:`pre`,wordWrap:!1,wordWrapWidth:100},nE=tE}));function iE(e,t,n,r=0,i=0,a=0){if(e.texture===U.WHITE&&!e.fill)return P.shared.setValue(e.color).setAlpha(e.alpha??1).toHexa();if(!e.fill){let n=t.createPattern(e.texture.source.resource,`repeat`),r=e.matrix.copyTo(F.shared);return r.scale(e.texture.source.pixelWidth,e.texture.source.pixelHeight),n.setTransform(r),n}if(e.fill instanceof Tx){let n=e.fill,r=t.createPattern(n.texture.source.resource,`repeat`);return Y.applyPatternTransform(r,n.transform,!1),r}if(e.fill instanceof xx){let o=e.fill,s=o.type===`linear`,c=o.textureSpace===`local`,l=1,u=1;c&&n&&(l=n.width+r,u=n.height+r);let d,f=!1;if(s){let{start:e,end:n}=o;d=t.createLinearGradient(e.x*l+i,e.y*u+a,n.x*l+i,n.y*u+a),f=Math.abs(n.x-e.x)<Math.abs((n.y-e.y)*.1)}else{let{center:e,innerRadius:n,outerCenter:r,outerRadius:s}=o;d=t.createRadialGradient(e.x*l+i,e.y*u+a,n*l,r.x*l+i,r.y*u+a,s*l)}if(f&&c&&n){let e=n.lineHeight/u;for(let t=0;t<n.lines.length;t++){let i=(t*n.lineHeight+r/2)/u;o.colorStops.forEach(t=>{let n=i+t.offset*e;n=Math.max(0,Math.min(1,n)),d.addColorStop(Math.floor(n*aE)/aE,P.shared.setValue(t.color).toHex())})}}else o.colorStops.forEach(e=>{d.addColorStop(e.offset,P.shared.setValue(e.color).toHex())});return d}return z(`FillStyle not recognised`,e),`red`}var aE,oE=s((()=>{Ar(),I(),Fc(),W(),B(),Sx(),Ex(),aE=1e5})),sE,cE,lE=s((()=>{Ar(),wi(),Rc(),gc(),W(),va(),Xr(),XT(),$T(),oE(),rE(),lT(),sE=class e extends cT{constructor(t){super(),this.resolution=1,this.pages=[],this._padding=0,this._measureCache=Object.create(null),this._currentChars=[],this._currentX=0,this._currentY=0,this._currentMaxCharHeight=0,this._currentPageIndex=-1,this._skipKerning=!1;let n={...e.defaultOptions,...t};this._textureSize=n.textureSize,this._mipmap=n.mipmap;let r=n.style.clone();n.overrideFill&&(r._fill.color=16777215,r._fill.alpha=1,r._fill.texture=U.WHITE,r._fill.fill=null),this.applyFillAsTint=n.overrideFill;let i=r.fontSize;r.fontSize=this.baseMeasurementFontSize;let a=ZT(r);n.overrideSize?(r._stroke&&(r._stroke.width*=this.baseRenderedFontSize/i),r.dropShadow&&(r.dropShadow.blur*=this.baseRenderedFontSize/i,r.dropShadow.distance*=this.baseRenderedFontSize/i)):r.fontSize=this.baseRenderedFontSize=i,this._style=r,this._skipKerning=n.skipKerning??!1,this.resolution=n.resolution??1,this._padding=n.padding??4,n.textureStyle&&(this._textureStyle=n.textureStyle instanceof _a?n.textureStyle:new _a(n.textureStyle)),this.fontMetrics=YT.measureFont(a),this.lineHeight=r.lineHeight||this.fontMetrics.fontSize||r.fontSize}ensureCharacters(e){let t=YT.graphemeSegmenter(e).filter(e=>!this._currentChars.includes(e)).filter((e,t,n)=>n.indexOf(e)===t);if(!t.length)return;this._currentChars=[...this._currentChars,...t];let n;n=this._currentPageIndex===-1?this._nextPage():this.pages[this._currentPageIndex];let{canvas:r,context:i}=n.canvasAndContext,a=n.texture.source,o=this._style,s=this._currentX,c=this._currentY,l=this._currentMaxCharHeight,u=this.baseRenderedFontSize/this.baseMeasurementFontSize,d=(o.dropShadow?.distance??0)+(o._stroke?.width??0),f=this._padding+d,p=!1,m=r.width/this.resolution,h=r.height/this.resolution;for(let e=0;e<t.length;e++){let n=t[e],d=YT.measureText(n,o,r,!1);d.lineHeight=d.height;let g=d.width*u,_=Math.ceil((o.fontStyle===`italic`?2:1)*g),v=d.height*u,y=_+f*2,b=v+f*2;if(p=!1,n!==`
913
913
  `&&n!==`\r`&&n!==` `&&n!==` `&&(p=!0,l=Math.ceil(Math.max(b,l))),s+y>m&&(c+=l,l=b,s=0,c+l>h)){a.update();let e=this._nextPage();r=e.canvasAndContext.canvas,i=e.canvasAndContext.context,a=e.texture.source,s=0,c=0,l=0}let x=i.measureText(n).width/u;if(this.chars[n]={id:n.codePointAt(0),xOffset:-(f/u),yOffset:-(f/u),xAdvance:x,kerning:{}},p){this._drawGlyph(i,d,s+f,c+f,u,o);let e=a.width*u,t=a.height*u,r=new V(s/e*a.width,c/t*a.height,y/e*a.width,b/t*a.height);this.chars[n].texture=new U({source:a,frame:r}),s+=Math.ceil(y)}}a.update(),this._currentX=s,this._currentY=c,this._currentMaxCharHeight=l,this._skipKerning||this._applyKerning(t,i,u)}get pageTextures(){return R(L,`BitmapFont.pageTextures is deprecated, please use BitmapFont.pages instead.`),this.pages}_applyKerning(e,t,n){let r=this._measureCache;for(let i=0;i<e.length;i++){let a=e[i];for(let e=0;e<this._currentChars.length;e++){let i=this._currentChars[e],o=r[a];o||=r[a]=t.measureText(a).width;let s=r[i];s||=r[i]=t.measureText(i).width;let c=t.measureText(a+i).width,l=c-(o+s);l&&this.chars[a]&&(this.chars[a].kerning[i]=l/n),c=t.measureText(a+i).width,l=c-(o+s),l&&this.chars[i]&&(this.chars[i].kerning[a]=l/n)}}}_nextPage(){this._currentPageIndex++;let e=this.resolution,t=Lc.getOptimalCanvasAndContext(this._textureSize,this._textureSize,e);this._setupContext(t.context,this._style,e);let n=e*(this.baseRenderedFontSize/this.baseMeasurementFontSize),r=new U({source:new hc({resource:t.canvas,resolution:n,alphaMode:`premultiply-alpha-on-upload`,autoGenerateMipmaps:this._mipmap})});this._textureStyle&&(r.source.style=this._textureStyle);let i={canvasAndContext:t,texture:r};return this.pages[this._currentPageIndex]=i,i}_setupContext(e,t,n){t.fontSize=this.baseRenderedFontSize,e.scale(n,n),e.font=ZT(t),t.fontSize=this.baseMeasurementFontSize,e.textBaseline=t.textBaseline;let r=t._stroke,i=r?.width??0;if(r&&(e.lineWidth=i,e.lineJoin=r.join,e.miterLimit=r.miterLimit,e.strokeStyle=iE(r,e)),t._fill&&(e.fillStyle=iE(t._fill,e)),t.dropShadow){let r=t.dropShadow,i=P.shared.setValue(r.color).toArray(),a=r.blur*n,o=r.distance*n;e.shadowColor=`rgba(${i[0]*255},${i[1]*255},${i[2]*255},${r.alpha})`,e.shadowBlur=a,e.shadowOffsetX=Math.cos(r.angle)*o,e.shadowOffsetY=Math.sin(r.angle)*o}else e.shadowColor=`black`,e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0}_drawGlyph(e,t,n,r,i,a){let o=t.text,s=t.fontProperties,c=(a._stroke?.width??0)*i,l=n+c/2,u=r-c/2,d=s.descent*i,f=t.lineHeight*i,p=!1;a.stroke&&c&&(p=!0,e.strokeText(o,l,u+f-d));let{shadowBlur:m,shadowOffsetX:h,shadowOffsetY:g}=e;a._fill&&(p&&(e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0),e.fillText(o,l,u+f-d)),p&&(e.shadowBlur=m,e.shadowOffsetX=h,e.shadowOffsetY=g)}destroy(){super.destroy();for(let e=0;e<this.pages.length;e++){let{canvasAndContext:t,texture:n}=this.pages[e];Lc.returnCanvasAndContext(t),n.destroy(!0)}this.pages=null}},sE.defaultOptions={textureSize:512,style:new nE,mipmap:!0},cE=sE}));function uE(e,t,n,r){let i={width:0,height:0,offsetY:0,scale:t.fontSize/n.baseMeasurementFontSize,lines:[{width:0,charPositions:[],spaceWidth:0,spacesIndex:[],chars:[]}]};i.offsetY=n.baseLineOffset;let a=i.lines[0],o=null,s=!0,c={spaceWord:!1,width:0,start:0,index:0,positions:[],chars:[]},l=n.baseMeasurementFontSize/t.fontSize,u=t.letterSpacing*l,d=t.wordWrapWidth*l,f=t.lineHeight?t.lineHeight*l:n.lineHeight,p=t.wordWrap&&t.breakWords,m=ST(t.whiteSpace),h=CT(t.whiteSpace);if(m||h){let t=[],n=m;for(let r=0;r<e.length;r++){let i=e[r];if(i===`\r`||i===`
914
914
  `){if(h)i===`\r`&&e[r+1]===`
@@ -1201,7 +1201,7 @@ fn mainFragment(
1201
1201
 
1202
1202
  outColor = texture(uTexture, coord, unclamped == coord ? 0.0 : -32.0);// lod-bias very negative to force lod 0
1203
1203
 
1204
- `}};I(),mp(),kp(),Mp(),Su(),bu(),W();var JD,YD,XD=class extends xu{constructor(){JD??=fp({name:`tiling-sprite-shader`,bits:[Ep,KD,Ap]}),YD??=pp({name:`tiling-sprite-shader`,bits:[Op,qD,jp]});let e=new yu({uMapCoord:{value:new F,type:`mat3x3<f32>`},uClampFrame:{value:new Float32Array([0,0,1,1]),type:`vec4<f32>`},uClampOffset:{value:new Float32Array([0,0]),type:`vec2<f32>`},uTextureTransform:{value:new F,type:`mat3x3<f32>`},uSizeAnchor:{value:new Float32Array([100,100,.5,.5]),type:`vec4<f32>`}});super({glProgram:YD,gpuProgram:JD,resources:{localUniforms:new yu({uTransformMatrix:{value:new F,type:`mat3x3<f32>`},uColor:{value:new Float32Array([1,1,1,1]),type:`vec4<f32>`},uRound:{value:0,type:`f32`}}),tilingUniforms:e,uTexture:U.EMPTY.source,uSampler:U.EMPTY.source.style}})}updateUniforms(e,t,n,r,i,a){let o=this.resources.tilingUniforms,s=a.width,c=a.height,l=a.textureMatrix,u=o.uniforms.uTextureTransform;u.set(n.a*s/e,n.b*s/t,n.c*c/e,n.d*c/t,n.tx/e,n.ty/t),u.invert(),o.uniforms.uMapCoord=l.mapCoord,o.uniforms.uClampFrame=l.uClampFrame,o.uniforms.uClampOffset=l.uClampOffset,o.uniforms.uTextureTransform=u,o.uniforms.uSizeAnchor[0]=e,o.uniforms.uSizeAnchor[1]=t,o.uniforms.uSizeAnchor[2]=r,o.uniforms.uSizeAnchor[3]=i,a&&(this.resources.uTexture=a.source,this.resources.uSampler=a.source.style)}},ZD=class extends zD{constructor(){super({positions:new Float32Array([0,0,1,0,1,1,0,1]),uvs:new Float32Array([0,0,1,0,1,1,0,1]),indices:new Uint32Array([0,1,2,0,2,3])})}};function QD(e,t){let n=e.anchor.x,r=e.anchor.y;t[0]=-n*e.width,t[1]=-r*e.height,t[2]=(1-n)*e.width,t[3]=-r*e.height,t[4]=(1-n)*e.width,t[5]=(1-r)*e.height,t[6]=-n*e.width,t[7]=(1-r)*e.height}function $D(e,t,n,r){let i=0,a=e.length/(t||2),o=r.a,s=r.b,c=r.c,l=r.d,u=r.tx,d=r.ty;for(n*=t;i<a;){let r=e[n],a=e[n+1];e[n]=o*r+c*a+u,e[n+1]=s*r+l*a+d,n+=t,i++}}I();function eO(e,t){let n=e.texture,r=n.frame.width,i=n.frame.height,a=0,o=0;e.applyAnchorToTexture&&(a=e.anchor.x,o=e.anchor.y),t[0]=t[6]=-a,t[2]=t[4]=1-a,t[1]=t[3]=-o,t[5]=t[7]=1-o;let s=e._tileTransform.matrix,c=F.shared;c.set(s.a*r/e.width,s.b*r/e.height,s.c*i/e.width,s.d*i/e.height,s.tx/e.width,s.ty/e.height),c.invert(),$D(t,2,0,c)}N(),Em(),Nu(),uu(),Tg(),qh();var tO=new ZD,nO=class{constructor(){this.canBatch=!0,this.geometry=new zD({indices:tO.indices.slice(),positions:tO.positions.slice(),uvs:tO.uvs.slice()})}destroy(){this.geometry.destroy(),this.shader?.destroy()}},rO=class{constructor(e){this._state=Mu.default2d,this._renderer=e,this._managedTilingSprites=new wg({renderer:e,type:`renderable`,name:`tilingSprite`})}validateRenderable(e){let t=this._getTilingSpriteData(e),n=t.canBatch;this._updateCanBatch(e);let r=t.canBatch;if(r&&r===n){let{batchableMesh:n}=t;return!n._batcher.checkAndUpdateTexture(n,e.texture)}return n!==r}addRenderable(e,t){let n=this._renderer.renderPipes.batch;this._updateCanBatch(e);let r=this._getTilingSpriteData(e),{geometry:i,canBatch:a}=r;if(a){r.batchableMesh||=new BD;let a=r.batchableMesh;e.didViewUpdate&&(this._updateBatchableMesh(e),a.geometry=i,a.renderable=e,a.transform=e.groupTransform,a.setTexture(e._texture)),a.roundPixels=this._renderer._roundPixels|e._roundPixels,n.addToBatch(a,t)}else n.break(t),r.shader||=new XD,this.updateRenderable(e),t.add(e)}execute(e){let t=this._renderer,{shader:n}=this._getTilingSpriteData(e);n.groups[0]=t.globalUniforms.bindGroup;let r=n.resources.localUniforms.uniforms;r.uTransformMatrix=e.groupTransform,r.uRound=t._roundPixels|e._roundPixels,Kh(e.groupColorAlpha,r.uColor,0),this._state.blendMode=Tm(e.groupBlendMode,e.texture._source),t.encoder.draw({geometry:tO,shader:n,state:this._state})}updateRenderable(e){let t=this._getTilingSpriteData(e),{canBatch:n}=t;if(n){let{batchableMesh:n}=t;e.didViewUpdate&&this._updateBatchableMesh(e),n._batcher.updateElement(n)}else if(e.didViewUpdate){let{shader:n}=t;n.updateUniforms(e.width,e.height,e._tileTransform.matrix,e.anchor.x,e.anchor.y,e.texture)}}_getTilingSpriteData(e){return e._gpuData[this._renderer.uid]||this._initTilingSpriteData(e)}_initTilingSpriteData(e){let t=new nO;return t.renderable=e,e._gpuData[this._renderer.uid]=t,this._managedTilingSprites.add(e),t}_updateBatchableMesh(e){let{geometry:t}=this._getTilingSpriteData(e),n=e.texture.source.style;n.addressMode!==`repeat`&&(n.addressMode=`repeat`,n.update()),eO(e,t.uvs),QD(e,t.positions)}destroy(){this._managedTilingSprites.destroy(),this._renderer=null}_updateCanBatch(e){let t=this._getTilingSpriteData(e),n=e.texture,r=!0;return this._renderer.type===lu.WEBGL&&(r=this._renderer.context.supports.nonPowOf2wrapping),t.canBatch=n.textureMatrix.isSimple&&(r||n.source.isPowerOfTwo),t.canBatch}};rO.extension={type:[j.WebGLPipes,j.WebGPUPipes],name:`tilingSprite`},N(),M.add(GD),M.add(rO),wc(),Ur(),W(),Xr(),Yo();var iO=class e extends Jo{constructor(...t){let n=t[0]||{};n instanceof U&&(n={texture:n}),t.length>1&&(R(L,`use new TilingSprite({ texture, width:100, height:100 }) instead`),n.width=t[1],n.height=t[2]),n={...e.defaultOptions,...n};let{texture:r,anchor:i,tilePosition:a,tileScale:o,tileRotation:s,width:c,height:l,applyAnchorToTexture:u,roundPixels:d,...f}=n??{};super({label:`TilingSprite`,...f}),this.renderPipeId=`tilingSprite`,this.batched=!0,this.allowChildren=!1,this._anchor=new Hr({_onUpdate:()=>{this.onViewUpdate()}}),this.applyAnchorToTexture=u,this.texture=r,this._width=c??r.width,this._height=l??r.height,this._tileTransform=new VD({observer:{_onUpdate:()=>this.onViewUpdate()}}),i&&(this.anchor=i),this.tilePosition=a,this.tileScale=o,this.tileRotation=s,this.roundPixels=d??!1}static from(t,n={}){return typeof t==`string`?new e({texture:J.get(t),...n}):new e({texture:t,...n})}get uvRespectAnchor(){return R(L,`uvRespectAnchor is deprecated, please use applyAnchorToTexture instead`),this.applyAnchorToTexture}set uvRespectAnchor(e){R(L,`uvRespectAnchor is deprecated, please use applyAnchorToTexture instead`),this.applyAnchorToTexture=e}get clampMargin(){return this._texture.textureMatrix.clampMargin}set clampMargin(e){this._texture.textureMatrix.clampMargin=e}get anchor(){return this._anchor}set anchor(e){typeof e==`number`?this._anchor.set(e):this._anchor.copyFrom(e)}get tilePosition(){return this._tileTransform.position}set tilePosition(e){this._tileTransform.position.copyFrom(e)}get tileScale(){return this._tileTransform.scale}set tileScale(e){typeof e==`number`?this._tileTransform.scale.set(e):this._tileTransform.scale.copyFrom(e)}set tileRotation(e){this._tileTransform.rotation=e}get tileRotation(){return this._tileTransform.rotation}get tileTransform(){return this._tileTransform}set texture(e){e||=U.EMPTY;let t=this._texture;t!==e&&(t&&t.dynamic&&t.off(`update`,this.onViewUpdate,this),e.dynamic&&e.on(`update`,this.onViewUpdate,this),this._texture=e,this.onViewUpdate())}get texture(){return this._texture}set width(e){this._width=e,this.onViewUpdate()}get width(){return this._width}set height(e){this._height=e,this.onViewUpdate()}get height(){return this._height}setSize(e,t){typeof e==`object`&&(t=e.height??e.width,e=e.width),this._width=e,this._height=t??e,this.onViewUpdate()}getSize(e){return e||={},e.width=this._width,e.height=this._height,e}updateBounds(){let e=this._bounds,t=this._anchor,n=this._width,r=this._height;e.minX=-t._x*n,e.maxX=e.minX+n,e.minY=-t._y*r,e.maxY=e.minY+r}containsPoint(e){let t=this._width,n=this._height,r=-t*this._anchor._x,i=0;return e.x>=r&&e.x<=r+t&&(i=-n*this._anchor._y,e.y>=i&&e.y<=i+n)}destroy(e=!1){if(super.destroy(e),this._anchor=null,this._tileTransform=null,this._bounds=null,typeof e==`boolean`?e:e?.texture){let t=typeof e==`boolean`?e:e?.textureSource;this._texture.destroy(t)}this._texture=null}};iO.defaultOptions={texture:U.EMPTY,anchor:{x:0,y:0},tilePosition:{x:0,y:0},tileScale:{x:1,y:1},tileRotation:0,applyAnchorToTexture:!1};var aO=iO;Ur(),Xr(),Yo();var oO=class extends Jo{constructor(e,t){let{text:n,resolution:r,style:i,anchor:a,width:o,height:s,roundPixels:c,...l}=e;super({...l}),this.batched=!0,this._resolution=null,this._autoResolution=!0,this._didTextUpdate=!0,this._styleClass=t,this.text=n??``,this.style=i,this.resolution=r??null,this.allowChildren=!1,this._anchor=new Hr({_onUpdate:()=>{this.onViewUpdate()}}),a&&(this.anchor=a),this.roundPixels=c??!1,o!==void 0&&(this.width=o),s!==void 0&&(this.height=s)}get anchor(){return this._anchor}set anchor(e){typeof e==`number`?this._anchor.set(e):this._anchor.copyFrom(e)}set text(e){e=e.toString(),this._text!==e&&(this._text=e,this.onViewUpdate())}get text(){return this._text}set resolution(e){this._autoResolution=e===null,this._resolution=e,this.onViewUpdate()}get resolution(){return this._resolution}get style(){return this._style}set style(e){e||={},this._style?.off(`update`,this.onViewUpdate,this),this._style=e instanceof this._styleClass?e:new this._styleClass(e),this._style.on(`update`,this.onViewUpdate,this),this.onViewUpdate()}get width(){return Math.abs(this.scale.x)*this.bounds.width}set width(e){this._setWidth(e,this.bounds.width)}get height(){return Math.abs(this.scale.y)*this.bounds.height}set height(e){this._setHeight(e,this.bounds.height)}getSize(e){return e||={},e.width=Math.abs(this.scale.x)*this.bounds.width,e.height=Math.abs(this.scale.y)*this.bounds.height,e}setSize(e,t){typeof e==`object`?(t=e.height??e.width,e=e.width):t??=e,e!==void 0&&this._setWidth(e,this.bounds.width),t!==void 0&&this._setHeight(t,this.bounds.height)}containsPoint(e){let t=this.bounds.width,n=this.bounds.height,r=-t*this.anchor.x,i=0;return e.x>=r&&e.x<=r+t&&(i=-n*this.anchor.y,e.y>=i&&e.y<=i+n)}onViewUpdate(){this.didViewUpdate||(this._didTextUpdate=!0),super.onViewUpdate()}destroy(e=!1){this._style?.off(`update`,this.onViewUpdate,this),super.destroy(e),this.owner=null,this._bounds=null,this._anchor=null,(typeof e==`boolean`?e:e?.style)&&this._style.destroy(e),this._style=null,this._text=null}get styleKey(){return`${this._text}:${this._style.styleKey}:${this._resolution}`}};function sO(e,t){let n=e[0]??{};return(typeof n==`string`||e[1])&&(R(L,`use new ${t}({ text: "hi!", style }) instead`),n={text:n,style:e[1]}),n}q(),da(),wi();var cO=null,lO=null;function uO(e,t){cO||(cO=K.get().createCanvas(256,128),lO=cO.getContext(`2d`,{willReadFrequently:!0}),lO.globalCompositeOperation=`copy`,lO.globalAlpha=1),(cO.width<e||cO.height<t)&&(cO.width=la(e),cO.height=la(t))}function dO(e,t,n){for(let r=0,i=4*n*t;r<t;++r,i+=4)if(e[i+3]!==0)return!1;return!0}function fO(e,t,n,r,i){let a=4*t;for(let t=r,o=r*a+4*n;t<=i;++t,o+=a)if(e[o+3]!==0)return!1;return!0}function pO(...e){let t=e[0];t.canvas||(t={canvas:e[0],resolution:e[1]});let{canvas:n}=t,r=Math.min(t.resolution??1,1),i=t.width??n.width,a=t.height??n.height,o=t.output;if(uO(i,a),!lO)throw TypeError(`Failed to get canvas 2D context`);lO.drawImage(n,0,0,i,a,0,0,i*r,a*r);let s=lO.getImageData(0,0,i,a).data,c=0,l=0,u=i-1,d=a-1;for(;l<a&&dO(s,i,l);)++l;if(l===a)return V.EMPTY;for(;dO(s,i,d);)--d;for(;fO(s,i,c,l,d);)++c;for(;fO(s,i,u,l,d);)--u;return++u,++d,lO.globalCompositeOperation=`source-over`,lO.strokeRect(c,l,u-c,d-l),lO.globalCompositeOperation=`copy`,o??=new V,o.set(c/r,l/r,(u-c)/r,(d-l)/r),o}Ar(),wi(),Rc(),XT(),$T(),oE();var mO=new V;function hO(e){let t=0;for(let n=0;n<e.length;n++)e.charCodeAt(n)===32&&t++;return t}var gO=new class{getCanvasAndContext(e){let{text:t,style:n,resolution:r=1}=e,i=n._getFinalPadding(),a=YT.measureText(t||` `,n),o=Math.ceil(Math.ceil(Math.max(1,a.width)+i*2)*r),s=Math.ceil(Math.ceil(Math.max(1,a.height)+i*2)*r),c=Lc.getOptimalCanvasAndContext(o,s);return this._renderTextToCanvas(n,i,r,c,a),{canvasAndContext:c,frame:n.trim?pO({canvas:c.canvas,width:o,height:s,resolution:1,output:mO}):mO.set(0,0,o,s)}}returnCanvasAndContext(e){Lc.returnCanvasAndContext(e)}_renderTextToCanvas(e,t,n,r,i){if(i.runsByLine&&i.runsByLine.length>0){this._renderTaggedTextToCanvas(i,e,t,n,r);return}let{canvas:a,context:o}=r,s=ZT(e),c=i.lines,l=i.lineHeight,u=i.lineWidths,d=i.maxLineWidth,f=i.fontProperties,p=a.height;if(o.resetTransform(),o.scale(n,n),o.textBaseline=e.textBaseline,e._stroke?.width){let t=e._stroke;o.lineWidth=t.width,o.miterLimit=t.miterLimit,o.lineJoin=t.join,o.lineCap=t.cap}o.font=s;let m,h,g=e.dropShadow?2:1,_=(e._stroke?.width??0)/2,v=(l-f.fontSize)/2;l-f.fontSize<0&&(v=0);for(let a=0;a<g;++a){let s=e.dropShadow&&a===0,g=s?Math.ceil(Math.max(1,p)+t*2):0,y=g*n;if(s)this._setupDropShadow(o,e,n,y);else{let n=e._gradientBounds,r=e._gradientOffset;if(n){let a={width:n.width,height:n.height,lineHeight:n.height,lines:i.lines};this._setFillAndStrokeStyles(o,e,a,t,_,r?.x??0,r?.y??0)}else r?this._setFillAndStrokeStyles(o,e,i,t,_,r.x,r.y):this._setFillAndStrokeStyles(o,e,i,t,_);o.shadowColor=`rgba(0,0,0,0)`}for(let n=0;n<c.length;n++){m=_,h=_+n*l+f.ascent+v,m+=this._getAlignmentOffset(u[n],d,e.align);let i=0;if(e.align===`justify`&&e.wordWrap&&n<c.length-1){let e=hO(c[n]);e>0&&(i=(d-u[n])/e)}e._stroke?.width&&this._drawLetterSpacing(c[n],e,r,m+t,h+t-g,!0,i),e._fill!==void 0&&this._drawLetterSpacing(c[n],e,r,m+t,h+t-g,!1,i)}}}_renderTaggedTextToCanvas(e,t,n,r,i){let{canvas:a,context:o}=i,{runsByLine:s,lineWidths:c,maxLineWidth:l,lineAscents:u,lineHeights:d,hasDropShadow:f}=e,p=a.height;o.resetTransform(),o.scale(r,r),o.textBaseline=t.textBaseline;let m=f?2:1,h=t._stroke?.width??0;for(let e of s)for(let t of e){let e=t.style._stroke?.width??0;e>h&&(h=e)}let g=h/2,_=[];for(let e=0;e<s.length;e++){let t=s[e],n=[];for(let e of t){let t=ZT(e.style);o.font=t,n.push({width:YT._measureText(e.text,e.style.letterSpacing,o),font:t})}_.push(n)}for(let e=0;e<m;++e){let a=f&&e===0,m=a?Math.ceil(Math.max(1,p)+n*2):0,h=m*r;a||(o.shadowColor=`rgba(0,0,0,0)`);let v=g;for(let e=0;e<s.length;e++){let f=s[e],p=c[e],y=u[e],b=d[e],x=_[e],S=g;S+=this._getAlignmentOffset(p,l,t.align);let C=0;if(t.align===`justify`&&t.wordWrap&&e<s.length-1){let e=0;for(let t of f)e+=hO(t.text);e>0&&(C=(l-p)/e)}let w=v+y,T=S+n;for(let e=0;e<f.length;e++){let t=f[e],{width:s,font:c}=x[e];if(o.font=c,o.textBaseline=t.style.textBaseline,t.style._stroke?.width){let e=t.style._stroke;if(o.lineWidth=e.width,o.miterLimit=e.miterLimit,o.lineJoin=e.join,o.lineCap=e.cap,a){if(t.style.dropShadow)this._setupDropShadow(o,t.style,r,h);else{let e=hO(t.text);T+=s+e*C;continue}}else{let r=YT.measureFont(c),i=t.style.lineHeight||r.fontSize;o.strokeStyle=iE(e,o,{width:s,height:i,lineHeight:i,lines:[t.text]},n*2,T-n,v)}this._drawLetterSpacing(t.text,t.style,i,T,w+n-m,!0,C)}let l=hO(t.text);T+=s+l*C}T=S+n;for(let e=0;e<f.length;e++){let t=f[e],{width:s,font:c}=x[e];if(o.font=c,o.textBaseline=t.style.textBaseline,t.style._fill!==void 0){if(a){if(t.style.dropShadow)this._setupDropShadow(o,t.style,r,h);else{let e=hO(t.text);T+=s+e*C;continue}}else{let e=YT.measureFont(c),r=t.style.lineHeight||e.fontSize,i={width:s,height:r,lineHeight:r,lines:[t.text]};o.fillStyle=iE(t.style._fill,o,i,n*2,T-n,v)}this._drawLetterSpacing(t.text,t.style,i,T,w+n-m,!1,C)}let l=hO(t.text);T+=s+l*C}v+=b}}}_setFillAndStrokeStyles(e,t,n,r,i,a=0,o=0){if(e.fillStyle=t._fill?iE(t._fill,e,n,r*2,a,o):null,t._stroke?.width){let s=i+r*2;e.strokeStyle=iE(t._stroke,e,n,s,a,o)}}_setupDropShadow(e,t,n,r){e.fillStyle=`black`,e.strokeStyle=`black`;let i=t.dropShadow,a=i.color,o=i.alpha;e.shadowColor=P.shared.setValue(a).setAlpha(o).toRgbaString();let s=i.blur*n,c=i.distance*n;e.shadowBlur=s,e.shadowOffsetX=Math.cos(i.angle)*c,e.shadowOffsetY=Math.sin(i.angle)*c+r}_getAlignmentOffset(e,t,n){return n===`right`?t-e:n===`center`?(t-e)/2:0}_drawLetterSpacing(e,t,n,r,i,a=!1,o=0){let{context:s}=n,c=t.letterSpacing,l=!1;if(YT.experimentalLetterSpacingSupported&&(YT.experimentalLetterSpacing?(s.letterSpacing=`${c}px`,s.textLetterSpacing=`${c}px`,l=!0):(s.letterSpacing=`0px`,s.textLetterSpacing=`0px`)),(c===0||l)&&o===0){a?s.strokeText(e,r,i):s.fillText(e,r,i);return}if(o!==0&&(c===0||l)){let t=e.split(` `),n=r,c=s.measureText(` `).width;for(let e=0;e<t.length;e++)a?s.strokeText(t[e],n,i):s.fillText(t[e],n,i),n+=s.measureText(t[e]).width+c+o;return}let u=r,d=YT.graphemeSegmenter(e),f=s.measureText(e).width,p=0;for(let e=0;e<d.length;++e){let t=d[e];a?s.strokeText(t,u,i):s.fillText(t,u,i);let n=``;for(let t=e+1;t<d.length;++t)n+=d[t];p=s.measureText(n).width,u+=f-p+c,t===` `&&(u+=o),f=p}}};Qs();function _O(e,t){let{texture:n,bounds:r}=e,i=t._style._getFinalPadding();Zs(r,t._anchor,n);let a=t._anchor._x*i*2,o=t._anchor._y*i*2;r.minX-=i-a,r.minY-=i-o,r.maxX-=i-a,r.maxY-=i-o}Kp();var vO=class extends Gp{};N(),Tg();var yO=class{constructor(e){this._renderer=e,e.runners.resolutionChange.add(this),this._managedTexts=new wg({renderer:e,type:`renderable`,onUnload:this.onTextUnload.bind(this),name:`canvasText`})}resolutionChange(){for(let e in this._managedTexts.items){let t=this._managedTexts.items[e];t?._autoResolution&&t.onViewUpdate()}}validateRenderable(e){let t=this._getGpuText(e),n=e.styleKey;return t.currentKey!==n||e._didTextUpdate}addRenderable(e,t){let n=this._getGpuText(e);if(e._didTextUpdate){let t=e._autoResolution?this._renderer.resolution:e.resolution;(n.currentKey!==e.styleKey||e._resolution!==t)&&this._updateGpuText(e),e._didTextUpdate=!1,_O(n,e)}this._renderer.renderPipes.batch.addToBatch(n,t)}updateRenderable(e){let t=this._getGpuText(e);t._batcher.updateElement(t)}_updateGpuText(e){let t=this._getGpuText(e);t.texture&&this._renderer.canvasText.decreaseReferenceCount(t.currentKey),e._resolution=e._autoResolution?this._renderer.resolution:e.resolution,t.texture=this._renderer.canvasText.getManagedTexture(e),t.currentKey=e.styleKey}_getGpuText(e){return e._gpuData[this._renderer.uid]||this.initGpuText(e)}initGpuText(e){let t=new vO;return t.currentKey=`--`,t.renderable=e,t.transform=e.groupTransform,t.bounds={minX:0,maxX:1,minY:0,maxY:0},t.roundPixels=this._renderer._roundPixels|e._roundPixels,e._gpuData[this._renderer.uid]=t,this._managedTexts.add(e),t}onTextUnload(e){let t=e._gpuData[this._renderer.uid];if(!t)return;let{canvasText:n}=this._renderer;n.getReferenceCount(t.currentKey)>0?n.decreaseReferenceCount(t.currentKey):t.texture&&n.returnTexture(t.texture)}destroy(){this._managedTexts.destroy(),this._renderer=null}};yO.extension={type:[j.WebGLPipes,j.WebGPUPipes,j.CanvasPipes],name:`text`},Va(),va(),Xr(),rE(),al();var bO=class{constructor(e,t){this._activeTextures={},this._renderer=e,this._retainCanvasContext=t}getTexture(e,t,n,r){typeof e==`string`&&(R(`8.0.0`,`CanvasTextSystem.getTexture: Use object TextOptions instead of separate arguments`),e={text:e,style:n,resolution:t}),e.style instanceof nE||(e.style=new nE(e.style)),e.textureStyle instanceof _a||(e.textureStyle=new _a(e.textureStyle)),typeof e.text!=`string`&&(e.text=e.text.toString());let{text:i,style:a,textureStyle:o,autoGenerateMipmaps:s}=e,c=e.resolution??this._renderer.resolution,{frame:l,canvasAndContext:u}=gO.getCanvasAndContext({text:i,style:a,resolution:c}),d=rl(u.canvas,l.width,l.height,c,s);if(o&&(d.source.style=o),a.trim&&(l.pad(a.padding),d.frame.copyFrom(l),d.frame.scale(1/c),d.updateUvs()),a.filters){let e=this._applyFilters(d,a.filters);return this.returnTexture(d),gO.returnCanvasAndContext(u),e}return this._renderer.texture.initSource(d._source),this._retainCanvasContext||gO.returnCanvasAndContext(u),d}returnTexture(e){let t=e.source,n=t.resource;if(this._retainCanvasContext&&n?.getContext){let e=n.getContext(`2d`);e&&gO.returnCanvasAndContext({canvas:n,context:e})}t.resource=null,t.uploadMethodId=`unknown`,t.alphaMode=`no-premultiply-alpha`,Ba.returnTexture(e,!0)}renderTextToCanvas(){R(`8.10.0`,`CanvasTextSystem.renderTextToCanvas: no longer supported, use CanvasTextSystem.getTexture instead`)}getManagedTexture(e){e._resolution=e._autoResolution?this._renderer.resolution:e.resolution;let t=e.styleKey;if(this._activeTextures[t])return this._increaseReferenceCount(t),this._activeTextures[t].texture;let n=this.getTexture({text:e.text,style:e.style,resolution:e._resolution,textureStyle:e.textureStyle,autoGenerateMipmaps:e.autoGenerateMipmaps});return this._activeTextures[t]={texture:n,usageCount:1},n}decreaseReferenceCount(e){let t=this._activeTextures[e];t&&(t.usageCount--,t.usageCount===0&&(this.returnTexture(t.texture),this._activeTextures[e]=null))}getReferenceCount(e){return this._activeTextures[e]?.usageCount??0}_increaseReferenceCount(e){this._activeTextures[e].usageCount++}_applyFilters(e,t){let n=this._renderer.renderTarget.renderTarget,r=this._renderer.filter.generateFilteredTexture({texture:e,filters:t});return this._renderer.renderTarget.bind({target:n,clear:!1}),r}destroy(){this._renderer=null;for(let e in this._activeTextures)this._activeTextures[e]&&this.returnTexture(this._activeTextures[e].texture);this._activeTextures=null}};N();var xO=class extends bO{constructor(e){super(e,!0)}};xO.extension={type:[j.CanvasSystem],name:`canvasText`},N();var SO=class extends bO{constructor(e){super(e,!1)}};SO.extension={type:[j.WebGLSystem,j.WebGPUSystem],name:`canvasText`},N(),M.add(xO),M.add(SO),M.add(yO),xa(),va(),XT(),rE();var CO=class extends oO{constructor(...e){let t=sO(e,`Text`);super(t,nE),this.renderPipeId=`text`,t.textureStyle&&(this.textureStyle=t.textureStyle instanceof _a?t.textureStyle:new _a(t.textureStyle)),this.autoGenerateMipmaps=t.autoGenerateMipmaps??ba.defaultOptions.autoGenerateMipmaps}updateBounds(){let e=this._bounds,t=this._anchor,n=0,r=0;if(this._style.trim){let{frame:e,canvasAndContext:t}=gO.getCanvasAndContext({text:this.text,style:this._style,resolution:1});gO.returnCanvasAndContext(t),n=e.width,r=e.height}else{let e=YT.measureText(this._text,this._style);n=e.width,r=e.height}e.minX=-t._x*n,e.maxX=e.minX+n,e.minY=-t._y*r,e.maxY=e.minY+r}};wc(),Tg(),Cw(),XT(),bE(),mE();var wO=class extends Sw{destroy(){this.context.customShader&&this.context.customShader.destroy(),super.destroy()}},TO=class{constructor(e){this._renderer=e,this._managedBitmapTexts=new wg({renderer:e,type:`renderable`,priority:-2,name:`bitmapText`})}validateRenderable(e){let t=this._getGpuBitmapText(e);return this._renderer.renderPipes.graphics.validateRenderable(t)}addRenderable(e,t){let n=this._getGpuBitmapText(e);EO(e,n),e._didTextUpdate&&(e._didTextUpdate=!1,this._updateContext(e,n)),this._renderer.renderPipes.graphics.addRenderable(n,t),n.context.customShader&&this._updateDistanceField(e)}updateRenderable(e){let t=this._getGpuBitmapText(e);EO(e,t),this._renderer.renderPipes.graphics.updateRenderable(t),t.context.customShader&&this._updateDistanceField(e)}_updateContext(e,t){let{context:n}=t,r=yE.getFont(e.text,e._style);if(n.clear(),r.distanceField.type!==`none`){let e=this.getSdfShader();e&&(n.customShader||=e)}let i=YT.graphemeSegmenter(e.text),a=e._style,o=r.baseLineOffset,s=uE(i,a,r,!0),c=a.padding,l=s.scale,u=s.width,d=s.height+s.offsetY;a._stroke&&(u+=a._stroke.width/l,d+=a._stroke.width/l),n.translate(-e._anchor._x*u-c,-e._anchor._y*d-c).scale(l,l);let f=r.applyFillAsTint?a._fill.color:16777215,p=r.fontMetrics.fontSize,m=r.lineHeight;a.lineHeight&&(p=a.fontSize/l,m=a.lineHeight/l);let h=(m-p)/2;h-r.baseLineOffset<0&&(h=0);for(let e=0;e<s.lines.length;e++){let t=s.lines[e];for(let e=0;e<t.charPositions.length;e++){let i=t.chars[e],a=r.chars[i];if(a?.texture){let r=a.texture;n.texture(r,f,Math.round(t.charPositions[e]+a.xOffset),Math.round(o+a.yOffset+h),r.orig.width,r.orig.height)}}o+=m}}_getGpuBitmapText(e){return e._gpuData[this._renderer.uid]||this.initGpuText(e)}initGpuText(e){let t=new wO;return e._gpuData[this._renderer.uid]=t,this._updateContext(e,t),this._managedBitmapTexts.add(e),t}_updateDistanceField(e){let t=this._getGpuBitmapText(e).context,n=e._style.fontFamily,r=J.get(`${n}-bitmap`),{a:i,b:a,c:o,d:s}=e.groupTransform,c=Math.sqrt(i*i+a*a),l=Math.sqrt(o*o+s*s),u=(Math.abs(c)+Math.abs(l))/2,d=r.baseRenderedFontSize/e._style.fontSize,f=u*r.distanceField.range*(1/d);t.customShader.resources.localUniforms.uniforms.uDistance=f}destroy(){this._managedBitmapTexts.destroy(),this._renderer=null,this._managedBitmapTexts=null}};function EO(e,t){t.groupTransform=e.groupTransform,t.groupColorAlpha=e.groupColorAlpha,t.groupColor=e.groupColor,t.groupBlendMode=e.groupBlendMode,t.globalDisplayStatus=e.globalDisplayStatus,t.groupTransform=e.groupTransform,t.localDisplayStatus=e.localDisplayStatus,t.groupAlpha=e.groupAlpha,t._roundPixels=e._roundPixels}N();var DO=class extends TO{getSdfShader(){return null}};DO.extension={type:[j.CanvasPipes],name:`bitmapText`};var OO={name:`local-uniform-msdf-bit`,vertex:{header:`
1204
+ `}};I(),mp(),kp(),Mp(),Su(),bu(),W();var JD,YD,XD=class extends xu{constructor(){JD??=fp({name:`tiling-sprite-shader`,bits:[Ep,KD,Ap]}),YD??=pp({name:`tiling-sprite-shader`,bits:[Op,qD,jp]});let e=new yu({uMapCoord:{value:new F,type:`mat3x3<f32>`},uClampFrame:{value:new Float32Array([0,0,1,1]),type:`vec4<f32>`},uClampOffset:{value:new Float32Array([0,0]),type:`vec2<f32>`},uTextureTransform:{value:new F,type:`mat3x3<f32>`},uSizeAnchor:{value:new Float32Array([100,100,.5,.5]),type:`vec4<f32>`}});super({glProgram:YD,gpuProgram:JD,resources:{localUniforms:new yu({uTransformMatrix:{value:new F,type:`mat3x3<f32>`},uColor:{value:new Float32Array([1,1,1,1]),type:`vec4<f32>`},uRound:{value:0,type:`f32`}}),tilingUniforms:e,uTexture:U.EMPTY.source,uSampler:U.EMPTY.source.style}})}updateUniforms(e,t,n,r,i,a){let o=this.resources.tilingUniforms,s=a.width,c=a.height,l=a.textureMatrix,u=o.uniforms.uTextureTransform;u.set(n.a*s/e,n.b*s/t,n.c*c/e,n.d*c/t,n.tx/e,n.ty/t),u.invert(),o.uniforms.uMapCoord=l.mapCoord,o.uniforms.uClampFrame=l.uClampFrame,o.uniforms.uClampOffset=l.uClampOffset,o.uniforms.uTextureTransform=u,o.uniforms.uSizeAnchor[0]=e,o.uniforms.uSizeAnchor[1]=t,o.uniforms.uSizeAnchor[2]=r,o.uniforms.uSizeAnchor[3]=i,a&&(this.resources.uTexture=a.source,this.resources.uSampler=a.source.style)}},ZD=class extends zD{constructor(){super({positions:new Float32Array([0,0,1,0,1,1,0,1]),uvs:new Float32Array([0,0,1,0,1,1,0,1]),indices:new Uint32Array([0,1,2,0,2,3])})}};function QD(e,t){let n=e.anchor.x,r=e.anchor.y;t[0]=-n*e.width,t[1]=-r*e.height,t[2]=(1-n)*e.width,t[3]=-r*e.height,t[4]=(1-n)*e.width,t[5]=(1-r)*e.height,t[6]=-n*e.width,t[7]=(1-r)*e.height}function $D(e,t,n,r){let i=0,a=e.length/(t||2),o=r.a,s=r.b,c=r.c,l=r.d,u=r.tx,d=r.ty;for(n*=t;i<a;){let r=e[n],a=e[n+1];e[n]=o*r+c*a+u,e[n+1]=s*r+l*a+d,n+=t,i++}}I();function eO(e,t){let n=e.texture,r=n.frame.width,i=n.frame.height,a=0,o=0;e.applyAnchorToTexture&&(a=e.anchor.x,o=e.anchor.y),t[0]=t[6]=-a,t[2]=t[4]=1-a,t[1]=t[3]=-o,t[5]=t[7]=1-o;let s=e._tileTransform.matrix,c=F.shared;c.set(s.a*r/e.width,s.b*r/e.height,s.c*i/e.width,s.d*i/e.height,s.tx/e.width,s.ty/e.height),c.invert(),$D(t,2,0,c)}N(),Em(),Nu(),uu(),Tg(),qh();var tO=new ZD,nO=class{constructor(){this.canBatch=!0,this.geometry=new zD({indices:tO.indices.slice(),positions:tO.positions.slice(),uvs:tO.uvs.slice()})}destroy(){this.geometry.destroy(),this.shader?.destroy()}},rO=class{constructor(e){this._state=Mu.default2d,this._renderer=e,this._managedTilingSprites=new wg({renderer:e,type:`renderable`,name:`tilingSprite`})}validateRenderable(e){let t=this._getTilingSpriteData(e),n=t.canBatch;this._updateCanBatch(e);let r=t.canBatch;if(r&&r===n){let{batchableMesh:n}=t;return!n._batcher.checkAndUpdateTexture(n,e.texture)}return n!==r}addRenderable(e,t){let n=this._renderer.renderPipes.batch;this._updateCanBatch(e);let r=this._getTilingSpriteData(e),{geometry:i,canBatch:a}=r;if(a){r.batchableMesh||=new BD;let a=r.batchableMesh;e.didViewUpdate&&(this._updateBatchableMesh(e),a.geometry=i,a.renderable=e,a.transform=e.groupTransform,a.setTexture(e._texture)),a.roundPixels=this._renderer._roundPixels|e._roundPixels,n.addToBatch(a,t)}else n.break(t),r.shader||=new XD,this.updateRenderable(e),t.add(e)}execute(e){let t=this._renderer,{shader:n}=this._getTilingSpriteData(e);n.groups[0]=t.globalUniforms.bindGroup;let r=n.resources.localUniforms.uniforms;r.uTransformMatrix=e.groupTransform,r.uRound=t._roundPixels|e._roundPixels,Kh(e.groupColorAlpha,r.uColor,0),this._state.blendMode=Tm(e.groupBlendMode,e.texture._source),t.encoder.draw({geometry:tO,shader:n,state:this._state})}updateRenderable(e){let t=this._getTilingSpriteData(e),{canBatch:n}=t;if(n){let{batchableMesh:n}=t;e.didViewUpdate&&this._updateBatchableMesh(e),n._batcher.updateElement(n)}else if(e.didViewUpdate){let{shader:n}=t;n.updateUniforms(e.width,e.height,e._tileTransform.matrix,e.anchor.x,e.anchor.y,e.texture)}}_getTilingSpriteData(e){return e._gpuData[this._renderer.uid]||this._initTilingSpriteData(e)}_initTilingSpriteData(e){let t=new nO;return t.renderable=e,e._gpuData[this._renderer.uid]=t,this._managedTilingSprites.add(e),t}_updateBatchableMesh(e){let{geometry:t}=this._getTilingSpriteData(e),n=e.texture.source.style;n.addressMode!==`repeat`&&(n.addressMode=`repeat`,n.update()),eO(e,t.uvs),QD(e,t.positions)}destroy(){this._managedTilingSprites.destroy(),this._renderer=null}_updateCanBatch(e){let t=this._getTilingSpriteData(e),n=e.texture,r=!0;return this._renderer.type===lu.WEBGL&&(r=this._renderer.context.supports.nonPowOf2wrapping),t.canBatch=n.textureMatrix.isSimple&&(r||n.source.isPowerOfTwo),t.canBatch}};rO.extension={type:[j.WebGLPipes,j.WebGPUPipes],name:`tilingSprite`},N(),M.add(GD),M.add(rO),wc(),Ur(),W(),Xr(),Yo();var iO=class e extends Jo{constructor(...t){let n=t[0]||{};n instanceof U&&(n={texture:n}),t.length>1&&(R(L,`use new TilingSprite({ texture, width:100, height:100 }) instead`),n.width=t[1],n.height=t[2]),n={...e.defaultOptions,...n};let{texture:r,anchor:i,tilePosition:a,tileScale:o,tileRotation:s,width:c,height:l,applyAnchorToTexture:u,roundPixels:d,...f}=n??{};super({label:`TilingSprite`,...f}),this.renderPipeId=`tilingSprite`,this.batched=!0,this.allowChildren=!1,this._anchor=new Hr({_onUpdate:()=>{this.onViewUpdate()}}),this.applyAnchorToTexture=u,this.texture=r,this._width=c??r.width,this._height=l??r.height,this._tileTransform=new VD({observer:{_onUpdate:()=>this.onViewUpdate()}}),i&&(this.anchor=i),this.tilePosition=a,this.tileScale=o,this.tileRotation=s,this.roundPixels=d??!1}static from(t,n={}){return typeof t==`string`?new e({texture:J.get(t),...n}):new e({texture:t,...n})}get uvRespectAnchor(){return R(L,`uvRespectAnchor is deprecated, please use applyAnchorToTexture instead`),this.applyAnchorToTexture}set uvRespectAnchor(e){R(L,`uvRespectAnchor is deprecated, please use applyAnchorToTexture instead`),this.applyAnchorToTexture=e}get clampMargin(){return this._texture.textureMatrix.clampMargin}set clampMargin(e){this._texture.textureMatrix.clampMargin=e}get anchor(){return this._anchor}set anchor(e){typeof e==`number`?this._anchor.set(e):this._anchor.copyFrom(e)}get tilePosition(){return this._tileTransform.position}set tilePosition(e){this._tileTransform.position.copyFrom(e)}get tileScale(){return this._tileTransform.scale}set tileScale(e){typeof e==`number`?this._tileTransform.scale.set(e):this._tileTransform.scale.copyFrom(e)}set tileRotation(e){this._tileTransform.rotation=e}get tileRotation(){return this._tileTransform.rotation}get tileTransform(){return this._tileTransform}set texture(e){e||=U.EMPTY;let t=this._texture;t!==e&&(t&&t.dynamic&&t.off(`update`,this.onViewUpdate,this),e.dynamic&&e.on(`update`,this.onViewUpdate,this),this._texture=e,this.onViewUpdate())}get texture(){return this._texture}set width(e){this._width=e,this.onViewUpdate()}get width(){return this._width}set height(e){this._height=e,this.onViewUpdate()}get height(){return this._height}setSize(e,t){typeof e==`object`&&(t=e.height??e.width,e=e.width),this._width=e,this._height=t??e,this.onViewUpdate()}getSize(e){return e||={},e.width=this._width,e.height=this._height,e}updateBounds(){let e=this._bounds,t=this._anchor,n=this._width,r=this._height;e.minX=-t._x*n,e.maxX=e.minX+n,e.minY=-t._y*r,e.maxY=e.minY+r}containsPoint(e){let t=this._width,n=this._height,r=-t*this._anchor._x,i=0;return e.x>=r&&e.x<=r+t&&(i=-n*this._anchor._y,e.y>=i&&e.y<=i+n)}destroy(e=!1){if(super.destroy(e),this._anchor=null,this._tileTransform=null,this._bounds=null,typeof e==`boolean`?e:e?.texture){let t=typeof e==`boolean`?e:e?.textureSource;this._texture.destroy(t)}this._texture=null}};iO.defaultOptions={texture:U.EMPTY,anchor:{x:0,y:0},tilePosition:{x:0,y:0},tileScale:{x:1,y:1},tileRotation:0,applyAnchorToTexture:!1};var aO=iO;Ur(),Xr(),Yo();var oO=class extends Jo{constructor(e,t){let{text:n,resolution:r,style:i,anchor:a,width:o,height:s,roundPixels:c,...l}=e;super({...l}),this.batched=!0,this._resolution=null,this._autoResolution=!0,this._didTextUpdate=!0,this._styleClass=t,this.text=n??``,this.style=i,this.resolution=r??null,this.allowChildren=!1,this._anchor=new Hr({_onUpdate:()=>{this.onViewUpdate()}}),a&&(this.anchor=a),this.roundPixels=c??!1,o!==void 0&&(this.width=o),s!==void 0&&(this.height=s)}get anchor(){return this._anchor}set anchor(e){typeof e==`number`?this._anchor.set(e):this._anchor.copyFrom(e)}set text(e){e=e.toString(),this._text!==e&&(this._text=e,this.onViewUpdate())}get text(){return this._text}set resolution(e){this._autoResolution=e===null,this._resolution=e,this.onViewUpdate()}get resolution(){return this._resolution}get style(){return this._style}set style(e){e||={},this._style?.off(`update`,this.onViewUpdate,this),this._style=e instanceof this._styleClass?e:new this._styleClass(e),this._style.on(`update`,this.onViewUpdate,this),this.onViewUpdate()}get width(){return Math.abs(this.scale.x)*this.bounds.width}set width(e){this._setWidth(e,this.bounds.width)}get height(){return Math.abs(this.scale.y)*this.bounds.height}set height(e){this._setHeight(e,this.bounds.height)}getSize(e){return e||={},e.width=Math.abs(this.scale.x)*this.bounds.width,e.height=Math.abs(this.scale.y)*this.bounds.height,e}setSize(e,t){typeof e==`object`?(t=e.height??e.width,e=e.width):t??=e,e!==void 0&&this._setWidth(e,this.bounds.width),t!==void 0&&this._setHeight(t,this.bounds.height)}containsPoint(e){let t=this.bounds.width,n=this.bounds.height,r=-t*this.anchor.x,i=0;return e.x>=r&&e.x<=r+t&&(i=-n*this.anchor.y,e.y>=i&&e.y<=i+n)}onViewUpdate(){this.didViewUpdate||(this._didTextUpdate=!0),super.onViewUpdate()}destroy(e=!1){this._style?.off(`update`,this.onViewUpdate,this),super.destroy(e),this.owner=null,this._bounds=null,this._anchor=null,(typeof e==`boolean`?e:e?.style)&&this._style.destroy(e),this._style=null,this._text=null}get styleKey(){return`${this._text}:${this._style.styleKey}:${this._resolution}`}};function sO(e,t){let n=e[0]??{};return(typeof n==`string`||e[1])&&(R(L,`use new ${t}({ text: "hi!", style }) instead`),n={text:n,style:e[1]}),n}q(),da(),wi();var cO=null,lO=null;function uO(e,t){cO||(cO=K.get().createCanvas(256,128),lO=cO.getContext(`2d`,{willReadFrequently:!0}),lO.globalCompositeOperation=`copy`,lO.globalAlpha=1),(cO.width<e||cO.height<t)&&(cO.width=la(e),cO.height=la(t))}function dO(e,t,n){for(let r=0,i=4*n*t;r<t;++r,i+=4)if(e[i+3]!==0)return!1;return!0}function fO(e,t,n,r,i){let a=4*t;for(let t=r,o=r*a+4*n;t<=i;++t,o+=a)if(e[o+3]!==0)return!1;return!0}function pO(...e){let t=e[0];t.canvas||(t={canvas:e[0],resolution:e[1]});let{canvas:n}=t,r=Math.min(t.resolution??1,1),i=t.width??n.width,a=t.height??n.height,o=t.output;if(uO(i,a),!lO)throw TypeError(`Failed to get canvas 2D context`);lO.drawImage(n,0,0,i,a,0,0,i*r,a*r);let s=lO.getImageData(0,0,i,a).data,c=0,l=0,u=i-1,d=a-1;for(;l<a&&dO(s,i,l);)++l;if(l===a)return V.EMPTY;for(;dO(s,i,d);)--d;for(;fO(s,i,c,l,d);)++c;for(;fO(s,i,u,l,d);)--u;return++u,++d,lO.globalCompositeOperation=`source-over`,lO.strokeRect(c,l,u-c,d-l),lO.globalCompositeOperation=`copy`,o??=new V,o.set(c/r,l/r,(u-c)/r,(d-l)/r),o}Ar(),wi(),Rc(),XT(),$T(),oE();var mO=new V;function hO(e){let t=0;for(let n=0;n<e.length;n++)e.charCodeAt(n)===32&&t++;return t}var gO=new class{getCanvasAndContext(e){let{text:t,style:n,resolution:r=1}=e,i=n._getFinalPadding(),a=YT.measureText(t||` `,n),o=Math.ceil(Math.ceil(Math.max(1,a.width)+i*2)*r),s=Math.ceil(Math.ceil(Math.max(1,a.height)+i*2)*r),c=Lc.getOptimalCanvasAndContext(o,s);return this._renderTextToCanvas(n,i,r,c,a),{canvasAndContext:c,frame:n.trim?pO({canvas:c.canvas,width:o,height:s,resolution:1,output:mO}):mO.set(0,0,o,s)}}returnCanvasAndContext(e){Lc.returnCanvasAndContext(e)}_renderTextToCanvas(e,t,n,r,i){if(i.runsByLine&&i.runsByLine.length>0){this._renderTaggedTextToCanvas(i,e,t,n,r);return}let{canvas:a,context:o}=r,s=ZT(e),c=i.lines,l=i.lineHeight,u=i.lineWidths,d=i.maxLineWidth,f=i.fontProperties,p=a.height;if(o.resetTransform(),o.scale(n,n),o.textBaseline=e.textBaseline,e._stroke?.width){let t=e._stroke;o.lineWidth=t.width,o.miterLimit=t.miterLimit,o.lineJoin=t.join,o.lineCap=t.cap}o.font=s;let m,h,g=e.dropShadow?2:1,_=(e._stroke?.width??0)/2,v=(l-f.fontSize)/2;l-f.fontSize<0&&(v=0);for(let a=0;a<g;++a){let s=e.dropShadow&&a===0,g=s?Math.ceil(Math.max(1,p)+t*2):0,y=g*n;if(s)this._setupDropShadow(o,e,n,y);else{let n=e._gradientBounds,r=e._gradientOffset;if(n){let a={width:n.width,height:n.height,lineHeight:n.height,lines:i.lines};this._setFillAndStrokeStyles(o,e,a,t,_,r?.x??0,r?.y??0)}else r?this._setFillAndStrokeStyles(o,e,i,t,_,r.x,r.y):this._setFillAndStrokeStyles(o,e,i,t,_);o.shadowColor=`rgba(0,0,0,0)`}for(let n=0;n<c.length;n++){m=_,h=_+n*l+f.ascent+v,m+=this._getAlignmentOffset(u[n],d,e.align);let i=0;if(e.align===`justify`&&e.wordWrap&&n<c.length-1){let e=hO(c[n]);e>0&&(i=(d-u[n])/e)}e._stroke?.width&&this._drawLetterSpacing(c[n],e,r,m+t,h+t-g,!0,i),e._fill!==void 0&&this._drawLetterSpacing(c[n],e,r,m+t,h+t-g,!1,i)}}}_renderTaggedTextToCanvas(e,t,n,r,i){let{canvas:a,context:o}=i,{runsByLine:s,lineWidths:c,maxLineWidth:l,lineAscents:u,lineHeights:d,hasDropShadow:f}=e,p=a.height;o.resetTransform(),o.scale(r,r),o.textBaseline=t.textBaseline;let m=f?2:1,h=t._stroke?.width??0;for(let e of s)for(let t of e){let e=t.style._stroke?.width??0;e>h&&(h=e)}let g=h/2,_=[];for(let e=0;e<s.length;e++){let t=s[e],n=[];for(let e of t){let t=ZT(e.style);o.font=t,n.push({width:YT._measureText(e.text,e.style.letterSpacing,o),font:t})}_.push(n)}for(let e=0;e<m;++e){let a=f&&e===0,m=a?Math.ceil(Math.max(1,p)+n*2):0,h=m*r;a||(o.shadowColor=`rgba(0,0,0,0)`);let v=g;for(let e=0;e<s.length;e++){let f=s[e],p=c[e],y=u[e],b=d[e],x=_[e],S=g;S+=this._getAlignmentOffset(p,l,t.align);let C=0;if(t.align===`justify`&&t.wordWrap&&e<s.length-1){let e=0;for(let t of f)e+=hO(t.text);e>0&&(C=(l-p)/e)}let w=v+y,ee=S+n;for(let e=0;e<f.length;e++){let t=f[e],{width:s,font:c}=x[e];if(o.font=c,o.textBaseline=t.style.textBaseline,t.style._stroke?.width){let e=t.style._stroke;if(o.lineWidth=e.width,o.miterLimit=e.miterLimit,o.lineJoin=e.join,o.lineCap=e.cap,a){if(t.style.dropShadow)this._setupDropShadow(o,t.style,r,h);else{let e=hO(t.text);ee+=s+e*C;continue}}else{let r=YT.measureFont(c),i=t.style.lineHeight||r.fontSize;o.strokeStyle=iE(e,o,{width:s,height:i,lineHeight:i,lines:[t.text]},n*2,ee-n,v)}this._drawLetterSpacing(t.text,t.style,i,ee,w+n-m,!0,C)}let l=hO(t.text);ee+=s+l*C}ee=S+n;for(let e=0;e<f.length;e++){let t=f[e],{width:s,font:c}=x[e];if(o.font=c,o.textBaseline=t.style.textBaseline,t.style._fill!==void 0){if(a){if(t.style.dropShadow)this._setupDropShadow(o,t.style,r,h);else{let e=hO(t.text);ee+=s+e*C;continue}}else{let e=YT.measureFont(c),r=t.style.lineHeight||e.fontSize,i={width:s,height:r,lineHeight:r,lines:[t.text]};o.fillStyle=iE(t.style._fill,o,i,n*2,ee-n,v)}this._drawLetterSpacing(t.text,t.style,i,ee,w+n-m,!1,C)}let l=hO(t.text);ee+=s+l*C}v+=b}}}_setFillAndStrokeStyles(e,t,n,r,i,a=0,o=0){if(e.fillStyle=t._fill?iE(t._fill,e,n,r*2,a,o):null,t._stroke?.width){let s=i+r*2;e.strokeStyle=iE(t._stroke,e,n,s,a,o)}}_setupDropShadow(e,t,n,r){e.fillStyle=`black`,e.strokeStyle=`black`;let i=t.dropShadow,a=i.color,o=i.alpha;e.shadowColor=P.shared.setValue(a).setAlpha(o).toRgbaString();let s=i.blur*n,c=i.distance*n;e.shadowBlur=s,e.shadowOffsetX=Math.cos(i.angle)*c,e.shadowOffsetY=Math.sin(i.angle)*c+r}_getAlignmentOffset(e,t,n){return n===`right`?t-e:n===`center`?(t-e)/2:0}_drawLetterSpacing(e,t,n,r,i,a=!1,o=0){let{context:s}=n,c=t.letterSpacing,l=!1;if(YT.experimentalLetterSpacingSupported&&(YT.experimentalLetterSpacing?(s.letterSpacing=`${c}px`,s.textLetterSpacing=`${c}px`,l=!0):(s.letterSpacing=`0px`,s.textLetterSpacing=`0px`)),(c===0||l)&&o===0){a?s.strokeText(e,r,i):s.fillText(e,r,i);return}if(o!==0&&(c===0||l)){let t=e.split(` `),n=r,c=s.measureText(` `).width;for(let e=0;e<t.length;e++)a?s.strokeText(t[e],n,i):s.fillText(t[e],n,i),n+=s.measureText(t[e]).width+c+o;return}let u=r,d=YT.graphemeSegmenter(e),f=s.measureText(e).width,p=0;for(let e=0;e<d.length;++e){let t=d[e];a?s.strokeText(t,u,i):s.fillText(t,u,i);let n=``;for(let t=e+1;t<d.length;++t)n+=d[t];p=s.measureText(n).width,u+=f-p+c,t===` `&&(u+=o),f=p}}};Qs();function _O(e,t){let{texture:n,bounds:r}=e,i=t._style._getFinalPadding();Zs(r,t._anchor,n);let a=t._anchor._x*i*2,o=t._anchor._y*i*2;r.minX-=i-a,r.minY-=i-o,r.maxX-=i-a,r.maxY-=i-o}Kp();var vO=class extends Gp{};N(),Tg();var yO=class{constructor(e){this._renderer=e,e.runners.resolutionChange.add(this),this._managedTexts=new wg({renderer:e,type:`renderable`,onUnload:this.onTextUnload.bind(this),name:`canvasText`})}resolutionChange(){for(let e in this._managedTexts.items){let t=this._managedTexts.items[e];t?._autoResolution&&t.onViewUpdate()}}validateRenderable(e){let t=this._getGpuText(e),n=e.styleKey;return t.currentKey!==n||e._didTextUpdate}addRenderable(e,t){let n=this._getGpuText(e);if(e._didTextUpdate){let t=e._autoResolution?this._renderer.resolution:e.resolution;(n.currentKey!==e.styleKey||e._resolution!==t)&&this._updateGpuText(e),e._didTextUpdate=!1,_O(n,e)}this._renderer.renderPipes.batch.addToBatch(n,t)}updateRenderable(e){let t=this._getGpuText(e);t._batcher.updateElement(t)}_updateGpuText(e){let t=this._getGpuText(e);t.texture&&this._renderer.canvasText.decreaseReferenceCount(t.currentKey),e._resolution=e._autoResolution?this._renderer.resolution:e.resolution,t.texture=this._renderer.canvasText.getManagedTexture(e),t.currentKey=e.styleKey}_getGpuText(e){return e._gpuData[this._renderer.uid]||this.initGpuText(e)}initGpuText(e){let t=new vO;return t.currentKey=`--`,t.renderable=e,t.transform=e.groupTransform,t.bounds={minX:0,maxX:1,minY:0,maxY:0},t.roundPixels=this._renderer._roundPixels|e._roundPixels,e._gpuData[this._renderer.uid]=t,this._managedTexts.add(e),t}onTextUnload(e){let t=e._gpuData[this._renderer.uid];if(!t)return;let{canvasText:n}=this._renderer;n.getReferenceCount(t.currentKey)>0?n.decreaseReferenceCount(t.currentKey):t.texture&&n.returnTexture(t.texture)}destroy(){this._managedTexts.destroy(),this._renderer=null}};yO.extension={type:[j.WebGLPipes,j.WebGPUPipes,j.CanvasPipes],name:`text`},Va(),va(),Xr(),rE(),al();var bO=class{constructor(e,t){this._activeTextures={},this._renderer=e,this._retainCanvasContext=t}getTexture(e,t,n,r){typeof e==`string`&&(R(`8.0.0`,`CanvasTextSystem.getTexture: Use object TextOptions instead of separate arguments`),e={text:e,style:n,resolution:t}),e.style instanceof nE||(e.style=new nE(e.style)),e.textureStyle instanceof _a||(e.textureStyle=new _a(e.textureStyle)),typeof e.text!=`string`&&(e.text=e.text.toString());let{text:i,style:a,textureStyle:o,autoGenerateMipmaps:s}=e,c=e.resolution??this._renderer.resolution,{frame:l,canvasAndContext:u}=gO.getCanvasAndContext({text:i,style:a,resolution:c}),d=rl(u.canvas,l.width,l.height,c,s);if(o&&(d.source.style=o),a.trim&&(l.pad(a.padding),d.frame.copyFrom(l),d.frame.scale(1/c),d.updateUvs()),a.filters){let e=this._applyFilters(d,a.filters);return this.returnTexture(d),gO.returnCanvasAndContext(u),e}return this._renderer.texture.initSource(d._source),this._retainCanvasContext||gO.returnCanvasAndContext(u),d}returnTexture(e){let t=e.source,n=t.resource;if(this._retainCanvasContext&&n?.getContext){let e=n.getContext(`2d`);e&&gO.returnCanvasAndContext({canvas:n,context:e})}t.resource=null,t.uploadMethodId=`unknown`,t.alphaMode=`no-premultiply-alpha`,Ba.returnTexture(e,!0)}renderTextToCanvas(){R(`8.10.0`,`CanvasTextSystem.renderTextToCanvas: no longer supported, use CanvasTextSystem.getTexture instead`)}getManagedTexture(e){e._resolution=e._autoResolution?this._renderer.resolution:e.resolution;let t=e.styleKey;if(this._activeTextures[t])return this._increaseReferenceCount(t),this._activeTextures[t].texture;let n=this.getTexture({text:e.text,style:e.style,resolution:e._resolution,textureStyle:e.textureStyle,autoGenerateMipmaps:e.autoGenerateMipmaps});return this._activeTextures[t]={texture:n,usageCount:1},n}decreaseReferenceCount(e){let t=this._activeTextures[e];t&&(t.usageCount--,t.usageCount===0&&(this.returnTexture(t.texture),this._activeTextures[e]=null))}getReferenceCount(e){return this._activeTextures[e]?.usageCount??0}_increaseReferenceCount(e){this._activeTextures[e].usageCount++}_applyFilters(e,t){let n=this._renderer.renderTarget.renderTarget,r=this._renderer.filter.generateFilteredTexture({texture:e,filters:t});return this._renderer.renderTarget.bind({target:n,clear:!1}),r}destroy(){this._renderer=null;for(let e in this._activeTextures)this._activeTextures[e]&&this.returnTexture(this._activeTextures[e].texture);this._activeTextures=null}};N();var xO=class extends bO{constructor(e){super(e,!0)}};xO.extension={type:[j.CanvasSystem],name:`canvasText`},N();var SO=class extends bO{constructor(e){super(e,!1)}};SO.extension={type:[j.WebGLSystem,j.WebGPUSystem],name:`canvasText`},N(),M.add(xO),M.add(SO),M.add(yO),xa(),va(),XT(),rE();var CO=class extends oO{constructor(...e){let t=sO(e,`Text`);super(t,nE),this.renderPipeId=`text`,t.textureStyle&&(this.textureStyle=t.textureStyle instanceof _a?t.textureStyle:new _a(t.textureStyle)),this.autoGenerateMipmaps=t.autoGenerateMipmaps??ba.defaultOptions.autoGenerateMipmaps}updateBounds(){let e=this._bounds,t=this._anchor,n=0,r=0;if(this._style.trim){let{frame:e,canvasAndContext:t}=gO.getCanvasAndContext({text:this.text,style:this._style,resolution:1});gO.returnCanvasAndContext(t),n=e.width,r=e.height}else{let e=YT.measureText(this._text,this._style);n=e.width,r=e.height}e.minX=-t._x*n,e.maxX=e.minX+n,e.minY=-t._y*r,e.maxY=e.minY+r}};wc(),Tg(),Cw(),XT(),bE(),mE();var wO=class extends Sw{destroy(){this.context.customShader&&this.context.customShader.destroy(),super.destroy()}},TO=class{constructor(e){this._renderer=e,this._managedBitmapTexts=new wg({renderer:e,type:`renderable`,priority:-2,name:`bitmapText`})}validateRenderable(e){let t=this._getGpuBitmapText(e);return this._renderer.renderPipes.graphics.validateRenderable(t)}addRenderable(e,t){let n=this._getGpuBitmapText(e);EO(e,n),e._didTextUpdate&&(e._didTextUpdate=!1,this._updateContext(e,n)),this._renderer.renderPipes.graphics.addRenderable(n,t),n.context.customShader&&this._updateDistanceField(e)}updateRenderable(e){let t=this._getGpuBitmapText(e);EO(e,t),this._renderer.renderPipes.graphics.updateRenderable(t),t.context.customShader&&this._updateDistanceField(e)}_updateContext(e,t){let{context:n}=t,r=yE.getFont(e.text,e._style);if(n.clear(),r.distanceField.type!==`none`){let e=this.getSdfShader();e&&(n.customShader||=e)}let i=YT.graphemeSegmenter(e.text),a=e._style,o=r.baseLineOffset,s=uE(i,a,r,!0),c=a.padding,l=s.scale,u=s.width,d=s.height+s.offsetY;a._stroke&&(u+=a._stroke.width/l,d+=a._stroke.width/l),n.translate(-e._anchor._x*u-c,-e._anchor._y*d-c).scale(l,l);let f=r.applyFillAsTint?a._fill.color:16777215,p=r.fontMetrics.fontSize,m=r.lineHeight;a.lineHeight&&(p=a.fontSize/l,m=a.lineHeight/l);let h=(m-p)/2;h-r.baseLineOffset<0&&(h=0);for(let e=0;e<s.lines.length;e++){let t=s.lines[e];for(let e=0;e<t.charPositions.length;e++){let i=t.chars[e],a=r.chars[i];if(a?.texture){let r=a.texture;n.texture(r,f,Math.round(t.charPositions[e]+a.xOffset),Math.round(o+a.yOffset+h),r.orig.width,r.orig.height)}}o+=m}}_getGpuBitmapText(e){return e._gpuData[this._renderer.uid]||this.initGpuText(e)}initGpuText(e){let t=new wO;return e._gpuData[this._renderer.uid]=t,this._updateContext(e,t),this._managedBitmapTexts.add(e),t}_updateDistanceField(e){let t=this._getGpuBitmapText(e).context,n=e._style.fontFamily,r=J.get(`${n}-bitmap`),{a:i,b:a,c:o,d:s}=e.groupTransform,c=Math.sqrt(i*i+a*a),l=Math.sqrt(o*o+s*s),u=(Math.abs(c)+Math.abs(l))/2,d=r.baseRenderedFontSize/e._style.fontSize,f=u*r.distanceField.range*(1/d);t.customShader.resources.localUniforms.uniforms.uDistance=f}destroy(){this._managedBitmapTexts.destroy(),this._renderer=null,this._managedBitmapTexts=null}};function EO(e,t){t.groupTransform=e.groupTransform,t.groupColorAlpha=e.groupColorAlpha,t.groupColor=e.groupColor,t.groupBlendMode=e.groupBlendMode,t.globalDisplayStatus=e.globalDisplayStatus,t.groupTransform=e.groupTransform,t.localDisplayStatus=e.localDisplayStatus,t.groupAlpha=e.groupAlpha,t._roundPixels=e._roundPixels}N();var DO=class extends TO{getSdfShader(){return null}};DO.extension={type:[j.CanvasPipes],name:`bitmapText`};var OO={name:`local-uniform-msdf-bit`,vertex:{header:`
1205
1205
  struct LocalUniforms {
1206
1206
  uColor:vec4<f32>,
1207
1207
  uTransformMatrix:mat3x3<f32>,
@@ -1305,7 +1305,7 @@ fn mainFragment(
1305
1305
  src: url('${n}');
1306
1306
  }`}wc();var ek=new Map;async function tk(e){let t=e.filter(e=>J.has(`${e}-and-url`)).map(e=>{if(!ek.has(e)){let{entries:t}=J.get(`${e}-and-url`),n=[];t.forEach(t=>{let r=t.url,i=t.faces.map(e=>({weight:e.weight,style:e.style}));n.push(...i.map(t=>$O({fontWeight:t.weight,fontStyle:t.style,fontFamily:e},r)))}),ek.set(e,Promise.all(n).then(e=>e.join(`
1307
1307
  `)))}return ek.get(e)});return(await Promise.all(t)).join(`
1308
- `)}function nk(e,t,n,r,i){let{domElement:a,styleElement:o,svgRoot:s}=i;a.innerHTML=`<style>${t.cssStyle}</style><div style='padding:0;'>${e}</div>`,a.setAttribute(`style`,`transform: scale(${n});transform-origin: top left; display: inline-block`),o.textContent=r;let{width:c,height:l}=i.image;return s.setAttribute(`width`,c.toString()),s.setAttribute(`height`,l.toString()),new XMLSerializer().serializeToString(s)}Rc();function rk(e,t){let n=Lc.getOptimalCanvasAndContext(e.width,e.height,t),{context:r}=n;return r.clearRect(0,0,e.width,e.height),r.drawImage(e,0,0),n}function ik(e,t,n){return new Promise(async r=>{n&&await new Promise(e=>setTimeout(e,100)),e.onload=()=>{r()},e.src=`data:image/svg+xml;charset=utf8,${encodeURIComponent(t)}`,e.crossOrigin=`anonymous`})}N(),Rc(),Va(),uu(),jb(),B(),ai(),al();var ak=class{constructor(e){this._activeTextures={},this._renderer=e,this._createCanvas=e.type===lu.WEBGPU}getTexture(e){return this.getTexturePromise(e)}getManagedTexture(e){let t=e.styleKey;if(this._activeTextures[t])return this._increaseReferenceCount(t),this._activeTextures[t].promise;let n=this._buildTexturePromise(e).then(e=>(this._activeTextures[t].texture=e,e));return this._activeTextures[t]={texture:null,promise:n,usageCount:1},n}getReferenceCount(e){return this._activeTextures[e]?.usageCount??null}_increaseReferenceCount(e){this._activeTextures[e].usageCount++}decreaseReferenceCount(e){let t=this._activeTextures[e];t&&(t.usageCount--,t.usageCount===0&&(t.texture?this._cleanUp(t.texture):t.promise.then(e=>{t.texture=e,this._cleanUp(t.texture)}).catch(()=>{z(`HTMLTextSystem: Failed to clean texture`)}),this._activeTextures[e]=null))}getTexturePromise(e){return this._buildTexturePromise(e)}async _buildTexturePromise(e){let{text:t,style:n,resolution:r,textureStyle:i,autoGenerateMipmaps:a}=e,o=ii.get(KO),s=ZO(t,n),c=await tk(s),l=JO(t,n,c,o),u=Math.ceil(Math.ceil(Math.max(1,l.width)+n.padding*2)*r),d=Math.ceil(Math.ceil(Math.max(1,l.height)+n.padding*2)*r),f=o.image;f.width=(u|0)+2,f.height=(d|0)+2,await ik(f,nk(t,n,r,c,o),Ab()&&s.length>0);let p=f,m;this._createCanvas&&(m=rk(f,r));let h=rl(m?m.canvas:p,f.width-2,f.height-2,r,a);return i&&(h.source.style=i),this._createCanvas&&(this._renderer.texture.initSource(h.source),Lc.returnCanvasAndContext(m)),ii.return(o),h}returnTexturePromise(e){e.then(e=>{this._cleanUp(e)}).catch(()=>{z(`HTMLTextSystem: Failed to clean texture`)})}_cleanUp(e){Ba.returnTexture(e,!0),e.source.resource=null,e.source.uploadMethodId=`unknown`}destroy(){this._renderer=null;for(let e in this._activeTextures)this._activeTextures[e]&&this.returnTexturePromise(this._activeTextures[e].promise);this._activeTextures=null}};ak.extension={type:[j.WebGLSystem,j.WebGPUSystem,j.CanvasSystem],name:`htmlText`},N(),M.add(ak),M.add(XO),xa(),va();var ok=class extends oO{constructor(...e){let t=sO(e,`HtmlText`);super(t,UO),this.renderPipeId=`htmlText`,t.textureStyle&&(this.textureStyle=t.textureStyle instanceof _a?t.textureStyle:new _a(t.textureStyle)),this.autoGenerateMipmaps=t.autoGenerateMipmaps??ba.defaultOptions.autoGenerateMipmaps}updateBounds(){let e=this._bounds,t=this._anchor,{width:n,height:r}=JO(this.text,this._style);e.minX=-t._x*n,e.maxX=e.minX+n,e.minY=-t._y*r,e.maxY=e.minY+r}get text(){return this._text}set text(e){let t=this._sanitiseText(e.toString());super.text=t}_sanitiseText(e){return this._removeInvalidHtmlTags(e.replace(/<br>/gi,`<br/>`).replace(/<hr>/gi,`<hr/>`).replace(/&nbsp;/gi,`&#160;`))}_removeInvalidHtmlTags(e){return e.replace(/<[^>]*?(?=<|$)/g,``)}};Xr();var sk=class e extends zD{constructor(...e){super({});let t=e[0]??{};typeof t==`number`&&(R(L,`PlaneGeometry constructor changed please use { width, height, verticesX, verticesY } instead`),t={width:t,height:e[1],verticesX:e[2],verticesY:e[3]}),this.build(t)}build(t){t={...e.defaultOptions,...t},this.verticesX=this.verticesX??t.verticesX,this.verticesY=this.verticesY??t.verticesY,this.width=this.width??t.width,this.height=this.height??t.height;let n=this.verticesX*this.verticesY,r=[],i=[],a=[],o=this.verticesX-1,s=this.verticesY-1,c=this.width/o,l=this.height/s;for(let e=0;e<n;e++){let t=e%this.verticesX,n=e/this.verticesX|0;r.push(t*c,n*l),i.push(t/o,n/s)}let u=o*s;for(let e=0;e<u;e++){let t=e%o,n=e/o|0,r=n*this.verticesX+t,i=n*this.verticesX+t+1,s=(n+1)*this.verticesX+t,c=(n+1)*this.verticesX+t+1;a.push(r,i,s,i,c,s)}this.buffers[0].data=new Float32Array(r),this.buffers[1].data=new Float32Array(i),this.indexBuffer.data=new Uint32Array(a),this.buffers[0].update(),this.buffers[1].update(),this.indexBuffer.update()}};sk.defaultOptions={width:100,height:100,verticesX:10,verticesY:10};var ck=sk;N(),Fc(),Gi(),zi();var lk=class{constructor(e){this._renderer=e}validateRenderable(e){return!1}addRenderable(e,t){this._renderer.renderPipes.batch.break(t),t.add(e)}updateRenderable(e){}execute(e){let t=this._renderer,n=t.canvasContext,r=n.activeContext;r.save();let i=e.groupTransform,a=t._roundPixels|e._roundPixels;n.setContextTransform(i,a===1),n.setBlendMode(e.groupBlendMode);let o=t.globalUniforms.globalUniformData?.worldColor??4294967295,s=e.groupColorAlpha,c=(o>>>24&255)/255,l=(s>>>24&255)/255,u=t.filter?.alphaMultiplier??1,d=c*l*u;if(d<=0){r.restore();return}r.globalAlpha=d;let f=o&16777215,p=Ui(Ri(s&16777215,f)),m=e.texture,h=Y.getCanvasSource(m);if(!h){r.restore();return}let g=n.smoothProperty,_=m.source.style.scaleMode!==`nearest`;r[g]!==_&&(r[g]=_);let v=p!==16777215||m.rotate!==0,y=v?Y.getTintedCanvas({texture:m},p):h,{leftWidth:b,topHeight:x,rightWidth:S,bottomHeight:C,width:w,height:T}=e,E=b+S,D=x+C,ee=Math.min(E>w?w/E:1,D>T?T/D:1,1),te=b*ee,ne=S*ee,re=x*ee,O=C*ee,k=Math.max(0,w-te-ne),ie=Math.max(0,T-re-O),ae=e.anchor,oe=m.source._resolution??m.source.resolution??1,se=m.frame.x*oe,ce=m.frame.y*oe,A=-ae.x*w,le=-ae.y*T,ue=b*oe,de=x*oe,fe=S*oe,pe=C*oe,me=m.frame.width*oe,he=m.frame.height*oe;v&&(se=0,ce=0,me=y.width,he=y.height),r.drawImage(y,se,ce,ue,de,A,le,te,re),r.drawImage(y,se+ue,ce,me-ue-fe,de,A+te,le,k,re),r.drawImage(y,se+me-fe,ce,fe,de,A+w-ne,le,ne,re),r.drawImage(y,se,ce+de,ue,he-de-pe,A,le+re,te,ie),r.drawImage(y,se+ue,ce+de,me-ue-fe,he-de-pe,A+te,le+re,k,ie),r.drawImage(y,se+me-fe,ce+de,fe,he-de-pe,A+w-ne,le+re,ne,ie),r.drawImage(y,se,ce+he-pe,ue,pe,A,le+T-O,te,O),r.drawImage(y,se+ue,ce+he-pe,me-ue-fe,pe,A+te,le+T-O,k,O),r.drawImage(y,se+me-fe,ce+he-pe,fe,pe,A+w-ne,le+T-O,ne,O),r.restore()}destroy(){this._renderer=null}};lk.extension={type:[j.CanvasPipes],name:`nineSliceSprite`};var uk=class e extends ck{constructor(t={}){t={...e.defaultOptions,...t},super({width:t.width,height:t.height,verticesX:4,verticesY:4}),this._trimX=0,this._trimY=0,this._trimWidth=t.originalWidth??e.defaultOptions.originalWidth,this._trimHeight=t.originalHeight??e.defaultOptions.originalHeight,this.update(t)}update(e){this.width=e.width??this.width,this.height=e.height??this.height,this._originalWidth=e.originalWidth??this._originalWidth,this._originalHeight=e.originalHeight??this._originalHeight,this._leftWidth=e.leftWidth??this._leftWidth,this._rightWidth=e.rightWidth??this._rightWidth,this._topHeight=e.topHeight??this._topHeight,this._bottomHeight=e.bottomHeight??this._bottomHeight,this._anchorX=e.anchor?.x,this._anchorY=e.anchor?.y,e.trim===void 0?(this._trimWidth=this._originalWidth,this._trimHeight=this._originalHeight):(this._trimX=e.trim?.x??0,this._trimY=e.trim?.y??0,this._trimWidth=e.trim?.width??this._originalWidth,this._trimHeight=e.trim?.height??this._originalHeight),this.updateUvs(),this.updatePositions()}updatePositions(){let e=this.positions,{width:t,height:n,_leftWidth:r,_rightWidth:i,_topHeight:a,_bottomHeight:o,_anchorX:s,_anchorY:c}=this,l=r+i,u=t>l?1:t/l,d=a+o,f=n>d?1:n/d,p=Math.min(u,f),m=s*t,h=c*n;e[0]=e[8]=e[16]=e[24]=-m,e[2]=e[10]=e[18]=e[26]=r*p-m,e[4]=e[12]=e[20]=e[28]=t-i*p-m,e[6]=e[14]=e[22]=e[30]=t-m,e[1]=e[3]=e[5]=e[7]=-h,e[9]=e[11]=e[13]=e[15]=a*p-h,e[17]=e[19]=e[21]=e[23]=n-o*p-h,e[25]=e[27]=e[29]=e[31]=n-h,this.getBuffer(`aPosition`).update()}updateUvs(){let e=this.uvs,t=this._originalWidth,n=this._originalHeight,r=this._trimX/t,i=this._trimY/n,a=(this._trimX+this._trimWidth)/t,o=(this._trimY+this._trimHeight)/n;e[0]=e[8]=e[16]=e[24]=r,e[1]=e[3]=e[5]=e[7]=i,e[6]=e[14]=e[22]=e[30]=a,e[25]=e[27]=e[29]=e[31]=o;let s=1/t,c=1/n;e[2]=e[10]=e[18]=e[26]=r+s*this._leftWidth,e[9]=e[11]=e[13]=e[15]=i+c*this._topHeight,e[4]=e[12]=e[20]=e[28]=a-s*this._rightWidth,e[17]=e[19]=e[21]=e[23]=o-c*this._bottomHeight,this.getBuffer(`aUV`).update()}};uk.defaultOptions={width:100,height:100,leftWidth:10,topHeight:10,rightWidth:10,bottomHeight:10,originalWidth:100,originalHeight:100};var dk=uk;N(),Tg();var fk=class extends BD{constructor(){super(),this.geometry=new dk}destroy(){this.geometry.destroy()}},pk=class{constructor(e){this._renderer=e,this._managedSprites=new wg({renderer:e,type:`renderable`,name:`nineSliceSprite`})}addRenderable(e,t){let n=this._getGpuSprite(e);e.didViewUpdate&&this._updateBatchableSprite(e,n),this._renderer.renderPipes.batch.addToBatch(n,t)}updateRenderable(e){let t=this._getGpuSprite(e);e.didViewUpdate&&this._updateBatchableSprite(e,t),t._batcher.updateElement(t)}validateRenderable(e){let t=this._getGpuSprite(e);return!t._batcher.checkAndUpdateTexture(t,e._texture)}_updateBatchableSprite(e,t){t.geometry.update(e),t.setTexture(e._texture)}_getGpuSprite(e){return e._gpuData[this._renderer.uid]||this._initGPUSprite(e)}_initGPUSprite(e){let t=e._gpuData[this._renderer.uid]=new fk,n=t;return n.renderable=e,n.transform=e.groupTransform,n.texture=e._texture,n.roundPixels=this._renderer._roundPixels|e._roundPixels,this._managedSprites.add(e),e.didViewUpdate||this._updateBatchableSprite(e,n),t}destroy(){this._managedSprites.destroy(),this._renderer=null}};pk.extension={type:[j.WebGLPipes,j.WebGPUPipes],name:`nineSliceSprite`},N(),M.add(lk),M.add(pk),Ur(),W(),Yo();var mk=class e extends Jo{constructor(t){t instanceof U&&(t={texture:t});let{width:n,height:r,anchor:i,leftWidth:a,rightWidth:o,topHeight:s,bottomHeight:c,texture:l,roundPixels:u,...d}=t;super({label:`NineSliceSprite`,...d}),this.renderPipeId=`nineSliceSprite`,this.batched=!0,this._leftWidth=a??l?.defaultBorders?.left??dk.defaultOptions.leftWidth,this._topHeight=s??l?.defaultBorders?.top??dk.defaultOptions.topHeight,this._rightWidth=o??l?.defaultBorders?.right??dk.defaultOptions.rightWidth,this._bottomHeight=c??l?.defaultBorders?.bottom??dk.defaultOptions.bottomHeight,this._width=n??l.width??dk.defaultOptions.width,this._height=r??l.height??dk.defaultOptions.height,this.allowChildren=!1,this.texture=l??e.defaultOptions.texture,this.roundPixels=u??!1,this._anchor=new Hr({_onUpdate:()=>{this.onViewUpdate()}}),i?this.anchor=i:this.texture.defaultAnchor&&(this.anchor=this.texture.defaultAnchor)}get anchor(){return this._anchor}set anchor(e){typeof e==`number`?this._anchor.set(e):this._anchor.copyFrom(e)}get width(){return this._width}set width(e){this._width=e,this.onViewUpdate()}get height(){return this._height}set height(e){this._height=e,this.onViewUpdate()}setSize(e,t){typeof e==`object`&&(t=e.height??e.width,e=e.width),this._width=e,this._height=t??e,this.onViewUpdate()}getSize(e){return e||={},e.width=this._width,e.height=this._height,e}get leftWidth(){return this._leftWidth}set leftWidth(e){this._leftWidth=e,this.onViewUpdate()}get topHeight(){return this._topHeight}set topHeight(e){this._topHeight=e,this.onViewUpdate()}get rightWidth(){return this._rightWidth}set rightWidth(e){this._rightWidth=e,this.onViewUpdate()}get bottomHeight(){return this._bottomHeight}set bottomHeight(e){this._bottomHeight=e,this.onViewUpdate()}get texture(){return this._texture}set texture(e){e||=U.EMPTY;let t=this._texture;t!==e&&(t&&t.dynamic&&t.off(`update`,this.onViewUpdate,this),e.dynamic&&e.on(`update`,this.onViewUpdate,this),this._texture=e,this.onViewUpdate())}get originalWidth(){return this._texture.width}get originalHeight(){return this._texture.height}get trim(){return this._texture.trim??null}destroy(e){if(super.destroy(e),typeof e==`boolean`?e:e?.texture){let t=typeof e==`boolean`?e:e?.textureSource;this._texture.destroy(t)}this._texture=null}updateBounds(){let e=this._bounds,t=this._anchor,n=this._width,r=this._height;e.minX=-t._x*n,e.maxX=e.minX+n,e.minY=-t._y*r,e.maxY=e.minY+r}};mk.defaultOptions={texture:U.EMPTY};var hk=mk;N(),Ac(),Xs(),wi(),Wm(),mp(),_p(),Tp(),Mp(),Zm(),qu(),Gu(),ed(),Su(),Ph(),xa(),W(),kc(),Xa(),Sx(),Cw(),ec(),rE(),Xn(),M.add(cd,dd);var gk=`mwg-pixel-art`;function _k(){if(document.getElementById(gk))return;let e=document.createElement(`style`);e.id=gk,e.textContent=`.${gk} { image-rendering: pixelated; }`,document.head.appendChild(e)}function vk(e){let t=null,n=()=>{t=matchMedia(`(resolution: ${window.devicePixelRatio}dppx)`),t.addEventListener(`change`,r,{once:!0})},r=()=>{e(),n()};return n(),()=>t?.removeEventListener(`change`,r)}var yk=class e{static{this.instance=null}constructor(t={}){this.app=new iT,this.elapsed=0,this.timeTotal=0,this.timeScale=1,this.onFrame=new p,this.hitStopRemaining=0,this.hitStopScale=0,this.stack=new h,this.pending=[],this.started=!1,this.stopWatchingDpr=null,this.options={canvas:t.canvas??document.createElement(`canvas`),background:t.background??0,maxDelta:t.maxDelta??.25,pixelArt:t.pixelArt??!0,resizeTo:t.resizeTo??window,extensions:t.extensions??[]},this.options.pixelArt&&(ba.defaultOptions.scaleMode=`nearest`),e.instance=this}get width(){return this.app.renderer.screen.width}get height(){return this.app.renderer.screen.height}static get current(){if(!e.instance)throw Error(`no Game has been created yet`);return e.instance}async start(e){if(this.started)throw Error(`this Game has already been started`);this.started=!0;for(let e of this.options.extensions)e();vt(),await this.app.init({canvas:this.options.canvas,background:this.options.background,resizeTo:this.options.resizeTo,antialias:!1,preserveDrawingBuffer:!1,resolution:window.devicePixelRatio||1,autoDensity:!0}),this.options.canvas.isConnected||document.body.appendChild(this.options.canvas),this.options.pixelArt&&(_k(),this.options.canvas.classList.add(gk)),this.app.renderer.on(`resize`,()=>{this.stack.resize(this.width,this.height)}),this.stopWatchingDpr=vk(()=>{this.app.renderer.resize(this.width,this.height,window.devicePixelRatio||1)}),this.expose(),this.switchNow(e),this.app.ticker.add(e=>this.frame(e.deltaMS/1e3))}switchScene(e){this.pending.push({kind:`switch`,next:e})}pushScene(e){this.pending.push({kind:`push`,next:e})}popScene(e){this.pending.push({kind:`pop`,result:e})}get currentScene(){return this.stack.current}hitStop(e,t=0){this.hitStopRemaining=e,this.hitStopScale=t}step(e){this.frame(e),this.app.renderer.render(this.app.stage)}expose(){let e=globalThis;e.__PIXI_APP__=this.app,e.__MWG__=this}frame(e){for(let e of this.pending)e.kind===`switch`?this.applySwitch(e.next):e.kind===`push`?this.applyPush(e.next):this.applyPop(e.result);this.pending.length=0,this.hitStopRemaining>0&&(this.hitStopRemaining-=e,this.timeScale=this.hitStopRemaining>0?this.hitStopScale:1),this.elapsed=Math.min(e,this.options.maxDelta)*this.timeScale,this.timeTotal+=this.elapsed,lt(),this.stack.update(this.elapsed),this.onFrame.dispatch(this.elapsed),Ye()}switchNow(e){this.applySwitch(e)}applySwitch(e){let t=new e;this.stack.replace(t),this.app.stage.removeChildren(),this.app.stage.addChild(t.stage),this.elapsed=0,this.timeTotal=0,this.timeScale=1,t.resize(this.width,this.height)}applyPush(e){let t=new e;this.stack.push(t),this.app.stage.addChild(t.stage),this.elapsed=0,this.timeTotal=0,this.timeScale=1,t.resize(this.width,this.height)}applyPop(e){let t=this.stack.current;this.stack.pop(e),t&&this.app.stage.removeChild(t.stage)}destroy(){yt(),this.stopWatchingDpr?.(),this.stack.destroy(),this.onFrame.removeAll(),this.app.destroy(!0,{children:!0}),e.instance===this&&(e.instance=null)}},bk=class extends m{constructor(...e){super(...e),this.stage=new G}teardown(){this.stage.destroy({children:!0})}},xk={name:`color-add-bit`,vertex:{header:`
1308
+ `)}function nk(e,t,n,r,i){let{domElement:a,styleElement:o,svgRoot:s}=i;a.innerHTML=`<style>${t.cssStyle}</style><div style='padding:0;'>${e}</div>`,a.setAttribute(`style`,`transform: scale(${n});transform-origin: top left; display: inline-block`),o.textContent=r;let{width:c,height:l}=i.image;return s.setAttribute(`width`,c.toString()),s.setAttribute(`height`,l.toString()),new XMLSerializer().serializeToString(s)}Rc();function rk(e,t){let n=Lc.getOptimalCanvasAndContext(e.width,e.height,t),{context:r}=n;return r.clearRect(0,0,e.width,e.height),r.drawImage(e,0,0),n}function ik(e,t,n){return new Promise(async r=>{n&&await new Promise(e=>setTimeout(e,100)),e.onload=()=>{r()},e.src=`data:image/svg+xml;charset=utf8,${encodeURIComponent(t)}`,e.crossOrigin=`anonymous`})}N(),Rc(),Va(),uu(),jb(),B(),ai(),al();var ak=class{constructor(e){this._activeTextures={},this._renderer=e,this._createCanvas=e.type===lu.WEBGPU}getTexture(e){return this.getTexturePromise(e)}getManagedTexture(e){let t=e.styleKey;if(this._activeTextures[t])return this._increaseReferenceCount(t),this._activeTextures[t].promise;let n=this._buildTexturePromise(e).then(e=>(this._activeTextures[t].texture=e,e));return this._activeTextures[t]={texture:null,promise:n,usageCount:1},n}getReferenceCount(e){return this._activeTextures[e]?.usageCount??null}_increaseReferenceCount(e){this._activeTextures[e].usageCount++}decreaseReferenceCount(e){let t=this._activeTextures[e];t&&(t.usageCount--,t.usageCount===0&&(t.texture?this._cleanUp(t.texture):t.promise.then(e=>{t.texture=e,this._cleanUp(t.texture)}).catch(()=>{z(`HTMLTextSystem: Failed to clean texture`)}),this._activeTextures[e]=null))}getTexturePromise(e){return this._buildTexturePromise(e)}async _buildTexturePromise(e){let{text:t,style:n,resolution:r,textureStyle:i,autoGenerateMipmaps:a}=e,o=ii.get(KO),s=ZO(t,n),c=await tk(s),l=JO(t,n,c,o),u=Math.ceil(Math.ceil(Math.max(1,l.width)+n.padding*2)*r),d=Math.ceil(Math.ceil(Math.max(1,l.height)+n.padding*2)*r),f=o.image;f.width=(u|0)+2,f.height=(d|0)+2,await ik(f,nk(t,n,r,c,o),Ab()&&s.length>0);let p=f,m;this._createCanvas&&(m=rk(f,r));let h=rl(m?m.canvas:p,f.width-2,f.height-2,r,a);return i&&(h.source.style=i),this._createCanvas&&(this._renderer.texture.initSource(h.source),Lc.returnCanvasAndContext(m)),ii.return(o),h}returnTexturePromise(e){e.then(e=>{this._cleanUp(e)}).catch(()=>{z(`HTMLTextSystem: Failed to clean texture`)})}_cleanUp(e){Ba.returnTexture(e,!0),e.source.resource=null,e.source.uploadMethodId=`unknown`}destroy(){this._renderer=null;for(let e in this._activeTextures)this._activeTextures[e]&&this.returnTexturePromise(this._activeTextures[e].promise);this._activeTextures=null}};ak.extension={type:[j.WebGLSystem,j.WebGPUSystem,j.CanvasSystem],name:`htmlText`},N(),M.add(ak),M.add(XO),xa(),va();var ok=class extends oO{constructor(...e){let t=sO(e,`HtmlText`);super(t,UO),this.renderPipeId=`htmlText`,t.textureStyle&&(this.textureStyle=t.textureStyle instanceof _a?t.textureStyle:new _a(t.textureStyle)),this.autoGenerateMipmaps=t.autoGenerateMipmaps??ba.defaultOptions.autoGenerateMipmaps}updateBounds(){let e=this._bounds,t=this._anchor,{width:n,height:r}=JO(this.text,this._style);e.minX=-t._x*n,e.maxX=e.minX+n,e.minY=-t._y*r,e.maxY=e.minY+r}get text(){return this._text}set text(e){let t=this._sanitiseText(e.toString());super.text=t}_sanitiseText(e){return this._removeInvalidHtmlTags(e.replace(/<br>/gi,`<br/>`).replace(/<hr>/gi,`<hr/>`).replace(/&nbsp;/gi,`&#160;`))}_removeInvalidHtmlTags(e){return e.replace(/<[^>]*?(?=<|$)/g,``)}};Xr();var sk=class e extends zD{constructor(...e){super({});let t=e[0]??{};typeof t==`number`&&(R(L,`PlaneGeometry constructor changed please use { width, height, verticesX, verticesY } instead`),t={width:t,height:e[1],verticesX:e[2],verticesY:e[3]}),this.build(t)}build(t){t={...e.defaultOptions,...t},this.verticesX=this.verticesX??t.verticesX,this.verticesY=this.verticesY??t.verticesY,this.width=this.width??t.width,this.height=this.height??t.height;let n=this.verticesX*this.verticesY,r=[],i=[],a=[],o=this.verticesX-1,s=this.verticesY-1,c=this.width/o,l=this.height/s;for(let e=0;e<n;e++){let t=e%this.verticesX,n=e/this.verticesX|0;r.push(t*c,n*l),i.push(t/o,n/s)}let u=o*s;for(let e=0;e<u;e++){let t=e%o,n=e/o|0,r=n*this.verticesX+t,i=n*this.verticesX+t+1,s=(n+1)*this.verticesX+t,c=(n+1)*this.verticesX+t+1;a.push(r,i,s,i,c,s)}this.buffers[0].data=new Float32Array(r),this.buffers[1].data=new Float32Array(i),this.indexBuffer.data=new Uint32Array(a),this.buffers[0].update(),this.buffers[1].update(),this.indexBuffer.update()}};sk.defaultOptions={width:100,height:100,verticesX:10,verticesY:10};var ck=sk;N(),Fc(),Gi(),zi();var lk=class{constructor(e){this._renderer=e}validateRenderable(e){return!1}addRenderable(e,t){this._renderer.renderPipes.batch.break(t),t.add(e)}updateRenderable(e){}execute(e){let t=this._renderer,n=t.canvasContext,r=n.activeContext;r.save();let i=e.groupTransform,a=t._roundPixels|e._roundPixels;n.setContextTransform(i,a===1),n.setBlendMode(e.groupBlendMode);let o=t.globalUniforms.globalUniformData?.worldColor??4294967295,s=e.groupColorAlpha,c=(o>>>24&255)/255,l=(s>>>24&255)/255,u=t.filter?.alphaMultiplier??1,d=c*l*u;if(d<=0){r.restore();return}r.globalAlpha=d;let f=o&16777215,p=Ui(Ri(s&16777215,f)),m=e.texture,h=Y.getCanvasSource(m);if(!h){r.restore();return}let g=n.smoothProperty,_=m.source.style.scaleMode!==`nearest`;r[g]!==_&&(r[g]=_);let v=p!==16777215||m.rotate!==0,y=v?Y.getTintedCanvas({texture:m},p):h,{leftWidth:b,topHeight:x,rightWidth:S,bottomHeight:C,width:w,height:ee}=e,T=b+S,E=x+C,te=Math.min(T>w?w/T:1,E>ee?ee/E:1,1),D=b*te,ne=S*te,re=x*te,O=C*te,k=Math.max(0,w-D-ne),ie=Math.max(0,ee-re-O),ae=e.anchor,oe=m.source._resolution??m.source.resolution??1,se=m.frame.x*oe,ce=m.frame.y*oe,A=-ae.x*w,le=-ae.y*ee,ue=b*oe,de=x*oe,fe=S*oe,pe=C*oe,me=m.frame.width*oe,he=m.frame.height*oe;v&&(se=0,ce=0,me=y.width,he=y.height),r.drawImage(y,se,ce,ue,de,A,le,D,re),r.drawImage(y,se+ue,ce,me-ue-fe,de,A+D,le,k,re),r.drawImage(y,se+me-fe,ce,fe,de,A+w-ne,le,ne,re),r.drawImage(y,se,ce+de,ue,he-de-pe,A,le+re,D,ie),r.drawImage(y,se+ue,ce+de,me-ue-fe,he-de-pe,A+D,le+re,k,ie),r.drawImage(y,se+me-fe,ce+de,fe,he-de-pe,A+w-ne,le+re,ne,ie),r.drawImage(y,se,ce+he-pe,ue,pe,A,le+ee-O,D,O),r.drawImage(y,se+ue,ce+he-pe,me-ue-fe,pe,A+D,le+ee-O,k,O),r.drawImage(y,se+me-fe,ce+he-pe,fe,pe,A+w-ne,le+ee-O,ne,O),r.restore()}destroy(){this._renderer=null}};lk.extension={type:[j.CanvasPipes],name:`nineSliceSprite`};var uk=class e extends ck{constructor(t={}){t={...e.defaultOptions,...t},super({width:t.width,height:t.height,verticesX:4,verticesY:4}),this._trimX=0,this._trimY=0,this._trimWidth=t.originalWidth??e.defaultOptions.originalWidth,this._trimHeight=t.originalHeight??e.defaultOptions.originalHeight,this.update(t)}update(e){this.width=e.width??this.width,this.height=e.height??this.height,this._originalWidth=e.originalWidth??this._originalWidth,this._originalHeight=e.originalHeight??this._originalHeight,this._leftWidth=e.leftWidth??this._leftWidth,this._rightWidth=e.rightWidth??this._rightWidth,this._topHeight=e.topHeight??this._topHeight,this._bottomHeight=e.bottomHeight??this._bottomHeight,this._anchorX=e.anchor?.x,this._anchorY=e.anchor?.y,e.trim===void 0?(this._trimWidth=this._originalWidth,this._trimHeight=this._originalHeight):(this._trimX=e.trim?.x??0,this._trimY=e.trim?.y??0,this._trimWidth=e.trim?.width??this._originalWidth,this._trimHeight=e.trim?.height??this._originalHeight),this.updateUvs(),this.updatePositions()}updatePositions(){let e=this.positions,{width:t,height:n,_leftWidth:r,_rightWidth:i,_topHeight:a,_bottomHeight:o,_anchorX:s,_anchorY:c}=this,l=r+i,u=t>l?1:t/l,d=a+o,f=n>d?1:n/d,p=Math.min(u,f),m=s*t,h=c*n;e[0]=e[8]=e[16]=e[24]=-m,e[2]=e[10]=e[18]=e[26]=r*p-m,e[4]=e[12]=e[20]=e[28]=t-i*p-m,e[6]=e[14]=e[22]=e[30]=t-m,e[1]=e[3]=e[5]=e[7]=-h,e[9]=e[11]=e[13]=e[15]=a*p-h,e[17]=e[19]=e[21]=e[23]=n-o*p-h,e[25]=e[27]=e[29]=e[31]=n-h,this.getBuffer(`aPosition`).update()}updateUvs(){let e=this.uvs,t=this._originalWidth,n=this._originalHeight,r=this._trimX/t,i=this._trimY/n,a=(this._trimX+this._trimWidth)/t,o=(this._trimY+this._trimHeight)/n;e[0]=e[8]=e[16]=e[24]=r,e[1]=e[3]=e[5]=e[7]=i,e[6]=e[14]=e[22]=e[30]=a,e[25]=e[27]=e[29]=e[31]=o;let s=1/t,c=1/n;e[2]=e[10]=e[18]=e[26]=r+s*this._leftWidth,e[9]=e[11]=e[13]=e[15]=i+c*this._topHeight,e[4]=e[12]=e[20]=e[28]=a-s*this._rightWidth,e[17]=e[19]=e[21]=e[23]=o-c*this._bottomHeight,this.getBuffer(`aUV`).update()}};uk.defaultOptions={width:100,height:100,leftWidth:10,topHeight:10,rightWidth:10,bottomHeight:10,originalWidth:100,originalHeight:100};var dk=uk;N(),Tg();var fk=class extends BD{constructor(){super(),this.geometry=new dk}destroy(){this.geometry.destroy()}},pk=class{constructor(e){this._renderer=e,this._managedSprites=new wg({renderer:e,type:`renderable`,name:`nineSliceSprite`})}addRenderable(e,t){let n=this._getGpuSprite(e);e.didViewUpdate&&this._updateBatchableSprite(e,n),this._renderer.renderPipes.batch.addToBatch(n,t)}updateRenderable(e){let t=this._getGpuSprite(e);e.didViewUpdate&&this._updateBatchableSprite(e,t),t._batcher.updateElement(t)}validateRenderable(e){let t=this._getGpuSprite(e);return!t._batcher.checkAndUpdateTexture(t,e._texture)}_updateBatchableSprite(e,t){t.geometry.update(e),t.setTexture(e._texture)}_getGpuSprite(e){return e._gpuData[this._renderer.uid]||this._initGPUSprite(e)}_initGPUSprite(e){let t=e._gpuData[this._renderer.uid]=new fk,n=t;return n.renderable=e,n.transform=e.groupTransform,n.texture=e._texture,n.roundPixels=this._renderer._roundPixels|e._roundPixels,this._managedSprites.add(e),e.didViewUpdate||this._updateBatchableSprite(e,n),t}destroy(){this._managedSprites.destroy(),this._renderer=null}};pk.extension={type:[j.WebGLPipes,j.WebGPUPipes],name:`nineSliceSprite`},N(),M.add(lk),M.add(pk),Ur(),W(),Yo();var mk=class e extends Jo{constructor(t){t instanceof U&&(t={texture:t});let{width:n,height:r,anchor:i,leftWidth:a,rightWidth:o,topHeight:s,bottomHeight:c,texture:l,roundPixels:u,...d}=t;super({label:`NineSliceSprite`,...d}),this.renderPipeId=`nineSliceSprite`,this.batched=!0,this._leftWidth=a??l?.defaultBorders?.left??dk.defaultOptions.leftWidth,this._topHeight=s??l?.defaultBorders?.top??dk.defaultOptions.topHeight,this._rightWidth=o??l?.defaultBorders?.right??dk.defaultOptions.rightWidth,this._bottomHeight=c??l?.defaultBorders?.bottom??dk.defaultOptions.bottomHeight,this._width=n??l.width??dk.defaultOptions.width,this._height=r??l.height??dk.defaultOptions.height,this.allowChildren=!1,this.texture=l??e.defaultOptions.texture,this.roundPixels=u??!1,this._anchor=new Hr({_onUpdate:()=>{this.onViewUpdate()}}),i?this.anchor=i:this.texture.defaultAnchor&&(this.anchor=this.texture.defaultAnchor)}get anchor(){return this._anchor}set anchor(e){typeof e==`number`?this._anchor.set(e):this._anchor.copyFrom(e)}get width(){return this._width}set width(e){this._width=e,this.onViewUpdate()}get height(){return this._height}set height(e){this._height=e,this.onViewUpdate()}setSize(e,t){typeof e==`object`&&(t=e.height??e.width,e=e.width),this._width=e,this._height=t??e,this.onViewUpdate()}getSize(e){return e||={},e.width=this._width,e.height=this._height,e}get leftWidth(){return this._leftWidth}set leftWidth(e){this._leftWidth=e,this.onViewUpdate()}get topHeight(){return this._topHeight}set topHeight(e){this._topHeight=e,this.onViewUpdate()}get rightWidth(){return this._rightWidth}set rightWidth(e){this._rightWidth=e,this.onViewUpdate()}get bottomHeight(){return this._bottomHeight}set bottomHeight(e){this._bottomHeight=e,this.onViewUpdate()}get texture(){return this._texture}set texture(e){e||=U.EMPTY;let t=this._texture;t!==e&&(t&&t.dynamic&&t.off(`update`,this.onViewUpdate,this),e.dynamic&&e.on(`update`,this.onViewUpdate,this),this._texture=e,this.onViewUpdate())}get originalWidth(){return this._texture.width}get originalHeight(){return this._texture.height}get trim(){return this._texture.trim??null}destroy(e){if(super.destroy(e),typeof e==`boolean`?e:e?.texture){let t=typeof e==`boolean`?e:e?.textureSource;this._texture.destroy(t)}this._texture=null}updateBounds(){let e=this._bounds,t=this._anchor,n=this._width,r=this._height;e.minX=-t._x*n,e.maxX=e.minX+n,e.minY=-t._y*r,e.maxY=e.minY+r}};mk.defaultOptions={texture:U.EMPTY};var hk=mk;N(),Ac(),Xs(),wi(),Wm(),mp(),_p(),Tp(),Mp(),Zm(),qu(),Gu(),ed(),Su(),Ph(),xa(),W(),kc(),Xa(),Sx(),Cw(),ec(),rE(),Xn(),M.add(cd,dd);var gk=`mwg-pixel-art`;function _k(){if(document.getElementById(gk))return;let e=document.createElement(`style`);e.id=gk,e.textContent=`.${gk} { image-rendering: pixelated; }`,document.head.appendChild(e)}function vk(e){let t=null,n=()=>{t=matchMedia(`(resolution: ${window.devicePixelRatio}dppx)`),t.addEventListener(`change`,r,{once:!0})},r=()=>{e(),n()};return n(),()=>t?.removeEventListener(`change`,r)}var yk=class e{static{this.instance=null}constructor(t={}){this.app=new iT,this.elapsed=0,this.timeTotal=0,this.timeScale=1,this.onFrame=new p,this.hitStopRemaining=0,this.hitStopScale=0,this.stack=new h,this.pending=[],this.started=!1,this.stopWatchingDpr=null,this.options={canvas:t.canvas??document.createElement(`canvas`),background:t.background??0,maxDelta:t.maxDelta??.25,pixelArt:t.pixelArt??!0,resizeTo:t.resizeTo??window,extensions:t.extensions??[]},this.options.pixelArt&&(ba.defaultOptions.scaleMode=`nearest`),e.instance=this}get width(){return this.app.renderer.screen.width}get height(){return this.app.renderer.screen.height}static get current(){if(!e.instance)throw Error(`no Game has been created yet`);return e.instance}async start(e){if(this.started)throw Error(`this Game has already been started`);this.started=!0;for(let e of this.options.extensions)e();vt(),await this.app.init({canvas:this.options.canvas,background:this.options.background,resizeTo:this.options.resizeTo,antialias:!1,preserveDrawingBuffer:!1,resolution:window.devicePixelRatio||1,autoDensity:!0}),this.options.canvas.isConnected||document.body.appendChild(this.options.canvas),this.options.pixelArt&&(_k(),this.options.canvas.classList.add(gk)),this.app.renderer.on(`resize`,()=>{this.stack.resize(this.width,this.height)}),this.stopWatchingDpr=vk(()=>{this.app.renderer.resize(this.width,this.height,window.devicePixelRatio||1)}),this.expose(),this.switchNow(e),this.app.ticker.add(e=>this.frame(e.deltaMS/1e3))}switchScene(e){this.pending.push({kind:`switch`,next:e})}pushScene(e){this.pending.push({kind:`push`,next:e})}popScene(e){this.pending.push({kind:`pop`,result:e})}get currentScene(){return this.stack.current}hitStop(e,t=0){this.hitStopRemaining=e,this.hitStopScale=t}step(e){this.frame(e),this.app.renderer.render(this.app.stage)}expose(){let e=globalThis;e.__PIXI_APP__=this.app,e.__MWG__=this}frame(e){for(let e of this.pending)e.kind===`switch`?this.applySwitch(e.next):e.kind===`push`?this.applyPush(e.next):this.applyPop(e.result);this.pending.length=0,this.hitStopRemaining>0&&(this.hitStopRemaining-=e,this.timeScale=this.hitStopRemaining>0?this.hitStopScale:1),this.elapsed=Math.min(e,this.options.maxDelta)*this.timeScale,this.timeTotal+=this.elapsed,lt(),this.stack.update(this.elapsed),this.onFrame.dispatch(this.elapsed),Ye()}switchNow(e){this.applySwitch(e)}applySwitch(e){let t=new e;this.stack.replace(t),this.app.stage.removeChildren(),this.app.stage.addChild(t.stage),this.elapsed=0,this.timeTotal=0,this.timeScale=1,t.resize(this.width,this.height)}applyPush(e){let t=new e;this.stack.push(t),this.app.stage.addChild(t.stage),this.elapsed=0,this.timeTotal=0,this.timeScale=1,t.resize(this.width,this.height)}applyPop(e){let t=this.stack.current;this.stack.pop(e),t&&this.app.stage.removeChild(t.stage)}destroy(){yt(),this.stopWatchingDpr?.(),this.stack.destroy(),this.onFrame.removeAll(),this.app.destroy(!0,{children:!0}),e.instance===this&&(e.instance=null)}},bk=class extends m{constructor(...e){super(...e),this.stage=new G}teardown(){this.stage.destroy({children:!0})}},xk={name:`color-add-bit`,vertex:{header:`
1309
1309
  in vec4 aColorAdd;
1310
1310
  out vec4 vColorAdd;
1311
1311
  `,main:`
@@ -1328,21 +1328,21 @@ fn mainFragment(
1328
1328
  `,end:`
1329
1329
  let addedAlpha = finalColor.a + vColorAdd.a;
1330
1330
  finalColor = vec4<f32>(finalColor.rgb + vColorAdd.rgb * addedAlpha, addedAlpha);
1331
- `}},Ck=class extends xu{constructor(e){super({glProgram:pp({name:`color-transform-batch`,bits:[gp,xk,Sp(e),jp]}),gpuProgram:fp({name:`color-transform-batch`,bits:[hp,Sk,bp(e),Ap]}),resources:{batchSamplers:Ym(e)}}),this.maxTextures=e}},wk=7,Tk=class extends $u{constructor(){let e=new Ku({data:new Float32Array(1),label:`mwg-color-transform-attribute-buffer`,usage:X.VERTEX|X.COPY_DST,shrinkToFit:!1}),t=new Ku({data:new Uint32Array(1),label:`mwg-color-transform-index-buffer`,usage:X.INDEX|X.COPY_DST,shrinkToFit:!1});super({attributes:{aPosition:{buffer:e,format:`float32x2`,stride:28,offset:0},aUV:{buffer:e,format:`float32x2`,stride:28,offset:8},aColor:{buffer:e,format:`unorm8x4`,stride:28,offset:16},aTextureIdAndRound:{buffer:e,format:`uint16x2`,stride:28,offset:20},aColorAdd:{buffer:e,format:`unorm8x4`,stride:28,offset:24}},indexBuffer:t})}},Ek=0,Dk=e=>e.colorAdd??Ek;function Ok(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h){e[n]=r*l+a*u+s,e[n+1]=o*u+i*l+c,e[n+2]=d,e[n+3]=f,t[n+4]=p,t[n+5]=m,t[n+6]=h}var kk=class e extends Um{static{this.extension={type:[j.Batcher],name:`mwg-color-transform`}}constructor(t){super(t),this.geometry=new Tk,this.name=e.extension.name,this.vertexSize=wk,this.shader=new Ck(t.maxTextures)}packAttributes(e,t,n,r,i){let a=i<<16|e.roundPixels&65535,{a:o,b:s,c,d:l,tx:u,ty:d}=e.transform,{positions:f,uvs:p}=e,m=e.color,h=Dk(e),g=e.attributeOffset,_=g+e.attributeSize;for(let e=g;e<_;e++){let i=e*2,g=f[i],_=f[i+1];t[r++]=o*g+c*_+u,t[r++]=l*_+s*g+d,t[r++]=p[i],t[r++]=p[i+1],n[r++]=m,n[r++]=a,n[r++]=h}}packQuadAttributes(e,t,n,r,i){let{a,b:o,c:s,d:c,tx:l,ty:u}=e.transform,{bounds:d}=e,f=e.texture.uvs,p=d.maxX,m=d.minX,h=d.maxY,g=d.minY,_=e.color,v=Dk(e),y=i<<16|e.roundPixels&65535;Ok(t,n,r,a,o,s,c,l,u,m,g,f.x0,f.y0,_,y,v),r+=wk,Ok(t,n,r,a,o,s,c,l,u,p,g,f.x1,f.y1,_,y,v),r+=wk,Ok(t,n,r,a,o,s,c,l,u,p,h,f.x2,f.y2,_,y,v),r+=wk,Ok(t,n,r,a,o,s,c,l,u,m,h,f.x3,f.y3,_,y,v)}_updateMaxTextures(e){this.shader.maxTextures!==e&&(this.shader.destroy(),this.shader=new Ck(e))}destroy(){this.shader.destroy(),super.destroy()}},Ak=`mwg-tinted-sprite`,jk=class{static{this.extension={type:[j.WebGLPipes,j.WebGPUPipes,j.CanvasPipes],name:Ak}}constructor(e){this.renderer=e}addRenderable(e,t){let n=this.element(e);e.didViewUpdate&&this.sync(e,n),this.renderer.renderPipes.batch.addToBatch(n,t)}updateRenderable(e){let t=this.element(e);e.didViewUpdate&&this.sync(e,t),t._batcher.updateElement(t)}validateRenderable(e){let t=this.element(e);return!t._batcher.checkAndUpdateTexture(t,e.texture)}sync(e,t){t.bounds=e.visualBounds,t.texture=e.texture,t.colorAdd=e.colorAdd}element(e){let t=e._gpuData;return t[this.renderer.uid]??this.create(e,t)}create(e,t){let n=new Mk;return n.renderable=e,n.transform=e.groupTransform,n.texture=e.texture,n.bounds=e.visualBounds,n.roundPixels=this.renderer._roundPixels|e._roundPixels,n.colorAdd=e.colorAdd,t[this.renderer.uid]=n,n}destroy(){this.renderer=null}},Mk=class{constructor(){this.batcherName=kk.extension.name,this.topology=`triangle-list`,this.attributeSize=4,this.indexSize=6,this.packAsQuad=!0,this.roundPixels=0,this.colorAdd=0,this._attributeStart=0,this._textureId=0,this._indexStart=0,this._batcher=null,this._batch=null}get blendMode(){return this.renderable.groupBlendMode}get color(){return this.renderable.groupColorAlpha}reset(){this.renderable=null,this.texture=null,this._batcher=null,this._batch=null,this.bounds=null,this.colorAdd=0}destroy(){this.reset()}},Nk=!1;function Pk(){Nk||(Nk=!0,M.add(kk),M.add(jk))}function Fk(e,t,n,r=0){return(Lk(r)<<24|Lk(n)<<16|Lk(t)<<8|Lk(e))>>>0}function Ik(e,t){return Fk((e>>16&255)/255*t,(e>>8&255)/255*t,(e&255)/255*t)}function Lk(e){return Math.max(0,Math.min(255,Math.round(e*255)))}var Rk=Ek;Pk();var zk=class extends $s{constructor(e){super(e),this._colorAdd=0,this.renderPipeId=Ak}get colorAdd(){return this._colorAdd}set colorAdd(e){this._colorAdd!==e&&(this._colorAdd=e,this.onViewUpdate())}setColorAdd(e,t,n,r=0){this.colorAdd=Fk(e,t,n,r)}lerpTint(e,t){let n=Math.round((1-t)*255);this.tint=n<<16|n<<8|n,this.colorAdd=Ik(e,t)}silhouette(e){this.tint=0,this.colorAdd=Ik(e,1)}resetColor(){this.tint=16777215,this.colorAdd=0}};function Bk(e){return[e>>16&255,e>>8&255,e&255]}function Vk(e,t,n){return Math.round(e)<<16|Math.round(t)<<8|Math.round(n)}function Hk(e,t,n){return e+(t-e)*n}function Uk(e,t,n){let[r,i,a]=Bk(e),[o,s,c]=Bk(t);return Vk(Hk(r,o,n),Hk(i,s,n),Hk(a,c,n))}function Wk(e,t){return{from:e,to:e.map((n,r)=>{if(e.length<=1)return t.mid;let i=r/(e.length-1);return i<=.5?Uk(t.min,t.mid,i*2):Uk(t.mid,t.max,(i-.5)*2)})}}function Gk(e,t,n=`exact`){let r=t.from.map(Bk),i=new Uint8ClampedArray(e.length);for(let a=0;a<e.length;a+=4){let o=e[a+3],s=e[a],c=e[a+1],l=e[a+2];if(i[a]=s,i[a+1]=c,i[a+2]=l,i[a+3]=o,o===0||r.length===0)continue;if(n===`exact`){let e=r.findIndex(([e,t,n])=>e===s&&t===c&&n===l);if(e<0)continue;let[n,o,u]=Bk(t.to[e]??t.from[e]);i[a]=n,i[a+1]=o,i[a+2]=u;continue}let u=0,d=1/0;for(let e=0;e<r.length;e+=1){let[t,n,i]=r[e],a=s-t,o=c-n,f=l-i,p=a*a+o*o+f*f;p<d&&(d=p,u=e)}let[f,p,m]=Bk(t.to[u]??t.from[u]);i[a]=f,i[a+1]=p,i[a+2]=m}return i}function Kk(e,t,n){let r=e.width,i=e.height;if(r<=0||i<=0||!e.source)return e;let a=t.createCanvas?.(r,i)??(typeof document>`u`?null:document.createElement(`canvas`));if(!a)return e;a.width=r,a.height=i;let o=a.getContext(`2d`);return o?(o.drawImage(e.source.resource,0,0),n(o,r,i),U.from(a)):e}function qk(e,t,n={},r=`exact`){return Kk(e,n,(e,n,i)=>{let a=Gk(e.getImageData(0,0,n,i).data,t,r);e.putImageData({data:a,width:n,height:i},0,0)})}function Jk(e){e=e.replace(/^"|"$/g,``);let t=[],n=0,r=0;for(let i=0;i<e.length;i+=1)e[i]===`(`?r+=1:e[i]===`)`?r=Math.max(0,r-1):e[i]===`~`&&r===0&&(t.push(e.slice(n,i)),n=i+1);t.push(e.slice(n));let i=(t.shift()??``).trim(),a=[];for(let e of t){let t=/^([A-Za-z][A-Za-z0-9_-]*)(?:\((.*)\))?$/.exec(e.trim());t&&a.push({name:t[1].toUpperCase(),args:t[2]===void 0?[]:t[2].split(`,`).map(e=>e.trim())})}return{path:i,modifiers:a}}function Yk(e,t){return e.modifiers.find(e=>e.name===t.toUpperCase())}function Xk(e,t,n){return[1,0,0,0,e/255,0,1,0,0,t/255,0,0,1,0,n/255,0,0,0,1,0]}function Zk(e){return[(e.red??100)/100,0,0,0,0,0,(e.green??100)/100,0,0,0,0,0,(e.blue??100)/100,0,0,0,0,0,1,0]}function Qk(e,t){let n=1-t,r=(e>>16&255)/255,i=(e>>8&255)/255,a=(e&255)/255;return[n,0,0,0,r*t,0,n,0,0,i*t,0,0,n,0,a*t,0,0,0,1,0]}function $k(e){let t=[`R`,`G`,`B`,`A`].map((t,n)=>e[n]??t),n=e=>{switch(e){case`R`:return[1,0,0,0,0];case`G`:return[0,1,0,0,0];case`B`:return[0,0,1,0,0];case`A`:return[0,0,0,1,0];case`0`:return[0,0,0,0,0];case`1`:return[0,0,0,0,1]}};return t.flatMap(e=>n(e))}function eA(e){if(e===void 0)return;let t=e.trim(),n=t.endsWith(`%`),r=Number(n?t.slice(0,-1):t);if(Number.isFinite(r))return n||r>1?r/100:r}function tA(e){if(e===void 0)return;let t=Number.parseInt(e.replace(/^#/,``),16);return Number.isFinite(t)?t:void 0}function nA(e,t,n=1){let r=Yk(t,`FL`);r&&(r.args.length===0||r.args.some(e=>/horiz|horizontal|x/i.test(e)))&&(e.scale.x*=-1),r?.args.some(e=>/vert|vertical|y/i.test(e))&&(e.scale.y*=-1);let i=Yk(t,`SCALE`);if(i){let t=Number(i.args[0]),r=Number(i.args[1]??i.args[0]);Number.isFinite(t)&&t>0&&(e.width=t*n),Number.isFinite(r)&&r>0&&(e.height=r*n)}if(Yk(t,`GS`)){let t=new LD;t.greyscale(1,!1),e.filters=[...e.filters??[],t]}let a=Yk(t,`CS`);if(a){let t=a.args.slice(0,3).map(Number);if(t.length===3&&t.every(e=>Number.isFinite(e))){let n=new LD;n.matrix=Xk(t[0],t[1],t[2]),e.filters=[...e.filters??[],n]}}let o=Yk(t,`R`),s=Yk(t,`G`),c=Yk(t,`B`);if(o||s||c){let t=o?Number(o.args[0]):void 0,n=s?Number(s.args[0]):void 0,r=c?Number(c.args[0]):void 0,i=new LD;i.matrix=Zk({red:Number.isFinite(t)?t:void 0,green:Number.isFinite(n)?n:void 0,blue:Number.isFinite(r)?r:void 0}),e.filters=[...e.filters??[],i]}let l=Yk(t,`CHAN`);if(l&&l.args.length>0){let t=l.args.map(e=>e.trim().toUpperCase()),n=new LD;n.matrix=$k(t),e.filters=[...e.filters??[],n]}let u=Yk(t,`O`);if(u){let t=eA(u.args[0]);t!==void 0&&(e.alpha*=Math.min(1,Math.max(0,t)))}}function rA(e,t){let n=Yk(t,`CROP`);if(!n||n.args.length<4||!e.source)return e;let r=n.args.slice(0,4).map(Number);if(r.some(e=>!Number.isFinite(e))||r[2]<=0||r[3]<=0)return e;let i=Math.max(0,r[0]),a=Math.max(0,r[1]),o=Math.min(r[2],Math.max(0,e.width-i)),s=Math.min(r[3],Math.max(0,e.height-a));return o>0&&s>0?new U({source:e.source,frame:new V(i,a,o,s)}):e}function iA(e,t){let n=e.trim();return tA(n)??t?.(n)}function aA(e,t){let n=[],r=[];for(let i of e){let[e,a]=i.split(`>`);if(e===void 0||a===void 0)continue;let o=iA(e,t),s=iA(a,t);o!==void 0&&s!==void 0&&(n.push(o),r.push(s))}return{from:n,to:r}}function oA(e,t){let n=e.join(`,`),r=n.indexOf(`>`);if(r<0)return{from:[],to:[]};let i=e=>e.split(`,`).map(e=>iA(e,t)).filter(e=>e!==void 0);return{from:i(n.slice(0,r)),to:i(n.slice(r+1))}}function sA(e,t,n={}){let r=e,i=Yk(t,`RC`);if(i&&i.args.length>0){let e=aA(i.args,n.resolveColor);e.from.length>0&&(r=qk(r,e,n,`exact`))}let a=Yk(t,`PAL`);if(a){let e=oA(a.args,n.resolveColor);e.from.length>0&&e.from.length===e.to.length&&(r=qk(r,e,n,`exact`))}let o=Yk(t,`BLIT`);if(o&&o.args.length>0&&n.resolveTexture){let e=n.resolveTexture(o.args[0]);if(e){let t=Number(o.args[1]??0)||0,i=Number(o.args[2]??0)||0;r=Kk(r,n,n=>{n.drawImage(e.source.resource,t,i)})}}let s=Yk(t,`MASK`);if(s&&s.args.length>0&&n.resolveTexture){let e=n.resolveTexture(s.args[0]);if(e){let t=Number(s.args[1]??0)||0,i=Number(s.args[2]??0)||0;r=Kk(r,n,(r,a,o)=>{let s=r.getImageData(0,0,a,o),c=cA(e.width,e.height,n);if(!c)return;let l=c.getContext(`2d`);if(!l)return;l.drawImage(e.source.resource,0,0);let u=l.getImageData(0,0,e.width,e.height),d=lA(s.data,a,o,u.data,e.width,e.height,t,i);r.putImageData({data:d,width:a,height:o},0,0)})}}let c=Yk(t,`BLEND`);if(c){let e=iA(c.args[0]??``,n.resolveColor),t=eA(c.args[1]);e!==void 0&&t!==void 0&&(r=Kk(r,n,(n,r,i)=>{let a=uA(n.getImageData(0,0,r,i).data,e,t);n.putImageData({data:a,width:r,height:i},0,0)}))}let l=Yk(t,`ROTATE`);if(l){let e=Number(l.args[0]);if(Number.isFinite(e)&&e%360!=0){let t=r.width,i=r.height;if(t>0&&i>0&&r.source){let a=cA(t,i,n),o=a?.getContext(`2d`);if(a&&o){o.drawImage(r.source.resource,0,0);let a=dA(o.getImageData(0,0,t,i).data,t,i,e),s=cA(a.width,a.height,n),c=s?.getContext(`2d`);s&&c&&(c.putImageData({data:a.data,width:a.width,height:a.height},0,0),r=U.from(s))}}}}return r}function cA(e,t,n){let r=n.createCanvas?.(e,t)??(typeof document>`u`?null:document.createElement(`canvas`));return r?(r.width=e,r.height=t,r):null}function lA(e,t,n,r,i,a,o,s){let c=new Uint8ClampedArray(e.length);for(let l=0;l<n;l+=1)for(let n=0;n<t;n+=1){let u=(l*t+n)*4,d=n-o,f=l-s,p=d>=0&&d<i&&f>=0&&f<a?r[(f*i+d)*4+3]:0;c[u]=e[u],c[u+1]=e[u+1],c[u+2]=e[u+2],c[u+3]=Math.round(e[u+3]*p/255)}return c}function uA(e,t,n){let r=Math.min(1,Math.max(0,n)),i=t>>16&255,a=t>>8&255,o=t&255,s=new Uint8ClampedArray(e.length);for(let t=0;t<e.length;t+=4){let n=e[t+3];if(s[t+3]=n,n===0){s[t]=e[t],s[t+1]=e[t+1],s[t+2]=e[t+2];continue}s[t]=e[t]*(1-r)+i*r,s[t+1]=e[t+1]*(1-r)+a*r,s[t+2]=e[t+2]*(1-r)+o*r}return s}function dA(e,t,n,r){let i=r*Math.PI/180,a=Math.cos(i),o=Math.sin(i),s=t/2,c=n/2,l=0,u=0;for(let[e,t]of[[-s,-c],[s,-c],[s,c],[-s,c]])l=Math.max(l,Math.abs(e*a-t*o)),u=Math.max(u,Math.abs(e*o+t*a));let d=Math.max(1,Math.round(l*2)),f=Math.max(1,Math.round(u*2)),p=new Uint8ClampedArray(d*f*4),m=t/2-.5,h=n/2-.5,g=d/2-.5,_=f/2-.5;for(let r=0;r<f;r+=1)for(let i=0;i<d;i+=1){let s=i-g,c=r-_,l=Math.round(s*a+c*o+m),u=Math.round(-s*o+c*a+h);if(l<0||l>=t||u<0||u>=n)continue;let f=(r*d+i)*4,v=(u*t+l)*4;p[f]=e[v],p[f+1]=e[v+1],p[f+2]=e[v+2],p[f+3]=e[v+3]}return{data:p,width:d,height:f}}var fA=class{constructor(e,{fps:t=10,loop:n=!0,startTime:r=0}={}){if(e.length===0)throw Error(`an animation needs at least one frame`);if(!(t>0))throw Error(`an animation needs a positive fps, got ${t}`);this.frameDuration=1/t,this.frames=e.map(e=>pA(e)?e:{texture:e}),this.times=this.frames.map(e=>e.duration??this.frameDuration),this.loop=n,this.startTime=r;let i=0,a=0;for(let e of this.frames)e.duration===void 0?i++:a+=e.duration;this.duration=i*this.frameDuration+a}frameAt(e){return this.frames[this.frameIndexAt(e)]}frameIndexAt(e){let t=e-this.startTime;if(t<=0)return 0;let n=this.duration;if(n<=0)return this.frames.length-1;let r=this.loop?t%n:Math.min(t,n);for(let e=0;e<this.times.length;e++){if(r<this.times[e])return e;r-=this.times[e]}return this.frames.length-1}};function pA(e){return e.texture!==void 0}var mA=class extends zk{constructor(...e){super(...e),this.animations=new Map,this.current=null,this.currentName=null,this.elapsed=0,this.finished=!1,this.offset={x:0,y:0},this.onFinish=null,this.paused=!1}add(e,t,n){return this.animations.set(e,new fA(t,n)),this}has(e){return this.animations.has(e)}get playing(){return this.currentName}get isFinished(){return this.finished}get frameOffset(){return this.offset}get elapsedTime(){return this.elapsed}play(e,t=!1){if(!t&&this.currentName===e&&!this.finished)return this;let n=this.animations.get(e);if(!n)throw Error(`no animation named "${e}" on this sprite`);return this.current=n,this.currentName=e,this.elapsed=0,this.finished=!1,this.show(n.frameAt(0)),this}stop(){this.current=null,this.currentName=null}update(e){let t=this.current;!t||this.paused||this.finished||(this.elapsed+=e,this.show(t.frameAt(this.elapsed)),!t.loop&&this.elapsed>=t.startTime+t.duration&&(this.finished=!0,this.onFinish?.(this.currentName)))}show(e){this.texture=e.texture,this.offset.x=e.offsetX??0,this.offset.y=e.offsetY??0}},hA=``;function gA(e){hA=e.endsWith(`/`)||e===``?e:e+`/`}function _A(){return typeof window>`u`?void 0:window.__MWG_ASSETS__}function vA(){return _A()!==void 0}function yA(){return Object.keys(_A()??{})}function bA(e){let t=_A();return!t||e in t}function xA(e){let t=_A();if(!t)return hA+e;let n=t[e];if(n===void 0)throw Error(`asset "${e}" is not in this build - check it is under the folder passed to compile-resources`);return n}async function SA(e,t={}){let{onProgress:n,resolution:r,optional:i,onMissing:a}=typeof t==`function`?{onProgress:t,resolution:void 0,optional:void 0,onMissing:void 0}:t,o=new Set(i??[]),s=e.filter(e=>!ND.cache.has(e)),c=s.filter(e=>!o.has(e)),l=s.filter(e=>o.has(e)),u=e=>{let t={alias:e,src:xA(e)};r!==void 0&&(t.data={resolution:r}),ND.add(t)};if(l.length===0&&c.length===0){n?.(1);return}for(let e of c)u(e);let d=c.length>0?ND.load(c,n):Promise.resolve(),f=l.map(async e=>{u(e);try{await ND.load(e)}catch(t){a?.(e,t)}});await Promise.all([d,...f]),l.length>0&&c.length===0&&n?.(1)}function CA(e,t){if(!ND.cache.has(e)){if(t!==void 0)return t;throw Error(`texture "${e}" has not been loaded - pass it to load() first`)}return ND.get(e)}function wA(e,t){if(!ND.cache.has(e)){if(t!==void 0)return t;throw Error(`asset "${e}" has not been loaded - pass it to load() first`)}return ND.get(e)}function TA(e){return ND.cache.has(e)}async function EA(e){let t=e.filter(e=>ND.cache.has(e));t.length!==0&&await ND.unload(t)}var DA=new Map;async function OA(e,t,n={}){let r=n.fetch??globalThis.fetch;if(!r)throw Error(`fetch is unavailable; provide LoadBinaryOptions.fetch`);let i=e.filter(e=>!DA.has(e));if(i.length===0){t?.(1);return}let a=0;await Promise.all(i.map(async e=>{let n=await r(xA(e));if(!n.ok)throw Error(`failed to load binary asset "${e}": ${n.status}`);DA.set(e,await n.arrayBuffer()),a++,t?.(a/i.length)}))}function kA(e){let t=DA.get(e);if(!t)throw Error(`binary asset "${e}" has not been loaded - pass it to loadBinary() first`);return t}function AA(e){return DA.has(e)}function jA(e){for(let t of e)DA.delete(t)}var MA=class{constructor(e={}){if(this.entries=new Map,this.clock=0,this.budgetBytes=e.budgetBytes??1/0,!(this.budgetBytes>=0))throw Error(`asset stream budget must not be negative`);this.loadAssets=e.load??SA,this.releaseAssets=e.release??EA}async preload(e,t){if(!e.id)throw Error(`asset bundle needs an id`);if(e.estimatedBytes!==void 0&&e.estimatedBytes<0)throw Error(`asset bundle size must not be negative`);let n=this.entries.get(e.id);if(n?.ready){n.lastUsed=++this.clock,t?.(1);return}let r=e.paths.filter(e=>!this.isRetained(e));r.length>0?await this.loadAssets([...r],t):t?.(1),this.entries.set(e.id,{...e,lastUsed:++this.clock,ready:!0}),await this.enforceBudget(e.id)}async preloadLikely(e,t){let n=[...e].sort((e,t)=>(t.priority??0)-(e.priority??0));for(let[e,r]of n.entries())await this.preload(r,t&&(r=>t((e+r)/n.length)));t?.(1)}use(e){let t=this.entries.get(e);return t?.ready?(t.lastUsed=++this.clock,!0):!1}isReady(e){return this.entries.get(e)?.ready??!1}async unload(e){let t=this.entries.get(e);if(!t)return;this.entries.delete(e);let n=t.paths.filter(e=>!this.isRetained(e));n.length>0&&await this.releaseAssets(n)}get estimatedBytes(){return[...this.entries.values()].reduce((e,t)=>e+(t.estimatedBytes??0),0)}async enforceBudget(e){for(;this.estimatedBytes>this.budgetBytes;){let t=[...this.entries.values()].filter(t=>t.id!==e).sort((e,t)=>e.lastUsed-t.lastUsed)[0];if(!t)return;await this.unload(t.id)}}isRetained(e){return[...this.entries.values()].some(t=>t.ready&&t.paths.includes(e))}};async function NA(e,t,n=fetch){let r=await n(e);if(!r.ok)throw Error(`fetchWithByteProgress: ${e} responded ${r.status}`);let i=r.headers.get(`content-length`),a=i!==null&&i!==``?Number(i):null;if(!r.body){let e=await r.blob();return t?.({loaded:e.size,total:a??e.size}),e}let o=r.body.getReader(),s=[],c=0;for(;;){let{done:e,value:n}=await o.read();if(e)break;s.push(n),c+=n.byteLength,t?.({loaded:c,total:a})}return new Blob(s)}var PA=l({AssetStream:()=>MA,fetchWithByteProgress:()=>NA,get:()=>wA,getBinary:()=>kA,has:()=>bA,isBinaryLoaded:()=>AA,isCompiled:()=>vA,isLoaded:()=>TA,load:()=>SA,loadBinary:()=>OA,paths:()=>yA,release:()=>EA,releaseBinary:()=>jA,resolve:()=>xA,setBase:()=>gA,texture:()=>CA});function FA(e){return{x:e.x,y:e.y,width:e.width,height:e.height}}var IA=class e{constructor(e,t,n){this.frames=new Map,this.names=new Map,this.texture=e,this.frameWidth=t,this.frameHeight=n,this.columns=Math.floor(e.width/t),this.rows=Math.floor(e.height/n)}static grid(t,n,r=n){return new e(CA(t),n,r)}static fromTexture(t,n,r=n){return new e(t,n,r)}get count(){return this.columns*this.rows}name(e,t){return this.names.set(e,t),this}nameAll(e){for(let[t,n]of Object.entries(e))this.names.set(t,n);return this}indexOf(e){let t=this.names.get(e);if(t===void 0)throw Error(`this sheet has no frame named "${e}"`);return t}get(e){let t=typeof e==`string`?this.indexOf(e):e,n=this.frames.get(t);if(n)return n;if(t<0||t>=this.count)throw Error(`frame ${t} is outside this sheet, which holds ${this.count}`);let r=new U({source:this.texture.source,frame:new V(t%this.columns*this.frameWidth,Math.floor(t/this.columns)*this.frameHeight,this.frameWidth,this.frameHeight)});return this.frames.set(t,r),r}region(e){let t=this.get(e);return{texture:t,frame:FA(t.frame)}}range(e,t){let n=[];for(let r=e;r<=t;r++)n.push(this.get(r));return n}pick(...e){return e.map(e=>this.get(e))}},LA=class{constructor(e={}){if(this.world=new G,this.x=0,this.y=0,this.viewWidth=0,this.viewHeight=0,this.screenX=0,this.screenY=0,this.followTarget=null,this.followIntensity=0,this.shakeMagnitude=0,this.shakeRemaining=0,this.shakeDuration=1,this.shakeX=0,this.shakeY=0,this.bounds=null,this.step=0,this._angle=0,this.targetAngle=null,this.angleIntensity=0,e.grid!==void 0&&e.grid!==`square`&&e.grid!==`hex`)throw Error(`camera grid must be "square" or "hex", not "${e.grid}"`);this.stepsPerTurn=e.grid===`hex`?6:4,this.deadzone=e.deadzone??0,this.pixelPerfectTileSize=e.pixelPerfectTileSize,this._zoom=1,this.zoom=e.zoom??1}get rotationSteps(){return this.step}get rotation(){return this._angle}get uprightRotation(){return-this.rotation}setRotationStep(e){if(!Number.isInteger(e))throw Error(`camera rotation step must be an integer`);this.step=(e%this.stepsPerTurn+this.stepsPerTurn)%this.stepsPerTurn,this._angle=this.step/this.stepsPerTurn*Math.PI*2,this.targetAngle=null,this.apply()}rotate(e=1){this.setRotationStep(this.step+e)}rotateTo(e){this._angle=e,this.targetAngle=null,this.angleIntensity=0,this.apply()}animateRotationTo(e,t=4){this.targetAngle=e,this.angleIntensity=t}get spin(){let e=this.rotation;return{cos:Math.cos(e),sin:Math.sin(e)}}get zoom(){return this._zoom}set zoom(e){let t=Math.max(.01,e);this._zoom=this.pixelPerfectTileSize?BA(t,this.pixelPerfectTileSize):t}setViewport(e,t,n=0,r=0){this.viewWidth=e,this.viewHeight=t,this.screenX=n,this.screenY=r}get view(){let e=this.viewWidth/this._zoom,t=this.viewHeight/this._zoom,{x:n,y:r}=this.clampedCentre(this.x,this.y);if(this._angle===0)return{x:n-e/2,y:r-t/2,width:e,height:t};let i=[this.toWorld(this.screenX,this.screenY),this.toWorld(this.screenX+this.viewWidth,this.screenY),this.toWorld(this.screenX+this.viewWidth,this.screenY+this.viewHeight),this.toWorld(this.screenX,this.screenY+this.viewHeight)],a=i.map(e=>e.x),o=i.map(e=>e.y),s=Math.min(...a),c=Math.min(...o);return{x:s,y:c,width:Math.max(...a)-s,height:Math.max(...o)-c}}setBounds(e){this.bounds=e}snapTo(e,t){this.x=e,this.y=t,this.followTarget=null,this.followIntensity=0,this.apply()}panTo(e,t,n=4){this.followTarget={x:e,y:t},this.followIntensity=n}follow(e,t=8){this.followTarget=e,this.followIntensity=t}stopFollowing(){this.followTarget=null,this.followIntensity=0}shake(e,t=.4){xn()||(this.shakeMagnitude=e,this.shakeRemaining=this.shakeDuration=t)}update(e){if(this.followTarget&&this.followIntensity>0){let t=this.viewWidth/this._zoom*this.deadzone/2,n=this.viewHeight/this._zoom*this.deadzone/2,r=this.followTarget.x-this.x,i=this.followTarget.y-this.y;r=r>t?r-t:r<-t?r+t:0,i=i>n?i-n:i<-n?i+n:0;let a=xn()?1:1-Math.exp(-this.followIntensity*e);this.x+=r*a,this.y+=i*a}if(this.targetAngle!==null&&this.angleIntensity>0){let t=zA(this._angle,this.targetAngle),n=xn()?1:1-Math.exp(-this.angleIntensity*e);this._angle+=t*n}if(this.shakeRemaining>0){this.shakeRemaining-=e;let t=Math.max(0,this.shakeRemaining/this.shakeDuration);this.shakeX=O(-this.shakeMagnitude,this.shakeMagnitude)*t,this.shakeY=O(-this.shakeMagnitude,this.shakeMagnitude)*t}else this.shakeX=this.shakeY=0;this.apply()}toScreen(e,t){let{x:n,y:r}=this.clampedCentre(this.x+this.shakeX,this.y+this.shakeY),{cos:i,sin:a}=this.spin,o=e-n,s=t-r;return{x:(o*i-s*a)*this._zoom+this.screenX+this.viewWidth/2,y:(o*a+s*i)*this._zoom+this.screenY+this.viewHeight/2}}toWorld(e,t){let{x:n,y:r}=this.clampedCentre(this.x+this.shakeX,this.y+this.shakeY),{cos:i,sin:a}=this.spin,o=(e-this.screenX-this.viewWidth/2)/this._zoom,s=(t-this.screenY-this.viewHeight/2)/this._zoom;return{x:n+o*i+s*a,y:r-o*a+s*i}}clampedCentre(e,t){if(!this.bounds)return{x:e,y:t};let n=this.viewWidth/this._zoom/2,r=this.viewHeight/this._zoom/2,{minX:i,minY:a,maxX:o,maxY:s}=this.bounds;return{x:o-i<n*2?(i+o)/2:RA(e,i+n,o-n),y:s-a<r*2?(a+s)/2:RA(t,a+r,s-r)}}apply(){let{x:e,y:t}=this.clampedCentre(this.x+this.shakeX,this.y+this.shakeY);if(this.world.scale.set(this._zoom),this._angle===0){this.world.rotation=0,this.world.pivot.set(0,0),this.world.x=Math.round(this.screenX+this.viewWidth/2-e*this._zoom),this.world.y=Math.round(this.screenY+this.viewHeight/2-t*this._zoom);return}this.world.rotation=this.rotation,this.world.pivot.set(e,t),this.world.x=Math.round(this.screenX+this.viewWidth/2),this.world.y=Math.round(this.screenY+this.viewHeight/2)}};function RA(e,t,n){return e<t?t:e>n?n:e}function zA(e,t){let n=Math.PI*2,r=(t-e)%n;return r>Math.PI&&(r-=n),r<-Math.PI&&(r+=n),r}function BA(e,t){return Math.max(1,Math.round(e*t))/t}function VA(e={}){let t=new LA(e),n=yk.current;return t.setViewport(n.width,n.height),t}var HA=class{constructor(e){this.container=new G,this.clip=new Sw,this.camera=new LA(e),this.container.addChild(this.camera.world),this.container.addChild(this.clip),this.container.mask=this.clip,this.resize(e.x,e.y,e.width,e.height)}resize(e,t,n,r){this.camera.setViewport(n,r,e,t),this.clip.clear().rect(e,t,n,r).fill(16777215)}update(e){this.camera.update(e)}};function UA(e,t){if(e>=t){let n=Math.floor(e/2);return[{x:0,y:0,width:n,height:t},{x:n,y:0,width:e-n,height:t}]}let n=Math.floor(t/2);return[{x:0,y:0,width:e,height:n},{x:0,y:n,width:e,height:t-n}]}var WA={protanopia:[.567,.433,0,0,0,.558,.442,0,0,0,0,.242,.758,0,0,0,0,0,1,0],deuteranopia:[.625,.375,0,0,0,.7,.3,0,0,0,0,.3,.7,0,0,0,0,0,1,0],tritanopia:[.95,.05,0,0,0,0,.433,.567,0,0,0,.475,.525,0,0,0,0,0,1,0]};function GA(e){let t=new LD;return t.matrix=WA[e],t}function KA(e,t){let n=[];for(let r of e)t.has(r)||n.push(r);return n}function qA(e,t,n,r=`square`){return r===`hex`?pn(e,t,n,n):{x:(e+.5)*n,y:(t+.5)*n}}var JA=class extends G{constructor(e){super(),this.drawn=new Set,this.marker=new Sw,this.widthInCells=e.widthInCells,this.cellSize=e.cellSize??2,this.shape=e.shape??`square`,this.renderTexture=Nh.create({width:this.shape===`hex`?Math.ceil((e.widthInCells-1)*this.cellSize*.75+this.cellSize):e.widthInCells*this.cellSize,height:this.shape===`hex`?e.heightInCells*this.cellSize+this.cellSize/2:e.heightInCells*this.cellSize}),this.sprite=new $s(this.renderTexture),this.addChild(this.sprite),this.addChild(this.marker)}get exploredCount(){return this.drawn.size}sync(e,t){let n=KA(e,this.drawn);if(n.length===0)return;let r=new Sw;for(let e of n){this.drawn.add(e);let n=e%this.widthInCells,i=Math.floor(e/this.widthInCells),a=qA(n,i,this.cellSize,this.shape);if(this.shape===`hex`){let e=this.cellSize/2,o=[];for(let t=0;t<6;t++){let n=Math.PI/3*t;o.push(a.x+Math.cos(n)*e,a.y+Math.sin(n)*e)}r.poly(o).fill({color:t(n,i)})}else r.rect(a.x-this.cellSize/2,a.y-this.cellSize/2,this.cellSize,this.cellSize).fill({color:t(n,i)})}yk.current.app.renderer.render({container:r,target:this.renderTexture,clear:!1}),r.destroy()}setMarker(e,t,n,r=16777215){this.setMarkers([{x:e,y:t,facing:n,color:r}])}setMarkers(e){this.marker.clear();for(let t of e){let e=t.color??16777215,n=qA(t.x,t.y,this.cellSize,this.shape);if(this.marker.circle(n.x,n.y,Math.max(1,this.cellSize)).fill({color:e}),t.facing!==void 0){let r=this.cellSize*2;this.marker.moveTo(n.x,n.y).lineTo(n.x+Math.cos(t.facing)*r,n.y+Math.sin(t.facing)*r).stroke({color:e,width:1})}}}reset(){this.drawn.clear(),yk.current.app.renderer.render({container:new G,target:this.renderTexture,clear:!0})}destroy(e){this.renderTexture.destroy(!0),super.destroy(e)}},YA=-1,XA=7237230,ZA=10132122;function QA(e,t){if(!Number.isInteger(e)||e<0||e>=4096)throw Error(`tileFrame needs a sheet index from 0 to 4095, got ${e}`);if(!Number.isInteger(t)||t<0||t>=1<<20)throw Error(`tileFrame needs a frame index from 0 to ${(1<<20)-1}, got ${t}`);return e<<20|t}function $A(e){return e>>>20}function ej(e){return e&(1<<20)-1}var tj=class extends G{constructor(e){if(super(),this.layers=[],this.layersByName=new Map,this.chunks=[],this.widthInTiles=e.width,this.heightInTiles=e.height,this.sheets=Array.isArray(e.sheet)?[...e.sheet]:[e.sheet],this.sheets.length===0)throw Error(`a TileMap needs at least one sheet`);if(this.tileWidth=e.tileWidth??this.sheets[0].frameWidth,this.tileHeight=e.tileHeight??this.sheets[0].frameHeight,this.shape=e.shape??`square`,this.heightStep=e.heightStep??this.tileHeight/2,!(this.heightStep>0))throw Error(`a TileMap's heightStep must be a positive number, got ${e.heightStep}`);this.chunkSize=e.chunkSize??16,this.chunkColumns=Math.ceil(this.widthInTiles/this.chunkSize),this.chunkRows=Math.ceil(this.heightInTiles/this.chunkSize);let t=this.widthInTiles*this.heightInTiles;this.cellTint=new Uint32Array(t).fill(16777215),this.cellAdd=new Uint32Array(t),this.cellHeight=new Int32Array(t),this.faces=Array(t).fill(null)}get layerCount(){return this.layers.length}get worldWidth(){switch(this.shape){case`square`:return this.widthInTiles*this.tileWidth;case`hex`:return this.widthInTiles<=0?0:(this.widthInTiles-1)*this.tileWidth*.75+this.tileWidth;case`isometric`:return(this.widthInTiles+this.heightInTiles)*(this.tileWidth/2);case`staggered`:return this.widthInTiles*this.tileWidth+this.tileWidth/2}}get worldHeight(){switch(this.shape){case`square`:return this.heightInTiles*this.tileHeight;case`hex`:return this.heightInTiles*this.tileHeight+this.tileHeight/2;case`isometric`:return(this.widthInTiles+this.heightInTiles)*(this.tileHeight/2);case`staggered`:return this.heightInTiles*(this.tileHeight/2)+this.tileHeight/2}}inside(e,t){return e>=0&&t>=0&&e<this.widthInTiles&&t<this.heightInTiles}index(e,t){return t*this.widthInTiles+e}addLayer(e,t){if(this.layersByName.has(e))throw Error(`this map already has a layer named "${e}"`);let n=this.widthInTiles*this.heightInTiles;if(t&&t.length!==n)throw Error(`layer "${e}" has ${t.length} cells, but the map has ${n}`);let r=new G,i=[];for(let e=0;e<this.chunkColumns*this.chunkRows;e++){let e=new G;i.push(e),r.addChild(e)}let a={name:e,data:t?Int32Array.from(t):new Int32Array(n).fill(-1),sprites:Array(n).fill(null),container:r};this.layers.push(a),this.layersByName.set(e,a),this.chunks.push(i),this.addChild(r);let o=this.layers.length===1;for(let e=0;e<this.heightInTiles;e++)for(let t=0;t<this.widthInTiles;t++){let n=a.data[this.index(t,e)];n!==-1&&this.buildSprite(a,t,e,n),o&&this.syncFaces(t,e)}return this}layerAt(e){let t=typeof e==`number`?this.layers[e]:this.layersByName.get(e);if(!t)throw Error(`no such layer: ${e}`);return t}chunkIndex(e,t){return Math.floor(t/this.chunkSize)*this.chunkColumns+Math.floor(e/this.chunkSize)}projectedCenter(e,t){switch(this.shape){case`square`:return{x:(e+.5)*this.tileWidth,y:(t+.5)*this.tileHeight};case`hex`:return pn(e,t,this.tileWidth,this.tileHeight);case`isometric`:return{x:(e-t+(this.heightInTiles-1))*(this.tileWidth/2)+this.tileWidth/2,y:(e+t)*(this.tileHeight/2)+this.tileHeight/2};case`staggered`:return{x:e*this.tileWidth+(t&1)*(this.tileWidth/2)+this.tileWidth/2,y:t*(this.tileHeight/2)+this.tileHeight/2}}}projectedTile(e,t){switch(this.shape){case`square`:return{x:Math.floor(e/this.tileWidth),y:Math.floor(t/this.tileHeight)};case`hex`:return mn(e,t,this.tileWidth,this.tileHeight);case`isometric`:{let n=(e-this.tileWidth/2)/(this.tileWidth/2)-(this.heightInTiles-1),r=(t-this.tileHeight/2)/(this.tileHeight/2);return{x:Math.round((n+r)/2),y:Math.round((r-n)/2)}}case`staggered`:{let n=Math.round((t-this.tileHeight/2)/(this.tileHeight/2));return{x:Math.round((e-this.tileWidth/2-(n&1)*(this.tileWidth/2))/this.tileWidth),y:n}}}}cellOrigin(e,t){let n=this.projectedCenter(e,t);return{x:n.x-this.tileWidth/2,y:n.y-this.tileHeight/2}}textureFor(e){let t=$A(e);if(t>=this.sheets.length)throw Error(`frame ${e} names sheet ${t}, but this map has ${this.sheets.length}`);return this.sheets[t].get(ej(e))}buildSprite(e,t,n,r){let i=new zk(this.textureFor(r)),a=this.cellOrigin(t,n);i.x=a.x,i.y=a.y-this.cellHeight[this.index(t,n)]*this.heightStep;let o=this.index(t,n);return i.tint=this.cellTint[o],i.colorAdd=this.cellAdd[o],e.sprites[o]=i,this.chunks[this.layers.indexOf(e)][this.chunkIndex(t,n)].addChild(i),i}getTile(e,t,n){return this.inside(t,n)?this.layerAt(e).data[this.index(t,n)]:-1}setTile(e,t,n,r){if(!this.inside(t,n))return;let i=this.layerAt(e),a=this.index(t,n);if(i.data[a]===r)return;i.data[a]=r;let o=i.sprites[a];r===-1?(o?.destroy(),i.sprites[a]=null):o?o.texture=this.textureFor(r):this.buildSprite(i,t,n,r),this.layers[0]===i&&this.syncFaces(t,n)}setLayerData(e,t){this.layerAt(e);for(let n=0;n<this.heightInTiles;n++)for(let r=0;r<this.widthInTiles;r++)this.setTile(e,r,n,t[this.index(r,n)]??-1)}setCellColor(e,t,n,r=0){if(!this.inside(e,t))return;let i=this.index(e,t);if(this.cellTint[i]===n&&this.cellAdd[i]===r)return;this.cellTint[i]=n,this.cellAdd[i]=r;for(let e of this.layers){let t=e.sprites[i];t&&(t.tint=n,t.colorAdd=r)}let a=this.faces[i];a&&(a.tint=n)}getCellTint(e,t){return this.inside(e,t)?this.cellTint[this.index(e,t)]:0}clearColors(){for(let e=0;e<this.heightInTiles;e++)for(let t=0;t<this.widthInTiles;t++)this.setCellColor(t,e,16777215,0)}setCellHeight(e,t,n){if(!this.inside(e,t))return;if(!Number.isInteger(n))throw Error(`a cell's height must be a whole number, got ${n}`);let r=this.index(e,t);if(this.cellHeight[r]===n)return;this.cellHeight[r]=n;let i=n*this.heightStep;for(let n of this.layers){let a=n.sprites[r];a&&(a.y=this.cellOrigin(e,t).y-i)}this.syncFaces(e,t)}getCellHeight(e,t){return this.inside(e,t)?this.cellHeight[this.index(e,t)]:0}get faceCount(){return this.faces.filter(e=>e!==null).length}syncFaces(e,t){if(this.layers.length===0)return;let n=this.index(e,t),r=(this.shape===`isometric`||this.shape===`staggered`)&&this.cellHeight[n]>0&&this.layers[0].data[n]!==-1,i=this.faces[n];if(!r){i&&(i.destroy(),this.faces[n]=null);return}let a=i??new Sw;if(this.drawFaces(a,e,t),a.tint=this.cellTint[n],!i){this.faces[n]=a;let r=this.chunks[0][this.chunkIndex(e,t)],i=this.layers[0].sprites[n];i?r.addChildAt(a,r.getChildIndex(i)):r.addChild(a)}}drawFaces(e,t,n){let r=this.cellOrigin(t,n),i=r.x,a=r.y,o=this.tileWidth/2,s=this.tileHeight/2,c=this.heightStep,l=this.cellHeight[this.index(t,n)];e.clear();for(let t=1;t<=l;t++){let n=t*c,r=(t-1)*c;e.poly([i,a+s-n,i+o,a+s*2-n,i+o,a+s*2-r,i,a+s-r]).fill(XA),e.poly([i+o,a+s*2-n,i+o*2,a+s-n,i+o*2,a+s-r,i+o,a+s*2-r]).fill(ZA)}}toTile(e,t){return this.projectedTile(e,t)}tileCenter(e,t){let n=this.projectedCenter(e,t);return n.y-=this.getCellHeight(e,t)*this.heightStep,n}cull(e){let t=e.view,n=this.projectedTile(t.x,t.y),r=this.projectedTile(t.x+t.width,t.y),i=this.projectedTile(t.x,t.y+t.height),a=this.projectedTile(t.x+t.width,t.y+t.height),o=Math.min(n.x,r.x,i.x,a.x),s=Math.max(n.x,r.x,i.x,a.x),c=Math.min(n.y,r.y,i.y,a.y),l=Math.max(n.y,r.y,i.y,a.y),u=Math.floor(o/this.chunkSize)-1,d=Math.floor(s/this.chunkSize)+1,f=Math.floor(c/this.chunkSize)-1,p=Math.floor(l/this.chunkSize)+1;for(let e=0;e<this.chunkRows;e++){let t=e>=f&&e<=p;for(let n=0;n<this.chunkColumns;n++){let r=t&&n>=u&&n<=d,i=e*this.chunkColumns+n;for(let e of this.chunks)e[i].renderable=r}}}get visibleChunks(){return this.chunks.length===0?0:this.chunks[0].filter(e=>e.renderable).length}},nj=class extends G{constructor(...e){super(...e),this.layers=new Map}addLayer(e,t,n=0){this.removeLayer(e);let r=new zk(t);return this.layers.set(e,{sprite:r,order:n}),this.addChild(r),this.resort(),r}removeLayer(e){let t=this.layers.get(e);t&&(this.layers.delete(e),t.sprite.destroy())}layer(e){return this.layers.get(e)?.sprite}hasLayer(e){return this.layers.has(e)}setTexture(e,t){let n=this.layers.get(e);n&&(n.sprite.texture=t)}resort(){[...this.layers.values()].sort((e,t)=>e.order-t.order).forEach((e,t)=>this.setChildIndex(e.sprite,t))}},rj=class{constructor(e,t,n,r={}){this.elapsed=0,this.arrived=!1,this.sprite=e,this.fromX=t.x,this.fromY=t.y,this.toX=n.x,this.toY=n.y;let i=Math.hypot(n.x-t.x,n.y-t.y);this.duration=r.duration??i/(r.speed??400),this.duration<=0&&(this.duration=1e-6),e.x=t.x,e.y=t.y}get done(){return this.arrived}get progress(){return Math.min(1,this.elapsed/this.duration)}update(e){if(this.arrived)return!1;this.elapsed+=e;let t=this.progress;return this.sprite.x=this.fromX+(this.toX-this.fromX)*t,this.sprite.y=this.fromY+(this.toY-this.fromY)*t,t>=1&&(this.arrived=!0,!0)}},ij=class{constructor(e,t,n={}){this.elapsed=0,this.sinceFlicker=0,this.expired=!1,this.current=[],this.from={...e},this.to={...t},this.segments=Math.max(0,Math.floor(n.segments??6)),this.jitter=n.jitter??12,this.flickerInterval=n.flickerInterval,this.random=n.random??Math.random,this.duration=n.duration,this.reroll()}get points(){return this.current}get done(){return this.expired}retarget(e,t){e&&(this.from={...e}),t&&(this.to={...t}),this.flickerInterval===void 0&&this.reroll()}update(e){return!this.expired&&(this.elapsed+=e,this.flickerInterval!==void 0&&(this.sinceFlicker+=e,this.sinceFlicker>=this.flickerInterval&&(this.sinceFlicker=0,this.reroll())),this.duration!==void 0&&this.elapsed>=this.duration&&(this.expired=!0,!0))}reroll(){let e=this.to.x-this.from.x,t=this.to.y-this.from.y,n=Math.hypot(e,t),r=n>0?-t/n:0,i=n>0?e/n:0,a=[{...this.from}],o=this.segments+1;for(let n=1;n<o;n+=1){let s=n/o,c=Math.sin(Math.PI*s),l=(this.random()*2-1)*this.jitter*c;a.push({x:this.from.x+e*s+r*l,y:this.from.y+t*s+i*l})}a.push({...this.to}),this.current=a}},aj=class{constructor(e,t={}){this.elapsed=0,this.expired=!1,this.child=e,this.offsetX=t.offsetX??0,this.offsetY=t.offsetY??0,this.duration=t.duration}get done(){return this.expired}follow(e,t){return this.child.x=e+this.offsetX,this.child.y=t+this.offsetY,this}update(e){return this.expired||this.duration===void 0?!1:(this.elapsed+=e,this.elapsed>=this.duration&&(this.expired=!0,!0))}},oj=`halo`,sj=class extends mA{constructor(e){super(),this.offsetX=e.offsetX??0,this.offsetY=e.offsetY??0,this.blendMode=e.blendMode??`add`,this.add(oj,e.frames,e.animation),this.play(oj)}follow(e,t){return this.position.set(e+this.offsetX,t+this.offsetY),this}};function cj(e){return typeof e==`number`?e:O(e[0],e[1])}var lj=class extends G{constructor(e={}){super(),this.pool=[],this.sprites=[],this.emitting=!1,this.poolCursor=0,this.debt=0;let t=Math.max(1,Math.floor(e.max??200));this.rate=e.rate??0,this.life=e.life??[.4,.9],this.speed=e.speed??[20,60],this.angleRange=e.angle??[0,Math.PI*2],this.gravityX=e.gravity?.x??0,this.gravityY=e.gravity?.y??0,this.scaleRange=e.scale??[1,1],this.alphaRange=e.alpha??[1,0],this.spin=e.spin??0,this.frames=e.frames,this.spawnArea=e.spawn??null;for(let n=0;n<t;n++){this.pool.push({x:0,y:0,vx:0,vy:0,age:0,life:0,rotation:0,spin:0,scale:1,alpha:1,frame:0,active:!1});let t=this.frames?.[0]??e.texture;if(t){let n=new $s(t);n.anchor.set(.5),n.visible=!1,e.tint!==void 0&&(n.tint=e.tint),this.sprites.push(n),this.addChild(n)}}}start(){this.emitting=!0}stop(){this.emitting=!1,this.debt=0}get isEmitting(){return this.emitting}get activeCount(){let e=0;for(let t of this.pool)t.active&&e++;return e}get particles(){return this.pool}burst(e){let t=0;for(let n=0;n<e&&this.spawn();n++)t++;return t}spawn(){let e=null;for(let t=0;t<this.pool.length;t++){let t=this.pool[this.poolCursor];if(this.poolCursor=(this.poolCursor+1)%this.pool.length,!t.active){e=t;break}}if(!e)return!1;let t=cj(this.angleRange),n=cj(this.speed),r=+!xn(),i=this.spawnOffset();return e.x=this.x+i.x,e.y=this.y+i.y,e.vx=Math.cos(t)*n*r,e.vy=Math.sin(t)*n*r,e.age=0,e.life=Math.max(1e-6,cj(this.life)),e.rotation=0,e.spin=cj(this.spin)*r,e.scale=this.scaleRange[0],e.alpha=this.alphaRange[0],e.frame=0,e.active=!0,!0}spawnOffset(){let e=this.spawnArea;if(!e)return{x:0,y:0};let t=e.height??e.width;if(e.shape===`rect`)return{x:(O()-.5)*e.width,y:(O()-.5)*t};let n=Math.sqrt(O()),r=O()*Math.PI*2;return{x:Math.cos(r)*n*(e.width/2),y:Math.sin(r)*n*(t/2)}}update(e){if(this.emitting&&this.rate>0){for(this.debt+=this.rate*e;this.debt>=1;)if(--this.debt,!this.spawn()){this.debt=0;break}}let t=xn();for(let n of this.pool){if(!n.active)continue;if(n.age+=e,n.age>=n.life){n.active=!1;continue}t?(n.vx=0,n.vy=0,n.spin=0):(n.vx+=this.gravityX*e,n.vy+=this.gravityY*e),n.x+=n.vx*e,n.y+=n.vy*e,n.rotation+=n.spin*e;let r=n.age/n.life;n.scale=this.scaleRange[0]+(this.scaleRange[1]-this.scaleRange[0])*r,n.alpha=this.alphaRange[0]+(this.alphaRange[1]-this.alphaRange[0])*r,this.frames&&(n.frame=Math.min(this.frames.length-1,Math.floor(r*this.frames.length)))}this.draw()}draw(){if(this.sprites.length!==0)for(let e=0;e<this.pool.length;e++){let t=this.pool[e],n=this.sprites[e];n.visible=t.active,t.active&&(n.x=t.x-this.x,n.y=t.y-this.y,n.rotation=t.rotation,n.alpha=t.alpha,n.scale.set(t.scale),this.frames&&(n.texture=this.frames[t.frame]??n.texture))}}clear(){for(let e of this.pool)e.active=!1;this.debt=0,this.draw()}},uj=class extends G{constructor(e={}){super(),this.overlay=new Sw,this.phase=`idle`,this.elapsed=0,this.duration=0,this.fromAlpha=0,this.toAlpha=0,this.defaultColor=e.color??0,this.viewWidth=e.width??0,this.viewHeight=e.height??0,this.overlay.alpha=0,this.overlay.tint=this.defaultColor,this.addChild(this.overlay),this.redraw()}setViewport(e,t){this.viewWidth=e,this.viewHeight=t,this.redraw()}redraw(){this.overlay.clear(),this.viewWidth>0&&this.viewHeight>0&&this.overlay.rect(0,0,this.viewWidth,this.viewHeight).fill({color:16777215})}get isBusy(){return this.phase!==`idle`}get washAlpha(){return this.overlay.alpha}fadeOut(e,t){this.begin(`fadeOut`,e,this.overlay.alpha,1,t)}fadeIn(e,t){this.begin(`fadeIn`,e,this.overlay.alpha,0,t)}flash(e,t,n=1){this.begin(`flash`,e,0,n,t)}setTint(e,t){this.phase=`idle`,this.elapsed=0,this.overlay.tint=e,this.overlay.alpha=Math.max(0,Math.min(1,t))}clear(){this.phase=`idle`,this.elapsed=0,this.overlay.alpha=0,this.overlay.tint=this.defaultColor}begin(e,t,n,r,i){if(xn()&&(t=0),this.overlay.tint=i??this.defaultColor,this.fromAlpha=n,this.toAlpha=r,this.elapsed=0,this.duration=t,!(t>0)){this.overlay.alpha=e===`flash`?0:r,this.phase=`idle`;return}this.phase=e,this.overlay.alpha=e===`flash`?0:n}update(e){if(this.phase===`idle`)return!1;if(xn())return this.overlay.alpha=this.phase===`flash`?0:this.toAlpha,this.phase=`idle`,!0;this.elapsed+=e;let t=Math.min(1,this.elapsed/this.duration);if(this.phase===`flash`){let e=t<.5?Dn.easeOutQuad(t*2):1-Dn.easeInQuad((t-.5)*2);this.overlay.alpha=this.toAlpha*e}else{let e=Dn.easeInOutQuad(t);this.overlay.alpha=this.fromAlpha+(this.toAlpha-this.fromAlpha)*e}return t>=1&&(this.overlay.alpha=this.phase===`flash`?0:this.toAlpha,this.phase=`idle`,!0)}},dj=class{constructor(e,t){this.idleOrMove=`idle`,this.inAction=!1,this.sprite=e,this.animationName=t.animationName,this.variant=t.variant??``,this.sprite.onFinish=()=>this.onSpriteFinish(),this.apply(this.idleOrMove)}get state(){return this.inAction?`action`:this.idleOrMove}get variantName(){return this.variant}setMoving(e,t){t!==void 0&&(this.variant=t),this.idleOrMove=e?`move`:`idle`,this.inAction||this.apply(this.idleOrMove)}playAction(e,t=!1){this.inAction&&!t||(e!==void 0&&(this.variant=e),this.inAction=!0,this.apply(`action`))}onSpriteFinish(){this.inAction&&(this.inAction=!1,this.apply(this.idleOrMove))}apply(e){let t=this.animationName(e,this.variant);this.sprite.has(t)&&this.sprite.play(t,e===`action`)}},fj=class{constructor(e,t){this.active=new Set,this.elapsed=0,this.target=e,this.styles=t.styles,this.priority=Object.keys(t.styles)}set(e,t){t?this.active.add(e):this.active.delete(e)}has(e){return this.active.has(e)}update(e){this.elapsed+=e;let t=this.priority.find(e=>this.active.has(e));if(t===void 0){this.target.resetColor();return}let n=this.styles[t],r=n.strength??.5,i=n.pulseRate?r*(.5+.5*Math.sin(this.elapsed*n.pulseRate*Math.PI*2)):r;this.target.lerpTint(n.color,i)}},pj=gj(),mj=new Map(pj.map((e,t)=>[hj(e),t]));function hj(e){let t=e.ne&&e.n&&e.e,n=e.se&&e.s&&e.e,r=e.sw&&e.s&&e.w,i=e.nw&&e.n&&e.w;return+!!e.n|(e.e?2:0)|(e.s?4:0)|(e.w?8:0)|(t?16:0)|(n?32:0)|(r?64:0)|(i?128:0)}function gj(){let e=new Set,t=[];for(let n=0;n<256;n++){let r={n:!!(n&1),e:!!(n&2),s:!!(n&4),w:!!(n&8),ne:!!(n&16),se:!!(n&32),sw:!!(n&64),nw:!!(n&128)},i=hj(r);e.has(i)||(e.add(i),t.push({mask:i,shape:{n:r.n,e:r.e,s:r.s,w:r.w,ne:r.ne&&r.n&&r.e,se:r.se&&r.s&&r.e,sw:r.sw&&r.s&&r.w,nw:r.nw&&r.n&&r.w}}))}return t.sort((e,t)=>e.mask-t.mask),t.map(e=>e.shape)}function _j(e){return mj.get(hj(e))}function vj(e,t,n,r){if(r.length!==pj.length)throw Error(`autotileFrames needs exactly ${pj.length} frames, got ${r.length}`);let i=new Int32Array(e*t);for(let a=0;a<t;a++)for(let t=0;t<e;t++){let o=a*e+t;if(!n(t,a)){i[o]=-1;continue}i[o]=r[_j({n:n(t,a-1),e:n(t+1,a),s:n(t,a+1),w:n(t-1,a),ne:n(t+1,a-1),se:n(t+1,a+1),sw:n(t-1,a+1),nw:n(t-1,a-1)})]}return i}function yj(e,t,n,r){let i=n*4/r,a=e,o=t;for(let e=0;e<i;e+=1)[a,o]=[-o,a];return{dx:a||0,dy:o||0}}function bj(e,t,n,r){let i=n*6/r,a=e,o=t;for(let e=0;e<i;e+=1){let e=-a-o;[a,o]=[-o,-e]}return{dx:a||0,dy:o||0}}function xj(e,t){let n=t??new Set;return!(e.hasAll&&!e.hasAll.every(e=>n.has(e))||e.hasAny&&!e.hasAny.some(e=>n.has(e))||e.hasNone&&e.hasNone.some(e=>n.has(e)))}function Sj(e,t,n,r,i=yj,a=0){let o=e.rotations??0;return e.conditions.every(e=>{let s=o>0?i(e.dx,e.dy,a,o):e;return xj(e,r(t+s.dx,n+s.dy))})}function Cj(e,t,n,r,i={}){let a=i.rotate??yj,o=i.random??new w,s=[];for(let i=0;i<t;i+=1)for(let t=0;t<e;t+=1){let e=-1,c=[];for(let o of n){let n=o.rotations??0,s=n>0?n:1;for(let n=0;n<s;n+=1){if(!Sj(o,t,i,r,a,n))continue;let s=o.conditions.length;s>e?(e=s,c=[{rule:o,rotationIndex:n}]):s===e&&c.push({rule:o,rotationIndex:n})}}if(c.length===0)continue;let l=c.length===1?c[0]:c[wj(c.map(e=>e.rule.probability??1),o)],u=l.rule.rotations??0;for(let e of l.rule.images){let n=u>0?a(e.dx??0,e.dy??0,l.rotationIndex,u):{dx:e.dx??0,dy:e.dy??0};s.push({x:t,y:i,ruleId:l.rule.id,image:e.image,dx:n.dx,dy:n.dy,layer:e.layer??0})}}return s}function wj(e,t){let n=e.reduce((e,t)=>e+Math.max(0,t),0);if(n<=0)return 0;let r=t.float()*n;for(let t=0;t<e.length;t+=1)if(r-=Math.max(0,e[t]),r<0)return t;return e.length-1}var Tj=[{workload:`sprites`,preferred:`PixiJS WebGL/WebGPU batcher`,fallback:`PixiJS WebGL`,reason:`high-volume textured 2D batches`},{workload:`ui`,preferred:`PixiJS display tree`,fallback:`PixiJS display tree`,reason:`themeable 2D layout and text`},{workload:`custom-shaders`,preferred:`backend-specific GLSL/WGSL only when profiled`,fallback:`PixiJS filters`,reason:`avoid maintaining paired shader sources without a measured gain`},{workload:`particles`,preferred:`PixiJS for 2D, Babylon.js for 3D`,fallback:`instanced sprites/meshes`,reason:`match simulation and depth to the scene`},{workload:`instanced-terrain`,preferred:`Babylon.js thin instances`,fallback:`PixiJS TileMap for 2D`,reason:`depth-tested repeated 3D geometry`},{workload:`voxels`,preferred:`Babylon.js thin instances`,fallback:`batched meshes`,reason:`color-grouped 3D voxels`},{workload:`animated-models`,preferred:`Babylon.js glTF animation groups`,fallback:`billboard sprites`,reason:`standard 3D interchange and animation support`},{workload:`large-3d-worlds`,preferred:`Babylon.js with streaming/culling`,fallback:`partitioned scenes`,reason:`scene graph, depth, and instancing`}];function Ej(e={}){let t=e.createCanvas?.()??(typeof document>`u`?null:document.createElement(`canvas`)),n=!!t?.getContext(`webgl2`);return{webgl1:n||!!(t?.getContext(`webgl`)??t?.getContext(`experimental-webgl`)),webgl2:n,webgpu:e.webgpu??!!globalThis.navigator?.gpu,wgsl:e.wgsl??!1}}async function Dj(){let e=globalThis.navigator?.gpu;if(!e)return{webgpu:!1,wgsl:!1};try{let t=await(await e.requestAdapter())?.requestDevice();return t?{webgpu:!0,wgsl:(await t.createShaderModule({code:`@compute @workgroup_size(1) fn main() {}`}).getCompilationInfo()).messages.length===0}:{webgpu:!1,wgsl:!1}}catch{return{webgpu:!1,wgsl:!1}}}var Oj=class extends G{},kj=class extends Sw{},Aj=class extends CO{},jj=class extends $s{},Mj=class extends aO{},Nj=xx,Pj=536870911,Fj={orthogonal:`square`,isometric:`isometric`,staggered:`staggered`};function Ij(e,t,n){if(e.frameWidth!==t.tilewidth||e.frameHeight!==t.tileheight)throw Error(`the tileset at firstgid ${n} is cut to ${e.frameWidth}x${e.frameHeight}, but the map is ${t.tilewidth}x${t.tileheight}`)}function Lj(e,t,n){let r=-1;for(let n=0;n<t.length&&t[n]<=e;n++)r=n;if(r===-1)throw Error(`layer "${n}" uses gid ${e}, below every tileset's firstgid (${t.join(`, `)})`);return r}function Rj(e,t){let n=e.orientation??`orthogonal`,r=Fj[n];if(!r)throw Error(`loadTiledMap does not read "${n}" maps yet`);if(r===`staggered`&&(e.staggeraxis??`y`)!==`y`)throw Error(`loadTiledMap only reads Y-axis staggered maps right now, this one is staggered on "${e.staggeraxis}"`);if(r===`staggered`&&(e.staggerindex??`odd`)!==`odd`)throw Error(`loadTiledMap only reads odd-index staggered maps right now, this one staggers "${e.staggerindex}"`);if(e.tilesets.length===0)throw Error(`loadTiledMap needs at least one tileset, this map has none`);let i=[...e.tilesets].sort((e,t)=>e.firstgid-t.firstgid),a,o;if(t instanceof IA){if(e.tilesets.length!==1)throw Error(`loadTiledMap was given one sheet but this map has ${e.tilesets.length} tilesets - pass one sheet per tileset`);Ij(t,e,i[0].firstgid),a=[t],o=[i[0].firstgid]}else{if(t.length!==e.tilesets.length)throw Error(`loadTiledMap was given ${t.length} sheets but this map has ${e.tilesets.length} tilesets - pass one sheet per tileset`);a=i.map(n=>{let r=t.find(e=>e.firstgid===n.firstgid);if(!r)throw Error(`loadTiledMap was given no sheet for the tileset at firstgid ${n.firstgid}`);return Ij(r.sheet,e,n.firstgid),r.sheet}),o=i.map(e=>e.firstgid)}let s=new tj({width:e.width,height:e.height,sheet:a,shape:r}),c=[];for(let t of e.layers)if(t.type===`tilelayer`){if(t.encoding&&t.encoding!==`csv`)throw Error(`layer "${t.name}" uses "${t.encoding}" encoding - export tile layers as CSV/plain, not compressed`);let e=(t.data??[]).map(e=>{let n=e&Pj;if(n===0)return-1;let r=Lj(n,o,t.name);return o.length===1?n-o[0]:QA(r,n-o[r])});s.addLayer(t.name,e)}else if(t.type===`objectgroup`)for(let n of t.objects??[])c.push({...n,tileX:Math.floor(n.x/e.tilewidth),tileY:Math.floor(n.y/e.tileheight)});return{map:s,objects:c}}var zj={panelBorder:4,padding:8,spacing:2,direction:`ltr`,font:{family:`ui-monospace, Consolas, "DejaVu Sans Mono", monospace`,size:12,lineHeight:1.4},color:{text:15263984,textDim:9079446,textHighlight:16770688,panelFill:1842214,panelBorder:4868702,selection:3820154,overlay:0},overlayAlpha:.5},Bj={panelBorder:6,padding:10,spacing:4,direction:`ltr`,font:{family:zj.font.family,size:14,lineHeight:1.5},color:{text:16777215,textDim:13421772,textHighlight:16776960,panelFill:0,panelBorder:16777215,selection:16776960,overlay:0},overlayAlpha:.85},Vj=zj;function Q(){return Vj}var $=new p;function Hj(e){Vj={...zj,...e,font:{...zj.font,...e.font},color:{...zj.color,...e.color}},$.dispatch(Vj)}function Uj(e){return typeof e==`string`?{text:e}:e}function Wj(e,t){return e.align??(t.direction===`rtl`?`right`:`left`)}function Gj(e,t=40){let n=Math.max(0,e);return{total:n,speed:Math.max(0,t),revealed:t===0?n:0}}function Kj(e,t){return e.revealed=Math.min(e.total,Math.max(0,e.revealed+e.speed*t)),Jj(e)}function qj(e){e.revealed=e.total}function Jj(e){return e.revealed>=e.total}var Yj=class extends CO{constructor(e={}){let t=Uj(e),n=Q();super({text:t.text??``,resolution:t.resolution,roundPixels:t.roundPixels,style:new nE({fontFamily:n.font.family,stroke:t.stroke,fontSize:t.size??n.font.size,fontWeight:t.bold?`bold`:`normal`,fill:t.color??n.color.text,lineHeight:(t.size??n.font.size)*n.font.lineHeight,align:Wj(t,n),wordWrap:t.wrapWidth!==void 0,wordWrapWidth:t.wrapWidth??0,breakWords:!0})}),this.themeListener=e=>this.restyle(e),this.revealSource=null,this.reveal=null,this.opts=t,$.add(this.themeListener)}setColor(e){this.style.fill=e}setText(e){this.revealSource=null,this.reveal=null,this.text!==e&&(this.text=e)}showProgressive(e,t){this.revealSource=e,this.reveal=Gj(e.length,t),this.renderRevealed()}updateReveal(e){if(!this.reveal)return!0;let t=Kj(this.reveal,e);return this.renderRevealed(),t}completeReveal(){this.reveal&&(qj(this.reveal),this.renderRevealed())}renderRevealed(){if(!this.reveal||this.revealSource===null)return;let e=this.revealSource.slice(0,Math.floor(this.reveal.revealed));this.text!==e&&(this.text=e)}restyle(e){this.style.fontFamily=e.font.family,this.opts.color===void 0&&(this.style.fill=e.color.text),this.opts.size===void 0&&(this.style.fontSize=e.font.size,this.style.lineHeight=e.font.size*e.font.lineHeight),this.opts.align===void 0&&(this.style.align=Wj(this.opts,e))}destroy(e){$.remove(this.themeListener),super.destroy(e)}},Xj=``,Zj=``,Qj=``;function $j(e){let t=``;for(let n=0;n<e.length;n++)if(e[n]===`\\`&&n+1<e.length&&(e[n+1]===`*`||e[n+1]===`_`||e[n+1]===`\\`)){let r=e[n+1];t+=r===`*`?Xj:r===`_`?Zj:Qj,n++}else t+=e[n];return t}function eM(e){return e.replaceAll(Xj,`*`).replaceAll(Zj,`_`).replaceAll(Qj,`\\`)}function tM(e){return e!==void 0&&/[\p{L}\p{N}_]/u.test(e)}function nM(e,t,n){let r=[],i=0;for(;i<e.length;){if(e[i]!==t){i++;continue}let a=0;for(;e[i+a]===t;)a++;if(!(t===`_`&&tM(e[i-1])&&tM(e[i+a]))){if(n)for(let e=0;e<Math.floor(a/2);e++)r.push(i+e*2);else a%2==1&&r.push(i+a-1)}i+=a}return r}function rM(e,t,n,r,i,a){let o=nM(e,t,n),s=n?2:1;for(let e=0;e+1<o.length;e+=2){let t=o[e],n=o[e+1];i.push({from:t+s,to:n,style:r}),a.push({from:t,to:t+s},{from:n,to:n+s})}}function iM(e){let t=[];for(let n of e){if(!n.text)continue;let e=t[t.length-1];e&&e.bold===n.bold&&e.italic===n.italic?e.text+=n.text:t.push({...n})}return t}function aM(e){let t=$j(e),n=[],r=[];rM(t,`*`,!0,`bold`,n,r),rM(t,`_`,!0,`bold`,n,r),rM(t,`*`,!1,`italic`,n,r),rM(t,`_`,!1,`italic`,n,r);let i=new Set([0,t.length]);for(let e of n)i.add(e.from),i.add(e.to);for(let e of r)i.add(e.from),i.add(e.to);let a=[...i].sort((e,t)=>e-t),o=[];for(let e=0;e+1<a.length;e++){let i=a[e],s=a[e+1];i>=s||r.some(e=>e.from<=i&&s<=e.to)||o.push({text:t.slice(i,s),bold:n.some(e=>e.style===`bold`&&e.from<=i&&s<=e.to),italic:n.some(e=>e.style===`italic`&&e.from<=i&&s<=e.to)})}return iM(o).map(e=>({...e,text:eM(e.text)}))}function oM(e){return aM(e).map(e=>e.text).join(``)}function sM(e,t){let n=[],r=Math.max(0,Math.floor(t));for(let t of e){if(r<=0)break;let e=Math.min(t.text.length,r);n.push({...t,text:t.text.slice(0,e)}),r-=e}return n}var cM=class extends ok{constructor(e={}){let t=Uj(e),n=Q();super({text:lM(t.text??``),resolution:t.resolution,style:new UO({fontFamily:n.font.family,fontSize:t.size??n.font.size,fontWeight:t.bold?`bold`:`normal`,fill:t.color??n.color.text,lineHeight:(t.size??n.font.size)*n.font.lineHeight,align:Wj(t,n),wordWrap:t.wrapWidth!==void 0,wordWrapWidth:t.wrapWidth??0,breakWords:!0})}),this.themeListener=e=>this.restyle(e),this.revealSpans=null,this.reveal=null,this.opts=t,$.add(this.themeListener)}setText(e){this.revealSpans=null,this.reveal=null;let t=lM(e);this.text!==t&&(this.text=t)}showProgressive(e,t){this.revealSpans=aM(e),this.reveal=Gj(oM(e).length,t),this.renderRevealed()}updateReveal(e){if(!this.reveal)return!0;let t=Kj(this.reveal,e);return this.renderRevealed(),t}completeReveal(){this.reveal&&(qj(this.reveal),this.renderRevealed())}renderRevealed(){if(!this.reveal||!this.revealSpans)return;let e=uM(sM(this.revealSpans,this.reveal.revealed));this.text!==e&&(this.text=e)}restyle(e){this.style.fontFamily=e.font.family,this.opts.color===void 0&&(this.style.fill=e.color.text),this.opts.size===void 0&&(this.style.fontSize=e.font.size,this.style.lineHeight=e.font.size*e.font.lineHeight),this.opts.align===void 0&&(this.style.align=Wj(this.opts,e))}destroy(e){$.remove(this.themeListener),super.destroy(e)}};function lM(e){return uM(aM(e))}function uM(e){return e.map(e=>{let t=dM(e.text);return e.italic&&(t=`<i>${t}</i>`),e.bold&&(t=`<b>${t}</b>`),t}).join(``)}function dM(e){return e.replaceAll(`&`,`&amp;`).replaceAll(`<`,`&lt;`).replaceAll(`>`,`&gt;`)}var fM=new Set([`b`,`i`,`span`,`br`,`img`]);function pM(e,t={}){let n=t.variables??{},r=[],i=[],a={bold:!1,italic:!1},o=``,s=()=>{if(!o)return;let e={text:o,bold:a.bold,italic:a.italic};a.color!==void 0&&(e.color=a.color),a.size!==void 0&&(e.size=a.size),r.push(e),o=``};for(let t=0;t<e.length;t++){let c=e[t];if(c===`&`){let n=wM(e,t);if(n){o+=n.text,t=n.end;continue}}if(c===`$`){let r=TM(e,t),i=r?n[r.name]:void 0;if(r&&i!==void 0){o+=i,t=r.end;continue}}if(c===`<`){let n=SM(e,t);if(n&&fM.has(n.name)){if(n.name===`img`){let i=CM(e,n);if(i){s(),r.push({text:``,bold:!1,italic:!1,image:i.src}),t=i.end;continue}}else if(n.name===`br`){o+=`
1332
- `,t=n.end;continue}else if(n.closing){let e=i[i.length-1];if(e?.tag===n.name){s(),a=e.style,i.pop(),t=n.end;continue}}else{s(),i.push({tag:n.name,style:a}),a=bM(a,n.name,n.body),t=n.end;continue}}}o+=c}return s(),r}function mM(e,t={}){return pM(e,t).map(e=>e.image??e.text).join(``)}function hM(e){return e.map(e=>{if(e.image!==void 0)return``;let t=yM(e.text);e.italic&&(t=`<i>${t}</i>`),e.bold&&(t=`<b>${t}</b>`);let n=[e.color===void 0?void 0:`color:${e.color}`,e.size===void 0?void 0:`font-size:${e.size}px`].filter(e=>e!==void 0);return n.length>0&&(t=`<span style="${n.join(`;`)}">${t}</span>`),t}).join(``)}function gM(e,t={}){let n=t.describeImage??(()=>`[image]`);return e.map(e=>e.image===void 0?e.text:n(e.image)).join(``)}function _M(e,t,n){let r=[];for(let t of e){if(t.image!==void 0){r.push({...t});continue}t.text.split(`
1333
- `).forEach((e,n)=>{n>0&&r.push({text:``,bold:t.bold,italic:t.italic,hardBreak:!0});for(let n of e.match(/\S+|\s+/g)??[])r.push({text:n,bold:t.bold,italic:t.italic,color:t.color,size:t.size})})}let i=[],a=[],o=0,s=()=>{for(;a.length>0&&a[a.length-1].text.trim()===``&&!a[a.length-1].image;)o-=t(a[a.length-1]),a.pop();i.push({spans:vM(a),width:Math.max(0,o)}),a=[],o=0};for(let e of r){if(e.hardBreak){s();continue}let r=t(e),i=e.image===void 0&&e.text.trim()===``;o>0&&!i&&o+r>n&&s(),a.push(e),o+=r}return(a.length>0||i.length===0)&&s(),i}function vM(e){let t=[];for(let n of e){let e=t[t.length-1];e&&n.image===void 0&&e.image===void 0&&e.bold===n.bold&&e.italic===n.italic&&e.color===n.color&&e.size===n.size?e.text+=n.text:t.push({...n})}return t}function yM(e){return e.replaceAll(`&`,`&amp;`).replaceAll(`<`,`&lt;`).replaceAll(`>`,`&gt;`).replaceAll(`"`,`&quot;`).replaceAll(`'`,`&#39;`)}function bM(e,t,n){if(t===`b`)return{...e,bold:!0};if(t===`i`)return{...e,italic:!0};let r=xM(n,`color`),i=Number(xM(n,`size`)??``),a={...e};return r&&(a.color=r),Number.isFinite(i)&&i>0&&(a.size=i),a}function xM(e,t){let n=RegExp(`(?:^|\\s)${t}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s"'>]+))`).exec(e);return n?n[1]??n[2]??n[3]:void 0}function SM(e,t){let n=/^<(\/?)([a-zA-Z]+)([^>]*)>/.exec(e.slice(t));if(!n)return null;let r=n[3].trimEnd();return{name:n[2].toLowerCase(),closing:n[1]===`/`,selfClosing:r.endsWith(`/`)&&n[1]===``,body:r.replace(/\/$/,``).trim(),end:t+n[0].length-1}}function CM(e,t){if(t.selfClosing){let e=xM(t.body,`src`);return e?{src:e,end:t.end}:null}let n=e.indexOf(`</img>`,t.end+1);if(n<0)return null;let r=e.slice(t.end+1,n).trim();return r?{src:r,end:n+6-1}:null}function wM(e,t){let n={lt:`<`,gt:`>`,amp:`&`,quot:`"`,apos:`'`},r=/^&(lt|gt|amp|quot|apos);/.exec(e.slice(t));if(r)return{text:n[r[1]],end:t+r[0].length-1};let i=/^&#(\d+);/.exec(e.slice(t));return i?{text:String.fromCodePoint(Number(i[1])),end:t+i[0].length-1}:null}function TM(e,t){let n=/^\$([A-Za-z_][A-Za-z0-9_]*)/.exec(e.slice(t));return n?{name:n[1],end:t+n[0].length-1}:null}var EM=class extends IO{constructor(e={}){let t=Uj(e),n=Q();super({text:t.text??``,style:DM(t,n)}),this.themeListener=e=>this.restyle(e),this.opts=t,$.add(this.themeListener)}setText(e){this.text!==e&&(this.text=e)}restyle(e){this.style=DM(this.opts,e)}destroy(e){$.remove(this.themeListener),super.destroy(e)}};function DM(e,t){return{fontFamily:t.font.family,fontSize:e.size??t.font.size,fontWeight:e.bold?`bold`:`normal`,fill:e.color??t.color.text,align:Wj(e,t),wordWrap:e.wrapWidth!==void 0,wordWrapWidth:e.wrapWidth??0,breakWords:!0}}var OM=class extends G{constructor(e,t){super();let n=typeof t.border==`number`?{left:t.border,top:t.border,right:t.border,bottom:t.border}:t.border;this.sprite=new hk({texture:e,leftWidth:n.left,topHeight:n.top,rightWidth:n.right,bottomHeight:n.bottom}),this.addChild(this.sprite)}get border(){return{left:this.sprite.leftWidth,top:this.sprite.topHeight,right:this.sprite.rightWidth,bottom:this.sprite.bottomHeight}}resize(e,t){let n=this.border;this.sprite.width=Math.max(e,n.left+n.right),this.sprite.height=Math.max(t,n.top+n.bottom)}},kM=`position:absolute;width:1px;height:1px;margin:-1px;padding:0;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap;border:0;`,AM=class{constructor(){this.polite=null,this.assertive=null}region(e){if(typeof document>`u`||!document.body)return null;let t=e?this.assertive:this.polite;if(t)return t;let n=document.createElement(`div`);return n.setAttribute(`aria-live`,e?`assertive`:`polite`),n.setAttribute(`aria-atomic`,`true`),n.setAttribute(`role`,`status`),n.setAttribute(`style`,kM),document.body.appendChild(n),e?this.assertive=n:this.polite=n,n}announce(e,t={}){let n=this.region(t.assertive??!1);n&&(n.textContent=``,n.appendChild(document.createTextNode(e)))}clear(){this.polite&&(this.polite.textContent=``),this.assertive&&(this.assertive.textContent=``)}destroy(){this.polite?.remove(),this.assertive?.remove(),this.polite=null,this.assertive=null}},jM=new AM,MM=class extends G{constructor(e){super(),this.content=new G,this.onClose=new p,this.titleLabel=null,this.innerWidth=0,this.innerHeight=0,this.currentWidth=0,this.currentHeight=0,this.themeListener=()=>this.restyle(),this.isClosed=!1,this.delegate=null;let t=Q();this.modal=e.modal??!0,this.closable=e.closable??!0,this.dims=e.dims??this.modal,this.anchor=e.anchor??`center`,this.background=t.panel?new OM(t.panel,{border:t.panelBorder}):new Sw,this.addChild(this.background),e.title!==void 0&&(this.titleLabel=new Yj({text:e.title,color:t.color.textHighlight,bold:!0}),this.addChild(this.titleLabel),jM.announce(e.title)),this.addChild(this.content),this.resize(e.width,e.height),$.add(this.themeListener)}restyle(){this.titleLabel?.setColor(Q().color.textHighlight),this.resize(this.currentWidth,this.currentHeight)}resize(e,t){this.currentWidth=e,this.currentHeight=t;let n=Q(),r=(this.background instanceof OM?this.background.border.left:2)+n.padding;this.background instanceof OM?this.background.resize(e,t):this.background.clear().roundRect(0,0,e,t,4).fill({color:n.color.panelFill}).stroke({color:n.color.panelBorder,width:1});let i=r;this.titleLabel&&(this.titleLabel.x=n.direction===`rtl`?e-r-this.titleLabel.width:r,this.titleLabel.y=r,i=r+this.titleLabel.height+n.padding),this.content.x=r,this.content.y=i,this.innerWidth=Math.max(0,e-r*2),this.innerHeight=Math.max(0,t-i-r)}get contentWidth(){return this.innerWidth}get contentHeight(){return this.innerHeight}setTitle(e){this.titleLabel?.setText(e)}handleAction(e){return this.isClosed?!1:this.delegate?.handleAction(e)?!0:e===`cancel`&&this.closable?(this.close(),!0):!1}get closed(){return this.isClosed}update(e){}close(){this.isClosed||(this.isClosed=!0,this.onClose.dispatch(),this.parent?.removeChild(this),this.destroy({children:!0}))}place(e,t){if(this.isClosed)return;let n=this.getLocalBounds(),r=Q().padding*2;this.x=Math.round((e-n.width)/2),this.y=this.anchor===`bottom`?Math.round(t-n.height-r):this.anchor===`top`?r:Math.round((t-n.height)/2)}destroy(e){this.isClosed=!0,$.remove(this.themeListener),super.destroy(e)}},NM=class extends G{constructor(){super(),this.windows=[],this.overlay=new Sw,this.viewportWidth=0,this.viewportHeight=0,this.listener=e=>this.handleAction(e),this.themeListener=()=>this.drawOverlay(),this.overlay.visible=!1,this.addChild(this.overlay),Ce.add(this.listener),$.add(this.themeListener)}setViewport(e,t){this.viewportWidth=e,this.viewportHeight=t,this.drawOverlay();for(let n of this.windows)n.place(e,t)}get top(){return this.windows[this.windows.length-1]??null}get isEmpty(){return this.windows.length===0}get depth(){return this.windows.length}push(e){if(e.closed)throw Error(`cannot open a window that was already closed`);return this.windows.push(e),this.addChild(e),e.onClose.add(()=>(this.forget(e),!1)),e.place(this.viewportWidth,this.viewportHeight),this.updateOverlay(),e}pop(){this.top?.close()}closeAll(){for(let e of[...this.windows].reverse())e.close()}forget(e){let t=this.windows.indexOf(e);t!==-1&&this.windows.splice(t,1),this.updateOverlay()}updateOverlay(){let e=this.windows.findIndex(e=>e.dims);if(e===-1){this.overlay.visible=!1;return}this.overlay.visible=!0,this.setChildIndex(this.overlay,Math.max(0,this.getChildIndex(this.windows[e])-1))}drawOverlay(){let e=Q();this.overlay.clear().rect(0,0,this.viewportWidth,this.viewportHeight).fill({color:e.color.overlay,alpha:e.overlayAlpha})}handleAction(e){return this.top?.handleAction(e)??!1}get blocksWorld(){return this.windows.some(e=>e.modal)}update(e){this.top?.update(e)}destroy(e){Ce.remove(this.listener),$.remove(this.themeListener),super.destroy(e)}},PM=class{constructor(e){this.list=[],this.current=0,this.hooks=e}get items(){return this.list}get selectedIndex(){return this.current}get selected(){return this.list[this.current]??null}get length(){return this.list.length}reset(e){this.list=e,this.current=e.findIndex(e=>!e.disabled),this.current===-1&&(this.current=0)}swap(e,t){[this.list[e],this.list[t]]=[this.list[t],this.list[e]]}land(e){this.current=e,this.hooks.onChange();let t=this.list[e];t&&this.hooks.onHighlight(t,e)}select(e){e<0||e>=this.list.length||this.list[e].disabled||this.land(e)}confirm(e){let t=this.selected;return!t||t.disabled?!1:(e?.(t,this.current),!0)}step(e,t){if(this.list.length===0)return!1;let n=this.current;for(let r=0;r<t;r++){let t=e(n,this.list.length);if(n=t,!(t<0||t>=this.list.length)&&!this.list[t].disabled)return this.land(t),!0}return!1}},FM=class extends G{constructor(e){super(),this.selection=new PM({onChange:()=>this.refresh(),onHighlight:(e,t)=>this.onHighlight?.(e,t)}),this.rows=[],this.rowsLayer=new G,this.highlight=new Sw,this.mask_=new Sw,this.scroll=0,this.themeListener=()=>this.restyle();let t=Q();this.viewWidth=e.width,this.viewHeight=e.height,this.explicitRowHeight=e.rowHeight!==void 0,this.rowHeight=e.rowHeight??Math.ceil(t.font.size*t.font.lineHeight)+t.spacing,this.onSelect=e.onSelect??null,this.onHighlight=e.onHighlight??null,this.addChild(this.highlight),this.addChild(this.rowsLayer),this.addChild(this.mask_),this.rowsLayer.mask=this.mask_,this.drawMask(),this.eventMode=`static`,this.on(`wheel`,e=>this.move(e.deltaY>0?1:-1)),this.setItems(e.items??[]),$.add(this.themeListener)}restyle(){let e=Q();this.explicitRowHeight||(this.rowHeight=Math.ceil(e.font.size*e.font.lineHeight)+e.spacing);let t=e.direction===`rtl`,n=this.selection.items;this.rows.forEach((r,i)=>{r.y=i*this.rowHeight;let a=n[i],o=r.children.find(e=>e instanceof Yj);if(o){o.setColor(a.disabled?e.color.textDim:e.color.text);let n=e.spacing+(a.icon?this.rowHeight:0);o.x=t?this.viewWidth-n-o.width:n,o.y=Math.round((this.rowHeight-o.height)/2)}a.icon&&(a.icon.x=t?this.viewWidth-e.spacing-this.rowHeight:e.spacing)}),this.refresh()}destroy(e){$.remove(this.themeListener),super.destroy(e)}drawMask(){this.mask_.clear().rect(0,0,this.viewWidth,this.viewHeight).fill({color:16777215})}get visibleRows(){return Math.max(1,Math.floor(this.viewHeight/this.rowHeight))}get selectedIndex(){return this.selection.selectedIndex}get selected(){return this.selection.selected}get length(){return this.selection.length}setItems(e){for(let e of this.rows)e.destroy({children:!0});this.rows=[],this.rowsLayer.removeChildren();let t=Q(),n=t.direction===`rtl`;e.forEach((e,r)=>{let i=new G;i.y=r*this.rowHeight,i.eventMode=`static`,i.cursor=e.disabled?`default`:`pointer`,i.on(`pointerdown`,()=>{e.disabled||(this.select(r),this.confirm())}),e.icon&&(e.icon.x=n?this.viewWidth-t.spacing-this.rowHeight:t.spacing,i.addChild(e.icon));let a=new Yj({text:e.text,color:e.disabled?t.color.textDim:t.color.text}),o=t.spacing+(e.icon?this.rowHeight:0);a.x=n?this.viewWidth-o-a.width:o,a.y=Math.round((this.rowHeight-a.height)/2),i.addChild(a),this.rows.push(i),this.rowsLayer.addChild(i)}),this.selection.reset(e),this.scroll=0,this.refresh()}resize(e,t){this.viewWidth=e,this.viewHeight=t,this.drawMask(),this.refresh()}move(e){return this.selection.step((t,n)=>(t+e+n)%n,this.selection.length)}select(e){this.selection.select(e)}confirm(){return this.selection.confirm(this.onSelect)}handleAction(e){switch(e){case`up`:return this.move(-1);case`down`:return this.move(1);case`confirm`:return this.confirm();default:return!1}}refresh(){let e=this.visibleRows,t=this.selection.selectedIndex,n=this.selection.length;t<this.scroll?this.scroll=t:t>=this.scroll+e&&(this.scroll=t-e+1),this.scroll=Math.max(0,Math.min(this.scroll,Math.max(0,n-e))),this.rowsLayer.y=-this.scroll*this.rowHeight;let r=Q();if(n===0){this.highlight.clear();return}this.highlight.clear().rect(0,(t-this.scroll)*this.rowHeight,this.viewWidth,this.rowHeight).fill({color:r.color.selection})}},IM=class extends G{columnX(e){return(Q().direction===`rtl`?this.columns-1-e:e)*this.cellSize}constructor(e){super(),this.selection=new PM({onChange:()=>this.refresh(),onHighlight:(e,t)=>this.onHighlight?.(e,t)}),this.cells=[],this.cellsLayer=new G,this.highlight=new Sw,this.pickupHighlight=new Sw,this.mask_=new Sw,this.scrollRow=0,this.pickedUp=null,this.pressedIndex=null,this.pressTimer=0,this.themeListener=()=>{let e=Q();this.selection.items.forEach((t,n)=>{let r=this.cells[n];r&&(r.x=this.columnX(n%this.columns),!((t.quantity??1)<=1)&&r.children.find(e=>e instanceof Yj)?.setColor(e.color.textHighlight))}),this.refresh()},this.viewWidth=e.width,this.viewHeight=e.height,this.columns=Math.max(1,e.columns),this.cellSize=e.cellSize??Math.floor(this.viewWidth/this.columns),this.longPressDuration=e.longPressDuration??.6,this.onSelect=e.onSelect??null,this.onHighlight=e.onHighlight??null,this.onQuickslot=e.onQuickslot??null,this.onReorder=e.onReorder??null,this.addChild(this.highlight),this.addChild(this.pickupHighlight),this.addChild(this.cellsLayer),this.addChild(this.mask_),this.cellsLayer.mask=this.mask_,this.drawMask(),this.eventMode=`static`,this.on(`wheel`,e=>this.move(0,e.deltaY>0?1:-1)),this.setItems(e.items??[]),$.add(this.themeListener)}destroy(e){$.remove(this.themeListener),super.destroy(e)}drawMask(){this.mask_.clear().rect(0,0,this.viewWidth,this.viewHeight).fill({color:16777215})}get visibleRows(){return Math.max(1,Math.floor(this.viewHeight/this.cellSize))}get rows(){return Math.max(1,Math.ceil(this.selection.length/this.columns))}get selectedIndex(){return this.selection.selectedIndex}get selected(){return this.selection.selected}get length(){return this.selection.length}setItems(e){this.pickedUp=null,this.pressedIndex=null;for(let e of this.cells)e.destroy({children:!0});this.cells=[],this.cellsLayer.removeChildren();let t=Q();e.forEach((e,n)=>{let r=Math.floor(n/this.columns),i=n%this.columns,a=new G;if(a.x=this.columnX(i),a.y=r*this.cellSize,a.eventMode=`static`,a.cursor=e.disabled?`default`:`pointer`,e.icon.x=Math.round((this.cellSize-e.icon.width)/2),e.icon.y=Math.round((this.cellSize-e.icon.height)/2),e.disabled&&(e.icon.alpha=.4),a.addChild(e.icon),(e.quantity??1)>1){let n=new Yj({text:String(e.quantity),size:10,color:t.color.textHighlight});n.x=this.cellSize-n.width-2,n.y=this.cellSize-n.height-1,a.addChild(n)}a.on(`pointerdown`,()=>{this.pressedIndex=n,this.pressTimer=0}),a.on(`pointerup`,()=>this.releaseCell(n)),a.on(`pointerupoutside`,()=>this.releaseCell(n)),this.cells.push(a),this.cellsLayer.addChild(a)}),this.selection.reset(e),this.scrollRow=0,this.refresh()}releaseCell(e){this.pressedIndex===e&&(this.pressedIndex=null,this.selection.items[e]?.disabled||this.tapCell(e))}resize(e,t){this.viewWidth=e,this.viewHeight=t,this.drawMask(),this.refresh()}update(e){if(this.pressedIndex===null||(this.pressTimer+=e,this.pressTimer<this.longPressDuration))return;let t=this.pressedIndex;this.pressedIndex=null;let n=this.selection.items[t];n&&!n.disabled&&this.onQuickslot?.(n,t)}tapCell(e){let t=this.selection.items;if(e<0||e>=t.length)return;if(this.pickedUp===null){if(t[e].disabled)return;this.pickedUp=e,this.refresh();return}let n=this.pickedUp;this.pickedUp=null,n!==e&&(this.swapCells(n,e),this.onReorder?.(n,e)),this.refresh()}swapCells(e,t){let n=this.selection.items;this.selection.swap(e,t);let r=this.cells[e],i=this.cells[t],a=r.removeChildren(),o=i.removeChildren();for(let e of o)r.addChild(e);for(let e of a)i.addChild(e);r.cursor=n[e].disabled?`default`:`pointer`,i.cursor=n[t].disabled?`default`:`pointer`}cancelPickup(){this.pickedUp=null,this.refresh()}move(e,t){let n=this.rows,r=this.columns;return this.selection.step(i=>{let a=(Math.floor(i/r)+t+n)%n,o=(i%r+e+r)%r;return a*r+o},n*r)}select(e){this.selection.select(e)}confirm(){return this.selection.confirm(this.onSelect)}handleAction(e){switch(e){case`up`:return this.move(0,-1);case`down`:return this.move(0,1);case`left`:return this.move(Q().direction===`rtl`?1:-1,0);case`right`:return this.move(Q().direction===`rtl`?-1:1,0);case`confirm`:return this.confirm();case`cancel`:return this.pickedUp!==null&&(this.cancelPickup(),!0);default:return!1}}cellRect(e){return{x:this.columnX(e%this.columns),y:Math.floor(e/this.columns)*this.cellSize}}refresh(){let e=this.visibleRows,t=this.selection.selectedIndex,n=Math.floor(t/this.columns);n<this.scrollRow?this.scrollRow=n:n>=this.scrollRow+e&&(this.scrollRow=n-e+1),this.scrollRow=Math.max(0,Math.min(this.scrollRow,Math.max(0,this.rows-e))),this.cellsLayer.y=-this.scrollRow*this.cellSize;let r=Q();if(this.pickupHighlight.clear(),this.pickedUp!==null){let{x:e,y:t}=this.cellRect(this.pickedUp);this.pickupHighlight.rect(e,t,this.cellSize,this.cellSize).stroke({color:r.color.textHighlight,width:2})}if(this.highlight.clear(),this.selection.length>0){let{x:e,y:n}=this.cellRect(t);this.highlight.rect(e,n,this.cellSize,this.cellSize).fill({color:r.color.selection})}}},LM=class{constructor(e){if(this.onChange=new p,this.currentTabIndex=0,this.currentQuery=``,this.rows_=[],this.currentSelectedIndex=0,this.detail=!1,e.tabs.length===0)throw Error(`TabbedList needs at least one tab`);this.tabList=[...e.tabs],this.rowsFor=e.rowsFor,this.pageSize=Math.max(0,Math.floor(e.pageSize??0)),this.labelOf=e.label??(e=>String(e)),this.filterOf=e.filter??((e,t)=>t===``||this.labelOf(e).toLowerCase().includes(t.toLowerCase())),this.disabledOf=e.disabled??(()=>!1),this.recompute()}get tabs(){return this.tabList}get tab(){return this.tabList[this.currentTabIndex]}get query(){return this.currentQuery}get rows(){return this.rows_}get pageCount(){return this.pageSize<=0?1:Math.max(1,Math.ceil(this.rows_.length/this.pageSize))}get page(){return this.pageSize<=0?0:Math.floor(this.currentSelectedIndex/this.pageSize)}get pageRows(){if(this.pageSize<=0)return this.rows_;let e=this.page*this.pageSize;return this.rows_.slice(e,e+this.pageSize)}get selectedIndex(){return this.currentSelectedIndex}get selected(){return this.rows_[this.currentSelectedIndex]??null}get detailOpen(){return this.detail}selectTab(e){let t=this.tabList.findIndex(t=>t.id===e);t===-1||this.tabList[t].disabled||t!==this.currentTabIndex&&(this.currentTabIndex=t,this.recompute(),this.emit())}nextTab(e=1){if(e===0)return;let t=e>0?1:-1,n=this.currentTabIndex;for(let r=0;r<Math.abs(e);r++)do n=(n+t+this.tabList.length)%this.tabList.length;while(this.tabList[n].disabled&&n!==this.currentTabIndex);n!==this.currentTabIndex&&(this.currentTabIndex=n,this.recompute(),this.emit())}setQuery(e){e!==this.currentQuery&&(this.currentQuery=e,this.recompute(),this.emit())}move(e){if(e===0||this.rows_.length===0)return;let t=e>0?1:-1,n=this.currentSelectedIndex;for(let r=0;r<Math.abs(e);r++){let e=n;do e+=t;while(e>=0&&e<this.rows_.length&&this.disabledOf(this.rows_[e]));if(e<0||e>=this.rows_.length)break;n=e}n!==this.currentSelectedIndex&&(this.currentSelectedIndex=n,this.emit())}setPage(e){let t=Math.max(0,Math.min(this.pageCount-1,Math.floor(e)));if(this.pageSize<=0)return;let n=this.firstSelectableOnPage(t);n!==this.currentSelectedIndex&&(this.currentSelectedIndex=n,this.emit())}nextPage(e){this.setPage(this.page+e)}openDetail(){return this.selected===null||this.disabledOf(this.selected)?!1:(this.detail||(this.detail=!0,this.emit()),!0)}closeDetail(){this.detail&&(this.detail=!1,this.emit())}firstSelectableOnPage(e){let t=e*this.pageSize,n=Math.min(this.rows_.length,t+this.pageSize);for(let e=t;e<n;e++)if(!this.disabledOf(this.rows_[e]))return e;return Math.min(t,Math.max(0,this.rows_.length-1))}firstSelectable(e){for(let t=e;t<this.rows_.length;t++)if(!this.disabledOf(this.rows_[t]))return t;return 0}recompute(){let e=this.rowsFor(this.tab.id).filter(e=>this.filterOf(e,this.currentQuery));this.rows_=e,this.currentSelectedIndex=e.length===0?0:this.firstSelectable(0),this.detail=!1}emit(){this.onChange.dispatch()}};function RM(e,t,n={}){let r={},i=t.replace(/\r/g,``).split(`
1334
- `),a=null,o=``,s=[],c=!1,l=()=>{if(a){if(r[a]!==void 0)throw Error(`Duplicate FTL message: ${a}`);if(s.length){if(!c)throw Error(`FTL select expression is not closed: ${a}`);let t=o.trim().match(/^\{\s*\$([\w-]+)\s*->\s*$/)?.[1];if(!t)throw Error(`Invalid FTL selector: ${o}`);r[a]=BM(e,t,s)}else r[a]=zM(o);a=null,o=``,s=[],c=!1}};for(let e of i){if(!e.trim()||e.trimStart().startsWith(`#`))continue;let t=e.match(/^([\w-]+)\s*=\s*(.*)$/);if(t){l(),a=t[1],o=t[2];continue}if(!a)throw Error(`FTL continuation has no message: ${e}`);if(e.trim()===`}`){if(!s.length||c)throw Error(`Unexpected FTL select terminator: ${e}`);c=!0;continue}if(c)throw Error(`FTL content follows a closed select expression: ${e}`);let n=e.match(/^\s*(\*)?\[([^\]]+)\]\s*(.*)$/);if(n){s.push({key:n[2],value:n[3],default:!!n[1]});continue}if(/^\s+/.test(e)){s.length?s[s.length-1].value+=` ${e.trim()}`:o+=` ${e.trim()}`;continue}throw Error(`Invalid FTL line: ${e}`)}return l(),{locale:e,direction:n.direction??(/^(ar|he|fa|ur)(?:-|$)/i.test(e)?`rtl`:`ltr`),messages:r}}function zM(e){return e.replace(/\{\s*\$([\w-]+)\s*(?:!([sra]))?\s*(?::\s*([^{}]*?))?\s*\}/g,(e,t,n,r)=>`{${t}${n?`!${n}`:``}${r===void 0?``:`:${r.trim()}`}}`).trim()}function BM(e,t,n){let r=n.filter(e=>e.default);if(r.length!==1)throw Error(`FTL select expressions need exactly one default variant`);let i=r[0],a=new Intl.PluralRules(e);return{format(e={}){let r=e[t],o=n.find(e=>e.key===String(r)),s=typeof r==`number`?a.select(r):``;return zM((o??n.find(e=>e.key===s)??i).value)}}}function VM(e,t,n={}){let r=n.domain??`messages`,i=r===`messages`?``:`${r}:`,a={},o=t.replace(/\r\n?/g,`
1331
+ `}},Ck=class extends xu{constructor(e){super({glProgram:pp({name:`color-transform-batch`,bits:[gp,xk,Sp(e),jp]}),gpuProgram:fp({name:`color-transform-batch`,bits:[hp,Sk,bp(e),Ap]}),resources:{batchSamplers:Ym(e)}}),this.maxTextures=e}},wk=7,Tk=class extends $u{constructor(){let e=new Ku({data:new Float32Array(1),label:`mwg-color-transform-attribute-buffer`,usage:X.VERTEX|X.COPY_DST,shrinkToFit:!1}),t=new Ku({data:new Uint32Array(1),label:`mwg-color-transform-index-buffer`,usage:X.INDEX|X.COPY_DST,shrinkToFit:!1});super({attributes:{aPosition:{buffer:e,format:`float32x2`,stride:28,offset:0},aUV:{buffer:e,format:`float32x2`,stride:28,offset:8},aColor:{buffer:e,format:`unorm8x4`,stride:28,offset:16},aTextureIdAndRound:{buffer:e,format:`uint16x2`,stride:28,offset:20},aColorAdd:{buffer:e,format:`unorm8x4`,stride:28,offset:24}},indexBuffer:t})}},Ek=0,Dk=e=>e.colorAdd??Ek;function Ok(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h){e[n]=r*l+a*u+s,e[n+1]=o*u+i*l+c,e[n+2]=d,e[n+3]=f,t[n+4]=p,t[n+5]=m,t[n+6]=h}var kk=class e extends Um{static{this.extension={type:[j.Batcher],name:`mwg-color-transform`}}constructor(t){super(t),this.geometry=new Tk,this.name=e.extension.name,this.vertexSize=wk,this.shader=new Ck(t.maxTextures)}packAttributes(e,t,n,r,i){let a=i<<16|e.roundPixels&65535,{a:o,b:s,c,d:l,tx:u,ty:d}=e.transform,{positions:f,uvs:p}=e,m=e.color,h=Dk(e),g=e.attributeOffset,_=g+e.attributeSize;for(let e=g;e<_;e++){let i=e*2,g=f[i],_=f[i+1];t[r++]=o*g+c*_+u,t[r++]=l*_+s*g+d,t[r++]=p[i],t[r++]=p[i+1],n[r++]=m,n[r++]=a,n[r++]=h}}packQuadAttributes(e,t,n,r,i){let{a,b:o,c:s,d:c,tx:l,ty:u}=e.transform,{bounds:d}=e,f=e.texture.uvs,p=d.maxX,m=d.minX,h=d.maxY,g=d.minY,_=e.color,v=Dk(e),y=i<<16|e.roundPixels&65535;Ok(t,n,r,a,o,s,c,l,u,m,g,f.x0,f.y0,_,y,v),r+=wk,Ok(t,n,r,a,o,s,c,l,u,p,g,f.x1,f.y1,_,y,v),r+=wk,Ok(t,n,r,a,o,s,c,l,u,p,h,f.x2,f.y2,_,y,v),r+=wk,Ok(t,n,r,a,o,s,c,l,u,m,h,f.x3,f.y3,_,y,v)}_updateMaxTextures(e){this.shader.maxTextures!==e&&(this.shader.destroy(),this.shader=new Ck(e))}destroy(){this.shader.destroy(),super.destroy()}},Ak=`mwg-tinted-sprite`;function jk(e){e.renderPipeId=Ak}var Mk=class{static{this.extension={type:[j.WebGLPipes,j.WebGPUPipes,j.CanvasPipes],name:Ak}}constructor(e){this.renderer=e}addRenderable(e,t){let n=this.element(e);e.didViewUpdate&&this.sync(e,n),this.renderer.renderPipes.batch.addToBatch(n,t)}updateRenderable(e){let t=this.element(e);e.didViewUpdate&&this.sync(e,t),t._batcher.updateElement(t)}validateRenderable(e){let t=this.element(e);return!t._batcher.checkAndUpdateTexture(t,e.texture)}sync(e,t){t.bounds=e.visualBounds,t.texture=e.texture,t.colorAdd=e.colorAdd}element(e){let t=e._gpuData;return t[this.renderer.uid]??this.create(e,t)}create(e,t){let n=new Nk;return n.renderable=e,n.transform=e.groupTransform,n.texture=e.texture,n.bounds=e.visualBounds,n.roundPixels=this.renderer._roundPixels|e._roundPixels,n.colorAdd=e.colorAdd,t[this.renderer.uid]=n,n}destroy(){this.renderer=null}},Nk=class{constructor(){this.batcherName=kk.extension.name,this.topology=`triangle-list`,this.attributeSize=4,this.indexSize=6,this.packAsQuad=!0,this.roundPixels=0,this.colorAdd=0,this._attributeStart=0,this._textureId=0,this._indexStart=0,this._batcher=null,this._batch=null}get blendMode(){return this.renderable.groupBlendMode}get color(){return this.renderable.groupColorAlpha}reset(){this.renderable=null,this.texture=null,this._batcher=null,this._batch=null,this.bounds=null,this.colorAdd=0}destroy(){this.reset()}},Pk=!1;function Fk(){Pk||(Pk=!0,M.add(kk),M.add(Mk))}function Ik(e,t,n,r=0){return(Rk(r)<<24|Rk(n)<<16|Rk(t)<<8|Rk(e))>>>0}function Lk(e,t){return Ik((e>>16&255)/255*t,(e>>8&255)/255*t,(e&255)/255*t)}function Rk(e){return Math.max(0,Math.min(255,Math.round(e*255)))}var zk=Ek;Fk();var Bk=class extends $s{constructor(e){super(e),this._colorAdd=0,jk(this)}get colorAdd(){return this._colorAdd}set colorAdd(e){this._colorAdd!==e&&(this._colorAdd=e,this.onViewUpdate())}setColorAdd(e,t,n,r=0){this.colorAdd=Ik(e,t,n,r)}lerpTint(e,t){let n=Math.round((1-t)*255);this.tint=n<<16|n<<8|n,this.colorAdd=Lk(e,t)}silhouette(e){this.tint=0,this.colorAdd=Lk(e,1)}resetColor(){this.tint=16777215,this.colorAdd=0}};function Vk(e){return[e>>16&255,e>>8&255,e&255]}function Hk(e,t,n){return Math.round(e)<<16|Math.round(t)<<8|Math.round(n)}function Uk(e,t,n){return e+(t-e)*n}function Wk(e,t,n){let[r,i,a]=Vk(e),[o,s,c]=Vk(t);return Hk(Uk(r,o,n),Uk(i,s,n),Uk(a,c,n))}function Gk(e,t){return{from:e,to:e.map((n,r)=>{if(e.length<=1)return t.mid;let i=r/(e.length-1);return i<=.5?Wk(t.min,t.mid,i*2):Wk(t.mid,t.max,(i-.5)*2)})}}function Kk(e,t,n=`exact`){let r=t.from.map(Vk),i=new Uint8ClampedArray(e.length);for(let a=0;a<e.length;a+=4){let o=e[a+3],s=e[a],c=e[a+1],l=e[a+2];if(i[a]=s,i[a+1]=c,i[a+2]=l,i[a+3]=o,o===0||r.length===0)continue;if(n===`exact`){let e=r.findIndex(([e,t,n])=>e===s&&t===c&&n===l);if(e<0)continue;let[n,o,u]=Vk(t.to[e]??t.from[e]);i[a]=n,i[a+1]=o,i[a+2]=u;continue}let u=0,d=1/0;for(let e=0;e<r.length;e+=1){let[t,n,i]=r[e],a=s-t,o=c-n,f=l-i,p=a*a+o*o+f*f;p<d&&(d=p,u=e)}let[f,p,m]=Vk(t.to[u]??t.from[u]);i[a]=f,i[a+1]=p,i[a+2]=m}return i}function qk(e,t,n){let r=e.width,i=e.height;if(r<=0||i<=0||!e.source)return e;let a=t.createCanvas?.(r,i)??(typeof document>`u`?null:document.createElement(`canvas`));if(!a)return e;a.width=r,a.height=i;let o=a.getContext(`2d`);return o?(o.drawImage(e.source.resource,0,0),n(o,r,i),U.from(a)):e}function Jk(e,t,n={},r=`exact`){return qk(e,n,(e,n,i)=>{let a=Kk(e.getImageData(0,0,n,i).data,t,r);e.putImageData({data:a,width:n,height:i},0,0)})}function Yk(e){e=e.replace(/^"|"$/g,``);let t=[],n=0,r=0;for(let i=0;i<e.length;i+=1)e[i]===`(`?r+=1:e[i]===`)`?r=Math.max(0,r-1):e[i]===`~`&&r===0&&(t.push(e.slice(n,i)),n=i+1);t.push(e.slice(n));let i=(t.shift()??``).trim(),a=[];for(let e of t){let t=/^([A-Za-z][A-Za-z0-9_-]*)(?:\((.*)\))?$/.exec(e.trim());t&&a.push({name:t[1].toUpperCase(),args:t[2]===void 0?[]:t[2].split(`,`).map(e=>e.trim())})}return{path:i,modifiers:a}}function Xk(e,t){return e.modifiers.find(e=>e.name===t.toUpperCase())}function Zk(e,t,n){return[1,0,0,0,e/255,0,1,0,0,t/255,0,0,1,0,n/255,0,0,0,1,0]}function Qk(e){return[(e.red??100)/100,0,0,0,0,0,(e.green??100)/100,0,0,0,0,0,(e.blue??100)/100,0,0,0,0,0,1,0]}function $k(e,t){let n=1-t,r=(e>>16&255)/255,i=(e>>8&255)/255,a=(e&255)/255;return[n,0,0,0,r*t,0,n,0,0,i*t,0,0,n,0,a*t,0,0,0,1,0]}function eA(e){let t=[`R`,`G`,`B`,`A`].map((t,n)=>e[n]??t),n=e=>{switch(e){case`R`:return[1,0,0,0,0];case`G`:return[0,1,0,0,0];case`B`:return[0,0,1,0,0];case`A`:return[0,0,0,1,0];case`0`:return[0,0,0,0,0];case`1`:return[0,0,0,0,1]}};return t.flatMap(e=>n(e))}function tA(e){if(e===void 0)return;let t=e.trim(),n=t.endsWith(`%`),r=Number(n?t.slice(0,-1):t);if(Number.isFinite(r))return n||r>1?r/100:r}function nA(e){if(e===void 0)return;let t=Number.parseInt(e.replace(/^#/,``),16);return Number.isFinite(t)?t:void 0}function rA(e,t,n=1){let r=Xk(t,`FL`);r&&(r.args.length===0||r.args.some(e=>/horiz|horizontal|x/i.test(e)))&&(e.scale.x*=-1),r?.args.some(e=>/vert|vertical|y/i.test(e))&&(e.scale.y*=-1);let i=Xk(t,`SCALE`);if(i){let t=Number(i.args[0]),r=Number(i.args[1]??i.args[0]);Number.isFinite(t)&&t>0&&(e.width=t*n),Number.isFinite(r)&&r>0&&(e.height=r*n)}if(Xk(t,`GS`)){let t=new LD;t.greyscale(1,!1),e.filters=[...e.filters??[],t]}let a=Xk(t,`CS`);if(a){let t=a.args.slice(0,3).map(Number);if(t.length===3&&t.every(e=>Number.isFinite(e))){let n=new LD;n.matrix=Zk(t[0],t[1],t[2]),e.filters=[...e.filters??[],n]}}let o=Xk(t,`R`),s=Xk(t,`G`),c=Xk(t,`B`);if(o||s||c){let t=o?Number(o.args[0]):void 0,n=s?Number(s.args[0]):void 0,r=c?Number(c.args[0]):void 0,i=new LD;i.matrix=Qk({red:Number.isFinite(t)?t:void 0,green:Number.isFinite(n)?n:void 0,blue:Number.isFinite(r)?r:void 0}),e.filters=[...e.filters??[],i]}let l=Xk(t,`CHAN`);if(l&&l.args.length>0){let t=l.args.map(e=>e.trim().toUpperCase()),n=new LD;n.matrix=eA(t),e.filters=[...e.filters??[],n]}let u=Xk(t,`O`);if(u){let t=tA(u.args[0]);t!==void 0&&(e.alpha*=Math.min(1,Math.max(0,t)))}}function iA(e,t){let n=Xk(t,`CROP`);if(!n||n.args.length<4||!e.source)return e;let r=n.args.slice(0,4).map(Number);if(r.some(e=>!Number.isFinite(e))||r[2]<=0||r[3]<=0)return e;let i=Math.max(0,r[0]),a=Math.max(0,r[1]),o=Math.min(r[2],Math.max(0,e.width-i)),s=Math.min(r[3],Math.max(0,e.height-a));return o>0&&s>0?new U({source:e.source,frame:new V(i,a,o,s)}):e}function aA(e,t){let n=e.trim();return nA(n)??t?.(n)}function oA(e,t){let n=[],r=[];for(let i of e){let[e,a]=i.split(`>`);if(e===void 0||a===void 0)continue;let o=aA(e,t),s=aA(a,t);o!==void 0&&s!==void 0&&(n.push(o),r.push(s))}return{from:n,to:r}}function sA(e,t){let n=e.join(`,`),r=n.indexOf(`>`);if(r<0)return{from:[],to:[]};let i=e=>e.split(`,`).map(e=>aA(e,t)).filter(e=>e!==void 0);return{from:i(n.slice(0,r)),to:i(n.slice(r+1))}}function cA(e,t,n={}){let r=e,i=Xk(t,`RC`);if(i&&i.args.length>0){let e=oA(i.args,n.resolveColor);e.from.length>0&&(r=Jk(r,e,n,`exact`))}let a=Xk(t,`PAL`);if(a){let e=sA(a.args,n.resolveColor);e.from.length>0&&e.from.length===e.to.length&&(r=Jk(r,e,n,`exact`))}let o=Xk(t,`BLIT`);if(o&&o.args.length>0&&n.resolveTexture){let e=n.resolveTexture(o.args[0]);if(e){let t=Number(o.args[1]??0)||0,i=Number(o.args[2]??0)||0;r=qk(r,n,n=>{n.drawImage(e.source.resource,t,i)})}}let s=Xk(t,`MASK`);if(s&&s.args.length>0&&n.resolveTexture){let e=n.resolveTexture(s.args[0]);if(e){let t=Number(s.args[1]??0)||0,i=Number(s.args[2]??0)||0;r=qk(r,n,(r,a,o)=>{let s=r.getImageData(0,0,a,o),c=lA(e.width,e.height,n);if(!c)return;let l=c.getContext(`2d`);if(!l)return;l.drawImage(e.source.resource,0,0);let u=l.getImageData(0,0,e.width,e.height),d=uA(s.data,a,o,u.data,e.width,e.height,t,i);r.putImageData({data:d,width:a,height:o},0,0)})}}let c=Xk(t,`BLEND`);if(c){let e=aA(c.args[0]??``,n.resolveColor),t=tA(c.args[1]);e!==void 0&&t!==void 0&&(r=qk(r,n,(n,r,i)=>{let a=dA(n.getImageData(0,0,r,i).data,e,t);n.putImageData({data:a,width:r,height:i},0,0)}))}let l=Xk(t,`ROTATE`);if(l){let e=Number(l.args[0]);if(Number.isFinite(e)&&e%360!=0){let t=r.width,i=r.height;if(t>0&&i>0&&r.source){let a=lA(t,i,n),o=a?.getContext(`2d`);if(a&&o){o.drawImage(r.source.resource,0,0);let a=fA(o.getImageData(0,0,t,i).data,t,i,e),s=lA(a.width,a.height,n),c=s?.getContext(`2d`);s&&c&&(c.putImageData({data:a.data,width:a.width,height:a.height},0,0),r=U.from(s))}}}}return r}function lA(e,t,n){let r=n.createCanvas?.(e,t)??(typeof document>`u`?null:document.createElement(`canvas`));return r?(r.width=e,r.height=t,r):null}function uA(e,t,n,r,i,a,o,s){let c=new Uint8ClampedArray(e.length);for(let l=0;l<n;l+=1)for(let n=0;n<t;n+=1){let u=(l*t+n)*4,d=n-o,f=l-s,p=d>=0&&d<i&&f>=0&&f<a?r[(f*i+d)*4+3]:0;c[u]=e[u],c[u+1]=e[u+1],c[u+2]=e[u+2],c[u+3]=Math.round(e[u+3]*p/255)}return c}function dA(e,t,n){let r=Math.min(1,Math.max(0,n)),i=t>>16&255,a=t>>8&255,o=t&255,s=new Uint8ClampedArray(e.length);for(let t=0;t<e.length;t+=4){let n=e[t+3];if(s[t+3]=n,n===0){s[t]=e[t],s[t+1]=e[t+1],s[t+2]=e[t+2];continue}s[t]=e[t]*(1-r)+i*r,s[t+1]=e[t+1]*(1-r)+a*r,s[t+2]=e[t+2]*(1-r)+o*r}return s}function fA(e,t,n,r){let i=r*Math.PI/180,a=Math.cos(i),o=Math.sin(i),s=t/2,c=n/2,l=0,u=0;for(let[e,t]of[[-s,-c],[s,-c],[s,c],[-s,c]])l=Math.max(l,Math.abs(e*a-t*o)),u=Math.max(u,Math.abs(e*o+t*a));let d=Math.max(1,Math.round(l*2)),f=Math.max(1,Math.round(u*2)),p=new Uint8ClampedArray(d*f*4),m=t/2-.5,h=n/2-.5,g=d/2-.5,_=f/2-.5;for(let r=0;r<f;r+=1)for(let i=0;i<d;i+=1){let s=i-g,c=r-_,l=Math.round(s*a+c*o+m),u=Math.round(-s*o+c*a+h);if(l<0||l>=t||u<0||u>=n)continue;let f=(r*d+i)*4,v=(u*t+l)*4;p[f]=e[v],p[f+1]=e[v+1],p[f+2]=e[v+2],p[f+3]=e[v+3]}return{data:p,width:d,height:f}}var pA=class{constructor(e,{fps:t=10,loop:n=!0,startTime:r=0}={}){if(e.length===0)throw Error(`an animation needs at least one frame`);if(!(t>0))throw Error(`an animation needs a positive fps, got ${t}`);this.frameDuration=1/t,this.frames=e.map(e=>mA(e)?e:{texture:e}),this.times=this.frames.map(e=>e.duration??this.frameDuration),this.loop=n,this.startTime=r;let i=0,a=0;for(let e of this.frames)e.duration===void 0?i++:a+=e.duration;this.duration=i*this.frameDuration+a}frameAt(e){return this.frames[this.frameIndexAt(e)]}frameIndexAt(e){let t=e-this.startTime;if(t<=0)return 0;let n=this.duration;if(n<=0)return this.frames.length-1;let r=this.loop?t%n:Math.min(t,n);for(let e=0;e<this.times.length;e++){if(r<this.times[e])return e;r-=this.times[e]}return this.frames.length-1}};function mA(e){return e.texture!==void 0}var hA=class extends Bk{constructor(...e){super(...e),this.animations=new Map,this.current=null,this.currentName=null,this.elapsed=0,this.finished=!1,this.offset={x:0,y:0},this.onFinish=null,this.paused=!1}add(e,t,n){return this.animations.set(e,new pA(t,n)),this}has(e){return this.animations.has(e)}get playing(){return this.currentName}get isFinished(){return this.finished}get frameOffset(){return this.offset}get elapsedTime(){return this.elapsed}play(e,t=!1){if(!t&&this.currentName===e&&!this.finished)return this;let n=this.animations.get(e);if(!n)throw Error(`no animation named "${e}" on this sprite`);return this.current=n,this.currentName=e,this.elapsed=0,this.finished=!1,this.show(n.frameAt(0)),this}stop(){this.current=null,this.currentName=null}update(e){let t=this.current;!t||this.paused||this.finished||(this.elapsed+=e,this.show(t.frameAt(this.elapsed)),!t.loop&&this.elapsed>=t.startTime+t.duration&&(this.finished=!0,this.onFinish?.(this.currentName)))}show(e){this.texture=e.texture,this.offset.x=e.offsetX??0,this.offset.y=e.offsetY??0}},gA=``;function _A(e){gA=e.endsWith(`/`)||e===``?e:e+`/`}function vA(){return typeof window>`u`?void 0:window.__MWG_ASSETS__}function yA(){return vA()!==void 0}function bA(){return Object.keys(vA()??{})}function xA(e){let t=vA();return!t||e in t}function SA(e){let t=vA();if(!t)return gA+e;let n=t[e];if(n===void 0)throw Error(`asset "${e}" is not in this build - check it is under the folder passed to compile-resources`);return n}async function CA(e,t={}){let{onProgress:n,resolution:r,optional:i,onMissing:a}=typeof t==`function`?{onProgress:t,resolution:void 0,optional:void 0,onMissing:void 0}:t,o=new Set(i??[]),s=e.filter(e=>!ND.cache.has(e)),c=s.filter(e=>!o.has(e)),l=s.filter(e=>o.has(e)),u=e=>{let t={alias:e,src:SA(e)};r!==void 0&&(t.data={resolution:r}),ND.add(t)};if(l.length===0&&c.length===0){n?.(1);return}for(let e of c)u(e);let d=c.length>0?ND.load(c,n):Promise.resolve(),f=l.map(async e=>{u(e);try{await ND.load(e)}catch(t){a?.(e,t)}});await Promise.all([d,...f]),l.length>0&&c.length===0&&n?.(1)}function wA(e,t){if(!ND.cache.has(e)){if(t!==void 0)return t;throw Error(`texture "${e}" has not been loaded - pass it to load() first`)}return ND.get(e)}function TA(e,t){if(!ND.cache.has(e)){if(t!==void 0)return t;throw Error(`asset "${e}" has not been loaded - pass it to load() first`)}return ND.get(e)}function EA(e){return ND.cache.has(e)}async function DA(e){let t=e.filter(e=>ND.cache.has(e));t.length!==0&&await ND.unload(t)}var OA=new Map;async function kA(e,t,n={}){let r=n.fetch??globalThis.fetch;if(!r)throw Error(`fetch is unavailable; provide LoadBinaryOptions.fetch`);let i=e.filter(e=>!OA.has(e));if(i.length===0){t?.(1);return}let a=0;await Promise.all(i.map(async e=>{let n=await r(SA(e));if(!n.ok)throw Error(`failed to load binary asset "${e}": ${n.status}`);OA.set(e,await n.arrayBuffer()),a++,t?.(a/i.length)}))}function AA(e){let t=OA.get(e);if(!t)throw Error(`binary asset "${e}" has not been loaded - pass it to loadBinary() first`);return t}function jA(e){return OA.has(e)}function MA(e){for(let t of e)OA.delete(t)}var NA=class{constructor(e={}){if(this.entries=new Map,this.clock=0,this.budgetBytes=e.budgetBytes??1/0,!(this.budgetBytes>=0))throw Error(`asset stream budget must not be negative`);this.loadAssets=e.load??CA,this.releaseAssets=e.release??DA}async preload(e,t){if(!e.id)throw Error(`asset bundle needs an id`);if(e.estimatedBytes!==void 0&&e.estimatedBytes<0)throw Error(`asset bundle size must not be negative`);let n=this.entries.get(e.id);if(n?.ready){n.lastUsed=++this.clock,t?.(1);return}let r=e.paths.filter(e=>!this.isRetained(e));r.length>0?await this.loadAssets([...r],t):t?.(1),this.entries.set(e.id,{...e,lastUsed:++this.clock,ready:!0}),await this.enforceBudget(e.id)}async preloadLikely(e,t){let n=[...e].sort((e,t)=>(t.priority??0)-(e.priority??0));for(let[e,r]of n.entries())await this.preload(r,t&&(r=>t((e+r)/n.length)));t?.(1)}use(e){let t=this.entries.get(e);return t?.ready?(t.lastUsed=++this.clock,!0):!1}isReady(e){return this.entries.get(e)?.ready??!1}async unload(e){let t=this.entries.get(e);if(!t)return;this.entries.delete(e);let n=t.paths.filter(e=>!this.isRetained(e));n.length>0&&await this.releaseAssets(n)}get estimatedBytes(){return[...this.entries.values()].reduce((e,t)=>e+(t.estimatedBytes??0),0)}async enforceBudget(e){for(;this.estimatedBytes>this.budgetBytes;){let t=[...this.entries.values()].filter(t=>t.id!==e).sort((e,t)=>e.lastUsed-t.lastUsed)[0];if(!t)return;await this.unload(t.id)}}isRetained(e){return[...this.entries.values()].some(t=>t.ready&&t.paths.includes(e))}};async function PA(e,t,n=fetch){let r=await n(e);if(!r.ok)throw Error(`fetchWithByteProgress: ${e} responded ${r.status}`);let i=r.headers.get(`content-length`),a=i!==null&&i!==``?Number(i):null;if(!r.body){let e=await r.blob();return t?.({loaded:e.size,total:a??e.size}),e}let o=r.body.getReader(),s=[],c=0;for(;;){let{done:e,value:n}=await o.read();if(e)break;s.push(n),c+=n.byteLength,t?.({loaded:c,total:a})}return new Blob(s)}var FA=l({AssetStream:()=>NA,fetchWithByteProgress:()=>PA,get:()=>TA,getBinary:()=>AA,has:()=>xA,isBinaryLoaded:()=>jA,isCompiled:()=>yA,isLoaded:()=>EA,load:()=>CA,loadBinary:()=>kA,paths:()=>bA,release:()=>DA,releaseBinary:()=>MA,resolve:()=>SA,setBase:()=>_A,texture:()=>wA});function IA(e){return{x:e.x,y:e.y,width:e.width,height:e.height}}var LA=class e{constructor(e,t,n){this.frames=new Map,this.names=new Map,this.texture=e,this.frameWidth=t,this.frameHeight=n,this.columns=Math.floor(e.width/t),this.rows=Math.floor(e.height/n)}static grid(t,n,r=n){return new e(wA(t),n,r)}static fromTexture(t,n,r=n){return new e(t,n,r)}get count(){return this.columns*this.rows}name(e,t){return this.names.set(e,t),this}nameAll(e){for(let[t,n]of Object.entries(e))this.names.set(t,n);return this}indexOf(e){let t=this.names.get(e);if(t===void 0)throw Error(`this sheet has no frame named "${e}"`);return t}get(e){let t=typeof e==`string`?this.indexOf(e):e,n=this.frames.get(t);if(n)return n;if(t<0||t>=this.count)throw Error(`frame ${t} is outside this sheet, which holds ${this.count}`);let r=new U({source:this.texture.source,frame:new V(t%this.columns*this.frameWidth,Math.floor(t/this.columns)*this.frameHeight,this.frameWidth,this.frameHeight)});return this.frames.set(t,r),r}region(e){let t=this.get(e);return{texture:t,frame:IA(t.frame)}}range(e,t){let n=[];for(let r=e;r<=t;r++)n.push(this.get(r));return n}pick(...e){return e.map(e=>this.get(e))}},RA=class{constructor(e={}){if(this.world=new G,this.x=0,this.y=0,this.viewWidth=0,this.viewHeight=0,this.screenX=0,this.screenY=0,this.followTarget=null,this.followIntensity=0,this.shakeMagnitude=0,this.shakeRemaining=0,this.shakeDuration=1,this.shakeX=0,this.shakeY=0,this.bounds=null,this.step=0,this._angle=0,this.targetAngle=null,this.angleIntensity=0,e.grid!==void 0&&e.grid!==`square`&&e.grid!==`hex`)throw Error(`camera grid must be "square" or "hex", not "${e.grid}"`);this.stepsPerTurn=e.grid===`hex`?6:4,this.deadzone=e.deadzone??0,this.pixelPerfectTileSize=e.pixelPerfectTileSize,this._zoom=1,this.zoom=e.zoom??1}get rotationSteps(){return this.step}get rotation(){return this._angle}get uprightRotation(){return-this.rotation}setRotationStep(e){if(!Number.isInteger(e))throw Error(`camera rotation step must be an integer`);this.step=(e%this.stepsPerTurn+this.stepsPerTurn)%this.stepsPerTurn,this._angle=this.step/this.stepsPerTurn*Math.PI*2,this.targetAngle=null,this.apply()}rotate(e=1){this.setRotationStep(this.step+e)}rotateTo(e){this._angle=e,this.targetAngle=null,this.angleIntensity=0,this.apply()}animateRotationTo(e,t=4){this.targetAngle=e,this.angleIntensity=t}get spin(){let e=this.rotation;return{cos:Math.cos(e),sin:Math.sin(e)}}get zoom(){return this._zoom}set zoom(e){let t=Math.max(.01,e);this._zoom=this.pixelPerfectTileSize?VA(t,this.pixelPerfectTileSize):t}setViewport(e,t,n=0,r=0){this.viewWidth=e,this.viewHeight=t,this.screenX=n,this.screenY=r}get view(){let e=this.viewWidth/this._zoom,t=this.viewHeight/this._zoom,{x:n,y:r}=this.clampedCentre(this.x,this.y);if(this._angle===0)return{x:n-e/2,y:r-t/2,width:e,height:t};let i=[this.toWorld(this.screenX,this.screenY),this.toWorld(this.screenX+this.viewWidth,this.screenY),this.toWorld(this.screenX+this.viewWidth,this.screenY+this.viewHeight),this.toWorld(this.screenX,this.screenY+this.viewHeight)],a=i.map(e=>e.x),o=i.map(e=>e.y),s=Math.min(...a),c=Math.min(...o);return{x:s,y:c,width:Math.max(...a)-s,height:Math.max(...o)-c}}setBounds(e){this.bounds=e}snapTo(e,t){this.x=e,this.y=t,this.followTarget=null,this.followIntensity=0,this.apply()}panTo(e,t,n=4){this.followTarget={x:e,y:t},this.followIntensity=n}follow(e,t=8){this.followTarget=e,this.followIntensity=t}stopFollowing(){this.followTarget=null,this.followIntensity=0}shake(e,t=.4){xn()||(this.shakeMagnitude=e,this.shakeRemaining=this.shakeDuration=t)}update(e){if(this.followTarget&&this.followIntensity>0){let t=this.viewWidth/this._zoom*this.deadzone/2,n=this.viewHeight/this._zoom*this.deadzone/2,r=this.followTarget.x-this.x,i=this.followTarget.y-this.y;r=r>t?r-t:r<-t?r+t:0,i=i>n?i-n:i<-n?i+n:0;let a=xn()?1:1-Math.exp(-this.followIntensity*e);this.x+=r*a,this.y+=i*a}if(this.targetAngle!==null&&this.angleIntensity>0){let t=BA(this._angle,this.targetAngle),n=xn()?1:1-Math.exp(-this.angleIntensity*e);this._angle+=t*n}if(this.shakeRemaining>0){this.shakeRemaining-=e;let t=Math.max(0,this.shakeRemaining/this.shakeDuration);this.shakeX=O(-this.shakeMagnitude,this.shakeMagnitude)*t,this.shakeY=O(-this.shakeMagnitude,this.shakeMagnitude)*t}else this.shakeX=this.shakeY=0;this.apply()}toScreen(e,t){let{x:n,y:r}=this.clampedCentre(this.x+this.shakeX,this.y+this.shakeY),{cos:i,sin:a}=this.spin,o=e-n,s=t-r;return{x:(o*i-s*a)*this._zoom+this.screenX+this.viewWidth/2,y:(o*a+s*i)*this._zoom+this.screenY+this.viewHeight/2}}toWorld(e,t){let{x:n,y:r}=this.clampedCentre(this.x+this.shakeX,this.y+this.shakeY),{cos:i,sin:a}=this.spin,o=(e-this.screenX-this.viewWidth/2)/this._zoom,s=(t-this.screenY-this.viewHeight/2)/this._zoom;return{x:n+o*i+s*a,y:r-o*a+s*i}}clampedCentre(e,t){if(!this.bounds)return{x:e,y:t};let n=this.viewWidth/this._zoom/2,r=this.viewHeight/this._zoom/2,{minX:i,minY:a,maxX:o,maxY:s}=this.bounds;return{x:o-i<n*2?(i+o)/2:zA(e,i+n,o-n),y:s-a<r*2?(a+s)/2:zA(t,a+r,s-r)}}apply(){let{x:e,y:t}=this.clampedCentre(this.x+this.shakeX,this.y+this.shakeY);if(this.world.scale.set(this._zoom),this._angle===0){this.world.rotation=0,this.world.pivot.set(0,0),this.world.x=Math.round(this.screenX+this.viewWidth/2-e*this._zoom),this.world.y=Math.round(this.screenY+this.viewHeight/2-t*this._zoom);return}this.world.rotation=this.rotation,this.world.pivot.set(e,t),this.world.x=Math.round(this.screenX+this.viewWidth/2),this.world.y=Math.round(this.screenY+this.viewHeight/2)}};function zA(e,t,n){return e<t?t:e>n?n:e}function BA(e,t){let n=Math.PI*2,r=(t-e)%n;return r>Math.PI&&(r-=n),r<-Math.PI&&(r+=n),r}function VA(e,t){return Math.max(1,Math.round(e*t))/t}function HA(e={}){let t=new RA(e),n=yk.current;return t.setViewport(n.width,n.height),t}var UA=class{constructor(e){this.container=new G,this.clip=new Sw,this.camera=new RA(e),this.container.addChild(this.camera.world),this.container.addChild(this.clip),this.container.mask=this.clip,this.resize(e.x,e.y,e.width,e.height)}resize(e,t,n,r){this.camera.setViewport(n,r,e,t),this.clip.clear().rect(e,t,n,r).fill(16777215)}update(e){this.camera.update(e)}};function WA(e,t){if(e>=t){let n=Math.floor(e/2);return[{x:0,y:0,width:n,height:t},{x:n,y:0,width:e-n,height:t}]}let n=Math.floor(t/2);return[{x:0,y:0,width:e,height:n},{x:0,y:n,width:e,height:t-n}]}var GA={protanopia:[.567,.433,0,0,0,.558,.442,0,0,0,0,.242,.758,0,0,0,0,0,1,0],deuteranopia:[.625,.375,0,0,0,.7,.3,0,0,0,0,.3,.7,0,0,0,0,0,1,0],tritanopia:[.95,.05,0,0,0,0,.433,.567,0,0,0,.475,.525,0,0,0,0,0,1,0]};function KA(e){let t=new LD;return t.matrix=GA[e],t}function qA(e,t){let n=[];for(let r of e)t.has(r)||n.push(r);return n}function JA(e,t,n,r=`square`){return r===`hex`?pn(e,t,n,n):{x:(e+.5)*n,y:(t+.5)*n}}var YA=class extends G{constructor(e){super(),this.drawn=new Set,this.marker=new Sw,this.widthInCells=e.widthInCells,this.cellSize=e.cellSize??2,this.shape=e.shape??`square`,this.renderTexture=Nh.create({width:this.shape===`hex`?Math.ceil((e.widthInCells-1)*this.cellSize*.75+this.cellSize):e.widthInCells*this.cellSize,height:this.shape===`hex`?e.heightInCells*this.cellSize+this.cellSize/2:e.heightInCells*this.cellSize}),this.sprite=new $s(this.renderTexture),this.addChild(this.sprite),this.addChild(this.marker)}get exploredCount(){return this.drawn.size}sync(e,t){let n=qA(e,this.drawn);if(n.length===0)return;let r=new Sw;for(let e of n){this.drawn.add(e);let n=e%this.widthInCells,i=Math.floor(e/this.widthInCells),a=JA(n,i,this.cellSize,this.shape);if(this.shape===`hex`){let e=this.cellSize/2,o=[];for(let t=0;t<6;t++){let n=Math.PI/3*t;o.push(a.x+Math.cos(n)*e,a.y+Math.sin(n)*e)}r.poly(o).fill({color:t(n,i)})}else r.rect(a.x-this.cellSize/2,a.y-this.cellSize/2,this.cellSize,this.cellSize).fill({color:t(n,i)})}yk.current.app.renderer.render({container:r,target:this.renderTexture,clear:!1}),r.destroy()}setMarker(e,t,n,r=16777215){this.setMarkers([{x:e,y:t,facing:n,color:r}])}setMarkers(e){this.marker.clear();for(let t of e){let e=t.color??16777215,n=JA(t.x,t.y,this.cellSize,this.shape);if(this.marker.circle(n.x,n.y,Math.max(1,this.cellSize)).fill({color:e}),t.facing!==void 0){let r=this.cellSize*2;this.marker.moveTo(n.x,n.y).lineTo(n.x+Math.cos(t.facing)*r,n.y+Math.sin(t.facing)*r).stroke({color:e,width:1})}}}reset(){this.drawn.clear(),yk.current.app.renderer.render({container:new G,target:this.renderTexture,clear:!0})}destroy(e){this.renderTexture.destroy(!0),super.destroy(e)}},XA=-1,ZA=7237230,QA=10132122;function $A(e,t){if(!Number.isInteger(e)||e<0||e>=4096)throw Error(`tileFrame needs a sheet index from 0 to 4095, got ${e}`);if(!Number.isInteger(t)||t<0||t>=1<<20)throw Error(`tileFrame needs a frame index from 0 to ${(1<<20)-1}, got ${t}`);return e<<20|t}function ej(e){return e>>>20}function tj(e){return e&(1<<20)-1}var nj=class extends G{constructor(e){if(super(),this.layers=[],this.layersByName=new Map,this.chunks=[],this.widthInTiles=e.width,this.heightInTiles=e.height,this.sheets=Array.isArray(e.sheet)?[...e.sheet]:[e.sheet],this.sheets.length===0)throw Error(`a TileMap needs at least one sheet`);if(this.tileWidth=e.tileWidth??this.sheets[0].frameWidth,this.tileHeight=e.tileHeight??this.sheets[0].frameHeight,this.shape=e.shape??`square`,this.heightStep=e.heightStep??this.tileHeight/2,!(this.heightStep>0))throw Error(`a TileMap's heightStep must be a positive number, got ${e.heightStep}`);this.chunkSize=e.chunkSize??16,this.chunkColumns=Math.ceil(this.widthInTiles/this.chunkSize),this.chunkRows=Math.ceil(this.heightInTiles/this.chunkSize);let t=this.widthInTiles*this.heightInTiles;this.cellTint=new Uint32Array(t).fill(16777215),this.cellAdd=new Uint32Array(t),this.cellHeight=new Int32Array(t),this.faces=Array(t).fill(null)}get layerCount(){return this.layers.length}get worldWidth(){switch(this.shape){case`square`:return this.widthInTiles*this.tileWidth;case`hex`:return this.widthInTiles<=0?0:(this.widthInTiles-1)*this.tileWidth*.75+this.tileWidth;case`isometric`:return(this.widthInTiles+this.heightInTiles)*(this.tileWidth/2);case`staggered`:return this.widthInTiles*this.tileWidth+this.tileWidth/2}}get worldHeight(){switch(this.shape){case`square`:return this.heightInTiles*this.tileHeight;case`hex`:return this.heightInTiles*this.tileHeight+this.tileHeight/2;case`isometric`:return(this.widthInTiles+this.heightInTiles)*(this.tileHeight/2);case`staggered`:return this.heightInTiles*(this.tileHeight/2)+this.tileHeight/2}}inside(e,t){return e>=0&&t>=0&&e<this.widthInTiles&&t<this.heightInTiles}index(e,t){return t*this.widthInTiles+e}addLayer(e,t){if(this.layersByName.has(e))throw Error(`this map already has a layer named "${e}"`);let n=this.widthInTiles*this.heightInTiles;if(t&&t.length!==n)throw Error(`layer "${e}" has ${t.length} cells, but the map has ${n}`);let r=new G,i=[];for(let e=0;e<this.chunkColumns*this.chunkRows;e++){let e=new G;i.push(e),r.addChild(e)}let a={name:e,data:t?Int32Array.from(t):new Int32Array(n).fill(-1),sprites:Array(n).fill(null),container:r};this.layers.push(a),this.layersByName.set(e,a),this.chunks.push(i),this.addChild(r);let o=this.layers.length===1;for(let e=0;e<this.heightInTiles;e++)for(let t=0;t<this.widthInTiles;t++){let n=a.data[this.index(t,e)];n!==-1&&this.buildSprite(a,t,e,n),o&&this.syncFaces(t,e)}return this}layerAt(e){let t=typeof e==`number`?this.layers[e]:this.layersByName.get(e);if(!t)throw Error(`no such layer: ${e}`);return t}chunkIndex(e,t){return Math.floor(t/this.chunkSize)*this.chunkColumns+Math.floor(e/this.chunkSize)}projectedCenter(e,t){switch(this.shape){case`square`:return{x:(e+.5)*this.tileWidth,y:(t+.5)*this.tileHeight};case`hex`:return pn(e,t,this.tileWidth,this.tileHeight);case`isometric`:return{x:(e-t+(this.heightInTiles-1))*(this.tileWidth/2)+this.tileWidth/2,y:(e+t)*(this.tileHeight/2)+this.tileHeight/2};case`staggered`:return{x:e*this.tileWidth+(t&1)*(this.tileWidth/2)+this.tileWidth/2,y:t*(this.tileHeight/2)+this.tileHeight/2}}}projectedTile(e,t){switch(this.shape){case`square`:return{x:Math.floor(e/this.tileWidth),y:Math.floor(t/this.tileHeight)};case`hex`:return mn(e,t,this.tileWidth,this.tileHeight);case`isometric`:{let n=(e-this.tileWidth/2)/(this.tileWidth/2)-(this.heightInTiles-1),r=(t-this.tileHeight/2)/(this.tileHeight/2);return{x:Math.round((n+r)/2),y:Math.round((r-n)/2)}}case`staggered`:{let n=Math.round((t-this.tileHeight/2)/(this.tileHeight/2));return{x:Math.round((e-this.tileWidth/2-(n&1)*(this.tileWidth/2))/this.tileWidth),y:n}}}}cellOrigin(e,t){let n=this.projectedCenter(e,t);return{x:n.x-this.tileWidth/2,y:n.y-this.tileHeight/2}}textureFor(e){let t=ej(e);if(t>=this.sheets.length)throw Error(`frame ${e} names sheet ${t}, but this map has ${this.sheets.length}`);return this.sheets[t].get(tj(e))}buildSprite(e,t,n,r){let i=new Bk(this.textureFor(r)),a=this.cellOrigin(t,n);i.x=a.x,i.y=a.y-this.cellHeight[this.index(t,n)]*this.heightStep;let o=this.index(t,n);return i.tint=this.cellTint[o],i.colorAdd=this.cellAdd[o],e.sprites[o]=i,this.chunks[this.layers.indexOf(e)][this.chunkIndex(t,n)].addChild(i),i}getTile(e,t,n){return this.inside(t,n)?this.layerAt(e).data[this.index(t,n)]:-1}setTile(e,t,n,r){if(!this.inside(t,n))return;let i=this.layerAt(e),a=this.index(t,n);if(i.data[a]===r)return;i.data[a]=r;let o=i.sprites[a];r===-1?(o?.destroy(),i.sprites[a]=null):o?o.texture=this.textureFor(r):this.buildSprite(i,t,n,r),this.layers[0]===i&&this.syncFaces(t,n)}setLayerData(e,t){this.layerAt(e);for(let n=0;n<this.heightInTiles;n++)for(let r=0;r<this.widthInTiles;r++)this.setTile(e,r,n,t[this.index(r,n)]??-1)}setCellColor(e,t,n,r=0){if(!this.inside(e,t))return;let i=this.index(e,t);if(this.cellTint[i]===n&&this.cellAdd[i]===r)return;this.cellTint[i]=n,this.cellAdd[i]=r;for(let e of this.layers){let t=e.sprites[i];t&&(t.tint=n,t.colorAdd=r)}let a=this.faces[i];a&&(a.tint=n)}getCellTint(e,t){return this.inside(e,t)?this.cellTint[this.index(e,t)]:0}clearColors(){for(let e=0;e<this.heightInTiles;e++)for(let t=0;t<this.widthInTiles;t++)this.setCellColor(t,e,16777215,0)}setCellHeight(e,t,n){if(!this.inside(e,t))return;if(!Number.isInteger(n))throw Error(`a cell's height must be a whole number, got ${n}`);let r=this.index(e,t);if(this.cellHeight[r]===n)return;this.cellHeight[r]=n;let i=n*this.heightStep;for(let n of this.layers){let a=n.sprites[r];a&&(a.y=this.cellOrigin(e,t).y-i)}this.syncFaces(e,t)}getCellHeight(e,t){return this.inside(e,t)?this.cellHeight[this.index(e,t)]:0}get faceCount(){return this.faces.filter(e=>e!==null).length}syncFaces(e,t){if(this.layers.length===0)return;let n=this.index(e,t),r=(this.shape===`isometric`||this.shape===`staggered`)&&this.cellHeight[n]>0&&this.layers[0].data[n]!==-1,i=this.faces[n];if(!r){i&&(i.destroy(),this.faces[n]=null);return}let a=i??new Sw;if(this.drawFaces(a,e,t),a.tint=this.cellTint[n],!i){this.faces[n]=a;let r=this.chunks[0][this.chunkIndex(e,t)],i=this.layers[0].sprites[n];i?r.addChildAt(a,r.getChildIndex(i)):r.addChild(a)}}drawFaces(e,t,n){let r=this.cellOrigin(t,n),i=r.x,a=r.y,o=this.tileWidth/2,s=this.tileHeight/2,c=this.heightStep,l=this.cellHeight[this.index(t,n)];e.clear();for(let t=1;t<=l;t++){let n=t*c,r=(t-1)*c;e.poly([i,a+s-n,i+o,a+s*2-n,i+o,a+s*2-r,i,a+s-r]).fill(ZA),e.poly([i+o,a+s*2-n,i+o*2,a+s-n,i+o*2,a+s-r,i+o,a+s*2-r]).fill(QA)}}toTile(e,t){return this.projectedTile(e,t)}tileCenter(e,t){let n=this.projectedCenter(e,t);return n.y-=this.getCellHeight(e,t)*this.heightStep,n}cull(e){let t=e.view,n=this.projectedTile(t.x,t.y),r=this.projectedTile(t.x+t.width,t.y),i=this.projectedTile(t.x,t.y+t.height),a=this.projectedTile(t.x+t.width,t.y+t.height),o=Math.min(n.x,r.x,i.x,a.x),s=Math.max(n.x,r.x,i.x,a.x),c=Math.min(n.y,r.y,i.y,a.y),l=Math.max(n.y,r.y,i.y,a.y),u=Math.floor(o/this.chunkSize)-1,d=Math.floor(s/this.chunkSize)+1,f=Math.floor(c/this.chunkSize)-1,p=Math.floor(l/this.chunkSize)+1;for(let e=0;e<this.chunkRows;e++){let t=e>=f&&e<=p;for(let n=0;n<this.chunkColumns;n++){let r=t&&n>=u&&n<=d,i=e*this.chunkColumns+n;for(let e of this.chunks)e[i].renderable=r}}}get visibleChunks(){return this.chunks.length===0?0:this.chunks[0].filter(e=>e.renderable).length}},rj=class extends G{constructor(...e){super(...e),this.layers=new Map}addLayer(e,t,n=0){this.removeLayer(e);let r=new Bk(t);return this.layers.set(e,{sprite:r,order:n}),this.addChild(r),this.resort(),r}removeLayer(e){let t=this.layers.get(e);t&&(this.layers.delete(e),t.sprite.destroy())}layer(e){return this.layers.get(e)?.sprite}hasLayer(e){return this.layers.has(e)}setTexture(e,t){let n=this.layers.get(e);n&&(n.sprite.texture=t)}resort(){[...this.layers.values()].sort((e,t)=>e.order-t.order).forEach((e,t)=>this.setChildIndex(e.sprite,t))}},ij=class{constructor(e,t,n,r={}){this.elapsed=0,this.arrived=!1,this.sprite=e,this.fromX=t.x,this.fromY=t.y,this.toX=n.x,this.toY=n.y;let i=Math.hypot(n.x-t.x,n.y-t.y);this.duration=r.duration??i/(r.speed??400),this.duration<=0&&(this.duration=1e-6),e.x=t.x,e.y=t.y}get done(){return this.arrived}get progress(){return Math.min(1,this.elapsed/this.duration)}update(e){if(this.arrived)return!1;this.elapsed+=e;let t=this.progress;return this.sprite.x=this.fromX+(this.toX-this.fromX)*t,this.sprite.y=this.fromY+(this.toY-this.fromY)*t,t>=1&&(this.arrived=!0,!0)}},aj=class{constructor(e,t,n={}){this.elapsed=0,this.sinceFlicker=0,this.expired=!1,this.current=[],this.from={...e},this.to={...t},this.segments=Math.max(0,Math.floor(n.segments??6)),this.jitter=n.jitter??12,this.flickerInterval=n.flickerInterval,this.random=n.random??Math.random,this.duration=n.duration,this.reroll()}get points(){return this.current}get done(){return this.expired}retarget(e,t){e&&(this.from={...e}),t&&(this.to={...t}),this.flickerInterval===void 0&&this.reroll()}update(e){return!this.expired&&(this.elapsed+=e,this.flickerInterval!==void 0&&(this.sinceFlicker+=e,this.sinceFlicker>=this.flickerInterval&&(this.sinceFlicker=0,this.reroll())),this.duration!==void 0&&this.elapsed>=this.duration&&(this.expired=!0,!0))}reroll(){let e=this.to.x-this.from.x,t=this.to.y-this.from.y,n=Math.hypot(e,t),r=n>0?-t/n:0,i=n>0?e/n:0,a=[{...this.from}],o=this.segments+1;for(let n=1;n<o;n+=1){let s=n/o,c=Math.sin(Math.PI*s),l=(this.random()*2-1)*this.jitter*c;a.push({x:this.from.x+e*s+r*l,y:this.from.y+t*s+i*l})}a.push({...this.to}),this.current=a}},oj=class{constructor(e,t={}){this.elapsed=0,this.expired=!1,this.child=e,this.offsetX=t.offsetX??0,this.offsetY=t.offsetY??0,this.duration=t.duration}get done(){return this.expired}follow(e,t){return this.child.x=e+this.offsetX,this.child.y=t+this.offsetY,this}update(e){return this.expired||this.duration===void 0?!1:(this.elapsed+=e,this.elapsed>=this.duration&&(this.expired=!0,!0))}},sj=`halo`,cj=class extends hA{constructor(e){super(),this.offsetX=e.offsetX??0,this.offsetY=e.offsetY??0,this.blendMode=e.blendMode??`add`,this.add(sj,e.frames,e.animation),this.play(sj)}follow(e,t){return this.position.set(e+this.offsetX,t+this.offsetY),this}};function lj(e){return typeof e==`number`?e:O(e[0],e[1])}var uj=class extends G{constructor(e={}){super(),this.pool=[],this.sprites=[],this.emitting=!1,this.poolCursor=0,this.debt=0;let t=Math.max(1,Math.floor(e.max??200));this.rate=e.rate??0,this.life=e.life??[.4,.9],this.speed=e.speed??[20,60],this.angleRange=e.angle??[0,Math.PI*2],this.gravityX=e.gravity?.x??0,this.gravityY=e.gravity?.y??0,this.scaleRange=e.scale??[1,1],this.alphaRange=e.alpha??[1,0],this.spin=e.spin??0,this.frames=e.frames,this.spawnArea=e.spawn??null;for(let n=0;n<t;n++){this.pool.push({x:0,y:0,vx:0,vy:0,age:0,life:0,rotation:0,spin:0,scale:1,alpha:1,frame:0,active:!1});let t=this.frames?.[0]??e.texture;if(t){let n=new $s(t);n.anchor.set(.5),n.visible=!1,e.tint!==void 0&&(n.tint=e.tint),this.sprites.push(n),this.addChild(n)}}}start(){this.emitting=!0}stop(){this.emitting=!1,this.debt=0}get isEmitting(){return this.emitting}get activeCount(){let e=0;for(let t of this.pool)t.active&&e++;return e}get particles(){return this.pool}burst(e){let t=0;for(let n=0;n<e&&this.spawn();n++)t++;return t}spawn(){let e=null;for(let t=0;t<this.pool.length;t++){let t=this.pool[this.poolCursor];if(this.poolCursor=(this.poolCursor+1)%this.pool.length,!t.active){e=t;break}}if(!e)return!1;let t=lj(this.angleRange),n=lj(this.speed),r=+!xn(),i=this.spawnOffset();return e.x=this.x+i.x,e.y=this.y+i.y,e.vx=Math.cos(t)*n*r,e.vy=Math.sin(t)*n*r,e.age=0,e.life=Math.max(1e-6,lj(this.life)),e.rotation=0,e.spin=lj(this.spin)*r,e.scale=this.scaleRange[0],e.alpha=this.alphaRange[0],e.frame=0,e.active=!0,!0}spawnOffset(){let e=this.spawnArea;if(!e)return{x:0,y:0};let t=e.height??e.width;if(e.shape===`rect`)return{x:(O()-.5)*e.width,y:(O()-.5)*t};let n=Math.sqrt(O()),r=O()*Math.PI*2;return{x:Math.cos(r)*n*(e.width/2),y:Math.sin(r)*n*(t/2)}}update(e){if(this.emitting&&this.rate>0){for(this.debt+=this.rate*e;this.debt>=1;)if(--this.debt,!this.spawn()){this.debt=0;break}}let t=xn();for(let n of this.pool){if(!n.active)continue;if(n.age+=e,n.age>=n.life){n.active=!1;continue}t?(n.vx=0,n.vy=0,n.spin=0):(n.vx+=this.gravityX*e,n.vy+=this.gravityY*e),n.x+=n.vx*e,n.y+=n.vy*e,n.rotation+=n.spin*e;let r=n.age/n.life;n.scale=this.scaleRange[0]+(this.scaleRange[1]-this.scaleRange[0])*r,n.alpha=this.alphaRange[0]+(this.alphaRange[1]-this.alphaRange[0])*r,this.frames&&(n.frame=Math.min(this.frames.length-1,Math.floor(r*this.frames.length)))}this.draw()}draw(){if(this.sprites.length!==0)for(let e=0;e<this.pool.length;e++){let t=this.pool[e],n=this.sprites[e];n.visible=t.active,t.active&&(n.x=t.x-this.x,n.y=t.y-this.y,n.rotation=t.rotation,n.alpha=t.alpha,n.scale.set(t.scale),this.frames&&(n.texture=this.frames[t.frame]??n.texture))}}clear(){for(let e of this.pool)e.active=!1;this.debt=0,this.draw()}},dj=class extends G{constructor(e={}){super(),this.overlay=new Sw,this.phase=`idle`,this.elapsed=0,this.duration=0,this.fromAlpha=0,this.toAlpha=0,this.defaultColor=e.color??0,this.viewWidth=e.width??0,this.viewHeight=e.height??0,this.overlay.alpha=0,this.overlay.tint=this.defaultColor,this.addChild(this.overlay),this.redraw()}setViewport(e,t){this.viewWidth=e,this.viewHeight=t,this.redraw()}redraw(){this.overlay.clear(),this.viewWidth>0&&this.viewHeight>0&&this.overlay.rect(0,0,this.viewWidth,this.viewHeight).fill({color:16777215})}get isBusy(){return this.phase!==`idle`}get washAlpha(){return this.overlay.alpha}fadeOut(e,t){this.begin(`fadeOut`,e,this.overlay.alpha,1,t)}fadeIn(e,t){this.begin(`fadeIn`,e,this.overlay.alpha,0,t)}flash(e,t,n=1){this.begin(`flash`,e,0,n,t)}setTint(e,t){this.phase=`idle`,this.elapsed=0,this.overlay.tint=e,this.overlay.alpha=Math.max(0,Math.min(1,t))}clear(){this.phase=`idle`,this.elapsed=0,this.overlay.alpha=0,this.overlay.tint=this.defaultColor}begin(e,t,n,r,i){if(xn()&&(t=0),this.overlay.tint=i??this.defaultColor,this.fromAlpha=n,this.toAlpha=r,this.elapsed=0,this.duration=t,!(t>0)){this.overlay.alpha=e===`flash`?0:r,this.phase=`idle`;return}this.phase=e,this.overlay.alpha=e===`flash`?0:n}update(e){if(this.phase===`idle`)return!1;if(xn())return this.overlay.alpha=this.phase===`flash`?0:this.toAlpha,this.phase=`idle`,!0;this.elapsed+=e;let t=Math.min(1,this.elapsed/this.duration);if(this.phase===`flash`){let e=t<.5?Dn.easeOutQuad(t*2):1-Dn.easeInQuad((t-.5)*2);this.overlay.alpha=this.toAlpha*e}else{let e=Dn.easeInOutQuad(t);this.overlay.alpha=this.fromAlpha+(this.toAlpha-this.fromAlpha)*e}return t>=1&&(this.overlay.alpha=this.phase===`flash`?0:this.toAlpha,this.phase=`idle`,!0)}},fj=class{constructor(e,t){this.idleOrMove=`idle`,this.inAction=!1,this.sprite=e,this.animationName=t.animationName,this.variant=t.variant??``,this.sprite.onFinish=()=>this.onSpriteFinish(),this.apply(this.idleOrMove)}get state(){return this.inAction?`action`:this.idleOrMove}get variantName(){return this.variant}setMoving(e,t){t!==void 0&&(this.variant=t),this.idleOrMove=e?`move`:`idle`,this.inAction||this.apply(this.idleOrMove)}playAction(e,t=!1){this.inAction&&!t||(e!==void 0&&(this.variant=e),this.inAction=!0,this.apply(`action`))}onSpriteFinish(){this.inAction&&(this.inAction=!1,this.apply(this.idleOrMove))}apply(e){let t=this.animationName(e,this.variant);this.sprite.has(t)&&this.sprite.play(t,e===`action`)}},pj=class{constructor(e,t){this.active=new Set,this.elapsed=0,this.target=e,this.styles=t.styles,this.priority=Object.keys(t.styles)}set(e,t){t?this.active.add(e):this.active.delete(e)}has(e){return this.active.has(e)}update(e){this.elapsed+=e;let t=this.priority.find(e=>this.active.has(e));if(t===void 0){this.target.resetColor();return}let n=this.styles[t],r=n.strength??.5,i=n.pulseRate?r*(.5+.5*Math.sin(this.elapsed*n.pulseRate*Math.PI*2)):r;this.target.lerpTint(n.color,i)}},mj=_j(),hj=new Map(mj.map((e,t)=>[gj(e),t]));function gj(e){let t=e.ne&&e.n&&e.e,n=e.se&&e.s&&e.e,r=e.sw&&e.s&&e.w,i=e.nw&&e.n&&e.w;return+!!e.n|(e.e?2:0)|(e.s?4:0)|(e.w?8:0)|(t?16:0)|(n?32:0)|(r?64:0)|(i?128:0)}function _j(){let e=new Set,t=[];for(let n=0;n<256;n++){let r={n:!!(n&1),e:!!(n&2),s:!!(n&4),w:!!(n&8),ne:!!(n&16),se:!!(n&32),sw:!!(n&64),nw:!!(n&128)},i=gj(r);e.has(i)||(e.add(i),t.push({mask:i,shape:{n:r.n,e:r.e,s:r.s,w:r.w,ne:r.ne&&r.n&&r.e,se:r.se&&r.s&&r.e,sw:r.sw&&r.s&&r.w,nw:r.nw&&r.n&&r.w}}))}return t.sort((e,t)=>e.mask-t.mask),t.map(e=>e.shape)}function vj(e){return hj.get(gj(e))}function yj(e,t,n,r){if(r.length!==mj.length)throw Error(`autotileFrames needs exactly ${mj.length} frames, got ${r.length}`);let i=new Int32Array(e*t);for(let a=0;a<t;a++)for(let t=0;t<e;t++){let o=a*e+t;if(!n(t,a)){i[o]=-1;continue}i[o]=r[vj({n:n(t,a-1),e:n(t+1,a),s:n(t,a+1),w:n(t-1,a),ne:n(t+1,a-1),se:n(t+1,a+1),sw:n(t-1,a+1),nw:n(t-1,a-1)})]}return i}function bj(e,t,n,r){let i=n*4/r,a=e,o=t;for(let e=0;e<i;e+=1)[a,o]=[-o,a];return{dx:a||0,dy:o||0}}function xj(e,t,n,r){let i=n*6/r,a=e,o=t;for(let e=0;e<i;e+=1){let e=-a-o;[a,o]=[-o,-e]}return{dx:a||0,dy:o||0}}function Sj(e,t){let n=t??new Set;return!(e.hasAll&&!e.hasAll.every(e=>n.has(e))||e.hasAny&&!e.hasAny.some(e=>n.has(e))||e.hasNone&&e.hasNone.some(e=>n.has(e)))}function Cj(e,t,n,r,i=bj,a=0){let o=e.rotations??0;return e.conditions.every(e=>{let s=o>0?i(e.dx,e.dy,a,o):e;return Sj(e,r(t+s.dx,n+s.dy))})}function wj(e,t,n,r,i={}){let a=i.rotate??bj,o=i.random??new w,s=[];for(let i=0;i<t;i+=1)for(let t=0;t<e;t+=1){let e=-1,c=[];for(let o of n){let n=o.rotations??0,s=n>0?n:1;for(let n=0;n<s;n+=1){if(!Cj(o,t,i,r,a,n))continue;let s=o.conditions.length;s>e?(e=s,c=[{rule:o,rotationIndex:n}]):s===e&&c.push({rule:o,rotationIndex:n})}}if(c.length===0)continue;let l=c.length===1?c[0]:c[Tj(c.map(e=>e.rule.probability??1),o)],u=l.rule.rotations??0;for(let e of l.rule.images){let n=u>0?a(e.dx??0,e.dy??0,l.rotationIndex,u):{dx:e.dx??0,dy:e.dy??0};s.push({x:t,y:i,ruleId:l.rule.id,image:e.image,dx:n.dx,dy:n.dy,layer:e.layer??0})}}return s}function Tj(e,t){let n=e.reduce((e,t)=>e+Math.max(0,t),0);if(n<=0)return 0;let r=t.float()*n;for(let t=0;t<e.length;t+=1)if(r-=Math.max(0,e[t]),r<0)return t;return e.length-1}var Ej=class extends G{},Dj=class extends Sw{},Oj=class extends CO{},kj=class extends $s{},Aj=class extends aO{},jj=xx,Mj=class extends Ej{constructor(e){super(),this.placements=e.placements,this.project=e.project,this.resolveImage=e.resolveImage??(e=>wA(e,U.EMPTY)),this.rebuild()}setPlacements(e){this.placements=e,this.rebuild()}rebuild(){for(let e of this.removeChildren())e.destroy();for(let e of[...this.placements].sort((e,t)=>e.layer-t.layer)){let t=this.project(e.x,e.y,e.dx,e.dy),n=new kj(this.resolveImage(e.image));n.x=t.x,n.y=t.y,this.addChild(n)}}},Nj=[{workload:`sprites`,preferred:`PixiJS WebGL/WebGPU batcher`,fallback:`PixiJS WebGL`,reason:`high-volume textured 2D batches`},{workload:`ui`,preferred:`PixiJS display tree`,fallback:`PixiJS display tree`,reason:`themeable 2D layout and text`},{workload:`custom-shaders`,preferred:`backend-specific GLSL/WGSL only when profiled`,fallback:`PixiJS filters`,reason:`avoid maintaining paired shader sources without a measured gain`},{workload:`particles`,preferred:`PixiJS for 2D, Babylon.js for 3D`,fallback:`instanced sprites/meshes`,reason:`match simulation and depth to the scene`},{workload:`instanced-terrain`,preferred:`Babylon.js thin instances`,fallback:`PixiJS TileMap for 2D`,reason:`depth-tested repeated 3D geometry`},{workload:`voxels`,preferred:`Babylon.js thin instances`,fallback:`batched meshes`,reason:`color-grouped 3D voxels`},{workload:`animated-models`,preferred:`Babylon.js glTF animation groups`,fallback:`billboard sprites`,reason:`standard 3D interchange and animation support`},{workload:`large-3d-worlds`,preferred:`Babylon.js with streaming/culling`,fallback:`partitioned scenes`,reason:`scene graph, depth, and instancing`}];function Pj(e={}){let t=e.createCanvas?.()??(typeof document>`u`?null:document.createElement(`canvas`)),n=!!t?.getContext(`webgl2`);return{webgl1:n||!!(t?.getContext(`webgl`)??t?.getContext(`experimental-webgl`)),webgl2:n,webgpu:e.webgpu??!!globalThis.navigator?.gpu,wgsl:e.wgsl??!1}}async function Fj(){let e=globalThis.navigator?.gpu;if(!e)return{webgpu:!1,wgsl:!1};try{let t=await(await e.requestAdapter())?.requestDevice();return t?{webgpu:!0,wgsl:(await t.createShaderModule({code:`@compute @workgroup_size(1) fn main() {}`}).getCompilationInfo()).messages.length===0}:{webgpu:!1,wgsl:!1}}catch{return{webgpu:!1,wgsl:!1}}}var Ij=536870911,Lj={orthogonal:`square`,isometric:`isometric`,staggered:`staggered`};function Rj(e,t,n){if(e.frameWidth!==t.tilewidth||e.frameHeight!==t.tileheight)throw Error(`the tileset at firstgid ${n} is cut to ${e.frameWidth}x${e.frameHeight}, but the map is ${t.tilewidth}x${t.tileheight}`)}function zj(e,t,n){let r=-1;for(let n=0;n<t.length&&t[n]<=e;n++)r=n;if(r===-1)throw Error(`layer "${n}" uses gid ${e}, below every tileset's firstgid (${t.join(`, `)})`);return r}function Bj(e,t){let n=e.orientation??`orthogonal`,r=Lj[n];if(!r)throw Error(`loadTiledMap does not read "${n}" maps yet`);if(r===`staggered`&&(e.staggeraxis??`y`)!==`y`)throw Error(`loadTiledMap only reads Y-axis staggered maps right now, this one is staggered on "${e.staggeraxis}"`);if(r===`staggered`&&(e.staggerindex??`odd`)!==`odd`)throw Error(`loadTiledMap only reads odd-index staggered maps right now, this one staggers "${e.staggerindex}"`);if(e.tilesets.length===0)throw Error(`loadTiledMap needs at least one tileset, this map has none`);let i=[...e.tilesets].sort((e,t)=>e.firstgid-t.firstgid),a,o;if(t instanceof LA){if(e.tilesets.length!==1)throw Error(`loadTiledMap was given one sheet but this map has ${e.tilesets.length} tilesets - pass one sheet per tileset`);Rj(t,e,i[0].firstgid),a=[t],o=[i[0].firstgid]}else{if(t.length!==e.tilesets.length)throw Error(`loadTiledMap was given ${t.length} sheets but this map has ${e.tilesets.length} tilesets - pass one sheet per tileset`);a=i.map(n=>{let r=t.find(e=>e.firstgid===n.firstgid);if(!r)throw Error(`loadTiledMap was given no sheet for the tileset at firstgid ${n.firstgid}`);return Rj(r.sheet,e,n.firstgid),r.sheet}),o=i.map(e=>e.firstgid)}let s=new nj({width:e.width,height:e.height,sheet:a,shape:r}),c=[];for(let t of e.layers)if(t.type===`tilelayer`){if(t.encoding&&t.encoding!==`csv`)throw Error(`layer "${t.name}" uses "${t.encoding}" encoding - export tile layers as CSV/plain, not compressed`);let e=(t.data??[]).map(e=>{let n=e&Ij;if(n===0)return-1;let r=zj(n,o,t.name);return o.length===1?n-o[0]:$A(r,n-o[r])});s.addLayer(t.name,e)}else if(t.type===`objectgroup`)for(let n of t.objects??[])c.push({...n,tileX:Math.floor(n.x/e.tilewidth),tileY:Math.floor(n.y/e.tileheight)});return{map:s,objects:c}}var Vj={panelBorder:4,padding:8,spacing:2,direction:`ltr`,font:{family:`ui-monospace, Consolas, "DejaVu Sans Mono", monospace`,size:12,lineHeight:1.4},color:{text:15263984,textDim:9079446,textHighlight:16770688,panelFill:1842214,panelBorder:4868702,selection:3820154,overlay:0},overlayAlpha:.5},Hj={panelBorder:6,padding:10,spacing:4,direction:`ltr`,font:{family:Vj.font.family,size:14,lineHeight:1.5},color:{text:16777215,textDim:13421772,textHighlight:16776960,panelFill:0,panelBorder:16777215,selection:16776960,overlay:0},overlayAlpha:.85},Uj=Vj;function Q(){return Uj}var $=new p;function Wj(e){Uj={...Vj,...e,font:{...Vj.font,...e.font},color:{...Vj.color,...e.color}},$.dispatch(Uj)}function Gj(e){return typeof e==`string`?{text:e}:e}function Kj(e,t){return e.align??(t.direction===`rtl`?`right`:`left`)}function qj(e,t=40){let n=Math.max(0,e);return{total:n,speed:Math.max(0,t),revealed:t===0?n:0}}function Jj(e,t){return e.revealed=Math.min(e.total,Math.max(0,e.revealed+e.speed*t)),Xj(e)}function Yj(e){e.revealed=e.total}function Xj(e){return e.revealed>=e.total}var Zj=class extends CO{constructor(e={}){let t=Gj(e),n=Q();super({text:t.text??``,resolution:t.resolution,roundPixels:t.roundPixels,style:new nE({fontFamily:n.font.family,stroke:t.stroke,fontSize:t.size??n.font.size,fontWeight:t.bold?`bold`:`normal`,fill:t.color??n.color.text,lineHeight:(t.size??n.font.size)*n.font.lineHeight,align:Kj(t,n),wordWrap:t.wrapWidth!==void 0,wordWrapWidth:t.wrapWidth??0,breakWords:!0})}),this.themeListener=e=>this.restyle(e),this.revealSource=null,this.reveal=null,this.opts=t,$.add(this.themeListener)}setColor(e){this.style.fill=e}setText(e){this.revealSource=null,this.reveal=null,this.text!==e&&(this.text=e)}showProgressive(e,t){this.revealSource=e,this.reveal=qj(e.length,t),this.renderRevealed()}updateReveal(e){if(!this.reveal)return!0;let t=Jj(this.reveal,e);return this.renderRevealed(),t}completeReveal(){this.reveal&&(Yj(this.reveal),this.renderRevealed())}renderRevealed(){if(!this.reveal||this.revealSource===null)return;let e=this.revealSource.slice(0,Math.floor(this.reveal.revealed));this.text!==e&&(this.text=e)}restyle(e){this.style.fontFamily=e.font.family,this.opts.color===void 0&&(this.style.fill=e.color.text),this.opts.size===void 0&&(this.style.fontSize=e.font.size,this.style.lineHeight=e.font.size*e.font.lineHeight),this.opts.align===void 0&&(this.style.align=Kj(this.opts,e))}destroy(e){$.remove(this.themeListener),super.destroy(e)}},Qj=``,$j=``,eM=``;function tM(e){let t=``;for(let n=0;n<e.length;n++)if(e[n]===`\\`&&n+1<e.length&&(e[n+1]===`*`||e[n+1]===`_`||e[n+1]===`\\`)){let r=e[n+1];t+=r===`*`?Qj:r===`_`?$j:eM,n++}else t+=e[n];return t}function nM(e){return e.replaceAll(Qj,`*`).replaceAll($j,`_`).replaceAll(eM,`\\`)}function rM(e){return e!==void 0&&/[\p{L}\p{N}_]/u.test(e)}function iM(e,t,n){let r=[],i=0;for(;i<e.length;){if(e[i]!==t){i++;continue}let a=0;for(;e[i+a]===t;)a++;if(!(t===`_`&&rM(e[i-1])&&rM(e[i+a]))){if(n)for(let e=0;e<Math.floor(a/2);e++)r.push(i+e*2);else a%2==1&&r.push(i+a-1)}i+=a}return r}function aM(e,t,n,r,i,a){let o=iM(e,t,n),s=n?2:1;for(let e=0;e+1<o.length;e+=2){let t=o[e],n=o[e+1];i.push({from:t+s,to:n,style:r}),a.push({from:t,to:t+s},{from:n,to:n+s})}}function oM(e){let t=[];for(let n of e){if(!n.text)continue;let e=t[t.length-1];e&&e.bold===n.bold&&e.italic===n.italic?e.text+=n.text:t.push({...n})}return t}function sM(e){let t=tM(e),n=[],r=[];aM(t,`*`,!0,`bold`,n,r),aM(t,`_`,!0,`bold`,n,r),aM(t,`*`,!1,`italic`,n,r),aM(t,`_`,!1,`italic`,n,r);let i=new Set([0,t.length]);for(let e of n)i.add(e.from),i.add(e.to);for(let e of r)i.add(e.from),i.add(e.to);let a=[...i].sort((e,t)=>e-t),o=[];for(let e=0;e+1<a.length;e++){let i=a[e],s=a[e+1];i>=s||r.some(e=>e.from<=i&&s<=e.to)||o.push({text:t.slice(i,s),bold:n.some(e=>e.style===`bold`&&e.from<=i&&s<=e.to),italic:n.some(e=>e.style===`italic`&&e.from<=i&&s<=e.to)})}return oM(o).map(e=>({...e,text:nM(e.text)}))}function cM(e){return sM(e).map(e=>e.text).join(``)}function lM(e,t){let n=[],r=Math.max(0,Math.floor(t));for(let t of e){if(r<=0)break;let e=Math.min(t.text.length,r);n.push({...t,text:t.text.slice(0,e)}),r-=e}return n}var uM=class extends ok{constructor(e={}){let t=Gj(e),n=Q();super({text:dM(t.text??``),resolution:t.resolution,style:new UO({fontFamily:n.font.family,fontSize:t.size??n.font.size,fontWeight:t.bold?`bold`:`normal`,fill:t.color??n.color.text,lineHeight:(t.size??n.font.size)*n.font.lineHeight,align:Kj(t,n),wordWrap:t.wrapWidth!==void 0,wordWrapWidth:t.wrapWidth??0,breakWords:!0})}),this.themeListener=e=>this.restyle(e),this.revealSpans=null,this.reveal=null,this.opts=t,$.add(this.themeListener)}setText(e){this.revealSpans=null,this.reveal=null;let t=dM(e);this.text!==t&&(this.text=t)}showProgressive(e,t){this.revealSpans=sM(e),this.reveal=qj(cM(e).length,t),this.renderRevealed()}updateReveal(e){if(!this.reveal)return!0;let t=Jj(this.reveal,e);return this.renderRevealed(),t}completeReveal(){this.reveal&&(Yj(this.reveal),this.renderRevealed())}renderRevealed(){if(!this.reveal||!this.revealSpans)return;let e=fM(lM(this.revealSpans,this.reveal.revealed));this.text!==e&&(this.text=e)}restyle(e){this.style.fontFamily=e.font.family,this.opts.color===void 0&&(this.style.fill=e.color.text),this.opts.size===void 0&&(this.style.fontSize=e.font.size,this.style.lineHeight=e.font.size*e.font.lineHeight),this.opts.align===void 0&&(this.style.align=Kj(this.opts,e))}destroy(e){$.remove(this.themeListener),super.destroy(e)}};function dM(e){return fM(sM(e))}function fM(e){return e.map(e=>{let t=pM(e.text);return e.italic&&(t=`<i>${t}</i>`),e.bold&&(t=`<b>${t}</b>`),t}).join(``)}function pM(e){return e.replaceAll(`&`,`&amp;`).replaceAll(`<`,`&lt;`).replaceAll(`>`,`&gt;`)}var mM=new Set([`b`,`i`,`span`,`br`,`img`]);function hM(e,t={}){let n=t.variables??{},r=[],i=[],a={bold:!1,italic:!1},o=``,s=()=>{if(!o)return;let e={text:o,bold:a.bold,italic:a.italic};a.color!==void 0&&(e.color=a.color),a.size!==void 0&&(e.size=a.size),r.push(e),o=``};for(let t=0;t<e.length;t++){let c=e[t];if(c===`&`){let n=DM(e,t);if(n){o+=n.text,t=n.end;continue}}if(c===`$`){let r=OM(e,t),i=r?n[r.name]:void 0;if(r&&i!==void 0){o+=i,t=r.end;continue}}if(c===`<`){let n=TM(e,t);if(n&&mM.has(n.name)){if(n.name===`img`){let i=EM(e,n);if(i){s(),r.push({text:``,bold:!1,italic:!1,image:i.src}),t=i.end;continue}}else if(n.name===`br`){o+=`
1332
+ `,t=n.end;continue}else if(n.closing){let e=i[i.length-1];if(e?.tag===n.name){s(),a=e.style,i.pop(),t=n.end;continue}}else{s(),i.push({tag:n.name,style:a}),a=CM(a,n.name,n.body),t=n.end;continue}}}o+=c}return s(),r}function gM(e,t={}){return hM(e,t).map(e=>e.image??e.text).join(``)}function _M(e){return e.map(e=>{if(e.image!==void 0)return``;let t=SM(e.text);e.italic&&(t=`<i>${t}</i>`),e.bold&&(t=`<b>${t}</b>`);let n=[e.color===void 0?void 0:`color:${e.color}`,e.size===void 0?void 0:`font-size:${e.size}px`].filter(e=>e!==void 0);return n.length>0&&(t=`<span style="${n.join(`;`)}">${t}</span>`),t}).join(``)}function vM(e,t={}){let n=t.describeImage??(()=>`[image]`);return e.map(e=>e.image===void 0?e.text:n(e.image)).join(``)}function yM(e,t,n){let r=[];for(let t of e){if(t.image!==void 0){r.push({...t});continue}t.text.split(`
1333
+ `).forEach((e,n)=>{n>0&&r.push({text:``,bold:t.bold,italic:t.italic,hardBreak:!0});for(let n of e.match(/\S+|\s+/g)??[])r.push({text:n,bold:t.bold,italic:t.italic,color:t.color,size:t.size})})}let i=[],a=[],o=0,s=()=>{for(;a.length>0&&a[a.length-1].text.trim()===``&&!a[a.length-1].image;)o-=t(a[a.length-1]),a.pop();i.push({spans:bM(a),width:Math.max(0,o)}),a=[],o=0};for(let e of r){if(e.hardBreak){s();continue}let r=t(e),i=e.image===void 0&&e.text.trim()===``;o>0&&!i&&o+r>n&&s(),a.push(e),o+=r}return(a.length>0||i.length===0)&&s(),i}function bM(e){let t=[];for(let n of e){let e=t[t.length-1];e&&n.image===void 0&&e.image===void 0&&e.bold===n.bold&&e.italic===n.italic&&e.color===n.color&&e.size===n.size?e.text+=n.text:t.push({...n})}return t}function xM(e,t){let n=t.direction??`ltr`,r=t.align??(n===`rtl`?`right`:`left`),i=[];for(let a=0;a<e.length;a++){let o=e[a],s=a*t.lineHeight,c=o.spans.map(e=>t.measure(e)),l=c.reduce((e,t)=>e+t,0),u=r===`left`?0:r===`right`?t.maxWidth-l:(t.maxWidth-l)/2,d=n===`rtl`?u+l:u;for(let e=0;e<o.spans.length;e++){let t=c[e],r=n===`rtl`?d-t:d;d=n===`rtl`?d-t:d+t,i.push({span:o.spans[e],x:r,y:s,width:t})}}return i}function SM(e){return e.replaceAll(`&`,`&amp;`).replaceAll(`<`,`&lt;`).replaceAll(`>`,`&gt;`).replaceAll(`"`,`&quot;`).replaceAll(`'`,`&#39;`)}function CM(e,t,n){if(t===`b`)return{...e,bold:!0};if(t===`i`)return{...e,italic:!0};let r=wM(n,`color`),i=Number(wM(n,`size`)??``),a={...e};return r&&(a.color=r),Number.isFinite(i)&&i>0&&(a.size=i),a}function wM(e,t){let n=RegExp(`(?:^|\\s)${t}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s"'>]+))`).exec(e);return n?n[1]??n[2]??n[3]:void 0}function TM(e,t){let n=/^<(\/?)([a-zA-Z]+)([^>]*)>/.exec(e.slice(t));if(!n)return null;let r=n[3].trimEnd();return{name:n[2].toLowerCase(),closing:n[1]===`/`,selfClosing:r.endsWith(`/`)&&n[1]===``,body:r.replace(/\/$/,``).trim(),end:t+n[0].length-1}}function EM(e,t){if(t.selfClosing){let e=wM(t.body,`src`);return e?{src:e,end:t.end}:null}let n=e.indexOf(`</img>`,t.end+1);if(n<0)return null;let r=e.slice(t.end+1,n).trim();return r?{src:r,end:n+6-1}:null}function DM(e,t){let n={lt:`<`,gt:`>`,amp:`&`,quot:`"`,apos:`'`},r=/^&(lt|gt|amp|quot|apos);/.exec(e.slice(t));if(r)return{text:n[r[1]],end:t+r[0].length-1};let i=/^&#(\d+);/.exec(e.slice(t));return i?{text:String.fromCodePoint(Number(i[1])),end:t+i[0].length-1}:null}function OM(e,t){let n=/^\$([A-Za-z_][A-Za-z0-9_]*)/.exec(e.slice(t));return n?{name:n[1],end:t+n[0].length-1}:null}var kM=class extends G{constructor(e={}){super(),this.themeListener=e=>this.rebuild(e),this.opts=e,this.rebuild(Q()),$.add(this.themeListener)}setText(e){this.opts.text=e,this.rebuild(Q())}rebuild(e){for(let e of this.removeChildren())e.destroy();let t=this.opts.lineHeight??e.font.size*e.font.lineHeight,n=this.opts.maxWidth??1/0,r=this.opts.maxWidth??0,i=this.opts.direction??e.direction,a=this.opts.resolveImage??(e=>wA(e,U.EMPTY)),o=jM(),s=n=>this.measurePiece(n,e,t,a,o),c=xM(yM(hM(this.opts.text??``,{variables:this.opts.variables}),s,n),{measure:s,maxWidth:r,lineHeight:t,direction:i,align:this.opts.align??(this.opts.maxWidth===void 0?`left`:void 0)});for(let n of c){let r=n.span.image===void 0?this.textFor(n.span,e,t):this.spriteFor(n.span.image,t,a);r.x=n.x,r.y=n.y,this.addChild(r)}}measurePiece(e,t,n,r,i){return e.image===void 0?i?(i.font=MM(e,t.font.family,t.font.size),i.measureText(e.text).width):e.text.length*(e.size??t.font.size):NM(r(e.image),n).width}textFor(e,t,n){return new Oj({text:e.text,resolution:this.opts.resolution,style:{fontFamily:t.font.family,fontSize:e.size??t.font.size,fontWeight:e.bold?`bold`:`normal`,fontStyle:e.italic?`italic`:`normal`,fill:e.color??t.color.text,lineHeight:n}})}spriteFor(e,t,n){let r=n(e),i=NM(r,t),a=new kj(r);return a.width=i.width,a.height=i.height,a}destroy(e){$.remove(this.themeListener),super.destroy(e)}},AM=null;function jM(){return typeof document>`u`?null:(AM??=document.createElement(`canvas`).getContext(`2d`),AM)}function MM(e,t,n){return`${e.italic?`italic `:``}${e.bold?`bold `:``}${e.size??n}px ${t}`}function NM(e,t){return{width:(e.width>0?e.width:t)*(t/(e.height>0?e.height:t)),height:t}}var PM=class extends IO{constructor(e={}){let t=Gj(e),n=Q();super({text:t.text??``,style:FM(t,n)}),this.themeListener=e=>this.restyle(e),this.opts=t,$.add(this.themeListener)}setText(e){this.text!==e&&(this.text=e)}restyle(e){this.style=FM(this.opts,e)}destroy(e){$.remove(this.themeListener),super.destroy(e)}};function FM(e,t){return{fontFamily:t.font.family,fontSize:e.size??t.font.size,fontWeight:e.bold?`bold`:`normal`,fill:e.color??t.color.text,align:Kj(e,t),wordWrap:e.wrapWidth!==void 0,wordWrapWidth:e.wrapWidth??0,breakWords:!0}}var IM=class extends G{constructor(e,t){super();let n=typeof t.border==`number`?{left:t.border,top:t.border,right:t.border,bottom:t.border}:t.border;this.sprite=new hk({texture:e,leftWidth:n.left,topHeight:n.top,rightWidth:n.right,bottomHeight:n.bottom}),this.addChild(this.sprite)}get border(){return{left:this.sprite.leftWidth,top:this.sprite.topHeight,right:this.sprite.rightWidth,bottom:this.sprite.bottomHeight}}resize(e,t){let n=this.border;this.sprite.width=Math.max(e,n.left+n.right),this.sprite.height=Math.max(t,n.top+n.bottom)}},LM=`position:absolute;width:1px;height:1px;margin:-1px;padding:0;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap;border:0;`,RM=class{constructor(){this.polite=null,this.assertive=null}region(e){if(typeof document>`u`||!document.body)return null;let t=e?this.assertive:this.polite;if(t)return t;let n=document.createElement(`div`);return n.setAttribute(`aria-live`,e?`assertive`:`polite`),n.setAttribute(`aria-atomic`,`true`),n.setAttribute(`role`,`status`),n.setAttribute(`style`,LM),document.body.appendChild(n),e?this.assertive=n:this.polite=n,n}announce(e,t={}){let n=this.region(t.assertive??!1);n&&(n.textContent=``,n.appendChild(document.createTextNode(e)))}clear(){this.polite&&(this.polite.textContent=``),this.assertive&&(this.assertive.textContent=``)}destroy(){this.polite?.remove(),this.assertive?.remove(),this.polite=null,this.assertive=null}},zM=new RM,BM=class extends G{constructor(e){super(),this.content=new G,this.onClose=new p,this.titleLabel=null,this.innerWidth=0,this.innerHeight=0,this.currentWidth=0,this.currentHeight=0,this.themeListener=()=>this.restyle(),this.isClosed=!1,this.delegate=null;let t=Q();this.modal=e.modal??!0,this.closable=e.closable??!0,this.dims=e.dims??this.modal,this.anchor=e.anchor??`center`,this.background=t.panel?new IM(t.panel,{border:t.panelBorder}):new Sw,this.addChild(this.background),e.title!==void 0&&(this.titleLabel=new Zj({text:e.title,color:t.color.textHighlight,bold:!0}),this.addChild(this.titleLabel),zM.announce(e.title)),this.addChild(this.content),this.resize(e.width,e.height),$.add(this.themeListener)}restyle(){this.titleLabel?.setColor(Q().color.textHighlight),this.resize(this.currentWidth,this.currentHeight)}resize(e,t){this.currentWidth=e,this.currentHeight=t;let n=Q(),r=(this.background instanceof IM?this.background.border.left:2)+n.padding;this.background instanceof IM?this.background.resize(e,t):this.background.clear().roundRect(0,0,e,t,4).fill({color:n.color.panelFill}).stroke({color:n.color.panelBorder,width:1});let i=r;this.titleLabel&&(this.titleLabel.x=n.direction===`rtl`?e-r-this.titleLabel.width:r,this.titleLabel.y=r,i=r+this.titleLabel.height+n.padding),this.content.x=r,this.content.y=i,this.innerWidth=Math.max(0,e-r*2),this.innerHeight=Math.max(0,t-i-r)}get contentWidth(){return this.innerWidth}get contentHeight(){return this.innerHeight}setTitle(e){this.titleLabel?.setText(e)}handleAction(e){return this.isClosed?!1:this.delegate?.handleAction(e)?!0:e===`cancel`&&this.closable?(this.close(),!0):!1}get closed(){return this.isClosed}update(e){}close(){this.isClosed||(this.isClosed=!0,this.onClose.dispatch(),this.parent?.removeChild(this),this.destroy({children:!0}))}place(e,t){if(this.isClosed)return;let n=this.getLocalBounds(),r=Q().padding*2;this.x=Math.round((e-n.width)/2),this.y=this.anchor===`bottom`?Math.round(t-n.height-r):this.anchor===`top`?r:Math.round((t-n.height)/2)}destroy(e){this.isClosed=!0,$.remove(this.themeListener),super.destroy(e)}},VM=class extends G{constructor(){super(),this.windows=[],this.overlay=new Sw,this.viewportWidth=0,this.viewportHeight=0,this.listener=e=>this.handleAction(e),this.themeListener=()=>this.drawOverlay(),this.overlay.visible=!1,this.addChild(this.overlay),Ce.add(this.listener),$.add(this.themeListener)}setViewport(e,t){this.viewportWidth=e,this.viewportHeight=t,this.drawOverlay();for(let n of this.windows)n.place(e,t)}get top(){return this.windows[this.windows.length-1]??null}get isEmpty(){return this.windows.length===0}get depth(){return this.windows.length}push(e){if(e.closed)throw Error(`cannot open a window that was already closed`);return this.windows.push(e),this.addChild(e),e.onClose.add(()=>(this.forget(e),!1)),e.place(this.viewportWidth,this.viewportHeight),this.updateOverlay(),e}pop(){this.top?.close()}closeAll(){for(let e of[...this.windows].reverse())e.close()}forget(e){let t=this.windows.indexOf(e);t!==-1&&this.windows.splice(t,1),this.updateOverlay()}updateOverlay(){let e=this.windows.findIndex(e=>e.dims);if(e===-1){this.overlay.visible=!1;return}this.overlay.visible=!0,this.setChildIndex(this.overlay,Math.max(0,this.getChildIndex(this.windows[e])-1))}drawOverlay(){let e=Q();this.overlay.clear().rect(0,0,this.viewportWidth,this.viewportHeight).fill({color:e.color.overlay,alpha:e.overlayAlpha})}handleAction(e){return this.top?.handleAction(e)??!1}get blocksWorld(){return this.windows.some(e=>e.modal)}update(e){this.top?.update(e)}destroy(e){Ce.remove(this.listener),$.remove(this.themeListener),super.destroy(e)}},HM=class{constructor(e){this.list=[],this.current=0,this.hooks=e}get items(){return this.list}get selectedIndex(){return this.current}get selected(){return this.list[this.current]??null}get length(){return this.list.length}reset(e){this.list=e,this.current=e.findIndex(e=>!e.disabled),this.current===-1&&(this.current=0)}swap(e,t){[this.list[e],this.list[t]]=[this.list[t],this.list[e]]}land(e){this.current=e,this.hooks.onChange();let t=this.list[e];t&&this.hooks.onHighlight(t,e)}select(e){e<0||e>=this.list.length||this.list[e].disabled||this.land(e)}confirm(e){let t=this.selected;return!t||t.disabled?!1:(e?.(t,this.current),!0)}step(e,t){if(this.list.length===0)return!1;let n=this.current;for(let r=0;r<t;r++){let t=e(n,this.list.length);if(n=t,!(t<0||t>=this.list.length)&&!this.list[t].disabled)return this.land(t),!0}return!1}},UM=class extends G{constructor(e){super(),this.selection=new HM({onChange:()=>this.refresh(),onHighlight:(e,t)=>this.onHighlight?.(e,t)}),this.rows=[],this.rowsLayer=new G,this.highlight=new Sw,this.mask_=new Sw,this.scroll=0,this.themeListener=()=>this.restyle();let t=Q();this.viewWidth=e.width,this.viewHeight=e.height,this.explicitRowHeight=e.rowHeight!==void 0,this.rowHeight=e.rowHeight??Math.ceil(t.font.size*t.font.lineHeight)+t.spacing,this.onSelect=e.onSelect??null,this.onHighlight=e.onHighlight??null,this.addChild(this.highlight),this.addChild(this.rowsLayer),this.addChild(this.mask_),this.rowsLayer.mask=this.mask_,this.drawMask(),this.eventMode=`static`,this.on(`wheel`,e=>this.move(e.deltaY>0?1:-1)),this.setItems(e.items??[]),$.add(this.themeListener)}restyle(){let e=Q();this.explicitRowHeight||(this.rowHeight=Math.ceil(e.font.size*e.font.lineHeight)+e.spacing);let t=e.direction===`rtl`,n=this.selection.items;this.rows.forEach((r,i)=>{r.y=i*this.rowHeight;let a=n[i],o=r.children.find(e=>e instanceof Zj);if(o){o.setColor(a.disabled?e.color.textDim:e.color.text);let n=e.spacing+(a.icon?this.rowHeight:0);o.x=t?this.viewWidth-n-o.width:n,o.y=Math.round((this.rowHeight-o.height)/2)}a.icon&&(a.icon.x=t?this.viewWidth-e.spacing-this.rowHeight:e.spacing)}),this.refresh()}destroy(e){$.remove(this.themeListener),super.destroy(e)}drawMask(){this.mask_.clear().rect(0,0,this.viewWidth,this.viewHeight).fill({color:16777215})}get visibleRows(){return Math.max(1,Math.floor(this.viewHeight/this.rowHeight))}get selectedIndex(){return this.selection.selectedIndex}get selected(){return this.selection.selected}get length(){return this.selection.length}setItems(e){for(let e of this.rows)e.destroy({children:!0});this.rows=[],this.rowsLayer.removeChildren();let t=Q(),n=t.direction===`rtl`;e.forEach((e,r)=>{let i=new G;i.y=r*this.rowHeight,i.eventMode=`static`,i.cursor=e.disabled?`default`:`pointer`,i.on(`pointerdown`,()=>{e.disabled||(this.select(r),this.confirm())}),e.icon&&(e.icon.x=n?this.viewWidth-t.spacing-this.rowHeight:t.spacing,i.addChild(e.icon));let a=new Zj({text:e.text,color:e.disabled?t.color.textDim:t.color.text}),o=t.spacing+(e.icon?this.rowHeight:0);a.x=n?this.viewWidth-o-a.width:o,a.y=Math.round((this.rowHeight-a.height)/2),i.addChild(a),this.rows.push(i),this.rowsLayer.addChild(i)}),this.selection.reset(e),this.scroll=0,this.refresh()}resize(e,t){this.viewWidth=e,this.viewHeight=t,this.drawMask(),this.refresh()}move(e){return this.selection.step((t,n)=>(t+e+n)%n,this.selection.length)}select(e){this.selection.select(e)}confirm(){return this.selection.confirm(this.onSelect)}handleAction(e){switch(e){case`up`:return this.move(-1);case`down`:return this.move(1);case`confirm`:return this.confirm();default:return!1}}refresh(){let e=this.visibleRows,t=this.selection.selectedIndex,n=this.selection.length;t<this.scroll?this.scroll=t:t>=this.scroll+e&&(this.scroll=t-e+1),this.scroll=Math.max(0,Math.min(this.scroll,Math.max(0,n-e))),this.rowsLayer.y=-this.scroll*this.rowHeight;let r=Q();if(n===0){this.highlight.clear();return}this.highlight.clear().rect(0,(t-this.scroll)*this.rowHeight,this.viewWidth,this.rowHeight).fill({color:r.color.selection})}},WM=class extends G{columnX(e){return(Q().direction===`rtl`?this.columns-1-e:e)*this.cellSize}constructor(e){super(),this.selection=new HM({onChange:()=>this.refresh(),onHighlight:(e,t)=>this.onHighlight?.(e,t)}),this.cells=[],this.cellsLayer=new G,this.highlight=new Sw,this.pickupHighlight=new Sw,this.mask_=new Sw,this.scrollRow=0,this.pickedUp=null,this.pressedIndex=null,this.pressTimer=0,this.themeListener=()=>{let e=Q();this.selection.items.forEach((t,n)=>{let r=this.cells[n];r&&(r.x=this.columnX(n%this.columns),!((t.quantity??1)<=1)&&r.children.find(e=>e instanceof Zj)?.setColor(e.color.textHighlight))}),this.refresh()},this.viewWidth=e.width,this.viewHeight=e.height,this.columns=Math.max(1,e.columns),this.cellSize=e.cellSize??Math.floor(this.viewWidth/this.columns),this.longPressDuration=e.longPressDuration??.6,this.onSelect=e.onSelect??null,this.onHighlight=e.onHighlight??null,this.onQuickslot=e.onQuickslot??null,this.onReorder=e.onReorder??null,this.addChild(this.highlight),this.addChild(this.pickupHighlight),this.addChild(this.cellsLayer),this.addChild(this.mask_),this.cellsLayer.mask=this.mask_,this.drawMask(),this.eventMode=`static`,this.on(`wheel`,e=>this.move(0,e.deltaY>0?1:-1)),this.setItems(e.items??[]),$.add(this.themeListener)}destroy(e){$.remove(this.themeListener),super.destroy(e)}drawMask(){this.mask_.clear().rect(0,0,this.viewWidth,this.viewHeight).fill({color:16777215})}get visibleRows(){return Math.max(1,Math.floor(this.viewHeight/this.cellSize))}get rows(){return Math.max(1,Math.ceil(this.selection.length/this.columns))}get selectedIndex(){return this.selection.selectedIndex}get selected(){return this.selection.selected}get length(){return this.selection.length}setItems(e){this.pickedUp=null,this.pressedIndex=null;for(let e of this.cells)e.destroy({children:!0});this.cells=[],this.cellsLayer.removeChildren();let t=Q();e.forEach((e,n)=>{let r=Math.floor(n/this.columns),i=n%this.columns,a=new G;if(a.x=this.columnX(i),a.y=r*this.cellSize,a.eventMode=`static`,a.cursor=e.disabled?`default`:`pointer`,e.icon.x=Math.round((this.cellSize-e.icon.width)/2),e.icon.y=Math.round((this.cellSize-e.icon.height)/2),e.disabled&&(e.icon.alpha=.4),a.addChild(e.icon),(e.quantity??1)>1){let n=new Zj({text:String(e.quantity),size:10,color:t.color.textHighlight});n.x=this.cellSize-n.width-2,n.y=this.cellSize-n.height-1,a.addChild(n)}a.on(`pointerdown`,()=>{this.pressedIndex=n,this.pressTimer=0}),a.on(`pointerup`,()=>this.releaseCell(n)),a.on(`pointerupoutside`,()=>this.releaseCell(n)),this.cells.push(a),this.cellsLayer.addChild(a)}),this.selection.reset(e),this.scrollRow=0,this.refresh()}releaseCell(e){this.pressedIndex===e&&(this.pressedIndex=null,this.selection.items[e]?.disabled||this.tapCell(e))}resize(e,t){this.viewWidth=e,this.viewHeight=t,this.drawMask(),this.refresh()}update(e){if(this.pressedIndex===null||(this.pressTimer+=e,this.pressTimer<this.longPressDuration))return;let t=this.pressedIndex;this.pressedIndex=null;let n=this.selection.items[t];n&&!n.disabled&&this.onQuickslot?.(n,t)}tapCell(e){let t=this.selection.items;if(e<0||e>=t.length)return;if(this.pickedUp===null){if(t[e].disabled)return;this.pickedUp=e,this.refresh();return}let n=this.pickedUp;this.pickedUp=null,n!==e&&(this.swapCells(n,e),this.onReorder?.(n,e)),this.refresh()}swapCells(e,t){let n=this.selection.items;this.selection.swap(e,t);let r=this.cells[e],i=this.cells[t],a=r.removeChildren(),o=i.removeChildren();for(let e of o)r.addChild(e);for(let e of a)i.addChild(e);r.cursor=n[e].disabled?`default`:`pointer`,i.cursor=n[t].disabled?`default`:`pointer`}cancelPickup(){this.pickedUp=null,this.refresh()}move(e,t){let n=this.rows,r=this.columns;return this.selection.step(i=>{let a=(Math.floor(i/r)+t+n)%n,o=(i%r+e+r)%r;return a*r+o},n*r)}select(e){this.selection.select(e)}confirm(){return this.selection.confirm(this.onSelect)}handleAction(e){switch(e){case`up`:return this.move(0,-1);case`down`:return this.move(0,1);case`left`:return this.move(Q().direction===`rtl`?1:-1,0);case`right`:return this.move(Q().direction===`rtl`?-1:1,0);case`confirm`:return this.confirm();case`cancel`:return this.pickedUp!==null&&(this.cancelPickup(),!0);default:return!1}}cellRect(e){return{x:this.columnX(e%this.columns),y:Math.floor(e/this.columns)*this.cellSize}}refresh(){let e=this.visibleRows,t=this.selection.selectedIndex,n=Math.floor(t/this.columns);n<this.scrollRow?this.scrollRow=n:n>=this.scrollRow+e&&(this.scrollRow=n-e+1),this.scrollRow=Math.max(0,Math.min(this.scrollRow,Math.max(0,this.rows-e))),this.cellsLayer.y=-this.scrollRow*this.cellSize;let r=Q();if(this.pickupHighlight.clear(),this.pickedUp!==null){let{x:e,y:t}=this.cellRect(this.pickedUp);this.pickupHighlight.rect(e,t,this.cellSize,this.cellSize).stroke({color:r.color.textHighlight,width:2})}if(this.highlight.clear(),this.selection.length>0){let{x:e,y:n}=this.cellRect(t);this.highlight.rect(e,n,this.cellSize,this.cellSize).fill({color:r.color.selection})}}},GM=class{constructor(e){if(this.onChange=new p,this.currentTabIndex=0,this.currentQuery=``,this.rows_=[],this.currentSelectedIndex=0,this.detail=!1,e.tabs.length===0)throw Error(`TabbedList needs at least one tab`);this.tabList=[...e.tabs],this.rowsFor=e.rowsFor,this.pageSize=Math.max(0,Math.floor(e.pageSize??0)),this.labelOf=e.label??(e=>String(e)),this.filterOf=e.filter??((e,t)=>t===``||this.labelOf(e).toLowerCase().includes(t.toLowerCase())),this.disabledOf=e.disabled??(()=>!1),this.recompute()}get tabs(){return this.tabList}get tab(){return this.tabList[this.currentTabIndex]}get query(){return this.currentQuery}get rows(){return this.rows_}get pageCount(){return this.pageSize<=0?1:Math.max(1,Math.ceil(this.rows_.length/this.pageSize))}get page(){return this.pageSize<=0?0:Math.floor(this.currentSelectedIndex/this.pageSize)}get pageRows(){if(this.pageSize<=0)return this.rows_;let e=this.page*this.pageSize;return this.rows_.slice(e,e+this.pageSize)}get selectedIndex(){return this.currentSelectedIndex}get selected(){return this.rows_[this.currentSelectedIndex]??null}get detailOpen(){return this.detail}selectTab(e){let t=this.tabList.findIndex(t=>t.id===e);t===-1||this.tabList[t].disabled||t!==this.currentTabIndex&&(this.currentTabIndex=t,this.recompute(),this.emit())}nextTab(e=1){if(e===0)return;let t=e>0?1:-1,n=this.currentTabIndex;for(let r=0;r<Math.abs(e);r++)do n=(n+t+this.tabList.length)%this.tabList.length;while(this.tabList[n].disabled&&n!==this.currentTabIndex);n!==this.currentTabIndex&&(this.currentTabIndex=n,this.recompute(),this.emit())}setQuery(e){e!==this.currentQuery&&(this.currentQuery=e,this.recompute(),this.emit())}move(e){if(e===0||this.rows_.length===0)return;let t=e>0?1:-1,n=this.currentSelectedIndex;for(let r=0;r<Math.abs(e);r++){let e=n;do e+=t;while(e>=0&&e<this.rows_.length&&this.disabledOf(this.rows_[e]));if(e<0||e>=this.rows_.length)break;n=e}n!==this.currentSelectedIndex&&(this.currentSelectedIndex=n,this.emit())}setPage(e){let t=Math.max(0,Math.min(this.pageCount-1,Math.floor(e)));if(this.pageSize<=0)return;let n=this.firstSelectableOnPage(t);n!==this.currentSelectedIndex&&(this.currentSelectedIndex=n,this.emit())}nextPage(e){this.setPage(this.page+e)}openDetail(){return this.selected===null||this.disabledOf(this.selected)?!1:(this.detail||(this.detail=!0,this.emit()),!0)}closeDetail(){this.detail&&(this.detail=!1,this.emit())}firstSelectableOnPage(e){let t=e*this.pageSize,n=Math.min(this.rows_.length,t+this.pageSize);for(let e=t;e<n;e++)if(!this.disabledOf(this.rows_[e]))return e;return Math.min(t,Math.max(0,this.rows_.length-1))}firstSelectable(e){for(let t=e;t<this.rows_.length;t++)if(!this.disabledOf(this.rows_[t]))return t;return 0}recompute(){let e=this.rowsFor(this.tab.id).filter(e=>this.filterOf(e,this.currentQuery));this.rows_=e,this.currentSelectedIndex=e.length===0?0:this.firstSelectable(0),this.detail=!1}emit(){this.onChange.dispatch()}};function KM(e,t,n={}){let r={},i=t.replace(/\r/g,``).split(`
1334
+ `),a=null,o=``,s=[],c=!1,l=()=>{if(a){if(r[a]!==void 0)throw Error(`Duplicate FTL message: ${a}`);if(s.length){if(!c)throw Error(`FTL select expression is not closed: ${a}`);let t=o.trim().match(/^\{\s*\$([\w-]+)\s*->\s*$/)?.[1];if(!t)throw Error(`Invalid FTL selector: ${o}`);r[a]=JM(e,t,s)}else r[a]=qM(o);a=null,o=``,s=[],c=!1}};for(let e of i){if(!e.trim()||e.trimStart().startsWith(`#`))continue;let t=e.match(/^([\w-]+)\s*=\s*(.*)$/);if(t){l(),a=t[1],o=t[2];continue}if(!a)throw Error(`FTL continuation has no message: ${e}`);if(e.trim()===`}`){if(!s.length||c)throw Error(`Unexpected FTL select terminator: ${e}`);c=!0;continue}if(c)throw Error(`FTL content follows a closed select expression: ${e}`);let n=e.match(/^\s*(\*)?\[([^\]]+)\]\s*(.*)$/);if(n){s.push({key:n[2],value:n[3],default:!!n[1]});continue}if(/^\s+/.test(e)){s.length?s[s.length-1].value+=` ${e.trim()}`:o+=` ${e.trim()}`;continue}throw Error(`Invalid FTL line: ${e}`)}return l(),{locale:e,direction:n.direction??(/^(ar|he|fa|ur)(?:-|$)/i.test(e)?`rtl`:`ltr`),messages:r}}function qM(e){return e.replace(/\{\s*\$([\w-]+)\s*(?:!([sra]))?\s*(?::\s*([^{}]*?))?\s*\}/g,(e,t,n,r)=>`{${t}${n?`!${n}`:``}${r===void 0?``:`:${r.trim()}`}}`).trim()}function JM(e,t,n){let r=n.filter(e=>e.default);if(r.length!==1)throw Error(`FTL select expressions need exactly one default variant`);let i=r[0],a=new Intl.PluralRules(e);return{format(e={}){let r=e[t],o=n.find(e=>e.key===String(r)),s=typeof r==`number`?a.select(r):``;return qM((o??n.find(e=>e.key===s)??i).value)}}}function YM(e,t,n={}){let r=n.domain??`messages`,i=r===`messages`?``:`${r}:`,a={},o=t.replace(/\r\n?/g,`
1335
1335
  `).split(`
1336
- `),s=null,c=()=>{if(s){if(s.id===void 0){if(s.str!==void 0||s.plurals.size>0||s.context!==void 0)throw Error(`PO entry has a translation but no msgid`);s=null;return}l(s),s=null}},l=t=>{let n=t.id;if(n===``)return;if(t.plural!==void 0&&t.plurals.size===0)throw Error(`PO message "${n}" has a plural but no msgstr[N] forms`);let r=i+(t.context?`${t.context}\u0004${n}`:n);if(a[r]!==void 0)throw Error(`Duplicate PO message: ${r}`);if(t.plurals.size>0){if([...t.plurals.values()].every(e=>e===``))return;let i=new Intl.PluralRules(e).resolvedOptions().pluralCategories,o={};for(let[r,a]of[...t.plurals].sort((e,t)=>e[0]-t[0])){let t=i[r];if(t===void 0)throw Error(`PO message "${n}" has plural form ${r}, but ${e} declares only ${i.length}`);o[t]=a}a[r]=o;return}t.str!==void 0&&t.str!==``&&(a[r]=t.str)};for(let e=0;e<o.length;e++){let t=o[e],n=t.trim();if(n===``){c();continue}if(n.startsWith(`#`))continue;let r=t.match(/^(msgctxt|msgid_plural|msgid|msgstr(?:\[(\d+)\])?)\s+(.*)$/);if(!r)throw Error(`Invalid PO line ${e+1}: ${t}`);let i=r[1],a=r[2]===void 0?void 0:Number(r[2]),l=HM(o,e,r[3]);if(e=l.next-1,s?(i===`msgctxt`||i===`msgid`)&&s.id!==void 0&&(c(),s={plurals:new Map}):s={plurals:new Map},i===`msgctxt`)s.context=l.text;else if(i===`msgid`)s.id=l.text;else if(i===`msgid_plural`)s.plural=l.text;else if(i===`msgstr`)s.str=l.text;else if(a!==void 0)s.plurals.set(a,l.text);else throw Error(`Invalid PO keyword on line ${e+1}: ${i}`)}return c(),{locale:e,direction:n.direction??(/^(ar|he|fa|ur)(?:-|$)/i.test(e)?`rtl`:`ltr`),messages:a}}function HM(e,t,n){if(!n.trim().startsWith(`"`))throw Error(`PO string must start with a quote on line ${t+1}: ${n}`);let r=UM(n.trim(),t),i=t+1;for(;i<e.length&&e[i].trim().startsWith(`"`);)r+=UM(e[i].trim(),i),i++;return{text:r,next:i}}function UM(e,t){let n=e.match(/^"((?:[^"\\]|\\.)*)"/);if(!n)throw Error(`Invalid PO string on line ${t+1}: ${e}`);return WM(n[1])}function WM(e){return e.replace(/\\(.)/g,(e,t)=>{switch(t){case`n`:return`
1337
- `;case`t`:return` `;case`r`:return`\r`;case`"`:return`"`;case`\\`:return`\\`;case`a`:return`\x07`;case`b`:return`\b`;case`f`:return`\f`;case`v`:return`\v`;default:return t}})}var GM=/\{sound:([^{}\r\n]+)\}/g;function KM(e){let t=[],n=``,r=0,i;for(GM.lastIndex=0;(i=GM.exec(e))!==null;){n+=e.slice(r,i.index);let a=i[1].trim();a===``?n+=i[0]:t.push({path:a,index:n.length}),r=i.index+i[0].length}return n+=e.slice(r),{text:n,cues:t}}function qM(e){return KM(e).text}function JM(){return{format(e,t){let n=e.params;if(t===`audio`){let t=`${e.type}.audio`;return lP(t)?ZN(t,n):``}let r=`${e.type}.${t}`;return lP(r)?QN(r,n):QN(e.type,n)}}}function YM(e,t){return new Intl.NumberFormat(YN(),t).format(e)}function XM(e,t){return new Intl.DateTimeFormat(YN(),t).format(e)}function ZM(e,t){return new Intl.ListFormat(YN(),t).format(e)}var QM=/\{(?!sound:)(\w+)(=)?(?:!([sra]))?(?::([^{}]*))?\}/g;function $M(e){let t=[];QM.lastIndex=0;let n=0,r;for(;(r=QM.exec(e))!==null;){r.index>n&&t.push(e.slice(n,r.index));let i=r[1],a=r[3],o=r[4];t.push({raw:r[0],token:i,debug:r[2]===`=`,conv:a,spec:o}),n=r.index+r[0].length}return n<e.length&&t.push(e.slice(n)),t}function eN(e){return`${e.debug?`=`:``}${e.conv?`!${e.conv}`:``}${e.spec===void 0?``:`:${e.spec}`}`}function tN(e,t){let n=new Map,r=new Map;for(let t of $M(e))typeof t!=`string`&&n.set(t.token,eN(t));for(let e of $M(t))typeof e!=`string`&&r.set(e.token,eN(e));return{missing:[...n.keys()].filter(e=>!r.has(e)),extra:[...r.keys()].filter(e=>!n.has(e)),changed:[...n].flatMap(([e,t])=>{let n=r.get(e);return n!==void 0&&n!==t?[{token:e,base:t,target:n}]:[]})}}var nN=/^(?:(.)?([<>=^]))?([+\- ])?(z)?(#)?(0)?(\d+)?([,_])?(?:\.(\d+))?([bcdeEfFgGnosxX%])?$/,rN={b:2,o:8,x:16,X:16},iN={b:`0b`,o:`0o`,x:`0x`,X:`0X`},aN=new Set([`f`,`F`,`e`,`E`,`g`,`G`,`%`,`n`]);function oN(e){return Number.isNaN(e)?`nan`:e===1/0?`inf`:e===-1/0?`-inf`:Object.is(e,-0)?`-0.0`:String(e)}function sN(e,t,n=3,r=`\\d`){return e.replace(RegExp(`\\B(?=(${r}{${n}})+(?!${r}))`,`g`),t)}function cN(e,t){let n=/^(\d+)/.exec(e);return n?sN(n[1],t)+e.slice(n[1].length):e}function lN(e,t,n,r){if(e.length>=t)return e;let i=n.repeat(t-e.length);return r===`<`?e+i:r===`^`?i.slice(0,Math.floor(i.length/2))+e+i.slice(Math.floor(i.length/2)):i+e}function uN(e){return e.replace(/([eE][+-])(\d)$/,`$10$2`)}function dN(e,t,n,r,i){let a=t===0?1:t;if(e===0)return r?`0.${`0`.repeat(a-1)}`:`0`;let o=Math.floor(Math.log10(e)),s;return o>=-4&&o<(i??a)?(s=e.toFixed(a-1-o),r||(s=s.replace(/(\.\d*?)0+$/,`$1`).replace(/\.$/,``))):(s=uN(e.toExponential(a-1)),r||(s=s.replace(/(\.\d*?)0+(e|$)/,`$1$2`).replace(/\.e/i,`e`))),n?s.toUpperCase():s}function fN(e){let t=`,`,n=`.`;for(let r of new Intl.NumberFormat(e).formatToParts(1000.5))r.type===`group`&&(t=r.value),r.type===`decimal`&&(n=r.value);return{group:t,decimal:n}}function pN(e,t,n,r,i,a){return lN(a===void 0?e:e.slice(0,a),i,t??(r?`0`:` `),n??`<`)}function mN(e,t,n=`en`){if(t===``)return typeof e==`number`?oN(e):e;let r=nN.exec(t);if(!r)return;let[i,a,o,s,c,l,u,d,f,p]=r.slice(1),m=f===void 0?void 0:Number(f),h=u===void 0?0:Number(u);if(typeof e==`string`)return o||s||c||d||a===`=`||p!==void 0&&p!==`s`?void 0:pN(e,i,a,l,h,m);if(p===`s`)return;if(p===`c`){if(o||c||l||d||m!==void 0)return;let t=Math.trunc(e);return t<0||t>1114111?void 0:lN(String.fromCodePoint(t),h,i??` `,a??`>`)}if(!Number.isFinite(e)){if(p!==void 0&&!aN.has(p))return;let t=Number.isNaN(e)?`nan`:`inf`;return(p===`F`||p===`E`||p===`G`)&&(t=t.toUpperCase()),p===`%`&&(t+=`%`),lN((e<0?`-`:o===`+`?`+`:o===` `?` `:``)+t,h,i??` `,a??`>`)}let g=e<0||Object.is(e,-0);s&&e===0&&(g=!1);let _=Math.abs(e),v=d===`,`?`,`:d===`_`?`_`:``,y;if(p===void 0){if(m!==void 0){if(Number.isInteger(_))return;y=dN(_,m,!1,!!c,m-1)}else y=oN(_);v&&(y=cN(y,v))}else if(p===`d`){if(m!==void 0||!Number.isInteger(_))return;y=String(Math.trunc(_)),v&&(y=sN(y,v))}else if(p in rN){if(m!==void 0||!Number.isInteger(_)||d===`,`)return;y=Math.trunc(_).toString(rN[p]),p===`X`&&(y=y.toUpperCase()),v&&(y=sN(y,v,4,`[0-9a-fA-F]`)),c&&(y=iN[p]+y)}else if(p===`n`){if(d||m!==void 0&&Number.isInteger(_))return;if(Number.isInteger(_))y=new Intl.NumberFormat(n).format(Math.trunc(_));else{let{group:e,decimal:t}=fN(n),r=dN(_,m??6,!1,!!c),i=r.split(`e`)[0],a=r.slice(i.length);y=cN(i,e).replace(`.`,t)+a}}else if(p===`f`||p===`F`)y=_.toFixed(m??6),v&&(y=cN(y,v));else if(p===`e`||p===`E`)y=uN(_.toExponential(m??6)),p===`E`&&(y=y.toUpperCase()),v&&(y=cN(y,v));else if(p===`g`||p===`G`)y=dN(_,m??6,p===`G`,!!c),v&&(y=cN(y,v));else{let e=_*100;y=(Number.isFinite(e)?e.toFixed(m??6):`inf`)+`%`,v&&Number.isFinite(e)&&(y=cN(y,v))}let b=g?`-`:o===`+`?`+`:o===` `?` `:``,x=i??(l&&!a?`0`:` `),S=a??(l&&!a?`=`:`>`);return S===`=`?b+lN(y,h-b.length,x,`>`):lN(b+y,h,x,S)}function hN(e,t){let n=new Set(Object.keys(e.messages)),r=new Set(Object.keys(t.messages));return{missing:[...n].filter(e=>!r.has(e)),extra:[...r].filter(e=>!n.has(e))}}function gN(e){let t=[];for(let[n,r]of Object.entries(e.messages)){if(typeof r==`string`){r===``&&t.push({key:n,kind:`empty-message`,detail:`message resolves to an empty string`});continue}_N(r)&&r.other===void 0&&t.push({key:n,kind:`plural-missing-other`,detail:`plural forms have no "other" branch`})}return t}function _N(e){return typeof e==`object`&&!!e&&!(`format`in e)}function vN(e){let t=[];for(let[n,r]of Object.entries(e.messages))n.endsWith(`.audio`)&&(typeof r==`string`?r===``&&t.push({key:n,kind:`empty-audio-path`,detail:`an empty audio entry already means "no sound"; remove the key instead`}):t.push({key:n,kind:`audio-not-a-path`,detail:`an audio entry must be a plain path string, not plural forms or a select message`}));return t}function yN(e){if(typeof e==`string`)return e;if(typeof e==`object`&&e&&`format`in e)try{return e.format()}catch{return``}let t=e;return t.other??Object.values(t)[0]??``}function bN(e,t){if(e===t)return 0;if(e.length===0)return t.length;if(t.length===0)return e.length;let n=Array.from({length:t.length+1},(e,t)=>t),r=Array(t.length+1);for(let i=1;i<=e.length;i++){r[0]=i;for(let a=1;a<=t.length;a++){let o=e[i-1]===t[a-1]?0:1;r[a]=Math.min(n[a]+1,r[a-1]+1,n[a-1]+o)}[n,r]=[r,n]}return n[t.length]}function xN(e,t=.8){let n=Object.entries(e.messages).map(([e,t])=>[e,yN(t)]).filter(([,e])=>e.length>0),r=[];for(let e=0;e<n.length;e++)for(let i=e+1;i<n.length;i++){let[a,o]=n[e],[s,c]=n[i],l=Math.max(o.length,c.length),u=bN(o,c),d=l===0?1:1-u/l;d>=t&&r.push({a,b:s,distance:u,similarity:d})}return r.sort((e,t)=>t.similarity-e.similarity)}function SN(e,t){let n=new Set(t),r=Object.keys(e.messages),i=r.filter(e=>!n.has(e));return{totalKeys:r.length,usedKeys:r.length-i.length,unusedKeys:i}}function CN(e,t){let n=Object.keys(e.messages);if(n.length===0)return 1;let{missing:r}=hN(e,t);return(n.length-r.length)/n.length}function wN(e){let t={},n=0;for(let r of Object.values(e.messages))if(!(typeof r==`string`||typeof r==`object`&&r&&`format`in r)){n++;for(let e of Object.keys(r))t[e]=(t[e]??0)+1}return{pluralKeys:n,formsPresent:t}}function TN(e,t,n){if(!(t in e.messages))throw Error(`mergeCatalogKeys: "${t}" is not a key in this catalog`);if(!(n in e.messages))throw Error(`mergeCatalogKeys: "${n}" is not a key in this catalog`);if(t===n)throw Error(`mergeCatalogKeys: survivingKey and mergedKey must be different keys`);let r={...e.messages};return delete r[n],{...e,messages:r}}function EN(e,t){return{base:e,target:t}}var DN=`.audio`;function ON(e){return e.endsWith(DN)}function kN(e){return[...new Set([...Object.keys(e.base.messages),...Object.keys(e.target.messages)])].filter(e=>!ON(e)).sort()}function AN(e){if(e===void 0)return;let t=yN(e);return t===``?void 0:t}var jN=[`log`,`compact`,`accessibility`,`debug`];function MN(e){let t=e.lastIndexOf(`.`);if(!(t<=0||!jN.includes(e.slice(t+1))))return`${e.slice(0,t)}${DN}`}function NN(e,t){let n=e.base.messages[t],r=e.target.messages[t],i=n!==void 0&&r!==void 0?`ok`:n===void 0?`extra`:`missing`,a=[`${t}${DN}`],o=MN(t);o&&a.push(o);let s,c,l=!1;for(let t of a){let n=AN(e.target.messages[t]);if(n!==void 0){s=n,c=t;break}let r=AN(e.base.messages[t]);if(r!==void 0){s=r,c=t,l=!0;break}}return{key:t,baseText:n===void 0?``:yN(n),targetText:r===void 0?``:yN(r),status:i,sound:s,soundKey:c,soundInherited:l}}function PN(e,t){let n=`${t}${DN}`;return n in e.target.messages||n in e.base.messages?n:MN(t)??n}function FN(e,t={}){let n=t.query?.toLowerCase()??``;return kN(e).map(t=>NN(e,t)).filter(e=>!t.missingOnly||e.status===`missing`).filter(e=>n===``||e.key.toLowerCase().includes(n)||e.baseText.toLowerCase().includes(n)||e.targetText.toLowerCase().includes(n))}function IN(e,t,n){let r=e.target.messages[t]??e.base.messages[t],i=n;if(r!==void 0&&typeof r==`object`&&!(`format`in r))try{let e=JSON.parse(n);typeof e==`object`&&e&&!Array.isArray(e)&&(i=e)}catch{}return{...e,target:{...e.target,messages:{...e.target.messages,[t]:i}}}}function LN(e,t){let n=e.base.messages[t];if(n===void 0)throw Error(`copyFromBase: "${t}" is not a key in the base catalog`);return{...e,target:{...e.target,messages:{...e.target.messages,[t]:n}}}}function RN(e,t){if(!(t in e.target.messages))throw Error(`deleteTargetKey: "${t}" is not a key in the target catalog`);let n={...e.target.messages};return delete n[t],{...e,target:{...e.target,messages:n}}}function zN(e,t,n){let r={...e.target.messages},i=PN(e,t);return n===``?delete r[i]:r[i]=n,{...e,target:{...e.target,messages:r}}}function BN(e){let t=e=>({...e,messages:Object.fromEntries(Object.entries(e.messages).filter(([e])=>!ON(e)))});return CN(t(e.base),t(e.target))}function VN(e){return{base:e.target,target:e.base}}var HN=l({AUDIO_SUFFIX:()=>DN,catalogCompleteness:()=>CN,catalogUsage:()=>SN,copyFromBase:()=>LN,createCatalogFormatter:()=>JM,createEditSession:()=>EN,cueKeyFor:()=>PN,deleteTargetKey:()=>RN,diffCatalogKeys:()=>hN,diffPlaceholders:()=>tN,direction:()=>XN,findSimilarMessages:()=>xN,formatDate:()=>XM,formatList:()=>ZM,formatNumber:()=>YM,formatSpec:()=>mN,has:()=>lP,isAudioKey:()=>ON,levenshteinDistance:()=>bN,locale:()=>YN,mergeCatalogKeys:()=>TN,messageText:()=>yN,nonBreakingUnit:()=>aP,parseFTL:()=>RM,parsePo:()=>VM,parseSoundMarkers:()=>KM,pluralFormCoverage:()=>wN,reset:()=>gP,sessionCompleteness:()=>BN,sessionKeys:()=>kN,sessionRow:()=>NN,sessionRows:()=>FN,setActive:()=>JN,setBase:()=>qN,setTargetSound:()=>zN,setTargetText:()=>IN,stripSoundMarkers:()=>qM,swapSession:()=>VN,t:()=>QN,tRaw:()=>ZN,tokenizeMessage:()=>$M,typographic:()=>iP,validateCatalog:()=>gN,validateMessageAudio:()=>vN}),UN=null,WN=null,GN=null,KN=null;function qN(e){UN=e}function JN(e){WN=e,GN=e?new Intl.PluralRules(e.locale):null}function YN(){return(WN??UN)?.locale??`en`}function XN(){return(WN??UN)?.direction??`ltr`}function ZN(e,t){let n=WN?.messages[e]??UN?.messages[e];if(n===void 0)return e;let r=typeof n==`string`?n:dP(n)?n.format(t):uP(n,t?.count);return t?fP(r,t):r}function QN(e,t){if(!lP(e))return e;let n=ZN(e,t),r=(WN??UN)?.typography===!1?n:iP(n,YN());return XN()===`rtl`?`⁧${r}⁩`:r}var $N=` `,eP=`\xA0`,tP=[`Chapitre`,`Tome`,`Livre`,`Partie`,`Section`,`Article`,`Acte`,`Scène`,`Niveau`,`Manche`,`Round`,`Étape`,`Volume`,`Figure`,`Page`,`Numéro`],nP=[`Nr`,`Dr`,`Bd`,`Kap`,`Art`,`Abb`,`Str`,`Tel`],rP=[`kg`,`g`,`mg`,`t`,`km`,`m`,`cm`,`mm`,`l`,`ml`,`h`,`min`,`s`,`%`,`°C`,`€`];function iP(e,t=YN()){let n=t.split(`-`)[0].toLowerCase(),r=e;return(n===`fr`||n===`it`||n===`nl`)&&(r=r.replace(/([\p{L}])'(?=[\p{L}])/gu,`$1’`)),n===`fr`&&(r=oP(r)),n===`de`&&(r=sP(r)),r}function aP(e,t,n=YN()){let r=n.split(`-`)[0].toLowerCase();return`${e}${r===`fr`?$N:r===`de`?eP:` `}${t}`}function oP(e){let t=e.replace(/\s?([;!?])/g,`${$N}$1`).replace(/«\s?/g,`«${$N}`).replace(/\s?»/g,`${$N}»`);t=t.replace(/(?<!\{soun)(\p{L})\s?:/gu,`$1${$N}:`);let n=RegExp(`\\b(${tP.join(`|`)})\\s+(?=\\d)`,`g`);return t.replace(n,`$1${eP}`)}function sP(e){let t=RegExp(`(\\d)\\s+(?=(?:${rP.map(cP).join(`|`)})(?![\\p{L}\\p{N}]))`,`gu`),n=RegExp(`\\b(${nP.join(`|`)})\\.\\s+`,`g`);return e.replace(t,`$1${eP}`).replace(n,`$1.${eP}`)}function cP(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function lP(e){return WN?.messages[e]!==void 0||UN?.messages[e]!==void 0}function uP(e,t){return t===void 0?e.other??Object.values(e)[0]??``:e[(GN??(KN??=new Intl.PluralRules(`en`))).select(t)]??e.other??``}function dP(e){return`format`in e}function fP(e,t){return $M(e).map(e=>typeof e==`string`?e:pP(e,t)).join(``)}function pP(e,t){let n=t[e.token];if(n===void 0)return e.raw;try{let t=e.conv===void 0?n:mP(n,e.conv),r=e.spec===void 0?String(t):mN(t,e.spec,YN());return r===void 0?e.raw:e.debug?`${e.token}=${r}`:r}catch{return e.raw}}function mP(e,t){if(t===`s`)return String(e);if(typeof e==`number`){let n=mN(e,``,`en`)??String(e);return t===`a`?hP(n):n}let n=`'${e.replace(/\\/g,`\\\\`).replace(/'/g,`\\'`).replace(/\n/g,`\\n`).replace(/\r/g,`\\r`).replace(/\t/g,`\\t`)}'`;return t===`a`?hP(n):n}function hP(e){let t=``;for(let n of e){let e=n.codePointAt(0)??0;t+=e>127?e>65535?`\\U${e.toString(16).padStart(8,`0`)}`:`\\u${e.toString(16).padStart(4,`0`)}`:n}return t}function gP(){UN=null,WN=null,GN=null}var _P=class extends MM{constructor(e){super({width:e.width,height:e.height,modal:!0,closable:!1,dims:e.dims,anchor:e.anchor??`bottom`}),this.pageIndex=0,this.reveal=Gj(0),this.pageText=``,this.pageCues=[],this.nextCue=0,this.portrait=null,this.portraitLayer=new G,this.choiceList=null,this.finished=!1,this.autoAdvanceElapsed=0,this.messageThemeListener=()=>this.restyleMessage(),this.pages=e.pages.map(e=>typeof e==`string`?{text:e}:e),this.speed=e.speed??40,this.mode=e.mode??`adv`,this.autoAdvance=e.autoAdvance,this.choices=e.choices??[],this.onDone=e.onDone??null,this.onSound=e.onSound??null,this.announce=e.announce??!0;let t=Q();this.content.addChild(this.portraitLayer),this.speakerLabel=new Yj({color:t.color.textHighlight,bold:!0}),this.content.addChild(this.speakerLabel),this.body=new Yj({wrapWidth:this.contentWidth}),this.content.addChild(this.body),this.prompt=new Yj({text:`▼`,color:t.color.textDim}),this.prompt.visible=!1,this.content.addChild(this.prompt),this.showPage(0),$.add(this.messageThemeListener)}restyleMessage(){let e=Q();this.speakerLabel.setColor(e.color.textHighlight),this.prompt.setColor(e.color.textDim)}destroy(e){$.remove(this.messageThemeListener),super.destroy(e)}showPage(e){let t=this.pages[e],n=Q(),r=n.direction===`rtl`;this.portraitLayer.removeChildren(),this.portrait=null;let i=0,a=this.contentWidth;t.portrait&&(this.portrait=new $s(t.portrait),r&&(this.portrait.x=this.contentWidth-this.portrait.width),this.portraitLayer.addChild(this.portrait),a=this.contentWidth-this.portrait.width-n.padding,i=r?0:this.portrait.width+n.padding),this.speakerLabel.visible=this.mode===`adv`&&t.speaker!==void 0,this.speakerLabel.x=i,this.speakerLabel.setText(t.speaker??``),this.body.x=i,this.body.y=this.mode===`adv`&&t.speaker!==void 0?this.speakerLabel.height+n.spacing:0,this.body.style.wordWrapWidth=Math.max(16,a);let o=KM(t.text);this.pageText=o.text,this.pageCues=o.cues,this.nextCue=0,this.announce&&jM.announce(t.speaker===void 0?this.pageText:`${t.speaker}: ${this.pageText}`),this.reveal=Gj(this.pageText.length,this.speed),this.autoAdvanceElapsed=0,this.playRevealedSounds(),this.renderBody(),this.prompt.visible=!1,this.prompt.x=r?0:this.contentWidth-this.prompt.width,this.prompt.y=this.contentHeight-this.prompt.height}renderBody(){if(this.mode===`adv`){this.body.setText(this.pageText.slice(0,Math.floor(this.reveal.revealed)));return}let e=this.pages.slice(0,this.pageIndex).map(e=>this.formatLine(e,KM(e.text).text)),t=this.pages[this.pageIndex];e.push(this.formatLine(t,this.pageText.slice(0,Math.floor(this.reveal.revealed)))),this.body.setText(e.join(`
1336
+ `),s=null,c=()=>{if(s){if(s.id===void 0){if(s.str!==void 0||s.plurals.size>0||s.context!==void 0)throw Error(`PO entry has a translation but no msgid`);s=null;return}l(s),s=null}},l=t=>{let n=t.id;if(n===``)return;if(t.plural!==void 0&&t.plurals.size===0)throw Error(`PO message "${n}" has a plural but no msgstr[N] forms`);let r=i+(t.context?`${t.context}\u0004${n}`:n);if(a[r]!==void 0)throw Error(`Duplicate PO message: ${r}`);if(t.plurals.size>0){if([...t.plurals.values()].every(e=>e===``))return;let i=new Intl.PluralRules(e).resolvedOptions().pluralCategories,o={};for(let[r,a]of[...t.plurals].sort((e,t)=>e[0]-t[0])){let t=i[r];if(t===void 0)throw Error(`PO message "${n}" has plural form ${r}, but ${e} declares only ${i.length}`);o[t]=a}a[r]=o;return}t.str!==void 0&&t.str!==``&&(a[r]=t.str)};for(let e=0;e<o.length;e++){let t=o[e],n=t.trim();if(n===``){c();continue}if(n.startsWith(`#`))continue;let r=t.match(/^(msgctxt|msgid_plural|msgid|msgstr(?:\[(\d+)\])?)\s+(.*)$/);if(!r)throw Error(`Invalid PO line ${e+1}: ${t}`);let i=r[1],a=r[2]===void 0?void 0:Number(r[2]),l=XM(o,e,r[3]);if(e=l.next-1,s?(i===`msgctxt`||i===`msgid`)&&s.id!==void 0&&(c(),s={plurals:new Map}):s={plurals:new Map},i===`msgctxt`)s.context=l.text;else if(i===`msgid`)s.id=l.text;else if(i===`msgid_plural`)s.plural=l.text;else if(i===`msgstr`)s.str=l.text;else if(a!==void 0)s.plurals.set(a,l.text);else throw Error(`Invalid PO keyword on line ${e+1}: ${i}`)}return c(),{locale:e,direction:n.direction??(/^(ar|he|fa|ur)(?:-|$)/i.test(e)?`rtl`:`ltr`),messages:a}}function XM(e,t,n){if(!n.trim().startsWith(`"`))throw Error(`PO string must start with a quote on line ${t+1}: ${n}`);let r=ZM(n.trim(),t),i=t+1;for(;i<e.length&&e[i].trim().startsWith(`"`);)r+=ZM(e[i].trim(),i),i++;return{text:r,next:i}}function ZM(e,t){let n=e.match(/^"((?:[^"\\]|\\.)*)"/);if(!n)throw Error(`Invalid PO string on line ${t+1}: ${e}`);return QM(n[1])}function QM(e){return e.replace(/\\(.)/g,(e,t)=>{switch(t){case`n`:return`
1337
+ `;case`t`:return` `;case`r`:return`\r`;case`"`:return`"`;case`\\`:return`\\`;case`a`:return`\x07`;case`b`:return`\b`;case`f`:return`\f`;case`v`:return`\v`;default:return t}})}var $M=/\{sound:([^{}\r\n]+)\}/g;function eN(e){let t=[],n=``,r=0,i;for($M.lastIndex=0;(i=$M.exec(e))!==null;){n+=e.slice(r,i.index);let a=i[1].trim();a===``?n+=i[0]:t.push({path:a,index:n.length}),r=i.index+i[0].length}return n+=e.slice(r),{text:n,cues:t}}function tN(e){return eN(e).text}function nN(){return{format(e,t){let n=e.params;if(t===`audio`){let t=`${e.type}.audio`;return _P(t)?aP(t,n):``}let r=`${e.type}.${t}`;return _P(r)?oP(r,n):oP(e.type,n)}}}function rN(e,t){return new Intl.NumberFormat(rP(),t).format(e)}function iN(e,t){return new Intl.DateTimeFormat(rP(),t).format(e)}function aN(e,t){return new Intl.ListFormat(rP(),t).format(e)}var oN=/\{(?!sound:)(\w+)(=)?(?:!([sra]))?(?::([^{}]*))?\}/g;function sN(e){let t=[];oN.lastIndex=0;let n=0,r;for(;(r=oN.exec(e))!==null;){r.index>n&&t.push(e.slice(n,r.index));let i=r[1],a=r[3],o=r[4];t.push({raw:r[0],token:i,debug:r[2]===`=`,conv:a,spec:o}),n=r.index+r[0].length}return n<e.length&&t.push(e.slice(n)),t}function cN(e){return`${e.debug?`=`:``}${e.conv?`!${e.conv}`:``}${e.spec===void 0?``:`:${e.spec}`}`}function lN(e,t){let n=new Map,r=new Map;for(let t of sN(e))typeof t!=`string`&&n.set(t.token,cN(t));for(let e of sN(t))typeof e!=`string`&&r.set(e.token,cN(e));return{missing:[...n.keys()].filter(e=>!r.has(e)),extra:[...r.keys()].filter(e=>!n.has(e)),changed:[...n].flatMap(([e,t])=>{let n=r.get(e);return n!==void 0&&n!==t?[{token:e,base:t,target:n}]:[]})}}var uN=/^(?:(.)?([<>=^]))?([+\- ])?(z)?(#)?(0)?(\d+)?([,_])?(?:\.(\d+))?([bcdeEfFgGnosxX%])?$/,dN={b:2,o:8,x:16,X:16},fN={b:`0b`,o:`0o`,x:`0x`,X:`0X`},pN=new Set([`f`,`F`,`e`,`E`,`g`,`G`,`%`,`n`]);function mN(e){return Number.isNaN(e)?`nan`:e===1/0?`inf`:e===-1/0?`-inf`:Object.is(e,-0)?`-0.0`:String(e)}function hN(e,t,n=3,r=`\\d`){return e.replace(RegExp(`\\B(?=(${r}{${n}})+(?!${r}))`,`g`),t)}function gN(e,t){let n=/^(\d+)/.exec(e);return n?hN(n[1],t)+e.slice(n[1].length):e}function _N(e,t,n,r){if(e.length>=t)return e;let i=n.repeat(t-e.length);return r===`<`?e+i:r===`^`?i.slice(0,Math.floor(i.length/2))+e+i.slice(Math.floor(i.length/2)):i+e}function vN(e){return e.replace(/([eE][+-])(\d)$/,`$10$2`)}function yN(e,t,n,r,i){let a=t===0?1:t;if(e===0)return r?`0.${`0`.repeat(a-1)}`:`0`;let o=Math.floor(Math.log10(e)),s;return o>=-4&&o<(i??a)?(s=e.toFixed(a-1-o),r||(s=s.replace(/(\.\d*?)0+$/,`$1`).replace(/\.$/,``))):(s=vN(e.toExponential(a-1)),r||(s=s.replace(/(\.\d*?)0+(e|$)/,`$1$2`).replace(/\.e/i,`e`))),n?s.toUpperCase():s}function bN(e){let t=`,`,n=`.`;for(let r of new Intl.NumberFormat(e).formatToParts(1000.5))r.type===`group`&&(t=r.value),r.type===`decimal`&&(n=r.value);return{group:t,decimal:n}}function xN(e,t,n,r,i,a){return _N(a===void 0?e:e.slice(0,a),i,t??(r?`0`:` `),n??`<`)}function SN(e,t,n=`en`){if(t===``)return typeof e==`number`?mN(e):e;let r=uN.exec(t);if(!r)return;let[i,a,o,s,c,l,u,d,f,p]=r.slice(1),m=f===void 0?void 0:Number(f),h=u===void 0?0:Number(u);if(typeof e==`string`)return o||s||c||d||a===`=`||p!==void 0&&p!==`s`?void 0:xN(e,i,a,l,h,m);if(p===`s`)return;if(p===`c`){if(o||c||l||d||m!==void 0)return;let t=Math.trunc(e);return t<0||t>1114111?void 0:_N(String.fromCodePoint(t),h,i??` `,a??`>`)}if(!Number.isFinite(e)){if(p!==void 0&&!pN.has(p))return;let t=Number.isNaN(e)?`nan`:`inf`;return(p===`F`||p===`E`||p===`G`)&&(t=t.toUpperCase()),p===`%`&&(t+=`%`),_N((e<0?`-`:o===`+`?`+`:o===` `?` `:``)+t,h,i??` `,a??`>`)}let g=e<0||Object.is(e,-0);s&&e===0&&(g=!1);let _=Math.abs(e),v=d===`,`?`,`:d===`_`?`_`:``,y;if(p===void 0){if(m!==void 0){if(Number.isInteger(_))return;y=yN(_,m,!1,!!c,m-1)}else y=mN(_);v&&(y=gN(y,v))}else if(p===`d`){if(m!==void 0||!Number.isInteger(_))return;y=String(Math.trunc(_)),v&&(y=hN(y,v))}else if(p in dN){if(m!==void 0||!Number.isInteger(_)||d===`,`)return;y=Math.trunc(_).toString(dN[p]),p===`X`&&(y=y.toUpperCase()),v&&(y=hN(y,v,4,`[0-9a-fA-F]`)),c&&(y=fN[p]+y)}else if(p===`n`){if(d||m!==void 0&&Number.isInteger(_))return;if(Number.isInteger(_))y=new Intl.NumberFormat(n).format(Math.trunc(_));else{let{group:e,decimal:t}=bN(n),r=yN(_,m??6,!1,!!c),i=r.split(`e`)[0],a=r.slice(i.length);y=gN(i,e).replace(`.`,t)+a}}else if(p===`f`||p===`F`)y=_.toFixed(m??6),v&&(y=gN(y,v));else if(p===`e`||p===`E`)y=vN(_.toExponential(m??6)),p===`E`&&(y=y.toUpperCase()),v&&(y=gN(y,v));else if(p===`g`||p===`G`)y=yN(_,m??6,p===`G`,!!c),v&&(y=gN(y,v));else{let e=_*100;y=(Number.isFinite(e)?e.toFixed(m??6):`inf`)+`%`,v&&Number.isFinite(e)&&(y=gN(y,v))}let b=g?`-`:o===`+`?`+`:o===` `?` `:``,x=i??(l&&!a?`0`:` `),S=a??(l&&!a?`=`:`>`);return S===`=`?b+_N(y,h-b.length,x,`>`):_N(b+y,h,x,S)}function CN(e,t){let n=new Set(Object.keys(e.messages)),r=new Set(Object.keys(t.messages));return{missing:[...n].filter(e=>!r.has(e)),extra:[...r].filter(e=>!n.has(e))}}function wN(e){let t=[];for(let[n,r]of Object.entries(e.messages)){if(typeof r==`string`){r===``&&t.push({key:n,kind:`empty-message`,detail:`message resolves to an empty string`});continue}TN(r)&&r.other===void 0&&t.push({key:n,kind:`plural-missing-other`,detail:`plural forms have no "other" branch`})}return t}function TN(e){return typeof e==`object`&&!!e&&!(`format`in e)}function EN(e){let t=[];for(let[n,r]of Object.entries(e.messages))n.endsWith(`.audio`)&&(typeof r==`string`?r===``&&t.push({key:n,kind:`empty-audio-path`,detail:`an empty audio entry already means "no sound"; remove the key instead`}):t.push({key:n,kind:`audio-not-a-path`,detail:`an audio entry must be a plain path string, not plural forms or a select message`}));return t}function DN(e){if(typeof e==`string`)return e;if(typeof e==`object`&&e&&`format`in e)try{return e.format()}catch{return``}let t=e;return t.other??Object.values(t)[0]??``}function ON(e,t){if(e===t)return 0;if(e.length===0)return t.length;if(t.length===0)return e.length;let n=Array.from({length:t.length+1},(e,t)=>t),r=Array(t.length+1);for(let i=1;i<=e.length;i++){r[0]=i;for(let a=1;a<=t.length;a++){let o=e[i-1]===t[a-1]?0:1;r[a]=Math.min(n[a]+1,r[a-1]+1,n[a-1]+o)}[n,r]=[r,n]}return n[t.length]}function kN(e,t=.8){let n=Object.entries(e.messages).map(([e,t])=>[e,DN(t)]).filter(([,e])=>e.length>0),r=[];for(let e=0;e<n.length;e++)for(let i=e+1;i<n.length;i++){let[a,o]=n[e],[s,c]=n[i],l=Math.max(o.length,c.length),u=ON(o,c),d=l===0?1:1-u/l;d>=t&&r.push({a,b:s,distance:u,similarity:d})}return r.sort((e,t)=>t.similarity-e.similarity)}function AN(e,t){let n=new Set(t),r=Object.keys(e.messages),i=r.filter(e=>!n.has(e));return{totalKeys:r.length,usedKeys:r.length-i.length,unusedKeys:i}}function jN(e,t){let n=Object.keys(e.messages);if(n.length===0)return 1;let{missing:r}=CN(e,t);return(n.length-r.length)/n.length}function MN(e){let t={},n=0;for(let r of Object.values(e.messages))if(!(typeof r==`string`||typeof r==`object`&&r&&`format`in r)){n++;for(let e of Object.keys(r))t[e]=(t[e]??0)+1}return{pluralKeys:n,formsPresent:t}}function NN(e,t,n){if(!(t in e.messages))throw Error(`mergeCatalogKeys: "${t}" is not a key in this catalog`);if(!(n in e.messages))throw Error(`mergeCatalogKeys: "${n}" is not a key in this catalog`);if(t===n)throw Error(`mergeCatalogKeys: survivingKey and mergedKey must be different keys`);let r={...e.messages};return delete r[n],{...e,messages:r}}function PN(e,t){return{base:e,target:t}}var FN=`.audio`;function IN(e){return e.endsWith(FN)}function LN(e){return[...new Set([...Object.keys(e.base.messages),...Object.keys(e.target.messages)])].filter(e=>!IN(e)).sort()}function RN(e){if(e===void 0)return;let t=DN(e);return t===``?void 0:t}var zN=[`log`,`compact`,`accessibility`,`debug`];function BN(e){let t=e.lastIndexOf(`.`);if(!(t<=0||!zN.includes(e.slice(t+1))))return`${e.slice(0,t)}${FN}`}function VN(e,t){let n=e.base.messages[t],r=e.target.messages[t],i=n!==void 0&&r!==void 0?`ok`:n===void 0?`extra`:`missing`,a=[`${t}${FN}`],o=BN(t);o&&a.push(o);let s,c,l=!1;for(let t of a){let n=RN(e.target.messages[t]);if(n!==void 0){s=n,c=t;break}let r=RN(e.base.messages[t]);if(r!==void 0){s=r,c=t,l=!0;break}}return{key:t,baseText:n===void 0?``:DN(n),targetText:r===void 0?``:DN(r),status:i,sound:s,soundKey:c,soundInherited:l}}function HN(e,t){let n=`${t}${FN}`;return n in e.target.messages||n in e.base.messages?n:BN(t)??n}function UN(e,t={}){let n=t.query?.toLowerCase()??``;return LN(e).map(t=>VN(e,t)).filter(e=>!t.missingOnly||e.status===`missing`).filter(e=>n===``||e.key.toLowerCase().includes(n)||e.baseText.toLowerCase().includes(n)||e.targetText.toLowerCase().includes(n))}function WN(e,t,n){let r=e.target.messages[t]??e.base.messages[t],i=n;if(r!==void 0&&typeof r==`object`&&!(`format`in r))try{let e=JSON.parse(n);typeof e==`object`&&e&&!Array.isArray(e)&&(i=e)}catch{}return{...e,target:{...e.target,messages:{...e.target.messages,[t]:i}}}}function GN(e,t){let n=e.base.messages[t];if(n===void 0)throw Error(`copyFromBase: "${t}" is not a key in the base catalog`);return{...e,target:{...e.target,messages:{...e.target.messages,[t]:n}}}}function KN(e,t){if(!(t in e.target.messages))throw Error(`deleteTargetKey: "${t}" is not a key in the target catalog`);let n={...e.target.messages};return delete n[t],{...e,target:{...e.target,messages:n}}}function qN(e,t,n){let r={...e.target.messages},i=HN(e,t);return n===``?delete r[i]:r[i]=n,{...e,target:{...e.target,messages:r}}}function JN(e){let t=e=>({...e,messages:Object.fromEntries(Object.entries(e.messages).filter(([e])=>!IN(e)))});return jN(t(e.base),t(e.target))}function YN(e){return{base:e.target,target:e.base}}var XN=l({AUDIO_SUFFIX:()=>FN,catalogCompleteness:()=>jN,catalogUsage:()=>AN,copyFromBase:()=>GN,createCatalogFormatter:()=>nN,createEditSession:()=>PN,cueKeyFor:()=>HN,deleteTargetKey:()=>KN,diffCatalogKeys:()=>CN,diffPlaceholders:()=>lN,direction:()=>iP,findSimilarMessages:()=>kN,formatDate:()=>iN,formatList:()=>aN,formatNumber:()=>rN,formatSpec:()=>SN,has:()=>_P,isAudioKey:()=>IN,levenshteinDistance:()=>ON,locale:()=>rP,mergeCatalogKeys:()=>NN,messageText:()=>DN,nonBreakingUnit:()=>pP,parseFTL:()=>KM,parsePo:()=>YM,parseSoundMarkers:()=>eN,pluralFormCoverage:()=>MN,reset:()=>wP,sessionCompleteness:()=>JN,sessionKeys:()=>LN,sessionRow:()=>VN,sessionRows:()=>UN,setActive:()=>nP,setBase:()=>tP,setTargetSound:()=>qN,setTargetText:()=>WN,stripSoundMarkers:()=>tN,swapSession:()=>YN,t:()=>oP,tRaw:()=>aP,tokenizeMessage:()=>sN,typographic:()=>fP,validateCatalog:()=>wN,validateMessageAudio:()=>EN}),ZN=null,QN=null,$N=null,eP=null;function tP(e){ZN=e}function nP(e){QN=e,$N=e?new Intl.PluralRules(e.locale):null}function rP(){return(QN??ZN)?.locale??`en`}function iP(){return(QN??ZN)?.direction??`ltr`}function aP(e,t){let n=QN?.messages[e]??ZN?.messages[e];if(n===void 0)return e;let r=typeof n==`string`?n:yP(n)?n.format(t):vP(n,t?.count);return t?bP(r,t):r}function oP(e,t){if(!_P(e))return e;let n=aP(e,t),r=(QN??ZN)?.typography===!1?n:fP(n,rP());return iP()===`rtl`?`⁧${r}⁩`:r}var sP=` `,cP=`\xA0`,lP=[`Chapitre`,`Tome`,`Livre`,`Partie`,`Section`,`Article`,`Acte`,`Scène`,`Niveau`,`Manche`,`Round`,`Étape`,`Volume`,`Figure`,`Page`,`Numéro`],uP=[`Nr`,`Dr`,`Bd`,`Kap`,`Art`,`Abb`,`Str`,`Tel`],dP=[`kg`,`g`,`mg`,`t`,`km`,`m`,`cm`,`mm`,`l`,`ml`,`h`,`min`,`s`,`%`,`°C`,`€`];function fP(e,t=rP()){let n=t.split(`-`)[0].toLowerCase(),r=e;return(n===`fr`||n===`it`||n===`nl`)&&(r=r.replace(/([\p{L}])'(?=[\p{L}])/gu,`$1’`)),n===`fr`&&(r=mP(r)),n===`de`&&(r=hP(r)),r}function pP(e,t,n=rP()){let r=n.split(`-`)[0].toLowerCase();return`${e}${r===`fr`?sP:r===`de`?cP:` `}${t}`}function mP(e){let t=e.replace(/\s?([;!?])/g,`${sP}$1`).replace(/«\s?/g,`«${sP}`).replace(/\s?»/g,`${sP}»`);t=t.replace(/(?<!\{soun)(\p{L})\s?:/gu,`$1${sP}:`);let n=RegExp(`\\b(${lP.join(`|`)})\\s+(?=\\d)`,`g`);return t.replace(n,`$1${cP}`)}function hP(e){let t=RegExp(`(\\d)\\s+(?=(?:${dP.map(gP).join(`|`)})(?![\\p{L}\\p{N}]))`,`gu`),n=RegExp(`\\b(${uP.join(`|`)})\\.\\s+`,`g`);return e.replace(t,`$1${cP}`).replace(n,`$1.${cP}`)}function gP(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function _P(e){return QN?.messages[e]!==void 0||ZN?.messages[e]!==void 0}function vP(e,t){return t===void 0?e.other??Object.values(e)[0]??``:e[($N??(eP??=new Intl.PluralRules(`en`))).select(t)]??e.other??``}function yP(e){return`format`in e}function bP(e,t){return sN(e).map(e=>typeof e==`string`?e:xP(e,t)).join(``)}function xP(e,t){let n=t[e.token];if(n===void 0)return e.raw;try{let t=e.conv===void 0?n:SP(n,e.conv),r=e.spec===void 0?String(t):SN(t,e.spec,rP());return r===void 0?e.raw:e.debug?`${e.token}=${r}`:r}catch{return e.raw}}function SP(e,t){if(t===`s`)return String(e);if(typeof e==`number`){let n=SN(e,``,`en`)??String(e);return t===`a`?CP(n):n}let n=`'${e.replace(/\\/g,`\\\\`).replace(/'/g,`\\'`).replace(/\n/g,`\\n`).replace(/\r/g,`\\r`).replace(/\t/g,`\\t`)}'`;return t===`a`?CP(n):n}function CP(e){let t=``;for(let n of e){let e=n.codePointAt(0)??0;t+=e>127?e>65535?`\\U${e.toString(16).padStart(8,`0`)}`:`\\u${e.toString(16).padStart(4,`0`)}`:n}return t}function wP(){ZN=null,QN=null,$N=null}var TP=class extends BM{constructor(e){super({width:e.width,height:e.height,modal:!0,closable:!1,dims:e.dims,anchor:e.anchor??`bottom`}),this.pageIndex=0,this.reveal=qj(0),this.pageText=``,this.pageCues=[],this.nextCue=0,this.portrait=null,this.portraitLayer=new G,this.choiceList=null,this.finished=!1,this.autoAdvanceElapsed=0,this.messageThemeListener=()=>this.restyleMessage(),this.pages=e.pages.map(e=>typeof e==`string`?{text:e}:e),this.speed=e.speed??40,this.mode=e.mode??`adv`,this.autoAdvance=e.autoAdvance,this.choices=e.choices??[],this.onDone=e.onDone??null,this.onSound=e.onSound??null,this.announce=e.announce??!0;let t=Q();this.content.addChild(this.portraitLayer),this.speakerLabel=new Zj({color:t.color.textHighlight,bold:!0}),this.content.addChild(this.speakerLabel),this.body=new Zj({wrapWidth:this.contentWidth}),this.content.addChild(this.body),this.prompt=new Zj({text:`▼`,color:t.color.textDim}),this.prompt.visible=!1,this.content.addChild(this.prompt),this.showPage(0),$.add(this.messageThemeListener)}restyleMessage(){let e=Q();this.speakerLabel.setColor(e.color.textHighlight),this.prompt.setColor(e.color.textDim)}destroy(e){$.remove(this.messageThemeListener),super.destroy(e)}showPage(e){let t=this.pages[e],n=Q(),r=n.direction===`rtl`;this.portraitLayer.removeChildren(),this.portrait=null;let i=0,a=this.contentWidth;t.portrait&&(this.portrait=new $s(t.portrait),r&&(this.portrait.x=this.contentWidth-this.portrait.width),this.portraitLayer.addChild(this.portrait),a=this.contentWidth-this.portrait.width-n.padding,i=r?0:this.portrait.width+n.padding),this.speakerLabel.visible=this.mode===`adv`&&t.speaker!==void 0,this.speakerLabel.x=i,this.speakerLabel.setText(t.speaker??``),this.body.x=i,this.body.y=this.mode===`adv`&&t.speaker!==void 0?this.speakerLabel.height+n.spacing:0,this.body.style.wordWrapWidth=Math.max(16,a);let o=eN(t.text);this.pageText=o.text,this.pageCues=o.cues,this.nextCue=0,this.announce&&zM.announce(t.speaker===void 0?this.pageText:`${t.speaker}: ${this.pageText}`),this.reveal=qj(this.pageText.length,this.speed),this.autoAdvanceElapsed=0,this.playRevealedSounds(),this.renderBody(),this.prompt.visible=!1,this.prompt.x=r?0:this.contentWidth-this.prompt.width,this.prompt.y=this.contentHeight-this.prompt.height}renderBody(){if(this.mode===`adv`){this.body.setText(this.pageText.slice(0,Math.floor(this.reveal.revealed)));return}let e=this.pages.slice(0,this.pageIndex).map(e=>this.formatLine(e,eN(e.text).text)),t=this.pages[this.pageIndex];e.push(this.formatLine(t,this.pageText.slice(0,Math.floor(this.reveal.revealed)))),this.body.setText(e.join(`
1338
1338
 
1339
- `))}formatLine(e,t){return e.speaker===void 0?t:`${e.speaker}: ${t}`}playRevealedSounds(){let e=Math.floor(this.reveal.revealed);for(;this.nextCue<this.pageCues.length&&this.pageCues[this.nextCue].index<=e;)this.onSound?.(this.pageCues[this.nextCue].path),this.nextCue++}get pageComplete(){return Jj(this.reveal)}update(e){if(!this.finished){if(!this.pageComplete){Kj(this.reveal,e),this.playRevealedSounds(),this.renderBody();return}this.prompt.visible=!this.choiceList,!(this.autoAdvance===void 0||this.choiceList)&&(this.autoAdvanceElapsed+=e,this.autoAdvanceElapsed>=this.autoAdvance&&(this.autoAdvanceElapsed=0,this.advance()))}}handleAction(e){return this.delegate?super.handleAction(e):e===`confirm`?this.pageComplete?(this.advance(),!0):(qj(this.reveal),this.playRevealedSounds(),this.renderBody(),!0):!1}advance(){if(this.pageIndex<this.pages.length-1){this.pageIndex++,this.showPage(this.pageIndex);return}if(this.choices.length>0){this.showChoices();return}this.finish(void 0)}showChoices(){let e=Q(),t=this.choices.map(e=>({text:e.text,disabled:e.disabled,value:e.value??e.text}));this.announce&&jM.announce(this.choices.map(e=>e.text).join(`, `));let n=Math.ceil(e.font.size*e.font.lineHeight)+e.spacing,r=t.length*n,i=this.body.y+this.body.height+e.padding,a=i+r-this.contentHeight;a>0&&this.grow(a),this.choiceList=new FM({width:this.contentWidth,height:r,items:t,onSelect:e=>this.finish(e.value)}),this.choiceList.y=i,this.content.addChild(this.choiceList),this.delegate=this.choiceList,this.prompt.visible=!1}grow(e){let t=this.getLocalBounds();this.resize(t.width,t.height+e),this.y=Math.max(0,this.y-e)}finish(e){this.finished||(this.finished=!0,this.onDone?.(e),this.close())}},vP=/[A-Za-z0-9]/;function yP(e,t){let{lineHeight:n,columnHeight:r}=t,i=t.rotate??vP,a=[],o=0,s=0;for(let t of e){if(t===`
1340
- `){o++,s=0;continue}s*n>=r&&(o++,s=0);let e=i.test(t),c=o===0?0:-o*n;a.push({char:t,x:e?c-n/2:c,y:e?s*n+n/2:s*n,rotate:e}),s++}return a}var bP=class extends G{constructor(e){super(),this.themeListener=e=>this.build(e),this.opts=e,this.build(Q()),$.add(this.themeListener)}build(e){this.removeChildren().forEach(e=>e.destroy());let t=this.opts.size??e.font.size,n=Math.ceil(t*e.font.lineHeight),r=yP(this.opts.text,{lineHeight:n,columnHeight:this.opts.columnHeight,rotate:this.opts.rotate});for(let n of r){let r=new CO({text:n.char,style:{fontFamily:e.font.family,fontSize:t,fill:this.opts.color??e.color.text}});n.rotate&&(r.anchor.set(.5),r.rotation=Math.PI/2),r.x=n.x,r.y=n.y,this.addChild(r)}}destroy(e){$.remove(this.themeListener),super.destroy(e)}};function xP(e,t=0,n=1){return n>t?Math.max(0,Math.min(1,(e-t)/(n-t))):0}function SP(e,t=0,n=1,r=0){let i=t+Math.max(0,Math.min(1,e))*(n-t);if(!(r>0))return i;let a=(String(r).split(`.`)[1]??``).length,o=t+Math.round((i-t)/r)*r;return Number(Math.max(t,Math.min(n,o)).toFixed(a))}var CP=class extends G{constructor(e){super(),this.onChange=new p,this.track=new Sw,this.fill=new Sw,this.knob=new Sw,this.dragging=!1,this.themeListener=()=>this.draw(),this.handleDown=e=>{this.disabled_||(this.dragging=!0,this.setFraction(this.fractionAt(this.toLocal(e.global).x)))},this.handleMove=e=>{!this.dragging||this.disabled_||this.setFraction(this.fractionAt(this.toLocal(e.global).x))},this.handleUp=()=>{this.dragging=!1},this.width_=e.width,this.height_=e.height??6,this.knobSize=e.knobSize??Math.max(12,this.height_*2),this.min=e.min??0,this.max=e.max??1,this.step=e.step??0,this.value_=this.snap(e.value??this.min),this.disabled_=e.disabled??!1,this.addChild(this.track),this.addChild(this.fill),this.addChild(this.knob),this.draw(),this.eventMode=`static`,this.cursor=`pointer`,this.on(`pointerdown`,this.handleDown),this.on(`pointermove`,this.handleMove),this.on(`pointerup`,this.handleUp),this.on(`pointerupoutside`,this.handleUp),$.add(this.themeListener)}get value(){return this.value_}get fraction(){return xP(this.value_,this.min,this.max)}get disabled(){return this.disabled_}setDisabled(e){this.disabled_=e,this.cursor=e?`default`:`pointer`,this.draw()}setValue(e){let t=this.snap(e);if(t===this.value_){this.draw();return}this.value_=t,this.draw(),this.onChange.dispatch(t)}setFraction(e){this.setValue(SP(e,this.min,this.max,this.step))}resize(e,t){this.width_=e,this.height_=t,this.draw()}get trackLength(){return Math.max(0,this.width_-this.knobSize)}snap(e){return SP(xP(e,this.min,this.max),this.min,this.max,this.step)}fractionAt(e){return this.trackLength>0?Math.max(0,Math.min(1,(e-this.knobSize/2)/this.trackLength)):0}draw(){let e=Q(),t=this.disabled_?e.color.textDim:e.color.textHighlight,n=e.color.panelFill,r=(this.knobSize-this.height_)/2;this.track.clear().roundRect(0,r,this.width_,this.height_,this.height_/2).fill({color:n});let i=this.knobSize/2+this.fraction*this.trackLength;this.fill.clear(),i>this.knobSize/2&&this.fill.roundRect(this.knobSize/2,r,i-this.knobSize/2,this.height_,this.height_/2).fill({color:t}),this.knob.clear().circle(i,this.knobSize/2,this.knobSize/2).fill({color:t})}destroy(e){$.remove(this.themeListener),super.destroy(e)}},wP=class extends G{constructor(e={}){super(),this.onChange=new p,this.box=new Sw,this.themeListener=()=>this.draw(),this.handleTap=()=>{this.disabled_||this.toggle()},this.size_=e.size??20,this.checked_=e.checked??!1,this.disabled_=e.disabled??!1,this.addChild(this.box),this.draw(),this.eventMode=`static`,this.cursor=`pointer`,this.on(`pointertap`,this.handleTap),$.add(this.themeListener)}get checked(){return this.checked_}get disabled(){return this.disabled_}setDisabled(e){this.disabled_=e,this.cursor=e?`default`:`pointer`,this.draw()}setChecked(e){if(e===this.checked_){this.draw();return}this.checked_=e,this.draw(),this.onChange.dispatch(e)}toggle(){this.setChecked(!this.checked_)}resize(e){this.size_=e,this.draw()}draw(){let e=Q(),t=this.disabled_?e.color.textDim:e.color.textHighlight;if(this.box.clear().roundRect(0,0,this.size_,this.size_,4).fill({color:e.color.panelFill}).stroke({color:this.disabled_?e.color.textDim:e.color.panelBorder,width:2}),this.checked_){let e=this.size_*.25;this.box.moveTo(e,this.size_*.55).lineTo(this.size_*.45,this.size_-e).lineTo(this.size_-e,e).stroke({color:t,width:Math.max(2,this.size_*.12),cap:`round`,join:`round`})}}destroy(e){$.remove(this.themeListener),super.destroy(e)}};function TP(e,t,n,r,i=1,a=!1){if(!(r>n))return n;let o=i>0?i:1,s=(String(o).split(`.`)[1]??``).length,c=Math.round((e-n)/o)+Math.round(t),l=Math.round((r-n)/o)+1,u=c;return u=a?(u%l+l)%l:Math.max(0,Math.min(l-1,u)),Number((n+u*o).toFixed(s))}var EP=class extends G{constructor(e={}){super(),this.onChange=new p,this.face=new Sw,this.themeListener=()=>this.draw(),this.handleTap=e=>{this.disabled_||(this.toLocal(e.global).y<this.height_/2?this.increment():this.decrement())},this.width_=e.width??24,this.height_=e.height??32,this.min=e.min??0,this.max=e.max??9,this.step=e.step??1,this.wrap=e.wrap??!1,this.disabled_=e.disabled??!1,this.value_=TP(e.value??this.min,0,this.min,this.max,this.step,!1),this.addChild(this.face),this.draw(),this.eventMode=`static`,this.cursor=`pointer`,this.on(`pointertap`,this.handleTap),$.add(this.themeListener)}get value(){return this.value_}get disabled(){return this.disabled_}setDisabled(e){this.disabled_=e,this.cursor=e?`default`:`pointer`,this.draw()}setValue(e){this.commit(TP(e,0,this.min,this.max,this.step,this.wrap))}increment(){this.commit(TP(this.value_,1,this.min,this.max,this.step,this.wrap))}decrement(){this.commit(TP(this.value_,-1,this.min,this.max,this.step,this.wrap))}resize(e,t){this.width_=e,this.height_=t,this.draw()}commit(e){if(e===this.value_){this.draw();return}this.value_=e,this.draw(),this.onChange.dispatch(e)}draw(){let e=Q(),t=this.disabled_?e.color.textDim:e.color.textHighlight;this.face.clear().roundRect(0,0,this.width_,this.height_,4).fill({color:e.color.panelFill}).stroke({color:e.color.panelBorder,width:1});let n=this.width_/2,r=Math.min(this.width_/4,this.height_/5);this.face.moveTo(n-r,r*1.6).lineTo(n,r*.6).lineTo(n+r,r*1.6).closePath().fill({color:t}),this.face.moveTo(n-r,this.height_-r*1.6).lineTo(n,this.height_-r*.6).lineTo(n+r,this.height_-r*1.6).closePath().fill({color:t})}destroy(e){$.remove(this.themeListener),super.destroy(e)}},DP=class{constructor(e){this.onChange=new p,this.open_=!1,this.options_=[...e.options],this.disabled_=e.disabled??!1;let t=e.selectedIndex??this.firstEnabled();this.current=this.options_[t]?.disabled?this.firstEnabled():t,this.highlight_=this.current}get options(){return this.options_}get selectedIndex(){return this.current}get selected(){return this.options_[this.current]??null}get isOpen(){return this.open_}get disabled(){return this.disabled_}get highlight(){return this.highlight_}setDisabled(e){this.disabled_=e,e&&(this.open_=!1)}setOptions(e){this.options_=[...e],this.current=this.firstEnabled(),this.highlight_=this.current,this.open_=!1}open(){this.disabled_||this.open_||(this.open_=!0,this.highlight_=this.current)}close(){this.open_=!1}toggleOpen(){this.open_?this.close():this.open()}move(e){if(!this.open_||this.options_.length===0)return;let t=this.options_.length,n=this.highlight_;for(let r=0;r<t;r++)if(n=((n+e)%t+t)%t,!this.options_[n].disabled){this.highlight_=n;return}}setHighlight(e){e<0||e>=this.options_.length||this.options_[e].disabled||(this.highlight_=e)}confirm(){if(!this.open_)return!1;let e=this.options_[this.highlight_];return!e||e.disabled?!1:(this.open_=!1,this.highlight_!==this.current&&(this.current=this.highlight_,this.onChange.dispatch({option:e,index:this.current})),!0)}cancel(){this.open_=!1,this.highlight_=this.current}firstEnabled(){let e=this.options_.findIndex(e=>!e.disabled);return e===-1?0:e}},OP=class{constructor(e={}){this.text=e.value??``,this.maxLength=e.maxLength,this.mask=e.mask??!1,this.maskCharacter=e.maskCharacter??`•`,this.caretIndex=this.text.length,this.anchor=this.caretIndex}get value(){return this.text}get maskedValue(){return this.mask?this.maskCharacter.repeat(this.text.length):this.text}get length(){return this.text.length}get caret(){return this.caretIndex}get selectionStart(){return Math.min(this.caretIndex,this.anchor)}get selectionEnd(){return Math.max(this.caretIndex,this.anchor)}get hasSelection(){return this.caretIndex!==this.anchor}get selectedText(){return this.text.slice(this.selectionStart,this.selectionEnd)}setValue(e){this.text=this.limit(e),this.caretIndex=this.text.length,this.anchor=this.caretIndex}setCaret(e,t=!1){this.caretIndex=Math.max(0,Math.min(this.text.length,e)),t||(this.anchor=this.caretIndex)}insert(e){e.length!==0&&this.replaceSelection(e)}backspace(){if(this.hasSelection){this.replaceSelection(``);return}this.caretIndex!==0&&(this.text=this.text.slice(0,this.caretIndex-1)+this.text.slice(this.caretIndex),this.setCaret(this.caretIndex-1))}deleteForward(){if(this.hasSelection){this.replaceSelection(``);return}this.caretIndex>=this.text.length||(this.text=this.text.slice(0,this.caretIndex)+this.text.slice(this.caretIndex+1),this.setCaret(this.caretIndex))}moveCaret(e,t=!1){this.setCaret(this.caretIndex+e,t)}moveToStart(e=!1){this.setCaret(0,e)}moveToEnd(e=!1){this.setCaret(this.text.length,e)}selectAll(){this.anchor=0,this.caretIndex=this.text.length}clearSelection(){this.anchor=this.caretIndex}replaceSelection(e){let t=this.selectionStart,n=this.selectionEnd,r=this.text.slice(0,t)+this.text.slice(n),i=this.maxLength!==void 0&&r.length+e.length>this.maxLength?e.slice(0,Math.max(0,this.maxLength-r.length)):e;this.text=this.text.slice(0,t)+i+this.text.slice(n),this.setCaret(t+i.length)}limit(e){return this.maxLength!==void 0&&e.length>this.maxLength?e.slice(0,this.maxLength):e}},kP=class{constructor(e){this.onChange=new p,this.current=0,this.sortKey_=null,this.ascending=!0,this.columns_=[...e.columns],this.rows_=[...e.rows??[]],this.pageSize_=e.pageSize??0,this.disabledOf=e.disabled??(()=>!1),this.current=this.firstEnabled()}get columns(){return this.columns_}get rows(){return this.rows_}get pageSize(){return this.pageSize_}get sortKey(){return this.sortKey_}get sortAscending(){return this.ascending}get selectedIndex(){return this.current}get selected(){return this.rows_[this.current]??null}get page(){return this.pageSize_>0?Math.floor(this.current/this.pageSize_):0}get pageCount(){return this.pageSize_>0?Math.max(1,Math.ceil(this.rows_.length/this.pageSize_)):1}get pageRows(){if(this.pageSize_<=0)return this.rows_;let e=this.page*this.pageSize_;return this.rows_.slice(e,e+this.pageSize_)}setRows(e){this.rows_=[...e],this.current=this.firstEnabled(),this.onChange.dispatch()}setColumns(e){this.columns_=[...e],this.sortKey_&&!this.columns_.some(e=>e.key===this.sortKey_)&&(this.sortKey_=null),this.onChange.dispatch()}setPageSize(e){this.pageSize_=Math.max(0,e),this.onChange.dispatch()}sortBy(e){let t=this.columns_.find(t=>t.key===e);if(!t)return;this.sortKey_===e?this.ascending=!this.ascending:(this.sortKey_=e,this.ascending=!0);let n=t.compare??((t,n)=>jP(AP(t,e),AP(n,e)));this.rows_.sort((e,t)=>(this.ascending?1:-1)*n(e,t)),this.current=this.firstEnabled(),this.onChange.dispatch()}select(e){e<0||e>=this.rows_.length||this.disabledOf(this.rows_[e])||(this.current=e,this.onChange.dispatch())}move(e){let t=this.rows_.length;if(t===0)return;let n=this.current;for(let r=0;r<t;r++){if(n+=e,n<0||n>=t)return;if(!this.disabledOf(this.rows_[n])){this.current=n,this.onChange.dispatch();return}}}setPage(e){if(this.pageSize_<=0)return;let t=Math.max(0,Math.min(this.pageCount-1,e))*this.pageSize_,n=Math.min(t+this.pageSize_,this.rows_.length);for(let e=t;e<n;e++)if(!this.disabledOf(this.rows_[e])){this.current=e,this.onChange.dispatch();return}}nextPage(e=1){this.setPage(this.page+e)}firstEnabled(){let e=this.rows_.findIndex(e=>!this.disabledOf(e));return e===-1?0:e}};function AP(e,t){return e&&typeof e==`object`?e[t]:void 0}function jP(e,t){return e===t?0:e===void 0?-1:t===void 0?1:typeof e==`number`&&typeof t==`number`?e-t:String(e).localeCompare(String(t))}var MP=class{constructor(e){this.onChange=new p,this.expanded=new Set,this.current=0,this.roots_=e.roots;for(let t of e.expanded??[])this.expanded.add(t);this.disabledOf=e.disabled??(()=>!1),this.current=this.firstEnabled()}get roots(){return this.roots_}get rows(){let e=[],t=(n,r)=>{for(let i of n){let n=(i.children?.length??0)>0,a=n&&this.expanded.has(i.id);e.push({node:i,depth:r,expanded:a,hasChildren:n}),a&&t(i.children,r+1)}};return t(this.roots_,0),e}get selectedIndex(){return this.current}get selected(){return this.rows[this.current]?.node??null}isExpanded(e){return this.expanded.has(e)}expand(e){this.expanded.has(e)||(this.expanded.add(e),this.onChange.dispatch())}collapse(e){if(!this.expanded.has(e))return;let t=this.rows[this.current]?.node.id;if(this.expanded.delete(e),t!==void 0&&!this.rows.some(e=>e.node.id===t)){let t=this.rows.findIndex(t=>t.node.id===e);t>=0&&(this.current=t)}this.onChange.dispatch()}toggle(e){this.expanded.has(e)?this.collapse(e):this.expand(e)}expandAll(){let e=t=>{for(let n of t)n.children?.length&&(this.expanded.add(n.id),e(n.children))};e(this.roots_),this.onChange.dispatch()}collapseAll(){this.expanded.clear(),this.select(0),this.onChange.dispatch()}select(e){let t=this.rows[e];!t||this.disabledOf(t.node)||(this.current=e,this.onChange.dispatch())}move(e){let t=this.rows.length;if(t===0)return;let n=this.current;for(let r=0;r<t;r++){if(n+=e,n<0||n>=t)return;if(!this.disabledOf(this.rows[n].node)){this.current=n,this.onChange.dispatch();return}}}firstEnabled(){let e=this.rows.findIndex(e=>!this.disabledOf(e.node));return e===-1?0:e}};function NP(e,t,n){return Math.max(0,Math.min(Math.max(0,t-n),e))}var PP=class extends G{constructor(e){super(),this.onChange=new p,this.content=new G,this.maskShape=new Sw,this.track=new Sw,this.thumb=new Sw,this.themeListener=()=>this.draw(),this.handleWheel=e=>{this.scrollBy(e.deltaY)},this.width_=e.width,this.height_=e.height,this.contentHeight_=Math.max(0,e.contentHeight??0),this.offset_=NP(e.offset??0,this.contentHeight_,this.height_),this.addChild(this.content),this.addChild(this.maskShape),this.addChild(this.track),this.addChild(this.thumb),this.content.mask=this.maskShape,this.eventMode=`static`,this.on(`wheel`,this.handleWheel),this.draw(),$.add(this.themeListener)}get offset(){return this.offset_}get contentHeight(){return this.contentHeight_}get viewportHeight(){return this.height_}get maxOffset(){return Math.max(0,this.contentHeight_-this.height_)}get scrollable(){return this.maxOffset>0}setContentHeight(e){this.contentHeight_=Math.max(0,e),this.setOffset(NP(this.offset_,this.contentHeight_,this.height_))}resize(e,t){this.width_=e,this.height_=t,this.setOffset(NP(this.offset_,this.contentHeight_,this.height_))}scrollBy(e){this.setOffset(NP(this.offset_+e,this.contentHeight_,this.height_))}scrollTo(e){this.setOffset(NP(e,this.contentHeight_,this.height_))}scrollIntoView(e,t){e<this.offset_?this.scrollTo(e):e+t>this.offset_+this.height_&&this.scrollTo(e+t-this.height_)}setOffset(e){if(e===this.offset_){this.draw();return}this.offset_=e,this.draw(),this.onChange.dispatch(e)}draw(){let e=Q();if(this.content.y=-this.offset_,this.maskShape.clear().rect(0,0,this.width_,this.height_).fill({color:16777215}),this.track.clear(),this.thumb.clear(),!this.scrollable)return;let t=this.width_-6;this.track.roundRect(t,0,6,this.height_,3).fill({color:e.color.panelFill});let n=Math.max(6,this.height_/this.contentHeight_*this.height_),r=this.offset_/this.maxOffset*(this.height_-n);this.thumb.roundRect(t,r,6,n,3).fill({color:e.color.textHighlight})}destroy(e){$.remove(this.themeListener),super.destroy(e)}};function FP(e){switch(e){case`top`:case`bottom`:return{x:.5,y:e===`top`?0:1};case`left`:case`right`:return{x:e===`left`?0:1,y:.5};case`top-left`:return{x:0,y:0};case`top-right`:return{x:1,y:0};case`bottom-left`:return{x:0,y:1};case`bottom-right`:return{x:1,y:1};default:return{x:.5,y:.5}}}function IP(e,t,n={width:0,height:0}){let r=e.margin??0,i=t.x+r,a=t.y+r,o=Math.max(0,t.width-r*2),s=Math.max(0,t.height-r*2);if(e.anchor===`fill`){let t=i+(e.offsetX??0),n=a+(e.offsetY??0);return{x:t,y:n,width:e.width??Math.max(0,i+o-t),height:e.height??Math.max(0,a+s-n)}}let c=FP(e.anchor??`center`),l=e.alignX??c.x,u=e.alignY??c.y,d=e.width??n.width,f=e.height??n.height;return{x:i+l*Math.max(0,o-d)+(e.offsetX??0),y:a+u*Math.max(0,s-f)+(e.offsetY??0),width:d,height:f}}var LP=class{constructor(e){this.spec=e}get columns(){return this.spec.columns}get rows(){return this.spec.rows}columnSizes(e){return RP(this.spec.columns,e,this.gap)}rowSizes(e){return RP(this.spec.rows,e,this.gap)}rect(e,t,n,r={}){let i=this.columnSizes(n.width),a=this.rowSizes(n.height),o=r.columnSpan??1,s=r.rowSpan??1;return{x:n.x+BP(i,t,this.gap),y:n.y+BP(a,e,this.gap),width:VP(i,t,o,this.gap),height:VP(a,e,s,this.gap)}}get gap(){return this.spec.gap??0}};function RP(e,t,n){let r=n*Math.max(0,e.length-1),i=Math.max(0,t-r),a=e.reduce((e,t)=>e+(t.size??0),0),o=e.reduce((e,t)=>e+(t.grow??0),0),s=Math.max(0,i-a),c=0;return e.map((t,n)=>{if(t.size!==void 0)return t.size;if(!t.grow||o===0)return 0;let r=n===zP(e)?s-c:Math.floor(s*t.grow/o);return c+=r,r})}function zP(e){for(let t=e.length-1;t>=0;t--)if(e[t].grow)return t;return-1}function BP(e,t,n){let r=0;for(let i=0;i<t&&i<e.length;i++)r+=e[i]+n;return r}function VP(e,t,n,r){let i=0;for(let a=t;a<t+n&&a<e.length;a++)i+=e[a],a>t&&(i+=r);return Math.max(0,i)}var HP=[`idle`,`hover`,`pressed`,`disabled`,`selected`,`focused`],UP=class e{constructor(){this.map=new Map}static{this.ANY=`*`}define(e,t,n){let r=this.map.get(e)??{};r[t]={...r[t],...n},this.map.set(e,r)}has(e){return this.map.has(e)}widgets(){return[...this.map.keys()]}resolve(t,n=`idle`){return this.map.get(t)?.[n]??this.map.get(t)?.idle??this.map.get(e.ANY)?.[n]??this.map.get(e.ANY)?.idle??{}}statesOf(e){let t=this.map.get(e);return t?HP.filter(e=>t[e]!==void 0):[]}static from(t){let n=new e;for(let[e,r]of Object.entries(t))if(WP(r))for(let t of HP){let i=r[t];i&&n.define(e,t,i)}else n.define(e,`idle`,r);return n}};function WP(e){return HP.some(t=>e[t]!==void 0)}var GP=class extends G{constructor(e){super(),this.capturing=null,this.onKeyCaptured=e=>this.capturing?(e.preventDefault(),e.code===`Escape`?this.cancelCapture():this.finishCapture(this.capturing,e.code),!0):!1,this.actions=[...e.actions],this.labelFor=e.label??(e=>e),this.onConflict=e.onConflict??(()=>!0),this.list=new FM({width:e.width,height:e.height,rowHeight:e.rowHeight,items:this.rows()}),this.addChild(this.list)}rows(){return this.actions.map(e=>({text:this.rowText(e),value:e,disabled:this.capturing!==null&&this.capturing!==e}))}rowText(e){if(this.capturing===e)return`${this.labelFor(e)}: press a key...`;let t=ze(e);return`${this.labelFor(e)}: ${t.length?t.join(`, `):`(unbound)`}`}refresh(){let e=this.list.selectedIndex;this.list.setItems(this.rows()),this.list.select(e)}startCapture(e){this.capturing=e,this.refresh(),queueMicrotask(()=>{this.capturing===e&&we.add(this.onKeyCaptured)})}cancelCapture(){we.remove(this.onKeyCaptured),this.capturing=null,this.refresh()}finishCapture(e,t){we.remove(this.onKeyCaptured),this.capturing=null;let n=Le(t).filter(t=>t!==e);if(n.length>0&&!this.onConflict(t,e,n)){this.refresh();return}for(let e of n)Fe(e,ze(e).filter(e=>e!==t));Fe(e,[t]),this.refresh()}get isCapturing(){return this.capturing!==null}handleAction(e){if(this.capturing)return!0;if(e===`confirm`){let e=this.list.selected?.value;return e&&this.startCapture(e),!0}return this.list.handleAction(e)}destroy(e){we.remove(this.onKeyCaptured),super.destroy(e)}},KP=class e extends G{constructor(t){super(),this.onClick=new p,this.onPress=new p,this.onRelease=new p,this.state=`idle`,this.themeListener=()=>this.draw(),this.width_=t.width,this.height_=t.height,this.disabled_=t.disabled??!1,this.skin=t.skin,this.labelOptions=t.label??{};let n=Q();this.background=e.createBackground(this.skin,n),this.addChild(this.background),this.icon=t.icon??null,this.icon&&this.addChild(this.icon),this.labelText=t.text===void 0?null:new Yj({align:`center`,...this.labelOptions,text:t.text}),this.labelText&&this.addChild(this.labelText),t.onClick&&this.onClick.add(t.onClick),t.onPress&&this.onPress.add(t.onPress),t.onRelease&&this.onRelease.add(t.onRelease),this.eventMode=`static`,this.on(`pointerover`,()=>this.setState(`hover`)),this.on(`pointerout`,()=>this.setState(`idle`)),this.on(`pointerdown`,()=>{this.setState(`pressed`),this.onPress.dispatch()}),this.on(`pointerup`,()=>{let e=this.state===`pressed`;this.setState(`hover`),e&&(this.onRelease.dispatch(),this.onClick.dispatch())}),this.on(`pointerupoutside`,()=>{let e=this.state===`pressed`;this.setState(`idle`),e&&this.onRelease.dispatch()}),this.setState(this.disabled_?`disabled`:`idle`),$.add(this.themeListener)}static createBackground(e,t){return e?new OM(e.texture,{border:e.border}):t.panel?new OM(t.panel,{border:t.panelBorder}):new Sw}resize(e,t){this.width_=e,this.height_=t,this.draw()}setText(e){e===void 0?(this.labelText?.destroy(),this.labelText=null):this.labelText?this.labelText.setText(e):(this.labelText=new Yj({align:`center`,...this.labelOptions,text:e}),this.addChild(this.labelText)),this.layoutContent()}get disabled(){return this.disabled_}setDisabled(e){this.disabled_=e,this.setState(e?`disabled`:`idle`)}setState(e){this.disabled_&&e!==`disabled`||(this.state=e,this.cursor=this.disabled_?`default`:`pointer`,this.eventMode=this.disabled_?`none`:`static`,this.draw())}layoutContent(){let e=Q().direction===`rtl`;if(this.icon&&!this.labelText){this.icon.x=Math.round((this.width_-this.icon.width)/2),this.icon.y=Math.round((this.height_-this.icon.height)/2);return}if(this.icon&&this.labelText){let t=Q().spacing,n=this.icon.width+t+this.labelText.width,r=Math.round((this.width_-n)/2);this.icon.x=e?r+this.labelText.width+t:r,this.icon.y=Math.round((this.height_-this.icon.height)/2),this.labelText.x=e?r:r+this.icon.width+t,this.labelText.y=Math.round((this.height_-this.labelText.height)/2);return}this.labelText&&(this.labelText.x=Math.round((this.width_-this.labelText.width)/2),this.labelText.y=Math.round((this.height_-this.labelText.height)/2))}draw(){let e=Q(),t=this.state===`pressed`?10066329:this.state===`hover`?14540253:this.state===`disabled`?7829367:16777215;if(this.background instanceof OM)this.background.resize(this.width_,this.height_),this.background.tint=this.skin?.tints?.[this.state]??t;else{let t=this.state===`pressed`?e.color.selection:e.color.panelFill;this.background.clear().roundRect(0,0,this.width_,this.height_,4).fill({color:t,alpha:this.state===`disabled`?.5:1}).stroke({color:e.color.panelBorder,width:1})}this.labelText?.setColor(this.disabled_?e.color.textDim:this.labelOptions.color??e.color.text),this.icon&&(this.icon.alpha=this.disabled_?.4:1),this.layoutContent()}destroy(e){$.remove(this.themeListener),super.destroy(e)}},qP=class extends G{constructor(e){super(),this.track=new Sw,this.fill=new Sw,this.themeListener=()=>this.draw(),this.width_=e.width,this.height_=e.height,this.explicitColor=e.color!==void 0,this.fillColor=e.color??Q().color.textHighlight,this.fraction=JP((e.value??1)/(e.max??1)),this.fillTexture=e.fillTexture,this.backgroundTexture=e.backgroundTexture,this.background_=e.background,this.roundUpToPixel=e.roundUpToPixel??!1,this.addChild(this.track),this.addChild(this.fill),this.draw(),$.add(this.themeListener)}get value(){return this.fraction}setValue(e,t=1){this.fraction=JP(t>0?e/t:0),this.draw()}get color(){return this.fillColor}setColor(e){this.explicitColor=!0,this.fillColor=e,this.draw()}get background(){return this.background_??Q().color.panelFill}resize(e,t){this.width_=e,this.height_=t,this.draw()}draw(){let e=Q();if(this.explicitColor||(this.fillColor=e.color.textHighlight),this.track.clear().rect(0,0,this.width_,this.height_),this.track.fill(this.backgroundTexture?{texture:this.backgroundTexture}:{color:this.background}),this.fill.clear(),this.fraction>0){let t=this.width_*this.fraction,n=this.roundUpToPixel?Math.ceil(t):t,r=e.direction===`rtl`?this.width_-n:0;this.fill.rect(r,0,n,this.height_),this.fill.fill(this.fillTexture?this.explicitColor?{texture:this.fillTexture,color:this.fillColor}:{texture:this.fillTexture}:{color:this.fillColor})}}destroy(e){$.remove(this.themeListener),super.destroy(e)}};function JP(e){return Math.max(0,Math.min(1,e))}function YP(e,t){return t<=0?1-e:t>=1||e<=t?1:1-(e-t)/(1-t)}function XP(e,t,n=!1){return n||e<=0?0:-t*e}function ZP(e,t,n){return n<=0?e:Math.max(e,Math.min(n,t))}var QP=class extends G{constructor(e){super(),this.rising=new G,this.elapsed=0,this.done=!1,this.duration=e.duration??.8,this.rise=e.rise??24,this.hold=Math.min(1,Math.max(0,e.hold??0));let t=new Yj({text:e.text,color:e.color,size:e.size});t.anchor.set(.5),this.rising.addChild(t),this.addChild(this.rising)}get finished(){return this.done}get riseOffset(){return this.rising.y}ageAtLeast(e){this.elapsed=ZP(this.elapsed,this.duration,e)}update(e){if(this.done)return;this.elapsed=Math.min(this.duration,this.elapsed+e);let t=this.duration>0?this.elapsed/this.duration:1;this.rising.y=XP(t,this.rise,xn()),this.alpha=YP(t,this.hold),t>=1&&(this.done=!0,this.parent?.removeChild(this),this.destroy({children:!0}))}},$P=4;function eF(e){return Math.max(0,e)/5}function tF(e,t,n=4){let r=t.y-t.height/2;return e.y+e.height/2+n<=r?e.y:r-e.height/2-n}function nF(e,t,n=4){let r=[];if(t.key===void 0)return r;let i=t;for(let a=e.length-1;a>=0;a--){let o=e[a];if(o.key!==t.key)continue;let s=tF(o,i,n);if(s===o.y)break;r.push({index:a,y:s,ageAtLeast:eF(r.length+1)}),i={...o,y:s}}return r}var rF=class extends G{constructor(...e){super(...e),this.live=[]}push(e){let t=new QP({text:e.text,color:e.color,size:e.size,duration:e.duration,rise:e.rise,hold:e.hold});e.scale!==void 0&&t.scale.set(e.scale);let n={key:e.key,x:e.x,y:e.y,height:t.height};for(let e of nF(this.live.map(e=>e.entry),n)){let t=this.live[e.index];t.entry.y=e.y,t.popup.y=e.y,t.popup.ageAtLeast(e.ageAtLeast)}return t.position.set(e.x,e.y),this.addChild(t),this.live.push({popup:t,entry:n}),t}update(e){for(let{popup:t}of this.live)t.update(e);for(let e=this.live.length-1;e>=0;e--)this.live[e].popup.finished&&this.live.splice(e,1)}get count(){return this.live.length}clear(){for(let{popup:e}of this.live)this.removeChild(e),e.destroy({children:!0});this.live.length=0}},iF=class extends G{constructor(e={}){super(),this.queue=[],this.current=null,this.phase=`fadeIn`,this.elapsed=0,this.fadeIn=e.fadeIn??.25,this.hold=e.hold??1,this.fadeOut=e.fadeOut??1.75,this.scaleFrom=e.scaleFrom??2}show(e){this.queue.push(e),this.current||this.start(this.queue.shift())}get isBusy(){return this.current!==null||this.queue.length>0}start(e){this.current=e,this.phase=`fadeIn`,this.elapsed=0,this.addChild(e),e.alpha=this.fadeIn>0?0:1,e.scale.set(this.fadeIn>0?this.scaleFrom:1)}update(e){let t=this.current;if(!t)return;if(this.elapsed+=e,this.phase===`fadeIn`){let e=this.fadeIn,n=e>0?Math.min(1,this.elapsed/e):1,r=Dn.easeOutCubic(n);t.alpha=r,t.scale.set(this.scaleFrom+(1-this.scaleFrom)*r),n>=1&&this.advance();return}if(this.phase===`hold`){this.elapsed>=this.hold&&this.advance();return}let n=this.fadeOut,r=n>0?Math.min(1,this.elapsed/n):1;t.alpha=1-r,r>=1&&this.finish()}advance(){this.phase=this.phase===`fadeIn`?`hold`:`fadeOut`,this.elapsed=0}finish(){let e=this.current;if(!e)return;this.removeChild(e),e.destroy({children:!0}),this.current=null;let t=this.queue.shift();t&&this.start(t)}},aF=class extends G{constructor(e={}){super(),this.viewWidth=0,this.viewHeight=0,this.panelWidth=0,this.panelHeight=0,this.pending=null,this.waited=0,this.delay=e.delay??.4,this.maxWidth=e.maxWidth??200,this.offsetX=e.offset?.x??12,this.offsetY=e.offset?.y??16,this.margin=e.margin??4,this.panel=new MM({width:0,height:0,modal:!1,closable:!1,dims:!1}),this.body=new Yj({text:``,wrapWidth:this.maxWidth}),this.panel.content.addChild(this.body),this.addChild(this.panel),this.visible=!1}setViewport(e,t){this.viewWidth=e,this.viewHeight=t,this.visible&&this.place()}hover(e,t,n){if(this.pending&&this.pending.text===e){this.pending.x=t,this.pending.y=n,this.visible&&this.place();return}this.pending={text:e,x:t,y:n},this.waited=0,this.visible=!1}leave(){this.pending=null,this.waited=0,this.visible=!1}get isShowing(){return this.visible}get text(){return this.pending?.text??null}get panelPosition(){return{x:this.panel.x,y:this.panel.y}}get size(){return{width:this.panelWidth,height:this.panelHeight}}update(e){if(!this.pending||this.visible||(this.waited+=e,this.waited<this.delay))return!1;this.body.setText(this.pending.text);let t=Q(),n=(t.panel?t.panelBorder:2)+t.padding,r=this.measureBody();return this.panelWidth=Math.ceil(r.width)+n*2,this.panelHeight=Math.ceil(r.height)+n*2,this.panel.resize(this.panelWidth,this.panelHeight),this.visible=!0,this.place(),!0}measureBody(){return{width:this.body.width,height:this.body.height}}place(){let e=this.pending;if(!e)return;let t=this.panelWidth,n=this.panelHeight,r=e.x+this.offsetX,i=e.y+this.offsetY;this.viewWidth>0&&(r+t+this.margin>this.viewWidth&&(r=e.x-this.offsetX-t),r=Math.max(this.margin,Math.min(r,Math.max(this.margin,this.viewWidth-t-this.margin)))),this.viewHeight>0&&(i+n+this.margin>this.viewHeight&&(i=e.y-this.offsetY-n),i=Math.max(this.margin,Math.min(i,Math.max(this.margin,this.viewHeight-n-this.margin)))),this.panel.x=r,this.panel.y=i}},oF=class extends G{constructor(e){super(),this.topics=e.topics;let t=e.listWidth??Math.floor(e.width/3),n=e.width-t-Q().spacing,r=Q().direction===`rtl`;this.list=new FM({width:t,height:e.height,items:this.topics.map(e=>({text:e.title})),onHighlight:(e,t)=>this.showBody(t),onSelect:(e,t)=>this.showBody(t)}),this.list.x=r?e.width-t:0,this.addChild(this.list),this.body=new Yj({wrapWidth:n}),this.body.x=r?0:t+Q().spacing,this.addChild(this.body),this.topics.length>0&&this.showBody(this.list.selectedIndex)}showBody(e){this.body.setText(this.topics[e]?.body??``)}handleAction(e){return this.list.handleAction(e)}},sF=class e extends G{constructor(t){super(),this.text=new Yj({text:e.format(t.stats),wrapWidth:t.width}),this.addChild(this.text)}setStats(t,n){this.text.setText(e.format(t)),n!==void 0&&(this.text.style.wordWrapWidth=n)}static format(e){return e.map(e=>`${e.label}: ${e.value}`).join(`
1341
- `)}},cF=class extends G{constructor(e){super(),this.backdrop=new Sw,this.progress=new qP({width:240,height:10,value:0}),this.width_=e.width,this.height_=e.height,this.onRetry=e.onRetry,this.onCancel=e.onCancel,this.title=new Yj({text:e.title??`Loading`,size:18,bold:!0,align:`center`}),this.status=new Yj({text:`Preparing...`,align:`center`}),this.addChild(this.backdrop,this.title,this.status,this.progress),this.layout()}setSnapshot(e){let t=e.total>0?e.completed/e.total:0;this.progress.setValue(t),e.status===`failed`?this.status.setText(`Loading failed. Retry or cancel.`):e.status===`cancelled`?this.status.setText(`Loading cancelled.`):e.status===`ready`?this.status.setText(`Ready`):this.status.setText(e.current?`Loading ${e.current}...`:`Preparing...`)}bind(e){this.setSnapshot(e.snapshot);let t=e=>this.setSnapshot(e);return e.changed.add(t),()=>e.changed.remove(t)}retry(){this.onRetry?.()}cancel(){this.onCancel?.()}resize(e,t){this.width_=e,this.height_=t,this.layout()}layout(){let e=Q().color;this.backdrop.clear().rect(0,0,this.width_,this.height_).fill({color:e.overlay,alpha:.92});let t=this.width_/2,n=this.height_/2;this.title.anchor.set(.5),this.status.anchor.set(.5),this.title.position.set(t,n-36),this.status.position.set(t,n-8),this.progress.position.set(t-120,n+16)}};function lF(e,t={}){return n=>new Promise(r=>{e.push(new _P({width:t.width??480,height:t.height??120,speed:t.speed??45,pages:[{text:n.text,speaker:n.speaker}],choices:n.choices,anchor:t.anchor??`bottom`,onDone:e=>r(e)}))})}function uF(e){let t=e/255;return t<=.03928?t/12.92:((t+.055)/1.055)**2.4}function dF(e){return .2126*uF(e>>16&255)+.7152*uF(e>>8&255)+.0722*uF(e&255)}function fF(e,t){let[n,r]=[dF(e),dF(t)].sort((e,t)=>t-e);return(n+.05)/(r+.05)}function pF(e,t,n=`AA`,r=!1){let i=n===`AAA`?r?4.5:7:r?3:4.5;return fF(e,t)>=i}var mF={farLeft:.12,left:.28,center:.5,right:.72,farRight:.88},hF=class extends G{constructor(e,t){super(),this.backdropLayer=new G,this.actorLayer=new G,this.backdrop=null,this.outgoingBackdrop=null,this.actors=new Map,this.definitions=new Map,this.focused=null,this.tweener=new On,this.dimAmount=.45,this.stageWidth=e,this.stageHeight=t,this.addChild(this.backdropLayer),this.addChild(this.actorLayer)}defineCharacter(e,t){this.definitions.set(e,t)}resize(e,t){this.stageWidth=e,this.stageHeight=t;for(let e of[this.backdrop,this.outgoingBackdrop])e&&this.fitBackdrop(e);for(let e of this.actors.values())this.placeActor(e)}setBackdrop(e,t=.4){this.outgoingBackdrop?.destroy();let n=this.backdrop;this.outgoingBackdrop=n;let r=new $s(e);this.fitBackdrop(r),this.backdrop=r,this.backdropLayer.addChild(r);let i=()=>{this.outgoingBackdrop===n&&(n?.destroy(),this.outgoingBackdrop=null)};return t<=0?(i(),Promise.resolve()):(r.alpha=0,this.tweener.tween(t,e=>{r.alpha=e}).then(i))}fitBackdrop(e){let t=e.texture,n=Math.max(this.stageWidth/t.width,this.stageHeight/t.height);e.scale.set(n),e.x=Math.round((this.stageWidth-t.width*n)/2),e.y=Math.round((this.stageHeight-t.height*n)/2)}show(e,t={}){let n=this.definitions.get(e);if(!n)throw Error(`no character defined as "${e}"`);let r=t.expression??Object.keys(n.expressions)[0],i=this.actors.get(e);if(i)return t.at!==void 0&&(i.slot=this.slotOf(t.at)),this.setExpression(e,r),this.placeActor(i),Promise.resolve();let a=new zk(n.sheet.get(n.expressions[r])),o={id:e,sprite:a,definition:n,slot:this.slotOf(t.at??`center`),expression:r};this.actors.set(e,o),this.actorLayer.addChild(a),this.placeActor(o),this.applyFocus();let s=t.fade??.25;return s<=0?Promise.resolve():(a.alpha=0,this.tweener.tween(s,e=>{a.alpha=e}))}hide(e,t=.25){let n=this.actors.get(e);return n?(this.actors.delete(e),this.focused===e&&(this.focused=null),this.applyFocus(),t<=0?(n.sprite.destroy(),Promise.resolve()):this.tweener.tween(t,e=>{n.sprite.alpha=1-e}).then(()=>n.sprite.destroy())):Promise.resolve()}hideAll(e=.25){return Promise.all([...this.actors.keys()].map(t=>this.hide(t,e))).then(()=>void 0)}setExpression(e,t){let n=this.actors.get(e);if(!n)return;let r=n.definition.expressions[t];if(r===void 0)throw Error(`character "${e}" has no expression "${t}"`);n.expression=t,n.sprite.texture=n.definition.sheet.get(r)}focus(e){this.focused=e,this.applyFocus()}applyFocus(){let e=Math.round(255*(1-this.dimAmount)),t=e<<16|e<<8|e;for(let e of this.actors.values()){let n=this.focused!==null&&e.id!==this.focused;e.sprite.tint=n?t:16777215}}slotOf(e){return typeof e==`number`?e:mF[e]}placeActor(e){let t=e.definition,n=(t.height??.7)*this.stageHeight,r=n/t.sheet.frameHeight;e.sprite.scale.set(r),e.sprite.x=Math.round(e.slot*this.stageWidth-t.sheet.frameWidth*r/2),e.sprite.y=Math.round((t.baseline??.92)*this.stageHeight-n)}update(e){this.tweener.update(e)}get isBusy(){return this.tweener.isBusy}},gF=class{constructor(e){this.state={answers:{}},this.cancelled=!1,this.historyLog=[],this.seenLines=new Set,this.skipSeen=!1,this.options=e}cancel(){this.cancelled=!0}get history(){return this.historyLog}async showLast(){let e=this.historyLog.at(-1);if(!e)return!1;let{windows:t}=this.options;return await new Promise(n=>{t.push(new _P({width:this.options.boxWidth??480,height:this.options.boxHeight??120,speed:0,pages:[{text:e.text,speaker:e.speaker}],dims:!1,anchor:`bottom`,onDone:()=>n()}))}),!0}async run(e){for(let t of e){if(this.cancelled)break;let e=await this.step(t);if(e!==void 0)throw Error(`a "goto ${e}" only runs inside runStory, not a straight run`)}return this.state}async runStory(e,t){if(!Object.prototype.hasOwnProperty.call(e,t))throw Error(`this story has no passage named "${t}"`);let n=e[t],r=0;for(;r<n.length&&!this.cancelled;){let t=await this.step(n[r]);if(r++,t!==void 0){if(!Object.prototype.hasOwnProperty.call(e,t))throw Error(`this story has no passage named "${t}"`);n=e[t],r=0}}return this.state}async step(e){let{stage:t}=this.options;if(`backdrop`in e){await t.setBackdrop(this.options.backdrop(e.backdrop),e.fade);return}if(`show`in e){await t.show(e.show,{at:e.at,expression:e.expression,fade:e.fade});return}if(`hide`in e){await t.hide(e.hide,e.fade);return}if(`hideAll`in e){await t.hideAll(e.fade);return}if(`expression`in e){t.setExpression(e.of,e.expression);return}if(`say`in e){await this.speak(e.say,e.as,e.speaker),this.recordHistory(e.say,e.as,e.speaker);return}if(`ask`in e){let t=await this.speak(e.ask,e.as,e.speaker,e.choices);return this.recordHistory(e.ask,e.as,e.speaker,t),e.store&&(this.state.answers[e.store]=t),e.choices.find(e=>(e.value??e.text)===t)?.goto}if(`goto`in e)return e.goto;if(`wait`in e){await new Promise(t=>setTimeout(t,e.wait*1e3));return}`call`in e&&await e.call(this.state)}recordHistory(e,t,n,r){let i=n??(t?this.options.displayName?.(t)??t:void 0);this.seenLines.add(_F(t,e)),this.historyLog.push({text:e,speaker:i,chosen:r})}speak(e,t,n,r){let{stage:i,windows:a}=this.options;i.focus(t??null);let o=n??(t?this.options.displayName?.(t)??t:void 0),s=this.skipSeen&&!r&&this.seenLines.has(_F(t,e));return new Promise(t=>{a.push(new _P({width:this.options.boxWidth??480,height:this.options.boxHeight??120,speed:s?0:this.options.speed??45,autoAdvance:s?0:void 0,mode:this.options.mode,pages:[{text:e,speaker:o}],choices:r,dims:!1,anchor:`bottom`,onDone:e=>t(e)}))})}};function _F(e,t){return`${e??``}\u0000${t}`}function vF(e){let t=yF(e);if(t.length===0)throw Error(`this twee source has no passages - passages start with ":: Name"`);let n={},r,i;for(let e of t){if(e.name===`StoryTitle`){r=e.body.trim()||void 0;continue}if(e.name===`StoryData`){i=xF(e.body);continue}if(Object.prototype.hasOwnProperty.call(n,e.name))throw Error(`this twee source defines "${e.name}" twice`);n[e.name]=SF(e.name,e.body)}let a=Object.keys(n);if(a.length===0)throw Error(`this twee source has no story passages, only StoryTitle/StoryData`);if(i!==void 0&&!Object.prototype.hasOwnProperty.call(n,i))throw Error(`StoryData starts at "${i}", which is not a passage in this file`);for(let[e,t]of Object.entries(n))for(let r of t)if(`ask`in r){for(let t of r.choices)if(t.goto!==void 0&&!Object.prototype.hasOwnProperty.call(n,t.goto))throw Error(`passage "${e}" links to "${t.goto}", which is not a passage in this file`)}return{story:n,start:i??a[0],title:r}}function yF(e){let t=[],n=null,r=[],i=()=>{n!==null&&t.push({name:n,body:r.join(`
1339
+ `))}formatLine(e,t){return e.speaker===void 0?t:`${e.speaker}: ${t}`}playRevealedSounds(){let e=Math.floor(this.reveal.revealed);for(;this.nextCue<this.pageCues.length&&this.pageCues[this.nextCue].index<=e;)this.onSound?.(this.pageCues[this.nextCue].path),this.nextCue++}get pageComplete(){return Xj(this.reveal)}update(e){if(!this.finished){if(!this.pageComplete){Jj(this.reveal,e),this.playRevealedSounds(),this.renderBody();return}this.prompt.visible=!this.choiceList,!(this.autoAdvance===void 0||this.choiceList)&&(this.autoAdvanceElapsed+=e,this.autoAdvanceElapsed>=this.autoAdvance&&(this.autoAdvanceElapsed=0,this.advance()))}}handleAction(e){return this.delegate?super.handleAction(e):e===`confirm`?this.pageComplete?(this.advance(),!0):(Yj(this.reveal),this.playRevealedSounds(),this.renderBody(),!0):!1}advance(){if(this.pageIndex<this.pages.length-1){this.pageIndex++,this.showPage(this.pageIndex);return}if(this.choices.length>0){this.showChoices();return}this.finish(void 0)}showChoices(){let e=Q(),t=this.choices.map(e=>({text:e.text,disabled:e.disabled,value:e.value??e.text}));this.announce&&zM.announce(this.choices.map(e=>e.text).join(`, `));let n=Math.ceil(e.font.size*e.font.lineHeight)+e.spacing,r=t.length*n,i=this.body.y+this.body.height+e.padding,a=i+r-this.contentHeight;a>0&&this.grow(a),this.choiceList=new UM({width:this.contentWidth,height:r,items:t,onSelect:e=>this.finish(e.value)}),this.choiceList.y=i,this.content.addChild(this.choiceList),this.delegate=this.choiceList,this.prompt.visible=!1}grow(e){let t=this.getLocalBounds();this.resize(t.width,t.height+e),this.y=Math.max(0,this.y-e)}finish(e){this.finished||(this.finished=!0,this.onDone?.(e),this.close())}},EP=/[A-Za-z0-9]/;function DP(e,t){let{lineHeight:n,columnHeight:r}=t,i=t.rotate??EP,a=[],o=0,s=0;for(let t of e){if(t===`
1340
+ `){o++,s=0;continue}s*n>=r&&(o++,s=0);let e=i.test(t),c=o===0?0:-o*n;a.push({char:t,x:e?c-n/2:c,y:e?s*n+n/2:s*n,rotate:e}),s++}return a}var OP=class extends G{constructor(e){super(),this.themeListener=e=>this.build(e),this.opts=e,this.build(Q()),$.add(this.themeListener)}build(e){this.removeChildren().forEach(e=>e.destroy());let t=this.opts.size??e.font.size,n=Math.ceil(t*e.font.lineHeight),r=DP(this.opts.text,{lineHeight:n,columnHeight:this.opts.columnHeight,rotate:this.opts.rotate});for(let n of r){let r=new CO({text:n.char,style:{fontFamily:e.font.family,fontSize:t,fill:this.opts.color??e.color.text}});n.rotate&&(r.anchor.set(.5),r.rotation=Math.PI/2),r.x=n.x,r.y=n.y,this.addChild(r)}}destroy(e){$.remove(this.themeListener),super.destroy(e)}};function kP(e,t=0,n=1){return n>t?Math.max(0,Math.min(1,(e-t)/(n-t))):0}function AP(e,t=0,n=1,r=0){let i=t+Math.max(0,Math.min(1,e))*(n-t);if(!(r>0))return i;let a=(String(r).split(`.`)[1]??``).length,o=t+Math.round((i-t)/r)*r;return Number(Math.max(t,Math.min(n,o)).toFixed(a))}var jP=class extends G{constructor(e){super(),this.onChange=new p,this.track=new Sw,this.fill=new Sw,this.knob=new Sw,this.dragging=!1,this.themeListener=()=>this.draw(),this.handleDown=e=>{this.disabled_||(this.dragging=!0,this.setFraction(this.fractionAt(this.toLocal(e.global).x)))},this.handleMove=e=>{!this.dragging||this.disabled_||this.setFraction(this.fractionAt(this.toLocal(e.global).x))},this.handleUp=()=>{this.dragging=!1},this.width_=e.width,this.height_=e.height??6,this.knobSize=e.knobSize??Math.max(12,this.height_*2),this.min=e.min??0,this.max=e.max??1,this.step=e.step??0,this.value_=this.snap(e.value??this.min),this.disabled_=e.disabled??!1,this.addChild(this.track),this.addChild(this.fill),this.addChild(this.knob),this.draw(),this.eventMode=`static`,this.cursor=`pointer`,this.on(`pointerdown`,this.handleDown),this.on(`pointermove`,this.handleMove),this.on(`pointerup`,this.handleUp),this.on(`pointerupoutside`,this.handleUp),$.add(this.themeListener)}get value(){return this.value_}get fraction(){return kP(this.value_,this.min,this.max)}get disabled(){return this.disabled_}setDisabled(e){this.disabled_=e,this.cursor=e?`default`:`pointer`,this.draw()}setValue(e){let t=this.snap(e);if(t===this.value_){this.draw();return}this.value_=t,this.draw(),this.onChange.dispatch(t)}setFraction(e){this.setValue(AP(e,this.min,this.max,this.step))}resize(e,t){this.width_=e,this.height_=t,this.draw()}get trackLength(){return Math.max(0,this.width_-this.knobSize)}snap(e){return AP(kP(e,this.min,this.max),this.min,this.max,this.step)}fractionAt(e){return this.trackLength>0?Math.max(0,Math.min(1,(e-this.knobSize/2)/this.trackLength)):0}draw(){let e=Q(),t=this.disabled_?e.color.textDim:e.color.textHighlight,n=e.color.panelFill,r=(this.knobSize-this.height_)/2;this.track.clear().roundRect(0,r,this.width_,this.height_,this.height_/2).fill({color:n});let i=this.knobSize/2+this.fraction*this.trackLength;this.fill.clear(),i>this.knobSize/2&&this.fill.roundRect(this.knobSize/2,r,i-this.knobSize/2,this.height_,this.height_/2).fill({color:t}),this.knob.clear().circle(i,this.knobSize/2,this.knobSize/2).fill({color:t})}destroy(e){$.remove(this.themeListener),super.destroy(e)}},MP=class extends G{constructor(e={}){super(),this.onChange=new p,this.box=new Sw,this.themeListener=()=>this.draw(),this.handleTap=()=>{this.disabled_||this.toggle()},this.size_=e.size??20,this.checked_=e.checked??!1,this.disabled_=e.disabled??!1,this.addChild(this.box),this.draw(),this.eventMode=`static`,this.cursor=`pointer`,this.on(`pointertap`,this.handleTap),$.add(this.themeListener)}get checked(){return this.checked_}get disabled(){return this.disabled_}setDisabled(e){this.disabled_=e,this.cursor=e?`default`:`pointer`,this.draw()}setChecked(e){if(e===this.checked_){this.draw();return}this.checked_=e,this.draw(),this.onChange.dispatch(e)}toggle(){this.setChecked(!this.checked_)}resize(e){this.size_=e,this.draw()}draw(){let e=Q(),t=this.disabled_?e.color.textDim:e.color.textHighlight;if(this.box.clear().roundRect(0,0,this.size_,this.size_,4).fill({color:e.color.panelFill}).stroke({color:this.disabled_?e.color.textDim:e.color.panelBorder,width:2}),this.checked_){let e=this.size_*.25;this.box.moveTo(e,this.size_*.55).lineTo(this.size_*.45,this.size_-e).lineTo(this.size_-e,e).stroke({color:t,width:Math.max(2,this.size_*.12),cap:`round`,join:`round`})}}destroy(e){$.remove(this.themeListener),super.destroy(e)}};function NP(e,t,n,r,i=1,a=!1){if(!(r>n))return n;let o=i>0?i:1,s=(String(o).split(`.`)[1]??``).length,c=Math.round((e-n)/o)+Math.round(t),l=Math.round((r-n)/o)+1,u=c;return u=a?(u%l+l)%l:Math.max(0,Math.min(l-1,u)),Number((n+u*o).toFixed(s))}var PP=class extends G{constructor(e={}){super(),this.onChange=new p,this.face=new Sw,this.themeListener=()=>this.draw(),this.handleTap=e=>{this.disabled_||(this.toLocal(e.global).y<this.height_/2?this.increment():this.decrement())},this.width_=e.width??24,this.height_=e.height??32,this.min=e.min??0,this.max=e.max??9,this.step=e.step??1,this.wrap=e.wrap??!1,this.disabled_=e.disabled??!1,this.value_=NP(e.value??this.min,0,this.min,this.max,this.step,!1),this.addChild(this.face),this.draw(),this.eventMode=`static`,this.cursor=`pointer`,this.on(`pointertap`,this.handleTap),$.add(this.themeListener)}get value(){return this.value_}get disabled(){return this.disabled_}setDisabled(e){this.disabled_=e,this.cursor=e?`default`:`pointer`,this.draw()}setValue(e){this.commit(NP(e,0,this.min,this.max,this.step,this.wrap))}increment(){this.commit(NP(this.value_,1,this.min,this.max,this.step,this.wrap))}decrement(){this.commit(NP(this.value_,-1,this.min,this.max,this.step,this.wrap))}resize(e,t){this.width_=e,this.height_=t,this.draw()}commit(e){if(e===this.value_){this.draw();return}this.value_=e,this.draw(),this.onChange.dispatch(e)}draw(){let e=Q(),t=this.disabled_?e.color.textDim:e.color.textHighlight;this.face.clear().roundRect(0,0,this.width_,this.height_,4).fill({color:e.color.panelFill}).stroke({color:e.color.panelBorder,width:1});let n=this.width_/2,r=Math.min(this.width_/4,this.height_/5);this.face.moveTo(n-r,r*1.6).lineTo(n,r*.6).lineTo(n+r,r*1.6).closePath().fill({color:t}),this.face.moveTo(n-r,this.height_-r*1.6).lineTo(n,this.height_-r*.6).lineTo(n+r,this.height_-r*1.6).closePath().fill({color:t})}destroy(e){$.remove(this.themeListener),super.destroy(e)}},FP=class{constructor(e){this.onChange=new p,this.open_=!1,this.options_=[...e.options],this.disabled_=e.disabled??!1;let t=e.selectedIndex??this.firstEnabled();this.current=this.options_[t]?.disabled?this.firstEnabled():t,this.highlight_=this.current}get options(){return this.options_}get selectedIndex(){return this.current}get selected(){return this.options_[this.current]??null}get isOpen(){return this.open_}get disabled(){return this.disabled_}get highlight(){return this.highlight_}setDisabled(e){this.disabled_=e,e&&(this.open_=!1)}setOptions(e){this.options_=[...e],this.current=this.firstEnabled(),this.highlight_=this.current,this.open_=!1}open(){this.disabled_||this.open_||(this.open_=!0,this.highlight_=this.current)}close(){this.open_=!1}toggleOpen(){this.open_?this.close():this.open()}move(e){if(!this.open_||this.options_.length===0)return;let t=this.options_.length,n=this.highlight_;for(let r=0;r<t;r++)if(n=((n+e)%t+t)%t,!this.options_[n].disabled){this.highlight_=n;return}}setHighlight(e){e<0||e>=this.options_.length||this.options_[e].disabled||(this.highlight_=e)}confirm(){if(!this.open_)return!1;let e=this.options_[this.highlight_];return!e||e.disabled?!1:(this.open_=!1,this.highlight_!==this.current&&(this.current=this.highlight_,this.onChange.dispatch({option:e,index:this.current})),!0)}cancel(){this.open_=!1,this.highlight_=this.current}firstEnabled(){let e=this.options_.findIndex(e=>!e.disabled);return e===-1?0:e}},IP=class{constructor(e={}){this.text=e.value??``,this.maxLength=e.maxLength,this.mask=e.mask??!1,this.maskCharacter=e.maskCharacter??`•`,this.caretIndex=this.text.length,this.anchor=this.caretIndex}get value(){return this.text}get maskedValue(){return this.mask?this.maskCharacter.repeat(this.text.length):this.text}get length(){return this.text.length}get caret(){return this.caretIndex}get selectionStart(){return Math.min(this.caretIndex,this.anchor)}get selectionEnd(){return Math.max(this.caretIndex,this.anchor)}get hasSelection(){return this.caretIndex!==this.anchor}get selectedText(){return this.text.slice(this.selectionStart,this.selectionEnd)}setValue(e){this.text=this.limit(e),this.caretIndex=this.text.length,this.anchor=this.caretIndex}setCaret(e,t=!1){this.caretIndex=Math.max(0,Math.min(this.text.length,e)),t||(this.anchor=this.caretIndex)}insert(e){e.length!==0&&this.replaceSelection(e)}backspace(){if(this.hasSelection){this.replaceSelection(``);return}this.caretIndex!==0&&(this.text=this.text.slice(0,this.caretIndex-1)+this.text.slice(this.caretIndex),this.setCaret(this.caretIndex-1))}deleteForward(){if(this.hasSelection){this.replaceSelection(``);return}this.caretIndex>=this.text.length||(this.text=this.text.slice(0,this.caretIndex)+this.text.slice(this.caretIndex+1),this.setCaret(this.caretIndex))}moveCaret(e,t=!1){this.setCaret(this.caretIndex+e,t)}moveToStart(e=!1){this.setCaret(0,e)}moveToEnd(e=!1){this.setCaret(this.text.length,e)}selectAll(){this.anchor=0,this.caretIndex=this.text.length}clearSelection(){this.anchor=this.caretIndex}replaceSelection(e){let t=this.selectionStart,n=this.selectionEnd,r=this.text.slice(0,t)+this.text.slice(n),i=this.maxLength!==void 0&&r.length+e.length>this.maxLength?e.slice(0,Math.max(0,this.maxLength-r.length)):e;this.text=this.text.slice(0,t)+i+this.text.slice(n),this.setCaret(t+i.length)}limit(e){return this.maxLength!==void 0&&e.length>this.maxLength?e.slice(0,this.maxLength):e}},LP=class{constructor(e){this.onChange=new p,this.current=0,this.sortKey_=null,this.ascending=!0,this.columns_=[...e.columns],this.rows_=[...e.rows??[]],this.pageSize_=e.pageSize??0,this.disabledOf=e.disabled??(()=>!1),this.current=this.firstEnabled()}get columns(){return this.columns_}get rows(){return this.rows_}get pageSize(){return this.pageSize_}get sortKey(){return this.sortKey_}get sortAscending(){return this.ascending}get selectedIndex(){return this.current}get selected(){return this.rows_[this.current]??null}get page(){return this.pageSize_>0?Math.floor(this.current/this.pageSize_):0}get pageCount(){return this.pageSize_>0?Math.max(1,Math.ceil(this.rows_.length/this.pageSize_)):1}get pageRows(){if(this.pageSize_<=0)return this.rows_;let e=this.page*this.pageSize_;return this.rows_.slice(e,e+this.pageSize_)}setRows(e){this.rows_=[...e],this.current=this.firstEnabled(),this.onChange.dispatch()}setColumns(e){this.columns_=[...e],this.sortKey_&&!this.columns_.some(e=>e.key===this.sortKey_)&&(this.sortKey_=null),this.onChange.dispatch()}setPageSize(e){this.pageSize_=Math.max(0,e),this.onChange.dispatch()}sortBy(e){let t=this.columns_.find(t=>t.key===e);if(!t)return;this.sortKey_===e?this.ascending=!this.ascending:(this.sortKey_=e,this.ascending=!0);let n=t.compare??((t,n)=>zP(RP(t,e),RP(n,e)));this.rows_.sort((e,t)=>(this.ascending?1:-1)*n(e,t)),this.current=this.firstEnabled(),this.onChange.dispatch()}select(e){e<0||e>=this.rows_.length||this.disabledOf(this.rows_[e])||(this.current=e,this.onChange.dispatch())}move(e){let t=this.rows_.length;if(t===0)return;let n=this.current;for(let r=0;r<t;r++){if(n+=e,n<0||n>=t)return;if(!this.disabledOf(this.rows_[n])){this.current=n,this.onChange.dispatch();return}}}setPage(e){if(this.pageSize_<=0)return;let t=Math.max(0,Math.min(this.pageCount-1,e))*this.pageSize_,n=Math.min(t+this.pageSize_,this.rows_.length);for(let e=t;e<n;e++)if(!this.disabledOf(this.rows_[e])){this.current=e,this.onChange.dispatch();return}}nextPage(e=1){this.setPage(this.page+e)}firstEnabled(){let e=this.rows_.findIndex(e=>!this.disabledOf(e));return e===-1?0:e}};function RP(e,t){return e&&typeof e==`object`?e[t]:void 0}function zP(e,t){return e===t?0:e===void 0?-1:t===void 0?1:typeof e==`number`&&typeof t==`number`?e-t:String(e).localeCompare(String(t))}var BP=class{constructor(e){this.onChange=new p,this.expanded=new Set,this.current=0,this.roots_=e.roots;for(let t of e.expanded??[])this.expanded.add(t);this.disabledOf=e.disabled??(()=>!1),this.current=this.firstEnabled()}get roots(){return this.roots_}get rows(){let e=[],t=(n,r)=>{for(let i of n){let n=(i.children?.length??0)>0,a=n&&this.expanded.has(i.id);e.push({node:i,depth:r,expanded:a,hasChildren:n}),a&&t(i.children,r+1)}};return t(this.roots_,0),e}get selectedIndex(){return this.current}get selected(){return this.rows[this.current]?.node??null}isExpanded(e){return this.expanded.has(e)}expand(e){this.expanded.has(e)||(this.expanded.add(e),this.onChange.dispatch())}collapse(e){if(!this.expanded.has(e))return;let t=this.rows[this.current]?.node.id;if(this.expanded.delete(e),t!==void 0&&!this.rows.some(e=>e.node.id===t)){let t=this.rows.findIndex(t=>t.node.id===e);t>=0&&(this.current=t)}this.onChange.dispatch()}toggle(e){this.expanded.has(e)?this.collapse(e):this.expand(e)}expandAll(){let e=t=>{for(let n of t)n.children?.length&&(this.expanded.add(n.id),e(n.children))};e(this.roots_),this.onChange.dispatch()}collapseAll(){this.expanded.clear(),this.select(0),this.onChange.dispatch()}select(e){let t=this.rows[e];!t||this.disabledOf(t.node)||(this.current=e,this.onChange.dispatch())}move(e){let t=this.rows.length;if(t===0)return;let n=this.current;for(let r=0;r<t;r++){if(n+=e,n<0||n>=t)return;if(!this.disabledOf(this.rows[n].node)){this.current=n,this.onChange.dispatch();return}}}firstEnabled(){let e=this.rows.findIndex(e=>!this.disabledOf(e.node));return e===-1?0:e}};function VP(e,t,n){return Math.max(0,Math.min(Math.max(0,t-n),e))}var HP=class extends G{constructor(e){super(),this.onChange=new p,this.content=new G,this.maskShape=new Sw,this.track=new Sw,this.thumb=new Sw,this.themeListener=()=>this.draw(),this.handleWheel=e=>{this.scrollBy(e.deltaY)},this.width_=e.width,this.height_=e.height,this.contentHeight_=Math.max(0,e.contentHeight??0),this.offset_=VP(e.offset??0,this.contentHeight_,this.height_),this.addChild(this.content),this.addChild(this.maskShape),this.addChild(this.track),this.addChild(this.thumb),this.content.mask=this.maskShape,this.eventMode=`static`,this.on(`wheel`,this.handleWheel),this.draw(),$.add(this.themeListener)}get offset(){return this.offset_}get contentHeight(){return this.contentHeight_}get viewportHeight(){return this.height_}get maxOffset(){return Math.max(0,this.contentHeight_-this.height_)}get scrollable(){return this.maxOffset>0}setContentHeight(e){this.contentHeight_=Math.max(0,e),this.setOffset(VP(this.offset_,this.contentHeight_,this.height_))}resize(e,t){this.width_=e,this.height_=t,this.setOffset(VP(this.offset_,this.contentHeight_,this.height_))}scrollBy(e){this.setOffset(VP(this.offset_+e,this.contentHeight_,this.height_))}scrollTo(e){this.setOffset(VP(e,this.contentHeight_,this.height_))}scrollIntoView(e,t){e<this.offset_?this.scrollTo(e):e+t>this.offset_+this.height_&&this.scrollTo(e+t-this.height_)}setOffset(e){if(e===this.offset_){this.draw();return}this.offset_=e,this.draw(),this.onChange.dispatch(e)}draw(){let e=Q();if(this.content.y=-this.offset_,this.maskShape.clear().rect(0,0,this.width_,this.height_).fill({color:16777215}),this.track.clear(),this.thumb.clear(),!this.scrollable)return;let t=this.width_-6;this.track.roundRect(t,0,6,this.height_,3).fill({color:e.color.panelFill});let n=Math.max(6,this.height_/this.contentHeight_*this.height_),r=this.offset_/this.maxOffset*(this.height_-n);this.thumb.roundRect(t,r,6,n,3).fill({color:e.color.textHighlight})}destroy(e){$.remove(this.themeListener),super.destroy(e)}};function UP(e){switch(e){case`top`:case`bottom`:return{x:.5,y:e===`top`?0:1};case`left`:case`right`:return{x:e===`left`?0:1,y:.5};case`top-left`:return{x:0,y:0};case`top-right`:return{x:1,y:0};case`bottom-left`:return{x:0,y:1};case`bottom-right`:return{x:1,y:1};default:return{x:.5,y:.5}}}function WP(e,t,n={width:0,height:0}){let r=e.margin??0,i=t.x+r,a=t.y+r,o=Math.max(0,t.width-r*2),s=Math.max(0,t.height-r*2);if(e.anchor===`fill`){let t=i+(e.offsetX??0),n=a+(e.offsetY??0);return{x:t,y:n,width:e.width??Math.max(0,i+o-t),height:e.height??Math.max(0,a+s-n)}}let c=UP(e.anchor??`center`),l=e.alignX??c.x,u=e.alignY??c.y,d=e.width??n.width,f=e.height??n.height;return{x:i+l*Math.max(0,o-d)+(e.offsetX??0),y:a+u*Math.max(0,s-f)+(e.offsetY??0),width:d,height:f}}var GP=class{constructor(e){this.spec=e}get columns(){return this.spec.columns}get rows(){return this.spec.rows}columnSizes(e){return KP(this.spec.columns,e,this.gap)}rowSizes(e){return KP(this.spec.rows,e,this.gap)}rect(e,t,n,r={}){let i=this.columnSizes(n.width),a=this.rowSizes(n.height),o=r.columnSpan??1,s=r.rowSpan??1;return{x:n.x+JP(i,t,this.gap),y:n.y+JP(a,e,this.gap),width:YP(i,t,o,this.gap),height:YP(a,e,s,this.gap)}}get gap(){return this.spec.gap??0}};function KP(e,t,n){let r=n*Math.max(0,e.length-1),i=Math.max(0,t-r),a=e.reduce((e,t)=>e+(t.size??0),0),o=e.reduce((e,t)=>e+(t.grow??0),0),s=Math.max(0,i-a),c=0;return e.map((t,n)=>{if(t.size!==void 0)return t.size;if(!t.grow||o===0)return 0;let r=n===qP(e)?s-c:Math.floor(s*t.grow/o);return c+=r,r})}function qP(e){for(let t=e.length-1;t>=0;t--)if(e[t].grow)return t;return-1}function JP(e,t,n){let r=0;for(let i=0;i<t&&i<e.length;i++)r+=e[i]+n;return r}function YP(e,t,n,r){let i=0;for(let a=t;a<t+n&&a<e.length;a++)i+=e[a],a>t&&(i+=r);return Math.max(0,i)}var XP=[`idle`,`hover`,`pressed`,`disabled`,`selected`,`focused`],ZP=class e{constructor(){this.map=new Map}static{this.ANY=`*`}define(e,t,n){let r=this.map.get(e)??{};r[t]={...r[t],...n},this.map.set(e,r)}has(e){return this.map.has(e)}widgets(){return[...this.map.keys()]}resolve(t,n=`idle`){return this.map.get(t)?.[n]??this.map.get(t)?.idle??this.map.get(e.ANY)?.[n]??this.map.get(e.ANY)?.idle??{}}statesOf(e){let t=this.map.get(e);return t?XP.filter(e=>t[e]!==void 0):[]}static from(t){let n=new e;for(let[e,r]of Object.entries(t))if(QP(r))for(let t of XP){let i=r[t];i&&n.define(e,t,i)}else n.define(e,`idle`,r);return n}};function QP(e){return XP.some(t=>e[t]!==void 0)}var $P=class extends G{constructor(e){super(),this.capturing=null,this.onKeyCaptured=e=>this.capturing?(e.preventDefault(),e.code===`Escape`?this.cancelCapture():this.finishCapture(this.capturing,e.code),!0):!1,this.actions=[...e.actions],this.labelFor=e.label??(e=>e),this.onConflict=e.onConflict??(()=>!0),this.list=new UM({width:e.width,height:e.height,rowHeight:e.rowHeight,items:this.rows()}),this.addChild(this.list)}rows(){return this.actions.map(e=>({text:this.rowText(e),value:e,disabled:this.capturing!==null&&this.capturing!==e}))}rowText(e){if(this.capturing===e)return`${this.labelFor(e)}: press a key...`;let t=ze(e);return`${this.labelFor(e)}: ${t.length?t.join(`, `):`(unbound)`}`}refresh(){let e=this.list.selectedIndex;this.list.setItems(this.rows()),this.list.select(e)}startCapture(e){this.capturing=e,this.refresh(),queueMicrotask(()=>{this.capturing===e&&we.add(this.onKeyCaptured)})}cancelCapture(){we.remove(this.onKeyCaptured),this.capturing=null,this.refresh()}finishCapture(e,t){we.remove(this.onKeyCaptured),this.capturing=null;let n=Le(t).filter(t=>t!==e);if(n.length>0&&!this.onConflict(t,e,n)){this.refresh();return}for(let e of n)Fe(e,ze(e).filter(e=>e!==t));Fe(e,[t]),this.refresh()}get isCapturing(){return this.capturing!==null}handleAction(e){if(this.capturing)return!0;if(e===`confirm`){let e=this.list.selected?.value;return e&&this.startCapture(e),!0}return this.list.handleAction(e)}destroy(e){we.remove(this.onKeyCaptured),super.destroy(e)}},eF=class e extends G{constructor(t){super(),this.onClick=new p,this.onPress=new p,this.onRelease=new p,this.state=`idle`,this.themeListener=()=>this.draw(),this.width_=t.width,this.height_=t.height,this.disabled_=t.disabled??!1,this.skin=t.skin,this.labelOptions=t.label??{};let n=Q();this.background=e.createBackground(this.skin,n),this.addChild(this.background),this.icon=t.icon??null,this.icon&&this.addChild(this.icon),this.labelText=t.text===void 0?null:new Zj({align:`center`,...this.labelOptions,text:t.text}),this.labelText&&this.addChild(this.labelText),t.onClick&&this.onClick.add(t.onClick),t.onPress&&this.onPress.add(t.onPress),t.onRelease&&this.onRelease.add(t.onRelease),this.eventMode=`static`,this.on(`pointerover`,()=>this.setState(`hover`)),this.on(`pointerout`,()=>this.setState(`idle`)),this.on(`pointerdown`,()=>{this.setState(`pressed`),this.onPress.dispatch()}),this.on(`pointerup`,()=>{let e=this.state===`pressed`;this.setState(`hover`),e&&(this.onRelease.dispatch(),this.onClick.dispatch())}),this.on(`pointerupoutside`,()=>{let e=this.state===`pressed`;this.setState(`idle`),e&&this.onRelease.dispatch()}),this.setState(this.disabled_?`disabled`:`idle`),$.add(this.themeListener)}static createBackground(e,t){return e?new IM(e.texture,{border:e.border}):t.panel?new IM(t.panel,{border:t.panelBorder}):new Sw}resize(e,t){this.width_=e,this.height_=t,this.draw()}setText(e){e===void 0?(this.labelText?.destroy(),this.labelText=null):this.labelText?this.labelText.setText(e):(this.labelText=new Zj({align:`center`,...this.labelOptions,text:e}),this.addChild(this.labelText)),this.layoutContent()}get disabled(){return this.disabled_}setDisabled(e){this.disabled_=e,this.setState(e?`disabled`:`idle`)}setState(e){this.disabled_&&e!==`disabled`||(this.state=e,this.cursor=this.disabled_?`default`:`pointer`,this.eventMode=this.disabled_?`none`:`static`,this.draw())}layoutContent(){let e=Q().direction===`rtl`;if(this.icon&&!this.labelText){this.icon.x=Math.round((this.width_-this.icon.width)/2),this.icon.y=Math.round((this.height_-this.icon.height)/2);return}if(this.icon&&this.labelText){let t=Q().spacing,n=this.icon.width+t+this.labelText.width,r=Math.round((this.width_-n)/2);this.icon.x=e?r+this.labelText.width+t:r,this.icon.y=Math.round((this.height_-this.icon.height)/2),this.labelText.x=e?r:r+this.icon.width+t,this.labelText.y=Math.round((this.height_-this.labelText.height)/2);return}this.labelText&&(this.labelText.x=Math.round((this.width_-this.labelText.width)/2),this.labelText.y=Math.round((this.height_-this.labelText.height)/2))}draw(){let e=Q(),t=this.state===`pressed`?10066329:this.state===`hover`?14540253:this.state===`disabled`?7829367:16777215;if(this.background instanceof IM)this.background.resize(this.width_,this.height_),this.background.tint=this.skin?.tints?.[this.state]??t;else{let t=this.state===`pressed`?e.color.selection:e.color.panelFill;this.background.clear().roundRect(0,0,this.width_,this.height_,4).fill({color:t,alpha:this.state===`disabled`?.5:1}).stroke({color:e.color.panelBorder,width:1})}this.labelText?.setColor(this.disabled_?e.color.textDim:this.labelOptions.color??e.color.text),this.icon&&(this.icon.alpha=this.disabled_?.4:1),this.layoutContent()}destroy(e){$.remove(this.themeListener),super.destroy(e)}},tF=class extends G{constructor(e){super(),this.track=new Sw,this.fill=new Sw,this.themeListener=()=>this.draw(),this.width_=e.width,this.height_=e.height,this.explicitColor=e.color!==void 0,this.fillColor=e.color??Q().color.textHighlight,this.fraction=nF((e.value??1)/(e.max??1)),this.fillTexture=e.fillTexture,this.backgroundTexture=e.backgroundTexture,this.background_=e.background,this.roundUpToPixel=e.roundUpToPixel??!1,this.addChild(this.track),this.addChild(this.fill),this.draw(),$.add(this.themeListener)}get value(){return this.fraction}setValue(e,t=1){this.fraction=nF(t>0?e/t:0),this.draw()}get color(){return this.fillColor}setColor(e){this.explicitColor=!0,this.fillColor=e,this.draw()}get background(){return this.background_??Q().color.panelFill}resize(e,t){this.width_=e,this.height_=t,this.draw()}draw(){let e=Q();if(this.explicitColor||(this.fillColor=e.color.textHighlight),this.track.clear().rect(0,0,this.width_,this.height_),this.track.fill(this.backgroundTexture?{texture:this.backgroundTexture}:{color:this.background}),this.fill.clear(),this.fraction>0){let t=this.width_*this.fraction,n=this.roundUpToPixel?Math.ceil(t):t,r=e.direction===`rtl`?this.width_-n:0;this.fill.rect(r,0,n,this.height_),this.fill.fill(this.fillTexture?this.explicitColor?{texture:this.fillTexture,color:this.fillColor}:{texture:this.fillTexture}:{color:this.fillColor})}}destroy(e){$.remove(this.themeListener),super.destroy(e)}};function nF(e){return Math.max(0,Math.min(1,e))}function rF(e,t){return t<=0?1-e:t>=1||e<=t?1:1-(e-t)/(1-t)}function iF(e,t,n=!1){return n||e<=0?0:-t*e}function aF(e,t,n){return n<=0?e:Math.max(e,Math.min(n,t))}var oF=class extends G{constructor(e){super(),this.rising=new G,this.elapsed=0,this.done=!1,this.duration=e.duration??.8,this.rise=e.rise??24,this.hold=Math.min(1,Math.max(0,e.hold??0));let t=new Zj({text:e.text,color:e.color,size:e.size});t.anchor.set(.5),this.rising.addChild(t),this.addChild(this.rising)}get finished(){return this.done}get riseOffset(){return this.rising.y}ageAtLeast(e){this.elapsed=aF(this.elapsed,this.duration,e)}update(e){if(this.done)return;this.elapsed=Math.min(this.duration,this.elapsed+e);let t=this.duration>0?this.elapsed/this.duration:1;this.rising.y=iF(t,this.rise,xn()),this.alpha=rF(t,this.hold),t>=1&&(this.done=!0,this.parent?.removeChild(this),this.destroy({children:!0}))}},sF=4;function cF(e){return Math.max(0,e)/5}function lF(e,t,n=4){let r=t.y-t.height/2;return e.y+e.height/2+n<=r?e.y:r-e.height/2-n}function uF(e,t,n=4){let r=[];if(t.key===void 0)return r;let i=t;for(let a=e.length-1;a>=0;a--){let o=e[a];if(o.key!==t.key)continue;let s=lF(o,i,n);if(s===o.y)break;r.push({index:a,y:s,ageAtLeast:cF(r.length+1)}),i={...o,y:s}}return r}var dF=class extends G{constructor(...e){super(...e),this.live=[]}push(e){let t=new oF({text:e.text,color:e.color,size:e.size,duration:e.duration,rise:e.rise,hold:e.hold});e.scale!==void 0&&t.scale.set(e.scale);let n={key:e.key,x:e.x,y:e.y,height:t.height};for(let e of uF(this.live.map(e=>e.entry),n)){let t=this.live[e.index];t.entry.y=e.y,t.popup.y=e.y,t.popup.ageAtLeast(e.ageAtLeast)}return t.position.set(e.x,e.y),this.addChild(t),this.live.push({popup:t,entry:n}),t}update(e){for(let{popup:t}of this.live)t.update(e);for(let e=this.live.length-1;e>=0;e--)this.live[e].popup.finished&&this.live.splice(e,1)}get count(){return this.live.length}clear(){for(let{popup:e}of this.live)this.removeChild(e),e.destroy({children:!0});this.live.length=0}},fF=class extends G{constructor(e={}){super(),this.queue=[],this.current=null,this.phase=`fadeIn`,this.elapsed=0,this.fadeIn=e.fadeIn??.25,this.hold=e.hold??1,this.fadeOut=e.fadeOut??1.75,this.scaleFrom=e.scaleFrom??2}show(e){this.queue.push(e),this.current||this.start(this.queue.shift())}get isBusy(){return this.current!==null||this.queue.length>0}start(e){this.current=e,this.phase=`fadeIn`,this.elapsed=0,this.addChild(e),e.alpha=this.fadeIn>0?0:1,e.scale.set(this.fadeIn>0?this.scaleFrom:1)}update(e){let t=this.current;if(!t)return;if(this.elapsed+=e,this.phase===`fadeIn`){let e=this.fadeIn,n=e>0?Math.min(1,this.elapsed/e):1,r=Dn.easeOutCubic(n);t.alpha=r,t.scale.set(this.scaleFrom+(1-this.scaleFrom)*r),n>=1&&this.advance();return}if(this.phase===`hold`){this.elapsed>=this.hold&&this.advance();return}let n=this.fadeOut,r=n>0?Math.min(1,this.elapsed/n):1;t.alpha=1-r,r>=1&&this.finish()}advance(){this.phase=this.phase===`fadeIn`?`hold`:`fadeOut`,this.elapsed=0}finish(){let e=this.current;if(!e)return;this.removeChild(e),e.destroy({children:!0}),this.current=null;let t=this.queue.shift();t&&this.start(t)}},pF=class extends G{constructor(e={}){super(),this.viewWidth=0,this.viewHeight=0,this.panelWidth=0,this.panelHeight=0,this.pending=null,this.waited=0,this.delay=e.delay??.4,this.maxWidth=e.maxWidth??200,this.offsetX=e.offset?.x??12,this.offsetY=e.offset?.y??16,this.margin=e.margin??4,this.panel=new BM({width:0,height:0,modal:!1,closable:!1,dims:!1}),this.body=new Zj({text:``,wrapWidth:this.maxWidth}),this.panel.content.addChild(this.body),this.addChild(this.panel),this.visible=!1}setViewport(e,t){this.viewWidth=e,this.viewHeight=t,this.visible&&this.place()}hover(e,t,n){if(this.pending&&this.pending.text===e){this.pending.x=t,this.pending.y=n,this.visible&&this.place();return}this.pending={text:e,x:t,y:n},this.waited=0,this.visible=!1}leave(){this.pending=null,this.waited=0,this.visible=!1}get isShowing(){return this.visible}get text(){return this.pending?.text??null}get panelPosition(){return{x:this.panel.x,y:this.panel.y}}get size(){return{width:this.panelWidth,height:this.panelHeight}}update(e){if(!this.pending||this.visible||(this.waited+=e,this.waited<this.delay))return!1;this.body.setText(this.pending.text);let t=Q(),n=(t.panel?t.panelBorder:2)+t.padding,r=this.measureBody();return this.panelWidth=Math.ceil(r.width)+n*2,this.panelHeight=Math.ceil(r.height)+n*2,this.panel.resize(this.panelWidth,this.panelHeight),this.visible=!0,this.place(),!0}measureBody(){return{width:this.body.width,height:this.body.height}}place(){let e=this.pending;if(!e)return;let t=this.panelWidth,n=this.panelHeight,r=e.x+this.offsetX,i=e.y+this.offsetY;this.viewWidth>0&&(r+t+this.margin>this.viewWidth&&(r=e.x-this.offsetX-t),r=Math.max(this.margin,Math.min(r,Math.max(this.margin,this.viewWidth-t-this.margin)))),this.viewHeight>0&&(i+n+this.margin>this.viewHeight&&(i=e.y-this.offsetY-n),i=Math.max(this.margin,Math.min(i,Math.max(this.margin,this.viewHeight-n-this.margin)))),this.panel.x=r,this.panel.y=i}},mF=class extends G{constructor(e){super(),this.topics=e.topics;let t=e.listWidth??Math.floor(e.width/3),n=e.width-t-Q().spacing,r=Q().direction===`rtl`;this.list=new UM({width:t,height:e.height,items:this.topics.map(e=>({text:e.title})),onHighlight:(e,t)=>this.showBody(t),onSelect:(e,t)=>this.showBody(t)}),this.list.x=r?e.width-t:0,this.addChild(this.list),this.body=new Zj({wrapWidth:n}),this.body.x=r?0:t+Q().spacing,this.addChild(this.body),this.topics.length>0&&this.showBody(this.list.selectedIndex)}showBody(e){this.body.setText(this.topics[e]?.body??``)}handleAction(e){return this.list.handleAction(e)}},hF=class e extends G{constructor(t){super(),this.text=new Zj({text:e.format(t.stats),wrapWidth:t.width}),this.addChild(this.text)}setStats(t,n){this.text.setText(e.format(t)),n!==void 0&&(this.text.style.wordWrapWidth=n)}static format(e){return e.map(e=>`${e.label}: ${e.value}`).join(`
1341
+ `)}},gF=class extends G{constructor(e){super(),this.backdrop=new Sw,this.progress=new tF({width:240,height:10,value:0}),this.width_=e.width,this.height_=e.height,this.onRetry=e.onRetry,this.onCancel=e.onCancel,this.title=new Zj({text:e.title??`Loading`,size:18,bold:!0,align:`center`}),this.status=new Zj({text:`Preparing...`,align:`center`}),this.addChild(this.backdrop,this.title,this.status,this.progress),this.layout()}setSnapshot(e){let t=e.total>0?e.completed/e.total:0;this.progress.setValue(t),e.status===`failed`?this.status.setText(`Loading failed. Retry or cancel.`):e.status===`cancelled`?this.status.setText(`Loading cancelled.`):e.status===`ready`?this.status.setText(`Ready`):this.status.setText(e.current?`Loading ${e.current}...`:`Preparing...`)}bind(e){this.setSnapshot(e.snapshot);let t=e=>this.setSnapshot(e);return e.changed.add(t),()=>e.changed.remove(t)}retry(){this.onRetry?.()}cancel(){this.onCancel?.()}resize(e,t){this.width_=e,this.height_=t,this.layout()}layout(){let e=Q().color;this.backdrop.clear().rect(0,0,this.width_,this.height_).fill({color:e.overlay,alpha:.92});let t=this.width_/2,n=this.height_/2;this.title.anchor.set(.5),this.status.anchor.set(.5),this.title.position.set(t,n-36),this.status.position.set(t,n-8),this.progress.position.set(t-120,n+16)}};function _F(e,t={}){return n=>new Promise(r=>{e.push(new TP({width:t.width??480,height:t.height??120,speed:t.speed??45,pages:[{text:n.text,speaker:n.speaker}],choices:n.choices,anchor:t.anchor??`bottom`,onDone:e=>r(e)}))})}function vF(e){let t=e/255;return t<=.03928?t/12.92:((t+.055)/1.055)**2.4}function yF(e){return .2126*vF(e>>16&255)+.7152*vF(e>>8&255)+.0722*vF(e&255)}function bF(e,t){let[n,r]=[yF(e),yF(t)].sort((e,t)=>t-e);return(n+.05)/(r+.05)}function xF(e,t,n=`AA`,r=!1){let i=n===`AAA`?r?4.5:7:r?3:4.5;return bF(e,t)>=i}var SF={farLeft:.12,left:.28,center:.5,right:.72,farRight:.88},CF=class extends G{constructor(e,t){super(),this.backdropLayer=new G,this.actorLayer=new G,this.backdrop=null,this.outgoingBackdrop=null,this.actors=new Map,this.definitions=new Map,this.focused=null,this.tweener=new On,this.dimAmount=.45,this.stageWidth=e,this.stageHeight=t,this.addChild(this.backdropLayer),this.addChild(this.actorLayer)}defineCharacter(e,t){this.definitions.set(e,t)}resize(e,t){this.stageWidth=e,this.stageHeight=t;for(let e of[this.backdrop,this.outgoingBackdrop])e&&this.fitBackdrop(e);for(let e of this.actors.values())this.placeActor(e)}setBackdrop(e,t=.4){this.outgoingBackdrop?.destroy();let n=this.backdrop;this.outgoingBackdrop=n;let r=new $s(e);this.fitBackdrop(r),this.backdrop=r,this.backdropLayer.addChild(r);let i=()=>{this.outgoingBackdrop===n&&(n?.destroy(),this.outgoingBackdrop=null)};return t<=0?(i(),Promise.resolve()):(r.alpha=0,this.tweener.tween(t,e=>{r.alpha=e}).then(i))}fitBackdrop(e){let t=e.texture,n=Math.max(this.stageWidth/t.width,this.stageHeight/t.height);e.scale.set(n),e.x=Math.round((this.stageWidth-t.width*n)/2),e.y=Math.round((this.stageHeight-t.height*n)/2)}show(e,t={}){let n=this.definitions.get(e);if(!n)throw Error(`no character defined as "${e}"`);let r=t.expression??Object.keys(n.expressions)[0],i=this.actors.get(e);if(i)return t.at!==void 0&&(i.slot=this.slotOf(t.at)),this.setExpression(e,r),this.placeActor(i),Promise.resolve();let a=new Bk(n.sheet.get(n.expressions[r])),o={id:e,sprite:a,definition:n,slot:this.slotOf(t.at??`center`),expression:r};this.actors.set(e,o),this.actorLayer.addChild(a),this.placeActor(o),this.applyFocus();let s=t.fade??.25;return s<=0?Promise.resolve():(a.alpha=0,this.tweener.tween(s,e=>{a.alpha=e}))}hide(e,t=.25){let n=this.actors.get(e);return n?(this.actors.delete(e),this.focused===e&&(this.focused=null),this.applyFocus(),t<=0?(n.sprite.destroy(),Promise.resolve()):this.tweener.tween(t,e=>{n.sprite.alpha=1-e}).then(()=>n.sprite.destroy())):Promise.resolve()}hideAll(e=.25){return Promise.all([...this.actors.keys()].map(t=>this.hide(t,e))).then(()=>void 0)}setExpression(e,t){let n=this.actors.get(e);if(!n)return;let r=n.definition.expressions[t];if(r===void 0)throw Error(`character "${e}" has no expression "${t}"`);n.expression=t,n.sprite.texture=n.definition.sheet.get(r)}focus(e){this.focused=e,this.applyFocus()}applyFocus(){let e=Math.round(255*(1-this.dimAmount)),t=e<<16|e<<8|e;for(let e of this.actors.values()){let n=this.focused!==null&&e.id!==this.focused;e.sprite.tint=n?t:16777215}}slotOf(e){return typeof e==`number`?e:SF[e]}placeActor(e){let t=e.definition,n=(t.height??.7)*this.stageHeight,r=n/t.sheet.frameHeight;e.sprite.scale.set(r),e.sprite.x=Math.round(e.slot*this.stageWidth-t.sheet.frameWidth*r/2),e.sprite.y=Math.round((t.baseline??.92)*this.stageHeight-n)}update(e){this.tweener.update(e)}get isBusy(){return this.tweener.isBusy}},wF=class{constructor(e){this.state={answers:{}},this.cancelled=!1,this.historyLog=[],this.seenLines=new Set,this.skipSeen=!1,this.options=e}cancel(){this.cancelled=!0}get history(){return this.historyLog}async showLast(){let e=this.historyLog.at(-1);if(!e)return!1;let{windows:t}=this.options;return await new Promise(n=>{t.push(new TP({width:this.options.boxWidth??480,height:this.options.boxHeight??120,speed:0,pages:[{text:e.text,speaker:e.speaker}],dims:!1,anchor:`bottom`,onDone:()=>n()}))}),!0}async run(e){for(let t of e){if(this.cancelled)break;let e=await this.step(t);if(e!==void 0)throw Error(`a "goto ${e}" only runs inside runStory, not a straight run`)}return this.state}async runStory(e,t){if(!Object.prototype.hasOwnProperty.call(e,t))throw Error(`this story has no passage named "${t}"`);let n=e[t],r=0;for(;r<n.length&&!this.cancelled;){let t=await this.step(n[r]);if(r++,t!==void 0){if(!Object.prototype.hasOwnProperty.call(e,t))throw Error(`this story has no passage named "${t}"`);n=e[t],r=0}}return this.state}async step(e){let{stage:t}=this.options;if(`backdrop`in e){await t.setBackdrop(this.options.backdrop(e.backdrop),e.fade);return}if(`show`in e){await t.show(e.show,{at:e.at,expression:e.expression,fade:e.fade});return}if(`hide`in e){await t.hide(e.hide,e.fade);return}if(`hideAll`in e){await t.hideAll(e.fade);return}if(`expression`in e){t.setExpression(e.of,e.expression);return}if(`say`in e){await this.speak(e.say,e.as,e.speaker),this.recordHistory(e.say,e.as,e.speaker);return}if(`ask`in e){let t=await this.speak(e.ask,e.as,e.speaker,e.choices);return this.recordHistory(e.ask,e.as,e.speaker,t),e.store&&(this.state.answers[e.store]=t),e.choices.find(e=>(e.value??e.text)===t)?.goto}if(`goto`in e)return e.goto;if(`wait`in e){await new Promise(t=>setTimeout(t,e.wait*1e3));return}`call`in e&&await e.call(this.state)}recordHistory(e,t,n,r){let i=n??(t?this.options.displayName?.(t)??t:void 0);this.seenLines.add(TF(t,e)),this.historyLog.push({text:e,speaker:i,chosen:r})}speak(e,t,n,r){let{stage:i,windows:a}=this.options;i.focus(t??null);let o=n??(t?this.options.displayName?.(t)??t:void 0),s=this.skipSeen&&!r&&this.seenLines.has(TF(t,e));return new Promise(t=>{a.push(new TP({width:this.options.boxWidth??480,height:this.options.boxHeight??120,speed:s?0:this.options.speed??45,autoAdvance:s?0:void 0,mode:this.options.mode,pages:[{text:e,speaker:o}],choices:r,dims:!1,anchor:`bottom`,onDone:e=>t(e)}))})}};function TF(e,t){return`${e??``}\u0000${t}`}function EF(e){let t=DF(e);if(t.length===0)throw Error(`this twee source has no passages - passages start with ":: Name"`);let n={},r,i;for(let e of t){if(e.name===`StoryTitle`){r=e.body.trim()||void 0;continue}if(e.name===`StoryData`){i=kF(e.body);continue}if(Object.prototype.hasOwnProperty.call(n,e.name))throw Error(`this twee source defines "${e.name}" twice`);n[e.name]=AF(e.name,e.body)}let a=Object.keys(n);if(a.length===0)throw Error(`this twee source has no story passages, only StoryTitle/StoryData`);if(i!==void 0&&!Object.prototype.hasOwnProperty.call(n,i))throw Error(`StoryData starts at "${i}", which is not a passage in this file`);for(let[e,t]of Object.entries(n))for(let r of t)if(`ask`in r){for(let t of r.choices)if(t.goto!==void 0&&!Object.prototype.hasOwnProperty.call(n,t.goto))throw Error(`passage "${e}" links to "${t.goto}", which is not a passage in this file`)}return{story:n,start:i??a[0],title:r}}function DF(e){let t=[],n=null,r=[],i=()=>{n!==null&&t.push({name:n,body:r.join(`
1342
1342
  `)})};for(let t of e.split(`
1343
- `))t.startsWith(`::`)?(i(),n=bF(t),r=[]):n!==null&&r.push(t);return i(),t}function bF(e){let t=e.slice(2).trim(),n=t.search(/[[{]/),r=(n===-1?t:t.slice(0,n)).trim();if(!r)throw Error(`a twee passage header needs a name, got "${e}"`);return r}function xF(e){let t;try{t=JSON.parse(e.trim())}catch{throw Error(`StoryData must be JSON - check the braces`)}if(typeof t!=`object`||!t||Array.isArray(t))throw Error(`StoryData must be a JSON object`);let n=t.start;if(n!==void 0&&typeof n!=`string`)throw Error(`StoryData "start" must be a passage name`);return n}function SF(e,t){let n=[],r=[];for(let i of t.split(`
1344
- `)){let t=CF(i,r,e).replace(/\s+/g,` `).trim();t!==``&&n.push(t)}if(r.length===0)return n.map(e=>({say:e}));let i=n.pop()??``;return[...n.map(e=>({say:e})),{ask:i,choices:r}]}function CF(e,t,n){let r=``,i=e;for(;;){let a=i.indexOf(`[[`);if(a===-1)return r+i;let o=i.indexOf(`]]`,a);if(o===-1)throw Error(`passage "${n}" has a "[[" with no closing "]]" in "${e.trim()}"`);r+=i.slice(0,a),t.push(wF(i.slice(a+2,o),n)),i=i.slice(o+2)}}function wF(e,t){if(e.includes(`[`)||e.includes(`]`))throw Error(`passage "${t}" links with a setter ("${e.trim()}") - story-format macros are not imported, so the link is refused rather than half-read`);let n=e.indexOf(`->`);if(n!==-1)return{text:e.slice(0,n).trim(),goto:e.slice(n+2).trim()};let r=e.indexOf(`<-`);if(r!==-1)return{text:e.slice(r+2).trim(),goto:e.slice(0,r).trim()};let i=e.trim();return{text:i,goto:i}}var TF=class{constructor(e){this.onChange=new p,this.onMusic=new p,this.index=0,this.beats=e}get length(){return this.beats.length}get position(){return this.index}get current(){return this.beats[this.index]??null}get done(){return this.beats.length===0||this.index>=this.beats.length-1}get music(){return this.current?.music??null}goTo(e){let t=Math.max(0,Math.min(this.beats.length-1,e));this.index=t,this.report()}advance(){return!this.done&&(this.goTo(this.index+1),!0)}back(){return this.index!==0&&(this.goTo(this.index-1),!0)}skip(){this.goTo(this.beats.length-1)}restart(){this.goTo(0)}report(){let e=this.current;e&&this.onChange.dispatch(e),this.onMusic.dispatch(this.music)}},EF=class extends G{constructor(e){super(),this.backdrop=new $s(U.EMPTY),this.handleAdvance=()=>{this.advance()},this.handleBeat=e=>{this.applyBeat(e)},this.sequence=e.sequence,this.textureFor=e.textureFor??(()=>null),this.playMusic=e.playMusic??(()=>{}),this.width_=e.width,this.height_=e.height,this.titleLabel=new Yj({text:``,color:Q().color.textHighlight}),this.textLabel=new Yj({text:``,wrapWidth:this.width_*.8}),this.addChild(this.backdrop),this.addChild(this.titleLabel),this.addChild(this.textLabel),this.eventMode=`static`,this.on(`pointertap`,this.handleAdvance),this.sequence.onChange.add(this.handleBeat),this.sequence.onMusic.add(this.playMusic),this.applyBeat(this.sequence.current)}get current(){return this.sequence.current}advance(){return this.sequence.advance()}skip(){this.sequence.skip()}resize(e,t){this.width_=e,this.height_=t,this.applyBeat(this.current)}applyBeat(e){if(!e){this.backdrop.visible=!1;return}let t=e.image?this.textureFor(e.image):null;if(this.backdrop.visible=t!==null,t){this.backdrop.texture=t;let e=Math.max(this.width_/t.width,this.height_/t.height);this.backdrop.scale.set(e),this.backdrop.x=(this.width_-t.width*e)/2,this.backdrop.y=(this.height_-t.height*e)/2}this.titleLabel.setText(e.title??``),this.titleLabel.x=this.width_*.1,this.titleLabel.y=this.height_*.12,this.textLabel.setText(e.text),this.textLabel.x=this.width_*.1,this.textLabel.y=this.height_*.24,this.textLabel.style.wordWrapWidth=this.width_*.8}destroy(e){this.sequence.onChange.remove(this.handleBeat),this.sequence.onMusic.remove(this.playMusic),super.destroy(e)}},DF=[[0,-1],[1,0],[0,1],[-1,0]],OF=[[0,-1],[1,-1],[1,0],[1,1],[0,1],[-1,1],[-1,0],[-1,-1]],kF=[[1,0],[1,-1],[0,-1],[-1,-1],[-1,0],[0,1]],AF=[[1,1],[1,0],[0,-1],[-1,0],[-1,1],[0,1]];function jF(e){return e===4?DF:OF}var MF={passable:!1,transparent:!1},NF={passable:!0,transparent:!0},PF=class e{constructor(e,t,n,r=0,i=`square`,a){if(this.rooms=[],this.width=e,this.shape=i,this.height=t,a!==void 0&&(!Number.isFinite(a)||a<0))throw Error(`viewDistance must be a finite non-negative number`);this.viewDistance=a,this.kinds=n,this.terrain=new Uint8Array(e*t).fill(r)}get cellCount(){return this.width*this.height}index(e,t){return t*this.width+e}xOf(e){return e%this.width}yOf(e){return Math.floor(e/this.width)}inside(e,t){return e>=0&&t>=0&&e<this.width&&t<this.height}neighbors(e,t,n=8){return this.shape===`hex`?cn(e,t):jF(n).map(([n,r])=>({x:e+n,y:t+r}))}forEachNeighbor(e,t,n,r){let i=this.shape===`hex`?e&1?AF:kF:jF(n);for(let[n,a]of i)r(e+n,t+a)}insideWithBorder(e,t){return e>0&&t>0&&e<this.width-1&&t<this.height-1}get(e,t){return this.inside(e,t)?this.terrain[this.index(e,t)]:0}set(e,t,n){this.inside(e,t)&&(this.terrain[this.index(e,t)]=n)}kindAt(e,t){return this.kinds[this.get(e,t)]??MF}passable(e,t){return this.inside(e,t)&&this.kindAt(e,t).passable}transparent(e,t){return this.inside(e,t)&&this.kindAt(e,t).transparent}fillRect(e,t){for(let n=e.top;n<=e.bottom;n++)for(let r=e.left;r<=e.right;r++)this.set(r,n,t)}passableCells(){let e=[];for(let t=0;t<this.terrain.length;t++)this.kinds[this.terrain[t]]?.passable&&e.push(t);return e}toJSON(){return{width:this.width,height:this.height,shape:this.shape,terrain:[...this.terrain],rooms:this.rooms.map(e=>({...e})),...this.viewDistance===void 0?{}:{viewDistance:this.viewDistance}}}static fromJSON(t,n){let r=new e(n.width,n.height,t,0,n.shape,n.viewDistance);return r.terrain.set(n.terrain.slice(0,r.terrain.length)),r.rooms=n.rooms.map(e=>({...e})),r}};function FF(e){return{x:Math.floor((e.left+e.right)/2),y:Math.floor((e.top+e.bottom)/2)}}function IF(e,t,n=0){return!(e.right+n<t.left||t.right+n<e.left||e.bottom+n<t.top||t.bottom+n<e.top)}var LF={id:`hall`,paint:(e,t,n)=>e.fillRect(t,n)};function RF(e){return Math.min(e.right-e.left+1,e.bottom-e.top+1)}function zF(e){return Math.max(e.right-e.left+1,e.bottom-e.top+1)}function BF(e,t){let n=RF(t),r=zF(t);return e.filter(e=>n>=(e.minSize??0)&&r<=(e.maxSize??1/0))}function VF(e,t){let n=BF(e,t);if(n.length===0)return null;let r=ce(n.map(e=>e.weight??1));return r===null?null:n[r]}var HF=[{passable:!1,transparent:!1},{passable:!0,transparent:!0}];function UF(e){let{width:t,height:n,rooms:r=14,minRoomSize:i=4,maxRoomSize:a=10,extraCorridors:o=3,wall:s=0,floor:c=1,kinds:l=[],hooks:u,builders:d}=e,f=new PF(t,n,[...HF,...l],s),p=[],m=[],h=[],g=0;for(let e=0;e<r*6&&p.length<r;e++){let e=ie(i,a),r=ie(i,a),o=k(1,Math.max(2,t-e-1)),s=k(1,Math.max(2,n-r-1)),l={left:o,top:s,right:o+e-1,bottom:s+r-1};if(l.right>=t-1||l.bottom>=n-1){g++;continue}if(p.some(e=>IF(l,e,2))){g++;continue}p.push(l);let m=(d?.length?VF(d,l):null)??LF;m.paint(f,l,c),h.push(m.id),u?.onRoomPlaced?.(l,p.length-1)}for(let e=1;e<p.length;e++){GF(f,FF(p[e-1]),FF(p[e]),c);let t={a:e-1,b:e,extra:!1};m.push(t),u?.onCorridorCarved?.(t,p[e-1],p[e])}for(let e=0;e<o&&p.length>2;e++){let e=k(p.length),t=k(p.length);if(e!==t){GF(f,FF(p[e]),FF(p[t]),c);let n={a:e,b:t,extra:!0};m.push(n),u?.onCorridorCarved?.(n,p[e],p[t])}}return f.rooms=p,{level:f,graph:m,retries:g,roomBuilders:h}}function WF(e){return UF(e).level}function GF(e,t,n,r){oe(.5)?(KF(e,t.x,n.x,t.y,!0,r),KF(e,t.y,n.y,n.x,!1,r)):(KF(e,t.y,n.y,t.x,!1,r),KF(e,t.x,n.x,n.y,!0,r))}function KF(e,t,n,r,i,a){let o=t<=n?1:-1;for(let s=t;s!==n+o;s+=o){let t=i?s:r,n=i?r:s;e.insideWithBorder(t,n)&&e.set(t,n,a)}}function qF(e,t=new Set){let n=e.passableCells().filter(e=>!t.has(e));return n.length>0?n[k(n.length)]:null}function JF(e,t){let n=null,r=-1;for(let i of e.rooms){let e=FF(i),a=(e.x-t.x)**2+(e.y-t.y)**2;a>r&&(r=a,n=i)}return n}var YF=class e{constructor(){this.defs=new Map,this.placed=new Map}define(e,t){this.defs.set(e,t)}place(e,t){if(!this.defs.has(t))throw Error(`FeatureLayer.place: no definition for kind "${t}"`);this.placed.set(e,t)}has(e){return this.placed.has(e)}kindAt(e){return this.placed.get(e)}remove(e){this.placed.delete(e)}inspect(e,t){this.defAt(e)?.inspect?.(e,t)}interact(e,t){let n=this.defAt(e);n&&(!n.interact||n.interact(e,t)!==!1)&&(n.consequence?.(e,t),n.persistent===!1&&this.remove(e))}defAt(e){let t=this.placed.get(e);return t===void 0?void 0:this.defs.get(t)}toJSON(){return{cells:[...this.placed.entries()]}}static fromJSON(t,n){let r=new e;for(let[e,n]of t)r.define(e,n);for(let[e,t]of n.cells)r.place(e,t);return r}};function XF(e,t=[],n=!0){let r=[],i=e.map(e=>e.value);t.forEach((e,t)=>{if(e.enabled===!1){r.push({step:`rare`,index:t,outcome:`deferred`});return}let n=oe(e.chance);r.push({step:`rare`,index:t,outcome:n?`added`:`skipped`}),n&&i.push(e.value)});for(let t=0;t<e.length;t++){let n=e[t].alternative;if(!n)continue;let a=oe(n.chance);r.push({step:`alternative`,index:t,outcome:a?`swapped`:`kept`}),a&&(i[t]=n.value)}return n&&(le(i),r.push({step:`shuffle`,index:-1,outcome:`shuffled`})),{roster:i,trace:r}}function ZF(e,t){return e.length===t.length&&e.every((e,n)=>e.a===t[n].a&&e.b===t[n].b&&e.extra===t[n].extra)}function QF(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function $F(e,t){if(e.length!==t.length)return!1;let n=[...e].sort((e,t)=>e[0]-t[0]),r=[...t].sort((e,t)=>e[0]-t[0]);return n.every(([e,t],n)=>e===r[n][0]&&t===r[n][1])}function eI(e,t){let n=[];return e.retries!==t.retries&&n.push({stage:`graph`,field:`retries`,expected:e.retries,actual:t.retries}),ZF(e.graph,t.graph)||n.push({stage:`graph`,field:`graph`,expected:e.graph,actual:t.graph}),(e.width!==t.width||e.height!==t.height||!QF(e.terrain,t.terrain))&&n.push({stage:`paint`,field:`terrain`,expected:e.terrain,actual:t.terrain}),(e.roomBuilders.length!==t.roomBuilders.length||e.roomBuilders.some((e,n)=>e!==t.roomBuilders[n]))&&n.push({stage:`paint`,field:`roomBuilders`,expected:e.roomBuilders,actual:t.roomBuilders}),$F(e.features,t.features)||n.push({stage:`paint`,field:`features`,expected:e.features,actual:t.features}),JSON.stringify(e.content)!==JSON.stringify(t.content)&&n.push({stage:`paint`,field:`content`,expected:e.content,actual:t.content}),e.rngDraws!==t.rngDraws&&n.push({stage:`paint`,field:`rngDraws`,expected:e.rngDraws,actual:t.rngDraws}),n}function tI(e,t=2){let n=e(),r=[];for(let i=1;i<t;i++)r.push(...eI(n,e()));return r}var nI=23283064365386963e-26;new class e{constructor(){this._seed=0,this._s0=0,this._s1=0,this._s2=0,this._c=0}getSeed(){return this._seed}setSeed(e){return e=e<1?1/e:e,this._seed=e,this._s0=(e>>>0)*nI,e=e*69069+1>>>0,this._s1=e*nI,e=e*69069+1>>>0,this._s2=e*nI,this._c=1,this}getUniform(){let e=2091639*this._s0+this._c*nI;return this._s0=this._s1,this._s1=this._s2,this._c=e|0,this._s2=e-this._c,this._s2}getUniformInt(e,t){let n=Math.max(e,t),r=Math.min(e,t);return Math.floor(this.getUniform()*(n-r+1))+r}getNormal(e=0,t=1){let n,r,i;do n=2*this.getUniform()-1,r=2*this.getUniform()-1,i=n*n+r*r;while(i>1||i==0);return e+n*Math.sqrt(-2*Math.log(i)/i)*t}getPercentage(){return 1+Math.floor(this.getUniform()*100)}getItem(e){return e.length?e[Math.floor(this.getUniform()*e.length)]:null}shuffle(e){let t=[],n=e.slice();for(;n.length;){let e=n.indexOf(this.getItem(n));t.push(n.splice(e,1)[0])}return t}getWeightedValue(e){let t=0;for(let n in e)t+=e[n];let n=this.getUniform()*t,r,i=0;for(r in e)if(i+=e[r],n<i)return r;return r}getState(){return[this._s0,this._s1,this._s2,this._c]}setState(e){return this._s0=e[0],this._s1=e[1],this._s2=e[2],this._c=e[3],this}clone(){return new e().setState(this.getState())}}().setSeed(Date.now());var rI=class{getContainer(){return null}setOptions(e){this._options=e}},iI=class extends rI{constructor(){super(),this._ctx=document.createElement(`canvas`).getContext(`2d`)}schedule(e){requestAnimationFrame(e)}getContainer(){return this._ctx.canvas}setOptions(e){super.setOptions(e);let t=`${e.fontStyle?`${e.fontStyle} `:``} ${e.fontSize}px ${e.fontFamily}`;this._ctx.font=t,this._updateSize(),this._ctx.font=t,this._ctx.textAlign=`center`,this._ctx.textBaseline=`middle`}clear(){let e=this._ctx.globalCompositeOperation;this._ctx.globalCompositeOperation=`copy`,this._ctx.fillStyle=this._options.bg,this._ctx.fillRect(0,0,this._ctx.canvas.width,this._ctx.canvas.height),this._ctx.globalCompositeOperation=e}eventToPosition(e,t){let n=this._ctx.canvas,r=n.getBoundingClientRect();return e-=r.left,t-=r.top,e*=n.width/r.width,t*=n.height/r.height,e<0||t<0||e>=n.width||t>=n.height?[-1,-1]:this._normalizedEventToPosition(e,t)}};function aI(e){return e.charAt(0).toUpperCase()+e.substring(1)}function oI(e,...t){let n=oI.map;return e.replace(/%(?:([a-z]+)|(?:{([^}]+)}))/gi,function(r,i,a,o){if(e.charAt(o-1)==`%`)return r.substring(1);if(!t.length)return r;let s=t[0],c=(i||a).split(`,`),l=c.shift()||``,u=n[l.toLowerCase()];if(!u)return r;s=t.shift();let d=s[u].apply(s,c),f=l.charAt(0);return f!=f.toLowerCase()&&(d=aI(d)),d})}oI.map={s:`toString`};var sI=class e extends iI{constructor(){super(),this._spacingX=0,this._spacingY=0,this._canvasCache={}}setOptions(e){super.setOptions(e),this._canvasCache={}}draw(t,n){e.cache?this._drawWithCache(t):this._drawNoCache(t,n)}_drawWithCache(e){let[t,n,r,i,a]=e,o=``+r+i+a,s;if(o in this._canvasCache)s=this._canvasCache[o];else{let e=this._options.border;s=document.createElement(`canvas`);let t=s.getContext(`2d`);if(s.width=this._spacingX,s.height=this._spacingY,t.fillStyle=a,t.fillRect(e,e,s.width-e,s.height-e),r){t.fillStyle=i,t.font=this._ctx.font,t.textAlign=`center`,t.textBaseline=`middle`;let e=[].concat(r);for(let n=0;n<e.length;n++)t.fillText(e[n],this._spacingX/2,Math.ceil(this._spacingY/2))}this._canvasCache[o]=s}this._ctx.drawImage(s,t*this._spacingX,n*this._spacingY)}_drawNoCache(e,t){let[n,r,i,a,o]=e;if(t){let e=this._options.border;this._ctx.fillStyle=o,this._ctx.fillRect(n*this._spacingX+e,r*this._spacingY+e,this._spacingX-e,this._spacingY-e)}if(!i)return;this._ctx.fillStyle=a;let s=[].concat(i);for(let e=0;e<s.length;e++)this._ctx.fillText(s[e],(n+.5)*this._spacingX,Math.ceil((r+.5)*this._spacingY))}computeSize(e,t){return[Math.floor(e/this._spacingX),Math.floor(t/this._spacingY)]}computeFontSize(e,t){let n=Math.floor(e/this._options.width),r=Math.floor(t/this._options.height),i=this._ctx.font;this._ctx.font=`100px `+this._options.fontFamily;let a=Math.ceil(this._ctx.measureText(`W`).width);this._ctx.font=i;let o=a/100*r/n;return o>1&&(r=Math.floor(r/o)),Math.floor(r/this._options.spacing)}_normalizedEventToPosition(e,t){return[Math.floor(e/this._spacingX),Math.floor(t/this._spacingY)]}_updateSize(){let e=this._options,t=Math.ceil(this._ctx.measureText(`W`).width);this._spacingX=Math.ceil(e.spacing*t),this._spacingY=Math.ceil(e.spacing*e.fontSize),e.forceSquareRatio&&(this._spacingX=this._spacingY=Math.max(this._spacingX,this._spacingY)),this._ctx.canvas.width=e.width*this._spacingX,this._ctx.canvas.height=e.height*this._spacingY}};sI.cache=!1;var cI={4:[[0,-1],[1,0],[0,1],[-1,0]],8:[[0,-1],[1,-1],[1,0],[1,1],[0,1],[-1,1],[-1,0],[-1,-1]],6:[[-1,-1],[1,-1],[2,0],[1,1],[-1,1],[-2,0]]},lI=class{constructor(e,t={}){this._lightPasses=e,this._options=Object.assign({topology:8},t)}_getCircle(e,t,n){let r=[],i,a,o;switch(this._options.topology){case 4:a=1,o=[0,1],i=[cI[8][7],cI[8][1],cI[8][3],cI[8][5]];break;case 6:i=cI[6],a=1,o=[-1,1];break;case 8:i=cI[4],a=2,o=[-1,1];break;default:throw Error(`Incorrect topology for FOV computation`)}let s=e+o[0]*n,c=t+o[1]*n;for(let e=0;e<i.length;e++)for(let t=0;t<n*a;t++)r.push([s,c]),s+=i[e][0],c+=i[e][1];return r}},uI=class extends lI{compute(e,t,n,r){if(r(e,t,0,1),!this._lightPasses(e,t))return;let i=[],a,o,s,c,l;for(let u=1;u<=n;u++){let n=this._getCircle(e,t,u),d=360/n.length;for(let e=0;e<n.length;e++)if(s=n[e][0],c=n[e][1],a=d*(e-.5),o=a+d,l=!this._lightPasses(s,c),this._visibleCoords(Math.floor(a),Math.ceil(o),l,i)&&r(s,c,u,1),i.length==2&&i[0]==0&&i[1]==360)return}}_visibleCoords(e,t,n,r){if(e<0){let i=this._visibleCoords(0,t,n,r),a=this._visibleCoords(360+e,360,n,r);return i||a}let i=0;for(;i<r.length&&r[i]<e;)i++;if(i==r.length)return n&&r.push(e,t),!0;let a=0;if(i%2){for(;i<r.length&&r[i]<t;)i++,a++;return a!=0&&(n&&(a%2?r.splice(i-a,a,t):r.splice(i-a,a)),!0)}for(;i<r.length&&r[i]<t;)i++,a++;return e==r[i-a]&&a==1?!1:(n&&(a%2?r.splice(i-a,a,e):r.splice(i-a,a,e,t)),!0)}},dI=class extends lI{compute(e,t,n,r){if(r(e,t,0,1),!this._lightPasses(e,t))return;let i=[],a,o,s,c,l,u;for(let d=1;d<=n;d++){let n=this._getCircle(e,t,d),f=n.length;for(let e=0;e<f;e++)if(a=n[e][0],o=n[e][1],c=[e?2*e-1:2*f-1,2*f],l=[2*e+1,2*f],s=!this._lightPasses(a,o),u=this._checkVisibility(c,l,s,i),u&&r(a,o,d,u),i.length==2&&i[0][0]==0&&i[1][0]==i[1][1])return}}_checkVisibility(e,t,n,r){if(e[0]>t[0])return(this._checkVisibility(e,[e[1],e[1]],n,r)+this._checkVisibility([0,1],t,n,r))/2;let i=0,a=!1;for(;i<r.length;){let t=r[i],n=t[0]*e[1]-e[0]*t[1];if(n>=0){n==0&&!(i%2)&&(a=!0);break}i++}let o=r.length,s=!1;for(;o--;){let e=r[o],n=t[0]*e[1]-e[0]*t[1];if(n>=0){n==0&&o%2&&(s=!0);break}}let c=!0;if((i==o&&(a||s)||a&&s&&i+1==o&&o%2||i>o&&i%2)&&(c=!1),!c)return 0;let l,u=o-i+1;if(u%2){if(i%2){let e=r[i];l=(t[0]*e[1]-e[0]*t[1])/(e[1]*t[1]),n&&r.splice(i,u,t)}else{let t=r[o];l=(t[0]*e[1]-e[0]*t[1])/(e[1]*t[1]),n&&r.splice(i,u,e)}}else if(i%2){let e=r[i],t=r[o];l=(t[0]*e[1]-e[0]*t[1])/(e[1]*t[1]),n&&r.splice(i,u)}else return n&&r.splice(i,u,e,t),1;let d=(t[0]*e[1]-e[0]*t[1])/(e[1]*t[1]);return l/d}},fI=[[-1,0,0,1],[0,-1,1,0],[0,-1,-1,0],[-1,0,0,-1],[1,0,0,-1],[0,1,-1,0],[0,1,1,0],[1,0,0,1]],pI={DiscreteShadowcasting:uI,PreciseShadowcasting:dI,RecursiveShadowcasting:class extends lI{compute(e,t,n,r){r(e,t,0,1);for(let i=0;i<fI.length;i++)this._renderOctant(e,t,fI[i],n,r)}compute180(e,t,n,r,i){i(e,t,0,1);let a=(r-1+8)%8,o=(r-2+8)%8,s=(r+1+8)%8;this._renderOctant(e,t,fI[o],n,i),this._renderOctant(e,t,fI[a],n,i),this._renderOctant(e,t,fI[r],n,i),this._renderOctant(e,t,fI[s],n,i)}compute90(e,t,n,r,i){i(e,t,0,1);let a=(r-1+8)%8;this._renderOctant(e,t,fI[r],n,i),this._renderOctant(e,t,fI[a],n,i)}_renderOctant(e,t,n,r,i){this._castVisibility(e,t,1,1,0,r+1,n[0],n[1],n[2],n[3],i)}_castVisibility(e,t,n,r,i,a,o,s,c,l,u){if(!(r<i))for(let d=n;d<=a;d++){let n=-d-1,f=-d,p=!1,m=0;for(;n<=0;){n+=1;let h=e+n*o+f*s,g=t+n*c+f*l,_=(n-.5)/(f+.5),v=(n+.5)/(f-.5);if(!(v>r)){if(_<i)break;if(n*n+f*f<a*a&&u(h,g,d,1),!p)!this._lightPasses(h,g)&&d<a&&(p=!0,this._castVisibility(e,t,d+1,r,_,a,o,s,c,l,u),m=v);else{if(!this._lightPasses(h,g)){m=v;continue}p=!1,r=m}}}if(p)break}}}};.5*(Math.sqrt(3)-1),(3-Math.sqrt(3))/6;var mI=class{constructor(e,t,n,r={}){this._toX=e,this._toY=t,this._passableCallback=n,this._options=Object.assign({topology:8},r),this._dirs=cI[this._options.topology],this._options.topology==8&&(this._dirs=[this._dirs[0],this._dirs[2],this._dirs[4],this._dirs[6],this._dirs[1],this._dirs[3],this._dirs[5],this._dirs[7]])}_getNeighbors(e,t){let n=[];for(let r=0;r<this._dirs.length;r++){let i=this._dirs[r],a=e+i[0],o=t+i[1];this._passableCallback(a,o)&&n.push([a,o])}return n}},hI={Dijkstra:class extends mI{constructor(e,t,n,r){super(e,t,n,r),this._computed={},this._todo=[],this._add(e,t,null)}compute(e,t,n){let r=e+`,`+t;if(r in this._computed||this._compute(e,t),!(r in this._computed))return;let i=this._computed[r];for(;i;)n(i.x,i.y),i=i.prev}_compute(e,t){for(;this._todo.length;){let n=this._todo.shift();if(n.x==e&&n.y==t)return;let r=this._getNeighbors(n.x,n.y);for(let e=0;e<r.length;e++){let t=r[e],i=t[0],a=t[1];i+`,`+a in this._computed||this._add(i,a,n)}}}_add(e,t,n){let r={x:e,y:t,prev:n};this._computed[e+`,`+t]=r,this._todo.push(r)}},AStar:class extends mI{constructor(e,t,n,r={}){super(e,t,n,r),this._todo=[],this._done={}}compute(e,t,n){for(this._todo=[],this._done={},this._fromX=e,this._fromY=t,this._add(this._toX,this._toY,null);this._todo.length;){let n=this._todo.shift(),r=n.x+`,`+n.y;if(r in this._done)continue;if(this._done[r]=n,n.x==e&&n.y==t)break;let i=this._getNeighbors(n.x,n.y);for(let e=0;e<i.length;e++){let t=i[e],r=t[0],a=t[1];r+`,`+a in this._done||this._add(r,a,n)}}let r=this._done[e+`,`+t];if(r)for(;r;)n(r.x,r.y),r=r.prev}_add(e,t,n){let r=this._distance(e,t),i={x:e,y:t,prev:n,g:n?n.g+1:0,h:r},a=i.g+i.h;for(let e=0;e<this._todo.length;e++){let t=this._todo[e],n=t.g+t.h;if(a<n||a==n&&r<t.h){this._todo.splice(e,0,i);return}}this._todo.push(i)}_distance(e,t){switch(this._options.topology){case 4:return Math.abs(e-this._fromX)+Math.abs(t-this._fromY);case 6:let n=Math.abs(e-this._fromX),r=Math.abs(t-this._fromY);return r+Math.max(0,(n-r)/2);case 8:return Math.max(Math.abs(e-this._fromX),Math.abs(t-this._fromY))}}}};function gI(e,t){return Math.max(Math.abs(e.x-t.x),Math.abs(e.y-t.y))}function _I(e,t){let n=[],r=e.x,i=e.y,a=Math.abs(t.x-e.x),o=-Math.abs(t.y-e.y),s=e.x<t.x?1:-1,c=e.y<t.y?1:-1,l=a+o;for(;n.push({x:r,y:i}),r!==t.x||i!==t.y;){let e=l*2;e>=o&&(l+=o,r+=s),e<=a&&(l+=a,i+=c)}return n}function vI(e,t,n,r={}){let i=e.shape===`hex`?dn(t,n):_I(t,n),a=r.stop??`opaque`,o=[],s=null;for(let t of i)if(o.push(t),o.length!==1&&a!==`none`&&(a===`outside`&&!e.inside(t.x,t.y)||a===`opaque`&&e.inside(t.x,t.y)&&!e.transparent(t.x,t.y)||a===`impassable`&&e.inside(t.x,t.y)&&!e.passable(t.x,t.y))){s=t;break}return{cells:o,stop:s}}function yI(e,t,n){let r=e.shape===`hex`?dn(t,n):_I(t,n);for(let t=1;t<r.length-1;t++)if(!e.transparent(r[t].x,r[t].y))return!1;return!0}function bI(e,t,n,r){return!((e.shape===`hex`?ln(t,n):gI(t,n))>r.range||(r.requireLineOfSight??!0)&&!yI(e,t,n))}function xI(e,t,n){switch(n.kind){case`single`:return[t];case`line`:return _I(e,t);case`cone`:return wI(e,t,n.width);case`burst`:{let e=[],r=n.radius;for(let n=-r;n<=r;n++)for(let i=-r;i<=r;i++)i*i+n*n>r*r||e.push({x:t.x+i,y:t.y+n});return e}}}function SI(e,t,n,r){return e.shape===`hex`?r.kind===`single`?[{...n}]:r.kind===`line`?dn(t,n):r.kind===`burst`?fn(n,r.radius):CI(t,n,r.width):xI(t,n,r)}function CI(e,t,n){let r=ln(e,t);if(r===0)return[{...e}];let i=dn(e,t),a=[];for(let t=1;t<=r;t++){let o=i[t],s=Math.round(t/r*n);for(let n of fn(o,s))ln(e,n)===t&&a.push(n)}return a}function wI(e,t,n){let r=t.x-e.x,i=t.y-e.y,a=Math.max(Math.abs(r),Math.abs(i));if(a===0)return[{...e}];let o=Math.sign(r),s=Math.sign(i),c=r!==0&&i!==0?o:s,l=r!==0&&i!==0?-s:o,u=[];for(let t=1;t<=a;t++){let r=e.x+o*t,i=e.y+s*t,d=Math.round(t/a*n);for(let e=-d;e<=d;e++)u.push({x:r+c*e,y:i+l*e})}return u}function TI(e,t,n,r){let i=new Set,a=[],o=t;for(let t=0;t<n;t++){let t=-1,n=r+1;for(let a=0;a<e.length;a++){if(i.has(a))continue;let s=gI(o,e[a]);s<=r&&s<n&&(n=s,t=a)}if(t===-1)break;i.add(t),a.push(e[t]),o=e[t]}return a}function EI(e,t,n=1){for(let n of t)if(e<=n.max)return n.multiplier;return n}function DI(e,t){return t.length===0?1:t[Math.min(e,t.length-1)]}function OI(e,t,n,r){let i=[];for(let a=1;a<=r;a++){let r={x:t.x+n.x*a,y:t.y+n.y*a};if(!e.passable(r.x,r.y))break;i.push(r)}return i}var kI=class{constructor(e,t){if(this.onMove=new p,this.onConfirm=new p,this.onCancel=new p,!Number.isFinite(t.range)||t.range<0)throw Error(`targeting range must be a finite non-negative number`);this.level=e,this.origin={...t.origin},this.range=t.range,this.requireLineOfSight=t.requireLineOfSight??!0,this.validate=t.validate,this.shape=t.shape??{kind:`single`},this.cursor={...t.cursor??t.origin}}get target(){return{...this.cursor}}get distance(){return this.level.shape===`hex`?ln(this.origin,this.cursor):gI(this.origin,this.cursor)}get inRange(){return this.distance<=this.range}get inSight(){return yI(this.level,this.origin,this.cursor)}get valid(){return!this.inRange||this.requireLineOfSight&&!this.inSight?!1:!this.validate||this.validate(this.cursor)}move(e,t){if(this.level.shape===`hex`){let n=this.level.neighbors(this.cursor.x,this.cursor.y).find(n=>n.x-this.cursor.x===e&&n.y-this.cursor.y===t);n&&this.moveTo(n);return}this.moveTo({x:this.cursor.x+e,y:this.cursor.y+t})}moveTo(e){this.level.inside(e.x,e.y)&&(this.cursor={x:e.x,y:e.y},this.onMove.dispatch({...this.cursor}))}setShape(e){this.shape=e}preview(){return this.valid?SI(this.level,this.origin,this.cursor,this.shape):[]}confirm(){if(!this.valid)return null;let e={origin:{...this.origin},target:{...this.cursor},shape:this.shape,cells:this.preview()};return this.onConfirm.dispatch(e),e}cancel(){this.onCancel.dispatch()}},AI=class{constructor(e){this.visible=new Set,this.explored=new Set,this.light=new Map,this.level=e,this.fov=e.shape===`hex`?null:new pI.PreciseShadowcasting((t,n)=>e.transparent(t,n))}update(e,t,n=this.level.viewDistance??Math.max(this.level.width,this.level.height),r){if(this.visible.clear(),this.light.clear(),r){this.updateFromHeight(e,t,n,r);return}if(this.fov){this.fov.compute(e,t,n,(e,t,n,r)=>{if(!this.level.inside(e,t))return;let i=this.level.index(e,t);this.visible.add(i),this.explored.add(i),this.light.set(i,r)});return}let i={x:e,y:t};for(let e of fn(i,n)){if(!this.level.inside(e.x,e.y))continue;let t=dn(i,e);t.slice(1,-1).some(e=>!this.level.inside(e.x,e.y)||!this.level.transparent(e.x,e.y))||this.lightCell(e.x,e.y,t.length-1,n)}}lightCell(e,t,n,r){let i=this.level.index(e,t);this.visible.add(i),this.explored.add(i),this.light.set(i,r===0?1:Math.max(0,1-n/(r+1)))}updateFromHeight(e,t,n,r){let i=r.height??r.heights.heightAt(e,t),a={x:e,y:t};if(this.level.shape===`hex`){for(let e of fn(a,n)){if(!this.level.inside(e.x,e.y))continue;let t=dn(a,e);this.heightBlocked(t,r.heights,i,r.heights.heightAt(e.x,e.y))||this.lightCell(e.x,e.y,t.length-1,n)}return}for(let o=t-n;o<=t+n;o++)for(let t=e-n;t<=e+n;t++){if(!this.level.inside(t,o)||gI(a,{x:t,y:o})>n)continue;let e=_I(a,{x:t,y:o});this.heightBlocked(e,r.heights,i,r.heights.heightAt(t,o))||this.lightCell(t,o,e.length-1,n)}}heightBlocked(e,t,n,r){let i=Math.max(n,r);for(let n=1;n<e.length-1;n++){let r=e[n];if(!this.level.inside(r.x,r.y)||!this.level.transparent(r.x,r.y)||t.heightAt(r.x,r.y)>i)return!0}return!1}isVisible(e,t){return this.visible.has(this.level.index(e,t))}isExplored(e,t){return this.explored.has(this.level.index(e,t))}lightAt(e,t){return this.light.get(this.level.index(e,t))??0}reset(){this.visible.clear(),this.explored.clear(),this.light.clear()}revealAll(){for(let e=0;e<this.level.cellCount;e++)this.explored.add(e)}},jI=class{constructor(e){this.level=e,this.heights=new Int32Array(e.cellCount)}heightAt(e,t){return this.level.inside(e,t)?this.heights[this.level.index(e,t)]:0}set(e,t,n){if(!Number.isInteger(n))throw Error(`a cell's height must be a whole number, got ${n}`);this.level.inside(e,t)&&(this.heights[this.level.index(e,t)]=n)}},MI=class{constructor(e){this.level=e}passable(e){let t=e.blocked;return(e,n)=>this.level.passable(e,n)?!t?.has(this.level.index(e,n)):!1}stepper(e){let t=this.passable(e),n=e.heights;if(!n)return(e,n,r,i)=>this.level.inside(e,n)&&this.level.inside(r,i)&&t(r,i);let r=e.climb??1;if(!Number.isInteger(r)||r<0)throw Error(`a climb limit must be a non-negative whole number, got ${e.climb}`);return(e,i,a,o)=>this.level.inside(e,i)&&this.level.inside(a,o)&&t(a,o)&&n.heightAt(a,o)-n.heightAt(e,i)<=r}find(e,t,n={}){if(this.level.shape===`hex`||n.heights){let r=this.distanceMap(t,n),i=[],a=e;for(let e=0;e<this.level.cellCount;e++){let e=this.descend(a,r,n);if(!e||(i.push(e),e.x===t.x&&e.y===t.y))break;a=e}return i}let r=new hI.AStar(t.x,t.y,this.passable(n),{topology:n.topology??8}),i=[];return r.compute(e.x,e.y,(e,t)=>i.push({x:e,y:t})),i.slice(1)}step(e,t,n={}){return this.find(e,t,n)[0]??null}distanceMap(e,t={}){let n=new Int32Array(this.level.cellCount).fill(-1),r=this.passable(t),i=this.stepper(t);if(!r(e.x,e.y))return n;let a=[this.level.index(e.x,e.y)];n[a[0]]=0;for(let e=0;e<a.length;e++){let r=a[e],o=this.level.xOf(r),s=this.level.yOf(r),c=n[r]+1;this.level.forEachNeighbor(o,s,t.topology??8,(e,t)=>{if(!i(e,t,o,s))return;let r=this.level.index(e,t);n[r]===-1&&(n[r]=c,a.push(r))})}return n}descend(e,t,n={}){let r=this.stepper(n),i=t[this.level.index(e.x,e.y)];if(i<=0)return null;let a=null,o=i;return this.level.forEachNeighbor(e.x,e.y,n.topology??8,(n,i)=>{if(!r(e.x,e.y,n,i))return;let s=t[this.level.index(n,i)];s!==-1&&s<o&&(o=s,a={x:n,y:i})}),a}autoExplore(e,t,n={}){let r=this.passable(n),i=this.stepper(n);if(!r(e.x,e.y))return[];let a=new Map,o=new Set([this.level.index(e.x,e.y)]),s=[e];for(let e=0;e<s.length;e++){let r=s[e];if(e>0&&!t.isExplored(r.x,r.y))return this.reconstruct(a,r);this.level.forEachNeighbor(r.x,r.y,n.topology??8,(e,t)=>{if(!i(r.x,r.y,e,t))return;let n=this.level.index(e,t);o.has(n)||(o.add(n),a.set(n,r),s.push({x:e,y:t}))})}return[]}reconstruct(e,t){let n=[t],r=e.get(this.level.index(t.x,t.y));for(;r;)n.push(r),r=e.get(this.level.index(r.x,r.y));return n.reverse()}},NI=class e{constructor(){this.entries=[],this.sequence=0,this.now=0}get size(){return this.entries.length}get actors(){return this.entries.map(e=>e.actor)}has(e){return this.entries.some(t=>t.actor===e)}add(e,t=0,n=e.priority??0){if(!Number.isFinite(t)||t<0)throw Error(`scheduler delay must be finite and non-negative`);if(!Number.isFinite(n))throw Error(`scheduler priority must be finite`);this.entries.push({actor:e,time:this.now+t,sequence:this.sequence++,priority:n}),this.sort()}remove(e){let t=this.entries.findIndex(t=>t.actor===e);t!==-1&&this.entries.splice(t,1)}clear(){this.entries.length=0,this.now=0,this.sequence=0}peek(){let e=this.entries[0];return e?(this.now=Math.max(this.now,e.time),e.actor):null}spend(e){let t=this.entries[0];if(!t)return;let n=t.actor.speed??1;t.time=this.now+e/(n>0?n:1),t.sequence=this.sequence++,this.sort()}postpone(e,t){let n=this.entries.find(t=>t.actor===e);n&&(n.time+=t,n.sequence=this.sequence++,this.sort())}timeOf(e){return this.entries.find(t=>t.actor===e)?.time??null}toJSON(e){return{now:this.now,sequence:this.sequence,entries:this.entries.map(t=>({id:e(t.actor),time:t.time,sequence:t.sequence,...t.priority===0?{}:{priority:t.priority}}))}}static restore(t,n){let r=new e;return r.now=t.now,r.sequence=t.sequence,r.entries=t.entries.map(e=>({actor:n(e.id),time:e.time,sequence:e.sequence,priority:e.priority??0})),r.sort(),r}sort(){this.entries.sort((e,t)=>e.time-t.time||t.priority-e.priority||e.sequence-t.sequence)}};function PI(e,t,n,r,i,a={}){let o=a.sightRadius??6,s=a.fleeBelow??0;if((a.disposition??`hostile`)!==`hostile`&&a.provoked!==!0)return{state:`wander`,step:FI(e,n,a)};let c=new AI(e);return c.update(n.x,n.y,o),c.isVisible(i.x,i.y)?r<=s?{state:`flee`,step:II(e,n,i,a)}:{state:`hunt`,step:t.step(n,i,a)}:{state:`wander`,step:FI(e,n,a)}}function FI(e,t,n){return se(LI(e,t,n))}function II(e,t,n,r){let i=LI(e,t,r),a=null,o=RI(t,n);for(let e of i){let t=RI(e,n);t>o&&(o=t,a=e)}return a}function LI(e,t,n){let r=n.blocked,i=[];for(let[a,o]of jF(n.topology??8)){let n={x:t.x+a,y:t.y+o};e.passable(n.x,n.y)&&(r?.has(e.index(n.x,n.y))||i.push(n))}return i}function RI(e,t){return(e.x-t.x)**2+(e.y-t.y)**2}var zI=class e{constructor(e){this.revealedKind=new Map,this.discovered=new Set,this.level=e}conceal(e,t,n,r){let i=this.level.index(e,t);this.revealedKind.set(i,r),this.discovered.delete(i),this.level.set(e,t,n)}isSecret(e,t){let n=this.level.index(e,t);return this.revealedKind.has(n)&&!this.discovered.has(n)}isDiscovered(e,t){return this.discovered.has(this.level.index(e,t))}discover(e,t){if(!this.isSecret(e,t))return!1;let n=this.level.index(e,t);return this.discovered.add(n),this.level.set(e,t,this.revealedKind.get(n)),!0}toJSON(){return{revealed:[...this.revealedKind],discovered:[...this.discovered]}}static fromJSON(t,n){let r=new e(t);for(let[e,t]of n.revealed)r.revealedKind.set(e,t);for(let e of n.discovered)r.discovered.add(e);return r}},BI=class e{constructor(e){this.openKind=new Map,this.closedKind=new Map,this.lockedBy=new Map,this.open_=new Map,this.level=e}place(e,t,n){let r=this.level.index(e,t);this.openKind.set(r,n.open),this.closedKind.set(r,n.closed),this.open_.set(r,n.startOpen??!1),n.locked===void 0?this.lockedBy.delete(r):this.lockedBy.set(r,n.locked),this.level.set(e,t,this.open_.get(r)?n.open:n.closed)}isDoor(e,t){return this.open_.has(this.level.index(e,t))}isOpen(e,t){return this.open_.get(this.level.index(e,t))===!0}isLocked(e,t){return this.lockedBy.has(this.level.index(e,t))}requiredKey(e,t){return this.lockedBy.get(this.level.index(e,t))}open(e,t){let n=this.level.index(e,t);return!this.open_.has(n)||this.open_.get(n)||this.lockedBy.has(n)?!1:(this.open_.set(n,!0),this.level.set(e,t,this.openKind.get(n)),!0)}close(e,t){let n=this.level.index(e,t);return!this.open_.has(n)||!this.open_.get(n)?!1:(this.open_.set(n,!1),this.level.set(e,t,this.closedKind.get(n)),!0)}unlock(e,t){let n=this.level.index(e,t);return this.lockedBy.has(n)?(this.lockedBy.delete(n),!0):!1}toJSON(){let e=[];for(let[t,n]of this.openKind)e.push({cell:t,open:n,closed:this.closedKind.get(t),locked:this.lockedBy.get(t),isOpen:this.open_.get(t)===!0});return{doors:e}}static fromJSON(t,n){let r=new e(t);for(let e of n.doors){let n=t.xOf(e.cell),i=t.yOf(e.cell);r.place(n,i,{open:e.open,closed:e.closed,locked:e.locked,startOpen:e.isOpen})}return r}},VI=class e{constructor(e=[]){this.current=0;for(let t=1;t<e.length;t++)if(e[t]>=e[t-1])throw Error(`boss phase thresholds must descend`);this.thresholds=e}get phase(){return this.current}check(e){let t=0;for(;t<this.thresholds.length&&e<=this.thresholds[t];)t++;let n=[];for(;this.current<t;)this.current++,n.push(this.current);return n}reset(){this.current=0}toJSON(){return{phase:this.current}}static fromJSON(t,n){let r=new e(t);return r.current=n.phase,r}},HI=class e{constructor(e){this.remaining=new Map,this.cooldowns=new Map(Object.entries(e))}advance(e=1){for(let[t,n]of this.remaining)n<=e?this.remaining.delete(t):this.remaining.set(t,n-e)}ready(){let e=[];for(let t of this.cooldowns.keys())this.remaining.has(t)||e.push(t);return e}use(e){let t=this.cooldowns.get(e);return t===void 0||this.remaining.has(e)?!1:(t>0&&this.remaining.set(e,t),!0)}toJSON(){return{remaining:[...this.remaining]}}static fromJSON(t,n){let r=new e(t);for(let[e,t]of n.remaining)r.remaining.set(e,t);return r}},UI=class extends x{modifyDamage(e,t,n){let r={attacker:e,defender:t,amount:n,prevented:!1};return this.emit(`beforeDamage`,r),r.amount=Math.max(0,r.amount),r.amount===0&&(r.prevented=!0),r}},WI=class{constructor(e){this.detected=!1,this.radius=e.radius}get isDetected(){return this.detected}checkDetection(e,t){if(this.detected)return!1;let n=t.some(t=>gI(e,t)<=this.radius);return n&&(this.detected=!0),n}reset(){this.detected=!1}},GI=class e{constructor(e){this.streak=0,this.lastTurn=-1/0,this.window=e}get count(){return this.streak}trigger(e){return this.streak=e-this.lastTurn<=this.window?this.streak+1:1,this.lastTurn=e,this.streak}isActive(e){return e-this.lastTurn<=this.window}reset(){this.streak=0,this.lastTurn=-1/0}toJSON(){return{streak:this.streak,lastTurn:this.lastTurn}}static fromJSON(t,n){let r=new e(t);return r.streak=n.streak,r.lastTurn=n.lastTurn,r}},KI=class e{constructor(e){if(this.index=-1,this.remaining=0,e.length===0)throw Error(`a multi-stage ability needs at least one stage`);this.stages=e}get active(){return this.index>=0}get stage(){return this.index>=0?this.stages[this.index]:null}start(){return!this.active&&(this.index=0,this.remaining=this.stages[0].duration,!0)}advance(){return!this.active||(this.remaining--,this.remaining>0)?null:(this.index++,this.index>=this.stages.length?(this.index=-1,`done`):(this.remaining=this.stages[this.index].duration,this.stages[this.index].name))}cancel(){this.index=-1,this.remaining=0}toJSON(){return{index:this.index,remaining:this.remaining}}static fromJSON(t,n){let r=new e(t);return r.index=n.index,r.remaining=n.remaining,r}},qI=class e{constructor(e){if(this.index=0,this.state=`idle`,typeof e.damage!=`function`&&!Number.isFinite(e.damage))throw Error(`beam damage must be a finite number or a function`);if(typeof e.damage==`number`&&e.damage<0)throw Error(`beam damage must be non-negative`);if(this.options=e,this.shape=e.shape??(e.fronts?`fronts`:`line`),e.fronts){let t=e.fronts([{...e.from}],0);this.fronts=t.length?[t.map(e=>({...e}))]:[]}else this.fronts=SI(e.level,e.from,e.target,{kind:`line`}).slice(1).map(e=>[{...e}])}get active(){return this.state===`active`}get done(){return this.state===`done`||this.state===`blocked`||this.state===`cancelled`}get beamShape(){return this.shape}get currentPath(){return this.fronts.flat().map(e=>({...e}))}start(){return this.state===`idle`&&(this.state=this.fronts.length===0?`done`:`active`,!0)}advance(){if(this.state!==`active`)return this.inactiveStep();let e=this.fronts[this.index]??[],t=Math.max(0,this.fronts.length-this.index-1),n=[],r=[],i=0;for(let a of e){let e={cell:{...a},step:this.index,remaining:t};if(!this.blocked(a,e)){n.push({...a}),this.options.onCell?.({...a},e);for(let t of this.options.targetsAt?.(a)??[]){let n=typeof this.options.damage==`function`?this.options.damage(t,e):this.options.damage;if(!Number.isFinite(n)||n<0)throw Error(`beam damage callback must return a non-negative finite number`);i+=n,r.push(t),this.options.applyDamage?.(t,n,e)}}}let a=this.index;if(this.index++,this.options.fronts&&n.length>0){let e=this.options.fronts(n.map(e=>({...e})),this.index);e.length&&this.fronts.push(e.map(e=>({...e})))}return n.length===0?this.state=`blocked`:this.index>=this.fronts.length&&(this.state=`done`),{status:n.length===0?`blocked`:this.state,cell:n[0]?{...n[0]}:null,cells:n.map(e=>({...e})),step:a,remaining:t,targets:[...r],damage:i}}cancel(){(this.state===`active`||this.state===`idle`)&&(this.state=`cancelled`)}toJSON(){return{state:this.state,fronts:this.fronts.map(e=>e.map(e=>({...e}))),index:this.index,shape:this.shape}}static fromJSON(t,n){let r=n.shape??(t.fronts?`fronts`:`line`);if(t.shape!==void 0&&t.shape!==r)throw Error(`beam save is shape "${r}", not "${t.shape}"`);let i=Object.create(e.prototype);return i.options=t,i.shape=r,i.fronts=n.fronts?n.fronts.map(e=>e.map(e=>({...e}))):(n.path??[]).map(e=>[{...e}]),i.index=n.index,i.state=n.state,i}blocked(e,t){let n=this.options.blocker??(this.options.stopAtOpaque===!1?`none`:`terrain`),r=!1;return n===`terrain`?r=!this.options.level.inside(e.x,e.y)||!this.options.level.transparent(e.x,e.y):n!==`none`&&(r=n({...e},t)===!0),r||this.options.isBlocked?.({...e},t)===!0}inactiveStep(){return{status:this.state,cell:null,cells:[],step:this.index,remaining:Math.max(0,this.fronts.length-this.index),targets:[],damage:0}}};function JI(e,t={}){return(t.within?[...t.within]:ZI(e.cellCount)).filter(n=>!(t.occupied?.has(n)||t.terrain&&!t.terrain.has(e.terrain[n])))}function YI(e,t,n){let r=new Set([t]),i=[t];for(let t=0;t<Math.max(0,n);t++){let t=[];for(let n of i)e.forEachNeighbor(e.xOf(n),e.yOf(n),8,(n,i)=>{if(!e.inside(n,i))return;let a=e.index(n,i);r.has(a)||(r.add(a),t.push(a))});i=t}return r.delete(t),[...r]}function XI(e,t){let n=[...new Set(e)];le(n);let r=n.slice(0,Math.max(0,t));return{cells:r,trace:{requested:t,available:n.length,selected:r}}}function ZI(e){let t=Array(e);for(let n=0;n<e;n++)t[n]=n;return t}var QI=l({AbilityCycle:()=>HI,BossPhases:()=>VI,CombatHooks:()=>UI,DUNGEON_KINDS:()=>HF,Doors:()=>BI,Elevation:()=>jI,FLOOR:()=>NF,FeatureLayer:()=>YF,FieldOfView:()=>AI,Level:()=>PF,MultiStageAbility:()=>KI,MultiTurnBeam:()=>qI,Pathfinder:()=>MI,Scheduler:()=>NI,Secrets:()=>zI,Stealth:()=>WI,TargetingController:()=>kI,TriggerTracker:()=>GI,WALL:()=>MF,areaFalloffMultiplier:()=>DI,ballistica:()=>vI,canTarget:()=>bI,candidateCells:()=>JI,cellsNear:()=>YI,chainTargets:()=>TI,chebyshevDistance:()=>gI,checkDeterminism:()=>tI,compareDungeonArtifacts:()=>eI,coneCells:()=>wI,decideMonsterAI:()=>PI,eligibleBuilders:()=>BF,findFreeCell:()=>qF,furthestRoom:()=>JF,generateDungeon:()=>WF,generateDungeonGraph:()=>UF,hallBuilder:()=>LF,hasLineOfSight:()=>yI,hexConeCells:()=>CI,knockbackPath:()=>OI,neighbourOffsets:()=>jF,pickBuilder:()=>VF,rangeMultiplier:()=>EI,rectCenter:()=>FF,rectsOverlap:()=>IF,resolveArea:()=>xI,resolveAreaOnLevel:()=>SI,rollRoster:()=>XF,selectDistinctCells:()=>XI,traceLine:()=>_I});function $I(e,t){let n=e=>t.filter(t=>t.op===e).sort((e,t)=>(e.order??0)-(t.order??0)),r=e;for(let e of n(`add`))r+=e.value;for(let e of n(`multiply`))r*=e.value;for(let e of n(`set`))r=e.value;return r}var eL=class e{constructor(e){this.modifiers=[],this.cache=null,this.baseValues={...e.base},this.derived=e.derived??[]}base(e){return this.baseValues[e]??0}setBase(e,t){this.baseValues[e]=t,this.cache=null}addModifier(e){this.modifiers.push(e),this.cache=null}removeModifier(e){let t=this.modifiers.indexOf(e);t!==-1&&this.modifiers.splice(t,1),this.cache=null}removeModifiersFrom(e){this.modifiers=this.modifiers.filter(t=>t.source!==e),this.cache=null}get(e){return this.resolveAll()[e]??0}resolveAll(){if(this.cache)return this.cache;let e={...this.baseValues};for(let t of Object.keys(e))e[t]=$I(e[t],this.modifiersFor(t));for(let t of this.derived)e[t.name]=$I(t.from(e),this.modifiersFor(t.name));return this.cache=e,e}modifiersFor(e){return this.modifiers.filter(t=>t.stat===e)}toJSON(){return{base:{...this.baseValues}}}static fromJSON(t,n){let r=new e(t);return r.baseValues={...t.base,...n.base},r.cache=null,r}};function tL(e,t,n){return{maxLevel:n,experienceFor:n=>n<=1?0:Math.round(e*(n-1)**t)}}var nL=class e{constructor(e,t={}){this.curve=e,this.level=t.level??1,this.experience=t.experience??this.curve.experienceFor(this.level)}get experienceToNext(){return this.level>=this.curve.maxLevel?null:this.curve.experienceFor(this.level+1)-this.experience}addExperience(e){this.experience+=e;let t=0;for(;this.level<this.curve.maxLevel&&this.experience>=this.curve.experienceFor(this.level+1);)this.level++,t++;return t}toJSON(){return{level:this.level,experience:this.experience}}static fromJSON(t,n){return new e(t,n)}};function rL(e,t,n=()=>ie(1,20)){return e+n()>=t}var iL=class e{constructor(e,t={}){this.available=0,this.stats=e,this.capFor=t.cap??(()=>1/0),this.costFor=t.cost??(()=>1)}get points(){return this.available}grant(e){this.available+=e}canSpend(e){return this.nextRankCost(e)!==null}spend(e){let t=this.nextRankCost(e);if(t===null)return!1;let n=this.stats.base(e);return this.available-=t,this.stats.setBase(e,n+1),!0}nextRankCost(e){let t=this.stats.base(e);if(t>=this.capFor(e))return null;let n=this.costFor(e,t+1);return this.available>=n?n:null}toJSON(){return{points:this.available}}static fromJSON(t,n,r){let i=new e(t,n);return i.available=r.points,i}},aL=class e{constructor(e,t=null,n={}){this.worn=new Map,this.names=new Set(e),this.stats=t,this.isSlotLocked=n.locked??(()=>!1)}get(e){return this.worn.get(e)}isLocked(e){let t=this.worn.get(e);return t!==void 0&&this.isSlotLocked(e,t)}equip(e,t){if(this.assertSlot(e),this.isLocked(e))return;let n=this.unequip(e);return this.wear(e,t),n}wear(e,t){this.worn.set(e,t);for(let e of t.modifiers??[])this.stats?.addModifier({...e,source:t})}unequip(e){let t=this.worn.get(e);if(t&&!this.isSlotLocked(e,t))return this.worn.delete(e),this.stats?.removeModifiersFrom(t),t}get slots(){return[...this.names]}assertSlot(e){if(!this.names.has(e))throw Error(`no such equipment slot: "${e}"`)}toJSON(e){return{worn:[...this.worn].map(([t,n])=>[t,e(n)])}}static fromJSON(t,n){let r=new e(t.slots,t.stats??null,{locked:t.locked});for(let[e,i]of n.worn)r.assertSlot(e),r.wear(e,t.resolve(i));return r}},oL=class e{constructor(e={}){this.slots=[],this.capacity=e.capacity}get items(){return this.slots}get totalWeight(){return this.slots.reduce((e,t)=>e+this.weightOf(t),0)}weightOf(e){return(e.weight??0)*e.quantity+(e.contents?.totalWeight??0)}find(e,t){return this.slots.find(n=>n.id===e&&(t===void 0||n.instanceId===t))}add(e){if(!Number.isFinite(e.quantity)||e.quantity<=0||e.weight!==void 0&&(!Number.isFinite(e.weight)||e.weight<0)||this.capacity!==void 0&&this.totalWeight+this.weightOf(e)>this.capacity)return!1;if(e.stackable){let t=this.slots.find(t=>t.id===e.id&&t.stackable&&t.instanceId===e.instanceId);if(t)return t.quantity+=e.quantity,!0}return this.slots.push({...e}),!0}remove(e,t,n){if(t!==void 0&&(!Number.isFinite(t)||t<=0))return;let r=this.slots.findIndex(t=>t.id===e&&(n===void 0||t.instanceId===n));if(r===-1)return;let i=this.slots[r];i.quantity-=t??i.quantity,i.quantity<=0&&this.slots.splice(r,1)}take(e,t=1,n){if(!Number.isFinite(t)||t<=0)return;let r=this.slots.findIndex(t=>t.id===e&&(n===void 0||t.instanceId===n));if(r===-1)return;let i=this.slots[r],a=Math.min(Math.floor(t),i.quantity);if(a<=0)return;let o={...i,quantity:a};return i.quantity-=a,i.quantity<=0&&this.slots.splice(r,1),o}toJSON(){return{capacity:this.capacity,slots:this.slots.map(e=>({id:e.id,quantity:e.quantity,instanceId:e.instanceId,identified:e.identified,cursed:e.cursed,blessed:e.blessed,level:e.level,affix:e.affix,durability:e.durability,maxDurability:e.maxDurability,contents:e.contents?.toJSON()}))}}static fromJSON(t,n){let r=new e({capacity:n.capacity});return r.slots=n.slots.map(n=>{let r=t.get(n.id);if(!r)throw Error(`Inventory.fromJSON: no definition for item "${n.id}"`);let{contents:i,...a}=n,o={...r,...sL(a),id:n.id,quantity:n.quantity};return i&&(o.contents=e.fromJSON(t,i)),o}),r}};function sL(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}function cL(e,t){return t.matches?t.matches(e):t.category===void 0?typeof t.id==`string`?e.id===t.id:(t.id??[]).includes(e.id):e.category===t.category}function lL(e){return e.matches!==void 0||e.category!==void 0||e.id!==void 0}function uL(e,t){let n=new Map;for(let t of e.items)n.set(t,t.quantity);let r=new Map;for(let i of t.ingredients){if(!lL(i))throw Error(`recipe ingredient must name an id, a category, or a matches predicate`);if(!Number.isFinite(i.quantity)||i.quantity<=0)throw Error(`recipe ingredient quantity must be a positive number`);let t=i.quantity;for(let a of e.items){if(t<=0)break;let e=n.get(a)??0;if(e<=0||!cL(a,i))continue;let o=Math.min(e,t);n.set(a,e-o),t-=o,r.set(a,(r.get(a)??0)+o)}if(t>0)return!1}for(let[t,n]of r)e.remove(t.id,n,t.instanceId);if(e.add(t.result))return!0;for(let[t,n]of r)e.add({...t,quantity:n});return!1}function dL(e,t){let n=e.add({duration:t.duration,tick:e=>t.tick?.(e),onExpire:t.onExpire});return{cancel:()=>{e.remove(n),t.onExpire()}}}function fL(e,t,n){let r=Symbol(`statusEffect`);for(let t of n.modifiers)e.addModifier({...t,source:r});return dL(t,{duration:n.duration,tick:n.tick,onExpire:()=>e.removeModifiersFrom(r)})}function pL(e,t={}){let n=e.entries.filter(e=>e.weight>0&&(t.curse===void 0||!!e.curse===t.curse)&&(t.predicate?.(e)??!0));if(n.length===0)return null;let r=ce(n.map(e=>e.weight));return r===null?null:n[r]}function mL(e){return e.affix}function hL(e,t){let n=e.affix!==void 0;e.affix=t.id,t.curse?e.cursed=!0:n&&(e.cursed=!1)}function gL(e){e.affix!==void 0&&(e.cursed=!1),delete e.affix}function _L(e,t){if(e.affix===void 0){gL(t);return}t.affix=e.affix,t.cursed=e.cursed??!1}function vL(e,t){return!(e.trigger!==t.trigger||e.kinds&&(t.kind===void 0||!e.kinds.includes(t.kind)))}function yL(e){e.identified=!0}function bL(e,t,n=`keep`){return Number.isFinite(t)?(e.level=(e.level??0)+t,n===`remove`&&gL(e),e.level):e.level??0}function xL(e,t){return e.maxDurability===void 0?!1:!Number.isFinite(t)||t<=0?(e.durability??e.maxDurability)<=0:(e.durability=Math.max(0,(e.durability??e.maxDurability)-t),e.durability<=0)}function SL(e,t){e.maxDurability!==void 0&&(!Number.isFinite(t)||t<=0||(e.durability=Math.min(e.maxDurability,(e.durability??e.maxDurability)+t)))}function CL(e,t,n){let r=new Map;for(let t of Object.keys(n.fields))r.set(t,e[t]),e[t]=n.fields[t];return dL(t,{duration:n.duration,tick:n.tick,onExpire:()=>{for(let[t,n]of r)e[t]=n}})}var wL=class e{constructor(e){this.progress=0,this.max=e.max,this.regenRate=e.regenRate,this.value=e.current??e.max}get current(){return this.value}canAfford(e){return this.value>=e}spend(e){return this.canAfford(e)?(this.value-=e,!0):!1}refund(e=1){let t=Math.min(e,this.max-this.value);return this.value+=t,t}advance(e=1){if(!(this.value>=this.max)){for(this.progress+=e;this.progress>=this.regenRate&&this.value<this.max;)this.progress-=this.regenRate,this.value++;this.value>=this.max&&(this.progress=0)}}toJSON(){return{current:this.value,progress:this.progress}}static fromJSON(t,n){let r=new e({...t,current:n.current});return r.progress=n.progress,r}};function TL(e){if(e.entries.length===0||!oe(e.chance??1))return null;let t=ce(e.entries.map(e=>e.weight));if(t===null)return null;let n=e.entries[t];return{id:n.id,quantity:n.quantity??1}}var EL=class e{constructor(e){this.grantedTiers=0,this.balance=0,this.choices=new Map,this.track=e}get points(){return this.balance}openTiers(e){let t=[];return this.track.tiers.forEach((n,r)=>{e>=n.threshold&&t.push(r)}),t}grant(e){let t=0;for(;this.grantedTiers<this.track.tiers.length&&e>=this.track.tiers[this.grantedTiers].threshold;){let e=this.track.tiers[this.grantedTiers];e.kind===`points`&&(this.balance+=e.points??0,t+=e.points??0),this.grantedTiers++}return t}spend(e){return this.balance<e?!1:(this.balance-=e,!0)}choose(e,t,n){let r=this.track.tiers[e];if(!r)throw Error(`no such advancement tier: ${e}`);if(r.kind===`points`)throw Error(`tier ${e} grants points, it has no choice`);if(n<r.threshold)throw Error(`tier ${e} has not opened yet`);if(this.choices.has(e))throw Error(`tier ${e} is already decided`);if(!(r.options??[]).some(e=>e.id===t))throw Error(`tier ${e} has no option "${t}"`);this.choices.set(e,t)}choice(e){return this.choices.get(e)??null}toJSON(){return{grantedTiers:this.grantedTiers,balance:this.balance,choices:[...this.choices]}}static fromJSON(t,n){let r=new e(t);r.grantedTiers=n.grantedTiers,r.balance=n.balance;for(let[e,t]of n.choices)r.choices.set(e,t);return r}};function DL(e,t){return t.map(t=>({stat:t.stat,op:t.op,value:t.base+t.perLevel*e}))}function OL(e){if(e.labels.length<e.kinds.length)throw Error(`not enough appearances: ${e.kinds.length} kinds but only ${e.labels.length} labels`);let t=[...e.labels];for(let e=t.length-1;e>0;e--){let n=k(0,e+1);[t[e],t[n]]=[t[n],t[e]]}let n=new Map;return e.kinds.forEach((e,r)=>n.set(e,t[r])),n}var kL=class e{constructor(e){this.assigned=new Map,this.tables=e}appearanceOf(e,t){let n=this.assigned.get(e);if(!n){let t=this.tables[e];if(!t)throw Error(`no such appearance category: "${e}"`);n=OL(t),this.assigned.set(e,n)}let r=n.get(t);if(r===void 0)throw Error(`"${t}" is not in appearance category "${e}"`);return r}toJSON(){return{assigned:[...this.assigned].map(([e,t])=>[e,[...t]])}}static fromJSON(t,n){let r=new e(t);for(let[e,t]of n.assigned)r.assigned.set(e,new Map(t));return r}};function AL(e,t,n,r,i,a){let o=a.prices.get(r);if(!o)return!1;let s=t.find(r);if(!s||s.quantity<i)return!1;let c=o.buy*i;return e.base(a.currency)<c?!1:(t.remove(r,i),n.add({...s,quantity:i})?(e.setBase(a.currency,e.base(a.currency)-c),!0):(t.add({...s,quantity:i}),!1))}function jL(e,t,n,r,i,a){let o=a.prices.get(r);if(!o)return!1;let s=n.find(r);return!s||s.quantity<i?!1:(n.remove(r,i),t.add({...s,quantity:i}),e.setBase(a.currency,e.base(a.currency)+o.sell*i),!0)}function ML(e){let t=Array.isArray(e)?e:[e];for(let e of t)if(!Number.isFinite(e.amount)||e.amount<0)throw Error(`a resource cost must be a non-negative number, "${e.stat}" costs ${e.amount}`);return t}function NL(e){let t=new Map;for(let n of e)t.set(n.stat,(t.get(n.stat)??0)+n.amount);return t}function PL(e,t){return[...NL(ML(t))].every(([t,n])=>e.base(t)>=n)}function FL(e,t){let n=NL(ML(t));if(![...n].every(([t,n])=>e.base(t)>=n))return!1;for(let[t,r]of n)e.setBase(t,e.base(t)-r);return!0}function IL(e,t,n=1){for(let[r,i]of NL(ML(t)))e.setBase(r,e.base(r)+i*n)}function LL(e,t,n,r){return FL(e,t)?n.refund(Math.floor(t.amount/r)):0}var RL=class e{constructor(){this.layers=[]}add(e,t=0){e<=0||this.layers.push({amount:e,decayPerTick:t})}get total(){return this.layers.reduce((e,t)=>e+t.amount,0)}get layerCount(){return this.layers.length}absorb(e){let t=e,n=0;for(;t>0&&this.layers.length>0;){let e=this.layers[this.layers.length-1],r=Math.min(e.amount,t);e.amount-=r,t-=r,n+=r,e.amount<=0&&this.layers.pop()}return n}advance(e=1){for(let t=this.layers.length-1;t>=0;t--){let n=this.layers[t];n.decayPerTick&&(n.amount-=n.decayPerTick*e,n.amount<=0&&this.layers.splice(t,1))}}clear(){this.layers=[]}toJSON(){return{layers:this.layers.map(e=>({...e}))}}static fromJSON(t){let n=new e;return n.layers=t.layers.map(e=>({...e})),n}};function zL(e,t,n){return le([...t]).slice(0,Math.min(n,t.length)).map(t=>{let n=Symbol(`trait:${t.name}`);for(let r of t.modifiers)e.addModifier({...r,source:n});return{trait:t,source:n}})}var BL=class{constructor(){this.affected=new Map}update(e,t){let n=new Set(e),r=e.filter(e=>!!e.aura),i=new Set(r);for(let i of r){let r=this.affected.get(i);r||(r=new Map,this.affected.set(i,r));for(let n of e){if(n===i)continue;let e=t(i,n),a=r.get(n);if(e&&!a){let e=Symbol(`aura:${i.aura.name}`);for(let t of i.aura.modifiers)n.stats.addModifier({...t,source:e});r.set(n,e)}else!e&&a&&(n.stats.removeModifiersFrom(a),r.delete(n))}for(let[e,t]of[...r])n.has(e)||(e.stats.removeModifiersFrom(t),r.delete(e))}for(let[e,t]of[...this.affected])if(!i.has(e)){for(let[e,n]of t)e.stats.removeModifiersFrom(n);this.affected.delete(e)}}},VL=class e{constructor(e){if(this.points=new Map,e.some(e=>!e.id||!Number.isFinite(e.threshold)||e.threshold<0))throw Error(`support levels need an id and a non-negative threshold`);this.levels=[...e].sort((e,t)=>e.threshold-t.threshold)}get(e,t){return this.points.get(HL(e,t))??0}level(e,t){let n=this.get(e,t),r=null;for(let e of this.levels){if(e.threshold>n)break;r=e}return r}add(e,t,n){if(!e||!t||e===t)throw Error(`support needs two different named units`);if(!Number.isFinite(n))throw Error(`support amount must be finite, got ${n}`);let r=this.level(e,t),i=HL(e,t),a=Math.max(0,(this.points.get(i)??0)+n);return this.points.set(i,a),{a:e,b:t,points:a,previousLevel:r,level:this.level(e,t)}}toJSON(){return{pairs:[...this.points].map(([e,t])=>{let[n,r]=e.split(`\0`);return[n,r,t]})}}static fromJSON(t,n){let r=new e(t);for(let[e,t,i]of n.pairs){if(!e||!t||e===t||!Number.isFinite(i)||i<0)throw Error(`invalid support save data`);let n=HL(e,t);if(r.points.has(n))throw Error(`invalid support save data: duplicate pair "${e}" / "${t}"`);r.points.set(n,i)}return r}};function HL(e,t){return[e,t].sort().join(`\0`)}var UL=new Set([`id`,`growth`,`level`,`startingAffix`,`startingItem`,`lowHpReaction`]);function WL(e,t={},n){let r=new eL({base:YL(e)}),i;e.growth!==void 0&&(i=new nL(JL(e,t),{level:e.level??1}));let a;if(e.startingItem!==void 0){let n=t.items?.[e.startingItem];if(!n)throw Error(`entity template "${e.id}": unknown starting item "${e.startingItem}"`);if(a=n(),e.startingAffix!==void 0){let n=t.affixes?.[e.startingAffix];if(!n)throw Error(`entity template "${e.id}": unknown affix "${e.startingAffix}"`);hL(a,n)}}else if(e.startingAffix!==void 0)throw Error(`entity template "${e.id}": a starting affix needs a starting item to carry it`);let o=new en,s={id:e.id,stats:r,progression:i,item:a,reactions:o};if(e.lowHpReaction!==void 0){if(!n)throw Error(`entity template "${e.id}": names a lowHpReaction threshold but no onLowHp callback was given`);let t=e.lowHpReaction;o.add({id:`low-hp`,when:e=>e.hp/e.maxHp<=t,action:()=>n(s)})}return s}function GL(e,t={},n){return e.map(e=>WL(e,t,n))}function KL(e){let t={stats:e.stats.toJSON()};return e.progression&&(t.progression=e.progression.toJSON()),e.item&&(t.item=e.item),t}function qL(e,t,n,r){let i=WL(e,t,r);if(i.stats=eL.fromJSON({base:YL(e)},n.stats),n.progression!==void 0){if(!i.progression)throw Error(`entity template "${e.id}": save data has progression but the row names no growth curve`);i.progression=nL.fromJSON(JL(e,t),n.progression)}return n.item!==void 0&&(i.item=n.item),i}function JL(e,t){let n=t.growthCurves?.[e.growth??``];if(!n)throw Error(`entity template "${e.id}": unknown growth curve "${e.growth}"`);return n}function YL(e){let t={};for(let[n,r]of Object.entries(e))if(!UL.has(n)){if(typeof r!=`number`)throw Error(`entity template "${e.id}": stat "${n}" must be a number, got ${typeof r}`);t[n]=r}return t}var XL=l({Advancement:()=>EL,Appearances:()=>kL,AuraField:()=>BL,Barrier:()=>RL,Charges:()=>wL,EquipmentSlots:()=>aL,Inventory:()=>oL,Progression:()=>nL,SkillPoints:()=>iL,StatBlock:()=>eL,SupportLedger:()=>VL,affixOf:()=>mL,applyAffix:()=>hL,applyItemStatusEffect:()=>CL,applyStatusEffect:()=>fL,assignAppearances:()=>OL,assignTraits:()=>zL,buildEntities:()=>GL,buildEntity:()=>WL,buy:()=>AL,canAfford:()=>PL,composeModifiers:()=>$I,convertToCharges:()=>LL,copyAffix:()=>_L,craft:()=>uL,damageItem:()=>xL,enchant:()=>bL,fromEntitySaveState:()=>qL,identify:()=>yL,matchesContext:()=>vL,powerCurve:()=>tL,refund:()=>IL,removeAffix:()=>gL,repairItem:()=>SL,rollAffix:()=>pL,rollLoot:()=>TL,scaledModifiers:()=>DL,sell:()=>jL,skillCheck:()=>rL,spend:()=>FL,toEntitySaveState:()=>KL}),ZL=class{constructor(){this.factories=new Map,this.loaded=new Map,this.currentId=null}define(e,t,n={}){this.factories.set(e,{create:t,persistent:n.persistent??!0})}enter(e,t){let n=this.factories.get(e);if(!n)throw Error(`no such map: "${e}"`);let r=this.loaded.get(e);return(!r||!n.persistent)&&(r=n.create(),this.loaded.set(e,r)),this.currentId=e,this.lastSpawn=t,r}get current(){return this.currentId?this.loaded.get(this.currentId)??null:null}get currentMapId(){return this.currentId}get spawn(){return this.lastSpawn}isLoaded(e){return this.loaded.has(e)}isPersistent(e){return this.factories.get(e)?.persistent??!0}unload(e){if(e===this.currentId)throw Error(`cannot unload the current map: "${e}"`);this.loaded.delete(e)}},QL=class{constructor(){this.locations=new Map}add(e){this.locations.set(e.id,e)}remove(e){this.locations.delete(e)}get(e){return this.locations.get(e)}at(e,t){for(let n of this.locations.values())if(n.x===e&&n.y===t)return n}get all(){return[...this.locations.values()]}},$L=class{constructor(){this.turn=0,this.effects=new Map}add(e){let t=Symbol();return this.effects.set(t,{...e}),t}remove(e){this.effects.delete(e)}has(e){return this.effects.has(e)}advance(e=1){this.turn+=e;for(let[t,n]of this.effects)n.tick(this.turn),n.duration!==void 0&&(n.duration-=e,n.duration<=0&&(this.effects.delete(t),n.onExpire?.()))}};function eR(e){if(e.entries.length===0||!oe(e.rate))return null;let t=ce(e.entries.map(e=>e.weight));return t===null?null:e.entries[t].value}var tR=class e{constructor(e={}){if(this.changed=new p,this.dayLength=e.dayLength??120,!(this.dayLength>0))throw Error(`an environment day must be longer than zero seconds`);if(this.boundaries=e.phaseBoundaries??[.2,.7,.8],this.boundaries[0]<=0||this.boundaries[0]>=this.boundaries[1]||this.boundaries[1]>=this.boundaries[2]||this.boundaries[2]>=1)throw Error(`environment phase boundaries must be ascending fractions strictly between 0 and 1`);if(this.seconds_=e.startSeconds??0,this.weather_=e.startWeather??`clear`,!Number.isFinite(this.seconds_))throw Error(`environment startSeconds must be finite`)}get day(){return Math.floor(this.seconds_/this.dayLength)}get seconds(){return this.seconds_}get weather(){return this.weather_}get phase(){let e=(this.seconds_%this.dayLength+this.dayLength)%this.dayLength/this.dayLength;return e<this.boundaries[0]?`dawn`:e<this.boundaries[1]?`day`:e<this.boundaries[2]?`dusk`:`night`}get night(){return this.phase===`night`}update(e){if(!Number.isFinite(e)||e<0)throw Error(`environment update must be non-negative, got ${e}`);this.seconds_+=e;let t=this.toJSON();return this.changed.dispatch(t),t}setWeather(e){if(!e)throw Error(`weather needs a non-empty id`);this.weather_=e;let t=this.toJSON();return this.changed.dispatch(t),t}toJSON(){return{day:this.day,seconds:this.seconds_,phase:this.phase,weather:this.weather_}}static fromJSON(t,n){return new e({...t,startSeconds:n.seconds,startWeather:n.weather})}},nR=class e{constructor(e){if(e.sides.length===0)throw Error(`SideTurns needs at least one side`);if(e.schedule.length===0)throw Error(`SideTurns needs a non-empty schedule`);let t=e.round??1,n=e.sideIndex??0,r=e.timeIndex??0;if(!Number.isInteger(t)||t<1)throw Error(`SideTurns round must be a positive integer`);if(n<0||n>=e.sides.length)throw Error(`SideTurns side index ${n} is outside ${e.sides.length} sides`);if(r<0||r>=e.schedule.length)throw Error(`SideTurns time index ${r} is outside ${e.schedule.length} times`);this.sides=[...e.sides],this.schedule=[...e.schedule],this.areas=e.areas??[],this.state={round:t,sideIndex:n,timeIndex:r}}get round(){return this.state.round}get side(){return this.sides[this.state.sideIndex]}get timeIndex(){return this.state.timeIndex}get timeOfDay(){return this.schedule[this.state.timeIndex]}get snapshot(){return{...this.state}}timeOfDayAt(e,t){for(let n of this.areas)if(n.contains(e,t))return n.times[this.state.timeIndex]??this.timeOfDay;return this.timeOfDay}lawfulBonusAt(e,t,n){return rR(e,this.timeOfDayAt(t,n).lawfulBonus)}advance(){let e=!1;return this.state.sideIndex++,this.state.sideIndex>=this.sides.length&&(this.state.sideIndex=0,this.state.round++,this.state.timeIndex=(this.state.timeIndex+1)%this.schedule.length,e=!0),{side:this.side,round:this.state.round,newRound:e}}toJSON(){return this.snapshot}static fromJSON(t,n){return new e({...t,round:n.round,sideIndex:n.sideIndex,timeIndex:n.timeIndex})}};function rR(e,t){switch(e){case`lawful`:return t;case`chaotic`:return-t;default:return 0}}var iR=l({EnvironmentClock:()=>tR,Overworld:()=>QL,SideTurns:()=>nR,TurnClock:()=>$L,World:()=>ZL,alignmentBonus:()=>rR,rollEncounter:()=>eR});function aR(e,t,n={}){let r=n.pick??k,i=0;return t.forEach((t,n)=>{oR(t,t.name??`#${n+1}`,e.shape);let a=sR(e,t);if(i+=a.length,a.length!==0)for(let[n,i]of a){let a=t.outputs[r(t.outputs.length)];for(let[r,o]of Object.entries(a))for(let a=0;a<t.height;a++)for(let s=0;s<t.width;s++){let c=o[a*t.width+s];c!==-1&&e.setTile(r,n+s,i+a,c)}}}),i}function oR(e,t,n){if(e.topology&&(n===`square`||n===`hex`)&&e.topology!==n)throw Error(`automap rule "${t}" targets ${e.topology} cells, but the map is ${n}`);if(!Number.isInteger(e.width)||e.width<=0||!Number.isInteger(e.height)||e.height<=0)throw Error(`automap rule "${t}" needs a positive width and height`);if(e.outputs.length===0)throw Error(`automap rule "${t}" has no outputs - a rule that matches and writes nothing is a mistake`);let r=e.width*e.height;for(let[n,i]of Object.entries(e.input))if(i.length!==r)throw Error(`automap rule "${t}" input "${n}" has ${i.length} cells, but the pattern is ${r}`);e.outputs.forEach((e,n)=>{for(let[i,a]of Object.entries(e))if(a.length!==r)throw Error(`automap rule "${t}" output ${n+1} "${i}" has ${a.length} cells, but the pattern is ${r}`)})}function sR(e,t){let n=[];for(let r=0;r+t.height<=e.heightInTiles;r++)for(let i=0;i+t.width<=e.widthInTiles;i++)cR(e,t,i,r)&&n.push([i,r]);return n}function cR(e,t,n,r){for(let[i,a]of Object.entries(t.input))for(let o=0;o<t.height;o++)for(let s=0;s<t.width;s++){let c=a[o*t.width+s];if(c!==-1&&e.getTile(i,n+s,r+o)!==c)return!1}return!0}var lR=class e{constructor(){this.switches=new Map,this.variables=new Map}switch(e){return this.switches.get(e)??!1}setSwitch(e,t){this.switches.set(e,t)}variable(e){return this.variables.get(e)??0}setVariable(e,t){this.variables.set(e,t)}toJSON(){return{switches:[...this.switches],variables:[...this.variables]}}static fromJSON(t){let n=new e;for(let[e,r]of t.switches)n.setSwitch(e,r);for(let[e,r]of t.variables)n.setVariable(e,r);return n}};function uR(e,t){return`switch`in e?t.switch(e.switch)===e.equals:t.variable(e.variable)>=e.atLeast}function dR(e,t){let n;for(let r of e.pages)(r.conditions??[]).every(e=>uR(e,t))&&(n=r);return n}var fR=class{constructor(e){this.cancelled=!1,this.options=e,this.state={game:e.game,answers:{}}}cancel(){this.cancelled=!0}async run(e){for(let t of e){if(this.cancelled)break;await this.step(t)}return this.state}async step(e){if(`say`in e){await this.speak(e.say,e.speaker);return}if(`ask`in e){let t=await this.speak(e.ask,e.speaker,e.choices);e.store&&(this.state.answers[e.store]=t);return}if(`wait`in e){await new Promise(t=>setTimeout(t,e.wait*1e3));return}if(`setSwitch`in e){this.state.game.setSwitch(e.setSwitch,e.value);return}if(`setVariable`in e){this.state.game.setVariable(e.setVariable,e.value);return}if(`addVariable`in e){let t=this.state.game.variable(e.addVariable);this.state.game.setVariable(e.addVariable,t+e.amount);return}if(`if`in e){let t=uR(e.if,this.state.game);await this.run(t?e.then:e.else??[]);return}if(`move`in e){await this.options.move?.(e.move.target,e.move.steps);return}`call`in e&&await e.call(this.state)}speak(e,t,n){return this.options.present({text:e,speaker:t,choices:n})}};function pR(e,t){t&&e.has?.(t)&&e.play?.(t)}var mR=class{constructor(e,t,n,r){this.facing=`down`,this.target=null,this.progress=0,this.sprite=e,this.x=this.fromX=t,this.y=this.fromY=n,this.tileWidth=r.tileWidth,this.tileHeight=r.tileHeight,this.speed=r.speed??4,this.options=r,this.place(),this.playIdle()}get isMoving(){return this.target!==null}turnTo(e,t){this.target||(this.facing=hR(e,t),this.playIdle())}moveBy(e,t){return!this.target&&(this.facing=hR(e,t),this.fromX=this.x,this.fromY=this.y,this.target={x:this.x+e,y:this.y+t},this.progress=0,this.playWalk(),!0)}update(e){this.sprite.update?.(e),this.target&&(this.progress=Math.min(1,this.progress+this.speed*e),this.sprite.x=gR(this.fromX,this.target.x,this.progress)*this.tileWidth,this.sprite.y=gR(this.fromY,this.target.y,this.progress)*this.tileHeight,this.progress>=1&&(this.x=this.target.x,this.y=this.target.y,this.target=null,this.playIdle()))}place(){this.sprite.x=this.x*this.tileWidth,this.sprite.y=this.y*this.tileHeight}playWalk(){pR(this.sprite,this.options.walkAnimation?.(this.facing))}playIdle(){pR(this.sprite,this.options.idleAnimation?.(this.facing))}};function hR(e,t){return e>0?`right`:e<0?`left`:t>0?`down`:`up`}function gR(e,t,n){return e+(t-e)*n}var _R=class{constructor(e,t,n,r={}){this.facing=0,this.moving=!1,this.sprite=e,this.x=t,this.y=n,this.speed=r.speed??4,this.options=r,this.place(),this.playIdle()}get isMoving(){return this.moving}move(e,t,n){let r=Math.hypot(e,t);r>0?(this.facing=Math.atan2(t,e),this.x+=e/r*this.speed*n,this.y+=t/r*this.speed*n,this.moving||(this.moving=!0,this.playWalk())):this.moving&&(this.moving=!1,this.playIdle()),this.place(),this.sprite.update?.(n)}turnTo(e,t){this.moving||e===0&&t===0||(this.facing=Math.atan2(t,e),this.playIdle())}place(){this.sprite.x=this.x,this.sprite.y=this.y}playWalk(){pR(this.sprite,this.options.walkAnimation?.(this.facing))}playIdle(){pR(this.sprite,this.options.idleAnimation?.(this.facing))}};function vR(e,t){return e.x<t.x+t.width&&e.x+e.width>t.x&&e.y<t.y+t.height&&e.y+e.height>t.y}function yR(e,t){let n=e.x-t.x,r=e.y-t.y,i=e.radius+t.radius;return n*n+r*r<i*i}function bR(e,t){let n=CR(e.x,t.x,t.x+t.width),r=CR(e.y,t.y,t.y+t.height),i=e.x-n,a=e.y-r;return i*i+a*a<e.radius*e.radius}function xR(e,t,n,r){let{tileSize:i,isSolid:a}=r;if(!(i>0))throw Error(`collision tileSize must be positive`);let o=SR(e.x,e.y,e.width,e.height,t,i,a,!0);return{x:o,y:SR(o,e.y,e.width,e.height,n,i,a,!1)}}function SR(e,t,n,r,i,a,o,s){if(i===0)return s?e:t;let c=s?e:t,l=s?n:r,u=c+i,d=Math.floor((s?t:e)/a),f=Math.floor(((s?t+r:e+n)-1e-6)/a),p=(e,t)=>s?o(e,t):o(t,e);if(i>0){let e=Math.floor((c+l-1e-6)/a),t=Math.floor((u+l-1e-6)/a);for(let n=e+1;n<=t;n++)for(let e=d;e<=f;e++)if(p(n,e))return n*a-l}else{let e=Math.floor(c/a),t=Math.floor(u/a);for(let n=e-1;n>=t;n--)for(let e=d;e<=f;e++)if(p(n,e))return(n+1)*a}return u}function CR(e,t,n){return e<t?t:e>n?n:e}var wR=class e{constructor(){this.definitions=new Map,this.stageIndex=new Map,this.tracked=null}define(e){this.definitions.set(e.id,e)}track(e){e!==null&&this.require(e),this.tracked=e}trackedQuest(){return this.tracked!==null&&this.status(this.tracked)===`active`?this.tracked:null}trackedLocation(){let e=this.trackedQuest();return e?this.currentStage(e)?.location??null:null}markerFor(e,t){return e.some(e=>this.status(e)===`active`&&this.stageSatisfied(e,t))?`turnIn`:e.some(e=>this.status(e)===`available`)?`offer`:`none`}canStart(e){return(this.require(e).requires??[]).every(e=>this.status(e)===`complete`)}start(e){if(!this.canStart(e))throw Error(`quest "${e}" cannot start yet - a prerequisite is incomplete`);this.stageIndex.set(e,0)}status(e){let t=this.require(e),n=this.stageIndex.get(e);return n===void 0?this.canStart(e)?`available`:`unavailable`:n>=t.stages.length?`complete`:`active`}currentStage(e){return this.status(e)===`active`?this.require(e).stages[this.stageIndex.get(e)]:null}progress(e,t){let n=this.currentStage(e);return n?.counter?Math.min(1,t.variable(n.counter.variable)/n.counter.target):null}advanceStage(e,t){return this.stageSatisfied(e,t)?(this.stageIndex.set(e,this.stageIndex.get(e)+1),!0):!1}stageSatisfied(e,t){let n=this.currentStage(e);return n?n.condition?uR(n.condition,t):!n.counter||t.variable(n.counter.variable)>=n.counter.target:!1}require(e){let t=this.definitions.get(e);if(!t)throw Error(`no such quest: "${e}"`);return t}toJSON(){return{stageIndex:[...this.stageIndex],tracked:this.tracked}}static fromJSON(t,n){let r=new e;for(let e of t)r.define(e);for(let[e,t]of n.stageIndex)r.stageIndex.set(e,t);return n.tracked&&(r.tracked=n.tracked),r}};function TR(e){let t=[],n=new Map;for(let r of e){let e=n.get(r.questId);e||(e={id:r.questId,stages:[]},r.requires!==void 0&&(e.requires=r.requires),n.set(r.questId,e),t.push(r.questId)),e.stages.push(ER(e.id,r))}return t.map(e=>n.get(e))}function ER(e,t){if(t.conditionSwitch!==void 0&&t.conditionVariable!==void 0)throw Error(`quest "${e}": a stage row cannot name both a condition switch and a condition variable`);let n={};if(t.conditionSwitch!==void 0){if(t.conditionEquals===void 0)throw Error(`quest "${e}": conditionSwitch needs a conditionEquals`);n.condition={switch:t.conditionSwitch,equals:t.conditionEquals}}else if(t.conditionVariable!==void 0){if(t.conditionAtLeast===void 0)throw Error(`quest "${e}": conditionVariable needs a conditionAtLeast`);n.condition={variable:t.conditionVariable,atLeast:t.conditionAtLeast}}if(t.counterVariable!==void 0){if(t.counterTarget===void 0)throw Error(`quest "${e}": counterVariable needs a counterTarget`);n.counter={variable:t.counterVariable,target:t.counterTarget}}if(t.description!==void 0&&(n.description=t.description),t.locationMap!==void 0||t.locationX!==void 0||t.locationY!==void 0){if(t.locationX===void 0||t.locationY===void 0)throw Error(`quest "${e}": a stage location needs both locationX and locationY`);n.location={x:t.locationX,y:t.locationY},t.locationMap!==void 0&&(n.location.map=t.locationMap)}return n}var DR=class{constructor(e){this.name=e}},OR=4,kR=8,AR=new WeakMap;function jR(e){return AR.get(e)}function MR(e,t){return AR.set(e,t),e}var NR=class{constructor(e){this.pos=0,this.symbols=[],this.objects=[],this.bytes=e}byte(){if(this.pos>=this.bytes.length)throw Error(`Marshal: unexpected end of input`);return this.bytes[this.pos++]}take(e){if(e<0)throw Error(`Marshal: negative length`);let t=this.bytes.subarray(this.pos,this.pos+e);if(t.length<e)throw Error(`Marshal: unexpected end of input`);return this.pos+=e,t}readFixnum(){let e=this.byte()<<24>>24;if(e===0)return 0;if(e>=5&&e<=127)return e-5;if(e<=-5&&e>=-128)return e+5;if(e>0){let t=0;for(let n=0;n<e;n++)t|=this.byte()<<8*n;return t>>>0}let t=-e,n=0;for(let e=0;e<t;e++)n|=this.byte()<<8*e;return(n>>>0)-2**(8*t)}readBytes(){return this.take(this.readFixnum())}readSymbol(){let e=new TextDecoder().decode(this.readBytes());return this.symbols.push(e),e}readSymbolLink(){let e=this.readFixnum(),t=this.symbols[e];if(t===void 0)throw Error(`Marshal: symbol link ${e} out of range`);return t}readSymbolValue(){let e=String.fromCharCode(this.byte());if(e===`:`)return this.readSymbol();if(e===`;`)return this.readSymbolLink();throw Error(`Marshal: expected a symbol, got tag "${e}"`)}link(e){return this.objects.push(e),e}readBignum(){let e=String.fromCharCode(this.byte())===`-`?-1:1,t=this.readFixnum(),n=0,r=1;for(let e=0;e<t;e++)n+=(this.byte()|this.byte()<<8)*r,r*=65536;return e*n}readFloat(){let e=new TextDecoder().decode(this.readBytes());return e===`inf`?1/0:e===`-inf`?-1/0:e===`nan`?NaN:Number(e)}readArray(){let e=[];this.link(e);let t=this.readFixnum();for(let n=0;n<t;n++)e.push(this.readValue());return e}readHash(e){let t=new Map;this.link(t);let n=this.readFixnum();for(let e=0;e<n;e++)t.set(this.readValue(),this.readValue());return e&&AR.set(t,this.readValue()),t}readIvars(e){let t={};for(let n=0;n<e;n++)t[this.readSymbolValue()]=this.readValue();return t}readObject(){let e={class:``,ivars:{}};return this.link(e),e.class=this.readSymbolValue(),e.ivars=this.readIvars(this.readFixnum()),e}readIvarWrapped(){let e=this.readValue();return this.readIvars(this.readFixnum()),e}readUserDefined(){let e={class:``,raw:new Uint8Array};return this.link(e),e.class=this.readSymbolValue(),e.raw=this.readBytes().slice(),e}readUserMarshal(){let e={class:``,value:null};return this.link(e),e.class=this.readSymbolValue(),e.value=this.readValue(),e}readValue(){let e=String.fromCharCode(this.byte());switch(e){case`0`:return null;case`T`:return!0;case`F`:return!1;case`i`:return this.readFixnum();case`l`:return this.link(this.readBignum());case`f`:return this.link(this.readFloat());case`:`:return this.readSymbol();case`;`:return this.readSymbolLink();case`"`:return this.link(new TextDecoder().decode(this.readBytes()));case`[`:return this.readArray();case`{`:return this.readHash(!1);case`}`:return this.readHash(!0);case`o`:return this.readObject();case`I`:return this.readIvarWrapped();case`u`:return this.readUserDefined();case`U`:return this.readUserMarshal();case`@`:{let e=this.readFixnum(),t=this.objects[e];if(t===void 0)throw Error(`Marshal: object link ${e} out of range`);return t}default:throw Error(`Marshal: unsupported tag "${e}" (0x${e.charCodeAt(0).toString(16)})`)}}readDocument(){let e=this.byte(),t=this.byte();if(e!==OR||t>kR)throw Error(`Marshal: unsupported version ${e}.${t} (expected ${OR}.${kR} or lower)`);return this.readValue()}};function PR(e){return new NR(e).readDocument()}function FR(e){return typeof e==`object`&&!!e&&`class`in e&&`ivars`in e}function IR(e){let t=[OR,kR];return LR(t,e),new Uint8Array(t)}function LR(e,t){if(t==null)e.push(RR(`0`));else if(t===!0)e.push(RR(`T`));else if(t===!1)e.push(RR(`F`));else if(t instanceof DR)e.push(RR(`:`)),zR(e,t.name);else if(typeof t==`number`)Number.isInteger(t)&&Math.abs(t)<2**30?(e.push(RR(`i`)),BR(e,t)):(e.push(RR(`f`)),zR(e,Number.isFinite(t)?String(t):t>0?`inf`:t<0?`-inf`:`nan`));else if(typeof t==`string`)e.push(RR(`"`)),zR(e,t);else if(Array.isArray(t)){e.push(RR(`[`)),BR(e,t.length);for(let n of t)LR(e,n)}else if(t instanceof Map){let n=AR.has(t);e.push(RR(n?`}`:`{`)),BR(e,t.size);for(let[n,r]of t)LR(e,n),LR(e,r);n&&LR(e,AR.get(t))}else if(FR(t)){e.push(RR(`o`)),e.push(RR(`:`)),zR(e,t.class);let n=Object.entries(t.ivars);BR(e,n.length);for(let[t,r]of n)e.push(RR(`:`)),zR(e,t),LR(e,r)}else throw Error(`Marshal: cannot encode a value of type ${typeof t}`)}function RR(e){return e.charCodeAt(0)}function zR(e,t){let n=new TextEncoder().encode(t);BR(e,n.length);for(let t of n)e.push(t)}function BR(e,t){if(t===0){e.push(0);return}if(t>0&&t<=122){e.push(t+5);return}if(t<0&&t>=-123){e.push(t-5&255);return}if(t>0){for(let n=1;n<=4;n++)if(t<2**(8*n)){e.push(n);for(let r=0;r<n;r++)e.push(t>>>8*r&255);return}}else for(let n=1;n<=4;n++)if(t>=-(2**(8*n))){e.push(-n&255);let r=t+2**(8*n);for(let t=0;t<n;t++)e.push(r>>>8*t&255);return}throw Error(`Marshal: integer ${t} is out of range for a Fixnum`)}var VR=l({AUTOMAP_EMPTY:()=>-1,EventRunner:()=>fR,FreeMover:()=>_R,GameState:()=>lR,GridMover:()=>mR,QuestLog:()=>wR,RubySymbol:()=>DR,aabbOverlap:()=>vR,activePage:()=>dR,automap:()=>aR,circleAabbOverlap:()=>bR,circleOverlap:()=>yR,conditionHolds:()=>uR,decodeMarshal:()=>PR,encodeMarshal:()=>IR,hashDefaultOf:()=>jR,questsFromRows:()=>TR,resolveAabbAgainstTiles:()=>xR,withHashDefault:()=>MR}),HR=tL(20,2,100),UR=class{constructor(e){this.species=e.species,this.deriveStats=e.deriveStats,this.progression=new nL(e.species.growth??HR,{level:e.level??1}),this.stats=new eL({base:this.computeBase()})}refreshStats(){let e=this.computeBase();for(let[t,n]of Object.entries(e))this.stats.setBase(t,n)}computeBase(){let e=this.progression.level;return this.deriveStats?this.deriveStats(this.species.baseStats,e):{...this.species.baseStats}}},WR=class{constructor(){this.multipliers=new Map}key(e,t){return`${e}:${t}`}set(e,t,n){this.multipliers.set(this.key(e,t),n)}get(e,t){return this.multipliers.get(this.key(e,t))??1}multiplierFor(e,t){return t.reduce((t,n)=>t*this.get(e,n),1)}},GR=class{constructor(e){this.storage=[],this.active=Array(e).fill(null)}get members(){return this.active}get boxed(){return this.storage}add(e){let t=this.active.indexOf(null);t===-1?this.storage.push(e):this.active[t]=e}store(e){let t=this.active[e];t&&(this.active[e]=null,this.storage.push(t))}withdraw(e,t){if(t<0||t>=this.active.length)return;let n=this.storage[e];if(!n)return;this.storage.splice(e,1);let r=this.active[t];this.active[t]=n,r&&this.storage.push(r)}get activeMembers(){return this.active.filter(e=>e!==null)}};function KR(e){return[...e].sort((e,t)=>(t.priority??0)-(e.priority??0)||t.speed-e.speed)}function qR(e,t){let n=null;for(let r of e)r.at(t)&&(n=r.into);return n}var JR=class{constructor(e,t){this.stages=new Map,this.modifiers=new Map,this.stats=e,this.max=t.max,this.multiplierFor=t.multiplier}get(e){return this.stages.get(e)??0}change(e,t){let n=this.get(e),r=Math.max(-this.max,Math.min(this.max,n+t)),i=r-n;return i===0?0:(this.stages.set(e,r),this.applyModifier(e,r),i)}applyModifier(e,t){let n=this.modifiers.get(e);if(n&&this.stats.removeModifier(n),t===0){this.modifiers.delete(e);return}let r={stat:e,op:`multiply`,value:this.multiplierFor(t)};this.stats.addModifier(r),this.modifiers.set(e,r)}resetAll(){for(let e of this.modifiers.values())this.stats.removeModifier(e);this.modifiers.clear(),this.stages.clear()}};function YR(e,t,n,r=(e,n)=>t.multiplierFor(e.type,n)){if(e.length===0)return null;let i=e[0],a=r(i,n);for(let t of e.slice(1)){let e=r(t,n);e>a&&(a=e,i=t)}return i}function XR(e,t,n,r){let i=null,a=ZR(e,n,r);return t.forEach((e,t)=>{let o=ZR(e.types,n,r);o<a&&(a=o,i=t)}),i}function ZR(e,t,n){return Math.max(...n.map(n=>t.multiplierFor(n,e)))}var QR=class extends x{},$R=class{constructor(){this.conditions=new Map}set(e){this.conditions.set(e.id,{...e})}has(e){return this.conditions.has(e)}get(e){return this.conditions.get(e)}clear(e){this.conditions.delete(e)}get active(){return[...this.conditions.values()]}advance(e=1){for(let[t,n]of this.conditions)n.duration!==void 0&&(n.duration-=e,n.duration<=0&&this.conditions.delete(t))}},ez=class{constructor(e){this.chanceToHit=tz(e.chanceToHit??1),this.strikeDuration=Math.max(0,e.strikeDuration??0),this.totalDamage=Math.max(0,e.damage)*Math.max(0,e.strikes),this.expectedDamage=this.totalDamage*this.chanceToHit,this.defenderHp0=e.defender.hp;let t=[],n=e.defender.hp;for(let r=0;r<=e.strikes;r++)r>0&&(e.hits?.[r-1]??!0)&&(n-=Math.max(0,e.damage)),t.push({strike:r,time:r*this.strikeDuration,attackerHp:e.attacker.hp,defenderHp:Math.max(0,n),defenderDamage:this.defenderHp0-Math.max(0,n)});this.frames=t}get duration(){return this.strikeDuration*(this.frames.length-1)}get defenderKilled(){return this.frames[this.frames.length-1].defenderHp===0}sampleAt(e){let t=this.frames.length-1;if(this.strikeDuration<=0)return this.frames[t];let n=0;for(let r=0;r<=t&&this.frames[r].time<=e+1e-9;r++)n=r;return this.frames[n]}};function tz(e){return Math.max(0,Math.min(1,e))}var nz=class{constructor(e){this.onChange=new p,this.stage_=`attacker`,this.charge=null,this.victim=null,this.highlight_=0,this.units=e.units,this.side=e.side,this.disabledOf=e.disabled??(e=>e.disabled??!1),this.canTarget=e.canTarget??(()=>!0)}get stage(){return this.stage_}get attacker(){return this.charge}get target(){return this.victim}get done(){return this.charge!==null&&this.victim!==null}get candidates(){return this.units.filter(e=>(this.side===void 0||e.side===this.side)&&!this.disabledOf(e))}get targets(){let e=this.charge;return e?this.units.filter(t=>t.id!==e.id&&!this.disabledOf(t)&&(e.side===void 0||t.side!==e.side)&&this.canTarget(e,t)):[]}get highlight(){return this.highlight_}get highlighted(){return this.active()[this.highlight_]??null}move(e){let t=this.active();t.length!==0&&(this.highlight_=((this.highlight_+e)%t.length+t.length)%t.length,this.onChange.dispatch())}select(){let e=this.highlighted;return e?(this.stage_===`attacker`?(this.charge=e,this.stage_=`target`,this.highlight_=0):this.victim=e,this.onChange.dispatch(),!0):!1}back(){if(this.stage_===`attacker`)return;let e=this.charge;this.charge=null,this.victim=null,this.stage_=`attacker`;let t=e?this.candidates.findIndex(t=>t.id===e.id):-1;this.highlight_=t>=0?t:0,this.onChange.dispatch()}reset(){this.charge=null,this.victim=null,this.stage_=`attacker`,this.highlight_=0,this.onChange.dispatch()}active(){return this.stage_===`attacker`?this.candidates:this.targets}},rz=class{constructor(e){this.onChange=new p,this.built=null,this.elapsed_=0,this.handleSelectorChange=()=>{if(this.selector.done&&this.attacker&&this.target){let e=this.damageFor(this.attacker,this.target);this.built=new ez({attacker:{hp:this.attacker.hp??0,name:this.attacker.id},defender:{hp:this.target.hp??0,name:this.target.id},damage:e.damage,strikes:e.strikes,...e.chanceToHit===void 0?{}:{chanceToHit:e.chanceToHit},...e.hits===void 0?{}:{hits:e.hits},strikeDuration:this.strikeDuration}),this.elapsed_=0}else this.built=null;this.onChange.dispatch()},this.damageFor=e.damageFor,this.strikeDuration=e.strikeDuration??0,this.selector=new nz({units:e.units,...e.side===void 0?{}:{side:e.side},...e.disabled===void 0?{}:{disabled:e.disabled},...e.canTarget===void 0?{}:{canTarget:e.canTarget}}),this.selector.onChange.add(this.handleSelectorChange)}get stage(){return this.selector.stage}get attacker(){return this.selector.attacker}get target(){return this.selector.target}get preview(){return this.built}get elapsed(){return this.elapsed_}get finished(){return this.built!==null&&this.elapsed_>=this.built.duration}get frame(){return this.built?this.built.sampleAt(this.elapsed_):null}move(e){this.selector.move(e)}select(){return this.selector.select()}back(){this.selector.back()}update(e){return this.built?(this.elapsed_=Math.min(this.built.duration,this.elapsed_+Math.max(0,e)),this.frame):null}finish(){this.built&&(this.elapsed_=this.built.duration)}reset(){this.selector.reset(),this.built=null,this.elapsed_=0}},iz=class{constructor(){this.onChange=new p,this.planned=[],this.undone=[]}get plans(){return this.planned}get isEmpty(){return this.planned.length===0}get canUndo(){return this.planned.length>0}get canRedo(){return this.undone.length>0}plannedFor(e){return this.planned.find(t=>t.unit===e)}plan(e){let t=this.planned.findIndex(t=>t.unit===e.unit);t>=0?this.planned[t]=e:this.planned.push(e),this.undone=[],this.onChange.dispatch()}undo(){let e=this.planned.pop();return e?(this.undone.push(e),this.onChange.dispatch(),e):null}redo(){let e=this.undone.pop();return e?(this.planned=this.planned.filter(t=>t.unit!==e.unit),this.planned.push(e),this.onChange.dispatch(),e):null}clear(){(this.planned.length!==0||this.undone.length!==0)&&(this.planned=[],this.undone=[],this.onChange.dispatch())}commit(){let e=this.planned;return this.planned=[],this.undone=[],e.length>0&&this.onChange.dispatch(),e}},az=class e{constructor(){this.counts=new Map}record(e,t,n=1){let r=this.counts.get(e)??new Map;r.set(t,(r.get(t)??0)+n),this.counts.set(e,r)}forType(e,t){return this.counts.get(e)?.get(t)??0}total(e){let t=this.counts.get(e);if(!t)return 0;let n=0;for(let e of t.values())n+=e;return n}breakdown(e){let t=this.counts.get(e);return t?[...t.entries()].map(([e,t])=>({unitType:e,count:t})):[]}toJSON(){return{counts:[...this.counts].map(([e,t])=>[e,[...t]])}}static fromJSON(t){let n=new e;for(let[e,r]of t.counts)n.counts.set(e,new Map(r));return n}},oz=l({AttackDialog:()=>rz,AttackPreview:()=>ez,BattleHooks:()=>QR,BattleStats:()=>az,Creature:()=>UR,Field:()=>$R,Party:()=>GR,StatStages:()=>JR,TypeMatrix:()=>WR,UnitSelector:()=>nz,Whiteboard:()=>iz,battleOrder:()=>KR,checkEvolution:()=>qR,chooseMove:()=>YR,chooseSwitch:()=>XR});function sz(e){let t=e.charCodeAt(0)-97,n=e.charCodeAt(1)-49;if(t<0||t>7||n<0||n>7||e.length!==2)throw Error(`not a square: "${e}"`);return n*8+t}function cz(e){return String.fromCharCode(97+(e&7))+String.fromCharCode(49+(e>>3))}function lz(e){let t=e.trim().split(/\s+/);if(t.length<4)throw Error(`not a FEN string: "${e}"`);let n=Array(64).fill(null),r=t[0].split(`/`);if(r.length!==8)throw Error(`a FEN placement needs 8 ranks: "${e}"`);if(r.forEach((t,r)=>{let i=7-r,a=0;for(let r of t)if(r>=`1`&&r<=`8`)a+=r.charCodeAt(0)-48;else{let o=r===r.toUpperCase()?`white`:`black`,s={p:`pawn`,n:`knight`,b:`bishop`,r:`rook`,q:`queen`,k:`king`}[r.toLowerCase()];if(!s||a>7)throw Error(`bad FEN rank "${t}" in "${e}"`);n[i*8+a]={side:o,kind:s},a++}if(a!==8)throw Error(`bad FEN rank "${t}" in "${e}"`)}),t[1]!==`w`&&t[1]!==`b`)throw Error(`a FEN side is "w" or "b": "${e}"`);let i={whiteKingside:!1,whiteQueenside:!1,blackKingside:!1,blackQueenside:!1};if(t[2]!==`-`)for(let n of t[2])if(n===`K`)i.whiteKingside=!0;else if(n===`Q`)i.whiteQueenside=!0;else if(n===`k`)i.blackKingside=!0;else if(n===`q`)i.blackQueenside=!0;else throw Error(`bad FEN castling "${t[2]}" in "${e}"`);let a=t[3]===`-`?null:sz(t[3]);if(a!==null){let n=t[1]===`w`?5:2;if(fz(a)!==n)throw Error(`bad FEN en passant square "${t[3]}" in "${e}"`)}let o={board:n,turn:t[1]===`w`?`white`:`black`,castling:i,enPassant:a};return xz(n,`white`),xz(n,`black`),o}function uz(e){return e===`white`?`black`:`white`}function dz(e){return e&7}function fz(e){return e>>3}function pz(e,t){return e>=0&&e<8&&t>=0&&t<8}function mz(){let e=[`rook`,`knight`,`bishop`,`queen`,`king`,`bishop`,`knight`,`rook`],t=Array(64).fill(null);for(let n=0;n<8;n++)t[n]={side:`white`,kind:e[n]},t[8+n]={side:`white`,kind:`pawn`},t[48+n]={side:`black`,kind:`pawn`},t[56+n]={side:`black`,kind:e[n]};return{board:t,turn:`white`,castling:{whiteKingside:!0,whiteQueenside:!0,blackKingside:!0,blackQueenside:!0},enPassant:null}}function hz(e){return{board:e.board.map(e=>e?{side:e.side,kind:e.kind}:null),turn:e.turn,castling:{...e.castling},enPassant:e.enPassant}}var gz=[[1,2],[2,1],[2,-1],[1,-2],[-1,-2],[-2,-1],[-2,1],[-1,2]],_z=[[1,0],[1,1],[0,1],[-1,1],[-1,0],[-1,-1],[0,-1],[1,-1]],vz=[[1,1],[-1,1],[-1,-1],[1,-1]],yz=[[1,0],[0,1],[-1,0],[0,-1]];function bz(e,t,n){let r=dz(t),i=fz(t),a=n===`white`?i-1:i+1;for(let t of[-1,1]){if(!pz(r+t,a))continue;let i=e[a*8+r+t];if(i&&i.side===n&&i.kind===`pawn`)return!0}for(let[t,a]of gz){if(!pz(r+t,i+a))continue;let o=e[(i+a)*8+r+t];if(o&&o.side===n&&o.kind===`knight`)return!0}for(let[t,a]of _z){if(!pz(r+t,i+a))continue;let o=e[(i+a)*8+r+t];if(o&&o.side===n&&o.kind===`king`)return!0}let o=[{steps:vz,kinds:[`bishop`,`queen`]},{steps:yz,kinds:[`rook`,`queen`]}];for(let{steps:t,kinds:a}of o)for(let[o,s]of t){let t=r+o,c=i+s;for(;pz(t,c);){let r=e[c*8+t];if(r){if(r.side===n&&a.includes(r.kind))return!0;break}t+=o,c+=s}}return!1}function xz(e,t){let n=e.findIndex(e=>e!==null&&e.side===t&&e.kind===`king`);if(n===-1)throw Error(`a position without a ${t} king cannot be judged`);return n}function Sz(e,t){return bz(e.board,xz(e.board,t),uz(t))}function Cz(e,t){let n=e.board[t];if(!n||n.side!==e.turn)return[];let r=[],i=dz(t),a=fz(t),o=o=>{for(let[s,c]of o){let o=i+s,l=a+c;for(;pz(o,l);){let i=l*8+o,a=e.board[i];if(!a)r.push({from:t,to:i});else{a.side!==n.side&&r.push({from:t,to:i});break}o+=s,l+=c}}};switch(n.kind){case`pawn`:{let o=n.side===`white`?1:-1,s=n.side===`white`?1:6,c=n.side===`white`?7:0;if(pz(i,a+o)&&!e.board[(a+o)*8+i]){let n=(a+o)*8+i;if(a+o===c)for(let e of[`knight`,`bishop`,`rook`,`queen`])r.push({from:t,to:n,promotion:e});else r.push({from:t,to:n}),a===s&&!e.board[(a+2*o)*8+i]&&r.push({from:t,to:(a+2*o)*8+i})}for(let s of[-1,1]){if(!pz(i+s,a+o))continue;let l=(a+o)*8+i+s,u=e.board[l];if(u&&u.side!==n.side){if(a+o===c)for(let e of[`knight`,`bishop`,`rook`,`queen`])r.push({from:t,to:l,promotion:e});else r.push({from:t,to:l})}else!u&&l===e.enPassant&&r.push({from:t,to:l,enPassantTake:a*8+i+s})}break}case`knight`:for(let[o,s]of gz){if(!pz(i+o,a+s))continue;let c=(a+s)*8+i+o,l=e.board[c];(!l||l.side!==n.side)&&r.push({from:t,to:c})}break;case`bishop`:o(vz);break;case`rook`:o(yz);break;case`queen`:o(vz),o(yz);break;case`king`:{for(let[o,s]of _z){if(!pz(i+o,a+s))continue;let c=(a+s)*8+i+o,l=e.board[c];l&&l.side===n.side||l&&l.kind===`king`||r.push({from:t,to:c})}let o=n.side===`white`?0:56,s=n.side===`white`?{king:e.castling.whiteKingside,queen:e.castling.whiteQueenside}:{king:e.castling.blackKingside,queen:e.castling.blackQueenside};t===o+4&&!Sz(e,n.side)&&(s.king&&!e.board[o+5]&&!e.board[o+6]&&!bz(e.board,o+5,uz(n.side))&&!bz(e.board,o+6,uz(n.side))&&r.push({from:t,to:o+6,castle:`kingside`}),s.queen&&!e.board[o+3]&&!e.board[o+2]&&!e.board[o+1]&&!bz(e.board,o+3,uz(n.side))&&!bz(e.board,o+2,uz(n.side))&&r.push({from:t,to:o+2,castle:`queenside`}));break}}return r}function wz(e,t){let n=e.board[t.from];if(!n)throw Error(`no piece on ${cz(t.from)} to move`);let r=(e,t)=>{let n=e===`white`?0:56;return t===n||t===n+7};n.kind===`king`&&(n.side===`white`?e.castling.whiteKingside=e.castling.whiteQueenside=!1:e.castling.blackKingside=e.castling.blackQueenside=!1),n.kind===`rook`&&r(n.side,t.from)&&(e.castling[Tz(n.side,t.from)]=!1);let i=e.board[t.to];if(i&&i.kind===`rook`&&r(i.side,t.to)&&(e.castling[Tz(i.side,t.to)]=!1),e.board[t.to]=t.promotion?{side:n.side,kind:t.promotion}:n,e.board[t.from]=null,t.enPassantTake!==void 0&&(e.board[t.enPassantTake]=null),t.castle){let r=n.side===`white`?0:56;t.castle===`kingside`?(e.board[r+5]=e.board[r+7],e.board[r+7]=null):(e.board[r+3]=e.board[r],e.board[r]=null)}e.enPassant=n.kind===`pawn`&&Math.abs(t.to-t.from)===16?(t.from+t.to)/2:null,e.turn=uz(n.side)}function Tz(e,t){let n=dz(t)===7;return e===`white`?n?`whiteKingside`:`whiteQueenside`:n?`blackKingside`:`blackQueenside`}function Ez(e){let t=[];for(let n=0;n<64;n++)if(!(!e.board[n]||e.board[n]?.side!==e.turn))for(let r of Cz(e,n)){let n=hz(e);wz(n,r),!Sz(n,e.turn)&&t.push({from:r.from,to:r.to,...r.promotion?{promotion:r.promotion}:{}})}return t}function Dz(e,t){let n=e.board[t.from];if(!n||n.side!==e.turn)throw Error(`no ${e.turn} piece on ${cz(t.from)} to move`);let r=Cz(e,t.from).find(e=>e.to===t.to&&(e.promotion??null)===(t.promotion??null));if(!r)throw Error(`${cz(t.from)}-${cz(t.to)} is not a legal move here`);let i=hz(e);if(wz(i,r),Sz(i,e.turn))throw Error(`${cz(t.from)}-${cz(t.to)} leaves the king in check`);wz(e,r)}function Oz(e){return Ez(e).length>0?`ongoing`:Sz(e,e.turn)?e.turn===`white`?`black-wins`:`white-wins`:`stalemate`}var kz=1e5;function Az(e,t,n){if(!Number.isInteger(n.depth)||n.depth<1)throw RangeError(`depth must be a positive integer`);let r=n.maxNodes??kz;if(!Number.isInteger(r)||r<1)throw RangeError(`maxNodes must be a positive integer`);let i=e.currentPlayer(t),a=0,o=0,s,c=(t,l,u,d)=>{if(n.signal?.aborted)return s=`cancelled`,0;if(++a>r)return s=`budget-exceeded`,0;let f=e.currentPlayer(t)===i;if(n.onNode?.(l,f),l===0||e.isTerminal(t))return e.evaluate(t,i);let p=e.moves(t);if(!p.length)return e.evaluate(t,i);let m=f?-1/0:1/0;for(let n of p){let r=c(e.apply(t,n),l-1,u,d);if(s)return r;if(f?(m=Math.max(m,r),u=Math.max(u,m)):(m=Math.min(m,r),d=Math.min(d,m)),d<=u){o++;break}}return m},l=e.moves(t),u=null,d=e.evaluate(t,i);if(!e.isTerminal(t)&&l.length){let r=e.currentPlayer(t)===i,a=r?-1/0:1/0,o=-1/0,f=1/0;for(let i of l){let l=c(e.apply(t,i),n.depth-1,o,f);if(s)break;(u===null||(r?l>a:l<a))&&(u=i,a=l),r?o=Math.max(o,a):f=Math.min(f,a)}u!==null&&(d=a)}return{move:s?null:u,score:d,depth:n.depth,nodes:a,cutoffs:o,status:s??`complete`,state:t}}var jz=1e5,Mz={pawn:100,knight:320,bishop:330,rook:500,queen:900,king:0};function Nz(e,t={}){return Pz(e,t).move}function Pz(e,t={}){let n=Az(Fz,e,{depth:Math.max(1,Math.floor(t.depth??3)),maxNodes:t.maxNodes===void 0?1e5:Math.max(1,Math.floor(t.maxNodes))});return{move:n.move,score:n.score,nodes:n.nodes}}var Fz={currentPlayer:e=>e.turn===`white`?1:-1,moves:e=>Rz(e,Ez(e)),apply:(e,t)=>{let n=hz(e);return Dz(n,t),n},isTerminal:e=>Oz(e)!==`ongoing`,evaluate:(e,t)=>Oz(e)===`ongoing`?Iz(e,t):Lz(e,t)};function Iz(e,t){let n=0;for(let t of e.board)t&&(n+=(t.side===`white`?1:-1)*Mz[t.kind]);return t===1?n:-n}function Lz(e,t){let n=Oz(e);return n===`stalemate`||!Sz(e,e.turn)?0:(n===`white-wins`?1:-1)===t?jz:-1e5}function Rz(e,t){return t.slice().sort((t,n)=>zz(e,n)-zz(e,t))}function zz(e,t){let n=e.board[t.to];return(t.promotion?Mz[t.promotion]:0)*10+(n?Mz[n.kind]:0)}var Bz=class{constructor(e,t,n){if(this.width=e,this.height=t,e<1||t<1)throw Error(`a board needs positive dimensions`);if(n&&n.length!==e*t)throw Error(`board cell count does not match dimensions`);this.cells=n?[...n]:Array(e*t).fill(null)}index(e,t){if(!this.inside(e,t))throw Error(`cell (${e},${t}) is outside the board`);return t*this.width+e}inside(e,t){return e>=0&&t>=0&&e<this.width&&t<this.height}get(e,t){return this.cells[this.index(e,t)]}set(e,t,n){this.cells[this.index(e,t)]=n}move(e,t){let n=this.get(e.x,e.y);if(n===null)throw Error(`cannot move an empty cell`);return this.set(e.x,e.y,null),this.set(t.x,t.y,n),n}};function Vz(){let e=Array(64).fill(null);for(let t=0;t<3;t++)for(let n=0;n<8;n++)(n+t)%2&&(e[t*8+n]={side:`black`,king:!1});for(let t=5;t<8;t++)for(let n=0;n<8;n++)(n+t)%2&&(e[t*8+n]={side:`red`,king:!1});return{board:e,turn:`red`,forcedFrom:null}}function Hz(e){let t=e.forcedFrom===null?e.board.map((t,n)=>t?.side===e.turn?n:-1).filter(e=>e>=0):[e.forcedFrom],n=t.flatMap(t=>Wz(e,t,!0));return n.length>0?n:e.forcedFrom===null?t.flatMap(t=>Wz(e,t,!1)):[]}function Uz(e,t){if(!Hz(e).some(e=>e.from===t.from&&e.to===t.to&&e.captures.length===t.captures.length))throw Error(`illegal checkers move`);let n=e.board[t.from];if(!n)throw Error(`no checkers piece on the source cell`);e.board[t.from]=null;for(let n of t.captures)e.board[n]=null;let r=!n.king&&(n.side===`red`&&Math.floor(t.to/8)===0||n.side===`black`&&Math.floor(t.to/8)===7);e.board[t.to]={...n,king:n.king||r};let i={board:e.board,turn:e.turn,forcedFrom:t.captures.length>0?t.to:null};t.captures.length===0||Wz(i,t.to,!0).length===0?(e.turn=e.turn===`red`?`black`:`red`,e.forcedFrom=null):e.forcedFrom=t.to}function Wz(e,t,n){let r=e.board[t];if(!r)return[];let i=t%8,a=Math.floor(t/8),o=r.king?[-1,1]:r.side===`red`?[-1]:[1],s=[];for(let c of o)for(let o of[-1,1]){let l=i+o,u=a+c,d=i+o*2,f=a+c*2;if(n){if(d<0||f<0||d>=8||f>=8)continue;let n=u*8+l,i=f*8+d;e.board[n]?.side!==r.side&&e.board[n]&&!e.board[i]&&s.push({from:t,to:i,captures:[n]})}else l>=0&&u>=0&&l<8&&u<8&&!e.board[u*8+l]&&s.push({from:t,to:u*8+l,captures:[]})}return s}function Gz(e=9){if(e<2||e>25)throw Error(`Go size must be between 2 and 25`);return{size:e,board:Array(e*e).fill(null),turn:`black`,ko:null,passes:0}}function Kz(e,t,n){let r=Xz(e,t,n);if(e.board[r]||e.ko===r)throw Error(`Go cell is occupied or forbidden by ko`);let i=[...e.board];i[r]=e.turn;let a=e.turn===`black`?`white`:`black`,o=0,s=null;for(let t of Zz(e,r)){if(i[t]!==a||$z(i,e.size,t)!==0)continue;let n=Qz(i,e.size,t);n.length===1&&(s=n[0]);for(let e of n)i[e]=null;o+=n.length}if($z(i,e.size,r)===0)throw Error(`suicide is not a legal Go move`);e.ko=o===1&&$z(i,e.size,r)===1?s:null,e.board=i,e.turn=a,e.passes=0}function qz(e){e.turn=e.turn===`black`?`white`:`black`,e.ko=null,e.passes++}function Jz(e){return e.passes>=2?`finished`:`ongoing`}function Yz(e){let t={black:0,white:0},n=new Set;for(let r=0;r<e.board.length;r++){let i=e.board[r];if(i)t[i]++;else if(!n.has(r)){let i=Qz(e.board,e.size,r),a=new Set;for(let t of i)for(let n of Zz(e,t))e.board[n]&&a.add(e.board[n]);for(let e of i)n.add(e);a.size===1&&(t[[...a][0]]+=i.length)}}return t}function Xz(e,t,n){if(t<0||n<0||t>=e.size||n>=e.size)throw Error(`Go cell is outside the board`);return n*e.size+t}function Zz(e,t){let n=t%e.size,r=Math.floor(t/e.size);return[[n-1,r],[n+1,r],[n,r-1],[n,r+1]].filter(([t,n])=>t>=0&&n>=0&&t<e.size&&n<e.size).map(([t,n])=>n*e.size+t)}function Qz(e,t,n){let r=e[n];if(!r)return[];let i=[],a=[n],o=new Set;for(;a.length;){let n=a.pop();if(o.has(n)||e[n]!==r)continue;o.add(n),i.push(n);let s=n%t,c=Math.floor(n/t);for(let[e,n]of[[s-1,c],[s+1,c],[s,c-1],[s,c+1]])e>=0&&n>=0&&e<t&&n<t&&a.push(n*t+e)}return i}function $z(e,t,n){let r=Qz(e,t,n),i=new Set;for(let n of r){let r=n%t,a=Math.floor(n/t);for(let[n,o]of[[r-1,a],[r+1,a],[r,a-1],[r,a+1]])n>=0&&o>=0&&n<t&&o<t&&e[o*t+n]===null&&i.add(o*t+n)}return i.size}function eB(){let e=Array(24).fill(0);return e[0]=2,e[11]=5,e[16]=3,e[18]=5,e[23]=-2,e[12]=-5,e[7]=-3,e[5]=-5,{points:e,bar:{white:0,black:0},off:{white:0,black:0},turn:`white`}}function tB(){let e=hB(2,6);return e[0]===e[1]?[...e,...e]:e}function nB(e,t){let n=e.turn===`white`?1:-1,r=[];for(let i of t){if(e.bar[e.turn]>0){let t=e.turn===`white`?i-1:24-i;iB(e,t,n)&&r.push({from:`bar`,to:t,die:i});continue}for(let t=0;t<24;t++)if(e.points[t]*n>0){let a=t+i*n;a<0||a>=24?r.push({from:t,to:`off`,die:i}):iB(e,a,n)&&r.push({from:t,to:a,die:i})}}return r}function rB(e,t){if(!nB(e,[t.die]).some(e=>e.from===t.from&&e.to===t.to))throw Error(`illegal backgammon move`);let n=e.turn===`white`?1:-1;if(t.from===`bar`?e.bar[e.turn]--:e.points[t.from]-=n,t.to===`off`)e.off[e.turn]++;else{if(e.points[t.to]*n<0){let n=e.turn===`white`?`black`:`white`;e.points[t.to]=0,e.bar[n]++}e.points[t.to]+=n}}function iB(e,t,n){return e.points[t]*n>=-1}function aB(e=0){let t=[`clubs`,`diamonds`,`hearts`,`spades`],n=[];for(let e of t)for(let t=1;t<=13;t++)n.push({suit:e,rank:t});return n.concat(Array(e).fill(null).map(()=>({suit:`spades`,rank:1})))}function oB(e){return le(e)}function sB(e,t,n){if(t<0||n<0||e.length<t*n)throw Error(`not enough cards to deal`);return Array.from({length:t},()=>e.splice(0,n))}function cB(e,t){if(e.length===0)throw Error(`a trick needs at least one play`);let n=e[0].card.suit,r=e=>e.rank===1?14:e.rank;return(t&&e.some(e=>e.card.suit===t)?e.filter(e=>e.card.suit===t):e.filter(e=>e.card.suit===n)).reduce((e,t)=>r(t.card)>r(e.card)?t:e).owner}function lB(e){let t=aB();return e===void 0?oB(t):ne(e,()=>oB(t)),{stock:t,waste:[],tableau:Array.from({length:7},(e,n)=>({down:t.splice(0,6-n),up:t.splice(0,1)})),foundations:[[],[],[],[]]}}function uB(e){e.stock.length===0&&(e.stock=e.waste.reverse(),e.waste=[]);let t=e.stock.pop()??null;return t&&e.waste.push(t),t}function dB(e,t,n,r=1){let i=e.tableau[t],a=e.tableau[n],o=i?.up.slice(-r);if(!i||!a||!o?.length||(a.up.length===0?o[0].rank!==13:!mB(o[0],a.up.at(-1))))throw Error(`illegal solitaire tableau move`);i.up.splice(-r,r),a.up.push(...o),i.down.length&&i.up.length===0&&i.up.push(i.down.pop())}function fB(e,t){let n=t===`waste`?e.waste.at(-1):e.tableau[t].up.at(-1);if(!n)throw Error(`no solitaire card to move`);let r=e.foundations.find(e=>e[0]?.suit===n.suit||e.length===0);if(!r||n.rank!==r.length+1)throw Error(`card cannot move to its foundation`);if(t===`waste`)e.waste.pop();else{let n=e.tableau[t];n.up.pop(),n.down.length&&n.up.length===0&&n.up.push(n.down.pop())}r.push(n)}function pB(e){return e.foundations.every(e=>e.length===13)}function mB(e,t){let n=e.suit===`diamonds`||e.suit===`hearts`,r=t.suit===`diamonds`||t.suit===`hearts`;return e.rank===t.rank-1&&n!==r}function hB(e,t){if(!Number.isInteger(e)||e<0||!Number.isInteger(t)||t<1)throw Error(`dice need a non-negative count and positive sides`);return Array.from({length:e},()=>ie(1,t))}function gB(e){let t=/^(\d+)d(\d+)([+-]\d+)?$/i.exec(e.trim());if(!t)throw Error(`bad dice expression: "${e}"`);return hB(Number(t[1]),Number(t[2])).reduce((e,t)=>e+t,Number(t[3]??0))}var _B=class{constructor(e,t){this.kept=new Set,this.count=e,this.sides=t,this.values=hB(e,t)}reRoll(){for(let e=0;e<this.values.length;e++)this.kept.has(e)||(this.values[e]=ie(1,this.sides))}keep(e){if(e<0||e>=this.count)throw Error(`die index is outside the cup`);this.kept.add(e)}clearKept(){this.kept.clear()}};function vB(e,t){if(e.length!==5||e.some(e=>e<1||e>6))throw Error(`a score sheet needs five d6 values`);let n=new Map;for(let t of e)n.set(t,(n.get(t)??0)+1);let r=e.reduce((e,t)=>e+t,0);if(t===`chance`)return r;if(t===`yahtzee`)return n.size===1?50:0;if(t===`fullHouse`)return[...n.values()].sort().join(`,`)===`2,3`?25:0;if(t===`threeKind`)return[...n.values()].some(e=>e>=3)?r:0;if(t===`fourKind`)return[...n.values()].some(e=>e>=4)?r:0;if(t===`smallStraight`||t===`largeStraight`){let e=[`1234`,`2345`,`3456`],r=[`12345`,`23456`],i=[...n.keys()].sort().join(``);return(t===`smallStraight`?e:r).some(e=>i.includes(e))?t===`smallStraight`?30:40:0}let i=[`ones`,`twos`,`threes`,`fours`,`fives`,`sixes`].indexOf(t)+1;return i>0?(n.get(i)??0)*i:0}function yB(e,t,n=`hex`){if(e<1||t<1)throw Error(`a tactical map needs positive dimensions`);return{width:e,height:t,shape:n,cells:Array.from({length:e*t},()=>({passable:!0,cover:0})),units:[],turn:``,round:1}}function bB(e,t,n){return AB(e,t,n)&&!kB(e,t,n)}function xB(e,t){if(!bB(e,t.x,t.y))throw Error(`tactical unit cannot be placed there`);e.units.push({...t}),e.turn||=t.owner}function SB(e,t){let n=OB(e,t);if(n.owner!==e.turn||n.actions<=0)return[];let r=PB(e,n,NB(e,n)),i=[];for(let a=0;a<e.height;a++)for(let o=0;o<e.width;o++){if(o===n.x&&a===n.y||!e.cells[a*e.width+o].passable||kB(e,o,a))continue;let s=FB(e,n,o,a,n.actions,r);s!==null&&i.push({unit:t,x:o,y:a,cost:s})}return i}function CB(e,t){let n=SB(e,t.unit).find(e=>e.x===t.x&&e.y===t.y);if(!n)throw Error(`illegal tactical move`);let r=OB(e,t.unit);r.x=t.x,r.y=t.y,r.actions-=n.cost}function wB(e,t){let n=OB(e,t);if(n.owner!==e.turn||n.actions<=0)throw Error(`only an active unit can enter overwatch`);n.actions=0,n.overwatch=!0}function TB(e,t,n){let r=OB(e,t),i=[];for(let t of[...e.units]){if(!t.overwatch||t.owner===r.owner||MB(e,t,r)>3)continue;let a=e.cells[r.y*e.width+r.x].cover??0,o=Math.max(0,n-a);if(r.hp=Math.max(0,r.hp-o),t.overwatch=!1,i.push({attacker:t.id,defender:r.id,damage:o,cover:a,killed:r.hp===0}),r.hp===0){e.units=e.units.filter(e=>e!==r);break}}return i}function EB(e,t,n,r){let i=OB(e,t),a=OB(e,n);if(i.owner!==e.turn||i.owner===a.owner)throw Error(`invalid tactical attack`);if(MB(e,i,a)>3)throw Error(`tactical target is out of range`);let o=e.cells[a.y*e.width+a.x].cover??0,s=Math.max(0,r-o);a.hp=Math.max(0,a.hp-s);let c=a.hp===0;return c&&(e.units=e.units.filter(e=>e!==a)),{attacker:t,defender:n,damage:s,cover:o,killed:c}}function DB(e){let t=[...new Set(e.units.map(e=>e.owner))];if(t.length===0)return;let n=t.indexOf(e.turn)+1;n>=t.length&&e.round++,e.turn=t[n%t.length];for(let t of e.units)t.owner===e.turn&&(t.actions=2,t.overwatch=!1)}function OB(e,t){let n=e.units.find(e=>e.id===t);if(!n)throw Error(`unknown tactical unit "${t}"`);return n}function kB(e,t,n){return e.units.some(e=>e.x===t&&e.y===n)}function AB(e,t,n){return t>=0&&n>=0&&t<e.width&&n<e.height}function jB(e,t,n){return e.shape===`hex`?cn(t,n):[{x:t-1,y:n},{x:t+1,y:n},{x:t,y:n-1},{x:t,y:n+1}]}function MB(e,t,n){return e.shape===`hex`?ln(t,n):Math.abs(t.x-n.x)+Math.abs(t.y-n.y)}function NB(e,t){return new Set(e.units.filter(n=>n.owner!==t.owner&&jB(e,t.x,t.y).some(e=>e.x===n.x&&e.y===n.y)).map(e=>e.id))}function PB(e,t,n){let r=new Set;for(let i of e.units)if(!(i.owner===t.owner||n.has(i.id)))for(let t of jB(e,i.x,i.y))r.add(`${t.x},${t.y}`);return r}function FB(e,t,n,r,i,a){let o=[{x:t.x,y:t.y,distance:0}],s=0,c=new Set([`${t.x},${t.y}`]);for(;s<o.length;){let t=o[s++];if(t.x===n&&t.y===r)return t.distance;if(!(t.distance>=i||t.distance>0&&a.has(`${t.x},${t.y}`)))for(let i of jB(e,t.x,t.y)){let a=`${i.x},${i.y}`;!AB(e,i.x,i.y)||c.has(a)||!e.cells[i.y*e.width+i.x].passable||kB(e,i.x,i.y)&&(i.x!==n||i.y!==r)||(c.add(a),o.push({x:i.x,y:i.y,distance:t.distance+1}))}}return null}var IB=class{constructor(e,t){if(this.visible=new Map,this.explored=new Map,this.shared=new Map,e<1||t<1)throw Error(`fog needs positive dimensions`);this.width=e,this.height=t}share(e){let t=[...new Set(e)].filter(e=>!!e);if(t.length===0)return;let n=new Set(t);for(let e of t)for(let t of this.shared.get(e)??[])n.add(t);for(let e of n)this.shared.set(e,n)}sync(e,t,n){if(!e)throw Error(`fog needs a faction id`);let r=new Set;for(let e of t)for(let t of n(e))this.inside(t.x,t.y)&&r.add(this.index(t.x,t.y));this.visible.set(e,r);let i=this.explored.get(e)??new Set;for(let e of r)i.add(e);this.explored.set(e,i)}reveal(e,t){if(!e)throw Error(`fog needs a faction id`);let n=this.explored.get(e)??new Set;for(let e of t)this.inside(e.x,e.y)&&n.add(this.index(e.x,e.y));this.explored.set(e,n)}isVisible(e,t,n){return this.seenBy(this.visible,e,this.index(t,n))}sees(e){return(t,n)=>this.isVisible(e,t,n)}isExplored(e,t,n){return this.seenBy(this.explored,e,this.index(t,n))}visibleCells(e){return this.cellsSeenBy(this.visible,e)}exploredCells(e){return this.cellsSeenBy(this.explored,e)}seenBy(e,t,n){let r=this.shared.get(t);if(!r)return e.get(t)?.has(n)??!1;for(let t of r)if(e.get(t)?.has(n))return!0;return!1}cellsSeenBy(e,t){let n=this.shared.get(t);if(!n)return[...e.get(t)??[]];let r=new Set;for(let t of n)for(let n of e.get(t)??[])r.add(n);return[...r].sort((e,t)=>e-t)}inside(e,t){return e>=0&&t>=0&&e<this.width&&t<this.height}index(e,t){return this.inside(e,t)?t*this.width+e:-1}};function LB(e){return{currency:e,pool:[]}}function RB(e,t,n,r){return e.currency<r||!bB(t,n.x,n.y)?!1:(xB(t,n),e.currency-=r,!0)}function zB(e,t,n,r,i){let a=e.pool.findIndex(e=>e.id===n);return a===-1||!bB(t,r,i)?!1:(xB(t,{...e.pool[a],x:r,y:i}),e.pool.splice(a,1),!0)}function BB(e,t,n){let r=t.units.findIndex(e=>e.id===n);if(r===-1)return!1;let{x:i,y:a,...o}=t.units[r];return e.pool.push(o),t.units.splice(r,1),!0}function VB(e,t,n){return e.units.filter(e=>e.owner===t).length*(n.incomePerUnit-n.upkeepPerUnit)}function HB(e,t,n,r){return e.currency+=VB(t,n,r),e.currency}function UB(e,t,n,r){if(e<1||t<1)throw Error(`a skirmish map needs positive dimensions`);let i=r??Object.keys(n)[0];if(!i||!n[i])throw Error(`a skirmish map needs at least one terrain kind`);return{width:e,height:t,terrainTable:n,cells:Array.from({length:e*t},()=>({terrain:i})),units:[],turn:``,round:1}}function WB(e,t,n,r,i=!1){if(!eV(e,t,n))throw Error(`cell is outside the skirmish map`);if(!e.terrainTable[r])throw Error(`unknown skirmish terrain "${r}"`);e.cells[n*e.width+t]=i?{terrain:r,village:!0}:{terrain:r}}function GB(e,t,n){return eV(e,t,n)&&rV(e,t,n)<1/0&&!tV(e,t,n)}function KB(e,t){if(!GB(e,t.x,t.y))throw Error(`skirmish unit cannot be placed there`);e.units.push({...t,remainingMoves:t.moves}),e.turn||=t.owner}function qB(e,t){let n=$B(e,t),r=n.remainingMoves??n.moves;if(n.owner!==e.turn||r<=0)return[];let i=[];for(let a=0;a<e.height;a++)for(let o=0;o<e.width;o++){if(o===n.x&&a===n.y||rV(e,o,a)===1/0||tV(e,o,a))continue;let s=iV(e,n,o,a,r);s!==null&&i.push({unit:t,x:o,y:a,cost:s})}return i}function JB(e,t){let n=qB(e,t.unit).find(e=>e.x===t.x&&e.y===t.y);if(!n)throw Error(`illegal skirmish move`);let r=$B(e,t.unit);r.x=t.x,r.y=t.y,r.remainingMoves=(r.remainingMoves??r.moves)-n.cost;let i=e.cells[t.y*e.width+t.x];i.village&&(i.owner=r.owner)}function YB(e,t,n){let r=$B(e,t),i=$B(e,n);if(r.owner!==e.turn||r.owner===i.owner)throw Error(`invalid skirmish attack`);if(ln(r,i)!==1)throw Error(`skirmish combat is adjacency-only`);let a=[XB(e,r,i)];return i.hp>0&&a.push(XB(e,i,r)),e.units=e.units.filter(e=>e.hp>0),{strikes:a}}function XB(e,t,n){let r=nV(e,n.x,n.y).defense,i=oe(Math.max(0,Math.min(1,t.hitChance*(1-r)))),a=i?Math.min(t.attack,n.hp):0;return n.hp-=a,{attacker:t.id,defender:n.id,hit:i,damage:a,killed:n.hp<=0}}function ZB(e,t,n,r){return n+e.cells.filter(e=>e.village&&e.owner===t).length*r}function QB(e,t=0){let n=[...new Set(e.units.map(e=>e.owner))];if(n.length===0)return;let r=n.indexOf(e.turn)+1;r>=n.length&&e.round++,e.turn=n[r%n.length];for(let n of e.units){if(n.owner!==e.turn)continue;n.remainingMoves=n.moves;let r=e.cells[n.y*e.width+n.x];r.village&&r.owner===n.owner&&t>0&&(n.hp=Math.min(n.maxHp,n.hp+t))}}function $B(e,t){let n=e.units.find(e=>e.id===t);if(!n)throw Error(`unknown skirmish unit "${t}"`);return n}function eV(e,t,n){return t>=0&&n>=0&&t<e.width&&n<e.height}function tV(e,t,n){return e.units.some(e=>e.x===t&&e.y===n)}function nV(e,t,n){return e.terrainTable[e.cells[n*e.width+t].terrain]}function rV(e,t,n){return nV(e,t,n).moveCost}function iV(e,t,n,r,i){let a=new Map([[`${t.x},${t.y}`,0]]),o=[{x:t.x,y:t.y,cost:0}];for(;o.length>0;){o.sort((e,t)=>e.cost-t.cost);let t=o.shift(),s=`${t.x},${t.y}`;if(!(t.cost>(a.get(s)??1/0))){if(t.x===n&&t.y===r)return t.cost;for(let s of cn(t.x,t.y)){if(!eV(e,s.x,s.y))continue;let c=rV(e,s.x,s.y);if(c===1/0||tV(e,s.x,s.y)&&(s.x!==n||s.y!==r))continue;let l=t.cost+c;if(l>i)continue;let u=`${s.x},${s.y}`;l<(a.get(u)??1/0)&&(a.set(u,l),o.push({x:s.x,y:s.y,cost:l}))}}}return null}var aV=l({BoardGrid:()=>Bz,DiceCup:()=>_B,FactionFog:()=>IB,addSkirmishUnit:()=>KB,addTacticalUnit:()=>xB,applyBackgammonMove:()=>rB,applyCheckersMove:()=>Uz,applyMove:()=>Dz,applyUpkeep:()=>HB,armyIncome:()=>VB,backgammonMoves:()=>nB,bankUnit:()=>BB,canPlaceSkirmishUnit:()=>GB,canPlaceTacticalUnit:()=>bB,checkersMoves:()=>Hz,chessGame:()=>Fz,chooseMove:()=>Nz,cloneChess:()=>hz,createDeck:()=>aB,deal:()=>sB,dealSolitaire:()=>lB,drawSolitaire:()=>uB,endSkirmishTurn:()=>QB,endTacticalTurn:()=>DB,gameResult:()=>Oz,goResult:()=>Jz,goScore:()=>Yz,inCheck:()=>Sz,legalMoves:()=>Ez,moveSkirmishUnit:()=>JB,moveSolitaireTableau:()=>dB,moveSolitaireToFoundation:()=>fB,moveTacticalUnit:()=>CB,parseFen:()=>lz,passGo:()=>qz,playGo:()=>Kz,recall:()=>zB,recruit:()=>RB,rollBackgammonDice:()=>tB,rollDice:()=>hB,rollExpression:()=>gB,scoreDice:()=>vB,search:()=>Pz,setSkirmishTerrain:()=>WB,setTacticalOverwatch:()=>wB,shuffleDeck:()=>oB,skirmishAttack:()=>YB,skirmishIncome:()=>ZB,skirmishMoves:()=>qB,solitaireWon:()=>pB,sq:()=>sz,squareName:()=>cz,startingArmy:()=>LB,startingBackgammon:()=>eB,startingCheckers:()=>Vz,startingChess:()=>mz,startingGo:()=>Gz,startingSkirmish:()=>UB,startingTactics:()=>yB,tacticalAttack:()=>EB,tacticalMoves:()=>SB,trickWinner:()=>cB,triggerTacticalOverwatch:()=>TB});function oV(e){return new Audio(xA(e))}var sV=new p,cV=class{constructor(e,t={}){this.next=0;let n=Math.max(1,t.poolSize??4),r=t.create??oV;this.volume=t.volume??1,this.caption=t.caption,this.pool=Array.from({length:n},()=>r(e))}play(e=1){let t=this.pool[this.next];this.next=(this.next+1)%this.pool.length,t.volume=this.volume*e,t.currentTime=0,Promise.resolve(t.play()).catch(()=>{}),this.caption&&sV.dispatch({text:this.caption})}stopAll(){for(let e of this.pool)e.pause(),e.currentTime=0}},lV=class{constructor(e={}){this.current=null,this.fades=[],this.trackQueue=null,this.playlistFade=1,this.volume=e.volume??1,this.create=e.create??oV}play(e,t=1){this.trackQueue=null,this.start(e,t,!0)}playTracks(e,t=1){if(e.length===0){this.stop(t);return}this.trackQueue=[...e],this.playlistFade=t,this.startNextTrack()}startNextTrack(){if(!this.trackQueue?.length)return;let e=this.trackQueue.shift();this.trackQueue.push(e),this.start(e,this.playlistFade,!1)}start(e,t,n){let r=this.create(e);r.loop=n,!n&&r.onended!==void 0&&(r.onended=()=>{this.current===r&&this.startNextTrack()});let i=this.current;if(this.current=r,t<=0){r.volume=this.volume,Promise.resolve(r.play()).catch(()=>{}),i?.pause();return}r.volume=0,Promise.resolve(r.play()).catch(()=>{}),this.fades.push({audio:r,elapsed:0,duration:t,from:0,to:this.volume,stopAtEnd:!1}),i&&this.fades.push({audio:i,elapsed:0,duration:t,from:i.volume,to:0,stopAtEnd:!0})}stop(e=1){this.trackQueue=null;let t=this.current;if(t){if(this.current=null,e<=0){t.pause();return}this.fades.push({audio:t,elapsed:0,duration:e,from:t.volume,to:0,stopAtEnd:!0})}}update(e){for(let t of[...this.fades]){t.elapsed+=e;let n=Math.min(1,t.elapsed/t.duration);t.audio.volume=t.from+(t.to-t.from)*n,n>=1&&(this.fades.splice(this.fades.indexOf(t),1),t.stopAtEnd&&(t.audio.pause(),t.audio.currentTime=0))}}},uV=class{constructor(e){this.states=new Map,this.cues=new Map,this.currentTrack=null,this.music=e}define(e,t){this.states.set(e,t)}enter(e){let t=this.states.get(e);if(!t)throw Error(`Orchestrator: no state defined for "${e}"`);t.track!==this.currentTrack&&(this.music.play(t.track,t.fadeDuration),this.currentTrack=t.track)}on(e,t){this.cues.set(e,t)}trigger(e){this.cues.get(e)?.play()}};function dV(e={}){let t=e.waveform??`square`,n=e.frequency??440,r=e.duration??.15,i=e.volume??.3,a=e.decay??8,o=e.sampleRate??22050,s=e.seed??1;if(!(r>0))throw Error(`tone duration must be positive`);if(t!==`noise`&&!(n>0))throw Error(`tone frequency must be positive`);if(!(o>0))throw Error(`tone sample rate must be positive`);let c=Math.max(1,Math.round(r*o)),l=new Float32Array(c);for(let e=0;e<c;e++){let r=e/o,u=a>0?Math.exp(-a*e/c):1,d=2*Math.PI*n*r;l[e]=i*u*pV(t,d,s,e)}return hV(l,o)}function fV(e={},t=e=>new Audio(e)){let n=t(dV(e));return Promise.resolve(n.play()).catch(()=>{}),n}function pV(e,t,n,r){switch(e){case`sine`:return Math.sin(t);case`square`:return Math.sin(t)>=0?1:-1;case`triangle`:{let e=t/(2*Math.PI),n=e-Math.floor(e);return 4*Math.abs(n-.5)-1}case`noise`:return mV(n,r)}}function mV(e,t){let n=Math.imul(e^t,2654435761)>>>0;return n=Math.imul(n^n>>>15,2246822519)>>>0,n=Math.imul(n^n>>>13,3266489917)>>>0,n^=n>>>16,(n>>>0)/4294967295*2-1}function hV(e,t){let n=e.length*2,r=new ArrayBuffer(44+n),i=new DataView(r);gV(i,0,`RIFF`),i.setUint32(4,36+n,!0),gV(i,8,`WAVE`),gV(i,12,`fmt `),i.setUint32(16,16,!0),i.setUint16(20,1,!0),i.setUint16(22,1,!0),i.setUint32(24,t,!0),i.setUint32(28,t*2,!0),i.setUint16(32,2,!0),i.setUint16(34,16,!0),gV(i,36,`data`),i.setUint32(40,n,!0);let a=44;for(let t of e){let e=Math.max(-1,Math.min(1,t));i.setInt16(a,Math.round(e*(e<0?32768:32767)),!0),a+=2}let o=``,s=new Uint8Array(r);for(let e of s)o+=String.fromCharCode(e);return`data:audio/wav;base64,${btoa(o)}`}function gV(e,t,n){for(let r=0;r<n.length;r++)e.setUint8(t+r,n.charCodeAt(r))}var _V=5e5;function vV(e){let t=e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength),n=new DataView(t.buffer,t.byteOffset,t.byteLength),r=0,i=e=>{let n=``;for(let i=0;i<e;i++)n+=String.fromCharCode(t[r+i]);return r+=e,n},a=()=>{let e=n.getUint32(r,!1);return r+=4,e},o=()=>{let e=n.getUint16(r,!1);return r+=2,e},s=()=>{let e=0;for(;;){let n=t[r++];if(e=e<<7|n&127,!(n&128))return e}};if(i(4)!==`MThd`||a()!==6)throw Error(`invalid MIDI header chunk`);let c=o(),l=o(),u=o();if(c!==0&&c!==1)throw Error(`unsupported MIDI format ${c}`);if(u&32768)throw Error(`SMPTE-based MIDI timing is not supported`);let d=u,f=[];for(let e=0;e<l;e++){let e=i(4),n=a();if(e!==`MTrk`){r+=n;continue}let o=r+n,c=0,l=0;for(;r<o;){c+=s();let e=t[r];if(e<128?e=l:(r++,e<240&&(l=e)),e===255){let e=t[r++],n=s();if(e===81&&n===3){let e=t[r]<<16|t[r+1]<<8|t[r+2];f.push({tick:c,type:`tempo`,microsecondsPerQuarter:e})}r+=n}else if(e===240||e===247)r+=s();else{let n=e&240,i=e&15;if(n===128||n===144){let e=t[r++],a=t[r++],o=n===144&&a>0;f.push({tick:c,type:o?`noteOn`:`noteOff`,note:e,velocity:a,channel:i})}else if(n===160||n===176||n===224)r+=2;else if(n===192||n===208)r+=1;else throw Error(`unsupported MIDI status byte 0x${e.toString(16)}`)}}}return f.sort((e,t)=>e.tick-t.tick),{ticksPerQuarter:d,events:f}}function yV(e){let t=[],n=new Map,r=_V,i=0,a=0;for(let o of e.events){if(a+=(o.tick-i)*r/e.ticksPerQuarter/1e6,i=o.tick,o.type===`tempo`){r=o.microsecondsPerQuarter;continue}let s=`${o.channel}:${o.note}`;if(o.type===`noteOn`)n.set(s,{time:a,velocity:o.velocity});else{let e=n.get(s);e&&(t.push({time:e.time,duration:Math.max(.01,a-e.time),note:o.note,velocity:e.velocity,channel:o.channel}),n.delete(s))}}for(let[e,r]of n){let[n,i]=e.split(`:`).map(Number);t.push({time:r.time,duration:.3,note:i,velocity:r.velocity,channel:n})}return t.sort((e,t)=>e.time-t.time)}function bV(e){return 440*2**((e-69)/12)}var xV=class{constructor(e,t={}){this.elapsed=0,this.index=0,this.playing=!1,this.notes=yV(e),this.playFn=t.play??fV,this.waveform=t.waveform??`square`,this.volume=t.volume??.2}play(){this.playing=this.index<this.notes.length}pause(){this.playing=!1}stop(){this.playing=!1,this.elapsed=0,this.index=0}update(e){if(this.playing){for(this.elapsed+=e;this.index<this.notes.length&&this.notes[this.index].time<=this.elapsed;){let e=this.notes[this.index];this.playFn({waveform:this.waveform,frequency:bV(e.note),duration:e.duration,volume:this.volume*(e.velocity/127)}),this.index++}this.index>=this.notes.length&&(this.playing=!1)}}get isPlaying(){return this.playing}get duration(){let e=this.notes.at(-1);return e?e.time+e.duration:0}};function SV(e,t={}){let n=t.refDistance??1,r=t.maxDistance??1/0,i=t.rolloff??1;if(!(e>n))return 1;if(!(e<r))return 0;let a=(n/e)**+i;return Math.max(0,Math.min(1,a))}function CV(e,t){let n=t.x-e.x,r=t.y-e.y,i=Math.hypot(n,r);if(i===0)return 0;let a=Math.sin(e.facing),o=Math.cos(e.facing),s=(n*a+r*o)/i;return Math.max(-1,Math.min(1,s))}var wV=class{constructor(e={}){this.x=e.x??0,this.y=e.y??0,this.facing=e.facing??0}moveTo(e,t){this.x=e,this.y=t}face(e){this.facing=e}},TV=class{constructor(e,t={}){this.sound=e,this.x=t.x??0,this.y=t.y??0,this.falloff={refDistance:t.refDistance,maxDistance:t.maxDistance,rolloff:t.rolloff}}moveTo(e,t){this.x=e,this.y=t}gainTo(e){return SV(Math.hypot(this.x-e.x,this.y-e.y),this.falloff)}panTo(e){return CV(e,this)}playFor(e){let t=this.gainTo(e);return t<=0?0:(this.sound.play(t),t)}},EV=l({AudioListener:()=>wV,MidiPlayer:()=>xV,Music:()=>lV,Orchestrator:()=>uV,Sound:()=>cV,SoundSource:()=>TV,audioGain:()=>SV,audioPan:()=>CV,createAudio:()=>oV,noteToFrequency:()=>bV,onCaption:()=>sV,parseMidi:()=>vV,playTone:()=>fV,scheduleMidi:()=>yV,synthesizeTone:()=>dV});function DV(e,t){if(!Number.isSafeInteger(t)||t<0)throw RangeError(`Turn budget must be a non-negative safe integer`);let n=0;for(;n<t;){if(e.finished())return{status:`finished`,steps:n};let t=e.scheduler.peek();if(t===null)return{status:`empty`,steps:n};if(e.needsInput(t))return{status:`input`,actor:t,steps:n};let r=e.act(t);if(r!==null){if(!Number.isFinite(r)||r<0)throw RangeError(`Action cost must be finite and non-negative, or null`);e.scheduler.spend(r)}n++}return{status:`limit`,steps:n}}function OV(e){let t=e.state,n=e.status??`ready`,r=[],i=0;for(let a of e.commands){if(n===`finished`)break;let o=e.step(t,a,e.random);t=o.state,n=o.status;for(let e of o.events)r.push(e);i++}return{state:t,events:r,status:n,processedCommands:i}}var kV=class e{constructor(e){if(this._reminders=[],this._results={},this.levels=new Map(e.levels.map(e=>[e.id,e])),this.levels.size!==e.levels.length)throw Error(`campaign level ids must be unique`);if(!this.levels.has(e.start))throw Error(`unknown campaign start level: ${e.start}`);this._currentLevel=e.start,this._state=structuredClone(e.state)}get currentLevel(){return this._currentLevel}get state(){return structuredClone(this._state)}get reminders(){return[...this._reminders]}get results(){return structuredClone(this._results)}playCurrent(){if(!this._currentLevel)throw Error(`campaign has no current level`);let e=this.levels.get(this._currentLevel);return this.completeCurrent(e.run(this.state,{levelId:e.id}))}completeCurrent(e){if(!this._currentLevel)throw Error(`campaign has no current level`);let t=this._currentLevel;if(this._state=structuredClone(e.state),e.result!==void 0&&(this._results[t]=structuredClone(e.result)),this._reminders=[...e.reminders??[]],e.outcome!==`completed`)this._currentLevel=null;else if(e.next===void 0)throw Error(`campaign level ${t} did not choose a next level`);else{if(e.next!==null&&!this.levels.has(e.next))throw Error(`unknown campaign transition: ${t} -> ${e.next}`);this._currentLevel=e.next}return{...e,state:this.state}}snapshot(){return{currentLevel:this._currentLevel,state:this.state,reminders:this.reminders,results:this.results}}static restore(t,n){let r=t.currentLevel??n.levels[0]?.id;if(!r)throw Error(`campaign restore requires at least one level`);let i=new e({levels:n.levels,start:r,state:t.state});return i._currentLevel=t.currentLevel,i._reminders=[...t.reminders],i._results=structuredClone(t.results),i}};function AV(e){let t=new w(e.seed);return{...OV({state:structuredClone(e.initialState),commands:e.commands,status:e.status,random:t,step:e.step}),seed:e.seed,random:t.getState()}}var jV=class e{constructor(e){this._state=e.state,this.scheduler=e.scheduler,this.random=e.random,this.rule=e.rule,this.actorId=e.actorId}get state(){return this._state}dispatch(e){let t=this.rule(this._state,e,{random:this.random,scheduler:this.scheduler});return this._state=t.state,t.cost!=null&&this.scheduler.spend(t.cost),t}snapshot(e=1){return{version:e,state:this._state,scheduler:this.scheduler.toJSON(this.actorId),random:this.random.getState()}}static restore(t,n){let r=new w;r.setState(t.random);let i=NI.restore(t.scheduler,n.actorOf);return new e({state:t.state,scheduler:i,random:r,rule:n.rule,actorId:n.actorId})}},MV=class e{constructor(e){this.followUps=[],this.runtime=e.runtime,this.queue=new Fn({play:e.play}),this.followUpOf=e.followUp}get locked(){return this.queue.isBusy}submit(e){return this.locked?null:this.commit(e)}update(e){this.queue.update(e),this.drainFollowUps()}cancel(){this.queue.clear(),this.followUps=[]}snapshot(e=1){return this.runtime.snapshot(e)}static restore(t,n){let r=jV.restore(t,{rule:n.rule,actorOf:n.actorOf,actorId:n.actorId});return new e({runtime:r,play:n.play,followUp:n.followUp})}commit(e){let t=this.runtime.dispatch(e);return this.queue.enqueue(t.events),this.followUpOf&&this.followUps.push(...this.followUpOf(t)),this.drainFollowUps(),t}drainFollowUps(){for(;!this.queue.isBusy&&this.followUps.length>0;){let e=this.followUps.shift();this.commit(e)}}},NV=class{constructor(e){this.saves=new Nt(e)}save(e,t,n){this.saves.save(e,{campaign:t.campaign.snapshot(),world:t.world,simulation:t.simulation?t.simulation.snapshot():null},n)}load(e){return this.saves.load(e)?.state??null}list(){return this.saves.list()}delete(e){this.saves.delete(e)}},PV=l({Campaign:()=>kV,CampaignSave:()=>NV,EventPresentation:()=>MV,Scheduler:()=>NI,SimulationRuntime:()=>jV,advanceToInput:()=>DV,runHeadlessScenario:()=>AV,runScenario:()=>OV}),FV=class extends Error{constructor(e){super(`${e.location.file}:${e.location.line}:${e.location.column}: ${e.message}`),this.name=`MwlSyntaxError`,this.diagnostic=e}},IV=new Set([`define`,`enddef`,`arg`,`ifdef`,`ifndef`,`else`,`endif`,`include`]);function LV(e,t={}){let n=new Map,r=new Set(t.defines??[]),i=e.split(/\r?\n/),a=[],o=[!0],s=null;for(let e=0;e<i.length;e++){let c=i[e],l=/^\s*#([A-Za-z_][\w-]*)(?:\s+(.*))?$/.exec(c);if(l&&IV.has(l[1])){let i=l[1],u=l[2]?.trim()??``;if(i===`define`){if(!o.at(-1)||s)continue;let n=HV(u);if(n.length===0)throw WV(`MWL_DEFINE`,`macro name is required`,t.file,e,c);s={name:n[0],parameters:n.slice(1),body:[]},r.add(n[0]);continue}if(i===`arg`){s&&u&&s.parameters.push(u.split(/\s+/)[0]);continue}if(i===`enddef`){if(!s)throw WV(`MWL_ENDDEF`,`unexpected #enddef`,t.file,e,c);n.set(s.name,{name:s.name,parameters:s.parameters,body:s.body.join(`
1345
- `)}),s=null;continue}if(i===`ifdef`||i===`ifndef`){let e=r.has(u);o.push(o.at(-1)===!0&&(i===`ifdef`?e:!e));continue}if(i===`else`){if(o.length<2)throw WV(`MWL_ELSE`,`unexpected #else`,t.file,e,c);o[o.length-1]=o[o.length-2]&&!o.at(-1);continue}if(i===`endif`){if(o.length<2)throw WV(`MWL_ENDIF`,`unexpected #endif`,t.file,e,c);o.pop();continue}if(i===`include`){if(o.at(-1)){let n=t.includes?.[UV(u)];if(n===void 0)throw WV(`MWL_INCLUDE`,`include not supplied: ${u}`,t.file,e,c);a.push(LV(n,t))}continue}}if(s){o.at(-1)&&s.body.push(c);continue}o.at(-1)&&!/^\s*#/.test(c)&&a.push(c)}if(s)throw WV(`MWL_ENDDEF`,`macro ${s.name} is missing #enddef`,t.file,i.length-1,i.at(-1)??``);if(o.length!==1)throw WV(`MWL_ENDIF`,`conditional is missing #endif`,t.file,i.length-1,i.at(-1)??``);return RV(a.join(`
1346
- `),n,t)}function RV(e,t,n){return e.replace(/\{([^{}]*)\}/g,(e,r)=>{let i=HV(r),a=t.get(i[0]);if(!a)return e;let o=a.body;for(let e=0;e<a.parameters.length;e++){let t=a.parameters[e],n=i.find(e=>e.startsWith(`${t}=`)),r=n?n.slice(t.length+1):i[e+1]??``;o=o.replaceAll(`{${t}}`,r)}return RV(o,t,n)})}function zV(e,t=`<mwl>`){let n=[],r=[],i=e.split(/\r?\n/);for(let e=0;e<i.length;e++){let a=i[e],o=a.trim();if(!o||o.startsWith(`#`))continue;let s={file:t,line:e+1,column:Math.max(1,a.indexOf(o)+1)},c=/^\[([A-Za-z_][\w-]*)\]$/.exec(o);if(c){let e={tag:c[1],attributes:{},children:[],location:s,gettext:[]};r.length?r.at(-1).children.push(e):n.push(e),r.push(e);continue}let l=/^\[\/([A-Za-z_][\w-]*)\]$/.exec(o);if(l){let e=r.pop();if(!e||e.tag!==l[1])throw new FV({code:`MWL_TAG`,message:`mismatched closing tag ${l[1]}`,location:s,lineText:a});continue}let u=/^([A-Za-z_][\w-]*)\s*=\s*(.*)$/.exec(o);if(u&&r.length){let e=r.at(-1);VV(u[2])&&e.gettext.push(u[1]),e.attributes[u[1]]=BV(u[2],s,a);continue}throw new FV({code:`MWL_TOKEN`,message:`expected a tag or key=value attribute`,location:s,lineText:a})}if(r.length){let e=r.at(-1);throw new FV({code:`MWL_TAG`,message:`unclosed tag ${e.tag}`,location:e.location})}return n}function BV(e,t,n=e){let r=e.trim(),i=/^_\s*"/.exec(r);if(i&&(r=r.slice(i[0].length-1)),r.startsWith(`"`)){if(!r.endsWith(`"`)||r.length<2)throw new FV({code:`MWL_STRING`,message:`unterminated quoted value`,location:t,lineText:n});return r.slice(1,-1).replaceAll(`""`,`"`)}return r}function VV(e){return/^_\s*"/.test(e.trim())}function HV(e){let t=[],n=``,r=!1;for(let i=0;i<e.length;i++){let a=e[i];a===`"`&&(r=!r),/\s/.test(a)&&!r?(n&&t.push(n),n=``):n+=a}return n&&t.push(n),t}function UV(e){return e.startsWith(`"`)&&e.endsWith(`"`)?e.slice(1,-1):e}function WV(e,t,n,r,i){return new FV({code:e,message:t,location:{file:n??`<mwl>`,line:r+1,column:1},lineText:i})}function GV(e,t){if(!Number.isInteger(t.version)||t.version<1)throw Error(`MWL save version must be a positive integer`);return JSON.stringify({format:`mwl-save`,version:t.version,world:e})}function KV(e,t){let n=JSON.parse(e),r=JV(n)?n:{format:`mwl-save`,version:1,world:n};if(r.version>t.version)throw Error(`MWL save version ${r.version} is newer than supported version ${t.version}`);let i=qV(r.world);for(let e=r.version;e<t.version;e++){let n=t.migrations?.[e+1];if(!n)throw Error(`missing MWL save migration to version ${e+1}`);i=qV(n(i))}return i}function qV(e){if(!e||typeof e!=`object`)throw Error(`invalid MWL saved world`);let t=e;if(!Number.isInteger(t.turn)||!t.variables||typeof t.variables!=`object`||!t.units||typeof t.units!=`object`)throw Error(`invalid MWL saved world: turn, variables, and units are required`);if(t.status!==void 0&&![`playing`,`won`,`lost`].includes(t.status))throw Error(`invalid MWL saved world status`);return structuredClone(t)}function JV(e){return!!e&&typeof e==`object`&&e.format===`mwl-save`&&typeof e.version==`number`&&`world`in e}function YV(e,t,n={}){let r=e.search(/\s+where\s+/),i=r<0?e:e.slice(0,r),a={...t};if(r>=0)for(let t of e.slice(r).replace(/^\s+where\s+/,``).split(`,`)){let e=/^\s*([A-Za-z_][A-Za-z0-9_.-]*)\s*=\s*(.+)\s*$/.exec(t);if(!e)throw Error(`invalid MWL where binding: ${t}`);let r=new XV(e[2],a,n.helpers??{});if(a[e[1]]=r.parseOr(),!r.atEnd())throw Error(`invalid MWL where binding: ${t}`)}let o=new XV(i,a,n.helpers??{}),s=o.parseOr();if(!o.atEnd())throw Error(`unexpected token in MWL condition: ${o.peek()}`);return QV(s)}var XV=class{constructor(e,t,n){this.index=0,this.tokens=ZV(e),this.context=t,this.helpers=n}parseOr(){let e=this.parseAnd();for(;this.take(`or`);)e=QV(e)||QV(this.parseAnd());return e}parseAnd(){let e=this.parseNot();for(;this.take(`and`);)e=QV(e)&&QV(this.parseNot());return e}parseNot(){return this.take(`not`)?!QV(this.parseNot()):this.parseComparison()}parseComparison(){let e=this.parseAdditive(),t=this.peek();if(![`==`,`~=`,`<`,`<=`,`>`,`>=`].includes(t))return e;this.index++;let n=this.parseAdditive();if(t===`==`)return e===n;if(t===`~=`)return e!==n;if(typeof e!=`number`||typeof n!=`number`)throw Error(`${t} requires numeric operands`);return t===`<`?e<n:t===`<=`?e<=n:t===`>`?e>n:e>=n}parseAdditive(){let e=this.parseMultiplicative();for(;this.peek()===`+`||this.peek()===`-`;){let t=this.tokens[this.index++],n=this.parseMultiplicative();if(typeof e!=`number`||typeof n!=`number`)throw Error(`${t} requires numeric operands`);e=t===`+`?e+n:e-n}return e}parseMultiplicative(){let e=this.parsePrimary();for(;this.peek()===`*`||this.peek()===`/`;){let t=this.tokens[this.index++],n=this.parsePrimary();if(typeof e!=`number`||typeof n!=`number`)throw Error(`${t} requires numeric operands`);if(t===`/`&&n===0)throw Error(`division by zero in MWL condition`);e=t===`*`?e*n:e/n}return e}parsePrimary(){if(this.take(`(`)){let e=this.parseOr();return this.expect(`)`),e}let e=this.tokens[this.index++];if(e===void 0)throw Error(`incomplete MWL condition`);if(/^-?(?:\d+(?:\.\d*)?|\.\d+)$/.test(e))return Number(e);if(e===`true`||e===`yes`)return!0;if(e===`false`||e===`no`)return!1;if(e.startsWith(`"`)||e.startsWith(`'`))return e.slice(1,-1);let t=this.helpers[e];if(t&&this.take(`(`)){let e=[];if(!this.take(`)`)){do e.push(this.parseOr());while(this.take(`,`));this.expect(`)`)}return t(...e)}let n=this.context[e];if(n===void 0)throw Error(`missing MWL condition variable "${e}"`);return n}take(e){return this.peek()===e&&(this.index++,!0)}expect(e){if(!this.take(e))throw Error(`expected "${e}" in MWL condition`)}peek(){return this.tokens[this.index]??`<end>`}atEnd(){return this.index>=this.tokens.length}};function ZV(e){let t=[],n=/\s*(?:("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*')|([A-Za-z_][A-Za-z0-9_.-]*)|(-?(?:\d+(?:\.\d*)?|\.\d+))|(==|~=|<=|>=|[()+*/,<>-]))/y,r=0;for(;r<e.length;){n.lastIndex=r;let i=n.exec(e);if(!i)throw Error(`invalid MWL condition near "${e.slice(r)}"`);t.push(i[1]??i[2]??i[3]??i[4]),r=n.lastIndex}return t}function QV(e){return e!==!1&&e!==0&&e!==``}function $V(e){let t=new tH(e),n=t.expression();if(t.skip(),!t.atEnd())throw Error(`invalid MWL expression near "${t.rest()}"`);return n}function eH(e,t){let n=typeof e==`string`?$V(e):e;if(n.kind===`number`)return n.value;if(n.kind===`variable`){let e=t[n.name];if(e===void 0||!Number.isFinite(e))throw Error(`missing MWL expression variable "${n.name}"`);return e}let r=eH(n.left,t),i=eH(n.right,t);if(n.op===`+`)return r+i;if(n.op===`-`)return r-i;if(n.op===`*`)return r*i;if(n.op===`/`){if(i===0)throw Error(`division by zero in MWL expression`);return r/i}return r**i}var tH=class{constructor(e){this.index=0,this.source=e}expression(){return this.additive()}additive(){let e=this.multiplicative();for(;;){this.skip();let t=this.peek(`+`)?`+`:this.peek(`-`)?`-`:null;if(!t)return e;this.index++,e={kind:`binary`,op:t,left:e,right:this.multiplicative()}}}multiplicative(){let e=this.power();for(;;){this.skip();let t=this.peek(`*`)?`*`:this.peek(`/`)?`/`:null;if(!t)return e;this.index++,e={kind:`binary`,op:t,left:e,right:this.power()}}}power(){let e=this.primary();return this.skip(),this.peek(`^`)&&(this.index++,e={kind:`binary`,op:`^`,left:e,right:this.power()}),e}primary(){if(this.skip(),this.peek(`(`)){this.index++;let e=this.expression();if(this.skip(),!this.peek(`)`))throw Error(`missing closing parenthesis in MWL expression`);return this.index++,e}let e=/^(?:\d+(?:\.\d*)?|\.\d+)/.exec(this.rest());if(e)return this.index+=e[0].length,{kind:`number`,value:Number(e[0])};let t=/^[A-Za-z_][A-Za-z0-9_.-]*/.exec(this.rest());if(t)return this.index+=t[0].length,{kind:`variable`,name:t[0]};throw Error(`expected number, variable, or parenthesis near "${this.rest()}"`)}peek(e){return this.source[this.index]===e}skip(){for(;/\s/.test(this.source[this.index]??``);)this.index++}atEnd(){return this.index>=this.source.length}rest(){return this.source.slice(this.index)}};function nH(e){let t=[],n=e=>{t.push(e),e.children.forEach(n)};return e.forEach(n),t}function rH(e,t){let n=e.attributes[t];if(!n)throw Error(`MWL ${e.tag} is missing ${t}`);return n}function iH(e,t){let n=e.attributes[t];if(n===void 0)return;let r=Number(n);return Number.isFinite(r)?r:void 0}function aH(e,t,n){let r=e.attributes[t];if(r===void 0)return n;let i=Number.parseInt(r,10);return Number.isFinite(i)?i:n}function oH(e,t){let n=e.attributes[t];return n===void 0?void 0:n===`true`||n===`yes`}function sH(e,t){return e!==void 0&&t.includes(e)?e:void 0}function cH(e,t,n){let r=n.carryoverPercentage??80,i=t?e.gold[t.id]??e.sides[t.id]?.gold??0:0;return{result:n.result,gold:Math.floor(i*r/100)+(n.bonus??0),add:n.carryoverAdd??!1,recall:t?Object.entries(e.units).filter(([,e])=>e.alive&&e.side===t.id).map(([e])=>e).sort():[],nextScenario:n.nextScenario??null}}function lH(e,t){return e.add?t+e.gold:Math.max(t,e.gold)}var uH=rH,dH=(e,t,n)=>aH(e,t,n)??n;function fH(){return{variables:{},units:{},sides:{},maps:{},gold:{},turn:1,status:`playing`,sideStatus:{},map:null,timeOfDay:``,scheduleIndex:0}}function pH(e){let t=e.split(/\r?\n/).filter(e=>e.trim()!==``).map(e=>e.split(`,`).map(e=>e.trim())),n=t.length,r=t.length?Math.max(...t.map(e=>e.length)):0,i=[],a={};for(let e=0;e<n;e++)for(let n=0;n<r;n++){let r=t[e]?.[n]??`_off^_usr`,o=/^([A-Za-z0-9_][\w.-]*)\s+(\S.*)$/.exec(r);o?(i.push(o[2]),(a[o[1]]??=[]).push({x:n,y:e})):i.push(r)}return{width:r,height:n,codes:i,starts:a}}var mH=class{constructor(e,t={}){this.unitTypes=new Map,this.schedule=[],this.pendingDialogue=null,this.dialogueCounter=0,this.game=e,this.world=t.world??fH(),this.onMessage=t.onMessage,this.resolveMap=t.resolveMap,this.hooks=t.hooks,this.onTrace=t.onTrace,this.persistence=t.persistence??{version:1},this.loadUnitTypes(),this.loadSchedule(),this.loadInitialContent(),this.loadInitialUnits(),this.loadLeaders(),this.loadScenarioExtras()}run(e){for(let t of this.nodes(`event`))(t.attributes.on??t.attributes.trigger)===e&&this.eventFiltersMatch(t)&&this.claimEvent(t)&&this.executeTracedEvent(t,e);this.checkObjectives()}fireEvent(e){let t=this.nodes(`event`).find(t=>t.attributes.id===e);return!t||!this.eventFiltersMatch(t)||!this.claimEvent(t)?!1:(this.executeTracedEvent(t,`fireEvent`),this.checkObjectives(),!0)}fireMoveto(e){let t=this.world.units[e];if(!(!t||!t.alive)){for(let n of this.nodes(`event`))(n.attributes.on??n.attributes.trigger)===`moveto`&&(n.attributes.x!==void 0&&!OH(n.attributes.x,t.x)||n.attributes.y!==void 0&&!OH(n.attributes.y,t.y)||(n.attributes.unit===void 0||n.attributes.unit===e)&&(n.attributes.side===void 0||n.attributes.side===t.side)&&this.eventFiltersMatch(n)&&this.claimEvent(n)&&this.executeTracedEvent(n,`moveto`));this.checkObjectives()}}claimEvent(e){if(!(e.attributes.once===void 0?e.attributes.on===`moveto`:e.attributes.once!==`false`))return!0;let t=e.attributes.id??`${e.attributes.on??e.attributes.trigger??`event`}@${e.location?.line??0}`,n=this.world.firedEvents??=[];return!n.includes(t)&&(n.push(t),!0)}eventFiltersMatch(e){if(!this.conditionMatches(e)||!this.filterConditionMatches(e))return!1;let t=e.children.find(e=>e.tag===`filter`);return!t||this.filterMatches(t)}executeEvent(e){for(let t of e.children.filter(e=>e.tag!==`condition`&&e.tag!==`filter`&&e.tag!==`filter_condition`)){if(t.tag===`say`){this.showSay(t);continue}if(t.tag===`dialogue`){this.showDialogue(t);continue}this.executeNode(t)}}executeTracedEvent(e,t){let n=e.attributes.id??`${e.attributes.on??e.attributes.trigger??`event`}@${e.location?.line??0}`;this.onTrace?.({type:`event`,phase:`claimed`,id:n,trigger:t});try{this.executeEvent(e),this.onTrace?.({type:`event`,phase:`completed`,id:n,trigger:t})}catch(e){throw this.onTrace?.({type:`error`,message:String(e),event:n}),e}}showDialogue(e){let t=null;for(let n of e.children)n.tag===`message`?(this.showMessage(n.attributes),t={text:n.attributes.text??n.attributes.value??``,...n.attributes.speaker===void 0?{}:{speaker:n.attributes.speaker},...n.attributes.portrait===void 0?{}:{portrait:n.attributes.portrait},...n.attributes.side===void 0||n.attributes.side===``?{}:{side:n.attributes.side}}):n.tag===`say`&&(this.showSay(n),t={text:n.attributes.text??``,speaker:n.attributes.speaker});let n=[];for(let t of e.children){if(t.tag!==`choice`||!t.attributes.text||t.attributes.variable!==void 0&&!EH(this.world.variables[t.attributes.variable],t.attributes.equals))continue;let e=t.children.filter(e=>e.tag===`branch`);if(e.length)for(let r of e)n.push({text:r.attributes.text??t.attributes.text,branch:r.children});else t.attributes.event&&n.push({text:t.attributes.text,event:t.attributes.event})}if(n.length===0)return;this.dialogueCounter+=1;let r=`dialogue-${this.dialogueCounter}`;this.pendingDialogue={id:r,choices:n},this.world.pendingDialogue={id:r,choices:n},this.onMessage?.({text:t?.text??``,...t?.speaker===void 0?{}:{speaker:t.speaker},choices:n,dialogueId:r})}showSay(e){this.onMessage&&this.onMessage({text:e.attributes.text??``,...e.attributes.speaker===void 0?{}:{speaker:e.attributes.speaker}})}answerDialogue(e,t){let n=this.pendingDialogue;if(!n||n.id!==e)return!1;let r=n.choices[t];if(!r)return!1;if(this.pendingDialogue=null,delete this.world.pendingDialogue,r.event){let e=this.nodes(`event`).find(e=>e.attributes.id===r.event);if(!e)throw Error(`MWL dialogue choice points at unknown event: ${r.event}`);if(!this.claimEvent(e))return!0;this.executeEvent(e)}else for(let e of r.branch??[])this.executeNode(e);return this.checkObjectives(),!0}evaluate(){return this.checkObjectives(),this.world.status}save(){return GV(this.world,this.persistence)}snapshot(){return JSON.stringify(this.world)}restore(e){let t=KV(e,this.persistence);Object.assign(this.world.variables,t.variables),Object.assign(this.world.units,t.units),Object.assign(this.world.sides,t.sides??{}),Object.assign(this.world.maps,t.maps??{}),Object.assign(this.world.gold,t.gold??{}),this.world.turn=t.turn,this.world.status=t.status,this.world.sideStatus={...t.sideStatus??{}},this.world.map=t.map??null,this.world.timeOfDay=t.timeOfDay??this.schedule[0]??``,this.world.scheduleIndex=t.scheduleIndex??0,this.world.firedEvents=[...t.firedEvents??[]],this.world.villages=t.villages?structuredClone(t.villages):void 0,this.world.clearedShroud=t.clearedShroud?structuredClone(t.clearedShroud):void 0,this.world.roles=t.roles?structuredClone(t.roles):void 0,this.world.objects=t.objects?structuredClone(t.objects):void 0,this.world.story=t.story?structuredClone(t.story):void 0,this.world.pendingDialogue=t.pendingDialogue,this.pendingDialogue=t.pendingDialogue?{id:t.pendingDialogue.id,choices:[...t.pendingDialogue.choices]}:null;let n=t.pendingDialogue?.id.match(/^dialogue-(\d+)$/);n&&(this.dialogueCounter=Math.max(this.dialogueCounter,Number(n[1])))}loadUnitTypes(){for(let e of this.nodes(`unit_type`)){let t=e.attributes.id;t&&this.unitTypes.set(t,{hitpoints:dH(e,`hitpoints`,1),movement:dH(e,`movement`,0)})}}loadSchedule(){this.schedule=this.nodes(`schedule`).flatMap(e=>e.children.filter(e=>e.tag===`time`).map(e=>e.attributes.id).filter(e=>!!e)),this.world.scheduleIndex=0,this.world.timeOfDay=this.schedule[0]??``}loadInitialContent(){for(let e of this.nodes(`side`)){let t={gold:dH(e,`gold`,0),income:dH(e,`income`,0)};e.attributes.leader!==void 0&&(t.leader=e.attributes.leader),e.attributes.controller!==void 0&&(t.controller=e.attributes.controller),e.attributes.recruit!==void 0&&(t.recruit=e.attributes.recruit),e.attributes.team_name!==void 0&&(t.teamName=e.attributes.team_name),e.attributes.user_team_name!==void 0&&(t.userTeamName=e.attributes.user_team_name),e.attributes.share_vision!==void 0&&(t.shareVision=e.attributes.share_vision),e.attributes.flag!==void 0&&(t.flag=e.attributes.flag),e.attributes.village_gold!==void 0&&(t.villageGold=dH(e,`village_gold`,0));for(let n of[`heal`,`fog`,`shroud`,`hidden`]){let r=e.attributes[n];r!==void 0&&(t[n]=r===`yes`||r===`true`)}this.world.sides[uH(e,`id`)]=t}for(let e of this.nodes(`map`)){let t=e.attributes.id??e.attributes.name??`map`;this.world.maps[t]={terrain:e.attributes.terrain??``,file:e.attributes.file},this.world.map||(this.world.map=this.buildMap(t,e))}}topLevelNodes(e){return(this.game.roots.find(e=>e.tag===`game`)?.children??this.game.roots).filter(t=>t.tag===e)}loadScenarioExtras(){for(let e of this.topLevelNodes(`object`)){let t={x:dH(e,`x`,0),y:dH(e,`y`,0)};e.attributes.id!==void 0&&(t.id=e.attributes.id),e.attributes.name!==void 0&&(t.name=e.attributes.name),e.attributes.image!==void 0&&(t.image=e.attributes.image),e.attributes.side!==void 0&&(t.side=e.attributes.side),(this.world.objects??=[]).push(t)}for(let e of this.topLevelNodes(`story`)){let t=e.attributes.text??e.attributes.value;if(t===void 0)continue;let n={text:t};e.attributes.title!==void 0&&(n.title=e.attributes.title),e.attributes.image!==void 0&&(n.image=e.attributes.image),e.attributes.music!==void 0&&(n.music=e.attributes.music),(this.world.story??=[]).push(n)}for(let e of this.topLevelNodes(`role`)){let t=e.attributes.role??e.attributes.name;t!==void 0&&((this.world.roles??={})[t]=Object.entries(this.world.units).filter(([t,n])=>n.alive&&TH(n,t,e.attributes)).map(([e])=>e))}}buildMap(e,t){let n=t.attributes.terrain;if(!n&&t.attributes.file&&this.resolveMap&&(n=this.resolveMap(t.attributes.file)),!n)return null;let r=pH(n);for(let e of t.children){if(e.tag!==`start`)continue;let t=e.attributes.side,n=CH(e,`x`),i=CH(e,`y`);t!==void 0&&n!==void 0&&i!==void 0&&(r.starts[t]??=[]).push({x:n,y:i})}return{id:e,...r}}loadInitialUnits(){for(let e of this.nodes(`unit`)){let t=uH(e,`id`),n={hp:dH(e,`hp`,1),x:dH(e,`x`,0),y:dH(e,`y`,0),alive:!0};if(e.attributes.type!==void 0){n.type=e.attributes.type;let t=this.unitTypes.get(e.attributes.type);t&&(n.moves=t.movement)}e.attributes.side!==void 0&&(n.side=e.attributes.side),this.world.units[t]=n}}loadLeaders(){for(let e of this.nodes(`side`)){let t=e.attributes.leader;if(!t)continue;let n=e.attributes.id;if(!n)continue;let r=this.world.map?.starts[n];if(!r?.length)continue;let i=this.unitTypes.get(t);for(let e of r){if(this.unitAt(e.x,e.y))continue;let r=`${t} ${n} (${e.x},${e.y})`;this.world.units[r]={hp:i?.hitpoints??1,x:e.x,y:e.y,alive:!0,type:t,side:n,moves:i?.movement??0}}}}unitAt(e,t){return Object.values(this.world.units).find(n=>n.alive&&n.x===e&&n.y===t)}executeNode(e){let t=e.tag===`command`?e.attributes.name:e.tag;if(!t)throw Error(`MWL command is missing name`);switch(t){case`message`:this.showMessage(e.attributes);break;case`spawn`:this.spawnUnit(e.attributes.type??``,e.attributes.side,dH(e,`x`,0),dH(e,`y`,0),e.attributes.id??e.attributes.target,e.attributes.hp===void 0?void 0:dH(e,`hp`,1));break;case`move`:this.applyMove(e.attributes.unit??uH(e,`target`),dH(e,`x`,0),dH(e,`y`,0));break;case`kill`:{let t=e.attributes.unit??e.attributes.target;t===void 0?yH(this.world,e.attributes):this.killUnit(t);break}case`fire_event`:{let t=e.attributes.id??e.attributes.name;if(!t)throw Error(`[fire_event] requires id`);this.fireEvent(t);break}case`store_unit`:{let t=e.attributes.variable??e.attributes.name??uH(e,`variable`);this.setVariableAt(t,this.matchingUnits(e).map(([e,t])=>({id:e,...bH(t)})));break}case`unstore_unit`:{let t=uH(e,`variable`);for(let e of this.storedUnits(t))this.restoreUnit(e,{});break}case`recall`:{let t=this.storedUnits(uH(e,`variable`)),n=e.attributes.id??e.attributes.unit,r=n===void 0?t[0]:t.find(e=>e.id===n);if(!r)throw Error(`[recall] found no stored unit${n===void 0?``:` named ${n}`}`);let i={};e.attributes.x!==void 0&&(i.x=dH(e,`x`,0)),e.attributes.y!==void 0&&(i.y=dH(e,`y`,0)),e.attributes.side!==void 0&&(i.side=e.attributes.side),this.restoreUnit(r,i);break}case`modify_unit`:{let t=e.children.find(e=>e.tag===`set`)?.attributes??e.attributes;for(let[,n]of this.matchingUnits(e))xH(n,t);break}case`heal_unit`:{let t=CH(e,`amount`),n=CH(e,`hp`);if(t===void 0&&n===void 0)throw Error(`[heal_unit] requires amount or hp`);for(let[,r]of this.matchingUnits(e))r.hp=n??r.hp+(t??0);break}case`set_terrain`:this.setTerrain(dH(e,`x`,0),dH(e,`y`,0),uH(e,`terrain`));break;case`capture_village`:{let t=dH(e,`x`,0),n=dH(e,`y`,0),r={x:t,y:n,side:uH(e,`side`)};e.attributes.name!==void 0&&(r.name=e.attributes.name),(this.world.villages??={})[`${t},${n}`]=r;break}case`clear_shroud`:{let t=uH(e,`side`),n=dH(e,`x`,0),r=dH(e,`y`,0),i=dH(e,`radius`,1),a=new Set(this.world.clearedShroud?.[t]??[]);for(let e=-i;e<=i;e++)for(let t=-i;t<=i;t++)a.add(`${n+t},${r+e}`);(this.world.clearedShroud??={})[t]=[...a];break}case`role`:{let t=e.attributes.role??e.attributes.name;if(!t)throw Error(`[role] requires role`);(this.world.roles??={})[t]=this.matchingUnits(e).map(([e])=>e);break}case`attack`:this.attack(e.attributes.defender??e.attributes.target??uH(e,`target`),dH(e,`amount`,0));break;case`modify_gold`:this.addGold(e.attributes.side??uH(e,`target`),dH(e,`delta`,dH(e,`amount`,0)));break;case`gold`:this.addGold(uH(e,`side`),dH(e,`delta`,dH(e,`amount`,0)));break;case`set_variable`:this.setVariable(e.tag===`command`?uH(e,`target`):uH(e,`name`),e.attributes.value??``);break;case`while`:{let t=dH(e,`max_iterations`,1e3);if(t<1||t>1e5)throw Error(`MWL while max_iterations must be between 1 and 100000`);for(let n=0;n<t&&this.nodeConditionMatches(e);n++)for(let t of e.children)this.executeNode(t);break}case`foreach`:{let t=this.variableAt(uH(e,`variable`)),n=Array.isArray(t)?t.map((e,t)=>[String(t),e]):typeof t==`string`?t.split(`,`).map((e,t)=>[String(t),e.trim()]).filter(([,e])=>e!==``):t&&typeof t==`object`?Object.entries(t):[],r=e.attributes.item??`item`,i=e.attributes.index??`index`;for(let t=0;t<n.length;t++){this.setVariableAt(r,n[t][1]),this.setVariableAt(i,t);for(let t of e.children)this.executeNode(t)}break}case`switch`:{let t=this.variableAt(uH(e,`variable`)),n=e.children.find(e=>e.tag===`case`&&e.attributes.equals!==void 0&&EH(t,e.attributes.equals)),r=e.children.find(e=>e.tag==="default");for(let e of(n??r)?.children??[])this.executeNode(e);break}case`end_turn`:this.endTurn();break;case`win`:this.markSideResult(e.attributes.side,`won`),this.world.status=`won`;break;case`lose`:this.markSideResult(e.attributes.side,`lost`),this.world.status=`lost`;break;case`endlevel`:{let t=e.attributes.result===`defeat`?`defeat`:`victory`;this.world.status=t===`defeat`?`lost`:`won`,this.world.carryover=cH(this.world,gH(this.world,e.attributes.side),{result:t,bonus:aH(e,`bonus`),carryoverPercentage:iH(e,`carryover_percentage`),carryoverAdd:oH(e,`carryover_add`),nextScenario:e.attributes.next_scenario??null});break}case`if`:if(!this.nodeConditionMatches(e))break;for(let t of e.children)this.executeNode(t);break;case`else`:for(let t of e.children)this.executeNode(t);break;case`hook`:this.runHook(e);break;default:throw Error(`unknown MWL command: ${t}`)}}runHook(e){let t=e.attributes.name??``,n=this.hooks?.command?.[t];if(!n)throw Error(`MWL hook ${t} is not implemented`);let{name:r,...i}=e.attributes;n(this.worldView(),this.emit(),i)}applyMove(e,t,n){let r=this.world.units[e];if(!r||!r.alive)throw Error(`MWL unit is not alive: ${e}`);let i=this.world.map??null;if(i){if(t<0||n<0||t>=i.width||n>=i.height)throw Error(`MWL move out of bounds: ${t},${n}`);let e=this.unitAt(t,n);if(e&&e!==r)throw Error(`MWL move onto an occupied cell: ${t},${n}`)}if(typeof r.moves==`number`){if(r.moves<=0)throw Error(`MWL unit has no moves left: ${e}`);--r.moves}r.x=t,r.y=n,this.fireMoveto(e)}showMessage(e){if(!this.onMessage)return;let t={text:this.interpolate(e.text??e.value??``),...e.speaker===void 0?{}:{speaker:e.speaker},...e.portrait===void 0?{}:{portrait:e.portrait},...e.side===void 0||e.side===``?{}:{side:e.side}};this.onMessage(t)}interpolate(e){let t=this.world.variables,n=Object.fromEntries(Object.entries(t).filter(e=>typeof e[1]==`number`));return e.replace(/\$\(([^)]*)\)/g,(e,t)=>{try{return String(eH(t,n))}catch{return``}}).replace(/\$([A-Za-z_][A-Za-z0-9_.]*)/g,(e,n)=>{let r=t[n];return r===void 0||typeof r==`boolean`?``:String(r)})}setVariable(e,t){let n=Number(t);if(t.trim()!==``&&Number.isFinite(n)){this.setVariableAt(e,n);return}let r=/^\$([A-Za-z_][A-Za-z0-9_.]*)$/.exec(t.trim());if(r){let t=this.world.variables[r[1]];this.setVariableAt(e,t===void 0?``:t);return}let i=Object.fromEntries(Object.entries(this.world.variables).filter(e=>typeof e[1]==`number`));if(/[+*/^()]|\s-\s/.test(t)||Object.prototype.hasOwnProperty.call(i,t.trim())){this.setVariableAt(e,eH(t,i));return}this.setVariableAt(e,t)}variableAt(e){let t=this.world.variables;for(let n of e.split(`.`)){if(!t||typeof t!=`object`||Array.isArray(t))return;t=t[n]}return t}setVariableAt(e,t){let n=this.variableAt(e),r=e.split(`.`);if(r.length===1){this.world.variables[e]=t,this.onTrace?.({type:`variable`,name:e,...n===void 0?{}:{previous:n},value:t});return}let i=this.world.variables;for(let e of r.slice(0,-1)){let t=i[e];(!t||typeof t!=`object`||Array.isArray(t))&&(i[e]={}),i=i[e]}i[r.at(-1)]=t,this.onTrace?.({type:`variable`,name:e,...n===void 0?{}:{previous:n},value:t})}spawnUnit(e,t,n,r,i,a){let o=e?this.unitTypes.get(e):void 0,s=i??`${e||`unit`}#${t??``}@${n},${r}`;this.world.units[s]={hp:a??o?.hitpoints??1,x:n,y:r,alive:!0,...e?{type:e}:{},...t===void 0?{}:{side:t},...o?{moves:o.movement}:{}}}killUnit(e){let t=this.world.units[e];if(!t||!t.alive)throw Error(`MWL unit is not alive: ${e}`);t.alive=!1}matchingUnits(e){let t=e.children.find(e=>e.tag===`filter`)?.attributes??e.attributes;return Object.entries(this.world.units).filter(([e,n])=>n.alive&&TH(n,e,t))}storedUnits(e){let t=this.world.variables[e];if(!Array.isArray(t))throw Error(`MWL variable ${e} is not a stored unit list; store one first`);return t.filter(e=>!!e&&typeof e==`object`&&!Array.isArray(e))}restoreUnit(e,t){let n=typeof e.id==`string`?e.id:void 0;if(!n)throw Error(`a stored unit snapshot is missing its id`);let r={hp:typeof e.hp==`number`?e.hp:1,x:t.x??(typeof e.x==`number`?e.x:0),y:t.y??(typeof e.y==`number`?e.y:0),alive:e.alive!==!1};typeof e.type==`string`&&(r.type=e.type);let i=t.side??(typeof e.side==`string`?e.side:void 0);i!==void 0&&(r.side=i),typeof e.moves==`number`&&(r.moves=e.moves),this.world.units[n]=r}setTerrain(e,t,n){let r=this.world.map;if(!r)throw Error(`[set_terrain] needs a loaded map`);if(e<0||t<0||e>=r.width||t>=r.height)throw Error(`[set_terrain] is outside the map: ${e},${t}`);let i=[...r.codes];i[t*r.width+e]=n,this.world.map={...r,codes:i}}addGold(e,t){this.world.gold[e]=(this.world.gold[e]??0)+t}endTurn(){this.world.turn+=1,this.advanceSchedule(),this.resetMoves(),this.run(`turn`),this.checkTimeOver()}checkTimeOver(){let e=aH(this.game.roots[0],`turn_limit`);e===void 0||this.world.turn<=e||this.world.variables.time_over===`yes`||(this.world.variables.time_over=`yes`,this.run(`time_over`))}advanceSchedule(){if(!this.schedule.length)return;let e=((this.world.scheduleIndex??0)+1)%this.schedule.length;this.world.scheduleIndex=e,this.world.timeOfDay=this.schedule[e]}resetMoves(){for(let e of Object.values(this.world.units)){if(!e.alive)continue;let t=e.type?this.unitTypes.get(e.type):void 0;t&&(e.moves=t.movement)}}filterMatches(e){return Object.entries(this.world.units).some(([t,n])=>n.alive&&TH(n,t,e.attributes))}conditionMatches(e){return e.children.filter(e=>e.tag===`condition`).every(e=>wH(this.world.variables[e.attributes.variable],e.attributes,DH(this.world.variables)))}nodeConditionMatches(e){return e.attributes.test===void 0?this.conditionMatches(e):YV(e.attributes.test,DH(this.world.variables))}filterConditionMatches(e){let t=e.children.find(e=>e.tag===`filter_condition`);return!t||t.children.every(e=>{if(e.tag===`variable`){let t=e.attributes.name;return t!==void 0&&wH(this.world.variables[t],e.attributes,DH(this.world.variables))}if(e.tag===`predicate`){let t=e.attributes.name,n=t?this.hooks?.predicate?.[t]:void 0;if(!n)throw Error(`MWL predicate ${t??`<missing>`} is not implemented`);let{name:r,...i}=e.attributes;return!!n(this.worldView(),i)}return e.tag!==`have_unit`||Object.entries(this.world.units).some(([t,n])=>n.alive&&(e.attributes.id===void 0||t===e.attributes.id)&&TH(n,t,e.attributes))})}conditionMet(e,t){let n=e.attributes.condition??``,r=e.attributes.side??t;switch(n){case`units_dead`:{let t=e.attributes.side_filter??r;return t!==void 0&&!Object.values(this.world.units).some(e=>e.alive&&e.side===t)}case`turns_elapsed`:{let t=CH(e,`turns`);return t!==void 0&&this.world.turn>=t}case`gold_at_least`:{let n=CH(e,`gold`),r=e.attributes.side??t;return n!==void 0&&r!==void 0&&(this.world.gold[r]??0)>=n}case`unit_at`:{let t=CH(e,`x`),n=CH(e,`y`),i=e.attributes.side_filter??r;return Object.values(this.world.units).some(r=>r.alive&&(i===void 0||r.side===i)&&(e.attributes.type===void 0||r.type===e.attributes.type)&&r.x===t&&r.y===n)}case`hook`:{let t=e.attributes.hook??``,n=this.hooks?.predicate?.[t];if(!n)throw Error(`MWL hook ${t} is not implemented`);let{hook:r,condition:i,...a}=e.attributes;return!!n(this.worldView(),a)}default:return!1}}checkObjectives(){if(this.world.status!==`playing`)return;let e=new Set,t=this.nodes(`side`);for(let n of t)for(let t of n.children)(t.tag===`victory`||t.tag===`defeat`)&&e.add(t);if(this.nodes(`victory`).some(t=>!e.has(t)&&this.conditionMet(t))){this.world.status=`won`;return}if(this.nodes(`defeat`).some(t=>!e.has(t)&&this.conditionMet(t))){this.world.status=`lost`;return}let n=!1,r=!1;for(let e of t){let t=e.attributes.id;!t||(this.world.sideStatus?.[t]??`playing`)!==`playing`||(e.children.some(e=>e.tag===`victory`&&this.conditionMet(e,t))?(this.markSideResult(t,`won`),n=!0):e.children.some(e=>e.tag===`defeat`&&this.conditionMet(e,t))&&(this.markSideResult(t,`lost`),r=!0))}n?this.world.status=`won`:r&&(this.world.status=`lost`)}markSideResult(e,t){e!==void 0&&e!==``&&((this.world.sideStatus??={})[e]=t)}worldView(){return{variables:this.world.variables,units:this.world.units,sides:this.world.sides,turn:this.world.turn}}emit(){return{move:(e,t,n)=>this.applyMove(e,t,n),attack:(e,t,n)=>{throw Error(`MWL hook attack is not available in the framework runtime; the engine adapter owns combat`)},spawn:(e,t,n,r)=>this.spawnUnit(e,t,n,r),kill:e=>this.killUnit(e),gold:(e,t)=>this.addGold(e,t),setVariable:(e,t)=>{this.world.variables[e]=t},message:(e,t)=>this.onMessage?.({text:t,...e?{speaker:e}:{}}),endTurn:()=>this.endTurn(),win:e=>{this.markSideResult(e,`won`),this.world.status=`won`},lose:e=>{this.markSideResult(e,`lost`),this.world.status=`lost`}}}attack(e,t){let n=this.world.units[e];if(!n||!n.alive)throw Error(`MWL unit is not alive: ${e}`);n.hp=Math.max(0,n.hp-t),n.hp===0&&(n.alive=!1)}nodes(e){let t=[],n=r=>{r.tag===e&&t.push(r),r.children.forEach(n)};return this.game.roots.forEach(n),t}};function hH(e,t){if(e.status===`playing`||t.name===`win`||t.name===`lose`)switch(t.name){case`set_variable`:e.variables[t.target]=t.value;break;case`modify_gold`:e.gold[t.target]=(e.gold[t.target]??0)+t.amount;break;case`move`:{let n=vH(e,t.target);n.x=t.x,n.y=t.y;break}case`spawn`:e.units[t.target]={hp:t.hp,x:t.x,y:t.y,alive:!0};break;case`kill`:t.target===void 0?yH(e,t.filter??{}):vH(e,t.target).alive=!1;break;case`end_turn`:e.turn++;break;case`win`:t.side!==void 0&&t.side!==``&&((e.sideStatus??={})[t.side]=`won`),e.status=`won`;break;case`lose`:t.side!==void 0&&t.side!==``&&((e.sideStatus??={})[t.side]=`lost`),e.status=`lost`;break;case`endlevel`:e.status=t.result===`defeat`?`lost`:`won`,e.carryover=cH(e,t.side??null,t)}}function gH(e,t){let n=t??Object.entries(e.sides).find(([,e])=>e.controller===`human`)?.[0];return!n||!(n in e.sides)?null:{id:n}}function _H(e){let t=new Map;for(let[n,r]of Object.entries(e.sides)){if(!r.teamName||r.shareVision===`none`)continue;let e=t.get(r.teamName);e?e.push(n):t.set(r.teamName,[n])}return[...t.values()].filter(e=>e.length>1)}function vH(e,t){let n=e.units[t];if(!n||!n.alive)throw Error(`MWL unit is not alive: ${t}`);return n}function yH(e,t){let n=0;for(let[r,i]of Object.entries(e.units))!i.alive||!TH(i,r,t)||(i.alive=!1,n++);return n}function bH(e){let t={hp:e.hp,x:e.x,y:e.y,alive:e.alive};return e.type!==void 0&&(t.type=e.type),e.side!==void 0&&(t.side=e.side),e.moves!==void 0&&(t.moves=e.moves),t}function xH(e,t){let n=SH(t.hp);n!==void 0&&(e.hp=n);let r=SH(t.moves);r!==void 0&&(e.moves=r),t.type!==void 0&&(e.type=t.type),t.side!==void 0&&(e.side=t.side),t.alive!==void 0&&(e.alive=t.alive===`yes`||t.alive===`true`)}function SH(e){if(e===void 0||e===``)return;let t=Number(e);return Number.isFinite(t)?t:void 0}function CH(e,t){let n=e.attributes[t];if(n===void 0||n===``)return;let r=Number.parseInt(n,10);return Number.isFinite(r)?r:void 0}function wH(e,t,n={}){let r=e=>e.startsWith(`$`)?n[e.slice(1)]:e;if(t.equals!==void 0)return EH(e,r(t.equals));if(t.not_equals!==void 0)return!EH(e,r(t.not_equals));if(t.in!==void 0)return t.in.split(`,`).map(e=>e.trim()).some(t=>EH(e,t));if(t.not_in!==void 0)return!t.not_in.split(`,`).map(e=>e.trim()).some(t=>EH(e,t));let i=typeof e==`number`?e:Number(e),a=e=>Number(t[e]);return t.less_than!==void 0||t.greater_than!==void 0||t.less_than_or_equal_to!==void 0||t.greater_than_or_equal_to!==void 0?!(typeof e==`boolean`||!Number.isFinite(i)||t.less_than!==void 0&&!(i<a(`less_than`))||t.greater_than!==void 0&&!(i>a(`greater_than`))||t.less_than_or_equal_to!==void 0&&!(i<=a(`less_than_or_equal_to`))||t.greater_than_or_equal_to!==void 0&&!(i>=a(`greater_than_or_equal_to`))):e!==void 0}function TH(e,t,n){let r=(n.not_type??``).split(`,`).map(e=>e.trim()).filter(Boolean),i=n.unit??n.id;return(i===void 0||t===i)&&(n.side===void 0||e.side===n.side)&&(n.type===void 0||e.type===n.type)&&(r.length===0||!r.includes(e.type??``))&&(n.x===void 0||e.x===Number(n.x))&&(n.y===void 0||e.y===Number(n.y))}function EH(e,t){if(e===void 0||t===void 0||typeof t!=`string`)return e===t;let n=Number(t);return typeof e==`number`&&t.trim()!==``&&Number.isFinite(n)?e===n:e===t}function DH(e){return Object.fromEntries(Object.entries(e).filter(e=>typeof e[1]==`string`||typeof e[1]==`number`||typeof e[1]==`boolean`))}function OH(e,t){return e.split(`,`).some(e=>{let n=e.trim(),r=n.match(/^(-?\d+)\s*-\s*(-?\d+)$/);if(r){let e=Number(r[1]),n=Number(r[2]);return t>=Math.min(e,n)&&t<=Math.max(e,n)}return/^-?\d+$/.test(n)&&Number(n)===t})}var kH=/^\s*([A-Za-z_][\w]*)\s*=\s*(.*?)\s*$/;function AH(e){let t=e.split(/\r?\n/),n={},r=0;for(;r<t.length;r++){let e=t[r];if(e.trim()===``)continue;let i=kH.exec(e);if(!i)break;n[i[1]]=i[2]}return{header:n,...pH(t.slice(r).map(e=>e.replace(/[,\s]+$/,``)).join(`
1347
- `))}}function jH(e){let t=[];for(let n of e.split(`|`)){let e=n.indexOf(`:`);if(e<=0||e===n.length-1)throw Error(`invalid table column "${n}"`);let r=n.slice(0,e).trim(),i=n.slice(e+1).trim();if(!/^[A-Za-z_][\w.-]*$/.test(r))throw Error(`invalid table column name "${r}"`);if(![`string`,`number`,`boolean`,`list`,`map`].includes(i))throw Error(`invalid table column type "${i}"`);if(t.some(e=>e.name===r))throw Error(`duplicate table column "${r}"`);t.push({name:r,type:i})}if(t.length===0)throw Error(`table must declare at least one column`);return t}var MH={game:{attributes:{schema:`string`,title:`string`,data_root:`string`,start_scene:`id`,default_schedule:`id`,save_slot:`string`,turn_limit:`integer`},children:`campaign.terrain_type.movetype.unit_type.unit.side.map.schedule.event.objectives.trait.weapon_special.dialogue.save.item.inventory.monster.status.loot.turn_clock.battle_move.type_matchup.evolution.table.object.story.role`.split(`.`)},campaign:{attributes:{id:`id`,name:`string`,title:`string`,description:`string`,start_scene:`id`,first_scenario:`id`},openChildren:!0},table:{attributes:{id:`id`,columns:`string`,list_delimiter:`string`,map_delimiter:`string`},children:[`row`]},row:{openAttributes:`string`},terrain_type:{attributes:{id:`id`,string:`string`,aliasof:`string`,mvt_alias:`string`,default_base:`string`,heals:`integer`,gives_income:`boolean`,map_code:`string`,base_tile:`string`,overlay_tile:`string`,defense:`number`,healing:`number`}},movetype:{attributes:{id:`id`,name:`string`},children:[`movement_costs`,`defense`,`resistance`]},movement_costs:{openAttributes:`number`},defense:{openAttributes:`number`},resistance:{openAttributes:`number`},unit_type:{attributes:{id:`string`,name:`string`,description:`string`,image:`string`,image_icon:`string`,profile:`string`,sound:`string`,hitpoints:`integer`,movement:`integer`,movement_type:`id`,movetype:`id`,experience:`integer`,level:`integer`,alignment:`id`,cost:`integer`,advances_to:`string`,race:`id`,usage:`id`},children:[`attack`,`trait`,`ability`]},unit:{attributes:{id:`id`,type:`string`,side:`string`,hp:`integer`,x:`integer`,y:`integer`}},attack:{attributes:{id:`id`,attacker:`string`,defender:`string`,target:`string`,amount:`integer`,weapon:`id`,name:`string`,sound:`string`,description:`string`,type:`id`,range:`id`,damage:`integer`,number:`integer`,strikes:`integer`,icon:`string`,specials:`string`}},side:{attributes:{id:`string`,controller:`id`,gold:`integer`,income:`integer`,income_base:`integer`,income_per_village:`integer`,leader:`id`,team:`integer`,recruit:`string`,color:`string`,team_name:`string`,user_team_name:`string`,share_vision:`string`,village_gold:`integer`,heal:`boolean`,fog:`boolean`,shroud:`boolean`,hidden:`boolean`,flag:`string`}},map:{attributes:{id:`id`,name:`string`,file:`string`,terrain:`string`},children:[`start`]},start:{attributes:{side:`string`,x:`integer`,y:`integer`}},schedule:{attributes:{id:`id`},children:[`time`]},time:{attributes:{id:`id`,name:`string`,lawful_bonus:`number`}},event:{attributes:{id:`id`,on:`id`,trigger:`id`,x:`coordinate`,y:`coordinate`,side:`string`,unit:`string`,once:`boolean`},children:`condition.filter.filter_condition.while.foreach.switch.command.say.dialogue.move.attack.spawn.kill.gold.endlevel.set_variable.if.else.message.teleport.end_turn.win.lose.hook.fire_event.store_unit.unstore_unit.recall.modify_unit.heal_unit.set_terrain.capture_village.clear_shroud.role`.split(`.`)},objectives:{attributes:{side:`string`,victory:`string`,defeat:`string`},children:[`victory`,`defeat`]},victory:{attributes:{side:`string`,condition:`id`,type:`string`,x:`integer`,y:`integer`,side_filter:`string`,turns:`integer`,gold:`integer`,hook:`string`,value:`integer`}},defeat:{attributes:{side:`string`,condition:`id`,type:`string`,x:`integer`,y:`integer`,side_filter:`string`,turns:`integer`,gold:`integer`,hook:`string`,value:`integer`}},condition:{attributes:{variable:`id`,equals:`string`,not_equals:`string`,in:`string`,not_in:`string`,less_than:`string`,greater_than:`string`,less_than_or_equal_to:`string`,greater_than_or_equal_to:`string`}},filter:{attributes:{side:`string`,type:`string`,not_type:`string`,unit:`string`,x:`integer`,y:`integer`,level:`integer`,alignment:`id`,can_recruit:`boolean`}},filter_condition:{children:[`variable`,`have_unit`,`predicate`]},variable:{attributes:{name:`id`,equals:`string`,not_equals:`string`,in:`string`,not_in:`string`,less_than:`string`,greater_than:`string`,less_than_or_equal_to:`string`,greater_than_or_equal_to:`string`}},have_unit:{attributes:{id:`string`,type:`string`,side:`string`,x:`integer`,y:`integer`}},predicate:{attributes:{name:`id`},openAttributes:`string`},command:{attributes:{name:`id`,target:`string`,value:`string`,amount:`integer`,x:`integer`,y:`integer`,hp:`integer`}},move:{attributes:{unit:`string`,target:`string`,x:`integer`,y:`integer`}},spawn:{attributes:{id:`string`,type:`string`,side:`string`,x:`integer`,y:`integer`,hp:`integer`}},kill:{attributes:{unit:`string`,target:`string`},openAttributes:`string`},gold:{attributes:{side:`string`,delta:`integer`,amount:`integer`}},endlevel:{attributes:{result:`id`,side:`string`,bonus:`integer`,carryover_percentage:`integer`,carryover_add:`boolean`,next_scenario:`id`}},set_variable:{attributes:{name:`id`,target:`id`,value:`string`}},if:{attributes:{test:`string`},children:[`condition`,`while`,`foreach`,`switch`,`if`,`else`,`command`,`message`,`move`,`attack`,`spawn`,`kill`,`gold`,`set_variable`,`win`,`lose`,`hook`]},else:{children:[`condition`,`while`,`foreach`,`switch`,`if`,`else`,`command`,`message`,`move`,`attack`,`spawn`,`kill`,`gold`,`set_variable`,`win`,`lose`,`hook`]},while:{attributes:{test:`string`,max_iterations:`integer`},children:[`condition`,`while`,`foreach`,`switch`,`if`,`else`,`message`,`move`,`attack`,`spawn`,`kill`,`gold`,`set_variable`,`win`,`lose`,`hook`]},foreach:{attributes:{variable:`id`,item:`id`,index:`id`},children:[`while`,`foreach`,`switch`,`if`,`else`,`message`,`move`,`attack`,`spawn`,`kill`,`gold`,`set_variable`,`win`,`lose`,`hook`]},switch:{attributes:{variable:`id`},children:[`case`,`default`]},case:{attributes:{equals:`string`},children:[`while`,`foreach`,`switch`,`if`,`else`,`message`,`move`,`attack`,`spawn`,`kill`,`gold`,`set_variable`,`win`,`lose`,`hook`]},default:{children:[`while`,`foreach`,`switch`,`if`,`else`,`message`,`move`,`attack`,`spawn`,`kill`,`gold`,`set_variable`,`win`,`lose`,`hook`]},message:{attributes:{speaker:`string`,text:`string`,value:`string`,portrait:`string`,side:`string`}},teleport:{attributes:{unit:`string`,target:`string`,x:`integer`,y:`integer`}},end_turn:{attributes:{}},win:{attributes:{side:`string`}},lose:{attributes:{side:`string`}},say:{attributes:{speaker:`id`,text:`string`}},dialogue:{attributes:{id:`id`,ref:`id`},children:[`say`,`choice`,`branch`,`message`]},choice:{attributes:{text:`string`,event:`id`,variable:`id`,equals:`string`},children:[`branch`]},branch:{attributes:{text:`string`},children:[`message`,`say`,`command`,`set_variable`,`move`,`attack`,`spawn`,`kill`,`gold`,`hook`]},trait:{attributes:{id:`id`,name:`string`},children:[`effect`]},ability:{attributes:{id:`id`,name:`string`},children:[`effect`]},weapon_special:{attributes:{id:`id`,name:`string`}},hook:{attributes:{name:`string`},openAttributes:`string`},fire_event:{attributes:{id:`id`,name:`string`}},store_unit:{attributes:{variable:`string`,name:`string`},children:[`filter`]},unstore_unit:{attributes:{variable:`string`,name:`string`}},recall:{attributes:{variable:`string`,id:`string`,unit:`string`,side:`string`,x:`integer`,y:`integer`}},modify_unit:{attributes:{hp:`integer`,moves:`integer`,type:`string`,side:`string`,alive:`boolean`},children:[`filter`,`set`]},set:{openAttributes:`string`},heal_unit:{attributes:{amount:`integer`,hp:`integer`,side:`string`,type:`string`,x:`integer`,y:`integer`},children:[`filter`]},set_terrain:{attributes:{terrain:`string`,x:`integer`,y:`integer`}},capture_village:{attributes:{side:`string`,x:`integer`,y:`integer`,name:`string`}},clear_shroud:{attributes:{side:`string`,x:`integer`,y:`integer`,radius:`integer`}},role:{attributes:{role:`string`,name:`string`,type:`string`,not_type:`string`,unit:`string`,side:`string`,x:`integer`,y:`integer`},children:[`filter`]},object:{attributes:{id:`id`,name:`string`,image:`string`,side:`string`,x:`integer`,y:`integer`},children:[`filter`]},story:{attributes:{text:`string`,value:`string`,title:`string`,image:`string`,music:`string`}},item:{attributes:{id:`id`,name:`string`,slot:`id`,stackable:`boolean`,weight:`number`},children:[`effect`]},inventory:{attributes:{unit:`string`,side:`string`,items:`string`}},monster:{attributes:{id:`string`,name:`string`,hp:`integer`,types:`string`,attack:`number`,defense:`number`,speed:`number`,accuracy:`number`,evasion:`number`,damage_min:`integer`,damage_max:`integer`,armor_min:`integer`,armor_max:`integer`,experience:`integer`,max_level:`integer`,image:`string`},children:[`ability`,`loot`]},status:{attributes:{id:`id`,name:`string`,duration:`integer`,tick:`string`,modifiers:`string`}},loot:{attributes:{item:`id`,chance:`number`,quantity:`integer`,weight:`number`}},turn_clock:{attributes:{id:`id`,tick:`number`,hunger:`number`}},ai:{attributes:{id:`id`,strategy:`id`,target:`id`,difficulty:`number`,scope:`id`,provider:`id`,algorithm:`id`,depth:`integer`,max_nodes:`integer`,player:`string`,moves:`string`,apply:`string`,terminal:`string`,evaluate:`string`},children:[`behavior`]},behavior:{attributes:{id:`id`,when:`string`,action:`string`,hook:`string`}},battle_move:{attributes:{id:`id`,type:`id`,target:`id`,power:`number`,cost:`number`}},type_matchup:{attributes:{attacker:`id`,defender:`id`,multiplier:`number`}},evolution:{attributes:{from:`id`,into:`id`,level:`integer`}},effect:{attributes:{apply_to:`id`,range:`id`,increase:`string`,increase_total:`string`,increase_damage:`string`,add:`string`,sub:`string`,multiply:`string`,divide:`string`,set:`string`}},save:{attributes:{version:`integer`,fields:`string`,migration:`string`}}};function NH(e,t=MH){let n=[],r=new Map,i=e=>{let t=e.attributes.id;t&&r.set(t,[...r.get(t)??[],e]),e.children.forEach(i)};e.forEach(i);let a=[],o=(e,i=!1)=>{let s=t[e.tag];if(!s){if(i){e.children.forEach(e=>o(e,!0));return}n.push({code:`MWL_UNKNOWN_TAG`,message:`unknown tag ${e.tag}`,location:e.location});return}for(let t of Object.keys(e.attributes))s.openAttributes||(!s.attributes||!(t in s.attributes))&&n.push({code:`MWL_UNKNOWN_ATTRIBUTE`,message:`unknown attribute ${t} on ${e.tag}`,location:e.location});for(let[t,i]of Object.entries(s.attributes??{})){let o=e.attributes[t];if(o!==void 0&&!IH(o,i)&&n.push({code:`MWL_VALUE`,message:`${t} must be ${i}`,location:e.location}),o!==void 0&&i===`ref`){let i=(r.get(o)??[]).filter(e=>{let n=s.refTargets?.[t];return!n||n===`*`||e.tag===n});i.length===0?n.push({code:`MWL_REF_MISSING`,message:`${t} references missing target ${o}`,location:e.location}):i.length>1?n.push({code:`MWL_REF_DUPLICATE`,message:`${t} references ambiguous target ${o}`,location:e.location}):s.acyclicRefs?.includes(t)&&a.push({from:e,to:i[0],name:t})}}if(s.openAttributes)for(let[t,r]of Object.entries(e.attributes))IH(r,s.openAttributes)||n.push({code:`MWL_VALUE`,message:`${t} must be ${s.openAttributes}`,location:e.location});for(let t of e.children)!s.openChildren&&s.children&&!s.children.includes(t.tag)&&n.push({code:`MWL_CHILD`,message:`${t.tag} is not allowed inside ${e.tag}`,location:t.location}),o(t,s.openChildren===!0)};e.forEach(e=>o(e)),PH(e,n);let s=new Set,c=new Set,l=(e,t)=>{if(s.has(e)){let r=t.indexOf(e);n.push({code:`MWL_REF_CYCLE`,message:`reference cycle through ${t.slice(r).map(e=>e.attributes.id??e.tag).join(` -> `)}`,location:e.location});return}if(!c.has(e)){s.add(e);for(let n of a.filter(t=>t.from===e))l(n.to,[...t,e]);s.delete(e),c.add(e)}};for(let e of a)l(e.from,[]);return n.sort((e,t)=>e.location.line-t.location.line||e.location.column-t.location.column)}function PH(e,t){let n=e=>{if(e.tag===`table`){let n;try{n=jH(e.attributes.columns??``)}catch(r){t.push({code:`MWL_TABLE`,message:String(r).replace(/^Error: /,``),location:e.location}),n=[]}let r=new Map(n.map(e=>[e.name,e]));for(let i of e.children.filter(e=>e.tag===`row`)){for(let e of Object.keys(i.attributes))r.has(e)||t.push({code:`MWL_TABLE`,message:`unknown table column ${e}`,location:i.location});for(let r of n){let n=i.attributes[r.name];if(n===void 0){t.push({code:`MWL_TABLE`,message:`missing table column ${r.name}`,location:i.location});continue}try{FH(n,r.type,r.name,e.attributes.list_delimiter,e.attributes.map_delimiter)}catch(e){t.push({code:`MWL_TABLE`,message:String(e).replace(/^Error: /,``),location:i.location})}}}}e.children.forEach(n)};e.forEach(n)}function FH(e,t,n,r=`;`,i=`=`){return Un(e,t,{column:n,listDelimiter:r,mapDelimiter:i,acceptYesNo:!0})}function IH(e,t){return t===`number`?Number.isFinite(Number(e)):t===`integer`?/^-?\d+$/.test(e):t===`boolean`?e===`true`||e===`false`||e===`yes`||e===`no`:t===`ref`?/^[A-Za-z_][\w.-]*$/.test(e):t===`coordinate`?/^-?\d+(?:\s*,\s*-?\d+|\s*-\s*-?\d+)*$/.test(e):t!==`id`||/^[A-Za-z_][\w.-]*$/.test(e)}function LH(e,t={}){return zH(zV(LV(e,t),t.file),t)}function RH(e,t={}){let n=[];for(let r of[...e].sort((e,t)=>e.file<t.file?-1:+(e.file>t.file))){let e=LV(r.source,{...t,file:r.file});n.push(...zV(e,r.file))}return zH(n,t)}function zH(e,t={}){let n=NH(e,t.schemas);if(n.length){let e=n[0];throw Error(`${e.location.file}:${e.location.line}:${e.location.column}: ${e.message}`)}let r=new Set,i=new Set,a=e=>{for(let[t,n]of Object.entries(e.attributes))if(BH(t))for(let e of HH(n).map(e=>e.trim()).filter(VH))r.add(UH(e));let t=e.gettext??[`name`,`text`,`title`];for(let n of t){let t=e.attributes[n];t!==void 0&&i.add(t)}let n={tag:e.tag,attributes:{...e.attributes},children:e.children.map(a),location:e.location};return e.gettext?{...n,gettext:[...e.gettext]}:n};return{schema:e.find(e=>e.tag===`game`)?.attributes.schema??`0.1`,roots:e.map(a),assets:[...r].sort(),messages:[...i].sort()}}function BH(e){return e===`file`||e===`image`||e===`image_icon`||e===`icon`||e===`profile`||e===`sound`||e.endsWith(`_sound`)||e.endsWith(`_image`)}function VH(e){return e.includes(`/`)||/\.(?:png|jpg|jpeg|gif|svg|webp|wav|ogg|mp3|flac|glb|gltf|vox|map|cfg)$/i.test(e)||e.startsWith(`data:`)}function HH(e){let t=[],n=0,r=0,i=0;for(let a=0;a<e.length;a+=1)e[a]===`(`?r+=1:e[a]===`)`&&r>0?--r:e[a]===`[`?i+=1:e[a]===`]`&&i>0?--i:e[a]===`,`&&r===0&&i===0&&(t.push(e.slice(n,a)),n=a+1);return t.push(e.slice(n)),t}function UH(e){let t=e.match(/~[A-Za-z][A-Za-z0-9_-]*(?:\(|$)/);return t?e.slice(0,t.index).trim():e}function WH(e,t={}){let n={};for(let t of e.messages)n[t]=t;return{locale:t.locale??`en`,direction:t.direction??`ltr`,messages:n}}function GH(e,t=`gameData`){return`export const ${t} = ${JSON.stringify(e,null,` `)} as const;\n`}function KH(e,t={}){let n=[{name:`game-data.ts`,content:GH(e,t.variable??`gameData`)},{name:`i18n.json`,content:`${JSON.stringify(WH(e),null,` `)}\n`},{name:`assets.json`,content:`${JSON.stringify({assets:e.assets},null,` `)}\n`},...Object.entries(t.artifacts??{}).sort(([e],[t])=>e<t?-1:+(e>t)).map(([e,t])=>({name:e,content:t}))];for(let e of n)t.onEmit?.(e);return n}function qH(e,t={},n={}){let r=KH(RH(e,t),n),i=KH(RH(e,t),n);if(r.length!==i.length||r.some((e,t)=>e.name!==i[t]?.name||e.content!==i[t]?.content))throw Error(`MWL generated artifacts are not deterministic`);return r}var JH=[`predicate`,`modifier`,`generator`,`command`,`ai`,`migration`];function YH(e){let t=e.indexOf(`:`);if(t<=0)return null;let n=e.slice(0,t),r=e.slice(t+1).trim();return!JH.includes(n)||!r?null:{type:n,name:r}}var XH=new Set([`hook`,`migration`]);function ZH(e){let t=new Map,n=e=>{for(let[t,n]of Object.entries(e.attributes))XH.has(t)&&r(n,e.location),e.tag===`hook`&&t===`name`&&r(n,e.location);e.children.forEach(n)},r=(e,n)=>{let r=YH(e);if(!r)return;let i=`${r.type}:${r.name}`;t.has(i)||t.set(i,{...r,location:n})};return e.roots.forEach(n),[...t.values()].sort((e,t)=>e.type.localeCompare(t.type)||e.name.localeCompare(t.name))}function QH(e,t){let n=new Set(t),r=[];for(let t of e){let e=`${t.type}:${t.name}`;n.has(e)||r.push({code:`MWL_HOOK`,message:`hook ${e} is not implemented`,location:t.location??{file:`<hook>`,line:0,column:0}})}return r}function $H(e){let t=[];t.push(`// Generated by mwl - do not edit.`),t.push(`import type { AiHook, CommandHook, GeneratorHook, MigrationHook, ModifierHook, PredicateHook } from '@datamoc/mw_games/mwl';`),t.push(``),t.push(`export interface MwlHooks {`);for(let n of e){let e=`${n.type[0].toUpperCase()}${n.type.slice(1)}Hook`;t.push(`\t'${n.type}:${n.name}': ${e};`)}return t.push(`}`),t.push(``),t.join(`
1348
- `)}function eU(e,t){let n=e.scenarios;if(n.length===0)throw Error(`campaign ${e.id} declares no scenarios`);let r=new Set(n.map(e=>e.id));if(r.size!==n.length)throw Error(`campaign ${e.id} declares a scenario twice`);let i=e.firstScenario||n[0].id;if(!r.has(i))throw Error(`campaign ${e.id} starts on an unknown scenario: ${i}`);return{start:i,levels:n.map(e=>({id:e.id,run:(n,r)=>{let i=t.run(e,n,r);return i.next===void 0?{...i,next:e.nextScenario??null}:i}}))}}var tU=rH,nU=iH,rU=aH,iU=oH,aU=sH;function oU(e){let t=nH(e.roots);return{campaigns:t.filter(e=>e.tag===`campaign`).map(e=>({id:tU(e,`id`),name:e.attributes.name,title:e.attributes.title,description:e.attributes.description,startScene:e.attributes.start_scene,firstScenario:e.attributes.first_scenario,scenarios:e.children.filter(e=>e.tag===`scenario`).map(e=>({id:tU(e,`id`),nextScenario:e.attributes.next_scenario||void 0}))})),items:t.filter(e=>e.tag===`item`).map(e=>({id:tU(e,`id`),name:tU(e,`name`),slot:e.attributes.slot,stackable:iU(e,`stackable`),weight:nU(e,`weight`),effects:e.children.filter(e=>e.tag===`effect`).map(cU)})),monsters:t.filter(e=>e.tag===`monster`).map(e=>({id:tU(e,`id`),name:e.attributes.name,hp:rU(e,`hp`,1),accuracy:nU(e,`accuracy`),evasion:nU(e,`evasion`),damage:lU(e,`damage_min`,`damage_max`),armor:lU(e,`armor_min`,`armor_max`),experience:rU(e,`experience`),maxLevel:rU(e,`max_level`),image:e.attributes.image,types:e.attributes.types?.split(`,`).map(e=>e.trim()).filter(Boolean),baseStats:[`attack`,`defense`,`speed`,`hp`].reduce((t,n)=>{let r=nU(e,n);return r!==void 0&&(t[n===`hp`?`maxHp`:n]=r),t},{})})),statuses:t.filter(e=>e.tag===`status`).map(e=>({id:tU(e,`id`),name:e.attributes.name,duration:rU(e,`duration`),tick:e.attributes.tick,modifiers:e.attributes.modifiers})),loot:t.filter(e=>e.tag===`loot`).map(e=>({item:tU(e,`item`),chance:nU(e,`chance`),quantity:rU(e,`quantity`),weight:nU(e,`weight`)})),turnClocks:t.filter(e=>e.tag===`turn_clock`).map(e=>({id:tU(e,`id`),tick:nU(e,`tick`),hunger:nU(e,`hunger`)})),ai:t.filter(e=>e.tag===`ai`).map(e=>({id:tU(e,`id`),strategy:e.attributes.strategy,target:e.attributes.target,difficulty:nU(e,`difficulty`),scope:aU(e.attributes.scope,[`actor`,`controller`]),provider:aU(e.attributes.provider,[`javascript`,`lua`]),algorithm:aU(e.attributes.algorithm,[`rules`,`alpha_beta`]),depth:rU(e,`depth`),maxNodes:rU(e,`max_nodes`),player:e.attributes.player,moves:e.attributes.moves,apply:e.attributes.apply,terminal:e.attributes.terminal,evaluate:e.attributes.evaluate,behaviors:e.children.filter(e=>e.tag===`behavior`).map(e=>({id:tU(e,`id`),when:e.attributes.when,action:e.attributes.action,hook:e.attributes.hook}))})),moves:t.filter(e=>e.tag===`battle_move`).map(e=>({id:tU(e,`id`),type:tU(e,`type`),target:tU(e,`target`),power:nU(e,`power`),cost:nU(e,`cost`)})),typeMatchups:t.filter(e=>e.tag===`type_matchup`).map(e=>({attacker:tU(e,`attacker`),defender:tU(e,`defender`),multiplier:nU(e,`multiplier`)??1})),evolutions:t.filter(e=>e.tag===`evolution`).map(e=>({from:tU(e,`from`),into:tU(e,`into`),level:rU(e,`level`,1)})),tables:t.filter(e=>e.tag===`table`).map(sU)}}function sU(e){let t=jH(tU(e,`columns`));return{id:tU(e,`id`),columns:t,rows:e.children.filter(e=>e.tag===`row`).map(n=>{let r={};for(let i of t){let t=n.attributes[i.name];t!==void 0&&(r[i.name]=FH(t,i.type,i.name,e.attributes.list_delimiter,e.attributes.map_delimiter))}return r})}}function cU(e){let t=[`add`,`sub`,`multiply`,`divide`,`set`,`increase`,`increase_total`,`increase_damage`].find(t=>e.attributes[t]!==void 0);return{applyTo:tU(e,`apply_to`),operation:t,value:t?e.attributes[t]:void 0,range:e.attributes.range}}function lU(e,t,n){let r=nU(e,t),i=nU(e,n);return r===void 0||i===void 0?void 0:[r,i]}function uU(e,t={}){return{id:e.id,stackable:e.stackable,weight:e.weight,slot:e.slot,modifiers:e.effects.map(e=>pU(e,t))}}function dU(e,t=1){return{id:e.id,quantity:t,stackable:e.stackable,weight:e.weight}}function fU(e,t,n={}){return $I(e,t.map(e=>pU(e,n)))}function pU(e,t={}){let n=e.operation;if(n!==`add`&&n!==`sub`&&n!==`multiply`&&n!==`divide`&&n!==`set`)throw Error(`MWL effect operation "${n??``}" is not a StatBlock modifier`);let r=e.value;if(r===void 0)throw Error(`MWL effect has no value`);let i=eH(r,t);return{stat:e.applyTo,op:n===`sub`?`add`:n===`divide`?`multiply`:n,value:n===`sub`?-i:n===`divide`?1/i:i}}function mU(e,t={}){let n=[],r=new Map,i=nH(e.roots);for(let e of i){let i=e.attributes.id;if(i){let t=`${e.tag}:${i}`,a=r.get(t);a?n.push(hU(`MWL_DUPLICATE_ID`,`duplicate ${e.tag} id "${i}"`,e.location??a.location)):r.set(t,e)}if(e.tag===`item`&&t.slots&&e.attributes.slot&&!t.slots.includes(e.attributes.slot)&&n.push(hU(`MWL_UNKNOWN_SLOT`,`unknown equipment slot "${e.attributes.slot}"`,e.location)),e.tag===`effect`){let t=[`add`,`sub`,`multiply`,`divide`,`set`,`increase`,`increase_total`,`increase_damage`].filter(t=>e.attributes[t]!==void 0);(!e.attributes.apply_to||t.length!==1)&&n.push(hU(`MWL_INCOMPLETE_EFFECT`,`an effect needs apply_to and exactly one operation`,e.location))}}let a=ZH(e),o=new Set(t.hooks??[]);for(let e of i){let t=e.attributes.hook??(e.tag===`hook`?e.attributes.name:void 0);t!==void 0&&!YH(t)&&n.push(hU(`MWL_INVALID_HOOK`,`invalid hook reference "${t}"`,e.location))}if(t.hooks)for(let e of a)o.has(`${e.type}:${e.name}`)||n.push(hU(`MWL_UNKNOWN_HOOK`,`hook ${e.type}:${e.name} is not declared by the game`,e.location));return n}function hU(e,t,n){return{code:e,message:t,location:n??{file:`<mwl>`,line:1,column:1}}}function gU(e,t={}){return mU({schema:`0.1`,roots:e,assets:[],messages:[]},t)}function _U(e,t={}){try{let n=RH(e,t),r=vU(n),i=[];for(let e of r.opaqueTags)i.push({severity:`warning`,code:`opaque-tag`,message:`ignored opaque tag: ${e}`});for(let e of r.danglingReferences)i.push({severity:`error`,code:`dangling-reference`,message:`dangling content reference: ${e}`});return{game:n,resources:[...n.assets],dependencies:[...r.references],ignored:[...r.opaqueTags],diagnostics:i}}catch(e){return{resources:[],dependencies:[],ignored:[],diagnostics:[{severity:`error`,code:`compile`,message:String(e)}]}}}function vU(e){let t=nH(e.roots),n={},r=new Set;for(let e of t)n[e.tag]=(n[e.tag]??0)+1,e.attributes.id&&r.add(e.attributes.id);let i=new Set(Object.keys(MH)),a=t.filter(e=>!i.has(e.tag)).map(e=>e.tag).filter((e,t,n)=>n.indexOf(e)===t).sort(),o=new Set;for(let e of t)for(let[t,n]of Object.entries(e.attributes))if(/^(?:ability|item|terrain|unit|unit_type|weapon)(?:_id)?$/.test(t))for(let e of n.split(`,`).map(e=>e.trim()).filter(Boolean))o.add(e);return{tags:Object.fromEntries(Object.entries(n).sort(([e],[t])=>e.localeCompare(t))),opaqueTags:a,references:[...o].sort(),danglingReferences:[...o].filter(e=>!r.has(e)).sort()}}function yU(e,t){let n={},r=[];for(let[i,a]of Object.entries(t)){let t=a.source??i,o=e.attributes[t];if(o===void 0){a.required?r.push(SU(`MWL_REQUIRED_FIELD`,`missing required attribute "${t}"`,e)):a.default!==void 0&&(n[i]=a.default);continue}let s=xU(o,a.type);s===void 0?r.push(SU(`MWL_FIELD_TYPE`,`invalid ${a.type} attribute "${t}": "${o}"`,e)):n[i]=s}return{value:n,diagnostics:r}}function bU(e,t,n){let r=[],i=[];for(let a of e.children){if(a.tag!==t)continue;let e=n(a);r.push(e.value),i.push(...e.diagnostics)}return{value:r,diagnostics:i}}function xU(e,t){if(t===`string`)return e;if(t===`id`)return/^[A-Za-z_][\w.-]*$/.test(e)?e:void 0;if(t===`number`)return Number.isFinite(Number(e))?Number(e):void 0;if(t===`integer`)return/^-?\d+$/.test(e)?Number(e):void 0;if(t===`boolean`)return e===`true`||e===`yes`?!0:e===`false`||e===`no`?!1:void 0;let n=e.split(`,`).map(e=>e.trim()).filter(Boolean);return t===`id-list`?n.every(e=>/^[A-Za-z_][\w.-]*$/.test(e))?n:void 0:n.every(e=>Number.isFinite(Number(e)))?n.map(Number):void 0}function SU(e,t,n){return{code:e,message:t,location:n.location??{file:`<mwl>`,line:1,column:1}}}function CU(){return{evaluate(e,t={}){let n={};for(let[e,r]of Object.entries(t)){if(typeof r!=`number`)throw Error(`MWL expression context value must be numeric: ${e}`);n[e]=r}return eH(e,n)},execute(){throw Error(`the expression ScriptHost cannot execute statements`)},call(){throw Error(`the expression ScriptHost cannot call functions`)},dispose(){}}}var wU=l({MWL_DEFAULT_CARRYOVER_PERCENTAGE:()=>80,MwlRuntime:()=>mH,MwlSyntaxError:()=>FV,campaignChain:()=>eU,carryoverIntoScenario:()=>lH,coerceTableValue:()=>FH,collectHookReferences:()=>ZH,compile:()=>LH,compileAndEmitSources:()=>qH,compileNodes:()=>zH,compileSources:()=>RH,composeEffects:()=>fU,contentCatalog:()=>oU,contentReport:()=>vU,createExpressionScriptHost:()=>CU,createWorld:()=>fH,decodeSave:()=>KV,effectToModifier:()=>pU,emitArtifacts:()=>KH,emitHooksDeclaration:()=>$H,emitModule:()=>GH,encodeSave:()=>GV,endLevelCarryover:()=>cH,evaluateCondition:()=>YV,evaluateExpression:()=>eH,execute:()=>hH,extractCatalog:()=>WH,hookTypes:()=>JH,inventoryItem:()=>dU,isGettext:()=>VV,itemDefinition:()=>uU,loadContent:()=>_U,parse:()=>zV,parseExpression:()=>$V,parseHookReference:()=>YH,parseMapFile:()=>AH,parseTableColumns:()=>jH,parseTerrain:()=>pH,parseValue:()=>BV,preprocess:()=>LV,readAttributes:()=>yU,readChildren:()=>bU,schema01:()=>MH,sideVisionGroups:()=>_H,validate:()=>NH,validateCatalog:()=>mU,validateCatalogNodes:()=>gU,validateHookReferences:()=>QH,validateWorld:()=>qV});function TU(e,t,n,r){let i=0,a=0,o=1;for(let s of t)s.id!==e.id&&r(s.x,s.y)&&(o++,s.side===e.side?i+=n(s.id):a+=n(s.id));return{own:n(e.id),allies:i,enemies:a,seen:o}}function EU(e,t,n,r){let i=0,a=0,o=0;for(let s of t)r(s.x,s.y)&&(o++,s.side===e?i+=n(s.id):a+=n(s.id));return{own:0,allies:i,enemies:a,seen:o}}function DU(e,t){return e.own*t.own+e.allies*t.allies+e.enemies*t.enemies}var OU=class e{constructor(e={}){this.values={};for(let[t,n]of Object.entries(e))n!==void 0&&(this.values[t]=n)}has(e){return this.values[e]!==void 0}get(e){return this.values[e]}set(e,t){this.values[e]=t}number(e,t=0){let n=this.values[e];return typeof n==`number`&&Number.isFinite(n)?n:typeof n==`boolean`?+!!n:t}flag(e,t=!1){let n=this.values[e];return typeof n==`boolean`?n:t}list(e){let t=this.values[e];return Array.isArray(t)?t:typeof t==`string`?[t]:[]}names(){return Object.keys(this.values)}with(t){let n=new e(this.values);for(let[e,r]of Object.entries(t))r!==void 0&&n.set(e,r);return n}toJSON(){return{...this.values}}static fromJSON(t){return new e(t)}},kU=class{constructor(e=[],t={}){this.levels=new Map,this.base=new OU(t);for(let t of e){if(this.levels.has(t.id))throw Error(`duplicate difficulty level: ${t.id}`);this.levels.set(t.id,t)}}get ids(){return[...this.levels.keys()]}get(e){return this.levels.get(e)}aspectsFor(e){let t=this.levels.get(e);if(!t)throw Error(`unknown difficulty level: ${e}`);return this.base.with(t.aspects??{})}},AU=class{constructor(){this.byUnit=new Map}set(e){this.byUnit.set(e.unit,{...e})}clear(e){this.byUnit.delete(e)}get(e){return this.byUnit.get(e)}all(){return[...this.byUnit.values()]}get isEmpty(){return this.byUnit.size===0}},jU=class{constructor(e,t=null){this.order=e,this.fallback=t}get length(){return this.order.length}at(e){if(this.order.length===0)return this.fallback;let t=(e%this.order.length+this.order.length)%this.order.length;return this.order[t]}next(e){if(this.order.length===0)return this.fallback;if(e===null)return this.order[0];let t=this.order.indexOf(e);return this.at(t<0?0:t+1)}},MU=class{constructor(e){this.stages=e.stages}decide(e,t){if(e.length===0)return null;for(let n of this.stages){if(n.when&&!n.when(t))continue;let r=n.weigh??NU,i=null;for(let a of e){let e=r(a,t);(!i||e>i.score)&&(i={candidate:a,stage:n.id,score:e})}return i}return null}};function NU(e,t){let n=0;for(let[r,i]of Object.entries(e.factors??{}))r!==`distance`&&(n+=i*t.aspects.number(r,1));let r=e.factors?.distance;return r!==void 0&&(n+=PU(r,t.aspects.number(`keep_away`,0))),n}function PU(e,t){return!(t>0)||e>=t?0:-(t-e)}function FU(e){return e?Math.max(0,e.priority??1):0}var IU=l({AIBudgetExceededError:()=>VU,AICancelledError:()=>BU,Aspects:()=>OU,Difficulty:()=>kU,Goals:()=>AU,HeuristicAI:()=>MU,JavaScriptAI:()=>zU,RecruitmentPattern:()=>jU,alphaBetaSearch:()=>Az,defaultWeigh:()=>NU,goalScore:()=>FU,keepAwayScore:()=>PU,personalScoreView:()=>TU,scoreWith:()=>DU,sideScoreView:()=>EU}),LU=1e4,RU=16,zU=class{constructor(e={}){this.agents=new Map,this.states=new Map,this.options=e,KU(e.maxSteps??LU,`maxSteps`),qU(e.maxMilliseconds??RU,`maxMilliseconds`)}register(e){if(!/^[A-Za-z_][A-Za-z0-9_.-]*$/.test(e.id))throw Error(`invalid AI agent id: ${e.id}`);if(this.agents.has(e.id))throw Error(`AI agent already registered: ${e.id}`);if(!e.behaviors.length)throw Error(`AI agent has no behaviours: ${e.id}`);let t=new Set;for(let n of e.behaviors){if(!n.id||t.has(n.id))throw Error(`duplicate AI behaviour: ${n.id}`);t.add(n.id)}this.agents.set(e.id,e),this.states.set(e.id,{})}decide(e,t){let n=this.agents.get(e);if(!n)throw Error(`unknown AI agent: ${e}`);let r=UU(t.state??this.states.get(e)??{}),i=t.maxSteps??this.options.maxSteps??LU,a=t.maxMilliseconds??this.options.maxMilliseconds??RU;KU(i,`maxSteps`),qU(a,`maxMilliseconds`);let o=0,s=JU(),c=[],l=GU(t.seed??this.options.seed??7173991),u=()=>{if(o++,t.signal?.aborted)throw new BU;if(o>i||JU()-s>a)throw new VU},d={perception:WU(t.perception),state:r,random:()=>(u(),l()),checkpoint:u,emit(e,t){if(!e)throw Error(`AI event name must not be empty`);u(),c.push(t===void 0?{name:e}:{name:e,payload:WU(t)})}},f=null,p,m=`idle`;try{for(let e of n.behaviors)if(u(),!(e.when&&!e.when(d))){p=e.id,f=HU(e.decide(d)),m=f?`action`:`idle`;break}}catch(e){if(e instanceof BU)m=`cancelled`;else if(e instanceof VU)m=`budget-exceeded`;else throw e}let h={agent:e,action:f,state:UU(r),behavior:p,status:m,steps:o,events:c};return this.states.set(e,UU(r)),this.options.onDecision?.(h),h}search(e,t,n){return Az(e,t,n)}exportState(){return{version:1,agents:Object.fromEntries([...this.states].map(([e,t])=>[e,UU(t)]))}}importState(e){if(e.version!==1)throw Error(`unsupported AI state version: ${e.version}`);for(let[t,n]of Object.entries(e.agents)){if(!this.agents.has(t))throw Error(`AI state names unknown agent: ${t}`);this.states.set(t,UU(n))}}dispose(){this.agents.clear(),this.states.clear()}},BU=class extends Error{constructor(){super(`AI decision cancelled`),this.name=`AICancelledError`}},VU=class extends Error{constructor(){super(`AI decision budget exceeded`),this.name=`AIBudgetExceededError`}};function HU(e){if(e===null)return null;if(!e||typeof e!=`object`||Array.isArray(e)||typeof e.type!=`string`||!e.type)throw Error(`AI action must be an object with a non-empty string type`);return WU(e)}function UU(e){return WU(e)}function WU(e){return typeof e!=`object`||!e?e:Array.isArray(e)?e.map(WU):Object.fromEntries(Object.entries(e).map(([e,t])=>[e,WU(t)]))}function GU(e){if(!Number.isInteger(e))throw TypeError(`AI seed must be an integer`);let t=e>>>0;return()=>(t=Math.imul(t,1664525)+1013904223>>>0,t/4294967296)}function KU(e,t){if(!Number.isInteger(e)||e<1)throw RangeError(`${t} must be a positive integer`)}function qU(e,t){if(!Number.isFinite(e)||e<0)throw RangeError(`${t} must be a non-negative number`)}function JU(){return typeof performance>`u`?Date.now():performance.now()}return wi(),W(),Xa(),Object.defineProperty(e,"AI",{enumerable:!0,get:function(){return IU}}),e.Achievements=$t,e.ActionJournal=Zt,e.ActorAnimator=dj,Object.defineProperty(e,"Actors",{enumerable:!0,get:function(){return XL}}),e.AnimatedSprite=mA,e.Animation=fA,Object.defineProperty(e,"Audio",{enumerable:!0,get:function(){return EV}}),e.BLOB_SHAPES=pj,e.Bar=qP,Object.defineProperty(e,"Battle",{enumerable:!0,get:function(){return oz}}),e.BitmapLabel=EM,e.Blob=En,Object.defineProperty(e,"Board",{enumerable:!0,get:function(){return aV}}),e.Button=KP,e.COLOR_BLINDNESS_MATRICES=WA,e.Camera=LA,e.Checkbox=wP,e.Collection=Kt,e.ColorTransformBatcher=kk,e.Container2D=G,e.DataTable=kP,e.DialogueStage=hF,e.Dropdown=DP,e.EMPTY=YA,e.Easing=Dn,e.EntityRegistry=Pn,e.FLOATING_TEXT_STACK_GAP=$P,e.FeedbackClient=nn,e.FloatingText=QP,e.FloatingTextStack=rF,e.Game=yk,e.Generator=w,e.Gradient=Nj,e.Grid=LP,e.HALO_ANIMATION=oj,e.Halo=sj,e.HelpScreen=oF,e.HookRegistry=x,Object.defineProperty(e,"I18n",{enumerable:!0,get:function(){return HN}}),e.IconGrid=IM,Object.defineProperty(e,"Input",{enumerable:!0,get:function(){return ve}}),e.Label=Yj,e.LayeredSprite=nj,e.LightningArc=ij,e.ListView=FM,e.LoadQueue=Nn,e.LoadingScreen=cF,e.LockstepClient=Rt,e.Logger=y,e.MersenneTwister=he,e.MessageBox=_P,e.Minimap=JA,Object.defineProperty(e,"Mwl",{enumerable:!0,get:function(){return wU}}),e.NO_COLOR_ADD=Rk,e.NewsClient=Ut,e.NewsSeenTracker=Gt,e.NinePatch=OM,e.Node2D=Oj,e.ParticleEmitter=lj,e.Player=Jt,e.PlayerInput=bt,e.PlayerStats=Vt,e.PresentationQueue=Fn,e.Projectile=rj,e.RENDERING_DECISIONS=Tj,Object.defineProperty(e,"Random",{enumerable:!0,get:function(){return S}}),e.RandomStreams=_e,e.ReactionTable=en,e.RebindScreen=GP,e.Recorder=qt,e.Rectangle2D=V,e.Registry=g,Object.defineProperty(e,"Resources",{enumerable:!0,get:function(){return PA}}),e.RichLabel=cM,Object.defineProperty(e,"Roguelike",{enumerable:!0,get:function(){return QI}}),Object.defineProperty(e,"Rpg",{enumerable:!0,get:function(){return VR}}),e.RunHistory=Bt,e.SaveSyncClient=It,e.SaveSystem=Nt,e.Scene=m,e.Scene2D=bk,e.SceneComponentHost=_,e.SceneStack=h,e.ScreenEffects=uj,e.ScreenReader=AM,e.ScrollBox=PP,e.Session=tn,e.Shape2D=kj,e.Signal=p,Object.defineProperty(e,"Simulation",{enumerable:!0,get:function(){return PV}}),e.Skins=UP,e.Slider=CP,e.Spawner=rn,e.Spinner=EP,e.Sprite2D=jj,e.SpriteAttachment=aj,e.SpriteSheet=IA,e.StageScript=gF,e.StateRegistry=Pt,e.StatsScreen=sF,e.StatusVisuals=fj,e.StoryScreen=EF,e.StorySequence=TF,e.SyncGuard=Bn,e.TabbedList=LM,e.TelemetryClient=Ht,e.Text2D=Aj,e.TextModel=OP,e.Texture2D=U,e.TileMap=tj,e.TiledSprite=Mj,e.TintedSprite=zk,e.Toast=iF,e.Tooltip=aF,e.TreeView=MP,e.Tweener=On,e.UndoHistory=kn,e.VerticalLabel=bP,e.Viewport=HA,e.Window=MM,e.WindowStack=NM,Object.defineProperty(e,"World",{enumerable:!0,get:function(){return iR}}),e.advanceReveal=Kj,e.anchorAlign=FP,e.applyImageModifiers=nA,e.applyTextureModifiers=sA,e.autotileFrames=vj,e.bitmapLabelStyle=DM,e.blendMatrix=Qk,e.blendPixels=uA,e.blobIndex=_j,e.channelScaleMatrix=Zk,e.channelSwapMatrix=$k,e.checkNoControlCharacters=Dt,e.checkSize=Et,e.colorShiftMatrix=Xk,e.completeReveal=qj,e.contrastRatio=fF,e.createCamera=VA,e.createColorBlindnessFilter=GA,e.croppedTexture=rA,e.defaultTheme=zj,e.deserializeReplay=Xt,e.detectWebGpu=Dj,e.escapeHtml=yM,e.floatingTextAgeAtLeast=ZP,e.floatingTextAlpha=YP,e.floatingTextRise=XP,e.floatingTextStackLifePenalty=eF,e.floatingTextStackLift=tF,e.floatingTextStackMoves=nF,e.hexDistance=ln,e.hexLine=dn,e.hexNeighbors=cn,e.hexRange=fn,e.hexRotate=bj,e.hexToPixel=pn,e.highContrastTheme=Bj,e.imageModifier=Yk,e.importTwee=vF,e.inspectGraphicsCapabilities=Ej,e.layoutMarkupLines=_M,e.layoutVertical=yP,e.loadTiledMap=Rj,e.markupAccessibilityText=gM,e.markupToHtml=hM,e.maskPixels=lA,e.matchTerrainRule=Sj,e.meetsContrast=pF,e.messageBoxPresenter=lF,e.minimapCellCenter=qA,e.motionDuration=wn,e.newlyRevealed=KA,e.packColorAdd=Fk,e.packTintAdd=Ik,e.paletteRangeMapping=Wk,e.parseCSV=Vn,e.parseColorPairs=aA,e.parseImagePath=Jk,e.parseMarkdown=aM,e.parseMarkup=pM,e.parsePaletteLists=oA,e.pixelToHex=mn,e.prefersReducedMotion=bn,e.recolorTexture=qk,e.rectOf=FA,e.reducedMotion=xn,e.registerColorTransform=Pk,e.relativeLuminance=dF,e.remapPixels=Gk,e.resolveAnchor=IP,e.resolveTerrainGraphics=Cj,e.revealComplete=Jj,e.rotatePixels=dA,e.sanitizeInboundText=Ot,e.scramble=xt,e.screenReader=jM,e.scrollOffset=NP,e.serializeReplay=Yt,e.setReducedMotion=Sn,e.setTheme=Hj,e.sliceSpans=sM,e.sliderFraction=xP,e.sliderValueAt=SP,e.snapZoom=BA,e.spinValue=TP,e.splitScreenHalves=UA,e.squareRotate=yj,e.startReveal=Gj,e.stateChecksum=zn,e.stripMarkdown=oM,e.stripMarkup=mM,e.theme=Q,e.themeChanged=$,e.tileFrame=QA,e.tileFrameIndex=ej,e.tileFrameSheet=$A,e.unscramble=St,e.validateSchema=At,e.version=f,e.watchReducedMotion=Cn,e.weightedFlood=An,e.withTextureCanvas=Kk,e})({});
1343
+ `))t.startsWith(`::`)?(i(),n=OF(t),r=[]):n!==null&&r.push(t);return i(),t}function OF(e){let t=e.slice(2).trim(),n=t.search(/[[{]/),r=(n===-1?t:t.slice(0,n)).trim();if(!r)throw Error(`a twee passage header needs a name, got "${e}"`);return r}function kF(e){let t;try{t=JSON.parse(e.trim())}catch{throw Error(`StoryData must be JSON - check the braces`)}if(typeof t!=`object`||!t||Array.isArray(t))throw Error(`StoryData must be a JSON object`);let n=t.start;if(n!==void 0&&typeof n!=`string`)throw Error(`StoryData "start" must be a passage name`);return n}function AF(e,t){let n=[],r=[];for(let i of t.split(`
1344
+ `)){let t=jF(i,r,e).replace(/\s+/g,` `).trim();t!==``&&n.push(t)}if(r.length===0)return n.map(e=>({say:e}));let i=n.pop()??``;return[...n.map(e=>({say:e})),{ask:i,choices:r}]}function jF(e,t,n){let r=``,i=e;for(;;){let a=i.indexOf(`[[`);if(a===-1)return r+i;let o=i.indexOf(`]]`,a);if(o===-1)throw Error(`passage "${n}" has a "[[" with no closing "]]" in "${e.trim()}"`);r+=i.slice(0,a),t.push(MF(i.slice(a+2,o),n)),i=i.slice(o+2)}}function MF(e,t){if(e.includes(`[`)||e.includes(`]`))throw Error(`passage "${t}" links with a setter ("${e.trim()}") - story-format macros are not imported, so the link is refused rather than half-read`);let n=e.indexOf(`->`);if(n!==-1)return{text:e.slice(0,n).trim(),goto:e.slice(n+2).trim()};let r=e.indexOf(`<-`);if(r!==-1)return{text:e.slice(r+2).trim(),goto:e.slice(0,r).trim()};let i=e.trim();return{text:i,goto:i}}var NF=class{constructor(e){this.onChange=new p,this.onMusic=new p,this.index=0,this.beats=e}get length(){return this.beats.length}get position(){return this.index}get current(){return this.beats[this.index]??null}get done(){return this.beats.length===0||this.index>=this.beats.length-1}get music(){return this.current?.music??null}goTo(e){let t=Math.max(0,Math.min(this.beats.length-1,e));this.index=t,this.report()}advance(){return!this.done&&(this.goTo(this.index+1),!0)}back(){return this.index!==0&&(this.goTo(this.index-1),!0)}skip(){this.goTo(this.beats.length-1)}restart(){this.goTo(0)}report(){let e=this.current;e&&this.onChange.dispatch(e),this.onMusic.dispatch(this.music)}},PF=class extends G{constructor(e){super(),this.backdrop=new $s(U.EMPTY),this.handleAdvance=()=>{this.advance()},this.handleBeat=e=>{this.applyBeat(e)},this.sequence=e.sequence,this.textureFor=e.textureFor??(()=>null),this.playMusic=e.playMusic??(()=>{}),this.width_=e.width,this.height_=e.height,this.titleLabel=new Zj({text:``,color:Q().color.textHighlight}),this.textLabel=new Zj({text:``,wrapWidth:this.width_*.8}),this.addChild(this.backdrop),this.addChild(this.titleLabel),this.addChild(this.textLabel),this.eventMode=`static`,this.on(`pointertap`,this.handleAdvance),this.sequence.onChange.add(this.handleBeat),this.sequence.onMusic.add(this.playMusic),this.applyBeat(this.sequence.current)}get current(){return this.sequence.current}advance(){return this.sequence.advance()}skip(){this.sequence.skip()}resize(e,t){this.width_=e,this.height_=t,this.applyBeat(this.current)}applyBeat(e){if(!e){this.backdrop.visible=!1;return}let t=e.image?this.textureFor(e.image):null;if(this.backdrop.visible=t!==null,t){this.backdrop.texture=t;let e=Math.max(this.width_/t.width,this.height_/t.height);this.backdrop.scale.set(e),this.backdrop.x=(this.width_-t.width*e)/2,this.backdrop.y=(this.height_-t.height*e)/2}this.titleLabel.setText(e.title??``),this.titleLabel.x=this.width_*.1,this.titleLabel.y=this.height_*.12,this.textLabel.setText(e.text),this.textLabel.x=this.width_*.1,this.textLabel.y=this.height_*.24,this.textLabel.style.wordWrapWidth=this.width_*.8}destroy(e){this.sequence.onChange.remove(this.handleBeat),this.sequence.onMusic.remove(this.playMusic),super.destroy(e)}},FF=[[0,-1],[1,0],[0,1],[-1,0]],IF=[[0,-1],[1,-1],[1,0],[1,1],[0,1],[-1,1],[-1,0],[-1,-1]],LF=[[1,0],[1,-1],[0,-1],[-1,-1],[-1,0],[0,1]],RF=[[1,1],[1,0],[0,-1],[-1,0],[-1,1],[0,1]];function zF(e){return e===4?FF:IF}var BF={passable:!1,transparent:!1},VF={passable:!0,transparent:!0},HF=class e{constructor(e,t,n,r=0,i=`square`,a){if(this.rooms=[],this.width=e,this.shape=i,this.height=t,a!==void 0&&(!Number.isFinite(a)||a<0))throw Error(`viewDistance must be a finite non-negative number`);this.viewDistance=a,this.kinds=n,this.terrain=new Uint8Array(e*t).fill(r)}get cellCount(){return this.width*this.height}index(e,t){return t*this.width+e}xOf(e){return e%this.width}yOf(e){return Math.floor(e/this.width)}inside(e,t){return e>=0&&t>=0&&e<this.width&&t<this.height}neighbors(e,t,n=8){return this.shape===`hex`?cn(e,t):zF(n).map(([n,r])=>({x:e+n,y:t+r}))}forEachNeighbor(e,t,n,r){let i=this.shape===`hex`?e&1?RF:LF:zF(n);for(let[n,a]of i)r(e+n,t+a)}insideWithBorder(e,t){return e>0&&t>0&&e<this.width-1&&t<this.height-1}get(e,t){return this.inside(e,t)?this.terrain[this.index(e,t)]:0}set(e,t,n){this.inside(e,t)&&(this.terrain[this.index(e,t)]=n)}kindAt(e,t){return this.kinds[this.get(e,t)]??BF}passable(e,t){return this.inside(e,t)&&this.kindAt(e,t).passable}transparent(e,t){return this.inside(e,t)&&this.kindAt(e,t).transparent}fillRect(e,t){for(let n=e.top;n<=e.bottom;n++)for(let r=e.left;r<=e.right;r++)this.set(r,n,t)}passableCells(){let e=[];for(let t=0;t<this.terrain.length;t++)this.kinds[this.terrain[t]]?.passable&&e.push(t);return e}toJSON(){return{width:this.width,height:this.height,shape:this.shape,terrain:[...this.terrain],rooms:this.rooms.map(e=>({...e})),...this.viewDistance===void 0?{}:{viewDistance:this.viewDistance}}}static fromJSON(t,n){let r=new e(n.width,n.height,t,0,n.shape,n.viewDistance);return r.terrain.set(n.terrain.slice(0,r.terrain.length)),r.rooms=n.rooms.map(e=>({...e})),r}};function UF(e){return{x:Math.floor((e.left+e.right)/2),y:Math.floor((e.top+e.bottom)/2)}}function WF(e,t,n=0){return!(e.right+n<t.left||t.right+n<e.left||e.bottom+n<t.top||t.bottom+n<e.top)}var GF={id:`hall`,paint:(e,t,n)=>e.fillRect(t,n)};function KF(e){return Math.min(e.right-e.left+1,e.bottom-e.top+1)}function qF(e){return Math.max(e.right-e.left+1,e.bottom-e.top+1)}function JF(e,t){let n=KF(t),r=qF(t);return e.filter(e=>n>=(e.minSize??0)&&r<=(e.maxSize??1/0))}function YF(e,t){let n=JF(e,t);if(n.length===0)return null;let r=ce(n.map(e=>e.weight??1));return r===null?null:n[r]}var XF=[{passable:!1,transparent:!1},{passable:!0,transparent:!0}];function ZF(e){let{width:t,height:n,rooms:r=14,minRoomSize:i=4,maxRoomSize:a=10,extraCorridors:o=3,wall:s=0,floor:c=1,kinds:l=[],hooks:u,builders:d}=e,f=new HF(t,n,[...XF,...l],s),p=[],m=[],h=[],g=0;for(let e=0;e<r*6&&p.length<r;e++){let e=ie(i,a),r=ie(i,a),o=k(1,Math.max(2,t-e-1)),s=k(1,Math.max(2,n-r-1)),l={left:o,top:s,right:o+e-1,bottom:s+r-1};if(l.right>=t-1||l.bottom>=n-1){g++;continue}if(p.some(e=>WF(l,e,2))){g++;continue}p.push(l);let m=(d?.length?YF(d,l):null)??GF;m.paint(f,l,c),h.push(m.id),u?.onRoomPlaced?.(l,p.length-1)}for(let e=1;e<p.length;e++){$F(f,UF(p[e-1]),UF(p[e]),c);let t={a:e-1,b:e,extra:!1};m.push(t),u?.onCorridorCarved?.(t,p[e-1],p[e])}for(let e=0;e<o&&p.length>2;e++){let e=k(p.length),t=k(p.length);if(e!==t){$F(f,UF(p[e]),UF(p[t]),c);let n={a:e,b:t,extra:!0};m.push(n),u?.onCorridorCarved?.(n,p[e],p[t])}}return f.rooms=p,{level:f,graph:m,retries:g,roomBuilders:h}}function QF(e){return ZF(e).level}function $F(e,t,n,r){oe(.5)?(eI(e,t.x,n.x,t.y,!0,r),eI(e,t.y,n.y,n.x,!1,r)):(eI(e,t.y,n.y,t.x,!1,r),eI(e,t.x,n.x,n.y,!0,r))}function eI(e,t,n,r,i,a){let o=t<=n?1:-1;for(let s=t;s!==n+o;s+=o){let t=i?s:r,n=i?r:s;e.insideWithBorder(t,n)&&e.set(t,n,a)}}function tI(e,t=new Set){let n=e.passableCells().filter(e=>!t.has(e));return n.length>0?n[k(n.length)]:null}function nI(e,t){let n=null,r=-1;for(let i of e.rooms){let e=UF(i),a=(e.x-t.x)**2+(e.y-t.y)**2;a>r&&(r=a,n=i)}return n}var rI=class e{constructor(){this.defs=new Map,this.placed=new Map}define(e,t){this.defs.set(e,t)}place(e,t){if(!this.defs.has(t))throw Error(`FeatureLayer.place: no definition for kind "${t}"`);this.placed.set(e,t)}has(e){return this.placed.has(e)}kindAt(e){return this.placed.get(e)}remove(e){this.placed.delete(e)}inspect(e,t){this.defAt(e)?.inspect?.(e,t)}interact(e,t){let n=this.defAt(e);n&&(!n.interact||n.interact(e,t)!==!1)&&(n.consequence?.(e,t),n.persistent===!1&&this.remove(e))}defAt(e){let t=this.placed.get(e);return t===void 0?void 0:this.defs.get(t)}toJSON(){return{cells:[...this.placed.entries()]}}static fromJSON(t,n){let r=new e;for(let[e,n]of t)r.define(e,n);for(let[e,t]of n.cells)r.place(e,t);return r}};function iI(e,t=[],n=!0){let r=[],i=e.map(e=>e.value);t.forEach((e,t)=>{if(e.enabled===!1){r.push({step:`rare`,index:t,outcome:`deferred`});return}let n=oe(e.chance);r.push({step:`rare`,index:t,outcome:n?`added`:`skipped`}),n&&i.push(e.value)});for(let t=0;t<e.length;t++){let n=e[t].alternative;if(!n)continue;let a=oe(n.chance);r.push({step:`alternative`,index:t,outcome:a?`swapped`:`kept`}),a&&(i[t]=n.value)}return n&&(le(i),r.push({step:`shuffle`,index:-1,outcome:`shuffled`})),{roster:i,trace:r}}function aI(e,t){return e.length===t.length&&e.every((e,n)=>e.a===t[n].a&&e.b===t[n].b&&e.extra===t[n].extra)}function oI(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function sI(e,t){if(e.length!==t.length)return!1;let n=[...e].sort((e,t)=>e[0]-t[0]),r=[...t].sort((e,t)=>e[0]-t[0]);return n.every(([e,t],n)=>e===r[n][0]&&t===r[n][1])}function cI(e,t){let n=[];return e.retries!==t.retries&&n.push({stage:`graph`,field:`retries`,expected:e.retries,actual:t.retries}),aI(e.graph,t.graph)||n.push({stage:`graph`,field:`graph`,expected:e.graph,actual:t.graph}),(e.width!==t.width||e.height!==t.height||!oI(e.terrain,t.terrain))&&n.push({stage:`paint`,field:`terrain`,expected:e.terrain,actual:t.terrain}),(e.roomBuilders.length!==t.roomBuilders.length||e.roomBuilders.some((e,n)=>e!==t.roomBuilders[n]))&&n.push({stage:`paint`,field:`roomBuilders`,expected:e.roomBuilders,actual:t.roomBuilders}),sI(e.features,t.features)||n.push({stage:`paint`,field:`features`,expected:e.features,actual:t.features}),JSON.stringify(e.content)!==JSON.stringify(t.content)&&n.push({stage:`paint`,field:`content`,expected:e.content,actual:t.content}),e.rngDraws!==t.rngDraws&&n.push({stage:`paint`,field:`rngDraws`,expected:e.rngDraws,actual:t.rngDraws}),n}function lI(e,t=2){let n=e(),r=[];for(let i=1;i<t;i++)r.push(...cI(n,e()));return r}var uI=23283064365386963e-26;new class e{constructor(){this._seed=0,this._s0=0,this._s1=0,this._s2=0,this._c=0}getSeed(){return this._seed}setSeed(e){return e=e<1?1/e:e,this._seed=e,this._s0=(e>>>0)*uI,e=e*69069+1>>>0,this._s1=e*uI,e=e*69069+1>>>0,this._s2=e*uI,this._c=1,this}getUniform(){let e=2091639*this._s0+this._c*uI;return this._s0=this._s1,this._s1=this._s2,this._c=e|0,this._s2=e-this._c,this._s2}getUniformInt(e,t){let n=Math.max(e,t),r=Math.min(e,t);return Math.floor(this.getUniform()*(n-r+1))+r}getNormal(e=0,t=1){let n,r,i;do n=2*this.getUniform()-1,r=2*this.getUniform()-1,i=n*n+r*r;while(i>1||i==0);return e+n*Math.sqrt(-2*Math.log(i)/i)*t}getPercentage(){return 1+Math.floor(this.getUniform()*100)}getItem(e){return e.length?e[Math.floor(this.getUniform()*e.length)]:null}shuffle(e){let t=[],n=e.slice();for(;n.length;){let e=n.indexOf(this.getItem(n));t.push(n.splice(e,1)[0])}return t}getWeightedValue(e){let t=0;for(let n in e)t+=e[n];let n=this.getUniform()*t,r,i=0;for(r in e)if(i+=e[r],n<i)return r;return r}getState(){return[this._s0,this._s1,this._s2,this._c]}setState(e){return this._s0=e[0],this._s1=e[1],this._s2=e[2],this._c=e[3],this}clone(){return new e().setState(this.getState())}}().setSeed(Date.now());var dI=class{getContainer(){return null}setOptions(e){this._options=e}},fI=class extends dI{constructor(){super(),this._ctx=document.createElement(`canvas`).getContext(`2d`)}schedule(e){requestAnimationFrame(e)}getContainer(){return this._ctx.canvas}setOptions(e){super.setOptions(e);let t=`${e.fontStyle?`${e.fontStyle} `:``} ${e.fontSize}px ${e.fontFamily}`;this._ctx.font=t,this._updateSize(),this._ctx.font=t,this._ctx.textAlign=`center`,this._ctx.textBaseline=`middle`}clear(){let e=this._ctx.globalCompositeOperation;this._ctx.globalCompositeOperation=`copy`,this._ctx.fillStyle=this._options.bg,this._ctx.fillRect(0,0,this._ctx.canvas.width,this._ctx.canvas.height),this._ctx.globalCompositeOperation=e}eventToPosition(e,t){let n=this._ctx.canvas,r=n.getBoundingClientRect();return e-=r.left,t-=r.top,e*=n.width/r.width,t*=n.height/r.height,e<0||t<0||e>=n.width||t>=n.height?[-1,-1]:this._normalizedEventToPosition(e,t)}};function pI(e){return e.charAt(0).toUpperCase()+e.substring(1)}function mI(e,...t){let n=mI.map;return e.replace(/%(?:([a-z]+)|(?:{([^}]+)}))/gi,function(r,i,a,o){if(e.charAt(o-1)==`%`)return r.substring(1);if(!t.length)return r;let s=t[0],c=(i||a).split(`,`),l=c.shift()||``,u=n[l.toLowerCase()];if(!u)return r;s=t.shift();let d=s[u].apply(s,c),f=l.charAt(0);return f!=f.toLowerCase()&&(d=pI(d)),d})}mI.map={s:`toString`};var hI=class e extends fI{constructor(){super(),this._spacingX=0,this._spacingY=0,this._canvasCache={}}setOptions(e){super.setOptions(e),this._canvasCache={}}draw(t,n){e.cache?this._drawWithCache(t):this._drawNoCache(t,n)}_drawWithCache(e){let[t,n,r,i,a]=e,o=``+r+i+a,s;if(o in this._canvasCache)s=this._canvasCache[o];else{let e=this._options.border;s=document.createElement(`canvas`);let t=s.getContext(`2d`);if(s.width=this._spacingX,s.height=this._spacingY,t.fillStyle=a,t.fillRect(e,e,s.width-e,s.height-e),r){t.fillStyle=i,t.font=this._ctx.font,t.textAlign=`center`,t.textBaseline=`middle`;let e=[].concat(r);for(let n=0;n<e.length;n++)t.fillText(e[n],this._spacingX/2,Math.ceil(this._spacingY/2))}this._canvasCache[o]=s}this._ctx.drawImage(s,t*this._spacingX,n*this._spacingY)}_drawNoCache(e,t){let[n,r,i,a,o]=e;if(t){let e=this._options.border;this._ctx.fillStyle=o,this._ctx.fillRect(n*this._spacingX+e,r*this._spacingY+e,this._spacingX-e,this._spacingY-e)}if(!i)return;this._ctx.fillStyle=a;let s=[].concat(i);for(let e=0;e<s.length;e++)this._ctx.fillText(s[e],(n+.5)*this._spacingX,Math.ceil((r+.5)*this._spacingY))}computeSize(e,t){return[Math.floor(e/this._spacingX),Math.floor(t/this._spacingY)]}computeFontSize(e,t){let n=Math.floor(e/this._options.width),r=Math.floor(t/this._options.height),i=this._ctx.font;this._ctx.font=`100px `+this._options.fontFamily;let a=Math.ceil(this._ctx.measureText(`W`).width);this._ctx.font=i;let o=a/100*r/n;return o>1&&(r=Math.floor(r/o)),Math.floor(r/this._options.spacing)}_normalizedEventToPosition(e,t){return[Math.floor(e/this._spacingX),Math.floor(t/this._spacingY)]}_updateSize(){let e=this._options,t=Math.ceil(this._ctx.measureText(`W`).width);this._spacingX=Math.ceil(e.spacing*t),this._spacingY=Math.ceil(e.spacing*e.fontSize),e.forceSquareRatio&&(this._spacingX=this._spacingY=Math.max(this._spacingX,this._spacingY)),this._ctx.canvas.width=e.width*this._spacingX,this._ctx.canvas.height=e.height*this._spacingY}};hI.cache=!1;var gI={4:[[0,-1],[1,0],[0,1],[-1,0]],8:[[0,-1],[1,-1],[1,0],[1,1],[0,1],[-1,1],[-1,0],[-1,-1]],6:[[-1,-1],[1,-1],[2,0],[1,1],[-1,1],[-2,0]]},_I=class{constructor(e,t={}){this._lightPasses=e,this._options=Object.assign({topology:8},t)}_getCircle(e,t,n){let r=[],i,a,o;switch(this._options.topology){case 4:a=1,o=[0,1],i=[gI[8][7],gI[8][1],gI[8][3],gI[8][5]];break;case 6:i=gI[6],a=1,o=[-1,1];break;case 8:i=gI[4],a=2,o=[-1,1];break;default:throw Error(`Incorrect topology for FOV computation`)}let s=e+o[0]*n,c=t+o[1]*n;for(let e=0;e<i.length;e++)for(let t=0;t<n*a;t++)r.push([s,c]),s+=i[e][0],c+=i[e][1];return r}},vI=class extends _I{compute(e,t,n,r){if(r(e,t,0,1),!this._lightPasses(e,t))return;let i=[],a,o,s,c,l;for(let u=1;u<=n;u++){let n=this._getCircle(e,t,u),d=360/n.length;for(let e=0;e<n.length;e++)if(s=n[e][0],c=n[e][1],a=d*(e-.5),o=a+d,l=!this._lightPasses(s,c),this._visibleCoords(Math.floor(a),Math.ceil(o),l,i)&&r(s,c,u,1),i.length==2&&i[0]==0&&i[1]==360)return}}_visibleCoords(e,t,n,r){if(e<0){let i=this._visibleCoords(0,t,n,r),a=this._visibleCoords(360+e,360,n,r);return i||a}let i=0;for(;i<r.length&&r[i]<e;)i++;if(i==r.length)return n&&r.push(e,t),!0;let a=0;if(i%2){for(;i<r.length&&r[i]<t;)i++,a++;return a!=0&&(n&&(a%2?r.splice(i-a,a,t):r.splice(i-a,a)),!0)}for(;i<r.length&&r[i]<t;)i++,a++;return e==r[i-a]&&a==1?!1:(n&&(a%2?r.splice(i-a,a,e):r.splice(i-a,a,e,t)),!0)}},yI=class extends _I{compute(e,t,n,r){if(r(e,t,0,1),!this._lightPasses(e,t))return;let i=[],a,o,s,c,l,u;for(let d=1;d<=n;d++){let n=this._getCircle(e,t,d),f=n.length;for(let e=0;e<f;e++)if(a=n[e][0],o=n[e][1],c=[e?2*e-1:2*f-1,2*f],l=[2*e+1,2*f],s=!this._lightPasses(a,o),u=this._checkVisibility(c,l,s,i),u&&r(a,o,d,u),i.length==2&&i[0][0]==0&&i[1][0]==i[1][1])return}}_checkVisibility(e,t,n,r){if(e[0]>t[0])return(this._checkVisibility(e,[e[1],e[1]],n,r)+this._checkVisibility([0,1],t,n,r))/2;let i=0,a=!1;for(;i<r.length;){let t=r[i],n=t[0]*e[1]-e[0]*t[1];if(n>=0){n==0&&!(i%2)&&(a=!0);break}i++}let o=r.length,s=!1;for(;o--;){let e=r[o],n=t[0]*e[1]-e[0]*t[1];if(n>=0){n==0&&o%2&&(s=!0);break}}let c=!0;if((i==o&&(a||s)||a&&s&&i+1==o&&o%2||i>o&&i%2)&&(c=!1),!c)return 0;let l,u=o-i+1;if(u%2){if(i%2){let e=r[i];l=(t[0]*e[1]-e[0]*t[1])/(e[1]*t[1]),n&&r.splice(i,u,t)}else{let t=r[o];l=(t[0]*e[1]-e[0]*t[1])/(e[1]*t[1]),n&&r.splice(i,u,e)}}else if(i%2){let e=r[i],t=r[o];l=(t[0]*e[1]-e[0]*t[1])/(e[1]*t[1]),n&&r.splice(i,u)}else return n&&r.splice(i,u,e,t),1;let d=(t[0]*e[1]-e[0]*t[1])/(e[1]*t[1]);return l/d}},bI=[[-1,0,0,1],[0,-1,1,0],[0,-1,-1,0],[-1,0,0,-1],[1,0,0,-1],[0,1,-1,0],[0,1,1,0],[1,0,0,1]],xI={DiscreteShadowcasting:vI,PreciseShadowcasting:yI,RecursiveShadowcasting:class extends _I{compute(e,t,n,r){r(e,t,0,1);for(let i=0;i<bI.length;i++)this._renderOctant(e,t,bI[i],n,r)}compute180(e,t,n,r,i){i(e,t,0,1);let a=(r-1+8)%8,o=(r-2+8)%8,s=(r+1+8)%8;this._renderOctant(e,t,bI[o],n,i),this._renderOctant(e,t,bI[a],n,i),this._renderOctant(e,t,bI[r],n,i),this._renderOctant(e,t,bI[s],n,i)}compute90(e,t,n,r,i){i(e,t,0,1);let a=(r-1+8)%8;this._renderOctant(e,t,bI[r],n,i),this._renderOctant(e,t,bI[a],n,i)}_renderOctant(e,t,n,r,i){this._castVisibility(e,t,1,1,0,r+1,n[0],n[1],n[2],n[3],i)}_castVisibility(e,t,n,r,i,a,o,s,c,l,u){if(!(r<i))for(let d=n;d<=a;d++){let n=-d-1,f=-d,p=!1,m=0;for(;n<=0;){n+=1;let h=e+n*o+f*s,g=t+n*c+f*l,_=(n-.5)/(f+.5),v=(n+.5)/(f-.5);if(!(v>r)){if(_<i)break;if(n*n+f*f<a*a&&u(h,g,d,1),!p)!this._lightPasses(h,g)&&d<a&&(p=!0,this._castVisibility(e,t,d+1,r,_,a,o,s,c,l,u),m=v);else{if(!this._lightPasses(h,g)){m=v;continue}p=!1,r=m}}}if(p)break}}}};.5*(Math.sqrt(3)-1),(3-Math.sqrt(3))/6;var SI=class{constructor(e,t,n,r={}){this._toX=e,this._toY=t,this._passableCallback=n,this._options=Object.assign({topology:8},r),this._dirs=gI[this._options.topology],this._options.topology==8&&(this._dirs=[this._dirs[0],this._dirs[2],this._dirs[4],this._dirs[6],this._dirs[1],this._dirs[3],this._dirs[5],this._dirs[7]])}_getNeighbors(e,t){let n=[];for(let r=0;r<this._dirs.length;r++){let i=this._dirs[r],a=e+i[0],o=t+i[1];this._passableCallback(a,o)&&n.push([a,o])}return n}},CI={Dijkstra:class extends SI{constructor(e,t,n,r){super(e,t,n,r),this._computed={},this._todo=[],this._add(e,t,null)}compute(e,t,n){let r=e+`,`+t;if(r in this._computed||this._compute(e,t),!(r in this._computed))return;let i=this._computed[r];for(;i;)n(i.x,i.y),i=i.prev}_compute(e,t){for(;this._todo.length;){let n=this._todo.shift();if(n.x==e&&n.y==t)return;let r=this._getNeighbors(n.x,n.y);for(let e=0;e<r.length;e++){let t=r[e],i=t[0],a=t[1];i+`,`+a in this._computed||this._add(i,a,n)}}}_add(e,t,n){let r={x:e,y:t,prev:n};this._computed[e+`,`+t]=r,this._todo.push(r)}},AStar:class extends SI{constructor(e,t,n,r={}){super(e,t,n,r),this._todo=[],this._done={}}compute(e,t,n){for(this._todo=[],this._done={},this._fromX=e,this._fromY=t,this._add(this._toX,this._toY,null);this._todo.length;){let n=this._todo.shift(),r=n.x+`,`+n.y;if(r in this._done)continue;if(this._done[r]=n,n.x==e&&n.y==t)break;let i=this._getNeighbors(n.x,n.y);for(let e=0;e<i.length;e++){let t=i[e],r=t[0],a=t[1];r+`,`+a in this._done||this._add(r,a,n)}}let r=this._done[e+`,`+t];if(r)for(;r;)n(r.x,r.y),r=r.prev}_add(e,t,n){let r=this._distance(e,t),i={x:e,y:t,prev:n,g:n?n.g+1:0,h:r},a=i.g+i.h;for(let e=0;e<this._todo.length;e++){let t=this._todo[e],n=t.g+t.h;if(a<n||a==n&&r<t.h){this._todo.splice(e,0,i);return}}this._todo.push(i)}_distance(e,t){switch(this._options.topology){case 4:return Math.abs(e-this._fromX)+Math.abs(t-this._fromY);case 6:let n=Math.abs(e-this._fromX),r=Math.abs(t-this._fromY);return r+Math.max(0,(n-r)/2);case 8:return Math.max(Math.abs(e-this._fromX),Math.abs(t-this._fromY))}}}};function wI(e,t){return Math.max(Math.abs(e.x-t.x),Math.abs(e.y-t.y))}function TI(e,t){let n=[],r=e.x,i=e.y,a=Math.abs(t.x-e.x),o=-Math.abs(t.y-e.y),s=e.x<t.x?1:-1,c=e.y<t.y?1:-1,l=a+o;for(;n.push({x:r,y:i}),r!==t.x||i!==t.y;){let e=l*2;e>=o&&(l+=o,r+=s),e<=a&&(l+=a,i+=c)}return n}function EI(e,t,n,r={}){let i=e.shape===`hex`?dn(t,n):TI(t,n),a=r.stop??`opaque`,o=[],s=null;for(let t of i)if(o.push(t),o.length!==1&&a!==`none`&&(a===`outside`&&!e.inside(t.x,t.y)||a===`opaque`&&e.inside(t.x,t.y)&&!e.transparent(t.x,t.y)||a===`impassable`&&e.inside(t.x,t.y)&&!e.passable(t.x,t.y))){s=t;break}return{cells:o,stop:s}}function DI(e,t,n){let r=e.shape===`hex`?dn(t,n):TI(t,n);for(let t=1;t<r.length-1;t++)if(!e.transparent(r[t].x,r[t].y))return!1;return!0}function OI(e,t,n,r){return!((e.shape===`hex`?ln(t,n):wI(t,n))>r.range||(r.requireLineOfSight??!0)&&!DI(e,t,n))}function kI(e,t,n){switch(n.kind){case`single`:return[t];case`line`:return TI(e,t);case`cone`:return MI(e,t,n.width);case`burst`:{let e=[],r=n.radius;for(let n=-r;n<=r;n++)for(let i=-r;i<=r;i++)i*i+n*n>r*r||e.push({x:t.x+i,y:t.y+n});return e}}}function AI(e,t,n,r){return e.shape===`hex`?r.kind===`single`?[{...n}]:r.kind===`line`?dn(t,n):r.kind===`burst`?fn(n,r.radius):jI(t,n,r.width):kI(t,n,r)}function jI(e,t,n){let r=ln(e,t);if(r===0)return[{...e}];let i=dn(e,t),a=[];for(let t=1;t<=r;t++){let o=i[t],s=Math.round(t/r*n);for(let n of fn(o,s))ln(e,n)===t&&a.push(n)}return a}function MI(e,t,n){let r=t.x-e.x,i=t.y-e.y,a=Math.max(Math.abs(r),Math.abs(i));if(a===0)return[{...e}];let o=Math.sign(r),s=Math.sign(i),c=r!==0&&i!==0?o:s,l=r!==0&&i!==0?-s:o,u=[];for(let t=1;t<=a;t++){let r=e.x+o*t,i=e.y+s*t,d=Math.round(t/a*n);for(let e=-d;e<=d;e++)u.push({x:r+c*e,y:i+l*e})}return u}function NI(e,t,n,r){let i=new Set,a=[],o=t;for(let t=0;t<n;t++){let t=-1,n=r+1;for(let a=0;a<e.length;a++){if(i.has(a))continue;let s=wI(o,e[a]);s<=r&&s<n&&(n=s,t=a)}if(t===-1)break;i.add(t),a.push(e[t]),o=e[t]}return a}function PI(e,t,n=1){for(let n of t)if(e<=n.max)return n.multiplier;return n}function FI(e,t){return t.length===0?1:t[Math.min(e,t.length-1)]}function II(e,t,n,r){let i=[];for(let a=1;a<=r;a++){let r={x:t.x+n.x*a,y:t.y+n.y*a};if(!e.passable(r.x,r.y))break;i.push(r)}return i}var LI=class{constructor(e,t){if(this.onMove=new p,this.onConfirm=new p,this.onCancel=new p,!Number.isFinite(t.range)||t.range<0)throw Error(`targeting range must be a finite non-negative number`);this.level=e,this.origin={...t.origin},this.range=t.range,this.requireLineOfSight=t.requireLineOfSight??!0,this.validate=t.validate,this.shape=t.shape??{kind:`single`},this.cursor={...t.cursor??t.origin}}get target(){return{...this.cursor}}get distance(){return this.level.shape===`hex`?ln(this.origin,this.cursor):wI(this.origin,this.cursor)}get inRange(){return this.distance<=this.range}get inSight(){return DI(this.level,this.origin,this.cursor)}get valid(){return!this.inRange||this.requireLineOfSight&&!this.inSight?!1:!this.validate||this.validate(this.cursor)}move(e,t){if(this.level.shape===`hex`){let n=this.level.neighbors(this.cursor.x,this.cursor.y).find(n=>n.x-this.cursor.x===e&&n.y-this.cursor.y===t);n&&this.moveTo(n);return}this.moveTo({x:this.cursor.x+e,y:this.cursor.y+t})}moveTo(e){this.level.inside(e.x,e.y)&&(this.cursor={x:e.x,y:e.y},this.onMove.dispatch({...this.cursor}))}setShape(e){this.shape=e}preview(){return this.valid?AI(this.level,this.origin,this.cursor,this.shape):[]}confirm(){if(!this.valid)return null;let e={origin:{...this.origin},target:{...this.cursor},shape:this.shape,cells:this.preview()};return this.onConfirm.dispatch(e),e}cancel(){this.onCancel.dispatch()}},RI=class{constructor(e){this.visible=new Set,this.explored=new Set,this.light=new Map,this.level=e,this.fov=e.shape===`hex`?null:new xI.PreciseShadowcasting((t,n)=>e.transparent(t,n))}update(e,t,n=this.level.viewDistance??Math.max(this.level.width,this.level.height),r){if(this.visible.clear(),this.light.clear(),r){this.updateFromHeight(e,t,n,r);return}if(this.fov){this.fov.compute(e,t,n,(e,t,n,r)=>{if(!this.level.inside(e,t))return;let i=this.level.index(e,t);this.visible.add(i),this.explored.add(i),this.light.set(i,r)});return}let i={x:e,y:t};for(let e of fn(i,n)){if(!this.level.inside(e.x,e.y))continue;let t=dn(i,e);t.slice(1,-1).some(e=>!this.level.inside(e.x,e.y)||!this.level.transparent(e.x,e.y))||this.lightCell(e.x,e.y,t.length-1,n)}}lightCell(e,t,n,r){let i=this.level.index(e,t);this.visible.add(i),this.explored.add(i),this.light.set(i,r===0?1:Math.max(0,1-n/(r+1)))}updateFromHeight(e,t,n,r){let i=r.height??r.heights.heightAt(e,t),a={x:e,y:t};if(this.level.shape===`hex`){for(let e of fn(a,n)){if(!this.level.inside(e.x,e.y))continue;let t=dn(a,e);this.heightBlocked(t,r.heights,i,r.heights.heightAt(e.x,e.y))||this.lightCell(e.x,e.y,t.length-1,n)}return}for(let o=t-n;o<=t+n;o++)for(let t=e-n;t<=e+n;t++){if(!this.level.inside(t,o)||wI(a,{x:t,y:o})>n)continue;let e=TI(a,{x:t,y:o});this.heightBlocked(e,r.heights,i,r.heights.heightAt(t,o))||this.lightCell(t,o,e.length-1,n)}}heightBlocked(e,t,n,r){let i=Math.max(n,r);for(let n=1;n<e.length-1;n++){let r=e[n];if(!this.level.inside(r.x,r.y)||!this.level.transparent(r.x,r.y)||t.heightAt(r.x,r.y)>i)return!0}return!1}isVisible(e,t){return this.visible.has(this.level.index(e,t))}isExplored(e,t){return this.explored.has(this.level.index(e,t))}lightAt(e,t){return this.light.get(this.level.index(e,t))??0}reset(){this.visible.clear(),this.explored.clear(),this.light.clear()}revealAll(){for(let e=0;e<this.level.cellCount;e++)this.explored.add(e)}},zI=class{constructor(e){this.level=e,this.heights=new Int32Array(e.cellCount)}heightAt(e,t){return this.level.inside(e,t)?this.heights[this.level.index(e,t)]:0}set(e,t,n){if(!Number.isInteger(n))throw Error(`a cell's height must be a whole number, got ${n}`);this.level.inside(e,t)&&(this.heights[this.level.index(e,t)]=n)}},BI=class{constructor(e){this.level=e}passable(e){let t=e.blocked;return(e,n)=>this.level.passable(e,n)?!t?.has(this.level.index(e,n)):!1}stepper(e){let t=this.passable(e),n=e.heights;if(!n)return(e,n,r,i)=>this.level.inside(e,n)&&this.level.inside(r,i)&&t(r,i);let r=e.climb??1;if(!Number.isInteger(r)||r<0)throw Error(`a climb limit must be a non-negative whole number, got ${e.climb}`);return(e,i,a,o)=>this.level.inside(e,i)&&this.level.inside(a,o)&&t(a,o)&&n.heightAt(a,o)-n.heightAt(e,i)<=r}find(e,t,n={}){if(this.level.shape===`hex`||n.heights){let r=this.distanceMap(t,n),i=[],a=e;for(let e=0;e<this.level.cellCount;e++){let e=this.descend(a,r,n);if(!e||(i.push(e),e.x===t.x&&e.y===t.y))break;a=e}return i}let r=new CI.AStar(t.x,t.y,this.passable(n),{topology:n.topology??8}),i=[];return r.compute(e.x,e.y,(e,t)=>i.push({x:e,y:t})),i.slice(1)}step(e,t,n={}){return this.find(e,t,n)[0]??null}distanceMap(e,t={}){let n=new Int32Array(this.level.cellCount).fill(-1),r=this.passable(t),i=this.stepper(t);if(!r(e.x,e.y))return n;let a=[this.level.index(e.x,e.y)];n[a[0]]=0;for(let e=0;e<a.length;e++){let r=a[e],o=this.level.xOf(r),s=this.level.yOf(r),c=n[r]+1;this.level.forEachNeighbor(o,s,t.topology??8,(e,t)=>{if(!i(e,t,o,s))return;let r=this.level.index(e,t);n[r]===-1&&(n[r]=c,a.push(r))})}return n}descend(e,t,n={}){let r=this.stepper(n),i=t[this.level.index(e.x,e.y)];if(i<=0)return null;let a=null,o=i;return this.level.forEachNeighbor(e.x,e.y,n.topology??8,(n,i)=>{if(!r(e.x,e.y,n,i))return;let s=t[this.level.index(n,i)];s!==-1&&s<o&&(o=s,a={x:n,y:i})}),a}autoExplore(e,t,n={}){let r=this.passable(n),i=this.stepper(n);if(!r(e.x,e.y))return[];let a=new Map,o=new Set([this.level.index(e.x,e.y)]),s=[e];for(let e=0;e<s.length;e++){let r=s[e];if(e>0&&!t.isExplored(r.x,r.y))return this.reconstruct(a,r);this.level.forEachNeighbor(r.x,r.y,n.topology??8,(e,t)=>{if(!i(r.x,r.y,e,t))return;let n=this.level.index(e,t);o.has(n)||(o.add(n),a.set(n,r),s.push({x:e,y:t}))})}return[]}reconstruct(e,t){let n=[t],r=e.get(this.level.index(t.x,t.y));for(;r;)n.push(r),r=e.get(this.level.index(r.x,r.y));return n.reverse()}},VI=class e{constructor(){this.entries=[],this.sequence=0,this.now=0}get size(){return this.entries.length}get actors(){return this.entries.map(e=>e.actor)}has(e){return this.entries.some(t=>t.actor===e)}add(e,t=0,n=e.priority??0){if(!Number.isFinite(t)||t<0)throw Error(`scheduler delay must be finite and non-negative`);if(!Number.isFinite(n))throw Error(`scheduler priority must be finite`);this.entries.push({actor:e,time:this.now+t,sequence:this.sequence++,priority:n}),this.sort()}remove(e){let t=this.entries.findIndex(t=>t.actor===e);t!==-1&&this.entries.splice(t,1)}clear(){this.entries.length=0,this.now=0,this.sequence=0}peek(){let e=this.entries[0];return e?(this.now=Math.max(this.now,e.time),e.actor):null}spend(e){let t=this.entries[0];if(!t)return;let n=t.actor.speed??1;t.time=this.now+e/(n>0?n:1),t.sequence=this.sequence++,this.sort()}postpone(e,t){let n=this.entries.find(t=>t.actor===e);n&&(n.time+=t,n.sequence=this.sequence++,this.sort())}timeOf(e){return this.entries.find(t=>t.actor===e)?.time??null}toJSON(e){return{now:this.now,sequence:this.sequence,entries:this.entries.map(t=>({id:e(t.actor),time:t.time,sequence:t.sequence,...t.priority===0?{}:{priority:t.priority}}))}}static restore(t,n){let r=new e;return r.now=t.now,r.sequence=t.sequence,r.entries=t.entries.map(e=>({actor:n(e.id),time:e.time,sequence:e.sequence,priority:e.priority??0})),r.sort(),r}sort(){this.entries.sort((e,t)=>e.time-t.time||t.priority-e.priority||e.sequence-t.sequence)}};function HI(e,t,n,r,i,a={}){let o=a.sightRadius??6,s=a.fleeBelow??0;if((a.disposition??`hostile`)!==`hostile`&&a.provoked!==!0)return{state:`wander`,step:UI(e,n,a)};let c=new RI(e);return c.update(n.x,n.y,o),c.isVisible(i.x,i.y)?r<=s?{state:`flee`,step:WI(e,n,i,a)}:{state:`hunt`,step:t.step(n,i,a)}:{state:`wander`,step:UI(e,n,a)}}function UI(e,t,n){return se(GI(e,t,n))}function WI(e,t,n,r){let i=GI(e,t,r),a=null,o=KI(t,n);for(let e of i){let t=KI(e,n);t>o&&(o=t,a=e)}return a}function GI(e,t,n){let r=n.blocked,i=[];for(let[a,o]of zF(n.topology??8)){let n={x:t.x+a,y:t.y+o};e.passable(n.x,n.y)&&(r?.has(e.index(n.x,n.y))||i.push(n))}return i}function KI(e,t){return(e.x-t.x)**2+(e.y-t.y)**2}var qI=class e{constructor(e){this.revealedKind=new Map,this.discovered=new Set,this.level=e}conceal(e,t,n,r){let i=this.level.index(e,t);this.revealedKind.set(i,r),this.discovered.delete(i),this.level.set(e,t,n)}isSecret(e,t){let n=this.level.index(e,t);return this.revealedKind.has(n)&&!this.discovered.has(n)}isDiscovered(e,t){return this.discovered.has(this.level.index(e,t))}discover(e,t){if(!this.isSecret(e,t))return!1;let n=this.level.index(e,t);return this.discovered.add(n),this.level.set(e,t,this.revealedKind.get(n)),!0}toJSON(){return{revealed:[...this.revealedKind],discovered:[...this.discovered]}}static fromJSON(t,n){let r=new e(t);for(let[e,t]of n.revealed)r.revealedKind.set(e,t);for(let e of n.discovered)r.discovered.add(e);return r}},JI=class e{constructor(e){this.openKind=new Map,this.closedKind=new Map,this.lockedBy=new Map,this.open_=new Map,this.level=e}place(e,t,n){let r=this.level.index(e,t);this.openKind.set(r,n.open),this.closedKind.set(r,n.closed),this.open_.set(r,n.startOpen??!1),n.locked===void 0?this.lockedBy.delete(r):this.lockedBy.set(r,n.locked),this.level.set(e,t,this.open_.get(r)?n.open:n.closed)}isDoor(e,t){return this.open_.has(this.level.index(e,t))}isOpen(e,t){return this.open_.get(this.level.index(e,t))===!0}isLocked(e,t){return this.lockedBy.has(this.level.index(e,t))}requiredKey(e,t){return this.lockedBy.get(this.level.index(e,t))}open(e,t){let n=this.level.index(e,t);return!this.open_.has(n)||this.open_.get(n)||this.lockedBy.has(n)?!1:(this.open_.set(n,!0),this.level.set(e,t,this.openKind.get(n)),!0)}close(e,t){let n=this.level.index(e,t);return!this.open_.has(n)||!this.open_.get(n)?!1:(this.open_.set(n,!1),this.level.set(e,t,this.closedKind.get(n)),!0)}unlock(e,t){let n=this.level.index(e,t);return this.lockedBy.has(n)?(this.lockedBy.delete(n),!0):!1}toJSON(){let e=[];for(let[t,n]of this.openKind)e.push({cell:t,open:n,closed:this.closedKind.get(t),locked:this.lockedBy.get(t),isOpen:this.open_.get(t)===!0});return{doors:e}}static fromJSON(t,n){let r=new e(t);for(let e of n.doors){let n=t.xOf(e.cell),i=t.yOf(e.cell);r.place(n,i,{open:e.open,closed:e.closed,locked:e.locked,startOpen:e.isOpen})}return r}},YI=class e{constructor(e=[]){this.current=0;for(let t=1;t<e.length;t++)if(e[t]>=e[t-1])throw Error(`boss phase thresholds must descend`);this.thresholds=e}get phase(){return this.current}check(e){let t=0;for(;t<this.thresholds.length&&e<=this.thresholds[t];)t++;let n=[];for(;this.current<t;)this.current++,n.push(this.current);return n}reset(){this.current=0}toJSON(){return{phase:this.current}}static fromJSON(t,n){let r=new e(t);return r.current=n.phase,r}},XI=class e{constructor(e){this.remaining=new Map,this.cooldowns=new Map(Object.entries(e))}advance(e=1){for(let[t,n]of this.remaining)n<=e?this.remaining.delete(t):this.remaining.set(t,n-e)}ready(){let e=[];for(let t of this.cooldowns.keys())this.remaining.has(t)||e.push(t);return e}use(e){let t=this.cooldowns.get(e);return t===void 0||this.remaining.has(e)?!1:(t>0&&this.remaining.set(e,t),!0)}toJSON(){return{remaining:[...this.remaining]}}static fromJSON(t,n){let r=new e(t);for(let[e,t]of n.remaining)r.remaining.set(e,t);return r}},ZI=class extends x{modifyDamage(e,t,n){let r={attacker:e,defender:t,amount:n,prevented:!1};return this.emit(`beforeDamage`,r),r.amount=Math.max(0,r.amount),r.amount===0&&(r.prevented=!0),r}},QI=class{constructor(e){this.detected=!1,this.radius=e.radius}get isDetected(){return this.detected}checkDetection(e,t){if(this.detected)return!1;let n=t.some(t=>wI(e,t)<=this.radius);return n&&(this.detected=!0),n}reset(){this.detected=!1}},$I=class e{constructor(e){this.streak=0,this.lastTurn=-1/0,this.window=e}get count(){return this.streak}trigger(e){return this.streak=e-this.lastTurn<=this.window?this.streak+1:1,this.lastTurn=e,this.streak}isActive(e){return e-this.lastTurn<=this.window}reset(){this.streak=0,this.lastTurn=-1/0}toJSON(){return{streak:this.streak,lastTurn:this.lastTurn}}static fromJSON(t,n){let r=new e(t);return r.streak=n.streak,r.lastTurn=n.lastTurn,r}},eL=class e{constructor(e){if(this.index=-1,this.remaining=0,e.length===0)throw Error(`a multi-stage ability needs at least one stage`);this.stages=e}get active(){return this.index>=0}get stage(){return this.index>=0?this.stages[this.index]:null}start(){return!this.active&&(this.index=0,this.remaining=this.stages[0].duration,!0)}advance(){return!this.active||(this.remaining--,this.remaining>0)?null:(this.index++,this.index>=this.stages.length?(this.index=-1,`done`):(this.remaining=this.stages[this.index].duration,this.stages[this.index].name))}cancel(){this.index=-1,this.remaining=0}toJSON(){return{index:this.index,remaining:this.remaining}}static fromJSON(t,n){let r=new e(t);return r.index=n.index,r.remaining=n.remaining,r}},tL=class e{constructor(e){if(this.index=0,this.state=`idle`,typeof e.damage!=`function`&&!Number.isFinite(e.damage))throw Error(`beam damage must be a finite number or a function`);if(typeof e.damage==`number`&&e.damage<0)throw Error(`beam damage must be non-negative`);if(this.options=e,this.shape=e.shape??(e.fronts?`fronts`:`line`),e.fronts){let t=e.fronts([{...e.from}],0);this.fronts=t.length?[t.map(e=>({...e}))]:[]}else this.fronts=AI(e.level,e.from,e.target,{kind:`line`}).slice(1).map(e=>[{...e}])}get active(){return this.state===`active`}get done(){return this.state===`done`||this.state===`blocked`||this.state===`cancelled`}get beamShape(){return this.shape}get currentPath(){return this.fronts.flat().map(e=>({...e}))}start(){return this.state===`idle`&&(this.state=this.fronts.length===0?`done`:`active`,!0)}advance(){if(this.state!==`active`)return this.inactiveStep();let e=this.fronts[this.index]??[],t=Math.max(0,this.fronts.length-this.index-1),n=[],r=[],i=0;for(let a of e){let e={cell:{...a},step:this.index,remaining:t};if(!this.blocked(a,e)){n.push({...a}),this.options.onCell?.({...a},e);for(let t of this.options.targetsAt?.(a)??[]){let n=typeof this.options.damage==`function`?this.options.damage(t,e):this.options.damage;if(!Number.isFinite(n)||n<0)throw Error(`beam damage callback must return a non-negative finite number`);i+=n,r.push(t),this.options.applyDamage?.(t,n,e)}}}let a=this.index;if(this.index++,this.options.fronts&&n.length>0){let e=this.options.fronts(n.map(e=>({...e})),this.index);e.length&&this.fronts.push(e.map(e=>({...e})))}return n.length===0?this.state=`blocked`:this.index>=this.fronts.length&&(this.state=`done`),{status:n.length===0?`blocked`:this.state,cell:n[0]?{...n[0]}:null,cells:n.map(e=>({...e})),step:a,remaining:t,targets:[...r],damage:i}}cancel(){(this.state===`active`||this.state===`idle`)&&(this.state=`cancelled`)}toJSON(){return{state:this.state,fronts:this.fronts.map(e=>e.map(e=>({...e}))),index:this.index,shape:this.shape}}static fromJSON(t,n){let r=n.shape??(t.fronts?`fronts`:`line`);if(t.shape!==void 0&&t.shape!==r)throw Error(`beam save is shape "${r}", not "${t.shape}"`);let i=Object.create(e.prototype);return i.options=t,i.shape=r,i.fronts=n.fronts?n.fronts.map(e=>e.map(e=>({...e}))):(n.path??[]).map(e=>[{...e}]),i.index=n.index,i.state=n.state,i}blocked(e,t){let n=this.options.blocker??(this.options.stopAtOpaque===!1?`none`:`terrain`),r=!1;return n===`terrain`?r=!this.options.level.inside(e.x,e.y)||!this.options.level.transparent(e.x,e.y):n!==`none`&&(r=n({...e},t)===!0),r||this.options.isBlocked?.({...e},t)===!0}inactiveStep(){return{status:this.state,cell:null,cells:[],step:this.index,remaining:Math.max(0,this.fronts.length-this.index),targets:[],damage:0}}};function nL(e,t={}){return(t.within?[...t.within]:aL(e.cellCount)).filter(n=>!(t.occupied?.has(n)||t.terrain&&!t.terrain.has(e.terrain[n])))}function rL(e,t,n){let r=new Set([t]),i=[t];for(let t=0;t<Math.max(0,n);t++){let t=[];for(let n of i)e.forEachNeighbor(e.xOf(n),e.yOf(n),8,(n,i)=>{if(!e.inside(n,i))return;let a=e.index(n,i);r.has(a)||(r.add(a),t.push(a))});i=t}return r.delete(t),[...r]}function iL(e,t){let n=[...new Set(e)];le(n);let r=n.slice(0,Math.max(0,t));return{cells:r,trace:{requested:t,available:n.length,selected:r}}}function aL(e){let t=Array(e);for(let n=0;n<e;n++)t[n]=n;return t}var oL=l({AbilityCycle:()=>XI,BossPhases:()=>YI,CombatHooks:()=>ZI,DUNGEON_KINDS:()=>XF,Doors:()=>JI,Elevation:()=>zI,FLOOR:()=>VF,FeatureLayer:()=>rI,FieldOfView:()=>RI,Level:()=>HF,MultiStageAbility:()=>eL,MultiTurnBeam:()=>tL,Pathfinder:()=>BI,Scheduler:()=>VI,Secrets:()=>qI,Stealth:()=>QI,TargetingController:()=>LI,TriggerTracker:()=>$I,WALL:()=>BF,areaFalloffMultiplier:()=>FI,ballistica:()=>EI,canTarget:()=>OI,candidateCells:()=>nL,cellsNear:()=>rL,chainTargets:()=>NI,chebyshevDistance:()=>wI,checkDeterminism:()=>lI,compareDungeonArtifacts:()=>cI,coneCells:()=>MI,decideMonsterAI:()=>HI,eligibleBuilders:()=>JF,findFreeCell:()=>tI,furthestRoom:()=>nI,generateDungeon:()=>QF,generateDungeonGraph:()=>ZF,hallBuilder:()=>GF,hasLineOfSight:()=>DI,hexConeCells:()=>jI,knockbackPath:()=>II,neighbourOffsets:()=>zF,pickBuilder:()=>YF,rangeMultiplier:()=>PI,rectCenter:()=>UF,rectsOverlap:()=>WF,resolveArea:()=>kI,resolveAreaOnLevel:()=>AI,rollRoster:()=>iI,selectDistinctCells:()=>iL,traceLine:()=>TI});function sL(e,t){let n=e=>t.filter(t=>t.op===e).sort((e,t)=>(e.order??0)-(t.order??0)),r=e;for(let e of n(`add`))r+=e.value;for(let e of n(`multiply`))r*=e.value;for(let e of n(`set`))r=e.value;return r}var cL=class e{constructor(e){this.modifiers=[],this.cache=null,this.baseValues={...e.base},this.derived=e.derived??[]}base(e){return this.baseValues[e]??0}setBase(e,t){this.baseValues[e]=t,this.cache=null}addModifier(e){this.modifiers.push(e),this.cache=null}removeModifier(e){let t=this.modifiers.indexOf(e);t!==-1&&this.modifiers.splice(t,1),this.cache=null}removeModifiersFrom(e){this.modifiers=this.modifiers.filter(t=>t.source!==e),this.cache=null}get(e){return this.resolveAll()[e]??0}resolveAll(){if(this.cache)return this.cache;let e={...this.baseValues};for(let t of Object.keys(e))e[t]=sL(e[t],this.modifiersFor(t));for(let t of this.derived)e[t.name]=sL(t.from(e),this.modifiersFor(t.name));return this.cache=e,e}modifiersFor(e){return this.modifiers.filter(t=>t.stat===e)}toJSON(){return{base:{...this.baseValues}}}static fromJSON(t,n){let r=new e(t);return r.baseValues={...t.base,...n.base},r.cache=null,r}};function lL(e,t,n){return{maxLevel:n,experienceFor:n=>n<=1?0:Math.round(e*(n-1)**t)}}var uL=class e{constructor(e,t={}){this.curve=e,this.level=t.level??1,this.experience=t.experience??this.curve.experienceFor(this.level)}get experienceToNext(){return this.level>=this.curve.maxLevel?null:this.curve.experienceFor(this.level+1)-this.experience}addExperience(e){this.experience+=e;let t=0;for(;this.level<this.curve.maxLevel&&this.experience>=this.curve.experienceFor(this.level+1);)this.level++,t++;return t}toJSON(){return{level:this.level,experience:this.experience}}static fromJSON(t,n){return new e(t,n)}};function dL(e,t,n=()=>ie(1,20)){return e+n()>=t}var fL=class e{constructor(e,t={}){this.available=0,this.stats=e,this.capFor=t.cap??(()=>1/0),this.costFor=t.cost??(()=>1)}get points(){return this.available}grant(e){this.available+=e}canSpend(e){return this.nextRankCost(e)!==null}spend(e){let t=this.nextRankCost(e);if(t===null)return!1;let n=this.stats.base(e);return this.available-=t,this.stats.setBase(e,n+1),!0}nextRankCost(e){let t=this.stats.base(e);if(t>=this.capFor(e))return null;let n=this.costFor(e,t+1);return this.available>=n?n:null}toJSON(){return{points:this.available}}static fromJSON(t,n,r){let i=new e(t,n);return i.available=r.points,i}},pL=class e{constructor(e,t=null,n={}){this.worn=new Map,this.names=new Set(e),this.stats=t,this.isSlotLocked=n.locked??(()=>!1)}get(e){return this.worn.get(e)}isLocked(e){let t=this.worn.get(e);return t!==void 0&&this.isSlotLocked(e,t)}equip(e,t){if(this.assertSlot(e),this.isLocked(e))return;let n=this.unequip(e);return this.wear(e,t),n}wear(e,t){this.worn.set(e,t);for(let e of t.modifiers??[])this.stats?.addModifier({...e,source:t})}unequip(e){let t=this.worn.get(e);if(t&&!this.isSlotLocked(e,t))return this.worn.delete(e),this.stats?.removeModifiersFrom(t),t}get slots(){return[...this.names]}assertSlot(e){if(!this.names.has(e))throw Error(`no such equipment slot: "${e}"`)}toJSON(e){return{worn:[...this.worn].map(([t,n])=>[t,e(n)])}}static fromJSON(t,n){let r=new e(t.slots,t.stats??null,{locked:t.locked});for(let[e,i]of n.worn)r.assertSlot(e),r.wear(e,t.resolve(i));return r}},mL=class e{constructor(e={}){this.slots=[],this.capacity=e.capacity}get items(){return this.slots}get totalWeight(){return this.slots.reduce((e,t)=>e+this.weightOf(t),0)}weightOf(e){return(e.weight??0)*e.quantity+(e.contents?.totalWeight??0)}find(e,t){return this.slots.find(n=>n.id===e&&(t===void 0||n.instanceId===t))}add(e){if(!Number.isFinite(e.quantity)||e.quantity<=0||e.weight!==void 0&&(!Number.isFinite(e.weight)||e.weight<0)||this.capacity!==void 0&&this.totalWeight+this.weightOf(e)>this.capacity)return!1;if(e.stackable){let t=this.slots.find(t=>t.id===e.id&&t.stackable&&t.instanceId===e.instanceId);if(t)return t.quantity+=e.quantity,!0}return this.slots.push({...e}),!0}remove(e,t,n){if(t!==void 0&&(!Number.isFinite(t)||t<=0))return;let r=this.slots.findIndex(t=>t.id===e&&(n===void 0||t.instanceId===n));if(r===-1)return;let i=this.slots[r];i.quantity-=t??i.quantity,i.quantity<=0&&this.slots.splice(r,1)}take(e,t=1,n){if(!Number.isFinite(t)||t<=0)return;let r=this.slots.findIndex(t=>t.id===e&&(n===void 0||t.instanceId===n));if(r===-1)return;let i=this.slots[r],a=Math.min(Math.floor(t),i.quantity);if(a<=0)return;let o={...i,quantity:a};return i.quantity-=a,i.quantity<=0&&this.slots.splice(r,1),o}toJSON(){return{capacity:this.capacity,slots:this.slots.map(e=>({id:e.id,quantity:e.quantity,instanceId:e.instanceId,identified:e.identified,cursed:e.cursed,blessed:e.blessed,level:e.level,affix:e.affix,durability:e.durability,maxDurability:e.maxDurability,contents:e.contents?.toJSON()}))}}static fromJSON(t,n){let r=new e({capacity:n.capacity});return r.slots=n.slots.map(n=>{let r=t.get(n.id);if(!r)throw Error(`Inventory.fromJSON: no definition for item "${n.id}"`);let{contents:i,...a}=n,o={...r,...hL(a),id:n.id,quantity:n.quantity};return i&&(o.contents=e.fromJSON(t,i)),o}),r}};function hL(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}function gL(e,t){return t.matches?t.matches(e):t.category===void 0?typeof t.id==`string`?e.id===t.id:(t.id??[]).includes(e.id):e.category===t.category}function _L(e){return e.matches!==void 0||e.category!==void 0||e.id!==void 0}function vL(e,t){let n=new Map;for(let t of e.items)n.set(t,t.quantity);let r=new Map;for(let i of t.ingredients){if(!_L(i))throw Error(`recipe ingredient must name an id, a category, or a matches predicate`);if(!Number.isFinite(i.quantity)||i.quantity<=0)throw Error(`recipe ingredient quantity must be a positive number`);let t=i.quantity;for(let a of e.items){if(t<=0)break;let e=n.get(a)??0;if(e<=0||!gL(a,i))continue;let o=Math.min(e,t);n.set(a,e-o),t-=o,r.set(a,(r.get(a)??0)+o)}if(t>0)return!1}for(let[t,n]of r)e.remove(t.id,n,t.instanceId);if(e.add(t.result))return!0;for(let[t,n]of r)e.add({...t,quantity:n});return!1}function yL(e,t){let n=e.add({duration:t.duration,tick:e=>t.tick?.(e),onExpire:t.onExpire});return{cancel:()=>{e.remove(n),t.onExpire()}}}function bL(e,t,n){let r=Symbol(`statusEffect`);for(let t of n.modifiers)e.addModifier({...t,source:r});return yL(t,{duration:n.duration,tick:n.tick,onExpire:()=>e.removeModifiersFrom(r)})}function xL(e,t={}){let n=e.entries.filter(e=>e.weight>0&&(t.curse===void 0||!!e.curse===t.curse)&&(t.predicate?.(e)??!0));if(n.length===0)return null;let r=ce(n.map(e=>e.weight));return r===null?null:n[r]}function SL(e){return e.affix}function CL(e,t){let n=e.affix!==void 0;e.affix=t.id,t.curse?e.cursed=!0:n&&(e.cursed=!1)}function wL(e){e.affix!==void 0&&(e.cursed=!1),delete e.affix}function TL(e,t){if(e.affix===void 0){wL(t);return}t.affix=e.affix,t.cursed=e.cursed??!1}function EL(e,t){return!(e.trigger!==t.trigger||e.kinds&&(t.kind===void 0||!e.kinds.includes(t.kind)))}function DL(e){e.identified=!0}function OL(e,t,n=`keep`){return Number.isFinite(t)?(e.level=(e.level??0)+t,n===`remove`&&wL(e),e.level):e.level??0}function kL(e,t){return e.maxDurability===void 0?!1:!Number.isFinite(t)||t<=0?(e.durability??e.maxDurability)<=0:(e.durability=Math.max(0,(e.durability??e.maxDurability)-t),e.durability<=0)}function AL(e,t){e.maxDurability!==void 0&&(!Number.isFinite(t)||t<=0||(e.durability=Math.min(e.maxDurability,(e.durability??e.maxDurability)+t)))}function jL(e,t,n){let r=new Map;for(let t of Object.keys(n.fields))r.set(t,e[t]),e[t]=n.fields[t];return yL(t,{duration:n.duration,tick:n.tick,onExpire:()=>{for(let[t,n]of r)e[t]=n}})}var ML=class e{constructor(e){this.progress=0,this.max=e.max,this.regenRate=e.regenRate,this.value=e.current??e.max}get current(){return this.value}canAfford(e){return this.value>=e}spend(e){return this.canAfford(e)?(this.value-=e,!0):!1}refund(e=1){let t=Math.min(e,this.max-this.value);return this.value+=t,t}advance(e=1){if(!(this.value>=this.max)){for(this.progress+=e;this.progress>=this.regenRate&&this.value<this.max;)this.progress-=this.regenRate,this.value++;this.value>=this.max&&(this.progress=0)}}toJSON(){return{current:this.value,progress:this.progress}}static fromJSON(t,n){let r=new e({...t,current:n.current});return r.progress=n.progress,r}};function NL(e){if(e.entries.length===0||!oe(e.chance??1))return null;let t=ce(e.entries.map(e=>e.weight));if(t===null)return null;let n=e.entries[t];return{id:n.id,quantity:n.quantity??1}}var PL=class e{constructor(e){this.grantedTiers=0,this.balance=0,this.choices=new Map,this.track=e}get points(){return this.balance}openTiers(e){let t=[];return this.track.tiers.forEach((n,r)=>{e>=n.threshold&&t.push(r)}),t}grant(e){let t=0;for(;this.grantedTiers<this.track.tiers.length&&e>=this.track.tiers[this.grantedTiers].threshold;){let e=this.track.tiers[this.grantedTiers];e.kind===`points`&&(this.balance+=e.points??0,t+=e.points??0),this.grantedTiers++}return t}spend(e){return this.balance<e?!1:(this.balance-=e,!0)}choose(e,t,n){let r=this.track.tiers[e];if(!r)throw Error(`no such advancement tier: ${e}`);if(r.kind===`points`)throw Error(`tier ${e} grants points, it has no choice`);if(n<r.threshold)throw Error(`tier ${e} has not opened yet`);if(this.choices.has(e))throw Error(`tier ${e} is already decided`);if(!(r.options??[]).some(e=>e.id===t))throw Error(`tier ${e} has no option "${t}"`);this.choices.set(e,t)}choice(e){return this.choices.get(e)??null}toJSON(){return{grantedTiers:this.grantedTiers,balance:this.balance,choices:[...this.choices]}}static fromJSON(t,n){let r=new e(t);r.grantedTiers=n.grantedTiers,r.balance=n.balance;for(let[e,t]of n.choices)r.choices.set(e,t);return r}};function FL(e,t){return t.map(t=>({stat:t.stat,op:t.op,value:t.base+t.perLevel*e}))}function IL(e){if(e.labels.length<e.kinds.length)throw Error(`not enough appearances: ${e.kinds.length} kinds but only ${e.labels.length} labels`);let t=[...e.labels];for(let e=t.length-1;e>0;e--){let n=k(0,e+1);[t[e],t[n]]=[t[n],t[e]]}let n=new Map;return e.kinds.forEach((e,r)=>n.set(e,t[r])),n}var LL=class e{constructor(e){this.assigned=new Map,this.tables=e}appearanceOf(e,t){let n=this.assigned.get(e);if(!n){let t=this.tables[e];if(!t)throw Error(`no such appearance category: "${e}"`);n=IL(t),this.assigned.set(e,n)}let r=n.get(t);if(r===void 0)throw Error(`"${t}" is not in appearance category "${e}"`);return r}toJSON(){return{assigned:[...this.assigned].map(([e,t])=>[e,[...t]])}}static fromJSON(t,n){let r=new e(t);for(let[e,t]of n.assigned)r.assigned.set(e,new Map(t));return r}};function RL(e,t,n,r,i,a){let o=a.prices.get(r);if(!o)return!1;let s=t.find(r);if(!s||s.quantity<i)return!1;let c=o.buy*i;return e.base(a.currency)<c?!1:(t.remove(r,i),n.add({...s,quantity:i})?(e.setBase(a.currency,e.base(a.currency)-c),!0):(t.add({...s,quantity:i}),!1))}function zL(e,t,n,r,i,a){let o=a.prices.get(r);if(!o)return!1;let s=n.find(r);return!s||s.quantity<i?!1:(n.remove(r,i),t.add({...s,quantity:i})?(e.setBase(a.currency,e.base(a.currency)+o.sell*i),!0):(n.add({...s,quantity:i}),!1))}function BL(e){let t=Array.isArray(e)?e:[e];for(let e of t)if(!Number.isFinite(e.amount)||e.amount<0)throw Error(`a resource cost must be a non-negative number, "${e.stat}" costs ${e.amount}`);return t}function VL(e){let t=new Map;for(let n of e)t.set(n.stat,(t.get(n.stat)??0)+n.amount);return t}function HL(e,t){return[...VL(BL(t))].every(([t,n])=>e.base(t)>=n)}function UL(e,t){let n=VL(BL(t));if(![...n].every(([t,n])=>e.base(t)>=n))return!1;for(let[t,r]of n)e.setBase(t,e.base(t)-r);return!0}function WL(e,t,n=1){for(let[r,i]of VL(BL(t)))e.setBase(r,e.base(r)+i*n)}function GL(e,t,n,r){return UL(e,t)?n.refund(Math.floor(t.amount/r)):0}var KL=class e{constructor(){this.layers=[]}add(e,t=0){e<=0||this.layers.push({amount:e,decayPerTick:t})}get total(){return this.layers.reduce((e,t)=>e+t.amount,0)}get layerCount(){return this.layers.length}absorb(e){let t=e,n=0;for(;t>0&&this.layers.length>0;){let e=this.layers[this.layers.length-1],r=Math.min(e.amount,t);e.amount-=r,t-=r,n+=r,e.amount<=0&&this.layers.pop()}return n}advance(e=1){for(let t=this.layers.length-1;t>=0;t--){let n=this.layers[t];n.decayPerTick&&(n.amount-=n.decayPerTick*e,n.amount<=0&&this.layers.splice(t,1))}}clear(){this.layers=[]}toJSON(){return{layers:this.layers.map(e=>({...e}))}}static fromJSON(t){let n=new e;return n.layers=t.layers.map(e=>({...e})),n}};function qL(e,t,n){return le([...t]).slice(0,Math.min(n,t.length)).map(t=>{let n=Symbol(`trait:${t.name}`);for(let r of t.modifiers)e.addModifier({...r,source:n});return{trait:t,source:n}})}var JL=class{constructor(){this.affected=new Map}update(e,t){let n=new Set(e),r=e.filter(e=>!!e.aura),i=new Set(r);for(let i of r){let r=this.affected.get(i);r||(r=new Map,this.affected.set(i,r));for(let n of e){if(n===i)continue;let e=t(i,n),a=r.get(n);if(e&&!a){let e=Symbol(`aura:${i.aura.name}`);for(let t of i.aura.modifiers)n.stats.addModifier({...t,source:e});r.set(n,e)}else!e&&a&&(n.stats.removeModifiersFrom(a),r.delete(n))}for(let[e,t]of[...r])n.has(e)||(e.stats.removeModifiersFrom(t),r.delete(e))}for(let[e,t]of[...this.affected])if(!i.has(e)){for(let[e,n]of t)e.stats.removeModifiersFrom(n);this.affected.delete(e)}}},YL=class e{constructor(e){if(this.points=new Map,e.some(e=>!e.id||!Number.isFinite(e.threshold)||e.threshold<0))throw Error(`support levels need an id and a non-negative threshold`);this.levels=[...e].sort((e,t)=>e.threshold-t.threshold)}get(e,t){return this.points.get(XL(e,t))??0}level(e,t){let n=this.get(e,t),r=null;for(let e of this.levels){if(e.threshold>n)break;r=e}return r}add(e,t,n){if(!e||!t||e===t)throw Error(`support needs two different named units`);if(!Number.isFinite(n))throw Error(`support amount must be finite, got ${n}`);let r=this.level(e,t),i=XL(e,t),a=Math.max(0,(this.points.get(i)??0)+n);return this.points.set(i,a),{a:e,b:t,points:a,previousLevel:r,level:this.level(e,t)}}toJSON(){return{pairs:[...this.points].map(([e,t])=>{let[n,r]=e.split(`\0`);return[n,r,t]})}}static fromJSON(t,n){let r=new e(t);for(let[e,t,i]of n.pairs){if(!e||!t||e===t||!Number.isFinite(i)||i<0)throw Error(`invalid support save data`);let n=XL(e,t);if(r.points.has(n))throw Error(`invalid support save data: duplicate pair "${e}" / "${t}"`);r.points.set(n,i)}return r}};function XL(e,t){return[e,t].sort().join(`\0`)}var ZL=new Set([`id`,`growth`,`level`,`startingAffix`,`startingItem`,`lowHpReaction`]);function QL(e,t={},n){let r=new cL({base:rR(e)}),i;e.growth!==void 0&&(i=new uL(nR(e,t),{level:e.level??1}));let a;if(e.startingItem!==void 0){let n=t.items?.[e.startingItem];if(!n)throw Error(`entity template "${e.id}": unknown starting item "${e.startingItem}"`);if(a=n(),e.startingAffix!==void 0){let n=t.affixes?.[e.startingAffix];if(!n)throw Error(`entity template "${e.id}": unknown affix "${e.startingAffix}"`);CL(a,n)}}else if(e.startingAffix!==void 0)throw Error(`entity template "${e.id}": a starting affix needs a starting item to carry it`);let o=new en,s={id:e.id,stats:r,progression:i,item:a,reactions:o};if(e.lowHpReaction!==void 0){if(!n)throw Error(`entity template "${e.id}": names a lowHpReaction threshold but no onLowHp callback was given`);let t=e.lowHpReaction;o.add({id:`low-hp`,when:e=>e.hp/e.maxHp<=t,action:()=>n(s)})}return s}function $L(e,t={},n){return e.map(e=>QL(e,t,n))}function eR(e){let t={stats:e.stats.toJSON()};return e.progression&&(t.progression=e.progression.toJSON()),e.item&&(t.item=e.item),t}function tR(e,t,n,r){let i=QL(e,t,r);if(i.stats=cL.fromJSON({base:rR(e)},n.stats),n.progression!==void 0){if(!i.progression)throw Error(`entity template "${e.id}": save data has progression but the row names no growth curve`);i.progression=uL.fromJSON(nR(e,t),n.progression)}return n.item!==void 0&&(i.item=n.item),i}function nR(e,t){let n=t.growthCurves?.[e.growth??``];if(!n)throw Error(`entity template "${e.id}": unknown growth curve "${e.growth}"`);return n}function rR(e){let t={};for(let[n,r]of Object.entries(e))if(!ZL.has(n)){if(typeof r!=`number`)throw Error(`entity template "${e.id}": stat "${n}" must be a number, got ${typeof r}`);t[n]=r}return t}var iR=l({Advancement:()=>PL,Appearances:()=>LL,AuraField:()=>JL,Barrier:()=>KL,Charges:()=>ML,EquipmentSlots:()=>pL,Inventory:()=>mL,Progression:()=>uL,SkillPoints:()=>fL,StatBlock:()=>cL,SupportLedger:()=>YL,affixOf:()=>SL,applyAffix:()=>CL,applyItemStatusEffect:()=>jL,applyStatusEffect:()=>bL,assignAppearances:()=>IL,assignTraits:()=>qL,buildEntities:()=>$L,buildEntity:()=>QL,buy:()=>RL,canAfford:()=>HL,composeModifiers:()=>sL,convertToCharges:()=>GL,copyAffix:()=>TL,craft:()=>vL,damageItem:()=>kL,enchant:()=>OL,fromEntitySaveState:()=>tR,identify:()=>DL,matchesContext:()=>EL,powerCurve:()=>lL,refund:()=>WL,removeAffix:()=>wL,repairItem:()=>AL,rollAffix:()=>xL,rollLoot:()=>NL,scaledModifiers:()=>FL,sell:()=>zL,skillCheck:()=>dL,spend:()=>UL,toEntitySaveState:()=>eR}),aR=class{constructor(){this.factories=new Map,this.loaded=new Map,this.currentId=null}define(e,t,n={}){this.factories.set(e,{create:t,persistent:n.persistent??!0})}enter(e,t){let n=this.factories.get(e);if(!n)throw Error(`no such map: "${e}"`);let r=this.loaded.get(e);return(!r||!n.persistent)&&(r=n.create(),this.loaded.set(e,r)),this.currentId=e,this.lastSpawn=t,r}get current(){return this.currentId?this.loaded.get(this.currentId)??null:null}get currentMapId(){return this.currentId}get spawn(){return this.lastSpawn}isLoaded(e){return this.loaded.has(e)}isPersistent(e){return this.factories.get(e)?.persistent??!0}unload(e){if(e===this.currentId)throw Error(`cannot unload the current map: "${e}"`);this.loaded.delete(e)}},oR=class{constructor(){this.locations=new Map}add(e){this.locations.set(e.id,e)}remove(e){this.locations.delete(e)}get(e){return this.locations.get(e)}at(e,t){for(let n of this.locations.values())if(n.x===e&&n.y===t)return n}get all(){return[...this.locations.values()]}},sR=class{constructor(){this.turn=0,this.effects=new Map}add(e){let t=Symbol();return this.effects.set(t,{...e}),t}remove(e){this.effects.delete(e)}has(e){return this.effects.has(e)}advance(e=1){this.turn+=e;for(let[t,n]of this.effects)n.tick(this.turn),n.duration!==void 0&&(n.duration-=e,n.duration<=0&&(this.effects.delete(t),n.onExpire?.()))}};function cR(e){if(e.entries.length===0||!oe(e.rate))return null;let t=ce(e.entries.map(e=>e.weight));return t===null?null:e.entries[t].value}var lR=class e{constructor(e={}){if(this.changed=new p,this.dayLength=e.dayLength??120,!(this.dayLength>0))throw Error(`an environment day must be longer than zero seconds`);if(this.boundaries=e.phaseBoundaries??[.2,.7,.8],this.boundaries[0]<=0||this.boundaries[0]>=this.boundaries[1]||this.boundaries[1]>=this.boundaries[2]||this.boundaries[2]>=1)throw Error(`environment phase boundaries must be ascending fractions strictly between 0 and 1`);if(this.seconds_=e.startSeconds??0,this.weather_=e.startWeather??`clear`,!Number.isFinite(this.seconds_))throw Error(`environment startSeconds must be finite`)}get day(){return Math.floor(this.seconds_/this.dayLength)}get seconds(){return this.seconds_}get weather(){return this.weather_}get phase(){let e=(this.seconds_%this.dayLength+this.dayLength)%this.dayLength/this.dayLength;return e<this.boundaries[0]?`dawn`:e<this.boundaries[1]?`day`:e<this.boundaries[2]?`dusk`:`night`}get night(){return this.phase===`night`}update(e){if(!Number.isFinite(e)||e<0)throw Error(`environment update must be non-negative, got ${e}`);this.seconds_+=e;let t=this.toJSON();return this.changed.dispatch(t),t}setWeather(e){if(!e)throw Error(`weather needs a non-empty id`);this.weather_=e;let t=this.toJSON();return this.changed.dispatch(t),t}toJSON(){return{day:this.day,seconds:this.seconds_,phase:this.phase,weather:this.weather_}}static fromJSON(t,n){return new e({...t,startSeconds:n.seconds,startWeather:n.weather})}},uR=class e{constructor(e){if(e.sides.length===0)throw Error(`SideTurns needs at least one side`);if(e.schedule.length===0)throw Error(`SideTurns needs a non-empty schedule`);let t=e.round??1,n=e.sideIndex??0,r=e.timeIndex??0;if(!Number.isInteger(t)||t<1)throw Error(`SideTurns round must be a positive integer`);if(n<0||n>=e.sides.length)throw Error(`SideTurns side index ${n} is outside ${e.sides.length} sides`);if(r<0||r>=e.schedule.length)throw Error(`SideTurns time index ${r} is outside ${e.schedule.length} times`);this.sides=[...e.sides],this.schedule=[...e.schedule],this.areas=e.areas??[],this.state={round:t,sideIndex:n,timeIndex:r}}get round(){return this.state.round}get side(){return this.sides[this.state.sideIndex]}get timeIndex(){return this.state.timeIndex}get timeOfDay(){return this.schedule[this.state.timeIndex]}get snapshot(){return{...this.state}}timeOfDayAt(e,t){for(let n of this.areas)if(n.contains(e,t))return n.times[this.state.timeIndex]??this.timeOfDay;return this.timeOfDay}lawfulBonusAt(e,t,n){return dR(e,this.timeOfDayAt(t,n).lawfulBonus)}advance(){let e=!1;return this.state.sideIndex++,this.state.sideIndex>=this.sides.length&&(this.state.sideIndex=0,this.state.round++,this.state.timeIndex=(this.state.timeIndex+1)%this.schedule.length,e=!0),{side:this.side,round:this.state.round,newRound:e}}toJSON(){return this.snapshot}static fromJSON(t,n){return new e({...t,round:n.round,sideIndex:n.sideIndex,timeIndex:n.timeIndex})}};function dR(e,t){switch(e){case`lawful`:return t;case`chaotic`:return-t;default:return 0}}var fR=l({EnvironmentClock:()=>lR,Overworld:()=>oR,SideTurns:()=>uR,TurnClock:()=>sR,World:()=>aR,alignmentBonus:()=>dR,rollEncounter:()=>cR});function pR(e,t,n={}){let r=n.pick??k,i=0;return t.forEach((t,n)=>{mR(t,t.name??`#${n+1}`,e.shape);let a=hR(e,t);if(i+=a.length,a.length!==0)for(let[n,i]of a){let a=t.outputs[r(t.outputs.length)];for(let[r,o]of Object.entries(a))for(let a=0;a<t.height;a++)for(let s=0;s<t.width;s++){let c=o[a*t.width+s];c!==-1&&e.setTile(r,n+s,i+a,c)}}}),i}function mR(e,t,n){if(e.topology&&(n===`square`||n===`hex`)&&e.topology!==n)throw Error(`automap rule "${t}" targets ${e.topology} cells, but the map is ${n}`);if(!Number.isInteger(e.width)||e.width<=0||!Number.isInteger(e.height)||e.height<=0)throw Error(`automap rule "${t}" needs a positive width and height`);if(e.outputs.length===0)throw Error(`automap rule "${t}" has no outputs - a rule that matches and writes nothing is a mistake`);let r=e.width*e.height;for(let[n,i]of Object.entries(e.input))if(i.length!==r)throw Error(`automap rule "${t}" input "${n}" has ${i.length} cells, but the pattern is ${r}`);e.outputs.forEach((e,n)=>{for(let[i,a]of Object.entries(e))if(a.length!==r)throw Error(`automap rule "${t}" output ${n+1} "${i}" has ${a.length} cells, but the pattern is ${r}`)})}function hR(e,t){let n=[];for(let r=0;r+t.height<=e.heightInTiles;r++)for(let i=0;i+t.width<=e.widthInTiles;i++)gR(e,t,i,r)&&n.push([i,r]);return n}function gR(e,t,n,r){for(let[i,a]of Object.entries(t.input))for(let o=0;o<t.height;o++)for(let s=0;s<t.width;s++){let c=a[o*t.width+s];if(c!==-1&&e.getTile(i,n+s,r+o)!==c)return!1}return!0}var _R=class e{constructor(){this.switches=new Map,this.variables=new Map}switch(e){return this.switches.get(e)??!1}setSwitch(e,t){this.switches.set(e,t)}variable(e){return this.variables.get(e)??0}setVariable(e,t){this.variables.set(e,t)}toJSON(){return{switches:[...this.switches],variables:[...this.variables]}}static fromJSON(t){let n=new e;for(let[e,r]of t.switches)n.setSwitch(e,r);for(let[e,r]of t.variables)n.setVariable(e,r);return n}};function vR(e,t){return`switch`in e?t.switch(e.switch)===e.equals:t.variable(e.variable)>=e.atLeast}function yR(e,t){let n;for(let r of e.pages)(r.conditions??[]).every(e=>vR(e,t))&&(n=r);return n}var bR=class{constructor(e){this.cancelled=!1,this.options=e,this.state={game:e.game,answers:{}}}cancel(){this.cancelled=!0}async run(e){for(let t of e){if(this.cancelled)break;await this.step(t)}return this.state}async step(e){if(`say`in e){await this.speak(e.say,e.speaker);return}if(`ask`in e){let t=await this.speak(e.ask,e.speaker,e.choices);e.store&&(this.state.answers[e.store]=t);return}if(`wait`in e){await new Promise(t=>setTimeout(t,e.wait*1e3));return}if(`setSwitch`in e){this.state.game.setSwitch(e.setSwitch,e.value);return}if(`setVariable`in e){this.state.game.setVariable(e.setVariable,e.value);return}if(`addVariable`in e){let t=this.state.game.variable(e.addVariable);this.state.game.setVariable(e.addVariable,t+e.amount);return}if(`if`in e){let t=vR(e.if,this.state.game);await this.run(t?e.then:e.else??[]);return}if(`move`in e){await this.options.move?.(e.move.target,e.move.steps);return}`call`in e&&await e.call(this.state)}speak(e,t,n){return this.options.present({text:e,speaker:t,choices:n})}};function xR(e,t){t&&e.has?.(t)&&e.play?.(t)}var SR=class{constructor(e,t,n,r){this.facing=`down`,this.target=null,this.progress=0,this.sprite=e,this.x=this.fromX=t,this.y=this.fromY=n,this.tileWidth=r.tileWidth,this.tileHeight=r.tileHeight,this.speed=r.speed??4,this.options=r,this.place(),this.playIdle()}get isMoving(){return this.target!==null}turnTo(e,t){this.target||(this.facing=CR(e,t),this.playIdle())}moveBy(e,t){return!this.target&&(this.facing=CR(e,t),this.fromX=this.x,this.fromY=this.y,this.target={x:this.x+e,y:this.y+t},this.progress=0,this.playWalk(),!0)}update(e){this.sprite.update?.(e),this.target&&(this.progress=Math.min(1,this.progress+this.speed*e),this.sprite.x=wR(this.fromX,this.target.x,this.progress)*this.tileWidth,this.sprite.y=wR(this.fromY,this.target.y,this.progress)*this.tileHeight,this.progress>=1&&(this.x=this.target.x,this.y=this.target.y,this.target=null,this.playIdle()))}place(){this.sprite.x=this.x*this.tileWidth,this.sprite.y=this.y*this.tileHeight}playWalk(){xR(this.sprite,this.options.walkAnimation?.(this.facing))}playIdle(){xR(this.sprite,this.options.idleAnimation?.(this.facing))}};function CR(e,t){return e>0?`right`:e<0?`left`:t>0?`down`:`up`}function wR(e,t,n){return e+(t-e)*n}var TR=class{constructor(e,t,n,r={}){this.facing=0,this.moving=!1,this.sprite=e,this.x=t,this.y=n,this.speed=r.speed??4,this.options=r,this.place(),this.playIdle()}get isMoving(){return this.moving}move(e,t,n){let r=Math.hypot(e,t);r>0?(this.facing=Math.atan2(t,e),this.x+=e/r*this.speed*n,this.y+=t/r*this.speed*n,this.moving||(this.moving=!0,this.playWalk())):this.moving&&(this.moving=!1,this.playIdle()),this.place(),this.sprite.update?.(n)}turnTo(e,t){this.moving||e===0&&t===0||(this.facing=Math.atan2(t,e),this.playIdle())}place(){this.sprite.x=this.x,this.sprite.y=this.y}playWalk(){xR(this.sprite,this.options.walkAnimation?.(this.facing))}playIdle(){xR(this.sprite,this.options.idleAnimation?.(this.facing))}};function ER(e,t){return e.x<t.x+t.width&&e.x+e.width>t.x&&e.y<t.y+t.height&&e.y+e.height>t.y}function DR(e,t){let n=e.x-t.x,r=e.y-t.y,i=e.radius+t.radius;return n*n+r*r<i*i}function OR(e,t){let n=jR(e.x,t.x,t.x+t.width),r=jR(e.y,t.y,t.y+t.height),i=e.x-n,a=e.y-r;return i*i+a*a<e.radius*e.radius}function kR(e,t,n,r){let{tileSize:i,isSolid:a}=r;if(!(i>0))throw Error(`collision tileSize must be positive`);let o=AR(e.x,e.y,e.width,e.height,t,i,a,!0);return{x:o,y:AR(o,e.y,e.width,e.height,n,i,a,!1)}}function AR(e,t,n,r,i,a,o,s){if(i===0)return s?e:t;let c=s?e:t,l=s?n:r,u=c+i,d=Math.floor((s?t:e)/a),f=Math.floor(((s?t+r:e+n)-1e-6)/a),p=(e,t)=>s?o(e,t):o(t,e);if(i>0){let e=Math.floor((c+l-1e-6)/a),t=Math.floor((u+l-1e-6)/a);for(let n=e+1;n<=t;n++)for(let e=d;e<=f;e++)if(p(n,e))return n*a-l}else{let e=Math.floor(c/a),t=Math.floor(u/a);for(let n=e-1;n>=t;n--)for(let e=d;e<=f;e++)if(p(n,e))return(n+1)*a}return u}function jR(e,t,n){return e<t?t:e>n?n:e}var MR=class e{constructor(){this.definitions=new Map,this.stageIndex=new Map,this.tracked=null}define(e){this.definitions.set(e.id,e)}track(e){e!==null&&this.require(e),this.tracked=e}trackedQuest(){return this.tracked!==null&&this.status(this.tracked)===`active`?this.tracked:null}trackedLocation(){let e=this.trackedQuest();return e?this.currentStage(e)?.location??null:null}markerFor(e,t){return e.some(e=>this.status(e)===`active`&&this.stageSatisfied(e,t))?`turnIn`:e.some(e=>this.status(e)===`available`)?`offer`:`none`}canStart(e){return(this.require(e).requires??[]).every(e=>this.status(e)===`complete`)}start(e){if(!this.canStart(e))throw Error(`quest "${e}" cannot start yet - a prerequisite is incomplete`);this.stageIndex.set(e,0)}status(e){let t=this.require(e),n=this.stageIndex.get(e);return n===void 0?this.canStart(e)?`available`:`unavailable`:n>=t.stages.length?`complete`:`active`}currentStage(e){return this.status(e)===`active`?this.require(e).stages[this.stageIndex.get(e)]:null}progress(e,t){let n=this.currentStage(e);return n?.counter?Math.min(1,t.variable(n.counter.variable)/n.counter.target):null}advanceStage(e,t){return this.stageSatisfied(e,t)?(this.stageIndex.set(e,this.stageIndex.get(e)+1),!0):!1}stageSatisfied(e,t){let n=this.currentStage(e);return n?n.condition?vR(n.condition,t):!n.counter||t.variable(n.counter.variable)>=n.counter.target:!1}require(e){let t=this.definitions.get(e);if(!t)throw Error(`no such quest: "${e}"`);return t}toJSON(){return{stageIndex:[...this.stageIndex],tracked:this.tracked}}static fromJSON(t,n){let r=new e;for(let e of t)r.define(e);for(let[e,t]of n.stageIndex)r.stageIndex.set(e,t);return n.tracked&&(r.tracked=n.tracked),r}};function NR(e){let t=[],n=new Map;for(let r of e){let e=n.get(r.questId);e||(e={id:r.questId,stages:[]},r.requires!==void 0&&(e.requires=r.requires),n.set(r.questId,e),t.push(r.questId)),e.stages.push(PR(e.id,r))}return t.map(e=>n.get(e))}function PR(e,t){if(t.conditionSwitch!==void 0&&t.conditionVariable!==void 0)throw Error(`quest "${e}": a stage row cannot name both a condition switch and a condition variable`);let n={};if(t.conditionSwitch!==void 0){if(t.conditionEquals===void 0)throw Error(`quest "${e}": conditionSwitch needs a conditionEquals`);n.condition={switch:t.conditionSwitch,equals:t.conditionEquals}}else if(t.conditionVariable!==void 0){if(t.conditionAtLeast===void 0)throw Error(`quest "${e}": conditionVariable needs a conditionAtLeast`);n.condition={variable:t.conditionVariable,atLeast:t.conditionAtLeast}}if(t.counterVariable!==void 0){if(t.counterTarget===void 0)throw Error(`quest "${e}": counterVariable needs a counterTarget`);n.counter={variable:t.counterVariable,target:t.counterTarget}}if(t.description!==void 0&&(n.description=t.description),t.locationMap!==void 0||t.locationX!==void 0||t.locationY!==void 0){if(t.locationX===void 0||t.locationY===void 0)throw Error(`quest "${e}": a stage location needs both locationX and locationY`);n.location={x:t.locationX,y:t.locationY},t.locationMap!==void 0&&(n.location.map=t.locationMap)}return n}var FR=class{constructor(e){this.name=e}},IR=4,LR=8,RR=new WeakMap;function zR(e){return RR.get(e)}function BR(e,t){return RR.set(e,t),e}var VR=class{constructor(e){this.pos=0,this.symbols=[],this.objects=[],this.bytes=e}byte(){if(this.pos>=this.bytes.length)throw Error(`Marshal: unexpected end of input`);return this.bytes[this.pos++]}take(e){if(e<0)throw Error(`Marshal: negative length`);let t=this.bytes.subarray(this.pos,this.pos+e);if(t.length<e)throw Error(`Marshal: unexpected end of input`);return this.pos+=e,t}readFixnum(){let e=this.byte()<<24>>24;if(e===0)return 0;if(e>=5&&e<=127)return e-5;if(e<=-5&&e>=-128)return e+5;if(e>0){let t=0;for(let n=0;n<e;n++)t|=this.byte()<<8*n;return t>>>0}let t=-e,n=0;for(let e=0;e<t;e++)n|=this.byte()<<8*e;return(n>>>0)-2**(8*t)}readBytes(){return this.take(this.readFixnum())}readSymbol(){let e=new TextDecoder().decode(this.readBytes());return this.symbols.push(e),e}readSymbolLink(){let e=this.readFixnum(),t=this.symbols[e];if(t===void 0)throw Error(`Marshal: symbol link ${e} out of range`);return t}readSymbolValue(){let e=String.fromCharCode(this.byte());if(e===`:`)return this.readSymbol();if(e===`;`)return this.readSymbolLink();throw Error(`Marshal: expected a symbol, got tag "${e}"`)}link(e){return this.objects.push(e),e}readBignum(){let e=String.fromCharCode(this.byte())===`-`?-1:1,t=this.readFixnum(),n=0,r=1;for(let e=0;e<t;e++)n+=(this.byte()|this.byte()<<8)*r,r*=65536;return e*n}readFloat(){let e=new TextDecoder().decode(this.readBytes());return e===`inf`?1/0:e===`-inf`?-1/0:e===`nan`?NaN:Number(e)}readArray(){let e=[];this.link(e);let t=this.readFixnum();for(let n=0;n<t;n++)e.push(this.readValue());return e}readHash(e){let t=new Map;this.link(t);let n=this.readFixnum();for(let e=0;e<n;e++)t.set(this.readValue(),this.readValue());return e&&RR.set(t,this.readValue()),t}readIvars(e){let t={};for(let n=0;n<e;n++)t[this.readSymbolValue()]=this.readValue();return t}readObject(){let e={class:``,ivars:{}};return this.link(e),e.class=this.readSymbolValue(),e.ivars=this.readIvars(this.readFixnum()),e}readIvarWrapped(){let e=this.readValue();return this.readIvars(this.readFixnum()),e}readUserDefined(){let e={class:``,raw:new Uint8Array};return this.link(e),e.class=this.readSymbolValue(),e.raw=this.readBytes().slice(),e}readUserMarshal(){let e={class:``,value:null};return this.link(e),e.class=this.readSymbolValue(),e.value=this.readValue(),e}readValue(){let e=String.fromCharCode(this.byte());switch(e){case`0`:return null;case`T`:return!0;case`F`:return!1;case`i`:return this.readFixnum();case`l`:return this.link(this.readBignum());case`f`:return this.link(this.readFloat());case`:`:return this.readSymbol();case`;`:return this.readSymbolLink();case`"`:return this.link(new TextDecoder().decode(this.readBytes()));case`[`:return this.readArray();case`{`:return this.readHash(!1);case`}`:return this.readHash(!0);case`o`:return this.readObject();case`I`:return this.readIvarWrapped();case`u`:return this.readUserDefined();case`U`:return this.readUserMarshal();case`@`:{let e=this.readFixnum(),t=this.objects[e];if(t===void 0)throw Error(`Marshal: object link ${e} out of range`);return t}default:throw Error(`Marshal: unsupported tag "${e}" (0x${e.charCodeAt(0).toString(16)})`)}}readDocument(){let e=this.byte(),t=this.byte();if(e!==IR||t>LR)throw Error(`Marshal: unsupported version ${e}.${t} (expected ${IR}.${LR} or lower)`);return this.readValue()}};function HR(e){return new VR(e).readDocument()}function UR(e){return typeof e==`object`&&!!e&&`class`in e&&`ivars`in e}function WR(e){let t=[IR,LR];return GR(t,e),new Uint8Array(t)}function GR(e,t){if(t==null)e.push(KR(`0`));else if(t===!0)e.push(KR(`T`));else if(t===!1)e.push(KR(`F`));else if(t instanceof FR)e.push(KR(`:`)),qR(e,t.name);else if(typeof t==`number`)Number.isInteger(t)&&Math.abs(t)<2**30?(e.push(KR(`i`)),JR(e,t)):(e.push(KR(`f`)),qR(e,Number.isFinite(t)?String(t):t>0?`inf`:t<0?`-inf`:`nan`));else if(typeof t==`string`)e.push(KR(`"`)),qR(e,t);else if(Array.isArray(t)){e.push(KR(`[`)),JR(e,t.length);for(let n of t)GR(e,n)}else if(t instanceof Map){let n=RR.has(t);e.push(KR(n?`}`:`{`)),JR(e,t.size);for(let[n,r]of t)GR(e,n),GR(e,r);n&&GR(e,RR.get(t))}else if(UR(t)){e.push(KR(`o`)),e.push(KR(`:`)),qR(e,t.class);let n=Object.entries(t.ivars);JR(e,n.length);for(let[t,r]of n)e.push(KR(`:`)),qR(e,t),GR(e,r)}else throw Error(`Marshal: cannot encode a value of type ${typeof t}`)}function KR(e){return e.charCodeAt(0)}function qR(e,t){let n=new TextEncoder().encode(t);JR(e,n.length);for(let t of n)e.push(t)}function JR(e,t){if(t===0){e.push(0);return}if(t>0&&t<=122){e.push(t+5);return}if(t<0&&t>=-123){e.push(t-5&255);return}if(t>0){for(let n=1;n<=4;n++)if(t<2**(8*n)){e.push(n);for(let r=0;r<n;r++)e.push(t>>>8*r&255);return}}else for(let n=1;n<=4;n++)if(t>=-(2**(8*n))){e.push(-n&255);let r=t+2**(8*n);for(let t=0;t<n;t++)e.push(r>>>8*t&255);return}throw Error(`Marshal: integer ${t} is out of range for a Fixnum`)}var YR=l({AUTOMAP_EMPTY:()=>-1,EventRunner:()=>bR,FreeMover:()=>TR,GameState:()=>_R,GridMover:()=>SR,QuestLog:()=>MR,RubySymbol:()=>FR,aabbOverlap:()=>ER,activePage:()=>yR,automap:()=>pR,circleAabbOverlap:()=>OR,circleOverlap:()=>DR,conditionHolds:()=>vR,decodeMarshal:()=>HR,encodeMarshal:()=>WR,hashDefaultOf:()=>zR,questsFromRows:()=>NR,resolveAabbAgainstTiles:()=>kR,withHashDefault:()=>BR}),XR=lL(20,2,100),ZR=class{constructor(e){this.species=e.species,this.deriveStats=e.deriveStats,this.progression=new uL(e.species.growth??XR,{level:e.level??1}),this.stats=new cL({base:this.computeBase()})}refreshStats(){let e=this.computeBase();for(let[t,n]of Object.entries(e))this.stats.setBase(t,n)}computeBase(){let e=this.progression.level;return this.deriveStats?this.deriveStats(this.species.baseStats,e):{...this.species.baseStats}}},QR=class{constructor(){this.multipliers=new Map}key(e,t){return`${e}:${t}`}set(e,t,n){this.multipliers.set(this.key(e,t),n)}get(e,t){return this.multipliers.get(this.key(e,t))??1}multiplierFor(e,t){return t.reduce((t,n)=>t*this.get(e,n),1)}},$R=class{constructor(e){this.storage=[],this.active=Array(e).fill(null)}get members(){return this.active}get boxed(){return this.storage}add(e){let t=this.active.indexOf(null);t===-1?this.storage.push(e):this.active[t]=e}store(e){let t=this.active[e];t&&(this.active[e]=null,this.storage.push(t))}withdraw(e,t){if(t<0||t>=this.active.length)return;let n=this.storage[e];if(!n)return;this.storage.splice(e,1);let r=this.active[t];this.active[t]=n,r&&this.storage.push(r)}get activeMembers(){return this.active.filter(e=>e!==null)}};function ez(e){return[...e].sort((e,t)=>(t.priority??0)-(e.priority??0)||t.speed-e.speed)}function tz(e,t){let n=null;for(let r of e)r.at(t)&&(n=r.into);return n}var nz=class{constructor(e,t){this.stages=new Map,this.modifiers=new Map,this.stats=e,this.max=t.max,this.multiplierFor=t.multiplier}get(e){return this.stages.get(e)??0}change(e,t){let n=this.get(e),r=Math.max(-this.max,Math.min(this.max,n+t)),i=r-n;return i===0?0:(this.stages.set(e,r),this.applyModifier(e,r),i)}applyModifier(e,t){let n=this.modifiers.get(e);if(n&&this.stats.removeModifier(n),t===0){this.modifiers.delete(e);return}let r={stat:e,op:`multiply`,value:this.multiplierFor(t)};this.stats.addModifier(r),this.modifiers.set(e,r)}resetAll(){for(let e of this.modifiers.values())this.stats.removeModifier(e);this.modifiers.clear(),this.stages.clear()}};function rz(e,t,n,r=(e,n)=>t.multiplierFor(e.type,n)){if(e.length===0)return null;let i=e[0],a=r(i,n);for(let t of e.slice(1)){let e=r(t,n);e>a&&(a=e,i=t)}return i}function iz(e,t,n,r){let i=null,a=az(e,n,r);return t.forEach((e,t)=>{let o=az(e.types,n,r);o<a&&(a=o,i=t)}),i}function az(e,t,n){return Math.max(...n.map(n=>t.multiplierFor(n,e)))}var oz=class extends x{},sz=class{constructor(){this.conditions=new Map}set(e){this.conditions.set(e.id,{...e})}has(e){return this.conditions.has(e)}get(e){return this.conditions.get(e)}clear(e){this.conditions.delete(e)}get active(){return[...this.conditions.values()]}advance(e=1){for(let[t,n]of this.conditions)n.duration!==void 0&&(n.duration-=e,n.duration<=0&&this.conditions.delete(t))}},cz=class{constructor(e){this.chanceToHit=lz(e.chanceToHit??1),this.strikeDuration=Math.max(0,e.strikeDuration??0),this.totalDamage=Math.max(0,e.damage)*Math.max(0,e.strikes),this.expectedDamage=this.totalDamage*this.chanceToHit,this.defenderHp0=e.defender.hp;let t=[],n=e.defender.hp;for(let r=0;r<=e.strikes;r++)r>0&&(e.hits?.[r-1]??!0)&&(n-=Math.max(0,e.damage)),t.push({strike:r,time:r*this.strikeDuration,attackerHp:e.attacker.hp,defenderHp:Math.max(0,n),defenderDamage:this.defenderHp0-Math.max(0,n)});this.frames=t}get duration(){return this.strikeDuration*(this.frames.length-1)}get defenderKilled(){return this.frames[this.frames.length-1].defenderHp===0}sampleAt(e){let t=this.frames.length-1;if(this.strikeDuration<=0)return this.frames[t];let n=0;for(let r=0;r<=t&&this.frames[r].time<=e+1e-9;r++)n=r;return this.frames[n]}};function lz(e){return Math.max(0,Math.min(1,e))}var uz=class{constructor(e){this.onChange=new p,this.stage_=`attacker`,this.charge=null,this.victim=null,this.highlight_=0,this.units=e.units,this.side=e.side,this.disabledOf=e.disabled??(e=>e.disabled??!1),this.canTarget=e.canTarget??(()=>!0)}get stage(){return this.stage_}get attacker(){return this.charge}get target(){return this.victim}get done(){return this.charge!==null&&this.victim!==null}get candidates(){return this.units.filter(e=>(this.side===void 0||e.side===this.side)&&!this.disabledOf(e))}get targets(){let e=this.charge;return e?this.units.filter(t=>t.id!==e.id&&!this.disabledOf(t)&&(e.side===void 0||t.side!==e.side)&&this.canTarget(e,t)):[]}get highlight(){return this.highlight_}get highlighted(){return this.active()[this.highlight_]??null}move(e){let t=this.active();t.length!==0&&(this.highlight_=((this.highlight_+e)%t.length+t.length)%t.length,this.onChange.dispatch())}select(){let e=this.highlighted;return e?(this.stage_===`attacker`?(this.charge=e,this.stage_=`target`,this.highlight_=0):this.victim=e,this.onChange.dispatch(),!0):!1}back(){if(this.stage_===`attacker`)return;let e=this.charge;this.charge=null,this.victim=null,this.stage_=`attacker`;let t=e?this.candidates.findIndex(t=>t.id===e.id):-1;this.highlight_=t>=0?t:0,this.onChange.dispatch()}reset(){this.charge=null,this.victim=null,this.stage_=`attacker`,this.highlight_=0,this.onChange.dispatch()}active(){return this.stage_===`attacker`?this.candidates:this.targets}},dz=class{constructor(e){this.onChange=new p,this.built=null,this.elapsed_=0,this.handleSelectorChange=()=>{if(this.selector.done&&this.attacker&&this.target){let e=this.damageFor(this.attacker,this.target);this.built=new cz({attacker:{hp:this.attacker.hp??0,name:this.attacker.id},defender:{hp:this.target.hp??0,name:this.target.id},damage:e.damage,strikes:e.strikes,...e.chanceToHit===void 0?{}:{chanceToHit:e.chanceToHit},...e.hits===void 0?{}:{hits:e.hits},strikeDuration:this.strikeDuration}),this.elapsed_=0}else this.built=null;this.onChange.dispatch()},this.damageFor=e.damageFor,this.strikeDuration=e.strikeDuration??0,this.selector=new uz({units:e.units,...e.side===void 0?{}:{side:e.side},...e.disabled===void 0?{}:{disabled:e.disabled},...e.canTarget===void 0?{}:{canTarget:e.canTarget}}),this.selector.onChange.add(this.handleSelectorChange)}get stage(){return this.selector.stage}get attacker(){return this.selector.attacker}get target(){return this.selector.target}get preview(){return this.built}get elapsed(){return this.elapsed_}get finished(){return this.built!==null&&this.elapsed_>=this.built.duration}get frame(){return this.built?this.built.sampleAt(this.elapsed_):null}move(e){this.selector.move(e)}select(){return this.selector.select()}back(){this.selector.back()}update(e){return this.built?(this.elapsed_=Math.min(this.built.duration,this.elapsed_+Math.max(0,e)),this.frame):null}finish(){this.built&&(this.elapsed_=this.built.duration)}reset(){this.selector.reset(),this.built=null,this.elapsed_=0}},fz=class{constructor(){this.onChange=new p,this.planned=[],this.undone=[]}get plans(){return this.planned}get isEmpty(){return this.planned.length===0}get canUndo(){return this.planned.length>0}get canRedo(){return this.undone.length>0}plannedFor(e){return this.planned.find(t=>t.unit===e)}plan(e){let t=this.planned.findIndex(t=>t.unit===e.unit);t>=0?this.planned[t]=e:this.planned.push(e),this.undone=[],this.onChange.dispatch()}undo(){let e=this.planned.pop();return e?(this.undone.push(e),this.onChange.dispatch(),e):null}redo(){let e=this.undone.pop();return e?(this.planned=this.planned.filter(t=>t.unit!==e.unit),this.planned.push(e),this.onChange.dispatch(),e):null}clear(){(this.planned.length!==0||this.undone.length!==0)&&(this.planned=[],this.undone=[],this.onChange.dispatch())}commit(){let e=this.planned;return this.planned=[],this.undone=[],e.length>0&&this.onChange.dispatch(),e}},pz=class e{constructor(){this.counts=new Map}record(e,t,n=1){let r=this.counts.get(e)??new Map;r.set(t,(r.get(t)??0)+n),this.counts.set(e,r)}forType(e,t){return this.counts.get(e)?.get(t)??0}total(e){let t=this.counts.get(e);if(!t)return 0;let n=0;for(let e of t.values())n+=e;return n}breakdown(e){let t=this.counts.get(e);return t?[...t.entries()].map(([e,t])=>({unitType:e,count:t})):[]}toJSON(){return{counts:[...this.counts].map(([e,t])=>[e,[...t]])}}static fromJSON(t){let n=new e;for(let[e,r]of t.counts)n.counts.set(e,new Map(r));return n}},mz=l({AttackDialog:()=>dz,AttackPreview:()=>cz,BattleHooks:()=>oz,BattleStats:()=>pz,Creature:()=>ZR,Field:()=>sz,Party:()=>$R,StatStages:()=>nz,TypeMatrix:()=>QR,UnitSelector:()=>uz,Whiteboard:()=>fz,battleOrder:()=>ez,checkEvolution:()=>tz,chooseMove:()=>rz,chooseSwitch:()=>iz});function hz(e){let t=e.charCodeAt(0)-97,n=e.charCodeAt(1)-49;if(t<0||t>7||n<0||n>7||e.length!==2)throw Error(`not a square: "${e}"`);return n*8+t}function gz(e){return String.fromCharCode(97+(e&7))+String.fromCharCode(49+(e>>3))}function _z(e){let t=e.trim().split(/\s+/);if(t.length<4)throw Error(`not a FEN string: "${e}"`);let n=Array(64).fill(null),r=t[0].split(`/`);if(r.length!==8)throw Error(`a FEN placement needs 8 ranks: "${e}"`);if(r.forEach((t,r)=>{let i=7-r,a=0;for(let r of t)if(r>=`1`&&r<=`8`)a+=r.charCodeAt(0)-48;else{let o=r===r.toUpperCase()?`white`:`black`,s={p:`pawn`,n:`knight`,b:`bishop`,r:`rook`,q:`queen`,k:`king`}[r.toLowerCase()];if(!s||a>7)throw Error(`bad FEN rank "${t}" in "${e}"`);n[i*8+a]={side:o,kind:s},a++}if(a!==8)throw Error(`bad FEN rank "${t}" in "${e}"`)}),t[1]!==`w`&&t[1]!==`b`)throw Error(`a FEN side is "w" or "b": "${e}"`);let i={whiteKingside:!1,whiteQueenside:!1,blackKingside:!1,blackQueenside:!1};if(t[2]!==`-`)for(let n of t[2])if(n===`K`)i.whiteKingside=!0;else if(n===`Q`)i.whiteQueenside=!0;else if(n===`k`)i.blackKingside=!0;else if(n===`q`)i.blackQueenside=!0;else throw Error(`bad FEN castling "${t[2]}" in "${e}"`);let a=t[3]===`-`?null:hz(t[3]);if(a!==null){let n=t[1]===`w`?5:2;if(bz(a)!==n)throw Error(`bad FEN en passant square "${t[3]}" in "${e}"`)}let o={board:n,turn:t[1]===`w`?`white`:`black`,castling:i,enPassant:a};return kz(n,`white`),kz(n,`black`),o}function vz(e){return e===`white`?`black`:`white`}function yz(e){return e&7}function bz(e){return e>>3}function xz(e,t){return e>=0&&e<8&&t>=0&&t<8}function Sz(){let e=[`rook`,`knight`,`bishop`,`queen`,`king`,`bishop`,`knight`,`rook`],t=Array(64).fill(null);for(let n=0;n<8;n++)t[n]={side:`white`,kind:e[n]},t[8+n]={side:`white`,kind:`pawn`},t[48+n]={side:`black`,kind:`pawn`},t[56+n]={side:`black`,kind:e[n]};return{board:t,turn:`white`,castling:{whiteKingside:!0,whiteQueenside:!0,blackKingside:!0,blackQueenside:!0},enPassant:null}}function Cz(e){return{board:e.board.map(e=>e?{side:e.side,kind:e.kind}:null),turn:e.turn,castling:{...e.castling},enPassant:e.enPassant}}var wz=[[1,2],[2,1],[2,-1],[1,-2],[-1,-2],[-2,-1],[-2,1],[-1,2]],Tz=[[1,0],[1,1],[0,1],[-1,1],[-1,0],[-1,-1],[0,-1],[1,-1]],Ez=[[1,1],[-1,1],[-1,-1],[1,-1]],Dz=[[1,0],[0,1],[-1,0],[0,-1]];function Oz(e,t,n){let r=yz(t),i=bz(t),a=n===`white`?i-1:i+1;for(let t of[-1,1]){if(!xz(r+t,a))continue;let i=e[a*8+r+t];if(i&&i.side===n&&i.kind===`pawn`)return!0}for(let[t,a]of wz){if(!xz(r+t,i+a))continue;let o=e[(i+a)*8+r+t];if(o&&o.side===n&&o.kind===`knight`)return!0}for(let[t,a]of Tz){if(!xz(r+t,i+a))continue;let o=e[(i+a)*8+r+t];if(o&&o.side===n&&o.kind===`king`)return!0}let o=[{steps:Ez,kinds:[`bishop`,`queen`]},{steps:Dz,kinds:[`rook`,`queen`]}];for(let{steps:t,kinds:a}of o)for(let[o,s]of t){let t=r+o,c=i+s;for(;xz(t,c);){let r=e[c*8+t];if(r){if(r.side===n&&a.includes(r.kind))return!0;break}t+=o,c+=s}}return!1}function kz(e,t){let n=e.findIndex(e=>e!==null&&e.side===t&&e.kind===`king`);if(n===-1)throw Error(`a position without a ${t} king cannot be judged`);return n}function Az(e,t){return Oz(e.board,kz(e.board,t),vz(t))}function jz(e,t){let n=e.board[t];if(!n||n.side!==e.turn)return[];let r=[],i=yz(t),a=bz(t),o=o=>{for(let[s,c]of o){let o=i+s,l=a+c;for(;xz(o,l);){let i=l*8+o,a=e.board[i];if(!a)r.push({from:t,to:i});else{a.side!==n.side&&r.push({from:t,to:i});break}o+=s,l+=c}}};switch(n.kind){case`pawn`:{let o=n.side===`white`?1:-1,s=n.side===`white`?1:6,c=n.side===`white`?7:0;if(xz(i,a+o)&&!e.board[(a+o)*8+i]){let n=(a+o)*8+i;if(a+o===c)for(let e of[`knight`,`bishop`,`rook`,`queen`])r.push({from:t,to:n,promotion:e});else r.push({from:t,to:n}),a===s&&!e.board[(a+2*o)*8+i]&&r.push({from:t,to:(a+2*o)*8+i})}for(let s of[-1,1]){if(!xz(i+s,a+o))continue;let l=(a+o)*8+i+s,u=e.board[l];if(u&&u.side!==n.side){if(a+o===c)for(let e of[`knight`,`bishop`,`rook`,`queen`])r.push({from:t,to:l,promotion:e});else r.push({from:t,to:l})}else!u&&l===e.enPassant&&r.push({from:t,to:l,enPassantTake:a*8+i+s})}break}case`knight`:for(let[o,s]of wz){if(!xz(i+o,a+s))continue;let c=(a+s)*8+i+o,l=e.board[c];(!l||l.side!==n.side)&&r.push({from:t,to:c})}break;case`bishop`:o(Ez);break;case`rook`:o(Dz);break;case`queen`:o(Ez),o(Dz);break;case`king`:{for(let[o,s]of Tz){if(!xz(i+o,a+s))continue;let c=(a+s)*8+i+o,l=e.board[c];l&&l.side===n.side||l&&l.kind===`king`||r.push({from:t,to:c})}let o=n.side===`white`?0:56,s=n.side===`white`?{king:e.castling.whiteKingside,queen:e.castling.whiteQueenside}:{king:e.castling.blackKingside,queen:e.castling.blackQueenside};t===o+4&&!Az(e,n.side)&&(s.king&&!e.board[o+5]&&!e.board[o+6]&&!Oz(e.board,o+5,vz(n.side))&&!Oz(e.board,o+6,vz(n.side))&&r.push({from:t,to:o+6,castle:`kingside`}),s.queen&&!e.board[o+3]&&!e.board[o+2]&&!e.board[o+1]&&!Oz(e.board,o+3,vz(n.side))&&!Oz(e.board,o+2,vz(n.side))&&r.push({from:t,to:o+2,castle:`queenside`}));break}}return r}function Mz(e,t){let n=e.board[t.from];if(!n)throw Error(`no piece on ${gz(t.from)} to move`);let r=(e,t)=>{let n=e===`white`?0:56;return t===n||t===n+7};n.kind===`king`&&(n.side===`white`?e.castling.whiteKingside=e.castling.whiteQueenside=!1:e.castling.blackKingside=e.castling.blackQueenside=!1),n.kind===`rook`&&r(n.side,t.from)&&(e.castling[Nz(n.side,t.from)]=!1);let i=e.board[t.to];if(i&&i.kind===`rook`&&r(i.side,t.to)&&(e.castling[Nz(i.side,t.to)]=!1),e.board[t.to]=t.promotion?{side:n.side,kind:t.promotion}:n,e.board[t.from]=null,t.enPassantTake!==void 0&&(e.board[t.enPassantTake]=null),t.castle){let r=n.side===`white`?0:56;t.castle===`kingside`?(e.board[r+5]=e.board[r+7],e.board[r+7]=null):(e.board[r+3]=e.board[r],e.board[r]=null)}e.enPassant=n.kind===`pawn`&&Math.abs(t.to-t.from)===16?(t.from+t.to)/2:null,e.turn=vz(n.side)}function Nz(e,t){let n=yz(t)===7;return e===`white`?n?`whiteKingside`:`whiteQueenside`:n?`blackKingside`:`blackQueenside`}function Pz(e){let t=[];for(let n=0;n<64;n++)if(!(!e.board[n]||e.board[n]?.side!==e.turn))for(let r of jz(e,n)){let n=Cz(e);Mz(n,r),!Az(n,e.turn)&&t.push({from:r.from,to:r.to,...r.promotion?{promotion:r.promotion}:{}})}return t}function Fz(e,t){let n=e.board[t.from];if(!n||n.side!==e.turn)throw Error(`no ${e.turn} piece on ${gz(t.from)} to move`);let r=jz(e,t.from).find(e=>e.to===t.to&&(e.promotion??null)===(t.promotion??null));if(!r)throw Error(`${gz(t.from)}-${gz(t.to)} is not a legal move here`);let i=Cz(e);if(Mz(i,r),Az(i,e.turn))throw Error(`${gz(t.from)}-${gz(t.to)} leaves the king in check`);Mz(e,r)}function Iz(e){return Pz(e).length>0?`ongoing`:Az(e,e.turn)?e.turn===`white`?`black-wins`:`white-wins`:`stalemate`}var Lz=1e5;function Rz(e,t,n){if(!Number.isInteger(n.depth)||n.depth<1)throw RangeError(`depth must be a positive integer`);let r=n.maxNodes??Lz;if(!Number.isInteger(r)||r<1)throw RangeError(`maxNodes must be a positive integer`);let i=e.currentPlayer(t),a=0,o=0,s,c=(t,l,u,d)=>{if(n.signal?.aborted)return s=`cancelled`,0;if(++a>r)return s=`budget-exceeded`,0;let f=e.currentPlayer(t)===i;if(n.onNode?.(l,f),l===0||e.isTerminal(t))return e.evaluate(t,i);let p=e.moves(t);if(!p.length)return e.evaluate(t,i);let m=f?-1/0:1/0;for(let n of p){let r=c(e.apply(t,n),l-1,u,d);if(s)return r;if(f?(m=Math.max(m,r),u=Math.max(u,m)):(m=Math.min(m,r),d=Math.min(d,m)),d<=u){o++;break}}return m},l=e.moves(t),u=null,d=e.evaluate(t,i);if(!e.isTerminal(t)&&l.length){let r=e.currentPlayer(t)===i,a=r?-1/0:1/0,o=-1/0,f=1/0;for(let i of l){let l=c(e.apply(t,i),n.depth-1,o,f);if(s)break;(u===null||(r?l>a:l<a))&&(u=i,a=l),r?o=Math.max(o,a):f=Math.min(f,a)}u!==null&&(d=a)}return{move:s?null:u,score:d,depth:n.depth,nodes:a,cutoffs:o,status:s??`complete`,state:t}}var zz=1e5,Bz={pawn:100,knight:320,bishop:330,rook:500,queen:900,king:0};function Vz(e,t={}){return Hz(e,t).move}function Hz(e,t={}){let n=Rz(Uz,e,{depth:Math.max(1,Math.floor(t.depth??3)),maxNodes:t.maxNodes===void 0?1e5:Math.max(1,Math.floor(t.maxNodes))});return{move:n.move,score:n.score,nodes:n.nodes}}var Uz={currentPlayer:e=>e.turn===`white`?1:-1,moves:e=>Kz(e,Pz(e)),apply:(e,t)=>{let n=Cz(e);return Fz(n,t),n},isTerminal:e=>Iz(e)!==`ongoing`,evaluate:(e,t)=>Iz(e)===`ongoing`?Wz(e,t):Gz(e,t)};function Wz(e,t){let n=0;for(let t of e.board)t&&(n+=(t.side===`white`?1:-1)*Bz[t.kind]);return t===1?n:-n}function Gz(e,t){let n=Iz(e);return n===`stalemate`||!Az(e,e.turn)?0:(n===`white-wins`?1:-1)===t?zz:-1e5}function Kz(e,t){return t.slice().sort((t,n)=>qz(e,n)-qz(e,t))}function qz(e,t){let n=e.board[t.to];return(t.promotion?Bz[t.promotion]:0)*10+(n?Bz[n.kind]:0)}var Jz=class{constructor(e,t,n){if(this.width=e,this.height=t,e<1||t<1)throw Error(`a board needs positive dimensions`);if(n&&n.length!==e*t)throw Error(`board cell count does not match dimensions`);this.cells=n?[...n]:Array(e*t).fill(null)}index(e,t){if(!this.inside(e,t))throw Error(`cell (${e},${t}) is outside the board`);return t*this.width+e}inside(e,t){return e>=0&&t>=0&&e<this.width&&t<this.height}get(e,t){return this.cells[this.index(e,t)]}set(e,t,n){this.cells[this.index(e,t)]=n}move(e,t){let n=this.get(e.x,e.y);if(n===null)throw Error(`cannot move an empty cell`);return this.set(e.x,e.y,null),this.set(t.x,t.y,n),n}};function Yz(){let e=Array(64).fill(null);for(let t=0;t<3;t++)for(let n=0;n<8;n++)(n+t)%2&&(e[t*8+n]={side:`black`,king:!1});for(let t=5;t<8;t++)for(let n=0;n<8;n++)(n+t)%2&&(e[t*8+n]={side:`red`,king:!1});return{board:e,turn:`red`,forcedFrom:null}}function Xz(e){let t=e.forcedFrom===null?e.board.map((t,n)=>t?.side===e.turn?n:-1).filter(e=>e>=0):[e.forcedFrom],n=t.flatMap(t=>Qz(e,t,!0));return n.length>0?n:e.forcedFrom===null?t.flatMap(t=>Qz(e,t,!1)):[]}function Zz(e,t){if(!Xz(e).some(e=>e.from===t.from&&e.to===t.to&&e.captures.length===t.captures.length))throw Error(`illegal checkers move`);let n=e.board[t.from];if(!n)throw Error(`no checkers piece on the source cell`);e.board[t.from]=null;for(let n of t.captures)e.board[n]=null;let r=!n.king&&(n.side===`red`&&Math.floor(t.to/8)===0||n.side===`black`&&Math.floor(t.to/8)===7);e.board[t.to]={...n,king:n.king||r};let i={board:e.board,turn:e.turn,forcedFrom:t.captures.length>0?t.to:null};t.captures.length===0||Qz(i,t.to,!0).length===0?(e.turn=e.turn===`red`?`black`:`red`,e.forcedFrom=null):e.forcedFrom=t.to}function Qz(e,t,n){let r=e.board[t];if(!r)return[];let i=t%8,a=Math.floor(t/8),o=r.king?[-1,1]:r.side===`red`?[-1]:[1],s=[];for(let c of o)for(let o of[-1,1]){let l=i+o,u=a+c,d=i+o*2,f=a+c*2;if(n){if(d<0||f<0||d>=8||f>=8)continue;let n=u*8+l,i=f*8+d;e.board[n]?.side!==r.side&&e.board[n]&&!e.board[i]&&s.push({from:t,to:i,captures:[n]})}else l>=0&&u>=0&&l<8&&u<8&&!e.board[u*8+l]&&s.push({from:t,to:u*8+l,captures:[]})}return s}function $z(e=9){if(e<2||e>25)throw Error(`Go size must be between 2 and 25`);return{size:e,board:Array(e*e).fill(null),turn:`black`,ko:null,passes:0}}function eB(e,t,n){let r=iB(e,t,n);if(e.board[r]||e.ko===r)throw Error(`Go cell is occupied or forbidden by ko`);let i=[...e.board];i[r]=e.turn;let a=e.turn===`black`?`white`:`black`,o=0,s=null;for(let t of aB(e.size,r)){if(i[t]!==a||sB(i,e.size,t)!==0)continue;let n=oB(i,e.size,t);n.length===1&&(s=n[0]);for(let e of n)i[e]=null;o+=n.length}if(sB(i,e.size,r)===0)throw Error(`suicide is not a legal Go move`);e.ko=o===1&&sB(i,e.size,r)===1?s:null,e.board=i,e.turn=a,e.passes=0}function tB(e){e.turn=e.turn===`black`?`white`:`black`,e.ko=null,e.passes++}function nB(e){return e.passes>=2?`finished`:`ongoing`}function rB(e){let t={black:0,white:0},n=new Set;for(let r=0;r<e.board.length;r++){let i=e.board[r];if(i)t[i]++;else if(!n.has(r)){let i=oB(e.board,e.size,r),a=new Set;for(let t of i)for(let n of aB(e.size,t))e.board[n]&&a.add(e.board[n]);for(let e of i)n.add(e);a.size===1&&(t[[...a][0]]+=i.length)}}return t}function iB(e,t,n){if(t<0||n<0||t>=e.size||n>=e.size)throw Error(`Go cell is outside the board`);return n*e.size+t}function aB(e,t){let n=t%e,r=Math.floor(t/e),i=[];return n>0&&i.push(t-1),n<e-1&&i.push(t+1),r>0&&i.push(t-e),r<e-1&&i.push(t+e),i}function oB(e,t,n){let r=e[n],i=[],a=[n],o=new Set;for(;a.length;){let n=a.pop();if(!(o.has(n)||e[n]!==r)){o.add(n),i.push(n);for(let e of aB(t,n))a.push(e)}}return i}function sB(e,t,n){let r=oB(e,t,n),i=new Set;for(let n of r)for(let r of aB(t,n))e[r]===null&&i.add(r);return i.size}function cB(){let e=Array(24).fill(0);return e[0]=2,e[11]=5,e[16]=3,e[18]=5,e[23]=-2,e[12]=-5,e[7]=-3,e[5]=-5,{points:e,bar:{white:0,black:0},off:{white:0,black:0},turn:`white`}}function lB(){let e=CB(2,6);return e[0]===e[1]?[...e,...e]:e}function uB(e,t){let n=e.turn===`white`?1:-1,r=n===1?[18,23]:[0,5],i=e=>n===1?24-e:e+1,a=!0,o=1/0;for(let t=0;t<24;t++)e.points[t]*n<=0||((t<r[0]||t>r[1])&&(a=!1),o=Math.min(o,i(t)));let s=(e,t)=>{if(!a)return!1;let n=i(e);return t===n||t>n&&n===o},c=[];for(let r of t){if(e.bar[e.turn]>0){let t=e.turn===`white`?r-1:24-r;fB(e,t,n)&&c.push({from:`bar`,to:t,die:r});continue}for(let t=0;t<24;t++)if(e.points[t]*n>0){let i=t+r*n;i<0||i>=24?s(t,r)&&c.push({from:t,to:`off`,die:r}):fB(e,i,n)&&c.push({from:t,to:i,die:r})}}return c}function dB(e,t){if(!uB(e,[t.die]).some(e=>e.from===t.from&&e.to===t.to))throw Error(`illegal backgammon move`);let n=e.turn===`white`?1:-1;if(t.from===`bar`?e.bar[e.turn]--:e.points[t.from]-=n,t.to===`off`)e.off[e.turn]++;else{if(e.points[t.to]*n<0){let n=e.turn===`white`?`black`:`white`;e.points[t.to]=0,e.bar[n]++}e.points[t.to]+=n}}function fB(e,t,n){return e.points[t]*n>=-1}function pB(e=0){let t=[`clubs`,`diamonds`,`hearts`,`spades`],n=[];for(let e of t)for(let t=1;t<=13;t++)n.push({suit:e,rank:t});return n.concat(Array(e).fill(null).map(()=>({suit:`spades`,rank:1})))}function mB(e){return le(e)}function hB(e,t,n){if(t<0||n<0||e.length<t*n)throw Error(`not enough cards to deal`);return Array.from({length:t},()=>e.splice(0,n))}function gB(e,t){if(e.length===0)throw Error(`a trick needs at least one play`);let n=e[0].card.suit,r=e=>e.rank===1?14:e.rank;return(t&&e.some(e=>e.card.suit===t)?e.filter(e=>e.card.suit===t):e.filter(e=>e.card.suit===n)).reduce((e,t)=>r(t.card)>r(e.card)?t:e).owner}function _B(e){let t=pB();return e===void 0?mB(t):ne(e,()=>mB(t)),{stock:t,waste:[],tableau:Array.from({length:7},(e,n)=>({down:t.splice(0,6-n),up:t.splice(0,1)})),foundations:[[],[],[],[]]}}function vB(e){e.stock.length===0&&(e.stock=e.waste.reverse(),e.waste=[]);let t=e.stock.pop()??null;return t&&e.waste.push(t),t}function yB(e,t,n,r=1){let i=e.tableau[t],a=e.tableau[n],o=i?.up.slice(-r);if(!i||!a||!o?.length||(a.up.length===0?o[0].rank!==13:!SB(o[0],a.up.at(-1))))throw Error(`illegal solitaire tableau move`);i.up.splice(-r,r),a.up.push(...o),i.down.length&&i.up.length===0&&i.up.push(i.down.pop())}function bB(e,t){let n=t===`waste`?e.waste.at(-1):e.tableau[t].up.at(-1);if(!n)throw Error(`no solitaire card to move`);let r=e.foundations.find(e=>e[0]?.suit===n.suit||e.length===0);if(!r||n.rank!==r.length+1)throw Error(`card cannot move to its foundation`);if(t===`waste`)e.waste.pop();else{let n=e.tableau[t];n.up.pop(),n.down.length&&n.up.length===0&&n.up.push(n.down.pop())}r.push(n)}function xB(e){return e.foundations.every(e=>e.length===13)}function SB(e,t){let n=e.suit===`diamonds`||e.suit===`hearts`,r=t.suit===`diamonds`||t.suit===`hearts`;return e.rank===t.rank-1&&n!==r}function CB(e,t){if(!Number.isInteger(e)||e<0||!Number.isInteger(t)||t<1)throw Error(`dice need a non-negative count and positive sides`);return Array.from({length:e},()=>ie(1,t))}function wB(e){let t=/^(\d+)d(\d+)([+-]\d+)?$/i.exec(e.trim());if(!t)throw Error(`bad dice expression: "${e}"`);return CB(Number(t[1]),Number(t[2])).reduce((e,t)=>e+t,Number(t[3]??0))}var TB=class{constructor(e,t){this.kept=new Set,this.count=e,this.sides=t,this.values=CB(e,t)}reRoll(){for(let e=0;e<this.values.length;e++)this.kept.has(e)||(this.values[e]=ie(1,this.sides))}keep(e){if(e<0||e>=this.count)throw Error(`die index is outside the cup`);this.kept.add(e)}clearKept(){this.kept.clear()}};function EB(e,t){if(e.length!==5||e.some(e=>e<1||e>6))throw Error(`a score sheet needs five d6 values`);let n=new Map;for(let t of e)n.set(t,(n.get(t)??0)+1);let r=e.reduce((e,t)=>e+t,0);if(t===`chance`)return r;if(t===`yahtzee`)return n.size===1?50:0;if(t===`fullHouse`)return[...n.values()].sort().join(`,`)===`2,3`?25:0;if(t===`threeKind`)return[...n.values()].some(e=>e>=3)?r:0;if(t===`fourKind`)return[...n.values()].some(e=>e>=4)?r:0;if(t===`smallStraight`||t===`largeStraight`){let e=[`1234`,`2345`,`3456`],r=[`12345`,`23456`],i=[...n.keys()].sort().join(``);return(t===`smallStraight`?e:r).some(e=>i.includes(e))?t===`smallStraight`?30:40:0}let i=[`ones`,`twos`,`threes`,`fours`,`fives`,`sixes`].indexOf(t)+1;return i>0?(n.get(i)??0)*i:0}function DB(e,t,n=`hex`){if(e<1||t<1)throw Error(`a tactical map needs positive dimensions`);return{width:e,height:t,shape:n,cells:Array.from({length:e*t},()=>({passable:!0,cover:0})),units:[],turn:``,round:1}}function OB(e,t,n){return RB(e,t,n)&&!LB(e,t,n)}function kB(e,t){if(!OB(e,t.x,t.y))throw Error(`tactical unit cannot be placed there`);e.units.push({...t,maxActions:t.maxActions??t.actions}),e.turn||=t.owner}function AB(e,t){let n=IB(e,t);if(n.owner!==e.turn||n.actions<=0)return[];let r=HB(e,n,VB(e,n)),i=[];for(let a=0;a<e.height;a++)for(let o=0;o<e.width;o++){if(o===n.x&&a===n.y||!e.cells[a*e.width+o].passable||LB(e,o,a))continue;let s=UB(e,n,o,a,n.actions,r);s!==null&&i.push({unit:t,x:o,y:a,cost:s})}return i}function jB(e,t){let n=AB(e,t.unit).find(e=>e.x===t.x&&e.y===t.y);if(!n)throw Error(`illegal tactical move`);let r=IB(e,t.unit);r.x=t.x,r.y=t.y,r.actions-=n.cost}function MB(e,t){let n=IB(e,t);if(n.owner!==e.turn||n.actions<=0)throw Error(`only an active unit can enter overwatch`);n.actions=0,n.overwatch=!0}function NB(e,t,n){let r=IB(e,t),i=[];for(let t of[...e.units]){if(!t.overwatch||t.owner===r.owner||BB(e,t,r)>3)continue;let a=e.cells[r.y*e.width+r.x].cover??0,o=Math.max(0,n-a);if(r.hp=Math.max(0,r.hp-o),t.overwatch=!1,i.push({attacker:t.id,defender:r.id,damage:o,cover:a,killed:r.hp===0}),r.hp===0){e.units=e.units.filter(e=>e!==r);break}}return i}function PB(e,t,n,r){let i=IB(e,t),a=IB(e,n);if(i.owner!==e.turn||i.owner===a.owner)throw Error(`invalid tactical attack`);if(BB(e,i,a)>3)throw Error(`tactical target is out of range`);let o=e.cells[a.y*e.width+a.x].cover??0,s=Math.max(0,r-o);a.hp=Math.max(0,a.hp-s);let c=a.hp===0;return c&&(e.units=e.units.filter(e=>e!==a)),{attacker:t,defender:n,damage:s,cover:o,killed:c}}function FB(e){let t=[...new Set(e.units.map(e=>e.owner))];if(t.length===0)return;let n=t.indexOf(e.turn)+1;n>=t.length&&e.round++,e.turn=t[n%t.length];for(let t of e.units)t.owner===e.turn&&(t.actions=t.maxActions??t.actions,t.overwatch=!1)}function IB(e,t){let n=e.units.find(e=>e.id===t);if(!n)throw Error(`unknown tactical unit "${t}"`);return n}function LB(e,t,n){return e.units.some(e=>e.x===t&&e.y===n)}function RB(e,t,n){return t>=0&&n>=0&&t<e.width&&n<e.height}function zB(e,t,n){return e.shape===`hex`?cn(t,n):[{x:t-1,y:n},{x:t+1,y:n},{x:t,y:n-1},{x:t,y:n+1}]}function BB(e,t,n){return e.shape===`hex`?ln(t,n):Math.abs(t.x-n.x)+Math.abs(t.y-n.y)}function VB(e,t){return new Set(e.units.filter(n=>n.owner!==t.owner&&zB(e,t.x,t.y).some(e=>e.x===n.x&&e.y===n.y)).map(e=>e.id))}function HB(e,t,n){let r=new Set;for(let i of e.units)if(!(i.owner===t.owner||n.has(i.id)))for(let t of zB(e,i.x,i.y))r.add(`${t.x},${t.y}`);return r}function UB(e,t,n,r,i,a){let o=[{x:t.x,y:t.y,distance:0}],s=0,c=new Set([`${t.x},${t.y}`]);for(;s<o.length;){let t=o[s++];if(t.x===n&&t.y===r)return t.distance;if(!(t.distance>=i||t.distance>0&&a.has(`${t.x},${t.y}`)))for(let i of zB(e,t.x,t.y)){let a=`${i.x},${i.y}`;!RB(e,i.x,i.y)||c.has(a)||!e.cells[i.y*e.width+i.x].passable||LB(e,i.x,i.y)&&(i.x!==n||i.y!==r)||(c.add(a),o.push({x:i.x,y:i.y,distance:t.distance+1}))}}return null}var WB=class{constructor(e,t){if(this.visible=new Map,this.explored=new Map,this.shared=new Map,e<1||t<1)throw Error(`fog needs positive dimensions`);this.width=e,this.height=t}share(e){let t=[...new Set(e)].filter(e=>!!e);if(t.length===0)return;let n=new Set(t);for(let e of t)for(let t of this.shared.get(e)??[])n.add(t);for(let e of n)this.shared.set(e,n)}sync(e,t,n){if(!e)throw Error(`fog needs a faction id`);let r=new Set;for(let e of t)for(let t of n(e))this.inside(t.x,t.y)&&r.add(this.index(t.x,t.y));this.visible.set(e,r);let i=this.explored.get(e)??new Set;for(let e of r)i.add(e);this.explored.set(e,i)}reveal(e,t){if(!e)throw Error(`fog needs a faction id`);let n=this.explored.get(e)??new Set;for(let e of t)this.inside(e.x,e.y)&&n.add(this.index(e.x,e.y));this.explored.set(e,n)}isVisible(e,t,n){return this.seenBy(this.visible,e,this.index(t,n))}sees(e){return(t,n)=>this.isVisible(e,t,n)}isExplored(e,t,n){return this.seenBy(this.explored,e,this.index(t,n))}visibleCells(e){return this.cellsSeenBy(this.visible,e)}exploredCells(e){return this.cellsSeenBy(this.explored,e)}seenBy(e,t,n){let r=this.shared.get(t);if(!r)return e.get(t)?.has(n)??!1;for(let t of r)if(e.get(t)?.has(n))return!0;return!1}cellsSeenBy(e,t){let n=this.shared.get(t);if(!n)return[...e.get(t)??[]];let r=new Set;for(let t of n)for(let n of e.get(t)??[])r.add(n);return[...r].sort((e,t)=>e-t)}inside(e,t){return e>=0&&t>=0&&e<this.width&&t<this.height}index(e,t){return this.inside(e,t)?t*this.width+e:-1}};function GB(e){return{currency:e,pool:[]}}function KB(e,t,n,r){return e.currency<r||!OB(t,n.x,n.y)?!1:(kB(t,n),e.currency-=r,!0)}function qB(e,t,n,r,i){let a=e.pool.findIndex(e=>e.id===n);return a===-1||!OB(t,r,i)?!1:(kB(t,{...e.pool[a],x:r,y:i}),e.pool.splice(a,1),!0)}function JB(e,t,n){let r=t.units.findIndex(e=>e.id===n);if(r===-1)return!1;let{x:i,y:a,...o}=t.units[r];return e.pool.push(o),t.units.splice(r,1),!0}function YB(e,t,n){return e.units.filter(e=>e.owner===t).length*(n.incomePerUnit-n.upkeepPerUnit)}function XB(e,t,n,r){return e.currency+=YB(t,n,r),e.currency}function ZB(e,t,n,r){if(e<1||t<1)throw Error(`a skirmish map needs positive dimensions`);let i=r??Object.keys(n)[0];if(!i||!n[i])throw Error(`a skirmish map needs at least one terrain kind`);return{width:e,height:t,terrainTable:n,cells:Array.from({length:e*t},()=>({terrain:i})),units:[],turn:``,round:1}}function QB(e,t,n,r,i=!1){if(!cV(e,t,n))throw Error(`cell is outside the skirmish map`);if(!e.terrainTable[r])throw Error(`unknown skirmish terrain "${r}"`);e.cells[n*e.width+t]=i?{terrain:r,village:!0}:{terrain:r}}function $B(e,t,n){return cV(e,t,n)&&dV(e,t,n)<1/0&&!lV(e,t,n)}function eV(e,t){if(!$B(e,t.x,t.y))throw Error(`skirmish unit cannot be placed there`);e.units.push({...t,remainingMoves:t.moves}),e.turn||=t.owner}function tV(e,t){let n=sV(e,t),r=n.remainingMoves??n.moves;if(n.owner!==e.turn||r<=0)return[];let i=new Set(e.units.filter(e=>e.id!==n.id).map(e=>`${e.x},${e.y}`)),a=fV(e,n,r,i),o=[];for(let s=0;s<e.height;s++)for(let c=0;c<e.width;c++){if(c===n.x&&s===n.y||dV(e,c,s)===1/0||i.has(`${c},${s}`))continue;let l=a.get(`${c},${s}`);l!==void 0&&l<=r&&o.push({unit:t,x:c,y:s,cost:l})}return o}function nV(e,t){let n=tV(e,t.unit).find(e=>e.x===t.x&&e.y===t.y);if(!n)throw Error(`illegal skirmish move`);let r=sV(e,t.unit);r.x=t.x,r.y=t.y,r.remainingMoves=(r.remainingMoves??r.moves)-n.cost;let i=e.cells[t.y*e.width+t.x];i.village&&(i.owner=r.owner)}function rV(e,t,n){let r=sV(e,t),i=sV(e,n);if(r.owner!==e.turn||r.owner===i.owner)throw Error(`invalid skirmish attack`);if(ln(r,i)!==1)throw Error(`skirmish combat is adjacency-only`);let a=[iV(e,r,i)];return i.hp>0&&a.push(iV(e,i,r)),e.units=e.units.filter(e=>e.hp>0),{strikes:a}}function iV(e,t,n){let r=uV(e,n.x,n.y).defense,i=oe(Math.max(0,Math.min(1,t.hitChance*(1-r)))),a=i?Math.min(t.attack,n.hp):0;return n.hp-=a,{attacker:t.id,defender:n.id,hit:i,damage:a,killed:n.hp<=0}}function aV(e,t,n,r){return n+e.cells.filter(e=>e.village&&e.owner===t).length*r}function oV(e,t=0){let n=[...new Set(e.units.map(e=>e.owner))];if(n.length===0)return;let r=n.indexOf(e.turn)+1;r>=n.length&&e.round++,e.turn=n[r%n.length];for(let n of e.units){if(n.owner!==e.turn)continue;n.remainingMoves=n.moves;let r=e.cells[n.y*e.width+n.x];r.village&&r.owner===n.owner&&t>0&&(n.hp=Math.min(n.maxHp,n.hp+t))}}function sV(e,t){let n=e.units.find(e=>e.id===t);if(!n)throw Error(`unknown skirmish unit "${t}"`);return n}function cV(e,t,n){return t>=0&&n>=0&&t<e.width&&n<e.height}function lV(e,t,n){return e.units.some(e=>e.x===t&&e.y===n)}function uV(e,t,n){return e.terrainTable[e.cells[n*e.width+t].terrain]}function dV(e,t,n){return uV(e,t,n).moveCost}function fV(e,t,n,r){let i=[],a=(e,t)=>{[i[e],i[t]]=[i[t],i[e]]},o=e=>{i.push(e);let t=i.length-1;for(;t>0;){let e=t-1>>1;if(i[e].cost<=i[t].cost)break;a(t,e),t=e}},s=()=>{if(i.length===0)return;let e=i[0],t=i.pop();if(i.length>0){i[0]=t;let e=0;for(;;){let t=e*2+1,n=t+1,r=e;if(t<i.length&&i[t].cost<i[r].cost&&(r=t),n<i.length&&i[n].cost<i[r].cost&&(r=n),r===e)break;a(e,r),e=r}}return e},c=new Map([[`${t.x},${t.y}`,0]]);for(o({x:t.x,y:t.y,cost:0});;){let t=s();if(t===void 0)break;let i=`${t.x},${t.y}`;if(!(t.cost>(c.get(i)??1/0)))for(let i of cn(t.x,t.y)){if(!cV(e,i.x,i.y))continue;let a=dV(e,i.x,i.y);if(a===1/0||r.has(`${i.x},${i.y}`))continue;let s=t.cost+a;if(s>n)continue;let l=`${i.x},${i.y}`;s<(c.get(l)??1/0)&&(c.set(l,s),o({x:i.x,y:i.y,cost:s}))}}return c}var pV=l({BoardGrid:()=>Jz,DiceCup:()=>TB,FactionFog:()=>WB,addSkirmishUnit:()=>eV,addTacticalUnit:()=>kB,applyBackgammonMove:()=>dB,applyCheckersMove:()=>Zz,applyMove:()=>Fz,applyUpkeep:()=>XB,armyIncome:()=>YB,backgammonMoves:()=>uB,bankUnit:()=>JB,canPlaceSkirmishUnit:()=>$B,canPlaceTacticalUnit:()=>OB,checkersMoves:()=>Xz,chessGame:()=>Uz,chooseMove:()=>Vz,cloneChess:()=>Cz,createDeck:()=>pB,deal:()=>hB,dealSolitaire:()=>_B,drawSolitaire:()=>vB,endSkirmishTurn:()=>oV,endTacticalTurn:()=>FB,gameResult:()=>Iz,goResult:()=>nB,goScore:()=>rB,inCheck:()=>Az,legalMoves:()=>Pz,moveSkirmishUnit:()=>nV,moveSolitaireTableau:()=>yB,moveSolitaireToFoundation:()=>bB,moveTacticalUnit:()=>jB,parseFen:()=>_z,passGo:()=>tB,playGo:()=>eB,recall:()=>qB,recruit:()=>KB,rollBackgammonDice:()=>lB,rollDice:()=>CB,rollExpression:()=>wB,scoreDice:()=>EB,search:()=>Hz,setSkirmishTerrain:()=>QB,setTacticalOverwatch:()=>MB,shuffleDeck:()=>mB,skirmishAttack:()=>rV,skirmishIncome:()=>aV,skirmishMoves:()=>tV,solitaireWon:()=>xB,sq:()=>hz,squareName:()=>gz,startingArmy:()=>GB,startingBackgammon:()=>cB,startingCheckers:()=>Yz,startingChess:()=>Sz,startingGo:()=>$z,startingSkirmish:()=>ZB,startingTactics:()=>DB,tacticalAttack:()=>PB,tacticalMoves:()=>AB,trickWinner:()=>gB,triggerTacticalOverwatch:()=>NB});function mV(e){return new Audio(SA(e))}var hV=new p,gV=class{constructor(e,t={}){this.next=0;let n=Math.max(1,t.poolSize??4),r=t.create??mV;this.volume=t.volume??1,this.caption=t.caption,this.pool=Array.from({length:n},()=>r(e))}play(e=1){let t=this.pool[this.next];this.next=(this.next+1)%this.pool.length,t.volume=this.volume*e,t.currentTime=0,Promise.resolve(t.play()).catch(()=>{}),this.caption&&hV.dispatch({text:this.caption})}stopAll(){for(let e of this.pool)e.pause(),e.currentTime=0}},_V=class{constructor(e={}){this.current=null,this.fades=[],this.trackQueue=null,this.playlistFade=1,this.volume=e.volume??1,this.create=e.create??mV}play(e,t=1){this.trackQueue=null,this.start(e,t,!0)}playTracks(e,t=1){if(e.length===0){this.stop(t);return}this.trackQueue=[...e],this.playlistFade=t,this.startNextTrack()}startNextTrack(){if(!this.trackQueue?.length)return;let e=this.trackQueue.shift();this.trackQueue.push(e),this.start(e,this.playlistFade,!1)}start(e,t,n){let r=this.create(e);r.loop=n,!n&&r.onended!==void 0&&(r.onended=()=>{this.current===r&&this.startNextTrack()});let i=this.current;if(this.current=r,t<=0){r.volume=this.volume,Promise.resolve(r.play()).catch(()=>{}),i?.pause();return}r.volume=0,Promise.resolve(r.play()).catch(()=>{}),this.fades.push({audio:r,elapsed:0,duration:t,from:0,to:this.volume,stopAtEnd:!1}),i&&this.fades.push({audio:i,elapsed:0,duration:t,from:i.volume,to:0,stopAtEnd:!0})}stop(e=1){this.trackQueue=null;let t=this.current;if(t){if(this.current=null,e<=0){t.pause();return}this.fades.push({audio:t,elapsed:0,duration:e,from:t.volume,to:0,stopAtEnd:!0})}}update(e){for(let t of[...this.fades]){t.elapsed+=e;let n=Math.min(1,t.elapsed/t.duration);t.audio.volume=t.from+(t.to-t.from)*n,n>=1&&(this.fades.splice(this.fades.indexOf(t),1),t.stopAtEnd&&(t.audio.pause(),t.audio.currentTime=0))}}},vV=class{constructor(e){this.states=new Map,this.cues=new Map,this.currentTrack=null,this.music=e}define(e,t){this.states.set(e,t)}enter(e){let t=this.states.get(e);if(!t)throw Error(`Orchestrator: no state defined for "${e}"`);t.track!==this.currentTrack&&(this.music.play(t.track,t.fadeDuration),this.currentTrack=t.track)}on(e,t){this.cues.set(e,t)}trigger(e){this.cues.get(e)?.play()}};function yV(e={}){let t=e.waveform??`square`,n=e.frequency??440,r=e.duration??.15,i=e.volume??.3,a=e.decay??8,o=e.sampleRate??22050,s=e.seed??1;if(!(r>0))throw Error(`tone duration must be positive`);if(t!==`noise`&&!(n>0))throw Error(`tone frequency must be positive`);if(!(o>0))throw Error(`tone sample rate must be positive`);let c=Math.max(1,Math.round(r*o)),l=new Float32Array(c);for(let e=0;e<c;e++){let r=e/o,u=a>0?Math.exp(-a*e/c):1,d=2*Math.PI*n*r;l[e]=i*u*xV(t,d,s,e)}return CV(l,o)}function bV(e={},t=e=>new Audio(e)){let n=t(yV(e));return Promise.resolve(n.play()).catch(()=>{}),n}function xV(e,t,n,r){switch(e){case`sine`:return Math.sin(t);case`square`:return Math.sin(t)>=0?1:-1;case`triangle`:{let e=t/(2*Math.PI),n=e-Math.floor(e);return 4*Math.abs(n-.5)-1}case`noise`:return SV(n,r)}}function SV(e,t){let n=Math.imul(e^t,2654435761)>>>0;return n=Math.imul(n^n>>>15,2246822519)>>>0,n=Math.imul(n^n>>>13,3266489917)>>>0,n^=n>>>16,(n>>>0)/4294967295*2-1}function CV(e,t){let n=e.length*2,r=new ArrayBuffer(44+n),i=new DataView(r);wV(i,0,`RIFF`),i.setUint32(4,36+n,!0),wV(i,8,`WAVE`),wV(i,12,`fmt `),i.setUint32(16,16,!0),i.setUint16(20,1,!0),i.setUint16(22,1,!0),i.setUint32(24,t,!0),i.setUint32(28,t*2,!0),i.setUint16(32,2,!0),i.setUint16(34,16,!0),wV(i,36,`data`),i.setUint32(40,n,!0);let a=44;for(let t of e){let e=Math.max(-1,Math.min(1,t));i.setInt16(a,Math.round(e*(e<0?32768:32767)),!0),a+=2}let o=``,s=new Uint8Array(r);for(let e of s)o+=String.fromCharCode(e);return`data:audio/wav;base64,${btoa(o)}`}function wV(e,t,n){for(let r=0;r<n.length;r++)e.setUint8(t+r,n.charCodeAt(r))}var TV=5e5;function EV(e){let t=e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength),n=new DataView(t.buffer,t.byteOffset,t.byteLength),r=0,i=e=>{let n=``;for(let i=0;i<e;i++)n+=String.fromCharCode(t[r+i]);return r+=e,n},a=()=>{let e=n.getUint32(r,!1);return r+=4,e},o=()=>{let e=n.getUint16(r,!1);return r+=2,e},s=()=>{let e=0;for(;;){let n=t[r++];if(e=e<<7|n&127,!(n&128))return e}};if(i(4)!==`MThd`||a()!==6)throw Error(`invalid MIDI header chunk`);let c=o(),l=o(),u=o();if(c!==0&&c!==1)throw Error(`unsupported MIDI format ${c}`);if(u&32768)throw Error(`SMPTE-based MIDI timing is not supported`);let d=u,f=[];for(let e=0;e<l;e++){let e=i(4),n=a();if(e!==`MTrk`){r+=n;continue}let o=r+n,c=0,l=0;for(;r<o;){c+=s();let e=t[r];if(e<128?e=l:(r++,e<240&&(l=e)),e===255){let e=t[r++],n=s();if(e===81&&n===3){let e=t[r]<<16|t[r+1]<<8|t[r+2];f.push({tick:c,type:`tempo`,microsecondsPerQuarter:e})}r+=n}else if(e===240||e===247)r+=s();else{let n=e&240,i=e&15;if(n===128||n===144){let e=t[r++],a=t[r++],o=n===144&&a>0;f.push({tick:c,type:o?`noteOn`:`noteOff`,note:e,velocity:a,channel:i})}else if(n===160||n===176||n===224)r+=2;else if(n===192||n===208)r+=1;else throw Error(`unsupported MIDI status byte 0x${e.toString(16)}`)}}}return f.sort((e,t)=>e.tick-t.tick),{ticksPerQuarter:d,events:f}}function DV(e){let t=[],n=new Map,r=TV,i=0,a=0;for(let o of e.events){if(a+=(o.tick-i)*r/e.ticksPerQuarter/1e6,i=o.tick,o.type===`tempo`){r=o.microsecondsPerQuarter;continue}let s=`${o.channel}:${o.note}`;if(o.type===`noteOn`)n.set(s,{time:a,velocity:o.velocity});else{let e=n.get(s);e&&(t.push({time:e.time,duration:Math.max(.01,a-e.time),note:o.note,velocity:e.velocity,channel:o.channel}),n.delete(s))}}for(let[e,r]of n){let[n,i]=e.split(`:`).map(Number);t.push({time:r.time,duration:.3,note:i,velocity:r.velocity,channel:n})}return t.sort((e,t)=>e.time-t.time)}function OV(e){return 440*2**((e-69)/12)}var kV=class{constructor(e,t={}){this.elapsed=0,this.index=0,this.playing=!1,this.notes=DV(e),this.playFn=t.play??bV,this.waveform=t.waveform??`square`,this.volume=t.volume??.2}play(){this.playing=this.index<this.notes.length}pause(){this.playing=!1}stop(){this.playing=!1,this.elapsed=0,this.index=0}update(e){if(this.playing){for(this.elapsed+=e;this.index<this.notes.length&&this.notes[this.index].time<=this.elapsed;){let e=this.notes[this.index];this.playFn({waveform:this.waveform,frequency:OV(e.note),duration:e.duration,volume:this.volume*(e.velocity/127)}),this.index++}this.index>=this.notes.length&&(this.playing=!1)}}get isPlaying(){return this.playing}get duration(){let e=this.notes.at(-1);return e?e.time+e.duration:0}};function AV(e,t={}){let n=t.refDistance??1,r=t.maxDistance??1/0,i=t.rolloff??1;if(!(e>n))return 1;if(!(e<r))return 0;let a=(n/e)**+i;return Math.max(0,Math.min(1,a))}function jV(e,t){let n=t.x-e.x,r=t.y-e.y,i=Math.hypot(n,r);if(i===0)return 0;let a=Math.sin(e.facing),o=Math.cos(e.facing),s=(n*a+r*o)/i;return Math.max(-1,Math.min(1,s))}var MV=class{constructor(e={}){this.x=e.x??0,this.y=e.y??0,this.facing=e.facing??0}moveTo(e,t){this.x=e,this.y=t}face(e){this.facing=e}},NV=class{constructor(e,t={}){this.sound=e,this.x=t.x??0,this.y=t.y??0,this.falloff={refDistance:t.refDistance,maxDistance:t.maxDistance,rolloff:t.rolloff}}moveTo(e,t){this.x=e,this.y=t}gainTo(e){return AV(Math.hypot(this.x-e.x,this.y-e.y),this.falloff)}panTo(e){return jV(e,this)}playFor(e){let t=this.gainTo(e);return t<=0?0:(this.sound.play(t),t)}},PV=l({AudioListener:()=>MV,MidiPlayer:()=>kV,Music:()=>_V,Orchestrator:()=>vV,Sound:()=>gV,SoundSource:()=>NV,audioGain:()=>AV,audioPan:()=>jV,createAudio:()=>mV,noteToFrequency:()=>OV,onCaption:()=>hV,parseMidi:()=>EV,playTone:()=>bV,scheduleMidi:()=>DV,synthesizeTone:()=>yV});function FV(e,t){if(!Number.isSafeInteger(t)||t<0)throw RangeError(`Turn budget must be a non-negative safe integer`);let n=0;for(;n<t;){if(e.finished())return{status:`finished`,steps:n};let t=e.scheduler.peek();if(t===null)return{status:`empty`,steps:n};if(e.needsInput(t))return{status:`input`,actor:t,steps:n};let r=e.act(t);if(r!==null){if(!Number.isFinite(r)||r<0)throw RangeError(`Action cost must be finite and non-negative, or null`);e.scheduler.spend(r)}n++}return{status:`limit`,steps:n}}function IV(e){let t=e.state,n=e.status??`ready`,r=[],i=0;for(let a of e.commands){if(n===`finished`)break;let o=e.step(t,a,e.random);t=o.state,n=o.status;for(let e of o.events)r.push(e);i++}return{state:t,events:r,status:n,processedCommands:i}}var LV=class e{constructor(e){if(this._reminders=[],this._results={},this.levels=new Map(e.levels.map(e=>[e.id,e])),this.levels.size!==e.levels.length)throw Error(`campaign level ids must be unique`);if(!this.levels.has(e.start))throw Error(`unknown campaign start level: ${e.start}`);this._currentLevel=e.start,this._state=structuredClone(e.state)}get currentLevel(){return this._currentLevel}get state(){return structuredClone(this._state)}get reminders(){return[...this._reminders]}get results(){return structuredClone(this._results)}playCurrent(){if(!this._currentLevel)throw Error(`campaign has no current level`);let e=this.levels.get(this._currentLevel);return this.completeCurrent(e.run(this.state,{levelId:e.id}))}completeCurrent(e){if(!this._currentLevel)throw Error(`campaign has no current level`);let t=this._currentLevel;if(this._state=structuredClone(e.state),e.result!==void 0&&(this._results[t]=structuredClone(e.result)),this._reminders=[...e.reminders??[]],e.outcome!==`completed`)this._currentLevel=null;else if(e.next===void 0)throw Error(`campaign level ${t} did not choose a next level`);else{if(e.next!==null&&!this.levels.has(e.next))throw Error(`unknown campaign transition: ${t} -> ${e.next}`);this._currentLevel=e.next}return{...e,state:this.state}}snapshot(){return{currentLevel:this._currentLevel,state:this.state,reminders:this.reminders,results:this.results}}static restore(t,n){let r=t.currentLevel??n.levels[0]?.id;if(!r)throw Error(`campaign restore requires at least one level`);let i=new e({levels:n.levels,start:r,state:t.state});return i._currentLevel=t.currentLevel,i._reminders=[...t.reminders],i._results=structuredClone(t.results),i}};function RV(e){let t=new w(e.seed);return{...IV({state:structuredClone(e.initialState),commands:e.commands,status:e.status,random:t,step:e.step}),seed:e.seed,random:t.getState()}}var zV=class e{constructor(e){this._state=e.state,this.scheduler=e.scheduler,this.random=e.random,this.rule=e.rule,this.actorId=e.actorId}get state(){return this._state}dispatch(e){let t=this.rule(this._state,e,{random:this.random,scheduler:this.scheduler});return this._state=t.state,t.cost!=null&&this.scheduler.spend(t.cost),t}snapshot(e=1){return{version:e,state:this._state,scheduler:this.scheduler.toJSON(this.actorId),random:this.random.getState()}}static restore(t,n){let r=new w;r.setState(t.random);let i=VI.restore(t.scheduler,n.actorOf);return new e({state:t.state,scheduler:i,random:r,rule:n.rule,actorId:n.actorId})}},BV=class e{constructor(e){this.followUps=[],this.runtime=e.runtime,this.queue=new Fn({play:e.play}),this.followUpOf=e.followUp}get locked(){return this.queue.isBusy}submit(e){return this.locked?null:this.commit(e)}update(e){this.queue.update(e),this.drainFollowUps()}cancel(){this.queue.clear(),this.followUps=[]}snapshot(e=1){return this.runtime.snapshot(e)}static restore(t,n){let r=zV.restore(t,{rule:n.rule,actorOf:n.actorOf,actorId:n.actorId});return new e({runtime:r,play:n.play,followUp:n.followUp})}commit(e){let t=this.runtime.dispatch(e);return this.queue.enqueue(t.events),this.followUpOf&&this.followUps.push(...this.followUpOf(t)),this.drainFollowUps(),t}drainFollowUps(){for(;!this.queue.isBusy&&this.followUps.length>0;){let e=this.followUps.shift();this.commit(e)}}},VV=class{constructor(e){this.saves=new Nt(e)}save(e,t,n){this.saves.save(e,{campaign:t.campaign.snapshot(),world:t.world,simulation:t.simulation?t.simulation.snapshot():null},n)}load(e){return this.saves.load(e)?.state??null}list(){return this.saves.list()}delete(e){this.saves.delete(e)}},HV=l({Campaign:()=>LV,CampaignSave:()=>VV,EventPresentation:()=>BV,Scheduler:()=>VI,SimulationRuntime:()=>zV,advanceToInput:()=>FV,runHeadlessScenario:()=>RV,runScenario:()=>IV}),UV=class extends Error{constructor(e){super(`${e.location.file}:${e.location.line}:${e.location.column}: ${e.message}`),this.name=`MwlSyntaxError`,this.diagnostic=e}},WV=new Set([`define`,`enddef`,`arg`,`ifdef`,`ifndef`,`else`,`endif`,`include`]);function GV(e,t={}){let n=new Map,r=new Set(t.defines??[]),i=e.split(/\r?\n/),a=[],o=[!0],s=null;for(let e=0;e<i.length;e++){let c=i[e],l=/^\s*#([A-Za-z_][\w-]*)(?:\s+(.*))?$/.exec(c);if(l&&WV.has(l[1])){let i=l[1],u=l[2]?.trim()??``;if(i===`define`){if(!o.at(-1)||s)continue;let n=XV(u);if(n.length===0)throw QV(`MWL_DEFINE`,`macro name is required`,t.file,e,c);s={name:n[0],parameters:n.slice(1),body:[]},r.add(n[0]);continue}if(i===`arg`){s&&u&&s.parameters.push(u.split(/\s+/)[0]);continue}if(i===`enddef`){if(!s)throw QV(`MWL_ENDDEF`,`unexpected #enddef`,t.file,e,c);n.set(s.name,{name:s.name,parameters:s.parameters,body:s.body.join(`
1345
+ `)}),s=null;continue}if(i===`ifdef`||i===`ifndef`){let e=r.has(u);o.push(o.at(-1)===!0&&(i===`ifdef`?e:!e));continue}if(i===`else`){if(o.length<2)throw QV(`MWL_ELSE`,`unexpected #else`,t.file,e,c);o[o.length-1]=o[o.length-2]&&!o.at(-1);continue}if(i===`endif`){if(o.length<2)throw QV(`MWL_ENDIF`,`unexpected #endif`,t.file,e,c);o.pop();continue}if(i===`include`){if(o.at(-1)){let n=t.includes?.[ZV(u)];if(n===void 0)throw QV(`MWL_INCLUDE`,`include not supplied: ${u}`,t.file,e,c);a.push(GV(n,t))}continue}}if(s){o.at(-1)&&s.body.push(c);continue}o.at(-1)&&!/^\s*#/.test(c)&&a.push(c)}if(s)throw QV(`MWL_ENDDEF`,`macro ${s.name} is missing #enddef`,t.file,i.length-1,i.at(-1)??``);if(o.length!==1)throw QV(`MWL_ENDIF`,`conditional is missing #endif`,t.file,i.length-1,i.at(-1)??``);return KV(a.join(`
1346
+ `),n,t)}function KV(e,t,n){return e.replace(/\{([^{}]*)\}/g,(e,r)=>{let i=XV(r),a=t.get(i[0]);if(!a)return e;let o=a.body;for(let e=0;e<a.parameters.length;e++){let t=a.parameters[e],n=i.find(e=>e.startsWith(`${t}=`)),r=n?n.slice(t.length+1):i[e+1]??``;o=o.replaceAll(`{${t}}`,r)}return KV(o,t,n)})}function qV(e,t=`<mwl>`){let n=[],r=[],i=e.split(/\r?\n/);for(let e=0;e<i.length;e++){let a=i[e],o=a.trim();if(!o||o.startsWith(`#`))continue;let s={file:t,line:e+1,column:Math.max(1,a.indexOf(o)+1)},c=/^\[([A-Za-z_][\w-]*)\]$/.exec(o);if(c){let e={tag:c[1],attributes:{},children:[],location:s,gettext:[]};r.length?r.at(-1).children.push(e):n.push(e),r.push(e);continue}let l=/^\[\/([A-Za-z_][\w-]*)\]$/.exec(o);if(l){let e=r.pop();if(!e||e.tag!==l[1])throw new UV({code:`MWL_TAG`,message:`mismatched closing tag ${l[1]}`,location:s,lineText:a});continue}let u=/^([A-Za-z_][\w-]*)\s*=\s*(.*)$/.exec(o);if(u&&r.length){let e=r.at(-1);YV(u[2])&&e.gettext.push(u[1]),e.attributes[u[1]]=JV(u[2],s,a);continue}throw new UV({code:`MWL_TOKEN`,message:`expected a tag or key=value attribute`,location:s,lineText:a})}if(r.length){let e=r.at(-1);throw new UV({code:`MWL_TAG`,message:`unclosed tag ${e.tag}`,location:e.location})}return n}function JV(e,t,n=e){let r=e.trim(),i=/^_\s*"/.exec(r);if(i&&(r=r.slice(i[0].length-1)),r.startsWith(`"`)){if(!r.endsWith(`"`)||r.length<2)throw new UV({code:`MWL_STRING`,message:`unterminated quoted value`,location:t,lineText:n});return r.slice(1,-1).replaceAll(`""`,`"`)}return r}function YV(e){return/^_\s*"/.test(e.trim())}function XV(e){let t=[],n=``,r=!1;for(let i=0;i<e.length;i++){let a=e[i];a===`"`&&(r=!r),/\s/.test(a)&&!r?(n&&t.push(n),n=``):n+=a}return n&&t.push(n),t}function ZV(e){return e.startsWith(`"`)&&e.endsWith(`"`)?e.slice(1,-1):e}function QV(e,t,n,r,i){return new UV({code:e,message:t,location:{file:n??`<mwl>`,line:r+1,column:1},lineText:i})}function $V(e,t){if(!Number.isInteger(t.version)||t.version<1)throw Error(`MWL save version must be a positive integer`);return JSON.stringify({format:`mwl-save`,version:t.version,world:e})}function eH(e,t){let n=JSON.parse(e),r=nH(n)?n:{format:`mwl-save`,version:1,world:n};if(r.version>t.version)throw Error(`MWL save version ${r.version} is newer than supported version ${t.version}`);let i=tH(r.world);for(let e=r.version;e<t.version;e++){let n=t.migrations?.[e+1];if(!n)throw Error(`missing MWL save migration to version ${e+1}`);i=tH(n(i))}return i}function tH(e){if(!e||typeof e!=`object`)throw Error(`invalid MWL saved world`);let t=e;if(!Number.isInteger(t.turn)||!t.variables||typeof t.variables!=`object`||!t.units||typeof t.units!=`object`)throw Error(`invalid MWL saved world: turn, variables, and units are required`);if(t.status!==void 0&&![`playing`,`won`,`lost`].includes(t.status))throw Error(`invalid MWL saved world status`);return structuredClone(t)}function nH(e){return!!e&&typeof e==`object`&&e.format===`mwl-save`&&typeof e.version==`number`&&`world`in e}function rH(e,t,n={}){let r=e.search(/\s+where\s+/),i=r<0?e:e.slice(0,r),a={...t};if(r>=0)for(let t of e.slice(r).replace(/^\s+where\s+/,``).split(`,`)){let e=/^\s*([A-Za-z_][A-Za-z0-9_.-]*)\s*=\s*(.+)\s*$/.exec(t);if(!e)throw Error(`invalid MWL where binding: ${t}`);let r=new iH(e[2],a,n.helpers??{});if(a[e[1]]=r.parseOr(),!r.atEnd())throw Error(`invalid MWL where binding: ${t}`)}let o=new iH(i,a,n.helpers??{}),s=o.parseOr();if(!o.atEnd())throw Error(`unexpected token in MWL condition: ${o.peek()}`);return oH(s)}var iH=class{constructor(e,t,n){this.index=0,this.tokens=aH(e),this.context=t,this.helpers=n}parseOr(){let e=this.parseAnd();for(;this.take(`or`);)e=oH(e)||oH(this.parseAnd());return e}parseAnd(){let e=this.parseNot();for(;this.take(`and`);)e=oH(e)&&oH(this.parseNot());return e}parseNot(){return this.take(`not`)?!oH(this.parseNot()):this.parseComparison()}parseComparison(){let e=this.parseAdditive(),t=this.peek();if(![`==`,`~=`,`<`,`<=`,`>`,`>=`].includes(t))return e;this.index++;let n=this.parseAdditive();if(t===`==`)return e===n;if(t===`~=`)return e!==n;if(typeof e!=`number`||typeof n!=`number`)throw Error(`${t} requires numeric operands`);return t===`<`?e<n:t===`<=`?e<=n:t===`>`?e>n:e>=n}parseAdditive(){let e=this.parseMultiplicative();for(;this.peek()===`+`||this.peek()===`-`;){let t=this.tokens[this.index++],n=this.parseMultiplicative();if(typeof e!=`number`||typeof n!=`number`)throw Error(`${t} requires numeric operands`);e=t===`+`?e+n:e-n}return e}parseMultiplicative(){let e=this.parsePrimary();for(;this.peek()===`*`||this.peek()===`/`;){let t=this.tokens[this.index++],n=this.parsePrimary();if(typeof e!=`number`||typeof n!=`number`)throw Error(`${t} requires numeric operands`);if(t===`/`&&n===0)throw Error(`division by zero in MWL condition`);e=t===`*`?e*n:e/n}return e}parsePrimary(){if(this.take(`(`)){let e=this.parseOr();return this.expect(`)`),e}let e=this.tokens[this.index++];if(e===void 0)throw Error(`incomplete MWL condition`);if(/^-?(?:\d+(?:\.\d*)?|\.\d+)$/.test(e))return Number(e);if(e===`true`||e===`yes`)return!0;if(e===`false`||e===`no`)return!1;if(e.startsWith(`"`)||e.startsWith(`'`))return e.slice(1,-1);let t=this.helpers[e];if(t&&this.take(`(`)){let e=[];if(!this.take(`)`)){do e.push(this.parseOr());while(this.take(`,`));this.expect(`)`)}return t(...e)}let n=this.context[e];if(n===void 0)throw Error(`missing MWL condition variable "${e}"`);return n}take(e){return this.peek()===e&&(this.index++,!0)}expect(e){if(!this.take(e))throw Error(`expected "${e}" in MWL condition`)}peek(){return this.tokens[this.index]??`<end>`}atEnd(){return this.index>=this.tokens.length}};function aH(e){let t=[],n=/\s*(?:("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*')|([A-Za-z_][A-Za-z0-9_.-]*)|(-?(?:\d+(?:\.\d*)?|\.\d+))|(==|~=|<=|>=|[()+*/,<>-]))/y,r=0;for(;r<e.length;){n.lastIndex=r;let i=n.exec(e);if(!i)throw Error(`invalid MWL condition near "${e.slice(r)}"`);t.push(i[1]??i[2]??i[3]??i[4]),r=n.lastIndex}return t}function oH(e){return e!==!1&&e!==0&&e!==``}function sH(e){let t=new lH(e),n=t.expression();if(t.skip(),!t.atEnd())throw Error(`invalid MWL expression near "${t.rest()}"`);return n}function cH(e,t){let n=typeof e==`string`?sH(e):e;if(n.kind===`number`)return n.value;if(n.kind===`variable`){let e=t[n.name];if(e===void 0||!Number.isFinite(e))throw Error(`missing MWL expression variable "${n.name}"`);return e}let r=cH(n.left,t),i=cH(n.right,t);if(n.op===`+`)return r+i;if(n.op===`-`)return r-i;if(n.op===`*`)return r*i;if(n.op===`/`){if(i===0)throw Error(`division by zero in MWL expression`);return r/i}return r**i}var lH=class{constructor(e){this.index=0,this.source=e}expression(){return this.additive()}additive(){let e=this.multiplicative();for(;;){this.skip();let t=this.peek(`+`)?`+`:this.peek(`-`)?`-`:null;if(!t)return e;this.index++,e={kind:`binary`,op:t,left:e,right:this.multiplicative()}}}multiplicative(){let e=this.power();for(;;){this.skip();let t=this.peek(`*`)?`*`:this.peek(`/`)?`/`:null;if(!t)return e;this.index++,e={kind:`binary`,op:t,left:e,right:this.power()}}}power(){let e=this.primary();return this.skip(),this.peek(`^`)&&(this.index++,e={kind:`binary`,op:`^`,left:e,right:this.power()}),e}primary(){if(this.skip(),this.peek(`(`)){this.index++;let e=this.expression();if(this.skip(),!this.peek(`)`))throw Error(`missing closing parenthesis in MWL expression`);return this.index++,e}let e=/^(?:\d+(?:\.\d*)?|\.\d+)/.exec(this.rest());if(e)return this.index+=e[0].length,{kind:`number`,value:Number(e[0])};let t=/^[A-Za-z_][A-Za-z0-9_.-]*/.exec(this.rest());if(t)return this.index+=t[0].length,{kind:`variable`,name:t[0]};throw Error(`expected number, variable, or parenthesis near "${this.rest()}"`)}peek(e){return this.source[this.index]===e}skip(){for(;/\s/.test(this.source[this.index]??``);)this.index++}atEnd(){return this.index>=this.source.length}rest(){return this.source.slice(this.index)}};function uH(e){let t=[],n=e=>{t.push(e),e.children.forEach(n)};return e.forEach(n),t}function dH(e,t){let n=e.attributes[t];if(!n)throw Error(`MWL ${e.tag} is missing ${t}`);return n}function fH(e,t){let n=e.attributes[t];if(n===void 0)return;let r=Number(n);return Number.isFinite(r)?r:void 0}function pH(e,t,n){let r=e.attributes[t];if(r===void 0)return n;let i=Number.parseInt(r,10);return Number.isFinite(i)?i:n}function mH(e,t){return hH(e.attributes[t])}function hH(e){return e===void 0?void 0:e===`true`||e===`yes`}function gH(e,t){return e!==void 0&&t.includes(e)?e:void 0}function _H(e,t,n){let r=n.carryoverPercentage??80,i=t?e.gold[t.id]??e.sides[t.id]?.gold??0:0;return{result:n.result,gold:Math.floor(i*r/100)+(n.bonus??0),add:n.carryoverAdd??!1,recall:t?Object.entries(e.units).filter(([,e])=>e.alive&&e.side===t.id).map(([e])=>e).sort():[],nextScenario:n.nextScenario??null}}function vH(e,t){return e.add?t+e.gold:Math.max(t,e.gold)}var yH=dH,bH=(e,t,n)=>pH(e,t,n)??n;function xH(){return{variables:{},units:{},sides:{},maps:{},gold:{},turn:1,status:`playing`,sideStatus:{},map:null,timeOfDay:``,scheduleIndex:0}}function SH(e){let t=e.split(/\r?\n/).filter(e=>e.trim()!==``).map(e=>e.split(`,`).map(e=>e.trim())),n=t.length,r=t.length?Math.max(...t.map(e=>e.length)):0,i=[],a={};for(let e=0;e<n;e++)for(let n=0;n<r;n++){let r=t[e]?.[n]??`_off^_usr`,o=/^([A-Za-z0-9_][\w.-]*)\s+(\S.*)$/.exec(r);o?(i.push(o[2]),(a[o[1]]??=[]).push({x:n,y:e})):i.push(r)}return{width:r,height:n,codes:i,starts:a}}var CH=class{constructor(e,t={}){this.unitTypes=new Map,this.schedule=[],this.pendingDialogue=null,this.dialogueCounter=0,this.game=e,this.world=t.world??xH(),this.onMessage=t.onMessage,this.resolveMap=t.resolveMap,this.hooks=t.hooks,this.onTrace=t.onTrace,this.persistence=t.persistence??{version:1},this.loadUnitTypes(),this.loadSchedule(),this.loadInitialContent(),this.loadInitialUnits(),this.loadLeaders(),this.loadScenarioExtras()}run(e){for(let t of this.nodes(`event`))(t.attributes.on??t.attributes.trigger)===e&&this.eventFiltersMatch(t)&&this.claimEvent(t)&&this.executeTracedEvent(t,e);this.checkObjectives()}fireEvent(e){let t=this.nodes(`event`).find(t=>t.attributes.id===e);return!t||!this.eventFiltersMatch(t)||!this.claimEvent(t)?!1:(this.executeTracedEvent(t,`fireEvent`),this.checkObjectives(),!0)}fireMoveto(e){let t=this.world.units[e];if(!(!t||!t.alive)){for(let n of this.nodes(`event`))(n.attributes.on??n.attributes.trigger)===`moveto`&&(n.attributes.x!==void 0&&!WH(n.attributes.x,t.x)||n.attributes.y!==void 0&&!WH(n.attributes.y,t.y)||(n.attributes.unit===void 0||n.attributes.unit===e)&&(n.attributes.side===void 0||n.attributes.side===t.side)&&this.eventFiltersMatch(n)&&this.claimEvent(n)&&this.executeTracedEvent(n,`moveto`));this.checkObjectives()}}claimEvent(e){if(!(e.attributes.once===void 0?e.attributes.on===`moveto`:e.attributes.once!==`false`))return!0;let t=e.attributes.id??`${e.attributes.on??e.attributes.trigger??`event`}@${e.location?.line??0}`,n=this.world.firedEvents??=[];return!n.includes(t)&&(n.push(t),!0)}eventFiltersMatch(e){if(!this.conditionMatches(e)||!this.filterConditionMatches(e))return!1;let t=e.children.find(e=>e.tag===`filter`);return!t||this.filterMatches(t)}executeEvent(e){this.runBlock(this.commandChildren(e))}runBlock(e){for(let t=0;t<e.length;t++){let n=e[t];if(!this.isConsumedElse(e,t)){if(n.tag===`say`){this.showSay(n);continue}if(n.tag===`dialogue`){this.showDialogue(n);continue}this.executeNode(n)}}}isConsumedElse(e,t){let n=e[t-1];return e[t]?.tag===`else`&&n?.tag===`if`&&this.nodeConditionMatches(n)}executeTracedEvent(e,t){let n=e.attributes.id??`${e.attributes.on??e.attributes.trigger??`event`}@${e.location?.line??0}`;this.onTrace?.({type:`event`,phase:`claimed`,id:n,trigger:t});try{this.executeEvent(e),this.onTrace?.({type:`event`,phase:`completed`,id:n,trigger:t})}catch(e){throw this.onTrace?.({type:`error`,message:String(e),event:n}),e}}showDialogue(e){let t=null;for(let n of e.children)n.tag===`message`?(this.showMessage(n.attributes),t={text:n.attributes.text??n.attributes.value??``,...n.attributes.speaker===void 0?{}:{speaker:n.attributes.speaker},...n.attributes.portrait===void 0?{}:{portrait:n.attributes.portrait},...n.attributes.side===void 0||n.attributes.side===``?{}:{side:n.attributes.side}}):n.tag===`say`&&(this.showSay(n),t={text:n.attributes.text??``,speaker:n.attributes.speaker});let n=[];for(let t of e.children){if(t.tag!==`choice`||!t.attributes.text||t.attributes.variable!==void 0&&!IH(this.variableAt(t.attributes.variable),t.attributes.equals))continue;let e=t.children.filter(e=>e.tag===`branch`);if(e.length)for(let r of e)n.push({text:r.attributes.text??t.attributes.text,branch:r.children});else t.attributes.event&&n.push({text:t.attributes.text,event:t.attributes.event})}if(n.length===0)return;this.dialogueCounter+=1;let r=`dialogue-${this.dialogueCounter}`;this.pendingDialogue={id:r,choices:n},this.world.pendingDialogue={id:r,choices:n},this.onMessage?.({text:t?.text??``,...t?.speaker===void 0?{}:{speaker:t.speaker},choices:n,dialogueId:r})}showSay(e){this.onMessage&&this.onMessage({text:e.attributes.text??``,...e.attributes.speaker===void 0?{}:{speaker:e.attributes.speaker}})}answerDialogue(e,t){let n=this.pendingDialogue;if(!n||n.id!==e)return!1;let r=n.choices[t];if(!r)return!1;if(this.pendingDialogue=null,delete this.world.pendingDialogue,r.event){let e=this.nodes(`event`).find(e=>e.attributes.id===r.event);if(!e)throw Error(`MWL dialogue choice points at unknown event: ${r.event}`);if(!this.claimEvent(e))return!0;this.executeEvent(e)}else this.runBlock(r.branch??[]);return this.checkObjectives(),!0}evaluate(){return this.checkObjectives(),this.world.status}save(){return $V(this.world,this.persistence)}snapshot(){return JSON.stringify(this.world)}restore(e){let t=eH(e,this.persistence);Object.assign(this.world.variables,t.variables),Object.assign(this.world.units,t.units),Object.assign(this.world.sides,t.sides??{}),Object.assign(this.world.maps,t.maps??{}),Object.assign(this.world.gold,t.gold??{}),this.world.turn=t.turn,this.world.status=t.status,this.world.sideStatus={...t.sideStatus??{}},this.world.map=t.map??null,this.world.timeOfDay=t.timeOfDay??this.schedule[0]??``,this.world.scheduleIndex=t.scheduleIndex??0,this.world.firedEvents=[...t.firedEvents??[]],this.world.villages=t.villages?structuredClone(t.villages):void 0,this.world.clearedShroud=t.clearedShroud?structuredClone(t.clearedShroud):void 0,this.world.roles=t.roles?structuredClone(t.roles):void 0,this.world.objects=t.objects?structuredClone(t.objects):void 0,this.world.story=t.story?structuredClone(t.story):void 0,this.world.pendingDialogue=t.pendingDialogue,this.pendingDialogue=t.pendingDialogue?{id:t.pendingDialogue.id,choices:[...t.pendingDialogue.choices]}:null;let n=t.pendingDialogue?.id.match(/^dialogue-(\d+)$/);n&&(this.dialogueCounter=Math.max(this.dialogueCounter,Number(n[1])))}loadUnitTypes(){for(let e of this.nodes(`unit_type`)){let t=e.attributes.id;t&&this.unitTypes.set(t,{hitpoints:bH(e,`hitpoints`,1),movement:bH(e,`movement`,0)})}}loadSchedule(){this.schedule=this.nodes(`schedule`).flatMap(e=>e.children.filter(e=>e.tag===`time`).map(e=>e.attributes.id).filter(e=>!!e)),this.world.scheduleIndex=0,this.world.timeOfDay=this.schedule[0]??``}loadInitialContent(){for(let e of this.nodes(`side`)){let t={gold:bH(e,`gold`,0),income:bH(e,`income`,0)};e.attributes.leader!==void 0&&(t.leader=e.attributes.leader),e.attributes.controller!==void 0&&(t.controller=e.attributes.controller),e.attributes.recruit!==void 0&&(t.recruit=e.attributes.recruit),e.attributes.team_name!==void 0&&(t.teamName=e.attributes.team_name),e.attributes.user_team_name!==void 0&&(t.userTeamName=e.attributes.user_team_name),e.attributes.share_vision!==void 0&&(t.shareVision=e.attributes.share_vision),e.attributes.flag!==void 0&&(t.flag=e.attributes.flag),e.attributes.village_gold!==void 0&&(t.villageGold=bH(e,`village_gold`,0));for(let n of[`heal`,`fog`,`shroud`,`hidden`]){let r=e.attributes[n];r!==void 0&&(t[n]=r===`yes`||r===`true`)}this.world.sides[yH(e,`id`)]=t}for(let e of this.nodes(`map`)){let t=e.attributes.id??e.attributes.name??`map`;this.world.maps[t]={terrain:e.attributes.terrain??``,file:e.attributes.file},this.world.map||(this.world.map=this.buildMap(t,e))}}topLevelNodes(e){return(this.game.roots.find(e=>e.tag===`game`)?.children??this.game.roots).filter(t=>t.tag===e)}loadScenarioExtras(){for(let e of this.topLevelNodes(`object`)){let t={x:bH(e,`x`,0),y:bH(e,`y`,0)};e.attributes.id!==void 0&&(t.id=e.attributes.id),e.attributes.name!==void 0&&(t.name=e.attributes.name),e.attributes.image!==void 0&&(t.image=e.attributes.image),e.attributes.side!==void 0&&(t.side=e.attributes.side),(this.world.objects??=[]).push(t)}for(let e of this.topLevelNodes(`story`)){let t=e.attributes.text??e.attributes.value;if(t===void 0)continue;let n={text:t};e.attributes.title!==void 0&&(n.title=e.attributes.title),e.attributes.image!==void 0&&(n.image=e.attributes.image),e.attributes.music!==void 0&&(n.music=e.attributes.music),(this.world.story??=[]).push(n)}for(let e of this.topLevelNodes(`role`)){let t=e.attributes.role??e.attributes.name;if(t===void 0)continue;let n=FH(e.attributes,`role`,`name`),r=Object.entries(this.world.units).filter(([e,t])=>t.alive&&PH(t,e,n));for(let[,e]of r)e.role=t;(this.world.roles??={})[t]=r.map(([e])=>e)}}buildMap(e,t){let n=t.attributes.terrain;if(!n&&t.attributes.file&&this.resolveMap&&(n=this.resolveMap(t.attributes.file)),!n)return null;let r=SH(n);for(let e of t.children){if(e.tag!==`start`)continue;let t=e.attributes.side,n=MH(e,`x`),i=MH(e,`y`);t!==void 0&&n!==void 0&&i!==void 0&&(r.starts[t]??=[]).push({x:n,y:i})}return{id:e,...r}}loadInitialUnits(){for(let e of this.nodes(`unit`)){let t=yH(e,`id`),n={hp:bH(e,`hp`,1),x:bH(e,`x`,0),y:bH(e,`y`,0),alive:!0};if(e.attributes.type!==void 0){n.type=e.attributes.type;let t=this.unitTypes.get(e.attributes.type);t&&(n.moves=t.movement)}e.attributes.side!==void 0&&(n.side=e.attributes.side),e.attributes.name!==void 0&&(n.name=e.attributes.name),e.attributes.role!==void 0&&(n.role=e.attributes.role);let r=mH(e,`can_recruit`);r!==void 0&&(n.can_recruit=r),this.world.units[t]=n}}loadLeaders(){for(let e of this.nodes(`side`)){let t=e.attributes.leader;if(!t)continue;let n=e.attributes.id;if(!n)continue;let r=this.world.map?.starts[n];if(!r?.length)continue;let i=this.unitTypes.get(t);for(let e of r){if(this.unitAt(e.x,e.y))continue;let r=`${t} ${n} (${e.x},${e.y})`;this.world.units[r]={hp:i?.hitpoints??1,x:e.x,y:e.y,alive:!0,type:t,side:n,moves:i?.movement??0,can_recruit:!0,leader:!0}}}}unitAt(e,t){return Object.values(this.world.units).find(n=>n.alive&&n.x===e&&n.y===t)}executeNode(e){let t=e.tag===`command`?e.attributes.name:e.tag;if(!t)throw Error(`MWL command is missing name`);switch(t){case`message`:this.showMessage(e.attributes);break;case`spawn`:this.spawnUnit(e.attributes.type??``,e.attributes.side,bH(e,`x`,0),bH(e,`y`,0),e.attributes.id??e.attributes.target,e.attributes.hp===void 0?void 0:bH(e,`hp`,1));break;case`move`:this.applyMove(e.attributes.unit??yH(e,`target`),bH(e,`x`,0),bH(e,`y`,0));break;case`kill`:{let t=e.attributes.unit??e.attributes.target;t===void 0?OH(this.world,e.attributes):this.killUnit(t);break}case`fire_event`:{let t=e.attributes.id??e.attributes.name;if(!t)throw Error(`[fire_event] requires id`);this.fireEvent(t);break}case`store_unit`:{let t=e.attributes.variable??e.attributes.name??yH(e,`variable`);this.setVariableAt(t,this.matchingUnits(e,[`variable`,`name`]).map(([e,t])=>({id:e,...kH(t)})));break}case`unstore_unit`:{let t=yH(e,`variable`);for(let e of this.storedUnits(t))this.restoreUnit(e,{});break}case`recall`:{let t=this.storedUnits(yH(e,`variable`)),n=e.attributes.id??e.attributes.unit,r=n===void 0?t[0]:t.find(e=>e.id===n);if(!r)throw Error(`[recall] found no stored unit${n===void 0?``:` named ${n}`}`);let i={};e.attributes.x!==void 0&&(i.x=bH(e,`x`,0)),e.attributes.y!==void 0&&(i.y=bH(e,`y`,0)),e.attributes.side!==void 0&&(i.side=e.attributes.side),this.restoreUnit(r,i);break}case`modify_unit`:{let t=e.children.find(e=>e.tag===`set`)?.attributes??e.attributes;for(let[,n]of this.matchingUnits(e))AH(n,t);break}case`heal_unit`:{let t=MH(e,`amount`),n=MH(e,`hp`);if(t===void 0&&n===void 0)throw Error(`[heal_unit] requires amount or hp`);for(let[,r]of this.matchingUnits(e))r.hp=n??r.hp+(t??0);break}case`set_terrain`:this.setTerrain(bH(e,`x`,0),bH(e,`y`,0),yH(e,`terrain`));break;case`capture_village`:{let t=bH(e,`x`,0),n=bH(e,`y`,0),r={x:t,y:n,side:yH(e,`side`)};e.attributes.name!==void 0&&(r.name=e.attributes.name),(this.world.villages??={})[`${t},${n}`]=r;break}case`clear_shroud`:{let t=yH(e,`side`),n=bH(e,`x`,0),r=bH(e,`y`,0),i=bH(e,`radius`,1),a=new Set(this.world.clearedShroud?.[t]??[]);for(let e=-i;e<=i;e++)for(let t=-i;t<=i;t++)a.add(`${n+t},${r+e}`);(this.world.clearedShroud??={})[t]=[...a];break}case`role`:{let t=e.attributes.role??e.attributes.name;if(!t)throw Error(`[role] requires role`);let n=this.matchingUnits(e,[`role`,`name`]);for(let[,e]of n)e.role=t;(this.world.roles??={})[t]=n.map(([e])=>e);break}case`attack`:this.attack(e.attributes.defender??e.attributes.target??yH(e,`target`),bH(e,`amount`,0));break;case`modify_gold`:this.addGold(e.attributes.side??yH(e,`target`),bH(e,`delta`,bH(e,`amount`,0)));break;case`gold`:this.addGold(yH(e,`side`),bH(e,`delta`,bH(e,`amount`,0)));break;case`set_variable`:this.setVariable(e.tag===`command`?yH(e,`target`):yH(e,`name`),e.attributes.value??``);break;case`while`:{let t=bH(e,`max_iterations`,1e3);if(t<1||t>1e5)throw Error(`MWL while max_iterations must be between 1 and 100000`);for(let n=0;n<t&&this.nodeConditionMatches(e);n++)this.runBlock(this.commandChildren(e));break}case`foreach`:{let t=this.variableAt(yH(e,`variable`)),n=Array.isArray(t)?t.map((e,t)=>[String(t),e]):typeof t==`string`?t.split(`,`).map((e,t)=>[String(t),e.trim()]).filter(([,e])=>e!==``):t&&typeof t==`object`?Object.entries(t):[],r=e.attributes.item??`item`,i=e.attributes.index??`index`;for(let t=0;t<n.length;t++)this.setVariableAt(r,n[t][1]),this.setVariableAt(i,t),this.runBlock(this.commandChildren(e));break}case`switch`:{let t=this.variableAt(yH(e,`variable`)),n=e.children.find(e=>e.tag===`case`&&e.attributes.equals!==void 0&&IH(t,e.attributes.equals)),r=e.children.find(e=>e.tag==="default");this.runBlock((n??r)?.children??[]);break}case`end_turn`:this.endTurn();break;case`win`:this.markSideResult(e.attributes.side,`won`),this.world.status=`won`;break;case`lose`:this.markSideResult(e.attributes.side,`lost`),this.world.status=`lost`;break;case`endlevel`:{let t=e.attributes.result===`defeat`?`defeat`:`victory`;this.world.status=t===`defeat`?`lost`:`won`,this.world.carryover=_H(this.world,TH(this.world,e.attributes.side),{result:t,bonus:pH(e,`bonus`),carryoverPercentage:fH(e,`carryover_percentage`),carryoverAdd:mH(e,`carryover_add`),nextScenario:e.attributes.next_scenario??null});break}case`if`:{let t=e.children.find(e=>e.tag===`else`),n=this.nodeConditionMatches(e)?e:t;this.runBlock(n?this.commandChildren(n):[]);break}case`else`:this.runBlock(this.commandChildren(e));break;case`hook`:this.runHook(e);break;default:throw Error(`unknown MWL command: ${t}`)}}commandChildren(e){return e.children.filter(e=>e.tag!==`condition`&&e.tag!==`filter`&&e.tag!==`filter_condition`)}runHook(e){let t=e.attributes.name??``,n=this.hooks?.command?.[t];if(!n)throw Error(`MWL hook ${t} is not implemented`);let{name:r,...i}=e.attributes;n(this.worldView(),this.emit(),i)}applyMove(e,t,n){let r=this.world.units[e];if(!r||!r.alive)throw Error(`MWL unit is not alive: ${e}`);let i=this.world.map??null;if(i){if(t<0||n<0||t>=i.width||n>=i.height)throw Error(`MWL move out of bounds: ${t},${n}`);let e=this.unitAt(t,n);if(e&&e!==r)throw Error(`MWL move onto an occupied cell: ${t},${n}`)}if(typeof r.moves==`number`){if(r.moves<=0)throw Error(`MWL unit has no moves left: ${e}`);--r.moves}r.x=t,r.y=n,this.fireMoveto(e)}showMessage(e){if(!this.onMessage)return;let t={text:this.interpolate(e.text??e.value??``),...e.speaker===void 0?{}:{speaker:e.speaker},...e.portrait===void 0?{}:{portrait:e.portrait},...e.side===void 0||e.side===``?{}:{side:e.side}};this.onMessage(t)}interpolate(e){let t=Object.fromEntries(Object.entries(this.world.variables).filter(e=>typeof e[1]==`number`));return e.replace(/\$\(([^)]*)\)/g,(e,n)=>{try{return String(cH(n,t))}catch{return``}}).replace(/\$([A-Za-z_][A-Za-z0-9_.]*)/g,(e,t)=>{let n=this.variableAt(t);return n===void 0||typeof n==`boolean`?``:String(n)})}setVariable(e,t){let n=Number(t);if(t.trim()!==``&&Number.isFinite(n)){this.setVariableAt(e,n);return}let r=/^\$([A-Za-z_][A-Za-z0-9_.]*)$/.exec(t.trim());if(r){let t=this.variableAt(r[1]);this.setVariableAt(e,t===void 0?``:t);return}let i=Object.fromEntries(Object.entries(this.world.variables).filter(e=>typeof e[1]==`number`));if(/[+*/^()]|\s-\s/.test(t)||Object.prototype.hasOwnProperty.call(i,t.trim())){this.setVariableAt(e,cH(t,i));return}this.setVariableAt(e,t)}variableAt(e){return HH(this.world.variables,e)}setVariableAt(e,t){let n=this.variableAt(e);VH(this.world.variables,e,t),this.onTrace?.({type:`variable`,name:e,...n===void 0?{}:{previous:n},value:t})}spawnUnit(e,t,n,r,i,a){let o=e?this.unitTypes.get(e):void 0,s=i??`${e||`unit`}#${t??``}@${n},${r}`;this.world.units[s]={hp:a??o?.hitpoints??1,x:n,y:r,alive:!0,...e?{type:e}:{},...t===void 0?{}:{side:t},...o?{moves:o.movement}:{}}}killUnit(e){let t=this.world.units[e];if(!t||!t.alive)throw Error(`MWL unit is not alive: ${e}`);t.alive=!1}matchingUnits(e,t=[]){let n=e.children.find(e=>e.tag===`filter`),r=n?n.attributes:FH(e.attributes,...t);return Object.entries(this.world.units).filter(([e,t])=>t.alive&&PH(t,e,r))}storedUnits(e){let t=this.variableAt(e);if(!Array.isArray(t))throw Error(`MWL variable ${e} is not a stored unit list; store one first`);return t.filter(e=>!!e&&typeof e==`object`&&!Array.isArray(e))}restoreUnit(e,t){let n=typeof e.id==`string`?e.id:void 0;if(!n)throw Error(`a stored unit snapshot is missing its id`);let r={hp:typeof e.hp==`number`?e.hp:1,x:t.x??(typeof e.x==`number`?e.x:0),y:t.y??(typeof e.y==`number`?e.y:0),alive:e.alive!==!1};typeof e.type==`string`&&(r.type=e.type);let i=t.side??(typeof e.side==`string`?e.side:void 0);i!==void 0&&(r.side=i),typeof e.moves==`number`&&(r.moves=e.moves),typeof e.name==`string`&&(r.name=e.name),typeof e.role==`string`&&(r.role=e.role),typeof e.can_recruit==`boolean`&&(r.can_recruit=e.can_recruit),typeof e.leader==`boolean`&&(r.leader=e.leader),this.world.units[n]=r}setTerrain(e,t,n){let r=this.world.map;if(!r)throw Error(`[set_terrain] needs a loaded map`);if(e<0||t<0||e>=r.width||t>=r.height)throw Error(`[set_terrain] is outside the map: ${e},${t}`);let i=[...r.codes];i[t*r.width+e]=n,this.world.map={...r,codes:i}}addGold(e,t){this.world.gold[e]=(this.world.gold[e]??0)+t}endTurn(){this.world.turn+=1,this.advanceSchedule(),this.resetMoves(),this.run(`turn`),this.checkTimeOver()}checkTimeOver(){let e=pH(this.game.roots[0],`turn_limit`);e===void 0||this.world.turn<=e||this.world.variables.time_over===`yes`||(this.world.variables.time_over=`yes`,this.run(`time_over`))}advanceSchedule(){if(!this.schedule.length)return;let e=((this.world.scheduleIndex??0)+1)%this.schedule.length;this.world.scheduleIndex=e,this.world.timeOfDay=this.schedule[e]}resetMoves(){for(let e of Object.values(this.world.units)){if(!e.alive)continue;let t=e.type?this.unitTypes.get(e.type):void 0;t&&(e.moves=t.movement)}}filterMatches(e){return Object.entries(this.world.units).some(([t,n])=>n.alive&&PH(n,t,e.attributes))}conditionMatches(e){return e.children.filter(e=>e.tag===`condition`).every(e=>{if(e.attributes.condition===`hook`){let t=e.attributes.hook,n=t?.startsWith(`predicate:`)?t.slice(10):void 0,r=n?this.hooks?.predicate?.[n]:void 0;if(!r)throw Error(`MWL predicate ${n??`<missing>`} is not implemented`);let{condition:i,hook:a,...o}=e.attributes;return!!r(this.worldView(),o)}return NH(this.variableAt(e.attributes.variable),e.attributes,UH(this.world.variables))})}nodeConditionMatches(e){return e.attributes.test===void 0?this.conditionMatches(e):rH(e.attributes.test,LH(this.world.variables))}filterConditionMatches(e){let t=e.children.find(e=>e.tag===`filter_condition`);return!t||t.children.every(e=>{if(e.tag===`variable`){let t=e.attributes.name;return t!==void 0&&NH(this.variableAt(t),e.attributes,UH(this.world.variables))}if(e.tag===`predicate`){let t=e.attributes.name,n=t?this.hooks?.predicate?.[t]:void 0;if(!n)throw Error(`MWL predicate ${t??`<missing>`} is not implemented`);let{name:r,...i}=e.attributes;return!!n(this.worldView(),i)}return e.tag!==`have_unit`||Object.entries(this.world.units).some(([t,n])=>n.alive&&(e.attributes.id===void 0||t===e.attributes.id)&&PH(n,t,e.attributes))})}conditionMet(e,t){let n=e.attributes.condition??``,r=e.attributes.side??t;switch(n){case`units_dead`:{let t=e.attributes.side_filter??r;return t!==void 0&&!Object.values(this.world.units).some(e=>e.alive&&e.side===t)}case`turns_elapsed`:{let t=MH(e,`turns`);return t!==void 0&&this.world.turn>=t}case`gold_at_least`:{let n=MH(e,`gold`),r=e.attributes.side??t;return n!==void 0&&r!==void 0&&(this.world.gold[r]??0)>=n}case`unit_at`:{let t=MH(e,`x`),n=MH(e,`y`),i=e.attributes.side_filter??r;return Object.values(this.world.units).some(r=>r.alive&&(i===void 0||r.side===i)&&(e.attributes.type===void 0||r.type===e.attributes.type)&&r.x===t&&r.y===n)}case`hook`:{let t=e.attributes.hook??``,n=this.hooks?.predicate?.[t];if(!n)throw Error(`MWL hook ${t} is not implemented`);let{hook:r,condition:i,...a}=e.attributes;return!!n(this.worldView(),a)}default:return!1}}checkObjectives(){if(this.world.status!==`playing`)return;let e=new Set,t=this.nodes(`side`);for(let n of t)for(let t of n.children)(t.tag===`victory`||t.tag===`defeat`)&&e.add(t);if(this.nodes(`victory`).some(t=>!e.has(t)&&this.conditionMet(t))){this.world.status=`won`;return}if(this.nodes(`defeat`).some(t=>!e.has(t)&&this.conditionMet(t))){this.world.status=`lost`;return}let n=!1,r=!1;for(let e of t){let t=e.attributes.id;!t||(this.world.sideStatus?.[t]??`playing`)!==`playing`||(e.children.some(e=>e.tag===`victory`&&this.conditionMet(e,t))?(this.markSideResult(t,`won`),n=!0):e.children.some(e=>e.tag===`defeat`&&this.conditionMet(e,t))&&(this.markSideResult(t,`lost`),r=!0))}n?this.world.status=`won`:r&&(this.world.status=`lost`)}markSideResult(e,t){e!==void 0&&e!==``&&((this.world.sideStatus??={})[e]=t)}worldView(){return{variables:this.world.variables,units:this.world.units,sides:this.world.sides,turn:this.world.turn}}emit(){return{move:(e,t,n)=>this.applyMove(e,t,n),attack:(e,t,n)=>{throw Error(`MWL hook attack is not available in the framework runtime; the engine adapter owns combat`)},spawn:(e,t,n,r)=>this.spawnUnit(e,t,n,r),kill:e=>this.killUnit(e),gold:(e,t)=>this.addGold(e,t),setVariable:(e,t)=>{VH(this.world.variables,e,t)},message:(e,t)=>this.onMessage?.({text:t,...e?{speaker:e}:{}}),endTurn:()=>this.endTurn(),win:e=>{this.markSideResult(e,`won`),this.world.status=`won`},lose:e=>{this.markSideResult(e,`lost`),this.world.status=`lost`}}}attack(e,t){let n=this.world.units[e];if(!n||!n.alive)throw Error(`MWL unit is not alive: ${e}`);n.hp=Math.max(0,n.hp-t),n.hp===0&&(n.alive=!1)}nodes(e){let t=[],n=r=>{r.tag===e&&t.push(r),r.children.forEach(n)};return this.game.roots.forEach(n),t}};function wH(e,t){if(e.status===`playing`||t.name===`win`||t.name===`lose`)switch(t.name){case`set_variable`:VH(e.variables,t.target,t.value);break;case`modify_gold`:e.gold[t.target]=(e.gold[t.target]??0)+t.amount;break;case`move`:{let n=DH(e,t.target);n.x=t.x,n.y=t.y;break}case`spawn`:e.units[t.target]={hp:t.hp,x:t.x,y:t.y,alive:!0};break;case`kill`:t.target===void 0?OH(e,t.filter??{}):DH(e,t.target).alive=!1;break;case`end_turn`:e.turn++;break;case`win`:t.side!==void 0&&t.side!==``&&((e.sideStatus??={})[t.side]=`won`),e.status=`won`;break;case`lose`:t.side!==void 0&&t.side!==``&&((e.sideStatus??={})[t.side]=`lost`),e.status=`lost`;break;case`endlevel`:e.status=t.result===`defeat`?`lost`:`won`,e.carryover=_H(e,t.side??null,t)}}function TH(e,t){let n=t??Object.entries(e.sides).find(([,e])=>e.controller===`human`)?.[0];return!n||!(n in e.sides)?null:{id:n}}function EH(e){let t=new Map;for(let[n,r]of Object.entries(e.sides)){if(!r.teamName||r.shareVision===`none`)continue;let e=t.get(r.teamName);e?e.push(n):t.set(r.teamName,[n])}return[...t.values()].filter(e=>e.length>1)}function DH(e,t){let n=e.units[t];if(!n||!n.alive)throw Error(`MWL unit is not alive: ${t}`);return n}function OH(e,t){let n=0;for(let[r,i]of Object.entries(e.units))!i.alive||!PH(i,r,t)||(i.alive=!1,n++);return n}function kH(e){let t={hp:e.hp,x:e.x,y:e.y,alive:e.alive};return e.type!==void 0&&(t.type=e.type),e.side!==void 0&&(t.side=e.side),e.moves!==void 0&&(t.moves=e.moves),e.name!==void 0&&(t.name=e.name),e.role!==void 0&&(t.role=e.role),e.can_recruit!==void 0&&(t.can_recruit=e.can_recruit),e.leader!==void 0&&(t.leader=e.leader),t}function AH(e,t){let n=jH(t.hp);n!==void 0&&(e.hp=n);let r=jH(t.moves);r!==void 0&&(e.moves=r),t.type!==void 0&&(e.type=t.type),t.side!==void 0&&(e.side=t.side);let i=hH(t.alive);i!==void 0&&(e.alive=i),t.name!==void 0&&(e.name=t.name),t.role!==void 0&&(e.role=t.role);let a=hH(t.can_recruit);a!==void 0&&(e.can_recruit=a)}function jH(e){if(e===void 0||e===``)return;let t=Number(e);return Number.isFinite(t)?t:void 0}function MH(e,t){let n=e.attributes[t];if(n===void 0||n===``)return;let r=Number.parseInt(n,10);return Number.isFinite(r)?r:void 0}function NH(e,t,n){let r=e=>{if(!e.startsWith(`$`))return e;let t=n(e.slice(1));return typeof t==`string`||typeof t==`number`||typeof t==`boolean`?t:void 0};if(t.equals!==void 0)return IH(e,r(t.equals));if(t.not_equals!==void 0)return!IH(e,r(t.not_equals));if(t.in!==void 0)return t.in.split(`,`).map(e=>e.trim()).some(t=>IH(e,t));if(t.not_in!==void 0)return!t.not_in.split(`,`).map(e=>e.trim()).some(t=>IH(e,t));let i=typeof e==`number`?e:Number(e),a=e=>Number(t[e]);return t.less_than!==void 0||t.greater_than!==void 0||t.less_than_or_equal_to!==void 0||t.greater_than_or_equal_to!==void 0?!(typeof e==`boolean`||!Number.isFinite(i)||t.less_than!==void 0&&!(i<a(`less_than`))||t.greater_than!==void 0&&!(i>a(`greater_than`))||t.less_than_or_equal_to!==void 0&&!(i<=a(`less_than_or_equal_to`))||t.greater_than_or_equal_to!==void 0&&!(i>=a(`greater_than_or_equal_to`))):e!==void 0}function PH(e,t,n){let r=(n.not_type??``).split(`,`).map(e=>e.trim()).filter(Boolean),i=hH(n.can_recruit),a=hH(n.leader),o=n.unit??n.id;return(o===void 0||t===o)&&(n.side===void 0||e.side===n.side)&&(n.type===void 0||e.type===n.type)&&(r.length===0||!r.includes(e.type??``))&&(n.name===void 0||e.name===n.name)&&(n.role===void 0||e.role===n.role)&&(i===void 0||(e.can_recruit??!1)===i)&&(a===void 0||(e.leader??!1)===a)&&(n.x===void 0||e.x===Number(n.x))&&(n.y===void 0||e.y===Number(n.y))}function FH(e,...t){if(t.length===0)return{...e};let n={...e};for(let e of t)delete n[e];return n}function IH(e,t){if(e===void 0||t===void 0||typeof t!=`string`)return e===t;let n=Number(t);return typeof e==`number`&&t.trim()!==``&&Number.isFinite(n)?e===n:e===t}function LH(e){return Object.fromEntries(Object.entries(e).filter(e=>typeof e[1]==`string`||typeof e[1]==`number`||typeof e[1]==`boolean`))}function RH(e){return e.split(`.`).flatMap(e=>{let t=/^([^[\]]*)((?:\[[^\]]*\])*)$/.exec(e);if(!t)return[e];let n=t[1]===``?[]:[t[1]];for(let e of t[2].matchAll(/\[([^\]]*)\]/g)){let t=Number(e[1]);n.push({index:/^\d+$/.test(e[1].trim())?t:void 0})}return n}).filter(e=>typeof e!=`string`||e!==``)}function zH(e){let t=RH(e);if(t.some(e=>typeof e!=`string`&&e.index===void 0))throw Error(`invalid variable path: ${e}`);return t}function BH(e){return typeof e!=`string`}function VH(e,t,n){let r=zH(t),i=e=>typeof e==`string`?e:e.index,a=e;for(let e=0;e<r.length-1;e++){let t=i(r[e]),n=a[t];(!n||typeof n!=`object`)&&(a[t]=BH(r[e+1])?[]:{}),a=a[t]}a[i(r[r.length-1])]=n}function HH(e,t){let n=e;for(let e of RH(t))if(typeof e==`string`){if(!n||typeof n!=`object`||Array.isArray(n))return;n=n[e]}else{if(!Array.isArray(n)||e.index===void 0)return;n=n[e.index]}return n}function UH(e){return t=>HH(e,t)}function WH(e,t){return e.split(`,`).some(e=>{let n=e.trim(),r=n.match(/^(-?\d+)\s*-\s*(-?\d+)$/);if(r){let e=Number(r[1]),n=Number(r[2]);return t>=Math.min(e,n)&&t<=Math.max(e,n)}return/^-?\d+$/.test(n)&&Number(n)===t})}var GH=/^\s*([A-Za-z_][\w]*)\s*=\s*(.*?)\s*$/;function KH(e){let t=e.split(/\r?\n/),n={},r=0;for(;r<t.length;r++){let e=t[r];if(e.trim()===``)continue;let i=GH.exec(e);if(!i)break;n[i[1]]=i[2]}return{header:n,...SH(t.slice(r).map(e=>e.replace(/[,\s]+$/,``)).join(`
1347
+ `))}}function qH(e){let t=[];for(let n of e.split(`|`)){let e=n.indexOf(`:`);if(e<=0||e===n.length-1)throw Error(`invalid table column "${n}"`);let r=n.slice(0,e).trim(),i=n.slice(e+1).trim();if(!/^[A-Za-z_][\w.-]*$/.test(r))throw Error(`invalid table column name "${r}"`);if(![`string`,`number`,`boolean`,`list`,`map`].includes(i))throw Error(`invalid table column type "${i}"`);if(t.some(e=>e.name===r))throw Error(`duplicate table column "${r}"`);t.push({name:r,type:i})}if(t.length===0)throw Error(`table must declare at least one column`);return t}var JH={game:{attributes:{schema:`string`,title:`string`,data_root:`string`,start_scene:`id`,default_schedule:`id`,save_slot:`string`,turn_limit:`integer`},children:`campaign.terrain_type.movetype.unit_type.unit.side.map.schedule.event.objectives.trait.weapon_special.dialogue.save.item.inventory.monster.status.loot.turn_clock.battle_move.type_matchup.evolution.table.object.story.role`.split(`.`)},campaign:{attributes:{id:`id`,name:`string`,title:`string`,description:`string`,start_scene:`id`,first_scenario:`id`},openChildren:!0},table:{attributes:{id:`id`,columns:`string`,list_delimiter:`string`,map_delimiter:`string`},children:[`row`]},row:{openAttributes:`string`},terrain_type:{attributes:{id:`id`,string:`string`,aliasof:`string`,mvt_alias:`string`,default_base:`string`,heals:`integer`,gives_income:`boolean`,map_code:`string`,base_tile:`string`,overlay_tile:`string`,defense:`number`,healing:`number`}},movetype:{attributes:{id:`id`,name:`string`},children:[`movement_costs`,`defense`,`resistance`]},movement_costs:{openAttributes:`number`},defense:{openAttributes:`number`},resistance:{openAttributes:`number`},unit_type:{attributes:{id:`string`,name:`string`,description:`string`,image:`string`,image_icon:`string`,profile:`string`,sound:`string`,hitpoints:`integer`,movement:`integer`,movement_type:`id`,movetype:`id`,experience:`integer`,level:`integer`,alignment:`id`,cost:`integer`,advances_to:`string`,race:`id`,usage:`id`},children:[`attack`,`trait`,`ability`]},unit:{attributes:{id:`id`,type:`string`,side:`string`,name:`string`,role:`string`,can_recruit:`boolean`,hp:`integer`,x:`integer`,y:`integer`}},attack:{attributes:{id:`id`,attacker:`string`,defender:`string`,target:`string`,amount:`integer`,weapon:`id`,name:`string`,sound:`string`,description:`string`,type:`id`,range:`id`,damage:`integer`,number:`integer`,strikes:`integer`,icon:`string`,specials:`string`}},side:{attributes:{id:`string`,controller:`id`,gold:`integer`,income:`integer`,income_base:`integer`,income_per_village:`integer`,leader:`id`,team:`integer`,recruit:`string`,color:`string`,team_name:`string`,user_team_name:`string`,share_vision:`string`,village_gold:`integer`,heal:`boolean`,fog:`boolean`,shroud:`boolean`,hidden:`boolean`,flag:`string`}},map:{attributes:{id:`id`,name:`string`,file:`string`,terrain:`string`},children:[`start`]},start:{attributes:{side:`string`,x:`integer`,y:`integer`}},schedule:{attributes:{id:`id`},children:[`time`]},time:{attributes:{id:`id`,name:`string`,lawful_bonus:`number`}},event:{attributes:{id:`id`,on:`id`,trigger:`id`,x:`coordinate`,y:`coordinate`,side:`string`,unit:`string`,once:`boolean`},children:`condition.filter.filter_condition.while.foreach.switch.command.say.dialogue.move.attack.spawn.kill.gold.endlevel.set_variable.if.else.message.teleport.end_turn.win.lose.hook.fire_event.store_unit.unstore_unit.recall.modify_unit.heal_unit.set_terrain.capture_village.clear_shroud.role`.split(`.`)},objectives:{attributes:{side:`string`,victory:`string`,defeat:`string`},children:[`victory`,`defeat`]},victory:{attributes:{side:`string`,condition:`id`,type:`string`,x:`integer`,y:`integer`,side_filter:`string`,turns:`integer`,gold:`integer`,hook:`string`,value:`integer`}},defeat:{attributes:{side:`string`,condition:`id`,type:`string`,x:`integer`,y:`integer`,side_filter:`string`,turns:`integer`,gold:`integer`,hook:`string`,value:`integer`}},condition:{attributes:{condition:`id`,hook:`string`,variable:`string`,equals:`string`,not_equals:`string`,in:`string`,not_in:`string`,less_than:`string`,greater_than:`string`,less_than_or_equal_to:`string`,greater_than_or_equal_to:`string`}},filter:{attributes:{side:`string`,type:`string`,not_type:`string`,unit:`string`,name:`string`,role:`string`,x:`integer`,y:`integer`,level:`integer`,alignment:`id`,can_recruit:`boolean`,leader:`boolean`}},filter_condition:{children:[`variable`,`have_unit`,`predicate`]},variable:{attributes:{name:`id`,equals:`string`,not_equals:`string`,in:`string`,not_in:`string`,less_than:`string`,greater_than:`string`,less_than_or_equal_to:`string`,greater_than_or_equal_to:`string`}},have_unit:{attributes:{id:`string`,type:`string`,side:`string`,name:`string`,role:`string`,can_recruit:`boolean`,x:`integer`,y:`integer`}},predicate:{attributes:{name:`id`},openAttributes:`string`},command:{attributes:{name:`id`,target:`string`,value:`string`,amount:`integer`,x:`integer`,y:`integer`,hp:`integer`}},move:{attributes:{unit:`string`,target:`string`,x:`integer`,y:`integer`}},spawn:{attributes:{id:`string`,type:`string`,side:`string`,x:`integer`,y:`integer`,hp:`integer`}},kill:{attributes:{unit:`string`,target:`string`},openAttributes:`string`},gold:{attributes:{side:`string`,delta:`integer`,amount:`integer`}},endlevel:{attributes:{result:`id`,side:`string`,bonus:`integer`,carryover_percentage:`integer`,carryover_add:`boolean`,next_scenario:`id`}},set_variable:{attributes:{name:`id`,target:`id`,value:`string`}},if:{attributes:{test:`string`},children:[`condition`,`while`,`foreach`,`switch`,`if`,`else`,`command`,`message`,`move`,`attack`,`spawn`,`kill`,`gold`,`set_variable`,`win`,`lose`,`hook`]},else:{children:[`condition`,`while`,`foreach`,`switch`,`if`,`else`,`command`,`message`,`move`,`attack`,`spawn`,`kill`,`gold`,`set_variable`,`win`,`lose`,`hook`]},while:{attributes:{test:`string`,max_iterations:`integer`},children:[`condition`,`while`,`foreach`,`switch`,`if`,`else`,`message`,`move`,`attack`,`spawn`,`kill`,`gold`,`set_variable`,`win`,`lose`,`hook`]},foreach:{attributes:{variable:`id`,item:`id`,index:`id`},children:[`while`,`foreach`,`switch`,`if`,`else`,`message`,`move`,`attack`,`spawn`,`kill`,`gold`,`set_variable`,`win`,`lose`,`hook`]},switch:{attributes:{variable:`id`},children:[`case`,`default`]},case:{attributes:{equals:`string`},children:[`while`,`foreach`,`switch`,`if`,`else`,`message`,`move`,`attack`,`spawn`,`kill`,`gold`,`set_variable`,`win`,`lose`,`hook`,`dialogue`]},default:{children:[`while`,`foreach`,`switch`,`if`,`else`,`message`,`move`,`attack`,`spawn`,`kill`,`gold`,`set_variable`,`win`,`lose`,`hook`,`dialogue`]},message:{attributes:{speaker:`string`,text:`string`,value:`string`,portrait:`string`,side:`string`}},teleport:{attributes:{unit:`string`,target:`string`,x:`integer`,y:`integer`}},end_turn:{attributes:{}},win:{attributes:{side:`string`}},lose:{attributes:{side:`string`}},say:{attributes:{speaker:`id`,text:`string`}},dialogue:{attributes:{id:`id`,ref:`id`},children:[`say`,`choice`,`branch`,`message`]},choice:{attributes:{text:`string`,event:`id`,variable:`id`,equals:`string`},children:[`branch`]},branch:{attributes:{text:`string`},children:[`message`,`say`,`command`,`set_variable`,`move`,`attack`,`spawn`,`kill`,`gold`,`hook`]},trait:{attributes:{id:`id`,name:`string`},children:[`effect`]},ability:{attributes:{id:`id`,name:`string`},children:[`effect`]},weapon_special:{attributes:{id:`id`,name:`string`}},hook:{attributes:{name:`string`},openAttributes:`string`},fire_event:{attributes:{id:`id`,name:`string`}},store_unit:{attributes:{variable:`string`,name:`string`},children:[`filter`]},unstore_unit:{attributes:{variable:`string`,name:`string`}},recall:{attributes:{variable:`string`,id:`string`,unit:`string`,side:`string`,x:`integer`,y:`integer`}},modify_unit:{attributes:{hp:`integer`,moves:`integer`,type:`string`,side:`string`,alive:`boolean`},children:[`filter`,`set`]},set:{openAttributes:`string`},heal_unit:{attributes:{amount:`integer`,hp:`integer`,side:`string`,type:`string`,x:`integer`,y:`integer`},children:[`filter`]},set_terrain:{attributes:{terrain:`string`,x:`integer`,y:`integer`}},capture_village:{attributes:{side:`string`,x:`integer`,y:`integer`,name:`string`}},clear_shroud:{attributes:{side:`string`,x:`integer`,y:`integer`,radius:`integer`}},role:{attributes:{role:`string`,name:`string`,type:`string`,not_type:`string`,unit:`string`,side:`string`,can_recruit:`boolean`,x:`integer`,y:`integer`},children:[`filter`]},object:{attributes:{id:`id`,name:`string`,image:`string`,side:`string`,x:`integer`,y:`integer`},children:[`filter`]},story:{attributes:{text:`string`,value:`string`,title:`string`,image:`string`,music:`string`}},item:{attributes:{id:`id`,name:`string`,slot:`id`,stackable:`boolean`,weight:`number`},children:[`effect`]},inventory:{attributes:{unit:`string`,side:`string`,items:`string`}},monster:{attributes:{id:`string`,name:`string`,hp:`integer`,types:`string`,attack:`number`,defense:`number`,speed:`number`,accuracy:`number`,evasion:`number`,damage_min:`integer`,damage_max:`integer`,armor_min:`integer`,armor_max:`integer`,experience:`integer`,max_level:`integer`,image:`string`},children:[`ability`,`loot`]},status:{attributes:{id:`id`,name:`string`,duration:`integer`,tick:`string`,modifiers:`string`}},loot:{attributes:{item:`id`,chance:`number`,quantity:`integer`,weight:`number`}},turn_clock:{attributes:{id:`id`,tick:`number`,hunger:`number`}},ai:{attributes:{id:`id`,strategy:`id`,target:`id`,difficulty:`number`,scope:`id`,provider:`id`,algorithm:`id`,depth:`integer`,max_nodes:`integer`,player:`string`,moves:`string`,apply:`string`,terminal:`string`,evaluate:`string`},children:[`behavior`]},behavior:{attributes:{id:`id`,when:`string`,action:`string`,hook:`string`}},battle_move:{attributes:{id:`id`,type:`id`,target:`id`,power:`number`,cost:`number`}},type_matchup:{attributes:{attacker:`id`,defender:`id`,multiplier:`number`}},evolution:{attributes:{from:`id`,into:`id`,level:`integer`}},effect:{attributes:{apply_to:`id`,range:`id`,increase:`string`,increase_total:`string`,increase_damage:`string`,add:`string`,sub:`string`,multiply:`string`,divide:`string`,set:`string`}},save:{attributes:{version:`integer`,fields:`string`,migration:`string`}}};function YH(e,t=JH){let n=[],r=new Map,i=e=>{let t=e.attributes.id;t&&r.set(t,[...r.get(t)??[],e]),e.children.forEach(i)};e.forEach(i);let a=[],o=(e,i=!1)=>{let s=t[e.tag];if(!s){if(i){e.children.forEach(e=>o(e,!0));return}n.push({code:`MWL_UNKNOWN_TAG`,message:`unknown tag ${e.tag}`,location:e.location});return}for(let t of Object.keys(e.attributes))s.openAttributes||(!s.attributes||!(t in s.attributes))&&n.push({code:`MWL_UNKNOWN_ATTRIBUTE`,message:`unknown attribute ${t} on ${e.tag}`,location:e.location});for(let[t,i]of Object.entries(s.attributes??{})){let o=e.attributes[t];if(o!==void 0&&!$H(o,i)&&n.push({code:`MWL_VALUE`,message:`${t} must be ${i}`,location:e.location}),o!==void 0&&i===`ref`){let i=(r.get(o)??[]).filter(e=>{let n=s.refTargets?.[t];return!n||n===`*`||e.tag===n});i.length===0?n.push({code:`MWL_REF_MISSING`,message:`${t} references missing target ${o}`,location:e.location}):i.length>1?n.push({code:`MWL_REF_DUPLICATE`,message:`${t} references ambiguous target ${o}`,location:e.location}):s.acyclicRefs?.includes(t)&&a.push({from:e,to:i[0],name:t})}}if(s.openAttributes)for(let[t,r]of Object.entries(e.attributes))$H(r,s.openAttributes)||n.push({code:`MWL_VALUE`,message:`${t} must be ${s.openAttributes}`,location:e.location});for(let t of e.children)!s.openChildren&&s.children&&!s.children.includes(t.tag)&&n.push({code:`MWL_CHILD`,message:`${t.tag} is not allowed inside ${e.tag}`,location:t.location}),o(t,s.openChildren===!0)};e.forEach(e=>o(e)),XH(e,n);let s=new Set,c=new Set,l=(e,t)=>{if(s.has(e)){let r=t.indexOf(e);n.push({code:`MWL_REF_CYCLE`,message:`reference cycle through ${t.slice(r).map(e=>e.attributes.id??e.tag).join(` -> `)}`,location:e.location});return}if(!c.has(e)){s.add(e);for(let n of a.filter(t=>t.from===e))l(n.to,[...t,e]);s.delete(e),c.add(e)}};for(let e of a)l(e.from,[]);return n.sort((e,t)=>e.location.line-t.location.line||e.location.column-t.location.column)}function XH(e,t){let n=e=>{if(e.tag===`table`){let n;try{n=qH(e.attributes.columns??``)}catch(r){t.push({code:`MWL_TABLE`,message:String(r).replace(/^Error: /,``),location:e.location}),n=[]}let r=new Map(n.map(e=>[e.name,e]));for(let i of e.children.filter(e=>e.tag===`row`)){for(let e of Object.keys(i.attributes))r.has(e)||t.push({code:`MWL_TABLE`,message:`unknown table column ${e}`,location:i.location});for(let r of n){let n=i.attributes[r.name];if(n===void 0){t.push({code:`MWL_TABLE`,message:`missing table column ${r.name}`,location:i.location});continue}try{ZH(n,r.type,r.name,e.attributes.list_delimiter,e.attributes.map_delimiter)}catch(e){t.push({code:`MWL_TABLE`,message:String(e).replace(/^Error: /,``),location:i.location})}}}}e.children.forEach(n)};e.forEach(n)}function ZH(e,t,n,r=`;`,i=`=`){return Un(e,t,{column:n,listDelimiter:r,mapDelimiter:i,acceptYesNo:!0})}function QH(e){return/^[A-Za-z_][\w.[\]-]*$/.test(e)}function $H(e,t){return t===`number`?Number.isFinite(Number(e)):t===`integer`?/^-?\d+$/.test(e):t===`boolean`?e===`true`||e===`false`||e===`yes`||e===`no`:t===`ref`?/^[A-Za-z_][\w.-]*$/.test(e):t===`coordinate`?/^-?\d+(?:\s*,\s*-?\d+|\s*-\s*-?\d+)*$/.test(e):t!==`id`||QH(e)}function eU(e,t={}){return nU(qV(GV(e,t),t.file),t)}function tU(e,t={}){let n=[];for(let r of[...e].sort((e,t)=>e.file<t.file?-1:+(e.file>t.file))){let e=GV(r.source,{...t,file:r.file});n.push(...qV(e,r.file))}return nU(n,t)}function nU(e,t={}){let n=YH(e,t.schemas);if(n.length){let e=n[0];throw Error(`${e.location.file}:${e.location.line}:${e.location.column}: ${e.message}`)}let r=new Set,i=new Set,a=e=>{for(let[t,n]of Object.entries(e.attributes))if(rU(t))for(let e of aU(n).map(e=>e.trim()).filter(iU))r.add(oU(e));let t=e.gettext??[`name`,`text`,`title`];for(let n of t){let t=e.attributes[n];t!==void 0&&i.add(t)}let n={tag:e.tag,attributes:{...e.attributes},children:e.children.map(a),location:e.location};return e.gettext?{...n,gettext:[...e.gettext]}:n};return{schema:e.find(e=>e.tag===`game`)?.attributes.schema??`0.1`,roots:e.map(a),assets:[...r].sort(),messages:[...i].sort()}}function rU(e){return e===`file`||e===`image`||e===`image_icon`||e===`icon`||e===`profile`||e===`sound`||e.endsWith(`_sound`)||e.endsWith(`_image`)}function iU(e){return e.includes(`/`)||/\.(?:png|jpg|jpeg|gif|svg|webp|wav|ogg|mp3|flac|glb|gltf|vox|map|cfg)$/i.test(e)||e.startsWith(`data:`)}function aU(e){let t=[],n=0,r=0,i=0;for(let a=0;a<e.length;a+=1)e[a]===`(`?r+=1:e[a]===`)`&&r>0?--r:e[a]===`[`?i+=1:e[a]===`]`&&i>0?--i:e[a]===`,`&&r===0&&i===0&&(t.push(e.slice(n,a)),n=a+1);return t.push(e.slice(n)),t}function oU(e){let t=e.match(/~[A-Za-z][A-Za-z0-9_-]*(?:\(|$)/);return t?e.slice(0,t.index).trim():e}function sU(e,t={}){let n={};for(let t of e.messages)n[t]=t;return{locale:t.locale??`en`,direction:t.direction??`ltr`,messages:n}}function cU(e,t=`gameData`){return`export const ${t} = ${JSON.stringify(e,null,` `)} as const;\n`}function lU(e,t={}){let n=[{name:`game-data.ts`,content:cU(e,t.variable??`gameData`)},{name:`i18n.json`,content:`${JSON.stringify(sU(e),null,` `)}\n`},{name:`assets.json`,content:`${JSON.stringify({assets:e.assets},null,` `)}\n`},...Object.entries(t.artifacts??{}).sort(([e],[t])=>e<t?-1:+(e>t)).map(([e,t])=>({name:e,content:t}))];for(let e of n)t.onEmit?.(e);return n}function uU(e,t={},n={}){let r=lU(tU(e,t),n),i=lU(tU(e,t),n);if(r.length!==i.length||r.some((e,t)=>e.name!==i[t]?.name||e.content!==i[t]?.content))throw Error(`MWL generated artifacts are not deterministic`);return r}var dU=[`predicate`,`modifier`,`generator`,`command`,`ai`,`migration`];function fU(e){let t=e.indexOf(`:`);if(t<=0)return null;let n=e.slice(0,t),r=e.slice(t+1).trim();return!dU.includes(n)||!r?null:{type:n,name:r}}var pU=new Set([`hook`,`migration`]);function mU(e){let t=new Map,n=e=>{for(let[t,n]of Object.entries(e.attributes))pU.has(t)&&r(n,e.location),e.tag===`hook`&&t===`name`&&r(n,e.location);e.children.forEach(n)},r=(e,n)=>{let r=fU(e);if(!r)return;let i=`${r.type}:${r.name}`;t.has(i)||t.set(i,{...r,location:n})};return e.roots.forEach(n),[...t.values()].sort((e,t)=>e.type.localeCompare(t.type)||e.name.localeCompare(t.name))}function hU(e,t){let n=new Set(t),r=[];for(let t of e){let e=`${t.type}:${t.name}`;n.has(e)||r.push({code:`MWL_HOOK`,message:`hook ${e} is not implemented`,location:t.location??{file:`<hook>`,line:0,column:0}})}return r}function gU(e){let t=[];t.push(`// Generated by mwl - do not edit.`),t.push(`import type { AiHook, CommandHook, GeneratorHook, MigrationHook, ModifierHook, PredicateHook } from '@datamoc/mw_games/mwl';`),t.push(``),t.push(`export interface MwlHooks {`);for(let n of e){let e=`${n.type[0].toUpperCase()}${n.type.slice(1)}Hook`;t.push(`\t'${n.type}:${n.name}': ${e};`)}return t.push(`}`),t.push(``),t.join(`
1348
+ `)}function _U(e,t){let n=e.scenarios;if(n.length===0)throw Error(`campaign ${e.id} declares no scenarios`);let r=new Set(n.map(e=>e.id));if(r.size!==n.length)throw Error(`campaign ${e.id} declares a scenario twice`);let i=e.firstScenario||n[0].id;if(!r.has(i))throw Error(`campaign ${e.id} starts on an unknown scenario: ${i}`);return{start:i,levels:n.map(e=>({id:e.id,run:(n,r)=>{let i=t.run(e,n,r);return i.next===void 0?{...i,next:e.nextScenario??null}:i}}))}}var vU=dH,yU=fH,bU=pH,xU=mH,SU=gH;function CU(e){let t=uH(e.roots);return{campaigns:t.filter(e=>e.tag===`campaign`).map(e=>({id:vU(e,`id`),name:e.attributes.name,title:e.attributes.title,description:e.attributes.description,startScene:e.attributes.start_scene,firstScenario:e.attributes.first_scenario,scenarios:e.children.filter(e=>e.tag===`scenario`).map(e=>({id:vU(e,`id`),nextScenario:e.attributes.next_scenario||void 0}))})),items:t.filter(e=>e.tag===`item`).map(e=>({id:vU(e,`id`),name:vU(e,`name`),slot:e.attributes.slot,stackable:xU(e,`stackable`),weight:yU(e,`weight`),effects:e.children.filter(e=>e.tag===`effect`).map(TU)})),monsters:t.filter(e=>e.tag===`monster`).map(e=>({id:vU(e,`id`),name:e.attributes.name,hp:bU(e,`hp`,1),accuracy:yU(e,`accuracy`),evasion:yU(e,`evasion`),damage:EU(e,`damage_min`,`damage_max`),armor:EU(e,`armor_min`,`armor_max`),experience:bU(e,`experience`),maxLevel:bU(e,`max_level`),image:e.attributes.image,types:e.attributes.types?.split(`,`).map(e=>e.trim()).filter(Boolean),baseStats:[`attack`,`defense`,`speed`,`hp`].reduce((t,n)=>{let r=yU(e,n);return r!==void 0&&(t[n===`hp`?`maxHp`:n]=r),t},{})})),statuses:t.filter(e=>e.tag===`status`).map(e=>({id:vU(e,`id`),name:e.attributes.name,duration:bU(e,`duration`),tick:e.attributes.tick,modifiers:e.attributes.modifiers})),loot:t.filter(e=>e.tag===`loot`).map(e=>({item:vU(e,`item`),chance:yU(e,`chance`),quantity:bU(e,`quantity`),weight:yU(e,`weight`)})),turnClocks:t.filter(e=>e.tag===`turn_clock`).map(e=>({id:vU(e,`id`),tick:yU(e,`tick`),hunger:yU(e,`hunger`)})),ai:t.filter(e=>e.tag===`ai`).map(e=>({id:vU(e,`id`),strategy:e.attributes.strategy,target:e.attributes.target,difficulty:yU(e,`difficulty`),scope:SU(e.attributes.scope,[`actor`,`controller`]),provider:SU(e.attributes.provider,[`javascript`,`lua`]),algorithm:SU(e.attributes.algorithm,[`rules`,`alpha_beta`]),depth:bU(e,`depth`),maxNodes:bU(e,`max_nodes`),player:e.attributes.player,moves:e.attributes.moves,apply:e.attributes.apply,terminal:e.attributes.terminal,evaluate:e.attributes.evaluate,behaviors:e.children.filter(e=>e.tag===`behavior`).map(e=>({id:vU(e,`id`),when:e.attributes.when,action:e.attributes.action,hook:e.attributes.hook}))})),moves:t.filter(e=>e.tag===`battle_move`).map(e=>({id:vU(e,`id`),type:vU(e,`type`),target:vU(e,`target`),power:yU(e,`power`),cost:yU(e,`cost`)})),typeMatchups:t.filter(e=>e.tag===`type_matchup`).map(e=>({attacker:vU(e,`attacker`),defender:vU(e,`defender`),multiplier:yU(e,`multiplier`)??1})),evolutions:t.filter(e=>e.tag===`evolution`).map(e=>({from:vU(e,`from`),into:vU(e,`into`),level:bU(e,`level`,1)})),tables:t.filter(e=>e.tag===`table`).map(wU)}}function wU(e){let t=qH(vU(e,`columns`));return{id:vU(e,`id`),columns:t,rows:e.children.filter(e=>e.tag===`row`).map(n=>{let r={};for(let i of t){let t=n.attributes[i.name];t!==void 0&&(r[i.name]=ZH(t,i.type,i.name,e.attributes.list_delimiter,e.attributes.map_delimiter))}return r})}}function TU(e){let t=[`add`,`sub`,`multiply`,`divide`,`set`,`increase`,`increase_total`,`increase_damage`].find(t=>e.attributes[t]!==void 0);return{applyTo:vU(e,`apply_to`),operation:t,value:t?e.attributes[t]:void 0,range:e.attributes.range}}function EU(e,t,n){let r=yU(e,t),i=yU(e,n);return r===void 0||i===void 0?void 0:[r,i]}function DU(e,t={}){return{id:e.id,stackable:e.stackable,weight:e.weight,slot:e.slot,modifiers:e.effects.map(e=>AU(e,t))}}function OU(e,t=1){return{id:e.id,quantity:t,stackable:e.stackable,weight:e.weight}}function kU(e,t,n={}){return sL(e,t.map(e=>AU(e,n)))}function AU(e,t={}){let n=e.operation;if(n!==`add`&&n!==`sub`&&n!==`multiply`&&n!==`divide`&&n!==`set`)throw Error(`MWL effect operation "${n??``}" is not a StatBlock modifier`);let r=e.value;if(r===void 0)throw Error(`MWL effect has no value`);let i=cH(r,t);return{stat:e.applyTo,op:n===`sub`?`add`:n===`divide`?`multiply`:n,value:n===`sub`?-i:n===`divide`?1/i:i}}function jU(e,t={}){let n=[],r=new Map,i=uH(e.roots);for(let e of i){let i=e.attributes.id;if(i){let t=`${e.tag}:${i}`,a=r.get(t);a?n.push(MU(`MWL_DUPLICATE_ID`,`duplicate ${e.tag} id "${i}"`,e.location??a.location)):r.set(t,e)}if(e.tag===`item`&&t.slots&&e.attributes.slot&&!t.slots.includes(e.attributes.slot)&&n.push(MU(`MWL_UNKNOWN_SLOT`,`unknown equipment slot "${e.attributes.slot}"`,e.location)),e.tag===`effect`){let t=[`add`,`sub`,`multiply`,`divide`,`set`,`increase`,`increase_total`,`increase_damage`].filter(t=>e.attributes[t]!==void 0);(!e.attributes.apply_to||t.length!==1)&&n.push(MU(`MWL_INCOMPLETE_EFFECT`,`an effect needs apply_to and exactly one operation`,e.location))}}let a=mU(e),o=new Set(t.hooks??[]);for(let e of i){let t=e.attributes.hook??(e.tag===`hook`?e.attributes.name:void 0);t!==void 0&&!fU(t)&&n.push(MU(`MWL_INVALID_HOOK`,`invalid hook reference "${t}"`,e.location))}if(t.hooks)for(let e of a)o.has(`${e.type}:${e.name}`)||n.push(MU(`MWL_UNKNOWN_HOOK`,`hook ${e.type}:${e.name} is not declared by the game`,e.location));return n}function MU(e,t,n){return{code:e,message:t,location:n??{file:`<mwl>`,line:1,column:1}}}function NU(e,t={}){return jU({schema:`0.1`,roots:e,assets:[],messages:[]},t)}function PU(e,t={}){try{let n=tU(e,t),r=FU(n),i=[];for(let e of r.opaqueTags)i.push({severity:`warning`,code:`opaque-tag`,message:`ignored opaque tag: ${e}`});for(let e of r.danglingReferences)i.push({severity:`error`,code:`dangling-reference`,message:`dangling content reference: ${e}`});return{game:n,resources:[...n.assets],dependencies:[...r.references],ignored:[...r.opaqueTags],diagnostics:i}}catch(e){return{resources:[],dependencies:[],ignored:[],diagnostics:[{severity:`error`,code:`compile`,message:String(e)}]}}}function FU(e){let t=uH(e.roots),n={},r=new Set;for(let e of t)n[e.tag]=(n[e.tag]??0)+1,e.attributes.id&&r.add(e.attributes.id);let i=new Set(Object.keys(JH)),a=t.filter(e=>!i.has(e.tag)).map(e=>e.tag).filter((e,t,n)=>n.indexOf(e)===t).sort(),o=new Set;for(let e of t)for(let[t,n]of Object.entries(e.attributes))if(/^(?:ability|item|terrain|unit|unit_type|weapon)(?:_id)?$/.test(t))for(let e of n.split(`,`).map(e=>e.trim()).filter(Boolean))o.add(e);return{tags:Object.fromEntries(Object.entries(n).sort(([e],[t])=>e.localeCompare(t))),opaqueTags:a,references:[...o].sort(),danglingReferences:[...o].filter(e=>!r.has(e)).sort()}}function IU(e,t){let n={},r=[];for(let[i,a]of Object.entries(t)){let t=a.source??i,o=e.attributes[t];if(o===void 0){a.required?r.push(zU(`MWL_REQUIRED_FIELD`,`missing required attribute "${t}"`,e)):a.default!==void 0&&(n[i]=a.default);continue}let s=RU(o,a.type);s===void 0?r.push(zU(`MWL_FIELD_TYPE`,`invalid ${a.type} attribute "${t}": "${o}"`,e)):n[i]=s}return{value:n,diagnostics:r}}function LU(e,t,n){let r=[],i=[];for(let a of e.children){if(a.tag!==t)continue;let e=n(a);r.push(e.value),i.push(...e.diagnostics)}return{value:r,diagnostics:i}}function RU(e,t){if(t===`string`)return e;if(t===`id`)return QH(e)?e:void 0;if(t===`number`)return Number.isFinite(Number(e))?Number(e):void 0;if(t===`integer`)return/^-?\d+$/.test(e)?Number(e):void 0;if(t===`boolean`)return e===`true`||e===`yes`?!0:e===`false`||e===`no`?!1:void 0;let n=e.split(`,`).map(e=>e.trim()).filter(Boolean);return t===`id-list`?n.every(e=>QH(e))?n:void 0:n.every(e=>Number.isFinite(Number(e)))?n.map(Number):void 0}function zU(e,t,n){return{code:e,message:t,location:n.location??{file:`<mwl>`,line:1,column:1}}}function BU(){return{evaluate(e,t={}){let n={};for(let[e,r]of Object.entries(t)){if(typeof r!=`number`)throw Error(`MWL expression context value must be numeric: ${e}`);n[e]=r}return cH(e,n)},execute(){throw Error(`the expression ScriptHost cannot execute statements`)},call(){throw Error(`the expression ScriptHost cannot call functions`)},dispose(){}}}var VU=l({MWL_DEFAULT_CARRYOVER_PERCENTAGE:()=>80,MwlRuntime:()=>CH,MwlSyntaxError:()=>UV,campaignChain:()=>_U,carryoverIntoScenario:()=>vH,coerceTableValue:()=>ZH,collectHookReferences:()=>mU,compile:()=>eU,compileAndEmitSources:()=>uU,compileNodes:()=>nU,compileSources:()=>tU,composeEffects:()=>kU,contentCatalog:()=>CU,contentReport:()=>FU,createExpressionScriptHost:()=>BU,createWorld:()=>xH,decodeSave:()=>eH,effectToModifier:()=>AU,emitArtifacts:()=>lU,emitHooksDeclaration:()=>gU,emitModule:()=>cU,encodeSave:()=>$V,endLevelCarryover:()=>_H,evaluateCondition:()=>rH,evaluateExpression:()=>cH,execute:()=>wH,extractCatalog:()=>sU,hookTypes:()=>dU,inventoryItem:()=>OU,isGettext:()=>YV,isMwlId:()=>QH,itemDefinition:()=>DU,loadContent:()=>PU,parse:()=>qV,parseExpression:()=>sH,parseHookReference:()=>fU,parseMapFile:()=>KH,parseTableColumns:()=>qH,parseTerrain:()=>SH,parseValue:()=>JV,preprocess:()=>GV,readAttributes:()=>IU,readChildren:()=>LU,schema01:()=>JH,sideVisionGroups:()=>EH,validate:()=>YH,validateCatalog:()=>jU,validateCatalogNodes:()=>NU,validateHookReferences:()=>hU,validateWorld:()=>tH});function HU(e,t){return e.filter(e=>(t.side===void 0||e.side===t.side)&&(t.type===void 0||e.type===t.type)&&(t.role===void 0||e.role===t.role)&&(t.can_recruit===void 0||(e.can_recruit??!1)===t.can_recruit)&&(t.name===void 0||e.name===t.name))}function UU(e,t,n,r){let i=0,a=0,o=1;for(let s of t)s.id!==e.id&&r(s.x,s.y)&&(o++,s.side===e.side?i+=n(s.id):a+=n(s.id));return{own:n(e.id),allies:i,enemies:a,seen:o}}function WU(e,t,n,r){let i=0,a=0,o=0;for(let s of t)r(s.x,s.y)&&(o++,s.side===e?i+=n(s.id):a+=n(s.id));return{own:0,allies:i,enemies:a,seen:o}}function GU(e,t){return e.own*t.own+e.allies*t.allies+e.enemies*t.enemies}var KU=class e{constructor(e={}){this.values={};for(let[t,n]of Object.entries(e))n!==void 0&&(this.values[t]=n)}has(e){return this.values[e]!==void 0}get(e){return this.values[e]}set(e,t){this.values[e]=t}number(e,t=0){let n=this.values[e];return typeof n==`number`&&Number.isFinite(n)?n:typeof n==`boolean`?+!!n:t}flag(e,t=!1){let n=this.values[e];return typeof n==`boolean`?n:t}list(e){let t=this.values[e];return Array.isArray(t)?t:typeof t==`string`?[t]:[]}names(){return Object.keys(this.values)}with(t){let n=new e(this.values);for(let[e,r]of Object.entries(t))r!==void 0&&n.set(e,r);return n}toJSON(){return{...this.values}}static fromJSON(t){return new e(t)}},qU=class{constructor(e=[],t={}){this.levels=new Map,this.base=new KU(t);for(let t of e){if(this.levels.has(t.id))throw Error(`duplicate difficulty level: ${t.id}`);this.levels.set(t.id,t)}}get ids(){return[...this.levels.keys()]}get(e){return this.levels.get(e)}aspectsFor(e){let t=this.levels.get(e);if(!t)throw Error(`unknown difficulty level: ${e}`);return this.base.with(t.aspects??{})}},JU=class{constructor(){this.byUnit=new Map}set(e){this.byUnit.set(e.unit,{...e})}clear(e){this.byUnit.delete(e)}get(e){return this.byUnit.get(e)}all(){return[...this.byUnit.values()]}get isEmpty(){return this.byUnit.size===0}},YU=class{constructor(e,t=null){this.order=e,this.fallback=t}get length(){return this.order.length}at(e){if(this.order.length===0)return this.fallback;let t=(e%this.order.length+this.order.length)%this.order.length;return this.order[t]}next(e){if(this.order.length===0)return this.fallback;if(e===null)return this.order[0];let t=this.order.indexOf(e);return this.at(t<0?0:t+1)}},XU=class{constructor(e){this.stages=e.stages}decide(e,t){if(e.length===0)return null;for(let n of this.stages){if(n.when&&!n.when(t))continue;let r=n.weigh??ZU,i=null;for(let a of e){let e=r(a,t);(!i||e>i.score)&&(i={candidate:a,stage:n.id,score:e})}return i}return null}};function ZU(e,t){let n=0;for(let[r,i]of Object.entries(e.factors??{}))r!==`distance`&&(n+=i*t.aspects.number(r,1));let r=e.factors?.distance;return r!==void 0&&(n+=QU(r,t.aspects.number(`keep_away`,0))),n}function QU(e,t){return!(t>0)||e>=t?0:-(t-e)}function $U(e){return e?Math.max(0,e.priority??1):0}var eW=l({AIBudgetExceededError:()=>aW,AICancelledError:()=>iW,Aspects:()=>KU,Difficulty:()=>qU,Goals:()=>JU,HeuristicAI:()=>XU,JavaScriptAI:()=>rW,RecruitmentPattern:()=>YU,alphaBetaSearch:()=>Rz,defaultWeigh:()=>ZU,goalScore:()=>$U,keepAwayScore:()=>QU,personalScoreView:()=>UU,scoreWith:()=>GU,sideScoreView:()=>WU,subjectsWhere:()=>HU}),tW=1e4,nW=16,rW=class{constructor(e={}){this.agents=new Map,this.states=new Map,this.options=e,uW(e.maxSteps??tW,`maxSteps`),dW(e.maxMilliseconds??nW,`maxMilliseconds`)}register(e){if(!/^[A-Za-z_][A-Za-z0-9_.-]*$/.test(e.id))throw Error(`invalid AI agent id: ${e.id}`);if(this.agents.has(e.id))throw Error(`AI agent already registered: ${e.id}`);if(!e.behaviors.length)throw Error(`AI agent has no behaviours: ${e.id}`);let t=new Set;for(let n of e.behaviors){if(!n.id||t.has(n.id))throw Error(`duplicate AI behaviour: ${n.id}`);t.add(n.id)}this.agents.set(e.id,e),this.states.set(e.id,{})}decide(e,t){let n=this.agents.get(e);if(!n)throw Error(`unknown AI agent: ${e}`);let r=sW(t.state??this.states.get(e)??{}),i=t.maxSteps??this.options.maxSteps??tW,a=t.maxMilliseconds??this.options.maxMilliseconds??nW;uW(i,`maxSteps`),dW(a,`maxMilliseconds`);let o=0,s=fW(),c=[],l=lW(t.seed??this.options.seed??7173991),u=()=>{if(o++,t.signal?.aborted)throw new iW;if(o>i||fW()-s>a)throw new aW},d={perception:cW(t.perception),state:r,random:()=>(u(),l()),checkpoint:u,emit(e,t){if(!e)throw Error(`AI event name must not be empty`);u(),c.push(t===void 0?{name:e}:{name:e,payload:cW(t)})}},f=null,p,m=`idle`;try{for(let e of n.behaviors)if(u(),!(e.when&&!e.when(d))){p=e.id,f=oW(e.decide(d)),m=f?`action`:`idle`;break}}catch(e){if(e instanceof iW)m=`cancelled`;else if(e instanceof aW)m=`budget-exceeded`;else throw e}let h={agent:e,action:f,state:sW(r),behavior:p,status:m,steps:o,events:c};return this.states.set(e,sW(r)),this.options.onDecision?.(h),h}search(e,t,n){return Rz(e,t,n)}exportState(){return{version:1,agents:Object.fromEntries([...this.states].map(([e,t])=>[e,sW(t)]))}}importState(e){if(e.version!==1)throw Error(`unsupported AI state version: ${e.version}`);for(let[t,n]of Object.entries(e.agents)){if(!this.agents.has(t))throw Error(`AI state names unknown agent: ${t}`);this.states.set(t,sW(n))}}dispose(){this.agents.clear(),this.states.clear()}},iW=class extends Error{constructor(){super(`AI decision cancelled`),this.name=`AICancelledError`}},aW=class extends Error{constructor(){super(`AI decision budget exceeded`),this.name=`AIBudgetExceededError`}};function oW(e){if(e===null)return null;if(!e||typeof e!=`object`||Array.isArray(e)||typeof e.type!=`string`||!e.type)throw Error(`AI action must be an object with a non-empty string type`);return cW(e)}function sW(e){return cW(e)}function cW(e){return typeof e!=`object`||!e?e:Array.isArray(e)?e.map(cW):Object.fromEntries(Object.entries(e).map(([e,t])=>[e,cW(t)]))}function lW(e){if(!Number.isInteger(e))throw TypeError(`AI seed must be an integer`);let t=e>>>0;return()=>(t=Math.imul(t,1664525)+1013904223>>>0,t/4294967296)}function uW(e,t){if(!Number.isInteger(e)||e<1)throw RangeError(`${t} must be a positive integer`)}function dW(e,t){if(!Number.isFinite(e)||e<0)throw RangeError(`${t} must be a non-negative number`)}function fW(){return typeof performance>`u`?Date.now():performance.now()}return wi(),W(),Xa(),Object.defineProperty(e,"AI",{enumerable:!0,get:function(){return eW}}),e.Achievements=$t,e.ActionJournal=Zt,e.ActorAnimator=fj,Object.defineProperty(e,"Actors",{enumerable:!0,get:function(){return iR}}),e.AnimatedSprite=hA,e.Animation=pA,Object.defineProperty(e,"Audio",{enumerable:!0,get:function(){return PV}}),e.BLOB_SHAPES=mj,e.Bar=tF,Object.defineProperty(e,"Battle",{enumerable:!0,get:function(){return mz}}),e.BitmapLabel=PM,e.Blob=En,Object.defineProperty(e,"Board",{enumerable:!0,get:function(){return pV}}),e.Button=eF,e.COLOR_BLINDNESS_MATRICES=GA,e.Camera=RA,e.Checkbox=MP,e.Collection=Kt,e.ColorTransformBatcher=kk,e.Container2D=G,e.DataTable=LP,e.DialogueStage=CF,e.Dropdown=FP,e.EMPTY=XA,e.Easing=Dn,e.EntityRegistry=Pn,e.FLOATING_TEXT_STACK_GAP=sF,e.FeedbackClient=nn,e.FloatingText=oF,e.FloatingTextStack=dF,e.Game=yk,e.Generator=w,e.Gradient=jj,e.Grid=GP,e.HALO_ANIMATION=sj,e.Halo=cj,e.HelpScreen=mF,e.HookRegistry=x,Object.defineProperty(e,"I18n",{enumerable:!0,get:function(){return XN}}),e.IconGrid=WM,Object.defineProperty(e,"Input",{enumerable:!0,get:function(){return ve}}),e.Label=Zj,e.LayeredSprite=rj,e.LightningArc=aj,e.ListView=UM,e.LoadQueue=Nn,e.LoadingScreen=gF,e.LockstepClient=Rt,e.Logger=y,e.MarkupText=kM,e.MersenneTwister=he,e.MessageBox=TP,e.Minimap=YA,Object.defineProperty(e,"Mwl",{enumerable:!0,get:function(){return VU}}),e.NO_COLOR_ADD=zk,e.NewsClient=Ut,e.NewsSeenTracker=Gt,e.NinePatch=IM,e.Node2D=Ej,e.ParticleEmitter=uj,e.Player=Jt,e.PlayerInput=bt,e.PlayerStats=Vt,e.PresentationQueue=Fn,e.Projectile=ij,e.RENDERING_DECISIONS=Nj,Object.defineProperty(e,"Random",{enumerable:!0,get:function(){return S}}),e.RandomStreams=_e,e.ReactionTable=en,e.RebindScreen=$P,e.Recorder=qt,e.Rectangle2D=V,e.Registry=g,Object.defineProperty(e,"Resources",{enumerable:!0,get:function(){return FA}}),e.RichLabel=uM,Object.defineProperty(e,"Roguelike",{enumerable:!0,get:function(){return oL}}),Object.defineProperty(e,"Rpg",{enumerable:!0,get:function(){return YR}}),e.RunHistory=Bt,e.SaveSyncClient=It,e.SaveSystem=Nt,e.Scene=m,e.Scene2D=bk,e.SceneComponentHost=_,e.SceneStack=h,e.ScreenEffects=dj,e.ScreenReader=RM,e.ScrollBox=HP,e.Session=tn,e.Shape2D=Dj,e.Signal=p,Object.defineProperty(e,"Simulation",{enumerable:!0,get:function(){return HV}}),e.Skins=ZP,e.Slider=jP,e.Spawner=rn,e.Spinner=PP,e.Sprite2D=kj,e.SpriteAttachment=oj,e.SpriteSheet=LA,e.StageScript=wF,e.StateRegistry=Pt,e.StatsScreen=hF,e.StatusVisuals=pj,e.StoryScreen=PF,e.StorySequence=NF,e.SyncGuard=Bn,e.TabbedList=GM,e.TelemetryClient=Ht,e.TerrainGraphicsLayer=Mj,e.Text2D=Oj,e.TextModel=IP,e.Texture2D=U,e.TileMap=nj,e.TiledSprite=Aj,e.TintedSprite=Bk,e.Toast=fF,e.Tooltip=pF,e.TreeView=BP,e.Tweener=On,e.UndoHistory=kn,e.VerticalLabel=OP,e.Viewport=UA,e.Window=BM,e.WindowStack=VM,Object.defineProperty(e,"World",{enumerable:!0,get:function(){return fR}}),e.advanceReveal=Jj,e.anchorAlign=UP,e.applyImageModifiers=rA,e.applyTextureModifiers=cA,e.autotileFrames=yj,e.bitmapLabelStyle=FM,e.blendMatrix=$k,e.blendPixels=dA,e.blobIndex=vj,e.channelScaleMatrix=Qk,e.channelSwapMatrix=eA,e.checkNoControlCharacters=Dt,e.checkSize=Et,e.colorShiftMatrix=Zk,e.completeReveal=Yj,e.contrastRatio=bF,e.createCamera=HA,e.createColorBlindnessFilter=KA,e.croppedTexture=iA,e.defaultTheme=Vj,e.deserializeReplay=Xt,e.detectWebGpu=Fj,e.escapeHtml=SM,e.floatingTextAgeAtLeast=aF,e.floatingTextAlpha=rF,e.floatingTextRise=iF,e.floatingTextStackLifePenalty=cF,e.floatingTextStackLift=lF,e.floatingTextStackMoves=uF,e.hexDistance=ln,e.hexLine=dn,e.hexNeighbors=cn,e.hexRange=fn,e.hexRotate=xj,e.hexToPixel=pn,e.highContrastTheme=Hj,e.imageModifier=Xk,e.importTwee=EF,e.inspectGraphicsCapabilities=Pj,e.layoutMarkupLines=yM,e.layoutVertical=DP,e.loadTiledMap=Bj,e.markupAccessibilityText=vM,e.markupToHtml=_M,e.maskPixels=uA,e.matchTerrainRule=Cj,e.meetsContrast=xF,e.messageBoxPresenter=_F,e.minimapCellCenter=JA,e.motionDuration=wn,e.newlyRevealed=qA,e.packColorAdd=Ik,e.packTintAdd=Lk,e.paletteRangeMapping=Gk,e.parseCSV=Vn,e.parseColorPairs=oA,e.parseImagePath=Yk,e.parseMarkdown=sM,e.parseMarkup=hM,e.parsePaletteLists=sA,e.pixelToHex=mn,e.positionMarkupLines=xM,e.prefersReducedMotion=bn,e.recolorTexture=Jk,e.rectOf=IA,e.reducedMotion=xn,e.registerColorTransform=Fk,e.relativeLuminance=yF,e.remapPixels=Kk,e.resolveAnchor=WP,e.resolveTerrainGraphics=wj,e.revealComplete=Xj,e.rotatePixels=fA,e.sanitizeInboundText=Ot,e.scramble=xt,e.screenReader=zM,e.scrollOffset=VP,e.serializeReplay=Yt,e.setReducedMotion=Sn,e.setTheme=Wj,e.sliceSpans=lM,e.sliderFraction=kP,e.sliderValueAt=AP,e.snapZoom=VA,e.spinValue=NP,e.splitScreenHalves=WA,e.squareRotate=bj,e.startReveal=qj,e.stateChecksum=zn,e.stripMarkdown=cM,e.stripMarkup=gM,e.theme=Q,e.themeChanged=$,e.tileFrame=$A,e.tileFrameIndex=tj,e.tileFrameSheet=ej,e.unscramble=St,e.validateSchema=At,e.version=f,e.watchReducedMotion=Cn,e.weightedFlood=An,e.withTextureCanvas=qk,e})({});