@datamoc/mw_games 0.5.3 → 0.5.4

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.
@@ -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.5.3`,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:()=>ee,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 ee=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(w(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=w(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 w(e,t){return(e<<t|e>>>32-t)>>>0}var T=[new ee],E=()=>T[T.length-1];function te(e){let t=new ee(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 ee)}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=l({DEFAULT_BINDINGS:()=>xe,actionsForKey:()=>we,attach:()=>tt,attachSwipe:()=>et,bind:()=>Se,bindAxis:()=>Ge,bindButton:()=>We,bindTouch:()=>Ye,detach:()=>nt,endFrame:()=>Ie,exportBindings:()=>De,gamepadAxisCode:()=>Ue,gamepadButtonCode:()=>He,importBindings:()=>Oe,isDown:()=>Ne,justPressed:()=>Pe,justReleased:()=>Fe,keysFor:()=>Ee,onAction:()=>he,onKey:()=>ge,onWheel:()=>_e,pollGamepads:()=>Ke,pressTouch:()=>Xe,releaseTouch:()=>Ze,resetBindings:()=>ke,rumble:()=>qe,touchCode:()=>Je,unbind:()=>Te,wheelActionFor:()=>ve}),de=new Map,fe=new Set,pe=new Set,me=new Set,he=new p(!0),ge=new p(!0),_e=new p(!0);function ve(e){return e.ctrlKey||e.metaKey?`zoom`:e.shiftKey?`scrollHorizontal`:`scroll`}function ye(e){let t=ve(e);t===`zoom`&&e.preventDefault();let n=t===`scrollHorizontal`&&e.deltaX!==0?e.deltaX:e.deltaY;_e.dispatch({action:t,delta:n})}var be=!1,xe={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 Se(e,t){de.set(e,new Set(t))}function Ce(e,t){let n=de.get(e)??new Set;for(let e of t)n.add(e);de.set(e,n)}function we(e){return Ae(e)}function Te(e){de.delete(e)}function Ee(e){return[...de.get(e)??[]]}function De(){let e={};for(let[t,n]of de)e[t]=[...n];return e}function Oe(e){de.clear();for(let[t,n]of Object.entries(e))Se(t,n)}function ke(){Oe(xe)}ke();function Ae(e){let t=[];for(let[n,r]of de)r.has(e)&&t.push(n);return t}function je(e){if(!fe.has(e)){fe.add(e);for(let t of Ae(e))pe.add(t),he.dispatch(t)}}function Me(e){if(fe.has(e)){fe.delete(e);for(let t of Ae(e))me.add(t)}}function Ne(e){let t=de.get(e);if(!t)return!1;for(let e of t)if(fe.has(e))return!0;return!1}function Pe(e){return pe.has(e)}function Fe(e){return me.has(e)}function Ie(){pe.clear(),me.clear()}function Le(e){if(e.repeat){ge.dispatch(e);return}je(e.code),ge.dispatch(e)}function Re(e){Me(e.code)}function ze(){fe.clear(),pe.clear(),me.clear()}var Be=.5,Ve=new Set;function He(e,t){return`Gamepad${e}Button${t}`}function Ue(e,t,n){return`Gamepad${e}Axis${t}${n>0?`+`:`-`}`}function We(e,t,n){Ce(e,n.map(e=>He(t,e)))}function Ge(e,t,n,r){Ce(e,[Ue(t,n,r)])}function Ke(e=typeof navigator?.getGamepads==`function`?navigator.getGamepads():[]){Ve.clear();for(let t of e)if(t){for(let e=0;e<t.buttons.length;e++)t.buttons[e].pressed&&Ve.add(He(t.index,e));for(let e=0;e<t.axes.length;e++){let n=t.axes[e];n>=Be?Ve.add(Ue(t.index,e,1)):n<=-.5&&Ve.add(Ue(t.index,e,-1))}}for(let e of Ve)je(e);for(let e of fe)Ve.has(e)||!e.startsWith(`Gamepad`)||Me(e)}function qe(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 Je(e){return`Touch:${e}`}function Ye(e,t=e){Ce(e,[Je(t)])}function Xe(e){je(Je(e))}function Ze(e){Me(Je(e))}var Qe={up:`up`,down:`down`,left:`left`,right:`right`,upLeft:`upLeft`,upRight:`upRight`,downLeft:`downLeft`,downRight:`downRight`},$e=[`right`,`downRight`,`down`,`downLeft`,`left`,`upLeft`,`up`,`upRight`];function et(e,t={}){let n={...Qe,...t.actions},r=t.minDistance??24;for(let e of[...$e,`tap`]){let t=n[e];t&&Ye(t,`swipe:${e}`)}let i=!1,a=-1,o=0,s=0;function c(e){Xe(`swipe:${e}`),Ze(`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=$e[(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 tt(e=window){be||(be=!0,e.addEventListener(`keydown`,Le),e.addEventListener(`keyup`,Re),window.addEventListener(`blur`,ze),e.addEventListener(`wheel`,ye,{passive:!1}))}function nt(e=window){be&&(be=!1,e.removeEventListener(`keydown`,Le),e.removeEventListener(`keyup`,Re),e.removeEventListener(`wheel`,ye),window.removeEventListener(`blur`,ze),ze())}var rt=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){Se(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`);We(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`);Ge(this.scoped(e),this.padIndex,t,n)}bindTouch(e,t=e){Ye(this.scoped(e),`${this.id}:${t}`)}pressTouch(e){Xe(`${this.id}:${e}`)}releaseTouch(e){Ze(`${this.id}:${e}`)}isDown(e){return Ne(this.scoped(e))}justPressed(e){return Pe(this.scoped(e))}justReleased(e){return Fe(this.scoped(e))}keysFor(e){return Ee(this.scoped(e))}};function it(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 ot(i)}function at(e,t){if(!t)throw Error(`scramble needs a non-empty key`);let n=st(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 ot(e){let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t)}function st(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 ct=10485760;function lt(e,t={}){let n=t.maxBytes??ct,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 ut(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 dt(e,t={}){return lt(e,t),ut(e),e}var ft=new Set([`__proto__`,`constructor`,`prototype`]);function pt(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)=>pt(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(ft.has(t))throw Error(`${n} contains a forbidden key "${t}"`);for(let[r,i]of Object.entries(t.fields))pt(e[r],i,`${n}.${r}`);return}}var mt=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 ht(){return typeof localStorage>`u`?new mt:{read:e=>localStorage.getItem(e),write:(e,t)=>localStorage.setItem(e,t),remove:e=>localStorage.removeItem(e),keys:()=>Object.keys(localStorage)}}var gt=class{constructor(e){this.namespace=e.namespace,this.version=e.version,this.migrations=e.migrations??{},this.storage=e.storage??ht()}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){lt(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?it(n,t):n}importSlot(e,t,n){lt(t);let r=n?at(t,n):t,i=JSON.parse(dt(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}},_t=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)}}},vt=class extends _t{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)}`}},yt=1,bt=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===yt}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})}},xt=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)}},St=class{constructor(e){this.store=new xt(e.storage??ht(),`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()}},Ct=class{constructor(e){this.store=new xt(e.storage??ht(),`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()}},wt=class extends _t{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}},Tt=class extends _t{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(dt(await t.text()));if(!Array.isArray(n))throw Error(`news response was not an array`);return n.map((e,t)=>Et(e,t))})}};function Et(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 Dt=class{constructor(e){this.store=new xt(e.storage??ht(),`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))}},Ot=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??ht()}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))}},kt=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)}},At=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 jt(e){return JSON.stringify(e)}function Mt(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 Nt=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 i of this.definitions.values())i.counter===e&&n<i.target&&n+t>=i.target&&(r.push(i.id),this.fresh.push(i.id));return r}unlocked(e){let t=this.definitions.get(e);if(!t)throw Error(`no such achievement: "${e}"`);return this.count(t.counter)>=t.target}progress(e){let t=this.definitions.get(e);if(!t)throw Error(`no such achievement: "${e}"`);return{count:this.count(t.counter),target:t.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}},Pt=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}},Ft=class{constructor(e={}){let t=e.storage??ht(),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))}},It=class extends _t{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}})}},Lt=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 Rt(e,t){let n=e,r=t-(e-(e&1))/2;return{x:n,y:-n-r,z:r}}function zt(e){return{x:e.x,y:e.z+(e.x-(e.x&1))/2}}var Bt=[{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 Vt(e,t){let n=Rt(e,t);return Bt.map(e=>zt({x:n.x+e.x,y:n.y+e.y,z:n.z+e.z}))}function Ht(e,t){let n=Rt(e.x,e.y),r=Rt(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 Ut(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 Wt(e,t){let n=Ht(e,t);if(n===0)return[{x:e.x,y:e.y}];let r=Rt(e.x,e.y),i=Rt(t.x,t.y),a=[];for(let e=0;e<=n;e++){let t=e/n;a.push(zt(Ut({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 Gt(e,t){let n=Rt(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(zt({x:n.x+e,y:n.y+i,z:n.z+t}))}return r}function Kt(e,t,n,r){return{x:e*n*.75+n/2,y:t*r+(e&1)*(r/2)+r/2}}function qt(e,t,n,r){let i=e-n/2,a=t-r/2,o=i/(n*.75),s=a/r-.5*o;return zt(Ut({x:o,y:-o-s,z:s}))}var Jt={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},Yt=class{constructor(){this.tweens=[]}tween(e,t,n=Jt.linear){return e>0?new Promise(r=>{this.tweens.push({elapsed:0,duration:e,apply:t,ease:n,resolve:r})}):(t(1),Promise.resolve())}update(e){if(this.tweens.length!==0)for(let t of[...this.tweens]){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=[]}},Xt=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}},Zt=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)}},Qt=class{constructor(){this.entities=new Map,this.ids=new Map,this.sequence=0}add(e){let t=this.ids.get(e);if(t!==void 0)return t;let n=`e${this.sequence++}`;return this.entities.set(n,e),this.ids.set(e,n),n}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}},$t=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()}};function en(e,t={}){let n=nn(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]=tn(c,t.columns?.[r]??`string`,r,n,a,o))}),i})}function tn(e,t,n,r,i,a){switch(t){case`string`:return e;case`number`:{let t=Number(e);if(!Number.isFinite(t))throw Error(`CSV row ${r+1}, column "${n}": "${e}" is not a number`);return t}case`boolean`:{let t=e.toLowerCase();if(t===`true`)return!0;if(t===`false`)return!1;throw Error(`CSV row ${r+1}, column "${n}": "${e}" is not "true" or "false"`)}case`list`:return e.split(i).map(e=>e.trim()).filter(e=>e.length>0);case`map`:{let t={};for(let o of e.split(i).map(e=>e.trim()).filter(e=>e.length>0)){let e=o.indexOf(a);if(e===-1)throw Error(`CSV row ${r+1}, column "${n}": "${o}" has no "${a}" to split a key from its value`);t[o.slice(0,e).trim()]=o.slice(e+a.length).trim()}return t}}}function nn(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.5.4`,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:()=>ee,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 ee=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(w(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=w(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 w(e,t){return(e<<t|e>>>32-t)>>>0}var T=[new ee],E=()=>T[T.length-1];function te(e){let t=new ee(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 ee)}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=l({DEFAULT_BINDINGS:()=>xe,actionsForKey:()=>we,attach:()=>tt,attachSwipe:()=>et,bind:()=>Se,bindAxis:()=>Ge,bindButton:()=>We,bindTouch:()=>Ye,detach:()=>nt,endFrame:()=>Ie,exportBindings:()=>De,gamepadAxisCode:()=>Ue,gamepadButtonCode:()=>He,importBindings:()=>Oe,isDown:()=>Ne,justPressed:()=>Pe,justReleased:()=>Fe,keysFor:()=>Ee,onAction:()=>he,onKey:()=>ge,onWheel:()=>_e,pollGamepads:()=>Ke,pressTouch:()=>Xe,releaseTouch:()=>Ze,resetBindings:()=>ke,rumble:()=>qe,touchCode:()=>Je,unbind:()=>Te,wheelActionFor:()=>ve}),de=new Map,fe=new Set,pe=new Set,me=new Set,he=new p(!0),ge=new p(!0),_e=new p(!0);function ve(e){return e.ctrlKey||e.metaKey?`zoom`:e.shiftKey?`scrollHorizontal`:`scroll`}function ye(e){let t=ve(e);t===`zoom`&&e.preventDefault();let n=t===`scrollHorizontal`&&e.deltaX!==0?e.deltaX:e.deltaY;_e.dispatch({action:t,delta:n})}var be=!1,xe={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 Se(e,t){de.set(e,new Set(t))}function Ce(e,t){let n=de.get(e)??new Set;for(let e of t)n.add(e);de.set(e,n)}function we(e){return Ae(e)}function Te(e){de.delete(e)}function Ee(e){return[...de.get(e)??[]]}function De(){let e={};for(let[t,n]of de)e[t]=[...n];return e}function Oe(e){de.clear();for(let[t,n]of Object.entries(e))Se(t,n)}function ke(){Oe(xe)}ke();function Ae(e){let t=[];for(let[n,r]of de)r.has(e)&&t.push(n);return t}function je(e){if(!fe.has(e)){fe.add(e);for(let t of Ae(e))pe.add(t),he.dispatch(t)}}function Me(e){if(fe.has(e)){fe.delete(e);for(let t of Ae(e))me.add(t)}}function Ne(e){let t=de.get(e);if(!t)return!1;for(let e of t)if(fe.has(e))return!0;return!1}function Pe(e){return pe.has(e)}function Fe(e){return me.has(e)}function Ie(){pe.clear(),me.clear()}function Le(e){if(e.repeat){ge.dispatch(e);return}je(e.code),ge.dispatch(e)}function Re(e){Me(e.code)}function ze(){fe.clear(),pe.clear(),me.clear()}var Be=.5,Ve=new Set;function He(e,t){return`Gamepad${e}Button${t}`}function Ue(e,t,n){return`Gamepad${e}Axis${t}${n>0?`+`:`-`}`}function We(e,t,n){Ce(e,n.map(e=>He(t,e)))}function Ge(e,t,n,r){Ce(e,[Ue(t,n,r)])}function Ke(e=typeof navigator?.getGamepads==`function`?navigator.getGamepads():[]){Ve.clear();for(let t of e)if(t){for(let e=0;e<t.buttons.length;e++)t.buttons[e].pressed&&Ve.add(He(t.index,e));for(let e=0;e<t.axes.length;e++){let n=t.axes[e];n>=Be?Ve.add(Ue(t.index,e,1)):n<=-.5&&Ve.add(Ue(t.index,e,-1))}}for(let e of Ve)je(e);for(let e of fe)Ve.has(e)||!e.startsWith(`Gamepad`)||Me(e)}function qe(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 Je(e){return`Touch:${e}`}function Ye(e,t=e){Ce(e,[Je(t)])}function Xe(e){je(Je(e))}function Ze(e){Me(Je(e))}var Qe={up:`up`,down:`down`,left:`left`,right:`right`,upLeft:`upLeft`,upRight:`upRight`,downLeft:`downLeft`,downRight:`downRight`},$e=[`right`,`downRight`,`down`,`downLeft`,`left`,`upLeft`,`up`,`upRight`];function et(e,t={}){let n={...Qe,...t.actions},r=t.minDistance??24;for(let e of[...$e,`tap`]){let t=n[e];t&&Ye(t,`swipe:${e}`)}let i=!1,a=-1,o=0,s=0;function c(e){Xe(`swipe:${e}`),Ze(`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=$e[(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 tt(e=window){be||(be=!0,e.addEventListener(`keydown`,Le),e.addEventListener(`keyup`,Re),window.addEventListener(`blur`,ze),e.addEventListener(`wheel`,ye,{passive:!1}))}function nt(e=window){be&&(be=!1,e.removeEventListener(`keydown`,Le),e.removeEventListener(`keyup`,Re),e.removeEventListener(`wheel`,ye),window.removeEventListener(`blur`,ze),ze())}var rt=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){Se(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`);We(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`);Ge(this.scoped(e),this.padIndex,t,n)}bindTouch(e,t=e){Ye(this.scoped(e),`${this.id}:${t}`)}pressTouch(e){Xe(`${this.id}:${e}`)}releaseTouch(e){Ze(`${this.id}:${e}`)}isDown(e){return Ne(this.scoped(e))}justPressed(e){return Pe(this.scoped(e))}justReleased(e){return Fe(this.scoped(e))}keysFor(e){return Ee(this.scoped(e))}};function it(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 ot(i)}function at(e,t){if(!t)throw Error(`scramble needs a non-empty key`);let n=st(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 ot(e){let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t)}function st(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 ct=10485760;function lt(e,t={}){let n=t.maxBytes??ct,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 ut(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 dt(e,t={}){return lt(e,t),ut(e),e}var ft=new Set([`__proto__`,`constructor`,`prototype`]);function pt(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)=>pt(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(ft.has(t))throw Error(`${n} contains a forbidden key "${t}"`);for(let[r,i]of Object.entries(t.fields))pt(e[r],i,`${n}.${r}`);return}}var mt=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 ht(){return typeof localStorage>`u`?new mt:{read:e=>localStorage.getItem(e),write:(e,t)=>localStorage.setItem(e,t),remove:e=>localStorage.removeItem(e),keys:()=>Object.keys(localStorage)}}var gt=class{constructor(e){this.namespace=e.namespace,this.version=e.version,this.migrations=e.migrations??{},this.storage=e.storage??ht()}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){lt(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?it(n,t):n}importSlot(e,t,n){lt(t);let r=n?at(t,n):t,i=JSON.parse(dt(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}},_t=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)}}},vt=class extends _t{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)}`}},yt=1,bt=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===yt}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})}},xt=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)}},St=class{constructor(e){this.store=new xt(e.storage??ht(),`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()}},Ct=class{constructor(e){this.store=new xt(e.storage??ht(),`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()}},wt=class extends _t{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}},Tt=class extends _t{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(dt(await t.text()));if(!Array.isArray(n))throw Error(`news response was not an array`);return n.map((e,t)=>Et(e,t))})}};function Et(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 Dt=class{constructor(e){this.store=new xt(e.storage??ht(),`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))}},Ot=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??ht()}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))}},kt=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)}},At=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 jt(e){return JSON.stringify(e)}function Mt(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 Nt=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 i of this.definitions.values())i.counter===e&&n<i.target&&n+t>=i.target&&(r.push(i.id),this.fresh.push(i.id));return r}unlocked(e){let t=this.definitions.get(e);if(!t)throw Error(`no such achievement: "${e}"`);return this.count(t.counter)>=t.target}progress(e){let t=this.definitions.get(e);if(!t)throw Error(`no such achievement: "${e}"`);return{count:this.count(t.counter),target:t.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}},Pt=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}},Ft=class{constructor(e={}){let t=e.storage??ht(),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))}},It=class extends _t{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}})}},Lt=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 Rt(e,t){let n=e,r=t-(e-(e&1))/2;return{x:n,y:-n-r,z:r}}function zt(e){return{x:e.x,y:e.z+(e.x-(e.x&1))/2}}var Bt=[{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 Vt(e,t){let n=Rt(e,t);return Bt.map(e=>zt({x:n.x+e.x,y:n.y+e.y,z:n.z+e.z}))}function Ht(e,t){let n=Rt(e.x,e.y),r=Rt(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 Ut(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 Wt(e,t){let n=Ht(e,t);if(n===0)return[{x:e.x,y:e.y}];let r=Rt(e.x,e.y),i=Rt(t.x,t.y),a=[];for(let e=0;e<=n;e++){let t=e/n;a.push(zt(Ut({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 Gt(e,t){let n=Rt(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(zt({x:n.x+e,y:n.y+i,z:n.z+t}))}return r}function Kt(e,t,n,r){return{x:e*n*.75+n/2,y:t*r+(e&1)*(r/2)+r/2}}function qt(e,t,n,r){let i=e-n/2,a=t-r/2,o=i/(n*.75),s=a/r-.5*o;return zt(Ut({x:o,y:-o-s,z:s}))}var Jt={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},Yt=class{constructor(){this.tweens=[]}tween(e,t,n=Jt.linear){return e>0?new Promise(r=>{this.tweens.push({elapsed:0,duration:e,apply:t,ease:n,resolve:r})}):(t(1),Promise.resolve())}update(e){if(this.tweens.length!==0)for(let t of[...this.tweens]){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=[]}},Xt=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}},Zt=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)}},Qt=class{constructor(){this.entities=new Map,this.ids=new Map,this.sequence=0}add(e){let t=this.ids.get(e);if(t!==void 0)return t;let n=`e${this.sequence++}`;return this.entities.set(n,e),this.ids.set(e,n),n}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}},$t=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()}};function en(e,t={}){let n=nn(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]=tn(c,t.columns?.[r]??`string`,r,n,a,o))}),i})}function tn(e,t,n,r,i,a){switch(t){case`string`:return e;case`number`:{let t=Number(e);if(!Number.isFinite(t))throw Error(`CSV row ${r+1}, column "${n}": "${e}" is not a number`);return t}case`boolean`:{let t=e.toLowerCase();if(t===`true`)return!0;if(t===`false`)return!1;throw Error(`CSV row ${r+1}, column "${n}": "${e}" is not "true" or "false"`)}case`list`:return e.split(i).map(e=>e.trim()).filter(e=>e.length>0);case`map`:{let t={};for(let o of e.split(i).map(e=>e.trim()).filter(e=>e.length>0)){let e=o.indexOf(a);if(e===-1)throw Error(`CSV row ${r+1}, column "${n}": "${o}" has no "${a}" to split a key from its value`);t[o.slice(0,e).trim()]=o.slice(e+a.length).trim()}return t}}}function nn(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,rn,an,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||{}),rn=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},an=(e,t)=>rn(e).priority??t,M={_addHandlers:{},_removeHandlers:{},_queue:{},remove(...e){return e.map(rn).forEach(e=>{e.type.forEach(t=>this._removeHandlers[t]?.(e))}),this},add(...e){return e.map(rn).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)=>an(t.value,n)-an(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)=>an(t,n)-an(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))}}})),on=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)})),sn,cn,ln=s((()=>{sn=d(on(),1),cn=sn.default})),un,dn,fn,pn,mn,hn,gn,_n,vn,yn,bn,xn,Sn,Cn,wn,Tn,En,Dn,On,kn,An,jn,Mn,Nn,Pn,Fn,In,Ln,Rn,zn=s((()=>{un={grad:.9,turn:360,rad:360/(2*Math.PI)},dn=function(e){return typeof e==`string`?e.length>0:typeof e==`number`},fn=function(e,t,n){return t===void 0&&(t=0),n===void 0&&(n=10**t),Math.round(n*e)/n+0},pn=function(e,t,n){return t===void 0&&(t=0),n===void 0&&(n=1),e>n?n:e>t?e:t},mn=function(e){return(e=isFinite(e)?e%360:0)>0?e:e+360},hn=function(e){return{r:pn(e.r,0,255),g:pn(e.g,0,255),b:pn(e.b,0,255),a:pn(e.a)}},gn=function(e){return{r:fn(e.r),g:fn(e.g),b:fn(e.b),a:fn(e.a,3)}},_n=/^#([0-9a-f]{3,8})$/i,vn=function(e){var t=e.toString(16);return t.length<2?`0`+t:t},yn=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}},bn=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}},xn=function(e){return{h:mn(e.h),s:pn(e.s,0,100),l:pn(e.l,0,100),a:pn(e.a)}},Sn=function(e){return{h:fn(e.h),s:fn(e.s),l:fn(e.l),a:fn(e.a,3)}},Cn=function(e){return bn((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},wn=function(e){return{h:(t=yn(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},Tn=/^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s*,\s*([+-]?\d*\.?\d+)%\s*,\s*([+-]?\d*\.?\d+)%\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,En=/^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s+([+-]?\d*\.?\d+)%\s+([+-]?\d*\.?\d+)%\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,Dn=/^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,On=/^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,kn={string:[[function(e){var t=_n.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?fn(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?fn(parseInt(e.substr(6,2),16)/255,2):1}:null:null},`hex`],[function(e){var t=Dn.exec(e)||On.exec(e);return t?t[2]!==t[4]||t[4]!==t[6]?null:hn({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=Tn.exec(e)||En.exec(e);if(!t)return null;var n,r;return Cn(xn({h:(n=t[1],r=t[2],r===void 0&&(r=`deg`),Number(n)*(un[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 dn(t)&&dn(n)&&dn(r)?hn({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!dn(t)||!dn(n)||!dn(r)?null:Cn(xn({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!dn(t)||!dn(n)||!dn(r)?null:bn(function(e){return{h:mn(e.h),s:pn(e.s,0,100),v:pn(e.v,0,100),a:pn(e.a)}}({h:Number(t),s:Number(n),v:Number(r),a:Number(a)}))},`hsv`]]},An=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]},jn=function(e){return typeof e==`string`?An(e.trim(),kn.string):typeof e==`object`&&e?An(e,kn.object):[null,void 0]},Mn=function(e,t){var n=wn(e);return{h:n.h,s:pn(n.s+100*t,0,100),l:n.l,a:n.a}},Nn=function(e){return(299*e.r+587*e.g+114*e.b)/1e3/255},Pn=function(e,t){var n=wn(e);return{h:n.h,s:n.s,l:pn(n.l+100*t,0,100),a:n.a}},Fn=function(){function e(e){this.parsed=jn(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 fn(Nn(this.rgba),2)},e.prototype.isDark=function(){return Nn(this.rgba)<.5},e.prototype.isLight=function(){return Nn(this.rgba)>=.5},e.prototype.toHex=function(){return e=gn(this.rgba),t=e.r,n=e.g,r=e.b,a=(i=e.a)<1?vn(fn(255*i)):``,`#`+vn(t)+vn(n)+vn(r)+a;var e,t,n,r,i,a},e.prototype.toRgb=function(){return gn(this.rgba)},e.prototype.toRgbString=function(){return e=gn(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 Sn(wn(this.rgba))},e.prototype.toHslString=function(){return e=Sn(wn(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=yn(this.rgba),{h:fn(e.h),s:fn(e.s),v:fn(e.v),a:fn(e.a,3)};var e},e.prototype.invert=function(){return In({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),In(Mn(this.rgba,e))},e.prototype.desaturate=function(e){return e===void 0&&(e=.1),In(Mn(this.rgba,-e))},e.prototype.grayscale=function(){return In(Mn(this.rgba,-1))},e.prototype.lighten=function(e){return e===void 0&&(e=.1),In(Pn(this.rgba,e))},e.prototype.darken=function(e){return e===void 0&&(e=.1),In(Pn(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`?In({r:(t=this.rgba).r,g:t.g,b:t.b,a:e}):fn(this.rgba.a,3);var t},e.prototype.hue=function(e){var t=wn(this.rgba);return typeof e==`number`?In({h:e,s:t.s,l:t.l,a:t.a}):fn(t.h)},e.prototype.isEqual=function(e){return this.toHex()===In(e).toHex()},e}(),In=function(e){return e instanceof Fn?e:new Fn(e)},Ln=[],Rn=function(e){e.forEach(function(e){Ln.indexOf(e)<0&&(e(Fn,kn),Ln.push(e))})}}));function Bn(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 Vn=s((()=>{})),Hn,P,Un=s((()=>{zn(),Vn(),Rn([Bn]),Hn=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=In(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}},Hn.shared=new Hn,Hn._temp=new Hn,Hn.HEX_PATTERN=/^(#|0x)?(([a-f0-9]{3}){1,2}([a-f0-9]{2})?)$/i,P=Hn})),Wn,Gn=s((()=>{Wn={cullArea:null,cullable:!1,cullableChildren:!0}})),Kn,qn,Jn,Yn=s((()=>{Kn=Math.PI*2,qn=180/Math.PI,Jn=Math.PI/180})),F,Xn,Zn=s((()=>{F=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 Xn.x=0,Xn.y=0,Xn}},Xn=new F})),I,Qn,$n,L=s((()=>{Yn(),Zn(),I=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 F;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 F;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(Kn-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 $n.identity()}static get shared(){return Qn.identity()}},Qn=new I,$n=new I})),er,tr=s((()=>{er=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 nr(e=`default`){return rr[e]===void 0&&(rr[e]=-1),++rr[e]}var rr,ir=s((()=>{rr={default:-1}})),ar,R,or,sr,z,cr=s((()=>{ar=new Set,R=`8.0.0`,or=`8.3.4`,sr={quiet:!1,noColor:!1},z=((e,t,n=3)=>{if(sr.quiet||ar.has(t))return;let r=Error().stack,i=`${t}
3
3
  Deprecated since v${e}`,a=typeof console.groupCollapsed==`function`&&!sr.noColor;r===void 0?console.warn(`PixiJS Deprecation Warning: `,i):(r=r.split(`
4
4
  `).splice(n).join(`
@@ -1328,12 +1328,12 @@ 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
- `}},FO=class extends Nl{constructor(e){super({glProgram:Tf({name:`color-transform-batch`,bits:[Of,NO,Pf(e),Uf]}),gpuProgram:wf({name:`color-transform-batch`,bits:[Df,PO,Mf(e),Hf]}),resources:{batchSamplers:sm(e)}}),this.maxTextures=e}},IO=7,LO=class extends du{constructor(){let e=new iu({data:new Float32Array(1),label:`mwg-color-transform-attribute-buffer`,usage:Z.VERTEX|Z.COPY_DST,shrinkToFit:!1}),t=new iu({data:new Uint32Array(1),label:`mwg-color-transform-index-buffer`,usage:Z.INDEX|Z.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})}},RO=0,zO=e=>e.colorAdd??RO;function BO(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 VO=class e extends tm{static{this.extension={type:[j.Batcher],name:`mwg-color-transform`}}constructor(t){super(t),this.geometry=new LO,this.name=e.extension.name,this.vertexSize=IO,this.shader=new FO(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=zO(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=zO(e),y=i<<16|e.roundPixels&65535;BO(t,n,r,a,o,s,c,l,u,m,g,f.x0,f.y0,_,y,v),r+=IO,BO(t,n,r,a,o,s,c,l,u,p,g,f.x1,f.y1,_,y,v),r+=IO,BO(t,n,r,a,o,s,c,l,u,p,h,f.x2,f.y2,_,y,v),r+=IO,BO(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 FO(e))}destroy(){this.shader.destroy(),super.destroy()}},HO=`mwg-tinted-sprite`,UO=class{static{this.extension={type:[j.WebGLPipes,j.WebGPUPipes,j.CanvasPipes],name:HO}}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 WO;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}},WO=class{constructor(){this.batcherName=VO.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()}},GO=!1;function KO(){GO||(GO=!0,M.add(VO),M.add(UO))}function qO(e,t,n,r=0){return(YO(r)<<24|YO(n)<<16|YO(t)<<8|YO(e))>>>0}function JO(e,t){return qO((e>>16&255)/255*t,(e>>8&255)/255*t,(e&255)/255*t)}function YO(e){return Math.max(0,Math.min(255,Math.round(e*255)))}var XO=RO;KO();var ZO=class extends ds{constructor(e){super(e),this._colorAdd=0,this.renderPipeId=HO}get colorAdd(){return this._colorAdd}set colorAdd(e){this._colorAdd!==e&&(this._colorAdd=e,this.onViewUpdate())}setColorAdd(e,t,n,r=0){this.colorAdd=qO(e,t,n,r)}lerpTint(e,t){let n=Math.round((1-t)*255);this.tint=n<<16|n<<8|n,this.colorAdd=JO(e,t)}silhouette(e){this.tint=0,this.colorAdd=JO(e,1)}resetColor(){this.tint=16777215,this.colorAdd=0}},QO=class{constructor(e,{fps:t=10,loop:n=!0}={}){if(e.length===0)throw Error(`an animation needs at least one frame`);this.frames=e,this.frameDuration=1/t,this.loop=n}get duration(){return this.frameDuration*this.frames.length}},$O=class extends ZO{constructor(...e){super(...e),this.animations=new Map,this.current=null,this.currentName=null,this.frameIndex=0,this.timer=0,this.finished=!1,this.onFinish=null,this.paused=!1}add(e,t,n){return this.animations.set(e,new QO(t,n)),this}has(e){return this.animations.has(e)}get playing(){return this.currentName}get isFinished(){return this.finished}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.frameIndex=0,this.timer=0,this.finished=!1,this.texture=n.frames[0],this}stop(){this.current=null,this.currentName=null}update(e){let t=this.current;if(!(!t||this.paused||this.finished)){for(this.timer+=e;this.timer>=t.frameDuration;)if(this.timer-=t.frameDuration,this.frameIndex<t.frames.length-1)this.frameIndex++;else if(t.loop)this.frameIndex=0;else{this.finished=!0,this.onFinish?.(this.currentName);break}this.texture=t.frames[this.frameIndex]}}},ek=``;function tk(e){ek=e.endsWith(`/`)||e===``?e:e+`/`}function nk(){return typeof window>`u`?void 0:window.__MWG_ASSETS__}function rk(){return nk()!==void 0}function ik(){return Object.keys(nk()??{})}function ak(e){let t=nk();return!t||e in t}function ok(e){let t=nk();if(!t)return ek+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 sk(e,t){let n=e.filter(e=>!GE.cache.has(e));if(n.length===0){t?.(1);return}for(let e of n)GE.add({alias:e,src:ok(e)});await GE.load(n,t)}function ck(e){if(!GE.cache.has(e))throw Error(`texture "${e}" has not been loaded - pass it to load() first`);return GE.get(e)}function lk(e){if(!GE.cache.has(e))throw Error(`asset "${e}" has not been loaded - pass it to load() first`);return GE.get(e)}function uk(e){return GE.cache.has(e)}async function dk(e){let t=e.filter(e=>GE.cache.has(e));t.length!==0&&await GE.unload(t)}var fk=new Map;async function pk(e,t,n={}){let r=n.fetch??globalThis.fetch;if(!r)throw Error(`fetch is unavailable; provide LoadBinaryOptions.fetch`);let i=e.filter(e=>!fk.has(e));if(i.length===0){t?.(1);return}let a=0;await Promise.all(i.map(async e=>{let n=await r(ok(e));if(!n.ok)throw Error(`failed to load binary asset "${e}": ${n.status}`);fk.set(e,await n.arrayBuffer()),a++,t?.(a/i.length)}))}function mk(e){let t=fk.get(e);if(!t)throw Error(`binary asset "${e}" has not been loaded - pass it to loadBinary() first`);return t}function hk(e){return fk.has(e)}function gk(e){for(let t of e)fk.delete(t)}var _k=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??sk,this.releaseAssets=e.release??dk}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 vk(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 yk=l({AssetStream:()=>_k,fetchWithByteProgress:()=>vk,get:()=>lk,getBinary:()=>mk,has:()=>ak,isBinaryLoaded:()=>hk,isCompiled:()=>rk,isLoaded:()=>uk,load:()=>sk,loadBinary:()=>pk,paths:()=>ik,release:()=>dk,releaseBinary:()=>gk,resolve:()=>ok,setBase:()=>tk,texture:()=>ck});function bk(e){return{x:e.x,y:e.y,width:e.width,height:e.height}}var xk=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(ck(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 W({source:this.texture.source,frame:new H(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:bk(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))}},Sk=class{constructor(e={}){this.world=new K,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.deadzone=e.deadzone??0,this.pixelPerfectTileSize=e.pixelPerfectTileSize,this._zoom=1,this.zoom=e.zoom??1}get zoom(){return this._zoom}set zoom(e){let t=Math.max(.01,e);this._zoom=this.pixelPerfectTileSize?wk(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);return{x:n-e/2,y:r-t/2,width:e,height:t}}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){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=1-Math.exp(-this.followIntensity*e);this.x+=r*a,this.y+=i*a}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);return{x:(e-n)*this._zoom+this.screenX+this.viewWidth/2,y:(t-r)*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);return{x:(e-this.screenX-this.viewWidth/2)/this._zoom+n,y:(t-this.screenY-this.viewHeight/2)/this._zoom+r}}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:Ck(e,i+n,o-n),y:s-a<r*2?(a+s)/2:Ck(t,a+r,s-r)}}apply(){let{x:e,y:t}=this.clampedCentre(this.x+this.shakeX,this.y+this.shakeY);this.world.scale.set(this._zoom),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)}};function Ck(e,t,n){return e<t?t:e>n?n:e}function wk(e,t){return Math.max(1,Math.round(e*t))/t}function Tk(e={}){let t=new Sk(e),n=jO.current;return t.setViewport(n.width,n.height),t}var Ek=class{constructor(e){this.container=new K,this.clip=new PC,this.camera=new Sk(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 Dk(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 Ok={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 kk(e){let t=new YE;return t.matrix=Ok[e],t}function Ak(e,t){let n=[];for(let r of e)t.has(r)||n.push(r);return n}var jk=class extends K{constructor(e){super(),this.drawn=new Set,this.marker=new PC,this.widthInCells=e.widthInCells,this.cellSize=e.cellSize??2,this.renderTexture=Gm.create({width:e.widthInCells*this.cellSize,height:e.heightInCells*this.cellSize}),this.sprite=new ds(this.renderTexture),this.addChild(this.sprite),this.addChild(this.marker)}get exploredCount(){return this.drawn.size}sync(e,t){let n=Ak(e,this.drawn);if(n.length===0)return;let r=new PC;for(let e of n){this.drawn.add(e);let n=e%this.widthInCells,i=Math.floor(e/this.widthInCells);r.rect(n*this.cellSize,i*this.cellSize,this.cellSize,this.cellSize).fill({color:t(n,i)})}jO.current.app.renderer.render({container:r,target:this.renderTexture,clear:!1}),r.destroy()}setMarker(e,t,n,r=16777215){if(this.marker.clear(),this.marker.circle(0,0,Math.max(1,this.cellSize)).fill({color:r}),n!==void 0){let e=this.cellSize*2;this.marker.moveTo(0,0).lineTo(Math.cos(n)*e,Math.sin(n)*e).stroke({color:r,width:1})}this.marker.x=(e+.5)*this.cellSize,this.marker.y=(t+.5)*this.cellSize}reset(){this.drawn.clear(),jO.current.app.renderer.render({container:new K,target:this.renderTexture,clear:!0})}destroy(e){this.renderTexture.destroy(!0),super.destroy(e)}},Mk=-1,Nk=7237230,Pk=10132122;function Fk(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 Ik(e){return e>>>20}function Lk(e){return e&(1<<20)-1}var Rk=class extends K{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 K,i=[];for(let e=0;e<this.chunkColumns*this.chunkRows;e++){let e=new K;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 Kt(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 qt(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=Ik(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(Lk(e))}buildSprite(e,t,n,r){let i=new ZO(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 PC;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(Nk),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(Pk)}}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}},zk=class extends K{constructor(...e){super(...e),this.layers=new Map}addLayer(e,t,n=0){this.removeLayer(e);let r=new ZO(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))}},Bk=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)}};function Vk(e){return typeof e==`number`?e:O(e[0],e[1])}var Hk=class extends K{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;for(let n=0;n<t;n++)if(this.pool.push({x:0,y:0,vx:0,vy:0,age:0,life:0,rotation:0,spin:0,scale:1,alpha:1,active:!1}),e.texture){let t=new ds(e.texture);t.anchor.set(.5),t.visible=!1,e.tint!==void 0&&(t.tint=e.tint),this.sprites.push(t),this.addChild(t)}}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=Vk(this.angleRange),n=Vk(this.speed);return e.x=this.x,e.y=this.y,e.vx=Math.cos(t)*n,e.vy=Math.sin(t)*n,e.age=0,e.life=Math.max(1e-6,Vk(this.life)),e.rotation=0,e.spin=Vk(this.spin),e.scale=this.scaleRange[0],e.alpha=this.alphaRange[0],e.active=!0,!0}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}}for(let t of this.pool){if(!t.active)continue;if(t.age+=e,t.age>=t.life){t.active=!1;continue}t.vx+=this.gravityX*e,t.vy+=this.gravityY*e,t.x+=t.vx*e,t.y+=t.vy*e,t.rotation+=t.spin*e;let n=t.age/t.life;t.scale=this.scaleRange[0]+(this.scaleRange[1]-this.scaleRange[0])*n,t.alpha=this.alphaRange[0]+(this.alphaRange[1]-this.alphaRange[0])*n}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))}}clear(){for(let e of this.pool)e.active=!1;this.debt=0,this.draw()}},Uk=class extends K{constructor(e={}){super(),this.overlay=new PC,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(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;this.elapsed+=e;let t=Math.min(1,this.elapsed/this.duration);if(this.phase===`flash`){let e=t<.5?Jt.easeOutQuad(t*2):1-Jt.easeInQuad((t-.5)*2);this.overlay.alpha=this.toAlpha*e}else{let e=Jt.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)}},Wk=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`)}},Gk=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)}},Kk=Yk(),qk=new Map(Kk.map((e,t)=>[Jk(e),t]));function Jk(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 Yk(){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=Jk(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 Xk(e){return qk.get(Jk(e))}function Zk(e,t,n,r){if(r.length!==Kk.length)throw Error(`autotileFrames needs exactly ${Kk.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[Xk({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}var Qk=[{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 $k(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 eA(){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 tA=class extends K{},nA=class extends PC{},rA=class extends FD{},iA=class extends ds{},aA=class extends _D{},oA=Nb,sA=536870911,cA={orthogonal:`square`,isometric:`isometric`,staggered:`staggered`};function lA(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 uA(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 dA(e,t){let n=e.orientation??`orthogonal`,r=cA[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 xk){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`);lA(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 lA(r.sheet,e,n.firstgid),r.sheet}),o=i.map(e=>e.firstgid)}let s=new Rk({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&sA;if(n===0)return-1;let r=uA(n,o,t.name);return o.length===1?n-o[0]:Fk(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 fA={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},pA={panelBorder:6,padding:10,spacing:4,direction:`ltr`,font:{family:fA.font.family,size:14,lineHeight:1.5},color:{text:16777215,textDim:13421772,textHighlight:16776960,panelFill:0,panelBorder:16777215,selection:16776960,overlay:0},overlayAlpha:.85},mA=fA;function $(){return mA}var hA=new p;function gA(e){mA={...fA,...e,font:{...fA.font,...e.font},color:{...fA.color,...e.color}},hA.dispatch(mA)}function _A(e){return typeof e==`string`?{text:e}:e}function vA(e,t){return e.align??(t.direction===`rtl`?`right`:`left`)}function yA(e,t=40){let n=Math.max(0,e);return{total:n,speed:Math.max(0,t),revealed:t===0?n:0}}function bA(e,t){return e.revealed=Math.min(e.total,Math.max(0,e.revealed+e.speed*t)),SA(e)}function xA(e){e.revealed=e.total}function SA(e){return e.revealed>=e.total}var CA=class extends FD{constructor(e={}){let t=_A(e),n=$();super({text:t.text??``,resolution:t.resolution,roundPixels:t.roundPixels,style:new mT({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:vA(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,hA.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=yA(e.length,t),this.renderRevealed()}updateReveal(e){if(!this.reveal)return!0;let t=bA(this.reveal,e);return this.renderRevealed(),t}completeReveal(){this.reveal&&(xA(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=vA(this.opts,e))}destroy(e){hA.remove(this.themeListener),super.destroy(e)}},wA=``,TA=``,EA=``;function DA(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===`*`?wA:r===`_`?TA:EA,n++}else t+=e[n];return t}function OA(e){return e.replaceAll(wA,`*`).replaceAll(TA,`_`).replaceAll(EA,`\\`)}function kA(e){return e!==void 0&&/[\p{L}\p{N}_]/u.test(e)}function AA(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===`_`&&kA(e[i-1])&&kA(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 jA(e,t,n,r,i,a){let o=AA(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 MA(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 NA(e){let t=DA(e),n=[],r=[];jA(t,`*`,!0,`bold`,n,r),jA(t,`_`,!0,`bold`,n,r),jA(t,`*`,!1,`italic`,n,r),jA(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 MA(o).map(e=>({...e,text:OA(e.text)}))}function PA(e){return NA(e).map(e=>e.text).join(``)}function FA(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 IA=class extends vO{constructor(e={}){let t=_A(e),n=$();super({text:LA(t.text??``),resolution:t.resolution,style:new tO({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:vA(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,hA.add(this.themeListener)}setText(e){this.revealSpans=null,this.reveal=null;let t=LA(e);this.text!==t&&(this.text=t)}showProgressive(e,t){this.revealSpans=NA(e),this.reveal=yA(PA(e).length,t),this.renderRevealed()}updateReveal(e){if(!this.reveal)return!0;let t=bA(this.reveal,e);return this.renderRevealed(),t}completeReveal(){this.reveal&&(xA(this.reveal),this.renderRevealed())}renderRevealed(){if(!this.reveal||!this.revealSpans)return;let e=RA(FA(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=vA(this.opts,e))}destroy(e){hA.remove(this.themeListener),super.destroy(e)}};function LA(e){return RA(NA(e))}function RA(e){return e.map(e=>{let t=zA(e.text);return e.italic&&(t=`<i>${t}</i>`),e.bold&&(t=`<b>${t}</b>`),t}).join(``)}function zA(e){return e.replaceAll(`&`,`&amp;`).replaceAll(`<`,`&lt;`).replaceAll(`>`,`&gt;`)}var BA=class extends JD{constructor(e={}){let t=_A(e),n=$();super({text:t.text??``,style:VA(t,n)}),this.themeListener=e=>this.restyle(e),this.opts=t,hA.add(this.themeListener)}setText(e){this.text!==e&&(this.text=e)}restyle(e){this.style=VA(this.opts,e)}destroy(e){hA.remove(this.themeListener),super.destroy(e)}};function VA(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:vA(e,t),wordWrap:e.wrapWidth!==void 0,wordWrapWidth:e.wrapWidth??0,breakWords:!0}}var HA=class extends K{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 DO({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)}},UA=class extends K{constructor(e){super(),this.content=new K,this.onClose=new p,this.titleLabel=null,this.innerWidth=0,this.innerHeight=0,this.currentWidth=0,this.currentHeight=0,this.themeListener=()=>this.restyle(),this.delegate=null;let t=$();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 HA(t.panel,{border:t.panelBorder}):new PC,this.addChild(this.background),e.title!==void 0&&(this.titleLabel=new CA({text:e.title,color:t.color.textHighlight,bold:!0}),this.addChild(this.titleLabel)),this.addChild(this.content),this.resize(e.width,e.height),hA.add(this.themeListener)}restyle(){this.titleLabel?.setColor($().color.textHighlight),this.resize(this.currentWidth,this.currentHeight)}resize(e,t){this.currentWidth=e,this.currentHeight=t;let n=$(),r=(this.background instanceof HA?this.background.border.left:2)+n.padding;this.background instanceof HA?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.delegate?.handleAction(e)?!0:e===`cancel`&&this.closable?(this.close(),!0):!1}update(e){}close(){this.onClose.dispatch(),this.parent?.removeChild(this),this.destroy({children:!0})}place(e,t){let n=this.getLocalBounds(),r=$().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){hA.remove(this.themeListener),super.destroy(e)}},WA=class extends K{constructor(){super(),this.windows=[],this.overlay=new PC,this.viewportWidth=0,this.viewportHeight=0,this.listener=e=>this.handleAction(e),this.themeListener=()=>this.drawOverlay(),this.overlay.visible=!1,this.addChild(this.overlay),he.add(this.listener),hA.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){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=$();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){he.remove(this.listener),hA.remove(this.themeListener),super.destroy(e)}},GA=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}},KA=class extends K{constructor(e){super(),this.selection=new GA({onChange:()=>this.refresh(),onHighlight:(e,t)=>this.onHighlight?.(e,t)}),this.rows=[],this.rowsLayer=new K,this.highlight=new PC,this.mask_=new PC,this.scroll=0,this.themeListener=()=>this.restyle();let t=$();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??[]),hA.add(this.themeListener)}restyle(){let e=$();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 CA);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){hA.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=$(),n=t.direction===`rtl`;e.forEach((e,r)=>{let i=new K;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 CA({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=$();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})}},qA=class extends K{columnX(e){return($().direction===`rtl`?this.columns-1-e:e)*this.cellSize}constructor(e){super(),this.selection=new GA({onChange:()=>this.refresh(),onHighlight:(e,t)=>this.onHighlight?.(e,t)}),this.cells=[],this.cellsLayer=new K,this.highlight=new PC,this.pickupHighlight=new PC,this.mask_=new PC,this.scrollRow=0,this.pickedUp=null,this.pressedIndex=null,this.pressTimer=0,this.themeListener=()=>{let e=$();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 CA)?.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??[]),hA.add(this.themeListener)}destroy(e){hA.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=$();e.forEach((e,n)=>{let r=Math.floor(n/this.columns),i=n%this.columns,a=new K;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 CA({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($().direction===`rtl`?1:-1,0);case`right`:return this.move($().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=$();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})}}},JA=class extends UA{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=yA(0),this.portrait=null,this.portraitLayer=new K,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;let t=$();this.content.addChild(this.portraitLayer),this.speakerLabel=new CA({color:t.color.textHighlight,bold:!0}),this.content.addChild(this.speakerLabel),this.body=new CA({wrapWidth:this.contentWidth}),this.content.addChild(this.body),this.prompt=new CA({text:`▼`,color:t.color.textDim}),this.prompt.visible=!1,this.content.addChild(this.prompt),this.showPage(0),hA.add(this.messageThemeListener)}restyleMessage(){let e=$();this.speakerLabel.setColor(e.color.textHighlight),this.prompt.setColor(e.color.textDim)}destroy(e){hA.remove(this.messageThemeListener),super.destroy(e)}showPage(e){let t=this.pages[e],n=$(),r=n.direction===`rtl`;this.portraitLayer.removeChildren(),this.portrait=null;let i=0,a=this.contentWidth;t.portrait&&(this.portrait=new ds(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),this.reveal=yA(t.text.length,this.speed),this.autoAdvanceElapsed=0,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.pages[this.pageIndex].text.slice(0,Math.floor(this.reveal.revealed)));return}let e=this.pages.slice(0,this.pageIndex).map(e=>this.formatLine(e,e.text)),t=this.pages[this.pageIndex];e.push(this.formatLine(t,t.text.slice(0,Math.floor(this.reveal.revealed)))),this.body.setText(e.join(`
1331
+ `}},FO=class extends Nl{constructor(e){super({glProgram:Tf({name:`color-transform-batch`,bits:[Of,NO,Pf(e),Uf]}),gpuProgram:wf({name:`color-transform-batch`,bits:[Df,PO,Mf(e),Hf]}),resources:{batchSamplers:sm(e)}}),this.maxTextures=e}},IO=7,LO=class extends du{constructor(){let e=new iu({data:new Float32Array(1),label:`mwg-color-transform-attribute-buffer`,usage:Z.VERTEX|Z.COPY_DST,shrinkToFit:!1}),t=new iu({data:new Uint32Array(1),label:`mwg-color-transform-index-buffer`,usage:Z.INDEX|Z.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})}},RO=0,zO=e=>e.colorAdd??RO;function BO(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 VO=class e extends tm{static{this.extension={type:[j.Batcher],name:`mwg-color-transform`}}constructor(t){super(t),this.geometry=new LO,this.name=e.extension.name,this.vertexSize=IO,this.shader=new FO(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=zO(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=zO(e),y=i<<16|e.roundPixels&65535;BO(t,n,r,a,o,s,c,l,u,m,g,f.x0,f.y0,_,y,v),r+=IO,BO(t,n,r,a,o,s,c,l,u,p,g,f.x1,f.y1,_,y,v),r+=IO,BO(t,n,r,a,o,s,c,l,u,p,h,f.x2,f.y2,_,y,v),r+=IO,BO(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 FO(e))}destroy(){this.shader.destroy(),super.destroy()}},HO=`mwg-tinted-sprite`,UO=class{static{this.extension={type:[j.WebGLPipes,j.WebGPUPipes,j.CanvasPipes],name:HO}}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 WO;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}},WO=class{constructor(){this.batcherName=VO.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()}},GO=!1;function KO(){GO||(GO=!0,M.add(VO),M.add(UO))}function qO(e,t,n,r=0){return(YO(r)<<24|YO(n)<<16|YO(t)<<8|YO(e))>>>0}function JO(e,t){return qO((e>>16&255)/255*t,(e>>8&255)/255*t,(e&255)/255*t)}function YO(e){return Math.max(0,Math.min(255,Math.round(e*255)))}var XO=RO;KO();var ZO=class extends ds{constructor(e){super(e),this._colorAdd=0,this.renderPipeId=HO}get colorAdd(){return this._colorAdd}set colorAdd(e){this._colorAdd!==e&&(this._colorAdd=e,this.onViewUpdate())}setColorAdd(e,t,n,r=0){this.colorAdd=qO(e,t,n,r)}lerpTint(e,t){let n=Math.round((1-t)*255);this.tint=n<<16|n<<8|n,this.colorAdd=JO(e,t)}silhouette(e){this.tint=0,this.colorAdd=JO(e,1)}resetColor(){this.tint=16777215,this.colorAdd=0}},QO=class{constructor(e,{fps:t=10,loop:n=!0}={}){if(e.length===0)throw Error(`an animation needs at least one frame`);this.frames=e,this.frameDuration=1/t,this.loop=n}get duration(){return this.frameDuration*this.frames.length}},$O=class extends ZO{constructor(...e){super(...e),this.animations=new Map,this.current=null,this.currentName=null,this.frameIndex=0,this.timer=0,this.finished=!1,this.onFinish=null,this.paused=!1}add(e,t,n){return this.animations.set(e,new QO(t,n)),this}has(e){return this.animations.has(e)}get playing(){return this.currentName}get isFinished(){return this.finished}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.frameIndex=0,this.timer=0,this.finished=!1,this.texture=n.frames[0],this}stop(){this.current=null,this.currentName=null}update(e){let t=this.current;if(!(!t||this.paused||this.finished)){for(this.timer+=e;this.timer>=t.frameDuration;)if(this.timer-=t.frameDuration,this.frameIndex<t.frames.length-1)this.frameIndex++;else if(t.loop)this.frameIndex=0;else{this.finished=!0,this.onFinish?.(this.currentName);break}this.texture=t.frames[this.frameIndex]}}},ek=``;function tk(e){ek=e.endsWith(`/`)||e===``?e:e+`/`}function nk(){return typeof window>`u`?void 0:window.__MWG_ASSETS__}function rk(){return nk()!==void 0}function ik(){return Object.keys(nk()??{})}function ak(e){let t=nk();return!t||e in t}function ok(e){let t=nk();if(!t)return ek+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 sk(e,t){let n=e.filter(e=>!GE.cache.has(e));if(n.length===0){t?.(1);return}for(let e of n)GE.add({alias:e,src:ok(e)});await GE.load(n,t)}function ck(e){if(!GE.cache.has(e))throw Error(`texture "${e}" has not been loaded - pass it to load() first`);return GE.get(e)}function lk(e){if(!GE.cache.has(e))throw Error(`asset "${e}" has not been loaded - pass it to load() first`);return GE.get(e)}function uk(e){return GE.cache.has(e)}async function dk(e){let t=e.filter(e=>GE.cache.has(e));t.length!==0&&await GE.unload(t)}var fk=new Map;async function pk(e,t,n={}){let r=n.fetch??globalThis.fetch;if(!r)throw Error(`fetch is unavailable; provide LoadBinaryOptions.fetch`);let i=e.filter(e=>!fk.has(e));if(i.length===0){t?.(1);return}let a=0;await Promise.all(i.map(async e=>{let n=await r(ok(e));if(!n.ok)throw Error(`failed to load binary asset "${e}": ${n.status}`);fk.set(e,await n.arrayBuffer()),a++,t?.(a/i.length)}))}function mk(e){let t=fk.get(e);if(!t)throw Error(`binary asset "${e}" has not been loaded - pass it to loadBinary() first`);return t}function hk(e){return fk.has(e)}function gk(e){for(let t of e)fk.delete(t)}var _k=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??sk,this.releaseAssets=e.release??dk}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 vk(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 yk=l({AssetStream:()=>_k,fetchWithByteProgress:()=>vk,get:()=>lk,getBinary:()=>mk,has:()=>ak,isBinaryLoaded:()=>hk,isCompiled:()=>rk,isLoaded:()=>uk,load:()=>sk,loadBinary:()=>pk,paths:()=>ik,release:()=>dk,releaseBinary:()=>gk,resolve:()=>ok,setBase:()=>tk,texture:()=>ck});function bk(e){return{x:e.x,y:e.y,width:e.width,height:e.height}}var xk=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(ck(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 W({source:this.texture.source,frame:new H(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:bk(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))}},Sk=class{constructor(e={}){this.world=new K,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.deadzone=e.deadzone??0,this.pixelPerfectTileSize=e.pixelPerfectTileSize,this._zoom=1,this.zoom=e.zoom??1}get zoom(){return this._zoom}set zoom(e){let t=Math.max(.01,e);this._zoom=this.pixelPerfectTileSize?wk(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);return{x:n-e/2,y:r-t/2,width:e,height:t}}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){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=1-Math.exp(-this.followIntensity*e);this.x+=r*a,this.y+=i*a}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);return{x:(e-n)*this._zoom+this.screenX+this.viewWidth/2,y:(t-r)*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);return{x:(e-this.screenX-this.viewWidth/2)/this._zoom+n,y:(t-this.screenY-this.viewHeight/2)/this._zoom+r}}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:Ck(e,i+n,o-n),y:s-a<r*2?(a+s)/2:Ck(t,a+r,s-r)}}apply(){let{x:e,y:t}=this.clampedCentre(this.x+this.shakeX,this.y+this.shakeY);this.world.scale.set(this._zoom),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)}};function Ck(e,t,n){return e<t?t:e>n?n:e}function wk(e,t){return Math.max(1,Math.round(e*t))/t}function Tk(e={}){let t=new Sk(e),n=jO.current;return t.setViewport(n.width,n.height),t}var Ek=class{constructor(e){this.container=new K,this.clip=new PC,this.camera=new Sk(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 Dk(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 Ok={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 kk(e){let t=new YE;return t.matrix=Ok[e],t}function Ak(e,t){let n=[];for(let r of e)t.has(r)||n.push(r);return n}var jk=class extends K{constructor(e){super(),this.drawn=new Set,this.marker=new PC,this.widthInCells=e.widthInCells,this.cellSize=e.cellSize??2,this.renderTexture=Gm.create({width:e.widthInCells*this.cellSize,height:e.heightInCells*this.cellSize}),this.sprite=new ds(this.renderTexture),this.addChild(this.sprite),this.addChild(this.marker)}get exploredCount(){return this.drawn.size}sync(e,t){let n=Ak(e,this.drawn);if(n.length===0)return;let r=new PC;for(let e of n){this.drawn.add(e);let n=e%this.widthInCells,i=Math.floor(e/this.widthInCells);r.rect(n*this.cellSize,i*this.cellSize,this.cellSize,this.cellSize).fill({color:t(n,i)})}jO.current.app.renderer.render({container:r,target:this.renderTexture,clear:!1}),r.destroy()}setMarker(e,t,n,r=16777215){if(this.marker.clear(),this.marker.circle(0,0,Math.max(1,this.cellSize)).fill({color:r}),n!==void 0){let e=this.cellSize*2;this.marker.moveTo(0,0).lineTo(Math.cos(n)*e,Math.sin(n)*e).stroke({color:r,width:1})}this.marker.x=(e+.5)*this.cellSize,this.marker.y=(t+.5)*this.cellSize}reset(){this.drawn.clear(),jO.current.app.renderer.render({container:new K,target:this.renderTexture,clear:!0})}destroy(e){this.renderTexture.destroy(!0),super.destroy(e)}},Mk=-1,Nk=7237230,Pk=10132122;function Fk(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 Ik(e){return e>>>20}function Lk(e){return e&(1<<20)-1}var Rk=class extends K{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 K,i=[];for(let e=0;e<this.chunkColumns*this.chunkRows;e++){let e=new K;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 Kt(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 qt(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=Ik(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(Lk(e))}buildSprite(e,t,n,r){let i=new ZO(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 PC;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(Nk),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(Pk)}}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}},zk=class extends K{constructor(...e){super(...e),this.layers=new Map}addLayer(e,t,n=0){this.removeLayer(e);let r=new ZO(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))}},Bk=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)}};function Vk(e){return typeof e==`number`?e:O(e[0],e[1])}var Hk=class extends K{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;for(let n=0;n<t;n++)if(this.pool.push({x:0,y:0,vx:0,vy:0,age:0,life:0,rotation:0,spin:0,scale:1,alpha:1,active:!1}),e.texture){let t=new ds(e.texture);t.anchor.set(.5),t.visible=!1,e.tint!==void 0&&(t.tint=e.tint),this.sprites.push(t),this.addChild(t)}}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=Vk(this.angleRange),n=Vk(this.speed);return e.x=this.x,e.y=this.y,e.vx=Math.cos(t)*n,e.vy=Math.sin(t)*n,e.age=0,e.life=Math.max(1e-6,Vk(this.life)),e.rotation=0,e.spin=Vk(this.spin),e.scale=this.scaleRange[0],e.alpha=this.alphaRange[0],e.active=!0,!0}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}}for(let t of this.pool){if(!t.active)continue;if(t.age+=e,t.age>=t.life){t.active=!1;continue}t.vx+=this.gravityX*e,t.vy+=this.gravityY*e,t.x+=t.vx*e,t.y+=t.vy*e,t.rotation+=t.spin*e;let n=t.age/t.life;t.scale=this.scaleRange[0]+(this.scaleRange[1]-this.scaleRange[0])*n,t.alpha=this.alphaRange[0]+(this.alphaRange[1]-this.alphaRange[0])*n}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))}}clear(){for(let e of this.pool)e.active=!1;this.debt=0,this.draw()}},Uk=class extends K{constructor(e={}){super(),this.overlay=new PC,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(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;this.elapsed+=e;let t=Math.min(1,this.elapsed/this.duration);if(this.phase===`flash`){let e=t<.5?Jt.easeOutQuad(t*2):1-Jt.easeInQuad((t-.5)*2);this.overlay.alpha=this.toAlpha*e}else{let e=Jt.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)}},Wk=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`)}},Gk=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)}},Kk=Yk(),qk=new Map(Kk.map((e,t)=>[Jk(e),t]));function Jk(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 Yk(){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=Jk(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 Xk(e){return qk.get(Jk(e))}function Zk(e,t,n,r){if(r.length!==Kk.length)throw Error(`autotileFrames needs exactly ${Kk.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[Xk({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}var Qk=[{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 $k(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 eA(){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 tA=class extends K{},nA=class extends PC{},rA=class extends FD{},iA=class extends ds{},aA=class extends _D{},oA=Nb,sA=536870911,cA={orthogonal:`square`,isometric:`isometric`,staggered:`staggered`};function lA(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 uA(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 dA(e,t){let n=e.orientation??`orthogonal`,r=cA[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 xk){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`);lA(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 lA(r.sheet,e,n.firstgid),r.sheet}),o=i.map(e=>e.firstgid)}let s=new Rk({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&sA;if(n===0)return-1;let r=uA(n,o,t.name);return o.length===1?n-o[0]:Fk(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 fA={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},pA={panelBorder:6,padding:10,spacing:4,direction:`ltr`,font:{family:fA.font.family,size:14,lineHeight:1.5},color:{text:16777215,textDim:13421772,textHighlight:16776960,panelFill:0,panelBorder:16777215,selection:16776960,overlay:0},overlayAlpha:.85},mA=fA;function $(){return mA}var hA=new p;function gA(e){mA={...fA,...e,font:{...fA.font,...e.font},color:{...fA.color,...e.color}},hA.dispatch(mA)}function _A(e){return typeof e==`string`?{text:e}:e}function vA(e,t){return e.align??(t.direction===`rtl`?`right`:`left`)}function yA(e,t=40){let n=Math.max(0,e);return{total:n,speed:Math.max(0,t),revealed:t===0?n:0}}function bA(e,t){return e.revealed=Math.min(e.total,Math.max(0,e.revealed+e.speed*t)),SA(e)}function xA(e){e.revealed=e.total}function SA(e){return e.revealed>=e.total}var CA=class extends FD{constructor(e={}){let t=_A(e),n=$();super({text:t.text??``,resolution:t.resolution,roundPixels:t.roundPixels,style:new mT({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:vA(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,hA.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=yA(e.length,t),this.renderRevealed()}updateReveal(e){if(!this.reveal)return!0;let t=bA(this.reveal,e);return this.renderRevealed(),t}completeReveal(){this.reveal&&(xA(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=vA(this.opts,e))}destroy(e){hA.remove(this.themeListener),super.destroy(e)}},wA=``,TA=``,EA=``;function DA(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===`*`?wA:r===`_`?TA:EA,n++}else t+=e[n];return t}function OA(e){return e.replaceAll(wA,`*`).replaceAll(TA,`_`).replaceAll(EA,`\\`)}function kA(e){return e!==void 0&&/[\p{L}\p{N}_]/u.test(e)}function AA(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===`_`&&kA(e[i-1])&&kA(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 jA(e,t,n,r,i,a){let o=AA(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 MA(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 NA(e){let t=DA(e),n=[],r=[];jA(t,`*`,!0,`bold`,n,r),jA(t,`_`,!0,`bold`,n,r),jA(t,`*`,!1,`italic`,n,r),jA(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 MA(o).map(e=>({...e,text:OA(e.text)}))}function PA(e){return NA(e).map(e=>e.text).join(``)}function FA(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 IA=class extends vO{constructor(e={}){let t=_A(e),n=$();super({text:LA(t.text??``),resolution:t.resolution,style:new tO({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:vA(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,hA.add(this.themeListener)}setText(e){this.revealSpans=null,this.reveal=null;let t=LA(e);this.text!==t&&(this.text=t)}showProgressive(e,t){this.revealSpans=NA(e),this.reveal=yA(PA(e).length,t),this.renderRevealed()}updateReveal(e){if(!this.reveal)return!0;let t=bA(this.reveal,e);return this.renderRevealed(),t}completeReveal(){this.reveal&&(xA(this.reveal),this.renderRevealed())}renderRevealed(){if(!this.reveal||!this.revealSpans)return;let e=RA(FA(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=vA(this.opts,e))}destroy(e){hA.remove(this.themeListener),super.destroy(e)}};function LA(e){return RA(NA(e))}function RA(e){return e.map(e=>{let t=zA(e.text);return e.italic&&(t=`<i>${t}</i>`),e.bold&&(t=`<b>${t}</b>`),t}).join(``)}function zA(e){return e.replaceAll(`&`,`&amp;`).replaceAll(`<`,`&lt;`).replaceAll(`>`,`&gt;`)}var BA=class extends JD{constructor(e={}){let t=_A(e),n=$();super({text:t.text??``,style:VA(t,n)}),this.themeListener=e=>this.restyle(e),this.opts=t,hA.add(this.themeListener)}setText(e){this.text!==e&&(this.text=e)}restyle(e){this.style=VA(this.opts,e)}destroy(e){hA.remove(this.themeListener),super.destroy(e)}};function VA(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:vA(e,t),wordWrap:e.wrapWidth!==void 0,wordWrapWidth:e.wrapWidth??0,breakWords:!0}}var HA=class extends K{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 DO({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)}},UA=class extends K{constructor(e){super(),this.content=new K,this.onClose=new p,this.titleLabel=null,this.innerWidth=0,this.innerHeight=0,this.currentWidth=0,this.currentHeight=0,this.themeListener=()=>this.restyle(),this.delegate=null;let t=$();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 HA(t.panel,{border:t.panelBorder}):new PC,this.addChild(this.background),e.title!==void 0&&(this.titleLabel=new CA({text:e.title,color:t.color.textHighlight,bold:!0}),this.addChild(this.titleLabel)),this.addChild(this.content),this.resize(e.width,e.height),hA.add(this.themeListener)}restyle(){this.titleLabel?.setColor($().color.textHighlight),this.resize(this.currentWidth,this.currentHeight)}resize(e,t){this.currentWidth=e,this.currentHeight=t;let n=$(),r=(this.background instanceof HA?this.background.border.left:2)+n.padding;this.background instanceof HA?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.delegate?.handleAction(e)?!0:e===`cancel`&&this.closable?(this.close(),!0):!1}update(e){}close(){this.onClose.dispatch(),this.parent?.removeChild(this),this.destroy({children:!0})}place(e,t){let n=this.getLocalBounds(),r=$().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){hA.remove(this.themeListener),super.destroy(e)}},WA=class extends K{constructor(){super(),this.windows=[],this.overlay=new PC,this.viewportWidth=0,this.viewportHeight=0,this.listener=e=>this.handleAction(e),this.themeListener=()=>this.drawOverlay(),this.overlay.visible=!1,this.addChild(this.overlay),he.add(this.listener),hA.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){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=$();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){he.remove(this.listener),hA.remove(this.themeListener),super.destroy(e)}},GA=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}},KA=class extends K{constructor(e){super(),this.selection=new GA({onChange:()=>this.refresh(),onHighlight:(e,t)=>this.onHighlight?.(e,t)}),this.rows=[],this.rowsLayer=new K,this.highlight=new PC,this.mask_=new PC,this.scroll=0,this.themeListener=()=>this.restyle();let t=$();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??[]),hA.add(this.themeListener)}restyle(){let e=$();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 CA);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){hA.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=$(),n=t.direction===`rtl`;e.forEach((e,r)=>{let i=new K;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 CA({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=$();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})}},qA=class extends K{columnX(e){return($().direction===`rtl`?this.columns-1-e:e)*this.cellSize}constructor(e){super(),this.selection=new GA({onChange:()=>this.refresh(),onHighlight:(e,t)=>this.onHighlight?.(e,t)}),this.cells=[],this.cellsLayer=new K,this.highlight=new PC,this.pickupHighlight=new PC,this.mask_=new PC,this.scrollRow=0,this.pickedUp=null,this.pressedIndex=null,this.pressTimer=0,this.themeListener=()=>{let e=$();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 CA)?.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??[]),hA.add(this.themeListener)}destroy(e){hA.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=$();e.forEach((e,n)=>{let r=Math.floor(n/this.columns),i=n%this.columns,a=new K;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 CA({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($().direction===`rtl`?1:-1,0);case`right`:return this.move($().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=$();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})}}};function JA(e,t,n={}){let r={},i=t.replace(/\r/g,``).split(`
1332
+ `),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]=XA(e,t,s)}else r[a]=YA(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 YA(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 XA(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 YA((o??n.find(e=>e.key===s)??i).value)}}}var ZA=/\{sound:([^{}\r\n]+)\}/g;function QA(e){let t=[],n=``,r=0,i;for(ZA.lastIndex=0;(i=ZA.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 $A(e){return QA(e).text}function ej(){return{format(e,t){let n=e.params;if(t===`audio`){let t=`${e.type}.audio`;return hM(t)?rM(t,n):``}let r=`${e.type}.${t}`;return hM(r)?iM(r,n):iM(e.type,n)}}}function tj(e,t){return new Intl.NumberFormat(tM(),t).format(e)}function nj(e,t){return new Intl.DateTimeFormat(tM(),t).format(e)}function rj(e,t){return new Intl.ListFormat(tM(),t).format(e)}var ij=/\{(?!sound:)(\w+)(=)?(?:!([sra]))?(?::([^{}]*))?\}/g;function aj(e){let t=[];ij.lastIndex=0;let n=0,r;for(;(r=ij.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 oj(e){return`${e.debug?`=`:``}${e.conv?`!${e.conv}`:``}${e.spec===void 0?``:`:${e.spec}`}`}function sj(e,t){let n=new Map,r=new Map;for(let t of aj(e))typeof t!=`string`&&n.set(t.token,oj(t));for(let e of aj(t))typeof e!=`string`&&r.set(e.token,oj(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 cj=/^(?:(.)?([<>=^]))?([+\- ])?(z)?(#)?(0)?(\d+)?([,_])?(?:\.(\d+))?([bcdeEfFgGnosxX%])?$/,lj={b:2,o:8,x:16,X:16},uj={b:`0b`,o:`0o`,x:`0x`,X:`0X`},dj=new Set([`f`,`F`,`e`,`E`,`g`,`G`,`%`,`n`]);function fj(e){return Number.isNaN(e)?`nan`:e===1/0?`inf`:e===-1/0?`-inf`:Object.is(e,-0)?`-0.0`:String(e)}function pj(e,t,n=3,r=`\\d`){return e.replace(RegExp(`\\B(?=(${r}{${n}})+(?!${r}))`,`g`),t)}function mj(e,t){let n=/^(\d+)/.exec(e);return n?pj(n[1],t)+e.slice(n[1].length):e}function hj(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 gj(e){return e.replace(/([eE][+-])(\d)$/,`$10$2`)}function _j(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=gj(e.toExponential(a-1)),r||(s=s.replace(/(\.\d*?)0+(e|$)/,`$1$2`).replace(/\.e/i,`e`))),n?s.toUpperCase():s}function vj(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 yj(e,t,n,r,i,a){return hj(a===void 0?e:e.slice(0,a),i,t??(r?`0`:` `),n??`<`)}function bj(e,t,n=`en`){if(t===``)return typeof e==`number`?fj(e):e;let r=cj.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:yj(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:hj(String.fromCodePoint(t),h,i??` `,a??`>`)}if(!Number.isFinite(e)){if(p!==void 0&&!dj.has(p))return;let t=Number.isNaN(e)?`nan`:`inf`;return(p===`F`||p===`E`||p===`G`)&&(t=t.toUpperCase()),p===`%`&&(t+=`%`),hj((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=_j(_,m,!1,!!c,m-1)}else y=fj(_);v&&(y=mj(y,v))}else if(p===`d`){if(m!==void 0||!Number.isInteger(_))return;y=String(Math.trunc(_)),v&&(y=pj(y,v))}else if(p in lj){if(m!==void 0||!Number.isInteger(_)||d===`,`)return;y=Math.trunc(_).toString(lj[p]),p===`X`&&(y=y.toUpperCase()),v&&(y=pj(y,v,4,`[0-9a-fA-F]`)),c&&(y=uj[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}=vj(n),r=_j(_,m??6,!1,!!c),i=r.split(`e`)[0],a=r.slice(i.length);y=mj(i,e).replace(`.`,t)+a}}else if(p===`f`||p===`F`)y=_.toFixed(m??6),v&&(y=mj(y,v));else if(p===`e`||p===`E`)y=gj(_.toExponential(m??6)),p===`E`&&(y=y.toUpperCase()),v&&(y=mj(y,v));else if(p===`g`||p===`G`)y=_j(_,m??6,p===`G`,!!c),v&&(y=mj(y,v));else{let e=_*100;y=(Number.isFinite(e)?e.toFixed(m??6):`inf`)+`%`,v&&Number.isFinite(e)&&(y=mj(y,v))}let b=g?`-`:o===`+`?`+`:o===` `?` `:``,x=i??(l&&!a?`0`:` `),S=a??(l&&!a?`=`:`>`);return S===`=`?b+hj(y,h-b.length,x,`>`):hj(b+y,h,x,S)}function xj(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 Sj(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}Cj(r)&&r.other===void 0&&t.push({key:n,kind:`plural-missing-other`,detail:`plural forms have no "other" branch`})}return t}function Cj(e){return typeof e==`object`&&!!e&&!(`format`in e)}function wj(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 Tj(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 Ej(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 Dj(e,t=.8){let n=Object.entries(e.messages).map(([e,t])=>[e,Tj(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=Ej(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 Oj(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 kj(e,t){let n=Object.keys(e.messages);if(n.length===0)return 1;let{missing:r}=xj(e,t);return(n.length-r.length)/n.length}function Aj(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 jj(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 Mj(e,t){return{base:e,target:t}}var Nj=`.audio`;function Pj(e){return e.endsWith(Nj)}function Fj(e){return[...new Set([...Object.keys(e.base.messages),...Object.keys(e.target.messages)])].filter(e=>!Pj(e)).sort()}function Ij(e){if(e===void 0)return;let t=Tj(e);return t===``?void 0:t}var Lj=[`log`,`compact`,`accessibility`,`debug`];function Rj(e){let t=e.lastIndexOf(`.`);if(!(t<=0||!Lj.includes(e.slice(t+1))))return`${e.slice(0,t)}${Nj}`}function zj(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}${Nj}`],o=Rj(t);o&&a.push(o);let s,c,l=!1;for(let t of a){let n=Ij(e.target.messages[t]);if(n!==void 0){s=n,c=t;break}let r=Ij(e.base.messages[t]);if(r!==void 0){s=r,c=t,l=!0;break}}return{key:t,baseText:n===void 0?``:Tj(n),targetText:r===void 0?``:Tj(r),status:i,sound:s,soundKey:c,soundInherited:l}}function Bj(e,t){let n=`${t}${Nj}`;return n in e.target.messages||n in e.base.messages?n:Rj(t)??n}function Vj(e,t={}){let n=t.query?.toLowerCase()??``;return Fj(e).map(t=>zj(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 Hj(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 Uj(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 Wj(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 Gj(e,t,n){let r={...e.target.messages},i=Bj(e,t);return n===``?delete r[i]:r[i]=n,{...e,target:{...e.target,messages:r}}}function Kj(e){let t=e=>({...e,messages:Object.fromEntries(Object.entries(e.messages).filter(([e])=>!Pj(e)))});return kj(t(e.base),t(e.target))}function qj(e){return{base:e.target,target:e.base}}var Jj=l({AUDIO_SUFFIX:()=>Nj,catalogCompleteness:()=>kj,catalogUsage:()=>Oj,copyFromBase:()=>Uj,createCatalogFormatter:()=>ej,createEditSession:()=>Mj,cueKeyFor:()=>Bj,deleteTargetKey:()=>Wj,diffCatalogKeys:()=>xj,diffPlaceholders:()=>sj,direction:()=>nM,findSimilarMessages:()=>Dj,formatDate:()=>nj,formatList:()=>rj,formatNumber:()=>tj,formatSpec:()=>bj,has:()=>hM,isAudioKey:()=>Pj,levenshteinDistance:()=>Ej,locale:()=>tM,mergeCatalogKeys:()=>jj,messageText:()=>Tj,nonBreakingUnit:()=>dM,parseFTL:()=>JA,parseSoundMarkers:()=>QA,pluralFormCoverage:()=>Aj,reset:()=>SM,sessionCompleteness:()=>Kj,sessionKeys:()=>Fj,sessionRow:()=>zj,sessionRows:()=>Vj,setActive:()=>eM,setBase:()=>$j,setTargetSound:()=>Gj,setTargetText:()=>Hj,stripSoundMarkers:()=>$A,swapSession:()=>qj,t:()=>iM,tRaw:()=>rM,tokenizeMessage:()=>aj,typographic:()=>uM,validateCatalog:()=>Sj,validateMessageAudio:()=>wj}),Yj=null,Xj=null,Zj=null,Qj=null;function $j(e){Yj=e}function eM(e){Xj=e,Zj=e?new Intl.PluralRules(e.locale):null}function tM(){return(Xj??Yj)?.locale??`en`}function nM(){return(Xj??Yj)?.direction??`ltr`}function rM(e,t){let n=Xj?.messages[e]??Yj?.messages[e];if(n===void 0)return e;let r=typeof n==`string`?n:_M(n)?n.format(t):gM(n,t?.count);return t?vM(r,t):r}function iM(e,t){if(!hM(e))return e;let n=rM(e,t),r=(Xj??Yj)?.typography===!1?n:uM(n,tM());return nM()===`rtl`?`⁧${r}⁩`:r}var aM=` `,oM=`\xA0`,sM=[`Chapitre`,`Tome`,`Livre`,`Partie`,`Section`,`Article`,`Acte`,`Scène`,`Niveau`,`Manche`,`Round`,`Étape`,`Volume`,`Figure`,`Page`,`Numéro`],cM=[`Nr`,`Dr`,`Bd`,`Kap`,`Art`,`Abb`,`Str`,`Tel`],lM=[`kg`,`g`,`mg`,`t`,`km`,`m`,`cm`,`mm`,`l`,`ml`,`h`,`min`,`s`,`%`,`°C`,`€`];function uM(e,t=tM()){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=fM(r)),n===`de`&&(r=pM(r)),r}function dM(e,t,n=tM()){let r=n.split(`-`)[0].toLowerCase();return`${e}${r===`fr`?aM:r===`de`?oM:` `}${t}`}function fM(e){let t=e.replace(/\s?([;!?])/g,`${aM}$1`).replace(/«\s?/g,`«${aM}`).replace(/\s?»/g,`${aM}»`);t=t.replace(/(?<!\{soun)(\p{L})\s?:/gu,`$1${aM}:`);let n=RegExp(`\\b(${sM.join(`|`)})\\s+(?=\\d)`,`g`);return t.replace(n,`$1${oM}`)}function pM(e){let t=RegExp(`(\\d)\\s+(?=(?:${lM.map(mM).join(`|`)})(?![\\p{L}\\p{N}]))`,`gu`),n=RegExp(`\\b(${cM.join(`|`)})\\.\\s+`,`g`);return e.replace(t,`$1${oM}`).replace(n,`$1.${oM}`)}function mM(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function hM(e){return Xj?.messages[e]!==void 0||Yj?.messages[e]!==void 0}function gM(e,t){return t===void 0?e.other??Object.values(e)[0]??``:e[(Zj??(Qj??=new Intl.PluralRules(`en`))).select(t)]??e.other??``}function _M(e){return`format`in e}function vM(e,t){return aj(e).map(e=>typeof e==`string`?e:yM(e,t)).join(``)}function yM(e,t){let n=t[e.token];if(n===void 0)return e.raw;try{let t=e.conv===void 0?n:bM(n,e.conv),r=e.spec===void 0?String(t):bj(t,e.spec,tM());return r===void 0?e.raw:e.debug?`${e.token}=${r}`:r}catch{return e.raw}}function bM(e,t){if(t===`s`)return String(e);if(typeof e==`number`){let n=bj(e,``,`en`)??String(e);return t===`a`?xM(n):n}let n=`'${e.replace(/\\/g,`\\\\`).replace(/'/g,`\\'`).replace(/\n/g,`\\n`).replace(/\r/g,`\\r`).replace(/\t/g,`\\t`)}'`;return t===`a`?xM(n):n}function xM(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 SM(){Yj=null,Xj=null,Zj=null}var CM=class extends UA{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=yA(0),this.pageText=``,this.pageCues=[],this.nextCue=0,this.portrait=null,this.portraitLayer=new K,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;let t=$();this.content.addChild(this.portraitLayer),this.speakerLabel=new CA({color:t.color.textHighlight,bold:!0}),this.content.addChild(this.speakerLabel),this.body=new CA({wrapWidth:this.contentWidth}),this.content.addChild(this.body),this.prompt=new CA({text:`▼`,color:t.color.textDim}),this.prompt.visible=!1,this.content.addChild(this.prompt),this.showPage(0),hA.add(this.messageThemeListener)}restyleMessage(){let e=$();this.speakerLabel.setColor(e.color.textHighlight),this.prompt.setColor(e.color.textDim)}destroy(e){hA.remove(this.messageThemeListener),super.destroy(e)}showPage(e){let t=this.pages[e],n=$(),r=n.direction===`rtl`;this.portraitLayer.removeChildren(),this.portrait=null;let i=0,a=this.contentWidth;t.portrait&&(this.portrait=new ds(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=QA(t.text);this.pageText=o.text,this.pageCues=o.cues,this.nextCue=0,this.reveal=yA(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,QA(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(`
1332
1333
 
1333
- `))}formatLine(e,t){return e.speaker===void 0?t:`${e.speaker}: ${t}`}get pageComplete(){return SA(this.reveal)}update(e){if(!this.finished){if(!this.pageComplete){bA(this.reveal,e),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):(xA(this.reveal),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=$(),t=this.choices.map(e=>({text:e.text,disabled:e.disabled,value:e.value??e.text})),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 KA({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())}},YA=/[A-Za-z0-9]/;function XA(e,t){let{lineHeight:n,columnHeight:r}=t,i=t.rotate??YA,a=[],o=0,s=0;for(let t of e){if(t===`
1334
- `){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 ZA=class extends K{constructor(e){super(),this.themeListener=e=>this.build(e),this.opts=e,this.build($()),hA.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=XA(this.opts.text,{lineHeight:n,columnHeight:this.opts.columnHeight,rotate:this.opts.rotate});for(let n of r){let r=new FD({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){hA.remove(this.themeListener),super.destroy(e)}},QA=class extends K{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 KA({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=Ee(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&&ge.add(this.onKeyCaptured)})}cancelCapture(){ge.remove(this.onKeyCaptured),this.capturing=null,this.refresh()}finishCapture(e,t){ge.remove(this.onKeyCaptured),this.capturing=null;let n=we(t).filter(t=>t!==e);if(n.length>0&&!this.onConflict(t,e,n)){this.refresh();return}for(let e of n)Se(e,Ee(e).filter(e=>e!==t));Se(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){ge.remove(this.onKeyCaptured),super.destroy(e)}},$A=class e extends K{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=$();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 CA({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`),hA.add(this.themeListener)}static createBackground(e,t){return e?new HA(e.texture,{border:e.border}):t.panel?new HA(t.panel,{border:t.panelBorder}):new PC}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 CA({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=$().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=$().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=$(),t=this.state===`pressed`?10066329:this.state===`hover`?14540253:this.state===`disabled`?7829367:16777215;if(this.background instanceof HA)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){hA.remove(this.themeListener),super.destroy(e)}},ej=class extends K{constructor(e){super(),this.track=new PC,this.fill=new PC,this.themeListener=()=>this.draw(),this.width_=e.width,this.height_=e.height,this.explicitColor=e.color!==void 0,this.color=e.color??$().color.textHighlight,this.fraction=tj((e.value??1)/(e.max??1)),this.fillTexture=e.fillTexture,this.backgroundTexture=e.backgroundTexture,this.roundUpToPixel=e.roundUpToPixel??!1,this.addChild(this.track),this.addChild(this.fill),this.draw(),hA.add(this.themeListener)}get value(){return this.fraction}setValue(e,t=1){this.fraction=tj(t>0?e/t:0),this.draw()}resize(e,t){this.width_=e,this.height_=t,this.draw()}draw(){let e=$();if(this.explicitColor||(this.color=e.color.textHighlight),this.track.clear().rect(0,0,this.width_,this.height_),this.track.fill(this.backgroundTexture?{texture:this.backgroundTexture}:{color:e.color.panelFill}),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.color}:{texture:this.fillTexture}:{color:this.color})}}destroy(e){hA.remove(this.themeListener),super.destroy(e)}};function tj(e){return Math.max(0,Math.min(1,e))}var nj=class extends K{constructor(e){super(),this.elapsed=0,this.done=!1,this.duration=e.duration??.8,this.rise=e.rise??24;let t=new CA({text:e.text,color:e.color,size:e.size});t.anchor.set(.5),this.addChild(t)}get finished(){return this.done}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.y=-this.rise*t,this.alpha=1-t,t>=1&&(this.done=!0,this.parent?.removeChild(this),this.destroy({children:!0}))}},rj=class extends K{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=Jt.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)}},ij=class extends K{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 UA({width:0,height:0,modal:!1,closable:!1,dims:!1}),this.body=new CA({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=$(),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}},aj=class extends K{constructor(e){super(),this.topics=e.topics;let t=e.listWidth??Math.floor(e.width/3),n=e.width-t-$().spacing,r=$().direction===`rtl`;this.list=new KA({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 CA({wrapWidth:n}),this.body.x=r?0:t+$().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)}},oj=class e extends K{constructor(t){super(),this.text=new CA({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(`
1335
- `)}},sj=class extends K{constructor(e){super(),this.backdrop=new PC,this.progress=new ej({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 CA({text:e.title??`Loading`,size:18,bold:!0,align:`center`}),this.status=new CA({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=$().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 cj(e,t={}){return n=>new Promise(r=>{e.push(new JA({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)}))})}var lj={farLeft:.12,left:.28,center:.5,right:.72,farRight:.88},uj=class extends K{constructor(e,t){super(),this.backdropLayer=new K,this.actorLayer=new K,this.backdrop=null,this.outgoingBackdrop=null,this.actors=new Map,this.definitions=new Map,this.focused=null,this.tweener=new Yt,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 ds(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 ZO(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:lj[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}},dj=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 JA({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(fj(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(fj(t,e));return new Promise(t=>{a.push(new JA({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 fj(e,t){return`${e??``}\u0000${t}`}function pj(e){let t=mj(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=gj(e.body);continue}if(Object.prototype.hasOwnProperty.call(n,e.name))throw Error(`this twee source defines "${e.name}" twice`);n[e.name]=_j(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 mj(e){let t=[],n=null,r=[],i=()=>{n!==null&&t.push({name:n,body:r.join(`
1334
+ `))}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 SA(this.reveal)}update(e){if(!this.finished){if(!this.pageComplete){bA(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):(xA(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=$(),t=this.choices.map(e=>({text:e.text,disabled:e.disabled,value:e.value??e.text})),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 KA({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())}},wM=/[A-Za-z0-9]/;function TM(e,t){let{lineHeight:n,columnHeight:r}=t,i=t.rotate??wM,a=[],o=0,s=0;for(let t of e){if(t===`
1335
+ `){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 EM=class extends K{constructor(e){super(),this.themeListener=e=>this.build(e),this.opts=e,this.build($()),hA.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=TM(this.opts.text,{lineHeight:n,columnHeight:this.opts.columnHeight,rotate:this.opts.rotate});for(let n of r){let r=new FD({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){hA.remove(this.themeListener),super.destroy(e)}},DM=class extends K{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 KA({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=Ee(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&&ge.add(this.onKeyCaptured)})}cancelCapture(){ge.remove(this.onKeyCaptured),this.capturing=null,this.refresh()}finishCapture(e,t){ge.remove(this.onKeyCaptured),this.capturing=null;let n=we(t).filter(t=>t!==e);if(n.length>0&&!this.onConflict(t,e,n)){this.refresh();return}for(let e of n)Se(e,Ee(e).filter(e=>e!==t));Se(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){ge.remove(this.onKeyCaptured),super.destroy(e)}},OM=class e extends K{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=$();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 CA({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`),hA.add(this.themeListener)}static createBackground(e,t){return e?new HA(e.texture,{border:e.border}):t.panel?new HA(t.panel,{border:t.panelBorder}):new PC}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 CA({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=$().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=$().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=$(),t=this.state===`pressed`?10066329:this.state===`hover`?14540253:this.state===`disabled`?7829367:16777215;if(this.background instanceof HA)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){hA.remove(this.themeListener),super.destroy(e)}},kM=class extends K{constructor(e){super(),this.track=new PC,this.fill=new PC,this.themeListener=()=>this.draw(),this.width_=e.width,this.height_=e.height,this.explicitColor=e.color!==void 0,this.color=e.color??$().color.textHighlight,this.fraction=AM((e.value??1)/(e.max??1)),this.fillTexture=e.fillTexture,this.backgroundTexture=e.backgroundTexture,this.roundUpToPixel=e.roundUpToPixel??!1,this.addChild(this.track),this.addChild(this.fill),this.draw(),hA.add(this.themeListener)}get value(){return this.fraction}setValue(e,t=1){this.fraction=AM(t>0?e/t:0),this.draw()}resize(e,t){this.width_=e,this.height_=t,this.draw()}draw(){let e=$();if(this.explicitColor||(this.color=e.color.textHighlight),this.track.clear().rect(0,0,this.width_,this.height_),this.track.fill(this.backgroundTexture?{texture:this.backgroundTexture}:{color:e.color.panelFill}),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.color}:{texture:this.fillTexture}:{color:this.color})}}destroy(e){hA.remove(this.themeListener),super.destroy(e)}};function AM(e){return Math.max(0,Math.min(1,e))}var jM=class extends K{constructor(e){super(),this.elapsed=0,this.done=!1,this.duration=e.duration??.8,this.rise=e.rise??24;let t=new CA({text:e.text,color:e.color,size:e.size});t.anchor.set(.5),this.addChild(t)}get finished(){return this.done}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.y=-this.rise*t,this.alpha=1-t,t>=1&&(this.done=!0,this.parent?.removeChild(this),this.destroy({children:!0}))}},MM=class extends K{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=Jt.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)}},NM=class extends K{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 UA({width:0,height:0,modal:!1,closable:!1,dims:!1}),this.body=new CA({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=$(),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}},PM=class extends K{constructor(e){super(),this.topics=e.topics;let t=e.listWidth??Math.floor(e.width/3),n=e.width-t-$().spacing,r=$().direction===`rtl`;this.list=new KA({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 CA({wrapWidth:n}),this.body.x=r?0:t+$().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)}},FM=class e extends K{constructor(t){super(),this.text=new CA({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(`
1336
+ `)}},IM=class extends K{constructor(e){super(),this.backdrop=new PC,this.progress=new kM({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 CA({text:e.title??`Loading`,size:18,bold:!0,align:`center`}),this.status=new CA({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=$().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 LM(e,t={}){return n=>new Promise(r=>{e.push(new CM({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)}))})}var RM={farLeft:.12,left:.28,center:.5,right:.72,farRight:.88},zM=class extends K{constructor(e,t){super(),this.backdropLayer=new K,this.actorLayer=new K,this.backdrop=null,this.outgoingBackdrop=null,this.actors=new Map,this.definitions=new Map,this.focused=null,this.tweener=new Yt,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 ds(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 ZO(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:RM[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}},BM=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 CM({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(VM(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(VM(t,e));return new Promise(t=>{a.push(new CM({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 VM(e,t){return`${e??``}\u0000${t}`}function HM(e){let t=UM(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=GM(e.body);continue}if(Object.prototype.hasOwnProperty.call(n,e.name))throw Error(`this twee source defines "${e.name}" twice`);n[e.name]=KM(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 UM(e){let t=[],n=null,r=[],i=()=>{n!==null&&t.push({name:n,body:r.join(`
1336
1337
  `)})};for(let t of e.split(`
1337
- `))t.startsWith(`::`)?(i(),n=hj(t),r=[]):n!==null&&r.push(t);return i(),t}function hj(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 gj(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 _j(e,t){let n=[],r=[];for(let i of t.split(`
1338
- `)){let t=vj(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 vj(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(yj(i.slice(a+2,o),n)),i=i.slice(o+2)}}function yj(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 bj=[[0,-1],[1,0],[0,1],[-1,0]],xj=[[0,-1],[1,-1],[1,0],[1,1],[0,1],[-1,1],[-1,0],[-1,-1]],Sj=[[1,0],[1,-1],[0,-1],[-1,-1],[-1,0],[0,1]],Cj=[[1,1],[1,0],[0,-1],[-1,0],[-1,1],[0,1]];function wj(e){return e===4?bj:xj}var Tj={passable:!1,transparent:!1},Ej={passable:!0,transparent:!0},Dj=class e{constructor(e,t,n,r=0,i=`square`){this.rooms=[],this.width=e,this.shape=i,this.height=t,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`?Vt(e,t):wj(n).map(([n,r])=>({x:e+n,y:t+r}))}forEachNeighbor(e,t,n,r){let i=this.shape===`hex`?e&1?Cj:Sj:wj(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)]??Tj}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}))}}static fromJSON(t,n){let r=new e(n.width,n.height,t,0,n.shape);return r.terrain.set(n.terrain.slice(0,r.terrain.length)),r.rooms=n.rooms.map(e=>({...e})),r}};function Oj(e){return{x:Math.floor((e.left+e.right)/2),y:Math.floor((e.top+e.bottom)/2)}}function kj(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 Aj={id:`hall`,paint:(e,t,n)=>e.fillRect(t,n)};function jj(e){return Math.min(e.right-e.left+1,e.bottom-e.top+1)}function Mj(e){return Math.max(e.right-e.left+1,e.bottom-e.top+1)}function Nj(e,t){let n=jj(t),r=Mj(t);return e.filter(e=>n>=(e.minSize??0)&&r<=(e.maxSize??1/0))}function Pj(e,t){let n=Nj(e,t);if(n.length===0)return null;let r=ce(n.map(e=>e.weight??1));return r===null?null:n[r]}var Fj=[{passable:!1,transparent:!1},{passable:!0,transparent:!0}];function Ij(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 Dj(t,n,[...Fj,...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=>kj(l,e,2))){g++;continue}p.push(l);let m=(d?.length?Pj(d,l):null)??Aj;m.paint(f,l,c),h.push(m.id),u?.onRoomPlaced?.(l,p.length-1)}for(let e=1;e<p.length;e++){Rj(f,Oj(p[e-1]),Oj(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){Rj(f,Oj(p[e]),Oj(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 Lj(e){return Ij(e).level}function Rj(e,t,n,r){oe(.5)?(zj(e,t.x,n.x,t.y,!0,r),zj(e,t.y,n.y,n.x,!1,r)):(zj(e,t.y,n.y,t.x,!1,r),zj(e,t.x,n.x,n.y,!0,r))}function zj(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 Bj(e,t=new Set){let n=e.passableCells().filter(e=>!t.has(e));return n.length>0?n[k(n.length)]:null}function Vj(e,t){let n=null,r=-1;for(let i of e.rooms){let e=Oj(i),a=(e.x-t.x)**2+(e.y-t.y)**2;a>r&&(r=a,n=i)}return n}var Hj=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 Uj(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 Wj(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 Gj(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 Kj(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 qj(e,t){let n=[];return e.retries!==t.retries&&n.push({stage:`graph`,field:`retries`,expected:e.retries,actual:t.retries}),Wj(e.graph,t.graph)||n.push({stage:`graph`,field:`graph`,expected:e.graph,actual:t.graph}),(e.width!==t.width||e.height!==t.height||!Gj(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}),Kj(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 Jj(e,t=2){let n=e(),r=[];for(let i=1;i<t;i++)r.push(...qj(n,e()));return r}var Yj=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)*Yj,e=e*69069+1>>>0,this._s1=e*Yj,e=e*69069+1>>>0,this._s2=e*Yj,this._c=1,this}getUniform(){let e=2091639*this._s0+this._c*Yj;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 Xj=class{getContainer(){return null}setOptions(e){this._options=e}},Zj=class extends Xj{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 Qj(e){return e.charAt(0).toUpperCase()+e.substring(1)}function $j(e,...t){let n=$j.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=Qj(d)),d})}$j.map={s:`toString`};var eM=class e extends Zj{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}};eM.cache=!1;var tM={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]]},nM=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=[tM[8][7],tM[8][1],tM[8][3],tM[8][5]];break;case 6:i=tM[6],a=1,o=[-1,1];break;case 8:i=tM[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}},rM=class extends nM{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)}},iM=class extends nM{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}},aM=[[-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]],oM={DiscreteShadowcasting:rM,PreciseShadowcasting:iM,RecursiveShadowcasting:class extends nM{compute(e,t,n,r){r(e,t,0,1);for(let i=0;i<aM.length;i++)this._renderOctant(e,t,aM[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,aM[o],n,i),this._renderOctant(e,t,aM[a],n,i),this._renderOctant(e,t,aM[r],n,i),this._renderOctant(e,t,aM[s],n,i)}compute90(e,t,n,r,i){i(e,t,0,1);let a=(r-1+8)%8;this._renderOctant(e,t,aM[r],n,i),this._renderOctant(e,t,aM[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 sM=class{constructor(e,t,n,r={}){this._toX=e,this._toY=t,this._passableCallback=n,this._options=Object.assign({topology:8},r),this._dirs=tM[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}},cM={Dijkstra:class extends sM{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 sM{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 lM(e,t){return Math.max(Math.abs(e.x-t.x),Math.abs(e.y-t.y))}function uM(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 dM(e,t,n){let r=uM(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 fM(e,t,n,r){return!(lM(t,n)>r.range||(r.requireLineOfSight??!0)&&!dM(e,t,n))}function pM(e,t,n){switch(n.kind){case`single`:return[t];case`line`:return uM(e,t);case`cone`:return mM(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 mM(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 hM(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=lM(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 gM(e,t,n=1){for(let n of t)if(e<=n.max)return n.multiplier;return n}function _M(e,t){return t.length===0?1:t[Math.min(e,t.length-1)]}function vM(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 yM=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 oM.PreciseShadowcasting((t,n)=>e.transparent(t,n))}update(e,t,n,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 Gt(i,n)){if(!this.level.inside(e.x,e.y))continue;let t=Wt(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 Gt(a,n)){if(!this.level.inside(e.x,e.y))continue;let t=Wt(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)||lM(a,{x:t,y:o})>n)continue;let e=uM(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)}},bM=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)}},xM=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 cM.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()}},SM=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){this.entries.push({actor:e,time:this.now+t,sequence:this.sequence++}),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}))}}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})),r.sort(),r}sort(){this.entries.sort((e,t)=>e.time-t.time||e.sequence-t.sequence)}};function CM(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:wM(e,n,a)};let c=new yM(e);return c.update(n.x,n.y,o),c.isVisible(i.x,i.y)?r<=s?{state:`flee`,step:TM(e,n,i,a)}:{state:`hunt`,step:t.step(n,i,a)}:{state:`wander`,step:wM(e,n,a)}}function wM(e,t,n){return se(EM(e,t,n))}function TM(e,t,n,r){let i=EM(e,t,r),a=null,o=DM(t,n);for(let e of i){let t=DM(e,n);t>o&&(o=t,a=e)}return a}function EM(e,t,n){let r=n.blocked,i=[];for(let[a,o]of wj(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 DM(e,t){return(e.x-t.x)**2+(e.y-t.y)**2}var OM=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}},kM=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}},AM=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}},jM=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}},MM=class e{constructor(e,t){this.width=e,this.height=t,this.volume=new Float32Array(e*t)}volumeAt(e,t){return e<0||t<0||e>=this.width||t>=this.height?0:this.volume[t*this.width+e]}total(){let e=0;for(let t=0;t<this.volume.length;t++)e+=this.volume[t];return e}seed(e,t,n){e<0||t<0||e>=this.width||t>=this.height||(this.volume[t*this.width+e]+=n)}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 wj(4)){let a=i+t,o=n+r;a<0||o<0||a>=this.width||o>=this.height||e(a,o)&&s.push(o*this.width+a)}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}}for(let e=0;e<r.length;e++){let t=r[e]*n;this.volume[e]=t<.001?0:t}}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}},NM=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}},PM=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=>lM(e,t)<=this.radius);return n&&(this.detected=!0),n}reset(){this.detected=!1}},FM=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}},IM=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}};function LM(e,t={}){return(t.within?[...t.within]:BM(e.cellCount)).filter(n=>!(t.occupied?.has(n)||t.terrain&&!t.terrain.has(e.terrain[n])))}function RM(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 zM(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 BM(e){let t=Array(e);for(let n=0;n<e;n++)t[n]=n;return t}var VM=l({AbilityCycle:()=>jM,Blob:()=>MM,BossPhases:()=>AM,CombatHooks:()=>NM,DUNGEON_KINDS:()=>Fj,Doors:()=>kM,Elevation:()=>bM,FLOOR:()=>Ej,FeatureLayer:()=>Hj,FieldOfView:()=>yM,Level:()=>Dj,MultiStageAbility:()=>IM,Pathfinder:()=>xM,Scheduler:()=>SM,Secrets:()=>OM,Stealth:()=>PM,TriggerTracker:()=>FM,WALL:()=>Tj,areaFalloffMultiplier:()=>_M,canTarget:()=>fM,candidateCells:()=>LM,cellsNear:()=>RM,chainTargets:()=>hM,chebyshevDistance:()=>lM,checkDeterminism:()=>Jj,compareDungeonArtifacts:()=>qj,coneCells:()=>mM,decideMonsterAI:()=>CM,eligibleBuilders:()=>Nj,findFreeCell:()=>Bj,furthestRoom:()=>Vj,generateDungeon:()=>Lj,generateDungeonGraph:()=>Ij,hallBuilder:()=>Aj,hasLineOfSight:()=>dM,knockbackPath:()=>vM,neighbourOffsets:()=>wj,pickBuilder:()=>Pj,rangeMultiplier:()=>gM,rectCenter:()=>Oj,rectsOverlap:()=>kj,resolveArea:()=>pM,rollRoster:()=>Uj,selectDistinctCells:()=>zM,traceLine:()=>uM});function HM(e,t,n={}){let r={},i=t.replace(/\r/g,``).split(`
1339
- `),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]=WM(e,t,s)}else r[a]=UM(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 UM(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 WM(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 UM((o??n.find(e=>e.key===s)??i).value)}}}function GM(){return{format(e,t){let n=e.params;if(t===`audio`){let t=`${e.type}.audio`;return oP(t)?JN(t,n):``}let r=`${e.type}.${t}`;return oP(r)?YN(r,n):YN(e.type,n)}}}function KM(e,t){return new Intl.NumberFormat(KN(),t).format(e)}function qM(e,t){return new Intl.DateTimeFormat(KN(),t).format(e)}function JM(e,t){return new Intl.ListFormat(KN(),t).format(e)}var YM=/\{(\w+)(=)?(?:!([sra]))?(?::([^{}]*))?\}/g;function XM(e){let t=[];YM.lastIndex=0;let n=0,r;for(;(r=YM.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 ZM(e){return`${e.debug?`=`:``}${e.conv?`!${e.conv}`:``}${e.spec===void 0?``:`:${e.spec}`}`}function QM(e,t){let n=new Map,r=new Map;for(let t of XM(e))typeof t!=`string`&&n.set(t.token,ZM(t));for(let e of XM(t))typeof e!=`string`&&r.set(e.token,ZM(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 $M=/^(?:(.)?([<>=^]))?([+\- ])?(z)?(#)?(0)?(\d+)?([,_])?(?:\.(\d+))?([bcdeEfFgGnosxX%])?$/,eN={b:2,o:8,x:16,X:16},tN={b:`0b`,o:`0o`,x:`0x`,X:`0X`},nN=new Set([`f`,`F`,`e`,`E`,`g`,`G`,`%`,`n`]);function rN(e){return Number.isNaN(e)?`nan`:e===1/0?`inf`:e===-1/0?`-inf`:Object.is(e,-0)?`-0.0`:String(e)}function iN(e,t,n=3,r=`\\d`){return e.replace(RegExp(`\\B(?=(${r}{${n}})+(?!${r}))`,`g`),t)}function aN(e,t){let n=/^(\d+)/.exec(e);return n?iN(n[1],t)+e.slice(n[1].length):e}function oN(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 sN(e){return e.replace(/([eE][+-])(\d)$/,`$10$2`)}function cN(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=sN(e.toExponential(a-1)),r||(s=s.replace(/(\.\d*?)0+(e|$)/,`$1$2`).replace(/\.e/i,`e`))),n?s.toUpperCase():s}function lN(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 uN(e,t,n,r,i,a){return oN(a===void 0?e:e.slice(0,a),i,t??(r?`0`:` `),n??`<`)}function dN(e,t,n=`en`){if(t===``)return typeof e==`number`?rN(e):e;let r=$M.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:uN(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:oN(String.fromCodePoint(t),h,i??` `,a??`>`)}if(!Number.isFinite(e)){if(p!==void 0&&!nN.has(p))return;let t=Number.isNaN(e)?`nan`:`inf`;return(p===`F`||p===`E`||p===`G`)&&(t=t.toUpperCase()),p===`%`&&(t+=`%`),oN((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=cN(_,m,!1,!!c,m-1)}else y=rN(_);v&&(y=aN(y,v))}else if(p===`d`){if(m!==void 0||!Number.isInteger(_))return;y=String(Math.trunc(_)),v&&(y=iN(y,v))}else if(p in eN){if(m!==void 0||!Number.isInteger(_)||d===`,`)return;y=Math.trunc(_).toString(eN[p]),p===`X`&&(y=y.toUpperCase()),v&&(y=iN(y,v,4,`[0-9a-fA-F]`)),c&&(y=tN[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}=lN(n),r=cN(_,m??6,!1,!!c),i=r.split(`e`)[0],a=r.slice(i.length);y=aN(i,e).replace(`.`,t)+a}}else if(p===`f`||p===`F`)y=_.toFixed(m??6),v&&(y=aN(y,v));else if(p===`e`||p===`E`)y=sN(_.toExponential(m??6)),p===`E`&&(y=y.toUpperCase()),v&&(y=aN(y,v));else if(p===`g`||p===`G`)y=cN(_,m??6,p===`G`,!!c),v&&(y=aN(y,v));else{let e=_*100;y=(Number.isFinite(e)?e.toFixed(m??6):`inf`)+`%`,v&&Number.isFinite(e)&&(y=aN(y,v))}let b=g?`-`:o===`+`?`+`:o===` `?` `:``,x=i??(l&&!a?`0`:` `),S=a??(l&&!a?`=`:`>`);return S===`=`?b+oN(y,h-b.length,x,`>`):oN(b+y,h,x,S)}function fN(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 pN(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}mN(r)&&r.other===void 0&&t.push({key:n,kind:`plural-missing-other`,detail:`plural forms have no "other" branch`})}return t}function mN(e){return typeof e==`object`&&!!e&&!(`format`in e)}function hN(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 gN(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 _N(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 vN(e,t=.8){let n=Object.entries(e.messages).map(([e,t])=>[e,gN(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=_N(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 yN(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 bN(e,t){let n=Object.keys(e.messages);if(n.length===0)return 1;let{missing:r}=fN(e,t);return(n.length-r.length)/n.length}function xN(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 SN(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 CN(e,t){return{base:e,target:t}}var wN=`.audio`;function TN(e){return e.endsWith(wN)}function EN(e){return[...new Set([...Object.keys(e.base.messages),...Object.keys(e.target.messages)])].filter(e=>!TN(e)).sort()}function DN(e){if(e===void 0)return;let t=gN(e);return t===``?void 0:t}var ON=[`log`,`compact`,`accessibility`,`debug`];function kN(e){let t=e.lastIndexOf(`.`);if(!(t<=0||!ON.includes(e.slice(t+1))))return`${e.slice(0,t)}${wN}`}function AN(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}${wN}`],o=kN(t);o&&a.push(o);let s,c,l=!1;for(let t of a){let n=DN(e.target.messages[t]);if(n!==void 0){s=n,c=t;break}let r=DN(e.base.messages[t]);if(r!==void 0){s=r,c=t,l=!0;break}}return{key:t,baseText:n===void 0?``:gN(n),targetText:r===void 0?``:gN(r),status:i,sound:s,soundKey:c,soundInherited:l}}function jN(e,t){let n=`${t}${wN}`;return n in e.target.messages||n in e.base.messages?n:kN(t)??n}function MN(e,t={}){let n=t.query?.toLowerCase()??``;return EN(e).map(t=>AN(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 NN(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 PN(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 FN(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 IN(e,t,n){let r={...e.target.messages},i=jN(e,t);return n===``?delete r[i]:r[i]=n,{...e,target:{...e.target,messages:r}}}function LN(e){let t=e=>({...e,messages:Object.fromEntries(Object.entries(e.messages).filter(([e])=>!TN(e)))});return bN(t(e.base),t(e.target))}function RN(e){return{base:e.target,target:e.base}}var zN=l({AUDIO_SUFFIX:()=>wN,catalogCompleteness:()=>bN,catalogUsage:()=>yN,copyFromBase:()=>PN,createCatalogFormatter:()=>GM,createEditSession:()=>CN,cueKeyFor:()=>jN,deleteTargetKey:()=>FN,diffCatalogKeys:()=>fN,diffPlaceholders:()=>QM,direction:()=>qN,findSimilarMessages:()=>vN,formatDate:()=>qM,formatList:()=>JM,formatNumber:()=>KM,formatSpec:()=>dN,has:()=>oP,isAudioKey:()=>TN,levenshteinDistance:()=>_N,locale:()=>KN,mergeCatalogKeys:()=>SN,messageText:()=>gN,nonBreakingUnit:()=>nP,parseFTL:()=>HM,pluralFormCoverage:()=>xN,reset:()=>pP,sessionCompleteness:()=>LN,sessionKeys:()=>EN,sessionRow:()=>AN,sessionRows:()=>MN,setActive:()=>GN,setBase:()=>WN,setTargetSound:()=>IN,setTargetText:()=>NN,swapSession:()=>RN,t:()=>YN,tRaw:()=>JN,tokenizeMessage:()=>XM,typographic:()=>tP,validateCatalog:()=>pN,validateMessageAudio:()=>hN}),BN=null,VN=null,HN=null,UN=null;function WN(e){BN=e}function GN(e){VN=e,HN=e?new Intl.PluralRules(e.locale):null}function KN(){return(VN??BN)?.locale??`en`}function qN(){return(VN??BN)?.direction??`ltr`}function JN(e,t){let n=VN?.messages[e]??BN?.messages[e];if(n===void 0)return e;let r=typeof n==`string`?n:cP(n)?n.format(t):sP(n,t?.count);return t?lP(r,t):r}function YN(e,t){if(!oP(e))return e;let n=JN(e,t),r=(VN??BN)?.typography===!1?n:tP(n,KN());return qN()===`rtl`?`⁧${r}⁩`:r}var XN=` `,ZN=`\xA0`,QN=[`Chapitre`,`Tome`,`Livre`,`Partie`,`Section`,`Article`,`Acte`,`Scène`,`Niveau`,`Manche`,`Round`,`Étape`,`Volume`,`Figure`,`Page`,`Numéro`],$N=[`Nr`,`Dr`,`Bd`,`Kap`,`Art`,`Abb`,`Str`,`Tel`],eP=[`kg`,`g`,`mg`,`t`,`km`,`m`,`cm`,`mm`,`l`,`ml`,`h`,`min`,`s`,`%`,`°C`,`€`];function tP(e,t=KN()){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=rP(r)),n===`de`&&(r=iP(r)),r}function nP(e,t,n=KN()){let r=n.split(`-`)[0].toLowerCase();return`${e}${r===`fr`?XN:r===`de`?ZN:` `}${t}`}function rP(e){let t=e.replace(/\s?([;!?])/g,`${XN}$1`).replace(/«\s?/g,`«${XN}`).replace(/\s?»/g,`${XN}»`);t=t.replace(/(\p{L})\s?:/gu,`$1${XN}:`);let n=RegExp(`\\b(${QN.join(`|`)})\\s+(?=\\d)`,`g`);return t.replace(n,`$1${ZN}`)}function iP(e){let t=RegExp(`(\\d)\\s+(?=(?:${eP.map(aP).join(`|`)})(?![\\p{L}\\p{N}]))`,`gu`),n=RegExp(`\\b(${$N.join(`|`)})\\.\\s+`,`g`);return e.replace(t,`$1${ZN}`).replace(n,`$1.${ZN}`)}function aP(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function oP(e){return VN?.messages[e]!==void 0||BN?.messages[e]!==void 0}function sP(e,t){return t===void 0?e.other??Object.values(e)[0]??``:e[(HN??(UN??=new Intl.PluralRules(`en`))).select(t)]??e.other??``}function cP(e){return`format`in e}function lP(e,t){return XM(e).map(e=>typeof e==`string`?e:uP(e,t)).join(``)}function uP(e,t){let n=t[e.token];if(n===void 0)return e.raw;try{let t=e.conv===void 0?n:dP(n,e.conv),r=e.spec===void 0?String(t):dN(t,e.spec,KN());return r===void 0?e.raw:e.debug?`${e.token}=${r}`:r}catch{return e.raw}}function dP(e,t){if(t===`s`)return String(e);if(typeof e==`number`){let n=dN(e,``,`en`)??String(e);return t===`a`?fP(n):n}let n=`'${e.replace(/\\/g,`\\\\`).replace(/'/g,`\\'`).replace(/\n/g,`\\n`).replace(/\r/g,`\\r`).replace(/\t/g,`\\t`)}'`;return t===`a`?fP(n):n}function fP(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 pP(){BN=null,VN=null,HN=null}function mP(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 hP=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]=mP(e[t],this.modifiersFor(t));for(let t of this.derived)e[t.name]=mP(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 gP(e,t,n){return{maxLevel:n,experienceFor:n=>n<=1?0:Math.round(e*(n-1)**t)}}var _P=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 vP(e,t,n=()=>ie(1,20)){return e+n()>=t}var yP=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}},bP=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}},xP=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,...SP(a),id:n.id,quantity:n.quantity};return i&&(o.contents=e.fromJSON(t,i)),o}),r}};function SP(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}function CP(e,t){let n=new Map;for(let e of t.ingredients)n.set(e.id,(n.get(e.id)??0)+e.quantity);for(let[t,r]of n){let n=e.find(t);if(!n||n.quantity<r)return!1}let r=t.ingredients.map(t=>({...e.find(t.id),quantity:t.quantity}));for(let n of t.ingredients)e.remove(n.id,n.quantity);if(e.add(t.result))return!0;for(let t of r)e.add(t);return!1}function wP(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 TP(e,t,n){let r=Symbol(`statusEffect`);for(let t of n.modifiers)e.addModifier({...t,source:r});return wP(t,{duration:n.duration,tick:n.tick,onExpire:()=>e.removeModifiersFrom(r)})}function EP(e){let t=e.entries.filter(e=>e.weight>0);if(t.length===0)return null;let n=ce(t.map(e=>e.weight));return n===null?null:t[n]}function DP(e){return e.affix}function OP(e,t){let n=e.affix!==void 0;e.affix=t.id,t.curse?e.cursed=!0:n&&(e.cursed=!1)}function kP(e){e.affix!==void 0&&(e.cursed=!1),delete e.affix}function AP(e,t){if(e.affix===void 0){kP(t);return}t.affix=e.affix,t.cursed=e.cursed??!1}function jP(e,t){return!(e.trigger!==t.trigger||e.kinds&&(t.kind===void 0||!e.kinds.includes(t.kind)))}function MP(e){e.identified=!0}function NP(e,t,n=`keep`){return Number.isFinite(t)?(e.level=(e.level??0)+t,n===`remove`&&kP(e),e.level):e.level??0}function PP(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 FP(e,t){e.maxDurability!==void 0&&(!Number.isFinite(t)||t<=0||(e.durability=Math.min(e.maxDurability,(e.durability??e.maxDurability)+t)))}function IP(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 wP(t,{duration:n.duration,tick:n.tick,onExpire:()=>{for(let[t,n]of r)e[t]=n}})}var LP=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 RP(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 zP=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 BP(e,t){return t.map(t=>({stat:t.stat,op:t.op,value:t.base+t.perLevel*e}))}function VP(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 HP=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=VP(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 UP(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 WP(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 GP(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 KP(e){let t=new Map;for(let n of e)t.set(n.stat,(t.get(n.stat)??0)+n.amount);return t}function qP(e,t){return[...KP(GP(t))].every(([t,n])=>e.base(t)>=n)}function JP(e,t){let n=KP(GP(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 YP(e,t,n=1){for(let[r,i]of KP(GP(t)))e.setBase(r,e.base(r)+i*n)}function XP(e,t,n,r){return JP(e,t)?n.refund(Math.floor(t.amount/r)):0}var ZP=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 QP(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 $P=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)}}},eF=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(tF(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=tF(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=tF(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 tF(e,t){return[e,t].sort().join(`\0`)}var nF=new Set([`id`,`growth`,`level`,`startingAffix`,`startingItem`,`lowHpReaction`]);function rF(e,t={},n){let r=new hP({base:cF(e)}),i;e.growth!==void 0&&(i=new _P(sF(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}"`);OP(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 Pt,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 iF(e,t={},n){return e.map(e=>rF(e,t,n))}function aF(e){let t={stats:e.stats.toJSON()};return e.progression&&(t.progression=e.progression.toJSON()),e.item&&(t.item=e.item),t}function oF(e,t,n,r){let i=rF(e,t,r);if(i.stats=hP.fromJSON({base:cF(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=_P.fromJSON(sF(e,t),n.progression)}return n.item!==void 0&&(i.item=n.item),i}function sF(e,t){let n=t.growthCurves?.[e.growth??``];if(!n)throw Error(`entity template "${e.id}": unknown growth curve "${e.growth}"`);return n}function cF(e){let t={};for(let[n,r]of Object.entries(e))if(!nF.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 lF=l({Advancement:()=>zP,Appearances:()=>HP,AuraField:()=>$P,Barrier:()=>ZP,Charges:()=>LP,EquipmentSlots:()=>bP,Inventory:()=>xP,Progression:()=>_P,SkillPoints:()=>yP,StatBlock:()=>hP,SupportLedger:()=>eF,affixOf:()=>DP,applyAffix:()=>OP,applyItemStatusEffect:()=>IP,applyStatusEffect:()=>TP,assignAppearances:()=>VP,assignTraits:()=>QP,buildEntities:()=>iF,buildEntity:()=>rF,buy:()=>UP,canAfford:()=>qP,convertToCharges:()=>XP,copyAffix:()=>AP,craft:()=>CP,damageItem:()=>PP,enchant:()=>NP,fromEntitySaveState:()=>oF,identify:()=>MP,matchesContext:()=>jP,powerCurve:()=>gP,refund:()=>YP,removeAffix:()=>kP,repairItem:()=>FP,rollAffix:()=>EP,rollLoot:()=>RP,scaledModifiers:()=>BP,sell:()=>WP,skillCheck:()=>vP,spend:()=>JP,toEntitySaveState:()=>aF}),uF=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)}},dF=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()]}},fF=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 pF(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 mF=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})}},hF=l({EnvironmentClock:()=>mF,Overworld:()=>dF,TurnClock:()=>fF,World:()=>uF,rollEncounter:()=>pF});function gF(e,t,n={}){let r=n.pick??k,i=0;return t.forEach((t,n)=>{_F(t,t.name??`#${n+1}`);let a=vF(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 _F(e,t){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 n=e.width*e.height;for(let[r,i]of Object.entries(e.input))if(i.length!==n)throw Error(`automap rule "${t}" input "${r}" has ${i.length} cells, but the pattern is ${n}`);e.outputs.forEach((e,r)=>{for(let[i,a]of Object.entries(e))if(a.length!==n)throw Error(`automap rule "${t}" output ${r+1} "${i}" has ${a.length} cells, but the pattern is ${n}`)})}function vF(e,t){let n=[];for(let r=0;r+t.height<=e.heightInTiles;r++)for(let i=0;i+t.width<=e.widthInTiles;i++)yF(e,t,i,r)&&n.push([i,r]);return n}function yF(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 bF=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 xF(e,t){return`switch`in e?t.switch(e.switch)===e.equals:t.variable(e.variable)>=e.atLeast}function SF(e,t){let n;for(let r of e.pages)(r.conditions??[]).every(e=>xF(e,t))&&(n=r);return n}var CF=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=xF(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 wF(e,t){t&&e.has?.(t)&&e.play?.(t)}var TF=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=EF(e,t),this.playIdle())}moveBy(e,t){return!this.target&&(this.facing=EF(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=DF(this.fromX,this.target.x,this.progress)*this.tileWidth,this.sprite.y=DF(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(){wF(this.sprite,this.options.walkAnimation?.(this.facing))}playIdle(){wF(this.sprite,this.options.idleAnimation?.(this.facing))}};function EF(e,t){return e>0?`right`:e<0?`left`:t>0?`down`:`up`}function DF(e,t,n){return e+(t-e)*n}var OF=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(){wF(this.sprite,this.options.walkAnimation?.(this.facing))}playIdle(){wF(this.sprite,this.options.idleAnimation?.(this.facing))}};function kF(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 AF(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 jF(e,t){let n=PF(e.x,t.x,t.x+t.width),r=PF(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 MF(e,t,n,r){let{tileSize:i,isSolid:a}=r;if(!(i>0))throw Error(`collision tileSize must be positive`);let o=NF(e.x,e.y,e.width,e.height,t,i,a,!0);return{x:o,y:NF(o,e.y,e.width,e.height,n,i,a,!1)}}function NF(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 PF(e,t,n){return e<t?t:e>n?n:e}var FF=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?xF(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 IF(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(LF(e.id,r))}return t.map(e=>n.get(e))}function LF(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 RF=class{constructor(e){this.name=e}},zF=4,BF=8,VF=new WeakMap;function HF(e){return VF.get(e)}function UF(e,t){return VF.set(e,t),e}var WF=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&&VF.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!==zF||t>BF)throw Error(`Marshal: unsupported version ${e}.${t} (expected ${zF}.${BF} or lower)`);return this.readValue()}};function GF(e){return new WF(e).readDocument()}function KF(e){return typeof e==`object`&&!!e&&`class`in e&&`ivars`in e}function qF(e){let t=[zF,BF];return JF(t,e),new Uint8Array(t)}function JF(e,t){if(t==null)e.push(YF(`0`));else if(t===!0)e.push(YF(`T`));else if(t===!1)e.push(YF(`F`));else if(t instanceof RF)e.push(YF(`:`)),XF(e,t.name);else if(typeof t==`number`)Number.isInteger(t)&&Math.abs(t)<2**30?(e.push(YF(`i`)),ZF(e,t)):(e.push(YF(`f`)),XF(e,Number.isFinite(t)?String(t):t>0?`inf`:t<0?`-inf`:`nan`));else if(typeof t==`string`)e.push(YF(`"`)),XF(e,t);else if(Array.isArray(t)){e.push(YF(`[`)),ZF(e,t.length);for(let n of t)JF(e,n)}else if(t instanceof Map){let n=VF.has(t);e.push(YF(n?`}`:`{`)),ZF(e,t.size);for(let[n,r]of t)JF(e,n),JF(e,r);n&&JF(e,VF.get(t))}else if(KF(t)){e.push(YF(`o`)),e.push(YF(`:`)),XF(e,t.class);let n=Object.entries(t.ivars);ZF(e,n.length);for(let[t,r]of n)e.push(YF(`:`)),XF(e,t),JF(e,r)}else throw Error(`Marshal: cannot encode a value of type ${typeof t}`)}function YF(e){return e.charCodeAt(0)}function XF(e,t){let n=new TextEncoder().encode(t);ZF(e,n.length);for(let t of n)e.push(t)}function ZF(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 QF=l({AUTOMAP_EMPTY:()=>-1,EventRunner:()=>CF,FreeMover:()=>OF,GameState:()=>bF,GridMover:()=>TF,QuestLog:()=>FF,RubySymbol:()=>RF,aabbOverlap:()=>kF,activePage:()=>SF,automap:()=>gF,circleAabbOverlap:()=>jF,circleOverlap:()=>AF,conditionHolds:()=>xF,decodeMarshal:()=>GF,encodeMarshal:()=>qF,hashDefaultOf:()=>HF,questsFromRows:()=>IF,resolveAabbAgainstTiles:()=>MF,withHashDefault:()=>UF}),$F=gP(20,2,100),eI=class{constructor(e){this.species=e.species,this.deriveStats=e.deriveStats,this.progression=new _P(e.species.growth??$F,{level:e.level??1}),this.stats=new hP({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}}},tI=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)}},nI=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 rI(e){return[...e].sort((e,t)=>(t.priority??0)-(e.priority??0)||t.speed-e.speed)}function iI(e,t){let n=null;for(let r of e)r.at(t)&&(n=r.into);return n}var aI=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 oI(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 sI(e,t,n,r){let i=null,a=cI(e,n,r);return t.forEach((e,t)=>{let o=cI(e.types,n,r);o<a&&(a=o,i=t)}),i}function cI(e,t,n){return Math.max(...n.map(n=>t.multiplierFor(n,e)))}var lI=class extends x{},uI=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))}},dI=l({BattleHooks:()=>lI,Creature:()=>eI,Field:()=>uI,Party:()=>nI,StatStages:()=>aI,TypeMatrix:()=>tI,battleOrder:()=>rI,checkEvolution:()=>iI,chooseMove:()=>oI,chooseSwitch:()=>sI});function fI(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 pI(e){return String.fromCharCode(97+(e&7))+String.fromCharCode(49+(e>>3))}function mI(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:fI(t[3]);if(a!==null){let n=t[1]===`w`?5:2;if(_I(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 EI(n,`white`),EI(n,`black`),o}function hI(e){return e===`white`?`black`:`white`}function gI(e){return e&7}function _I(e){return e>>3}function vI(e,t){return e>=0&&e<8&&t>=0&&t<8}function yI(){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 bI(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 xI=[[1,2],[2,1],[2,-1],[1,-2],[-1,-2],[-2,-1],[-2,1],[-1,2]],SI=[[1,0],[1,1],[0,1],[-1,1],[-1,0],[-1,-1],[0,-1],[1,-1]],CI=[[1,1],[-1,1],[-1,-1],[1,-1]],wI=[[1,0],[0,1],[-1,0],[0,-1]];function TI(e,t,n){let r=gI(t),i=_I(t),a=n===`white`?i-1:i+1;for(let t of[-1,1]){if(!vI(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 xI){if(!vI(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 SI){if(!vI(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:CI,kinds:[`bishop`,`queen`]},{steps:wI,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(;vI(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 EI(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 DI(e,t){return TI(e.board,EI(e.board,t),hI(t))}function OI(e,t){let n=e.board[t];if(!n||n.side!==e.turn)return[];let r=[],i=gI(t),a=_I(t),o=o=>{for(let[s,c]of o){let o=i+s,l=a+c;for(;vI(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(vI(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(!vI(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 xI){if(!vI(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(CI);break;case`rook`:o(wI);break;case`queen`:o(CI),o(wI);break;case`king`:{for(let[o,s]of SI){if(!vI(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&&!DI(e,n.side)&&(s.king&&!e.board[o+5]&&!e.board[o+6]&&!TI(e.board,o+5,hI(n.side))&&!TI(e.board,o+6,hI(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]&&!TI(e.board,o+3,hI(n.side))&&!TI(e.board,o+2,hI(n.side))&&r.push({from:t,to:o+2,castle:`queenside`}));break}}return r}function kI(e,t){let n=e.board[t.from];if(!n)throw Error(`no piece on ${pI(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[AI(n.side,t.from)]=!1);let i=e.board[t.to];if(i&&i.kind===`rook`&&r(i.side,t.to)&&(e.castling[AI(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=hI(n.side)}function AI(e,t){let n=gI(t)===7;return e===`white`?n?`whiteKingside`:`whiteQueenside`:n?`blackKingside`:`blackQueenside`}function jI(e){let t=[];for(let n=0;n<64;n++)if(!(!e.board[n]||e.board[n]?.side!==e.turn))for(let r of OI(e,n)){let n=bI(e);kI(n,r),!DI(n,e.turn)&&t.push({from:r.from,to:r.to,...r.promotion?{promotion:r.promotion}:{}})}return t}function MI(e,t){let n=e.board[t.from];if(!n||n.side!==e.turn)throw Error(`no ${e.turn} piece on ${pI(t.from)} to move`);let r=OI(e,t.from).find(e=>e.to===t.to&&(e.promotion??null)===(t.promotion??null));if(!r)throw Error(`${pI(t.from)}-${pI(t.to)} is not a legal move here`);let i=bI(e);if(kI(i,r),DI(i,e.turn))throw Error(`${pI(t.from)}-${pI(t.to)} leaves the king in check`);kI(e,r)}function NI(e){return jI(e).length>0?`ongoing`:DI(e,e.turn)?e.turn===`white`?`black-wins`:`white-wins`:`stalemate`}var PI={pawn:100,knight:320,bishop:330,rook:500,queen:900,king:0};function FI(e,t={}){return II(e,t).move}function II(e,t={}){let n=Math.max(1,Math.floor(t.depth??3)),r=t.maxNodes===void 0?1/0:Math.max(1,Math.floor(t.maxNodes)),i=zI(e,jI(e));if(i.length===0)return{move:null,score:RI(e,0),nodes:1};let a=0,o=i[0],s=-1/0,c=-1/0;for(let t of i){if(a>=r)break;let i=bI(e);MI(i,t);let u=-l(i,n-1,-1/0,-c,1);u>s&&(s=u,o=t),c=Math.max(c,u)}return{move:o,score:s,nodes:a};function l(e,t,n,i,o){if(a>=r)return LI(e);if(a++,NI(e)!==`ongoing`)return RI(e,o);if(t===0)return LI(e);let s=-1/0;for(let r of zI(e,jI(e))){let a=bI(e);if(MI(a,r),s=Math.max(s,-l(a,t-1,-i,-n,o+1)),n=Math.max(n,s),n>=i)break}return s}}function LI(e){let t=0;for(let n of e.board)n&&(t+=(n.side===`white`?1:-1)*PI[n.kind]);return e.turn===`white`?t:-t}function RI(e,t){return DI(e,e.turn)?-1e5+t:0}function zI(e,t){return t.slice().sort((t,n)=>BI(e,n)-BI(e,t))}function BI(e,t){let n=e.board[t.to];return(t.promotion?PI[t.promotion]:0)*10+(n?PI[n.kind]:0)}var VI=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 HI(){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 UI(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=>GI(e,t,!0));return n.length>0?n:e.forcedFrom===null?t.flatMap(t=>GI(e,t,!1)):[]}function WI(e,t){if(!UI(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||GI(i,t.to,!0).length===0?(e.turn=e.turn===`red`?`black`:`red`,e.forcedFrom=null):e.forcedFrom=t.to}function GI(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 KI(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 qI(e,t,n){let r=ZI(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 QI(e,r)){if(i[t]!==a||eL(i,e.size,t)!==0)continue;let n=$I(i,e.size,t);n.length===1&&(s=n[0]);for(let e of n)i[e]=null;o+=n.length}if(eL(i,e.size,r)===0)throw Error(`suicide is not a legal Go move`);e.ko=o===1&&eL(i,e.size,r)===1?s:null,e.board=i,e.turn=a,e.passes=0}function JI(e){e.turn=e.turn===`black`?`white`:`black`,e.ko=null,e.passes++}function YI(e){return e.passes>=2?`finished`:`ongoing`}function XI(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=$I(e.board,e.size,r),a=new Set;for(let t of i)for(let n of QI(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 ZI(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 QI(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 $I(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 eL(e,t,n){let r=$I(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 tL(){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 nL(){let e=gL(2,6);return e[0]===e[1]?[...e,...e]:e}function rL(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;aL(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}):aL(e,a,n)&&r.push({from:t,to:a,die:i})}}return r}function iL(e,t){if(!rL(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 aL(e,t,n){return e.points[t]*n>=-1}function oL(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 sL(e){return le(e)}function cL(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 lL(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 uL(e){let t=oL();return e===void 0?sL(t):ne(e,()=>sL(t)),{stock:t,waste:[],tableau:Array.from({length:7},(e,n)=>({down:t.splice(0,6-n),up:t.splice(0,1)})),foundations:[[],[],[],[]]}}function dL(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 fL(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:!hL(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 pL(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 mL(e){return e.foundations.every(e=>e.length===13)}function hL(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 gL(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 _L(e){let t=/^(\d+)d(\d+)([+-]\d+)?$/i.exec(e.trim());if(!t)throw Error(`bad dice expression: "${e}"`);return gL(Number(t[1]),Number(t[2])).reduce((e,t)=>e+t,Number(t[3]??0))}var vL=class{constructor(e,t){this.kept=new Set,this.count=e,this.sides=t,this.values=gL(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 yL(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 bL(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 xL(e,t,n){return jL(e,t,n)&&!AL(e,t,n)}function SL(e,t){if(!xL(e,t.x,t.y))throw Error(`tactical unit cannot be placed there`);e.units.push({...t}),e.turn||=t.owner}function CL(e,t){let n=kL(e,t);if(n.owner!==e.turn||n.actions<=0)return[];let r=FL(e,n,PL(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||AL(e,o,a))continue;let s=IL(e,n,o,a,n.actions,r);s!==null&&i.push({unit:t,x:o,y:a,cost:s})}return i}function wL(e,t){let n=CL(e,t.unit).find(e=>e.x===t.x&&e.y===t.y);if(!n)throw Error(`illegal tactical move`);let r=kL(e,t.unit);r.x=t.x,r.y=t.y,r.actions-=n.cost}function TL(e,t){let n=kL(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 EL(e,t,n){let r=kL(e,t),i=[];for(let t of[...e.units]){if(!t.overwatch||t.owner===r.owner||NL(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 DL(e,t,n,r){let i=kL(e,t),a=kL(e,n);if(i.owner!==e.turn||i.owner===a.owner)throw Error(`invalid tactical attack`);if(NL(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 OL(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 kL(e,t){let n=e.units.find(e=>e.id===t);if(!n)throw Error(`unknown tactical unit "${t}"`);return n}function AL(e,t,n){return e.units.some(e=>e.x===t&&e.y===n)}function jL(e,t,n){return t>=0&&n>=0&&t<e.width&&n<e.height}function ML(e,t,n){return e.shape===`hex`?Vt(t,n):[{x:t-1,y:n},{x:t+1,y:n},{x:t,y:n-1},{x:t,y:n+1}]}function NL(e,t,n){return e.shape===`hex`?Ht(t,n):Math.abs(t.x-n.x)+Math.abs(t.y-n.y)}function PL(e,t){return new Set(e.units.filter(n=>n.owner!==t.owner&&ML(e,t.x,t.y).some(e=>e.x===n.x&&e.y===n.y)).map(e=>e.id))}function FL(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 ML(e,i.x,i.y))r.add(`${t.x},${t.y}`);return r}function IL(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 ML(e,t.x,t.y)){let a=`${i.x},${i.y}`;!jL(e,i.x,i.y)||c.has(a)||!e.cells[i.y*e.width+i.x].passable||AL(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 LL=class{constructor(e,t){if(this.visible=new Map,this.explored=new Map,e<1||t<1)throw Error(`fog needs positive dimensions`);this.width=e,this.height=t}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)}isVisible(e,t,n){return this.visible.get(e)?.has(this.index(t,n))??!1}isExplored(e,t,n){return this.explored.get(e)?.has(this.index(t,n))??!1}visibleCells(e){return[...this.visible.get(e)??[]]}exploredCells(e){return[...this.explored.get(e)??[]]}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 RL(e){return{currency:e,pool:[]}}function zL(e,t,n,r){return e.currency<r||!xL(t,n.x,n.y)?!1:(SL(t,n),e.currency-=r,!0)}function BL(e,t,n,r,i){let a=e.pool.findIndex(e=>e.id===n);return a===-1||!xL(t,r,i)?!1:(SL(t,{...e.pool[a],x:r,y:i}),e.pool.splice(a,1),!0)}function VL(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 HL(e,t,n){return e.units.filter(e=>e.owner===t).length*(n.incomePerUnit-n.upkeepPerUnit)}function UL(e,t,n,r){return e.currency+=HL(t,n,r),e.currency}function WL(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 GL(e,t,n,r,i=!1){if(!tR(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 KL(e,t,n){return tR(e,t,n)&&iR(e,t,n)<1/0&&!nR(e,t,n)}function qL(e,t){if(!KL(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 JL(e,t){let n=eR(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||iR(e,o,a)===1/0||nR(e,o,a))continue;let s=aR(e,n,o,a,r);s!==null&&i.push({unit:t,x:o,y:a,cost:s})}return i}function YL(e,t){let n=JL(e,t.unit).find(e=>e.x===t.x&&e.y===t.y);if(!n)throw Error(`illegal skirmish move`);let r=eR(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 XL(e,t,n){let r=eR(e,t),i=eR(e,n);if(r.owner!==e.turn||r.owner===i.owner)throw Error(`invalid skirmish attack`);if(Ht(r,i)!==1)throw Error(`skirmish combat is adjacency-only`);let a=[ZL(e,r,i)];return i.hp>0&&a.push(ZL(e,i,r)),e.units=e.units.filter(e=>e.hp>0),{strikes:a}}function ZL(e,t,n){let r=rR(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 QL(e,t,n,r){return n+e.cells.filter(e=>e.village&&e.owner===t).length*r}function $L(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 eR(e,t){let n=e.units.find(e=>e.id===t);if(!n)throw Error(`unknown skirmish unit "${t}"`);return n}function tR(e,t,n){return t>=0&&n>=0&&t<e.width&&n<e.height}function nR(e,t,n){return e.units.some(e=>e.x===t&&e.y===n)}function rR(e,t,n){return e.terrainTable[e.cells[n*e.width+t].terrain]}function iR(e,t,n){return rR(e,t,n).moveCost}function aR(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 Vt(t.x,t.y)){if(!tR(e,s.x,s.y))continue;let c=iR(e,s.x,s.y);if(c===1/0||nR(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 oR=l({BoardGrid:()=>VI,DiceCup:()=>vL,FactionFog:()=>LL,addSkirmishUnit:()=>qL,addTacticalUnit:()=>SL,applyBackgammonMove:()=>iL,applyCheckersMove:()=>WI,applyMove:()=>MI,applyUpkeep:()=>UL,armyIncome:()=>HL,backgammonMoves:()=>rL,bankUnit:()=>VL,canPlaceSkirmishUnit:()=>KL,canPlaceTacticalUnit:()=>xL,checkersMoves:()=>UI,chooseMove:()=>FI,cloneChess:()=>bI,createDeck:()=>oL,deal:()=>cL,dealSolitaire:()=>uL,drawSolitaire:()=>dL,endSkirmishTurn:()=>$L,endTacticalTurn:()=>OL,gameResult:()=>NI,goResult:()=>YI,goScore:()=>XI,inCheck:()=>DI,legalMoves:()=>jI,moveSkirmishUnit:()=>YL,moveSolitaireTableau:()=>fL,moveSolitaireToFoundation:()=>pL,moveTacticalUnit:()=>wL,parseFen:()=>mI,passGo:()=>JI,playGo:()=>qI,recall:()=>BL,recruit:()=>zL,rollBackgammonDice:()=>nL,rollDice:()=>gL,rollExpression:()=>_L,scoreDice:()=>yL,search:()=>II,setSkirmishTerrain:()=>GL,setTacticalOverwatch:()=>TL,shuffleDeck:()=>sL,skirmishAttack:()=>XL,skirmishIncome:()=>QL,skirmishMoves:()=>JL,solitaireWon:()=>mL,sq:()=>fI,squareName:()=>pI,startingArmy:()=>RL,startingBackgammon:()=>tL,startingCheckers:()=>HI,startingChess:()=>yI,startingGo:()=>KI,startingSkirmish:()=>WL,startingTactics:()=>bL,tacticalAttack:()=>DL,tacticalMoves:()=>CL,trickWinner:()=>lL,triggerTacticalOverwatch:()=>EL});function sR(e){return new Audio(ok(e))}var cR=new p,lR=class{constructor(e,t={}){this.next=0;let n=Math.max(1,t.poolSize??4),r=t.create??sR;this.volume=t.volume??1,this.caption=t.caption,this.pool=Array.from({length:n},()=>r(e))}play(){let e=this.pool[this.next];this.next=(this.next+1)%this.pool.length,e.volume=this.volume,e.currentTime=0,Promise.resolve(e.play()).catch(()=>{}),this.caption&&cR.dispatch({text:this.caption})}stopAll(){for(let e of this.pool)e.pause(),e.currentTime=0}},uR=class{constructor(e={}){this.current=null,this.fades=[],this.trackQueue=null,this.playlistFade=1,this.volume=e.volume??1,this.create=e.create??sR}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))}}},dR=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 fR(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*mR(t,d,s,e)}return gR(l,o)}function pR(e={},t=e=>new Audio(e)){let n=t(fR(e));return Promise.resolve(n.play()).catch(()=>{}),n}function mR(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 hR(n,r)}}function hR(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 gR(e,t){let n=e.length*2,r=new ArrayBuffer(44+n),i=new DataView(r);_R(i,0,`RIFF`),i.setUint32(4,36+n,!0),_R(i,8,`WAVE`),_R(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),_R(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 _R(e,t,n){for(let r=0;r<n.length;r++)e.setUint8(t+r,n.charCodeAt(r))}var vR=5e5;function yR(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 bR(e){let t=[],n=new Map,r=vR,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 xR(e){return 440*2**((e-69)/12)}var SR=class{constructor(e,t={}){this.elapsed=0,this.index=0,this.playing=!1,this.notes=bR(e),this.playFn=t.play??pR,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:xR(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}},CR=l({MidiPlayer:()=>SR,Music:()=>uR,Orchestrator:()=>dR,Sound:()=>lR,createAudio:()=>sR,noteToFrequency:()=>xR,onCaption:()=>cR,parseMidi:()=>yR,playTone:()=>pR,scheduleMidi:()=>bR,synthesizeTone:()=>fR});function wR(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 TR(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 ER=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 ee;r.setState(t.random);let i=SM.restore(t.scheduler,n.actorOf);return new e({state:t.state,scheduler:i,random:r,rule:n.rule,actorId:n.actorId})}},DR=l({Scheduler:()=>SM,SimulationRuntime:()=>ER,advanceToInput:()=>wR,runScenario:()=>TR});return e.Achievements=Nt,e.ActorAnimator=Wk,Object.defineProperty(e,"Actors",{enumerable:!0,get:function(){return lF}}),e.AnimatedSprite=$O,e.Animation=QO,Object.defineProperty(e,"Audio",{enumerable:!0,get:function(){return CR}}),e.BLOB_SHAPES=Kk,e.Bar=ej,Object.defineProperty(e,"Battle",{enumerable:!0,get:function(){return dI}}),e.BitmapLabel=BA,Object.defineProperty(e,"Board",{enumerable:!0,get:function(){return oR}}),e.Button=$A,e.COLOR_BLINDNESS_MATRICES=Ok,e.Camera=Sk,e.Collection=Ot,e.ColorTransformBatcher=VO,e.DialogueStage=uj,e.EMPTY=Mk,e.Easing=Jt,e.EntityRegistry=Qt,e.FeedbackClient=It,e.FloatingText=nj,e.Game=jO,e.Generator=ee,e.Gradient=oA,e.HelpScreen=aj,e.HookRegistry=x,Object.defineProperty(e,"I18n",{enumerable:!0,get:function(){return zN}}),e.IconGrid=qA,Object.defineProperty(e,"Input",{enumerable:!0,get:function(){return ue}}),e.Label=CA,e.LayeredSprite=zk,e.ListView=KA,e.LoadQueue=Zt,e.LoadingScreen=sj,e.LockstepClient=bt,e.Logger=y,e.MessageBox=JA,e.Minimap=jk,e.NO_COLOR_ADD=XO,e.NewsClient=Tt,e.NewsSeenTracker=Dt,e.NinePatch=HA,e.Node2D=tA,e.ParticleEmitter=Hk,e.Player=At,e.PlayerInput=rt,e.PlayerStats=Ct,e.PresentationQueue=$t,e.Projectile=Bk,e.RENDERING_DECISIONS=Qk,Object.defineProperty(e,"Random",{enumerable:!0,get:function(){return S}}),e.ReactionTable=Pt,e.RebindScreen=QA,e.Recorder=kt,e.Registry=g,Object.defineProperty(e,"Resources",{enumerable:!0,get:function(){return yk}}),e.RichLabel=IA,Object.defineProperty(e,"Roguelike",{enumerable:!0,get:function(){return VM}}),Object.defineProperty(e,"Rpg",{enumerable:!0,get:function(){return QF}}),e.RunHistory=St,e.SaveSyncClient=vt,e.SaveSystem=gt,e.Scene=m,e.Scene2D=MO,e.SceneComponentHost=_,e.SceneStack=h,e.ScreenEffects=Uk,e.Session=Ft,e.Shape2D=nA,e.Signal=p,Object.defineProperty(e,"Simulation",{enumerable:!0,get:function(){return DR}}),e.Spawner=Lt,e.Sprite2D=iA,e.SpriteSheet=xk,e.StageScript=dj,e.StatsScreen=oj,e.StatusVisuals=Gk,e.TelemetryClient=wt,e.Text2D=rA,e.TileMap=Rk,e.TiledSprite=aA,e.TintedSprite=ZO,e.Toast=rj,e.Tooltip=ij,e.Tweener=Yt,e.UndoHistory=Xt,e.VerticalLabel=ZA,e.Viewport=Ek,e.Window=UA,e.WindowStack=WA,Object.defineProperty(e,"World",{enumerable:!0,get:function(){return hF}}),e.advanceReveal=bA,e.autotileFrames=Zk,e.bitmapLabelStyle=VA,e.blobIndex=Xk,e.checkNoControlCharacters=ut,e.checkSize=lt,e.completeReveal=xA,e.createCamera=Tk,e.createColorBlindnessFilter=kk,e.defaultTheme=fA,e.deserializeReplay=Mt,e.detectWebGpu=eA,e.hexDistance=Ht,e.hexLine=Wt,e.hexNeighbors=Vt,e.hexRange=Gt,e.hexToPixel=Kt,e.highContrastTheme=pA,e.importTwee=pj,e.inspectGraphicsCapabilities=$k,e.layoutVertical=XA,e.loadTiledMap=dA,e.messageBoxPresenter=cj,e.newlyRevealed=Ak,e.packColorAdd=qO,e.packTintAdd=JO,e.parseCSV=en,e.parseMarkdown=NA,e.pixelToHex=qt,e.rectOf=bk,e.registerColorTransform=KO,e.revealComplete=SA,e.sanitizeInboundText=dt,e.scramble=it,e.serializeReplay=jt,e.setTheme=gA,e.sliceSpans=FA,e.snapZoom=wk,e.splitScreenHalves=Dk,e.startReveal=yA,e.stripMarkdown=PA,e.theme=$,e.themeChanged=hA,e.tileFrame=Fk,e.tileFrameIndex=Lk,e.tileFrameSheet=Ik,e.unscramble=at,e.validateSchema=pt,e.version=f,e})({});
1338
+ `))t.startsWith(`::`)?(i(),n=WM(t),r=[]):n!==null&&r.push(t);return i(),t}function WM(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 GM(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 KM(e,t){let n=[],r=[];for(let i of t.split(`
1339
+ `)){let t=qM(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 qM(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(JM(i.slice(a+2,o),n)),i=i.slice(o+2)}}function JM(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 YM=[[0,-1],[1,0],[0,1],[-1,0]],XM=[[0,-1],[1,-1],[1,0],[1,1],[0,1],[-1,1],[-1,0],[-1,-1]],ZM=[[1,0],[1,-1],[0,-1],[-1,-1],[-1,0],[0,1]],QM=[[1,1],[1,0],[0,-1],[-1,0],[-1,1],[0,1]];function $M(e){return e===4?YM:XM}var eN={passable:!1,transparent:!1},tN={passable:!0,transparent:!0},nN=class e{constructor(e,t,n,r=0,i=`square`){this.rooms=[],this.width=e,this.shape=i,this.height=t,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`?Vt(e,t):$M(n).map(([n,r])=>({x:e+n,y:t+r}))}forEachNeighbor(e,t,n,r){let i=this.shape===`hex`?e&1?QM:ZM:$M(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)]??eN}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}))}}static fromJSON(t,n){let r=new e(n.width,n.height,t,0,n.shape);return r.terrain.set(n.terrain.slice(0,r.terrain.length)),r.rooms=n.rooms.map(e=>({...e})),r}};function rN(e){return{x:Math.floor((e.left+e.right)/2),y:Math.floor((e.top+e.bottom)/2)}}function iN(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 aN={id:`hall`,paint:(e,t,n)=>e.fillRect(t,n)};function oN(e){return Math.min(e.right-e.left+1,e.bottom-e.top+1)}function sN(e){return Math.max(e.right-e.left+1,e.bottom-e.top+1)}function cN(e,t){let n=oN(t),r=sN(t);return e.filter(e=>n>=(e.minSize??0)&&r<=(e.maxSize??1/0))}function lN(e,t){let n=cN(e,t);if(n.length===0)return null;let r=ce(n.map(e=>e.weight??1));return r===null?null:n[r]}var uN=[{passable:!1,transparent:!1},{passable:!0,transparent:!0}];function dN(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 nN(t,n,[...uN,...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=>iN(l,e,2))){g++;continue}p.push(l);let m=(d?.length?lN(d,l):null)??aN;m.paint(f,l,c),h.push(m.id),u?.onRoomPlaced?.(l,p.length-1)}for(let e=1;e<p.length;e++){pN(f,rN(p[e-1]),rN(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){pN(f,rN(p[e]),rN(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 fN(e){return dN(e).level}function pN(e,t,n,r){oe(.5)?(mN(e,t.x,n.x,t.y,!0,r),mN(e,t.y,n.y,n.x,!1,r)):(mN(e,t.y,n.y,t.x,!1,r),mN(e,t.x,n.x,n.y,!0,r))}function mN(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 hN(e,t=new Set){let n=e.passableCells().filter(e=>!t.has(e));return n.length>0?n[k(n.length)]:null}function gN(e,t){let n=null,r=-1;for(let i of e.rooms){let e=rN(i),a=(e.x-t.x)**2+(e.y-t.y)**2;a>r&&(r=a,n=i)}return n}var _N=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 vN(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 yN(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 bN(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 xN(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 SN(e,t){let n=[];return e.retries!==t.retries&&n.push({stage:`graph`,field:`retries`,expected:e.retries,actual:t.retries}),yN(e.graph,t.graph)||n.push({stage:`graph`,field:`graph`,expected:e.graph,actual:t.graph}),(e.width!==t.width||e.height!==t.height||!bN(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}),xN(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 CN(e,t=2){let n=e(),r=[];for(let i=1;i<t;i++)r.push(...SN(n,e()));return r}var wN=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)*wN,e=e*69069+1>>>0,this._s1=e*wN,e=e*69069+1>>>0,this._s2=e*wN,this._c=1,this}getUniform(){let e=2091639*this._s0+this._c*wN;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 TN=class{getContainer(){return null}setOptions(e){this._options=e}},EN=class extends TN{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 DN(e){return e.charAt(0).toUpperCase()+e.substring(1)}function ON(e,...t){let n=ON.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=DN(d)),d})}ON.map={s:`toString`};var kN=class e extends EN{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}};kN.cache=!1;var AN={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]]},jN=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=[AN[8][7],AN[8][1],AN[8][3],AN[8][5]];break;case 6:i=AN[6],a=1,o=[-1,1];break;case 8:i=AN[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}},MN=class extends jN{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)}},NN=class extends jN{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}},PN=[[-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]],FN={DiscreteShadowcasting:MN,PreciseShadowcasting:NN,RecursiveShadowcasting:class extends jN{compute(e,t,n,r){r(e,t,0,1);for(let i=0;i<PN.length;i++)this._renderOctant(e,t,PN[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,PN[o],n,i),this._renderOctant(e,t,PN[a],n,i),this._renderOctant(e,t,PN[r],n,i),this._renderOctant(e,t,PN[s],n,i)}compute90(e,t,n,r,i){i(e,t,0,1);let a=(r-1+8)%8;this._renderOctant(e,t,PN[r],n,i),this._renderOctant(e,t,PN[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 IN=class{constructor(e,t,n,r={}){this._toX=e,this._toY=t,this._passableCallback=n,this._options=Object.assign({topology:8},r),this._dirs=AN[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}},LN={Dijkstra:class extends IN{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 IN{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 RN(e,t){return Math.max(Math.abs(e.x-t.x),Math.abs(e.y-t.y))}function zN(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 BN(e,t,n){let r=zN(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 VN(e,t,n,r){return!(RN(t,n)>r.range||(r.requireLineOfSight??!0)&&!BN(e,t,n))}function HN(e,t,n){switch(n.kind){case`single`:return[t];case`line`:return zN(e,t);case`cone`:return UN(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 UN(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 WN(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=RN(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 GN(e,t,n=1){for(let n of t)if(e<=n.max)return n.multiplier;return n}function KN(e,t){return t.length===0?1:t[Math.min(e,t.length-1)]}function qN(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 JN=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 FN.PreciseShadowcasting((t,n)=>e.transparent(t,n))}update(e,t,n,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 Gt(i,n)){if(!this.level.inside(e.x,e.y))continue;let t=Wt(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 Gt(a,n)){if(!this.level.inside(e.x,e.y))continue;let t=Wt(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)||RN(a,{x:t,y:o})>n)continue;let e=zN(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)}},YN=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)}},XN=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 LN.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()}},ZN=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){this.entries.push({actor:e,time:this.now+t,sequence:this.sequence++}),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}))}}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})),r.sort(),r}sort(){this.entries.sort((e,t)=>e.time-t.time||e.sequence-t.sequence)}};function QN(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:$N(e,n,a)};let c=new JN(e);return c.update(n.x,n.y,o),c.isVisible(i.x,i.y)?r<=s?{state:`flee`,step:eP(e,n,i,a)}:{state:`hunt`,step:t.step(n,i,a)}:{state:`wander`,step:$N(e,n,a)}}function $N(e,t,n){return se(tP(e,t,n))}function eP(e,t,n,r){let i=tP(e,t,r),a=null,o=nP(t,n);for(let e of i){let t=nP(e,n);t>o&&(o=t,a=e)}return a}function tP(e,t,n){let r=n.blocked,i=[];for(let[a,o]of $M(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 nP(e,t){return(e.x-t.x)**2+(e.y-t.y)**2}var rP=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}},iP=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}},aP=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}},oP=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}},sP=class e{constructor(e,t){this.width=e,this.height=t,this.volume=new Float32Array(e*t)}volumeAt(e,t){return e<0||t<0||e>=this.width||t>=this.height?0:this.volume[t*this.width+e]}total(){let e=0;for(let t=0;t<this.volume.length;t++)e+=this.volume[t];return e}seed(e,t,n){e<0||t<0||e>=this.width||t>=this.height||(this.volume[t*this.width+e]+=n)}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 $M(4)){let a=i+t,o=n+r;a<0||o<0||a>=this.width||o>=this.height||e(a,o)&&s.push(o*this.width+a)}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}}for(let e=0;e<r.length;e++){let t=r[e]*n;this.volume[e]=t<.001?0:t}}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}},cP=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}},lP=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=>RN(e,t)<=this.radius);return n&&(this.detected=!0),n}reset(){this.detected=!1}},uP=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}},dP=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}};function fP(e,t={}){return(t.within?[...t.within]:hP(e.cellCount)).filter(n=>!(t.occupied?.has(n)||t.terrain&&!t.terrain.has(e.terrain[n])))}function pP(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 mP(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 hP(e){let t=Array(e);for(let n=0;n<e;n++)t[n]=n;return t}var gP=l({AbilityCycle:()=>oP,Blob:()=>sP,BossPhases:()=>aP,CombatHooks:()=>cP,DUNGEON_KINDS:()=>uN,Doors:()=>iP,Elevation:()=>YN,FLOOR:()=>tN,FeatureLayer:()=>_N,FieldOfView:()=>JN,Level:()=>nN,MultiStageAbility:()=>dP,Pathfinder:()=>XN,Scheduler:()=>ZN,Secrets:()=>rP,Stealth:()=>lP,TriggerTracker:()=>uP,WALL:()=>eN,areaFalloffMultiplier:()=>KN,canTarget:()=>VN,candidateCells:()=>fP,cellsNear:()=>pP,chainTargets:()=>WN,chebyshevDistance:()=>RN,checkDeterminism:()=>CN,compareDungeonArtifacts:()=>SN,coneCells:()=>UN,decideMonsterAI:()=>QN,eligibleBuilders:()=>cN,findFreeCell:()=>hN,furthestRoom:()=>gN,generateDungeon:()=>fN,generateDungeonGraph:()=>dN,hallBuilder:()=>aN,hasLineOfSight:()=>BN,knockbackPath:()=>qN,neighbourOffsets:()=>$M,pickBuilder:()=>lN,rangeMultiplier:()=>GN,rectCenter:()=>rN,rectsOverlap:()=>iN,resolveArea:()=>HN,rollRoster:()=>vN,selectDistinctCells:()=>mP,traceLine:()=>zN});function _P(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 vP=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]=_P(e[t],this.modifiersFor(t));for(let t of this.derived)e[t.name]=_P(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 yP(e,t,n){return{maxLevel:n,experienceFor:n=>n<=1?0:Math.round(e*(n-1)**t)}}var bP=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 xP(e,t,n=()=>ie(1,20)){return e+n()>=t}var SP=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}},CP=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}},wP=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,...TP(a),id:n.id,quantity:n.quantity};return i&&(o.contents=e.fromJSON(t,i)),o}),r}};function TP(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}function EP(e,t){let n=new Map;for(let e of t.ingredients)n.set(e.id,(n.get(e.id)??0)+e.quantity);for(let[t,r]of n){let n=e.find(t);if(!n||n.quantity<r)return!1}let r=t.ingredients.map(t=>({...e.find(t.id),quantity:t.quantity}));for(let n of t.ingredients)e.remove(n.id,n.quantity);if(e.add(t.result))return!0;for(let t of r)e.add(t);return!1}function DP(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 OP(e,t,n){let r=Symbol(`statusEffect`);for(let t of n.modifiers)e.addModifier({...t,source:r});return DP(t,{duration:n.duration,tick:n.tick,onExpire:()=>e.removeModifiersFrom(r)})}function kP(e){let t=e.entries.filter(e=>e.weight>0);if(t.length===0)return null;let n=ce(t.map(e=>e.weight));return n===null?null:t[n]}function AP(e){return e.affix}function jP(e,t){let n=e.affix!==void 0;e.affix=t.id,t.curse?e.cursed=!0:n&&(e.cursed=!1)}function MP(e){e.affix!==void 0&&(e.cursed=!1),delete e.affix}function NP(e,t){if(e.affix===void 0){MP(t);return}t.affix=e.affix,t.cursed=e.cursed??!1}function PP(e,t){return!(e.trigger!==t.trigger||e.kinds&&(t.kind===void 0||!e.kinds.includes(t.kind)))}function FP(e){e.identified=!0}function IP(e,t,n=`keep`){return Number.isFinite(t)?(e.level=(e.level??0)+t,n===`remove`&&MP(e),e.level):e.level??0}function LP(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 RP(e,t){e.maxDurability!==void 0&&(!Number.isFinite(t)||t<=0||(e.durability=Math.min(e.maxDurability,(e.durability??e.maxDurability)+t)))}function zP(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 DP(t,{duration:n.duration,tick:n.tick,onExpire:()=>{for(let[t,n]of r)e[t]=n}})}var BP=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 VP(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 HP=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 UP(e,t){return t.map(t=>({stat:t.stat,op:t.op,value:t.base+t.perLevel*e}))}function WP(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 GP=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=WP(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 KP(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 qP(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 JP(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 YP(e){let t=new Map;for(let n of e)t.set(n.stat,(t.get(n.stat)??0)+n.amount);return t}function XP(e,t){return[...YP(JP(t))].every(([t,n])=>e.base(t)>=n)}function ZP(e,t){let n=YP(JP(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 QP(e,t,n=1){for(let[r,i]of YP(JP(t)))e.setBase(r,e.base(r)+i*n)}function $P(e,t,n,r){return ZP(e,t)?n.refund(Math.floor(t.amount/r)):0}var eF=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 tF(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 nF=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)}}},rF=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(iF(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=iF(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=iF(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 iF(e,t){return[e,t].sort().join(`\0`)}var aF=new Set([`id`,`growth`,`level`,`startingAffix`,`startingItem`,`lowHpReaction`]);function oF(e,t={},n){let r=new vP({base:dF(e)}),i;e.growth!==void 0&&(i=new bP(uF(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}"`);jP(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 Pt,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 sF(e,t={},n){return e.map(e=>oF(e,t,n))}function cF(e){let t={stats:e.stats.toJSON()};return e.progression&&(t.progression=e.progression.toJSON()),e.item&&(t.item=e.item),t}function lF(e,t,n,r){let i=oF(e,t,r);if(i.stats=vP.fromJSON({base:dF(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=bP.fromJSON(uF(e,t),n.progression)}return n.item!==void 0&&(i.item=n.item),i}function uF(e,t){let n=t.growthCurves?.[e.growth??``];if(!n)throw Error(`entity template "${e.id}": unknown growth curve "${e.growth}"`);return n}function dF(e){let t={};for(let[n,r]of Object.entries(e))if(!aF.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 fF=l({Advancement:()=>HP,Appearances:()=>GP,AuraField:()=>nF,Barrier:()=>eF,Charges:()=>BP,EquipmentSlots:()=>CP,Inventory:()=>wP,Progression:()=>bP,SkillPoints:()=>SP,StatBlock:()=>vP,SupportLedger:()=>rF,affixOf:()=>AP,applyAffix:()=>jP,applyItemStatusEffect:()=>zP,applyStatusEffect:()=>OP,assignAppearances:()=>WP,assignTraits:()=>tF,buildEntities:()=>sF,buildEntity:()=>oF,buy:()=>KP,canAfford:()=>XP,convertToCharges:()=>$P,copyAffix:()=>NP,craft:()=>EP,damageItem:()=>LP,enchant:()=>IP,fromEntitySaveState:()=>lF,identify:()=>FP,matchesContext:()=>PP,powerCurve:()=>yP,refund:()=>QP,removeAffix:()=>MP,repairItem:()=>RP,rollAffix:()=>kP,rollLoot:()=>VP,scaledModifiers:()=>UP,sell:()=>qP,skillCheck:()=>xP,spend:()=>ZP,toEntitySaveState:()=>cF}),pF=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)}},mF=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()]}},hF=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 gF(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 _F=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})}},vF=l({EnvironmentClock:()=>_F,Overworld:()=>mF,TurnClock:()=>hF,World:()=>pF,rollEncounter:()=>gF});function yF(e,t,n={}){let r=n.pick??k,i=0;return t.forEach((t,n)=>{bF(t,t.name??`#${n+1}`);let a=xF(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 bF(e,t){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 n=e.width*e.height;for(let[r,i]of Object.entries(e.input))if(i.length!==n)throw Error(`automap rule "${t}" input "${r}" has ${i.length} cells, but the pattern is ${n}`);e.outputs.forEach((e,r)=>{for(let[i,a]of Object.entries(e))if(a.length!==n)throw Error(`automap rule "${t}" output ${r+1} "${i}" has ${a.length} cells, but the pattern is ${n}`)})}function xF(e,t){let n=[];for(let r=0;r+t.height<=e.heightInTiles;r++)for(let i=0;i+t.width<=e.widthInTiles;i++)SF(e,t,i,r)&&n.push([i,r]);return n}function SF(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 CF=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 wF(e,t){return`switch`in e?t.switch(e.switch)===e.equals:t.variable(e.variable)>=e.atLeast}function TF(e,t){let n;for(let r of e.pages)(r.conditions??[]).every(e=>wF(e,t))&&(n=r);return n}var EF=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=wF(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 DF(e,t){t&&e.has?.(t)&&e.play?.(t)}var OF=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=kF(e,t),this.playIdle())}moveBy(e,t){return!this.target&&(this.facing=kF(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=AF(this.fromX,this.target.x,this.progress)*this.tileWidth,this.sprite.y=AF(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(){DF(this.sprite,this.options.walkAnimation?.(this.facing))}playIdle(){DF(this.sprite,this.options.idleAnimation?.(this.facing))}};function kF(e,t){return e>0?`right`:e<0?`left`:t>0?`down`:`up`}function AF(e,t,n){return e+(t-e)*n}var jF=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(){DF(this.sprite,this.options.walkAnimation?.(this.facing))}playIdle(){DF(this.sprite,this.options.idleAnimation?.(this.facing))}};function MF(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 NF(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 PF(e,t){let n=LF(e.x,t.x,t.x+t.width),r=LF(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 FF(e,t,n,r){let{tileSize:i,isSolid:a}=r;if(!(i>0))throw Error(`collision tileSize must be positive`);let o=IF(e.x,e.y,e.width,e.height,t,i,a,!0);return{x:o,y:IF(o,e.y,e.width,e.height,n,i,a,!1)}}function IF(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 LF(e,t,n){return e<t?t:e>n?n:e}var RF=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?wF(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 zF(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(BF(e.id,r))}return t.map(e=>n.get(e))}function BF(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 VF=class{constructor(e){this.name=e}},HF=4,UF=8,WF=new WeakMap;function GF(e){return WF.get(e)}function KF(e,t){return WF.set(e,t),e}var qF=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&&WF.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!==HF||t>UF)throw Error(`Marshal: unsupported version ${e}.${t} (expected ${HF}.${UF} or lower)`);return this.readValue()}};function JF(e){return new qF(e).readDocument()}function YF(e){return typeof e==`object`&&!!e&&`class`in e&&`ivars`in e}function XF(e){let t=[HF,UF];return ZF(t,e),new Uint8Array(t)}function ZF(e,t){if(t==null)e.push(QF(`0`));else if(t===!0)e.push(QF(`T`));else if(t===!1)e.push(QF(`F`));else if(t instanceof VF)e.push(QF(`:`)),$F(e,t.name);else if(typeof t==`number`)Number.isInteger(t)&&Math.abs(t)<2**30?(e.push(QF(`i`)),eI(e,t)):(e.push(QF(`f`)),$F(e,Number.isFinite(t)?String(t):t>0?`inf`:t<0?`-inf`:`nan`));else if(typeof t==`string`)e.push(QF(`"`)),$F(e,t);else if(Array.isArray(t)){e.push(QF(`[`)),eI(e,t.length);for(let n of t)ZF(e,n)}else if(t instanceof Map){let n=WF.has(t);e.push(QF(n?`}`:`{`)),eI(e,t.size);for(let[n,r]of t)ZF(e,n),ZF(e,r);n&&ZF(e,WF.get(t))}else if(YF(t)){e.push(QF(`o`)),e.push(QF(`:`)),$F(e,t.class);let n=Object.entries(t.ivars);eI(e,n.length);for(let[t,r]of n)e.push(QF(`:`)),$F(e,t),ZF(e,r)}else throw Error(`Marshal: cannot encode a value of type ${typeof t}`)}function QF(e){return e.charCodeAt(0)}function $F(e,t){let n=new TextEncoder().encode(t);eI(e,n.length);for(let t of n)e.push(t)}function eI(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 tI=l({AUTOMAP_EMPTY:()=>-1,EventRunner:()=>EF,FreeMover:()=>jF,GameState:()=>CF,GridMover:()=>OF,QuestLog:()=>RF,RubySymbol:()=>VF,aabbOverlap:()=>MF,activePage:()=>TF,automap:()=>yF,circleAabbOverlap:()=>PF,circleOverlap:()=>NF,conditionHolds:()=>wF,decodeMarshal:()=>JF,encodeMarshal:()=>XF,hashDefaultOf:()=>GF,questsFromRows:()=>zF,resolveAabbAgainstTiles:()=>FF,withHashDefault:()=>KF}),nI=yP(20,2,100),rI=class{constructor(e){this.species=e.species,this.deriveStats=e.deriveStats,this.progression=new bP(e.species.growth??nI,{level:e.level??1}),this.stats=new vP({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}}},iI=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)}},aI=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 oI(e){return[...e].sort((e,t)=>(t.priority??0)-(e.priority??0)||t.speed-e.speed)}function sI(e,t){let n=null;for(let r of e)r.at(t)&&(n=r.into);return n}var cI=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 lI(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 uI(e,t,n,r){let i=null,a=dI(e,n,r);return t.forEach((e,t)=>{let o=dI(e.types,n,r);o<a&&(a=o,i=t)}),i}function dI(e,t,n){return Math.max(...n.map(n=>t.multiplierFor(n,e)))}var fI=class extends x{},pI=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))}},mI=l({BattleHooks:()=>fI,Creature:()=>rI,Field:()=>pI,Party:()=>aI,StatStages:()=>cI,TypeMatrix:()=>iI,battleOrder:()=>oI,checkEvolution:()=>sI,chooseMove:()=>lI,chooseSwitch:()=>uI});function hI(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 gI(e){return String.fromCharCode(97+(e&7))+String.fromCharCode(49+(e>>3))}function _I(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:hI(t[3]);if(a!==null){let n=t[1]===`w`?5:2;if(bI(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 kI(n,`white`),kI(n,`black`),o}function vI(e){return e===`white`?`black`:`white`}function yI(e){return e&7}function bI(e){return e>>3}function xI(e,t){return e>=0&&e<8&&t>=0&&t<8}function SI(){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 CI(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 wI=[[1,2],[2,1],[2,-1],[1,-2],[-1,-2],[-2,-1],[-2,1],[-1,2]],TI=[[1,0],[1,1],[0,1],[-1,1],[-1,0],[-1,-1],[0,-1],[1,-1]],EI=[[1,1],[-1,1],[-1,-1],[1,-1]],DI=[[1,0],[0,1],[-1,0],[0,-1]];function OI(e,t,n){let r=yI(t),i=bI(t),a=n===`white`?i-1:i+1;for(let t of[-1,1]){if(!xI(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 wI){if(!xI(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 TI){if(!xI(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:EI,kinds:[`bishop`,`queen`]},{steps:DI,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(;xI(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 kI(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 AI(e,t){return OI(e.board,kI(e.board,t),vI(t))}function jI(e,t){let n=e.board[t];if(!n||n.side!==e.turn)return[];let r=[],i=yI(t),a=bI(t),o=o=>{for(let[s,c]of o){let o=i+s,l=a+c;for(;xI(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(xI(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(!xI(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 wI){if(!xI(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(EI);break;case`rook`:o(DI);break;case`queen`:o(EI),o(DI);break;case`king`:{for(let[o,s]of TI){if(!xI(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&&!AI(e,n.side)&&(s.king&&!e.board[o+5]&&!e.board[o+6]&&!OI(e.board,o+5,vI(n.side))&&!OI(e.board,o+6,vI(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]&&!OI(e.board,o+3,vI(n.side))&&!OI(e.board,o+2,vI(n.side))&&r.push({from:t,to:o+2,castle:`queenside`}));break}}return r}function MI(e,t){let n=e.board[t.from];if(!n)throw Error(`no piece on ${gI(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[NI(n.side,t.from)]=!1);let i=e.board[t.to];if(i&&i.kind===`rook`&&r(i.side,t.to)&&(e.castling[NI(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=vI(n.side)}function NI(e,t){let n=yI(t)===7;return e===`white`?n?`whiteKingside`:`whiteQueenside`:n?`blackKingside`:`blackQueenside`}function PI(e){let t=[];for(let n=0;n<64;n++)if(!(!e.board[n]||e.board[n]?.side!==e.turn))for(let r of jI(e,n)){let n=CI(e);MI(n,r),!AI(n,e.turn)&&t.push({from:r.from,to:r.to,...r.promotion?{promotion:r.promotion}:{}})}return t}function FI(e,t){let n=e.board[t.from];if(!n||n.side!==e.turn)throw Error(`no ${e.turn} piece on ${gI(t.from)} to move`);let r=jI(e,t.from).find(e=>e.to===t.to&&(e.promotion??null)===(t.promotion??null));if(!r)throw Error(`${gI(t.from)}-${gI(t.to)} is not a legal move here`);let i=CI(e);if(MI(i,r),AI(i,e.turn))throw Error(`${gI(t.from)}-${gI(t.to)} leaves the king in check`);MI(e,r)}function II(e){return PI(e).length>0?`ongoing`:AI(e,e.turn)?e.turn===`white`?`black-wins`:`white-wins`:`stalemate`}var LI={pawn:100,knight:320,bishop:330,rook:500,queen:900,king:0};function RI(e,t={}){return zI(e,t).move}function zI(e,t={}){let n=Math.max(1,Math.floor(t.depth??3)),r=t.maxNodes===void 0?1/0:Math.max(1,Math.floor(t.maxNodes)),i=HI(e,PI(e));if(i.length===0)return{move:null,score:VI(e,0),nodes:1};let a=0,o=i[0],s=-1/0,c=-1/0;for(let t of i){if(a>=r)break;let i=CI(e);FI(i,t);let u=-l(i,n-1,-1/0,-c,1);u>s&&(s=u,o=t),c=Math.max(c,u)}return{move:o,score:s,nodes:a};function l(e,t,n,i,o){if(a>=r)return BI(e);if(a++,II(e)!==`ongoing`)return VI(e,o);if(t===0)return BI(e);let s=-1/0;for(let r of HI(e,PI(e))){let a=CI(e);if(FI(a,r),s=Math.max(s,-l(a,t-1,-i,-n,o+1)),n=Math.max(n,s),n>=i)break}return s}}function BI(e){let t=0;for(let n of e.board)n&&(t+=(n.side===`white`?1:-1)*LI[n.kind]);return e.turn===`white`?t:-t}function VI(e,t){return AI(e,e.turn)?-1e5+t:0}function HI(e,t){return t.slice().sort((t,n)=>UI(e,n)-UI(e,t))}function UI(e,t){let n=e.board[t.to];return(t.promotion?LI[t.promotion]:0)*10+(n?LI[n.kind]:0)}var WI=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 GI(){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 KI(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=>JI(e,t,!0));return n.length>0?n:e.forcedFrom===null?t.flatMap(t=>JI(e,t,!1)):[]}function qI(e,t){if(!KI(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||JI(i,t.to,!0).length===0?(e.turn=e.turn===`red`?`black`:`red`,e.forcedFrom=null):e.forcedFrom=t.to}function JI(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 YI(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 XI(e,t,n){let r=eL(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 tL(e,r)){if(i[t]!==a||rL(i,e.size,t)!==0)continue;let n=nL(i,e.size,t);n.length===1&&(s=n[0]);for(let e of n)i[e]=null;o+=n.length}if(rL(i,e.size,r)===0)throw Error(`suicide is not a legal Go move`);e.ko=o===1&&rL(i,e.size,r)===1?s:null,e.board=i,e.turn=a,e.passes=0}function ZI(e){e.turn=e.turn===`black`?`white`:`black`,e.ko=null,e.passes++}function QI(e){return e.passes>=2?`finished`:`ongoing`}function $I(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=nL(e.board,e.size,r),a=new Set;for(let t of i)for(let n of tL(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 eL(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 tL(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 nL(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 rL(e,t,n){let r=nL(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 iL(){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 aL(){let e=yL(2,6);return e[0]===e[1]?[...e,...e]:e}function oL(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;cL(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}):cL(e,a,n)&&r.push({from:t,to:a,die:i})}}return r}function sL(e,t){if(!oL(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 cL(e,t,n){return e.points[t]*n>=-1}function lL(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 uL(e){return le(e)}function dL(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 fL(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 pL(e){let t=lL();return e===void 0?uL(t):ne(e,()=>uL(t)),{stock:t,waste:[],tableau:Array.from({length:7},(e,n)=>({down:t.splice(0,6-n),up:t.splice(0,1)})),foundations:[[],[],[],[]]}}function mL(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 hL(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:!vL(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 gL(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 _L(e){return e.foundations.every(e=>e.length===13)}function vL(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 yL(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 bL(e){let t=/^(\d+)d(\d+)([+-]\d+)?$/i.exec(e.trim());if(!t)throw Error(`bad dice expression: "${e}"`);return yL(Number(t[1]),Number(t[2])).reduce((e,t)=>e+t,Number(t[3]??0))}var xL=class{constructor(e,t){this.kept=new Set,this.count=e,this.sides=t,this.values=yL(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 SL(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 CL(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 wL(e,t,n){return PL(e,t,n)&&!NL(e,t,n)}function TL(e,t){if(!wL(e,t.x,t.y))throw Error(`tactical unit cannot be placed there`);e.units.push({...t}),e.turn||=t.owner}function EL(e,t){let n=ML(e,t);if(n.owner!==e.turn||n.actions<=0)return[];let r=RL(e,n,LL(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||NL(e,o,a))continue;let s=zL(e,n,o,a,n.actions,r);s!==null&&i.push({unit:t,x:o,y:a,cost:s})}return i}function DL(e,t){let n=EL(e,t.unit).find(e=>e.x===t.x&&e.y===t.y);if(!n)throw Error(`illegal tactical move`);let r=ML(e,t.unit);r.x=t.x,r.y=t.y,r.actions-=n.cost}function OL(e,t){let n=ML(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 kL(e,t,n){let r=ML(e,t),i=[];for(let t of[...e.units]){if(!t.overwatch||t.owner===r.owner||IL(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 AL(e,t,n,r){let i=ML(e,t),a=ML(e,n);if(i.owner!==e.turn||i.owner===a.owner)throw Error(`invalid tactical attack`);if(IL(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 jL(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 ML(e,t){let n=e.units.find(e=>e.id===t);if(!n)throw Error(`unknown tactical unit "${t}"`);return n}function NL(e,t,n){return e.units.some(e=>e.x===t&&e.y===n)}function PL(e,t,n){return t>=0&&n>=0&&t<e.width&&n<e.height}function FL(e,t,n){return e.shape===`hex`?Vt(t,n):[{x:t-1,y:n},{x:t+1,y:n},{x:t,y:n-1},{x:t,y:n+1}]}function IL(e,t,n){return e.shape===`hex`?Ht(t,n):Math.abs(t.x-n.x)+Math.abs(t.y-n.y)}function LL(e,t){return new Set(e.units.filter(n=>n.owner!==t.owner&&FL(e,t.x,t.y).some(e=>e.x===n.x&&e.y===n.y)).map(e=>e.id))}function RL(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 FL(e,i.x,i.y))r.add(`${t.x},${t.y}`);return r}function zL(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 FL(e,t.x,t.y)){let a=`${i.x},${i.y}`;!PL(e,i.x,i.y)||c.has(a)||!e.cells[i.y*e.width+i.x].passable||NL(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 BL=class{constructor(e,t){if(this.visible=new Map,this.explored=new Map,e<1||t<1)throw Error(`fog needs positive dimensions`);this.width=e,this.height=t}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)}isVisible(e,t,n){return this.visible.get(e)?.has(this.index(t,n))??!1}isExplored(e,t,n){return this.explored.get(e)?.has(this.index(t,n))??!1}visibleCells(e){return[...this.visible.get(e)??[]]}exploredCells(e){return[...this.explored.get(e)??[]]}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 VL(e){return{currency:e,pool:[]}}function HL(e,t,n,r){return e.currency<r||!wL(t,n.x,n.y)?!1:(TL(t,n),e.currency-=r,!0)}function UL(e,t,n,r,i){let a=e.pool.findIndex(e=>e.id===n);return a===-1||!wL(t,r,i)?!1:(TL(t,{...e.pool[a],x:r,y:i}),e.pool.splice(a,1),!0)}function WL(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 GL(e,t,n){return e.units.filter(e=>e.owner===t).length*(n.incomePerUnit-n.upkeepPerUnit)}function KL(e,t,n,r){return e.currency+=GL(t,n,r),e.currency}function qL(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 JL(e,t,n,r,i=!1){if(!iR(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 YL(e,t,n){return iR(e,t,n)&&sR(e,t,n)<1/0&&!aR(e,t,n)}function XL(e,t){if(!YL(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 ZL(e,t){let n=rR(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||sR(e,o,a)===1/0||aR(e,o,a))continue;let s=cR(e,n,o,a,r);s!==null&&i.push({unit:t,x:o,y:a,cost:s})}return i}function QL(e,t){let n=ZL(e,t.unit).find(e=>e.x===t.x&&e.y===t.y);if(!n)throw Error(`illegal skirmish move`);let r=rR(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 $L(e,t,n){let r=rR(e,t),i=rR(e,n);if(r.owner!==e.turn||r.owner===i.owner)throw Error(`invalid skirmish attack`);if(Ht(r,i)!==1)throw Error(`skirmish combat is adjacency-only`);let a=[eR(e,r,i)];return i.hp>0&&a.push(eR(e,i,r)),e.units=e.units.filter(e=>e.hp>0),{strikes:a}}function eR(e,t,n){let r=oR(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 tR(e,t,n,r){return n+e.cells.filter(e=>e.village&&e.owner===t).length*r}function nR(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 rR(e,t){let n=e.units.find(e=>e.id===t);if(!n)throw Error(`unknown skirmish unit "${t}"`);return n}function iR(e,t,n){return t>=0&&n>=0&&t<e.width&&n<e.height}function aR(e,t,n){return e.units.some(e=>e.x===t&&e.y===n)}function oR(e,t,n){return e.terrainTable[e.cells[n*e.width+t].terrain]}function sR(e,t,n){return oR(e,t,n).moveCost}function cR(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 Vt(t.x,t.y)){if(!iR(e,s.x,s.y))continue;let c=sR(e,s.x,s.y);if(c===1/0||aR(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 lR=l({BoardGrid:()=>WI,DiceCup:()=>xL,FactionFog:()=>BL,addSkirmishUnit:()=>XL,addTacticalUnit:()=>TL,applyBackgammonMove:()=>sL,applyCheckersMove:()=>qI,applyMove:()=>FI,applyUpkeep:()=>KL,armyIncome:()=>GL,backgammonMoves:()=>oL,bankUnit:()=>WL,canPlaceSkirmishUnit:()=>YL,canPlaceTacticalUnit:()=>wL,checkersMoves:()=>KI,chooseMove:()=>RI,cloneChess:()=>CI,createDeck:()=>lL,deal:()=>dL,dealSolitaire:()=>pL,drawSolitaire:()=>mL,endSkirmishTurn:()=>nR,endTacticalTurn:()=>jL,gameResult:()=>II,goResult:()=>QI,goScore:()=>$I,inCheck:()=>AI,legalMoves:()=>PI,moveSkirmishUnit:()=>QL,moveSolitaireTableau:()=>hL,moveSolitaireToFoundation:()=>gL,moveTacticalUnit:()=>DL,parseFen:()=>_I,passGo:()=>ZI,playGo:()=>XI,recall:()=>UL,recruit:()=>HL,rollBackgammonDice:()=>aL,rollDice:()=>yL,rollExpression:()=>bL,scoreDice:()=>SL,search:()=>zI,setSkirmishTerrain:()=>JL,setTacticalOverwatch:()=>OL,shuffleDeck:()=>uL,skirmishAttack:()=>$L,skirmishIncome:()=>tR,skirmishMoves:()=>ZL,solitaireWon:()=>_L,sq:()=>hI,squareName:()=>gI,startingArmy:()=>VL,startingBackgammon:()=>iL,startingCheckers:()=>GI,startingChess:()=>SI,startingGo:()=>YI,startingSkirmish:()=>qL,startingTactics:()=>CL,tacticalAttack:()=>AL,tacticalMoves:()=>EL,trickWinner:()=>fL,triggerTacticalOverwatch:()=>kL});function uR(e){return new Audio(ok(e))}var dR=new p,fR=class{constructor(e,t={}){this.next=0;let n=Math.max(1,t.poolSize??4),r=t.create??uR;this.volume=t.volume??1,this.caption=t.caption,this.pool=Array.from({length:n},()=>r(e))}play(){let e=this.pool[this.next];this.next=(this.next+1)%this.pool.length,e.volume=this.volume,e.currentTime=0,Promise.resolve(e.play()).catch(()=>{}),this.caption&&dR.dispatch({text:this.caption})}stopAll(){for(let e of this.pool)e.pause(),e.currentTime=0}},pR=class{constructor(e={}){this.current=null,this.fades=[],this.trackQueue=null,this.playlistFade=1,this.volume=e.volume??1,this.create=e.create??uR}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))}}},mR=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 hR(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*_R(t,d,s,e)}return yR(l,o)}function gR(e={},t=e=>new Audio(e)){let n=t(hR(e));return Promise.resolve(n.play()).catch(()=>{}),n}function _R(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 vR(n,r)}}function vR(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 yR(e,t){let n=e.length*2,r=new ArrayBuffer(44+n),i=new DataView(r);bR(i,0,`RIFF`),i.setUint32(4,36+n,!0),bR(i,8,`WAVE`),bR(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),bR(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 bR(e,t,n){for(let r=0;r<n.length;r++)e.setUint8(t+r,n.charCodeAt(r))}var xR=5e5;function SR(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 CR(e){let t=[],n=new Map,r=xR,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 wR(e){return 440*2**((e-69)/12)}var TR=class{constructor(e,t={}){this.elapsed=0,this.index=0,this.playing=!1,this.notes=CR(e),this.playFn=t.play??gR,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:wR(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}},ER=l({MidiPlayer:()=>TR,Music:()=>pR,Orchestrator:()=>mR,Sound:()=>fR,createAudio:()=>uR,noteToFrequency:()=>wR,onCaption:()=>dR,parseMidi:()=>SR,playTone:()=>gR,scheduleMidi:()=>CR,synthesizeTone:()=>hR});function DR(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 OR(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 kR=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 ee;r.setState(t.random);let i=ZN.restore(t.scheduler,n.actorOf);return new e({state:t.state,scheduler:i,random:r,rule:n.rule,actorId:n.actorId})}},AR=l({Scheduler:()=>ZN,SimulationRuntime:()=>kR,advanceToInput:()=>DR,runScenario:()=>OR});return e.Achievements=Nt,e.ActorAnimator=Wk,Object.defineProperty(e,"Actors",{enumerable:!0,get:function(){return fF}}),e.AnimatedSprite=$O,e.Animation=QO,Object.defineProperty(e,"Audio",{enumerable:!0,get:function(){return ER}}),e.BLOB_SHAPES=Kk,e.Bar=kM,Object.defineProperty(e,"Battle",{enumerable:!0,get:function(){return mI}}),e.BitmapLabel=BA,Object.defineProperty(e,"Board",{enumerable:!0,get:function(){return lR}}),e.Button=OM,e.COLOR_BLINDNESS_MATRICES=Ok,e.Camera=Sk,e.Collection=Ot,e.ColorTransformBatcher=VO,e.DialogueStage=zM,e.EMPTY=Mk,e.Easing=Jt,e.EntityRegistry=Qt,e.FeedbackClient=It,e.FloatingText=jM,e.Game=jO,e.Generator=ee,e.Gradient=oA,e.HelpScreen=PM,e.HookRegistry=x,Object.defineProperty(e,"I18n",{enumerable:!0,get:function(){return Jj}}),e.IconGrid=qA,Object.defineProperty(e,"Input",{enumerable:!0,get:function(){return ue}}),e.Label=CA,e.LayeredSprite=zk,e.ListView=KA,e.LoadQueue=Zt,e.LoadingScreen=IM,e.LockstepClient=bt,e.Logger=y,e.MessageBox=CM,e.Minimap=jk,e.NO_COLOR_ADD=XO,e.NewsClient=Tt,e.NewsSeenTracker=Dt,e.NinePatch=HA,e.Node2D=tA,e.ParticleEmitter=Hk,e.Player=At,e.PlayerInput=rt,e.PlayerStats=Ct,e.PresentationQueue=$t,e.Projectile=Bk,e.RENDERING_DECISIONS=Qk,Object.defineProperty(e,"Random",{enumerable:!0,get:function(){return S}}),e.ReactionTable=Pt,e.RebindScreen=DM,e.Recorder=kt,e.Registry=g,Object.defineProperty(e,"Resources",{enumerable:!0,get:function(){return yk}}),e.RichLabel=IA,Object.defineProperty(e,"Roguelike",{enumerable:!0,get:function(){return gP}}),Object.defineProperty(e,"Rpg",{enumerable:!0,get:function(){return tI}}),e.RunHistory=St,e.SaveSyncClient=vt,e.SaveSystem=gt,e.Scene=m,e.Scene2D=MO,e.SceneComponentHost=_,e.SceneStack=h,e.ScreenEffects=Uk,e.Session=Ft,e.Shape2D=nA,e.Signal=p,Object.defineProperty(e,"Simulation",{enumerable:!0,get:function(){return AR}}),e.Spawner=Lt,e.Sprite2D=iA,e.SpriteSheet=xk,e.StageScript=BM,e.StatsScreen=FM,e.StatusVisuals=Gk,e.TelemetryClient=wt,e.Text2D=rA,e.TileMap=Rk,e.TiledSprite=aA,e.TintedSprite=ZO,e.Toast=MM,e.Tooltip=NM,e.Tweener=Yt,e.UndoHistory=Xt,e.VerticalLabel=EM,e.Viewport=Ek,e.Window=UA,e.WindowStack=WA,Object.defineProperty(e,"World",{enumerable:!0,get:function(){return vF}}),e.advanceReveal=bA,e.autotileFrames=Zk,e.bitmapLabelStyle=VA,e.blobIndex=Xk,e.checkNoControlCharacters=ut,e.checkSize=lt,e.completeReveal=xA,e.createCamera=Tk,e.createColorBlindnessFilter=kk,e.defaultTheme=fA,e.deserializeReplay=Mt,e.detectWebGpu=eA,e.hexDistance=Ht,e.hexLine=Wt,e.hexNeighbors=Vt,e.hexRange=Gt,e.hexToPixel=Kt,e.highContrastTheme=pA,e.importTwee=HM,e.inspectGraphicsCapabilities=$k,e.layoutVertical=TM,e.loadTiledMap=dA,e.messageBoxPresenter=LM,e.newlyRevealed=Ak,e.packColorAdd=qO,e.packTintAdd=JO,e.parseCSV=en,e.parseMarkdown=NA,e.pixelToHex=qt,e.rectOf=bk,e.registerColorTransform=KO,e.revealComplete=SA,e.sanitizeInboundText=dt,e.scramble=it,e.serializeReplay=jt,e.setTheme=gA,e.sliceSpans=FA,e.snapZoom=wk,e.splitScreenHalves=Dk,e.startReveal=yA,e.stripMarkdown=PA,e.theme=$,e.themeChanged=hA,e.tileFrame=Fk,e.tileFrameIndex=Lk,e.tileFrameSheet=Ik,e.unscramble=at,e.validateSchema=pt,e.version=f,e})({});