@utsp/core 0.16.0-nightly.20251231153713.b870da1 → 0.16.0-nightly.20260101200530.42ed56f
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 +6 -6
- package/dist/benchmark.d.ts +117 -82
- package/dist/benchmark.mjs +6 -6
- package/dist/index.cjs +6 -6
- package/dist/index.d.ts +99 -79
- package/dist/index.mjs +6 -6
- package/package.json +4 -2
package/dist/benchmark.cjs
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
|
-
"use strict";var pe=Object.defineProperty;var Cn=Object.getOwnPropertyDescriptor;var fn=Object.getOwnPropertyNames;var Sn=Object.prototype.hasOwnProperty;var In=(g,e,t)=>e in g?pe(g,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):g[e]=t;var y=(g,e)=>pe(g,"name",{value:e,configurable:!0});var T=(g,e)=>()=>(g&&(e=g(g=0)),e);var W=(g,e)=>{for(var t in e)pe(g,t,{get:e[t],enumerable:!0})},On=(g,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of fn(e))!Sn.call(g,n)&&n!==t&&pe(g,n,{get:()=>e[n],enumerable:!(r=Cn(e,n))||r.enumerable});return g};var G=g=>On(pe({},"__esModule",{value:!0}),g);var h=(g,e,t)=>(In(g,typeof e!="symbol"?e+"":e,t),t);var Je,dr=T(()=>{"use strict";Je=(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))(Je||{})});var fe,lr,cr,ur,pr,mr,hr,br,gr,yr,Cr,fr,Sr,Ir,Or,xr,vr,wr,Ur,Mr,Er,Ar,Pr,Rr,kr,zr,Br,Tr,Fr,Lr,Dr,Vr,Hr,qe,Ke,_r,Qe,et,tt,rt,nt,ot,$=T(()=>{"use strict";fe=y(g=>g?2:1,"charCodeByteSize"),lr=6,cr=6,ur=6,pr=7,mr=5,hr=3,br=1,gr=6,yr=4,Cr=5,fr=2,Sr=8,Ir=7,Or=7,xr=8,vr=10,wr=6,Ur=3,Mr=9,Er=15,Ar=51,Pr=5,Rr=6,kr=4,zr=3,Br=3,Tr=4,Fr=5,Lr=4,Dr=2,Vr=5,Hr=5,qe=5,Ke=5,_r=3,Qe=8,et=6,tt=3,rt=8,nt=3,ot=4});var H,f,B=T(()=>{"use strict";H=class H{constructor(e){h(this,"data");h(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 Gr={};W(Gr,{PlaySoundFlags:()=>Xr,SoundEffectsFlags:()=>Wr});var Xr,Wr,$r=T(()=>{"use strict";Xr=(a=>(a[a.Loop=1]="Loop",a[a.HasVolume=2]="HasVolume",a[a.HasPitch=4]="HasPitch",a[a.HasFadeIn=8]="HasFadeIn",a[a.HasPosition=16]="HasPosition",a[a.HasLowpass=32]="HasLowpass",a[a.HasHighpass=64]="HasHighpass",a[a.HasReverb=128]="HasReverb",a))(Xr||{}),Wr=(r=>(r[r.HasLowpass=1]="HasLowpass",r[r.HasHighpass=2]="HasHighpass",r[r.HasReverb=4]="HasReverb",r))(Wr||{})});var Jr={};W(Jr,{AudioOrderType:()=>Zr,AudioTargetType:()=>jr,getAudioOrderTypeName:()=>vn,isValidAudioOrderType:()=>xn});function xn(g){return g>=1&&g<=9}function vn(g){switch(g){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${g.toString(16)})`}}var Zr,jr,qr=T(()=>{"use strict";Zr=(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))(Zr||{}),jr=(r=>(r[r.InstanceId=0]="InstanceId",r[r.SoundId=1]="SoundId",r[r.All=2]="All",r))(jr||{});y(xn,"isValidAudioOrderType");y(vn,"getAudioOrderTypeName")});var en={};W(en,{GamepadVibrateFlags:()=>Qr,MobileVibrateFlags:()=>Kr});var Kr,Qr,tn=T(()=>{"use strict";Kr=(e=>(e[e.HasIntensity=1]="HasIntensity",e))(Kr||{}),Qr=(t=>(t[t.HasStartDelay=1]="HasStartDelay",t[t.AllGamepads=2]="AllGamepads",t))(Qr||{})});var nn={};W(nn,{VibrationOrderType:()=>rn});var rn,on=T(()=>{"use strict";rn=(n=>(n[n.MobileVibrate=1]="MobileVibrate",n[n.MobileCancel=2]="MobileCancel",n[n.GamepadVibrate=16]="GamepadVibrate",n[n.GamepadCancel=17]="GamepadCancel",n))(rn||{})});var yt,Q,Ct=T(()=>{"use strict";$();yt=class yt{constructor(){h(this,"charCodeSize",fe)}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,s=e.readUInt8(i++),a=e.readUInt8(i++),d=e.readUInt8(i++),[l,c]=this.readCharCode(e,i,r);i=c;let u=e.readUInt8(i++),p=e.readUInt8(i++);return{order:{type:1,posX:a,posY:d,charCode:l,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,s=e.readUInt8(n+4)+1,a=i*s;this.checkSize(e,t,7+a*o);let d=[],l=n+7;for(let u=0;u<a;u++){let[p,m]=this.readCharCode(e,l,r);d.push(p),l=m}return{order:{type:3,posX:e.readUInt8(n+1),posY:e.readUInt8(n+2),sizeX:i,sizeY:s,bgColorCode:e.readUInt8(n+5),fgColorCode:e.readUInt8(n+6),frame:d},bytesRead:7+a*o}}decodeSubFrameMultiColorOrder(e,t,r){this.checkSize(e,t,5);let n=t,o=this.charCodeSize(r),i=e.readUInt8(n+3)+1,s=e.readUInt8(n+4)+1,a=i*s,d=o+2;this.checkSize(e,t,5+a*d);let l=[],c=n+5;for(let p=0;p<a;p++){let[m,b]=this.readCharCode(e,c,r);c=b,l.push({charCode:m,bgColorCode:e.readUInt8(c++),fgColorCode:e.readUInt8(c++)})}return{order:{type:4,posX:e.readUInt8(n+1),posY:e.readUInt8(n+2),sizeX:i,sizeY:s,frame:l},bytesRead:5+a*d}}decodeFullFrameOrder(e,t,r,n){this.checkSize(e,t,3);let o=t,i=this.charCodeSize(r),s=n||Math.floor((e.length-t-3)/i);this.checkSize(e,t,3+s*i);let a=[],d=o+3;for(let c=0;c<s;c++){let[u,p]=this.readCharCode(e,d,r);a.push(u),d=p}return{order:{type:5,bgColorCode:e.readUInt8(o+1),fgColorCode:e.readUInt8(o+2),frame:a},bytesRead:3+s*i}}decodeFullFrameMultiColorOrder(e,t,r,n){this.checkSize(e,t,1);let o=t,s=this.charCodeSize(r)+2,a=n||Math.floor((e.length-t-1)/s);this.checkSize(e,t,1+a*s);let d=[],l=o+1;for(let u=0;u<a;u++){let[p,m]=this.readCharCode(e,l,r);l=m,d.push({charCode:p,bgColorCode:e.readUInt8(l++),fgColorCode:e.readUInt8(l++)})}return{order:{type:6,frame:d},bytesRead:1+a*s}}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 s=[];for(let d=0;d<i;d++){let l=r+5+d*2;s.push({bgColorCode:e.readUInt8(l),fgColorCode:e.readUInt8(l+1)})}return{order:{type:9,posX:e.readUInt8(r+1),posY:e.readUInt8(r+2),sizeX:n,sizeY:o,colorData:s},bytesRead:5+i*2}}decodeShapeOrder(e,t,r){this.checkSize(e,t,2);let n=t,o=e.readUInt8(n+1),{shapeData:i,bytesRead:s}=this.decodeShapeData(e,n+2,o,r);return{order:{type:10,shapeType:o,shapeData:i},bytesRead:2+s}}decodeShapeData(e,t,r,n){let o=t,i=this.charCodeSize(n);switch(r){case 1:{let s=7+i;this.checkSize(e,t,s);let a=e.readUInt8(o++),d=e.readUInt8(o++),l=e.readUInt8(o++)+1,c=e.readUInt8(o++)+1,u=e.readUInt8(o++)===1,[p,m]=this.readCharCode(e,o,n);o=m;let b=e.readUInt8(o++),C=e.readUInt8(o++);return{shapeData:{posX:a,posY:d,width:l,height:c,filled:u,charCode:p,bgColorCode:b,fgColorCode:C},bytesRead:s}}case 2:{let s=6+i;this.checkSize(e,t,s);let a=e.readUInt8(o++),d=e.readUInt8(o++),l=e.readUInt8(o++)+1,c=e.readUInt8(o++)===1,[u,p]=this.readCharCode(e,o,n);o=p;let m=e.readUInt8(o++),b=e.readUInt8(o++);return{shapeData:{centerX:a,centerY:d,radius:l,filled:c,charCode:u,bgColorCode:m,fgColorCode:b},bytesRead:s}}case 3:{let s=6+i;this.checkSize(e,t,s);let a=e.readUInt8(o++),d=e.readUInt8(o++),l=e.readUInt8(o++),c=e.readUInt8(o++),[u,p]=this.readCharCode(e,o,n);o=p;let m=e.readUInt8(o++),b=e.readUInt8(o++);return{shapeData:{x1:a,y1:d,x2:l,y2:c,charCode:u,bgColorCode:m,fgColorCode:b},bytesRead:s}}case 4:{let s=7+i;this.checkSize(e,t,s);let a=e.readUInt8(o++),d=e.readUInt8(o++),l=e.readUInt8(o++)+1,c=e.readUInt8(o++)+1,u=e.readUInt8(o++)===1,[p,m]=this.readCharCode(e,o,n);o=m;let b=e.readUInt8(o++),C=e.readUInt8(o++);return{shapeData:{centerX:a,centerY:d,radiusX:l,radiusY:c,filled:u,charCode:p,bgColorCode:b,fgColorCode:C},bytesRead:s}}case 5:{let s=9+i;this.checkSize(e,t,s);let a=e.readUInt8(o++),d=e.readUInt8(o++),l=e.readUInt8(o++),c=e.readUInt8(o++),u=e.readUInt8(o++),p=e.readUInt8(o++),m=e.readUInt8(o++)===1,[b,C]=this.readCharCode(e,o,n);o=C;let S=e.readUInt8(o++),O=e.readUInt8(o++);return{shapeData:{x1:a,y1:d,x2:l,y2:c,x3:u,y3:p,filled:m,charCode:b,bgColorCode:S,fgColorCode:O},bytesRead:s}}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,s=e.readUInt8(i++),[a,d]=this.readCharCode(e,i,r);i=d;let l=e.readUInt8(i++),c=e.readUInt8(i++),u=e.readUInt16BE(i);i+=2,this.checkSize(e,t,o+u*2);let p=[];for(let b=0;b<u;b++)p.push({posX:e.readUInt8(i++),posY:e.readUInt8(i++)});return{order:{type:11,charCode:a,bgColorCode:l,fgColorCode:c,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),s=n+4;this.checkSize(e,t,3+i*s);let a=[],d=o+3;for(let c=0;c<i;c++){let[u,p]=this.readCharCode(e,d,r);d=p,a.push({charCode:u,bgColorCode:e.readUInt8(d++),fgColorCode:e.readUInt8(d++),posX:e.readUInt8(d++),posY:e.readUInt8(d++)})}return{order:{type:12,dots:a},bytesRead:3+i*s}}decodeBitmaskOrder(e,t,r){let o=8+this.charCodeSize(r);this.checkSize(e,t,o);let i=t,s=e.readUInt8(i++),a=e.readUInt8(i++),d=e.readUInt8(i++),l=e.readUInt8(i++)+1,c=e.readUInt8(i++)+1,[u,p]=this.readCharCode(e,i,r);i=p;let m=e.readUInt8(i++),b=e.readUInt8(i++),C=e.readUInt8(i++)===1,S=Math.ceil(l*c/8);this.checkSize(e,t,o+S);let O=new Uint8Array(S);for(let v=0;v<S;v++)O[v]=e.readUInt8(i+v);return{order:{type:17,posX:a,posY:d,sizeX:l,sizeY:c,charCode:u,bgColorCode:m,fgColorCode:b,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 s=t,a=e.readUInt8(s++),d=e.readUInt8(s++),l=e.readUInt8(s++),c=e.readUInt8(s++)+1,u=e.readUInt8(s++)+1,p=e.readUInt8(s++)===1,m=Math.ceil(c*u/4);this.checkSize(e,t,i+m);let b=[];for(let O=0;O<3;O++){let[I,v]=this.readCharCode(e,s,r);s=v,b.push({charCode:I,bgColorCode:e.readUInt8(s++),fgColorCode:e.readUInt8(s++)})}let C=new Uint8Array(m);for(let O=0;O<m;O++)C[O]=e.readUInt8(s+O);return{order:{type:18,posX:d,posY:l,sizeX:c,sizeY:u,override:p,variants:b,mask:C},bytesRead:i+m}}decodeBitmask16Order(e,t,r){let i=6+15*(this.charCodeSize(r)+2);this.checkSize(e,t,i);let s=t,a=e.readUInt8(s++),d=e.readUInt8(s++),l=e.readUInt8(s++),c=e.readUInt8(s++)+1,u=e.readUInt8(s++)+1,p=e.readUInt8(s++)===1,m=Math.ceil(c*u/2);this.checkSize(e,t,i+m);let b=[];for(let O=0;O<15;O++){let[I,v]=this.readCharCode(e,s,r);s=v,b.push({charCode:I,bgColorCode:e.readUInt8(s++),fgColorCode:e.readUInt8(s++)})}let C=new Uint8Array(m);for(let O=0;O<m;O++)C[O]=e.readUInt8(s+O);return{order:{type:24,posX:d,posY:l,sizeX:c,sizeY:u,override:p,variants:b,mask:C},bytesRead:i+m}}decodePolylineOrder(e,t,r){let o=4+this.charCodeSize(r);this.checkSize(e,t,o);let i=t,s=e.readUInt8(i++),[a,d]=this.readCharCode(e,i,r);i=d;let l=e.readUInt8(i++),c=e.readUInt8(i++),u=e.readUInt8(i++);this.checkSize(e,t,o+u*2);let p=[];for(let b=0;b<u;b++)p.push({x:e.readUInt8(i++),y:e.readUInt8(i++)});return{order:{type:25,charCode:a,fgColorCode:l,bgColorCode:c,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 s=0;s<n;s++){let a=r+6+s*2;o.push({posX:e.readUInt8(a),posY:e.readUInt8(a+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 s=0;s<n;s++){let a=r+4+s*2;o.push({posX:e.readUInt8(a),posY:e.readUInt8(a+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 s=0;s<n;s++){let a=r+3+s*5;o.push({spriteIndex:e.readUInt8(a),bgColorCode:e.readUInt8(a+1),fgColorCode:e.readUInt8(a+2),posX:e.readUInt8(a+3),posY:e.readUInt8(a+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 s=0;s<n;s++){let a=r+3+s*3;o.push({spriteIndex:e.readUInt8(a),posX:e.readUInt8(a+1),posY:e.readUInt8(a+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,s=e.readUInt8(i++),[a,d]=this.readCharCode(e,i,r);i=d;let l=e.readUInt8(i++),c=e.readUInt8(i++);return{order:{type:19,charCode:a,bgColorCode:l,fgColorCode:c},bytesRead:o}}decodeFillCharOrder(e,t,r){this.checkSize(e,t,5);let n=this.charCodeSize(r),o=t,i=e.readUInt8(o+1)+1,s=e.readUInt8(o+2)+1,a=i*s,d=5+a*n;this.checkSize(e,t,d);let l=[],c=o+5;for(let p=0;p<a;p++){let[m,b]=this.readCharCode(e,c,r);l.push(m),c=b}return{order:{type:20,patternWidth:i,patternHeight:s,bgColorCode:e.readUInt8(o+3),fgColorCode:e.readUInt8(o+4),pattern:l},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(yt,"OrderDecoder");Q=yt});var ft,ee,St=T(()=>{"use strict";ft=class ft{decode(e,t=0){this.checkSize(e,t,7);let n=t,o=e.readUInt8(n++),i=e.readUInt16BE(n);n+=2;let s=e.readUInt16BE(n);n+=2;let a=e.readUInt8(n++)+1,d=e.readUInt8(n++)+1;return{display:{id:o,originX:i,originY:s,sizeX:a,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(ft,"DisplayDecoder");ee=ft});var wn,It,te,Ot=T(()=>{"use strict";Ct();wn=64,It=class It{constructor(){h(this,"orderDecoder");this.orderDecoder=new Q}decode(e,t=0){this.checkSize(e,t,13);let n=t,o=e.readUInt16BE(n);n+=2;let i=e.readUInt8(n++),s=e.readUInt8(n++),a=e.readUInt16BE(n);n+=2;let d=e.readUInt16BE(n);n+=2;let l=e.readUInt16BE(n);n+=2;let c=e.readUInt16BE(n);n+=2;let u=e.readUInt8(n++),p=(i&wn)!==0,m=[],b=n;for(let S=0;S<u;S++){let O=this.orderDecoder.decode(e,b,p);m.push(O.order),b+=O.bytesRead}return{layer:{id:o,updateFlags:i,zIndex:s,originX:a,originY:d,width:l,height:c,orderCount:u,orders:m,is16bit:p},bytesRead:b-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(It,"LayerDecoder");te=It});var xt,we,sn=T(()=>{"use strict";xt=class xt{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 s=e.readUInt8(r++),a={type:n,soundId:o,instanceId:i,flags:s};return s&2&&(this.checkSize(e,r,1),a.volume=e.readUInt8(r++)),s&4&&(this.checkSize(e,r,1),a.pitch=e.readUInt8(r++)),s&8&&(this.checkSize(e,r,1),a.fadeIn=e.readUInt8(r++)),s&16&&(this.checkSize(e,r,4),a.posX=e.readUInt16BE(r),r+=2,a.posY=e.readUInt16BE(r),r+=2),s&32&&(this.checkSize(e,r,1),a.lowpass=e.readUInt8(r++)),s&64&&(this.checkSize(e,r,1),a.highpass=e.readUInt8(r++)),s&128&&(this.checkSize(e,r,1),a.reverb=e.readUInt8(r++)),{order:a,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 s=e.readUInt8(r++),a={type:n,soundId:o,instanceId:i,flags:s};return s&2&&(this.checkSize(e,r,1),a.volume=e.readUInt8(r++)),s&4&&(this.checkSize(e,r,1),a.pitch=e.readUInt8(r++)),s&8&&(this.checkSize(e,r,1),a.fadeIn=e.readUInt8(r++)),s&32&&(this.checkSize(e,r,1),a.lowpass=e.readUInt8(r++)),s&64&&(this.checkSize(e,r,1),a.highpass=e.readUInt8(r++)),s&128&&(this.checkSize(e,r,1),a.reverb=e.readUInt8(r++)),{order:a,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++),s={type:n,targetType:o,duration:i};return o===0?(this.checkSize(e,r,2),s.target=e.readUInt16BE(r),r+=2):o===1&&(this.checkSize(e,r,1),s.target=e.readUInt8(r++)),{order:s,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++),s={type:n,instanceId:o,flags:i};return i&1&&(this.checkSize(e,r,1),s.lowpass=e.readUInt8(r++)),i&2&&(this.checkSize(e,r,1),s.highpass=e.readUInt8(r++)),i&4&&(this.checkSize(e,r,1),s.reverb=e.readUInt8(r++)),{order:s,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(xt,"AudioOrderDecoder");we=xt});var vt,Ue,an=T(()=>{"use strict";vt=class vt{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++),s=[];for(let d=0;d<i;d++)s.push(e.readUInt16BE(r)),r+=2;let a={type:n,flags:o,pattern:s};return o&1&&(a.intensity=e.readUInt8(r++)/255),{order:a,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++),s=e.readUInt16BE(r);r+=2;let a=e.readUInt8(r++),d=e.readUInt8(r++),l={type:n,flags:o,gamepadIndex:i,duration:s,strongMagnitude:a,weakMagnitude:d};return o&1&&(l.startDelay=e.readUInt16BE(r),r+=2),{order:l,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(vt,"VibrationOrderDecoder");Ue=vt});var wt,re,Ut=T(()=>{"use strict";wt=class wt{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:s,bytesRead:a}=this.decode(e,t+o);n.push(s),o+=a}return{orders:n,bytesRead:o}}decodeCreateInstance(e,t){let r=t,n=e.readUInt8(t++),o=e.readUInt8(t++),i=e.readUInt8(t++),s=e.readUInt8(t++),a=e.readInt16BE(t);t+=2;let d=e.readInt16BE(t);t+=2;let l=e.readUInt8(t++),c=e.readUInt16BE(t);t+=2;let u=e.toUint8Array().subarray(t,t+c);t+=c;let p=new TextDecoder().decode(u),m=JSON.parse(p);return{order:{type:n,instanceId:o,macroId:i,layerId:s,x:a,y:d,tabIndex:l,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 s=e.toUint8Array().subarray(t,t+i);t+=i;let a=new TextDecoder().decode(s),d=JSON.parse(a);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(wt,"MacroOrderDecoder");re=wt});var Mt,Me,dn=T(()=>{"use strict";Mt=class Mt{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++],s={type:n,displayId:o,flags:i};return i&1&&(s.scanlines={enabled:e[r++]===1,opacity:e[r++]/255,pattern:e[r++],colorR:e[r++],colorG:e[r++],colorB:e[r++]}),i&2&&(s.ambientEffect={enabled:e[r++]===1,blur:e[r++],scale:e[r++]/100,opacity:e[r++]/255}),{order:s,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(Mt,"PostProcessOrderDecoder");Me=Mt});var ln={};W(ln,{UpdatePacketDecoder:()=>me});var Et,me,At=T(()=>{"use strict";St();Ot();sn();an();Ut();dn();B();Et=class Et{constructor(){h(this,"displayDecoder");h(this,"layerDecoder");h(this,"audioOrderDecoder");h(this,"vibrationOrderDecoder");h(this,"macroOrderDecoder");h(this,"postProcessOrderDecoder");this.displayDecoder=new ee,this.layerDecoder=new te,this.audioOrderDecoder=new we,this.vibrationOrderDecoder=new Ue,this.macroOrderDecoder=new re,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 s=r.readUInt8(o);o+=1;let a=[],d=0;for(let k=0;k<s;k++){let x=this.displayDecoder.decode(r,o);a.push(x.display),o+=x.bytesRead,d+=x.bytesRead}this.checkSize(r,o,2);let l=r.readUInt16BE(o);o+=2;let c=[],u=0;for(let k=0;k<l;k++){let x=this.layerDecoder.decode(r,o);c.push({...x.layer,byteSize:x.bytesRead}),o+=x.bytesRead,u+=x.bytesRead}this.checkSize(r,o,1);let p=r.readUInt8(o);o+=1;let m=[],b=0;for(let k=0;k<p;k++){let x=this.audioOrderDecoder.decode(r,o);m.push(x.order),o+=x.bytesRead,b+=x.bytesRead}this.checkSize(r,o,1);let C=r.readUInt8(o);o+=1;let S=[],O=0;for(let k=0;k<C;k++){let x=this.vibrationOrderDecoder.decode(r,o);S.push(x.order),o+=x.bytesRead,O+=x.bytesRead}this.checkSize(r,o,1);let I=r.readUInt8(o);o+=1;let v=[],M=0;for(let k=0;k<I;k++){let x=this.macroOrderDecoder.decode(r,o);v.push(x.order),o+=x.bytesRead,M+=x.bytesRead}this.checkSize(r,o,1);let A=r.readUInt8(o);o+=1;let E=[],U=0;for(let k=0;k<A;k++){let x=this.postProcessOrderDecoder.decode(r.toUint8Array(),o);E.push(x.order),o+=x.bytesRead,U+=x.bytesRead}return{tick:i,displayCount:s,displays:a,layerCount:l,layers:c,audioOrderCount:p,audioOrders:m,vibrationOrderCount:C,vibrationOrders:S,macroOrderCount:I,macroOrders:v,postProcessOrderCount:A,postProcessOrders:E,__byteSizes:{displays:d,layers:u,audioOrders:b,vibrationOrders:O,macroOrders:M,postProcessOrders:U}}}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 s=r.readUInt16BE(n);return{tick:o,displayCount:i,layerCount:s}}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(Et,"UpdatePacketDecoder");me=Et});var Ln={};W(Ln,{BufferCompat:()=>f,CellBuffer:()=>N,Core:()=>je,DisplayDecoder:()=>ee,DisplayEncoder:()=>Se,DisplayRasterizer:()=>ae,Layer:()=>le,LayerDecoder:()=>te,LayerEncoder:()=>j,LayerRasterizer:()=>se,LoadDecoder:()=>oe,LoadEncoder:()=>D,MacroEventDecoder:()=>ie,MacroEventEncoder:()=>ve,MacroLoadDecoder:()=>ne,MacroLoadEncoder:()=>K,MacroOrderDecoder:()=>re,MacroOrderEncoder:()=>J,OrderBuilder:()=>Ee,OrderDecoder:()=>Q,OrderEncoder:()=>Z,ShapeType:()=>Je,SpriteRegistry:()=>de,UpdatePacketDecoder:()=>me,UpdatePacketEncoder:()=>q,Vector2:()=>yn.Vector2});module.exports=G(Ln);$();$();B();var st=class st{constructor(){h(this,"charCodeSize",fe)}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(lr+(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(cr+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(ur+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(pr+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 s of e.frame)i=this.writeCharCode(o,s,i,t);return o.toUint8Array()}encodeSubFrameMultiColorOrder(e,t){let r=e.sizeX*e.sizeY,n=this.charCodeSize(t),o=f.allocUnsafe(mr+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 s of e.frame)i=this.writeCharCode(o,s.charCode,i,t),o.writeUInt8(s.bgColorCode,i++),o.writeUInt8(s.fgColorCode,i++);return o.toUint8Array()}encodeFullFrameOrder(e,t){let r=e.frame.length,n=this.charCodeSize(t),o=f.allocUnsafe(hr+r*n),i=0;o.writeUInt8(e.type,i++),o.writeUInt8(e.bgColorCode,i++),o.writeUInt8(e.fgColorCode,i++);for(let s of e.frame)i=this.writeCharCode(o,s,i,t);return o.toUint8Array()}encodeFullFrameMultiColorOrder(e,t){let r=e.frame.length,n=this.charCodeSize(t),o=f.allocUnsafe(br+r*(n+2)),i=0;o.writeUInt8(e.type,i++);for(let s of e.frame)i=this.writeCharCode(o,s.charCode,i,t),o.writeUInt8(s.bgColorCode,i++),o.writeUInt8(s.fgColorCode,i++);return o.toUint8Array()}encodeSpriteOrder(e){let t=f.allocUnsafe(gr),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(yr),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(Cr+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(fr+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(Sr+(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(Ir+(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(Or+(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(xr+(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(vr+(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 s of e.positions)o.writeUInt8(s.posX,i++),o.writeUInt8(s.posY,i++);return o.toUint8Array()}encodeDotCloudMultiColorOrder(e,t){let r=e.dots.length,n=this.charCodeSize(t),o=f.allocUnsafe(Ur+r*(n+4)),i=0;o.writeUInt8(e.type,i++),o.writeUInt16BE(r,i),i+=2;for(let s of e.dots)i=this.writeCharCode(o,s.charCode,i,t),o.writeUInt8(s.bgColorCode,i++),o.writeUInt8(s.fgColorCode,i++),o.writeUInt8(s.posX,i++),o.writeUInt8(s.posY,i++);return o.toUint8Array()}encodeBitmaskOrder(e,t){let r=e.mask.length,n=f.allocUnsafe(Mr+(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(Er+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 s of e.variants)i=this.writeCharCode(o,s.charCode,i,t),o.writeUInt8(s.bgColorCode,i++),o.writeUInt8(s.fgColorCode,i++);for(let s=0;s<r;s++)o.writeUInt8(e.mask[s],i++);return o.toUint8Array()}encodeBitmask16Order(e,t){let r=e.mask.length,n=this.charCodeSize(t),o=f.allocUnsafe(Ar+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 s of e.variants)i=this.writeCharCode(o,s.charCode,i,t),o.writeUInt8(s.bgColorCode,i++),o.writeUInt8(s.fgColorCode,i++);for(let s=0;s<r;s++)o.writeUInt8(e.mask[s],i++);return o.toUint8Array()}encodePolylineOrder(e,t){let r=e.points.length,n=f.allocUnsafe(Pr+(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(Rr+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+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(zr+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(Br+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(Tr+(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(Fr+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 s of e.pattern)i=this.writeCharCode(o,s,i,t);return o.toUint8Array()}encodeFillSpriteOrder(e){let t=f.allocUnsafe(Lr),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(Dr),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.spriteIndex,r++),t.toUint8Array()}};y(st,"OrderEncoder");var Z=st;B();var at=class at{encode(e){let t=f.allocUnsafe(7),r=0;return t.writeUInt8(e.id,r++),t.writeUInt16BE(e.originX,r),r+=2,t.writeUInt16BE(e.originY,r),r+=2,t.writeUInt8(e.sizeX-1,r++),t.writeUInt8(e.sizeY-1,r++),t.toUint8Array()}calculateSize(e){return 7}};y(at,"DisplayEncoder");var Se=at;B();var Nr=255,Yr=64,dt=class dt{constructor(){h(this,"orderEncoder");this.orderEncoder=new Z}encode(e){let t=e.is16bit;if(e.orders.length>Nr)throw new Error(`[UTSP] LayerEncoder: Layer ${e.id} has ${e.orders.length} orders, max is ${Nr}. This would cause packet corruption! Split into multiple layers.`);let r=e.orders.map(l=>this.orderEncoder.encode(l,t)),n=13,o=r.reduce((l,c)=>l+c.length,0),i=n+o,s=f.allocUnsafe(i),a=0;s.writeUInt16BE(e.id,a),a+=2;let d=e.updateFlags;t?d|=Yr:d&=~Yr,s.writeUInt8(d,a++),s.writeUInt8(e.zIndex,a++),s.writeUInt16BE(e.originX,a),a+=2,s.writeUInt16BE(e.originY,a),a+=2,s.writeUInt16BE(e.width,a),a+=2,s.writeUInt16BE(e.height,a),a+=2,s.writeUInt8(e.orders.length,a++);for(let l of r)f.from(l).copy(s,a),a+=l.length;return s.toUint8Array()}calculateSize(e){let r=e.is16bit;return 13+e.orders.reduce((o,i)=>o+this.orderEncoder.encode(i,r).length,0)}};y(dt,"LayerEncoder");var j=dt;B();$();var lt=class lt{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 qe;case 8:return Ke;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=Vr;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=Hr,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(qe),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(Ke),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(lt,"AudioOrderEncoder");var Ie=lt;B();var ct=class ct{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 s=Math.min(65535,Math.max(0,Math.round(i)));r.writeUInt16BE(s,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 s=Math.min(65535,Math.max(0,Math.round(e.startDelay)));r.writeUInt16BE(s,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(ct,"VibrationOrderEncoder");var Oe=ct;B();var ut=class ut{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(ut,"MacroOrderEncoder");var J=ut;B();$();var pt=class pt{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 Qe;case 3:return et;case 4:return tt;case 5:return rt;case 6:return nt;case 7:return ot;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=_r;return e.flags&1&&(t+=6),e.flags&2&&(t+=4),t}encodeSetScanlinesOrder(e){let t=f.allocUnsafe(Qe),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(et),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(tt),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(rt),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(nt),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(ot),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(pt,"PostProcessOrderEncoder");var xe=pt;B();var mt=class mt{constructor(){h(this,"layerEncoder");h(this,"audioOrderEncoder");h(this,"vibrationOrderEncoder");h(this,"macroOrderEncoder");h(this,"postProcessOrderEncoder");this.layerEncoder=new j,this.audioOrderEncoder=new Ie,this.vibrationOrderEncoder=new Oe,this.macroOrderEncoder=new J,this.postProcessOrderEncoder=new xe}encode(e){let t=e.layers.map(x=>this.layerEncoder.encode(x)),r=e.audioOrders||[],n=r.map(x=>this.audioOrderEncoder.encode(x)),o=e.vibrationOrders||[],i=o.map(x=>this.vibrationOrderEncoder.encode(x)),s=e.macroOrders||[],a=s.map(x=>this.macroOrderEncoder.encode(x)),d=e.postProcessOrders||[],l=d.map(x=>this.postProcessOrderEncoder.encode(x)),c=9,u=e.displays.length*7,p=2,m=t.reduce((x,L)=>x+L.length,0),b=1,C=n.reduce((x,L)=>x+L.length,0),S=1,O=i.reduce((x,L)=>x+L.length,0),I=1,v=a.reduce((x,L)=>x+L.length,0),M=1,A=l.reduce((x,L)=>x+L.length,0),E=c+u+p+m+b+C+S+O+I+v+M+A,U=f.allocUnsafe(E),w=0,k=typeof e.tick=="bigint"?e.tick:BigInt(e.tick);U.writeBigUInt64BE(k,w),w+=8,U.writeUInt8(e.displays.length,w),w+=1;for(let x of e.displays)U.writeUInt8(x.id,w++),U.writeUInt16BE(x.originX,w),w+=2,U.writeUInt16BE(x.originY,w),w+=2,U.writeUInt8(Math.max(1,Math.min(256,x.sizeX))-1,w++),U.writeUInt8(Math.max(1,Math.min(256,x.sizeY))-1,w++);U.writeUInt16BE(e.layers.length,w),w+=2;for(let x of t)f.from(x).copy(U,w),w+=x.length;U.writeUInt8(r.length,w),w+=1;for(let x of n)f.from(x).copy(U,w),w+=x.length;U.writeUInt8(o.length,w),w+=1;for(let x of i)f.from(x).copy(U,w),w+=x.length;U.writeUInt8(s.length,w),w+=1;for(let x of a)f.from(x).copy(U,w),w+=x.length;U.writeUInt8(d.length,w),w+=1;for(let x of l)f.from(x).copy(U,w),w+=x.length;return U.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,a=(e.audioOrders||[]).reduce((O,I)=>O+this.audioOrderEncoder.calculateSize(I),0),d=1,c=(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),b=1,S=(e.postProcessOrders||[]).reduce((O,I)=>O+this.postProcessOrderEncoder.calculateSize(I),0);return 9+r+n+o+i+a+d+c+u+m+b+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=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(mt,"UpdatePacketEncoder");var q=mt;B();var ht=class ht{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 s of e.colors)o.writeUInt8(s.colorId,i++),o.writeUInt8(s.r,i++),o.writeUInt8(s.g,i++),o.writeUInt8(s.b,i++),o.writeUInt8(s.a,i++),o.writeUInt8(s.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 s of i.data)n.writeUInt8(s,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 s of i.data)n.writeUInt8(s.charCode,o++),n.writeUInt8(s.fgColorId,o++),n.writeUInt8(s.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 s of e.characters){if(s.bitmap.length!==r)throw new Error(`Character ${s.charCode}: bitmap size ${s.bitmap.length} does not match expected ${r} bytes`);o.writeUInt8(s.charCode,i++);for(let a=0;a<s.bitmap.length;a++)o.writeUInt8(s.bitmap[a],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 s=0;s<i.midiData.length;s++)n.writeUInt8(i.midiData[s],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 s=4;s+=r.length,s+=2,e.offsetX!==void 0&&(s+=2),e.offsetY!==void 0&&(s+=2),e.charSpacing!==void 0&&(s+=2),e.lineHeight!==void 0&&(s+=2),e.fontWeight!==void 0&&(s+=1+n.length),e.fontStyle!==void 0&&(s+=1+o.length);let a=f.allocUnsafe(s),d=0;a.writeUInt8(6,d++),a.writeUInt8(e.fontId,d++),a.writeUInt8(i,d++),a.writeUInt8(r.length,d++);for(let l=0;l<r.length;l++)a.writeUInt8(r[l],d++);if(a.writeUInt16BE(e.fontSize,d),d+=2,e.offsetX!==void 0&&(a.writeInt16BE(e.offsetX,d),d+=2),e.offsetY!==void 0&&(a.writeInt16BE(e.offsetY,d),d+=2),e.charSpacing!==void 0&&(a.writeInt16BE(e.charSpacing,d),d+=2),e.lineHeight!==void 0&&(a.writeUInt16BE(Math.round(e.lineHeight*100),d),d+=2),e.fontWeight!==void 0){a.writeUInt8(n.length,d++);for(let l=0;l<n.length;l++)a.writeUInt8(n[l],d++)}if(e.fontStyle!==void 0){a.writeUInt8(o.length,d++);for(let l=0;l<o.length;l++)a.writeUInt8(o[l],d++)}return a.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(ht,"LoadEncoder");var D=ht;B();var bt=class bt{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(bt,"MacroLoadEncoder");var K=bt;B();var gt=class gt{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(gt,"MacroEventEncoder");var ve=gt;Ct();St();Ot();At();Ut();B();var Pt=class Pt{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 s=e.toUint8Array().subarray(t,t+i);t+=i;let a=new TextDecoder().decode(s),d=JSON.parse(a);return{load:{loadType:7,macroId:o,template:d},bytesRead:t-r}}};y(Pt,"MacroLoadDecoder");var ne=Pt;var Rt=class Rt{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,s;i&&(this.checkSize(e,t,1,"ColorPalette slotId"),s=e.readUInt8(t++));let a=e.readUInt8(t++);this.checkSize(e,t,a*6,`ColorPalette ${a} colors`);let d=[];for(let c=0;c<a;c++)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,...s!==void 0&&{slotId:s},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 a=0;a<o;a++){this.checkSize(e,t,3,`Sprite ${a} header`);let d=e.readUInt8(t++),l=e.readUInt8(t++),c=e.readUInt8(t++),u=l*c;this.checkSize(e,t,u,`Sprite ${a} data`);let p=[];for(let m=0;m<u;m++)p.push(e.readUInt8(t++));i.push({spriteId:d,sizeX:l,sizeY:c,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 a=0;a<o;a++){this.checkSize(e,t,3,`MulticolorSprite ${a} header`);let d=e.readUInt8(t++),l=e.readUInt8(t++),c=e.readUInt8(t++),u=l*c,p=u*3;this.checkSize(e,t,p,`MulticolorSprite ${a} data`);let m=[];for(let b=0;b<u;b++)m.push({charCode:e.readUInt8(t++),fgColorId:e.readUInt8(t++),bgColorId:e.readUInt8(t++)});i.push({spriteId:d,sizeX:l,sizeY:c,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++),s=e.readUInt8(t++),a=e.readUInt8(t++),d=e.readUInt8(t++),l=e.readUInt8(t++),c=Math.ceil(i*s/8),u=[];for(let m=0;m<l;m++){this.checkSize(e,t,1+c,`BitmapFont character ${m}`);let b=e.readUInt8(t++),C=new Uint8Array(c);for(let S=0;S<c;S++)C[S]=e.readUInt8(t++);u.push({charCode:b,bitmap:C})}return{load:{loadType:4,fontId:o,width:i,height:s,cellWidth:a,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 a=0;a<o;a++){this.checkSize(e,t,3,`Sound ${a} header`);let d=e.readUInt8(t++),l=e.readUInt16BE(t);t+=2,this.checkSize(e,t,l,`Sound ${a} MIDI data`);let c=new Uint8Array(l);for(let u=0;u<l;u++)c[u]=e.readUInt8(t++);i.push({soundId:d,midiData:c})}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++),s=e.readUInt8(t++),a=e.readUInt8(t++);this.checkSize(e,t,a,"WebFont family string");let d=new Uint8Array(a);for(let p=0;p<a;p++)d[p]=e.readUInt8(t++);let l=n.decode(d);this.checkSize(e,t,2,"WebFont fontSize");let c=e.readUInt16BE(t);t+=2;let u={loadType:6,fontId:i,fontFamily:l,fontSize:c};if(s&1&&(this.checkSize(e,t,2,"WebFont offsetX"),u.offsetX=e.readInt16BE(t),t+=2),s&2&&(this.checkSize(e,t,2,"WebFont offsetY"),u.offsetY=e.readInt16BE(t),t+=2),s&4&&(this.checkSize(e,t,2,"WebFont charSpacing"),u.charSpacing=e.readInt16BE(t),t+=2),s&8){this.checkSize(e,t,2,"WebFont lineHeight");let p=e.readUInt16BE(t);u.lineHeight=p/100,t+=2}if(s&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 b=0;b<p;b++)m[b]=e.readUInt8(t++);u.fontWeight=n.decode(m)}if(s&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 b=0;b<p;b++)m[b]=e.readUInt8(t++);u.fontStyle=n.decode(m)}return{load:u,bytesRead:t-r}}decodeMacro(e,t){return new ne().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++),s=e.readUInt8(t++),a=e.readUInt8(t++),d=e.readUInt8(t++),l=e.readUInt8(t++);if(![1,4,16].includes(l))throw new Error(`Invalid atlasBlocks value: ${l}. Must be 1, 4, or 16.`);let c=l;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 b=0;b<u;b++)p[b]=e.readUInt8(t++);return{load:{loadType:8,fontId:o,glyphWidth:i,glyphHeight:s,cellWidth:a,cellHeight:d,atlasBlocks:c,imageData:p},bytesRead:t-r}}};y(Rt,"LoadDecoder");var oe=Rt;var kt=class kt{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:s,bytesRead:a}=this.decode(e,t+o);n.push(s),o+=a}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,s;return o===1?(i=e.readUInt8(t+3)===1,s=4):(i=e.readFloatBE(t+3),s=7),{event:{type:r,instanceId:n,value:i},bytesRead:s}}decodeSubmit(e,t){let r=t,n=e.readUInt8(t++),o=e.readUInt8(t++),i=e.readUInt16BE(t);t+=2;let s=e.toUint8Array().subarray(t,t+i);t+=i;let a=new TextDecoder().decode(s);return{event:{type:n,instanceId:o,text:a},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(kt,"MacroEventDecoder");var ie=kt;var Un=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 he(g){if(g<128)return g;let e=Un.get(g);return e!==void 0?e:g&255}y(he,"unicodeToCp437");var zt=class zt{constructor(){h(this,"currentWidth",256);h(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:s}=e;if(!this.isInBounds(r,n))return;let a=n*this.currentWidth+r;t.set(a,o,s,i)}rasterizeText(e,t){let{posX:r,posY:n,text:o,bgColorCode:i,fgColorCode:s}=e;if(this.isInBounds(r,n))for(let a=0;a<o.length;a++){let d=r+a;if(d>=this.currentWidth)break;let l=n*this.currentWidth+d,c=o.charCodeAt(a),u=he(c);t.set(l,u,s,i)}}rasterizeTextMultiline(e,t){let{posX:r,posY:n,text:o,bgColorCode:i,fgColorCode:s}=e,a=o.split(`
|
|
2
|
-
`),d=n;for(let l of a){if(d>=this.currentHeight)break;if(d>=0&&this.isInBounds(r,d))for(let c=0;c<l.length;c++){let u=r+c;if(u>=this.currentWidth)break;let p=d*this.currentWidth+u,m=l.charCodeAt(c),b=he(m);t.set(p,b,s,i)}d++}}rasterizeSubFrame(e,t){let{posX:r,posY:n,sizeX:o,sizeY:i,frame:s,bgColorCode:a,fgColorCode:d}=e;for(let l=0;l<i;l++){let c=n+l;if(!(c<0||c>=this.currentHeight))for(let u=0;u<o;u++){let p=r+u;if(p<0||p>=this.currentWidth)continue;let m=l*o+u;if(m>=s.length)break;let b=c*this.currentWidth+p;t.set(b,s[m],d,a)}}}rasterizeSubFrameMultiColor(e,t){let{posX:r,posY:n,sizeX:o,sizeY:i,frame:s}=e;for(let a=0;a<i;a++){let d=n+a;if(!(d<0||d>=this.currentHeight))for(let l=0;l<o;l++){let c=r+l;if(c<0||c>=this.currentWidth)continue;let u=a*o+l;if(u>=s.length)break;let p=s[u],m=d*this.currentWidth+c;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 s=0;s<i&&s<r.length;s++)t.set(s,r[s],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:s}=e;for(let a=0;a<i;a++){let d=n+a;if(!(d<0||d>=this.currentHeight))for(let l=0;l<o;l++){let c=r+l;if(c<0||c>=this.currentWidth)continue;let u=a*o+l;if(u>=s.length)break;let p=d*this.currentWidth+c,m=s[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:s,charCode:a,bgColorCode:d,fgColorCode:l}=e;if(s)for(let c=0;c<i;c++){let u=n+c;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 b=u*this.currentWidth+m;t.set(b,a,l,d)}}else{for(let c=0;c<o;c++)this.setCell(r+c,n,a,d,l,t),this.setCell(r+c,n+i-1,a,d,l,t);for(let c=0;c<i;c++)this.setCell(r,n+c,a,d,l,t),this.setCell(r+o-1,n+c,a,d,l,t)}}rasterizeCircle(e,t){let{centerX:r,centerY:n,radius:o,filled:i,charCode:s,bgColorCode:a,fgColorCode:d}=e;if(i)for(let l=-o;l<=o;l++){let c=n+l;if(!(c<0||c>=this.currentHeight))for(let u=-o;u<=o;u++){let p=r+u;if(!(p<0||p>=this.currentWidth)&&u*u+l*l<=o*o){let m=c*this.currentWidth+p;t.set(m,s,d,a)}}}else{let l=o,c=0,u=0;for(;l>=c;)this.setCell(r+l,n+c,s,a,d,t),this.setCell(r+c,n+l,s,a,d,t),this.setCell(r-c,n+l,s,a,d,t),this.setCell(r-l,n+c,s,a,d,t),this.setCell(r-l,n-c,s,a,d,t),this.setCell(r-c,n-l,s,a,d,t),this.setCell(r+c,n-l,s,a,d,t),this.setCell(r+l,n-c,s,a,d,t),u<=0&&(c+=1,u+=2*c+1),u>0&&(l-=1,u-=2*l+1)}}rasterizeLine(e,t){let{x1:r,y1:n,x2:o,y2:i,charCode:s,bgColorCode:a,fgColorCode:d}=e,l=Math.abs(o-r),c=Math.abs(i-n),u=r<o?1:-1,p=n<i?1:-1,m=l-c,b=r,C=n;for(;this.setCell(b,C,s,a,d,t),!(b===o&&C===i);){let S=2*m;S>-c&&(m-=c,b+=u),S<l&&(m+=l,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 s=0;s<i.length-1;s++){let a=i[s],d=i[s+1];this.rasterizeLineSegment(a.x,a.y,d.x,d.y,r,o,n,t)}}rasterizeLineSegment(e,t,r,n,o,i,s,a){let d=Math.abs(r-e),l=Math.abs(n-t),c=e<r?1:-1,u=t<n?1:-1,p=d-l,m=e,b=t;for(;this.setCell(m,b,o,i,s,a),!(m===r&&b===n);){let C=2*p;C>-l&&(p-=l,m+=c),C<d&&(p+=d,b+=u)}}rasterizeEllipse(e,t){let{centerX:r,centerY:n,radiusX:o,radiusY:i,filled:s,charCode:a,bgColorCode:d,fgColorCode:l}=e;if(s)for(let c=-i;c<=i;c++){let u=n+c;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)+c*c/(i*i)<=1){let C=u*this.currentWidth+m;t.set(C,a,l,d)}}}else{let c=Math.max(o,i)*8;for(let u=0;u<c;u++){let p=2*Math.PI*u/c,m=Math.round(r+o*Math.cos(p)),b=Math.round(n+i*Math.sin(p));this.setCell(m,b,a,d,l,t)}}}rasterizeTriangle(e,t){let{x1:r,y1:n,x2:o,y2:i,x3:s,y3:a,filled:d,charCode:l,bgColorCode:c,fgColorCode:u}=e;if(d){let p=[{x:r,y:n},{x:o,y:i},{x:s,y:a}].sort((I,v)=>I.y-v.y),[m,b,C]=p,S=y((I,v,M)=>{let A=Math.round(Math.min(v,M)),E=Math.round(Math.max(v,M));for(let U=A;U<=E;U++)if(U>=0&&U<this.currentWidth&&I>=0&&I<this.currentHeight){let w=I*this.currentWidth+U;t.set(w,l,u,c)}},"drawLine"),O=y((I,v,M,A,E)=>A===v?M:M+(I-v)*(E-M)/(A-v),"interpolate");for(let I=m.y;I<=b.y;I++){let v=O(I,m.y,m.x,C.y,C.x),M=O(I,m.y,m.x,b.y,b.x);S(I,v,M)}for(let I=b.y+1;I<=C.y;I++){let v=O(I,m.y,m.x,C.y,C.x),M=O(I,b.y,b.x,C.y,C.x);S(I,v,M)}}else this.drawLineSegment(r,n,o,i,l,c,u,t),this.drawLineSegment(o,i,s,a,l,c,u,t),this.drawLineSegment(s,a,r,n,l,c,u,t)}drawLineSegment(e,t,r,n,o,i,s,a){let d=Math.abs(r-e),l=Math.abs(n-t),c=e<r?1:-1,u=t<n?1:-1,p=d-l,m=e,b=t;for(;this.setCell(m,b,o,i,s,a),!(m===r&&b===n);){let C=2*p;C>-l&&(p-=l,m+=c),C<d&&(p+=d,b+=u)}}rasterizeDotCloud(e,t){let{charCode:r,bgColorCode:n,fgColorCode:o,positions:i}=e,s=this.currentWidth;for(let a=0;a<i.length;a++){let d=i[a];if(d.posX<0||d.posX>=s||d.posY<0||d.posY>=this.currentHeight)continue;let l=d.posY*s+d.posX;t.set(l,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:s,bgColorCode:a,fgColorCode:d,override:l,mask:c}=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 b=r+m;if(b<0||b>=this.currentWidth)continue;let C=u*o+m,S=Math.floor(C/8),O=C%8,I=(c[S]&1<<O)!==0,v=p*this.currentWidth+b;I?t.set(v,s,d,a):l&&t.set(v,255,255,255)}}}rasterizeBitmask4(e,t){let{posX:r,posY:n,sizeX:o,sizeY:i,override:s,variants:a,mask:d}=e;for(let l=0;l<i;l++){let c=n+l;if(!(c<0||c>=this.currentHeight))for(let u=0;u<o;u++){let p=r+u;if(p<0||p>=this.currentWidth)continue;let m=l*o+u,b=Math.floor(m/4),C=m%4*2,S=d[b]>>C&3,O=c*this.currentWidth+p;if(S>0){let I=a[S-1];t.set(O,I.charCode,I.fgColorCode,I.bgColorCode)}else s&&t.set(O,255,255,255)}}}rasterizeBitmask16(e,t){let{posX:r,posY:n,sizeX:o,sizeY:i,override:s,variants:a,mask:d}=e;for(let l=0;l<i;l++){let c=n+l;if(!(c<0||c>=this.currentHeight))for(let u=0;u<o;u++){let p=r+u;if(p<0||p>=this.currentWidth)continue;let m=l*o+u,b=Math.floor(m/2),C=m%2*4,S=d[b]>>C&15,O=c*this.currentWidth+p;if(S>0){let I=a[S-1];t.set(O,I.charCode,I.fgColorCode,I.bgColorCode)}else s&&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:s}=e;for(let a=0;a<this.currentHeight;a++)for(let d=0;d<this.currentWidth;d++){let l=d%r,u=a%n*r+l;if(u<o.length){let p=a*this.currentWidth+d;t.set(p,o[u],s,i)}}}rasterizeSprite(e,t,r){if(!r)return;let{posX:n,posY:o,spriteIndex:i,bgColorCode:s,fgColorCode:a}=e,d=r.getUnicolorSprite(i);if(!d)return;let l=d.data;for(let c=0;c<d.sizeY;c++)for(let u=0;u<d.sizeX;u++){let p=n+u,m=o+c;if(!this.isInBounds(p,m))continue;let b=c*d.sizeX+u,C=l.get(b);this.setCell(p,m,C,s,a,t)}}rasterizeSpriteMultiColor(e,t,r){if(!r)return;let{posX:n,posY:o,spriteIndex:i}=e,s=r.getMulticolorSprite(i);if(!s)return;let a=s.data;for(let d=0;d<s.sizeY;d++)for(let l=0;l<s.sizeX;l++){let c=n+l,u=o+d;if(!this.isInBounds(c,u))continue;let p=d*s.sizeX+l,m=a.getCharCode(p),b=a.getFgColorCode(p),C=a.getBgColorCode(p);this.setCell(c,u,m,C,b,t)}}rasterizeSpriteCloud(e,t,r){if(!r)return;let{spriteIndex:n,bgColorCode:o,fgColorCode:i,positions:s}=e,a=r.getUnicolorSprite(n);if(a){if(a.sizeX===1&&a.sizeY===1){let d=a.data.get(0),l=this.currentWidth;for(let c=0;c<s.length;c++){let u=s[c];if(u.posX<0||u.posX>=l||u.posY<0||u.posY>=this.currentHeight)continue;let p=u.posY*l+u.posX;t.set(p,d,i,o)}return}for(let d=0;d<s.length;d++){let l=a.data;for(let c=0;c<a.sizeY;c++)for(let u=0;u<a.sizeX;u++){let p=s[d].posX+u,m=s[d].posY+c;if(!this.isInBounds(p,m))continue;let b=c*a.sizeX+u,C=l.get(b);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 s=0;s<o.length;s++){let a=i.data;for(let d=0;d<i.sizeY;d++)for(let l=0;l<i.sizeX;l++){let c=o[s].posX+l,u=o[s].posY+d;if(!this.isInBounds(c,u))continue;let p=d*i.sizeX+l,m=a.getCharCode(p),b=a.getFgColorCode(p),C=a.getBgColorCode(p);this.setCell(c,u,m,C,b,t)}}}rasterizeSpriteCloudVaried(e,t,r){if(!r)return;let{sprites:n}=e;for(let o=0;o<n.length;o++){let i=n[o],s=r.getUnicolorSprite(i.spriteIndex);if(!s)continue;let a=s.data;for(let d=0;d<s.sizeY;d++)for(let l=0;l<s.sizeX;l++){let c=i.posX+l,u=i.posY+d;if(!this.isInBounds(c,u))continue;let p=d*s.sizeX+l,m=a.get(p);this.setCell(c,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],s=r.getMulticolorSprite(i.spriteIndex);if(!s)continue;let a=s.data;for(let d=0;d<s.sizeY;d++)for(let l=0;l<s.sizeX;l++){let c=i.posX+l,u=i.posY+d;if(!this.isInBounds(c,u))continue;let p=d*s.sizeX+l,m=a.getCharCode(p),b=a.getFgColorCode(p),C=a.getBgColorCode(p);this.setCell(c,u,m,C,b,t)}}}rasterizeFillSprite(e,t,r){if(!r)return;let{spriteIndex:n,bgColorCode:o,fgColorCode:i}=e,s=r.getUnicolorSprite(n);if(!s)return;let a=s.data;for(let d=0;d<this.currentHeight;d++)for(let l=0;l<this.currentWidth;l++){let c=l%s.sizeX,p=d%s.sizeY*s.sizeX+c,m=a.get(p),b=d*this.currentWidth+l;t.set(b,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 s=0;s<this.currentHeight;s++)for(let a=0;a<this.currentWidth;a++){let d=a%o.sizeX,c=s%o.sizeY*o.sizeX+d,u=i.getCharCode(c),p=i.getFgColorCode(c),m=i.getBgColorCode(c),b=s*this.currentWidth+a;t.set(b,u,p,m)}}setCell(e,t,r,n,o,i){if(!this.isInBounds(e,t))return;let s=t*this.currentWidth+e;i.set(s,r,o,n)}isInBounds(e,t){return e>=0&&e<this.currentWidth&&t>=0&&t<this.currentHeight}};y(zt,"LayerRasterizer");var se=zt;var _=class _{constructor(e){this.engine=e;h(this,"colorCache",new Array(256));h(this,"cellsBuffer",[]);h(this,"opacityBuffer",new Uint8Array(0));h(this,"visibleLayersBuffer",[]);h(this,"visibleLayerIdsBuffer",[]);this.rebuildColorCache()}static getChar(e){let t=_.charCache.get(e);return t===void 0&&(t=String.fromCharCode(e),_.charCache.set(e,t)),t}getLastVisibleLayerIds(){return this.visibleLayerIdsBuffer}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,s=t.x,a=t.x+256,d=t.y,l=t.y+256;return!(n<=s||r>=a||i<=d||o>=l)}rasterize(e,t){let r=e.width*e.height,n=this.cellsBuffer;n.length=r;for(let d=0;d<r;d++)n[d]?(n[d].char=" ",n[d].fgColorIndex=255,n[d].bgColorIndex=255,n[d].fgEmission=0,n[d].bgEmission=0):n[d]={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 d=0;d<t.length;d++){let l=t[d];l.isEnabled()&&this.isLayerVisible(e,l.getOrigin())&&i.push(l)}i.sort((d,l)=>l.getZOrder()-d.getZOrder());let s=this.visibleLayerIdsBuffer;s.length=i.length;for(let d=0;d<i.length;d++)s[d]=i[d].getId();for(let d=0;d<e.height;d++)for(let l=0;l<e.width;l++){let c=d*e.width+l;if(o[c])continue;let u=e.x+l,p=e.y+d;for(let m=0;m<i.length;m++){let b=i[m],C=u-b.getOrigin().x,S=p-b.getOrigin().y,O=b.getWidth(),I=b.getHeight();if(C<0||C>=O||S<0||S>=I)continue;let v=S*O+C,M=b.getData(),A=M.getCharCode(v),E=M.getFgColorCode(v),U=M.getBgColorCode(v),w=n[c];if(A!==0&&w.char===" "&&(w.char=_.getChar(A)),E!==255&&w.fgColorIndex===255&&(w.fgColorIndex=E,w.fgEmission=this.getColorEmission(E)),U!==255){w.bgColorIndex===255&&(w.bgColorIndex=U,w.bgEmission=this.getColorEmission(U)),o[c]=1;break}}}let a=new Array(r);for(let d=0;d<r;d++)a[d]={char:n[d].char,fgColorIndex:n[d].fgColorIndex,bgColorIndex:n[d].bgColorIndex,fgEmission:n[d].fgEmission,bgEmission:n[d].bgEmission};return{id:e.id,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 a=0;a<r;a++)n[a]?(n[a].char=" ",n[a].fgColorIndex=255,n[a].bgColorIndex=255,n[a].fgEmission=0,n[a].bgEmission=0):n[a]={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 a=0;a<t.length;a++){let d=t[a];this.isLayerVisible(e,d.getOrigin())&&i.push(d)}for(let a=0;a<e.height;a++)for(let d=0;d<e.width;d++){let l=a*e.width+d;if(o[l])continue;let c=e.x+d,u=e.y+a;for(let p=0;p<i.length;p++){let m=i[p],b=c-m.getOrigin().x,C=u-m.getOrigin().y,S=m.getWidth(),O=m.getHeight();if(b<0||b>=S||C<0||C>=O)continue;let I=C*S+b,v=m.getData(),M=v.getCharCode(I),A=v.getFgColorCode(I),E=v.getBgColorCode(I),U=n[l];if(M!==0&&U.char===" "&&(U.char=_.getChar(M)),A!==255&&U.fgColorIndex===255&&(U.fgColorIndex=A,U.fgEmission=this.getColorEmission(A)),E!==255){U.bgColorIndex===255&&(U.bgColorIndex=E,U.bgEmission=this.getColorEmission(E)),o[l]=1;break}}}let s=new Array(r);for(let a=0;a<r;a++)s[a]={char:n[a].char,fgColorIndex:n[a].fgColorIndex,bgColorIndex:n[a].bgColorIndex,fgEmission:n[a].fgEmission,bgEmission:n[a].bgEmission};return{id:e.id,width:e.width,height:e.height,cells:s,palette:this.colorCache}}calculateIntersection(e,t){let r=e.x,n=e.x+e.width,o=e.y,i=e.y+e.height,s=t.x,a=t.x+256,d=t.y,l=t.y+256,c=Math.max(r,s),u=Math.min(n,a),p=Math.max(o,d),m=Math.min(i,l);return{visible:c<u&&p<m,originStart:{x:c-e.x,y:p-e.y},originEnd:{x:u-e.x,y:m-e.y},layerStart:{x:c-t.x,y:p-t.y},layerEnd:{x:u-t.x,y:m-t.y}}}};y(_,"DisplayRasterizer"),h(_,"charCache",(()=>{let e=new Map;for(let t=0;t<256;t++)e.set(t,String.fromCharCode(t));return e})());var ae=_;B();var P=class P{static toCharCode(e){if(typeof e=="number")return e&65535;let t=e.charCodeAt(0);return he(t)}static dedent(e){let t=e.split(`
|
|
1
|
+
"use strict";var me=Object.defineProperty;var xn=Object.getOwnPropertyDescriptor;var vn=Object.getOwnPropertyNames;var wn=Object.prototype.hasOwnProperty;var Un=(g,e,t)=>e in g?me(g,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):g[e]=t;var y=(g,e)=>me(g,"name",{value:e,configurable:!0});var F=(g,e)=>()=>(g&&(e=g(g=0)),e);var W=(g,e)=>{for(var t in e)me(g,t,{get:e[t],enumerable:!0})},Mn=(g,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of vn(e))!wn.call(g,n)&&n!==t&&me(g,n,{get:()=>e[n],enumerable:!(r=xn(e,n))||r.enumerable});return g};var G=g=>Mn(me({},"__esModule",{value:!0}),g);var h=(g,e,t)=>(Un(g,typeof e!="symbol"?e+"":e,t),t);var Je,lr=F(()=>{"use strict";Je=(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))(Je||{})});var Se,cr,ur,pr,mr,hr,br,gr,yr,Cr,fr,Sr,Ir,Or,xr,vr,wr,Ur,Mr,Er,Ar,Pr,Rr,zr,kr,Br,Tr,Fr,Lr,Dr,Vr,_r,Hr,qe,Ke,Nr,Qe,et,tt,rt,nt,ot,$=F(()=>{"use strict";Se=y(g=>g?2:1,"charCodeByteSize"),cr=6,ur=6,pr=6,mr=7,hr=5,br=3,gr=1,yr=6,Cr=4,fr=5,Sr=2,Ir=8,Or=7,xr=7,vr=8,wr=10,Ur=6,Mr=3,Er=9,Ar=15,Pr=51,Rr=5,zr=6,kr=4,Br=3,Tr=3,Fr=4,Lr=5,Dr=4,Vr=2,_r=5,Hr=5,qe=5,Ke=5,Nr=3,Qe=8,et=6,tt=3,rt=8,nt=3,ot=4});var _,f,T=F(()=>{"use strict";_=class _{constructor(e){h(this,"data");h(this,"view");this.data=new Uint8Array(e),this.view=new DataView(this.data.buffer)}static from(e){let t=new _(0);return t.data=e,t.view=new DataView(e.buffer,e.byteOffset,e.byteLength),t}static allocUnsafe(e){return new _(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 _.from(r)}subarray(e,t){let r=this.data.subarray(e,t);return _.from(r)}toBuffer(){return typeof Buffer<"u"&&Buffer.from?Buffer.from(this.data):this.data}static fromNodeBuffer(e){return e instanceof Uint8Array?_.from(e):_.from(new Uint8Array(e))}};y(_,"BufferCompat");f=_});var jr={};W(jr,{PlaySoundFlags:()=>$r,SoundEffectsFlags:()=>Zr});var $r,Zr,Jr=F(()=>{"use strict";$r=(a=>(a[a.Loop=1]="Loop",a[a.HasVolume=2]="HasVolume",a[a.HasPitch=4]="HasPitch",a[a.HasFadeIn=8]="HasFadeIn",a[a.HasPosition=16]="HasPosition",a[a.HasLowpass=32]="HasLowpass",a[a.HasHighpass=64]="HasHighpass",a[a.HasReverb=128]="HasReverb",a))($r||{}),Zr=(r=>(r[r.HasLowpass=1]="HasLowpass",r[r.HasHighpass=2]="HasHighpass",r[r.HasReverb=4]="HasReverb",r))(Zr||{})});var Qr={};W(Qr,{AudioOrderType:()=>qr,AudioTargetType:()=>Kr,getAudioOrderTypeName:()=>An,isValidAudioOrderType:()=>En});function En(g){return g>=1&&g<=9}function An(g){switch(g){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${g.toString(16)})`}}var qr,Kr,en=F(()=>{"use strict";qr=(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))(qr||{}),Kr=(r=>(r[r.InstanceId=0]="InstanceId",r[r.SoundId=1]="SoundId",r[r.All=2]="All",r))(Kr||{});y(En,"isValidAudioOrderType");y(An,"getAudioOrderTypeName")});var nn={};W(nn,{GamepadVibrateFlags:()=>rn,MobileVibrateFlags:()=>tn});var tn,rn,on=F(()=>{"use strict";tn=(e=>(e[e.HasIntensity=1]="HasIntensity",e))(tn||{}),rn=(t=>(t[t.HasStartDelay=1]="HasStartDelay",t[t.AllGamepads=2]="AllGamepads",t))(rn||{})});var an={};W(an,{VibrationOrderType:()=>sn});var sn,dn=F(()=>{"use strict";sn=(n=>(n[n.MobileVibrate=1]="MobileVibrate",n[n.MobileCancel=2]="MobileCancel",n[n.GamepadVibrate=16]="GamepadVibrate",n[n.GamepadCancel=17]="GamepadCancel",n))(sn||{})});var Ct,ee,ft=F(()=>{"use strict";$();Ct=class Ct{constructor(){h(this,"charCodeSize",Se)}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,s=e.readUInt8(i++),a=e.readUInt8(i++),d=e.readUInt8(i++),[l,c]=this.readCharCode(e,i,r);i=c;let p=e.readUInt8(i++),u=e.readUInt8(i++);return{order:{type:1,posX:a,posY:d,charCode:l,bgColorCode:p,fgColorCode:u},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,s=e.readUInt8(n+4)+1,a=i*s;this.checkSize(e,t,7+a*o);let d=[],l=n+7;for(let p=0;p<a;p++){let[u,m]=this.readCharCode(e,l,r);d.push(u),l=m}return{order:{type:3,posX:e.readUInt8(n+1),posY:e.readUInt8(n+2),sizeX:i,sizeY:s,bgColorCode:e.readUInt8(n+5),fgColorCode:e.readUInt8(n+6),frame:d},bytesRead:7+a*o}}decodeSubFrameMultiColorOrder(e,t,r){this.checkSize(e,t,5);let n=t,o=this.charCodeSize(r),i=e.readUInt8(n+3)+1,s=e.readUInt8(n+4)+1,a=i*s,d=o+2;this.checkSize(e,t,5+a*d);let l=[],c=n+5;for(let u=0;u<a;u++){let[m,b]=this.readCharCode(e,c,r);c=b,l.push({charCode:m,bgColorCode:e.readUInt8(c++),fgColorCode:e.readUInt8(c++)})}return{order:{type:4,posX:e.readUInt8(n+1),posY:e.readUInt8(n+2),sizeX:i,sizeY:s,frame:l},bytesRead:5+a*d}}decodeFullFrameOrder(e,t,r,n){this.checkSize(e,t,3);let o=t,i=this.charCodeSize(r),s=n||Math.floor((e.length-t-3)/i);this.checkSize(e,t,3+s*i);let a=[],d=o+3;for(let c=0;c<s;c++){let[p,u]=this.readCharCode(e,d,r);a.push(p),d=u}return{order:{type:5,bgColorCode:e.readUInt8(o+1),fgColorCode:e.readUInt8(o+2),frame:a},bytesRead:3+s*i}}decodeFullFrameMultiColorOrder(e,t,r,n){this.checkSize(e,t,1);let o=t,s=this.charCodeSize(r)+2,a=n||Math.floor((e.length-t-1)/s);this.checkSize(e,t,1+a*s);let d=[],l=o+1;for(let p=0;p<a;p++){let[u,m]=this.readCharCode(e,l,r);l=m,d.push({charCode:u,bgColorCode:e.readUInt8(l++),fgColorCode:e.readUInt8(l++)})}return{order:{type:6,frame:d},bytesRead:1+a*s}}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 s=[];for(let d=0;d<i;d++){let l=r+5+d*2;s.push({bgColorCode:e.readUInt8(l),fgColorCode:e.readUInt8(l+1)})}return{order:{type:9,posX:e.readUInt8(r+1),posY:e.readUInt8(r+2),sizeX:n,sizeY:o,colorData:s},bytesRead:5+i*2}}decodeShapeOrder(e,t,r){this.checkSize(e,t,2);let n=t,o=e.readUInt8(n+1),{shapeData:i,bytesRead:s}=this.decodeShapeData(e,n+2,o,r);return{order:{type:10,shapeType:o,shapeData:i},bytesRead:2+s}}decodeShapeData(e,t,r,n){let o=t,i=this.charCodeSize(n);switch(r){case 1:{let s=7+i;this.checkSize(e,t,s);let a=e.readUInt8(o++),d=e.readUInt8(o++),l=e.readUInt8(o++)+1,c=e.readUInt8(o++)+1,p=e.readUInt8(o++)===1,[u,m]=this.readCharCode(e,o,n);o=m;let b=e.readUInt8(o++),C=e.readUInt8(o++);return{shapeData:{posX:a,posY:d,width:l,height:c,filled:p,charCode:u,bgColorCode:b,fgColorCode:C},bytesRead:s}}case 2:{let s=6+i;this.checkSize(e,t,s);let a=e.readUInt8(o++),d=e.readUInt8(o++),l=e.readUInt8(o++)+1,c=e.readUInt8(o++)===1,[p,u]=this.readCharCode(e,o,n);o=u;let m=e.readUInt8(o++),b=e.readUInt8(o++);return{shapeData:{centerX:a,centerY:d,radius:l,filled:c,charCode:p,bgColorCode:m,fgColorCode:b},bytesRead:s}}case 3:{let s=6+i;this.checkSize(e,t,s);let a=e.readUInt8(o++),d=e.readUInt8(o++),l=e.readUInt8(o++),c=e.readUInt8(o++),[p,u]=this.readCharCode(e,o,n);o=u;let m=e.readUInt8(o++),b=e.readUInt8(o++);return{shapeData:{x1:a,y1:d,x2:l,y2:c,charCode:p,bgColorCode:m,fgColorCode:b},bytesRead:s}}case 4:{let s=7+i;this.checkSize(e,t,s);let a=e.readUInt8(o++),d=e.readUInt8(o++),l=e.readUInt8(o++)+1,c=e.readUInt8(o++)+1,p=e.readUInt8(o++)===1,[u,m]=this.readCharCode(e,o,n);o=m;let b=e.readUInt8(o++),C=e.readUInt8(o++);return{shapeData:{centerX:a,centerY:d,radiusX:l,radiusY:c,filled:p,charCode:u,bgColorCode:b,fgColorCode:C},bytesRead:s}}case 5:{let s=9+i;this.checkSize(e,t,s);let a=e.readUInt8(o++),d=e.readUInt8(o++),l=e.readUInt8(o++),c=e.readUInt8(o++),p=e.readUInt8(o++),u=e.readUInt8(o++),m=e.readUInt8(o++)===1,[b,C]=this.readCharCode(e,o,n);o=C;let S=e.readUInt8(o++),I=e.readUInt8(o++);return{shapeData:{x1:a,y1:d,x2:l,y2:c,x3:p,y3:u,filled:m,charCode:b,bgColorCode:S,fgColorCode:I},bytesRead:s}}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,s=e.readUInt8(i++),[a,d]=this.readCharCode(e,i,r);i=d;let l=e.readUInt8(i++),c=e.readUInt8(i++),p=e.readUInt16BE(i);i+=2,this.checkSize(e,t,o+p*2);let u=[];for(let b=0;b<p;b++)u.push({posX:e.readUInt8(i++),posY:e.readUInt8(i++)});return{order:{type:11,charCode:a,bgColorCode:l,fgColorCode:c,positions:u},bytesRead:o+p*2}}decodeDotCloudMultiColorOrder(e,t,r){this.checkSize(e,t,3);let n=this.charCodeSize(r),o=t,i=e.readUInt16BE(o+1),s=n+4;this.checkSize(e,t,3+i*s);let a=[],d=o+3;for(let c=0;c<i;c++){let[p,u]=this.readCharCode(e,d,r);d=u,a.push({charCode:p,bgColorCode:e.readUInt8(d++),fgColorCode:e.readUInt8(d++),posX:e.readUInt8(d++),posY:e.readUInt8(d++)})}return{order:{type:12,dots:a},bytesRead:3+i*s}}decodeBitmaskOrder(e,t,r){let o=8+this.charCodeSize(r);this.checkSize(e,t,o);let i=t,s=e.readUInt8(i++),a=e.readUInt8(i++),d=e.readUInt8(i++),l=e.readUInt8(i++)+1,c=e.readUInt8(i++)+1,[p,u]=this.readCharCode(e,i,r);i=u;let m=e.readUInt8(i++),b=e.readUInt8(i++),C=e.readUInt8(i++)===1,S=Math.ceil(l*c/8);this.checkSize(e,t,o+S);let I=new Uint8Array(S);for(let v=0;v<S;v++)I[v]=e.readUInt8(i+v);return{order:{type:17,posX:a,posY:d,sizeX:l,sizeY:c,charCode:p,bgColorCode:m,fgColorCode:b,override:C,mask:I},bytesRead:o+S}}decodeBitmask4Order(e,t,r){let i=6+3*(this.charCodeSize(r)+2);this.checkSize(e,t,i);let s=t,a=e.readUInt8(s++),d=e.readUInt8(s++),l=e.readUInt8(s++),c=e.readUInt8(s++)+1,p=e.readUInt8(s++)+1,u=e.readUInt8(s++)===1,m=Math.ceil(c*p/4);this.checkSize(e,t,i+m);let b=[];for(let I=0;I<3;I++){let[O,v]=this.readCharCode(e,s,r);s=v,b.push({charCode:O,bgColorCode:e.readUInt8(s++),fgColorCode:e.readUInt8(s++)})}let C=new Uint8Array(m);for(let I=0;I<m;I++)C[I]=e.readUInt8(s+I);return{order:{type:18,posX:d,posY:l,sizeX:c,sizeY:p,override:u,variants:b,mask:C},bytesRead:i+m}}decodeBitmask16Order(e,t,r){let i=6+15*(this.charCodeSize(r)+2);this.checkSize(e,t,i);let s=t,a=e.readUInt8(s++),d=e.readUInt8(s++),l=e.readUInt8(s++),c=e.readUInt8(s++)+1,p=e.readUInt8(s++)+1,u=e.readUInt8(s++)===1,m=Math.ceil(c*p/2);this.checkSize(e,t,i+m);let b=[];for(let I=0;I<15;I++){let[O,v]=this.readCharCode(e,s,r);s=v,b.push({charCode:O,bgColorCode:e.readUInt8(s++),fgColorCode:e.readUInt8(s++)})}let C=new Uint8Array(m);for(let I=0;I<m;I++)C[I]=e.readUInt8(s+I);return{order:{type:24,posX:d,posY:l,sizeX:c,sizeY:p,override:u,variants:b,mask:C},bytesRead:i+m}}decodePolylineOrder(e,t,r){let o=4+this.charCodeSize(r);this.checkSize(e,t,o);let i=t,s=e.readUInt8(i++),[a,d]=this.readCharCode(e,i,r);i=d;let l=e.readUInt8(i++),c=e.readUInt8(i++),p=e.readUInt8(i++);this.checkSize(e,t,o+p*2);let u=[];for(let b=0;b<p;b++)u.push({x:e.readUInt8(i++),y:e.readUInt8(i++)});return{order:{type:25,charCode:a,fgColorCode:l,bgColorCode:c,points:u},bytesRead:o+p*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 s=0;s<n;s++){let a=r+6+s*2;o.push({posX:e.readUInt8(a),posY:e.readUInt8(a+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 s=0;s<n;s++){let a=r+4+s*2;o.push({posX:e.readUInt8(a),posY:e.readUInt8(a+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 s=0;s<n;s++){let a=r+3+s*5;o.push({spriteIndex:e.readUInt8(a),bgColorCode:e.readUInt8(a+1),fgColorCode:e.readUInt8(a+2),posX:e.readUInt8(a+3),posY:e.readUInt8(a+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 s=0;s<n;s++){let a=r+3+s*3;o.push({spriteIndex:e.readUInt8(a),posX:e.readUInt8(a+1),posY:e.readUInt8(a+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,s=e.readUInt8(i++),[a,d]=this.readCharCode(e,i,r);i=d;let l=e.readUInt8(i++),c=e.readUInt8(i++);return{order:{type:19,charCode:a,bgColorCode:l,fgColorCode:c},bytesRead:o}}decodeFillCharOrder(e,t,r){this.checkSize(e,t,5);let n=this.charCodeSize(r),o=t,i=e.readUInt8(o+1)+1,s=e.readUInt8(o+2)+1,a=i*s,d=5+a*n;this.checkSize(e,t,d);let l=[],c=o+5;for(let u=0;u<a;u++){let[m,b]=this.readCharCode(e,c,r);l.push(m),c=b}return{order:{type:20,patternWidth:i,patternHeight:s,bgColorCode:e.readUInt8(o+3),fgColorCode:e.readUInt8(o+4),pattern:l},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(Ct,"OrderDecoder");ee=Ct});var Pn,ln,cn,St,te,It=F(()=>{"use strict";Pn=4,ln=4,cn=8,St=class St{decode(e,t=0){this.checkSize(e,t,cn);let r=t,n=e.readUInt8(r++),o=e.readUInt16BE(r);r+=2;let i=e.readUInt16BE(r);r+=2;let s=e.readUInt8(r++)+1,a=e.readUInt8(r++)+1,d=e.readUInt8(r++);if(d>ln)throw new Error(`Invalid renderPass count: ${d} (max ${ln})`);let l=d*Pn;this.checkSize(e,r,l);let c=[];for(let u=0;u<d;u++){let m=e.readUInt8(r++),b=e.readUInt8(r++),C=e.readUInt8(r++),S=e.readUInt8(r++);c.push({id:m,zMin:b,zMax:C,enabled:(S&1)!==0})}return{display:{id:n,originX:o,originY:i,sizeX:s,sizeY:a,renderPasses:c.length>0?c:void 0},bytesRead:cn+l}}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(St,"DisplayDecoder");te=St});var Rn,Ot,re,xt=F(()=>{"use strict";ft();Rn=64,Ot=class Ot{constructor(){h(this,"orderDecoder");this.orderDecoder=new ee}decode(e,t=0){this.checkSize(e,t,13);let n=t,o=e.readUInt16BE(n);n+=2;let i=e.readUInt8(n++),s=e.readUInt8(n++),a=e.readUInt16BE(n);n+=2;let d=e.readUInt16BE(n);n+=2;let l=e.readUInt16BE(n);n+=2;let c=e.readUInt16BE(n);n+=2;let p=e.readUInt8(n++),u=(i&Rn)!==0,m=[],b=n;for(let S=0;S<p;S++){let I=this.orderDecoder.decode(e,b,u);m.push(I.order),b+=I.bytesRead}return{layer:{id:o,updateFlags:i,zIndex:s,originX:a,originY:d,width:l,height:c,orderCount:p,orders:m,is16bit:u},bytesRead:b-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(Ot,"LayerDecoder");re=Ot});var vt,we,un=F(()=>{"use strict";vt=class vt{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 s=e.readUInt8(r++),a={type:n,soundId:o,instanceId:i,flags:s};return s&2&&(this.checkSize(e,r,1),a.volume=e.readUInt8(r++)),s&4&&(this.checkSize(e,r,1),a.pitch=e.readUInt8(r++)),s&8&&(this.checkSize(e,r,1),a.fadeIn=e.readUInt8(r++)),s&16&&(this.checkSize(e,r,4),a.posX=e.readUInt16BE(r),r+=2,a.posY=e.readUInt16BE(r),r+=2),s&32&&(this.checkSize(e,r,1),a.lowpass=e.readUInt8(r++)),s&64&&(this.checkSize(e,r,1),a.highpass=e.readUInt8(r++)),s&128&&(this.checkSize(e,r,1),a.reverb=e.readUInt8(r++)),{order:a,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 s=e.readUInt8(r++),a={type:n,soundId:o,instanceId:i,flags:s};return s&2&&(this.checkSize(e,r,1),a.volume=e.readUInt8(r++)),s&4&&(this.checkSize(e,r,1),a.pitch=e.readUInt8(r++)),s&8&&(this.checkSize(e,r,1),a.fadeIn=e.readUInt8(r++)),s&32&&(this.checkSize(e,r,1),a.lowpass=e.readUInt8(r++)),s&64&&(this.checkSize(e,r,1),a.highpass=e.readUInt8(r++)),s&128&&(this.checkSize(e,r,1),a.reverb=e.readUInt8(r++)),{order:a,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++),s={type:n,targetType:o,duration:i};return o===0?(this.checkSize(e,r,2),s.target=e.readUInt16BE(r),r+=2):o===1&&(this.checkSize(e,r,1),s.target=e.readUInt8(r++)),{order:s,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++),s={type:n,instanceId:o,flags:i};return i&1&&(this.checkSize(e,r,1),s.lowpass=e.readUInt8(r++)),i&2&&(this.checkSize(e,r,1),s.highpass=e.readUInt8(r++)),i&4&&(this.checkSize(e,r,1),s.reverb=e.readUInt8(r++)),{order:s,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(vt,"AudioOrderDecoder");we=vt});var wt,Ue,pn=F(()=>{"use strict";wt=class wt{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++),s=[];for(let d=0;d<i;d++)s.push(e.readUInt16BE(r)),r+=2;let a={type:n,flags:o,pattern:s};return o&1&&(a.intensity=e.readUInt8(r++)/255),{order:a,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++),s=e.readUInt16BE(r);r+=2;let a=e.readUInt8(r++),d=e.readUInt8(r++),l={type:n,flags:o,gamepadIndex:i,duration:s,strongMagnitude:a,weakMagnitude:d};return o&1&&(l.startDelay=e.readUInt16BE(r),r+=2),{order:l,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(wt,"VibrationOrderDecoder");Ue=wt});var Ut,ne,Mt=F(()=>{"use strict";Ut=class Ut{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:s,bytesRead:a}=this.decode(e,t+o);n.push(s),o+=a}return{orders:n,bytesRead:o}}decodeCreateInstance(e,t){let r=t,n=e.readUInt8(t++),o=e.readUInt8(t++),i=e.readUInt8(t++),s=e.readUInt8(t++),a=e.readInt16BE(t);t+=2;let d=e.readInt16BE(t);t+=2;let l=e.readUInt8(t++),c=e.readUInt16BE(t);t+=2;let p=e.toUint8Array().subarray(t,t+c);t+=c;let u=new TextDecoder().decode(p),m=JSON.parse(u);return{order:{type:n,instanceId:o,macroId:i,layerId:s,x:a,y:d,tabIndex:l,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 s=e.toUint8Array().subarray(t,t+i);t+=i;let a=new TextDecoder().decode(s),d=JSON.parse(a);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(Ut,"MacroOrderDecoder");ne=Ut});var Et,Me,mn=F(()=>{"use strict";Et=class Et{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++],s={type:n,displayId:o,flags:i};return i&1&&(s.scanlines={enabled:e[r++]===1,opacity:e[r++]/255,pattern:e[r++],colorR:e[r++],colorG:e[r++],colorB:e[r++]}),i&2&&(s.ambientEffect={enabled:e[r++]===1,blur:e[r++],scale:e[r++]/100,opacity:e[r++]/255}),{order:s,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(Et,"PostProcessOrderDecoder");Me=Et});var hn={};W(hn,{UpdatePacketDecoder:()=>he});var At,he,Pt=F(()=>{"use strict";It();xt();un();pn();Mt();mn();T();At=class At{constructor(){h(this,"displayDecoder");h(this,"layerDecoder");h(this,"audioOrderDecoder");h(this,"vibrationOrderDecoder");h(this,"macroOrderDecoder");h(this,"postProcessOrderDecoder");this.displayDecoder=new te,this.layerDecoder=new re,this.audioOrderDecoder=new we,this.vibrationOrderDecoder=new Ue,this.macroOrderDecoder=new ne,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 s=r.readUInt8(o);o+=1;let a=[],d=0;for(let k=0;k<s;k++){let x=this.displayDecoder.decode(r,o);a.push(x.display),o+=x.bytesRead,d+=x.bytesRead}this.checkSize(r,o,2);let l=r.readUInt16BE(o);o+=2;let c=[],p=0;for(let k=0;k<l;k++){let x=this.layerDecoder.decode(r,o);c.push({...x.layer,byteSize:x.bytesRead}),o+=x.bytesRead,p+=x.bytesRead}this.checkSize(r,o,1);let u=r.readUInt8(o);o+=1;let m=[],b=0;for(let k=0;k<u;k++){let x=this.audioOrderDecoder.decode(r,o);m.push(x.order),o+=x.bytesRead,b+=x.bytesRead}this.checkSize(r,o,1);let C=r.readUInt8(o);o+=1;let S=[],I=0;for(let k=0;k<C;k++){let x=this.vibrationOrderDecoder.decode(r,o);S.push(x.order),o+=x.bytesRead,I+=x.bytesRead}this.checkSize(r,o,1);let O=r.readUInt8(o);o+=1;let v=[],w=0;for(let k=0;k<O;k++){let x=this.macroOrderDecoder.decode(r,o);v.push(x.order),o+=x.bytesRead,w+=x.bytesRead}this.checkSize(r,o,1);let A=r.readUInt8(o);o+=1;let E=[],U=0;for(let k=0;k<A;k++){let x=this.postProcessOrderDecoder.decode(r.toUint8Array(),o);E.push(x.order),o+=x.bytesRead,U+=x.bytesRead}return{tick:i,displayCount:s,displays:a,layerCount:l,layers:c,audioOrderCount:u,audioOrders:m,vibrationOrderCount:C,vibrationOrders:S,macroOrderCount:O,macroOrders:v,postProcessOrderCount:A,postProcessOrders:E,__byteSizes:{displays:d,layers:p,audioOrders:b,vibrationOrders:I,macroOrders:w,postProcessOrders:U}}}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;for(let a=0;a<i;a++){let d=this.displayDecoder.decode(r,n);n+=d.bytesRead}this.checkSize(r,n,2);let s=r.readUInt16BE(n);return{tick:o,displayCount:i,layerCount:s}}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(At,"UpdatePacketDecoder");he=At});var Yn={};W(Yn,{BufferCompat:()=>f,CellBuffer:()=>N,Core:()=>je,DisplayDecoder:()=>te,DisplayEncoder:()=>j,DisplayRasterizer:()=>de,Layer:()=>ce,LayerDecoder:()=>re,LayerEncoder:()=>J,LayerRasterizer:()=>ae,LoadDecoder:()=>ie,LoadEncoder:()=>D,MacroEventDecoder:()=>se,MacroEventEncoder:()=>ve,MacroLoadDecoder:()=>oe,MacroLoadEncoder:()=>Q,MacroOrderDecoder:()=>ne,MacroOrderEncoder:()=>q,OrderBuilder:()=>Ee,OrderDecoder:()=>ee,OrderEncoder:()=>Z,ShapeType:()=>Je,SpriteRegistry:()=>le,UpdatePacketDecoder:()=>he,UpdatePacketEncoder:()=>K,Vector2:()=>On.Vector2});module.exports=G(Yn);$();$();T();var st=class st{constructor(){h(this,"charCodeSize",Se)}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(cr+(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(ur+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(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()}encodeSubFrameOrder(e,t){let r=e.sizeX*e.sizeY,n=this.charCodeSize(t),o=f.allocUnsafe(mr+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 s of e.frame)i=this.writeCharCode(o,s,i,t);return o.toUint8Array()}encodeSubFrameMultiColorOrder(e,t){let r=e.sizeX*e.sizeY,n=this.charCodeSize(t),o=f.allocUnsafe(hr+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 s of e.frame)i=this.writeCharCode(o,s.charCode,i,t),o.writeUInt8(s.bgColorCode,i++),o.writeUInt8(s.fgColorCode,i++);return o.toUint8Array()}encodeFullFrameOrder(e,t){let r=e.frame.length,n=this.charCodeSize(t),o=f.allocUnsafe(br+r*n),i=0;o.writeUInt8(e.type,i++),o.writeUInt8(e.bgColorCode,i++),o.writeUInt8(e.fgColorCode,i++);for(let s of e.frame)i=this.writeCharCode(o,s,i,t);return o.toUint8Array()}encodeFullFrameMultiColorOrder(e,t){let r=e.frame.length,n=this.charCodeSize(t),o=f.allocUnsafe(gr+r*(n+2)),i=0;o.writeUInt8(e.type,i++);for(let s of e.frame)i=this.writeCharCode(o,s.charCode,i,t),o.writeUInt8(s.bgColorCode,i++),o.writeUInt8(s.fgColorCode,i++);return o.toUint8Array()}encodeSpriteOrder(e){let t=f.allocUnsafe(yr),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(Cr),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(fr+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(Sr+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(Ir+(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(Or+(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(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++),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(vr+(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(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++),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(Ur+(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 s of e.positions)o.writeUInt8(s.posX,i++),o.writeUInt8(s.posY,i++);return o.toUint8Array()}encodeDotCloudMultiColorOrder(e,t){let r=e.dots.length,n=this.charCodeSize(t),o=f.allocUnsafe(Mr+r*(n+4)),i=0;o.writeUInt8(e.type,i++),o.writeUInt16BE(r,i),i+=2;for(let s of e.dots)i=this.writeCharCode(o,s.charCode,i,t),o.writeUInt8(s.bgColorCode,i++),o.writeUInt8(s.fgColorCode,i++),o.writeUInt8(s.posX,i++),o.writeUInt8(s.posY,i++);return o.toUint8Array()}encodeBitmaskOrder(e,t){let r=e.mask.length,n=f.allocUnsafe(Er+(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(Ar+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 s of e.variants)i=this.writeCharCode(o,s.charCode,i,t),o.writeUInt8(s.bgColorCode,i++),o.writeUInt8(s.fgColorCode,i++);for(let s=0;s<r;s++)o.writeUInt8(e.mask[s],i++);return o.toUint8Array()}encodeBitmask16Order(e,t){let r=e.mask.length,n=this.charCodeSize(t),o=f.allocUnsafe(Pr+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 s of e.variants)i=this.writeCharCode(o,s.charCode,i,t),o.writeUInt8(s.bgColorCode,i++),o.writeUInt8(s.fgColorCode,i++);for(let s=0;s<r;s++)o.writeUInt8(e.mask[s],i++);return o.toUint8Array()}encodePolylineOrder(e,t){let r=e.points.length,n=f.allocUnsafe(Rr+(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(zr+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+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(Br+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(Tr+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(Fr+(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(Lr+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 s of e.pattern)i=this.writeCharCode(o,s,i,t);return o.toUint8Array()}encodeFillSpriteOrder(e){let t=f.allocUnsafe(Dr),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(Vr),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.spriteIndex,r++),t.toUint8Array()}};y(st,"OrderEncoder");var Z=st;T();var Yr=4,at=4,Xr=8,dt=class dt{encode(e){let t=e.renderPasses?.length??0;if(t>at)throw new Error(`renderPasses supports up to ${at} entries, got ${t}`);let r=Xr+t*Yr,n=f.allocUnsafe(r),o=0;if(n.writeUInt8(e.id,o++),n.writeUInt16BE(e.originX,o),o+=2,n.writeUInt16BE(e.originY,o),o+=2,n.writeUInt8(e.sizeX-1,o++),n.writeUInt8(e.sizeY-1,o++),n.writeUInt8(t,o++),t>0&&e.renderPasses)for(let i of e.renderPasses){let s=Math.max(0,Math.min(255,i.id)),a=Math.max(0,Math.min(255,i.zMin)),d=Math.max(0,Math.min(255,i.zMax)),l=i.enabled===!1?0:1;n.writeUInt8(s,o++),n.writeUInt8(a,o++),n.writeUInt8(d,o++),n.writeUInt8(l,o++)}return n.toUint8Array()}calculateSize(e){let t=Math.min(e.renderPasses?.length??0,at);return Xr+t*Yr}};y(dt,"DisplayEncoder");var j=dt;T();var Wr=255,Gr=64,lt=class lt{constructor(){h(this,"orderEncoder");this.orderEncoder=new Z}encode(e){let t=e.is16bit;if(e.orders.length>Wr)throw new Error(`[UTSP] LayerEncoder: Layer ${e.id} has ${e.orders.length} orders, max is ${Wr}. This would cause packet corruption! Split into multiple layers.`);let r=e.orders.map(l=>this.orderEncoder.encode(l,t)),n=13,o=r.reduce((l,c)=>l+c.length,0),i=n+o,s=f.allocUnsafe(i),a=0;s.writeUInt16BE(e.id,a),a+=2;let d=e.updateFlags;t?d|=Gr:d&=~Gr,s.writeUInt8(d,a++),s.writeUInt8(e.zIndex,a++),s.writeUInt16BE(e.originX,a),a+=2,s.writeUInt16BE(e.originY,a),a+=2,s.writeUInt16BE(e.width,a),a+=2,s.writeUInt16BE(e.height,a),a+=2,s.writeUInt8(e.orders.length,a++);for(let l of r)f.from(l).copy(s,a),a+=l.length;return s.toUint8Array()}calculateSize(e){let r=e.is16bit;return 13+e.orders.reduce((o,i)=>o+this.orderEncoder.encode(i,r).length,0)}};y(lt,"LayerEncoder");var J=lt;T();$();var ct=class ct{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 qe;case 8:return Ke;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=_r;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=Hr,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(qe),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(Ke),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(ct,"AudioOrderEncoder");var Ie=ct;T();var ut=class ut{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 s=Math.min(65535,Math.max(0,Math.round(i)));r.writeUInt16BE(s,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 s=Math.min(65535,Math.max(0,Math.round(e.startDelay)));r.writeUInt16BE(s,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(ut,"VibrationOrderEncoder");var Oe=ut;T();var pt=class pt{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(pt,"MacroOrderEncoder");var q=pt;T();$();var mt=class mt{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 Qe;case 3:return et;case 4:return tt;case 5:return rt;case 6:return nt;case 7:return ot;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=Nr;return e.flags&1&&(t+=6),e.flags&2&&(t+=4),t}encodeSetScanlinesOrder(e){let t=f.allocUnsafe(Qe),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(et),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(tt),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(rt),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(nt),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(ot),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(mt,"PostProcessOrderEncoder");var xe=mt;T();var ht=class ht{constructor(){h(this,"layerEncoder");h(this,"audioOrderEncoder");h(this,"vibrationOrderEncoder");h(this,"macroOrderEncoder");h(this,"postProcessOrderEncoder");h(this,"displayEncoder");this.layerEncoder=new J,this.audioOrderEncoder=new Ie,this.vibrationOrderEncoder=new Oe,this.macroOrderEncoder=new q,this.postProcessOrderEncoder=new xe,this.displayEncoder=new j}encode(e){let t=e.layers.map(x=>this.layerEncoder.encode(x)),r=e.audioOrders||[],n=r.map(x=>this.audioOrderEncoder.encode(x)),o=e.vibrationOrders||[],i=o.map(x=>this.vibrationOrderEncoder.encode(x)),s=e.macroOrders||[],a=s.map(x=>this.macroOrderEncoder.encode(x)),d=e.postProcessOrders||[],l=d.map(x=>this.postProcessOrderEncoder.encode(x)),c=9,p=e.displays.reduce((x,B)=>x+this.displayEncoder.calculateSize(B),0),u=2,m=t.reduce((x,B)=>x+B.length,0),b=1,C=n.reduce((x,B)=>x+B.length,0),S=1,I=i.reduce((x,B)=>x+B.length,0),O=1,v=a.reduce((x,B)=>x+B.length,0),w=1,A=l.reduce((x,B)=>x+B.length,0),E=c+p+u+m+b+C+S+I+O+v+w+A,U=f.allocUnsafe(E),M=0,k=typeof e.tick=="bigint"?e.tick:BigInt(e.tick);U.writeBigUInt64BE(k,M),M+=8,U.writeUInt8(e.displays.length,M),M+=1;for(let x of e.displays){let B=this.displayEncoder.encode(x);f.from(B).copy(U,M),M+=B.length}U.writeUInt16BE(e.layers.length,M),M+=2;for(let x of t)f.from(x).copy(U,M),M+=x.length;U.writeUInt8(r.length,M),M+=1;for(let x of n)f.from(x).copy(U,M),M+=x.length;U.writeUInt8(o.length,M),M+=1;for(let x of i)f.from(x).copy(U,M),M+=x.length;U.writeUInt8(s.length,M),M+=1;for(let x of a)f.from(x).copy(U,M),M+=x.length;U.writeUInt8(d.length,M),M+=1;for(let x of l)f.from(x).copy(U,M),M+=x.length;return U.toUint8Array()}calculateSize(e){let r=e.displays.reduce((I,O)=>I+this.displayEncoder.calculateSize(O),0),n=2,o=e.layers.reduce((I,O)=>I+this.layerEncoder.calculateSize(O),0),i=1,a=(e.audioOrders||[]).reduce((I,O)=>I+this.audioOrderEncoder.calculateSize(O),0),d=1,c=(e.vibrationOrders||[]).reduce((I,O)=>I+this.vibrationOrderEncoder.calculateSize(O),0),p=1,m=(e.macroOrders||[]).reduce((I,O)=>I+this.macroOrderEncoder.calculateSize(O),0),b=1,S=(e.postProcessOrders||[]).reduce((I,O)=>I+this.postProcessOrderEncoder.calculateSize(O),0);return 9+r+n+o+i+a+d+c+p+m+b+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=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(ht,"UpdatePacketEncoder");var K=ht;T();var bt=class bt{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 s of e.colors)o.writeUInt8(s.colorId,i++),o.writeUInt8(s.r,i++),o.writeUInt8(s.g,i++),o.writeUInt8(s.b,i++),o.writeUInt8(s.a,i++),o.writeUInt8(s.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 s of i.data)n.writeUInt8(s,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 s of i.data)n.writeUInt8(s.charCode,o++),n.writeUInt8(s.fgColorId,o++),n.writeUInt8(s.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 s of e.characters){if(s.bitmap.length!==r)throw new Error(`Character ${s.charCode}: bitmap size ${s.bitmap.length} does not match expected ${r} bytes`);o.writeUInt8(s.charCode,i++);for(let a=0;a<s.bitmap.length;a++)o.writeUInt8(s.bitmap[a],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 s=0;s<i.midiData.length;s++)n.writeUInt8(i.midiData[s],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 s=4;s+=r.length,s+=2,e.offsetX!==void 0&&(s+=2),e.offsetY!==void 0&&(s+=2),e.charSpacing!==void 0&&(s+=2),e.lineHeight!==void 0&&(s+=2),e.fontWeight!==void 0&&(s+=1+n.length),e.fontStyle!==void 0&&(s+=1+o.length);let a=f.allocUnsafe(s),d=0;a.writeUInt8(6,d++),a.writeUInt8(e.fontId,d++),a.writeUInt8(i,d++),a.writeUInt8(r.length,d++);for(let l=0;l<r.length;l++)a.writeUInt8(r[l],d++);if(a.writeUInt16BE(e.fontSize,d),d+=2,e.offsetX!==void 0&&(a.writeInt16BE(e.offsetX,d),d+=2),e.offsetY!==void 0&&(a.writeInt16BE(e.offsetY,d),d+=2),e.charSpacing!==void 0&&(a.writeInt16BE(e.charSpacing,d),d+=2),e.lineHeight!==void 0&&(a.writeUInt16BE(Math.round(e.lineHeight*100),d),d+=2),e.fontWeight!==void 0){a.writeUInt8(n.length,d++);for(let l=0;l<n.length;l++)a.writeUInt8(n[l],d++)}if(e.fontStyle!==void 0){a.writeUInt8(o.length,d++);for(let l=0;l<o.length;l++)a.writeUInt8(o[l],d++)}return a.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(bt,"LoadEncoder");var D=bt;T();var gt=class gt{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(gt,"MacroLoadEncoder");var Q=gt;T();var yt=class yt{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(yt,"MacroEventEncoder");var ve=yt;ft();It();xt();Pt();Mt();T();var Rt=class Rt{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 s=e.toUint8Array().subarray(t,t+i);t+=i;let a=new TextDecoder().decode(s),d=JSON.parse(a);return{load:{loadType:7,macroId:o,template:d},bytesRead:t-r}}};y(Rt,"MacroLoadDecoder");var oe=Rt;var zt=class zt{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,s;i&&(this.checkSize(e,t,1,"ColorPalette slotId"),s=e.readUInt8(t++));let a=e.readUInt8(t++);this.checkSize(e,t,a*6,`ColorPalette ${a} colors`);let d=[];for(let c=0;c<a;c++)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,...s!==void 0&&{slotId:s},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 a=0;a<o;a++){this.checkSize(e,t,3,`Sprite ${a} header`);let d=e.readUInt8(t++),l=e.readUInt8(t++),c=e.readUInt8(t++),p=l*c;this.checkSize(e,t,p,`Sprite ${a} data`);let u=[];for(let m=0;m<p;m++)u.push(e.readUInt8(t++));i.push({spriteId:d,sizeX:l,sizeY:c,data:u})}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 a=0;a<o;a++){this.checkSize(e,t,3,`MulticolorSprite ${a} header`);let d=e.readUInt8(t++),l=e.readUInt8(t++),c=e.readUInt8(t++),p=l*c,u=p*3;this.checkSize(e,t,u,`MulticolorSprite ${a} data`);let m=[];for(let b=0;b<p;b++)m.push({charCode:e.readUInt8(t++),fgColorId:e.readUInt8(t++),bgColorId:e.readUInt8(t++)});i.push({spriteId:d,sizeX:l,sizeY:c,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++),s=e.readUInt8(t++),a=e.readUInt8(t++),d=e.readUInt8(t++),l=e.readUInt8(t++),c=Math.ceil(i*s/8),p=[];for(let m=0;m<l;m++){this.checkSize(e,t,1+c,`BitmapFont character ${m}`);let b=e.readUInt8(t++),C=new Uint8Array(c);for(let S=0;S<c;S++)C[S]=e.readUInt8(t++);p.push({charCode:b,bitmap:C})}return{load:{loadType:4,fontId:o,width:i,height:s,cellWidth:a,cellHeight:d,characters:p},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 a=0;a<o;a++){this.checkSize(e,t,3,`Sound ${a} header`);let d=e.readUInt8(t++),l=e.readUInt16BE(t);t+=2,this.checkSize(e,t,l,`Sound ${a} MIDI data`);let c=new Uint8Array(l);for(let p=0;p<l;p++)c[p]=e.readUInt8(t++);i.push({soundId:d,midiData:c})}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++),s=e.readUInt8(t++),a=e.readUInt8(t++);this.checkSize(e,t,a,"WebFont family string");let d=new Uint8Array(a);for(let u=0;u<a;u++)d[u]=e.readUInt8(t++);let l=n.decode(d);this.checkSize(e,t,2,"WebFont fontSize");let c=e.readUInt16BE(t);t+=2;let p={loadType:6,fontId:i,fontFamily:l,fontSize:c};if(s&1&&(this.checkSize(e,t,2,"WebFont offsetX"),p.offsetX=e.readInt16BE(t),t+=2),s&2&&(this.checkSize(e,t,2,"WebFont offsetY"),p.offsetY=e.readInt16BE(t),t+=2),s&4&&(this.checkSize(e,t,2,"WebFont charSpacing"),p.charSpacing=e.readInt16BE(t),t+=2),s&8){this.checkSize(e,t,2,"WebFont lineHeight");let u=e.readUInt16BE(t);p.lineHeight=u/100,t+=2}if(s&16){this.checkSize(e,t,1,"WebFont weight length");let u=e.readUInt8(t++);this.checkSize(e,t,u,"WebFont weight string");let m=new Uint8Array(u);for(let b=0;b<u;b++)m[b]=e.readUInt8(t++);p.fontWeight=n.decode(m)}if(s&32){this.checkSize(e,t,1,"WebFont style length");let u=e.readUInt8(t++);this.checkSize(e,t,u,"WebFont style string");let m=new Uint8Array(u);for(let b=0;b<u;b++)m[b]=e.readUInt8(t++);p.fontStyle=n.decode(m)}return{load:p,bytesRead:t-r}}decodeMacro(e,t){return new oe().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++),s=e.readUInt8(t++),a=e.readUInt8(t++),d=e.readUInt8(t++),l=e.readUInt8(t++);if(![1,4,16].includes(l))throw new Error(`Invalid atlasBlocks value: ${l}. Must be 1, 4, or 16.`);let c=l;this.checkSize(e,t,4,"ImageFont image data size");let p=e.readUInt32LE(t);t+=4,this.checkSize(e,t,p,"ImageFont image data");let u=new Uint8Array(p);for(let b=0;b<p;b++)u[b]=e.readUInt8(t++);return{load:{loadType:8,fontId:o,glyphWidth:i,glyphHeight:s,cellWidth:a,cellHeight:d,atlasBlocks:c,imageData:u},bytesRead:t-r}}};y(zt,"LoadDecoder");var ie=zt;var kt=class kt{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:s,bytesRead:a}=this.decode(e,t+o);n.push(s),o+=a}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,s;return o===1?(i=e.readUInt8(t+3)===1,s=4):(i=e.readFloatBE(t+3),s=7),{event:{type:r,instanceId:n,value:i},bytesRead:s}}decodeSubmit(e,t){let r=t,n=e.readUInt8(t++),o=e.readUInt8(t++),i=e.readUInt16BE(t);t+=2;let s=e.toUint8Array().subarray(t,t+i);t+=i;let a=new TextDecoder().decode(s);return{event:{type:n,instanceId:o,text:a},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(kt,"MacroEventDecoder");var se=kt;var zn=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 be(g){if(g<128)return g;let e=zn.get(g);return e!==void 0?e:g&255}y(be,"unicodeToCp437");var Bt=class Bt{constructor(){h(this,"currentWidth",256);h(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:s}=e;if(!this.isInBounds(r,n))return;let a=n*this.currentWidth+r;t.set(a,o,s,i)}rasterizeText(e,t){let{posX:r,posY:n,text:o,bgColorCode:i,fgColorCode:s}=e;if(this.isInBounds(r,n))for(let a=0;a<o.length;a++){let d=r+a;if(d>=this.currentWidth)break;let l=n*this.currentWidth+d,c=o.charCodeAt(a),p=be(c);t.set(l,p,s,i)}}rasterizeTextMultiline(e,t){let{posX:r,posY:n,text:o,bgColorCode:i,fgColorCode:s}=e,a=o.split(`
|
|
2
|
+
`),d=n;for(let l of a){if(d>=this.currentHeight)break;if(d>=0&&this.isInBounds(r,d))for(let c=0;c<l.length;c++){let p=r+c;if(p>=this.currentWidth)break;let u=d*this.currentWidth+p,m=l.charCodeAt(c),b=be(m);t.set(u,b,s,i)}d++}}rasterizeSubFrame(e,t){let{posX:r,posY:n,sizeX:o,sizeY:i,frame:s,bgColorCode:a,fgColorCode:d}=e;for(let l=0;l<i;l++){let c=n+l;if(!(c<0||c>=this.currentHeight))for(let p=0;p<o;p++){let u=r+p;if(u<0||u>=this.currentWidth)continue;let m=l*o+p;if(m>=s.length)break;let b=c*this.currentWidth+u;t.set(b,s[m],d,a)}}}rasterizeSubFrameMultiColor(e,t){let{posX:r,posY:n,sizeX:o,sizeY:i,frame:s}=e;for(let a=0;a<i;a++){let d=n+a;if(!(d<0||d>=this.currentHeight))for(let l=0;l<o;l++){let c=r+l;if(c<0||c>=this.currentWidth)continue;let p=a*o+l;if(p>=s.length)break;let u=s[p],m=d*this.currentWidth+c;t.set(m,u.charCode,u.fgColorCode,u.bgColorCode)}}}rasterizeFullFrame(e,t){let{frame:r,bgColorCode:n,fgColorCode:o}=e,i=this.currentWidth*this.currentHeight;for(let s=0;s<i&&s<r.length;s++)t.set(s,r[s],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:s}=e;for(let a=0;a<i;a++){let d=n+a;if(!(d<0||d>=this.currentHeight))for(let l=0;l<o;l++){let c=r+l;if(c<0||c>=this.currentWidth)continue;let p=a*o+l;if(p>=s.length)break;let u=d*this.currentWidth+c,m=s[p];t.setColorsOnly(u,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:s,charCode:a,bgColorCode:d,fgColorCode:l}=e;if(s)for(let c=0;c<i;c++){let p=n+c;if(!(p<0||p>=this.currentHeight))for(let u=0;u<o;u++){let m=r+u;if(m<0||m>=this.currentWidth)continue;let b=p*this.currentWidth+m;t.set(b,a,l,d)}}else{for(let c=0;c<o;c++)this.setCell(r+c,n,a,d,l,t),this.setCell(r+c,n+i-1,a,d,l,t);for(let c=0;c<i;c++)this.setCell(r,n+c,a,d,l,t),this.setCell(r+o-1,n+c,a,d,l,t)}}rasterizeCircle(e,t){let{centerX:r,centerY:n,radius:o,filled:i,charCode:s,bgColorCode:a,fgColorCode:d}=e;if(i)for(let l=-o;l<=o;l++){let c=n+l;if(!(c<0||c>=this.currentHeight))for(let p=-o;p<=o;p++){let u=r+p;if(!(u<0||u>=this.currentWidth)&&p*p+l*l<=o*o){let m=c*this.currentWidth+u;t.set(m,s,d,a)}}}else{let l=o,c=0,p=0;for(;l>=c;)this.setCell(r+l,n+c,s,a,d,t),this.setCell(r+c,n+l,s,a,d,t),this.setCell(r-c,n+l,s,a,d,t),this.setCell(r-l,n+c,s,a,d,t),this.setCell(r-l,n-c,s,a,d,t),this.setCell(r-c,n-l,s,a,d,t),this.setCell(r+c,n-l,s,a,d,t),this.setCell(r+l,n-c,s,a,d,t),p<=0&&(c+=1,p+=2*c+1),p>0&&(l-=1,p-=2*l+1)}}rasterizeLine(e,t){let{x1:r,y1:n,x2:o,y2:i,charCode:s,bgColorCode:a,fgColorCode:d}=e,l=Math.abs(o-r),c=Math.abs(i-n),p=r<o?1:-1,u=n<i?1:-1,m=l-c,b=r,C=n;for(;this.setCell(b,C,s,a,d,t),!(b===o&&C===i);){let S=2*m;S>-c&&(m-=c,b+=p),S<l&&(m+=l,C+=u)}}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 s=0;s<i.length-1;s++){let a=i[s],d=i[s+1];this.rasterizeLineSegment(a.x,a.y,d.x,d.y,r,o,n,t)}}rasterizeLineSegment(e,t,r,n,o,i,s,a){let d=Math.abs(r-e),l=Math.abs(n-t),c=e<r?1:-1,p=t<n?1:-1,u=d-l,m=e,b=t;for(;this.setCell(m,b,o,i,s,a),!(m===r&&b===n);){let C=2*u;C>-l&&(u-=l,m+=c),C<d&&(u+=d,b+=p)}}rasterizeEllipse(e,t){let{centerX:r,centerY:n,radiusX:o,radiusY:i,filled:s,charCode:a,bgColorCode:d,fgColorCode:l}=e;if(s)for(let c=-i;c<=i;c++){let p=n+c;if(!(p<0||p>=this.currentHeight))for(let u=-o;u<=o;u++){let m=r+u;if(m<0||m>=this.currentWidth)continue;if(u*u/(o*o)+c*c/(i*i)<=1){let C=p*this.currentWidth+m;t.set(C,a,l,d)}}}else{let c=Math.max(o,i)*8;for(let p=0;p<c;p++){let u=2*Math.PI*p/c,m=Math.round(r+o*Math.cos(u)),b=Math.round(n+i*Math.sin(u));this.setCell(m,b,a,d,l,t)}}}rasterizeTriangle(e,t){let{x1:r,y1:n,x2:o,y2:i,x3:s,y3:a,filled:d,charCode:l,bgColorCode:c,fgColorCode:p}=e;if(d){let u=[{x:r,y:n},{x:o,y:i},{x:s,y:a}].sort((O,v)=>O.y-v.y),[m,b,C]=u,S=y((O,v,w)=>{let A=Math.round(Math.min(v,w)),E=Math.round(Math.max(v,w));for(let U=A;U<=E;U++)if(U>=0&&U<this.currentWidth&&O>=0&&O<this.currentHeight){let M=O*this.currentWidth+U;t.set(M,l,p,c)}},"drawLine"),I=y((O,v,w,A,E)=>A===v?w:w+(O-v)*(E-w)/(A-v),"interpolate");for(let O=m.y;O<=b.y;O++){let v=I(O,m.y,m.x,C.y,C.x),w=I(O,m.y,m.x,b.y,b.x);S(O,v,w)}for(let O=b.y+1;O<=C.y;O++){let v=I(O,m.y,m.x,C.y,C.x),w=I(O,b.y,b.x,C.y,C.x);S(O,v,w)}}else this.drawLineSegment(r,n,o,i,l,c,p,t),this.drawLineSegment(o,i,s,a,l,c,p,t),this.drawLineSegment(s,a,r,n,l,c,p,t)}drawLineSegment(e,t,r,n,o,i,s,a){let d=Math.abs(r-e),l=Math.abs(n-t),c=e<r?1:-1,p=t<n?1:-1,u=d-l,m=e,b=t;for(;this.setCell(m,b,o,i,s,a),!(m===r&&b===n);){let C=2*u;C>-l&&(u-=l,m+=c),C<d&&(u+=d,b+=p)}}rasterizeDotCloud(e,t){let{charCode:r,bgColorCode:n,fgColorCode:o,positions:i}=e,s=this.currentWidth;for(let a=0;a<i.length;a++){let d=i[a];if(d.posX<0||d.posX>=s||d.posY<0||d.posY>=this.currentHeight)continue;let l=d.posY*s+d.posX;t.set(l,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:s,bgColorCode:a,fgColorCode:d,override:l,mask:c}=e;for(let p=0;p<i;p++){let u=n+p;if(!(u<0||u>=this.currentHeight))for(let m=0;m<o;m++){let b=r+m;if(b<0||b>=this.currentWidth)continue;let C=p*o+m,S=Math.floor(C/8),I=C%8,O=(c[S]&1<<I)!==0,v=u*this.currentWidth+b;O?t.set(v,s,d,a):l&&t.set(v,255,255,255)}}}rasterizeBitmask4(e,t){let{posX:r,posY:n,sizeX:o,sizeY:i,override:s,variants:a,mask:d}=e;for(let l=0;l<i;l++){let c=n+l;if(!(c<0||c>=this.currentHeight))for(let p=0;p<o;p++){let u=r+p;if(u<0||u>=this.currentWidth)continue;let m=l*o+p,b=Math.floor(m/4),C=m%4*2,S=d[b]>>C&3,I=c*this.currentWidth+u;if(S>0){let O=a[S-1];t.set(I,O.charCode,O.fgColorCode,O.bgColorCode)}else s&&t.set(I,255,255,255)}}}rasterizeBitmask16(e,t){let{posX:r,posY:n,sizeX:o,sizeY:i,override:s,variants:a,mask:d}=e;for(let l=0;l<i;l++){let c=n+l;if(!(c<0||c>=this.currentHeight))for(let p=0;p<o;p++){let u=r+p;if(u<0||u>=this.currentWidth)continue;let m=l*o+p,b=Math.floor(m/2),C=m%2*4,S=d[b]>>C&15,I=c*this.currentWidth+u;if(S>0){let O=a[S-1];t.set(I,O.charCode,O.fgColorCode,O.bgColorCode)}else s&&t.set(I,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:s}=e;for(let a=0;a<this.currentHeight;a++)for(let d=0;d<this.currentWidth;d++){let l=d%r,p=a%n*r+l;if(p<o.length){let u=a*this.currentWidth+d;t.set(u,o[p],s,i)}}}rasterizeSprite(e,t,r){if(!r)return;let{posX:n,posY:o,spriteIndex:i,bgColorCode:s,fgColorCode:a}=e,d=r.getUnicolorSprite(i);if(!d)return;let l=d.data;for(let c=0;c<d.sizeY;c++)for(let p=0;p<d.sizeX;p++){let u=n+p,m=o+c;if(!this.isInBounds(u,m))continue;let b=c*d.sizeX+p,C=l.get(b);this.setCell(u,m,C,s,a,t)}}rasterizeSpriteMultiColor(e,t,r){if(!r)return;let{posX:n,posY:o,spriteIndex:i}=e,s=r.getMulticolorSprite(i);if(!s)return;let a=s.data;for(let d=0;d<s.sizeY;d++)for(let l=0;l<s.sizeX;l++){let c=n+l,p=o+d;if(!this.isInBounds(c,p))continue;let u=d*s.sizeX+l,m=a.getCharCode(u),b=a.getFgColorCode(u),C=a.getBgColorCode(u);this.setCell(c,p,m,C,b,t)}}rasterizeSpriteCloud(e,t,r){if(!r)return;let{spriteIndex:n,bgColorCode:o,fgColorCode:i,positions:s}=e,a=r.getUnicolorSprite(n);if(a){if(a.sizeX===1&&a.sizeY===1){let d=a.data.get(0),l=this.currentWidth;for(let c=0;c<s.length;c++){let p=s[c];if(p.posX<0||p.posX>=l||p.posY<0||p.posY>=this.currentHeight)continue;let u=p.posY*l+p.posX;t.set(u,d,i,o)}return}for(let d=0;d<s.length;d++){let l=a.data;for(let c=0;c<a.sizeY;c++)for(let p=0;p<a.sizeX;p++){let u=s[d].posX+p,m=s[d].posY+c;if(!this.isInBounds(u,m))continue;let b=c*a.sizeX+p,C=l.get(b);this.setCell(u,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 s=0;s<o.length;s++){let a=i.data;for(let d=0;d<i.sizeY;d++)for(let l=0;l<i.sizeX;l++){let c=o[s].posX+l,p=o[s].posY+d;if(!this.isInBounds(c,p))continue;let u=d*i.sizeX+l,m=a.getCharCode(u),b=a.getFgColorCode(u),C=a.getBgColorCode(u);this.setCell(c,p,m,C,b,t)}}}rasterizeSpriteCloudVaried(e,t,r){if(!r)return;let{sprites:n}=e;for(let o=0;o<n.length;o++){let i=n[o],s=r.getUnicolorSprite(i.spriteIndex);if(!s)continue;let a=s.data;for(let d=0;d<s.sizeY;d++)for(let l=0;l<s.sizeX;l++){let c=i.posX+l,p=i.posY+d;if(!this.isInBounds(c,p))continue;let u=d*s.sizeX+l,m=a.get(u);this.setCell(c,p,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],s=r.getMulticolorSprite(i.spriteIndex);if(!s)continue;let a=s.data;for(let d=0;d<s.sizeY;d++)for(let l=0;l<s.sizeX;l++){let c=i.posX+l,p=i.posY+d;if(!this.isInBounds(c,p))continue;let u=d*s.sizeX+l,m=a.getCharCode(u),b=a.getFgColorCode(u),C=a.getBgColorCode(u);this.setCell(c,p,m,C,b,t)}}}rasterizeFillSprite(e,t,r){if(!r)return;let{spriteIndex:n,bgColorCode:o,fgColorCode:i}=e,s=r.getUnicolorSprite(n);if(!s)return;let a=s.data;for(let d=0;d<this.currentHeight;d++)for(let l=0;l<this.currentWidth;l++){let c=l%s.sizeX,u=d%s.sizeY*s.sizeX+c,m=a.get(u),b=d*this.currentWidth+l;t.set(b,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 s=0;s<this.currentHeight;s++)for(let a=0;a<this.currentWidth;a++){let d=a%o.sizeX,c=s%o.sizeY*o.sizeX+d,p=i.getCharCode(c),u=i.getFgColorCode(c),m=i.getBgColorCode(c),b=s*this.currentWidth+a;t.set(b,p,u,m)}}setCell(e,t,r,n,o,i){if(!this.isInBounds(e,t))return;let s=t*this.currentWidth+e;i.set(s,r,o,n)}isInBounds(e,t){return e>=0&&e<this.currentWidth&&t>=0&&t<this.currentHeight}};y(Bt,"LayerRasterizer");var ae=Bt;var H=class H{constructor(e){this.engine=e;h(this,"colorCache",new Array(256));h(this,"cellsBuffer",[]);h(this,"opacityBuffer",new Uint8Array(0));h(this,"visibleLayersBuffer",[]);h(this,"visibleLayerIdsBuffer",[]);h(this,"passCellsBuffers",[]);h(this,"passOpacityBuffers",[]);this.rebuildColorCache()}static getChar(e){let t=H.charCache.get(e);return t===void 0&&(t=String.fromCharCode(e),H.charCache.set(e,t)),t}getLastVisibleLayerIds(){return this.visibleLayerIdsBuffer}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,s=t.x,a=t.x+256,d=t.y,l=t.y+256;return!(n<=s||r>=a||i<=d||o>=l)}rasterize(e,t,r){let n=this.normalizePasses(r);return this.rasterizeMultiPass(e,t,n)}rasterizeSinglePass(e,t){let r=e.width*e.height,n=this.cellsBuffer;n.length=r;for(let d=0;d<r;d++)n[d]?(n[d].char=" ",n[d].fgColorIndex=255,n[d].bgColorIndex=255,n[d].fgEmission=0,n[d].bgEmission=0):n[d]={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 d=0;d<t.length;d++){let l=t[d];l.isEnabled()&&this.isLayerVisible(e,l.getOrigin())&&i.push(l)}i.sort((d,l)=>l.getZOrder()-d.getZOrder());let s=this.visibleLayerIdsBuffer;s.length=i.length;for(let d=0;d<i.length;d++)s[d]=i[d].getId();for(let d=0;d<e.height;d++)for(let l=0;l<e.width;l++){let c=d*e.width+l;if(o[c])continue;let p=e.x+l,u=e.y+d;for(let m=0;m<i.length;m++){let b=i[m],C=p-b.getOrigin().x,S=u-b.getOrigin().y,I=b.getWidth(),O=b.getHeight();if(C<0||C>=I||S<0||S>=O)continue;let v=S*I+C,w=b.getData(),A=w.getCharCode(v),E=w.getFgColorCode(v),U=w.getBgColorCode(v),M=n[c];if(A!==0&&M.char===" "&&(M.char=H.getChar(A)),E!==255&&M.fgColorIndex===255&&(M.fgColorIndex=E,M.fgEmission=this.getColorEmission(E)),U!==255){M.bgColorIndex===255&&(M.bgColorIndex=U,M.bgEmission=this.getColorEmission(U)),o[c]=1;break}}}let a=new Array(r);for(let d=0;d<r;d++)a[d]={char:n[d].char,fgColorIndex:n[d].fgColorIndex,bgColorIndex:n[d].bgColorIndex,fgEmission:n[d].fgEmission,bgEmission:n[d].bgEmission};return{id:e.id,width:e.width,height:e.height,cells:a,palette:this.colorCache}}rasterizeMultiPass(e,t,r){let n=e.width*e.height;this.ensurePassBuffers(r.length,n),this.visibleLayerIdsBuffer.length=0;let o=this.visibleLayersBuffer;o.length=0;for(let l=0;l<t.length;l++){let c=t[l];c.isEnabled()&&this.isLayerVisible(e,c.getOrigin())&&o.push(c)}o.sort((l,c)=>c.getZOrder()-l.getZOrder());for(let l=0;l<r.length;l++){let c=r[l],p=this.passCellsBuffers[l],u=this.preparePassBuffers(p,this.passOpacityBuffers[l],n);this.passOpacityBuffers[l]=u;let m=[];for(let C=0;C<o.length;C++){let S=o[C],I=S.getZOrder();I<c.zMin||I>c.zMax||m.push(S)}let b=this.visibleLayerIdsBuffer.length;for(let C=0;C<m.length;C++)this.visibleLayerIdsBuffer[b+C]=m[C].getId();this.composePass(e,m,p,u)}let i=this.cellsBuffer,s=this.preparePassBuffers(i,this.opacityBuffer,n);this.opacityBuffer=s;let a=new Array(n),d=[];for(let l=0;l<r.length;l++){let c=this.passCellsBuffers[l],p=new Array(n);for(let u=0;u<n;u++){let m=c[u];p[u]={char:m.char,fgColorIndex:m.fgColorIndex,bgColorIndex:m.bgColorIndex,fgEmission:m.fgEmission,bgEmission:m.bgEmission}}d.push({id:r[l].id,zMin:r[l].zMin,zMax:r[l].zMax,cells:p})}for(let l=0;l<n;l++){let c=i[l];for(let p=0;p<r.length;p++){let u=this.passCellsBuffers[p][l];if(c.char===" "&&u.char!==" "&&(c.char=u.char),c.fgColorIndex===255&&u.fgColorIndex!==255&&(c.fgColorIndex=u.fgColorIndex,c.fgEmission=u.fgEmission),u.bgColorIndex!==255){c.bgColorIndex===255&&(c.bgColorIndex=u.bgColorIndex,c.bgEmission=u.bgEmission);break}}a[l]={char:c.char,fgColorIndex:c.fgColorIndex,bgColorIndex:c.bgColorIndex,fgEmission:c.fgEmission,bgEmission:c.bgEmission}}return{id:e.id,width:e.width,height:e.height,cells:a,palette:this.colorCache,passes:d}}composePass(e,t,r,n){let o=e.width,i=e.height;for(let s=0;s<i;s++)for(let a=0;a<o;a++){let d=s*o+a;if(n[d])continue;let l=e.x+a,c=e.y+s;for(let p=0;p<t.length;p++){let u=t[p],m=l-u.getOrigin().x,b=c-u.getOrigin().y,C=u.getWidth(),S=u.getHeight();if(m<0||m>=C||b<0||b>=S)continue;let I=b*C+m,O=u.getData(),v=O.getCharCode(I),w=O.getFgColorCode(I),A=O.getBgColorCode(I),E=r[d];if(v!==0&&E.char===" "&&(E.char=H.getChar(v)),w!==255&&E.fgColorIndex===255&&(E.fgColorIndex=w,E.fgEmission=this.getColorEmission(w)),A!==255){E.bgColorIndex===255&&(E.bgColorIndex=A,E.bgEmission=this.getColorEmission(A)),n[d]=1;break}}}}preparePassBuffers(e,t,r){e.length=r;for(let n=0;n<r;n++)e[n]?(e[n].char=" ",e[n].fgColorIndex=255,e[n].bgColorIndex=255,e[n].fgEmission=0,e[n].bgEmission=0):e[n]={char:" ",fgColorIndex:255,bgColorIndex:255,fgEmission:0,bgEmission:0};return t.length<r?t=new Uint8Array(r):t.fill(0,0,r),t}ensurePassBuffers(e,t){for(;this.passCellsBuffers.length<e;)this.passCellsBuffers.push([]);for(;this.passOpacityBuffers.length<e;)this.passOpacityBuffers.push(new Uint8Array(t));this.passCellsBuffers.length>e&&(this.passCellsBuffers.length=e),this.passOpacityBuffers.length>e&&(this.passOpacityBuffers.length=e);for(let r=0;r<e;r++)this.passOpacityBuffers[r].length<t?this.passOpacityBuffers[r]=new Uint8Array(t):this.passOpacityBuffers[r].fill(0,0,t)}normalizePasses(e){let t={id:0,zMin:0,zMax:255,enabled:!0};if(!e||e.length===0)return[t];let r=e.filter(n=>n.enabled!==!1);return r.length===0?[t]:r.slice(0,4)}rasterizeWithSortedLayers(e,t){let r=e.width*e.height,n=this.cellsBuffer;n.length=r;for(let a=0;a<r;a++)n[a]?(n[a].char=" ",n[a].fgColorIndex=255,n[a].bgColorIndex=255,n[a].fgEmission=0,n[a].bgEmission=0):n[a]={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 a=0;a<t.length;a++){let d=t[a];this.isLayerVisible(e,d.getOrigin())&&i.push(d)}for(let a=0;a<e.height;a++)for(let d=0;d<e.width;d++){let l=a*e.width+d;if(o[l])continue;let c=e.x+d,p=e.y+a;for(let u=0;u<i.length;u++){let m=i[u],b=c-m.getOrigin().x,C=p-m.getOrigin().y,S=m.getWidth(),I=m.getHeight();if(b<0||b>=S||C<0||C>=I)continue;let O=C*S+b,v=m.getData(),w=v.getCharCode(O),A=v.getFgColorCode(O),E=v.getBgColorCode(O),U=n[l];if(w!==0&&U.char===" "&&(U.char=H.getChar(w)),A!==255&&U.fgColorIndex===255&&(U.fgColorIndex=A,U.fgEmission=this.getColorEmission(A)),E!==255){U.bgColorIndex===255&&(U.bgColorIndex=E,U.bgEmission=this.getColorEmission(E)),o[l]=1;break}}}let s=new Array(r);for(let a=0;a<r;a++)s[a]={char:n[a].char,fgColorIndex:n[a].fgColorIndex,bgColorIndex:n[a].bgColorIndex,fgEmission:n[a].fgEmission,bgEmission:n[a].bgEmission};return{id:e.id,width:e.width,height:e.height,cells:s,palette:this.colorCache}}calculateIntersection(e,t){let r=e.x,n=e.x+e.width,o=e.y,i=e.y+e.height,s=t.x,a=t.x+256,d=t.y,l=t.y+256,c=Math.max(r,s),p=Math.min(n,a),u=Math.max(o,d),m=Math.min(i,l);return{visible:c<p&&u<m,originStart:{x:c-e.x,y:u-e.y},originEnd:{x:p-e.x,y:m-e.y},layerStart:{x:c-t.x,y:u-t.y},layerEnd:{x:p-t.x,y:m-t.y}}}};y(H,"DisplayRasterizer"),h(H,"charCache",(()=>{let e=new Map;for(let t=0;t<256;t++)e.set(t,String.fromCharCode(t));return e})());var de=H;T();var R=class R{static toCharCode(e){if(typeof e=="number")return e&65535;let t=e.charCodeAt(0);return be(t)}static dedent(e){let t=e.split(`
|
|
3
3
|
`);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(`
|
|
4
|
-
`)}static char(e,t,r,n=15,o=0){return{type:1,posX:e,posY:t,charCode:P.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:P.dedent(r),bgColorCode:o,fgColorCode:n}}static subFrame(e,t,r,n,o,i=15,s=0){return{type:3,posX:e,posY:t,sizeX:r,sizeY:n,frame:o.map(a=>P.toCharCode(a)),bgColorCode:s,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:P.toCharCode(i.charCode),bgColorCode:i.bgColorCode,fgColorCode:i.fgColorCode}))}}static fullFrame(e,t=15,r=0){return{type:5,frame:e.map(n=>P.toCharCode(n)),bgColorCode:r,fgColorCode:t}}static fullFrameMultiColor(e){return{type:6,frame:e.map(t=>({charCode:P.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:P.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:P.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:P.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:P.toCharCode(o.charCode??9608),bgColorCode:o.bgColor??0,fgColorCode:o.fgColor??15}}}static triangle(e,t,r,n,o,i,s={}){return{type:10,shapeType:5,shapeData:{x1:e,y1:t,x2:r,y2:n,x3:o,y3:i,filled:s.filled??!0,charCode:P.toCharCode(s.charCode??9608),bgColorCode:s.bgColor??0,fgColorCode:s.fgColor??15}}}static dotCloud(e,t,r=15,n=0){return{type:11,charCode:P.toCharCode(t),bgColorCode:n,fgColorCode:r,positions:e}}static dotCloudMultiColor(e){return{type:12,dots:e.map(t=>({...t,charCode:P.toCharCode(t.charCode)}))}}static bitmask(e,t,r,n,o,i,s=15,a=0,d=!1){let l=r*n,c=Math.ceil(l/8),u=new Uint8Array(c);for(let p=0;p<l;p++)if(o[p]){let m=Math.floor(p/8),b=p%8;u[m]|=1<<b}return{type:17,posX:e,posY:t,sizeX:r,sizeY:n,charCode:P.toCharCode(i),bgColorCode:a,fgColorCode:s,override:d,mask:u}}static bitmask4(e,t,r,n,o,i,s=!1){let a={char:"?",fgColor:15,bgColor:0},d=[i[0]??a,i[1]??a,i[2]??a],l=r*n,c=Math.ceil(l/4),u=new Uint8Array(c);for(let p=0;p<l;p++){let m=o[p]&3,b=Math.floor(p/4),C=p%4*2;u[b]|=m<<C}return{type:18,posX:e,posY:t,sizeX:r,sizeY:n,override:s,variants:[{charCode:P.toCharCode(d[0].char),fgColorCode:d[0].fgColor,bgColorCode:d[0].bgColor},{charCode:P.toCharCode(d[1].char),fgColorCode:d[1].fgColor,bgColorCode:d[1].bgColor},{charCode:P.toCharCode(d[2].char),fgColorCode:d[2].fgColor,bgColorCode:d[2].bgColor}],mask:u}}static bitmask16(e,t,r,n,o,i,s=!1){let a={char:"?",fgColor:15,bgColor:0},d=[];for(let p=0;p<15;p++)d.push(i[p]??a);let l=r*n,c=Math.ceil(l/2),u=new Uint8Array(c);for(let p=0;p<l;p++){let m=o[p]&15,b=Math.floor(p/2),C=p%2*4;u[b]|=m<<C}return{type:24,posX:e,posY:t,sizeX:r,sizeY:n,override:s,variants:d.map(p=>({charCode:P.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:P.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=>P.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,s={}){let a=[];for(let d=0;d<=o;d++)for(let l=0;l<=i;l++)a.push({posX:e+l*r,posY:t+d*n});return this.dotCloud(a,s.charCode??"+",s.fgColor??15,s.bgColor??0)}static polyline(e,t="*",r=15,n=0){return{type:25,charCode:P.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(P,"OrderBuilder");var Ee=P;dr();var Tt=class Tt{constructor(e=65536,t=!1){h(this,"charCodes");h(this,"fgColors");h(this,"bgColors");h(this,"size");h(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 s=e[i];this.charCodes[s]=o,this.fgColors[s]=r,this.bgColors[s]=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(Tt,"CellBuffer");var N=Tt,Ft=class Ft{constructor(e){h(this,"data");h(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(Ft,"CharCodeBuffer");var Ae=Ft;var Lt=class Lt{constructor(){h(this,"unicolorSprites",new Map);h(this,"multicolorSprites",new Map)}loadUnicolorSprites(e){for(let t of e.sprites){let r=new Ae(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 N(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(Lt,"SpriteRegistry");var de=Lt;var be=require("@utsp/types");var Dt=class Dt{constructor(e=0,t=60,r=40){h(this,"id");h(this,"origin");h(this,"size");h(this,"previousOrigin",new be.Vector2(0,0));h(this,"previousSize",new be.Vector2(0,0));h(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 be.Vector2(0,0),this.size=new be.Vector2(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}))}getDebugInfo(){return{id:this.id,origin:{x:this.origin.x,y:this.origin.y},size:{x:this.size.x,y:this.size.y}}}};y(Dt,"Display");var Pe=Dt;var cn=require("@utsp/types");var Vt=255,Y=class Y{constructor(e,t,r,n,o){h(this,"id",0);h(this,"name");h(this,"origin");h(this,"orders",[]);h(this,"zOrder",0);h(this,"data");h(this,"width");h(this,"height");h(this,"isStatic",!1);h(this,"spriteRegistry");h(this,"mode","server");h(this,"charCodeMode");h(this,"previousOrigin");h(this,"previousZOrder");h(this,"enabled",!0);h(this,"useSetMode",!1);h(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.name=i.name,this.width=r,this.height=n,this.isStatic=i.isStatic??!1,this.charCodeMode=i.charCodeMode??"8bit";let s=this.charCodeMode==="16bit";this.data=new N(r*n,s),this.previousOrigin=new cn.Vector2(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}getName(){return this.name}setName(e){let t=typeof e=="string"?e.trim():void 0;this.name=t&&t.length>0?t:void 0}getDebugInfo(){return{id:this.id,name:this.name,z:this.zOrder,isStatic:this.isStatic,charCodeMode:this.charCodeMode,width:this.width,height:this.height,origin:{x:this.origin.x,y:this.origin.y},enabled:this.enabled,useSetMode:this.useSetMode,needsCommit:this.needsCommit,ordersCount:this.orders.length}}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>Vt&&(console.error(`[UTSP] \u26A0\uFE0F CRITICAL: Layer ${this.id} has ${this.orders.length} orders, but max is ${Vt}!
|
|
4
|
+
`)}static char(e,t,r,n=15,o=0){return{type:1,posX:e,posY:t,charCode:R.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:R.dedent(r),bgColorCode:o,fgColorCode:n}}static subFrame(e,t,r,n,o,i=15,s=0){return{type:3,posX:e,posY:t,sizeX:r,sizeY:n,frame:o.map(a=>R.toCharCode(a)),bgColorCode:s,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:R.toCharCode(i.charCode),bgColorCode:i.bgColorCode,fgColorCode:i.fgColorCode}))}}static fullFrame(e,t=15,r=0){return{type:5,frame:e.map(n=>R.toCharCode(n)),bgColorCode:r,fgColorCode:t}}static fullFrameMultiColor(e){return{type:6,frame:e.map(t=>({charCode:R.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:R.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:R.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:R.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:R.toCharCode(o.charCode??9608),bgColorCode:o.bgColor??0,fgColorCode:o.fgColor??15}}}static triangle(e,t,r,n,o,i,s={}){return{type:10,shapeType:5,shapeData:{x1:e,y1:t,x2:r,y2:n,x3:o,y3:i,filled:s.filled??!0,charCode:R.toCharCode(s.charCode??9608),bgColorCode:s.bgColor??0,fgColorCode:s.fgColor??15}}}static dotCloud(e,t,r=15,n=0){return{type:11,charCode:R.toCharCode(t),bgColorCode:n,fgColorCode:r,positions:e}}static dotCloudMultiColor(e){return{type:12,dots:e.map(t=>({...t,charCode:R.toCharCode(t.charCode)}))}}static bitmask(e,t,r,n,o,i,s=15,a=0,d=!1){let l=r*n,c=Math.ceil(l/8),p=new Uint8Array(c);for(let u=0;u<l;u++)if(o[u]){let m=Math.floor(u/8),b=u%8;p[m]|=1<<b}return{type:17,posX:e,posY:t,sizeX:r,sizeY:n,charCode:R.toCharCode(i),bgColorCode:a,fgColorCode:s,override:d,mask:p}}static bitmask4(e,t,r,n,o,i,s=!1){let a={char:"?",fgColor:15,bgColor:0},d=[i[0]??a,i[1]??a,i[2]??a],l=r*n,c=Math.ceil(l/4),p=new Uint8Array(c);for(let u=0;u<l;u++){let m=o[u]&3,b=Math.floor(u/4),C=u%4*2;p[b]|=m<<C}return{type:18,posX:e,posY:t,sizeX:r,sizeY:n,override:s,variants:[{charCode:R.toCharCode(d[0].char),fgColorCode:d[0].fgColor,bgColorCode:d[0].bgColor},{charCode:R.toCharCode(d[1].char),fgColorCode:d[1].fgColor,bgColorCode:d[1].bgColor},{charCode:R.toCharCode(d[2].char),fgColorCode:d[2].fgColor,bgColorCode:d[2].bgColor}],mask:p}}static bitmask16(e,t,r,n,o,i,s=!1){let a={char:"?",fgColor:15,bgColor:0},d=[];for(let u=0;u<15;u++)d.push(i[u]??a);let l=r*n,c=Math.ceil(l/2),p=new Uint8Array(c);for(let u=0;u<l;u++){let m=o[u]&15,b=Math.floor(u/2),C=u%2*4;p[b]|=m<<C}return{type:24,posX:e,posY:t,sizeX:r,sizeY:n,override:s,variants:d.map(u=>({charCode:R.toCharCode(u.char),fgColorCode:u.fgColor,bgColorCode:u.bgColor})),mask:p}}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:R.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=>R.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,s={}){let a=[];for(let d=0;d<=o;d++)for(let l=0;l<=i;l++)a.push({posX:e+l*r,posY:t+d*n});return this.dotCloud(a,s.charCode??"+",s.fgColor??15,s.bgColor??0)}static polyline(e,t="*",r=15,n=0){return{type:25,charCode:R.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(R,"OrderBuilder");var Ee=R;lr();var Ft=class Ft{constructor(e=65536,t=!1){h(this,"charCodes");h(this,"fgColors");h(this,"bgColors");h(this,"size");h(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 s=e[i];this.charCodes[s]=o,this.fgColors[s]=r,this.bgColors[s]=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(Ft,"CellBuffer");var N=Ft,Lt=class Lt{constructor(e){h(this,"data");h(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(Lt,"CharCodeBuffer");var Ae=Lt;var Dt=class Dt{constructor(){h(this,"unicolorSprites",new Map);h(this,"multicolorSprites",new Map)}loadUnicolorSprites(e){for(let t of e.sprites){let r=new Ae(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 N(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(Dt,"SpriteRegistry");var le=Dt;var ge=require("@utsp/types");var Vt=class Vt{constructor(e=0,t=60,r=40){h(this,"id");h(this,"origin");h(this,"size");h(this,"previousOrigin",new ge.Vector2(0,0));h(this,"previousSize",new ge.Vector2(0,0));h(this,"toDraw",[]);h(this,"renderPasses");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 ge.Vector2(0,0),this.size=new ge.Vector2(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}))}getRenderPasses(){return this.renderPasses}setRenderPasses(e){if(!e||e.length===0){this.renderPasses=void 0;return}if(e.length>4)throw new Error(`renderPasses supports up to 4 entries, got ${e.length}`);this.renderPasses=e.map(t=>this.normalizePass(t))}normalizePass(e){let t=Math.max(0,Math.min(255,e.zMin)),r=Math.max(0,Math.min(255,e.zMax));if(t>r){let n=t;t=r,r=n}return{id:e.id,zMin:t,zMax:r,enabled:e.enabled!==!1}}getDebugInfo(){return{id:this.id,origin:{x:this.origin.x,y:this.origin.y},size:{x:this.size.x,y:this.size.y},renderPasses:this.renderPasses}}};y(Vt,"Display");var Pe=Vt;var bn=require("@utsp/types");var _t=255,Y=class Y{constructor(e,t,r,n,o){h(this,"id",0);h(this,"name");h(this,"origin");h(this,"orders",[]);h(this,"zOrder",0);h(this,"data");h(this,"width");h(this,"height");h(this,"isStatic",!1);h(this,"spriteRegistry");h(this,"mode","server");h(this,"charCodeMode");h(this,"previousOrigin");h(this,"previousZOrder");h(this,"enabled",!0);h(this,"useSetMode",!1);h(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.name=i.name,this.width=r,this.height=n,this.isStatic=i.isStatic??!1,this.charCodeMode=i.charCodeMode??"8bit";let s=this.charCodeMode==="16bit";this.data=new N(r*n,s),this.previousOrigin=new bn.Vector2(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}getName(){return this.name}setName(e){let t=typeof e=="string"?e.trim():void 0;this.name=t&&t.length>0?t:void 0}getDebugInfo(){return{id:this.id,name:this.name,z:this.zOrder,isStatic:this.isStatic,charCodeMode:this.charCodeMode,width:this.width,height:this.height,origin:{x:this.origin.x,y:this.origin.y},enabled:this.enabled,useSetMode:this.useSetMode,needsCommit:this.needsCommit,ordersCount:this.orders.length}}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>_t&&(console.error(`[UTSP] \u26A0\uFE0F CRITICAL: Layer ${this.id} has ${this.orders.length} orders, but max is ${_t}!
|
|
5
5
|
This WILL cause packet corruption and decoding errors.
|
|
6
6
|
Solution: Split into multiple layers or reduce order count.
|
|
7
|
-
Orders breakdown: ${this.getOrdersBreakdown()}`),this.orders=this.orders.slice(0,Vt)),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"),h(Y,"rasterizer",new se);var le=Y;var Ht=class Ht{constructor(){h(this,"macros",new Map);h(this,"macroNameToId",new Map);h(this,"nextMacroId",0);h(this,"instances",new Map);h(this,"instanceNameToId",new Map);h(this,"nextInstanceId",0);h(this,"layerNameToId",new Map);h(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(Ht,"MacroRegistry");var Re=Ht;function V(g){return typeof g=="number"?g:g.charCodeAt(0)}y(V,"toCharCode");function ge(g){return typeof g=="string"?g.charAt(0):String.fromCharCode(g)}y(ge,"toCharString");var Mn={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"}},_t={update(g,e,t,r){let n,o;e.subtype==="button"&&e.button?(n=t.resolveValue(e.button.width,g.params),o=t.resolveValue(e.button.height??3,g.params)):(n=t.resolveValue(g.params.width??1,g.params),o=t.resolveValue(g.params.height??1,g.params));let i=g.isHovered;g.isHovered=En(t.mouseX,t.mouseY,g.x,g.y,n,o);let s=g.isActive;g.isActive=g.isHovered&&t.mouseDown,s&&!g.isActive&&g.isHovered&&(r.push({instanceId:g.instanceId,event:"click"}),e.subtype==="button"&&e.button?.soundRelease!==void 0&&t.playSound?.(e.button.soundRelease)),e.subtype==="button"&&e.button&&(!i&&g.isHovered&&e.button.soundHover!==void 0&&t.playSound?.(e.button.soundHover),!s&&g.isActive&&e.button.soundClick!==void 0&&t.playSound?.(e.button.soundClick))},render(g,e,t){let r=un(g),n=e.states[r]??e.states.normal,o={...g.params,...n},i=[];if(e.subtype==="button"&&e.button)An(g,e,o,i,t);else if(e.base)for(let s of e.base){let a=kn(s,g.x,g.y,o,t);a&&i.push(a)}return i}};function En(g,e,t,r,n,o){return g>=t&&g<t+n&&e>=r&&e<r+o}y(En,"isPointInRect");function un(g){return g.isDisabled?"disabled":g.isActive?"active":g.isHovered?"hover":g.isFocused?"focused":"normal"}y(un,"getUIState");function ye(g){if(typeof g=="number")return Math.max(0,Math.min(255,Math.floor(g)));if(typeof g=="string"){let e=parseInt(g,10);if(!isNaN(e))return Math.max(0,Math.min(255,Math.floor(e)))}return 243}y(ye,"toColorIndex");function An(g,e,t,r,n){let o=e.button,i=un(g),s=e.states[i]??e.states.normal,a=n.resolveValue(o.width,t),d=n.resolveValue(o.height??3,t),l=n.resolveValue(o.label,t),c=o.border??"single",u=n.resolveValue(s.fg??15,t),p=n.resolveValue(s.bg??0,t),m=n.resolveValue(s.textFg??u,t),b=s.offsetY??0,C=g.x,S=g.y+b;c==="none"?Pn(C,S,a,d,l,u,p,m,r):Rn(C,S,a,d,l,u,p,m,c,r)}y(An,"renderButton");function Pn(g,e,t,r,n,o,i,s,a){if(r===1)a.push({type:2,posX:g,posY:e,text:" ".repeat(t),fgColorCode:o,bgColorCode:i});else for(let c=0;c<r;c++)a.push({type:2,posX:g,posY:e+c,text:" ".repeat(t),fgColorCode:o,bgColorCode:i});let d=g+Math.floor((t-n.length)/2),l=e+Math.floor(r/2);a.push({type:2,posX:d,posY:l,text:n,fgColorCode:s,bgColorCode:i})}y(Pn,"renderButtonNoBorder");function Rn(g,e,t,r,n,o,i,s,a,d){let l=Mn[a];d.push({type:2,posX:g,posY:e,text:l.topLeft+l.horizontal.repeat(t-2)+l.topRight,fgColorCode:o,bgColorCode:i});for(let b=1;b<r-1;b++)d.push({type:2,posX:g,posY:e+b,text:l.vertical+" ".repeat(t-2)+l.vertical,fgColorCode:o,bgColorCode:i});d.push({type:2,posX:g,posY:e+r-1,text:l.bottomLeft+l.horizontal.repeat(t-2)+l.bottomRight,fgColorCode:o,bgColorCode:i});let c=t-2,u=r-2,p=g+1+Math.floor((c-n.length)/2),m=e+1+Math.floor(u/2);d.push({type:2,posX:p,posY:m,text:n,fgColorCode:s,bgColorCode:i})}y(Rn,"renderButtonWithBorder");function kn(g,e,t,r,n){if(g.fillRect){let[o,i,s,a,d,l,c]=g.fillRect;return{type:3,posX:e+n.resolveValue(o,r),posY:t+n.resolveValue(i,r),sizeX:n.resolveValue(s,r),sizeY:n.resolveValue(a,r),fgColorCode:ye(n.resolveValue(l,r)),bgColorCode:ye(n.resolveValue(c,r)),frame:Array(n.resolveValue(s,r)*n.resolveValue(a,r)).fill(V(d))}}if(g.text){let[o,i,s,a]=g.text;return{type:2,posX:e+n.resolveValue(o,r),posY:t+n.resolveValue(i,r),text:n.resolveValue(s,r),fgColorCode:ye(n.resolveValue(a,r)),bgColorCode:255}}if(g.setCell){let[o,i,s,a,d]=g.setCell;return{type:1,posX:e+n.resolveValue(o,r),posY:t+n.resolveValue(i,r),charCode:V(n.resolveValue(s,r)),fgColorCode:ye(n.resolveValue(a,r)),bgColorCode:ye(n.resolveValue(d,r))}}return null}y(kn,"executeRenderCommand");function pn(g,e,t,r,n,o,i){return{type:"ui",instanceId:g,macroId:e,layerId:t,x:r,y:n,params:o,tabIndex:i,isHovered:!1,isFocused:!1,isActive:!1,isDisabled:!1}}y(pn,"createUIInstance");var Yt=class Yt{update(e,t,r,n){let o=t.emitter,{resolveValue:i}=r;if(!e.emitDone){if(o.burst){let s=i(o.burst,e.params);for(let a=0;a<s&&!(o.limit&&e.particles.length>=o.limit);a++)e.particles.push(this.createParticle(e,t,r));o.once&&(e.emitDone=!0)}else if(o.rate){let s=i(o.rate,e.params);for(e.timeSinceEmit+=s;e.timeSinceEmit>=1&&!(o.limit&&e.particles.length>=o.limit);)e.particles.push(this.createParticle(e,t,r)),e.timeSinceEmit-=1}}for(let s=e.particles.length-1;s>=0;s--){let a=e.particles[s];a.x+=a.vx,a.y+=a.vy,a.lifetime-=1,a.lifetime<=0&&e.particles.splice(s,1)}}render(e,t,r){if(e.particles.length===0)return[];let{resolveValue:n}=r,o=t.emitter,i=o.viewport??o.zone,s=n(i.x,e.params),a=n(i.y,e.params),d=n(i.width,e.params),l=n(i.height,e.params),c=e.x+(typeof s=="number"?s:0),u=e.y+(typeof a=="number"?a:0),p=typeof d=="number"?d:0,m=typeof l=="number"?l:0;if(p<=0||m<=0)return[];let b=[];for(let C of e.particles){let S=Math.floor(C.x),O=Math.floor(C.y);if(S<c||S>=c+p||O<u||O>=u+m)continue;let I=C.fg;if(t.particle.fade&&C.maxLifetime>0){let v=C.lifetime/C.maxLifetime;I=this.fadeColorIndex(C.fg,v)}b.push({charCode:V(C.char),fgColorCode:I,bgColorCode:C.bg??255,posX:S,posY:O})}return[{type:12,dots:b}]}createParticle(e,t,r){let{resolveValue:n,resolveRandomValue:o}=r,i=t.emitter,s=t.particle,a=n(i.zone.x,e.params),d=n(i.zone.y,e.params),l=n(i.zone.width,e.params),c=n(i.zone.height,e.params),u=e.x+a+Math.random()*l,p=e.y+d+Math.random()*c,m=0,b=0;if("x"in s.velocity&&"y"in s.velocity)m=n(s.velocity.x,e.params),b=n(s.velocity.y,e.params);else if("angle"in s.velocity&&"speed"in s.velocity){let E=o(s.velocity.angle),U=o(s.velocity.speed,e.params),w=E*Math.PI/180;m=Math.cos(w)*U,b=Math.sin(w)*U}let C=o(s.lifetime),S=Array.isArray(s.char)?s.char[Math.floor(Math.random()*s.char.length)]:s.char,O=ge(S),I=Array.isArray(s.fg)?s.fg[Math.floor(Math.random()*s.fg.length)]:s.fg,v=typeof I=="number"?I:parseInt(I,10)||243,M=s.bg?Array.isArray(s.bg)?s.bg[Math.floor(Math.random()*s.bg.length)]:s.bg:void 0,A=M!==void 0?typeof M=="number"?M:parseInt(M,10)||255:void 0;return{x:u,y:p,vx:m,vy:b,char:O,fg:v,bg:A,lifetime:C,maxLifetime:C}}fadeColorIndex(e,t){return t<.1?255:e}};y(Yt,"ParticleHandler");var ke=Yt;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,s=t.transform.offset;s&&(e.currentOffsetX=this.resolveRandomOffset(s.x,e.params,r)*i,e.currentOffsetY=this.resolveRandomOffset(s.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),s=r.resolveValue(o,t);return i+Math.random()*(s-i)}return 0}};y(Xt,"EffectHandler");var ze=Xt;var Wt=class Wt{constructor(){h(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 a=Math.min(i,e.totalCells-e.revealedCount);if(t.pauseOn&&a>0){let d=e.cells[e.revealedCount];d&&t.pauseOn.chars.includes(d.char)&&(e.pauseRemaining=t.pauseOn.duration)}e.revealedCount+=a,e.revealedCount>=e.totalCells&&(e.finished=!0,n.push({instanceId:e.instanceId,event:"complete"}))}else{let a=Math.min(i,e.revealedCount);e.revealedCount-=a,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 s of o)i.has(s.y)||i.set(s.y,[]),i.get(s.y).push(s);for(let[s,a]of i){a.sort((l,c)=>l.x-c.x);let d=0;for(;d<a.length;){let l=a[d],c=d+1;for(;c<a.length&&a[c].x===a[c-1].x+1&&a[c].fg===l.fg&&a[c].bg===l.bg;)c++;if(c-d===1)n.push({type:1,posX:e.x+l.x,posY:e.y+s,charCode:l.char.charCodeAt(0),fgColorCode:l.fg,bgColorCode:l.bg});else{let p="";for(let m=d;m<c;m++)p+=a[m].char;n.push({type:2,posX:e.x+l.x,posY:e.y+s,text:p,fgColorCode:l.fg,bgColorCode:l.bg})}d=c}}if(t.cursor&&!e.finished&&(!t.cursor.blink||e.blinkState)&&e.revealedCount<e.cells.length){let a=e.cells[e.revealedCount];if(a){let d=t.cursor.bg??a.bg;n.push({type:1,posX:e.x+a.x,posY:e.y+a.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),s=r(o.fg??15,t),a=r(o.bg??0,t),d=i.split(`
|
|
8
|
-
`);for(let l=0;l<d.length;l++){let c=d[l];for(let u=0;u<c.length;u++)n.push({char:c[u],fg:s,bg:a,x:u,y:l,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:l,sizeY:c,data:u}=d;for(let p=0;p<c;p++)for(let m=0;m<l;m++){let b=p*l+m,C=u.get(b);C.charCode!==0&&n.push({char:String.fromCharCode(C.charCode),fg:C.fgColorCode,bg:C.bgColorCode,x:m,y:p,revealOrder:0})}break}}let a=this.spriteRegistry.getUnicolorSprite(i);if(a){let{sizeX:d,sizeY:l,data:c}=a,u=r(o.fg??15,t),p=r(o.bg??0,t);for(let m=0;m<l;m++)for(let b=0;b<d;b++){let C=m*d+b,S=c.get(C);S!==0&&n.push({char:String.fromCharCode(S),fg:u,bg:p,x:b,y:m,revealOrder:0})}}break}case"cells":{for(let i of o.cells)n.push({char:ge(i.char),fg:i.fg,bg:i.bg,x:i.x,y:i.y,revealOrder:0});break}case"fill":{let i=ge(o.char),s=r(o.fg,t),a=r(o.bg,t),d=r(o.width,t),l=r(o.height,t);for(let c=0;c<l;c++)for(let u=0;u<d;u++)n.push({char:i,fg:s,bg:a,x:u,y:c,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 a of e)a.x>n&&(n=a.x),a.y>o&&(o=a.y);let i=n+1,s=o+1;switch(t){case"typewriter":for(let a of e)a.revealOrder=a.y*i+a.x;break;case"typewriter-rev":for(let a of e)a.revealOrder=(s-1-a.y)*i+(i-1-a.x);break;case"ltr":for(let a of e)a.revealOrder=a.x*s+a.y;break;case"rtl":for(let a of e)a.revealOrder=(i-1-a.x)*s+a.y;break;case"ttb":for(let a of e)a.revealOrder=a.y;break;case"btt":for(let a of e)a.revealOrder=s-1-a.y;break;case"random":{let a=e.map((d,l)=>l);for(let d=a.length-1;d>0;d--){let l=Math.floor(Math.random()*(d+1));[a[d],a[l]]=[a[l],a[d]]}for(let d=0;d<e.length;d++)e[d].revealOrder=a[d];break}case"center-out":{let a=(i-1)/2,d=(s-1)/2;for(let l of e)l.revealOrder=Math.abs(l.x-a)+Math.abs(l.y-d);break}case"spiral":{let a=(i-1)/2,d=(s-1)/2,l=Math.max(a,d);for(let c of e){let u=Math.abs(c.x-a),p=Math.abs(c.y-d),m=Math.max(u,p);c.revealOrder=l-m+(c.y*i+c.x)*.001}break}}e.sort((a,d)=>a.revealOrder-d.revealOrder);for(let a=0;a<e.length;a++)e[a].revealOrder=a}};y(Wt,"RevealHandler");var Be=Wt;var Gt=class Gt{update(e,t,r,n){let{resolveValue:o}=r,i=e.params;e.currentTick++;let s=i.point;if(s&&typeof s.x=="number"&&typeof s.y=="number"){e.points.push({x:s.x,y:s.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 a=i.points;if(Array.isArray(a)){e.points=a.map(l=>({x:l.x,y:l.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 s=n(t.char,o),a=n(t.fg,o)??15,d=n(t.bg,o)??255,l=t.closed??!1,c=t.fadeOut??!1,u=i.map(m=>({x:e.x+m.x,y:e.y+m.y}));return l&&u.length>=2&&u.push({...u[0]}),c&&i.length>=2?this.renderFadedLine(e,t,r,u,s,a,d):[{type:25,charCode:V(s),fgColorCode:a,bgColorCode:d,points:u.map(m=>({x:m.x&255,y:m.y&255}))}]}renderFadedLine(e,t,r,n,o,i,s){let a=e.params,d=t.fadeLength??n.length,l=[],c=n.length,u=Math.max(0,c-d);if(u>0){let m=n.slice(0,u+1);m.length>=2&&l.push({type:25,charCode:V(o),fgColorCode:i,bgColorCode:s,points:m.map(b=>({x:b.x&255,y:b.y&255}))})}let p=n.slice(u);if(p.length>=2){let m=Math.max(0,i-8);l.push({type:25,charCode:V(o),fgColorCode:m,bgColorCode:s,points:p.map(b=>({x:b.x&255,y:b.y&255}))})}return l}};y(Gt,"LineHandler");var Te=Gt;var Bn=!1;function ce(...g){Bn&&console.log("[MacroEngine]",...g)}y(ce,"macroLog");var $t=class $t{constructor(){h(this,"templates",new Map);h(this,"instances",new Map);h(this,"spriteRegistry",null);h(this,"playSound",null);h(this,"focusedInstanceId",null);h(this,"focusableInstances",[]);h(this,"mouseX",0);h(this,"mouseY",0);h(this,"mouseDown",!1);h(this,"particleHandler",new ke);h(this,"effectHandler",new ze);h(this,"revealHandler",new Be);h(this,"lineHandler",new Te);h(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){ce(`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(ce(`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){ce(`createInstance: FAILED - template ${e.macroId} not found`);return}ce(`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=pn(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,(a,d)=>this.resolveValue(a,d)),i=o.length,s=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:s==="hide"?i:0,totalCells:i,delayRemaining:n.delay??0,pauseRemaining:0,finished:!1,direction:s,speed:n.speed??1,blinkState:!0,blinkTimer:0};break}case"line":{let n=[],o=e.params.points;if(Array.isArray(o)){for(let s of o)n.push({x:s.x,y:s.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&&ce(`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":_t.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;ce(`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 _t.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($t,"MacroEngine");var Fe=$t;var Zt=class Zt{constructor(){h(this,"axes",new Map);h(this,"buttons",new Map);h(this,"touchZones",new Map);h(this,"axisNameToId",new Map);h(this,"buttonNameToId",new Map);h(this,"touchZoneNameToId",new Map);h(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 a=this.axisNameToId.get(t);throw new Error(`Axis name "${t}" is already defined with bindingId ${a}`)}let s={bindingId:e,name:t,min:n,max:o,defaultValue:i,sources:r};this.axes.set(e,s),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 a=this.touchZoneNameToId.get(t);throw new Error(`Touch zone name "${t}" is already defined with zoneId ${a}`)}if(o<=0||i<=0)throw new Error(`Touch zone dimensions must be positive, got ${o}x${i}`);let s={zoneId:e,name:t,x:r,y:n,width:o,height:i};this.touchZones.set(e,s),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 a=t.get(i.sourceId)??0,d=i.deadzone??0;Math.abs(a)<d?a=0:a=(a>0?1:-1)*((Math.abs(a)-d)/(1-d));let l=i.scale??1;a*=l;let c=i.sensitivity??1;a*=c,i.invert&&(a=-a),n+=a}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})
|
|
7
|
+
Orders breakdown: ${this.getOrdersBreakdown()}`),this.orders=this.orders.slice(0,_t)),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"),h(Y,"rasterizer",new ae);var ce=Y;var Ht=class Ht{constructor(){h(this,"macros",new Map);h(this,"macroNameToId",new Map);h(this,"nextMacroId",0);h(this,"instances",new Map);h(this,"instanceNameToId",new Map);h(this,"nextInstanceId",0);h(this,"layerNameToId",new Map);h(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(Ht,"MacroRegistry");var Re=Ht;function V(g){return typeof g=="number"?g:g.charCodeAt(0)}y(V,"toCharCode");function ye(g){return typeof g=="string"?g.charAt(0):String.fromCharCode(g)}y(ye,"toCharString");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"}},Nt={update(g,e,t,r){let n,o;e.subtype==="button"&&e.button?(n=t.resolveValue(e.button.width,g.params),o=t.resolveValue(e.button.height??3,g.params)):(n=t.resolveValue(g.params.width??1,g.params),o=t.resolveValue(g.params.height??1,g.params));let i=g.isHovered;g.isHovered=Bn(t.mouseX,t.mouseY,g.x,g.y,n,o);let s=g.isActive;g.isActive=g.isHovered&&t.mouseDown,s&&!g.isActive&&g.isHovered&&(r.push({instanceId:g.instanceId,event:"click"}),e.subtype==="button"&&e.button?.soundRelease!==void 0&&t.playSound?.(e.button.soundRelease)),e.subtype==="button"&&e.button&&(!i&&g.isHovered&&e.button.soundHover!==void 0&&t.playSound?.(e.button.soundHover),!s&&g.isActive&&e.button.soundClick!==void 0&&t.playSound?.(e.button.soundClick))},render(g,e,t){let r=gn(g),n=e.states[r]??e.states.normal,o={...g.params,...n},i=[];if(e.subtype==="button"&&e.button)Tn(g,e,o,i,t);else if(e.base)for(let s of e.base){let a=Dn(s,g.x,g.y,o,t);a&&i.push(a)}return i}};function Bn(g,e,t,r,n,o){return g>=t&&g<t+n&&e>=r&&e<r+o}y(Bn,"isPointInRect");function gn(g){return g.isDisabled?"disabled":g.isActive?"active":g.isHovered?"hover":g.isFocused?"focused":"normal"}y(gn,"getUIState");function Ce(g){if(typeof g=="number")return Math.max(0,Math.min(255,Math.floor(g)));if(typeof g=="string"){let e=parseInt(g,10);if(!isNaN(e))return Math.max(0,Math.min(255,Math.floor(e)))}return 243}y(Ce,"toColorIndex");function Tn(g,e,t,r,n){let o=e.button,i=gn(g),s=e.states[i]??e.states.normal,a=n.resolveValue(o.width,t),d=n.resolveValue(o.height??3,t),l=n.resolveValue(o.label,t),c=o.border??"single",p=n.resolveValue(s.fg??15,t),u=n.resolveValue(s.bg??0,t),m=n.resolveValue(s.textFg??p,t),b=s.offsetY??0,C=g.x,S=g.y+b;c==="none"?Fn(C,S,a,d,l,p,u,m,r):Ln(C,S,a,d,l,p,u,m,c,r)}y(Tn,"renderButton");function Fn(g,e,t,r,n,o,i,s,a){if(r===1)a.push({type:2,posX:g,posY:e,text:" ".repeat(t),fgColorCode:o,bgColorCode:i});else for(let c=0;c<r;c++)a.push({type:2,posX:g,posY:e+c,text:" ".repeat(t),fgColorCode:o,bgColorCode:i});let d=g+Math.floor((t-n.length)/2),l=e+Math.floor(r/2);a.push({type:2,posX:d,posY:l,text:n,fgColorCode:s,bgColorCode:i})}y(Fn,"renderButtonNoBorder");function Ln(g,e,t,r,n,o,i,s,a,d){let l=kn[a];d.push({type:2,posX:g,posY:e,text:l.topLeft+l.horizontal.repeat(t-2)+l.topRight,fgColorCode:o,bgColorCode:i});for(let b=1;b<r-1;b++)d.push({type:2,posX:g,posY:e+b,text:l.vertical+" ".repeat(t-2)+l.vertical,fgColorCode:o,bgColorCode:i});d.push({type:2,posX:g,posY:e+r-1,text:l.bottomLeft+l.horizontal.repeat(t-2)+l.bottomRight,fgColorCode:o,bgColorCode:i});let c=t-2,p=r-2,u=g+1+Math.floor((c-n.length)/2),m=e+1+Math.floor(p/2);d.push({type:2,posX:u,posY:m,text:n,fgColorCode:s,bgColorCode:i})}y(Ln,"renderButtonWithBorder");function Dn(g,e,t,r,n){if(g.fillRect){let[o,i,s,a,d,l,c]=g.fillRect;return{type:3,posX:e+n.resolveValue(o,r),posY:t+n.resolveValue(i,r),sizeX:n.resolveValue(s,r),sizeY:n.resolveValue(a,r),fgColorCode:Ce(n.resolveValue(l,r)),bgColorCode:Ce(n.resolveValue(c,r)),frame:Array(n.resolveValue(s,r)*n.resolveValue(a,r)).fill(V(d))}}if(g.text){let[o,i,s,a]=g.text;return{type:2,posX:e+n.resolveValue(o,r),posY:t+n.resolveValue(i,r),text:n.resolveValue(s,r),fgColorCode:Ce(n.resolveValue(a,r)),bgColorCode:255}}if(g.setCell){let[o,i,s,a,d]=g.setCell;return{type:1,posX:e+n.resolveValue(o,r),posY:t+n.resolveValue(i,r),charCode:V(n.resolveValue(s,r)),fgColorCode:Ce(n.resolveValue(a,r)),bgColorCode:Ce(n.resolveValue(d,r))}}return null}y(Dn,"executeRenderCommand");function yn(g,e,t,r,n,o,i){return{type:"ui",instanceId:g,macroId:e,layerId:t,x:r,y:n,params:o,tabIndex:i,isHovered:!1,isFocused:!1,isActive:!1,isDisabled:!1}}y(yn,"createUIInstance");var Xt=class Xt{update(e,t,r,n){let o=t.emitter,{resolveValue:i}=r;if(!e.emitDone){if(o.burst){let s=i(o.burst,e.params);for(let a=0;a<s&&!(o.limit&&e.particles.length>=o.limit);a++)e.particles.push(this.createParticle(e,t,r));o.once&&(e.emitDone=!0)}else if(o.rate){let s=i(o.rate,e.params);for(e.timeSinceEmit+=s;e.timeSinceEmit>=1&&!(o.limit&&e.particles.length>=o.limit);)e.particles.push(this.createParticle(e,t,r)),e.timeSinceEmit-=1}}for(let s=e.particles.length-1;s>=0;s--){let a=e.particles[s];a.x+=a.vx,a.y+=a.vy,a.lifetime-=1,a.lifetime<=0&&e.particles.splice(s,1)}}render(e,t,r){if(e.particles.length===0)return[];let{resolveValue:n}=r,o=t.emitter,i=o.viewport??o.zone,s=n(i.x,e.params),a=n(i.y,e.params),d=n(i.width,e.params),l=n(i.height,e.params),c=e.x+(typeof s=="number"?s:0),p=e.y+(typeof a=="number"?a:0),u=typeof d=="number"?d:0,m=typeof l=="number"?l:0;if(u<=0||m<=0)return[];let b=[];for(let C of e.particles){let S=Math.floor(C.x),I=Math.floor(C.y);if(S<c||S>=c+u||I<p||I>=p+m)continue;let O=C.fg;if(t.particle.fade&&C.maxLifetime>0){let v=C.lifetime/C.maxLifetime;O=this.fadeColorIndex(C.fg,v)}b.push({charCode:V(C.char),fgColorCode:O,bgColorCode:C.bg??255,posX:S,posY:I})}return[{type:12,dots:b}]}createParticle(e,t,r){let{resolveValue:n,resolveRandomValue:o}=r,i=t.emitter,s=t.particle,a=n(i.zone.x,e.params),d=n(i.zone.y,e.params),l=n(i.zone.width,e.params),c=n(i.zone.height,e.params),p=e.x+a+Math.random()*l,u=e.y+d+Math.random()*c,m=0,b=0;if("x"in s.velocity&&"y"in s.velocity)m=n(s.velocity.x,e.params),b=n(s.velocity.y,e.params);else if("angle"in s.velocity&&"speed"in s.velocity){let E=o(s.velocity.angle),U=o(s.velocity.speed,e.params),M=E*Math.PI/180;m=Math.cos(M)*U,b=Math.sin(M)*U}let C=o(s.lifetime),S=Array.isArray(s.char)?s.char[Math.floor(Math.random()*s.char.length)]:s.char,I=ye(S),O=Array.isArray(s.fg)?s.fg[Math.floor(Math.random()*s.fg.length)]:s.fg,v=typeof O=="number"?O:parseInt(O,10)||243,w=s.bg?Array.isArray(s.bg)?s.bg[Math.floor(Math.random()*s.bg.length)]:s.bg:void 0,A=w!==void 0?typeof w=="number"?w:parseInt(w,10)||255:void 0;return{x:p,y:u,vx:m,vy:b,char:I,fg:v,bg:A,lifetime:C,maxLifetime:C}}fadeColorIndex(e,t){return t<.1?255:e}};y(Xt,"ParticleHandler");var ze=Xt;var Wt=class Wt{update(e,t,r,n){e.elapsed+=1;let o=Math.min(1,e.elapsed/e.duration),i=t.transform.decay?1-o:1,s=t.transform.offset;s&&(e.currentOffsetX=this.resolveRandomOffset(s.x,e.params,r)*i,e.currentOffsetY=this.resolveRandomOffset(s.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),s=r.resolveValue(o,t);return i+Math.random()*(s-i)}return 0}};y(Wt,"EffectHandler");var ke=Wt;var Gt=class Gt{constructor(){h(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 a=Math.min(i,e.totalCells-e.revealedCount);if(t.pauseOn&&a>0){let d=e.cells[e.revealedCount];d&&t.pauseOn.chars.includes(d.char)&&(e.pauseRemaining=t.pauseOn.duration)}e.revealedCount+=a,e.revealedCount>=e.totalCells&&(e.finished=!0,n.push({instanceId:e.instanceId,event:"complete"}))}else{let a=Math.min(i,e.revealedCount);e.revealedCount-=a,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 s of o)i.has(s.y)||i.set(s.y,[]),i.get(s.y).push(s);for(let[s,a]of i){a.sort((l,c)=>l.x-c.x);let d=0;for(;d<a.length;){let l=a[d],c=d+1;for(;c<a.length&&a[c].x===a[c-1].x+1&&a[c].fg===l.fg&&a[c].bg===l.bg;)c++;if(c-d===1)n.push({type:1,posX:e.x+l.x,posY:e.y+s,charCode:l.char.charCodeAt(0),fgColorCode:l.fg,bgColorCode:l.bg});else{let u="";for(let m=d;m<c;m++)u+=a[m].char;n.push({type:2,posX:e.x+l.x,posY:e.y+s,text:u,fgColorCode:l.fg,bgColorCode:l.bg})}d=c}}if(t.cursor&&!e.finished&&(!t.cursor.blink||e.blinkState)&&e.revealedCount<e.cells.length){let a=e.cells[e.revealedCount];if(a){let d=t.cursor.bg??a.bg;n.push({type:1,posX:e.x+a.x,posY:e.y+a.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),s=r(o.fg??15,t),a=r(o.bg??0,t),d=i.split(`
|
|
8
|
+
`);for(let l=0;l<d.length;l++){let c=d[l];for(let p=0;p<c.length;p++)n.push({char:c[p],fg:s,bg:a,x:p,y:l,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:l,sizeY:c,data:p}=d;for(let u=0;u<c;u++)for(let m=0;m<l;m++){let b=u*l+m,C=p.get(b);C.charCode!==0&&n.push({char:String.fromCharCode(C.charCode),fg:C.fgColorCode,bg:C.bgColorCode,x:m,y:u,revealOrder:0})}break}}let a=this.spriteRegistry.getUnicolorSprite(i);if(a){let{sizeX:d,sizeY:l,data:c}=a,p=r(o.fg??15,t),u=r(o.bg??0,t);for(let m=0;m<l;m++)for(let b=0;b<d;b++){let C=m*d+b,S=c.get(C);S!==0&&n.push({char:String.fromCharCode(S),fg:p,bg:u,x:b,y:m,revealOrder:0})}}break}case"cells":{for(let i of o.cells)n.push({char:ye(i.char),fg:i.fg,bg:i.bg,x:i.x,y:i.y,revealOrder:0});break}case"fill":{let i=ye(o.char),s=r(o.fg,t),a=r(o.bg,t),d=r(o.width,t),l=r(o.height,t);for(let c=0;c<l;c++)for(let p=0;p<d;p++)n.push({char:i,fg:s,bg:a,x:p,y:c,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 a of e)a.x>n&&(n=a.x),a.y>o&&(o=a.y);let i=n+1,s=o+1;switch(t){case"typewriter":for(let a of e)a.revealOrder=a.y*i+a.x;break;case"typewriter-rev":for(let a of e)a.revealOrder=(s-1-a.y)*i+(i-1-a.x);break;case"ltr":for(let a of e)a.revealOrder=a.x*s+a.y;break;case"rtl":for(let a of e)a.revealOrder=(i-1-a.x)*s+a.y;break;case"ttb":for(let a of e)a.revealOrder=a.y;break;case"btt":for(let a of e)a.revealOrder=s-1-a.y;break;case"random":{let a=e.map((d,l)=>l);for(let d=a.length-1;d>0;d--){let l=Math.floor(Math.random()*(d+1));[a[d],a[l]]=[a[l],a[d]]}for(let d=0;d<e.length;d++)e[d].revealOrder=a[d];break}case"center-out":{let a=(i-1)/2,d=(s-1)/2;for(let l of e)l.revealOrder=Math.abs(l.x-a)+Math.abs(l.y-d);break}case"spiral":{let a=(i-1)/2,d=(s-1)/2,l=Math.max(a,d);for(let c of e){let p=Math.abs(c.x-a),u=Math.abs(c.y-d),m=Math.max(p,u);c.revealOrder=l-m+(c.y*i+c.x)*.001}break}}e.sort((a,d)=>a.revealOrder-d.revealOrder);for(let a=0;a<e.length;a++)e[a].revealOrder=a}};y(Gt,"RevealHandler");var Be=Gt;var $t=class $t{update(e,t,r,n){let{resolveValue:o}=r,i=e.params;e.currentTick++;let s=i.point;if(s&&typeof s.x=="number"&&typeof s.y=="number"){e.points.push({x:s.x,y:s.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 a=i.points;if(Array.isArray(a)){e.points=a.map(l=>({x:l.x,y:l.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 s=n(t.char,o),a=n(t.fg,o)??15,d=n(t.bg,o)??255,l=t.closed??!1,c=t.fadeOut??!1,p=i.map(m=>({x:e.x+m.x,y:e.y+m.y}));return l&&p.length>=2&&p.push({...p[0]}),c&&i.length>=2?this.renderFadedLine(e,t,r,p,s,a,d):[{type:25,charCode:V(s),fgColorCode:a,bgColorCode:d,points:p.map(m=>({x:m.x&255,y:m.y&255}))}]}renderFadedLine(e,t,r,n,o,i,s){let a=e.params,d=t.fadeLength??n.length,l=[],c=n.length,p=Math.max(0,c-d);if(p>0){let m=n.slice(0,p+1);m.length>=2&&l.push({type:25,charCode:V(o),fgColorCode:i,bgColorCode:s,points:m.map(b=>({x:b.x&255,y:b.y&255}))})}let u=n.slice(p);if(u.length>=2){let m=Math.max(0,i-8);l.push({type:25,charCode:V(o),fgColorCode:m,bgColorCode:s,points:u.map(b=>({x:b.x&255,y:b.y&255}))})}return l}};y($t,"LineHandler");var Te=$t;var _n=!1;function ue(...g){_n&&console.log("[MacroEngine]",...g)}y(ue,"macroLog");var Zt=class Zt{constructor(){h(this,"templates",new Map);h(this,"instances",new Map);h(this,"spriteRegistry",null);h(this,"playSound",null);h(this,"focusedInstanceId",null);h(this,"focusableInstances",[]);h(this,"mouseX",0);h(this,"mouseY",0);h(this,"mouseDown",!1);h(this,"particleHandler",new ze);h(this,"effectHandler",new ke);h(this,"revealHandler",new Be);h(this,"lineHandler",new Te);h(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){ue(`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(ue(`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){ue(`createInstance: FAILED - template ${e.macroId} not found`);return}ue(`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=yn(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,(a,d)=>this.resolveValue(a,d)),i=o.length,s=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:s==="hide"?i:0,totalCells:i,delayRemaining:n.delay??0,pauseRemaining:0,finished:!1,direction:s,speed:n.speed??1,blinkState:!0,blinkTimer:0};break}case"line":{let n=[],o=e.params.points;if(Array.isArray(o)){for(let s of o)n.push({x:s.x,y:s.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&&ue(`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":Nt.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;ue(`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 Nt.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(Zt,"MacroEngine");var Fe=Zt;var jt=class jt{constructor(){h(this,"axes",new Map);h(this,"buttons",new Map);h(this,"touchZones",new Map);h(this,"axisNameToId",new Map);h(this,"buttonNameToId",new Map);h(this,"touchZoneNameToId",new Map);h(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 a=this.axisNameToId.get(t);throw new Error(`Axis name "${t}" is already defined with bindingId ${a}`)}let s={bindingId:e,name:t,min:n,max:o,defaultValue:i,sources:r};this.axes.set(e,s),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 a=this.touchZoneNameToId.get(t);throw new Error(`Touch zone name "${t}" is already defined with zoneId ${a}`)}if(o<=0||i<=0)throw new Error(`Touch zone dimensions must be positive, got ${o}x${i}`);let s={zoneId:e,name:t,x:r,y:n,width:o,height:i};this.touchZones.set(e,s),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 a=t.get(i.sourceId)??0,d=i.deadzone??0;Math.abs(a)<d?a=0:a=(a>0?1:-1)*((Math.abs(a)-d)/(1-d));let l=i.scale??1;a*=l;let c=i.sensitivity??1;a*=c,i.invert&&(a=-a),n+=a}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})
|
|
9
9
|
`;return e+=`Axes (${this.axes.size}):
|
|
10
10
|
`,this.axes.forEach(t=>{e+=` [${t.bindingId}] ${t.name}: `,e+=`${t.min} to ${t.max} (default: ${t.defaultValue})
|
|
11
11
|
`}),e+=`Buttons (${this.buttons.size}):
|
|
12
12
|
`,this.buttons.forEach(t=>{e+=` [${t.bindingId}] ${t.name}: `,e+=`(default: ${t.defaultValue})
|
|
13
13
|
`}),e+=`Touch Zones (${this.touchZones.size}):
|
|
14
14
|
`,this.touchZones.forEach(t=>{e+=` [${t.zoneId}] ${t.name}: `,e+=`(${t.x}, ${t.y}) ${t.width}x${t.height}
|
|
15
|
-
`}),e}};y(Zt,"InputBindingRegistry");var Le=Zt;function mn(g=0n){return{tick:g,axes:new Map,buttons:new Map,displayId:0,mouseX:0,mouseY:0,mouseOverDisplay:!1,textInputs:[],macroEvents:[],displayViewports:[],touchPositions:[]}}y(mn,"createEmptyCompressedInputPacket");function hn(g){return g/127}y(hn,"decodeInt8ToAxis");function bn(g){return g===0?0:Math.ceil(g/8)}y(bn,"getButtonByteCount");B();function gn(g,e){let t=e.getAllAxes().length,r=e.getAllButtons().length,n=bn(r),o=8+t+n+4;if(g.length<o)throw new Error(`Invalid compressed input packet: expected at least ${o} bytes (${t} axes + ${r} buttons), got ${g.length}`);let i=new DataView(g.buffer,g.byteOffset,g.byteLength),s=0,a=mn();a.tick=i.getBigUint64(s,!0),s+=8;for(let l=0;l<t;l++){let c=g[s],u=c>127?c-256:c,p=hn(u);a.axes.set(l,p),s+=1}for(let l=0;l<n;l++){let c=g[s];for(let u=0;u<8;u++){let p=l*8+u;if(p<r){let m=(c&1<<u)!==0;a.buttons.set(p,m)}}s+=1}a.displayId=g[s],s+=1,a.mouseX=g[s],s+=1,a.mouseY=g[s],s+=1;let d=g[s];if(a.mouseOverDisplay=(d&1)!==0,s+=1,s<g.length){let l=g[s];s+=1;let c=new TextDecoder;a.textInputs=[];for(let u=0;u<l&&s<g.length;u++){let p=g[s];if(s+=1,s+p<=g.length){let m=g.slice(s,s+p),b=c.decode(m);a.textInputs.push(b),s+=p}}}if(s<g.length){let l=g[s];s+=1;let c=new ie,u=[],p=f.from(g);for(let m=0;m<l&&s<g.length;m++){let b=c.decode(p,s);u.push(b.event),s+=b.bytesRead}a.macroEvents=u}if(s<g.length){let l=g[s];s+=1;for(let c=0;c<l&&s+5<=g.length;c++){let u=g[s];s+=1;let p=i.getUint16(s,!1);s+=2;let m=i.getUint16(s,!1);s+=2,a.displayViewports.push({displayId:u,pixelWidth:p,pixelHeight:m})}}if(s<g.length){let l=Math.min(g[s],10);s+=1;for(let c=0;c<l&&s+4<=g.length;c++){let u=g[s]&15;s+=1;let p=g[s];s+=1;let m=g[s];s+=1;let C=(g[s]&1)!==0;s+=1,a.touchPositions.push({id:u,x:p,y:m,over:C})}}return a}y(gn,"decodeCompressedInput");var R=require("@utsp/types");var jt=class jt{constructor(e,t){h(this,"enabled",!1);h(this,"currentStats",null);h(this,"_userId");h(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(jt,"UserStats");var De=jt;var Jt=class Jt{constructor(e,t,r){this.id=e;this.name=t;h(this,"displays",[]);h(this,"layers",[]);h(this,"spriteRegistry");h(this,"mode");h(this,"axes",new Map);h(this,"buttons",new Map);h(this,"textInputs",[]);h(this,"mouseX",0);h(this,"mouseY",0);h(this,"mouseOver",!1);h(this,"mouseDisplayId",0);h(this,"touchPositions",new Map);h(this,"activeTouchId",null);h(this,"inputBindings",new Le);h(this,"stats");h(this,"soundCommands",[]);h(this,"nextSoundInstanceId",1);h(this,"audioConfigCommands",[]);h(this,"lastListenerX",-1);h(this,"lastListenerY",-1);h(this,"pendingSendSounds",!1);h(this,"audioProcessor");h(this,"loadedSounds",new Map);h(this,"soundLoadErrors",new Map);h(this,"playingSounds",new Map);h(this,"mobileVibrationCommands",[]);h(this,"mobileVibrationProcessor");h(this,"gamepadVibrationCommands",[]);h(this,"gamepadVibrationProcessor");h(this,"macroRegistry",new Re);h(this,"macroEngine",new Fe);h(this,"macroEventHandlers",new Map);h(this,"postProcessCommands",[]);h(this,"currentPostProcessConfig",null);h(this,"bridgeMessages",[]);h(this,"totalBytesSent",0);h(this,"totalBytesReceived",0);h(this,"bytesSentPerTick",[]);h(this,"bytesReceivedPerTick",[]);h(this,"bytesTickIndex",0);h(this,"bytesTickRate",20);h(this,"currentTickBytesSent",0);h(this,"currentTickBytesReceived",0);h(this,"availableViewports",new Map);h(this,"data");h(this,"currentScalingModes",new Map);h(this,"currentCellSizes",new Map);h(this,"currentGridConfigs",new Map);h(this,"currentPaletteSlotIds",new Map);this.mode=r,this.stats=new De(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,s=o.y+n;return{displayId:t,localX:r,localY:n,worldX:i,worldY:s}}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,s=r.getOrigin(),a=s.x+o,d=s.y+i;return{displayId:n,localX:o,localY:i,worldX:a,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 Pe(t.id,t.sizeX,t.sizeY);this.displays.length<=t.id;)this.displays.push(null);this.displays[t.id]=r}r.setOrigin(new R.Vector2(t.originX,t.originY)),r.setSize(new R.Vector2(t.sizeX,t.sizeY))}}updateLayersFromPacket(e){for(let t of e){let r=this.findLayerById(t.id);r||(r=new le(new R.Vector2(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 R.Vector2(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:s})=>{this.defineAxisBinding(t,r,n??[],o,i,s)})}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=gn(e,this.inputBindings),r=this.inputBindings.getAllAxes(),n=this.inputBindings.getAllButtons(),o=r.sort((s,a)=>s.bindingId-a.bindingId),i=n.sort((s,a)=>s.bindingId-a.bindingId);for(let[s,a]of t.axes)if(s<o.length){let d=o[s];this.setAxis(d.name,a)}for(let[s,a]of t.buttons)if(s<i.length){let d=i[s];this.setButton(d.name,a)}this.mouseX=t.mouseX,this.mouseY=t.mouseY,this.mouseOver=t.mouseOverDisplay,this.mouseDisplayId=t.displayId;for(let s of t.touchPositions)this.setTouchPosition(s.id,s.x,s.y,s.over);for(let s of t.displayViewports)this.setDisplayViewport(s.displayId,s.pixelWidth,s.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}=(on(),G(nn)),{MobileVibrateFlags:r,GamepadVibrateFlags:n}=(tn(),G(en));for(let o of e)switch(o.type){case t.MobileVibrate:{if(!this.mobileVibrationProcessor)break;let i=o,s=i.pattern;i.flags&r.HasIntensity&&i.intensity!==void 0&&(s=s.map(a=>Math.round(a*i.intensity))),this.mobileVibrationProcessor.vibrate(s);break}case t.MobileCancel:{if(!this.mobileVibrationProcessor)break;this.mobileVibrationProcessor.cancel();break}case t.GamepadVibrate:{if(!this.gamepadVibrationProcessor)break;let i=o,s={duration:i.duration,strongMagnitude:i.strongMagnitude/255,weakMagnitude:i.weakMagnitude/255,startDelay:i.startDelay};if(i.flags&n.AllGamepads)for(let a=0;a<4;a++)this.gamepadVibrationProcessor.vibrate(a,s);else this.gamepadVibrationProcessor.vibrate(i.gamepadIndex,s);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}=(qr(),G(Jr)),{PlaySoundFlags:n}=($r(),G(Gr));for(let o of e)switch(o.type){case t.PlaySound:case t.PlayGlobalSound:{let i=o,s=i.volume!==void 0?i.volume/255:void 0,a=i.pitch!==void 0?.25*Math.pow(2,i.pitch/64):void 0,d=i.fadeIn!==void 0?i.fadeIn/10:void 0,l=(i.flags&n.Loop)!==0,c=i.posX!==void 0&&i.posY!==void 0?{x:i.posX,y:i.posY}:void 0;this.audioProcessor.play(i.soundId,{volume:s,pitch:a,loop:l,fadeIn:d,position:c,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,s=i.duration/10;i.targetType===r.All?this.audioProcessor.fadeOut("all",s):this.audioProcessor.fadeOut(i.target,s);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.getName();t&&this.macroRegistry.setLayerMapping(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,s=t+o.y;this.macroEngine.updateMouse(i,s,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 s=i.map(a=>{let d={...a};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,s)}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??R.POST_PROCESS_DEFAULTS.scanlines.opacity,pattern:r?.pattern??R.POST_PROCESS_DEFAULTS.scanlines.pattern,color:r?.color??R.POST_PROCESS_DEFAULTS.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??R.POST_PROCESS_DEFAULTS.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??R.POST_PROCESS_DEFAULTS.ambientEffect.blur,scale:r?.scale??R.POST_PROCESS_DEFAULTS.ambientEffect.scale}}):this.setPostProcess(e,{...this.currentPostProcessConfig,ambientEffect:{enabled:!0,blur:t.blur??r?.blur??R.POST_PROCESS_DEFAULTS.ambientEffect.blur,scale:t.scale??r?.scale??R.POST_PROCESS_DEFAULTS.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??R.POST_PROCESS_DEFAULTS.ambientEffect.scale}})}setAmbientEffectScale(e,t){let r=this.currentPostProcessConfig?.ambientEffect;this.setPostProcess(e,{...this.currentPostProcessConfig,ambientEffect:{enabled:r?.enabled??!0,blur:r?.blur??R.POST_PROCESS_DEFAULTS.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??R.POST_PROCESS_DEFAULTS.ambientEffect.blur,scale:e.scale??R.POST_PROCESS_DEFAULTS.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:R.GRID_DEFAULTS.color,lineWidth:R.GRID_DEFAULTS.lineWidth}:r={enabled:t.enabled,color:t.color??R.GRID_DEFAULTS.color,lineWidth:t.lineWidth??R.GRID_DEFAULTS.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}getDebugInfo(){let e=Array.from(this.availableViewports.entries()).map(([t,r])=>({displayId:t,pixelWidth:r.pixelWidth,pixelHeight:r.pixelHeight}));return{id:this.id,name:this.name,bytesSentTotal:this.totalBytesSent,bytesSentTick:this.currentTickBytesSent,availableViewports:e,layers:this.layers.map(t=>t.getDebugInfo()),displays:this.displays.map(t=>t.getDebugInfo())}}};y(Jt,"User");var Ve=Jt;var qt=class qt{constructor(){h(this,"enabled",!1);h(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 displayCompositeLayerIds(){return this.currentStats?.displayCompositeLayerIds??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,displayCompositeLayerIds:new Map})}recordDisplayComposite(e,t){!this.enabled||!this.currentStats||(this.currentStats.displayCompositeLayerIds||(this.currentStats.displayCompositeLayerIds=new Map),this.currentStats.displayCompositeLayerIds.set(e,[...t]))}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 He=qt;function Tn(g){return Math.sqrt(g)*16}y(Tn,"getAtlasColumns");function Fn(g){return g*256-1}y(Fn,"getMaxCharCode");var Kt=class Kt{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(Kt,"WebFont");var ue=Kt,Qt=class Qt{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(Qt,"BitmapFont");var _e=Qt,er=class er{constructor(e,t){this.fontId=e;this.config=t;h(this,"atlasColumns");h(this,"maxCharCode");this.atlasColumns=Tn(t.atlasBlocks),this.maxCharCode=Fn(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,s=(r+1)/this.atlasColumns;return{u1:n,v1:o,u2:i,v2:s}}isValidCharCode(e){return e>=0&&e<=this.maxCharCode}};y(er,"ImageFont");var Ce=er;var tr=class tr{constructor(){h(this,"fonts",new Map)}loadFont(e,t){if(this.fonts.has(e))throw new Error(`WebFont with ID ${e} already exists`);let r=new ue(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(tr,"WebFontRegistry");var Ne=tr;var rr=class rr{constructor(){h(this,"fonts",new Map)}loadFont(e,t){if(this.fonts.has(e))throw new Error(`BitmapFont with ID ${e} already exists`);let r=new _e(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(rr,"BitmapFontRegistry");var Ye=rr;var nr=class nr{constructor(){h(this,"fonts",new Map);h(this,"nameToId",new Map);h(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 Ce(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 Ce(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(nr,"ImageFontRegistry");var Xe=nr;var or=class or{constructor(){h(this,"sounds",new Map);h(this,"nameToId",new Map);h(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),s={soundId:i,name:e,loadType:"external",format:t,url:r,size:n,checksum:o};return this.sounds.set(i,s),this.nameToId.set(e,i),i}registerExternalWithId(e,t,r,n,o,i){this.validateId(e),this.checkIdAvailable(e,t);let s={soundId:e,name:t,loadType:"external",format:r,url:n,size:o,checksum:i};this.sounds.set(e,s),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(or,"SoundRegistry");var We=or;var ir=class ir{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(ir,"AudioOrderCollector");var Ge=ir;var sr=class sr{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(sr,"VibrationOrderCollector");var $e=sr;var F=require("@utsp/types");var ar=class ar{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??F.POST_PROCESS_DEFAULTS.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??F.POST_PROCESS_DEFAULTS.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??F.POST_PROCESS_DEFAULTS.ambientEffect.blur,scale:o.scale??F.POST_PROCESS_DEFAULTS.ambientEffect.scale,opacity:o.opacity??F.POST_PROCESS_DEFAULTS.ambientEffect.opacity}}return n.flags=r,n}createSetScanlinesOrder(e,t,r){return{type:2,displayId:e,enabled:t,opacity:r??F.POST_PROCESS_DEFAULTS.scanlines.opacity,pattern:0,colorR:0,colorG:0,colorB:0}}createSetAmbientEffectOrder(e,t,r,n){return{type:3,displayId:e,enabled:t,blur:r??F.POST_PROCESS_DEFAULTS.ambientEffect.blur,scale:n??F.POST_PROCESS_DEFAULTS.ambientEffect.scale,opacity:F.POST_PROCESS_DEFAULTS.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:(0,F.scalingModeToValue)(t)}}createSetGridOrder(e,t){let{r,g:n,b:o,a:i}=this.parseColor(t.color??F.GRID_DEFAULTS.color);return{type:5,displayId:e,enabled:t.enabled,colorR:r,colorG:n,colorB:o,colorA:i,lineWidth:t.lineWidth??F.GRID_DEFAULTS.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(ar,"PostProcessOrderCollector");var Ze=ar;var X=class X{constructor(e={}){h(this,"users",new Map);h(this,"mode");h(this,"maxUsers");h(this,"strictMode");h(this,"currentTick",0);h(this,"encoder");h(this,"displayRasterizer");h(this,"colorPalette",new Map);h(this,"stats",new He);h(this,"spriteRegistry",new de);h(this,"webFontRegistry",new Ne);h(this,"bitmapFontRegistry",new Ye);h(this,"imageFontRegistry",new Xe);h(this,"soundRegistry",new We);h(this,"audioOrderCollector");h(this,"vibrationOrderCollector");h(this,"postProcessOrderCollector");h(this,"activeWebFontId",0);h(this,"_renderCallCount",0);h(this,"paletteSlots",new Map);h(this,"onPaletteChangedCallback");h(this,"onBitmapFontChangedCallback");h(this,"onImageFontChangedCallback");this.mode=e.mode??"server",this.maxUsers=e.maxUsers??64,this.strictMode=e.strictMode??!1,this.encoder=new q,this.displayRasterizer=new ae(this),this.audioOrderCollector=new Ge(this.soundRegistry),this.vibrationOrderCollector=new $e,this.postProcessOrderCollector=new Ze,this.initializeDefaultPalette(),this.displayRasterizer.rebuildColorCache(),this.loadDefaultWebFont()}initializeDefaultPalette(){X.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 Ve(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});X.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});X.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(),s=n.getDisplays();t+=i.length,n.getStats().isEnabled()&&n.getStats().startTick(this.currentTick);let a=s.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}});s.forEach(S=>S.resetChangeTracking());let d=[],l=[];i.forEach((S,O)=>{if(!S.getNeedsCommit())return;let I=S.getOrigin(),v=S.getOrders(),M=S.getStatic(),A=S.calculateUpdateFlags();S.resetChangeTracking(),S.resetCommit(),S.getId()===0&&S.setId(O);let E={id:S.getId(),updateFlags:A,zIndex:S.getZOrder(),originX:I.x,originY:I.y,width:S.getWidth(),height:S.getHeight(),is16bit:S.getCharCodeMode()==="16bit",orderCount:v.length,orders:v};v.length>0&&this.stats.isEnabled()&&this.stats.recordLayerInfo(S.getId(),M,v.length,A),M?d.push(E):l.push(E)}),r+=d.length+l.length;let c=this.audioOrderCollector.collectFromUser(n),u=this.vibrationOrderCollector.collectFromUser(n),p=this.postProcessOrderCollector.collectFromUser(n),m=n.flushMacroOrders(),b=null,C=null;if(this.stats.isEnabled()&&this.stats.recordPacketSplit(o,a.length,d.length,l.length),d.length>0&&(b=this.encoder.encode({tick:this.currentTick,displayCount:a.length,displays:a,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:a.length,displays:a,layerCount:l.length,layers:l,audioOrderCount:c.length,audioOrders:c,vibrationOrderCount:u.length,vibrationOrders:u,macroOrderCount:m.length,macroOrders:m,postProcessOrderCount:p.length,postProcessOrders:p}),e.set(o,{static:b,dynamic:C}),n.getStats().isEnabled()){let S=s.reduce((M,A)=>{let E=A.getSize();return M+E.x*E.y},0);n.getStats().recordDisplays(s.length,S),n.getStats().recordLayers(i.length,d.length+l.length,d.length,l.length),[...d,...l].forEach(M=>{n.getStats().recordLayerOrders(M.id,M.orders.length)});let O=b?.length||0,I=C?.length||0;n.getStats().recordPacketSizes(O,I);let v=n.getInputBindingRegistry();n.getStats().recordInput(!1,v.getAxisCount(),v.getButtonCount()),n.getStats().endTick()}if(n.endTickBytes(),this.stats.isEnabled()){let S=[...d,...l];S.forEach((A,E)=>{this.stats.recordLayerOrders(E,A.orders)}),s.forEach((A,E)=>{this.stats.recordDisplayLayers(E,S.length)});let O=(b?.length||0)+(C?.length||0),I=s.length*12,v=S.length*20,M=O-I-v;this.stats.recordUpdatePacketSize(O,I,v,M>0?M: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((s,a)=>{let d=s.getOrigin(),l=s.getSize();return{id:a,originX:d.x,originY:d.y,sizeX:l.x,sizeY:l.y}}),i=n.map((s,a)=>{let d=s.getOrigin(),l=s.getOrders(),c=7;return s.getId()===0&&s.setId(a),{id:s.getId(),updateFlags:c,zIndex:s.getZOrder(),originX:d.x,originY:d.y,width:s.getWidth(),height:s.getHeight(),is16bit:s.getCharCodeMode()==="16bit",orderCount:l.length,orders:l}});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}=(At(),G(ln)),o=new r().decode(t);return this.applyUpdatePacket(e,o)?o:null}applyLoadPacket(e){try{let n=new oe().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 D,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 D,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 s=0;s<o.sizeX*o.sizeY;s++)i.push(o.data.get(s));t.push({spriteId:o.id,sizeX:o.sizeX,sizeY:o.sizeY,data:i})}}return t.length===0?null:new D().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 s=0;s<o.sizeX*o.sizeY;s++){let a=o.data.get(s);i.push({charCode:a.charCode,fgColorId:a.fgColorCode,bgColorId:a.bgColorCode})}t.push({spriteId:o.id,sizeX:o.sizeX,sizeY:o.sizeY,data:i})}}return t.length===0?null:new D().encode({loadType:3,sprites:t})}generateWebFontsLoadPackets(){let e=this.getWebFontRegistry(),t=e.getFontIds(),r=[],n=new D;for(let o of t){let i=e.getFont(o);if(i){let s=i.getConfig(),a=n.encode({loadType:6,fontId:o,fontFamily:s.fontFamily,fontSize:s.fontSize,offsetX:s.offsetX,offsetY:s.offsetY,charSpacing:s.charSpacing,lineHeight:s.lineHeight,fontWeight:s.fontWeight,fontStyle:s.fontStyle});r.push(a)}}return r}generateBitmapFontsLoadPackets(){let e=this.getBitmapFontRegistry(),t=e.getFontIds(),r=[],n=new D;for(let o of t){let i=e.getFont(o);if(i){let s=[];for(let a=0;a<256;a++){let d=i.getGlyph(a);d&&s.push({charCode:a,bitmap:d})}if(s.length>0){let a=n.encode({loadType:4,fontId:o,width:i.getCharWidth(),height:i.getCharHeight(),cellWidth:i.getCellWidth(),cellHeight:i.getCellHeight(),characters:s});r.push(a)}}}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 s=this.generateBitmapFontsLoadPackets();return e.push(...s),e}generateMacroLoadPackets(e){let t=this.getUser(e);if(!t)return[];let r=t.getMacroLoads();if(r.length===0)return[];let n=new K;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(s=>{let a=s.getSize();return{id:s.getId(),originX:0,originY:0,sizeX:a.x,sizeY:a.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,t){let r=this.getUser(e);if(!r)return null;let n=r.getDisplays(),o=t?r.getLayers().filter(t):r.getLayers(),i=performance.now(),s=[];for(let d of n){if(!d)continue;let l=d.getOrigin(),c=d.getSize();if(s.push(this.displayRasterizer.rasterize({id:d.getId(),x:l.x,y:l.y,width:c.x,height:c.y},o)),this.stats.isEnabled()){let u=d.getId();this.stats.recordDisplayComposite(u,this.displayRasterizer.getLastVisibleLayerIds())}}let a=performance.now()-i;return this._renderCallCount||(this._renderCallCount=0),this._renderCallCount++,{userId:r.id,userName:r.name,tick:this.currentTick,displays:s}}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 s=await this.loadSound(o,i);t[o]=s});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 s=typeof require<"u"?require:null;if(!s)throw new Error("Node.js require is not available");let a="fs",d=s("path"),l=s(a),c=d.resolve(e),u=l.readFileSync(c);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 ue(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:s}])=>{let a=await this.loadImageFont(o,i,s);t[o]=a});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 require<"u"?require:null;if(!n)throw new Error("Node.js require is not available");let s=n("fs").readFileSync(e);return new Uint8Array(s)}}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(X,"Core"),h(X,"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 je=X;var yn=require("@utsp/types");
|
|
15
|
+
`}),e}};y(jt,"InputBindingRegistry");var Le=jt;function Cn(g=0n){return{tick:g,axes:new Map,buttons:new Map,displayId:0,mouseX:0,mouseY:0,mouseOverDisplay:!1,textInputs:[],macroEvents:[],displayViewports:[],touchPositions:[]}}y(Cn,"createEmptyCompressedInputPacket");function fn(g){return g/127}y(fn,"decodeInt8ToAxis");function Sn(g){return g===0?0:Math.ceil(g/8)}y(Sn,"getButtonByteCount");T();function In(g,e){let t=e.getAllAxes().length,r=e.getAllButtons().length,n=Sn(r),o=8+t+n+4;if(g.length<o)throw new Error(`Invalid compressed input packet: expected at least ${o} bytes (${t} axes + ${r} buttons), got ${g.length}`);let i=new DataView(g.buffer,g.byteOffset,g.byteLength),s=0,a=Cn();a.tick=i.getBigUint64(s,!0),s+=8;for(let l=0;l<t;l++){let c=g[s],p=c>127?c-256:c,u=fn(p);a.axes.set(l,u),s+=1}for(let l=0;l<n;l++){let c=g[s];for(let p=0;p<8;p++){let u=l*8+p;if(u<r){let m=(c&1<<p)!==0;a.buttons.set(u,m)}}s+=1}a.displayId=g[s],s+=1,a.mouseX=g[s],s+=1,a.mouseY=g[s],s+=1;let d=g[s];if(a.mouseOverDisplay=(d&1)!==0,s+=1,s<g.length){let l=g[s];s+=1;let c=new TextDecoder;a.textInputs=[];for(let p=0;p<l&&s<g.length;p++){let u=g[s];if(s+=1,s+u<=g.length){let m=g.slice(s,s+u),b=c.decode(m);a.textInputs.push(b),s+=u}}}if(s<g.length){let l=g[s];s+=1;let c=new se,p=[],u=f.from(g);for(let m=0;m<l&&s<g.length;m++){let b=c.decode(u,s);p.push(b.event),s+=b.bytesRead}a.macroEvents=p}if(s<g.length){let l=g[s];s+=1;for(let c=0;c<l&&s+5<=g.length;c++){let p=g[s];s+=1;let u=i.getUint16(s,!1);s+=2;let m=i.getUint16(s,!1);s+=2,a.displayViewports.push({displayId:p,pixelWidth:u,pixelHeight:m})}}if(s<g.length){let l=Math.min(g[s],10);s+=1;for(let c=0;c<l&&s+4<=g.length;c++){let p=g[s]&15;s+=1;let u=g[s];s+=1;let m=g[s];s+=1;let C=(g[s]&1)!==0;s+=1,a.touchPositions.push({id:p,x:u,y:m,over:C})}}return a}y(In,"decodeCompressedInput");var z=require("@utsp/types");var Jt=class Jt{constructor(e,t){h(this,"enabled",!1);h(this,"currentStats",null);h(this,"_userId");h(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(Jt,"UserStats");var De=Jt;var qt=class qt{constructor(e,t,r){this.id=e;this.name=t;h(this,"displays",[]);h(this,"layers",[]);h(this,"spriteRegistry");h(this,"mode");h(this,"axes",new Map);h(this,"buttons",new Map);h(this,"textInputs",[]);h(this,"mouseX",0);h(this,"mouseY",0);h(this,"mouseOver",!1);h(this,"mouseDisplayId",0);h(this,"touchPositions",new Map);h(this,"activeTouchId",null);h(this,"inputBindings",new Le);h(this,"stats");h(this,"soundCommands",[]);h(this,"nextSoundInstanceId",1);h(this,"audioConfigCommands",[]);h(this,"lastListenerX",-1);h(this,"lastListenerY",-1);h(this,"pendingSendSounds",!1);h(this,"audioProcessor");h(this,"loadedSounds",new Map);h(this,"soundLoadErrors",new Map);h(this,"playingSounds",new Map);h(this,"mobileVibrationCommands",[]);h(this,"mobileVibrationProcessor");h(this,"gamepadVibrationCommands",[]);h(this,"gamepadVibrationProcessor");h(this,"macroRegistry",new Re);h(this,"macroEngine",new Fe);h(this,"macroEventHandlers",new Map);h(this,"postProcessCommands",[]);h(this,"currentPostProcessConfig",null);h(this,"bridgeMessages",[]);h(this,"totalBytesSent",0);h(this,"totalBytesReceived",0);h(this,"bytesSentPerTick",[]);h(this,"bytesReceivedPerTick",[]);h(this,"bytesTickIndex",0);h(this,"bytesTickRate",20);h(this,"currentTickBytesSent",0);h(this,"currentTickBytesReceived",0);h(this,"availableViewports",new Map);h(this,"data");h(this,"currentScalingModes",new Map);h(this,"currentCellSizes",new Map);h(this,"currentGridConfigs",new Map);h(this,"currentPaletteSlotIds",new Map);this.mode=r,this.stats=new De(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,s=o.y+n;return{displayId:t,localX:r,localY:n,worldX:i,worldY:s}}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,s=r.getOrigin(),a=s.x+o,d=s.y+i;return{displayId:n,localX:o,localY:i,worldX:a,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 Pe(t.id,t.sizeX,t.sizeY);this.displays.length<=t.id;)this.displays.push(null);this.displays[t.id]=r}r.setOrigin(new z.Vector2(t.originX,t.originY)),r.setSize(new z.Vector2(t.sizeX,t.sizeY)),r.setRenderPasses(t.renderPasses)}}updateLayersFromPacket(e){for(let t of e){let r=this.findLayerById(t.id);r||(r=new ce(new z.Vector2(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 z.Vector2(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:s})=>{this.defineAxisBinding(t,r,n??[],o,i,s)})}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=In(e,this.inputBindings),r=this.inputBindings.getAllAxes(),n=this.inputBindings.getAllButtons(),o=r.sort((s,a)=>s.bindingId-a.bindingId),i=n.sort((s,a)=>s.bindingId-a.bindingId);for(let[s,a]of t.axes)if(s<o.length){let d=o[s];this.setAxis(d.name,a)}for(let[s,a]of t.buttons)if(s<i.length){let d=i[s];this.setButton(d.name,a)}this.mouseX=t.mouseX,this.mouseY=t.mouseY,this.mouseOver=t.mouseOverDisplay,this.mouseDisplayId=t.displayId;for(let s of t.touchPositions)this.setTouchPosition(s.id,s.x,s.y,s.over);for(let s of t.displayViewports)this.setDisplayViewport(s.displayId,s.pixelWidth,s.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}=(dn(),G(an)),{MobileVibrateFlags:r,GamepadVibrateFlags:n}=(on(),G(nn));for(let o of e)switch(o.type){case t.MobileVibrate:{if(!this.mobileVibrationProcessor)break;let i=o,s=i.pattern;i.flags&r.HasIntensity&&i.intensity!==void 0&&(s=s.map(a=>Math.round(a*i.intensity))),this.mobileVibrationProcessor.vibrate(s);break}case t.MobileCancel:{if(!this.mobileVibrationProcessor)break;this.mobileVibrationProcessor.cancel();break}case t.GamepadVibrate:{if(!this.gamepadVibrationProcessor)break;let i=o,s={duration:i.duration,strongMagnitude:i.strongMagnitude/255,weakMagnitude:i.weakMagnitude/255,startDelay:i.startDelay};if(i.flags&n.AllGamepads)for(let a=0;a<4;a++)this.gamepadVibrationProcessor.vibrate(a,s);else this.gamepadVibrationProcessor.vibrate(i.gamepadIndex,s);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}=(en(),G(Qr)),{PlaySoundFlags:n}=(Jr(),G(jr));for(let o of e)switch(o.type){case t.PlaySound:case t.PlayGlobalSound:{let i=o,s=i.volume!==void 0?i.volume/255:void 0,a=i.pitch!==void 0?.25*Math.pow(2,i.pitch/64):void 0,d=i.fadeIn!==void 0?i.fadeIn/10:void 0,l=(i.flags&n.Loop)!==0,c=i.posX!==void 0&&i.posY!==void 0?{x:i.posX,y:i.posY}:void 0;this.audioProcessor.play(i.soundId,{volume:s,pitch:a,loop:l,fadeIn:d,position:c,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,s=i.duration/10;i.targetType===r.All?this.audioProcessor.fadeOut("all",s):this.audioProcessor.fadeOut(i.target,s);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.getName();t&&this.macroRegistry.setLayerMapping(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,s=t+o.y;this.macroEngine.updateMouse(i,s,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 s=i.map(a=>{let d={...a};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,s)}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??z.POST_PROCESS_DEFAULTS.scanlines.opacity,pattern:r?.pattern??z.POST_PROCESS_DEFAULTS.scanlines.pattern,color:r?.color??z.POST_PROCESS_DEFAULTS.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??z.POST_PROCESS_DEFAULTS.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??z.POST_PROCESS_DEFAULTS.ambientEffect.blur,scale:r?.scale??z.POST_PROCESS_DEFAULTS.ambientEffect.scale}}):this.setPostProcess(e,{...this.currentPostProcessConfig,ambientEffect:{enabled:!0,blur:t.blur??r?.blur??z.POST_PROCESS_DEFAULTS.ambientEffect.blur,scale:t.scale??r?.scale??z.POST_PROCESS_DEFAULTS.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??z.POST_PROCESS_DEFAULTS.ambientEffect.scale}})}setAmbientEffectScale(e,t){let r=this.currentPostProcessConfig?.ambientEffect;this.setPostProcess(e,{...this.currentPostProcessConfig,ambientEffect:{enabled:r?.enabled??!0,blur:r?.blur??z.POST_PROCESS_DEFAULTS.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??z.POST_PROCESS_DEFAULTS.ambientEffect.blur,scale:e.scale??z.POST_PROCESS_DEFAULTS.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:z.GRID_DEFAULTS.color,lineWidth:z.GRID_DEFAULTS.lineWidth}:r={enabled:t.enabled,color:t.color??z.GRID_DEFAULTS.color,lineWidth:t.lineWidth??z.GRID_DEFAULTS.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}getDebugInfo(){let e=Array.from(this.availableViewports.entries()).map(([t,r])=>({displayId:t,pixelWidth:r.pixelWidth,pixelHeight:r.pixelHeight}));return{id:this.id,name:this.name,bytesSentTotal:this.totalBytesSent,bytesSentTick:this.currentTickBytesSent,availableViewports:e,layers:this.layers.map(t=>t.getDebugInfo()),displays:this.displays.map(t=>t.getDebugInfo())}}};y(qt,"User");var Ve=qt;var Kt=class Kt{constructor(){h(this,"enabled",!1);h(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 displayCompositeLayerIds(){return this.currentStats?.displayCompositeLayerIds??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,displayCompositeLayerIds:new Map})}recordDisplayComposite(e,t){!this.enabled||!this.currentStats||(this.currentStats.displayCompositeLayerIds||(this.currentStats.displayCompositeLayerIds=new Map),this.currentStats.displayCompositeLayerIds.set(e,[...t]))}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(Kt,"CoreStats");var _e=Kt;function Hn(g){return Math.sqrt(g)*16}y(Hn,"getAtlasColumns");function Nn(g){return g*256-1}y(Nn,"getMaxCharCode");var Qt=class Qt{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(Qt,"WebFont");var pe=Qt,er=class er{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(er,"BitmapFont");var He=er,tr=class tr{constructor(e,t){this.fontId=e;this.config=t;h(this,"atlasColumns");h(this,"maxCharCode");this.atlasColumns=Hn(t.atlasBlocks),this.maxCharCode=Nn(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,s=(r+1)/this.atlasColumns;return{u1:n,v1:o,u2:i,v2:s}}isValidCharCode(e){return e>=0&&e<=this.maxCharCode}};y(tr,"ImageFont");var fe=tr;var rr=class rr{constructor(){h(this,"fonts",new Map)}loadFont(e,t){if(this.fonts.has(e))throw new Error(`WebFont with ID ${e} already exists`);let r=new pe(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(rr,"WebFontRegistry");var Ne=rr;var nr=class nr{constructor(){h(this,"fonts",new Map)}loadFont(e,t){if(this.fonts.has(e))throw new Error(`BitmapFont with ID ${e} already exists`);let r=new He(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(nr,"BitmapFontRegistry");var Ye=nr;var or=class or{constructor(){h(this,"fonts",new Map);h(this,"nameToId",new Map);h(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 fe(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 fe(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(or,"ImageFontRegistry");var Xe=or;var ir=class ir{constructor(){h(this,"sounds",new Map);h(this,"nameToId",new Map);h(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),s={soundId:i,name:e,loadType:"external",format:t,url:r,size:n,checksum:o};return this.sounds.set(i,s),this.nameToId.set(e,i),i}registerExternalWithId(e,t,r,n,o,i){this.validateId(e),this.checkIdAvailable(e,t);let s={soundId:e,name:t,loadType:"external",format:r,url:n,size:o,checksum:i};this.sounds.set(e,s),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(ir,"SoundRegistry");var We=ir;var sr=class sr{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(sr,"AudioOrderCollector");var Ge=sr;var ar=class ar{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(ar,"VibrationOrderCollector");var $e=ar;var L=require("@utsp/types");var dr=class dr{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??L.POST_PROCESS_DEFAULTS.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??L.POST_PROCESS_DEFAULTS.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??L.POST_PROCESS_DEFAULTS.ambientEffect.blur,scale:o.scale??L.POST_PROCESS_DEFAULTS.ambientEffect.scale,opacity:o.opacity??L.POST_PROCESS_DEFAULTS.ambientEffect.opacity}}return n.flags=r,n}createSetScanlinesOrder(e,t,r){return{type:2,displayId:e,enabled:t,opacity:r??L.POST_PROCESS_DEFAULTS.scanlines.opacity,pattern:0,colorR:0,colorG:0,colorB:0}}createSetAmbientEffectOrder(e,t,r,n){return{type:3,displayId:e,enabled:t,blur:r??L.POST_PROCESS_DEFAULTS.ambientEffect.blur,scale:n??L.POST_PROCESS_DEFAULTS.ambientEffect.scale,opacity:L.POST_PROCESS_DEFAULTS.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:(0,L.scalingModeToValue)(t)}}createSetGridOrder(e,t){let{r,g:n,b:o,a:i}=this.parseColor(t.color??L.GRID_DEFAULTS.color);return{type:5,displayId:e,enabled:t.enabled,colorR:r,colorG:n,colorB:o,colorA:i,lineWidth:t.lineWidth??L.GRID_DEFAULTS.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(dr,"PostProcessOrderCollector");var Ze=dr;var X=class X{constructor(e={}){h(this,"users",new Map);h(this,"mode");h(this,"maxUsers");h(this,"strictMode");h(this,"currentTick",0);h(this,"encoder");h(this,"displayRasterizer");h(this,"colorPalette",new Map);h(this,"stats",new _e);h(this,"spriteRegistry",new le);h(this,"webFontRegistry",new Ne);h(this,"bitmapFontRegistry",new Ye);h(this,"imageFontRegistry",new Xe);h(this,"soundRegistry",new We);h(this,"audioOrderCollector");h(this,"vibrationOrderCollector");h(this,"postProcessOrderCollector");h(this,"activeWebFontId",0);h(this,"_renderCallCount",0);h(this,"paletteSlots",new Map);h(this,"onPaletteChangedCallback");h(this,"onBitmapFontChangedCallback");h(this,"onImageFontChangedCallback");this.mode=e.mode??"server",this.maxUsers=e.maxUsers??64,this.strictMode=e.strictMode??!1,this.encoder=new K,this.displayRasterizer=new de(this),this.audioOrderCollector=new Ge(this.soundRegistry),this.vibrationOrderCollector=new $e,this.postProcessOrderCollector=new Ze,this.initializeDefaultPalette(),this.displayRasterizer.rebuildColorCache(),this.loadDefaultWebFont()}initializeDefaultPalette(){X.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 Ve(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});X.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});X.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(),s=n.getDisplays();t+=i.length,n.getStats().isEnabled()&&n.getStats().startTick(this.currentTick);let a=s.map(S=>{let I=S.getOrigin(),O=S.getSize();return{id:S.getId(),originX:I.x,originY:I.y,sizeX:O.x,sizeY:O.y,renderPasses:S.getRenderPasses()}});s.forEach(S=>S.resetChangeTracking());let d=[],l=[];i.forEach((S,I)=>{if(!S.getNeedsCommit())return;let O=S.getOrigin(),v=S.getOrders(),w=S.getStatic(),A=S.calculateUpdateFlags();S.resetChangeTracking(),S.resetCommit(),S.getId()===0&&S.setId(I);let E={id:S.getId(),updateFlags:A,zIndex:S.getZOrder(),originX:O.x,originY:O.y,width:S.getWidth(),height:S.getHeight(),is16bit:S.getCharCodeMode()==="16bit",orderCount:v.length,orders:v};v.length>0&&this.stats.isEnabled()&&this.stats.recordLayerInfo(S.getId(),w,v.length,A),w?d.push(E):l.push(E)}),r+=d.length+l.length;let c=this.audioOrderCollector.collectFromUser(n),p=this.vibrationOrderCollector.collectFromUser(n),u=this.postProcessOrderCollector.collectFromUser(n),m=n.flushMacroOrders(),b=null,C=null;if(this.stats.isEnabled()&&this.stats.recordPacketSplit(o,a.length,d.length,l.length),d.length>0&&(b=this.encoder.encode({tick:this.currentTick,displayCount:a.length,displays:a,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:a.length,displays:a,layerCount:l.length,layers:l,audioOrderCount:c.length,audioOrders:c,vibrationOrderCount:p.length,vibrationOrders:p,macroOrderCount:m.length,macroOrders:m,postProcessOrderCount:u.length,postProcessOrders:u}),e.set(o,{static:b,dynamic:C}),n.getStats().isEnabled()){let S=s.reduce((w,A)=>{let E=A.getSize();return w+E.x*E.y},0);n.getStats().recordDisplays(s.length,S),n.getStats().recordLayers(i.length,d.length+l.length,d.length,l.length),[...d,...l].forEach(w=>{n.getStats().recordLayerOrders(w.id,w.orders.length)});let I=b?.length||0,O=C?.length||0;n.getStats().recordPacketSizes(I,O);let v=n.getInputBindingRegistry();n.getStats().recordInput(!1,v.getAxisCount(),v.getButtonCount()),n.getStats().endTick()}if(n.endTickBytes(),this.stats.isEnabled()){let S=[...d,...l];S.forEach((A,E)=>{this.stats.recordLayerOrders(E,A.orders)}),s.forEach((A,E)=>{this.stats.recordDisplayLayers(E,S.length)});let I=(b?.length||0)+(C?.length||0),O=a.reduce((A,E)=>{let U=Math.min(E.renderPasses?.length??0,4);return A+8+U*4},0),v=S.length*20,w=I-O-v;this.stats.recordUpdatePacketSize(I,O,v,w>0?w: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((s,a)=>{let d=s.getOrigin(),l=s.getSize();return{id:a,originX:d.x,originY:d.y,sizeX:l.x,sizeY:l.y,renderPasses:s.getRenderPasses()}}),i=n.map((s,a)=>{let d=s.getOrigin(),l=s.getOrders(),c=7;return s.getId()===0&&s.setId(a),{id:s.getId(),updateFlags:c,zIndex:s.getZOrder(),originX:d.x,originY:d.y,width:s.getWidth(),height:s.getHeight(),is16bit:s.getCharCodeMode()==="16bit",orderCount:l.length,orders:l}});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}=(Pt(),G(hn)),o=new r().decode(t);return this.applyUpdatePacket(e,o)?o:null}applyLoadPacket(e){try{let n=new ie().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 D,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 D,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 s=0;s<o.sizeX*o.sizeY;s++)i.push(o.data.get(s));t.push({spriteId:o.id,sizeX:o.sizeX,sizeY:o.sizeY,data:i})}}return t.length===0?null:new D().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 s=0;s<o.sizeX*o.sizeY;s++){let a=o.data.get(s);i.push({charCode:a.charCode,fgColorId:a.fgColorCode,bgColorId:a.bgColorCode})}t.push({spriteId:o.id,sizeX:o.sizeX,sizeY:o.sizeY,data:i})}}return t.length===0?null:new D().encode({loadType:3,sprites:t})}generateWebFontsLoadPackets(){let e=this.getWebFontRegistry(),t=e.getFontIds(),r=[],n=new D;for(let o of t){let i=e.getFont(o);if(i){let s=i.getConfig(),a=n.encode({loadType:6,fontId:o,fontFamily:s.fontFamily,fontSize:s.fontSize,offsetX:s.offsetX,offsetY:s.offsetY,charSpacing:s.charSpacing,lineHeight:s.lineHeight,fontWeight:s.fontWeight,fontStyle:s.fontStyle});r.push(a)}}return r}generateBitmapFontsLoadPackets(){let e=this.getBitmapFontRegistry(),t=e.getFontIds(),r=[],n=new D;for(let o of t){let i=e.getFont(o);if(i){let s=[];for(let a=0;a<256;a++){let d=i.getGlyph(a);d&&s.push({charCode:a,bitmap:d})}if(s.length>0){let a=n.encode({loadType:4,fontId:o,width:i.getCharWidth(),height:i.getCharHeight(),cellWidth:i.getCellWidth(),cellHeight:i.getCellHeight(),characters:s});r.push(a)}}}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 s=this.generateBitmapFontsLoadPackets();return e.push(...s),e}generateMacroLoadPackets(e){let t=this.getUser(e);if(!t)return[];let r=t.getMacroLoads();if(r.length===0)return[];let n=new Q;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(s=>{let a=s.getSize();return{id:s.getId(),originX:0,originY:0,sizeX:a.x,sizeY:a.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,t){let r=this.getUser(e);if(!r)return null;let n=r.getDisplays(),o=t?r.getLayers().filter(t):r.getLayers(),i=performance.now(),s=[];for(let d of n){if(!d)continue;let l=d.getOrigin(),c=d.getSize();if(s.push(this.displayRasterizer.rasterize({id:d.getId(),x:l.x,y:l.y,width:c.x,height:c.y},o,d.getRenderPasses())),this.stats.isEnabled()){let p=d.getId();this.stats.recordDisplayComposite(p,this.displayRasterizer.getLastVisibleLayerIds())}}let a=performance.now()-i;return this._renderCallCount||(this._renderCallCount=0),this._renderCallCount++,{userId:r.id,userName:r.name,tick:this.currentTick,displays:s}}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 s=await this.loadSound(o,i);t[o]=s});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 u=await fetch(e);if(!u.ok)throw new Error(`HTTP ${u.status}: ${u.statusText}`);let m=await u.arrayBuffer();return new Uint8Array(m)}catch(u){let m=u instanceof Error?u.message:String(u);throw new Error(`Failed to load sound "${e}": ${m}`)}if((o||i)&&n)try{let u=await fetch(e);if(!u.ok)throw new Error(`HTTP ${u.status}: ${u.statusText}`);let m=await u.arrayBuffer();return new Uint8Array(m)}catch(u){let m=u instanceof Error?u.message:String(u);throw new Error(`Failed to load sound "${e}": ${m}`)}let s=typeof require<"u"?require:null;if(!s)throw new Error("Node.js require is not available");let a="fs",d=s("path"),l=s(a),c=d.resolve(e),p=l.readFileSync(c);return new Uint8Array(p)}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 pe(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:s}])=>{let a=await this.loadImageFont(o,i,s);t[o]=a});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 require<"u"?require:null;if(!n)throw new Error("Node.js require is not available");let s=n("fs").readFileSync(e);return new Uint8Array(s)}}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(X,"Core"),h(X,"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 je=X;var On=require("@utsp/types");
|