@utsp/core 0.14.0 → 0.14.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/benchmark.cjs +10 -5
- package/dist/benchmark.d.ts +157 -30
- package/dist/benchmark.mjs +10 -5
- package/dist/index.cjs +10 -5
- package/dist/index.d.ts +210 -55
- package/dist/index.mjs +10 -5
- package/package.json +2 -2
package/dist/index.mjs
CHANGED
|
@@ -1,10 +1,15 @@
|
|
|
1
|
-
var Q=Object.defineProperty;var Vn=Object.getOwnPropertyDescriptor;var Hn=Object.getOwnPropertyNames;var _n=Object.prototype.hasOwnProperty;var Nn=(h,e,t)=>e in h?Q(h,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):h[e]=t;var y=(h,e)=>Q(h,"name",{value:e,configurable:!0}),ee=(h=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(h,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):h)(function(h){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+h+'" is not supported')});var z=(h,e)=>()=>(h&&(e=h(h=0)),e);var te=(h,e)=>{for(var t in e)Q(h,t,{get:e[t],enumerable:!0})},Yn=(h,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Hn(e))!_n.call(h,n)&&n!==t&&Q(h,n,{get:()=>e[n],enumerable:!(r=Vn(e,n))||r.enumerable});return h};var re=h=>Yn(Q({},"__esModule",{value:!0}),h);var b=(h,e,t)=>(Nn(h,typeof e!="symbol"?e+"":e,t),t);var Pe,So,B,ke,Io,Oo,wo,Er,Pr,kr,Rr,Br,zr,Tr,Fr,Lr,Dr,Vr,Hr,_r,Nr,Yr,Xr,Wr,Gr,$r,Zr,jr,Jr,qr,Kr,Qr,en,tn,rn,nn,on,an,sn,Uo,vo,Mo,Ao,nt,ot,Eo,dn,it,at,st,dt,ct,lt,W=z(()=>{"use strict";Pe=256,So=65536,B=255,ke=y(h=>h?2:1,"charCodeByteSize"),Io=9,Oo=5,wo=13,Er=6,Pr=6,kr=6,Rr=7,Br=5,zr=3,Tr=1,Fr=6,Lr=4,Dr=5,Vr=2,Hr=8,_r=7,Nr=7,Yr=8,Xr=10,Wr=6,Gr=3,$r=9,Zr=15,jr=51,Jr=5,qr=6,Kr=4,Qr=3,en=3,tn=4,rn=5,nn=4,on=2,an=5,sn=5,Uo=2,vo=3,Mo=2,Ao=2,nt=5,ot=5,Eo=4,dn=3,it=8,at=6,st=3,dt=8,ct=3,lt=4});var cn,ln=z(()=>{"use strict";cn=(o=>(o[o.Rectangle=1]="Rectangle",o[o.Circle=2]="Circle",o[o.Line=3]="Line",o[o.Ellipse=4]="Ellipse",o[o.Triangle=5]="Triangle",o))(cn||{})});function Gn(h){return h>=1&&h<=3}function $n(h){return h>=1&&h<=4}function Zn(h){switch(h){case 1:return"CreateInstance";case 2:return"UpdateInstance";case 3:return"RemoveInstance";default:return`Unknown(0x${h.toString(16)})`}}function jn(h){switch(h){case 1:return"Click";case 2:return"Change";case 3:return"Submit";case 4:return"Select";default:return`Unknown(0x${h.toString(16)})`}}var un,pn,mn=z(()=>{"use strict";un=(r=>(r[r.CreateInstance=1]="CreateInstance",r[r.UpdateInstance=2]="UpdateInstance",r[r.RemoveInstance=3]="RemoveInstance",r))(un||{}),pn=(n=>(n[n.Click=1]="Click",n[n.Change=2]="Change",n[n.Submit=3]="Submit",n[n.Select=4]="Select",n))(pn||{});y(Gn,"isValidMacroOrderType");y($n,"isValidMacroEventType");y(Zn,"getMacroOrderTypeName");y(jn,"getMacroEventTypeName")});var H,f,L=z(()=>{"use strict";H=class H{constructor(e){b(this,"data");b(this,"view");this.data=new Uint8Array(e),this.view=new DataView(this.data.buffer)}static from(e){let t=new H(0);return t.data=e,t.view=new DataView(e.buffer,e.byteOffset,e.byteLength),t}static allocUnsafe(e){return new H(e)}get length(){return this.data.length}toUint8Array(){return this.data}readUInt8(e){return this.view.getUint8(e)}readInt8(e){return this.view.getInt8(e)}readUInt16BE(e){return this.view.getUint16(e,!1)}readInt16BE(e){return this.view.getInt16(e,!1)}readUInt16LE(e){return this.view.getUint16(e,!0)}readInt16LE(e){return this.view.getInt16(e,!0)}readUInt32BE(e){return this.view.getUint32(e,!1)}readInt32BE(e){return this.view.getInt32(e,!1)}readUInt32LE(e){return this.view.getUint32(e,!0)}readInt32LE(e){return this.view.getInt32(e,!0)}readBigUInt64BE(e){return this.view.getBigUint64(e,!1)}readBigInt64BE(e){return this.view.getBigInt64(e,!1)}readBigUInt64LE(e){return this.view.getBigUint64(e,!0)}readBigInt64LE(e){return this.view.getBigInt64(e,!0)}writeUInt8(e,t){this.view.setUint8(t,e)}writeInt8(e,t){this.view.setInt8(t,e)}writeUInt16BE(e,t){this.view.setUint16(t,e,!1)}writeInt16BE(e,t){this.view.setInt16(t,e,!1)}writeUInt16LE(e,t){this.view.setUint16(t,e,!0)}writeInt16LE(e,t){this.view.setInt16(t,e,!0)}writeUInt32BE(e,t){this.view.setUint32(t,e,!1)}writeInt32BE(e,t){this.view.setInt32(t,e,!1)}writeUInt32LE(e,t){this.view.setUint32(t,e,!0)}writeInt32LE(e,t){this.view.setInt32(t,e,!0)}writeBigUInt64BE(e,t){this.view.setBigUint64(t,e,!1)}writeBigInt64BE(e,t){this.view.setBigInt64(t,e,!1)}writeBigUInt64LE(e,t){this.view.setBigUint64(t,e,!0)}writeBigInt64LE(e,t){this.view.setBigInt64(t,e,!0)}readFloatBE(e){return this.view.getFloat32(e,!1)}readFloatLE(e){return this.view.getFloat32(e,!0)}writeFloatBE(e,t){this.view.setFloat32(t,e,!1)}writeFloatLE(e,t){this.view.setFloat32(t,e,!0)}copy(e,t=0,r=0,n=this.length){let o=this.data.subarray(r,n);return e.data.set(o,t),o.length}slice(e,t){let r=this.data.slice(e,t);return H.from(r)}subarray(e,t){let r=this.data.subarray(e,t);return H.from(r)}toBuffer(){return typeof Buffer<"u"&&Buffer.from?Buffer.from(this.data):this.data}static fromNodeBuffer(e){return e instanceof Uint8Array?H.from(e):H.from(new Uint8Array(e))}};y(H,"BufferCompat");f=H});var yn={};te(yn,{VibrationOrderType:()=>kt});var kt,Rt=z(()=>{"use strict";kt=(n=>(n[n.MobileVibrate=1]="MobileVibrate",n[n.MobileCancel=2]="MobileCancel",n[n.GamepadVibrate=16]="GamepadVibrate",n[n.GamepadCancel=17]="GamepadCancel",n))(kt||{})});var Cn={};te(Cn,{GamepadVibrateFlags:()=>zt,MobileVibrateFlags:()=>Bt});var Bt,zt,Tt=z(()=>{"use strict";Bt=(e=>(e[e.HasIntensity=1]="HasIntensity",e))(Bt||{}),zt=(t=>(t[t.HasStartDelay=1]="HasStartDelay",t[t.AllGamepads=2]="AllGamepads",t))(zt||{})});var Sn={};te(Sn,{AudioOrderType:()=>Ft,AudioTargetType:()=>Lt,getAudioOrderTypeName:()=>fn,isValidAudioOrderType:()=>xn});function xn(h){return h>=1&&h<=9}function fn(h){switch(h){case 1:return"PlaySound";case 2:return"PlayGlobalSound";case 3:return"StopSound";case 4:return"FadeOutSound";case 5:return"PauseSound";case 6:return"ResumeSound";case 7:return"SetListenerPosition";case 8:return"ConfigureSpatial";case 9:return"SetSoundEffects";default:return`UnknownAudio(0x${h.toString(16)})`}}var Ft,Lt,Dt=z(()=>{"use strict";Ft=(d=>(d[d.PlaySound=1]="PlaySound",d[d.PlayGlobalSound=2]="PlayGlobalSound",d[d.StopSound=3]="StopSound",d[d.FadeOutSound=4]="FadeOutSound",d[d.PauseSound=5]="PauseSound",d[d.ResumeSound=6]="ResumeSound",d[d.SetListenerPosition=7]="SetListenerPosition",d[d.ConfigureSpatial=8]="ConfigureSpatial",d[d.SetSoundEffects=9]="SetSoundEffects",d))(Ft||{}),Lt=(r=>(r[r.InstanceId=0]="InstanceId",r[r.SoundId=1]="SoundId",r[r.All=2]="All",r))(Lt||{});y(xn,"isValidAudioOrderType");y(fn,"getAudioOrderTypeName")});var On={};te(On,{PlaySoundFlags:()=>Vt,SoundEffectsFlags:()=>In});var Vt,In,Ht=z(()=>{"use strict";Vt=(s=>(s[s.Loop=1]="Loop",s[s.HasVolume=2]="HasVolume",s[s.HasPitch=4]="HasPitch",s[s.HasFadeIn=8]="HasFadeIn",s[s.HasPosition=16]="HasPosition",s[s.HasLowpass=32]="HasLowpass",s[s.HasHighpass=64]="HasHighpass",s[s.HasReverb=128]="HasReverb",s))(Vt||{}),In=(r=>(r[r.HasLowpass=1]="HasLowpass",r[r.HasHighpass=2]="HasHighpass",r[r.HasReverb=4]="HasReverb",r))(In||{})});import{ScalingModeValue as ao}from"@utsp/types";var Un=z(()=>{"use strict"});var vn,Mn=z(()=>{"use strict";vn=(a=>(a[a.SetConfig=1]="SetConfig",a[a.SetScanlines=2]="SetScanlines",a[a.SetAmbientEffect=3]="SetAmbientEffect",a[a.SetScalingMode=4]="SetScalingMode",a[a.SetGrid=5]="SetGrid",a[a.SwitchPalette=6]="SwitchPalette",a[a.SetCellSize=7]="SetCellSize",a))(vn||{})});var pr,Je,Rn=z(()=>{"use strict";pr=class pr{decode(e,t=0){this.checkSize(e,t,7);let n=t,o=e.readUInt8(n++),i=e.readUInt16BE(n);n+=2;let a=e.readUInt16BE(n);n+=2;let s=e.readUInt8(n++)+1,d=e.readUInt8(n++)+1;return{display:{id:o,originX:i,originY:a,sizeX:s,sizeY:d},bytesRead:7}}checkSize(e,t,r){if(t+r>e.length)throw new Error(`Buffer too short for display: need ${r} bytes at offset ${t}, but only ${e.length-t} bytes available`)}};y(pr,"DisplayDecoder");Je=pr});var mr,qe,Bn=z(()=>{"use strict";W();mr=class mr{constructor(){b(this,"charCodeSize",ke)}decode(e,t=0,r=!1){if(t>=e.length)throw new Error("Buffer too short to decode order type");let n=e.readUInt8(t);switch(n){case 1:return this.decodeCharOrder(e,t,r);case 2:return this.decodeTextOrder(e,t);case 23:return this.decodeTextMultilineOrder(e,t);case 3:return this.decodeSubFrameOrder(e,t,r);case 4:return this.decodeSubFrameMultiColorOrder(e,t,r);case 5:return this.decodeFullFrameOrder(e,t,r);case 6:return this.decodeFullFrameMultiColorOrder(e,t,r);case 7:return this.decodeSpriteOrder(e,t);case 8:return this.decodeSpriteMultiColorOrder(e,t);case 9:return this.decodeColorMapOrder(e,t);case 10:return this.decodeShapeOrder(e,t,r);case 11:return this.decodeDotCloudOrder(e,t,r);case 12:return this.decodeDotCloudMultiColorOrder(e,t,r);case 17:return this.decodeBitmaskOrder(e,t,r);case 18:return this.decodeBitmask4Order(e,t,r);case 24:return this.decodeBitmask16Order(e,t,r);case 25:return this.decodePolylineOrder(e,t,r);case 13:return this.decodeSpriteCloudOrder(e,t);case 14:return this.decodeSpriteCloudMultiColorOrder(e,t);case 15:return this.decodeSpriteCloudVariedOrder(e,t);case 16:return this.decodeSpriteCloudVariedMultiColorOrder(e,t);case 19:return this.decodeClearOrder(e,t,r);case 20:return this.decodeFillCharOrder(e,t,r);case 21:return this.decodeFillSpriteOrder(e,t);case 22:return this.decodeFillSpriteMultiColorOrder(e,t);default:throw new Error(`Unknown order type: 0x${n.toString(16)}`)}}readCharCode(e,t,r){return r?[e.readUInt16LE(t),t+2]:[e.readUInt8(t),t+1]}decodeCharOrder(e,t,r){let o=5+this.charCodeSize(r);this.checkSize(e,t,o);let i=t,a=e.readUInt8(i++),s=e.readUInt8(i++),d=e.readUInt8(i++),[c,l]=this.readCharCode(e,i,r);i=l;let u=e.readUInt8(i++),p=e.readUInt8(i++);return{order:{type:1,posX:s,posY:d,charCode:c,bgColorCode:u,fgColorCode:p},bytesRead:o}}decodeTextOrder(e,t){this.checkSize(e,t,5);let r=t,n=e.readUInt8(r+3);this.checkSize(e,t,5+n);let o=e.subarray(r+4,r+4+n),i=new TextDecoder().decode(o.toUint8Array());return{order:{type:2,posX:e.readUInt8(r+1),posY:e.readUInt8(r+2),text:i,bgColorCode:e.readUInt8(r+4+n),fgColorCode:e.readUInt8(r+5+n)},bytesRead:6+n}}decodeTextMultilineOrder(e,t){this.checkSize(e,t,5);let r=t,n=e.readUInt8(r+3);this.checkSize(e,t,5+n);let o=e.subarray(r+4,r+4+n),i=new TextDecoder().decode(o.toUint8Array());return{order:{type:23,posX:e.readUInt8(r+1),posY:e.readUInt8(r+2),text:i,bgColorCode:e.readUInt8(r+4+n),fgColorCode:e.readUInt8(r+5+n)},bytesRead:6+n}}decodeSubFrameOrder(e,t,r){this.checkSize(e,t,7);let n=t,o=this.charCodeSize(r),i=e.readUInt8(n+3)+1,a=e.readUInt8(n+4)+1,s=i*a;this.checkSize(e,t,7+s*o);let d=[],c=n+7;for(let u=0;u<s;u++){let[p,m]=this.readCharCode(e,c,r);d.push(p),c=m}return{order:{type:3,posX:e.readUInt8(n+1),posY:e.readUInt8(n+2),sizeX:i,sizeY:a,bgColorCode:e.readUInt8(n+5),fgColorCode:e.readUInt8(n+6),frame:d},bytesRead:7+s*o}}decodeSubFrameMultiColorOrder(e,t,r){this.checkSize(e,t,5);let n=t,o=this.charCodeSize(r),i=e.readUInt8(n+3)+1,a=e.readUInt8(n+4)+1,s=i*a,d=o+2;this.checkSize(e,t,5+s*d);let c=[],l=n+5;for(let p=0;p<s;p++){let[m,g]=this.readCharCode(e,l,r);l=g,c.push({charCode:m,bgColorCode:e.readUInt8(l++),fgColorCode:e.readUInt8(l++)})}return{order:{type:4,posX:e.readUInt8(n+1),posY:e.readUInt8(n+2),sizeX:i,sizeY:a,frame:c},bytesRead:5+s*d}}decodeFullFrameOrder(e,t,r,n){this.checkSize(e,t,3);let o=t,i=this.charCodeSize(r),a=n||Math.floor((e.length-t-3)/i);this.checkSize(e,t,3+a*i);let s=[],d=o+3;for(let l=0;l<a;l++){let[u,p]=this.readCharCode(e,d,r);s.push(u),d=p}return{order:{type:5,bgColorCode:e.readUInt8(o+1),fgColorCode:e.readUInt8(o+2),frame:s},bytesRead:3+a*i}}decodeFullFrameMultiColorOrder(e,t,r,n){this.checkSize(e,t,1);let o=t,a=this.charCodeSize(r)+2,s=n||Math.floor((e.length-t-1)/a);this.checkSize(e,t,1+s*a);let d=[],c=o+1;for(let u=0;u<s;u++){let[p,m]=this.readCharCode(e,c,r);c=m,d.push({charCode:p,bgColorCode:e.readUInt8(c++),fgColorCode:e.readUInt8(c++)})}return{order:{type:6,frame:d},bytesRead:1+s*a}}decodeSpriteOrder(e,t){this.checkSize(e,t,6);let r=t;return{order:{type:7,posX:e.readUInt8(r+1),posY:e.readUInt8(r+2),spriteIndex:e.readUInt8(r+3),bgColorCode:e.readUInt8(r+4),fgColorCode:e.readUInt8(r+5)},bytesRead:6}}decodeSpriteMultiColorOrder(e,t){this.checkSize(e,t,4);let r=t;return{order:{type:8,posX:e.readUInt8(r+1),posY:e.readUInt8(r+2),spriteIndex:e.readUInt8(r+3)},bytesRead:4}}decodeColorMapOrder(e,t){this.checkSize(e,t,5);let r=t,n=e.readUInt8(r+3)+1,o=e.readUInt8(r+4)+1,i=n*o;this.checkSize(e,t,5+i*2);let a=[];for(let d=0;d<i;d++){let c=r+5+d*2;a.push({bgColorCode:e.readUInt8(c),fgColorCode:e.readUInt8(c+1)})}return{order:{type:9,posX:e.readUInt8(r+1),posY:e.readUInt8(r+2),sizeX:n,sizeY:o,colorData:a},bytesRead:5+i*2}}decodeShapeOrder(e,t,r){this.checkSize(e,t,2);let n=t,o=e.readUInt8(n+1),{shapeData:i,bytesRead:a}=this.decodeShapeData(e,n+2,o,r);return{order:{type:10,shapeType:o,shapeData:i},bytesRead:2+a}}decodeShapeData(e,t,r,n){let o=t,i=this.charCodeSize(n);switch(r){case 1:{let a=7+i;this.checkSize(e,t,a);let s=e.readUInt8(o++),d=e.readUInt8(o++),c=e.readUInt8(o++)+1,l=e.readUInt8(o++)+1,u=e.readUInt8(o++)===1,[p,m]=this.readCharCode(e,o,n);o=m;let g=e.readUInt8(o++),C=e.readUInt8(o++);return{shapeData:{posX:s,posY:d,width:c,height:l,filled:u,charCode:p,bgColorCode:g,fgColorCode:C},bytesRead:a}}case 2:{let a=6+i;this.checkSize(e,t,a);let s=e.readUInt8(o++),d=e.readUInt8(o++),c=e.readUInt8(o++)+1,l=e.readUInt8(o++)===1,[u,p]=this.readCharCode(e,o,n);o=p;let m=e.readUInt8(o++),g=e.readUInt8(o++);return{shapeData:{centerX:s,centerY:d,radius:c,filled:l,charCode:u,bgColorCode:m,fgColorCode:g},bytesRead:a}}case 3:{let a=6+i;this.checkSize(e,t,a);let s=e.readUInt8(o++),d=e.readUInt8(o++),c=e.readUInt8(o++),l=e.readUInt8(o++),[u,p]=this.readCharCode(e,o,n);o=p;let m=e.readUInt8(o++),g=e.readUInt8(o++);return{shapeData:{x1:s,y1:d,x2:c,y2:l,charCode:u,bgColorCode:m,fgColorCode:g},bytesRead:a}}case 4:{let a=7+i;this.checkSize(e,t,a);let s=e.readUInt8(o++),d=e.readUInt8(o++),c=e.readUInt8(o++)+1,l=e.readUInt8(o++)+1,u=e.readUInt8(o++)===1,[p,m]=this.readCharCode(e,o,n);o=m;let g=e.readUInt8(o++),C=e.readUInt8(o++);return{shapeData:{centerX:s,centerY:d,radiusX:c,radiusY:l,filled:u,charCode:p,bgColorCode:g,fgColorCode:C},bytesRead:a}}case 5:{let a=9+i;this.checkSize(e,t,a);let s=e.readUInt8(o++),d=e.readUInt8(o++),c=e.readUInt8(o++),l=e.readUInt8(o++),u=e.readUInt8(o++),p=e.readUInt8(o++),m=e.readUInt8(o++)===1,[g,C]=this.readCharCode(e,o,n);o=C;let x=e.readUInt8(o++),O=e.readUInt8(o++);return{shapeData:{x1:s,y1:d,x2:c,y2:l,x3:u,y3:p,filled:m,charCode:g,bgColorCode:x,fgColorCode:O},bytesRead:a}}default:throw new Error(`Unknown shape type: ${r}`)}}decodeDotCloudOrder(e,t,r){let o=1+this.charCodeSize(r)+2+2;this.checkSize(e,t,o);let i=t,a=e.readUInt8(i++),[s,d]=this.readCharCode(e,i,r);i=d;let c=e.readUInt8(i++),l=e.readUInt8(i++),u=e.readUInt16BE(i);i+=2,this.checkSize(e,t,o+u*2);let p=[];for(let g=0;g<u;g++)p.push({posX:e.readUInt8(i++),posY:e.readUInt8(i++)});return{order:{type:11,charCode:s,bgColorCode:c,fgColorCode:l,positions:p},bytesRead:o+u*2}}decodeDotCloudMultiColorOrder(e,t,r){this.checkSize(e,t,3);let n=this.charCodeSize(r),o=t,i=e.readUInt16BE(o+1),a=n+4;this.checkSize(e,t,3+i*a);let s=[],d=o+3;for(let l=0;l<i;l++){let[u,p]=this.readCharCode(e,d,r);d=p,s.push({charCode:u,bgColorCode:e.readUInt8(d++),fgColorCode:e.readUInt8(d++),posX:e.readUInt8(d++),posY:e.readUInt8(d++)})}return{order:{type:12,dots:s},bytesRead:3+i*a}}decodeBitmaskOrder(e,t,r){let o=8+this.charCodeSize(r);this.checkSize(e,t,o);let i=t,a=e.readUInt8(i++),s=e.readUInt8(i++),d=e.readUInt8(i++),c=e.readUInt8(i++)+1,l=e.readUInt8(i++)+1,[u,p]=this.readCharCode(e,i,r);i=p;let m=e.readUInt8(i++),g=e.readUInt8(i++),C=e.readUInt8(i++)===1,x=Math.ceil(c*l/8);this.checkSize(e,t,o+x);let O=new Uint8Array(x);for(let w=0;w<x;w++)O[w]=e.readUInt8(i+w);return{order:{type:17,posX:s,posY:d,sizeX:c,sizeY:l,charCode:u,bgColorCode:m,fgColorCode:g,override:C,mask:O},bytesRead:o+x}}decodeBitmask4Order(e,t,r){let i=6+3*(this.charCodeSize(r)+2);this.checkSize(e,t,i);let a=t,s=e.readUInt8(a++),d=e.readUInt8(a++),c=e.readUInt8(a++),l=e.readUInt8(a++)+1,u=e.readUInt8(a++)+1,p=e.readUInt8(a++)===1,m=Math.ceil(l*u/4);this.checkSize(e,t,i+m);let g=[];for(let O=0;O<3;O++){let[I,w]=this.readCharCode(e,a,r);a=w,g.push({charCode:I,bgColorCode:e.readUInt8(a++),fgColorCode:e.readUInt8(a++)})}let C=new Uint8Array(m);for(let O=0;O<m;O++)C[O]=e.readUInt8(a+O);return{order:{type:18,posX:d,posY:c,sizeX:l,sizeY:u,override:p,variants:g,mask:C},bytesRead:i+m}}decodeBitmask16Order(e,t,r){let i=6+15*(this.charCodeSize(r)+2);this.checkSize(e,t,i);let a=t,s=e.readUInt8(a++),d=e.readUInt8(a++),c=e.readUInt8(a++),l=e.readUInt8(a++)+1,u=e.readUInt8(a++)+1,p=e.readUInt8(a++)===1,m=Math.ceil(l*u/2);this.checkSize(e,t,i+m);let g=[];for(let O=0;O<15;O++){let[I,w]=this.readCharCode(e,a,r);a=w,g.push({charCode:I,bgColorCode:e.readUInt8(a++),fgColorCode:e.readUInt8(a++)})}let C=new Uint8Array(m);for(let O=0;O<m;O++)C[O]=e.readUInt8(a+O);return{order:{type:24,posX:d,posY:c,sizeX:l,sizeY:u,override:p,variants:g,mask:C},bytesRead:i+m}}decodePolylineOrder(e,t,r){let o=4+this.charCodeSize(r);this.checkSize(e,t,o);let i=t,a=e.readUInt8(i++),[s,d]=this.readCharCode(e,i,r);i=d;let c=e.readUInt8(i++),l=e.readUInt8(i++),u=e.readUInt8(i++);this.checkSize(e,t,o+u*2);let p=[];for(let g=0;g<u;g++)p.push({x:e.readUInt8(i++),y:e.readUInt8(i++)});return{order:{type:25,charCode:s,fgColorCode:c,bgColorCode:l,points:p},bytesRead:o+u*2}}decodeSpriteCloudOrder(e,t){this.checkSize(e,t,6);let r=t,n=e.readUInt16BE(r+4);this.checkSize(e,t,6+n*2);let o=[];for(let a=0;a<n;a++){let s=r+6+a*2;o.push({posX:e.readUInt8(s),posY:e.readUInt8(s+1)})}return{order:{type:13,spriteIndex:e.readUInt8(r+1),bgColorCode:e.readUInt8(r+2),fgColorCode:e.readUInt8(r+3),positions:o},bytesRead:6+n*2}}decodeSpriteCloudMultiColorOrder(e,t){this.checkSize(e,t,4);let r=t,n=e.readUInt16BE(r+2);this.checkSize(e,t,4+n*2);let o=[];for(let a=0;a<n;a++){let s=r+4+a*2;o.push({posX:e.readUInt8(s),posY:e.readUInt8(s+1)})}return{order:{type:14,spriteIndex:e.readUInt8(r+1),positions:o},bytesRead:4+n*2}}decodeSpriteCloudVariedOrder(e,t){this.checkSize(e,t,3);let r=t,n=e.readUInt16BE(r+1);this.checkSize(e,t,3+n*5);let o=[];for(let a=0;a<n;a++){let s=r+3+a*5;o.push({spriteIndex:e.readUInt8(s),bgColorCode:e.readUInt8(s+1),fgColorCode:e.readUInt8(s+2),posX:e.readUInt8(s+3),posY:e.readUInt8(s+4)})}return{order:{type:15,sprites:o},bytesRead:3+n*5}}decodeSpriteCloudVariedMultiColorOrder(e,t){this.checkSize(e,t,3);let r=t,n=e.readUInt16BE(r+1);this.checkSize(e,t,3+n*3);let o=[];for(let a=0;a<n;a++){let s=r+3+a*3;o.push({spriteIndex:e.readUInt8(s),posX:e.readUInt8(s+1),posY:e.readUInt8(s+2)})}return{order:{type:16,sprites:o},bytesRead:3+n*3}}decodeClearOrder(e,t,r){let o=3+this.charCodeSize(r);this.checkSize(e,t,o);let i=t,a=e.readUInt8(i++),[s,d]=this.readCharCode(e,i,r);i=d;let c=e.readUInt8(i++),l=e.readUInt8(i++);return{order:{type:19,charCode:s,bgColorCode:c,fgColorCode:l},bytesRead:o}}decodeFillCharOrder(e,t,r){this.checkSize(e,t,5);let n=this.charCodeSize(r),o=t,i=e.readUInt8(o+1)+1,a=e.readUInt8(o+2)+1,s=i*a,d=5+s*n;this.checkSize(e,t,d);let c=[],l=o+5;for(let p=0;p<s;p++){let[m,g]=this.readCharCode(e,l,r);c.push(m),l=g}return{order:{type:20,patternWidth:i,patternHeight:a,bgColorCode:e.readUInt8(o+3),fgColorCode:e.readUInt8(o+4),pattern:c},bytesRead:d}}decodeFillSpriteOrder(e,t){this.checkSize(e,t,4);let r=t;return{order:{type:21,spriteIndex:e.readUInt8(r+1),bgColorCode:e.readUInt8(r+2),fgColorCode:e.readUInt8(r+3)},bytesRead:4}}decodeFillSpriteMultiColorOrder(e,t){this.checkSize(e,t,2);let r=t;return{order:{type:22,spriteIndex:e.readUInt8(r+1)},bytesRead:2}}checkSize(e,t,r){if(t+r>e.length)throw new Error(`Buffer too short: need ${r} bytes at offset ${t}, but only ${e.length-t} bytes available`)}};y(mr,"OrderDecoder");qe=mr});var lo,hr,Ke,zn=z(()=>{"use strict";Bn();lo=64,hr=class hr{constructor(){b(this,"orderDecoder");this.orderDecoder=new qe}decode(e,t=0){this.checkSize(e,t,13);let n=t,o=e.readUInt16BE(n);n+=2;let i=e.readUInt8(n++),a=e.readUInt8(n++),s=e.readUInt16BE(n);n+=2;let d=e.readUInt16BE(n);n+=2;let c=e.readUInt16BE(n);n+=2;let l=e.readUInt16BE(n);n+=2;let u=e.readUInt8(n++),p=(i&lo)!==0,m=[],g=n;for(let x=0;x<u;x++){let O=this.orderDecoder.decode(e,g,p);m.push(O.order),g+=O.bytesRead}return{layer:{id:o,updateFlags:i,zIndex:a,originX:s,originY:d,width:c,height:l,orderCount:u,orders:m,is16bit:p},bytesRead:g-t}}checkSize(e,t,r){if(t+r>e.length)throw new Error(`Buffer too short for layer: need ${r} bytes at offset ${t}, but only ${e.length-t} bytes available`)}};y(hr,"LayerDecoder");Ke=hr});var br,Ue,gr=z(()=>{"use strict";br=class br{decode(e,t=0){if(t>=e.length)throw new Error("Buffer too short to decode audio order type");let r=e.readUInt8(t);switch(r){case 1:return this.decodePlaySoundOrder(e,t);case 2:return this.decodePlayGlobalSoundOrder(e,t);case 3:return this.decodeStopSoundOrder(e,t);case 4:return this.decodeFadeOutSoundOrder(e,t);case 5:return this.decodePauseSoundOrder(e,t);case 6:return this.decodeResumeSoundOrder(e,t);case 7:return this.decodeSetListenerPositionOrder(e,t);case 8:return this.decodeConfigureSpatialOrder(e,t);case 9:return this.decodeSetSoundEffectsOrder(e,t);default:throw new Error(`Unknown audio order type: 0x${r.toString(16)}`)}}decodePlaySoundOrder(e,t){this.checkSize(e,t,5);let r=t,n=e.readUInt8(r++),o=e.readUInt8(r++),i=e.readUInt16BE(r);r+=2;let a=e.readUInt8(r++),s={type:n,soundId:o,instanceId:i,flags:a};return a&2&&(this.checkSize(e,r,1),s.volume=e.readUInt8(r++)),a&4&&(this.checkSize(e,r,1),s.pitch=e.readUInt8(r++)),a&8&&(this.checkSize(e,r,1),s.fadeIn=e.readUInt8(r++)),a&16&&(this.checkSize(e,r,4),s.posX=e.readUInt16BE(r),r+=2,s.posY=e.readUInt16BE(r),r+=2),a&32&&(this.checkSize(e,r,1),s.lowpass=e.readUInt8(r++)),a&64&&(this.checkSize(e,r,1),s.highpass=e.readUInt8(r++)),a&128&&(this.checkSize(e,r,1),s.reverb=e.readUInt8(r++)),{order:s,bytesRead:r-t}}decodePlayGlobalSoundOrder(e,t){this.checkSize(e,t,5);let r=t,n=e.readUInt8(r++),o=e.readUInt8(r++),i=e.readUInt16BE(r);r+=2;let a=e.readUInt8(r++),s={type:n,soundId:o,instanceId:i,flags:a};return a&2&&(this.checkSize(e,r,1),s.volume=e.readUInt8(r++)),a&4&&(this.checkSize(e,r,1),s.pitch=e.readUInt8(r++)),a&8&&(this.checkSize(e,r,1),s.fadeIn=e.readUInt8(r++)),a&32&&(this.checkSize(e,r,1),s.lowpass=e.readUInt8(r++)),a&64&&(this.checkSize(e,r,1),s.highpass=e.readUInt8(r++)),a&128&&(this.checkSize(e,r,1),s.reverb=e.readUInt8(r++)),{order:s,bytesRead:r-t}}decodeStopSoundOrder(e,t){this.checkSize(e,t,2);let r=t,n=e.readUInt8(r++),o=e.readUInt8(r++),i={type:n,targetType:o};return o===0?(this.checkSize(e,r,2),i.target=e.readUInt16BE(r),r+=2):o===1&&(this.checkSize(e,r,1),i.target=e.readUInt8(r++)),{order:i,bytesRead:r-t}}decodeFadeOutSoundOrder(e,t){this.checkSize(e,t,3);let r=t,n=e.readUInt8(r++),o=e.readUInt8(r++),i=e.readUInt8(r++),a={type:n,targetType:o,duration:i};return o===0?(this.checkSize(e,r,2),a.target=e.readUInt16BE(r),r+=2):o===1&&(this.checkSize(e,r,1),a.target=e.readUInt8(r++)),{order:a,bytesRead:r-t}}decodePauseSoundOrder(e,t){this.checkSize(e,t,2);let r=t,n=e.readUInt8(r++),o=e.readUInt8(r++),i={type:n,targetType:o};return o===0?(this.checkSize(e,r,2),i.target=e.readUInt16BE(r),r+=2):o===1&&(this.checkSize(e,r,1),i.target=e.readUInt8(r++)),{order:i,bytesRead:r-t}}decodeResumeSoundOrder(e,t){this.checkSize(e,t,2);let r=t,n=e.readUInt8(r++),o=e.readUInt8(r++),i={type:n,targetType:o};return o===0?(this.checkSize(e,r,2),i.target=e.readUInt16BE(r),r+=2):o===1&&(this.checkSize(e,r,1),i.target=e.readUInt8(r++)),{order:i,bytesRead:r-t}}decodeSetListenerPositionOrder(e,t){this.checkSize(e,t,5);let r=t,n=e.readUInt8(r++),o=e.readUInt16BE(r);r+=2;let i=e.readUInt16BE(r);return r+=2,{order:{type:n,x:o,y:i},bytesRead:5}}decodeConfigureSpatialOrder(e,t){this.checkSize(e,t,5);let r=t;return{order:{type:e.readUInt8(r),maxDistance:e.readUInt8(r+1),referenceDistance:e.readUInt8(r+2),rolloffFactor:e.readUInt8(r+3),panSpread:e.readUInt8(r+4)},bytesRead:5}}decodeSetSoundEffectsOrder(e,t){this.checkSize(e,t,4);let r=t,n=e.readUInt8(r++),o=e.readUInt16BE(r);r+=2;let i=e.readUInt8(r++),a={type:n,instanceId:o,flags:i};return i&1&&(this.checkSize(e,r,1),a.lowpass=e.readUInt8(r++)),i&2&&(this.checkSize(e,r,1),a.highpass=e.readUInt8(r++)),i&4&&(this.checkSize(e,r,1),a.reverb=e.readUInt8(r++)),{order:a,bytesRead:r-t}}checkSize(e,t,r){if(t+r>e.length)throw new Error(`Buffer too short for audio order: need ${r} bytes at offset ${t}, but only ${e.length-t} bytes available`)}};y(br,"AudioOrderDecoder");Ue=br});var yr,ve,Cr=z(()=>{"use strict";yr=class yr{decode(e,t=0){if(t>=e.length)throw new Error("Buffer too short to decode vibration order type");let r=e.readUInt8(t);switch(r){case 1:return this.decodeMobileVibrateOrder(e,t);case 2:return this.decodeMobileCancelOrder(e,t);case 16:return this.decodeGamepadVibrateOrder(e,t);case 17:return this.decodeGamepadCancelOrder(e,t);default:throw new Error(`Unknown vibration order type: 0x${r.toString(16)}`)}}decodeMobileVibrateOrder(e,t){let r=t,n=e.readUInt8(r++),o=e.readUInt8(r++),i=e.readUInt8(r++),a=[];for(let d=0;d<i;d++)a.push(e.readUInt16BE(r)),r+=2;let s={type:n,flags:o,pattern:a};return o&1&&(s.intensity=e.readUInt8(r++)/255),{order:s,bytesRead:r-t}}decodeMobileCancelOrder(e,t){return{order:{type:2},bytesRead:1}}decodeGamepadVibrateOrder(e,t){let r=t,n=e.readUInt8(r++),o=e.readUInt8(r++),i=e.readUInt8(r++),a=e.readUInt16BE(r);r+=2;let s=e.readUInt8(r++),d=e.readUInt8(r++),c={type:n,flags:o,gamepadIndex:i,duration:a,strongMagnitude:s,weakMagnitude:d};return o&1&&(c.startDelay=e.readUInt16BE(r),r+=2),{order:c,bytesRead:r-t}}decodeGamepadCancelOrder(e,t){let r=t,n=e.readUInt8(r++),o=e.readUInt8(r++),i=e.readUInt8(r++);return{order:{type:n,flags:o,gamepadIndex:i},bytesRead:r-t}}};y(yr,"VibrationOrderDecoder");ve=yr});var xr,Qe,Tn=z(()=>{"use strict";xr=class xr{decode(e,t=0){let r=e.readUInt8(t);switch(r){case 1:return this.decodeCreateInstance(e,t);case 2:return this.decodeUpdateInstance(e,t);case 3:return this.decodeRemoveInstance(e,t);default:throw new Error(`Unknown macro order type: 0x${r.toString(16)}`)}}decodeAll(e,t,r){let n=[],o=0;for(let i=0;i<r;i++){let{order:a,bytesRead:s}=this.decode(e,t+o);n.push(a),o+=s}return{orders:n,bytesRead:o}}decodeCreateInstance(e,t){let r=t,n=e.readUInt8(t++),o=e.readUInt8(t++),i=e.readUInt8(t++),a=e.readUInt8(t++),s=e.readInt16BE(t);t+=2;let d=e.readInt16BE(t);t+=2;let c=e.readUInt8(t++),l=e.readUInt16BE(t);t+=2;let u=e.toUint8Array().subarray(t,t+l);t+=l;let p=new TextDecoder().decode(u),m=JSON.parse(p);return{order:{type:n,instanceId:o,macroId:i,layerId:a,x:s,y:d,tabIndex:c,params:m},bytesRead:t-r}}decodeUpdateInstance(e,t){let r=t,n=e.readUInt8(t++),o=e.readUInt8(t++),i=e.readUInt16BE(t);t+=2;let a=e.toUint8Array().subarray(t,t+i);t+=i;let s=new TextDecoder().decode(a),d=JSON.parse(s);return{order:{type:n,instanceId:o,params:d},bytesRead:t-r}}decodeRemoveInstance(e,t){let r=e.readUInt8(t),n=e.readUInt8(t+1);return{order:{type:r,instanceId:n},bytesRead:2}}};y(xr,"MacroOrderDecoder");Qe=xr});var fr,Me,Sr=z(()=>{"use strict";fr=class fr{decode(e,t){let r=e[t];switch(r){case 1:return this.decodeSetConfigOrder(e,t);case 2:return this.decodeSetScanlinesOrder(e,t);case 3:return this.decodeSetAmbientEffectOrder(e,t);case 4:return this.decodeSetScalingModeOrder(e,t);case 5:return this.decodeSetGridOrder(e,t);case 6:return this.decodeSwitchPaletteOrder(e,t);case 7:return this.decodeSetCellSizeOrder(e,t);default:throw new Error(`Unknown post-process order type: ${r}`)}}decodeSetConfigOrder(e,t){let r=t,n=e[r++],o=e[r++],i=e[r++],a={type:n,displayId:o,flags:i};return i&1&&(a.scanlines={enabled:e[r++]===1,opacity:e[r++]/255,pattern:e[r++],colorR:e[r++],colorG:e[r++],colorB:e[r++]}),i&2&&(a.ambientEffect={enabled:e[r++]===1,blur:e[r++],scale:e[r++]/100,opacity:e[r++]/255}),{order:a,bytesRead:r-t}}decodeSetScanlinesOrder(e,t){let r=t;return{order:{type:e[r++],displayId:e[r++],enabled:e[r++]===1,opacity:e[r++]/255,pattern:e[r++],colorR:e[r++],colorG:e[r++],colorB:e[r++]},bytesRead:r-t}}decodeSetAmbientEffectOrder(e,t){let r=t;return{order:{type:e[r++],displayId:e[r++],enabled:e[r++]===1,blur:e[r++],scale:e[r++]/100,opacity:e[r++]/255},bytesRead:r-t}}decodeSetScalingModeOrder(e,t){let r=t;return{order:{type:e[r++],displayId:e[r++],mode:e[r++]},bytesRead:r-t}}decodeSetGridOrder(e,t){let r=t;return{order:{type:e[r++],displayId:e[r++],enabled:e[r++]===1,colorR:e[r++],colorG:e[r++],colorB:e[r++],colorA:e[r++],lineWidth:e[r++]},bytesRead:r-t}}decodeSwitchPaletteOrder(e,t){let r=t;return{order:{type:e[r++],displayId:e[r++],slotId:e[r++]},bytesRead:r-t}}decodeSetCellSizeOrder(e,t){let r=t;return{order:{type:e[r++],displayId:e[r++],cellWidth:e[r++],cellHeight:e[r++]},bytesRead:r-t}}};y(fr,"PostProcessOrderDecoder");Me=fr});var Fn={};te(Fn,{UpdatePacketDecoder:()=>et});var Ir,et,Or=z(()=>{"use strict";Rn();zn();gr();Cr();Tn();Sr();L();Ir=class Ir{constructor(){b(this,"displayDecoder");b(this,"layerDecoder");b(this,"audioOrderDecoder");b(this,"vibrationOrderDecoder");b(this,"macroOrderDecoder");b(this,"postProcessOrderDecoder");this.displayDecoder=new Je,this.layerDecoder=new Ke,this.audioOrderDecoder=new Ue,this.vibrationOrderDecoder=new ve,this.macroOrderDecoder=new Qe,this.postProcessOrderDecoder=new Me}decode(e,t=0){let r=f.from(e);this.checkSize(r,t,15);let o=t,i=Number(r.readBigUInt64BE(o));o+=8;let a=r.readUInt8(o);o+=1;let s=[];for(let w=0;w<a;w++){let U=this.displayDecoder.decode(r,o);s.push(U.display),o+=U.bytesRead}this.checkSize(r,o,2);let d=r.readUInt16BE(o);o+=2;let c=[];for(let w=0;w<d;w++){let U=this.layerDecoder.decode(r,o);c.push(U.layer),o+=U.bytesRead}this.checkSize(r,o,1);let l=r.readUInt8(o);o+=1;let u=[];for(let w=0;w<l;w++){let U=this.audioOrderDecoder.decode(r,o);u.push(U.order),o+=U.bytesRead}this.checkSize(r,o,1);let p=r.readUInt8(o);o+=1;let m=[];for(let w=0;w<p;w++){let U=this.vibrationOrderDecoder.decode(r,o);m.push(U.order),o+=U.bytesRead}this.checkSize(r,o,1);let g=r.readUInt8(o);o+=1;let C=[];for(let w=0;w<g;w++){let U=this.macroOrderDecoder.decode(r,o);C.push(U.order),o+=U.bytesRead}this.checkSize(r,o,1);let x=r.readUInt8(o);o+=1;let O=[];for(let w=0;w<x;w++){let U=this.postProcessOrderDecoder.decode(r.toUint8Array(),o);O.push(U.order),o+=U.bytesRead}return{tick:i,displayCount:a,displays:s,layerCount:d,layers:c,audioOrderCount:l,audioOrders:u,vibrationOrderCount:p,vibrationOrders:m,macroOrderCount:g,macroOrders:C,postProcessOrderCount:x,postProcessOrders:O}}isValid(e,t=0){let r=f.from(e);try{return this.checkSize(r,t,15),!0}catch{return!1}}decodeHeader(e,t=0){let r=f.from(e);this.checkSize(r,t,13);let n=t,o=Number(r.readBigUInt64BE(n));n+=8;let i=r.readUInt8(n);n+=1,n+=i*7,this.checkSize(r,n,2);let a=r.readUInt16BE(n);return{tick:o,displayCount:i,layerCount:a}}checkSize(e,t,r){if(t+r>e.length)throw new Error(`Buffer too short for update packet: need ${r} bytes at offset ${t}, but only ${e.length-t} bytes available`)}};y(Ir,"UpdatePacketDecoder");et=Ir});import{Vector2 as Ee}from"@utsp/types";var rt=class rt{constructor(e=0,t=60,r=40){b(this,"id");b(this,"origin");b(this,"size");b(this,"previousOrigin",new Ee(0,0));b(this,"previousSize",new Ee(0,0));b(this,"toDraw",[]);if(e<0||e>255)throw new Error(`Display ID must be between 0 and 255, got ${e}`);if(t<1||t>256)throw new Error(`Display sizeX must be between 1 and 256, got ${t}`);if(r<1||r>256)throw new Error(`Display sizeY must be between 1 and 256, got ${r}`);this.id=e,this.origin=new Ee(0,0),this.size=new Ee(t,r),this.toDraw=new Array(this.size.x*this.size.y).fill(null).map(()=>({charCode:0,fgColorCode:0,bgColorCode:0}))}getId(){return this.id}getOrigin(){return this.origin}setOrigin(e){this.origin=e}moveOrigin(e,t){this.origin.x+=e,this.origin.y+=t}hasOriginChanged(){return this.origin.x!==this.previousOrigin.x||this.origin.y!==this.previousOrigin.y}hasSizeChanged(){return this.size.x!==this.previousSize.x||this.size.y!==this.previousSize.y}hasChanged(){return this.hasOriginChanged()||this.hasSizeChanged()}resetChangeTracking(){this.previousOrigin.x=this.origin.x,this.previousOrigin.y=this.origin.y,this.previousSize.x=this.size.x,this.previousSize.y=this.size.y}getSize(){return this.size}setSize(e){if(e.x<1||e.x>256)throw new Error(`Display sizeX must be between 1 and 256, got ${e.x}`);if(e.y<1||e.y>256)throw new Error(`Display sizeY must be between 1 and 256, got ${e.y}`);this.size=e,this.toDraw=new Array(this.size.x*this.size.y).fill(null).map(()=>({charCode:0,fgColorCode:0,bgColorCode:0}))}};y(rt,"Display");var ne=rt;var pt=class pt{constructor(e=65536,t=!1){b(this,"charCodes");b(this,"fgColors");b(this,"bgColors");b(this,"size");b(this,"is16bit");this.size=e,this.is16bit=t,this.charCodes=t?new Uint16Array(e):new Uint8Array(e),this.fgColors=new Uint8Array(e),this.bgColors=new Uint8Array(e),this.clear()}clear(){this.charCodes.fill(0),this.fgColors.fill(255),this.bgColors.fill(255)}clearWithColor(e,t,r){let n=this.is16bit?e:e&255;this.charCodes.fill(n),this.fgColors.fill(t),this.bgColors.fill(r)}set(e,t,r,n){this.charCodes[e]=this.is16bit?t:t&255,this.fgColors[e]=r,this.bgColors[e]=n}fillCharsUniform(e,t,r,n){let o=this.is16bit?t:t&255;for(let i=0;i<e.length;i++){let a=e[i];this.charCodes[a]=o,this.fgColors[a]=r,this.bgColors[a]=n}}get(e){return{charCode:this.charCodes[e],fgColorCode:this.fgColors[e],bgColorCode:this.bgColors[e]}}setCharOnly(e,t){this.charCodes[e]=this.is16bit?t:t&255}setColorsOnly(e,t,r){this.fgColors[e]=t,this.bgColors[e]=r}getCharCode(e){return this.charCodes[e]}getFgColorCode(e){return this.fgColors[e]}getBgColorCode(e){return this.bgColors[e]}getRawCharCodes(){return this.charCodes}getRawFgColors(){return this.fgColors}getRawBgColors(){return this.bgColors}getSize(){return this.size}is16BitMode(){return this.is16bit}};y(pt,"CellBuffer");var G=pt,mt=class mt{constructor(e){b(this,"data");b(this,"size");this.size=e,this.data=new Uint16Array(e)}clear(){this.data.fill(0)}set(e,t){this.data[e]=t}get(e){return this.data[e]}getRawData(){return this.data}getSize(){return this.size}};y(mt,"CharCodeBuffer");var oe=mt;import{Vector2 as Wn}from"@utsp/types";var Xn=new Map([[9474,179],[9472,196],[9484,218],[9488,191],[9492,192],[9496,217],[9500,195],[9508,180],[9516,194],[9524,193],[9532,197],[9553,186],[9552,205],[9556,201],[9559,187],[9562,200],[9565,188],[9568,204],[9571,185],[9574,203],[9577,202],[9580,206],[9608,219],[9619,178],[9618,177],[9617,176],[9600,223],[9604,220],[9612,221],[9616,222]]);function ie(h){if(h<128)return h;let e=Xn.get(h);return e!==void 0?e:h&255}y(ie,"unicodeToCp437");var ht=class ht{constructor(){b(this,"currentWidth",256);b(this,"currentHeight",256)}rasterizeOrders(e,t,r,n,o){this.currentWidth=r,this.currentHeight=n,this.clearBuffer(t);for(let i of e)this.rasterizeOrder(i,t,o)}clearBuffer(e){e.clear()}rasterizeOrder(e,t,r){switch(e.type){case 1:this.rasterizeChar(e,t);break;case 2:this.rasterizeText(e,t);break;case 23:this.rasterizeTextMultiline(e,t);break;case 3:this.rasterizeSubFrame(e,t);break;case 4:this.rasterizeSubFrameMultiColor(e,t);break;case 5:this.rasterizeFullFrame(e,t);break;case 6:this.rasterizeFullFrameMultiColor(e,t);break;case 7:this.rasterizeSprite(e,t,r);break;case 8:this.rasterizeSpriteMultiColor(e,t,r);break;case 9:this.rasterizeColorMap(e,t);break;case 10:this.rasterizeShape(e,t);break;case 11:this.rasterizeDotCloud(e,t);break;case 12:this.rasterizeDotCloudMultiColor(e,t);break;case 17:this.rasterizeBitmask(e,t);break;case 18:this.rasterizeBitmask4(e,t);break;case 24:this.rasterizeBitmask16(e,t);break;case 25:this.rasterizePolyline(e,t);break;case 13:this.rasterizeSpriteCloud(e,t,r);break;case 14:this.rasterizeSpriteCloudMultiColor(e,t,r);break;case 15:this.rasterizeSpriteCloudVaried(e,t,r);break;case 16:this.rasterizeSpriteCloudVariedMultiColor(e,t,r);break;case 19:this.rasterizeClear(e,t);break;case 20:this.rasterizeFillChar(e,t);break;case 21:this.rasterizeFillSprite(e,t,r);break;case 22:this.rasterizeFillSpriteMultiColor(e,t,r);break;default:break}}rasterizeChar(e,t){let{posX:r,posY:n,charCode:o,bgColorCode:i,fgColorCode:a}=e;if(!this.isInBounds(r,n))return;let s=n*this.currentWidth+r;t.set(s,o,a,i)}rasterizeText(e,t){let{posX:r,posY:n,text:o,bgColorCode:i,fgColorCode:a}=e;if(this.isInBounds(r,n))for(let s=0;s<o.length;s++){let d=r+s;if(d>=this.currentWidth)break;let c=n*this.currentWidth+d,l=o.charCodeAt(s),u=ie(l);t.set(c,u,a,i)}}rasterizeTextMultiline(e,t){let{posX:r,posY:n,text:o,bgColorCode:i,fgColorCode:a}=e,s=o.split(`
|
|
2
|
-
`),d=n;for(let c of s){if(d>=this.currentHeight)break;if(d>=0&&this.isInBounds(r,d))for(let l=0;l<c.length;l++){let u=r+l;if(u>=this.currentWidth)break;let p=d*this.currentWidth+u,m=c.charCodeAt(l),g=ie(m);t.set(p,g,a,i)}d++}}rasterizeSubFrame(e,t){let{posX:r,posY:n,sizeX:o,sizeY:i,frame:a,bgColorCode:s,fgColorCode:d}=e;for(let c=0;c<i;c++){let l=n+c;if(!(l<0||l>=this.currentHeight))for(let u=0;u<o;u++){let p=r+u;if(p<0||p>=this.currentWidth)continue;let m=c*o+u;if(m>=a.length)break;let g=l*this.currentWidth+p;t.set(g,a[m],d,s)}}}rasterizeSubFrameMultiColor(e,t){let{posX:r,posY:n,sizeX:o,sizeY:i,frame:a}=e;for(let s=0;s<i;s++){let d=n+s;if(!(d<0||d>=this.currentHeight))for(let c=0;c<o;c++){let l=r+c;if(l<0||l>=this.currentWidth)continue;let u=s*o+c;if(u>=a.length)break;let p=a[u],m=d*this.currentWidth+l;t.set(m,p.charCode,p.fgColorCode,p.bgColorCode)}}}rasterizeFullFrame(e,t){let{frame:r,bgColorCode:n,fgColorCode:o}=e,i=this.currentWidth*this.currentHeight;for(let a=0;a<i&&a<r.length;a++)t.set(a,r[a],o,n)}rasterizeFullFrameMultiColor(e,t){let{frame:r}=e,n=this.currentWidth*this.currentHeight;for(let o=0;o<n&&o<r.length;o++){let i=r[o];t.set(o,i.charCode,i.fgColorCode,i.bgColorCode)}}rasterizeColorMap(e,t){let{posX:r,posY:n,sizeX:o,sizeY:i,colorData:a}=e;for(let s=0;s<i;s++){let d=n+s;if(!(d<0||d>=this.currentHeight))for(let c=0;c<o;c++){let l=r+c;if(l<0||l>=this.currentWidth)continue;let u=s*o+c;if(u>=a.length)break;let p=d*this.currentWidth+l,m=a[u];t.setColorsOnly(p,m.fgColorCode,m.bgColorCode)}}}rasterizeShape(e,t){let{shapeType:r,shapeData:n}=e;switch(r){case 1:this.rasterizeRectangle(n,t);break;case 2:this.rasterizeCircle(n,t);break;case 3:this.rasterizeLine(n,t);break;case 4:this.rasterizeEllipse(n,t);break;case 5:this.rasterizeTriangle(n,t);break}}rasterizeRectangle(e,t){let{posX:r,posY:n,width:o,height:i,filled:a,charCode:s,bgColorCode:d,fgColorCode:c}=e;if(a)for(let l=0;l<i;l++){let u=n+l;if(!(u<0||u>=this.currentHeight))for(let p=0;p<o;p++){let m=r+p;if(m<0||m>=this.currentWidth)continue;let g=u*this.currentWidth+m;t.set(g,s,c,d)}}else{for(let l=0;l<o;l++)this.setCell(r+l,n,s,d,c,t),this.setCell(r+l,n+i-1,s,d,c,t);for(let l=0;l<i;l++)this.setCell(r,n+l,s,d,c,t),this.setCell(r+o-1,n+l,s,d,c,t)}}rasterizeCircle(e,t){let{centerX:r,centerY:n,radius:o,filled:i,charCode:a,bgColorCode:s,fgColorCode:d}=e;if(i)for(let c=-o;c<=o;c++){let l=n+c;if(!(l<0||l>=this.currentHeight))for(let u=-o;u<=o;u++){let p=r+u;if(!(p<0||p>=this.currentWidth)&&u*u+c*c<=o*o){let m=l*this.currentWidth+p;t.set(m,a,d,s)}}}else{let c=o,l=0,u=0;for(;c>=l;)this.setCell(r+c,n+l,a,s,d,t),this.setCell(r+l,n+c,a,s,d,t),this.setCell(r-l,n+c,a,s,d,t),this.setCell(r-c,n+l,a,s,d,t),this.setCell(r-c,n-l,a,s,d,t),this.setCell(r-l,n-c,a,s,d,t),this.setCell(r+l,n-c,a,s,d,t),this.setCell(r+c,n-l,a,s,d,t),u<=0&&(l+=1,u+=2*l+1),u>0&&(c-=1,u-=2*c+1)}}rasterizeLine(e,t){let{x1:r,y1:n,x2:o,y2:i,charCode:a,bgColorCode:s,fgColorCode:d}=e,c=Math.abs(o-r),l=Math.abs(i-n),u=r<o?1:-1,p=n<i?1:-1,m=c-l,g=r,C=n;for(;this.setCell(g,C,a,s,d,t),!(g===o&&C===i);){let x=2*m;x>-l&&(m-=l,g+=u),x<c&&(m+=c,C+=p)}}rasterizePolyline(e,t){let{charCode:r,fgColorCode:n,bgColorCode:o,points:i}=e;if(i.length<2){i.length===1&&this.setCell(i[0].x,i[0].y,r,o,n,t);return}for(let a=0;a<i.length-1;a++){let s=i[a],d=i[a+1];this.rasterizeLineSegment(s.x,s.y,d.x,d.y,r,o,n,t)}}rasterizeLineSegment(e,t,r,n,o,i,a,s){let d=Math.abs(r-e),c=Math.abs(n-t),l=e<r?1:-1,u=t<n?1:-1,p=d-c,m=e,g=t;for(;this.setCell(m,g,o,i,a,s),!(m===r&&g===n);){let C=2*p;C>-c&&(p-=c,m+=l),C<d&&(p+=d,g+=u)}}rasterizeEllipse(e,t){let{centerX:r,centerY:n,radiusX:o,radiusY:i,filled:a,charCode:s,bgColorCode:d,fgColorCode:c}=e;if(a)for(let l=-i;l<=i;l++){let u=n+l;if(!(u<0||u>=this.currentHeight))for(let p=-o;p<=o;p++){let m=r+p;if(m<0||m>=this.currentWidth)continue;if(p*p/(o*o)+l*l/(i*i)<=1){let C=u*this.currentWidth+m;t.set(C,s,c,d)}}}else{let l=Math.max(o,i)*8;for(let u=0;u<l;u++){let p=2*Math.PI*u/l,m=Math.round(r+o*Math.cos(p)),g=Math.round(n+i*Math.sin(p));this.setCell(m,g,s,d,c,t)}}}rasterizeTriangle(e,t){let{x1:r,y1:n,x2:o,y2:i,x3:a,y3:s,filled:d,charCode:c,bgColorCode:l,fgColorCode:u}=e;if(d){let p=[{x:r,y:n},{x:o,y:i},{x:a,y:s}].sort((I,w)=>I.y-w.y),[m,g,C]=p,x=y((I,w,U)=>{let P=Math.round(Math.min(w,U)),E=Math.round(Math.max(w,U));for(let v=P;v<=E;v++)if(v>=0&&v<this.currentWidth&&I>=0&&I<this.currentHeight){let S=I*this.currentWidth+v;t.set(S,c,u,l)}},"drawLine"),O=y((I,w,U,P,E)=>P===w?U:U+(I-w)*(E-U)/(P-w),"interpolate");for(let I=m.y;I<=g.y;I++){let w=O(I,m.y,m.x,C.y,C.x),U=O(I,m.y,m.x,g.y,g.x);x(I,w,U)}for(let I=g.y+1;I<=C.y;I++){let w=O(I,m.y,m.x,C.y,C.x),U=O(I,g.y,g.x,C.y,C.x);x(I,w,U)}}else this.drawLineSegment(r,n,o,i,c,l,u,t),this.drawLineSegment(o,i,a,s,c,l,u,t),this.drawLineSegment(a,s,r,n,c,l,u,t)}drawLineSegment(e,t,r,n,o,i,a,s){let d=Math.abs(r-e),c=Math.abs(n-t),l=e<r?1:-1,u=t<n?1:-1,p=d-c,m=e,g=t;for(;this.setCell(m,g,o,i,a,s),!(m===r&&g===n);){let C=2*p;C>-c&&(p-=c,m+=l),C<d&&(p+=d,g+=u)}}rasterizeDotCloud(e,t){let{charCode:r,bgColorCode:n,fgColorCode:o,positions:i}=e,a=this.currentWidth;for(let s=0;s<i.length;s++){let d=i[s];if(d.posX<0||d.posX>=a||d.posY<0||d.posY>=this.currentHeight)continue;let c=d.posY*a+d.posX;t.set(c,r,o,n)}}rasterizeDotCloudMultiColor(e,t){let{dots:r}=e;for(let n of r)this.setCell(n.posX,n.posY,n.charCode,n.bgColorCode,n.fgColorCode,t)}rasterizeBitmask(e,t){let{posX:r,posY:n,sizeX:o,sizeY:i,charCode:a,bgColorCode:s,fgColorCode:d,override:c,mask:l}=e;for(let u=0;u<i;u++){let p=n+u;if(!(p<0||p>=this.currentHeight))for(let m=0;m<o;m++){let g=r+m;if(g<0||g>=this.currentWidth)continue;let C=u*o+m,x=Math.floor(C/8),O=C%8,I=(l[x]&1<<O)!==0,w=p*this.currentWidth+g;I?t.set(w,a,d,s):c&&t.set(w,255,255,255)}}}rasterizeBitmask4(e,t){let{posX:r,posY:n,sizeX:o,sizeY:i,override:a,variants:s,mask:d}=e;for(let c=0;c<i;c++){let l=n+c;if(!(l<0||l>=this.currentHeight))for(let u=0;u<o;u++){let p=r+u;if(p<0||p>=this.currentWidth)continue;let m=c*o+u,g=Math.floor(m/4),C=m%4*2,x=d[g]>>C&3,O=l*this.currentWidth+p;if(x>0){let I=s[x-1];t.set(O,I.charCode,I.fgColorCode,I.bgColorCode)}else a&&t.set(O,255,255,255)}}}rasterizeBitmask16(e,t){let{posX:r,posY:n,sizeX:o,sizeY:i,override:a,variants:s,mask:d}=e;for(let c=0;c<i;c++){let l=n+c;if(!(l<0||l>=this.currentHeight))for(let u=0;u<o;u++){let p=r+u;if(p<0||p>=this.currentWidth)continue;let m=c*o+u,g=Math.floor(m/2),C=m%2*4,x=d[g]>>C&15,O=l*this.currentWidth+p;if(x>0){let I=s[x-1];t.set(O,I.charCode,I.fgColorCode,I.bgColorCode)}else a&&t.set(O,255,255,255)}}}rasterizeClear(e,t){let{charCode:r,bgColorCode:n,fgColorCode:o}=e;t.clearWithColor(r,o,n)}rasterizeFillChar(e,t){let{patternWidth:r,patternHeight:n,pattern:o,bgColorCode:i,fgColorCode:a}=e;for(let s=0;s<this.currentHeight;s++)for(let d=0;d<this.currentWidth;d++){let c=d%r,u=s%n*r+c;if(u<o.length){let p=s*this.currentWidth+d;t.set(p,o[u],a,i)}}}rasterizeSprite(e,t,r){if(!r)return;let{posX:n,posY:o,spriteIndex:i,bgColorCode:a,fgColorCode:s}=e,d=r.getUnicolorSprite(i);if(!d)return;let c=d.data;for(let l=0;l<d.sizeY;l++)for(let u=0;u<d.sizeX;u++){let p=n+u,m=o+l;if(!this.isInBounds(p,m))continue;let g=l*d.sizeX+u,C=c.get(g);this.setCell(p,m,C,a,s,t)}}rasterizeSpriteMultiColor(e,t,r){if(!r)return;let{posX:n,posY:o,spriteIndex:i}=e,a=r.getMulticolorSprite(i);if(!a)return;let s=a.data;for(let d=0;d<a.sizeY;d++)for(let c=0;c<a.sizeX;c++){let l=n+c,u=o+d;if(!this.isInBounds(l,u))continue;let p=d*a.sizeX+c,m=s.getCharCode(p),g=s.getFgColorCode(p),C=s.getBgColorCode(p);this.setCell(l,u,m,C,g,t)}}rasterizeSpriteCloud(e,t,r){if(!r)return;let{spriteIndex:n,bgColorCode:o,fgColorCode:i,positions:a}=e,s=r.getUnicolorSprite(n);if(s){if(s.sizeX===1&&s.sizeY===1){let d=s.data.get(0),c=this.currentWidth;for(let l=0;l<a.length;l++){let u=a[l];if(u.posX<0||u.posX>=c||u.posY<0||u.posY>=this.currentHeight)continue;let p=u.posY*c+u.posX;t.set(p,d,i,o)}return}for(let d=0;d<a.length;d++){let c=s.data;for(let l=0;l<s.sizeY;l++)for(let u=0;u<s.sizeX;u++){let p=a[d].posX+u,m=a[d].posY+l;if(!this.isInBounds(p,m))continue;let g=l*s.sizeX+u,C=c.get(g);this.setCell(p,m,C,o,i,t)}}}}rasterizeSpriteCloudMultiColor(e,t,r){if(!r)return;let{spriteIndex:n,positions:o}=e,i=r.getMulticolorSprite(n);if(i)for(let a=0;a<o.length;a++){let s=i.data;for(let d=0;d<i.sizeY;d++)for(let c=0;c<i.sizeX;c++){let l=o[a].posX+c,u=o[a].posY+d;if(!this.isInBounds(l,u))continue;let p=d*i.sizeX+c,m=s.getCharCode(p),g=s.getFgColorCode(p),C=s.getBgColorCode(p);this.setCell(l,u,m,C,g,t)}}}rasterizeSpriteCloudVaried(e,t,r){if(!r)return;let{sprites:n}=e;for(let o=0;o<n.length;o++){let i=n[o],a=r.getUnicolorSprite(i.spriteIndex);if(!a)continue;let s=a.data;for(let d=0;d<a.sizeY;d++)for(let c=0;c<a.sizeX;c++){let l=i.posX+c,u=i.posY+d;if(!this.isInBounds(l,u))continue;let p=d*a.sizeX+c,m=s.get(p);this.setCell(l,u,m,i.bgColorCode,i.fgColorCode,t)}}}rasterizeSpriteCloudVariedMultiColor(e,t,r){if(!r)return;let{sprites:n}=e;for(let o=0;o<n.length;o++){let i=n[o],a=r.getMulticolorSprite(i.spriteIndex);if(!a)continue;let s=a.data;for(let d=0;d<a.sizeY;d++)for(let c=0;c<a.sizeX;c++){let l=i.posX+c,u=i.posY+d;if(!this.isInBounds(l,u))continue;let p=d*a.sizeX+c,m=s.getCharCode(p),g=s.getFgColorCode(p),C=s.getBgColorCode(p);this.setCell(l,u,m,C,g,t)}}}rasterizeFillSprite(e,t,r){if(!r)return;let{spriteIndex:n,bgColorCode:o,fgColorCode:i}=e,a=r.getUnicolorSprite(n);if(!a)return;let s=a.data;for(let d=0;d<this.currentHeight;d++)for(let c=0;c<this.currentWidth;c++){let l=c%a.sizeX,p=d%a.sizeY*a.sizeX+l,m=s.get(p),g=d*this.currentWidth+c;t.set(g,m,i,o)}}rasterizeFillSpriteMultiColor(e,t,r){if(!r)return;let{spriteIndex:n}=e,o=r.getMulticolorSprite(n);if(!o)return;let i=o.data;for(let a=0;a<this.currentHeight;a++)for(let s=0;s<this.currentWidth;s++){let d=s%o.sizeX,l=a%o.sizeY*o.sizeX+d,u=i.getCharCode(l),p=i.getFgColorCode(l),m=i.getBgColorCode(l),g=a*this.currentWidth+s;t.set(g,u,p,m)}}setCell(e,t,r,n,o,i){if(!this.isInBounds(e,t))return;let a=t*this.currentWidth+e;i.set(a,r,o,n)}isInBounds(e,t){return e>=0&&e<this.currentWidth&&t>=0&&t<this.currentHeight}};y(ht,"LayerRasterizer");var Re=ht;var Y=class Y{constructor(e,t,r,n,o){b(this,"id",0);b(this,"origin");b(this,"orders",[]);b(this,"zOrder",0);b(this,"data");b(this,"width");b(this,"height");b(this,"isStatic",!1);b(this,"spriteRegistry");b(this,"mode","server");b(this,"charCodeMode");b(this,"previousOrigin");b(this,"previousZOrder");b(this,"enabled",!0);b(this,"useSetMode",!1);b(this,"needsCommit",!1);if(r<1||r>256||n<1||n>256)throw new Error(`Layer size must be 1-256, got ${r}\xD7${n}`);let i={};typeof o=="boolean"?i={isStatic:o}:o&&(i=o),this.origin=e,this.zOrder=t,this.width=r,this.height=n,this.isStatic=i.isStatic??!1,this.charCodeMode=i.charCodeMode??"8bit";let a=this.charCodeMode==="16bit";this.data=new G(r*n,a),this.previousOrigin=new Wn(e.x,e.y),this.previousZOrder=t}getCharCodeMode(){return this.charCodeMode}setMode(e){this.mode=e}setSpriteRegistry(e){this.spriteRegistry=e}getOrders(){return this.orders}addOrders(e){this.orders.push(...e),this.useSetMode=!1,(this.mode==="client"||this.mode==="standalone")&&Y.rasterizer.rasterizeOrders(this.orders,this.data,this.width,this.height,this.spriteRegistry)}addTemporaryOrders(e){(this.mode==="client"||this.mode==="standalone")&&Y.rasterizer.rasterizeOrders(e,this.data,this.width,this.height,this.spriteRegistry)}setOrders(e){this.orders=e,this.useSetMode=!0,(this.mode==="client"||this.mode==="standalone")&&Y.rasterizer.rasterizeOrders(e,this.data,this.width,this.height,this.spriteRegistry)}clearOrders(){this.orders=[],(this.mode==="client"||this.mode==="standalone")&&Y.rasterizer.clearBuffer(this.data)}getOrigin(){return this.origin}setOrigin(e){this.origin=e}getZOrder(){return this.zOrder}setZOrder(e){this.zOrder=e}getId(){return this.id}setId(e){this.id=e}getData(){return this.data}getWidth(){return this.width}getHeight(){return this.height}getCellAt(e,t){return e<0||e>=this.width||t<0||t>=this.height?null:this.data.get(t*this.width+e)}setStatic(e){this.isStatic=e}getStatic(){return this.isStatic}setEnabled(e){this.enabled=e}isEnabled(){return this.enabled}hasOriginChanged(){return this.origin.x!==this.previousOrigin.x||this.origin.y!==this.previousOrigin.y}hasZOrderChanged(){return this.zOrder!==this.previousZOrder}calculateUpdateFlags(){if(!this.enabled)return 0;let e=1;return this.useSetMode&&(e|=2),this.hasOriginChanged()&&(e|=4),this.hasZOrderChanged()&&(e|=8),(this.orders.length>0||this.needsCommit&&this.useSetMode)&&(e|=4),e}resetChangeTracking(){this.previousOrigin.x=this.origin.x,this.previousOrigin.y=this.origin.y,this.previousZOrder=this.zOrder}commit(){this.needsCommit=!0}getNeedsCommit(){return this.needsCommit}resetCommit(){this.needsCommit=!1}};y(Y,"Layer"),b(Y,"rasterizer",new Re);var ae=Y;var bt=class bt{constructor(){b(this,"macros",new Map);b(this,"macroNameToId",new Map);b(this,"nextMacroId",0);b(this,"instances",new Map);b(this,"instanceNameToId",new Map);b(this,"nextInstanceId",0);b(this,"layerNameToId",new Map);b(this,"pendingOrders",[])}registerMacro(e){let t=e.id;if(this.macroNameToId.has(t)){let o=this.macroNameToId.get(t);return this.macros.set(o,{macroId:o,name:t,template:e}),o}let r=this.nextMacroId++;if(r>255)throw new Error("Maximum macro count (256) exceeded");let n={macroId:r,name:t,template:e};return this.macros.set(r,n),this.macroNameToId.set(t,r),r}getMacroByName(e){let t=this.macroNameToId.get(e);return t!==void 0?this.macros.get(t):void 0}getMacroById(e){return this.macros.get(e)}getMacroId(e){return this.macroNameToId.get(e)}toMacroLoad(e){let t=this.macros.get(e);if(t)return{loadType:7,macroId:t.macroId,template:t.template}}toAllMacroLoads(){let e=[];for(let t of this.macros.values())e.push({loadType:7,macroId:t.macroId,template:t.template});return e}setLayerMapping(e,t){this.layerNameToId.set(e,t)}createInstance(e){let t=this.macroNameToId.get(e.macro);if(t===void 0){console.warn(`MacroRegistry: Unknown macro "${e.macro}"`);return}let r=this.layerNameToId.get(e.layer);if(r===void 0){console.warn(`MacroRegistry: Unknown layer "${e.layer}"`);return}if(this.instanceNameToId.has(e.id))return console.warn(`MacroRegistry: Instance "${e.id}" already exists`),this.instanceNameToId.get(e.id);let n=this.nextInstanceId++;if(n>255)throw new Error("Maximum instance count (256) exceeded");let o={instanceId:n,name:e.id,macroId:t,layerId:r,x:e.x,y:e.y,tabIndex:e.tabIndex??0,params:e.params??{}};this.instances.set(n,o),this.instanceNameToId.set(e.id,n);let i={type:1,instanceId:n,macroId:t,layerId:r,x:e.x,y:e.y,tabIndex:e.tabIndex??0,params:e.params??{}};return this.pendingOrders.push(i),n}updateInstance(e,t){let r=this.instanceNameToId.get(e);if(r===void 0)return!1;let n=this.instances.get(r);if(!n)return!1;for(let i in t)n.params[i]=t[i];let o={type:2,instanceId:r,params:t};return this.pendingOrders.push(o),!0}removeInstance(e){let t=this.instanceNameToId.get(e);if(t===void 0)return!1;this.instances.delete(t),this.instanceNameToId.delete(e);let r={type:3,instanceId:t};return this.pendingOrders.push(r),!0}getInstanceByName(e){let t=this.instanceNameToId.get(e);return t!==void 0?this.instances.get(t):void 0}getInstanceById(e){return this.instances.get(e)}getInstanceName(e){return this.instances.get(e)?.name}flushPendingOrders(){let e=this.pendingOrders;return this.pendingOrders=[],e}hasPendingOrders(){return this.pendingOrders.length>0}getAllInstances(){return Array.from(this.instances.values())}clearInstances(){this.instances.clear(),this.instanceNameToId.clear(),this.nextInstanceId=0,this.pendingOrders=[]}clear(){this.macros.clear(),this.macroNameToId.clear(),this.nextMacroId=0,this.clearInstances()}};y(bt,"MacroRegistry");var se=bt;function V(h){return typeof h=="number"?h:h.charCodeAt(0)}y(V,"toCharCode");function de(h){return typeof h=="string"?h.charAt(0):String.fromCharCode(h)}y(de,"toCharString");var hn=(S=>(S[S.Char=1]="Char",S[S.Text=2]="Text",S[S.TextMultiline=23]="TextMultiline",S[S.SubFrame=3]="SubFrame",S[S.SubFrameMultiColor=4]="SubFrameMultiColor",S[S.FullFrame=5]="FullFrame",S[S.FullFrameMultiColor=6]="FullFrameMultiColor",S[S.Sprite=7]="Sprite",S[S.SpriteMultiColor=8]="SpriteMultiColor",S[S.ColorMap=9]="ColorMap",S[S.Shape=10]="Shape",S[S.DotCloud=11]="DotCloud",S[S.DotCloudMultiColor=12]="DotCloudMultiColor",S[S.SpriteCloud=13]="SpriteCloud",S[S.SpriteCloudMultiColor=14]="SpriteCloudMultiColor",S[S.SpriteCloudVaried=15]="SpriteCloudVaried",S[S.SpriteCloudVariedMultiColor=16]="SpriteCloudVariedMultiColor",S[S.Bitmask=17]="Bitmask",S[S.Bitmask4=18]="Bitmask4",S[S.Bitmask16=24]="Bitmask16",S[S.Polyline=25]="Polyline",S[S.Clear=19]="Clear",S[S.FillChar=20]="FillChar",S[S.FillSprite=21]="FillSprite",S[S.FillSpriteMultiColor=22]="FillSpriteMultiColor",S))(hn||{});function Jn(h){return h>=1&&h<=2||h>=3&&h<=6||h>=7&&h<=8||h>=9&&h<=10||h>=11&&h<=18||h>=19&&h<=23||h===24||h===25}y(Jn,"isValidOrderType");function qn(h){switch(h){case 1:return"Char";case 2:return"Text";case 3:return"SubFrame";case 4:return"SubFrameMultiColor";case 5:return"FullFrame";case 6:return"FullFrameMultiColor";case 7:return"Sprite";case 8:return"SpriteMultiColor";case 9:return"ColorMap";case 10:return"Shape";case 11:return"DotCloud";case 12:return"DotCloudMultiColor";case 13:return"SpriteCloud";case 14:return"SpriteCloudMultiColor";case 15:return"SpriteCloudVaried";case 16:return"SpriteCloudVariedMultiColor";case 17:return"Bitmask";case 18:return"Bitmask4";case 24:return"Bitmask16";case 25:return"Polyline";case 19:return"Clear";case 20:return"FillChar";case 21:return"FillSprite";case 22:return"FillSpriteMultiColor";default:return`Unknown(0x${h.toString(16)})`}}y(qn,"getOrderTypeName");var Kn={single:{topLeft:"\u250C",topRight:"\u2510",bottomLeft:"\u2514",bottomRight:"\u2518",horizontal:"\u2500",vertical:"\u2502"},double:{topLeft:"\u2554",topRight:"\u2557",bottomLeft:"\u255A",bottomRight:"\u255D",horizontal:"\u2550",vertical:"\u2551"},rounded:{topLeft:"\u256D",topRight:"\u256E",bottomLeft:"\u2570",bottomRight:"\u256F",horizontal:"\u2500",vertical:"\u2502"}},gt={update(h,e,t,r){let n,o;e.subtype==="button"&&e.button?(n=t.resolveValue(e.button.width,h.params),o=t.resolveValue(e.button.height??3,h.params)):(n=t.resolveValue(h.params.width??1,h.params),o=t.resolveValue(h.params.height??1,h.params));let i=h.isHovered;h.isHovered=Qn(t.mouseX,t.mouseY,h.x,h.y,n,o);let a=h.isActive;h.isActive=h.isHovered&&t.mouseDown,a&&!h.isActive&&h.isHovered&&(r.push({instanceId:h.instanceId,event:"click"}),e.subtype==="button"&&e.button?.soundRelease!==void 0&&t.playSound?.(e.button.soundRelease)),e.subtype==="button"&&e.button&&(!i&&h.isHovered&&e.button.soundHover!==void 0&&t.playSound?.(e.button.soundHover),!a&&h.isActive&&e.button.soundClick!==void 0&&t.playSound?.(e.button.soundClick))},render(h,e,t){let r=bn(h),n=e.states[r]??e.states.normal,o={...h.params,...n},i=[];if(e.subtype==="button"&&e.button)eo(h,e,o,i,t);else if(e.base)for(let a of e.base){let s=no(a,h.x,h.y,o,t);s&&i.push(s)}return i}};function Qn(h,e,t,r,n,o){return h>=t&&h<t+n&&e>=r&&e<r+o}y(Qn,"isPointInRect");function bn(h){return h.isDisabled?"disabled":h.isActive?"active":h.isHovered?"hover":h.isFocused?"focused":"normal"}y(bn,"getUIState");function ce(h){if(typeof h=="number")return Math.max(0,Math.min(255,Math.floor(h)));if(typeof h=="string"){let e=parseInt(h,10);if(!isNaN(e))return Math.max(0,Math.min(255,Math.floor(e)))}return 243}y(ce,"toColorIndex");function eo(h,e,t,r,n){let o=e.button,i=bn(h),a=e.states[i]??e.states.normal,s=n.resolveValue(o.width,t),d=n.resolveValue(o.height??3,t),c=n.resolveValue(o.label,t),l=o.border??"single",u=n.resolveValue(a.fg??15,t),p=n.resolveValue(a.bg??0,t),m=n.resolveValue(a.textFg??u,t),g=a.offsetY??0,C=h.x,x=h.y+g;l==="none"?to(C,x,s,d,c,u,p,m,r):ro(C,x,s,d,c,u,p,m,l,r)}y(eo,"renderButton");function to(h,e,t,r,n,o,i,a,s){if(r===1)s.push({type:2,posX:h,posY:e,text:" ".repeat(t),fgColorCode:o,bgColorCode:i});else for(let l=0;l<r;l++)s.push({type:2,posX:h,posY:e+l,text:" ".repeat(t),fgColorCode:o,bgColorCode:i});let d=h+Math.floor((t-n.length)/2),c=e+Math.floor(r/2);s.push({type:2,posX:d,posY:c,text:n,fgColorCode:a,bgColorCode:i})}y(to,"renderButtonNoBorder");function ro(h,e,t,r,n,o,i,a,s,d){let c=Kn[s];d.push({type:2,posX:h,posY:e,text:c.topLeft+c.horizontal.repeat(t-2)+c.topRight,fgColorCode:o,bgColorCode:i});for(let g=1;g<r-1;g++)d.push({type:2,posX:h,posY:e+g,text:c.vertical+" ".repeat(t-2)+c.vertical,fgColorCode:o,bgColorCode:i});d.push({type:2,posX:h,posY:e+r-1,text:c.bottomLeft+c.horizontal.repeat(t-2)+c.bottomRight,fgColorCode:o,bgColorCode:i});let l=t-2,u=r-2,p=h+1+Math.floor((l-n.length)/2),m=e+1+Math.floor(u/2);d.push({type:2,posX:p,posY:m,text:n,fgColorCode:a,bgColorCode:i})}y(ro,"renderButtonWithBorder");function no(h,e,t,r,n){if(h.fillRect){let[o,i,a,s,d,c,l]=h.fillRect;return{type:3,posX:e+n.resolveValue(o,r),posY:t+n.resolveValue(i,r),sizeX:n.resolveValue(a,r),sizeY:n.resolveValue(s,r),fgColorCode:ce(n.resolveValue(c,r)),bgColorCode:ce(n.resolveValue(l,r)),frame:Array(n.resolveValue(a,r)*n.resolveValue(s,r)).fill(V(d))}}if(h.text){let[o,i,a,s]=h.text;return{type:2,posX:e+n.resolveValue(o,r),posY:t+n.resolveValue(i,r),text:n.resolveValue(a,r),fgColorCode:ce(n.resolveValue(s,r)),bgColorCode:255}}if(h.setCell){let[o,i,a,s,d]=h.setCell;return{type:1,posX:e+n.resolveValue(o,r),posY:t+n.resolveValue(i,r),charCode:V(n.resolveValue(a,r)),fgColorCode:ce(n.resolveValue(s,r)),bgColorCode:ce(n.resolveValue(d,r))}}return null}y(no,"executeRenderCommand");function gn(h,e,t,r,n,o,i){return{type:"ui",instanceId:h,macroId:e,layerId:t,x:r,y:n,params:o,tabIndex:i,isHovered:!1,isFocused:!1,isActive:!1,isDisabled:!1}}y(gn,"createUIInstance");var Ct=class Ct{update(e,t,r,n){let o=t.emitter,{resolveValue:i}=r;if(!e.emitDone){if(o.burst){let a=i(o.burst,e.params);for(let s=0;s<a&&!(o.limit&&e.particles.length>=o.limit);s++)e.particles.push(this.createParticle(e,t,r));o.once&&(e.emitDone=!0)}else if(o.rate){let a=i(o.rate,e.params);for(e.timeSinceEmit+=a;e.timeSinceEmit>=1&&!(o.limit&&e.particles.length>=o.limit);)e.particles.push(this.createParticle(e,t,r)),e.timeSinceEmit-=1}}for(let a=e.particles.length-1;a>=0;a--){let s=e.particles[a];s.x+=s.vx,s.y+=s.vy,s.lifetime-=1,s.lifetime<=0&&e.particles.splice(a,1)}}render(e,t,r){if(e.particles.length===0)return[];let{resolveValue:n}=r,o=t.emitter,i=o.viewport??o.zone,a=n(i.x,e.params),s=n(i.y,e.params),d=n(i.width,e.params),c=n(i.height,e.params),l=e.x+(typeof a=="number"?a:0),u=e.y+(typeof s=="number"?s:0),p=typeof d=="number"?d:0,m=typeof c=="number"?c:0;if(p<=0||m<=0)return[];let g=[];for(let C of e.particles){let x=Math.floor(C.x),O=Math.floor(C.y);if(x<l||x>=l+p||O<u||O>=u+m)continue;let I=C.fg;if(t.particle.fade&&C.maxLifetime>0){let w=C.lifetime/C.maxLifetime;I=this.fadeColorIndex(C.fg,w)}g.push({charCode:V(C.char),fgColorCode:I,bgColorCode:C.bg??255,posX:x,posY:O})}return[{type:12,dots:g}]}createParticle(e,t,r){let{resolveValue:n,resolveRandomValue:o}=r,i=t.emitter,a=t.particle,s=n(i.zone.x,e.params),d=n(i.zone.y,e.params),c=n(i.zone.width,e.params),l=n(i.zone.height,e.params),u=e.x+s+Math.random()*c,p=e.y+d+Math.random()*l,m=0,g=0;if("x"in a.velocity&&"y"in a.velocity)m=n(a.velocity.x,e.params),g=n(a.velocity.y,e.params);else if("angle"in a.velocity&&"speed"in a.velocity){let E=o(a.velocity.angle),v=o(a.velocity.speed,e.params),S=E*Math.PI/180;m=Math.cos(S)*v,g=Math.sin(S)*v}let C=o(a.lifetime),x=Array.isArray(a.char)?a.char[Math.floor(Math.random()*a.char.length)]:a.char,O=de(x),I=Array.isArray(a.fg)?a.fg[Math.floor(Math.random()*a.fg.length)]:a.fg,w=typeof I=="number"?I:parseInt(I,10)||243,U=a.bg?Array.isArray(a.bg)?a.bg[Math.floor(Math.random()*a.bg.length)]:a.bg:void 0,P=U!==void 0?typeof U=="number"?U:parseInt(U,10)||255:void 0;return{x:u,y:p,vx:m,vy:g,char:O,fg:w,bg:P,lifetime:C,maxLifetime:C}}fadeColorIndex(e,t){return t<.1?255:e}};y(Ct,"ParticleHandler");var Be=Ct;var xt=class xt{update(e,t,r,n){e.elapsed+=1;let o=Math.min(1,e.elapsed/e.duration),i=t.transform.decay?1-o:1,a=t.transform.offset;a&&(e.currentOffsetX=this.resolveRandomOffset(a.x,e.params,r)*i,e.currentOffsetY=this.resolveRandomOffset(a.y,e.params,r)*i),e.elapsed>=e.duration&&(n.push({instanceId:e.instanceId,event:"complete"}),r.deleteInstance(e.instanceId))}render(e,t,r){return[]}getOffset(e){return{x:e.currentOffsetX,y:e.currentOffsetY}}resolveRandomOffset(e,t,r){if(typeof e=="number")return e;if(typeof e=="string")return r.resolveValue(e,t);if(typeof e=="object"&&"random"in e){let[n,o]=e.random,i=r.resolveValue(n,t),a=r.resolveValue(o,t);return i+Math.random()*(a-i)}return 0}};y(xt,"EffectHandler");var ze=xt;var ft=class ft{constructor(){b(this,"spriteRegistry",null)}setSpriteRegistry(e){this.spriteRegistry=e}update(e,t,r,n){if(e.finished)return;if(e.delayRemaining>0){e.delayRemaining--;return}if(e.pauseRemaining>0){e.pauseRemaining--;return}let o=t.cursor?.blinkRate??15;e.blinkTimer++,e.blinkTimer>=o&&(e.blinkTimer=0,e.blinkState=!e.blinkState);let i=e.speed;if(e.direction==="reveal"){let s=Math.min(i,e.totalCells-e.revealedCount);if(t.pauseOn&&s>0){let d=e.cells[e.revealedCount];d&&t.pauseOn.chars.includes(d.char)&&(e.pauseRemaining=t.pauseOn.duration)}e.revealedCount+=s,e.revealedCount>=e.totalCells&&(e.finished=!0,n.push({instanceId:e.instanceId,event:"complete"}))}else{let s=Math.min(i,e.revealedCount);e.revealedCount-=s,e.revealedCount<=0&&(e.finished=!0,n.push({instanceId:e.instanceId,event:"complete"}))}}render(e,t,r){let n=[],o=e.cells.slice(0,e.revealedCount),i=new Map;for(let a of o)i.has(a.y)||i.set(a.y,[]),i.get(a.y).push(a);for(let[a,s]of i){s.sort((c,l)=>c.x-l.x);let d=0;for(;d<s.length;){let c=s[d],l=d+1;for(;l<s.length&&s[l].x===s[l-1].x+1&&s[l].fg===c.fg&&s[l].bg===c.bg;)l++;if(l-d===1)n.push({type:1,posX:e.x+c.x,posY:e.y+a,charCode:c.char.charCodeAt(0),fgColorCode:c.fg,bgColorCode:c.bg});else{let p="";for(let m=d;m<l;m++)p+=s[m].char;n.push({type:2,posX:e.x+c.x,posY:e.y+a,text:p,fgColorCode:c.fg,bgColorCode:c.bg})}d=l}}if(t.cursor&&!e.finished&&(!t.cursor.blink||e.blinkState)&&e.revealedCount<e.cells.length){let s=e.cells[e.revealedCount];if(s){let d=t.cursor.bg??s.bg;n.push({type:1,posX:e.x+s.x,posY:e.y+s.y,charCode:V(t.cursor.char),fgColorCode:t.cursor.fg??15,bgColorCode:d})}}return n}buildCells(e,t,r){let n=[],o=e.content;switch(o.type){case"text":{let i=r(o.text,t),a=r(o.fg??15,t),s=r(o.bg??0,t),d=i.split(`
|
|
3
|
-
`);for(let c=0;c<d.length;c++){let l=d[c];for(let u=0;u<l.length;u++)n.push({char:l[u],fg:a,bg:s,x:u,y:c,revealOrder:0})}break}case"sprite":{if(!this.spriteRegistry)break;let i=r(o.sprite,t);if(o.multicolor!==!1){let d=this.spriteRegistry.getMulticolorSprite(i);if(d){let{sizeX:c,sizeY:l,data:u}=d;for(let p=0;p<l;p++)for(let m=0;m<c;m++){let g=p*c+m,C=u.get(g);C.charCode!==0&&n.push({char:String.fromCharCode(C.charCode),fg:C.fgColorCode,bg:C.bgColorCode,x:m,y:p,revealOrder:0})}break}}let s=this.spriteRegistry.getUnicolorSprite(i);if(s){let{sizeX:d,sizeY:c,data:l}=s,u=r(o.fg??15,t),p=r(o.bg??0,t);for(let m=0;m<c;m++)for(let g=0;g<d;g++){let C=m*d+g,x=l.get(C);x!==0&&n.push({char:String.fromCharCode(x),fg:u,bg:p,x:g,y:m,revealOrder:0})}}break}case"cells":{for(let i of o.cells)n.push({char:de(i.char),fg:i.fg,bg:i.bg,x:i.x,y:i.y,revealOrder:0});break}case"fill":{let i=de(o.char),a=r(o.fg,t),s=r(o.bg,t),d=r(o.width,t),c=r(o.height,t);for(let l=0;l<c;l++)for(let u=0;u<d;u++)n.push({char:i,fg:a,bg:s,x:u,y:l,revealOrder:0});break}}return this.assignRevealOrder(n,e.pattern,e.direction),n}assignRevealOrder(e,t,r){if(e.length===0)return;let n=0,o=0;for(let s of e)s.x>n&&(n=s.x),s.y>o&&(o=s.y);let i=n+1,a=o+1;switch(t){case"typewriter":for(let s of e)s.revealOrder=s.y*i+s.x;break;case"typewriter-rev":for(let s of e)s.revealOrder=(a-1-s.y)*i+(i-1-s.x);break;case"ltr":for(let s of e)s.revealOrder=s.x*a+s.y;break;case"rtl":for(let s of e)s.revealOrder=(i-1-s.x)*a+s.y;break;case"ttb":for(let s of e)s.revealOrder=s.y;break;case"btt":for(let s of e)s.revealOrder=a-1-s.y;break;case"random":{let s=e.map((d,c)=>c);for(let d=s.length-1;d>0;d--){let c=Math.floor(Math.random()*(d+1));[s[d],s[c]]=[s[c],s[d]]}for(let d=0;d<e.length;d++)e[d].revealOrder=s[d];break}case"center-out":{let s=(i-1)/2,d=(a-1)/2;for(let c of e)c.revealOrder=Math.abs(c.x-s)+Math.abs(c.y-d);break}case"spiral":{let s=(i-1)/2,d=(a-1)/2,c=Math.max(s,d);for(let l of e){let u=Math.abs(l.x-s),p=Math.abs(l.y-d),m=Math.max(u,p);l.revealOrder=c-m+(l.y*i+l.x)*.001}break}}e.sort((s,d)=>s.revealOrder-d.revealOrder);for(let s=0;s<e.length;s++)e[s].revealOrder=s}};y(ft,"RevealHandler");var Te=ft;var St=class St{update(e,t,r,n){let{resolveValue:o}=r,i=e.params;e.currentTick++;let a=i.point;if(a&&typeof a.x=="number"&&typeof a.y=="number"){e.points.push({x:a.x,y:a.y,addedAt:e.currentTick}),delete i.point;let d=o(t.maxPoints,i)??100;for(;e.points.length>d;)e.points.shift()}i.clear===!0&&(e.points=[],delete i.clear);let s=i.points;if(Array.isArray(s)){e.points=s.map(c=>({x:c.x,y:c.y,addedAt:e.currentTick})),delete i.points;let d=o(t.maxPoints,i)??100;for(;e.points.length>d;)e.points.shift()}}render(e,t,r){let{resolveValue:n}=r,o=e.params,i=e.points;if(i.length===0)return[];let a=n(t.char,o),s=n(t.fg,o)??15,d=n(t.bg,o)??255,c=t.closed??!1,l=t.fadeOut??!1,u=i.map(m=>({x:e.x+m.x,y:e.y+m.y}));return c&&u.length>=2&&u.push({...u[0]}),l&&i.length>=2?this.renderFadedLine(e,t,r,u,a,s,d):[{type:25,charCode:V(a),fgColorCode:s,bgColorCode:d,points:u.map(m=>({x:m.x&255,y:m.y&255}))}]}renderFadedLine(e,t,r,n,o,i,a){let s=e.params,d=t.fadeLength??n.length,c=[],l=n.length,u=Math.max(0,l-d);if(u>0){let m=n.slice(0,u+1);m.length>=2&&c.push({type:25,charCode:V(o),fgColorCode:i,bgColorCode:a,points:m.map(g=>({x:g.x&255,y:g.y&255}))})}let p=n.slice(u);if(p.length>=2){let m=Math.max(0,i-8);c.push({type:25,charCode:V(o),fgColorCode:m,bgColorCode:a,points:p.map(g=>({x:g.x&255,y:g.y&255}))})}return c}};y(St,"LineHandler");var Fe=St;var io=!1;function j(...h){io&&console.log("[MacroEngine]",...h)}y(j,"macroLog");var It=class It{constructor(){b(this,"templates",new Map);b(this,"instances",new Map);b(this,"spriteRegistry",null);b(this,"playSound",null);b(this,"focusedInstanceId",null);b(this,"focusableInstances",[]);b(this,"mouseX",0);b(this,"mouseY",0);b(this,"mouseDown",!1);b(this,"particleHandler",new Be);b(this,"effectHandler",new ze);b(this,"revealHandler",new Te);b(this,"lineHandler",new Fe);b(this,"instancesToDelete",[])}setSpriteRegistry(e){this.spriteRegistry=e,this.revealHandler.setSpriteRegistry(e)}setAudioCallback(e){this.playSound=e}createContext(){return{mouseX:this.mouseX,mouseY:this.mouseY,mouseDown:this.mouseDown,playSound:this.playSound??void 0,getTemplate:e=>this.getTemplate(e),resolveValue:(e,t)=>this.resolveValue(e,t),resolveRandomValue:(e,t)=>this.resolveRandomValue(e,t),deleteInstance:e=>{this.instancesToDelete.push(e)}}}loadTemplate(e,t){j(`loadTemplate: macroId=${e}, type=${t.type}`),this.templates.set(e,{macroId:e,template:t})}getTemplate(e){return this.templates.get(e)?.template}hasTemplate(e){return this.templates.has(e)}applyOrder(e){switch(j(`applyOrder: type=${e.type}, instanceId=${e.instanceId}`),e.type){case 1:this.createInstance(e);break;case 2:this.updateInstance(e);break;case 3:this.removeInstance(e);break}}createInstance(e){let t=this.getTemplate(e.macroId);if(!t){j(`createInstance: FAILED - template ${e.macroId} not found`);return}j(`createInstance: id=${e.instanceId}, macroId=${e.macroId}, type=${t.type}, pos=(${e.x}, ${e.y}), layer=${e.layerId}`);let r;switch(t.type){case"ui":r=gn(e.instanceId,e.macroId,e.layerId,e.x,e.y,e.params,e.tabIndex),e.tabIndex>0&&this.addToFocusableList(e.instanceId,e.tabIndex);break;case"particle":r={type:"particle",instanceId:e.instanceId,macroId:e.macroId,layerId:e.layerId,x:e.x,y:e.y,params:e.params,particles:[],timeSinceEmit:0,emitDone:!1};break;case"effect":{let n=t;r={type:"effect",instanceId:e.instanceId,macroId:e.macroId,layerId:e.layerId,x:e.x,y:e.y,params:e.params,elapsed:0,duration:this.resolveValue(n.transform.duration,e.params),currentOffsetX:0,currentOffsetY:0};break}case"reveal":{let n=t,o=this.revealHandler.buildCells(n,e.params,(s,d)=>this.resolveValue(s,d)),i=o.length,a=n.direction??"reveal";r={type:"reveal",instanceId:e.instanceId,macroId:e.macroId,layerId:e.layerId,x:e.x,y:e.y,params:e.params,cells:o,revealedCount:a==="hide"?i:0,totalCells:i,delayRemaining:n.delay??0,pauseRemaining:0,finished:!1,direction:a,speed:n.speed??1,blinkState:!0,blinkTimer:0};break}case"line":{let n=[],o=e.params.points;if(Array.isArray(o)){for(let a of o)n.push({x:a.x,y:a.y,addedAt:0});delete e.params.points}let i=e.params.point;i&&typeof i.x=="number"&&typeof i.y=="number"&&(n.push({x:i.x,y:i.y,addedAt:0}),delete e.params.point),r={type:"line",instanceId:e.instanceId,macroId:e.macroId,layerId:e.layerId,x:e.x,y:e.y,params:e.params,points:n,currentTick:0};break}default:return}r&&this.instances.set(e.instanceId,r)}updateInstance(e){let t=this.instances.get(e.instanceId);if(t)for(let r in e.params)t.params[r]=e.params[r]}removeInstance(e){let t=this.instances.get(e.instanceId);t&&(t.type==="ui"&&(this.removeFromFocusableList(e.instanceId),this.focusedInstanceId===e.instanceId&&(this.focusedInstanceId=null)),this.instances.delete(e.instanceId))}addToFocusableList(e,t){this.focusableInstances.push(e),this.focusableInstances.sort((r,n)=>{let o=this.instances.get(r),i=this.instances.get(n);return(o?.tabIndex??0)-(i?.tabIndex??0)})}removeFromFocusableList(e){let t=this.focusableInstances.indexOf(e);t!==-1&&this.focusableInstances.splice(t,1)}focusNext(){if(this.focusableInstances.length===0)return;let t=((this.focusedInstanceId!==null?this.focusableInstances.indexOf(this.focusedInstanceId):-1)+1)%this.focusableInstances.length;this.setFocus(this.focusableInstances[t])}focusPrevious(){if(this.focusableInstances.length===0)return;let t=((this.focusedInstanceId!==null?this.focusableInstances.indexOf(this.focusedInstanceId):0)-1+this.focusableInstances.length)%this.focusableInstances.length;this.setFocus(this.focusableInstances[t])}setFocus(e){if(this.focusedInstanceId!==null){let t=this.instances.get(this.focusedInstanceId);t?.type==="ui"&&(t.isFocused=!1)}if(this.focusedInstanceId=e,e!==null){let t=this.instances.get(e);t?.type==="ui"&&(t.isFocused=!0)}}updateMouse(e,t,r){this.mouseX=e,this.mouseY=t,this.mouseDown=r}estimateUISize(e,t){if(e.subtype==="button"&&e.button){let o=this.resolveValue(e.button.width,t??{}),i=this.resolveValue(e.button.height??3,t??{});return{width:o,height:i}}let r=1,n=1;if(e.base)for(let o of e.base)"w"in o&&typeof o.w=="number"&&(r=Math.max(r,o.w)),"h"in o&&typeof o.h=="number"&&(n=Math.max(n,o.h));return{width:r,height:n}}activateFocused(){if(this.focusedInstanceId===null)return;let e=this.instances.get(this.focusedInstanceId);e?.type==="ui"&&(e.isActive=!0)}update(){let e=[];this.instances.size>0&&j(`update: instances=${this.instances.size}, templates=${this.templates.size}`);let t=this.createContext();this.instancesToDelete=[];for(let n of this.instances.values()){let o=this.getTemplate(n.macroId);if(o)switch(n.type){case"ui":gt.update(n,o,t,e);break;case"particle":this.particleHandler.update(n,o,t,e);break;case"effect":this.effectHandler.update(n,o,t,e);break;case"reveal":this.revealHandler.update(n,o,t,e);break;case"line":this.lineHandler.update(n,o,t,e);break}}for(let n of this.instancesToDelete)this.instances.delete(n);return{events:e.map(n=>({instanceId:n.instanceId,event:n.event,data:n.data}))}}getOrdersByLayer(){let e=new Map;for(let t of this.instances.values()){let r=this.renderInstance(t);r.length!==0&&(e.has(t.layerId)||e.set(t.layerId,[]),e.get(t.layerId).push(...r))}if(e.size>0){let t=0;for(let r of e.values())t+=r.length;j(`getOrdersByLayer: ${e.size} layers, ${t} total orders`)}return e}renderInstance(e){let t=this.getTemplate(e.macroId);if(!t)return[];let r=this.createContext();switch(e.type){case"ui":return gt.render(e,t,r);case"particle":return this.particleHandler.render(e,t,r);case"effect":return this.effectHandler.render(e,t,r);case"reveal":return this.revealHandler.render(e,t,r);case"line":return this.lineHandler.render(e,t,r);default:return[]}}resolveValue(e,t){if(typeof e=="string"&&e.startsWith("$")){let r=e.slice(1);return t[r]??e}return e}resolveRandomValue(e,t){if(typeof e=="string"){let r=this.resolveValue(e,t??{});return typeof r=="number"?r:0}if(Array.isArray(e)){let[r,n]=e;return r+Math.random()*(n-r)}return e}getEffectOffset(){let e=0,t=0;for(let r of this.instances.values())r.type==="effect"&&(e+=r.currentOffsetX,t+=r.currentOffsetY);return{x:e,y:t}}getAllInstances(){return Array.from(this.instances.values())}getInstanceCount(){return this.instances.size}clear(){this.templates.clear(),this.instances.clear(),this.focusedInstanceId=null,this.focusableInstances=[]}};y(It,"MacroEngine");var le=It;var Ot=class Ot{constructor(){b(this,"axes",new Map);b(this,"buttons",new Map);b(this,"axisNameToId",new Map);b(this,"buttonNameToId",new Map);b(this,"version",1)}defineAxis(e,t,r=[],n=-1,o=1,i=0){if(e<0||e>255)throw new Error(`Axis bindingId must be between 0 and 255, got ${e}`);if(this.axes.has(e))throw new Error(`Axis bindingId ${e} is already defined`);if(this.axisNameToId.has(t)){let s=this.axisNameToId.get(t);throw new Error(`Axis name "${t}" is already defined with bindingId ${s}`)}let a={bindingId:e,name:t,min:n,max:o,defaultValue:i,sources:r};this.axes.set(e,a),this.axisNameToId.set(t,e),this.version++}defineButton(e,t,r=[],n=!1){if(e<0||e>255)throw new Error(`Button bindingId must be between 0 and 255, got ${e}`);if(this.buttons.has(e))throw new Error(`Button bindingId ${e} is already defined`);if(this.buttonNameToId.has(t)){let i=this.buttonNameToId.get(t);throw new Error(`Button name "${t}" is already defined with bindingId ${i}`)}let o={bindingId:e,name:t,defaultValue:n,sources:r};this.buttons.set(e,o),this.buttonNameToId.set(t,e),this.version++}evaluateAxis(e,t){let r=this.axes.get(e);if(!r)return 0;let n=0;for(let i of r.sources){let s=t.get(i.sourceId)??0,d=i.deadzone??0;Math.abs(s)<d?s=0:s=(s>0?1:-1)*((Math.abs(s)-d)/(1-d));let c=i.scale??1;s*=c;let l=i.sensitivity??1;s*=l,i.invert&&(s=-s),n+=s}return Math.max(r.min,Math.min(r.max,n))}evaluateButton(e,t){let r=this.buttons.get(e);if(!r)return!1;for(let n of r.sources)if(t.get(n.sourceId)??!1)return!0;return!1}toLoadPacket(){let e={type:"input-binding",version:this.version,axes:Array.from(this.axes.values()),buttons:Array.from(this.buttons.values())};return JSON.stringify(e)}toLoadPacketObject(){return{type:"input-binding",version:this.version,axes:Array.from(this.axes.values()),buttons:Array.from(this.buttons.values())}}getAxisBindingId(e){return this.axisNameToId.get(e)??null}getButtonBindingId(e){return this.buttonNameToId.get(e)??null}getAxisName(e){return this.axes.get(e)?.name??null}getButtonName(e){return this.buttons.get(e)?.name??null}getAxisBinding(e){return this.axes.get(e)??null}getButtonBinding(e){return this.buttons.get(e)??null}hasAxis(e){return this.axes.has(e)}hasButton(e){return this.buttons.has(e)}getAxisCount(){return this.axes.size}getButtonCount(){return this.buttons.size}getAllAxes(){return Array.from(this.axes.values())}getAllButtons(){return Array.from(this.buttons.values())}getVersion(){return this.version}removeAxis(e){let t=this.axes.get(e);return t?(this.axes.delete(e),this.axisNameToId.delete(t.name),this.version++,!0):!1}removeButton(e){let t=this.buttons.get(e);return t?(this.buttons.delete(e),this.buttonNameToId.delete(t.name),this.version++,!0):!1}clearAxes(){this.axes.clear(),this.axisNameToId.clear(),this.version++}clearButtons(){this.buttons.clear(),this.buttonNameToId.clear(),this.version++}clear(){this.axes.clear(),this.axisNameToId.clear(),this.buttons.clear(),this.buttonNameToId.clear(),this.version=1}toString(){let e=`InputBindingRegistry (version ${this.version})
|
|
1
|
+
var Q=Object.defineProperty;var Xn=Object.getOwnPropertyDescriptor;var Wn=Object.getOwnPropertyNames;var Gn=Object.prototype.hasOwnProperty;var $n=(h,e,t)=>e in h?Q(h,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):h[e]=t;var y=(h,e)=>Q(h,"name",{value:e,configurable:!0}),ee=(h=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(h,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):h)(function(h){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+h+'" is not supported')});var F=(h,e)=>()=>(h&&(e=h(h=0)),e);var te=(h,e)=>{for(var t in e)Q(h,t,{get:e[t],enumerable:!0})},Zn=(h,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Wn(e))!Gn.call(h,n)&&n!==t&&Q(h,n,{get:()=>e[n],enumerable:!(r=Xn(e,n))||r.enumerable});return h};var re=h=>Zn(Q({},"__esModule",{value:!0}),h);var b=(h,e,t)=>($n(h,typeof e!="symbol"?e+"":e,t),t);var Pe,Uo,z,Re,Mo,Ao,Eo,kr,Br,zr,Tr,Fr,Lr,Dr,Vr,Hr,_r,Nr,Yr,Xr,Wr,Gr,$r,Zr,jr,Jr,qr,Kr,Qr,en,tn,rn,nn,on,an,sn,dn,cn,ln,Po,Ro,ko,Bo,it,at,zo,un,st,dt,ct,lt,ut,pt,W=F(()=>{"use strict";Pe=256,Uo=65536,z=255,Re=y(h=>h?2:1,"charCodeByteSize"),Mo=9,Ao=5,Eo=13,kr=6,Br=6,zr=6,Tr=7,Fr=5,Lr=3,Dr=1,Vr=6,Hr=4,_r=5,Nr=2,Yr=8,Xr=7,Wr=7,Gr=8,$r=10,Zr=6,jr=3,Jr=9,qr=15,Kr=51,Qr=5,en=6,tn=4,rn=3,nn=3,on=4,an=5,sn=4,dn=2,cn=5,ln=5,Po=2,Ro=3,ko=2,Bo=2,it=5,at=5,zo=4,un=3,st=8,dt=6,ct=3,lt=8,ut=3,pt=4});var pn,mn=F(()=>{"use strict";pn=(o=>(o[o.Rectangle=1]="Rectangle",o[o.Circle=2]="Circle",o[o.Line=3]="Line",o[o.Ellipse=4]="Ellipse",o[o.Triangle=5]="Triangle",o))(pn||{})});function qn(h){return h>=1&&h<=3}function Kn(h){return h>=1&&h<=4}function Qn(h){switch(h){case 1:return"CreateInstance";case 2:return"UpdateInstance";case 3:return"RemoveInstance";default:return`Unknown(0x${h.toString(16)})`}}function eo(h){switch(h){case 1:return"Click";case 2:return"Change";case 3:return"Submit";case 4:return"Select";default:return`Unknown(0x${h.toString(16)})`}}var hn,bn,gn=F(()=>{"use strict";hn=(r=>(r[r.CreateInstance=1]="CreateInstance",r[r.UpdateInstance=2]="UpdateInstance",r[r.RemoveInstance=3]="RemoveInstance",r))(hn||{}),bn=(n=>(n[n.Click=1]="Click",n[n.Change=2]="Change",n[n.Submit=3]="Submit",n[n.Select=4]="Select",n))(bn||{});y(qn,"isValidMacroOrderType");y(Kn,"isValidMacroEventType");y(Qn,"getMacroOrderTypeName");y(eo,"getMacroEventTypeName")});var H,x,L=F(()=>{"use strict";H=class H{constructor(e){b(this,"data");b(this,"view");this.data=new Uint8Array(e),this.view=new DataView(this.data.buffer)}static from(e){let t=new H(0);return t.data=e,t.view=new DataView(e.buffer,e.byteOffset,e.byteLength),t}static allocUnsafe(e){return new H(e)}get length(){return this.data.length}toUint8Array(){return this.data}readUInt8(e){return this.view.getUint8(e)}readInt8(e){return this.view.getInt8(e)}readUInt16BE(e){return this.view.getUint16(e,!1)}readInt16BE(e){return this.view.getInt16(e,!1)}readUInt16LE(e){return this.view.getUint16(e,!0)}readInt16LE(e){return this.view.getInt16(e,!0)}readUInt32BE(e){return this.view.getUint32(e,!1)}readInt32BE(e){return this.view.getInt32(e,!1)}readUInt32LE(e){return this.view.getUint32(e,!0)}readInt32LE(e){return this.view.getInt32(e,!0)}readBigUInt64BE(e){return this.view.getBigUint64(e,!1)}readBigInt64BE(e){return this.view.getBigInt64(e,!1)}readBigUInt64LE(e){return this.view.getBigUint64(e,!0)}readBigInt64LE(e){return this.view.getBigInt64(e,!0)}writeUInt8(e,t){this.view.setUint8(t,e)}writeInt8(e,t){this.view.setInt8(t,e)}writeUInt16BE(e,t){this.view.setUint16(t,e,!1)}writeInt16BE(e,t){this.view.setInt16(t,e,!1)}writeUInt16LE(e,t){this.view.setUint16(t,e,!0)}writeInt16LE(e,t){this.view.setInt16(t,e,!0)}writeUInt32BE(e,t){this.view.setUint32(t,e,!1)}writeInt32BE(e,t){this.view.setInt32(t,e,!1)}writeUInt32LE(e,t){this.view.setUint32(t,e,!0)}writeInt32LE(e,t){this.view.setInt32(t,e,!0)}writeBigUInt64BE(e,t){this.view.setBigUint64(t,e,!1)}writeBigInt64BE(e,t){this.view.setBigInt64(t,e,!1)}writeBigUInt64LE(e,t){this.view.setBigUint64(t,e,!0)}writeBigInt64LE(e,t){this.view.setBigInt64(t,e,!0)}readFloatBE(e){return this.view.getFloat32(e,!1)}readFloatLE(e){return this.view.getFloat32(e,!0)}writeFloatBE(e,t){this.view.setFloat32(t,e,!1)}writeFloatLE(e,t){this.view.setFloat32(t,e,!0)}copy(e,t=0,r=0,n=this.length){let o=this.data.subarray(r,n);return e.data.set(o,t),o.length}slice(e,t){let r=this.data.slice(e,t);return H.from(r)}subarray(e,t){let r=this.data.subarray(e,t);return H.from(r)}toBuffer(){return typeof Buffer<"u"&&Buffer.from?Buffer.from(this.data):this.data}static fromNodeBuffer(e){return e instanceof Uint8Array?H.from(e):H.from(new Uint8Array(e))}};y(H,"BufferCompat");x=H});var fn={};te(fn,{VibrationOrderType:()=>Bt});var Bt,zt=F(()=>{"use strict";Bt=(n=>(n[n.MobileVibrate=1]="MobileVibrate",n[n.MobileCancel=2]="MobileCancel",n[n.GamepadVibrate=16]="GamepadVibrate",n[n.GamepadCancel=17]="GamepadCancel",n))(Bt||{})});var Sn={};te(Sn,{GamepadVibrateFlags:()=>Ft,MobileVibrateFlags:()=>Tt});var Tt,Ft,Lt=F(()=>{"use strict";Tt=(e=>(e[e.HasIntensity=1]="HasIntensity",e))(Tt||{}),Ft=(t=>(t[t.HasStartDelay=1]="HasStartDelay",t[t.AllGamepads=2]="AllGamepads",t))(Ft||{})});var wn={};te(wn,{AudioOrderType:()=>Dt,AudioTargetType:()=>Vt,getAudioOrderTypeName:()=>On,isValidAudioOrderType:()=>In});function In(h){return h>=1&&h<=9}function On(h){switch(h){case 1:return"PlaySound";case 2:return"PlayGlobalSound";case 3:return"StopSound";case 4:return"FadeOutSound";case 5:return"PauseSound";case 6:return"ResumeSound";case 7:return"SetListenerPosition";case 8:return"ConfigureSpatial";case 9:return"SetSoundEffects";default:return`UnknownAudio(0x${h.toString(16)})`}}var Dt,Vt,Ht=F(()=>{"use strict";Dt=(d=>(d[d.PlaySound=1]="PlaySound",d[d.PlayGlobalSound=2]="PlayGlobalSound",d[d.StopSound=3]="StopSound",d[d.FadeOutSound=4]="FadeOutSound",d[d.PauseSound=5]="PauseSound",d[d.ResumeSound=6]="ResumeSound",d[d.SetListenerPosition=7]="SetListenerPosition",d[d.ConfigureSpatial=8]="ConfigureSpatial",d[d.SetSoundEffects=9]="SetSoundEffects",d))(Dt||{}),Vt=(r=>(r[r.InstanceId=0]="InstanceId",r[r.SoundId=1]="SoundId",r[r.All=2]="All",r))(Vt||{});y(In,"isValidAudioOrderType");y(On,"getAudioOrderTypeName")});var Un={};te(Un,{PlaySoundFlags:()=>_t,SoundEffectsFlags:()=>vn});var _t,vn,Nt=F(()=>{"use strict";_t=(s=>(s[s.Loop=1]="Loop",s[s.HasVolume=2]="HasVolume",s[s.HasPitch=4]="HasPitch",s[s.HasFadeIn=8]="HasFadeIn",s[s.HasPosition=16]="HasPosition",s[s.HasLowpass=32]="HasLowpass",s[s.HasHighpass=64]="HasHighpass",s[s.HasReverb=128]="HasReverb",s))(_t||{}),vn=(r=>(r[r.HasLowpass=1]="HasLowpass",r[r.HasHighpass=2]="HasHighpass",r[r.HasReverb=4]="HasReverb",r))(vn||{})});import{ScalingModeValue as po}from"@utsp/types";var En=F(()=>{"use strict"});var Pn,Rn=F(()=>{"use strict";Pn=(a=>(a[a.SetConfig=1]="SetConfig",a[a.SetScanlines=2]="SetScanlines",a[a.SetAmbientEffect=3]="SetAmbientEffect",a[a.SetScalingMode=4]="SetScalingMode",a[a.SetGrid=5]="SetGrid",a[a.SwitchPalette=6]="SwitchPalette",a[a.SetCellSize=7]="SetCellSize",a))(Pn||{})});var hr,qe,Fn=F(()=>{"use strict";hr=class hr{decode(e,t=0){this.checkSize(e,t,7);let n=t,o=e.readUInt8(n++),i=e.readUInt16BE(n);n+=2;let a=e.readUInt16BE(n);n+=2;let s=e.readUInt8(n++)+1,d=e.readUInt8(n++)+1;return{display:{id:o,originX:i,originY:a,sizeX:s,sizeY:d},bytesRead:7}}checkSize(e,t,r){if(t+r>e.length)throw new Error(`Buffer too short for display: need ${r} bytes at offset ${t}, but only ${e.length-t} bytes available`)}};y(hr,"DisplayDecoder");qe=hr});var br,Ke,Ln=F(()=>{"use strict";W();br=class br{constructor(){b(this,"charCodeSize",Re)}decode(e,t=0,r=!1){if(t>=e.length)throw new Error("Buffer too short to decode order type");let n=e.readUInt8(t);switch(n){case 1:return this.decodeCharOrder(e,t,r);case 2:return this.decodeTextOrder(e,t);case 23:return this.decodeTextMultilineOrder(e,t);case 3:return this.decodeSubFrameOrder(e,t,r);case 4:return this.decodeSubFrameMultiColorOrder(e,t,r);case 5:return this.decodeFullFrameOrder(e,t,r);case 6:return this.decodeFullFrameMultiColorOrder(e,t,r);case 7:return this.decodeSpriteOrder(e,t);case 8:return this.decodeSpriteMultiColorOrder(e,t);case 9:return this.decodeColorMapOrder(e,t);case 10:return this.decodeShapeOrder(e,t,r);case 11:return this.decodeDotCloudOrder(e,t,r);case 12:return this.decodeDotCloudMultiColorOrder(e,t,r);case 17:return this.decodeBitmaskOrder(e,t,r);case 18:return this.decodeBitmask4Order(e,t,r);case 24:return this.decodeBitmask16Order(e,t,r);case 25:return this.decodePolylineOrder(e,t,r);case 13:return this.decodeSpriteCloudOrder(e,t);case 14:return this.decodeSpriteCloudMultiColorOrder(e,t);case 15:return this.decodeSpriteCloudVariedOrder(e,t);case 16:return this.decodeSpriteCloudVariedMultiColorOrder(e,t);case 19:return this.decodeClearOrder(e,t,r);case 20:return this.decodeFillCharOrder(e,t,r);case 21:return this.decodeFillSpriteOrder(e,t);case 22:return this.decodeFillSpriteMultiColorOrder(e,t);default:throw new Error(`Unknown order type: 0x${n.toString(16)}`)}}readCharCode(e,t,r){return r?[e.readUInt16LE(t),t+2]:[e.readUInt8(t),t+1]}decodeCharOrder(e,t,r){let o=5+this.charCodeSize(r);this.checkSize(e,t,o);let i=t,a=e.readUInt8(i++),s=e.readUInt8(i++),d=e.readUInt8(i++),[c,l]=this.readCharCode(e,i,r);i=l;let u=e.readUInt8(i++),p=e.readUInt8(i++);return{order:{type:1,posX:s,posY:d,charCode:c,bgColorCode:u,fgColorCode:p},bytesRead:o}}decodeTextOrder(e,t){this.checkSize(e,t,5);let r=t,n=e.readUInt8(r+3);this.checkSize(e,t,5+n);let o=e.subarray(r+4,r+4+n),i=new TextDecoder().decode(o.toUint8Array());return{order:{type:2,posX:e.readUInt8(r+1),posY:e.readUInt8(r+2),text:i,bgColorCode:e.readUInt8(r+4+n),fgColorCode:e.readUInt8(r+5+n)},bytesRead:6+n}}decodeTextMultilineOrder(e,t){this.checkSize(e,t,5);let r=t,n=e.readUInt8(r+3);this.checkSize(e,t,5+n);let o=e.subarray(r+4,r+4+n),i=new TextDecoder().decode(o.toUint8Array());return{order:{type:23,posX:e.readUInt8(r+1),posY:e.readUInt8(r+2),text:i,bgColorCode:e.readUInt8(r+4+n),fgColorCode:e.readUInt8(r+5+n)},bytesRead:6+n}}decodeSubFrameOrder(e,t,r){this.checkSize(e,t,7);let n=t,o=this.charCodeSize(r),i=e.readUInt8(n+3)+1,a=e.readUInt8(n+4)+1,s=i*a;this.checkSize(e,t,7+s*o);let d=[],c=n+7;for(let u=0;u<s;u++){let[p,m]=this.readCharCode(e,c,r);d.push(p),c=m}return{order:{type:3,posX:e.readUInt8(n+1),posY:e.readUInt8(n+2),sizeX:i,sizeY:a,bgColorCode:e.readUInt8(n+5),fgColorCode:e.readUInt8(n+6),frame:d},bytesRead:7+s*o}}decodeSubFrameMultiColorOrder(e,t,r){this.checkSize(e,t,5);let n=t,o=this.charCodeSize(r),i=e.readUInt8(n+3)+1,a=e.readUInt8(n+4)+1,s=i*a,d=o+2;this.checkSize(e,t,5+s*d);let c=[],l=n+5;for(let p=0;p<s;p++){let[m,g]=this.readCharCode(e,l,r);l=g,c.push({charCode:m,bgColorCode:e.readUInt8(l++),fgColorCode:e.readUInt8(l++)})}return{order:{type:4,posX:e.readUInt8(n+1),posY:e.readUInt8(n+2),sizeX:i,sizeY:a,frame:c},bytesRead:5+s*d}}decodeFullFrameOrder(e,t,r,n){this.checkSize(e,t,3);let o=t,i=this.charCodeSize(r),a=n||Math.floor((e.length-t-3)/i);this.checkSize(e,t,3+a*i);let s=[],d=o+3;for(let l=0;l<a;l++){let[u,p]=this.readCharCode(e,d,r);s.push(u),d=p}return{order:{type:5,bgColorCode:e.readUInt8(o+1),fgColorCode:e.readUInt8(o+2),frame:s},bytesRead:3+a*i}}decodeFullFrameMultiColorOrder(e,t,r,n){this.checkSize(e,t,1);let o=t,a=this.charCodeSize(r)+2,s=n||Math.floor((e.length-t-1)/a);this.checkSize(e,t,1+s*a);let d=[],c=o+1;for(let u=0;u<s;u++){let[p,m]=this.readCharCode(e,c,r);c=m,d.push({charCode:p,bgColorCode:e.readUInt8(c++),fgColorCode:e.readUInt8(c++)})}return{order:{type:6,frame:d},bytesRead:1+s*a}}decodeSpriteOrder(e,t){this.checkSize(e,t,6);let r=t;return{order:{type:7,posX:e.readUInt8(r+1),posY:e.readUInt8(r+2),spriteIndex:e.readUInt8(r+3),bgColorCode:e.readUInt8(r+4),fgColorCode:e.readUInt8(r+5)},bytesRead:6}}decodeSpriteMultiColorOrder(e,t){this.checkSize(e,t,4);let r=t;return{order:{type:8,posX:e.readUInt8(r+1),posY:e.readUInt8(r+2),spriteIndex:e.readUInt8(r+3)},bytesRead:4}}decodeColorMapOrder(e,t){this.checkSize(e,t,5);let r=t,n=e.readUInt8(r+3)+1,o=e.readUInt8(r+4)+1,i=n*o;this.checkSize(e,t,5+i*2);let a=[];for(let d=0;d<i;d++){let c=r+5+d*2;a.push({bgColorCode:e.readUInt8(c),fgColorCode:e.readUInt8(c+1)})}return{order:{type:9,posX:e.readUInt8(r+1),posY:e.readUInt8(r+2),sizeX:n,sizeY:o,colorData:a},bytesRead:5+i*2}}decodeShapeOrder(e,t,r){this.checkSize(e,t,2);let n=t,o=e.readUInt8(n+1),{shapeData:i,bytesRead:a}=this.decodeShapeData(e,n+2,o,r);return{order:{type:10,shapeType:o,shapeData:i},bytesRead:2+a}}decodeShapeData(e,t,r,n){let o=t,i=this.charCodeSize(n);switch(r){case 1:{let a=7+i;this.checkSize(e,t,a);let s=e.readUInt8(o++),d=e.readUInt8(o++),c=e.readUInt8(o++)+1,l=e.readUInt8(o++)+1,u=e.readUInt8(o++)===1,[p,m]=this.readCharCode(e,o,n);o=m;let g=e.readUInt8(o++),C=e.readUInt8(o++);return{shapeData:{posX:s,posY:d,width:c,height:l,filled:u,charCode:p,bgColorCode:g,fgColorCode:C},bytesRead:a}}case 2:{let a=6+i;this.checkSize(e,t,a);let s=e.readUInt8(o++),d=e.readUInt8(o++),c=e.readUInt8(o++)+1,l=e.readUInt8(o++)===1,[u,p]=this.readCharCode(e,o,n);o=p;let m=e.readUInt8(o++),g=e.readUInt8(o++);return{shapeData:{centerX:s,centerY:d,radius:c,filled:l,charCode:u,bgColorCode:m,fgColorCode:g},bytesRead:a}}case 3:{let a=6+i;this.checkSize(e,t,a);let s=e.readUInt8(o++),d=e.readUInt8(o++),c=e.readUInt8(o++),l=e.readUInt8(o++),[u,p]=this.readCharCode(e,o,n);o=p;let m=e.readUInt8(o++),g=e.readUInt8(o++);return{shapeData:{x1:s,y1:d,x2:c,y2:l,charCode:u,bgColorCode:m,fgColorCode:g},bytesRead:a}}case 4:{let a=7+i;this.checkSize(e,t,a);let s=e.readUInt8(o++),d=e.readUInt8(o++),c=e.readUInt8(o++)+1,l=e.readUInt8(o++)+1,u=e.readUInt8(o++)===1,[p,m]=this.readCharCode(e,o,n);o=m;let g=e.readUInt8(o++),C=e.readUInt8(o++);return{shapeData:{centerX:s,centerY:d,radiusX:c,radiusY:l,filled:u,charCode:p,bgColorCode:g,fgColorCode:C},bytesRead:a}}case 5:{let a=9+i;this.checkSize(e,t,a);let s=e.readUInt8(o++),d=e.readUInt8(o++),c=e.readUInt8(o++),l=e.readUInt8(o++),u=e.readUInt8(o++),p=e.readUInt8(o++),m=e.readUInt8(o++)===1,[g,C]=this.readCharCode(e,o,n);o=C;let S=e.readUInt8(o++),O=e.readUInt8(o++);return{shapeData:{x1:s,y1:d,x2:c,y2:l,x3:u,y3:p,filled:m,charCode:g,bgColorCode:S,fgColorCode:O},bytesRead:a}}default:throw new Error(`Unknown shape type: ${r}`)}}decodeDotCloudOrder(e,t,r){let o=1+this.charCodeSize(r)+2+2;this.checkSize(e,t,o);let i=t,a=e.readUInt8(i++),[s,d]=this.readCharCode(e,i,r);i=d;let c=e.readUInt8(i++),l=e.readUInt8(i++),u=e.readUInt16BE(i);i+=2,this.checkSize(e,t,o+u*2);let p=[];for(let g=0;g<u;g++)p.push({posX:e.readUInt8(i++),posY:e.readUInt8(i++)});return{order:{type:11,charCode:s,bgColorCode:c,fgColorCode:l,positions:p},bytesRead:o+u*2}}decodeDotCloudMultiColorOrder(e,t,r){this.checkSize(e,t,3);let n=this.charCodeSize(r),o=t,i=e.readUInt16BE(o+1),a=n+4;this.checkSize(e,t,3+i*a);let s=[],d=o+3;for(let l=0;l<i;l++){let[u,p]=this.readCharCode(e,d,r);d=p,s.push({charCode:u,bgColorCode:e.readUInt8(d++),fgColorCode:e.readUInt8(d++),posX:e.readUInt8(d++),posY:e.readUInt8(d++)})}return{order:{type:12,dots:s},bytesRead:3+i*a}}decodeBitmaskOrder(e,t,r){let o=8+this.charCodeSize(r);this.checkSize(e,t,o);let i=t,a=e.readUInt8(i++),s=e.readUInt8(i++),d=e.readUInt8(i++),c=e.readUInt8(i++)+1,l=e.readUInt8(i++)+1,[u,p]=this.readCharCode(e,i,r);i=p;let m=e.readUInt8(i++),g=e.readUInt8(i++),C=e.readUInt8(i++)===1,S=Math.ceil(c*l/8);this.checkSize(e,t,o+S);let O=new Uint8Array(S);for(let w=0;w<S;w++)O[w]=e.readUInt8(i+w);return{order:{type:17,posX:s,posY:d,sizeX:c,sizeY:l,charCode:u,bgColorCode:m,fgColorCode:g,override:C,mask:O},bytesRead:o+S}}decodeBitmask4Order(e,t,r){let i=6+3*(this.charCodeSize(r)+2);this.checkSize(e,t,i);let a=t,s=e.readUInt8(a++),d=e.readUInt8(a++),c=e.readUInt8(a++),l=e.readUInt8(a++)+1,u=e.readUInt8(a++)+1,p=e.readUInt8(a++)===1,m=Math.ceil(l*u/4);this.checkSize(e,t,i+m);let g=[];for(let O=0;O<3;O++){let[I,w]=this.readCharCode(e,a,r);a=w,g.push({charCode:I,bgColorCode:e.readUInt8(a++),fgColorCode:e.readUInt8(a++)})}let C=new Uint8Array(m);for(let O=0;O<m;O++)C[O]=e.readUInt8(a+O);return{order:{type:18,posX:d,posY:c,sizeX:l,sizeY:u,override:p,variants:g,mask:C},bytesRead:i+m}}decodeBitmask16Order(e,t,r){let i=6+15*(this.charCodeSize(r)+2);this.checkSize(e,t,i);let a=t,s=e.readUInt8(a++),d=e.readUInt8(a++),c=e.readUInt8(a++),l=e.readUInt8(a++)+1,u=e.readUInt8(a++)+1,p=e.readUInt8(a++)===1,m=Math.ceil(l*u/2);this.checkSize(e,t,i+m);let g=[];for(let O=0;O<15;O++){let[I,w]=this.readCharCode(e,a,r);a=w,g.push({charCode:I,bgColorCode:e.readUInt8(a++),fgColorCode:e.readUInt8(a++)})}let C=new Uint8Array(m);for(let O=0;O<m;O++)C[O]=e.readUInt8(a+O);return{order:{type:24,posX:d,posY:c,sizeX:l,sizeY:u,override:p,variants:g,mask:C},bytesRead:i+m}}decodePolylineOrder(e,t,r){let o=4+this.charCodeSize(r);this.checkSize(e,t,o);let i=t,a=e.readUInt8(i++),[s,d]=this.readCharCode(e,i,r);i=d;let c=e.readUInt8(i++),l=e.readUInt8(i++),u=e.readUInt8(i++);this.checkSize(e,t,o+u*2);let p=[];for(let g=0;g<u;g++)p.push({x:e.readUInt8(i++),y:e.readUInt8(i++)});return{order:{type:25,charCode:s,fgColorCode:c,bgColorCode:l,points:p},bytesRead:o+u*2}}decodeSpriteCloudOrder(e,t){this.checkSize(e,t,6);let r=t,n=e.readUInt16BE(r+4);this.checkSize(e,t,6+n*2);let o=[];for(let a=0;a<n;a++){let s=r+6+a*2;o.push({posX:e.readUInt8(s),posY:e.readUInt8(s+1)})}return{order:{type:13,spriteIndex:e.readUInt8(r+1),bgColorCode:e.readUInt8(r+2),fgColorCode:e.readUInt8(r+3),positions:o},bytesRead:6+n*2}}decodeSpriteCloudMultiColorOrder(e,t){this.checkSize(e,t,4);let r=t,n=e.readUInt16BE(r+2);this.checkSize(e,t,4+n*2);let o=[];for(let a=0;a<n;a++){let s=r+4+a*2;o.push({posX:e.readUInt8(s),posY:e.readUInt8(s+1)})}return{order:{type:14,spriteIndex:e.readUInt8(r+1),positions:o},bytesRead:4+n*2}}decodeSpriteCloudVariedOrder(e,t){this.checkSize(e,t,3);let r=t,n=e.readUInt16BE(r+1);this.checkSize(e,t,3+n*5);let o=[];for(let a=0;a<n;a++){let s=r+3+a*5;o.push({spriteIndex:e.readUInt8(s),bgColorCode:e.readUInt8(s+1),fgColorCode:e.readUInt8(s+2),posX:e.readUInt8(s+3),posY:e.readUInt8(s+4)})}return{order:{type:15,sprites:o},bytesRead:3+n*5}}decodeSpriteCloudVariedMultiColorOrder(e,t){this.checkSize(e,t,3);let r=t,n=e.readUInt16BE(r+1);this.checkSize(e,t,3+n*3);let o=[];for(let a=0;a<n;a++){let s=r+3+a*3;o.push({spriteIndex:e.readUInt8(s),posX:e.readUInt8(s+1),posY:e.readUInt8(s+2)})}return{order:{type:16,sprites:o},bytesRead:3+n*3}}decodeClearOrder(e,t,r){let o=3+this.charCodeSize(r);this.checkSize(e,t,o);let i=t,a=e.readUInt8(i++),[s,d]=this.readCharCode(e,i,r);i=d;let c=e.readUInt8(i++),l=e.readUInt8(i++);return{order:{type:19,charCode:s,bgColorCode:c,fgColorCode:l},bytesRead:o}}decodeFillCharOrder(e,t,r){this.checkSize(e,t,5);let n=this.charCodeSize(r),o=t,i=e.readUInt8(o+1)+1,a=e.readUInt8(o+2)+1,s=i*a,d=5+s*n;this.checkSize(e,t,d);let c=[],l=o+5;for(let p=0;p<s;p++){let[m,g]=this.readCharCode(e,l,r);c.push(m),l=g}return{order:{type:20,patternWidth:i,patternHeight:a,bgColorCode:e.readUInt8(o+3),fgColorCode:e.readUInt8(o+4),pattern:c},bytesRead:d}}decodeFillSpriteOrder(e,t){this.checkSize(e,t,4);let r=t;return{order:{type:21,spriteIndex:e.readUInt8(r+1),bgColorCode:e.readUInt8(r+2),fgColorCode:e.readUInt8(r+3)},bytesRead:4}}decodeFillSpriteMultiColorOrder(e,t){this.checkSize(e,t,2);let r=t;return{order:{type:22,spriteIndex:e.readUInt8(r+1)},bytesRead:2}}checkSize(e,t,r){if(t+r>e.length)throw new Error(`Buffer too short: need ${r} bytes at offset ${t}, but only ${e.length-t} bytes available`)}};y(br,"OrderDecoder");Ke=br});var bo,gr,Qe,Dn=F(()=>{"use strict";Ln();bo=64,gr=class gr{constructor(){b(this,"orderDecoder");this.orderDecoder=new Ke}decode(e,t=0){this.checkSize(e,t,13);let n=t,o=e.readUInt16BE(n);n+=2;let i=e.readUInt8(n++),a=e.readUInt8(n++),s=e.readUInt16BE(n);n+=2;let d=e.readUInt16BE(n);n+=2;let c=e.readUInt16BE(n);n+=2;let l=e.readUInt16BE(n);n+=2;let u=e.readUInt8(n++),p=(i&bo)!==0,m=[],g=n;for(let S=0;S<u;S++){let O=this.orderDecoder.decode(e,g,p);m.push(O.order),g+=O.bytesRead}return{layer:{id:o,updateFlags:i,zIndex:a,originX:s,originY:d,width:c,height:l,orderCount:u,orders:m,is16bit:p},bytesRead:g-t}}checkSize(e,t,r){if(t+r>e.length)throw new Error(`Buffer too short for layer: need ${r} bytes at offset ${t}, but only ${e.length-t} bytes available`)}};y(gr,"LayerDecoder");Qe=gr});var yr,ve,Cr=F(()=>{"use strict";yr=class yr{decode(e,t=0){if(t>=e.length)throw new Error("Buffer too short to decode audio order type");let r=e.readUInt8(t);switch(r){case 1:return this.decodePlaySoundOrder(e,t);case 2:return this.decodePlayGlobalSoundOrder(e,t);case 3:return this.decodeStopSoundOrder(e,t);case 4:return this.decodeFadeOutSoundOrder(e,t);case 5:return this.decodePauseSoundOrder(e,t);case 6:return this.decodeResumeSoundOrder(e,t);case 7:return this.decodeSetListenerPositionOrder(e,t);case 8:return this.decodeConfigureSpatialOrder(e,t);case 9:return this.decodeSetSoundEffectsOrder(e,t);default:throw new Error(`Unknown audio order type: 0x${r.toString(16)}`)}}decodePlaySoundOrder(e,t){this.checkSize(e,t,5);let r=t,n=e.readUInt8(r++),o=e.readUInt8(r++),i=e.readUInt16BE(r);r+=2;let a=e.readUInt8(r++),s={type:n,soundId:o,instanceId:i,flags:a};return a&2&&(this.checkSize(e,r,1),s.volume=e.readUInt8(r++)),a&4&&(this.checkSize(e,r,1),s.pitch=e.readUInt8(r++)),a&8&&(this.checkSize(e,r,1),s.fadeIn=e.readUInt8(r++)),a&16&&(this.checkSize(e,r,4),s.posX=e.readUInt16BE(r),r+=2,s.posY=e.readUInt16BE(r),r+=2),a&32&&(this.checkSize(e,r,1),s.lowpass=e.readUInt8(r++)),a&64&&(this.checkSize(e,r,1),s.highpass=e.readUInt8(r++)),a&128&&(this.checkSize(e,r,1),s.reverb=e.readUInt8(r++)),{order:s,bytesRead:r-t}}decodePlayGlobalSoundOrder(e,t){this.checkSize(e,t,5);let r=t,n=e.readUInt8(r++),o=e.readUInt8(r++),i=e.readUInt16BE(r);r+=2;let a=e.readUInt8(r++),s={type:n,soundId:o,instanceId:i,flags:a};return a&2&&(this.checkSize(e,r,1),s.volume=e.readUInt8(r++)),a&4&&(this.checkSize(e,r,1),s.pitch=e.readUInt8(r++)),a&8&&(this.checkSize(e,r,1),s.fadeIn=e.readUInt8(r++)),a&32&&(this.checkSize(e,r,1),s.lowpass=e.readUInt8(r++)),a&64&&(this.checkSize(e,r,1),s.highpass=e.readUInt8(r++)),a&128&&(this.checkSize(e,r,1),s.reverb=e.readUInt8(r++)),{order:s,bytesRead:r-t}}decodeStopSoundOrder(e,t){this.checkSize(e,t,2);let r=t,n=e.readUInt8(r++),o=e.readUInt8(r++),i={type:n,targetType:o};return o===0?(this.checkSize(e,r,2),i.target=e.readUInt16BE(r),r+=2):o===1&&(this.checkSize(e,r,1),i.target=e.readUInt8(r++)),{order:i,bytesRead:r-t}}decodeFadeOutSoundOrder(e,t){this.checkSize(e,t,3);let r=t,n=e.readUInt8(r++),o=e.readUInt8(r++),i=e.readUInt8(r++),a={type:n,targetType:o,duration:i};return o===0?(this.checkSize(e,r,2),a.target=e.readUInt16BE(r),r+=2):o===1&&(this.checkSize(e,r,1),a.target=e.readUInt8(r++)),{order:a,bytesRead:r-t}}decodePauseSoundOrder(e,t){this.checkSize(e,t,2);let r=t,n=e.readUInt8(r++),o=e.readUInt8(r++),i={type:n,targetType:o};return o===0?(this.checkSize(e,r,2),i.target=e.readUInt16BE(r),r+=2):o===1&&(this.checkSize(e,r,1),i.target=e.readUInt8(r++)),{order:i,bytesRead:r-t}}decodeResumeSoundOrder(e,t){this.checkSize(e,t,2);let r=t,n=e.readUInt8(r++),o=e.readUInt8(r++),i={type:n,targetType:o};return o===0?(this.checkSize(e,r,2),i.target=e.readUInt16BE(r),r+=2):o===1&&(this.checkSize(e,r,1),i.target=e.readUInt8(r++)),{order:i,bytesRead:r-t}}decodeSetListenerPositionOrder(e,t){this.checkSize(e,t,5);let r=t,n=e.readUInt8(r++),o=e.readUInt16BE(r);r+=2;let i=e.readUInt16BE(r);return r+=2,{order:{type:n,x:o,y:i},bytesRead:5}}decodeConfigureSpatialOrder(e,t){this.checkSize(e,t,5);let r=t;return{order:{type:e.readUInt8(r),maxDistance:e.readUInt8(r+1),referenceDistance:e.readUInt8(r+2),rolloffFactor:e.readUInt8(r+3),panSpread:e.readUInt8(r+4)},bytesRead:5}}decodeSetSoundEffectsOrder(e,t){this.checkSize(e,t,4);let r=t,n=e.readUInt8(r++),o=e.readUInt16BE(r);r+=2;let i=e.readUInt8(r++),a={type:n,instanceId:o,flags:i};return i&1&&(this.checkSize(e,r,1),a.lowpass=e.readUInt8(r++)),i&2&&(this.checkSize(e,r,1),a.highpass=e.readUInt8(r++)),i&4&&(this.checkSize(e,r,1),a.reverb=e.readUInt8(r++)),{order:a,bytesRead:r-t}}checkSize(e,t,r){if(t+r>e.length)throw new Error(`Buffer too short for audio order: need ${r} bytes at offset ${t}, but only ${e.length-t} bytes available`)}};y(yr,"AudioOrderDecoder");ve=yr});var xr,Ue,fr=F(()=>{"use strict";xr=class xr{decode(e,t=0){if(t>=e.length)throw new Error("Buffer too short to decode vibration order type");let r=e.readUInt8(t);switch(r){case 1:return this.decodeMobileVibrateOrder(e,t);case 2:return this.decodeMobileCancelOrder(e,t);case 16:return this.decodeGamepadVibrateOrder(e,t);case 17:return this.decodeGamepadCancelOrder(e,t);default:throw new Error(`Unknown vibration order type: 0x${r.toString(16)}`)}}decodeMobileVibrateOrder(e,t){let r=t,n=e.readUInt8(r++),o=e.readUInt8(r++),i=e.readUInt8(r++),a=[];for(let d=0;d<i;d++)a.push(e.readUInt16BE(r)),r+=2;let s={type:n,flags:o,pattern:a};return o&1&&(s.intensity=e.readUInt8(r++)/255),{order:s,bytesRead:r-t}}decodeMobileCancelOrder(e,t){return{order:{type:2},bytesRead:1}}decodeGamepadVibrateOrder(e,t){let r=t,n=e.readUInt8(r++),o=e.readUInt8(r++),i=e.readUInt8(r++),a=e.readUInt16BE(r);r+=2;let s=e.readUInt8(r++),d=e.readUInt8(r++),c={type:n,flags:o,gamepadIndex:i,duration:a,strongMagnitude:s,weakMagnitude:d};return o&1&&(c.startDelay=e.readUInt16BE(r),r+=2),{order:c,bytesRead:r-t}}decodeGamepadCancelOrder(e,t){let r=t,n=e.readUInt8(r++),o=e.readUInt8(r++),i=e.readUInt8(r++);return{order:{type:n,flags:o,gamepadIndex:i},bytesRead:r-t}}};y(xr,"VibrationOrderDecoder");Ue=xr});var Sr,et,Vn=F(()=>{"use strict";Sr=class Sr{decode(e,t=0){let r=e.readUInt8(t);switch(r){case 1:return this.decodeCreateInstance(e,t);case 2:return this.decodeUpdateInstance(e,t);case 3:return this.decodeRemoveInstance(e,t);default:throw new Error(`Unknown macro order type: 0x${r.toString(16)}`)}}decodeAll(e,t,r){let n=[],o=0;for(let i=0;i<r;i++){let{order:a,bytesRead:s}=this.decode(e,t+o);n.push(a),o+=s}return{orders:n,bytesRead:o}}decodeCreateInstance(e,t){let r=t,n=e.readUInt8(t++),o=e.readUInt8(t++),i=e.readUInt8(t++),a=e.readUInt8(t++),s=e.readInt16BE(t);t+=2;let d=e.readInt16BE(t);t+=2;let c=e.readUInt8(t++),l=e.readUInt16BE(t);t+=2;let u=e.toUint8Array().subarray(t,t+l);t+=l;let p=new TextDecoder().decode(u),m=JSON.parse(p);return{order:{type:n,instanceId:o,macroId:i,layerId:a,x:s,y:d,tabIndex:c,params:m},bytesRead:t-r}}decodeUpdateInstance(e,t){let r=t,n=e.readUInt8(t++),o=e.readUInt8(t++),i=e.readUInt16BE(t);t+=2;let a=e.toUint8Array().subarray(t,t+i);t+=i;let s=new TextDecoder().decode(a),d=JSON.parse(s);return{order:{type:n,instanceId:o,params:d},bytesRead:t-r}}decodeRemoveInstance(e,t){let r=e.readUInt8(t),n=e.readUInt8(t+1);return{order:{type:r,instanceId:n},bytesRead:2}}};y(Sr,"MacroOrderDecoder");et=Sr});var Ir,Me,Or=F(()=>{"use strict";Ir=class Ir{decode(e,t){let r=e[t];switch(r){case 1:return this.decodeSetConfigOrder(e,t);case 2:return this.decodeSetScanlinesOrder(e,t);case 3:return this.decodeSetAmbientEffectOrder(e,t);case 4:return this.decodeSetScalingModeOrder(e,t);case 5:return this.decodeSetGridOrder(e,t);case 6:return this.decodeSwitchPaletteOrder(e,t);case 7:return this.decodeSetCellSizeOrder(e,t);default:throw new Error(`Unknown post-process order type: ${r}`)}}decodeSetConfigOrder(e,t){let r=t,n=e[r++],o=e[r++],i=e[r++],a={type:n,displayId:o,flags:i};return i&1&&(a.scanlines={enabled:e[r++]===1,opacity:e[r++]/255,pattern:e[r++],colorR:e[r++],colorG:e[r++],colorB:e[r++]}),i&2&&(a.ambientEffect={enabled:e[r++]===1,blur:e[r++],scale:e[r++]/100,opacity:e[r++]/255}),{order:a,bytesRead:r-t}}decodeSetScanlinesOrder(e,t){let r=t;return{order:{type:e[r++],displayId:e[r++],enabled:e[r++]===1,opacity:e[r++]/255,pattern:e[r++],colorR:e[r++],colorG:e[r++],colorB:e[r++]},bytesRead:r-t}}decodeSetAmbientEffectOrder(e,t){let r=t;return{order:{type:e[r++],displayId:e[r++],enabled:e[r++]===1,blur:e[r++],scale:e[r++]/100,opacity:e[r++]/255},bytesRead:r-t}}decodeSetScalingModeOrder(e,t){let r=t;return{order:{type:e[r++],displayId:e[r++],mode:e[r++]},bytesRead:r-t}}decodeSetGridOrder(e,t){let r=t;return{order:{type:e[r++],displayId:e[r++],enabled:e[r++]===1,colorR:e[r++],colorG:e[r++],colorB:e[r++],colorA:e[r++],lineWidth:e[r++]},bytesRead:r-t}}decodeSwitchPaletteOrder(e,t){let r=t;return{order:{type:e[r++],displayId:e[r++],slotId:e[r++]},bytesRead:r-t}}decodeSetCellSizeOrder(e,t){let r=t;return{order:{type:e[r++],displayId:e[r++],cellWidth:e[r++],cellHeight:e[r++]},bytesRead:r-t}}};y(Ir,"PostProcessOrderDecoder");Me=Ir});var Hn={};te(Hn,{UpdatePacketDecoder:()=>tt});var wr,tt,vr=F(()=>{"use strict";Fn();Dn();Cr();fr();Vn();Or();L();wr=class wr{constructor(){b(this,"displayDecoder");b(this,"layerDecoder");b(this,"audioOrderDecoder");b(this,"vibrationOrderDecoder");b(this,"macroOrderDecoder");b(this,"postProcessOrderDecoder");this.displayDecoder=new qe,this.layerDecoder=new Qe,this.audioOrderDecoder=new ve,this.vibrationOrderDecoder=new Ue,this.macroOrderDecoder=new et,this.postProcessOrderDecoder=new Me}decode(e,t=0){let r=x.from(e);this.checkSize(r,t,15);let o=t,i=Number(r.readBigUInt64BE(o));o+=8;let a=r.readUInt8(o);o+=1;let s=[];for(let w=0;w<a;w++){let U=this.displayDecoder.decode(r,o);s.push(U.display),o+=U.bytesRead}this.checkSize(r,o,2);let d=r.readUInt16BE(o);o+=2;let c=[];for(let w=0;w<d;w++){let U=this.layerDecoder.decode(r,o);c.push(U.layer),o+=U.bytesRead}this.checkSize(r,o,1);let l=r.readUInt8(o);o+=1;let u=[];for(let w=0;w<l;w++){let U=this.audioOrderDecoder.decode(r,o);u.push(U.order),o+=U.bytesRead}this.checkSize(r,o,1);let p=r.readUInt8(o);o+=1;let m=[];for(let w=0;w<p;w++){let U=this.vibrationOrderDecoder.decode(r,o);m.push(U.order),o+=U.bytesRead}this.checkSize(r,o,1);let g=r.readUInt8(o);o+=1;let C=[];for(let w=0;w<g;w++){let U=this.macroOrderDecoder.decode(r,o);C.push(U.order),o+=U.bytesRead}this.checkSize(r,o,1);let S=r.readUInt8(o);o+=1;let O=[];for(let w=0;w<S;w++){let U=this.postProcessOrderDecoder.decode(r.toUint8Array(),o);O.push(U.order),o+=U.bytesRead}return{tick:i,displayCount:a,displays:s,layerCount:d,layers:c,audioOrderCount:l,audioOrders:u,vibrationOrderCount:p,vibrationOrders:m,macroOrderCount:g,macroOrders:C,postProcessOrderCount:S,postProcessOrders:O}}isValid(e,t=0){let r=x.from(e);try{return this.checkSize(r,t,15),!0}catch{return!1}}decodeHeader(e,t=0){let r=x.from(e);this.checkSize(r,t,13);let n=t,o=Number(r.readBigUInt64BE(n));n+=8;let i=r.readUInt8(n);n+=1,n+=i*7,this.checkSize(r,n,2);let a=r.readUInt16BE(n);return{tick:o,displayCount:i,layerCount:a}}checkSize(e,t,r){if(t+r>e.length)throw new Error(`Buffer too short for update packet: need ${r} bytes at offset ${t}, but only ${e.length-t} bytes available`)}};y(wr,"UpdatePacketDecoder");tt=wr});import{Vector2 as Ee}from"@utsp/types";var ot=class ot{constructor(e=0,t=60,r=40){b(this,"id");b(this,"origin");b(this,"size");b(this,"previousOrigin",new Ee(0,0));b(this,"previousSize",new Ee(0,0));b(this,"toDraw",[]);if(e<0||e>255)throw new Error(`Display ID must be between 0 and 255, got ${e}`);if(t<1||t>256)throw new Error(`Display sizeX must be between 1 and 256, got ${t}`);if(r<1||r>256)throw new Error(`Display sizeY must be between 1 and 256, got ${r}`);this.id=e,this.origin=new Ee(0,0),this.size=new Ee(t,r),this.toDraw=new Array(this.size.x*this.size.y).fill(null).map(()=>({charCode:0,fgColorCode:0,bgColorCode:0}))}getId(){return this.id}getOrigin(){return this.origin}setOrigin(e){this.origin=e}moveOrigin(e,t){this.origin.x+=e,this.origin.y+=t}hasOriginChanged(){return this.origin.x!==this.previousOrigin.x||this.origin.y!==this.previousOrigin.y}hasSizeChanged(){return this.size.x!==this.previousSize.x||this.size.y!==this.previousSize.y}hasChanged(){return this.hasOriginChanged()||this.hasSizeChanged()}resetChangeTracking(){this.previousOrigin.x=this.origin.x,this.previousOrigin.y=this.origin.y,this.previousSize.x=this.size.x,this.previousSize.y=this.size.y}getSize(){return this.size}setSize(e){if(e.x<1||e.x>256)throw new Error(`Display sizeX must be between 1 and 256, got ${e.x}`);if(e.y<1||e.y>256)throw new Error(`Display sizeY must be between 1 and 256, got ${e.y}`);this.size=e,this.toDraw=new Array(this.size.x*this.size.y).fill(null).map(()=>({charCode:0,fgColorCode:0,bgColorCode:0}))}};y(ot,"Display");var ne=ot;var ht=class ht{constructor(e=65536,t=!1){b(this,"charCodes");b(this,"fgColors");b(this,"bgColors");b(this,"size");b(this,"is16bit");this.size=e,this.is16bit=t,this.charCodes=t?new Uint16Array(e):new Uint8Array(e),this.fgColors=new Uint8Array(e),this.bgColors=new Uint8Array(e),this.clear()}clear(){this.charCodes.fill(0),this.fgColors.fill(255),this.bgColors.fill(255)}clearWithColor(e,t,r){let n=this.is16bit?e:e&255;this.charCodes.fill(n),this.fgColors.fill(t),this.bgColors.fill(r)}set(e,t,r,n){this.charCodes[e]=this.is16bit?t:t&255,this.fgColors[e]=r,this.bgColors[e]=n}fillCharsUniform(e,t,r,n){let o=this.is16bit?t:t&255;for(let i=0;i<e.length;i++){let a=e[i];this.charCodes[a]=o,this.fgColors[a]=r,this.bgColors[a]=n}}get(e){return{charCode:this.charCodes[e],fgColorCode:this.fgColors[e],bgColorCode:this.bgColors[e]}}setCharOnly(e,t){this.charCodes[e]=this.is16bit?t:t&255}setColorsOnly(e,t,r){this.fgColors[e]=t,this.bgColors[e]=r}getCharCode(e){return this.charCodes[e]}getFgColorCode(e){return this.fgColors[e]}getBgColorCode(e){return this.bgColors[e]}getRawCharCodes(){return this.charCodes}getRawFgColors(){return this.fgColors}getRawBgColors(){return this.bgColors}getSize(){return this.size}is16BitMode(){return this.is16bit}};y(ht,"CellBuffer");var G=ht,bt=class bt{constructor(e){b(this,"data");b(this,"size");this.size=e,this.data=new Uint16Array(e)}clear(){this.data.fill(0)}set(e,t){this.data[e]=t}get(e){return this.data[e]}getRawData(){return this.data}getSize(){return this.size}};y(bt,"CharCodeBuffer");var oe=bt;import{Vector2 as Jn}from"@utsp/types";var jn=new Map([[9474,179],[9472,196],[9484,218],[9488,191],[9492,192],[9496,217],[9500,195],[9508,180],[9516,194],[9524,193],[9532,197],[9553,186],[9552,205],[9556,201],[9559,187],[9562,200],[9565,188],[9568,204],[9571,185],[9574,203],[9577,202],[9580,206],[9608,219],[9619,178],[9618,177],[9617,176],[9600,223],[9604,220],[9612,221],[9616,222]]);function ie(h){if(h<128)return h;let e=jn.get(h);return e!==void 0?e:h&255}y(ie,"unicodeToCp437");var gt=class gt{constructor(){b(this,"currentWidth",256);b(this,"currentHeight",256)}rasterizeOrders(e,t,r,n,o){this.currentWidth=r,this.currentHeight=n,this.clearBuffer(t);for(let i of e)this.rasterizeOrder(i,t,o)}clearBuffer(e){e.clear()}rasterizeOrder(e,t,r){switch(e.type){case 1:this.rasterizeChar(e,t);break;case 2:this.rasterizeText(e,t);break;case 23:this.rasterizeTextMultiline(e,t);break;case 3:this.rasterizeSubFrame(e,t);break;case 4:this.rasterizeSubFrameMultiColor(e,t);break;case 5:this.rasterizeFullFrame(e,t);break;case 6:this.rasterizeFullFrameMultiColor(e,t);break;case 7:this.rasterizeSprite(e,t,r);break;case 8:this.rasterizeSpriteMultiColor(e,t,r);break;case 9:this.rasterizeColorMap(e,t);break;case 10:this.rasterizeShape(e,t);break;case 11:this.rasterizeDotCloud(e,t);break;case 12:this.rasterizeDotCloudMultiColor(e,t);break;case 17:this.rasterizeBitmask(e,t);break;case 18:this.rasterizeBitmask4(e,t);break;case 24:this.rasterizeBitmask16(e,t);break;case 25:this.rasterizePolyline(e,t);break;case 13:this.rasterizeSpriteCloud(e,t,r);break;case 14:this.rasterizeSpriteCloudMultiColor(e,t,r);break;case 15:this.rasterizeSpriteCloudVaried(e,t,r);break;case 16:this.rasterizeSpriteCloudVariedMultiColor(e,t,r);break;case 19:this.rasterizeClear(e,t);break;case 20:this.rasterizeFillChar(e,t);break;case 21:this.rasterizeFillSprite(e,t,r);break;case 22:this.rasterizeFillSpriteMultiColor(e,t,r);break;default:break}}rasterizeChar(e,t){let{posX:r,posY:n,charCode:o,bgColorCode:i,fgColorCode:a}=e;if(!this.isInBounds(r,n))return;let s=n*this.currentWidth+r;t.set(s,o,a,i)}rasterizeText(e,t){let{posX:r,posY:n,text:o,bgColorCode:i,fgColorCode:a}=e;if(this.isInBounds(r,n))for(let s=0;s<o.length;s++){let d=r+s;if(d>=this.currentWidth)break;let c=n*this.currentWidth+d,l=o.charCodeAt(s),u=ie(l);t.set(c,u,a,i)}}rasterizeTextMultiline(e,t){let{posX:r,posY:n,text:o,bgColorCode:i,fgColorCode:a}=e,s=o.split(`
|
|
2
|
+
`),d=n;for(let c of s){if(d>=this.currentHeight)break;if(d>=0&&this.isInBounds(r,d))for(let l=0;l<c.length;l++){let u=r+l;if(u>=this.currentWidth)break;let p=d*this.currentWidth+u,m=c.charCodeAt(l),g=ie(m);t.set(p,g,a,i)}d++}}rasterizeSubFrame(e,t){let{posX:r,posY:n,sizeX:o,sizeY:i,frame:a,bgColorCode:s,fgColorCode:d}=e;for(let c=0;c<i;c++){let l=n+c;if(!(l<0||l>=this.currentHeight))for(let u=0;u<o;u++){let p=r+u;if(p<0||p>=this.currentWidth)continue;let m=c*o+u;if(m>=a.length)break;let g=l*this.currentWidth+p;t.set(g,a[m],d,s)}}}rasterizeSubFrameMultiColor(e,t){let{posX:r,posY:n,sizeX:o,sizeY:i,frame:a}=e;for(let s=0;s<i;s++){let d=n+s;if(!(d<0||d>=this.currentHeight))for(let c=0;c<o;c++){let l=r+c;if(l<0||l>=this.currentWidth)continue;let u=s*o+c;if(u>=a.length)break;let p=a[u],m=d*this.currentWidth+l;t.set(m,p.charCode,p.fgColorCode,p.bgColorCode)}}}rasterizeFullFrame(e,t){let{frame:r,bgColorCode:n,fgColorCode:o}=e,i=this.currentWidth*this.currentHeight;for(let a=0;a<i&&a<r.length;a++)t.set(a,r[a],o,n)}rasterizeFullFrameMultiColor(e,t){let{frame:r}=e,n=this.currentWidth*this.currentHeight;for(let o=0;o<n&&o<r.length;o++){let i=r[o];t.set(o,i.charCode,i.fgColorCode,i.bgColorCode)}}rasterizeColorMap(e,t){let{posX:r,posY:n,sizeX:o,sizeY:i,colorData:a}=e;for(let s=0;s<i;s++){let d=n+s;if(!(d<0||d>=this.currentHeight))for(let c=0;c<o;c++){let l=r+c;if(l<0||l>=this.currentWidth)continue;let u=s*o+c;if(u>=a.length)break;let p=d*this.currentWidth+l,m=a[u];t.setColorsOnly(p,m.fgColorCode,m.bgColorCode)}}}rasterizeShape(e,t){let{shapeType:r,shapeData:n}=e;switch(r){case 1:this.rasterizeRectangle(n,t);break;case 2:this.rasterizeCircle(n,t);break;case 3:this.rasterizeLine(n,t);break;case 4:this.rasterizeEllipse(n,t);break;case 5:this.rasterizeTriangle(n,t);break}}rasterizeRectangle(e,t){let{posX:r,posY:n,width:o,height:i,filled:a,charCode:s,bgColorCode:d,fgColorCode:c}=e;if(a)for(let l=0;l<i;l++){let u=n+l;if(!(u<0||u>=this.currentHeight))for(let p=0;p<o;p++){let m=r+p;if(m<0||m>=this.currentWidth)continue;let g=u*this.currentWidth+m;t.set(g,s,c,d)}}else{for(let l=0;l<o;l++)this.setCell(r+l,n,s,d,c,t),this.setCell(r+l,n+i-1,s,d,c,t);for(let l=0;l<i;l++)this.setCell(r,n+l,s,d,c,t),this.setCell(r+o-1,n+l,s,d,c,t)}}rasterizeCircle(e,t){let{centerX:r,centerY:n,radius:o,filled:i,charCode:a,bgColorCode:s,fgColorCode:d}=e;if(i)for(let c=-o;c<=o;c++){let l=n+c;if(!(l<0||l>=this.currentHeight))for(let u=-o;u<=o;u++){let p=r+u;if(!(p<0||p>=this.currentWidth)&&u*u+c*c<=o*o){let m=l*this.currentWidth+p;t.set(m,a,d,s)}}}else{let c=o,l=0,u=0;for(;c>=l;)this.setCell(r+c,n+l,a,s,d,t),this.setCell(r+l,n+c,a,s,d,t),this.setCell(r-l,n+c,a,s,d,t),this.setCell(r-c,n+l,a,s,d,t),this.setCell(r-c,n-l,a,s,d,t),this.setCell(r-l,n-c,a,s,d,t),this.setCell(r+l,n-c,a,s,d,t),this.setCell(r+c,n-l,a,s,d,t),u<=0&&(l+=1,u+=2*l+1),u>0&&(c-=1,u-=2*c+1)}}rasterizeLine(e,t){let{x1:r,y1:n,x2:o,y2:i,charCode:a,bgColorCode:s,fgColorCode:d}=e,c=Math.abs(o-r),l=Math.abs(i-n),u=r<o?1:-1,p=n<i?1:-1,m=c-l,g=r,C=n;for(;this.setCell(g,C,a,s,d,t),!(g===o&&C===i);){let S=2*m;S>-l&&(m-=l,g+=u),S<c&&(m+=c,C+=p)}}rasterizePolyline(e,t){let{charCode:r,fgColorCode:n,bgColorCode:o,points:i}=e;if(i.length<2){i.length===1&&this.setCell(i[0].x,i[0].y,r,o,n,t);return}for(let a=0;a<i.length-1;a++){let s=i[a],d=i[a+1];this.rasterizeLineSegment(s.x,s.y,d.x,d.y,r,o,n,t)}}rasterizeLineSegment(e,t,r,n,o,i,a,s){let d=Math.abs(r-e),c=Math.abs(n-t),l=e<r?1:-1,u=t<n?1:-1,p=d-c,m=e,g=t;for(;this.setCell(m,g,o,i,a,s),!(m===r&&g===n);){let C=2*p;C>-c&&(p-=c,m+=l),C<d&&(p+=d,g+=u)}}rasterizeEllipse(e,t){let{centerX:r,centerY:n,radiusX:o,radiusY:i,filled:a,charCode:s,bgColorCode:d,fgColorCode:c}=e;if(a)for(let l=-i;l<=i;l++){let u=n+l;if(!(u<0||u>=this.currentHeight))for(let p=-o;p<=o;p++){let m=r+p;if(m<0||m>=this.currentWidth)continue;if(p*p/(o*o)+l*l/(i*i)<=1){let C=u*this.currentWidth+m;t.set(C,s,c,d)}}}else{let l=Math.max(o,i)*8;for(let u=0;u<l;u++){let p=2*Math.PI*u/l,m=Math.round(r+o*Math.cos(p)),g=Math.round(n+i*Math.sin(p));this.setCell(m,g,s,d,c,t)}}}rasterizeTriangle(e,t){let{x1:r,y1:n,x2:o,y2:i,x3:a,y3:s,filled:d,charCode:c,bgColorCode:l,fgColorCode:u}=e;if(d){let p=[{x:r,y:n},{x:o,y:i},{x:a,y:s}].sort((I,w)=>I.y-w.y),[m,g,C]=p,S=y((I,w,U)=>{let P=Math.round(Math.min(w,U)),R=Math.round(Math.max(w,U));for(let M=P;M<=R;M++)if(M>=0&&M<this.currentWidth&&I>=0&&I<this.currentHeight){let f=I*this.currentWidth+M;t.set(f,c,u,l)}},"drawLine"),O=y((I,w,U,P,R)=>P===w?U:U+(I-w)*(R-U)/(P-w),"interpolate");for(let I=m.y;I<=g.y;I++){let w=O(I,m.y,m.x,C.y,C.x),U=O(I,m.y,m.x,g.y,g.x);S(I,w,U)}for(let I=g.y+1;I<=C.y;I++){let w=O(I,m.y,m.x,C.y,C.x),U=O(I,g.y,g.x,C.y,C.x);S(I,w,U)}}else this.drawLineSegment(r,n,o,i,c,l,u,t),this.drawLineSegment(o,i,a,s,c,l,u,t),this.drawLineSegment(a,s,r,n,c,l,u,t)}drawLineSegment(e,t,r,n,o,i,a,s){let d=Math.abs(r-e),c=Math.abs(n-t),l=e<r?1:-1,u=t<n?1:-1,p=d-c,m=e,g=t;for(;this.setCell(m,g,o,i,a,s),!(m===r&&g===n);){let C=2*p;C>-c&&(p-=c,m+=l),C<d&&(p+=d,g+=u)}}rasterizeDotCloud(e,t){let{charCode:r,bgColorCode:n,fgColorCode:o,positions:i}=e,a=this.currentWidth;for(let s=0;s<i.length;s++){let d=i[s];if(d.posX<0||d.posX>=a||d.posY<0||d.posY>=this.currentHeight)continue;let c=d.posY*a+d.posX;t.set(c,r,o,n)}}rasterizeDotCloudMultiColor(e,t){let{dots:r}=e;for(let n of r)this.setCell(n.posX,n.posY,n.charCode,n.bgColorCode,n.fgColorCode,t)}rasterizeBitmask(e,t){let{posX:r,posY:n,sizeX:o,sizeY:i,charCode:a,bgColorCode:s,fgColorCode:d,override:c,mask:l}=e;for(let u=0;u<i;u++){let p=n+u;if(!(p<0||p>=this.currentHeight))for(let m=0;m<o;m++){let g=r+m;if(g<0||g>=this.currentWidth)continue;let C=u*o+m,S=Math.floor(C/8),O=C%8,I=(l[S]&1<<O)!==0,w=p*this.currentWidth+g;I?t.set(w,a,d,s):c&&t.set(w,255,255,255)}}}rasterizeBitmask4(e,t){let{posX:r,posY:n,sizeX:o,sizeY:i,override:a,variants:s,mask:d}=e;for(let c=0;c<i;c++){let l=n+c;if(!(l<0||l>=this.currentHeight))for(let u=0;u<o;u++){let p=r+u;if(p<0||p>=this.currentWidth)continue;let m=c*o+u,g=Math.floor(m/4),C=m%4*2,S=d[g]>>C&3,O=l*this.currentWidth+p;if(S>0){let I=s[S-1];t.set(O,I.charCode,I.fgColorCode,I.bgColorCode)}else a&&t.set(O,255,255,255)}}}rasterizeBitmask16(e,t){let{posX:r,posY:n,sizeX:o,sizeY:i,override:a,variants:s,mask:d}=e;for(let c=0;c<i;c++){let l=n+c;if(!(l<0||l>=this.currentHeight))for(let u=0;u<o;u++){let p=r+u;if(p<0||p>=this.currentWidth)continue;let m=c*o+u,g=Math.floor(m/2),C=m%2*4,S=d[g]>>C&15,O=l*this.currentWidth+p;if(S>0){let I=s[S-1];t.set(O,I.charCode,I.fgColorCode,I.bgColorCode)}else a&&t.set(O,255,255,255)}}}rasterizeClear(e,t){let{charCode:r,bgColorCode:n,fgColorCode:o}=e;t.clearWithColor(r,o,n)}rasterizeFillChar(e,t){let{patternWidth:r,patternHeight:n,pattern:o,bgColorCode:i,fgColorCode:a}=e;for(let s=0;s<this.currentHeight;s++)for(let d=0;d<this.currentWidth;d++){let c=d%r,u=s%n*r+c;if(u<o.length){let p=s*this.currentWidth+d;t.set(p,o[u],a,i)}}}rasterizeSprite(e,t,r){if(!r)return;let{posX:n,posY:o,spriteIndex:i,bgColorCode:a,fgColorCode:s}=e,d=r.getUnicolorSprite(i);if(!d)return;let c=d.data;for(let l=0;l<d.sizeY;l++)for(let u=0;u<d.sizeX;u++){let p=n+u,m=o+l;if(!this.isInBounds(p,m))continue;let g=l*d.sizeX+u,C=c.get(g);this.setCell(p,m,C,a,s,t)}}rasterizeSpriteMultiColor(e,t,r){if(!r)return;let{posX:n,posY:o,spriteIndex:i}=e,a=r.getMulticolorSprite(i);if(!a)return;let s=a.data;for(let d=0;d<a.sizeY;d++)for(let c=0;c<a.sizeX;c++){let l=n+c,u=o+d;if(!this.isInBounds(l,u))continue;let p=d*a.sizeX+c,m=s.getCharCode(p),g=s.getFgColorCode(p),C=s.getBgColorCode(p);this.setCell(l,u,m,C,g,t)}}rasterizeSpriteCloud(e,t,r){if(!r)return;let{spriteIndex:n,bgColorCode:o,fgColorCode:i,positions:a}=e,s=r.getUnicolorSprite(n);if(s){if(s.sizeX===1&&s.sizeY===1){let d=s.data.get(0),c=this.currentWidth;for(let l=0;l<a.length;l++){let u=a[l];if(u.posX<0||u.posX>=c||u.posY<0||u.posY>=this.currentHeight)continue;let p=u.posY*c+u.posX;t.set(p,d,i,o)}return}for(let d=0;d<a.length;d++){let c=s.data;for(let l=0;l<s.sizeY;l++)for(let u=0;u<s.sizeX;u++){let p=a[d].posX+u,m=a[d].posY+l;if(!this.isInBounds(p,m))continue;let g=l*s.sizeX+u,C=c.get(g);this.setCell(p,m,C,o,i,t)}}}}rasterizeSpriteCloudMultiColor(e,t,r){if(!r)return;let{spriteIndex:n,positions:o}=e,i=r.getMulticolorSprite(n);if(i)for(let a=0;a<o.length;a++){let s=i.data;for(let d=0;d<i.sizeY;d++)for(let c=0;c<i.sizeX;c++){let l=o[a].posX+c,u=o[a].posY+d;if(!this.isInBounds(l,u))continue;let p=d*i.sizeX+c,m=s.getCharCode(p),g=s.getFgColorCode(p),C=s.getBgColorCode(p);this.setCell(l,u,m,C,g,t)}}}rasterizeSpriteCloudVaried(e,t,r){if(!r)return;let{sprites:n}=e;for(let o=0;o<n.length;o++){let i=n[o],a=r.getUnicolorSprite(i.spriteIndex);if(!a)continue;let s=a.data;for(let d=0;d<a.sizeY;d++)for(let c=0;c<a.sizeX;c++){let l=i.posX+c,u=i.posY+d;if(!this.isInBounds(l,u))continue;let p=d*a.sizeX+c,m=s.get(p);this.setCell(l,u,m,i.bgColorCode,i.fgColorCode,t)}}}rasterizeSpriteCloudVariedMultiColor(e,t,r){if(!r)return;let{sprites:n}=e;for(let o=0;o<n.length;o++){let i=n[o],a=r.getMulticolorSprite(i.spriteIndex);if(!a)continue;let s=a.data;for(let d=0;d<a.sizeY;d++)for(let c=0;c<a.sizeX;c++){let l=i.posX+c,u=i.posY+d;if(!this.isInBounds(l,u))continue;let p=d*a.sizeX+c,m=s.getCharCode(p),g=s.getFgColorCode(p),C=s.getBgColorCode(p);this.setCell(l,u,m,C,g,t)}}}rasterizeFillSprite(e,t,r){if(!r)return;let{spriteIndex:n,bgColorCode:o,fgColorCode:i}=e,a=r.getUnicolorSprite(n);if(!a)return;let s=a.data;for(let d=0;d<this.currentHeight;d++)for(let c=0;c<this.currentWidth;c++){let l=c%a.sizeX,p=d%a.sizeY*a.sizeX+l,m=s.get(p),g=d*this.currentWidth+c;t.set(g,m,i,o)}}rasterizeFillSpriteMultiColor(e,t,r){if(!r)return;let{spriteIndex:n}=e,o=r.getMulticolorSprite(n);if(!o)return;let i=o.data;for(let a=0;a<this.currentHeight;a++)for(let s=0;s<this.currentWidth;s++){let d=s%o.sizeX,l=a%o.sizeY*o.sizeX+d,u=i.getCharCode(l),p=i.getFgColorCode(l),m=i.getBgColorCode(l),g=a*this.currentWidth+s;t.set(g,u,p,m)}}setCell(e,t,r,n,o,i){if(!this.isInBounds(e,t))return;let a=t*this.currentWidth+e;i.set(a,r,o,n)}isInBounds(e,t){return e>=0&&e<this.currentWidth&&t>=0&&t<this.currentHeight}};y(gt,"LayerRasterizer");var ke=gt;var Be=255,Y=class Y{constructor(e,t,r,n,o){b(this,"id",0);b(this,"origin");b(this,"orders",[]);b(this,"zOrder",0);b(this,"data");b(this,"width");b(this,"height");b(this,"isStatic",!1);b(this,"spriteRegistry");b(this,"mode","server");b(this,"charCodeMode");b(this,"previousOrigin");b(this,"previousZOrder");b(this,"enabled",!0);b(this,"useSetMode",!1);b(this,"needsCommit",!1);if(r<1||r>256||n<1||n>256)throw new Error(`Layer size must be 1-256, got ${r}\xD7${n}`);let i={};typeof o=="boolean"?i={isStatic:o}:o&&(i=o),this.origin=e,this.zOrder=t,this.width=r,this.height=n,this.isStatic=i.isStatic??!1,this.charCodeMode=i.charCodeMode??"8bit";let a=this.charCodeMode==="16bit";this.data=new G(r*n,a),this.previousOrigin=new Jn(e.x,e.y),this.previousZOrder=t}getCharCodeMode(){return this.charCodeMode}setMode(e){this.mode=e}setSpriteRegistry(e){this.spriteRegistry=e}getOrders(){return this.orders}addOrders(e){this.orders.push(...e),this.useSetMode=!1,(this.mode==="client"||this.mode==="standalone")&&Y.rasterizer.rasterizeOrders(this.orders,this.data,this.width,this.height,this.spriteRegistry)}addTemporaryOrders(e){(this.mode==="client"||this.mode==="standalone")&&Y.rasterizer.rasterizeOrders(e,this.data,this.width,this.height,this.spriteRegistry)}setOrders(e){this.orders=e,this.useSetMode=!0,(this.mode==="client"||this.mode==="standalone")&&Y.rasterizer.rasterizeOrders(e,this.data,this.width,this.height,this.spriteRegistry)}clearOrders(){this.orders=[],(this.mode==="client"||this.mode==="standalone")&&Y.rasterizer.clearBuffer(this.data)}getOrigin(){return this.origin}setOrigin(e){this.origin=e}getZOrder(){return this.zOrder}setZOrder(e){this.zOrder=e}getId(){return this.id}setId(e){this.id=e}getData(){return this.data}getWidth(){return this.width}getHeight(){return this.height}getCellAt(e,t){return e<0||e>=this.width||t<0||t>=this.height?null:this.data.get(t*this.width+e)}setStatic(e){this.isStatic=e}getStatic(){return this.isStatic}setEnabled(e){this.enabled=e}isEnabled(){return this.enabled}hasOriginChanged(){return this.origin.x!==this.previousOrigin.x||this.origin.y!==this.previousOrigin.y}hasZOrderChanged(){return this.zOrder!==this.previousZOrder}calculateUpdateFlags(){if(!this.enabled)return 0;let e=1;return this.useSetMode&&(e|=2),this.hasOriginChanged()&&(e|=4),this.hasZOrderChanged()&&(e|=8),(this.orders.length>0||this.needsCommit&&this.useSetMode)&&(e|=4),e}resetChangeTracking(){this.previousOrigin.x=this.origin.x,this.previousOrigin.y=this.origin.y,this.previousZOrder=this.zOrder}commit(){this.orders.length>Be&&(console.error(`[UTSP] \u26A0\uFE0F CRITICAL: Layer ${this.id} has ${this.orders.length} orders, but max is ${Be}!
|
|
3
|
+
This WILL cause packet corruption and decoding errors.
|
|
4
|
+
Solution: Split into multiple layers or reduce order count.
|
|
5
|
+
Orders breakdown: ${this.getOrdersBreakdown()}`),this.orders=this.orders.slice(0,Be)),this.needsCommit=!0}getOrdersBreakdown(){let e=new Map;for(let t of this.orders){let r=t.type??"unknown";e.set(r,(e.get(r)??0)+1)}return Array.from(e.entries()).map(([t,r])=>`0x${t.toString(16)}:${r}`).join(", ")}getNeedsCommit(){return this.needsCommit}resetCommit(){this.needsCommit=!1}};y(Y,"Layer"),b(Y,"rasterizer",new ke);var ae=Y;var yt=class yt{constructor(){b(this,"macros",new Map);b(this,"macroNameToId",new Map);b(this,"nextMacroId",0);b(this,"instances",new Map);b(this,"instanceNameToId",new Map);b(this,"nextInstanceId",0);b(this,"layerNameToId",new Map);b(this,"pendingOrders",[])}registerMacro(e){let t=e.id;if(this.macroNameToId.has(t)){let o=this.macroNameToId.get(t);return this.macros.set(o,{macroId:o,name:t,template:e}),o}let r=this.nextMacroId++;if(r>255)throw new Error("Maximum macro count (256) exceeded");let n={macroId:r,name:t,template:e};return this.macros.set(r,n),this.macroNameToId.set(t,r),r}getMacroByName(e){let t=this.macroNameToId.get(e);return t!==void 0?this.macros.get(t):void 0}getMacroById(e){return this.macros.get(e)}getMacroId(e){return this.macroNameToId.get(e)}toMacroLoad(e){let t=this.macros.get(e);if(t)return{loadType:7,macroId:t.macroId,template:t.template}}toAllMacroLoads(){let e=[];for(let t of this.macros.values())e.push({loadType:7,macroId:t.macroId,template:t.template});return e}setLayerMapping(e,t){this.layerNameToId.set(e,t)}createInstance(e){let t=this.macroNameToId.get(e.macro);if(t===void 0){console.warn(`MacroRegistry: Unknown macro "${e.macro}"`);return}let r=this.layerNameToId.get(e.layer);if(r===void 0){console.warn(`MacroRegistry: Unknown layer "${e.layer}"`);return}if(this.instanceNameToId.has(e.id))return console.warn(`MacroRegistry: Instance "${e.id}" already exists`),this.instanceNameToId.get(e.id);let n=this.nextInstanceId++;if(n>255)throw new Error("Maximum instance count (256) exceeded");let o={instanceId:n,name:e.id,macroId:t,layerId:r,x:e.x,y:e.y,tabIndex:e.tabIndex??0,params:e.params??{}};this.instances.set(n,o),this.instanceNameToId.set(e.id,n);let i={type:1,instanceId:n,macroId:t,layerId:r,x:e.x,y:e.y,tabIndex:e.tabIndex??0,params:e.params??{}};return this.pendingOrders.push(i),n}updateInstance(e,t){let r=this.instanceNameToId.get(e);if(r===void 0)return!1;let n=this.instances.get(r);if(!n)return!1;for(let i in t)n.params[i]=t[i];let o={type:2,instanceId:r,params:t};return this.pendingOrders.push(o),!0}removeInstance(e){let t=this.instanceNameToId.get(e);if(t===void 0)return!1;this.instances.delete(t),this.instanceNameToId.delete(e);let r={type:3,instanceId:t};return this.pendingOrders.push(r),!0}getInstanceByName(e){let t=this.instanceNameToId.get(e);return t!==void 0?this.instances.get(t):void 0}getInstanceById(e){return this.instances.get(e)}getInstanceName(e){return this.instances.get(e)?.name}flushPendingOrders(){let e=this.pendingOrders;return this.pendingOrders=[],e}hasPendingOrders(){return this.pendingOrders.length>0}getAllInstances(){return Array.from(this.instances.values())}clearInstances(){this.instances.clear(),this.instanceNameToId.clear(),this.nextInstanceId=0,this.pendingOrders=[]}clear(){this.macros.clear(),this.macroNameToId.clear(),this.nextMacroId=0,this.clearInstances()}};y(yt,"MacroRegistry");var se=yt;function V(h){return typeof h=="number"?h:h.charCodeAt(0)}y(V,"toCharCode");function de(h){return typeof h=="string"?h.charAt(0):String.fromCharCode(h)}y(de,"toCharString");var yn=(f=>(f[f.Char=1]="Char",f[f.Text=2]="Text",f[f.TextMultiline=23]="TextMultiline",f[f.SubFrame=3]="SubFrame",f[f.SubFrameMultiColor=4]="SubFrameMultiColor",f[f.FullFrame=5]="FullFrame",f[f.FullFrameMultiColor=6]="FullFrameMultiColor",f[f.Sprite=7]="Sprite",f[f.SpriteMultiColor=8]="SpriteMultiColor",f[f.ColorMap=9]="ColorMap",f[f.Shape=10]="Shape",f[f.DotCloud=11]="DotCloud",f[f.DotCloudMultiColor=12]="DotCloudMultiColor",f[f.SpriteCloud=13]="SpriteCloud",f[f.SpriteCloudMultiColor=14]="SpriteCloudMultiColor",f[f.SpriteCloudVaried=15]="SpriteCloudVaried",f[f.SpriteCloudVariedMultiColor=16]="SpriteCloudVariedMultiColor",f[f.Bitmask=17]="Bitmask",f[f.Bitmask4=18]="Bitmask4",f[f.Bitmask16=24]="Bitmask16",f[f.Polyline=25]="Polyline",f[f.Clear=19]="Clear",f[f.FillChar=20]="FillChar",f[f.FillSprite=21]="FillSprite",f[f.FillSpriteMultiColor=22]="FillSpriteMultiColor",f))(yn||{});function to(h){return h>=1&&h<=2||h>=3&&h<=6||h>=7&&h<=8||h>=9&&h<=10||h>=11&&h<=18||h>=19&&h<=23||h===24||h===25}y(to,"isValidOrderType");function ro(h){switch(h){case 1:return"Char";case 2:return"Text";case 3:return"SubFrame";case 4:return"SubFrameMultiColor";case 5:return"FullFrame";case 6:return"FullFrameMultiColor";case 7:return"Sprite";case 8:return"SpriteMultiColor";case 9:return"ColorMap";case 10:return"Shape";case 11:return"DotCloud";case 12:return"DotCloudMultiColor";case 13:return"SpriteCloud";case 14:return"SpriteCloudMultiColor";case 15:return"SpriteCloudVaried";case 16:return"SpriteCloudVariedMultiColor";case 17:return"Bitmask";case 18:return"Bitmask4";case 24:return"Bitmask16";case 25:return"Polyline";case 19:return"Clear";case 20:return"FillChar";case 21:return"FillSprite";case 22:return"FillSpriteMultiColor";default:return`Unknown(0x${h.toString(16)})`}}y(ro,"getOrderTypeName");var no={single:{topLeft:"\u250C",topRight:"\u2510",bottomLeft:"\u2514",bottomRight:"\u2518",horizontal:"\u2500",vertical:"\u2502"},double:{topLeft:"\u2554",topRight:"\u2557",bottomLeft:"\u255A",bottomRight:"\u255D",horizontal:"\u2550",vertical:"\u2551"},rounded:{topLeft:"\u256D",topRight:"\u256E",bottomLeft:"\u2570",bottomRight:"\u256F",horizontal:"\u2500",vertical:"\u2502"}},Ct={update(h,e,t,r){let n,o;e.subtype==="button"&&e.button?(n=t.resolveValue(e.button.width,h.params),o=t.resolveValue(e.button.height??3,h.params)):(n=t.resolveValue(h.params.width??1,h.params),o=t.resolveValue(h.params.height??1,h.params));let i=h.isHovered;h.isHovered=oo(t.mouseX,t.mouseY,h.x,h.y,n,o);let a=h.isActive;h.isActive=h.isHovered&&t.mouseDown,a&&!h.isActive&&h.isHovered&&(r.push({instanceId:h.instanceId,event:"click"}),e.subtype==="button"&&e.button?.soundRelease!==void 0&&t.playSound?.(e.button.soundRelease)),e.subtype==="button"&&e.button&&(!i&&h.isHovered&&e.button.soundHover!==void 0&&t.playSound?.(e.button.soundHover),!a&&h.isActive&&e.button.soundClick!==void 0&&t.playSound?.(e.button.soundClick))},render(h,e,t){let r=Cn(h),n=e.states[r]??e.states.normal,o={...h.params,...n},i=[];if(e.subtype==="button"&&e.button)io(h,e,o,i,t);else if(e.base)for(let a of e.base){let s=co(a,h.x,h.y,o,t);s&&i.push(s)}return i}};function oo(h,e,t,r,n,o){return h>=t&&h<t+n&&e>=r&&e<r+o}y(oo,"isPointInRect");function Cn(h){return h.isDisabled?"disabled":h.isActive?"active":h.isHovered?"hover":h.isFocused?"focused":"normal"}y(Cn,"getUIState");function ce(h){if(typeof h=="number")return Math.max(0,Math.min(255,Math.floor(h)));if(typeof h=="string"){let e=parseInt(h,10);if(!isNaN(e))return Math.max(0,Math.min(255,Math.floor(e)))}return 243}y(ce,"toColorIndex");function io(h,e,t,r,n){let o=e.button,i=Cn(h),a=e.states[i]??e.states.normal,s=n.resolveValue(o.width,t),d=n.resolveValue(o.height??3,t),c=n.resolveValue(o.label,t),l=o.border??"single",u=n.resolveValue(a.fg??15,t),p=n.resolveValue(a.bg??0,t),m=n.resolveValue(a.textFg??u,t),g=a.offsetY??0,C=h.x,S=h.y+g;l==="none"?ao(C,S,s,d,c,u,p,m,r):so(C,S,s,d,c,u,p,m,l,r)}y(io,"renderButton");function ao(h,e,t,r,n,o,i,a,s){if(r===1)s.push({type:2,posX:h,posY:e,text:" ".repeat(t),fgColorCode:o,bgColorCode:i});else for(let l=0;l<r;l++)s.push({type:2,posX:h,posY:e+l,text:" ".repeat(t),fgColorCode:o,bgColorCode:i});let d=h+Math.floor((t-n.length)/2),c=e+Math.floor(r/2);s.push({type:2,posX:d,posY:c,text:n,fgColorCode:a,bgColorCode:i})}y(ao,"renderButtonNoBorder");function so(h,e,t,r,n,o,i,a,s,d){let c=no[s];d.push({type:2,posX:h,posY:e,text:c.topLeft+c.horizontal.repeat(t-2)+c.topRight,fgColorCode:o,bgColorCode:i});for(let g=1;g<r-1;g++)d.push({type:2,posX:h,posY:e+g,text:c.vertical+" ".repeat(t-2)+c.vertical,fgColorCode:o,bgColorCode:i});d.push({type:2,posX:h,posY:e+r-1,text:c.bottomLeft+c.horizontal.repeat(t-2)+c.bottomRight,fgColorCode:o,bgColorCode:i});let l=t-2,u=r-2,p=h+1+Math.floor((l-n.length)/2),m=e+1+Math.floor(u/2);d.push({type:2,posX:p,posY:m,text:n,fgColorCode:a,bgColorCode:i})}y(so,"renderButtonWithBorder");function co(h,e,t,r,n){if(h.fillRect){let[o,i,a,s,d,c,l]=h.fillRect;return{type:3,posX:e+n.resolveValue(o,r),posY:t+n.resolveValue(i,r),sizeX:n.resolveValue(a,r),sizeY:n.resolveValue(s,r),fgColorCode:ce(n.resolveValue(c,r)),bgColorCode:ce(n.resolveValue(l,r)),frame:Array(n.resolveValue(a,r)*n.resolveValue(s,r)).fill(V(d))}}if(h.text){let[o,i,a,s]=h.text;return{type:2,posX:e+n.resolveValue(o,r),posY:t+n.resolveValue(i,r),text:n.resolveValue(a,r),fgColorCode:ce(n.resolveValue(s,r)),bgColorCode:255}}if(h.setCell){let[o,i,a,s,d]=h.setCell;return{type:1,posX:e+n.resolveValue(o,r),posY:t+n.resolveValue(i,r),charCode:V(n.resolveValue(a,r)),fgColorCode:ce(n.resolveValue(s,r)),bgColorCode:ce(n.resolveValue(d,r))}}return null}y(co,"executeRenderCommand");function xn(h,e,t,r,n,o,i){return{type:"ui",instanceId:h,macroId:e,layerId:t,x:r,y:n,params:o,tabIndex:i,isHovered:!1,isFocused:!1,isActive:!1,isDisabled:!1}}y(xn,"createUIInstance");var ft=class ft{update(e,t,r,n){let o=t.emitter,{resolveValue:i}=r;if(!e.emitDone){if(o.burst){let a=i(o.burst,e.params);for(let s=0;s<a&&!(o.limit&&e.particles.length>=o.limit);s++)e.particles.push(this.createParticle(e,t,r));o.once&&(e.emitDone=!0)}else if(o.rate){let a=i(o.rate,e.params);for(e.timeSinceEmit+=a;e.timeSinceEmit>=1&&!(o.limit&&e.particles.length>=o.limit);)e.particles.push(this.createParticle(e,t,r)),e.timeSinceEmit-=1}}for(let a=e.particles.length-1;a>=0;a--){let s=e.particles[a];s.x+=s.vx,s.y+=s.vy,s.lifetime-=1,s.lifetime<=0&&e.particles.splice(a,1)}}render(e,t,r){if(e.particles.length===0)return[];let{resolveValue:n}=r,o=t.emitter,i=o.viewport??o.zone,a=n(i.x,e.params),s=n(i.y,e.params),d=n(i.width,e.params),c=n(i.height,e.params),l=e.x+(typeof a=="number"?a:0),u=e.y+(typeof s=="number"?s:0),p=typeof d=="number"?d:0,m=typeof c=="number"?c:0;if(p<=0||m<=0)return[];let g=[];for(let C of e.particles){let S=Math.floor(C.x),O=Math.floor(C.y);if(S<l||S>=l+p||O<u||O>=u+m)continue;let I=C.fg;if(t.particle.fade&&C.maxLifetime>0){let w=C.lifetime/C.maxLifetime;I=this.fadeColorIndex(C.fg,w)}g.push({charCode:V(C.char),fgColorCode:I,bgColorCode:C.bg??255,posX:S,posY:O})}return[{type:12,dots:g}]}createParticle(e,t,r){let{resolveValue:n,resolveRandomValue:o}=r,i=t.emitter,a=t.particle,s=n(i.zone.x,e.params),d=n(i.zone.y,e.params),c=n(i.zone.width,e.params),l=n(i.zone.height,e.params),u=e.x+s+Math.random()*c,p=e.y+d+Math.random()*l,m=0,g=0;if("x"in a.velocity&&"y"in a.velocity)m=n(a.velocity.x,e.params),g=n(a.velocity.y,e.params);else if("angle"in a.velocity&&"speed"in a.velocity){let R=o(a.velocity.angle),M=o(a.velocity.speed,e.params),f=R*Math.PI/180;m=Math.cos(f)*M,g=Math.sin(f)*M}let C=o(a.lifetime),S=Array.isArray(a.char)?a.char[Math.floor(Math.random()*a.char.length)]:a.char,O=de(S),I=Array.isArray(a.fg)?a.fg[Math.floor(Math.random()*a.fg.length)]:a.fg,w=typeof I=="number"?I:parseInt(I,10)||243,U=a.bg?Array.isArray(a.bg)?a.bg[Math.floor(Math.random()*a.bg.length)]:a.bg:void 0,P=U!==void 0?typeof U=="number"?U:parseInt(U,10)||255:void 0;return{x:u,y:p,vx:m,vy:g,char:O,fg:w,bg:P,lifetime:C,maxLifetime:C}}fadeColorIndex(e,t){return t<.1?255:e}};y(ft,"ParticleHandler");var ze=ft;var St=class St{update(e,t,r,n){e.elapsed+=1;let o=Math.min(1,e.elapsed/e.duration),i=t.transform.decay?1-o:1,a=t.transform.offset;a&&(e.currentOffsetX=this.resolveRandomOffset(a.x,e.params,r)*i,e.currentOffsetY=this.resolveRandomOffset(a.y,e.params,r)*i),e.elapsed>=e.duration&&(n.push({instanceId:e.instanceId,event:"complete"}),r.deleteInstance(e.instanceId))}render(e,t,r){return[]}getOffset(e){return{x:e.currentOffsetX,y:e.currentOffsetY}}resolveRandomOffset(e,t,r){if(typeof e=="number")return e;if(typeof e=="string")return r.resolveValue(e,t);if(typeof e=="object"&&"random"in e){let[n,o]=e.random,i=r.resolveValue(n,t),a=r.resolveValue(o,t);return i+Math.random()*(a-i)}return 0}};y(St,"EffectHandler");var Te=St;var It=class It{constructor(){b(this,"spriteRegistry",null)}setSpriteRegistry(e){this.spriteRegistry=e}update(e,t,r,n){if(e.finished)return;if(e.delayRemaining>0){e.delayRemaining--;return}if(e.pauseRemaining>0){e.pauseRemaining--;return}let o=t.cursor?.blinkRate??15;e.blinkTimer++,e.blinkTimer>=o&&(e.blinkTimer=0,e.blinkState=!e.blinkState);let i=e.speed;if(e.direction==="reveal"){let s=Math.min(i,e.totalCells-e.revealedCount);if(t.pauseOn&&s>0){let d=e.cells[e.revealedCount];d&&t.pauseOn.chars.includes(d.char)&&(e.pauseRemaining=t.pauseOn.duration)}e.revealedCount+=s,e.revealedCount>=e.totalCells&&(e.finished=!0,n.push({instanceId:e.instanceId,event:"complete"}))}else{let s=Math.min(i,e.revealedCount);e.revealedCount-=s,e.revealedCount<=0&&(e.finished=!0,n.push({instanceId:e.instanceId,event:"complete"}))}}render(e,t,r){let n=[],o=e.cells.slice(0,e.revealedCount),i=new Map;for(let a of o)i.has(a.y)||i.set(a.y,[]),i.get(a.y).push(a);for(let[a,s]of i){s.sort((c,l)=>c.x-l.x);let d=0;for(;d<s.length;){let c=s[d],l=d+1;for(;l<s.length&&s[l].x===s[l-1].x+1&&s[l].fg===c.fg&&s[l].bg===c.bg;)l++;if(l-d===1)n.push({type:1,posX:e.x+c.x,posY:e.y+a,charCode:c.char.charCodeAt(0),fgColorCode:c.fg,bgColorCode:c.bg});else{let p="";for(let m=d;m<l;m++)p+=s[m].char;n.push({type:2,posX:e.x+c.x,posY:e.y+a,text:p,fgColorCode:c.fg,bgColorCode:c.bg})}d=l}}if(t.cursor&&!e.finished&&(!t.cursor.blink||e.blinkState)&&e.revealedCount<e.cells.length){let s=e.cells[e.revealedCount];if(s){let d=t.cursor.bg??s.bg;n.push({type:1,posX:e.x+s.x,posY:e.y+s.y,charCode:V(t.cursor.char),fgColorCode:t.cursor.fg??15,bgColorCode:d})}}return n}buildCells(e,t,r){let n=[],o=e.content;switch(o.type){case"text":{let i=r(o.text,t),a=r(o.fg??15,t),s=r(o.bg??0,t),d=i.split(`
|
|
6
|
+
`);for(let c=0;c<d.length;c++){let l=d[c];for(let u=0;u<l.length;u++)n.push({char:l[u],fg:a,bg:s,x:u,y:c,revealOrder:0})}break}case"sprite":{if(!this.spriteRegistry)break;let i=r(o.sprite,t);if(o.multicolor!==!1){let d=this.spriteRegistry.getMulticolorSprite(i);if(d){let{sizeX:c,sizeY:l,data:u}=d;for(let p=0;p<l;p++)for(let m=0;m<c;m++){let g=p*c+m,C=u.get(g);C.charCode!==0&&n.push({char:String.fromCharCode(C.charCode),fg:C.fgColorCode,bg:C.bgColorCode,x:m,y:p,revealOrder:0})}break}}let s=this.spriteRegistry.getUnicolorSprite(i);if(s){let{sizeX:d,sizeY:c,data:l}=s,u=r(o.fg??15,t),p=r(o.bg??0,t);for(let m=0;m<c;m++)for(let g=0;g<d;g++){let C=m*d+g,S=l.get(C);S!==0&&n.push({char:String.fromCharCode(S),fg:u,bg:p,x:g,y:m,revealOrder:0})}}break}case"cells":{for(let i of o.cells)n.push({char:de(i.char),fg:i.fg,bg:i.bg,x:i.x,y:i.y,revealOrder:0});break}case"fill":{let i=de(o.char),a=r(o.fg,t),s=r(o.bg,t),d=r(o.width,t),c=r(o.height,t);for(let l=0;l<c;l++)for(let u=0;u<d;u++)n.push({char:i,fg:a,bg:s,x:u,y:l,revealOrder:0});break}}return this.assignRevealOrder(n,e.pattern,e.direction),n}assignRevealOrder(e,t,r){if(e.length===0)return;let n=0,o=0;for(let s of e)s.x>n&&(n=s.x),s.y>o&&(o=s.y);let i=n+1,a=o+1;switch(t){case"typewriter":for(let s of e)s.revealOrder=s.y*i+s.x;break;case"typewriter-rev":for(let s of e)s.revealOrder=(a-1-s.y)*i+(i-1-s.x);break;case"ltr":for(let s of e)s.revealOrder=s.x*a+s.y;break;case"rtl":for(let s of e)s.revealOrder=(i-1-s.x)*a+s.y;break;case"ttb":for(let s of e)s.revealOrder=s.y;break;case"btt":for(let s of e)s.revealOrder=a-1-s.y;break;case"random":{let s=e.map((d,c)=>c);for(let d=s.length-1;d>0;d--){let c=Math.floor(Math.random()*(d+1));[s[d],s[c]]=[s[c],s[d]]}for(let d=0;d<e.length;d++)e[d].revealOrder=s[d];break}case"center-out":{let s=(i-1)/2,d=(a-1)/2;for(let c of e)c.revealOrder=Math.abs(c.x-s)+Math.abs(c.y-d);break}case"spiral":{let s=(i-1)/2,d=(a-1)/2,c=Math.max(s,d);for(let l of e){let u=Math.abs(l.x-s),p=Math.abs(l.y-d),m=Math.max(u,p);l.revealOrder=c-m+(l.y*i+l.x)*.001}break}}e.sort((s,d)=>s.revealOrder-d.revealOrder);for(let s=0;s<e.length;s++)e[s].revealOrder=s}};y(It,"RevealHandler");var Fe=It;var Ot=class Ot{update(e,t,r,n){let{resolveValue:o}=r,i=e.params;e.currentTick++;let a=i.point;if(a&&typeof a.x=="number"&&typeof a.y=="number"){e.points.push({x:a.x,y:a.y,addedAt:e.currentTick}),delete i.point;let d=o(t.maxPoints,i)??100;for(;e.points.length>d;)e.points.shift()}i.clear===!0&&(e.points=[],delete i.clear);let s=i.points;if(Array.isArray(s)){e.points=s.map(c=>({x:c.x,y:c.y,addedAt:e.currentTick})),delete i.points;let d=o(t.maxPoints,i)??100;for(;e.points.length>d;)e.points.shift()}}render(e,t,r){let{resolveValue:n}=r,o=e.params,i=e.points;if(i.length===0)return[];let a=n(t.char,o),s=n(t.fg,o)??15,d=n(t.bg,o)??255,c=t.closed??!1,l=t.fadeOut??!1,u=i.map(m=>({x:e.x+m.x,y:e.y+m.y}));return c&&u.length>=2&&u.push({...u[0]}),l&&i.length>=2?this.renderFadedLine(e,t,r,u,a,s,d):[{type:25,charCode:V(a),fgColorCode:s,bgColorCode:d,points:u.map(m=>({x:m.x&255,y:m.y&255}))}]}renderFadedLine(e,t,r,n,o,i,a){let s=e.params,d=t.fadeLength??n.length,c=[],l=n.length,u=Math.max(0,l-d);if(u>0){let m=n.slice(0,u+1);m.length>=2&&c.push({type:25,charCode:V(o),fgColorCode:i,bgColorCode:a,points:m.map(g=>({x:g.x&255,y:g.y&255}))})}let p=n.slice(u);if(p.length>=2){let m=Math.max(0,i-8);c.push({type:25,charCode:V(o),fgColorCode:m,bgColorCode:a,points:p.map(g=>({x:g.x&255,y:g.y&255}))})}return c}};y(Ot,"LineHandler");var Le=Ot;var uo=!1;function j(...h){uo&&console.log("[MacroEngine]",...h)}y(j,"macroLog");var wt=class wt{constructor(){b(this,"templates",new Map);b(this,"instances",new Map);b(this,"spriteRegistry",null);b(this,"playSound",null);b(this,"focusedInstanceId",null);b(this,"focusableInstances",[]);b(this,"mouseX",0);b(this,"mouseY",0);b(this,"mouseDown",!1);b(this,"particleHandler",new ze);b(this,"effectHandler",new Te);b(this,"revealHandler",new Fe);b(this,"lineHandler",new Le);b(this,"instancesToDelete",[])}setSpriteRegistry(e){this.spriteRegistry=e,this.revealHandler.setSpriteRegistry(e)}setAudioCallback(e){this.playSound=e}createContext(){return{mouseX:this.mouseX,mouseY:this.mouseY,mouseDown:this.mouseDown,playSound:this.playSound??void 0,getTemplate:e=>this.getTemplate(e),resolveValue:(e,t)=>this.resolveValue(e,t),resolveRandomValue:(e,t)=>this.resolveRandomValue(e,t),deleteInstance:e=>{this.instancesToDelete.push(e)}}}loadTemplate(e,t){j(`loadTemplate: macroId=${e}, type=${t.type}`),this.templates.set(e,{macroId:e,template:t})}getTemplate(e){return this.templates.get(e)?.template}hasTemplate(e){return this.templates.has(e)}applyOrder(e){switch(j(`applyOrder: type=${e.type}, instanceId=${e.instanceId}`),e.type){case 1:this.createInstance(e);break;case 2:this.updateInstance(e);break;case 3:this.removeInstance(e);break}}createInstance(e){let t=this.getTemplate(e.macroId);if(!t){j(`createInstance: FAILED - template ${e.macroId} not found`);return}j(`createInstance: id=${e.instanceId}, macroId=${e.macroId}, type=${t.type}, pos=(${e.x}, ${e.y}), layer=${e.layerId}`);let r;switch(t.type){case"ui":r=xn(e.instanceId,e.macroId,e.layerId,e.x,e.y,e.params,e.tabIndex),e.tabIndex>0&&this.addToFocusableList(e.instanceId,e.tabIndex);break;case"particle":r={type:"particle",instanceId:e.instanceId,macroId:e.macroId,layerId:e.layerId,x:e.x,y:e.y,params:e.params,particles:[],timeSinceEmit:0,emitDone:!1};break;case"effect":{let n=t;r={type:"effect",instanceId:e.instanceId,macroId:e.macroId,layerId:e.layerId,x:e.x,y:e.y,params:e.params,elapsed:0,duration:this.resolveValue(n.transform.duration,e.params),currentOffsetX:0,currentOffsetY:0};break}case"reveal":{let n=t,o=this.revealHandler.buildCells(n,e.params,(s,d)=>this.resolveValue(s,d)),i=o.length,a=n.direction??"reveal";r={type:"reveal",instanceId:e.instanceId,macroId:e.macroId,layerId:e.layerId,x:e.x,y:e.y,params:e.params,cells:o,revealedCount:a==="hide"?i:0,totalCells:i,delayRemaining:n.delay??0,pauseRemaining:0,finished:!1,direction:a,speed:n.speed??1,blinkState:!0,blinkTimer:0};break}case"line":{let n=[],o=e.params.points;if(Array.isArray(o)){for(let a of o)n.push({x:a.x,y:a.y,addedAt:0});delete e.params.points}let i=e.params.point;i&&typeof i.x=="number"&&typeof i.y=="number"&&(n.push({x:i.x,y:i.y,addedAt:0}),delete e.params.point),r={type:"line",instanceId:e.instanceId,macroId:e.macroId,layerId:e.layerId,x:e.x,y:e.y,params:e.params,points:n,currentTick:0};break}default:return}r&&this.instances.set(e.instanceId,r)}updateInstance(e){let t=this.instances.get(e.instanceId);if(t)for(let r in e.params)t.params[r]=e.params[r]}removeInstance(e){let t=this.instances.get(e.instanceId);t&&(t.type==="ui"&&(this.removeFromFocusableList(e.instanceId),this.focusedInstanceId===e.instanceId&&(this.focusedInstanceId=null)),this.instances.delete(e.instanceId))}addToFocusableList(e,t){this.focusableInstances.push(e),this.focusableInstances.sort((r,n)=>{let o=this.instances.get(r),i=this.instances.get(n);return(o?.tabIndex??0)-(i?.tabIndex??0)})}removeFromFocusableList(e){let t=this.focusableInstances.indexOf(e);t!==-1&&this.focusableInstances.splice(t,1)}focusNext(){if(this.focusableInstances.length===0)return;let t=((this.focusedInstanceId!==null?this.focusableInstances.indexOf(this.focusedInstanceId):-1)+1)%this.focusableInstances.length;this.setFocus(this.focusableInstances[t])}focusPrevious(){if(this.focusableInstances.length===0)return;let t=((this.focusedInstanceId!==null?this.focusableInstances.indexOf(this.focusedInstanceId):0)-1+this.focusableInstances.length)%this.focusableInstances.length;this.setFocus(this.focusableInstances[t])}setFocus(e){if(this.focusedInstanceId!==null){let t=this.instances.get(this.focusedInstanceId);t?.type==="ui"&&(t.isFocused=!1)}if(this.focusedInstanceId=e,e!==null){let t=this.instances.get(e);t?.type==="ui"&&(t.isFocused=!0)}}updateMouse(e,t,r){this.mouseX=e,this.mouseY=t,this.mouseDown=r}estimateUISize(e,t){if(e.subtype==="button"&&e.button){let o=this.resolveValue(e.button.width,t??{}),i=this.resolveValue(e.button.height??3,t??{});return{width:o,height:i}}let r=1,n=1;if(e.base)for(let o of e.base)"w"in o&&typeof o.w=="number"&&(r=Math.max(r,o.w)),"h"in o&&typeof o.h=="number"&&(n=Math.max(n,o.h));return{width:r,height:n}}activateFocused(){if(this.focusedInstanceId===null)return;let e=this.instances.get(this.focusedInstanceId);e?.type==="ui"&&(e.isActive=!0)}update(){let e=[];this.instances.size>0&&j(`update: instances=${this.instances.size}, templates=${this.templates.size}`);let t=this.createContext();this.instancesToDelete=[];for(let n of this.instances.values()){let o=this.getTemplate(n.macroId);if(o)switch(n.type){case"ui":Ct.update(n,o,t,e);break;case"particle":this.particleHandler.update(n,o,t,e);break;case"effect":this.effectHandler.update(n,o,t,e);break;case"reveal":this.revealHandler.update(n,o,t,e);break;case"line":this.lineHandler.update(n,o,t,e);break}}for(let n of this.instancesToDelete)this.instances.delete(n);return{events:e.map(n=>({instanceId:n.instanceId,event:n.event,data:n.data}))}}getOrdersByLayer(){let e=new Map;for(let t of this.instances.values()){let r=this.renderInstance(t);r.length!==0&&(e.has(t.layerId)||e.set(t.layerId,[]),e.get(t.layerId).push(...r))}if(e.size>0){let t=0;for(let r of e.values())t+=r.length;j(`getOrdersByLayer: ${e.size} layers, ${t} total orders`)}return e}renderInstance(e){let t=this.getTemplate(e.macroId);if(!t)return[];let r=this.createContext();switch(e.type){case"ui":return Ct.render(e,t,r);case"particle":return this.particleHandler.render(e,t,r);case"effect":return this.effectHandler.render(e,t,r);case"reveal":return this.revealHandler.render(e,t,r);case"line":return this.lineHandler.render(e,t,r);default:return[]}}resolveValue(e,t){if(typeof e=="string"&&e.startsWith("$")){let r=e.slice(1);return t[r]??e}return e}resolveRandomValue(e,t){if(typeof e=="string"){let r=this.resolveValue(e,t??{});return typeof r=="number"?r:0}if(Array.isArray(e)){let[r,n]=e;return r+Math.random()*(n-r)}return e}getEffectOffset(){let e=0,t=0;for(let r of this.instances.values())r.type==="effect"&&(e+=r.currentOffsetX,t+=r.currentOffsetY);return{x:e,y:t}}getAllInstances(){return Array.from(this.instances.values())}getInstanceCount(){return this.instances.size}clear(){this.templates.clear(),this.instances.clear(),this.focusedInstanceId=null,this.focusableInstances=[]}};y(wt,"MacroEngine");var le=wt;var vt=class vt{constructor(){b(this,"axes",new Map);b(this,"buttons",new Map);b(this,"touchZones",new Map);b(this,"axisNameToId",new Map);b(this,"buttonNameToId",new Map);b(this,"touchZoneNameToId",new Map);b(this,"version",1)}defineAxis(e,t,r=[],n=-1,o=1,i=0){if(e<0||e>255)throw new Error(`Axis bindingId must be between 0 and 255, got ${e}`);if(this.axes.has(e))throw new Error(`Axis bindingId ${e} is already defined`);if(this.axisNameToId.has(t)){let s=this.axisNameToId.get(t);throw new Error(`Axis name "${t}" is already defined with bindingId ${s}`)}let a={bindingId:e,name:t,min:n,max:o,defaultValue:i,sources:r};this.axes.set(e,a),this.axisNameToId.set(t,e),this.version++}defineButton(e,t,r=[],n=!1){if(e<0||e>255)throw new Error(`Button bindingId must be between 0 and 255, got ${e}`);if(this.buttons.has(e))throw new Error(`Button bindingId ${e} is already defined`);if(this.buttonNameToId.has(t)){let i=this.buttonNameToId.get(t);throw new Error(`Button name "${t}" is already defined with bindingId ${i}`)}let o={bindingId:e,name:t,defaultValue:n,sources:r};this.buttons.set(e,o),this.buttonNameToId.set(t,e),this.version++}defineTouchZone(e,t,r,n,o,i){if(e<0||e>31)throw new Error(`Touch zone zoneId must be between 0 and 31, got ${e}`);if(this.touchZones.has(e))throw new Error(`Touch zone zoneId ${e} is already defined`);if(this.touchZoneNameToId.has(t)){let s=this.touchZoneNameToId.get(t);throw new Error(`Touch zone name "${t}" is already defined with zoneId ${s}`)}if(o<=0||i<=0)throw new Error(`Touch zone dimensions must be positive, got ${o}x${i}`);let a={zoneId:e,name:t,x:r,y:n,width:o,height:i};this.touchZones.set(e,a),this.touchZoneNameToId.set(t,e),this.version++}evaluateAxis(e,t){let r=this.axes.get(e);if(!r)return 0;let n=0;for(let i of r.sources){let s=t.get(i.sourceId)??0,d=i.deadzone??0;Math.abs(s)<d?s=0:s=(s>0?1:-1)*((Math.abs(s)-d)/(1-d));let c=i.scale??1;s*=c;let l=i.sensitivity??1;s*=l,i.invert&&(s=-s),n+=s}return Math.max(r.min,Math.min(r.max,n))}evaluateButton(e,t){let r=this.buttons.get(e);if(!r)return!1;for(let n of r.sources)if(t.get(n.sourceId)??!1)return!0;return!1}toLoadPacket(){let e={type:"input-binding",version:this.version,axes:Array.from(this.axes.values()),buttons:Array.from(this.buttons.values()),touchZones:this.touchZones.size>0?Array.from(this.touchZones.values()):void 0};return JSON.stringify(e)}toLoadPacketObject(){return{type:"input-binding",version:this.version,axes:Array.from(this.axes.values()),buttons:Array.from(this.buttons.values()),touchZones:this.touchZones.size>0?Array.from(this.touchZones.values()):void 0}}getAxisBindingId(e){return this.axisNameToId.get(e)??null}getButtonBindingId(e){return this.buttonNameToId.get(e)??null}getAxisName(e){return this.axes.get(e)?.name??null}getButtonName(e){return this.buttons.get(e)?.name??null}getAxisBinding(e){return this.axes.get(e)??null}getButtonBinding(e){return this.buttons.get(e)??null}hasAxis(e){return this.axes.has(e)}hasButton(e){return this.buttons.has(e)}hasTouchZone(e){return this.touchZones.has(e)}getAxisCount(){return this.axes.size}getButtonCount(){return this.buttons.size}getTouchZoneCount(){return this.touchZones.size}getAllAxes(){return Array.from(this.axes.values())}getAllButtons(){return Array.from(this.buttons.values())}getAllTouchZones(){return Array.from(this.touchZones.values())}getTouchZone(e){return this.touchZones.get(e)??null}getTouchZoneId(e){return this.touchZoneNameToId.get(e)??null}getVersion(){return this.version}removeAxis(e){let t=this.axes.get(e);return t?(this.axes.delete(e),this.axisNameToId.delete(t.name),this.version++,!0):!1}removeButton(e){let t=this.buttons.get(e);return t?(this.buttons.delete(e),this.buttonNameToId.delete(t.name),this.version++,!0):!1}removeTouchZone(e){let t=this.touchZones.get(e);return t?(this.touchZones.delete(e),this.touchZoneNameToId.delete(t.name),this.version++,!0):!1}clearAxes(){this.axes.clear(),this.axisNameToId.clear(),this.version++}clearButtons(){this.buttons.clear(),this.buttonNameToId.clear(),this.version++}clearTouchZones(){this.touchZones.clear(),this.touchZoneNameToId.clear(),this.version++}clear(){this.axes.clear(),this.axisNameToId.clear(),this.buttons.clear(),this.buttonNameToId.clear(),this.touchZones.clear(),this.touchZoneNameToId.clear(),this.version=1}toString(){let e=`InputBindingRegistry (version ${this.version})
|
|
4
7
|
`;return e+=`Axes (${this.axes.size}):
|
|
5
8
|
`,this.axes.forEach(t=>{e+=` [${t.bindingId}] ${t.name}: `,e+=`${t.min} to ${t.max} (default: ${t.defaultValue})
|
|
6
9
|
`}),e+=`Buttons (${this.buttons.size}):
|
|
7
10
|
`,this.buttons.forEach(t=>{e+=` [${t.bindingId}] ${t.name}: `,e+=`(default: ${t.defaultValue})
|
|
8
|
-
`}),e}};y(Ot,"InputBindingRegistry");var ue=Ot;function wt(h=0n){return{tick:h,axes:new Map,buttons:new Map,displayId:0,mouseX:0,mouseY:0,mouseOverDisplay:!1,textInputs:[],macroEvents:[],displayViewports:[]}}y(wt,"createEmptyCompressedInputPacket");function Ut(h){let e=Math.max(-1,Math.min(1,h));return Math.round(e*127)}y(Ut,"encodeAxisToInt8");function vt(h){return h/127}y(vt,"decodeInt8ToAxis");function J(h){return h===0?0:Math.ceil(h/8)}y(J,"getButtonByteCount");function Mt(h,e){let r=h,n=J(e);return 8+r+n+4}y(Mt,"getCompressedPacketSize");var At=class At{decode(e,t=0){let r=e.readUInt8(t);switch(r){case 1:return this.decodeClick(e,t);case 2:return this.decodeChange(e,t);case 3:return this.decodeSubmit(e,t);case 4:return this.decodeSelect(e,t);default:throw new Error(`Unknown macro event type: 0x${r.toString(16)}`)}}decodeAll(e,t,r){let n=[],o=0;for(let i=0;i<r;i++){let{event:a,bytesRead:s}=this.decode(e,t+o);n.push(a),o+=s}return{events:n,bytesRead:o}}decodeClick(e,t){let r=e.readUInt8(t),n=e.readUInt8(t+1);return{event:{type:r,instanceId:n},bytesRead:2}}decodeChange(e,t){let r=e.readUInt8(t),n=e.readUInt8(t+1),o=e.readUInt8(t+2),i,a;return o===1?(i=e.readUInt8(t+3)===1,a=4):(i=e.readFloatBE(t+3),a=7),{event:{type:r,instanceId:n,value:i},bytesRead:a}}decodeSubmit(e,t){let r=t,n=e.readUInt8(t++),o=e.readUInt8(t++),i=e.readUInt16BE(t);t+=2;let a=e.toUint8Array().subarray(t,t+i);t+=i;let s=new TextDecoder().decode(a);return{event:{type:n,instanceId:o,text:s},bytesRead:t-r}}decodeSelect(e,t){let r=e.readUInt8(t),n=e.readUInt8(t+1),o=e.readUInt16BE(t+2);return{event:{type:r,instanceId:n,index:o},bytesRead:4}}};y(At,"MacroEventDecoder");var Le=At;L();function Et(h,e){let t=e.getAllAxes().length,r=e.getAllButtons().length,n=J(r),o=8+t+n+4;if(h.length<o)throw new Error(`Invalid compressed input packet: expected at least ${o} bytes (${t} axes + ${r} buttons), got ${h.length}`);let i=new DataView(h.buffer,h.byteOffset,h.byteLength),a=0,s=wt();s.tick=i.getBigUint64(a,!0),a+=8;for(let c=0;c<t;c++){let l=h[a],u=l>127?l-256:l,p=vt(u);s.axes.set(c,p),a+=1}for(let c=0;c<n;c++){let l=h[a];for(let u=0;u<8;u++){let p=c*8+u;if(p<r){let m=(l&1<<u)!==0;s.buttons.set(p,m)}}a+=1}s.displayId=h[a],a+=1,s.mouseX=h[a],a+=1,s.mouseY=h[a],a+=1;let d=h[a];if(s.mouseOverDisplay=(d&1)!==0,a+=1,a<h.length){let c=h[a];a+=1;let l=new TextDecoder;s.textInputs=[];for(let u=0;u<c&&a<h.length;u++){let p=h[a];if(a+=1,a+p<=h.length){let m=h.slice(a,a+p),g=l.decode(m);s.textInputs.push(g),a+=p}}}if(a<h.length){let c=h[a];a+=1;let l=new Le,u=[],p=f.from(h);for(let m=0;m<c&&a<h.length;m++){let g=l.decode(p,a);u.push(g.event),a+=g.bytesRead}s.macroEvents=u}if(a<h.length){let c=h[a];a+=1;for(let l=0;l<c&&a+5<=h.length;l++){let u=h[a];a+=1;let p=i.getUint16(a,!1);a+=2;let m=i.getUint16(a,!1);a+=2,s.displayViewports.push({displayId:u,pixelWidth:p,pixelHeight:m})}}return s}y(Et,"decodeCompressedInput");import{Vector2 as De,POST_PROCESS_DEFAULTS as D,GRID_DEFAULTS as Ve}from"@utsp/types";var Pt=class Pt{constructor(e,t){b(this,"enabled",!1);b(this,"currentStats",null);b(this,"_userId");b(this,"_userName");this._userId=e,this._userName=t}setEnabled(e){this.enabled=e,e||(this.currentStats=null)}isEnabled(){return this.enabled}get userId(){return this.currentStats?.userId??this._userId}get userName(){return this.currentStats?.userName??this._userName}get tick(){return this.currentStats?.tick??0}get timestamp(){return this.currentStats?.timestamp??0}get displayCount(){return this.currentStats?.displayCount??0}get totalDisplayArea(){return this.currentStats?.totalDisplayArea??0}get totalLayers(){return this.currentStats?.totalLayers??0}get visibleLayers(){return this.currentStats?.visibleLayers??0}get staticLayers(){return this.currentStats?.staticLayers??0}get dynamicLayers(){return this.currentStats?.dynamicLayers??0}get totalOrders(){return this.currentStats?.totalOrders??0}get ordersByLayer(){return this.currentStats?.ordersByLayer??new Map}get staticPacketSize(){return this.currentStats?.staticPacketSize??0}get dynamicPacketSize(){return this.currentStats?.dynamicPacketSize??0}get totalPacketSize(){return this.currentStats?.totalPacketSize??0}get compressedPacketSize(){return Math.round(this.totalPacketSize*.25)}get hasInput(){return this.currentStats?.hasInput??!1}get axisCount(){return this.currentStats?.axisCount??0}get buttonCount(){return this.currentStats?.buttonCount??0}startTick(e){this.enabled&&(this.currentStats={userId:this._userId,userName:this._userName,tick:e,timestamp:Date.now(),displayCount:0,totalDisplayArea:0,totalLayers:0,visibleLayers:0,staticLayers:0,dynamicLayers:0,totalOrders:0,ordersByLayer:new Map,staticPacketSize:0,dynamicPacketSize:0,totalPacketSize:0,hasInput:!1,axisCount:0,buttonCount:0})}recordDisplays(e,t){!this.enabled||!this.currentStats||(this.currentStats.displayCount=e,this.currentStats.totalDisplayArea=t)}recordLayers(e,t,r,n){!this.enabled||!this.currentStats||(this.currentStats.totalLayers=e,this.currentStats.visibleLayers=t,this.currentStats.staticLayers=r,this.currentStats.dynamicLayers=n)}recordLayerOrders(e,t){!this.enabled||!this.currentStats||(this.currentStats.totalOrders+=t,this.currentStats.ordersByLayer.set(e,t))}recordPacketSizes(e,t){!this.enabled||!this.currentStats||(this.currentStats.staticPacketSize=e,this.currentStats.dynamicPacketSize=t,this.currentStats.totalPacketSize=e+t)}recordInput(e,t,r){!this.enabled||!this.currentStats||(this.currentStats.hasInput=e,this.currentStats.axisCount=t,this.currentStats.buttonCount=r)}endTick(){}reset(){this.currentStats=null}};y(Pt,"UserStats");var pe=Pt;var _t=class _t{constructor(e,t,r){this.id=e;this.name=t;b(this,"displays",[]);b(this,"layers",[]);b(this,"spriteRegistry");b(this,"mode");b(this,"axes",new Map);b(this,"buttons",new Map);b(this,"textInputs",[]);b(this,"mouseX",0);b(this,"mouseY",0);b(this,"mouseOver",!1);b(this,"mouseDisplayId",0);b(this,"touchPositions",new Map);b(this,"activeTouchId",null);b(this,"inputBindings",new ue);b(this,"stats");b(this,"soundCommands",[]);b(this,"nextSoundInstanceId",1);b(this,"audioConfigCommands",[]);b(this,"lastListenerX",-1);b(this,"lastListenerY",-1);b(this,"pendingSendSounds",!1);b(this,"audioProcessor");b(this,"loadedSounds",new Map);b(this,"soundLoadErrors",new Map);b(this,"playingSounds",new Map);b(this,"mobileVibrationCommands",[]);b(this,"mobileVibrationProcessor");b(this,"gamepadVibrationCommands",[]);b(this,"gamepadVibrationProcessor");b(this,"macroRegistry",new se);b(this,"macroEngine",new le);b(this,"macroEventHandlers",new Map);b(this,"postProcessCommands",[]);b(this,"currentPostProcessConfig",null);b(this,"bridgeMessages",[]);b(this,"totalBytesSent",0);b(this,"totalBytesReceived",0);b(this,"bytesSentPerTick",[]);b(this,"bytesReceivedPerTick",[]);b(this,"bytesTickIndex",0);b(this,"bytesTickRate",20);b(this,"currentTickBytesSent",0);b(this,"currentTickBytesReceived",0);b(this,"availableViewports",new Map);b(this,"data");b(this,"currentScalingModes",new Map);b(this,"currentCellSizes",new Map);b(this,"currentGridConfigs",new Map);b(this,"currentPaletteSlotIds",new Map);this.mode=r,this.stats=new pe(e,t),this.data={}}setSpriteRegistry(e){this.spriteRegistry=e;for(let t of this.layers)t.setSpriteRegistry(e);this.macroEngine.setSpriteRegistry(e)}getDisplays(){return this.displays}addDisplay(e){this.displays.push(e)}removeDisplay(e){let t=this.displays.indexOf(e);return t!==-1?(this.displays.splice(t,1),!0):!1}clearDisplays(){this.displays=[]}setDisplayViewport(e,t,r){this.availableViewports.set(e,{pixelWidth:t,pixelHeight:r})}getDisplayViewport(e){return this.availableViewports.get(e)??null}getAllDisplayViewports(){return this.availableViewports}calculateMaxCells(e,t,r){let n=this.availableViewports.get(e);return n?{cols:Math.floor(n.pixelWidth/t),rows:Math.floor(n.pixelHeight/r)}:null}getLayers(){return this.layers}getLayerById(e){return this.layers.find(t=>t.getId()===e)}addLayer(e,t){e.setMode(this.mode);let r=this.layers.length+1;e.setId(r),this.layers.push(e),this.spriteRegistry&&e.setSpriteRegistry(this.spriteRegistry),t&&this.macroRegistry.setLayerMapping(t,e.getId())}removeLayer(e){let t=this.layers.indexOf(e);return t!==-1?(this.layers.splice(t,1),!0):!1}clearLayers(){this.layers=[]}setMousePosition(e,t,r=!0){this.mouseX=Math.max(0,Math.min(255,e)),this.mouseY=Math.max(0,Math.min(255,t)),this.mouseOver=r}setTouchPosition(e,t,r,n=!0,o=0){if(e<0||e>9){console.warn(`Invalid touchId ${e}, must be 0-9`);return}n?(this.touchPositions.set(e,{x:Math.max(0,Math.min(255,t)),y:Math.max(0,Math.min(255,r)),over:!0,displayId:o}),this.activeTouchId=e):(this.touchPositions.delete(e),this.activeTouchId===e&&(this.activeTouchId=null))}setAxis(e,t){let r=Math.max(-1,Math.min(1,t));this.axes.set(e,r)}getAxis(e){return this.axes.get(e)??0}setButton(e,t){this.buttons.set(e,t)}getButton(e){return this.buttons.get(e)??!1}getButtonJustPressed(e){let t=`${e}_justPressed`;return this.buttons.get(t)??!1}getButtonJustReleased(e){let t=`${e}_justReleased`;return this.buttons.get(t)??!1}setTextInputs(e){this.textInputs=e}getTextInputs(){return this.textInputs}clearTextInputs(){this.textInputs=[]}getAxisNames(){return Array.from(this.axes.keys())}getButtonNames(){return Array.from(this.buttons.keys())}clearAxes(){this.axes.clear()}clearButtons(){this.buttons.clear()}getMouseDisplayInfo(){if(!this.mouseOver||this.displays.length===0)return null;let e=this.displays[0],t=0,r=this.mouseX,n=this.mouseY,o=e.getOrigin(),i=o.x+r,a=o.y+n;return{displayId:t,localX:r,localY:n,worldX:i,worldY:a}}getTouchDisplayInfo(e=0){if(e<0||e>9)return console.warn(`Invalid touchId ${e}, must be 0-9`),null;let t=this.touchPositions.get(e);if(!t||!t.over||this.displays.length===0)return null;let r=this.displays[0],n=t.displayId,o=t.x,i=t.y,a=r.getOrigin(),s=a.x+o,d=a.y+i;return{displayId:n,localX:o,localY:i,worldX:s,worldY:d}}getIsMouseOnADisplay(){return this.mouseOver}getMouseDisplayHover(){let e=this.getMouseDisplayInfo();return e?e.displayId:null}findLayerById(e){return this.layers.find(t=>t.getId()===e)??null}applyUpdate(e){if(this.updateDisplaysFromPacket(e.displays),this.updateLayersFromPacket(e.layers),e.macroOrders&&e.macroOrders.length>0)for(let t of e.macroOrders)this.macroEngine.applyOrder(t)}updateDisplaysFromPacket(e){for(let t of e){let r=this.displays[t.id];if(!r){for(r=new ne(t.id,t.sizeX,t.sizeY);this.displays.length<=t.id;)this.displays.push(null);this.displays[t.id]=r}r.setOrigin(new De(t.originX,t.originY)),r.setSize(new De(t.sizeX,t.sizeY))}}updateLayersFromPacket(e){for(let t of e){let r=this.findLayerById(t.id);r||(r=new ae(new De(t.originX,t.originY),t.zIndex,t.width,t.height,{isStatic:!1,charCodeMode:t.is16bit?"16bit":"8bit"}),r.setId(t.id),r.setMode(this.mode),this.spriteRegistry&&r.setSpriteRegistry(this.spriteRegistry),this.addLayer(r)),t.updateFlags&1&&r.setOrigin(new De(t.originX,t.originY)),t.updateFlags&2&&r.setZOrder(t.zIndex),t.updateFlags&4&&r.setOrders(t.orders)}}defineAxisBinding(e,t,r=[],n=-1,o=1,i=0){this.inputBindings.defineAxis(e,t,r,n,o,i)}defineButtonBinding(e,t,r=[],n=!1){this.inputBindings.defineButton(e,t,r,n)}defineAxisBindings(e){e.forEach(({bindingId:t,name:r,sources:n,min:o,max:i,defaultValue:a})=>{this.defineAxisBinding(t,r,n??[],o,i,a)})}defineButtonBindings(e){e.forEach(({bindingId:t,name:r,sources:n,defaultValue:o})=>{this.defineButtonBinding(t,r,n??[],o)})}getInputBindingsLoadPacket(){return this.inputBindings.toLoadPacket()}applyInputBindingsLoadPacket(e){try{let t=JSON.parse(e);if(t.type!=="input-binding")throw new Error(`Invalid packet type: ${t.type}`);for(let r of t.axes)this.defineAxisBinding(r.bindingId,r.name,r.sources||[],r.min,r.max,r.defaultValue);for(let r of t.buttons)this.defineButtonBinding(r.bindingId,r.name,r.sources||[],r.defaultValue)}catch(t){throw console.error("[User] Failed to apply input bindings:",t),t}}getInputBindingRegistry(){return this.inputBindings}getStats(){return this.stats}getTotalBytesSent(){return this.totalBytesSent}getTotalBytesReceived(){return this.totalBytesReceived}recordBytesSent(e){this.totalBytesSent+=e,this.currentTickBytesSent+=e}recordBytesReceived(e){this.totalBytesReceived+=e,this.currentTickBytesReceived+=e}resetByteCounters(){this.totalBytesSent=0,this.totalBytesReceived=0}setBytesTickRate(e){e<=0||(this.bytesTickRate=e,this.bytesSentPerTick=new Array(e).fill(0),this.bytesReceivedPerTick=new Array(e).fill(0),this.bytesTickIndex=0)}endTickBytes(){this.bytesSentPerTick.length!==this.bytesTickRate&&(this.bytesSentPerTick=new Array(this.bytesTickRate).fill(0),this.bytesReceivedPerTick=new Array(this.bytesTickRate).fill(0)),this.bytesSentPerTick[this.bytesTickIndex]=this.currentTickBytesSent,this.bytesReceivedPerTick[this.bytesTickIndex]=this.currentTickBytesReceived,this.bytesTickIndex=(this.bytesTickIndex+1)%this.bytesTickRate,this.currentTickBytesSent=0,this.currentTickBytesReceived=0}getBytesSentPerSecond(){return this.bytesSentPerTick.reduce((e,t)=>e+t,0)}getBytesReceivedPerSecond(){return this.bytesReceivedPerTick.reduce((e,t)=>e+t,0)}getAxisBindingId(e){return this.inputBindings.getAxisBindingId(e)}getButtonBindingId(e){return this.inputBindings.getButtonBindingId(e)}decodeAndApplyCompressedInput(e){let t=Et(e,this.inputBindings),r=this.inputBindings.getAllAxes(),n=this.inputBindings.getAllButtons(),o=r.sort((a,s)=>a.bindingId-s.bindingId),i=n.sort((a,s)=>a.bindingId-s.bindingId);for(let[a,s]of t.axes)if(a<o.length){let d=o[a];this.setAxis(d.name,s)}for(let[a,s]of t.buttons)if(a<i.length){let d=i[a];this.setButton(d.name,s)}this.mouseX=t.mouseX,this.mouseY=t.mouseY,this.mouseOver=t.mouseOverDisplay,this.mouseDisplayId=t.displayId;for(let a of t.displayViewports)this.setDisplayViewport(a.displayId,a.pixelWidth,a.pixelHeight)}playSound(e,t){let r=this.nextSoundInstanceId++,n={sound:e,instanceId:r,volume:t?.volume,pitch:t?.pitch,loop:t?.loop,fadeIn:t?.fadeIn,x:t?.x,y:t?.y,lowpass:t?.lowpass,highpass:t?.highpass,reverb:t?.reverb};return this.soundCommands.push(n),r}stopSound(e){let t={sound:e};this.soundCommands.push(t)}fadeOutSound(e,t){let r={fadeOut:!0,sound:e,duration:t};this.soundCommands.push(r)}fadeOutAllSounds(e){let t={fadeOut:!0,sound:"all",duration:e};this.soundCommands.push(t)}stopAllSounds(){let e={sound:"all"};this.soundCommands.push(e)}pauseSound(e){let t={pause:!0,sound:e};this.soundCommands.push(t)}pauseAllSounds(){let e={pause:!0,sound:"all"};this.soundCommands.push(e)}resumeSound(e){let t={resume:!0,sound:e};this.soundCommands.push(t)}resumeAllSounds(){let e={resume:!0,sound:"all"};this.soundCommands.push(e)}setSoundEffects(e,t){let r={setEffects:!0,instanceId:e,lowpass:t.lowpass,highpass:t.highpass,reverb:t.reverb};this.soundCommands.push(r)}setListenerPosition(e,t){e===this.lastListenerX&&t===this.lastListenerY||(this.lastListenerX=e,this.lastListenerY=t,this.audioConfigCommands.push({type:"set-listener-position",x:e,y:t}))}configureSpatialAudio(e){this.audioConfigCommands.push({type:"configure-spatial",...e})}flushAudioConfigCommands(){let e=this.audioConfigCommands;return this.audioConfigCommands=[],e}hasAudioConfigCommands(){return this.audioConfigCommands.length>0}flushSoundCommands(){let e=this.soundCommands;return this.soundCommands=[],e}hasSoundCommands(){return this.soundCommands.length>0}sendSounds(){this.pendingSendSounds=!0}needsSendSounds(){return this.pendingSendSounds}clearSendSounds(){this.pendingSendSounds=!1}setAudioProcessor(e){this.audioProcessor=e,this.macroEngine.setAudioCallback(t=>{e.play(t)})}getAudioProcessor(){return this.audioProcessor}applyAudioCommands(e){if(this.audioProcessor&&this.mode!=="server")for(let t of e){if("setEffects"in t&&t.setEffects===!0){let n=t;this.audioProcessor.setEffects(n.instanceId,n.lowpass,n.highpass,n.reverb);continue}if("fadeOut"in t&&t.fadeOut===!0){let n=t;this.audioProcessor.fadeOut(n.sound,n.duration);continue}if("pause"in t&&t.pause===!0){let n=t;this.audioProcessor.pause(n.sound);continue}if("resume"in t&&t.resume===!0){let n=t;this.audioProcessor.resume(n.sound);continue}if("instanceId"in t||"volume"in t||"pitch"in t||"loop"in t||"fadeIn"in t||"x"in t||"y"in t||"lowpass"in t||"highpass"in t||"reverb"in t){let n=t,o=n.x!==void 0&&n.y!==void 0?{x:n.x,y:n.y}:void 0;this.audioProcessor.play(n.sound,{volume:n.volume,pitch:n.pitch,loop:n.loop,fadeIn:n.fadeIn,position:o,instanceId:n.instanceId,lowpass:n.lowpass,highpass:n.highpass,reverb:n.reverb})}else{let n=t;n.sound==="all"?this.audioProcessor.stopAll():this.audioProcessor.stop(n.sound)}}}applyAudioConfigCommands(e){if(this.audioProcessor&&this.mode!=="server")for(let t of e)t.type==="set-listener-position"?this.audioProcessor.setListenerPosition(t.x,t.y):t.type==="configure-spatial"&&this.audioProcessor.configureSpatial({maxDistance:t.maxDistance,referenceDistance:t.referenceDistance,rolloffFactor:t.rolloffFactor,panSpread:t.panSpread})}vibrate(e){let t={pattern:e};this.mobileVibrationCommands.push(t)}cancelVibration(){let e={cancel:!0};this.mobileVibrationCommands.push(e)}vibrateTap(){this.vibrate(10)}vibrateMediumTap(){this.vibrate(25)}vibrateHeavyTap(){this.vibrate(50)}vibrateSuccess(){this.vibrate([30,50,30])}vibrateError(){this.vibrate([50,30,50,30,50])}vibrateWarning(){this.vibrate([100])}vibrateSelection(){this.vibrate(5)}vibrateImpact(e="medium"){let t={light:15,medium:30,heavy:50};this.vibrate(t[e])}vibrateNotification(){this.vibrate([100,100,100,100,100])}vibrateGamepad(e,t){let r={gamepadIndex:e,options:t};this.gamepadVibrationCommands.push(r)}stopGamepadVibration(e="all"){let t={gamepadIndex:e,cancel:!0};this.gamepadVibrationCommands.push(t)}gamepadTap(e=0){this.vibrateGamepad(e,{duration:50,strongMagnitude:.3,weakMagnitude:.5})}gamepadImpact(e=0){this.vibrateGamepad(e,{duration:100,strongMagnitude:.7,weakMagnitude:.3})}gamepadHeavy(e=0){this.vibrateGamepad(e,{duration:200,strongMagnitude:1,weakMagnitude:.2})}gamepadExplosion(e=0){this.vibrateGamepad(e,{duration:400,strongMagnitude:1,weakMagnitude:.8})}gamepadSuccess(e=0){this.vibrateGamepad(e,{duration:150,strongMagnitude:.4,weakMagnitude:.6})}gamepadError(e=0){this.vibrateGamepad(e,{duration:300,strongMagnitude:.8,weakMagnitude:.4})}hasGamepadVibrationCommands(){return this.gamepadVibrationCommands.length>0}flushGamepadVibrationCommands(){let e=this.gamepadVibrationCommands;return this.gamepadVibrationCommands=[],e}setGamepadVibrationProcessor(e){this.gamepadVibrationProcessor=e}applyGamepadVibrationCommands(e){if(this.gamepadVibrationProcessor&&this.mode!=="server"){for(let t of e)if("cancel"in t&&t.cancel===!0)t.gamepadIndex==="all"?this.gamepadVibrationProcessor.stopAllVibrations():this.gamepadVibrationProcessor.stopVibration(t.gamepadIndex);else if("options"in t){let r=t;if(r.gamepadIndex==="all")for(let n=0;n<4;n++)this.gamepadVibrationProcessor.vibrate(n,r.options);else this.gamepadVibrationProcessor.vibrate(r.gamepadIndex,r.options)}}}hasMobileVibrationCommands(){return this.mobileVibrationCommands.length>0}flushMobileVibrationCommands(){let e=this.mobileVibrationCommands;return this.mobileVibrationCommands=[],e}setMobileVibrationProcessor(e){this.mobileVibrationProcessor=e}getMobileVibrationProcessor(){return this.mobileVibrationProcessor}applyMobileVibrationCommands(e){if(this.mobileVibrationProcessor&&this.mode!=="server")for(let t of e)"cancel"in t&&t.cancel===!0?this.mobileVibrationProcessor.cancel():"pattern"in t&&this.mobileVibrationProcessor.vibrate(t.pattern)}applyVibrationOrders(e){if(this.mode==="server")return;let{VibrationOrderType:t}=(Rt(),re(yn)),{MobileVibrateFlags:r,GamepadVibrateFlags:n}=(Tt(),re(Cn));for(let o of e)switch(o.type){case t.MobileVibrate:{if(!this.mobileVibrationProcessor)break;let i=o,a=i.pattern;i.flags&r.HasIntensity&&i.intensity!==void 0&&(a=a.map(s=>Math.round(s*i.intensity))),this.mobileVibrationProcessor.vibrate(a);break}case t.MobileCancel:{if(!this.mobileVibrationProcessor)break;this.mobileVibrationProcessor.cancel();break}case t.GamepadVibrate:{if(!this.gamepadVibrationProcessor)break;let i=o,a={duration:i.duration,strongMagnitude:i.strongMagnitude/255,weakMagnitude:i.weakMagnitude/255,startDelay:i.startDelay};if(i.flags&n.AllGamepads)for(let s=0;s<4;s++)this.gamepadVibrationProcessor.vibrate(s,a);else this.gamepadVibrationProcessor.vibrate(i.gamepadIndex,a);break}case t.GamepadCancel:{if(!this.gamepadVibrationProcessor)break;let i=o;i.flags&n.AllGamepads?this.gamepadVibrationProcessor.stopAllVibrations():this.gamepadVibrationProcessor.stopVibration(i.gamepadIndex);break}}}applyAudioOrders(e){if(!this.audioProcessor||this.mode==="server")return;let{AudioOrderType:t,AudioTargetType:r}=(Dt(),re(Sn)),{PlaySoundFlags:n}=(Ht(),re(On));for(let o of e)switch(o.type){case t.PlaySound:case t.PlayGlobalSound:{let i=o,a=i.volume!==void 0?i.volume/255:void 0,s=i.pitch!==void 0?.25*Math.pow(2,i.pitch/64):void 0,d=i.fadeIn!==void 0?i.fadeIn/10:void 0,c=(i.flags&n.Loop)!==0,l=i.posX!==void 0&&i.posY!==void 0?{x:i.posX,y:i.posY}:void 0;this.audioProcessor.play(i.soundId,{volume:a,pitch:s,loop:c,fadeIn:d,position:l,instanceId:i.instanceId,lowpass:i.lowpass,highpass:i.highpass,reverb:i.reverb});break}case t.StopSound:{let i=o;i.targetType===r.All?this.audioProcessor.stopAll():i.targetType===r.InstanceId?this.audioProcessor.stop(i.target):this.audioProcessor.stop(i.target);break}case t.FadeOutSound:{let i=o,a=i.duration/10;i.targetType===r.All?this.audioProcessor.fadeOut("all",a):this.audioProcessor.fadeOut(i.target,a);break}case t.PauseSound:{let i=o;i.targetType===r.All?this.audioProcessor.pause("all"):this.audioProcessor.pause(i.target);break}case t.ResumeSound:{let i=o;i.targetType===r.All?this.audioProcessor.resume("all"):this.audioProcessor.resume(i.target);break}case t.SetListenerPosition:{let i=o;this.audioProcessor.setListenerPosition(i.x,i.y);break}case t.ConfigureSpatial:{let i=o;this.audioProcessor.configureSpatial({maxDistance:i.maxDistance*100,referenceDistance:i.referenceDistance*100,rolloffFactor:i.rolloffFactor/100,panSpread:i.panSpread/255});break}case t.SetSoundEffects:{let i=o;this.audioProcessor.setEffects(i.instanceId,i.lowpass,i.highpass,i.reverb);break}}}handleAudioAck(e){switch(e.type){case"sound-loaded":this.loadedSounds.set(e.soundId,{name:e.name,loadedAt:Date.now()}),this.soundLoadErrors.delete(e.soundId);break;case"sound-error":this.soundLoadErrors.set(e.soundId,{name:e.name,error:e.error,at:Date.now()});break;case"playback-started":this.playingSounds.set(e.instanceId,{soundId:e.soundId,startedAt:Date.now()});break;case"playback-ended":this.playingSounds.delete(e.instanceId);break;case"playback-error":e.instanceId!==void 0&&this.playingSounds.delete(e.instanceId);break}}isSoundLoaded(e){return this.loadedSounds.has(e)}getSoundLoadError(e){return this.soundLoadErrors.get(e)?.error}getLoadedSounds(){return this.loadedSounds}getSoundLoadErrors(){return this.soundLoadErrors}isSoundPlaying(e){return this.playingSounds.has(e)}getPlayingSounds(){return this.playingSounds}getPlayingSoundCount(){return this.playingSounds.size}loadMacro(e,t){let r={...t,id:e},n=this.macroRegistry.registerMacro(r);return this.mode==="client"&&this.macroEngine.loadTemplate(n,r),n}createInstance(e){return this.updateLayerMappings(),this.macroRegistry.createInstance(e)}updateInstance(e,t){return this.macroRegistry.updateInstance(e,t)}removeInstance(e){return this.macroEventHandlers.delete(e),this.macroRegistry.removeInstance(e)}onMacroEvent(e,t,r){this.macroEventHandlers.has(e)||this.macroEventHandlers.set(e,new Map),this.macroEventHandlers.get(e).set(t,r)}offMacroEvent(e,t){t?this.macroEventHandlers.get(e)?.delete(t):this.macroEventHandlers.delete(e)}handleMacroEvent(e){let t=this.macroRegistry.getInstanceName(e.instanceId);if(!t){console.warn(`MacroEvent: Unknown instance ID ${e.instanceId}`);return}let r=this.macroEventHandlers.get(t);if(!r)return;let n,o;switch(e.type){case 1:n="click",o=void 0;break;case 2:n="change",o=e.value;break;case 3:n="submit",o=e.text;break;case 4:n="select",o=e.index;break;default:return}let i=r.get(n);i&&i(o)}flushMacroOrders(){return this.macroRegistry.flushPendingOrders()}hasPendingMacroOrders(){return this.macroRegistry.hasPendingOrders()}applyMacroOrders(e){for(let t of e)this.macroEngine.applyOrder(t)}getMacroRegistry(){return this.macroRegistry}getMacroLoads(){return this.macroRegistry.toAllMacroLoads()}updateLayerMappings(){for(let e of this.layers){let t=e.getId()}}registerLayerName(e,t){this.macroRegistry.setLayerMapping(e,t.getId())}loadMacroTemplate(e,t){this.macroEngine.loadTemplate(e,t)}updateMacros(){return this.macroEngine.update()}processMacroEvents(e){for(let t of e.events){let r=this.macroRegistry.getInstanceName(t.instanceId);if(!r)continue;let n=this.macroEventHandlers.get(r);if(!n)continue;let o=n.get(t.event);o&&o(t.data)}}updateMacroMouse(e,t,r){let n=this.displays.find(o=>o.getId()===this.mouseDisplayId);if(!n&&this.displays.length>0&&(n=this.displays[0]),n){let o=n.getOrigin(),i=e+o.x,a=t+o.y;this.macroEngine.updateMouse(i,a,r)}else this.macroEngine.updateMouse(e,t,r)}getMacroRenderOrders(){let e=this.macroEngine.getOrdersByLayer(),t=this.displays[0];if(!t)return e;let r=t.getOrigin();if(r.x===0&&r.y===0)return e;let n=new Map;for(let[o,i]of e){let a=i.map(s=>{let d={...s};return"posX"in d&&typeof d.posX=="number"&&(d.posX=d.posX-r.x),"posY"in d&&typeof d.posY=="number"&&(d.posY=d.posY-r.y),d});n.set(o,a)}return n}getMacroEffectOffset(){return this.macroEngine.getEffectOffset()}getMacroEngine(){return this.macroEngine}macroFocusNext(){this.macroEngine.focusNext()}macroFocusPrevious(){this.macroEngine.focusPrevious()}macroActivateFocused(){this.macroEngine.activateFocused()}setPostProcess(e,t){let r=JSON.stringify(t),n=JSON.stringify(this.currentPostProcessConfig);r!==n&&(this.currentPostProcessConfig=t,this.postProcessCommands.push({type:"set-config",displayId:e,config:t??void 0}))}setScanlinesEnabled(e,t){if(t){let r=this.currentPostProcessConfig?.scanlines;this.setPostProcess(e,{scanlines:{enabled:!0,opacity:r?.opacity??D.scanlines.opacity,pattern:r?.pattern??D.scanlines.pattern,color:r?.color??D.scanlines.color}})}else this.setPostProcess(e,{scanlines:{enabled:!1}})}setScanlinesOpacity(e,t){let r=Math.max(0,Math.min(1,t)),n=this.currentPostProcessConfig?.scanlines;this.setPostProcess(e,{scanlines:{enabled:!0,opacity:r,pattern:n?.pattern??"horizontal",color:n?.color??{r:0,g:0,b:0}}})}setScanlinesPattern(e,t){let r=this.currentPostProcessConfig?.scanlines;this.setPostProcess(e,{scanlines:{enabled:r?.enabled??!0,opacity:r?.opacity??D.scanlines.opacity,pattern:t,color:r?.color??{r:0,g:0,b:0}}})}setAmbientEffect(e,t){let r=this.currentPostProcessConfig?.ambientEffect;typeof t=="boolean"?this.setPostProcess(e,{...this.currentPostProcessConfig,ambientEffect:{enabled:t,blur:r?.blur??D.ambientEffect.blur,scale:r?.scale??D.ambientEffect.scale}}):this.setPostProcess(e,{...this.currentPostProcessConfig,ambientEffect:{enabled:!0,blur:t.blur??r?.blur??D.ambientEffect.blur,scale:t.scale??r?.scale??D.ambientEffect.scale}})}setAmbientEffectEnabled(e,t){this.setAmbientEffect(e,t)}setAmbientEffectBlur(e,t){let r=this.currentPostProcessConfig?.ambientEffect;this.setPostProcess(e,{...this.currentPostProcessConfig,ambientEffect:{enabled:r?.enabled??!0,blur:Math.max(0,t),scale:r?.scale??D.ambientEffect.scale}})}setAmbientEffectScale(e,t){let r=this.currentPostProcessConfig?.ambientEffect;this.setPostProcess(e,{...this.currentPostProcessConfig,ambientEffect:{enabled:r?.enabled??!0,blur:r?.blur??D.ambientEffect.blur,scale:Math.max(1,t)}})}isAmbientEffectEnabled(){return this.currentPostProcessConfig?.ambientEffect?.enabled??!1}getAmbientEffectConfig(){let e=this.currentPostProcessConfig?.ambientEffect;return e?{enabled:e.enabled,blur:e.blur??D.ambientEffect.blur,scale:e.scale??D.ambientEffect.scale}:null}getPostProcessConfig(){return this.currentPostProcessConfig}hasPostProcessCommands(){return this.postProcessCommands.length>0}flushPostProcessCommands(){let e=this.postProcessCommands;return this.postProcessCommands=[],e}setScalingMode(e,t){this.currentScalingModes.get(e)!==t&&(this.currentScalingModes.set(e,t),this.postProcessCommands.push({type:"set-scaling-mode",displayId:e,scalingMode:t}))}getScalingMode(e){return this.currentScalingModes.get(e)??null}setCellSize(e,t,r){let n=Math.max(1,Math.min(255,Math.round(t))),o=Math.max(1,Math.min(255,Math.round(r))),i=this.currentCellSizes.get(e);i&&i.width===n&&i.height===o||(this.currentCellSizes.set(e,{width:n,height:o}),this.postProcessCommands.push({type:"set-cell-size",displayId:e,cellWidth:n,cellHeight:o}))}getCellSize(e){let t=this.currentCellSizes.get(e);return{cellWidth:t?.width??8,cellHeight:t?.height??8}}setGrid(e,t){let r;typeof t=="boolean"?r={enabled:t,color:Ve.color,lineWidth:Ve.lineWidth}:r={enabled:t.enabled,color:t.color??Ve.color,lineWidth:t.lineWidth??Ve.lineWidth},this.currentGridConfigs.set(e,r),this.postProcessCommands.push({type:"set-grid",displayId:e,gridConfig:r})}setGridEnabled(e,t){this.setGrid(e,t)}isGridEnabled(e){return this.currentGridConfigs.get(e)?.enabled??!1}getGridConfig(e){return this.currentGridConfigs.get(e)??null}switchPalette(e,t){if(t<0||t>255)throw new Error(`Palette slot ID must be between 0 and 255, got ${t}`);this.currentPaletteSlotIds.get(e)!==t&&(this.currentPaletteSlotIds.set(e,t),this.postProcessCommands.push({type:"switch-palette",displayId:e,paletteSlotId:t}))}getCurrentPaletteSlotId(e){return this.currentPaletteSlotIds.get(e)??null}sendBridge(e,t){this.bridgeMessages.push({channel:e,data:t})}getBridgeMessages(){let e=this.bridgeMessages;return this.bridgeMessages=[],e}hasBridgeMessages(){return this.bridgeMessages.length>0}};y(_t,"User");var me=_t;W();W();L();var Nt=class Nt{constructor(){b(this,"charCodeSize",ke)}encode(e,t=!1){switch(e.type){case 1:return this.encodeCharOrder(e,t);case 2:return this.encodeTextOrder(e);case 23:return this.encodeTextMultilineOrder(e);case 3:return this.encodeSubFrameOrder(e,t);case 4:return this.encodeSubFrameMultiColorOrder(e,t);case 5:return this.encodeFullFrameOrder(e,t);case 6:return this.encodeFullFrameMultiColorOrder(e,t);case 7:return this.encodeSpriteOrder(e);case 8:return this.encodeSpriteMultiColorOrder(e);case 9:return this.encodeColorMapOrder(e);case 10:return this.encodeShapeOrder(e,t);case 11:return this.encodeDotCloudOrder(e,t);case 12:return this.encodeDotCloudMultiColorOrder(e,t);case 17:return this.encodeBitmaskOrder(e,t);case 18:return this.encodeBitmask4Order(e,t);case 24:return this.encodeBitmask16Order(e,t);case 25:return this.encodePolylineOrder(e,t);case 13:return this.encodeSpriteCloudOrder(e);case 14:return this.encodeSpriteCloudMultiColorOrder(e);case 15:return this.encodeSpriteCloudVariedOrder(e);case 16:return this.encodeSpriteCloudVariedMultiColorOrder(e);case 19:return this.encodeClearOrder(e,t);case 20:return this.encodeFillCharOrder(e,t);case 21:return this.encodeFillSpriteOrder(e);case 22:return this.encodeFillSpriteMultiColorOrder(e);default:throw new Error(`Unknown order type: ${e.type}`)}}writeCharCode(e,t,r,n){return n?(e.writeUInt16LE(t,r),r+2):(e.writeUInt8(t,r),r+1)}encodeCharOrder(e,t){let r=f.allocUnsafe(Er+(t?1:0)),n=0;return r.writeUInt8(e.type,n++),r.writeUInt8(e.posX,n++),r.writeUInt8(e.posY,n++),n=this.writeCharCode(r,e.charCode,n,t),r.writeUInt8(e.bgColorCode,n++),r.writeUInt8(e.fgColorCode,n++),r.toUint8Array()}encodeTextOrder(e){let t=new TextEncoder().encode(e.text),r=f.allocUnsafe(Pr+t.length),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.posX,n++),r.writeUInt8(e.posY,n++),r.writeUInt8(t.length,n++);for(let o=0;o<t.length;o++)r.writeUInt8(t[o],n++);return r.writeUInt8(e.bgColorCode,n++),r.writeUInt8(e.fgColorCode,n++),r.toUint8Array()}encodeTextMultilineOrder(e){let t=new TextEncoder().encode(e.text),r=f.allocUnsafe(kr+t.length),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.posX,n++),r.writeUInt8(e.posY,n++),r.writeUInt8(t.length,n++);for(let o=0;o<t.length;o++)r.writeUInt8(t[o],n++);return r.writeUInt8(e.bgColorCode,n++),r.writeUInt8(e.fgColorCode,n++),r.toUint8Array()}encodeSubFrameOrder(e,t){let r=e.sizeX*e.sizeY,n=this.charCodeSize(t),o=f.allocUnsafe(Rr+r*n),i=0;o.writeUInt8(e.type,i++),o.writeUInt8(e.posX,i++),o.writeUInt8(e.posY,i++),o.writeUInt8(e.sizeX-1,i++),o.writeUInt8(e.sizeY-1,i++),o.writeUInt8(e.bgColorCode,i++),o.writeUInt8(e.fgColorCode,i++);for(let a of e.frame)i=this.writeCharCode(o,a,i,t);return o.toUint8Array()}encodeSubFrameMultiColorOrder(e,t){let r=e.sizeX*e.sizeY,n=this.charCodeSize(t),o=f.allocUnsafe(Br+r*(n+2)),i=0;o.writeUInt8(e.type,i++),o.writeUInt8(e.posX,i++),o.writeUInt8(e.posY,i++),o.writeUInt8(e.sizeX-1,i++),o.writeUInt8(e.sizeY-1,i++);for(let a of e.frame)i=this.writeCharCode(o,a.charCode,i,t),o.writeUInt8(a.bgColorCode,i++),o.writeUInt8(a.fgColorCode,i++);return o.toUint8Array()}encodeFullFrameOrder(e,t){let r=e.frame.length,n=this.charCodeSize(t),o=f.allocUnsafe(zr+r*n),i=0;o.writeUInt8(e.type,i++),o.writeUInt8(e.bgColorCode,i++),o.writeUInt8(e.fgColorCode,i++);for(let a of e.frame)i=this.writeCharCode(o,a,i,t);return o.toUint8Array()}encodeFullFrameMultiColorOrder(e,t){let r=e.frame.length,n=this.charCodeSize(t),o=f.allocUnsafe(Tr+r*(n+2)),i=0;o.writeUInt8(e.type,i++);for(let a of e.frame)i=this.writeCharCode(o,a.charCode,i,t),o.writeUInt8(a.bgColorCode,i++),o.writeUInt8(a.fgColorCode,i++);return o.toUint8Array()}encodeSpriteOrder(e){let t=f.allocUnsafe(Fr),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.posX,r++),t.writeUInt8(e.posY,r++),t.writeUInt8(e.spriteIndex,r++),t.writeUInt8(e.bgColorCode,r++),t.writeUInt8(e.fgColorCode,r++),t.toUint8Array()}encodeSpriteMultiColorOrder(e){let t=f.allocUnsafe(Lr),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.posX,r++),t.writeUInt8(e.posY,r++),t.writeUInt8(e.spriteIndex,r++),t.toUint8Array()}encodeColorMapOrder(e){let t=e.sizeX*e.sizeY,r=f.allocUnsafe(Dr+t*2),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.posX,n++),r.writeUInt8(e.posY,n++),r.writeUInt8(e.sizeX-1,n++),r.writeUInt8(e.sizeY-1,n++);for(let o of e.colorData)r.writeUInt8(o.bgColorCode,n++),r.writeUInt8(o.fgColorCode,n++);return r.toUint8Array()}encodeShapeOrder(e,t){let r=this.encodeShapeData(e.shapeType,e.shapeData,t),n=f.allocUnsafe(Vr+r.length),o=0;n.writeUInt8(e.type,o++),n.writeUInt8(e.shapeType,o++);for(let i=0;i<r.length;i++)n.writeUInt8(r[i],o++);return n.toUint8Array()}encodeShapeData(e,t,r){let n=this.charCodeSize(r);switch(e){case 1:{let o=f.allocUnsafe(Hr+(r?1:0)),i=0;return o.writeUInt8(t.posX,i++),o.writeUInt8(t.posY,i++),o.writeUInt8(t.width-1,i++),o.writeUInt8(t.height-1,i++),o.writeUInt8(t.filled?1:0,i++),i=this.writeCharCode(o,t.charCode,i,r),o.writeUInt8(t.bgColorCode,i++),o.writeUInt8(t.fgColorCode,i++),o.toUint8Array()}case 2:{let o=f.allocUnsafe(_r+(r?1:0)),i=0;return o.writeUInt8(t.centerX,i++),o.writeUInt8(t.centerY,i++),o.writeUInt8(t.radius-1,i++),o.writeUInt8(t.filled?1:0,i++),i=this.writeCharCode(o,t.charCode,i,r),o.writeUInt8(t.bgColorCode,i++),o.writeUInt8(t.fgColorCode,i++),o.toUint8Array()}case 3:{let o=f.allocUnsafe(Nr+(r?1:0)),i=0;return o.writeUInt8(t.x1,i++),o.writeUInt8(t.y1,i++),o.writeUInt8(t.x2,i++),o.writeUInt8(t.y2,i++),i=this.writeCharCode(o,t.charCode,i,r),o.writeUInt8(t.bgColorCode,i++),o.writeUInt8(t.fgColorCode,i++),o.toUint8Array()}case 4:{let o=f.allocUnsafe(Yr+(r?1:0)),i=0;return o.writeUInt8(t.centerX,i++),o.writeUInt8(t.centerY,i++),o.writeUInt8(t.radiusX-1,i++),o.writeUInt8(t.radiusY-1,i++),o.writeUInt8(t.filled?1:0,i++),i=this.writeCharCode(o,t.charCode,i,r),o.writeUInt8(t.bgColorCode,i++),o.writeUInt8(t.fgColorCode,i++),o.toUint8Array()}case 5:{let o=f.allocUnsafe(Xr+(r?1:0)),i=0;return o.writeUInt8(t.x1,i++),o.writeUInt8(t.y1,i++),o.writeUInt8(t.x2,i++),o.writeUInt8(t.y2,i++),o.writeUInt8(t.x3,i++),o.writeUInt8(t.y3,i++),o.writeUInt8(t.filled?1:0,i++),i=this.writeCharCode(o,t.charCode,i,r),o.writeUInt8(t.bgColorCode,i++),o.writeUInt8(t.fgColorCode,i++),o.toUint8Array()}default:throw new Error(`Unknown shape type: ${e}`)}}encodeDotCloudOrder(e,t){let r=e.positions.length,n=this.charCodeSize(t),o=f.allocUnsafe(Wr+(t?1:0)+r*2),i=0;o.writeUInt8(e.type,i++),i=this.writeCharCode(o,e.charCode,i,t),o.writeUInt8(e.bgColorCode,i++),o.writeUInt8(e.fgColorCode,i++),o.writeUInt16BE(r,i),i+=2;for(let a of e.positions)o.writeUInt8(a.posX,i++),o.writeUInt8(a.posY,i++);return o.toUint8Array()}encodeDotCloudMultiColorOrder(e,t){let r=e.dots.length,n=this.charCodeSize(t),o=f.allocUnsafe(Gr+2+r*(n+4)),i=0;o.writeUInt8(e.type,i++),o.writeUInt16BE(r,i),i+=2;for(let a of e.dots)i=this.writeCharCode(o,a.charCode,i,t),o.writeUInt8(a.bgColorCode,i++),o.writeUInt8(a.fgColorCode,i++),o.writeUInt8(a.posX,i++),o.writeUInt8(a.posY,i++);return o.toUint8Array()}encodeBitmaskOrder(e,t){let r=e.mask.length,n=f.allocUnsafe($r+(t?1:0)+r),o=0;n.writeUInt8(e.type,o++),n.writeUInt8(e.posX,o++),n.writeUInt8(e.posY,o++),n.writeUInt8(e.sizeX-1,o++),n.writeUInt8(e.sizeY-1,o++),o=this.writeCharCode(n,e.charCode,o,t),n.writeUInt8(e.bgColorCode,o++),n.writeUInt8(e.fgColorCode,o++),n.writeUInt8(e.override?1:0,o++);for(let i=0;i<r;i++)n.writeUInt8(e.mask[i],o++);return n.toUint8Array()}encodeBitmask4Order(e,t){let r=e.mask.length,n=this.charCodeSize(t),o=f.allocUnsafe(Zr+3*(t?1:0)+r),i=0;o.writeUInt8(e.type,i++),o.writeUInt8(e.posX,i++),o.writeUInt8(e.posY,i++),o.writeUInt8(e.sizeX-1,i++),o.writeUInt8(e.sizeY-1,i++),o.writeUInt8(e.override?1:0,i++);for(let a of e.variants)i=this.writeCharCode(o,a.charCode,i,t),o.writeUInt8(a.bgColorCode,i++),o.writeUInt8(a.fgColorCode,i++);for(let a=0;a<r;a++)o.writeUInt8(e.mask[a],i++);return o.toUint8Array()}encodeBitmask16Order(e,t){let r=e.mask.length,n=this.charCodeSize(t),o=f.allocUnsafe(jr+15*(t?1:0)+r),i=0;o.writeUInt8(e.type,i++),o.writeUInt8(e.posX,i++),o.writeUInt8(e.posY,i++),o.writeUInt8(e.sizeX-1,i++),o.writeUInt8(e.sizeY-1,i++),o.writeUInt8(e.override?1:0,i++);for(let a of e.variants)i=this.writeCharCode(o,a.charCode,i,t),o.writeUInt8(a.bgColorCode,i++),o.writeUInt8(a.fgColorCode,i++);for(let a=0;a<r;a++)o.writeUInt8(e.mask[a],i++);return o.toUint8Array()}encodePolylineOrder(e,t){let r=e.points.length,n=f.allocUnsafe(Jr+(t?1:0)+r*2),o=0;n.writeUInt8(e.type,o++),o=this.writeCharCode(n,e.charCode,o,t),n.writeUInt8(e.fgColorCode,o++),n.writeUInt8(e.bgColorCode,o++),n.writeUInt8(r,o++);for(let i of e.points)n.writeUInt8(i.x,o++),n.writeUInt8(i.y,o++);return n.toUint8Array()}encodeSpriteCloudOrder(e){let t=e.positions.length,r=f.allocUnsafe(qr+2+t*2),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.spriteIndex,n++),r.writeUInt8(e.bgColorCode,n++),r.writeUInt8(e.fgColorCode,n++),r.writeUInt16BE(t,n),n+=2;for(let o of e.positions)r.writeUInt8(o.posX,n++),r.writeUInt8(o.posY,n++);return r.toUint8Array()}encodeSpriteCloudMultiColorOrder(e){let t=e.positions.length,r=f.allocUnsafe(Kr+2+t*2),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.spriteIndex,n++),r.writeUInt16BE(t,n),n+=2;for(let o of e.positions)r.writeUInt8(o.posX,n++),r.writeUInt8(o.posY,n++);return r.toUint8Array()}encodeSpriteCloudVariedOrder(e){let t=e.sprites.length,r=f.allocUnsafe(Qr+t*5),n=0;r.writeUInt8(e.type,n++),r.writeUInt16BE(t,n),n+=2;for(let o of e.sprites)r.writeUInt8(o.spriteIndex,n++),r.writeUInt8(o.bgColorCode,n++),r.writeUInt8(o.fgColorCode,n++),r.writeUInt8(o.posX,n++),r.writeUInt8(o.posY,n++);return r.toUint8Array()}encodeSpriteCloudVariedMultiColorOrder(e){let t=e.sprites.length,r=f.allocUnsafe(en+t*3),n=0;r.writeUInt8(e.type,n++),r.writeUInt16BE(t,n),n+=2;for(let o of e.sprites)r.writeUInt8(o.spriteIndex,n++),r.writeUInt8(o.posX,n++),r.writeUInt8(o.posY,n++);return r.toUint8Array()}encodeClearOrder(e,t){let r=f.allocUnsafe(tn+(t?1:0)),n=0;return r.writeUInt8(e.type,n++),n=this.writeCharCode(r,e.charCode,n,t),r.writeUInt8(e.bgColorCode,n++),r.writeUInt8(e.fgColorCode,n++),r.toUint8Array()}encodeFillCharOrder(e,t){let r=e.patternWidth*e.patternHeight,n=this.charCodeSize(t),o=f.allocUnsafe(rn+r*n),i=0;o.writeUInt8(e.type,i++),o.writeUInt8(e.patternWidth-1,i++),o.writeUInt8(e.patternHeight-1,i++),o.writeUInt8(e.bgColorCode,i++),o.writeUInt8(e.fgColorCode,i++);for(let a of e.pattern)i=this.writeCharCode(o,a,i,t);return o.toUint8Array()}encodeFillSpriteOrder(e){let t=f.allocUnsafe(nn),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.spriteIndex,r++),t.writeUInt8(e.bgColorCode,r++),t.writeUInt8(e.fgColorCode,r++),t.toUint8Array()}encodeFillSpriteMultiColorOrder(e){let t=f.allocUnsafe(on),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.spriteIndex,r++),t.toUint8Array()}};y(Nt,"OrderEncoder");var He=Nt;L();var wn=64,Yt=class Yt{constructor(){b(this,"orderEncoder");this.orderEncoder=new He}encode(e){let t=e.is16bit,r=e.orders.map(c=>this.orderEncoder.encode(c,t)),n=13,o=r.reduce((c,l)=>c+l.length,0),i=n+o,a=f.allocUnsafe(i),s=0;a.writeUInt16BE(e.id,s),s+=2;let d=e.updateFlags;t?d|=wn:d&=~wn,a.writeUInt8(d,s++),a.writeUInt8(e.zIndex,s++),a.writeUInt16BE(e.originX,s),s+=2,a.writeUInt16BE(e.originY,s),s+=2,a.writeUInt16BE(e.width,s),s+=2,a.writeUInt16BE(e.height,s),s+=2,a.writeUInt8(e.orders.length,s++);for(let c of r)f.from(c).copy(a,s),s+=c.length;return a.toUint8Array()}calculateSize(e){let r=e.is16bit;return 13+e.orders.reduce((o,i)=>o+this.orderEncoder.encode(i,r).length,0)}};y(Yt,"LayerEncoder");var _e=Yt;L();W();var Xt=class Xt{encode(e){switch(e.type){case 1:return this.encodePlaySoundOrder(e);case 2:return this.encodePlayGlobalSoundOrder(e);case 3:return this.encodeStopSoundOrder(e);case 4:return this.encodeFadeOutSoundOrder(e);case 5:return this.encodePauseSoundOrder(e);case 6:return this.encodeResumeSoundOrder(e);case 7:return this.encodeSetListenerPositionOrder(e);case 8:return this.encodeConfigureSpatialOrder(e);case 9:return this.encodeSetSoundEffectsOrder(e);default:throw new Error(`Unknown audio order type: ${e.type}`)}}calculateSize(e){switch(e.type){case 1:return this.calculatePlaySoundSize(e);case 2:return this.calculatePlayGlobalSoundSize(e);case 3:case 5:case 6:return this.calculateTargetOrderSize(e);case 4:return this.calculateFadeOutSize(e);case 7:return nt;case 8:return ot;case 9:return this.calculateSetSoundEffectsSize(e);default:throw new Error(`Unknown audio order type: ${e.type}`)}}encodePlaySoundOrder(e){let t=this.calculatePlaySoundSize(e),r=f.allocUnsafe(t),n=0;return r.writeUInt8(e.type,n++),r.writeUInt8(e.soundId,n++),r.writeUInt16BE(e.instanceId,n),n+=2,r.writeUInt8(e.flags,n++),e.flags&2&&r.writeUInt8(e.volume??255,n++),e.flags&4&&r.writeUInt8(e.pitch??128,n++),e.flags&8&&r.writeUInt8(e.fadeIn??0,n++),e.flags&16&&(r.writeUInt16BE(e.posX??0,n),n+=2,r.writeUInt16BE(e.posY??0,n),n+=2),e.flags&32&&r.writeUInt8(e.lowpass??0,n++),e.flags&64&&r.writeUInt8(e.highpass??0,n++),e.flags&128&&r.writeUInt8(e.reverb??0,n++),r.toUint8Array()}encodePlayGlobalSoundOrder(e){let t=this.calculatePlayGlobalSoundSize(e),r=f.allocUnsafe(t),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.soundId,n++),r.writeUInt16BE(e.instanceId,n),n+=2;let o=e.flags&-17;return r.writeUInt8(o,n++),o&2&&r.writeUInt8(e.volume??255,n++),o&4&&r.writeUInt8(e.pitch??128,n++),o&8&&r.writeUInt8(e.fadeIn??0,n++),o&32&&r.writeUInt8(e.lowpass??0,n++),o&64&&r.writeUInt8(e.highpass??0,n++),o&128&&r.writeUInt8(e.reverb??0,n++),r.toUint8Array()}calculatePlaySoundSize(e){let t=an;return e.flags&2&&(t+=1),e.flags&4&&(t+=1),e.flags&8&&(t+=1),e.flags&16&&(t+=4),e.flags&32&&(t+=1),e.flags&64&&(t+=1),e.flags&128&&(t+=1),t}calculatePlayGlobalSoundSize(e){let t=sn,r=e.flags&-17;return r&2&&(t+=1),r&4&&(t+=1),r&8&&(t+=1),r&32&&(t+=1),r&64&&(t+=1),r&128&&(t+=1),t}encodeStopSoundOrder(e){return this.encodeTargetOrder(e.type,e.targetType,e.target)}encodePauseSoundOrder(e){return this.encodeTargetOrder(e.type,e.targetType,e.target)}encodeResumeSoundOrder(e){return this.encodeTargetOrder(e.type,e.targetType,e.target)}encodeFadeOutSoundOrder(e){let t=this.calculateFadeOutSize(e),r=f.allocUnsafe(t),n=0;return r.writeUInt8(e.type,n++),r.writeUInt8(e.targetType,n++),r.writeUInt8(e.duration,n++),e.targetType===0?r.writeUInt16BE(e.target??0,n):e.targetType===1&&r.writeUInt8(e.target??0,n),r.toUint8Array()}encodeTargetOrder(e,t,r){let n=2;t===0?n+=2:t===1&&(n+=1);let o=f.allocUnsafe(n),i=0;return o.writeUInt8(e,i++),o.writeUInt8(t,i++),t===0?o.writeUInt16BE(r??0,i):t===1&&o.writeUInt8(r??0,i),o.toUint8Array()}calculateTargetOrderSize(e){let t=2;return e.targetType===0?t+=2:e.targetType===1&&(t+=1),t}calculateFadeOutSize(e){let t=3;return e.targetType===0?t+=2:e.targetType===1&&(t+=1),t}encodeSetListenerPositionOrder(e){let t=f.allocUnsafe(nt),r=0;return t.writeUInt8(e.type,r++),t.writeUInt16BE(e.x,r),r+=2,t.writeUInt16BE(e.y,r),t.toUint8Array()}encodeConfigureSpatialOrder(e){let t=f.allocUnsafe(ot),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.maxDistance,r++),t.writeUInt8(e.referenceDistance,r++),t.writeUInt8(e.rolloffFactor,r++),t.writeUInt8(e.panSpread,r++),t.toUint8Array()}encodeSetSoundEffectsOrder(e){let t=this.calculateSetSoundEffectsSize(e),r=f.allocUnsafe(t),n=0;return r.writeUInt8(e.type,n++),r.writeUInt16BE(e.instanceId,n),n+=2,r.writeUInt8(e.flags,n++),e.flags&1&&r.writeUInt8(e.lowpass??0,n++),e.flags&2&&r.writeUInt8(e.highpass??0,n++),e.flags&4&&r.writeUInt8(e.reverb??0,n++),r.toUint8Array()}calculateSetSoundEffectsSize(e){let t=4;return e.flags&1&&(t+=1),e.flags&2&&(t+=1),e.flags&4&&(t+=1),t}};y(Xt,"AudioOrderEncoder");var Ne=Xt;L();var Wt=class Wt{encode(e){switch(e.type){case 1:return this.encodeMobileVibrateOrder(e);case 2:return this.encodeMobileCancelOrder(e);case 16:return this.encodeGamepadVibrateOrder(e);case 17:return this.encodeGamepadCancelOrder(e);default:throw new Error(`Unknown vibration order type: ${e.type}`)}}calculateSize(e){switch(e.type){case 1:return this.calculateMobileVibrateSize(e);case 2:return 1;case 16:return this.calculateGamepadVibrateSize(e);case 17:return 3;default:throw new Error(`Unknown vibration order type: ${e.type}`)}}calculateMobileVibrateSize(e){let t=3+e.pattern.length*2;return e.intensity!==void 0&&(t+=1),t}encodeMobileVibrateOrder(e){let t=this.calculateMobileVibrateSize(e),r=f.allocUnsafe(t),n=0,o=0;e.intensity!==void 0&&(o|=1),r.writeUInt8(e.type,n++),r.writeUInt8(o,n++),r.writeUInt8(e.pattern.length,n++);for(let i of e.pattern){let a=Math.min(65535,Math.max(0,Math.round(i)));r.writeUInt16BE(a,n),n+=2}if(e.intensity!==void 0){let i=Math.round(Math.min(1,Math.max(0,e.intensity))*255);r.writeUInt8(i,n++)}return r.toUint8Array()}encodeMobileCancelOrder(e){let t=f.allocUnsafe(1);return t.writeUInt8(2,0),t.toUint8Array()}calculateGamepadVibrateSize(e){let t=7;return e.startDelay!==void 0&&e.startDelay>0&&(t+=2),t}encodeGamepadVibrateOrder(e){let t=this.calculateGamepadVibrateSize(e),r=f.allocUnsafe(t),n=0,o=0;e.startDelay!==void 0&&e.startDelay>0&&(o|=1),e.gamepadIndex===255&&(o|=2),r.writeUInt8(e.type,n++),r.writeUInt8(o,n++),r.writeUInt8(e.gamepadIndex,n++);let i=Math.min(65535,Math.max(0,Math.round(e.duration)));if(r.writeUInt16BE(i,n),n+=2,r.writeUInt8(e.strongMagnitude,n++),r.writeUInt8(e.weakMagnitude,n++),e.startDelay!==void 0&&e.startDelay>0){let a=Math.min(65535,Math.max(0,Math.round(e.startDelay)));r.writeUInt16BE(a,n),n+=2}return r.toUint8Array()}encodeGamepadCancelOrder(e){let t=f.allocUnsafe(3),r=0,n=0;return e.gamepadIndex===255&&(n|=2),t.writeUInt8(e.type,r++),t.writeUInt8(n,r++),t.writeUInt8(e.gamepadIndex,r++),t.toUint8Array()}};y(Wt,"VibrationOrderEncoder");var he=Wt;L();var Gt=class Gt{encode(e){switch(e.type){case 1:return this.encodeCreateInstance(e);case 2:return this.encodeUpdateInstance(e);case 3:return this.encodeRemoveInstance(e);default:throw new Error(`Unknown macro order type: ${e.type}`)}}calculateSize(e){switch(e.type){case 1:return this.calculateCreateInstanceSize(e);case 2:return this.calculateUpdateInstanceSize(e);case 3:return 2;default:throw new Error(`Unknown macro order type: ${e.type}`)}}encodeCreateInstance(e){let t=JSON.stringify(e.params),r=new TextEncoder().encode(t);if(r.length>65535)throw new Error(`Params JSON too large: ${r.length} bytes (max 65535)`);let n=11+r.length,o=f.allocUnsafe(n),i=0;return o.writeUInt8(e.type,i++),o.writeUInt8(e.instanceId,i++),o.writeUInt8(e.macroId,i++),o.writeUInt8(e.layerId,i++),o.writeInt16BE(e.x,i),i+=2,o.writeInt16BE(e.y,i),i+=2,o.writeUInt8(e.tabIndex,i++),o.writeUInt16BE(r.length,i),i+=2,o.toUint8Array().set(r,i),o.toUint8Array()}calculateCreateInstanceSize(e){let t=JSON.stringify(e.params);return 11+new TextEncoder().encode(t).length}encodeUpdateInstance(e){let t=JSON.stringify(e.params),r=new TextEncoder().encode(t);if(r.length>65535)throw new Error(`Params JSON too large: ${r.length} bytes (max 65535)`);let n=4+r.length,o=f.allocUnsafe(n),i=0;return o.writeUInt8(e.type,i++),o.writeUInt8(e.instanceId,i++),o.writeUInt16BE(r.length,i),i+=2,o.toUint8Array().set(r,i),o.toUint8Array()}calculateUpdateInstanceSize(e){let t=JSON.stringify(e.params);return 4+new TextEncoder().encode(t).length}encodeRemoveInstance(e){let t=f.allocUnsafe(2);return t.writeUInt8(e.type,0),t.writeUInt8(e.instanceId,1),t.toUint8Array()}};y(Gt,"MacroOrderEncoder");var Ye=Gt;L();W();var $t=class $t{encode(e){switch(e.type){case 1:return this.encodeSetConfigOrder(e);case 2:return this.encodeSetScanlinesOrder(e);case 3:return this.encodeSetAmbientEffectOrder(e);case 4:return this.encodeSetScalingModeOrder(e);case 5:return this.encodeSetGridOrder(e);case 6:return this.encodeSwitchPaletteOrder(e);case 7:return this.encodeSetCellSizeOrder(e);default:throw new Error(`Unknown post-process order type: ${e.type}`)}}calculateSize(e){switch(e.type){case 1:return this.calculateSetConfigSize(e);case 2:return it;case 3:return at;case 4:return st;case 5:return dt;case 6:return ct;case 7:return lt;default:throw new Error(`Unknown post-process order type: ${e.type}`)}}encodeSetConfigOrder(e){let t=this.calculateSetConfigSize(e),r=f.allocUnsafe(t),n=0;return r.writeUInt8(e.type,n++),r.writeUInt8(e.displayId,n++),r.writeUInt8(e.flags,n++),e.flags&1&&e.scanlines&&(r.writeUInt8(e.scanlines.enabled?1:0,n++),r.writeUInt8(Math.round(e.scanlines.opacity*255),n++),r.writeUInt8(e.scanlines.pattern,n++),r.writeUInt8(e.scanlines.colorR,n++),r.writeUInt8(e.scanlines.colorG,n++),r.writeUInt8(e.scanlines.colorB,n++)),e.flags&2&&e.ambientEffect&&(r.writeUInt8(e.ambientEffect.enabled?1:0,n++),r.writeUInt8(Math.min(255,Math.round(e.ambientEffect.blur)),n++),r.writeUInt8(Math.min(255,Math.max(100,Math.round(e.ambientEffect.scale*100))),n++),r.writeUInt8(Math.round(e.ambientEffect.opacity*255),n++)),r.toUint8Array()}calculateSetConfigSize(e){let t=dn;return e.flags&1&&(t+=6),e.flags&2&&(t+=4),t}encodeSetScanlinesOrder(e){let t=f.allocUnsafe(it),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.displayId,r++),t.writeUInt8(e.enabled?1:0,r++),t.writeUInt8(Math.round(e.opacity*255),r++),t.writeUInt8(e.pattern,r++),t.writeUInt8(e.colorR,r++),t.writeUInt8(e.colorG,r++),t.writeUInt8(e.colorB,r++),t.toUint8Array()}encodeSetAmbientEffectOrder(e){let t=f.allocUnsafe(at),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.displayId,r++),t.writeUInt8(e.enabled?1:0,r++),t.writeUInt8(Math.min(255,Math.round(e.blur)),r++),t.writeUInt8(Math.min(255,Math.max(100,Math.round(e.scale*100))),r++),t.writeUInt8(Math.round(e.opacity*255),r++),t.toUint8Array()}encodeSetScalingModeOrder(e){let t=f.allocUnsafe(st),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.displayId,r++),t.writeUInt8(e.mode,r++),t.toUint8Array()}encodeSetGridOrder(e){let t=f.allocUnsafe(dt),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.displayId,r++),t.writeUInt8(e.enabled?1:0,r++),t.writeUInt8(e.colorR,r++),t.writeUInt8(e.colorG,r++),t.writeUInt8(e.colorB,r++),t.writeUInt8(e.colorA,r++),t.writeUInt8(Math.min(10,Math.max(1,e.lineWidth)),r++),t.toUint8Array()}encodeSwitchPaletteOrder(e){let t=f.allocUnsafe(ct),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.displayId,r++),t.writeUInt8(e.slotId,r++),t.toUint8Array()}encodeSetCellSizeOrder(e){let t=f.allocUnsafe(lt),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.displayId,r++),t.writeUInt8(e.cellWidth,r++),t.writeUInt8(e.cellHeight,r++),t.toUint8Array()}};y($t,"PostProcessOrderEncoder");var Xe=$t;L();var Zt=class Zt{constructor(){b(this,"layerEncoder");b(this,"audioOrderEncoder");b(this,"vibrationOrderEncoder");b(this,"macroOrderEncoder");b(this,"postProcessOrderEncoder");this.layerEncoder=new _e,this.audioOrderEncoder=new Ne,this.vibrationOrderEncoder=new he,this.macroOrderEncoder=new Ye,this.postProcessOrderEncoder=new Xe}encode(e){let t=e.layers.map(M=>this.layerEncoder.encode(M)),r=e.audioOrders||[],n=r.map(M=>this.audioOrderEncoder.encode(M)),o=e.vibrationOrders||[],i=o.map(M=>this.vibrationOrderEncoder.encode(M)),a=e.macroOrders||[],s=a.map(M=>this.macroOrderEncoder.encode(M)),d=e.postProcessOrders||[],c=d.map(M=>this.postProcessOrderEncoder.encode(M)),l=9,u=e.displays.length*7,p=2,m=t.reduce((M,T)=>M+T.length,0),g=1,C=n.reduce((M,T)=>M+T.length,0),x=1,O=i.reduce((M,T)=>M+T.length,0),I=1,w=s.reduce((M,T)=>M+T.length,0),U=1,P=c.reduce((M,T)=>M+T.length,0),E=l+u+p+m+g+C+x+O+I+w+U+P,v=f.allocUnsafe(E),S=0,A=typeof e.tick=="bigint"?e.tick:BigInt(e.tick);v.writeBigUInt64BE(A,S),S+=8,v.writeUInt8(e.displays.length,S),S+=1;for(let M of e.displays)v.writeUInt8(M.id,S++),v.writeUInt16BE(M.originX,S),S+=2,v.writeUInt16BE(M.originY,S),S+=2,v.writeUInt8(Math.max(1,Math.min(256,M.sizeX))-1,S++),v.writeUInt8(Math.max(1,Math.min(256,M.sizeY))-1,S++);v.writeUInt16BE(e.layers.length,S),S+=2;for(let M of t)f.from(M).copy(v,S),S+=M.length;v.writeUInt8(r.length,S),S+=1;for(let M of n)f.from(M).copy(v,S),S+=M.length;v.writeUInt8(o.length,S),S+=1;for(let M of i)f.from(M).copy(v,S),S+=M.length;v.writeUInt8(a.length,S),S+=1;for(let M of s)f.from(M).copy(v,S),S+=M.length;v.writeUInt8(d.length,S),S+=1;for(let M of c)f.from(M).copy(v,S),S+=M.length;return v.toUint8Array()}calculateSize(e){let r=e.displays.length*7,n=2,o=e.layers.reduce((O,I)=>O+this.layerEncoder.calculateSize(I),0),i=1,s=(e.audioOrders||[]).reduce((O,I)=>O+this.audioOrderEncoder.calculateSize(I),0),d=1,l=(e.vibrationOrders||[]).reduce((O,I)=>O+this.vibrationOrderEncoder.calculateSize(I),0),u=1,m=(e.macroOrders||[]).reduce((O,I)=>O+this.macroOrderEncoder.calculateSize(I),0),g=1,x=(e.postProcessOrders||[]).reduce((O,I)=>O+this.postProcessOrderEncoder.calculateSize(I),0);return 9+r+n+o+i+s+d+l+u+m+g+x}static createEmptyPacket(e){return{tick:typeof e=="bigint"?Number(e):e,displayCount:0,displays:[],layerCount:0,layers:[],audioOrderCount:0,audioOrders:[],vibrationOrderCount:0,vibrationOrders:[],macroOrderCount:0,macroOrders:[],postProcessOrderCount:0,postProcessOrders:[]}}encodeEmpty(e){let t=f.allocUnsafe(15),r=typeof e=="bigint"?e:BigInt(e);return t.writeBigUInt64BE(r,0),t.writeUInt8(0,8),t.writeUInt16BE(0,9),t.writeUInt8(0,11),t.writeUInt8(0,12),t.writeUInt8(0,13),t.writeUInt8(0,14),t.toUint8Array()}};y(Zt,"UpdatePacketEncoder");var We=Zt;var An=(s=>(s[s.ColorPalette=1]="ColorPalette",s[s.Sprite=2]="Sprite",s[s.MulticolorSprite=3]="MulticolorSprite",s[s.BitmapFont=4]="BitmapFont",s[s.Sound=5]="Sound",s[s.WebFont=6]="WebFont",s[s.Macro=7]="Macro",s[s.ImageFont=8]="ImageFont",s))(An||{});L();var jt=class jt{encode(e){let t=JSON.stringify(e.template),r=new TextEncoder().encode(t);if(r.length>65535)throw new Error(`Macro template JSON too large: ${r.length} bytes (max 65535)`);let n=4+r.length,o=f.allocUnsafe(n),i=0;return o.writeUInt8(7,i++),o.writeUInt8(e.macroId,i++),o.writeUInt16BE(r.length,i),i+=2,o.toUint8Array().set(r,i),o.toUint8Array()}calculateSize(e){let t=JSON.stringify(e.template);return 4+new TextEncoder().encode(t).length}};y(jt,"MacroLoadEncoder");var Ge=jt;L();var Jt=class Jt{encode(e){switch(e.loadType){case 1:return this.encodeColorPalette(e);case 2:return this.encodeSprite(e);case 3:return this.encodeMulticolorSprite(e);case 4:return this.encodeBitmapFont(e);case 5:return this.encodeSound(e);case 6:return this.encodeWebFont(e);case 8:return this.encodeImageFont(e);default:throw new Error(`Unknown load type: ${e.loadType}`)}}encodeColorPalette(e){let t=e.colors.length;if(t>255)throw new Error(`Palette size ${t} exceeds maximum of 255`);let r=e.slotId!==void 0,n=r?4:3,o=f.allocUnsafe(n+t*6),i=0;o.writeUInt8(1,i++),o.writeUInt8(r?255:0,i++),r&&o.writeUInt8(e.slotId,i++),o.writeUInt8(t,i++);for(let a of e.colors)o.writeUInt8(a.colorId,i++),o.writeUInt8(a.r,i++),o.writeUInt8(a.g,i++),o.writeUInt8(a.b,i++),o.writeUInt8(a.a,i++),o.writeUInt8(a.e??0,i++);return o.toUint8Array()}encodeSprite(e){let t=e.sprites.length;if(t>255)throw new Error(`Sprite count ${t} exceeds maximum of 255`);let r=2;for(let i of e.sprites)r+=3,r+=i.data.length;let n=f.allocUnsafe(r),o=0;n.writeUInt8(2,o++),n.writeUInt8(t,o++);for(let i of e.sprites){if(i.data.length!==i.sizeX*i.sizeY)throw new Error(`Sprite ${i.spriteId}: data length ${i.data.length} does not match size ${i.sizeX}x${i.sizeY}`);n.writeUInt8(i.spriteId,o++),n.writeUInt8(i.sizeX,o++),n.writeUInt8(i.sizeY,o++);for(let a of i.data)n.writeUInt8(a,o++)}return n.toUint8Array()}encodeMulticolorSprite(e){let t=e.sprites.length;if(t>255)throw new Error(`Sprite count ${t} exceeds maximum of 255`);let r=2;for(let i of e.sprites)r+=3,r+=i.data.length*3;let n=f.allocUnsafe(r),o=0;n.writeUInt8(3,o++),n.writeUInt8(t,o++);for(let i of e.sprites){if(i.data.length!==i.sizeX*i.sizeY)throw new Error(`Sprite ${i.spriteId}: data length ${i.data.length} does not match size ${i.sizeX}x${i.sizeY}`);n.writeUInt8(i.spriteId,o++),n.writeUInt8(i.sizeX,o++),n.writeUInt8(i.sizeY,o++);for(let a of i.data)n.writeUInt8(a.charCode,o++),n.writeUInt8(a.fgColorId,o++),n.writeUInt8(a.bgColorId,o++)}return n.toUint8Array()}encodeBitmapFont(e){let t=e.characters.length;if(t>255)throw new Error(`Character count ${t} exceeds maximum of 255`);let r=Math.ceil(e.width*e.height/8),n=7+t*(1+r),o=f.allocUnsafe(n),i=0;o.writeUInt8(4,i++),o.writeUInt8(e.fontId,i++),o.writeUInt8(e.width,i++),o.writeUInt8(e.height,i++),o.writeUInt8(e.cellWidth,i++),o.writeUInt8(e.cellHeight,i++),o.writeUInt8(t,i++);for(let a of e.characters){if(a.bitmap.length!==r)throw new Error(`Character ${a.charCode}: bitmap size ${a.bitmap.length} does not match expected ${r} bytes`);o.writeUInt8(a.charCode,i++);for(let s=0;s<a.bitmap.length;s++)o.writeUInt8(a.bitmap[s],i++)}return o.toUint8Array()}encodeSound(e){let t=e.sounds.length;if(t>255)throw new Error(`Sound count ${t} exceeds maximum of 255`);let r=2;for(let i of e.sounds){if(i.midiData.length>65535)throw new Error(`Sound ${i.soundId}: MIDI data size ${i.midiData.length} exceeds maximum of 65535 bytes`);r+=3,r+=i.midiData.length}let n=f.allocUnsafe(r),o=0;n.writeUInt8(5,o++),n.writeUInt8(t,o++);for(let i of e.sounds){n.writeUInt8(i.soundId,o++),n.writeUInt16BE(i.midiData.length,o),o+=2;for(let a=0;a<i.midiData.length;a++)n.writeUInt8(i.midiData[a],o++)}return n.toUint8Array()}encodeWebFont(e){let t=new TextEncoder,r=t.encode(e.fontFamily),n=e.fontWeight?t.encode(e.fontWeight):new Uint8Array(0),o=e.fontStyle?t.encode(e.fontStyle):new Uint8Array(0),i=0;e.offsetX!==void 0&&(i|=1),e.offsetY!==void 0&&(i|=2),e.charSpacing!==void 0&&(i|=4),e.lineHeight!==void 0&&(i|=8),e.fontWeight!==void 0&&(i|=16),e.fontStyle!==void 0&&(i|=32);let a=4;a+=r.length,a+=2,e.offsetX!==void 0&&(a+=2),e.offsetY!==void 0&&(a+=2),e.charSpacing!==void 0&&(a+=2),e.lineHeight!==void 0&&(a+=2),e.fontWeight!==void 0&&(a+=1+n.length),e.fontStyle!==void 0&&(a+=1+o.length);let s=f.allocUnsafe(a),d=0;s.writeUInt8(6,d++),s.writeUInt8(e.fontId,d++),s.writeUInt8(i,d++),s.writeUInt8(r.length,d++);for(let c=0;c<r.length;c++)s.writeUInt8(r[c],d++);if(s.writeUInt16BE(e.fontSize,d),d+=2,e.offsetX!==void 0&&(s.writeInt16BE(e.offsetX,d),d+=2),e.offsetY!==void 0&&(s.writeInt16BE(e.offsetY,d),d+=2),e.charSpacing!==void 0&&(s.writeInt16BE(e.charSpacing,d),d+=2),e.lineHeight!==void 0&&(s.writeUInt16BE(Math.round(e.lineHeight*100),d),d+=2),e.fontWeight!==void 0){s.writeUInt8(n.length,d++);for(let c=0;c<n.length;c++)s.writeUInt8(n[c],d++)}if(e.fontStyle!==void 0){s.writeUInt8(o.length,d++);for(let c=0;c<o.length;c++)s.writeUInt8(o[c],d++)}return s.toUint8Array()}encodeImageFont(e){if(![1,4,16].includes(e.atlasBlocks))throw new Error(`Invalid atlasBlocks: ${e.atlasBlocks}. Must be 1, 4, or 16.`);if(e.imageData.length>16*1024*1024)throw new Error(`Image data size ${e.imageData.length} exceeds maximum of 16MB`);let t=11+e.imageData.length,r=f.allocUnsafe(t),n=0;r.writeUInt8(8,n++),r.writeUInt8(e.fontId,n++),r.writeUInt8(e.glyphWidth,n++),r.writeUInt8(e.glyphHeight,n++),r.writeUInt8(e.cellWidth,n++),r.writeUInt8(e.cellHeight,n++),r.writeUInt8(e.atlasBlocks,n++),r.writeUInt32LE(e.imageData.length,n),n+=4;for(let o=0;o<e.imageData.length;o++)r.writeUInt8(e.imageData[o],n++);return r.toUint8Array()}};y(Jt,"LoadEncoder");var _=Jt;L();var qt=class qt{decode(e,t=0){let r=t,n=e.readUInt8(t++);if(n!==7)throw new Error(`Expected LoadType.Macro (0x07), got 0x${n.toString(16)}`);let o=e.readUInt8(t++),i=e.readUInt16BE(t);t+=2;let a=e.toUint8Array().subarray(t,t+i);t+=i;let s=new TextDecoder().decode(a),d=JSON.parse(s);return{load:{loadType:7,macroId:o,template:d},bytesRead:t-r}}};y(qt,"MacroLoadDecoder");var $e=qt;var Kt=class Kt{decode(e,t=0){let r=f.from(e);if(t>=r.length)throw new Error("Buffer too short to decode load type");let n=r.readUInt8(t);switch(n){case 1:return this.decodeColorPalette(r,t);case 2:return this.decodeSprite(r,t);case 3:return this.decodeMulticolorSprite(r,t);case 4:return this.decodeBitmapFont(r,t);case 5:return this.decodeSound(r,t);case 6:return this.decodeWebFont(r,t);case 7:return this.decodeMacro(r,t);case 8:return this.decodeImageFont(r,t);default:throw new Error(`Unknown load type: 0x${n.toString(16)}`)}}decodeColorPalette(e,t){let r=t;this.checkSize(e,t,3,"ColorPalette header");let n=e.readUInt8(t++),i=e.readUInt8(t++)===255,a;i&&(this.checkSize(e,t,1,"ColorPalette slotId"),a=e.readUInt8(t++));let s=e.readUInt8(t++);this.checkSize(e,t,s*6,`ColorPalette ${s} colors`);let d=[];for(let l=0;l<s;l++)d.push({colorId:e.readUInt8(t++),r:e.readUInt8(t++),g:e.readUInt8(t++),b:e.readUInt8(t++),a:e.readUInt8(t++),e:e.readUInt8(t++)});return{load:{loadType:1,...a!==void 0&&{slotId:a},colors:d},bytesRead:t-r}}decodeSprite(e,t){let r=t;this.checkSize(e,t,2,"Sprite header");let n=e.readUInt8(t++),o=e.readUInt8(t++),i=[];for(let s=0;s<o;s++){this.checkSize(e,t,3,`Sprite ${s} header`);let d=e.readUInt8(t++),c=e.readUInt8(t++),l=e.readUInt8(t++),u=c*l;this.checkSize(e,t,u,`Sprite ${s} data`);let p=[];for(let m=0;m<u;m++)p.push(e.readUInt8(t++));i.push({spriteId:d,sizeX:c,sizeY:l,data:p})}return{load:{loadType:2,sprites:i},bytesRead:t-r}}decodeMulticolorSprite(e,t){let r=t;this.checkSize(e,t,2,"MulticolorSprite header");let n=e.readUInt8(t++),o=e.readUInt8(t++),i=[];for(let s=0;s<o;s++){this.checkSize(e,t,3,`MulticolorSprite ${s} header`);let d=e.readUInt8(t++),c=e.readUInt8(t++),l=e.readUInt8(t++),u=c*l,p=u*3;this.checkSize(e,t,p,`MulticolorSprite ${s} data`);let m=[];for(let g=0;g<u;g++)m.push({charCode:e.readUInt8(t++),fgColorId:e.readUInt8(t++),bgColorId:e.readUInt8(t++)});i.push({spriteId:d,sizeX:c,sizeY:l,data:m})}return{load:{loadType:3,sprites:i},bytesRead:t-r}}decodeBitmapFont(e,t){let r=t;this.checkSize(e,t,7,"BitmapFont header");let n=e.readUInt8(t++),o=e.readUInt8(t++),i=e.readUInt8(t++),a=e.readUInt8(t++),s=e.readUInt8(t++),d=e.readUInt8(t++),c=e.readUInt8(t++),l=Math.ceil(i*a/8),u=[];for(let m=0;m<c;m++){this.checkSize(e,t,1+l,`BitmapFont character ${m}`);let g=e.readUInt8(t++),C=new Uint8Array(l);for(let x=0;x<l;x++)C[x]=e.readUInt8(t++);u.push({charCode:g,bitmap:C})}return{load:{loadType:4,fontId:o,width:i,height:a,cellWidth:s,cellHeight:d,characters:u},bytesRead:t-r}}decodeSound(e,t){let r=t;this.checkSize(e,t,2,"Sound header");let n=e.readUInt8(t++),o=e.readUInt8(t++),i=[];for(let s=0;s<o;s++){this.checkSize(e,t,3,`Sound ${s} header`);let d=e.readUInt8(t++),c=e.readUInt16BE(t);t+=2,this.checkSize(e,t,c,`Sound ${s} MIDI data`);let l=new Uint8Array(c);for(let u=0;u<c;u++)l[u]=e.readUInt8(t++);i.push({soundId:d,midiData:l})}return{load:{loadType:5,sounds:i},bytesRead:t-r}}checkSize(e,t,r,n){if(t+r>e.length)throw new Error(`Buffer too short for ${n}: need ${r} bytes at offset ${t}, but only ${e.length-t} bytes remaining`)}decodeWebFont(e,t){let r=t,n=new TextDecoder;this.checkSize(e,t,5,"WebFont header");let o=e.readUInt8(t++),i=e.readUInt8(t++),a=e.readUInt8(t++),s=e.readUInt8(t++);this.checkSize(e,t,s,"WebFont family string");let d=new Uint8Array(s);for(let p=0;p<s;p++)d[p]=e.readUInt8(t++);let c=n.decode(d);this.checkSize(e,t,2,"WebFont fontSize");let l=e.readUInt16BE(t);t+=2;let u={loadType:6,fontId:i,fontFamily:c,fontSize:l};if(a&1&&(this.checkSize(e,t,2,"WebFont offsetX"),u.offsetX=e.readInt16BE(t),t+=2),a&2&&(this.checkSize(e,t,2,"WebFont offsetY"),u.offsetY=e.readInt16BE(t),t+=2),a&4&&(this.checkSize(e,t,2,"WebFont charSpacing"),u.charSpacing=e.readInt16BE(t),t+=2),a&8){this.checkSize(e,t,2,"WebFont lineHeight");let p=e.readUInt16BE(t);u.lineHeight=p/100,t+=2}if(a&16){this.checkSize(e,t,1,"WebFont weight length");let p=e.readUInt8(t++);this.checkSize(e,t,p,"WebFont weight string");let m=new Uint8Array(p);for(let g=0;g<p;g++)m[g]=e.readUInt8(t++);u.fontWeight=n.decode(m)}if(a&32){this.checkSize(e,t,1,"WebFont style length");let p=e.readUInt8(t++);this.checkSize(e,t,p,"WebFont style string");let m=new Uint8Array(p);for(let g=0;g<p;g++)m[g]=e.readUInt8(t++);u.fontStyle=n.decode(m)}return{load:u,bytesRead:t-r}}decodeMacro(e,t){return new $e().decode(e,t)}decodeImageFont(e,t){let r=t;this.checkSize(e,t,7,"ImageFont header");let n=e.readUInt8(t++),o=e.readUInt8(t++),i=e.readUInt8(t++),a=e.readUInt8(t++),s=e.readUInt8(t++),d=e.readUInt8(t++),c=e.readUInt8(t++);if(![1,4,16].includes(c))throw new Error(`Invalid atlasBlocks value: ${c}. Must be 1, 4, or 16.`);let l=c;this.checkSize(e,t,4,"ImageFont image data size");let u=e.readUInt32LE(t);t+=4,this.checkSize(e,t,u,"ImageFont image data");let p=new Uint8Array(u);for(let g=0;g<u;g++)p[g]=e.readUInt8(t++);return{load:{loadType:8,fontId:o,glyphWidth:i,glyphHeight:a,cellWidth:s,cellHeight:d,atlasBlocks:l,imageData:p},bytesRead:t-r}}};y(Kt,"LoadDecoder");var Ze=Kt;var X=class X{constructor(e){this.engine=e;b(this,"colorCache",new Array(256));b(this,"cellsBuffer",[]);b(this,"opacityBuffer",new Uint8Array(0));b(this,"visibleLayersBuffer",[]);this.rebuildColorCache()}static getChar(e){let t=X.charCache.get(e);return t===void 0&&(t=String.fromCharCode(e),X.charCache.set(e,t)),t}rebuildColorCache(){for(let e=0;e<256;e++){let t=this.engine.getColor(e);t?this.colorCache[e]={r:t.r,g:t.g,b:t.b,a:t.a}:this.colorCache[e]={r:0,g:0,b:0,a:0}}}getColorRGB(e){return this.colorCache[e]??this.colorCache[255]}getColorEmission(e){let t=this.engine.getColor(e);return t?t.e:0}isLayerVisible(e,t){let r=e.x,n=e.x+e.width,o=e.y,i=e.y+e.height,a=t.x,s=t.x+256,d=t.y,c=t.y+256;return!(n<=a||r>=s||i<=d||o>=c)}rasterize(e,t){let r=e.width*e.height,n=this.cellsBuffer;n.length=r;for(let s=0;s<r;s++)n[s]?(n[s].char=" ",n[s].fgColorIndex=255,n[s].bgColorIndex=255,n[s].fgEmission=0,n[s].bgEmission=0):n[s]={char:" ",fgColorIndex:255,bgColorIndex:255,fgEmission:0,bgEmission:0};this.opacityBuffer.length<r?this.opacityBuffer=new Uint8Array(r):this.opacityBuffer.fill(0,0,r);let o=this.opacityBuffer,i=this.visibleLayersBuffer;i.length=0;for(let s=0;s<t.length;s++){let d=t[s];d.isEnabled()&&this.isLayerVisible(e,d.getOrigin())&&i.push(d)}i.sort((s,d)=>d.getZOrder()-s.getZOrder());for(let s=0;s<e.height;s++)for(let d=0;d<e.width;d++){let c=s*e.width+d;if(o[c])continue;let l=e.x+d,u=e.y+s;for(let p=0;p<i.length;p++){let m=i[p],g=l-m.getOrigin().x,C=u-m.getOrigin().y,x=m.getWidth(),O=m.getHeight();if(g<0||g>=x||C<0||C>=O)continue;let I=C*x+g,w=m.getData(),U=w.getCharCode(I),P=w.getFgColorCode(I),E=w.getBgColorCode(I),v=n[c];if(U!==0&&v.char===" "&&(v.char=X.getChar(U)),P!==255&&v.fgColorIndex===255&&(v.fgColorIndex=P,v.fgEmission=this.getColorEmission(P)),E!==255){v.bgColorIndex===255&&(v.bgColorIndex=E,v.bgEmission=this.getColorEmission(E)),o[c]=1;break}}}let a=new Array(r);for(let s=0;s<r;s++)a[s]={char:n[s].char,fgColorIndex:n[s].fgColorIndex,bgColorIndex:n[s].bgColorIndex,fgEmission:n[s].fgEmission,bgEmission:n[s].bgEmission};return{width:e.width,height:e.height,cells:a,palette:this.colorCache}}rasterizeWithSortedLayers(e,t){let r=e.width*e.height,n=this.cellsBuffer;n.length=r;for(let s=0;s<r;s++)n[s]?(n[s].char=" ",n[s].fgColorIndex=255,n[s].bgColorIndex=255,n[s].fgEmission=0,n[s].bgEmission=0):n[s]={char:" ",fgColorIndex:255,bgColorIndex:255,fgEmission:0,bgEmission:0};this.opacityBuffer.length<r?this.opacityBuffer=new Uint8Array(r):this.opacityBuffer.fill(0,0,r);let o=this.opacityBuffer,i=this.visibleLayersBuffer;i.length=0;for(let s=0;s<t.length;s++){let d=t[s];this.isLayerVisible(e,d.getOrigin())&&i.push(d)}for(let s=0;s<e.height;s++)for(let d=0;d<e.width;d++){let c=s*e.width+d;if(o[c])continue;let l=e.x+d,u=e.y+s;for(let p=0;p<i.length;p++){let m=i[p],g=l-m.getOrigin().x,C=u-m.getOrigin().y,x=m.getWidth(),O=m.getHeight();if(g<0||g>=x||C<0||C>=O)continue;let I=C*x+g,w=m.getData(),U=w.getCharCode(I),P=w.getFgColorCode(I),E=w.getBgColorCode(I),v=n[c];if(U!==0&&v.char===" "&&(v.char=X.getChar(U)),P!==255&&v.fgColorIndex===255&&(v.fgColorIndex=P,v.fgEmission=this.getColorEmission(P)),E!==255){v.bgColorIndex===255&&(v.bgColorIndex=E,v.bgEmission=this.getColorEmission(E)),o[c]=1;break}}}let a=new Array(r);for(let s=0;s<r;s++)a[s]={char:n[s].char,fgColorIndex:n[s].fgColorIndex,bgColorIndex:n[s].bgColorIndex,fgEmission:n[s].fgEmission,bgEmission:n[s].bgEmission};return{width:e.width,height:e.height,cells:a,palette:this.colorCache}}calculateIntersection(e,t){let r=e.x,n=e.x+e.width,o=e.y,i=e.y+e.height,a=t.x,s=t.x+256,d=t.y,c=t.y+256,l=Math.max(r,a),u=Math.min(n,s),p=Math.max(o,d),m=Math.min(i,c);return{visible:l<u&&p<m,originStart:{x:l-e.x,y:p-e.y},originEnd:{x:u-e.x,y:m-e.y},layerStart:{x:l-t.x,y:p-t.y},layerEnd:{x:u-t.x,y:m-t.y}}}};y(X,"DisplayRasterizer"),b(X,"charCache",(()=>{let e=new Map;for(let t=0;t<256;t++)e.set(t,String.fromCharCode(t));return e})());var je=X;var Qt=class Qt{constructor(){b(this,"enabled",!1);b(this,"currentStats",null)}setEnabled(e){this.enabled=e,e||(this.currentStats=null)}isEnabled(){return this.enabled}get tick(){return this.currentStats?.tick??0}get timestamp(){return this.currentStats?.timestamp??0}get totalOrders(){return this.currentStats?.totalOrders??0}get ordersByLayer(){return this.currentStats?.ordersByLayer??new Map}get ordersByType(){return this.currentStats?.ordersByType??new Map}get totalLayers(){return this.currentStats?.totalLayers??0}get visibleLayers(){return this.currentStats?.visibleLayers??0}get layersPerDisplay(){return this.currentStats?.layersPerDisplay??new Map}get updatePacketSize(){return this.currentStats?.updatePacketSize??0}get displayHeaderSize(){return this.currentStats?.displayHeaderSize??0}get layerHeaderSize(){return this.currentStats?.layerHeaderSize??0}get orderDataSize(){return this.currentStats?.orderDataSize??0}get compressionRatio(){return this.currentStats?.compressionRatio??0}get compressedPacketSize(){return Math.round(this.updatePacketSize*this.compressionRatio)}get totalCells(){return this.currentStats?.totalCells??0}get nonEmptyCells(){return this.currentStats?.nonEmptyCells??0}get cellsWithBackground(){return this.currentStats?.cellsWithBackground??0}get rasterizationTimeMs(){return this.currentStats?.rasterizationTimeMs??0}get encodingTimeMs(){return this.currentStats?.encodingTimeMs??0}get packetSplit(){return this.currentStats?.packetSplit}get layerDetails(){return this.currentStats?.layerDetails}startTick(e){this.enabled&&(this.currentStats={tick:e,timestamp:Date.now(),totalOrders:0,ordersByLayer:new Map,ordersByType:new Map,totalLayers:0,visibleLayers:0,layersPerDisplay:new Map,updatePacketSize:0,displayHeaderSize:0,layerHeaderSize:0,orderDataSize:0,compressionRatio:0,totalCells:0,nonEmptyCells:0,cellsWithBackground:0,rasterizationTimeMs:0,encodingTimeMs:0})}recordLayerOrders(e,t){if(!(!this.enabled||!this.currentStats)){this.currentStats.totalOrders+=t.length,this.currentStats.ordersByLayer.set(e,t.length);for(let r of t){let n=this.currentStats.ordersByType.get(r.type)||0;this.currentStats.ordersByType.set(r.type,n+1)}}}recordLayers(e,t){!this.enabled||!this.currentStats||(this.currentStats.totalLayers=e,this.currentStats.visibleLayers=t)}recordDisplayLayers(e,t){!this.enabled||!this.currentStats||this.currentStats.layersPerDisplay.set(e,t)}recordUpdatePacketSize(e,t,r,n){!this.enabled||!this.currentStats||(this.currentStats.updatePacketSize=e,this.currentStats.displayHeaderSize=t,this.currentStats.layerHeaderSize=r,this.currentStats.orderDataSize=n,this.currentStats.compressionRatio=.25)}recordPacketSplit(e,t,r,n){!this.enabled||!this.currentStats||(this.currentStats.packetSplit={userId:e,displayCount:t,staticLayerCount:r,dynamicLayerCount:n})}recordLayerInfo(e,t,r,n){!this.enabled||!this.currentStats||(this.currentStats.layerDetails||(this.currentStats.layerDetails=[]),this.currentStats.layerDetails.push({layerId:e,isStatic:t,orderCount:r,updateFlags:n}))}recordRenderStats(e,t,r){!this.enabled||!this.currentStats||(this.currentStats.totalCells=e,this.currentStats.nonEmptyCells=t,this.currentStats.cellsWithBackground=r)}recordRasterizationTime(e){!this.enabled||!this.currentStats||(this.currentStats.rasterizationTimeMs=e)}recordEncodingTime(e){!this.enabled||!this.currentStats||(this.currentStats.encodingTimeMs=e)}endTick(){}reset(){this.currentStats=null}};y(Qt,"CoreStats");var be=Qt;var er=class er{constructor(){b(this,"unicolorSprites",new Map);b(this,"multicolorSprites",new Map)}loadUnicolorSprites(e){for(let t of e.sprites){let r=new oe(t.sizeX*t.sizeY);for(let o=0;o<t.data.length;o++)r.set(o,t.data[o]);let n={id:t.spriteId,sizeX:t.sizeX,sizeY:t.sizeY,data:r};this.unicolorSprites.set(n.id,n)}}loadMulticolorSprites(e){for(let t of e.sprites){let r=new G(t.sizeX*t.sizeY);for(let o=0;o<t.data.length;o++){let i=t.data[o];r.set(o,i.charCode,i.fgColorId,i.bgColorId)}let n={id:t.spriteId,sizeX:t.sizeX,sizeY:t.sizeY,data:r};this.multicolorSprites.set(n.id,n)}}getUnicolorSprite(e){return this.unicolorSprites.get(e)}getMulticolorSprite(e){return this.multicolorSprites.get(e)}hasUnicolorSprite(e){return this.unicolorSprites.has(e)}hasMulticolorSprite(e){return this.multicolorSprites.has(e)}unloadUnicolorSprite(e){return this.unicolorSprites.delete(e)}unloadMulticolorSprite(e){return this.multicolorSprites.delete(e)}clearUnicolorSprites(){this.unicolorSprites.clear()}clearMulticolorSprites(){this.multicolorSprites.clear()}clearAll(){this.unicolorSprites.clear(),this.multicolorSprites.clear()}getUnicolorSpriteCount(){return this.unicolorSprites.size}getMulticolorSpriteCount(){return this.multicolorSprites.size}getTotalSpriteCount(){return this.unicolorSprites.size+this.multicolorSprites.size}};y(er,"SpriteRegistry");var ge=er;var En=(r=>(r.Web="web",r.Bitmap="bitmap",r.Image="image",r))(En||{});function tr(h){return Math.sqrt(h)*16}y(tr,"getAtlasColumns");function Pn(h){return h*256-1}y(Pn,"getMaxCharCode");function so(h,e){let r=tr(h)*e;return{width:r,height:r}}y(so,"getAtlasDimensions");var rr=class rr{constructor(e,t){this.fontId=e;this.config=t}getFontId(){return this.fontId}getConfig(){return{...this.config}}getFontFamily(){return this.config.fontFamily}getFontSize(){return this.config.fontSize}getOffsetX(){return this.config.offsetX??0}getOffsetY(){return this.config.offsetY??0}getCharSpacing(){return this.config.charSpacing??0}getLineHeight(){return this.config.lineHeight??1.2}getFontWeight(){return this.config.fontWeight??"normal"}getFontStyle(){return this.config.fontStyle??"normal"}toCSS(){let e=[];e.push(`font-family: ${this.config.fontFamily}`),e.push(`font-size: ${this.config.fontSize}px`);let t=this.config.fontWeight??"normal";t!=="normal"&&e.push(`font-weight: ${t}`);let r=this.config.fontStyle??"normal";return r!=="normal"&&e.push(`font-style: ${r}`),e.join("; ")+";"}};y(rr,"WebFont");var $=rr,nr=class nr{constructor(e,t){this.fontId=e;this.config=t}getFontId(){return this.fontId}getConfig(){return{charWidth:this.config.charWidth,charHeight:this.config.charHeight,cellWidth:this.config.cellWidth,cellHeight:this.config.cellHeight,glyphs:new Map(this.config.glyphs)}}getCharWidth(){return this.config.charWidth}getCharHeight(){return this.config.charHeight}getCellWidth(){return this.config.cellWidth??this.config.charWidth}getCellHeight(){return this.config.cellHeight??this.config.charHeight}getGlyph(e){return this.config.glyphs.get(e)}hasGlyph(e){return this.config.glyphs.has(e)}getGlyphCount(){return this.config.glyphs.size}getCharCodes(){return Array.from(this.config.glyphs.keys())}};y(nr,"BitmapFont");var ye=nr,or=class or{constructor(e,t){this.fontId=e;this.config=t;b(this,"atlasColumns");b(this,"maxCharCode");this.atlasColumns=tr(t.atlasBlocks),this.maxCharCode=Pn(t.atlasBlocks)}getFontId(){return this.fontId}getConfig(){return{glyphWidth:this.config.glyphWidth,glyphHeight:this.config.glyphHeight,cellWidth:this.config.cellWidth,cellHeight:this.config.cellHeight,atlasBlocks:this.config.atlasBlocks,imageData:this.config.imageData}}getGlyphWidth(){return this.config.glyphWidth}getGlyphHeight(){return this.config.glyphHeight}getCellWidth(){return this.config.cellWidth??this.config.glyphWidth}getCellHeight(){return this.config.cellHeight??this.config.glyphHeight}getAtlasBlocks(){return this.config.atlasBlocks}getAtlasColumns(){return this.atlasColumns}getMaxCharCode(){return this.maxCharCode}getImageData(){return this.config.imageData}getAtlasDimensions(){return{width:this.atlasColumns*this.config.glyphWidth,height:this.atlasColumns*this.config.glyphHeight}}getCharUV(e){if(e<0||e>this.maxCharCode)return null;let t=e%this.atlasColumns,r=Math.floor(e/this.atlasColumns),n=t/this.atlasColumns,o=r/this.atlasColumns,i=(t+1)/this.atlasColumns,a=(r+1)/this.atlasColumns;return{u1:n,v1:o,u2:i,v2:a}}isValidCharCode(e){return e>=0&&e<=this.maxCharCode}};y(or,"ImageFont");var q=or;var ir=class ir{constructor(){b(this,"fonts",new Map)}loadFont(e,t){if(this.fonts.has(e))throw new Error(`WebFont with ID ${e} already exists`);let r=new $(e,t);this.fonts.set(e,r)}getFont(e){return this.fonts.get(e)}hasFont(e){return this.fonts.has(e)}unloadFont(e){return this.fonts.delete(e)}clearFonts(){this.fonts.clear()}getFontIds(){return Array.from(this.fonts.keys()).sort((e,t)=>e-t)}getAllFonts(){return Array.from(this.fonts.entries()).sort((e,t)=>e[0]-t[0]).map(e=>e[1])}getFontCount(){return this.fonts.size}};y(ir,"WebFontRegistry");var Ce=ir;var ar=class ar{constructor(){b(this,"fonts",new Map)}loadFont(e,t){if(this.fonts.has(e))throw new Error(`BitmapFont with ID ${e} already exists`);let r=new ye(e,t);this.fonts.set(e,r)}getFont(e){return this.fonts.get(e)}hasFont(e){return this.fonts.has(e)}unloadFont(e){return this.fonts.delete(e)}clearFonts(){this.fonts.clear()}getFontIds(){return Array.from(this.fonts.keys()).sort((e,t)=>e-t)}getAllFonts(){return Array.from(this.fonts.entries()).sort((e,t)=>e[0]-t[0]).map(e=>e[1])}getFontCount(){return this.fonts.size}};y(ar,"BitmapFontRegistry");var xe=ar;var sr=class sr{constructor(){b(this,"fonts",new Map);b(this,"nameToId",new Map);b(this,"nextId",0)}allocateId(e){if(this.nextId>255)throw new Error(`Cannot register font "${e}": maximum 256 fonts reached`);return this.nextId++}registerFont(e,t,r){if(this.nameToId.has(e))throw new Error(`ImageFont with name "${e}" already exists`);let n=this.allocateId(e),o={glyphWidth:t.glyphWidth,glyphHeight:t.glyphHeight,cellWidth:t.cellWidth,cellHeight:t.cellHeight,atlasBlocks:t.atlasBlocks??1,imageData:r},i=new q(n,o);return this.fonts.set(n,i),this.nameToId.set(e,n),n}loadFont(e,t){if(this.fonts.has(e))throw new Error(`ImageFont with ID ${e} already exists`);let r=new q(e,t);this.fonts.set(e,r),e>=this.nextId&&(this.nextId=e+1)}getFont(e){return this.fonts.get(e)}getFontByName(e){let t=this.nameToId.get(e);if(t!==void 0)return this.fonts.get(t)}getFontId(e){return this.nameToId.get(e)}getFontName(e){for(let[t,r]of this.nameToId.entries())if(r===e)return t}hasFont(e){return this.fonts.has(e)}hasFontByName(e){return this.nameToId.has(e)}unloadFont(e){if(!this.fonts.get(e))return!1;for(let[r,n]of this.nameToId.entries())if(n===e){this.nameToId.delete(r);break}return this.fonts.delete(e)}unloadFontByName(e){let t=this.nameToId.get(e);return t===void 0?!1:(this.nameToId.delete(e),this.fonts.delete(t))}clearFonts(){this.fonts.clear(),this.nameToId.clear(),this.nextId=0}getFontIds(){return Array.from(this.fonts.keys()).sort((e,t)=>e-t)}getFontNames(){return Array.from(this.nameToId.keys())}getAllFonts(){return Array.from(this.fonts.entries()).sort((e,t)=>e[0]-t[0]).map(e=>e[1])}getFontCount(){return this.fonts.size}};y(sr,"ImageFontRegistry");var fe=sr;var dr=class dr{constructor(){b(this,"sounds",new Map);b(this,"nameToId",new Map);b(this,"nextId",0)}registerFile(e,t,r){let n=this.allocateId(e),o={soundId:n,name:e,loadType:"file",format:t,data:r};return this.sounds.set(n,o),this.nameToId.set(e,n),n}registerFileWithId(e,t,r,n){this.validateId(e),this.checkIdAvailable(e,t);let o={soundId:e,name:t,loadType:"file",format:r,data:n};this.sounds.set(e,o),this.nameToId.set(t,e)}registerExternal(e,t,r,n,o){let i=this.allocateId(e),a={soundId:i,name:e,loadType:"external",format:t,url:r,size:n,checksum:o};return this.sounds.set(i,a),this.nameToId.set(e,i),i}registerExternalWithId(e,t,r,n,o,i){this.validateId(e),this.checkIdAvailable(e,t);let a={soundId:e,name:t,loadType:"external",format:r,url:n,size:o,checksum:i};this.sounds.set(e,a),this.nameToId.set(t,e)}get(e){if(typeof e=="number")return this.sounds.get(e);let t=this.nameToId.get(e);return t!==void 0?this.sounds.get(t):void 0}has(e){return this.get(e)!==void 0}getAll(){return Array.from(this.sounds.values())}getFileSounds(){return this.getAll().filter(e=>e.loadType==="file")}getExternalSounds(){return this.getAll().filter(e=>e.loadType==="external")}getNames(){return Array.from(this.nameToId.keys())}getId(e){return this.nameToId.get(e)}toLoadPackets(){let e=[],t=this.getFileSounds();if(t.length>0){let n=t.map(o=>({soundId:o.soundId,name:o.name,format:o.format,data:o.data}));e.push({type:"sound",mode:"file",sounds:n})}let r=this.getExternalSounds();if(r.length>0){let n=r.map(o=>({soundId:o.soundId,name:o.name,format:o.format,url:o.url,size:o.size,checksum:o.checksum}));e.push({type:"sound",mode:"external",sounds:n})}return e}toLoadPacket(e){let t=this.get(e);return t?t.loadType==="file"?{type:"sound",mode:"file",sounds:[{soundId:t.soundId,name:t.name,format:t.format,data:t.data}]}:{type:"sound",mode:"external",sounds:[{soundId:t.soundId,name:t.name,format:t.format,url:t.url,size:t.size,checksum:t.checksum}]}:null}unregister(e){let t=this.get(e);return t?(this.sounds.delete(t.soundId),this.nameToId.delete(t.name),!0):!1}clear(){this.sounds.clear(),this.nameToId.clear(),this.nextId=0}get size(){return this.sounds.size}getStats(){let e=this.getAll(),t=e.filter(n=>n.loadType==="file"),r=t.reduce((n,o)=>n+(o.data?.length??0),0);return{total:e.length,file:t.length,external:e.length-t.length,totalFileSize:r}}allocateId(e){if(this.nameToId.has(e))throw new Error(`Sound with name "${e}" already exists`);for(;this.sounds.has(this.nextId);)if(this.nextId++,this.nextId>255)throw new Error("Maximum number of sounds (256) reached");return this.nextId++}validateId(e){if(!Number.isInteger(e)||e<0||e>255)throw new Error(`Invalid sound ID: ${e}. Must be an integer between 0 and 255.`)}checkIdAvailable(e,t){if(this.sounds.has(e)){let r=this.sounds.get(e);throw new Error(`Sound ID ${e} is already used by "${r.name}". Cannot register "${t}".`)}if(this.nameToId.has(t))throw new Error(`Sound with name "${t}" already exists`)}};y(dr,"SoundRegistry");var Se=dr;var cr=class cr{constructor(e){this.soundRegistry=e}collectFromUser(e){let t=[],r=e.flushSoundCommands();for(let o of r){let i=this.convertSoundCommand(o);i&&t.push(i)}let n=e.flushAudioConfigCommands();for(let o of n){let i=this.convertConfigCommand(o);i&&t.push(i)}return t}convertSoundCommand(e){return"setEffects"in e&&e.setEffects===!0?this.convertSetEffectsCommand(e):"fadeOut"in e&&e.fadeOut===!0?this.convertFadeOutCommand(e):"pause"in e&&e.pause===!0?this.convertPauseCommand(e):"resume"in e&&e.resume===!0?this.convertResumeCommand(e):"instanceId"in e||"volume"in e||"pitch"in e||"loop"in e||"fadeIn"in e||"x"in e||"y"in e||"lowpass"in e||"highpass"in e||"reverb"in e?this.convertPlayCommand(e):this.convertStopCommand(e)}convertPlayCommand(e){let t=this.resolveSoundId(e.sound);if(t===null)return console.warn(`[AudioOrderCollector] Unknown sound: ${e.sound}`),null;let r=0;e.loop&&(r|=1),e.volume!==void 0&&(r|=2),e.pitch!==void 0&&(r|=4),e.fadeIn!==void 0&&(r|=8),e.lowpass!==void 0&&e.lowpass>0&&(r|=32),e.highpass!==void 0&&e.highpass>0&&(r|=64),e.reverb!==void 0&&e.reverb>0&&(r|=128);let n=e.x!==void 0&&e.y!==void 0;return n&&(r|=16),n?{type:1,soundId:t,instanceId:e.instanceId??0,flags:r,volume:e.volume!==void 0?this.encodeVolume(e.volume):void 0,pitch:e.pitch!==void 0?this.encodePitch(e.pitch):void 0,fadeIn:e.fadeIn!==void 0?this.encodeFadeTime(e.fadeIn):void 0,posX:this.encodePosition(e.x),posY:this.encodePosition(e.y),lowpass:e.lowpass!==void 0&&e.lowpass>0?this.encodeFilterFreq(e.lowpass):void 0,highpass:e.highpass!==void 0&&e.highpass>0?this.encodeFilterFreq(e.highpass):void 0,reverb:e.reverb!==void 0&&e.reverb>0?this.encodeReverb(e.reverb):void 0}:{type:2,soundId:t,instanceId:e.instanceId??0,flags:r&-17,volume:e.volume!==void 0?this.encodeVolume(e.volume):void 0,pitch:e.pitch!==void 0?this.encodePitch(e.pitch):void 0,fadeIn:e.fadeIn!==void 0?this.encodeFadeTime(e.fadeIn):void 0,lowpass:e.lowpass!==void 0&&e.lowpass>0?this.encodeFilterFreq(e.lowpass):void 0,highpass:e.highpass!==void 0&&e.highpass>0?this.encodeFilterFreq(e.highpass):void 0,reverb:e.reverb!==void 0&&e.reverb>0?this.encodeReverb(e.reverb):void 0}}convertStopCommand(e){let{targetType:t,target:r}=this.resolveTarget(e.sound);return{type:3,targetType:t,target:r}}convertFadeOutCommand(e){let{targetType:t,target:r}=this.resolveTarget(e.sound);return{type:4,targetType:t,duration:this.encodeFadeTime(e.duration),target:r}}convertPauseCommand(e){let{targetType:t,target:r}=this.resolveTarget(e.sound);return{type:5,targetType:t,target:r}}convertResumeCommand(e){let{targetType:t,target:r}=this.resolveTarget(e.sound);return{type:6,targetType:t,target:r}}convertSetEffectsCommand(e){let t=0;return e.lowpass!==void 0&&(t|=1),e.highpass!==void 0&&(t|=2),e.reverb!==void 0&&(t|=4),{type:9,instanceId:e.instanceId,flags:t,lowpass:e.lowpass!==void 0?this.encodeFilterFreq(e.lowpass):void 0,highpass:e.highpass!==void 0?this.encodeFilterFreq(e.highpass):void 0,reverb:e.reverb!==void 0?this.encodeReverb(e.reverb):void 0}}convertConfigCommand(e){return e.type==="set-listener-position"?{type:7,x:this.encodePosition(e.x),y:this.encodePosition(e.y)}:e.type==="configure-spatial"?{type:8,maxDistance:this.encodeDistance(e.maxDistance??1e3),referenceDistance:this.encodeDistance(e.referenceDistance??100),rolloffFactor:this.encodeRolloff(e.rolloffFactor??1),panSpread:this.encodePanSpread(e.panSpread??.5)}:null}resolveSoundId(e){if(typeof e=="number")return e>=0&&e<=255?e:null;let t=this.soundRegistry.getId(e);return t!==void 0?t:null}resolveTarget(e){if(e==="all")return{targetType:2,target:void 0};if(typeof e=="number")return{targetType:0,target:e};let t=this.soundRegistry.getId(e);return t!==void 0?{targetType:1,target:t}:(console.warn(`[AudioOrderCollector] Unknown sound name: ${e}, treating as 'all'`),{targetType:2,target:void 0})}encodeVolume(e){return Math.round(Math.max(0,Math.min(1,e))*255)}encodePitch(e){let t=Math.max(.25,Math.min(4,e)),r=64*Math.log2(t/.25);return Math.round(Math.max(0,Math.min(255,r)))}encodeFadeTime(e){return Math.round(Math.max(0,Math.min(25.5,e))*10)}encodeDistance(e){return Math.round(Math.max(0,Math.min(25500,e))/100)}encodeRolloff(e){return Math.round(Math.max(0,Math.min(2.55,e))*100)}encodePanSpread(e){return Math.round(Math.max(0,Math.min(1,e))*255)}encodePosition(e){return Math.round(Math.max(0,Math.min(65535,e)))}encodeFilterFreq(e){return e<=0?0:Math.round(Math.max(1,Math.min(255,e/100)))}encodeReverb(e){return Math.round(Math.max(0,Math.min(1,e))*255)}};y(cr,"AudioOrderCollector");var Ie=cr;var lr=class lr{collectFromUser(e){let t=[];if(e.hasMobileVibrationCommands()){let r=e.flushMobileVibrationCommands();for(let n of r){let o=this.convertMobileCommand(n);o&&t.push(o)}}if(e.hasGamepadVibrationCommands()){let r=e.flushGamepadVibrationCommands();for(let n of r){let o=this.convertGamepadCommand(n);o&&t.push(o)}}return t}convertMobileCommand(e){return"cancel"in e&&e.cancel===!0?this.convertMobileCancelCommand():"pattern"in e?this.convertMobileVibrateCommand(e):null}convertMobileVibrateCommand(e){let t=0;e.intensity!==void 0&&e.intensity!==1&&(t|=1);let r=e.pattern,n=Array.isArray(r)?[...r]:[r],o={type:1,flags:t,pattern:n.map(i=>Math.round(i))};return t&1&&(o.intensity=Math.round(Math.min(1,Math.max(0,e.intensity))*255)/255),o}convertMobileCancelCommand(){return{type:2}}convertGamepadCommand(e){if("cancel"in e&&e.cancel===!0){let t=e.gamepadIndex??"all";return this.convertGamepadCancelCommand({gamepadIndex:t})}if("options"in e&&e.options){let t=e.gamepadIndex??0;return this.convertGamepadVibrateCommand({gamepadIndex:t,options:e.options})}return null}convertGamepadVibrateCommand(e){let{gamepadIndex:t,options:r}=e,n=0;r.startDelay!==void 0&&r.startDelay>0&&(n|=1);let o=t==="all"?255:t;t==="all"&&(n|=2);let i={type:16,flags:n,gamepadIndex:o,duration:Math.round(r.duration),strongMagnitude:Math.round(Math.min(1,Math.max(0,r.strongMagnitude??1))*255),weakMagnitude:Math.round(Math.min(1,Math.max(0,r.weakMagnitude??.5))*255)};return r.startDelay!==void 0&&r.startDelay>0&&(i.startDelay=Math.round(r.startDelay)),i}convertGamepadCancelCommand(e){let{gamepadIndex:t}=e,r=0,n=t==="all"?255:t;return t==="all"&&(r|=2),{type:17,flags:r,gamepadIndex:n}}};y(lr,"VibrationOrderCollector");var Oe=lr;import{POST_PROCESS_DEFAULTS as N,GRID_DEFAULTS as kn,scalingModeToValue as co}from"@utsp/types";var ur=class ur{collectFromUser(e){let t=e.flushPostProcessCommands();return this.convertCommands(t)}convertCommands(e){let t=[];for(let r of e){let n=this.convertCommand(r);n&&t.push(n)}return t}convertCommand(e){let t=e.displayId;switch(e.type){case"set-config":return this.convertSetConfig(e);case"set-scanlines-enabled":return this.createSetScanlinesOrder(t,e.enabled??!1,e.opacity);case"set-scanlines-opacity":return this.createSetScanlinesOrder(t,!0,e.opacity??N.scanlines.opacity);case"set-ambient-effect-enabled":return this.createSetAmbientEffectOrder(t,e.enabled??!1);case"set-ambient-effect-blur":return this.createSetAmbientEffectOrder(t,!0,e.blur);case"set-ambient-effect-scale":return this.createSetAmbientEffectOrder(t,!0,void 0,e.scale);case"set-scaling-mode":return this.createSetScalingModeOrder(t,e.scalingMode);case"set-grid":return this.createSetGridOrder(t,e.gridConfig);case"switch-palette":return this.createSwitchPaletteOrder(t,e.paletteSlotId);case"set-cell-size":return this.createSetCellSizeOrder(t,e.cellWidth,e.cellHeight);default:return console.warn(`[PostProcessOrderCollector] Unknown command type: ${e.type}`),null}}convertSetConfig(e){let t=e.displayId;if(!e.config)return{type:1,displayId:t,flags:3,scanlines:{enabled:!1,opacity:0,pattern:0,colorR:0,colorG:0,colorB:0},ambientEffect:{enabled:!1,blur:0,scale:1,opacity:0}};let r=0,n={type:1,displayId:t,flags:0};if(e.config.scanlines){r|=1;let o=e.config.scanlines;n.scanlines={enabled:o.enabled,opacity:o.opacity??N.scanlines.opacity,pattern:this.patternToType(o.pattern??"horizontal"),colorR:o.color?.r??0,colorG:o.color?.g??0,colorB:o.color?.b??0}}if(e.config.ambientEffect){r|=2;let o=e.config.ambientEffect;n.ambientEffect={enabled:o.enabled,blur:o.blur??N.ambientEffect.blur,scale:o.scale??N.ambientEffect.scale,opacity:o.opacity??N.ambientEffect.opacity}}return n.flags=r,n}createSetScanlinesOrder(e,t,r){return{type:2,displayId:e,enabled:t,opacity:r??N.scanlines.opacity,pattern:0,colorR:0,colorG:0,colorB:0}}createSetAmbientEffectOrder(e,t,r,n){return{type:3,displayId:e,enabled:t,blur:r??N.ambientEffect.blur,scale:n??N.ambientEffect.scale,opacity:N.ambientEffect.opacity}}patternToType(e){switch(e){case"horizontal":return 0;case"vertical":return 1;case"grid":return 2;default:return 0}}createSetScalingModeOrder(e,t){return{type:4,displayId:e,mode:co(t)}}createSetGridOrder(e,t){let{r,g:n,b:o,a:i}=this.parseColor(t.color??kn.color);return{type:5,displayId:e,enabled:t.enabled,colorR:r,colorG:n,colorB:o,colorA:i,lineWidth:t.lineWidth??kn.lineWidth}}createSwitchPaletteOrder(e,t){return{type:6,displayId:e,slotId:t}}createSetCellSizeOrder(e,t,r){return{type:7,displayId:e,cellWidth:t,cellHeight:r}}parseColor(e){let t=e.match(/rgba?\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*([\d.]+))?\s*\)/);if(t)return{r:parseInt(t[1],10),g:parseInt(t[2],10),b:parseInt(t[3],10),a:t[4]?Math.round(parseFloat(t[4])*255):255};let r=e.match(/^#([0-9a-fA-F]{6}|[0-9a-fA-F]{3})$/);if(r){let n=r[1];return n.length===3?{r:parseInt(n[0]+n[0],16),g:parseInt(n[1]+n[1],16),b:parseInt(n[2]+n[2],16),a:255}:{r:parseInt(n.slice(0,2),16),g:parseInt(n.slice(2,4),16),b:parseInt(n.slice(4,6),16),a:255}}return{r:144,g:24,b:24,a:255}}};y(ur,"PostProcessOrderCollector");var we=ur;var Z=class Z{constructor(e={}){b(this,"users",new Map);b(this,"mode");b(this,"maxUsers");b(this,"strictMode");b(this,"currentTick",0);b(this,"encoder");b(this,"displayRasterizer");b(this,"colorPalette",new Map);b(this,"stats",new be);b(this,"spriteRegistry",new ge);b(this,"webFontRegistry",new Ce);b(this,"bitmapFontRegistry",new xe);b(this,"imageFontRegistry",new fe);b(this,"soundRegistry",new Se);b(this,"audioOrderCollector");b(this,"vibrationOrderCollector");b(this,"postProcessOrderCollector");b(this,"activeWebFontId",0);b(this,"_renderCallCount",0);b(this,"paletteSlots",new Map);b(this,"onPaletteChangedCallback");b(this,"onBitmapFontChangedCallback");b(this,"onImageFontChangedCallback");this.mode=e.mode??"server",this.maxUsers=e.maxUsers??64,this.strictMode=e.strictMode??!1,this.encoder=new We,this.displayRasterizer=new je(this),this.audioOrderCollector=new Ie(this.soundRegistry),this.vibrationOrderCollector=new Oe,this.postProcessOrderCollector=new we,this.initializeDefaultPalette(),this.displayRasterizer.rebuildColorCache(),this.loadDefaultWebFont()}initializeDefaultPalette(){Z.ANSI_VGA_COLORS.forEach(e=>{this.colorPalette.set(e.colorId,{r:e.r,g:e.g,b:e.b,a:e.a,e:e.e})}),this.colorPalette.set(255,{r:0,g:0,b:0,a:0,e:0})}getMode(){return this.mode}getMaxUsers(){return this.maxUsers}isStrictMode(){return this.strictMode}isServer(){return this.mode==="server"}isClient(){return this.mode==="client"}isStandalone(){return this.mode==="standalone"}createUser(e,t){if(this.users.has(e))throw new Error(`User with ID ${e} already exists`);if(this.mode==="server"&&this.users.size>=this.maxUsers)throw new Error(`Maximum number of users reached (${this.maxUsers}). Cannot create user ${e}`);if(this.mode==="client"&&this.users.size>=1)throw new Error(`Client mode only allows one user. Cannot create user ${e}`);let r=new me(e,t,this.mode);return r.setSpriteRegistry(this.spriteRegistry),this.users.set(e,r),r}getUser(e){return this.users.get(e)??null}getUsers(){return Array.from(this.users.values())}hasUser(e){return this.users.has(e)}removeUser(e){return this.users.delete(e)}getUserCount(){return this.users.size}clearAllUsers(){this.users.clear()}setColor(e,t,r,n,o=255,i=0){if(e<0||e>255)throw new Error(`Color ID must be between 0 and 255, got ${e}`);if(e>=240)throw new Error("Color IDs 240-255 are reserved (240-254: UI palette, 255: skip color). Use IDs 0-239 for custom colors.");if(t<0||t>255||r<0||r>255||n<0||n>255||o<0||o>255||i<0||i>255)throw new Error("Color components must be between 0 and 255");this.colorPalette.set(e,{r:t,g:r,b:n,a:o,e:i}),this.onPaletteChangedCallback&&this.onPaletteChangedCallback(this.colorPalette)}onPaletteChanged(e){this.onPaletteChangedCallback=e}onBitmapFontChanged(e){this.onBitmapFontChangedCallback=e}getColor(e){return this.colorPalette.get(e)??null}loadPalette(e){for(let t of e)t.colorId<0||t.colorId>255||this.colorPalette.set(t.colorId,{r:t.r,g:t.g,b:t.b,a:t.a,e:t.e??0});Z.ANSI_VGA_COLORS.forEach(t=>{this.colorPalette.set(t.colorId,{r:t.r,g:t.g,b:t.b,a:t.a,e:t.e})}),this.colorPalette.set(255,{r:0,g:0,b:0,a:0,e:0}),this.displayRasterizer.rebuildColorCache(),this.onPaletteChangedCallback&&this.onPaletteChangedCallback(this.colorPalette)}getPalette(){return new Map(this.colorPalette)}resetPalette(){this.colorPalette.clear(),this.initializeDefaultPalette(),this.onPaletteChangedCallback&&this.onPaletteChangedCallback(this.colorPalette)}loadPaletteToSlot(e,t){if(e<0||e>255)throw new Error(`Palette slot ID must be between 0 and 255, got ${e}`);let r=new Map;for(let n of t)n.colorId<0||n.colorId>255||r.set(n.colorId,{r:n.r,g:n.g,b:n.b,a:n.a,e:n.e??0});Z.ANSI_VGA_COLORS.forEach(n=>{r.set(n.colorId,{r:n.r,g:n.g,b:n.b,a:n.a,e:n.e})}),r.set(255,{r:0,g:0,b:0,a:0,e:0}),this.paletteSlots.set(e,r)}getPaletteFromSlot(e){return this.paletteSlots.get(e)??null}hasPaletteSlot(e){return this.paletteSlots.has(e)}clearPaletteSlot(e){this.paletteSlots.delete(e)}clearAllPaletteSlots(){this.paletteSlots.clear()}getColorCSS(e){let t=this.getColor(e);if(!t)return null;let r=t.a/255;return`rgba(${t.r}, ${t.g}, ${t.b}, ${r})`}getUserIds(){return Array.from(this.users.keys())}forEachUser(e){this.users.forEach(e)}filterUsers(e){return this.getUsers().filter(e)}findUser(e){return this.getUsers().find(e)}getCurrentTick(){return this.currentTick}getStats(){return this.stats}endTick(){this.stats.isEnabled()&&this.stats.startTick(this.currentTick);let e=new Map,t=0,r=0;return this.users.forEach((n,o)=>{let i=n.getLayers(),a=n.getDisplays();t+=i.length,n.getStats().isEnabled()&&n.getStats().startTick(this.currentTick);let s=a.map(x=>{let O=x.getOrigin(),I=x.getSize();return{id:x.getId(),originX:O.x,originY:O.y,sizeX:I.x,sizeY:I.y}});a.forEach(x=>x.resetChangeTracking());let d=[],c=[];i.forEach((x,O)=>{let I=x.getOrigin(),w=x.getOrders(),U=x.getStatic(),P=x.calculateUpdateFlags();x.resetChangeTracking(),x.getId()===0&&x.setId(O);let E={id:x.getId(),updateFlags:P,zIndex:x.getZOrder(),originX:I.x,originY:I.y,width:x.getWidth(),height:x.getHeight(),orderCount:w.length,orders:w};U?d.push(E):c.push(E)}),r+=d.length+c.length;let l=this.audioOrderCollector.collectFromUser(n),u=this.vibrationOrderCollector.collectFromUser(n),p=n.flushMacroOrders(),m=this.postProcessOrderCollector.collectFromUser(n),g=[...d,...c],C=this.encoder.encode({tick:this.currentTick,displayCount:s.length,displays:s,layerCount:g.length,layers:g,audioOrderCount:l.length,audioOrders:l,vibrationOrderCount:u.length,vibrationOrders:u,macroOrderCount:p.length,macroOrders:p,postProcessOrderCount:m.length,postProcessOrders:m});if(e.set(o,C),this.stats.isEnabled()){g.forEach((w,U)=>{this.stats.recordLayerOrders(U,w.orders)}),a.forEach((w,U)=>{this.stats.recordDisplayLayers(U,g.length)});let x=a.length*12,O=g.length*20,I=C.length-x-O;this.stats.recordUpdatePacketSize(C.length,x,O,I>0?I:0)}n.endTickBytes()}),this.stats.isEnabled()&&(this.stats.recordLayers(t,r),this.stats.endTick()),this.currentTick++,e}endTickSplit(){this.stats.isEnabled()&&this.stats.startTick(this.currentTick);let e=new Map,t=0,r=0;return this.users.forEach((n,o)=>{let i=n.getLayers(),a=n.getDisplays();t+=i.length,n.getStats().isEnabled()&&n.getStats().startTick(this.currentTick);let s=a.map(x=>{let O=x.getOrigin(),I=x.getSize();return{id:x.getId(),originX:O.x,originY:O.y,sizeX:I.x,sizeY:I.y}});a.forEach(x=>x.resetChangeTracking());let d=[],c=[];i.forEach((x,O)=>{if(!x.getNeedsCommit())return;let I=x.getOrigin(),w=x.getOrders(),U=x.getStatic(),P=x.calculateUpdateFlags();x.resetChangeTracking(),x.resetCommit(),x.getId()===0&&x.setId(O);let E={id:x.getId(),updateFlags:P,zIndex:x.getZOrder(),originX:I.x,originY:I.y,width:x.getWidth(),height:x.getHeight(),orderCount:w.length,orders:w};w.length>0&&this.stats.isEnabled()&&this.stats.recordLayerInfo(x.getId(),U,w.length,P),U?d.push(E):c.push(E)}),r+=d.length+c.length;let l=this.audioOrderCollector.collectFromUser(n),u=this.vibrationOrderCollector.collectFromUser(n),p=this.postProcessOrderCollector.collectFromUser(n),m=n.flushMacroOrders(),g=null,C=null;if(this.stats.isEnabled()&&this.stats.recordPacketSplit(o,s.length,d.length,c.length),d.length>0&&(g=this.encoder.encode({tick:this.currentTick,displayCount:s.length,displays:s,layerCount:d.length,layers:d,audioOrderCount:0,audioOrders:[],vibrationOrderCount:0,vibrationOrders:[],macroOrderCount:0,macroOrders:[],postProcessOrderCount:0,postProcessOrders:[]})),C=this.encoder.encode({tick:this.currentTick,displayCount:s.length,displays:s,layerCount:c.length,layers:c,audioOrderCount:l.length,audioOrders:l,vibrationOrderCount:u.length,vibrationOrders:u,macroOrderCount:m.length,macroOrders:m,postProcessOrderCount:p.length,postProcessOrders:p}),e.set(o,{static:g,dynamic:C}),n.getStats().isEnabled()){let x=a.reduce((U,P)=>{let E=P.getSize();return U+E.x*E.y},0);n.getStats().recordDisplays(a.length,x),n.getStats().recordLayers(i.length,d.length+c.length,d.length,c.length),[...d,...c].forEach(U=>{n.getStats().recordLayerOrders(U.id,U.orders.length)});let O=g?.length||0,I=C?.length||0;n.getStats().recordPacketSizes(O,I);let w=n.getInputBindingRegistry();n.getStats().recordInput(!1,w.getAxisCount(),w.getButtonCount()),n.getStats().endTick()}if(n.endTickBytes(),this.stats.isEnabled()){let x=[...d,...c];x.forEach((P,E)=>{this.stats.recordLayerOrders(E,P.orders)}),a.forEach((P,E)=>{this.stats.recordDisplayLayers(E,x.length)});let O=(g?.length||0)+(C?.length||0),I=a.length*12,w=x.length*20,U=O-I-w;this.stats.recordUpdatePacketSize(O,I,w,U>0?U:0)}}),this.stats.isEnabled()&&(this.stats.recordLayers(t,r),this.stats.endTick()),this.currentTick++,e}getSnapshot(e){let t=this.getUser(e);if(!t)return null;let r=t.getDisplays(),n=t.getLayers(),o=r.map((a,s)=>{let d=a.getOrigin(),c=a.getSize();return{id:s,originX:d.x,originY:d.y,sizeX:c.x,sizeY:c.y}}),i=n.map((a,s)=>{let d=a.getOrigin(),c=a.getOrders(),l=7;return a.getId()===0&&a.setId(s),{id:a.getId(),updateFlags:l,zIndex:a.getZOrder(),originX:d.x,originY:d.y,width:a.getWidth(),height:a.getHeight(),is16bit:a.getCharCodeMode()==="16bit",orderCount:c.length,orders:c}});return this.encoder.encode({tick:this.currentTick,displayCount:o.length,displays:o,layerCount:i.length,layers:i,audioOrderCount:0,audioOrders:[],vibrationOrderCount:0,vibrationOrders:[],macroOrderCount:0,macroOrders:[],postProcessOrderCount:0,postProcessOrders:[]})}resetTick(){this.currentTick=0}applyUpdatePacket(e,t){let r=this.getUser(e);if(!r){if(this.strictMode)throw new Error(`Cannot apply update packet: user ${e} does not exist`);return!1}return r.applyUpdate(t),t.audioOrders&&t.audioOrders.length>0&&r.applyAudioOrders(t.audioOrders),t.vibrationOrders&&t.vibrationOrders.length>0&&r.applyVibrationOrders(t.vibrationOrders),!0}applyUpdatePacketBuffer(e,t){let{UpdatePacketDecoder:r}=(Or(),re(Fn)),o=new r().decode(t);return this.applyUpdatePacket(e,o)?o:null}applyLoadPacket(e){try{let n=new Ze().decode(e).load;switch(n.loadType){case 1:n.slotId!==void 0?this.loadPaletteToSlot(n.slotId,n.colors):this.loadPalette(n.colors);break;case 2:this.loadUnicolorSprites(n);break;case 3:this.loadMulticolorSprites(n);break;case 4:{let o=this.getBitmapFontRegistry();o.hasFont(n.fontId)&&o.unloadFont(n.fontId),o.loadFont(n.fontId,{charWidth:n.width,charHeight:n.height,cellWidth:n.cellWidth,cellHeight:n.cellHeight,glyphs:new Map(n.characters.map(i=>[i.charCode,i.bitmap]))});break}case 6:{let o=this.getWebFontRegistry();o.hasFont(n.fontId)&&o.unloadFont(n.fontId),this.loadWebFontById(n.fontId,{fontFamily:n.fontFamily,fontSize:n.fontSize,offsetX:n.offsetX,offsetY:n.offsetY,charSpacing:n.charSpacing,lineHeight:n.lineHeight,fontWeight:n.fontWeight,fontStyle:n.fontStyle});break}case 5:console.warn("[Core] Sound loading not yet implemented");break;case 7:{for(let o of this.users.values())o.loadMacroTemplate(n.macroId,n.template);break}default:return console.error(`[Core] Unknown LoadType: ${n.loadType}`),!1}return!0}catch(t){return console.error("[Core] Failed to apply LoadPacket:",t),!1}}generatePaletteLoadPacket(){let e=this.getPalette();if(e.size===0)return null;let t=new _,r=[];return e.forEach((n,o)=>{o!==255&&r.push({colorId:o,r:n.r,g:n.g,b:n.b,a:n.a,e:n.e})}),t.encode({loadType:1,colors:r})}generatePaletteSlotLoadPacket(e){let t=this.getPaletteFromSlot(e);if(!t||t.size===0)return null;let r=new _,n=[];return t.forEach((o,i)=>{i!==255&&n.push({colorId:i,r:o.r,g:o.g,b:o.b,a:o.a,e:o.e})}),r.encode({loadType:1,slotId:e,colors:n})}generateAllPaletteSlotLoadPackets(){let e=[];return this.paletteSlots.forEach((t,r)=>{let n=this.generatePaletteSlotLoadPacket(r);n&&e.push(n)}),e}generateUnicolorSpritesLoadPacket(){let e=this.getSpriteRegistry(),t=[];for(let n=0;n<=255;n++){let o=e.getUnicolorSprite(n);if(o){let i=[];for(let a=0;a<o.sizeX*o.sizeY;a++)i.push(o.data.get(a));t.push({spriteId:o.id,sizeX:o.sizeX,sizeY:o.sizeY,data:i})}}return t.length===0?null:new _().encode({loadType:2,sprites:t})}generateMulticolorSpritesLoadPacket(){let e=this.getSpriteRegistry(),t=[];for(let n=0;n<=255;n++){let o=e.getMulticolorSprite(n);if(o){let i=[];for(let a=0;a<o.sizeX*o.sizeY;a++){let s=o.data.get(a);i.push({charCode:s.charCode,fgColorId:s.fgColorCode,bgColorId:s.bgColorCode})}t.push({spriteId:o.id,sizeX:o.sizeX,sizeY:o.sizeY,data:i})}}return t.length===0?null:new _().encode({loadType:3,sprites:t})}generateWebFontsLoadPackets(){let e=this.getWebFontRegistry(),t=e.getFontIds(),r=[],n=new _;for(let o of t){let i=e.getFont(o);if(i){let a=i.getConfig(),s=n.encode({loadType:6,fontId:o,fontFamily:a.fontFamily,fontSize:a.fontSize,offsetX:a.offsetX,offsetY:a.offsetY,charSpacing:a.charSpacing,lineHeight:a.lineHeight,fontWeight:a.fontWeight,fontStyle:a.fontStyle});r.push(s)}}return r}generateBitmapFontsLoadPackets(){let e=this.getBitmapFontRegistry(),t=e.getFontIds(),r=[],n=new _;for(let o of t){let i=e.getFont(o);if(i){let a=[];for(let s=0;s<256;s++){let d=i.getGlyph(s);d&&a.push({charCode:s,bitmap:d})}if(a.length>0){let s=n.encode({loadType:4,fontId:o,width:i.getCharWidth(),height:i.getCharHeight(),cellWidth:i.getCellWidth(),cellHeight:i.getCellHeight(),characters:a});r.push(s)}}}return r}generateAllLoadPackets(){let e=[],t=this.generatePaletteLoadPacket();t&&e.push(t);let r=this.generateAllPaletteSlotLoadPackets();e.push(...r);let n=this.generateUnicolorSpritesLoadPacket();n&&e.push(n);let o=this.generateMulticolorSpritesLoadPacket();o&&e.push(o);let i=this.generateWebFontsLoadPackets();e.push(...i);let a=this.generateBitmapFontsLoadPackets();return e.push(...a),e}generateMacroLoadPackets(e){let t=this.getUser(e);if(!t)return[];let r=t.getMacroLoads();if(r.length===0)return[];let n=new Ge;return r.map(o=>n.encode(o))}applyInputBindingsLoadPacket(e,t){let r=this.getUser(e);if(!r){if(this.strictMode)throw new Error(`Cannot apply input bindings: user ${e} does not exist`);return!1}try{return r.applyInputBindingsLoadPacket(t),!0}catch(n){return console.error(`[Core] Failed to apply input bindings for user ${e}:`,n),!1}}getRenderState(e){let t=this.getUser(e);if(!t)return null;let r=t.getDisplays(),n=t.getLayers(),o=performance.now(),i=new Array(r.length);for(let s=0;s<r.length;s++){let d=r[s],c=d.getOrigin(),l=d.getSize();i[s]=this.displayRasterizer.rasterize({x:c.x,y:c.y,width:l.x,height:l.y},n)}let a=performance.now()-o;return this._renderCallCount||(this._renderCallCount=0),this._renderCallCount++,{userId:t.id,userName:t.name,tick:this.currentTick,displays:i}}getAllRenderStates(){let e=new Map;return this.users.forEach((t,r)=>{let n=this.getRenderState(r);n&&e.set(r,n)}),e}enableStats(e){this.stats.setEnabled(e)}getStatsInstance(){return this.stats}resetStats(){this.stats.reset()}loadUnicolorSprites(e){this.spriteRegistry.loadUnicolorSprites(e)}loadMulticolorSprites(e){this.spriteRegistry.loadMulticolorSprites(e)}unloadUnicolorSprite(e){return this.spriteRegistry.unloadUnicolorSprite(e)}unloadMulticolorSprite(e){return this.spriteRegistry.unloadMulticolorSprite(e)}clearUnicolorSprites(){this.spriteRegistry.clearUnicolorSprites()}clearMulticolorSprites(){this.spriteRegistry.clearMulticolorSprites()}clearAllSprites(){this.spriteRegistry.clearAll()}getUnicolorSpriteCount(){return this.spriteRegistry.getUnicolorSpriteCount()}getMulticolorSpriteCount(){return this.spriteRegistry.getMulticolorSpriteCount()}getTotalSpriteCount(){return this.spriteRegistry.getTotalSpriteCount()}hasUnicolorSprite(e){return this.spriteRegistry.hasUnicolorSprite(e)}hasMulticolorSprite(e){return this.spriteRegistry.hasMulticolorSprite(e)}getSpriteRegistry(){return this.spriteRegistry}getSoundRegistry(){return this.soundRegistry}async loadSound(e,t){let r=this.detectSoundFormat(t),n=await this.loadSoundData(t);return this.soundRegistry.registerFile(e,r,n)}async loadSounds(e){let t={},n=Object.entries(e).map(async([o,i])=>{let a=await this.loadSound(o,i);t[o]=a});return await Promise.all(n),t}detectSoundFormat(e){let t=e.split(".").pop()?.toLowerCase()??"",r={mp3:"mp3",wav:"wav",ogg:"ogg",webm:"webm",aac:"aac",m4a:"aac"},n=r[t];if(!n)throw new Error(`Unsupported audio format: .${t}. Supported: ${Object.keys(r).join(", ")}`);return n}async loadSoundData(e){let t=globalThis;if(typeof t.document<"u"||typeof t.window<"u"||typeof t.fetch=="function")try{let n=await fetch(e);if(!n.ok)throw new Error(`HTTP ${n.status}: ${n.statusText}`);let o=await n.arrayBuffer();return new Uint8Array(o)}catch(n){let o=n instanceof Error?n.message:String(n);throw new Error(`Failed to load sound "${e}": ${o}`)}else{let n=typeof ee<"u"?ee:null;if(!n)throw new Error("Node.js require is not available");let a=n("fs").readFileSync(e);return new Uint8Array(a)}}registerSound(e,t,r){return this.soundRegistry.registerFile(e,t,r)}registerExternalSound(e,t,r,n){return this.soundRegistry.registerExternal(e,t,r,n)}hasSound(e){return this.soundRegistry.has(e)}generateSoundLoadPackets(){return this.soundRegistry.toLoadPackets()}loadDefaultWebFont(){this.webFontRegistry.loadFont(0,{fontFamily:"Courier New",fontSize:16,offsetX:0,offsetY:0,charSpacing:0,lineHeight:1,fontWeight:"normal",fontStyle:"normal"}),this.activeWebFontId=0}loadWebFont(e){let t=e.getFontId(),r=e.getConfig();this.webFontRegistry.loadFont(t,r)}getWebFont(e){return this.webFontRegistry.getFont(e)??null}hasWebFont(e){return this.webFontRegistry.hasFont(e)}unloadWebFont(e){if(e===0)throw new Error("Cannot unload default font (fontId 0)");return this.webFontRegistry.unloadFont(e)}clearWebFonts(){this.webFontRegistry.clearFonts(),this.loadDefaultWebFont()}setActiveWebFont(e){if(!this.webFontRegistry.hasFont(e))throw new Error(`WebFont with ID ${e} does not exist`);this.activeWebFontId=e}getActiveWebFontId(){return this.activeWebFontId}getActiveWebFont(){let e=this.webFontRegistry.getFont(this.activeWebFontId);if(!e)throw new Error(`Active WebFont ${this.activeWebFontId} not found. This should not happen.`);return e}getWebFontCount(){return this.webFontRegistry.getFontCount()}getWebFontIds(){return this.webFontRegistry.getFontIds()}getWebFontRegistry(){return this.webFontRegistry}getBitmapFontRegistry(){return this.bitmapFontRegistry}loadWebFontById(e,t){let r=new $(e,t);this.loadWebFont(r)}loadBitmapFontById(e,t){this.bitmapFontRegistry.loadFont(e,t),this.onBitmapFontChangedCallback&&this.onBitmapFontChangedCallback(e)}getBitmapFont(e){return this.bitmapFontRegistry.getFont(e)??null}hasBitmapFont(e){return this.bitmapFontRegistry.hasFont(e)}unloadBitmapFont(e){return this.bitmapFontRegistry.unloadFont(e)}clearBitmapFonts(){this.bitmapFontRegistry.clearFonts()}getBitmapFontCount(){return this.bitmapFontRegistry.getFontCount()}getBitmapFontIds(){return this.bitmapFontRegistry.getFontIds()}async loadImageFont(e,t,r){let n=await this.loadImageData(t),o=this.imageFontRegistry.registerFont(e,r,n);return this.onImageFontChangedCallback&&this.onImageFontChangedCallback(o),o}async loadImageFonts(e){let t={},n=Object.entries(e).map(async([o,{path:i,options:a}])=>{let s=await this.loadImageFont(o,i,a);t[o]=s});return await Promise.all(n),t}async loadImageData(e){let t=globalThis;if(typeof t.document<"u"||typeof t.window<"u"||typeof t.fetch=="function")try{let n=await fetch(e);if(!n.ok)throw new Error(`HTTP ${n.status}: ${n.statusText}`);let o=await n.arrayBuffer();return new Uint8Array(o)}catch(n){let o=n instanceof Error?n.message:String(n);throw new Error(`Failed to load image font "${e}": ${o}`)}else{let n=typeof ee<"u"?ee:null;if(!n)throw new Error("Node.js require is not available");let a=n("fs").readFileSync(e);return new Uint8Array(a)}}getImageFontId(e){return this.imageFontRegistry.getFontId(e)}getImageFontByName(e){return this.imageFontRegistry.getFontByName(e)??null}onImageFontChanged(e){this.onImageFontChangedCallback=e}getImageFontRegistry(){return this.imageFontRegistry}loadImageFontById(e,t){this.imageFontRegistry.loadFont(e,t),this.onImageFontChangedCallback&&this.onImageFontChangedCallback(e)}getImageFont(e){return this.imageFontRegistry.getFont(e)??null}hasImageFont(e){return this.imageFontRegistry.hasFont(e)}hasImageFontByName(e){return this.imageFontRegistry.hasFontByName(e)}unloadImageFont(e){return this.imageFontRegistry.unloadFont(e)}unloadImageFontByName(e){return this.imageFontRegistry.unloadFontByName(e)}clearImageFonts(){this.imageFontRegistry.clearFonts()}getImageFontCount(){return this.imageFontRegistry.getFontCount()}getImageFontIds(){return this.imageFontRegistry.getFontIds()}getImageFontNames(){return this.imageFontRegistry.getFontNames()}};y(Z,"Core"),b(Z,"ANSI_VGA_COLORS",[{colorId:240,r:16,g:16,b:16,a:255,e:0},{colorId:241,r:128,g:128,b:128,a:255,e:0},{colorId:242,r:192,g:192,b:192,a:255,e:0},{colorId:243,r:240,g:240,b:240,a:255,e:0},{colorId:244,r:200,g:50,b:50,a:255,e:0},{colorId:245,r:50,g:200,b:50,a:255,e:0},{colorId:246,r:220,g:180,b:50,a:255,e:0},{colorId:247,r:50,g:100,b:220,a:255,e:0},{colorId:248,r:50,g:200,b:200,a:255,e:0},{colorId:249,r:200,g:50,b:200,a:255,e:0},{colorId:250,r:220,g:120,b:50,a:255,e:0},{colorId:251,r:120,g:220,b:120,a:255,e:0},{colorId:252,r:120,g:180,b:220,a:255,e:0},{colorId:253,r:220,g:150,b:200,a:255,e:0},{colorId:254,r:250,g:220,b:150,a:255,e:0}]);var wr=Z;import{Vector2 as Ud}from"@utsp/types";var K=new Map([[24,new Uint8Array([0,24,60,126,255,255,0,0])],[25,new Uint8Array([0,0,255,255,126,60,24,0])],[26,new Uint8Array([0,48,120,252,252,120,48,0])],[27,new Uint8Array([0,12,30,63,63,30,12,0])],[32,new Uint8Array([0,0,0,0,0,0,0,0])],[33,new Uint8Array([24,24,24,24,24,0,24,0])],[34,new Uint8Array([108,108,108,0,0,0,0,0])],[35,new Uint8Array([54,54,127,54,127,54,54,0])],[36,new Uint8Array([12,63,104,62,11,126,24,0])],[37,new Uint8Array([96,102,12,24,48,102,6,0])],[38,new Uint8Array([56,108,108,56,109,102,59,0])],[39,new Uint8Array([24,24,24,0,0,0,0,0])],[40,new Uint8Array([12,24,48,48,48,24,12,0])],[41,new Uint8Array([48,24,12,12,12,24,48,0])],[42,new Uint8Array([0,102,60,255,60,102,0,0])],[43,new Uint8Array([0,24,24,126,24,24,0,0])],[44,new Uint8Array([0,0,0,0,0,24,24,48])],[45,new Uint8Array([0,0,0,126,0,0,0,0])],[46,new Uint8Array([0,0,0,0,0,24,24,0])],[47,new Uint8Array([0,6,12,24,48,96,0,0])],[48,new Uint8Array([60,102,110,126,118,102,60,0])],[49,new Uint8Array([24,56,24,24,24,24,126,0])],[50,new Uint8Array([60,102,6,12,24,48,126,0])],[51,new Uint8Array([60,102,6,28,6,102,60,0])],[52,new Uint8Array([12,28,60,108,126,12,12,0])],[53,new Uint8Array([126,96,124,6,6,102,60,0])],[54,new Uint8Array([28,48,96,124,102,102,60,0])],[55,new Uint8Array([126,6,12,24,48,48,48,0])],[56,new Uint8Array([60,102,102,60,102,102,60,0])],[57,new Uint8Array([60,102,102,62,6,12,56,0])],[58,new Uint8Array([0,0,24,24,0,24,24,0])],[59,new Uint8Array([0,0,24,24,0,24,24,48])],[60,new Uint8Array([12,24,48,96,48,24,12,0])],[61,new Uint8Array([0,0,126,0,126,0,0,0])],[62,new Uint8Array([48,24,12,6,12,24,48,0])],[63,new Uint8Array([60,102,12,24,24,0,24,0])],[64,new Uint8Array([60,102,110,106,110,96,60,0])],[65,new Uint8Array([60,102,102,126,102,102,102,0])],[66,new Uint8Array([124,102,102,124,102,102,124,0])],[67,new Uint8Array([60,102,96,96,96,102,60,0])],[68,new Uint8Array([120,108,102,102,102,108,120,0])],[69,new Uint8Array([126,96,96,124,96,96,126,0])],[70,new Uint8Array([126,96,96,124,96,96,96,0])],[71,new Uint8Array([60,102,96,110,102,102,60,0])],[72,new Uint8Array([102,102,102,126,102,102,102,0])],[73,new Uint8Array([126,24,24,24,24,24,126,0])],[74,new Uint8Array([62,12,12,12,12,108,56,0])],[75,new Uint8Array([102,108,120,112,120,108,102,0])],[76,new Uint8Array([96,96,96,96,96,96,126,0])],[77,new Uint8Array([99,119,127,107,99,99,99,0])],[78,new Uint8Array([102,102,118,126,110,102,102,0])],[79,new Uint8Array([60,102,102,102,102,102,60,0])],[80,new Uint8Array([124,102,102,124,96,96,96,0])],[81,new Uint8Array([60,102,102,102,106,108,54,0])],[82,new Uint8Array([124,102,102,124,108,102,102,0])],[83,new Uint8Array([60,102,96,60,6,102,60,0])],[84,new Uint8Array([126,24,24,24,24,24,24,0])],[85,new Uint8Array([102,102,102,102,102,102,60,0])],[86,new Uint8Array([102,102,102,102,102,60,24,0])],[87,new Uint8Array([99,99,99,107,127,119,99,0])],[88,new Uint8Array([102,102,60,24,60,102,102,0])],[89,new Uint8Array([102,102,102,60,24,24,24,0])],[90,new Uint8Array([126,6,12,24,48,96,126,0])],[91,new Uint8Array([60,48,48,48,48,48,60,0])],[92,new Uint8Array([0,96,48,24,12,6,0,0])],[93,new Uint8Array([60,12,12,12,12,12,60,0])],[94,new Uint8Array([24,60,102,0,0,0,0,0])],[95,new Uint8Array([0,0,0,0,0,0,255,0])],[96,new Uint8Array([48,24,12,0,0,0,0,0])],[97,new Uint8Array([0,0,60,6,62,102,62,0])],[98,new Uint8Array([96,96,124,102,102,102,124,0])],[99,new Uint8Array([0,0,60,102,96,102,60,0])],[100,new Uint8Array([6,6,62,102,102,102,62,0])],[101,new Uint8Array([0,0,60,102,126,96,60,0])],[102,new Uint8Array([28,54,48,124,48,48,48,0])],[103,new Uint8Array([0,0,62,102,102,62,6,60])],[104,new Uint8Array([96,96,124,102,102,102,102,0])],[105,new Uint8Array([24,0,56,24,24,24,60,0])],[106,new Uint8Array([12,0,28,12,12,12,108,56])],[107,new Uint8Array([96,96,102,108,120,108,102,0])],[108,new Uint8Array([56,24,24,24,24,24,60,0])],[109,new Uint8Array([0,0,102,127,107,107,99,0])],[110,new Uint8Array([0,0,124,102,102,102,102,0])],[111,new Uint8Array([0,0,60,102,102,102,60,0])],[112,new Uint8Array([0,0,124,102,102,124,96,96])],[113,new Uint8Array([0,0,62,102,102,62,6,6])],[114,new Uint8Array([0,0,108,118,96,96,96,0])],[115,new Uint8Array([0,0,62,96,60,6,124,0])],[116,new Uint8Array([48,48,124,48,48,54,28,0])],[117,new Uint8Array([0,0,102,102,102,102,62,0])],[118,new Uint8Array([0,0,102,102,102,60,24,0])],[119,new Uint8Array([0,0,99,107,107,127,54,0])],[120,new Uint8Array([0,0,102,60,24,60,102,0])],[121,new Uint8Array([0,0,102,102,102,62,6,60])],[122,new Uint8Array([0,0,126,12,24,48,126,0])],[123,new Uint8Array([14,24,24,112,24,24,14,0])],[124,new Uint8Array([24,24,24,24,24,24,24,0])],[125,new Uint8Array([112,24,24,14,24,24,112,0])],[126,new Uint8Array([49,107,70,0,0,0,0,0])],[179,new Uint8Array([24,24,24,24,24,24,24,24])],[196,new Uint8Array([0,0,0,255,0,0,0,0])],[218,new Uint8Array([0,0,0,31,24,24,24,24])],[191,new Uint8Array([0,0,0,248,24,24,24,24])],[192,new Uint8Array([24,24,24,31,0,0,0,0])],[217,new Uint8Array([24,24,24,248,0,0,0,0])],[195,new Uint8Array([24,24,24,31,24,24,24,24])],[180,new Uint8Array([24,24,24,248,24,24,24,24])],[194,new Uint8Array([0,0,0,255,24,24,24,24])],[193,new Uint8Array([24,24,24,255,0,0,0,0])],[197,new Uint8Array([24,24,24,255,24,24,24,24])],[186,new Uint8Array([54,54,54,54,54,54,54,54])],[205,new Uint8Array([0,0,0,255,0,255,0,0])],[201,new Uint8Array([0,0,0,63,54,54,54,54])],[187,new Uint8Array([0,0,0,252,54,54,54,54])],[200,new Uint8Array([54,54,54,63,0,0,0,0])],[188,new Uint8Array([54,54,54,252,0,0,0,0])],[204,new Uint8Array([54,54,54,63,54,54,54,54])],[185,new Uint8Array([54,54,54,252,54,54,54,54])],[203,new Uint8Array([0,0,0,255,54,54,54,54])],[202,new Uint8Array([54,54,54,255,0,0,0,0])],[206,new Uint8Array([54,54,54,255,54,54,54,54])],[219,new Uint8Array([255,255,255,255,255,255,255,255])],[178,new Uint8Array([170,85,170,85,170,85,170,85])],[177,new Uint8Array([136,34,136,34,136,34,136,34])],[176,new Uint8Array([34,136,34,136,34,136,34,136])],[223,new Uint8Array([255,255,255,255,0,0,0,0])],[220,new Uint8Array([0,0,0,0,255,255,255,255])],[221,new Uint8Array([240,240,240,240,240,240,240,240])],[222,new Uint8Array([15,15,15,15,15,15,15,15])]]);function uo(h){return K.get(h)}y(uo,"getCharBitmap");function po(h){return K.has(h)}y(po,"hasChar");function mo(){return Array.from(K.keys()).sort((h,e)=>h-e)}y(mo,"getAllCharCodes");function ho(h){let e=Array.from(K.entries()).map(([t,r])=>({charCode:t,bitmap:r}));return{loadType:4,fontId:h,width:8,height:8,cellWidth:8,cellHeight:8,characters:e}}y(ho,"createASCII8x8FontLoad");function bo(){return{charWidth:8,charHeight:8,glyphs:new Map(K)}}y(bo,"getASCII8x8FontConfig");L();var Ur=class Ur{encode(e){switch(e.type){case 1:return this.encodeClick(e);case 2:return this.encodeChange(e);case 3:return this.encodeSubmit(e);case 4:return this.encodeSelect(e);default:throw new Error(`Unknown macro event type: ${e.type}`)}}calculateSize(e){switch(e.type){case 1:return 2;case 2:return this.calculateChangeSize(e);case 3:return this.calculateSubmitSize(e);case 4:return 4;default:throw new Error(`Unknown macro event type: ${e.type}`)}}encodeClick(e){let t=f.allocUnsafe(2);return t.writeUInt8(e.type,0),t.writeUInt8(e.instanceId,1),t.toUint8Array()}encodeChange(e){if(typeof e.value=="boolean"){let r=f.allocUnsafe(4);return r.writeUInt8(e.type,0),r.writeUInt8(e.instanceId,1),r.writeUInt8(1,2),r.writeUInt8(e.value?1:0,3),r.toUint8Array()}else{let r=f.allocUnsafe(7);return r.writeUInt8(e.type,0),r.writeUInt8(e.instanceId,1),r.writeUInt8(0,2),r.writeFloatBE(e.value,3),r.toUint8Array()}}calculateChangeSize(e){return typeof e.value=="boolean"?4:7}encodeSubmit(e){let t=new TextEncoder().encode(e.text);if(t.length>65535)throw new Error(`Submit text too large: ${t.length} bytes (max 65535)`);let r=4+t.length,n=f.allocUnsafe(r),o=0;return n.writeUInt8(e.type,o++),n.writeUInt8(e.instanceId,o++),n.writeUInt16BE(t.length,o),o+=2,n.toUint8Array().set(t,o),n.toUint8Array()}calculateSubmitSize(e){return 4+new TextEncoder().encode(e.text).length}encodeSelect(e){let t=f.allocUnsafe(4);return t.writeUInt8(e.type,0),t.writeUInt8(e.instanceId,1),t.writeUInt16BE(e.index,2),t.toUint8Array()}};y(Ur,"MacroEventEncoder");var tt=Ur;function go(h,e,t,r,n,o,i,a=[],s=[],d=[]){let c=Array.from(e.entries()).sort((k,F)=>k[0]-F[0]),l=Array.from(t.entries()).sort((k,F)=>k[0]-F[0]),u=c.length,p=l.length,m=Mt(u,p),g=new TextEncoder,C=a.map(k=>g.encode(k)),x=1+C.reduce((k,F)=>k+1+F.length,0),O=new tt,I=s.map(k=>O.encode(k)),w=1+I.reduce((k,F)=>k+F.length,0),U=Math.min(d.length,255),P=1+U*5,E=m+x+w+P,v=new Uint8Array(E),S=new DataView(v.buffer),A=0;S.setBigUint64(A,h,!0),A+=8;for(let[,k]of c){let F=Ut(k);v[A]=F+256&255,A+=1}let M=J(p);for(let k=0;k<M;k++){let F=0;for(let Ae=0;Ae<8;Ae++){let Ar=k*8+Ae;if(Ar<p){let[,Dn]=l[Ar];Dn&&(F|=1<<Ae)}}v[A]=F,A+=1}v[A]=r&255,A+=1,v[A]=n&255,A+=1,v[A]=o&255,A+=1;let T=0;i&&(T|=1),v[A]=T,A+=1,v[A]=Math.min(a.length,255),A+=1;for(let k of C)v[A]=Math.min(k.length,255),A+=1,v.set(k.slice(0,255),A),A+=k.length;v[A]=Math.min(s.length,255),A+=1;for(let k of I)v.set(k,A),A+=k.length;v[A]=U,A+=1;for(let k=0;k<U;k++){let F=d[k];v[A]=F.displayId&255,A+=1,S.setUint16(A,Math.min(F.pixelWidth,65535),!1),A+=2,S.setUint16(A,Math.min(F.pixelHeight,65535),!1),A+=2}return v}y(go,"encodeCompressedInput");var R=class R{static toCharCode(e){if(typeof e=="number")return e&65535;let t=e.charCodeAt(0);return ie(t)}static dedent(e){let t=e.split(`
|
|
11
|
+
`}),e+=`Touch Zones (${this.touchZones.size}):
|
|
12
|
+
`,this.touchZones.forEach(t=>{e+=` [${t.zoneId}] ${t.name}: `,e+=`(${t.x}, ${t.y}) ${t.width}x${t.height}
|
|
13
|
+
`}),e}};y(vt,"InputBindingRegistry");var ue=vt;function Ut(h=0n){return{tick:h,axes:new Map,buttons:new Map,displayId:0,mouseX:0,mouseY:0,mouseOverDisplay:!1,textInputs:[],macroEvents:[],displayViewports:[],touchPositions:[]}}y(Ut,"createEmptyCompressedInputPacket");function Mt(h){let e=Math.max(-1,Math.min(1,h));return Math.round(e*127)}y(Mt,"encodeAxisToInt8");function At(h){return h/127}y(At,"decodeInt8ToAxis");function J(h){return h===0?0:Math.ceil(h/8)}y(J,"getButtonByteCount");function Et(h,e){let r=h,n=J(e);return 8+r+n+4}y(Et,"getCompressedPacketSize");var Pt=class Pt{decode(e,t=0){let r=e.readUInt8(t);switch(r){case 1:return this.decodeClick(e,t);case 2:return this.decodeChange(e,t);case 3:return this.decodeSubmit(e,t);case 4:return this.decodeSelect(e,t);default:throw new Error(`Unknown macro event type: 0x${r.toString(16)}`)}}decodeAll(e,t,r){let n=[],o=0;for(let i=0;i<r;i++){let{event:a,bytesRead:s}=this.decode(e,t+o);n.push(a),o+=s}return{events:n,bytesRead:o}}decodeClick(e,t){let r=e.readUInt8(t),n=e.readUInt8(t+1);return{event:{type:r,instanceId:n},bytesRead:2}}decodeChange(e,t){let r=e.readUInt8(t),n=e.readUInt8(t+1),o=e.readUInt8(t+2),i,a;return o===1?(i=e.readUInt8(t+3)===1,a=4):(i=e.readFloatBE(t+3),a=7),{event:{type:r,instanceId:n,value:i},bytesRead:a}}decodeSubmit(e,t){let r=t,n=e.readUInt8(t++),o=e.readUInt8(t++),i=e.readUInt16BE(t);t+=2;let a=e.toUint8Array().subarray(t,t+i);t+=i;let s=new TextDecoder().decode(a);return{event:{type:n,instanceId:o,text:s},bytesRead:t-r}}decodeSelect(e,t){let r=e.readUInt8(t),n=e.readUInt8(t+1),o=e.readUInt16BE(t+2);return{event:{type:r,instanceId:n,index:o},bytesRead:4}}};y(Pt,"MacroEventDecoder");var De=Pt;L();function Rt(h,e){let t=e.getAllAxes().length,r=e.getAllButtons().length,n=J(r),o=8+t+n+4;if(h.length<o)throw new Error(`Invalid compressed input packet: expected at least ${o} bytes (${t} axes + ${r} buttons), got ${h.length}`);let i=new DataView(h.buffer,h.byteOffset,h.byteLength),a=0,s=Ut();s.tick=i.getBigUint64(a,!0),a+=8;for(let c=0;c<t;c++){let l=h[a],u=l>127?l-256:l,p=At(u);s.axes.set(c,p),a+=1}for(let c=0;c<n;c++){let l=h[a];for(let u=0;u<8;u++){let p=c*8+u;if(p<r){let m=(l&1<<u)!==0;s.buttons.set(p,m)}}a+=1}s.displayId=h[a],a+=1,s.mouseX=h[a],a+=1,s.mouseY=h[a],a+=1;let d=h[a];if(s.mouseOverDisplay=(d&1)!==0,a+=1,a<h.length){let c=h[a];a+=1;let l=new TextDecoder;s.textInputs=[];for(let u=0;u<c&&a<h.length;u++){let p=h[a];if(a+=1,a+p<=h.length){let m=h.slice(a,a+p),g=l.decode(m);s.textInputs.push(g),a+=p}}}if(a<h.length){let c=h[a];a+=1;let l=new De,u=[],p=x.from(h);for(let m=0;m<c&&a<h.length;m++){let g=l.decode(p,a);u.push(g.event),a+=g.bytesRead}s.macroEvents=u}if(a<h.length){let c=h[a];a+=1;for(let l=0;l<c&&a+5<=h.length;l++){let u=h[a];a+=1;let p=i.getUint16(a,!1);a+=2;let m=i.getUint16(a,!1);a+=2,s.displayViewports.push({displayId:u,pixelWidth:p,pixelHeight:m})}}if(a<h.length){let c=Math.min(h[a],10);a+=1;for(let l=0;l<c&&a+4<=h.length;l++){let u=h[a]&15;a+=1;let p=h[a];a+=1;let m=h[a];a+=1;let C=(h[a]&1)!==0;a+=1,s.touchPositions.push({id:u,x:p,y:m,over:C})}}return s}y(Rt,"decodeCompressedInput");import{Vector2 as Ve,POST_PROCESS_DEFAULTS as D,GRID_DEFAULTS as He}from"@utsp/types";var kt=class kt{constructor(e,t){b(this,"enabled",!1);b(this,"currentStats",null);b(this,"_userId");b(this,"_userName");this._userId=e,this._userName=t}setEnabled(e){this.enabled=e,e||(this.currentStats=null)}isEnabled(){return this.enabled}get userId(){return this.currentStats?.userId??this._userId}get userName(){return this.currentStats?.userName??this._userName}get tick(){return this.currentStats?.tick??0}get timestamp(){return this.currentStats?.timestamp??0}get displayCount(){return this.currentStats?.displayCount??0}get totalDisplayArea(){return this.currentStats?.totalDisplayArea??0}get totalLayers(){return this.currentStats?.totalLayers??0}get visibleLayers(){return this.currentStats?.visibleLayers??0}get staticLayers(){return this.currentStats?.staticLayers??0}get dynamicLayers(){return this.currentStats?.dynamicLayers??0}get totalOrders(){return this.currentStats?.totalOrders??0}get ordersByLayer(){return this.currentStats?.ordersByLayer??new Map}get staticPacketSize(){return this.currentStats?.staticPacketSize??0}get dynamicPacketSize(){return this.currentStats?.dynamicPacketSize??0}get totalPacketSize(){return this.currentStats?.totalPacketSize??0}get compressedPacketSize(){return Math.round(this.totalPacketSize*.25)}get hasInput(){return this.currentStats?.hasInput??!1}get axisCount(){return this.currentStats?.axisCount??0}get buttonCount(){return this.currentStats?.buttonCount??0}startTick(e){this.enabled&&(this.currentStats={userId:this._userId,userName:this._userName,tick:e,timestamp:Date.now(),displayCount:0,totalDisplayArea:0,totalLayers:0,visibleLayers:0,staticLayers:0,dynamicLayers:0,totalOrders:0,ordersByLayer:new Map,staticPacketSize:0,dynamicPacketSize:0,totalPacketSize:0,hasInput:!1,axisCount:0,buttonCount:0})}recordDisplays(e,t){!this.enabled||!this.currentStats||(this.currentStats.displayCount=e,this.currentStats.totalDisplayArea=t)}recordLayers(e,t,r,n){!this.enabled||!this.currentStats||(this.currentStats.totalLayers=e,this.currentStats.visibleLayers=t,this.currentStats.staticLayers=r,this.currentStats.dynamicLayers=n)}recordLayerOrders(e,t){!this.enabled||!this.currentStats||(this.currentStats.totalOrders+=t,this.currentStats.ordersByLayer.set(e,t))}recordPacketSizes(e,t){!this.enabled||!this.currentStats||(this.currentStats.staticPacketSize=e,this.currentStats.dynamicPacketSize=t,this.currentStats.totalPacketSize=e+t)}recordInput(e,t,r){!this.enabled||!this.currentStats||(this.currentStats.hasInput=e,this.currentStats.axisCount=t,this.currentStats.buttonCount=r)}endTick(){}reset(){this.currentStats=null}};y(kt,"UserStats");var pe=kt;var Yt=class Yt{constructor(e,t,r){this.id=e;this.name=t;b(this,"displays",[]);b(this,"layers",[]);b(this,"spriteRegistry");b(this,"mode");b(this,"axes",new Map);b(this,"buttons",new Map);b(this,"textInputs",[]);b(this,"mouseX",0);b(this,"mouseY",0);b(this,"mouseOver",!1);b(this,"mouseDisplayId",0);b(this,"touchPositions",new Map);b(this,"activeTouchId",null);b(this,"inputBindings",new ue);b(this,"stats");b(this,"soundCommands",[]);b(this,"nextSoundInstanceId",1);b(this,"audioConfigCommands",[]);b(this,"lastListenerX",-1);b(this,"lastListenerY",-1);b(this,"pendingSendSounds",!1);b(this,"audioProcessor");b(this,"loadedSounds",new Map);b(this,"soundLoadErrors",new Map);b(this,"playingSounds",new Map);b(this,"mobileVibrationCommands",[]);b(this,"mobileVibrationProcessor");b(this,"gamepadVibrationCommands",[]);b(this,"gamepadVibrationProcessor");b(this,"macroRegistry",new se);b(this,"macroEngine",new le);b(this,"macroEventHandlers",new Map);b(this,"postProcessCommands",[]);b(this,"currentPostProcessConfig",null);b(this,"bridgeMessages",[]);b(this,"totalBytesSent",0);b(this,"totalBytesReceived",0);b(this,"bytesSentPerTick",[]);b(this,"bytesReceivedPerTick",[]);b(this,"bytesTickIndex",0);b(this,"bytesTickRate",20);b(this,"currentTickBytesSent",0);b(this,"currentTickBytesReceived",0);b(this,"availableViewports",new Map);b(this,"data");b(this,"currentScalingModes",new Map);b(this,"currentCellSizes",new Map);b(this,"currentGridConfigs",new Map);b(this,"currentPaletteSlotIds",new Map);this.mode=r,this.stats=new pe(e,t),this.data={}}setSpriteRegistry(e){this.spriteRegistry=e;for(let t of this.layers)t.setSpriteRegistry(e);this.macroEngine.setSpriteRegistry(e)}getDisplays(){return this.displays}addDisplay(e){this.displays.push(e)}removeDisplay(e){let t=this.displays.indexOf(e);return t!==-1?(this.displays.splice(t,1),!0):!1}clearDisplays(){this.displays=[]}setDisplayViewport(e,t,r){this.availableViewports.set(e,{pixelWidth:t,pixelHeight:r})}getDisplayViewport(e){return this.availableViewports.get(e)??null}getAllDisplayViewports(){return this.availableViewports}calculateMaxCells(e,t,r){let n=this.availableViewports.get(e);return n?{cols:Math.floor(n.pixelWidth/t),rows:Math.floor(n.pixelHeight/r)}:null}getLayers(){return this.layers}getLayerById(e){return this.layers.find(t=>t.getId()===e)}addLayer(e,t){e.setMode(this.mode);let r=this.layers.length+1;e.setId(r),this.layers.push(e),this.spriteRegistry&&e.setSpriteRegistry(this.spriteRegistry),t&&this.macroRegistry.setLayerMapping(t,e.getId())}removeLayer(e){let t=this.layers.indexOf(e);return t!==-1?(this.layers.splice(t,1),!0):!1}clearLayers(){this.layers=[]}setMousePosition(e,t,r=!0){this.mouseX=Math.max(0,Math.min(255,e)),this.mouseY=Math.max(0,Math.min(255,t)),this.mouseOver=r}setTouchPosition(e,t,r,n=!0,o=0){if(e<0||e>9){console.warn(`Invalid touchId ${e}, must be 0-9`);return}n?(this.touchPositions.set(e,{x:Math.max(0,Math.min(255,t)),y:Math.max(0,Math.min(255,r)),over:!0,displayId:o}),this.activeTouchId=e):(this.touchPositions.delete(e),this.activeTouchId===e&&(this.activeTouchId=null))}setAxis(e,t){let r=Math.max(-1,Math.min(1,t));this.axes.set(e,r)}getAxis(e){return this.axes.get(e)??0}setButton(e,t){this.buttons.set(e,t)}getButton(e){return this.buttons.get(e)??!1}getButtonJustPressed(e){let t=`${e}_justPressed`;return this.buttons.get(t)??!1}getButtonJustReleased(e){let t=`${e}_justReleased`;return this.buttons.get(t)??!1}setTextInputs(e){this.textInputs=e}getTextInputs(){return this.textInputs}clearTextInputs(){this.textInputs=[]}getAxisNames(){return Array.from(this.axes.keys())}getButtonNames(){return Array.from(this.buttons.keys())}clearAxes(){this.axes.clear()}clearButtons(){this.buttons.clear()}getMouseDisplayInfo(){if(!this.mouseOver||this.displays.length===0)return null;let e=this.displays[0],t=0,r=this.mouseX,n=this.mouseY,o=e.getOrigin(),i=o.x+r,a=o.y+n;return{displayId:t,localX:r,localY:n,worldX:i,worldY:a}}getTouchDisplayInfo(e=0){if(e<0||e>9)return console.warn(`Invalid touchId ${e}, must be 0-9`),null;let t=this.touchPositions.get(e);if(!t||!t.over||this.displays.length===0)return null;let r=this.displays[0],n=t.displayId,o=t.x,i=t.y,a=r.getOrigin(),s=a.x+o,d=a.y+i;return{displayId:n,localX:o,localY:i,worldX:s,worldY:d}}getIsMouseOnADisplay(){return this.mouseOver}getMouseDisplayHover(){let e=this.getMouseDisplayInfo();return e?e.displayId:null}findLayerById(e){return this.layers.find(t=>t.getId()===e)??null}applyUpdate(e){if(this.updateDisplaysFromPacket(e.displays),this.updateLayersFromPacket(e.layers),e.macroOrders&&e.macroOrders.length>0)for(let t of e.macroOrders)this.macroEngine.applyOrder(t)}updateDisplaysFromPacket(e){for(let t of e){let r=this.displays[t.id];if(!r){for(r=new ne(t.id,t.sizeX,t.sizeY);this.displays.length<=t.id;)this.displays.push(null);this.displays[t.id]=r}r.setOrigin(new Ve(t.originX,t.originY)),r.setSize(new Ve(t.sizeX,t.sizeY))}}updateLayersFromPacket(e){for(let t of e){let r=this.findLayerById(t.id);r||(r=new ae(new Ve(t.originX,t.originY),t.zIndex,t.width,t.height,{isStatic:!1,charCodeMode:t.is16bit?"16bit":"8bit"}),r.setId(t.id),r.setMode(this.mode),this.spriteRegistry&&r.setSpriteRegistry(this.spriteRegistry),this.addLayer(r)),t.updateFlags&1&&r.setOrigin(new Ve(t.originX,t.originY)),t.updateFlags&2&&r.setZOrder(t.zIndex),t.updateFlags&4&&r.setOrders(t.orders)}}defineAxisBinding(e,t,r=[],n=-1,o=1,i=0){this.inputBindings.defineAxis(e,t,r,n,o,i)}defineButtonBinding(e,t,r=[],n=!1){this.inputBindings.defineButton(e,t,r,n)}defineAxisBindings(e){e.forEach(({bindingId:t,name:r,sources:n,min:o,max:i,defaultValue:a})=>{this.defineAxisBinding(t,r,n??[],o,i,a)})}defineButtonBindings(e){e.forEach(({bindingId:t,name:r,sources:n,defaultValue:o})=>{this.defineButtonBinding(t,r,n??[],o)})}getInputBindingsLoadPacket(){return this.inputBindings.toLoadPacket()}applyInputBindingsLoadPacket(e){try{let t=JSON.parse(e);if(t.type!=="input-binding")throw new Error(`Invalid packet type: ${t.type}`);for(let r of t.axes)this.defineAxisBinding(r.bindingId,r.name,r.sources||[],r.min,r.max,r.defaultValue);for(let r of t.buttons)this.defineButtonBinding(r.bindingId,r.name,r.sources||[],r.defaultValue)}catch(t){throw console.error("[User] Failed to apply input bindings:",t),t}}getInputBindingRegistry(){return this.inputBindings}getStats(){return this.stats}getTotalBytesSent(){return this.totalBytesSent}getTotalBytesReceived(){return this.totalBytesReceived}recordBytesSent(e){this.totalBytesSent+=e,this.currentTickBytesSent+=e}recordBytesReceived(e){this.totalBytesReceived+=e,this.currentTickBytesReceived+=e}resetByteCounters(){this.totalBytesSent=0,this.totalBytesReceived=0}setBytesTickRate(e){e<=0||(this.bytesTickRate=e,this.bytesSentPerTick=new Array(e).fill(0),this.bytesReceivedPerTick=new Array(e).fill(0),this.bytesTickIndex=0)}endTickBytes(){this.bytesSentPerTick.length!==this.bytesTickRate&&(this.bytesSentPerTick=new Array(this.bytesTickRate).fill(0),this.bytesReceivedPerTick=new Array(this.bytesTickRate).fill(0)),this.bytesSentPerTick[this.bytesTickIndex]=this.currentTickBytesSent,this.bytesReceivedPerTick[this.bytesTickIndex]=this.currentTickBytesReceived,this.bytesTickIndex=(this.bytesTickIndex+1)%this.bytesTickRate,this.currentTickBytesSent=0,this.currentTickBytesReceived=0}getBytesSentPerSecond(){return this.bytesSentPerTick.reduce((e,t)=>e+t,0)}getBytesReceivedPerSecond(){return this.bytesReceivedPerTick.reduce((e,t)=>e+t,0)}getAxisBindingId(e){return this.inputBindings.getAxisBindingId(e)}getButtonBindingId(e){return this.inputBindings.getButtonBindingId(e)}decodeAndApplyCompressedInput(e){let t=Rt(e,this.inputBindings),r=this.inputBindings.getAllAxes(),n=this.inputBindings.getAllButtons(),o=r.sort((a,s)=>a.bindingId-s.bindingId),i=n.sort((a,s)=>a.bindingId-s.bindingId);for(let[a,s]of t.axes)if(a<o.length){let d=o[a];this.setAxis(d.name,s)}for(let[a,s]of t.buttons)if(a<i.length){let d=i[a];this.setButton(d.name,s)}this.mouseX=t.mouseX,this.mouseY=t.mouseY,this.mouseOver=t.mouseOverDisplay,this.mouseDisplayId=t.displayId;for(let a of t.touchPositions)this.setTouchPosition(a.id,a.x,a.y,a.over);for(let a of t.displayViewports)this.setDisplayViewport(a.displayId,a.pixelWidth,a.pixelHeight)}playSound(e,t){let r=this.nextSoundInstanceId++,n={sound:e,instanceId:r,volume:t?.volume,pitch:t?.pitch,loop:t?.loop,fadeIn:t?.fadeIn,x:t?.x,y:t?.y,lowpass:t?.lowpass,highpass:t?.highpass,reverb:t?.reverb};return this.soundCommands.push(n),r}stopSound(e){let t={sound:e};this.soundCommands.push(t)}fadeOutSound(e,t){let r={fadeOut:!0,sound:e,duration:t};this.soundCommands.push(r)}fadeOutAllSounds(e){let t={fadeOut:!0,sound:"all",duration:e};this.soundCommands.push(t)}stopAllSounds(){let e={sound:"all"};this.soundCommands.push(e)}pauseSound(e){let t={pause:!0,sound:e};this.soundCommands.push(t)}pauseAllSounds(){let e={pause:!0,sound:"all"};this.soundCommands.push(e)}resumeSound(e){let t={resume:!0,sound:e};this.soundCommands.push(t)}resumeAllSounds(){let e={resume:!0,sound:"all"};this.soundCommands.push(e)}setSoundEffects(e,t){let r={setEffects:!0,instanceId:e,lowpass:t.lowpass,highpass:t.highpass,reverb:t.reverb};this.soundCommands.push(r)}setListenerPosition(e,t){e===this.lastListenerX&&t===this.lastListenerY||(this.lastListenerX=e,this.lastListenerY=t,this.audioConfigCommands.push({type:"set-listener-position",x:e,y:t}))}configureSpatialAudio(e){this.audioConfigCommands.push({type:"configure-spatial",...e})}flushAudioConfigCommands(){let e=this.audioConfigCommands;return this.audioConfigCommands=[],e}hasAudioConfigCommands(){return this.audioConfigCommands.length>0}flushSoundCommands(){let e=this.soundCommands;return this.soundCommands=[],e}hasSoundCommands(){return this.soundCommands.length>0}sendSounds(){this.pendingSendSounds=!0}needsSendSounds(){return this.pendingSendSounds}clearSendSounds(){this.pendingSendSounds=!1}setAudioProcessor(e){this.audioProcessor=e,this.macroEngine.setAudioCallback(t=>{e.play(t)})}getAudioProcessor(){return this.audioProcessor}applyAudioCommands(e){if(this.audioProcessor&&this.mode!=="server")for(let t of e){if("setEffects"in t&&t.setEffects===!0){let n=t;this.audioProcessor.setEffects(n.instanceId,n.lowpass,n.highpass,n.reverb);continue}if("fadeOut"in t&&t.fadeOut===!0){let n=t;this.audioProcessor.fadeOut(n.sound,n.duration);continue}if("pause"in t&&t.pause===!0){let n=t;this.audioProcessor.pause(n.sound);continue}if("resume"in t&&t.resume===!0){let n=t;this.audioProcessor.resume(n.sound);continue}if("instanceId"in t||"volume"in t||"pitch"in t||"loop"in t||"fadeIn"in t||"x"in t||"y"in t||"lowpass"in t||"highpass"in t||"reverb"in t){let n=t,o=n.x!==void 0&&n.y!==void 0?{x:n.x,y:n.y}:void 0;this.audioProcessor.play(n.sound,{volume:n.volume,pitch:n.pitch,loop:n.loop,fadeIn:n.fadeIn,position:o,instanceId:n.instanceId,lowpass:n.lowpass,highpass:n.highpass,reverb:n.reverb})}else{let n=t;n.sound==="all"?this.audioProcessor.stopAll():this.audioProcessor.stop(n.sound)}}}applyAudioConfigCommands(e){if(this.audioProcessor&&this.mode!=="server")for(let t of e)t.type==="set-listener-position"?this.audioProcessor.setListenerPosition(t.x,t.y):t.type==="configure-spatial"&&this.audioProcessor.configureSpatial({maxDistance:t.maxDistance,referenceDistance:t.referenceDistance,rolloffFactor:t.rolloffFactor,panSpread:t.panSpread})}vibrate(e){let t={pattern:e};this.mobileVibrationCommands.push(t)}cancelVibration(){let e={cancel:!0};this.mobileVibrationCommands.push(e)}vibrateTap(){this.vibrate(10)}vibrateMediumTap(){this.vibrate(25)}vibrateHeavyTap(){this.vibrate(50)}vibrateSuccess(){this.vibrate([30,50,30])}vibrateError(){this.vibrate([50,30,50,30,50])}vibrateWarning(){this.vibrate([100])}vibrateSelection(){this.vibrate(5)}vibrateImpact(e="medium"){let t={light:15,medium:30,heavy:50};this.vibrate(t[e])}vibrateNotification(){this.vibrate([100,100,100,100,100])}vibrateGamepad(e,t){let r={gamepadIndex:e,options:t};this.gamepadVibrationCommands.push(r)}stopGamepadVibration(e="all"){let t={gamepadIndex:e,cancel:!0};this.gamepadVibrationCommands.push(t)}gamepadTap(e=0){this.vibrateGamepad(e,{duration:50,strongMagnitude:.3,weakMagnitude:.5})}gamepadImpact(e=0){this.vibrateGamepad(e,{duration:100,strongMagnitude:.7,weakMagnitude:.3})}gamepadHeavy(e=0){this.vibrateGamepad(e,{duration:200,strongMagnitude:1,weakMagnitude:.2})}gamepadExplosion(e=0){this.vibrateGamepad(e,{duration:400,strongMagnitude:1,weakMagnitude:.8})}gamepadSuccess(e=0){this.vibrateGamepad(e,{duration:150,strongMagnitude:.4,weakMagnitude:.6})}gamepadError(e=0){this.vibrateGamepad(e,{duration:300,strongMagnitude:.8,weakMagnitude:.4})}hasGamepadVibrationCommands(){return this.gamepadVibrationCommands.length>0}flushGamepadVibrationCommands(){let e=this.gamepadVibrationCommands;return this.gamepadVibrationCommands=[],e}setGamepadVibrationProcessor(e){this.gamepadVibrationProcessor=e}applyGamepadVibrationCommands(e){if(this.gamepadVibrationProcessor&&this.mode!=="server"){for(let t of e)if("cancel"in t&&t.cancel===!0)t.gamepadIndex==="all"?this.gamepadVibrationProcessor.stopAllVibrations():this.gamepadVibrationProcessor.stopVibration(t.gamepadIndex);else if("options"in t){let r=t;if(r.gamepadIndex==="all")for(let n=0;n<4;n++)this.gamepadVibrationProcessor.vibrate(n,r.options);else this.gamepadVibrationProcessor.vibrate(r.gamepadIndex,r.options)}}}hasMobileVibrationCommands(){return this.mobileVibrationCommands.length>0}flushMobileVibrationCommands(){let e=this.mobileVibrationCommands;return this.mobileVibrationCommands=[],e}setMobileVibrationProcessor(e){this.mobileVibrationProcessor=e}getMobileVibrationProcessor(){return this.mobileVibrationProcessor}applyMobileVibrationCommands(e){if(this.mobileVibrationProcessor&&this.mode!=="server")for(let t of e)"cancel"in t&&t.cancel===!0?this.mobileVibrationProcessor.cancel():"pattern"in t&&this.mobileVibrationProcessor.vibrate(t.pattern)}applyVibrationOrders(e){if(this.mode==="server")return;let{VibrationOrderType:t}=(zt(),re(fn)),{MobileVibrateFlags:r,GamepadVibrateFlags:n}=(Lt(),re(Sn));for(let o of e)switch(o.type){case t.MobileVibrate:{if(!this.mobileVibrationProcessor)break;let i=o,a=i.pattern;i.flags&r.HasIntensity&&i.intensity!==void 0&&(a=a.map(s=>Math.round(s*i.intensity))),this.mobileVibrationProcessor.vibrate(a);break}case t.MobileCancel:{if(!this.mobileVibrationProcessor)break;this.mobileVibrationProcessor.cancel();break}case t.GamepadVibrate:{if(!this.gamepadVibrationProcessor)break;let i=o,a={duration:i.duration,strongMagnitude:i.strongMagnitude/255,weakMagnitude:i.weakMagnitude/255,startDelay:i.startDelay};if(i.flags&n.AllGamepads)for(let s=0;s<4;s++)this.gamepadVibrationProcessor.vibrate(s,a);else this.gamepadVibrationProcessor.vibrate(i.gamepadIndex,a);break}case t.GamepadCancel:{if(!this.gamepadVibrationProcessor)break;let i=o;i.flags&n.AllGamepads?this.gamepadVibrationProcessor.stopAllVibrations():this.gamepadVibrationProcessor.stopVibration(i.gamepadIndex);break}}}applyAudioOrders(e){if(!this.audioProcessor||this.mode==="server")return;let{AudioOrderType:t,AudioTargetType:r}=(Ht(),re(wn)),{PlaySoundFlags:n}=(Nt(),re(Un));for(let o of e)switch(o.type){case t.PlaySound:case t.PlayGlobalSound:{let i=o,a=i.volume!==void 0?i.volume/255:void 0,s=i.pitch!==void 0?.25*Math.pow(2,i.pitch/64):void 0,d=i.fadeIn!==void 0?i.fadeIn/10:void 0,c=(i.flags&n.Loop)!==0,l=i.posX!==void 0&&i.posY!==void 0?{x:i.posX,y:i.posY}:void 0;this.audioProcessor.play(i.soundId,{volume:a,pitch:s,loop:c,fadeIn:d,position:l,instanceId:i.instanceId,lowpass:i.lowpass,highpass:i.highpass,reverb:i.reverb});break}case t.StopSound:{let i=o;i.targetType===r.All?this.audioProcessor.stopAll():i.targetType===r.InstanceId?this.audioProcessor.stop(i.target):this.audioProcessor.stop(i.target);break}case t.FadeOutSound:{let i=o,a=i.duration/10;i.targetType===r.All?this.audioProcessor.fadeOut("all",a):this.audioProcessor.fadeOut(i.target,a);break}case t.PauseSound:{let i=o;i.targetType===r.All?this.audioProcessor.pause("all"):this.audioProcessor.pause(i.target);break}case t.ResumeSound:{let i=o;i.targetType===r.All?this.audioProcessor.resume("all"):this.audioProcessor.resume(i.target);break}case t.SetListenerPosition:{let i=o;this.audioProcessor.setListenerPosition(i.x,i.y);break}case t.ConfigureSpatial:{let i=o;this.audioProcessor.configureSpatial({maxDistance:i.maxDistance*100,referenceDistance:i.referenceDistance*100,rolloffFactor:i.rolloffFactor/100,panSpread:i.panSpread/255});break}case t.SetSoundEffects:{let i=o;this.audioProcessor.setEffects(i.instanceId,i.lowpass,i.highpass,i.reverb);break}}}handleAudioAck(e){switch(e.type){case"sound-loaded":this.loadedSounds.set(e.soundId,{name:e.name,loadedAt:Date.now()}),this.soundLoadErrors.delete(e.soundId);break;case"sound-error":this.soundLoadErrors.set(e.soundId,{name:e.name,error:e.error,at:Date.now()});break;case"playback-started":this.playingSounds.set(e.instanceId,{soundId:e.soundId,startedAt:Date.now()});break;case"playback-ended":this.playingSounds.delete(e.instanceId);break;case"playback-error":e.instanceId!==void 0&&this.playingSounds.delete(e.instanceId);break}}isSoundLoaded(e){return this.loadedSounds.has(e)}getSoundLoadError(e){return this.soundLoadErrors.get(e)?.error}getLoadedSounds(){return this.loadedSounds}getSoundLoadErrors(){return this.soundLoadErrors}isSoundPlaying(e){return this.playingSounds.has(e)}getPlayingSounds(){return this.playingSounds}getPlayingSoundCount(){return this.playingSounds.size}getAudioLoadingState(e){let t=this.loadedSounds.size,r=this.soundLoadErrors.size,n=e>0&&t>=e,o=Array.from(this.soundLoadErrors.values()).map(i=>i.name);return{loadedCount:t,totalExpected:e,errorCount:r,isComplete:n,errors:o}}loadMacro(e,t){let r={...t,id:e},n=this.macroRegistry.registerMacro(r);return this.mode==="client"&&this.macroEngine.loadTemplate(n,r),n}createInstance(e){return this.updateLayerMappings(),this.macroRegistry.createInstance(e)}updateInstance(e,t){return this.macroRegistry.updateInstance(e,t)}removeInstance(e){return this.macroEventHandlers.delete(e),this.macroRegistry.removeInstance(e)}onMacroEvent(e,t,r){this.macroEventHandlers.has(e)||this.macroEventHandlers.set(e,new Map),this.macroEventHandlers.get(e).set(t,r)}offMacroEvent(e,t){t?this.macroEventHandlers.get(e)?.delete(t):this.macroEventHandlers.delete(e)}handleMacroEvent(e){let t=this.macroRegistry.getInstanceName(e.instanceId);if(!t){console.warn(`MacroEvent: Unknown instance ID ${e.instanceId}`);return}let r=this.macroEventHandlers.get(t);if(!r)return;let n,o;switch(e.type){case 1:n="click",o=void 0;break;case 2:n="change",o=e.value;break;case 3:n="submit",o=e.text;break;case 4:n="select",o=e.index;break;default:return}let i=r.get(n);i&&i(o)}flushMacroOrders(){return this.macroRegistry.flushPendingOrders()}hasPendingMacroOrders(){return this.macroRegistry.hasPendingOrders()}applyMacroOrders(e){for(let t of e)this.macroEngine.applyOrder(t)}getMacroRegistry(){return this.macroRegistry}getMacroLoads(){return this.macroRegistry.toAllMacroLoads()}updateLayerMappings(){for(let e of this.layers){let t=e.getId()}}registerLayerName(e,t){this.macroRegistry.setLayerMapping(e,t.getId())}loadMacroTemplate(e,t){this.macroEngine.loadTemplate(e,t)}updateMacros(){return this.macroEngine.update()}processMacroEvents(e){for(let t of e.events){let r=this.macroRegistry.getInstanceName(t.instanceId);if(!r)continue;let n=this.macroEventHandlers.get(r);if(!n)continue;let o=n.get(t.event);o&&o(t.data)}}updateMacroMouse(e,t,r){let n=this.displays.find(o=>o.getId()===this.mouseDisplayId);if(!n&&this.displays.length>0&&(n=this.displays[0]),n){let o=n.getOrigin(),i=e+o.x,a=t+o.y;this.macroEngine.updateMouse(i,a,r)}else this.macroEngine.updateMouse(e,t,r)}getMacroRenderOrders(){let e=this.macroEngine.getOrdersByLayer(),t=this.displays[0];if(!t)return e;let r=t.getOrigin();if(r.x===0&&r.y===0)return e;let n=new Map;for(let[o,i]of e){let a=i.map(s=>{let d={...s};return"posX"in d&&typeof d.posX=="number"&&(d.posX=d.posX-r.x),"posY"in d&&typeof d.posY=="number"&&(d.posY=d.posY-r.y),d});n.set(o,a)}return n}getMacroEffectOffset(){return this.macroEngine.getEffectOffset()}getMacroEngine(){return this.macroEngine}macroFocusNext(){this.macroEngine.focusNext()}macroFocusPrevious(){this.macroEngine.focusPrevious()}macroActivateFocused(){this.macroEngine.activateFocused()}setPostProcess(e,t){let r=JSON.stringify(t),n=JSON.stringify(this.currentPostProcessConfig);r!==n&&(this.currentPostProcessConfig=t,this.postProcessCommands.push({type:"set-config",displayId:e,config:t??void 0}))}setScanlinesEnabled(e,t){if(t){let r=this.currentPostProcessConfig?.scanlines;this.setPostProcess(e,{scanlines:{enabled:!0,opacity:r?.opacity??D.scanlines.opacity,pattern:r?.pattern??D.scanlines.pattern,color:r?.color??D.scanlines.color}})}else this.setPostProcess(e,{scanlines:{enabled:!1}})}setScanlinesOpacity(e,t){let r=Math.max(0,Math.min(1,t)),n=this.currentPostProcessConfig?.scanlines;this.setPostProcess(e,{scanlines:{enabled:!0,opacity:r,pattern:n?.pattern??"horizontal",color:n?.color??{r:0,g:0,b:0}}})}setScanlinesPattern(e,t){let r=this.currentPostProcessConfig?.scanlines;this.setPostProcess(e,{scanlines:{enabled:r?.enabled??!0,opacity:r?.opacity??D.scanlines.opacity,pattern:t,color:r?.color??{r:0,g:0,b:0}}})}setAmbientEffect(e,t){let r=this.currentPostProcessConfig?.ambientEffect;typeof t=="boolean"?this.setPostProcess(e,{...this.currentPostProcessConfig,ambientEffect:{enabled:t,blur:r?.blur??D.ambientEffect.blur,scale:r?.scale??D.ambientEffect.scale}}):this.setPostProcess(e,{...this.currentPostProcessConfig,ambientEffect:{enabled:!0,blur:t.blur??r?.blur??D.ambientEffect.blur,scale:t.scale??r?.scale??D.ambientEffect.scale}})}setAmbientEffectEnabled(e,t){this.setAmbientEffect(e,t)}setAmbientEffectBlur(e,t){let r=this.currentPostProcessConfig?.ambientEffect;this.setPostProcess(e,{...this.currentPostProcessConfig,ambientEffect:{enabled:r?.enabled??!0,blur:Math.max(0,t),scale:r?.scale??D.ambientEffect.scale}})}setAmbientEffectScale(e,t){let r=this.currentPostProcessConfig?.ambientEffect;this.setPostProcess(e,{...this.currentPostProcessConfig,ambientEffect:{enabled:r?.enabled??!0,blur:r?.blur??D.ambientEffect.blur,scale:Math.max(1,t)}})}isAmbientEffectEnabled(){return this.currentPostProcessConfig?.ambientEffect?.enabled??!1}getAmbientEffectConfig(){let e=this.currentPostProcessConfig?.ambientEffect;return e?{enabled:e.enabled,blur:e.blur??D.ambientEffect.blur,scale:e.scale??D.ambientEffect.scale}:null}getPostProcessConfig(){return this.currentPostProcessConfig}hasPostProcessCommands(){return this.postProcessCommands.length>0}flushPostProcessCommands(){let e=this.postProcessCommands;return this.postProcessCommands=[],e}setScalingMode(e,t){this.currentScalingModes.get(e)!==t&&(this.currentScalingModes.set(e,t),this.postProcessCommands.push({type:"set-scaling-mode",displayId:e,scalingMode:t}))}getScalingMode(e){return this.currentScalingModes.get(e)??null}setCellSize(e,t,r){let n=Math.max(1,Math.min(255,Math.round(t))),o=Math.max(1,Math.min(255,Math.round(r))),i=this.currentCellSizes.get(e);i&&i.width===n&&i.height===o||(this.currentCellSizes.set(e,{width:n,height:o}),this.postProcessCommands.push({type:"set-cell-size",displayId:e,cellWidth:n,cellHeight:o}))}getCellSize(e){let t=this.currentCellSizes.get(e);return{cellWidth:t?.width??8,cellHeight:t?.height??8}}setGrid(e,t){let r;typeof t=="boolean"?r={enabled:t,color:He.color,lineWidth:He.lineWidth}:r={enabled:t.enabled,color:t.color??He.color,lineWidth:t.lineWidth??He.lineWidth},this.currentGridConfigs.set(e,r),this.postProcessCommands.push({type:"set-grid",displayId:e,gridConfig:r})}setGridEnabled(e,t){this.setGrid(e,t)}isGridEnabled(e){return this.currentGridConfigs.get(e)?.enabled??!1}getGridConfig(e){return this.currentGridConfigs.get(e)??null}switchPalette(e,t){if(t<0||t>255)throw new Error(`Palette slot ID must be between 0 and 255, got ${t}`);this.currentPaletteSlotIds.get(e)!==t&&(this.currentPaletteSlotIds.set(e,t),this.postProcessCommands.push({type:"switch-palette",displayId:e,paletteSlotId:t}))}getCurrentPaletteSlotId(e){return this.currentPaletteSlotIds.get(e)??null}sendBridge(e,t){this.bridgeMessages.push({channel:e,data:t})}getBridgeMessages(){let e=this.bridgeMessages;return this.bridgeMessages=[],e}hasBridgeMessages(){return this.bridgeMessages.length>0}};y(Yt,"User");var me=Yt;W();W();L();var Xt=class Xt{constructor(){b(this,"charCodeSize",Re)}encode(e,t=!1){switch(e.type){case 1:return this.encodeCharOrder(e,t);case 2:return this.encodeTextOrder(e);case 23:return this.encodeTextMultilineOrder(e);case 3:return this.encodeSubFrameOrder(e,t);case 4:return this.encodeSubFrameMultiColorOrder(e,t);case 5:return this.encodeFullFrameOrder(e,t);case 6:return this.encodeFullFrameMultiColorOrder(e,t);case 7:return this.encodeSpriteOrder(e);case 8:return this.encodeSpriteMultiColorOrder(e);case 9:return this.encodeColorMapOrder(e);case 10:return this.encodeShapeOrder(e,t);case 11:return this.encodeDotCloudOrder(e,t);case 12:return this.encodeDotCloudMultiColorOrder(e,t);case 17:return this.encodeBitmaskOrder(e,t);case 18:return this.encodeBitmask4Order(e,t);case 24:return this.encodeBitmask16Order(e,t);case 25:return this.encodePolylineOrder(e,t);case 13:return this.encodeSpriteCloudOrder(e);case 14:return this.encodeSpriteCloudMultiColorOrder(e);case 15:return this.encodeSpriteCloudVariedOrder(e);case 16:return this.encodeSpriteCloudVariedMultiColorOrder(e);case 19:return this.encodeClearOrder(e,t);case 20:return this.encodeFillCharOrder(e,t);case 21:return this.encodeFillSpriteOrder(e);case 22:return this.encodeFillSpriteMultiColorOrder(e);default:throw new Error(`Unknown order type: ${e.type}`)}}writeCharCode(e,t,r,n){return n?(e.writeUInt16LE(t,r),r+2):(e.writeUInt8(t,r),r+1)}encodeCharOrder(e,t){let r=x.allocUnsafe(kr+(t?1:0)),n=0;return r.writeUInt8(e.type,n++),r.writeUInt8(e.posX,n++),r.writeUInt8(e.posY,n++),n=this.writeCharCode(r,e.charCode,n,t),r.writeUInt8(e.bgColorCode,n++),r.writeUInt8(e.fgColorCode,n++),r.toUint8Array()}encodeTextOrder(e){let t=new TextEncoder().encode(e.text),r=x.allocUnsafe(Br+t.length),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.posX,n++),r.writeUInt8(e.posY,n++),r.writeUInt8(t.length,n++);for(let o=0;o<t.length;o++)r.writeUInt8(t[o],n++);return r.writeUInt8(e.bgColorCode,n++),r.writeUInt8(e.fgColorCode,n++),r.toUint8Array()}encodeTextMultilineOrder(e){let t=new TextEncoder().encode(e.text),r=x.allocUnsafe(zr+t.length),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.posX,n++),r.writeUInt8(e.posY,n++),r.writeUInt8(t.length,n++);for(let o=0;o<t.length;o++)r.writeUInt8(t[o],n++);return r.writeUInt8(e.bgColorCode,n++),r.writeUInt8(e.fgColorCode,n++),r.toUint8Array()}encodeSubFrameOrder(e,t){let r=e.sizeX*e.sizeY,n=this.charCodeSize(t),o=x.allocUnsafe(Tr+r*n),i=0;o.writeUInt8(e.type,i++),o.writeUInt8(e.posX,i++),o.writeUInt8(e.posY,i++),o.writeUInt8(e.sizeX-1,i++),o.writeUInt8(e.sizeY-1,i++),o.writeUInt8(e.bgColorCode,i++),o.writeUInt8(e.fgColorCode,i++);for(let a of e.frame)i=this.writeCharCode(o,a,i,t);return o.toUint8Array()}encodeSubFrameMultiColorOrder(e,t){let r=e.sizeX*e.sizeY,n=this.charCodeSize(t),o=x.allocUnsafe(Fr+r*(n+2)),i=0;o.writeUInt8(e.type,i++),o.writeUInt8(e.posX,i++),o.writeUInt8(e.posY,i++),o.writeUInt8(e.sizeX-1,i++),o.writeUInt8(e.sizeY-1,i++);for(let a of e.frame)i=this.writeCharCode(o,a.charCode,i,t),o.writeUInt8(a.bgColorCode,i++),o.writeUInt8(a.fgColorCode,i++);return o.toUint8Array()}encodeFullFrameOrder(e,t){let r=e.frame.length,n=this.charCodeSize(t),o=x.allocUnsafe(Lr+r*n),i=0;o.writeUInt8(e.type,i++),o.writeUInt8(e.bgColorCode,i++),o.writeUInt8(e.fgColorCode,i++);for(let a of e.frame)i=this.writeCharCode(o,a,i,t);return o.toUint8Array()}encodeFullFrameMultiColorOrder(e,t){let r=e.frame.length,n=this.charCodeSize(t),o=x.allocUnsafe(Dr+r*(n+2)),i=0;o.writeUInt8(e.type,i++);for(let a of e.frame)i=this.writeCharCode(o,a.charCode,i,t),o.writeUInt8(a.bgColorCode,i++),o.writeUInt8(a.fgColorCode,i++);return o.toUint8Array()}encodeSpriteOrder(e){let t=x.allocUnsafe(Vr),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.posX,r++),t.writeUInt8(e.posY,r++),t.writeUInt8(e.spriteIndex,r++),t.writeUInt8(e.bgColorCode,r++),t.writeUInt8(e.fgColorCode,r++),t.toUint8Array()}encodeSpriteMultiColorOrder(e){let t=x.allocUnsafe(Hr),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.posX,r++),t.writeUInt8(e.posY,r++),t.writeUInt8(e.spriteIndex,r++),t.toUint8Array()}encodeColorMapOrder(e){let t=e.sizeX*e.sizeY,r=x.allocUnsafe(_r+t*2),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.posX,n++),r.writeUInt8(e.posY,n++),r.writeUInt8(e.sizeX-1,n++),r.writeUInt8(e.sizeY-1,n++);for(let o of e.colorData)r.writeUInt8(o.bgColorCode,n++),r.writeUInt8(o.fgColorCode,n++);return r.toUint8Array()}encodeShapeOrder(e,t){let r=this.encodeShapeData(e.shapeType,e.shapeData,t),n=x.allocUnsafe(Nr+r.length),o=0;n.writeUInt8(e.type,o++),n.writeUInt8(e.shapeType,o++);for(let i=0;i<r.length;i++)n.writeUInt8(r[i],o++);return n.toUint8Array()}encodeShapeData(e,t,r){let n=this.charCodeSize(r);switch(e){case 1:{let o=x.allocUnsafe(Yr+(r?1:0)),i=0;return o.writeUInt8(t.posX,i++),o.writeUInt8(t.posY,i++),o.writeUInt8(t.width-1,i++),o.writeUInt8(t.height-1,i++),o.writeUInt8(t.filled?1:0,i++),i=this.writeCharCode(o,t.charCode,i,r),o.writeUInt8(t.bgColorCode,i++),o.writeUInt8(t.fgColorCode,i++),o.toUint8Array()}case 2:{let o=x.allocUnsafe(Xr+(r?1:0)),i=0;return o.writeUInt8(t.centerX,i++),o.writeUInt8(t.centerY,i++),o.writeUInt8(t.radius-1,i++),o.writeUInt8(t.filled?1:0,i++),i=this.writeCharCode(o,t.charCode,i,r),o.writeUInt8(t.bgColorCode,i++),o.writeUInt8(t.fgColorCode,i++),o.toUint8Array()}case 3:{let o=x.allocUnsafe(Wr+(r?1:0)),i=0;return o.writeUInt8(t.x1,i++),o.writeUInt8(t.y1,i++),o.writeUInt8(t.x2,i++),o.writeUInt8(t.y2,i++),i=this.writeCharCode(o,t.charCode,i,r),o.writeUInt8(t.bgColorCode,i++),o.writeUInt8(t.fgColorCode,i++),o.toUint8Array()}case 4:{let o=x.allocUnsafe(Gr+(r?1:0)),i=0;return o.writeUInt8(t.centerX,i++),o.writeUInt8(t.centerY,i++),o.writeUInt8(t.radiusX-1,i++),o.writeUInt8(t.radiusY-1,i++),o.writeUInt8(t.filled?1:0,i++),i=this.writeCharCode(o,t.charCode,i,r),o.writeUInt8(t.bgColorCode,i++),o.writeUInt8(t.fgColorCode,i++),o.toUint8Array()}case 5:{let o=x.allocUnsafe($r+(r?1:0)),i=0;return o.writeUInt8(t.x1,i++),o.writeUInt8(t.y1,i++),o.writeUInt8(t.x2,i++),o.writeUInt8(t.y2,i++),o.writeUInt8(t.x3,i++),o.writeUInt8(t.y3,i++),o.writeUInt8(t.filled?1:0,i++),i=this.writeCharCode(o,t.charCode,i,r),o.writeUInt8(t.bgColorCode,i++),o.writeUInt8(t.fgColorCode,i++),o.toUint8Array()}default:throw new Error(`Unknown shape type: ${e}`)}}encodeDotCloudOrder(e,t){let r=e.positions.length,n=this.charCodeSize(t),o=x.allocUnsafe(Zr+(t?1:0)+r*2),i=0;o.writeUInt8(e.type,i++),i=this.writeCharCode(o,e.charCode,i,t),o.writeUInt8(e.bgColorCode,i++),o.writeUInt8(e.fgColorCode,i++),o.writeUInt16BE(r,i),i+=2;for(let a of e.positions)o.writeUInt8(a.posX,i++),o.writeUInt8(a.posY,i++);return o.toUint8Array()}encodeDotCloudMultiColorOrder(e,t){let r=e.dots.length,n=this.charCodeSize(t),o=x.allocUnsafe(jr+r*(n+4)),i=0;o.writeUInt8(e.type,i++),o.writeUInt16BE(r,i),i+=2;for(let a of e.dots)i=this.writeCharCode(o,a.charCode,i,t),o.writeUInt8(a.bgColorCode,i++),o.writeUInt8(a.fgColorCode,i++),o.writeUInt8(a.posX,i++),o.writeUInt8(a.posY,i++);return o.toUint8Array()}encodeBitmaskOrder(e,t){let r=e.mask.length,n=x.allocUnsafe(Jr+(t?1:0)+r),o=0;n.writeUInt8(e.type,o++),n.writeUInt8(e.posX,o++),n.writeUInt8(e.posY,o++),n.writeUInt8(e.sizeX-1,o++),n.writeUInt8(e.sizeY-1,o++),o=this.writeCharCode(n,e.charCode,o,t),n.writeUInt8(e.bgColorCode,o++),n.writeUInt8(e.fgColorCode,o++),n.writeUInt8(e.override?1:0,o++);for(let i=0;i<r;i++)n.writeUInt8(e.mask[i],o++);return n.toUint8Array()}encodeBitmask4Order(e,t){let r=e.mask.length,n=this.charCodeSize(t),o=x.allocUnsafe(qr+3*(t?1:0)+r),i=0;o.writeUInt8(e.type,i++),o.writeUInt8(e.posX,i++),o.writeUInt8(e.posY,i++),o.writeUInt8(e.sizeX-1,i++),o.writeUInt8(e.sizeY-1,i++),o.writeUInt8(e.override?1:0,i++);for(let a of e.variants)i=this.writeCharCode(o,a.charCode,i,t),o.writeUInt8(a.bgColorCode,i++),o.writeUInt8(a.fgColorCode,i++);for(let a=0;a<r;a++)o.writeUInt8(e.mask[a],i++);return o.toUint8Array()}encodeBitmask16Order(e,t){let r=e.mask.length,n=this.charCodeSize(t),o=x.allocUnsafe(Kr+15*(t?1:0)+r),i=0;o.writeUInt8(e.type,i++),o.writeUInt8(e.posX,i++),o.writeUInt8(e.posY,i++),o.writeUInt8(e.sizeX-1,i++),o.writeUInt8(e.sizeY-1,i++),o.writeUInt8(e.override?1:0,i++);for(let a of e.variants)i=this.writeCharCode(o,a.charCode,i,t),o.writeUInt8(a.bgColorCode,i++),o.writeUInt8(a.fgColorCode,i++);for(let a=0;a<r;a++)o.writeUInt8(e.mask[a],i++);return o.toUint8Array()}encodePolylineOrder(e,t){let r=e.points.length,n=x.allocUnsafe(Qr+(t?1:0)+r*2),o=0;n.writeUInt8(e.type,o++),o=this.writeCharCode(n,e.charCode,o,t),n.writeUInt8(e.fgColorCode,o++),n.writeUInt8(e.bgColorCode,o++),n.writeUInt8(r,o++);for(let i of e.points)n.writeUInt8(i.x,o++),n.writeUInt8(i.y,o++);return n.toUint8Array()}encodeSpriteCloudOrder(e){let t=e.positions.length,r=x.allocUnsafe(en+t*2),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.spriteIndex,n++),r.writeUInt8(e.bgColorCode,n++),r.writeUInt8(e.fgColorCode,n++),r.writeUInt16BE(t,n),n+=2;for(let o of e.positions)r.writeUInt8(o.posX,n++),r.writeUInt8(o.posY,n++);return r.toUint8Array()}encodeSpriteCloudMultiColorOrder(e){let t=e.positions.length,r=x.allocUnsafe(tn+t*2),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.spriteIndex,n++),r.writeUInt16BE(t,n),n+=2;for(let o of e.positions)r.writeUInt8(o.posX,n++),r.writeUInt8(o.posY,n++);return r.toUint8Array()}encodeSpriteCloudVariedOrder(e){let t=e.sprites.length,r=x.allocUnsafe(rn+t*5),n=0;r.writeUInt8(e.type,n++),r.writeUInt16BE(t,n),n+=2;for(let o of e.sprites)r.writeUInt8(o.spriteIndex,n++),r.writeUInt8(o.bgColorCode,n++),r.writeUInt8(o.fgColorCode,n++),r.writeUInt8(o.posX,n++),r.writeUInt8(o.posY,n++);return r.toUint8Array()}encodeSpriteCloudVariedMultiColorOrder(e){let t=e.sprites.length,r=x.allocUnsafe(nn+t*3),n=0;r.writeUInt8(e.type,n++),r.writeUInt16BE(t,n),n+=2;for(let o of e.sprites)r.writeUInt8(o.spriteIndex,n++),r.writeUInt8(o.posX,n++),r.writeUInt8(o.posY,n++);return r.toUint8Array()}encodeClearOrder(e,t){let r=x.allocUnsafe(on+(t?1:0)),n=0;return r.writeUInt8(e.type,n++),n=this.writeCharCode(r,e.charCode,n,t),r.writeUInt8(e.bgColorCode,n++),r.writeUInt8(e.fgColorCode,n++),r.toUint8Array()}encodeFillCharOrder(e,t){let r=e.patternWidth*e.patternHeight,n=this.charCodeSize(t),o=x.allocUnsafe(an+r*n),i=0;o.writeUInt8(e.type,i++),o.writeUInt8(e.patternWidth-1,i++),o.writeUInt8(e.patternHeight-1,i++),o.writeUInt8(e.bgColorCode,i++),o.writeUInt8(e.fgColorCode,i++);for(let a of e.pattern)i=this.writeCharCode(o,a,i,t);return o.toUint8Array()}encodeFillSpriteOrder(e){let t=x.allocUnsafe(sn),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.spriteIndex,r++),t.writeUInt8(e.bgColorCode,r++),t.writeUInt8(e.fgColorCode,r++),t.toUint8Array()}encodeFillSpriteMultiColorOrder(e){let t=x.allocUnsafe(dn),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.spriteIndex,r++),t.toUint8Array()}};y(Xt,"OrderEncoder");var _e=Xt;L();var Mn=255,An=64,Wt=class Wt{constructor(){b(this,"orderEncoder");this.orderEncoder=new _e}encode(e){let t=e.is16bit;if(e.orders.length>Mn)throw new Error(`[UTSP] LayerEncoder: Layer ${e.id} has ${e.orders.length} orders, max is ${Mn}. This would cause packet corruption! Split into multiple layers.`);let r=e.orders.map(c=>this.orderEncoder.encode(c,t)),n=13,o=r.reduce((c,l)=>c+l.length,0),i=n+o,a=x.allocUnsafe(i),s=0;a.writeUInt16BE(e.id,s),s+=2;let d=e.updateFlags;t?d|=An:d&=~An,a.writeUInt8(d,s++),a.writeUInt8(e.zIndex,s++),a.writeUInt16BE(e.originX,s),s+=2,a.writeUInt16BE(e.originY,s),s+=2,a.writeUInt16BE(e.width,s),s+=2,a.writeUInt16BE(e.height,s),s+=2,a.writeUInt8(e.orders.length,s++);for(let c of r)x.from(c).copy(a,s),s+=c.length;return a.toUint8Array()}calculateSize(e){let r=e.is16bit;return 13+e.orders.reduce((o,i)=>o+this.orderEncoder.encode(i,r).length,0)}};y(Wt,"LayerEncoder");var Ne=Wt;L();W();var Gt=class Gt{encode(e){switch(e.type){case 1:return this.encodePlaySoundOrder(e);case 2:return this.encodePlayGlobalSoundOrder(e);case 3:return this.encodeStopSoundOrder(e);case 4:return this.encodeFadeOutSoundOrder(e);case 5:return this.encodePauseSoundOrder(e);case 6:return this.encodeResumeSoundOrder(e);case 7:return this.encodeSetListenerPositionOrder(e);case 8:return this.encodeConfigureSpatialOrder(e);case 9:return this.encodeSetSoundEffectsOrder(e);default:throw new Error(`Unknown audio order type: ${e.type}`)}}calculateSize(e){switch(e.type){case 1:return this.calculatePlaySoundSize(e);case 2:return this.calculatePlayGlobalSoundSize(e);case 3:case 5:case 6:return this.calculateTargetOrderSize(e);case 4:return this.calculateFadeOutSize(e);case 7:return it;case 8:return at;case 9:return this.calculateSetSoundEffectsSize(e);default:throw new Error(`Unknown audio order type: ${e.type}`)}}encodePlaySoundOrder(e){let t=this.calculatePlaySoundSize(e),r=x.allocUnsafe(t),n=0;return r.writeUInt8(e.type,n++),r.writeUInt8(e.soundId,n++),r.writeUInt16BE(e.instanceId,n),n+=2,r.writeUInt8(e.flags,n++),e.flags&2&&r.writeUInt8(e.volume??255,n++),e.flags&4&&r.writeUInt8(e.pitch??128,n++),e.flags&8&&r.writeUInt8(e.fadeIn??0,n++),e.flags&16&&(r.writeUInt16BE(e.posX??0,n),n+=2,r.writeUInt16BE(e.posY??0,n),n+=2),e.flags&32&&r.writeUInt8(e.lowpass??0,n++),e.flags&64&&r.writeUInt8(e.highpass??0,n++),e.flags&128&&r.writeUInt8(e.reverb??0,n++),r.toUint8Array()}encodePlayGlobalSoundOrder(e){let t=this.calculatePlayGlobalSoundSize(e),r=x.allocUnsafe(t),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.soundId,n++),r.writeUInt16BE(e.instanceId,n),n+=2;let o=e.flags&-17;return r.writeUInt8(o,n++),o&2&&r.writeUInt8(e.volume??255,n++),o&4&&r.writeUInt8(e.pitch??128,n++),o&8&&r.writeUInt8(e.fadeIn??0,n++),o&32&&r.writeUInt8(e.lowpass??0,n++),o&64&&r.writeUInt8(e.highpass??0,n++),o&128&&r.writeUInt8(e.reverb??0,n++),r.toUint8Array()}calculatePlaySoundSize(e){let t=cn;return e.flags&2&&(t+=1),e.flags&4&&(t+=1),e.flags&8&&(t+=1),e.flags&16&&(t+=4),e.flags&32&&(t+=1),e.flags&64&&(t+=1),e.flags&128&&(t+=1),t}calculatePlayGlobalSoundSize(e){let t=ln,r=e.flags&-17;return r&2&&(t+=1),r&4&&(t+=1),r&8&&(t+=1),r&32&&(t+=1),r&64&&(t+=1),r&128&&(t+=1),t}encodeStopSoundOrder(e){return this.encodeTargetOrder(e.type,e.targetType,e.target)}encodePauseSoundOrder(e){return this.encodeTargetOrder(e.type,e.targetType,e.target)}encodeResumeSoundOrder(e){return this.encodeTargetOrder(e.type,e.targetType,e.target)}encodeFadeOutSoundOrder(e){let t=this.calculateFadeOutSize(e),r=x.allocUnsafe(t),n=0;return r.writeUInt8(e.type,n++),r.writeUInt8(e.targetType,n++),r.writeUInt8(e.duration,n++),e.targetType===0?r.writeUInt16BE(e.target??0,n):e.targetType===1&&r.writeUInt8(e.target??0,n),r.toUint8Array()}encodeTargetOrder(e,t,r){let n=2;t===0?n+=2:t===1&&(n+=1);let o=x.allocUnsafe(n),i=0;return o.writeUInt8(e,i++),o.writeUInt8(t,i++),t===0?o.writeUInt16BE(r??0,i):t===1&&o.writeUInt8(r??0,i),o.toUint8Array()}calculateTargetOrderSize(e){let t=2;return e.targetType===0?t+=2:e.targetType===1&&(t+=1),t}calculateFadeOutSize(e){let t=3;return e.targetType===0?t+=2:e.targetType===1&&(t+=1),t}encodeSetListenerPositionOrder(e){let t=x.allocUnsafe(it),r=0;return t.writeUInt8(e.type,r++),t.writeUInt16BE(e.x,r),r+=2,t.writeUInt16BE(e.y,r),t.toUint8Array()}encodeConfigureSpatialOrder(e){let t=x.allocUnsafe(at),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.maxDistance,r++),t.writeUInt8(e.referenceDistance,r++),t.writeUInt8(e.rolloffFactor,r++),t.writeUInt8(e.panSpread,r++),t.toUint8Array()}encodeSetSoundEffectsOrder(e){let t=this.calculateSetSoundEffectsSize(e),r=x.allocUnsafe(t),n=0;return r.writeUInt8(e.type,n++),r.writeUInt16BE(e.instanceId,n),n+=2,r.writeUInt8(e.flags,n++),e.flags&1&&r.writeUInt8(e.lowpass??0,n++),e.flags&2&&r.writeUInt8(e.highpass??0,n++),e.flags&4&&r.writeUInt8(e.reverb??0,n++),r.toUint8Array()}calculateSetSoundEffectsSize(e){let t=4;return e.flags&1&&(t+=1),e.flags&2&&(t+=1),e.flags&4&&(t+=1),t}};y(Gt,"AudioOrderEncoder");var Ye=Gt;L();var $t=class $t{encode(e){switch(e.type){case 1:return this.encodeMobileVibrateOrder(e);case 2:return this.encodeMobileCancelOrder(e);case 16:return this.encodeGamepadVibrateOrder(e);case 17:return this.encodeGamepadCancelOrder(e);default:throw new Error(`Unknown vibration order type: ${e.type}`)}}calculateSize(e){switch(e.type){case 1:return this.calculateMobileVibrateSize(e);case 2:return 1;case 16:return this.calculateGamepadVibrateSize(e);case 17:return 3;default:throw new Error(`Unknown vibration order type: ${e.type}`)}}calculateMobileVibrateSize(e){let t=3+e.pattern.length*2;return e.intensity!==void 0&&(t+=1),t}encodeMobileVibrateOrder(e){let t=this.calculateMobileVibrateSize(e),r=x.allocUnsafe(t),n=0,o=0;e.intensity!==void 0&&(o|=1),r.writeUInt8(e.type,n++),r.writeUInt8(o,n++),r.writeUInt8(e.pattern.length,n++);for(let i of e.pattern){let a=Math.min(65535,Math.max(0,Math.round(i)));r.writeUInt16BE(a,n),n+=2}if(e.intensity!==void 0){let i=Math.round(Math.min(1,Math.max(0,e.intensity))*255);r.writeUInt8(i,n++)}return r.toUint8Array()}encodeMobileCancelOrder(e){let t=x.allocUnsafe(1);return t.writeUInt8(2,0),t.toUint8Array()}calculateGamepadVibrateSize(e){let t=7;return e.startDelay!==void 0&&e.startDelay>0&&(t+=2),t}encodeGamepadVibrateOrder(e){let t=this.calculateGamepadVibrateSize(e),r=x.allocUnsafe(t),n=0,o=0;e.startDelay!==void 0&&e.startDelay>0&&(o|=1),e.gamepadIndex===255&&(o|=2),r.writeUInt8(e.type,n++),r.writeUInt8(o,n++),r.writeUInt8(e.gamepadIndex,n++);let i=Math.min(65535,Math.max(0,Math.round(e.duration)));if(r.writeUInt16BE(i,n),n+=2,r.writeUInt8(e.strongMagnitude,n++),r.writeUInt8(e.weakMagnitude,n++),e.startDelay!==void 0&&e.startDelay>0){let a=Math.min(65535,Math.max(0,Math.round(e.startDelay)));r.writeUInt16BE(a,n),n+=2}return r.toUint8Array()}encodeGamepadCancelOrder(e){let t=x.allocUnsafe(3),r=0,n=0;return e.gamepadIndex===255&&(n|=2),t.writeUInt8(e.type,r++),t.writeUInt8(n,r++),t.writeUInt8(e.gamepadIndex,r++),t.toUint8Array()}};y($t,"VibrationOrderEncoder");var he=$t;L();var Zt=class Zt{encode(e){switch(e.type){case 1:return this.encodeCreateInstance(e);case 2:return this.encodeUpdateInstance(e);case 3:return this.encodeRemoveInstance(e);default:throw new Error(`Unknown macro order type: ${e.type}`)}}calculateSize(e){switch(e.type){case 1:return this.calculateCreateInstanceSize(e);case 2:return this.calculateUpdateInstanceSize(e);case 3:return 2;default:throw new Error(`Unknown macro order type: ${e.type}`)}}encodeCreateInstance(e){let t=JSON.stringify(e.params),r=new TextEncoder().encode(t);if(r.length>65535)throw new Error(`Params JSON too large: ${r.length} bytes (max 65535)`);let n=11+r.length,o=x.allocUnsafe(n),i=0;return o.writeUInt8(e.type,i++),o.writeUInt8(e.instanceId,i++),o.writeUInt8(e.macroId,i++),o.writeUInt8(e.layerId,i++),o.writeInt16BE(e.x,i),i+=2,o.writeInt16BE(e.y,i),i+=2,o.writeUInt8(e.tabIndex,i++),o.writeUInt16BE(r.length,i),i+=2,o.toUint8Array().set(r,i),o.toUint8Array()}calculateCreateInstanceSize(e){let t=JSON.stringify(e.params);return 11+new TextEncoder().encode(t).length}encodeUpdateInstance(e){let t=JSON.stringify(e.params),r=new TextEncoder().encode(t);if(r.length>65535)throw new Error(`Params JSON too large: ${r.length} bytes (max 65535)`);let n=4+r.length,o=x.allocUnsafe(n),i=0;return o.writeUInt8(e.type,i++),o.writeUInt8(e.instanceId,i++),o.writeUInt16BE(r.length,i),i+=2,o.toUint8Array().set(r,i),o.toUint8Array()}calculateUpdateInstanceSize(e){let t=JSON.stringify(e.params);return 4+new TextEncoder().encode(t).length}encodeRemoveInstance(e){let t=x.allocUnsafe(2);return t.writeUInt8(e.type,0),t.writeUInt8(e.instanceId,1),t.toUint8Array()}};y(Zt,"MacroOrderEncoder");var Xe=Zt;L();W();var jt=class jt{encode(e){switch(e.type){case 1:return this.encodeSetConfigOrder(e);case 2:return this.encodeSetScanlinesOrder(e);case 3:return this.encodeSetAmbientEffectOrder(e);case 4:return this.encodeSetScalingModeOrder(e);case 5:return this.encodeSetGridOrder(e);case 6:return this.encodeSwitchPaletteOrder(e);case 7:return this.encodeSetCellSizeOrder(e);default:throw new Error(`Unknown post-process order type: ${e.type}`)}}calculateSize(e){switch(e.type){case 1:return this.calculateSetConfigSize(e);case 2:return st;case 3:return dt;case 4:return ct;case 5:return lt;case 6:return ut;case 7:return pt;default:throw new Error(`Unknown post-process order type: ${e.type}`)}}encodeSetConfigOrder(e){let t=this.calculateSetConfigSize(e),r=x.allocUnsafe(t),n=0;return r.writeUInt8(e.type,n++),r.writeUInt8(e.displayId,n++),r.writeUInt8(e.flags,n++),e.flags&1&&e.scanlines&&(r.writeUInt8(e.scanlines.enabled?1:0,n++),r.writeUInt8(Math.round(e.scanlines.opacity*255),n++),r.writeUInt8(e.scanlines.pattern,n++),r.writeUInt8(e.scanlines.colorR,n++),r.writeUInt8(e.scanlines.colorG,n++),r.writeUInt8(e.scanlines.colorB,n++)),e.flags&2&&e.ambientEffect&&(r.writeUInt8(e.ambientEffect.enabled?1:0,n++),r.writeUInt8(Math.min(255,Math.round(e.ambientEffect.blur)),n++),r.writeUInt8(Math.min(255,Math.max(100,Math.round(e.ambientEffect.scale*100))),n++),r.writeUInt8(Math.round(e.ambientEffect.opacity*255),n++)),r.toUint8Array()}calculateSetConfigSize(e){let t=un;return e.flags&1&&(t+=6),e.flags&2&&(t+=4),t}encodeSetScanlinesOrder(e){let t=x.allocUnsafe(st),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.displayId,r++),t.writeUInt8(e.enabled?1:0,r++),t.writeUInt8(Math.round(e.opacity*255),r++),t.writeUInt8(e.pattern,r++),t.writeUInt8(e.colorR,r++),t.writeUInt8(e.colorG,r++),t.writeUInt8(e.colorB,r++),t.toUint8Array()}encodeSetAmbientEffectOrder(e){let t=x.allocUnsafe(dt),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.displayId,r++),t.writeUInt8(e.enabled?1:0,r++),t.writeUInt8(Math.min(255,Math.round(e.blur)),r++),t.writeUInt8(Math.min(255,Math.max(100,Math.round(e.scale*100))),r++),t.writeUInt8(Math.round(e.opacity*255),r++),t.toUint8Array()}encodeSetScalingModeOrder(e){let t=x.allocUnsafe(ct),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.displayId,r++),t.writeUInt8(e.mode,r++),t.toUint8Array()}encodeSetGridOrder(e){let t=x.allocUnsafe(lt),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.displayId,r++),t.writeUInt8(e.enabled?1:0,r++),t.writeUInt8(e.colorR,r++),t.writeUInt8(e.colorG,r++),t.writeUInt8(e.colorB,r++),t.writeUInt8(e.colorA,r++),t.writeUInt8(Math.min(10,Math.max(1,e.lineWidth)),r++),t.toUint8Array()}encodeSwitchPaletteOrder(e){let t=x.allocUnsafe(ut),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.displayId,r++),t.writeUInt8(e.slotId,r++),t.toUint8Array()}encodeSetCellSizeOrder(e){let t=x.allocUnsafe(pt),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.displayId,r++),t.writeUInt8(e.cellWidth,r++),t.writeUInt8(e.cellHeight,r++),t.toUint8Array()}};y(jt,"PostProcessOrderEncoder");var We=jt;L();var Jt=class Jt{constructor(){b(this,"layerEncoder");b(this,"audioOrderEncoder");b(this,"vibrationOrderEncoder");b(this,"macroOrderEncoder");b(this,"postProcessOrderEncoder");this.layerEncoder=new Ne,this.audioOrderEncoder=new Ye,this.vibrationOrderEncoder=new he,this.macroOrderEncoder=new Xe,this.postProcessOrderEncoder=new We}encode(e){let t=e.layers.map(v=>this.layerEncoder.encode(v)),r=e.audioOrders||[],n=r.map(v=>this.audioOrderEncoder.encode(v)),o=e.vibrationOrders||[],i=o.map(v=>this.vibrationOrderEncoder.encode(v)),a=e.macroOrders||[],s=a.map(v=>this.macroOrderEncoder.encode(v)),d=e.postProcessOrders||[],c=d.map(v=>this.postProcessOrderEncoder.encode(v)),l=9,u=e.displays.length*7,p=2,m=t.reduce((v,T)=>v+T.length,0),g=1,C=n.reduce((v,T)=>v+T.length,0),S=1,O=i.reduce((v,T)=>v+T.length,0),I=1,w=s.reduce((v,T)=>v+T.length,0),U=1,P=c.reduce((v,T)=>v+T.length,0),R=l+u+p+m+g+C+S+O+I+w+U+P,M=x.allocUnsafe(R),f=0,nt=typeof e.tick=="bigint"?e.tick:BigInt(e.tick);M.writeBigUInt64BE(nt,f),f+=8,M.writeUInt8(e.displays.length,f),f+=1;for(let v of e.displays)M.writeUInt8(v.id,f++),M.writeUInt16BE(v.originX,f),f+=2,M.writeUInt16BE(v.originY,f),f+=2,M.writeUInt8(Math.max(1,Math.min(256,v.sizeX))-1,f++),M.writeUInt8(Math.max(1,Math.min(256,v.sizeY))-1,f++);M.writeUInt16BE(e.layers.length,f),f+=2;for(let v of t)x.from(v).copy(M,f),f+=v.length;M.writeUInt8(r.length,f),f+=1;for(let v of n)x.from(v).copy(M,f),f+=v.length;M.writeUInt8(o.length,f),f+=1;for(let v of i)x.from(v).copy(M,f),f+=v.length;M.writeUInt8(a.length,f),f+=1;for(let v of s)x.from(v).copy(M,f),f+=v.length;M.writeUInt8(d.length,f),f+=1;for(let v of c)x.from(v).copy(M,f),f+=v.length;return M.toUint8Array()}calculateSize(e){let r=e.displays.length*7,n=2,o=e.layers.reduce((O,I)=>O+this.layerEncoder.calculateSize(I),0),i=1,s=(e.audioOrders||[]).reduce((O,I)=>O+this.audioOrderEncoder.calculateSize(I),0),d=1,l=(e.vibrationOrders||[]).reduce((O,I)=>O+this.vibrationOrderEncoder.calculateSize(I),0),u=1,m=(e.macroOrders||[]).reduce((O,I)=>O+this.macroOrderEncoder.calculateSize(I),0),g=1,S=(e.postProcessOrders||[]).reduce((O,I)=>O+this.postProcessOrderEncoder.calculateSize(I),0);return 9+r+n+o+i+s+d+l+u+m+g+S}static createEmptyPacket(e){return{tick:typeof e=="bigint"?Number(e):e,displayCount:0,displays:[],layerCount:0,layers:[],audioOrderCount:0,audioOrders:[],vibrationOrderCount:0,vibrationOrders:[],macroOrderCount:0,macroOrders:[],postProcessOrderCount:0,postProcessOrders:[]}}encodeEmpty(e){let t=x.allocUnsafe(15),r=typeof e=="bigint"?e:BigInt(e);return t.writeBigUInt64BE(r,0),t.writeUInt8(0,8),t.writeUInt16BE(0,9),t.writeUInt8(0,11),t.writeUInt8(0,12),t.writeUInt8(0,13),t.writeUInt8(0,14),t.toUint8Array()}};y(Jt,"UpdatePacketEncoder");var Ge=Jt;var kn=(s=>(s[s.ColorPalette=1]="ColorPalette",s[s.Sprite=2]="Sprite",s[s.MulticolorSprite=3]="MulticolorSprite",s[s.BitmapFont=4]="BitmapFont",s[s.Sound=5]="Sound",s[s.WebFont=6]="WebFont",s[s.Macro=7]="Macro",s[s.ImageFont=8]="ImageFont",s))(kn||{});L();var qt=class qt{encode(e){let t=JSON.stringify(e.template),r=new TextEncoder().encode(t);if(r.length>65535)throw new Error(`Macro template JSON too large: ${r.length} bytes (max 65535)`);let n=4+r.length,o=x.allocUnsafe(n),i=0;return o.writeUInt8(7,i++),o.writeUInt8(e.macroId,i++),o.writeUInt16BE(r.length,i),i+=2,o.toUint8Array().set(r,i),o.toUint8Array()}calculateSize(e){let t=JSON.stringify(e.template);return 4+new TextEncoder().encode(t).length}};y(qt,"MacroLoadEncoder");var $e=qt;L();var Kt=class Kt{encode(e){switch(e.loadType){case 1:return this.encodeColorPalette(e);case 2:return this.encodeSprite(e);case 3:return this.encodeMulticolorSprite(e);case 4:return this.encodeBitmapFont(e);case 5:return this.encodeSound(e);case 6:return this.encodeWebFont(e);case 8:return this.encodeImageFont(e);default:throw new Error(`Unknown load type: ${e.loadType}`)}}encodeColorPalette(e){let t=e.colors.length;if(t>255)throw new Error(`Palette size ${t} exceeds maximum of 255`);let r=e.slotId!==void 0,n=r?4:3,o=x.allocUnsafe(n+t*6),i=0;o.writeUInt8(1,i++),o.writeUInt8(r?255:0,i++),r&&o.writeUInt8(e.slotId,i++),o.writeUInt8(t,i++);for(let a of e.colors)o.writeUInt8(a.colorId,i++),o.writeUInt8(a.r,i++),o.writeUInt8(a.g,i++),o.writeUInt8(a.b,i++),o.writeUInt8(a.a,i++),o.writeUInt8(a.e??0,i++);return o.toUint8Array()}encodeSprite(e){let t=e.sprites.length;if(t>255)throw new Error(`Sprite count ${t} exceeds maximum of 255`);let r=2;for(let i of e.sprites)r+=3,r+=i.data.length;let n=x.allocUnsafe(r),o=0;n.writeUInt8(2,o++),n.writeUInt8(t,o++);for(let i of e.sprites){if(i.data.length!==i.sizeX*i.sizeY)throw new Error(`Sprite ${i.spriteId}: data length ${i.data.length} does not match size ${i.sizeX}x${i.sizeY}`);n.writeUInt8(i.spriteId,o++),n.writeUInt8(i.sizeX,o++),n.writeUInt8(i.sizeY,o++);for(let a of i.data)n.writeUInt8(a,o++)}return n.toUint8Array()}encodeMulticolorSprite(e){let t=e.sprites.length;if(t>255)throw new Error(`Sprite count ${t} exceeds maximum of 255`);let r=2;for(let i of e.sprites)r+=3,r+=i.data.length*3;let n=x.allocUnsafe(r),o=0;n.writeUInt8(3,o++),n.writeUInt8(t,o++);for(let i of e.sprites){if(i.data.length!==i.sizeX*i.sizeY)throw new Error(`Sprite ${i.spriteId}: data length ${i.data.length} does not match size ${i.sizeX}x${i.sizeY}`);n.writeUInt8(i.spriteId,o++),n.writeUInt8(i.sizeX,o++),n.writeUInt8(i.sizeY,o++);for(let a of i.data)n.writeUInt8(a.charCode,o++),n.writeUInt8(a.fgColorId,o++),n.writeUInt8(a.bgColorId,o++)}return n.toUint8Array()}encodeBitmapFont(e){let t=e.characters.length;if(t>255)throw new Error(`Character count ${t} exceeds maximum of 255`);let r=Math.ceil(e.width*e.height/8),n=7+t*(1+r),o=x.allocUnsafe(n),i=0;o.writeUInt8(4,i++),o.writeUInt8(e.fontId,i++),o.writeUInt8(e.width,i++),o.writeUInt8(e.height,i++),o.writeUInt8(e.cellWidth,i++),o.writeUInt8(e.cellHeight,i++),o.writeUInt8(t,i++);for(let a of e.characters){if(a.bitmap.length!==r)throw new Error(`Character ${a.charCode}: bitmap size ${a.bitmap.length} does not match expected ${r} bytes`);o.writeUInt8(a.charCode,i++);for(let s=0;s<a.bitmap.length;s++)o.writeUInt8(a.bitmap[s],i++)}return o.toUint8Array()}encodeSound(e){let t=e.sounds.length;if(t>255)throw new Error(`Sound count ${t} exceeds maximum of 255`);let r=2;for(let i of e.sounds){if(i.midiData.length>65535)throw new Error(`Sound ${i.soundId}: MIDI data size ${i.midiData.length} exceeds maximum of 65535 bytes`);r+=3,r+=i.midiData.length}let n=x.allocUnsafe(r),o=0;n.writeUInt8(5,o++),n.writeUInt8(t,o++);for(let i of e.sounds){n.writeUInt8(i.soundId,o++),n.writeUInt16BE(i.midiData.length,o),o+=2;for(let a=0;a<i.midiData.length;a++)n.writeUInt8(i.midiData[a],o++)}return n.toUint8Array()}encodeWebFont(e){let t=new TextEncoder,r=t.encode(e.fontFamily),n=e.fontWeight?t.encode(e.fontWeight):new Uint8Array(0),o=e.fontStyle?t.encode(e.fontStyle):new Uint8Array(0),i=0;e.offsetX!==void 0&&(i|=1),e.offsetY!==void 0&&(i|=2),e.charSpacing!==void 0&&(i|=4),e.lineHeight!==void 0&&(i|=8),e.fontWeight!==void 0&&(i|=16),e.fontStyle!==void 0&&(i|=32);let a=4;a+=r.length,a+=2,e.offsetX!==void 0&&(a+=2),e.offsetY!==void 0&&(a+=2),e.charSpacing!==void 0&&(a+=2),e.lineHeight!==void 0&&(a+=2),e.fontWeight!==void 0&&(a+=1+n.length),e.fontStyle!==void 0&&(a+=1+o.length);let s=x.allocUnsafe(a),d=0;s.writeUInt8(6,d++),s.writeUInt8(e.fontId,d++),s.writeUInt8(i,d++),s.writeUInt8(r.length,d++);for(let c=0;c<r.length;c++)s.writeUInt8(r[c],d++);if(s.writeUInt16BE(e.fontSize,d),d+=2,e.offsetX!==void 0&&(s.writeInt16BE(e.offsetX,d),d+=2),e.offsetY!==void 0&&(s.writeInt16BE(e.offsetY,d),d+=2),e.charSpacing!==void 0&&(s.writeInt16BE(e.charSpacing,d),d+=2),e.lineHeight!==void 0&&(s.writeUInt16BE(Math.round(e.lineHeight*100),d),d+=2),e.fontWeight!==void 0){s.writeUInt8(n.length,d++);for(let c=0;c<n.length;c++)s.writeUInt8(n[c],d++)}if(e.fontStyle!==void 0){s.writeUInt8(o.length,d++);for(let c=0;c<o.length;c++)s.writeUInt8(o[c],d++)}return s.toUint8Array()}encodeImageFont(e){if(![1,4,16].includes(e.atlasBlocks))throw new Error(`Invalid atlasBlocks: ${e.atlasBlocks}. Must be 1, 4, or 16.`);if(e.imageData.length>16*1024*1024)throw new Error(`Image data size ${e.imageData.length} exceeds maximum of 16MB`);let t=11+e.imageData.length,r=x.allocUnsafe(t),n=0;r.writeUInt8(8,n++),r.writeUInt8(e.fontId,n++),r.writeUInt8(e.glyphWidth,n++),r.writeUInt8(e.glyphHeight,n++),r.writeUInt8(e.cellWidth,n++),r.writeUInt8(e.cellHeight,n++),r.writeUInt8(e.atlasBlocks,n++),r.writeUInt32LE(e.imageData.length,n),n+=4;for(let o=0;o<e.imageData.length;o++)r.writeUInt8(e.imageData[o],n++);return r.toUint8Array()}};y(Kt,"LoadEncoder");var _=Kt;L();var Qt=class Qt{decode(e,t=0){let r=t,n=e.readUInt8(t++);if(n!==7)throw new Error(`Expected LoadType.Macro (0x07), got 0x${n.toString(16)}`);let o=e.readUInt8(t++),i=e.readUInt16BE(t);t+=2;let a=e.toUint8Array().subarray(t,t+i);t+=i;let s=new TextDecoder().decode(a),d=JSON.parse(s);return{load:{loadType:7,macroId:o,template:d},bytesRead:t-r}}};y(Qt,"MacroLoadDecoder");var Ze=Qt;var er=class er{decode(e,t=0){let r=x.from(e);if(t>=r.length)throw new Error("Buffer too short to decode load type");let n=r.readUInt8(t);switch(n){case 1:return this.decodeColorPalette(r,t);case 2:return this.decodeSprite(r,t);case 3:return this.decodeMulticolorSprite(r,t);case 4:return this.decodeBitmapFont(r,t);case 5:return this.decodeSound(r,t);case 6:return this.decodeWebFont(r,t);case 7:return this.decodeMacro(r,t);case 8:return this.decodeImageFont(r,t);default:throw new Error(`Unknown load type: 0x${n.toString(16)}`)}}decodeColorPalette(e,t){let r=t;this.checkSize(e,t,3,"ColorPalette header");let n=e.readUInt8(t++),i=e.readUInt8(t++)===255,a;i&&(this.checkSize(e,t,1,"ColorPalette slotId"),a=e.readUInt8(t++));let s=e.readUInt8(t++);this.checkSize(e,t,s*6,`ColorPalette ${s} colors`);let d=[];for(let l=0;l<s;l++)d.push({colorId:e.readUInt8(t++),r:e.readUInt8(t++),g:e.readUInt8(t++),b:e.readUInt8(t++),a:e.readUInt8(t++),e:e.readUInt8(t++)});return{load:{loadType:1,...a!==void 0&&{slotId:a},colors:d},bytesRead:t-r}}decodeSprite(e,t){let r=t;this.checkSize(e,t,2,"Sprite header");let n=e.readUInt8(t++),o=e.readUInt8(t++),i=[];for(let s=0;s<o;s++){this.checkSize(e,t,3,`Sprite ${s} header`);let d=e.readUInt8(t++),c=e.readUInt8(t++),l=e.readUInt8(t++),u=c*l;this.checkSize(e,t,u,`Sprite ${s} data`);let p=[];for(let m=0;m<u;m++)p.push(e.readUInt8(t++));i.push({spriteId:d,sizeX:c,sizeY:l,data:p})}return{load:{loadType:2,sprites:i},bytesRead:t-r}}decodeMulticolorSprite(e,t){let r=t;this.checkSize(e,t,2,"MulticolorSprite header");let n=e.readUInt8(t++),o=e.readUInt8(t++),i=[];for(let s=0;s<o;s++){this.checkSize(e,t,3,`MulticolorSprite ${s} header`);let d=e.readUInt8(t++),c=e.readUInt8(t++),l=e.readUInt8(t++),u=c*l,p=u*3;this.checkSize(e,t,p,`MulticolorSprite ${s} data`);let m=[];for(let g=0;g<u;g++)m.push({charCode:e.readUInt8(t++),fgColorId:e.readUInt8(t++),bgColorId:e.readUInt8(t++)});i.push({spriteId:d,sizeX:c,sizeY:l,data:m})}return{load:{loadType:3,sprites:i},bytesRead:t-r}}decodeBitmapFont(e,t){let r=t;this.checkSize(e,t,7,"BitmapFont header");let n=e.readUInt8(t++),o=e.readUInt8(t++),i=e.readUInt8(t++),a=e.readUInt8(t++),s=e.readUInt8(t++),d=e.readUInt8(t++),c=e.readUInt8(t++),l=Math.ceil(i*a/8),u=[];for(let m=0;m<c;m++){this.checkSize(e,t,1+l,`BitmapFont character ${m}`);let g=e.readUInt8(t++),C=new Uint8Array(l);for(let S=0;S<l;S++)C[S]=e.readUInt8(t++);u.push({charCode:g,bitmap:C})}return{load:{loadType:4,fontId:o,width:i,height:a,cellWidth:s,cellHeight:d,characters:u},bytesRead:t-r}}decodeSound(e,t){let r=t;this.checkSize(e,t,2,"Sound header");let n=e.readUInt8(t++),o=e.readUInt8(t++),i=[];for(let s=0;s<o;s++){this.checkSize(e,t,3,`Sound ${s} header`);let d=e.readUInt8(t++),c=e.readUInt16BE(t);t+=2,this.checkSize(e,t,c,`Sound ${s} MIDI data`);let l=new Uint8Array(c);for(let u=0;u<c;u++)l[u]=e.readUInt8(t++);i.push({soundId:d,midiData:l})}return{load:{loadType:5,sounds:i},bytesRead:t-r}}checkSize(e,t,r,n){if(t+r>e.length)throw new Error(`Buffer too short for ${n}: need ${r} bytes at offset ${t}, but only ${e.length-t} bytes remaining`)}decodeWebFont(e,t){let r=t,n=new TextDecoder;this.checkSize(e,t,5,"WebFont header");let o=e.readUInt8(t++),i=e.readUInt8(t++),a=e.readUInt8(t++),s=e.readUInt8(t++);this.checkSize(e,t,s,"WebFont family string");let d=new Uint8Array(s);for(let p=0;p<s;p++)d[p]=e.readUInt8(t++);let c=n.decode(d);this.checkSize(e,t,2,"WebFont fontSize");let l=e.readUInt16BE(t);t+=2;let u={loadType:6,fontId:i,fontFamily:c,fontSize:l};if(a&1&&(this.checkSize(e,t,2,"WebFont offsetX"),u.offsetX=e.readInt16BE(t),t+=2),a&2&&(this.checkSize(e,t,2,"WebFont offsetY"),u.offsetY=e.readInt16BE(t),t+=2),a&4&&(this.checkSize(e,t,2,"WebFont charSpacing"),u.charSpacing=e.readInt16BE(t),t+=2),a&8){this.checkSize(e,t,2,"WebFont lineHeight");let p=e.readUInt16BE(t);u.lineHeight=p/100,t+=2}if(a&16){this.checkSize(e,t,1,"WebFont weight length");let p=e.readUInt8(t++);this.checkSize(e,t,p,"WebFont weight string");let m=new Uint8Array(p);for(let g=0;g<p;g++)m[g]=e.readUInt8(t++);u.fontWeight=n.decode(m)}if(a&32){this.checkSize(e,t,1,"WebFont style length");let p=e.readUInt8(t++);this.checkSize(e,t,p,"WebFont style string");let m=new Uint8Array(p);for(let g=0;g<p;g++)m[g]=e.readUInt8(t++);u.fontStyle=n.decode(m)}return{load:u,bytesRead:t-r}}decodeMacro(e,t){return new Ze().decode(e,t)}decodeImageFont(e,t){let r=t;this.checkSize(e,t,7,"ImageFont header");let n=e.readUInt8(t++),o=e.readUInt8(t++),i=e.readUInt8(t++),a=e.readUInt8(t++),s=e.readUInt8(t++),d=e.readUInt8(t++),c=e.readUInt8(t++);if(![1,4,16].includes(c))throw new Error(`Invalid atlasBlocks value: ${c}. Must be 1, 4, or 16.`);let l=c;this.checkSize(e,t,4,"ImageFont image data size");let u=e.readUInt32LE(t);t+=4,this.checkSize(e,t,u,"ImageFont image data");let p=new Uint8Array(u);for(let g=0;g<u;g++)p[g]=e.readUInt8(t++);return{load:{loadType:8,fontId:o,glyphWidth:i,glyphHeight:a,cellWidth:s,cellHeight:d,atlasBlocks:l,imageData:p},bytesRead:t-r}}};y(er,"LoadDecoder");var je=er;var X=class X{constructor(e){this.engine=e;b(this,"colorCache",new Array(256));b(this,"cellsBuffer",[]);b(this,"opacityBuffer",new Uint8Array(0));b(this,"visibleLayersBuffer",[]);this.rebuildColorCache()}static getChar(e){let t=X.charCache.get(e);return t===void 0&&(t=String.fromCharCode(e),X.charCache.set(e,t)),t}rebuildColorCache(){for(let e=0;e<256;e++){let t=this.engine.getColor(e);t?this.colorCache[e]={r:t.r,g:t.g,b:t.b,a:t.a}:this.colorCache[e]={r:0,g:0,b:0,a:0}}}getColorRGB(e){return this.colorCache[e]??this.colorCache[255]}getColorEmission(e){let t=this.engine.getColor(e);return t?t.e:0}isLayerVisible(e,t){let r=e.x,n=e.x+e.width,o=e.y,i=e.y+e.height,a=t.x,s=t.x+256,d=t.y,c=t.y+256;return!(n<=a||r>=s||i<=d||o>=c)}rasterize(e,t){let r=e.width*e.height,n=this.cellsBuffer;n.length=r;for(let s=0;s<r;s++)n[s]?(n[s].char=" ",n[s].fgColorIndex=255,n[s].bgColorIndex=255,n[s].fgEmission=0,n[s].bgEmission=0):n[s]={char:" ",fgColorIndex:255,bgColorIndex:255,fgEmission:0,bgEmission:0};this.opacityBuffer.length<r?this.opacityBuffer=new Uint8Array(r):this.opacityBuffer.fill(0,0,r);let o=this.opacityBuffer,i=this.visibleLayersBuffer;i.length=0;for(let s=0;s<t.length;s++){let d=t[s];d.isEnabled()&&this.isLayerVisible(e,d.getOrigin())&&i.push(d)}i.sort((s,d)=>d.getZOrder()-s.getZOrder());for(let s=0;s<e.height;s++)for(let d=0;d<e.width;d++){let c=s*e.width+d;if(o[c])continue;let l=e.x+d,u=e.y+s;for(let p=0;p<i.length;p++){let m=i[p],g=l-m.getOrigin().x,C=u-m.getOrigin().y,S=m.getWidth(),O=m.getHeight();if(g<0||g>=S||C<0||C>=O)continue;let I=C*S+g,w=m.getData(),U=w.getCharCode(I),P=w.getFgColorCode(I),R=w.getBgColorCode(I),M=n[c];if(U!==0&&M.char===" "&&(M.char=X.getChar(U)),P!==255&&M.fgColorIndex===255&&(M.fgColorIndex=P,M.fgEmission=this.getColorEmission(P)),R!==255){M.bgColorIndex===255&&(M.bgColorIndex=R,M.bgEmission=this.getColorEmission(R)),o[c]=1;break}}}let a=new Array(r);for(let s=0;s<r;s++)a[s]={char:n[s].char,fgColorIndex:n[s].fgColorIndex,bgColorIndex:n[s].bgColorIndex,fgEmission:n[s].fgEmission,bgEmission:n[s].bgEmission};return{width:e.width,height:e.height,cells:a,palette:this.colorCache}}rasterizeWithSortedLayers(e,t){let r=e.width*e.height,n=this.cellsBuffer;n.length=r;for(let s=0;s<r;s++)n[s]?(n[s].char=" ",n[s].fgColorIndex=255,n[s].bgColorIndex=255,n[s].fgEmission=0,n[s].bgEmission=0):n[s]={char:" ",fgColorIndex:255,bgColorIndex:255,fgEmission:0,bgEmission:0};this.opacityBuffer.length<r?this.opacityBuffer=new Uint8Array(r):this.opacityBuffer.fill(0,0,r);let o=this.opacityBuffer,i=this.visibleLayersBuffer;i.length=0;for(let s=0;s<t.length;s++){let d=t[s];this.isLayerVisible(e,d.getOrigin())&&i.push(d)}for(let s=0;s<e.height;s++)for(let d=0;d<e.width;d++){let c=s*e.width+d;if(o[c])continue;let l=e.x+d,u=e.y+s;for(let p=0;p<i.length;p++){let m=i[p],g=l-m.getOrigin().x,C=u-m.getOrigin().y,S=m.getWidth(),O=m.getHeight();if(g<0||g>=S||C<0||C>=O)continue;let I=C*S+g,w=m.getData(),U=w.getCharCode(I),P=w.getFgColorCode(I),R=w.getBgColorCode(I),M=n[c];if(U!==0&&M.char===" "&&(M.char=X.getChar(U)),P!==255&&M.fgColorIndex===255&&(M.fgColorIndex=P,M.fgEmission=this.getColorEmission(P)),R!==255){M.bgColorIndex===255&&(M.bgColorIndex=R,M.bgEmission=this.getColorEmission(R)),o[c]=1;break}}}let a=new Array(r);for(let s=0;s<r;s++)a[s]={char:n[s].char,fgColorIndex:n[s].fgColorIndex,bgColorIndex:n[s].bgColorIndex,fgEmission:n[s].fgEmission,bgEmission:n[s].bgEmission};return{width:e.width,height:e.height,cells:a,palette:this.colorCache}}calculateIntersection(e,t){let r=e.x,n=e.x+e.width,o=e.y,i=e.y+e.height,a=t.x,s=t.x+256,d=t.y,c=t.y+256,l=Math.max(r,a),u=Math.min(n,s),p=Math.max(o,d),m=Math.min(i,c);return{visible:l<u&&p<m,originStart:{x:l-e.x,y:p-e.y},originEnd:{x:u-e.x,y:m-e.y},layerStart:{x:l-t.x,y:p-t.y},layerEnd:{x:u-t.x,y:m-t.y}}}};y(X,"DisplayRasterizer"),b(X,"charCache",(()=>{let e=new Map;for(let t=0;t<256;t++)e.set(t,String.fromCharCode(t));return e})());var Je=X;var tr=class tr{constructor(){b(this,"enabled",!1);b(this,"currentStats",null)}setEnabled(e){this.enabled=e,e||(this.currentStats=null)}isEnabled(){return this.enabled}get tick(){return this.currentStats?.tick??0}get timestamp(){return this.currentStats?.timestamp??0}get totalOrders(){return this.currentStats?.totalOrders??0}get ordersByLayer(){return this.currentStats?.ordersByLayer??new Map}get ordersByType(){return this.currentStats?.ordersByType??new Map}get totalLayers(){return this.currentStats?.totalLayers??0}get visibleLayers(){return this.currentStats?.visibleLayers??0}get layersPerDisplay(){return this.currentStats?.layersPerDisplay??new Map}get updatePacketSize(){return this.currentStats?.updatePacketSize??0}get displayHeaderSize(){return this.currentStats?.displayHeaderSize??0}get layerHeaderSize(){return this.currentStats?.layerHeaderSize??0}get orderDataSize(){return this.currentStats?.orderDataSize??0}get compressionRatio(){return this.currentStats?.compressionRatio??0}get compressedPacketSize(){return Math.round(this.updatePacketSize*this.compressionRatio)}get totalCells(){return this.currentStats?.totalCells??0}get nonEmptyCells(){return this.currentStats?.nonEmptyCells??0}get cellsWithBackground(){return this.currentStats?.cellsWithBackground??0}get rasterizationTimeMs(){return this.currentStats?.rasterizationTimeMs??0}get encodingTimeMs(){return this.currentStats?.encodingTimeMs??0}get packetSplit(){return this.currentStats?.packetSplit}get layerDetails(){return this.currentStats?.layerDetails}startTick(e){this.enabled&&(this.currentStats={tick:e,timestamp:Date.now(),totalOrders:0,ordersByLayer:new Map,ordersByType:new Map,totalLayers:0,visibleLayers:0,layersPerDisplay:new Map,updatePacketSize:0,displayHeaderSize:0,layerHeaderSize:0,orderDataSize:0,compressionRatio:0,totalCells:0,nonEmptyCells:0,cellsWithBackground:0,rasterizationTimeMs:0,encodingTimeMs:0})}recordLayerOrders(e,t){if(!(!this.enabled||!this.currentStats)){this.currentStats.totalOrders+=t.length,this.currentStats.ordersByLayer.set(e,t.length);for(let r of t){let n=this.currentStats.ordersByType.get(r.type)||0;this.currentStats.ordersByType.set(r.type,n+1)}}}recordLayers(e,t){!this.enabled||!this.currentStats||(this.currentStats.totalLayers=e,this.currentStats.visibleLayers=t)}recordDisplayLayers(e,t){!this.enabled||!this.currentStats||this.currentStats.layersPerDisplay.set(e,t)}recordUpdatePacketSize(e,t,r,n){!this.enabled||!this.currentStats||(this.currentStats.updatePacketSize=e,this.currentStats.displayHeaderSize=t,this.currentStats.layerHeaderSize=r,this.currentStats.orderDataSize=n,this.currentStats.compressionRatio=.25)}recordPacketSplit(e,t,r,n){!this.enabled||!this.currentStats||(this.currentStats.packetSplit={userId:e,displayCount:t,staticLayerCount:r,dynamicLayerCount:n})}recordLayerInfo(e,t,r,n){!this.enabled||!this.currentStats||(this.currentStats.layerDetails||(this.currentStats.layerDetails=[]),this.currentStats.layerDetails.push({layerId:e,isStatic:t,orderCount:r,updateFlags:n}))}recordRenderStats(e,t,r){!this.enabled||!this.currentStats||(this.currentStats.totalCells=e,this.currentStats.nonEmptyCells=t,this.currentStats.cellsWithBackground=r)}recordRasterizationTime(e){!this.enabled||!this.currentStats||(this.currentStats.rasterizationTimeMs=e)}recordEncodingTime(e){!this.enabled||!this.currentStats||(this.currentStats.encodingTimeMs=e)}endTick(){}reset(){this.currentStats=null}};y(tr,"CoreStats");var be=tr;var rr=class rr{constructor(){b(this,"unicolorSprites",new Map);b(this,"multicolorSprites",new Map)}loadUnicolorSprites(e){for(let t of e.sprites){let r=new oe(t.sizeX*t.sizeY);for(let o=0;o<t.data.length;o++)r.set(o,t.data[o]);let n={id:t.spriteId,sizeX:t.sizeX,sizeY:t.sizeY,data:r};this.unicolorSprites.set(n.id,n)}}loadMulticolorSprites(e){for(let t of e.sprites){let r=new G(t.sizeX*t.sizeY);for(let o=0;o<t.data.length;o++){let i=t.data[o];r.set(o,i.charCode,i.fgColorId,i.bgColorId)}let n={id:t.spriteId,sizeX:t.sizeX,sizeY:t.sizeY,data:r};this.multicolorSprites.set(n.id,n)}}getUnicolorSprite(e){return this.unicolorSprites.get(e)}getMulticolorSprite(e){return this.multicolorSprites.get(e)}hasUnicolorSprite(e){return this.unicolorSprites.has(e)}hasMulticolorSprite(e){return this.multicolorSprites.has(e)}unloadUnicolorSprite(e){return this.unicolorSprites.delete(e)}unloadMulticolorSprite(e){return this.multicolorSprites.delete(e)}clearUnicolorSprites(){this.unicolorSprites.clear()}clearMulticolorSprites(){this.multicolorSprites.clear()}clearAll(){this.unicolorSprites.clear(),this.multicolorSprites.clear()}getUnicolorSpriteCount(){return this.unicolorSprites.size}getMulticolorSpriteCount(){return this.multicolorSprites.size}getTotalSpriteCount(){return this.unicolorSprites.size+this.multicolorSprites.size}};y(rr,"SpriteRegistry");var ge=rr;var Bn=(r=>(r.Web="web",r.Bitmap="bitmap",r.Image="image",r))(Bn||{});function nr(h){return Math.sqrt(h)*16}y(nr,"getAtlasColumns");function zn(h){return h*256-1}y(zn,"getMaxCharCode");function mo(h,e){let r=nr(h)*e;return{width:r,height:r}}y(mo,"getAtlasDimensions");var or=class or{constructor(e,t){this.fontId=e;this.config=t}getFontId(){return this.fontId}getConfig(){return{...this.config}}getFontFamily(){return this.config.fontFamily}getFontSize(){return this.config.fontSize}getOffsetX(){return this.config.offsetX??0}getOffsetY(){return this.config.offsetY??0}getCharSpacing(){return this.config.charSpacing??0}getLineHeight(){return this.config.lineHeight??1.2}getFontWeight(){return this.config.fontWeight??"normal"}getFontStyle(){return this.config.fontStyle??"normal"}toCSS(){let e=[];e.push(`font-family: ${this.config.fontFamily}`),e.push(`font-size: ${this.config.fontSize}px`);let t=this.config.fontWeight??"normal";t!=="normal"&&e.push(`font-weight: ${t}`);let r=this.config.fontStyle??"normal";return r!=="normal"&&e.push(`font-style: ${r}`),e.join("; ")+";"}};y(or,"WebFont");var $=or,ir=class ir{constructor(e,t){this.fontId=e;this.config=t}getFontId(){return this.fontId}getConfig(){return{charWidth:this.config.charWidth,charHeight:this.config.charHeight,cellWidth:this.config.cellWidth,cellHeight:this.config.cellHeight,glyphs:new Map(this.config.glyphs)}}getCharWidth(){return this.config.charWidth}getCharHeight(){return this.config.charHeight}getCellWidth(){return this.config.cellWidth??this.config.charWidth}getCellHeight(){return this.config.cellHeight??this.config.charHeight}getGlyph(e){return this.config.glyphs.get(e)}hasGlyph(e){return this.config.glyphs.has(e)}getGlyphCount(){return this.config.glyphs.size}getCharCodes(){return Array.from(this.config.glyphs.keys())}};y(ir,"BitmapFont");var ye=ir,ar=class ar{constructor(e,t){this.fontId=e;this.config=t;b(this,"atlasColumns");b(this,"maxCharCode");this.atlasColumns=nr(t.atlasBlocks),this.maxCharCode=zn(t.atlasBlocks)}getFontId(){return this.fontId}getConfig(){return{glyphWidth:this.config.glyphWidth,glyphHeight:this.config.glyphHeight,cellWidth:this.config.cellWidth,cellHeight:this.config.cellHeight,atlasBlocks:this.config.atlasBlocks,imageData:this.config.imageData}}getGlyphWidth(){return this.config.glyphWidth}getGlyphHeight(){return this.config.glyphHeight}getCellWidth(){return this.config.cellWidth??this.config.glyphWidth}getCellHeight(){return this.config.cellHeight??this.config.glyphHeight}getAtlasBlocks(){return this.config.atlasBlocks}getAtlasColumns(){return this.atlasColumns}getMaxCharCode(){return this.maxCharCode}getImageData(){return this.config.imageData}getAtlasDimensions(){return{width:this.atlasColumns*this.config.glyphWidth,height:this.atlasColumns*this.config.glyphHeight}}getCharUV(e){if(e<0||e>this.maxCharCode)return null;let t=e%this.atlasColumns,r=Math.floor(e/this.atlasColumns),n=t/this.atlasColumns,o=r/this.atlasColumns,i=(t+1)/this.atlasColumns,a=(r+1)/this.atlasColumns;return{u1:n,v1:o,u2:i,v2:a}}isValidCharCode(e){return e>=0&&e<=this.maxCharCode}};y(ar,"ImageFont");var q=ar;var sr=class sr{constructor(){b(this,"fonts",new Map)}loadFont(e,t){if(this.fonts.has(e))throw new Error(`WebFont with ID ${e} already exists`);let r=new $(e,t);this.fonts.set(e,r)}getFont(e){return this.fonts.get(e)}hasFont(e){return this.fonts.has(e)}unloadFont(e){return this.fonts.delete(e)}clearFonts(){this.fonts.clear()}getFontIds(){return Array.from(this.fonts.keys()).sort((e,t)=>e-t)}getAllFonts(){return Array.from(this.fonts.entries()).sort((e,t)=>e[0]-t[0]).map(e=>e[1])}getFontCount(){return this.fonts.size}};y(sr,"WebFontRegistry");var Ce=sr;var dr=class dr{constructor(){b(this,"fonts",new Map)}loadFont(e,t){if(this.fonts.has(e))throw new Error(`BitmapFont with ID ${e} already exists`);let r=new ye(e,t);this.fonts.set(e,r)}getFont(e){return this.fonts.get(e)}hasFont(e){return this.fonts.has(e)}unloadFont(e){return this.fonts.delete(e)}clearFonts(){this.fonts.clear()}getFontIds(){return Array.from(this.fonts.keys()).sort((e,t)=>e-t)}getAllFonts(){return Array.from(this.fonts.entries()).sort((e,t)=>e[0]-t[0]).map(e=>e[1])}getFontCount(){return this.fonts.size}};y(dr,"BitmapFontRegistry");var xe=dr;var cr=class cr{constructor(){b(this,"fonts",new Map);b(this,"nameToId",new Map);b(this,"nextId",0)}allocateId(e){if(this.nextId>255)throw new Error(`Cannot register font "${e}": maximum 256 fonts reached`);return this.nextId++}registerFont(e,t,r){if(this.nameToId.has(e))throw new Error(`ImageFont with name "${e}" already exists`);let n=this.allocateId(e),o={glyphWidth:t.glyphWidth,glyphHeight:t.glyphHeight,cellWidth:t.cellWidth,cellHeight:t.cellHeight,atlasBlocks:t.atlasBlocks??1,imageData:r},i=new q(n,o);return this.fonts.set(n,i),this.nameToId.set(e,n),n}loadFont(e,t){if(this.fonts.has(e))throw new Error(`ImageFont with ID ${e} already exists`);let r=new q(e,t);this.fonts.set(e,r),e>=this.nextId&&(this.nextId=e+1)}getFont(e){return this.fonts.get(e)}getFontByName(e){let t=this.nameToId.get(e);if(t!==void 0)return this.fonts.get(t)}getFontId(e){return this.nameToId.get(e)}getFontName(e){for(let[t,r]of this.nameToId.entries())if(r===e)return t}hasFont(e){return this.fonts.has(e)}hasFontByName(e){return this.nameToId.has(e)}unloadFont(e){if(!this.fonts.get(e))return!1;for(let[r,n]of this.nameToId.entries())if(n===e){this.nameToId.delete(r);break}return this.fonts.delete(e)}unloadFontByName(e){let t=this.nameToId.get(e);return t===void 0?!1:(this.nameToId.delete(e),this.fonts.delete(t))}clearFonts(){this.fonts.clear(),this.nameToId.clear(),this.nextId=0}getFontIds(){return Array.from(this.fonts.keys()).sort((e,t)=>e-t)}getFontNames(){return Array.from(this.nameToId.keys())}getAllFonts(){return Array.from(this.fonts.entries()).sort((e,t)=>e[0]-t[0]).map(e=>e[1])}getFontCount(){return this.fonts.size}};y(cr,"ImageFontRegistry");var fe=cr;var lr=class lr{constructor(){b(this,"sounds",new Map);b(this,"nameToId",new Map);b(this,"nextId",0)}registerFile(e,t,r){let n=this.allocateId(e),o={soundId:n,name:e,loadType:"file",format:t,data:r};return this.sounds.set(n,o),this.nameToId.set(e,n),n}registerFileWithId(e,t,r,n){this.validateId(e),this.checkIdAvailable(e,t);let o={soundId:e,name:t,loadType:"file",format:r,data:n};this.sounds.set(e,o),this.nameToId.set(t,e)}registerExternal(e,t,r,n,o){let i=this.allocateId(e),a={soundId:i,name:e,loadType:"external",format:t,url:r,size:n,checksum:o};return this.sounds.set(i,a),this.nameToId.set(e,i),i}registerExternalWithId(e,t,r,n,o,i){this.validateId(e),this.checkIdAvailable(e,t);let a={soundId:e,name:t,loadType:"external",format:r,url:n,size:o,checksum:i};this.sounds.set(e,a),this.nameToId.set(t,e)}get(e){if(typeof e=="number")return this.sounds.get(e);let t=this.nameToId.get(e);return t!==void 0?this.sounds.get(t):void 0}has(e){return this.get(e)!==void 0}getAll(){return Array.from(this.sounds.values())}getFileSounds(){return this.getAll().filter(e=>e.loadType==="file")}getExternalSounds(){return this.getAll().filter(e=>e.loadType==="external")}getNames(){return Array.from(this.nameToId.keys())}getId(e){return this.nameToId.get(e)}toLoadPackets(){let e=[],t=this.sounds.size,r=this.getFileSounds();if(r.length>0){let o=r.map(i=>({soundId:i.soundId,name:i.name,format:i.format,data:i.data}));e.push({type:"sound",mode:"file",sounds:o,totalSounds:t})}let n=this.getExternalSounds();if(n.length>0){let o=n.map(i=>({soundId:i.soundId,name:i.name,format:i.format,url:i.url,size:i.size,checksum:i.checksum}));e.push({type:"sound",mode:"external",sounds:o,totalSounds:t})}return e}toLoadPacket(e){let t=this.get(e);return t?t.loadType==="file"?{type:"sound",mode:"file",sounds:[{soundId:t.soundId,name:t.name,format:t.format,data:t.data}]}:{type:"sound",mode:"external",sounds:[{soundId:t.soundId,name:t.name,format:t.format,url:t.url,size:t.size,checksum:t.checksum}]}:null}unregister(e){let t=this.get(e);return t?(this.sounds.delete(t.soundId),this.nameToId.delete(t.name),!0):!1}clear(){this.sounds.clear(),this.nameToId.clear(),this.nextId=0}get size(){return this.sounds.size}getStats(){let e=this.getAll(),t=e.filter(n=>n.loadType==="file"),r=t.reduce((n,o)=>n+(o.data?.length??0),0);return{total:e.length,file:t.length,external:e.length-t.length,totalFileSize:r}}allocateId(e){if(this.nameToId.has(e))throw new Error(`Sound with name "${e}" already exists`);for(;this.sounds.has(this.nextId);)if(this.nextId++,this.nextId>255)throw new Error("Maximum number of sounds (256) reached");return this.nextId++}validateId(e){if(!Number.isInteger(e)||e<0||e>255)throw new Error(`Invalid sound ID: ${e}. Must be an integer between 0 and 255.`)}checkIdAvailable(e,t){if(this.sounds.has(e)){let r=this.sounds.get(e);throw new Error(`Sound ID ${e} is already used by "${r.name}". Cannot register "${t}".`)}if(this.nameToId.has(t))throw new Error(`Sound with name "${t}" already exists`)}};y(lr,"SoundRegistry");var Se=lr;var ur=class ur{constructor(e){this.soundRegistry=e}collectFromUser(e){let t=[],r=e.flushSoundCommands();for(let o of r){let i=this.convertSoundCommand(o);i&&t.push(i)}let n=e.flushAudioConfigCommands();for(let o of n){let i=this.convertConfigCommand(o);i&&t.push(i)}return t}convertSoundCommand(e){return"setEffects"in e&&e.setEffects===!0?this.convertSetEffectsCommand(e):"fadeOut"in e&&e.fadeOut===!0?this.convertFadeOutCommand(e):"pause"in e&&e.pause===!0?this.convertPauseCommand(e):"resume"in e&&e.resume===!0?this.convertResumeCommand(e):"instanceId"in e||"volume"in e||"pitch"in e||"loop"in e||"fadeIn"in e||"x"in e||"y"in e||"lowpass"in e||"highpass"in e||"reverb"in e?this.convertPlayCommand(e):this.convertStopCommand(e)}convertPlayCommand(e){let t=this.resolveSoundId(e.sound);if(t===null)return console.warn(`[AudioOrderCollector] Unknown sound: ${e.sound}`),null;let r=0;e.loop&&(r|=1),e.volume!==void 0&&(r|=2),e.pitch!==void 0&&(r|=4),e.fadeIn!==void 0&&(r|=8),e.lowpass!==void 0&&e.lowpass>0&&(r|=32),e.highpass!==void 0&&e.highpass>0&&(r|=64),e.reverb!==void 0&&e.reverb>0&&(r|=128);let n=e.x!==void 0&&e.y!==void 0;return n&&(r|=16),n?{type:1,soundId:t,instanceId:e.instanceId??0,flags:r,volume:e.volume!==void 0?this.encodeVolume(e.volume):void 0,pitch:e.pitch!==void 0?this.encodePitch(e.pitch):void 0,fadeIn:e.fadeIn!==void 0?this.encodeFadeTime(e.fadeIn):void 0,posX:this.encodePosition(e.x),posY:this.encodePosition(e.y),lowpass:e.lowpass!==void 0&&e.lowpass>0?this.encodeFilterFreq(e.lowpass):void 0,highpass:e.highpass!==void 0&&e.highpass>0?this.encodeFilterFreq(e.highpass):void 0,reverb:e.reverb!==void 0&&e.reverb>0?this.encodeReverb(e.reverb):void 0}:{type:2,soundId:t,instanceId:e.instanceId??0,flags:r&-17,volume:e.volume!==void 0?this.encodeVolume(e.volume):void 0,pitch:e.pitch!==void 0?this.encodePitch(e.pitch):void 0,fadeIn:e.fadeIn!==void 0?this.encodeFadeTime(e.fadeIn):void 0,lowpass:e.lowpass!==void 0&&e.lowpass>0?this.encodeFilterFreq(e.lowpass):void 0,highpass:e.highpass!==void 0&&e.highpass>0?this.encodeFilterFreq(e.highpass):void 0,reverb:e.reverb!==void 0&&e.reverb>0?this.encodeReverb(e.reverb):void 0}}convertStopCommand(e){let{targetType:t,target:r}=this.resolveTarget(e.sound);return{type:3,targetType:t,target:r}}convertFadeOutCommand(e){let{targetType:t,target:r}=this.resolveTarget(e.sound);return{type:4,targetType:t,duration:this.encodeFadeTime(e.duration),target:r}}convertPauseCommand(e){let{targetType:t,target:r}=this.resolveTarget(e.sound);return{type:5,targetType:t,target:r}}convertResumeCommand(e){let{targetType:t,target:r}=this.resolveTarget(e.sound);return{type:6,targetType:t,target:r}}convertSetEffectsCommand(e){let t=0;return e.lowpass!==void 0&&(t|=1),e.highpass!==void 0&&(t|=2),e.reverb!==void 0&&(t|=4),{type:9,instanceId:e.instanceId,flags:t,lowpass:e.lowpass!==void 0?this.encodeFilterFreq(e.lowpass):void 0,highpass:e.highpass!==void 0?this.encodeFilterFreq(e.highpass):void 0,reverb:e.reverb!==void 0?this.encodeReverb(e.reverb):void 0}}convertConfigCommand(e){return e.type==="set-listener-position"?{type:7,x:this.encodePosition(e.x),y:this.encodePosition(e.y)}:e.type==="configure-spatial"?{type:8,maxDistance:this.encodeDistance(e.maxDistance??1e3),referenceDistance:this.encodeDistance(e.referenceDistance??100),rolloffFactor:this.encodeRolloff(e.rolloffFactor??1),panSpread:this.encodePanSpread(e.panSpread??.5)}:null}resolveSoundId(e){if(typeof e=="number")return e>=0&&e<=255?e:null;let t=this.soundRegistry.getId(e);return t!==void 0?t:null}resolveTarget(e){if(e==="all")return{targetType:2,target:void 0};if(typeof e=="number")return{targetType:0,target:e};let t=this.soundRegistry.getId(e);return t!==void 0?{targetType:1,target:t}:(console.warn(`[AudioOrderCollector] Unknown sound name: ${e}, treating as 'all'`),{targetType:2,target:void 0})}encodeVolume(e){return Math.round(Math.max(0,Math.min(1,e))*255)}encodePitch(e){let t=Math.max(.25,Math.min(4,e)),r=64*Math.log2(t/.25);return Math.round(Math.max(0,Math.min(255,r)))}encodeFadeTime(e){return Math.round(Math.max(0,Math.min(25.5,e))*10)}encodeDistance(e){return Math.round(Math.max(0,Math.min(25500,e))/100)}encodeRolloff(e){return Math.round(Math.max(0,Math.min(2.55,e))*100)}encodePanSpread(e){return Math.round(Math.max(0,Math.min(1,e))*255)}encodePosition(e){return Math.round(Math.max(0,Math.min(65535,e)))}encodeFilterFreq(e){return e<=0?0:Math.round(Math.max(1,Math.min(255,e/100)))}encodeReverb(e){return Math.round(Math.max(0,Math.min(1,e))*255)}};y(ur,"AudioOrderCollector");var Ie=ur;var pr=class pr{collectFromUser(e){let t=[];if(e.hasMobileVibrationCommands()){let r=e.flushMobileVibrationCommands();for(let n of r){let o=this.convertMobileCommand(n);o&&t.push(o)}}if(e.hasGamepadVibrationCommands()){let r=e.flushGamepadVibrationCommands();for(let n of r){let o=this.convertGamepadCommand(n);o&&t.push(o)}}return t}convertMobileCommand(e){return"cancel"in e&&e.cancel===!0?this.convertMobileCancelCommand():"pattern"in e?this.convertMobileVibrateCommand(e):null}convertMobileVibrateCommand(e){let t=0;e.intensity!==void 0&&e.intensity!==1&&(t|=1);let r=e.pattern,n=Array.isArray(r)?[...r]:[r],o={type:1,flags:t,pattern:n.map(i=>Math.round(i))};return t&1&&(o.intensity=Math.round(Math.min(1,Math.max(0,e.intensity))*255)/255),o}convertMobileCancelCommand(){return{type:2}}convertGamepadCommand(e){if("cancel"in e&&e.cancel===!0){let t=e.gamepadIndex??"all";return this.convertGamepadCancelCommand({gamepadIndex:t})}if("options"in e&&e.options){let t=e.gamepadIndex??0;return this.convertGamepadVibrateCommand({gamepadIndex:t,options:e.options})}return null}convertGamepadVibrateCommand(e){let{gamepadIndex:t,options:r}=e,n=0;r.startDelay!==void 0&&r.startDelay>0&&(n|=1);let o=t==="all"?255:t;t==="all"&&(n|=2);let i={type:16,flags:n,gamepadIndex:o,duration:Math.round(r.duration),strongMagnitude:Math.round(Math.min(1,Math.max(0,r.strongMagnitude??1))*255),weakMagnitude:Math.round(Math.min(1,Math.max(0,r.weakMagnitude??.5))*255)};return r.startDelay!==void 0&&r.startDelay>0&&(i.startDelay=Math.round(r.startDelay)),i}convertGamepadCancelCommand(e){let{gamepadIndex:t}=e,r=0,n=t==="all"?255:t;return t==="all"&&(r|=2),{type:17,flags:r,gamepadIndex:n}}};y(pr,"VibrationOrderCollector");var Oe=pr;import{POST_PROCESS_DEFAULTS as N,GRID_DEFAULTS as Tn,scalingModeToValue as ho}from"@utsp/types";var mr=class mr{collectFromUser(e){let t=e.flushPostProcessCommands();return this.convertCommands(t)}convertCommands(e){let t=[];for(let r of e){let n=this.convertCommand(r);n&&t.push(n)}return t}convertCommand(e){let t=e.displayId;switch(e.type){case"set-config":return this.convertSetConfig(e);case"set-scanlines-enabled":return this.createSetScanlinesOrder(t,e.enabled??!1,e.opacity);case"set-scanlines-opacity":return this.createSetScanlinesOrder(t,!0,e.opacity??N.scanlines.opacity);case"set-ambient-effect-enabled":return this.createSetAmbientEffectOrder(t,e.enabled??!1);case"set-ambient-effect-blur":return this.createSetAmbientEffectOrder(t,!0,e.blur);case"set-ambient-effect-scale":return this.createSetAmbientEffectOrder(t,!0,void 0,e.scale);case"set-scaling-mode":return this.createSetScalingModeOrder(t,e.scalingMode);case"set-grid":return this.createSetGridOrder(t,e.gridConfig);case"switch-palette":return this.createSwitchPaletteOrder(t,e.paletteSlotId);case"set-cell-size":return this.createSetCellSizeOrder(t,e.cellWidth,e.cellHeight);default:return console.warn(`[PostProcessOrderCollector] Unknown command type: ${e.type}`),null}}convertSetConfig(e){let t=e.displayId;if(!e.config)return{type:1,displayId:t,flags:3,scanlines:{enabled:!1,opacity:0,pattern:0,colorR:0,colorG:0,colorB:0},ambientEffect:{enabled:!1,blur:0,scale:1,opacity:0}};let r=0,n={type:1,displayId:t,flags:0};if(e.config.scanlines){r|=1;let o=e.config.scanlines;n.scanlines={enabled:o.enabled,opacity:o.opacity??N.scanlines.opacity,pattern:this.patternToType(o.pattern??"horizontal"),colorR:o.color?.r??0,colorG:o.color?.g??0,colorB:o.color?.b??0}}if(e.config.ambientEffect){r|=2;let o=e.config.ambientEffect;n.ambientEffect={enabled:o.enabled,blur:o.blur??N.ambientEffect.blur,scale:o.scale??N.ambientEffect.scale,opacity:o.opacity??N.ambientEffect.opacity}}return n.flags=r,n}createSetScanlinesOrder(e,t,r){return{type:2,displayId:e,enabled:t,opacity:r??N.scanlines.opacity,pattern:0,colorR:0,colorG:0,colorB:0}}createSetAmbientEffectOrder(e,t,r,n){return{type:3,displayId:e,enabled:t,blur:r??N.ambientEffect.blur,scale:n??N.ambientEffect.scale,opacity:N.ambientEffect.opacity}}patternToType(e){switch(e){case"horizontal":return 0;case"vertical":return 1;case"grid":return 2;default:return 0}}createSetScalingModeOrder(e,t){return{type:4,displayId:e,mode:ho(t)}}createSetGridOrder(e,t){let{r,g:n,b:o,a:i}=this.parseColor(t.color??Tn.color);return{type:5,displayId:e,enabled:t.enabled,colorR:r,colorG:n,colorB:o,colorA:i,lineWidth:t.lineWidth??Tn.lineWidth}}createSwitchPaletteOrder(e,t){return{type:6,displayId:e,slotId:t}}createSetCellSizeOrder(e,t,r){return{type:7,displayId:e,cellWidth:t,cellHeight:r}}parseColor(e){let t=e.match(/rgba?\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*([\d.]+))?\s*\)/);if(t)return{r:parseInt(t[1],10),g:parseInt(t[2],10),b:parseInt(t[3],10),a:t[4]?Math.round(parseFloat(t[4])*255):255};let r=e.match(/^#([0-9a-fA-F]{6}|[0-9a-fA-F]{3})$/);if(r){let n=r[1];return n.length===3?{r:parseInt(n[0]+n[0],16),g:parseInt(n[1]+n[1],16),b:parseInt(n[2]+n[2],16),a:255}:{r:parseInt(n.slice(0,2),16),g:parseInt(n.slice(2,4),16),b:parseInt(n.slice(4,6),16),a:255}}return{r:144,g:24,b:24,a:255}}};y(mr,"PostProcessOrderCollector");var we=mr;var Z=class Z{constructor(e={}){b(this,"users",new Map);b(this,"mode");b(this,"maxUsers");b(this,"strictMode");b(this,"currentTick",0);b(this,"encoder");b(this,"displayRasterizer");b(this,"colorPalette",new Map);b(this,"stats",new be);b(this,"spriteRegistry",new ge);b(this,"webFontRegistry",new Ce);b(this,"bitmapFontRegistry",new xe);b(this,"imageFontRegistry",new fe);b(this,"soundRegistry",new Se);b(this,"audioOrderCollector");b(this,"vibrationOrderCollector");b(this,"postProcessOrderCollector");b(this,"activeWebFontId",0);b(this,"_renderCallCount",0);b(this,"paletteSlots",new Map);b(this,"onPaletteChangedCallback");b(this,"onBitmapFontChangedCallback");b(this,"onImageFontChangedCallback");this.mode=e.mode??"server",this.maxUsers=e.maxUsers??64,this.strictMode=e.strictMode??!1,this.encoder=new Ge,this.displayRasterizer=new Je(this),this.audioOrderCollector=new Ie(this.soundRegistry),this.vibrationOrderCollector=new Oe,this.postProcessOrderCollector=new we,this.initializeDefaultPalette(),this.displayRasterizer.rebuildColorCache(),this.loadDefaultWebFont()}initializeDefaultPalette(){Z.ANSI_VGA_COLORS.forEach(e=>{this.colorPalette.set(e.colorId,{r:e.r,g:e.g,b:e.b,a:e.a,e:e.e})}),this.colorPalette.set(255,{r:0,g:0,b:0,a:0,e:0})}getMode(){return this.mode}getMaxUsers(){return this.maxUsers}isStrictMode(){return this.strictMode}isServer(){return this.mode==="server"}isClient(){return this.mode==="client"}isStandalone(){return this.mode==="standalone"}createUser(e,t){if(this.users.has(e))throw new Error(`User with ID ${e} already exists`);if(this.mode==="server"&&this.users.size>=this.maxUsers)throw new Error(`Maximum number of users reached (${this.maxUsers}). Cannot create user ${e}`);if(this.mode==="client"&&this.users.size>=1)throw new Error(`Client mode only allows one user. Cannot create user ${e}`);let r=new me(e,t,this.mode);return r.setSpriteRegistry(this.spriteRegistry),this.users.set(e,r),r}getUser(e){return this.users.get(e)??null}getUsers(){return Array.from(this.users.values())}hasUser(e){return this.users.has(e)}removeUser(e){return this.users.delete(e)}getUserCount(){return this.users.size}clearAllUsers(){this.users.clear()}setColor(e,t,r,n,o=255,i=0){if(e<0||e>255)throw new Error(`Color ID must be between 0 and 255, got ${e}`);if(e>=240)throw new Error("Color IDs 240-255 are reserved (240-254: UI palette, 255: skip color). Use IDs 0-239 for custom colors.");if(t<0||t>255||r<0||r>255||n<0||n>255||o<0||o>255||i<0||i>255)throw new Error("Color components must be between 0 and 255");this.colorPalette.set(e,{r:t,g:r,b:n,a:o,e:i}),this.onPaletteChangedCallback&&this.onPaletteChangedCallback(this.colorPalette)}onPaletteChanged(e){this.onPaletteChangedCallback=e}onBitmapFontChanged(e){this.onBitmapFontChangedCallback=e}getColor(e){return this.colorPalette.get(e)??null}loadPalette(e){for(let t of e)t.colorId<0||t.colorId>255||this.colorPalette.set(t.colorId,{r:t.r,g:t.g,b:t.b,a:t.a,e:t.e??0});Z.ANSI_VGA_COLORS.forEach(t=>{this.colorPalette.set(t.colorId,{r:t.r,g:t.g,b:t.b,a:t.a,e:t.e})}),this.colorPalette.set(255,{r:0,g:0,b:0,a:0,e:0}),this.displayRasterizer.rebuildColorCache(),this.onPaletteChangedCallback&&this.onPaletteChangedCallback(this.colorPalette)}getPalette(){return new Map(this.colorPalette)}resetPalette(){this.colorPalette.clear(),this.initializeDefaultPalette(),this.onPaletteChangedCallback&&this.onPaletteChangedCallback(this.colorPalette)}loadPaletteToSlot(e,t){if(e<0||e>255)throw new Error(`Palette slot ID must be between 0 and 255, got ${e}`);let r=new Map;for(let n of t)n.colorId<0||n.colorId>255||r.set(n.colorId,{r:n.r,g:n.g,b:n.b,a:n.a,e:n.e??0});Z.ANSI_VGA_COLORS.forEach(n=>{r.set(n.colorId,{r:n.r,g:n.g,b:n.b,a:n.a,e:n.e})}),r.set(255,{r:0,g:0,b:0,a:0,e:0}),this.paletteSlots.set(e,r)}getPaletteFromSlot(e){return this.paletteSlots.get(e)??null}hasPaletteSlot(e){return this.paletteSlots.has(e)}clearPaletteSlot(e){this.paletteSlots.delete(e)}clearAllPaletteSlots(){this.paletteSlots.clear()}getColorCSS(e){let t=this.getColor(e);if(!t)return null;let r=t.a/255;return`rgba(${t.r}, ${t.g}, ${t.b}, ${r})`}getUserIds(){return Array.from(this.users.keys())}forEachUser(e){this.users.forEach(e)}filterUsers(e){return this.getUsers().filter(e)}findUser(e){return this.getUsers().find(e)}getCurrentTick(){return this.currentTick}getStats(){return this.stats}endTick(){this.stats.isEnabled()&&this.stats.startTick(this.currentTick);let e=new Map,t=0,r=0;return this.users.forEach((n,o)=>{let i=n.getLayers(),a=n.getDisplays();t+=i.length,n.getStats().isEnabled()&&n.getStats().startTick(this.currentTick);let s=a.map(S=>{let O=S.getOrigin(),I=S.getSize();return{id:S.getId(),originX:O.x,originY:O.y,sizeX:I.x,sizeY:I.y}});a.forEach(S=>S.resetChangeTracking());let d=[],c=[];i.forEach((S,O)=>{if(!S.getNeedsCommit())return;let I=S.getOrigin(),w=S.getOrders(),U=S.getStatic(),P=S.calculateUpdateFlags();S.resetChangeTracking(),S.resetCommit(),S.getId()===0&&S.setId(O);let R={id:S.getId(),updateFlags:P,zIndex:S.getZOrder(),originX:I.x,originY:I.y,width:S.getWidth(),height:S.getHeight(),is16bit:S.getCharCodeMode()==="16bit",orderCount:w.length,orders:w};w.length>0&&this.stats.isEnabled()&&this.stats.recordLayerInfo(S.getId(),U,w.length,P),U?d.push(R):c.push(R)}),r+=d.length+c.length;let l=this.audioOrderCollector.collectFromUser(n),u=this.vibrationOrderCollector.collectFromUser(n),p=this.postProcessOrderCollector.collectFromUser(n),m=n.flushMacroOrders(),g=null,C=null;if(this.stats.isEnabled()&&this.stats.recordPacketSplit(o,s.length,d.length,c.length),d.length>0&&(g=this.encoder.encode({tick:this.currentTick,displayCount:s.length,displays:s,layerCount:d.length,layers:d,audioOrderCount:0,audioOrders:[],vibrationOrderCount:0,vibrationOrders:[],macroOrderCount:0,macroOrders:[],postProcessOrderCount:0,postProcessOrders:[]})),C=this.encoder.encode({tick:this.currentTick,displayCount:s.length,displays:s,layerCount:c.length,layers:c,audioOrderCount:l.length,audioOrders:l,vibrationOrderCount:u.length,vibrationOrders:u,macroOrderCount:m.length,macroOrders:m,postProcessOrderCount:p.length,postProcessOrders:p}),e.set(o,{static:g,dynamic:C}),n.getStats().isEnabled()){let S=a.reduce((U,P)=>{let R=P.getSize();return U+R.x*R.y},0);n.getStats().recordDisplays(a.length,S),n.getStats().recordLayers(i.length,d.length+c.length,d.length,c.length),[...d,...c].forEach(U=>{n.getStats().recordLayerOrders(U.id,U.orders.length)});let O=g?.length||0,I=C?.length||0;n.getStats().recordPacketSizes(O,I);let w=n.getInputBindingRegistry();n.getStats().recordInput(!1,w.getAxisCount(),w.getButtonCount()),n.getStats().endTick()}if(n.endTickBytes(),this.stats.isEnabled()){let S=[...d,...c];S.forEach((P,R)=>{this.stats.recordLayerOrders(R,P.orders)}),a.forEach((P,R)=>{this.stats.recordDisplayLayers(R,S.length)});let O=(g?.length||0)+(C?.length||0),I=a.length*12,w=S.length*20,U=O-I-w;this.stats.recordUpdatePacketSize(O,I,w,U>0?U:0)}}),this.stats.isEnabled()&&(this.stats.recordLayers(t,r),this.stats.endTick()),this.currentTick++,e}getSnapshot(e){let t=this.getUser(e);if(!t)return null;let r=t.getDisplays(),n=t.getLayers(),o=r.map((a,s)=>{let d=a.getOrigin(),c=a.getSize();return{id:s,originX:d.x,originY:d.y,sizeX:c.x,sizeY:c.y}}),i=n.map((a,s)=>{let d=a.getOrigin(),c=a.getOrders(),l=7;return a.getId()===0&&a.setId(s),{id:a.getId(),updateFlags:l,zIndex:a.getZOrder(),originX:d.x,originY:d.y,width:a.getWidth(),height:a.getHeight(),is16bit:a.getCharCodeMode()==="16bit",orderCount:c.length,orders:c}});return this.encoder.encode({tick:this.currentTick,displayCount:o.length,displays:o,layerCount:i.length,layers:i,audioOrderCount:0,audioOrders:[],vibrationOrderCount:0,vibrationOrders:[],macroOrderCount:0,macroOrders:[],postProcessOrderCount:0,postProcessOrders:[]})}resetTick(){this.currentTick=0}applyUpdatePacket(e,t){let r=this.getUser(e);if(!r){if(this.strictMode)throw new Error(`Cannot apply update packet: user ${e} does not exist`);return!1}return r.applyUpdate(t),t.audioOrders&&t.audioOrders.length>0&&r.applyAudioOrders(t.audioOrders),t.vibrationOrders&&t.vibrationOrders.length>0&&r.applyVibrationOrders(t.vibrationOrders),!0}applyUpdatePacketBuffer(e,t){let{UpdatePacketDecoder:r}=(vr(),re(Hn)),o=new r().decode(t);return this.applyUpdatePacket(e,o)?o:null}applyLoadPacket(e){try{let n=new je().decode(e).load;switch(n.loadType){case 1:n.slotId!==void 0?this.loadPaletteToSlot(n.slotId,n.colors):this.loadPalette(n.colors);break;case 2:this.loadUnicolorSprites(n);break;case 3:this.loadMulticolorSprites(n);break;case 4:{let o=this.getBitmapFontRegistry();o.hasFont(n.fontId)&&o.unloadFont(n.fontId),o.loadFont(n.fontId,{charWidth:n.width,charHeight:n.height,cellWidth:n.cellWidth,cellHeight:n.cellHeight,glyphs:new Map(n.characters.map(i=>[i.charCode,i.bitmap]))});break}case 6:{let o=this.getWebFontRegistry();o.hasFont(n.fontId)&&o.unloadFont(n.fontId),this.loadWebFontById(n.fontId,{fontFamily:n.fontFamily,fontSize:n.fontSize,offsetX:n.offsetX,offsetY:n.offsetY,charSpacing:n.charSpacing,lineHeight:n.lineHeight,fontWeight:n.fontWeight,fontStyle:n.fontStyle});break}case 5:console.warn("[Core] Sound loading not yet implemented");break;case 7:{for(let o of this.users.values())o.loadMacroTemplate(n.macroId,n.template);break}default:return console.error(`[Core] Unknown LoadType: ${n.loadType}`),!1}return!0}catch(t){return console.error("[Core] Failed to apply LoadPacket:",t),!1}}generatePaletteLoadPacket(){let e=this.getPalette();if(e.size===0)return null;let t=new _,r=[];return e.forEach((n,o)=>{o!==255&&r.push({colorId:o,r:n.r,g:n.g,b:n.b,a:n.a,e:n.e})}),t.encode({loadType:1,colors:r})}generatePaletteSlotLoadPacket(e){let t=this.getPaletteFromSlot(e);if(!t||t.size===0)return null;let r=new _,n=[];return t.forEach((o,i)=>{i!==255&&n.push({colorId:i,r:o.r,g:o.g,b:o.b,a:o.a,e:o.e})}),r.encode({loadType:1,slotId:e,colors:n})}generateAllPaletteSlotLoadPackets(){let e=[];return this.paletteSlots.forEach((t,r)=>{let n=this.generatePaletteSlotLoadPacket(r);n&&e.push(n)}),e}generateUnicolorSpritesLoadPacket(){let e=this.getSpriteRegistry(),t=[];for(let n=0;n<=255;n++){let o=e.getUnicolorSprite(n);if(o){let i=[];for(let a=0;a<o.sizeX*o.sizeY;a++)i.push(o.data.get(a));t.push({spriteId:o.id,sizeX:o.sizeX,sizeY:o.sizeY,data:i})}}return t.length===0?null:new _().encode({loadType:2,sprites:t})}generateMulticolorSpritesLoadPacket(){let e=this.getSpriteRegistry(),t=[];for(let n=0;n<=255;n++){let o=e.getMulticolorSprite(n);if(o){let i=[];for(let a=0;a<o.sizeX*o.sizeY;a++){let s=o.data.get(a);i.push({charCode:s.charCode,fgColorId:s.fgColorCode,bgColorId:s.bgColorCode})}t.push({spriteId:o.id,sizeX:o.sizeX,sizeY:o.sizeY,data:i})}}return t.length===0?null:new _().encode({loadType:3,sprites:t})}generateWebFontsLoadPackets(){let e=this.getWebFontRegistry(),t=e.getFontIds(),r=[],n=new _;for(let o of t){let i=e.getFont(o);if(i){let a=i.getConfig(),s=n.encode({loadType:6,fontId:o,fontFamily:a.fontFamily,fontSize:a.fontSize,offsetX:a.offsetX,offsetY:a.offsetY,charSpacing:a.charSpacing,lineHeight:a.lineHeight,fontWeight:a.fontWeight,fontStyle:a.fontStyle});r.push(s)}}return r}generateBitmapFontsLoadPackets(){let e=this.getBitmapFontRegistry(),t=e.getFontIds(),r=[],n=new _;for(let o of t){let i=e.getFont(o);if(i){let a=[];for(let s=0;s<256;s++){let d=i.getGlyph(s);d&&a.push({charCode:s,bitmap:d})}if(a.length>0){let s=n.encode({loadType:4,fontId:o,width:i.getCharWidth(),height:i.getCharHeight(),cellWidth:i.getCellWidth(),cellHeight:i.getCellHeight(),characters:a});r.push(s)}}}return r}generateAllLoadPackets(){let e=[],t=this.generatePaletteLoadPacket();t&&e.push(t);let r=this.generateAllPaletteSlotLoadPackets();e.push(...r);let n=this.generateUnicolorSpritesLoadPacket();n&&e.push(n);let o=this.generateMulticolorSpritesLoadPacket();o&&e.push(o);let i=this.generateWebFontsLoadPackets();e.push(...i);let a=this.generateBitmapFontsLoadPackets();return e.push(...a),e}generateMacroLoadPackets(e){let t=this.getUser(e);if(!t)return[];let r=t.getMacroLoads();if(r.length===0)return[];let n=new $e;return r.map(o=>n.encode(o))}generateInitialUpdatePacket(e){let t=this.getUser(e);if(!t||!t.hasPostProcessCommands())return null;let r=this.postProcessOrderCollector.collectFromUser(t);if(r.length===0)return null;let o=t.getDisplays().map(a=>{let s=a.getSize();return{id:a.getId(),originX:0,originY:0,sizeX:s.x,sizeY:s.y}});return this.encoder.encode({tick:0,displayCount:o.length,displays:o,layerCount:0,layers:[],audioOrderCount:0,audioOrders:[],vibrationOrderCount:0,vibrationOrders:[],macroOrderCount:0,macroOrders:[],postProcessOrderCount:r.length,postProcessOrders:r})}applyInputBindingsLoadPacket(e,t){let r=this.getUser(e);if(!r){if(this.strictMode)throw new Error(`Cannot apply input bindings: user ${e} does not exist`);return!1}try{return r.applyInputBindingsLoadPacket(t),!0}catch(n){return console.error(`[Core] Failed to apply input bindings for user ${e}:`,n),!1}}getRenderState(e){let t=this.getUser(e);if(!t)return null;let r=t.getDisplays(),n=t.getLayers(),o=performance.now(),i=new Array(r.length);for(let s=0;s<r.length;s++){let d=r[s],c=d.getOrigin(),l=d.getSize();i[s]=this.displayRasterizer.rasterize({x:c.x,y:c.y,width:l.x,height:l.y},n)}let a=performance.now()-o;return this._renderCallCount||(this._renderCallCount=0),this._renderCallCount++,{userId:t.id,userName:t.name,tick:this.currentTick,displays:i}}getAllRenderStates(){let e=new Map;return this.users.forEach((t,r)=>{let n=this.getRenderState(r);n&&e.set(r,n)}),e}enableStats(e){this.stats.setEnabled(e)}getStatsInstance(){return this.stats}resetStats(){this.stats.reset()}loadUnicolorSprites(e){this.spriteRegistry.loadUnicolorSprites(e)}loadMulticolorSprites(e){this.spriteRegistry.loadMulticolorSprites(e)}unloadUnicolorSprite(e){return this.spriteRegistry.unloadUnicolorSprite(e)}unloadMulticolorSprite(e){return this.spriteRegistry.unloadMulticolorSprite(e)}clearUnicolorSprites(){this.spriteRegistry.clearUnicolorSprites()}clearMulticolorSprites(){this.spriteRegistry.clearMulticolorSprites()}clearAllSprites(){this.spriteRegistry.clearAll()}getUnicolorSpriteCount(){return this.spriteRegistry.getUnicolorSpriteCount()}getMulticolorSpriteCount(){return this.spriteRegistry.getMulticolorSpriteCount()}getTotalSpriteCount(){return this.spriteRegistry.getTotalSpriteCount()}hasUnicolorSprite(e){return this.spriteRegistry.hasUnicolorSprite(e)}hasMulticolorSprite(e){return this.spriteRegistry.hasMulticolorSprite(e)}getSpriteRegistry(){return this.spriteRegistry}getSoundRegistry(){return this.soundRegistry}async loadSound(e,t){let r=this.detectSoundFormat(t),n=await this.loadSoundData(t);return this.soundRegistry.registerFile(e,r,n)}async loadSounds(e){let t={},n=Object.entries(e).map(async([o,i])=>{let a=await this.loadSound(o,i);t[o]=a});return await Promise.all(n),t}detectSoundFormat(e){let t=e.split(".").pop()?.toLowerCase()??"",r={mp3:"mp3",wav:"wav",ogg:"ogg",webm:"webm",aac:"aac",m4a:"aac"},n=r[t];if(!n)throw new Error(`Unsupported audio format: .${t}. Supported: ${Object.keys(r).join(", ")}`);return n}async loadSoundData(e){let t=globalThis,r=typeof t.window<"u"||typeof t.document<"u",n=typeof t.fetch=="function",o=/^https?:\/\//i.test(e),i=e.startsWith("file:");if(r)try{let p=await fetch(e);if(!p.ok)throw new Error(`HTTP ${p.status}: ${p.statusText}`);let m=await p.arrayBuffer();return new Uint8Array(m)}catch(p){let m=p instanceof Error?p.message:String(p);throw new Error(`Failed to load sound "${e}": ${m}`)}if((o||i)&&n)try{let p=await fetch(e);if(!p.ok)throw new Error(`HTTP ${p.status}: ${p.statusText}`);let m=await p.arrayBuffer();return new Uint8Array(m)}catch(p){let m=p instanceof Error?p.message:String(p);throw new Error(`Failed to load sound "${e}": ${m}`)}let a=typeof ee<"u"?ee:null;if(!a)throw new Error("Node.js require is not available");let s="fs",d=a("path"),c=a(s),l=d.resolve(e),u=c.readFileSync(l);return new Uint8Array(u)}registerSound(e,t,r){return this.soundRegistry.registerFile(e,t,r)}registerExternalSound(e,t,r,n){return this.soundRegistry.registerExternal(e,t,r,n)}hasSound(e){return this.soundRegistry.has(e)}generateSoundLoadPackets(){return this.soundRegistry.toLoadPackets()}loadDefaultWebFont(){this.webFontRegistry.loadFont(0,{fontFamily:"Courier New",fontSize:16,offsetX:0,offsetY:0,charSpacing:0,lineHeight:1,fontWeight:"normal",fontStyle:"normal"}),this.activeWebFontId=0}loadWebFont(e){let t=e.getFontId(),r=e.getConfig();this.webFontRegistry.loadFont(t,r)}getWebFont(e){return this.webFontRegistry.getFont(e)??null}hasWebFont(e){return this.webFontRegistry.hasFont(e)}unloadWebFont(e){if(e===0)throw new Error("Cannot unload default font (fontId 0)");return this.webFontRegistry.unloadFont(e)}clearWebFonts(){this.webFontRegistry.clearFonts(),this.loadDefaultWebFont()}setActiveWebFont(e){if(!this.webFontRegistry.hasFont(e))throw new Error(`WebFont with ID ${e} does not exist`);this.activeWebFontId=e}getActiveWebFontId(){return this.activeWebFontId}getActiveWebFont(){let e=this.webFontRegistry.getFont(this.activeWebFontId);if(!e)throw new Error(`Active WebFont ${this.activeWebFontId} not found. This should not happen.`);return e}getWebFontCount(){return this.webFontRegistry.getFontCount()}getWebFontIds(){return this.webFontRegistry.getFontIds()}getWebFontRegistry(){return this.webFontRegistry}getBitmapFontRegistry(){return this.bitmapFontRegistry}loadWebFontById(e,t){let r=new $(e,t);this.loadWebFont(r)}loadBitmapFontById(e,t){this.bitmapFontRegistry.loadFont(e,t),this.onBitmapFontChangedCallback&&this.onBitmapFontChangedCallback(e)}getBitmapFont(e){return this.bitmapFontRegistry.getFont(e)??null}hasBitmapFont(e){return this.bitmapFontRegistry.hasFont(e)}unloadBitmapFont(e){return this.bitmapFontRegistry.unloadFont(e)}clearBitmapFonts(){this.bitmapFontRegistry.clearFonts()}getBitmapFontCount(){return this.bitmapFontRegistry.getFontCount()}getBitmapFontIds(){return this.bitmapFontRegistry.getFontIds()}async loadImageFont(e,t,r){let n=await this.loadImageData(t),o=this.imageFontRegistry.registerFont(e,r,n);return this.onImageFontChangedCallback&&this.onImageFontChangedCallback(o),o}async loadImageFonts(e){let t={},n=Object.entries(e).map(async([o,{path:i,options:a}])=>{let s=await this.loadImageFont(o,i,a);t[o]=s});return await Promise.all(n),t}async loadImageData(e){let t=globalThis;if(typeof t.document<"u"||typeof t.window<"u"||typeof t.fetch=="function")try{let n=await fetch(e);if(!n.ok)throw new Error(`HTTP ${n.status}: ${n.statusText}`);let o=await n.arrayBuffer();return new Uint8Array(o)}catch(n){let o=n instanceof Error?n.message:String(n);throw new Error(`Failed to load image font "${e}": ${o}`)}else{let n=typeof ee<"u"?ee:null;if(!n)throw new Error("Node.js require is not available");let a=n("fs").readFileSync(e);return new Uint8Array(a)}}getImageFontId(e){return this.imageFontRegistry.getFontId(e)}getImageFontByName(e){return this.imageFontRegistry.getFontByName(e)??null}onImageFontChanged(e){this.onImageFontChangedCallback=e}getImageFontRegistry(){return this.imageFontRegistry}loadImageFontById(e,t){this.imageFontRegistry.loadFont(e,t),this.onImageFontChangedCallback&&this.onImageFontChangedCallback(e)}getImageFont(e){return this.imageFontRegistry.getFont(e)??null}hasImageFont(e){return this.imageFontRegistry.hasFont(e)}hasImageFontByName(e){return this.imageFontRegistry.hasFontByName(e)}unloadImageFont(e){return this.imageFontRegistry.unloadFont(e)}unloadImageFontByName(e){return this.imageFontRegistry.unloadFontByName(e)}clearImageFonts(){this.imageFontRegistry.clearFonts()}getImageFontCount(){return this.imageFontRegistry.getFontCount()}getImageFontIds(){return this.imageFontRegistry.getFontIds()}getImageFontNames(){return this.imageFontRegistry.getFontNames()}};y(Z,"Core"),b(Z,"ANSI_VGA_COLORS",[{colorId:240,r:16,g:16,b:16,a:255,e:0},{colorId:241,r:128,g:128,b:128,a:255,e:0},{colorId:242,r:192,g:192,b:192,a:255,e:0},{colorId:243,r:240,g:240,b:240,a:255,e:0},{colorId:244,r:200,g:50,b:50,a:255,e:0},{colorId:245,r:50,g:200,b:50,a:255,e:0},{colorId:246,r:220,g:180,b:50,a:255,e:0},{colorId:247,r:50,g:100,b:220,a:255,e:0},{colorId:248,r:50,g:200,b:200,a:255,e:0},{colorId:249,r:200,g:50,b:200,a:255,e:0},{colorId:250,r:220,g:120,b:50,a:255,e:0},{colorId:251,r:120,g:220,b:120,a:255,e:0},{colorId:252,r:120,g:180,b:220,a:255,e:0},{colorId:253,r:220,g:150,b:200,a:255,e:0},{colorId:254,r:250,g:220,b:150,a:255,e:0}]);var Ur=Z;import{Vector2 as Rd}from"@utsp/types";var K=new Map([[24,new Uint8Array([0,24,60,126,255,255,0,0])],[25,new Uint8Array([0,0,255,255,126,60,24,0])],[26,new Uint8Array([0,48,120,252,252,120,48,0])],[27,new Uint8Array([0,12,30,63,63,30,12,0])],[32,new Uint8Array([0,0,0,0,0,0,0,0])],[33,new Uint8Array([24,24,24,24,24,0,24,0])],[34,new Uint8Array([108,108,108,0,0,0,0,0])],[35,new Uint8Array([54,54,127,54,127,54,54,0])],[36,new Uint8Array([12,63,104,62,11,126,24,0])],[37,new Uint8Array([96,102,12,24,48,102,6,0])],[38,new Uint8Array([56,108,108,56,109,102,59,0])],[39,new Uint8Array([24,24,24,0,0,0,0,0])],[40,new Uint8Array([12,24,48,48,48,24,12,0])],[41,new Uint8Array([48,24,12,12,12,24,48,0])],[42,new Uint8Array([0,102,60,255,60,102,0,0])],[43,new Uint8Array([0,24,24,126,24,24,0,0])],[44,new Uint8Array([0,0,0,0,0,24,24,48])],[45,new Uint8Array([0,0,0,126,0,0,0,0])],[46,new Uint8Array([0,0,0,0,0,24,24,0])],[47,new Uint8Array([0,6,12,24,48,96,0,0])],[48,new Uint8Array([60,102,110,126,118,102,60,0])],[49,new Uint8Array([24,56,24,24,24,24,126,0])],[50,new Uint8Array([60,102,6,12,24,48,126,0])],[51,new Uint8Array([60,102,6,28,6,102,60,0])],[52,new Uint8Array([12,28,60,108,126,12,12,0])],[53,new Uint8Array([126,96,124,6,6,102,60,0])],[54,new Uint8Array([28,48,96,124,102,102,60,0])],[55,new Uint8Array([126,6,12,24,48,48,48,0])],[56,new Uint8Array([60,102,102,60,102,102,60,0])],[57,new Uint8Array([60,102,102,62,6,12,56,0])],[58,new Uint8Array([0,0,24,24,0,24,24,0])],[59,new Uint8Array([0,0,24,24,0,24,24,48])],[60,new Uint8Array([12,24,48,96,48,24,12,0])],[61,new Uint8Array([0,0,126,0,126,0,0,0])],[62,new Uint8Array([48,24,12,6,12,24,48,0])],[63,new Uint8Array([60,102,12,24,24,0,24,0])],[64,new Uint8Array([60,102,110,106,110,96,60,0])],[65,new Uint8Array([60,102,102,126,102,102,102,0])],[66,new Uint8Array([124,102,102,124,102,102,124,0])],[67,new Uint8Array([60,102,96,96,96,102,60,0])],[68,new Uint8Array([120,108,102,102,102,108,120,0])],[69,new Uint8Array([126,96,96,124,96,96,126,0])],[70,new Uint8Array([126,96,96,124,96,96,96,0])],[71,new Uint8Array([60,102,96,110,102,102,60,0])],[72,new Uint8Array([102,102,102,126,102,102,102,0])],[73,new Uint8Array([126,24,24,24,24,24,126,0])],[74,new Uint8Array([62,12,12,12,12,108,56,0])],[75,new Uint8Array([102,108,120,112,120,108,102,0])],[76,new Uint8Array([96,96,96,96,96,96,126,0])],[77,new Uint8Array([99,119,127,107,99,99,99,0])],[78,new Uint8Array([102,102,118,126,110,102,102,0])],[79,new Uint8Array([60,102,102,102,102,102,60,0])],[80,new Uint8Array([124,102,102,124,96,96,96,0])],[81,new Uint8Array([60,102,102,102,106,108,54,0])],[82,new Uint8Array([124,102,102,124,108,102,102,0])],[83,new Uint8Array([60,102,96,60,6,102,60,0])],[84,new Uint8Array([126,24,24,24,24,24,24,0])],[85,new Uint8Array([102,102,102,102,102,102,60,0])],[86,new Uint8Array([102,102,102,102,102,60,24,0])],[87,new Uint8Array([99,99,99,107,127,119,99,0])],[88,new Uint8Array([102,102,60,24,60,102,102,0])],[89,new Uint8Array([102,102,102,60,24,24,24,0])],[90,new Uint8Array([126,6,12,24,48,96,126,0])],[91,new Uint8Array([60,48,48,48,48,48,60,0])],[92,new Uint8Array([0,96,48,24,12,6,0,0])],[93,new Uint8Array([60,12,12,12,12,12,60,0])],[94,new Uint8Array([24,60,102,0,0,0,0,0])],[95,new Uint8Array([0,0,0,0,0,0,255,0])],[96,new Uint8Array([48,24,12,0,0,0,0,0])],[97,new Uint8Array([0,0,60,6,62,102,62,0])],[98,new Uint8Array([96,96,124,102,102,102,124,0])],[99,new Uint8Array([0,0,60,102,96,102,60,0])],[100,new Uint8Array([6,6,62,102,102,102,62,0])],[101,new Uint8Array([0,0,60,102,126,96,60,0])],[102,new Uint8Array([28,54,48,124,48,48,48,0])],[103,new Uint8Array([0,0,62,102,102,62,6,60])],[104,new Uint8Array([96,96,124,102,102,102,102,0])],[105,new Uint8Array([24,0,56,24,24,24,60,0])],[106,new Uint8Array([12,0,28,12,12,12,108,56])],[107,new Uint8Array([96,96,102,108,120,108,102,0])],[108,new Uint8Array([56,24,24,24,24,24,60,0])],[109,new Uint8Array([0,0,102,127,107,107,99,0])],[110,new Uint8Array([0,0,124,102,102,102,102,0])],[111,new Uint8Array([0,0,60,102,102,102,60,0])],[112,new Uint8Array([0,0,124,102,102,124,96,96])],[113,new Uint8Array([0,0,62,102,102,62,6,6])],[114,new Uint8Array([0,0,108,118,96,96,96,0])],[115,new Uint8Array([0,0,62,96,60,6,124,0])],[116,new Uint8Array([48,48,124,48,48,54,28,0])],[117,new Uint8Array([0,0,102,102,102,102,62,0])],[118,new Uint8Array([0,0,102,102,102,60,24,0])],[119,new Uint8Array([0,0,99,107,107,127,54,0])],[120,new Uint8Array([0,0,102,60,24,60,102,0])],[121,new Uint8Array([0,0,102,102,102,62,6,60])],[122,new Uint8Array([0,0,126,12,24,48,126,0])],[123,new Uint8Array([14,24,24,112,24,24,14,0])],[124,new Uint8Array([24,24,24,24,24,24,24,0])],[125,new Uint8Array([112,24,24,14,24,24,112,0])],[126,new Uint8Array([49,107,70,0,0,0,0,0])],[179,new Uint8Array([24,24,24,24,24,24,24,24])],[196,new Uint8Array([0,0,0,255,0,0,0,0])],[218,new Uint8Array([0,0,0,31,24,24,24,24])],[191,new Uint8Array([0,0,0,248,24,24,24,24])],[192,new Uint8Array([24,24,24,31,0,0,0,0])],[217,new Uint8Array([24,24,24,248,0,0,0,0])],[195,new Uint8Array([24,24,24,31,24,24,24,24])],[180,new Uint8Array([24,24,24,248,24,24,24,24])],[194,new Uint8Array([0,0,0,255,24,24,24,24])],[193,new Uint8Array([24,24,24,255,0,0,0,0])],[197,new Uint8Array([24,24,24,255,24,24,24,24])],[186,new Uint8Array([54,54,54,54,54,54,54,54])],[205,new Uint8Array([0,0,0,255,0,255,0,0])],[201,new Uint8Array([0,0,0,63,54,54,54,54])],[187,new Uint8Array([0,0,0,252,54,54,54,54])],[200,new Uint8Array([54,54,54,63,0,0,0,0])],[188,new Uint8Array([54,54,54,252,0,0,0,0])],[204,new Uint8Array([54,54,54,63,54,54,54,54])],[185,new Uint8Array([54,54,54,252,54,54,54,54])],[203,new Uint8Array([0,0,0,255,54,54,54,54])],[202,new Uint8Array([54,54,54,255,0,0,0,0])],[206,new Uint8Array([54,54,54,255,54,54,54,54])],[219,new Uint8Array([255,255,255,255,255,255,255,255])],[178,new Uint8Array([170,85,170,85,170,85,170,85])],[177,new Uint8Array([136,34,136,34,136,34,136,34])],[176,new Uint8Array([34,136,34,136,34,136,34,136])],[223,new Uint8Array([255,255,255,255,0,0,0,0])],[220,new Uint8Array([0,0,0,0,255,255,255,255])],[221,new Uint8Array([240,240,240,240,240,240,240,240])],[222,new Uint8Array([15,15,15,15,15,15,15,15])]]);function go(h){return K.get(h)}y(go,"getCharBitmap");function yo(h){return K.has(h)}y(yo,"hasChar");function Co(){return Array.from(K.keys()).sort((h,e)=>h-e)}y(Co,"getAllCharCodes");function xo(h){let e=Array.from(K.entries()).map(([t,r])=>({charCode:t,bitmap:r}));return{loadType:4,fontId:h,width:8,height:8,cellWidth:8,cellHeight:8,characters:e}}y(xo,"createASCII8x8FontLoad");function fo(){return{charWidth:8,charHeight:8,glyphs:new Map(K)}}y(fo,"getASCII8x8FontConfig");L();var Mr=class Mr{encode(e){switch(e.type){case 1:return this.encodeClick(e);case 2:return this.encodeChange(e);case 3:return this.encodeSubmit(e);case 4:return this.encodeSelect(e);default:throw new Error(`Unknown macro event type: ${e.type}`)}}calculateSize(e){switch(e.type){case 1:return 2;case 2:return this.calculateChangeSize(e);case 3:return this.calculateSubmitSize(e);case 4:return 4;default:throw new Error(`Unknown macro event type: ${e.type}`)}}encodeClick(e){let t=x.allocUnsafe(2);return t.writeUInt8(e.type,0),t.writeUInt8(e.instanceId,1),t.toUint8Array()}encodeChange(e){if(typeof e.value=="boolean"){let r=x.allocUnsafe(4);return r.writeUInt8(e.type,0),r.writeUInt8(e.instanceId,1),r.writeUInt8(1,2),r.writeUInt8(e.value?1:0,3),r.toUint8Array()}else{let r=x.allocUnsafe(7);return r.writeUInt8(e.type,0),r.writeUInt8(e.instanceId,1),r.writeUInt8(0,2),r.writeFloatBE(e.value,3),r.toUint8Array()}}calculateChangeSize(e){return typeof e.value=="boolean"?4:7}encodeSubmit(e){let t=new TextEncoder().encode(e.text);if(t.length>65535)throw new Error(`Submit text too large: ${t.length} bytes (max 65535)`);let r=4+t.length,n=x.allocUnsafe(r),o=0;return n.writeUInt8(e.type,o++),n.writeUInt8(e.instanceId,o++),n.writeUInt16BE(t.length,o),o+=2,n.toUint8Array().set(t,o),n.toUint8Array()}calculateSubmitSize(e){return 4+new TextEncoder().encode(e.text).length}encodeSelect(e){let t=x.allocUnsafe(4);return t.writeUInt8(e.type,0),t.writeUInt8(e.instanceId,1),t.writeUInt16BE(e.index,2),t.toUint8Array()}};y(Mr,"MacroEventEncoder");var rt=Mr;function So(h,e,t,r,n,o,i,a=[],s=[],d=[],c=[]){let l=Array.from(e.entries()).sort((E,B)=>E[0]-B[0]),u=Array.from(t.entries()).sort((E,B)=>E[0]-B[0]),p=l.length,m=u.length,g=Et(p,m),C=new TextEncoder,S=a.map(E=>C.encode(E)),O=1+S.reduce((E,B)=>E+1+B.length,0),I=new rt,w=s.map(E=>I.encode(E)),U=1+w.reduce((E,B)=>E+B.length,0),P=Math.min(d.length,255),R=1+P*5,M=Math.min(c.length,10),f=1+M*4,nt=g+O+U+R+f,v=new Uint8Array(nt),T=new DataView(v.buffer),A=0;T.setBigUint64(A,h,!0),A+=8;for(let[,E]of l){let B=Mt(E);v[A]=B+256&255,A+=1}let Nn=J(m);for(let E=0;E<Nn;E++){let B=0;for(let Ae=0;Ae<8;Ae++){let Rr=E*8+Ae;if(Rr<m){let[,Yn]=u[Rr];Yn&&(B|=1<<Ae)}}v[A]=B,A+=1}v[A]=r&255,A+=1,v[A]=n&255,A+=1,v[A]=o&255,A+=1;let Pr=0;i&&(Pr|=1),v[A]=Pr,A+=1,v[A]=Math.min(a.length,255),A+=1;for(let E of S)v[A]=Math.min(E.length,255),A+=1,v.set(E.slice(0,255),A),A+=E.length;v[A]=Math.min(s.length,255),A+=1;for(let E of w)v.set(E,A),A+=E.length;v[A]=P,A+=1;for(let E=0;E<P;E++){let B=d[E];v[A]=B.displayId&255,A+=1,T.setUint16(A,Math.min(B.pixelWidth,65535),!1),A+=2,T.setUint16(A,Math.min(B.pixelHeight,65535),!1),A+=2}v[A]=M,A+=1;for(let E=0;E<M;E++){let B=c[E];v[A]=B.id&15,A+=1,v[A]=B.x&255,A+=1,v[A]=B.y&255,A+=1,v[A]=B.over?1:0,A+=1}return v}y(So,"encodeCompressedInput");var k=class k{static toCharCode(e){if(typeof e=="number")return e&65535;let t=e.charCodeAt(0);return ie(t)}static dedent(e){let t=e.split(`
|
|
9
14
|
`);if(t.length>0&&t[0].trim()===""&&t.shift(),t.length>0&&t[t.length-1].trim()===""&&t.pop(),t.length===0)return"";let r=t.filter(o=>o.trim().length>0);if(r.length===0)return"";let n=Math.min(...r.map(o=>{let i=o.match(/^(\s*)/);return i?i[1].length:0}));return t.map(o=>o.slice(n)).join(`
|
|
10
|
-
`)}static char(e,t,r,n=15,o=0){return{type:1,posX:e,posY:t,charCode:
|
|
15
|
+
`)}static char(e,t,r,n=15,o=0){return{type:1,posX:e,posY:t,charCode:k.toCharCode(r),bgColorCode:o,fgColorCode:n}}static text(e,t,r,n=15,o=0){return{type:2,posX:e,posY:t,text:r,bgColorCode:o,fgColorCode:n}}static textMultiline(e,t,r,n=15,o=0){return{type:23,posX:e,posY:t,text:k.dedent(r),bgColorCode:o,fgColorCode:n}}static subFrame(e,t,r,n,o,i=15,a=0){return{type:3,posX:e,posY:t,sizeX:r,sizeY:n,frame:o.map(s=>k.toCharCode(s)),bgColorCode:a,fgColorCode:i}}static subFrameMultiColor(e,t,r,n,o){return{type:4,posX:e,posY:t,sizeX:r,sizeY:n,frame:o.map(i=>({charCode:k.toCharCode(i.charCode),bgColorCode:i.bgColorCode,fgColorCode:i.fgColorCode}))}}static fullFrame(e,t=15,r=0){return{type:5,frame:e.map(n=>k.toCharCode(n)),bgColorCode:r,fgColorCode:t}}static fullFrameMultiColor(e){return{type:6,frame:e.map(t=>({charCode:k.toCharCode(t.charCode),bgColorCode:t.bgColorCode,fgColorCode:t.fgColorCode}))}}static sprite(e,t,r,n=15,o=0){return{type:7,posX:e,posY:t,spriteIndex:r,bgColorCode:o,fgColorCode:n}}static spriteMultiColor(e,t,r){return{type:8,posX:e,posY:t,spriteIndex:r}}static colorMap(e,t,r,n,o){return{type:9,posX:e,posY:t,sizeX:r,sizeY:n,colorData:o}}static rectangle(e,t,r,n,o={}){return{type:10,shapeType:1,shapeData:{posX:e,posY:t,width:r,height:n,filled:o.filled??!0,charCode:k.toCharCode(o.charCode??9608),bgColorCode:o.bgColor??0,fgColorCode:o.fgColor??15}}}static circle(e,t,r,n={}){return{type:10,shapeType:2,shapeData:{centerX:e,centerY:t,radius:r,filled:n.filled??!0,charCode:k.toCharCode(n.charCode??9608),bgColorCode:n.bgColor??0,fgColorCode:n.fgColor??15}}}static line(e,t,r,n,o={}){return{type:10,shapeType:3,shapeData:{x1:e,y1:t,x2:r,y2:n,charCode:k.toCharCode(o.charCode??9608),bgColorCode:o.bgColor??0,fgColorCode:o.fgColor??15}}}static ellipse(e,t,r,n,o={}){return{type:10,shapeType:4,shapeData:{centerX:e,centerY:t,radiusX:r,radiusY:n,filled:o.filled??!0,charCode:k.toCharCode(o.charCode??9608),bgColorCode:o.bgColor??0,fgColorCode:o.fgColor??15}}}static triangle(e,t,r,n,o,i,a={}){return{type:10,shapeType:5,shapeData:{x1:e,y1:t,x2:r,y2:n,x3:o,y3:i,filled:a.filled??!0,charCode:k.toCharCode(a.charCode??9608),bgColorCode:a.bgColor??0,fgColorCode:a.fgColor??15}}}static dotCloud(e,t,r=15,n=0){return{type:11,charCode:k.toCharCode(t),bgColorCode:n,fgColorCode:r,positions:e}}static dotCloudMultiColor(e){return{type:12,dots:e.map(t=>({...t,charCode:k.toCharCode(t.charCode)}))}}static bitmask(e,t,r,n,o,i,a=15,s=0,d=!1){let c=r*n,l=Math.ceil(c/8),u=new Uint8Array(l);for(let p=0;p<c;p++)if(o[p]){let m=Math.floor(p/8),g=p%8;u[m]|=1<<g}return{type:17,posX:e,posY:t,sizeX:r,sizeY:n,charCode:k.toCharCode(i),bgColorCode:s,fgColorCode:a,override:d,mask:u}}static bitmask4(e,t,r,n,o,i,a=!1){let s={char:"?",fgColor:15,bgColor:0},d=[i[0]??s,i[1]??s,i[2]??s],c=r*n,l=Math.ceil(c/4),u=new Uint8Array(l);for(let p=0;p<c;p++){let m=o[p]&3,g=Math.floor(p/4),C=p%4*2;u[g]|=m<<C}return{type:18,posX:e,posY:t,sizeX:r,sizeY:n,override:a,variants:[{charCode:k.toCharCode(d[0].char),fgColorCode:d[0].fgColor,bgColorCode:d[0].bgColor},{charCode:k.toCharCode(d[1].char),fgColorCode:d[1].fgColor,bgColorCode:d[1].bgColor},{charCode:k.toCharCode(d[2].char),fgColorCode:d[2].fgColor,bgColorCode:d[2].bgColor}],mask:u}}static bitmask16(e,t,r,n,o,i,a=!1){let s={char:"?",fgColor:15,bgColor:0},d=[];for(let p=0;p<15;p++)d.push(i[p]??s);let c=r*n,l=Math.ceil(c/2),u=new Uint8Array(l);for(let p=0;p<c;p++){let m=o[p]&15,g=Math.floor(p/2),C=p%2*4;u[g]|=m<<C}return{type:24,posX:e,posY:t,sizeX:r,sizeY:n,override:a,variants:d.map(p=>({charCode:k.toCharCode(p.char),fgColorCode:p.fgColor,bgColorCode:p.bgColor})),mask:u}}static spriteCloud(e,t,r=15,n=0){return{type:13,spriteIndex:e,bgColorCode:n,fgColorCode:r,positions:t}}static spriteCloudMultiColor(e,t){return{type:14,spriteIndex:e,positions:t}}static spriteCloudVaried(e){return{type:15,sprites:e}}static spriteCloudVariedMultiColor(e){return{type:16,sprites:e}}static clear(e=32,t=15,r=0){return{type:19,charCode:k.toCharCode(e),bgColorCode:r,fgColorCode:t}}static fillChar(e,t,r,n=15,o=0){return{type:20,patternWidth:e,patternHeight:t,pattern:r.map(i=>k.toCharCode(i)),bgColorCode:o,fgColorCode:n}}static fillSprite(e,t=15,r=0){return{type:21,spriteIndex:e,bgColorCode:r,fgColorCode:t}}static fillSpriteMultiColor(e){return{type:22,spriteIndex:e}}static boxWithBorder(e,t,r,n,o,i){return[this.rectangle(e+1,t+1,r-2,n-2,{charCode:i.charCode??9608,bgColor:i.bgColor??0,fgColor:i.fgColor??8,filled:!0}),this.rectangle(e,t,r,n,{charCode:o.charCode??9608,bgColor:o.bgColor??0,fgColor:o.fgColor??15,filled:!1})]}static grid(e,t,r,n,o,i,a={}){let s=[];for(let d=0;d<=o;d++)for(let c=0;c<=i;c++)s.push({posX:e+c*r,posY:t+d*n});return this.dotCloud(s,a.charCode??"+",a.fgColor??15,a.bgColor??0)}static polyline(e,t="*",r=15,n=0){return{type:25,charCode:k.toCharCode(t),fgColorCode:r,bgColorCode:n,points:e.map(o=>({x:o.x&255,y:o.y&255}))}}static polylineFromCoords(e,t="*",r=15,n=0){let o=[];for(let i=0;i<e.length-1;i+=2)o.push({x:e[i],y:e[i+1]});return this.polyline(o,t,r,n)}static polygon(e,t="*",r=15,n=0){if(e.length<2)return this.polyline(e,t,r,n);let o=[...e,e[0]];return this.polyline(o,t,r,n)}};y(k,"OrderBuilder");var Ar=k;W();Ht();mn();var _n=(u=>(u[u.LayerEnabled=1]="LayerEnabled",u[u.SetMode=2]="SetMode",u[u.UpdatePosition=4]="UpdatePosition",u[u.UpdateZOrder=8]="UpdateZOrder",u[u.Disabled=0]="Disabled",u[u.EnabledAddMode=1]="EnabledAddMode",u[u.EnabledSetMode=3]="EnabledSetMode",u[u.EnabledAddMoveOnly=5]="EnabledAddMoveOnly",u[u.EnabledSetMoveOnly=7]="EnabledSetMoveOnly",u[u.EnabledAddReorderOnly=9]="EnabledAddReorderOnly",u[u.EnabledSetReorderOnly=11]="EnabledSetReorderOnly",u[u.FullUpdate=15]="FullUpdate",u))(_n||{}),Er;(c=>{function h(l,u){return(l&u)!==0}c.hasFlag=h,y(h,"hasFlag");function e(l,u){return l|u}c.addFlag=e,y(e,"addFlag");function t(l,u){return l&~u}c.removeFlag=t,y(t,"removeFlag");function r(...l){return l.reduce((u,p)=>u|p,0)}c.combine=r,y(r,"combine");function n(l){return(l&240)===0}c.isValid=n,y(n,"isValid");function o(l){return h(l,1)}c.isEnabled=o,y(o,"isEnabled");function i(l){return h(l,2)}c.isSetMode=i,y(i,"isSetMode");function a(l){return h(l,4)}c.hasPositionChanged=a,y(a,"hasPositionChanged");function s(l){return h(l,8)}c.hasZOrderChanged=s,y(s,"hasZOrderChanged");function d(l){if(l===0)return"Disabled";let u=[];return h(l,1)?u.push("Enabled"):u.push("Disabled"),h(l,2)?u.push("SET"):u.push("ADD"),h(l,4)&&u.push("Position"),h(l,8)&&u.push("ZOrder"),u.join(" | ")}c.describe=d,y(d,"describe")})(Er||(Er={}));gn();vr();Nt();Cr();zt();Lt();fr();Rn();En();Or();export{K as ASCII_8X8_FONT,at as AUDIO_CONFIGURE_SPATIAL_SIZE,Ro as AUDIO_FADEOUT_SOUND_MIN_SIZE,ko as AUDIO_PAUSE_SOUND_MIN_SIZE,ln as AUDIO_PLAY_GLOBAL_SOUND_MIN_SIZE,cn as AUDIO_PLAY_SOUND_MIN_SIZE,Bo as AUDIO_RESUME_SOUND_MIN_SIZE,it as AUDIO_SET_LISTENER_POSITION_SIZE,zo as AUDIO_SET_SOUND_EFFECTS_MIN_SIZE,Po as AUDIO_STOP_SOUND_MIN_SIZE,Ie as AudioOrderCollector,ve as AudioOrderDecoder,Dt as AudioOrderType,Vt as AudioTargetType,Kr as BITMASK16_ORDER_MIN_SIZE,qr as BITMASK4_ORDER_MIN_SIZE,Jr as BITMASK_ORDER_MIN_SIZE,ye as BitmapFont,xe as BitmapFontRegistry,kr as CHAR_ORDER_SIZE,Xr as CIRCLE_SHAPE_SIZE,on as CLEAR_ORDER_SIZE,_r as COLORMAP_ORDER_MIN_SIZE,z as COLOR_SKIP,G as CellBuffer,oe as CharCodeBuffer,Ur as Core,be as CoreStats,Ao as DISPLAY_HEADER_SIZE,jr as DOTCLOUD_MULTICOLOR_ORDER_MIN_SIZE,Zr as DOTCLOUD_ORDER_MIN_SIZE,ne as Display,Gr as ELLIPSE_SHAPE_SIZE,an as FILLCHAR_ORDER_MIN_SIZE,dn as FILLSPRITE_MULTICOLOR_ORDER_SIZE,sn as FILLSPRITE_ORDER_SIZE,Dr as FULLFRAME_MULTICOLOR_ORDER_MIN_SIZE,Lr as FULLFRAME_ORDER_MIN_SIZE,Bn as FontType,Ft as GamepadVibrateFlags,q as ImageFont,fe as ImageFontRegistry,ue as InputBindingRegistry,Uo as LAYER_CELL_COUNT,Eo as LAYER_HEADER_SIZE,Pe as LAYER_SIZE,Wr as LINE_SHAPE_SIZE,ae as Layer,kn as LoadType,Be as MAX_ORDERS_PER_LAYER,le as MacroEngine,bn as MacroEventType,hn as MacroOrderType,se as MacroRegistry,Tt as MobileVibrateFlags,Ar as OrderBuilder,yn as OrderType,Qr as POLYLINE_ORDER_MIN_SIZE,dt as POSTPROCESS_SET_AMBIENT_EFFECT_SIZE,pt as POSTPROCESS_SET_CELL_SIZE_SIZE,un as POSTPROCESS_SET_CONFIG_MIN_SIZE,lt as POSTPROCESS_SET_GRID_SIZE,ct as POSTPROCESS_SET_SCALING_MODE_SIZE,st as POSTPROCESS_SET_SCANLINES_SIZE,ut as POSTPROCESS_SWITCH_PALETTE_SIZE,_t as PlaySoundFlags,we as PostProcessOrderCollector,Me as PostProcessOrderDecoder,Pn as PostProcessOrderType,Yr as RECTANGLE_SHAPE_SIZE,Nr as SHAPE_ORDER_MIN_SIZE,tn as SPRITECLOUD_MULTICOLOR_ORDER_MIN_SIZE,en as SPRITECLOUD_ORDER_MIN_SIZE,nn as SPRITECLOUD_VARIED_MULTICOLOR_ORDER_MIN_SIZE,rn as SPRITECLOUD_VARIED_ORDER_MIN_SIZE,Hr as SPRITE_MULTICOLOR_ORDER_SIZE,Vr as SPRITE_ORDER_SIZE,Fr as SUBFRAME_MULTICOLOR_ORDER_MIN_SIZE,Tr as SUBFRAME_ORDER_MIN_SIZE,po as ScalingModeValue,pn as ShapeType,Se as SoundRegistry,ge as SpriteRegistry,zr as TEXT_MULTILINE_ORDER_MIN_SIZE,Br as TEXT_ORDER_MIN_SIZE,$r as TRIANGLE_SHAPE_SIZE,Mo as UPDATE_PACKET_HEADER_SIZE,_n as UpdateFlags,Er as UpdateFlagsHelper,tt as UpdatePacketDecoder,me as User,pe as UserStats,Rd as Vector2,Oe as VibrationOrderCollector,Ue as VibrationOrderDecoder,he as VibrationOrderEncoder,Bt as VibrationOrderType,$ as WebFont,Ce as WebFontRegistry,Re as charCodeByteSize,xo as createASCII8x8FontLoad,Ut as createEmptyCompressedInputPacket,Rt as decodeCompressedInput,At as decodeInt8ToAxis,Mt as encodeAxisToInt8,So as encodeCompressedInput,fo as getASCII8x8FontConfig,Co as getAllCharCodes,nr as getAtlasColumns,mo as getAtlasDimensions,On as getAudioOrderTypeName,J as getButtonByteCount,go as getCharBitmap,Et as getCompressedPacketSize,eo as getMacroEventTypeName,Qn as getMacroOrderTypeName,zn as getMaxCharCode,ro as getOrderTypeName,yo as hasChar,In as isValidAudioOrderType,Kn as isValidMacroEventType,qn as isValidMacroOrderType,to as isValidOrderType};
|