@quake2ts/engine 0.0.855 → 0.0.857

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
- "use strict";var Quake2Engine=(()=>{var cg=Object.create;var Zs=Object.defineProperty;var ug=Object.getOwnPropertyDescriptor;var dg=Object.getOwnPropertyNames;var fg=Object.getPrototypeOf,hg=Object.prototype.hasOwnProperty;var mg=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),zi=(t,e)=>{for(var r in e)Zs(t,r,{get:e[r],enumerable:!0})},Yf=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of dg(e))!hg.call(t,i)&&i!==r&&Zs(t,i,{get:()=>e[i],enumerable:!(n=ug(e,i))||n.enumerable});return t};var pg=(t,e,r)=>(r=t!=null?cg(fg(t)):{},Yf(e||!t||!t.__esModule?Zs(r,"default",{value:t,enumerable:!0}):r,t)),gg=t=>Yf(Zs({},"__esModule",{value:!0}),t);var Fh=mg((wA,Bh)=>{"use strict";Bh.exports=Worker});var L2={};zi(L2,{ATTN_IDLE:()=>Tu,ATTN_LOOP_NONE:()=>Au,ATTN_NONE:()=>ao,ATTN_NORM:()=>Eu,ATTN_STATIC:()=>Lu,AssetDependencyError:()=>Mi,AssetDependencyTracker:()=>ls,AssetManager:()=>ql,AssetPreviewGenerator:()=>tu,AudioApi:()=>Xi,AudioContextController:()=>Zl,AudioOcclusion:()=>us,AudioRegistry:()=>ga,AudioRegistryError:()=>as,AudioSystem:()=>nc,BSP_SURFACE_FRAGMENT_SOURCE:()=>bd,BSP_SURFACE_VERTEX_SOURCE:()=>yd,BSP_VERTEX_LAYOUT:()=>dd,BspLoader:()=>Yi,BspLump:()=>Du,BspParseError:()=>le,BspSurfacePipeline:()=>va,Camera:()=>gc,ClientConnection:()=>su,Command:()=>eo,CommandRegistry:()=>Oi,ConfigStringRegistry:()=>$i,ConnectionState:()=>Of,CoordinateSystem:()=>Qd,Cvar:()=>oo,CvarRegistry:()=>Hi,DemoAnalyzer:()=>Ka,DemoCameraMode:()=>Df,DemoClipper:()=>eu,DemoEventType:()=>If,DemoPlaybackController:()=>Ns,DemoReader:()=>vr,DemoRecorder:()=>Gs,DemoValidator:()=>Jc,DynamicLightManager:()=>lc,EngineHost:()=>Wi,EngineRuntime:()=>so,FileType:()=>kf,FixedTimestepLoop:()=>ri,Framebuffer:()=>Ai,IndexBuffer:()=>st,LoggingRenderer:()=>ou,LruCache:()=>En,MAX_SOUND_CHANNELS:()=>io,MD2_FRAGMENT_SHADER:()=>Ad,MD2_VERTEX_SHADER:()=>Md,MD3_FRAGMENT_SHADER:()=>$d,MD3_VERTEX_SHADER:()=>Xd,MapAnalyzer:()=>ru,Md2Loader:()=>qi,Md2MeshBuffers:()=>wa,Md2ParseError:()=>it,Md2Pipeline:()=>Ma,Md3Loader:()=>Zi,Md3ModelMesh:()=>La,Md3ParseError:()=>er,Md3Pipeline:()=>Pa,Md3SurfaceMesh:()=>gs,MessageWriter:()=>Qc,MusicSystem:()=>ic,NetworkMessageParser:()=>xt,NullRenderer:()=>nu,PARTICLE_FRAGMENT_SHADER:()=>Yd,PARTICLE_VERTEX_SHADER:()=>Kd,PROTOCOL_VERSION_RERELEASE:()=>Xr,PakArchive:()=>Ki,PakIndexStore:()=>Yl,PakIngestionError:()=>An,PakParseError:()=>ze,PakValidationError:()=>li,PakValidator:()=>ll,PakWriter:()=>al,ParticleRenderer:()=>Ca,ParticleSystem:()=>Ra,PlaybackState:()=>jc,RERELEASE_KNOWN_PAKS:()=>Fu,ResourceLoadTracker:()=>ol,ResourceType:()=>Bu,SKYBOX_FRAGMENT_SHADER:()=>Sd,SKYBOX_VERTEX_SHADER:()=>_d,SOUND_FULLVOLUME:()=>Gi,SOUND_LOOP_ATTENUATE:()=>Pu,ShaderProgram:()=>ce,SkyboxPipeline:()=>_a,SoundChannel:()=>Cr,SoundPrecache:()=>Jl,SoundRegistry:()=>Ql,SpriteLoader:()=>ji,SpriteParseError:()=>Tn,SpriteRenderer:()=>Ba,StreamingPakArchive:()=>il,Texture2D:()=>lt,TextureCache:()=>Qi,TextureCubeMap:()=>ya,TgaParseError:()=>qr,U_ALPHA:()=>Ar,U_ANGLE1:()=>Pt,U_ANGLE2:()=>Mt,U_ANGLE3:()=>At,U_EFFECTS16:()=>Qe,U_EFFECTS8:()=>qe,U_EVENT:()=>Tt,U_FRAME16:()=>Ct,U_FRAME8:()=>Et,U_INSTANCE_BITS:()=>Pr,U_LOOP_ATTENUATION_HIGH:()=>_n,U_LOOP_VOLUME:()=>Rr,U_MODEL:()=>Rt,U_MODEL2:()=>Bt,U_MODEL3:()=>Ft,U_MODEL4:()=>It,U_OLDORIGIN:()=>pr,U_OLD_FRAME_HIGH:()=>wn,U_ORIGIN1:()=>St,U_ORIGIN2:()=>wt,U_ORIGIN3:()=>Lt,U_OWNER_HIGH:()=>Sn,U_REMOVE:()=>ro,U_RENDERFX16:()=>je,U_RENDERFX8:()=>Ye,U_SCALE:()=>Lr,U_SKIN16:()=>Je,U_SKIN8:()=>Ze,U_SOLID:()=>kt,U_SOUND:()=>Dt,VertexArray:()=>Be,VertexBuffer:()=>Ce,VirtualFileSystem:()=>sl,advanceAnimation:()=>Th,applyEntityDelta:()=>$0,applySurfaceState:()=>ds,attenuationToDistanceMultiplier:()=>Vi,boxIntersectsFrustum:()=>Ei,buildBspGeometry:()=>sc,buildMd2Geometry:()=>Ed,buildMd2VertexData:()=>Td,buildMd3SurfaceGeometry:()=>Hd,buildMd3VertexData:()=>Wd,calculateMaxAudibleDistance:()=>si,calculatePakChecksum:()=>dh,captureRenderTarget:()=>eg,computeFrameBlend:()=>Lh,computeSkyScroll:()=>Li,createAnimationState:()=>Ph,createAudioGraph:()=>jl,createBspSurfaces:()=>oc,createEmptyEntityState:()=>Wr,createEmptyProtocolPlayerState:()=>_r,createEngine:()=>T2,createEngineRuntime:()=>lh,createFaceLightmap:()=>ul,createHeadlessRenderTarget:()=>J0,createInitialChannels:()=>ec,createOcclusionResolver:()=>cm,createProgramFromSources:()=>fm,createRenderer:()=>hp,createWebGLContext:()=>um,createWebGPUContext:()=>Ac,createWebGPURenderer:()=>wp,decodeOgg:()=>Kl,deriveSurfaceRenderState:()=>vd,detectFileType:()=>Uf,extractFrustumPlanes:()=>sr,filesToPakSources:()=>Iu,findLeafForPoint:()=>Ti,gatherVisibleFaces:()=>cn,groupMd2Animations:()=>wh,ingestPakFiles:()=>ph,ingestPaks:()=>cl,interpolateMd3Tag:()=>Zm,interpolateVec3:()=>Rh,isBinaryFile:()=>Y0,isTextFile:()=>zf,parseBsp:()=>lo,parseEntLump:()=>Z0,parseMd2:()=>ku,parseMd3:()=>Uu,parsePcx:()=>ho,parseSprite:()=>zu,parseTga:()=>Ou,parseWal:()=>fl,parseWalTexture:()=>pl,parseWav:()=>gl,pcxToRgba:()=>hl,pickChannel:()=>tc,preparePcxTexture:()=>ml,queryCapabilities:()=>mp,removeViewTranslation:()=>Sa,resolveLightStyles:()=>xd,serializeEntLump:()=>j0,spawnBfgExplosion:()=>lp,spawnBlasterImpact:()=>sp,spawnBlood:()=>Jm,spawnBulletImpact:()=>jm,spawnExplosion:()=>Qm,spawnMuzzleFlash:()=>tp,spawnRailTrail:()=>ap,spawnSparks:()=>op,spawnSplash:()=>np,spawnSteam:()=>ip,spawnTeleportFlash:()=>ep,spawnTrail:()=>rp,validateEntity:()=>Q0,walToRgba:()=>Nu,wireDropTarget:()=>gh,wireFileInput:()=>yh});var yg=()=>typeof performance<"u"?performance.now():Date.now(),bg=t=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>t()):setTimeout(t,25)},ri=class{constructor(e,r={}){this.callbacks=e;this.accumulatorMs=0;this.frame=0;this.running=!1;this.tick=()=>{if(!this.running)return;let e=this.options.now(),r=this.lastTimeMs===void 0?0:e-this.lastTimeMs;this.lastTimeMs=e,this.advance(r,e),this.running&&this.options.schedule(this.tick)};let n=r.fixedDeltaMs??25,i=r.maxSubSteps??5;this.options={fixedDeltaMs:n,maxSubSteps:i,maxDeltaMs:r.maxDeltaMs??n*i,startTimeMs:r.startTimeMs,now:r.now??yg,schedule:r.schedule??bg}}start(){this.running||(this.running=!0,this.lastTimeMs=this.options.startTimeMs??this.options.now(),this.options.schedule(this.tick))}stop(){this.running=!1}pump(e){let r=(this.lastTimeMs??0)+e;this.lastTimeMs=r,this.advance(e,r)}isRunning(){return this.running}get frameNumber(){return this.frame}advance(e,r){let n=Math.min(Math.max(e,0),this.options.maxDeltaMs);this.accumulatorMs=Math.min(this.accumulatorMs+n,this.options.fixedDeltaMs*this.options.maxSubSteps);let i=0;for(;this.accumulatorMs>=this.options.fixedDeltaMs&&i<this.options.maxSubSteps;)this.frame+=1,this.callbacks.simulate({frame:this.frame,deltaMs:this.options.fixedDeltaMs,nowMs:r}),this.accumulatorMs-=this.options.fixedDeltaMs,i+=1;let a=this.options.fixedDeltaMs===0?0:this.accumulatorMs/this.options.fixedDeltaMs;this.callbacks.render?.({alpha:a,nowMs:r,accumulatorMs:this.accumulatorMs,frame:this.frame})}};var eo=class{constructor(e,r,n){this.name=e,this.callback=r,this.description=n}execute(e){this.callback(e)}},Oi=class{constructor(){this.commands=new Map;this.history=[];this.historyLimit=64;this.autocompleteProviders=[]}register(e,r,n){let i=new eo(e,r,n);return this.commands.set(e,i),i}registerCommand(e,r){this.register(e,r)}registerAutocompleteProvider(e){this.autocompleteProviders.push(e)}get(e){return this.commands.get(e)}execute(e){let r=e.trim();if(r.length===0)return!1;(this.history.length===0||this.history[this.history.length-1]!==r)&&(this.history.push(r),this.history.length>this.historyLimit&&this.history.shift());let n=this.tokenize(e);if(n.length===0)return!1;let i=n[0],a=n.slice(1),o=this.get(i);return o?(o.execute(a),!0):(this.onConsoleOutput?.(`Unknown command "${i}"`),!1)}executeCommand(e){this.execute(e)}getHistory(){return[...this.history]}getSuggestions(e){let r=new Set;for(let n of this.commands.keys())n.startsWith(e)&&r.add(n);for(let n of this.autocompleteProviders){let i=n();for(let a of i)a.startsWith(e)&&r.add(a)}return Array.from(r).sort()}tokenize(e){let r=[],n="",i=!1;for(let a=0;a<e.length;a++){let o=e[a];o==='"'?i=!i:o===" "&&!i?n.length>0&&(r.push(n),n=""):n+=o}return n.length>0&&r.push(n),r}list(){return[...this.commands.values()].sort((e,r)=>e.name.localeCompare(r.name))}};var xg=Object.defineProperty,vg=(t,e)=>{for(var r in e)xg(t,r,{get:e[r],enumerable:!0})},qf={x:0,y:0,z:0};var O2=Math.PI/180;function Zf(t,e){return{x:t.x-e.x,y:t.y-e.y,z:t.z-e.z}}function _g(t,e){return{x:t.x*e,y:t.y*e,z:t.z*e}}function Sg(t,e){return t.x*e.x+t.y*e.y+t.z*e.z}function wg(t){return Sg(t,t)}function mu(t){return Math.sqrt(wg(t))}function Kr(t){let e=mu(t);return e===0?t:_g(t,1/e)}var Mg=Math.PI/180,Ag=180/Math.PI,Ae=Mg,pu=Ag;var mr=[[-.525731,0,.850651],[-.442863,.238856,.864188],[-.295242,0,.955423],[-.309017,.5,.809017],[-.16246,.262866,.951056],[0,0,1],[0,.850651,.525731],[-.147621,.716567,.681718],[.147621,.716567,.681718],[0,.525731,.850651],[.309017,.5,.809017],[.525731,0,.850651],[.295242,0,.955423],[.442863,.238856,.864188],[.16246,.262866,.951056],[-.681718,.147621,.716567],[-.809017,.309017,.5],[-.587785,.425325,.688191],[-.850651,.525731,0],[-.864188,.442863,.238856],[-.716567,.681718,.147621],[-.688191,.587785,.425325],[-.5,.809017,.309017],[-.238856,.864188,.442863],[-.425325,.688191,.587785],[-.716567,.681718,-.147621],[-.5,.809017,-.309017],[-.525731,.850651,0],[0,.850651,-.525731],[-.238856,.864188,-.442863],[0,.955423,-.295242],[-.262866,.951056,-.16246],[0,1,0],[0,.955423,.295242],[-.262866,.951056,.16246],[.238856,.864188,.442863],[.262866,.951056,.16246],[.5,.809017,.309017],[.238856,.864188,-.442863],[.262866,.951056,-.16246],[.5,.809017,-.309017],[.850651,.525731,0],[.716567,.681718,.147621],[.716567,.681718,-.147621],[.525731,.850651,0],[.425325,.688191,.587785],[.864188,.442863,.238856],[.688191,.587785,.425325],[.809017,.309017,.5],[.681718,.147621,.716567],[.587785,.425325,.688191],[.955423,.295242,0],[1,0,0],[.951056,.16246,.262866],[.850651,-.525731,0],[.955423,-.295242,0],[.864188,-.442863,.238856],[.951056,-.16246,.262866],[.809017,-.309017,.5],[.681718,-.147621,.716567],[.850651,0,.525731],[.864188,.442863,-.238856],[.809017,.309017,-.5],[.951056,.16246,-.262866],[.525731,0,-.850651],[.681718,.147621,-.716567],[.681718,-.147621,-.716567],[.850651,0,-.525731],[.809017,-.309017,-.5],[.864188,-.442863,-.238856],[.951056,-.16246,-.262866],[.147621,.716567,-.681718],[.309017,.5,-.809017],[.425325,.688191,-.587785],[.442863,.238856,-.864188],[.587785,.425325,-.688191],[.688191,.587785,-.425325],[-.147621,.716567,-.681718],[-.309017,.5,-.809017],[0,.525731,-.850651],[-.525731,0,-.850651],[-.442863,.238856,-.864188],[-.295242,0,-.955423],[-.16246,.262866,-.951056],[0,0,-1],[.295242,0,-.955423],[.16246,.262866,-.951056],[-.442863,-.238856,-.864188],[-.309017,-.5,-.809017],[-.16246,-.262866,-.951056],[0,-.850651,-.525731],[-.147621,-.716567,-.681718],[.147621,-.716567,-.681718],[0,-.525731,-.850651],[.309017,-.5,-.809017],[.442863,-.238856,-.864188],[.16246,-.262866,-.951056],[.238856,-.864188,-.442863],[.5,-.809017,-.309017],[.425325,-.688191,-.587785],[.716567,-.681718,-.147621],[.688191,-.587785,-.425325],[.587785,-.425325,-.688191],[0,-.955423,-.295242],[0,-1,0],[.262866,-.951056,-.16246],[0,-.850651,.525731],[0,-.955423,.295242],[.238856,-.864188,.442863],[.262866,-.951056,.16246],[.5,-.809017,.309017],[.716567,-.681718,.147621],[.525731,-.850651,0],[-.238856,-.864188,-.442863],[-.5,-.809017,-.309017],[-.262866,-.951056,-.16246],[-.850651,-.525731,0],[-.716567,-.681718,-.147621],[-.716567,-.681718,.147621],[-.525731,-.850651,0],[-.5,-.809017,.309017],[-.238856,-.864188,.442863],[-.262866,-.951056,.16246],[-.864188,-.442863,.238856],[-.809017,-.309017,.5],[-.688191,-.587785,.425325],[-.681718,-.147621,.716567],[-.442863,-.238856,.864188],[-.587785,-.425325,.688191],[-.309017,-.5,.809017],[-.147621,-.716567,.681718],[-.425325,-.688191,.587785],[-.16246,-.262866,.951056],[.442863,-.238856,.864188],[.16246,-.262866,.951056],[.309017,-.5,.809017],[.147621,-.716567,.681718],[0,-.525731,.850651],[.425325,-.688191,.587785],[.587785,-.425325,.688191],[.688191,-.587785,.425325],[-.955423,.295242,0],[-.951056,.16246,.262866],[-1,0,0],[-.850651,0,.525731],[-.955423,-.295242,0],[-.951056,-.16246,.262866],[-.864188,.442863,-.238856],[-.951056,.16246,-.262866],[-.809017,.309017,-.5],[-.864188,-.442863,-.238856],[-.951056,-.16246,-.262866],[-.809017,-.309017,-.5],[-.681718,.147621,-.716567],[-.681718,-.147621,-.716567],[-.850651,0,-.525731],[-.688191,.587785,-.425325],[-.587785,.425325,-.688191],[-.425325,.688191,-.587785],[-.425325,-.688191,-.587785],[-.587785,-.425325,-.688191],[-.688191,-.587785,-.425325]];var Sr=624,Eg=397,Tg=2567483615,Lg=2147483648,Pg=2147483647,fu=4294967296,Rg=class{constructor(t=5489){this.state=new Uint32Array(Sr),this.index=Sr,this.seed(t)}seed(t){this.state[0]=t>>>0;for(let e=1;e<Sr;e++){let r=this.state[e-1]^this.state[e-1]>>>30,n=Math.imul(r>>>0,1812433253)+e;this.state[e]=n>>>0}this.index=Sr}nextUint32(){this.index>=Sr&&this.twist();let t=this.state[this.index++];return t^=t>>>11,t^=t<<7&2636928640,t^=t<<15&4022730752,t^=t>>>18,t>>>0}twist(){for(let t=0;t<Sr;t++){let e=this.state[t]&Lg|this.state[(t+1)%Sr]&Pg,r=this.state[(t+Eg)%Sr]^e>>>1;(e&1)!==0&&(r^=Tg),this.state[t]=r>>>0}this.index=0}getState(){return{index:this.index,state:Array.from(this.state)}}setState(t){if(t.state.length!==Sr)throw new Error(`Expected ${Sr} MT state values, received ${t.state.length}`);this.index=t.index,this.state=Uint32Array.from(t.state,e=>e>>>0)}},jf=class{constructor(t={}){this.mt=new Rg(t.seed)}seed(t){this.mt.seed(t)}frandom(){return this.mt.nextUint32()/fu}frandomRange(t,e){return t+(e-t)*this.frandom()}frandomMax(t){return this.frandomRange(0,t)}crandom(){return this.frandomRange(-1,1)}crandomOpen(){let t=Number.EPSILON;return this.frandomRange(-1+t,1)}irandomUint32(){return this.mt.nextUint32()}irandomRange(t,e){if(e-t<=1)return t;let r=e-t,n=fu-fu%r,i;do i=this.mt.nextUint32();while(i>=n);return t+i%r}irandom(t){return t<=0?0:this.irandomRange(0,t)}randomTimeRange(t,e){return e<=t?t:this.irandomRange(t,e)}randomTime(t){return this.irandom(t)}randomIndex(t){return this.irandom(t.length)}getState(){return{mt:this.mt.getState()}}setState(t){this.mt.setState(t.mt)}};function Cg(){return new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1])}function gu(t,e){let r=new Float32Array(16);for(let n=0;n<4;n+=1)for(let i=0;i<4;i+=1)r[i*4+n]=t[0+n]*e[i*4+0]+t[4+n]*e[i*4+1]+t[8+n]*e[i*4+2]+t[12+n]*e[i*4+3];return r}function Qf(t,e){let r=e.x,n=e.y,i=e.z;return{x:t[0]*r+t[4]*n+t[8]*i+t[12],y:t[1]*r+t[5]*n+t[9]*i+t[13],z:t[2]*r+t[6]*n+t[10]*i+t[14]}}function Jf(t,e){let r=Cg();return r[0]=e[0].x,r[1]=e[0].y,r[2]=e[0].z,r[4]=e[1].x,r[5]=e[1].y,r[6]=e[1].z,r[8]=e[2].x,r[9]=e[2].y,r[10]=e[2].z,r[12]=t.x,r[13]=t.y,r[14]=t.z,r}var wr=1,gn=2;var yu=8,bu=16,Bg=32;var Fg=16384;var js=65536,eh=1<<17,Ig=1<<18,Dg=1<<19,kg=1<<20,Ug=1<<21,zg=1<<22,Og=1<<23,N2=1<<24,Qs=1<<25,Ng=1<<26,G2=1<<27,V2=1<<28,H2=1<<29,Js=1<<30,W2=1<<31;var yn=0;var bn=4,Yr=8,xn=16,vn=32,el=64;var X2=1<<25,$2=1<<28,K2=1<<29,Y2=1<<30,q2=1<<31;var Z2=wr|gn,j2=wr|js|gn|Qs|Js,Q2=wr|js|gn,J2=wr|eh|gn|Qs|Js,eM=Bg|yu|bu,tM=wr|bu|yu,Gg=wr|Qs|Js|gn|Ng,rM=Ig|Dg|kg|Ug|zg|Og,nM=wr|yu|bu|Qs|Js,iM=wr|js|gn,aM=wr|gn,oM=wr|js|gn|eh,sM=Gg|Fg;var lM=Number.MAX_SAFE_INTEGER-1;var tl=(t=>(t[t.None=0]="None",t[t.Archive=1]="Archive",t[t.UserInfo=2]="UserInfo",t[t.ServerInfo=4]="ServerInfo",t[t.Latch=8]="Latch",t[t.Cheat=16]="Cheat",t))(tl||{});var rl=256;var xu=256,vu=8192,nl=2048,_u=512,Su=256,wu=rl*2,Mu=256,hu=32,to=96;var ee=(t=>(t[t.Name=0]="Name",t[t.CdTrack=1]="CdTrack",t[t.Sky=2]="Sky",t[t.SkyAxis=3]="SkyAxis",t[t.SkyRotate=4]="SkyRotate",t[t.StatusBar=5]="StatusBar",t[t.HealthBarName=55]="HealthBarName",t[t.CONFIG_N64_PHYSICS=56]="CONFIG_N64_PHYSICS",t[t.CONFIG_CTF_TEAMS=57]="CONFIG_CTF_TEAMS",t[t.CONFIG_COOP_RESPAWN_STRING=58]="CONFIG_COOP_RESPAWN_STRING",t[t.Story=54]="Story",t[t.AirAccel=59]="AirAccel",t[t.MaxClients=60]="MaxClients",t[t.MapChecksum=61]="MapChecksum",t[t.Models=62]="Models",t[t.Sounds=62+vu]="Sounds",t[t.Images=t.Sounds+nl]="Images",t[t.Lights=t.Images+_u]="Lights",t[t.ShadowLights=t.Lights+xu]="ShadowLights",t[t.Items=t.ShadowLights+Mu]="Items",t[t.Players=t.Items+Su]="Players",t[t.PlayerSkins=t.Players]="PlayerSkins",t[t.General=t.Players+rl]="General",t[t.WheelWeapons=t.General+wu]="WheelWeapons",t[t.WheelAmmo=t.WheelWeapons+hu]="WheelAmmo",t[t.WheelPowerups=t.WheelAmmo+hu]="WheelPowerups",t[t.CdLoopCount=t.WheelPowerups+hu]="CdLoopCount",t[t.GameStyle=t.CdLoopCount+1]="GameStyle",t[t.MaxConfigStrings=t.GameStyle+1]="MaxConfigStrings",t))(ee||{}),th=ee.MaxConfigStrings;function rh(t){return t>=5&&t<59?to*(59-t):t>=ee.General&&t<ee.WheelWeapons?to*(ee.MaxConfigStrings-t):to}var cM=ee.Sounds,uM=ee.Images,dM=ee.Lights,fM=ee.Items,hM=ee.Players,mM=ee.General,Vg={};vg(Vg,{addReplayFrame:()=>$g,createReplaySession:()=>Xg,deserializeReplay:()=>Wg,serializeReplay:()=>Hg});function Hg(t){return JSON.stringify(t,null,2)}function Wg(t){let e=JSON.parse(t);if(!e.metadata||!Array.isArray(e.frames))throw new Error("Invalid replay format: missing metadata or frames");return e}function Xg(t,e){return{metadata:{map:t,date:new Date().toISOString(),version:"1.0",seed:e},frames:[]}}function $g(t,e,r,n){t.frames.push({serverFrame:r,cmd:e,timestamp:Date.now()-n})}var R=(t=>(t[t.bad=0]="bad",t[t.muzzleflash=1]="muzzleflash",t[t.muzzleflash2=2]="muzzleflash2",t[t.temp_entity=3]="temp_entity",t[t.layout=4]="layout",t[t.inventory=5]="inventory",t[t.nop=6]="nop",t[t.disconnect=7]="disconnect",t[t.reconnect=8]="reconnect",t[t.sound=9]="sound",t[t.print=10]="print",t[t.stufftext=11]="stufftext",t[t.serverdata=12]="serverdata",t[t.configstring=13]="configstring",t[t.spawnbaseline=14]="spawnbaseline",t[t.centerprint=15]="centerprint",t[t.download=16]="download",t[t.playerinfo=17]="playerinfo",t[t.packetentities=18]="packetentities",t[t.deltapacketentities=19]="deltapacketentities",t[t.frame=20]="frame",t[t.splitclient=21]="splitclient",t[t.configblast=22]="configblast",t[t.spawnbaselineblast=23]="spawnbaselineblast",t[t.level_restart=24]="level_restart",t[t.damage=25]="damage",t[t.locprint=26]="locprint",t[t.fog=27]="fog",t[t.waitingforplayers=28]="waitingforplayers",t[t.bot_chat=29]="bot_chat",t[t.poi=30]="poi",t[t.help_path=31]="help_path",t[t.muzzleflash3=32]="muzzleflash3",t[t.achievement=33]="achievement",t))(R||{}),ii=(t=>(t[t.bad=0]="bad",t[t.nop=1]="nop",t[t.move=2]="move",t[t.userinfo=3]="userinfo",t[t.stringcmd=4]="stringcmd",t))(ii||{}),U=(t=>(t[t.GUNSHOT=0]="GUNSHOT",t[t.BLOOD=1]="BLOOD",t[t.BLASTER=2]="BLASTER",t[t.RAILTRAIL=3]="RAILTRAIL",t[t.SHOTGUN=4]="SHOTGUN",t[t.EXPLOSION1=5]="EXPLOSION1",t[t.EXPLOSION2=6]="EXPLOSION2",t[t.ROCKET_EXPLOSION=7]="ROCKET_EXPLOSION",t[t.GRENADE_EXPLOSION=8]="GRENADE_EXPLOSION",t[t.SPARKS=9]="SPARKS",t[t.SPLASH=10]="SPLASH",t[t.BUBBLETRAIL=11]="BUBBLETRAIL",t[t.SCREEN_SPARKS=12]="SCREEN_SPARKS",t[t.SHIELD_SPARKS=13]="SHIELD_SPARKS",t[t.BULLET_SPARKS=14]="BULLET_SPARKS",t[t.LASER_SPARKS=15]="LASER_SPARKS",t[t.PARASITE_ATTACK=16]="PARASITE_ATTACK",t[t.ROCKET_EXPLOSION_WATER=17]="ROCKET_EXPLOSION_WATER",t[t.GRENADE_EXPLOSION_WATER=18]="GRENADE_EXPLOSION_WATER",t[t.MEDIC_CABLE_ATTACK=19]="MEDIC_CABLE_ATTACK",t[t.BFG_EXPLOSION=20]="BFG_EXPLOSION",t[t.BFG_BIGEXPLOSION=21]="BFG_BIGEXPLOSION",t[t.BOSSTPORT=22]="BOSSTPORT",t[t.BFG_LASER=23]="BFG_LASER",t[t.GRAPPLE_CABLE=24]="GRAPPLE_CABLE",t[t.WELDING_SPARKS=25]="WELDING_SPARKS",t[t.GREENBLOOD=26]="GREENBLOOD",t[t.BLUEHYPERBLASTER=27]="BLUEHYPERBLASTER",t[t.PLASMA_EXPLOSION=28]="PLASMA_EXPLOSION",t[t.TUNNEL_SPARKS=29]="TUNNEL_SPARKS",t[t.BLASTER2=30]="BLASTER2",t[t.RAILTRAIL2=31]="RAILTRAIL2",t[t.FLAME=32]="FLAME",t[t.LIGHTNING=33]="LIGHTNING",t[t.DEBUGTRAIL=34]="DEBUGTRAIL",t[t.PLAIN_EXPLOSION=35]="PLAIN_EXPLOSION",t[t.FLASHLIGHT=36]="FLASHLIGHT",t[t.FORCEWALL=37]="FORCEWALL",t[t.HEATBEAM=38]="HEATBEAM",t[t.MONSTER_HEATBEAM=39]="MONSTER_HEATBEAM",t[t.STEAM=40]="STEAM",t[t.BUBBLETRAIL2=41]="BUBBLETRAIL2",t[t.MOREBLOOD=42]="MOREBLOOD",t[t.HEATBEAM_SPARKS=43]="HEATBEAM_SPARKS",t[t.HEATBEAM_STEAM=44]="HEATBEAM_STEAM",t[t.CHAINFIST_SMOKE=45]="CHAINFIST_SMOKE",t[t.ELECTRIC_SPARKS=46]="ELECTRIC_SPARKS",t[t.TRACKER_EXPLOSION=47]="TRACKER_EXPLOSION",t[t.TELEPORT_EFFECT=48]="TELEPORT_EFFECT",t[t.DBALL_GOAL=49]="DBALL_GOAL",t[t.WIDOWBEAMOUT=50]="WIDOWBEAMOUT",t[t.NUKEBLAST=51]="NUKEBLAST",t[t.WIDOWSPLASH=52]="WIDOWSPLASH",t[t.EXPLOSION1_BIG=53]="EXPLOSION1_BIG",t[t.EXPLOSION1_NP=54]="EXPLOSION1_NP",t[t.FLECHETTE=55]="FLECHETTE",t[t.BLUEHYPERBLASTER_KEX=56]="BLUEHYPERBLASTER_KEX",t[t.BFG_ZAP=57]="BFG_ZAP",t[t.BERSERK_SLAM=58]="BERSERK_SLAM",t[t.GRAPPLE_CABLE_2=59]="GRAPPLE_CABLE_2",t[t.POWER_SPLASH=60]="POWER_SPLASH",t[t.LIGHTNING_BEAM=61]="LIGHTNING_BEAM",t[t.EXPLOSION1_NL=62]="EXPLOSION1_NL",t[t.EXPLOSION2_NL=63]="EXPLOSION2_NL",t))(U||{});var nh=64;var Kg=12,Yg=9,pM=Math.ceil(Kg*Yg/16),qg=23,Zg=2,gM=Math.ceil(qg*Zg/16);function ih(t,e){t.writeByte(e.msec),t.writeByte(e.buttons),t.writeAngle16(e.angles.x),t.writeAngle16(e.angles.y),t.writeAngle16(e.angles.z),t.writeShort(e.forwardmove),t.writeShort(e.sidemove),t.writeShort(e.upmove),t.writeByte(e.impulse),t.writeByte(0)}var jg=[0,145,227,114,7,150,228,117,14,159,237,124,9,152,234,123,28,141,255,110,27,138,248,105,18,131,241,96,21,132,246,103,56,169,219,74,63,174,220,77,54,167,213,68,49,160,210,67,36,181,199,86,35,178,192,81,42,187,201,88,45,188,206,95,112,225,147,2,119,230,148,5,126,239,157,12,121,232,154,11,108,253,143,30,107,250,136,25,98,243,129,16,101,244,134,23,72,217,171,58,79,222,172,61,70,215,165,52,65,208,162,51,84,197,183,38,83,194,176,33,90,203,185,40,93,204,190,47,224,113,3,146,231,118,4,149,238,127,13,156,233,120,10,155,252,109,31,142,251,106,24,137,242,99,17,128,245,100,22,135,216,73,59,170,223,78,60,173,214,71,53,164,209,64,50,163,196,85,39,182,195,82,32,177,202,91,41,184,205,92,46,191,144,1,115,226,151,6,116,229,158,15,125,236,153,8,122,235,140,29,111,254,139,26,104,249,130,19,97,240,133,20,102,247,168,57,75,218,175,62,76,221,166,55,69,212,161,48,66,211,180,37,86,199,179,34,80,193,186,43,89,200,189,44,94,207];function ah(t){let e=0;for(let r=0;r<t.length;r++)e=jg[(e^t[r])&255];return e}var St=1,wt=2,Mt=4,At=8,Et=16,Tt=32,ro=64,Mr=128,ai=256,Lt=512,Pt=1024,Rt=2048,Ye=4096,Ar=8192,qe=16384,Er=32768,Ze=65536,Ct=1<<17,je=1<<18,Qe=1<<19,Bt=1<<20,Ft=1<<21,It=1<<22,Tr=1<<23,pr=1<<24,Je=1<<25,Dt=1<<26,kt=1<<27,Lr=1<<28,Pr=1<<29,Rr=1<<30,Ni=-2147483648,_n=1,Sn=2,wn=4;var Mn=class{constructor(t){t instanceof Uint8Array?this.view=new DataView(t.buffer,t.byteOffset,t.byteLength):this.view=new DataView(t),this.offset=0,this.length=this.view.byteLength}getPosition(){return this.offset}getReadPosition(){return this.offset}getLength(){return this.length}getRemaining(){return this.length-this.offset}seek(t){if(t<0||t>this.length)throw new Error(`Seek out of bounds: ${t} (length: ${this.length})`);this.offset=t}setReadPosition(t){this.seek(t)}hasMore(){return this.offset<this.length}hasBytes(t){return this.offset+t<=this.length}readChar(){let t=this.view.getInt8(this.offset);return this.offset+=1,t}readByte(){let t=this.view.getUint8(this.offset);return this.offset+=1,t}readShort(){let t=this.view.getInt16(this.offset,!0);return this.offset+=2,t}readUShort(){let t=this.view.getUint16(this.offset,!0);return this.offset+=2,t}readLong(){let t=this.view.getInt32(this.offset,!0);return this.offset+=4,t}readULong(){let t=this.view.getUint32(this.offset,!0);return this.offset+=4,t}readFloat(){let t=this.view.getFloat32(this.offset,!0);return this.offset+=4,t}readString(){let t="";for(;this.offset<this.length;){let e=this.readChar();if(e===-1||e===0)break;t+=String.fromCharCode(e)}return t}readStringLine(){let t="";for(;this.offset<this.length;){let e=this.readChar();if(e===-1||e===0||e===10)break;t+=String.fromCharCode(e)}return t}readCoord(){return this.readShort()*(1/8)}readAngle(){return this.readChar()*(360/256)}readAngle16(){return this.readShort()*360/65536}readData(t){if(this.offset+t>this.length)throw new Error(`Read out of bounds: ${this.offset+t} (length: ${this.length})`);let e=new Uint8Array(this.view.buffer,this.view.byteOffset+this.offset,t);return this.offset+=t,new Uint8Array(e)}readPos(t){t.x=this.readCoord(),t.y=this.readCoord(),t.z=this.readCoord()}readDir(t){let e=this.readByte();if(e>=162){t.x=0,t.y=0,t.z=0;return}let r=mr[e];t.x=r[0],t.y=r[1],t.z=r[2]}},oi=class{constructor(t=1400){typeof t=="number"?(this.buffer=new Uint8Array(t),this.fixed=!1):(this.buffer=t,this.fixed=!0),this.view=new DataView(this.buffer.buffer,this.buffer.byteOffset,this.buffer.byteLength),this.offset=0}ensureSpace(t){if(this.offset+t>this.buffer.byteLength){if(this.fixed)throw new Error(`Buffer overflow: capacity ${this.buffer.byteLength}, needed ${this.offset+t}`);let e=Math.max(this.buffer.byteLength*2,this.offset+t),r=new Uint8Array(e);r.set(this.buffer),this.buffer=r,this.view=new DataView(this.buffer.buffer,this.buffer.byteOffset,this.buffer.byteLength)}}writeByte(t){this.ensureSpace(1),this.view.setUint8(this.offset,t),this.offset+=1}writeBytes(t){this.ensureSpace(t.byteLength),this.buffer.set(t,this.offset),this.offset+=t.byteLength}writeChar(t){this.ensureSpace(1),this.view.setInt8(this.offset,t),this.offset+=1}writeShort(t){this.ensureSpace(2),this.view.setInt16(this.offset,t,!0),this.offset+=2}writeLong(t){this.ensureSpace(4),this.view.setInt32(this.offset,t,!0),this.offset+=4}writeFloat(t){this.ensureSpace(4),this.view.setFloat32(this.offset,t,!0),this.offset+=4}writeString(t){let e=t.length;this.ensureSpace(e+1);for(let r=0;r<e;r++)this.view.setUint8(this.offset+r,t.charCodeAt(r));this.view.setUint8(this.offset+e,0),this.offset+=e+1}writeCoord(t){this.writeShort(Math.trunc(t*8))}writeAngle(t){this.writeByte(Math.trunc(t*256/360)&255)}writeAngle16(t){this.writeShort(Math.trunc(t*65536/360)&65535)}writePos(t){this.writeCoord(t.x),this.writeCoord(t.y),this.writeCoord(t.z)}writeDir(t){let e=-1,r=0;if(t.x===0&&t.y===0&&t.z===0){this.writeByte(0);return}for(let n=0;n<mr.length;n++){let i=mr[n],a=t.x*i[0]+t.y*i[1]+t.z*i[2];a>e&&(e=a,r=n)}this.writeByte(r)}getData(){return this.buffer.slice(0,this.offset)}getBuffer(){return this.buffer}getOffset(){return this.offset}reset(){this.offset=0}},no=class{constructor(t=1024){this.buffer=new Uint8Array(t),this.view=new DataView(this.buffer.buffer),this.offset=0}ensureCapacity(t){if(this.offset+t>this.buffer.length){let e=Math.max(this.buffer.length*2,this.offset+t),r=new Uint8Array(e);r.set(this.buffer),this.buffer=r,this.view=new DataView(this.buffer.buffer)}}getData(){return this.buffer.slice(0,this.offset)}writeByte(t){this.ensureCapacity(1),this.view.setUint8(this.offset,t),this.offset+=1}writeChar(t){this.ensureCapacity(1),this.view.setInt8(this.offset,t),this.offset+=1}writeShort(t){this.ensureCapacity(2),this.view.setInt16(this.offset,t,!0),this.offset+=2}writeUShort(t){this.ensureCapacity(2),this.view.setUint16(this.offset,t,!0),this.offset+=2}writeLong(t){this.ensureCapacity(4),this.view.setInt32(this.offset,t,!0),this.offset+=4}writeFloat(t){this.ensureCapacity(4),this.view.setFloat32(this.offset,t,!0),this.offset+=4}writeString(t){let e=t.length+1;this.ensureCapacity(e);for(let r=0;r<t.length;r++)this.view.setUint8(this.offset+r,t.charCodeAt(r));this.view.setUint8(this.offset+t.length,0),this.offset+=e}writeData(t){this.ensureCapacity(t.length),this.buffer.set(t,this.offset),this.offset+=t.length}writeCoord(t){this.writeShort(Math.round(t*8))}writeAngle(t){this.writeByte(Math.round(t*256/360)&255)}writeAngle16(t){this.writeShort(Math.round(t*65536/360))}writeDir(t,e,r){let n=0,i=-999999,a=Math.sqrt(t*t+e*e+r*r);if(a>0){t/=a,e/=a,r/=a;for(let o=0;o<162;o++){let s=t*mr[o][0]+e*mr[o][1]+r*mr[o][2];s>i&&(i=s,n=o)}}this.writeByte(n)}},ni=class nt{constructor(){this.qport=0,this.incomingSequence=0,this.outgoingSequence=0,this.incomingAcknowledged=0,this.incomingReliableAcknowledged=!1,this.incomingReliableSequence=0,this.outgoingReliableSequence=0,this.reliableLength=0,this.fragmentSendOffset=0,this.fragmentBuffer=null,this.fragmentLength=0,this.fragmentReceived=0,this.lastReceived=0,this.lastSent=0,this.remoteAddress=null,this.reliableMessage=new oi(nt.MAX_RELIABLE_BUFFER);let e=Date.now();this.lastReceived=e,this.lastSent=e,this.qport=Math.floor(Math.random()*65536)}setup(e,r=null){this.qport=e,this.remoteAddress=r,this.reset()}reset(){this.incomingSequence=0,this.outgoingSequence=0,this.incomingAcknowledged=0,this.incomingReliableAcknowledged=!1,this.incomingReliableSequence=0,this.outgoingReliableSequence=0,this.reliableLength=0,this.reliableMessage.reset(),this.fragmentSendOffset=0,this.fragmentBuffer=null,this.fragmentLength=0,this.fragmentReceived=0,this.lastReceived=Date.now(),this.lastSent=Date.now()}transmit(e){this.outgoingSequence++,this.lastSent=Date.now();let r=0,n=!1,i=0;this.reliableLength>0&&(this.reliableLength>nt.FRAGMENT_SIZE?(n=!0,this.fragmentSendOffset>=this.reliableLength&&(this.fragmentSendOffset=0),r=this.reliableLength-this.fragmentSendOffset,r>nt.FRAGMENT_SIZE&&(r=nt.FRAGMENT_SIZE),i=this.fragmentSendOffset,this.fragmentSendOffset+=r):r=this.reliableLength);let a=nt.PACKET_HEADER,o=r>0?2+(n?8:0):0,s=e?e.length:0;a+o+r+s>nt.MAX_MSGLEN&&(s=nt.MAX_MSGLEN-a-o-r,s<0&&(s=0));let c=new ArrayBuffer(a+o+r+s),l=new DataView(c),u=new Uint8Array(c),d=this.outgoingSequence;r>0&&(d|=2147483648,(this.outgoingReliableSequence&1)!==0&&(d|=1073741824)),l.setUint32(0,d,!0);let f=this.incomingSequence;(this.incomingReliableSequence&1)!==0&&(f|=2147483648),l.setUint32(4,f,!0),l.setUint16(8,this.qport,!0);let h=a;if(r>0){let m=r;n&&(m|=32768),l.setUint16(h,m,!0),h+=2,n&&(l.setUint32(h,i,!0),h+=4,l.setUint32(h,this.reliableLength,!0),h+=4);let p=this.reliableMessage.getBuffer().subarray(i,i+r);u.set(p,h),h+=r}if(e&&s>0){let m=e.slice(0,s);u.set(m,h)}return u}process(e){if(e.length<4)return null;this.lastReceived=Date.now();let r=new DataView(e.buffer,e.byteOffset,e.byteLength),n=r.getUint32(0,!0);if(n===4294967295)return e.subarray(4);if(e.length<nt.PACKET_HEADER)return null;let i=r.getUint32(4,!0),a=r.getUint16(8,!0);if(this.qport!==a)return null;let o=n&1073741823;if((o-this.incomingSequence|0)<=0)return null;this.incomingSequence=o;let s=i&2147483647,c=(i&2147483648)!==0;if(s>this.incomingAcknowledged&&(this.incomingAcknowledged=s),this.reliableLength>0){let m=c?1:0,g=this.outgoingReliableSequence&1;m!==g&&(this.reliableLength=0,this.reliableMessage.reset(),this.outgoingReliableSequence^=1,this.fragmentSendOffset=0)}let l=(n&2147483648)!==0,u=(n&1073741824)!==0?1:0,d=nt.PACKET_HEADER,f=null;if(l){if(d+2>e.byteLength)return null;let m=r.getUint16(d,!0);d+=2;let g=(m&32768)!==0;m&=32767;let p=this.incomingReliableSequence&1;if(u===p)if(g){if(d+8>e.byteLength)return null;let y=r.getUint32(d,!0);d+=4;let v=r.getUint32(d,!0);if(d+=4,v>nt.MAX_RELIABLE_BUFFER)return console.warn(`NetChan: received invalid fragment total ${v} > ${nt.MAX_RELIABLE_BUFFER}`),null;if((!this.fragmentBuffer||this.fragmentBuffer.length!==v)&&(this.fragmentBuffer=new Uint8Array(v),this.fragmentLength=v,this.fragmentReceived=0),d+m>e.byteLength)return null;let b=e.subarray(d,d+m);y===this.fragmentReceived&&y+m<=v&&(this.fragmentBuffer.set(b,y),this.fragmentReceived+=m,this.fragmentReceived>=v&&(f=this.fragmentBuffer,this.incomingReliableSequence++,this.fragmentBuffer=null,this.fragmentLength=0,this.fragmentReceived=0))}else{if(this.incomingReliableSequence++,d+m>e.byteLength)return null;f=e.slice(d,d+m)}d+=m}let h=e.slice(d);if(f&&f.length>0){let m=f.length+h.length,g=new Uint8Array(m);return g.set(f,0),g.set(h,f.length),g}return h||new Uint8Array(0)}canSendReliable(){return this.reliableLength===0}writeReliableByte(e){if(this.reliableLength+1>nt.MAX_RELIABLE_BUFFER)throw new Error("NetChan reliable buffer overflow");this.reliableMessage.writeByte(e),this.reliableLength++}writeReliableShort(e){if(this.reliableLength+2>nt.MAX_RELIABLE_BUFFER)throw new Error("NetChan reliable buffer overflow");this.reliableMessage.writeShort(e),this.reliableLength+=2}writeReliableLong(e){if(this.reliableLength+4>nt.MAX_RELIABLE_BUFFER)throw new Error("NetChan reliable buffer overflow");this.reliableMessage.writeLong(e),this.reliableLength+=4}writeReliableString(e){let r=e.length+1;if(this.reliableLength+r>nt.MAX_RELIABLE_BUFFER)throw new Error("NetChan reliable buffer overflow");this.reliableMessage.writeString(e),this.reliableLength+=r}getReliableData(){return this.reliableLength===0?new Uint8Array(0):this.reliableMessage.getBuffer().subarray(0,this.reliableLength)}needsKeepalive(e){return e-this.lastSent>1e3}isTimedOut(e,r=3e4){return e-this.lastReceived>r}};ni.MAX_MSGLEN=1400;ni.FRAGMENT_SIZE=1024;ni.PACKET_HEADER=10;ni.HEADER_OVERHEAD=ni.PACKET_HEADER+2;ni.MAX_RELIABLE_BUFFER=262144;var oh=ni;var sh=(t=>(t[t.Bullets=0]="Bullets",t[t.Shells=1]="Shells",t[t.Rockets=2]="Rockets",t[t.Grenades=3]="Grenades",t[t.Cells=4]="Cells",t[t.Slugs=5]="Slugs",t[t.MagSlugs=6]="MagSlugs",t[t.Trap=7]="Trap",t[t.Flechettes=8]="Flechettes",t[t.Tesla=9]="Tesla",t[t.Disruptor=10]="Disruptor",t[t.Prox=11]="Prox",t[t.Nuke=12]="Nuke",t[t.Rounds=13]="Rounds",t))(sh||{}),yM=Object.keys(sh).length/2;var io=32,Cr=(t=>(t[t.Auto=0]="Auto",t[t.Weapon=1]="Weapon",t[t.Voice=2]="Voice",t[t.Item=3]="Item",t[t.Body=4]="Body",t[t.Aux=5]="Aux",t[t.Footstep=6]="Footstep",t[t.Aux3=7]="Aux3",t[t.NoPhsAdd=8]="NoPhsAdd",t[t.Reliable=16]="Reliable",t[t.ForcePos=32]="ForcePos",t))(Cr||{}),Au=-1,ao=0,Eu=1,Tu=2,Lu=3,Gi=80,Pu=.003;function Vi(t){return t*.001}function si(t){let e=Vi(t);return e<=0?Number.POSITIVE_INFINITY:Gi+1/e}var oo=class{constructor({name:e,defaultValue:r,description:n,flags:i=tl.None,onChange:a}){this.modifiedCount=0;this.name=e,this.defaultValue=r,this.description=n,this.flags=i,this._value=r,this.onChange=a}get string(){return this._value}getString(){return this.string}get number(){return Number(this._value)}getFloat(){return this.number}get integer(){return Math.trunc(this.number)}getInt(){return this.integer}get boolean(){return!!this.integer}getBoolean(){return this.boolean}set(e){if(this.flags&tl.Latch){if(e===this._value){this.latched=void 0;return}if(this.latched===e)return;this.latched!==e&&(this.latched=e);return}this.apply(e)}reset(){this.latched=void 0,this.apply(this.defaultValue)}applyLatched(){if(this.latched===void 0)return!1;let e=this.latched;return this.latched=void 0,e===this._value?!1:(this.apply(e),!0)}apply(e){if(this._value===e)return;let r=this._value;this._value=e,this.modifiedCount+=1,this.onChange?.(this,r)}},Hi=class{constructor(){this.cvars=new Map}register(e){let r=this.cvars.get(e.name);if(r)return r;let n=e.onChange,i=(o,s)=>{n?.(o,s),this.onCvarChange?.(o.name,o.string)},a=new oo({...e,onChange:i});return this.cvars.set(e.name,a),a}get(e){return this.cvars.get(e)}getCvar(e){return this.get(e)}setValue(e,r){let n=this.get(e);if(!n)throw new Error(`Unknown cvar: ${e}`);return n.set(r),n}setCvar(e,r){this.setValue(e,r)}resetAll(){for(let e of this.cvars.values())e.reset()}applyLatched(){let e=!1;for(let r of this.cvars.values())e=r.applyLatched()||e;return e}list(){return[...this.cvars.values()].sort((e,r)=>e.name.localeCompare(r.name))}listCvars(){return this.list().map(e=>({name:e.name,value:e.string,defaultValue:e.defaultValue,flags:e.flags,description:e.description}))}};var Wi=class{constructor(e,r,n={}){this.game=e;this.client=r;this.started=!1;this.paused_=!1;this.commands=new Oi;this.cvars=new Hi;this.stepSimulation=e=>{this.previousFrame=this.latestFrame,this.latestFrame=this.game.frame(e,this.latestCommand)};this.renderClient=e=>{this.client&&(this.latestCommand=this.client.render({...e,previous:this.previousFrame,latest:this.latestFrame}))};let i=n.loop?.now?.()??Date.now();this.startTimeMs=n.startTimeMs??n.loop?.startTimeMs??i,this.loop=new ri({simulate:this.stepSimulation,render:this.renderClient},{...n.loop,startTimeMs:this.startTimeMs}),this.commands.registerAutocompleteProvider(()=>this.cvars.list().map(a=>a.name))}start(){if(!this.started){try{this.latestFrame=this.game.init(this.startTimeMs)??this.latestFrame,this.client?.init(this.latestFrame)}catch(e){throw this.game.shutdown(),this.client?.shutdown(),e}this.started=!0,this.paused_=!1,this.loop.start()}}stop(){this.started&&(this.loop.stop(),this.client?.shutdown(),this.game.shutdown(),this.previousFrame=void 0,this.latestFrame=void 0,this.started=!1,this.paused_=!1)}setPaused(e){this.paused_=e,e?this.loop.stop():this.started&&this.loop.start()}get paused(){return this.paused_}pump(e){this.loop.pump(e)}getLatestFrame(){return this.latestFrame}isRunning(){return this.loop.isRunning()}};var Xi=class{constructor(e){this.registry=e.registry,this.system=e.system,this.music=e.music,this.client=e.client}soundindex(e){return this.registry.registerName(e)}sound(e,r,n,i,a,o){this.system.play({entity:e,channel:r,soundIndex:n,volume:i,attenuation:a,timeOffsetMs:o}),this.triggerSubtitle(n)}positioned_sound(e,r,n,i){this.system.positionedSound(e,r,n,i),this.triggerSubtitle(r)}loop_sound(e,r,n,i,a){let o=this.system.play({entity:e,channel:r,soundIndex:n,volume:i,attenuation:a,looping:!0});return this.triggerSubtitle(n),o}stop_entity_sounds(e){this.system.stopEntitySounds(e)}setPlaybackRate(e){this.system.setPlaybackRate(e)}set_listener(e){this.system.setListener(e)}play_music(e,r=!0){return this.music?this.music.play(e,{loop:r}):Promise.resolve()}play_track(e,r=!0){return this.music?this.music.playTrack(e):Promise.resolve()}pause_music(){this.music?.pause()}resume_music(){return this.music?.resume()??Promise.resolve()}stop_music(){this.music?.stop()}set_music_volume(e){this.music?.setVolume(e)}play_ambient(e,r,n){this.system.ambientSound(e,r,n),this.triggerSubtitle(r)}play_channel(e){this.system.play({...e}),this.triggerSubtitle(e.soundIndex)}triggerSubtitle(e){if(!this.client)return;let r=this.registry.getName(e);if(!r)return;let n=r.match(/\[(.*?)\]/);n&&this.client.showSubtitle(n[1],r)}};var so=class{constructor(e,r){this.engine=e;this.host=r;this.started=!1}start(){this.started||(this.engine.init(),this.host.start(),this.started=!0)}stop(){this.started&&(this.host.stop(),this.engine.shutdown(),this.started=!1)}pump(e){this.host.pump(e)}getLatestFrame(){return this.host.getLatestFrame()}isRunning(){return this.started&&this.host.isRunning()}};function lh(t,e,r,n,i){let a=new Xi({...n,client:r}),o=new Wi(e,r,i);return{runtime:new so(t,o),audio:a}}function Qg(t){if(t<0||t>=ee.MaxConfigStrings)throw new RangeError(`Configstring index ${t} is out of range (0-${ee.MaxConfigStrings-1})`)}function ch(t,e){let r=rh(t);if(e.length>r)throw new RangeError(`Configstring ${t} exceeds maximum length (${e.length} > ${r}); limit is ${to} chars per slot`)}var $i=class{constructor(){this.values=new Map;this.modelCursor=ee.Models;this.soundCursor=ee.Sounds;this.imageCursor=ee.Images;this.lightCursor=ee.Lights;this.shadowLightCursor=ee.ShadowLights;this.itemCursor=ee.Items;this.playerSkinCursor=ee.PlayerSkins;this.generalCursor=ee.General}set(e,r){return Qg(e),ch(e,r),this.values.set(e,r),e}get(e){return this.values.get(e)}getName(e){return this.get(e)}getAll(){let e=new Array(th).fill("");for(let[r,n]of this.values.entries())e[r]=n;return e}modelIndex(e){return this.register(e,ee.Models,vu,"modelCursor")}soundIndex(e){return this.register(e,ee.Sounds,nl,"soundCursor")}findSoundIndex(e){for(let r=ee.Sounds;r<ee.Sounds+nl;r+=1)if(this.values.get(r)===e)return r}imageIndex(e){return this.register(e,ee.Images,_u,"imageCursor")}lightIndex(e){return this.register(e,ee.Lights,xu,"lightCursor")}shadowLightIndex(e){return this.register(e,ee.ShadowLights,Mu,"shadowLightCursor")}itemIndex(e){return this.register(e,ee.Items,Su,"itemCursor")}playerSkinIndex(e){return this.register(e,ee.PlayerSkins,rl,"playerSkinCursor")}generalIndex(e){return this.register(e,ee.General,wu,"generalCursor")}register(e,r,n,i){for(let s=r;s<r+n;s+=1)if(this.values.get(s)===e)return s;let a=this[i],o=r+n;if(a>=o)throw new RangeError(`Out of configstring slots for range starting at ${r}`);return ch(a,e),this.values.set(a,e),this[i]=a+1,a}};var Jg="PACK";function ey(t,e,r){let n=[];for(let i=0;i<r;i+=1){let a=t.getUint8(e+i);if(a===0)break;n.push(a)}return String.fromCharCode(...n)}function Te(t){return t.replace(/\\/g,"/").replace(/^\/+/,"").toLowerCase()}function ty(){let t=new Uint32Array(256);for(let e=0;e<256;e+=1){let r=e;for(let n=0;n<8;n+=1)r=(r&1)!==0?3988292384^r>>>1:r>>>1;t[e]=r>>>0}return t}var ry=ty();function uh(t){let e=4294967295;for(let r=0;r<t.length;r+=1){let n=t[r];e=ry[(e^n)&255]^e>>>8}return(e^4294967295)>>>0}var ze=class extends Error{},Ki=class t{constructor(e,r,n,i){this.name=e;this.buffer=r;this.entries=new Map(n.map(a=>[a.name,a])),this.checksum=i,this.size=r.byteLength}static fromArrayBuffer(e,r){let n=new DataView(r);if(r.byteLength<12)throw new ze("PAK buffer too small to contain header");let i=String.fromCharCode(n.getUint8(0),n.getUint8(1),n.getUint8(2),n.getUint8(3));if(i!==Jg)throw new ze(`Invalid PAK header magic: ${i}`);let a=n.getInt32(4,!0),o=n.getInt32(8,!0);if(a<12)throw new ze(`Invalid directory offset: ${a}`);if(o<0||o%64!==0)throw new ze(`Invalid directory length: ${o}`);if(a+o>r.byteLength)throw new ze("Directory exceeds buffer length");let c=o/64,l=[],u=new Map;for(let d=0;d<c;d+=1){let f=a+d*64,h=ey(n,f,56),m=Te(h),g=n.getInt32(f+56,!0),p=n.getInt32(f+60,!0);if(g<0||p<0||g+p>r.byteLength)throw new ze(`Invalid entry bounds for ${h||"<unnamed>"} (offset=${g}, length=${p})`);if(!m)throw new ze(`Entry ${d} has an empty name`);let y={name:m,offset:g,length:p};u.set(m,y)}return l.push(...u.values()),new t(e,r,l,uh(new Uint8Array(r)))}getEntry(e){return this.entries.get(Te(e))}listEntries(){return Array.from(this.entries.values())}list(){return Array.from(this.entries.keys())}readFile(e){let r=this.getEntry(e);if(!r)throw new ze(`File not found in PAK: ${e}`);return new Uint8Array(this.buffer,r.offset,r.length)}validate(){return{checksum:this.checksum,entries:this.listEntries()}}};function dh(t){return uh(new Uint8Array(t))}var ny="PACK",fh=12,Ru=64;function hh(t){return t.replace(/\\/g,"/").replace(/^\/+/,"").toLowerCase()}var il=class{constructor(e){this.source=e;this.entries=null}async readDirectory(){if(this.entries)return Array.from(this.entries.values());let e=await this.readChunk(0,fh),r=new DataView(e),n=String.fromCharCode(r.getUint8(0),r.getUint8(1),r.getUint8(2),r.getUint8(3));if(n!==ny)throw new ze(`Invalid PAK header magic: ${n}`);let i=r.getInt32(4,!0),a=r.getInt32(8,!0);if(i<fh)throw new ze(`Invalid directory offset: ${i}`);if(a<0||a%Ru!==0)throw new ze(`Invalid directory length: ${a}`);let o=await this.readChunk(i,a),s=new DataView(o),c=a/Ru,l=new Map;for(let u=0;u<c;u++){let d=u*Ru,f=this.readCString(s,d,56),h=hh(f),m=s.getInt32(d+56,!0),g=s.getInt32(d+60,!0);m<0||g<0||m+g>this.source.size,h&&l.set(h,{name:h,offset:m,length:g})}return this.entries=l,Array.from(l.values())}async readFile(e){let r=await this.getEntry(e);if(!r)throw new ze(`File not found in PAK: ${e}`);return this.source.slice(r.offset,r.offset+r.length).stream()}async getFileBlob(e){let r=await this.getEntry(e);if(!r)throw new ze(`File not found in PAK: ${e}`);return this.source.slice(r.offset,r.offset+r.length)}async getEntry(e){return this.entries||await this.readDirectory(),this.entries.get(hh(e))}async readChunk(e,r){let n=this.source.slice(e,e+r);return"arrayBuffer"in n?await n.arrayBuffer():new Response(n).arrayBuffer()}readCString(e,r,n){let i=[];for(let a=0;a<n;a+=1){let o=e.getUint8(r+a);if(o===0)break;i.push(o)}return String.fromCharCode(...i)}};var Cu=12,mh=64,al=class t{constructor(){this.entries=new Map}addFile(e,r){let n=Te(e);if(n.length>56)throw new Error(`Path too long: '${n}' (max 56 chars)`);this.entries.set(n,r)}removeFile(e){return this.entries.delete(Te(e))}build(){let e=0;for(let f of this.entries.values())e+=f.byteLength;let r=this.entries.size*mh,n=Cu+e+r,i=new Uint8Array(n),a=new DataView(i.buffer);a.setUint8(0,80),a.setUint8(1,65),a.setUint8(2,67),a.setUint8(3,75);let o=Cu+e;a.setInt32(4,o,!0),a.setInt32(8,r,!0);let s=Cu,c=new Map,l=Array.from(this.entries.keys()).sort();for(let f of l){let h=this.entries.get(f);c.set(f,s),i.set(h,s),s+=h.byteLength}let u=o,d=new TextEncoder;for(let f of l){let h=this.entries.get(f),m=d.encode(f);if(m.length>56)throw new Error(`Path too long after encoding: ${f}`);for(let g=0;g<56;g++)g<m.length?a.setUint8(u+g,m[g]):a.setUint8(u+g,0);a.setInt32(u+56,c.get(f),!0),a.setInt32(u+60,h.byteLength,!0),u+=mh}return i}static buildFromEntries(e){let r=new t;for(let[n,i]of e)r.addFile(n,i);return r.build()}};var Bu=(o=>(o.Texture="texture",o.Sound="sound",o.Model="model",o.Map="map",o.Sprite="sprite",o.ConfigString="configString",o))(Bu||{}),ol=class{constructor(){this.tracking=!1;this.entries=[];this.currentFrame=0;this.currentTime=0}startTracking(){this.tracking=!0,this.entries=[]}stopTracking(){this.tracking=!1;let e={byFrame:new Map,byTime:new Map,uniqueResources:new Map};for(let r of this.entries){e.byFrame.has(r.frame)||e.byFrame.set(r.frame,[]),e.byFrame.get(r.frame).push(r),e.byTime.has(r.timestamp)||e.byTime.set(r.timestamp,[]),e.byTime.get(r.timestamp).push(r);let n=`${r.type}:${r.path}`;e.uniqueResources.has(n)||e.uniqueResources.set(n,r)}return e}recordLoad(e,r,n,i){this.tracking&&this.entries.push({type:e,path:r,timestamp:this.currentTime,frame:this.currentFrame,size:n,pakSource:i})}setCurrentFrame(e){this.currentFrame=e}setCurrentTime(e){this.currentTime=e}};var sl=class{constructor(e=[]){this.mounts=[];this.files=new Map;e.forEach(r=>this.mountPak(r))}mountPak(e,r=0){let n=this.mounts.findIndex(i=>i.pak===e);n!==-1&&this.mounts.splice(n,1),this.mounts.push({pak:e,priority:r}),this.mounts.sort((i,a)=>a.priority-i.priority);for(let i of e.listEntries()){let a=Te(i.name),o={archive:e,entry:i,priority:r};this.files.has(a)||this.files.set(a,[]);let s=this.files.get(a),c=s.findIndex(l=>l.archive===e);c!==-1&&s.splice(c,1),s.unshift(o),s.sort((l,u)=>u.priority-l.priority)}return e}setPriority(e,r){this.mountPak(e,r)}getPaks(){return[...this.mounts].sort((e,r)=>e.priority-r.priority)}get mountedPaks(){return this.mounts.map(e=>e.pak)}hasFile(e){return this.files.has(Te(e))}getSource(e){let r=this.files.get(Te(e));if(!(!r||r.length===0))return r[0]}stat(e){let r=this.getSource(e);if(r)return{path:r.entry.name,size:r.entry.length,sourcePak:r.archive.name}}getFileMetadata(e){let r=this.getSource(e);if(r)return{path:r.entry.name,size:r.entry.length,sourcePak:r.archive.name,offset:r.entry.offset}}async readFile(e){let r=this.getSource(e);if(!r)throw new Error(`File not found in VFS: ${e}`);return r.archive.readFile(e)}async readBinaryFile(e){return this.readFile(e)}streamFile(e,r=1024*1024){let n=this.getSource(e);if(!n)throw new Error(`File not found in VFS: ${e}`);let{archive:i}=n,a=i.readFile(e),o=0,s=a.length;return new ReadableStream({pull(c){if(o>=s){c.close();return}let l=Math.min(o+r,s),u=a.slice(o,l);o=l,c.enqueue(u)}})}async readTextFile(e){let r=await this.readFile(e);return new TextDecoder("utf-8").decode(r)}list(e=""){let r=Te(e).replace(/\/+$|^\//g,""),n=[],i=new Set,a=r?`${r}/`:"";for(let[o,s]of this.files){let c=s[0];if(r&&!c.entry.name.startsWith(a))continue;let l=r?c.entry.name.slice(a.length):c.entry.name,u=l.indexOf("/");u===-1?n.push({path:c.entry.name,size:c.entry.length,sourcePak:c.archive.name}):i.add(l.slice(0,u))}return n.sort((o,s)=>o.path.localeCompare(s.path)),{files:n,directories:[...i].sort()}}async listDirectory(e){return this.list(e).files}findByExtension(e){if(e instanceof RegExp)return this.searchFiles(e);if(Array.isArray(e))return this.listByExtension(e);let r=e.startsWith(".")?e.toLowerCase():`.${e.toLowerCase()}`,n=[];for(let[i,a]of this.files){let o=a[0];o.entry.name.toLowerCase().endsWith(r)&&n.push({path:o.entry.name,size:o.entry.length,sourcePak:o.archive.name})}return n.sort((i,a)=>i.path.localeCompare(a.path))}listByExtension(e){let r=new Set(e.map(i=>i.startsWith(".")?i.toLowerCase():`.${i.toLowerCase()}`)),n=[];for(let[i,a]of this.files){let o=a[0],s=o.entry.name.toLowerCase();for(let c of r)if(s.endsWith(c)){n.push({path:o.entry.name,size:o.entry.length,sourcePak:o.archive.name});break}}return n.sort((i,a)=>i.path.localeCompare(a.path))}searchFiles(e){let r=[];for(let[n,i]of this.files){let a=i[0];e.test(a.entry.name)&&r.push({path:a.entry.name,size:a.entry.length,sourcePak:a.archive.name})}return r.sort((n,i)=>n.path.localeCompare(i.path))}getPakInfo(){return this.mounts.map(e=>({filename:e.pak.name,entryCount:e.pak.listEntries().length,totalSize:e.pak.size,priority:e.priority}))}getDirectoryTree(){let e={name:"",path:"",files:[],directories:[]},r=new Map;r.set("",e);let n=Array.from(this.files.values()).map(i=>{let a=i[0];return{path:a.entry.name,size:a.entry.length,sourcePak:a.archive.name}}).sort((i,a)=>i.path.localeCompare(a.path));for(let i of n){let a=i.path.split("/"),o=a.pop(),s="",c=e;for(let l of a){let u=s;s=s?`${s}/${l}`:l;let d=r.get(s);d||(d={name:l,path:s,files:[],directories:[]},c.directories.push(d),r.set(s,d)),c=d}c.files.push(i)}return e}};var Fu=Object.freeze([{name:"pak0.pak",checksum:2378051181,description:"Base game assets"},{name:"pak0.pak@baseq2",checksum:2378051181,description:"Base game assets (baseq2)"},{name:"pak0.pak@rogue",checksum:3373211245,description:"Ground Zero (rogue) mission pack"},{name:"pak0.pak@xatrix",checksum:1358269824,description:"The Reckoning (xatrix) mission pack"}]),li=class extends Error{constructor(r){super(r.status==="unknown"?`Unknown PAK not allowed: ${r.name}`:`PAK checksum mismatch for ${r.name}`);this.result=r;this.name="PakValidationError"}},ll=class{constructor(e=Fu){this.known=new Map;e.forEach(r=>this.known.set(this.normalizePakName(r.name),r))}validateArchive(e,r){let n=this.normalizePakName(r??("name"in e?e.name:"unknown")),i=e.checksum,a="size"in e?e.size:void 0,o=this.known.get(n);return o?o.checksum!==i?{name:n,checksum:i,expectedChecksum:o.checksum,status:"mismatch",size:a,description:o.description}:{name:n,checksum:i,expectedChecksum:o.checksum,status:"valid",size:a,description:o.description}:{name:n,checksum:i,status:"unknown",size:a}}assertValid(e,r){let n=this.validateArchive(e,r);if(n.status==="mismatch")throw new li(n);return n}normalizePakName(e){let r=Te(e),n=r.split("/"),i=n.pop()??r,a=n.pop();return a?`${i}@${a}`:i}};var An=class extends Error{constructor(r,n){super(`Failed to ingest PAK: ${r}`);this.file=r;this.name="PakIngestionError",n instanceof Error&&n.stack&&(this.stack=n.stack),this.cause=n}};async function iy(t,e){if(typeof t.arrayBuffer=="function"){let r=await t.arrayBuffer();return e?.({file:"blob",loadedBytes:r.byteLength,totalBytes:r.byteLength,state:"reading"}),r}if(typeof FileReader<"u")return new Promise((r,n)=>{let i=new FileReader;i.onerror=()=>n(i.error??new Error("Unknown FileReader error")),i.onprogress=a=>{e?.({file:"blob",loadedBytes:a.loaded,totalBytes:a.total||t.size,state:"reading"})},i.onload=()=>{let a=i.result;a instanceof ArrayBuffer?r(a):n(new Error("Unexpected FileReader result"))},i.readAsArrayBuffer(t)});if(typeof Response<"u"){let r=await new Response(t).arrayBuffer();return e?.({file:"blob",loadedBytes:r.byteLength,totalBytes:r.byteLength,state:"reading"}),r}if(typeof t.stream=="function"){let r=t.stream().getReader(),n=[],i=0;for(;;){let{done:s,value:c}=await r.read();if(s)break;if(!c)continue;let l=c;n.push(l),i+=l.byteLength,e?.({file:"blob",loadedBytes:i,totalBytes:t.size,state:"reading"})}let a=new Uint8Array(i),o=0;for(let s of n)a.set(s,o),o+=s.byteLength;return a.buffer}throw new An("blob",new Error("Unsupported Blob type"))}async function ay(t,e){if(t.data instanceof ArrayBuffer)return e?.({file:t.name,loadedBytes:t.data.byteLength,totalBytes:t.data.byteLength,state:"reading"}),t.data;if(t.data instanceof Blob){let n=t.data.size;return iy(t.data,i=>e?.({...i,file:t.name,totalBytes:n}))}let r=t.data.buffer.slice(t.data.byteOffset,t.data.byteOffset+t.data.byteLength);return e?.({file:t.name,loadedBytes:r.byteLength,totalBytes:r.byteLength,state:"reading"}),r}async function cl(t,e,r){let n=typeof r=="function"?{onProgress:r}:r??{},i=n.persistIndexes??!!n.pakIndexStore,a=n.enforceValidation??!!n.validator,o=n.allowUnknownPaks??!0,s=n.stopOnError??!1,c=[];for(let l of e)try{let u=await ay(l,n.onProgress),d=Ki.fromArrayBuffer(l.name,u),f=n.validator?.validateArchive(d);if(f){n.onValidationResult?.(f);let h=f.status==="mismatch",m=f.status==="unknown";if(h&&a||m&&!o){let g=new li(f);if(n.onError?.(l.name,g),s)throw new An(l.name,g);c.push({archive:d,mounted:!1,validation:f});continue}}if(t.mountPak(d),i&&n.pakIndexStore)try{await n.pakIndexStore.persist(d)}catch(h){if(n.onError?.(l.name,h),s)throw new An(l.name,h)}n.onProgress?.({file:l.name,loadedBytes:u.byteLength,totalBytes:u.byteLength,state:"parsed"}),c.push({archive:d,mounted:!0,validation:f})}catch(u){if(n.onProgress?.({file:l.name,loadedBytes:0,totalBytes:0,state:"error"}),n.onError?.(l.name,u),s)throw new An(l.name,u)}return c}var En=class{constructor(e,r=1/0,n=()=>0){this._capacity=e;this._maxMemory=r;this.sizeCalculator=n;this.map=new Map;this.currentMemoryUsage=0;if(e<=0)throw new RangeError("LRU cache capacity must be greater than zero")}get size(){return this.map.size}get memoryUsage(){return this.currentMemoryUsage}get capacity(){return this._capacity}set capacity(e){if(e<=0)throw new RangeError("LRU cache capacity must be greater than zero");this._capacity=e,this.evict()}get maxMemory(){return this._maxMemory}set maxMemory(e){this._maxMemory=e,this.evict()}has(e){return this.map.has(e)}get(e){let r=this.map.get(e);if(r!==void 0)return this.map.delete(e),this.map.set(e,r),r}set(e,r){let n=this.sizeCalculator(r);this.map.has(e)&&this.delete(e),this.map.set(e,r),this.currentMemoryUsage+=n,this.evict()}delete(e){let r=this.map.get(e);return r!==void 0?(this.currentMemoryUsage-=this.sizeCalculator(r),this.map.delete(e)):!1}clear(){this.map.clear(),this.currentMemoryUsage=0}entries(){return Array.from(this.map.entries()).reverse().map(([e,r])=>({key:e,value:r}))}evict(){for(;this.map.size>this._capacity;){let e=this.map.keys().next();if(!e.done)this.delete(e.value);else break}for(;this.currentMemoryUsage>this._maxMemory&&this.map.size>0;){let e=this.map.keys().next();if(!e.done)this.delete(e.value);else break}}};function oy(t){return Array.isArray(t)?t:Array.from(t)}function Iu(t){return oy(t).map(e=>({name:e.name,data:e}))}async function ph(t,e,r){let n=Iu(e);return cl(t,n,r??{})}function gh(t,e){let r=i=>{i.preventDefault(),i.dataTransfer?.dropEffect&&(i.dataTransfer.dropEffect="copy")},n=i=>{i.preventDefault();let a=i.dataTransfer?.files;a&&a.length>0&&e(Array.from(a))};return t.addEventListener("dragover",r),t.addEventListener("drop",n),()=>{t.removeEventListener("dragover",r),t.removeEventListener("drop",n)}}function yh(t,e){let r=n=>{let i=n.target;!i||!i.files||i.files.length===0||(e(i.files),i.value="")};return t.addEventListener("change",r),()=>t.removeEventListener("change",r)}var sy="IBSP",ly=38,xh=19,cy=8+xh*8,Du=(b=>(b[b.Entities=0]="Entities",b[b.Planes=1]="Planes",b[b.Vertices=2]="Vertices",b[b.Visibility=3]="Visibility",b[b.Nodes=4]="Nodes",b[b.TexInfo=5]="TexInfo",b[b.Faces=6]="Faces",b[b.Lighting=7]="Lighting",b[b.Leafs=8]="Leafs",b[b.LeafFaces=9]="LeafFaces",b[b.LeafBrushes=10]="LeafBrushes",b[b.Edges=11]="Edges",b[b.SurfEdges=12]="SurfEdges",b[b.Models=13]="Models",b[b.Brushes=14]="Brushes",b[b.BrushSides=15]="BrushSides",b[b.Pop=16]="Pop",b[b.Areas=17]="Areas",b[b.AreaPortals=18]="AreaPortals",b))(Du||{}),le=class extends Error{},Yi=class{constructor(e,r={}){this.vfs=e;this.options=r}async load(e){let r=await this.vfs.readFile(e),n=new Uint8Array(r.byteLength);if(n.set(new Uint8Array(r)),this.options.useWorker&&typeof Worker<"u")try{let i=await this.parseInWorker(n.buffer);return vh(i)}catch(i){console.warn("BSP worker parsing failed, falling back to main thread",i)}return lo(n.buffer)}parseInWorker(e){return new Promise((r,n)=>{if(!this.options.workerPath){n(new Error("No worker path provided"));return}let i=new Worker(this.options.workerPath,{type:"module"});i.onmessage=a=>{let{type:o,data:s,message:c}=a.data;o==="success"?(r(this.rehydrateData(s)),i.terminate()):(n(new Error(c)),i.terminate())},i.onerror=a=>{n(a),i.terminate()},i.postMessage(e,[e])})}rehydrateData(e){if(e.entities&&!e.entities.getUniqueClassnames){let r=e.entities;r.getUniqueClassnames=function(){let n=new Set;for(let i of this.entities)i.classname&&n.add(i.classname);return Array.from(n).sort()}}return e}};function lo(t){let e=uy(t);return vh(e)}function vh(t){return{...t,pickEntity(e){let r=null,n=1/0;for(let i of t.entities.entities){let a=i.properties.model;if(!a||!a.startsWith("*"))continue;let o=parseInt(a.substring(1),10);if(isNaN(o)||o<0||o>=t.models.length)continue;let s=t.models[o],c=dy(e.origin,e.direction,s.mins,s.maxs);c!==null&&c<n&&(n=c,r={entity:i,model:s,distance:c})}return r},findLeaf(e){let n=t.models[0].headNode;for(;n>=0;){let i=t.nodes[n],a=t.planes[i.planeIndex];a.normal[0]*e[0]+a.normal[1]*e[1]+a.normal[2]*e[2]-a.dist>=0?n=i.children[0]:n=i.children[1]}return t.leafs[-(n+1)]},calculatePVS(e){let r=this.findLeaf(e);if(!(r.cluster===-1||!t.visibility)&&!(r.cluster<0||r.cluster>=t.visibility.clusters.length))return t.visibility.clusters[r.cluster].pvs}}}function uy(t){if(t.byteLength<cy)throw new le("BSP too small to contain header");let e=new DataView(t),r=String.fromCharCode(e.getUint8(0),e.getUint8(1),e.getUint8(2),e.getUint8(3));if(r!==sy)throw new le(`Invalid BSP magic ${r}`);let n=e.getInt32(4,!0);if(n!==ly)throw new le(`Unsupported BSP version ${n}`);let i=new Map;for(let A=0;A<xh;A+=1){let T=e.getInt32(8+A*8,!0),M=e.getInt32(12+A*8,!0);if(T<0||M<0||T+M>t.byteLength)throw new le(`Invalid lump bounds for index ${A}`);i.set(A,{offset:T,length:M})}let a={version:n,lumps:i},o=fy(t,i.get(0)),s=my(t,i.get(1)),c=py(t,i.get(2)),l=gy(t,i.get(4)),u=yy(t,i.get(5)),d=by(t,i.get(6)),f=new Uint8Array(t,i.get(7).offset,i.get(7).length),h=Ry(d,i.get(7)),m=xy(t,i.get(8)),g=vy(t,i.get(11)),p=_y(t,i.get(12)),y=Sy(t,i.get(13)),v=wy(t,i.get(14)),b=My(t,i.get(15)),x=Ly(t,i.get(9),i.get(10),m),_=Py(t,i.get(3)),w=Ay(t,i.get(17)),S=Ey(t,i.get(18));return{header:a,entities:o,planes:s,vertices:c,nodes:l,texInfo:u,faces:d,lightMaps:f,lightMapInfo:h,leafs:m,leafLists:x,edges:g,surfEdges:p,models:y,brushes:v,brushSides:b,visibility:_,areas:w,areaPortals:S}}function dy(t,e,r,n){let i=0,a=1/0;for(let o=0;o<3;o++)if(Math.abs(e[o])<1e-8){if(t[o]<r[o]||t[o]>n[o])return null}else{let s=1/e[o],c=(r[o]-t[o])*s,l=(n[o]-t[o])*s;if(c>l){let u=c;c=l,l=u}if(i=Math.max(i,c),a=Math.min(a,l),i>a)return null}return i}function fy(t,e){let r=new TextDecoder().decode(new Uint8Array(t,e.offset,e.length)),n=hy(r),i=n.find(a=>a.classname==="worldspawn");return{raw:r,entities:n,worldspawn:i,getUniqueClassnames(){let a=new Set;for(let o of n)o.classname&&a.add(o.classname);return Array.from(a).sort()}}}function hy(t){let e=[],r=/\{([^}]*)\}/gms,n;for(;(n=r.exec(t))!==null;){let i=n[1],a={},o=/"([^\"]*)"\s+"([^\"]*)"/g,s;for(;(s=o.exec(i))!==null;)a[s[1]]=s[2];e.push({classname:a.classname,properties:a})}return e}function my(t,e){let r=new DataView(t,e.offset,e.length),n=e.length/20;if(n%1!==0)throw new le("Plane lump has invalid length");let i=[];for(let a=0;a<n;a+=1){let o=[r.getFloat32(a*20,!0),r.getFloat32(a*20+4,!0),r.getFloat32(a*20+8,!0)],s=r.getFloat32(a*20+12,!0),c=r.getInt32(a*20+16,!0);i.push({normal:o,dist:s,type:c})}return i}function py(t,e){let r=new DataView(t,e.offset,e.length),n=e.length/12;if(n%1!==0)throw new le("Vertex lump has invalid length");let i=[];for(let a=0;a<n;a+=1)i.push([r.getFloat32(a*12,!0),r.getFloat32(a*12+4,!0),r.getFloat32(a*12+8,!0)]);return i}function gy(t,e){let r=new DataView(t,e.offset,e.length),n=28,i=e.length/n;if(i%1!==0)throw new le("Node lump has invalid length");let a=[];for(let o=0;o<i;o+=1){let s=o*n,c=r.getInt32(s,!0),l=[r.getInt32(s+4,!0),r.getInt32(s+8,!0)],u=[r.getInt16(s+12,!0),r.getInt16(s+14,!0),r.getInt16(s+16,!0)],d=[r.getInt16(s+18,!0),r.getInt16(s+20,!0),r.getInt16(s+22,!0)],f=r.getUint16(s+24,!0),h=r.getUint16(s+26,!0);a.push({planeIndex:c,children:l,mins:u,maxs:d,firstFace:f,numFaces:h})}return a}function yy(t,e){let r=new DataView(t,e.offset,e.length),n=76,i=e.length/n;if(i%1!==0)throw new le("TexInfo lump has invalid length");let a=[];for(let o=0;o<i;o+=1){let s=o*n,c=[r.getFloat32(s,!0),r.getFloat32(s+4,!0),r.getFloat32(s+8,!0)],l=r.getFloat32(s+12,!0),u=[r.getFloat32(s+16,!0),r.getFloat32(s+20,!0),r.getFloat32(s+24,!0)],d=r.getFloat32(s+28,!0),f=r.getInt32(s+32,!0),h=r.getInt32(s+36,!0),m=new Uint8Array(t,e.offset+s+40,32),g=new TextDecoder("utf-8").decode(m).replace(/\0.*$/,""),p=r.getInt32(s+72,!0);a.push({s:c,sOffset:l,t:u,tOffset:d,flags:f,value:h,texture:g,nextTexInfo:p})}return a}function by(t,e){let r=new DataView(t,e.offset,e.length),n=20,i=e.length/n;if(i%1!==0)throw new le("Face lump has invalid length");let a=[];for(let o=0;o<i;o+=1){let s=o*n,c=r.getUint16(s,!0),l=r.getInt16(s+2,!0),u=r.getInt32(s+4,!0),d=r.getInt16(s+8,!0),f=r.getInt16(s+10,!0),h=[r.getUint8(s+12),r.getUint8(s+13),r.getUint8(s+14),r.getUint8(s+15)],m=r.getInt32(s+16,!0);a.push({planeIndex:c,side:l,firstEdge:u,numEdges:d,texInfo:f,styles:h,lightOffset:m})}return a}function xy(t,e){let r=new DataView(t,e.offset,e.length),n=28,i=e.length/n;if(i%1!==0)throw new le("Leaf lump has invalid length");let a=[];for(let o=0;o<i;o+=1){let s=o*n,c=r.getInt32(s,!0),l=r.getInt16(s+4,!0),u=r.getInt16(s+6,!0),d=[r.getInt16(s+8,!0),r.getInt16(s+10,!0),r.getInt16(s+12,!0)],f=[r.getInt16(s+14,!0),r.getInt16(s+16,!0),r.getInt16(s+18,!0)],h=r.getUint16(s+20,!0),m=r.getUint16(s+22,!0),g=r.getUint16(s+24,!0),p=r.getUint16(s+26,!0);a.push({contents:c,cluster:l,area:u,mins:d,maxs:f,firstLeafFace:h,numLeafFaces:m,firstLeafBrush:g,numLeafBrushes:p})}return a}function vy(t,e){let r=new DataView(t,e.offset,e.length),n=4,i=e.length/n;if(i%1!==0)throw new le("Edge lump has invalid length");let a=[];for(let o=0;o<i;o+=1){let s=o*n;a.push({vertices:[r.getUint16(s,!0),r.getUint16(s+2,!0)]})}return a}function _y(t,e){let r=e.length/4;if(r%1!==0)throw new le("SurfEdge lump has invalid length");let n=new DataView(t,e.offset,e.length),i=new Int32Array(r);for(let a=0;a<r;a+=1)i[a]=n.getInt32(a*4,!0);return i}function Sy(t,e){let r=new DataView(t,e.offset,e.length),n=48;if(e.length%n!==0)throw new le("Model lump has invalid length");let i=e.length/n,a=[];for(let o=0;o<i;o+=1){let s=o*n,c=[r.getFloat32(s,!0),r.getFloat32(s+4,!0),r.getFloat32(s+8,!0)],l=[r.getFloat32(s+12,!0),r.getFloat32(s+16,!0),r.getFloat32(s+20,!0)],u=[r.getFloat32(s+24,!0),r.getFloat32(s+28,!0),r.getFloat32(s+32,!0)],d=r.getInt32(s+36,!0),f=r.getInt32(s+40,!0),h=r.getInt32(s+44,!0);a.push({mins:c,maxs:l,origin:u,headNode:d,firstFace:f,numFaces:h})}return a}function wy(t,e){let r=new DataView(t,e.offset,e.length),n=12,i=e.length/n;if(i%1!==0)throw new le("Brush lump has invalid length");let a=[];for(let o=0;o<i;o+=1){let s=o*n;a.push({firstSide:r.getInt32(s,!0),numSides:r.getInt32(s+4,!0),contents:r.getInt32(s+8,!0)})}return a}function My(t,e){let r=new DataView(t,e.offset,e.length),n=4,i=e.length/n;if(i%1!==0)throw new le("Brush side lump has invalid length");let a=[];for(let o=0;o<i;o+=1){let s=o*n;a.push({planeIndex:r.getUint16(s,!0),texInfo:r.getInt16(s+2,!0)})}return a}function Ay(t,e){let r=new DataView(t,e.offset,e.length),n=8,i=e.length/n;if(i%1!==0)throw new le("Area lump has invalid length");let a=[];for(let o=0;o<i;o+=1){let s=o*n,c=r.getInt32(s,!0),l=r.getInt32(s+4,!0);a.push({numAreaPortals:c,firstAreaPortal:l})}return a}function Ey(t,e){return Ty(t,e)}function Ty(t,e){let r=new DataView(t,e.offset,e.length),n=8,i=e.length/n;if(i%1!==0)throw new le("AreaPortal lump has invalid length");let a=[];for(let o=0;o<i;o+=1){let s=o*n,c=r.getInt32(s,!0),l=r.getInt32(s+4,!0);a.push({portalNumber:c,otherArea:l})}return a}function Ly(t,e,r,n){let i=[],a=[],o=e.length/2,s=r.length/2,c=new DataView(t,e.offset,e.length),l=new DataView(t,r.offset,r.length);for(let u of n){if(u.firstLeafFace+u.numLeafFaces>o)throw new le("Leaf faces reference data past lump bounds");if(u.firstLeafBrush+u.numLeafBrushes>s)throw new le("Leaf brushes reference data past lump bounds");let d=[];for(let h=0;h<u.numLeafFaces;h+=1)d.push(c.getUint16((u.firstLeafFace+h)*2,!0));let f=[];for(let h=0;h<u.numLeafBrushes;h+=1)f.push(l.getUint16((u.firstLeafBrush+h)*2,!0));i.push(d),a.push(f)}return{leafFaces:i,leafBrushes:a}}function Py(t,e){if(e.length===0)return;if(e.length<4)throw new le("Visibility lump too small");let r=new DataView(t,e.offset,e.length),n=r.getInt32(0,!0),i=4+n*8;if(n<0||i>e.length)throw new le("Visibility lump truncated");let a=4,o=[];for(let s=0;s<n;s+=1){let c=r.getInt32(a,!0),l=r.getInt32(a+4,!0);a+=8;let u=e.offset+c,d=e.offset+l,f=e.offset+e.length;if(c<0||l<0||u>=f||d>=f)throw new le("Visibility offsets out of range");o.push({pvs:bh(t,u,n,e),phs:bh(t,d,n,e)})}return{numClusters:n,clusters:o}}function bh(t,e,r,n){let i=Math.ceil(r/8),a=new Uint8Array(i),o=new Uint8Array(t),s=e,c=0,l=n.offset+n.length;for(;c<i;){if(s>=l)throw new le("Visibility data truncated");let u=o[s++];if(u!==0){a[c++]=u;continue}if(s>=l)throw new le("Visibility run exceeds lump bounds");let d=o[s++];for(let f=0;f<d&&c<i;f+=1)a[c++]=0}return a}function Ry(t,e){return t.map(r=>{if(!(r.lightOffset<0))return{offset:r.lightOffset,length:Math.max(0,e.length-r.lightOffset)}})}function ul(t,e,r){if(t.lightOffset<0||t.lightOffset>=e.byteLength)return;let n=e.byteLength-t.lightOffset,i=Math.min(r?.length??n,n);if(!(i<=0))return e.subarray(t.lightOffset,t.lightOffset+i)}var Cy=844121161,By=8,_h=68,it=class extends Error{},qi=class{constructor(e){this.vfs=e;this.cache=new Map}async load(e){if(this.cache.has(e))return this.cache.get(e);let r=await this.vfs.readFile(e),n=new Uint8Array(r.byteLength);n.set(r);let i=ku(n.buffer);return this.cache.set(e,i),i}get(e){return this.cache.get(e)}};function Sh(t,e,r){let n=[];for(let i=0;i<r;i+=1){let a=t.getUint8(e+i);if(a===0)break;n.push(a)}return String.fromCharCode(...n)}function co(t,e,r,n){if(r!==0&&(e<_h||e+r>t.byteLength))throw new it(`${n} section is out of bounds`)}function Fy(t){if(t.byteLength<_h)throw new it("MD2 buffer too small to contain header");let e=new DataView(t),r=e.getInt32(0,!0),n=e.getInt32(4,!0);if(r!==Cy)throw new it(`Invalid MD2 ident: ${r}`);if(n!==By)throw new it(`Unsupported MD2 version: ${n}`);let i={ident:r,version:n,skinWidth:e.getInt32(8,!0),skinHeight:e.getInt32(12,!0),frameSize:e.getInt32(16,!0),numSkins:e.getInt32(20,!0),numVertices:e.getInt32(24,!0),numTexCoords:e.getInt32(28,!0),numTriangles:e.getInt32(32,!0),numGlCommands:e.getInt32(36,!0),numFrames:e.getInt32(40,!0),offsetSkins:e.getInt32(44,!0),offsetTexCoords:e.getInt32(48,!0),offsetTriangles:e.getInt32(52,!0),offsetFrames:e.getInt32(56,!0),offsetGlCommands:e.getInt32(60,!0),offsetEnd:e.getInt32(64,!0),magic:r},a=40+i.numVertices*4;if(i.frameSize!==a)throw new it(`Unexpected frame size ${i.frameSize}, expected ${a}`);if(i.offsetEnd>t.byteLength)throw new it("MD2 offset_end exceeds buffer length");return i}function Iy(t,e){let r=e.numSkins*64;co(t,e.offsetSkins,r,"skins");let n=new DataView(t,e.offsetSkins,r),i=[];for(let a=0;a<e.numSkins;a+=1)i.push({name:Sh(n,a*64,64)});return i}function Dy(t,e){let r=e.numTexCoords*4;co(t,e.offsetTexCoords,r,"texcoords");let n=new DataView(t,e.offsetTexCoords,r),i=[];for(let a=0;a<e.numTexCoords;a+=1){let o=a*4;i.push({s:n.getInt16(o,!0),t:n.getInt16(o+2,!0)})}return i}function ky(t,e){let r=e.numTriangles*12;co(t,e.offsetTriangles,r,"triangles");let n=new DataView(t,e.offsetTriangles,r),i=[];for(let a=0;a<e.numTriangles;a+=1){let o=a*12,s=[n.getUint16(o,!0),n.getUint16(o+2,!0),n.getUint16(o+4,!0)],c=[n.getUint16(o+6,!0),n.getUint16(o+8,!0),n.getUint16(o+10,!0)];if(s.some(l=>l>=e.numVertices)||c.some(l=>l>=e.numTexCoords))throw new it("Triangle references out of range vertex or texcoord");i.push({vertexIndices:s,texCoordIndices:c})}return i}function Uy(t,e){let r=e.numFrames*e.frameSize;co(t,e.offsetFrames,r,"frames");let n=[];for(let i=0;i<e.numFrames;i+=1){let a=e.offsetFrames+i*e.frameSize,o=new DataView(t,a,e.frameSize),s={x:o.getFloat32(0,!0),y:o.getFloat32(4,!0),z:o.getFloat32(8,!0)},c={x:o.getFloat32(12,!0),y:o.getFloat32(16,!0),z:o.getFloat32(20,!0)},l=Sh(o,24,16),u=[],d=1/0,f=1/0,h=1/0,m=-1/0,g=-1/0,p=-1/0;for(let y=0;y<e.numVertices;y+=1){let v=40+y*4,b=o.getUint8(v)*s.x+c.x,x=o.getUint8(v+1)*s.y+c.y,_=o.getUint8(v+2)*s.z+c.z;b<d&&(d=b),x<f&&(f=x),_<h&&(h=_),b>m&&(m=b),x>g&&(g=x),_>p&&(p=_);let w={x:b,y:x,z:_},S=o.getUint8(v+3),A=mr[S];if(!A)throw new it(`Invalid normal index ${S} in frame ${l}`);let T={x:A[0],y:A[1],z:A[2]};u.push({position:w,normalIndex:S,normal:T})}n.push({name:l,vertices:u,minBounds:{x:d,y:f,z:h},maxBounds:{x:m,y:g,z:p}})}return n}function zy(t,e){let r=e.numGlCommands*4;if(co(t,e.offsetGlCommands,r,"gl commands"),r===0)return[];let n=new DataView(t,e.offsetGlCommands,r),i=[],a=0;for(;;){if(a+4>r)throw new it("GL command list ended unexpectedly");let o=n.getInt32(a,!0);if(a+=4,o===0)break;let s=Math.abs(o),c=[],l=s*12;if(a+l>r)throw new it("GL command vertex block exceeds buffer");for(let u=0;u<s;u+=1){let d=n.getFloat32(a,!0),f=n.getFloat32(a+4,!0),h=n.getInt32(a+8,!0);if(a+=12,h<0||h>=e.numVertices)throw new it("GL command references invalid vertex index");c.push({s:d,t:f,vertexIndex:h})}i.push({mode:o>0?"strip":"fan",vertices:c})}if(a!==r)throw new it("GL command list did not consume expected data");return i}function ku(t){let e=Fy(t),r=Iy(t,e),n=Dy(t,e),i=ky(t,e),a=Uy(t,e),o=zy(t,e);return{header:e,skins:r,texCoords:n,triangles:i,frames:a,glCommands:o}}function wh(t){let e=[],r=0;for(;r<t.length;){let n=t[r].name,i=n.replace(/\d+$/,"")||n,a=r;for(;a+1<t.length&&(t[a+1].name.replace(/\d+$/,"")||t[a+1].name)===i;)a+=1;e.push({name:i,firstFrame:r,lastFrame:a}),r=a+1}return e}var Mh=860898377,Oy=15,er=class extends Error{constructor(e){super(e),this.name="Md3ParseError"}};function uo(t,e,r){let n=new Uint8Array(t.buffer,t.byteOffset+e,r);return new TextDecoder("utf-8").decode(n).replace(/\0.*$/,"").trim()}function Ny(t){let e=(t>>8&255)*(2*Math.PI/255),r=(t&255)*(2*Math.PI/255),n=Math.sin(r);return{x:Math.cos(e)*n,y:Math.sin(e)*n,z:Math.cos(r)}}function dl(t,e,r,n){if(e<0||e+r>n)throw new er(`${t} exceeds buffer bounds`)}function Gy(t){let e=t.getInt32(0,!0);if(e!==Mh)throw new er(`Invalid MD3 ident: ${e}`);let r=t.getInt32(4,!0);if(r!==Oy)throw new er(`Unsupported MD3 version: ${r}`);let n=uo(t,8,64),i=t.getInt32(72,!0),a=t.getInt32(76,!0),o=t.getInt32(80,!0),s=t.getInt32(84,!0),c=t.getInt32(88,!0),l=t.getInt32(92,!0),u=t.getInt32(96,!0),d=t.getInt32(100,!0),f=t.getInt32(104,!0);if(a<=0||s<0||o<0)throw new er("Invalid MD3 counts");return{ident:e,version:r,name:n,flags:i,numFrames:a,numTags:o,numSurfaces:s,numSkins:c,ofsFrames:l,ofsTags:u,ofsSurfaces:d,ofsEnd:f,magic:e}}function Vy(t,e){let r=[];dl("Frames",e.ofsFrames,e.numFrames*56,t.byteLength);for(let i=0;i<e.numFrames;i+=1){let a=e.ofsFrames+i*56;r.push({minBounds:{x:t.getFloat32(a,!0),y:t.getFloat32(a+4,!0),z:t.getFloat32(a+8,!0)},maxBounds:{x:t.getFloat32(a+12,!0),y:t.getFloat32(a+16,!0),z:t.getFloat32(a+20,!0)},localOrigin:{x:t.getFloat32(a+24,!0),y:t.getFloat32(a+28,!0),z:t.getFloat32(a+32,!0)},radius:t.getFloat32(a+36,!0),name:uo(t,a+40,16)})}return r}function Hy(t,e){let r=[],i=e.numFrames*e.numTags*112;dl("Tags",e.ofsTags,i,t.byteLength);for(let a=0;a<e.numFrames;a+=1){let o=[];for(let s=0;s<e.numTags;s+=1){let c=e.ofsTags+(a*e.numTags+s)*112,l=c+64,u=l+12;o.push({name:uo(t,c,64),origin:{x:t.getFloat32(l,!0),y:t.getFloat32(l+4,!0),z:t.getFloat32(l+8,!0)},axis:[{x:t.getFloat32(u,!0),y:t.getFloat32(u+4,!0),z:t.getFloat32(u+8,!0)},{x:t.getFloat32(u+12,!0),y:t.getFloat32(u+16,!0),z:t.getFloat32(u+20,!0)},{x:t.getFloat32(u+24,!0),y:t.getFloat32(u+28,!0),z:t.getFloat32(u+32,!0)}]})}r.push(o)}return r}function Wy(t,e){let r=t.getInt32(e,!0);if(r!==Mh)throw new er(`Invalid surface ident at ${e}: ${r}`);let n=uo(t,e+4,64),i=t.getInt32(e+68,!0),a=t.getInt32(e+72,!0),o=t.getInt32(e+76,!0),s=t.getInt32(e+80,!0),c=t.getInt32(e+84,!0),l=t.getInt32(e+88,!0),u=t.getInt32(e+92,!0),d=t.getInt32(e+96,!0),f=t.getInt32(e+100,!0),h=t.getInt32(e+104,!0);if(a<=0||s<=0||c<=0)throw new er(`Invalid surface counts for ${n}`);let m=h;dl(`Surface ${n}`,e,m,t.byteLength);let g=[],p=e+l;for(let S=0;S<c;S+=1){let A=p+S*12;g.push({indices:[t.getInt32(A,!0),t.getInt32(A+4,!0),t.getInt32(A+8,!0)]})}let y=[],v=e+u;for(let S=0;S<o;S+=1){let A=v+S*68;y.push({name:uo(t,A,64),shaderIndex:t.getInt32(A+64,!0)})}let b=[],x=e+d;for(let S=0;S<s;S+=1){let A=x+S*8;b.push({s:t.getFloat32(A,!0),t:t.getFloat32(A+4,!0)})}let _=[],w=e+f;for(let S=0;S<a;S+=1){let A=[];for(let T=0;T<s;T+=1){let M=w+(S*s+T)*8,P=t.getInt16(M,!0)/64,I=t.getInt16(M+2,!0)/64,D=t.getInt16(M+4,!0)/64,B=t.getUint16(M+6,!0);A.push({position:{x:P,y:I,z:D},latLng:B,normal:Ny(B)})}_.push(A)}return{surface:{name:n,flags:i,numFrames:a,shaders:y,triangles:g,texCoords:b,vertices:_},nextOffset:e+h}}function Uu(t){if(t.byteLength<108)throw new er("MD3 buffer too small for header");let e=new DataView(t),r=Gy(e);dl("MD3 end",r.ofsEnd,0,t.byteLength);let n=Vy(e,r),i=Hy(e,r),a=[],o=r.ofsSurfaces;for(let s=0;s<r.numSurfaces;s+=1){let{surface:c,nextOffset:l}=Wy(e,o);a.push(c),o=l}if(o!==r.ofsEnd)throw new er("Surface parsing did not reach ofsEnd");return{header:r,frames:n,tags:i,surfaces:a}}var Zi=class{constructor(e){this.vfs=e;this.cache=new Map}async load(e){if(this.cache.has(e))return this.cache.get(e);let r=await this.vfs.readFile(e),n=Uu(r.slice().buffer);return this.cache.set(e,n),n}get(e){return this.cache.get(e)}};var Xy=844317769,$y=2,Ah=64,Eh=12,Tn=class extends Error{};function Ky(t,e,r){let n=[];for(let i=0;i<r;i+=1){let a=t.getUint8(e+i);if(a===0)break;n.push(a)}return String.fromCharCode(...n)}function zu(t){if(t.byteLength<Eh)throw new Tn("Sprite buffer too small to contain header");let e=new DataView(t),r=e.getInt32(0,!0),n=e.getInt32(4,!0),i=e.getInt32(8,!0);if(r!==Xy)throw new Tn(`Invalid Sprite ident: ${r}`);if(n!==$y)throw new Tn(`Unsupported Sprite version: ${n}`);let a=[],o=16+Ah,s=Eh;for(let c=0;c<i;c+=1){if(s+o>t.byteLength)throw new Tn("Sprite frame data exceeds buffer length");let l=e.getInt32(s,!0),u=e.getInt32(s+4,!0),d=e.getInt32(s+8,!0),f=e.getInt32(s+12,!0),h=Ky(e,s+16,Ah);a.push({width:l,height:u,originX:d,originY:f,name:h}),s+=o}return{ident:r,version:n,numFrames:i,frames:a}}var ji=class{constructor(e){this.vfs=e}async load(e){let r=await this.vfs.readFile(e),n=new Uint8Array(r.byteLength);return n.set(r),zu(n.buffer)}};function Th(t,e){let r=(t.sequence.end-t.sequence.start+1)/t.sequence.fps,n=t.sequence.loop!==!1,i=t.time+e;return n?i=(i%r+r)%r:i>r&&(i=r),{...t,time:Math.max(0,Math.min(i,r))}}function Lh(t){let e=t.sequence.end-t.sequence.start+1,r=1/t.sequence.fps,n=t.sequence.loop!==!1,i=t.time/r;if(!n&&i>=e)return{frame0:t.sequence.end,frame1:t.sequence.end,lerp:0};let a=n?i%e:Math.min(i,e-1),o=Math.floor(a),s=t.sequence.start+o,c=o+1>=e?n?t.sequence.start:t.sequence.end:s+1,l=!n&&o>=e-1?0:a-o;return{frame0:s,frame1:c,lerp:l}}function Ph(t){return{sequence:t,time:0}}function Rh(t,e,r){return{x:t.x+(e.x-t.x)*r,y:t.y+(e.y-t.y)*r,z:t.z+(e.z-t.z)*r}}var fo=class extends Error{constructor(e){super(e),this.name="WalParseError"}};function fl(t){if(t.byteLength<100)throw new fo("WAL buffer too small");let e=new DataView(t),r=new Uint8Array(t,0,32),n=new TextDecoder("utf-8").decode(r).replace(/\0.*$/,"").trim(),i=e.getInt32(32,!0),a=e.getInt32(36,!0),o=[e.getInt32(40,!0),e.getInt32(44,!0),e.getInt32(48,!0),e.getInt32(52,!0)],s=new Uint8Array(t,56,32),c=new TextDecoder("utf-8").decode(s).replace(/\0.*$/,"").trim(),l=e.getInt32(88,!0),u=e.getInt32(92,!0),d=e.getInt32(96,!0);if(i<=0||a<=0)throw new fo("Invalid WAL dimensions");let f=[],h=i,m=a;for(let g=0;g<o.length;g+=1){let p=o[g],y=Math.max(1,h*m|0);if(p<=0||p+y>t.byteLength)throw new fo(`Invalid WAL mip offset for level ${g}`);let v=new Uint8Array(t,p,y);f.push({level:g,width:h,height:m,data:v}),h=Math.max(1,h>>1),m=Math.max(1,m>>1)}return{name:n,width:i,height:a,mipmaps:f,animName:c,flags:l,contents:u,value:d}}var ci=class extends Error{constructor(e){super(e),this.name="PcxParseError"}};function ho(t){if(t.byteLength<128)throw new ci("PCX buffer too small for header");let e=new DataView(t),r=e.getUint8(0),n=e.getUint8(2),i=e.getUint8(3),a=e.getUint16(4,!0),o=e.getUint16(6,!0),s=e.getUint16(8,!0),c=e.getUint16(10,!0);if(r!==10||n!==1)throw new ci("Unsupported PCX encoding");if(i!==8)throw new ci("Only 8bpp PCX files are supported");let l=s-a+1,u=c-o+1,d=e.getUint16(66,!0),f=t.byteLength-769;if(f<128||new DataView(t,f,1).getUint8(0)!==12)throw new ci("Missing PCX palette");let h=new Uint8Array(t,f+1,768),m=new Uint8Array(t,128,f-128),g=new Uint8Array(l*u),p=0,y=0;for(let v=0;v<u;v+=1){let b=0;for(;b<d&&p<m.length;){let x=1,_=m[p++];if((_&192)===192){if(x=_&63,p>=m.length)throw new ci("Unexpected end of PCX RLE data");_=m[p++]}for(let w=0;w<x&&b<d;w+=1)b<l&&(g[y++]=_),b+=1}}return{width:l,height:u,bitsPerPixel:i,pixels:g,palette:h}}function hl(t){let e=new Uint8Array(t.width*t.height*4);for(let r=0;r<t.pixels.length;r+=1){let n=t.pixels[r],i=n*3,a=r*4;e[a]=t.palette[i],e[a+1]=t.palette[i+1],e[a+2]=t.palette[i+2],e[a+3]=n===255?0:255}return e}var qr=class extends Error{constructor(e){super(e),this.name="TgaParseError"}};function Ou(t){let e=new DataView(t);if(t.byteLength<18)throw new qr("Buffer too small for TGA header");let r=e.getUint8(0),n=e.getUint8(1),i=e.getUint8(2),a=e.getUint16(12,!0),o=e.getUint16(14,!0),s=e.getUint8(16),c=e.getUint8(17);if(i!==2&&i!==10&&i!==3&&i!==11)throw new qr(`Unsupported TGA image type: ${i} (only RGB/Grayscale supported)`);if(s!==24&&s!==32&&s!==8)throw new qr(`Unsupported pixel depth: ${s} (only 8, 24, 32 bpp supported)`);let l=i>=9,u=i===3||i===11,d=s/8,f=18+r;if(n===1){let b=e.getUint16(5,!0),x=e.getUint8(7);f+=b*(x/8)}let h=a*o,m=new Uint8Array(h*4),g=(c&32)!==0,p=0,y=new Uint8Array(t),v=b=>{if(u){let x=y[f++];m[b]=x,m[b+1]=x,m[b+2]=x,m[b+3]=255}else{let x=y[f++],_=y[f++],w=y[f++],S=s===32?y[f++]:255;m[b]=w,m[b+1]=_,m[b+2]=x,m[b+3]=S}};if(l){let b=0;for(;b<h;){if(f>=t.byteLength)throw new qr("Unexpected end of TGA RLE data");let x=y[f++],_=(x&127)+1,w=(x&128)!==0;if(b+_>h)throw new qr("TGA RLE packet exceeds image bounds");if(w){let S=u?y[f]:y[f+2],A=u?y[f]:y[f+1],T=y[f],M=u?255:s===32?y[f+3]:255;f+=d;for(let P=0;P<_;P++){let I=(b+P)*4;m[I]=S,m[I+1]=A,m[I+2]=T,m[I+3]=M}}else for(let S=0;S<_;S++)v((b+S)*4);b+=_}}else for(let b=0;b<h;b++){if(f>=t.byteLength)throw new qr("Unexpected end of TGA data");v(b*4)}if(!g){let b=a*4,x=new Uint8Array(b);for(let _=0;_<o/2;_++){let w=_*b,S=(o-1-_)*b;x.set(m.subarray(w,w+b)),m.set(m.subarray(S,S+b),w),m.set(x,S)}}return{width:a,height:o,bitsPerPixel:32,pixels:m}}function Yy(t){let e=0;for(let r of t.levels)e+=r.rgba.byteLength;return e}var Qi=class{constructor(e={}){this.cache=new En(e.capacity??128,e.maxMemory??256*1024*1024,Yy)}get size(){return this.cache.size}get memoryUsage(){return this.cache.memoryUsage}get(e){return this.cache.get(e.toLowerCase())}set(e,r){this.cache.set(e.toLowerCase(),r)}clear(){this.cache.clear()}get capacity(){return this.cache.capacity}set capacity(e){this.cache.capacity=e}get maxMemory(){return this.cache.maxMemory}set maxMemory(e){this.cache.maxMemory=e}};function Nu(t,e){let r=[];for(let n of t.mipmaps){let i=new Uint8Array(n.width*n.height*4);for(let a=0;a<n.data.length;a+=1){let o=n.data[a],s=o*3,c=a*4;i[c]=e[s],i[c+1]=e[s+1],i[c+2]=e[s+2],i[c+3]=o===255?0:255}r.push({level:n.level,width:n.width,height:n.height,rgba:i})}return{width:t.width,height:t.height,levels:r,source:"wal"}}function ml(t){let e=hl(t),r={level:0,width:t.width,height:t.height,rgba:e};return{width:t.width,height:t.height,levels:[r],source:"pcx"}}function Ch(t){let e={level:0,width:t.width,height:t.height,rgba:t.pixels};return{width:t.width,height:t.height,levels:[e],source:"tga"}}function pl(t,e){return Nu(fl(t),e)}var ui=class extends Error{constructor(e){super(e),this.name="WavParseError"}};function Gu(t,e,r){return new TextDecoder("ascii").decode(new Uint8Array(t.buffer,t.byteOffset+e,r))}function gl(t){if(t.byteLength<44)throw new ui("WAV buffer too small");let e=new DataView(t);if(Gu(e,0,4)!=="RIFF"||Gu(e,8,4)!=="WAVE")throw new ui("Invalid WAV header");let r=12,n=-1,i=-1,a=0,o=0;for(;r+8<=t.byteLength;){let m=Gu(e,r,4),g=e.getUint32(r+4,!0),p=r+8;m==="fmt "?(n=p,a=g):m==="data"&&(i=p,o=g),r=p+g}if(n===-1||i===-1)throw new ui("Missing fmt or data chunk");let s=e.getUint16(n,!0),c=e.getUint16(n+2,!0),l=e.getUint32(n+4,!0),u=e.getUint16(n+14,!0);if(s!==1)throw new ui("Only PCM WAV is supported");let d=u/8,f=o/(d*c),h=new Float32Array(f*c);for(let m=0;m<f;m+=1)for(let g=0;g<c;g+=1){let p=m*c+g,y=i+p*d,v=0;if(u===8)v=e.getUint8(y),h[p]=(v-128)/128;else if(u===16)v=e.getInt16(y,!0),h[p]=v/32768;else if(u===24){let b=e.getUint8(y),x=e.getUint8(y+1),_=e.getInt8(y+2);v=b|x<<8|_<<16,h[p]=v/8388608}else throw new ui(`Unsupported bitsPerSample: ${u}`)}return{sampleRate:l,channels:c,bitsPerSample:u,samples:h}}var qy=(t,e=4294967295,r=79764919)=>{let n=new Int32Array(256),i,a,o,s=e;for(i=0;i<256;i++){for(o=i<<24,a=8;a>0;--a)o=2147483648&o?o<<1^r:o<<1;n[i]=o}for(i=0;i<t.length;i++)s=s<<8^n[255&(s>>24^t[i])];return s};var Vu=(t,e=qy)=>{let r=p=>new Uint8Array(p.length/2).map(((y,v)=>parseInt(p.substring(2*v,2*(v+1)),16))),n=p=>r(p)[0],i=new Map;[,8364,,8218,402,8222,8230,8224,8225,710,8240,352,8249,338,,381,,,8216,8217,8220,8221,8226,8211,8212,732,8482,353,8250,339,,382,376].forEach(((p,y)=>i.set(p,y)));let a=new Uint8Array(t.length),o,s,c,l=!1,u=0,d=42,f=t.length>13&&t.substring(0,9)==="dynEncode",h=0;f&&(h=11,s=n(t.substring(9,h)),s<=1&&(h+=2,d=n(t.substring(11,h))),s===1&&(h+=8,c=(p=>new DataView(r(p).buffer).getInt32(0,!0))(t.substring(13,h))));let m=256-d;for(let p=h;p<t.length;p++)if(o=t.charCodeAt(p),o!==61||l){if(o===92&&p<t.length-5&&f){let y=t.charCodeAt(p+1);y!==117&&y!==85||(o=parseInt(t.substring(p+2,p+6),16),p+=5)}if(o>255){let y=i.get(o);y&&(o=y+127)}l&&(l=!1,o-=64),a[u++]=o<d&&o>0?o+m:o-d}else l=!0;let g=a.subarray(0,u);if(f&&s===1){let p=e(g);if(p!==c){let y="Decode failed crc32 validation";throw console.error("`simple-yenc`\n",y+`
1
+ "use strict";var Quake2Engine=(()=>{var cg=Object.create;var Zs=Object.defineProperty;var ug=Object.getOwnPropertyDescriptor;var dg=Object.getOwnPropertyNames;var fg=Object.getPrototypeOf,hg=Object.prototype.hasOwnProperty;var mg=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),zi=(t,e)=>{for(var r in e)Zs(t,r,{get:e[r],enumerable:!0})},Yf=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of dg(e))!hg.call(t,i)&&i!==r&&Zs(t,i,{get:()=>e[i],enumerable:!(n=ug(e,i))||n.enumerable});return t};var pg=(t,e,r)=>(r=t!=null?cg(fg(t)):{},Yf(e||!t||!t.__esModule?Zs(r,"default",{value:t,enumerable:!0}):r,t)),gg=t=>Yf(Zs({},"__esModule",{value:!0}),t);var Fh=mg((wA,Bh)=>{"use strict";Bh.exports=Worker});var T2={};zi(T2,{ATTN_IDLE:()=>Lu,ATTN_LOOP_NONE:()=>Au,ATTN_NONE:()=>ao,ATTN_NORM:()=>Eu,ATTN_STATIC:()=>Tu,AssetDependencyError:()=>Mi,AssetDependencyTracker:()=>ls,AssetManager:()=>ql,AssetPreviewGenerator:()=>tu,AudioApi:()=>Xi,AudioContextController:()=>Zl,AudioOcclusion:()=>us,AudioRegistry:()=>ga,AudioRegistryError:()=>as,AudioSystem:()=>nc,BSP_SURFACE_FRAGMENT_SOURCE:()=>bd,BSP_SURFACE_VERTEX_SOURCE:()=>yd,BSP_VERTEX_LAYOUT:()=>dd,BspLoader:()=>Yi,BspLump:()=>Du,BspParseError:()=>le,BspSurfacePipeline:()=>va,Camera:()=>gc,ClientConnection:()=>su,Command:()=>eo,CommandRegistry:()=>Oi,ConfigStringRegistry:()=>$i,ConnectionState:()=>Of,CoordinateSystem:()=>Qd,Cvar:()=>oo,CvarRegistry:()=>Hi,DemoAnalyzer:()=>Ka,DemoCameraMode:()=>Df,DemoClipper:()=>eu,DemoEventType:()=>If,DemoPlaybackController:()=>Ns,DemoReader:()=>vr,DemoRecorder:()=>Gs,DemoValidator:()=>Jc,DynamicLightManager:()=>lc,EngineHost:()=>Wi,EngineRuntime:()=>so,FileType:()=>kf,FixedTimestepLoop:()=>ri,Framebuffer:()=>Ai,IndexBuffer:()=>st,LoggingRenderer:()=>ou,LruCache:()=>En,MAX_SOUND_CHANNELS:()=>io,MD2_FRAGMENT_SHADER:()=>Ad,MD2_VERTEX_SHADER:()=>Md,MD3_FRAGMENT_SHADER:()=>$d,MD3_VERTEX_SHADER:()=>Xd,MapAnalyzer:()=>ru,Md2Loader:()=>qi,Md2MeshBuffers:()=>wa,Md2ParseError:()=>it,Md2Pipeline:()=>Ma,Md3Loader:()=>Zi,Md3ModelMesh:()=>Ta,Md3ParseError:()=>er,Md3Pipeline:()=>Pa,Md3SurfaceMesh:()=>gs,MessageWriter:()=>Qc,MusicSystem:()=>ic,NetworkMessageParser:()=>xt,NullRenderer:()=>nu,PARTICLE_FRAGMENT_SHADER:()=>Yd,PARTICLE_VERTEX_SHADER:()=>Kd,PROTOCOL_VERSION_RERELEASE:()=>Xr,PakArchive:()=>Ki,PakIndexStore:()=>Yl,PakIngestionError:()=>An,PakParseError:()=>ze,PakValidationError:()=>li,PakValidator:()=>ll,PakWriter:()=>al,ParticleRenderer:()=>Ca,ParticleSystem:()=>Ra,PlaybackState:()=>jc,RERELEASE_KNOWN_PAKS:()=>Fu,ResourceLoadTracker:()=>ol,ResourceType:()=>Bu,SKYBOX_FRAGMENT_SHADER:()=>Sd,SKYBOX_VERTEX_SHADER:()=>_d,SOUND_FULLVOLUME:()=>Gi,SOUND_LOOP_ATTENUATE:()=>Pu,ShaderProgram:()=>ce,SkyboxPipeline:()=>_a,SoundChannel:()=>Cr,SoundPrecache:()=>Jl,SoundRegistry:()=>Ql,SpriteLoader:()=>ji,SpriteParseError:()=>Ln,SpriteRenderer:()=>Ba,StreamingPakArchive:()=>il,Texture2D:()=>lt,TextureCache:()=>Qi,TextureCubeMap:()=>ya,TgaParseError:()=>qr,U_ALPHA:()=>Ar,U_ANGLE1:()=>Pt,U_ANGLE2:()=>Mt,U_ANGLE3:()=>At,U_EFFECTS16:()=>Qe,U_EFFECTS8:()=>qe,U_EVENT:()=>Lt,U_FRAME16:()=>Ct,U_FRAME8:()=>Et,U_INSTANCE_BITS:()=>Pr,U_LOOP_ATTENUATION_HIGH:()=>_n,U_LOOP_VOLUME:()=>Rr,U_MODEL:()=>Rt,U_MODEL2:()=>Bt,U_MODEL3:()=>Ft,U_MODEL4:()=>It,U_OLDORIGIN:()=>pr,U_OLD_FRAME_HIGH:()=>wn,U_ORIGIN1:()=>St,U_ORIGIN2:()=>wt,U_ORIGIN3:()=>Tt,U_OWNER_HIGH:()=>Sn,U_REMOVE:()=>ro,U_RENDERFX16:()=>je,U_RENDERFX8:()=>Ye,U_SCALE:()=>Tr,U_SKIN16:()=>Je,U_SKIN8:()=>Ze,U_SOLID:()=>kt,U_SOUND:()=>Dt,VertexArray:()=>Be,VertexBuffer:()=>Ce,VirtualFileSystem:()=>sl,advanceAnimation:()=>Lh,applyEntityDelta:()=>$0,applySurfaceState:()=>ds,attenuationToDistanceMultiplier:()=>Vi,boxIntersectsFrustum:()=>Ei,buildBspGeometry:()=>sc,buildMd2Geometry:()=>Ed,buildMd2VertexData:()=>Ld,buildMd3SurfaceGeometry:()=>Hd,buildMd3VertexData:()=>Wd,calculateMaxAudibleDistance:()=>si,calculatePakChecksum:()=>dh,captureRenderTarget:()=>eg,computeFrameBlend:()=>Th,computeSkyScroll:()=>Ti,createAnimationState:()=>Ph,createAudioGraph:()=>jl,createBspSurfaces:()=>oc,createEmptyEntityState:()=>Wr,createEmptyProtocolPlayerState:()=>_r,createEngine:()=>L2,createEngineRuntime:()=>lh,createFaceLightmap:()=>ul,createHeadlessRenderTarget:()=>J0,createInitialChannels:()=>ec,createOcclusionResolver:()=>cm,createProgramFromSources:()=>fm,createRenderer:()=>hp,createWebGLContext:()=>um,createWebGPUContext:()=>Ac,createWebGPURenderer:()=>wp,decodeOgg:()=>Kl,deriveSurfaceRenderState:()=>vd,detectFileType:()=>Uf,extractFrustumPlanes:()=>sr,filesToPakSources:()=>Iu,findLeafForPoint:()=>Li,gatherVisibleFaces:()=>cn,groupMd2Animations:()=>wh,ingestPakFiles:()=>ph,ingestPaks:()=>cl,interpolateMd3Tag:()=>Zm,interpolateVec3:()=>Rh,isBinaryFile:()=>Y0,isTextFile:()=>zf,parseBsp:()=>lo,parseEntLump:()=>Z0,parseMd2:()=>ku,parseMd3:()=>Uu,parsePcx:()=>ho,parseSprite:()=>zu,parseTga:()=>Ou,parseWal:()=>fl,parseWalTexture:()=>pl,parseWav:()=>gl,pcxToRgba:()=>hl,pickChannel:()=>tc,preparePcxTexture:()=>ml,queryCapabilities:()=>mp,removeViewTranslation:()=>Sa,resolveLightStyles:()=>xd,serializeEntLump:()=>j0,spawnBfgExplosion:()=>lp,spawnBlasterImpact:()=>sp,spawnBlood:()=>Jm,spawnBulletImpact:()=>jm,spawnExplosion:()=>Qm,spawnMuzzleFlash:()=>tp,spawnRailTrail:()=>ap,spawnSparks:()=>op,spawnSplash:()=>np,spawnSteam:()=>ip,spawnTeleportFlash:()=>ep,spawnTrail:()=>rp,validateEntity:()=>Q0,walToRgba:()=>Nu,wireDropTarget:()=>gh,wireFileInput:()=>yh});var yg=()=>typeof performance<"u"?performance.now():Date.now(),bg=t=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>t()):setTimeout(t,25)},ri=class{constructor(e,r={}){this.callbacks=e;this.accumulatorMs=0;this.frame=0;this.running=!1;this.tick=()=>{if(!this.running)return;let e=this.options.now(),r=this.lastTimeMs===void 0?0:e-this.lastTimeMs;this.lastTimeMs=e,this.advance(r,e),this.running&&this.options.schedule(this.tick)};let n=r.fixedDeltaMs??25,i=r.maxSubSteps??5;this.options={fixedDeltaMs:n,maxSubSteps:i,maxDeltaMs:r.maxDeltaMs??n*i,startTimeMs:r.startTimeMs,now:r.now??yg,schedule:r.schedule??bg}}start(){this.running||(this.running=!0,this.lastTimeMs=this.options.startTimeMs??this.options.now(),this.options.schedule(this.tick))}stop(){this.running=!1}pump(e){let r=(this.lastTimeMs??0)+e;this.lastTimeMs=r,this.advance(e,r)}isRunning(){return this.running}get frameNumber(){return this.frame}advance(e,r){let n=Math.min(Math.max(e,0),this.options.maxDeltaMs);this.accumulatorMs=Math.min(this.accumulatorMs+n,this.options.fixedDeltaMs*this.options.maxSubSteps);let i=0;for(;this.accumulatorMs>=this.options.fixedDeltaMs&&i<this.options.maxSubSteps;)this.frame+=1,this.callbacks.simulate({frame:this.frame,deltaMs:this.options.fixedDeltaMs,nowMs:r}),this.accumulatorMs-=this.options.fixedDeltaMs,i+=1;let a=this.options.fixedDeltaMs===0?0:this.accumulatorMs/this.options.fixedDeltaMs;this.callbacks.render?.({alpha:a,nowMs:r,accumulatorMs:this.accumulatorMs,frame:this.frame})}};var eo=class{constructor(e,r,n){this.name=e,this.callback=r,this.description=n}execute(e){this.callback(e)}},Oi=class{constructor(){this.commands=new Map;this.history=[];this.historyLimit=64;this.autocompleteProviders=[]}register(e,r,n){let i=new eo(e,r,n);return this.commands.set(e,i),i}registerCommand(e,r){this.register(e,r)}registerAutocompleteProvider(e){this.autocompleteProviders.push(e)}get(e){return this.commands.get(e)}execute(e){let r=e.trim();if(r.length===0)return!1;(this.history.length===0||this.history[this.history.length-1]!==r)&&(this.history.push(r),this.history.length>this.historyLimit&&this.history.shift());let n=this.tokenize(e);if(n.length===0)return!1;let i=n[0],a=n.slice(1),o=this.get(i);return o?(o.execute(a),!0):(this.onConsoleOutput?.(`Unknown command "${i}"`),!1)}executeCommand(e){this.execute(e)}getHistory(){return[...this.history]}getSuggestions(e){let r=new Set;for(let n of this.commands.keys())n.startsWith(e)&&r.add(n);for(let n of this.autocompleteProviders){let i=n();for(let a of i)a.startsWith(e)&&r.add(a)}return Array.from(r).sort()}tokenize(e){let r=[],n="",i=!1;for(let a=0;a<e.length;a++){let o=e[a];o==='"'?i=!i:o===" "&&!i?n.length>0&&(r.push(n),n=""):n+=o}return n.length>0&&r.push(n),r}list(){return[...this.commands.values()].sort((e,r)=>e.name.localeCompare(r.name))}};var xg=Object.defineProperty,vg=(t,e)=>{for(var r in e)xg(t,r,{get:e[r],enumerable:!0})},qf={x:0,y:0,z:0};var O2=Math.PI/180;function Zf(t,e){return{x:t.x-e.x,y:t.y-e.y,z:t.z-e.z}}function _g(t,e){return{x:t.x*e,y:t.y*e,z:t.z*e}}function Sg(t,e){return t.x*e.x+t.y*e.y+t.z*e.z}function wg(t){return Sg(t,t)}function mu(t){return Math.sqrt(wg(t))}function Kr(t){let e=mu(t);return e===0?t:_g(t,1/e)}var Mg=Math.PI/180,Ag=180/Math.PI,Ae=Mg,pu=Ag;var mr=[[-.525731,0,.850651],[-.442863,.238856,.864188],[-.295242,0,.955423],[-.309017,.5,.809017],[-.16246,.262866,.951056],[0,0,1],[0,.850651,.525731],[-.147621,.716567,.681718],[.147621,.716567,.681718],[0,.525731,.850651],[.309017,.5,.809017],[.525731,0,.850651],[.295242,0,.955423],[.442863,.238856,.864188],[.16246,.262866,.951056],[-.681718,.147621,.716567],[-.809017,.309017,.5],[-.587785,.425325,.688191],[-.850651,.525731,0],[-.864188,.442863,.238856],[-.716567,.681718,.147621],[-.688191,.587785,.425325],[-.5,.809017,.309017],[-.238856,.864188,.442863],[-.425325,.688191,.587785],[-.716567,.681718,-.147621],[-.5,.809017,-.309017],[-.525731,.850651,0],[0,.850651,-.525731],[-.238856,.864188,-.442863],[0,.955423,-.295242],[-.262866,.951056,-.16246],[0,1,0],[0,.955423,.295242],[-.262866,.951056,.16246],[.238856,.864188,.442863],[.262866,.951056,.16246],[.5,.809017,.309017],[.238856,.864188,-.442863],[.262866,.951056,-.16246],[.5,.809017,-.309017],[.850651,.525731,0],[.716567,.681718,.147621],[.716567,.681718,-.147621],[.525731,.850651,0],[.425325,.688191,.587785],[.864188,.442863,.238856],[.688191,.587785,.425325],[.809017,.309017,.5],[.681718,.147621,.716567],[.587785,.425325,.688191],[.955423,.295242,0],[1,0,0],[.951056,.16246,.262866],[.850651,-.525731,0],[.955423,-.295242,0],[.864188,-.442863,.238856],[.951056,-.16246,.262866],[.809017,-.309017,.5],[.681718,-.147621,.716567],[.850651,0,.525731],[.864188,.442863,-.238856],[.809017,.309017,-.5],[.951056,.16246,-.262866],[.525731,0,-.850651],[.681718,.147621,-.716567],[.681718,-.147621,-.716567],[.850651,0,-.525731],[.809017,-.309017,-.5],[.864188,-.442863,-.238856],[.951056,-.16246,-.262866],[.147621,.716567,-.681718],[.309017,.5,-.809017],[.425325,.688191,-.587785],[.442863,.238856,-.864188],[.587785,.425325,-.688191],[.688191,.587785,-.425325],[-.147621,.716567,-.681718],[-.309017,.5,-.809017],[0,.525731,-.850651],[-.525731,0,-.850651],[-.442863,.238856,-.864188],[-.295242,0,-.955423],[-.16246,.262866,-.951056],[0,0,-1],[.295242,0,-.955423],[.16246,.262866,-.951056],[-.442863,-.238856,-.864188],[-.309017,-.5,-.809017],[-.16246,-.262866,-.951056],[0,-.850651,-.525731],[-.147621,-.716567,-.681718],[.147621,-.716567,-.681718],[0,-.525731,-.850651],[.309017,-.5,-.809017],[.442863,-.238856,-.864188],[.16246,-.262866,-.951056],[.238856,-.864188,-.442863],[.5,-.809017,-.309017],[.425325,-.688191,-.587785],[.716567,-.681718,-.147621],[.688191,-.587785,-.425325],[.587785,-.425325,-.688191],[0,-.955423,-.295242],[0,-1,0],[.262866,-.951056,-.16246],[0,-.850651,.525731],[0,-.955423,.295242],[.238856,-.864188,.442863],[.262866,-.951056,.16246],[.5,-.809017,.309017],[.716567,-.681718,.147621],[.525731,-.850651,0],[-.238856,-.864188,-.442863],[-.5,-.809017,-.309017],[-.262866,-.951056,-.16246],[-.850651,-.525731,0],[-.716567,-.681718,-.147621],[-.716567,-.681718,.147621],[-.525731,-.850651,0],[-.5,-.809017,.309017],[-.238856,-.864188,.442863],[-.262866,-.951056,.16246],[-.864188,-.442863,.238856],[-.809017,-.309017,.5],[-.688191,-.587785,.425325],[-.681718,-.147621,.716567],[-.442863,-.238856,.864188],[-.587785,-.425325,.688191],[-.309017,-.5,.809017],[-.147621,-.716567,.681718],[-.425325,-.688191,.587785],[-.16246,-.262866,.951056],[.442863,-.238856,.864188],[.16246,-.262866,.951056],[.309017,-.5,.809017],[.147621,-.716567,.681718],[0,-.525731,.850651],[.425325,-.688191,.587785],[.587785,-.425325,.688191],[.688191,-.587785,.425325],[-.955423,.295242,0],[-.951056,.16246,.262866],[-1,0,0],[-.850651,0,.525731],[-.955423,-.295242,0],[-.951056,-.16246,.262866],[-.864188,.442863,-.238856],[-.951056,.16246,-.262866],[-.809017,.309017,-.5],[-.864188,-.442863,-.238856],[-.951056,-.16246,-.262866],[-.809017,-.309017,-.5],[-.681718,.147621,-.716567],[-.681718,-.147621,-.716567],[-.850651,0,-.525731],[-.688191,.587785,-.425325],[-.587785,.425325,-.688191],[-.425325,.688191,-.587785],[-.425325,-.688191,-.587785],[-.587785,-.425325,-.688191],[-.688191,-.587785,-.425325]];var Sr=624,Eg=397,Lg=2567483615,Tg=2147483648,Pg=2147483647,fu=4294967296,Rg=class{constructor(t=5489){this.state=new Uint32Array(Sr),this.index=Sr,this.seed(t)}seed(t){this.state[0]=t>>>0;for(let e=1;e<Sr;e++){let r=this.state[e-1]^this.state[e-1]>>>30,n=Math.imul(r>>>0,1812433253)+e;this.state[e]=n>>>0}this.index=Sr}nextUint32(){this.index>=Sr&&this.twist();let t=this.state[this.index++];return t^=t>>>11,t^=t<<7&2636928640,t^=t<<15&4022730752,t^=t>>>18,t>>>0}twist(){for(let t=0;t<Sr;t++){let e=this.state[t]&Tg|this.state[(t+1)%Sr]&Pg,r=this.state[(t+Eg)%Sr]^e>>>1;(e&1)!==0&&(r^=Lg),this.state[t]=r>>>0}this.index=0}getState(){return{index:this.index,state:Array.from(this.state)}}setState(t){if(t.state.length!==Sr)throw new Error(`Expected ${Sr} MT state values, received ${t.state.length}`);this.index=t.index,this.state=Uint32Array.from(t.state,e=>e>>>0)}},jf=class{constructor(t={}){this.mt=new Rg(t.seed)}seed(t){this.mt.seed(t)}frandom(){return this.mt.nextUint32()/fu}frandomRange(t,e){return t+(e-t)*this.frandom()}frandomMax(t){return this.frandomRange(0,t)}crandom(){return this.frandomRange(-1,1)}crandomOpen(){let t=Number.EPSILON;return this.frandomRange(-1+t,1)}irandomUint32(){return this.mt.nextUint32()}irandomRange(t,e){if(e-t<=1)return t;let r=e-t,n=fu-fu%r,i;do i=this.mt.nextUint32();while(i>=n);return t+i%r}irandom(t){return t<=0?0:this.irandomRange(0,t)}randomTimeRange(t,e){return e<=t?t:this.irandomRange(t,e)}randomTime(t){return this.irandom(t)}randomIndex(t){return this.irandom(t.length)}getState(){return{mt:this.mt.getState()}}setState(t){this.mt.setState(t.mt)}};function Cg(){return new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1])}function gu(t,e){let r=new Float32Array(16);for(let n=0;n<4;n+=1)for(let i=0;i<4;i+=1)r[i*4+n]=t[0+n]*e[i*4+0]+t[4+n]*e[i*4+1]+t[8+n]*e[i*4+2]+t[12+n]*e[i*4+3];return r}function Qf(t,e){let r=e.x,n=e.y,i=e.z;return{x:t[0]*r+t[4]*n+t[8]*i+t[12],y:t[1]*r+t[5]*n+t[9]*i+t[13],z:t[2]*r+t[6]*n+t[10]*i+t[14]}}function Jf(t,e){let r=Cg();return r[0]=e[0].x,r[1]=e[0].y,r[2]=e[0].z,r[4]=e[1].x,r[5]=e[1].y,r[6]=e[1].z,r[8]=e[2].x,r[9]=e[2].y,r[10]=e[2].z,r[12]=t.x,r[13]=t.y,r[14]=t.z,r}var wr=1,gn=2;var yu=8,bu=16,Bg=32;var Fg=16384;var js=65536,eh=1<<17,Ig=1<<18,Dg=1<<19,kg=1<<20,Ug=1<<21,zg=1<<22,Og=1<<23,N2=1<<24,Qs=1<<25,Ng=1<<26,G2=1<<27,V2=1<<28,H2=1<<29,Js=1<<30,W2=1<<31;var yn=0;var bn=4,Yr=8,xn=16,vn=32,el=64;var X2=1<<25,$2=1<<28,K2=1<<29,Y2=1<<30,q2=1<<31;var Z2=wr|gn,j2=wr|js|gn|Qs|Js,Q2=wr|js|gn,J2=wr|eh|gn|Qs|Js,eM=Bg|yu|bu,tM=wr|bu|yu,Gg=wr|Qs|Js|gn|Ng,rM=Ig|Dg|kg|Ug|zg|Og,nM=wr|yu|bu|Qs|Js,iM=wr|js|gn,aM=wr|gn,oM=wr|js|gn|eh,sM=Gg|Fg;var lM=Number.MAX_SAFE_INTEGER-1;var tl=(t=>(t[t.None=0]="None",t[t.Archive=1]="Archive",t[t.UserInfo=2]="UserInfo",t[t.ServerInfo=4]="ServerInfo",t[t.Latch=8]="Latch",t[t.Cheat=16]="Cheat",t))(tl||{});var rl=256;var xu=256,vu=8192,nl=2048,_u=512,Su=256,wu=rl*2,Mu=256,hu=32,to=96;var ee=(t=>(t[t.Name=0]="Name",t[t.CdTrack=1]="CdTrack",t[t.Sky=2]="Sky",t[t.SkyAxis=3]="SkyAxis",t[t.SkyRotate=4]="SkyRotate",t[t.StatusBar=5]="StatusBar",t[t.HealthBarName=55]="HealthBarName",t[t.CONFIG_N64_PHYSICS=56]="CONFIG_N64_PHYSICS",t[t.CONFIG_CTF_TEAMS=57]="CONFIG_CTF_TEAMS",t[t.CONFIG_COOP_RESPAWN_STRING=58]="CONFIG_COOP_RESPAWN_STRING",t[t.Story=54]="Story",t[t.AirAccel=59]="AirAccel",t[t.MaxClients=60]="MaxClients",t[t.MapChecksum=61]="MapChecksum",t[t.Models=62]="Models",t[t.Sounds=62+vu]="Sounds",t[t.Images=t.Sounds+nl]="Images",t[t.Lights=t.Images+_u]="Lights",t[t.ShadowLights=t.Lights+xu]="ShadowLights",t[t.Items=t.ShadowLights+Mu]="Items",t[t.Players=t.Items+Su]="Players",t[t.PlayerSkins=t.Players]="PlayerSkins",t[t.General=t.Players+rl]="General",t[t.WheelWeapons=t.General+wu]="WheelWeapons",t[t.WheelAmmo=t.WheelWeapons+hu]="WheelAmmo",t[t.WheelPowerups=t.WheelAmmo+hu]="WheelPowerups",t[t.CdLoopCount=t.WheelPowerups+hu]="CdLoopCount",t[t.GameStyle=t.CdLoopCount+1]="GameStyle",t[t.MaxConfigStrings=t.GameStyle+1]="MaxConfigStrings",t))(ee||{}),th=ee.MaxConfigStrings;function rh(t){return t>=5&&t<59?to*(59-t):t>=ee.General&&t<ee.WheelWeapons?to*(ee.MaxConfigStrings-t):to}var cM=ee.Sounds,uM=ee.Images,dM=ee.Lights,fM=ee.Items,hM=ee.Players,mM=ee.General,Vg={};vg(Vg,{addReplayFrame:()=>$g,createReplaySession:()=>Xg,deserializeReplay:()=>Wg,serializeReplay:()=>Hg});function Hg(t){return JSON.stringify(t,null,2)}function Wg(t){let e=JSON.parse(t);if(!e.metadata||!Array.isArray(e.frames))throw new Error("Invalid replay format: missing metadata or frames");return e}function Xg(t,e){return{metadata:{map:t,date:new Date().toISOString(),version:"1.0",seed:e},frames:[]}}function $g(t,e,r,n){t.frames.push({serverFrame:r,cmd:e,timestamp:Date.now()-n})}var R=(t=>(t[t.bad=0]="bad",t[t.muzzleflash=1]="muzzleflash",t[t.muzzleflash2=2]="muzzleflash2",t[t.temp_entity=3]="temp_entity",t[t.layout=4]="layout",t[t.inventory=5]="inventory",t[t.nop=6]="nop",t[t.disconnect=7]="disconnect",t[t.reconnect=8]="reconnect",t[t.sound=9]="sound",t[t.print=10]="print",t[t.stufftext=11]="stufftext",t[t.serverdata=12]="serverdata",t[t.configstring=13]="configstring",t[t.spawnbaseline=14]="spawnbaseline",t[t.centerprint=15]="centerprint",t[t.download=16]="download",t[t.playerinfo=17]="playerinfo",t[t.packetentities=18]="packetentities",t[t.deltapacketentities=19]="deltapacketentities",t[t.frame=20]="frame",t[t.splitclient=21]="splitclient",t[t.configblast=22]="configblast",t[t.spawnbaselineblast=23]="spawnbaselineblast",t[t.level_restart=24]="level_restart",t[t.damage=25]="damage",t[t.locprint=26]="locprint",t[t.fog=27]="fog",t[t.waitingforplayers=28]="waitingforplayers",t[t.bot_chat=29]="bot_chat",t[t.poi=30]="poi",t[t.help_path=31]="help_path",t[t.muzzleflash3=32]="muzzleflash3",t[t.achievement=33]="achievement",t))(R||{}),ii=(t=>(t[t.bad=0]="bad",t[t.nop=1]="nop",t[t.move=2]="move",t[t.userinfo=3]="userinfo",t[t.stringcmd=4]="stringcmd",t))(ii||{}),U=(t=>(t[t.GUNSHOT=0]="GUNSHOT",t[t.BLOOD=1]="BLOOD",t[t.BLASTER=2]="BLASTER",t[t.RAILTRAIL=3]="RAILTRAIL",t[t.SHOTGUN=4]="SHOTGUN",t[t.EXPLOSION1=5]="EXPLOSION1",t[t.EXPLOSION2=6]="EXPLOSION2",t[t.ROCKET_EXPLOSION=7]="ROCKET_EXPLOSION",t[t.GRENADE_EXPLOSION=8]="GRENADE_EXPLOSION",t[t.SPARKS=9]="SPARKS",t[t.SPLASH=10]="SPLASH",t[t.BUBBLETRAIL=11]="BUBBLETRAIL",t[t.SCREEN_SPARKS=12]="SCREEN_SPARKS",t[t.SHIELD_SPARKS=13]="SHIELD_SPARKS",t[t.BULLET_SPARKS=14]="BULLET_SPARKS",t[t.LASER_SPARKS=15]="LASER_SPARKS",t[t.PARASITE_ATTACK=16]="PARASITE_ATTACK",t[t.ROCKET_EXPLOSION_WATER=17]="ROCKET_EXPLOSION_WATER",t[t.GRENADE_EXPLOSION_WATER=18]="GRENADE_EXPLOSION_WATER",t[t.MEDIC_CABLE_ATTACK=19]="MEDIC_CABLE_ATTACK",t[t.BFG_EXPLOSION=20]="BFG_EXPLOSION",t[t.BFG_BIGEXPLOSION=21]="BFG_BIGEXPLOSION",t[t.BOSSTPORT=22]="BOSSTPORT",t[t.BFG_LASER=23]="BFG_LASER",t[t.GRAPPLE_CABLE=24]="GRAPPLE_CABLE",t[t.WELDING_SPARKS=25]="WELDING_SPARKS",t[t.GREENBLOOD=26]="GREENBLOOD",t[t.BLUEHYPERBLASTER=27]="BLUEHYPERBLASTER",t[t.PLASMA_EXPLOSION=28]="PLASMA_EXPLOSION",t[t.TUNNEL_SPARKS=29]="TUNNEL_SPARKS",t[t.BLASTER2=30]="BLASTER2",t[t.RAILTRAIL2=31]="RAILTRAIL2",t[t.FLAME=32]="FLAME",t[t.LIGHTNING=33]="LIGHTNING",t[t.DEBUGTRAIL=34]="DEBUGTRAIL",t[t.PLAIN_EXPLOSION=35]="PLAIN_EXPLOSION",t[t.FLASHLIGHT=36]="FLASHLIGHT",t[t.FORCEWALL=37]="FORCEWALL",t[t.HEATBEAM=38]="HEATBEAM",t[t.MONSTER_HEATBEAM=39]="MONSTER_HEATBEAM",t[t.STEAM=40]="STEAM",t[t.BUBBLETRAIL2=41]="BUBBLETRAIL2",t[t.MOREBLOOD=42]="MOREBLOOD",t[t.HEATBEAM_SPARKS=43]="HEATBEAM_SPARKS",t[t.HEATBEAM_STEAM=44]="HEATBEAM_STEAM",t[t.CHAINFIST_SMOKE=45]="CHAINFIST_SMOKE",t[t.ELECTRIC_SPARKS=46]="ELECTRIC_SPARKS",t[t.TRACKER_EXPLOSION=47]="TRACKER_EXPLOSION",t[t.TELEPORT_EFFECT=48]="TELEPORT_EFFECT",t[t.DBALL_GOAL=49]="DBALL_GOAL",t[t.WIDOWBEAMOUT=50]="WIDOWBEAMOUT",t[t.NUKEBLAST=51]="NUKEBLAST",t[t.WIDOWSPLASH=52]="WIDOWSPLASH",t[t.EXPLOSION1_BIG=53]="EXPLOSION1_BIG",t[t.EXPLOSION1_NP=54]="EXPLOSION1_NP",t[t.FLECHETTE=55]="FLECHETTE",t[t.BLUEHYPERBLASTER_KEX=56]="BLUEHYPERBLASTER_KEX",t[t.BFG_ZAP=57]="BFG_ZAP",t[t.BERSERK_SLAM=58]="BERSERK_SLAM",t[t.GRAPPLE_CABLE_2=59]="GRAPPLE_CABLE_2",t[t.POWER_SPLASH=60]="POWER_SPLASH",t[t.LIGHTNING_BEAM=61]="LIGHTNING_BEAM",t[t.EXPLOSION1_NL=62]="EXPLOSION1_NL",t[t.EXPLOSION2_NL=63]="EXPLOSION2_NL",t))(U||{});var nh=64;var Kg=12,Yg=9,pM=Math.ceil(Kg*Yg/16),qg=23,Zg=2,gM=Math.ceil(qg*Zg/16);function ih(t,e){t.writeByte(e.msec),t.writeByte(e.buttons),t.writeAngle16(e.angles.x),t.writeAngle16(e.angles.y),t.writeAngle16(e.angles.z),t.writeShort(e.forwardmove),t.writeShort(e.sidemove),t.writeShort(e.upmove),t.writeByte(e.impulse),t.writeByte(0)}var jg=[0,145,227,114,7,150,228,117,14,159,237,124,9,152,234,123,28,141,255,110,27,138,248,105,18,131,241,96,21,132,246,103,56,169,219,74,63,174,220,77,54,167,213,68,49,160,210,67,36,181,199,86,35,178,192,81,42,187,201,88,45,188,206,95,112,225,147,2,119,230,148,5,126,239,157,12,121,232,154,11,108,253,143,30,107,250,136,25,98,243,129,16,101,244,134,23,72,217,171,58,79,222,172,61,70,215,165,52,65,208,162,51,84,197,183,38,83,194,176,33,90,203,185,40,93,204,190,47,224,113,3,146,231,118,4,149,238,127,13,156,233,120,10,155,252,109,31,142,251,106,24,137,242,99,17,128,245,100,22,135,216,73,59,170,223,78,60,173,214,71,53,164,209,64,50,163,196,85,39,182,195,82,32,177,202,91,41,184,205,92,46,191,144,1,115,226,151,6,116,229,158,15,125,236,153,8,122,235,140,29,111,254,139,26,104,249,130,19,97,240,133,20,102,247,168,57,75,218,175,62,76,221,166,55,69,212,161,48,66,211,180,37,86,199,179,34,80,193,186,43,89,200,189,44,94,207];function ah(t){let e=0;for(let r=0;r<t.length;r++)e=jg[(e^t[r])&255];return e}var St=1,wt=2,Mt=4,At=8,Et=16,Lt=32,ro=64,Mr=128,ai=256,Tt=512,Pt=1024,Rt=2048,Ye=4096,Ar=8192,qe=16384,Er=32768,Ze=65536,Ct=1<<17,je=1<<18,Qe=1<<19,Bt=1<<20,Ft=1<<21,It=1<<22,Lr=1<<23,pr=1<<24,Je=1<<25,Dt=1<<26,kt=1<<27,Tr=1<<28,Pr=1<<29,Rr=1<<30,Ni=-2147483648,_n=1,Sn=2,wn=4;var Mn=class{constructor(t){t instanceof Uint8Array?this.view=new DataView(t.buffer,t.byteOffset,t.byteLength):this.view=new DataView(t),this.offset=0,this.length=this.view.byteLength}getPosition(){return this.offset}getReadPosition(){return this.offset}getLength(){return this.length}getRemaining(){return this.length-this.offset}seek(t){if(t<0||t>this.length)throw new Error(`Seek out of bounds: ${t} (length: ${this.length})`);this.offset=t}setReadPosition(t){this.seek(t)}hasMore(){return this.offset<this.length}hasBytes(t){return this.offset+t<=this.length}readChar(){let t=this.view.getInt8(this.offset);return this.offset+=1,t}readByte(){let t=this.view.getUint8(this.offset);return this.offset+=1,t}readShort(){let t=this.view.getInt16(this.offset,!0);return this.offset+=2,t}readUShort(){let t=this.view.getUint16(this.offset,!0);return this.offset+=2,t}readLong(){let t=this.view.getInt32(this.offset,!0);return this.offset+=4,t}readULong(){let t=this.view.getUint32(this.offset,!0);return this.offset+=4,t}readFloat(){let t=this.view.getFloat32(this.offset,!0);return this.offset+=4,t}readString(){let t="";for(;this.offset<this.length;){let e=this.readChar();if(e===-1||e===0)break;t+=String.fromCharCode(e)}return t}readStringLine(){let t="";for(;this.offset<this.length;){let e=this.readChar();if(e===-1||e===0||e===10)break;t+=String.fromCharCode(e)}return t}readCoord(){return this.readShort()*(1/8)}readAngle(){return this.readChar()*(360/256)}readAngle16(){return this.readShort()*360/65536}readData(t){if(this.offset+t>this.length)throw new Error(`Read out of bounds: ${this.offset+t} (length: ${this.length})`);let e=new Uint8Array(this.view.buffer,this.view.byteOffset+this.offset,t);return this.offset+=t,new Uint8Array(e)}readPos(t){t.x=this.readCoord(),t.y=this.readCoord(),t.z=this.readCoord()}readDir(t){let e=this.readByte();if(e>=162){t.x=0,t.y=0,t.z=0;return}let r=mr[e];t.x=r[0],t.y=r[1],t.z=r[2]}},oi=class{constructor(t=1400){typeof t=="number"?(this.buffer=new Uint8Array(t),this.fixed=!1):(this.buffer=t,this.fixed=!0),this.view=new DataView(this.buffer.buffer,this.buffer.byteOffset,this.buffer.byteLength),this.offset=0}ensureSpace(t){if(this.offset+t>this.buffer.byteLength){if(this.fixed)throw new Error(`Buffer overflow: capacity ${this.buffer.byteLength}, needed ${this.offset+t}`);let e=Math.max(this.buffer.byteLength*2,this.offset+t),r=new Uint8Array(e);r.set(this.buffer),this.buffer=r,this.view=new DataView(this.buffer.buffer,this.buffer.byteOffset,this.buffer.byteLength)}}writeByte(t){this.ensureSpace(1),this.view.setUint8(this.offset,t),this.offset+=1}writeBytes(t){this.ensureSpace(t.byteLength),this.buffer.set(t,this.offset),this.offset+=t.byteLength}writeChar(t){this.ensureSpace(1),this.view.setInt8(this.offset,t),this.offset+=1}writeShort(t){this.ensureSpace(2),this.view.setInt16(this.offset,t,!0),this.offset+=2}writeLong(t){this.ensureSpace(4),this.view.setInt32(this.offset,t,!0),this.offset+=4}writeFloat(t){this.ensureSpace(4),this.view.setFloat32(this.offset,t,!0),this.offset+=4}writeString(t){let e=t.length;this.ensureSpace(e+1);for(let r=0;r<e;r++)this.view.setUint8(this.offset+r,t.charCodeAt(r));this.view.setUint8(this.offset+e,0),this.offset+=e+1}writeCoord(t){this.writeShort(Math.trunc(t*8))}writeAngle(t){this.writeByte(Math.trunc(t*256/360)&255)}writeAngle16(t){this.writeShort(Math.trunc(t*65536/360)&65535)}writePos(t){this.writeCoord(t.x),this.writeCoord(t.y),this.writeCoord(t.z)}writeDir(t){let e=-1,r=0;if(t.x===0&&t.y===0&&t.z===0){this.writeByte(0);return}for(let n=0;n<mr.length;n++){let i=mr[n],a=t.x*i[0]+t.y*i[1]+t.z*i[2];a>e&&(e=a,r=n)}this.writeByte(r)}getData(){return this.buffer.slice(0,this.offset)}getBuffer(){return this.buffer}getOffset(){return this.offset}reset(){this.offset=0}},no=class{constructor(t=1024){this.buffer=new Uint8Array(t),this.view=new DataView(this.buffer.buffer),this.offset=0}ensureCapacity(t){if(this.offset+t>this.buffer.length){let e=Math.max(this.buffer.length*2,this.offset+t),r=new Uint8Array(e);r.set(this.buffer),this.buffer=r,this.view=new DataView(this.buffer.buffer)}}getData(){return this.buffer.slice(0,this.offset)}writeByte(t){this.ensureCapacity(1),this.view.setUint8(this.offset,t),this.offset+=1}writeChar(t){this.ensureCapacity(1),this.view.setInt8(this.offset,t),this.offset+=1}writeShort(t){this.ensureCapacity(2),this.view.setInt16(this.offset,t,!0),this.offset+=2}writeUShort(t){this.ensureCapacity(2),this.view.setUint16(this.offset,t,!0),this.offset+=2}writeLong(t){this.ensureCapacity(4),this.view.setInt32(this.offset,t,!0),this.offset+=4}writeFloat(t){this.ensureCapacity(4),this.view.setFloat32(this.offset,t,!0),this.offset+=4}writeString(t){let e=t.length+1;this.ensureCapacity(e);for(let r=0;r<t.length;r++)this.view.setUint8(this.offset+r,t.charCodeAt(r));this.view.setUint8(this.offset+t.length,0),this.offset+=e}writeData(t){this.ensureCapacity(t.length),this.buffer.set(t,this.offset),this.offset+=t.length}writeCoord(t){this.writeShort(Math.round(t*8))}writeAngle(t){this.writeByte(Math.round(t*256/360)&255)}writeAngle16(t){this.writeShort(Math.round(t*65536/360))}writeDir(t,e,r){let n=0,i=-999999,a=Math.sqrt(t*t+e*e+r*r);if(a>0){t/=a,e/=a,r/=a;for(let o=0;o<162;o++){let s=t*mr[o][0]+e*mr[o][1]+r*mr[o][2];s>i&&(i=s,n=o)}}this.writeByte(n)}},ni=class nt{constructor(){this.qport=0,this.incomingSequence=0,this.outgoingSequence=0,this.incomingAcknowledged=0,this.incomingReliableAcknowledged=!1,this.incomingReliableSequence=0,this.outgoingReliableSequence=0,this.reliableLength=0,this.fragmentSendOffset=0,this.fragmentBuffer=null,this.fragmentLength=0,this.fragmentReceived=0,this.lastReceived=0,this.lastSent=0,this.remoteAddress=null,this.reliableMessage=new oi(nt.MAX_RELIABLE_BUFFER);let e=Date.now();this.lastReceived=e,this.lastSent=e,this.qport=Math.floor(Math.random()*65536)}setup(e,r=null){this.qport=e,this.remoteAddress=r,this.reset()}reset(){this.incomingSequence=0,this.outgoingSequence=0,this.incomingAcknowledged=0,this.incomingReliableAcknowledged=!1,this.incomingReliableSequence=0,this.outgoingReliableSequence=0,this.reliableLength=0,this.reliableMessage.reset(),this.fragmentSendOffset=0,this.fragmentBuffer=null,this.fragmentLength=0,this.fragmentReceived=0,this.lastReceived=Date.now(),this.lastSent=Date.now()}transmit(e){this.outgoingSequence++,this.lastSent=Date.now();let r=0,n=!1,i=0;this.reliableLength>0&&(this.reliableLength>nt.FRAGMENT_SIZE?(n=!0,this.fragmentSendOffset>=this.reliableLength&&(this.fragmentSendOffset=0),r=this.reliableLength-this.fragmentSendOffset,r>nt.FRAGMENT_SIZE&&(r=nt.FRAGMENT_SIZE),i=this.fragmentSendOffset,this.fragmentSendOffset+=r):r=this.reliableLength);let a=nt.PACKET_HEADER,o=r>0?2+(n?8:0):0,s=e?e.length:0;a+o+r+s>nt.MAX_MSGLEN&&(s=nt.MAX_MSGLEN-a-o-r,s<0&&(s=0));let c=new ArrayBuffer(a+o+r+s),l=new DataView(c),u=new Uint8Array(c),d=this.outgoingSequence;r>0&&(d|=2147483648,(this.outgoingReliableSequence&1)!==0&&(d|=1073741824)),l.setUint32(0,d,!0);let f=this.incomingSequence;(this.incomingReliableSequence&1)!==0&&(f|=2147483648),l.setUint32(4,f,!0),l.setUint16(8,this.qport,!0);let h=a;if(r>0){let m=r;n&&(m|=32768),l.setUint16(h,m,!0),h+=2,n&&(l.setUint32(h,i,!0),h+=4,l.setUint32(h,this.reliableLength,!0),h+=4);let p=this.reliableMessage.getBuffer().subarray(i,i+r);u.set(p,h),h+=r}if(e&&s>0){let m=e.slice(0,s);u.set(m,h)}return u}process(e){if(e.length<4)return null;this.lastReceived=Date.now();let r=new DataView(e.buffer,e.byteOffset,e.byteLength),n=r.getUint32(0,!0);if(n===4294967295)return e.subarray(4);if(e.length<nt.PACKET_HEADER)return null;let i=r.getUint32(4,!0),a=r.getUint16(8,!0);if(this.qport!==a)return null;let o=n&1073741823;if((o-this.incomingSequence|0)<=0)return null;this.incomingSequence=o;let s=i&2147483647,c=(i&2147483648)!==0;if(s>this.incomingAcknowledged&&(this.incomingAcknowledged=s),this.reliableLength>0){let m=c?1:0,g=this.outgoingReliableSequence&1;m!==g&&(this.reliableLength=0,this.reliableMessage.reset(),this.outgoingReliableSequence^=1,this.fragmentSendOffset=0)}let l=(n&2147483648)!==0,u=(n&1073741824)!==0?1:0,d=nt.PACKET_HEADER,f=null;if(l){if(d+2>e.byteLength)return null;let m=r.getUint16(d,!0);d+=2;let g=(m&32768)!==0;m&=32767;let p=this.incomingReliableSequence&1;if(u===p)if(g){if(d+8>e.byteLength)return null;let y=r.getUint32(d,!0);d+=4;let v=r.getUint32(d,!0);if(d+=4,v>nt.MAX_RELIABLE_BUFFER)return console.warn(`NetChan: received invalid fragment total ${v} > ${nt.MAX_RELIABLE_BUFFER}`),null;if((!this.fragmentBuffer||this.fragmentBuffer.length!==v)&&(this.fragmentBuffer=new Uint8Array(v),this.fragmentLength=v,this.fragmentReceived=0),d+m>e.byteLength)return null;let b=e.subarray(d,d+m);y===this.fragmentReceived&&y+m<=v&&(this.fragmentBuffer.set(b,y),this.fragmentReceived+=m,this.fragmentReceived>=v&&(f=this.fragmentBuffer,this.incomingReliableSequence++,this.fragmentBuffer=null,this.fragmentLength=0,this.fragmentReceived=0))}else{if(this.incomingReliableSequence++,d+m>e.byteLength)return null;f=e.slice(d,d+m)}d+=m}let h=e.slice(d);if(f&&f.length>0){let m=f.length+h.length,g=new Uint8Array(m);return g.set(f,0),g.set(h,f.length),g}return h||new Uint8Array(0)}canSendReliable(){return this.reliableLength===0}writeReliableByte(e){if(this.reliableLength+1>nt.MAX_RELIABLE_BUFFER)throw new Error("NetChan reliable buffer overflow");this.reliableMessage.writeByte(e),this.reliableLength++}writeReliableShort(e){if(this.reliableLength+2>nt.MAX_RELIABLE_BUFFER)throw new Error("NetChan reliable buffer overflow");this.reliableMessage.writeShort(e),this.reliableLength+=2}writeReliableLong(e){if(this.reliableLength+4>nt.MAX_RELIABLE_BUFFER)throw new Error("NetChan reliable buffer overflow");this.reliableMessage.writeLong(e),this.reliableLength+=4}writeReliableString(e){let r=e.length+1;if(this.reliableLength+r>nt.MAX_RELIABLE_BUFFER)throw new Error("NetChan reliable buffer overflow");this.reliableMessage.writeString(e),this.reliableLength+=r}getReliableData(){return this.reliableLength===0?new Uint8Array(0):this.reliableMessage.getBuffer().subarray(0,this.reliableLength)}needsKeepalive(e){return e-this.lastSent>1e3}isTimedOut(e,r=3e4){return e-this.lastReceived>r}};ni.MAX_MSGLEN=1400;ni.FRAGMENT_SIZE=1024;ni.PACKET_HEADER=10;ni.HEADER_OVERHEAD=ni.PACKET_HEADER+2;ni.MAX_RELIABLE_BUFFER=262144;var oh=ni;var sh=(t=>(t[t.Bullets=0]="Bullets",t[t.Shells=1]="Shells",t[t.Rockets=2]="Rockets",t[t.Grenades=3]="Grenades",t[t.Cells=4]="Cells",t[t.Slugs=5]="Slugs",t[t.MagSlugs=6]="MagSlugs",t[t.Trap=7]="Trap",t[t.Flechettes=8]="Flechettes",t[t.Tesla=9]="Tesla",t[t.Disruptor=10]="Disruptor",t[t.Prox=11]="Prox",t[t.Nuke=12]="Nuke",t[t.Rounds=13]="Rounds",t))(sh||{}),yM=Object.keys(sh).length/2;var io=32,Cr=(t=>(t[t.Auto=0]="Auto",t[t.Weapon=1]="Weapon",t[t.Voice=2]="Voice",t[t.Item=3]="Item",t[t.Body=4]="Body",t[t.Aux=5]="Aux",t[t.Footstep=6]="Footstep",t[t.Aux3=7]="Aux3",t[t.NoPhsAdd=8]="NoPhsAdd",t[t.Reliable=16]="Reliable",t[t.ForcePos=32]="ForcePos",t))(Cr||{}),Au=-1,ao=0,Eu=1,Lu=2,Tu=3,Gi=80,Pu=.003;function Vi(t){return t*.001}function si(t){let e=Vi(t);return e<=0?Number.POSITIVE_INFINITY:Gi+1/e}var oo=class{constructor({name:e,defaultValue:r,description:n,flags:i=tl.None,onChange:a}){this.modifiedCount=0;this.name=e,this.defaultValue=r,this.description=n,this.flags=i,this._value=r,this.onChange=a}get string(){return this._value}getString(){return this.string}get number(){return Number(this._value)}getFloat(){return this.number}get integer(){return Math.trunc(this.number)}getInt(){return this.integer}get boolean(){return!!this.integer}getBoolean(){return this.boolean}set(e){if(this.flags&tl.Latch){if(e===this._value){this.latched=void 0;return}if(this.latched===e)return;this.latched!==e&&(this.latched=e);return}this.apply(e)}reset(){this.latched=void 0,this.apply(this.defaultValue)}applyLatched(){if(this.latched===void 0)return!1;let e=this.latched;return this.latched=void 0,e===this._value?!1:(this.apply(e),!0)}apply(e){if(this._value===e)return;let r=this._value;this._value=e,this.modifiedCount+=1,this.onChange?.(this,r)}},Hi=class{constructor(){this.cvars=new Map}register(e){let r=this.cvars.get(e.name);if(r)return r;let n=e.onChange,i=(o,s)=>{n?.(o,s),this.onCvarChange?.(o.name,o.string)},a=new oo({...e,onChange:i});return this.cvars.set(e.name,a),a}get(e){return this.cvars.get(e)}getCvar(e){return this.get(e)}setValue(e,r){let n=this.get(e);if(!n)throw new Error(`Unknown cvar: ${e}`);return n.set(r),n}setCvar(e,r){this.setValue(e,r)}resetAll(){for(let e of this.cvars.values())e.reset()}applyLatched(){let e=!1;for(let r of this.cvars.values())e=r.applyLatched()||e;return e}list(){return[...this.cvars.values()].sort((e,r)=>e.name.localeCompare(r.name))}listCvars(){return this.list().map(e=>({name:e.name,value:e.string,defaultValue:e.defaultValue,flags:e.flags,description:e.description}))}};var Wi=class{constructor(e,r,n={}){this.game=e;this.client=r;this.started=!1;this.paused_=!1;this.commands=new Oi;this.cvars=new Hi;this.stepSimulation=e=>{this.previousFrame=this.latestFrame,this.latestFrame=this.game.frame(e,this.latestCommand)};this.renderClient=e=>{this.client&&(this.latestCommand=this.client.render({...e,previous:this.previousFrame,latest:this.latestFrame}))};let i=n.loop?.now?.()??Date.now();this.startTimeMs=n.startTimeMs??n.loop?.startTimeMs??i,this.loop=new ri({simulate:this.stepSimulation,render:this.renderClient},{...n.loop,startTimeMs:this.startTimeMs}),this.commands.registerAutocompleteProvider(()=>this.cvars.list().map(a=>a.name))}start(){if(!this.started){try{this.latestFrame=this.game.init(this.startTimeMs)??this.latestFrame,this.client?.init(this.latestFrame)}catch(e){throw this.game.shutdown(),this.client?.shutdown(),e}this.started=!0,this.paused_=!1,this.loop.start()}}stop(){this.started&&(this.loop.stop(),this.client?.shutdown(),this.game.shutdown(),this.previousFrame=void 0,this.latestFrame=void 0,this.started=!1,this.paused_=!1)}setPaused(e){this.paused_=e,e?this.loop.stop():this.started&&this.loop.start()}get paused(){return this.paused_}pump(e){this.loop.pump(e)}getLatestFrame(){return this.latestFrame}isRunning(){return this.loop.isRunning()}};var Xi=class{constructor(e){this.registry=e.registry,this.system=e.system,this.music=e.music,this.client=e.client}soundindex(e){return this.registry.registerName(e)}sound(e,r,n,i,a,o){this.system.play({entity:e,channel:r,soundIndex:n,volume:i,attenuation:a,timeOffsetMs:o}),this.triggerSubtitle(n)}positioned_sound(e,r,n,i){this.system.positionedSound(e,r,n,i),this.triggerSubtitle(r)}loop_sound(e,r,n,i,a){let o=this.system.play({entity:e,channel:r,soundIndex:n,volume:i,attenuation:a,looping:!0});return this.triggerSubtitle(n),o}stop_entity_sounds(e){this.system.stopEntitySounds(e)}setPlaybackRate(e){this.system.setPlaybackRate(e)}set_listener(e){this.system.setListener(e)}play_music(e,r=!0){return this.music?this.music.play(e,{loop:r}):Promise.resolve()}play_track(e,r=!0){return this.music?this.music.playTrack(e):Promise.resolve()}pause_music(){this.music?.pause()}resume_music(){return this.music?.resume()??Promise.resolve()}stop_music(){this.music?.stop()}set_music_volume(e){this.music?.setVolume(e)}play_ambient(e,r,n){this.system.ambientSound(e,r,n),this.triggerSubtitle(r)}play_channel(e){this.system.play({...e}),this.triggerSubtitle(e.soundIndex)}triggerSubtitle(e){if(!this.client)return;let r=this.registry.getName(e);if(!r)return;let n=r.match(/\[(.*?)\]/);n&&this.client.showSubtitle(n[1],r)}};var so=class{constructor(e,r){this.engine=e;this.host=r;this.started=!1}start(){this.started||(this.engine.init(),this.host.start(),this.started=!0)}stop(){this.started&&(this.host.stop(),this.engine.shutdown(),this.started=!1)}pump(e){this.host.pump(e)}getLatestFrame(){return this.host.getLatestFrame()}isRunning(){return this.started&&this.host.isRunning()}};function lh(t,e,r,n,i){let a=new Xi({...n,client:r}),o=new Wi(e,r,i);return{runtime:new so(t,o),audio:a}}function Qg(t){if(t<0||t>=ee.MaxConfigStrings)throw new RangeError(`Configstring index ${t} is out of range (0-${ee.MaxConfigStrings-1})`)}function ch(t,e){let r=rh(t);if(e.length>r)throw new RangeError(`Configstring ${t} exceeds maximum length (${e.length} > ${r}); limit is ${to} chars per slot`)}var $i=class{constructor(){this.values=new Map;this.modelCursor=ee.Models;this.soundCursor=ee.Sounds;this.imageCursor=ee.Images;this.lightCursor=ee.Lights;this.shadowLightCursor=ee.ShadowLights;this.itemCursor=ee.Items;this.playerSkinCursor=ee.PlayerSkins;this.generalCursor=ee.General}set(e,r){return Qg(e),ch(e,r),this.values.set(e,r),e}get(e){return this.values.get(e)}getName(e){return this.get(e)}getAll(){let e=new Array(th).fill("");for(let[r,n]of this.values.entries())e[r]=n;return e}modelIndex(e){return this.register(e,ee.Models,vu,"modelCursor")}soundIndex(e){return this.register(e,ee.Sounds,nl,"soundCursor")}findSoundIndex(e){for(let r=ee.Sounds;r<ee.Sounds+nl;r+=1)if(this.values.get(r)===e)return r}imageIndex(e){return this.register(e,ee.Images,_u,"imageCursor")}lightIndex(e){return this.register(e,ee.Lights,xu,"lightCursor")}shadowLightIndex(e){return this.register(e,ee.ShadowLights,Mu,"shadowLightCursor")}itemIndex(e){return this.register(e,ee.Items,Su,"itemCursor")}playerSkinIndex(e){return this.register(e,ee.PlayerSkins,rl,"playerSkinCursor")}generalIndex(e){return this.register(e,ee.General,wu,"generalCursor")}register(e,r,n,i){for(let s=r;s<r+n;s+=1)if(this.values.get(s)===e)return s;let a=this[i],o=r+n;if(a>=o)throw new RangeError(`Out of configstring slots for range starting at ${r}`);return ch(a,e),this.values.set(a,e),this[i]=a+1,a}};var Jg="PACK";function ey(t,e,r){let n=[];for(let i=0;i<r;i+=1){let a=t.getUint8(e+i);if(a===0)break;n.push(a)}return String.fromCharCode(...n)}function Le(t){return t.replace(/\\/g,"/").replace(/^\/+/,"").toLowerCase()}function ty(){let t=new Uint32Array(256);for(let e=0;e<256;e+=1){let r=e;for(let n=0;n<8;n+=1)r=(r&1)!==0?3988292384^r>>>1:r>>>1;t[e]=r>>>0}return t}var ry=ty();function uh(t){let e=4294967295;for(let r=0;r<t.length;r+=1){let n=t[r];e=ry[(e^n)&255]^e>>>8}return(e^4294967295)>>>0}var ze=class extends Error{},Ki=class t{constructor(e,r,n,i){this.name=e;this.buffer=r;this.entries=new Map(n.map(a=>[a.name,a])),this.checksum=i,this.size=r.byteLength}static fromArrayBuffer(e,r){let n=new DataView(r);if(r.byteLength<12)throw new ze("PAK buffer too small to contain header");let i=String.fromCharCode(n.getUint8(0),n.getUint8(1),n.getUint8(2),n.getUint8(3));if(i!==Jg)throw new ze(`Invalid PAK header magic: ${i}`);let a=n.getInt32(4,!0),o=n.getInt32(8,!0);if(a<12)throw new ze(`Invalid directory offset: ${a}`);if(o<0||o%64!==0)throw new ze(`Invalid directory length: ${o}`);if(a+o>r.byteLength)throw new ze("Directory exceeds buffer length");let c=o/64,l=[],u=new Map;for(let d=0;d<c;d+=1){let f=a+d*64,h=ey(n,f,56),m=Le(h),g=n.getInt32(f+56,!0),p=n.getInt32(f+60,!0);if(g<0||p<0||g+p>r.byteLength)throw new ze(`Invalid entry bounds for ${h||"<unnamed>"} (offset=${g}, length=${p})`);if(!m)throw new ze(`Entry ${d} has an empty name`);let y={name:m,offset:g,length:p};u.set(m,y)}return l.push(...u.values()),new t(e,r,l,uh(new Uint8Array(r)))}getEntry(e){return this.entries.get(Le(e))}listEntries(){return Array.from(this.entries.values())}list(){return Array.from(this.entries.keys())}readFile(e){let r=this.getEntry(e);if(!r)throw new ze(`File not found in PAK: ${e}`);return new Uint8Array(this.buffer,r.offset,r.length)}validate(){return{checksum:this.checksum,entries:this.listEntries()}}};function dh(t){return uh(new Uint8Array(t))}var ny="PACK",fh=12,Ru=64;function hh(t){return t.replace(/\\/g,"/").replace(/^\/+/,"").toLowerCase()}var il=class{constructor(e){this.source=e;this.entries=null}async readDirectory(){if(this.entries)return Array.from(this.entries.values());let e=await this.readChunk(0,fh),r=new DataView(e),n=String.fromCharCode(r.getUint8(0),r.getUint8(1),r.getUint8(2),r.getUint8(3));if(n!==ny)throw new ze(`Invalid PAK header magic: ${n}`);let i=r.getInt32(4,!0),a=r.getInt32(8,!0);if(i<fh)throw new ze(`Invalid directory offset: ${i}`);if(a<0||a%Ru!==0)throw new ze(`Invalid directory length: ${a}`);let o=await this.readChunk(i,a),s=new DataView(o),c=a/Ru,l=new Map;for(let u=0;u<c;u++){let d=u*Ru,f=this.readCString(s,d,56),h=hh(f),m=s.getInt32(d+56,!0),g=s.getInt32(d+60,!0);m<0||g<0||m+g>this.source.size,h&&l.set(h,{name:h,offset:m,length:g})}return this.entries=l,Array.from(l.values())}async readFile(e){let r=await this.getEntry(e);if(!r)throw new ze(`File not found in PAK: ${e}`);return this.source.slice(r.offset,r.offset+r.length).stream()}async getFileBlob(e){let r=await this.getEntry(e);if(!r)throw new ze(`File not found in PAK: ${e}`);return this.source.slice(r.offset,r.offset+r.length)}async getEntry(e){return this.entries||await this.readDirectory(),this.entries.get(hh(e))}async readChunk(e,r){let n=this.source.slice(e,e+r);return"arrayBuffer"in n?await n.arrayBuffer():new Response(n).arrayBuffer()}readCString(e,r,n){let i=[];for(let a=0;a<n;a+=1){let o=e.getUint8(r+a);if(o===0)break;i.push(o)}return String.fromCharCode(...i)}};var Cu=12,mh=64,al=class t{constructor(){this.entries=new Map}addFile(e,r){let n=Le(e);if(n.length>56)throw new Error(`Path too long: '${n}' (max 56 chars)`);this.entries.set(n,r)}removeFile(e){return this.entries.delete(Le(e))}build(){let e=0;for(let f of this.entries.values())e+=f.byteLength;let r=this.entries.size*mh,n=Cu+e+r,i=new Uint8Array(n),a=new DataView(i.buffer);a.setUint8(0,80),a.setUint8(1,65),a.setUint8(2,67),a.setUint8(3,75);let o=Cu+e;a.setInt32(4,o,!0),a.setInt32(8,r,!0);let s=Cu,c=new Map,l=Array.from(this.entries.keys()).sort();for(let f of l){let h=this.entries.get(f);c.set(f,s),i.set(h,s),s+=h.byteLength}let u=o,d=new TextEncoder;for(let f of l){let h=this.entries.get(f),m=d.encode(f);if(m.length>56)throw new Error(`Path too long after encoding: ${f}`);for(let g=0;g<56;g++)g<m.length?a.setUint8(u+g,m[g]):a.setUint8(u+g,0);a.setInt32(u+56,c.get(f),!0),a.setInt32(u+60,h.byteLength,!0),u+=mh}return i}static buildFromEntries(e){let r=new t;for(let[n,i]of e)r.addFile(n,i);return r.build()}};var Bu=(o=>(o.Texture="texture",o.Sound="sound",o.Model="model",o.Map="map",o.Sprite="sprite",o.ConfigString="configString",o))(Bu||{}),ol=class{constructor(){this.tracking=!1;this.entries=[];this.currentFrame=0;this.currentTime=0}startTracking(){this.tracking=!0,this.entries=[]}stopTracking(){this.tracking=!1;let e={byFrame:new Map,byTime:new Map,uniqueResources:new Map};for(let r of this.entries){e.byFrame.has(r.frame)||e.byFrame.set(r.frame,[]),e.byFrame.get(r.frame).push(r),e.byTime.has(r.timestamp)||e.byTime.set(r.timestamp,[]),e.byTime.get(r.timestamp).push(r);let n=`${r.type}:${r.path}`;e.uniqueResources.has(n)||e.uniqueResources.set(n,r)}return e}recordLoad(e,r,n,i){this.tracking&&this.entries.push({type:e,path:r,timestamp:this.currentTime,frame:this.currentFrame,size:n,pakSource:i})}setCurrentFrame(e){this.currentFrame=e}setCurrentTime(e){this.currentTime=e}};var sl=class{constructor(e=[]){this.mounts=[];this.files=new Map;e.forEach(r=>this.mountPak(r))}mountPak(e,r=0){let n=this.mounts.findIndex(i=>i.pak===e);n!==-1&&this.mounts.splice(n,1),this.mounts.push({pak:e,priority:r}),this.mounts.sort((i,a)=>a.priority-i.priority);for(let i of e.listEntries()){let a=Le(i.name),o={archive:e,entry:i,priority:r};this.files.has(a)||this.files.set(a,[]);let s=this.files.get(a),c=s.findIndex(l=>l.archive===e);c!==-1&&s.splice(c,1),s.unshift(o),s.sort((l,u)=>u.priority-l.priority)}return e}setPriority(e,r){this.mountPak(e,r)}getPaks(){return[...this.mounts].sort((e,r)=>e.priority-r.priority)}get mountedPaks(){return this.mounts.map(e=>e.pak)}hasFile(e){return this.files.has(Le(e))}getSource(e){let r=this.files.get(Le(e));if(!(!r||r.length===0))return r[0]}stat(e){let r=this.getSource(e);if(r)return{path:r.entry.name,size:r.entry.length,sourcePak:r.archive.name}}getFileMetadata(e){let r=this.getSource(e);if(r)return{path:r.entry.name,size:r.entry.length,sourcePak:r.archive.name,offset:r.entry.offset}}async readFile(e){let r=this.getSource(e);if(!r)throw new Error(`File not found in VFS: ${e}`);return r.archive.readFile(e)}async readBinaryFile(e){return this.readFile(e)}streamFile(e,r=1024*1024){let n=this.getSource(e);if(!n)throw new Error(`File not found in VFS: ${e}`);let{archive:i}=n,a=i.readFile(e),o=0,s=a.length;return new ReadableStream({pull(c){if(o>=s){c.close();return}let l=Math.min(o+r,s),u=a.slice(o,l);o=l,c.enqueue(u)}})}async readTextFile(e){let r=await this.readFile(e);return new TextDecoder("utf-8").decode(r)}list(e=""){let r=Le(e).replace(/\/+$|^\//g,""),n=[],i=new Set,a=r?`${r}/`:"";for(let[o,s]of this.files){let c=s[0];if(r&&!c.entry.name.startsWith(a))continue;let l=r?c.entry.name.slice(a.length):c.entry.name,u=l.indexOf("/");u===-1?n.push({path:c.entry.name,size:c.entry.length,sourcePak:c.archive.name}):i.add(l.slice(0,u))}return n.sort((o,s)=>o.path.localeCompare(s.path)),{files:n,directories:[...i].sort()}}async listDirectory(e){return this.list(e).files}findByExtension(e){if(e instanceof RegExp)return this.searchFiles(e);if(Array.isArray(e))return this.listByExtension(e);let r=e.startsWith(".")?e.toLowerCase():`.${e.toLowerCase()}`,n=[];for(let[i,a]of this.files){let o=a[0];o.entry.name.toLowerCase().endsWith(r)&&n.push({path:o.entry.name,size:o.entry.length,sourcePak:o.archive.name})}return n.sort((i,a)=>i.path.localeCompare(a.path))}listByExtension(e){let r=new Set(e.map(i=>i.startsWith(".")?i.toLowerCase():`.${i.toLowerCase()}`)),n=[];for(let[i,a]of this.files){let o=a[0],s=o.entry.name.toLowerCase();for(let c of r)if(s.endsWith(c)){n.push({path:o.entry.name,size:o.entry.length,sourcePak:o.archive.name});break}}return n.sort((i,a)=>i.path.localeCompare(a.path))}searchFiles(e){let r=[];for(let[n,i]of this.files){let a=i[0];e.test(a.entry.name)&&r.push({path:a.entry.name,size:a.entry.length,sourcePak:a.archive.name})}return r.sort((n,i)=>n.path.localeCompare(i.path))}getPakInfo(){return this.mounts.map(e=>({filename:e.pak.name,entryCount:e.pak.listEntries().length,totalSize:e.pak.size,priority:e.priority}))}getDirectoryTree(){let e={name:"",path:"",files:[],directories:[]},r=new Map;r.set("",e);let n=Array.from(this.files.values()).map(i=>{let a=i[0];return{path:a.entry.name,size:a.entry.length,sourcePak:a.archive.name}}).sort((i,a)=>i.path.localeCompare(a.path));for(let i of n){let a=i.path.split("/"),o=a.pop(),s="",c=e;for(let l of a){let u=s;s=s?`${s}/${l}`:l;let d=r.get(s);d||(d={name:l,path:s,files:[],directories:[]},c.directories.push(d),r.set(s,d)),c=d}c.files.push(i)}return e}};var Fu=Object.freeze([{name:"pak0.pak",checksum:2378051181,description:"Base game assets"},{name:"pak0.pak@baseq2",checksum:2378051181,description:"Base game assets (baseq2)"},{name:"pak0.pak@rogue",checksum:3373211245,description:"Ground Zero (rogue) mission pack"},{name:"pak0.pak@xatrix",checksum:1358269824,description:"The Reckoning (xatrix) mission pack"}]),li=class extends Error{constructor(r){super(r.status==="unknown"?`Unknown PAK not allowed: ${r.name}`:`PAK checksum mismatch for ${r.name}`);this.result=r;this.name="PakValidationError"}},ll=class{constructor(e=Fu){this.known=new Map;e.forEach(r=>this.known.set(this.normalizePakName(r.name),r))}validateArchive(e,r){let n=this.normalizePakName(r??("name"in e?e.name:"unknown")),i=e.checksum,a="size"in e?e.size:void 0,o=this.known.get(n);return o?o.checksum!==i?{name:n,checksum:i,expectedChecksum:o.checksum,status:"mismatch",size:a,description:o.description}:{name:n,checksum:i,expectedChecksum:o.checksum,status:"valid",size:a,description:o.description}:{name:n,checksum:i,status:"unknown",size:a}}assertValid(e,r){let n=this.validateArchive(e,r);if(n.status==="mismatch")throw new li(n);return n}normalizePakName(e){let r=Le(e),n=r.split("/"),i=n.pop()??r,a=n.pop();return a?`${i}@${a}`:i}};var An=class extends Error{constructor(r,n){super(`Failed to ingest PAK: ${r}`);this.file=r;this.name="PakIngestionError",n instanceof Error&&n.stack&&(this.stack=n.stack),this.cause=n}};async function iy(t,e){if(typeof t.arrayBuffer=="function"){let r=await t.arrayBuffer();return e?.({file:"blob",loadedBytes:r.byteLength,totalBytes:r.byteLength,state:"reading"}),r}if(typeof FileReader<"u")return new Promise((r,n)=>{let i=new FileReader;i.onerror=()=>n(i.error??new Error("Unknown FileReader error")),i.onprogress=a=>{e?.({file:"blob",loadedBytes:a.loaded,totalBytes:a.total||t.size,state:"reading"})},i.onload=()=>{let a=i.result;a instanceof ArrayBuffer?r(a):n(new Error("Unexpected FileReader result"))},i.readAsArrayBuffer(t)});if(typeof Response<"u"){let r=await new Response(t).arrayBuffer();return e?.({file:"blob",loadedBytes:r.byteLength,totalBytes:r.byteLength,state:"reading"}),r}if(typeof t.stream=="function"){let r=t.stream().getReader(),n=[],i=0;for(;;){let{done:s,value:c}=await r.read();if(s)break;if(!c)continue;let l=c;n.push(l),i+=l.byteLength,e?.({file:"blob",loadedBytes:i,totalBytes:t.size,state:"reading"})}let a=new Uint8Array(i),o=0;for(let s of n)a.set(s,o),o+=s.byteLength;return a.buffer}throw new An("blob",new Error("Unsupported Blob type"))}async function ay(t,e){if(t.data instanceof ArrayBuffer)return e?.({file:t.name,loadedBytes:t.data.byteLength,totalBytes:t.data.byteLength,state:"reading"}),t.data;if(t.data instanceof Blob){let n=t.data.size;return iy(t.data,i=>e?.({...i,file:t.name,totalBytes:n}))}let r=t.data.buffer.slice(t.data.byteOffset,t.data.byteOffset+t.data.byteLength);return e?.({file:t.name,loadedBytes:r.byteLength,totalBytes:r.byteLength,state:"reading"}),r}async function cl(t,e,r){let n=typeof r=="function"?{onProgress:r}:r??{},i=n.persistIndexes??!!n.pakIndexStore,a=n.enforceValidation??!!n.validator,o=n.allowUnknownPaks??!0,s=n.stopOnError??!1,c=[];for(let l of e)try{let u=await ay(l,n.onProgress),d=Ki.fromArrayBuffer(l.name,u),f=n.validator?.validateArchive(d);if(f){n.onValidationResult?.(f);let h=f.status==="mismatch",m=f.status==="unknown";if(h&&a||m&&!o){let g=new li(f);if(n.onError?.(l.name,g),s)throw new An(l.name,g);c.push({archive:d,mounted:!1,validation:f});continue}}if(t.mountPak(d),i&&n.pakIndexStore)try{await n.pakIndexStore.persist(d)}catch(h){if(n.onError?.(l.name,h),s)throw new An(l.name,h)}n.onProgress?.({file:l.name,loadedBytes:u.byteLength,totalBytes:u.byteLength,state:"parsed"}),c.push({archive:d,mounted:!0,validation:f})}catch(u){if(n.onProgress?.({file:l.name,loadedBytes:0,totalBytes:0,state:"error"}),n.onError?.(l.name,u),s)throw new An(l.name,u)}return c}var En=class{constructor(e,r=1/0,n=()=>0){this._capacity=e;this._maxMemory=r;this.sizeCalculator=n;this.map=new Map;this.currentMemoryUsage=0;if(e<=0)throw new RangeError("LRU cache capacity must be greater than zero")}get size(){return this.map.size}get memoryUsage(){return this.currentMemoryUsage}get capacity(){return this._capacity}set capacity(e){if(e<=0)throw new RangeError("LRU cache capacity must be greater than zero");this._capacity=e,this.evict()}get maxMemory(){return this._maxMemory}set maxMemory(e){this._maxMemory=e,this.evict()}has(e){return this.map.has(e)}get(e){let r=this.map.get(e);if(r!==void 0)return this.map.delete(e),this.map.set(e,r),r}set(e,r){let n=this.sizeCalculator(r);this.map.has(e)&&this.delete(e),this.map.set(e,r),this.currentMemoryUsage+=n,this.evict()}delete(e){let r=this.map.get(e);return r!==void 0?(this.currentMemoryUsage-=this.sizeCalculator(r),this.map.delete(e)):!1}clear(){this.map.clear(),this.currentMemoryUsage=0}entries(){return Array.from(this.map.entries()).reverse().map(([e,r])=>({key:e,value:r}))}evict(){for(;this.map.size>this._capacity;){let e=this.map.keys().next();if(!e.done)this.delete(e.value);else break}for(;this.currentMemoryUsage>this._maxMemory&&this.map.size>0;){let e=this.map.keys().next();if(!e.done)this.delete(e.value);else break}}};function oy(t){return Array.isArray(t)?t:Array.from(t)}function Iu(t){return oy(t).map(e=>({name:e.name,data:e}))}async function ph(t,e,r){let n=Iu(e);return cl(t,n,r??{})}function gh(t,e){let r=i=>{i.preventDefault(),i.dataTransfer?.dropEffect&&(i.dataTransfer.dropEffect="copy")},n=i=>{i.preventDefault();let a=i.dataTransfer?.files;a&&a.length>0&&e(Array.from(a))};return t.addEventListener("dragover",r),t.addEventListener("drop",n),()=>{t.removeEventListener("dragover",r),t.removeEventListener("drop",n)}}function yh(t,e){let r=n=>{let i=n.target;!i||!i.files||i.files.length===0||(e(i.files),i.value="")};return t.addEventListener("change",r),()=>t.removeEventListener("change",r)}var sy="IBSP",ly=38,xh=19,cy=8+xh*8,Du=(b=>(b[b.Entities=0]="Entities",b[b.Planes=1]="Planes",b[b.Vertices=2]="Vertices",b[b.Visibility=3]="Visibility",b[b.Nodes=4]="Nodes",b[b.TexInfo=5]="TexInfo",b[b.Faces=6]="Faces",b[b.Lighting=7]="Lighting",b[b.Leafs=8]="Leafs",b[b.LeafFaces=9]="LeafFaces",b[b.LeafBrushes=10]="LeafBrushes",b[b.Edges=11]="Edges",b[b.SurfEdges=12]="SurfEdges",b[b.Models=13]="Models",b[b.Brushes=14]="Brushes",b[b.BrushSides=15]="BrushSides",b[b.Pop=16]="Pop",b[b.Areas=17]="Areas",b[b.AreaPortals=18]="AreaPortals",b))(Du||{}),le=class extends Error{},Yi=class{constructor(e,r={}){this.vfs=e;this.options=r}async load(e){let r=await this.vfs.readFile(e),n=new Uint8Array(r.byteLength);if(n.set(new Uint8Array(r)),this.options.useWorker&&typeof Worker<"u")try{let i=await this.parseInWorker(n.buffer);return vh(i)}catch(i){console.warn("BSP worker parsing failed, falling back to main thread",i)}return lo(n.buffer)}parseInWorker(e){return new Promise((r,n)=>{if(!this.options.workerPath){n(new Error("No worker path provided"));return}let i=new Worker(this.options.workerPath,{type:"module"});i.onmessage=a=>{let{type:o,data:s,message:c}=a.data;o==="success"?(r(this.rehydrateData(s)),i.terminate()):(n(new Error(c)),i.terminate())},i.onerror=a=>{n(a),i.terminate()},i.postMessage(e,[e])})}rehydrateData(e){if(e.entities&&!e.entities.getUniqueClassnames){let r=e.entities;r.getUniqueClassnames=function(){let n=new Set;for(let i of this.entities)i.classname&&n.add(i.classname);return Array.from(n).sort()}}return e}};function lo(t){let e=uy(t);return vh(e)}function vh(t){return{...t,pickEntity(e){let r=null,n=1/0;for(let i of t.entities.entities){let a=i.properties.model;if(!a||!a.startsWith("*"))continue;let o=parseInt(a.substring(1),10);if(isNaN(o)||o<0||o>=t.models.length)continue;let s=t.models[o],c=dy(e.origin,e.direction,s.mins,s.maxs);c!==null&&c<n&&(n=c,r={entity:i,model:s,distance:c})}return r},findLeaf(e){let n=t.models[0].headNode;for(;n>=0;){let i=t.nodes[n],a=t.planes[i.planeIndex];a.normal[0]*e[0]+a.normal[1]*e[1]+a.normal[2]*e[2]-a.dist>=0?n=i.children[0]:n=i.children[1]}return t.leafs[-(n+1)]},calculatePVS(e){let r=this.findLeaf(e);if(!(r.cluster===-1||!t.visibility)&&!(r.cluster<0||r.cluster>=t.visibility.clusters.length))return t.visibility.clusters[r.cluster].pvs}}}function uy(t){if(t.byteLength<cy)throw new le("BSP too small to contain header");let e=new DataView(t),r=String.fromCharCode(e.getUint8(0),e.getUint8(1),e.getUint8(2),e.getUint8(3));if(r!==sy)throw new le(`Invalid BSP magic ${r}`);let n=e.getInt32(4,!0);if(n!==ly)throw new le(`Unsupported BSP version ${n}`);let i=new Map;for(let A=0;A<xh;A+=1){let L=e.getInt32(8+A*8,!0),M=e.getInt32(12+A*8,!0);if(L<0||M<0||L+M>t.byteLength)throw new le(`Invalid lump bounds for index ${A}`);i.set(A,{offset:L,length:M})}let a={version:n,lumps:i},o=fy(t,i.get(0)),s=my(t,i.get(1)),c=py(t,i.get(2)),l=gy(t,i.get(4)),u=yy(t,i.get(5)),d=by(t,i.get(6)),f=new Uint8Array(t,i.get(7).offset,i.get(7).length),h=Ry(d,i.get(7)),m=xy(t,i.get(8)),g=vy(t,i.get(11)),p=_y(t,i.get(12)),y=Sy(t,i.get(13)),v=wy(t,i.get(14)),b=My(t,i.get(15)),x=Ty(t,i.get(9),i.get(10),m),_=Py(t,i.get(3)),w=Ay(t,i.get(17)),S=Ey(t,i.get(18));return{header:a,entities:o,planes:s,vertices:c,nodes:l,texInfo:u,faces:d,lightMaps:f,lightMapInfo:h,leafs:m,leafLists:x,edges:g,surfEdges:p,models:y,brushes:v,brushSides:b,visibility:_,areas:w,areaPortals:S}}function dy(t,e,r,n){let i=0,a=1/0;for(let o=0;o<3;o++)if(Math.abs(e[o])<1e-8){if(t[o]<r[o]||t[o]>n[o])return null}else{let s=1/e[o],c=(r[o]-t[o])*s,l=(n[o]-t[o])*s;if(c>l){let u=c;c=l,l=u}if(i=Math.max(i,c),a=Math.min(a,l),i>a)return null}return i}function fy(t,e){let r=new TextDecoder().decode(new Uint8Array(t,e.offset,e.length)),n=hy(r),i=n.find(a=>a.classname==="worldspawn");return{raw:r,entities:n,worldspawn:i,getUniqueClassnames(){let a=new Set;for(let o of n)o.classname&&a.add(o.classname);return Array.from(a).sort()}}}function hy(t){let e=[],r=/\{([^}]*)\}/gms,n;for(;(n=r.exec(t))!==null;){let i=n[1],a={},o=/"([^\"]*)"\s+"([^\"]*)"/g,s;for(;(s=o.exec(i))!==null;)a[s[1]]=s[2];e.push({classname:a.classname,properties:a})}return e}function my(t,e){let r=new DataView(t,e.offset,e.length),n=e.length/20;if(n%1!==0)throw new le("Plane lump has invalid length");let i=[];for(let a=0;a<n;a+=1){let o=[r.getFloat32(a*20,!0),r.getFloat32(a*20+4,!0),r.getFloat32(a*20+8,!0)],s=r.getFloat32(a*20+12,!0),c=r.getInt32(a*20+16,!0);i.push({normal:o,dist:s,type:c})}return i}function py(t,e){let r=new DataView(t,e.offset,e.length),n=e.length/12;if(n%1!==0)throw new le("Vertex lump has invalid length");let i=[];for(let a=0;a<n;a+=1)i.push([r.getFloat32(a*12,!0),r.getFloat32(a*12+4,!0),r.getFloat32(a*12+8,!0)]);return i}function gy(t,e){let r=new DataView(t,e.offset,e.length),n=28,i=e.length/n;if(i%1!==0)throw new le("Node lump has invalid length");let a=[];for(let o=0;o<i;o+=1){let s=o*n,c=r.getInt32(s,!0),l=[r.getInt32(s+4,!0),r.getInt32(s+8,!0)],u=[r.getInt16(s+12,!0),r.getInt16(s+14,!0),r.getInt16(s+16,!0)],d=[r.getInt16(s+18,!0),r.getInt16(s+20,!0),r.getInt16(s+22,!0)],f=r.getUint16(s+24,!0),h=r.getUint16(s+26,!0);a.push({planeIndex:c,children:l,mins:u,maxs:d,firstFace:f,numFaces:h})}return a}function yy(t,e){let r=new DataView(t,e.offset,e.length),n=76,i=e.length/n;if(i%1!==0)throw new le("TexInfo lump has invalid length");let a=[];for(let o=0;o<i;o+=1){let s=o*n,c=[r.getFloat32(s,!0),r.getFloat32(s+4,!0),r.getFloat32(s+8,!0)],l=r.getFloat32(s+12,!0),u=[r.getFloat32(s+16,!0),r.getFloat32(s+20,!0),r.getFloat32(s+24,!0)],d=r.getFloat32(s+28,!0),f=r.getInt32(s+32,!0),h=r.getInt32(s+36,!0),m=new Uint8Array(t,e.offset+s+40,32),g=new TextDecoder("utf-8").decode(m).replace(/\0.*$/,""),p=r.getInt32(s+72,!0);a.push({s:c,sOffset:l,t:u,tOffset:d,flags:f,value:h,texture:g,nextTexInfo:p})}return a}function by(t,e){let r=new DataView(t,e.offset,e.length),n=20,i=e.length/n;if(i%1!==0)throw new le("Face lump has invalid length");let a=[];for(let o=0;o<i;o+=1){let s=o*n,c=r.getUint16(s,!0),l=r.getInt16(s+2,!0),u=r.getInt32(s+4,!0),d=r.getInt16(s+8,!0),f=r.getInt16(s+10,!0),h=[r.getUint8(s+12),r.getUint8(s+13),r.getUint8(s+14),r.getUint8(s+15)],m=r.getInt32(s+16,!0);a.push({planeIndex:c,side:l,firstEdge:u,numEdges:d,texInfo:f,styles:h,lightOffset:m})}return a}function xy(t,e){let r=new DataView(t,e.offset,e.length),n=28,i=e.length/n;if(i%1!==0)throw new le("Leaf lump has invalid length");let a=[];for(let o=0;o<i;o+=1){let s=o*n,c=r.getInt32(s,!0),l=r.getInt16(s+4,!0),u=r.getInt16(s+6,!0),d=[r.getInt16(s+8,!0),r.getInt16(s+10,!0),r.getInt16(s+12,!0)],f=[r.getInt16(s+14,!0),r.getInt16(s+16,!0),r.getInt16(s+18,!0)],h=r.getUint16(s+20,!0),m=r.getUint16(s+22,!0),g=r.getUint16(s+24,!0),p=r.getUint16(s+26,!0);a.push({contents:c,cluster:l,area:u,mins:d,maxs:f,firstLeafFace:h,numLeafFaces:m,firstLeafBrush:g,numLeafBrushes:p})}return a}function vy(t,e){let r=new DataView(t,e.offset,e.length),n=4,i=e.length/n;if(i%1!==0)throw new le("Edge lump has invalid length");let a=[];for(let o=0;o<i;o+=1){let s=o*n;a.push({vertices:[r.getUint16(s,!0),r.getUint16(s+2,!0)]})}return a}function _y(t,e){let r=e.length/4;if(r%1!==0)throw new le("SurfEdge lump has invalid length");let n=new DataView(t,e.offset,e.length),i=new Int32Array(r);for(let a=0;a<r;a+=1)i[a]=n.getInt32(a*4,!0);return i}function Sy(t,e){let r=new DataView(t,e.offset,e.length),n=48;if(e.length%n!==0)throw new le("Model lump has invalid length");let i=e.length/n,a=[];for(let o=0;o<i;o+=1){let s=o*n,c=[r.getFloat32(s,!0),r.getFloat32(s+4,!0),r.getFloat32(s+8,!0)],l=[r.getFloat32(s+12,!0),r.getFloat32(s+16,!0),r.getFloat32(s+20,!0)],u=[r.getFloat32(s+24,!0),r.getFloat32(s+28,!0),r.getFloat32(s+32,!0)],d=r.getInt32(s+36,!0),f=r.getInt32(s+40,!0),h=r.getInt32(s+44,!0);a.push({mins:c,maxs:l,origin:u,headNode:d,firstFace:f,numFaces:h})}return a}function wy(t,e){let r=new DataView(t,e.offset,e.length),n=12,i=e.length/n;if(i%1!==0)throw new le("Brush lump has invalid length");let a=[];for(let o=0;o<i;o+=1){let s=o*n;a.push({firstSide:r.getInt32(s,!0),numSides:r.getInt32(s+4,!0),contents:r.getInt32(s+8,!0)})}return a}function My(t,e){let r=new DataView(t,e.offset,e.length),n=4,i=e.length/n;if(i%1!==0)throw new le("Brush side lump has invalid length");let a=[];for(let o=0;o<i;o+=1){let s=o*n;a.push({planeIndex:r.getUint16(s,!0),texInfo:r.getInt16(s+2,!0)})}return a}function Ay(t,e){let r=new DataView(t,e.offset,e.length),n=8,i=e.length/n;if(i%1!==0)throw new le("Area lump has invalid length");let a=[];for(let o=0;o<i;o+=1){let s=o*n,c=r.getInt32(s,!0),l=r.getInt32(s+4,!0);a.push({numAreaPortals:c,firstAreaPortal:l})}return a}function Ey(t,e){return Ly(t,e)}function Ly(t,e){let r=new DataView(t,e.offset,e.length),n=8,i=e.length/n;if(i%1!==0)throw new le("AreaPortal lump has invalid length");let a=[];for(let o=0;o<i;o+=1){let s=o*n,c=r.getInt32(s,!0),l=r.getInt32(s+4,!0);a.push({portalNumber:c,otherArea:l})}return a}function Ty(t,e,r,n){let i=[],a=[],o=e.length/2,s=r.length/2,c=new DataView(t,e.offset,e.length),l=new DataView(t,r.offset,r.length);for(let u of n){if(u.firstLeafFace+u.numLeafFaces>o)throw new le("Leaf faces reference data past lump bounds");if(u.firstLeafBrush+u.numLeafBrushes>s)throw new le("Leaf brushes reference data past lump bounds");let d=[];for(let h=0;h<u.numLeafFaces;h+=1)d.push(c.getUint16((u.firstLeafFace+h)*2,!0));let f=[];for(let h=0;h<u.numLeafBrushes;h+=1)f.push(l.getUint16((u.firstLeafBrush+h)*2,!0));i.push(d),a.push(f)}return{leafFaces:i,leafBrushes:a}}function Py(t,e){if(e.length===0)return;if(e.length<4)throw new le("Visibility lump too small");let r=new DataView(t,e.offset,e.length),n=r.getInt32(0,!0),i=4+n*8;if(n<0||i>e.length)throw new le("Visibility lump truncated");let a=4,o=[];for(let s=0;s<n;s+=1){let c=r.getInt32(a,!0),l=r.getInt32(a+4,!0);a+=8;let u=e.offset+c,d=e.offset+l,f=e.offset+e.length;if(c<0||l<0||u>=f||d>=f)throw new le("Visibility offsets out of range");o.push({pvs:bh(t,u,n,e),phs:bh(t,d,n,e)})}return{numClusters:n,clusters:o}}function bh(t,e,r,n){let i=Math.ceil(r/8),a=new Uint8Array(i),o=new Uint8Array(t),s=e,c=0,l=n.offset+n.length;for(;c<i;){if(s>=l)throw new le("Visibility data truncated");let u=o[s++];if(u!==0){a[c++]=u;continue}if(s>=l)throw new le("Visibility run exceeds lump bounds");let d=o[s++];for(let f=0;f<d&&c<i;f+=1)a[c++]=0}return a}function Ry(t,e){return t.map(r=>{if(!(r.lightOffset<0))return{offset:r.lightOffset,length:Math.max(0,e.length-r.lightOffset)}})}function ul(t,e,r){if(t.lightOffset<0||t.lightOffset>=e.byteLength)return;let n=e.byteLength-t.lightOffset,i=Math.min(r?.length??n,n);if(!(i<=0))return e.subarray(t.lightOffset,t.lightOffset+i)}var Cy=844121161,By=8,_h=68,it=class extends Error{},qi=class{constructor(e){this.vfs=e;this.cache=new Map}async load(e){if(this.cache.has(e))return this.cache.get(e);let r=await this.vfs.readFile(e),n=new Uint8Array(r.byteLength);n.set(r);let i=ku(n.buffer);return this.cache.set(e,i),i}get(e){return this.cache.get(e)}};function Sh(t,e,r){let n=[];for(let i=0;i<r;i+=1){let a=t.getUint8(e+i);if(a===0)break;n.push(a)}return String.fromCharCode(...n)}function co(t,e,r,n){if(r!==0&&(e<_h||e+r>t.byteLength))throw new it(`${n} section is out of bounds`)}function Fy(t){if(t.byteLength<_h)throw new it("MD2 buffer too small to contain header");let e=new DataView(t),r=e.getInt32(0,!0),n=e.getInt32(4,!0);if(r!==Cy)throw new it(`Invalid MD2 ident: ${r}`);if(n!==By)throw new it(`Unsupported MD2 version: ${n}`);let i={ident:r,version:n,skinWidth:e.getInt32(8,!0),skinHeight:e.getInt32(12,!0),frameSize:e.getInt32(16,!0),numSkins:e.getInt32(20,!0),numVertices:e.getInt32(24,!0),numTexCoords:e.getInt32(28,!0),numTriangles:e.getInt32(32,!0),numGlCommands:e.getInt32(36,!0),numFrames:e.getInt32(40,!0),offsetSkins:e.getInt32(44,!0),offsetTexCoords:e.getInt32(48,!0),offsetTriangles:e.getInt32(52,!0),offsetFrames:e.getInt32(56,!0),offsetGlCommands:e.getInt32(60,!0),offsetEnd:e.getInt32(64,!0),magic:r},a=40+i.numVertices*4;if(i.frameSize!==a)throw new it(`Unexpected frame size ${i.frameSize}, expected ${a}`);if(i.offsetEnd>t.byteLength)throw new it("MD2 offset_end exceeds buffer length");return i}function Iy(t,e){let r=e.numSkins*64;co(t,e.offsetSkins,r,"skins");let n=new DataView(t,e.offsetSkins,r),i=[];for(let a=0;a<e.numSkins;a+=1)i.push({name:Sh(n,a*64,64)});return i}function Dy(t,e){let r=e.numTexCoords*4;co(t,e.offsetTexCoords,r,"texcoords");let n=new DataView(t,e.offsetTexCoords,r),i=[];for(let a=0;a<e.numTexCoords;a+=1){let o=a*4;i.push({s:n.getInt16(o,!0),t:n.getInt16(o+2,!0)})}return i}function ky(t,e){let r=e.numTriangles*12;co(t,e.offsetTriangles,r,"triangles");let n=new DataView(t,e.offsetTriangles,r),i=[];for(let a=0;a<e.numTriangles;a+=1){let o=a*12,s=[n.getUint16(o,!0),n.getUint16(o+2,!0),n.getUint16(o+4,!0)],c=[n.getUint16(o+6,!0),n.getUint16(o+8,!0),n.getUint16(o+10,!0)];if(s.some(l=>l>=e.numVertices)||c.some(l=>l>=e.numTexCoords))throw new it("Triangle references out of range vertex or texcoord");i.push({vertexIndices:s,texCoordIndices:c})}return i}function Uy(t,e){let r=e.numFrames*e.frameSize;co(t,e.offsetFrames,r,"frames");let n=[];for(let i=0;i<e.numFrames;i+=1){let a=e.offsetFrames+i*e.frameSize,o=new DataView(t,a,e.frameSize),s={x:o.getFloat32(0,!0),y:o.getFloat32(4,!0),z:o.getFloat32(8,!0)},c={x:o.getFloat32(12,!0),y:o.getFloat32(16,!0),z:o.getFloat32(20,!0)},l=Sh(o,24,16),u=[],d=1/0,f=1/0,h=1/0,m=-1/0,g=-1/0,p=-1/0;for(let y=0;y<e.numVertices;y+=1){let v=40+y*4,b=o.getUint8(v)*s.x+c.x,x=o.getUint8(v+1)*s.y+c.y,_=o.getUint8(v+2)*s.z+c.z;b<d&&(d=b),x<f&&(f=x),_<h&&(h=_),b>m&&(m=b),x>g&&(g=x),_>p&&(p=_);let w={x:b,y:x,z:_},S=o.getUint8(v+3),A=mr[S];if(!A)throw new it(`Invalid normal index ${S} in frame ${l}`);let L={x:A[0],y:A[1],z:A[2]};u.push({position:w,normalIndex:S,normal:L})}n.push({name:l,vertices:u,minBounds:{x:d,y:f,z:h},maxBounds:{x:m,y:g,z:p}})}return n}function zy(t,e){let r=e.numGlCommands*4;if(co(t,e.offsetGlCommands,r,"gl commands"),r===0)return[];let n=new DataView(t,e.offsetGlCommands,r),i=[],a=0;for(;;){if(a+4>r)throw new it("GL command list ended unexpectedly");let o=n.getInt32(a,!0);if(a+=4,o===0)break;let s=Math.abs(o),c=[],l=s*12;if(a+l>r)throw new it("GL command vertex block exceeds buffer");for(let u=0;u<s;u+=1){let d=n.getFloat32(a,!0),f=n.getFloat32(a+4,!0),h=n.getInt32(a+8,!0);if(a+=12,h<0||h>=e.numVertices)throw new it("GL command references invalid vertex index");c.push({s:d,t:f,vertexIndex:h})}i.push({mode:o>0?"strip":"fan",vertices:c})}if(a!==r)throw new it("GL command list did not consume expected data");return i}function ku(t){let e=Fy(t),r=Iy(t,e),n=Dy(t,e),i=ky(t,e),a=Uy(t,e),o=zy(t,e);return{header:e,skins:r,texCoords:n,triangles:i,frames:a,glCommands:o}}function wh(t){let e=[],r=0;for(;r<t.length;){let n=t[r].name,i=n.replace(/\d+$/,"")||n,a=r;for(;a+1<t.length&&(t[a+1].name.replace(/\d+$/,"")||t[a+1].name)===i;)a+=1;e.push({name:i,firstFrame:r,lastFrame:a}),r=a+1}return e}var Mh=860898377,Oy=15,er=class extends Error{constructor(e){super(e),this.name="Md3ParseError"}};function uo(t,e,r){let n=new Uint8Array(t.buffer,t.byteOffset+e,r);return new TextDecoder("utf-8").decode(n).replace(/\0.*$/,"").trim()}function Ny(t){let e=(t>>8&255)*(2*Math.PI/255),r=(t&255)*(2*Math.PI/255),n=Math.sin(r);return{x:Math.cos(e)*n,y:Math.sin(e)*n,z:Math.cos(r)}}function dl(t,e,r,n){if(e<0||e+r>n)throw new er(`${t} exceeds buffer bounds`)}function Gy(t){let e=t.getInt32(0,!0);if(e!==Mh)throw new er(`Invalid MD3 ident: ${e}`);let r=t.getInt32(4,!0);if(r!==Oy)throw new er(`Unsupported MD3 version: ${r}`);let n=uo(t,8,64),i=t.getInt32(72,!0),a=t.getInt32(76,!0),o=t.getInt32(80,!0),s=t.getInt32(84,!0),c=t.getInt32(88,!0),l=t.getInt32(92,!0),u=t.getInt32(96,!0),d=t.getInt32(100,!0),f=t.getInt32(104,!0);if(a<=0||s<0||o<0)throw new er("Invalid MD3 counts");return{ident:e,version:r,name:n,flags:i,numFrames:a,numTags:o,numSurfaces:s,numSkins:c,ofsFrames:l,ofsTags:u,ofsSurfaces:d,ofsEnd:f,magic:e}}function Vy(t,e){let r=[];dl("Frames",e.ofsFrames,e.numFrames*56,t.byteLength);for(let i=0;i<e.numFrames;i+=1){let a=e.ofsFrames+i*56;r.push({minBounds:{x:t.getFloat32(a,!0),y:t.getFloat32(a+4,!0),z:t.getFloat32(a+8,!0)},maxBounds:{x:t.getFloat32(a+12,!0),y:t.getFloat32(a+16,!0),z:t.getFloat32(a+20,!0)},localOrigin:{x:t.getFloat32(a+24,!0),y:t.getFloat32(a+28,!0),z:t.getFloat32(a+32,!0)},radius:t.getFloat32(a+36,!0),name:uo(t,a+40,16)})}return r}function Hy(t,e){let r=[],i=e.numFrames*e.numTags*112;dl("Tags",e.ofsTags,i,t.byteLength);for(let a=0;a<e.numFrames;a+=1){let o=[];for(let s=0;s<e.numTags;s+=1){let c=e.ofsTags+(a*e.numTags+s)*112,l=c+64,u=l+12;o.push({name:uo(t,c,64),origin:{x:t.getFloat32(l,!0),y:t.getFloat32(l+4,!0),z:t.getFloat32(l+8,!0)},axis:[{x:t.getFloat32(u,!0),y:t.getFloat32(u+4,!0),z:t.getFloat32(u+8,!0)},{x:t.getFloat32(u+12,!0),y:t.getFloat32(u+16,!0),z:t.getFloat32(u+20,!0)},{x:t.getFloat32(u+24,!0),y:t.getFloat32(u+28,!0),z:t.getFloat32(u+32,!0)}]})}r.push(o)}return r}function Wy(t,e){let r=t.getInt32(e,!0);if(r!==Mh)throw new er(`Invalid surface ident at ${e}: ${r}`);let n=uo(t,e+4,64),i=t.getInt32(e+68,!0),a=t.getInt32(e+72,!0),o=t.getInt32(e+76,!0),s=t.getInt32(e+80,!0),c=t.getInt32(e+84,!0),l=t.getInt32(e+88,!0),u=t.getInt32(e+92,!0),d=t.getInt32(e+96,!0),f=t.getInt32(e+100,!0),h=t.getInt32(e+104,!0);if(a<=0||s<=0||c<=0)throw new er(`Invalid surface counts for ${n}`);let m=h;dl(`Surface ${n}`,e,m,t.byteLength);let g=[],p=e+l;for(let S=0;S<c;S+=1){let A=p+S*12;g.push({indices:[t.getInt32(A,!0),t.getInt32(A+4,!0),t.getInt32(A+8,!0)]})}let y=[],v=e+u;for(let S=0;S<o;S+=1){let A=v+S*68;y.push({name:uo(t,A,64),shaderIndex:t.getInt32(A+64,!0)})}let b=[],x=e+d;for(let S=0;S<s;S+=1){let A=x+S*8;b.push({s:t.getFloat32(A,!0),t:t.getFloat32(A+4,!0)})}let _=[],w=e+f;for(let S=0;S<a;S+=1){let A=[];for(let L=0;L<s;L+=1){let M=w+(S*s+L)*8,P=t.getInt16(M,!0)/64,I=t.getInt16(M+2,!0)/64,D=t.getInt16(M+4,!0)/64,B=t.getUint16(M+6,!0);A.push({position:{x:P,y:I,z:D},latLng:B,normal:Ny(B)})}_.push(A)}return{surface:{name:n,flags:i,numFrames:a,shaders:y,triangles:g,texCoords:b,vertices:_},nextOffset:e+h}}function Uu(t){if(t.byteLength<108)throw new er("MD3 buffer too small for header");let e=new DataView(t),r=Gy(e);dl("MD3 end",r.ofsEnd,0,t.byteLength);let n=Vy(e,r),i=Hy(e,r),a=[],o=r.ofsSurfaces;for(let s=0;s<r.numSurfaces;s+=1){let{surface:c,nextOffset:l}=Wy(e,o);a.push(c),o=l}if(o!==r.ofsEnd)throw new er("Surface parsing did not reach ofsEnd");return{header:r,frames:n,tags:i,surfaces:a}}var Zi=class{constructor(e){this.vfs=e;this.cache=new Map}async load(e){if(this.cache.has(e))return this.cache.get(e);let r=await this.vfs.readFile(e),n=Uu(r.slice().buffer);return this.cache.set(e,n),n}get(e){return this.cache.get(e)}};var Xy=844317769,$y=2,Ah=64,Eh=12,Ln=class extends Error{};function Ky(t,e,r){let n=[];for(let i=0;i<r;i+=1){let a=t.getUint8(e+i);if(a===0)break;n.push(a)}return String.fromCharCode(...n)}function zu(t){if(t.byteLength<Eh)throw new Ln("Sprite buffer too small to contain header");let e=new DataView(t),r=e.getInt32(0,!0),n=e.getInt32(4,!0),i=e.getInt32(8,!0);if(r!==Xy)throw new Ln(`Invalid Sprite ident: ${r}`);if(n!==$y)throw new Ln(`Unsupported Sprite version: ${n}`);let a=[],o=16+Ah,s=Eh;for(let c=0;c<i;c+=1){if(s+o>t.byteLength)throw new Ln("Sprite frame data exceeds buffer length");let l=e.getInt32(s,!0),u=e.getInt32(s+4,!0),d=e.getInt32(s+8,!0),f=e.getInt32(s+12,!0),h=Ky(e,s+16,Ah);a.push({width:l,height:u,originX:d,originY:f,name:h}),s+=o}return{ident:r,version:n,numFrames:i,frames:a}}var ji=class{constructor(e){this.vfs=e}async load(e){let r=await this.vfs.readFile(e),n=new Uint8Array(r.byteLength);return n.set(r),zu(n.buffer)}};function Lh(t,e){let r=(t.sequence.end-t.sequence.start+1)/t.sequence.fps,n=t.sequence.loop!==!1,i=t.time+e;return n?i=(i%r+r)%r:i>r&&(i=r),{...t,time:Math.max(0,Math.min(i,r))}}function Th(t){let e=t.sequence.end-t.sequence.start+1,r=1/t.sequence.fps,n=t.sequence.loop!==!1,i=t.time/r;if(!n&&i>=e)return{frame0:t.sequence.end,frame1:t.sequence.end,lerp:0};let a=n?i%e:Math.min(i,e-1),o=Math.floor(a),s=t.sequence.start+o,c=o+1>=e?n?t.sequence.start:t.sequence.end:s+1,l=!n&&o>=e-1?0:a-o;return{frame0:s,frame1:c,lerp:l}}function Ph(t){return{sequence:t,time:0}}function Rh(t,e,r){return{x:t.x+(e.x-t.x)*r,y:t.y+(e.y-t.y)*r,z:t.z+(e.z-t.z)*r}}var fo=class extends Error{constructor(e){super(e),this.name="WalParseError"}};function fl(t){if(t.byteLength<100)throw new fo("WAL buffer too small");let e=new DataView(t),r=new Uint8Array(t,0,32),n=new TextDecoder("utf-8").decode(r).replace(/\0.*$/,"").trim(),i=e.getInt32(32,!0),a=e.getInt32(36,!0),o=[e.getInt32(40,!0),e.getInt32(44,!0),e.getInt32(48,!0),e.getInt32(52,!0)],s=new Uint8Array(t,56,32),c=new TextDecoder("utf-8").decode(s).replace(/\0.*$/,"").trim(),l=e.getInt32(88,!0),u=e.getInt32(92,!0),d=e.getInt32(96,!0);if(i<=0||a<=0)throw new fo("Invalid WAL dimensions");let f=[],h=i,m=a;for(let g=0;g<o.length;g+=1){let p=o[g],y=Math.max(1,h*m|0);if(p<=0||p+y>t.byteLength)throw new fo(`Invalid WAL mip offset for level ${g}`);let v=new Uint8Array(t,p,y);f.push({level:g,width:h,height:m,data:v}),h=Math.max(1,h>>1),m=Math.max(1,m>>1)}return{name:n,width:i,height:a,mipmaps:f,animName:c,flags:l,contents:u,value:d}}var ci=class extends Error{constructor(e){super(e),this.name="PcxParseError"}};function ho(t){if(t.byteLength<128)throw new ci("PCX buffer too small for header");let e=new DataView(t),r=e.getUint8(0),n=e.getUint8(2),i=e.getUint8(3),a=e.getUint16(4,!0),o=e.getUint16(6,!0),s=e.getUint16(8,!0),c=e.getUint16(10,!0);if(r!==10||n!==1)throw new ci("Unsupported PCX encoding");if(i!==8)throw new ci("Only 8bpp PCX files are supported");let l=s-a+1,u=c-o+1,d=e.getUint16(66,!0),f=t.byteLength-769;if(f<128||new DataView(t,f,1).getUint8(0)!==12)throw new ci("Missing PCX palette");let h=new Uint8Array(t,f+1,768),m=new Uint8Array(t,128,f-128),g=new Uint8Array(l*u),p=0,y=0;for(let v=0;v<u;v+=1){let b=0;for(;b<d&&p<m.length;){let x=1,_=m[p++];if((_&192)===192){if(x=_&63,p>=m.length)throw new ci("Unexpected end of PCX RLE data");_=m[p++]}for(let w=0;w<x&&b<d;w+=1)b<l&&(g[y++]=_),b+=1}}return{width:l,height:u,bitsPerPixel:i,pixels:g,palette:h}}function hl(t){let e=new Uint8Array(t.width*t.height*4);for(let r=0;r<t.pixels.length;r+=1){let n=t.pixels[r],i=n*3,a=r*4;e[a]=t.palette[i],e[a+1]=t.palette[i+1],e[a+2]=t.palette[i+2],e[a+3]=n===255?0:255}return e}var qr=class extends Error{constructor(e){super(e),this.name="TgaParseError"}};function Ou(t){let e=new DataView(t);if(t.byteLength<18)throw new qr("Buffer too small for TGA header");let r=e.getUint8(0),n=e.getUint8(1),i=e.getUint8(2),a=e.getUint16(12,!0),o=e.getUint16(14,!0),s=e.getUint8(16),c=e.getUint8(17);if(i!==2&&i!==10&&i!==3&&i!==11)throw new qr(`Unsupported TGA image type: ${i} (only RGB/Grayscale supported)`);if(s!==24&&s!==32&&s!==8)throw new qr(`Unsupported pixel depth: ${s} (only 8, 24, 32 bpp supported)`);let l=i>=9,u=i===3||i===11,d=s/8,f=18+r;if(n===1){let b=e.getUint16(5,!0),x=e.getUint8(7);f+=b*(x/8)}let h=a*o,m=new Uint8Array(h*4),g=(c&32)!==0,p=0,y=new Uint8Array(t),v=b=>{if(u){let x=y[f++];m[b]=x,m[b+1]=x,m[b+2]=x,m[b+3]=255}else{let x=y[f++],_=y[f++],w=y[f++],S=s===32?y[f++]:255;m[b]=w,m[b+1]=_,m[b+2]=x,m[b+3]=S}};if(l){let b=0;for(;b<h;){if(f>=t.byteLength)throw new qr("Unexpected end of TGA RLE data");let x=y[f++],_=(x&127)+1,w=(x&128)!==0;if(b+_>h)throw new qr("TGA RLE packet exceeds image bounds");if(w){let S=u?y[f]:y[f+2],A=u?y[f]:y[f+1],L=y[f],M=u?255:s===32?y[f+3]:255;f+=d;for(let P=0;P<_;P++){let I=(b+P)*4;m[I]=S,m[I+1]=A,m[I+2]=L,m[I+3]=M}}else for(let S=0;S<_;S++)v((b+S)*4);b+=_}}else for(let b=0;b<h;b++){if(f>=t.byteLength)throw new qr("Unexpected end of TGA data");v(b*4)}if(!g){let b=a*4,x=new Uint8Array(b);for(let _=0;_<o/2;_++){let w=_*b,S=(o-1-_)*b;x.set(m.subarray(w,w+b)),m.set(m.subarray(S,S+b),w),m.set(x,S)}}return{width:a,height:o,bitsPerPixel:32,pixels:m}}function Yy(t){let e=0;for(let r of t.levels)e+=r.rgba.byteLength;return e}var Qi=class{constructor(e={}){this.cache=new En(e.capacity??128,e.maxMemory??256*1024*1024,Yy)}get size(){return this.cache.size}get memoryUsage(){return this.cache.memoryUsage}get(e){return this.cache.get(e.toLowerCase())}set(e,r){this.cache.set(e.toLowerCase(),r)}clear(){this.cache.clear()}get capacity(){return this.cache.capacity}set capacity(e){this.cache.capacity=e}get maxMemory(){return this.cache.maxMemory}set maxMemory(e){this.cache.maxMemory=e}};function Nu(t,e){let r=[];for(let n of t.mipmaps){let i=new Uint8Array(n.width*n.height*4);for(let a=0;a<n.data.length;a+=1){let o=n.data[a],s=o*3,c=a*4;i[c]=e[s],i[c+1]=e[s+1],i[c+2]=e[s+2],i[c+3]=o===255?0:255}r.push({level:n.level,width:n.width,height:n.height,rgba:i})}return{width:t.width,height:t.height,levels:r,source:"wal"}}function ml(t){let e=hl(t),r={level:0,width:t.width,height:t.height,rgba:e};return{width:t.width,height:t.height,levels:[r],source:"pcx"}}function Ch(t){let e={level:0,width:t.width,height:t.height,rgba:t.pixels};return{width:t.width,height:t.height,levels:[e],source:"tga"}}function pl(t,e){return Nu(fl(t),e)}var ui=class extends Error{constructor(e){super(e),this.name="WavParseError"}};function Gu(t,e,r){return new TextDecoder("ascii").decode(new Uint8Array(t.buffer,t.byteOffset+e,r))}function gl(t){if(t.byteLength<44)throw new ui("WAV buffer too small");let e=new DataView(t);if(Gu(e,0,4)!=="RIFF"||Gu(e,8,4)!=="WAVE")throw new ui("Invalid WAV header");let r=12,n=-1,i=-1,a=0,o=0;for(;r+8<=t.byteLength;){let m=Gu(e,r,4),g=e.getUint32(r+4,!0),p=r+8;m==="fmt "?(n=p,a=g):m==="data"&&(i=p,o=g),r=p+g}if(n===-1||i===-1)throw new ui("Missing fmt or data chunk");let s=e.getUint16(n,!0),c=e.getUint16(n+2,!0),l=e.getUint32(n+4,!0),u=e.getUint16(n+14,!0);if(s!==1)throw new ui("Only PCM WAV is supported");let d=u/8,f=o/(d*c),h=new Float32Array(f*c);for(let m=0;m<f;m+=1)for(let g=0;g<c;g+=1){let p=m*c+g,y=i+p*d,v=0;if(u===8)v=e.getUint8(y),h[p]=(v-128)/128;else if(u===16)v=e.getInt16(y,!0),h[p]=v/32768;else if(u===24){let b=e.getUint8(y),x=e.getUint8(y+1),_=e.getInt8(y+2);v=b|x<<8|_<<16,h[p]=v/8388608}else throw new ui(`Unsupported bitsPerSample: ${u}`)}return{sampleRate:l,channels:c,bitsPerSample:u,samples:h}}var qy=(t,e=4294967295,r=79764919)=>{let n=new Int32Array(256),i,a,o,s=e;for(i=0;i<256;i++){for(o=i<<24,a=8;a>0;--a)o=2147483648&o?o<<1^r:o<<1;n[i]=o}for(i=0;i<t.length;i++)s=s<<8^n[255&(s>>24^t[i])];return s};var Vu=(t,e=qy)=>{let r=p=>new Uint8Array(p.length/2).map(((y,v)=>parseInt(p.substring(2*v,2*(v+1)),16))),n=p=>r(p)[0],i=new Map;[,8364,,8218,402,8222,8230,8224,8225,710,8240,352,8249,338,,381,,,8216,8217,8220,8221,8226,8211,8212,732,8482,353,8250,339,,382,376].forEach(((p,y)=>i.set(p,y)));let a=new Uint8Array(t.length),o,s,c,l=!1,u=0,d=42,f=t.length>13&&t.substring(0,9)==="dynEncode",h=0;f&&(h=11,s=n(t.substring(9,h)),s<=1&&(h+=2,d=n(t.substring(11,h))),s===1&&(h+=8,c=(p=>new DataView(r(p).buffer).getInt32(0,!0))(t.substring(13,h))));let m=256-d;for(let p=h;p<t.length;p++)if(o=t.charCodeAt(p),o!==61||l){if(o===92&&p<t.length-5&&f){let y=t.charCodeAt(p+1);y!==117&&y!==85||(o=parseInt(t.substring(p+2,p+6),16),p+=5)}if(o>255){let y=i.get(o);y&&(o=y+127)}l&&(l=!1,o-=64),a[u++]=o<d&&o>0?o+m:o-d}else l=!0;let g=a.subarray(0,u);if(f&&s===1){let p=e(g);if(p!==c){let y="Decode failed crc32 validation";throw console.error("`simple-yenc`\n",y+`
2
2
  `,"Expected: "+c+"; Got: "+p+`
3
- `,"Visit https://github.com/eshaz/simple-yenc for more information"),Error(y)}}return g};function _e(){let t=Uint8Array,e=Float32Array;_e.modules||Object.defineProperties(_e,{modules:{value:new WeakMap},setModule:{value(r,n){_e.modules.set(r,Promise.resolve(n))}},getModule:{value(r,n){let i=_e.modules.get(r);return i||(n?i=WebAssembly.compile(Vu(n)):(n=r.wasm,i=_e.inflateDynEncodeString(n).then(a=>WebAssembly.compile(a))),_e.modules.set(r,i)),i}},concatFloat32:{value(r,n){let i=new e(n),a=0,o=0;for(;a<r.length;)i.set(r[a],o),o+=r[a++].length;return i}},getDecodedAudio:{value:(r,n,i,a,o)=>({errors:r,channelData:n,samplesDecoded:i,sampleRate:a,bitDepth:o})},getDecodedAudioMultiChannel:{value(r,n,i,a,o,s){let c=[],l,u;for(l=0;l<i;l++){let d=[];for(u=0;u<n.length;)d.push(n[u++][l]||[]);c.push(_e.concatFloat32(d,a))}return _e.getDecodedAudio(r,c,a,o,s)}},inflateDynEncodeString:{value(r){return r=Vu(r),new Promise(n=>{let i=String.raw`dynEncode012804c7886d(‰›•)((()>+ˆ*§§)§ˆ,§§§§)§ˆ+§§§)§+.-()(*)-+)(ˆ.7*§)i¸¸,3§(i¸¸,3/G+.••—š¡*(,˜ŽŽ(,3‡‡‰˜‡Š‰›+)2å:-œ),§H(P*DI*H(P*@I++hH)H*r,hH(H(P*<J,i)’^*<H,H(P*4’U((I-H(H*i0’J,^*DH+H-H*œšI+H,I*4)33H(H*H)“^*DH(H+H)^*@H+i§H)œi§›™3æ*).§K(iH“I/+§H,iHn,§H+i(H+i(rCJ0I,H*I-+hH,,hH(H-V)(i)œ’J.H.W)(i)’c)(H,i)“I,H-i*’I-4)33i(I.*hH(V)(H+n5(H(i*’I-i(I,i)I.+hH,i*’J+iHn,hi(I-i*I,+hH,H/’H-c)(H,iFn,hi(I,+hH,H0n5-H*V)(J(,hH/H(i)œ’J(H(V)(J(i)’c)(H)H(i)œ’H,c)(3H*i*’I*H,i)’I,4(3(-H(H,’W)(H-’I-H,i*’I,4)3(3(3H,H-’I1H+I,H.i)œH1V)(“J.i(v5(33H.-H(H,’i(c)(H,i*’I,4)333–)-§i*I*+§H*iHn,hiž73H,H(i)8(H+šJ+H)P*(H*’V)(J-“r,§H)P*,H.i)œ’H+H,“i)œ’V)(-H*i*’I*H+i)œI+H-H.’I.H,H-’i)œI,4)333Ã+)-§iø7i(^*(iü7I,*h+hH+iDn,h*hilI+i)I,+hH+,hH+iô7’H,c)(i)H+i´8’W)(œH,’I,H+i*’I+4)-+hH(H)8*J-i(p5.*h*h*hH-i')u,hH(P*(J+,hH(P*0J,H(P*,n50H+H,’H-b((3H(P*0i)’I.4)3H-i¨*n5*H-iÅ*s,hiž73H-i)œJ+V)&+I,H(H+V)æ,8(I.H(H*8*J-i(p51H-i)œJ+i¸7’V)(H(H+iø7’V)(8(’J/H(P*0J+s,hi73H+H,H.’J,’I.H(P*(m5(H.H(P*,s5.+hH,m5*H(P*(J.H+’H.H+H/“’U((b((H(H(P*0i)’J+^*0H,i)“I,4(3(3H(H.^*03H-i¨*o5)33i(73(3(3-H,H+i)žc)(H,i*’I,H+i)’I+4)33i)I-3H-3!2)0§K(i2“J,L(H,H(^*(H,H*^*4H,i(^*0H,i(^*DH,j(_*<H,H)P*(^*,H,H+P*(^*8*h*h+hH,i)8(I3i§I**h*h*h*h*h*h*hH,i*8(6+(),03H,j(_*@i*I-H,P*<J.i,’J(H,P*8J/s50H,H.i+’J0^*<i¦I*H.H,P*4J1’J.U(*H.U((J2›i')o5/H.U()I.H,H(^*<H0H1’U((H.i0œJ.i§›i0ži')™o5/H/H.H2šJ*H(’J.q50H,P*0J/H*’I-H,P*(J0,hH,P*,H-q,hi)I-423+hH*m5+H/H0’H(H1’U((b((H/i)’I/H(i)’I(H*i)“I*4(3(3H,H.^*<H,H-^*04*3iØ1U((5+i(I(i¨7i1^*(i$6iè1^*(i°7iè6^*(i¬7iÈ6^*(+hH(iÈ*n,hiÈ*I(+hH(i¨,n,hi¨,I(+hH(iØ,n,hiØ,I(+hH(iè,o,hH,i-’H(’i0c)(H(i*’I(4)33iè1i1H,i-’iÈ*8)Bi(I(+hH(ido,hH,i-’H(’i-c)(H(i*’I(4)33iÈ6iè6H,i-’iF8)BiØ1i)b((41-H,i-’H(’i/c)(H(i*’I(4)3(3(-H,i-’H(’i1c)(H(i*’I(4)3(3(-H,i-’H(’i0c)(H(i*’I(4)3(3(3H,H/^*0H,H(^*<3i(I*4*3H,H,i¸)’^*TH,H,iø-’^*PH,H,iX’^*LH,H,i(’^*HH,i-8(I(H,i-8(I-i¥I*H,i,8(I.H(iErH-iErš5)H(i©*’I1H-i)’I0i(i;H.i,’J(i(H(i(rCJ(“J*H*i;sCI*i¨1I-H(I/+hH/,hH,i-’H-V)(i)œ’H,i+8(c)(H/i)“I/H-i*’I-H*i)’I*4)-H(i)œi¨1’I/+hH(H*o,hH,i-’H/V)(i)œ’i(c)(H/i*’I/H(i)’I(4)33i¤I*H,iø-’H,i¸)’H,i-’i;8)5+H0H1’I2i(I-+hH-H2p,hH,H,iP’8*J*i(p5-H*i7u,hH,i-’H-i)œ’H*c)(H-i)’I-4*3i(I/i+I.i+I(*h*h*hH*i8“6*(*)3H-m,hi£I*403H-i)œH,’W)-I/i*I(4)3i3I.i/I(3H2H,H(8(H.’J(H-’J.p,hi¢I*4.3H,i-’H-i)œ’I*+hH(,hH*H/c)(H*i*’I*H(i)“I(4)-H.I-4+3(3(33H,W)1m,hiŸI*4,3H,iø-’H,i¸)’H,i-’H18)J(,hi¡I*H(i(p5,H1H,V)ú-H,V)ø-’o5,3H,i(’H,iX’H,i-’H1i)œ’H08)J(,hi I*H(i(p5,H0H,V)šH,V)˜’o5,3H,H,iP’H,iH’8+I*4+3(3(3H,i$6i¬78+I*3H*H3šm5(3i)I-H*i(r5)3H)H,P*0^*(H+H,P*<^*(H*I-3H,i2’L(H-33Á)+(i¨03b+(,(-(.(/(0(1(2(3(5(7(9(;(?(C(G(K(S([(c(k({(‹(›(«(Ë(ë( (*)(iø03O)()()()(*(*(*(*(+(+(+(+(,(,(,(,(-(-(-(-(i¨13M8(9(:(((0(/(1(.(2(-(3(,(4(+(5(*(6()(7(T7œ‰šœ‡Ž‰œš›*S7•œ‰Š”U”—Љ”›S0›‘–U œ`;_e.getModule(_e,i).then(a=>WebAssembly.instantiate(a,{})).then(({exports:a})=>{let o=new Map(Object.entries(a)),s=o.get("puff"),c=o.get("memory").buffer,l=new t(c),u=new DataView(c),d=o.get("__heap_base"),f=r.length,h=d;d+=4,u.setInt32(h,f,!0);let m=d;d+=f,l.set(r,m);let g=d;d+=4,u.setInt32(g,l.byteLength-d,!0),s(d,g,m,h),n(l.slice(d,d+u.getInt32(g,!0)))})})}}}),Object.defineProperty(this,"wasm",{enumerable:!0,get:()=>this._wasm}),this.getOutputChannels=(r,n,i)=>{let a=[],o=0;for(;o<n;)a.push(r.slice(o*i,o++*i+i));return a},this.allocateTypedArray=(r,n,i=!0)=>{let a=this._wasm.malloc(n.BYTES_PER_ELEMENT*r);return i&&this._pointers.add(a),{ptr:a,len:r,buf:new n(this._wasm.HEAP,a,r)}},this.free=()=>{this._pointers.forEach(r=>{this._wasm.free(r)}),this._pointers.clear()},this.codeToString=r=>{let n=[],i=new Uint8Array(this._wasm.HEAP);for(let a=i[r];a!==0;a=i[++r])n.push(a);return String.fromCharCode.apply(null,n)},this.addError=(r,n,i,a,o,s)=>{r.push({message:n,frameLength:i,frameNumber:a,inputBytes:o,outputSamples:s})},this.instantiate=(r,n)=>(n&&_e.setModule(r,n),this._wasm=new r(_e).instantiate(),this._pointers=new Set,this._wasm.ready.then(()=>this))}var Ih=pg(Fh(),1);var Zy=()=>globalThis.Worker||Ih.default,Ji=class extends Zy(){constructor(e,r,n,i){_e.modules||new _e;let a=_e.modules.get(n);if(!a){let o="text/javascript",s,c=`'use strict';(${((l,u,d)=>{let f,h,m=new Promise(g=>{h=g});self.onmessage=({data:{id:g,command:p,data:y}})=>{let v=m,b={id:g},x;p==="init"?(Object.defineProperties(l,{WASMAudioDecoderCommon:{value:u},EmscriptenWASM:{value:d},module:{value:y.module},isWebWorker:{value:!0}}),f=new l(y.options),h()):p==="free"?f.free():p==="ready"?v=v.then(()=>f.ready):p==="reset"?v=v.then(()=>f.reset()):(Object.assign(b,f[p](Array.isArray(y)?y.map(_=>new Uint8Array(_)):new Uint8Array(y))),x=b.channelData?b.channelData.map(_=>_.buffer):[]),v.then(()=>self.postMessage(b,x))}}).toString()})(${n}, ${_e}, ${i})`;try{s=typeof process.versions.node<"u"}catch{}a=s?`data:${o};base64,${Buffer.from(c).toString("base64")}`:URL.createObjectURL(new Blob([c],{type:o})),_e.modules.set(n,a)}super(a,{name:r}),this._id=Number.MIN_SAFE_INTEGER,this._enqueuedOperations=new Map,this.onmessage=({data:o})=>{let{id:s,...c}=o;this._enqueuedOperations.get(s)(c),this._enqueuedOperations.delete(s)},new i(_e).getModule().then(o=>{this.postToDecoder("init",{module:o,options:e})})}async postToDecoder(e,r){return new Promise(n=>{this.postMessage({command:e,id:this._id,data:r}),this._enqueuedOperations.set(this._id++,n)})}get ready(){return this.postToDecoder("ready")}async free(){await this.postToDecoder("free").finally(()=>{this.terminate()})}async reset(){await this.postToDecoder("reset")}};var yl=(t,e)=>{Object.defineProperty(t,"name",{value:e})};var Se=Symbol,Dh=", ",W=(()=>{let t="front",e="side",r="rear",n="left",i="center",a="right";return["",t+" ",e+" ",r+" "].map(o=>[[n,a],[n,a,i],[n,i,a],[i,n,a],[i]].flatMap(s=>s.map(c=>o+c).join(Dh)))})(),Br="LFE",Ln="monophonic (mono)",Pn="stereo",mo="surround",Le=(t,...e)=>`${[Ln,Pn,`linear ${mo}`,"quadraphonic",`5.0 ${mo}`,`5.1 ${mo}`,`6.1 ${mo}`,`7.1 ${mo}`][t-1]} (${e.join(Dh)})`,po=[Ln,Le(2,W[0][0]),Le(3,W[0][2]),Le(4,W[1][0],W[3][0]),Le(5,W[1][2],W[3][0]),Le(6,W[1][2],W[3][0],Br),Le(7,W[1][2],W[2][0],W[3][4],Br),Le(8,W[1][2],W[2][0],W[3][0],Br)],kh=192e3,Uh=176400,bl=96e3,xl=88200,zh=64e3,Rn=48e3,ea=44100,ta=32e3,ra=24e3,na=22050,ia=16e3,vl=12e3,_l=11025,aa=8e3,Oh=7350,gr="absoluteGranulePosition",Y="bandwidth",dt="bitDepth",ft="bitrate",go=ft+"Maximum",yo=ft+"Minimum",bo=ft+"Nominal",Fr="buffer",xo=Fr+"Fullness",be="codec",ht=be+"Frames",vo="coupledStreamCount",oa="crc",_o=oa+"16",So=oa+"32",pe="data",H="description",Ir="duration",sa="emphasis",wo="hasOpusPadding",Vt="header",Cn="isContinuedPacket",Mo="isCopyrighted",Bn="isFirstPage",Ao="isHome",Ht="isLastPage",Zr="isOriginal",jr="isPrivate",Eo="isVbr",Ut="layer",C="length",K="mode",Qr=K+"Extension",Sl="mpeg",Jr=Sl+"Version",To="numberAACFrames",Lo="outputGain",di="preSkip",Po="profile",wl=Se(),en="protection",Hu="rawData",tr="segments",Z="subarray",Fn="version",fi="vorbis",Ro=fi+"Comments",la=fi+"Setup",Ml="block",Co=Ml+"ingStrategy",Al=Se(),tn=Ml+"Size",In=Ml+"size0",Dn=Ml+"size1",Bo=Se(),El="channel",rn=El+"MappingFamily",Fo=El+"MappingTable",mt=El+"Mode",Io=Se(),V=El+"s",Nh="copyright",Do=Nh+"Id",ko=Nh+"IdStart",nn="frame",an=nn+"Count",zt=nn+"Length",Tl="Number",on=nn+Tl,Dr=nn+"Padding",X=nn+"Size",Gh="Rate",Uo="inputSample"+Gh,Wu="page",hi=Wu+"Checksum",ca=Se(),kn=Wu+"SegmentTable",Ie=Wu+"Sequence"+Tl,Xu="sample",zo=Xu+Tl,te=Xu+Gh,kr=Se(),re=Xu+"s",Ll="stream",Oo=Ll+"Count",No=Ll+"Info",Ur=Ll+"Serial"+Tl,$u=Ll+"StructureVersion",Ku="total",mi=Ku+"BytesOut",pi=Ku+"Duration",gi=Ku+"Samples",oe=Se(),rr=Se(),Go=Se(),Un=Se(),yr=Se(),Pl=Se(),Yu=Se(),zn=Se(),fe=Se(),nr=Se(),ir=Se(),zr=Se(),On=Se(),Rl=Se(),br=Se(),xr=Se(),ar=Se(),Cl=Se(),pt=Uint8Array,Nn=DataView,he="reserved",gt="bad",ua="free",Vo="none",Bl="16bit CRC";var qu=(t,e,r)=>{for(let n=0;n<t[C];n++){let i=e(n);for(let a=8;a>0;a--)i=r(i);t[n]=i}return t},Qy=qu(new pt(256),t=>t,t=>t&128?7^t<<1:t<<1),Pe=[qu(new Uint16Array(256),t=>t<<8,t=>t<<1^(t&32768?32773:0))],Re=[qu(new Uint32Array(256),t=>t,t=>t>>>1^(t&1)*3988292384)];for(let t=0;t<15;t++){Pe.push(new Uint16Array(256)),Re.push(new Uint32Array(256));for(let e=0;e<=255;e++)Pe[t+1][e]=Pe[0][Pe[t][e]>>>8]^Pe[t][e]<<8,Re[t+1][e]=Re[t][e]>>>8^Re[0][Re[t][e]&255]}var Hh=t=>{let e=0,r=t[C];for(let n=0;n!==r;n++)e=Qy[e^t[n]];return e},Wh=t=>{let e=t[C],r=e-16,n=0,i=0;for(;i<=r;)n^=t[i++]<<8|t[i++],n=Pe[15][n>>8]^Pe[14][n&255]^Pe[13][t[i++]]^Pe[12][t[i++]]^Pe[11][t[i++]]^Pe[10][t[i++]]^Pe[9][t[i++]]^Pe[8][t[i++]]^Pe[7][t[i++]]^Pe[6][t[i++]]^Pe[5][t[i++]]^Pe[4][t[i++]]^Pe[3][t[i++]]^Pe[2][t[i++]]^Pe[1][t[i++]]^Pe[0][t[i++]];for(;i!==e;)n=(n&255)<<8^Pe[0][n>>8^t[i++]];return n},Xh=t=>{let e=t[C],r=e-16,n=0,i=0;for(;i<=r;)n=Re[15][(t[i++]^n)&255]^Re[14][(t[i++]^n>>>8)&255]^Re[13][(t[i++]^n>>>16)&255]^Re[12][t[i++]^n>>>24]^Re[11][t[i++]]^Re[10][t[i++]]^Re[9][t[i++]]^Re[8][t[i++]]^Re[7][t[i++]]^Re[6][t[i++]]^Re[5][t[i++]]^Re[4][t[i++]]^Re[3][t[i++]]^Re[2][t[i++]]^Re[1][t[i++]]^Re[0][t[i++]];for(;i!==e;)n=Re[0][(n^t[i++])&255]^n>>>8;return n^-1},Wo=(...t)=>{let e=new pt(t.reduce((r,n)=>r+n[C],0));return t.reduce((r,n)=>(e.set(n,r),r+n[C]),0),e},Wt=t=>String.fromCharCode(...t),Vh=[0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15],Ho=t=>Vh[t&15]<<4|Vh[t>>4],Fl=class{constructor(e){this._data=e,this._pos=e[C]*8}set position(e){this._pos=e}get position(){return this._pos}read(e){let r=Math.floor(this._pos/8),n=this._pos%8;return this._pos-=e,(Ho(this._data[r-1])<<8)+Ho(this._data[r])>>7-n&255}},$h=(t,e)=>{try{return t.getBigInt64(e,!0)}catch{let r=t.getUint8(e+7)&128?-1:1,n=t.getUint32(e,!0),i=t.getUint32(e+4,!0);return r===-1&&(n=~n+1,i=~i+1),i>1048575&&console.warn("This platform does not support BigInt"),r*(n+i*2**32)}};var Xo=class{constructor(e,r){this._onCodecHeader=e,this._onCodecUpdate=r,this[br]()}[xr](){this._isEnabled=!0}[br](){this._headerCache=new Map,this._codecUpdateData=new WeakMap,this._codecHeaderSent=!1,this._codecShouldUpdate=!1,this._bitrate=null,this._isEnabled=!1}[Rl](e,r){if(this._onCodecUpdate){this._bitrate!==e&&(this._bitrate=e,this._codecShouldUpdate=!0);let n=this._codecUpdateData.get(this._headerCache.get(this._currentHeader));this._codecShouldUpdate&&n&&this._onCodecUpdate({bitrate:e,...n},r),this._codecShouldUpdate=!1}}[fe](e){let r=this._headerCache.get(e);return r&&this._updateCurrentHeader(e),r}[nr](e,r,n){this._isEnabled&&(this._codecHeaderSent||(this._onCodecHeader({...r}),this._codecHeaderSent=!0),this._updateCurrentHeader(e),this._headerCache.set(e,r),this._codecUpdateData.set(r,n))}_updateCurrentHeader(e){this._onCodecUpdate&&e!==this._currentHeader&&(this._codecShouldUpdate=!0,this._currentHeader=e)}};var Oe=new WeakMap,at=new WeakMap;var yt=class{constructor(e,r){this._codecParser=e,this._headerCache=r}*[Yu](){let e;do{if(e=yield*this.Frame[ir](this._codecParser,this._headerCache,0),e)return e;this._codecParser[rr](1)}while(!0)}*[zn](e){let r=yield*this[Yu](),n=at.get(r)[C];if(e||this._codecParser._flushing||(yield*this.Header[fe](this._codecParser,this._headerCache,n)))return this._headerCache[xr](),this._codecParser[rr](n),this._codecParser[Un](r),r;this._codecParser[yr](`Missing ${nn} at ${n} bytes from current position.`,`Dropping current ${nn} and trying again.`),this._headerCache[br](),this._codecParser[rr](1)}};var yi=class{constructor(e,r){at.set(this,{[Vt]:e}),this[pe]=r}};var Xt=class extends yi{static*[ir](e,r,n,i,a){let o=yield*e[fe](n,i,a);if(o){let s=Oe.get(o)[zt],c=Oe.get(o)[re],l=(yield*n[oe](s,a))[Z](0,s);return new r(o,l,c)}else return null}constructor(e,r,n){super(e,r),this[Vt]=e,this[re]=n,this[Ir]=n/e[te]*1e3,this[on]=null,this[mi]=null,this[gi]=null,this[pi]=null,at.get(this)[C]=r[C]}};var Zu="unsynchronizationFlag",ju="extendedHeaderFlag",Qu="experimentalFlag",Ju="footerPresent",$o=class t{static*getID3v2Header(e,r,n){let a={},o=yield*e[oe](3,n);if(o[0]!==73||o[1]!==68||o[2]!==51||(o=yield*e[oe](10,n),a[Fn]=`id3v2.${o[3]}.${o[4]}`,o[5]&15)||(a[Zu]=!!(o[5]&128),a[ju]=!!(o[5]&64),a[Qu]=!!(o[5]&32),a[Ju]=!!(o[5]&16),o[6]&128||o[7]&128||o[8]&128||o[9]&128))return null;let s=o[6]<<21|o[7]<<14|o[8]<<7|o[9];return a[C]=10+s,new t(a)}constructor(e){this[Fn]=e[Fn],this[Zu]=e[Zu],this[ju]=e[ju],this[Qu]=e[Qu],this[Ju]=e[Ju],this[C]=e[C]}};var $t=class{constructor(e){Oe.set(this,e),this[dt]=e[dt],this[ft]=null,this[V]=e[V],this[mt]=e[mt],this[te]=e[te]}};var jh={0:[ua,ua,ua,ua,ua],16:[32,32,32,32,8],240:[gt,gt,gt,gt,gt]},Il=(t,e,r)=>8*((t+r)%e+e)*(1<<(t+r)/e)-8*e*(e/8|0);for(let t=2;t<15;t++)jh[t<<4]=[t*32,Il(t,4,0),Il(t,4,-1),Il(t,8,4),Il(t,8,0)];var Jy=0,e1=1,t1=2,r1=3,Kh=4,Dl="bands ",kl=" to 31",Yh={0:Dl+4+kl,16:Dl+8+kl,32:Dl+12+kl,48:Dl+16+kl},bi="bitrateIndex",Ko="v2",Gl="v1",Ul="Intensity stereo ",zl=", MS stereo ",Ol="on",Nl="off",n1={0:Ul+Nl+zl+Nl,16:Ul+Ol+zl+Nl,32:Ul+Nl+zl+Ol,48:Ul+Ol+zl+Ol},ed={0:{[H]:he},2:{[H]:"Layer III",[Dr]:1,[Qr]:n1,[Gl]:{[bi]:t1,[re]:1152},[Ko]:{[bi]:Kh,[re]:576}},4:{[H]:"Layer II",[Dr]:1,[Qr]:Yh,[re]:1152,[Gl]:{[bi]:e1},[Ko]:{[bi]:Kh}},6:{[H]:"Layer I",[Dr]:4,[Qr]:Yh,[re]:384,[Gl]:{[bi]:Jy},[Ko]:{[bi]:r1}}},td="MPEG Version ",qh="ISO/IEC ",i1={0:{[H]:`${td}2.5 (later extension of MPEG 2)`,[Ut]:Ko,[te]:{0:_l,4:vl,8:aa,12:he}},8:{[H]:he},16:{[H]:`${td}2 (${qh}13818-3)`,[Ut]:Ko,[te]:{0:na,4:ra,8:ia,12:he}},24:{[H]:`${td}1 (${qh}11172-3)`,[Ut]:Gl,[te]:{0:ea,4:Rn,8:ta,12:he}},length:C},a1={0:Bl,1:Vo},o1={0:Vo,1:"50/15 ms",2:he,3:"CCIT J.17"},Zh={0:{[V]:2,[H]:Pn},64:{[V]:2,[H]:"joint "+Pn},128:{[V]:2,[H]:"dual channel"},192:{[V]:1,[H]:Ln}},xi=class t extends $t{static*[fe](e,r,n){let i={},a=yield*$o.getID3v2Header(e,r,n);a&&(yield*e[oe](a[C],n),e[rr](a[C]));let o=yield*e[oe](4,n),s=Wt(o[Z](0,4)),c=r[fe](s);if(c)return new t(c);if(o[0]!==255||o[1]<224)return null;let l=i1[o[1]&24];if(l[H]===he)return null;let u=o[1]&6;if(ed[u][H]===he)return null;let d={...ed[u],...ed[u][l[Ut]]};if(i[Jr]=l[H],i[Ut]=d[H],i[re]=d[re],i[en]=a1[o[1]&1],i[C]=4,i[ft]=jh[o[2]&240][d[bi]],i[ft]===gt||(i[te]=l[te][o[2]&12],i[te]===he)||(i[Dr]=o[2]&2&&d[Dr],i[jr]=!!(o[2]&1),i[zt]=Math.floor(125*i[ft]*i[re]/i[te]+i[Dr]),!i[zt]))return null;let f=o[3]&192;if(i[mt]=Zh[f][H],i[V]=Zh[f][V],i[Qr]=d[Qr][o[3]&48],i[Mo]=!!(o[3]&8),i[Zr]=!!(o[3]&4),i[sa]=o1[o[3]&3],i[sa]===he)return null;i[dt]=16;{let{length:h,frameLength:m,samples:g,...p}=i;r[nr](s,i,p)}return new t(i)}constructor(e){super(e),this[ft]=e[ft],this[sa]=e[sa],this[Dr]=e[Dr],this[Mo]=e[Mo],this[Zr]=e[Zr],this[jr]=e[jr],this[Ut]=e[Ut],this[Qr]=e[Qr],this[Jr]=e[Jr],this[en]=e[en]}};var Yo=class t extends Xt{static*[ir](e,r,n){return yield*super[ir](xi,t,e,r,n)}constructor(e,r,n){super(e,r,n)}};var qo=class extends yt{constructor(e,r,n){super(e,r),this.Frame=Yo,this.Header=xi,n(this[be])}get[be](){return Sl}*[zr](){return yield*this[zn]()}};var s1={0:"MPEG-4",8:"MPEG-2"},l1={0:"valid",2:gt,4:gt,6:gt},c1={0:Bl,1:Vo},u1={0:"AAC Main",64:"AAC LC (Low Complexity)",128:"AAC SSR (Scalable Sample Rate)",192:"AAC LTP (Long Term Prediction)"},d1={0:bl,4:xl,8:zh,12:Rn,16:ea,20:ta,24:ra,28:na,32:ia,36:vl,40:_l,44:aa,48:Oh,52:he,56:he,60:"frequency is written explicitly"},Qh={0:{[V]:0,[H]:"Defined in AOT Specific Config"},64:{[V]:1,[H]:Ln},128:{[V]:2,[H]:Le(2,W[0][0])},192:{[V]:3,[H]:Le(3,W[1][3])},256:{[V]:4,[H]:Le(4,W[1][3],W[3][4])},320:{[V]:5,[H]:Le(5,W[1][3],W[3][0])},384:{[V]:6,[H]:Le(6,W[1][3],W[3][0],Br)},448:{[V]:8,[H]:Le(8,W[1][3],W[2][0],W[3][0],Br)}},vi=class t extends $t{static*[fe](e,r,n){let i={},a=yield*e[oe](7,n),o=Wt([a[0],a[1],a[2],a[3]&252|a[6]&3]),s=r[fe](o);if(s)Object.assign(i,s);else{if(a[0]!==255||a[1]<240||(i[Jr]=s1[a[1]&8],i[Ut]=l1[a[1]&6],i[Ut]===gt))return null;let l=a[1]&1;i[en]=c1[l],i[C]=l?7:9,i[wl]=a[2]&192,i[kr]=a[2]&60;let u=a[2]&2;if(i[Po]=u1[i[wl]],i[te]=d1[i[kr]],i[te]===he)return null;i[jr]=!!u,i[Io]=(a[2]<<8|a[3])&448,i[mt]=Qh[i[Io]][H],i[V]=Qh[i[Io]][V],i[Zr]=!!(a[3]&32),i[Ao]=!!(a[3]&8),i[Do]=!!(a[3]&8),i[ko]=!!(a[3]&4),i[dt]=16,i[re]=1024,i[To]=a[6]&3;{let{length:d,channelModeBits:f,profileBits:h,sampleRateBits:m,frameLength:g,samples:p,numberAACFrames:y,...v}=i;r[nr](o,i,v)}}if(i[zt]=(a[3]<<11|a[4]<<3|a[5]>>5)&8191,!i[zt])return null;let c=(a[5]<<6|a[6]>>2)&2047;return i[xo]=c===2047?"VBR":c,new t(i)}constructor(e){super(e),this[Do]=e[Do],this[ko]=e[ko],this[xo]=e[xo],this[Ao]=e[Ao],this[Zr]=e[Zr],this[jr]=e[jr],this[Ut]=e[Ut],this[C]=e[C],this[Jr]=e[Jr],this[To]=e[To],this[Po]=e[Po],this[en]=e[en]}get audioSpecificConfig(){let e=Oe.get(this),r=e[wl]+64<<5|e[kr]<<5|e[Io]>>3,n=new pt(2);return new Nn(n[Fr]).setUint16(0,r,!1),n}};var Zo=class t extends Xt{static*[ir](e,r,n){return yield*super[ir](vi,t,e,r,n)}constructor(e,r,n){super(e,r,n)}};var jo=class extends yt{constructor(e,r,n){super(e,r),this.Frame=Zo,this.Header=vi,n(this[be])}get[be](){return"aac"}*[zr](){return yield*this[zn]()}};var Gn=class t extends Xt{static _getFrameFooterCrc16(e){return(e[e[C]-2]<<8)+e[e[C]-1]}static[Cl](e){let r=t._getFrameFooterCrc16(e),n=Wh(e[Z](0,-2));return r===n}constructor(e,r,n){r[No]=n,r[_o]=t._getFrameFooterCrc16(e),super(r,e,Oe.get(r)[re])}};var Jh="get from STREAMINFO metadata block",f1={0:"Fixed",1:"Variable"},em={0:he,16:192};for(let t=2;t<16;t++)em[t<<4]=t<6?576*2**(t-2):2**t;var h1={0:Jh,1:xl,2:Uh,3:kh,4:aa,5:ia,6:na,7:ra,8:ta,9:ea,10:Rn,11:bl,15:gt},m1={0:{[V]:1,[H]:Ln},16:{[V]:2,[H]:Le(2,W[0][0])},32:{[V]:3,[H]:Le(3,W[0][1])},48:{[V]:4,[H]:Le(4,W[1][0],W[3][0])},64:{[V]:5,[H]:Le(5,W[1][1],W[3][0])},80:{[V]:6,[H]:Le(6,W[1][1],Br,W[3][0])},96:{[V]:7,[H]:Le(7,W[1][1],Br,W[3][4],W[2][0])},112:{[V]:8,[H]:Le(8,W[1][1],Br,W[3][0],W[2][0])},128:{[V]:2,[H]:`${Pn} (left, diff)`},144:{[V]:2,[H]:`${Pn} (diff, right)`},160:{[V]:2,[H]:`${Pn} (avg, diff)`},176:he,192:he,208:he,224:he,240:he},p1={0:Jh,2:8,4:12,6:he,8:16,10:20,12:24,14:he},Vn=class t extends $t{static _decodeUTF8Int(e){if(e[0]>254)return null;if(e[0]<128)return{value:e[0],length:1};let r=1;for(let o=64;o&e[0];o>>=1)r++;let n=r-1,i=0,a=0;for(;n>0;a+=6,n--){if((e[n]&192)!==128)return null;i|=(e[n]&63)<<a}return i|=(e[n]&127>>r)<<a,{value:i,length:r}}static[ar](e,r){let n={[oe]:function*(){return e}};return t[fe](n,r,0).next().value}static*[fe](e,r,n){let i=yield*e[oe](6,n);if(i[0]!==255||!(i[1]===248||i[1]===249))return null;let a={},o=Wt(i[Z](0,4)),s=r[fe](o);if(s)Object.assign(a,s);else{if(a[Al]=i[1]&1,a[Co]=f1[a[Al]],a[Bo]=i[2]&240,a[kr]=i[2]&15,a[tn]=em[a[Bo]],a[tn]===he||(a[te]=h1[a[kr]],a[te]===gt)||i[3]&1)return null;let l=m1[i[3]&240];if(l===he||(a[V]=l[V],a[mt]=l[H],a[dt]=p1[i[3]&14],a[dt]===he))return null}a[C]=5,i=yield*e[oe](a[C]+8,n);let c=t._decodeUTF8Int(i[Z](4));if(!c||(a[Al]?a[zo]=c.value:a[on]=c.value,a[C]+=c[C],a[Bo]===96?(i[C]<a[C]&&(i=yield*e[oe](a[C],n)),a[tn]=i[a[C]-1]+1,a[C]+=1):a[Bo]===112&&(i[C]<a[C]&&(i=yield*e[oe](a[C],n)),a[tn]=(i[a[C]-1]<<8)+i[a[C]]+1,a[C]+=2),a[re]=a[tn],a[kr]===12?(i[C]<a[C]&&(i=yield*e[oe](a[C],n)),a[te]=i[a[C]-1]*1e3,a[C]+=1):a[kr]===13?(i[C]<a[C]&&(i=yield*e[oe](a[C],n)),a[te]=(i[a[C]-1]<<8)+i[a[C]],a[C]+=2):a[kr]===14&&(i[C]<a[C]&&(i=yield*e[oe](a[C],n)),a[te]=((i[a[C]-1]<<8)+i[a[C]])*10,a[C]+=2),i[C]<a[C]&&(i=yield*e[oe](a[C],n)),a[oa]=i[a[C]-1],a[oa]!==Hh(i[Z](0,a[C]-1))))return null;if(!s){let{blockingStrategyBits:l,frameNumber:u,sampleNumber:d,samples:f,sampleRateBits:h,blockSizeBits:m,crc:g,length:p,...y}=a;r[nr](o,a,y)}return new t(a)}constructor(e){super(e),this[_o]=null,this[Co]=e[Co],this[tn]=e[tn],this[on]=e[on],this[zo]=e[zo],this[No]=null}};var g1=2,y1=512*1024,_i=class extends yt{constructor(e,r,n){super(e,r),this.Frame=Gn,this.Header=Vn,n(this[be])}get[be](){return"flac"}*_getNextFrameSyncOffset(e){let r=yield*this._codecParser[oe](2,0),n=r[C]-2;for(;e<n;){if(r[e]===255){let a=r[e+1];if(a===248||a===249)break;a!==255&&e++}e++}return e}*[zr](){do{let e=yield*Vn[fe](this._codecParser,this._headerCache,0);if(e){let r=Oe.get(e)[C]+g1;for(;r<=y1;){if(this._codecParser._flushing||(yield*Vn[fe](this._codecParser,this._headerCache,r))){let n=yield*this._codecParser[oe](r);if(this._codecParser._flushing||(n=n[Z](0,r)),Gn[Cl](n)){let i=new Gn(n,e);return this._headerCache[xr](),this._codecParser[rr](r),this._codecParser[Un](i),i}}r=yield*this._getNextFrameSyncOffset(r+1)}this._codecParser[yr](`Unable to sync FLAC frame after searching ${r} bytes.`),this._codecParser[rr](r)}else this._codecParser[rr](yield*this._getNextFrameSyncOffset(1))}while(!0)}[On](e){return e[Ie]===0?(this._headerCache[xr](),this._streamInfo=e[pe][Z](13)):e[Ie]===1||(e[ht]=at.get(e)[tr].map(r=>{let n=Vn[ar](r,this._headerCache);if(n)return new Gn(r,n,this._streamInfo);this._codecParser[yr]("Failed to parse Ogg FLAC frame","Skipping invalid FLAC frame")}).filter(r=>!!r)),e}};var Si=class t{static*[fe](e,r,n){let i={},a=yield*e[oe](28,n);if(a[0]!==79||a[1]!==103||a[2]!==103||a[3]!==83||(i[$u]=a[4],a[5]&248))return null;i[Ht]=!!(a[5]&4),i[Bn]=!!(a[5]&2),i[Cn]=!!(a[5]&1);let s=new Nn(pt.from(a[Z](0,28))[Fr]);i[gr]=$h(s,6),i[Ur]=s.getInt32(14,!0),i[Ie]=s.getInt32(18,!0),i[hi]=s.getInt32(22,!0);let c=a[26];i[C]=c+27,a=yield*e[oe](i[C],n),i[zt]=0,i[kn]=[],i[ca]=pt.from(a[Z](27,i[C]));for(let l=0,u=0;l<c;l++){let d=i[ca][l];i[zt]+=d,u+=d,(d!==255||l===c-1)&&(i[kn].push(u),u=0)}return new t(i)}constructor(e){Oe.set(this,e),this[gr]=e[gr],this[Cn]=e[Cn],this[Bn]=e[Bn],this[Ht]=e[Ht],this[kn]=e[kn],this[Ie]=e[Ie],this[hi]=e[hi],this[Ur]=e[Ur]}};var Qo=class t extends yi{static*[ir](e,r,n){let i=yield*Si[fe](e,r,n);if(i){let a=Oe.get(i)[zt],o=Oe.get(i)[C],s=o+a,c=(yield*e[oe](s,0))[Z](0,s),l=c[Z](o,s);return new t(i,l,c)}else return null}constructor(e,r,n){super(e,r),at.get(this)[C]=n[C],this[ht]=[],this[Hu]=n,this[gr]=e[gr],this[So]=e[hi],this[Ir]=0,this[Cn]=e[Cn],this[Bn]=e[Bn],this[Ht]=e[Ht],this[Ie]=e[Ie],this[re]=0,this[Ur]=e[Ur]}};var da=class extends Xt{constructor(e,r,n){super(r,e,n)}};var tm={0:po.slice(0,2),1:po},or="SILK-only",ot="CELT-only",Vl="Hybrid",Hn="narrowband",Hl="medium-band",Wn="wideband",fa="super-wideband",ha="fullband",b1={0:{[K]:or,[Y]:Hn,[X]:10},8:{[K]:or,[Y]:Hn,[X]:20},16:{[K]:or,[Y]:Hn,[X]:40},24:{[K]:or,[Y]:Hn,[X]:60},32:{[K]:or,[Y]:Hl,[X]:10},40:{[K]:or,[Y]:Hl,[X]:20},48:{[K]:or,[Y]:Hl,[X]:40},56:{[K]:or,[Y]:Hl,[X]:60},64:{[K]:or,[Y]:Wn,[X]:10},72:{[K]:or,[Y]:Wn,[X]:20},80:{[K]:or,[Y]:Wn,[X]:40},88:{[K]:or,[Y]:Wn,[X]:60},96:{[K]:Vl,[Y]:fa,[X]:10},104:{[K]:Vl,[Y]:fa,[X]:20},112:{[K]:Vl,[Y]:ha,[X]:10},120:{[K]:Vl,[Y]:ha,[X]:20},128:{[K]:ot,[Y]:Hn,[X]:2.5},136:{[K]:ot,[Y]:Hn,[X]:5},144:{[K]:ot,[Y]:Hn,[X]:10},152:{[K]:ot,[Y]:Hn,[X]:20},160:{[K]:ot,[Y]:Wn,[X]:2.5},168:{[K]:ot,[Y]:Wn,[X]:5},176:{[K]:ot,[Y]:Wn,[X]:10},184:{[K]:ot,[Y]:Wn,[X]:20},192:{[K]:ot,[Y]:fa,[X]:2.5},200:{[K]:ot,[Y]:fa,[X]:5},208:{[K]:ot,[Y]:fa,[X]:10},216:{[K]:ot,[Y]:fa,[X]:20},224:{[K]:ot,[Y]:ha,[X]:2.5},232:{[K]:ot,[Y]:ha,[X]:5},240:{[K]:ot,[Y]:ha,[X]:10},248:{[K]:ot,[Y]:ha,[X]:20}},ma=class t extends $t{static[ar](e,r,n){let i={};if(i[V]=e[9],i[rn]=e[18],i[C]=i[rn]!==0?21+i[V]:19,e[C]<i[C])throw new Error("Out of data while inside an Ogg Page");let a=r[0]&3,o=a===3?2:1,s=Wt(e[Z](0,i[C]))+Wt(r[Z](0,o)),c=n[fe](s);if(c)return new t(c);if(s.substr(0,8)!=="OpusHead"||e[8]!==1)return null;i[pe]=pt.from(e[Z](0,i[C]));let l=new Nn(i[pe][Fr]);if(i[dt]=16,i[di]=l.getUint16(10,!0),i[Uo]=l.getUint32(12,!0),i[te]=Rn,i[Lo]=l.getInt16(16,!0),i[rn]in tm&&(i[mt]=tm[i[rn]][i[V]-1],!i[mt]))return null;i[rn]!==0&&(i[Oo]=e[19],i[vo]=e[20],i[Fo]=[...e[Z](21,i[V]+21)]);let u=b1[248&r[0]];switch(i[K]=u[K],i[Y]=u[Y],i[X]=u[X],a){case 0:i[an]=1;break;case 1:case 2:i[an]=2;break;case 3:i[Eo]=!!(128&r[1]),i[wo]=!!(64&r[1]),i[an]=63&r[1];break;default:return null}{let{length:d,data:f,channelMappingFamily:h,...m}=i;n[nr](s,i,m)}return new t(i)}constructor(e){super(e),this[pe]=e[pe],this[Y]=e[Y],this[rn]=e[rn],this[Fo]=e[Fo],this[vo]=e[vo],this[an]=e[an],this[X]=e[X],this[wo]=e[wo],this[Uo]=e[Uo],this[Eo]=e[Eo],this[K]=e[K],this[Lo]=e[Lo],this[di]=e[di],this[Oo]=e[Oo]}};var Jo=class extends yt{constructor(e,r,n){super(e,r),this.Frame=da,this.Header=ma,n(this[be]),this._identificationHeader=null,this._preSkipRemaining=null}get[be](){return"opus"}[On](e){return e[Ie]===0?(this._headerCache[xr](),this._identificationHeader=e[pe]):e[Ie]===1||(e[ht]=at.get(e)[tr].map(r=>{let n=ma[ar](this._identificationHeader,r,this._headerCache);if(n){this._preSkipRemaining===null&&(this._preSkipRemaining=n[di]);let i=n[X]*n[an]/1e3*n[te];return this._preSkipRemaining>0&&(this._preSkipRemaining-=i,i=this._preSkipRemaining<0?-this._preSkipRemaining:0),new da(r,n,i)}this._codecParser[Pl]("Failed to parse Ogg Opus Header","Not a valid Ogg Opus file")})),e}};var pa=class extends Xt{constructor(e,r,n){super(r,e,n)}};var rd={};for(let t=0;t<8;t++)rd[t+6]=2**(6+t);var es=class t extends $t{static[ar](e,r,n,i){if(e[C]<30)throw new Error("Out of data while inside an Ogg Page");let a=Wt(e[Z](0,30)),o=r[fe](a);if(o)return new t(o);let s={[C]:30};if(a.substr(0,7)!=="vorbis")return null;s[pe]=pt.from(e[Z](0,30));let c=new Nn(s[pe][Fr]);if(s[Fn]=c.getUint32(7,!0),s[Fn]!==0||(s[V]=e[11],s[mt]=po[s[V]-1]||"application defined",s[te]=c.getUint32(12,!0),s[go]=c.getInt32(16,!0),s[bo]=c.getInt32(20,!0),s[yo]=c.getInt32(24,!0),s[Dn]=rd[(e[28]&240)>>4],s[In]=rd[e[28]&15],s[In]>s[Dn])||e[29]!==1)return null;s[dt]=32,s[la]=i,s[Ro]=n;{let{length:l,data:u,version:d,vorbisSetup:f,vorbisComments:h,...m}=s;r[nr](a,s,m)}return new t(s)}constructor(e){super(e),this[go]=e[go],this[yo]=e[yo],this[bo]=e[bo],this[In]=e[In],this[Dn]=e[Dn],this[pe]=e[pe],this[Ro]=e[Ro],this[la]=e[la]}};var ts=class extends yt{constructor(e,r,n){super(e,r),this.Frame=pa,n(this[be]),this._identificationHeader=null,this._setupComplete=!1,this._prevBlockSize=null}get[be](){return fi}[On](e){e[ht]=[];for(let r of at.get(e)[tr])if(r[0]===1)this._headerCache[xr](),this._identificationHeader=e[pe],this._setupComplete=!1;else if(r[0]===3)this._vorbisComments=r;else if(r[0]===5)this._vorbisSetup=r,this._mode=this._parseSetupHeader(r),this._setupComplete=!0;else if(this._setupComplete){let n=es[ar](this._identificationHeader,this._headerCache,this._vorbisComments,this._vorbisSetup);n?e[ht].push(new pa(r,n,this._getSamples(r,n))):this._codecParser[logError]("Failed to parse Ogg Vorbis Header","Not a valid Ogg Vorbis file")}return e}_getSamples(e,r){let i=this._mode.blockFlags[e[0]>>1&this._mode.mask]?r[Dn]:r[In],a=this._prevBlockSize===null?0:(this._prevBlockSize+i)/4;return this._prevBlockSize=i,a}_parseSetupHeader(e){let r=new Fl(e),n={count:0,blockFlags:[]};for(;(r.read(1)&1)!==1;);let i;for(;n.count<64&&r.position>0;){Ho(r.read(8));let a=0;for(;r.read(8)===0&&a++<3;);if(a===4)i=r.read(7),n.blockFlags.unshift(i&1),r.position+=6,n.count++;else{((Ho(i)&126)>>1)+1!==n.count&&this._codecParser[yr]("vorbis derived mode count did not match actual mode count");break}}return n.mask=(1<<Math.log2(n.count))-1,n}};var nd=class{constructor(e,r,n){this._codecParser=e,this._headerCache=r,this._onCodec=n,this._continuedPacket=new pt,this._codec=null,this._isSupported=null,this._previousAbsoluteGranulePosition=null}get[be](){return this._codec||""}_updateCodec(e,r){this._codec!==e&&(this._headerCache[br](),this._parser=new r(this._codecParser,this._headerCache,this._onCodec),this._codec=e)}_checkCodecSupport({data:e}){let r=Wt(e[Z](0,8));switch(r){case"fishead\0":return!1;case"OpusHead":return this._updateCodec("opus",Jo),!0;case(/^\x7fFLAC/.test(r)&&r):return this._updateCodec("flac",_i),!0;case(/^\x01vorbis/.test(r)&&r):return this._updateCodec(fi,ts),!0;default:return!1}}_checkPageSequenceNumber(e){e[Ie]!==this._pageSequenceNumber+1&&this._pageSequenceNumber>1&&e[Ie]>1&&this._codecParser[yr]("Unexpected gap in Ogg Page Sequence Number.",`Expected: ${this._pageSequenceNumber+1}, Got: ${e[Ie]}`),this._pageSequenceNumber=e[Ie]}_parsePage(e){this._isSupported===null&&(this._pageSequenceNumber=e[Ie],this._isSupported=this._checkCodecSupport(e)),this._checkPageSequenceNumber(e);let r=at.get(e),n=Oe.get(r[Vt]),i=0;if(r[tr]=n[kn].map(a=>e[pe][Z](i,i+=a)),this._continuedPacket[C]&&(r[tr][0]=Wo(this._continuedPacket,r[tr][0]),this._continuedPacket=new pt),n[ca][n[ca][C]-1]===255&&(this._continuedPacket=Wo(this._continuedPacket,r[tr].pop())),this._previousAbsoluteGranulePosition!==null&&(e[re]=Number(e[gr]-this._previousAbsoluteGranulePosition)),this._previousAbsoluteGranulePosition=e[gr],this._isSupported){let a=this._parser[On](e);return this._codecParser[Un](a),a}else return e}},rs=class extends yt{constructor(e,r,n){super(e,r),this._onCodec=n,this.Frame=Qo,this.Header=Si,this._streams=new Map,this._currentSerialNumber=null}get[be](){let e=this._streams.get(this._currentSerialNumber);return e?e.codec:""}*[zr](){let e=yield*this[zn](!0);this._currentSerialNumber=e[Ur];let r=this._streams.get(this._currentSerialNumber);return r||(r=new nd(this._codecParser,this._headerCache,this._onCodec),this._streams.set(this._currentSerialNumber,r)),e[Ht]&&this._streams.delete(this._currentSerialNumber),r._parsePage(e)}};var id=()=>{},ns=class{constructor(e,{onCodec:r,onCodecHeader:n,onCodecUpdate:i,enableLogging:a=!1,enableFrameCRC32:o=!0}={}){this._inputMimeType=e,this._onCodec=r||id,this._onCodecHeader=n||id,this._onCodecUpdate=i,this._enableLogging=a,this._crc32=o?Xh:id,this[br]()}get[be](){return this._parser?this._parser[be]:""}[br](){this._headerCache=new Xo(this._onCodecHeader,this._onCodecUpdate),this._generator=this._getGenerator(),this._generator.next()}*flush(){this._flushing=!0;for(let e=this._generator.next();e.value;e=this._generator.next())yield e.value;this._flushing=!1,this[br]()}*parseChunk(e){for(let r=this._generator.next(e);r.value;r=this._generator.next())yield r.value}parseAll(e){return[...this.parseChunk(e),...this.flush()]}*_getGenerator(){if(this._inputMimeType.match(/aac/))this._parser=new jo(this,this._headerCache,this._onCodec);else if(this._inputMimeType.match(/mpeg/))this._parser=new qo(this,this._headerCache,this._onCodec);else if(this._inputMimeType.match(/flac/))this._parser=new _i(this,this._headerCache,this._onCodec);else if(this._inputMimeType.match(/ogg/))this._parser=new rs(this,this._headerCache,this._onCodec);else throw new Error(`Unsupported Codec ${mimeType}`);for(this._frameNumber=0,this._currentReadPosition=0,this._totalBytesIn=0,this._totalBytesOut=0,this._totalSamples=0,this._sampleRate=void 0,this._rawData=new Uint8Array(0);;){let e=yield*this._parser[zr]();e&&(yield e)}}*[oe](e=0,r=0){let n;for(;this._rawData[C]<=e+r;){if(n=yield,this._flushing)return this._rawData[Z](r);n&&(this._totalBytesIn+=n[C],this._rawData=Wo(this._rawData,n))}return this._rawData[Z](r)}[rr](e){this._currentReadPosition+=e,this._rawData=this._rawData[Z](e)}[Go](e){this._sampleRate=e[Vt][te],e[Vt][ft]=e[Ir]>0?Math.round(e[pe][C]/e[Ir])*8:0,e[on]=this._frameNumber++,e[mi]=this._totalBytesOut,e[gi]=this._totalSamples,e[pi]=this._totalSamples/this._sampleRate*1e3,e[So]=this._crc32(e[pe]),this._headerCache[Rl](e[Vt][ft],e[pi]),this._totalBytesOut+=e[pe][C],this._totalSamples+=e[re]}[Un](e){if(e[ht]){if(e[Ht]){let r=e[re];e[ht].forEach(n=>{let i=n[re];r<i&&(n[re]=r>0?r:0,n[Ir]=n[re]/n[Vt][te]*1e3),r-=i,this[Go](n)})}else e[re]=0,e[ht].forEach(r=>{e[re]+=r[re],this[Go](r)});e[Ir]=e[re]/this._sampleRate*1e3||0,e[gi]=this._totalSamples,e[pi]=this._totalSamples/this._sampleRate*1e3||0,e[mi]=this._totalBytesOut}else this[Go](e)}_log(e,r){if(this._enableLogging){let n=[`${be}: ${this[be]}`,`inputMimeType: ${this._inputMimeType}`,`readPosition: ${this._currentReadPosition}`,`totalBytesIn: ${this._totalBytesIn}`,`${mi}: ${this._totalBytesOut}`],i=Math.max(...n.map(a=>a[C]));r.push(`--stats--${"-".repeat(i-9)}`,...n,"-".repeat(i)),e("codec-parser",r.reduce((a,o)=>a+`
4
- `+o,""))}}[yr](...e){this._log(console.warn,e)}[Pl](...e){this._log(console.error,e)}};var rm=ns;var Wl=ht;var Xl=pe;var nm=Vt;var im=Ht;var am=la;var om=gi;function sn(t){var e=e;function r(){}e={};function n(k){throw k}var i,a,o,s,c,l,u,d,f,h,m;function g(){var k=m.buffer;i=new Int8Array(k),a=new Int16Array(k),s=new Uint8Array(k),c=new Uint16Array(k),o=new Int32Array(k),l=new Uint32Array(k),u=new Float32Array(k),d=new Float64Array(k),f=new BigInt64Array(k),h=new BigUint64Array(k)}for(var p=k=>{for(var se,ke,De=0,fr=0,Zt=k.length,mn=new Uint8Array((Zt*3>>2)-(k[Zt-2]=="=")-(k[Zt-1]=="="));De<Zt;De+=4,fr+=3)se=O[k.charCodeAt(De+1)],ke=O[k.charCodeAt(De+2)],mn[fr]=O[k.charCodeAt(De)]<<2|se>>4,mn[fr+1]=se<<4|ke>>2,mn[fr+2]=ke<<6|O[k.charCodeAt(De+3)];return mn},y=()=>n(""),v=()=>{},b={},x=k=>k(),_=()=>performance.now(),w=(k,se)=>{if(b[k]&&(clearTimeout(b[k].id),delete b[k]),!se)return 0;var ke=setTimeout(()=>{delete b[k],x(()=>ut(k,_()))},se);return b[k]={id:ke,timeout_ms:se},0},S=Math.atan,A=Math.cos,T=Math.exp,M=Math.log,P=Math.pow,I=Math.sin,D=k=>{var se=s.length;return k>>>=0,!1},B=k=>{throw`exit(${k})`},O=new Uint8Array(123),Q=25;Q>=0;--Q)O[48+Q]=52+Q,O[65+Q]=Q,O[97+Q]=26+Q;O[43]=62,O[47]=63;var Ge={e:y,d:v,f:w,b:S,a:A,i:T,h:M,g:P,c:I,k:D,j:B};function me(k){Me=k.n,ge=k.o,ue=k.p,ye=k.q,Ve=k.r,ct=k.s,qt=k.t,ut=k.v}var Me,ge,ue,ye,Ve,ct,qt,ut;function He(k){k.m()}sn.wasm||Object.defineProperty(sn,"wasm",{get:()=>String.raw`dynEncode012091253f87dì%nä= 4&¿nÝØä‘ÂLÚªã9ÚØ[äº\ ¼¡³R=}L]ŸÈÿ2 ÿù¶J1jj¡é,zäV|i¸Qk¹‡= 
3
+ `,"Visit https://github.com/eshaz/simple-yenc for more information"),Error(y)}}return g};function _e(){let t=Uint8Array,e=Float32Array;_e.modules||Object.defineProperties(_e,{modules:{value:new WeakMap},setModule:{value(r,n){_e.modules.set(r,Promise.resolve(n))}},getModule:{value(r,n){let i=_e.modules.get(r);return i||(n?i=WebAssembly.compile(Vu(n)):(n=r.wasm,i=_e.inflateDynEncodeString(n).then(a=>WebAssembly.compile(a))),_e.modules.set(r,i)),i}},concatFloat32:{value(r,n){let i=new e(n),a=0,o=0;for(;a<r.length;)i.set(r[a],o),o+=r[a++].length;return i}},getDecodedAudio:{value:(r,n,i,a,o)=>({errors:r,channelData:n,samplesDecoded:i,sampleRate:a,bitDepth:o})},getDecodedAudioMultiChannel:{value(r,n,i,a,o,s){let c=[],l,u;for(l=0;l<i;l++){let d=[];for(u=0;u<n.length;)d.push(n[u++][l]||[]);c.push(_e.concatFloat32(d,a))}return _e.getDecodedAudio(r,c,a,o,s)}},inflateDynEncodeString:{value(r){return r=Vu(r),new Promise(n=>{let i=String.raw`dynEncode012804c7886d(‰›•)((()>+ˆ*§§)§ˆ,§§§§)§ˆ+§§§)§+.-()(*)-+)(ˆ.7*§)i¸¸,3§(i¸¸,3/G+.••—š¡*(,˜ŽŽ(,3‡‡‰˜‡Š‰›+)2å:-œ),§H(P*DI*H(P*@I++hH)H*r,hH(H(P*<J,i)’^*<H,H(P*4’U((I-H(H*i0’J,^*DH+H-H*œšI+H,I*4)33H(H*H)“^*DH(H+H)^*@H+i§H)œi§›™3æ*).§K(iH“I/+§H,iHn,§H+i(H+i(rCJ0I,H*I-+hH,,hH(H-V)(i)œ’J.H.W)(i)’c)(H,i)“I,H-i*’I-4)33i(I.*hH(V)(H+n5(H(i*’I-i(I,i)I.+hH,i*’J+iHn,hi(I-i*I,+hH,H/’H-c)(H,iFn,hi(I,+hH,H0n5-H*V)(J(,hH/H(i)œ’J(H(V)(J(i)’c)(H)H(i)œ’H,c)(3H*i*’I*H,i)’I,4(3(-H(H,’W)(H-’I-H,i*’I,4)3(3(3H,H-’I1H+I,H.i)œH1V)(“J.i(v5(33H.-H(H,’i(c)(H,i*’I,4)333–)-§i*I*+§H*iHn,hiž73H,H(i)8(H+šJ+H)P*(H*’V)(J-“r,§H)P*,H.i)œ’H+H,“i)œ’V)(-H*i*’I*H+i)œI+H-H.’I.H,H-’i)œI,4)333Ã+)-§iø7i(^*(iü7I,*h+hH+iDn,h*hilI+i)I,+hH+,hH+iô7’H,c)(i)H+i´8’W)(œH,’I,H+i*’I+4)-+hH(H)8*J-i(p5.*h*h*hH-i')u,hH(P*(J+,hH(P*0J,H(P*,n50H+H,’H-b((3H(P*0i)’I.4)3H-i¨*n5*H-iÅ*s,hiž73H-i)œJ+V)&+I,H(H+V)æ,8(I.H(H*8*J-i(p51H-i)œJ+i¸7’V)(H(H+iø7’V)(8(’J/H(P*0J+s,hi73H+H,H.’J,’I.H(P*(m5(H.H(P*,s5.+hH,m5*H(P*(J.H+’H.H+H/“’U((b((H(H(P*0i)’J+^*0H,i)“I,4(3(3H(H.^*03H-i¨*o5)33i(73(3(3-H,H+i)žc)(H,i*’I,H+i)’I+4)33i)I-3H-3!2)0§K(i2“J,L(H,H(^*(H,H*^*4H,i(^*0H,i(^*DH,j(_*<H,H)P*(^*,H,H+P*(^*8*h*h+hH,i)8(I3i§I**h*h*h*h*h*h*hH,i*8(6+(),03H,j(_*@i*I-H,P*<J.i,’J(H,P*8J/s50H,H.i+’J0^*<i¦I*H.H,P*4J1’J.U(*H.U((J2›i')o5/H.U()I.H,H(^*<H0H1’U((H.i0œJ.i§›i0ži')™o5/H/H.H2šJ*H(’J.q50H,P*0J/H*’I-H,P*(J0,hH,P*,H-q,hi)I-423+hH*m5+H/H0’H(H1’U((b((H/i)’I/H(i)’I(H*i)“I*4(3(3H,H.^*<H,H-^*04*3iØ1U((5+i(I(i¨7i1^*(i$6iè1^*(i°7iè6^*(i¬7iÈ6^*(+hH(iÈ*n,hiÈ*I(+hH(i¨,n,hi¨,I(+hH(iØ,n,hiØ,I(+hH(iè,o,hH,i-’H(’i0c)(H(i*’I(4)33iè1i1H,i-’iÈ*8)Bi(I(+hH(ido,hH,i-’H(’i-c)(H(i*’I(4)33iÈ6iè6H,i-’iF8)BiØ1i)b((41-H,i-’H(’i/c)(H(i*’I(4)3(3(-H,i-’H(’i1c)(H(i*’I(4)3(3(-H,i-’H(’i0c)(H(i*’I(4)3(3(3H,H/^*0H,H(^*<3i(I*4*3H,H,i¸)’^*TH,H,iø-’^*PH,H,iX’^*LH,H,i(’^*HH,i-8(I(H,i-8(I-i¥I*H,i,8(I.H(iErH-iErš5)H(i©*’I1H-i)’I0i(i;H.i,’J(i(H(i(rCJ(“J*H*i;sCI*i¨1I-H(I/+hH/,hH,i-’H-V)(i)œ’H,i+8(c)(H/i)“I/H-i*’I-H*i)’I*4)-H(i)œi¨1’I/+hH(H*o,hH,i-’H/V)(i)œ’i(c)(H/i*’I/H(i)’I(4)33i¤I*H,iø-’H,i¸)’H,i-’i;8)5+H0H1’I2i(I-+hH-H2p,hH,H,iP’8*J*i(p5-H*i7u,hH,i-’H-i)œ’H*c)(H-i)’I-4*3i(I/i+I.i+I(*h*h*hH*i8“6*(*)3H-m,hi£I*403H-i)œH,’W)-I/i*I(4)3i3I.i/I(3H2H,H(8(H.’J(H-’J.p,hi¢I*4.3H,i-’H-i)œ’I*+hH(,hH*H/c)(H*i*’I*H(i)“I(4)-H.I-4+3(3(33H,W)1m,hiŸI*4,3H,iø-’H,i¸)’H,i-’H18)J(,hi¡I*H(i(p5,H1H,V)ú-H,V)ø-’o5,3H,i(’H,iX’H,i-’H1i)œ’H08)J(,hi I*H(i(p5,H0H,V)šH,V)˜’o5,3H,H,iP’H,iH’8+I*4+3(3(3H,i$6i¬78+I*3H*H3šm5(3i)I-H*i(r5)3H)H,P*0^*(H+H,P*<^*(H*I-3H,i2’L(H-33Á)+(i¨03b+(,(-(.(/(0(1(2(3(5(7(9(;(?(C(G(K(S([(c(k({(‹(›(«(Ë(ë( (*)(iø03O)()()()(*(*(*(*(+(+(+(+(,(,(,(,(-(-(-(-(i¨13M8(9(:(((0(/(1(.(2(-(3(,(4(+(5(*(6()(7(T7œ‰šœ‡Ž‰œš›*S7•œ‰Š”U”—Љ”›S0›‘–U œ`;_e.getModule(_e,i).then(a=>WebAssembly.instantiate(a,{})).then(({exports:a})=>{let o=new Map(Object.entries(a)),s=o.get("puff"),c=o.get("memory").buffer,l=new t(c),u=new DataView(c),d=o.get("__heap_base"),f=r.length,h=d;d+=4,u.setInt32(h,f,!0);let m=d;d+=f,l.set(r,m);let g=d;d+=4,u.setInt32(g,l.byteLength-d,!0),s(d,g,m,h),n(l.slice(d,d+u.getInt32(g,!0)))})})}}}),Object.defineProperty(this,"wasm",{enumerable:!0,get:()=>this._wasm}),this.getOutputChannels=(r,n,i)=>{let a=[],o=0;for(;o<n;)a.push(r.slice(o*i,o++*i+i));return a},this.allocateTypedArray=(r,n,i=!0)=>{let a=this._wasm.malloc(n.BYTES_PER_ELEMENT*r);return i&&this._pointers.add(a),{ptr:a,len:r,buf:new n(this._wasm.HEAP,a,r)}},this.free=()=>{this._pointers.forEach(r=>{this._wasm.free(r)}),this._pointers.clear()},this.codeToString=r=>{let n=[],i=new Uint8Array(this._wasm.HEAP);for(let a=i[r];a!==0;a=i[++r])n.push(a);return String.fromCharCode.apply(null,n)},this.addError=(r,n,i,a,o,s)=>{r.push({message:n,frameLength:i,frameNumber:a,inputBytes:o,outputSamples:s})},this.instantiate=(r,n)=>(n&&_e.setModule(r,n),this._wasm=new r(_e).instantiate(),this._pointers=new Set,this._wasm.ready.then(()=>this))}var Ih=pg(Fh(),1);var Zy=()=>globalThis.Worker||Ih.default,Ji=class extends Zy(){constructor(e,r,n,i){_e.modules||new _e;let a=_e.modules.get(n);if(!a){let o="text/javascript",s,c=`'use strict';(${((l,u,d)=>{let f,h,m=new Promise(g=>{h=g});self.onmessage=({data:{id:g,command:p,data:y}})=>{let v=m,b={id:g},x;p==="init"?(Object.defineProperties(l,{WASMAudioDecoderCommon:{value:u},EmscriptenWASM:{value:d},module:{value:y.module},isWebWorker:{value:!0}}),f=new l(y.options),h()):p==="free"?f.free():p==="ready"?v=v.then(()=>f.ready):p==="reset"?v=v.then(()=>f.reset()):(Object.assign(b,f[p](Array.isArray(y)?y.map(_=>new Uint8Array(_)):new Uint8Array(y))),x=b.channelData?b.channelData.map(_=>_.buffer):[]),v.then(()=>self.postMessage(b,x))}}).toString()})(${n}, ${_e}, ${i})`;try{s=typeof process.versions.node<"u"}catch{}a=s?`data:${o};base64,${Buffer.from(c).toString("base64")}`:URL.createObjectURL(new Blob([c],{type:o})),_e.modules.set(n,a)}super(a,{name:r}),this._id=Number.MIN_SAFE_INTEGER,this._enqueuedOperations=new Map,this.onmessage=({data:o})=>{let{id:s,...c}=o;this._enqueuedOperations.get(s)(c),this._enqueuedOperations.delete(s)},new i(_e).getModule().then(o=>{this.postToDecoder("init",{module:o,options:e})})}async postToDecoder(e,r){return new Promise(n=>{this.postMessage({command:e,id:this._id,data:r}),this._enqueuedOperations.set(this._id++,n)})}get ready(){return this.postToDecoder("ready")}async free(){await this.postToDecoder("free").finally(()=>{this.terminate()})}async reset(){await this.postToDecoder("reset")}};var yl=(t,e)=>{Object.defineProperty(t,"name",{value:e})};var Se=Symbol,Dh=", ",W=(()=>{let t="front",e="side",r="rear",n="left",i="center",a="right";return["",t+" ",e+" ",r+" "].map(o=>[[n,a],[n,a,i],[n,i,a],[i,n,a],[i]].flatMap(s=>s.map(c=>o+c).join(Dh)))})(),Br="LFE",Tn="monophonic (mono)",Pn="stereo",mo="surround",Te=(t,...e)=>`${[Tn,Pn,`linear ${mo}`,"quadraphonic",`5.0 ${mo}`,`5.1 ${mo}`,`6.1 ${mo}`,`7.1 ${mo}`][t-1]} (${e.join(Dh)})`,po=[Tn,Te(2,W[0][0]),Te(3,W[0][2]),Te(4,W[1][0],W[3][0]),Te(5,W[1][2],W[3][0]),Te(6,W[1][2],W[3][0],Br),Te(7,W[1][2],W[2][0],W[3][4],Br),Te(8,W[1][2],W[2][0],W[3][0],Br)],kh=192e3,Uh=176400,bl=96e3,xl=88200,zh=64e3,Rn=48e3,ea=44100,ta=32e3,ra=24e3,na=22050,ia=16e3,vl=12e3,_l=11025,aa=8e3,Oh=7350,gr="absoluteGranulePosition",Y="bandwidth",dt="bitDepth",ft="bitrate",go=ft+"Maximum",yo=ft+"Minimum",bo=ft+"Nominal",Fr="buffer",xo=Fr+"Fullness",be="codec",ht=be+"Frames",vo="coupledStreamCount",oa="crc",_o=oa+"16",So=oa+"32",pe="data",H="description",Ir="duration",sa="emphasis",wo="hasOpusPadding",Vt="header",Cn="isContinuedPacket",Mo="isCopyrighted",Bn="isFirstPage",Ao="isHome",Ht="isLastPage",Zr="isOriginal",jr="isPrivate",Eo="isVbr",Ut="layer",C="length",K="mode",Qr=K+"Extension",Sl="mpeg",Jr=Sl+"Version",Lo="numberAACFrames",To="outputGain",di="preSkip",Po="profile",wl=Se(),en="protection",Hu="rawData",tr="segments",Z="subarray",Fn="version",fi="vorbis",Ro=fi+"Comments",la=fi+"Setup",Ml="block",Co=Ml+"ingStrategy",Al=Se(),tn=Ml+"Size",In=Ml+"size0",Dn=Ml+"size1",Bo=Se(),El="channel",rn=El+"MappingFamily",Fo=El+"MappingTable",mt=El+"Mode",Io=Se(),V=El+"s",Nh="copyright",Do=Nh+"Id",ko=Nh+"IdStart",nn="frame",an=nn+"Count",zt=nn+"Length",Ll="Number",on=nn+Ll,Dr=nn+"Padding",X=nn+"Size",Gh="Rate",Uo="inputSample"+Gh,Wu="page",hi=Wu+"Checksum",ca=Se(),kn=Wu+"SegmentTable",Ie=Wu+"Sequence"+Ll,Xu="sample",zo=Xu+Ll,te=Xu+Gh,kr=Se(),re=Xu+"s",Tl="stream",Oo=Tl+"Count",No=Tl+"Info",Ur=Tl+"Serial"+Ll,$u=Tl+"StructureVersion",Ku="total",mi=Ku+"BytesOut",pi=Ku+"Duration",gi=Ku+"Samples",oe=Se(),rr=Se(),Go=Se(),Un=Se(),yr=Se(),Pl=Se(),Yu=Se(),zn=Se(),fe=Se(),nr=Se(),ir=Se(),zr=Se(),On=Se(),Rl=Se(),br=Se(),xr=Se(),ar=Se(),Cl=Se(),pt=Uint8Array,Nn=DataView,he="reserved",gt="bad",ua="free",Vo="none",Bl="16bit CRC";var qu=(t,e,r)=>{for(let n=0;n<t[C];n++){let i=e(n);for(let a=8;a>0;a--)i=r(i);t[n]=i}return t},Qy=qu(new pt(256),t=>t,t=>t&128?7^t<<1:t<<1),Pe=[qu(new Uint16Array(256),t=>t<<8,t=>t<<1^(t&32768?32773:0))],Re=[qu(new Uint32Array(256),t=>t,t=>t>>>1^(t&1)*3988292384)];for(let t=0;t<15;t++){Pe.push(new Uint16Array(256)),Re.push(new Uint32Array(256));for(let e=0;e<=255;e++)Pe[t+1][e]=Pe[0][Pe[t][e]>>>8]^Pe[t][e]<<8,Re[t+1][e]=Re[t][e]>>>8^Re[0][Re[t][e]&255]}var Hh=t=>{let e=0,r=t[C];for(let n=0;n!==r;n++)e=Qy[e^t[n]];return e},Wh=t=>{let e=t[C],r=e-16,n=0,i=0;for(;i<=r;)n^=t[i++]<<8|t[i++],n=Pe[15][n>>8]^Pe[14][n&255]^Pe[13][t[i++]]^Pe[12][t[i++]]^Pe[11][t[i++]]^Pe[10][t[i++]]^Pe[9][t[i++]]^Pe[8][t[i++]]^Pe[7][t[i++]]^Pe[6][t[i++]]^Pe[5][t[i++]]^Pe[4][t[i++]]^Pe[3][t[i++]]^Pe[2][t[i++]]^Pe[1][t[i++]]^Pe[0][t[i++]];for(;i!==e;)n=(n&255)<<8^Pe[0][n>>8^t[i++]];return n},Xh=t=>{let e=t[C],r=e-16,n=0,i=0;for(;i<=r;)n=Re[15][(t[i++]^n)&255]^Re[14][(t[i++]^n>>>8)&255]^Re[13][(t[i++]^n>>>16)&255]^Re[12][t[i++]^n>>>24]^Re[11][t[i++]]^Re[10][t[i++]]^Re[9][t[i++]]^Re[8][t[i++]]^Re[7][t[i++]]^Re[6][t[i++]]^Re[5][t[i++]]^Re[4][t[i++]]^Re[3][t[i++]]^Re[2][t[i++]]^Re[1][t[i++]]^Re[0][t[i++]];for(;i!==e;)n=Re[0][(n^t[i++])&255]^n>>>8;return n^-1},Wo=(...t)=>{let e=new pt(t.reduce((r,n)=>r+n[C],0));return t.reduce((r,n)=>(e.set(n,r),r+n[C]),0),e},Wt=t=>String.fromCharCode(...t),Vh=[0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15],Ho=t=>Vh[t&15]<<4|Vh[t>>4],Fl=class{constructor(e){this._data=e,this._pos=e[C]*8}set position(e){this._pos=e}get position(){return this._pos}read(e){let r=Math.floor(this._pos/8),n=this._pos%8;return this._pos-=e,(Ho(this._data[r-1])<<8)+Ho(this._data[r])>>7-n&255}},$h=(t,e)=>{try{return t.getBigInt64(e,!0)}catch{let r=t.getUint8(e+7)&128?-1:1,n=t.getUint32(e,!0),i=t.getUint32(e+4,!0);return r===-1&&(n=~n+1,i=~i+1),i>1048575&&console.warn("This platform does not support BigInt"),r*(n+i*2**32)}};var Xo=class{constructor(e,r){this._onCodecHeader=e,this._onCodecUpdate=r,this[br]()}[xr](){this._isEnabled=!0}[br](){this._headerCache=new Map,this._codecUpdateData=new WeakMap,this._codecHeaderSent=!1,this._codecShouldUpdate=!1,this._bitrate=null,this._isEnabled=!1}[Rl](e,r){if(this._onCodecUpdate){this._bitrate!==e&&(this._bitrate=e,this._codecShouldUpdate=!0);let n=this._codecUpdateData.get(this._headerCache.get(this._currentHeader));this._codecShouldUpdate&&n&&this._onCodecUpdate({bitrate:e,...n},r),this._codecShouldUpdate=!1}}[fe](e){let r=this._headerCache.get(e);return r&&this._updateCurrentHeader(e),r}[nr](e,r,n){this._isEnabled&&(this._codecHeaderSent||(this._onCodecHeader({...r}),this._codecHeaderSent=!0),this._updateCurrentHeader(e),this._headerCache.set(e,r),this._codecUpdateData.set(r,n))}_updateCurrentHeader(e){this._onCodecUpdate&&e!==this._currentHeader&&(this._codecShouldUpdate=!0,this._currentHeader=e)}};var Oe=new WeakMap,at=new WeakMap;var yt=class{constructor(e,r){this._codecParser=e,this._headerCache=r}*[Yu](){let e;do{if(e=yield*this.Frame[ir](this._codecParser,this._headerCache,0),e)return e;this._codecParser[rr](1)}while(!0)}*[zn](e){let r=yield*this[Yu](),n=at.get(r)[C];if(e||this._codecParser._flushing||(yield*this.Header[fe](this._codecParser,this._headerCache,n)))return this._headerCache[xr](),this._codecParser[rr](n),this._codecParser[Un](r),r;this._codecParser[yr](`Missing ${nn} at ${n} bytes from current position.`,`Dropping current ${nn} and trying again.`),this._headerCache[br](),this._codecParser[rr](1)}};var yi=class{constructor(e,r){at.set(this,{[Vt]:e}),this[pe]=r}};var Xt=class extends yi{static*[ir](e,r,n,i,a){let o=yield*e[fe](n,i,a);if(o){let s=Oe.get(o)[zt],c=Oe.get(o)[re],l=(yield*n[oe](s,a))[Z](0,s);return new r(o,l,c)}else return null}constructor(e,r,n){super(e,r),this[Vt]=e,this[re]=n,this[Ir]=n/e[te]*1e3,this[on]=null,this[mi]=null,this[gi]=null,this[pi]=null,at.get(this)[C]=r[C]}};var Zu="unsynchronizationFlag",ju="extendedHeaderFlag",Qu="experimentalFlag",Ju="footerPresent",$o=class t{static*getID3v2Header(e,r,n){let a={},o=yield*e[oe](3,n);if(o[0]!==73||o[1]!==68||o[2]!==51||(o=yield*e[oe](10,n),a[Fn]=`id3v2.${o[3]}.${o[4]}`,o[5]&15)||(a[Zu]=!!(o[5]&128),a[ju]=!!(o[5]&64),a[Qu]=!!(o[5]&32),a[Ju]=!!(o[5]&16),o[6]&128||o[7]&128||o[8]&128||o[9]&128))return null;let s=o[6]<<21|o[7]<<14|o[8]<<7|o[9];return a[C]=10+s,new t(a)}constructor(e){this[Fn]=e[Fn],this[Zu]=e[Zu],this[ju]=e[ju],this[Qu]=e[Qu],this[Ju]=e[Ju],this[C]=e[C]}};var $t=class{constructor(e){Oe.set(this,e),this[dt]=e[dt],this[ft]=null,this[V]=e[V],this[mt]=e[mt],this[te]=e[te]}};var jh={0:[ua,ua,ua,ua,ua],16:[32,32,32,32,8],240:[gt,gt,gt,gt,gt]},Il=(t,e,r)=>8*((t+r)%e+e)*(1<<(t+r)/e)-8*e*(e/8|0);for(let t=2;t<15;t++)jh[t<<4]=[t*32,Il(t,4,0),Il(t,4,-1),Il(t,8,4),Il(t,8,0)];var Jy=0,e1=1,t1=2,r1=3,Kh=4,Dl="bands ",kl=" to 31",Yh={0:Dl+4+kl,16:Dl+8+kl,32:Dl+12+kl,48:Dl+16+kl},bi="bitrateIndex",Ko="v2",Gl="v1",Ul="Intensity stereo ",zl=", MS stereo ",Ol="on",Nl="off",n1={0:Ul+Nl+zl+Nl,16:Ul+Ol+zl+Nl,32:Ul+Nl+zl+Ol,48:Ul+Ol+zl+Ol},ed={0:{[H]:he},2:{[H]:"Layer III",[Dr]:1,[Qr]:n1,[Gl]:{[bi]:t1,[re]:1152},[Ko]:{[bi]:Kh,[re]:576}},4:{[H]:"Layer II",[Dr]:1,[Qr]:Yh,[re]:1152,[Gl]:{[bi]:e1},[Ko]:{[bi]:Kh}},6:{[H]:"Layer I",[Dr]:4,[Qr]:Yh,[re]:384,[Gl]:{[bi]:Jy},[Ko]:{[bi]:r1}}},td="MPEG Version ",qh="ISO/IEC ",i1={0:{[H]:`${td}2.5 (later extension of MPEG 2)`,[Ut]:Ko,[te]:{0:_l,4:vl,8:aa,12:he}},8:{[H]:he},16:{[H]:`${td}2 (${qh}13818-3)`,[Ut]:Ko,[te]:{0:na,4:ra,8:ia,12:he}},24:{[H]:`${td}1 (${qh}11172-3)`,[Ut]:Gl,[te]:{0:ea,4:Rn,8:ta,12:he}},length:C},a1={0:Bl,1:Vo},o1={0:Vo,1:"50/15 ms",2:he,3:"CCIT J.17"},Zh={0:{[V]:2,[H]:Pn},64:{[V]:2,[H]:"joint "+Pn},128:{[V]:2,[H]:"dual channel"},192:{[V]:1,[H]:Tn}},xi=class t extends $t{static*[fe](e,r,n){let i={},a=yield*$o.getID3v2Header(e,r,n);a&&(yield*e[oe](a[C],n),e[rr](a[C]));let o=yield*e[oe](4,n),s=Wt(o[Z](0,4)),c=r[fe](s);if(c)return new t(c);if(o[0]!==255||o[1]<224)return null;let l=i1[o[1]&24];if(l[H]===he)return null;let u=o[1]&6;if(ed[u][H]===he)return null;let d={...ed[u],...ed[u][l[Ut]]};if(i[Jr]=l[H],i[Ut]=d[H],i[re]=d[re],i[en]=a1[o[1]&1],i[C]=4,i[ft]=jh[o[2]&240][d[bi]],i[ft]===gt||(i[te]=l[te][o[2]&12],i[te]===he)||(i[Dr]=o[2]&2&&d[Dr],i[jr]=!!(o[2]&1),i[zt]=Math.floor(125*i[ft]*i[re]/i[te]+i[Dr]),!i[zt]))return null;let f=o[3]&192;if(i[mt]=Zh[f][H],i[V]=Zh[f][V],i[Qr]=d[Qr][o[3]&48],i[Mo]=!!(o[3]&8),i[Zr]=!!(o[3]&4),i[sa]=o1[o[3]&3],i[sa]===he)return null;i[dt]=16;{let{length:h,frameLength:m,samples:g,...p}=i;r[nr](s,i,p)}return new t(i)}constructor(e){super(e),this[ft]=e[ft],this[sa]=e[sa],this[Dr]=e[Dr],this[Mo]=e[Mo],this[Zr]=e[Zr],this[jr]=e[jr],this[Ut]=e[Ut],this[Qr]=e[Qr],this[Jr]=e[Jr],this[en]=e[en]}};var Yo=class t extends Xt{static*[ir](e,r,n){return yield*super[ir](xi,t,e,r,n)}constructor(e,r,n){super(e,r,n)}};var qo=class extends yt{constructor(e,r,n){super(e,r),this.Frame=Yo,this.Header=xi,n(this[be])}get[be](){return Sl}*[zr](){return yield*this[zn]()}};var s1={0:"MPEG-4",8:"MPEG-2"},l1={0:"valid",2:gt,4:gt,6:gt},c1={0:Bl,1:Vo},u1={0:"AAC Main",64:"AAC LC (Low Complexity)",128:"AAC SSR (Scalable Sample Rate)",192:"AAC LTP (Long Term Prediction)"},d1={0:bl,4:xl,8:zh,12:Rn,16:ea,20:ta,24:ra,28:na,32:ia,36:vl,40:_l,44:aa,48:Oh,52:he,56:he,60:"frequency is written explicitly"},Qh={0:{[V]:0,[H]:"Defined in AOT Specific Config"},64:{[V]:1,[H]:Tn},128:{[V]:2,[H]:Te(2,W[0][0])},192:{[V]:3,[H]:Te(3,W[1][3])},256:{[V]:4,[H]:Te(4,W[1][3],W[3][4])},320:{[V]:5,[H]:Te(5,W[1][3],W[3][0])},384:{[V]:6,[H]:Te(6,W[1][3],W[3][0],Br)},448:{[V]:8,[H]:Te(8,W[1][3],W[2][0],W[3][0],Br)}},vi=class t extends $t{static*[fe](e,r,n){let i={},a=yield*e[oe](7,n),o=Wt([a[0],a[1],a[2],a[3]&252|a[6]&3]),s=r[fe](o);if(s)Object.assign(i,s);else{if(a[0]!==255||a[1]<240||(i[Jr]=s1[a[1]&8],i[Ut]=l1[a[1]&6],i[Ut]===gt))return null;let l=a[1]&1;i[en]=c1[l],i[C]=l?7:9,i[wl]=a[2]&192,i[kr]=a[2]&60;let u=a[2]&2;if(i[Po]=u1[i[wl]],i[te]=d1[i[kr]],i[te]===he)return null;i[jr]=!!u,i[Io]=(a[2]<<8|a[3])&448,i[mt]=Qh[i[Io]][H],i[V]=Qh[i[Io]][V],i[Zr]=!!(a[3]&32),i[Ao]=!!(a[3]&8),i[Do]=!!(a[3]&8),i[ko]=!!(a[3]&4),i[dt]=16,i[re]=1024,i[Lo]=a[6]&3;{let{length:d,channelModeBits:f,profileBits:h,sampleRateBits:m,frameLength:g,samples:p,numberAACFrames:y,...v}=i;r[nr](o,i,v)}}if(i[zt]=(a[3]<<11|a[4]<<3|a[5]>>5)&8191,!i[zt])return null;let c=(a[5]<<6|a[6]>>2)&2047;return i[xo]=c===2047?"VBR":c,new t(i)}constructor(e){super(e),this[Do]=e[Do],this[ko]=e[ko],this[xo]=e[xo],this[Ao]=e[Ao],this[Zr]=e[Zr],this[jr]=e[jr],this[Ut]=e[Ut],this[C]=e[C],this[Jr]=e[Jr],this[Lo]=e[Lo],this[Po]=e[Po],this[en]=e[en]}get audioSpecificConfig(){let e=Oe.get(this),r=e[wl]+64<<5|e[kr]<<5|e[Io]>>3,n=new pt(2);return new Nn(n[Fr]).setUint16(0,r,!1),n}};var Zo=class t extends Xt{static*[ir](e,r,n){return yield*super[ir](vi,t,e,r,n)}constructor(e,r,n){super(e,r,n)}};var jo=class extends yt{constructor(e,r,n){super(e,r),this.Frame=Zo,this.Header=vi,n(this[be])}get[be](){return"aac"}*[zr](){return yield*this[zn]()}};var Gn=class t extends Xt{static _getFrameFooterCrc16(e){return(e[e[C]-2]<<8)+e[e[C]-1]}static[Cl](e){let r=t._getFrameFooterCrc16(e),n=Wh(e[Z](0,-2));return r===n}constructor(e,r,n){r[No]=n,r[_o]=t._getFrameFooterCrc16(e),super(r,e,Oe.get(r)[re])}};var Jh="get from STREAMINFO metadata block",f1={0:"Fixed",1:"Variable"},em={0:he,16:192};for(let t=2;t<16;t++)em[t<<4]=t<6?576*2**(t-2):2**t;var h1={0:Jh,1:xl,2:Uh,3:kh,4:aa,5:ia,6:na,7:ra,8:ta,9:ea,10:Rn,11:bl,15:gt},m1={0:{[V]:1,[H]:Tn},16:{[V]:2,[H]:Te(2,W[0][0])},32:{[V]:3,[H]:Te(3,W[0][1])},48:{[V]:4,[H]:Te(4,W[1][0],W[3][0])},64:{[V]:5,[H]:Te(5,W[1][1],W[3][0])},80:{[V]:6,[H]:Te(6,W[1][1],Br,W[3][0])},96:{[V]:7,[H]:Te(7,W[1][1],Br,W[3][4],W[2][0])},112:{[V]:8,[H]:Te(8,W[1][1],Br,W[3][0],W[2][0])},128:{[V]:2,[H]:`${Pn} (left, diff)`},144:{[V]:2,[H]:`${Pn} (diff, right)`},160:{[V]:2,[H]:`${Pn} (avg, diff)`},176:he,192:he,208:he,224:he,240:he},p1={0:Jh,2:8,4:12,6:he,8:16,10:20,12:24,14:he},Vn=class t extends $t{static _decodeUTF8Int(e){if(e[0]>254)return null;if(e[0]<128)return{value:e[0],length:1};let r=1;for(let o=64;o&e[0];o>>=1)r++;let n=r-1,i=0,a=0;for(;n>0;a+=6,n--){if((e[n]&192)!==128)return null;i|=(e[n]&63)<<a}return i|=(e[n]&127>>r)<<a,{value:i,length:r}}static[ar](e,r){let n={[oe]:function*(){return e}};return t[fe](n,r,0).next().value}static*[fe](e,r,n){let i=yield*e[oe](6,n);if(i[0]!==255||!(i[1]===248||i[1]===249))return null;let a={},o=Wt(i[Z](0,4)),s=r[fe](o);if(s)Object.assign(a,s);else{if(a[Al]=i[1]&1,a[Co]=f1[a[Al]],a[Bo]=i[2]&240,a[kr]=i[2]&15,a[tn]=em[a[Bo]],a[tn]===he||(a[te]=h1[a[kr]],a[te]===gt)||i[3]&1)return null;let l=m1[i[3]&240];if(l===he||(a[V]=l[V],a[mt]=l[H],a[dt]=p1[i[3]&14],a[dt]===he))return null}a[C]=5,i=yield*e[oe](a[C]+8,n);let c=t._decodeUTF8Int(i[Z](4));if(!c||(a[Al]?a[zo]=c.value:a[on]=c.value,a[C]+=c[C],a[Bo]===96?(i[C]<a[C]&&(i=yield*e[oe](a[C],n)),a[tn]=i[a[C]-1]+1,a[C]+=1):a[Bo]===112&&(i[C]<a[C]&&(i=yield*e[oe](a[C],n)),a[tn]=(i[a[C]-1]<<8)+i[a[C]]+1,a[C]+=2),a[re]=a[tn],a[kr]===12?(i[C]<a[C]&&(i=yield*e[oe](a[C],n)),a[te]=i[a[C]-1]*1e3,a[C]+=1):a[kr]===13?(i[C]<a[C]&&(i=yield*e[oe](a[C],n)),a[te]=(i[a[C]-1]<<8)+i[a[C]],a[C]+=2):a[kr]===14&&(i[C]<a[C]&&(i=yield*e[oe](a[C],n)),a[te]=((i[a[C]-1]<<8)+i[a[C]])*10,a[C]+=2),i[C]<a[C]&&(i=yield*e[oe](a[C],n)),a[oa]=i[a[C]-1],a[oa]!==Hh(i[Z](0,a[C]-1))))return null;if(!s){let{blockingStrategyBits:l,frameNumber:u,sampleNumber:d,samples:f,sampleRateBits:h,blockSizeBits:m,crc:g,length:p,...y}=a;r[nr](o,a,y)}return new t(a)}constructor(e){super(e),this[_o]=null,this[Co]=e[Co],this[tn]=e[tn],this[on]=e[on],this[zo]=e[zo],this[No]=null}};var g1=2,y1=512*1024,_i=class extends yt{constructor(e,r,n){super(e,r),this.Frame=Gn,this.Header=Vn,n(this[be])}get[be](){return"flac"}*_getNextFrameSyncOffset(e){let r=yield*this._codecParser[oe](2,0),n=r[C]-2;for(;e<n;){if(r[e]===255){let a=r[e+1];if(a===248||a===249)break;a!==255&&e++}e++}return e}*[zr](){do{let e=yield*Vn[fe](this._codecParser,this._headerCache,0);if(e){let r=Oe.get(e)[C]+g1;for(;r<=y1;){if(this._codecParser._flushing||(yield*Vn[fe](this._codecParser,this._headerCache,r))){let n=yield*this._codecParser[oe](r);if(this._codecParser._flushing||(n=n[Z](0,r)),Gn[Cl](n)){let i=new Gn(n,e);return this._headerCache[xr](),this._codecParser[rr](r),this._codecParser[Un](i),i}}r=yield*this._getNextFrameSyncOffset(r+1)}this._codecParser[yr](`Unable to sync FLAC frame after searching ${r} bytes.`),this._codecParser[rr](r)}else this._codecParser[rr](yield*this._getNextFrameSyncOffset(1))}while(!0)}[On](e){return e[Ie]===0?(this._headerCache[xr](),this._streamInfo=e[pe][Z](13)):e[Ie]===1||(e[ht]=at.get(e)[tr].map(r=>{let n=Vn[ar](r,this._headerCache);if(n)return new Gn(r,n,this._streamInfo);this._codecParser[yr]("Failed to parse Ogg FLAC frame","Skipping invalid FLAC frame")}).filter(r=>!!r)),e}};var Si=class t{static*[fe](e,r,n){let i={},a=yield*e[oe](28,n);if(a[0]!==79||a[1]!==103||a[2]!==103||a[3]!==83||(i[$u]=a[4],a[5]&248))return null;i[Ht]=!!(a[5]&4),i[Bn]=!!(a[5]&2),i[Cn]=!!(a[5]&1);let s=new Nn(pt.from(a[Z](0,28))[Fr]);i[gr]=$h(s,6),i[Ur]=s.getInt32(14,!0),i[Ie]=s.getInt32(18,!0),i[hi]=s.getInt32(22,!0);let c=a[26];i[C]=c+27,a=yield*e[oe](i[C],n),i[zt]=0,i[kn]=[],i[ca]=pt.from(a[Z](27,i[C]));for(let l=0,u=0;l<c;l++){let d=i[ca][l];i[zt]+=d,u+=d,(d!==255||l===c-1)&&(i[kn].push(u),u=0)}return new t(i)}constructor(e){Oe.set(this,e),this[gr]=e[gr],this[Cn]=e[Cn],this[Bn]=e[Bn],this[Ht]=e[Ht],this[kn]=e[kn],this[Ie]=e[Ie],this[hi]=e[hi],this[Ur]=e[Ur]}};var Qo=class t extends yi{static*[ir](e,r,n){let i=yield*Si[fe](e,r,n);if(i){let a=Oe.get(i)[zt],o=Oe.get(i)[C],s=o+a,c=(yield*e[oe](s,0))[Z](0,s),l=c[Z](o,s);return new t(i,l,c)}else return null}constructor(e,r,n){super(e,r),at.get(this)[C]=n[C],this[ht]=[],this[Hu]=n,this[gr]=e[gr],this[So]=e[hi],this[Ir]=0,this[Cn]=e[Cn],this[Bn]=e[Bn],this[Ht]=e[Ht],this[Ie]=e[Ie],this[re]=0,this[Ur]=e[Ur]}};var da=class extends Xt{constructor(e,r,n){super(r,e,n)}};var tm={0:po.slice(0,2),1:po},or="SILK-only",ot="CELT-only",Vl="Hybrid",Hn="narrowband",Hl="medium-band",Wn="wideband",fa="super-wideband",ha="fullband",b1={0:{[K]:or,[Y]:Hn,[X]:10},8:{[K]:or,[Y]:Hn,[X]:20},16:{[K]:or,[Y]:Hn,[X]:40},24:{[K]:or,[Y]:Hn,[X]:60},32:{[K]:or,[Y]:Hl,[X]:10},40:{[K]:or,[Y]:Hl,[X]:20},48:{[K]:or,[Y]:Hl,[X]:40},56:{[K]:or,[Y]:Hl,[X]:60},64:{[K]:or,[Y]:Wn,[X]:10},72:{[K]:or,[Y]:Wn,[X]:20},80:{[K]:or,[Y]:Wn,[X]:40},88:{[K]:or,[Y]:Wn,[X]:60},96:{[K]:Vl,[Y]:fa,[X]:10},104:{[K]:Vl,[Y]:fa,[X]:20},112:{[K]:Vl,[Y]:ha,[X]:10},120:{[K]:Vl,[Y]:ha,[X]:20},128:{[K]:ot,[Y]:Hn,[X]:2.5},136:{[K]:ot,[Y]:Hn,[X]:5},144:{[K]:ot,[Y]:Hn,[X]:10},152:{[K]:ot,[Y]:Hn,[X]:20},160:{[K]:ot,[Y]:Wn,[X]:2.5},168:{[K]:ot,[Y]:Wn,[X]:5},176:{[K]:ot,[Y]:Wn,[X]:10},184:{[K]:ot,[Y]:Wn,[X]:20},192:{[K]:ot,[Y]:fa,[X]:2.5},200:{[K]:ot,[Y]:fa,[X]:5},208:{[K]:ot,[Y]:fa,[X]:10},216:{[K]:ot,[Y]:fa,[X]:20},224:{[K]:ot,[Y]:ha,[X]:2.5},232:{[K]:ot,[Y]:ha,[X]:5},240:{[K]:ot,[Y]:ha,[X]:10},248:{[K]:ot,[Y]:ha,[X]:20}},ma=class t extends $t{static[ar](e,r,n){let i={};if(i[V]=e[9],i[rn]=e[18],i[C]=i[rn]!==0?21+i[V]:19,e[C]<i[C])throw new Error("Out of data while inside an Ogg Page");let a=r[0]&3,o=a===3?2:1,s=Wt(e[Z](0,i[C]))+Wt(r[Z](0,o)),c=n[fe](s);if(c)return new t(c);if(s.substr(0,8)!=="OpusHead"||e[8]!==1)return null;i[pe]=pt.from(e[Z](0,i[C]));let l=new Nn(i[pe][Fr]);if(i[dt]=16,i[di]=l.getUint16(10,!0),i[Uo]=l.getUint32(12,!0),i[te]=Rn,i[To]=l.getInt16(16,!0),i[rn]in tm&&(i[mt]=tm[i[rn]][i[V]-1],!i[mt]))return null;i[rn]!==0&&(i[Oo]=e[19],i[vo]=e[20],i[Fo]=[...e[Z](21,i[V]+21)]);let u=b1[248&r[0]];switch(i[K]=u[K],i[Y]=u[Y],i[X]=u[X],a){case 0:i[an]=1;break;case 1:case 2:i[an]=2;break;case 3:i[Eo]=!!(128&r[1]),i[wo]=!!(64&r[1]),i[an]=63&r[1];break;default:return null}{let{length:d,data:f,channelMappingFamily:h,...m}=i;n[nr](s,i,m)}return new t(i)}constructor(e){super(e),this[pe]=e[pe],this[Y]=e[Y],this[rn]=e[rn],this[Fo]=e[Fo],this[vo]=e[vo],this[an]=e[an],this[X]=e[X],this[wo]=e[wo],this[Uo]=e[Uo],this[Eo]=e[Eo],this[K]=e[K],this[To]=e[To],this[di]=e[di],this[Oo]=e[Oo]}};var Jo=class extends yt{constructor(e,r,n){super(e,r),this.Frame=da,this.Header=ma,n(this[be]),this._identificationHeader=null,this._preSkipRemaining=null}get[be](){return"opus"}[On](e){return e[Ie]===0?(this._headerCache[xr](),this._identificationHeader=e[pe]):e[Ie]===1||(e[ht]=at.get(e)[tr].map(r=>{let n=ma[ar](this._identificationHeader,r,this._headerCache);if(n){this._preSkipRemaining===null&&(this._preSkipRemaining=n[di]);let i=n[X]*n[an]/1e3*n[te];return this._preSkipRemaining>0&&(this._preSkipRemaining-=i,i=this._preSkipRemaining<0?-this._preSkipRemaining:0),new da(r,n,i)}this._codecParser[Pl]("Failed to parse Ogg Opus Header","Not a valid Ogg Opus file")})),e}};var pa=class extends Xt{constructor(e,r,n){super(r,e,n)}};var rd={};for(let t=0;t<8;t++)rd[t+6]=2**(6+t);var es=class t extends $t{static[ar](e,r,n,i){if(e[C]<30)throw new Error("Out of data while inside an Ogg Page");let a=Wt(e[Z](0,30)),o=r[fe](a);if(o)return new t(o);let s={[C]:30};if(a.substr(0,7)!=="vorbis")return null;s[pe]=pt.from(e[Z](0,30));let c=new Nn(s[pe][Fr]);if(s[Fn]=c.getUint32(7,!0),s[Fn]!==0||(s[V]=e[11],s[mt]=po[s[V]-1]||"application defined",s[te]=c.getUint32(12,!0),s[go]=c.getInt32(16,!0),s[bo]=c.getInt32(20,!0),s[yo]=c.getInt32(24,!0),s[Dn]=rd[(e[28]&240)>>4],s[In]=rd[e[28]&15],s[In]>s[Dn])||e[29]!==1)return null;s[dt]=32,s[la]=i,s[Ro]=n;{let{length:l,data:u,version:d,vorbisSetup:f,vorbisComments:h,...m}=s;r[nr](a,s,m)}return new t(s)}constructor(e){super(e),this[go]=e[go],this[yo]=e[yo],this[bo]=e[bo],this[In]=e[In],this[Dn]=e[Dn],this[pe]=e[pe],this[Ro]=e[Ro],this[la]=e[la]}};var ts=class extends yt{constructor(e,r,n){super(e,r),this.Frame=pa,n(this[be]),this._identificationHeader=null,this._setupComplete=!1,this._prevBlockSize=null}get[be](){return fi}[On](e){e[ht]=[];for(let r of at.get(e)[tr])if(r[0]===1)this._headerCache[xr](),this._identificationHeader=e[pe],this._setupComplete=!1;else if(r[0]===3)this._vorbisComments=r;else if(r[0]===5)this._vorbisSetup=r,this._mode=this._parseSetupHeader(r),this._setupComplete=!0;else if(this._setupComplete){let n=es[ar](this._identificationHeader,this._headerCache,this._vorbisComments,this._vorbisSetup);n?e[ht].push(new pa(r,n,this._getSamples(r,n))):this._codecParser[logError]("Failed to parse Ogg Vorbis Header","Not a valid Ogg Vorbis file")}return e}_getSamples(e,r){let i=this._mode.blockFlags[e[0]>>1&this._mode.mask]?r[Dn]:r[In],a=this._prevBlockSize===null?0:(this._prevBlockSize+i)/4;return this._prevBlockSize=i,a}_parseSetupHeader(e){let r=new Fl(e),n={count:0,blockFlags:[]};for(;(r.read(1)&1)!==1;);let i;for(;n.count<64&&r.position>0;){Ho(r.read(8));let a=0;for(;r.read(8)===0&&a++<3;);if(a===4)i=r.read(7),n.blockFlags.unshift(i&1),r.position+=6,n.count++;else{((Ho(i)&126)>>1)+1!==n.count&&this._codecParser[yr]("vorbis derived mode count did not match actual mode count");break}}return n.mask=(1<<Math.log2(n.count))-1,n}};var nd=class{constructor(e,r,n){this._codecParser=e,this._headerCache=r,this._onCodec=n,this._continuedPacket=new pt,this._codec=null,this._isSupported=null,this._previousAbsoluteGranulePosition=null}get[be](){return this._codec||""}_updateCodec(e,r){this._codec!==e&&(this._headerCache[br](),this._parser=new r(this._codecParser,this._headerCache,this._onCodec),this._codec=e)}_checkCodecSupport({data:e}){let r=Wt(e[Z](0,8));switch(r){case"fishead\0":return!1;case"OpusHead":return this._updateCodec("opus",Jo),!0;case(/^\x7fFLAC/.test(r)&&r):return this._updateCodec("flac",_i),!0;case(/^\x01vorbis/.test(r)&&r):return this._updateCodec(fi,ts),!0;default:return!1}}_checkPageSequenceNumber(e){e[Ie]!==this._pageSequenceNumber+1&&this._pageSequenceNumber>1&&e[Ie]>1&&this._codecParser[yr]("Unexpected gap in Ogg Page Sequence Number.",`Expected: ${this._pageSequenceNumber+1}, Got: ${e[Ie]}`),this._pageSequenceNumber=e[Ie]}_parsePage(e){this._isSupported===null&&(this._pageSequenceNumber=e[Ie],this._isSupported=this._checkCodecSupport(e)),this._checkPageSequenceNumber(e);let r=at.get(e),n=Oe.get(r[Vt]),i=0;if(r[tr]=n[kn].map(a=>e[pe][Z](i,i+=a)),this._continuedPacket[C]&&(r[tr][0]=Wo(this._continuedPacket,r[tr][0]),this._continuedPacket=new pt),n[ca][n[ca][C]-1]===255&&(this._continuedPacket=Wo(this._continuedPacket,r[tr].pop())),this._previousAbsoluteGranulePosition!==null&&(e[re]=Number(e[gr]-this._previousAbsoluteGranulePosition)),this._previousAbsoluteGranulePosition=e[gr],this._isSupported){let a=this._parser[On](e);return this._codecParser[Un](a),a}else return e}},rs=class extends yt{constructor(e,r,n){super(e,r),this._onCodec=n,this.Frame=Qo,this.Header=Si,this._streams=new Map,this._currentSerialNumber=null}get[be](){let e=this._streams.get(this._currentSerialNumber);return e?e.codec:""}*[zr](){let e=yield*this[zn](!0);this._currentSerialNumber=e[Ur];let r=this._streams.get(this._currentSerialNumber);return r||(r=new nd(this._codecParser,this._headerCache,this._onCodec),this._streams.set(this._currentSerialNumber,r)),e[Ht]&&this._streams.delete(this._currentSerialNumber),r._parsePage(e)}};var id=()=>{},ns=class{constructor(e,{onCodec:r,onCodecHeader:n,onCodecUpdate:i,enableLogging:a=!1,enableFrameCRC32:o=!0}={}){this._inputMimeType=e,this._onCodec=r||id,this._onCodecHeader=n||id,this._onCodecUpdate=i,this._enableLogging=a,this._crc32=o?Xh:id,this[br]()}get[be](){return this._parser?this._parser[be]:""}[br](){this._headerCache=new Xo(this._onCodecHeader,this._onCodecUpdate),this._generator=this._getGenerator(),this._generator.next()}*flush(){this._flushing=!0;for(let e=this._generator.next();e.value;e=this._generator.next())yield e.value;this._flushing=!1,this[br]()}*parseChunk(e){for(let r=this._generator.next(e);r.value;r=this._generator.next())yield r.value}parseAll(e){return[...this.parseChunk(e),...this.flush()]}*_getGenerator(){if(this._inputMimeType.match(/aac/))this._parser=new jo(this,this._headerCache,this._onCodec);else if(this._inputMimeType.match(/mpeg/))this._parser=new qo(this,this._headerCache,this._onCodec);else if(this._inputMimeType.match(/flac/))this._parser=new _i(this,this._headerCache,this._onCodec);else if(this._inputMimeType.match(/ogg/))this._parser=new rs(this,this._headerCache,this._onCodec);else throw new Error(`Unsupported Codec ${mimeType}`);for(this._frameNumber=0,this._currentReadPosition=0,this._totalBytesIn=0,this._totalBytesOut=0,this._totalSamples=0,this._sampleRate=void 0,this._rawData=new Uint8Array(0);;){let e=yield*this._parser[zr]();e&&(yield e)}}*[oe](e=0,r=0){let n;for(;this._rawData[C]<=e+r;){if(n=yield,this._flushing)return this._rawData[Z](r);n&&(this._totalBytesIn+=n[C],this._rawData=Wo(this._rawData,n))}return this._rawData[Z](r)}[rr](e){this._currentReadPosition+=e,this._rawData=this._rawData[Z](e)}[Go](e){this._sampleRate=e[Vt][te],e[Vt][ft]=e[Ir]>0?Math.round(e[pe][C]/e[Ir])*8:0,e[on]=this._frameNumber++,e[mi]=this._totalBytesOut,e[gi]=this._totalSamples,e[pi]=this._totalSamples/this._sampleRate*1e3,e[So]=this._crc32(e[pe]),this._headerCache[Rl](e[Vt][ft],e[pi]),this._totalBytesOut+=e[pe][C],this._totalSamples+=e[re]}[Un](e){if(e[ht]){if(e[Ht]){let r=e[re];e[ht].forEach(n=>{let i=n[re];r<i&&(n[re]=r>0?r:0,n[Ir]=n[re]/n[Vt][te]*1e3),r-=i,this[Go](n)})}else e[re]=0,e[ht].forEach(r=>{e[re]+=r[re],this[Go](r)});e[Ir]=e[re]/this._sampleRate*1e3||0,e[gi]=this._totalSamples,e[pi]=this._totalSamples/this._sampleRate*1e3||0,e[mi]=this._totalBytesOut}else this[Go](e)}_log(e,r){if(this._enableLogging){let n=[`${be}: ${this[be]}`,`inputMimeType: ${this._inputMimeType}`,`readPosition: ${this._currentReadPosition}`,`totalBytesIn: ${this._totalBytesIn}`,`${mi}: ${this._totalBytesOut}`],i=Math.max(...n.map(a=>a[C]));r.push(`--stats--${"-".repeat(i-9)}`,...n,"-".repeat(i)),e("codec-parser",r.reduce((a,o)=>a+`
4
+ `+o,""))}}[yr](...e){this._log(console.warn,e)}[Pl](...e){this._log(console.error,e)}};var rm=ns;var Wl=ht;var Xl=pe;var nm=Vt;var im=Ht;var am=la;var om=gi;function sn(t){var e=e;function r(){}e={};function n(k){throw k}var i,a,o,s,c,l,u,d,f,h,m;function g(){var k=m.buffer;i=new Int8Array(k),a=new Int16Array(k),s=new Uint8Array(k),c=new Uint16Array(k),o=new Int32Array(k),l=new Uint32Array(k),u=new Float32Array(k),d=new Float64Array(k),f=new BigInt64Array(k),h=new BigUint64Array(k)}for(var p=k=>{for(var se,ke,De=0,fr=0,Zt=k.length,mn=new Uint8Array((Zt*3>>2)-(k[Zt-2]=="=")-(k[Zt-1]=="="));De<Zt;De+=4,fr+=3)se=O[k.charCodeAt(De+1)],ke=O[k.charCodeAt(De+2)],mn[fr]=O[k.charCodeAt(De)]<<2|se>>4,mn[fr+1]=se<<4|ke>>2,mn[fr+2]=ke<<6|O[k.charCodeAt(De+3)];return mn},y=()=>n(""),v=()=>{},b={},x=k=>k(),_=()=>performance.now(),w=(k,se)=>{if(b[k]&&(clearTimeout(b[k].id),delete b[k]),!se)return 0;var ke=setTimeout(()=>{delete b[k],x(()=>ut(k,_()))},se);return b[k]={id:ke,timeout_ms:se},0},S=Math.atan,A=Math.cos,L=Math.exp,M=Math.log,P=Math.pow,I=Math.sin,D=k=>{var se=s.length;return k>>>=0,!1},B=k=>{throw`exit(${k})`},O=new Uint8Array(123),Q=25;Q>=0;--Q)O[48+Q]=52+Q,O[65+Q]=Q,O[97+Q]=26+Q;O[43]=62,O[47]=63;var Ge={e:y,d:v,f:w,b:S,a:A,i:L,h:M,g:P,c:I,k:D,j:B};function me(k){Me=k.n,ge=k.o,ue=k.p,ye=k.q,Ve=k.r,ct=k.s,qt=k.t,ut=k.v}var Me,ge,ue,ye,Ve,ct,qt,ut;function He(k){k.m()}sn.wasm||Object.defineProperty(sn,"wasm",{get:()=>String.raw`dynEncode012091253f87dì%nä= 4&¿nÝØä‘ÂLÚªã9ÚØ[äº\ ¼¡³R=}L]ŸÈÿ2 ÿù¶J1jj¡é,zäV|i¸Qk¹‡= 
5
5
  ¨¨Ÿ%‰€ýv²†±»ŸoúâLa:ê±ÊäÌÓ.÷؇ý×>àW>z¯°8¯ñ€\Ñós 9ˆ\§ôÊ@Ü (tÂø4° ¢7fqÓg²Jè6x[zç®&4=} p.(°tÍޖ™ã¾>÷CõË"*k?¿~ 7‚~H2ÛÜâ.ÏQä;Œ6{ÜãFÑá'DœD¤±°HQ>MínÎϕÎöʵ’Ñӓ…™Þ“‰Ž‘š†Š‚œÌP¼P¨Þˆ*X²E=M¦qíxMà ±=M̚ë4/<šgNO‰™/¢ ¢>ˆa~Ï®”ììììì0”ìœa笡çëOÓÇM Q9tùµyuéµµÞϒ/Ÿ±Óõò}E{òÓJ¹Û|· ôfÒ c’¬”Wêaûÿlʽp¹|)‘ÖEL–†¦ }‰ypÕSϹI†]¢ˆºãæ°ÿo¶7ÛRqš¾ÔÅEߨ‘]æˉwÚ{óç‰Vwó1¾”E­Øpˆàe"Æùû–¡Áª ‡ Ààð´Lõ›€ÎxEÓ¢N¦‘…9Ÿëùši&€ Ò§Ø!ÇFçS=MbäO?ß·™縪‡7ùa}5ðšûÕtsUŒþ£Kïg‡ˆN™¾)ø§\V0uSIö:ÌU4ж¯´Õn9ÔƒèE£ZƼ{hµmى¾6ÆžÑ+xñ´«„þ¸=M‚ߤ·å®«ïÆGFÝì|H?äE"þ!9«Æïpæ'][¯ù·£W÷O§&#aŸ‡x$qf=}ø ô bϗŸ×W÷LôožÝWQÕӎ)u †÷½èV|¥Gà¨Ö¸˜@Œê| ÇK5ò €A·Â9’CS2š¸‹¼¿,ä›Ý ÑÝy™!ÑR„%ÆÝÎ0Âv§ qTcó±hØÉã‰=}Z=}Ælü­ën¯ð(-°ÜwVχï.th¥í­‡S~SÏ»Z”ZÔZ
6
6
  3–BÌÛ¬•<éæO)ÎyÚ¯O*®uìÛ$öI¥Ý9ôø³\¤ò³Ù¹ÇP¸J׎y@ÔyOÇm—’ô½üœš¾|S?2àú¤F?½ûoo3ôž;<àáûܘ8‚ì²7ïë¨RäY¹|ÓºÌF,ƒÐ™-¸*\P!FJÒ8= o6HwLrúº”¶Ð۞\Ù¬o¢–9Iq„Ý.ôf¶Îȏ{Ī×N|Mfs…•¤ „ÉݖàŸâ§‘*+ã§­’ô¯î¬7ç×§ä)€Š!Z¨ƒÉž,Äp~ý·wsSGó—äs„E€\ýï鞧Ö:Ò'“Cç(_X$\¦½eҒ8$’X˜F|e‚•œíٙә‚†¡¤Û<ØÞÛ¸9‰¿ðÃÎ#b~× ‚4éîÿÏq
7
7
  ˜ód‡|0•wU‰—&®è·vh6¨—{Ú珁Ú18ә(ÓY‚\ƒ0¦= çˆèíß)Ø=} ˜[xü-v˜?N(Kk‘gš0}âډ´ð“†¬”œÕQNÍ¢usѳ=}. ëg…û= Í M—Bp'²¨ œx’4è@9t“§eݵ¾âð½ z?†‹Z¹FH'‰Ì¯¿<ŒK,üµ<{˜ ¶JãývåàÆeù0Ð"F¥ÃÒÞŽþԛÉvC›zl}„ðN’£ Í^ƒP%²¸FX»WÎêô¶…ŠäÉJ^gƒ×SÃã.žÄt*'ªG‘«ÒB<ÜӅ¿ºp­\àuV¯£›Åݑ½á–Þ ùߞ=}ÎÚ^‹Ÿÿí>¥!¨ â=M·? */¤"å)â·ÿîÿî*(%*›2[½"üríÔ4š’l½»a}¯CwpCÓèìGc-ã6®=M32†k?Êg­…–!So-™x›>³G+ã@ò,™ Áïƒá„åN0þŠÙ‚è.~È÷¡vTr¶‰­‚Æ[üB±º»ávëw¹{pÜºû"Aæ’±9Æ^¹³òïRIAy5GÂwÉfœ4@Tù|qý7†ðªwBL|ÔqŽ‘v!ª°|]KiÐJVQ5‰¸åõ§‡‡åŒ"H¼0e¬<óBîÚS€ÏUìHPÙA+çÉ'se†ÌNf°@ÈM,ð½egÖ¬x©“„‹û½2~«ŠÒ1;ֈ«…¯°4&90èE»Ó׺ç‚ʧJ<Æ¿&~Nu¼ãÙµ¢.UÇä(qQô^ö–·“%!É
@@ -138,7 +138,7 @@ KÙ:KµºKí{K]ûK£[KÚKóšKÓ½R׿ÿ'P^j9TîçmóœþL¿_o©×hÙtÙ
138
138
  ÁiŸ;ª•äÀž‡%Ёn= =M+W= ÓÖc[aS
139
139
  FÁð]Nô‡Ý'= “qr(¶ù¤nŒü«òÿ¿d&ÿ ÈõT4Þ=}z|ö ¿OW×SMtdH.τãRX&§o3ؘÜXÍ^œÊM–í£W´iâ]NüOå£S£Å·ƒç÷­˜Ý§½GÑU y¹¦ß§/6P0(Cúýb"þ¥°VٌÄᣈ’ÓÙ@¾YýòDŽŒ{òÃv?’EP©”=MBé­\ĽYäýRò øfâëEEf¼D+gC×úDZGÅÿ±Ç?TzÙ¡±†Ï€ÁÕ¯¦ð‰vZ’mT}Œ3x˘z×cºrÑM=M„ c-ɩԈ™7½wæc§Î»cû¾yf‡ÙWòŒÆÝÔc¥³ôØfƒ«Äñ·9‰ø%­g:y”^+{U]¤þ‚…[&fӁÏY낫‡Gªõ‡¹¦ÖŒðþ¬m„oÛø‘?/ÛS’.[S›9ÛùœC›…/û2”²Y£ÎÑ%/sy¢×ÌùJ­W6Oí\g0^JùêßÏ0í[Ü“'ÏÔ>žÀ-¿[ÔW?Y]±ž ØÙÃî<~ÎëR~Ìf¾Z—/×¼_á¾Þê+îoÐñ{Þ\e3K%©¹§íB¹§(c=}ËÈ·SzÔnf§èx}o\9öf|%Ýå¥~©‚Iǀ ü€ñY8}FfŸú@Rú1éþ3‚÷˂‹ótQøvœû|³Îaá,Óé>BG6Òê}—ÄJ|¶=}°Žˆöf6žõk¶ÌºHgN’j‡Ò{柾M;9·é—§WèO±›Ä3қËÒyt™ ;ù´ˆà©aš|—Ó^!ÝøûšÄ
140
140
  (VV¸ ÇÙcÏ>yoçz ÃvòG{3Þ£½šŠcמôŒ íŚé;°OÛ‰GØ<wÜW> rU]Žq­{û'ùÝír{*øï?t-ígùWÿ…&§] m}×ût¥‚Ë~ß&>&Õv!b#ÅÌ‚q¢µ|jŽÍüùÉ^Æ&™ôžþŸ~sIµ"“]d)uâ´‘ºvk Å\<͉ÿ­öꍽƒÂ
141
- ïBçϧmÙIólÜoëVbƒ¦¯éWÇû3`});var $r={a:Ge};this.setModule=k=>{t.setModule(sn,k)},this.getModule=()=>t.getModule(sn),this.instantiate=()=>(this.getModule().then(k=>WebAssembly.instantiate(k,$r)).then(k=>{let se=k.exports;me(se),m=se.l,g(),He(se),r()}),this.ready=new Promise(k=>{r=k}).then(()=>{this.HEAP=m.buffer,this.malloc=ge,this.free=qt,this.create_decoder=Me,this.send_setup=ue,this.init_dsp=ye,this.decode_packets=Ve,this.destroy_decoder=ct}),this)}function wi(){return this._init=()=>new this._WASMAudioDecoderCommon().instantiate(this._EmscriptenWASM,this._module).then(t=>{this._common=t,this._input=this._common.allocateTypedArray(this._inputSize,Uint8Array),this._firstPage=!0,this._inputLen=this._common.allocateTypedArray(1,Uint32Array),this._outputBufferPtr=this._common.allocateTypedArray(1,Uint32Array),this._channels=this._common.allocateTypedArray(1,Uint32Array),this._sampleRate=this._common.allocateTypedArray(1,Uint32Array),this._samplesDecoded=this._common.allocateTypedArray(1,Uint32Array);let e=256;this._errors=this._common.allocateTypedArray(e,Uint32Array),this._errorsLength=this._common.allocateTypedArray(1,Int32Array),this._frameNumber=0,this._inputBytes=0,this._outputSamples=0,this._decoder=this._common.wasm.create_decoder(this._input.ptr,this._inputLen.ptr,this._outputBufferPtr.ptr,this._channels.ptr,this._sampleRate.ptr,this._samplesDecoded.ptr,this._errors.ptr,this._errorsLength.ptr,e)}),Object.defineProperty(this,"ready",{enumerable:!0,get:()=>this._ready}),this.reset=()=>(this.free(),this._init()),this.free=()=>{this._common.wasm.destroy_decoder(this._decoder),this._common.free()},this.sendSetupHeader=t=>{this._input.buf.set(t),this._inputLen.buf[0]=t.length,this._common.wasm.send_setup(this._decoder,this._firstPage),this._firstPage=!1},this.initDsp=()=>{this._common.wasm.init_dsp(this._decoder)},this.decodePackets=t=>{let e=[],r=0,n=[];for(let i=0;i<t.length;i++){let a=t[i];this._input.buf.set(a),this._inputLen.buf[0]=a.length,this._common.wasm.decode_packets(this._decoder);let o=this._samplesDecoded.buf[0],s=[],c=new Uint32Array(this._common.wasm.HEAP,this._outputBufferPtr.buf[0],this._channels.buf[0]);for(let l=0;l<this._channels.buf[0];l++){let u=new Float32Array(o);o&&u.set(new Float32Array(this._common.wasm.HEAP,c[l],o)),s.push(u)}e.push(s),r+=o,this._frameNumber++,this._inputBytes+=a.length,this._outputSamples+=o;for(let l=0;l<this._errorsLength.buf;l+=2){let u=this._common.codeToString(this._errors.buf[l]),d=this._common.codeToString(this._errors.buf[l+1]);n.push({message:u+" vorbis_synthesis"+d,frameLength:a.length,frameNumber:this._frameNumber,inputBytes:this._inputBytes,outputSamples:this._outputSamples})}this._errorsLength.buf[0]=0}return this._WASMAudioDecoderCommon.getDecodedAudioMultiChannel(n,e,this._channels.buf[0],r,this._sampleRate.buf[0],16)},this._isWebWorker=wi.isWebWorker,this._WASMAudioDecoderCommon=wi.WASMAudioDecoderCommon||_e,this._EmscriptenWASM=wi.EmscriptenWASM||sn,this._module=wi.module,this._inputSize=128*1024,this._ready=this._init(),this}var $l=Symbol(),ln=class{constructor(){this._onCodec=e=>{if(e!=="vorbis")throw new Error("@wasm-audio-decoders/ogg-vorbis does not support this codec "+e)},new _e,this._init(),this._ready=this[$l](wi)}_init(){this._vorbisSetupInProgress=!0,this._totalSamplesDecoded=0,this._codecParser=new rm("audio/ogg",{onCodec:this._onCodec,enableFrameCRC32:!1})}async[$l](e){if(this._decoder){let r=this._decoder;await r.ready.then(()=>r.free())}return this._decoder=new e,this._decoder.ready}get ready(){return this._ready}async reset(){return this._init(),this._decoder.reset()}free(){this._decoder.free()}async decodeOggPages(e){let r=[];for(let a=0;a<e.length;a++){let o=e[a];if(this._vorbisSetupInProgress&&(o[Xl][0]===1&&this._decoder.sendSetupHeader(o[Xl]),o[Wl].length)){let s=o[Wl][0][nm];this._decoder.sendSetupHeader(s[am]),this._decoder.initDsp(),this._vorbisSetupInProgress=!1}r.push(...o[Wl].map(s=>s[Xl]))}let n=await this._decoder.decodePackets(r);this._totalSamplesDecoded+=n.samplesDecoded;let i=e[e.length-1];if(i&&i[im]){let a=this._totalSamplesDecoded-i[om];if(a>0){for(let o=0;o<n.channelData.length;o++)n.channelData[o]=n.channelData[o].subarray(0,n.samplesDecoded-a);n.samplesDecoded-=a,this._totalSamplesDecoded-=a}}return n}async decode(e){return this.decodeOggPages([...this._codecParser.parseChunk(e)])}async flush(){let e=await this.decodeOggPages([...this._codecParser.flush()]);return await this.reset(),e}async decodeFile(e){let r=await this.decodeOggPages([...this._codecParser.parseAll(e)]);return await this.reset(),r}};var ad=class extends Ji{constructor(e){super(e,"ogg-vorbis-decoder",wi,sn)}async sendSetupHeader(e){return this.postToDecoder("sendSetupHeader",e)}async initDsp(){return this.postToDecoder("initDsp")}async decodePackets(e){return this.postToDecoder("decodePackets",e)}},is=class extends ln{constructor(){super(),this._ready=super[$l](ad)}async free(){await this._decoder.free()}terminate(){this._decoder.terminate()}};yl(ln,"OggVorbisDecoder");yl(is,"OggVorbisDecoderWebWorker");var od=class extends Error{constructor(e){super(e),this.name="OggDecodeError"}};async function Kl(t,e=new ln){await e.ready;let r=await e.decode(new Uint8Array(t)),n=r.errors;if(n&&n.length>0)throw new od(n.map(i=>i.message).join("; "));return{sampleRate:r.sampleRate,channels:r.channelData.length,bitDepth:r.bitDepth,channelData:r.channelData}}var as=class extends Error{constructor(e){super(e),this.name="AudioRegistryError"}},ga=class{constructor(e,r={}){this.vfs=e;this.refCounts=new Map;this.nextRequestId=0;this.cache=new En(r.cacheSize??64),r.workerPath&&(this.worker=new Worker(r.workerPath,{type:"module"}))}get size(){return this.cache.size}get capacity(){return this.cache.capacity}async load(e){let r=e.toLowerCase(),n=this.cache.get(r);if(n)return this.refCounts.set(r,(this.refCounts.get(r)??0)+1),n;let a=(await this.vfs.readFile(e)).slice().buffer,o=await this.decodeByExtension(e,a);return this.cache.set(r,o),this.refCounts.set(r,1),o}release(e){let r=e.toLowerCase(),n=this.refCounts.get(r)??0;n<=1?(this.cache.delete(r),this.refCounts.delete(r)):this.refCounts.set(r,n-1)}clearAll(){this.cache.clear(),this.refCounts.clear()}set capacity(e){this.cache.capacity=e}async decodeByExtension(e,r){let n=e.toLowerCase();if(n.endsWith(".wav")){if(this.worker)return this.decodeWavInWorker(r);let i=gl(r),a=i.channels,o=Array.from({length:a},()=>new Float32Array(i.samples.length/a));for(let s=0;s<i.samples.length;s+=1)o[s%a][Math.floor(s/a)]=i.samples[s];return{sampleRate:i.sampleRate,channels:a,bitDepth:i.bitsPerSample,channelData:o}}if(n.endsWith(".ogg")||n.endsWith(".oga"))return Kl(r);throw new as(`Unsupported audio format: ${e}`)}decodeWavInWorker(e){return new Promise((r,n)=>{if(!this.worker){n(new Error("Worker not initialized"));return}let i=this.nextRequestId++,a=o=>{if(o.data.id===i)if(this.worker.removeEventListener("message",a),o.data.type==="success"){let s=o.data.data,c=s.channels,l=Array.from({length:c},()=>new Float32Array(s.samples.length/c));for(let u=0;u<s.samples.length;u+=1)l[u%c][Math.floor(u/c)]=s.samples[u];r({sampleRate:s.sampleRate,channels:c,bitDepth:s.bitsPerSample,channelData:l})}else n(new Error(o.data.message))};this.worker.addEventListener("message",a),this.worker.postMessage({id:i,buffer:e,type:"wav"},[e])})}};var x1="quake2ts-pak-indexes",v1="pak-indexes";function sm(){if(typeof indexedDB<"u")return indexedDB;if(typeof window<"u"&&"indexedDB"in window)return window.indexedDB;if(typeof globalThis<"u"&&"indexedDB"in globalThis)return globalThis.indexedDB}function os(t,e){let r=sm();return r?new Promise((n,i)=>{let a=r.open(t,1);a.onupgradeneeded=()=>{let{result:o}=a;o.objectStoreNames.contains(e)||o.createObjectStore(e,{keyPath:"key"})},a.onerror=()=>i(a.error??new Error("Unknown IndexedDB error")),a.onsuccess=()=>n(a.result)}):Promise.reject(new Error("IndexedDB is not available in this environment"))}function ss(t,e,r,n){return new Promise((i,a)=>{let s=t.transaction(e,r).objectStore(e),c=n(s);c.onsuccess=()=>i(c.result),c.onerror=()=>a(c.error??new Error("IndexedDB transaction error"))})}function sd(t,e){return`${Te(t)}:${e.toString(16)}`}function _1(t){return t.map(e=>({...e}))}var Yl=class{constructor(e=x1,r=v1){this.dbName=e;this.storeName=r}get isSupported(){return!!sm()}async persist(e){if(!this.isSupported)return;let r=e.validate(),n={...r,key:sd(e.name,r.checksum),name:e.name,size:e.size,persistedAt:Date.now(),entries:_1(r.entries)},i=await os(this.dbName,this.storeName);return await ss(i,this.storeName,"readwrite",a=>a.put(n)),i.close(),n}async find(e,r){if(!this.isSupported)return;let n=await os(this.dbName,this.storeName),i=r!==void 0?sd(e,r):void 0,a=await ss(n,this.storeName,"readonly",o=>i?o.get(i):o.getAll());if(n.close(),!!a){if(Array.isArray(a)){let o=Te(e),s=a.filter(c=>Te(c.name)===o);return s.length===0?void 0:s.sort((c,l)=>l.persistedAt-c.persistedAt)[0]}return a}}async remove(e,r){if(!this.isSupported)return!1;let n=await os(this.dbName,this.storeName),i=r!==void 0?sd(e,r):void 0,a=await ss(n,this.storeName,"readwrite",o=>{if(i)return o.delete(i);let s=`${Te(e)}:`;return o.delete(IDBKeyRange.bound(s,`${s}\uFFFF`,!1,!0))});return n.close(),typeof a=="number"?a>0:!0}async clear(){if(!this.isSupported)return;let e=await os(this.dbName,this.storeName);await ss(e,this.storeName,"readwrite",r=>r.clear()),e.close()}async list(){if(!this.isSupported)return[];let e=await os(this.dbName,this.storeName),r=await ss(e,this.storeName,"readonly",n=>n.getAll());return e.close(),r.sort((n,i)=>i.persistedAt-n.persistedAt)}};var Mi=class extends Error{constructor(r,n){super(n??`Missing dependencies: ${r.join(", ")}`);this.missing=r;this.name="AssetDependencyError"}},ls=class{constructor(){this.nodes=new Map}register(e,r=[]){let n=this.nodes.get(e)??{dependencies:new Set,loaded:!1};r.forEach(i=>n.dependencies.add(i)),this.nodes.set(e,n),r.forEach(i=>{this.nodes.has(i)||this.nodes.set(i,{dependencies:new Set,loaded:!1})})}markLoaded(e){let r=this.nodes.get(e)??{dependencies:new Set,loaded:!1},n=this.getMissingDependencies(e,r);if(n.length>0)throw new Mi(n,`Asset ${e} is missing dependencies: ${n.join(", ")}`);r.loaded=!0,this.nodes.set(e,r)}markUnloaded(e){let r=this.nodes.get(e);r&&(r.loaded=!1)}isLoaded(e){return this.nodes.get(e)?.loaded??!1}missingDependencies(e){let r=this.nodes.get(e);return r?this.getMissingDependencies(e,r):[]}reset(){this.nodes.clear()}getMissingDependencies(e,r){let n=[];for(let i of r.dependencies)this.nodes.get(i)?.loaded||n.push(i);return n}},ql=class{constructor(e,r={}){this.vfs=e;this.maps=new Map;this.loadQueue=[];this.activeLoads=0;this.textures=new Qi({capacity:r.textureCacheCapacity??128,maxMemory:r.textureMemoryLimit}),this.audio=new ga(e,{cacheSize:r.audioCacheSize??64,workerPath:r.audioWorkerPath}),this.dependencyTracker=r.dependencyTracker??new ls,this.resourceTracker=r.resourceTracker,this.md2=new qi(e),this.md3=new Zi(e),this.sprite=new ji(e),this.bsp=new Yi(e,{useWorker:!!r.bspWorkerPath,workerPath:r.bspWorkerPath}),this.maxConcurrentLoads=r.maxConcurrentLoads??4,this.palette=new Uint8Array(768);for(let n=0;n<256;n++)this.palette[n*3]=n,this.palette[n*3+1]=n,this.palette[n*3+2]=n}async loadPalette(e="pics/colormap.pcx"){try{let r=await this.vfs.readFile(e),n=ho(r);n.palette&&(this.palette=n.palette)}catch(r){console.warn(`Failed to load palette from ${e}:`,r)}}isAssetLoaded(e,r){return this.dependencyTracker.isLoaded(this.makeKey(e,r))}registerTexture(e,r){this.textures.set(e,r);let n=this.makeKey("texture",e);this.dependencyTracker.register(n),this.dependencyTracker.markLoaded(n)}async loadTexture(e){if(this.resourceTracker){let o=this.vfs.stat(e);this.resourceTracker.recordLoad("texture",e,o?.size,o?.sourcePak)}let r=this.textures.get(e);if(r)return r;let n=await this.vfs.readFile(e),i=e.split(".").pop()?.toLowerCase(),a;if(i==="wal")a=pl(n,this.palette);else if(i==="pcx")a=ml(ho(n));else if(i==="tga")a=Ch(Ou(n));else throw new Error(`Unsupported texture format for loadTexture: ${i}`);return this.registerTexture(e,a),a}async loadSound(e){if(this.resourceTracker){let i=this.vfs.stat(e);this.resourceTracker.recordLoad("sound",e,i?.size,i?.sourcePak)}let r=await this.audio.load(e),n=this.makeKey("sound",e);return this.dependencyTracker.register(n),this.dependencyTracker.markLoaded(n),r}async loadMd2Model(e,r=[]){if(this.resourceTracker){let s=this.vfs.stat(e);this.resourceTracker.recordLoad("model",e,s?.size,s?.sourcePak)}let n=this.makeKey("model",e),i=r.map(s=>this.makeKey("texture",s));this.dependencyTracker.register(n,i);let a=this.dependencyTracker.missingDependencies(n);if(a.length>0)throw new Mi(a,`Asset ${n} is missing dependencies: ${a.join(", ")}`);let o=await this.md2.load(e);return this.dependencyTracker.markLoaded(n),o}getMd2Model(e){if(this.resourceTracker){let r=this.vfs.stat(e);this.resourceTracker.recordLoad("model",e,r?.size,r?.sourcePak)}return this.md2.get(e)}async loadMd3Model(e,r=[]){if(this.resourceTracker){let s=this.vfs.stat(e);this.resourceTracker.recordLoad("model",e,s?.size,s?.sourcePak)}let n=this.makeKey("model",e),i=r.map(s=>this.makeKey("texture",s));this.dependencyTracker.register(n,i);let a=this.dependencyTracker.missingDependencies(n);if(a.length>0)throw new Mi(a,`Asset ${n} is missing dependencies: ${a.join(", ")}`);let o=await this.md3.load(e);return this.dependencyTracker.markLoaded(n),o}getMd3Model(e){if(this.resourceTracker){let r=this.vfs.stat(e);this.resourceTracker.recordLoad("model",e,r?.size,r?.sourcePak)}return this.md3.get(e)}async loadSprite(e){if(this.resourceTracker){let i=this.vfs.stat(e);this.resourceTracker.recordLoad("sprite",e,i?.size,i?.sourcePak)}let r=this.makeKey("sprite",e);this.dependencyTracker.register(r);let n=await this.sprite.load(e);return this.dependencyTracker.markLoaded(r),n}async loadMap(e){if(this.resourceTracker){let i=this.vfs.stat(e);this.resourceTracker.recordLoad("map",e,i?.size,i?.sourcePak)}let r=this.makeKey("map",e);if(this.maps.has(e))return this.maps.get(e);this.dependencyTracker.register(r);let n=await this.bsp.load(e);return this.maps.set(e,n),this.dependencyTracker.markLoaded(r),n}getMap(e){return this.maps.get(e)}listFiles(e){return this.vfs.findByExtension(e)}resetForLevelChange(){this.textures.clear(),this.audio.clearAll(),this.dependencyTracker.reset(),this.maps.clear(),this.loadQueue.length=0}getMemoryUsage(){let e=0,r=0;if(typeof process<"u"&&process.memoryUsage){let n=process.memoryUsage();e=n.heapTotal,r=n.heapUsed}return{textures:this.textures.memoryUsage,audio:this.audio.size,heapTotal:e,heapUsed:r}}enforceMemoryBudget(e){e.textureMemoryLimit!==void 0&&(this.textures.maxMemory=e.textureMemoryLimit),e.textureCacheCapacity!==void 0&&(this.textures.capacity=e.textureCacheCapacity),e.audioCacheSize!==void 0&&(this.audio.capacity=e.audioCacheSize)}clearCache(e){switch(e){case"texture":this.textures.clear();break;case"sound":this.audio.clearAll();break;case"map":this.maps.clear();break}}async preloadAssets(e){let r=e.map(n=>{let i=this.detectAssetType(n);return i?this.queueLoad(n,i,0):Promise.resolve()});await Promise.all(r)}queueLoad(e,r,n=1){return r==="texture"&&this.textures.get(e)?Promise.resolve(this.textures.get(e)):new Promise((i,a)=>{this.loadQueue.push({path:e,type:r,priority:n,resolve:i,reject:a}),this.loadQueue.sort((o,s)=>s.priority-o.priority),this.processQueue()})}async processQueue(){if(this.activeLoads>=this.maxConcurrentLoads||this.loadQueue.length===0)return;let e=this.loadQueue.shift();this.activeLoads++;try{let r;switch(e.type){case"texture":r=await this.loadTexture(e.path);break;case"sound":r=await this.loadSound(e.path);break;case"model":e.path.endsWith(".md2")?r=await this.loadMd2Model(e.path):e.path.endsWith(".md3")&&(r=await this.loadMd3Model(e.path));break;case"sprite":r=await this.loadSprite(e.path);break;case"map":r=await this.loadMap(e.path);break;default:throw new Error(`Unknown asset type ${e.type}`)}e.resolve(r)}catch(r){e.reject(r)}finally{this.activeLoads--,this.processQueue()}}detectAssetType(e){let r=e.split(".").pop()?.toLowerCase();return r?["wal","pcx","tga","png","jpg"].includes(r)?"texture":["wav","ogg"].includes(r)?"sound":["md2","md3"].includes(r)?"model":["sp2"].includes(r)?"sprite":["bsp"].includes(r)?"map":null:null}makeKey(e,r){return`${e}:${Te(r)}`}};var Zl=class{constructor(e){this.factory=e}getContext(){return this.context||(this.context=this.factory()),this.context}async resume(){let e=this.getContext();e.state==="suspended"&&await e.resume()}getState(){return this.context?.state??"suspended"}};function jl(t){let e=t.getContext(),r=e.createGain();r.gain.value=1;let n=e.createDynamicsCompressor(),i=e.createBiquadFilter?.(),a;if(e.createConvolver&&e.createGain){let o=e.createConvolver(),s=e.createGain(),c=e.createGain();s.connect(o),o.connect(c),a={convolver:o,input:s,output:c}}return i?(i.type="lowpass",i.frequency.value=2e4,i.Q.value=.707,r.connect(i),i.connect(n),a&&a.output.connect(i)):(r.connect(n),a&&a.output.connect(n)),n.connect(e.destination),{context:e,master:r,compressor:n,filter:i,reverb:a}}var Ql=class{constructor(e=new $i){this.configStrings=e;this.buffers=new Map}registerName(e){return this.configStrings.soundIndex(e)}register(e,r){let n=this.registerName(e);return this.buffers.set(n,r),n}find(e){return this.configStrings.findSoundIndex(e)}get(e){return this.buffers.get(e)}has(e){return this.buffers.has(e)}getName(e){return this.configStrings.getName(e)}};var Jl=class{constructor(e){this.vfs=e.vfs,this.registry=e.registry,this.contextController=e.context,this.soundRoot=e.soundRoot??"sound/",this.decodeAudio=e.decodeAudio??((r,n)=>{if(!r.decodeAudioData)throw new Error("decodeAudioData is not available on the provided audio context");return r.decodeAudioData(n)})}async precache(e){let r=[...new Set(e.map(a=>this.normalize(a)))],n={loaded:[],skipped:[],missing:[],errors:{}},i=this.contextController.getContext();for(let a of r)try{let o=this.registry.find(a);if(o!==void 0&&this.registry.has(o)){n.skipped.push(a);continue}if(!this.vfs.stat(a)){n.missing.push(a);continue}let l=(await this.vfs.readFile(a)).slice().buffer,u=await this.decodeAudio(i,l);this.registry.register(a,u),n.loaded.push(a)}catch(o){let s=o instanceof Error?o:new Error(String(o));n.errors[a]=s}return n}normalize(e){let r=Te(e.replace(/^\//,""));return r.startsWith(this.soundRoot)?r:Te(`${this.soundRoot}${r}`)}};var S1=7,cs=t=>t&S1;function ec(t){return Array.from({length:io},()=>({entnum:0,entchannel:Cr.Auto,endTimeMs:0,isPlayer:!1,active:!1})).map(e=>({...e,isPlayer:e.entnum===t}))}function tc(t,e,r,n){if(r<0)throw new Error("pickChannel: entchannel must be non-negative");let i=cs(r),a=-1,o=Number.POSITIVE_INFINITY;for(let s=0;s<t.length;s+=1){let c=t[s],l=cs(c.entchannel);if(i!==Cr.Auto&&c.entnum===e&&l===i){a=s;break}if(c.active&&c.entnum===n.playerEntity&&e!==n.playerEntity)continue;let u=c.endTimeMs-n.nowMs;(a===-1||u<o)&&(o=u,a=s)}return a===-1?void 0:a}var rc=class{constructor(e){this.activePreset=null;this.enabled=!0;this.node=e,this.node.input.gain.value=.5,this.node.output.gain.value=1}setPreset(e){this.activePreset=e,this.node.convolver.buffer!==(e?.buffer??null)&&(this.node.convolver.buffer=e?.buffer??null),e&&e.gain!==void 0?this.node.output.gain.value=e.gain:this.node.output.gain.value=1}setEnabled(e){this.enabled=e,e?this.node.input.gain.value=.5:this.node.input.gain.value=0}getOutputNode(){return this.node.output}getInputNode(){return this.node.input}};var nc=class{constructor(e){this.activeSources=new Map;this.playbackRate=1;this.contextController=e.context,this.registry=e.registry,this.playerEntity=e.playerEntity,this.channels=ec(e.playerEntity),this.listener=e.listener??{origin:qf,right:{x:1,y:0,z:0}},this.sfxVolume=e.sfxVolume??1,this.masterVolume=e.masterVolume??1,this.resolveOcclusion=e.resolveOcclusion,this.graph=jl(this.contextController),this.graph.master.gain.value=this.masterVolume,this.graph.reverb&&(this.reverb=new rc(this.graph.reverb))}setListener(e){this.listener=e}setMasterVolume(e){this.masterVolume=e,this.graph.master.gain.value=e}setSfxVolume(e){this.sfxVolume=e}setPlaybackRate(e){this.playbackRate=e;for(let r of this.activeSources.values())r.source.playbackRate&&(r.source.playbackRate.value=e),this.updateSourceGain(r)}async ensureRunning(){await this.contextController.resume()}setReverbPreset(e){this.reverb?.setPreset(e)}play(e){let r=this.registry.get(e.soundIndex);if(!r)return;let n=this.graph.context,i=n.currentTime*1e3,a=tc(this.channels,e.entity,e.channel,{nowMs:i,playerEntity:this.playerEntity});if(a===void 0)return;let o=this.activeSources.get(a);o&&(o.source.onended=null,o.source.stop(),this.activeSources.delete(a));let s=n.createBufferSource();s.buffer=r,s.loop=e.looping??!1,s.playbackRate&&(s.playbackRate.value=this.playbackRate);let c=e.origin??this.listener.origin,l=n.createGain(),u=this.createPanner(n,e.attenuation),d=this.resolveOcclusion?.(this.listener,c,e.attenuation),f=lm(d?.gainScale??1),h=this.resolveOcclusion?this.createOcclusionFilter(n,d?.lowpassHz??2e4):void 0;this.applyOriginToPanner(u,c);let g=e.volume/255*this.sfxVolume,p=Math.abs(this.playbackRate-1)<.001?1:0;l.gain.value=g*f*p;let y=n.currentTime+(e.timeOffsetMs??0)/1e3,v=(e.looping?Number.POSITIVE_INFINITY:r.duration*1e3)+y*1e3;s.connect(u);let b=u;h?(u.connect(h),h.connect(l),b=l):(u.connect(l),b=l),l.connect(this.graph.master),this.reverb&&l.connect(this.reverb.getInputNode()),s.start(y),s.onended=()=>{this.channels[a].active=!1,this.activeSources.delete(a)};let x={channelIndex:a,entnum:e.entity,entchannel:cs(e.channel),endTimeMs:v,source:s,panner:u,gain:l,baseGain:g,origin:c,attenuation:e.attenuation,occlusion:h?{scale:f,lowpassHz:d?.lowpassHz,filter:h}:d?{scale:f,lowpassHz:d.lowpassHz}:void 0};return this.channels[a]={entnum:e.entity,entchannel:cs(e.channel),endTimeMs:v,isPlayer:e.entity===this.playerEntity,active:!0},this.activeSources.set(a,x),x}stop(e){let r=this.activeSources.get(e);r&&(r.source.stop(),this.channels[e].active=!1,this.activeSources.delete(e))}stopEntitySounds(e){for(let[r,n]of[...this.activeSources.entries()])n.entnum===e&&(n.source.stop(),this.channels[r].active=!1,this.activeSources.delete(r))}updateEntityPosition(e,r){for(let n of this.activeSources.values())if(n.entnum===e&&(this.applyOriginToPanner(n.panner,r),n.origin=r,this.resolveOcclusion)){let i=this.resolveOcclusion(this.listener,r,n.attenuation);this.applyOcclusion(n,i)}}positionedSound(e,r,n,i){return this.play({entity:0,channel:Cr.Auto,soundIndex:r,volume:n,attenuation:i,origin:e})}ambientSound(e,r,n){return this.play({entity:0,channel:Cr.Auto,soundIndex:r,volume:n,attenuation:ao,origin:e,looping:!0})}getChannelState(e){return this.channels[e]}getDiagnostics(){return{activeChannels:this.activeSources.size,masterVolume:this.masterVolume,sfxVolume:this.sfxVolume,channels:[...this.channels],activeSounds:[...this.activeSources.values()].map(e=>({entnum:e.entnum,entchannel:e.entchannel,channelIndex:e.channelIndex,origin:e.origin,gain:e.gain.gain.value,baseGain:e.baseGain,attenuation:e.attenuation,maxDistance:e.panner.maxDistance,distanceModel:e.panner.distanceModel,occlusion:e.occlusion?{scale:e.occlusion.scale,lowpassHz:e.occlusion.lowpassHz}:void 0}))}}setUnderwater(e,r=400){let n=this.graph.filter;n&&(n.type="lowpass",n.Q.value=.707,n.frequency.value=e?r:2e4)}createPanner(e,r){let n=e.createPanner?e.createPanner():Object.assign(e.createGain(),{positionX:{value:this.listener.origin.x},positionY:{value:this.listener.origin.y},positionZ:{value:this.listener.origin.z}});return this.configurePanner(n,r)}configurePanner(e,r){let n=Vi(r);return e.refDistance=Gi,e.maxDistance=si(r),e.rolloffFactor=n,e.distanceModel="linear",e.positionX.value=this.listener.origin.x,e.positionY.value=this.listener.origin.y,e.positionZ.value=this.listener.origin.z,e}applyOriginToPanner(e,r){e.positionX.value=r.x,e.positionY.value=r.y,e.positionZ.value=r.z}createOcclusionFilter(e,r){if(!e.createBiquadFilter)return;let n=e.createBiquadFilter();return n.type="lowpass",n.Q.value=.707,n.frequency.value=ld(r,10,2e4),n}updateSourceGain(e){let r=e.occlusion?.scale??1,n=Math.abs(this.playbackRate-1)<.001?1:0;e.gain.gain.value=e.baseGain*r*n}applyOcclusion(e,r){let n=lm(r?.gainScale??1),i=Math.abs(this.playbackRate-1)<.001?1:0;if(e.gain.gain.value=e.baseGain*n*i,e.occlusion?.filter){let a=r?.lowpassHz??2e4;e.occlusion.filter.frequency.value=ld(a,10,2e4)}e.occlusion?(e.occlusion.scale=n,e.occlusion.lowpassHz=r?.lowpassHz):r&&(e.occlusion={scale:n,lowpassHz:r.lowpassHz})}},ld=(t,e,r)=>Math.min(r,Math.max(e,t)),lm=t=>ld(t,0,1);var us=class{constructor(e){this.trace=e;this.resolve=(e,r,n)=>{let i=mu(Zf(r,e.origin)),a=si(n),c=2e4*(1-Math.min(i,a)/Math.max(1,a)*.9),l=this.trace(e.origin,r,void 0,void 0),u=1,d=2e4;l.fraction<1&&(u=.3,d=400);let f=Math.min(c,d);if(u<1||f<2e4)return{gainScale:u,lowpassHz:f}}}};function cm(t){return new us(t).resolve}var ic=class{constructor(e){this.createElement=e.createElement,this.resolveSource=e.resolveSource??(async r=>r),this.volume=e.volume??1,this.crossfadeDuration=e.crossfadeDuration??1}async playTrack(e){let r=`music/track${e.toString().padStart(2,"0")}.ogg`;return this.play(r)}async play(e,{loop:r=!0,restart:n=!1}={}){if(this.track===e&&this.currentElement){this.currentElement.loop=r,this.cancelFade(),this.fadingElement&&(this.fadingElement.pause(),this.fadingElement=void 0),this.currentElement.volume=this.volume,n&&(this.currentElement.currentTime=0),(this.currentElement.paused||n)&&await this.currentElement.play();return}let i=await this.resolveSource(e);this.cancelFade(),this.fadingElement&&(this.fadingElement.pause(),this.fadingElement=void 0),this.currentElement&&(this.fadingElement=this.currentElement,this.currentElement=void 0);let a=this.createElement();a.src=i,a.loop=r,a.volume=0,a.currentTime=0,a.load();try{await a.play()}catch(o){console.warn(`MusicSystem: Failed to play ${e}`,o),this.fadingElement}this.currentElement=a,this.track=e,this.startCrossfade()}pause(){this.cancelFade(),this.currentElement&&!this.currentElement.paused&&this.currentElement.pause(),this.fadingElement&&(this.fadingElement.pause(),this.fadingElement=void 0)}async resume(){!this.currentElement||!this.currentElement.paused||(await this.currentElement.play(),this.currentElement.volume=this.volume)}stop(){this.cancelFade(),this.currentElement&&(this.currentElement.pause(),this.currentElement.currentTime=0,this.currentElement=void 0),this.fadingElement&&(this.fadingElement.pause(),this.fadingElement=void 0),this.track=void 0}setVolume(e){this.volume=e,this.currentElement&&!this.fadeInterval&&(this.currentElement.volume=e)}getState(){let e=!!(this.currentElement&&!this.currentElement.paused&&!this.currentElement.ended),r=!!this.currentElement?.paused;return{track:this.track,paused:r,playing:e,volume:this.volume}}startCrossfade(){let r=this.crossfadeDuration*1e3/50,n=this.volume/r,i=0,a=this.fadingElement?this.fadingElement.volume:0,o=()=>{let s=!1;this.currentElement&&(i=Math.min(this.volume,i+n),this.currentElement.volume=i,i<this.volume&&(s=!0)),this.fadingElement&&(a=Math.max(0,a-n),this.fadingElement.volume=a,a>0?s=!0:(this.fadingElement.pause(),this.fadingElement=void 0)),s||this.cancelFade()};o(),(this.currentElement&&this.currentElement.volume<this.volume||this.fadingElement)&&(this.fadeInterval=setInterval(o,50))}cancelFade(){this.fadeInterval&&(clearInterval(this.fadeInterval),this.fadeInterval=void 0)}};function w1(t){t.enable(t.DEPTH_TEST),t.depthFunc(t.LEQUAL),t.enable(t.CULL_FACE),t.cullFace(t.BACK),t.enable(t.BLEND),t.blendFuncSeparate(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA,t.ONE,t.ONE_MINUS_SRC_ALPHA)}function M1(t,e,r,n){for(let i of e){let a=t.getExtension(i);if(!a)throw new Error(`Missing required WebGL extension: ${i}`);n.set(i,a)}for(let i of r){let a=t.getExtension(i);a&&n.set(i,a)}}function um(t,e={}){let{contextAttributes:r,requiredExtensions:n=[],optionalExtensions:i=[]}=e,a=t.getContext("webgl2",r??{antialias:!0});if(!a)throw new Error("WebGL2 not supported or failed to initialize");w1(a);let o=new Map;M1(a,n,i,o);let s=!1,c=new Set,l=new Set,u=f=>{s=!0,f.preventDefault();for(let h of c)h()},d=()=>{s=!1;for(let f of l)f()};return t.addEventListener("webglcontextlost",u),t.addEventListener("webglcontextrestored",d),{gl:a,extensions:o,isLost:()=>s,onLost(f){return c.add(f),()=>c.delete(f)},onRestored(f){return l.add(f),()=>l.delete(f)},dispose(){t.removeEventListener("webglcontextlost",u),t.removeEventListener("webglcontextrestored",d),c.clear(),l.clear(),o.clear()}}}function dm(t,e,r){let n=t.createShader(e);if(!n)throw new Error("Failed to allocate shader");if(t.shaderSource(n,r.trim()),t.compileShader(n),!t.getShaderParameter(n,t.COMPILE_STATUS)){let a=t.getShaderInfoLog(n)??"Unknown shader compile failure";throw t.deleteShader(n),new Error(a)}return n}function A1(t,e,r,n){let i=t.createProgram();if(!i)throw new Error("Failed to allocate shader program");if(t.attachShader(i,e),t.attachShader(i,r),n)for(let[o,s]of Object.entries(n))t.bindAttribLocation(i,s,o);if(t.linkProgram(i),!t.getProgramParameter(i,t.LINK_STATUS)){let o=t.getProgramInfoLog(i)??"Unknown shader link failure";throw t.deleteProgram(i),new Error(o)}return i}var ce=class t{constructor(e,r,n){this.uniformLocations=new Map;this.attributeLocations=new Map;this.gl=e,this.program=r,this.sourceSize=n}static create(e,r,n){let i=dm(e,e.VERTEX_SHADER,r.vertex),a=dm(e,e.FRAGMENT_SHADER,r.fragment);try{let o=A1(e,i,a,n),s=r.vertex.length+r.fragment.length;return new t(e,o,s)}finally{e.deleteShader(i),e.deleteShader(a)}}use(){this.gl.useProgram(this.program)}getUniformLocation(e){if(!this.uniformLocations.has(e)){let r=this.gl.getUniformLocation(this.program,e);this.uniformLocations.set(e,r)}return this.uniformLocations.get(e)??null}getAttributeLocation(e){if(!this.attributeLocations.has(e)){let r=this.gl.getAttribLocation(this.program,e);this.attributeLocations.set(e,r)}return this.attributeLocations.get(e)??-1}dispose(){this.gl.deleteProgram(this.program),this.uniformLocations.clear(),this.attributeLocations.clear()}};function fm(t,e,r){return ce.create(t,e,r)}var Ce=class{constructor(e,r=e.STATIC_DRAW,n){this.gl=e,this.target=n??e.ARRAY_BUFFER;let i=e.createBuffer();if(!i)throw new Error("Failed to allocate buffer");this.buffer=i,e.bindBuffer(this.target,this.buffer),e.bufferData(this.target,0,r)}bind(){this.gl.bindBuffer(this.target,this.buffer)}upload(e,r=this.gl.STATIC_DRAW){this.bind(),this.gl.bufferData(this.target,e,r)}update(e,r=0){this.bind(),this.gl.bufferSubData(this.target,r,e)}dispose(){this.gl.deleteBuffer(this.buffer)}},st=class extends Ce{constructor(e,r=e.STATIC_DRAW){super(e,r,e.ELEMENT_ARRAY_BUFFER)}},Be=class{constructor(e){this.gl=e;let r=e.createVertexArray();if(!r)throw new Error("Failed to allocate vertex array object");this.vao=r}bind(){this.gl.bindVertexArray(this.vao)}configureAttributes(e,r){this.bind(),r&&r.bind();for(let n of e)this.gl.enableVertexAttribArray(n.index),this.gl.vertexAttribPointer(n.index,n.size,n.type,n.normalized??!1,n.stride??0,n.offset??0),n.divisor!==void 0&&this.gl.vertexAttribDivisor(n.index,n.divisor)}dispose(){this.gl.deleteVertexArray(this.vao)}},lt=class{constructor(e,r=e.TEXTURE_2D){this.width=0;this.height=0;this.gl=e,this.target=r;let n=e.createTexture();if(!n)throw new Error("Failed to allocate texture");this.texture=n}bind(e=0){this.gl.activeTexture(this.gl.TEXTURE0+e),this.gl.bindTexture(this.target,this.texture)}setParameters(e){this.bind(),e.wrapS!==void 0&&this.gl.texParameteri(this.target,this.gl.TEXTURE_WRAP_S,e.wrapS),e.wrapT!==void 0&&this.gl.texParameteri(this.target,this.gl.TEXTURE_WRAP_T,e.wrapT),e.minFilter!==void 0&&this.gl.texParameteri(this.target,this.gl.TEXTURE_MIN_FILTER,e.minFilter),e.magFilter!==void 0&&this.gl.texParameteri(this.target,this.gl.TEXTURE_MAG_FILTER,e.magFilter)}upload(e,r,n){this.width=e,this.height=r,this.uploadImage(0,this.gl.RGBA,e,r,0,this.gl.RGBA,this.gl.UNSIGNED_BYTE,n)}uploadImage(e,r,n,i,a,o,s,c){this.bind(),this.gl.texImage2D(this.target,e,r,n,i,a,o,s,c)}dispose(){this.gl.deleteTexture(this.texture)}},ya=class{constructor(e){this.gl=e,this.target=e.TEXTURE_CUBE_MAP;let r=e.createTexture();if(!r)throw new Error("Failed to allocate cubemap texture");this.texture=r}bind(e=0){this.gl.activeTexture(this.gl.TEXTURE0+e),this.gl.bindTexture(this.target,this.texture)}setParameters(e){this.bind(),e.wrapS!==void 0&&this.gl.texParameteri(this.target,this.gl.TEXTURE_WRAP_S,e.wrapS),e.wrapT!==void 0&&this.gl.texParameteri(this.target,this.gl.TEXTURE_WRAP_T,e.wrapT),e.minFilter!==void 0&&this.gl.texParameteri(this.target,this.gl.TEXTURE_MIN_FILTER,e.minFilter),e.magFilter!==void 0&&this.gl.texParameteri(this.target,this.gl.TEXTURE_MAG_FILTER,e.magFilter)}uploadFace(e,r,n,i,a,o,s,c,l){this.bind(),this.gl.texImage2D(e,r,n,i,a,o,s,c,l)}dispose(){this.gl.deleteTexture(this.texture)}},Ai=class{constructor(e){this.gl=e;let r=e.createFramebuffer();if(!r)throw new Error("Failed to allocate framebuffer");this.framebuffer=r}bind(e=this.gl.FRAMEBUFFER){this.gl.bindFramebuffer(e,this.framebuffer)}attachTexture2D(e,r,n=0){this.bind(),this.gl.framebufferTexture2D(this.gl.FRAMEBUFFER,e,r.target,r.texture,n)}dispose(){this.gl.deleteFramebuffer(this.framebuffer)}};var ud=4,cd=7*ud,dd=[{index:0,size:3,type:5126,stride:cd,offset:0},{index:1,size:2,type:5126,stride:cd,offset:3*ud},{index:2,size:2,type:5126,stride:cd,offset:5*ud}];function E1(t,e){return{width:t,height:t,padding:e,data:new Uint8Array(t*t*4),cursorX:0,cursorY:0,rowHeight:0}}function T1(t){let e=t.width*t.height;if(e===0)throw new Error("Invalid lightmap with zero area");let r=t.samples.byteLength/e;if(!Number.isInteger(r)||r<3||r>4)throw new Error("Unsupported lightmap channel count");return r}function L1(t,e,r){let n=T1(r),i=t.width*4,a=e.x+t.padding,o=e.y+t.padding,s=0;for(let c=0;c<r.height;c++){let l=(o+c)*i+a*4;for(let u=0;u<r.width;u++){let d=l+u*4;t.data[d]=r.samples[s],t.data[d+1]=r.samples[s+1],t.data[d+2]=r.samples[s+2],t.data[d+3]=n===4?r.samples[s+3]:255,s+=n}}}function P1(t,e,r){let n=e.width+r.lightmapPadding*2,i=e.height+r.lightmapPadding*2;if(n>r.atlasSize||i>r.atlasSize)throw new Error("Lightmap too large for atlas");for(let s of t){if(s.cursorX+n>s.width&&(s.cursorX=0,s.cursorY+=s.rowHeight+r.lightmapPadding,s.rowHeight=0),s.cursorY+i>s.height)continue;let c={atlasIndex:t.indexOf(s),x:s.cursorX,y:s.cursorY,width:e.width,height:e.height};return s.cursorX+=n+r.lightmapPadding,s.rowHeight=Math.max(s.rowHeight,i),{placement:c,atlas:s}}let a=E1(r.atlasSize,r.lightmapPadding);t.push(a);let o={atlasIndex:t.length-1,x:0,y:0,width:e.width,height:e.height};return a.cursorX=n+r.lightmapPadding,a.rowHeight=i,{placement:o,atlas:a}}function ac(t){return t instanceof Float32Array?t:new Float32Array(t)}function R1(t,e){if(!t){let n=new Uint16Array(e);for(let i=0;i<e;i++)n[i]=i;return n}return t instanceof Uint16Array?t:new Uint16Array(t)}function C1(t,e){let r=new Float32Array(t.length);for(let n=0;n<t.length;n+=2)r[n]=e.offset[0]+t[n]*e.scale[0],r[n+1]=e.offset[1]+t[n+1]*e.scale[1];return r}function B1(t,e){let r=ac(t.vertices),n=ac(t.textureCoords),i=e?C1(ac(t.lightmapCoords??t.textureCoords),e):ac(t.lightmapCoords??new Float32Array(n.length)),a=r.length/3;if(n.length/2!==a)throw new Error("Texture coordinates count mismatch");if(i.length/2!==a)throw new Error("Lightmap coordinates count mismatch");let o=new Float32Array(a*7);for(let s=0;s<a;s++){let c=s*3,l=s*2,u=s*7;o[u]=r[c],o[u+1]=r[c+1],o[u+2]=r[c+2],o[u+3]=n[l],o[u+4]=n[l+1],o[u+5]=i[l],o[u+6]=i[l+1]}return o}function oc(t){let e=[];for(let r=0;r<t.faces.length;r++){let n=t.faces[r];if(n.texInfo<0)continue;let i=t.texInfo[n.texInfo],a=[],o=[],s=[];for(let f=0;f<n.numEdges;f++){let h=t.surfEdges[n.firstEdge+f],m=t.edges[Math.abs(h)],g=h>=0?m.vertices[0]:m.vertices[1],p=t.vertices[g];a.push(p[0],p[1],p[2]);let y=p[0]*i.s[0]+p[1]*i.s[1]+p[2]*i.s[2]+i.sOffset,v=p[0]*i.t[0]+p[1]*i.t[1]+p[2]*i.t[2]+i.tOffset;o.push(y,v),s.push(y,v)}let c=[],l=a.length/3;for(let f=1;f<l-1;f++)c.push(0,f,f+1);let u,d=t.lightMapInfo[r];if(d){let f=1/0,h=-1/0,m=1/0,g=-1/0;for(let _=0;_<o.length;_+=2){let w=o[_],S=o[_+1];w<f&&(f=w),w>h&&(h=w),S<m&&(m=S),S>g&&(g=S)}let p=Math.floor(f/16),y=Math.floor(m/16),v=Math.ceil(h/16)-p+1,b=Math.ceil(g/16)-y+1,x=ul(n,t.lightMaps,d);if(x&&x.length===v*b*3){u={width:v,height:b,samples:x};for(let _=0;_<s.length;_+=2)s[_]=o[_]/16-p+.5,s[_+1]=o[_+1]/16-y+.5}}e.push({vertices:new Float32Array(a),textureCoords:new Float32Array(o),lightmapCoords:new Float32Array(s),indices:new Uint16Array(c),texture:i.texture,surfaceFlags:i.flags,lightmap:u,faceIndex:r})}return e}function sc(t,e,r,n={}){let i=e;if(r&&n.hiddenClassnames&&n.hiddenClassnames.size>0){let u=new Set;for(let d of r.entities.entities)if(d.classname&&n.hiddenClassnames.has(d.classname)){let f=d.properties.model;if(f&&f.startsWith("*")){let h=parseInt(f.substring(1),10);if(!isNaN(h)&&h>=0&&h<r.models.length){let m=r.models[h];for(let g=0;g<m.numFaces;g++)u.add(m.firstFace+g)}}}u.size>0&&(i=e.filter(d=>!u.has(d.faceIndex)))}let a={atlasSize:n.atlasSize??1024,lightmapPadding:n.lightmapPadding??1,hiddenClassnames:n.hiddenClassnames??new Set},o=[],s=new Map;i.forEach((u,d)=>{if(!u.lightmap)return;let{placement:f,atlas:h}=P1(o,u.lightmap,a);L1(h,f,u.lightmap),s.set(d,{atlasIndex:f.atlasIndex,offset:[(f.x+a.lightmapPadding)/a.atlasSize,(f.y+a.lightmapPadding)/a.atlasSize],scale:[f.width/a.atlasSize,f.height/a.atlasSize]})});let c=o.map(u=>{let d=new lt(t);return d.setParameters({wrapS:t.CLAMP_TO_EDGE,wrapT:t.CLAMP_TO_EDGE,minFilter:t.LINEAR,magFilter:t.LINEAR}),d.uploadImage(0,t.RGBA,u.width,u.height,0,t.RGBA,t.UNSIGNED_BYTE,u.data),{texture:d,width:u.width,height:u.height,pixels:u.data}});return{surfaces:i.map((u,d)=>{let f=s.get(d),h=B1(u,f),m=R1(u.indices,h.length/7),g=new Ce(t,t.STATIC_DRAW,t.ARRAY_BUFFER);g.upload(h);let p=new st(t,t.STATIC_DRAW);p.upload(m);let y=new Be(t);return y.configureAttributes(dd,g),{vao:y,vertexBuffer:g,indexBuffer:p,indexCount:m.length,vertexCount:h.length/7,texture:u.texture,surfaceFlags:u.surfaceFlags??yn,lightmap:f,vertexData:h,indexData:m}}),lightmaps:c}}function ba(t){let{normal:e,distance:r}=t,n=Math.sqrt(e.x*e.x+e.y*e.y+e.z*e.z);if(n===0)return t;let i=1/n;return{normal:{x:e.x*i,y:e.y*i,z:e.z*i},distance:r*i}}function sr(t){if(t.length!==16)throw new Error("View-projection matrix must contain 16 elements");let e=t[0],r=t[4],n=t[8],i=t[12],a=t[1],o=t[5],s=t[9],c=t[13],l=t[2],u=t[6],d=t[10],f=t[14],h=t[3],m=t[7],g=t[11],p=t[15];return[ba({normal:{x:h+e,y:m+r,z:g+n},distance:p+i}),ba({normal:{x:h-e,y:m-r,z:g-n},distance:p-i}),ba({normal:{x:h+a,y:m+o,z:g+s},distance:p+c}),ba({normal:{x:h-a,y:m-o,z:g-s},distance:p-c}),ba({normal:{x:h+l,y:m+u,z:g+d},distance:p+f}),ba({normal:{x:h-l,y:m-u,z:g-d},distance:p-f})]}function F1(t,e){return t.normal.x*e.x+t.normal.y*e.y+t.normal.z*e.z+t.distance}function Ei(t,e,r){for(let n of r){let i=n.normal.x>=0?e.x:t.x,a=n.normal.y>=0?e.y:t.y,o=n.normal.z>=0?e.z:t.z;if(F1(n,{x:i,y:a,z:o})<0)return!1}return!0}function hm(t,e,r){let n=(t.x+e.x)*.5,i=(t.y+e.y)*.5,a=(t.z+e.z)*.5,o=(e.x-t.x)*.5,s=(e.y-t.y)*.5,c=(e.z-t.z)*.5,l=r,u=l[0]*n+l[4]*i+l[8]*a+l[12],d=l[1]*n+l[5]*i+l[9]*a+l[13],f=l[2]*n+l[6]*i+l[10]*a+l[14],h=Math.abs(l[0])*o+Math.abs(l[4])*s+Math.abs(l[8])*c,m=Math.abs(l[1])*o+Math.abs(l[5])*s+Math.abs(l[9])*c,g=Math.abs(l[2])*o+Math.abs(l[6])*s+Math.abs(l[10])*c;return{mins:{x:u-h,y:d-m,z:f-g},maxs:{x:u+h,y:d+m,z:f+g}}}function fd(t){return t<0}function hd(t){return-t-1}function mm(t,e){return t.normal[0]*e.x+t.normal[1]*e.y+t.normal[2]*e.z-t.dist}function pd(t,e,r){if(!t||e<0||r<0)return!0;let n=Math.ceil(t.numClusters/8),i=t.clusters[e].pvs,a=Math.floor(r/8),o=1<<r%8;return a<0||a>=n?!1:(i[a]&o)!==0}function I1(t,e){let r={x:t.mins[0],y:t.mins[1],z:t.mins[2]},n={x:t.maxs[0],y:t.maxs[1],z:t.maxs[2]};return Ei(r,n,e)}function Ti(t,e){if(t.models.length===0)return-1;let r=t.models[0].headNode;for(;r>=0;){let n=t.nodes[r],i=t.planes[n.planeIndex],o=mm(i,e)>=0?0:1,s=n.children[o];if(fd(s))return hd(s);r=s}return fd(r)?hd(r):-1}function D1(t,e){let r=t.leafs[e],n=[];for(let i=0;i<r.numLeafFaces;i+=1)n.push(t.leafLists.leafFaces[e][i]);return n}function md(t,e,r,n,i,a,o,s){if(fd(e)){let h=hd(e),m=t.leafs[h];if(s&&m.area>=0&&!s.has(m.area)||!pd(t.visibility,i,m.cluster)||!I1(m,n))return;let g={x:(m.mins[0]+m.maxs[0])*.5,y:(m.mins[1]+m.maxs[1])*.5,z:(m.mins[2]+m.maxs[2])*.5},p=g.x-r.x,y=g.y-r.y,v=g.z-r.z,b=-(p*p+y*y+v*v);for(let x of D1(t,h))o.has(x)||(o.add(x),a.push({faceIndex:x,leafIndex:h,sortKey:b}));return}let c=t.nodes[e],l=t.planes[c.planeIndex],u=mm(l,r),d=u>=0?c.children[0]:c.children[1],f=u>=0?c.children[1]:c.children[0];Ei({x:c.mins[0],y:c.mins[1],z:c.mins[2]},{x:c.maxs[0],y:c.maxs[1],z:c.maxs[2]},n)&&(md(t,d,r,n,i,a,o,s),md(t,f,r,n,i,a,o,s))}function gd(t,e,r){let n=new Set;if(e<0||e>=t.areas.length)return n;let i=[e];for(n.add(e);i.length>0;){let a=i.pop(),o=t.areas[a];for(let s=0;s<o.numAreaPortals;s++){let c=o.firstAreaPortal+s,l=t.areaPortals[c],u=l.otherArea;(l.portalNumber<=0||r[l.portalNumber])&&!n.has(u)&&(n.add(u),i.push(u))}}return n}function cn(t,e,r,n){let i=Ti(t,e),a=i>=0?t.leafs[i]:null,o=a?a.cluster:-1,s=a?a.area:-1,c=null;n&&s>=0&&t.areas&&t.areas.length>0&&(c=gd(t,s,n));let l=[],u=new Set;if(t.models.length>0){let d=t.models[0].headNode;md(t,d,e,r,o,l,u,c)}return l}var Or=32,lc=class{constructor(){this.lights=[]}addLight(e,r){if(e.key!==void 0){let n=this.lights.findIndex(i=>i.key===e.key);if(n!==-1){this.lights[n]=e;return}}this.lights.push(e)}clear(){this.lights=[]}update(e,r=0){if(this.lights=this.lights.filter(n=>n.die>e),r>0)for(let n of this.lights)n.radiusSpeed!==void 0&&n.radiusSpeed!==0&&(n.intensity+=n.radiusSpeed*r,n.intensity<0&&(n.intensity=0))}getActiveLights(){return this.lights}};function xa(t){let e=[];for(let r=0;r<t.length;r+=3){let n=t[r],i=t[r+1],a=t[r+2];e.push(n,i,i,a,a,n)}return t instanceof Uint32Array||Math.max(...e)>65535?new Uint32Array(e):new Uint16Array(e)}var yd=`#version 300 es
141
+ ïBçϧmÙIólÜoëVbƒ¦¯éWÇû3`});var $r={a:Ge};this.setModule=k=>{t.setModule(sn,k)},this.getModule=()=>t.getModule(sn),this.instantiate=()=>(this.getModule().then(k=>WebAssembly.instantiate(k,$r)).then(k=>{let se=k.exports;me(se),m=se.l,g(),He(se),r()}),this.ready=new Promise(k=>{r=k}).then(()=>{this.HEAP=m.buffer,this.malloc=ge,this.free=qt,this.create_decoder=Me,this.send_setup=ue,this.init_dsp=ye,this.decode_packets=Ve,this.destroy_decoder=ct}),this)}function wi(){return this._init=()=>new this._WASMAudioDecoderCommon().instantiate(this._EmscriptenWASM,this._module).then(t=>{this._common=t,this._input=this._common.allocateTypedArray(this._inputSize,Uint8Array),this._firstPage=!0,this._inputLen=this._common.allocateTypedArray(1,Uint32Array),this._outputBufferPtr=this._common.allocateTypedArray(1,Uint32Array),this._channels=this._common.allocateTypedArray(1,Uint32Array),this._sampleRate=this._common.allocateTypedArray(1,Uint32Array),this._samplesDecoded=this._common.allocateTypedArray(1,Uint32Array);let e=256;this._errors=this._common.allocateTypedArray(e,Uint32Array),this._errorsLength=this._common.allocateTypedArray(1,Int32Array),this._frameNumber=0,this._inputBytes=0,this._outputSamples=0,this._decoder=this._common.wasm.create_decoder(this._input.ptr,this._inputLen.ptr,this._outputBufferPtr.ptr,this._channels.ptr,this._sampleRate.ptr,this._samplesDecoded.ptr,this._errors.ptr,this._errorsLength.ptr,e)}),Object.defineProperty(this,"ready",{enumerable:!0,get:()=>this._ready}),this.reset=()=>(this.free(),this._init()),this.free=()=>{this._common.wasm.destroy_decoder(this._decoder),this._common.free()},this.sendSetupHeader=t=>{this._input.buf.set(t),this._inputLen.buf[0]=t.length,this._common.wasm.send_setup(this._decoder,this._firstPage),this._firstPage=!1},this.initDsp=()=>{this._common.wasm.init_dsp(this._decoder)},this.decodePackets=t=>{let e=[],r=0,n=[];for(let i=0;i<t.length;i++){let a=t[i];this._input.buf.set(a),this._inputLen.buf[0]=a.length,this._common.wasm.decode_packets(this._decoder);let o=this._samplesDecoded.buf[0],s=[],c=new Uint32Array(this._common.wasm.HEAP,this._outputBufferPtr.buf[0],this._channels.buf[0]);for(let l=0;l<this._channels.buf[0];l++){let u=new Float32Array(o);o&&u.set(new Float32Array(this._common.wasm.HEAP,c[l],o)),s.push(u)}e.push(s),r+=o,this._frameNumber++,this._inputBytes+=a.length,this._outputSamples+=o;for(let l=0;l<this._errorsLength.buf;l+=2){let u=this._common.codeToString(this._errors.buf[l]),d=this._common.codeToString(this._errors.buf[l+1]);n.push({message:u+" vorbis_synthesis"+d,frameLength:a.length,frameNumber:this._frameNumber,inputBytes:this._inputBytes,outputSamples:this._outputSamples})}this._errorsLength.buf[0]=0}return this._WASMAudioDecoderCommon.getDecodedAudioMultiChannel(n,e,this._channels.buf[0],r,this._sampleRate.buf[0],16)},this._isWebWorker=wi.isWebWorker,this._WASMAudioDecoderCommon=wi.WASMAudioDecoderCommon||_e,this._EmscriptenWASM=wi.EmscriptenWASM||sn,this._module=wi.module,this._inputSize=128*1024,this._ready=this._init(),this}var $l=Symbol(),ln=class{constructor(){this._onCodec=e=>{if(e!=="vorbis")throw new Error("@wasm-audio-decoders/ogg-vorbis does not support this codec "+e)},new _e,this._init(),this._ready=this[$l](wi)}_init(){this._vorbisSetupInProgress=!0,this._totalSamplesDecoded=0,this._codecParser=new rm("audio/ogg",{onCodec:this._onCodec,enableFrameCRC32:!1})}async[$l](e){if(this._decoder){let r=this._decoder;await r.ready.then(()=>r.free())}return this._decoder=new e,this._decoder.ready}get ready(){return this._ready}async reset(){return this._init(),this._decoder.reset()}free(){this._decoder.free()}async decodeOggPages(e){let r=[];for(let a=0;a<e.length;a++){let o=e[a];if(this._vorbisSetupInProgress&&(o[Xl][0]===1&&this._decoder.sendSetupHeader(o[Xl]),o[Wl].length)){let s=o[Wl][0][nm];this._decoder.sendSetupHeader(s[am]),this._decoder.initDsp(),this._vorbisSetupInProgress=!1}r.push(...o[Wl].map(s=>s[Xl]))}let n=await this._decoder.decodePackets(r);this._totalSamplesDecoded+=n.samplesDecoded;let i=e[e.length-1];if(i&&i[im]){let a=this._totalSamplesDecoded-i[om];if(a>0){for(let o=0;o<n.channelData.length;o++)n.channelData[o]=n.channelData[o].subarray(0,n.samplesDecoded-a);n.samplesDecoded-=a,this._totalSamplesDecoded-=a}}return n}async decode(e){return this.decodeOggPages([...this._codecParser.parseChunk(e)])}async flush(){let e=await this.decodeOggPages([...this._codecParser.flush()]);return await this.reset(),e}async decodeFile(e){let r=await this.decodeOggPages([...this._codecParser.parseAll(e)]);return await this.reset(),r}};var ad=class extends Ji{constructor(e){super(e,"ogg-vorbis-decoder",wi,sn)}async sendSetupHeader(e){return this.postToDecoder("sendSetupHeader",e)}async initDsp(){return this.postToDecoder("initDsp")}async decodePackets(e){return this.postToDecoder("decodePackets",e)}},is=class extends ln{constructor(){super(),this._ready=super[$l](ad)}async free(){await this._decoder.free()}terminate(){this._decoder.terminate()}};yl(ln,"OggVorbisDecoder");yl(is,"OggVorbisDecoderWebWorker");var od=class extends Error{constructor(e){super(e),this.name="OggDecodeError"}};async function Kl(t,e=new ln){await e.ready;let r=await e.decode(new Uint8Array(t)),n=r.errors;if(n&&n.length>0)throw new od(n.map(i=>i.message).join("; "));return{sampleRate:r.sampleRate,channels:r.channelData.length,bitDepth:r.bitDepth,channelData:r.channelData}}var as=class extends Error{constructor(e){super(e),this.name="AudioRegistryError"}},ga=class{constructor(e,r={}){this.vfs=e;this.refCounts=new Map;this.nextRequestId=0;this.cache=new En(r.cacheSize??64),r.workerPath&&(this.worker=new Worker(r.workerPath,{type:"module"}))}get size(){return this.cache.size}get capacity(){return this.cache.capacity}async load(e){let r=e.toLowerCase(),n=this.cache.get(r);if(n)return this.refCounts.set(r,(this.refCounts.get(r)??0)+1),n;let a=(await this.vfs.readFile(e)).slice().buffer,o=await this.decodeByExtension(e,a);return this.cache.set(r,o),this.refCounts.set(r,1),o}release(e){let r=e.toLowerCase(),n=this.refCounts.get(r)??0;n<=1?(this.cache.delete(r),this.refCounts.delete(r)):this.refCounts.set(r,n-1)}clearAll(){this.cache.clear(),this.refCounts.clear()}set capacity(e){this.cache.capacity=e}async decodeByExtension(e,r){let n=e.toLowerCase();if(n.endsWith(".wav")){if(this.worker)return this.decodeWavInWorker(r);let i=gl(r),a=i.channels,o=Array.from({length:a},()=>new Float32Array(i.samples.length/a));for(let s=0;s<i.samples.length;s+=1)o[s%a][Math.floor(s/a)]=i.samples[s];return{sampleRate:i.sampleRate,channels:a,bitDepth:i.bitsPerSample,channelData:o}}if(n.endsWith(".ogg")||n.endsWith(".oga"))return Kl(r);throw new as(`Unsupported audio format: ${e}`)}decodeWavInWorker(e){return new Promise((r,n)=>{if(!this.worker){n(new Error("Worker not initialized"));return}let i=this.nextRequestId++,a=o=>{if(o.data.id===i)if(this.worker.removeEventListener("message",a),o.data.type==="success"){let s=o.data.data,c=s.channels,l=Array.from({length:c},()=>new Float32Array(s.samples.length/c));for(let u=0;u<s.samples.length;u+=1)l[u%c][Math.floor(u/c)]=s.samples[u];r({sampleRate:s.sampleRate,channels:c,bitDepth:s.bitsPerSample,channelData:l})}else n(new Error(o.data.message))};this.worker.addEventListener("message",a),this.worker.postMessage({id:i,buffer:e,type:"wav"},[e])})}};var x1="quake2ts-pak-indexes",v1="pak-indexes";function sm(){if(typeof indexedDB<"u")return indexedDB;if(typeof window<"u"&&"indexedDB"in window)return window.indexedDB;if(typeof globalThis<"u"&&"indexedDB"in globalThis)return globalThis.indexedDB}function os(t,e){let r=sm();return r?new Promise((n,i)=>{let a=r.open(t,1);a.onupgradeneeded=()=>{let{result:o}=a;o.objectStoreNames.contains(e)||o.createObjectStore(e,{keyPath:"key"})},a.onerror=()=>i(a.error??new Error("Unknown IndexedDB error")),a.onsuccess=()=>n(a.result)}):Promise.reject(new Error("IndexedDB is not available in this environment"))}function ss(t,e,r,n){return new Promise((i,a)=>{let s=t.transaction(e,r).objectStore(e),c=n(s);c.onsuccess=()=>i(c.result),c.onerror=()=>a(c.error??new Error("IndexedDB transaction error"))})}function sd(t,e){return`${Le(t)}:${e.toString(16)}`}function _1(t){return t.map(e=>({...e}))}var Yl=class{constructor(e=x1,r=v1){this.dbName=e;this.storeName=r}get isSupported(){return!!sm()}async persist(e){if(!this.isSupported)return;let r=e.validate(),n={...r,key:sd(e.name,r.checksum),name:e.name,size:e.size,persistedAt:Date.now(),entries:_1(r.entries)},i=await os(this.dbName,this.storeName);return await ss(i,this.storeName,"readwrite",a=>a.put(n)),i.close(),n}async find(e,r){if(!this.isSupported)return;let n=await os(this.dbName,this.storeName),i=r!==void 0?sd(e,r):void 0,a=await ss(n,this.storeName,"readonly",o=>i?o.get(i):o.getAll());if(n.close(),!!a){if(Array.isArray(a)){let o=Le(e),s=a.filter(c=>Le(c.name)===o);return s.length===0?void 0:s.sort((c,l)=>l.persistedAt-c.persistedAt)[0]}return a}}async remove(e,r){if(!this.isSupported)return!1;let n=await os(this.dbName,this.storeName),i=r!==void 0?sd(e,r):void 0,a=await ss(n,this.storeName,"readwrite",o=>{if(i)return o.delete(i);let s=`${Le(e)}:`;return o.delete(IDBKeyRange.bound(s,`${s}\uFFFF`,!1,!0))});return n.close(),typeof a=="number"?a>0:!0}async clear(){if(!this.isSupported)return;let e=await os(this.dbName,this.storeName);await ss(e,this.storeName,"readwrite",r=>r.clear()),e.close()}async list(){if(!this.isSupported)return[];let e=await os(this.dbName,this.storeName),r=await ss(e,this.storeName,"readonly",n=>n.getAll());return e.close(),r.sort((n,i)=>i.persistedAt-n.persistedAt)}};var Mi=class extends Error{constructor(r,n){super(n??`Missing dependencies: ${r.join(", ")}`);this.missing=r;this.name="AssetDependencyError"}},ls=class{constructor(){this.nodes=new Map}register(e,r=[]){let n=this.nodes.get(e)??{dependencies:new Set,loaded:!1};r.forEach(i=>n.dependencies.add(i)),this.nodes.set(e,n),r.forEach(i=>{this.nodes.has(i)||this.nodes.set(i,{dependencies:new Set,loaded:!1})})}markLoaded(e){let r=this.nodes.get(e)??{dependencies:new Set,loaded:!1},n=this.getMissingDependencies(e,r);if(n.length>0)throw new Mi(n,`Asset ${e} is missing dependencies: ${n.join(", ")}`);r.loaded=!0,this.nodes.set(e,r)}markUnloaded(e){let r=this.nodes.get(e);r&&(r.loaded=!1)}isLoaded(e){return this.nodes.get(e)?.loaded??!1}missingDependencies(e){let r=this.nodes.get(e);return r?this.getMissingDependencies(e,r):[]}reset(){this.nodes.clear()}getMissingDependencies(e,r){let n=[];for(let i of r.dependencies)this.nodes.get(i)?.loaded||n.push(i);return n}},ql=class{constructor(e,r={}){this.vfs=e;this.maps=new Map;this.loadQueue=[];this.activeLoads=0;this.textures=new Qi({capacity:r.textureCacheCapacity??128,maxMemory:r.textureMemoryLimit}),this.audio=new ga(e,{cacheSize:r.audioCacheSize??64,workerPath:r.audioWorkerPath}),this.dependencyTracker=r.dependencyTracker??new ls,this.resourceTracker=r.resourceTracker,this.md2=new qi(e),this.md3=new Zi(e),this.sprite=new ji(e),this.bsp=new Yi(e,{useWorker:!!r.bspWorkerPath,workerPath:r.bspWorkerPath}),this.maxConcurrentLoads=r.maxConcurrentLoads??4,this.palette=new Uint8Array(768);for(let n=0;n<256;n++)this.palette[n*3]=n,this.palette[n*3+1]=n,this.palette[n*3+2]=n}async loadPalette(e="pics/colormap.pcx"){try{let r=await this.vfs.readFile(e),n=ho(r);n.palette&&(this.palette=n.palette)}catch(r){console.warn(`Failed to load palette from ${e}:`,r)}}isAssetLoaded(e,r){return this.dependencyTracker.isLoaded(this.makeKey(e,r))}registerTexture(e,r){this.textures.set(e,r);let n=this.makeKey("texture",e);this.dependencyTracker.register(n),this.dependencyTracker.markLoaded(n)}async loadTexture(e){if(this.resourceTracker){let o=this.vfs.stat(e);this.resourceTracker.recordLoad("texture",e,o?.size,o?.sourcePak)}let r=this.textures.get(e);if(r)return r;let n=await this.vfs.readFile(e),i=e.split(".").pop()?.toLowerCase(),a;if(i==="wal")a=pl(n,this.palette);else if(i==="pcx")a=ml(ho(n));else if(i==="tga")a=Ch(Ou(n));else throw new Error(`Unsupported texture format for loadTexture: ${i}`);return this.registerTexture(e,a),a}async loadSound(e){if(this.resourceTracker){let i=this.vfs.stat(e);this.resourceTracker.recordLoad("sound",e,i?.size,i?.sourcePak)}let r=await this.audio.load(e),n=this.makeKey("sound",e);return this.dependencyTracker.register(n),this.dependencyTracker.markLoaded(n),r}async loadMd2Model(e,r=[]){if(this.resourceTracker){let s=this.vfs.stat(e);this.resourceTracker.recordLoad("model",e,s?.size,s?.sourcePak)}let n=this.makeKey("model",e),i=r.map(s=>this.makeKey("texture",s));this.dependencyTracker.register(n,i);let a=this.dependencyTracker.missingDependencies(n);if(a.length>0)throw new Mi(a,`Asset ${n} is missing dependencies: ${a.join(", ")}`);let o=await this.md2.load(e);return this.dependencyTracker.markLoaded(n),o}getMd2Model(e){if(this.resourceTracker){let r=this.vfs.stat(e);this.resourceTracker.recordLoad("model",e,r?.size,r?.sourcePak)}return this.md2.get(e)}async loadMd3Model(e,r=[]){if(this.resourceTracker){let s=this.vfs.stat(e);this.resourceTracker.recordLoad("model",e,s?.size,s?.sourcePak)}let n=this.makeKey("model",e),i=r.map(s=>this.makeKey("texture",s));this.dependencyTracker.register(n,i);let a=this.dependencyTracker.missingDependencies(n);if(a.length>0)throw new Mi(a,`Asset ${n} is missing dependencies: ${a.join(", ")}`);let o=await this.md3.load(e);return this.dependencyTracker.markLoaded(n),o}getMd3Model(e){if(this.resourceTracker){let r=this.vfs.stat(e);this.resourceTracker.recordLoad("model",e,r?.size,r?.sourcePak)}return this.md3.get(e)}async loadSprite(e){if(this.resourceTracker){let i=this.vfs.stat(e);this.resourceTracker.recordLoad("sprite",e,i?.size,i?.sourcePak)}let r=this.makeKey("sprite",e);this.dependencyTracker.register(r);let n=await this.sprite.load(e);return this.dependencyTracker.markLoaded(r),n}async loadMap(e){if(this.resourceTracker){let i=this.vfs.stat(e);this.resourceTracker.recordLoad("map",e,i?.size,i?.sourcePak)}let r=this.makeKey("map",e);if(this.maps.has(e))return this.maps.get(e);this.dependencyTracker.register(r);let n=await this.bsp.load(e);return this.maps.set(e,n),this.dependencyTracker.markLoaded(r),n}getMap(e){return this.maps.get(e)}listFiles(e){return this.vfs.findByExtension(e)}resetForLevelChange(){this.textures.clear(),this.audio.clearAll(),this.dependencyTracker.reset(),this.maps.clear(),this.loadQueue.length=0}getMemoryUsage(){let e=0,r=0;if(typeof process<"u"&&process.memoryUsage){let n=process.memoryUsage();e=n.heapTotal,r=n.heapUsed}return{textures:this.textures.memoryUsage,audio:this.audio.size,heapTotal:e,heapUsed:r}}enforceMemoryBudget(e){e.textureMemoryLimit!==void 0&&(this.textures.maxMemory=e.textureMemoryLimit),e.textureCacheCapacity!==void 0&&(this.textures.capacity=e.textureCacheCapacity),e.audioCacheSize!==void 0&&(this.audio.capacity=e.audioCacheSize)}clearCache(e){switch(e){case"texture":this.textures.clear();break;case"sound":this.audio.clearAll();break;case"map":this.maps.clear();break}}async preloadAssets(e){let r=e.map(n=>{let i=this.detectAssetType(n);return i?this.queueLoad(n,i,0):Promise.resolve()});await Promise.all(r)}queueLoad(e,r,n=1){return r==="texture"&&this.textures.get(e)?Promise.resolve(this.textures.get(e)):new Promise((i,a)=>{this.loadQueue.push({path:e,type:r,priority:n,resolve:i,reject:a}),this.loadQueue.sort((o,s)=>s.priority-o.priority),this.processQueue()})}async processQueue(){if(this.activeLoads>=this.maxConcurrentLoads||this.loadQueue.length===0)return;let e=this.loadQueue.shift();this.activeLoads++;try{let r;switch(e.type){case"texture":r=await this.loadTexture(e.path);break;case"sound":r=await this.loadSound(e.path);break;case"model":e.path.endsWith(".md2")?r=await this.loadMd2Model(e.path):e.path.endsWith(".md3")&&(r=await this.loadMd3Model(e.path));break;case"sprite":r=await this.loadSprite(e.path);break;case"map":r=await this.loadMap(e.path);break;default:throw new Error(`Unknown asset type ${e.type}`)}e.resolve(r)}catch(r){e.reject(r)}finally{this.activeLoads--,this.processQueue()}}detectAssetType(e){let r=e.split(".").pop()?.toLowerCase();return r?["wal","pcx","tga","png","jpg"].includes(r)?"texture":["wav","ogg"].includes(r)?"sound":["md2","md3"].includes(r)?"model":["sp2"].includes(r)?"sprite":["bsp"].includes(r)?"map":null:null}makeKey(e,r){return`${e}:${Le(r)}`}};var Zl=class{constructor(e){this.factory=e}getContext(){return this.context||(this.context=this.factory()),this.context}async resume(){let e=this.getContext();e.state==="suspended"&&await e.resume()}getState(){return this.context?.state??"suspended"}};function jl(t){let e=t.getContext(),r=e.createGain();r.gain.value=1;let n=e.createDynamicsCompressor(),i=e.createBiquadFilter?.(),a;if(e.createConvolver&&e.createGain){let o=e.createConvolver(),s=e.createGain(),c=e.createGain();s.connect(o),o.connect(c),a={convolver:o,input:s,output:c}}return i?(i.type="lowpass",i.frequency.value=2e4,i.Q.value=.707,r.connect(i),i.connect(n),a&&a.output.connect(i)):(r.connect(n),a&&a.output.connect(n)),n.connect(e.destination),{context:e,master:r,compressor:n,filter:i,reverb:a}}var Ql=class{constructor(e=new $i){this.configStrings=e;this.buffers=new Map}registerName(e){return this.configStrings.soundIndex(e)}register(e,r){let n=this.registerName(e);return this.buffers.set(n,r),n}find(e){return this.configStrings.findSoundIndex(e)}get(e){return this.buffers.get(e)}has(e){return this.buffers.has(e)}getName(e){return this.configStrings.getName(e)}};var Jl=class{constructor(e){this.vfs=e.vfs,this.registry=e.registry,this.contextController=e.context,this.soundRoot=e.soundRoot??"sound/",this.decodeAudio=e.decodeAudio??((r,n)=>{if(!r.decodeAudioData)throw new Error("decodeAudioData is not available on the provided audio context");return r.decodeAudioData(n)})}async precache(e){let r=[...new Set(e.map(a=>this.normalize(a)))],n={loaded:[],skipped:[],missing:[],errors:{}},i=this.contextController.getContext();for(let a of r)try{let o=this.registry.find(a);if(o!==void 0&&this.registry.has(o)){n.skipped.push(a);continue}if(!this.vfs.stat(a)){n.missing.push(a);continue}let l=(await this.vfs.readFile(a)).slice().buffer,u=await this.decodeAudio(i,l);this.registry.register(a,u),n.loaded.push(a)}catch(o){let s=o instanceof Error?o:new Error(String(o));n.errors[a]=s}return n}normalize(e){let r=Le(e.replace(/^\//,""));return r.startsWith(this.soundRoot)?r:Le(`${this.soundRoot}${r}`)}};var S1=7,cs=t=>t&S1;function ec(t){return Array.from({length:io},()=>({entnum:0,entchannel:Cr.Auto,endTimeMs:0,isPlayer:!1,active:!1})).map(e=>({...e,isPlayer:e.entnum===t}))}function tc(t,e,r,n){if(r<0)throw new Error("pickChannel: entchannel must be non-negative");let i=cs(r),a=-1,o=Number.POSITIVE_INFINITY;for(let s=0;s<t.length;s+=1){let c=t[s],l=cs(c.entchannel);if(i!==Cr.Auto&&c.entnum===e&&l===i){a=s;break}if(c.active&&c.entnum===n.playerEntity&&e!==n.playerEntity)continue;let u=c.endTimeMs-n.nowMs;(a===-1||u<o)&&(o=u,a=s)}return a===-1?void 0:a}var rc=class{constructor(e){this.activePreset=null;this.enabled=!0;this.node=e,this.node.input.gain.value=.5,this.node.output.gain.value=1}setPreset(e){this.activePreset=e,this.node.convolver.buffer!==(e?.buffer??null)&&(this.node.convolver.buffer=e?.buffer??null),e&&e.gain!==void 0?this.node.output.gain.value=e.gain:this.node.output.gain.value=1}setEnabled(e){this.enabled=e,e?this.node.input.gain.value=.5:this.node.input.gain.value=0}getOutputNode(){return this.node.output}getInputNode(){return this.node.input}};var nc=class{constructor(e){this.activeSources=new Map;this.playbackRate=1;this.contextController=e.context,this.registry=e.registry,this.playerEntity=e.playerEntity,this.channels=ec(e.playerEntity),this.listener=e.listener??{origin:qf,right:{x:1,y:0,z:0}},this.sfxVolume=e.sfxVolume??1,this.masterVolume=e.masterVolume??1,this.resolveOcclusion=e.resolveOcclusion,this.graph=jl(this.contextController),this.graph.master.gain.value=this.masterVolume,this.graph.reverb&&(this.reverb=new rc(this.graph.reverb))}setListener(e){this.listener=e}setMasterVolume(e){this.masterVolume=e,this.graph.master.gain.value=e}setSfxVolume(e){this.sfxVolume=e}setPlaybackRate(e){this.playbackRate=e;for(let r of this.activeSources.values())r.source.playbackRate&&(r.source.playbackRate.value=e),this.updateSourceGain(r)}async ensureRunning(){await this.contextController.resume()}setReverbPreset(e){this.reverb?.setPreset(e)}play(e){let r=this.registry.get(e.soundIndex);if(!r)return;let n=this.graph.context,i=n.currentTime*1e3,a=tc(this.channels,e.entity,e.channel,{nowMs:i,playerEntity:this.playerEntity});if(a===void 0)return;let o=this.activeSources.get(a);o&&(o.source.onended=null,o.source.stop(),this.activeSources.delete(a));let s=n.createBufferSource();s.buffer=r,s.loop=e.looping??!1,s.playbackRate&&(s.playbackRate.value=this.playbackRate);let c=e.origin??this.listener.origin,l=n.createGain(),u=this.createPanner(n,e.attenuation),d=this.resolveOcclusion?.(this.listener,c,e.attenuation),f=lm(d?.gainScale??1),h=this.resolveOcclusion?this.createOcclusionFilter(n,d?.lowpassHz??2e4):void 0;this.applyOriginToPanner(u,c);let g=e.volume/255*this.sfxVolume,p=Math.abs(this.playbackRate-1)<.001?1:0;l.gain.value=g*f*p;let y=n.currentTime+(e.timeOffsetMs??0)/1e3,v=(e.looping?Number.POSITIVE_INFINITY:r.duration*1e3)+y*1e3;s.connect(u);let b=u;h?(u.connect(h),h.connect(l),b=l):(u.connect(l),b=l),l.connect(this.graph.master),this.reverb&&l.connect(this.reverb.getInputNode()),s.start(y),s.onended=()=>{this.channels[a].active=!1,this.activeSources.delete(a)};let x={channelIndex:a,entnum:e.entity,entchannel:cs(e.channel),endTimeMs:v,source:s,panner:u,gain:l,baseGain:g,origin:c,attenuation:e.attenuation,occlusion:h?{scale:f,lowpassHz:d?.lowpassHz,filter:h}:d?{scale:f,lowpassHz:d.lowpassHz}:void 0};return this.channels[a]={entnum:e.entity,entchannel:cs(e.channel),endTimeMs:v,isPlayer:e.entity===this.playerEntity,active:!0},this.activeSources.set(a,x),x}stop(e){let r=this.activeSources.get(e);r&&(r.source.stop(),this.channels[e].active=!1,this.activeSources.delete(e))}stopEntitySounds(e){for(let[r,n]of[...this.activeSources.entries()])n.entnum===e&&(n.source.stop(),this.channels[r].active=!1,this.activeSources.delete(r))}updateEntityPosition(e,r){for(let n of this.activeSources.values())if(n.entnum===e&&(this.applyOriginToPanner(n.panner,r),n.origin=r,this.resolveOcclusion)){let i=this.resolveOcclusion(this.listener,r,n.attenuation);this.applyOcclusion(n,i)}}positionedSound(e,r,n,i){return this.play({entity:0,channel:Cr.Auto,soundIndex:r,volume:n,attenuation:i,origin:e})}ambientSound(e,r,n){return this.play({entity:0,channel:Cr.Auto,soundIndex:r,volume:n,attenuation:ao,origin:e,looping:!0})}getChannelState(e){return this.channels[e]}getDiagnostics(){return{activeChannels:this.activeSources.size,masterVolume:this.masterVolume,sfxVolume:this.sfxVolume,channels:[...this.channels],activeSounds:[...this.activeSources.values()].map(e=>({entnum:e.entnum,entchannel:e.entchannel,channelIndex:e.channelIndex,origin:e.origin,gain:e.gain.gain.value,baseGain:e.baseGain,attenuation:e.attenuation,maxDistance:e.panner.maxDistance,distanceModel:e.panner.distanceModel,occlusion:e.occlusion?{scale:e.occlusion.scale,lowpassHz:e.occlusion.lowpassHz}:void 0}))}}setUnderwater(e,r=400){let n=this.graph.filter;n&&(n.type="lowpass",n.Q.value=.707,n.frequency.value=e?r:2e4)}createPanner(e,r){let n=e.createPanner?e.createPanner():Object.assign(e.createGain(),{positionX:{value:this.listener.origin.x},positionY:{value:this.listener.origin.y},positionZ:{value:this.listener.origin.z}});return this.configurePanner(n,r)}configurePanner(e,r){let n=Vi(r);return e.refDistance=Gi,e.maxDistance=si(r),e.rolloffFactor=n,e.distanceModel="linear",e.positionX.value=this.listener.origin.x,e.positionY.value=this.listener.origin.y,e.positionZ.value=this.listener.origin.z,e}applyOriginToPanner(e,r){e.positionX.value=r.x,e.positionY.value=r.y,e.positionZ.value=r.z}createOcclusionFilter(e,r){if(!e.createBiquadFilter)return;let n=e.createBiquadFilter();return n.type="lowpass",n.Q.value=.707,n.frequency.value=ld(r,10,2e4),n}updateSourceGain(e){let r=e.occlusion?.scale??1,n=Math.abs(this.playbackRate-1)<.001?1:0;e.gain.gain.value=e.baseGain*r*n}applyOcclusion(e,r){let n=lm(r?.gainScale??1),i=Math.abs(this.playbackRate-1)<.001?1:0;if(e.gain.gain.value=e.baseGain*n*i,e.occlusion?.filter){let a=r?.lowpassHz??2e4;e.occlusion.filter.frequency.value=ld(a,10,2e4)}e.occlusion?(e.occlusion.scale=n,e.occlusion.lowpassHz=r?.lowpassHz):r&&(e.occlusion={scale:n,lowpassHz:r.lowpassHz})}},ld=(t,e,r)=>Math.min(r,Math.max(e,t)),lm=t=>ld(t,0,1);var us=class{constructor(e){this.trace=e;this.resolve=(e,r,n)=>{let i=mu(Zf(r,e.origin)),a=si(n),c=2e4*(1-Math.min(i,a)/Math.max(1,a)*.9),l=this.trace(e.origin,r,void 0,void 0),u=1,d=2e4;l.fraction<1&&(u=.3,d=400);let f=Math.min(c,d);if(u<1||f<2e4)return{gainScale:u,lowpassHz:f}}}};function cm(t){return new us(t).resolve}var ic=class{constructor(e){this.createElement=e.createElement,this.resolveSource=e.resolveSource??(async r=>r),this.volume=e.volume??1,this.crossfadeDuration=e.crossfadeDuration??1}async playTrack(e){let r=`music/track${e.toString().padStart(2,"0")}.ogg`;return this.play(r)}async play(e,{loop:r=!0,restart:n=!1}={}){if(this.track===e&&this.currentElement){this.currentElement.loop=r,this.cancelFade(),this.fadingElement&&(this.fadingElement.pause(),this.fadingElement=void 0),this.currentElement.volume=this.volume,n&&(this.currentElement.currentTime=0),(this.currentElement.paused||n)&&await this.currentElement.play();return}let i=await this.resolveSource(e);this.cancelFade(),this.fadingElement&&(this.fadingElement.pause(),this.fadingElement=void 0),this.currentElement&&(this.fadingElement=this.currentElement,this.currentElement=void 0);let a=this.createElement();a.src=i,a.loop=r,a.volume=0,a.currentTime=0,a.load();try{await a.play()}catch(o){console.warn(`MusicSystem: Failed to play ${e}`,o),this.fadingElement}this.currentElement=a,this.track=e,this.startCrossfade()}pause(){this.cancelFade(),this.currentElement&&!this.currentElement.paused&&this.currentElement.pause(),this.fadingElement&&(this.fadingElement.pause(),this.fadingElement=void 0)}async resume(){!this.currentElement||!this.currentElement.paused||(await this.currentElement.play(),this.currentElement.volume=this.volume)}stop(){this.cancelFade(),this.currentElement&&(this.currentElement.pause(),this.currentElement.currentTime=0,this.currentElement=void 0),this.fadingElement&&(this.fadingElement.pause(),this.fadingElement=void 0),this.track=void 0}setVolume(e){this.volume=e,this.currentElement&&!this.fadeInterval&&(this.currentElement.volume=e)}getState(){let e=!!(this.currentElement&&!this.currentElement.paused&&!this.currentElement.ended),r=!!this.currentElement?.paused;return{track:this.track,paused:r,playing:e,volume:this.volume}}startCrossfade(){let r=this.crossfadeDuration*1e3/50,n=this.volume/r,i=0,a=this.fadingElement?this.fadingElement.volume:0,o=()=>{let s=!1;this.currentElement&&(i=Math.min(this.volume,i+n),this.currentElement.volume=i,i<this.volume&&(s=!0)),this.fadingElement&&(a=Math.max(0,a-n),this.fadingElement.volume=a,a>0?s=!0:(this.fadingElement.pause(),this.fadingElement=void 0)),s||this.cancelFade()};o(),(this.currentElement&&this.currentElement.volume<this.volume||this.fadingElement)&&(this.fadeInterval=setInterval(o,50))}cancelFade(){this.fadeInterval&&(clearInterval(this.fadeInterval),this.fadeInterval=void 0)}};function w1(t){t.enable(t.DEPTH_TEST),t.depthFunc(t.LEQUAL),t.enable(t.CULL_FACE),t.cullFace(t.BACK),t.enable(t.BLEND),t.blendFuncSeparate(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA,t.ONE,t.ONE_MINUS_SRC_ALPHA)}function M1(t,e,r,n){for(let i of e){let a=t.getExtension(i);if(!a)throw new Error(`Missing required WebGL extension: ${i}`);n.set(i,a)}for(let i of r){let a=t.getExtension(i);a&&n.set(i,a)}}function um(t,e={}){let{contextAttributes:r,requiredExtensions:n=[],optionalExtensions:i=[]}=e,a=t.getContext("webgl2",r??{antialias:!0});if(!a)throw new Error("WebGL2 not supported or failed to initialize");w1(a);let o=new Map;M1(a,n,i,o);let s=!1,c=new Set,l=new Set,u=f=>{s=!0,f.preventDefault();for(let h of c)h()},d=()=>{s=!1;for(let f of l)f()};return t.addEventListener("webglcontextlost",u),t.addEventListener("webglcontextrestored",d),{gl:a,extensions:o,isLost:()=>s,onLost(f){return c.add(f),()=>c.delete(f)},onRestored(f){return l.add(f),()=>l.delete(f)},dispose(){t.removeEventListener("webglcontextlost",u),t.removeEventListener("webglcontextrestored",d),c.clear(),l.clear(),o.clear()}}}function dm(t,e,r){let n=t.createShader(e);if(!n)throw new Error("Failed to allocate shader");if(t.shaderSource(n,r.trim()),t.compileShader(n),!t.getShaderParameter(n,t.COMPILE_STATUS)){let a=t.getShaderInfoLog(n)??"Unknown shader compile failure";throw t.deleteShader(n),new Error(a)}return n}function A1(t,e,r,n){let i=t.createProgram();if(!i)throw new Error("Failed to allocate shader program");if(t.attachShader(i,e),t.attachShader(i,r),n)for(let[o,s]of Object.entries(n))t.bindAttribLocation(i,s,o);if(t.linkProgram(i),!t.getProgramParameter(i,t.LINK_STATUS)){let o=t.getProgramInfoLog(i)??"Unknown shader link failure";throw t.deleteProgram(i),new Error(o)}return i}var ce=class t{constructor(e,r,n){this.uniformLocations=new Map;this.attributeLocations=new Map;this.gl=e,this.program=r,this.sourceSize=n}static create(e,r,n){let i=dm(e,e.VERTEX_SHADER,r.vertex),a=dm(e,e.FRAGMENT_SHADER,r.fragment);try{let o=A1(e,i,a,n),s=r.vertex.length+r.fragment.length;return new t(e,o,s)}finally{e.deleteShader(i),e.deleteShader(a)}}use(){this.gl.useProgram(this.program)}getUniformLocation(e){if(!this.uniformLocations.has(e)){let r=this.gl.getUniformLocation(this.program,e);this.uniformLocations.set(e,r)}return this.uniformLocations.get(e)??null}getAttributeLocation(e){if(!this.attributeLocations.has(e)){let r=this.gl.getAttribLocation(this.program,e);this.attributeLocations.set(e,r)}return this.attributeLocations.get(e)??-1}dispose(){this.gl.deleteProgram(this.program),this.uniformLocations.clear(),this.attributeLocations.clear()}};function fm(t,e,r){return ce.create(t,e,r)}var Ce=class{constructor(e,r=e.STATIC_DRAW,n){this.gl=e,this.target=n??e.ARRAY_BUFFER;let i=e.createBuffer();if(!i)throw new Error("Failed to allocate buffer");this.buffer=i,e.bindBuffer(this.target,this.buffer),e.bufferData(this.target,0,r)}bind(){this.gl.bindBuffer(this.target,this.buffer)}upload(e,r=this.gl.STATIC_DRAW){this.bind(),this.gl.bufferData(this.target,e,r)}update(e,r=0){this.bind(),this.gl.bufferSubData(this.target,r,e)}dispose(){this.gl.deleteBuffer(this.buffer)}},st=class extends Ce{constructor(e,r=e.STATIC_DRAW){super(e,r,e.ELEMENT_ARRAY_BUFFER)}},Be=class{constructor(e){this.gl=e;let r=e.createVertexArray();if(!r)throw new Error("Failed to allocate vertex array object");this.vao=r}bind(){this.gl.bindVertexArray(this.vao)}configureAttributes(e,r){this.bind(),r&&r.bind();for(let n of e)this.gl.enableVertexAttribArray(n.index),this.gl.vertexAttribPointer(n.index,n.size,n.type,n.normalized??!1,n.stride??0,n.offset??0),n.divisor!==void 0&&this.gl.vertexAttribDivisor(n.index,n.divisor)}dispose(){this.gl.deleteVertexArray(this.vao)}},lt=class{constructor(e,r=e.TEXTURE_2D){this.width=0;this.height=0;this.gl=e,this.target=r;let n=e.createTexture();if(!n)throw new Error("Failed to allocate texture");this.texture=n}bind(e=0){this.gl.activeTexture(this.gl.TEXTURE0+e),this.gl.bindTexture(this.target,this.texture)}setParameters(e){this.bind(),e.wrapS!==void 0&&this.gl.texParameteri(this.target,this.gl.TEXTURE_WRAP_S,e.wrapS),e.wrapT!==void 0&&this.gl.texParameteri(this.target,this.gl.TEXTURE_WRAP_T,e.wrapT),e.minFilter!==void 0&&this.gl.texParameteri(this.target,this.gl.TEXTURE_MIN_FILTER,e.minFilter),e.magFilter!==void 0&&this.gl.texParameteri(this.target,this.gl.TEXTURE_MAG_FILTER,e.magFilter)}upload(e,r,n){this.width=e,this.height=r,this.uploadImage(0,this.gl.RGBA,e,r,0,this.gl.RGBA,this.gl.UNSIGNED_BYTE,n)}uploadImage(e,r,n,i,a,o,s,c){this.bind(),this.gl.texImage2D(this.target,e,r,n,i,a,o,s,c)}dispose(){this.gl.deleteTexture(this.texture)}},ya=class{constructor(e){this.gl=e,this.target=e.TEXTURE_CUBE_MAP;let r=e.createTexture();if(!r)throw new Error("Failed to allocate cubemap texture");this.texture=r}bind(e=0){this.gl.activeTexture(this.gl.TEXTURE0+e),this.gl.bindTexture(this.target,this.texture)}setParameters(e){this.bind(),e.wrapS!==void 0&&this.gl.texParameteri(this.target,this.gl.TEXTURE_WRAP_S,e.wrapS),e.wrapT!==void 0&&this.gl.texParameteri(this.target,this.gl.TEXTURE_WRAP_T,e.wrapT),e.minFilter!==void 0&&this.gl.texParameteri(this.target,this.gl.TEXTURE_MIN_FILTER,e.minFilter),e.magFilter!==void 0&&this.gl.texParameteri(this.target,this.gl.TEXTURE_MAG_FILTER,e.magFilter)}uploadFace(e,r,n,i,a,o,s,c,l){this.bind(),this.gl.texImage2D(e,r,n,i,a,o,s,c,l)}dispose(){this.gl.deleteTexture(this.texture)}},Ai=class{constructor(e){this.gl=e;let r=e.createFramebuffer();if(!r)throw new Error("Failed to allocate framebuffer");this.framebuffer=r}bind(e=this.gl.FRAMEBUFFER){this.gl.bindFramebuffer(e,this.framebuffer)}attachTexture2D(e,r,n=0){this.bind(),this.gl.framebufferTexture2D(this.gl.FRAMEBUFFER,e,r.target,r.texture,n)}dispose(){this.gl.deleteFramebuffer(this.framebuffer)}};var ud=4,cd=7*ud,dd=[{index:0,size:3,type:5126,stride:cd,offset:0},{index:1,size:2,type:5126,stride:cd,offset:3*ud},{index:2,size:2,type:5126,stride:cd,offset:5*ud}];function E1(t,e){return{width:t,height:t,padding:e,data:new Uint8Array(t*t*4),cursorX:0,cursorY:0,rowHeight:0}}function L1(t){let e=t.width*t.height;if(e===0)throw new Error("Invalid lightmap with zero area");let r=t.samples.byteLength/e;if(!Number.isInteger(r)||r<3||r>4)throw new Error("Unsupported lightmap channel count");return r}function T1(t,e,r){let n=L1(r),i=t.width*4,a=e.x+t.padding,o=e.y+t.padding,s=0;for(let c=0;c<r.height;c++){let l=(o+c)*i+a*4;for(let u=0;u<r.width;u++){let d=l+u*4;t.data[d]=r.samples[s],t.data[d+1]=r.samples[s+1],t.data[d+2]=r.samples[s+2],t.data[d+3]=n===4?r.samples[s+3]:255,s+=n}}}function P1(t,e,r){let n=e.width+r.lightmapPadding*2,i=e.height+r.lightmapPadding*2;if(n>r.atlasSize||i>r.atlasSize)throw new Error("Lightmap too large for atlas");for(let s of t){if(s.cursorX+n>s.width&&(s.cursorX=0,s.cursorY+=s.rowHeight+r.lightmapPadding,s.rowHeight=0),s.cursorY+i>s.height)continue;let c={atlasIndex:t.indexOf(s),x:s.cursorX,y:s.cursorY,width:e.width,height:e.height};return s.cursorX+=n+r.lightmapPadding,s.rowHeight=Math.max(s.rowHeight,i),{placement:c,atlas:s}}let a=E1(r.atlasSize,r.lightmapPadding);t.push(a);let o={atlasIndex:t.length-1,x:0,y:0,width:e.width,height:e.height};return a.cursorX=n+r.lightmapPadding,a.rowHeight=i,{placement:o,atlas:a}}function ac(t){return t instanceof Float32Array?t:new Float32Array(t)}function R1(t,e){if(!t){let n=new Uint16Array(e);for(let i=0;i<e;i++)n[i]=i;return n}return t instanceof Uint16Array?t:new Uint16Array(t)}function C1(t,e){let r=new Float32Array(t.length);for(let n=0;n<t.length;n+=2)r[n]=e.offset[0]+t[n]*e.scale[0],r[n+1]=e.offset[1]+t[n+1]*e.scale[1];return r}function B1(t,e){let r=ac(t.vertices),n=ac(t.textureCoords),i=e?C1(ac(t.lightmapCoords??t.textureCoords),e):ac(t.lightmapCoords??new Float32Array(n.length)),a=r.length/3;if(n.length/2!==a)throw new Error("Texture coordinates count mismatch");if(i.length/2!==a)throw new Error("Lightmap coordinates count mismatch");let o=new Float32Array(a*7);for(let s=0;s<a;s++){let c=s*3,l=s*2,u=s*7;o[u]=r[c],o[u+1]=r[c+1],o[u+2]=r[c+2],o[u+3]=n[l],o[u+4]=n[l+1],o[u+5]=i[l],o[u+6]=i[l+1]}return o}function oc(t){let e=[];for(let r=0;r<t.faces.length;r++){let n=t.faces[r];if(n.texInfo<0)continue;let i=t.texInfo[n.texInfo],a=[],o=[],s=[];for(let f=0;f<n.numEdges;f++){let h=t.surfEdges[n.firstEdge+f],m=t.edges[Math.abs(h)],g=h>=0?m.vertices[0]:m.vertices[1],p=t.vertices[g];a.push(p[0],p[1],p[2]);let y=p[0]*i.s[0]+p[1]*i.s[1]+p[2]*i.s[2]+i.sOffset,v=p[0]*i.t[0]+p[1]*i.t[1]+p[2]*i.t[2]+i.tOffset;o.push(y,v),s.push(y,v)}let c=[],l=a.length/3;for(let f=1;f<l-1;f++)c.push(0,f,f+1);let u,d=t.lightMapInfo[r];if(d){let f=1/0,h=-1/0,m=1/0,g=-1/0;for(let _=0;_<o.length;_+=2){let w=o[_],S=o[_+1];w<f&&(f=w),w>h&&(h=w),S<m&&(m=S),S>g&&(g=S)}let p=Math.floor(f/16),y=Math.floor(m/16),v=Math.ceil(h/16)-p+1,b=Math.ceil(g/16)-y+1,x=ul(n,t.lightMaps,d);if(x&&x.length===v*b*3){u={width:v,height:b,samples:x};for(let _=0;_<s.length;_+=2)s[_]=o[_]/16-p+.5,s[_+1]=o[_+1]/16-y+.5}}e.push({vertices:new Float32Array(a),textureCoords:new Float32Array(o),lightmapCoords:new Float32Array(s),indices:new Uint16Array(c),texture:i.texture,surfaceFlags:i.flags,lightmap:u,faceIndex:r})}return e}function sc(t,e,r,n={}){let i=e;if(r&&n.hiddenClassnames&&n.hiddenClassnames.size>0){let u=new Set;for(let d of r.entities.entities)if(d.classname&&n.hiddenClassnames.has(d.classname)){let f=d.properties.model;if(f&&f.startsWith("*")){let h=parseInt(f.substring(1),10);if(!isNaN(h)&&h>=0&&h<r.models.length){let m=r.models[h];for(let g=0;g<m.numFaces;g++)u.add(m.firstFace+g)}}}u.size>0&&(i=e.filter(d=>!u.has(d.faceIndex)))}let a={atlasSize:n.atlasSize??1024,lightmapPadding:n.lightmapPadding??1,hiddenClassnames:n.hiddenClassnames??new Set},o=[],s=new Map;i.forEach((u,d)=>{if(!u.lightmap)return;let{placement:f,atlas:h}=P1(o,u.lightmap,a);T1(h,f,u.lightmap),s.set(d,{atlasIndex:f.atlasIndex,offset:[(f.x+a.lightmapPadding)/a.atlasSize,(f.y+a.lightmapPadding)/a.atlasSize],scale:[f.width/a.atlasSize,f.height/a.atlasSize]})});let c=o.map(u=>{let d=new lt(t);return d.setParameters({wrapS:t.CLAMP_TO_EDGE,wrapT:t.CLAMP_TO_EDGE,minFilter:t.LINEAR,magFilter:t.LINEAR}),d.uploadImage(0,t.RGBA,u.width,u.height,0,t.RGBA,t.UNSIGNED_BYTE,u.data),{texture:d,width:u.width,height:u.height,pixels:u.data}});return{surfaces:i.map((u,d)=>{let f=s.get(d),h=B1(u,f),m=R1(u.indices,h.length/7),g=new Ce(t,t.STATIC_DRAW,t.ARRAY_BUFFER);g.upload(h);let p=new st(t,t.STATIC_DRAW);p.upload(m);let y=new Be(t);return y.configureAttributes(dd,g),{vao:y,vertexBuffer:g,indexBuffer:p,indexCount:m.length,vertexCount:h.length/7,texture:u.texture,surfaceFlags:u.surfaceFlags??yn,lightmap:f,vertexData:h,indexData:m}}),lightmaps:c}}function ba(t){let{normal:e,distance:r}=t,n=Math.sqrt(e.x*e.x+e.y*e.y+e.z*e.z);if(n===0)return t;let i=1/n;return{normal:{x:e.x*i,y:e.y*i,z:e.z*i},distance:r*i}}function sr(t){if(t.length!==16)throw new Error("View-projection matrix must contain 16 elements");let e=t[0],r=t[4],n=t[8],i=t[12],a=t[1],o=t[5],s=t[9],c=t[13],l=t[2],u=t[6],d=t[10],f=t[14],h=t[3],m=t[7],g=t[11],p=t[15];return[ba({normal:{x:h+e,y:m+r,z:g+n},distance:p+i}),ba({normal:{x:h-e,y:m-r,z:g-n},distance:p-i}),ba({normal:{x:h+a,y:m+o,z:g+s},distance:p+c}),ba({normal:{x:h-a,y:m-o,z:g-s},distance:p-c}),ba({normal:{x:h+l,y:m+u,z:g+d},distance:p+f}),ba({normal:{x:h-l,y:m-u,z:g-d},distance:p-f})]}function F1(t,e){return t.normal.x*e.x+t.normal.y*e.y+t.normal.z*e.z+t.distance}function Ei(t,e,r){for(let n of r){let i=n.normal.x>=0?e.x:t.x,a=n.normal.y>=0?e.y:t.y,o=n.normal.z>=0?e.z:t.z;if(F1(n,{x:i,y:a,z:o})<0)return!1}return!0}function hm(t,e,r){let n=(t.x+e.x)*.5,i=(t.y+e.y)*.5,a=(t.z+e.z)*.5,o=(e.x-t.x)*.5,s=(e.y-t.y)*.5,c=(e.z-t.z)*.5,l=r,u=l[0]*n+l[4]*i+l[8]*a+l[12],d=l[1]*n+l[5]*i+l[9]*a+l[13],f=l[2]*n+l[6]*i+l[10]*a+l[14],h=Math.abs(l[0])*o+Math.abs(l[4])*s+Math.abs(l[8])*c,m=Math.abs(l[1])*o+Math.abs(l[5])*s+Math.abs(l[9])*c,g=Math.abs(l[2])*o+Math.abs(l[6])*s+Math.abs(l[10])*c;return{mins:{x:u-h,y:d-m,z:f-g},maxs:{x:u+h,y:d+m,z:f+g}}}function fd(t){return t<0}function hd(t){return-t-1}function mm(t,e){return t.normal[0]*e.x+t.normal[1]*e.y+t.normal[2]*e.z-t.dist}function pd(t,e,r){if(!t||e<0||r<0)return!0;let n=Math.ceil(t.numClusters/8),i=t.clusters[e].pvs,a=Math.floor(r/8),o=1<<r%8;return a<0||a>=n?!1:(i[a]&o)!==0}function I1(t,e){let r={x:t.mins[0],y:t.mins[1],z:t.mins[2]},n={x:t.maxs[0],y:t.maxs[1],z:t.maxs[2]};return Ei(r,n,e)}function Li(t,e){if(t.models.length===0)return-1;let r=t.models[0].headNode;for(;r>=0;){let n=t.nodes[r],i=t.planes[n.planeIndex],o=mm(i,e)>=0?0:1,s=n.children[o];if(fd(s))return hd(s);r=s}return fd(r)?hd(r):-1}function D1(t,e){let r=t.leafs[e],n=[];for(let i=0;i<r.numLeafFaces;i+=1)n.push(t.leafLists.leafFaces[e][i]);return n}function md(t,e,r,n,i,a,o,s){if(fd(e)){let h=hd(e),m=t.leafs[h];if(s&&m.area>=0&&!s.has(m.area)||!pd(t.visibility,i,m.cluster)||!I1(m,n))return;let g={x:(m.mins[0]+m.maxs[0])*.5,y:(m.mins[1]+m.maxs[1])*.5,z:(m.mins[2]+m.maxs[2])*.5},p=g.x-r.x,y=g.y-r.y,v=g.z-r.z,b=-(p*p+y*y+v*v);for(let x of D1(t,h))o.has(x)||(o.add(x),a.push({faceIndex:x,leafIndex:h,sortKey:b}));return}let c=t.nodes[e],l=t.planes[c.planeIndex],u=mm(l,r),d=u>=0?c.children[0]:c.children[1],f=u>=0?c.children[1]:c.children[0];Ei({x:c.mins[0],y:c.mins[1],z:c.mins[2]},{x:c.maxs[0],y:c.maxs[1],z:c.maxs[2]},n)&&(md(t,d,r,n,i,a,o,s),md(t,f,r,n,i,a,o,s))}function gd(t,e,r){let n=new Set;if(e<0||e>=t.areas.length)return n;let i=[e];for(n.add(e);i.length>0;){let a=i.pop(),o=t.areas[a];for(let s=0;s<o.numAreaPortals;s++){let c=o.firstAreaPortal+s,l=t.areaPortals[c],u=l.otherArea;(l.portalNumber<=0||r[l.portalNumber])&&!n.has(u)&&(n.add(u),i.push(u))}}return n}function cn(t,e,r,n){let i=Li(t,e),a=i>=0?t.leafs[i]:null,o=a?a.cluster:-1,s=a?a.area:-1,c=null;n&&s>=0&&t.areas&&t.areas.length>0&&(c=gd(t,s,n));let l=[],u=new Set;if(t.models.length>0){let d=t.models[0].headNode;md(t,d,e,r,o,l,u,c)}return l}var Or=32,lc=class{constructor(){this.lights=[]}addLight(e,r){if(e.key!==void 0){let n=this.lights.findIndex(i=>i.key===e.key);if(n!==-1){this.lights[n]=e;return}}this.lights.push(e)}clear(){this.lights=[]}update(e,r=0){if(this.lights=this.lights.filter(n=>n.die>e),r>0)for(let n of this.lights)n.radiusSpeed!==void 0&&n.radiusSpeed!==0&&(n.intensity+=n.radiusSpeed*r,n.intensity<0&&(n.intensity=0))}getActiveLights(){return this.lights}};function xa(t){let e=[];for(let r=0;r<t.length;r+=3){let n=t[r],i=t[r+1],a=t[r+2];e.push(n,i,i,a,a,n)}return t instanceof Uint32Array||Math.max(...e)>65535?new Uint32Array(e):new Uint16Array(e)}var yd=`#version 300 es
142
142
  precision highp float;
143
143
 
144
144
  layout(location = 0) in vec3 a_position;
@@ -339,7 +339,7 @@ void main() {
339
339
  }
340
340
 
341
341
  o_color = finalColor;
342
- }`,pm=[0,255,255,255],k1=[0,-1,-1,-1];function xd(t=pm,e=[]){let r=new Float32Array(4);for(let n=0;n<4;n+=1){let i=t[n]??255;if(i===255){r[n]=0;continue}let a=e[i];r[n]=a!==void 0?a:1}return r}function U1(t){return[-(t*.25%1),0]}function vd(t=yn,e=0){let r=(t&el)!==0,n=(t&Yr)!==0,i=(t&bn)!==0,a=(t&xn)!==0,o=(t&vn)!==0,s=a?.33:o?.66:1,c=a||o||n,l=!c&&!i,u=r?U1(e):[0,0];return{alpha:s,blend:c,depthWrite:l,warp:n,flowOffset:u,sky:i}}var va=class{constructor(e){this.uniformDlights=[];this.gl=e,this.program=ce.create(e,{vertex:yd,fragment:bd},{a_position:0,a_texCoord:1,a_lightmapCoord:2,a_lightmapStep:3}),this.uniformMvp=this.program.getUniformLocation("u_modelViewProjection"),this.uniformTexScroll=this.program.getUniformLocation("u_texScroll"),this.uniformLmScroll=this.program.getUniformLocation("u_lightmapScroll"),this.uniformLightStyles=this.program.getUniformLocation("u_lightStyleFactors"),this.uniformStyleLayerMapping=this.program.getUniformLocation("u_styleLayerMapping"),this.uniformAlpha=this.program.getUniformLocation("u_alpha"),this.uniformApplyLightmap=this.program.getUniformLocation("u_applyLightmap"),this.uniformWarp=this.program.getUniformLocation("u_warp"),this.uniformLightmapOnly=this.program.getUniformLocation("u_lightmapOnly"),this.uniformDiffuse=this.program.getUniformLocation("u_diffuseMap"),this.uniformLightmap=this.program.getUniformLocation("u_lightmapAtlas"),this.uniformRefraction=this.program.getUniformLocation("u_refractionMap"),this.uniformHasRefraction=this.program.getUniformLocation("u_hasRefraction"),this.uniformTime=this.program.getUniformLocation("u_time"),this.uniformRenderMode=this.program.getUniformLocation("u_renderMode"),this.uniformSolidColor=this.program.getUniformLocation("u_solidColor"),this.uniformNumDlights=this.program.getUniformLocation("u_numDlights");for(let r=0;r<Or;r++)this.uniformDlights.push({pos:this.program.getUniformLocation(`u_dlights[${r}].position`),color:this.program.getUniformLocation(`u_dlights[${r}].color`),intensity:this.program.getUniformLocation(`u_dlights[${r}].intensity`)});this.uniformBrightness=this.program.getUniformLocation("u_brightness"),this.uniformGamma=this.program.getUniformLocation("u_gamma"),this.uniformFullbright=this.program.getUniformLocation("u_fullbright"),this.uniformAmbient=this.program.getUniformLocation("u_ambient")}get shaderSize(){return this.program.sourceSize}bind(e){let{modelViewProjection:r,styleIndices:n=pm,styleLayers:i=k1,styleValues:a=[],diffuseSampler:o=0,lightmapSampler:s,refractionSampler:c,surfaceFlags:l=yn,timeSeconds:u=0,texScroll:d,alpha:f,warp:h,dlights:m=[],renderMode:g,lightmapOnly:p,brightness:y=1,gamma:v=1,fullbright:b=!1,ambient:x=0}=e,_=vd(l,u),w=xd(n,a),S=d?d[0]:_.flowOffset[0],A=d?d[1]:_.flowOffset[1],T=f!==void 0?f:_.alpha,M=h!==void 0?h:_.warp;this.program.use(),this.gl.uniformMatrix4fv(this.uniformMvp,!1,r),this.gl.uniform2f(this.uniformTexScroll,S,A),this.gl.uniform2f(this.uniformLmScroll,_.flowOffset[0],_.flowOffset[1]),this.gl.uniform4fv(this.uniformLightStyles,w),this.gl.uniform4fv(this.uniformStyleLayerMapping,i),this.gl.uniform1f(this.uniformAlpha,T);let P=!_.sky&&s!==void 0&&!M;this.gl.uniform1i(this.uniformApplyLightmap,P?1:0),this.gl.uniform1i(this.uniformWarp,M?1:0),this.gl.uniform1i(this.uniformLightmapOnly,p?1:0),this.gl.uniform1f(this.uniformTime,u),this.gl.uniform1i(this.uniformDiffuse,o),this.gl.uniform1i(this.uniformLightmap,s??0),c!==void 0&&M?(this.gl.uniform1i(this.uniformRefraction,c),this.gl.uniform1i(this.uniformHasRefraction,1)):this.gl.uniform1i(this.uniformHasRefraction,0);let I=0,D=[1,1,1,1];g&&(g.mode==="solid"||g.mode==="wireframe"?I=1:g.mode==="solid-faceted"&&(I=2),g.color?D=[...g.color]:g.generateRandomColor&&(D=[1,1,1,1])),this.gl.uniform1i(this.uniformRenderMode,I),this.gl.uniform4f(this.uniformSolidColor,D[0],D[1],D[2],D[3]);let B=Math.min(m.length,Or);this.gl.uniform1i(this.uniformNumDlights,B);for(let O=0;O<B;O++){let Q=m[O];this.gl.uniform3f(this.uniformDlights[O].pos,Q.origin.x,Q.origin.y,Q.origin.z),this.gl.uniform3f(this.uniformDlights[O].color,Q.color.x,Q.color.y,Q.color.z),this.gl.uniform1f(this.uniformDlights[O].intensity,Q.intensity)}return this.gl.uniform1f(this.uniformBrightness,y),this.gl.uniform1f(this.uniformGamma,v),this.gl.uniform1i(this.uniformFullbright,b?1:0),this.gl.uniform1f(this.uniformAmbient,x),_}draw(e,r){if(e.vao.bind(),r&&r.mode==="wireframe"){if(!e.wireframeIndexBuffer){let n=e;n.wireframeIndexBuffer=new st(this.gl,this.gl.STATIC_DRAW);let i=xa(e.indexData);n.wireframeIndexBuffer.upload(i),n.wireframeIndexCount=i.length}e.wireframeIndexBuffer.bind(),this.gl.drawElements(this.gl.LINES,e.wireframeIndexCount,this.gl.UNSIGNED_SHORT,0)}else e.indexBuffer.bind(),this.gl.drawElements(this.gl.TRIANGLES,e.indexCount,this.gl.UNSIGNED_SHORT,0)}dispose(){this.program.dispose()}};function ds(t,e){t.depthMask(e.depthWrite),e.blend?(t.enable(t.BLEND),t.blendFunc(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA)):t.disable(t.BLEND)}var gm=new Float32Array([-1,-1,1,1,-1,1,1,1,1,-1,-1,1,1,1,1,-1,1,1,-1,-1,-1,-1,1,-1,1,1,-1,-1,-1,-1,1,1,-1,1,-1,-1,-1,-1,-1,-1,-1,1,-1,1,1,-1,-1,-1,-1,1,1,-1,1,-1,1,-1,-1,1,1,-1,1,1,1,1,-1,-1,1,1,1,1,-1,1,-1,1,-1,-1,1,1,1,1,1,-1,1,-1,1,1,1,1,1,-1,-1,-1,-1,1,-1,-1,1,-1,1,-1,-1,-1,1,-1,1,-1,-1,1]),_d=`#version 300 es
342
+ }`,pm=[0,255,255,255],k1=[0,-1,-1,-1];function xd(t=pm,e=[]){let r=new Float32Array(4);for(let n=0;n<4;n+=1){let i=t[n]??255;if(i===255){r[n]=0;continue}let a=e[i];r[n]=a!==void 0?a:1}return r}function U1(t){return[-(t*.25%1),0]}function vd(t=yn,e=0){let r=(t&el)!==0,n=(t&Yr)!==0,i=(t&bn)!==0,a=(t&xn)!==0,o=(t&vn)!==0,s=a?.33:o?.66:1,c=a||o||n,l=!c&&!i,u=r?U1(e):[0,0];return{alpha:s,blend:c,depthWrite:l,warp:n,flowOffset:u,sky:i}}var va=class{constructor(e){this.uniformDlights=[];this.gl=e,this.program=ce.create(e,{vertex:yd,fragment:bd},{a_position:0,a_texCoord:1,a_lightmapCoord:2,a_lightmapStep:3}),this.uniformMvp=this.program.getUniformLocation("u_modelViewProjection"),this.uniformTexScroll=this.program.getUniformLocation("u_texScroll"),this.uniformLmScroll=this.program.getUniformLocation("u_lightmapScroll"),this.uniformLightStyles=this.program.getUniformLocation("u_lightStyleFactors"),this.uniformStyleLayerMapping=this.program.getUniformLocation("u_styleLayerMapping"),this.uniformAlpha=this.program.getUniformLocation("u_alpha"),this.uniformApplyLightmap=this.program.getUniformLocation("u_applyLightmap"),this.uniformWarp=this.program.getUniformLocation("u_warp"),this.uniformLightmapOnly=this.program.getUniformLocation("u_lightmapOnly"),this.uniformDiffuse=this.program.getUniformLocation("u_diffuseMap"),this.uniformLightmap=this.program.getUniformLocation("u_lightmapAtlas"),this.uniformRefraction=this.program.getUniformLocation("u_refractionMap"),this.uniformHasRefraction=this.program.getUniformLocation("u_hasRefraction"),this.uniformTime=this.program.getUniformLocation("u_time"),this.uniformRenderMode=this.program.getUniformLocation("u_renderMode"),this.uniformSolidColor=this.program.getUniformLocation("u_solidColor"),this.uniformNumDlights=this.program.getUniformLocation("u_numDlights");for(let r=0;r<Or;r++)this.uniformDlights.push({pos:this.program.getUniformLocation(`u_dlights[${r}].position`),color:this.program.getUniformLocation(`u_dlights[${r}].color`),intensity:this.program.getUniformLocation(`u_dlights[${r}].intensity`)});this.uniformBrightness=this.program.getUniformLocation("u_brightness"),this.uniformGamma=this.program.getUniformLocation("u_gamma"),this.uniformFullbright=this.program.getUniformLocation("u_fullbright"),this.uniformAmbient=this.program.getUniformLocation("u_ambient")}get shaderSize(){return this.program.sourceSize}bind(e){let{modelViewProjection:r,styleIndices:n=pm,styleLayers:i=k1,styleValues:a=[],diffuseSampler:o=0,lightmapSampler:s,refractionSampler:c,surfaceFlags:l=yn,timeSeconds:u=0,texScroll:d,alpha:f,warp:h,dlights:m=[],renderMode:g,lightmapOnly:p,brightness:y=1,gamma:v=1,fullbright:b=!1,ambient:x=0}=e,_=vd(l,u),w=xd(n,a),S=d?d[0]:_.flowOffset[0],A=d?d[1]:_.flowOffset[1],L=f!==void 0?f:_.alpha,M=h!==void 0?h:_.warp;this.program.use(),this.gl.uniformMatrix4fv(this.uniformMvp,!1,r),this.gl.uniform2f(this.uniformTexScroll,S,A),this.gl.uniform2f(this.uniformLmScroll,_.flowOffset[0],_.flowOffset[1]),this.gl.uniform4fv(this.uniformLightStyles,w),this.gl.uniform4fv(this.uniformStyleLayerMapping,i),this.gl.uniform1f(this.uniformAlpha,L);let P=!_.sky&&s!==void 0&&!M;this.gl.uniform1i(this.uniformApplyLightmap,P?1:0),this.gl.uniform1i(this.uniformWarp,M?1:0),this.gl.uniform1i(this.uniformLightmapOnly,p?1:0),this.gl.uniform1f(this.uniformTime,u),this.gl.uniform1i(this.uniformDiffuse,o),this.gl.uniform1i(this.uniformLightmap,s??0),c!==void 0&&M?(this.gl.uniform1i(this.uniformRefraction,c),this.gl.uniform1i(this.uniformHasRefraction,1)):this.gl.uniform1i(this.uniformHasRefraction,0);let I=0,D=[1,1,1,1];g&&(g.mode==="solid"||g.mode==="wireframe"?I=1:g.mode==="solid-faceted"&&(I=2),g.color?D=[...g.color]:g.generateRandomColor&&(D=[1,1,1,1])),this.gl.uniform1i(this.uniformRenderMode,I),this.gl.uniform4f(this.uniformSolidColor,D[0],D[1],D[2],D[3]);let B=Math.min(m.length,Or);this.gl.uniform1i(this.uniformNumDlights,B);for(let O=0;O<B;O++){let Q=m[O];this.gl.uniform3f(this.uniformDlights[O].pos,Q.origin.x,Q.origin.y,Q.origin.z),this.gl.uniform3f(this.uniformDlights[O].color,Q.color.x,Q.color.y,Q.color.z),this.gl.uniform1f(this.uniformDlights[O].intensity,Q.intensity)}return this.gl.uniform1f(this.uniformBrightness,y),this.gl.uniform1f(this.uniformGamma,v),this.gl.uniform1i(this.uniformFullbright,b?1:0),this.gl.uniform1f(this.uniformAmbient,x),_}draw(e,r){if(e.vao.bind(),r&&r.mode==="wireframe"){if(!e.wireframeIndexBuffer){let n=e;n.wireframeIndexBuffer=new st(this.gl,this.gl.STATIC_DRAW);let i=xa(e.indexData);n.wireframeIndexBuffer.upload(i),n.wireframeIndexCount=i.length}e.wireframeIndexBuffer.bind(),this.gl.drawElements(this.gl.LINES,e.wireframeIndexCount,this.gl.UNSIGNED_SHORT,0)}else e.indexBuffer.bind(),this.gl.drawElements(this.gl.TRIANGLES,e.indexCount,this.gl.UNSIGNED_SHORT,0)}dispose(){this.program.dispose()}};function ds(t,e){t.depthMask(e.depthWrite),e.blend?(t.enable(t.BLEND),t.blendFunc(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA)):t.disable(t.BLEND)}var gm=new Float32Array([-1,-1,1,1,-1,1,1,1,1,-1,-1,1,1,1,1,-1,1,1,-1,-1,-1,-1,1,-1,1,1,-1,-1,-1,-1,1,1,-1,1,-1,-1,-1,-1,-1,-1,-1,1,-1,1,1,-1,-1,-1,-1,1,1,-1,1,-1,1,-1,-1,1,1,-1,1,1,1,1,-1,-1,1,1,1,1,-1,1,-1,1,-1,-1,1,1,1,1,1,-1,1,-1,1,1,1,1,1,-1,-1,-1,-1,1,-1,-1,1,-1,1,-1,-1,-1,1,-1,1,-1,-1,1]),_d=`#version 300 es
343
343
  precision highp float;
344
344
 
345
345
  layout(location = 0) in vec3 a_position;
@@ -350,23 +350,28 @@ uniform vec2 u_scroll;
350
350
  out vec3 v_direction;
351
351
 
352
352
  void main() {
353
- // Transform Quake-space position/direction to GL-space direction for cubemap sampling.
354
- // Quake Basis: X(Fwd), Y(Left), Z(Up)
355
- // GL Basis (Cubemap): -Z(Front), -X(Left), +Y(Top)
356
- // Mapping:
357
- // Quake X (1,0,0) -> GL -Z (0,0,-1)
358
- // Quake Y (0,1,0) -> GL -X (-1,0,0)
359
- // Quake Z (0,0,1) -> GL Y (0,1,0)
360
- vec3 dir = vec3(-a_position.y, a_position.z, -a_position.x);
361
-
362
- // Normalize just in case, though a_position is on a cube surface.
363
- // Actually, for a cubemap lookup, normalization isn't strictly required by the hardware
364
- // (it grabs the vector direction), but good practice if we modify it.
365
- dir = normalize(dir);
366
-
353
+ // The cube vertices (a_position) are in GL space (-1 to 1, standard OpenGL cube).
354
+ // The viewProjection matrix expects Quake-space input (it contains Quake-to-GL transform).
355
+ // So we must transform GL -> Quake before applying the view matrix.
356
+ //
357
+ // GL-to-Quake mapping (inverse of Quake-to-GL):
358
+ // GL -Z -> Quake +X (forward)
359
+ // GL -X -> Quake +Y (left)
360
+ // GL +Y -> Quake +Z (up)
361
+ // So: (gl.x, gl.y, gl.z) -> (-gl.z, -gl.x, gl.y)
362
+ vec3 quakePos = vec3(-a_position.z, -a_position.x, a_position.y);
363
+ vec4 pos = u_viewProjectionNoTranslation * vec4(quakePos, 1.0);
364
+ // Force z = w to render at far plane, avoiding clipping issues
365
+ // for triangles that intersect the camera plane
366
+ gl_Position = pos.xyww;
367
+
368
+ // For cubemap sampling, use the original GL-space position since
369
+ // WebGL cubemap targets (POSITIVE_X, etc.) are in GL conventions.
370
+ vec3 dir = a_position;
371
+
372
+ // Apply scroll offset for animated skies
367
373
  dir.xy += u_scroll;
368
374
  v_direction = dir;
369
- gl_Position = u_viewProjectionNoTranslation * vec4(a_position, 1.0);
370
375
  }`,Sd=`#version 300 es
371
376
  precision highp float;
372
377
 
@@ -377,7 +382,7 @@ out vec4 o_color;
377
382
 
378
383
  void main() {
379
384
  o_color = texture(u_skybox, v_direction);
380
- }`,_a=class{constructor(e){this.gl=e,this.program=ce.create(e,{vertex:_d,fragment:Sd},{a_position:0}),this.vao=new Be(e),this.vbo=new Ce(e,e.STATIC_DRAW),this.vbo.upload(gm,e.STATIC_DRAW);let r=[{index:0,size:3,type:e.FLOAT,stride:12,offset:0}];this.vao.configureAttributes(r,this.vbo),this.uniformViewProj=this.program.getUniformLocation("u_viewProjectionNoTranslation"),this.uniformScroll=this.program.getUniformLocation("u_scroll"),this.uniformSampler=this.program.getUniformLocation("u_skybox"),this.cubemap=new ya(e),this.cubemap.setParameters({minFilter:e.LINEAR,magFilter:e.LINEAR,wrapS:e.CLAMP_TO_EDGE,wrapT:e.CLAMP_TO_EDGE})}get shaderSize(){return this.program.sourceSize}bind(e){let{viewProjection:r,scroll:n,textureUnit:i=0}=e;this.program.use(),this.gl.depthMask(!1),this.gl.uniformMatrix4fv(this.uniformViewProj,!1,r),this.gl.uniform2f(this.uniformScroll,n[0],n[1]),this.gl.uniform1i(this.uniformSampler,i),this.cubemap.bind(i),this.vao.bind()}draw(){this.gl.drawArrays(this.gl.TRIANGLES,0,gm.length/3)}dispose(){this.vbo.dispose(),this.vao.dispose(),this.cubemap.dispose(),this.program.dispose()}};function Sa(t){let e=new Float32Array(t);return e[12]=0,e[13]=0,e[14]=0,e}function Li(t,e=[.01,.02]){let[r,n]=e;return[r*t,n*t]}var Md=`#version 300 es
385
+ }`,_a=class{constructor(e){this.gl=e,this.program=ce.create(e,{vertex:_d,fragment:Sd},{a_position:0}),this.vao=new Be(e),this.vbo=new Ce(e,e.STATIC_DRAW),this.vbo.upload(gm,e.STATIC_DRAW);let r=[{index:0,size:3,type:e.FLOAT,stride:12,offset:0}];this.vao.configureAttributes(r,this.vbo),this.uniformViewProj=this.program.getUniformLocation("u_viewProjectionNoTranslation"),this.uniformScroll=this.program.getUniformLocation("u_scroll"),this.uniformSampler=this.program.getUniformLocation("u_skybox"),this.cubemap=new ya(e),this.cubemap.setParameters({minFilter:e.LINEAR,magFilter:e.LINEAR,wrapS:e.CLAMP_TO_EDGE,wrapT:e.CLAMP_TO_EDGE})}get shaderSize(){return this.program.sourceSize}bind(e){let{viewProjection:r,scroll:n,textureUnit:i=0}=e;this.program.use(),this.gl.enable(this.gl.DEPTH_TEST),this.gl.depthFunc(this.gl.LEQUAL),this.gl.depthMask(!1),this.gl.disable(this.gl.CULL_FACE),this.gl.uniformMatrix4fv(this.uniformViewProj,!1,r),this.gl.uniform2f(this.uniformScroll,n[0],n[1]),this.gl.uniform1i(this.uniformSampler,i),this.cubemap.bind(i),this.vao.bind()}draw(){this.gl.drawArrays(this.gl.TRIANGLES,0,gm.length/3)}dispose(){this.vbo.dispose(),this.vao.dispose(),this.cubemap.dispose(),this.program.dispose()}};function Sa(t){let e=new Float32Array(t);return e[12]=0,e[13]=0,e[14]=0,e}function Ti(t,e=[.01,.02]){let[r,n]=e;return[r*t,n*t]}var Md=`#version 300 es
381
386
  precision highp float;
382
387
 
383
388
  layout(location = 0) in vec3 a_position;
@@ -489,7 +494,7 @@ void main() {
489
494
  }
490
495
 
491
496
  o_color = finalColor;
492
- }`;function z1(t){let e=t.x*t.x+t.y*t.y+t.z*t.z;if(e<=0)return{x:0,y:0,z:1};let r=1/Math.sqrt(e);return{x:t.x*r,y:t.y*r,z:t.z*r}}function wd(t,e,r){return t+(e-t)*r}function ym(t,e,r){return{x:wd(t.x,e.x,r),y:wd(t.y,e.y,r),z:wd(t.z,e.z,r)}}function O1(t,e,r){return[t/r.skinWidth,1-e/r.skinHeight]}function Ed(t){if(t.glCommands.length===0){let n=[],i=[];return t.triangles.forEach(a=>{let o=n.length;for(let s=0;s<3;s+=1){let c=a.vertexIndices[s],l=a.texCoordIndices[s],u=t.texCoords[l];n.push({vertexIndex:c,texCoord:O1(u.s,u.t,t.header)})}i.push(o,o+1,o+2)}),{vertices:n,indices:new Uint16Array(i)}}let e=[],r=[];for(let n of t.glCommands){let i=e.length;if(e.push(...n.vertices.map(a=>({vertexIndex:a.vertexIndex,texCoord:[a.s,1-a.t]}))),n.mode==="strip")for(let a=0;a<n.vertices.length-2;a+=1){let o=a%2===0,s=i+a+(o?0:1),c=i+a+(o?1:0),l=i+a+2;r.push(s,c,l)}else for(let a=1;a<n.vertices.length-1;a+=1)r.push(i,i+a,i+a+1)}return{vertices:e,indices:new Uint16Array(r)}}function Td(t,e,r){let{frame0:n,frame1:i,lerp:a}=r,o=t.frames[n],s=t.frames[i];if(!o||!s)throw new Error("Requested MD2 frames are out of range");let c=new Float32Array(e.vertices.length*8);return e.vertices.forEach((l,u)=>{let d=o.vertices[l.vertexIndex],f=s.vertices[l.vertexIndex];if(!d||!f)throw new Error("MD2 vertex index out of range for frame");let h=ym(d.position,f.position,a),m=z1(ym(d.normal,f.normal,a)),g=u*8;c[g]=h.x,c[g+1]=h.y,c[g+2]=h.z,c[g+3]=m.x,c[g+4]=m.y,c[g+5]=m.z,c[g+6]=l.texCoord[0],c[g+7]=l.texCoord[1]}),c}var wa=class{constructor(e,r,n){this.gl=e,this.geometry=Ed(r),this.vertexBuffer=new Ce(e,e.STATIC_DRAW),this.indexBuffer=new st(e,e.STATIC_DRAW),this.vertexArray=new Be(e),this.indexCount=this.geometry.indices.length,this.vertexArray.configureAttributes([{index:0,size:3,type:e.FLOAT,stride:32,offset:0},{index:1,size:3,type:e.FLOAT,stride:32,offset:12},{index:2,size:2,type:e.FLOAT,stride:32,offset:24}],this.vertexBuffer),this.vertexArray.bind(),this.indexBuffer.bind(),this.indexBuffer.upload(this.geometry.indices,e.STATIC_DRAW),this.update(r,n)}update(e,r){let n=Td(e,this.geometry,r);this.vertexBuffer.upload(n,this.gl.STATIC_DRAW)}bind(){this.vertexArray.bind(),this.indexBuffer.bind()}dispose(){this.vertexBuffer.dispose(),this.indexBuffer.dispose(),this.vertexArray.dispose(),this.wireframeIndexBuffer?.dispose()}},Ma=class{constructor(e){this.uniformDlights=[];this.gl=e,this.program=ce.create(e,{vertex:Md,fragment:Ad},{a_position:0,a_normal:1,a_texCoord:2}),this.uniformMvp=this.program.getUniformLocation("u_modelViewProjection"),this.uniformModelMatrix=this.program.getUniformLocation("u_modelMatrix"),this.uniformLightDir=this.program.getUniformLocation("u_lightDir"),this.uniformAmbient=this.program.getUniformLocation("u_ambient"),this.uniformTint=this.program.getUniformLocation("u_tint"),this.uniformDiffuse=this.program.getUniformLocation("u_diffuseMap"),this.uniformRenderMode=this.program.getUniformLocation("u_renderMode"),this.uniformSolidColor=this.program.getUniformLocation("u_solidColor"),this.uniformNumDlights=this.program.getUniformLocation("u_numDlights");for(let r=0;r<Or;r++)this.uniformDlights.push({pos:this.program.getUniformLocation(`u_dlights[${r}].position`),color:this.program.getUniformLocation(`u_dlights[${r}].color`),intensity:this.program.getUniformLocation(`u_dlights[${r}].intensity`)});this.uniformBrightness=this.program.getUniformLocation("u_brightness"),this.uniformGamma=this.program.getUniformLocation("u_gamma"),this.uniformFullbright=this.program.getUniformLocation("u_fullbright"),this.uniformGlobalAmbient=this.program.getUniformLocation("u_globalAmbient")}get shaderSize(){return this.program.sourceSize}bind(e){let{modelViewProjection:r,modelMatrix:n,lightDirection:i=[0,0,1],ambientLight:a=.2,tint:o=[1,1,1,1],diffuseSampler:s=0,dlights:c=[],renderMode:l,brightness:u=1,gamma:d=1,fullbright:f=!1,ambient:h=0}=e,m=new Float32Array(i),g=new Float32Array(o);this.program.use(),this.gl.uniformMatrix4fv(this.uniformMvp,!1,r),n?this.gl.uniformMatrix4fv(this.uniformModelMatrix,!1,n):this.gl.uniformMatrix4fv(this.uniformModelMatrix,!1,new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1])),this.gl.uniform3fv(this.uniformLightDir,m),this.gl.uniform1f(this.uniformAmbient,a),this.gl.uniform4fv(this.uniformTint,g),this.gl.uniform1i(this.uniformDiffuse,s);let p=0,y=[1,1,1,1];l&&(l.mode==="solid"||l.mode==="wireframe"?p=1:l.mode==="solid-faceted"&&(p=2),l.color?y=[...l.color]:l.generateRandomColor),this.gl.uniform1i(this.uniformRenderMode,p),this.gl.uniform4f(this.uniformSolidColor,y[0],y[1],y[2],y[3]);let v=Math.min(c.length,Or);this.gl.uniform1i(this.uniformNumDlights,v);for(let b=0;b<v;b++){let x=c[b];this.gl.uniform3f(this.uniformDlights[b].pos,x.origin.x,x.origin.y,x.origin.z),this.gl.uniform3f(this.uniformDlights[b].color,x.color.x,x.color.y,x.color.z),this.gl.uniform1f(this.uniformDlights[b].intensity,x.intensity)}this.gl.uniform1f(this.uniformBrightness,u),this.gl.uniform1f(this.uniformGamma,d),this.gl.uniform1i(this.uniformFullbright,f?1:0),this.gl.uniform1f(this.uniformGlobalAmbient,h)}draw(e,r){if(e.vertexArray.bind(),r&&r.mode==="wireframe"){if(!e.wireframeIndexBuffer){e.wireframeIndexBuffer=new st(this.gl,this.gl.STATIC_DRAW);let n=xa(e.geometry.indices);e.wireframeIndexBuffer.upload(n),e.wireframeIndexCount=n.length}e.wireframeIndexBuffer.bind(),this.gl.drawElements(this.gl.LINES,e.wireframeIndexCount,this.gl.UNSIGNED_SHORT,0)}else e.indexBuffer.bind(),this.gl.drawElements(this.gl.TRIANGLES,e.indexCount,this.gl.UNSIGNED_SHORT,0)}dispose(){this.program.dispose()}};var G=1e-6,xe=typeof Float32Array<"u"?Float32Array:Array,lr=Math.random,bm="zyx";function un(t){return t>=0?Math.round(t):t%.5===0?Math.floor(t):Math.round(t)}var pL=Math.PI/180,gL=180/Math.PI;var hs={};zi(hs,{add:()=>lb,adjoint:()=>Y1,clone:()=>G1,copy:()=>V1,create:()=>Ld,determinant:()=>q1,equals:()=>fb,exactEquals:()=>db,frob:()=>sb,fromMat2d:()=>rb,fromMat4:()=>N1,fromQuat:()=>nb,fromRotation:()=>eb,fromScaling:()=>tb,fromTranslation:()=>J1,fromValues:()=>H1,identity:()=>X1,invert:()=>K1,mul:()=>hb,multiply:()=>xm,multiplyScalar:()=>cb,multiplyScalarAndAdd:()=>ub,normalFromMat4:()=>ib,projection:()=>ab,rotate:()=>j1,scale:()=>Q1,set:()=>W1,str:()=>ob,sub:()=>mb,subtract:()=>vm,translate:()=>Z1,transpose:()=>$1});function Ld(){var t=new xe(9);return xe!=Float32Array&&(t[1]=0,t[2]=0,t[3]=0,t[5]=0,t[6]=0,t[7]=0),t[0]=1,t[4]=1,t[8]=1,t}function N1(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[4],t[4]=e[5],t[5]=e[6],t[6]=e[8],t[7]=e[9],t[8]=e[10],t}function G1(t){var e=new xe(9);return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],e}function V1(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[4]=e[4],t[5]=e[5],t[6]=e[6],t[7]=e[7],t[8]=e[8],t}function H1(t,e,r,n,i,a,o,s,c){var l=new xe(9);return l[0]=t,l[1]=e,l[2]=r,l[3]=n,l[4]=i,l[5]=a,l[6]=o,l[7]=s,l[8]=c,l}function W1(t,e,r,n,i,a,o,s,c,l){return t[0]=e,t[1]=r,t[2]=n,t[3]=i,t[4]=a,t[5]=o,t[6]=s,t[7]=c,t[8]=l,t}function X1(t){return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=1,t[5]=0,t[6]=0,t[7]=0,t[8]=1,t}function $1(t,e){if(t===e){var r=e[1],n=e[2],i=e[5];t[1]=e[3],t[2]=e[6],t[3]=r,t[5]=e[7],t[6]=n,t[7]=i}else t[0]=e[0],t[1]=e[3],t[2]=e[6],t[3]=e[1],t[4]=e[4],t[5]=e[7],t[6]=e[2],t[7]=e[5],t[8]=e[8];return t}function K1(t,e){var r=e[0],n=e[1],i=e[2],a=e[3],o=e[4],s=e[5],c=e[6],l=e[7],u=e[8],d=u*o-s*l,f=-u*a+s*c,h=l*a-o*c,m=r*d+n*f+i*h;return m?(m=1/m,t[0]=d*m,t[1]=(-u*n+i*l)*m,t[2]=(s*n-i*o)*m,t[3]=f*m,t[4]=(u*r-i*c)*m,t[5]=(-s*r+i*a)*m,t[6]=h*m,t[7]=(-l*r+n*c)*m,t[8]=(o*r-n*a)*m,t):null}function Y1(t,e){var r=e[0],n=e[1],i=e[2],a=e[3],o=e[4],s=e[5],c=e[6],l=e[7],u=e[8];return t[0]=o*u-s*l,t[1]=i*l-n*u,t[2]=n*s-i*o,t[3]=s*c-a*u,t[4]=r*u-i*c,t[5]=i*a-r*s,t[6]=a*l-o*c,t[7]=n*c-r*l,t[8]=r*o-n*a,t}function q1(t){var e=t[0],r=t[1],n=t[2],i=t[3],a=t[4],o=t[5],s=t[6],c=t[7],l=t[8];return e*(l*a-o*c)+r*(-l*i+o*s)+n*(c*i-a*s)}function xm(t,e,r){var n=e[0],i=e[1],a=e[2],o=e[3],s=e[4],c=e[5],l=e[6],u=e[7],d=e[8],f=r[0],h=r[1],m=r[2],g=r[3],p=r[4],y=r[5],v=r[6],b=r[7],x=r[8];return t[0]=f*n+h*o+m*l,t[1]=f*i+h*s+m*u,t[2]=f*a+h*c+m*d,t[3]=g*n+p*o+y*l,t[4]=g*i+p*s+y*u,t[5]=g*a+p*c+y*d,t[6]=v*n+b*o+x*l,t[7]=v*i+b*s+x*u,t[8]=v*a+b*c+x*d,t}function Z1(t,e,r){var n=e[0],i=e[1],a=e[2],o=e[3],s=e[4],c=e[5],l=e[6],u=e[7],d=e[8],f=r[0],h=r[1];return t[0]=n,t[1]=i,t[2]=a,t[3]=o,t[4]=s,t[5]=c,t[6]=f*n+h*o+l,t[7]=f*i+h*s+u,t[8]=f*a+h*c+d,t}function j1(t,e,r){var n=e[0],i=e[1],a=e[2],o=e[3],s=e[4],c=e[5],l=e[6],u=e[7],d=e[8],f=Math.sin(r),h=Math.cos(r);return t[0]=h*n+f*o,t[1]=h*i+f*s,t[2]=h*a+f*c,t[3]=h*o-f*n,t[4]=h*s-f*i,t[5]=h*c-f*a,t[6]=l,t[7]=u,t[8]=d,t}function Q1(t,e,r){var n=r[0],i=r[1];return t[0]=n*e[0],t[1]=n*e[1],t[2]=n*e[2],t[3]=i*e[3],t[4]=i*e[4],t[5]=i*e[5],t[6]=e[6],t[7]=e[7],t[8]=e[8],t}function J1(t,e){return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=1,t[5]=0,t[6]=e[0],t[7]=e[1],t[8]=1,t}function eb(t,e){var r=Math.sin(e),n=Math.cos(e);return t[0]=n,t[1]=r,t[2]=0,t[3]=-r,t[4]=n,t[5]=0,t[6]=0,t[7]=0,t[8]=1,t}function tb(t,e){return t[0]=e[0],t[1]=0,t[2]=0,t[3]=0,t[4]=e[1],t[5]=0,t[6]=0,t[7]=0,t[8]=1,t}function rb(t,e){return t[0]=e[0],t[1]=e[1],t[2]=0,t[3]=e[2],t[4]=e[3],t[5]=0,t[6]=e[4],t[7]=e[5],t[8]=1,t}function nb(t,e){var r=e[0],n=e[1],i=e[2],a=e[3],o=r+r,s=n+n,c=i+i,l=r*o,u=n*o,d=n*s,f=i*o,h=i*s,m=i*c,g=a*o,p=a*s,y=a*c;return t[0]=1-d-m,t[3]=u-y,t[6]=f+p,t[1]=u+y,t[4]=1-l-m,t[7]=h-g,t[2]=f-p,t[5]=h+g,t[8]=1-l-d,t}function ib(t,e){var r=e[0],n=e[1],i=e[2],a=e[3],o=e[4],s=e[5],c=e[6],l=e[7],u=e[8],d=e[9],f=e[10],h=e[11],m=e[12],g=e[13],p=e[14],y=e[15],v=r*s-n*o,b=r*c-i*o,x=r*l-a*o,_=n*c-i*s,w=n*l-a*s,S=i*l-a*c,A=u*g-d*m,T=u*p-f*m,M=u*y-h*m,P=d*p-f*g,I=d*y-h*g,D=f*y-h*p,B=v*D-b*I+x*P+_*M-w*T+S*A;return B?(B=1/B,t[0]=(s*D-c*I+l*P)*B,t[1]=(c*M-o*D-l*T)*B,t[2]=(o*I-s*M+l*A)*B,t[3]=(i*I-n*D-a*P)*B,t[4]=(r*D-i*M+a*T)*B,t[5]=(n*M-r*I-a*A)*B,t[6]=(g*S-p*w+y*_)*B,t[7]=(p*x-m*S-y*b)*B,t[8]=(m*w-g*x+y*v)*B,t):null}function ab(t,e,r){return t[0]=2/e,t[1]=0,t[2]=0,t[3]=0,t[4]=-2/r,t[5]=0,t[6]=-1,t[7]=1,t[8]=1,t}function ob(t){return"mat3("+t[0]+", "+t[1]+", "+t[2]+", "+t[3]+", "+t[4]+", "+t[5]+", "+t[6]+", "+t[7]+", "+t[8]+")"}function sb(t){return Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]+t[3]*t[3]+t[4]*t[4]+t[5]*t[5]+t[6]*t[6]+t[7]*t[7]+t[8]*t[8])}function lb(t,e,r){return t[0]=e[0]+r[0],t[1]=e[1]+r[1],t[2]=e[2]+r[2],t[3]=e[3]+r[3],t[4]=e[4]+r[4],t[5]=e[5]+r[5],t[6]=e[6]+r[6],t[7]=e[7]+r[7],t[8]=e[8]+r[8],t}function vm(t,e,r){return t[0]=e[0]-r[0],t[1]=e[1]-r[1],t[2]=e[2]-r[2],t[3]=e[3]-r[3],t[4]=e[4]-r[4],t[5]=e[5]-r[5],t[6]=e[6]-r[6],t[7]=e[7]-r[7],t[8]=e[8]-r[8],t}function cb(t,e,r){return t[0]=e[0]*r,t[1]=e[1]*r,t[2]=e[2]*r,t[3]=e[3]*r,t[4]=e[4]*r,t[5]=e[5]*r,t[6]=e[6]*r,t[7]=e[7]*r,t[8]=e[8]*r,t}function ub(t,e,r,n){return t[0]=e[0]+r[0]*n,t[1]=e[1]+r[1]*n,t[2]=e[2]+r[2]*n,t[3]=e[3]+r[3]*n,t[4]=e[4]+r[4]*n,t[5]=e[5]+r[5]*n,t[6]=e[6]+r[6]*n,t[7]=e[7]+r[7]*n,t[8]=e[8]+r[8]*n,t}function db(t,e){return t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2]&&t[3]===e[3]&&t[4]===e[4]&&t[5]===e[5]&&t[6]===e[6]&&t[7]===e[7]&&t[8]===e[8]}function fb(t,e){var r=t[0],n=t[1],i=t[2],a=t[3],o=t[4],s=t[5],c=t[6],l=t[7],u=t[8],d=e[0],f=e[1],h=e[2],m=e[3],g=e[4],p=e[5],y=e[6],v=e[7],b=e[8];return Math.abs(r-d)<=G*Math.max(1,Math.abs(r),Math.abs(d))&&Math.abs(n-f)<=G*Math.max(1,Math.abs(n),Math.abs(f))&&Math.abs(i-h)<=G*Math.max(1,Math.abs(i),Math.abs(h))&&Math.abs(a-m)<=G*Math.max(1,Math.abs(a),Math.abs(m))&&Math.abs(o-g)<=G*Math.max(1,Math.abs(o),Math.abs(g))&&Math.abs(s-p)<=G*Math.max(1,Math.abs(s),Math.abs(p))&&Math.abs(c-y)<=G*Math.max(1,Math.abs(c),Math.abs(y))&&Math.abs(l-v)<=G*Math.max(1,Math.abs(l),Math.abs(v))&&Math.abs(u-b)<=G*Math.max(1,Math.abs(u),Math.abs(b))}var hb=xm,mb=vm;var F={};zi(F,{add:()=>Jb,adjoint:()=>Sb,clone:()=>gb,copy:()=>yb,create:()=>pb,decompose:()=>Ob,determinant:()=>wb,equals:()=>nx,exactEquals:()=>rx,frob:()=>Qb,fromQuat:()=>Vb,fromQuat2:()=>kb,fromRotation:()=>Bb,fromRotationTranslation:()=>wm,fromRotationTranslationScale:()=>Nb,fromRotationTranslationScaleOrigin:()=>Gb,fromScaling:()=>Cb,fromTranslation:()=>Rb,fromValues:()=>bb,fromXRotation:()=>Fb,fromYRotation:()=>Ib,fromZRotation:()=>Db,frustum:()=>Hb,getRotation:()=>zb,getScaling:()=>Mm,getTranslation:()=>Ub,identity:()=>_m,invert:()=>_b,lookAt:()=>qb,mul:()=>ix,multiply:()=>Sm,multiplyScalar:()=>ex,multiplyScalarAndAdd:()=>tx,ortho:()=>Kb,orthoNO:()=>Em,orthoZO:()=>Yb,perspective:()=>Wb,perspectiveFromFieldOfView:()=>$b,perspectiveNO:()=>Am,perspectiveZO:()=>Xb,rotate:()=>Eb,rotateX:()=>Tb,rotateY:()=>Lb,rotateZ:()=>Pb,scale:()=>Ab,set:()=>xb,str:()=>jb,sub:()=>ax,subtract:()=>Tm,targetTo:()=>Zb,translate:()=>Mb,transpose:()=>vb});function pb(){var t=new xe(16);return xe!=Float32Array&&(t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0),t[0]=1,t[5]=1,t[10]=1,t[15]=1,t}function gb(t){var e=new xe(16);return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],e[9]=t[9],e[10]=t[10],e[11]=t[11],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15],e}function yb(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[4]=e[4],t[5]=e[5],t[6]=e[6],t[7]=e[7],t[8]=e[8],t[9]=e[9],t[10]=e[10],t[11]=e[11],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],t}function bb(t,e,r,n,i,a,o,s,c,l,u,d,f,h,m,g){var p=new xe(16);return p[0]=t,p[1]=e,p[2]=r,p[3]=n,p[4]=i,p[5]=a,p[6]=o,p[7]=s,p[8]=c,p[9]=l,p[10]=u,p[11]=d,p[12]=f,p[13]=h,p[14]=m,p[15]=g,p}function xb(t,e,r,n,i,a,o,s,c,l,u,d,f,h,m,g,p){return t[0]=e,t[1]=r,t[2]=n,t[3]=i,t[4]=a,t[5]=o,t[6]=s,t[7]=c,t[8]=l,t[9]=u,t[10]=d,t[11]=f,t[12]=h,t[13]=m,t[14]=g,t[15]=p,t}function _m(t){return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}function vb(t,e){if(t===e){var r=e[1],n=e[2],i=e[3],a=e[6],o=e[7],s=e[11];t[1]=e[4],t[2]=e[8],t[3]=e[12],t[4]=r,t[6]=e[9],t[7]=e[13],t[8]=n,t[9]=a,t[11]=e[14],t[12]=i,t[13]=o,t[14]=s}else t[0]=e[0],t[1]=e[4],t[2]=e[8],t[3]=e[12],t[4]=e[1],t[5]=e[5],t[6]=e[9],t[7]=e[13],t[8]=e[2],t[9]=e[6],t[10]=e[10],t[11]=e[14],t[12]=e[3],t[13]=e[7],t[14]=e[11],t[15]=e[15];return t}function _b(t,e){var r=e[0],n=e[1],i=e[2],a=e[3],o=e[4],s=e[5],c=e[6],l=e[7],u=e[8],d=e[9],f=e[10],h=e[11],m=e[12],g=e[13],p=e[14],y=e[15],v=r*s-n*o,b=r*c-i*o,x=r*l-a*o,_=n*c-i*s,w=n*l-a*s,S=i*l-a*c,A=u*g-d*m,T=u*p-f*m,M=u*y-h*m,P=d*p-f*g,I=d*y-h*g,D=f*y-h*p,B=v*D-b*I+x*P+_*M-w*T+S*A;return B?(B=1/B,t[0]=(s*D-c*I+l*P)*B,t[1]=(i*I-n*D-a*P)*B,t[2]=(g*S-p*w+y*_)*B,t[3]=(f*w-d*S-h*_)*B,t[4]=(c*M-o*D-l*T)*B,t[5]=(r*D-i*M+a*T)*B,t[6]=(p*x-m*S-y*b)*B,t[7]=(u*S-f*x+h*b)*B,t[8]=(o*I-s*M+l*A)*B,t[9]=(n*M-r*I-a*A)*B,t[10]=(m*w-g*x+y*v)*B,t[11]=(d*x-u*w-h*v)*B,t[12]=(s*T-o*P-c*A)*B,t[13]=(r*P-n*T+i*A)*B,t[14]=(g*b-m*_-p*v)*B,t[15]=(u*_-d*b+f*v)*B,t):null}function Sb(t,e){var r=e[0],n=e[1],i=e[2],a=e[3],o=e[4],s=e[5],c=e[6],l=e[7],u=e[8],d=e[9],f=e[10],h=e[11],m=e[12],g=e[13],p=e[14],y=e[15],v=r*s-n*o,b=r*c-i*o,x=r*l-a*o,_=n*c-i*s,w=n*l-a*s,S=i*l-a*c,A=u*g-d*m,T=u*p-f*m,M=u*y-h*m,P=d*p-f*g,I=d*y-h*g,D=f*y-h*p;return t[0]=s*D-c*I+l*P,t[1]=i*I-n*D-a*P,t[2]=g*S-p*w+y*_,t[3]=f*w-d*S-h*_,t[4]=c*M-o*D-l*T,t[5]=r*D-i*M+a*T,t[6]=p*x-m*S-y*b,t[7]=u*S-f*x+h*b,t[8]=o*I-s*M+l*A,t[9]=n*M-r*I-a*A,t[10]=m*w-g*x+y*v,t[11]=d*x-u*w-h*v,t[12]=s*T-o*P-c*A,t[13]=r*P-n*T+i*A,t[14]=g*b-m*_-p*v,t[15]=u*_-d*b+f*v,t}function wb(t){var e=t[0],r=t[1],n=t[2],i=t[3],a=t[4],o=t[5],s=t[6],c=t[7],l=t[8],u=t[9],d=t[10],f=t[11],h=t[12],m=t[13],g=t[14],p=t[15],y=e*o-r*a,v=e*s-n*a,b=r*s-n*o,x=l*m-u*h,_=l*g-d*h,w=u*g-d*m,S=e*w-r*_+n*x,A=a*w-o*_+s*x,T=l*b-u*v+d*y,M=h*b-m*v+g*y;return c*S-i*A+p*T-f*M}function Sm(t,e,r){var n=e[0],i=e[1],a=e[2],o=e[3],s=e[4],c=e[5],l=e[6],u=e[7],d=e[8],f=e[9],h=e[10],m=e[11],g=e[12],p=e[13],y=e[14],v=e[15],b=r[0],x=r[1],_=r[2],w=r[3];return t[0]=b*n+x*s+_*d+w*g,t[1]=b*i+x*c+_*f+w*p,t[2]=b*a+x*l+_*h+w*y,t[3]=b*o+x*u+_*m+w*v,b=r[4],x=r[5],_=r[6],w=r[7],t[4]=b*n+x*s+_*d+w*g,t[5]=b*i+x*c+_*f+w*p,t[6]=b*a+x*l+_*h+w*y,t[7]=b*o+x*u+_*m+w*v,b=r[8],x=r[9],_=r[10],w=r[11],t[8]=b*n+x*s+_*d+w*g,t[9]=b*i+x*c+_*f+w*p,t[10]=b*a+x*l+_*h+w*y,t[11]=b*o+x*u+_*m+w*v,b=r[12],x=r[13],_=r[14],w=r[15],t[12]=b*n+x*s+_*d+w*g,t[13]=b*i+x*c+_*f+w*p,t[14]=b*a+x*l+_*h+w*y,t[15]=b*o+x*u+_*m+w*v,t}function Mb(t,e,r){var n=r[0],i=r[1],a=r[2],o,s,c,l,u,d,f,h,m,g,p,y;return e===t?(t[12]=e[0]*n+e[4]*i+e[8]*a+e[12],t[13]=e[1]*n+e[5]*i+e[9]*a+e[13],t[14]=e[2]*n+e[6]*i+e[10]*a+e[14],t[15]=e[3]*n+e[7]*i+e[11]*a+e[15]):(o=e[0],s=e[1],c=e[2],l=e[3],u=e[4],d=e[5],f=e[6],h=e[7],m=e[8],g=e[9],p=e[10],y=e[11],t[0]=o,t[1]=s,t[2]=c,t[3]=l,t[4]=u,t[5]=d,t[6]=f,t[7]=h,t[8]=m,t[9]=g,t[10]=p,t[11]=y,t[12]=o*n+u*i+m*a+e[12],t[13]=s*n+d*i+g*a+e[13],t[14]=c*n+f*i+p*a+e[14],t[15]=l*n+h*i+y*a+e[15]),t}function Ab(t,e,r){var n=r[0],i=r[1],a=r[2];return t[0]=e[0]*n,t[1]=e[1]*n,t[2]=e[2]*n,t[3]=e[3]*n,t[4]=e[4]*i,t[5]=e[5]*i,t[6]=e[6]*i,t[7]=e[7]*i,t[8]=e[8]*a,t[9]=e[9]*a,t[10]=e[10]*a,t[11]=e[11]*a,t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],t}function Eb(t,e,r,n){var i=n[0],a=n[1],o=n[2],s=Math.sqrt(i*i+a*a+o*o),c,l,u,d,f,h,m,g,p,y,v,b,x,_,w,S,A,T,M,P,I,D,B,O;return s<G?null:(s=1/s,i*=s,a*=s,o*=s,c=Math.sin(r),l=Math.cos(r),u=1-l,d=e[0],f=e[1],h=e[2],m=e[3],g=e[4],p=e[5],y=e[6],v=e[7],b=e[8],x=e[9],_=e[10],w=e[11],S=i*i*u+l,A=a*i*u+o*c,T=o*i*u-a*c,M=i*a*u-o*c,P=a*a*u+l,I=o*a*u+i*c,D=i*o*u+a*c,B=a*o*u-i*c,O=o*o*u+l,t[0]=d*S+g*A+b*T,t[1]=f*S+p*A+x*T,t[2]=h*S+y*A+_*T,t[3]=m*S+v*A+w*T,t[4]=d*M+g*P+b*I,t[5]=f*M+p*P+x*I,t[6]=h*M+y*P+_*I,t[7]=m*M+v*P+w*I,t[8]=d*D+g*B+b*O,t[9]=f*D+p*B+x*O,t[10]=h*D+y*B+_*O,t[11]=m*D+v*B+w*O,e!==t&&(t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t)}function Tb(t,e,r){var n=Math.sin(r),i=Math.cos(r),a=e[4],o=e[5],s=e[6],c=e[7],l=e[8],u=e[9],d=e[10],f=e[11];return e!==t&&(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t[4]=a*i+l*n,t[5]=o*i+u*n,t[6]=s*i+d*n,t[7]=c*i+f*n,t[8]=l*i-a*n,t[9]=u*i-o*n,t[10]=d*i-s*n,t[11]=f*i-c*n,t}function Lb(t,e,r){var n=Math.sin(r),i=Math.cos(r),a=e[0],o=e[1],s=e[2],c=e[3],l=e[8],u=e[9],d=e[10],f=e[11];return e!==t&&(t[4]=e[4],t[5]=e[5],t[6]=e[6],t[7]=e[7],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t[0]=a*i-l*n,t[1]=o*i-u*n,t[2]=s*i-d*n,t[3]=c*i-f*n,t[8]=a*n+l*i,t[9]=o*n+u*i,t[10]=s*n+d*i,t[11]=c*n+f*i,t}function Pb(t,e,r){var n=Math.sin(r),i=Math.cos(r),a=e[0],o=e[1],s=e[2],c=e[3],l=e[4],u=e[5],d=e[6],f=e[7];return e!==t&&(t[8]=e[8],t[9]=e[9],t[10]=e[10],t[11]=e[11],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t[0]=a*i+l*n,t[1]=o*i+u*n,t[2]=s*i+d*n,t[3]=c*i+f*n,t[4]=l*i-a*n,t[5]=u*i-o*n,t[6]=d*i-s*n,t[7]=f*i-c*n,t}function Rb(t,e){return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=e[0],t[13]=e[1],t[14]=e[2],t[15]=1,t}function Cb(t,e){return t[0]=e[0],t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=e[1],t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=e[2],t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}function Bb(t,e,r){var n=r[0],i=r[1],a=r[2],o=Math.sqrt(n*n+i*i+a*a),s,c,l;return o<G?null:(o=1/o,n*=o,i*=o,a*=o,s=Math.sin(e),c=Math.cos(e),l=1-c,t[0]=n*n*l+c,t[1]=i*n*l+a*s,t[2]=a*n*l-i*s,t[3]=0,t[4]=n*i*l-a*s,t[5]=i*i*l+c,t[6]=a*i*l+n*s,t[7]=0,t[8]=n*a*l+i*s,t[9]=i*a*l-n*s,t[10]=a*a*l+c,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t)}function Fb(t,e){var r=Math.sin(e),n=Math.cos(e);return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=n,t[6]=r,t[7]=0,t[8]=0,t[9]=-r,t[10]=n,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}function Ib(t,e){var r=Math.sin(e),n=Math.cos(e);return t[0]=n,t[1]=0,t[2]=-r,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=r,t[9]=0,t[10]=n,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}function Db(t,e){var r=Math.sin(e),n=Math.cos(e);return t[0]=n,t[1]=r,t[2]=0,t[3]=0,t[4]=-r,t[5]=n,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}function wm(t,e,r){var n=e[0],i=e[1],a=e[2],o=e[3],s=n+n,c=i+i,l=a+a,u=n*s,d=n*c,f=n*l,h=i*c,m=i*l,g=a*l,p=o*s,y=o*c,v=o*l;return t[0]=1-(h+g),t[1]=d+v,t[2]=f-y,t[3]=0,t[4]=d-v,t[5]=1-(u+g),t[6]=m+p,t[7]=0,t[8]=f+y,t[9]=m-p,t[10]=1-(u+h),t[11]=0,t[12]=r[0],t[13]=r[1],t[14]=r[2],t[15]=1,t}function kb(t,e){var r=new xe(3),n=-e[0],i=-e[1],a=-e[2],o=e[3],s=e[4],c=e[5],l=e[6],u=e[7],d=n*n+i*i+a*a+o*o;return d>0?(r[0]=(s*o+u*n+c*a-l*i)*2/d,r[1]=(c*o+u*i+l*n-s*a)*2/d,r[2]=(l*o+u*a+s*i-c*n)*2/d):(r[0]=(s*o+u*n+c*a-l*i)*2,r[1]=(c*o+u*i+l*n-s*a)*2,r[2]=(l*o+u*a+s*i-c*n)*2),wm(t,e,r),t}function Ub(t,e){return t[0]=e[12],t[1]=e[13],t[2]=e[14],t}function Mm(t,e){var r=e[0],n=e[1],i=e[2],a=e[4],o=e[5],s=e[6],c=e[8],l=e[9],u=e[10];return t[0]=Math.sqrt(r*r+n*n+i*i),t[1]=Math.sqrt(a*a+o*o+s*s),t[2]=Math.sqrt(c*c+l*l+u*u),t}function zb(t,e){var r=new xe(3);Mm(r,e);var n=1/r[0],i=1/r[1],a=1/r[2],o=e[0]*n,s=e[1]*i,c=e[2]*a,l=e[4]*n,u=e[5]*i,d=e[6]*a,f=e[8]*n,h=e[9]*i,m=e[10]*a,g=o+u+m,p=0;return g>0?(p=Math.sqrt(g+1)*2,t[3]=.25*p,t[0]=(d-h)/p,t[1]=(f-c)/p,t[2]=(s-l)/p):o>u&&o>m?(p=Math.sqrt(1+o-u-m)*2,t[3]=(d-h)/p,t[0]=.25*p,t[1]=(s+l)/p,t[2]=(f+c)/p):u>m?(p=Math.sqrt(1+u-o-m)*2,t[3]=(f-c)/p,t[0]=(s+l)/p,t[1]=.25*p,t[2]=(d+h)/p):(p=Math.sqrt(1+m-o-u)*2,t[3]=(s-l)/p,t[0]=(f+c)/p,t[1]=(d+h)/p,t[2]=.25*p),t}function Ob(t,e,r,n){e[0]=n[12],e[1]=n[13],e[2]=n[14];var i=n[0],a=n[1],o=n[2],s=n[4],c=n[5],l=n[6],u=n[8],d=n[9],f=n[10];r[0]=Math.sqrt(i*i+a*a+o*o),r[1]=Math.sqrt(s*s+c*c+l*l),r[2]=Math.sqrt(u*u+d*d+f*f);var h=1/r[0],m=1/r[1],g=1/r[2],p=i*h,y=a*m,v=o*g,b=s*h,x=c*m,_=l*g,w=u*h,S=d*m,A=f*g,T=p+x+A,M=0;return T>0?(M=Math.sqrt(T+1)*2,t[3]=.25*M,t[0]=(_-S)/M,t[1]=(w-v)/M,t[2]=(y-b)/M):p>x&&p>A?(M=Math.sqrt(1+p-x-A)*2,t[3]=(_-S)/M,t[0]=.25*M,t[1]=(y+b)/M,t[2]=(w+v)/M):x>A?(M=Math.sqrt(1+x-p-A)*2,t[3]=(w-v)/M,t[0]=(y+b)/M,t[1]=.25*M,t[2]=(_+S)/M):(M=Math.sqrt(1+A-p-x)*2,t[3]=(y-b)/M,t[0]=(w+v)/M,t[1]=(_+S)/M,t[2]=.25*M),t}function Nb(t,e,r,n){var i=e[0],a=e[1],o=e[2],s=e[3],c=i+i,l=a+a,u=o+o,d=i*c,f=i*l,h=i*u,m=a*l,g=a*u,p=o*u,y=s*c,v=s*l,b=s*u,x=n[0],_=n[1],w=n[2];return t[0]=(1-(m+p))*x,t[1]=(f+b)*x,t[2]=(h-v)*x,t[3]=0,t[4]=(f-b)*_,t[5]=(1-(d+p))*_,t[6]=(g+y)*_,t[7]=0,t[8]=(h+v)*w,t[9]=(g-y)*w,t[10]=(1-(d+m))*w,t[11]=0,t[12]=r[0],t[13]=r[1],t[14]=r[2],t[15]=1,t}function Gb(t,e,r,n,i){var a=e[0],o=e[1],s=e[2],c=e[3],l=a+a,u=o+o,d=s+s,f=a*l,h=a*u,m=a*d,g=o*u,p=o*d,y=s*d,v=c*l,b=c*u,x=c*d,_=n[0],w=n[1],S=n[2],A=i[0],T=i[1],M=i[2],P=(1-(g+y))*_,I=(h+x)*_,D=(m-b)*_,B=(h-x)*w,O=(1-(f+y))*w,Q=(p+v)*w,Ge=(m+b)*S,me=(p-v)*S,Me=(1-(f+g))*S;return t[0]=P,t[1]=I,t[2]=D,t[3]=0,t[4]=B,t[5]=O,t[6]=Q,t[7]=0,t[8]=Ge,t[9]=me,t[10]=Me,t[11]=0,t[12]=r[0]+A-(P*A+B*T+Ge*M),t[13]=r[1]+T-(I*A+O*T+me*M),t[14]=r[2]+M-(D*A+Q*T+Me*M),t[15]=1,t}function Vb(t,e){var r=e[0],n=e[1],i=e[2],a=e[3],o=r+r,s=n+n,c=i+i,l=r*o,u=n*o,d=n*s,f=i*o,h=i*s,m=i*c,g=a*o,p=a*s,y=a*c;return t[0]=1-d-m,t[1]=u+y,t[2]=f-p,t[3]=0,t[4]=u-y,t[5]=1-l-m,t[6]=h+g,t[7]=0,t[8]=f+p,t[9]=h-g,t[10]=1-l-d,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}function Hb(t,e,r,n,i,a,o){var s=1/(r-e),c=1/(i-n),l=1/(a-o);return t[0]=a*2*s,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=a*2*c,t[6]=0,t[7]=0,t[8]=(r+e)*s,t[9]=(i+n)*c,t[10]=(o+a)*l,t[11]=-1,t[12]=0,t[13]=0,t[14]=o*a*2*l,t[15]=0,t}function Am(t,e,r,n,i){var a=1/Math.tan(e/2);if(t[0]=a/r,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=a,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=-1,t[12]=0,t[13]=0,t[15]=0,i!=null&&i!==1/0){var o=1/(n-i);t[10]=(i+n)*o,t[14]=2*i*n*o}else t[10]=-1,t[14]=-2*n;return t}var Wb=Am;function Xb(t,e,r,n,i){var a=1/Math.tan(e/2);if(t[0]=a/r,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=a,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=-1,t[12]=0,t[13]=0,t[15]=0,i!=null&&i!==1/0){var o=1/(n-i);t[10]=i*o,t[14]=i*n*o}else t[10]=-1,t[14]=-n;return t}function $b(t,e,r,n){var i=Math.tan(e.upDegrees*Math.PI/180),a=Math.tan(e.downDegrees*Math.PI/180),o=Math.tan(e.leftDegrees*Math.PI/180),s=Math.tan(e.rightDegrees*Math.PI/180),c=2/(o+s),l=2/(i+a);return t[0]=c,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=l,t[6]=0,t[7]=0,t[8]=-((o-s)*c*.5),t[9]=(i-a)*l*.5,t[10]=n/(r-n),t[11]=-1,t[12]=0,t[13]=0,t[14]=n*r/(r-n),t[15]=0,t}function Em(t,e,r,n,i,a,o){var s=1/(e-r),c=1/(n-i),l=1/(a-o);return t[0]=-2*s,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=-2*c,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=2*l,t[11]=0,t[12]=(e+r)*s,t[13]=(i+n)*c,t[14]=(o+a)*l,t[15]=1,t}var Kb=Em;function Yb(t,e,r,n,i,a,o){var s=1/(e-r),c=1/(n-i),l=1/(a-o);return t[0]=-2*s,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=-2*c,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=l,t[11]=0,t[12]=(e+r)*s,t[13]=(i+n)*c,t[14]=a*l,t[15]=1,t}function qb(t,e,r,n){var i,a,o,s,c,l,u,d,f,h,m=e[0],g=e[1],p=e[2],y=n[0],v=n[1],b=n[2],x=r[0],_=r[1],w=r[2];return Math.abs(m-x)<G&&Math.abs(g-_)<G&&Math.abs(p-w)<G?_m(t):(u=m-x,d=g-_,f=p-w,h=1/Math.sqrt(u*u+d*d+f*f),u*=h,d*=h,f*=h,i=v*f-b*d,a=b*u-y*f,o=y*d-v*u,h=Math.sqrt(i*i+a*a+o*o),h?(h=1/h,i*=h,a*=h,o*=h):(i=0,a=0,o=0),s=d*o-f*a,c=f*i-u*o,l=u*a-d*i,h=Math.sqrt(s*s+c*c+l*l),h?(h=1/h,s*=h,c*=h,l*=h):(s=0,c=0,l=0),t[0]=i,t[1]=s,t[2]=u,t[3]=0,t[4]=a,t[5]=c,t[6]=d,t[7]=0,t[8]=o,t[9]=l,t[10]=f,t[11]=0,t[12]=-(i*m+a*g+o*p),t[13]=-(s*m+c*g+l*p),t[14]=-(u*m+d*g+f*p),t[15]=1,t)}function Zb(t,e,r,n){var i=e[0],a=e[1],o=e[2],s=n[0],c=n[1],l=n[2],u=i-r[0],d=a-r[1],f=o-r[2],h=u*u+d*d+f*f;h>0&&(h=1/Math.sqrt(h),u*=h,d*=h,f*=h);var m=c*f-l*d,g=l*u-s*f,p=s*d-c*u;return h=m*m+g*g+p*p,h>0&&(h=1/Math.sqrt(h),m*=h,g*=h,p*=h),t[0]=m,t[1]=g,t[2]=p,t[3]=0,t[4]=d*p-f*g,t[5]=f*m-u*p,t[6]=u*g-d*m,t[7]=0,t[8]=u,t[9]=d,t[10]=f,t[11]=0,t[12]=i,t[13]=a,t[14]=o,t[15]=1,t}function jb(t){return"mat4("+t[0]+", "+t[1]+", "+t[2]+", "+t[3]+", "+t[4]+", "+t[5]+", "+t[6]+", "+t[7]+", "+t[8]+", "+t[9]+", "+t[10]+", "+t[11]+", "+t[12]+", "+t[13]+", "+t[14]+", "+t[15]+")"}function Qb(t){return Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]+t[3]*t[3]+t[4]*t[4]+t[5]*t[5]+t[6]*t[6]+t[7]*t[7]+t[8]*t[8]+t[9]*t[9]+t[10]*t[10]+t[11]*t[11]+t[12]*t[12]+t[13]*t[13]+t[14]*t[14]+t[15]*t[15])}function Jb(t,e,r){return t[0]=e[0]+r[0],t[1]=e[1]+r[1],t[2]=e[2]+r[2],t[3]=e[3]+r[3],t[4]=e[4]+r[4],t[5]=e[5]+r[5],t[6]=e[6]+r[6],t[7]=e[7]+r[7],t[8]=e[8]+r[8],t[9]=e[9]+r[9],t[10]=e[10]+r[10],t[11]=e[11]+r[11],t[12]=e[12]+r[12],t[13]=e[13]+r[13],t[14]=e[14]+r[14],t[15]=e[15]+r[15],t}function Tm(t,e,r){return t[0]=e[0]-r[0],t[1]=e[1]-r[1],t[2]=e[2]-r[2],t[3]=e[3]-r[3],t[4]=e[4]-r[4],t[5]=e[5]-r[5],t[6]=e[6]-r[6],t[7]=e[7]-r[7],t[8]=e[8]-r[8],t[9]=e[9]-r[9],t[10]=e[10]-r[10],t[11]=e[11]-r[11],t[12]=e[12]-r[12],t[13]=e[13]-r[13],t[14]=e[14]-r[14],t[15]=e[15]-r[15],t}function ex(t,e,r){return t[0]=e[0]*r,t[1]=e[1]*r,t[2]=e[2]*r,t[3]=e[3]*r,t[4]=e[4]*r,t[5]=e[5]*r,t[6]=e[6]*r,t[7]=e[7]*r,t[8]=e[8]*r,t[9]=e[9]*r,t[10]=e[10]*r,t[11]=e[11]*r,t[12]=e[12]*r,t[13]=e[13]*r,t[14]=e[14]*r,t[15]=e[15]*r,t}function tx(t,e,r,n){return t[0]=e[0]+r[0]*n,t[1]=e[1]+r[1]*n,t[2]=e[2]+r[2]*n,t[3]=e[3]+r[3]*n,t[4]=e[4]+r[4]*n,t[5]=e[5]+r[5]*n,t[6]=e[6]+r[6]*n,t[7]=e[7]+r[7]*n,t[8]=e[8]+r[8]*n,t[9]=e[9]+r[9]*n,t[10]=e[10]+r[10]*n,t[11]=e[11]+r[11]*n,t[12]=e[12]+r[12]*n,t[13]=e[13]+r[13]*n,t[14]=e[14]+r[14]*n,t[15]=e[15]+r[15]*n,t}function rx(t,e){return t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2]&&t[3]===e[3]&&t[4]===e[4]&&t[5]===e[5]&&t[6]===e[6]&&t[7]===e[7]&&t[8]===e[8]&&t[9]===e[9]&&t[10]===e[10]&&t[11]===e[11]&&t[12]===e[12]&&t[13]===e[13]&&t[14]===e[14]&&t[15]===e[15]}function nx(t,e){var r=t[0],n=t[1],i=t[2],a=t[3],o=t[4],s=t[5],c=t[6],l=t[7],u=t[8],d=t[9],f=t[10],h=t[11],m=t[12],g=t[13],p=t[14],y=t[15],v=e[0],b=e[1],x=e[2],_=e[3],w=e[4],S=e[5],A=e[6],T=e[7],M=e[8],P=e[9],I=e[10],D=e[11],B=e[12],O=e[13],Q=e[14],Ge=e[15];return Math.abs(r-v)<=G*Math.max(1,Math.abs(r),Math.abs(v))&&Math.abs(n-b)<=G*Math.max(1,Math.abs(n),Math.abs(b))&&Math.abs(i-x)<=G*Math.max(1,Math.abs(i),Math.abs(x))&&Math.abs(a-_)<=G*Math.max(1,Math.abs(a),Math.abs(_))&&Math.abs(o-w)<=G*Math.max(1,Math.abs(o),Math.abs(w))&&Math.abs(s-S)<=G*Math.max(1,Math.abs(s),Math.abs(S))&&Math.abs(c-A)<=G*Math.max(1,Math.abs(c),Math.abs(A))&&Math.abs(l-T)<=G*Math.max(1,Math.abs(l),Math.abs(T))&&Math.abs(u-M)<=G*Math.max(1,Math.abs(u),Math.abs(M))&&Math.abs(d-P)<=G*Math.max(1,Math.abs(d),Math.abs(P))&&Math.abs(f-I)<=G*Math.max(1,Math.abs(f),Math.abs(I))&&Math.abs(h-D)<=G*Math.max(1,Math.abs(h),Math.abs(D))&&Math.abs(m-B)<=G*Math.max(1,Math.abs(m),Math.abs(B))&&Math.abs(g-O)<=G*Math.max(1,Math.abs(g),Math.abs(O))&&Math.abs(p-Q)<=G*Math.max(1,Math.abs(p),Math.abs(Q))&&Math.abs(y-Ge)<=G*Math.max(1,Math.abs(y),Math.abs(Ge))}var ix=Sm,ax=Tm;var pc={};zi(pc,{add:()=>Lv,calculateW:()=>yv,clone:()=>Mv,conjugate:()=>_v,copy:()=>Ev,create:()=>Nd,dot:()=>Km,equals:()=>Iv,exactEquals:()=>Fv,exp:()=>Hm,fromEuler:()=>Sv,fromMat3:()=>Xm,fromValues:()=>Av,getAngle:()=>hv,getAxisAngle:()=>fv,identity:()=>dv,invert:()=>vv,len:()=>Cv,length:()=>Ym,lerp:()=>Rv,ln:()=>Wm,mul:()=>Pv,multiply:()=>Vm,normalize:()=>Gd,pow:()=>bv,random:()=>xv,rotateX:()=>mv,rotateY:()=>pv,rotateZ:()=>gv,rotationTo:()=>Dv,scale:()=>$m,set:()=>Tv,setAxes:()=>Uv,setAxisAngle:()=>Gm,slerp:()=>mc,sqlerp:()=>kv,sqrLen:()=>Bv,squaredLength:()=>qm,str:()=>wv});var L={};zi(L,{add:()=>cx,angle:()=>Rx,bezier:()=>Sx,ceil:()=>ux,clone:()=>ox,copy:()=>sx,create:()=>cc,cross:()=>ps,dist:()=>zx,distance:()=>Bm,div:()=>Ux,divide:()=>Cm,dot:()=>ms,equals:()=>Ix,exactEquals:()=>Fx,floor:()=>dx,forEach:()=>Gx,fromValues:()=>uc,hermite:()=>_x,inverse:()=>bx,len:()=>Rd,length:()=>Lm,lerp:()=>xx,max:()=>hx,min:()=>fx,mul:()=>kx,multiply:()=>Rm,negate:()=>yx,normalize:()=>Pd,random:()=>wx,rotateX:()=>Tx,rotateY:()=>Lx,rotateZ:()=>Px,round:()=>mx,scale:()=>px,scaleAndAdd:()=>gx,set:()=>lx,slerp:()=>vx,sqrDist:()=>Ox,sqrLen:()=>Nx,squaredDistance:()=>Fm,squaredLength:()=>Im,str:()=>Bx,sub:()=>Dx,subtract:()=>Pm,transformMat3:()=>Ax,transformMat4:()=>Mx,transformQuat:()=>Ex,zero:()=>Cx});function cc(){var t=new xe(3);return xe!=Float32Array&&(t[0]=0,t[1]=0,t[2]=0),t}function ox(t){var e=new xe(3);return e[0]=t[0],e[1]=t[1],e[2]=t[2],e}function Lm(t){var e=t[0],r=t[1],n=t[2];return Math.sqrt(e*e+r*r+n*n)}function uc(t,e,r){var n=new xe(3);return n[0]=t,n[1]=e,n[2]=r,n}function sx(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t}function lx(t,e,r,n){return t[0]=e,t[1]=r,t[2]=n,t}function cx(t,e,r){return t[0]=e[0]+r[0],t[1]=e[1]+r[1],t[2]=e[2]+r[2],t}function Pm(t,e,r){return t[0]=e[0]-r[0],t[1]=e[1]-r[1],t[2]=e[2]-r[2],t}function Rm(t,e,r){return t[0]=e[0]*r[0],t[1]=e[1]*r[1],t[2]=e[2]*r[2],t}function Cm(t,e,r){return t[0]=e[0]/r[0],t[1]=e[1]/r[1],t[2]=e[2]/r[2],t}function ux(t,e){return t[0]=Math.ceil(e[0]),t[1]=Math.ceil(e[1]),t[2]=Math.ceil(e[2]),t}function dx(t,e){return t[0]=Math.floor(e[0]),t[1]=Math.floor(e[1]),t[2]=Math.floor(e[2]),t}function fx(t,e,r){return t[0]=Math.min(e[0],r[0]),t[1]=Math.min(e[1],r[1]),t[2]=Math.min(e[2],r[2]),t}function hx(t,e,r){return t[0]=Math.max(e[0],r[0]),t[1]=Math.max(e[1],r[1]),t[2]=Math.max(e[2],r[2]),t}function mx(t,e){return t[0]=un(e[0]),t[1]=un(e[1]),t[2]=un(e[2]),t}function px(t,e,r){return t[0]=e[0]*r,t[1]=e[1]*r,t[2]=e[2]*r,t}function gx(t,e,r,n){return t[0]=e[0]+r[0]*n,t[1]=e[1]+r[1]*n,t[2]=e[2]+r[2]*n,t}function Bm(t,e){var r=e[0]-t[0],n=e[1]-t[1],i=e[2]-t[2];return Math.sqrt(r*r+n*n+i*i)}function Fm(t,e){var r=e[0]-t[0],n=e[1]-t[1],i=e[2]-t[2];return r*r+n*n+i*i}function Im(t){var e=t[0],r=t[1],n=t[2];return e*e+r*r+n*n}function yx(t,e){return t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t}function bx(t,e){return t[0]=1/e[0],t[1]=1/e[1],t[2]=1/e[2],t}function Pd(t,e){var r=e[0],n=e[1],i=e[2],a=r*r+n*n+i*i;return a>0&&(a=1/Math.sqrt(a)),t[0]=e[0]*a,t[1]=e[1]*a,t[2]=e[2]*a,t}function ms(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]}function ps(t,e,r){var n=e[0],i=e[1],a=e[2],o=r[0],s=r[1],c=r[2];return t[0]=i*c-a*s,t[1]=a*o-n*c,t[2]=n*s-i*o,t}function xx(t,e,r,n){var i=e[0],a=e[1],o=e[2];return t[0]=i+n*(r[0]-i),t[1]=a+n*(r[1]-a),t[2]=o+n*(r[2]-o),t}function vx(t,e,r,n){var i=Math.acos(Math.min(Math.max(ms(e,r),-1),1)),a=Math.sin(i),o=Math.sin((1-n)*i)/a,s=Math.sin(n*i)/a;return t[0]=o*e[0]+s*r[0],t[1]=o*e[1]+s*r[1],t[2]=o*e[2]+s*r[2],t}function _x(t,e,r,n,i,a){var o=a*a,s=o*(2*a-3)+1,c=o*(a-2)+a,l=o*(a-1),u=o*(3-2*a);return t[0]=e[0]*s+r[0]*c+n[0]*l+i[0]*u,t[1]=e[1]*s+r[1]*c+n[1]*l+i[1]*u,t[2]=e[2]*s+r[2]*c+n[2]*l+i[2]*u,t}function Sx(t,e,r,n,i,a){var o=1-a,s=o*o,c=a*a,l=s*o,u=3*a*s,d=3*c*o,f=c*a;return t[0]=e[0]*l+r[0]*u+n[0]*d+i[0]*f,t[1]=e[1]*l+r[1]*u+n[1]*d+i[1]*f,t[2]=e[2]*l+r[2]*u+n[2]*d+i[2]*f,t}function wx(t,e){e=e===void 0?1:e;var r=lr()*2*Math.PI,n=lr()*2-1,i=Math.sqrt(1-n*n)*e;return t[0]=Math.cos(r)*i,t[1]=Math.sin(r)*i,t[2]=n*e,t}function Mx(t,e,r){var n=e[0],i=e[1],a=e[2],o=r[3]*n+r[7]*i+r[11]*a+r[15];return o=o||1,t[0]=(r[0]*n+r[4]*i+r[8]*a+r[12])/o,t[1]=(r[1]*n+r[5]*i+r[9]*a+r[13])/o,t[2]=(r[2]*n+r[6]*i+r[10]*a+r[14])/o,t}function Ax(t,e,r){var n=e[0],i=e[1],a=e[2];return t[0]=n*r[0]+i*r[3]+a*r[6],t[1]=n*r[1]+i*r[4]+a*r[7],t[2]=n*r[2]+i*r[5]+a*r[8],t}function Ex(t,e,r){var n=r[0],i=r[1],a=r[2],o=r[3],s=e[0],c=e[1],l=e[2],u=i*l-a*c,d=a*s-n*l,f=n*c-i*s;return u=u+u,d=d+d,f=f+f,t[0]=s+o*u+i*f-a*d,t[1]=c+o*d+a*u-n*f,t[2]=l+o*f+n*d-i*u,t}function Tx(t,e,r,n){var i=[],a=[];return i[0]=e[0]-r[0],i[1]=e[1]-r[1],i[2]=e[2]-r[2],a[0]=i[0],a[1]=i[1]*Math.cos(n)-i[2]*Math.sin(n),a[2]=i[1]*Math.sin(n)+i[2]*Math.cos(n),t[0]=a[0]+r[0],t[1]=a[1]+r[1],t[2]=a[2]+r[2],t}function Lx(t,e,r,n){var i=[],a=[];return i[0]=e[0]-r[0],i[1]=e[1]-r[1],i[2]=e[2]-r[2],a[0]=i[2]*Math.sin(n)+i[0]*Math.cos(n),a[1]=i[1],a[2]=i[2]*Math.cos(n)-i[0]*Math.sin(n),t[0]=a[0]+r[0],t[1]=a[1]+r[1],t[2]=a[2]+r[2],t}function Px(t,e,r,n){var i=[],a=[];return i[0]=e[0]-r[0],i[1]=e[1]-r[1],i[2]=e[2]-r[2],a[0]=i[0]*Math.cos(n)-i[1]*Math.sin(n),a[1]=i[0]*Math.sin(n)+i[1]*Math.cos(n),a[2]=i[2],t[0]=a[0]+r[0],t[1]=a[1]+r[1],t[2]=a[2]+r[2],t}function Rx(t,e){var r=t[0],n=t[1],i=t[2],a=e[0],o=e[1],s=e[2],c=Math.sqrt((r*r+n*n+i*i)*(a*a+o*o+s*s)),l=c&&ms(t,e)/c;return Math.acos(Math.min(Math.max(l,-1),1))}function Cx(t){return t[0]=0,t[1]=0,t[2]=0,t}function Bx(t){return"vec3("+t[0]+", "+t[1]+", "+t[2]+")"}function Fx(t,e){return t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2]}function Ix(t,e){var r=t[0],n=t[1],i=t[2],a=e[0],o=e[1],s=e[2];return Math.abs(r-a)<=G*Math.max(1,Math.abs(r),Math.abs(a))&&Math.abs(n-o)<=G*Math.max(1,Math.abs(n),Math.abs(o))&&Math.abs(i-s)<=G*Math.max(1,Math.abs(i),Math.abs(s))}var Dx=Pm,kx=Rm,Ux=Cm,zx=Bm,Ox=Fm,Rd=Lm,Nx=Im,Gx=(function(){var t=cc();return function(e,r,n,i,a,o){var s,c;for(r||(r=3),n||(n=0),i?c=Math.min(i*r+n,e.length):c=e.length,s=n;s<c;s+=r)t[0]=e[s],t[1]=e[s+1],t[2]=e[s+2],a(t,t,o),e[s]=t[0],e[s+1]=t[1],e[s+2]=t[2];return e}})();var Aa={};zi(Aa,{add:()=>Dd,ceil:()=>Vx,clone:()=>Cd,copy:()=>Fd,create:()=>Dm,cross:()=>Zx,dist:()=>ov,distance:()=>Om,div:()=>av,divide:()=>zm,dot:()=>hc,equals:()=>rv,exactEquals:()=>Od,floor:()=>Hx,forEach:()=>uv,fromValues:()=>Bd,inverse:()=>qx,len:()=>lv,length:()=>dc,lerp:()=>zd,max:()=>Xx,min:()=>Wx,mul:()=>iv,multiply:()=>Um,negate:()=>Yx,normalize:()=>Ud,random:()=>jx,round:()=>$x,scale:()=>kd,scaleAndAdd:()=>Kx,set:()=>Id,sqrDist:()=>sv,sqrLen:()=>cv,squaredDistance:()=>Nm,squaredLength:()=>fc,str:()=>tv,sub:()=>nv,subtract:()=>km,transformMat4:()=>Qx,transformQuat:()=>Jx,zero:()=>ev});function Dm(){var t=new xe(4);return xe!=Float32Array&&(t[0]=0,t[1]=0,t[2]=0,t[3]=0),t}function Cd(t){var e=new xe(4);return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e}function Bd(t,e,r,n){var i=new xe(4);return i[0]=t,i[1]=e,i[2]=r,i[3]=n,i}function Fd(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t}function Id(t,e,r,n,i){return t[0]=e,t[1]=r,t[2]=n,t[3]=i,t}function Dd(t,e,r){return t[0]=e[0]+r[0],t[1]=e[1]+r[1],t[2]=e[2]+r[2],t[3]=e[3]+r[3],t}function km(t,e,r){return t[0]=e[0]-r[0],t[1]=e[1]-r[1],t[2]=e[2]-r[2],t[3]=e[3]-r[3],t}function Um(t,e,r){return t[0]=e[0]*r[0],t[1]=e[1]*r[1],t[2]=e[2]*r[2],t[3]=e[3]*r[3],t}function zm(t,e,r){return t[0]=e[0]/r[0],t[1]=e[1]/r[1],t[2]=e[2]/r[2],t[3]=e[3]/r[3],t}function Vx(t,e){return t[0]=Math.ceil(e[0]),t[1]=Math.ceil(e[1]),t[2]=Math.ceil(e[2]),t[3]=Math.ceil(e[3]),t}function Hx(t,e){return t[0]=Math.floor(e[0]),t[1]=Math.floor(e[1]),t[2]=Math.floor(e[2]),t[3]=Math.floor(e[3]),t}function Wx(t,e,r){return t[0]=Math.min(e[0],r[0]),t[1]=Math.min(e[1],r[1]),t[2]=Math.min(e[2],r[2]),t[3]=Math.min(e[3],r[3]),t}function Xx(t,e,r){return t[0]=Math.max(e[0],r[0]),t[1]=Math.max(e[1],r[1]),t[2]=Math.max(e[2],r[2]),t[3]=Math.max(e[3],r[3]),t}function $x(t,e){return t[0]=un(e[0]),t[1]=un(e[1]),t[2]=un(e[2]),t[3]=un(e[3]),t}function kd(t,e,r){return t[0]=e[0]*r,t[1]=e[1]*r,t[2]=e[2]*r,t[3]=e[3]*r,t}function Kx(t,e,r,n){return t[0]=e[0]+r[0]*n,t[1]=e[1]+r[1]*n,t[2]=e[2]+r[2]*n,t[3]=e[3]+r[3]*n,t}function Om(t,e){var r=e[0]-t[0],n=e[1]-t[1],i=e[2]-t[2],a=e[3]-t[3];return Math.sqrt(r*r+n*n+i*i+a*a)}function Nm(t,e){var r=e[0]-t[0],n=e[1]-t[1],i=e[2]-t[2],a=e[3]-t[3];return r*r+n*n+i*i+a*a}function dc(t){var e=t[0],r=t[1],n=t[2],i=t[3];return Math.sqrt(e*e+r*r+n*n+i*i)}function fc(t){var e=t[0],r=t[1],n=t[2],i=t[3];return e*e+r*r+n*n+i*i}function Yx(t,e){return t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=-e[3],t}function qx(t,e){return t[0]=1/e[0],t[1]=1/e[1],t[2]=1/e[2],t[3]=1/e[3],t}function Ud(t,e){var r=e[0],n=e[1],i=e[2],a=e[3],o=r*r+n*n+i*i+a*a;return o>0&&(o=1/Math.sqrt(o)),t[0]=r*o,t[1]=n*o,t[2]=i*o,t[3]=a*o,t}function hc(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]+t[3]*e[3]}function Zx(t,e,r,n){var i=r[0]*n[1]-r[1]*n[0],a=r[0]*n[2]-r[2]*n[0],o=r[0]*n[3]-r[3]*n[0],s=r[1]*n[2]-r[2]*n[1],c=r[1]*n[3]-r[3]*n[1],l=r[2]*n[3]-r[3]*n[2],u=e[0],d=e[1],f=e[2],h=e[3];return t[0]=d*l-f*c+h*s,t[1]=-(u*l)+f*o-h*a,t[2]=u*c-d*o+h*i,t[3]=-(u*s)+d*a-f*i,t}function zd(t,e,r,n){var i=e[0],a=e[1],o=e[2],s=e[3];return t[0]=i+n*(r[0]-i),t[1]=a+n*(r[1]-a),t[2]=o+n*(r[2]-o),t[3]=s+n*(r[3]-s),t}function jx(t,e){e=e===void 0?1:e;var r,n,i,a,o,s,c;c=lr(),r=c*2-1,n=(4*lr()-2)*Math.sqrt(c*-c+c),o=r*r+n*n,c=lr(),i=c*2-1,a=(4*lr()-2)*Math.sqrt(c*-c+c),s=i*i+a*a;var l=Math.sqrt((1-o)/s);return t[0]=e*r,t[1]=e*n,t[2]=e*i*l,t[3]=e*a*l,t}function Qx(t,e,r){var n=e[0],i=e[1],a=e[2],o=e[3];return t[0]=r[0]*n+r[4]*i+r[8]*a+r[12]*o,t[1]=r[1]*n+r[5]*i+r[9]*a+r[13]*o,t[2]=r[2]*n+r[6]*i+r[10]*a+r[14]*o,t[3]=r[3]*n+r[7]*i+r[11]*a+r[15]*o,t}function Jx(t,e,r){var n=r[0],i=r[1],a=r[2],o=r[3],s=e[0],c=e[1],l=e[2],u=i*l-a*c,d=a*s-n*l,f=n*c-i*s;return u=u+u,d=d+d,f=f+f,t[0]=s+o*u+i*f-a*d,t[1]=c+o*d+a*u-n*f,t[2]=l+o*f+n*d-i*u,t[3]=e[3],t}function ev(t){return t[0]=0,t[1]=0,t[2]=0,t[3]=0,t}function tv(t){return"vec4("+t[0]+", "+t[1]+", "+t[2]+", "+t[3]+")"}function Od(t,e){return t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2]&&t[3]===e[3]}function rv(t,e){var r=t[0],n=t[1],i=t[2],a=t[3],o=e[0],s=e[1],c=e[2],l=e[3];return Math.abs(r-o)<=G*Math.max(1,Math.abs(r),Math.abs(o))&&Math.abs(n-s)<=G*Math.max(1,Math.abs(n),Math.abs(s))&&Math.abs(i-c)<=G*Math.max(1,Math.abs(i),Math.abs(c))&&Math.abs(a-l)<=G*Math.max(1,Math.abs(a),Math.abs(l))}var nv=km,iv=Um,av=zm,ov=Om,sv=Nm,lv=dc,cv=fc,uv=(function(){var t=Dm();return function(e,r,n,i,a,o){var s,c;for(r||(r=4),n||(n=0),i?c=Math.min(i*r+n,e.length):c=e.length,s=n;s<c;s+=r)t[0]=e[s],t[1]=e[s+1],t[2]=e[s+2],t[3]=e[s+3],a(t,t,o),e[s]=t[0],e[s+1]=t[1],e[s+2]=t[2],e[s+3]=t[3];return e}})();function Nd(){var t=new xe(4);return xe!=Float32Array&&(t[0]=0,t[1]=0,t[2]=0),t[3]=1,t}function dv(t){return t[0]=0,t[1]=0,t[2]=0,t[3]=1,t}function Gm(t,e,r){r=r*.5;var n=Math.sin(r);return t[0]=n*e[0],t[1]=n*e[1],t[2]=n*e[2],t[3]=Math.cos(r),t}function fv(t,e){var r=Math.acos(e[3])*2,n=Math.sin(r/2);return n>G?(t[0]=e[0]/n,t[1]=e[1]/n,t[2]=e[2]/n):(t[0]=1,t[1]=0,t[2]=0),r}function hv(t,e){var r=Km(t,e);return Math.acos(2*r*r-1)}function Vm(t,e,r){var n=e[0],i=e[1],a=e[2],o=e[3],s=r[0],c=r[1],l=r[2],u=r[3];return t[0]=n*u+o*s+i*l-a*c,t[1]=i*u+o*c+a*s-n*l,t[2]=a*u+o*l+n*c-i*s,t[3]=o*u-n*s-i*c-a*l,t}function mv(t,e,r){r*=.5;var n=e[0],i=e[1],a=e[2],o=e[3],s=Math.sin(r),c=Math.cos(r);return t[0]=n*c+o*s,t[1]=i*c+a*s,t[2]=a*c-i*s,t[3]=o*c-n*s,t}function pv(t,e,r){r*=.5;var n=e[0],i=e[1],a=e[2],o=e[3],s=Math.sin(r),c=Math.cos(r);return t[0]=n*c-a*s,t[1]=i*c+o*s,t[2]=a*c+n*s,t[3]=o*c-i*s,t}function gv(t,e,r){r*=.5;var n=e[0],i=e[1],a=e[2],o=e[3],s=Math.sin(r),c=Math.cos(r);return t[0]=n*c+i*s,t[1]=i*c-n*s,t[2]=a*c+o*s,t[3]=o*c-a*s,t}function yv(t,e){var r=e[0],n=e[1],i=e[2];return t[0]=r,t[1]=n,t[2]=i,t[3]=Math.sqrt(Math.abs(1-r*r-n*n-i*i)),t}function Hm(t,e){var r=e[0],n=e[1],i=e[2],a=e[3],o=Math.sqrt(r*r+n*n+i*i),s=Math.exp(a),c=o>0?s*Math.sin(o)/o:0;return t[0]=r*c,t[1]=n*c,t[2]=i*c,t[3]=s*Math.cos(o),t}function Wm(t,e){var r=e[0],n=e[1],i=e[2],a=e[3],o=Math.sqrt(r*r+n*n+i*i),s=o>0?Math.atan2(o,a)/o:0;return t[0]=r*s,t[1]=n*s,t[2]=i*s,t[3]=.5*Math.log(r*r+n*n+i*i+a*a),t}function bv(t,e,r){return Wm(t,e),$m(t,t,r),Hm(t,t),t}function mc(t,e,r,n){var i=e[0],a=e[1],o=e[2],s=e[3],c=r[0],l=r[1],u=r[2],d=r[3],f,h,m,g,p;return h=i*c+a*l+o*u+s*d,h<0&&(h=-h,c=-c,l=-l,u=-u,d=-d),1-h>G?(f=Math.acos(h),m=Math.sin(f),g=Math.sin((1-n)*f)/m,p=Math.sin(n*f)/m):(g=1-n,p=n),t[0]=g*i+p*c,t[1]=g*a+p*l,t[2]=g*o+p*u,t[3]=g*s+p*d,t}function xv(t){var e=lr(),r=lr(),n=lr(),i=Math.sqrt(1-e),a=Math.sqrt(e);return t[0]=i*Math.sin(2*Math.PI*r),t[1]=i*Math.cos(2*Math.PI*r),t[2]=a*Math.sin(2*Math.PI*n),t[3]=a*Math.cos(2*Math.PI*n),t}function vv(t,e){var r=e[0],n=e[1],i=e[2],a=e[3],o=r*r+n*n+i*i+a*a,s=o?1/o:0;return t[0]=-r*s,t[1]=-n*s,t[2]=-i*s,t[3]=a*s,t}function _v(t,e){return t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=e[3],t}function Xm(t,e){var r=e[0]+e[4]+e[8],n;if(r>0)n=Math.sqrt(r+1),t[3]=.5*n,n=.5/n,t[0]=(e[5]-e[7])*n,t[1]=(e[6]-e[2])*n,t[2]=(e[1]-e[3])*n;else{var i=0;e[4]>e[0]&&(i=1),e[8]>e[i*3+i]&&(i=2);var a=(i+1)%3,o=(i+2)%3;n=Math.sqrt(e[i*3+i]-e[a*3+a]-e[o*3+o]+1),t[i]=.5*n,n=.5/n,t[3]=(e[a*3+o]-e[o*3+a])*n,t[a]=(e[a*3+i]+e[i*3+a])*n,t[o]=(e[o*3+i]+e[i*3+o])*n}return t}function Sv(t,e,r,n){var i=arguments.length>4&&arguments[4]!==void 0?arguments[4]:bm,a=Math.PI/360;e*=a,n*=a,r*=a;var o=Math.sin(e),s=Math.cos(e),c=Math.sin(r),l=Math.cos(r),u=Math.sin(n),d=Math.cos(n);switch(i){case"xyz":t[0]=o*l*d+s*c*u,t[1]=s*c*d-o*l*u,t[2]=s*l*u+o*c*d,t[3]=s*l*d-o*c*u;break;case"xzy":t[0]=o*l*d-s*c*u,t[1]=s*c*d-o*l*u,t[2]=s*l*u+o*c*d,t[3]=s*l*d+o*c*u;break;case"yxz":t[0]=o*l*d+s*c*u,t[1]=s*c*d-o*l*u,t[2]=s*l*u-o*c*d,t[3]=s*l*d+o*c*u;break;case"yzx":t[0]=o*l*d+s*c*u,t[1]=s*c*d+o*l*u,t[2]=s*l*u-o*c*d,t[3]=s*l*d-o*c*u;break;case"zxy":t[0]=o*l*d-s*c*u,t[1]=s*c*d+o*l*u,t[2]=s*l*u+o*c*d,t[3]=s*l*d-o*c*u;break;case"zyx":t[0]=o*l*d-s*c*u,t[1]=s*c*d+o*l*u,t[2]=s*l*u-o*c*d,t[3]=s*l*d+o*c*u;break;default:throw new Error("Unknown angle order "+i)}return t}function wv(t){return"quat("+t[0]+", "+t[1]+", "+t[2]+", "+t[3]+")"}var Mv=Cd,Av=Bd,Ev=Fd,Tv=Id,Lv=Dd,Pv=Vm,$m=kd,Km=hc,Rv=zd,Ym=dc,Cv=Ym,qm=fc,Bv=qm,Gd=Ud,Fv=Od;function Iv(t,e){return Math.abs(hc(t,e))>=1-G}var Dv=(function(){var t=cc(),e=uc(1,0,0),r=uc(0,1,0);return function(n,i,a){var o=ms(i,a);return o<-.999999?(ps(t,e,i),Rd(t)<1e-6&&ps(t,r,i),Pd(t,t),Gm(n,t,Math.PI),n):o>.999999?(n[0]=0,n[1]=0,n[2]=0,n[3]=1,n):(ps(t,i,a),n[0]=t[0],n[1]=t[1],n[2]=t[2],n[3]=1+o,Gd(n,n))}})(),kv=(function(){var t=Nd(),e=Nd();return function(r,n,i,a,o,s){return mc(t,n,o,s),mc(e,i,a,s),mc(r,t,e,2*s*(1-s)),r}})(),Uv=(function(){var t=Ld();return function(e,r,n,i){return t[0]=n[0],t[3]=n[1],t[6]=n[2],t[1]=i[0],t[4]=i[1],t[7]=i[2],t[2]=-r[0],t[5]=-r[1],t[8]=-r[2],Gd(e,Xm(e,t))}})();var gc=class{constructor(e,r){this._position=L.create();this._angles=L.create();this._bobAngles=L.create();this._bobOffset=L.create();this._kickAngles=L.create();this._rollAngle=0;this._fov=90;this._aspect=1;this._near=.1;this._far=1e3;this._viewMatrix=F.create();this._projectionMatrix=F.create();this._viewProjectionMatrix=F.create();this._dirty=!0;e!==void 0&&r!==void 0&&r>0&&(this._aspect=e/r)}get position(){return this._position}set position(e){L.equals(this._position,e)||(L.copy(this._position,e),this._dirty=!0,this.triggerMoveEvent())}get angles(){return this._angles}set angles(e){L.equals(this._angles,e)||(L.copy(this._angles,e),this._dirty=!0,this.triggerMoveEvent())}get bobAngles(){return this._bobAngles}set bobAngles(e){L.copy(this._bobAngles,e),this._dirty=!0}get kickAngles(){return this._kickAngles}set kickAngles(e){L.copy(this._kickAngles,e),this._dirty=!0}get bobOffset(){return this._bobOffset}set bobOffset(e){L.copy(this._bobOffset,e),this._dirty=!0}get rollAngle(){return this._rollAngle}set rollAngle(e){this._rollAngle=e,this._dirty=!0}get fov(){return this._fov}set fov(e){this._fov=e,this._dirty=!0}get aspect(){return this._aspect}set aspect(e){this._aspect=e,this._dirty=!0}toState(){return{position:L.clone(this._position),angles:L.clone(this._angles),fov:this._fov,aspect:this._aspect,near:this._near,far:this._far}}setPosition(e,r,n){let i=L.fromValues(e,r,n);L.equals(this._position,i)||(L.copy(this._position,i),this._dirty=!0,this.triggerMoveEvent())}setRotation(e,r,n){let i=L.fromValues(e,r,n);L.equals(this._angles,i)||(L.copy(this._angles,i),this._dirty=!0,this.triggerMoveEvent())}setFov(e){this.fov=e}setAspectRatio(e){this.aspect=e}lookAt(e){let r=L.create();if(L.subtract(r,e,this._position),L.length(r)<.001)return;let i=Math.atan2(r[1],r[0])*pu,a=Math.hypot(r[0],r[1]),o=-Math.atan2(r[2],a)*pu;this.setRotation(o,i,0)}triggerMoveEvent(){this.onCameraMove&&this.onCameraMove({position:L.clone(this._position),angles:L.clone(this._angles)})}get viewMatrix(){return this.updateMatrices(),this._viewMatrix}get projectionMatrix(){return this.updateMatrices(),this._projectionMatrix}get viewProjectionMatrix(){return this.updateMatrices(),this._viewProjectionMatrix}getViewmodelProjectionMatrix(e){let r=F.create();return F.perspective(r,e*Ae,this._aspect,this._near,this._far),r}screenToWorldRay(e,r){let n=e*2-1,i=1-r*2,a=L.fromValues(n,i,-1),o=L.fromValues(n,i,1),s=F.create();F.invert(s,this.viewProjectionMatrix);let c=L.create(),l=L.create();L.transformMat4(c,a,s),L.transformMat4(l,o,s);let u=L.create();return L.subtract(u,l,c),L.normalize(u,u),{origin:L.clone(this._position),direction:u}}updateMatrices(){if(!this._dirty)return;F.perspective(this._projectionMatrix,this._fov*Ae,this._aspect,this._near,this._far);let e=F.fromValues(0,0,-1,0,-1,0,0,0,0,1,0,0,0,0,0,1),r=this._angles[0]+this._bobAngles[0]+this._kickAngles[0],n=this._angles[1]+this._bobAngles[1]+this._kickAngles[1],i=this._angles[2]+this._bobAngles[2]+this._kickAngles[2]+this._rollAngle,a=r*Ae,o=n*Ae,s=i*Ae,c=F.create();F.identity(c),F.rotateZ(c,c,-o),F.rotateY(c,c,-a),F.rotateX(c,c,-s);let l=F.create();F.multiply(l,e,c);let u=L.add(L.create(),this._position,this._bobOffset),d=L.negate(L.create(),u),f=L.create();L.transformMat4(f,d,c);let h=L.fromValues(f[1]?-f[1]:0,f[2]||0,f[0]?-f[0]:0);F.copy(this._viewMatrix,l),this._viewMatrix[12]=h[0],this._viewMatrix[13]=h[1],this._viewMatrix[14]=h[2],F.multiply(this._viewProjectionMatrix,this._projectionMatrix,this._viewMatrix),this._dirty=!1}};var zv=[.2,.2,.2],Ov={x:0,y:0,z:1},Nv=[.8,.8,.8];function Vd(t,e,r){return t+(e-t)*r}function Ta(t,e,r){return{x:Vd(t.x,e.x,r),y:Vd(t.y,e.y,r),z:Vd(t.z,e.z,r)}}function Ea(t){return t<0?0:t>1?1:t}function Hd(t){let e=[],r=[];for(let n of t.triangles){let i=e.length,[a,o,s]=n.indices,c=t.texCoords[a],l=t.texCoords[o],u=t.texCoords[s];if(!c||!l||!u)throw new Error(`Missing texCoord for triangle in surface ${t.name}`);e.push({vertexIndex:a,texCoord:[c.s,1-c.t]},{vertexIndex:o,texCoord:[l.s,1-l.t]},{vertexIndex:s,texCoord:[u.s,1-u.t]}),r.push(i,i+1,i+2)}return{vertices:e,indices:new Uint16Array(r)}}function Gv(t,e,r){let n=r?.ambient??zv,i=r?.directional??{direction:Ov,color:Nv},a=Kr(t),o=Kr(i.direction),s=Ea(a.x*o.x+a.y*o.y+a.z*o.z),c=n[0]+i.color[0]*s,l=n[1]+i.color[1]*s,u=n[2]+i.color[2]*s;if(r?.dynamicLights){let d=r.modelMatrix?Qf(r.modelMatrix,e):e;for(let f of r.dynamicLights){let h=d.x-f.origin.x,m=d.y-f.origin.y,g=d.z-f.origin.z,p=h*h+m*m+g*g,y=f.radius*f.radius;if(p<y&&y>0){let v=1-Math.sqrt(p)/f.radius,b=Math.sqrt(p),x=b>0?Ea(-(h*a.x+m*a.y+g*a.z)/b):0,_=Ea(v*x);c+=f.color[0]*_,l+=f.color[1]*_,u+=f.color[2]*_}}}return[Ea(c),Ea(l),Ea(u)]}function Wd(t,e,r,n){let i=t.vertices[r.frame0],a=t.vertices[r.frame1];if(!i||!a)throw new Error("Requested MD3 frames are out of range");let o=new Float32Array(e.vertices.length*12);return e.vertices.forEach((s,c)=>{let l=i[s.vertexIndex],u=a[s.vertexIndex];if(!l||!u)throw new Error(`Vertex index ${s.vertexIndex} missing for frame`);let d=Ta(l.position,u.position,r.lerp),f=Kr(Ta(l.normal,u.normal,r.lerp)),h=Gv(f,d,n),m=c*12;o[m]=d.x,o[m+1]=d.y,o[m+2]=d.z,o[m+3]=f.x,o[m+4]=f.y,o[m+5]=f.z,o[m+6]=s.texCoord[0],o[m+7]=s.texCoord[1],o[m+8]=h[0],o[m+9]=h[1],o[m+10]=h[2],o[m+11]=1}),o}function Zm(t,e,r){let n=t.tags[0];if(!n)return null;let i=n.findIndex(g=>g.name===r);if(i===-1)return null;let a=t.tags[e.frame0]?.[i],o=t.tags[e.frame1]?.[i];if(!a||!o)throw new Error(`Tag ${r} is missing for one of the interpolated frames`);let s=Ta(a.origin,o.origin,e.lerp),c=Kr(Ta(a.axis[0],o.axis[0],e.lerp)),l=Kr(Ta(a.axis[1],o.axis[1],e.lerp)),u=Kr(Ta(a.axis[2],o.axis[2],e.lerp)),d=c,f=Kr({x:l.x-d.x*(d.x*l.x+d.y*l.y+d.z*l.z),y:l.y-d.y*(d.x*l.x+d.y*l.y+d.z*l.z),z:l.z-d.z*(d.x*l.x+d.y*l.y+d.z*l.z)}),h=Kr({x:d.y*f.z-d.z*f.y,y:d.z*f.x-d.x*f.z,z:d.x*f.y-d.y*f.x}),m=[d,f,h];return{origin:s,axis:m,matrix:Jf(s,m)}}var Xd=`#version 300 es
497
+ }`;function z1(t){let e=t.x*t.x+t.y*t.y+t.z*t.z;if(e<=0)return{x:0,y:0,z:1};let r=1/Math.sqrt(e);return{x:t.x*r,y:t.y*r,z:t.z*r}}function wd(t,e,r){return t+(e-t)*r}function ym(t,e,r){return{x:wd(t.x,e.x,r),y:wd(t.y,e.y,r),z:wd(t.z,e.z,r)}}function O1(t,e,r){return[t/r.skinWidth,1-e/r.skinHeight]}function Ed(t){if(t.glCommands.length===0){let n=[],i=[];return t.triangles.forEach(a=>{let o=n.length;for(let s=0;s<3;s+=1){let c=a.vertexIndices[s],l=a.texCoordIndices[s],u=t.texCoords[l];n.push({vertexIndex:c,texCoord:O1(u.s,u.t,t.header)})}i.push(o,o+1,o+2)}),{vertices:n,indices:new Uint16Array(i)}}let e=[],r=[];for(let n of t.glCommands){let i=e.length;if(e.push(...n.vertices.map(a=>({vertexIndex:a.vertexIndex,texCoord:[a.s,1-a.t]}))),n.mode==="strip")for(let a=0;a<n.vertices.length-2;a+=1){let o=a%2===0,s=i+a+(o?0:1),c=i+a+(o?1:0),l=i+a+2;r.push(s,c,l)}else for(let a=1;a<n.vertices.length-1;a+=1)r.push(i,i+a,i+a+1)}return{vertices:e,indices:new Uint16Array(r)}}function Ld(t,e,r){let{frame0:n,frame1:i,lerp:a}=r,o=t.frames[n],s=t.frames[i];if(!o||!s)throw new Error("Requested MD2 frames are out of range");let c=new Float32Array(e.vertices.length*8);return e.vertices.forEach((l,u)=>{let d=o.vertices[l.vertexIndex],f=s.vertices[l.vertexIndex];if(!d||!f)throw new Error("MD2 vertex index out of range for frame");let h=ym(d.position,f.position,a),m=z1(ym(d.normal,f.normal,a)),g=u*8;c[g]=h.x,c[g+1]=h.y,c[g+2]=h.z,c[g+3]=m.x,c[g+4]=m.y,c[g+5]=m.z,c[g+6]=l.texCoord[0],c[g+7]=l.texCoord[1]}),c}var wa=class{constructor(e,r,n){this.gl=e,this.geometry=Ed(r),this.vertexBuffer=new Ce(e,e.STATIC_DRAW),this.indexBuffer=new st(e,e.STATIC_DRAW),this.vertexArray=new Be(e),this.indexCount=this.geometry.indices.length,this.vertexArray.configureAttributes([{index:0,size:3,type:e.FLOAT,stride:32,offset:0},{index:1,size:3,type:e.FLOAT,stride:32,offset:12},{index:2,size:2,type:e.FLOAT,stride:32,offset:24}],this.vertexBuffer),this.vertexArray.bind(),this.indexBuffer.bind(),this.indexBuffer.upload(this.geometry.indices,e.STATIC_DRAW),this.update(r,n)}update(e,r){let n=Ld(e,this.geometry,r);this.vertexBuffer.upload(n,this.gl.STATIC_DRAW)}bind(){this.vertexArray.bind(),this.indexBuffer.bind()}dispose(){this.vertexBuffer.dispose(),this.indexBuffer.dispose(),this.vertexArray.dispose(),this.wireframeIndexBuffer?.dispose()}},Ma=class{constructor(e){this.uniformDlights=[];this.gl=e,this.program=ce.create(e,{vertex:Md,fragment:Ad},{a_position:0,a_normal:1,a_texCoord:2}),this.uniformMvp=this.program.getUniformLocation("u_modelViewProjection"),this.uniformModelMatrix=this.program.getUniformLocation("u_modelMatrix"),this.uniformLightDir=this.program.getUniformLocation("u_lightDir"),this.uniformAmbient=this.program.getUniformLocation("u_ambient"),this.uniformTint=this.program.getUniformLocation("u_tint"),this.uniformDiffuse=this.program.getUniformLocation("u_diffuseMap"),this.uniformRenderMode=this.program.getUniformLocation("u_renderMode"),this.uniformSolidColor=this.program.getUniformLocation("u_solidColor"),this.uniformNumDlights=this.program.getUniformLocation("u_numDlights");for(let r=0;r<Or;r++)this.uniformDlights.push({pos:this.program.getUniformLocation(`u_dlights[${r}].position`),color:this.program.getUniformLocation(`u_dlights[${r}].color`),intensity:this.program.getUniformLocation(`u_dlights[${r}].intensity`)});this.uniformBrightness=this.program.getUniformLocation("u_brightness"),this.uniformGamma=this.program.getUniformLocation("u_gamma"),this.uniformFullbright=this.program.getUniformLocation("u_fullbright"),this.uniformGlobalAmbient=this.program.getUniformLocation("u_globalAmbient")}get shaderSize(){return this.program.sourceSize}bind(e){let{modelViewProjection:r,modelMatrix:n,lightDirection:i=[0,0,1],ambientLight:a=.2,tint:o=[1,1,1,1],diffuseSampler:s=0,dlights:c=[],renderMode:l,brightness:u=1,gamma:d=1,fullbright:f=!1,ambient:h=0}=e,m=new Float32Array(i),g=new Float32Array(o);this.program.use(),this.gl.uniformMatrix4fv(this.uniformMvp,!1,r),n?this.gl.uniformMatrix4fv(this.uniformModelMatrix,!1,n):this.gl.uniformMatrix4fv(this.uniformModelMatrix,!1,new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1])),this.gl.uniform3fv(this.uniformLightDir,m),this.gl.uniform1f(this.uniformAmbient,a),this.gl.uniform4fv(this.uniformTint,g),this.gl.uniform1i(this.uniformDiffuse,s);let p=0,y=[1,1,1,1];l&&(l.mode==="solid"||l.mode==="wireframe"?p=1:l.mode==="solid-faceted"&&(p=2),l.color?y=[...l.color]:l.generateRandomColor),this.gl.uniform1i(this.uniformRenderMode,p),this.gl.uniform4f(this.uniformSolidColor,y[0],y[1],y[2],y[3]);let v=Math.min(c.length,Or);this.gl.uniform1i(this.uniformNumDlights,v);for(let b=0;b<v;b++){let x=c[b];this.gl.uniform3f(this.uniformDlights[b].pos,x.origin.x,x.origin.y,x.origin.z),this.gl.uniform3f(this.uniformDlights[b].color,x.color.x,x.color.y,x.color.z),this.gl.uniform1f(this.uniformDlights[b].intensity,x.intensity)}this.gl.uniform1f(this.uniformBrightness,u),this.gl.uniform1f(this.uniformGamma,d),this.gl.uniform1i(this.uniformFullbright,f?1:0),this.gl.uniform1f(this.uniformGlobalAmbient,h)}draw(e,r){if(e.vertexArray.bind(),r&&r.mode==="wireframe"){if(!e.wireframeIndexBuffer){e.wireframeIndexBuffer=new st(this.gl,this.gl.STATIC_DRAW);let n=xa(e.geometry.indices);e.wireframeIndexBuffer.upload(n),e.wireframeIndexCount=n.length}e.wireframeIndexBuffer.bind(),this.gl.drawElements(this.gl.LINES,e.wireframeIndexCount,this.gl.UNSIGNED_SHORT,0)}else e.indexBuffer.bind(),this.gl.drawElements(this.gl.TRIANGLES,e.indexCount,this.gl.UNSIGNED_SHORT,0)}dispose(){this.program.dispose()}};var G=1e-6,xe=typeof Float32Array<"u"?Float32Array:Array,lr=Math.random,bm="zyx";function un(t){return t>=0?Math.round(t):t%.5===0?Math.floor(t):Math.round(t)}var pT=Math.PI/180,gT=180/Math.PI;var hs={};zi(hs,{add:()=>lb,adjoint:()=>Y1,clone:()=>G1,copy:()=>V1,create:()=>Td,determinant:()=>q1,equals:()=>fb,exactEquals:()=>db,frob:()=>sb,fromMat2d:()=>rb,fromMat4:()=>N1,fromQuat:()=>nb,fromRotation:()=>eb,fromScaling:()=>tb,fromTranslation:()=>J1,fromValues:()=>H1,identity:()=>X1,invert:()=>K1,mul:()=>hb,multiply:()=>xm,multiplyScalar:()=>cb,multiplyScalarAndAdd:()=>ub,normalFromMat4:()=>ib,projection:()=>ab,rotate:()=>j1,scale:()=>Q1,set:()=>W1,str:()=>ob,sub:()=>mb,subtract:()=>vm,translate:()=>Z1,transpose:()=>$1});function Td(){var t=new xe(9);return xe!=Float32Array&&(t[1]=0,t[2]=0,t[3]=0,t[5]=0,t[6]=0,t[7]=0),t[0]=1,t[4]=1,t[8]=1,t}function N1(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[4],t[4]=e[5],t[5]=e[6],t[6]=e[8],t[7]=e[9],t[8]=e[10],t}function G1(t){var e=new xe(9);return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],e}function V1(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[4]=e[4],t[5]=e[5],t[6]=e[6],t[7]=e[7],t[8]=e[8],t}function H1(t,e,r,n,i,a,o,s,c){var l=new xe(9);return l[0]=t,l[1]=e,l[2]=r,l[3]=n,l[4]=i,l[5]=a,l[6]=o,l[7]=s,l[8]=c,l}function W1(t,e,r,n,i,a,o,s,c,l){return t[0]=e,t[1]=r,t[2]=n,t[3]=i,t[4]=a,t[5]=o,t[6]=s,t[7]=c,t[8]=l,t}function X1(t){return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=1,t[5]=0,t[6]=0,t[7]=0,t[8]=1,t}function $1(t,e){if(t===e){var r=e[1],n=e[2],i=e[5];t[1]=e[3],t[2]=e[6],t[3]=r,t[5]=e[7],t[6]=n,t[7]=i}else t[0]=e[0],t[1]=e[3],t[2]=e[6],t[3]=e[1],t[4]=e[4],t[5]=e[7],t[6]=e[2],t[7]=e[5],t[8]=e[8];return t}function K1(t,e){var r=e[0],n=e[1],i=e[2],a=e[3],o=e[4],s=e[5],c=e[6],l=e[7],u=e[8],d=u*o-s*l,f=-u*a+s*c,h=l*a-o*c,m=r*d+n*f+i*h;return m?(m=1/m,t[0]=d*m,t[1]=(-u*n+i*l)*m,t[2]=(s*n-i*o)*m,t[3]=f*m,t[4]=(u*r-i*c)*m,t[5]=(-s*r+i*a)*m,t[6]=h*m,t[7]=(-l*r+n*c)*m,t[8]=(o*r-n*a)*m,t):null}function Y1(t,e){var r=e[0],n=e[1],i=e[2],a=e[3],o=e[4],s=e[5],c=e[6],l=e[7],u=e[8];return t[0]=o*u-s*l,t[1]=i*l-n*u,t[2]=n*s-i*o,t[3]=s*c-a*u,t[4]=r*u-i*c,t[5]=i*a-r*s,t[6]=a*l-o*c,t[7]=n*c-r*l,t[8]=r*o-n*a,t}function q1(t){var e=t[0],r=t[1],n=t[2],i=t[3],a=t[4],o=t[5],s=t[6],c=t[7],l=t[8];return e*(l*a-o*c)+r*(-l*i+o*s)+n*(c*i-a*s)}function xm(t,e,r){var n=e[0],i=e[1],a=e[2],o=e[3],s=e[4],c=e[5],l=e[6],u=e[7],d=e[8],f=r[0],h=r[1],m=r[2],g=r[3],p=r[4],y=r[5],v=r[6],b=r[7],x=r[8];return t[0]=f*n+h*o+m*l,t[1]=f*i+h*s+m*u,t[2]=f*a+h*c+m*d,t[3]=g*n+p*o+y*l,t[4]=g*i+p*s+y*u,t[5]=g*a+p*c+y*d,t[6]=v*n+b*o+x*l,t[7]=v*i+b*s+x*u,t[8]=v*a+b*c+x*d,t}function Z1(t,e,r){var n=e[0],i=e[1],a=e[2],o=e[3],s=e[4],c=e[5],l=e[6],u=e[7],d=e[8],f=r[0],h=r[1];return t[0]=n,t[1]=i,t[2]=a,t[3]=o,t[4]=s,t[5]=c,t[6]=f*n+h*o+l,t[7]=f*i+h*s+u,t[8]=f*a+h*c+d,t}function j1(t,e,r){var n=e[0],i=e[1],a=e[2],o=e[3],s=e[4],c=e[5],l=e[6],u=e[7],d=e[8],f=Math.sin(r),h=Math.cos(r);return t[0]=h*n+f*o,t[1]=h*i+f*s,t[2]=h*a+f*c,t[3]=h*o-f*n,t[4]=h*s-f*i,t[5]=h*c-f*a,t[6]=l,t[7]=u,t[8]=d,t}function Q1(t,e,r){var n=r[0],i=r[1];return t[0]=n*e[0],t[1]=n*e[1],t[2]=n*e[2],t[3]=i*e[3],t[4]=i*e[4],t[5]=i*e[5],t[6]=e[6],t[7]=e[7],t[8]=e[8],t}function J1(t,e){return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=1,t[5]=0,t[6]=e[0],t[7]=e[1],t[8]=1,t}function eb(t,e){var r=Math.sin(e),n=Math.cos(e);return t[0]=n,t[1]=r,t[2]=0,t[3]=-r,t[4]=n,t[5]=0,t[6]=0,t[7]=0,t[8]=1,t}function tb(t,e){return t[0]=e[0],t[1]=0,t[2]=0,t[3]=0,t[4]=e[1],t[5]=0,t[6]=0,t[7]=0,t[8]=1,t}function rb(t,e){return t[0]=e[0],t[1]=e[1],t[2]=0,t[3]=e[2],t[4]=e[3],t[5]=0,t[6]=e[4],t[7]=e[5],t[8]=1,t}function nb(t,e){var r=e[0],n=e[1],i=e[2],a=e[3],o=r+r,s=n+n,c=i+i,l=r*o,u=n*o,d=n*s,f=i*o,h=i*s,m=i*c,g=a*o,p=a*s,y=a*c;return t[0]=1-d-m,t[3]=u-y,t[6]=f+p,t[1]=u+y,t[4]=1-l-m,t[7]=h-g,t[2]=f-p,t[5]=h+g,t[8]=1-l-d,t}function ib(t,e){var r=e[0],n=e[1],i=e[2],a=e[3],o=e[4],s=e[5],c=e[6],l=e[7],u=e[8],d=e[9],f=e[10],h=e[11],m=e[12],g=e[13],p=e[14],y=e[15],v=r*s-n*o,b=r*c-i*o,x=r*l-a*o,_=n*c-i*s,w=n*l-a*s,S=i*l-a*c,A=u*g-d*m,L=u*p-f*m,M=u*y-h*m,P=d*p-f*g,I=d*y-h*g,D=f*y-h*p,B=v*D-b*I+x*P+_*M-w*L+S*A;return B?(B=1/B,t[0]=(s*D-c*I+l*P)*B,t[1]=(c*M-o*D-l*L)*B,t[2]=(o*I-s*M+l*A)*B,t[3]=(i*I-n*D-a*P)*B,t[4]=(r*D-i*M+a*L)*B,t[5]=(n*M-r*I-a*A)*B,t[6]=(g*S-p*w+y*_)*B,t[7]=(p*x-m*S-y*b)*B,t[8]=(m*w-g*x+y*v)*B,t):null}function ab(t,e,r){return t[0]=2/e,t[1]=0,t[2]=0,t[3]=0,t[4]=-2/r,t[5]=0,t[6]=-1,t[7]=1,t[8]=1,t}function ob(t){return"mat3("+t[0]+", "+t[1]+", "+t[2]+", "+t[3]+", "+t[4]+", "+t[5]+", "+t[6]+", "+t[7]+", "+t[8]+")"}function sb(t){return Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]+t[3]*t[3]+t[4]*t[4]+t[5]*t[5]+t[6]*t[6]+t[7]*t[7]+t[8]*t[8])}function lb(t,e,r){return t[0]=e[0]+r[0],t[1]=e[1]+r[1],t[2]=e[2]+r[2],t[3]=e[3]+r[3],t[4]=e[4]+r[4],t[5]=e[5]+r[5],t[6]=e[6]+r[6],t[7]=e[7]+r[7],t[8]=e[8]+r[8],t}function vm(t,e,r){return t[0]=e[0]-r[0],t[1]=e[1]-r[1],t[2]=e[2]-r[2],t[3]=e[3]-r[3],t[4]=e[4]-r[4],t[5]=e[5]-r[5],t[6]=e[6]-r[6],t[7]=e[7]-r[7],t[8]=e[8]-r[8],t}function cb(t,e,r){return t[0]=e[0]*r,t[1]=e[1]*r,t[2]=e[2]*r,t[3]=e[3]*r,t[4]=e[4]*r,t[5]=e[5]*r,t[6]=e[6]*r,t[7]=e[7]*r,t[8]=e[8]*r,t}function ub(t,e,r,n){return t[0]=e[0]+r[0]*n,t[1]=e[1]+r[1]*n,t[2]=e[2]+r[2]*n,t[3]=e[3]+r[3]*n,t[4]=e[4]+r[4]*n,t[5]=e[5]+r[5]*n,t[6]=e[6]+r[6]*n,t[7]=e[7]+r[7]*n,t[8]=e[8]+r[8]*n,t}function db(t,e){return t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2]&&t[3]===e[3]&&t[4]===e[4]&&t[5]===e[5]&&t[6]===e[6]&&t[7]===e[7]&&t[8]===e[8]}function fb(t,e){var r=t[0],n=t[1],i=t[2],a=t[3],o=t[4],s=t[5],c=t[6],l=t[7],u=t[8],d=e[0],f=e[1],h=e[2],m=e[3],g=e[4],p=e[5],y=e[6],v=e[7],b=e[8];return Math.abs(r-d)<=G*Math.max(1,Math.abs(r),Math.abs(d))&&Math.abs(n-f)<=G*Math.max(1,Math.abs(n),Math.abs(f))&&Math.abs(i-h)<=G*Math.max(1,Math.abs(i),Math.abs(h))&&Math.abs(a-m)<=G*Math.max(1,Math.abs(a),Math.abs(m))&&Math.abs(o-g)<=G*Math.max(1,Math.abs(o),Math.abs(g))&&Math.abs(s-p)<=G*Math.max(1,Math.abs(s),Math.abs(p))&&Math.abs(c-y)<=G*Math.max(1,Math.abs(c),Math.abs(y))&&Math.abs(l-v)<=G*Math.max(1,Math.abs(l),Math.abs(v))&&Math.abs(u-b)<=G*Math.max(1,Math.abs(u),Math.abs(b))}var hb=xm,mb=vm;var F={};zi(F,{add:()=>Jb,adjoint:()=>Sb,clone:()=>gb,copy:()=>yb,create:()=>pb,decompose:()=>Ob,determinant:()=>wb,equals:()=>nx,exactEquals:()=>rx,frob:()=>Qb,fromQuat:()=>Vb,fromQuat2:()=>kb,fromRotation:()=>Bb,fromRotationTranslation:()=>wm,fromRotationTranslationScale:()=>Nb,fromRotationTranslationScaleOrigin:()=>Gb,fromScaling:()=>Cb,fromTranslation:()=>Rb,fromValues:()=>bb,fromXRotation:()=>Fb,fromYRotation:()=>Ib,fromZRotation:()=>Db,frustum:()=>Hb,getRotation:()=>zb,getScaling:()=>Mm,getTranslation:()=>Ub,identity:()=>_m,invert:()=>_b,lookAt:()=>qb,mul:()=>ix,multiply:()=>Sm,multiplyScalar:()=>ex,multiplyScalarAndAdd:()=>tx,ortho:()=>Kb,orthoNO:()=>Em,orthoZO:()=>Yb,perspective:()=>Wb,perspectiveFromFieldOfView:()=>$b,perspectiveNO:()=>Am,perspectiveZO:()=>Xb,rotate:()=>Eb,rotateX:()=>Lb,rotateY:()=>Tb,rotateZ:()=>Pb,scale:()=>Ab,set:()=>xb,str:()=>jb,sub:()=>ax,subtract:()=>Lm,targetTo:()=>Zb,translate:()=>Mb,transpose:()=>vb});function pb(){var t=new xe(16);return xe!=Float32Array&&(t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0),t[0]=1,t[5]=1,t[10]=1,t[15]=1,t}function gb(t){var e=new xe(16);return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],e[9]=t[9],e[10]=t[10],e[11]=t[11],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15],e}function yb(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[4]=e[4],t[5]=e[5],t[6]=e[6],t[7]=e[7],t[8]=e[8],t[9]=e[9],t[10]=e[10],t[11]=e[11],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],t}function bb(t,e,r,n,i,a,o,s,c,l,u,d,f,h,m,g){var p=new xe(16);return p[0]=t,p[1]=e,p[2]=r,p[3]=n,p[4]=i,p[5]=a,p[6]=o,p[7]=s,p[8]=c,p[9]=l,p[10]=u,p[11]=d,p[12]=f,p[13]=h,p[14]=m,p[15]=g,p}function xb(t,e,r,n,i,a,o,s,c,l,u,d,f,h,m,g,p){return t[0]=e,t[1]=r,t[2]=n,t[3]=i,t[4]=a,t[5]=o,t[6]=s,t[7]=c,t[8]=l,t[9]=u,t[10]=d,t[11]=f,t[12]=h,t[13]=m,t[14]=g,t[15]=p,t}function _m(t){return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}function vb(t,e){if(t===e){var r=e[1],n=e[2],i=e[3],a=e[6],o=e[7],s=e[11];t[1]=e[4],t[2]=e[8],t[3]=e[12],t[4]=r,t[6]=e[9],t[7]=e[13],t[8]=n,t[9]=a,t[11]=e[14],t[12]=i,t[13]=o,t[14]=s}else t[0]=e[0],t[1]=e[4],t[2]=e[8],t[3]=e[12],t[4]=e[1],t[5]=e[5],t[6]=e[9],t[7]=e[13],t[8]=e[2],t[9]=e[6],t[10]=e[10],t[11]=e[14],t[12]=e[3],t[13]=e[7],t[14]=e[11],t[15]=e[15];return t}function _b(t,e){var r=e[0],n=e[1],i=e[2],a=e[3],o=e[4],s=e[5],c=e[6],l=e[7],u=e[8],d=e[9],f=e[10],h=e[11],m=e[12],g=e[13],p=e[14],y=e[15],v=r*s-n*o,b=r*c-i*o,x=r*l-a*o,_=n*c-i*s,w=n*l-a*s,S=i*l-a*c,A=u*g-d*m,L=u*p-f*m,M=u*y-h*m,P=d*p-f*g,I=d*y-h*g,D=f*y-h*p,B=v*D-b*I+x*P+_*M-w*L+S*A;return B?(B=1/B,t[0]=(s*D-c*I+l*P)*B,t[1]=(i*I-n*D-a*P)*B,t[2]=(g*S-p*w+y*_)*B,t[3]=(f*w-d*S-h*_)*B,t[4]=(c*M-o*D-l*L)*B,t[5]=(r*D-i*M+a*L)*B,t[6]=(p*x-m*S-y*b)*B,t[7]=(u*S-f*x+h*b)*B,t[8]=(o*I-s*M+l*A)*B,t[9]=(n*M-r*I-a*A)*B,t[10]=(m*w-g*x+y*v)*B,t[11]=(d*x-u*w-h*v)*B,t[12]=(s*L-o*P-c*A)*B,t[13]=(r*P-n*L+i*A)*B,t[14]=(g*b-m*_-p*v)*B,t[15]=(u*_-d*b+f*v)*B,t):null}function Sb(t,e){var r=e[0],n=e[1],i=e[2],a=e[3],o=e[4],s=e[5],c=e[6],l=e[7],u=e[8],d=e[9],f=e[10],h=e[11],m=e[12],g=e[13],p=e[14],y=e[15],v=r*s-n*o,b=r*c-i*o,x=r*l-a*o,_=n*c-i*s,w=n*l-a*s,S=i*l-a*c,A=u*g-d*m,L=u*p-f*m,M=u*y-h*m,P=d*p-f*g,I=d*y-h*g,D=f*y-h*p;return t[0]=s*D-c*I+l*P,t[1]=i*I-n*D-a*P,t[2]=g*S-p*w+y*_,t[3]=f*w-d*S-h*_,t[4]=c*M-o*D-l*L,t[5]=r*D-i*M+a*L,t[6]=p*x-m*S-y*b,t[7]=u*S-f*x+h*b,t[8]=o*I-s*M+l*A,t[9]=n*M-r*I-a*A,t[10]=m*w-g*x+y*v,t[11]=d*x-u*w-h*v,t[12]=s*L-o*P-c*A,t[13]=r*P-n*L+i*A,t[14]=g*b-m*_-p*v,t[15]=u*_-d*b+f*v,t}function wb(t){var e=t[0],r=t[1],n=t[2],i=t[3],a=t[4],o=t[5],s=t[6],c=t[7],l=t[8],u=t[9],d=t[10],f=t[11],h=t[12],m=t[13],g=t[14],p=t[15],y=e*o-r*a,v=e*s-n*a,b=r*s-n*o,x=l*m-u*h,_=l*g-d*h,w=u*g-d*m,S=e*w-r*_+n*x,A=a*w-o*_+s*x,L=l*b-u*v+d*y,M=h*b-m*v+g*y;return c*S-i*A+p*L-f*M}function Sm(t,e,r){var n=e[0],i=e[1],a=e[2],o=e[3],s=e[4],c=e[5],l=e[6],u=e[7],d=e[8],f=e[9],h=e[10],m=e[11],g=e[12],p=e[13],y=e[14],v=e[15],b=r[0],x=r[1],_=r[2],w=r[3];return t[0]=b*n+x*s+_*d+w*g,t[1]=b*i+x*c+_*f+w*p,t[2]=b*a+x*l+_*h+w*y,t[3]=b*o+x*u+_*m+w*v,b=r[4],x=r[5],_=r[6],w=r[7],t[4]=b*n+x*s+_*d+w*g,t[5]=b*i+x*c+_*f+w*p,t[6]=b*a+x*l+_*h+w*y,t[7]=b*o+x*u+_*m+w*v,b=r[8],x=r[9],_=r[10],w=r[11],t[8]=b*n+x*s+_*d+w*g,t[9]=b*i+x*c+_*f+w*p,t[10]=b*a+x*l+_*h+w*y,t[11]=b*o+x*u+_*m+w*v,b=r[12],x=r[13],_=r[14],w=r[15],t[12]=b*n+x*s+_*d+w*g,t[13]=b*i+x*c+_*f+w*p,t[14]=b*a+x*l+_*h+w*y,t[15]=b*o+x*u+_*m+w*v,t}function Mb(t,e,r){var n=r[0],i=r[1],a=r[2],o,s,c,l,u,d,f,h,m,g,p,y;return e===t?(t[12]=e[0]*n+e[4]*i+e[8]*a+e[12],t[13]=e[1]*n+e[5]*i+e[9]*a+e[13],t[14]=e[2]*n+e[6]*i+e[10]*a+e[14],t[15]=e[3]*n+e[7]*i+e[11]*a+e[15]):(o=e[0],s=e[1],c=e[2],l=e[3],u=e[4],d=e[5],f=e[6],h=e[7],m=e[8],g=e[9],p=e[10],y=e[11],t[0]=o,t[1]=s,t[2]=c,t[3]=l,t[4]=u,t[5]=d,t[6]=f,t[7]=h,t[8]=m,t[9]=g,t[10]=p,t[11]=y,t[12]=o*n+u*i+m*a+e[12],t[13]=s*n+d*i+g*a+e[13],t[14]=c*n+f*i+p*a+e[14],t[15]=l*n+h*i+y*a+e[15]),t}function Ab(t,e,r){var n=r[0],i=r[1],a=r[2];return t[0]=e[0]*n,t[1]=e[1]*n,t[2]=e[2]*n,t[3]=e[3]*n,t[4]=e[4]*i,t[5]=e[5]*i,t[6]=e[6]*i,t[7]=e[7]*i,t[8]=e[8]*a,t[9]=e[9]*a,t[10]=e[10]*a,t[11]=e[11]*a,t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],t}function Eb(t,e,r,n){var i=n[0],a=n[1],o=n[2],s=Math.sqrt(i*i+a*a+o*o),c,l,u,d,f,h,m,g,p,y,v,b,x,_,w,S,A,L,M,P,I,D,B,O;return s<G?null:(s=1/s,i*=s,a*=s,o*=s,c=Math.sin(r),l=Math.cos(r),u=1-l,d=e[0],f=e[1],h=e[2],m=e[3],g=e[4],p=e[5],y=e[6],v=e[7],b=e[8],x=e[9],_=e[10],w=e[11],S=i*i*u+l,A=a*i*u+o*c,L=o*i*u-a*c,M=i*a*u-o*c,P=a*a*u+l,I=o*a*u+i*c,D=i*o*u+a*c,B=a*o*u-i*c,O=o*o*u+l,t[0]=d*S+g*A+b*L,t[1]=f*S+p*A+x*L,t[2]=h*S+y*A+_*L,t[3]=m*S+v*A+w*L,t[4]=d*M+g*P+b*I,t[5]=f*M+p*P+x*I,t[6]=h*M+y*P+_*I,t[7]=m*M+v*P+w*I,t[8]=d*D+g*B+b*O,t[9]=f*D+p*B+x*O,t[10]=h*D+y*B+_*O,t[11]=m*D+v*B+w*O,e!==t&&(t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t)}function Lb(t,e,r){var n=Math.sin(r),i=Math.cos(r),a=e[4],o=e[5],s=e[6],c=e[7],l=e[8],u=e[9],d=e[10],f=e[11];return e!==t&&(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t[4]=a*i+l*n,t[5]=o*i+u*n,t[6]=s*i+d*n,t[7]=c*i+f*n,t[8]=l*i-a*n,t[9]=u*i-o*n,t[10]=d*i-s*n,t[11]=f*i-c*n,t}function Tb(t,e,r){var n=Math.sin(r),i=Math.cos(r),a=e[0],o=e[1],s=e[2],c=e[3],l=e[8],u=e[9],d=e[10],f=e[11];return e!==t&&(t[4]=e[4],t[5]=e[5],t[6]=e[6],t[7]=e[7],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t[0]=a*i-l*n,t[1]=o*i-u*n,t[2]=s*i-d*n,t[3]=c*i-f*n,t[8]=a*n+l*i,t[9]=o*n+u*i,t[10]=s*n+d*i,t[11]=c*n+f*i,t}function Pb(t,e,r){var n=Math.sin(r),i=Math.cos(r),a=e[0],o=e[1],s=e[2],c=e[3],l=e[4],u=e[5],d=e[6],f=e[7];return e!==t&&(t[8]=e[8],t[9]=e[9],t[10]=e[10],t[11]=e[11],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t[0]=a*i+l*n,t[1]=o*i+u*n,t[2]=s*i+d*n,t[3]=c*i+f*n,t[4]=l*i-a*n,t[5]=u*i-o*n,t[6]=d*i-s*n,t[7]=f*i-c*n,t}function Rb(t,e){return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=e[0],t[13]=e[1],t[14]=e[2],t[15]=1,t}function Cb(t,e){return t[0]=e[0],t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=e[1],t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=e[2],t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}function Bb(t,e,r){var n=r[0],i=r[1],a=r[2],o=Math.sqrt(n*n+i*i+a*a),s,c,l;return o<G?null:(o=1/o,n*=o,i*=o,a*=o,s=Math.sin(e),c=Math.cos(e),l=1-c,t[0]=n*n*l+c,t[1]=i*n*l+a*s,t[2]=a*n*l-i*s,t[3]=0,t[4]=n*i*l-a*s,t[5]=i*i*l+c,t[6]=a*i*l+n*s,t[7]=0,t[8]=n*a*l+i*s,t[9]=i*a*l-n*s,t[10]=a*a*l+c,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t)}function Fb(t,e){var r=Math.sin(e),n=Math.cos(e);return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=n,t[6]=r,t[7]=0,t[8]=0,t[9]=-r,t[10]=n,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}function Ib(t,e){var r=Math.sin(e),n=Math.cos(e);return t[0]=n,t[1]=0,t[2]=-r,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=r,t[9]=0,t[10]=n,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}function Db(t,e){var r=Math.sin(e),n=Math.cos(e);return t[0]=n,t[1]=r,t[2]=0,t[3]=0,t[4]=-r,t[5]=n,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}function wm(t,e,r){var n=e[0],i=e[1],a=e[2],o=e[3],s=n+n,c=i+i,l=a+a,u=n*s,d=n*c,f=n*l,h=i*c,m=i*l,g=a*l,p=o*s,y=o*c,v=o*l;return t[0]=1-(h+g),t[1]=d+v,t[2]=f-y,t[3]=0,t[4]=d-v,t[5]=1-(u+g),t[6]=m+p,t[7]=0,t[8]=f+y,t[9]=m-p,t[10]=1-(u+h),t[11]=0,t[12]=r[0],t[13]=r[1],t[14]=r[2],t[15]=1,t}function kb(t,e){var r=new xe(3),n=-e[0],i=-e[1],a=-e[2],o=e[3],s=e[4],c=e[5],l=e[6],u=e[7],d=n*n+i*i+a*a+o*o;return d>0?(r[0]=(s*o+u*n+c*a-l*i)*2/d,r[1]=(c*o+u*i+l*n-s*a)*2/d,r[2]=(l*o+u*a+s*i-c*n)*2/d):(r[0]=(s*o+u*n+c*a-l*i)*2,r[1]=(c*o+u*i+l*n-s*a)*2,r[2]=(l*o+u*a+s*i-c*n)*2),wm(t,e,r),t}function Ub(t,e){return t[0]=e[12],t[1]=e[13],t[2]=e[14],t}function Mm(t,e){var r=e[0],n=e[1],i=e[2],a=e[4],o=e[5],s=e[6],c=e[8],l=e[9],u=e[10];return t[0]=Math.sqrt(r*r+n*n+i*i),t[1]=Math.sqrt(a*a+o*o+s*s),t[2]=Math.sqrt(c*c+l*l+u*u),t}function zb(t,e){var r=new xe(3);Mm(r,e);var n=1/r[0],i=1/r[1],a=1/r[2],o=e[0]*n,s=e[1]*i,c=e[2]*a,l=e[4]*n,u=e[5]*i,d=e[6]*a,f=e[8]*n,h=e[9]*i,m=e[10]*a,g=o+u+m,p=0;return g>0?(p=Math.sqrt(g+1)*2,t[3]=.25*p,t[0]=(d-h)/p,t[1]=(f-c)/p,t[2]=(s-l)/p):o>u&&o>m?(p=Math.sqrt(1+o-u-m)*2,t[3]=(d-h)/p,t[0]=.25*p,t[1]=(s+l)/p,t[2]=(f+c)/p):u>m?(p=Math.sqrt(1+u-o-m)*2,t[3]=(f-c)/p,t[0]=(s+l)/p,t[1]=.25*p,t[2]=(d+h)/p):(p=Math.sqrt(1+m-o-u)*2,t[3]=(s-l)/p,t[0]=(f+c)/p,t[1]=(d+h)/p,t[2]=.25*p),t}function Ob(t,e,r,n){e[0]=n[12],e[1]=n[13],e[2]=n[14];var i=n[0],a=n[1],o=n[2],s=n[4],c=n[5],l=n[6],u=n[8],d=n[9],f=n[10];r[0]=Math.sqrt(i*i+a*a+o*o),r[1]=Math.sqrt(s*s+c*c+l*l),r[2]=Math.sqrt(u*u+d*d+f*f);var h=1/r[0],m=1/r[1],g=1/r[2],p=i*h,y=a*m,v=o*g,b=s*h,x=c*m,_=l*g,w=u*h,S=d*m,A=f*g,L=p+x+A,M=0;return L>0?(M=Math.sqrt(L+1)*2,t[3]=.25*M,t[0]=(_-S)/M,t[1]=(w-v)/M,t[2]=(y-b)/M):p>x&&p>A?(M=Math.sqrt(1+p-x-A)*2,t[3]=(_-S)/M,t[0]=.25*M,t[1]=(y+b)/M,t[2]=(w+v)/M):x>A?(M=Math.sqrt(1+x-p-A)*2,t[3]=(w-v)/M,t[0]=(y+b)/M,t[1]=.25*M,t[2]=(_+S)/M):(M=Math.sqrt(1+A-p-x)*2,t[3]=(y-b)/M,t[0]=(w+v)/M,t[1]=(_+S)/M,t[2]=.25*M),t}function Nb(t,e,r,n){var i=e[0],a=e[1],o=e[2],s=e[3],c=i+i,l=a+a,u=o+o,d=i*c,f=i*l,h=i*u,m=a*l,g=a*u,p=o*u,y=s*c,v=s*l,b=s*u,x=n[0],_=n[1],w=n[2];return t[0]=(1-(m+p))*x,t[1]=(f+b)*x,t[2]=(h-v)*x,t[3]=0,t[4]=(f-b)*_,t[5]=(1-(d+p))*_,t[6]=(g+y)*_,t[7]=0,t[8]=(h+v)*w,t[9]=(g-y)*w,t[10]=(1-(d+m))*w,t[11]=0,t[12]=r[0],t[13]=r[1],t[14]=r[2],t[15]=1,t}function Gb(t,e,r,n,i){var a=e[0],o=e[1],s=e[2],c=e[3],l=a+a,u=o+o,d=s+s,f=a*l,h=a*u,m=a*d,g=o*u,p=o*d,y=s*d,v=c*l,b=c*u,x=c*d,_=n[0],w=n[1],S=n[2],A=i[0],L=i[1],M=i[2],P=(1-(g+y))*_,I=(h+x)*_,D=(m-b)*_,B=(h-x)*w,O=(1-(f+y))*w,Q=(p+v)*w,Ge=(m+b)*S,me=(p-v)*S,Me=(1-(f+g))*S;return t[0]=P,t[1]=I,t[2]=D,t[3]=0,t[4]=B,t[5]=O,t[6]=Q,t[7]=0,t[8]=Ge,t[9]=me,t[10]=Me,t[11]=0,t[12]=r[0]+A-(P*A+B*L+Ge*M),t[13]=r[1]+L-(I*A+O*L+me*M),t[14]=r[2]+M-(D*A+Q*L+Me*M),t[15]=1,t}function Vb(t,e){var r=e[0],n=e[1],i=e[2],a=e[3],o=r+r,s=n+n,c=i+i,l=r*o,u=n*o,d=n*s,f=i*o,h=i*s,m=i*c,g=a*o,p=a*s,y=a*c;return t[0]=1-d-m,t[1]=u+y,t[2]=f-p,t[3]=0,t[4]=u-y,t[5]=1-l-m,t[6]=h+g,t[7]=0,t[8]=f+p,t[9]=h-g,t[10]=1-l-d,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}function Hb(t,e,r,n,i,a,o){var s=1/(r-e),c=1/(i-n),l=1/(a-o);return t[0]=a*2*s,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=a*2*c,t[6]=0,t[7]=0,t[8]=(r+e)*s,t[9]=(i+n)*c,t[10]=(o+a)*l,t[11]=-1,t[12]=0,t[13]=0,t[14]=o*a*2*l,t[15]=0,t}function Am(t,e,r,n,i){var a=1/Math.tan(e/2);if(t[0]=a/r,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=a,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=-1,t[12]=0,t[13]=0,t[15]=0,i!=null&&i!==1/0){var o=1/(n-i);t[10]=(i+n)*o,t[14]=2*i*n*o}else t[10]=-1,t[14]=-2*n;return t}var Wb=Am;function Xb(t,e,r,n,i){var a=1/Math.tan(e/2);if(t[0]=a/r,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=a,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=-1,t[12]=0,t[13]=0,t[15]=0,i!=null&&i!==1/0){var o=1/(n-i);t[10]=i*o,t[14]=i*n*o}else t[10]=-1,t[14]=-n;return t}function $b(t,e,r,n){var i=Math.tan(e.upDegrees*Math.PI/180),a=Math.tan(e.downDegrees*Math.PI/180),o=Math.tan(e.leftDegrees*Math.PI/180),s=Math.tan(e.rightDegrees*Math.PI/180),c=2/(o+s),l=2/(i+a);return t[0]=c,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=l,t[6]=0,t[7]=0,t[8]=-((o-s)*c*.5),t[9]=(i-a)*l*.5,t[10]=n/(r-n),t[11]=-1,t[12]=0,t[13]=0,t[14]=n*r/(r-n),t[15]=0,t}function Em(t,e,r,n,i,a,o){var s=1/(e-r),c=1/(n-i),l=1/(a-o);return t[0]=-2*s,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=-2*c,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=2*l,t[11]=0,t[12]=(e+r)*s,t[13]=(i+n)*c,t[14]=(o+a)*l,t[15]=1,t}var Kb=Em;function Yb(t,e,r,n,i,a,o){var s=1/(e-r),c=1/(n-i),l=1/(a-o);return t[0]=-2*s,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=-2*c,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=l,t[11]=0,t[12]=(e+r)*s,t[13]=(i+n)*c,t[14]=a*l,t[15]=1,t}function qb(t,e,r,n){var i,a,o,s,c,l,u,d,f,h,m=e[0],g=e[1],p=e[2],y=n[0],v=n[1],b=n[2],x=r[0],_=r[1],w=r[2];return Math.abs(m-x)<G&&Math.abs(g-_)<G&&Math.abs(p-w)<G?_m(t):(u=m-x,d=g-_,f=p-w,h=1/Math.sqrt(u*u+d*d+f*f),u*=h,d*=h,f*=h,i=v*f-b*d,a=b*u-y*f,o=y*d-v*u,h=Math.sqrt(i*i+a*a+o*o),h?(h=1/h,i*=h,a*=h,o*=h):(i=0,a=0,o=0),s=d*o-f*a,c=f*i-u*o,l=u*a-d*i,h=Math.sqrt(s*s+c*c+l*l),h?(h=1/h,s*=h,c*=h,l*=h):(s=0,c=0,l=0),t[0]=i,t[1]=s,t[2]=u,t[3]=0,t[4]=a,t[5]=c,t[6]=d,t[7]=0,t[8]=o,t[9]=l,t[10]=f,t[11]=0,t[12]=-(i*m+a*g+o*p),t[13]=-(s*m+c*g+l*p),t[14]=-(u*m+d*g+f*p),t[15]=1,t)}function Zb(t,e,r,n){var i=e[0],a=e[1],o=e[2],s=n[0],c=n[1],l=n[2],u=i-r[0],d=a-r[1],f=o-r[2],h=u*u+d*d+f*f;h>0&&(h=1/Math.sqrt(h),u*=h,d*=h,f*=h);var m=c*f-l*d,g=l*u-s*f,p=s*d-c*u;return h=m*m+g*g+p*p,h>0&&(h=1/Math.sqrt(h),m*=h,g*=h,p*=h),t[0]=m,t[1]=g,t[2]=p,t[3]=0,t[4]=d*p-f*g,t[5]=f*m-u*p,t[6]=u*g-d*m,t[7]=0,t[8]=u,t[9]=d,t[10]=f,t[11]=0,t[12]=i,t[13]=a,t[14]=o,t[15]=1,t}function jb(t){return"mat4("+t[0]+", "+t[1]+", "+t[2]+", "+t[3]+", "+t[4]+", "+t[5]+", "+t[6]+", "+t[7]+", "+t[8]+", "+t[9]+", "+t[10]+", "+t[11]+", "+t[12]+", "+t[13]+", "+t[14]+", "+t[15]+")"}function Qb(t){return Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]+t[3]*t[3]+t[4]*t[4]+t[5]*t[5]+t[6]*t[6]+t[7]*t[7]+t[8]*t[8]+t[9]*t[9]+t[10]*t[10]+t[11]*t[11]+t[12]*t[12]+t[13]*t[13]+t[14]*t[14]+t[15]*t[15])}function Jb(t,e,r){return t[0]=e[0]+r[0],t[1]=e[1]+r[1],t[2]=e[2]+r[2],t[3]=e[3]+r[3],t[4]=e[4]+r[4],t[5]=e[5]+r[5],t[6]=e[6]+r[6],t[7]=e[7]+r[7],t[8]=e[8]+r[8],t[9]=e[9]+r[9],t[10]=e[10]+r[10],t[11]=e[11]+r[11],t[12]=e[12]+r[12],t[13]=e[13]+r[13],t[14]=e[14]+r[14],t[15]=e[15]+r[15],t}function Lm(t,e,r){return t[0]=e[0]-r[0],t[1]=e[1]-r[1],t[2]=e[2]-r[2],t[3]=e[3]-r[3],t[4]=e[4]-r[4],t[5]=e[5]-r[5],t[6]=e[6]-r[6],t[7]=e[7]-r[7],t[8]=e[8]-r[8],t[9]=e[9]-r[9],t[10]=e[10]-r[10],t[11]=e[11]-r[11],t[12]=e[12]-r[12],t[13]=e[13]-r[13],t[14]=e[14]-r[14],t[15]=e[15]-r[15],t}function ex(t,e,r){return t[0]=e[0]*r,t[1]=e[1]*r,t[2]=e[2]*r,t[3]=e[3]*r,t[4]=e[4]*r,t[5]=e[5]*r,t[6]=e[6]*r,t[7]=e[7]*r,t[8]=e[8]*r,t[9]=e[9]*r,t[10]=e[10]*r,t[11]=e[11]*r,t[12]=e[12]*r,t[13]=e[13]*r,t[14]=e[14]*r,t[15]=e[15]*r,t}function tx(t,e,r,n){return t[0]=e[0]+r[0]*n,t[1]=e[1]+r[1]*n,t[2]=e[2]+r[2]*n,t[3]=e[3]+r[3]*n,t[4]=e[4]+r[4]*n,t[5]=e[5]+r[5]*n,t[6]=e[6]+r[6]*n,t[7]=e[7]+r[7]*n,t[8]=e[8]+r[8]*n,t[9]=e[9]+r[9]*n,t[10]=e[10]+r[10]*n,t[11]=e[11]+r[11]*n,t[12]=e[12]+r[12]*n,t[13]=e[13]+r[13]*n,t[14]=e[14]+r[14]*n,t[15]=e[15]+r[15]*n,t}function rx(t,e){return t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2]&&t[3]===e[3]&&t[4]===e[4]&&t[5]===e[5]&&t[6]===e[6]&&t[7]===e[7]&&t[8]===e[8]&&t[9]===e[9]&&t[10]===e[10]&&t[11]===e[11]&&t[12]===e[12]&&t[13]===e[13]&&t[14]===e[14]&&t[15]===e[15]}function nx(t,e){var r=t[0],n=t[1],i=t[2],a=t[3],o=t[4],s=t[5],c=t[6],l=t[7],u=t[8],d=t[9],f=t[10],h=t[11],m=t[12],g=t[13],p=t[14],y=t[15],v=e[0],b=e[1],x=e[2],_=e[3],w=e[4],S=e[5],A=e[6],L=e[7],M=e[8],P=e[9],I=e[10],D=e[11],B=e[12],O=e[13],Q=e[14],Ge=e[15];return Math.abs(r-v)<=G*Math.max(1,Math.abs(r),Math.abs(v))&&Math.abs(n-b)<=G*Math.max(1,Math.abs(n),Math.abs(b))&&Math.abs(i-x)<=G*Math.max(1,Math.abs(i),Math.abs(x))&&Math.abs(a-_)<=G*Math.max(1,Math.abs(a),Math.abs(_))&&Math.abs(o-w)<=G*Math.max(1,Math.abs(o),Math.abs(w))&&Math.abs(s-S)<=G*Math.max(1,Math.abs(s),Math.abs(S))&&Math.abs(c-A)<=G*Math.max(1,Math.abs(c),Math.abs(A))&&Math.abs(l-L)<=G*Math.max(1,Math.abs(l),Math.abs(L))&&Math.abs(u-M)<=G*Math.max(1,Math.abs(u),Math.abs(M))&&Math.abs(d-P)<=G*Math.max(1,Math.abs(d),Math.abs(P))&&Math.abs(f-I)<=G*Math.max(1,Math.abs(f),Math.abs(I))&&Math.abs(h-D)<=G*Math.max(1,Math.abs(h),Math.abs(D))&&Math.abs(m-B)<=G*Math.max(1,Math.abs(m),Math.abs(B))&&Math.abs(g-O)<=G*Math.max(1,Math.abs(g),Math.abs(O))&&Math.abs(p-Q)<=G*Math.max(1,Math.abs(p),Math.abs(Q))&&Math.abs(y-Ge)<=G*Math.max(1,Math.abs(y),Math.abs(Ge))}var ix=Sm,ax=Lm;var pc={};zi(pc,{add:()=>Tv,calculateW:()=>yv,clone:()=>Mv,conjugate:()=>_v,copy:()=>Ev,create:()=>Nd,dot:()=>Km,equals:()=>Iv,exactEquals:()=>Fv,exp:()=>Hm,fromEuler:()=>Sv,fromMat3:()=>Xm,fromValues:()=>Av,getAngle:()=>hv,getAxisAngle:()=>fv,identity:()=>dv,invert:()=>vv,len:()=>Cv,length:()=>Ym,lerp:()=>Rv,ln:()=>Wm,mul:()=>Pv,multiply:()=>Vm,normalize:()=>Gd,pow:()=>bv,random:()=>xv,rotateX:()=>mv,rotateY:()=>pv,rotateZ:()=>gv,rotationTo:()=>Dv,scale:()=>$m,set:()=>Lv,setAxes:()=>Uv,setAxisAngle:()=>Gm,slerp:()=>mc,sqlerp:()=>kv,sqrLen:()=>Bv,squaredLength:()=>qm,str:()=>wv});var T={};zi(T,{add:()=>cx,angle:()=>Rx,bezier:()=>Sx,ceil:()=>ux,clone:()=>ox,copy:()=>sx,create:()=>cc,cross:()=>ps,dist:()=>zx,distance:()=>Bm,div:()=>Ux,divide:()=>Cm,dot:()=>ms,equals:()=>Ix,exactEquals:()=>Fx,floor:()=>dx,forEach:()=>Gx,fromValues:()=>uc,hermite:()=>_x,inverse:()=>bx,len:()=>Rd,length:()=>Tm,lerp:()=>xx,max:()=>hx,min:()=>fx,mul:()=>kx,multiply:()=>Rm,negate:()=>yx,normalize:()=>Pd,random:()=>wx,rotateX:()=>Lx,rotateY:()=>Tx,rotateZ:()=>Px,round:()=>mx,scale:()=>px,scaleAndAdd:()=>gx,set:()=>lx,slerp:()=>vx,sqrDist:()=>Ox,sqrLen:()=>Nx,squaredDistance:()=>Fm,squaredLength:()=>Im,str:()=>Bx,sub:()=>Dx,subtract:()=>Pm,transformMat3:()=>Ax,transformMat4:()=>Mx,transformQuat:()=>Ex,zero:()=>Cx});function cc(){var t=new xe(3);return xe!=Float32Array&&(t[0]=0,t[1]=0,t[2]=0),t}function ox(t){var e=new xe(3);return e[0]=t[0],e[1]=t[1],e[2]=t[2],e}function Tm(t){var e=t[0],r=t[1],n=t[2];return Math.sqrt(e*e+r*r+n*n)}function uc(t,e,r){var n=new xe(3);return n[0]=t,n[1]=e,n[2]=r,n}function sx(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t}function lx(t,e,r,n){return t[0]=e,t[1]=r,t[2]=n,t}function cx(t,e,r){return t[0]=e[0]+r[0],t[1]=e[1]+r[1],t[2]=e[2]+r[2],t}function Pm(t,e,r){return t[0]=e[0]-r[0],t[1]=e[1]-r[1],t[2]=e[2]-r[2],t}function Rm(t,e,r){return t[0]=e[0]*r[0],t[1]=e[1]*r[1],t[2]=e[2]*r[2],t}function Cm(t,e,r){return t[0]=e[0]/r[0],t[1]=e[1]/r[1],t[2]=e[2]/r[2],t}function ux(t,e){return t[0]=Math.ceil(e[0]),t[1]=Math.ceil(e[1]),t[2]=Math.ceil(e[2]),t}function dx(t,e){return t[0]=Math.floor(e[0]),t[1]=Math.floor(e[1]),t[2]=Math.floor(e[2]),t}function fx(t,e,r){return t[0]=Math.min(e[0],r[0]),t[1]=Math.min(e[1],r[1]),t[2]=Math.min(e[2],r[2]),t}function hx(t,e,r){return t[0]=Math.max(e[0],r[0]),t[1]=Math.max(e[1],r[1]),t[2]=Math.max(e[2],r[2]),t}function mx(t,e){return t[0]=un(e[0]),t[1]=un(e[1]),t[2]=un(e[2]),t}function px(t,e,r){return t[0]=e[0]*r,t[1]=e[1]*r,t[2]=e[2]*r,t}function gx(t,e,r,n){return t[0]=e[0]+r[0]*n,t[1]=e[1]+r[1]*n,t[2]=e[2]+r[2]*n,t}function Bm(t,e){var r=e[0]-t[0],n=e[1]-t[1],i=e[2]-t[2];return Math.sqrt(r*r+n*n+i*i)}function Fm(t,e){var r=e[0]-t[0],n=e[1]-t[1],i=e[2]-t[2];return r*r+n*n+i*i}function Im(t){var e=t[0],r=t[1],n=t[2];return e*e+r*r+n*n}function yx(t,e){return t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t}function bx(t,e){return t[0]=1/e[0],t[1]=1/e[1],t[2]=1/e[2],t}function Pd(t,e){var r=e[0],n=e[1],i=e[2],a=r*r+n*n+i*i;return a>0&&(a=1/Math.sqrt(a)),t[0]=e[0]*a,t[1]=e[1]*a,t[2]=e[2]*a,t}function ms(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]}function ps(t,e,r){var n=e[0],i=e[1],a=e[2],o=r[0],s=r[1],c=r[2];return t[0]=i*c-a*s,t[1]=a*o-n*c,t[2]=n*s-i*o,t}function xx(t,e,r,n){var i=e[0],a=e[1],o=e[2];return t[0]=i+n*(r[0]-i),t[1]=a+n*(r[1]-a),t[2]=o+n*(r[2]-o),t}function vx(t,e,r,n){var i=Math.acos(Math.min(Math.max(ms(e,r),-1),1)),a=Math.sin(i),o=Math.sin((1-n)*i)/a,s=Math.sin(n*i)/a;return t[0]=o*e[0]+s*r[0],t[1]=o*e[1]+s*r[1],t[2]=o*e[2]+s*r[2],t}function _x(t,e,r,n,i,a){var o=a*a,s=o*(2*a-3)+1,c=o*(a-2)+a,l=o*(a-1),u=o*(3-2*a);return t[0]=e[0]*s+r[0]*c+n[0]*l+i[0]*u,t[1]=e[1]*s+r[1]*c+n[1]*l+i[1]*u,t[2]=e[2]*s+r[2]*c+n[2]*l+i[2]*u,t}function Sx(t,e,r,n,i,a){var o=1-a,s=o*o,c=a*a,l=s*o,u=3*a*s,d=3*c*o,f=c*a;return t[0]=e[0]*l+r[0]*u+n[0]*d+i[0]*f,t[1]=e[1]*l+r[1]*u+n[1]*d+i[1]*f,t[2]=e[2]*l+r[2]*u+n[2]*d+i[2]*f,t}function wx(t,e){e=e===void 0?1:e;var r=lr()*2*Math.PI,n=lr()*2-1,i=Math.sqrt(1-n*n)*e;return t[0]=Math.cos(r)*i,t[1]=Math.sin(r)*i,t[2]=n*e,t}function Mx(t,e,r){var n=e[0],i=e[1],a=e[2],o=r[3]*n+r[7]*i+r[11]*a+r[15];return o=o||1,t[0]=(r[0]*n+r[4]*i+r[8]*a+r[12])/o,t[1]=(r[1]*n+r[5]*i+r[9]*a+r[13])/o,t[2]=(r[2]*n+r[6]*i+r[10]*a+r[14])/o,t}function Ax(t,e,r){var n=e[0],i=e[1],a=e[2];return t[0]=n*r[0]+i*r[3]+a*r[6],t[1]=n*r[1]+i*r[4]+a*r[7],t[2]=n*r[2]+i*r[5]+a*r[8],t}function Ex(t,e,r){var n=r[0],i=r[1],a=r[2],o=r[3],s=e[0],c=e[1],l=e[2],u=i*l-a*c,d=a*s-n*l,f=n*c-i*s;return u=u+u,d=d+d,f=f+f,t[0]=s+o*u+i*f-a*d,t[1]=c+o*d+a*u-n*f,t[2]=l+o*f+n*d-i*u,t}function Lx(t,e,r,n){var i=[],a=[];return i[0]=e[0]-r[0],i[1]=e[1]-r[1],i[2]=e[2]-r[2],a[0]=i[0],a[1]=i[1]*Math.cos(n)-i[2]*Math.sin(n),a[2]=i[1]*Math.sin(n)+i[2]*Math.cos(n),t[0]=a[0]+r[0],t[1]=a[1]+r[1],t[2]=a[2]+r[2],t}function Tx(t,e,r,n){var i=[],a=[];return i[0]=e[0]-r[0],i[1]=e[1]-r[1],i[2]=e[2]-r[2],a[0]=i[2]*Math.sin(n)+i[0]*Math.cos(n),a[1]=i[1],a[2]=i[2]*Math.cos(n)-i[0]*Math.sin(n),t[0]=a[0]+r[0],t[1]=a[1]+r[1],t[2]=a[2]+r[2],t}function Px(t,e,r,n){var i=[],a=[];return i[0]=e[0]-r[0],i[1]=e[1]-r[1],i[2]=e[2]-r[2],a[0]=i[0]*Math.cos(n)-i[1]*Math.sin(n),a[1]=i[0]*Math.sin(n)+i[1]*Math.cos(n),a[2]=i[2],t[0]=a[0]+r[0],t[1]=a[1]+r[1],t[2]=a[2]+r[2],t}function Rx(t,e){var r=t[0],n=t[1],i=t[2],a=e[0],o=e[1],s=e[2],c=Math.sqrt((r*r+n*n+i*i)*(a*a+o*o+s*s)),l=c&&ms(t,e)/c;return Math.acos(Math.min(Math.max(l,-1),1))}function Cx(t){return t[0]=0,t[1]=0,t[2]=0,t}function Bx(t){return"vec3("+t[0]+", "+t[1]+", "+t[2]+")"}function Fx(t,e){return t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2]}function Ix(t,e){var r=t[0],n=t[1],i=t[2],a=e[0],o=e[1],s=e[2];return Math.abs(r-a)<=G*Math.max(1,Math.abs(r),Math.abs(a))&&Math.abs(n-o)<=G*Math.max(1,Math.abs(n),Math.abs(o))&&Math.abs(i-s)<=G*Math.max(1,Math.abs(i),Math.abs(s))}var Dx=Pm,kx=Rm,Ux=Cm,zx=Bm,Ox=Fm,Rd=Tm,Nx=Im,Gx=(function(){var t=cc();return function(e,r,n,i,a,o){var s,c;for(r||(r=3),n||(n=0),i?c=Math.min(i*r+n,e.length):c=e.length,s=n;s<c;s+=r)t[0]=e[s],t[1]=e[s+1],t[2]=e[s+2],a(t,t,o),e[s]=t[0],e[s+1]=t[1],e[s+2]=t[2];return e}})();var Aa={};zi(Aa,{add:()=>Dd,ceil:()=>Vx,clone:()=>Cd,copy:()=>Fd,create:()=>Dm,cross:()=>Zx,dist:()=>ov,distance:()=>Om,div:()=>av,divide:()=>zm,dot:()=>hc,equals:()=>rv,exactEquals:()=>Od,floor:()=>Hx,forEach:()=>uv,fromValues:()=>Bd,inverse:()=>qx,len:()=>lv,length:()=>dc,lerp:()=>zd,max:()=>Xx,min:()=>Wx,mul:()=>iv,multiply:()=>Um,negate:()=>Yx,normalize:()=>Ud,random:()=>jx,round:()=>$x,scale:()=>kd,scaleAndAdd:()=>Kx,set:()=>Id,sqrDist:()=>sv,sqrLen:()=>cv,squaredDistance:()=>Nm,squaredLength:()=>fc,str:()=>tv,sub:()=>nv,subtract:()=>km,transformMat4:()=>Qx,transformQuat:()=>Jx,zero:()=>ev});function Dm(){var t=new xe(4);return xe!=Float32Array&&(t[0]=0,t[1]=0,t[2]=0,t[3]=0),t}function Cd(t){var e=new xe(4);return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e}function Bd(t,e,r,n){var i=new xe(4);return i[0]=t,i[1]=e,i[2]=r,i[3]=n,i}function Fd(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t}function Id(t,e,r,n,i){return t[0]=e,t[1]=r,t[2]=n,t[3]=i,t}function Dd(t,e,r){return t[0]=e[0]+r[0],t[1]=e[1]+r[1],t[2]=e[2]+r[2],t[3]=e[3]+r[3],t}function km(t,e,r){return t[0]=e[0]-r[0],t[1]=e[1]-r[1],t[2]=e[2]-r[2],t[3]=e[3]-r[3],t}function Um(t,e,r){return t[0]=e[0]*r[0],t[1]=e[1]*r[1],t[2]=e[2]*r[2],t[3]=e[3]*r[3],t}function zm(t,e,r){return t[0]=e[0]/r[0],t[1]=e[1]/r[1],t[2]=e[2]/r[2],t[3]=e[3]/r[3],t}function Vx(t,e){return t[0]=Math.ceil(e[0]),t[1]=Math.ceil(e[1]),t[2]=Math.ceil(e[2]),t[3]=Math.ceil(e[3]),t}function Hx(t,e){return t[0]=Math.floor(e[0]),t[1]=Math.floor(e[1]),t[2]=Math.floor(e[2]),t[3]=Math.floor(e[3]),t}function Wx(t,e,r){return t[0]=Math.min(e[0],r[0]),t[1]=Math.min(e[1],r[1]),t[2]=Math.min(e[2],r[2]),t[3]=Math.min(e[3],r[3]),t}function Xx(t,e,r){return t[0]=Math.max(e[0],r[0]),t[1]=Math.max(e[1],r[1]),t[2]=Math.max(e[2],r[2]),t[3]=Math.max(e[3],r[3]),t}function $x(t,e){return t[0]=un(e[0]),t[1]=un(e[1]),t[2]=un(e[2]),t[3]=un(e[3]),t}function kd(t,e,r){return t[0]=e[0]*r,t[1]=e[1]*r,t[2]=e[2]*r,t[3]=e[3]*r,t}function Kx(t,e,r,n){return t[0]=e[0]+r[0]*n,t[1]=e[1]+r[1]*n,t[2]=e[2]+r[2]*n,t[3]=e[3]+r[3]*n,t}function Om(t,e){var r=e[0]-t[0],n=e[1]-t[1],i=e[2]-t[2],a=e[3]-t[3];return Math.sqrt(r*r+n*n+i*i+a*a)}function Nm(t,e){var r=e[0]-t[0],n=e[1]-t[1],i=e[2]-t[2],a=e[3]-t[3];return r*r+n*n+i*i+a*a}function dc(t){var e=t[0],r=t[1],n=t[2],i=t[3];return Math.sqrt(e*e+r*r+n*n+i*i)}function fc(t){var e=t[0],r=t[1],n=t[2],i=t[3];return e*e+r*r+n*n+i*i}function Yx(t,e){return t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=-e[3],t}function qx(t,e){return t[0]=1/e[0],t[1]=1/e[1],t[2]=1/e[2],t[3]=1/e[3],t}function Ud(t,e){var r=e[0],n=e[1],i=e[2],a=e[3],o=r*r+n*n+i*i+a*a;return o>0&&(o=1/Math.sqrt(o)),t[0]=r*o,t[1]=n*o,t[2]=i*o,t[3]=a*o,t}function hc(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]+t[3]*e[3]}function Zx(t,e,r,n){var i=r[0]*n[1]-r[1]*n[0],a=r[0]*n[2]-r[2]*n[0],o=r[0]*n[3]-r[3]*n[0],s=r[1]*n[2]-r[2]*n[1],c=r[1]*n[3]-r[3]*n[1],l=r[2]*n[3]-r[3]*n[2],u=e[0],d=e[1],f=e[2],h=e[3];return t[0]=d*l-f*c+h*s,t[1]=-(u*l)+f*o-h*a,t[2]=u*c-d*o+h*i,t[3]=-(u*s)+d*a-f*i,t}function zd(t,e,r,n){var i=e[0],a=e[1],o=e[2],s=e[3];return t[0]=i+n*(r[0]-i),t[1]=a+n*(r[1]-a),t[2]=o+n*(r[2]-o),t[3]=s+n*(r[3]-s),t}function jx(t,e){e=e===void 0?1:e;var r,n,i,a,o,s,c;c=lr(),r=c*2-1,n=(4*lr()-2)*Math.sqrt(c*-c+c),o=r*r+n*n,c=lr(),i=c*2-1,a=(4*lr()-2)*Math.sqrt(c*-c+c),s=i*i+a*a;var l=Math.sqrt((1-o)/s);return t[0]=e*r,t[1]=e*n,t[2]=e*i*l,t[3]=e*a*l,t}function Qx(t,e,r){var n=e[0],i=e[1],a=e[2],o=e[3];return t[0]=r[0]*n+r[4]*i+r[8]*a+r[12]*o,t[1]=r[1]*n+r[5]*i+r[9]*a+r[13]*o,t[2]=r[2]*n+r[6]*i+r[10]*a+r[14]*o,t[3]=r[3]*n+r[7]*i+r[11]*a+r[15]*o,t}function Jx(t,e,r){var n=r[0],i=r[1],a=r[2],o=r[3],s=e[0],c=e[1],l=e[2],u=i*l-a*c,d=a*s-n*l,f=n*c-i*s;return u=u+u,d=d+d,f=f+f,t[0]=s+o*u+i*f-a*d,t[1]=c+o*d+a*u-n*f,t[2]=l+o*f+n*d-i*u,t[3]=e[3],t}function ev(t){return t[0]=0,t[1]=0,t[2]=0,t[3]=0,t}function tv(t){return"vec4("+t[0]+", "+t[1]+", "+t[2]+", "+t[3]+")"}function Od(t,e){return t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2]&&t[3]===e[3]}function rv(t,e){var r=t[0],n=t[1],i=t[2],a=t[3],o=e[0],s=e[1],c=e[2],l=e[3];return Math.abs(r-o)<=G*Math.max(1,Math.abs(r),Math.abs(o))&&Math.abs(n-s)<=G*Math.max(1,Math.abs(n),Math.abs(s))&&Math.abs(i-c)<=G*Math.max(1,Math.abs(i),Math.abs(c))&&Math.abs(a-l)<=G*Math.max(1,Math.abs(a),Math.abs(l))}var nv=km,iv=Um,av=zm,ov=Om,sv=Nm,lv=dc,cv=fc,uv=(function(){var t=Dm();return function(e,r,n,i,a,o){var s,c;for(r||(r=4),n||(n=0),i?c=Math.min(i*r+n,e.length):c=e.length,s=n;s<c;s+=r)t[0]=e[s],t[1]=e[s+1],t[2]=e[s+2],t[3]=e[s+3],a(t,t,o),e[s]=t[0],e[s+1]=t[1],e[s+2]=t[2],e[s+3]=t[3];return e}})();function Nd(){var t=new xe(4);return xe!=Float32Array&&(t[0]=0,t[1]=0,t[2]=0),t[3]=1,t}function dv(t){return t[0]=0,t[1]=0,t[2]=0,t[3]=1,t}function Gm(t,e,r){r=r*.5;var n=Math.sin(r);return t[0]=n*e[0],t[1]=n*e[1],t[2]=n*e[2],t[3]=Math.cos(r),t}function fv(t,e){var r=Math.acos(e[3])*2,n=Math.sin(r/2);return n>G?(t[0]=e[0]/n,t[1]=e[1]/n,t[2]=e[2]/n):(t[0]=1,t[1]=0,t[2]=0),r}function hv(t,e){var r=Km(t,e);return Math.acos(2*r*r-1)}function Vm(t,e,r){var n=e[0],i=e[1],a=e[2],o=e[3],s=r[0],c=r[1],l=r[2],u=r[3];return t[0]=n*u+o*s+i*l-a*c,t[1]=i*u+o*c+a*s-n*l,t[2]=a*u+o*l+n*c-i*s,t[3]=o*u-n*s-i*c-a*l,t}function mv(t,e,r){r*=.5;var n=e[0],i=e[1],a=e[2],o=e[3],s=Math.sin(r),c=Math.cos(r);return t[0]=n*c+o*s,t[1]=i*c+a*s,t[2]=a*c-i*s,t[3]=o*c-n*s,t}function pv(t,e,r){r*=.5;var n=e[0],i=e[1],a=e[2],o=e[3],s=Math.sin(r),c=Math.cos(r);return t[0]=n*c-a*s,t[1]=i*c+o*s,t[2]=a*c+n*s,t[3]=o*c-i*s,t}function gv(t,e,r){r*=.5;var n=e[0],i=e[1],a=e[2],o=e[3],s=Math.sin(r),c=Math.cos(r);return t[0]=n*c+i*s,t[1]=i*c-n*s,t[2]=a*c+o*s,t[3]=o*c-a*s,t}function yv(t,e){var r=e[0],n=e[1],i=e[2];return t[0]=r,t[1]=n,t[2]=i,t[3]=Math.sqrt(Math.abs(1-r*r-n*n-i*i)),t}function Hm(t,e){var r=e[0],n=e[1],i=e[2],a=e[3],o=Math.sqrt(r*r+n*n+i*i),s=Math.exp(a),c=o>0?s*Math.sin(o)/o:0;return t[0]=r*c,t[1]=n*c,t[2]=i*c,t[3]=s*Math.cos(o),t}function Wm(t,e){var r=e[0],n=e[1],i=e[2],a=e[3],o=Math.sqrt(r*r+n*n+i*i),s=o>0?Math.atan2(o,a)/o:0;return t[0]=r*s,t[1]=n*s,t[2]=i*s,t[3]=.5*Math.log(r*r+n*n+i*i+a*a),t}function bv(t,e,r){return Wm(t,e),$m(t,t,r),Hm(t,t),t}function mc(t,e,r,n){var i=e[0],a=e[1],o=e[2],s=e[3],c=r[0],l=r[1],u=r[2],d=r[3],f,h,m,g,p;return h=i*c+a*l+o*u+s*d,h<0&&(h=-h,c=-c,l=-l,u=-u,d=-d),1-h>G?(f=Math.acos(h),m=Math.sin(f),g=Math.sin((1-n)*f)/m,p=Math.sin(n*f)/m):(g=1-n,p=n),t[0]=g*i+p*c,t[1]=g*a+p*l,t[2]=g*o+p*u,t[3]=g*s+p*d,t}function xv(t){var e=lr(),r=lr(),n=lr(),i=Math.sqrt(1-e),a=Math.sqrt(e);return t[0]=i*Math.sin(2*Math.PI*r),t[1]=i*Math.cos(2*Math.PI*r),t[2]=a*Math.sin(2*Math.PI*n),t[3]=a*Math.cos(2*Math.PI*n),t}function vv(t,e){var r=e[0],n=e[1],i=e[2],a=e[3],o=r*r+n*n+i*i+a*a,s=o?1/o:0;return t[0]=-r*s,t[1]=-n*s,t[2]=-i*s,t[3]=a*s,t}function _v(t,e){return t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=e[3],t}function Xm(t,e){var r=e[0]+e[4]+e[8],n;if(r>0)n=Math.sqrt(r+1),t[3]=.5*n,n=.5/n,t[0]=(e[5]-e[7])*n,t[1]=(e[6]-e[2])*n,t[2]=(e[1]-e[3])*n;else{var i=0;e[4]>e[0]&&(i=1),e[8]>e[i*3+i]&&(i=2);var a=(i+1)%3,o=(i+2)%3;n=Math.sqrt(e[i*3+i]-e[a*3+a]-e[o*3+o]+1),t[i]=.5*n,n=.5/n,t[3]=(e[a*3+o]-e[o*3+a])*n,t[a]=(e[a*3+i]+e[i*3+a])*n,t[o]=(e[o*3+i]+e[i*3+o])*n}return t}function Sv(t,e,r,n){var i=arguments.length>4&&arguments[4]!==void 0?arguments[4]:bm,a=Math.PI/360;e*=a,n*=a,r*=a;var o=Math.sin(e),s=Math.cos(e),c=Math.sin(r),l=Math.cos(r),u=Math.sin(n),d=Math.cos(n);switch(i){case"xyz":t[0]=o*l*d+s*c*u,t[1]=s*c*d-o*l*u,t[2]=s*l*u+o*c*d,t[3]=s*l*d-o*c*u;break;case"xzy":t[0]=o*l*d-s*c*u,t[1]=s*c*d-o*l*u,t[2]=s*l*u+o*c*d,t[3]=s*l*d+o*c*u;break;case"yxz":t[0]=o*l*d+s*c*u,t[1]=s*c*d-o*l*u,t[2]=s*l*u-o*c*d,t[3]=s*l*d+o*c*u;break;case"yzx":t[0]=o*l*d+s*c*u,t[1]=s*c*d+o*l*u,t[2]=s*l*u-o*c*d,t[3]=s*l*d-o*c*u;break;case"zxy":t[0]=o*l*d-s*c*u,t[1]=s*c*d+o*l*u,t[2]=s*l*u+o*c*d,t[3]=s*l*d-o*c*u;break;case"zyx":t[0]=o*l*d-s*c*u,t[1]=s*c*d+o*l*u,t[2]=s*l*u-o*c*d,t[3]=s*l*d+o*c*u;break;default:throw new Error("Unknown angle order "+i)}return t}function wv(t){return"quat("+t[0]+", "+t[1]+", "+t[2]+", "+t[3]+")"}var Mv=Cd,Av=Bd,Ev=Fd,Lv=Id,Tv=Dd,Pv=Vm,$m=kd,Km=hc,Rv=zd,Ym=dc,Cv=Ym,qm=fc,Bv=qm,Gd=Ud,Fv=Od;function Iv(t,e){return Math.abs(hc(t,e))>=1-G}var Dv=(function(){var t=cc(),e=uc(1,0,0),r=uc(0,1,0);return function(n,i,a){var o=ms(i,a);return o<-.999999?(ps(t,e,i),Rd(t)<1e-6&&ps(t,r,i),Pd(t,t),Gm(n,t,Math.PI),n):o>.999999?(n[0]=0,n[1]=0,n[2]=0,n[3]=1,n):(ps(t,i,a),n[0]=t[0],n[1]=t[1],n[2]=t[2],n[3]=1+o,Gd(n,n))}})(),kv=(function(){var t=Nd(),e=Nd();return function(r,n,i,a,o,s){return mc(t,n,o,s),mc(e,i,a,s),mc(r,t,e,2*s*(1-s)),r}})(),Uv=(function(){var t=Td();return function(e,r,n,i){return t[0]=n[0],t[3]=n[1],t[6]=n[2],t[1]=i[0],t[4]=i[1],t[7]=i[2],t[2]=-r[0],t[5]=-r[1],t[8]=-r[2],Gd(e,Xm(e,t))}})();var gc=class{constructor(e,r){this._position=T.create();this._angles=T.create();this._bobAngles=T.create();this._bobOffset=T.create();this._kickAngles=T.create();this._rollAngle=0;this._fov=90;this._aspect=1;this._near=.1;this._far=1e3;this._viewMatrix=F.create();this._projectionMatrix=F.create();this._viewProjectionMatrix=F.create();this._dirty=!0;e!==void 0&&r!==void 0&&r>0&&(this._aspect=e/r)}get position(){return this._position}set position(e){T.equals(this._position,e)||(T.copy(this._position,e),this._dirty=!0,this.triggerMoveEvent())}get angles(){return this._angles}set angles(e){T.equals(this._angles,e)||(T.copy(this._angles,e),this._dirty=!0,this.triggerMoveEvent())}get bobAngles(){return this._bobAngles}set bobAngles(e){T.copy(this._bobAngles,e),this._dirty=!0}get kickAngles(){return this._kickAngles}set kickAngles(e){T.copy(this._kickAngles,e),this._dirty=!0}get bobOffset(){return this._bobOffset}set bobOffset(e){T.copy(this._bobOffset,e),this._dirty=!0}get rollAngle(){return this._rollAngle}set rollAngle(e){this._rollAngle=e,this._dirty=!0}get fov(){return this._fov}set fov(e){this._fov=e,this._dirty=!0}get aspect(){return this._aspect}set aspect(e){this._aspect=e,this._dirty=!0}toState(){return{position:T.clone(this._position),angles:T.clone(this._angles),fov:this._fov,aspect:this._aspect,near:this._near,far:this._far}}setPosition(e,r,n){let i=T.fromValues(e,r,n);T.equals(this._position,i)||(T.copy(this._position,i),this._dirty=!0,this.triggerMoveEvent())}setRotation(e,r,n){let i=T.fromValues(e,r,n);T.equals(this._angles,i)||(T.copy(this._angles,i),this._dirty=!0,this.triggerMoveEvent())}setFov(e){this.fov=e}setAspectRatio(e){this.aspect=e}lookAt(e){let r=T.create();if(T.subtract(r,e,this._position),T.length(r)<.001)return;let i=Math.atan2(r[1],r[0])*pu,a=Math.hypot(r[0],r[1]),o=-Math.atan2(r[2],a)*pu;this.setRotation(o,i,0)}triggerMoveEvent(){this.onCameraMove&&this.onCameraMove({position:T.clone(this._position),angles:T.clone(this._angles)})}get viewMatrix(){return this.updateMatrices(),this._viewMatrix}get projectionMatrix(){return this.updateMatrices(),this._projectionMatrix}get viewProjectionMatrix(){return this.updateMatrices(),this._viewProjectionMatrix}getViewmodelProjectionMatrix(e){let r=F.create();return F.perspective(r,e*Ae,this._aspect,this._near,this._far),r}screenToWorldRay(e,r){let n=e*2-1,i=1-r*2,a=T.fromValues(n,i,-1),o=T.fromValues(n,i,1),s=F.create();F.invert(s,this.viewProjectionMatrix);let c=T.create(),l=T.create();T.transformMat4(c,a,s),T.transformMat4(l,o,s);let u=T.create();return T.subtract(u,l,c),T.normalize(u,u),{origin:T.clone(this._position),direction:u}}updateMatrices(){if(!this._dirty)return;F.perspective(this._projectionMatrix,this._fov*Ae,this._aspect,this._near,this._far);let e=F.fromValues(0,0,-1,0,-1,0,0,0,0,1,0,0,0,0,0,1),r=this._angles[0]+this._bobAngles[0]+this._kickAngles[0],n=this._angles[1]+this._bobAngles[1]+this._kickAngles[1],i=this._angles[2]+this._bobAngles[2]+this._kickAngles[2]+this._rollAngle,a=r*Ae,o=n*Ae,s=i*Ae,c=F.create();F.identity(c),F.rotateZ(c,c,-o),F.rotateY(c,c,-a),F.rotateX(c,c,-s);let l=F.create();F.multiply(l,e,c);let u=T.add(T.create(),this._position,this._bobOffset),d=T.negate(T.create(),u),f=T.create();T.transformMat4(f,d,c);let h=T.fromValues(f[1]?-f[1]:0,f[2]||0,f[0]?-f[0]:0);F.copy(this._viewMatrix,l),this._viewMatrix[12]=h[0],this._viewMatrix[13]=h[1],this._viewMatrix[14]=h[2],F.multiply(this._viewProjectionMatrix,this._projectionMatrix,this._viewMatrix),this._dirty=!1}};var zv=[.2,.2,.2],Ov={x:0,y:0,z:1},Nv=[.8,.8,.8];function Vd(t,e,r){return t+(e-t)*r}function La(t,e,r){return{x:Vd(t.x,e.x,r),y:Vd(t.y,e.y,r),z:Vd(t.z,e.z,r)}}function Ea(t){return t<0?0:t>1?1:t}function Hd(t){let e=[],r=[];for(let n of t.triangles){let i=e.length,[a,o,s]=n.indices,c=t.texCoords[a],l=t.texCoords[o],u=t.texCoords[s];if(!c||!l||!u)throw new Error(`Missing texCoord for triangle in surface ${t.name}`);e.push({vertexIndex:a,texCoord:[c.s,1-c.t]},{vertexIndex:o,texCoord:[l.s,1-l.t]},{vertexIndex:s,texCoord:[u.s,1-u.t]}),r.push(i,i+1,i+2)}return{vertices:e,indices:new Uint16Array(r)}}function Gv(t,e,r){let n=r?.ambient??zv,i=r?.directional??{direction:Ov,color:Nv},a=Kr(t),o=Kr(i.direction),s=Ea(a.x*o.x+a.y*o.y+a.z*o.z),c=n[0]+i.color[0]*s,l=n[1]+i.color[1]*s,u=n[2]+i.color[2]*s;if(r?.dynamicLights){let d=r.modelMatrix?Qf(r.modelMatrix,e):e;for(let f of r.dynamicLights){let h=d.x-f.origin.x,m=d.y-f.origin.y,g=d.z-f.origin.z,p=h*h+m*m+g*g,y=f.radius*f.radius;if(p<y&&y>0){let v=1-Math.sqrt(p)/f.radius,b=Math.sqrt(p),x=b>0?Ea(-(h*a.x+m*a.y+g*a.z)/b):0,_=Ea(v*x);c+=f.color[0]*_,l+=f.color[1]*_,u+=f.color[2]*_}}}return[Ea(c),Ea(l),Ea(u)]}function Wd(t,e,r,n){let i=t.vertices[r.frame0],a=t.vertices[r.frame1];if(!i||!a)throw new Error("Requested MD3 frames are out of range");let o=new Float32Array(e.vertices.length*12);return e.vertices.forEach((s,c)=>{let l=i[s.vertexIndex],u=a[s.vertexIndex];if(!l||!u)throw new Error(`Vertex index ${s.vertexIndex} missing for frame`);let d=La(l.position,u.position,r.lerp),f=Kr(La(l.normal,u.normal,r.lerp)),h=Gv(f,d,n),m=c*12;o[m]=d.x,o[m+1]=d.y,o[m+2]=d.z,o[m+3]=f.x,o[m+4]=f.y,o[m+5]=f.z,o[m+6]=s.texCoord[0],o[m+7]=s.texCoord[1],o[m+8]=h[0],o[m+9]=h[1],o[m+10]=h[2],o[m+11]=1}),o}function Zm(t,e,r){let n=t.tags[0];if(!n)return null;let i=n.findIndex(g=>g.name===r);if(i===-1)return null;let a=t.tags[e.frame0]?.[i],o=t.tags[e.frame1]?.[i];if(!a||!o)throw new Error(`Tag ${r} is missing for one of the interpolated frames`);let s=La(a.origin,o.origin,e.lerp),c=Kr(La(a.axis[0],o.axis[0],e.lerp)),l=Kr(La(a.axis[1],o.axis[1],e.lerp)),u=Kr(La(a.axis[2],o.axis[2],e.lerp)),d=c,f=Kr({x:l.x-d.x*(d.x*l.x+d.y*l.y+d.z*l.z),y:l.y-d.y*(d.x*l.x+d.y*l.y+d.z*l.z),z:l.z-d.z*(d.x*l.x+d.y*l.y+d.z*l.z)}),h=Kr({x:d.y*f.z-d.z*f.y,y:d.z*f.x-d.x*f.z,z:d.x*f.y-d.y*f.x}),m=[d,f,h];return{origin:s,axis:m,matrix:Jf(s,m)}}var Xd=`#version 300 es
493
498
  precision highp float;
494
499
 
495
500
  layout(location = 0) in vec3 a_position;
@@ -564,7 +569,7 @@ void main() {
564
569
  }
565
570
 
566
571
  o_color = finalColor;
567
- }`,gs=class{constructor(e,r,n,i){this.gl=e,this.geometry=Hd(r),this.vertexBuffer=new Ce(e,e.STATIC_DRAW),this.indexBuffer=new st(e,e.STATIC_DRAW),this.vertexArray=new Be(e),this.indexCount=this.geometry.indices.length,this.vertexArray.configureAttributes([{index:0,size:3,type:e.FLOAT,stride:48,offset:0},{index:1,size:3,type:e.FLOAT,stride:48,offset:12},{index:2,size:2,type:e.FLOAT,stride:48,offset:24},{index:3,size:4,type:e.FLOAT,stride:48,offset:32}],this.vertexBuffer),this.vertexArray.bind(),this.indexBuffer.bind(),this.indexBuffer.upload(this.geometry.indices,e.STATIC_DRAW),this.update(r,n,i)}update(e,r,n){let i=Wd(e,this.geometry,r,n);this.vertexBuffer.upload(i,this.gl.STATIC_DRAW)}bind(){this.vertexArray.bind(),this.indexBuffer.bind()}dispose(){this.vertexBuffer.dispose(),this.indexBuffer.dispose(),this.vertexArray.dispose(),this.wireframeIndexBuffer?.dispose()}},La=class{constructor(e,r,n,i){this.surfaces=new Map;this.gl=e,this.model=r,this.blend=n,this.lighting=i,r.surfaces.forEach(a=>{this.surfaces.set(a.name,new gs(e,a,n,i))})}update(e,r){this.blend=e,this.lighting=r??this.lighting;for(let n of this.model.surfaces)this.surfaces.get(n.name)?.update(n,e,this.lighting)}dispose(){for(let e of this.surfaces.values())e.dispose();this.surfaces.clear()}},Pa=class{constructor(e){this.gl=e,this.program=ce.create(e,{vertex:Xd,fragment:$d},{a_position:0,a_normal:1,a_texCoord:2,a_color:3}),this.uniformMvp=this.program.getUniformLocation("u_modelViewProjection"),this.uniformTint=this.program.getUniformLocation("u_tint"),this.uniformDiffuse=this.program.getUniformLocation("u_diffuseMap"),this.uniformRenderMode=this.program.getUniformLocation("u_renderMode"),this.uniformSolidColor=this.program.getUniformLocation("u_solidColor"),this.uniformBrightness=this.program.getUniformLocation("u_brightness"),this.uniformGamma=this.program.getUniformLocation("u_gamma"),this.uniformFullbright=this.program.getUniformLocation("u_fullbright"),this.uniformGlobalAmbient=this.program.getUniformLocation("u_globalAmbient")}get shaderSize(){return this.program.sourceSize}bind(e,r=[1,1,1,1],n=0){this.program.use(),this.gl.uniformMatrix4fv(this.uniformMvp,!1,e),this.gl.uniform4fv(this.uniformTint,new Float32Array(r)),this.gl.uniform1i(this.uniformDiffuse,n),this.gl.uniform1i(this.uniformRenderMode,0),this.gl.uniform4f(this.uniformSolidColor,1,1,1,1)}drawSurface(e,r){let n=r?.diffuseSampler??0,i=r?.tint??[1,1,1,1],a=r?.renderMode,o=r?.brightness??1,s=r?.gamma??1,c=r?.fullbright??!1,l=r?.globalAmbient??0;this.gl.uniform4fv(this.uniformTint,new Float32Array(i)),this.gl.uniform1i(this.uniformDiffuse,n);let u=0,d=[1,1,1,1];if(a&&(a.mode==="solid"||a.mode==="wireframe"?u=1:a.mode==="solid-faceted"&&(u=2),a.color&&(d=[...a.color])),this.gl.uniform1i(this.uniformRenderMode,u),this.gl.uniform4f(this.uniformSolidColor,d[0],d[1],d[2],d[3]),this.gl.uniform1f(this.uniformBrightness,o),this.gl.uniform1f(this.uniformGamma,s),this.gl.uniform1i(this.uniformFullbright,c?1:0),this.gl.uniform1f(this.uniformGlobalAmbient,l),e.vertexArray.bind(),a&&a.mode==="wireframe"){if(!e.wireframeIndexBuffer){e.wireframeIndexBuffer=new st(this.gl,this.gl.STATIC_DRAW);let f=xa(e.geometry.indices);e.wireframeIndexBuffer.upload(f),e.wireframeIndexCount=f.length}e.wireframeIndexBuffer.bind(),this.gl.drawElements(this.gl.LINES,e.wireframeIndexCount,this.gl.UNSIGNED_SHORT,0)}else e.indexBuffer.bind(),this.gl.drawElements(this.gl.TRIANGLES,e.indexCount,this.gl.UNSIGNED_SHORT,0)}dispose(){this.program.dispose()}};var Vv=[1,1,1,1],Ra=class{constructor(e,r){this.maxParticles=e,this.rng=r,this.alive=new Uint8Array(e),this.positionX=new Float32Array(e),this.positionY=new Float32Array(e),this.positionZ=new Float32Array(e),this.velocityX=new Float32Array(e),this.velocityY=new Float32Array(e),this.velocityZ=new Float32Array(e),this.colorR=new Float32Array(e),this.colorG=new Float32Array(e),this.colorB=new Float32Array(e),this.colorA=new Float32Array(e),this.size=new Float32Array(e),this.lifetime=new Float32Array(e),this.remaining=new Float32Array(e),this.gravity=new Float32Array(e),this.damping=new Float32Array(e),this.bounce=new Float32Array(e),this.fade=new Uint8Array(e),this.blendMode=new Uint8Array(e),this.textureIndex=new Int16Array(e)}spawn(e){let r=this.findFreeSlot();if(r===-1)return null;let n=e.color??Vv,i=e.velocity??{x:0,y:0,z:0};return this.alive[r]=1,this.positionX[r]=e.position.x,this.positionY[r]=e.position.y,this.positionZ[r]=e.position.z,this.velocityX[r]=i.x,this.velocityY[r]=i.y,this.velocityZ[r]=i.z,this.colorR[r]=n[0],this.colorG[r]=n[1],this.colorB[r]=n[2],this.colorA[r]=n[3],this.size[r]=e.size??2.5,this.lifetime[r]=e.lifetime,this.remaining[r]=e.lifetime,this.gravity[r]=e.gravity??800,this.damping[r]=e.damping??0,this.bounce[r]=e.bounce??.25,this.fade[r]=e.fade?1:0,this.blendMode[r]=e.blendMode==="additive"?1:0,this.textureIndex[r]=e.textureIndex??0,r}update(e,r={}){let n=r.floorZ??-1/0;for(let i=0;i<this.maxParticles;i+=1){if(!this.alive[i])continue;if(this.remaining[i]-=e,this.remaining[i]<=0){this.alive[i]=0;continue}let a=Math.max(0,1-this.damping[i]*e);this.velocityX[i]*=a,this.velocityY[i]*=a,this.velocityZ[i]=this.velocityZ[i]*a-this.gravity[i]*e,this.positionX[i]+=this.velocityX[i]*e,this.positionY[i]+=this.velocityY[i]*e,this.positionZ[i]+=this.velocityZ[i]*e,this.positionZ[i]<n&&(this.positionZ[i]=n,this.velocityZ[i]=-this.velocityZ[i]*this.bounce[i],this.velocityX[i]*=.7,this.velocityY[i]*=.7)}}killAll(){this.alive.fill(0)}aliveCount(){let e=0;for(let r=0;r<this.maxParticles;r+=1)this.alive[r]&&(e+=1);return e}getState(e){return{alive:this.alive[e]===1,position:{x:this.positionX[e],y:this.positionY[e],z:this.positionZ[e]},velocity:{x:this.velocityX[e],y:this.velocityY[e],z:this.velocityZ[e]},remaining:this.remaining[e],color:[this.colorR[e],this.colorG[e],this.colorB[e],this.colorA[e]],size:this.size[e],blendMode:this.blendMode[e]===1?"additive":"alpha",textureIndex:this.textureIndex[e]}}buildMesh(e,r){let n=[],i=[],a=[],o=s=>{let c=i.length,l=0;for(let u=0;u<this.maxParticles;u+=1){if(!this.alive[u]||(s==="additive"?1:0)!==this.blendMode[u])continue;l+=1;let d=n.length/9,f=this.size[u]*.5,h=this.fade[u]?Math.max(this.remaining[u]/this.lifetime[u],0):1,m=this.blendMode[u]===1?1.2:1,g=this.colorR[u]*m,p=this.colorG[u]*m,y=this.colorB[u]*m,v=this.colorA[u]*h,b=this.positionX[u],x=this.positionY[u],_=this.positionZ[u],w=e.x*f,S=e.y*f,A=e.z*f,T=r.x*f,M=r.y*f,P=r.z*f,I=[{x:b-w-T,y:x-S-M,z:_-A-P},{x:b+w-T,y:x+S-M,z:_+A-P},{x:b-w+T,y:x-S+M,z:_-A+P},{x:b+w+T,y:x+S+M,z:_+A+P}],D=[[0,1],[1,1],[0,0],[1,0]];I.forEach((B,O)=>{n.push(B.x,B.y,B.z,D[O]?.[0]??0,D[O]?.[1]??0,g,p,y,v)}),i.push(d,d+1,d+2,d+2,d+1,d+3)}l>0&&a.push({blendMode:s,start:c,count:i.length-c})};return o("alpha"),o("additive"),{vertices:new Float32Array(n),indices:new Uint16Array(i),batches:a}}findFreeSlot(){for(let e=0;e<this.maxParticles;e+=1)if(!this.alive[e])return e;return-1}},Kd=`#version 300 es
572
+ }`,gs=class{constructor(e,r,n,i){this.gl=e,this.geometry=Hd(r),this.vertexBuffer=new Ce(e,e.STATIC_DRAW),this.indexBuffer=new st(e,e.STATIC_DRAW),this.vertexArray=new Be(e),this.indexCount=this.geometry.indices.length,this.vertexArray.configureAttributes([{index:0,size:3,type:e.FLOAT,stride:48,offset:0},{index:1,size:3,type:e.FLOAT,stride:48,offset:12},{index:2,size:2,type:e.FLOAT,stride:48,offset:24},{index:3,size:4,type:e.FLOAT,stride:48,offset:32}],this.vertexBuffer),this.vertexArray.bind(),this.indexBuffer.bind(),this.indexBuffer.upload(this.geometry.indices,e.STATIC_DRAW),this.update(r,n,i)}update(e,r,n){let i=Wd(e,this.geometry,r,n);this.vertexBuffer.upload(i,this.gl.STATIC_DRAW)}bind(){this.vertexArray.bind(),this.indexBuffer.bind()}dispose(){this.vertexBuffer.dispose(),this.indexBuffer.dispose(),this.vertexArray.dispose(),this.wireframeIndexBuffer?.dispose()}},Ta=class{constructor(e,r,n,i){this.surfaces=new Map;this.gl=e,this.model=r,this.blend=n,this.lighting=i,r.surfaces.forEach(a=>{this.surfaces.set(a.name,new gs(e,a,n,i))})}update(e,r){this.blend=e,this.lighting=r??this.lighting;for(let n of this.model.surfaces)this.surfaces.get(n.name)?.update(n,e,this.lighting)}dispose(){for(let e of this.surfaces.values())e.dispose();this.surfaces.clear()}},Pa=class{constructor(e){this.gl=e,this.program=ce.create(e,{vertex:Xd,fragment:$d},{a_position:0,a_normal:1,a_texCoord:2,a_color:3}),this.uniformMvp=this.program.getUniformLocation("u_modelViewProjection"),this.uniformTint=this.program.getUniformLocation("u_tint"),this.uniformDiffuse=this.program.getUniformLocation("u_diffuseMap"),this.uniformRenderMode=this.program.getUniformLocation("u_renderMode"),this.uniformSolidColor=this.program.getUniformLocation("u_solidColor"),this.uniformBrightness=this.program.getUniformLocation("u_brightness"),this.uniformGamma=this.program.getUniformLocation("u_gamma"),this.uniformFullbright=this.program.getUniformLocation("u_fullbright"),this.uniformGlobalAmbient=this.program.getUniformLocation("u_globalAmbient")}get shaderSize(){return this.program.sourceSize}bind(e,r=[1,1,1,1],n=0){this.program.use(),this.gl.uniformMatrix4fv(this.uniformMvp,!1,e),this.gl.uniform4fv(this.uniformTint,new Float32Array(r)),this.gl.uniform1i(this.uniformDiffuse,n),this.gl.uniform1i(this.uniformRenderMode,0),this.gl.uniform4f(this.uniformSolidColor,1,1,1,1)}drawSurface(e,r){let n=r?.diffuseSampler??0,i=r?.tint??[1,1,1,1],a=r?.renderMode,o=r?.brightness??1,s=r?.gamma??1,c=r?.fullbright??!1,l=r?.globalAmbient??0;this.gl.uniform4fv(this.uniformTint,new Float32Array(i)),this.gl.uniform1i(this.uniformDiffuse,n);let u=0,d=[1,1,1,1];if(a&&(a.mode==="solid"||a.mode==="wireframe"?u=1:a.mode==="solid-faceted"&&(u=2),a.color&&(d=[...a.color])),this.gl.uniform1i(this.uniformRenderMode,u),this.gl.uniform4f(this.uniformSolidColor,d[0],d[1],d[2],d[3]),this.gl.uniform1f(this.uniformBrightness,o),this.gl.uniform1f(this.uniformGamma,s),this.gl.uniform1i(this.uniformFullbright,c?1:0),this.gl.uniform1f(this.uniformGlobalAmbient,l),e.vertexArray.bind(),a&&a.mode==="wireframe"){if(!e.wireframeIndexBuffer){e.wireframeIndexBuffer=new st(this.gl,this.gl.STATIC_DRAW);let f=xa(e.geometry.indices);e.wireframeIndexBuffer.upload(f),e.wireframeIndexCount=f.length}e.wireframeIndexBuffer.bind(),this.gl.drawElements(this.gl.LINES,e.wireframeIndexCount,this.gl.UNSIGNED_SHORT,0)}else e.indexBuffer.bind(),this.gl.drawElements(this.gl.TRIANGLES,e.indexCount,this.gl.UNSIGNED_SHORT,0)}dispose(){this.program.dispose()}};var Vv=[1,1,1,1],Ra=class{constructor(e,r){this.maxParticles=e,this.rng=r,this.alive=new Uint8Array(e),this.positionX=new Float32Array(e),this.positionY=new Float32Array(e),this.positionZ=new Float32Array(e),this.velocityX=new Float32Array(e),this.velocityY=new Float32Array(e),this.velocityZ=new Float32Array(e),this.colorR=new Float32Array(e),this.colorG=new Float32Array(e),this.colorB=new Float32Array(e),this.colorA=new Float32Array(e),this.size=new Float32Array(e),this.lifetime=new Float32Array(e),this.remaining=new Float32Array(e),this.gravity=new Float32Array(e),this.damping=new Float32Array(e),this.bounce=new Float32Array(e),this.fade=new Uint8Array(e),this.blendMode=new Uint8Array(e),this.textureIndex=new Int16Array(e)}spawn(e){let r=this.findFreeSlot();if(r===-1)return null;let n=e.color??Vv,i=e.velocity??{x:0,y:0,z:0};return this.alive[r]=1,this.positionX[r]=e.position.x,this.positionY[r]=e.position.y,this.positionZ[r]=e.position.z,this.velocityX[r]=i.x,this.velocityY[r]=i.y,this.velocityZ[r]=i.z,this.colorR[r]=n[0],this.colorG[r]=n[1],this.colorB[r]=n[2],this.colorA[r]=n[3],this.size[r]=e.size??2.5,this.lifetime[r]=e.lifetime,this.remaining[r]=e.lifetime,this.gravity[r]=e.gravity??800,this.damping[r]=e.damping??0,this.bounce[r]=e.bounce??.25,this.fade[r]=e.fade?1:0,this.blendMode[r]=e.blendMode==="additive"?1:0,this.textureIndex[r]=e.textureIndex??0,r}update(e,r={}){let n=r.floorZ??-1/0;for(let i=0;i<this.maxParticles;i+=1){if(!this.alive[i])continue;if(this.remaining[i]-=e,this.remaining[i]<=0){this.alive[i]=0;continue}let a=Math.max(0,1-this.damping[i]*e);this.velocityX[i]*=a,this.velocityY[i]*=a,this.velocityZ[i]=this.velocityZ[i]*a-this.gravity[i]*e,this.positionX[i]+=this.velocityX[i]*e,this.positionY[i]+=this.velocityY[i]*e,this.positionZ[i]+=this.velocityZ[i]*e,this.positionZ[i]<n&&(this.positionZ[i]=n,this.velocityZ[i]=-this.velocityZ[i]*this.bounce[i],this.velocityX[i]*=.7,this.velocityY[i]*=.7)}}killAll(){this.alive.fill(0)}aliveCount(){let e=0;for(let r=0;r<this.maxParticles;r+=1)this.alive[r]&&(e+=1);return e}getState(e){return{alive:this.alive[e]===1,position:{x:this.positionX[e],y:this.positionY[e],z:this.positionZ[e]},velocity:{x:this.velocityX[e],y:this.velocityY[e],z:this.velocityZ[e]},remaining:this.remaining[e],color:[this.colorR[e],this.colorG[e],this.colorB[e],this.colorA[e]],size:this.size[e],blendMode:this.blendMode[e]===1?"additive":"alpha",textureIndex:this.textureIndex[e]}}buildMesh(e,r){let n=[],i=[],a=[],o=s=>{let c=i.length,l=0;for(let u=0;u<this.maxParticles;u+=1){if(!this.alive[u]||(s==="additive"?1:0)!==this.blendMode[u])continue;l+=1;let d=n.length/9,f=this.size[u]*.5,h=this.fade[u]?Math.max(this.remaining[u]/this.lifetime[u],0):1,m=this.blendMode[u]===1?1.2:1,g=this.colorR[u]*m,p=this.colorG[u]*m,y=this.colorB[u]*m,v=this.colorA[u]*h,b=this.positionX[u],x=this.positionY[u],_=this.positionZ[u],w=e.x*f,S=e.y*f,A=e.z*f,L=r.x*f,M=r.y*f,P=r.z*f,I=[{x:b-w-L,y:x-S-M,z:_-A-P},{x:b+w-L,y:x+S-M,z:_+A-P},{x:b-w+L,y:x-S+M,z:_-A+P},{x:b+w+L,y:x+S+M,z:_+A+P}],D=[[0,1],[1,1],[0,0],[1,0]];I.forEach((B,O)=>{n.push(B.x,B.y,B.z,D[O]?.[0]??0,D[O]?.[1]??0,g,p,y,v)}),i.push(d,d+1,d+2,d+2,d+1,d+3)}l>0&&a.push({blendMode:s,start:c,count:i.length-c})};return o("alpha"),o("additive"),{vertices:new Float32Array(n),indices:new Uint16Array(i),batches:a}}findFreeSlot(){for(let e=0;e<this.maxParticles;e+=1)if(!this.alive[e])return e;return-1}},Kd=`#version 300 es
568
573
  precision highp float;
569
574
 
570
575
  layout(location = 0) in vec3 a_position;
@@ -694,7 +699,7 @@ void main() {
694
699
  vec4 color = texture(u_texture, v_texCoord);
695
700
  o_color = vec4(color.rgb * u_intensity, 1.0);
696
701
  }
697
- `,bc=class{constructor(e){this.width=0;this.height=0;this.gl=e,this.extractProgram=ce.create(e,{vertex:qd,fragment:Xv},{a_position:0}),this.blurProgram=ce.create(e,{vertex:qd,fragment:$v},{a_position:0}),this.compositeProgram=ce.create(e,{vertex:qd,fragment:Kv},{a_position:0}),this.framebuffer1=new Ai(e),this.framebuffer2=new Ai(e),this.texture1=new lt(e),this.texture2=new lt(e),this.texture1.setParameters({minFilter:e.LINEAR,magFilter:e.LINEAR,wrapS:e.CLAMP_TO_EDGE,wrapT:e.CLAMP_TO_EDGE}),this.texture2.setParameters({minFilter:e.LINEAR,magFilter:e.LINEAR,wrapS:e.CLAMP_TO_EDGE,wrapT:e.CLAMP_TO_EDGE}),this.vao=e.createVertexArray(),e.bindVertexArray(this.vao);let r=new Float32Array([-1,-1,1,-1,-1,1,1,1]),n=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,n),e.bufferData(e.ARRAY_BUFFER,r,e.STATIC_DRAW),e.enableVertexAttribArray(0),e.vertexAttribPointer(0,2,e.FLOAT,!1,0,0),e.bindVertexArray(null)}resize(e,r){if(this.width!==e||this.height!==r){this.width=e,this.height=r;let n=Math.floor(e/2)||1,i=Math.floor(r/2)||1;this.texture1.upload(n,i,null),this.framebuffer1.attachTexture2D(this.gl.COLOR_ATTACHMENT0,this.texture1),this.texture2.upload(n,i,null),this.framebuffer2.attachTexture2D(this.gl.COLOR_ATTACHMENT0,this.texture2)}}render(e,r=.5){let n=this.gl,i=Math.floor(this.width/2)||1,a=Math.floor(this.height/2)||1;n.bindVertexArray(this.vao),this.framebuffer1.bind(),n.viewport(0,0,i,a),n.clear(n.COLOR_BUFFER_BIT),this.extractProgram.use(),n.activeTexture(n.TEXTURE0),n.bindTexture(n.TEXTURE_2D,e.texture),n.uniform1i(this.extractProgram.getUniformLocation("u_texture"),0),n.uniform1f(this.extractProgram.getUniformLocation("u_threshold"),.7),n.drawArrays(n.TRIANGLE_STRIP,0,4),this.blurProgram.use(),n.uniform1fv(this.blurProgram.getUniformLocation("u_weight"),[.227027,.1945946,.1216216,.054054,.016216]);let o=this.blurProgram.getUniformLocation("u_horizontal"),s=this.blurProgram.getUniformLocation("u_texture"),c=4,l=!0,u=!0;for(let d=0;d<c;d++)this.framebuffer2.bind(),l?(this.framebuffer2.bind(),n.bindTexture(n.TEXTURE_2D,this.texture1.texture)):(this.framebuffer1.bind(),n.bindTexture(n.TEXTURE_2D,this.texture2.texture)),n.uniform1i(o,l?1:0),n.uniform1i(s,0),n.drawArrays(n.TRIANGLE_STRIP,0,4),l=!l;n.bindFramebuffer(n.FRAMEBUFFER,null),n.viewport(0,0,this.width,this.height),n.enable(n.BLEND),n.blendFunc(n.ONE,n.ONE),n.disable(n.DEPTH_TEST),this.compositeProgram.use(),n.activeTexture(n.TEXTURE0),n.bindTexture(n.TEXTURE_2D,this.texture1.texture),n.uniform1i(this.compositeProgram.getUniformLocation("u_texture"),0),n.uniform1f(this.compositeProgram.getUniformLocation("u_intensity"),r),n.drawArrays(n.TRIANGLE_STRIP,0,4),n.blendFunc(n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA),n.enable(n.DEPTH_TEST),n.bindVertexArray(null)}dispose(){this.extractProgram.dispose(),this.blurProgram.dispose(),this.compositeProgram.dispose(),this.framebuffer1.dispose(),this.framebuffer2.dispose(),this.texture1.dispose(),this.texture2.dispose(),this.gl.deleteVertexArray(this.vao)}};var Yv={gatherVisibleFaces:cn,extractFrustumPlanes:sr,computeSkyScroll:Li,removeViewTranslation:Sa};function qv(t,e,r,n,i){if(!n)return;let a=i.removeViewTranslation(e.viewMatrix),o=F.create();F.multiply(o,e.projectionMatrix,a);let s=i.computeSkyScroll(r,n.scrollSpeeds??[.01,.02]);t.bind({viewProjection:o,scroll:s,textureUnit:n.textureUnit??0}),t.draw(),t.gl.depthMask(!0)}function Zv(t){return[...t].sort((e,r)=>r.sortKey-e.sortKey)}function jv(t){return[...t].sort((e,r)=>e.sortKey-r.sortKey)}function Qv(t,e,r){let n=e?.materials?.getMaterial(t.texture),i;if(n){let s=n.texture;s&&(i=s)}i||(i=e?.textures?.get(t.texture));let a=t.lightmap?.atlasIndex,o=a!==void 0?e?.lightmaps?.[a]?.texture:void 0;return{diffuse:i,lightmap:o,refraction:r}}function cp(t,e,r,n){let i=n.diffuse;i&&r.diffuse!==i&&(i.bind(0),r.diffuse=i);let a=n.lightmap;a&&r.lightmap!==a&&(a.bind(1),r.lightmap=a),a||(r.lightmap=void 0);let o=n.refraction,s;return o&&t.surfaceFlags&Yr?(r.refraction!==o&&(o.bind(2),r.refraction=o),s=2):r.refraction=void 0,{diffuse:0,lightmap:a?1:void 0,refraction:s}}function Jv(t,e,r,n){if(!r)return!1;let i=r.fov?e.getViewmodelProjectionMatrix(r.fov):e.projectionMatrix,a=n(e.viewMatrix),o=F.create();return F.multiply(o,i,a),r.depthRange&&t.depthRange(r.depthRange[0],r.depthRange[1]),r.draw(new Float32Array(o)),r.depthRange&&t.depthRange(0,1),!0}function e_(t,e){if(!t)return 1;let r=Math.floor(e*10)%t.length;return(t.charCodeAt(r)-97)/12}var up=(t,e,r,n=Yv)=>{let i=new yc(t),a=new bc(t),o=0,s,c=0,l=0,u=(f,h)=>((!s||c!==f||l!==h)&&(s=new lt(t),s.upload(f,h,null),s.setParameters({minFilter:t.LINEAR,magFilter:t.LINEAR,wrapS:t.CLAMP_TO_EDGE,wrapT:t.CLAMP_TO_EDGE}),c=f,l=h),s);return{renderFrame:f=>{let h=performance.now(),m=o>0?1e3/(h-o):0;o=h;let g={batches:0,facesDrawn:0,drawCalls:0,skyDrawn:!1,viewModelDrawn:!1,fps:Math.round(m),vertexCount:0},{camera:p,world:y,sky:v,clearColor:b=[0,0,0,1],timeSeconds:x=0,viewModel:_,dlights:w,renderMode:S,disableLightmaps:A,lightmapOnly:T,brightness:M,gamma:P,fullbright:I,ambient:D,lightStyleOverrides:B,waterTint:O,underwaterWarp:Q,bloom:Ge,bloomIntensity:me,portalState:Me}=f,ge=new Float32Array(p.viewProjectionMatrix);if(t.clearColor(b[0],b[1],b[2],b[3]),t.clear(t.COLOR_BUFFER_BIT|t.DEPTH_BUFFER_BIT),qv(r,p,x,v,n),g.skyDrawn=!!v,y){y.materials?.update(x);let ue=n.extractFrustumPlanes(Array.from(ge)),ye={x:p.position[0]??0,y:p.position[1]??0,z:p.position[2]??0},Ve=n.gatherVisibleFaces(y.map,ye,ue,Me),ct=[],qt=[];for(let se of Ve){let ke=y.surfaces[se.faceIndex];if(!ke)continue;(ke.surfaceFlags&(xn|vn|Yr))!==0?qt.push(se):ct.push(se)}let ut=Zv(ct),He=y.lightStyles||[];if(B&&B.size>0){let se=[...y.lightStyles||[]];for(let[ke,De]of B){for(;se.length<=ke;)se.push(1);se[ke]=e_(De,x)}He=se}let $r=(se,ke)=>{let De,fr,Zt={},mn=ke?s:void 0;for(let{faceIndex:Hs}of se){let vt=y.surfaces[Hs];if(!vt||(vt.surfaceFlags&bn)!==0)continue;let Ws=y.map.faces[Hs]?.styles,Ya=y.materials?.getMaterial(vt.texture),Jn=Qv(vt,y,mn),qa=S;S&&!S.applyToAll&&Jn.diffuse?qa=void 0:S&&!S.applyToAll&&!Jn.diffuse&&(qa=S);let Za=Jn.lightmap;A&&(Za=void 0);let Ui={diffuse:Jn.diffuse,lightmap:Za,surfaceFlags:vt.surfaceFlags,styleKey:Ws?.join(",")??""};if(De&&De.diffuse===Ui.diffuse&&De.lightmap===Ui.lightmap&&De.surfaceFlags===Ui.surfaceFlags&&De.styleKey===Ui.styleKey){let Xs={...Jn,lightmap:Za};cp(vt,y,Zt,Xs),fr&&ds(t,fr)}else{g.batches+=1,Zt.diffuse=void 0,Zt.lightmap=void 0,Zt.refraction=void 0;let Xs={...Jn,lightmap:Za},$s=cp(vt,y,Zt,Xs),Nf=Ya?Ya.scrollOffset:void 0,Gf=Ya?Ya.warp:void 0;fr=e.bind({modelViewProjection:ge,styleIndices:Ws,styleValues:He,surfaceFlags:vt.surfaceFlags,timeSeconds:x,diffuseSampler:$s.diffuse??0,lightmapSampler:$s.lightmap,refractionSampler:$s.refraction,texScroll:Nf,warp:Gf,dlights:w,renderMode:qa,lightmapOnly:T,brightness:M,gamma:P,fullbright:I,ambient:D}),ds(t,fr),De=Ui}e.draw(vt,qa),g.facesDrawn+=1,g.drawCalls+=1,g.vertexCount+=vt.vertexCount}};if($r(ut,!1),qt.length>0){let se=t.canvas.width,ke=t.canvas.height;u(se,ke).bind(2),t.copyTexImage2D(t.TEXTURE_2D,0,t.RGBA,0,0,se,ke,0)}let k=jv(qt);$r(k,!0)}if(Jv(t,p,_,n.removeViewTranslation)&&(g.viewModelDrawn=!0),Q){let ue=t.canvas.width,ye=t.canvas.height,Ve=u(ue,ye);Ve.bind(0),t.copyTexImage2D(t.TEXTURE_2D,0,t.RGBA,0,0,ue,ye,0),t.disable(t.DEPTH_TEST),t.depthMask(!1),i.render(Ve.texture,x),t.enable(t.DEPTH_TEST),t.depthMask(!0)}if(Ge){let ue=t.canvas.width,ye=t.canvas.height;a.resize(ue,ye);let Ve=u(ue,ye);Ve.bind(0),t.copyTexImage2D(t.TEXTURE_2D,0,t.RGBA,0,0,ue,ye,0),a.render(Ve,me??.5)}return g}}};var t_=`#version 300 es
702
+ `,bc=class{constructor(e){this.width=0;this.height=0;this.gl=e,this.extractProgram=ce.create(e,{vertex:qd,fragment:Xv},{a_position:0}),this.blurProgram=ce.create(e,{vertex:qd,fragment:$v},{a_position:0}),this.compositeProgram=ce.create(e,{vertex:qd,fragment:Kv},{a_position:0}),this.framebuffer1=new Ai(e),this.framebuffer2=new Ai(e),this.texture1=new lt(e),this.texture2=new lt(e),this.texture1.setParameters({minFilter:e.LINEAR,magFilter:e.LINEAR,wrapS:e.CLAMP_TO_EDGE,wrapT:e.CLAMP_TO_EDGE}),this.texture2.setParameters({minFilter:e.LINEAR,magFilter:e.LINEAR,wrapS:e.CLAMP_TO_EDGE,wrapT:e.CLAMP_TO_EDGE}),this.vao=e.createVertexArray(),e.bindVertexArray(this.vao);let r=new Float32Array([-1,-1,1,-1,-1,1,1,1]),n=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,n),e.bufferData(e.ARRAY_BUFFER,r,e.STATIC_DRAW),e.enableVertexAttribArray(0),e.vertexAttribPointer(0,2,e.FLOAT,!1,0,0),e.bindVertexArray(null)}resize(e,r){if(this.width!==e||this.height!==r){this.width=e,this.height=r;let n=Math.floor(e/2)||1,i=Math.floor(r/2)||1;this.texture1.upload(n,i,null),this.framebuffer1.attachTexture2D(this.gl.COLOR_ATTACHMENT0,this.texture1),this.texture2.upload(n,i,null),this.framebuffer2.attachTexture2D(this.gl.COLOR_ATTACHMENT0,this.texture2)}}render(e,r=.5){let n=this.gl,i=Math.floor(this.width/2)||1,a=Math.floor(this.height/2)||1;n.bindVertexArray(this.vao),this.framebuffer1.bind(),n.viewport(0,0,i,a),n.clear(n.COLOR_BUFFER_BIT),this.extractProgram.use(),n.activeTexture(n.TEXTURE0),n.bindTexture(n.TEXTURE_2D,e.texture),n.uniform1i(this.extractProgram.getUniformLocation("u_texture"),0),n.uniform1f(this.extractProgram.getUniformLocation("u_threshold"),.7),n.drawArrays(n.TRIANGLE_STRIP,0,4),this.blurProgram.use(),n.uniform1fv(this.blurProgram.getUniformLocation("u_weight"),[.227027,.1945946,.1216216,.054054,.016216]);let o=this.blurProgram.getUniformLocation("u_horizontal"),s=this.blurProgram.getUniformLocation("u_texture"),c=4,l=!0,u=!0;for(let d=0;d<c;d++)this.framebuffer2.bind(),l?(this.framebuffer2.bind(),n.bindTexture(n.TEXTURE_2D,this.texture1.texture)):(this.framebuffer1.bind(),n.bindTexture(n.TEXTURE_2D,this.texture2.texture)),n.uniform1i(o,l?1:0),n.uniform1i(s,0),n.drawArrays(n.TRIANGLE_STRIP,0,4),l=!l;n.bindFramebuffer(n.FRAMEBUFFER,null),n.viewport(0,0,this.width,this.height),n.enable(n.BLEND),n.blendFunc(n.ONE,n.ONE),n.disable(n.DEPTH_TEST),this.compositeProgram.use(),n.activeTexture(n.TEXTURE0),n.bindTexture(n.TEXTURE_2D,this.texture1.texture),n.uniform1i(this.compositeProgram.getUniformLocation("u_texture"),0),n.uniform1f(this.compositeProgram.getUniformLocation("u_intensity"),r),n.drawArrays(n.TRIANGLE_STRIP,0,4),n.blendFunc(n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA),n.enable(n.DEPTH_TEST),n.bindVertexArray(null)}dispose(){this.extractProgram.dispose(),this.blurProgram.dispose(),this.compositeProgram.dispose(),this.framebuffer1.dispose(),this.framebuffer2.dispose(),this.texture1.dispose(),this.texture2.dispose(),this.gl.deleteVertexArray(this.vao)}};var Yv={gatherVisibleFaces:cn,extractFrustumPlanes:sr,computeSkyScroll:Ti,removeViewTranslation:Sa};function qv(t,e,r,n,i){if(!n)return;let a=i.removeViewTranslation(e.viewMatrix),o=F.create();F.multiply(o,e.projectionMatrix,a);let s=i.computeSkyScroll(r,n.scrollSpeeds??[.01,.02]);t.bind({viewProjection:o,scroll:s,textureUnit:n.textureUnit??0}),t.draw(),t.gl.depthMask(!0)}function Zv(t){return[...t].sort((e,r)=>r.sortKey-e.sortKey)}function jv(t){return[...t].sort((e,r)=>e.sortKey-r.sortKey)}function Qv(t,e,r){let n=e?.materials?.getMaterial(t.texture),i;if(n){let s=n.texture;s&&(i=s)}i||(i=e?.textures?.get(t.texture));let a=t.lightmap?.atlasIndex,o=a!==void 0?e?.lightmaps?.[a]?.texture:void 0;return{diffuse:i,lightmap:o,refraction:r}}function cp(t,e,r,n){let i=n.diffuse;i&&r.diffuse!==i&&(i.bind(0),r.diffuse=i);let a=n.lightmap;a&&r.lightmap!==a&&(a.bind(1),r.lightmap=a),a||(r.lightmap=void 0);let o=n.refraction,s;return o&&t.surfaceFlags&Yr?(r.refraction!==o&&(o.bind(2),r.refraction=o),s=2):r.refraction=void 0,{diffuse:0,lightmap:a?1:void 0,refraction:s}}function Jv(t,e,r,n){if(!r)return!1;let i=r.fov?e.getViewmodelProjectionMatrix(r.fov):e.projectionMatrix,a=n(e.viewMatrix),o=F.create();return F.multiply(o,i,a),r.depthRange&&t.depthRange(r.depthRange[0],r.depthRange[1]),r.draw(new Float32Array(o)),r.depthRange&&t.depthRange(0,1),!0}function e_(t,e){if(!t)return 1;let r=Math.floor(e*10)%t.length;return(t.charCodeAt(r)-97)/12}var up=(t,e,r,n=Yv)=>{let i=new yc(t),a=new bc(t),o=0,s,c=0,l=0,u=(f,h)=>((!s||c!==f||l!==h)&&(s=new lt(t),s.upload(f,h,null),s.setParameters({minFilter:t.LINEAR,magFilter:t.LINEAR,wrapS:t.CLAMP_TO_EDGE,wrapT:t.CLAMP_TO_EDGE}),c=f,l=h),s);return{renderFrame:f=>{let h=performance.now(),m=o>0?1e3/(h-o):0;o=h;let g={batches:0,facesDrawn:0,drawCalls:0,skyDrawn:!1,viewModelDrawn:!1,fps:Math.round(m),vertexCount:0},{camera:p,world:y,sky:v,clearColor:b=[0,0,0,1],timeSeconds:x=0,viewModel:_,dlights:w,renderMode:S,disableLightmaps:A,lightmapOnly:L,brightness:M,gamma:P,fullbright:I,ambient:D,lightStyleOverrides:B,waterTint:O,underwaterWarp:Q,bloom:Ge,bloomIntensity:me,portalState:Me}=f,ge=new Float32Array(p.viewProjectionMatrix);if(t.clearColor(b[0],b[1],b[2],b[3]),t.clear(t.COLOR_BUFFER_BIT|t.DEPTH_BUFFER_BIT),qv(r,p,x,v,n),g.skyDrawn=!!v,y){y.materials?.update(x);let ue=n.extractFrustumPlanes(Array.from(ge)),ye={x:p.position[0]??0,y:p.position[1]??0,z:p.position[2]??0},Ve=n.gatherVisibleFaces(y.map,ye,ue,Me),ct=[],qt=[];for(let se of Ve){let ke=y.surfaces[se.faceIndex];if(!ke)continue;(ke.surfaceFlags&(xn|vn|Yr))!==0?qt.push(se):ct.push(se)}let ut=Zv(ct),He=y.lightStyles||[];if(B&&B.size>0){let se=[...y.lightStyles||[]];for(let[ke,De]of B){for(;se.length<=ke;)se.push(1);se[ke]=e_(De,x)}He=se}let $r=(se,ke)=>{let De,fr,Zt={},mn=ke?s:void 0;for(let{faceIndex:Hs}of se){let vt=y.surfaces[Hs];if(!vt||(vt.surfaceFlags&bn)!==0)continue;let Ws=y.map.faces[Hs]?.styles,Ya=y.materials?.getMaterial(vt.texture),Jn=Qv(vt,y,mn),qa=S;S&&!S.applyToAll&&Jn.diffuse?qa=void 0:S&&!S.applyToAll&&!Jn.diffuse&&(qa=S);let Za=Jn.lightmap;A&&(Za=void 0);let Ui={diffuse:Jn.diffuse,lightmap:Za,surfaceFlags:vt.surfaceFlags,styleKey:Ws?.join(",")??""};if(De&&De.diffuse===Ui.diffuse&&De.lightmap===Ui.lightmap&&De.surfaceFlags===Ui.surfaceFlags&&De.styleKey===Ui.styleKey){let Xs={...Jn,lightmap:Za};cp(vt,y,Zt,Xs),fr&&ds(t,fr)}else{g.batches+=1,Zt.diffuse=void 0,Zt.lightmap=void 0,Zt.refraction=void 0;let Xs={...Jn,lightmap:Za},$s=cp(vt,y,Zt,Xs),Nf=Ya?Ya.scrollOffset:void 0,Gf=Ya?Ya.warp:void 0;fr=e.bind({modelViewProjection:ge,styleIndices:Ws,styleValues:He,surfaceFlags:vt.surfaceFlags,timeSeconds:x,diffuseSampler:$s.diffuse??0,lightmapSampler:$s.lightmap,refractionSampler:$s.refraction,texScroll:Nf,warp:Gf,dlights:w,renderMode:qa,lightmapOnly:L,brightness:M,gamma:P,fullbright:I,ambient:D}),ds(t,fr),De=Ui}e.draw(vt,qa),g.facesDrawn+=1,g.drawCalls+=1,g.vertexCount+=vt.vertexCount}};if($r(ut,!1),qt.length>0){let se=t.canvas.width,ke=t.canvas.height;u(se,ke).bind(2),t.copyTexImage2D(t.TEXTURE_2D,0,t.RGBA,0,0,se,ke,0)}let k=jv(qt);$r(k,!0)}if(Jv(t,p,_,n.removeViewTranslation)&&(g.viewModelDrawn=!0),Q){let ue=t.canvas.width,ye=t.canvas.height,Ve=u(ue,ye);Ve.bind(0),t.copyTexImage2D(t.TEXTURE_2D,0,t.RGBA,0,0,ue,ye,0),t.disable(t.DEPTH_TEST),t.depthMask(!1),i.render(Ve.texture,x),t.enable(t.DEPTH_TEST),t.depthMask(!0)}if(Ge){let ue=t.canvas.width,ye=t.canvas.height;a.resize(ue,ye);let Ve=u(ue,ye);Ve.bind(0),t.copyTexImage2D(t.TEXTURE_2D,0,t.RGBA,0,0,ue,ye,0),a.render(Ve,me??.5)}return g}}};var t_=`#version 300 es
698
703
  precision highp float;
699
704
 
700
705
  layout(location = 0) in vec2 a_position;
@@ -740,7 +745,7 @@ out vec4 o_color;
740
745
 
741
746
  void main() {
742
747
  o_color = v_color;
743
- }`,xc=class{constructor(e){this.vertices=[];this.gl=e,this.program=ce.create(e,{vertex:n_,fragment:i_},{a_position:0,a_color:1}),this.uniformViewProjection=this.program.getUniformLocation("u_viewProjection"),this.vao=new Be(e),this.vbo=new Ce(e,e.STREAM_DRAW),this.vao.configureAttributes([{index:0,size:3,type:e.FLOAT,stride:28,offset:0},{index:1,size:4,type:e.FLOAT,stride:28,offset:12}],this.vbo)}get shaderSize(){return this.program.sourceSize}addLine(e,r,n={r:1,g:0,b:0,a:1}){this.vertices.push(e.x,e.y,e.z,n.r,n.g,n.b,n.a,r.x,r.y,r.z,n.r,n.g,n.b,n.a)}addBBox(e,r,n={r:0,g:1,b:0,a:1}){let i={x:e.x,y:e.y,z:e.z},a={x:r.x,y:e.y,z:e.z},o={x:r.x,y:r.y,z:e.z},s={x:e.x,y:r.y,z:e.z},c={x:e.x,y:e.y,z:r.z},l={x:r.x,y:e.y,z:r.z},u={x:r.x,y:r.y,z:r.z},d={x:e.x,y:r.y,z:r.z};this.addLine(i,a,n),this.addLine(a,o,n),this.addLine(o,s,n),this.addLine(s,i,n),this.addLine(c,l,n),this.addLine(l,u,n),this.addLine(u,d,n),this.addLine(d,c,n),this.addLine(i,c,n),this.addLine(a,l,n),this.addLine(o,u,n),this.addLine(s,d,n)}clear(){this.vertices=[]}render(e){this.vertices.length!==0&&(this.program.use(),this.gl.uniformMatrix4fv(this.uniformViewProjection,!1,e),this.vbo.upload(new Float32Array(this.vertices),this.gl.STREAM_DRAW),this.vao.bind(),this.gl.drawArrays(this.gl.LINES,0,this.vertices.length/7))}};function a_(t,e){let r=t.models[0].headNode;for(;r>=0;){let i=t.nodes[r],a=t.planes[i.planeIndex];a.normal[0]*e.x+a.normal[1]*e.y+a.normal[2]*e.z-a.dist>=0?r=i.children[0]:r=i.children[1]}let n=-(r+1);return{leaf:t.leafs[n],index:n}}function o_(t){if(t.entities.worldspawn?.properties.light){let e=parseInt(t.entities.worldspawn.properties.light,10);if(!isNaN(e))return e/255}if(t.entities.worldspawn?.properties._minlight){let e=parseInt(t.entities.worldspawn.properties._minlight,10);if(!isNaN(e))return e/255}return .2}function s_(t,e,r,n){let i=t.faces[e];if(!i||i.lightOffset<0||!t.lightMapInfo[e])return 0;let o=t.texInfo[i.texInfo],s=1/0,c=-1/0,l=1/0,u=-1/0,d=i.firstEdge;for(let A=0;A<i.numEdges;A++){let T=t.surfEdges[d+A],M=T>=0?t.edges[T].vertices[0]:t.edges[Math.abs(T)].vertices[1],P=t.vertices[M],I=P[0]*o.s[0]+P[1]*o.s[1]+P[2]*o.s[2]+o.sOffset,D=P[0]*o.t[0]+P[1]*o.t[1]+P[2]*o.t[2]+o.tOffset;I<s&&(s=I),I>c&&(c=I),D<l&&(l=D),D>u&&(u=D)}let f=Math.floor(s/16),h=Math.floor(l/16),m=Math.ceil(c/16)-f+1,g=Math.ceil(u/16)-h+1,p=r/16-f,y=n/16-h,v=Math.max(0,Math.min(m-1,Math.floor(p))),b=Math.max(0,Math.min(g-1,Math.floor(y))),x=i.lightOffset+(b*m+v)*3;if(x+2>=t.lightMaps.length)return 0;let _=t.lightMaps[x],w=t.lightMaps[x+1],S=t.lightMaps[x+2];return Math.max(_,w,S)/255}function dp(t,e){if(!t)return 1;let r=o_(t),n={x:e.x,y:e.y,z:e.z-8192},i=1,a=-1,o=0,s=0,{leaf:c,index:l}=a_(t,e);if(c.contents&1)return r;let u=t.leafLists.leafFaces[l];if(u)for(let d of u){let f=t.faces[d],h=t.planes[f.planeIndex],m=f.side,g=m?-h.normal[0]:h.normal[0],p=m?-h.normal[1]:h.normal[1],y=m?-h.normal[2]:h.normal[2],v=m?-h.dist:h.dist;if(y>.7){let b=g*e.x+p*e.y+y*e.z-v;if(b>=0&&b<64){let x=t.texInfo[f.texInfo],_=e.x*x.s[0]+e.y*x.s[1]+e.z*x.s[2]+x.sOffset,w=e.x*x.t[0]+e.y*x.t[1]+e.z*x.t[2]+x.tOffset,S=s_(t,d,_,w);if(S>r)return S}}}return Math.max(r,.2)}var vc=class{constructor(e){this.activeQueries=[];this.queryPool=[];this.currentQuery=null;this.lastGpuTimeMs=0;this.frameStartTime=0;this.lastCpuFrameTimeMs=0;this.textureMemoryBytes=0;this.bufferMemoryBytes=0;this.shaderMemoryBytes=0;this.gl=e,this.ext=e.getExtension("EXT_disjoint_timer_query_webgl2")}get available(){return!!this.ext}getPerformanceReport(e){let r=this.textureMemoryBytes/1048576,n=this.bufferMemoryBytes/(1024*1024);return{frameTimeMs:this.lastCpuFrameTimeMs,gpuTimeMs:this.lastGpuTimeMs,cpuFrameTimeMs:this.lastCpuFrameTimeMs,drawCalls:e.drawCalls,triangles:Math.floor(e.vertexCount/3),vertices:e.vertexCount,textureBinds:e.batches,shaderSwitches:e.shaderSwitches,visibleSurfaces:e.visibleSurfaces,culledSurfaces:e.culledSurfaces,visibleEntities:e.visibleEntities,culledEntities:e.culledEntities,memoryUsageMB:{textures:r,geometry:n,total:r+n}}}startFrame(){if(this.frameStartTime=performance.now(),!this.ext||this.currentQuery)return;let e=this.getQuery();e&&(this.gl.beginQuery(this.ext.TIME_ELAPSED_EXT,e),this.currentQuery=e)}endFrame(){this.lastCpuFrameTimeMs=performance.now()-this.frameStartTime,!(!this.ext||!this.currentQuery)&&(this.gl.endQuery(this.ext.TIME_ELAPSED_EXT),this.activeQueries.push(this.currentQuery),this.currentQuery=null,this.pollQueries())}trackTextureMemory(e){this.textureMemoryBytes+=e}trackBufferMemory(e){this.bufferMemoryBytes+=e}trackShaderMemory(e){this.shaderMemoryBytes+=e}getMemoryUsage(){let e=this.textureMemoryBytes,r=this.bufferMemoryBytes,n=this.shaderMemoryBytes,i=this.bufferMemoryBytes,a=e+r+n;return{texturesBytes:e,geometryBytes:r,shadersBytes:n,buffersBytes:i,totalBytes:a}}getQuery(){return this.queryPool.length>0?this.queryPool.pop():this.gl.createQuery()}pollQueries(){if(this.activeQueries.length===0)return;let e=this.activeQueries[0],r=this.gl.getQueryParameter(e,this.gl.QUERY_RESULT_AVAILABLE),n=this.gl.getParameter(this.ext.GPU_DISJOINT_EXT);if(r)if(n)this.activeQueries.forEach(i=>this.queryPool.push(i)),this.activeQueries.length=0;else{let i=this.gl.getQueryParameter(e,this.gl.QUERY_RESULT);this.lastGpuTimeMs=i/1e6,this.activeQueries.shift(),this.queryPool.push(e)}}dispose(){[...this.activeQueries,...this.queryPool].forEach(e=>this.gl.deleteQuery(e)),this.activeQueries.length=0,this.queryPool.length=0}};var fp={1:[1,0,0,1],2:[0,1,0,1],3:[1,1,0,1],4:[0,0,1,1],5:[0,1,1,1],6:[1,0,1,1],7:[1,1,1,1],0:[0,0,0,1]};function _c(t){let e=[],r="",n;for(let i=0;i<t.length;i++){if(t[i]==="^"&&i+1<t.length){let a=t[i+1];if(fp[a]){r.length>0&&(e.push({text:r,color:n}),r=""),n=fp[a],i++;continue}}r+=t[i]}return r.length>0&&e.push({text:r,color:n}),e}var l_=`
748
+ }`,xc=class{constructor(e){this.vertices=[];this.gl=e,this.program=ce.create(e,{vertex:n_,fragment:i_},{a_position:0,a_color:1}),this.uniformViewProjection=this.program.getUniformLocation("u_viewProjection"),this.vao=new Be(e),this.vbo=new Ce(e,e.STREAM_DRAW),this.vao.configureAttributes([{index:0,size:3,type:e.FLOAT,stride:28,offset:0},{index:1,size:4,type:e.FLOAT,stride:28,offset:12}],this.vbo)}get shaderSize(){return this.program.sourceSize}addLine(e,r,n={r:1,g:0,b:0,a:1}){this.vertices.push(e.x,e.y,e.z,n.r,n.g,n.b,n.a,r.x,r.y,r.z,n.r,n.g,n.b,n.a)}addBBox(e,r,n={r:0,g:1,b:0,a:1}){let i={x:e.x,y:e.y,z:e.z},a={x:r.x,y:e.y,z:e.z},o={x:r.x,y:r.y,z:e.z},s={x:e.x,y:r.y,z:e.z},c={x:e.x,y:e.y,z:r.z},l={x:r.x,y:e.y,z:r.z},u={x:r.x,y:r.y,z:r.z},d={x:e.x,y:r.y,z:r.z};this.addLine(i,a,n),this.addLine(a,o,n),this.addLine(o,s,n),this.addLine(s,i,n),this.addLine(c,l,n),this.addLine(l,u,n),this.addLine(u,d,n),this.addLine(d,c,n),this.addLine(i,c,n),this.addLine(a,l,n),this.addLine(o,u,n),this.addLine(s,d,n)}clear(){this.vertices=[]}render(e){this.vertices.length!==0&&(this.program.use(),this.gl.uniformMatrix4fv(this.uniformViewProjection,!1,e),this.vbo.upload(new Float32Array(this.vertices),this.gl.STREAM_DRAW),this.vao.bind(),this.gl.drawArrays(this.gl.LINES,0,this.vertices.length/7))}};function a_(t,e){let r=t.models[0].headNode;for(;r>=0;){let i=t.nodes[r],a=t.planes[i.planeIndex];a.normal[0]*e.x+a.normal[1]*e.y+a.normal[2]*e.z-a.dist>=0?r=i.children[0]:r=i.children[1]}let n=-(r+1);return{leaf:t.leafs[n],index:n}}function o_(t){if(t.entities.worldspawn?.properties.light){let e=parseInt(t.entities.worldspawn.properties.light,10);if(!isNaN(e))return e/255}if(t.entities.worldspawn?.properties._minlight){let e=parseInt(t.entities.worldspawn.properties._minlight,10);if(!isNaN(e))return e/255}return .2}function s_(t,e,r,n){let i=t.faces[e];if(!i||i.lightOffset<0||!t.lightMapInfo[e])return 0;let o=t.texInfo[i.texInfo],s=1/0,c=-1/0,l=1/0,u=-1/0,d=i.firstEdge;for(let A=0;A<i.numEdges;A++){let L=t.surfEdges[d+A],M=L>=0?t.edges[L].vertices[0]:t.edges[Math.abs(L)].vertices[1],P=t.vertices[M],I=P[0]*o.s[0]+P[1]*o.s[1]+P[2]*o.s[2]+o.sOffset,D=P[0]*o.t[0]+P[1]*o.t[1]+P[2]*o.t[2]+o.tOffset;I<s&&(s=I),I>c&&(c=I),D<l&&(l=D),D>u&&(u=D)}let f=Math.floor(s/16),h=Math.floor(l/16),m=Math.ceil(c/16)-f+1,g=Math.ceil(u/16)-h+1,p=r/16-f,y=n/16-h,v=Math.max(0,Math.min(m-1,Math.floor(p))),b=Math.max(0,Math.min(g-1,Math.floor(y))),x=i.lightOffset+(b*m+v)*3;if(x+2>=t.lightMaps.length)return 0;let _=t.lightMaps[x],w=t.lightMaps[x+1],S=t.lightMaps[x+2];return Math.max(_,w,S)/255}function dp(t,e){if(!t)return 1;let r=o_(t),n={x:e.x,y:e.y,z:e.z-8192},i=1,a=-1,o=0,s=0,{leaf:c,index:l}=a_(t,e);if(c.contents&1)return r;let u=t.leafLists.leafFaces[l];if(u)for(let d of u){let f=t.faces[d],h=t.planes[f.planeIndex],m=f.side,g=m?-h.normal[0]:h.normal[0],p=m?-h.normal[1]:h.normal[1],y=m?-h.normal[2]:h.normal[2],v=m?-h.dist:h.dist;if(y>.7){let b=g*e.x+p*e.y+y*e.z-v;if(b>=0&&b<64){let x=t.texInfo[f.texInfo],_=e.x*x.s[0]+e.y*x.s[1]+e.z*x.s[2]+x.sOffset,w=e.x*x.t[0]+e.y*x.t[1]+e.z*x.t[2]+x.tOffset,S=s_(t,d,_,w);if(S>r)return S}}}return Math.max(r,.2)}var vc=class{constructor(e){this.activeQueries=[];this.queryPool=[];this.currentQuery=null;this.lastGpuTimeMs=0;this.frameStartTime=0;this.lastCpuFrameTimeMs=0;this.textureMemoryBytes=0;this.bufferMemoryBytes=0;this.shaderMemoryBytes=0;this.gl=e,this.ext=e.getExtension("EXT_disjoint_timer_query_webgl2")}get available(){return!!this.ext}getPerformanceReport(e){let r=this.textureMemoryBytes/1048576,n=this.bufferMemoryBytes/(1024*1024);return{frameTimeMs:this.lastCpuFrameTimeMs,gpuTimeMs:this.lastGpuTimeMs,cpuFrameTimeMs:this.lastCpuFrameTimeMs,drawCalls:e.drawCalls,triangles:Math.floor(e.vertexCount/3),vertices:e.vertexCount,textureBinds:e.batches,shaderSwitches:e.shaderSwitches,visibleSurfaces:e.visibleSurfaces,culledSurfaces:e.culledSurfaces,visibleEntities:e.visibleEntities,culledEntities:e.culledEntities,memoryUsageMB:{textures:r,geometry:n,total:r+n}}}startFrame(){if(this.frameStartTime=performance.now(),!this.ext||this.currentQuery)return;let e=this.getQuery();e&&(this.gl.beginQuery(this.ext.TIME_ELAPSED_EXT,e),this.currentQuery=e)}endFrame(){this.lastCpuFrameTimeMs=performance.now()-this.frameStartTime,!(!this.ext||!this.currentQuery)&&(this.gl.endQuery(this.ext.TIME_ELAPSED_EXT),this.activeQueries.push(this.currentQuery),this.currentQuery=null,this.pollQueries())}trackTextureMemory(e){this.textureMemoryBytes+=e}trackBufferMemory(e){this.bufferMemoryBytes+=e}trackShaderMemory(e){this.shaderMemoryBytes+=e}getMemoryUsage(){let e=this.textureMemoryBytes,r=this.bufferMemoryBytes,n=this.shaderMemoryBytes,i=this.bufferMemoryBytes,a=e+r+n;return{texturesBytes:e,geometryBytes:r,shadersBytes:n,buffersBytes:i,totalBytes:a}}getQuery(){return this.queryPool.length>0?this.queryPool.pop():this.gl.createQuery()}pollQueries(){if(this.activeQueries.length===0)return;let e=this.activeQueries[0],r=this.gl.getQueryParameter(e,this.gl.QUERY_RESULT_AVAILABLE),n=this.gl.getParameter(this.ext.GPU_DISJOINT_EXT);if(r)if(n)this.activeQueries.forEach(i=>this.queryPool.push(i)),this.activeQueries.length=0;else{let i=this.gl.getQueryParameter(e,this.gl.QUERY_RESULT);this.lastGpuTimeMs=i/1e6,this.activeQueries.shift(),this.queryPool.push(e)}}dispose(){[...this.activeQueries,...this.queryPool].forEach(e=>this.gl.deleteQuery(e)),this.activeQueries.length=0,this.queryPool.length=0}};var fp={1:[1,0,0,1],2:[0,1,0,1],3:[1,1,0,1],4:[0,0,1,1],5:[0,1,1,1],6:[1,0,1,1],7:[1,1,1,1],0:[0,0,0,1]};function _c(t){let e=[],r="",n;for(let i=0;i<t.length;i++){if(t[i]==="^"&&i+1<t.length){let a=t[i+1];if(fp[a]){r.length>0&&(e.push({text:r,color:n}),r=""),n=fp[a],i++;continue}}r+=t[i]}return r.length>0&&e.push({text:r,color:n}),e}var l_=`
744
749
  attribute vec3 a_position;
745
750
  attribute vec3 a_color;
746
751
  uniform mat4 u_viewProjection;
@@ -792,7 +797,7 @@ void main() {
792
797
 
793
798
  gl_FragColor = vec4(color, 1.0);
794
799
  }
795
- `;function Sc(t){return L.fromValues(t.x,t.y,t.z)}function cr(t){return{x:t[0],y:t[1],z:t[2]}}var wc=class{constructor(e){this.vertices=[];this.solidVertices=[];this.labels=[];this.gl=e,this.shader=ce.create(e,{vertex:l_,fragment:c_}),this.vao=new Be(e),this.vbo=new Ce(e,e.DYNAMIC_DRAW),this.vao.configureAttributes([{index:0,size:3,type:e.FLOAT,stride:24,offset:0},{index:1,size:3,type:e.FLOAT,stride:24,offset:12}],this.vbo),this.shaderSolid=ce.create(e,{vertex:u_,fragment:d_}),this.vaoSolid=new Be(e),this.vboSolid=new Ce(e,e.DYNAMIC_DRAW),this.vaoSolid.configureAttributes([{index:0,size:3,type:e.FLOAT,stride:36,offset:0},{index:1,size:3,type:e.FLOAT,stride:36,offset:12},{index:2,size:3,type:e.FLOAT,stride:36,offset:24}],this.vboSolid)}get shaderSize(){return this.shader.sourceSize+this.shaderSolid.sourceSize}drawLine(e,r,n){this.vertices.push(e.x,e.y,e.z,n.r,n.g,n.b,r.x,r.y,r.z,n.r,n.g,n.b)}drawBoundingBox(e,r,n){let{x:i,y:a,z:o}=e,{x:s,y:c,z:l}=r;this.drawLine({x:i,y:a,z:o},{x:s,y:a,z:o},n),this.drawLine({x:s,y:a,z:o},{x:s,y:c,z:o},n),this.drawLine({x:s,y:c,z:o},{x:i,y:c,z:o},n),this.drawLine({x:i,y:c,z:o},{x:i,y:a,z:o},n),this.drawLine({x:i,y:a,z:l},{x:s,y:a,z:l},n),this.drawLine({x:s,y:a,z:l},{x:s,y:c,z:l},n),this.drawLine({x:s,y:c,z:l},{x:i,y:c,z:l},n),this.drawLine({x:i,y:c,z:l},{x:i,y:a,z:l},n),this.drawLine({x:i,y:a,z:o},{x:i,y:a,z:l},n),this.drawLine({x:s,y:a,z:o},{x:s,y:a,z:l},n),this.drawLine({x:s,y:c,z:o},{x:s,y:c,z:l},n),this.drawLine({x:i,y:c,z:o},{x:i,y:c,z:l},n)}drawPoint(e,r,n){let i=r/2;this.drawBoundingBox({x:e.x-i,y:e.y-i,z:e.z-i},{x:e.x+i,y:e.y+i,z:e.z+i},n)}drawAxes(e,r){this.drawLine(e,{x:e.x+r,y:e.y,z:e.z},{r:1,g:0,b:0}),this.drawLine(e,{x:e.x,y:e.y+r,z:e.z},{r:0,g:1,b:0}),this.drawLine(e,{x:e.x,y:e.y,z:e.z+r},{r:0,g:0,b:1})}drawText3D(e,r){this.labels.push({text:e,position:r})}addTriangle(e,r,n,i,a){this.solidVertices.push(e.x,e.y,e.z),this.solidVertices.push(a.r,a.g,a.b),this.solidVertices.push(i.x,i.y,i.z),this.solidVertices.push(r.x,r.y,r.z),this.solidVertices.push(a.r,a.g,a.b),this.solidVertices.push(i.x,i.y,i.z),this.solidVertices.push(n.x,n.y,n.z),this.solidVertices.push(a.r,a.g,a.b),this.solidVertices.push(i.x,i.y,i.z)}addCone(e,r,n,i){let o=Sc(e),s=Sc(r),c=L.create();L.subtract(c,o,s),L.normalize(c,c);let l=L.fromValues(0,0,1);Math.abs(L.dot(c,l))>.99&&(l=L.fromValues(0,1,0));let u=L.create();L.cross(u,l,c),L.normalize(u,u);let d=L.create();L.cross(d,c,u);let f=[];for(let p=0;p<16;p++){let y=p/16*Math.PI*2,v=Math.cos(y)*n,b=Math.sin(y)*n,x=L.clone(s);L.scaleAndAdd(x,x,u,v),L.scaleAndAdd(x,x,d,b),f.push(x)}let h=L.clone(c);L.scale(h,h,-1);let m=cr(h),g=r;for(let p=0;p<16;p++){let y=cr(f[p]),v=cr(f[(p+1)%16]);this.addTriangle(g,v,y,m,i)}for(let p=0;p<16;p++){let y=f[p],v=f[(p+1)%16],b=cr(y),x=cr(v),_=L.create();L.subtract(_,v,y);let w=L.create();L.subtract(w,o,y);let S=L.create();L.cross(S,_,w),L.normalize(S,S);let A=cr(S);this.addTriangle(b,x,e,A,i)}}addTorus(e,r,n,i,a={x:0,y:0,z:1}){let c=Sc(a);L.normalize(c,c);let l=Sc(e),u=L.fromValues(0,0,1),d=F.create();if(Math.abs(L.dot(c,u))>.999)c[2]<0&&F.rotateX(d,d,Math.PI);else{let m=L.create();L.cross(m,u,c),L.normalize(m,m);let g=Math.acos(L.dot(u,c));F.fromRotation(d,g,m)}let f=[],h=[];for(let m=0;m<=16;m++){let g=m/16*Math.PI*2,p=Math.cos(g),y=Math.sin(g),v=[],b=[];for(let x=0;x<=8;x++){let _=x/8*Math.PI*2,w=Math.cos(_),S=Math.sin(_),A=(r+n*w)*p,T=(r+n*w)*y,M=n*S,P=L.fromValues(A,T,M),I=w*p,D=w*y,B=S,O=L.fromValues(I,D,B);L.transformMat4(P,P,d),L.transformMat4(O,O,d),L.add(P,P,l),v.push(P),b.push(O)}f.push(v),h.push(b)}for(let m=0;m<16;m++)for(let g=0;g<8;g++){let p=f[m][g],y=f[m+1][g],v=f[m+1][g+1],b=f[m][g+1],x=cr(p),_=cr(y),w=cr(v),S=cr(b),A=L.create();L.subtract(A,y,p);let T=L.create();L.subtract(T,v,p);let M=L.create();L.cross(M,A,T),L.normalize(M,M),this.addTriangle(x,_,w,cr(M),i);let P=L.create();L.subtract(P,v,p);let I=L.create();L.subtract(I,b,p);let D=L.create();L.cross(D,P,I),L.normalize(D,D),this.addTriangle(x,w,S,cr(D),i)}}render(e,r=!1){if(r&&this.gl.disable(this.gl.DEPTH_TEST),this.vertices.length>0){this.shader.use();let n=this.shader.getUniformLocation("u_viewProjection");n&&this.gl.uniformMatrix4fv(n,!1,e),this.vbo.upload(new Float32Array(this.vertices)),this.vao.bind(),this.gl.drawArrays(this.gl.LINES,0,this.vertices.length/6)}if(this.solidVertices.length>0){this.shaderSolid.use();let n=this.shaderSolid.getUniformLocation("u_viewProjection");n&&this.gl.uniformMatrix4fv(n,!1,e);let i=this.shaderSolid.getUniformLocation("u_lightingEnabled");i&&this.gl.uniform1i(i,1),this.vboSolid.upload(new Float32Array(this.solidVertices)),this.vaoSolid.bind(),this.gl.drawArrays(this.gl.TRIANGLES,0,this.solidVertices.length/9)}r&&this.gl.enable(this.gl.DEPTH_TEST)}getLabels(e,r,n){let i=[];for(let a of this.labels){let o=Aa.fromValues(a.position.x,a.position.y,a.position.z,1),s=Aa.create(),l=e,u=o[0],d=o[1],f=o[2],h=o[3];if(s[0]=l[0]*u+l[4]*d+l[8]*f+l[12]*h,s[1]=l[1]*u+l[5]*d+l[9]*f+l[13]*h,s[2]=l[2]*u+l[6]*d+l[10]*f+l[14]*h,s[3]=l[3]*u+l[7]*d+l[11]*f+l[15]*h,s[3]>0){let m=s[0]/s[3],g=s[1]/s[3],p=(m+1)*.5*r,y=(1-g)*.5*n;p>=0&&p<=r&&y>=0&&y<=n&&i.push({text:a.text,x:p,y})}}return i}clear(){this.vertices=[],this.solidVertices=[],this.labels=[]}};function Mc(t,e,r,n=32){let i=[];for(let s of t){let c=!0;for(let l of e)if(l.normal.x*s.origin.x+l.normal.y*s.origin.y+l.normal.z*s.origin.z+l.distance<-s.intensity){c=!1;break}if(c){let l=0;if(r){let u=s.origin.x-r.x,d=s.origin.y-r.y,f=s.origin.z-r.z;l=u*u+d*d+f*f}i.push({light:s,distSq:l})}}r&&i.sort((s,c)=>s.distSq-c.distSq);let a=[],o=Math.min(i.length,n);for(let s=0;s<o;s++)a.push(i[s].light);return a}function Zd(t){let e=(t*1664525+1013904223>>>0)/4294967296,r=(t*25214903917+11>>>0)/4294967296,n=(t*69069+1>>>0)/4294967296;return[e,r,n,1]}var hp=t=>{let e=new va(t),r=new _a(t),n=new Ma(t),i=new Pa(t),a=new Ba(t),o=new xc(t),s=new wc(t),c=new vc(t),l=new jf({seed:Date.now()}),u=new Ra(4096,l),d=new Ca(t,u),f=e.shaderSize+r.shaderSize+n.shaderSize+i.shaderSize+a.shaderSize+o.shaderSize+s.shaderSize+d.shaderSize;c.trackShaderMemory(f);let h=new Map,m=new Map,g=new Map,p=new Map,y=0,v=600,b=300,x=null,_={drawCalls:0,vertexCount:0,batches:0,shaderSwitches:0,visibleSurfaces:0,culledSurfaces:0,visibleEntities:0,culledEntities:0},w=new Map,S=new Map,A=0,T=1,M=1,P=!1,I=0,D=new Map,B=!1,O=!1,Q=.5,Ge=1,me=new Array(1024).fill(!0),Me=up(t,e,r),ge=1e4,ue=[],ye=0,Ve=pc.create(),ct=L.create(),qt=L.create();for(let E=0;E<ge;E++){let $={id:-1,model:void 0,transform:new Float32Array(16),type:"md3",blend:{frame0:0,frame1:0,lerp:0},tint:[1,1,1,1],lighting:{ambient:[.5,.5,.5],dynamicLights:[],modelMatrix:void 0}};$.lighting&&($.lighting.modelMatrix=$.transform),ue.push($)}let ut=[],He,$r,k,se=(E,$)=>{if(E.type==="md2"){let ae=E.model;if(!ae.lods||ae.lods.length===0)return{model:E.model,type:E.type};let de=E.transform[12]-$.x,ne=E.transform[13]-$.y,ve=E.transform[14]-$.z,tt=Math.sqrt(de*de+ne*ne+ve*ve),Nt=Math.floor(tt*Ge/500);if(Nt<=0)return{model:E.model,type:E.type};let Ue=ae.lods,jt=Math.min(Nt-1,Ue.length-1);return{model:Ue[jt],type:E.type}}return{model:E.model,type:E.type}},ke=(E,$,ae)=>{c.startFrame(),y++;let de=ut.length>0?[...$,...ut]:$;ut.length=0,ye=0,E.deltaTime&&u.update(E.deltaTime),t.disable(t.BLEND),t.enable(t.DEPTH_TEST),t.depthMask(!0);let ve=E.renderMode,tt=!1;ae?.wireframe||A===6?ve={mode:"wireframe",applyToAll:!0,color:[1,1,1,1]}:A===5&&(tt=!0);let Nt=E.sky;ae?.showSkybox===!1&&(Nt=void 0);let Ue=new Float32Array(E.camera.viewProjectionMatrix),jt=sr(Ue),Gt=E.dlights?Mc(E.dlights,jt,{x:E.camera.position[0],y:E.camera.position[1],z:E.camera.position[2]},32):void 0,ja={...E,sky:Nt,renderMode:ve,disableLightmaps:ae?.showLightmaps===!1&&A!==5,dlights:Gt,lightmapOnly:tt,brightness:T,gamma:M,fullbright:P,ambient:I,lightStyleOverrides:D,underwaterWarp:B,bloom:O,bloomIntensity:Q,portalState:me},Ks=Me.renderFrame(ja),Vf=Ks.facesDrawn||0,Hf=0;E.world&&E.world.map&&E.world.map.faces&&(Hf=E.world.map.faces.length);let ag=Hf-Vf,lu=-1,cu=-1,uu=null;if(E.world&&ae?.cullingEnabled!==!1){let z={x:E.camera.position[0],y:E.camera.position[1],z:E.camera.position[2]},We=Ti(E.world.map,z);if(We>=0){let _t=E.world.map.leafs[We];lu=_t.cluster,cu=_t.area,cu>=0&&E.world.map.areas.length>0&&(uu=gd(E.world.map,cu,me))}}let Ys,Qa=0,du=0,Wf=0,qs=0,og={x:E.camera.position[0],y:E.camera.position[1],z:E.camera.position[2]};if(y%v===0)for(let[z,We]of p)y-We.lastFrameSeen>b&&p.delete(z);for(let z of de){if(E.world&&lu>=0){let J={x:z.transform[12],y:z.transform[13],z:z.transform[14]},N=-1;if(z.id!==void 0){let q=p.get(z.id);q&&q.position[12]===z.transform[12]&&q.position[13]===z.transform[13]&&q.position[14]===z.transform[14]?(N=q.leafIndex,q.lastFrameSeen=y):(N=Ti(E.world.map,J),N>=0&&p.set(z.id,{leafIndex:N,position:new Float32Array(z.transform),lastFrameSeen:y}))}else N=Ti(E.world.map,J);if(N>=0){let q=E.world.map.leafs[N],Qt=q.cluster,$e=q.area;if(uu&&$e>=0&&!uu.has($e)){qs++;continue}if(!pd(E.world.map.visibility,lu,Qt)){qs++;continue}}}let{model:We,type:_t}=se(z,og),Xe,Ee;if(_t==="md2"){let J=We,N=J.frames[z.blend.frame0%J.frames.length],q=J.frames[z.blend.frame1%J.frames.length];N&&q&&(Xe={x:Math.min(N.minBounds.x,q.minBounds.x),y:Math.min(N.minBounds.y,q.minBounds.y),z:Math.min(N.minBounds.z,q.minBounds.z)},Ee={x:Math.max(N.maxBounds.x,q.maxBounds.x),y:Math.max(N.maxBounds.y,q.maxBounds.y),z:Math.max(N.maxBounds.z,q.maxBounds.z)})}else if(_t==="md3"){let J=We,N=J.frames[z.blend.frame0%J.frames.length],q=J.frames[z.blend.frame1%J.frames.length];N&&q?(Xe={x:Math.min(N.minBounds.x,q.minBounds.x),y:Math.min(N.minBounds.y,q.minBounds.y),z:Math.min(N.minBounds.z,q.minBounds.z)},Ee={x:Math.max(N.maxBounds.x,q.maxBounds.x),y:Math.max(N.maxBounds.y,q.maxBounds.y),z:Math.max(N.maxBounds.z,q.maxBounds.z)}):(Xe={x:-32,y:-32,z:-32},Ee={x:32,y:32,z:32})}if(Xe&&Ee){let J=hm(Xe,Ee,z.transform);if(!Ei(J.mins,J.maxs,jt)){qs++;continue}}Wf++;let hr={x:z.transform[12],y:z.transform[13],z:z.transform[14]},rt=dp(E.world?.map,hr),Fe=z.id!==void 0?w.get(z.id):void 0;switch(_t){case"md2":{let J=We,N=m.get(J);if(N)N.update(J,z.blend);else{N=new wa(t,J,z.blend),m.set(J,N);let Ke=N.geometry.vertices.length*8*4,pn=N.geometry.indices.length*2;c.trackBufferMemory(Ke+pn)}let q=gu(Ue,z.transform),Qt=z.skin,$e=Qt?E.world?.textures?.get(Qt):void 0;$e&&$e!==Ys&&($e.bind(0),Ys=$e);let Jt=ve;if(Jt&&!Jt.applyToAll&&$e&&(Jt=void 0),Jt?.generateRandomColor&&z.id!==void 0){let Ke=Zd(z.id);Jt={...Jt,color:Ke}}if(n.bind({modelViewProjection:q,modelMatrix:z.transform,ambientLight:rt,dlights:E.dlights,renderMode:Jt,tint:z.tint,brightness:T,gamma:M,fullbright:P,ambient:I}),n.draw(N,Jt),Qa++,du+=N.geometry.vertices.length,Fe){let Ke={mode:"wireframe",applyToAll:!0,color:Fe};n.bind({modelViewProjection:q,modelMatrix:z.transform,ambientLight:1,renderMode:Ke,tint:[1,1,1,1],brightness:1,gamma:1,fullbright:!0,ambient:0}),n.draw(N,Ke),Qa++}}break;case"md3":{let J=We,N=h.get(J),q=z,Qt=E.dlights?E.dlights.map(Ke=>({origin:Ke.origin,color:[Ke.color.x,Ke.color.y,Ke.color.z],radius:Ke.intensity})):void 0,$e={...q.lighting,ambient:[rt,rt,rt],dynamicLights:Qt,modelMatrix:z.transform};N?N.update(z.blend,$e):(N=new La(t,J,z.blend,$e),h.set(J,N));let Jt=gu(Ue,z.transform);i.bind(Jt);for(let Ke of J.surfaces){let pn=N.surfaces.get(Ke.name);if(pn){let $f=q.skins?.get(Ke.name),Ja=$f?E.world?.textures?.get($f):void 0;Ja&&Ja!==Ys&&(Ja.bind(0),Ys=Ja);let ti=ve;if(ti&&!ti.applyToAll&&Ja&&(ti=void 0),ti?.generateRandomColor&&z.id!==void 0){let Kf=Zd(z.id);ti={...ti,color:Kf}}let sg={renderMode:ti,brightness:T,gamma:M,fullbright:P,globalAmbient:I};if(i.drawSurface(pn,sg),Qa++,du+=pn.geometry.vertices.length,Fe){let lg={renderMode:{mode:"wireframe",applyToAll:!0,color:Fe},brightness:1,gamma:1,fullbright:!0,globalAmbient:0};i.drawSurface(pn,lg),Qa++}}}}break}}let ei=E.camera.viewMatrix;if(ei){let z={x:ei[0],y:ei[4],z:ei[8]},We={x:ei[1],y:ei[5],z:ei[9]};d.render({viewProjection:Ue,viewRight:z,viewUp:We})}if(ja.waterTint&&(He(),k(0,0,t.canvas.width,t.canvas.height,ja.waterTint),$r()),o.render(Ue),o.clear(),E.world&&(S.size>0||A===3)){let z=new Map(S);if(A===3&&E.world){let We=sr(Ue),_t={x:E.camera.position[0],y:E.camera.position[1],z:E.camera.position[2]},Xe=cn(E.world.map,_t,We,me);for(let{faceIndex:Ee,leafIndex:hr}of Xe){let rt=E.world.map.leafs[hr];rt&&!z.has(Ee)&&z.set(Ee,Zd(rt.cluster))}}for(let[We,_t]of z){let Xe=E.world.surfaces[We];if(Xe&&Xe.vertexCount>0){let Ee=[];for(let Fe=0;Fe<Xe.vertexCount;Fe++)Ee.push({x:Xe.vertexData[Fe*7],y:Xe.vertexData[Fe*7+1],z:Xe.vertexData[Fe*7+2]});let rt={r:_t[0],g:_t[1],b:_t[2]};for(let Fe=0;Fe<Ee.length;Fe++){let J=Ee[Fe],N=Ee[(Fe+1)%Ee.length];s.drawLine(J,N,rt)}s.drawLine(Ee[0],Ee[Ee.length/2|0],rt)}}}if((ae?.showNormals||A===2)&&E.world){let z=sr(Ue),We={x:E.camera.position[0],y:E.camera.position[1],z:E.camera.position[2]},_t=cn(E.world.map,We,z,me);for(let{faceIndex:Xe}of _t){let Ee=E.world.map.faces[Xe],hr=E.world.map.planes[Ee.planeIndex],rt=E.world.surfaces[Xe];if(!rt)continue;let Fe=0,J=0,N=0,q=rt.vertexCount;for(let Qt=0;Qt<q;Qt++){let $e=Qt*7;Fe+=rt.vertexData[$e],J+=rt.vertexData[$e+1],N+=rt.vertexData[$e+2]}if(q>0){Fe/=q,J/=q,N/=q;let Qt=Ee.side===0?hr.normal[0]:-hr.normal[0],$e=Ee.side===0?hr.normal[1]:-hr.normal[1],Jt=Ee.side===0?hr.normal[2]:-hr.normal[2],Ke={x:Fe,y:J,z:N},pn={x:Fe+Qt*8,y:J+$e*8,z:N+Jt*8};s.drawLine(Ke,pn,{r:1,g:1,b:0})}}}s.render(Ue);let Xf=s.getLabels(Ue,t.canvas.width,t.canvas.height);if(Xf.length>0){He();for(let z of Xf)vt(z.x,z.y,z.text,[1,1,1,1]);$r()}s.clear(),_={drawCalls:Ks.drawCalls+Qa,vertexCount:Ks.vertexCount+du,batches:Ks.batches,shaderSwitches:0,visibleSurfaces:Vf,culledSurfaces:ag,visibleEntities:Wf,culledEntities:qs},c.endFrame()},De=async(E,$)=>{if(g.has(E))return g.get(E);let ae=new Blob([$]),de=await createImageBitmap(ae),ne=new lt(t);return ne.upload(de.width,de.height,de),g.set(E,ne),c.trackTextureMemory(de.width*de.height*4),E.includes("conchars")&&(x=ne),ne},fr=(E,$)=>{if(g.has(E))return g.get(E);let ae=new lt(t),de=$.levels[0];return ae.upload(de.width,de.height,de.rgba),g.set(E,ae),c.trackTextureMemory(de.width*de.height*4),E.includes("conchars")&&(x=ae),ae},Zt=E=>g.get(E);He=()=>{t.enable(t.BLEND),t.blendFunc(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA),t.disable(t.DEPTH_TEST),t.depthMask(!1);let E=F.create();F.ortho(E,0,t.canvas.width,t.canvas.height,0,-1,1),a.begin(E)},$r=()=>{t.disable(t.BLEND),t.enable(t.DEPTH_TEST),t.depthMask(!0)};let mn=(E,$,ae,de)=>{ae.bind(0),a.draw(E,$,ae.width,ae.height,0,0,1,1,de)},Hs=(E,$,ae,de)=>{if(!x)return;let ne=8,ve=8,tt=x.width/ne,Nt=ae&255,Ue=Nt%tt*ne/x.width,jt=Math.floor(Nt/tt)*ve/x.height,Gt=Ue+ne/x.width,ja=jt+ve/x.height;x.bind(0),a.draw(E,$,ne,ve,Ue,jt,Gt,ja,de)},vt=(E,$,ae,de)=>{let ne=_c(ae),ve=E,tt=8;for(let Nt of ne){let Ue=Nt.color||de;for(let jt=0;jt<Nt.text.length;jt++)Hs(ve,$,Nt.text.charCodeAt(jt),Ue),ve+=tt}},Ws=(E,$)=>{let ne=$.replace(/\^[0-9]/g,"").length*8,ve=(t.canvas.width-ne)/2;vt(ve,E,$)};return k=(E,$,ae,de,ne)=>{a.drawRect(E,$,ae,de,ne)},{get width(){return t.canvas.width},get height(){return t.canvas.height},get collisionVis(){return o},get debug(){return s},get particleSystem(){return u},getPerformanceReport:()=>c.getPerformanceReport(_),getMemoryUsage:()=>c.getMemoryUsage(),renderFrame:ke,registerPic:De,registerTexture:fr,getTexture:Zt,begin2D:He,end2D:$r,drawPic:mn,drawString:vt,drawCenterString:Ws,drawfillRect:k,setEntityHighlight:(E,$)=>{w.set(E,$)},clearEntityHighlight:E=>{w.delete(E)},highlightSurface:(E,$)=>{S.set(E,$)},removeSurfaceHighlight:E=>{S.delete(E)},setDebugMode:E=>{A=E},setBrightness:E=>{T=Math.max(0,Math.min(2,E))},setGamma:E=>{M=Math.max(.5,Math.min(3,E))},setFullbright:E=>{P=E},setAmbient:E=>{I=Math.max(0,Math.min(1,E))},setLightStyle:(E,$)=>{$===null?D.delete(E):D.set(E,$)},setUnderwaterWarp:E=>{B=E},setBloom:E=>{O=E},setBloomIntensity:E=>{Q=E},setLodBias:E=>{Ge=Math.max(0,Math.min(2,E))},setAreaPortalState:(E,$)=>{E>=0&&E<me.length&&(me[E]=$)},renderInstanced:(E,$)=>{let ae="glCommands"in E,de=ae?"md2":"md3";for(let ne of $){if(ye>=ge){console.warn("Max instances reached");break}let ve=ue[ye++];ve.model=E,ve.type=de;let tt=ve.blend;ne.frame!==void 0?(tt.frame0=ne.frame,tt.frame1=ne.frame,tt.lerp=0):(tt.frame0=ne.frame0||0,tt.frame1=ne.frame1||0,tt.lerp=ne.lerp||0),ae&&(ve.skin=ne.skin!==void 0?"skin"+ne.skin:void 0);let Nt=ne.rotation,Ue=ne.position,jt=ne.scale||{x:1,y:1,z:1};F.fromRotationTranslationScale(ve.transform,Ve,ct,qt);let Gt=ve.lighting;Gt&&(Gt.dynamicLights?Gt.dynamicLights.length=0:Gt.dynamicLights=[],Gt.ambient?(Gt.ambient[0]=.5,Gt.ambient[1]=.5,Gt.ambient[2]=.5):Gt.ambient=[.5,.5,.5]),ut.push(ve)}},uploadBspGeometry:E=>{let $=oc(E);return sc(t,$,E)},dispose:()=>{c.dispose()}}};async function Ac(t,e){if(!navigator.gpu)throw new Error("WebGPU is not supported in this environment");let r=await navigator.gpu.requestAdapter({powerPreference:e?.powerPreference||"high-performance"});if(!r)throw new Error("No appropriate GPUAdapter found");if(e?.requiredFeatures){for(let f of e.requiredFeatures)if(!r.features.has(f))throw new Error(`Required feature not available: ${f}`)}let n={requiredFeatures:e?.requiredFeatures,requiredLimits:e?.requiredLimits},i=await r.requestDevice(n),a,o="rgba8unorm",s="depth24plus",c=!0,l=e?.width||800,u=e?.height||600;if(t){if(a=t.getContext("webgpu"),!a)throw new Error("Failed to get WebGPU context from canvas");c=!1,o=navigator.gpu.getPreferredCanvasFormat(),l=t.width,u=t.height,a.configure({device:i,format:o,alphaMode:"opaque"})}let d=new Set;for(let f of r.features)d.add(f);return{adapter:r,device:i,context:a,format:o,depthFormat:s,features:d,limits:i.limits,isHeadless:c,width:l,height:u}}function mp(t){let{features:e,limits:r}=t;return{hasTimestampQuery:e.has("timestamp-query"),hasDepthClipControl:e.has("depth-clip-control"),hasTextureCompressionBC:e.has("texture-compression-bc"),hasTextureCompressionETC2:e.has("texture-compression-etc2"),hasTextureCompressionASTC:e.has("texture-compression-astc"),maxTextureDimension2D:r.maxTextureDimension2D,maxBindGroups:r.maxBindGroups,maxUniformBufferBindingSize:r.maxUniformBufferBindingSize,maxStorageBufferBindingSize:r.maxStorageBufferBindingSize}}var f_=!0;function h_(t,e){if(!t)return 1;let r=Math.floor(e*10)%t.length;return(t.charCodeAt(r)-97)/12}function m_(t){return[...t].sort((e,r)=>r.sortKey-e.sortKey)}function p_(t){return[...t].sort((e,r)=>e.sortKey-r.sortKey)}var Ec=class{constructor(e,r){this.context=e;this.pipelines=r;this.depthTexture=null;this.copyTexture=null;this.headlessTarget=null;this.lastWidth=0;this.lastHeight=0;this.lastFrameTime=0;this.currentFrameContext=null}ensureDepthTexture(e,r){return this.depthTexture&&this.lastWidth===e&&this.lastHeight===r?this.depthTexture.createView():(this.depthTexture&&this.depthTexture.destroy(),this.depthTexture=this.context.device.createTexture({size:[e,r],format:"depth24plus",usage:GPUTextureUsage.RENDER_ATTACHMENT,label:"depth-buffer"}),this.copyTexture&&(this.copyTexture.destroy(),this.copyTexture=null),this.lastWidth=e,this.lastHeight=r,this.depthTexture.createView())}ensureCopyTexture(e,r){return this.copyTexture&&this.lastWidth===e&&this.lastHeight===r?this.copyTexture:(this.copyTexture&&this.copyTexture.destroy(),this.copyTexture=this.context.device.createTexture({size:[e,r],format:this.context.format,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT,label:"frame-copy-texture"}),this.copyTexture)}ensureHeadlessTarget(e,r){return this.headlessTarget&&this.headlessTarget.width===e&&this.headlessTarget.height===r?this.headlessTarget.createView():(this.headlessTarget&&this.headlessTarget.destroy(),this.headlessTarget=this.context.device.createTexture({size:[e,r],format:this.context.format,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC|GPUTextureUsage.TEXTURE_BINDING,label:"headless-render-target"}),this.headlessTarget.createView())}beginFrame(){let{device:e,context:r,width:n,height:i}=this.context,a=e.createCommandEncoder({label:"frame-command-encoder"}),o;r?o=r.getCurrentTexture().createView():o=this.ensureHeadlessTarget(n,i);let s=this.ensureDepthTexture(n,i);return{device:e,commandEncoder:a,renderTarget:o,depthTexture:s,width:n,height:i}}begin2DPass(){if(!this.currentFrameContext)throw new Error("begin2DPass called outside of renderFrame");let{commandEncoder:e,renderTarget:r,width:n,height:i}=this.currentFrameContext;this.pipelines.sprite.setProjection(n,i),this.pipelines.sprite.begin(e,r)}end2DPass(){this.pipelines.sprite.end()}renderFrame(e){let r=performance.now(),n=this.lastFrameTime>0?1e3/(r-this.lastFrameTime):0;this.lastFrameTime=r;let i={batches:0,facesDrawn:0,drawCalls:0,skyDrawn:!1,viewModelDrawn:!1,fps:Math.round(n),vertexCount:0},a=this.beginFrame();this.currentFrameContext=a;let{commandEncoder:o,renderTarget:s,depthTexture:c}=a,{clearColor:l=[0,0,0,1],world:u,camera:d,timeSeconds:f=0,dlights:h,renderMode:m,disableLightmaps:g,lightmapOnly:p,brightness:y,gamma:v,fullbright:b,ambient:x,lightStyleOverrides:_,portalState:w}=e,S=new Float32Array(e.camera.viewProjectionMatrix),A={colorAttachments:[{view:s,clearValue:l,loadOp:"clear",storeOp:"store"}],depthStencilAttachment:{view:c,depthClearValue:1,depthLoadOp:"clear",depthStoreOp:"store"},label:"opaque-render-pass"},T=o.beginRenderPass(A);if(e.sky&&e.sky.cubemap){if(f_){let I=e.cameraState??e.camera.toState(),D=Li(e.timeSeconds??0,e.sky.scrollSpeeds??[.01,.02]);this.pipelines.skybox.draw(T,{cameraState:I,scroll:D,cubemap:e.sky.cubemap})}else{let I=Sa(e.camera.viewMatrix),D=F.create();F.multiply(D,e.camera.projectionMatrix,I);let B=Li(e.timeSeconds??0,e.sky.scrollSpeeds??[.01,.02]);this.pipelines.skybox.draw(T,{viewProjection:D,scroll:B,cubemap:e.sky.cubemap})}i.skyDrawn=!0}let M=[],P=[];if(u){u.materials?.update(f);let I=sr(Array.from(S)),D={x:d.position[0]??0,y:d.position[1]??0,z:d.position[2]??0},B=cn(u.map,D,I,w);for(let ge of B){let ue=u.surfaces[ge.faceIndex];if(!ue)continue;(ue.surfaceFlags&(xn|vn|Yr))!==0?P.push(ge):M.push(ge)}let O=m_(M),Q=u.lightStyles||[];if(_&&_.size>0){let ge=[...u.lightStyles||[]];for(let[ue,ye]of _){for(;ge.length<=ue;)ge.push(1);ge[ue]=h_(ye,f)}Q=ge}let Ge=(ge,ue,ye)=>{for(let{faceIndex:Ve}of ge){let ct=u.surfaces[Ve];if(!ct||(ct.surfaceFlags&bn)!==0)continue;let qt=u.map.faces[Ve]?.styles;this.pipelines.bsp.bind(ue,{modelViewProjection:S,styleIndices:qt,styleValues:ye,surfaceFlags:ct.surfaceFlags,timeSeconds:f,dlights:h,renderMode:m,lightmapOnly:p,brightness:y,gamma:v,fullbright:b,ambient:x,cameraPosition:e.camera.position}),this.pipelines.bsp.draw(ue,ct,m),i.facesDrawn++,i.drawCalls++,i.vertexCount+=ct.vertexCount}};Ge(O,T,Q),T.end();let me={colorAttachments:[{view:s,loadOp:"load",storeOp:"store"}],depthStencilAttachment:{view:c,depthLoadOp:"load",depthStoreOp:"store"},label:"transparent-render-pass"},Me=o.beginRenderPass(me);if(P.length>0){let ge=p_(P);Ge(ge,Me,Q)}Me.end()}else T.end();return e.underwaterWarp||e.bloom,e.onDraw2D&&e.onDraw2D(),this.pipelines.sprite.isActive&&(console.warn("2D render pass was not properly closed - auto-closing to prevent resource leak"),this.end2DPass()),this.context.device.queue.submit([o.finish()]),this.currentFrameContext=null,i}};var pp=`
800
+ `;function Sc(t){return T.fromValues(t.x,t.y,t.z)}function cr(t){return{x:t[0],y:t[1],z:t[2]}}var wc=class{constructor(e){this.vertices=[];this.solidVertices=[];this.labels=[];this.gl=e,this.shader=ce.create(e,{vertex:l_,fragment:c_}),this.vao=new Be(e),this.vbo=new Ce(e,e.DYNAMIC_DRAW),this.vao.configureAttributes([{index:0,size:3,type:e.FLOAT,stride:24,offset:0},{index:1,size:3,type:e.FLOAT,stride:24,offset:12}],this.vbo),this.shaderSolid=ce.create(e,{vertex:u_,fragment:d_}),this.vaoSolid=new Be(e),this.vboSolid=new Ce(e,e.DYNAMIC_DRAW),this.vaoSolid.configureAttributes([{index:0,size:3,type:e.FLOAT,stride:36,offset:0},{index:1,size:3,type:e.FLOAT,stride:36,offset:12},{index:2,size:3,type:e.FLOAT,stride:36,offset:24}],this.vboSolid)}get shaderSize(){return this.shader.sourceSize+this.shaderSolid.sourceSize}drawLine(e,r,n){this.vertices.push(e.x,e.y,e.z,n.r,n.g,n.b,r.x,r.y,r.z,n.r,n.g,n.b)}drawBoundingBox(e,r,n){let{x:i,y:a,z:o}=e,{x:s,y:c,z:l}=r;this.drawLine({x:i,y:a,z:o},{x:s,y:a,z:o},n),this.drawLine({x:s,y:a,z:o},{x:s,y:c,z:o},n),this.drawLine({x:s,y:c,z:o},{x:i,y:c,z:o},n),this.drawLine({x:i,y:c,z:o},{x:i,y:a,z:o},n),this.drawLine({x:i,y:a,z:l},{x:s,y:a,z:l},n),this.drawLine({x:s,y:a,z:l},{x:s,y:c,z:l},n),this.drawLine({x:s,y:c,z:l},{x:i,y:c,z:l},n),this.drawLine({x:i,y:c,z:l},{x:i,y:a,z:l},n),this.drawLine({x:i,y:a,z:o},{x:i,y:a,z:l},n),this.drawLine({x:s,y:a,z:o},{x:s,y:a,z:l},n),this.drawLine({x:s,y:c,z:o},{x:s,y:c,z:l},n),this.drawLine({x:i,y:c,z:o},{x:i,y:c,z:l},n)}drawPoint(e,r,n){let i=r/2;this.drawBoundingBox({x:e.x-i,y:e.y-i,z:e.z-i},{x:e.x+i,y:e.y+i,z:e.z+i},n)}drawAxes(e,r){this.drawLine(e,{x:e.x+r,y:e.y,z:e.z},{r:1,g:0,b:0}),this.drawLine(e,{x:e.x,y:e.y+r,z:e.z},{r:0,g:1,b:0}),this.drawLine(e,{x:e.x,y:e.y,z:e.z+r},{r:0,g:0,b:1})}drawText3D(e,r){this.labels.push({text:e,position:r})}addTriangle(e,r,n,i,a){this.solidVertices.push(e.x,e.y,e.z),this.solidVertices.push(a.r,a.g,a.b),this.solidVertices.push(i.x,i.y,i.z),this.solidVertices.push(r.x,r.y,r.z),this.solidVertices.push(a.r,a.g,a.b),this.solidVertices.push(i.x,i.y,i.z),this.solidVertices.push(n.x,n.y,n.z),this.solidVertices.push(a.r,a.g,a.b),this.solidVertices.push(i.x,i.y,i.z)}addCone(e,r,n,i){let o=Sc(e),s=Sc(r),c=T.create();T.subtract(c,o,s),T.normalize(c,c);let l=T.fromValues(0,0,1);Math.abs(T.dot(c,l))>.99&&(l=T.fromValues(0,1,0));let u=T.create();T.cross(u,l,c),T.normalize(u,u);let d=T.create();T.cross(d,c,u);let f=[];for(let p=0;p<16;p++){let y=p/16*Math.PI*2,v=Math.cos(y)*n,b=Math.sin(y)*n,x=T.clone(s);T.scaleAndAdd(x,x,u,v),T.scaleAndAdd(x,x,d,b),f.push(x)}let h=T.clone(c);T.scale(h,h,-1);let m=cr(h),g=r;for(let p=0;p<16;p++){let y=cr(f[p]),v=cr(f[(p+1)%16]);this.addTriangle(g,v,y,m,i)}for(let p=0;p<16;p++){let y=f[p],v=f[(p+1)%16],b=cr(y),x=cr(v),_=T.create();T.subtract(_,v,y);let w=T.create();T.subtract(w,o,y);let S=T.create();T.cross(S,_,w),T.normalize(S,S);let A=cr(S);this.addTriangle(b,x,e,A,i)}}addTorus(e,r,n,i,a={x:0,y:0,z:1}){let c=Sc(a);T.normalize(c,c);let l=Sc(e),u=T.fromValues(0,0,1),d=F.create();if(Math.abs(T.dot(c,u))>.999)c[2]<0&&F.rotateX(d,d,Math.PI);else{let m=T.create();T.cross(m,u,c),T.normalize(m,m);let g=Math.acos(T.dot(u,c));F.fromRotation(d,g,m)}let f=[],h=[];for(let m=0;m<=16;m++){let g=m/16*Math.PI*2,p=Math.cos(g),y=Math.sin(g),v=[],b=[];for(let x=0;x<=8;x++){let _=x/8*Math.PI*2,w=Math.cos(_),S=Math.sin(_),A=(r+n*w)*p,L=(r+n*w)*y,M=n*S,P=T.fromValues(A,L,M),I=w*p,D=w*y,B=S,O=T.fromValues(I,D,B);T.transformMat4(P,P,d),T.transformMat4(O,O,d),T.add(P,P,l),v.push(P),b.push(O)}f.push(v),h.push(b)}for(let m=0;m<16;m++)for(let g=0;g<8;g++){let p=f[m][g],y=f[m+1][g],v=f[m+1][g+1],b=f[m][g+1],x=cr(p),_=cr(y),w=cr(v),S=cr(b),A=T.create();T.subtract(A,y,p);let L=T.create();T.subtract(L,v,p);let M=T.create();T.cross(M,A,L),T.normalize(M,M),this.addTriangle(x,_,w,cr(M),i);let P=T.create();T.subtract(P,v,p);let I=T.create();T.subtract(I,b,p);let D=T.create();T.cross(D,P,I),T.normalize(D,D),this.addTriangle(x,w,S,cr(D),i)}}render(e,r=!1){if(r&&this.gl.disable(this.gl.DEPTH_TEST),this.vertices.length>0){this.shader.use();let n=this.shader.getUniformLocation("u_viewProjection");n&&this.gl.uniformMatrix4fv(n,!1,e),this.vbo.upload(new Float32Array(this.vertices)),this.vao.bind(),this.gl.drawArrays(this.gl.LINES,0,this.vertices.length/6)}if(this.solidVertices.length>0){this.shaderSolid.use();let n=this.shaderSolid.getUniformLocation("u_viewProjection");n&&this.gl.uniformMatrix4fv(n,!1,e);let i=this.shaderSolid.getUniformLocation("u_lightingEnabled");i&&this.gl.uniform1i(i,1),this.vboSolid.upload(new Float32Array(this.solidVertices)),this.vaoSolid.bind(),this.gl.drawArrays(this.gl.TRIANGLES,0,this.solidVertices.length/9)}r&&this.gl.enable(this.gl.DEPTH_TEST)}getLabels(e,r,n){let i=[];for(let a of this.labels){let o=Aa.fromValues(a.position.x,a.position.y,a.position.z,1),s=Aa.create(),l=e,u=o[0],d=o[1],f=o[2],h=o[3];if(s[0]=l[0]*u+l[4]*d+l[8]*f+l[12]*h,s[1]=l[1]*u+l[5]*d+l[9]*f+l[13]*h,s[2]=l[2]*u+l[6]*d+l[10]*f+l[14]*h,s[3]=l[3]*u+l[7]*d+l[11]*f+l[15]*h,s[3]>0){let m=s[0]/s[3],g=s[1]/s[3],p=(m+1)*.5*r,y=(1-g)*.5*n;p>=0&&p<=r&&y>=0&&y<=n&&i.push({text:a.text,x:p,y})}}return i}clear(){this.vertices=[],this.solidVertices=[],this.labels=[]}};function Mc(t,e,r,n=32){let i=[];for(let s of t){let c=!0;for(let l of e)if(l.normal.x*s.origin.x+l.normal.y*s.origin.y+l.normal.z*s.origin.z+l.distance<-s.intensity){c=!1;break}if(c){let l=0;if(r){let u=s.origin.x-r.x,d=s.origin.y-r.y,f=s.origin.z-r.z;l=u*u+d*d+f*f}i.push({light:s,distSq:l})}}r&&i.sort((s,c)=>s.distSq-c.distSq);let a=[],o=Math.min(i.length,n);for(let s=0;s<o;s++)a.push(i[s].light);return a}function Zd(t){let e=(t*1664525+1013904223>>>0)/4294967296,r=(t*25214903917+11>>>0)/4294967296,n=(t*69069+1>>>0)/4294967296;return[e,r,n,1]}var hp=t=>{let e=new va(t),r=new _a(t),n=new Ma(t),i=new Pa(t),a=new Ba(t),o=new xc(t),s=new wc(t),c=new vc(t),l=new jf({seed:Date.now()}),u=new Ra(4096,l),d=new Ca(t,u),f=e.shaderSize+r.shaderSize+n.shaderSize+i.shaderSize+a.shaderSize+o.shaderSize+s.shaderSize+d.shaderSize;c.trackShaderMemory(f);let h=new Map,m=new Map,g=new Map,p=new Map,y=0,v=600,b=300,x=null,_={drawCalls:0,vertexCount:0,batches:0,shaderSwitches:0,visibleSurfaces:0,culledSurfaces:0,visibleEntities:0,culledEntities:0},w=new Map,S=new Map,A=0,L=1,M=1,P=!1,I=0,D=new Map,B=!1,O=!1,Q=.5,Ge=1,me=new Array(1024).fill(!0),Me=up(t,e,r),ge=1e4,ue=[],ye=0,Ve=pc.create(),ct=T.create(),qt=T.create();for(let E=0;E<ge;E++){let $={id:-1,model:void 0,transform:new Float32Array(16),type:"md3",blend:{frame0:0,frame1:0,lerp:0},tint:[1,1,1,1],lighting:{ambient:[.5,.5,.5],dynamicLights:[],modelMatrix:void 0}};$.lighting&&($.lighting.modelMatrix=$.transform),ue.push($)}let ut=[],He,$r,k,se=(E,$)=>{if(E.type==="md2"){let ae=E.model;if(!ae.lods||ae.lods.length===0)return{model:E.model,type:E.type};let de=E.transform[12]-$.x,ne=E.transform[13]-$.y,ve=E.transform[14]-$.z,tt=Math.sqrt(de*de+ne*ne+ve*ve),Nt=Math.floor(tt*Ge/500);if(Nt<=0)return{model:E.model,type:E.type};let Ue=ae.lods,jt=Math.min(Nt-1,Ue.length-1);return{model:Ue[jt],type:E.type}}return{model:E.model,type:E.type}},ke=(E,$,ae)=>{c.startFrame(),y++;let de=ut.length>0?[...$,...ut]:$;ut.length=0,ye=0,E.deltaTime&&u.update(E.deltaTime),t.disable(t.BLEND),t.enable(t.DEPTH_TEST),t.depthMask(!0);let ve=E.renderMode,tt=!1;ae?.wireframe||A===6?ve={mode:"wireframe",applyToAll:!0,color:[1,1,1,1]}:A===5&&(tt=!0);let Nt=E.sky;ae?.showSkybox===!1&&(Nt=void 0);let Ue=new Float32Array(E.camera.viewProjectionMatrix),jt=sr(Ue),Gt=E.dlights?Mc(E.dlights,jt,{x:E.camera.position[0],y:E.camera.position[1],z:E.camera.position[2]},32):void 0,ja={...E,sky:Nt,renderMode:ve,disableLightmaps:ae?.showLightmaps===!1&&A!==5,dlights:Gt,lightmapOnly:tt,brightness:L,gamma:M,fullbright:P,ambient:I,lightStyleOverrides:D,underwaterWarp:B,bloom:O,bloomIntensity:Q,portalState:me},Ks=Me.renderFrame(ja),Vf=Ks.facesDrawn||0,Hf=0;E.world&&E.world.map&&E.world.map.faces&&(Hf=E.world.map.faces.length);let ag=Hf-Vf,lu=-1,cu=-1,uu=null;if(E.world&&ae?.cullingEnabled!==!1){let z={x:E.camera.position[0],y:E.camera.position[1],z:E.camera.position[2]},We=Li(E.world.map,z);if(We>=0){let _t=E.world.map.leafs[We];lu=_t.cluster,cu=_t.area,cu>=0&&E.world.map.areas.length>0&&(uu=gd(E.world.map,cu,me))}}let Ys,Qa=0,du=0,Wf=0,qs=0,og={x:E.camera.position[0],y:E.camera.position[1],z:E.camera.position[2]};if(y%v===0)for(let[z,We]of p)y-We.lastFrameSeen>b&&p.delete(z);for(let z of de){if(E.world&&lu>=0){let J={x:z.transform[12],y:z.transform[13],z:z.transform[14]},N=-1;if(z.id!==void 0){let q=p.get(z.id);q&&q.position[12]===z.transform[12]&&q.position[13]===z.transform[13]&&q.position[14]===z.transform[14]?(N=q.leafIndex,q.lastFrameSeen=y):(N=Li(E.world.map,J),N>=0&&p.set(z.id,{leafIndex:N,position:new Float32Array(z.transform),lastFrameSeen:y}))}else N=Li(E.world.map,J);if(N>=0){let q=E.world.map.leafs[N],Qt=q.cluster,$e=q.area;if(uu&&$e>=0&&!uu.has($e)){qs++;continue}if(!pd(E.world.map.visibility,lu,Qt)){qs++;continue}}}let{model:We,type:_t}=se(z,og),Xe,Ee;if(_t==="md2"){let J=We,N=J.frames[z.blend.frame0%J.frames.length],q=J.frames[z.blend.frame1%J.frames.length];N&&q&&(Xe={x:Math.min(N.minBounds.x,q.minBounds.x),y:Math.min(N.minBounds.y,q.minBounds.y),z:Math.min(N.minBounds.z,q.minBounds.z)},Ee={x:Math.max(N.maxBounds.x,q.maxBounds.x),y:Math.max(N.maxBounds.y,q.maxBounds.y),z:Math.max(N.maxBounds.z,q.maxBounds.z)})}else if(_t==="md3"){let J=We,N=J.frames[z.blend.frame0%J.frames.length],q=J.frames[z.blend.frame1%J.frames.length];N&&q?(Xe={x:Math.min(N.minBounds.x,q.minBounds.x),y:Math.min(N.minBounds.y,q.minBounds.y),z:Math.min(N.minBounds.z,q.minBounds.z)},Ee={x:Math.max(N.maxBounds.x,q.maxBounds.x),y:Math.max(N.maxBounds.y,q.maxBounds.y),z:Math.max(N.maxBounds.z,q.maxBounds.z)}):(Xe={x:-32,y:-32,z:-32},Ee={x:32,y:32,z:32})}if(Xe&&Ee){let J=hm(Xe,Ee,z.transform);if(!Ei(J.mins,J.maxs,jt)){qs++;continue}}Wf++;let hr={x:z.transform[12],y:z.transform[13],z:z.transform[14]},rt=dp(E.world?.map,hr),Fe=z.id!==void 0?w.get(z.id):void 0;switch(_t){case"md2":{let J=We,N=m.get(J);if(N)N.update(J,z.blend);else{N=new wa(t,J,z.blend),m.set(J,N);let Ke=N.geometry.vertices.length*8*4,pn=N.geometry.indices.length*2;c.trackBufferMemory(Ke+pn)}let q=gu(Ue,z.transform),Qt=z.skin,$e=Qt?E.world?.textures?.get(Qt):void 0;$e&&$e!==Ys&&($e.bind(0),Ys=$e);let Jt=ve;if(Jt&&!Jt.applyToAll&&$e&&(Jt=void 0),Jt?.generateRandomColor&&z.id!==void 0){let Ke=Zd(z.id);Jt={...Jt,color:Ke}}if(n.bind({modelViewProjection:q,modelMatrix:z.transform,ambientLight:rt,dlights:E.dlights,renderMode:Jt,tint:z.tint,brightness:L,gamma:M,fullbright:P,ambient:I}),n.draw(N,Jt),Qa++,du+=N.geometry.vertices.length,Fe){let Ke={mode:"wireframe",applyToAll:!0,color:Fe};n.bind({modelViewProjection:q,modelMatrix:z.transform,ambientLight:1,renderMode:Ke,tint:[1,1,1,1],brightness:1,gamma:1,fullbright:!0,ambient:0}),n.draw(N,Ke),Qa++}}break;case"md3":{let J=We,N=h.get(J),q=z,Qt=E.dlights?E.dlights.map(Ke=>({origin:Ke.origin,color:[Ke.color.x,Ke.color.y,Ke.color.z],radius:Ke.intensity})):void 0,$e={...q.lighting,ambient:[rt,rt,rt],dynamicLights:Qt,modelMatrix:z.transform};N?N.update(z.blend,$e):(N=new Ta(t,J,z.blend,$e),h.set(J,N));let Jt=gu(Ue,z.transform);i.bind(Jt);for(let Ke of J.surfaces){let pn=N.surfaces.get(Ke.name);if(pn){let $f=q.skins?.get(Ke.name),Ja=$f?E.world?.textures?.get($f):void 0;Ja&&Ja!==Ys&&(Ja.bind(0),Ys=Ja);let ti=ve;if(ti&&!ti.applyToAll&&Ja&&(ti=void 0),ti?.generateRandomColor&&z.id!==void 0){let Kf=Zd(z.id);ti={...ti,color:Kf}}let sg={renderMode:ti,brightness:L,gamma:M,fullbright:P,globalAmbient:I};if(i.drawSurface(pn,sg),Qa++,du+=pn.geometry.vertices.length,Fe){let lg={renderMode:{mode:"wireframe",applyToAll:!0,color:Fe},brightness:1,gamma:1,fullbright:!0,globalAmbient:0};i.drawSurface(pn,lg),Qa++}}}}break}}let ei=E.camera.viewMatrix;if(ei){let z={x:ei[0],y:ei[4],z:ei[8]},We={x:ei[1],y:ei[5],z:ei[9]};d.render({viewProjection:Ue,viewRight:z,viewUp:We})}if(ja.waterTint&&(He(),k(0,0,t.canvas.width,t.canvas.height,ja.waterTint),$r()),o.render(Ue),o.clear(),E.world&&(S.size>0||A===3)){let z=new Map(S);if(A===3&&E.world){let We=sr(Ue),_t={x:E.camera.position[0],y:E.camera.position[1],z:E.camera.position[2]},Xe=cn(E.world.map,_t,We,me);for(let{faceIndex:Ee,leafIndex:hr}of Xe){let rt=E.world.map.leafs[hr];rt&&!z.has(Ee)&&z.set(Ee,Zd(rt.cluster))}}for(let[We,_t]of z){let Xe=E.world.surfaces[We];if(Xe&&Xe.vertexCount>0){let Ee=[];for(let Fe=0;Fe<Xe.vertexCount;Fe++)Ee.push({x:Xe.vertexData[Fe*7],y:Xe.vertexData[Fe*7+1],z:Xe.vertexData[Fe*7+2]});let rt={r:_t[0],g:_t[1],b:_t[2]};for(let Fe=0;Fe<Ee.length;Fe++){let J=Ee[Fe],N=Ee[(Fe+1)%Ee.length];s.drawLine(J,N,rt)}s.drawLine(Ee[0],Ee[Ee.length/2|0],rt)}}}if((ae?.showNormals||A===2)&&E.world){let z=sr(Ue),We={x:E.camera.position[0],y:E.camera.position[1],z:E.camera.position[2]},_t=cn(E.world.map,We,z,me);for(let{faceIndex:Xe}of _t){let Ee=E.world.map.faces[Xe],hr=E.world.map.planes[Ee.planeIndex],rt=E.world.surfaces[Xe];if(!rt)continue;let Fe=0,J=0,N=0,q=rt.vertexCount;for(let Qt=0;Qt<q;Qt++){let $e=Qt*7;Fe+=rt.vertexData[$e],J+=rt.vertexData[$e+1],N+=rt.vertexData[$e+2]}if(q>0){Fe/=q,J/=q,N/=q;let Qt=Ee.side===0?hr.normal[0]:-hr.normal[0],$e=Ee.side===0?hr.normal[1]:-hr.normal[1],Jt=Ee.side===0?hr.normal[2]:-hr.normal[2],Ke={x:Fe,y:J,z:N},pn={x:Fe+Qt*8,y:J+$e*8,z:N+Jt*8};s.drawLine(Ke,pn,{r:1,g:1,b:0})}}}s.render(Ue);let Xf=s.getLabels(Ue,t.canvas.width,t.canvas.height);if(Xf.length>0){He();for(let z of Xf)vt(z.x,z.y,z.text,[1,1,1,1]);$r()}s.clear(),_={drawCalls:Ks.drawCalls+Qa,vertexCount:Ks.vertexCount+du,batches:Ks.batches,shaderSwitches:0,visibleSurfaces:Vf,culledSurfaces:ag,visibleEntities:Wf,culledEntities:qs},c.endFrame()},De=async(E,$)=>{if(g.has(E))return g.get(E);let ae=new Blob([$]),de=await createImageBitmap(ae),ne=new lt(t);return ne.upload(de.width,de.height,de),g.set(E,ne),c.trackTextureMemory(de.width*de.height*4),E.includes("conchars")&&(x=ne),ne},fr=(E,$)=>{if(g.has(E))return g.get(E);let ae=new lt(t),de=$.levels[0];return ae.upload(de.width,de.height,de.rgba),g.set(E,ae),c.trackTextureMemory(de.width*de.height*4),E.includes("conchars")&&(x=ae),ae},Zt=E=>g.get(E);He=()=>{t.enable(t.BLEND),t.blendFunc(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA),t.disable(t.DEPTH_TEST),t.depthMask(!1);let E=F.create();F.ortho(E,0,t.canvas.width,t.canvas.height,0,-1,1),a.begin(E)},$r=()=>{t.disable(t.BLEND),t.enable(t.DEPTH_TEST),t.depthMask(!0)};let mn=(E,$,ae,de)=>{ae.bind(0),a.draw(E,$,ae.width,ae.height,0,0,1,1,de)},Hs=(E,$,ae,de)=>{if(!x)return;let ne=8,ve=8,tt=x.width/ne,Nt=ae&255,Ue=Nt%tt*ne/x.width,jt=Math.floor(Nt/tt)*ve/x.height,Gt=Ue+ne/x.width,ja=jt+ve/x.height;x.bind(0),a.draw(E,$,ne,ve,Ue,jt,Gt,ja,de)},vt=(E,$,ae,de)=>{let ne=_c(ae),ve=E,tt=8;for(let Nt of ne){let Ue=Nt.color||de;for(let jt=0;jt<Nt.text.length;jt++)Hs(ve,$,Nt.text.charCodeAt(jt),Ue),ve+=tt}},Ws=(E,$)=>{let ne=$.replace(/\^[0-9]/g,"").length*8,ve=(t.canvas.width-ne)/2;vt(ve,E,$)};return k=(E,$,ae,de,ne)=>{a.drawRect(E,$,ae,de,ne)},{get width(){return t.canvas.width},get height(){return t.canvas.height},get collisionVis(){return o},get debug(){return s},get particleSystem(){return u},getPerformanceReport:()=>c.getPerformanceReport(_),getMemoryUsage:()=>c.getMemoryUsage(),renderFrame:ke,registerPic:De,registerTexture:fr,getTexture:Zt,begin2D:He,end2D:$r,drawPic:mn,drawString:vt,drawCenterString:Ws,drawfillRect:k,setEntityHighlight:(E,$)=>{w.set(E,$)},clearEntityHighlight:E=>{w.delete(E)},highlightSurface:(E,$)=>{S.set(E,$)},removeSurfaceHighlight:E=>{S.delete(E)},setDebugMode:E=>{A=E},setBrightness:E=>{L=Math.max(0,Math.min(2,E))},setGamma:E=>{M=Math.max(.5,Math.min(3,E))},setFullbright:E=>{P=E},setAmbient:E=>{I=Math.max(0,Math.min(1,E))},setLightStyle:(E,$)=>{$===null?D.delete(E):D.set(E,$)},setUnderwaterWarp:E=>{B=E},setBloom:E=>{O=E},setBloomIntensity:E=>{Q=E},setLodBias:E=>{Ge=Math.max(0,Math.min(2,E))},setAreaPortalState:(E,$)=>{E>=0&&E<me.length&&(me[E]=$)},renderInstanced:(E,$)=>{let ae="glCommands"in E,de=ae?"md2":"md3";for(let ne of $){if(ye>=ge){console.warn("Max instances reached");break}let ve=ue[ye++];ve.model=E,ve.type=de;let tt=ve.blend;ne.frame!==void 0?(tt.frame0=ne.frame,tt.frame1=ne.frame,tt.lerp=0):(tt.frame0=ne.frame0||0,tt.frame1=ne.frame1||0,tt.lerp=ne.lerp||0),ae&&(ve.skin=ne.skin!==void 0?"skin"+ne.skin:void 0);let Nt=ne.rotation,Ue=ne.position,jt=ne.scale||{x:1,y:1,z:1};F.fromRotationTranslationScale(ve.transform,Ve,ct,qt);let Gt=ve.lighting;Gt&&(Gt.dynamicLights?Gt.dynamicLights.length=0:Gt.dynamicLights=[],Gt.ambient?(Gt.ambient[0]=.5,Gt.ambient[1]=.5,Gt.ambient[2]=.5):Gt.ambient=[.5,.5,.5]),ut.push(ve)}},uploadBspGeometry:E=>{let $=oc(E);return sc(t,$,E)},dispose:()=>{c.dispose()}}};async function Ac(t,e){if(!navigator.gpu)throw new Error("WebGPU is not supported in this environment");let r=await navigator.gpu.requestAdapter({powerPreference:e?.powerPreference||"high-performance"});if(!r)throw new Error("No appropriate GPUAdapter found");if(e?.requiredFeatures){for(let f of e.requiredFeatures)if(!r.features.has(f))throw new Error(`Required feature not available: ${f}`)}let n={requiredFeatures:e?.requiredFeatures,requiredLimits:e?.requiredLimits},i=await r.requestDevice(n),a,o="rgba8unorm",s="depth24plus",c=!0,l=e?.width||800,u=e?.height||600;if(t){if(a=t.getContext("webgpu"),!a)throw new Error("Failed to get WebGPU context from canvas");c=!1,o=navigator.gpu.getPreferredCanvasFormat(),l=t.width,u=t.height,a.configure({device:i,format:o,alphaMode:"opaque"})}let d=new Set;for(let f of r.features)d.add(f);return{adapter:r,device:i,context:a,format:o,depthFormat:s,features:d,limits:i.limits,isHeadless:c,width:l,height:u}}function mp(t){let{features:e,limits:r}=t;return{hasTimestampQuery:e.has("timestamp-query"),hasDepthClipControl:e.has("depth-clip-control"),hasTextureCompressionBC:e.has("texture-compression-bc"),hasTextureCompressionETC2:e.has("texture-compression-etc2"),hasTextureCompressionASTC:e.has("texture-compression-astc"),maxTextureDimension2D:r.maxTextureDimension2D,maxBindGroups:r.maxBindGroups,maxUniformBufferBindingSize:r.maxUniformBufferBindingSize,maxStorageBufferBindingSize:r.maxStorageBufferBindingSize}}var f_=!0;function h_(t,e){if(!t)return 1;let r=Math.floor(e*10)%t.length;return(t.charCodeAt(r)-97)/12}function m_(t){return[...t].sort((e,r)=>r.sortKey-e.sortKey)}function p_(t){return[...t].sort((e,r)=>e.sortKey-r.sortKey)}var Ec=class{constructor(e,r){this.context=e;this.pipelines=r;this.depthTexture=null;this.copyTexture=null;this.headlessTarget=null;this.lastWidth=0;this.lastHeight=0;this.lastFrameTime=0;this.currentFrameContext=null}ensureDepthTexture(e,r){return this.depthTexture&&this.lastWidth===e&&this.lastHeight===r?this.depthTexture.createView():(this.depthTexture&&this.depthTexture.destroy(),this.depthTexture=this.context.device.createTexture({size:[e,r],format:"depth24plus",usage:GPUTextureUsage.RENDER_ATTACHMENT,label:"depth-buffer"}),this.copyTexture&&(this.copyTexture.destroy(),this.copyTexture=null),this.lastWidth=e,this.lastHeight=r,this.depthTexture.createView())}ensureCopyTexture(e,r){return this.copyTexture&&this.lastWidth===e&&this.lastHeight===r?this.copyTexture:(this.copyTexture&&this.copyTexture.destroy(),this.copyTexture=this.context.device.createTexture({size:[e,r],format:this.context.format,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT,label:"frame-copy-texture"}),this.copyTexture)}ensureHeadlessTarget(e,r){return this.headlessTarget&&this.headlessTarget.width===e&&this.headlessTarget.height===r?this.headlessTarget.createView():(this.headlessTarget&&this.headlessTarget.destroy(),this.headlessTarget=this.context.device.createTexture({size:[e,r],format:this.context.format,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC|GPUTextureUsage.TEXTURE_BINDING,label:"headless-render-target"}),this.headlessTarget.createView())}beginFrame(){let{device:e,context:r,width:n,height:i}=this.context,a=e.createCommandEncoder({label:"frame-command-encoder"}),o;r?o=r.getCurrentTexture().createView():o=this.ensureHeadlessTarget(n,i);let s=this.ensureDepthTexture(n,i);return{device:e,commandEncoder:a,renderTarget:o,depthTexture:s,width:n,height:i}}begin2DPass(){if(!this.currentFrameContext)throw new Error("begin2DPass called outside of renderFrame");let{commandEncoder:e,renderTarget:r,width:n,height:i}=this.currentFrameContext;this.pipelines.sprite.setProjection(n,i),this.pipelines.sprite.begin(e,r)}end2DPass(){this.pipelines.sprite.end()}renderFrame(e){let r=performance.now(),n=this.lastFrameTime>0?1e3/(r-this.lastFrameTime):0;this.lastFrameTime=r;let i={batches:0,facesDrawn:0,drawCalls:0,skyDrawn:!1,viewModelDrawn:!1,fps:Math.round(n),vertexCount:0},a=this.beginFrame();this.currentFrameContext=a;let{commandEncoder:o,renderTarget:s,depthTexture:c}=a,{clearColor:l=[0,0,0,1],world:u,camera:d,timeSeconds:f=0,dlights:h,renderMode:m,disableLightmaps:g,lightmapOnly:p,brightness:y,gamma:v,fullbright:b,ambient:x,lightStyleOverrides:_,portalState:w}=e,S=new Float32Array(e.camera.viewProjectionMatrix),A={colorAttachments:[{view:s,clearValue:l,loadOp:"clear",storeOp:"store"}],depthStencilAttachment:{view:c,depthClearValue:1,depthLoadOp:"clear",depthStoreOp:"store"},label:"opaque-render-pass"},L=o.beginRenderPass(A);if(e.sky&&e.sky.cubemap){if(f_){let I=e.cameraState??e.camera.toState(),D=Ti(e.timeSeconds??0,e.sky.scrollSpeeds??[.01,.02]);this.pipelines.skybox.draw(L,{cameraState:I,scroll:D,cubemap:e.sky.cubemap})}else{let I=Sa(e.camera.viewMatrix),D=F.create();F.multiply(D,e.camera.projectionMatrix,I);let B=Ti(e.timeSeconds??0,e.sky.scrollSpeeds??[.01,.02]);this.pipelines.skybox.draw(L,{viewProjection:D,scroll:B,cubemap:e.sky.cubemap})}i.skyDrawn=!0}let M=[],P=[];if(u){u.materials?.update(f);let I=sr(Array.from(S)),D={x:d.position[0]??0,y:d.position[1]??0,z:d.position[2]??0},B=cn(u.map,D,I,w);for(let ge of B){let ue=u.surfaces[ge.faceIndex];if(!ue)continue;(ue.surfaceFlags&(xn|vn|Yr))!==0?P.push(ge):M.push(ge)}let O=m_(M),Q=u.lightStyles||[];if(_&&_.size>0){let ge=[...u.lightStyles||[]];for(let[ue,ye]of _){for(;ge.length<=ue;)ge.push(1);ge[ue]=h_(ye,f)}Q=ge}let Ge=(ge,ue,ye)=>{for(let{faceIndex:Ve}of ge){let ct=u.surfaces[Ve];if(!ct||(ct.surfaceFlags&bn)!==0)continue;let qt=u.map.faces[Ve]?.styles;this.pipelines.bsp.bind(ue,{modelViewProjection:S,styleIndices:qt,styleValues:ye,surfaceFlags:ct.surfaceFlags,timeSeconds:f,dlights:h,renderMode:m,lightmapOnly:p,brightness:y,gamma:v,fullbright:b,ambient:x,cameraPosition:e.camera.position}),this.pipelines.bsp.draw(ue,ct,m),i.facesDrawn++,i.drawCalls++,i.vertexCount+=ct.vertexCount}};Ge(O,L,Q),L.end();let me={colorAttachments:[{view:s,loadOp:"load",storeOp:"store"}],depthStencilAttachment:{view:c,depthLoadOp:"load",depthStoreOp:"store"},label:"transparent-render-pass"},Me=o.beginRenderPass(me);if(P.length>0){let ge=p_(P);Ge(ge,Me,Q)}Me.end()}else L.end();return e.underwaterWarp||e.bloom,e.onDraw2D&&e.onDraw2D(),this.pipelines.sprite.isActive&&(console.warn("2D render pass was not properly closed - auto-closing to prevent resource leak"),this.end2DPass()),this.context.device.queue.submit([o.finish()]),this.currentFrameContext=null,i}};var pp=`
796
801
  struct VSOutput {
797
802
  @builtin(position) position: vec4f,
798
803
  @location(0) texcoord: vec2f,
@@ -822,7 +827,7 @@ fn vs_main(@builtin(vertex_index) vertexIndex : u32) -> VSOutput {
822
827
  fn fs_main(in: VSOutput) -> @location(0) vec4f {
823
828
  return textureSample(img, imgSampler, in.texcoord);
824
829
  }
825
- `;var Tc;var Fa=class{constructor(e,r){this.device=e;this.size=Math.ceil(r.size/4)*4,this.usage=r.usage,this.buffer=e.createBuffer({size:this.size,usage:this.usage,label:r.label,mappedAtCreation:r.mappedAtCreation}),Tc?.trackBuffer(this)}write(e,r=0){let n=e.byteLength;if(r+n>this.size)throw new Error(`Buffer write out of bounds: offset ${r} + data ${n} > buffer ${this.size}`);this.device.queue.writeBuffer(this.buffer,r,e,0)}async mapAsync(e,r=0,n){await this.buffer.mapAsync(e,r,n)}getMappedRange(e=0,r){return this.buffer.getMappedRange(e,r)}unmap(){this.buffer.unmap()}destroy(){Tc?.untrackBuffer(this),this.buffer.destroy()}},Ia=class extends Fa{constructor(e,r){super(e,{size:r.size,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST|(r.usage||0),label:r.label})}},Da=class extends Fa{constructor(e,r){super(e,{size:r.size,usage:GPUBufferUsage.INDEX|GPUBufferUsage.COPY_DST|(r.usage||0),label:r.label})}},Lc=class extends Fa{constructor(e,r){super(e,{size:r.size,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST|(r.usage||0),label:r.label})}};function gp(t){switch(t){case"rgba8unorm":case"rgba8unorm-srgb":case"bgra8unorm":case"bgra8unorm-srgb":case"rgba8sint":case"rgba8uint":return 4;case"rg8unorm":case"rg8sint":case"rg8uint":case"r16float":case"r16sint":case"r16uint":return 2;case"r8unorm":case"r8sint":case"r8uint":return 1;case"rgba16float":case"rgba16sint":case"rgba16uint":case"rgba32float":return 8;case"rgba32float":case"rgba32sint":case"rgba32uint":return 16;case"depth24plus":case"depth24plus-stencil8":case"depth32float":return 4;default:return 4}}var Xn=class Xn{constructor(e,r){this.device=e;this.width=r.width,this.height=r.height,this.format=r.format;let n=r.usage??GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT;this.texture=e.createTexture({size:[this.width,this.height,1],format:this.format,usage:n,mipLevelCount:r.mipLevelCount??1,label:r.label}),Tc?.trackTexture(this)}upload(e,r={}){let n=r.width??this.width,i=r.height??this.height,a=r.depthOrArrayLayers??1,o=r.mipLevel??0,s=gp(this.format),c=r.bytesPerRow;c||(c=n*s),this.device.queue.writeTexture({texture:this.texture,mipLevel:o,origin:{x:0,y:0,z:0}},e,{offset:0,bytesPerRow:c,rowsPerImage:r.rowsPerImage??i},{width:n,height:i,depthOrArrayLayers:a})}getMipmapPipeline(e){let r=Xn.mipmapPipelines.get(this.device);r||(r=new Map,Xn.mipmapPipelines.set(this.device,r));let n=r.get(e);if(!n){let i=this.device.createShaderModule({code:pp,label:"mipmap-shader"});n=this.device.createRenderPipeline({layout:"auto",vertex:{module:i,entryPoint:"vs_main"},fragment:{module:i,entryPoint:"fs_main",targets:[{format:e}]},primitive:{topology:"triangle-list"},label:`mipmap-pipeline-${e}`}),r.set(e,n)}return n}getMipmapSampler(){let e=Xn.mipmapSamplers.get(this.device);return e||(e=this.device.createSampler({minFilter:"linear",magFilter:"linear",label:"mipmap-sampler"}),Xn.mipmapSamplers.set(this.device,e)),e}generateMipmaps(e){let r=this.texture.mipLevelCount;if(r<=1)return;let n=this.getMipmapPipeline(this.format),i=this.getMipmapSampler();for(let a=1;a<r;a++){let o=this.texture.createView({baseMipLevel:a-1,mipLevelCount:1,label:`mipmap-src-${a-1}`}),s=this.texture.createView({baseMipLevel:a,mipLevelCount:1,label:`mipmap-dst-${a}`}),c=e.beginRenderPass({colorAttachments:[{view:s,loadOp:"clear",storeOp:"store"}],label:`mipmap-pass-${a}`}),l=this.device.createBindGroup({layout:n.getBindGroupLayout(0),entries:[{binding:0,resource:i},{binding:1,resource:o}],label:`mipmap-bindgroup-${a}`});c.setPipeline(n),c.setBindGroup(0,l),c.draw(6),c.end()}}createView(e){return this.texture.createView(e)}destroy(){Tc?.untrackTexture(this),this.texture.destroy()}get memorySize(){let e=gp(this.format),r=0,n=this.width,i=this.height,a=this.texture.mipLevelCount;for(let o=0;o<a;o++)r+=n*i*e,n=Math.max(1,Math.floor(n/2)),i=Math.max(1,Math.floor(i/2));return r}};Xn.mipmapPipelines=new WeakMap,Xn.mipmapSamplers=new WeakMap;var $n=Xn;var Pc=class{constructor(e,r){this.sampler=e.createSampler({...r,label:r.label})}destroy(){}};function Cc(t){return new Pc(t,{minFilter:"linear",magFilter:"linear",mipmapFilter:"linear",label:"linear-sampler"})}var Rc=class{constructor(e,r){this.device=e;this.module=e.createShaderModule({code:r.code,label:r.label})}get compilationInfo(){return this.module.getCompilationInfo()}},ys=class{constructor(e,r){this.device=e;let n=r.layout;this.pipeline=e.createRenderPipeline({layout:n,vertex:{module:r.vertex.module.module,entryPoint:r.vertex.entryPoint,buffers:r.vertex.buffers},fragment:r.fragment?{module:r.fragment.module.module,entryPoint:r.fragment.entryPoint,targets:r.fragment.targets}:void 0,primitive:r.primitive,depthStencil:r.depthStencil,multisample:r.multisample,label:r.label})}get layout(){throw new Error("Cannot retrieve layout from pipeline created with 'auto' layout")}destroy(){}};var jd=class{constructor(e,r){this.device=e;this.layout=e.createBindGroupLayout({entries:r.entries,label:r.label})}},bs=class{constructor(e,r,n,i){this.device=e;let a=n.map(o=>{let s;return o.resource instanceof Fa?s={buffer:o.resource.buffer}:o.resource instanceof Pc?s=o.resource.sampler:s=o.resource,{binding:o.binding,resource:s}});this.bindGroup=e.createBindGroup({layout:r.layout,entries:a,label:i})}destroy(){}},xs=class{constructor(e){this.label=e;this.entries=[]}addUniformBuffer(e,r){return this.entries.push({binding:e,visibility:r,buffer:{type:"uniform"}}),this}addStorageBuffer(e,r,n="read-only-storage"){return this.entries.push({binding:e,visibility:r,buffer:{type:n}}),this}addTexture(e,r,n="float",i="2d"){return this.entries.push({binding:e,visibility:r,texture:{sampleType:n,viewDimension:i}}),this}addSampler(e,r,n="filtering"){return this.entries.push({binding:e,visibility:r,sampler:{type:n}}),this}build(e){return new jd(e,{entries:this.entries,label:this.label})}};var yp=`
830
+ `;var Lc;var Fa=class{constructor(e,r){this.device=e;this.size=Math.ceil(r.size/4)*4,this.usage=r.usage,this.buffer=e.createBuffer({size:this.size,usage:this.usage,label:r.label,mappedAtCreation:r.mappedAtCreation}),Lc?.trackBuffer(this)}write(e,r=0){let n=e.byteLength;if(r+n>this.size)throw new Error(`Buffer write out of bounds: offset ${r} + data ${n} > buffer ${this.size}`);this.device.queue.writeBuffer(this.buffer,r,e,0)}async mapAsync(e,r=0,n){await this.buffer.mapAsync(e,r,n)}getMappedRange(e=0,r){return this.buffer.getMappedRange(e,r)}unmap(){this.buffer.unmap()}destroy(){Lc?.untrackBuffer(this),this.buffer.destroy()}},Ia=class extends Fa{constructor(e,r){super(e,{size:r.size,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST|(r.usage||0),label:r.label})}},Da=class extends Fa{constructor(e,r){super(e,{size:r.size,usage:GPUBufferUsage.INDEX|GPUBufferUsage.COPY_DST|(r.usage||0),label:r.label})}},Tc=class extends Fa{constructor(e,r){super(e,{size:r.size,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST|(r.usage||0),label:r.label})}};function gp(t){switch(t){case"rgba8unorm":case"rgba8unorm-srgb":case"bgra8unorm":case"bgra8unorm-srgb":case"rgba8sint":case"rgba8uint":return 4;case"rg8unorm":case"rg8sint":case"rg8uint":case"r16float":case"r16sint":case"r16uint":return 2;case"r8unorm":case"r8sint":case"r8uint":return 1;case"rgba16float":case"rgba16sint":case"rgba16uint":case"rgba32float":return 8;case"rgba32float":case"rgba32sint":case"rgba32uint":return 16;case"depth24plus":case"depth24plus-stencil8":case"depth32float":return 4;default:return 4}}var Xn=class Xn{constructor(e,r){this.device=e;this.width=r.width,this.height=r.height,this.format=r.format;let n=r.usage??GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT;this.texture=e.createTexture({size:[this.width,this.height,1],format:this.format,usage:n,mipLevelCount:r.mipLevelCount??1,label:r.label}),Lc?.trackTexture(this)}upload(e,r={}){let n=r.width??this.width,i=r.height??this.height,a=r.depthOrArrayLayers??1,o=r.mipLevel??0,s=gp(this.format),c=r.bytesPerRow;c||(c=n*s),this.device.queue.writeTexture({texture:this.texture,mipLevel:o,origin:{x:0,y:0,z:0}},e,{offset:0,bytesPerRow:c,rowsPerImage:r.rowsPerImage??i},{width:n,height:i,depthOrArrayLayers:a})}getMipmapPipeline(e){let r=Xn.mipmapPipelines.get(this.device);r||(r=new Map,Xn.mipmapPipelines.set(this.device,r));let n=r.get(e);if(!n){let i=this.device.createShaderModule({code:pp,label:"mipmap-shader"});n=this.device.createRenderPipeline({layout:"auto",vertex:{module:i,entryPoint:"vs_main"},fragment:{module:i,entryPoint:"fs_main",targets:[{format:e}]},primitive:{topology:"triangle-list"},label:`mipmap-pipeline-${e}`}),r.set(e,n)}return n}getMipmapSampler(){let e=Xn.mipmapSamplers.get(this.device);return e||(e=this.device.createSampler({minFilter:"linear",magFilter:"linear",label:"mipmap-sampler"}),Xn.mipmapSamplers.set(this.device,e)),e}generateMipmaps(e){let r=this.texture.mipLevelCount;if(r<=1)return;let n=this.getMipmapPipeline(this.format),i=this.getMipmapSampler();for(let a=1;a<r;a++){let o=this.texture.createView({baseMipLevel:a-1,mipLevelCount:1,label:`mipmap-src-${a-1}`}),s=this.texture.createView({baseMipLevel:a,mipLevelCount:1,label:`mipmap-dst-${a}`}),c=e.beginRenderPass({colorAttachments:[{view:s,loadOp:"clear",storeOp:"store"}],label:`mipmap-pass-${a}`}),l=this.device.createBindGroup({layout:n.getBindGroupLayout(0),entries:[{binding:0,resource:i},{binding:1,resource:o}],label:`mipmap-bindgroup-${a}`});c.setPipeline(n),c.setBindGroup(0,l),c.draw(6),c.end()}}createView(e){return this.texture.createView(e)}destroy(){Lc?.untrackTexture(this),this.texture.destroy()}get memorySize(){let e=gp(this.format),r=0,n=this.width,i=this.height,a=this.texture.mipLevelCount;for(let o=0;o<a;o++)r+=n*i*e,n=Math.max(1,Math.floor(n/2)),i=Math.max(1,Math.floor(i/2));return r}};Xn.mipmapPipelines=new WeakMap,Xn.mipmapSamplers=new WeakMap;var $n=Xn;var Pc=class{constructor(e,r){this.sampler=e.createSampler({...r,label:r.label})}destroy(){}};function Cc(t){return new Pc(t,{minFilter:"linear",magFilter:"linear",mipmapFilter:"linear",label:"linear-sampler"})}var Rc=class{constructor(e,r){this.device=e;this.module=e.createShaderModule({code:r.code,label:r.label})}get compilationInfo(){return this.module.getCompilationInfo()}},ys=class{constructor(e,r){this.device=e;let n=r.layout;this.pipeline=e.createRenderPipeline({layout:n,vertex:{module:r.vertex.module.module,entryPoint:r.vertex.entryPoint,buffers:r.vertex.buffers},fragment:r.fragment?{module:r.fragment.module.module,entryPoint:r.fragment.entryPoint,targets:r.fragment.targets}:void 0,primitive:r.primitive,depthStencil:r.depthStencil,multisample:r.multisample,label:r.label})}get layout(){throw new Error("Cannot retrieve layout from pipeline created with 'auto' layout")}destroy(){}};var jd=class{constructor(e,r){this.device=e;this.layout=e.createBindGroupLayout({entries:r.entries,label:r.label})}},bs=class{constructor(e,r,n,i){this.device=e;let a=n.map(o=>{let s;return o.resource instanceof Fa?s={buffer:o.resource.buffer}:o.resource instanceof Pc?s=o.resource.sampler:s=o.resource,{binding:o.binding,resource:s}});this.bindGroup=e.createBindGroup({layout:r.layout,entries:a,label:i})}destroy(){}},xs=class{constructor(e){this.label=e;this.entries=[]}addUniformBuffer(e,r){return this.entries.push({binding:e,visibility:r,buffer:{type:"uniform"}}),this}addStorageBuffer(e,r,n="read-only-storage"){return this.entries.push({binding:e,visibility:r,buffer:{type:n}}),this}addTexture(e,r,n="float",i="2d"){return this.entries.push({binding:e,visibility:r,texture:{sampleType:n,viewDimension:i}}),this}addSampler(e,r,n="filtering"){return this.entries.push({binding:e,visibility:r,sampler:{type:n}}),this}build(e){return new jd(e,{entries:this.entries,label:this.label})}};var yp=`
826
831
  // Sprite Rendering Shader (WGSL)
827
832
 
828
833
  struct VertexInput {
@@ -866,7 +871,7 @@ fn fs_main(input: VertexOutput) -> @location(0) vec4f {
866
871
  fn fs_solid(input: VertexOutput) -> @location(0) vec4f {
867
872
  return input.color;
868
873
  }
869
- `;var ka=2048,Bc=4,bp=6,vs=8,Fc=class{constructor(e,r){this.device=e;this.format=r;this.currentVertexCount=0;this.currentIndexCount=0;this.currentTexture=null;this.drawCommands=[];this.textureBindGroups=new Map;this._activeEncoder=null;this._activeRenderTarget=null;let n=new Rc(e,{code:yp,label:"sprite-shader"}),i={arrayStride:vs*4,stepMode:"vertex",attributes:[{format:"float32x2",offset:0,shaderLocation:0},{format:"float32x2",offset:8,shaderLocation:1},{format:"float32x4",offset:16,shaderLocation:2}]},a=new xs("sprite-uniform-layout");a.addUniformBuffer(0,GPUShaderStage.VERTEX);let o=a.build(e),s=new xs("sprite-texture-layout");s.addSampler(0,GPUShaderStage.FRAGMENT),s.addTexture(1,GPUShaderStage.FRAGMENT),this.textureBindGroupLayout=s.build(e);let c=e.createPipelineLayout({bindGroupLayouts:[o.layout,this.textureBindGroupLayout.layout],label:"sprite-pipeline-layout"}),l=e.createPipelineLayout({bindGroupLayouts:[o.layout],label:"sprite-pipeline-solid-layout"}),u={color:{srcFactor:"src-alpha",dstFactor:"one-minus-src-alpha",operation:"add"},alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"}};this.pipelineTextured=new ys(e,{layout:c,vertex:{module:n,entryPoint:"vs_main",buffers:[i]},fragment:{module:n,entryPoint:"fs_main",targets:[{format:this.format,blend:u}]},primitive:{topology:"triangle-list",cullMode:"none"},label:"sprite-pipeline-textured"}),this.pipelineSolid=new ys(e,{layout:l,vertex:{module:n,entryPoint:"vs_main",buffers:[i]},fragment:{module:n,entryPoint:"fs_solid",targets:[{format:this.format,blend:u}]},primitive:{topology:"triangle-list",cullMode:"none"},label:"sprite-pipeline-solid"}),this.vertexBuffer=new Ia(e,{size:ka*Bc*vs*4,label:"sprite-vertex-buffer",usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}),this.indexBuffer=new Da(e,{size:ka*bp*2,label:"sprite-index-buffer",usage:GPUBufferUsage.INDEX|GPUBufferUsage.COPY_DST}),this.uniformBuffer=new Lc(e,{size:64,label:"sprite-uniform-buffer",usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this.uniformBindGroup=new bs(e,o,[{binding:0,resource:this.uniformBuffer}],"sprite-uniform-bind-group"),this.vertexData=new Float32Array(ka*Bc*vs);let d=new Uint16Array(ka*bp);for(let f=0;f<ka;f++){let h=f*4,m=f*6;d[m]=h,d[m+1]=h+1,d[m+2]=h+2,d[m+3]=h,d[m+4]=h+2,d[m+5]=h+3}this.indexBuffer.write(d),this.projectionMatrix=F.create(),this.defaultSampler=Cc(e)}setProjection(e,r){F.ortho(this.projectionMatrix,0,e,r,0,-1,1),this.uniformBuffer.write(this.projectionMatrix)}begin(e,r){this.currentVertexCount=0,this.currentIndexCount=0,this.drawCommands=[],this.currentTexture=null,this._activeEncoder=e,this._activeRenderTarget=r}drawTexturedQuad(e,r,n,i,a,o=0,s=0,c=1,l=1,u=[1,1,1,1]){this.currentVertexCount+Bc>ka*Bc&&this.flush(),(this.drawCommands.length===0||this.currentTexture!==a)&&(this.drawCommands.push({texture:a,start:this.currentIndexCount,count:0}),this.currentTexture=a);let d=this.currentVertexCount*vs,[f,h,m,g]=u;this.vertexData[d]=e,this.vertexData[d+1]=r,this.vertexData[d+2]=o,this.vertexData[d+3]=s,this.vertexData[d+4]=f,this.vertexData[d+5]=h,this.vertexData[d+6]=m,this.vertexData[d+7]=g,this.vertexData[d+8]=e,this.vertexData[d+9]=r+i,this.vertexData[d+10]=o,this.vertexData[d+11]=l,this.vertexData[d+12]=f,this.vertexData[d+13]=h,this.vertexData[d+14]=m,this.vertexData[d+15]=g,this.vertexData[d+16]=e+n,this.vertexData[d+17]=r+i,this.vertexData[d+18]=c,this.vertexData[d+19]=l,this.vertexData[d+20]=f,this.vertexData[d+21]=h,this.vertexData[d+22]=m,this.vertexData[d+23]=g,this.vertexData[d+24]=e+n,this.vertexData[d+25]=r,this.vertexData[d+26]=c,this.vertexData[d+27]=s,this.vertexData[d+28]=f,this.vertexData[d+29]=h,this.vertexData[d+30]=m,this.vertexData[d+31]=g,this.currentVertexCount+=4,this.currentIndexCount+=6,this.drawCommands[this.drawCommands.length-1].count+=6}drawSolidRect(e,r,n,i,a){this.currentTexture!==null&&(this.drawCommands.push({texture:null,start:this.currentIndexCount,count:0}),this.currentTexture=null),this.drawTexturedQuad(e,r,n,i,null,0,0,0,0,a)}flush(){if(this.currentVertexCount===0||!this._activeEncoder||!this._activeRenderTarget)return;let e=this.currentVertexCount*vs;this.vertexBuffer.write(this.vertexData.subarray(0,e));let r=this._activeEncoder.beginRenderPass({colorAttachments:[{view:this._activeRenderTarget,loadOp:"load",storeOp:"store"}],label:"sprite-pass"});r.setBindGroup(0,this.uniformBindGroup.bindGroup),r.setVertexBuffer(0,this.vertexBuffer.buffer),r.setIndexBuffer(this.indexBuffer.buffer,"uint16");for(let n of this.drawCommands)if(n.count!==0){if(n.texture){r.setPipeline(this.pipelineTextured.pipeline);let i=this.textureBindGroups.get(n.texture);i||(i=new bs(this.device,this.textureBindGroupLayout,[{binding:0,resource:this.defaultSampler},{binding:1,resource:n.texture.createView()}],`sprite-texture-bind-group-${n.texture.texture.label}`),this.textureBindGroups.set(n.texture,i)),r.setBindGroup(1,i.bindGroup)}else r.setPipeline(this.pipelineSolid.pipeline);r.drawIndexed(n.count,1,n.start,0,0)}r.end(),this.currentVertexCount=0,this.currentIndexCount=0,this.drawCommands=[],this.currentTexture=null}end(){this.flush(),this._activeEncoder=null,this._activeRenderTarget=null}get isActive(){return this._activeEncoder!==null}destroy(){this.vertexBuffer.destroy(),this.indexBuffer.destroy(),this.uniformBuffer.destroy()}};var xp=`// Skybox shader using full-screen triangle approach
874
+ `;var ka=2048,Bc=4,bp=6,vs=8,Fc=class{constructor(e,r){this.device=e;this.format=r;this.currentVertexCount=0;this.currentIndexCount=0;this.currentTexture=null;this.drawCommands=[];this.textureBindGroups=new Map;this._activeEncoder=null;this._activeRenderTarget=null;let n=new Rc(e,{code:yp,label:"sprite-shader"}),i={arrayStride:vs*4,stepMode:"vertex",attributes:[{format:"float32x2",offset:0,shaderLocation:0},{format:"float32x2",offset:8,shaderLocation:1},{format:"float32x4",offset:16,shaderLocation:2}]},a=new xs("sprite-uniform-layout");a.addUniformBuffer(0,GPUShaderStage.VERTEX);let o=a.build(e),s=new xs("sprite-texture-layout");s.addSampler(0,GPUShaderStage.FRAGMENT),s.addTexture(1,GPUShaderStage.FRAGMENT),this.textureBindGroupLayout=s.build(e);let c=e.createPipelineLayout({bindGroupLayouts:[o.layout,this.textureBindGroupLayout.layout],label:"sprite-pipeline-layout"}),l=e.createPipelineLayout({bindGroupLayouts:[o.layout],label:"sprite-pipeline-solid-layout"}),u={color:{srcFactor:"src-alpha",dstFactor:"one-minus-src-alpha",operation:"add"},alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"}};this.pipelineTextured=new ys(e,{layout:c,vertex:{module:n,entryPoint:"vs_main",buffers:[i]},fragment:{module:n,entryPoint:"fs_main",targets:[{format:this.format,blend:u}]},primitive:{topology:"triangle-list",cullMode:"none"},label:"sprite-pipeline-textured"}),this.pipelineSolid=new ys(e,{layout:l,vertex:{module:n,entryPoint:"vs_main",buffers:[i]},fragment:{module:n,entryPoint:"fs_solid",targets:[{format:this.format,blend:u}]},primitive:{topology:"triangle-list",cullMode:"none"},label:"sprite-pipeline-solid"}),this.vertexBuffer=new Ia(e,{size:ka*Bc*vs*4,label:"sprite-vertex-buffer",usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}),this.indexBuffer=new Da(e,{size:ka*bp*2,label:"sprite-index-buffer",usage:GPUBufferUsage.INDEX|GPUBufferUsage.COPY_DST}),this.uniformBuffer=new Tc(e,{size:64,label:"sprite-uniform-buffer",usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this.uniformBindGroup=new bs(e,o,[{binding:0,resource:this.uniformBuffer}],"sprite-uniform-bind-group"),this.vertexData=new Float32Array(ka*Bc*vs);let d=new Uint16Array(ka*bp);for(let f=0;f<ka;f++){let h=f*4,m=f*6;d[m]=h,d[m+1]=h+1,d[m+2]=h+2,d[m+3]=h,d[m+4]=h+2,d[m+5]=h+3}this.indexBuffer.write(d),this.projectionMatrix=F.create(),this.defaultSampler=Cc(e)}setProjection(e,r){F.ortho(this.projectionMatrix,0,e,r,0,-1,1),this.uniformBuffer.write(this.projectionMatrix)}begin(e,r){this.currentVertexCount=0,this.currentIndexCount=0,this.drawCommands=[],this.currentTexture=null,this._activeEncoder=e,this._activeRenderTarget=r}drawTexturedQuad(e,r,n,i,a,o=0,s=0,c=1,l=1,u=[1,1,1,1]){this.currentVertexCount+Bc>ka*Bc&&this.flush(),(this.drawCommands.length===0||this.currentTexture!==a)&&(this.drawCommands.push({texture:a,start:this.currentIndexCount,count:0}),this.currentTexture=a);let d=this.currentVertexCount*vs,[f,h,m,g]=u;this.vertexData[d]=e,this.vertexData[d+1]=r,this.vertexData[d+2]=o,this.vertexData[d+3]=s,this.vertexData[d+4]=f,this.vertexData[d+5]=h,this.vertexData[d+6]=m,this.vertexData[d+7]=g,this.vertexData[d+8]=e,this.vertexData[d+9]=r+i,this.vertexData[d+10]=o,this.vertexData[d+11]=l,this.vertexData[d+12]=f,this.vertexData[d+13]=h,this.vertexData[d+14]=m,this.vertexData[d+15]=g,this.vertexData[d+16]=e+n,this.vertexData[d+17]=r+i,this.vertexData[d+18]=c,this.vertexData[d+19]=l,this.vertexData[d+20]=f,this.vertexData[d+21]=h,this.vertexData[d+22]=m,this.vertexData[d+23]=g,this.vertexData[d+24]=e+n,this.vertexData[d+25]=r,this.vertexData[d+26]=c,this.vertexData[d+27]=s,this.vertexData[d+28]=f,this.vertexData[d+29]=h,this.vertexData[d+30]=m,this.vertexData[d+31]=g,this.currentVertexCount+=4,this.currentIndexCount+=6,this.drawCommands[this.drawCommands.length-1].count+=6}drawSolidRect(e,r,n,i,a){this.currentTexture!==null&&(this.drawCommands.push({texture:null,start:this.currentIndexCount,count:0}),this.currentTexture=null),this.drawTexturedQuad(e,r,n,i,null,0,0,0,0,a)}flush(){if(this.currentVertexCount===0||!this._activeEncoder||!this._activeRenderTarget)return;let e=this.currentVertexCount*vs;this.vertexBuffer.write(this.vertexData.subarray(0,e));let r=this._activeEncoder.beginRenderPass({colorAttachments:[{view:this._activeRenderTarget,loadOp:"load",storeOp:"store"}],label:"sprite-pass"});r.setBindGroup(0,this.uniformBindGroup.bindGroup),r.setVertexBuffer(0,this.vertexBuffer.buffer),r.setIndexBuffer(this.indexBuffer.buffer,"uint16");for(let n of this.drawCommands)if(n.count!==0){if(n.texture){r.setPipeline(this.pipelineTextured.pipeline);let i=this.textureBindGroups.get(n.texture);i||(i=new bs(this.device,this.textureBindGroupLayout,[{binding:0,resource:this.defaultSampler},{binding:1,resource:n.texture.createView()}],`sprite-texture-bind-group-${n.texture.texture.label}`),this.textureBindGroups.set(n.texture,i)),r.setBindGroup(1,i.bindGroup)}else r.setPipeline(this.pipelineSolid.pipeline);r.drawIndexed(n.count,1,n.start,0,0)}r.end(),this.currentVertexCount=0,this.currentIndexCount=0,this.drawCommands=[],this.currentTexture=null}end(){this.flush(),this._activeEncoder=null,this._activeRenderTarget=null}get isActive(){return this._activeEncoder!==null}destroy(){this.vertexBuffer.destroy(),this.indexBuffer.destroy(),this.uniformBuffer.destroy()}};var xp=`// Skybox shader using full-screen triangle approach
870
875
  // This avoids the w\u22480 issue with cube geometry at diagonal view angles
871
876
  // by computing the world-space direction analytically per-pixel
872
877
 
@@ -945,7 +950,7 @@ fn fragmentMain(@builtin(position) fragCoord: vec4<f32>) -> @location(0) vec4<f3
945
950
 
946
951
  return textureSample(t_skybox, s_skybox, cubemapDir);
947
952
  }
948
- `;var Qd=(n=>(n.QUAKE="quake",n.OPENGL="opengl",n.WEBGPU="webgpu",n))(Qd||{});var Ua=class{constructor(){this.coordinateSystem="webgpu"}buildProjectionMatrix(e){let r=F.create(),n=1/Math.tan(e.fov*Ae/2),i=1/(e.near-e.far);return r[0]=n/e.aspect,r[5]=n,r[10]=e.far*i,r[11]=-1,r[14]=e.near*e.far*i,r[15]=0,r}buildViewMatrix(e){let[r,n,i]=e.angles,a=r*Ae,o=n*Ae,s=i*Ae,c=F.create();F.identity(c),F.rotateZ(c,c,-o),F.rotateY(c,c,-a),F.rotateX(c,c,-s);let l=F.fromValues(0,0,-1,0,-1,0,0,0,0,1,0,0,0,0,0,1),u=F.fromValues(0,0,-1,0,-1,0,0,0,0,1,0,0,0,0,0,1),d=F.create();F.multiply(d,u,c);let f=L.fromValues(e.position[0],e.position[1],e.position[2]),h=L.transformMat4(L.create(),f,d);L.negate(h,h);let m=F.clone(d);return m[12]=h[0],m[13]=h[1],m[14]=h[2],m}};var vp=new Float32Array([-1,-1,1,-1,1,1,-1,-1,1,1,-1,1]),Ic=class{constructor(e,r){this.device=e;this.format=r;this.matrixBuilder=new Ua;let n=e.createShaderModule({label:"skybox-shader",code:xp});this.vertexBuffer=e.createBuffer({label:"skybox-vertex-buffer",size:vp.byteLength,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST,mappedAtCreation:!0}),new Float32Array(this.vertexBuffer.getMappedRange()).set(vp),this.vertexBuffer.unmap(),this.uniformBuffer=e.createBuffer({label:"skybox-uniform-buffer",size:64,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this.sampler=e.createSampler({label:"skybox-sampler",minFilter:"linear",magFilter:"linear",addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge",addressModeW:"clamp-to-edge"});let i=e.createBindGroupLayout({label:"skybox-bind-group-layout",entries:[{binding:0,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}},{binding:1,visibility:GPUShaderStage.FRAGMENT,texture:{viewDimension:"cube"}},{binding:2,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}}]});this.pipeline=e.createRenderPipeline({label:"skybox-pipeline",layout:e.createPipelineLayout({bindGroupLayouts:[i]}),vertex:{module:n,entryPoint:"vertexMain",buffers:[{arrayStride:8,attributes:[{shaderLocation:0,offset:0,format:"float32x2"}]}]},fragment:{module:n,entryPoint:"fragmentMain",targets:[{format:this.format,blend:{color:{srcFactor:"src-alpha",dstFactor:"one-minus-src-alpha",operation:"add"},alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"}}}]},depthStencil:{format:"depth24plus",depthWriteEnabled:!1,depthCompare:"always"},primitive:{topology:"triangle-list",cullMode:"none"}}),this.bindGroupHelper=new Jd(e,i,this.uniformBuffer,this.sampler)}draw(e,r){if(!r.cameraState)throw new Error("SkyboxPipeline: cameraState is required for full-screen skybox rendering");let n=r.cameraState,i=this.matrixBuilder.buildViewMatrix(n),a=hs.fromValues(i[0],i[4],i[8],i[1],i[5],i[9],i[2],i[6],i[10]),o=Math.tan(n.fov*Ae/2),s=n.aspect,c=new Float32Array(16);c[0]=a[0],c[1]=a[1],c[2]=a[2],c[3]=0,c[4]=a[3],c[5]=a[4],c[6]=a[5],c[7]=0,c[8]=a[6],c[9]=a[7],c[10]=a[8],c[11]=0,c[12]=o,c[13]=s,c[14]=r.scroll[0],c[15]=r.scroll[1],this.device.queue.writeBuffer(this.uniformBuffer,0,c);let l=this.bindGroupHelper.getBindGroup(r.cubemap);e.setPipeline(this.pipeline),e.setBindGroup(0,l),e.setVertexBuffer(0,this.vertexBuffer),e.draw(6)}destroy(){this.vertexBuffer.destroy(),this.uniformBuffer.destroy()}},Jd=class{constructor(e,r,n,i){this.device=e;this.layout=r;this.uniformBuffer=n;this.sampler=i;this.bindGroupCache=new Map}getBindGroup(e){if(this.bindGroupCache.has(e))return this.bindGroupCache.get(e);let r=this.device.createBindGroup({layout:this.layout,entries:[{binding:0,resource:{buffer:this.uniformBuffer}},{binding:1,resource:e.createView()},{binding:2,resource:this.sampler}]});return this.bindGroupCache.set(e,r),r}};var _p=`struct DLight {
953
+ `;var Qd=(n=>(n.QUAKE="quake",n.OPENGL="opengl",n.WEBGPU="webgpu",n))(Qd||{});var Ua=class{constructor(){this.coordinateSystem="webgpu"}buildProjectionMatrix(e){let r=F.create(),n=1/Math.tan(e.fov*Ae/2),i=1/(e.near-e.far);return r[0]=n/e.aspect,r[5]=n,r[10]=e.far*i,r[11]=-1,r[14]=e.near*e.far*i,r[15]=0,r}buildViewMatrix(e){let[r,n,i]=e.angles,a=r*Ae,o=n*Ae,s=i*Ae,c=F.create();F.identity(c),F.rotateZ(c,c,-o),F.rotateY(c,c,-a),F.rotateX(c,c,-s);let l=F.fromValues(0,0,-1,0,-1,0,0,0,0,1,0,0,0,0,0,1),u=F.fromValues(0,0,-1,0,-1,0,0,0,0,1,0,0,0,0,0,1),d=F.create();F.multiply(d,u,c);let f=T.fromValues(e.position[0],e.position[1],e.position[2]),h=T.transformMat4(T.create(),f,d);T.negate(h,h);let m=F.clone(d);return m[12]=h[0],m[13]=h[1],m[14]=h[2],m}};var vp=new Float32Array([-1,-1,1,-1,1,1,-1,-1,1,1,-1,1]),Ic=class{constructor(e,r){this.device=e;this.format=r;this.matrixBuilder=new Ua;let n=e.createShaderModule({label:"skybox-shader",code:xp});this.vertexBuffer=e.createBuffer({label:"skybox-vertex-buffer",size:vp.byteLength,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST,mappedAtCreation:!0}),new Float32Array(this.vertexBuffer.getMappedRange()).set(vp),this.vertexBuffer.unmap(),this.uniformBuffer=e.createBuffer({label:"skybox-uniform-buffer",size:64,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this.sampler=e.createSampler({label:"skybox-sampler",minFilter:"linear",magFilter:"linear",addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge",addressModeW:"clamp-to-edge"});let i=e.createBindGroupLayout({label:"skybox-bind-group-layout",entries:[{binding:0,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}},{binding:1,visibility:GPUShaderStage.FRAGMENT,texture:{viewDimension:"cube"}},{binding:2,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}}]});this.pipeline=e.createRenderPipeline({label:"skybox-pipeline",layout:e.createPipelineLayout({bindGroupLayouts:[i]}),vertex:{module:n,entryPoint:"vertexMain",buffers:[{arrayStride:8,attributes:[{shaderLocation:0,offset:0,format:"float32x2"}]}]},fragment:{module:n,entryPoint:"fragmentMain",targets:[{format:this.format,blend:{color:{srcFactor:"src-alpha",dstFactor:"one-minus-src-alpha",operation:"add"},alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"}}}]},depthStencil:{format:"depth24plus",depthWriteEnabled:!1,depthCompare:"always"},primitive:{topology:"triangle-list",cullMode:"none"}}),this.bindGroupHelper=new Jd(e,i,this.uniformBuffer,this.sampler)}draw(e,r){if(!r.cameraState)throw new Error("SkyboxPipeline: cameraState is required for full-screen skybox rendering");let n=r.cameraState,i=this.matrixBuilder.buildViewMatrix(n),a=hs.fromValues(i[0],i[4],i[8],i[1],i[5],i[9],i[2],i[6],i[10]),o=Math.tan(n.fov*Ae/2),s=n.aspect,c=new Float32Array(16);c[0]=a[0],c[1]=a[1],c[2]=a[2],c[3]=0,c[4]=a[3],c[5]=a[4],c[6]=a[5],c[7]=0,c[8]=a[6],c[9]=a[7],c[10]=a[8],c[11]=0,c[12]=o,c[13]=s,c[14]=r.scroll[0],c[15]=r.scroll[1],this.device.queue.writeBuffer(this.uniformBuffer,0,c);let l=this.bindGroupHelper.getBindGroup(r.cubemap);e.setPipeline(this.pipeline),e.setBindGroup(0,l),e.setVertexBuffer(0,this.vertexBuffer),e.draw(6)}destroy(){this.vertexBuffer.destroy(),this.uniformBuffer.destroy()}},Jd=class{constructor(e,r,n,i){this.device=e;this.layout=r;this.uniformBuffer=n;this.sampler=i;this.bindGroupCache=new Map}getBindGroup(e){if(this.bindGroupCache.has(e))return this.bindGroupCache.get(e);let r=this.device.createBindGroup({layout:this.layout,entries:[{binding:0,resource:{buffer:this.uniformBuffer}},{binding:1,resource:e.createView()},{binding:2,resource:this.sampler}]});return this.bindGroupCache.set(e,r),r}};var _p=`struct DLight {
949
954
  position: vec3<f32>,
950
955
  intensity: f32,
951
956
  color: vec3<f32>,
@@ -1117,14 +1122,14 @@ fn fragmentMain(input: VertexOutput) -> @location(0) vec4<f32> {
1117
1122
 
1118
1123
  return finalColor;
1119
1124
  }
1120
- `;var Sp=[0,255,255,255],b_=[0,-1,-1,-1];function x_(t=Sp,e=[]){let r=new Float32Array(4);for(let n=0;n<4;n+=1){let i=t[n]??255;if(i===255){r[n]=0;continue}let a=e[i];r[n]=a!==void 0?a:1}return r}function v_(t){return[-(t*.25%1),0]}function __(t=yn,e=0){let r=(t&el)!==0,n=(t&Yr)!==0,i=(t&bn)!==0,a=(t&xn)!==0,o=(t&vn)!==0,s=a?.33:o?.66:1,c=a||o||n,l=!c&&!i,u=r?v_(e):[0,0];return{alpha:s,blend:c,depthWrite:l,warp:n,flowOffset:u,sky:i}}var Dc=class{constructor(e,r,n){this.textureBindGroupCache=new Map;this.device=e;let i=2048,a=256;this.frameUniformBuffer=e.createBuffer({size:i,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this.surfaceUniformBuffer=e.createBuffer({size:a,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this.frameBindGroupLayout=e.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}}]}),this.surfaceBindGroupLayout=e.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}}]}),this.textureBindGroupLayout=e.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,texture:{}},{binding:1,visibility:GPUShaderStage.FRAGMENT,sampler:{}},{binding:2,visibility:GPUShaderStage.FRAGMENT,texture:{}},{binding:3,visibility:GPUShaderStage.FRAGMENT,sampler:{}}]}),this.defaultSampler=Cc(e),this.defaultWhiteTexture=new $n(e,{width:1,height:1,format:"rgba8unorm",label:"bsp-default-white"}),this.defaultWhiteTexture.upload(new Uint8Array([255,255,255,255])),this.defaultBindGroup=e.createBindGroup({layout:this.textureBindGroupLayout,entries:[{binding:0,resource:this.defaultWhiteTexture.createView()},{binding:1,resource:this.defaultSampler.sampler},{binding:2,resource:this.defaultWhiteTexture.createView()},{binding:3,resource:this.defaultSampler.sampler}]}),this.createPipelines(r,n),this.frameBindGroup=e.createBindGroup({layout:this.frameBindGroupLayout,entries:[{binding:0,resource:{buffer:this.frameUniformBuffer}}]})}createPipelines(e,r){let n=this.device.createShaderModule({code:_p}),i=this.device.createPipelineLayout({bindGroupLayouts:[this.frameBindGroupLayout,this.surfaceBindGroupLayout,this.textureBindGroupLayout]}),a={module:n,entryPoint:"vertexMain",buffers:[{arrayStride:32,attributes:[{shaderLocation:0,offset:0,format:"float32x3"},{shaderLocation:1,offset:12,format:"float32x2"},{shaderLocation:2,offset:20,format:"float32x2"},{shaderLocation:3,offset:28,format:"float32"}]}]};this.pipeline=this.device.createRenderPipeline({layout:i,vertex:a,fragment:{module:n,entryPoint:"fragmentMain",targets:[{format:e,blend:{color:{srcFactor:"src-alpha",dstFactor:"one-minus-src-alpha",operation:"add"},alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"}}}]},primitive:{topology:"triangle-list",cullMode:"back"},depthStencil:{format:r,depthWriteEnabled:!0,depthCompare:"less"}}),this.pipelineWireframe=this.device.createRenderPipeline({layout:i,vertex:a,fragment:{module:n,entryPoint:"fragmentMain",targets:[{format:e,writeMask:GPUColorWrite.ALL}]},primitive:{topology:"line-list"},depthStencil:{format:r,depthWriteEnabled:!0,depthCompare:"less"}})}bind(e,r){let{modelViewProjection:n,styleIndices:i=Sp,styleLayers:a=b_,styleValues:o=[],diffuseTexture:s,diffuseSampler:c,lightmapTexture:l,lightmapSampler:u,surfaceFlags:d=yn,timeSeconds:f=0,texScroll:h,alpha:m,warp:g,dlights:p=[],renderMode:y,lightmapOnly:v,brightness:b=1,gamma:x=1,fullbright:_=!1,ambient:w=0,cameraPosition:S=[0,0,0]}=r,A=__(d,f),T=x_(i,o),M=h?h[0]:A.flowOffset[0],P=h?h[1]:A.flowOffset[1],I=m!==void 0?m:A.alpha,D=g!==void 0?g:A.warp,B=new Float32Array(512);B.set(n,0),B.set(S,16),B[19]=0,B[20]=f,B[21]=b,B[22]=x,B[23]=w;let O=Math.min(p.length,Or),Q=new Uint32Array(B.buffer,96,1);Q[0]=O;let Ge=new Uint32Array(B.buffer,100,1);Ge[0]=_?1:0;let me=32;for(let ut=0;ut<O;ut++){let He=p[ut];B[me+0]=He.origin.x,B[me+1]=He.origin.y,B[me+2]=He.origin.z,B[me+3]=He.intensity,B[me+4]=He.color.x,B[me+5]=He.color.y,B[me+6]=He.color.z,B[me+7]=0,me+=8}this.device.queue.writeBuffer(this.frameUniformBuffer,0,B,0,me);let Me=new Float32Array(32);Me[0]=M,Me[1]=P,Me[2]=A.flowOffset[0],Me[3]=A.flowOffset[1],Me.set(T,4),Me.set(a,8);let ge=0,ue=[1,1,1,1];y&&(y.mode==="solid"||y.mode==="wireframe"?ge=1:y.mode==="solid-faceted"&&(ge=2),y.color?ue=[...y.color]:y.generateRandomColor&&(ue=[1,1,1,1])),Me.set(ue,12),Me[16]=I;let ye=new Uint32Array(Me.buffer),Ve=!A.sky&&u!==void 0&&!D;ye[17]=Ve?1:0,ye[18]=D?1:0,ye[19]=v?1:0,ye[20]=ge,this.device.queue.writeBuffer(this.surfaceUniformBuffer,0,Me);let ct=this.device.createBindGroup({layout:this.surfaceBindGroupLayout,entries:[{binding:0,resource:{buffer:this.surfaceUniformBuffer}}]});if(s&&c&&l&&u){let ut=this.device.createBindGroup({layout:this.textureBindGroupLayout,entries:[{binding:0,resource:s},{binding:1,resource:c},{binding:2,resource:l},{binding:3,resource:u}]});e.setBindGroup(2,ut)}else e.setBindGroup(2,this.defaultBindGroup);let qt=y&&y.mode==="wireframe"?this.pipelineWireframe:this.pipeline;return e.setPipeline(qt),e.setBindGroup(0,this.frameBindGroup),e.setBindGroup(1,ct),A}draw(e,r,n){r.gpuIndexBuffer&&(n&&n.mode==="wireframe"||(e.setVertexBuffer(0,r.gpuVertexBuffer),e.setIndexBuffer(r.gpuIndexBuffer,"uint16"),e.drawIndexed(r.indexCount)))}destroy(){this.frameUniformBuffer.destroy(),this.surfaceUniformBuffer.destroy(),this.defaultWhiteTexture.destroy()}};var ef=class{constructor(e,r,n){this.context=e;this.frameRenderer=r;this.pipelines=n;this.type="webgpu";this.picCache=new Map;this.font=null;this.is2DActive=!1;this.whiteTexture=new $n(e.device,{width:1,height:1,format:e.format,label:"white-texture"}),this.whiteTexture.upload(new Uint8Array([255,255,255,255])),this.collisionVis=null,this.debug=null,this.particleSystem=null}get device(){return this.context.device}get width(){return this.context.width}get height(){return this.context.height}renderFrame(e,r=[],n){let i=e,a=i.dlights;if(i.dlights&&i.dlights.length>0){let s=new Float32Array(i.camera.viewProjectionMatrix),c=sr(s),l={x:i.camera.position[0],y:i.camera.position[1],z:i.camera.position[2]};a=Mc(i.dlights,c,l,32)}let o={...i,dlights:a};this.frameRenderer.renderFrame(o)}uploadBspGeometry(e){for(let r of e){if(r.gpuVertexBuffer&&r.gpuIndexBuffer)continue;let n=new Ia(this.device,{size:r.vertexData.byteLength,label:`bsp-surface-vb-${r.texture}`});n.write(r.vertexData);let i=new Da(this.device,{size:r.indexData.byteLength,label:`bsp-surface-ib-${r.texture}`});i.write(r.indexData);let a=r;a.gpuVertexBuffer=n.buffer,a.gpuIndexBuffer=i.buffer}}async registerPic(e,r){if(this.picCache.has(e))return this.picCache.get(e);let n=new $n(this.device,{width:256,height:256,format:this.context.format,label:`pic-${e}`});return n.upload(r),this.picCache.set(e,n),n}registerTexture(e,r){if(this.picCache.has(e))return this.picCache.get(e);let n=new $n(this.device,{width:r.width,height:r.height,format:this.context.format,mipLevelCount:r.levels.length,label:`texture-${e}`});for(let i of r.levels)n.upload(i.rgba,{width:i.width,height:i.height,mipLevel:i.level});return this.picCache.set(e,n),n}begin2D(){this.frameRenderer.begin2DPass(),this.is2DActive=!0}end2D(){this.frameRenderer.end2DPass(),this.is2DActive=!1}drawPic(e,r,n,i=[1,1,1,1]){if(!this.is2DActive)throw new Error("drawPic called outside begin2D/end2D");this.pipelines.sprite.drawTexturedQuad(e,r,n.width,n.height,n,0,0,1,1,i)}drawfillRect(e,r,n,i,a){if(!this.is2DActive)throw new Error("drawfillRect called outside begin2D/end2D");this.pipelines.sprite.drawSolidRect(e,r,n,i,a)}drawString(e,r,n,i=[1,1,1,1]){if(!this.is2DActive)throw new Error("drawString called outside begin2D/end2D");if(!this.font)return;let a=_c(n),o=e,s=8,c=8;for(let l of a){let u=l.color||i;for(let d of l.text){let f=d.charCodeAt(0),h=f%16,m=Math.floor(f/16),g=h/16,p=m/16,y=(h+1)/16,v=(m+1)/16;this.pipelines.sprite.drawTexturedQuad(o,r,s,c,this.font,g,p,y,v,u),o+=s}}}drawCenterString(e,r){if(!this.is2DActive)throw new Error("drawCenterString called outside begin2D/end2D");let a=r.replace(/\^[0-9]/g,"").length*8,o=(this.width-a)/2;this.drawString(o,e,r)}setEntityHighlight(e,r){}clearEntityHighlight(e){}highlightSurface(e,r){}removeSurfaceHighlight(e){}setDebugMode(e){}setBrightness(e){}setGamma(e){}setFullbright(e){}setAmbient(e){}setLightStyle(e,r){}setUnderwaterWarp(e){}setBloom(e){}setBloomIntensity(e){}setLodBias(e){}renderInstanced(e,r){}getPerformanceReport(){return{frameTimeMs:0,gpuTimeMs:0,cpuFrameTimeMs:0,drawCalls:0,triangles:0,vertices:0,textureBinds:0,shaderSwitches:0,visibleSurfaces:0,culledSurfaces:0,visibleEntities:0,culledEntities:0,memoryUsageMB:{textures:0,geometry:0,total:0}}}getMemoryUsage(){return{texturesBytes:0,geometryBytes:0,shadersBytes:0,buffersBytes:0,totalBytes:0}}resize(e,r){this.context.context&&!this.context.isHeadless?(this.context.width=e,this.context.height=r):(this.context.width=e,this.context.height=r)}dispose(){this.pipelines.sprite.destroy(),this.pipelines.skybox.destroy(),this.pipelines.bsp.destroy();for(let e of this.picCache.values())e.destroy();this.picCache.clear(),this.whiteTexture.destroy(),this.context.device.destroy()}destroy(){this.dispose()}};async function wp(t,e){let r=await Ac(t,e),n=new Fc(r.device,r.format),i=new Ic(r.device,r.format),a=new Dc(r.device,r.format,r.depthFormat||"depth24plus"),o={sprite:n,skybox:i,bsp:a};t?(r.width=t.width,r.height=t.height):(r.width=800,r.height=600);let s=new Ec(r,o);return new ef(r,s,o)}var vr=class{constructor(e){this.messageOffsets=[];this.currentBlock=null;this.buffer=e,this.view=new DataView(e),this.offset=0,this.scan()}scan(){let e=0;for(this.messageOffsets=[];e+4<=this.buffer.byteLength;){let r=this.view.getInt32(e,!0);if(r===-1)break;if(r<0||r>2097152){console.warn(`DemoReader: Invalid block length ${r} at offset ${e} during scan`);break}if(e+4+r>this.buffer.byteLength){console.warn(`DemoReader: Incomplete block at offset ${e} during scan`);break}this.messageOffsets.push(e),e+=4+r}}hasMore(){return this.offset<this.buffer.byteLength}readNextBlock(){if(this.offset+4>this.buffer.byteLength)return null;let e=this.view.getInt32(this.offset,!0);if(e===-1||e<0||this.offset+4+e>this.buffer.byteLength)return null;this.offset+=4;let r=this.buffer.slice(this.offset,this.offset+e);return this.offset+=e,{length:e,data:new Mn(r)}}nextBlock(){let e=this.readNextBlock();return e?(this.currentBlock=e,!0):(this.currentBlock=null,!1)}getBlock(){if(!this.currentBlock)throw new Error("No current block. Call nextBlock() first.");return this.currentBlock}readAllBlocksToBuffer(){let e=0,r=this.offset,n=[],i=this.offset;for(;i+4<=this.buffer.byteLength;){let c=this.view.getInt32(i,!0);if(c===-1||c<0||i+4+c>this.buffer.byteLength)break;n.push({offset:i+4,length:c}),e+=c,i+=4+c}let a=new Uint8Array(e),o=0,s=new Uint8Array(this.buffer);for(let c of n)a.set(s.subarray(c.offset,c.offset+c.length),o),o+=c.length;return this.offset=i,a.buffer}reset(){this.offset=0,this.currentBlock=null}seekToMessage(e){return e<0||e>=this.messageOffsets.length?!1:(this.offset=this.messageOffsets[e],this.currentBlock=null,!0)}getMessageCount(){return this.messageOffsets.length}getOffset(){return this.offset}getProgress(){let e=this.offset,r=this.buffer.byteLength;return{current:e,total:r,percent:r>0?e/r*100:0}}};function Ha(t){let e=t.length;for(;--e>=0;)t[e]=0}var S_=0,l0=1,w_=2,M_=3,A_=258,Af=29,Ds=256,Ts=Ds+1+Af,Na=30,Ef=19,c0=2*Ts+1,Pi=15,tf=16,E_=7,Tf=256,u0=16,d0=17,f0=18,gf=new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]),Gc=new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]),T_=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),h0=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),L_=512,fn=new Array((Ts+2)*2);Ha(fn);var Ms=new Array(Na*2);Ha(Ms);var Ls=new Array(L_);Ha(Ls);var Ps=new Array(A_-M_+1);Ha(Ps);var Lf=new Array(Af);Ha(Lf);var Vc=new Array(Na);Ha(Vc);function rf(t,e,r,n,i){this.static_tree=t,this.extra_bits=e,this.extra_base=r,this.elems=n,this.max_length=i,this.has_stree=t&&t.length}var m0,p0,g0;function nf(t,e){this.dyn_tree=t,this.max_code=0,this.stat_desc=e}var y0=t=>t<256?Ls[t]:Ls[256+(t>>>7)],Rs=(t,e)=>{t.pending_buf[t.pending++]=e&255,t.pending_buf[t.pending++]=e>>>8&255},Ot=(t,e,r)=>{t.bi_valid>tf-r?(t.bi_buf|=e<<t.bi_valid&65535,Rs(t,t.bi_buf),t.bi_buf=e>>tf-t.bi_valid,t.bi_valid+=r-tf):(t.bi_buf|=e<<t.bi_valid&65535,t.bi_valid+=r)},Gr=(t,e,r)=>{Ot(t,r[e*2],r[e*2+1])},b0=(t,e)=>{let r=0;do r|=t&1,t>>>=1,r<<=1;while(--e>0);return r>>>1},P_=t=>{t.bi_valid===16?(Rs(t,t.bi_buf),t.bi_buf=0,t.bi_valid=0):t.bi_valid>=8&&(t.pending_buf[t.pending++]=t.bi_buf&255,t.bi_buf>>=8,t.bi_valid-=8)},R_=(t,e)=>{let r=e.dyn_tree,n=e.max_code,i=e.stat_desc.static_tree,a=e.stat_desc.has_stree,o=e.stat_desc.extra_bits,s=e.stat_desc.extra_base,c=e.stat_desc.max_length,l,u,d,f,h,m,g=0;for(f=0;f<=Pi;f++)t.bl_count[f]=0;for(r[t.heap[t.heap_max]*2+1]=0,l=t.heap_max+1;l<c0;l++)u=t.heap[l],f=r[r[u*2+1]*2+1]+1,f>c&&(f=c,g++),r[u*2+1]=f,!(u>n)&&(t.bl_count[f]++,h=0,u>=s&&(h=o[u-s]),m=r[u*2],t.opt_len+=m*(f+h),a&&(t.static_len+=m*(i[u*2+1]+h)));if(g!==0){do{for(f=c-1;t.bl_count[f]===0;)f--;t.bl_count[f]--,t.bl_count[f+1]+=2,t.bl_count[c]--,g-=2}while(g>0);for(f=c;f!==0;f--)for(u=t.bl_count[f];u!==0;)d=t.heap[--l],!(d>n)&&(r[d*2+1]!==f&&(t.opt_len+=(f-r[d*2+1])*r[d*2],r[d*2+1]=f),u--)}},x0=(t,e,r)=>{let n=new Array(Pi+1),i=0,a,o;for(a=1;a<=Pi;a++)i=i+r[a-1]<<1,n[a]=i;for(o=0;o<=e;o++){let s=t[o*2+1];s!==0&&(t[o*2]=b0(n[s]++,s))}},C_=()=>{let t,e,r,n,i,a=new Array(Pi+1);for(r=0,n=0;n<Af-1;n++)for(Lf[n]=r,t=0;t<1<<gf[n];t++)Ps[r++]=n;for(Ps[r-1]=n,i=0,n=0;n<16;n++)for(Vc[n]=i,t=0;t<1<<Gc[n];t++)Ls[i++]=n;for(i>>=7;n<Na;n++)for(Vc[n]=i<<7,t=0;t<1<<Gc[n]-7;t++)Ls[256+i++]=n;for(e=0;e<=Pi;e++)a[e]=0;for(t=0;t<=143;)fn[t*2+1]=8,t++,a[8]++;for(;t<=255;)fn[t*2+1]=9,t++,a[9]++;for(;t<=279;)fn[t*2+1]=7,t++,a[7]++;for(;t<=287;)fn[t*2+1]=8,t++,a[8]++;for(x0(fn,Ts+1,a),t=0;t<Na;t++)Ms[t*2+1]=5,Ms[t*2]=b0(t,5);m0=new rf(fn,gf,Ds+1,Ts,Pi),p0=new rf(Ms,Gc,0,Na,Pi),g0=new rf(new Array(0),T_,0,Ef,E_)},v0=t=>{let e;for(e=0;e<Ts;e++)t.dyn_ltree[e*2]=0;for(e=0;e<Na;e++)t.dyn_dtree[e*2]=0;for(e=0;e<Ef;e++)t.bl_tree[e*2]=0;t.dyn_ltree[Tf*2]=1,t.opt_len=t.static_len=0,t.sym_next=t.matches=0},_0=t=>{t.bi_valid>8?Rs(t,t.bi_buf):t.bi_valid>0&&(t.pending_buf[t.pending++]=t.bi_buf),t.bi_buf=0,t.bi_valid=0},Mp=(t,e,r,n)=>{let i=e*2,a=r*2;return t[i]<t[a]||t[i]===t[a]&&n[e]<=n[r]},af=(t,e,r)=>{let n=t.heap[r],i=r<<1;for(;i<=t.heap_len&&(i<t.heap_len&&Mp(e,t.heap[i+1],t.heap[i],t.depth)&&i++,!Mp(e,n,t.heap[i],t.depth));)t.heap[r]=t.heap[i],r=i,i<<=1;t.heap[r]=n},Ap=(t,e,r)=>{let n,i,a=0,o,s;if(t.sym_next!==0)do n=t.pending_buf[t.sym_buf+a++]&255,n+=(t.pending_buf[t.sym_buf+a++]&255)<<8,i=t.pending_buf[t.sym_buf+a++],n===0?Gr(t,i,e):(o=Ps[i],Gr(t,o+Ds+1,e),s=gf[o],s!==0&&(i-=Lf[o],Ot(t,i,s)),n--,o=y0(n),Gr(t,o,r),s=Gc[o],s!==0&&(n-=Vc[o],Ot(t,n,s)));while(a<t.sym_next);Gr(t,Tf,e)},yf=(t,e)=>{let r=e.dyn_tree,n=e.stat_desc.static_tree,i=e.stat_desc.has_stree,a=e.stat_desc.elems,o,s,c=-1,l;for(t.heap_len=0,t.heap_max=c0,o=0;o<a;o++)r[o*2]!==0?(t.heap[++t.heap_len]=c=o,t.depth[o]=0):r[o*2+1]=0;for(;t.heap_len<2;)l=t.heap[++t.heap_len]=c<2?++c:0,r[l*2]=1,t.depth[l]=0,t.opt_len--,i&&(t.static_len-=n[l*2+1]);for(e.max_code=c,o=t.heap_len>>1;o>=1;o--)af(t,r,o);l=a;do o=t.heap[1],t.heap[1]=t.heap[t.heap_len--],af(t,r,1),s=t.heap[1],t.heap[--t.heap_max]=o,t.heap[--t.heap_max]=s,r[l*2]=r[o*2]+r[s*2],t.depth[l]=(t.depth[o]>=t.depth[s]?t.depth[o]:t.depth[s])+1,r[o*2+1]=r[s*2+1]=l,t.heap[1]=l++,af(t,r,1);while(t.heap_len>=2);t.heap[--t.heap_max]=t.heap[1],R_(t,e),x0(r,c,t.bl_count)},Ep=(t,e,r)=>{let n,i=-1,a,o=e[1],s=0,c=7,l=4;for(o===0&&(c=138,l=3),e[(r+1)*2+1]=65535,n=0;n<=r;n++)a=o,o=e[(n+1)*2+1],!(++s<c&&a===o)&&(s<l?t.bl_tree[a*2]+=s:a!==0?(a!==i&&t.bl_tree[a*2]++,t.bl_tree[u0*2]++):s<=10?t.bl_tree[d0*2]++:t.bl_tree[f0*2]++,s=0,i=a,o===0?(c=138,l=3):a===o?(c=6,l=3):(c=7,l=4))},Tp=(t,e,r)=>{let n,i=-1,a,o=e[1],s=0,c=7,l=4;for(o===0&&(c=138,l=3),n=0;n<=r;n++)if(a=o,o=e[(n+1)*2+1],!(++s<c&&a===o)){if(s<l)do Gr(t,a,t.bl_tree);while(--s!==0);else a!==0?(a!==i&&(Gr(t,a,t.bl_tree),s--),Gr(t,u0,t.bl_tree),Ot(t,s-3,2)):s<=10?(Gr(t,d0,t.bl_tree),Ot(t,s-3,3)):(Gr(t,f0,t.bl_tree),Ot(t,s-11,7));s=0,i=a,o===0?(c=138,l=3):a===o?(c=6,l=3):(c=7,l=4)}},B_=t=>{let e;for(Ep(t,t.dyn_ltree,t.l_desc.max_code),Ep(t,t.dyn_dtree,t.d_desc.max_code),yf(t,t.bl_desc),e=Ef-1;e>=3&&t.bl_tree[h0[e]*2+1]===0;e--);return t.opt_len+=3*(e+1)+5+5+4,e},F_=(t,e,r,n)=>{let i;for(Ot(t,e-257,5),Ot(t,r-1,5),Ot(t,n-4,4),i=0;i<n;i++)Ot(t,t.bl_tree[h0[i]*2+1],3);Tp(t,t.dyn_ltree,e-1),Tp(t,t.dyn_dtree,r-1)},I_=t=>{let e=4093624447,r;for(r=0;r<=31;r++,e>>>=1)if(e&1&&t.dyn_ltree[r*2]!==0)return 0;if(t.dyn_ltree[18]!==0||t.dyn_ltree[20]!==0||t.dyn_ltree[26]!==0)return 1;for(r=32;r<Ds;r++)if(t.dyn_ltree[r*2]!==0)return 1;return 0},Lp=!1,D_=t=>{Lp||(C_(),Lp=!0),t.l_desc=new nf(t.dyn_ltree,m0),t.d_desc=new nf(t.dyn_dtree,p0),t.bl_desc=new nf(t.bl_tree,g0),t.bi_buf=0,t.bi_valid=0,v0(t)},S0=(t,e,r,n)=>{Ot(t,(S_<<1)+(n?1:0),3),_0(t),Rs(t,r),Rs(t,~r),r&&t.pending_buf.set(t.window.subarray(e,e+r),t.pending),t.pending+=r},k_=t=>{Ot(t,l0<<1,3),Gr(t,Tf,fn),P_(t)},U_=(t,e,r,n)=>{let i,a,o=0;t.level>0?(t.strm.data_type===2&&(t.strm.data_type=I_(t)),yf(t,t.l_desc),yf(t,t.d_desc),o=B_(t),i=t.opt_len+3+7>>>3,a=t.static_len+3+7>>>3,a<=i&&(i=a)):i=a=r+5,r+4<=i&&e!==-1?S0(t,e,r,n):t.strategy===4||a===i?(Ot(t,(l0<<1)+(n?1:0),3),Ap(t,fn,Ms)):(Ot(t,(w_<<1)+(n?1:0),3),F_(t,t.l_desc.max_code+1,t.d_desc.max_code+1,o+1),Ap(t,t.dyn_ltree,t.dyn_dtree)),v0(t),n&&_0(t)},z_=(t,e,r)=>(t.pending_buf[t.sym_buf+t.sym_next++]=e,t.pending_buf[t.sym_buf+t.sym_next++]=e>>8,t.pending_buf[t.sym_buf+t.sym_next++]=r,e===0?t.dyn_ltree[r*2]++:(t.matches++,e--,t.dyn_ltree[(Ps[r]+Ds+1)*2]++,t.dyn_dtree[y0(e)*2]++),t.sym_next===t.sym_end),O_=D_,N_=S0,G_=U_,V_=z_,H_=k_,W_={_tr_init:O_,_tr_stored_block:N_,_tr_flush_block:G_,_tr_tally:V_,_tr_align:H_},X_=(t,e,r,n)=>{let i=t&65535|0,a=t>>>16&65535|0,o=0;for(;r!==0;){o=r>2e3?2e3:r,r-=o;do i=i+e[n++]|0,a=a+i|0;while(--o);i%=65521,a%=65521}return i|a<<16|0},Cs=X_,$_=()=>{let t,e=[];for(var r=0;r<256;r++){t=r;for(var n=0;n<8;n++)t=t&1?3988292384^t>>>1:t>>>1;e[r]=t}return e},K_=new Uint32Array($_()),Y_=(t,e,r,n)=>{let i=K_,a=n+r;t^=-1;for(let o=n;o<a;o++)t=t>>>8^i[(t^e[o])&255];return t^-1},Ne=Y_,Bi={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"},Di={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8},{_tr_init:q_,_tr_stored_block:bf,_tr_flush_block:Z_,_tr_tally:qn,_tr_align:j_}=W_,{Z_NO_FLUSH:Zn,Z_PARTIAL_FLUSH:Q_,Z_FULL_FLUSH:J_,Z_FINISH:ur,Z_BLOCK:Pp,Z_OK:et,Z_STREAM_END:Rp,Z_STREAM_ERROR:Vr,Z_DATA_ERROR:eS,Z_BUF_ERROR:of,Z_DEFAULT_COMPRESSION:tS,Z_FILTERED:rS,Z_HUFFMAN_ONLY:kc,Z_RLE:nS,Z_FIXED:iS,Z_DEFAULT_STRATEGY:aS,Z_UNKNOWN:oS,Z_DEFLATED:Xc}=Di,sS=9,lS=15,cS=8,uS=29,dS=256,xf=dS+1+uS,fS=30,hS=19,mS=2*xf+1,pS=15,j=3,Yn=258,Hr=Yn+j+1,gS=32,Ga=42,Pf=57,vf=69,_f=73,Sf=91,wf=103,Ri=113,Ss=666,bt=1,Wa=2,Fi=3,Xa=4,yS=3,Ci=(t,e)=>(t.msg=Bi[e],e),Cp=t=>t*2-(t>4?9:0),Kn=t=>{let e=t.length;for(;--e>=0;)t[e]=0},bS=t=>{let e,r,n,i=t.w_size;e=t.hash_size,n=e;do r=t.head[--n],t.head[n]=r>=i?r-i:0;while(--e);e=i,n=e;do r=t.prev[--n],t.prev[n]=r>=i?r-i:0;while(--e)},xS=(t,e,r)=>(e<<t.hash_shift^r)&t.hash_mask,jn=xS,Kt=t=>{let e=t.state,r=e.pending;r>t.avail_out&&(r=t.avail_out),r!==0&&(t.output.set(e.pending_buf.subarray(e.pending_out,e.pending_out+r),t.next_out),t.next_out+=r,e.pending_out+=r,t.total_out+=r,t.avail_out-=r,e.pending-=r,e.pending===0&&(e.pending_out=0))},Yt=(t,e)=>{Z_(t,t.block_start>=0?t.block_start:-1,t.strstart-t.block_start,e),t.block_start=t.strstart,Kt(t.strm)},ie=(t,e)=>{t.pending_buf[t.pending++]=e},_s=(t,e)=>{t.pending_buf[t.pending++]=e>>>8&255,t.pending_buf[t.pending++]=e&255},Mf=(t,e,r,n)=>{let i=t.avail_in;return i>n&&(i=n),i===0?0:(t.avail_in-=i,e.set(t.input.subarray(t.next_in,t.next_in+i),r),t.state.wrap===1?t.adler=Cs(t.adler,e,i,r):t.state.wrap===2&&(t.adler=Ne(t.adler,e,i,r)),t.next_in+=i,t.total_in+=i,i)},w0=(t,e)=>{let r=t.max_chain_length,n=t.strstart,i,a,o=t.prev_length,s=t.nice_match,c=t.strstart>t.w_size-Hr?t.strstart-(t.w_size-Hr):0,l=t.window,u=t.w_mask,d=t.prev,f=t.strstart+Yn,h=l[n+o-1],m=l[n+o];t.prev_length>=t.good_match&&(r>>=2),s>t.lookahead&&(s=t.lookahead);do if(i=e,!(l[i+o]!==m||l[i+o-1]!==h||l[i]!==l[n]||l[++i]!==l[n+1])){n+=2,i++;do;while(l[++n]===l[++i]&&l[++n]===l[++i]&&l[++n]===l[++i]&&l[++n]===l[++i]&&l[++n]===l[++i]&&l[++n]===l[++i]&&l[++n]===l[++i]&&l[++n]===l[++i]&&n<f);if(a=Yn-(f-n),n=f-Yn,a>o){if(t.match_start=e,o=a,a>=s)break;h=l[n+o-1],m=l[n+o]}}while((e=d[e&u])>c&&--r!==0);return o<=t.lookahead?o:t.lookahead},Va=t=>{let e=t.w_size,r,n,i;do{if(n=t.window_size-t.lookahead-t.strstart,t.strstart>=e+(e-Hr)&&(t.window.set(t.window.subarray(e,e+e-n),0),t.match_start-=e,t.strstart-=e,t.block_start-=e,t.insert>t.strstart&&(t.insert=t.strstart),bS(t),n+=e),t.strm.avail_in===0)break;if(r=Mf(t.strm,t.window,t.strstart+t.lookahead,n),t.lookahead+=r,t.lookahead+t.insert>=j)for(i=t.strstart-t.insert,t.ins_h=t.window[i],t.ins_h=jn(t,t.ins_h,t.window[i+1]);t.insert&&(t.ins_h=jn(t,t.ins_h,t.window[i+j-1]),t.prev[i&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=i,i++,t.insert--,!(t.lookahead+t.insert<j)););}while(t.lookahead<Hr&&t.strm.avail_in!==0)},M0=(t,e)=>{let r=t.pending_buf_size-5>t.w_size?t.w_size:t.pending_buf_size-5,n,i,a,o=0,s=t.strm.avail_in;do{if(n=65535,a=t.bi_valid+42>>3,t.strm.avail_out<a||(a=t.strm.avail_out-a,i=t.strstart-t.block_start,n>i+t.strm.avail_in&&(n=i+t.strm.avail_in),n>a&&(n=a),n<r&&(n===0&&e!==ur||e===Zn||n!==i+t.strm.avail_in)))break;o=e===ur&&n===i+t.strm.avail_in?1:0,bf(t,0,0,o),t.pending_buf[t.pending-4]=n,t.pending_buf[t.pending-3]=n>>8,t.pending_buf[t.pending-2]=~n,t.pending_buf[t.pending-1]=~n>>8,Kt(t.strm),i&&(i>n&&(i=n),t.strm.output.set(t.window.subarray(t.block_start,t.block_start+i),t.strm.next_out),t.strm.next_out+=i,t.strm.avail_out-=i,t.strm.total_out+=i,t.block_start+=i,n-=i),n&&(Mf(t.strm,t.strm.output,t.strm.next_out,n),t.strm.next_out+=n,t.strm.avail_out-=n,t.strm.total_out+=n)}while(o===0);return s-=t.strm.avail_in,s&&(s>=t.w_size?(t.matches=2,t.window.set(t.strm.input.subarray(t.strm.next_in-t.w_size,t.strm.next_in),0),t.strstart=t.w_size,t.insert=t.strstart):(t.window_size-t.strstart<=s&&(t.strstart-=t.w_size,t.window.set(t.window.subarray(t.w_size,t.w_size+t.strstart),0),t.matches<2&&t.matches++,t.insert>t.strstart&&(t.insert=t.strstart)),t.window.set(t.strm.input.subarray(t.strm.next_in-s,t.strm.next_in),t.strstart),t.strstart+=s,t.insert+=s>t.w_size-t.insert?t.w_size-t.insert:s),t.block_start=t.strstart),t.high_water<t.strstart&&(t.high_water=t.strstart),o?Xa:e!==Zn&&e!==ur&&t.strm.avail_in===0&&t.strstart===t.block_start?Wa:(a=t.window_size-t.strstart,t.strm.avail_in>a&&t.block_start>=t.w_size&&(t.block_start-=t.w_size,t.strstart-=t.w_size,t.window.set(t.window.subarray(t.w_size,t.w_size+t.strstart),0),t.matches<2&&t.matches++,a+=t.w_size,t.insert>t.strstart&&(t.insert=t.strstart)),a>t.strm.avail_in&&(a=t.strm.avail_in),a&&(Mf(t.strm,t.window,t.strstart,a),t.strstart+=a,t.insert+=a>t.w_size-t.insert?t.w_size-t.insert:a),t.high_water<t.strstart&&(t.high_water=t.strstart),a=t.bi_valid+42>>3,a=t.pending_buf_size-a>65535?65535:t.pending_buf_size-a,r=a>t.w_size?t.w_size:a,i=t.strstart-t.block_start,(i>=r||(i||e===ur)&&e!==Zn&&t.strm.avail_in===0&&i<=a)&&(n=i>a?a:i,o=e===ur&&t.strm.avail_in===0&&n===i?1:0,bf(t,t.block_start,n,o),t.block_start+=n,Kt(t.strm)),o?Fi:bt)},sf=(t,e)=>{let r,n;for(;;){if(t.lookahead<Hr){if(Va(t),t.lookahead<Hr&&e===Zn)return bt;if(t.lookahead===0)break}if(r=0,t.lookahead>=j&&(t.ins_h=jn(t,t.ins_h,t.window[t.strstart+j-1]),r=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),r!==0&&t.strstart-r<=t.w_size-Hr&&(t.match_length=w0(t,r)),t.match_length>=j)if(n=qn(t,t.strstart-t.match_start,t.match_length-j),t.lookahead-=t.match_length,t.match_length<=t.max_lazy_match&&t.lookahead>=j){t.match_length--;do t.strstart++,t.ins_h=jn(t,t.ins_h,t.window[t.strstart+j-1]),r=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart;while(--t.match_length!==0);t.strstart++}else t.strstart+=t.match_length,t.match_length=0,t.ins_h=t.window[t.strstart],t.ins_h=jn(t,t.ins_h,t.window[t.strstart+1]);else n=qn(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++;if(n&&(Yt(t,!1),t.strm.avail_out===0))return bt}return t.insert=t.strstart<j-1?t.strstart:j-1,e===ur?(Yt(t,!0),t.strm.avail_out===0?Fi:Xa):t.sym_next&&(Yt(t,!1),t.strm.avail_out===0)?bt:Wa},za=(t,e)=>{let r,n,i;for(;;){if(t.lookahead<Hr){if(Va(t),t.lookahead<Hr&&e===Zn)return bt;if(t.lookahead===0)break}if(r=0,t.lookahead>=j&&(t.ins_h=jn(t,t.ins_h,t.window[t.strstart+j-1]),r=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),t.prev_length=t.match_length,t.prev_match=t.match_start,t.match_length=j-1,r!==0&&t.prev_length<t.max_lazy_match&&t.strstart-r<=t.w_size-Hr&&(t.match_length=w0(t,r),t.match_length<=5&&(t.strategy===rS||t.match_length===j&&t.strstart-t.match_start>4096)&&(t.match_length=j-1)),t.prev_length>=j&&t.match_length<=t.prev_length){i=t.strstart+t.lookahead-j,n=qn(t,t.strstart-1-t.prev_match,t.prev_length-j),t.lookahead-=t.prev_length-1,t.prev_length-=2;do++t.strstart<=i&&(t.ins_h=jn(t,t.ins_h,t.window[t.strstart+j-1]),r=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart);while(--t.prev_length!==0);if(t.match_available=0,t.match_length=j-1,t.strstart++,n&&(Yt(t,!1),t.strm.avail_out===0))return bt}else if(t.match_available){if(n=qn(t,0,t.window[t.strstart-1]),n&&Yt(t,!1),t.strstart++,t.lookahead--,t.strm.avail_out===0)return bt}else t.match_available=1,t.strstart++,t.lookahead--}return t.match_available&&(n=qn(t,0,t.window[t.strstart-1]),t.match_available=0),t.insert=t.strstart<j-1?t.strstart:j-1,e===ur?(Yt(t,!0),t.strm.avail_out===0?Fi:Xa):t.sym_next&&(Yt(t,!1),t.strm.avail_out===0)?bt:Wa},vS=(t,e)=>{let r,n,i,a,o=t.window;for(;;){if(t.lookahead<=Yn){if(Va(t),t.lookahead<=Yn&&e===Zn)return bt;if(t.lookahead===0)break}if(t.match_length=0,t.lookahead>=j&&t.strstart>0&&(i=t.strstart-1,n=o[i],n===o[++i]&&n===o[++i]&&n===o[++i])){a=t.strstart+Yn;do;while(n===o[++i]&&n===o[++i]&&n===o[++i]&&n===o[++i]&&n===o[++i]&&n===o[++i]&&n===o[++i]&&n===o[++i]&&i<a);t.match_length=Yn-(a-i),t.match_length>t.lookahead&&(t.match_length=t.lookahead)}if(t.match_length>=j?(r=qn(t,1,t.match_length-j),t.lookahead-=t.match_length,t.strstart+=t.match_length,t.match_length=0):(r=qn(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++),r&&(Yt(t,!1),t.strm.avail_out===0))return bt}return t.insert=0,e===ur?(Yt(t,!0),t.strm.avail_out===0?Fi:Xa):t.sym_next&&(Yt(t,!1),t.strm.avail_out===0)?bt:Wa},_S=(t,e)=>{let r;for(;;){if(t.lookahead===0&&(Va(t),t.lookahead===0)){if(e===Zn)return bt;break}if(t.match_length=0,r=qn(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++,r&&(Yt(t,!1),t.strm.avail_out===0))return bt}return t.insert=0,e===ur?(Yt(t,!0),t.strm.avail_out===0?Fi:Xa):t.sym_next&&(Yt(t,!1),t.strm.avail_out===0)?bt:Wa};function Nr(t,e,r,n,i){this.good_length=t,this.max_lazy=e,this.nice_length=r,this.max_chain=n,this.func=i}var ws=[new Nr(0,0,0,0,M0),new Nr(4,4,8,4,sf),new Nr(4,5,16,8,sf),new Nr(4,6,32,32,sf),new Nr(4,4,16,16,za),new Nr(8,16,32,32,za),new Nr(8,16,128,128,za),new Nr(8,32,128,256,za),new Nr(32,128,258,1024,za),new Nr(32,258,258,4096,za)],SS=t=>{t.window_size=2*t.w_size,Kn(t.head),t.max_lazy_match=ws[t.level].max_lazy,t.good_match=ws[t.level].good_length,t.nice_match=ws[t.level].nice_length,t.max_chain_length=ws[t.level].max_chain,t.strstart=0,t.block_start=0,t.lookahead=0,t.insert=0,t.match_length=t.prev_length=j-1,t.match_available=0,t.ins_h=0};function wS(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=Xc,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Uint16Array(mS*2),this.dyn_dtree=new Uint16Array((2*fS+1)*2),this.bl_tree=new Uint16Array((2*hS+1)*2),Kn(this.dyn_ltree),Kn(this.dyn_dtree),Kn(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(pS+1),this.heap=new Uint16Array(2*xf+1),Kn(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(2*xf+1),Kn(this.depth),this.sym_buf=0,this.lit_bufsize=0,this.sym_next=0,this.sym_end=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}var ks=t=>{if(!t)return 1;let e=t.state;return!e||e.strm!==t||e.status!==Ga&&e.status!==Pf&&e.status!==vf&&e.status!==_f&&e.status!==Sf&&e.status!==wf&&e.status!==Ri&&e.status!==Ss?1:0},A0=t=>{if(ks(t))return Ci(t,Vr);t.total_in=t.total_out=0,t.data_type=oS;let e=t.state;return e.pending=0,e.pending_out=0,e.wrap<0&&(e.wrap=-e.wrap),e.status=e.wrap===2?Pf:e.wrap?Ga:Ri,t.adler=e.wrap===2?0:1,e.last_flush=-2,q_(e),et},E0=t=>{let e=A0(t);return e===et&&SS(t.state),e},MS=(t,e)=>ks(t)||t.state.wrap!==2?Vr:(t.state.gzhead=e,et),T0=(t,e,r,n,i,a)=>{if(!t)return Vr;let o=1;if(e===tS&&(e=6),n<0?(o=0,n=-n):n>15&&(o=2,n-=16),i<1||i>sS||r!==Xc||n<8||n>15||e<0||e>9||a<0||a>iS||n===8&&o!==1)return Ci(t,Vr);n===8&&(n=9);let s=new wS;return t.state=s,s.strm=t,s.status=Ga,s.wrap=o,s.gzhead=null,s.w_bits=n,s.w_size=1<<s.w_bits,s.w_mask=s.w_size-1,s.hash_bits=i+7,s.hash_size=1<<s.hash_bits,s.hash_mask=s.hash_size-1,s.hash_shift=~~((s.hash_bits+j-1)/j),s.window=new Uint8Array(s.w_size*2),s.head=new Uint16Array(s.hash_size),s.prev=new Uint16Array(s.w_size),s.lit_bufsize=1<<i+6,s.pending_buf_size=s.lit_bufsize*4,s.pending_buf=new Uint8Array(s.pending_buf_size),s.sym_buf=s.lit_bufsize,s.sym_end=(s.lit_bufsize-1)*3,s.level=e,s.strategy=a,s.method=r,E0(t)},AS=(t,e)=>T0(t,e,Xc,lS,cS,aS),ES=(t,e)=>{if(ks(t)||e>Pp||e<0)return t?Ci(t,Vr):Vr;let r=t.state;if(!t.output||t.avail_in!==0&&!t.input||r.status===Ss&&e!==ur)return Ci(t,t.avail_out===0?of:Vr);let n=r.last_flush;if(r.last_flush=e,r.pending!==0){if(Kt(t),t.avail_out===0)return r.last_flush=-1,et}else if(t.avail_in===0&&Cp(e)<=Cp(n)&&e!==ur)return Ci(t,of);if(r.status===Ss&&t.avail_in!==0)return Ci(t,of);if(r.status===Ga&&r.wrap===0&&(r.status=Ri),r.status===Ga){let i=Xc+(r.w_bits-8<<4)<<8,a=-1;if(r.strategy>=kc||r.level<2?a=0:r.level<6?a=1:r.level===6?a=2:a=3,i|=a<<6,r.strstart!==0&&(i|=gS),i+=31-i%31,_s(r,i),r.strstart!==0&&(_s(r,t.adler>>>16),_s(r,t.adler&65535)),t.adler=1,r.status=Ri,Kt(t),r.pending!==0)return r.last_flush=-1,et}if(r.status===Pf){if(t.adler=0,ie(r,31),ie(r,139),ie(r,8),r.gzhead)ie(r,(r.gzhead.text?1:0)+(r.gzhead.hcrc?2:0)+(r.gzhead.extra?4:0)+(r.gzhead.name?8:0)+(r.gzhead.comment?16:0)),ie(r,r.gzhead.time&255),ie(r,r.gzhead.time>>8&255),ie(r,r.gzhead.time>>16&255),ie(r,r.gzhead.time>>24&255),ie(r,r.level===9?2:r.strategy>=kc||r.level<2?4:0),ie(r,r.gzhead.os&255),r.gzhead.extra&&r.gzhead.extra.length&&(ie(r,r.gzhead.extra.length&255),ie(r,r.gzhead.extra.length>>8&255)),r.gzhead.hcrc&&(t.adler=Ne(t.adler,r.pending_buf,r.pending,0)),r.gzindex=0,r.status=vf;else if(ie(r,0),ie(r,0),ie(r,0),ie(r,0),ie(r,0),ie(r,r.level===9?2:r.strategy>=kc||r.level<2?4:0),ie(r,yS),r.status=Ri,Kt(t),r.pending!==0)return r.last_flush=-1,et}if(r.status===vf){if(r.gzhead.extra){let i=r.pending,a=(r.gzhead.extra.length&65535)-r.gzindex;for(;r.pending+a>r.pending_buf_size;){let s=r.pending_buf_size-r.pending;if(r.pending_buf.set(r.gzhead.extra.subarray(r.gzindex,r.gzindex+s),r.pending),r.pending=r.pending_buf_size,r.gzhead.hcrc&&r.pending>i&&(t.adler=Ne(t.adler,r.pending_buf,r.pending-i,i)),r.gzindex+=s,Kt(t),r.pending!==0)return r.last_flush=-1,et;i=0,a-=s}let o=new Uint8Array(r.gzhead.extra);r.pending_buf.set(o.subarray(r.gzindex,r.gzindex+a),r.pending),r.pending+=a,r.gzhead.hcrc&&r.pending>i&&(t.adler=Ne(t.adler,r.pending_buf,r.pending-i,i)),r.gzindex=0}r.status=_f}if(r.status===_f){if(r.gzhead.name){let i=r.pending,a;do{if(r.pending===r.pending_buf_size){if(r.gzhead.hcrc&&r.pending>i&&(t.adler=Ne(t.adler,r.pending_buf,r.pending-i,i)),Kt(t),r.pending!==0)return r.last_flush=-1,et;i=0}r.gzindex<r.gzhead.name.length?a=r.gzhead.name.charCodeAt(r.gzindex++)&255:a=0,ie(r,a)}while(a!==0);r.gzhead.hcrc&&r.pending>i&&(t.adler=Ne(t.adler,r.pending_buf,r.pending-i,i)),r.gzindex=0}r.status=Sf}if(r.status===Sf){if(r.gzhead.comment){let i=r.pending,a;do{if(r.pending===r.pending_buf_size){if(r.gzhead.hcrc&&r.pending>i&&(t.adler=Ne(t.adler,r.pending_buf,r.pending-i,i)),Kt(t),r.pending!==0)return r.last_flush=-1,et;i=0}r.gzindex<r.gzhead.comment.length?a=r.gzhead.comment.charCodeAt(r.gzindex++)&255:a=0,ie(r,a)}while(a!==0);r.gzhead.hcrc&&r.pending>i&&(t.adler=Ne(t.adler,r.pending_buf,r.pending-i,i))}r.status=wf}if(r.status===wf){if(r.gzhead.hcrc){if(r.pending+2>r.pending_buf_size&&(Kt(t),r.pending!==0))return r.last_flush=-1,et;ie(r,t.adler&255),ie(r,t.adler>>8&255),t.adler=0}if(r.status=Ri,Kt(t),r.pending!==0)return r.last_flush=-1,et}if(t.avail_in!==0||r.lookahead!==0||e!==Zn&&r.status!==Ss){let i=r.level===0?M0(r,e):r.strategy===kc?_S(r,e):r.strategy===nS?vS(r,e):ws[r.level].func(r,e);if((i===Fi||i===Xa)&&(r.status=Ss),i===bt||i===Fi)return t.avail_out===0&&(r.last_flush=-1),et;if(i===Wa&&(e===Q_?j_(r):e!==Pp&&(bf(r,0,0,!1),e===J_&&(Kn(r.head),r.lookahead===0&&(r.strstart=0,r.block_start=0,r.insert=0))),Kt(t),t.avail_out===0))return r.last_flush=-1,et}return e!==ur?et:r.wrap<=0?Rp:(r.wrap===2?(ie(r,t.adler&255),ie(r,t.adler>>8&255),ie(r,t.adler>>16&255),ie(r,t.adler>>24&255),ie(r,t.total_in&255),ie(r,t.total_in>>8&255),ie(r,t.total_in>>16&255),ie(r,t.total_in>>24&255)):(_s(r,t.adler>>>16),_s(r,t.adler&65535)),Kt(t),r.wrap>0&&(r.wrap=-r.wrap),r.pending!==0?et:Rp)},TS=t=>{if(ks(t))return Vr;let e=t.state.status;return t.state=null,e===Ri?Ci(t,eS):et},LS=(t,e)=>{let r=e.length;if(ks(t))return Vr;let n=t.state,i=n.wrap;if(i===2||i===1&&n.status!==Ga||n.lookahead)return Vr;if(i===1&&(t.adler=Cs(t.adler,e,r,0)),n.wrap=0,r>=n.w_size){i===0&&(Kn(n.head),n.strstart=0,n.block_start=0,n.insert=0);let c=new Uint8Array(n.w_size);c.set(e.subarray(r-n.w_size,r),0),e=c,r=n.w_size}let a=t.avail_in,o=t.next_in,s=t.input;for(t.avail_in=r,t.next_in=0,t.input=e,Va(n);n.lookahead>=j;){let c=n.strstart,l=n.lookahead-(j-1);do n.ins_h=jn(n,n.ins_h,n.window[c+j-1]),n.prev[c&n.w_mask]=n.head[n.ins_h],n.head[n.ins_h]=c,c++;while(--l);n.strstart=c,n.lookahead=j-1,Va(n)}return n.strstart+=n.lookahead,n.block_start=n.strstart,n.insert=n.lookahead,n.lookahead=0,n.match_length=n.prev_length=j-1,n.match_available=0,t.next_in=o,t.input=s,t.avail_in=a,n.wrap=i,et},PS=AS,RS=T0,CS=E0,BS=A0,FS=MS,IS=ES,DS=TS,kS=LS,US="pako deflate (from Nodeca project)",As={deflateInit:PS,deflateInit2:RS,deflateReset:CS,deflateResetKeep:BS,deflateSetHeader:FS,deflate:IS,deflateEnd:DS,deflateSetDictionary:kS,deflateInfo:US},zS=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),OS=function(t){let e=Array.prototype.slice.call(arguments,1);for(;e.length;){let r=e.shift();if(r){if(typeof r!="object")throw new TypeError(r+"must be non-object");for(let n in r)zS(r,n)&&(t[n]=r[n])}}return t},NS=t=>{let e=0;for(let n=0,i=t.length;n<i;n++)e+=t[n].length;let r=new Uint8Array(e);for(let n=0,i=0,a=t.length;n<a;n++){let o=t[n];r.set(o,i),i+=o.length}return r},$c={assign:OS,flattenChunks:NS},L0=!0;try{String.fromCharCode.apply(null,new Uint8Array(1))}catch{L0=!1}var Bs=new Uint8Array(256);for(let t=0;t<256;t++)Bs[t]=t>=252?6:t>=248?5:t>=240?4:t>=224?3:t>=192?2:1;Bs[254]=Bs[254]=1;var GS=t=>{if(typeof TextEncoder=="function"&&TextEncoder.prototype.encode)return new TextEncoder().encode(t);let e,r,n,i,a,o=t.length,s=0;for(i=0;i<o;i++)r=t.charCodeAt(i),(r&64512)===55296&&i+1<o&&(n=t.charCodeAt(i+1),(n&64512)===56320&&(r=65536+(r-55296<<10)+(n-56320),i++)),s+=r<128?1:r<2048?2:r<65536?3:4;for(e=new Uint8Array(s),a=0,i=0;a<s;i++)r=t.charCodeAt(i),(r&64512)===55296&&i+1<o&&(n=t.charCodeAt(i+1),(n&64512)===56320&&(r=65536+(r-55296<<10)+(n-56320),i++)),r<128?e[a++]=r:r<2048?(e[a++]=192|r>>>6,e[a++]=128|r&63):r<65536?(e[a++]=224|r>>>12,e[a++]=128|r>>>6&63,e[a++]=128|r&63):(e[a++]=240|r>>>18,e[a++]=128|r>>>12&63,e[a++]=128|r>>>6&63,e[a++]=128|r&63);return e},VS=(t,e)=>{if(e<65534&&t.subarray&&L0)return String.fromCharCode.apply(null,t.length===e?t:t.subarray(0,e));let r="";for(let n=0;n<e;n++)r+=String.fromCharCode(t[n]);return r},HS=(t,e)=>{let r=e||t.length;if(typeof TextDecoder=="function"&&TextDecoder.prototype.decode)return new TextDecoder().decode(t.subarray(0,e));let n,i,a=new Array(r*2);for(i=0,n=0;n<r;){let o=t[n++];if(o<128){a[i++]=o;continue}let s=Bs[o];if(s>4){a[i++]=65533,n+=s-1;continue}for(o&=s===2?31:s===3?15:7;s>1&&n<r;)o=o<<6|t[n++]&63,s--;if(s>1){a[i++]=65533;continue}o<65536?a[i++]=o:(o-=65536,a[i++]=55296|o>>10&1023,a[i++]=56320|o&1023)}return VS(a,i)},WS=(t,e)=>{e=e||t.length,e>t.length&&(e=t.length);let r=e-1;for(;r>=0&&(t[r]&192)===128;)r--;return r<0||r===0?e:r+Bs[t[r]]>e?r:e},Fs={string2buf:GS,buf2string:HS,utf8border:WS};function XS(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}var P0=XS,R0=Object.prototype.toString,{Z_NO_FLUSH:$S,Z_SYNC_FLUSH:KS,Z_FULL_FLUSH:YS,Z_FINISH:qS,Z_OK:Hc,Z_STREAM_END:ZS,Z_DEFAULT_COMPRESSION:jS,Z_DEFAULT_STRATEGY:QS,Z_DEFLATED:JS}=Di;function Us(t){this.options=$c.assign({level:jS,method:JS,chunkSize:16384,windowBits:15,memLevel:8,strategy:QS},t||{});let e=this.options;e.raw&&e.windowBits>0?e.windowBits=-e.windowBits:e.gzip&&e.windowBits>0&&e.windowBits<16&&(e.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new P0,this.strm.avail_out=0;let r=As.deflateInit2(this.strm,e.level,e.method,e.windowBits,e.memLevel,e.strategy);if(r!==Hc)throw new Error(Bi[r]);if(e.header&&As.deflateSetHeader(this.strm,e.header),e.dictionary){let n;if(typeof e.dictionary=="string"?n=Fs.string2buf(e.dictionary):R0.call(e.dictionary)==="[object ArrayBuffer]"?n=new Uint8Array(e.dictionary):n=e.dictionary,r=As.deflateSetDictionary(this.strm,n),r!==Hc)throw new Error(Bi[r]);this._dict_set=!0}}Us.prototype.push=function(t,e){let r=this.strm,n=this.options.chunkSize,i,a;if(this.ended)return!1;for(e===~~e?a=e:a=e===!0?qS:$S,typeof t=="string"?r.input=Fs.string2buf(t):R0.call(t)==="[object ArrayBuffer]"?r.input=new Uint8Array(t):r.input=t,r.next_in=0,r.avail_in=r.input.length;;){if(r.avail_out===0&&(r.output=new Uint8Array(n),r.next_out=0,r.avail_out=n),(a===KS||a===YS)&&r.avail_out<=6){this.onData(r.output.subarray(0,r.next_out)),r.avail_out=0;continue}if(i=As.deflate(r,a),i===ZS)return r.next_out>0&&this.onData(r.output.subarray(0,r.next_out)),i=As.deflateEnd(this.strm),this.onEnd(i),this.ended=!0,i===Hc;if(r.avail_out===0){this.onData(r.output);continue}if(a>0&&r.next_out>0){this.onData(r.output.subarray(0,r.next_out)),r.avail_out=0;continue}if(r.avail_in===0)break}return!0};Us.prototype.onData=function(t){this.chunks.push(t)};Us.prototype.onEnd=function(t){t===Hc&&(this.result=$c.flattenChunks(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg};function Rf(t,e){let r=new Us(e);if(r.push(t,!0),r.err)throw r.msg||Bi[r.err];return r.result}function ew(t,e){return e=e||{},e.raw=!0,Rf(t,e)}function tw(t,e){return e=e||{},e.gzip=!0,Rf(t,e)}var rw=Us,nw=Rf,iw=ew,aw=tw,ow=Di,sw={Deflate:rw,deflate:nw,deflateRaw:iw,gzip:aw,constants:ow},Uc=16209,lw=16191,cw=function(e,r){let n,i,a,o,s,c,l,u,d,f,h,m,g,p,y,v,b,x,_,w,S,A,T,M,P=e.state;n=e.next_in,T=e.input,i=n+(e.avail_in-5),a=e.next_out,M=e.output,o=a-(r-e.avail_out),s=a+(e.avail_out-257),c=P.dmax,l=P.wsize,u=P.whave,d=P.wnext,f=P.window,h=P.hold,m=P.bits,g=P.lencode,p=P.distcode,y=(1<<P.lenbits)-1,v=(1<<P.distbits)-1;e:do{m<15&&(h+=T[n++]<<m,m+=8,h+=T[n++]<<m,m+=8),b=g[h&y];t:for(;;){if(x=b>>>24,h>>>=x,m-=x,x=b>>>16&255,x===0)M[a++]=b&65535;else if(x&16){_=b&65535,x&=15,x&&(m<x&&(h+=T[n++]<<m,m+=8),_+=h&(1<<x)-1,h>>>=x,m-=x),m<15&&(h+=T[n++]<<m,m+=8,h+=T[n++]<<m,m+=8),b=p[h&v];r:for(;;){if(x=b>>>24,h>>>=x,m-=x,x=b>>>16&255,x&16){if(w=b&65535,x&=15,m<x&&(h+=T[n++]<<m,m+=8,m<x&&(h+=T[n++]<<m,m+=8)),w+=h&(1<<x)-1,w>c){e.msg="invalid distance too far back",P.mode=Uc;break e}if(h>>>=x,m-=x,x=a-o,w>x){if(x=w-x,x>u&&P.sane){e.msg="invalid distance too far back",P.mode=Uc;break e}if(S=0,A=f,d===0){if(S+=l-x,x<_){_-=x;do M[a++]=f[S++];while(--x);S=a-w,A=M}}else if(d<x){if(S+=l+d-x,x-=d,x<_){_-=x;do M[a++]=f[S++];while(--x);if(S=0,d<_){x=d,_-=x;do M[a++]=f[S++];while(--x);S=a-w,A=M}}}else if(S+=d-x,x<_){_-=x;do M[a++]=f[S++];while(--x);S=a-w,A=M}for(;_>2;)M[a++]=A[S++],M[a++]=A[S++],M[a++]=A[S++],_-=3;_&&(M[a++]=A[S++],_>1&&(M[a++]=A[S++]))}else{S=a-w;do M[a++]=M[S++],M[a++]=M[S++],M[a++]=M[S++],_-=3;while(_>2);_&&(M[a++]=M[S++],_>1&&(M[a++]=M[S++]))}}else if((x&64)===0){b=p[(b&65535)+(h&(1<<x)-1)];continue r}else{e.msg="invalid distance code",P.mode=Uc;break e}break}}else if((x&64)===0){b=g[(b&65535)+(h&(1<<x)-1)];continue t}else if(x&32){P.mode=lw;break e}else{e.msg="invalid literal/length code",P.mode=Uc;break e}break}}while(n<i&&a<s);_=m>>3,n-=_,m-=_<<3,h&=(1<<m)-1,e.next_in=n,e.next_out=a,e.avail_in=n<i?5+(i-n):5-(n-i),e.avail_out=a<s?257+(s-a):257-(a-s),P.hold=h,P.bits=m},Oa=15,Bp=852,Fp=592,Ip=0,lf=1,Dp=2,uw=new Uint16Array([3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0]),dw=new Uint8Array([16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78]),fw=new Uint16Array([1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0]),hw=new Uint8Array([16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64]),mw=(t,e,r,n,i,a,o,s)=>{let c=s.bits,l=0,u=0,d=0,f=0,h=0,m=0,g=0,p=0,y=0,v=0,b,x,_,w,S,A=null,T,M=new Uint16Array(Oa+1),P=new Uint16Array(Oa+1),I=null,D,B,O;for(l=0;l<=Oa;l++)M[l]=0;for(u=0;u<n;u++)M[e[r+u]]++;for(h=c,f=Oa;f>=1&&M[f]===0;f--);if(h>f&&(h=f),f===0)return i[a++]=1<<24|64<<16|0,i[a++]=1<<24|64<<16|0,s.bits=1,0;for(d=1;d<f&&M[d]===0;d++);for(h<d&&(h=d),p=1,l=1;l<=Oa;l++)if(p<<=1,p-=M[l],p<0)return-1;if(p>0&&(t===Ip||f!==1))return-1;for(P[1]=0,l=1;l<Oa;l++)P[l+1]=P[l]+M[l];for(u=0;u<n;u++)e[r+u]!==0&&(o[P[e[r+u]]++]=u);if(t===Ip?(A=I=o,T=20):t===lf?(A=uw,I=dw,T=257):(A=fw,I=hw,T=0),v=0,u=0,l=d,S=a,m=h,g=0,_=-1,y=1<<h,w=y-1,t===lf&&y>Bp||t===Dp&&y>Fp)return 1;for(;;){D=l-g,o[u]+1<T?(B=0,O=o[u]):o[u]>=T?(B=I[o[u]-T],O=A[o[u]-T]):(B=96,O=0),b=1<<l-g,x=1<<m,d=x;do x-=b,i[S+(v>>g)+x]=D<<24|B<<16|O|0;while(x!==0);for(b=1<<l-1;v&b;)b>>=1;if(b!==0?(v&=b-1,v+=b):v=0,u++,--M[l]===0){if(l===f)break;l=e[r+o[u]]}if(l>h&&(v&w)!==_){for(g===0&&(g=h),S+=d,m=l-g,p=1<<m;m+g<f&&(p-=M[m+g],!(p<=0));)m++,p<<=1;if(y+=1<<m,t===lf&&y>Bp||t===Dp&&y>Fp)return 1;_=v&w,i[_]=h<<24|m<<16|S-a|0}}return v!==0&&(i[S+v]=l-g<<24|64<<16|0),s.bits=h,0},Es=mw,pw=0,C0=1,B0=2,{Z_FINISH:kp,Z_BLOCK:gw,Z_TREES:zc,Z_OK:Ii,Z_STREAM_END:yw,Z_NEED_DICT:bw,Z_STREAM_ERROR:dr,Z_DATA_ERROR:F0,Z_MEM_ERROR:I0,Z_BUF_ERROR:xw,Z_DEFLATED:Up}=Di,Kc=16180,zp=16181,Op=16182,Np=16183,Gp=16184,Vp=16185,Hp=16186,Wp=16187,Xp=16188,$p=16189,Wc=16190,dn=16191,cf=16192,Kp=16193,uf=16194,Yp=16195,qp=16196,Zp=16197,jp=16198,Oc=16199,Nc=16200,Qp=16201,Jp=16202,e0=16203,t0=16204,r0=16205,df=16206,n0=16207,i0=16208,we=16209,D0=16210,k0=16211,vw=852,_w=592,Sw=15,ww=Sw,a0=t=>(t>>>24&255)+(t>>>8&65280)+((t&65280)<<8)+((t&255)<<24);function Mw(){this.strm=null,this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}var ki=t=>{if(!t)return 1;let e=t.state;return!e||e.strm!==t||e.mode<Kc||e.mode>k0?1:0},U0=t=>{if(ki(t))return dr;let e=t.state;return t.total_in=t.total_out=e.total=0,t.msg="",e.wrap&&(t.adler=e.wrap&1),e.mode=Kc,e.last=0,e.havedict=0,e.flags=-1,e.dmax=32768,e.head=null,e.hold=0,e.bits=0,e.lencode=e.lendyn=new Int32Array(vw),e.distcode=e.distdyn=new Int32Array(_w),e.sane=1,e.back=-1,Ii},z0=t=>{if(ki(t))return dr;let e=t.state;return e.wsize=0,e.whave=0,e.wnext=0,U0(t)},O0=(t,e)=>{let r;if(ki(t))return dr;let n=t.state;return e<0?(r=0,e=-e):(r=(e>>4)+5,e<48&&(e&=15)),e&&(e<8||e>15)?dr:(n.window!==null&&n.wbits!==e&&(n.window=null),n.wrap=r,n.wbits=e,z0(t))},N0=(t,e)=>{if(!t)return dr;let r=new Mw;t.state=r,r.strm=t,r.window=null,r.mode=Kc;let n=O0(t,e);return n!==Ii&&(t.state=null),n},Aw=t=>N0(t,ww),o0=!0,ff,hf,Ew=t=>{if(o0){ff=new Int32Array(512),hf=new Int32Array(32);let e=0;for(;e<144;)t.lens[e++]=8;for(;e<256;)t.lens[e++]=9;for(;e<280;)t.lens[e++]=7;for(;e<288;)t.lens[e++]=8;for(Es(C0,t.lens,0,288,ff,0,t.work,{bits:9}),e=0;e<32;)t.lens[e++]=5;Es(B0,t.lens,0,32,hf,0,t.work,{bits:5}),o0=!1}t.lencode=ff,t.lenbits=9,t.distcode=hf,t.distbits=5},G0=(t,e,r,n)=>{let i,a=t.state;return a.window===null&&(a.wsize=1<<a.wbits,a.wnext=0,a.whave=0,a.window=new Uint8Array(a.wsize)),n>=a.wsize?(a.window.set(e.subarray(r-a.wsize,r),0),a.wnext=0,a.whave=a.wsize):(i=a.wsize-a.wnext,i>n&&(i=n),a.window.set(e.subarray(r-n,r-n+i),a.wnext),n-=i,n?(a.window.set(e.subarray(r-n,r),0),a.wnext=n,a.whave=a.wsize):(a.wnext+=i,a.wnext===a.wsize&&(a.wnext=0),a.whave<a.wsize&&(a.whave+=i))),0},Tw=(t,e)=>{let r,n,i,a,o,s,c,l,u,d,f,h,m,g,p=0,y,v,b,x,_,w,S,A,T=new Uint8Array(4),M,P,I=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(ki(t)||!t.output||!t.input&&t.avail_in!==0)return dr;r=t.state,r.mode===dn&&(r.mode=cf),o=t.next_out,i=t.output,c=t.avail_out,a=t.next_in,n=t.input,s=t.avail_in,l=r.hold,u=r.bits,d=s,f=c,A=Ii;e:for(;;)switch(r.mode){case Kc:if(r.wrap===0){r.mode=cf;break}for(;u<16;){if(s===0)break e;s--,l+=n[a++]<<u,u+=8}if(r.wrap&2&&l===35615){r.wbits===0&&(r.wbits=15),r.check=0,T[0]=l&255,T[1]=l>>>8&255,r.check=Ne(r.check,T,2,0),l=0,u=0,r.mode=zp;break}if(r.head&&(r.head.done=!1),!(r.wrap&1)||(((l&255)<<8)+(l>>8))%31){t.msg="incorrect header check",r.mode=we;break}if((l&15)!==Up){t.msg="unknown compression method",r.mode=we;break}if(l>>>=4,u-=4,S=(l&15)+8,r.wbits===0&&(r.wbits=S),S>15||S>r.wbits){t.msg="invalid window size",r.mode=we;break}r.dmax=1<<r.wbits,r.flags=0,t.adler=r.check=1,r.mode=l&512?$p:dn,l=0,u=0;break;case zp:for(;u<16;){if(s===0)break e;s--,l+=n[a++]<<u,u+=8}if(r.flags=l,(r.flags&255)!==Up){t.msg="unknown compression method",r.mode=we;break}if(r.flags&57344){t.msg="unknown header flags set",r.mode=we;break}r.head&&(r.head.text=l>>8&1),r.flags&512&&r.wrap&4&&(T[0]=l&255,T[1]=l>>>8&255,r.check=Ne(r.check,T,2,0)),l=0,u=0,r.mode=Op;case Op:for(;u<32;){if(s===0)break e;s--,l+=n[a++]<<u,u+=8}r.head&&(r.head.time=l),r.flags&512&&r.wrap&4&&(T[0]=l&255,T[1]=l>>>8&255,T[2]=l>>>16&255,T[3]=l>>>24&255,r.check=Ne(r.check,T,4,0)),l=0,u=0,r.mode=Np;case Np:for(;u<16;){if(s===0)break e;s--,l+=n[a++]<<u,u+=8}r.head&&(r.head.xflags=l&255,r.head.os=l>>8),r.flags&512&&r.wrap&4&&(T[0]=l&255,T[1]=l>>>8&255,r.check=Ne(r.check,T,2,0)),l=0,u=0,r.mode=Gp;case Gp:if(r.flags&1024){for(;u<16;){if(s===0)break e;s--,l+=n[a++]<<u,u+=8}r.length=l,r.head&&(r.head.extra_len=l),r.flags&512&&r.wrap&4&&(T[0]=l&255,T[1]=l>>>8&255,r.check=Ne(r.check,T,2,0)),l=0,u=0}else r.head&&(r.head.extra=null);r.mode=Vp;case Vp:if(r.flags&1024&&(h=r.length,h>s&&(h=s),h&&(r.head&&(S=r.head.extra_len-r.length,r.head.extra||(r.head.extra=new Uint8Array(r.head.extra_len)),r.head.extra.set(n.subarray(a,a+h),S)),r.flags&512&&r.wrap&4&&(r.check=Ne(r.check,n,h,a)),s-=h,a+=h,r.length-=h),r.length))break e;r.length=0,r.mode=Hp;case Hp:if(r.flags&2048){if(s===0)break e;h=0;do S=n[a+h++],r.head&&S&&r.length<65536&&(r.head.name+=String.fromCharCode(S));while(S&&h<s);if(r.flags&512&&r.wrap&4&&(r.check=Ne(r.check,n,h,a)),s-=h,a+=h,S)break e}else r.head&&(r.head.name=null);r.length=0,r.mode=Wp;case Wp:if(r.flags&4096){if(s===0)break e;h=0;do S=n[a+h++],r.head&&S&&r.length<65536&&(r.head.comment+=String.fromCharCode(S));while(S&&h<s);if(r.flags&512&&r.wrap&4&&(r.check=Ne(r.check,n,h,a)),s-=h,a+=h,S)break e}else r.head&&(r.head.comment=null);r.mode=Xp;case Xp:if(r.flags&512){for(;u<16;){if(s===0)break e;s--,l+=n[a++]<<u,u+=8}if(r.wrap&4&&l!==(r.check&65535)){t.msg="header crc mismatch",r.mode=we;break}l=0,u=0}r.head&&(r.head.hcrc=r.flags>>9&1,r.head.done=!0),t.adler=r.check=0,r.mode=dn;break;case $p:for(;u<32;){if(s===0)break e;s--,l+=n[a++]<<u,u+=8}t.adler=r.check=a0(l),l=0,u=0,r.mode=Wc;case Wc:if(r.havedict===0)return t.next_out=o,t.avail_out=c,t.next_in=a,t.avail_in=s,r.hold=l,r.bits=u,bw;t.adler=r.check=1,r.mode=dn;case dn:if(e===gw||e===zc)break e;case cf:if(r.last){l>>>=u&7,u-=u&7,r.mode=df;break}for(;u<3;){if(s===0)break e;s--,l+=n[a++]<<u,u+=8}switch(r.last=l&1,l>>>=1,u-=1,l&3){case 0:r.mode=Kp;break;case 1:if(Ew(r),r.mode=Oc,e===zc){l>>>=2,u-=2;break e}break;case 2:r.mode=qp;break;case 3:t.msg="invalid block type",r.mode=we}l>>>=2,u-=2;break;case Kp:for(l>>>=u&7,u-=u&7;u<32;){if(s===0)break e;s--,l+=n[a++]<<u,u+=8}if((l&65535)!==(l>>>16^65535)){t.msg="invalid stored block lengths",r.mode=we;break}if(r.length=l&65535,l=0,u=0,r.mode=uf,e===zc)break e;case uf:r.mode=Yp;case Yp:if(h=r.length,h){if(h>s&&(h=s),h>c&&(h=c),h===0)break e;i.set(n.subarray(a,a+h),o),s-=h,a+=h,c-=h,o+=h,r.length-=h;break}r.mode=dn;break;case qp:for(;u<14;){if(s===0)break e;s--,l+=n[a++]<<u,u+=8}if(r.nlen=(l&31)+257,l>>>=5,u-=5,r.ndist=(l&31)+1,l>>>=5,u-=5,r.ncode=(l&15)+4,l>>>=4,u-=4,r.nlen>286||r.ndist>30){t.msg="too many length or distance symbols",r.mode=we;break}r.have=0,r.mode=Zp;case Zp:for(;r.have<r.ncode;){for(;u<3;){if(s===0)break e;s--,l+=n[a++]<<u,u+=8}r.lens[I[r.have++]]=l&7,l>>>=3,u-=3}for(;r.have<19;)r.lens[I[r.have++]]=0;if(r.lencode=r.lendyn,r.lenbits=7,M={bits:r.lenbits},A=Es(pw,r.lens,0,19,r.lencode,0,r.work,M),r.lenbits=M.bits,A){t.msg="invalid code lengths set",r.mode=we;break}r.have=0,r.mode=jp;case jp:for(;r.have<r.nlen+r.ndist;){for(;p=r.lencode[l&(1<<r.lenbits)-1],y=p>>>24,v=p>>>16&255,b=p&65535,!(y<=u);){if(s===0)break e;s--,l+=n[a++]<<u,u+=8}if(b<16)l>>>=y,u-=y,r.lens[r.have++]=b;else{if(b===16){for(P=y+2;u<P;){if(s===0)break e;s--,l+=n[a++]<<u,u+=8}if(l>>>=y,u-=y,r.have===0){t.msg="invalid bit length repeat",r.mode=we;break}S=r.lens[r.have-1],h=3+(l&3),l>>>=2,u-=2}else if(b===17){for(P=y+3;u<P;){if(s===0)break e;s--,l+=n[a++]<<u,u+=8}l>>>=y,u-=y,S=0,h=3+(l&7),l>>>=3,u-=3}else{for(P=y+7;u<P;){if(s===0)break e;s--,l+=n[a++]<<u,u+=8}l>>>=y,u-=y,S=0,h=11+(l&127),l>>>=7,u-=7}if(r.have+h>r.nlen+r.ndist){t.msg="invalid bit length repeat",r.mode=we;break}for(;h--;)r.lens[r.have++]=S}}if(r.mode===we)break;if(r.lens[256]===0){t.msg="invalid code -- missing end-of-block",r.mode=we;break}if(r.lenbits=9,M={bits:r.lenbits},A=Es(C0,r.lens,0,r.nlen,r.lencode,0,r.work,M),r.lenbits=M.bits,A){t.msg="invalid literal/lengths set",r.mode=we;break}if(r.distbits=6,r.distcode=r.distdyn,M={bits:r.distbits},A=Es(B0,r.lens,r.nlen,r.ndist,r.distcode,0,r.work,M),r.distbits=M.bits,A){t.msg="invalid distances set",r.mode=we;break}if(r.mode=Oc,e===zc)break e;case Oc:r.mode=Nc;case Nc:if(s>=6&&c>=258){t.next_out=o,t.avail_out=c,t.next_in=a,t.avail_in=s,r.hold=l,r.bits=u,cw(t,f),o=t.next_out,i=t.output,c=t.avail_out,a=t.next_in,n=t.input,s=t.avail_in,l=r.hold,u=r.bits,r.mode===dn&&(r.back=-1);break}for(r.back=0;p=r.lencode[l&(1<<r.lenbits)-1],y=p>>>24,v=p>>>16&255,b=p&65535,!(y<=u);){if(s===0)break e;s--,l+=n[a++]<<u,u+=8}if(v&&(v&240)===0){for(x=y,_=v,w=b;p=r.lencode[w+((l&(1<<x+_)-1)>>x)],y=p>>>24,v=p>>>16&255,b=p&65535,!(x+y<=u);){if(s===0)break e;s--,l+=n[a++]<<u,u+=8}l>>>=x,u-=x,r.back+=x}if(l>>>=y,u-=y,r.back+=y,r.length=b,v===0){r.mode=r0;break}if(v&32){r.back=-1,r.mode=dn;break}if(v&64){t.msg="invalid literal/length code",r.mode=we;break}r.extra=v&15,r.mode=Qp;case Qp:if(r.extra){for(P=r.extra;u<P;){if(s===0)break e;s--,l+=n[a++]<<u,u+=8}r.length+=l&(1<<r.extra)-1,l>>>=r.extra,u-=r.extra,r.back+=r.extra}r.was=r.length,r.mode=Jp;case Jp:for(;p=r.distcode[l&(1<<r.distbits)-1],y=p>>>24,v=p>>>16&255,b=p&65535,!(y<=u);){if(s===0)break e;s--,l+=n[a++]<<u,u+=8}if((v&240)===0){for(x=y,_=v,w=b;p=r.distcode[w+((l&(1<<x+_)-1)>>x)],y=p>>>24,v=p>>>16&255,b=p&65535,!(x+y<=u);){if(s===0)break e;s--,l+=n[a++]<<u,u+=8}l>>>=x,u-=x,r.back+=x}if(l>>>=y,u-=y,r.back+=y,v&64){t.msg="invalid distance code",r.mode=we;break}r.offset=b,r.extra=v&15,r.mode=e0;case e0:if(r.extra){for(P=r.extra;u<P;){if(s===0)break e;s--,l+=n[a++]<<u,u+=8}r.offset+=l&(1<<r.extra)-1,l>>>=r.extra,u-=r.extra,r.back+=r.extra}if(r.offset>r.dmax){t.msg="invalid distance too far back",r.mode=we;break}r.mode=t0;case t0:if(c===0)break e;if(h=f-c,r.offset>h){if(h=r.offset-h,h>r.whave&&r.sane){t.msg="invalid distance too far back",r.mode=we;break}h>r.wnext?(h-=r.wnext,m=r.wsize-h):m=r.wnext-h,h>r.length&&(h=r.length),g=r.window}else g=i,m=o-r.offset,h=r.length;h>c&&(h=c),c-=h,r.length-=h;do i[o++]=g[m++];while(--h);r.length===0&&(r.mode=Nc);break;case r0:if(c===0)break e;i[o++]=r.length,c--,r.mode=Nc;break;case df:if(r.wrap){for(;u<32;){if(s===0)break e;s--,l|=n[a++]<<u,u+=8}if(f-=c,t.total_out+=f,r.total+=f,r.wrap&4&&f&&(t.adler=r.check=r.flags?Ne(r.check,i,f,o-f):Cs(r.check,i,f,o-f)),f=c,r.wrap&4&&(r.flags?l:a0(l))!==r.check){t.msg="incorrect data check",r.mode=we;break}l=0,u=0}r.mode=n0;case n0:if(r.wrap&&r.flags){for(;u<32;){if(s===0)break e;s--,l+=n[a++]<<u,u+=8}if(r.wrap&4&&l!==(r.total&4294967295)){t.msg="incorrect length check",r.mode=we;break}l=0,u=0}r.mode=i0;case i0:A=yw;break e;case we:A=F0;break e;case D0:return I0;case k0:default:return dr}return t.next_out=o,t.avail_out=c,t.next_in=a,t.avail_in=s,r.hold=l,r.bits=u,(r.wsize||f!==t.avail_out&&r.mode<we&&(r.mode<df||e!==kp))&&G0(t,t.output,t.next_out,f-t.avail_out),d-=t.avail_in,f-=t.avail_out,t.total_in+=d,t.total_out+=f,r.total+=f,r.wrap&4&&f&&(t.adler=r.check=r.flags?Ne(r.check,i,f,t.next_out-f):Cs(r.check,i,f,t.next_out-f)),t.data_type=r.bits+(r.last?64:0)+(r.mode===dn?128:0)+(r.mode===Oc||r.mode===uf?256:0),(d===0&&f===0||e===kp)&&A===Ii&&(A=xw),A},Lw=t=>{if(ki(t))return dr;let e=t.state;return e.window&&(e.window=null),t.state=null,Ii},Pw=(t,e)=>{if(ki(t))return dr;let r=t.state;return(r.wrap&2)===0?dr:(r.head=e,e.done=!1,Ii)},Rw=(t,e)=>{let r=e.length,n,i,a;return ki(t)||(n=t.state,n.wrap!==0&&n.mode!==Wc)?dr:n.mode===Wc&&(i=1,i=Cs(i,e,r,0),i!==n.check)?F0:(a=G0(t,e,r,r),a?(n.mode=D0,I0):(n.havedict=1,Ii))},Cw=z0,Bw=O0,Fw=U0,Iw=Aw,Dw=N0,kw=Tw,Uw=Lw,zw=Pw,Ow=Rw,Nw="pako inflate (from Nodeca project)",hn={inflateReset:Cw,inflateReset2:Bw,inflateResetKeep:Fw,inflateInit:Iw,inflateInit2:Dw,inflate:kw,inflateEnd:Uw,inflateGetHeader:zw,inflateSetDictionary:Ow,inflateInfo:Nw};function Gw(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}var Vw=Gw,V0=Object.prototype.toString,{Z_NO_FLUSH:Hw,Z_FINISH:Ww,Z_OK:Is,Z_STREAM_END:mf,Z_NEED_DICT:pf,Z_STREAM_ERROR:Xw,Z_DATA_ERROR:s0,Z_MEM_ERROR:$w}=Di;function zs(t){this.options=$c.assign({chunkSize:1024*64,windowBits:15,to:""},t||{});let e=this.options;e.raw&&e.windowBits>=0&&e.windowBits<16&&(e.windowBits=-e.windowBits,e.windowBits===0&&(e.windowBits=-15)),e.windowBits>=0&&e.windowBits<16&&!(t&&t.windowBits)&&(e.windowBits+=32),e.windowBits>15&&e.windowBits<48&&(e.windowBits&15)===0&&(e.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new P0,this.strm.avail_out=0;let r=hn.inflateInit2(this.strm,e.windowBits);if(r!==Is)throw new Error(Bi[r]);if(this.header=new Vw,hn.inflateGetHeader(this.strm,this.header),e.dictionary&&(typeof e.dictionary=="string"?e.dictionary=Fs.string2buf(e.dictionary):V0.call(e.dictionary)==="[object ArrayBuffer]"&&(e.dictionary=new Uint8Array(e.dictionary)),e.raw&&(r=hn.inflateSetDictionary(this.strm,e.dictionary),r!==Is)))throw new Error(Bi[r])}zs.prototype.push=function(t,e){let r=this.strm,n=this.options.chunkSize,i=this.options.dictionary,a,o,s;if(this.ended)return!1;for(e===~~e?o=e:o=e===!0?Ww:Hw,V0.call(t)==="[object ArrayBuffer]"?r.input=new Uint8Array(t):r.input=t,r.next_in=0,r.avail_in=r.input.length;;){for(r.avail_out===0&&(r.output=new Uint8Array(n),r.next_out=0,r.avail_out=n),a=hn.inflate(r,o),a===pf&&i&&(a=hn.inflateSetDictionary(r,i),a===Is?a=hn.inflate(r,o):a===s0&&(a=pf));r.avail_in>0&&a===mf&&r.state.wrap>0&&t[r.next_in]!==0;)hn.inflateReset(r),a=hn.inflate(r,o);switch(a){case Xw:case s0:case pf:case $w:return this.onEnd(a),this.ended=!0,!1}if(s=r.avail_out,r.next_out&&(r.avail_out===0||a===mf))if(this.options.to==="string"){let c=Fs.utf8border(r.output,r.next_out),l=r.next_out-c,u=Fs.buf2string(r.output,c);r.next_out=l,r.avail_out=n-l,l&&r.output.set(r.output.subarray(c,c+l),0),this.onData(u)}else this.onData(r.output.length===r.next_out?r.output:r.output.subarray(0,r.next_out));if(!(a===Is&&s===0)){if(a===mf)return a=hn.inflateEnd(this.strm),this.onEnd(a),this.ended=!0,!0;if(r.avail_in===0)break}}return!0};zs.prototype.onData=function(t){this.chunks.push(t)};zs.prototype.onEnd=function(t){t===Is&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=$c.flattenChunks(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg};function Cf(t,e){let r=new zs(e);if(r.push(t),r.err)throw r.msg||Bi[r.err];return r.result}function Kw(t,e){return e=e||{},e.raw=!0,Cf(t,e)}var Yw=zs,qw=Cf,Zw=Kw,jw=Cf,Qw=Di,Jw={Inflate:Yw,inflate:qw,inflateRaw:Zw,ungzip:jw,constants:Qw},{Deflate:e2,deflate:t2,deflateRaw:r2,gzip:n2}=sw,{Inflate:i2,inflate:a2,inflateRaw:o2,ungzip:s2}=Jw,l2=e2,c2=t2,u2=r2,d2=n2,f2=i2,h2=a2,m2=o2,p2=s2,g2=Di,Bf={Deflate:l2,deflate:c2,deflateRaw:u2,gzip:d2,Inflate:f2,inflate:h2,inflateRaw:m2,ungzip:p2,constants:g2};var $a=class $a{constructor(e=$a.INITIAL_SIZE){this.buffer=new Uint8Array(e),this.readOffset=0,this.writeOffset=0}append(e){let r=e instanceof Uint8Array?e:new Uint8Array(e),n=this.writeOffset+r.length;n>this.buffer.length&&this.grow(n),this.buffer.set(r,this.writeOffset),this.writeOffset+=r.length}hasBytes(e){return this.writeOffset-this.readOffset>=e}available(){return this.writeOffset-this.readOffset}readByte(){if(!this.hasBytes(1))throw new Error("Buffer underflow");return this.buffer[this.readOffset++]}readShort(){if(!this.hasBytes(2))throw new Error("Buffer underflow");let e=this.buffer[this.readOffset]|this.buffer[this.readOffset+1]<<8;return this.readOffset+=2,e>32767?e-65536:e}readLong(){if(!this.hasBytes(4))throw new Error("Buffer underflow");let e=this.buffer[this.readOffset]|this.buffer[this.readOffset+1]<<8|this.buffer[this.readOffset+2]<<16|this.buffer[this.readOffset+3]<<24;return this.readOffset+=4,e}readFloat(){if(!this.hasBytes(4))throw new Error("Buffer underflow");let r=new DataView(this.buffer.buffer,this.buffer.byteOffset+this.readOffset,4).getFloat32(0,!0);return this.readOffset+=4,r}readString(){let e=Math.min($a.MAX_STRING_LENGTH,this.writeOffset-this.readOffset),r=0;for(;r<e&&this.buffer[this.readOffset+r]!==0;)r++;if(r>=e)throw this.writeOffset-this.readOffset<=e?new Error("Buffer underflow"):new Error("String exceeds max length");let n=this.buffer.slice(this.readOffset,this.readOffset+r);return this.readOffset+=r+1,new TextDecoder("latin1").decode(n)}peekBytes(e){if(!this.hasBytes(e))throw new Error("Buffer underflow");return this.buffer.slice(this.readOffset,this.readOffset+e)}readBytes(e){if(!this.hasBytes(e))throw new Error("Buffer underflow");let r=this.buffer.slice(this.readOffset,this.readOffset+e);return this.readOffset+=e,r}readData(e){return this.readBytes(e)}getReadPosition(){return this.readOffset}getWritePosition(){return this.writeOffset}setReadPosition(e){if(e<0||e>this.writeOffset)throw new Error("Invalid read position");this.readOffset=e}grow(e){let r=e?Math.max(e,this.buffer.length*2):this.buffer.length*2,n=new Uint8Array(r);n.set(this.buffer),this.buffer=n}compact(){if(this.readOffset===0)return;let e=this.writeOffset-this.readOffset;if(e===0){this.readOffset=0,this.writeOffset=0;return}this.buffer.copyWithin(0,this.readOffset,this.writeOffset),this.readOffset=0,this.writeOffset=e}getCapacity(){return this.buffer.length}reset(){this.readOffset=0,this.writeOffset=0}};$a.INITIAL_SIZE=64*1024,$a.MAX_STRING_LENGTH=2048;var Qn=$a;var Wr=()=>({number:0,modelindex:0,modelindex2:0,modelindex3:0,modelindex4:0,frame:0,skinnum:0,effects:0,renderfx:0,origin:{x:0,y:0,z:0},old_origin:{x:0,y:0,z:0},angles:{x:0,y:0,z:0},sound:0,event:0,solid:0,bits:0,bitsHigh:0,alpha:0,scale:0,instanceBits:0,loopVolume:0,loopAttenuation:0,owner:0,oldFrame:0}),_r=()=>({pm_type:0,origin:{x:0,y:0,z:0},velocity:{x:0,y:0,z:0},pm_time:0,pm_flags:0,gravity:0,delta_angles:{x:0,y:0,z:0},viewoffset:{x:0,y:0,z:0},viewangles:{x:0,y:0,z:0},kick_angles:{x:0,y:0,z:0},gun_index:0,gun_frame:0,gun_offset:{x:0,y:0,z:0},gun_angles:{x:0,y:0,z:0},blend:[0,0,0,0],fov:0,rdflags:0,stats:new Array(32).fill(0),gunskin:0,gunrate:0,damage_blend:[0,0,0,0],team_id:0,watertype:0});var H0={0:R.bad,1:R.nop,2:R.disconnect,3:R.reconnect,4:R.download,5:R.frame,6:R.inventory,7:R.layout,8:R.muzzleflash,9:R.temp_entity,10:R.sound,11:R.print,12:R.stufftext,13:R.serverdata,14:R.configstring,15:R.spawnbaseline,16:R.centerprint,17:R.playerinfo,18:R.packetentities,19:R.deltapacketentities,20:R.muzzleflash2},Yc=class{constructor(){this.protocolVersion=34}translateCommand(e){return H0[e]!==void 0?H0[e]:R.bad}parseServerData(e){let r=e.readLong(),n=e.readLong(),i=e.readByte(),a=e.readString(),o=e.readShort(),s=e.readString();return{protocol:r,serverCount:n,attractLoop:i,gameDir:a,playerNum:o,levelName:s}}parseEntityBits(e){let r=e.readByte();r&Mr&&(r|=e.readByte()<<8),r&Er&&(r|=e.readByte()<<16),r&Tr&&(r|=e.readByte()<<24);let n;return r&ai?n=e.readShort():n=e.readByte(),{number:n,bits:r,bitsHigh:0}}parseDelta(e,r,n,i,a,o){r.number=e.number,r.modelindex=e.modelindex,r.modelindex2=e.modelindex2,r.modelindex3=e.modelindex3,r.modelindex4=e.modelindex4,r.frame=e.frame,r.skinnum=e.skinnum,r.effects=e.effects,r.renderfx=e.renderfx,r.origin.x=e.origin.x,r.origin.y=e.origin.y,r.origin.z=e.origin.z,r.old_origin.x=e.origin.x,r.old_origin.y=e.origin.y,r.old_origin.z=e.origin.z,r.angles.x=e.angles.x,r.angles.y=e.angles.y,r.angles.z=e.angles.z,r.sound=e.sound,r.event=e.event,r.solid=e.solid,r.number=n,r.bits=i,i&Rt&&(r.modelindex=o.readByte()),i&Bt&&(r.modelindex2=o.readByte()),i&Ft&&(r.modelindex3=o.readByte()),i&It&&(r.modelindex4=o.readByte()),i&Et&&(r.frame=o.readByte()),i&Ct&&(r.frame=o.readShort()),i&Ze&&i&Je?r.skinnum=o.readLong():i&Ze?r.skinnum=o.readByte():i&Je&&(r.skinnum=o.readShort()),i&qe&&i&Qe?r.effects=o.readLong():i&qe?r.effects=o.readByte():i&Qe&&(r.effects=o.readShort()),i&Ye&&i&je?r.renderfx=o.readLong():i&Ye?r.renderfx=o.readByte():i&je&&(r.renderfx=o.readShort()),i&St&&(r.origin.x=o.readShort()*.125),i&wt&&(r.origin.y=o.readShort()*.125),i&Lt&&(r.origin.z=o.readShort()*.125),i&Pt&&(r.angles.x=o.readByte()*(360/256)),i&Mt&&(r.angles.y=o.readByte()*(360/256)),i&At&&(r.angles.z=o.readByte()*(360/256)),i&pr&&(r.old_origin.x=o.readShort()*.125,r.old_origin.y=o.readShort()*.125,r.old_origin.z=o.readShort()*.125),i&Dt&&(r.sound=o.readByte()),i&Tt?r.event=o.readByte():r.event=0,i&kt&&(r.solid=o.readShort())}parsePlayerState(e){let r=_r(),n=e.readShort();n&1&&(r.pm_type=e.readByte()),n&2&&(r.origin.x=e.readShort()*.125,r.origin.y=e.readShort()*.125,r.origin.z=e.readShort()*.125),n&4&&(r.velocity.x=e.readShort()*.125,r.velocity.y=e.readShort()*.125,r.velocity.z=e.readShort()*.125),n&8&&(r.pm_time=e.readByte()),n&16&&(r.pm_flags=e.readByte()),n&32&&(r.gravity=e.readShort()),n&64&&(r.delta_angles.x=e.readShort()*(180/32768),r.delta_angles.y=e.readShort()*(180/32768),r.delta_angles.z=e.readShort()*(180/32768)),n&128&&(r.viewoffset.x=(e.readByte()<<24>>24)*.25,r.viewoffset.y=(e.readByte()<<24>>24)*.25,r.viewoffset.z=(e.readByte()<<24>>24)*.25),n&256&&(r.viewangles.x=e.readShort()*(360/65536),r.viewangles.y=e.readShort()*(360/65536),r.viewangles.z=e.readShort()*(360/65536)),n&512&&(r.kick_angles.x=(e.readByte()<<24>>24)*.25,r.kick_angles.y=(e.readByte()<<24>>24)*.25,r.kick_angles.z=(e.readByte()<<24>>24)*.25),n&4096&&(r.gun_index=e.readByte()),n&8192&&(r.gun_frame=e.readByte(),r.gun_offset.x=(e.readByte()<<24>>24)*.25,r.gun_offset.y=(e.readByte()<<24>>24)*.25,r.gun_offset.z=(e.readByte()<<24>>24)*.25,r.gun_angles.x=(e.readByte()<<24>>24)*.25,r.gun_angles.y=(e.readByte()<<24>>24)*.25,r.gun_angles.z=(e.readByte()<<24>>24)*.25),n&1024&&(r.blend[0]=e.readByte(),r.blend[1]=e.readByte(),r.blend[2]=e.readByte(),r.blend[3]=e.readByte()),n&2048&&(r.fov=e.readByte()),n&16384&&(r.rdflags=e.readByte()),n&32768&&(r.watertype=e.readByte());let i=e.readLong();for(let a=0;a<32;a++)i&1<<a&&(r.stats[a]=e.readShort());return r}};var Xr=2023,qc=class{constructor(){this.protocolVersion=Xr}translateCommand(e){return e}parseServerData(e){let r=e.readLong(),n=e.readLong(),i=e.readByte(),a=e.readByte(),o=e.readString(),s=e.readShort();if(s===-2){let l=e.readShort();for(let u=0;u<l;u++)e.readShort();s=0}else s===-1&&(s=-1);let c=e.readString();return{protocol:r,serverCount:n,spawnCount:n,attractLoop:0,gameDir:o,playerNum:s,levelName:c,tickRate:a,demoType:i}}parseEntityBits(e){let r=e.readByte();r&Mr&&(r|=e.readByte()<<8),r&Er&&(r|=e.readByte()<<16),r&Tr&&(r|=e.readByte()<<24);let n=0;r&Ni&&(n=e.readByte());let i;return r&ai?i=e.readShort():i=e.readByte(),{number:i,bits:r,bitsHigh:n}}parseDelta(e,r,n,i,a,o){Object.assign(r,e),r.origin={...e.origin},r.old_origin={...e.old_origin},r.angles={...e.angles},r.number=n,r.bits=i,r.bitsHigh=a,i&Rt&&(r.modelindex=o.readByte()),i&Bt&&(r.modelindex2=o.readByte()),i&Ft&&(r.modelindex3=o.readByte()),i&It&&(r.modelindex4=o.readByte()),i&Et&&(r.frame=o.readByte()),i&Ct&&(r.frame=o.readShort()),i&Ze&&i&Je?r.skinnum=o.readLong():i&Ze?r.skinnum=o.readByte():i&Je&&(r.skinnum=o.readShort()),i&qe&&i&Qe?r.effects=o.readLong():i&qe?r.effects=o.readByte():i&Qe&&(r.effects=o.readShort()),i&Ye&&i&je?r.renderfx=o.readLong():i&Ye?r.renderfx=o.readByte():i&je&&(r.renderfx=o.readShort()),i&St&&(r.origin.x=o.readShort()*.125),i&wt&&(r.origin.y=o.readShort()*.125),i&Lt&&(r.origin.z=o.readShort()*.125),i&Pt&&(r.angles.x=o.readByte()*(360/256)),i&Mt&&(r.angles.y=o.readByte()*(360/256)),i&At&&(r.angles.z=o.readByte()*(360/256)),i&pr&&(r.old_origin.x=o.readShort()*.125,r.old_origin.y=o.readShort()*.125,r.old_origin.z=o.readShort()*.125),i&Dt&&(r.sound=o.readByte()),i&Tt?r.event=o.readByte():r.event=0,i&kt&&(r.solid=o.readShort()),i&Ar&&(r.alpha=o.readByte()/255),i&Lr&&(r.scale=o.readFloat()),i&Pr&&(r.instanceBits=o.readLong()),i&Rr&&(r.loopVolume=o.readByte()/255),a&_n&&(r.loopAttenuation=o.readByte()/255),a&Sn&&(r.owner=o.readShort()),a&wn&&(r.oldFrame=o.readShort())}parsePlayerState(e){let r=_r(),n=e.readShort();n&1&&(r.pm_type=e.readByte()),n&2&&(r.origin.x=e.readShort()*.125,r.origin.y=e.readShort()*.125,r.origin.z=e.readShort()*.125),n&4&&(r.velocity.x=e.readShort()*.125,r.velocity.y=e.readShort()*.125,r.velocity.z=e.readShort()*.125),n&8&&(r.pm_time=e.readByte()),n&16&&(r.pm_flags=e.readByte()),n&32&&(r.gravity=e.readShort()),n&64&&(r.delta_angles.x=e.readShort()*(180/32768),r.delta_angles.y=e.readShort()*(180/32768),r.delta_angles.z=e.readShort()*(180/32768)),n&128&&(r.viewoffset.x=(e.readByte()<<24>>24)*.25,r.viewoffset.y=(e.readByte()<<24>>24)*.25,r.viewoffset.z=(e.readByte()<<24>>24)*.25),n&256&&(r.viewangles.x=e.readShort()*(360/65536),r.viewangles.y=e.readShort()*(360/65536),r.viewangles.z=e.readShort()*(360/65536)),n&512&&(r.kick_angles.x=(e.readByte()<<24>>24)*.25,r.kick_angles.y=(e.readByte()<<24>>24)*.25,r.kick_angles.z=(e.readByte()<<24>>24)*.25),n&4096&&(r.gun_index=e.readByte()),n&8192&&(r.gun_frame=e.readByte(),r.gun_offset.x=(e.readByte()<<24>>24)*.25,r.gun_offset.y=(e.readByte()<<24>>24)*.25,r.gun_offset.z=(e.readByte()<<24>>24)*.25,r.gun_angles.x=(e.readByte()<<24>>24)*.25,r.gun_angles.y=(e.readByte()<<24>>24)*.25,r.gun_angles.z=(e.readByte()<<24>>24)*.25),n&1024&&(r.blend[0]=e.readByte(),r.blend[1]=e.readByte(),r.blend[2]=e.readByte(),r.blend[3]=e.readByte()),n&2048&&(r.fov=e.readByte()),n&16384&&(r.rdflags=e.readByte()),n&32768&&(r.watertype=e.readByte());let i=e.readLong();for(let a=0;a<32;a++)i&1<<a&&(r.stats[a]=e.readShort());return r}};var Zc=class{constructor(e=0){this.protocolVersion=e}translateCommand(e){return e}parseServerData(e){let r=e.readLong(),n=e.readLong(),i=e.readByte(),a=e.readString(),o=e.readShort(),s=e.readString();return{protocol:r,serverCount:n,attractLoop:i,gameDir:a,playerNum:o,levelName:s}}parseEntityBits(e){let r=e.readByte();r&Mr&&(r|=e.readByte()<<8),r&Er&&(r|=e.readByte()<<16),r&Tr&&(r|=e.readByte()<<24);let n;return r&ai?n=e.readShort():n=e.readByte(),{number:n,bits:r,bitsHigh:0}}parseDelta(e,r,n,i,a,o){r.number=e.number,r.modelindex=e.modelindex,r.modelindex2=e.modelindex2,r.modelindex3=e.modelindex3,r.modelindex4=e.modelindex4,r.frame=e.frame,r.skinnum=e.skinnum,r.effects=e.effects,r.renderfx=e.renderfx,r.origin.x=e.origin.x,r.origin.y=e.origin.y,r.origin.z=e.origin.z,r.old_origin.x=e.origin.x,r.old_origin.y=e.origin.y,r.old_origin.z=e.origin.z,r.angles.x=e.angles.x,r.angles.y=e.angles.y,r.angles.z=e.angles.z,r.sound=e.sound,r.event=e.event,r.solid=e.solid,r.number=n,r.bits=i,i&Rt&&(r.modelindex=o.readByte()),i&Bt&&(r.modelindex2=o.readByte()),i&Ft&&(r.modelindex3=o.readByte()),i&It&&(r.modelindex4=o.readByte()),i&Et&&(r.frame=o.readByte()),i&Ct&&(r.frame=o.readShort()),i&Ze&&i&Je?r.skinnum=o.readLong():i&Ze?r.skinnum=o.readByte():i&Je&&(r.skinnum=o.readShort()),i&qe&&i&Qe?r.effects=o.readLong():i&qe?r.effects=o.readByte():i&Qe&&(r.effects=o.readShort()),i&Ye&&i&je?r.renderfx=o.readLong():i&Ye?r.renderfx=o.readByte():i&je&&(r.renderfx=o.readShort()),i&St&&(r.origin.x=o.readShort()*.125),i&wt&&(r.origin.y=o.readShort()*.125),i&Lt&&(r.origin.z=o.readShort()*.125),i&Pt&&(r.angles.x=o.readByte()*(360/256)),i&Mt&&(r.angles.y=o.readByte()*(360/256)),i&At&&(r.angles.z=o.readByte()*(360/256)),i&pr&&(r.old_origin.x=o.readShort()*.125,r.old_origin.y=o.readShort()*.125,r.old_origin.z=o.readShort()*.125),i&Dt&&(r.sound=o.readByte()),i&Tt?r.event=o.readByte():r.event=0,i&kt&&(r.solid=o.readShort())}parsePlayerState(e){let r=_r(),n=e.readShort();n&1&&(r.pm_type=e.readByte()),n&2&&(r.origin.x=e.readShort()*.125,r.origin.y=e.readShort()*.125,r.origin.z=e.readShort()*.125),n&4&&(r.velocity.x=e.readShort()*.125,r.velocity.y=e.readShort()*.125,r.velocity.z=e.readShort()*.125),n&8&&(r.pm_time=e.readByte()),n&16&&(r.pm_flags=e.readByte()),n&32&&(r.gravity=e.readShort()),n&64&&(r.delta_angles.x=e.readShort()*(180/32768),r.delta_angles.y=e.readShort()*(180/32768),r.delta_angles.z=e.readShort()*(180/32768)),n&128&&(r.viewoffset.x=(e.readByte()<<24>>24)*.25,r.viewoffset.y=(e.readByte()<<24>>24)*.25,r.viewoffset.z=(e.readByte()<<24>>24)*.25),n&256&&(r.viewangles.x=e.readShort()*(360/65536),r.viewangles.y=e.readShort()*(360/65536),r.viewangles.z=e.readShort()*(360/65536)),n&512&&(r.kick_angles.x=(e.readByte()<<24>>24)*.25,r.kick_angles.y=(e.readByte()<<24>>24)*.25,r.kick_angles.z=(e.readByte()<<24>>24)*.25),n&4096&&(r.gun_index=e.readByte()),n&8192&&(r.gun_frame=e.readByte(),r.gun_offset.x=(e.readByte()<<24>>24)*.25,r.gun_offset.y=(e.readByte()<<24>>24)*.25,r.gun_offset.z=(e.readByte()<<24>>24)*.25,r.gun_angles.x=(e.readByte()<<24>>24)*.25,r.gun_angles.y=(e.readByte()<<24>>24)*.25,r.gun_angles.z=(e.readByte()<<24>>24)*.25),n&1024&&(r.blend[0]=e.readByte(),r.blend[1]=e.readByte(),r.blend[2]=e.readByte(),r.blend[3]=e.readByte()),n&2048&&(r.fov=e.readByte()),n&16384&&(r.rdflags=e.readByte()),n&32768&&(r.watertype=e.readByte());let i=e.readLong();for(let a=0;a<32;a++)i&1<<a&&(r.stats[a]=e.readShort());return r}};var Os=class{constructor(){this.protocolVersion=0}translateCommand(e){return e===7?R.serverdata:e===12?R.serverdata:e===13?R.serverdata:e===R.stufftext?R.stufftext:R.bad}parseServerData(e){let r=e.readLong();if(r===Xr){let n=e.readLong(),i=e.readByte(),a=e.readByte(),o=e.readString(),s=e.readShort();if(s===-2){let l=e.readShort();for(let u=0;u<l;u++)e.readShort();s=0}else s===-1&&(s=-1);let c=e.readString();return{protocol:r,serverCount:n,spawnCount:n,attractLoop:0,gameDir:o,playerNum:s,levelName:c,tickRate:a,demoType:i}}else{let n=e.readLong(),i=e.readByte(),a=e.readString(),o=e.readShort(),s=e.readString();return{protocol:r,serverCount:n,attractLoop:i,gameDir:a,playerNum:o,levelName:s}}}parseEntityBits(e){throw new Error("Bootstrap handler cannot parse entities")}parseDelta(e,r,n,i,a,o){throw new Error("Bootstrap handler cannot parse delta")}parsePlayerState(e){throw new Error("Bootstrap handler cannot parse player state")}};function W0(t){return t===0?new Os:t===Xr?new qc:t===34?new Yc:new Zc(t)}var X0=1,y2=2,b2=128,Ff=class extends Qn{constructor(r){super(0);this.stream=r}readByte(){return this.stream.readByte()}readShort(){return this.stream.readShort()}readLong(){return this.stream.readLong()}readFloat(){return this.stream.readFloat()}readString(){return this.stream.readString()}readData(r){return this.stream.readData(r)}hasBytes(r){return this.stream.hasMore()}available(){return this.stream.getRemaining()}getReadPosition(){return this.stream.getPosition()}peekBytes(r){throw new Error("peekBytes not implemented for BinaryStreamAdapter")}},xt=class t{constructor(e,r,n=!1){this.strictMode=!1;this.errorCount=0;this.isDemo=X0;e instanceof Mn?this.stream=new Ff(e):this.stream=e,this.handler=r,this.strictMode=n,this.protocolHandler=new Os}setProtocolVersion(e){this.protocolHandler.protocolVersion!==e&&(this.protocolHandler=W0(e))}getProtocolVersion(){return this.protocolHandler.protocolVersion}getErrorCount(){return this.errorCount}parseMessage(){for(;this.stream.hasBytes(1);){let e=this.stream.getReadPosition(),r=-1;try{if(r=this.stream.readByte(),r===-1)break;let n=r,i=this.protocolHandler.translateCommand(r);switch(i){case R.bad:if(n===0)return;let a=`Unknown server command: ${n} (translated: ${i}) at offset ${e} (Protocol: ${this.getProtocolVersion()})`;if(this.strictMode)throw new Error(a);console.warn(a),this.errorCount++;return;case R.nop:break;case R.disconnect:this.handler?.onDisconnect&&this.handler.onDisconnect();break;case R.reconnect:this.handler?.onReconnect&&this.handler.onReconnect();break;case R.print:this.parsePrint();break;case R.serverdata:this.parseServerData();break;case R.configstring:this.parseConfigString();break;case R.spawnbaseline:this.parseSpawnBaseline();break;case R.centerprint:this.parseCenterPrint();break;case R.download:this.parseDownload();break;case R.frame:this.parseFrame();break;case R.packetentities:this.parsePacketEntities(!1);break;case R.deltapacketentities:this.parsePacketEntities(!0);break;case R.playerinfo:this.parsePlayerState();break;case R.stufftext:this.parseStuffText();break;case R.layout:this.parseLayout();break;case R.inventory:this.parseInventory();break;case R.sound:this.parseSound();break;case R.muzzleflash:this.parseMuzzleFlash();break;case R.muzzleflash2:this.parseMuzzleFlash2();break;case R.temp_entity:this.parseTempEntity();break;case R.splitclient:this.parseSplitClient();break;case R.configblast:this.parseConfigBlast();break;case R.spawnbaselineblast:this.parseSpawnBaselineBlast();break;case R.level_restart:this.handler?.onLevelRestart&&this.handler.onLevelRestart();break;case R.damage:this.parseDamage();break;case R.locprint:this.parseLocPrint();break;case R.fog:this.parseFog();break;case R.waitingforplayers:this.parseWaitingForPlayers();break;case R.bot_chat:this.parseBotChat();break;case R.poi:this.parsePoi();break;case R.help_path:this.parseHelpPath();break;case R.muzzleflash3:this.parseMuzzleFlash3();break;case R.achievement:this.parseAchievement();break;default:let o=`Unknown server command: ${n} (translated: ${i}) at offset ${e}`;if(this.strictMode)throw new Error(o);console.warn(o),this.errorCount++;return}}catch(n){let i=n.message;if(i==="Buffer underflow"||i.includes("StreamingBuffer")){try{this.stream.setReadPosition(e)}catch(o){console.error("Failed to rollback stream position",o)}return}let a=`offset ${e}, cmd ${r}, protocol ${this.getProtocolVersion()}`;if(console.warn(`Error parsing command ${r} (${a}): ${i}`),this.errorCount++,this.strictMode)throw n;return}}}readAngle16(){return this.stream.readShort()*(360/65536)}readCoord(){return this.stream.readShort()*.125}readAngle(){return this.stream.readByte()*(360/256)}readPos(e){e.x=this.stream.readShort()*.125,e.y=this.stream.readShort()*.125,e.z=this.stream.readShort()*.125}readDir(e){let r=this.stream.readByte();if(r>=mr.length)e.x=0,e.y=0,e.z=0;else{let n=mr[r];e.x=n[0],e.y=n[1],e.z=n[2]}}parsePrint(){let e=this.stream.readByte(),r=this.stream.readString();this.handler&&this.handler.onPrint(e,r)}parseStuffText(){let e=this.stream.readString();this.handler&&this.handler.onStuffText(e)}parseLayout(){let e=this.stream.readString();this.handler&&this.handler.onLayout(e)}parseCenterPrint(){let e=this.stream.readString();this.handler&&this.handler.onCenterPrint(e)}parseServerData(){let e=this.protocolHandler.parseServerData(this.stream);this.setProtocolVersion(e.protocol),this.handler&&this.handler.onServerData(e.protocol,e.serverCount,e.attractLoop,e.gameDir,e.playerNum,e.levelName,e.tickRate,e.demoType),e.protocol===Xr?this.isDemo=e.demoType??X0:this.isDemo=e.attractLoop}parseConfigString(){let e=this.stream.readShort(),r=this.stream.readString();this.handler&&this.handler.onConfigString(e,r)}parseSplitClient(){let e=this.stream.readByte();this.handler?.onSplitClient&&this.handler.onSplitClient(e)}parseConfigBlast(){let e=this.stream.readShort(),r=this.stream.readShort(),n=this.stream.readData(e);try{let i=Bf.inflate(n),a=new Mn(i.buffer);for(;a.hasMore();){let o=a.readUShort(),s=a.readString();this.handler&&this.handler.onConfigString(o,s)}}catch(i){console.error("svc_configblast error",i)}}parseSpawnBaselineBlast(){let e=this.stream.readShort(),r=this.stream.readShort(),n=this.stream.readData(e);try{let i=Bf.inflate(n),a=new Mn(i.buffer),o=new t(a,this.handler,this.strictMode);for(o.setProtocolVersion(this.getProtocolVersion());a.hasMore();)o.parseSpawnBaseline()}catch(i){console.error("svc_spawnbaselineblast error",i)}}parseLocPrint(){let e=this.stream.readByte(),r=this.stream.readString(),n=this.stream.readByte(),i=[];for(let a=0;a<n;a++)i.push(this.stream.readString());this.handler?.onLocPrint&&this.handler.onLocPrint(e,r,i)}parseWaitingForPlayers(){let e=this.stream.readByte();this.handler?.onWaitingForPlayers&&this.handler.onWaitingForPlayers(e)}parseBotChat(){let e=this.stream.readString(),r=this.stream.readShort(),n=this.stream.readString();this.handler?.onBotChat&&this.handler.onBotChat(n)}parsePoi(){let e=this.stream.readShort(),r=this.stream.readShort(),n={x:0,y:0,z:0};this.readPos(n);let i=this.stream.readShort(),a=this.stream.readByte(),o=this.stream.readByte();this.handler?.onPoi&&this.handler.onPoi(o,n)}parseHelpPath(){let e=this.stream.readByte(),r={x:0,y:0,z:0};this.readPos(r);let n={x:0,y:0,z:0};this.readDir(n),this.handler?.onHelpPath&&this.handler.onHelpPath(r)}parseAchievement(){let e=this.stream.readString();this.handler?.onAchievement&&this.handler.onAchievement(e)}parseDownload(){let e=this.stream.readShort(),r=this.stream.readByte(),n;e>0&&(n=this.stream.readData(e)),this.handler&&this.handler.onDownload(e,r,n)}parseInventory(){let r=new Array(256);for(let n=0;n<256;n++)r[n]=this.stream.readShort();this.handler&&this.handler.onInventory(r)}parseSound(){let e=this.stream.readByte(),r=this.stream.readByte(),n,i,a,o,s;if(e&1&&(n=this.stream.readByte()),e&2&&(i=this.stream.readByte()),e&16&&(a=this.stream.readByte()),e&8&&(o=this.stream.readShort()),e&4){let c={x:0,y:0,z:0};this.readPos(c),s=c}this.handler&&this.handler.onSound(e,r,n,i,a,o,s)}parseMuzzleFlash(){let e=this.stream.readShort(),r=this.stream.readByte();this.handler&&this.handler.onMuzzleFlash(e,r)}parseMuzzleFlash2(){let e=this.stream.readShort(),r=this.stream.readByte();this.handler&&this.handler.onMuzzleFlash2(e,r)}parseMuzzleFlash3(){let e=this.stream.readShort(),r=this.stream.readShort();this.handler?.onMuzzleFlash3&&this.handler.onMuzzleFlash3(e,r)}parseFog(){let e=this.stream.readByte();if(e&128){let n=this.stream.readByte();e|=n<<8}let r={};e&1&&(r.density=this.stream.readFloat(),r.skyfactor=this.stream.readByte()),e&2&&(r.red=this.stream.readByte()),e&4&&(r.green=this.stream.readByte()),e&8&&(r.blue=this.stream.readByte()),e&16&&(r.time=this.stream.readShort()),e&32&&(r.hf_falloff=this.stream.readFloat()),e&64&&(r.hf_density=this.stream.readFloat()),e&256&&(r.hf_start_r=this.stream.readByte()),e&512&&(r.hf_start_g=this.stream.readByte()),e&1024&&(r.hf_start_b=this.stream.readByte()),e&2048&&(r.hf_start_dist=this.stream.readLong()),e&4096&&(r.hf_end_r=this.stream.readByte()),e&8192&&(r.hf_end_g=this.stream.readByte()),e&16384&&(r.hf_end_b=this.stream.readByte()),e&32768&&(r.hf_end_dist=this.stream.readLong()),this.handler?.onFog&&this.handler.onFog(r)}parseDamage(){let e=this.stream.readByte(),r=[];for(let n=0;n<e;n++){let i=this.stream.readByte(),a={x:0,y:0,z:0};this.readDir(a);let o=i&31,s=(i&32)!==0,c=(i&64)!==0,l=(i&128)!==0;r.push({damage:o,health:s,armor:c,power:l,dir:a})}this.handler?.onDamage&&this.handler.onDamage(r)}parseTempEntity(){let e=this.stream.readByte(),r={x:0,y:0,z:0},n={x:0,y:0,z:0},i={x:0,y:0,z:0},a,o,s,c,l;switch(e){case U.EXPLOSION1:case U.EXPLOSION2:case U.ROCKET_EXPLOSION:case U.GRENADE_EXPLOSION:case U.ROCKET_EXPLOSION_WATER:case U.GRENADE_EXPLOSION_WATER:case U.BFG_EXPLOSION:case U.BFG_BIGEXPLOSION:case U.BOSSTPORT:case U.PLASMA_EXPLOSION:case U.PLAIN_EXPLOSION:case U.CHAINFIST_SMOKE:case U.TRACKER_EXPLOSION:case U.TELEPORT_EFFECT:case U.DBALL_GOAL:case U.NUKEBLAST:case U.WIDOWSPLASH:case U.EXPLOSION1_BIG:case U.EXPLOSION1_NP:this.readPos(r);break;case U.GUNSHOT:case U.BLOOD:case U.BLASTER:case U.SHOTGUN:case U.SPARKS:case U.BULLET_SPARKS:case U.SCREEN_SPARKS:case U.SHIELD_SPARKS:case U.BLASTER2:case U.FLECHETTE:case U.MOREBLOOD:case U.ELECTRIC_SPARKS:case U.HEATBEAM_SPARKS:case U.HEATBEAM_STEAM:this.readPos(r),this.readDir(i);break;case U.SPLASH:case U.LASER_SPARKS:case U.WELDING_SPARKS:case U.TUNNEL_SPARKS:a=this.stream.readByte(),this.readPos(r),this.readDir(i),o=this.stream.readByte();break;case U.BLUEHYPERBLASTER:this.getProtocolVersion()>=32?(this.readPos(r),this.readPos(n)):(this.readPos(r),this.readDir(i));break;case U.GREENBLOOD:this.getProtocolVersion()>=32?(this.readPos(r),this.readDir(i)):(this.readPos(r),this.readPos(n));break;case U.RAILTRAIL:case U.BUBBLETRAIL:case U.BFG_LASER:case U.DEBUGTRAIL:case U.BUBBLETRAIL2:this.readPos(r),this.readPos(n);break;case U.PARASITE_ATTACK:case U.MEDIC_CABLE_ATTACK:this.stream.readShort(),this.readPos(r),this.readPos(n);break;case U.GRAPPLE_CABLE:s=this.stream.readShort(),this.readPos(r),this.readPos(n),this.readPos(i);break;case U.LIGHTNING:c=this.stream.readShort(),l=this.stream.readShort(),this.readPos(r),this.readPos(n);break;case U.FLASHLIGHT:this.readPos(r),s=this.stream.readShort();break;case U.FORCEWALL:this.readPos(r),this.readPos(n),o=this.stream.readByte();break;case U.STEAM:let u=this.stream.readShort();a=this.stream.readByte(),this.readPos(r),this.readDir(i),o=this.stream.readByte(),this.stream.readShort(),u!==-1&&this.stream.readLong();break;case U.WIDOWBEAMOUT:this.stream.readShort();case U.HEATBEAM:case U.MONSTER_HEATBEAM:s=this.stream.readShort(),this.readPos(r),this.readPos(n),this.readDir(i);break}this.handler&&this.handler.onTempEntity(e,r,n,i,a,o,s,c,l)}parseSpawnBaseline(){let e=this.protocolHandler.parseEntityBits(this.stream),r=Wr();this.protocolHandler.parseDelta(Wr(),r,e.number,e.bits,e.bitsHigh,this.stream),this.handler&&this.handler.onSpawnBaseline(r)}parseFrame(){let e=this.stream.readLong(),r=this.stream.readLong(),n=0;this.getProtocolVersion()!==26&&this.getProtocolVersion()!==25&&(n=this.stream.readByte());let i=this.stream.readByte(),a=this.stream.readData(i),o=this.stream.readByte();if(o=this.protocolHandler.translateCommand(o),o!==R.playerinfo){if(this.strictMode)throw new Error(`Expected svc_playerinfo after svc_frame, got ${o}`);return}let s=this.parsePlayerState(),c=this.stream.readByte();if(c=this.protocolHandler.translateCommand(c),c!==R.packetentities&&c!==R.deltapacketentities){if(this.strictMode)throw new Error(`Expected svc_packetentities after svc_playerinfo, got ${c}`);return}let l=this.collectPacketEntities();if(this.isDemo===b2){let u=this.stream.readByte();for(let d=0;d<u;d++)this.stream.readByte()}this.isDemo===y2&&this.stream.readLong(),this.handler&&this.handler.onFrame({serverFrame:e,deltaFrame:r,surpressCount:n,areaBytes:i,areaBits:a,playerState:s,packetEntities:{delta:!0,entities:l}})}parsePlayerState(){return this.protocolHandler.parsePlayerState(this.stream)}parsePacketEntities(e){let r=this.collectPacketEntities();this.handler&&this.handler.onFrame({serverFrame:0,deltaFrame:0,surpressCount:0,areaBytes:0,areaBits:new Uint8Array,playerState:_r(),packetEntities:{delta:e,entities:r}})}collectPacketEntities(){let e=[];for(;;){let r=this.protocolHandler.parseEntityBits(this.stream);if(r.bits&ro){if(r.number===0)break;continue}let n=Wr();if(r.number===0)break;this.protocolHandler.parseDelta(Wr(),n,r.number,r.bits,r.bitsHigh,this.stream),e.push(n)}return e}};var If=(u=>(u.WeaponFire="weapon_fire",u.DamageDealt="damage_dealt",u.DamageReceived="damage_received",u.Pickup="pickup",u.Death="death",u.Kill="kill",u.Spawn="spawn",u.PlayerInfo="player_info",u.Chat="chat",u.Objective="objective",u))(If||{});var Ka=class{constructor(e){this.events=[];this.summary={totalKills:0,totalDeaths:0,damageDealt:0,damageReceived:0,weaponUsage:new Map};this.header=null;this.configStrings=new Map;this.serverInfo={};this.statistics=null;this.playerStats=new Map;this.weaponStats=new Map;this.activeEntities=new Set;this.buffer=e}analyze(){let e=new vr(this.buffer),r=-1,n=0,i=.1,a=0,o={onServerData:(s,c,l,u,d,f,h,m)=>{a=s,this.header={protocolVersion:s,gameDir:u,levelName:f,playerNum:d,serverCount:c,spawnCount:c,tickRate:h,demoType:m},h&&h>0&&(i=1/h)},onConfigString:(s,c)=>{this.configStrings.set(s,c),s===0&&this.parseServerInfo(c)},onSpawnBaseline:s=>{},onFrame:s=>{let c=new Set;if(s.packetEntities&&s.packetEntities.entities)for(let l of s.packetEntities.entities)c.add(l.number),this.activeEntities.has(l.number)||this.recordEvent({type:"spawn",frame:r,time:n,entityId:l.number,position:{x:l.origin.x,y:l.origin.y,z:l.origin.z},description:`Entity ${l.number} spawned`});this.activeEntities=c,s.playerState&&this.header},onPrint:(s,c)=>{let l=c.replace(/\n/g," ").trim();l.includes("died")||l.includes("killed")||l.includes("suicide")?(this.summary.totalDeaths++,this.recordEvent({type:"death",frame:r,time:n,description:l})):l.startsWith("You got the ")?this.recordEvent({type:"pickup",frame:r,time:n,description:l}):(s===3||s===2)&&this.recordEvent({type:"chat",frame:r,time:n,description:l,data:{level:s}})},onCenterPrint:s=>{this.recordEvent({type:"objective",frame:r,time:n,description:s.trim()})},onStuffText:()=>{},onSound:()=>{},onTempEntity:()=>{},onLayout:()=>{},onInventory:()=>{},onMuzzleFlash:(s,c)=>{this.handleWeaponFire(s,c,r,n)},onMuzzleFlash2:(s,c)=>{this.handleWeaponFire(s,c,r,n)},onMuzzleFlash3:(s,c)=>{this.handleWeaponFire(s,c,r,n)},onDisconnect:()=>{},onReconnect:()=>{},onDownload:()=>{},onDamage:s=>{for(let c of s)if(this.recordEvent({type:"damage_received",frame:r,time:n,value:c.damage,position:c.dir,description:`Took ${c.damage} damage`}),this.summary.damageReceived+=c.damage,this.header){let l=this.getOrCreatePlayerStats(this.header.playerNum);l.damageReceived+=c.damage}}};for(;e.hasMore();){let s=e.readNextBlock();if(!s)break;r++,n=r*i;let c=new xt(s.data,o);c.setProtocolVersion(a),c.parseMessage(),a=c.getProtocolVersion()}return this.statistics={duration:n,frameCount:r+1,averageFps:(r+1)/(n||1),mapName:this.header?.levelName||"unknown",playerCount:1},{events:this.events,summary:this.summary,header:this.header,configStrings:this.configStrings,serverInfo:this.serverInfo,statistics:this.statistics,playerStats:this.playerStats,weaponStats:this.weaponStats}}handleWeaponFire(e,r,n,i){this.recordEvent({type:"weapon_fire",frame:n,time:i,entityId:e,value:r,description:`Weapon ${r} fired by ${e}`});let a=this.summary.weaponUsage.get(r)||0;this.summary.weaponUsage.set(r,a+1);let o=this.getOrCreateWeaponStat(e,r);o.shotsFired++}recordEvent(e){this.events.push(e)}parseServerInfo(e){let r=e.split("\\");for(let n=1;n<r.length;n+=2)n+1<r.length&&(this.serverInfo[r[n]]=r[n+1])}getOrCreatePlayerStats(e){let r=this.playerStats.get(e);return r||(r={kills:0,deaths:0,damageDealt:0,damageReceived:0,suicides:0},this.playerStats.set(e,r)),r}getOrCreateWeaponStat(e,r){let n=this.weaponStats.get(e);n||(n=[],this.weaponStats.set(e,n));let i=n.find(a=>a.weaponId===r);return i||(i={weaponId:r,shotsFired:0,hits:0,kills:0},n.push(i)),i}};var Df=(i=>(i[i.FirstPerson=0]="FirstPerson",i[i.ThirdPerson=1]="ThirdPerson",i[i.Free=2]="Free",i[i.Follow=3]="Follow",i))(Df||{});var jc=(i=>(i[i.Stopped=0]="Stopped",i[i.Playing=1]="Playing",i[i.Paused=2]="Paused",i[i.Finished=3]="Finished",i))(jc||{}),x2=()=>({onServerData:()=>{},onConfigString:()=>{},onSpawnBaseline:()=>{},onFrame:()=>{},onCenterPrint:()=>{},onStuffText:()=>{},onPrint:()=>{},onSound:()=>{},onTempEntity:()=>{},onLayout:()=>{},onInventory:()=>{},onMuzzleFlash:()=>{},onMuzzleFlash2:()=>{},onDisconnect:()=>{},onReconnect:()=>{},onDownload:()=>{}}),Ns=class{constructor(){this.reader=null;this.buffer=null;this.state=0;this.playbackSpeed=1;this.currentProtocolVersion=0;this.currentFrameIndex=-1;this.lastFrameData=null;this.accumulatedTime=0;this.frameDuration=100;this.snapshotInterval=100;this.snapshots=new Map;this.cachedEvents=null;this.cachedSummary=null;this.cachedHeader=null;this.cachedConfigStrings=null;this.cachedServerInfo=null;this.cachedStatistics=null;this.cachedPlayerStats=null;this.cachedWeaponStats=null;this.tracker=null;this.cameraMode=0;this.thirdPersonDistance=80;this.thirdPersonOffset={x:0,y:0,z:0}}setHandler(e){this.handler=e}setCallbacks(e){this.callbacks=e}loadDemo(e){this.buffer=e,this.reader=new vr(e),this.transitionState(0),this.accumulatedTime=0,this.currentProtocolVersion=0,this.currentFrameIndex=-1,this.snapshots.clear(),this.lastFrameData=null,this.cachedEvents=null,this.cachedSummary=null,this.cachedHeader=null,this.cachedConfigStrings=null,this.cachedServerInfo=null,this.cachedStatistics=null,this.cachedPlayerStats=null,this.cachedWeaponStats=null}play(){this.reader&&this.state!==1&&this.transitionState(1)}pause(){this.state===1&&this.transitionState(2)}stop(){this.transitionState(0),this.reader&&this.reader.reset(),this.accumulatedTime=0,this.currentProtocolVersion=0,this.currentFrameIndex=-1,this.lastFrameData=null}transitionState(e){this.state!==e&&(this.state=e,this.callbacks?.onPlaybackStateChange&&this.callbacks.onPlaybackStateChange(e))}setFrameDuration(e){this.frameDuration=e}setSpeed(e){this.playbackSpeed=Math.max(.1,Math.min(e,16))}getSpeed(){return this.playbackSpeed}getPlaybackSpeed(){return this.playbackSpeed}getInterpolationFactor(){return this.frameDuration<=0?0:Math.max(0,Math.min(1,this.accumulatedTime/this.frameDuration))}update(e){if(!(this.state!==1||!this.reader))for(this.accumulatedTime+=e*1e3*this.playbackSpeed;this.accumulatedTime>=this.frameDuration;){if(!this.processNextFrame())return;this.accumulatedTime-=this.frameDuration,this.callbacks?.onTimeUpdate&&this.callbacks.onTimeUpdate(this.getCurrentTime())}}stepForward(){this.reader&&(this.processNextFrame(),this.callbacks?.onTimeUpdate&&this.callbacks.onTimeUpdate(this.getCurrentTime()))}stepBackward(){this.reader&&this.currentFrameIndex>0&&this.seek(this.currentFrameIndex-1)}seekToTime(e){let r=this.timeToFrame(e);this.seek(r)}seekToFrame(e){this.seek(e)}frameToTime(e){return e*this.frameDuration/1e3}timeToFrame(e){return Math.floor(e*1e3/this.frameDuration)}playFrom(e){if(e.type==="frame")this.seek(e.frame);else if(e.type==="time")this.seekToTime(e.seconds);else throw new Error(`Invalid offset type: ${e.type}`);this.play()}playRange(e,r){let n=e.type==="frame"?e.frame:this.timeToFrame(e.seconds),i=r.type==="frame"?r.frame:this.timeToFrame(r.seconds),a=this.getTotalFrames(),o=Math.max(0,a-1);if(n<0)throw new Error(`Invalid start offset: ${n}`);if(i<n)throw new Error(`End offset (${i}) cannot be before start offset (${n})`);this.playFrom(e);let s=this.callbacks?.onFrameUpdate,c={...this.callbacks,onFrameUpdate:l=>{if(s&&s(l),this.currentFrameIndex>=i){this.pause();let u=this.callbacks?.onPlaybackComplete;this.callbacks===c&&this.setCallbacks({...this.callbacks,onFrameUpdate:s}),u&&u()}}};this.setCallbacks(c)}seek(e){if(!this.reader)return;let r=this.getTotalFrames();if(r>0&&e>=r&&(e=r-1),e<0&&(e=0),e===this.currentFrameIndex+1){this.processNextFrame(),this.callbacks?.onSeekComplete&&this.callbacks.onSeekComplete();return}if(e===this.currentFrameIndex){this.callbacks?.onSeekComplete&&this.callbacks.onSeekComplete();return}let n=-1,i=null;if(e>this.currentFrameIndex&&this.currentFrameIndex!==-1&&(n=this.currentFrameIndex),this.callbacks?.onRestoreSnapshot)for(let[a,o]of this.snapshots)a<=e&&a>n&&(n=a,i=o);for(n===-1&&this.currentFrameIndex>e?(this.reader.reset(),this.currentFrameIndex=-1,this.currentProtocolVersion=0):n===-1&&(this.reader.reset(),this.currentFrameIndex=-1,this.currentProtocolVersion=0),i&&this.callbacks?.onRestoreSnapshot&&(this.callbacks.onRestoreSnapshot(i),this.reader.seekToMessage(n+1)?this.currentFrameIndex=n:(this.reader.reset(),this.currentFrameIndex=-1,this.currentProtocolVersion=0));this.currentFrameIndex<e&&(this.callbacks?.onCaptureSnapshot&&(this.currentFrameIndex+1)%this.snapshotInterval,!!this.processNextFrame()););this.accumulatedTime=0,this.callbacks?.onSeekComplete&&this.callbacks.onSeekComplete(),this.callbacks?.onTimeUpdate&&this.callbacks.onTimeUpdate(this.getCurrentTime())}processNextFrame(){if(!this.reader||!this.reader.hasMore())return this.transitionState(3),this.callbacks?.onPlaybackComplete&&this.callbacks.onPlaybackComplete(),!1;let e=this.reader.readNextBlock();if(!e)return this.transitionState(3),this.callbacks?.onPlaybackComplete&&this.callbacks.onPlaybackComplete(),!1;this.currentFrameIndex++,this.tracker&&(this.tracker.setCurrentFrame(this.currentFrameIndex),this.tracker.setCurrentTime(this.getCurrentTime()));try{let r={...this.handler||x2(),onFrame:i=>{this.lastFrameData=i,this.handler?.onFrame&&this.handler.onFrame(i),this.callbacks?.onFrameUpdate&&this.callbacks.onFrameUpdate(i)}},n=new xt(e.data,r);if(n.setProtocolVersion(this.currentProtocolVersion),n.parseMessage(),this.currentProtocolVersion=n.getProtocolVersion(),this.callbacks?.onCaptureSnapshot&&this.currentFrameIndex%this.snapshotInterval===0&&this.currentFrameIndex>0){let i=this.callbacks.onCaptureSnapshot(this.currentFrameIndex);i&&this.snapshots.set(this.currentFrameIndex,i)}}catch(r){return console.error("Error processing demo frame",r),this.callbacks?.onPlaybackError&&this.callbacks.onPlaybackError(r instanceof Error?r:new Error(String(r))),!1}return!0}getState(){return this.state}getCurrentTime(){return this.currentFrameIndex<0?this.accumulatedTime/1e3:(this.currentFrameIndex*this.frameDuration+this.accumulatedTime)/1e3}getFrameCount(){return this.reader?this.reader.getMessageCount():0}getTotalFrames(){return this.getFrameCount()}getCurrentFrame(){return this.currentFrameIndex<0?0:this.currentFrameIndex}getDuration(){return this.getFrameCount()*this.frameDuration/1e3}getTotalBytes(){return this.reader?this.reader.getProgress().total:0}getProcessedBytes(){return this.reader?this.reader.getOffset():0}getFrameData(e){if(e===this.currentFrameIndex&&this.lastFrameData)return this.lastFrameData;let r=this.state;return this.pause(),this.seek(e),r===1&&this.play(),this.lastFrameData}getFramePlayerState(e){if(e===this.currentFrameIndex&&this.handler?.getPlayerState){let n=this.handler.getPlayerState();if(n)return n}let r=this.getFrameData(e);return r?r.playerState:null}getFrameEntities(e){if(e===this.currentFrameIndex&&this.handler?.getEntities){let r=this.handler.getEntities();if(r)return Array.from(r.values())}if(this.seek(e),this.handler?.getEntities){let r=this.handler.getEntities();return r?Array.from(r.values()):[]}return[]}compareFrames(e,r){let n=this.getFramePlayerState(e),i=this.getFrameEntities(e),a=new Map;i.forEach(u=>a.set(u.number,u));let o=this.getFramePlayerState(r),s=this.getFrameEntities(r),c=new Map;s.forEach(u=>c.set(u.number,u));let l={frameA:e,frameB:r,playerStateDiff:{origin:null,viewangles:null,health:null,ammo:null},entityDiffs:{added:[],removed:[],moved:[]}};n&&o&&((n.origin.x!==o.origin.x||n.origin.y!==o.origin.y||n.origin.z!==o.origin.z)&&(l.playerStateDiff.origin={x:o.origin.x-n.origin.x,y:o.origin.y-n.origin.y,z:o.origin.z-n.origin.z}),n.stats[1]!==o.stats[1]&&(l.playerStateDiff.health=o.stats[1]-n.stats[1]),n.stats[2]!==o.stats[2]&&(l.playerStateDiff.ammo=o.stats[2]-n.stats[2]));for(let[u,d]of c){let f=a.get(u);f?(f.origin.x!==d.origin.x||f.origin.y!==d.origin.y||f.origin.z!==d.origin.z)&&l.entityDiffs.moved.push({id:u,delta:{x:d.origin.x-f.origin.x,y:d.origin.y-f.origin.y,z:d.origin.z-f.origin.z}}):l.entityDiffs.added.push(u)}for(let[u,d]of a)c.has(u)||l.entityDiffs.removed.push(u);return l}getEntityTrajectory(e,r,n){let i=[],a=this.getCurrentFrame();for(this.seek(r);this.getCurrentFrame()<=n&&this.state!==3;){let o=null;if(e===-1){let s=this.getFramePlayerState(this.getCurrentFrame());s&&(o={...s.origin})}else if(this.handler?.getEntities){let s=this.handler.getEntities().get(e);s&&(o={...s.origin})}if(o&&i.push(o),this.getCurrentFrame()===n)break;this.stepForward()}return this.seek(a),i}getEvents(){return this.ensureAnalysis(),this.cachedEvents||[]}getDemoEvents(){return this.getEvents()}filterEvents(e,r){return this.getDemoEvents().filter(i=>!(i.type!==e||r!==void 0&&i.entityId!==r))}getEventSummary(){return this.ensureAnalysis(),this.cachedSummary||{totalKills:0,totalDeaths:0,damageDealt:0,damageReceived:0,weaponUsage:new Map}}getMetadata(){let e=this.getDemoHeader();if(!e)return null;let r=this.getDemoServerInfo(),n="Unknown";return this.cachedConfigStrings,{mapName:e.levelName,playerName:n,serverName:r.hostname,demoVersion:e.protocolVersion,tickRate:e.tickRate||10}}getDemoHeader(){return this.ensureAnalysis(),this.cachedHeader}getDemoConfigStrings(){return this.ensureAnalysis(),this.cachedConfigStrings||new Map}getDemoServerInfo(){return this.ensureAnalysis(),this.cachedServerInfo||{}}getDemoStatistics(){return this.ensureAnalysis(),this.cachedStatistics}getPlayerStatistics(e){return this.ensureAnalysis(),this.cachedPlayerStats?.get(e)||null}getWeaponStatistics(e){return this.ensureAnalysis(),this.cachedWeaponStats?.get(e)||null}ensureAnalysis(){if(!this.cachedEvents&&this.buffer){let r=new Ka(this.buffer).analyze();this.cachedEvents=r.events,this.cachedSummary=r.summary,this.cachedHeader=r.header,this.cachedConfigStrings=r.configStrings,this.cachedServerInfo=r.serverInfo,this.cachedStatistics=r.statistics,this.cachedPlayerStats=r.playerStats,this.cachedWeaponStats=r.weaponStats}}setCameraMode(e){this.cameraMode=e}getCameraMode(){return this.cameraMode}setThirdPersonDistance(e){this.thirdPersonDistance=e}setThirdPersonOffset(e){this.thirdPersonOffset=e}async playWithTracking(e,r={}){if(this.tracker=e,e.startTracking(),r.fastForward)try{this.state===0&&this.reader,this.transitionState(1);let n=100,i=async()=>{if(this.state!==1)throw new Error("Playback stopped unexpectedly during fast forward");let a=0;for(;a<n;){if(!this.processNextFrame()){this.transitionState(0);let o=e.stopTracking();return this.tracker=null,this.callbacks?.onPlaybackComplete&&this.callbacks.onPlaybackComplete(),o}a++}return await new Promise(o=>setTimeout(o,0)),i()};return await i()}catch(n){throw this.transitionState(0),e.stopTracking(),this.tracker=null,n}else return new Promise((n,i)=>{let a=this.callbacks?.onPlaybackComplete,o=this.callbacks?.onPlaybackError,s=()=>{this.setCallbacks({...this.callbacks,onPlaybackComplete:a,onPlaybackError:o}),this.tracker=null};this.setCallbacks({...this.callbacks,onPlaybackComplete:()=>{let c=e.stopTracking();a&&a(),s(),n(c)},onPlaybackError:c=>{e.stopTracking(),o&&o(c),s(),i(c)}}),this.play()})}async playRangeWithTracking(e,r,n,i={}){this.tracker=n,n.startTracking();let a=e.type==="frame"?e.frame:this.timeToFrame(e.seconds),o=r.type==="frame"?r.frame:this.timeToFrame(r.seconds);if(i.fastForward)try{this.playFrom(e),this.transitionState(1);let s=100,c=async()=>{if(this.state!==1)throw new Error("Playback stopped unexpectedly during fast forward");let l=0;for(;l<s;){if(this.currentFrameIndex>=o||!this.processNextFrame()){this.transitionState(0);let u=n.stopTracking();return this.tracker=null,this.callbacks?.onPlaybackComplete&&this.callbacks.onPlaybackComplete(),u}l++}return await new Promise(u=>setTimeout(u,0)),c()};return await c()}catch(s){throw this.transitionState(0),n.stopTracking(),this.tracker=null,s}else return new Promise((s,c)=>{let l=this.callbacks?.onPlaybackComplete,u=this.callbacks?.onPlaybackError,d=()=>{this.setCallbacks({...this.callbacks,onPlaybackComplete:l,onPlaybackError:u}),this.tracker=null};this.setCallbacks({...this.callbacks,onPlaybackComplete:()=>{let f=n.stopTracking();l&&l(),d(),s(f)},onPlaybackError:f=>{n.stopTracking(),u&&u(f),d(),c(f)}}),this.playRange(e,r)})}};var Gs=class{constructor(){this.isRecording=!1;this.startTime=0;this.frameCount=0;this.filename=null;this.lastMessageSize=-1;this.messageBuffer=new oi(1024*1024)}startRecording(e,r=0){this.isRecording||(this.isRecording=!0,this.filename=e,this.startTime=r,this.frameCount=0,this.messageBuffer.reset(),console.log(`DemoRecorder: Started recording to ${e}`))}recordMessage(e){if(this.isRecording){this.messageBuffer.writeLong(e.byteLength);for(let r=0;r<e.length;r++)this.messageBuffer.writeByte(e[r]);this.frameCount++}}stopRecording(){return this.isRecording?(this.isRecording=!1,this.messageBuffer.writeLong(-1),console.log(`DemoRecorder: Stopped recording. Frames: ${this.frameCount}, Size: ${this.messageBuffer.getOffset()} bytes`),this.messageBuffer.getData()):null}getIsRecording(){return this.isRecording}};var Qc=class{constructor(e,r=34){this.writer=e||new oi(new Uint8Array(64*1024)),this.protocol=r}getData(){return this.writer.getData()}getOpcode(e){if(this.protocol===34)switch(e){case R.serverdata:return 13;case R.frame:return 5;case R.playerinfo:return 17;case R.packetentities:return 18;case R.deltapacketentities:return 19;case R.print:return 11;case R.centerprint:return 16;case R.stufftext:return 12;case R.sound:return 10;case R.temp_entity:return 9;case R.configstring:return 14;case R.spawnbaseline:return 15;case R.layout:return 7;case R.inventory:return 6;case R.muzzleflash:return 8;case R.muzzleflash2:return 20}return e}writeCommand(e,r){let n=r??this.protocol;n===34||n===0?this.writer.writeByte(this.getOpcode(e)):this.writer.writeByte(e)}writeServerData(e,r,n,i,a,o){this.writeCommand(R.serverdata),this.writer.writeLong(e),this.writer.writeLong(r),this.writer.writeByte(n),this.writer.writeString(i),this.writer.writeShort(a),this.writer.writeString(o)}writeConfigString(e,r){this.writeCommand(R.configstring),this.writer.writeShort(e),this.writer.writeString(r)}writeStuffText(e){this.writeCommand(R.stufftext),this.writer.writeString(e)}writeCenterPrint(e){this.writeCommand(R.centerprint),this.writer.writeString(e)}writePrint(e,r){this.writeCommand(R.print),this.writer.writeByte(e),this.writer.writeString(r)}writeLayout(e){this.writeCommand(R.layout),this.writer.writeString(e)}writeInventory(e){this.writeCommand(R.inventory);for(let r of e)this.writer.writeShort(r);for(let r=e.length;r<256;r++)this.writer.writeShort(0)}writeMuzzleFlash(e,r){this.writeCommand(R.muzzleflash),this.writer.writeShort(e),this.writer.writeByte(r)}writeMuzzleFlash2(e,r){this.writeCommand(R.muzzleflash2),this.writer.writeShort(e),this.writer.writeByte(r)}writeSound(e,r,n,i,a,o,s,c){this.writeCommand(R.sound),this.writer.writeByte(e),this.writer.writeByte(r),e&1&&this.writer.writeByte(n),e&2&&this.writer.writeByte(i),e&16&&this.writer.writeByte(a),e&8&&this.writer.writeShort(o),e&4&&(this.writer.writeCoord(s.x),this.writer.writeCoord(s.y),this.writer.writeCoord(s.z))}writeTempEntity(e,r,n,i,a,o,s,c,l){this.writeCommand(R.temp_entity),this.writer.writeByte(e),r&&this.writer.writePos(r)}writePlayerState(e){this.writeCommand(R.playerinfo);let r=0;e.pm_type!==0&&(r|=1),(e.origin.x!==0||e.origin.y!==0||e.origin.z!==0)&&(r|=2),(e.velocity.x!==0||e.velocity.y!==0||e.velocity.z!==0)&&(r|=4),e.pm_time!==0&&(r|=8),e.pm_flags!==0&&(r|=16),e.gravity!==0&&(r|=32),(e.delta_angles.x!==0||e.delta_angles.y!==0||e.delta_angles.z!==0)&&(r|=64),(e.viewoffset.x!==0||e.viewoffset.y!==0||e.viewoffset.z!==0)&&(r|=128),(e.viewangles.x!==0||e.viewangles.y!==0||e.viewangles.z!==0)&&(r|=256),(e.kick_angles.x!==0||e.kick_angles.y!==0||e.kick_angles.z!==0)&&(r|=512),e.gun_index!==0&&(r|=4096),(e.gun_frame!==0||e.gun_offset.x!==0||e.gun_offset.y!==0||e.gun_offset.z!==0||e.gun_angles.x!==0||e.gun_angles.y!==0||e.gun_angles.z!==0)&&(r|=8192),(e.blend[0]!==0||e.blend[1]!==0||e.blend[2]!==0||e.blend[3]!==0)&&(r|=1024),e.fov!==0&&(r|=2048),e.rdflags!==0&&(r|=16384),e.watertype!==0&&(r|=32768),this.writer.writeShort(r),r&1&&this.writer.writeByte(e.pm_type),r&2&&(this.writer.writeShort(e.origin.x/.125),this.writer.writeShort(e.origin.y/.125),this.writer.writeShort(e.origin.z/.125)),r&4&&(this.writer.writeShort(e.velocity.x/.125),this.writer.writeShort(e.velocity.y/.125),this.writer.writeShort(e.velocity.z/.125)),r&8&&this.writer.writeByte(e.pm_time),r&16&&this.writer.writeByte(e.pm_flags),r&32&&this.writer.writeShort(e.gravity),r&64&&(this.writer.writeShort(e.delta_angles.x/(180/32768)),this.writer.writeShort(e.delta_angles.y/(180/32768)),this.writer.writeShort(e.delta_angles.z/(180/32768))),r&128&&(this.writer.writeByte(e.viewoffset.x/.25),this.writer.writeByte(e.viewoffset.y/.25),this.writer.writeByte(e.viewoffset.z/.25)),r&256&&(this.writer.writeShort(e.viewangles.x/(360/65536)),this.writer.writeShort(e.viewangles.y/(360/65536)),this.writer.writeShort(e.viewangles.z/(360/65536))),r&512&&(this.writer.writeByte(e.kick_angles.x/.25),this.writer.writeByte(e.kick_angles.y/.25),this.writer.writeByte(e.kick_angles.z/.25)),r&4096&&this.writer.writeByte(e.gun_index),r&8192&&(this.writer.writeByte(e.gun_frame),this.writer.writeByte(e.gun_offset.x/.25),this.writer.writeByte(e.gun_offset.y/.25),this.writer.writeByte(e.gun_offset.z/.25),this.writer.writeByte(e.gun_angles.x/.25),this.writer.writeByte(e.gun_angles.y/.25),this.writer.writeByte(e.gun_angles.z/.25)),r&1024&&(this.writer.writeByte(e.blend[0]),this.writer.writeByte(e.blend[1]),this.writer.writeByte(e.blend[2]),this.writer.writeByte(e.blend[3])),r&2048&&this.writer.writeByte(e.fov),r&16384&&this.writer.writeByte(e.rdflags),r&32768&&this.writer.writeByte(e.watertype);let n=0;for(let i=0;i<32;i++)e.stats[i]!==0&&(n|=1<<i);this.writer.writeLong(n);for(let i=0;i<32;i++)n&1<<i&&this.writer.writeShort(e.stats[i])}writePacketEntities(e,r,n){this.writeCommand(r?R.deltapacketentities:R.packetentities);for(let i of e)this.writeDeltaEntity(Wr(),i,!0);this.writer.writeShort(0)}writeFrame(e,r){this.writeCommand(R.frame),this.writer.writeLong(e.serverFrame),this.writer.writeLong(e.deltaFrame),r!==26&&r!==25&&this.writer.writeByte(e.surpressCount),this.writer.writeByte(e.areaBytes),this.writer.writeBytes(e.areaBits),this.writePlayerState(e.playerState),this.writePacketEntities(e.packetEntities.entities,e.packetEntities.delta,r)}writeDeltaEntity(e,r,n){let i=0,a=0;(r.modelindex!==e.modelindex||n)&&(i|=Rt),(r.modelindex2!==e.modelindex2||n)&&(i|=Bt),(r.modelindex3!==e.modelindex3||n)&&(i|=Ft),(r.modelindex4!==e.modelindex4||n)&&(i|=It),(r.frame!==e.frame||n)&&(r.frame>=256?i|=Ct:i|=Et),(r.skinnum!==e.skinnum||n)&&(r.skinnum>=256?i|=Je:i|=Ze),(r.effects!==e.effects||n)&&(r.effects>=256?i|=Qe:i|=qe),(r.renderfx!==e.renderfx||n)&&(r.renderfx>=256?i|=je:i|=Ye),(r.origin.x!==e.origin.x||n)&&r.origin.x!==0&&(i|=St),(r.origin.y!==e.origin.y||n)&&r.origin.y!==0&&(i|=wt),(r.origin.z!==e.origin.z||n)&&r.origin.z!==0&&(i|=Lt),(r.angles.x!==e.angles.x||n)&&r.angles.x!==0&&(i|=Pt),(r.angles.y!==e.angles.y||n)&&r.angles.y!==0&&(i|=Mt),(r.angles.z!==e.angles.z||n)&&r.angles.z!==0&&(i|=At),(r.sound!==e.sound||n)&&(i|=Dt),(r.event!==e.event||n)&&(i|=Tt),(r.solid!==e.solid||n)&&(i|=kt),this.protocol!==34&&((r.alpha!==e.alpha||n)&&(i|=Ar),(r.scale!==e.scale||n)&&(i|=Lr),(r.instanceBits!==e.instanceBits||n)&&(i|=Pr),(r.loopVolume!==e.loopVolume||n)&&(i|=Rr),(r.loopAttenuation!==e.loopAttenuation||n)&&(a|=_n),(r.owner!==e.owner||n)&&(a|=Sn),(r.oldFrame!==e.oldFrame||n)&&(a|=wn)),a>0&&(i|=Ni),i&4278190080&&(i|=Tr),i&4294901760&&(i|=Er),i&4294967040&&(i|=Mr),this.writer.writeByte(i&255),i&Mr&&this.writer.writeByte(i>>8&255),i&Er&&this.writer.writeByte(i>>16&255),i&Tr&&this.writer.writeByte(i>>24&255),i&Ni&&this.writer.writeByte(a&255),r.number>=256?this.writer.writeShort(r.number):this.writer.writeByte(r.number),i&Rt&&this.writer.writeByte(r.modelindex),i&Bt&&this.writer.writeByte(r.modelindex2),i&Ft&&this.writer.writeByte(r.modelindex3),i&It&&this.writer.writeByte(r.modelindex4),i&Et&&this.writer.writeByte(r.frame),i&Ct&&this.writer.writeShort(r.frame),i&Ze&&this.writer.writeByte(r.skinnum),i&Je&&this.writer.writeShort(r.skinnum),i&qe&&this.writer.writeByte(r.effects),i&Qe&&this.writer.writeShort(r.effects),i&Ye&&this.writer.writeByte(r.renderfx),i&je&&this.writer.writeShort(r.renderfx),i&St&&this.writer.writeCoord(r.origin.x),i&wt&&this.writer.writeCoord(r.origin.y),i&Lt&&this.writer.writeCoord(r.origin.z),i&Pt&&this.writer.writeAngle(r.angles.x),i&Mt&&this.writer.writeAngle(r.angles.y),i&At&&this.writer.writeAngle(r.angles.z),i&Dt&&this.writer.writeByte(r.sound??0),i&Tt&&this.writer.writeByte(r.event??0),i&kt&&this.writer.writeShort(r.solid),this.protocol!==34&&(i&Ar&&this.writer.writeByte(r.alpha*255),i&Lr&&this.writer.writeFloat(r.scale),i&Pr&&this.writer.writeLong(r.instanceBits),i&Rr&&this.writer.writeByte(r.loopVolume*255),a&_n&&this.writer.writeByte(r.loopAttenuation*255),a&Sn&&this.writer.writeShort(r.owner),a&wn&&this.writer.writeShort(r.oldFrame))}};var Jc=class{static validate(e,r){if(r&&!r.toLowerCase().endsWith(".dm2"))return{valid:!1,error:"Invalid file extension (expected .dm2)"};if(e.byteLength<5)return{valid:!1,error:"File too small to be a valid demo"};let n=new DataView(e),i=n.getInt32(0,!0);if(i<=0||i>e.byteLength-4)return{valid:!1,error:`Invalid first block length: ${i}`};let a=n.getUint8(4);if(a!==R.serverdata)return{valid:!1,error:`First command is not svc_serverdata (expected ${R.serverdata}, got ${a})`};let o=-1;return i>=5&&(o=n.getInt32(5,!0)),{valid:!0,version:o}}};var eu=class{constructor(e){this.frames=[];this.configStrings=new Map;this.baselines=new Map;this.currentEntities=new Map;if(e){let r=new Qn(e.byteLength);r.append(new Uint8Array(e)),r.setReadPosition(0),this.parser=new xt(r,this)}else this.parser=new xt(new Qn,this)}extractClip(e,r,n,i){let a=new vr(e.buffer),o=[],s=0,c=r.frame??-1,l=n.frame??Number.MAX_SAFE_INTEGER,u=0,d=0;for(;a.nextBlock();){let p=a.getBlock().data,y=!1,v=-1,b=!1,x={onServerData:S=>{u=S,y=!0,b=!0},onConfigString:()=>{y=!0,b=!0},onSpawnBaseline:()=>{y=!0,b=!0},onFrame:S=>{v=S.serverFrame,b=!0,v>=c&&v<=l&&(y=!0)},onCenterPrint:()=>{b=!0},onStuffText:()=>{b=!0},onPrint:()=>{b=!0},onSound:()=>{b=!0},onTempEntity:()=>{b=!0},onLayout:()=>{b=!0},onInventory:()=>{b=!0},onMuzzleFlash:()=>{b=!0},onMuzzleFlash2:()=>{b=!0},onDisconnect:()=>{b=!0},onReconnect:()=>{b=!0},onDownload:()=>{b=!0}},_=new Qn(p.getLength());_.append(p.readData(p.getLength())),_.setReadPosition(0),p.seek(0);let w=new xt(_,x);u>0&&w.setProtocolVersion(u);try{w.parseMessage()}catch{}if(b||d>=c&&d<=l&&(y=!0),y){let S=new Uint8Array(4);new DataView(S.buffer).setUint32(0,p.getLength(),!0),o.push(S);let T=p.readData(p.getLength());o.push(T),s+=4+T.length}d++}let f=new Uint8Array(4);new DataView(f.buffer).setInt32(0,-1,!0),o.push(f),s+=4;let h=new Uint8Array(s),m=0;for(let g of o)h.set(g,m),m+=g.length;return h}extractDemoRange(e,r,n){return this.extractClip(e,{frame:r},{frame:n})}onServerData(e,r,n,i,a,o){this.serverData={protocol:e,serverCount:r,attractLoop:n,gameDir:i,playerNum:a,levelName:o}}onConfigString(e,r){this.configStrings.set(e,r)}onSpawnBaseline(e){this.baselines.set(e.number,e)}onFrame(e){this.frames.push(e)}onCenterPrint(e){}onStuffText(e){}onPrint(e,r){}onSound(e,r,n,i,a,o,s){}onTempEntity(e,r,n,i,a,o,s,c,l){}onLayout(e){}onInventory(e){}onMuzzleFlash(e,r){}onMuzzleFlash2(e,r){}onDisconnect(){}onReconnect(){}onDownload(e,r,n){}};function $0(t,e){let r=e.bits;t.bits=r,t.number=e.number,r&Rt&&(t.modelindex=e.modelindex),r&Bt&&(t.modelindex2=e.modelindex2),r&Ft&&(t.modelindex3=e.modelindex3),r&It&&(t.modelindex4=e.modelindex4),r&Et&&(t.frame=e.frame),r&Ct&&(t.frame=e.frame),r&Ze&&(t.skinnum=e.skinnum),r&Je&&(t.skinnum=e.skinnum),r&qe&&(t.effects=e.effects),r&Qe&&(t.effects=e.effects),r&Ye&&(t.renderfx=e.renderfx),r&je&&(t.renderfx=e.renderfx),r&St&&(t.origin.x=e.origin.x),r&wt&&(t.origin.y=e.origin.y),r&Lt&&(t.origin.z=e.origin.z),r&Pt&&(t.angles.x=e.angles.x),r&Mt&&(t.angles.y=e.angles.y),r&At&&(t.angles.z=e.angles.z),r&pr&&(t.old_origin.x=e.old_origin.x,t.old_origin.y=e.old_origin.y,t.old_origin.z=e.old_origin.z),r&Dt&&(t.sound=e.sound),r&Tt&&(t.event=e.event),r&kt&&(t.solid=e.solid),r&Ar&&(t.alpha=e.alpha),r&Lr&&(t.scale=e.scale),r&Pr&&(t.instanceBits=e.instanceBits),r&Rr&&(t.loopVolume=e.loopVolume)}var kf=(f=>(f.Unknown="unknown",f.BSP="bsp",f.MD2="md2",f.MD3="md3",f.WAL="wal",f.PCX="pcx",f.TGA="tga",f.WAV="wav",f.OGG="ogg",f.TXT="txt",f.CFG="cfg",f.DEM="dem",f))(kf||{}),K0={".bsp":"bsp",".md2":"md2",".md3":"md3",".wal":"wal",".pcx":"pcx",".tga":"tga",".wav":"wav",".ogg":"ogg",".txt":"txt",".cfg":"cfg",".dm2":"dem"};function Vs(t,e){if(t.length<e.length)return!1;for(let r=0;r<e.length;r++)if(t[r]!==e[r])return!1;return!0}var v2=[73,66,83,80],_2=[73,68,80,50],S2=[73,68,80,51];var w2=[82,73,70,70];var M2=[79,103,103,83];function Uf(t,e){let r=t.slice(t.lastIndexOf(".")).toLowerCase();if(e){if(Vs(e,v2))return"bsp";if(Vs(e,_2))return"md2";if(Vs(e,S2))return"md3";if(Vs(e,M2))return"ogg";if(e.length>128&&e[0]===10&&e[1]<6)return"pcx";if(Vs(e,w2)&&e.length>=12&&e[8]===87&&e[9]===65&&e[10]===86&&e[11]===69)return"wav"}return K0[r]?K0[r]:"unknown"}function zf(t){let e=Uf(t);return e==="txt"||e==="cfg"}function Y0(t){return!zf(t)}function A2(t,e,r,n,i){let a=new Uint8ClampedArray(n*i*4),o=e/n,s=r/i;for(let c=0;c<i;c++)for(let l=0;l<n;l++){let u=l*o,d=c*s,f=Math.floor(u),h=Math.floor(d),m=u-f,g=d-h,p=Math.min(f+1,e-1),y=Math.min(h+1,r-1),v=(h*e+f)*4,b=(h*e+p)*4,x=(y*e+f)*4,_=(y*e+p)*4,w=(c*n+l)*4;for(let S=0;S<4;S++){let A=t[v+S],T=t[b+S],M=t[x+S],P=t[_+S],I=A*(1-m)+T*m,D=M*(1-m)+P*m,B=I*(1-g)+D*g;a[w+S]=B}}return a}function E2(t,e,r,n,i,a,o,s,c,l,u){n=Math.floor(n),i=Math.floor(i),a=Math.floor(a),o=Math.floor(o);let d=Math.abs(a-n),f=Math.abs(o-i),h=n<a?1:-1,m=i<o?1:-1,g=d-f;for(;;){if(n>=0&&n<e&&i>=0&&i<r){let y=(i*e+n)*4,v=1-u/255;t[y]=s*(u/255)+t[y]*v,t[y+1]=c*(u/255)+t[y+1]*v,t[y+2]=l*(u/255)+t[y+2]*v,t[y+3]=255}if(n===a&&i===o)break;let p=2*g;p>-f&&(g-=f,n+=h),p<d&&(g+=d,i+=m)}}function q0(t,e,r,n,i){let s=(t.x-n.x)*.707-(t.y-n.y)*.707,c=(t.x-n.x)*.707+(t.y-n.y)*.707,l=t.z-n.z,u=.866,d=.5,f=c*u-l*d,h=c*d+l*u,m=e/2+s*i,g=r/2-h*i;return{x:m,y:g}}var tu=class{constructor(e){this.assetManager=e}async generateTextureThumbnail(e,r){try{let n=await this.assetManager.loadTexture(e);if(!n||n.levels.length===0)return null;let i=n.levels[0],a=i.width/i.height,o=r,s=r;a>1?s=Math.floor(r/a):o=Math.floor(r*a),o=Math.max(1,o),s=Math.max(1,s);let c=A2(i.rgba,i.width,i.height,o,s);return new ImageData(c,o,s)}catch(n){return console.error(`Failed to generate thumbnail for ${e}`,n),null}}async generateModelThumbnail(e,r){try{let n=[],i=[],a=e.split(".").pop()?.toLowerCase();if(a==="md2"){let p=await this.assetManager.loadMd2Model(e);if(!p||p.frames.length===0)return null;n=p.frames[0].vertices.map(v=>v.position);for(let v of p.triangles)i.push(v.vertexIndices[0],v.vertexIndices[1]),i.push(v.vertexIndices[1],v.vertexIndices[2]),i.push(v.vertexIndices[2],v.vertexIndices[0])}else if(a==="md3"){let p=await this.assetManager.loadMd3Model(e);if(!p||p.surfaces.length===0)return null;let y=0;for(let v of p.surfaces){if(v.vertices.length===0)continue;let b=v.vertices[0];n.push(...b.map(x=>({x:x.position.x,y:x.position.y,z:x.position.z})));for(let x of v.triangles)i.push(y+x.indices[0],y+x.indices[1]),i.push(y+x.indices[1],y+x.indices[2]),i.push(y+x.indices[2],y+x.indices[0]);y+=b.length}}else return null;if(n.length===0)return null;let o={x:1/0,y:1/0,z:1/0},s={x:-1/0,y:-1/0,z:-1/0};for(let p of n)o.x=Math.min(o.x,p.x),o.y=Math.min(o.y,p.y),o.z=Math.min(o.z,p.z),s.x=Math.max(s.x,p.x),s.y=Math.max(s.y,p.y),s.z=Math.max(s.z,p.z);let c={x:(o.x+s.x)/2,y:(o.y+s.y)/2,z:(o.z+s.z)/2},l=s.x-o.x,u=s.y-o.y,d=s.z-o.z,f=Math.max(l,u,d),h=Math.max(f,.001),m=r*.8/h,g=new Uint8ClampedArray(r*r*4);for(let p=0;p<i.length;p+=2){let y=i[p],v=i[p+1],b=n[y],x=n[v],_=q0(b,r,r,c,m),w=q0(x,r,r,c,m);E2(g,r,r,_.x,_.y,w.x,w.y,0,255,0,255)}return new ImageData(g,r,r)}catch(n){return console.error(`Failed to generate model thumbnail for ${e}`,n),null}}async getMapBounds(e,r){try{let n=lo(r);if(n.models.length>0){let i=n.models[0];return{mins:{x:i.mins[0],y:i.mins[1],z:i.mins[2]},maxs:{x:i.maxs[0],y:i.maxs[1],z:i.maxs[2]}}}return null}catch(n){return console.error("Failed to get map bounds",n),null}}async extractMapScreenshot(e){return null}};var ru=class{constructor(e){this.loader=e}async getMapStatistics(e){let r=await this.loader.load(e),n=r.faces.filter(o=>o.lightOffset!==-1).length,i=r.models[0],a=i?{mins:i.mins,maxs:i.maxs}:{mins:[0,0,0],maxs:[0,0,0]};return{entityCount:r.entities.entities.length,surfaceCount:r.faces.length,lightmapCount:n,vertexCount:r.vertices.length,bounds:a}}async getUsedTextures(e){let r=await this.loader.load(e),n=new Set;for(let i of r.texInfo)i.texture&&n.add(i.texture);return Array.from(n).sort()}async getUsedModels(e){let r=await this.loader.load(e),n=new Set;for(let i of r.entities.entities)i.properties.model&&!i.properties.model.startsWith("*")&&n.add(i.properties.model);return Array.from(n).sort()}async getUsedSounds(e){let r=await this.loader.load(e),n=new Set;for(let i of r.entities.entities){i.properties.noise&&n.add(i.properties.noise);for(let[a,o]of Object.entries(i.properties))(a==="noise"||a.endsWith("_sound")||a==="sound")&&typeof o=="string"&&n.add(o)}return Array.from(n).sort()}};function Z0(t){let e=[],r=0,n=t.length;function i(){for(;r<n&&/\s/.test(t[r]);)r++}function a(){if(i(),r>=n)return null;if(t[r]==='"'){r++;let o=r;for(;r<n&&t[r]!=='"';)t[r],r++;let s=t.substring(o,r);return r++,s}else{if(t[r]==="{"||t[r]==="}")return t[r++];{if(t.startsWith("//",r)){for(;r<n&&t[r]!==`
1125
+ `;var Sp=[0,255,255,255],b_=[0,-1,-1,-1];function x_(t=Sp,e=[]){let r=new Float32Array(4);for(let n=0;n<4;n+=1){let i=t[n]??255;if(i===255){r[n]=0;continue}let a=e[i];r[n]=a!==void 0?a:1}return r}function v_(t){return[-(t*.25%1),0]}function __(t=yn,e=0){let r=(t&el)!==0,n=(t&Yr)!==0,i=(t&bn)!==0,a=(t&xn)!==0,o=(t&vn)!==0,s=a?.33:o?.66:1,c=a||o||n,l=!c&&!i,u=r?v_(e):[0,0];return{alpha:s,blend:c,depthWrite:l,warp:n,flowOffset:u,sky:i}}var Dc=class{constructor(e,r,n){this.textureBindGroupCache=new Map;this.device=e;let i=2048,a=256;this.frameUniformBuffer=e.createBuffer({size:i,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this.surfaceUniformBuffer=e.createBuffer({size:a,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this.frameBindGroupLayout=e.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}}]}),this.surfaceBindGroupLayout=e.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}}]}),this.textureBindGroupLayout=e.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,texture:{}},{binding:1,visibility:GPUShaderStage.FRAGMENT,sampler:{}},{binding:2,visibility:GPUShaderStage.FRAGMENT,texture:{}},{binding:3,visibility:GPUShaderStage.FRAGMENT,sampler:{}}]}),this.defaultSampler=Cc(e),this.defaultWhiteTexture=new $n(e,{width:1,height:1,format:"rgba8unorm",label:"bsp-default-white"}),this.defaultWhiteTexture.upload(new Uint8Array([255,255,255,255])),this.defaultBindGroup=e.createBindGroup({layout:this.textureBindGroupLayout,entries:[{binding:0,resource:this.defaultWhiteTexture.createView()},{binding:1,resource:this.defaultSampler.sampler},{binding:2,resource:this.defaultWhiteTexture.createView()},{binding:3,resource:this.defaultSampler.sampler}]}),this.createPipelines(r,n),this.frameBindGroup=e.createBindGroup({layout:this.frameBindGroupLayout,entries:[{binding:0,resource:{buffer:this.frameUniformBuffer}}]})}createPipelines(e,r){let n=this.device.createShaderModule({code:_p}),i=this.device.createPipelineLayout({bindGroupLayouts:[this.frameBindGroupLayout,this.surfaceBindGroupLayout,this.textureBindGroupLayout]}),a={module:n,entryPoint:"vertexMain",buffers:[{arrayStride:32,attributes:[{shaderLocation:0,offset:0,format:"float32x3"},{shaderLocation:1,offset:12,format:"float32x2"},{shaderLocation:2,offset:20,format:"float32x2"},{shaderLocation:3,offset:28,format:"float32"}]}]};this.pipeline=this.device.createRenderPipeline({layout:i,vertex:a,fragment:{module:n,entryPoint:"fragmentMain",targets:[{format:e,blend:{color:{srcFactor:"src-alpha",dstFactor:"one-minus-src-alpha",operation:"add"},alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"}}}]},primitive:{topology:"triangle-list",cullMode:"back"},depthStencil:{format:r,depthWriteEnabled:!0,depthCompare:"less"}}),this.pipelineWireframe=this.device.createRenderPipeline({layout:i,vertex:a,fragment:{module:n,entryPoint:"fragmentMain",targets:[{format:e,writeMask:GPUColorWrite.ALL}]},primitive:{topology:"line-list"},depthStencil:{format:r,depthWriteEnabled:!0,depthCompare:"less"}})}bind(e,r){let{modelViewProjection:n,styleIndices:i=Sp,styleLayers:a=b_,styleValues:o=[],diffuseTexture:s,diffuseSampler:c,lightmapTexture:l,lightmapSampler:u,surfaceFlags:d=yn,timeSeconds:f=0,texScroll:h,alpha:m,warp:g,dlights:p=[],renderMode:y,lightmapOnly:v,brightness:b=1,gamma:x=1,fullbright:_=!1,ambient:w=0,cameraPosition:S=[0,0,0]}=r,A=__(d,f),L=x_(i,o),M=h?h[0]:A.flowOffset[0],P=h?h[1]:A.flowOffset[1],I=m!==void 0?m:A.alpha,D=g!==void 0?g:A.warp,B=new Float32Array(512);B.set(n,0),B.set(S,16),B[19]=0,B[20]=f,B[21]=b,B[22]=x,B[23]=w;let O=Math.min(p.length,Or),Q=new Uint32Array(B.buffer,96,1);Q[0]=O;let Ge=new Uint32Array(B.buffer,100,1);Ge[0]=_?1:0;let me=32;for(let ut=0;ut<O;ut++){let He=p[ut];B[me+0]=He.origin.x,B[me+1]=He.origin.y,B[me+2]=He.origin.z,B[me+3]=He.intensity,B[me+4]=He.color.x,B[me+5]=He.color.y,B[me+6]=He.color.z,B[me+7]=0,me+=8}this.device.queue.writeBuffer(this.frameUniformBuffer,0,B,0,me);let Me=new Float32Array(32);Me[0]=M,Me[1]=P,Me[2]=A.flowOffset[0],Me[3]=A.flowOffset[1],Me.set(L,4),Me.set(a,8);let ge=0,ue=[1,1,1,1];y&&(y.mode==="solid"||y.mode==="wireframe"?ge=1:y.mode==="solid-faceted"&&(ge=2),y.color?ue=[...y.color]:y.generateRandomColor&&(ue=[1,1,1,1])),Me.set(ue,12),Me[16]=I;let ye=new Uint32Array(Me.buffer),Ve=!A.sky&&u!==void 0&&!D;ye[17]=Ve?1:0,ye[18]=D?1:0,ye[19]=v?1:0,ye[20]=ge,this.device.queue.writeBuffer(this.surfaceUniformBuffer,0,Me);let ct=this.device.createBindGroup({layout:this.surfaceBindGroupLayout,entries:[{binding:0,resource:{buffer:this.surfaceUniformBuffer}}]});if(s&&c&&l&&u){let ut=this.device.createBindGroup({layout:this.textureBindGroupLayout,entries:[{binding:0,resource:s},{binding:1,resource:c},{binding:2,resource:l},{binding:3,resource:u}]});e.setBindGroup(2,ut)}else e.setBindGroup(2,this.defaultBindGroup);let qt=y&&y.mode==="wireframe"?this.pipelineWireframe:this.pipeline;return e.setPipeline(qt),e.setBindGroup(0,this.frameBindGroup),e.setBindGroup(1,ct),A}draw(e,r,n){r.gpuIndexBuffer&&(n&&n.mode==="wireframe"||(e.setVertexBuffer(0,r.gpuVertexBuffer),e.setIndexBuffer(r.gpuIndexBuffer,"uint16"),e.drawIndexed(r.indexCount)))}destroy(){this.frameUniformBuffer.destroy(),this.surfaceUniformBuffer.destroy(),this.defaultWhiteTexture.destroy()}};var ef=class{constructor(e,r,n){this.context=e;this.frameRenderer=r;this.pipelines=n;this.type="webgpu";this.picCache=new Map;this.font=null;this.is2DActive=!1;this.whiteTexture=new $n(e.device,{width:1,height:1,format:e.format,label:"white-texture"}),this.whiteTexture.upload(new Uint8Array([255,255,255,255])),this.collisionVis=null,this.debug=null,this.particleSystem=null}get device(){return this.context.device}get width(){return this.context.width}get height(){return this.context.height}renderFrame(e,r=[],n){let i=e,a=i.dlights;if(i.dlights&&i.dlights.length>0){let s=new Float32Array(i.camera.viewProjectionMatrix),c=sr(s),l={x:i.camera.position[0],y:i.camera.position[1],z:i.camera.position[2]};a=Mc(i.dlights,c,l,32)}let o={...i,dlights:a};this.frameRenderer.renderFrame(o)}uploadBspGeometry(e){for(let r of e){if(r.gpuVertexBuffer&&r.gpuIndexBuffer)continue;let n=new Ia(this.device,{size:r.vertexData.byteLength,label:`bsp-surface-vb-${r.texture}`});n.write(r.vertexData);let i=new Da(this.device,{size:r.indexData.byteLength,label:`bsp-surface-ib-${r.texture}`});i.write(r.indexData);let a=r;a.gpuVertexBuffer=n.buffer,a.gpuIndexBuffer=i.buffer}}async registerPic(e,r){if(this.picCache.has(e))return this.picCache.get(e);let n=new $n(this.device,{width:256,height:256,format:this.context.format,label:`pic-${e}`});return n.upload(r),this.picCache.set(e,n),n}registerTexture(e,r){if(this.picCache.has(e))return this.picCache.get(e);let n=new $n(this.device,{width:r.width,height:r.height,format:this.context.format,mipLevelCount:r.levels.length,label:`texture-${e}`});for(let i of r.levels)n.upload(i.rgba,{width:i.width,height:i.height,mipLevel:i.level});return this.picCache.set(e,n),n}begin2D(){this.frameRenderer.begin2DPass(),this.is2DActive=!0}end2D(){this.frameRenderer.end2DPass(),this.is2DActive=!1}drawPic(e,r,n,i=[1,1,1,1]){if(!this.is2DActive)throw new Error("drawPic called outside begin2D/end2D");this.pipelines.sprite.drawTexturedQuad(e,r,n.width,n.height,n,0,0,1,1,i)}drawfillRect(e,r,n,i,a){if(!this.is2DActive)throw new Error("drawfillRect called outside begin2D/end2D");this.pipelines.sprite.drawSolidRect(e,r,n,i,a)}drawString(e,r,n,i=[1,1,1,1]){if(!this.is2DActive)throw new Error("drawString called outside begin2D/end2D");if(!this.font)return;let a=_c(n),o=e,s=8,c=8;for(let l of a){let u=l.color||i;for(let d of l.text){let f=d.charCodeAt(0),h=f%16,m=Math.floor(f/16),g=h/16,p=m/16,y=(h+1)/16,v=(m+1)/16;this.pipelines.sprite.drawTexturedQuad(o,r,s,c,this.font,g,p,y,v,u),o+=s}}}drawCenterString(e,r){if(!this.is2DActive)throw new Error("drawCenterString called outside begin2D/end2D");let a=r.replace(/\^[0-9]/g,"").length*8,o=(this.width-a)/2;this.drawString(o,e,r)}setEntityHighlight(e,r){}clearEntityHighlight(e){}highlightSurface(e,r){}removeSurfaceHighlight(e){}setDebugMode(e){}setBrightness(e){}setGamma(e){}setFullbright(e){}setAmbient(e){}setLightStyle(e,r){}setUnderwaterWarp(e){}setBloom(e){}setBloomIntensity(e){}setLodBias(e){}renderInstanced(e,r){}getPerformanceReport(){return{frameTimeMs:0,gpuTimeMs:0,cpuFrameTimeMs:0,drawCalls:0,triangles:0,vertices:0,textureBinds:0,shaderSwitches:0,visibleSurfaces:0,culledSurfaces:0,visibleEntities:0,culledEntities:0,memoryUsageMB:{textures:0,geometry:0,total:0}}}getMemoryUsage(){return{texturesBytes:0,geometryBytes:0,shadersBytes:0,buffersBytes:0,totalBytes:0}}resize(e,r){this.context.context&&!this.context.isHeadless?(this.context.width=e,this.context.height=r):(this.context.width=e,this.context.height=r)}dispose(){this.pipelines.sprite.destroy(),this.pipelines.skybox.destroy(),this.pipelines.bsp.destroy();for(let e of this.picCache.values())e.destroy();this.picCache.clear(),this.whiteTexture.destroy(),this.context.device.destroy()}destroy(){this.dispose()}};async function wp(t,e){let r=await Ac(t,e),n=new Fc(r.device,r.format),i=new Ic(r.device,r.format),a=new Dc(r.device,r.format,r.depthFormat||"depth24plus"),o={sprite:n,skybox:i,bsp:a};t?(r.width=t.width,r.height=t.height):(r.width=800,r.height=600);let s=new Ec(r,o);return new ef(r,s,o)}var vr=class{constructor(e){this.messageOffsets=[];this.currentBlock=null;this.buffer=e,this.view=new DataView(e),this.offset=0,this.scan()}scan(){let e=0;for(this.messageOffsets=[];e+4<=this.buffer.byteLength;){let r=this.view.getInt32(e,!0);if(r===-1)break;if(r<0||r>2097152){console.warn(`DemoReader: Invalid block length ${r} at offset ${e} during scan`);break}if(e+4+r>this.buffer.byteLength){console.warn(`DemoReader: Incomplete block at offset ${e} during scan`);break}this.messageOffsets.push(e),e+=4+r}}hasMore(){return this.offset<this.buffer.byteLength}readNextBlock(){if(this.offset+4>this.buffer.byteLength)return null;let e=this.view.getInt32(this.offset,!0);if(e===-1||e<0||this.offset+4+e>this.buffer.byteLength)return null;this.offset+=4;let r=this.buffer.slice(this.offset,this.offset+e);return this.offset+=e,{length:e,data:new Mn(r)}}nextBlock(){let e=this.readNextBlock();return e?(this.currentBlock=e,!0):(this.currentBlock=null,!1)}getBlock(){if(!this.currentBlock)throw new Error("No current block. Call nextBlock() first.");return this.currentBlock}readAllBlocksToBuffer(){let e=0,r=this.offset,n=[],i=this.offset;for(;i+4<=this.buffer.byteLength;){let c=this.view.getInt32(i,!0);if(c===-1||c<0||i+4+c>this.buffer.byteLength)break;n.push({offset:i+4,length:c}),e+=c,i+=4+c}let a=new Uint8Array(e),o=0,s=new Uint8Array(this.buffer);for(let c of n)a.set(s.subarray(c.offset,c.offset+c.length),o),o+=c.length;return this.offset=i,a.buffer}reset(){this.offset=0,this.currentBlock=null}seekToMessage(e){return e<0||e>=this.messageOffsets.length?!1:(this.offset=this.messageOffsets[e],this.currentBlock=null,!0)}getMessageCount(){return this.messageOffsets.length}getOffset(){return this.offset}getProgress(){let e=this.offset,r=this.buffer.byteLength;return{current:e,total:r,percent:r>0?e/r*100:0}}};function Ha(t){let e=t.length;for(;--e>=0;)t[e]=0}var S_=0,l0=1,w_=2,M_=3,A_=258,Af=29,Ds=256,Ls=Ds+1+Af,Na=30,Ef=19,c0=2*Ls+1,Pi=15,tf=16,E_=7,Lf=256,u0=16,d0=17,f0=18,gf=new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]),Gc=new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]),L_=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),h0=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),T_=512,fn=new Array((Ls+2)*2);Ha(fn);var Ms=new Array(Na*2);Ha(Ms);var Ts=new Array(T_);Ha(Ts);var Ps=new Array(A_-M_+1);Ha(Ps);var Tf=new Array(Af);Ha(Tf);var Vc=new Array(Na);Ha(Vc);function rf(t,e,r,n,i){this.static_tree=t,this.extra_bits=e,this.extra_base=r,this.elems=n,this.max_length=i,this.has_stree=t&&t.length}var m0,p0,g0;function nf(t,e){this.dyn_tree=t,this.max_code=0,this.stat_desc=e}var y0=t=>t<256?Ts[t]:Ts[256+(t>>>7)],Rs=(t,e)=>{t.pending_buf[t.pending++]=e&255,t.pending_buf[t.pending++]=e>>>8&255},Ot=(t,e,r)=>{t.bi_valid>tf-r?(t.bi_buf|=e<<t.bi_valid&65535,Rs(t,t.bi_buf),t.bi_buf=e>>tf-t.bi_valid,t.bi_valid+=r-tf):(t.bi_buf|=e<<t.bi_valid&65535,t.bi_valid+=r)},Gr=(t,e,r)=>{Ot(t,r[e*2],r[e*2+1])},b0=(t,e)=>{let r=0;do r|=t&1,t>>>=1,r<<=1;while(--e>0);return r>>>1},P_=t=>{t.bi_valid===16?(Rs(t,t.bi_buf),t.bi_buf=0,t.bi_valid=0):t.bi_valid>=8&&(t.pending_buf[t.pending++]=t.bi_buf&255,t.bi_buf>>=8,t.bi_valid-=8)},R_=(t,e)=>{let r=e.dyn_tree,n=e.max_code,i=e.stat_desc.static_tree,a=e.stat_desc.has_stree,o=e.stat_desc.extra_bits,s=e.stat_desc.extra_base,c=e.stat_desc.max_length,l,u,d,f,h,m,g=0;for(f=0;f<=Pi;f++)t.bl_count[f]=0;for(r[t.heap[t.heap_max]*2+1]=0,l=t.heap_max+1;l<c0;l++)u=t.heap[l],f=r[r[u*2+1]*2+1]+1,f>c&&(f=c,g++),r[u*2+1]=f,!(u>n)&&(t.bl_count[f]++,h=0,u>=s&&(h=o[u-s]),m=r[u*2],t.opt_len+=m*(f+h),a&&(t.static_len+=m*(i[u*2+1]+h)));if(g!==0){do{for(f=c-1;t.bl_count[f]===0;)f--;t.bl_count[f]--,t.bl_count[f+1]+=2,t.bl_count[c]--,g-=2}while(g>0);for(f=c;f!==0;f--)for(u=t.bl_count[f];u!==0;)d=t.heap[--l],!(d>n)&&(r[d*2+1]!==f&&(t.opt_len+=(f-r[d*2+1])*r[d*2],r[d*2+1]=f),u--)}},x0=(t,e,r)=>{let n=new Array(Pi+1),i=0,a,o;for(a=1;a<=Pi;a++)i=i+r[a-1]<<1,n[a]=i;for(o=0;o<=e;o++){let s=t[o*2+1];s!==0&&(t[o*2]=b0(n[s]++,s))}},C_=()=>{let t,e,r,n,i,a=new Array(Pi+1);for(r=0,n=0;n<Af-1;n++)for(Tf[n]=r,t=0;t<1<<gf[n];t++)Ps[r++]=n;for(Ps[r-1]=n,i=0,n=0;n<16;n++)for(Vc[n]=i,t=0;t<1<<Gc[n];t++)Ts[i++]=n;for(i>>=7;n<Na;n++)for(Vc[n]=i<<7,t=0;t<1<<Gc[n]-7;t++)Ts[256+i++]=n;for(e=0;e<=Pi;e++)a[e]=0;for(t=0;t<=143;)fn[t*2+1]=8,t++,a[8]++;for(;t<=255;)fn[t*2+1]=9,t++,a[9]++;for(;t<=279;)fn[t*2+1]=7,t++,a[7]++;for(;t<=287;)fn[t*2+1]=8,t++,a[8]++;for(x0(fn,Ls+1,a),t=0;t<Na;t++)Ms[t*2+1]=5,Ms[t*2]=b0(t,5);m0=new rf(fn,gf,Ds+1,Ls,Pi),p0=new rf(Ms,Gc,0,Na,Pi),g0=new rf(new Array(0),L_,0,Ef,E_)},v0=t=>{let e;for(e=0;e<Ls;e++)t.dyn_ltree[e*2]=0;for(e=0;e<Na;e++)t.dyn_dtree[e*2]=0;for(e=0;e<Ef;e++)t.bl_tree[e*2]=0;t.dyn_ltree[Lf*2]=1,t.opt_len=t.static_len=0,t.sym_next=t.matches=0},_0=t=>{t.bi_valid>8?Rs(t,t.bi_buf):t.bi_valid>0&&(t.pending_buf[t.pending++]=t.bi_buf),t.bi_buf=0,t.bi_valid=0},Mp=(t,e,r,n)=>{let i=e*2,a=r*2;return t[i]<t[a]||t[i]===t[a]&&n[e]<=n[r]},af=(t,e,r)=>{let n=t.heap[r],i=r<<1;for(;i<=t.heap_len&&(i<t.heap_len&&Mp(e,t.heap[i+1],t.heap[i],t.depth)&&i++,!Mp(e,n,t.heap[i],t.depth));)t.heap[r]=t.heap[i],r=i,i<<=1;t.heap[r]=n},Ap=(t,e,r)=>{let n,i,a=0,o,s;if(t.sym_next!==0)do n=t.pending_buf[t.sym_buf+a++]&255,n+=(t.pending_buf[t.sym_buf+a++]&255)<<8,i=t.pending_buf[t.sym_buf+a++],n===0?Gr(t,i,e):(o=Ps[i],Gr(t,o+Ds+1,e),s=gf[o],s!==0&&(i-=Tf[o],Ot(t,i,s)),n--,o=y0(n),Gr(t,o,r),s=Gc[o],s!==0&&(n-=Vc[o],Ot(t,n,s)));while(a<t.sym_next);Gr(t,Lf,e)},yf=(t,e)=>{let r=e.dyn_tree,n=e.stat_desc.static_tree,i=e.stat_desc.has_stree,a=e.stat_desc.elems,o,s,c=-1,l;for(t.heap_len=0,t.heap_max=c0,o=0;o<a;o++)r[o*2]!==0?(t.heap[++t.heap_len]=c=o,t.depth[o]=0):r[o*2+1]=0;for(;t.heap_len<2;)l=t.heap[++t.heap_len]=c<2?++c:0,r[l*2]=1,t.depth[l]=0,t.opt_len--,i&&(t.static_len-=n[l*2+1]);for(e.max_code=c,o=t.heap_len>>1;o>=1;o--)af(t,r,o);l=a;do o=t.heap[1],t.heap[1]=t.heap[t.heap_len--],af(t,r,1),s=t.heap[1],t.heap[--t.heap_max]=o,t.heap[--t.heap_max]=s,r[l*2]=r[o*2]+r[s*2],t.depth[l]=(t.depth[o]>=t.depth[s]?t.depth[o]:t.depth[s])+1,r[o*2+1]=r[s*2+1]=l,t.heap[1]=l++,af(t,r,1);while(t.heap_len>=2);t.heap[--t.heap_max]=t.heap[1],R_(t,e),x0(r,c,t.bl_count)},Ep=(t,e,r)=>{let n,i=-1,a,o=e[1],s=0,c=7,l=4;for(o===0&&(c=138,l=3),e[(r+1)*2+1]=65535,n=0;n<=r;n++)a=o,o=e[(n+1)*2+1],!(++s<c&&a===o)&&(s<l?t.bl_tree[a*2]+=s:a!==0?(a!==i&&t.bl_tree[a*2]++,t.bl_tree[u0*2]++):s<=10?t.bl_tree[d0*2]++:t.bl_tree[f0*2]++,s=0,i=a,o===0?(c=138,l=3):a===o?(c=6,l=3):(c=7,l=4))},Lp=(t,e,r)=>{let n,i=-1,a,o=e[1],s=0,c=7,l=4;for(o===0&&(c=138,l=3),n=0;n<=r;n++)if(a=o,o=e[(n+1)*2+1],!(++s<c&&a===o)){if(s<l)do Gr(t,a,t.bl_tree);while(--s!==0);else a!==0?(a!==i&&(Gr(t,a,t.bl_tree),s--),Gr(t,u0,t.bl_tree),Ot(t,s-3,2)):s<=10?(Gr(t,d0,t.bl_tree),Ot(t,s-3,3)):(Gr(t,f0,t.bl_tree),Ot(t,s-11,7));s=0,i=a,o===0?(c=138,l=3):a===o?(c=6,l=3):(c=7,l=4)}},B_=t=>{let e;for(Ep(t,t.dyn_ltree,t.l_desc.max_code),Ep(t,t.dyn_dtree,t.d_desc.max_code),yf(t,t.bl_desc),e=Ef-1;e>=3&&t.bl_tree[h0[e]*2+1]===0;e--);return t.opt_len+=3*(e+1)+5+5+4,e},F_=(t,e,r,n)=>{let i;for(Ot(t,e-257,5),Ot(t,r-1,5),Ot(t,n-4,4),i=0;i<n;i++)Ot(t,t.bl_tree[h0[i]*2+1],3);Lp(t,t.dyn_ltree,e-1),Lp(t,t.dyn_dtree,r-1)},I_=t=>{let e=4093624447,r;for(r=0;r<=31;r++,e>>>=1)if(e&1&&t.dyn_ltree[r*2]!==0)return 0;if(t.dyn_ltree[18]!==0||t.dyn_ltree[20]!==0||t.dyn_ltree[26]!==0)return 1;for(r=32;r<Ds;r++)if(t.dyn_ltree[r*2]!==0)return 1;return 0},Tp=!1,D_=t=>{Tp||(C_(),Tp=!0),t.l_desc=new nf(t.dyn_ltree,m0),t.d_desc=new nf(t.dyn_dtree,p0),t.bl_desc=new nf(t.bl_tree,g0),t.bi_buf=0,t.bi_valid=0,v0(t)},S0=(t,e,r,n)=>{Ot(t,(S_<<1)+(n?1:0),3),_0(t),Rs(t,r),Rs(t,~r),r&&t.pending_buf.set(t.window.subarray(e,e+r),t.pending),t.pending+=r},k_=t=>{Ot(t,l0<<1,3),Gr(t,Lf,fn),P_(t)},U_=(t,e,r,n)=>{let i,a,o=0;t.level>0?(t.strm.data_type===2&&(t.strm.data_type=I_(t)),yf(t,t.l_desc),yf(t,t.d_desc),o=B_(t),i=t.opt_len+3+7>>>3,a=t.static_len+3+7>>>3,a<=i&&(i=a)):i=a=r+5,r+4<=i&&e!==-1?S0(t,e,r,n):t.strategy===4||a===i?(Ot(t,(l0<<1)+(n?1:0),3),Ap(t,fn,Ms)):(Ot(t,(w_<<1)+(n?1:0),3),F_(t,t.l_desc.max_code+1,t.d_desc.max_code+1,o+1),Ap(t,t.dyn_ltree,t.dyn_dtree)),v0(t),n&&_0(t)},z_=(t,e,r)=>(t.pending_buf[t.sym_buf+t.sym_next++]=e,t.pending_buf[t.sym_buf+t.sym_next++]=e>>8,t.pending_buf[t.sym_buf+t.sym_next++]=r,e===0?t.dyn_ltree[r*2]++:(t.matches++,e--,t.dyn_ltree[(Ps[r]+Ds+1)*2]++,t.dyn_dtree[y0(e)*2]++),t.sym_next===t.sym_end),O_=D_,N_=S0,G_=U_,V_=z_,H_=k_,W_={_tr_init:O_,_tr_stored_block:N_,_tr_flush_block:G_,_tr_tally:V_,_tr_align:H_},X_=(t,e,r,n)=>{let i=t&65535|0,a=t>>>16&65535|0,o=0;for(;r!==0;){o=r>2e3?2e3:r,r-=o;do i=i+e[n++]|0,a=a+i|0;while(--o);i%=65521,a%=65521}return i|a<<16|0},Cs=X_,$_=()=>{let t,e=[];for(var r=0;r<256;r++){t=r;for(var n=0;n<8;n++)t=t&1?3988292384^t>>>1:t>>>1;e[r]=t}return e},K_=new Uint32Array($_()),Y_=(t,e,r,n)=>{let i=K_,a=n+r;t^=-1;for(let o=n;o<a;o++)t=t>>>8^i[(t^e[o])&255];return t^-1},Ne=Y_,Bi={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"},Di={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8},{_tr_init:q_,_tr_stored_block:bf,_tr_flush_block:Z_,_tr_tally:qn,_tr_align:j_}=W_,{Z_NO_FLUSH:Zn,Z_PARTIAL_FLUSH:Q_,Z_FULL_FLUSH:J_,Z_FINISH:ur,Z_BLOCK:Pp,Z_OK:et,Z_STREAM_END:Rp,Z_STREAM_ERROR:Vr,Z_DATA_ERROR:eS,Z_BUF_ERROR:of,Z_DEFAULT_COMPRESSION:tS,Z_FILTERED:rS,Z_HUFFMAN_ONLY:kc,Z_RLE:nS,Z_FIXED:iS,Z_DEFAULT_STRATEGY:aS,Z_UNKNOWN:oS,Z_DEFLATED:Xc}=Di,sS=9,lS=15,cS=8,uS=29,dS=256,xf=dS+1+uS,fS=30,hS=19,mS=2*xf+1,pS=15,j=3,Yn=258,Hr=Yn+j+1,gS=32,Ga=42,Pf=57,vf=69,_f=73,Sf=91,wf=103,Ri=113,Ss=666,bt=1,Wa=2,Fi=3,Xa=4,yS=3,Ci=(t,e)=>(t.msg=Bi[e],e),Cp=t=>t*2-(t>4?9:0),Kn=t=>{let e=t.length;for(;--e>=0;)t[e]=0},bS=t=>{let e,r,n,i=t.w_size;e=t.hash_size,n=e;do r=t.head[--n],t.head[n]=r>=i?r-i:0;while(--e);e=i,n=e;do r=t.prev[--n],t.prev[n]=r>=i?r-i:0;while(--e)},xS=(t,e,r)=>(e<<t.hash_shift^r)&t.hash_mask,jn=xS,Kt=t=>{let e=t.state,r=e.pending;r>t.avail_out&&(r=t.avail_out),r!==0&&(t.output.set(e.pending_buf.subarray(e.pending_out,e.pending_out+r),t.next_out),t.next_out+=r,e.pending_out+=r,t.total_out+=r,t.avail_out-=r,e.pending-=r,e.pending===0&&(e.pending_out=0))},Yt=(t,e)=>{Z_(t,t.block_start>=0?t.block_start:-1,t.strstart-t.block_start,e),t.block_start=t.strstart,Kt(t.strm)},ie=(t,e)=>{t.pending_buf[t.pending++]=e},_s=(t,e)=>{t.pending_buf[t.pending++]=e>>>8&255,t.pending_buf[t.pending++]=e&255},Mf=(t,e,r,n)=>{let i=t.avail_in;return i>n&&(i=n),i===0?0:(t.avail_in-=i,e.set(t.input.subarray(t.next_in,t.next_in+i),r),t.state.wrap===1?t.adler=Cs(t.adler,e,i,r):t.state.wrap===2&&(t.adler=Ne(t.adler,e,i,r)),t.next_in+=i,t.total_in+=i,i)},w0=(t,e)=>{let r=t.max_chain_length,n=t.strstart,i,a,o=t.prev_length,s=t.nice_match,c=t.strstart>t.w_size-Hr?t.strstart-(t.w_size-Hr):0,l=t.window,u=t.w_mask,d=t.prev,f=t.strstart+Yn,h=l[n+o-1],m=l[n+o];t.prev_length>=t.good_match&&(r>>=2),s>t.lookahead&&(s=t.lookahead);do if(i=e,!(l[i+o]!==m||l[i+o-1]!==h||l[i]!==l[n]||l[++i]!==l[n+1])){n+=2,i++;do;while(l[++n]===l[++i]&&l[++n]===l[++i]&&l[++n]===l[++i]&&l[++n]===l[++i]&&l[++n]===l[++i]&&l[++n]===l[++i]&&l[++n]===l[++i]&&l[++n]===l[++i]&&n<f);if(a=Yn-(f-n),n=f-Yn,a>o){if(t.match_start=e,o=a,a>=s)break;h=l[n+o-1],m=l[n+o]}}while((e=d[e&u])>c&&--r!==0);return o<=t.lookahead?o:t.lookahead},Va=t=>{let e=t.w_size,r,n,i;do{if(n=t.window_size-t.lookahead-t.strstart,t.strstart>=e+(e-Hr)&&(t.window.set(t.window.subarray(e,e+e-n),0),t.match_start-=e,t.strstart-=e,t.block_start-=e,t.insert>t.strstart&&(t.insert=t.strstart),bS(t),n+=e),t.strm.avail_in===0)break;if(r=Mf(t.strm,t.window,t.strstart+t.lookahead,n),t.lookahead+=r,t.lookahead+t.insert>=j)for(i=t.strstart-t.insert,t.ins_h=t.window[i],t.ins_h=jn(t,t.ins_h,t.window[i+1]);t.insert&&(t.ins_h=jn(t,t.ins_h,t.window[i+j-1]),t.prev[i&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=i,i++,t.insert--,!(t.lookahead+t.insert<j)););}while(t.lookahead<Hr&&t.strm.avail_in!==0)},M0=(t,e)=>{let r=t.pending_buf_size-5>t.w_size?t.w_size:t.pending_buf_size-5,n,i,a,o=0,s=t.strm.avail_in;do{if(n=65535,a=t.bi_valid+42>>3,t.strm.avail_out<a||(a=t.strm.avail_out-a,i=t.strstart-t.block_start,n>i+t.strm.avail_in&&(n=i+t.strm.avail_in),n>a&&(n=a),n<r&&(n===0&&e!==ur||e===Zn||n!==i+t.strm.avail_in)))break;o=e===ur&&n===i+t.strm.avail_in?1:0,bf(t,0,0,o),t.pending_buf[t.pending-4]=n,t.pending_buf[t.pending-3]=n>>8,t.pending_buf[t.pending-2]=~n,t.pending_buf[t.pending-1]=~n>>8,Kt(t.strm),i&&(i>n&&(i=n),t.strm.output.set(t.window.subarray(t.block_start,t.block_start+i),t.strm.next_out),t.strm.next_out+=i,t.strm.avail_out-=i,t.strm.total_out+=i,t.block_start+=i,n-=i),n&&(Mf(t.strm,t.strm.output,t.strm.next_out,n),t.strm.next_out+=n,t.strm.avail_out-=n,t.strm.total_out+=n)}while(o===0);return s-=t.strm.avail_in,s&&(s>=t.w_size?(t.matches=2,t.window.set(t.strm.input.subarray(t.strm.next_in-t.w_size,t.strm.next_in),0),t.strstart=t.w_size,t.insert=t.strstart):(t.window_size-t.strstart<=s&&(t.strstart-=t.w_size,t.window.set(t.window.subarray(t.w_size,t.w_size+t.strstart),0),t.matches<2&&t.matches++,t.insert>t.strstart&&(t.insert=t.strstart)),t.window.set(t.strm.input.subarray(t.strm.next_in-s,t.strm.next_in),t.strstart),t.strstart+=s,t.insert+=s>t.w_size-t.insert?t.w_size-t.insert:s),t.block_start=t.strstart),t.high_water<t.strstart&&(t.high_water=t.strstart),o?Xa:e!==Zn&&e!==ur&&t.strm.avail_in===0&&t.strstart===t.block_start?Wa:(a=t.window_size-t.strstart,t.strm.avail_in>a&&t.block_start>=t.w_size&&(t.block_start-=t.w_size,t.strstart-=t.w_size,t.window.set(t.window.subarray(t.w_size,t.w_size+t.strstart),0),t.matches<2&&t.matches++,a+=t.w_size,t.insert>t.strstart&&(t.insert=t.strstart)),a>t.strm.avail_in&&(a=t.strm.avail_in),a&&(Mf(t.strm,t.window,t.strstart,a),t.strstart+=a,t.insert+=a>t.w_size-t.insert?t.w_size-t.insert:a),t.high_water<t.strstart&&(t.high_water=t.strstart),a=t.bi_valid+42>>3,a=t.pending_buf_size-a>65535?65535:t.pending_buf_size-a,r=a>t.w_size?t.w_size:a,i=t.strstart-t.block_start,(i>=r||(i||e===ur)&&e!==Zn&&t.strm.avail_in===0&&i<=a)&&(n=i>a?a:i,o=e===ur&&t.strm.avail_in===0&&n===i?1:0,bf(t,t.block_start,n,o),t.block_start+=n,Kt(t.strm)),o?Fi:bt)},sf=(t,e)=>{let r,n;for(;;){if(t.lookahead<Hr){if(Va(t),t.lookahead<Hr&&e===Zn)return bt;if(t.lookahead===0)break}if(r=0,t.lookahead>=j&&(t.ins_h=jn(t,t.ins_h,t.window[t.strstart+j-1]),r=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),r!==0&&t.strstart-r<=t.w_size-Hr&&(t.match_length=w0(t,r)),t.match_length>=j)if(n=qn(t,t.strstart-t.match_start,t.match_length-j),t.lookahead-=t.match_length,t.match_length<=t.max_lazy_match&&t.lookahead>=j){t.match_length--;do t.strstart++,t.ins_h=jn(t,t.ins_h,t.window[t.strstart+j-1]),r=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart;while(--t.match_length!==0);t.strstart++}else t.strstart+=t.match_length,t.match_length=0,t.ins_h=t.window[t.strstart],t.ins_h=jn(t,t.ins_h,t.window[t.strstart+1]);else n=qn(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++;if(n&&(Yt(t,!1),t.strm.avail_out===0))return bt}return t.insert=t.strstart<j-1?t.strstart:j-1,e===ur?(Yt(t,!0),t.strm.avail_out===0?Fi:Xa):t.sym_next&&(Yt(t,!1),t.strm.avail_out===0)?bt:Wa},za=(t,e)=>{let r,n,i;for(;;){if(t.lookahead<Hr){if(Va(t),t.lookahead<Hr&&e===Zn)return bt;if(t.lookahead===0)break}if(r=0,t.lookahead>=j&&(t.ins_h=jn(t,t.ins_h,t.window[t.strstart+j-1]),r=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),t.prev_length=t.match_length,t.prev_match=t.match_start,t.match_length=j-1,r!==0&&t.prev_length<t.max_lazy_match&&t.strstart-r<=t.w_size-Hr&&(t.match_length=w0(t,r),t.match_length<=5&&(t.strategy===rS||t.match_length===j&&t.strstart-t.match_start>4096)&&(t.match_length=j-1)),t.prev_length>=j&&t.match_length<=t.prev_length){i=t.strstart+t.lookahead-j,n=qn(t,t.strstart-1-t.prev_match,t.prev_length-j),t.lookahead-=t.prev_length-1,t.prev_length-=2;do++t.strstart<=i&&(t.ins_h=jn(t,t.ins_h,t.window[t.strstart+j-1]),r=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart);while(--t.prev_length!==0);if(t.match_available=0,t.match_length=j-1,t.strstart++,n&&(Yt(t,!1),t.strm.avail_out===0))return bt}else if(t.match_available){if(n=qn(t,0,t.window[t.strstart-1]),n&&Yt(t,!1),t.strstart++,t.lookahead--,t.strm.avail_out===0)return bt}else t.match_available=1,t.strstart++,t.lookahead--}return t.match_available&&(n=qn(t,0,t.window[t.strstart-1]),t.match_available=0),t.insert=t.strstart<j-1?t.strstart:j-1,e===ur?(Yt(t,!0),t.strm.avail_out===0?Fi:Xa):t.sym_next&&(Yt(t,!1),t.strm.avail_out===0)?bt:Wa},vS=(t,e)=>{let r,n,i,a,o=t.window;for(;;){if(t.lookahead<=Yn){if(Va(t),t.lookahead<=Yn&&e===Zn)return bt;if(t.lookahead===0)break}if(t.match_length=0,t.lookahead>=j&&t.strstart>0&&(i=t.strstart-1,n=o[i],n===o[++i]&&n===o[++i]&&n===o[++i])){a=t.strstart+Yn;do;while(n===o[++i]&&n===o[++i]&&n===o[++i]&&n===o[++i]&&n===o[++i]&&n===o[++i]&&n===o[++i]&&n===o[++i]&&i<a);t.match_length=Yn-(a-i),t.match_length>t.lookahead&&(t.match_length=t.lookahead)}if(t.match_length>=j?(r=qn(t,1,t.match_length-j),t.lookahead-=t.match_length,t.strstart+=t.match_length,t.match_length=0):(r=qn(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++),r&&(Yt(t,!1),t.strm.avail_out===0))return bt}return t.insert=0,e===ur?(Yt(t,!0),t.strm.avail_out===0?Fi:Xa):t.sym_next&&(Yt(t,!1),t.strm.avail_out===0)?bt:Wa},_S=(t,e)=>{let r;for(;;){if(t.lookahead===0&&(Va(t),t.lookahead===0)){if(e===Zn)return bt;break}if(t.match_length=0,r=qn(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++,r&&(Yt(t,!1),t.strm.avail_out===0))return bt}return t.insert=0,e===ur?(Yt(t,!0),t.strm.avail_out===0?Fi:Xa):t.sym_next&&(Yt(t,!1),t.strm.avail_out===0)?bt:Wa};function Nr(t,e,r,n,i){this.good_length=t,this.max_lazy=e,this.nice_length=r,this.max_chain=n,this.func=i}var ws=[new Nr(0,0,0,0,M0),new Nr(4,4,8,4,sf),new Nr(4,5,16,8,sf),new Nr(4,6,32,32,sf),new Nr(4,4,16,16,za),new Nr(8,16,32,32,za),new Nr(8,16,128,128,za),new Nr(8,32,128,256,za),new Nr(32,128,258,1024,za),new Nr(32,258,258,4096,za)],SS=t=>{t.window_size=2*t.w_size,Kn(t.head),t.max_lazy_match=ws[t.level].max_lazy,t.good_match=ws[t.level].good_length,t.nice_match=ws[t.level].nice_length,t.max_chain_length=ws[t.level].max_chain,t.strstart=0,t.block_start=0,t.lookahead=0,t.insert=0,t.match_length=t.prev_length=j-1,t.match_available=0,t.ins_h=0};function wS(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=Xc,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Uint16Array(mS*2),this.dyn_dtree=new Uint16Array((2*fS+1)*2),this.bl_tree=new Uint16Array((2*hS+1)*2),Kn(this.dyn_ltree),Kn(this.dyn_dtree),Kn(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(pS+1),this.heap=new Uint16Array(2*xf+1),Kn(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(2*xf+1),Kn(this.depth),this.sym_buf=0,this.lit_bufsize=0,this.sym_next=0,this.sym_end=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}var ks=t=>{if(!t)return 1;let e=t.state;return!e||e.strm!==t||e.status!==Ga&&e.status!==Pf&&e.status!==vf&&e.status!==_f&&e.status!==Sf&&e.status!==wf&&e.status!==Ri&&e.status!==Ss?1:0},A0=t=>{if(ks(t))return Ci(t,Vr);t.total_in=t.total_out=0,t.data_type=oS;let e=t.state;return e.pending=0,e.pending_out=0,e.wrap<0&&(e.wrap=-e.wrap),e.status=e.wrap===2?Pf:e.wrap?Ga:Ri,t.adler=e.wrap===2?0:1,e.last_flush=-2,q_(e),et},E0=t=>{let e=A0(t);return e===et&&SS(t.state),e},MS=(t,e)=>ks(t)||t.state.wrap!==2?Vr:(t.state.gzhead=e,et),L0=(t,e,r,n,i,a)=>{if(!t)return Vr;let o=1;if(e===tS&&(e=6),n<0?(o=0,n=-n):n>15&&(o=2,n-=16),i<1||i>sS||r!==Xc||n<8||n>15||e<0||e>9||a<0||a>iS||n===8&&o!==1)return Ci(t,Vr);n===8&&(n=9);let s=new wS;return t.state=s,s.strm=t,s.status=Ga,s.wrap=o,s.gzhead=null,s.w_bits=n,s.w_size=1<<s.w_bits,s.w_mask=s.w_size-1,s.hash_bits=i+7,s.hash_size=1<<s.hash_bits,s.hash_mask=s.hash_size-1,s.hash_shift=~~((s.hash_bits+j-1)/j),s.window=new Uint8Array(s.w_size*2),s.head=new Uint16Array(s.hash_size),s.prev=new Uint16Array(s.w_size),s.lit_bufsize=1<<i+6,s.pending_buf_size=s.lit_bufsize*4,s.pending_buf=new Uint8Array(s.pending_buf_size),s.sym_buf=s.lit_bufsize,s.sym_end=(s.lit_bufsize-1)*3,s.level=e,s.strategy=a,s.method=r,E0(t)},AS=(t,e)=>L0(t,e,Xc,lS,cS,aS),ES=(t,e)=>{if(ks(t)||e>Pp||e<0)return t?Ci(t,Vr):Vr;let r=t.state;if(!t.output||t.avail_in!==0&&!t.input||r.status===Ss&&e!==ur)return Ci(t,t.avail_out===0?of:Vr);let n=r.last_flush;if(r.last_flush=e,r.pending!==0){if(Kt(t),t.avail_out===0)return r.last_flush=-1,et}else if(t.avail_in===0&&Cp(e)<=Cp(n)&&e!==ur)return Ci(t,of);if(r.status===Ss&&t.avail_in!==0)return Ci(t,of);if(r.status===Ga&&r.wrap===0&&(r.status=Ri),r.status===Ga){let i=Xc+(r.w_bits-8<<4)<<8,a=-1;if(r.strategy>=kc||r.level<2?a=0:r.level<6?a=1:r.level===6?a=2:a=3,i|=a<<6,r.strstart!==0&&(i|=gS),i+=31-i%31,_s(r,i),r.strstart!==0&&(_s(r,t.adler>>>16),_s(r,t.adler&65535)),t.adler=1,r.status=Ri,Kt(t),r.pending!==0)return r.last_flush=-1,et}if(r.status===Pf){if(t.adler=0,ie(r,31),ie(r,139),ie(r,8),r.gzhead)ie(r,(r.gzhead.text?1:0)+(r.gzhead.hcrc?2:0)+(r.gzhead.extra?4:0)+(r.gzhead.name?8:0)+(r.gzhead.comment?16:0)),ie(r,r.gzhead.time&255),ie(r,r.gzhead.time>>8&255),ie(r,r.gzhead.time>>16&255),ie(r,r.gzhead.time>>24&255),ie(r,r.level===9?2:r.strategy>=kc||r.level<2?4:0),ie(r,r.gzhead.os&255),r.gzhead.extra&&r.gzhead.extra.length&&(ie(r,r.gzhead.extra.length&255),ie(r,r.gzhead.extra.length>>8&255)),r.gzhead.hcrc&&(t.adler=Ne(t.adler,r.pending_buf,r.pending,0)),r.gzindex=0,r.status=vf;else if(ie(r,0),ie(r,0),ie(r,0),ie(r,0),ie(r,0),ie(r,r.level===9?2:r.strategy>=kc||r.level<2?4:0),ie(r,yS),r.status=Ri,Kt(t),r.pending!==0)return r.last_flush=-1,et}if(r.status===vf){if(r.gzhead.extra){let i=r.pending,a=(r.gzhead.extra.length&65535)-r.gzindex;for(;r.pending+a>r.pending_buf_size;){let s=r.pending_buf_size-r.pending;if(r.pending_buf.set(r.gzhead.extra.subarray(r.gzindex,r.gzindex+s),r.pending),r.pending=r.pending_buf_size,r.gzhead.hcrc&&r.pending>i&&(t.adler=Ne(t.adler,r.pending_buf,r.pending-i,i)),r.gzindex+=s,Kt(t),r.pending!==0)return r.last_flush=-1,et;i=0,a-=s}let o=new Uint8Array(r.gzhead.extra);r.pending_buf.set(o.subarray(r.gzindex,r.gzindex+a),r.pending),r.pending+=a,r.gzhead.hcrc&&r.pending>i&&(t.adler=Ne(t.adler,r.pending_buf,r.pending-i,i)),r.gzindex=0}r.status=_f}if(r.status===_f){if(r.gzhead.name){let i=r.pending,a;do{if(r.pending===r.pending_buf_size){if(r.gzhead.hcrc&&r.pending>i&&(t.adler=Ne(t.adler,r.pending_buf,r.pending-i,i)),Kt(t),r.pending!==0)return r.last_flush=-1,et;i=0}r.gzindex<r.gzhead.name.length?a=r.gzhead.name.charCodeAt(r.gzindex++)&255:a=0,ie(r,a)}while(a!==0);r.gzhead.hcrc&&r.pending>i&&(t.adler=Ne(t.adler,r.pending_buf,r.pending-i,i)),r.gzindex=0}r.status=Sf}if(r.status===Sf){if(r.gzhead.comment){let i=r.pending,a;do{if(r.pending===r.pending_buf_size){if(r.gzhead.hcrc&&r.pending>i&&(t.adler=Ne(t.adler,r.pending_buf,r.pending-i,i)),Kt(t),r.pending!==0)return r.last_flush=-1,et;i=0}r.gzindex<r.gzhead.comment.length?a=r.gzhead.comment.charCodeAt(r.gzindex++)&255:a=0,ie(r,a)}while(a!==0);r.gzhead.hcrc&&r.pending>i&&(t.adler=Ne(t.adler,r.pending_buf,r.pending-i,i))}r.status=wf}if(r.status===wf){if(r.gzhead.hcrc){if(r.pending+2>r.pending_buf_size&&(Kt(t),r.pending!==0))return r.last_flush=-1,et;ie(r,t.adler&255),ie(r,t.adler>>8&255),t.adler=0}if(r.status=Ri,Kt(t),r.pending!==0)return r.last_flush=-1,et}if(t.avail_in!==0||r.lookahead!==0||e!==Zn&&r.status!==Ss){let i=r.level===0?M0(r,e):r.strategy===kc?_S(r,e):r.strategy===nS?vS(r,e):ws[r.level].func(r,e);if((i===Fi||i===Xa)&&(r.status=Ss),i===bt||i===Fi)return t.avail_out===0&&(r.last_flush=-1),et;if(i===Wa&&(e===Q_?j_(r):e!==Pp&&(bf(r,0,0,!1),e===J_&&(Kn(r.head),r.lookahead===0&&(r.strstart=0,r.block_start=0,r.insert=0))),Kt(t),t.avail_out===0))return r.last_flush=-1,et}return e!==ur?et:r.wrap<=0?Rp:(r.wrap===2?(ie(r,t.adler&255),ie(r,t.adler>>8&255),ie(r,t.adler>>16&255),ie(r,t.adler>>24&255),ie(r,t.total_in&255),ie(r,t.total_in>>8&255),ie(r,t.total_in>>16&255),ie(r,t.total_in>>24&255)):(_s(r,t.adler>>>16),_s(r,t.adler&65535)),Kt(t),r.wrap>0&&(r.wrap=-r.wrap),r.pending!==0?et:Rp)},LS=t=>{if(ks(t))return Vr;let e=t.state.status;return t.state=null,e===Ri?Ci(t,eS):et},TS=(t,e)=>{let r=e.length;if(ks(t))return Vr;let n=t.state,i=n.wrap;if(i===2||i===1&&n.status!==Ga||n.lookahead)return Vr;if(i===1&&(t.adler=Cs(t.adler,e,r,0)),n.wrap=0,r>=n.w_size){i===0&&(Kn(n.head),n.strstart=0,n.block_start=0,n.insert=0);let c=new Uint8Array(n.w_size);c.set(e.subarray(r-n.w_size,r),0),e=c,r=n.w_size}let a=t.avail_in,o=t.next_in,s=t.input;for(t.avail_in=r,t.next_in=0,t.input=e,Va(n);n.lookahead>=j;){let c=n.strstart,l=n.lookahead-(j-1);do n.ins_h=jn(n,n.ins_h,n.window[c+j-1]),n.prev[c&n.w_mask]=n.head[n.ins_h],n.head[n.ins_h]=c,c++;while(--l);n.strstart=c,n.lookahead=j-1,Va(n)}return n.strstart+=n.lookahead,n.block_start=n.strstart,n.insert=n.lookahead,n.lookahead=0,n.match_length=n.prev_length=j-1,n.match_available=0,t.next_in=o,t.input=s,t.avail_in=a,n.wrap=i,et},PS=AS,RS=L0,CS=E0,BS=A0,FS=MS,IS=ES,DS=LS,kS=TS,US="pako deflate (from Nodeca project)",As={deflateInit:PS,deflateInit2:RS,deflateReset:CS,deflateResetKeep:BS,deflateSetHeader:FS,deflate:IS,deflateEnd:DS,deflateSetDictionary:kS,deflateInfo:US},zS=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),OS=function(t){let e=Array.prototype.slice.call(arguments,1);for(;e.length;){let r=e.shift();if(r){if(typeof r!="object")throw new TypeError(r+"must be non-object");for(let n in r)zS(r,n)&&(t[n]=r[n])}}return t},NS=t=>{let e=0;for(let n=0,i=t.length;n<i;n++)e+=t[n].length;let r=new Uint8Array(e);for(let n=0,i=0,a=t.length;n<a;n++){let o=t[n];r.set(o,i),i+=o.length}return r},$c={assign:OS,flattenChunks:NS},T0=!0;try{String.fromCharCode.apply(null,new Uint8Array(1))}catch{T0=!1}var Bs=new Uint8Array(256);for(let t=0;t<256;t++)Bs[t]=t>=252?6:t>=248?5:t>=240?4:t>=224?3:t>=192?2:1;Bs[254]=Bs[254]=1;var GS=t=>{if(typeof TextEncoder=="function"&&TextEncoder.prototype.encode)return new TextEncoder().encode(t);let e,r,n,i,a,o=t.length,s=0;for(i=0;i<o;i++)r=t.charCodeAt(i),(r&64512)===55296&&i+1<o&&(n=t.charCodeAt(i+1),(n&64512)===56320&&(r=65536+(r-55296<<10)+(n-56320),i++)),s+=r<128?1:r<2048?2:r<65536?3:4;for(e=new Uint8Array(s),a=0,i=0;a<s;i++)r=t.charCodeAt(i),(r&64512)===55296&&i+1<o&&(n=t.charCodeAt(i+1),(n&64512)===56320&&(r=65536+(r-55296<<10)+(n-56320),i++)),r<128?e[a++]=r:r<2048?(e[a++]=192|r>>>6,e[a++]=128|r&63):r<65536?(e[a++]=224|r>>>12,e[a++]=128|r>>>6&63,e[a++]=128|r&63):(e[a++]=240|r>>>18,e[a++]=128|r>>>12&63,e[a++]=128|r>>>6&63,e[a++]=128|r&63);return e},VS=(t,e)=>{if(e<65534&&t.subarray&&T0)return String.fromCharCode.apply(null,t.length===e?t:t.subarray(0,e));let r="";for(let n=0;n<e;n++)r+=String.fromCharCode(t[n]);return r},HS=(t,e)=>{let r=e||t.length;if(typeof TextDecoder=="function"&&TextDecoder.prototype.decode)return new TextDecoder().decode(t.subarray(0,e));let n,i,a=new Array(r*2);for(i=0,n=0;n<r;){let o=t[n++];if(o<128){a[i++]=o;continue}let s=Bs[o];if(s>4){a[i++]=65533,n+=s-1;continue}for(o&=s===2?31:s===3?15:7;s>1&&n<r;)o=o<<6|t[n++]&63,s--;if(s>1){a[i++]=65533;continue}o<65536?a[i++]=o:(o-=65536,a[i++]=55296|o>>10&1023,a[i++]=56320|o&1023)}return VS(a,i)},WS=(t,e)=>{e=e||t.length,e>t.length&&(e=t.length);let r=e-1;for(;r>=0&&(t[r]&192)===128;)r--;return r<0||r===0?e:r+Bs[t[r]]>e?r:e},Fs={string2buf:GS,buf2string:HS,utf8border:WS};function XS(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}var P0=XS,R0=Object.prototype.toString,{Z_NO_FLUSH:$S,Z_SYNC_FLUSH:KS,Z_FULL_FLUSH:YS,Z_FINISH:qS,Z_OK:Hc,Z_STREAM_END:ZS,Z_DEFAULT_COMPRESSION:jS,Z_DEFAULT_STRATEGY:QS,Z_DEFLATED:JS}=Di;function Us(t){this.options=$c.assign({level:jS,method:JS,chunkSize:16384,windowBits:15,memLevel:8,strategy:QS},t||{});let e=this.options;e.raw&&e.windowBits>0?e.windowBits=-e.windowBits:e.gzip&&e.windowBits>0&&e.windowBits<16&&(e.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new P0,this.strm.avail_out=0;let r=As.deflateInit2(this.strm,e.level,e.method,e.windowBits,e.memLevel,e.strategy);if(r!==Hc)throw new Error(Bi[r]);if(e.header&&As.deflateSetHeader(this.strm,e.header),e.dictionary){let n;if(typeof e.dictionary=="string"?n=Fs.string2buf(e.dictionary):R0.call(e.dictionary)==="[object ArrayBuffer]"?n=new Uint8Array(e.dictionary):n=e.dictionary,r=As.deflateSetDictionary(this.strm,n),r!==Hc)throw new Error(Bi[r]);this._dict_set=!0}}Us.prototype.push=function(t,e){let r=this.strm,n=this.options.chunkSize,i,a;if(this.ended)return!1;for(e===~~e?a=e:a=e===!0?qS:$S,typeof t=="string"?r.input=Fs.string2buf(t):R0.call(t)==="[object ArrayBuffer]"?r.input=new Uint8Array(t):r.input=t,r.next_in=0,r.avail_in=r.input.length;;){if(r.avail_out===0&&(r.output=new Uint8Array(n),r.next_out=0,r.avail_out=n),(a===KS||a===YS)&&r.avail_out<=6){this.onData(r.output.subarray(0,r.next_out)),r.avail_out=0;continue}if(i=As.deflate(r,a),i===ZS)return r.next_out>0&&this.onData(r.output.subarray(0,r.next_out)),i=As.deflateEnd(this.strm),this.onEnd(i),this.ended=!0,i===Hc;if(r.avail_out===0){this.onData(r.output);continue}if(a>0&&r.next_out>0){this.onData(r.output.subarray(0,r.next_out)),r.avail_out=0;continue}if(r.avail_in===0)break}return!0};Us.prototype.onData=function(t){this.chunks.push(t)};Us.prototype.onEnd=function(t){t===Hc&&(this.result=$c.flattenChunks(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg};function Rf(t,e){let r=new Us(e);if(r.push(t,!0),r.err)throw r.msg||Bi[r.err];return r.result}function ew(t,e){return e=e||{},e.raw=!0,Rf(t,e)}function tw(t,e){return e=e||{},e.gzip=!0,Rf(t,e)}var rw=Us,nw=Rf,iw=ew,aw=tw,ow=Di,sw={Deflate:rw,deflate:nw,deflateRaw:iw,gzip:aw,constants:ow},Uc=16209,lw=16191,cw=function(e,r){let n,i,a,o,s,c,l,u,d,f,h,m,g,p,y,v,b,x,_,w,S,A,L,M,P=e.state;n=e.next_in,L=e.input,i=n+(e.avail_in-5),a=e.next_out,M=e.output,o=a-(r-e.avail_out),s=a+(e.avail_out-257),c=P.dmax,l=P.wsize,u=P.whave,d=P.wnext,f=P.window,h=P.hold,m=P.bits,g=P.lencode,p=P.distcode,y=(1<<P.lenbits)-1,v=(1<<P.distbits)-1;e:do{m<15&&(h+=L[n++]<<m,m+=8,h+=L[n++]<<m,m+=8),b=g[h&y];t:for(;;){if(x=b>>>24,h>>>=x,m-=x,x=b>>>16&255,x===0)M[a++]=b&65535;else if(x&16){_=b&65535,x&=15,x&&(m<x&&(h+=L[n++]<<m,m+=8),_+=h&(1<<x)-1,h>>>=x,m-=x),m<15&&(h+=L[n++]<<m,m+=8,h+=L[n++]<<m,m+=8),b=p[h&v];r:for(;;){if(x=b>>>24,h>>>=x,m-=x,x=b>>>16&255,x&16){if(w=b&65535,x&=15,m<x&&(h+=L[n++]<<m,m+=8,m<x&&(h+=L[n++]<<m,m+=8)),w+=h&(1<<x)-1,w>c){e.msg="invalid distance too far back",P.mode=Uc;break e}if(h>>>=x,m-=x,x=a-o,w>x){if(x=w-x,x>u&&P.sane){e.msg="invalid distance too far back",P.mode=Uc;break e}if(S=0,A=f,d===0){if(S+=l-x,x<_){_-=x;do M[a++]=f[S++];while(--x);S=a-w,A=M}}else if(d<x){if(S+=l+d-x,x-=d,x<_){_-=x;do M[a++]=f[S++];while(--x);if(S=0,d<_){x=d,_-=x;do M[a++]=f[S++];while(--x);S=a-w,A=M}}}else if(S+=d-x,x<_){_-=x;do M[a++]=f[S++];while(--x);S=a-w,A=M}for(;_>2;)M[a++]=A[S++],M[a++]=A[S++],M[a++]=A[S++],_-=3;_&&(M[a++]=A[S++],_>1&&(M[a++]=A[S++]))}else{S=a-w;do M[a++]=M[S++],M[a++]=M[S++],M[a++]=M[S++],_-=3;while(_>2);_&&(M[a++]=M[S++],_>1&&(M[a++]=M[S++]))}}else if((x&64)===0){b=p[(b&65535)+(h&(1<<x)-1)];continue r}else{e.msg="invalid distance code",P.mode=Uc;break e}break}}else if((x&64)===0){b=g[(b&65535)+(h&(1<<x)-1)];continue t}else if(x&32){P.mode=lw;break e}else{e.msg="invalid literal/length code",P.mode=Uc;break e}break}}while(n<i&&a<s);_=m>>3,n-=_,m-=_<<3,h&=(1<<m)-1,e.next_in=n,e.next_out=a,e.avail_in=n<i?5+(i-n):5-(n-i),e.avail_out=a<s?257+(s-a):257-(a-s),P.hold=h,P.bits=m},Oa=15,Bp=852,Fp=592,Ip=0,lf=1,Dp=2,uw=new Uint16Array([3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0]),dw=new Uint8Array([16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78]),fw=new Uint16Array([1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0]),hw=new Uint8Array([16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64]),mw=(t,e,r,n,i,a,o,s)=>{let c=s.bits,l=0,u=0,d=0,f=0,h=0,m=0,g=0,p=0,y=0,v=0,b,x,_,w,S,A=null,L,M=new Uint16Array(Oa+1),P=new Uint16Array(Oa+1),I=null,D,B,O;for(l=0;l<=Oa;l++)M[l]=0;for(u=0;u<n;u++)M[e[r+u]]++;for(h=c,f=Oa;f>=1&&M[f]===0;f--);if(h>f&&(h=f),f===0)return i[a++]=1<<24|64<<16|0,i[a++]=1<<24|64<<16|0,s.bits=1,0;for(d=1;d<f&&M[d]===0;d++);for(h<d&&(h=d),p=1,l=1;l<=Oa;l++)if(p<<=1,p-=M[l],p<0)return-1;if(p>0&&(t===Ip||f!==1))return-1;for(P[1]=0,l=1;l<Oa;l++)P[l+1]=P[l]+M[l];for(u=0;u<n;u++)e[r+u]!==0&&(o[P[e[r+u]]++]=u);if(t===Ip?(A=I=o,L=20):t===lf?(A=uw,I=dw,L=257):(A=fw,I=hw,L=0),v=0,u=0,l=d,S=a,m=h,g=0,_=-1,y=1<<h,w=y-1,t===lf&&y>Bp||t===Dp&&y>Fp)return 1;for(;;){D=l-g,o[u]+1<L?(B=0,O=o[u]):o[u]>=L?(B=I[o[u]-L],O=A[o[u]-L]):(B=96,O=0),b=1<<l-g,x=1<<m,d=x;do x-=b,i[S+(v>>g)+x]=D<<24|B<<16|O|0;while(x!==0);for(b=1<<l-1;v&b;)b>>=1;if(b!==0?(v&=b-1,v+=b):v=0,u++,--M[l]===0){if(l===f)break;l=e[r+o[u]]}if(l>h&&(v&w)!==_){for(g===0&&(g=h),S+=d,m=l-g,p=1<<m;m+g<f&&(p-=M[m+g],!(p<=0));)m++,p<<=1;if(y+=1<<m,t===lf&&y>Bp||t===Dp&&y>Fp)return 1;_=v&w,i[_]=h<<24|m<<16|S-a|0}}return v!==0&&(i[S+v]=l-g<<24|64<<16|0),s.bits=h,0},Es=mw,pw=0,C0=1,B0=2,{Z_FINISH:kp,Z_BLOCK:gw,Z_TREES:zc,Z_OK:Ii,Z_STREAM_END:yw,Z_NEED_DICT:bw,Z_STREAM_ERROR:dr,Z_DATA_ERROR:F0,Z_MEM_ERROR:I0,Z_BUF_ERROR:xw,Z_DEFLATED:Up}=Di,Kc=16180,zp=16181,Op=16182,Np=16183,Gp=16184,Vp=16185,Hp=16186,Wp=16187,Xp=16188,$p=16189,Wc=16190,dn=16191,cf=16192,Kp=16193,uf=16194,Yp=16195,qp=16196,Zp=16197,jp=16198,Oc=16199,Nc=16200,Qp=16201,Jp=16202,e0=16203,t0=16204,r0=16205,df=16206,n0=16207,i0=16208,we=16209,D0=16210,k0=16211,vw=852,_w=592,Sw=15,ww=Sw,a0=t=>(t>>>24&255)+(t>>>8&65280)+((t&65280)<<8)+((t&255)<<24);function Mw(){this.strm=null,this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}var ki=t=>{if(!t)return 1;let e=t.state;return!e||e.strm!==t||e.mode<Kc||e.mode>k0?1:0},U0=t=>{if(ki(t))return dr;let e=t.state;return t.total_in=t.total_out=e.total=0,t.msg="",e.wrap&&(t.adler=e.wrap&1),e.mode=Kc,e.last=0,e.havedict=0,e.flags=-1,e.dmax=32768,e.head=null,e.hold=0,e.bits=0,e.lencode=e.lendyn=new Int32Array(vw),e.distcode=e.distdyn=new Int32Array(_w),e.sane=1,e.back=-1,Ii},z0=t=>{if(ki(t))return dr;let e=t.state;return e.wsize=0,e.whave=0,e.wnext=0,U0(t)},O0=(t,e)=>{let r;if(ki(t))return dr;let n=t.state;return e<0?(r=0,e=-e):(r=(e>>4)+5,e<48&&(e&=15)),e&&(e<8||e>15)?dr:(n.window!==null&&n.wbits!==e&&(n.window=null),n.wrap=r,n.wbits=e,z0(t))},N0=(t,e)=>{if(!t)return dr;let r=new Mw;t.state=r,r.strm=t,r.window=null,r.mode=Kc;let n=O0(t,e);return n!==Ii&&(t.state=null),n},Aw=t=>N0(t,ww),o0=!0,ff,hf,Ew=t=>{if(o0){ff=new Int32Array(512),hf=new Int32Array(32);let e=0;for(;e<144;)t.lens[e++]=8;for(;e<256;)t.lens[e++]=9;for(;e<280;)t.lens[e++]=7;for(;e<288;)t.lens[e++]=8;for(Es(C0,t.lens,0,288,ff,0,t.work,{bits:9}),e=0;e<32;)t.lens[e++]=5;Es(B0,t.lens,0,32,hf,0,t.work,{bits:5}),o0=!1}t.lencode=ff,t.lenbits=9,t.distcode=hf,t.distbits=5},G0=(t,e,r,n)=>{let i,a=t.state;return a.window===null&&(a.wsize=1<<a.wbits,a.wnext=0,a.whave=0,a.window=new Uint8Array(a.wsize)),n>=a.wsize?(a.window.set(e.subarray(r-a.wsize,r),0),a.wnext=0,a.whave=a.wsize):(i=a.wsize-a.wnext,i>n&&(i=n),a.window.set(e.subarray(r-n,r-n+i),a.wnext),n-=i,n?(a.window.set(e.subarray(r-n,r),0),a.wnext=n,a.whave=a.wsize):(a.wnext+=i,a.wnext===a.wsize&&(a.wnext=0),a.whave<a.wsize&&(a.whave+=i))),0},Lw=(t,e)=>{let r,n,i,a,o,s,c,l,u,d,f,h,m,g,p=0,y,v,b,x,_,w,S,A,L=new Uint8Array(4),M,P,I=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(ki(t)||!t.output||!t.input&&t.avail_in!==0)return dr;r=t.state,r.mode===dn&&(r.mode=cf),o=t.next_out,i=t.output,c=t.avail_out,a=t.next_in,n=t.input,s=t.avail_in,l=r.hold,u=r.bits,d=s,f=c,A=Ii;e:for(;;)switch(r.mode){case Kc:if(r.wrap===0){r.mode=cf;break}for(;u<16;){if(s===0)break e;s--,l+=n[a++]<<u,u+=8}if(r.wrap&2&&l===35615){r.wbits===0&&(r.wbits=15),r.check=0,L[0]=l&255,L[1]=l>>>8&255,r.check=Ne(r.check,L,2,0),l=0,u=0,r.mode=zp;break}if(r.head&&(r.head.done=!1),!(r.wrap&1)||(((l&255)<<8)+(l>>8))%31){t.msg="incorrect header check",r.mode=we;break}if((l&15)!==Up){t.msg="unknown compression method",r.mode=we;break}if(l>>>=4,u-=4,S=(l&15)+8,r.wbits===0&&(r.wbits=S),S>15||S>r.wbits){t.msg="invalid window size",r.mode=we;break}r.dmax=1<<r.wbits,r.flags=0,t.adler=r.check=1,r.mode=l&512?$p:dn,l=0,u=0;break;case zp:for(;u<16;){if(s===0)break e;s--,l+=n[a++]<<u,u+=8}if(r.flags=l,(r.flags&255)!==Up){t.msg="unknown compression method",r.mode=we;break}if(r.flags&57344){t.msg="unknown header flags set",r.mode=we;break}r.head&&(r.head.text=l>>8&1),r.flags&512&&r.wrap&4&&(L[0]=l&255,L[1]=l>>>8&255,r.check=Ne(r.check,L,2,0)),l=0,u=0,r.mode=Op;case Op:for(;u<32;){if(s===0)break e;s--,l+=n[a++]<<u,u+=8}r.head&&(r.head.time=l),r.flags&512&&r.wrap&4&&(L[0]=l&255,L[1]=l>>>8&255,L[2]=l>>>16&255,L[3]=l>>>24&255,r.check=Ne(r.check,L,4,0)),l=0,u=0,r.mode=Np;case Np:for(;u<16;){if(s===0)break e;s--,l+=n[a++]<<u,u+=8}r.head&&(r.head.xflags=l&255,r.head.os=l>>8),r.flags&512&&r.wrap&4&&(L[0]=l&255,L[1]=l>>>8&255,r.check=Ne(r.check,L,2,0)),l=0,u=0,r.mode=Gp;case Gp:if(r.flags&1024){for(;u<16;){if(s===0)break e;s--,l+=n[a++]<<u,u+=8}r.length=l,r.head&&(r.head.extra_len=l),r.flags&512&&r.wrap&4&&(L[0]=l&255,L[1]=l>>>8&255,r.check=Ne(r.check,L,2,0)),l=0,u=0}else r.head&&(r.head.extra=null);r.mode=Vp;case Vp:if(r.flags&1024&&(h=r.length,h>s&&(h=s),h&&(r.head&&(S=r.head.extra_len-r.length,r.head.extra||(r.head.extra=new Uint8Array(r.head.extra_len)),r.head.extra.set(n.subarray(a,a+h),S)),r.flags&512&&r.wrap&4&&(r.check=Ne(r.check,n,h,a)),s-=h,a+=h,r.length-=h),r.length))break e;r.length=0,r.mode=Hp;case Hp:if(r.flags&2048){if(s===0)break e;h=0;do S=n[a+h++],r.head&&S&&r.length<65536&&(r.head.name+=String.fromCharCode(S));while(S&&h<s);if(r.flags&512&&r.wrap&4&&(r.check=Ne(r.check,n,h,a)),s-=h,a+=h,S)break e}else r.head&&(r.head.name=null);r.length=0,r.mode=Wp;case Wp:if(r.flags&4096){if(s===0)break e;h=0;do S=n[a+h++],r.head&&S&&r.length<65536&&(r.head.comment+=String.fromCharCode(S));while(S&&h<s);if(r.flags&512&&r.wrap&4&&(r.check=Ne(r.check,n,h,a)),s-=h,a+=h,S)break e}else r.head&&(r.head.comment=null);r.mode=Xp;case Xp:if(r.flags&512){for(;u<16;){if(s===0)break e;s--,l+=n[a++]<<u,u+=8}if(r.wrap&4&&l!==(r.check&65535)){t.msg="header crc mismatch",r.mode=we;break}l=0,u=0}r.head&&(r.head.hcrc=r.flags>>9&1,r.head.done=!0),t.adler=r.check=0,r.mode=dn;break;case $p:for(;u<32;){if(s===0)break e;s--,l+=n[a++]<<u,u+=8}t.adler=r.check=a0(l),l=0,u=0,r.mode=Wc;case Wc:if(r.havedict===0)return t.next_out=o,t.avail_out=c,t.next_in=a,t.avail_in=s,r.hold=l,r.bits=u,bw;t.adler=r.check=1,r.mode=dn;case dn:if(e===gw||e===zc)break e;case cf:if(r.last){l>>>=u&7,u-=u&7,r.mode=df;break}for(;u<3;){if(s===0)break e;s--,l+=n[a++]<<u,u+=8}switch(r.last=l&1,l>>>=1,u-=1,l&3){case 0:r.mode=Kp;break;case 1:if(Ew(r),r.mode=Oc,e===zc){l>>>=2,u-=2;break e}break;case 2:r.mode=qp;break;case 3:t.msg="invalid block type",r.mode=we}l>>>=2,u-=2;break;case Kp:for(l>>>=u&7,u-=u&7;u<32;){if(s===0)break e;s--,l+=n[a++]<<u,u+=8}if((l&65535)!==(l>>>16^65535)){t.msg="invalid stored block lengths",r.mode=we;break}if(r.length=l&65535,l=0,u=0,r.mode=uf,e===zc)break e;case uf:r.mode=Yp;case Yp:if(h=r.length,h){if(h>s&&(h=s),h>c&&(h=c),h===0)break e;i.set(n.subarray(a,a+h),o),s-=h,a+=h,c-=h,o+=h,r.length-=h;break}r.mode=dn;break;case qp:for(;u<14;){if(s===0)break e;s--,l+=n[a++]<<u,u+=8}if(r.nlen=(l&31)+257,l>>>=5,u-=5,r.ndist=(l&31)+1,l>>>=5,u-=5,r.ncode=(l&15)+4,l>>>=4,u-=4,r.nlen>286||r.ndist>30){t.msg="too many length or distance symbols",r.mode=we;break}r.have=0,r.mode=Zp;case Zp:for(;r.have<r.ncode;){for(;u<3;){if(s===0)break e;s--,l+=n[a++]<<u,u+=8}r.lens[I[r.have++]]=l&7,l>>>=3,u-=3}for(;r.have<19;)r.lens[I[r.have++]]=0;if(r.lencode=r.lendyn,r.lenbits=7,M={bits:r.lenbits},A=Es(pw,r.lens,0,19,r.lencode,0,r.work,M),r.lenbits=M.bits,A){t.msg="invalid code lengths set",r.mode=we;break}r.have=0,r.mode=jp;case jp:for(;r.have<r.nlen+r.ndist;){for(;p=r.lencode[l&(1<<r.lenbits)-1],y=p>>>24,v=p>>>16&255,b=p&65535,!(y<=u);){if(s===0)break e;s--,l+=n[a++]<<u,u+=8}if(b<16)l>>>=y,u-=y,r.lens[r.have++]=b;else{if(b===16){for(P=y+2;u<P;){if(s===0)break e;s--,l+=n[a++]<<u,u+=8}if(l>>>=y,u-=y,r.have===0){t.msg="invalid bit length repeat",r.mode=we;break}S=r.lens[r.have-1],h=3+(l&3),l>>>=2,u-=2}else if(b===17){for(P=y+3;u<P;){if(s===0)break e;s--,l+=n[a++]<<u,u+=8}l>>>=y,u-=y,S=0,h=3+(l&7),l>>>=3,u-=3}else{for(P=y+7;u<P;){if(s===0)break e;s--,l+=n[a++]<<u,u+=8}l>>>=y,u-=y,S=0,h=11+(l&127),l>>>=7,u-=7}if(r.have+h>r.nlen+r.ndist){t.msg="invalid bit length repeat",r.mode=we;break}for(;h--;)r.lens[r.have++]=S}}if(r.mode===we)break;if(r.lens[256]===0){t.msg="invalid code -- missing end-of-block",r.mode=we;break}if(r.lenbits=9,M={bits:r.lenbits},A=Es(C0,r.lens,0,r.nlen,r.lencode,0,r.work,M),r.lenbits=M.bits,A){t.msg="invalid literal/lengths set",r.mode=we;break}if(r.distbits=6,r.distcode=r.distdyn,M={bits:r.distbits},A=Es(B0,r.lens,r.nlen,r.ndist,r.distcode,0,r.work,M),r.distbits=M.bits,A){t.msg="invalid distances set",r.mode=we;break}if(r.mode=Oc,e===zc)break e;case Oc:r.mode=Nc;case Nc:if(s>=6&&c>=258){t.next_out=o,t.avail_out=c,t.next_in=a,t.avail_in=s,r.hold=l,r.bits=u,cw(t,f),o=t.next_out,i=t.output,c=t.avail_out,a=t.next_in,n=t.input,s=t.avail_in,l=r.hold,u=r.bits,r.mode===dn&&(r.back=-1);break}for(r.back=0;p=r.lencode[l&(1<<r.lenbits)-1],y=p>>>24,v=p>>>16&255,b=p&65535,!(y<=u);){if(s===0)break e;s--,l+=n[a++]<<u,u+=8}if(v&&(v&240)===0){for(x=y,_=v,w=b;p=r.lencode[w+((l&(1<<x+_)-1)>>x)],y=p>>>24,v=p>>>16&255,b=p&65535,!(x+y<=u);){if(s===0)break e;s--,l+=n[a++]<<u,u+=8}l>>>=x,u-=x,r.back+=x}if(l>>>=y,u-=y,r.back+=y,r.length=b,v===0){r.mode=r0;break}if(v&32){r.back=-1,r.mode=dn;break}if(v&64){t.msg="invalid literal/length code",r.mode=we;break}r.extra=v&15,r.mode=Qp;case Qp:if(r.extra){for(P=r.extra;u<P;){if(s===0)break e;s--,l+=n[a++]<<u,u+=8}r.length+=l&(1<<r.extra)-1,l>>>=r.extra,u-=r.extra,r.back+=r.extra}r.was=r.length,r.mode=Jp;case Jp:for(;p=r.distcode[l&(1<<r.distbits)-1],y=p>>>24,v=p>>>16&255,b=p&65535,!(y<=u);){if(s===0)break e;s--,l+=n[a++]<<u,u+=8}if((v&240)===0){for(x=y,_=v,w=b;p=r.distcode[w+((l&(1<<x+_)-1)>>x)],y=p>>>24,v=p>>>16&255,b=p&65535,!(x+y<=u);){if(s===0)break e;s--,l+=n[a++]<<u,u+=8}l>>>=x,u-=x,r.back+=x}if(l>>>=y,u-=y,r.back+=y,v&64){t.msg="invalid distance code",r.mode=we;break}r.offset=b,r.extra=v&15,r.mode=e0;case e0:if(r.extra){for(P=r.extra;u<P;){if(s===0)break e;s--,l+=n[a++]<<u,u+=8}r.offset+=l&(1<<r.extra)-1,l>>>=r.extra,u-=r.extra,r.back+=r.extra}if(r.offset>r.dmax){t.msg="invalid distance too far back",r.mode=we;break}r.mode=t0;case t0:if(c===0)break e;if(h=f-c,r.offset>h){if(h=r.offset-h,h>r.whave&&r.sane){t.msg="invalid distance too far back",r.mode=we;break}h>r.wnext?(h-=r.wnext,m=r.wsize-h):m=r.wnext-h,h>r.length&&(h=r.length),g=r.window}else g=i,m=o-r.offset,h=r.length;h>c&&(h=c),c-=h,r.length-=h;do i[o++]=g[m++];while(--h);r.length===0&&(r.mode=Nc);break;case r0:if(c===0)break e;i[o++]=r.length,c--,r.mode=Nc;break;case df:if(r.wrap){for(;u<32;){if(s===0)break e;s--,l|=n[a++]<<u,u+=8}if(f-=c,t.total_out+=f,r.total+=f,r.wrap&4&&f&&(t.adler=r.check=r.flags?Ne(r.check,i,f,o-f):Cs(r.check,i,f,o-f)),f=c,r.wrap&4&&(r.flags?l:a0(l))!==r.check){t.msg="incorrect data check",r.mode=we;break}l=0,u=0}r.mode=n0;case n0:if(r.wrap&&r.flags){for(;u<32;){if(s===0)break e;s--,l+=n[a++]<<u,u+=8}if(r.wrap&4&&l!==(r.total&4294967295)){t.msg="incorrect length check",r.mode=we;break}l=0,u=0}r.mode=i0;case i0:A=yw;break e;case we:A=F0;break e;case D0:return I0;case k0:default:return dr}return t.next_out=o,t.avail_out=c,t.next_in=a,t.avail_in=s,r.hold=l,r.bits=u,(r.wsize||f!==t.avail_out&&r.mode<we&&(r.mode<df||e!==kp))&&G0(t,t.output,t.next_out,f-t.avail_out),d-=t.avail_in,f-=t.avail_out,t.total_in+=d,t.total_out+=f,r.total+=f,r.wrap&4&&f&&(t.adler=r.check=r.flags?Ne(r.check,i,f,t.next_out-f):Cs(r.check,i,f,t.next_out-f)),t.data_type=r.bits+(r.last?64:0)+(r.mode===dn?128:0)+(r.mode===Oc||r.mode===uf?256:0),(d===0&&f===0||e===kp)&&A===Ii&&(A=xw),A},Tw=t=>{if(ki(t))return dr;let e=t.state;return e.window&&(e.window=null),t.state=null,Ii},Pw=(t,e)=>{if(ki(t))return dr;let r=t.state;return(r.wrap&2)===0?dr:(r.head=e,e.done=!1,Ii)},Rw=(t,e)=>{let r=e.length,n,i,a;return ki(t)||(n=t.state,n.wrap!==0&&n.mode!==Wc)?dr:n.mode===Wc&&(i=1,i=Cs(i,e,r,0),i!==n.check)?F0:(a=G0(t,e,r,r),a?(n.mode=D0,I0):(n.havedict=1,Ii))},Cw=z0,Bw=O0,Fw=U0,Iw=Aw,Dw=N0,kw=Lw,Uw=Tw,zw=Pw,Ow=Rw,Nw="pako inflate (from Nodeca project)",hn={inflateReset:Cw,inflateReset2:Bw,inflateResetKeep:Fw,inflateInit:Iw,inflateInit2:Dw,inflate:kw,inflateEnd:Uw,inflateGetHeader:zw,inflateSetDictionary:Ow,inflateInfo:Nw};function Gw(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}var Vw=Gw,V0=Object.prototype.toString,{Z_NO_FLUSH:Hw,Z_FINISH:Ww,Z_OK:Is,Z_STREAM_END:mf,Z_NEED_DICT:pf,Z_STREAM_ERROR:Xw,Z_DATA_ERROR:s0,Z_MEM_ERROR:$w}=Di;function zs(t){this.options=$c.assign({chunkSize:1024*64,windowBits:15,to:""},t||{});let e=this.options;e.raw&&e.windowBits>=0&&e.windowBits<16&&(e.windowBits=-e.windowBits,e.windowBits===0&&(e.windowBits=-15)),e.windowBits>=0&&e.windowBits<16&&!(t&&t.windowBits)&&(e.windowBits+=32),e.windowBits>15&&e.windowBits<48&&(e.windowBits&15)===0&&(e.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new P0,this.strm.avail_out=0;let r=hn.inflateInit2(this.strm,e.windowBits);if(r!==Is)throw new Error(Bi[r]);if(this.header=new Vw,hn.inflateGetHeader(this.strm,this.header),e.dictionary&&(typeof e.dictionary=="string"?e.dictionary=Fs.string2buf(e.dictionary):V0.call(e.dictionary)==="[object ArrayBuffer]"&&(e.dictionary=new Uint8Array(e.dictionary)),e.raw&&(r=hn.inflateSetDictionary(this.strm,e.dictionary),r!==Is)))throw new Error(Bi[r])}zs.prototype.push=function(t,e){let r=this.strm,n=this.options.chunkSize,i=this.options.dictionary,a,o,s;if(this.ended)return!1;for(e===~~e?o=e:o=e===!0?Ww:Hw,V0.call(t)==="[object ArrayBuffer]"?r.input=new Uint8Array(t):r.input=t,r.next_in=0,r.avail_in=r.input.length;;){for(r.avail_out===0&&(r.output=new Uint8Array(n),r.next_out=0,r.avail_out=n),a=hn.inflate(r,o),a===pf&&i&&(a=hn.inflateSetDictionary(r,i),a===Is?a=hn.inflate(r,o):a===s0&&(a=pf));r.avail_in>0&&a===mf&&r.state.wrap>0&&t[r.next_in]!==0;)hn.inflateReset(r),a=hn.inflate(r,o);switch(a){case Xw:case s0:case pf:case $w:return this.onEnd(a),this.ended=!0,!1}if(s=r.avail_out,r.next_out&&(r.avail_out===0||a===mf))if(this.options.to==="string"){let c=Fs.utf8border(r.output,r.next_out),l=r.next_out-c,u=Fs.buf2string(r.output,c);r.next_out=l,r.avail_out=n-l,l&&r.output.set(r.output.subarray(c,c+l),0),this.onData(u)}else this.onData(r.output.length===r.next_out?r.output:r.output.subarray(0,r.next_out));if(!(a===Is&&s===0)){if(a===mf)return a=hn.inflateEnd(this.strm),this.onEnd(a),this.ended=!0,!0;if(r.avail_in===0)break}}return!0};zs.prototype.onData=function(t){this.chunks.push(t)};zs.prototype.onEnd=function(t){t===Is&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=$c.flattenChunks(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg};function Cf(t,e){let r=new zs(e);if(r.push(t),r.err)throw r.msg||Bi[r.err];return r.result}function Kw(t,e){return e=e||{},e.raw=!0,Cf(t,e)}var Yw=zs,qw=Cf,Zw=Kw,jw=Cf,Qw=Di,Jw={Inflate:Yw,inflate:qw,inflateRaw:Zw,ungzip:jw,constants:Qw},{Deflate:e2,deflate:t2,deflateRaw:r2,gzip:n2}=sw,{Inflate:i2,inflate:a2,inflateRaw:o2,ungzip:s2}=Jw,l2=e2,c2=t2,u2=r2,d2=n2,f2=i2,h2=a2,m2=o2,p2=s2,g2=Di,Bf={Deflate:l2,deflate:c2,deflateRaw:u2,gzip:d2,Inflate:f2,inflate:h2,inflateRaw:m2,ungzip:p2,constants:g2};var $a=class $a{constructor(e=$a.INITIAL_SIZE){this.buffer=new Uint8Array(e),this.readOffset=0,this.writeOffset=0}append(e){let r=e instanceof Uint8Array?e:new Uint8Array(e),n=this.writeOffset+r.length;n>this.buffer.length&&this.grow(n),this.buffer.set(r,this.writeOffset),this.writeOffset+=r.length}hasBytes(e){return this.writeOffset-this.readOffset>=e}available(){return this.writeOffset-this.readOffset}readByte(){if(!this.hasBytes(1))throw new Error("Buffer underflow");return this.buffer[this.readOffset++]}readShort(){if(!this.hasBytes(2))throw new Error("Buffer underflow");let e=this.buffer[this.readOffset]|this.buffer[this.readOffset+1]<<8;return this.readOffset+=2,e>32767?e-65536:e}readLong(){if(!this.hasBytes(4))throw new Error("Buffer underflow");let e=this.buffer[this.readOffset]|this.buffer[this.readOffset+1]<<8|this.buffer[this.readOffset+2]<<16|this.buffer[this.readOffset+3]<<24;return this.readOffset+=4,e}readFloat(){if(!this.hasBytes(4))throw new Error("Buffer underflow");let r=new DataView(this.buffer.buffer,this.buffer.byteOffset+this.readOffset,4).getFloat32(0,!0);return this.readOffset+=4,r}readString(){let e=Math.min($a.MAX_STRING_LENGTH,this.writeOffset-this.readOffset),r=0;for(;r<e&&this.buffer[this.readOffset+r]!==0;)r++;if(r>=e)throw this.writeOffset-this.readOffset<=e?new Error("Buffer underflow"):new Error("String exceeds max length");let n=this.buffer.slice(this.readOffset,this.readOffset+r);return this.readOffset+=r+1,new TextDecoder("latin1").decode(n)}peekBytes(e){if(!this.hasBytes(e))throw new Error("Buffer underflow");return this.buffer.slice(this.readOffset,this.readOffset+e)}readBytes(e){if(!this.hasBytes(e))throw new Error("Buffer underflow");let r=this.buffer.slice(this.readOffset,this.readOffset+e);return this.readOffset+=e,r}readData(e){return this.readBytes(e)}getReadPosition(){return this.readOffset}getWritePosition(){return this.writeOffset}setReadPosition(e){if(e<0||e>this.writeOffset)throw new Error("Invalid read position");this.readOffset=e}grow(e){let r=e?Math.max(e,this.buffer.length*2):this.buffer.length*2,n=new Uint8Array(r);n.set(this.buffer),this.buffer=n}compact(){if(this.readOffset===0)return;let e=this.writeOffset-this.readOffset;if(e===0){this.readOffset=0,this.writeOffset=0;return}this.buffer.copyWithin(0,this.readOffset,this.writeOffset),this.readOffset=0,this.writeOffset=e}getCapacity(){return this.buffer.length}reset(){this.readOffset=0,this.writeOffset=0}};$a.INITIAL_SIZE=64*1024,$a.MAX_STRING_LENGTH=2048;var Qn=$a;var Wr=()=>({number:0,modelindex:0,modelindex2:0,modelindex3:0,modelindex4:0,frame:0,skinnum:0,effects:0,renderfx:0,origin:{x:0,y:0,z:0},old_origin:{x:0,y:0,z:0},angles:{x:0,y:0,z:0},sound:0,event:0,solid:0,bits:0,bitsHigh:0,alpha:0,scale:0,instanceBits:0,loopVolume:0,loopAttenuation:0,owner:0,oldFrame:0}),_r=()=>({pm_type:0,origin:{x:0,y:0,z:0},velocity:{x:0,y:0,z:0},pm_time:0,pm_flags:0,gravity:0,delta_angles:{x:0,y:0,z:0},viewoffset:{x:0,y:0,z:0},viewangles:{x:0,y:0,z:0},kick_angles:{x:0,y:0,z:0},gun_index:0,gun_frame:0,gun_offset:{x:0,y:0,z:0},gun_angles:{x:0,y:0,z:0},blend:[0,0,0,0],fov:0,rdflags:0,stats:new Array(32).fill(0),gunskin:0,gunrate:0,damage_blend:[0,0,0,0],team_id:0,watertype:0});var H0={0:R.bad,1:R.nop,2:R.disconnect,3:R.reconnect,4:R.download,5:R.frame,6:R.inventory,7:R.layout,8:R.muzzleflash,9:R.temp_entity,10:R.sound,11:R.print,12:R.stufftext,13:R.serverdata,14:R.configstring,15:R.spawnbaseline,16:R.centerprint,17:R.playerinfo,18:R.packetentities,19:R.deltapacketentities,20:R.muzzleflash2},Yc=class{constructor(){this.protocolVersion=34}translateCommand(e){return H0[e]!==void 0?H0[e]:R.bad}parseServerData(e){let r=e.readLong(),n=e.readLong(),i=e.readByte(),a=e.readString(),o=e.readShort(),s=e.readString();return{protocol:r,serverCount:n,attractLoop:i,gameDir:a,playerNum:o,levelName:s}}parseEntityBits(e){let r=e.readByte();r&Mr&&(r|=e.readByte()<<8),r&Er&&(r|=e.readByte()<<16),r&Lr&&(r|=e.readByte()<<24);let n;return r&ai?n=e.readShort():n=e.readByte(),{number:n,bits:r,bitsHigh:0}}parseDelta(e,r,n,i,a,o){r.number=e.number,r.modelindex=e.modelindex,r.modelindex2=e.modelindex2,r.modelindex3=e.modelindex3,r.modelindex4=e.modelindex4,r.frame=e.frame,r.skinnum=e.skinnum,r.effects=e.effects,r.renderfx=e.renderfx,r.origin.x=e.origin.x,r.origin.y=e.origin.y,r.origin.z=e.origin.z,r.old_origin.x=e.origin.x,r.old_origin.y=e.origin.y,r.old_origin.z=e.origin.z,r.angles.x=e.angles.x,r.angles.y=e.angles.y,r.angles.z=e.angles.z,r.sound=e.sound,r.event=e.event,r.solid=e.solid,r.number=n,r.bits=i,i&Rt&&(r.modelindex=o.readByte()),i&Bt&&(r.modelindex2=o.readByte()),i&Ft&&(r.modelindex3=o.readByte()),i&It&&(r.modelindex4=o.readByte()),i&Et&&(r.frame=o.readByte()),i&Ct&&(r.frame=o.readShort()),i&Ze&&i&Je?r.skinnum=o.readLong():i&Ze?r.skinnum=o.readByte():i&Je&&(r.skinnum=o.readShort()),i&qe&&i&Qe?r.effects=o.readLong():i&qe?r.effects=o.readByte():i&Qe&&(r.effects=o.readShort()),i&Ye&&i&je?r.renderfx=o.readLong():i&Ye?r.renderfx=o.readByte():i&je&&(r.renderfx=o.readShort()),i&St&&(r.origin.x=o.readShort()*.125),i&wt&&(r.origin.y=o.readShort()*.125),i&Tt&&(r.origin.z=o.readShort()*.125),i&Pt&&(r.angles.x=o.readByte()*(360/256)),i&Mt&&(r.angles.y=o.readByte()*(360/256)),i&At&&(r.angles.z=o.readByte()*(360/256)),i&pr&&(r.old_origin.x=o.readShort()*.125,r.old_origin.y=o.readShort()*.125,r.old_origin.z=o.readShort()*.125),i&Dt&&(r.sound=o.readByte()),i&Lt?r.event=o.readByte():r.event=0,i&kt&&(r.solid=o.readShort())}parsePlayerState(e){let r=_r(),n=e.readShort();n&1&&(r.pm_type=e.readByte()),n&2&&(r.origin.x=e.readShort()*.125,r.origin.y=e.readShort()*.125,r.origin.z=e.readShort()*.125),n&4&&(r.velocity.x=e.readShort()*.125,r.velocity.y=e.readShort()*.125,r.velocity.z=e.readShort()*.125),n&8&&(r.pm_time=e.readByte()),n&16&&(r.pm_flags=e.readByte()),n&32&&(r.gravity=e.readShort()),n&64&&(r.delta_angles.x=e.readShort()*(180/32768),r.delta_angles.y=e.readShort()*(180/32768),r.delta_angles.z=e.readShort()*(180/32768)),n&128&&(r.viewoffset.x=(e.readByte()<<24>>24)*.25,r.viewoffset.y=(e.readByte()<<24>>24)*.25,r.viewoffset.z=(e.readByte()<<24>>24)*.25),n&256&&(r.viewangles.x=e.readShort()*(360/65536),r.viewangles.y=e.readShort()*(360/65536),r.viewangles.z=e.readShort()*(360/65536)),n&512&&(r.kick_angles.x=(e.readByte()<<24>>24)*.25,r.kick_angles.y=(e.readByte()<<24>>24)*.25,r.kick_angles.z=(e.readByte()<<24>>24)*.25),n&4096&&(r.gun_index=e.readByte()),n&8192&&(r.gun_frame=e.readByte(),r.gun_offset.x=(e.readByte()<<24>>24)*.25,r.gun_offset.y=(e.readByte()<<24>>24)*.25,r.gun_offset.z=(e.readByte()<<24>>24)*.25,r.gun_angles.x=(e.readByte()<<24>>24)*.25,r.gun_angles.y=(e.readByte()<<24>>24)*.25,r.gun_angles.z=(e.readByte()<<24>>24)*.25),n&1024&&(r.blend[0]=e.readByte(),r.blend[1]=e.readByte(),r.blend[2]=e.readByte(),r.blend[3]=e.readByte()),n&2048&&(r.fov=e.readByte()),n&16384&&(r.rdflags=e.readByte()),n&32768&&(r.watertype=e.readByte());let i=e.readLong();for(let a=0;a<32;a++)i&1<<a&&(r.stats[a]=e.readShort());return r}};var Xr=2023,qc=class{constructor(){this.protocolVersion=Xr}translateCommand(e){return e}parseServerData(e){let r=e.readLong(),n=e.readLong(),i=e.readByte(),a=e.readByte(),o=e.readString(),s=e.readShort();if(s===-2){let l=e.readShort();for(let u=0;u<l;u++)e.readShort();s=0}else s===-1&&(s=-1);let c=e.readString();return{protocol:r,serverCount:n,spawnCount:n,attractLoop:0,gameDir:o,playerNum:s,levelName:c,tickRate:a,demoType:i}}parseEntityBits(e){let r=e.readByte();r&Mr&&(r|=e.readByte()<<8),r&Er&&(r|=e.readByte()<<16),r&Lr&&(r|=e.readByte()<<24);let n=0;r&Ni&&(n=e.readByte());let i;return r&ai?i=e.readShort():i=e.readByte(),{number:i,bits:r,bitsHigh:n}}parseDelta(e,r,n,i,a,o){Object.assign(r,e),r.origin={...e.origin},r.old_origin={...e.old_origin},r.angles={...e.angles},r.number=n,r.bits=i,r.bitsHigh=a,i&Rt&&(r.modelindex=o.readByte()),i&Bt&&(r.modelindex2=o.readByte()),i&Ft&&(r.modelindex3=o.readByte()),i&It&&(r.modelindex4=o.readByte()),i&Et&&(r.frame=o.readByte()),i&Ct&&(r.frame=o.readShort()),i&Ze&&i&Je?r.skinnum=o.readLong():i&Ze?r.skinnum=o.readByte():i&Je&&(r.skinnum=o.readShort()),i&qe&&i&Qe?r.effects=o.readLong():i&qe?r.effects=o.readByte():i&Qe&&(r.effects=o.readShort()),i&Ye&&i&je?r.renderfx=o.readLong():i&Ye?r.renderfx=o.readByte():i&je&&(r.renderfx=o.readShort()),i&St&&(r.origin.x=o.readShort()*.125),i&wt&&(r.origin.y=o.readShort()*.125),i&Tt&&(r.origin.z=o.readShort()*.125),i&Pt&&(r.angles.x=o.readByte()*(360/256)),i&Mt&&(r.angles.y=o.readByte()*(360/256)),i&At&&(r.angles.z=o.readByte()*(360/256)),i&pr&&(r.old_origin.x=o.readShort()*.125,r.old_origin.y=o.readShort()*.125,r.old_origin.z=o.readShort()*.125),i&Dt&&(r.sound=o.readByte()),i&Lt?r.event=o.readByte():r.event=0,i&kt&&(r.solid=o.readShort()),i&Ar&&(r.alpha=o.readByte()/255),i&Tr&&(r.scale=o.readFloat()),i&Pr&&(r.instanceBits=o.readLong()),i&Rr&&(r.loopVolume=o.readByte()/255),a&_n&&(r.loopAttenuation=o.readByte()/255),a&Sn&&(r.owner=o.readShort()),a&wn&&(r.oldFrame=o.readShort())}parsePlayerState(e){let r=_r(),n=e.readShort();n&1&&(r.pm_type=e.readByte()),n&2&&(r.origin.x=e.readShort()*.125,r.origin.y=e.readShort()*.125,r.origin.z=e.readShort()*.125),n&4&&(r.velocity.x=e.readShort()*.125,r.velocity.y=e.readShort()*.125,r.velocity.z=e.readShort()*.125),n&8&&(r.pm_time=e.readByte()),n&16&&(r.pm_flags=e.readByte()),n&32&&(r.gravity=e.readShort()),n&64&&(r.delta_angles.x=e.readShort()*(180/32768),r.delta_angles.y=e.readShort()*(180/32768),r.delta_angles.z=e.readShort()*(180/32768)),n&128&&(r.viewoffset.x=(e.readByte()<<24>>24)*.25,r.viewoffset.y=(e.readByte()<<24>>24)*.25,r.viewoffset.z=(e.readByte()<<24>>24)*.25),n&256&&(r.viewangles.x=e.readShort()*(360/65536),r.viewangles.y=e.readShort()*(360/65536),r.viewangles.z=e.readShort()*(360/65536)),n&512&&(r.kick_angles.x=(e.readByte()<<24>>24)*.25,r.kick_angles.y=(e.readByte()<<24>>24)*.25,r.kick_angles.z=(e.readByte()<<24>>24)*.25),n&4096&&(r.gun_index=e.readByte()),n&8192&&(r.gun_frame=e.readByte(),r.gun_offset.x=(e.readByte()<<24>>24)*.25,r.gun_offset.y=(e.readByte()<<24>>24)*.25,r.gun_offset.z=(e.readByte()<<24>>24)*.25,r.gun_angles.x=(e.readByte()<<24>>24)*.25,r.gun_angles.y=(e.readByte()<<24>>24)*.25,r.gun_angles.z=(e.readByte()<<24>>24)*.25),n&1024&&(r.blend[0]=e.readByte(),r.blend[1]=e.readByte(),r.blend[2]=e.readByte(),r.blend[3]=e.readByte()),n&2048&&(r.fov=e.readByte()),n&16384&&(r.rdflags=e.readByte()),n&32768&&(r.watertype=e.readByte());let i=e.readLong();for(let a=0;a<32;a++)i&1<<a&&(r.stats[a]=e.readShort());return r}};var Zc=class{constructor(e=0){this.protocolVersion=e}translateCommand(e){return e}parseServerData(e){let r=e.readLong(),n=e.readLong(),i=e.readByte(),a=e.readString(),o=e.readShort(),s=e.readString();return{protocol:r,serverCount:n,attractLoop:i,gameDir:a,playerNum:o,levelName:s}}parseEntityBits(e){let r=e.readByte();r&Mr&&(r|=e.readByte()<<8),r&Er&&(r|=e.readByte()<<16),r&Lr&&(r|=e.readByte()<<24);let n;return r&ai?n=e.readShort():n=e.readByte(),{number:n,bits:r,bitsHigh:0}}parseDelta(e,r,n,i,a,o){r.number=e.number,r.modelindex=e.modelindex,r.modelindex2=e.modelindex2,r.modelindex3=e.modelindex3,r.modelindex4=e.modelindex4,r.frame=e.frame,r.skinnum=e.skinnum,r.effects=e.effects,r.renderfx=e.renderfx,r.origin.x=e.origin.x,r.origin.y=e.origin.y,r.origin.z=e.origin.z,r.old_origin.x=e.origin.x,r.old_origin.y=e.origin.y,r.old_origin.z=e.origin.z,r.angles.x=e.angles.x,r.angles.y=e.angles.y,r.angles.z=e.angles.z,r.sound=e.sound,r.event=e.event,r.solid=e.solid,r.number=n,r.bits=i,i&Rt&&(r.modelindex=o.readByte()),i&Bt&&(r.modelindex2=o.readByte()),i&Ft&&(r.modelindex3=o.readByte()),i&It&&(r.modelindex4=o.readByte()),i&Et&&(r.frame=o.readByte()),i&Ct&&(r.frame=o.readShort()),i&Ze&&i&Je?r.skinnum=o.readLong():i&Ze?r.skinnum=o.readByte():i&Je&&(r.skinnum=o.readShort()),i&qe&&i&Qe?r.effects=o.readLong():i&qe?r.effects=o.readByte():i&Qe&&(r.effects=o.readShort()),i&Ye&&i&je?r.renderfx=o.readLong():i&Ye?r.renderfx=o.readByte():i&je&&(r.renderfx=o.readShort()),i&St&&(r.origin.x=o.readShort()*.125),i&wt&&(r.origin.y=o.readShort()*.125),i&Tt&&(r.origin.z=o.readShort()*.125),i&Pt&&(r.angles.x=o.readByte()*(360/256)),i&Mt&&(r.angles.y=o.readByte()*(360/256)),i&At&&(r.angles.z=o.readByte()*(360/256)),i&pr&&(r.old_origin.x=o.readShort()*.125,r.old_origin.y=o.readShort()*.125,r.old_origin.z=o.readShort()*.125),i&Dt&&(r.sound=o.readByte()),i&Lt?r.event=o.readByte():r.event=0,i&kt&&(r.solid=o.readShort())}parsePlayerState(e){let r=_r(),n=e.readShort();n&1&&(r.pm_type=e.readByte()),n&2&&(r.origin.x=e.readShort()*.125,r.origin.y=e.readShort()*.125,r.origin.z=e.readShort()*.125),n&4&&(r.velocity.x=e.readShort()*.125,r.velocity.y=e.readShort()*.125,r.velocity.z=e.readShort()*.125),n&8&&(r.pm_time=e.readByte()),n&16&&(r.pm_flags=e.readByte()),n&32&&(r.gravity=e.readShort()),n&64&&(r.delta_angles.x=e.readShort()*(180/32768),r.delta_angles.y=e.readShort()*(180/32768),r.delta_angles.z=e.readShort()*(180/32768)),n&128&&(r.viewoffset.x=(e.readByte()<<24>>24)*.25,r.viewoffset.y=(e.readByte()<<24>>24)*.25,r.viewoffset.z=(e.readByte()<<24>>24)*.25),n&256&&(r.viewangles.x=e.readShort()*(360/65536),r.viewangles.y=e.readShort()*(360/65536),r.viewangles.z=e.readShort()*(360/65536)),n&512&&(r.kick_angles.x=(e.readByte()<<24>>24)*.25,r.kick_angles.y=(e.readByte()<<24>>24)*.25,r.kick_angles.z=(e.readByte()<<24>>24)*.25),n&4096&&(r.gun_index=e.readByte()),n&8192&&(r.gun_frame=e.readByte(),r.gun_offset.x=(e.readByte()<<24>>24)*.25,r.gun_offset.y=(e.readByte()<<24>>24)*.25,r.gun_offset.z=(e.readByte()<<24>>24)*.25,r.gun_angles.x=(e.readByte()<<24>>24)*.25,r.gun_angles.y=(e.readByte()<<24>>24)*.25,r.gun_angles.z=(e.readByte()<<24>>24)*.25),n&1024&&(r.blend[0]=e.readByte(),r.blend[1]=e.readByte(),r.blend[2]=e.readByte(),r.blend[3]=e.readByte()),n&2048&&(r.fov=e.readByte()),n&16384&&(r.rdflags=e.readByte()),n&32768&&(r.watertype=e.readByte());let i=e.readLong();for(let a=0;a<32;a++)i&1<<a&&(r.stats[a]=e.readShort());return r}};var Os=class{constructor(){this.protocolVersion=0}translateCommand(e){return e===7?R.serverdata:e===12?R.serverdata:e===13?R.serverdata:e===R.stufftext?R.stufftext:R.bad}parseServerData(e){let r=e.readLong();if(r===Xr){let n=e.readLong(),i=e.readByte(),a=e.readByte(),o=e.readString(),s=e.readShort();if(s===-2){let l=e.readShort();for(let u=0;u<l;u++)e.readShort();s=0}else s===-1&&(s=-1);let c=e.readString();return{protocol:r,serverCount:n,spawnCount:n,attractLoop:0,gameDir:o,playerNum:s,levelName:c,tickRate:a,demoType:i}}else{let n=e.readLong(),i=e.readByte(),a=e.readString(),o=e.readShort(),s=e.readString();return{protocol:r,serverCount:n,attractLoop:i,gameDir:a,playerNum:o,levelName:s}}}parseEntityBits(e){throw new Error("Bootstrap handler cannot parse entities")}parseDelta(e,r,n,i,a,o){throw new Error("Bootstrap handler cannot parse delta")}parsePlayerState(e){throw new Error("Bootstrap handler cannot parse player state")}};function W0(t){return t===0?new Os:t===Xr?new qc:t===34?new Yc:new Zc(t)}var X0=1,y2=2,b2=128,Ff=class extends Qn{constructor(r){super(0);this.stream=r}readByte(){return this.stream.readByte()}readShort(){return this.stream.readShort()}readLong(){return this.stream.readLong()}readFloat(){return this.stream.readFloat()}readString(){return this.stream.readString()}readData(r){return this.stream.readData(r)}hasBytes(r){return this.stream.hasMore()}available(){return this.stream.getRemaining()}getReadPosition(){return this.stream.getPosition()}peekBytes(r){throw new Error("peekBytes not implemented for BinaryStreamAdapter")}},xt=class t{constructor(e,r,n=!1){this.strictMode=!1;this.errorCount=0;this.isDemo=X0;e instanceof Mn?this.stream=new Ff(e):this.stream=e,this.handler=r,this.strictMode=n,this.protocolHandler=new Os}setProtocolVersion(e){this.protocolHandler.protocolVersion!==e&&(this.protocolHandler=W0(e))}getProtocolVersion(){return this.protocolHandler.protocolVersion}getErrorCount(){return this.errorCount}parseMessage(){for(;this.stream.hasBytes(1);){let e=this.stream.getReadPosition(),r=-1;try{if(r=this.stream.readByte(),r===-1)break;let n=r,i=this.protocolHandler.translateCommand(r);switch(i){case R.bad:if(n===0)return;let a=`Unknown server command: ${n} (translated: ${i}) at offset ${e} (Protocol: ${this.getProtocolVersion()})`;if(this.strictMode)throw new Error(a);console.warn(a),this.errorCount++;return;case R.nop:break;case R.disconnect:this.handler?.onDisconnect&&this.handler.onDisconnect();break;case R.reconnect:this.handler?.onReconnect&&this.handler.onReconnect();break;case R.print:this.parsePrint();break;case R.serverdata:this.parseServerData();break;case R.configstring:this.parseConfigString();break;case R.spawnbaseline:this.parseSpawnBaseline();break;case R.centerprint:this.parseCenterPrint();break;case R.download:this.parseDownload();break;case R.frame:this.parseFrame();break;case R.packetentities:this.parsePacketEntities(!1);break;case R.deltapacketentities:this.parsePacketEntities(!0);break;case R.playerinfo:this.parsePlayerState();break;case R.stufftext:this.parseStuffText();break;case R.layout:this.parseLayout();break;case R.inventory:this.parseInventory();break;case R.sound:this.parseSound();break;case R.muzzleflash:this.parseMuzzleFlash();break;case R.muzzleflash2:this.parseMuzzleFlash2();break;case R.temp_entity:this.parseTempEntity();break;case R.splitclient:this.parseSplitClient();break;case R.configblast:this.parseConfigBlast();break;case R.spawnbaselineblast:this.parseSpawnBaselineBlast();break;case R.level_restart:this.handler?.onLevelRestart&&this.handler.onLevelRestart();break;case R.damage:this.parseDamage();break;case R.locprint:this.parseLocPrint();break;case R.fog:this.parseFog();break;case R.waitingforplayers:this.parseWaitingForPlayers();break;case R.bot_chat:this.parseBotChat();break;case R.poi:this.parsePoi();break;case R.help_path:this.parseHelpPath();break;case R.muzzleflash3:this.parseMuzzleFlash3();break;case R.achievement:this.parseAchievement();break;default:let o=`Unknown server command: ${n} (translated: ${i}) at offset ${e}`;if(this.strictMode)throw new Error(o);console.warn(o),this.errorCount++;return}}catch(n){let i=n.message;if(i==="Buffer underflow"||i.includes("StreamingBuffer")){try{this.stream.setReadPosition(e)}catch(o){console.error("Failed to rollback stream position",o)}return}let a=`offset ${e}, cmd ${r}, protocol ${this.getProtocolVersion()}`;if(console.warn(`Error parsing command ${r} (${a}): ${i}`),this.errorCount++,this.strictMode)throw n;return}}}readAngle16(){return this.stream.readShort()*(360/65536)}readCoord(){return this.stream.readShort()*.125}readAngle(){return this.stream.readByte()*(360/256)}readPos(e){e.x=this.stream.readShort()*.125,e.y=this.stream.readShort()*.125,e.z=this.stream.readShort()*.125}readDir(e){let r=this.stream.readByte();if(r>=mr.length)e.x=0,e.y=0,e.z=0;else{let n=mr[r];e.x=n[0],e.y=n[1],e.z=n[2]}}parsePrint(){let e=this.stream.readByte(),r=this.stream.readString();this.handler&&this.handler.onPrint(e,r)}parseStuffText(){let e=this.stream.readString();this.handler&&this.handler.onStuffText(e)}parseLayout(){let e=this.stream.readString();this.handler&&this.handler.onLayout(e)}parseCenterPrint(){let e=this.stream.readString();this.handler&&this.handler.onCenterPrint(e)}parseServerData(){let e=this.protocolHandler.parseServerData(this.stream);this.setProtocolVersion(e.protocol),this.handler&&this.handler.onServerData(e.protocol,e.serverCount,e.attractLoop,e.gameDir,e.playerNum,e.levelName,e.tickRate,e.demoType),e.protocol===Xr?this.isDemo=e.demoType??X0:this.isDemo=e.attractLoop}parseConfigString(){let e=this.stream.readShort(),r=this.stream.readString();this.handler&&this.handler.onConfigString(e,r)}parseSplitClient(){let e=this.stream.readByte();this.handler?.onSplitClient&&this.handler.onSplitClient(e)}parseConfigBlast(){let e=this.stream.readShort(),r=this.stream.readShort(),n=this.stream.readData(e);try{let i=Bf.inflate(n),a=new Mn(i.buffer);for(;a.hasMore();){let o=a.readUShort(),s=a.readString();this.handler&&this.handler.onConfigString(o,s)}}catch(i){console.error("svc_configblast error",i)}}parseSpawnBaselineBlast(){let e=this.stream.readShort(),r=this.stream.readShort(),n=this.stream.readData(e);try{let i=Bf.inflate(n),a=new Mn(i.buffer),o=new t(a,this.handler,this.strictMode);for(o.setProtocolVersion(this.getProtocolVersion());a.hasMore();)o.parseSpawnBaseline()}catch(i){console.error("svc_spawnbaselineblast error",i)}}parseLocPrint(){let e=this.stream.readByte(),r=this.stream.readString(),n=this.stream.readByte(),i=[];for(let a=0;a<n;a++)i.push(this.stream.readString());this.handler?.onLocPrint&&this.handler.onLocPrint(e,r,i)}parseWaitingForPlayers(){let e=this.stream.readByte();this.handler?.onWaitingForPlayers&&this.handler.onWaitingForPlayers(e)}parseBotChat(){let e=this.stream.readString(),r=this.stream.readShort(),n=this.stream.readString();this.handler?.onBotChat&&this.handler.onBotChat(n)}parsePoi(){let e=this.stream.readShort(),r=this.stream.readShort(),n={x:0,y:0,z:0};this.readPos(n);let i=this.stream.readShort(),a=this.stream.readByte(),o=this.stream.readByte();this.handler?.onPoi&&this.handler.onPoi(o,n)}parseHelpPath(){let e=this.stream.readByte(),r={x:0,y:0,z:0};this.readPos(r);let n={x:0,y:0,z:0};this.readDir(n),this.handler?.onHelpPath&&this.handler.onHelpPath(r)}parseAchievement(){let e=this.stream.readString();this.handler?.onAchievement&&this.handler.onAchievement(e)}parseDownload(){let e=this.stream.readShort(),r=this.stream.readByte(),n;e>0&&(n=this.stream.readData(e)),this.handler&&this.handler.onDownload(e,r,n)}parseInventory(){let r=new Array(256);for(let n=0;n<256;n++)r[n]=this.stream.readShort();this.handler&&this.handler.onInventory(r)}parseSound(){let e=this.stream.readByte(),r=this.stream.readByte(),n,i,a,o,s;if(e&1&&(n=this.stream.readByte()),e&2&&(i=this.stream.readByte()),e&16&&(a=this.stream.readByte()),e&8&&(o=this.stream.readShort()),e&4){let c={x:0,y:0,z:0};this.readPos(c),s=c}this.handler&&this.handler.onSound(e,r,n,i,a,o,s)}parseMuzzleFlash(){let e=this.stream.readShort(),r=this.stream.readByte();this.handler&&this.handler.onMuzzleFlash(e,r)}parseMuzzleFlash2(){let e=this.stream.readShort(),r=this.stream.readByte();this.handler&&this.handler.onMuzzleFlash2(e,r)}parseMuzzleFlash3(){let e=this.stream.readShort(),r=this.stream.readShort();this.handler?.onMuzzleFlash3&&this.handler.onMuzzleFlash3(e,r)}parseFog(){let e=this.stream.readByte();if(e&128){let n=this.stream.readByte();e|=n<<8}let r={};e&1&&(r.density=this.stream.readFloat(),r.skyfactor=this.stream.readByte()),e&2&&(r.red=this.stream.readByte()),e&4&&(r.green=this.stream.readByte()),e&8&&(r.blue=this.stream.readByte()),e&16&&(r.time=this.stream.readShort()),e&32&&(r.hf_falloff=this.stream.readFloat()),e&64&&(r.hf_density=this.stream.readFloat()),e&256&&(r.hf_start_r=this.stream.readByte()),e&512&&(r.hf_start_g=this.stream.readByte()),e&1024&&(r.hf_start_b=this.stream.readByte()),e&2048&&(r.hf_start_dist=this.stream.readLong()),e&4096&&(r.hf_end_r=this.stream.readByte()),e&8192&&(r.hf_end_g=this.stream.readByte()),e&16384&&(r.hf_end_b=this.stream.readByte()),e&32768&&(r.hf_end_dist=this.stream.readLong()),this.handler?.onFog&&this.handler.onFog(r)}parseDamage(){let e=this.stream.readByte(),r=[];for(let n=0;n<e;n++){let i=this.stream.readByte(),a={x:0,y:0,z:0};this.readDir(a);let o=i&31,s=(i&32)!==0,c=(i&64)!==0,l=(i&128)!==0;r.push({damage:o,health:s,armor:c,power:l,dir:a})}this.handler?.onDamage&&this.handler.onDamage(r)}parseTempEntity(){let e=this.stream.readByte(),r={x:0,y:0,z:0},n={x:0,y:0,z:0},i={x:0,y:0,z:0},a,o,s,c,l;switch(e){case U.EXPLOSION1:case U.EXPLOSION2:case U.ROCKET_EXPLOSION:case U.GRENADE_EXPLOSION:case U.ROCKET_EXPLOSION_WATER:case U.GRENADE_EXPLOSION_WATER:case U.BFG_EXPLOSION:case U.BFG_BIGEXPLOSION:case U.BOSSTPORT:case U.PLASMA_EXPLOSION:case U.PLAIN_EXPLOSION:case U.CHAINFIST_SMOKE:case U.TRACKER_EXPLOSION:case U.TELEPORT_EFFECT:case U.DBALL_GOAL:case U.NUKEBLAST:case U.WIDOWSPLASH:case U.EXPLOSION1_BIG:case U.EXPLOSION1_NP:this.readPos(r);break;case U.GUNSHOT:case U.BLOOD:case U.BLASTER:case U.SHOTGUN:case U.SPARKS:case U.BULLET_SPARKS:case U.SCREEN_SPARKS:case U.SHIELD_SPARKS:case U.BLASTER2:case U.FLECHETTE:case U.MOREBLOOD:case U.ELECTRIC_SPARKS:case U.HEATBEAM_SPARKS:case U.HEATBEAM_STEAM:this.readPos(r),this.readDir(i);break;case U.SPLASH:case U.LASER_SPARKS:case U.WELDING_SPARKS:case U.TUNNEL_SPARKS:a=this.stream.readByte(),this.readPos(r),this.readDir(i),o=this.stream.readByte();break;case U.BLUEHYPERBLASTER:this.getProtocolVersion()>=32?(this.readPos(r),this.readPos(n)):(this.readPos(r),this.readDir(i));break;case U.GREENBLOOD:this.getProtocolVersion()>=32?(this.readPos(r),this.readDir(i)):(this.readPos(r),this.readPos(n));break;case U.RAILTRAIL:case U.BUBBLETRAIL:case U.BFG_LASER:case U.DEBUGTRAIL:case U.BUBBLETRAIL2:this.readPos(r),this.readPos(n);break;case U.PARASITE_ATTACK:case U.MEDIC_CABLE_ATTACK:this.stream.readShort(),this.readPos(r),this.readPos(n);break;case U.GRAPPLE_CABLE:s=this.stream.readShort(),this.readPos(r),this.readPos(n),this.readPos(i);break;case U.LIGHTNING:c=this.stream.readShort(),l=this.stream.readShort(),this.readPos(r),this.readPos(n);break;case U.FLASHLIGHT:this.readPos(r),s=this.stream.readShort();break;case U.FORCEWALL:this.readPos(r),this.readPos(n),o=this.stream.readByte();break;case U.STEAM:let u=this.stream.readShort();a=this.stream.readByte(),this.readPos(r),this.readDir(i),o=this.stream.readByte(),this.stream.readShort(),u!==-1&&this.stream.readLong();break;case U.WIDOWBEAMOUT:this.stream.readShort();case U.HEATBEAM:case U.MONSTER_HEATBEAM:s=this.stream.readShort(),this.readPos(r),this.readPos(n),this.readDir(i);break}this.handler&&this.handler.onTempEntity(e,r,n,i,a,o,s,c,l)}parseSpawnBaseline(){let e=this.protocolHandler.parseEntityBits(this.stream),r=Wr();this.protocolHandler.parseDelta(Wr(),r,e.number,e.bits,e.bitsHigh,this.stream),this.handler&&this.handler.onSpawnBaseline(r)}parseFrame(){let e=this.stream.readLong(),r=this.stream.readLong(),n=0;this.getProtocolVersion()!==26&&this.getProtocolVersion()!==25&&(n=this.stream.readByte());let i=this.stream.readByte(),a=this.stream.readData(i),o=this.stream.readByte();if(o=this.protocolHandler.translateCommand(o),o!==R.playerinfo){if(this.strictMode)throw new Error(`Expected svc_playerinfo after svc_frame, got ${o}`);return}let s=this.parsePlayerState(),c=this.stream.readByte();if(c=this.protocolHandler.translateCommand(c),c!==R.packetentities&&c!==R.deltapacketentities){if(this.strictMode)throw new Error(`Expected svc_packetentities after svc_playerinfo, got ${c}`);return}let l=this.collectPacketEntities();if(this.isDemo===b2){let u=this.stream.readByte();for(let d=0;d<u;d++)this.stream.readByte()}this.isDemo===y2&&this.stream.readLong(),this.handler&&this.handler.onFrame({serverFrame:e,deltaFrame:r,surpressCount:n,areaBytes:i,areaBits:a,playerState:s,packetEntities:{delta:!0,entities:l}})}parsePlayerState(){return this.protocolHandler.parsePlayerState(this.stream)}parsePacketEntities(e){let r=this.collectPacketEntities();this.handler&&this.handler.onFrame({serverFrame:0,deltaFrame:0,surpressCount:0,areaBytes:0,areaBits:new Uint8Array,playerState:_r(),packetEntities:{delta:e,entities:r}})}collectPacketEntities(){let e=[];for(;;){let r=this.protocolHandler.parseEntityBits(this.stream);if(r.bits&ro){if(r.number===0)break;continue}let n=Wr();if(r.number===0)break;this.protocolHandler.parseDelta(Wr(),n,r.number,r.bits,r.bitsHigh,this.stream),e.push(n)}return e}};var If=(u=>(u.WeaponFire="weapon_fire",u.DamageDealt="damage_dealt",u.DamageReceived="damage_received",u.Pickup="pickup",u.Death="death",u.Kill="kill",u.Spawn="spawn",u.PlayerInfo="player_info",u.Chat="chat",u.Objective="objective",u))(If||{});var Ka=class{constructor(e){this.events=[];this.summary={totalKills:0,totalDeaths:0,damageDealt:0,damageReceived:0,weaponUsage:new Map};this.header=null;this.configStrings=new Map;this.serverInfo={};this.statistics=null;this.playerStats=new Map;this.weaponStats=new Map;this.activeEntities=new Set;this.buffer=e}analyze(){let e=new vr(this.buffer),r=-1,n=0,i=.1,a=0,o={onServerData:(s,c,l,u,d,f,h,m)=>{a=s,this.header={protocolVersion:s,gameDir:u,levelName:f,playerNum:d,serverCount:c,spawnCount:c,tickRate:h,demoType:m},h&&h>0&&(i=1/h)},onConfigString:(s,c)=>{this.configStrings.set(s,c),s===0&&this.parseServerInfo(c)},onSpawnBaseline:s=>{},onFrame:s=>{let c=new Set;if(s.packetEntities&&s.packetEntities.entities)for(let l of s.packetEntities.entities)c.add(l.number),this.activeEntities.has(l.number)||this.recordEvent({type:"spawn",frame:r,time:n,entityId:l.number,position:{x:l.origin.x,y:l.origin.y,z:l.origin.z},description:`Entity ${l.number} spawned`});this.activeEntities=c,s.playerState&&this.header},onPrint:(s,c)=>{let l=c.replace(/\n/g," ").trim();l.includes("died")||l.includes("killed")||l.includes("suicide")?(this.summary.totalDeaths++,this.recordEvent({type:"death",frame:r,time:n,description:l})):l.startsWith("You got the ")?this.recordEvent({type:"pickup",frame:r,time:n,description:l}):(s===3||s===2)&&this.recordEvent({type:"chat",frame:r,time:n,description:l,data:{level:s}})},onCenterPrint:s=>{this.recordEvent({type:"objective",frame:r,time:n,description:s.trim()})},onStuffText:()=>{},onSound:()=>{},onTempEntity:()=>{},onLayout:()=>{},onInventory:()=>{},onMuzzleFlash:(s,c)=>{this.handleWeaponFire(s,c,r,n)},onMuzzleFlash2:(s,c)=>{this.handleWeaponFire(s,c,r,n)},onMuzzleFlash3:(s,c)=>{this.handleWeaponFire(s,c,r,n)},onDisconnect:()=>{},onReconnect:()=>{},onDownload:()=>{},onDamage:s=>{for(let c of s)if(this.recordEvent({type:"damage_received",frame:r,time:n,value:c.damage,position:c.dir,description:`Took ${c.damage} damage`}),this.summary.damageReceived+=c.damage,this.header){let l=this.getOrCreatePlayerStats(this.header.playerNum);l.damageReceived+=c.damage}}};for(;e.hasMore();){let s=e.readNextBlock();if(!s)break;r++,n=r*i;let c=new xt(s.data,o);c.setProtocolVersion(a),c.parseMessage(),a=c.getProtocolVersion()}return this.statistics={duration:n,frameCount:r+1,averageFps:(r+1)/(n||1),mapName:this.header?.levelName||"unknown",playerCount:1},{events:this.events,summary:this.summary,header:this.header,configStrings:this.configStrings,serverInfo:this.serverInfo,statistics:this.statistics,playerStats:this.playerStats,weaponStats:this.weaponStats}}handleWeaponFire(e,r,n,i){this.recordEvent({type:"weapon_fire",frame:n,time:i,entityId:e,value:r,description:`Weapon ${r} fired by ${e}`});let a=this.summary.weaponUsage.get(r)||0;this.summary.weaponUsage.set(r,a+1);let o=this.getOrCreateWeaponStat(e,r);o.shotsFired++}recordEvent(e){this.events.push(e)}parseServerInfo(e){let r=e.split("\\");for(let n=1;n<r.length;n+=2)n+1<r.length&&(this.serverInfo[r[n]]=r[n+1])}getOrCreatePlayerStats(e){let r=this.playerStats.get(e);return r||(r={kills:0,deaths:0,damageDealt:0,damageReceived:0,suicides:0},this.playerStats.set(e,r)),r}getOrCreateWeaponStat(e,r){let n=this.weaponStats.get(e);n||(n=[],this.weaponStats.set(e,n));let i=n.find(a=>a.weaponId===r);return i||(i={weaponId:r,shotsFired:0,hits:0,kills:0},n.push(i)),i}};var Df=(i=>(i[i.FirstPerson=0]="FirstPerson",i[i.ThirdPerson=1]="ThirdPerson",i[i.Free=2]="Free",i[i.Follow=3]="Follow",i))(Df||{});var jc=(i=>(i[i.Stopped=0]="Stopped",i[i.Playing=1]="Playing",i[i.Paused=2]="Paused",i[i.Finished=3]="Finished",i))(jc||{}),x2=()=>({onServerData:()=>{},onConfigString:()=>{},onSpawnBaseline:()=>{},onFrame:()=>{},onCenterPrint:()=>{},onStuffText:()=>{},onPrint:()=>{},onSound:()=>{},onTempEntity:()=>{},onLayout:()=>{},onInventory:()=>{},onMuzzleFlash:()=>{},onMuzzleFlash2:()=>{},onDisconnect:()=>{},onReconnect:()=>{},onDownload:()=>{}}),Ns=class{constructor(){this.reader=null;this.buffer=null;this.state=0;this.playbackSpeed=1;this.currentProtocolVersion=0;this.currentFrameIndex=-1;this.lastFrameData=null;this.accumulatedTime=0;this.frameDuration=100;this.snapshotInterval=100;this.snapshots=new Map;this.cachedEvents=null;this.cachedSummary=null;this.cachedHeader=null;this.cachedConfigStrings=null;this.cachedServerInfo=null;this.cachedStatistics=null;this.cachedPlayerStats=null;this.cachedWeaponStats=null;this.tracker=null;this.cameraMode=0;this.thirdPersonDistance=80;this.thirdPersonOffset={x:0,y:0,z:0}}setHandler(e){this.handler=e}setCallbacks(e){this.callbacks=e}loadDemo(e){this.buffer=e,this.reader=new vr(e),this.transitionState(0),this.accumulatedTime=0,this.currentProtocolVersion=0,this.currentFrameIndex=-1,this.snapshots.clear(),this.lastFrameData=null,this.cachedEvents=null,this.cachedSummary=null,this.cachedHeader=null,this.cachedConfigStrings=null,this.cachedServerInfo=null,this.cachedStatistics=null,this.cachedPlayerStats=null,this.cachedWeaponStats=null}play(){this.reader&&this.state!==1&&this.transitionState(1)}pause(){this.state===1&&this.transitionState(2)}stop(){this.transitionState(0),this.reader&&this.reader.reset(),this.accumulatedTime=0,this.currentProtocolVersion=0,this.currentFrameIndex=-1,this.lastFrameData=null}transitionState(e){this.state!==e&&(this.state=e,this.callbacks?.onPlaybackStateChange&&this.callbacks.onPlaybackStateChange(e))}setFrameDuration(e){this.frameDuration=e}setSpeed(e){this.playbackSpeed=Math.max(.1,Math.min(e,16))}getSpeed(){return this.playbackSpeed}getPlaybackSpeed(){return this.playbackSpeed}getInterpolationFactor(){return this.frameDuration<=0?0:Math.max(0,Math.min(1,this.accumulatedTime/this.frameDuration))}update(e){if(!(this.state!==1||!this.reader))for(this.accumulatedTime+=e*1e3*this.playbackSpeed;this.accumulatedTime>=this.frameDuration;){if(!this.processNextFrame())return;this.accumulatedTime-=this.frameDuration,this.callbacks?.onTimeUpdate&&this.callbacks.onTimeUpdate(this.getCurrentTime())}}stepForward(){this.reader&&(this.processNextFrame(),this.callbacks?.onTimeUpdate&&this.callbacks.onTimeUpdate(this.getCurrentTime()))}stepBackward(){this.reader&&this.currentFrameIndex>0&&this.seek(this.currentFrameIndex-1)}seekToTime(e){let r=this.timeToFrame(e);this.seek(r)}seekToFrame(e){this.seek(e)}frameToTime(e){return e*this.frameDuration/1e3}timeToFrame(e){return Math.floor(e*1e3/this.frameDuration)}playFrom(e){if(e.type==="frame")this.seek(e.frame);else if(e.type==="time")this.seekToTime(e.seconds);else throw new Error(`Invalid offset type: ${e.type}`);this.play()}playRange(e,r){let n=e.type==="frame"?e.frame:this.timeToFrame(e.seconds),i=r.type==="frame"?r.frame:this.timeToFrame(r.seconds),a=this.getTotalFrames(),o=Math.max(0,a-1);if(n<0)throw new Error(`Invalid start offset: ${n}`);if(i<n)throw new Error(`End offset (${i}) cannot be before start offset (${n})`);this.playFrom(e);let s=this.callbacks?.onFrameUpdate,c={...this.callbacks,onFrameUpdate:l=>{if(s&&s(l),this.currentFrameIndex>=i){this.pause();let u=this.callbacks?.onPlaybackComplete;this.callbacks===c&&this.setCallbacks({...this.callbacks,onFrameUpdate:s}),u&&u()}}};this.setCallbacks(c)}seek(e){if(!this.reader)return;let r=this.getTotalFrames();if(r>0&&e>=r&&(e=r-1),e<0&&(e=0),e===this.currentFrameIndex+1){this.processNextFrame(),this.callbacks?.onSeekComplete&&this.callbacks.onSeekComplete();return}if(e===this.currentFrameIndex){this.callbacks?.onSeekComplete&&this.callbacks.onSeekComplete();return}let n=-1,i=null;if(e>this.currentFrameIndex&&this.currentFrameIndex!==-1&&(n=this.currentFrameIndex),this.callbacks?.onRestoreSnapshot)for(let[a,o]of this.snapshots)a<=e&&a>n&&(n=a,i=o);for(n===-1&&this.currentFrameIndex>e?(this.reader.reset(),this.currentFrameIndex=-1,this.currentProtocolVersion=0):n===-1&&(this.reader.reset(),this.currentFrameIndex=-1,this.currentProtocolVersion=0),i&&this.callbacks?.onRestoreSnapshot&&(this.callbacks.onRestoreSnapshot(i),this.reader.seekToMessage(n+1)?this.currentFrameIndex=n:(this.reader.reset(),this.currentFrameIndex=-1,this.currentProtocolVersion=0));this.currentFrameIndex<e&&(this.callbacks?.onCaptureSnapshot&&(this.currentFrameIndex+1)%this.snapshotInterval,!!this.processNextFrame()););this.accumulatedTime=0,this.callbacks?.onSeekComplete&&this.callbacks.onSeekComplete(),this.callbacks?.onTimeUpdate&&this.callbacks.onTimeUpdate(this.getCurrentTime())}processNextFrame(){if(!this.reader||!this.reader.hasMore())return this.transitionState(3),this.callbacks?.onPlaybackComplete&&this.callbacks.onPlaybackComplete(),!1;let e=this.reader.readNextBlock();if(!e)return this.transitionState(3),this.callbacks?.onPlaybackComplete&&this.callbacks.onPlaybackComplete(),!1;this.currentFrameIndex++,this.tracker&&(this.tracker.setCurrentFrame(this.currentFrameIndex),this.tracker.setCurrentTime(this.getCurrentTime()));try{let r={...this.handler||x2(),onFrame:i=>{this.lastFrameData=i,this.handler?.onFrame&&this.handler.onFrame(i),this.callbacks?.onFrameUpdate&&this.callbacks.onFrameUpdate(i)}},n=new xt(e.data,r);if(n.setProtocolVersion(this.currentProtocolVersion),n.parseMessage(),this.currentProtocolVersion=n.getProtocolVersion(),this.callbacks?.onCaptureSnapshot&&this.currentFrameIndex%this.snapshotInterval===0&&this.currentFrameIndex>0){let i=this.callbacks.onCaptureSnapshot(this.currentFrameIndex);i&&this.snapshots.set(this.currentFrameIndex,i)}}catch(r){return console.error("Error processing demo frame",r),this.callbacks?.onPlaybackError&&this.callbacks.onPlaybackError(r instanceof Error?r:new Error(String(r))),!1}return!0}getState(){return this.state}getCurrentTime(){return this.currentFrameIndex<0?this.accumulatedTime/1e3:(this.currentFrameIndex*this.frameDuration+this.accumulatedTime)/1e3}getFrameCount(){return this.reader?this.reader.getMessageCount():0}getTotalFrames(){return this.getFrameCount()}getCurrentFrame(){return this.currentFrameIndex<0?0:this.currentFrameIndex}getDuration(){return this.getFrameCount()*this.frameDuration/1e3}getTotalBytes(){return this.reader?this.reader.getProgress().total:0}getProcessedBytes(){return this.reader?this.reader.getOffset():0}getFrameData(e){if(e===this.currentFrameIndex&&this.lastFrameData)return this.lastFrameData;let r=this.state;return this.pause(),this.seek(e),r===1&&this.play(),this.lastFrameData}getFramePlayerState(e){if(e===this.currentFrameIndex&&this.handler?.getPlayerState){let n=this.handler.getPlayerState();if(n)return n}let r=this.getFrameData(e);return r?r.playerState:null}getFrameEntities(e){if(e===this.currentFrameIndex&&this.handler?.getEntities){let r=this.handler.getEntities();if(r)return Array.from(r.values())}if(this.seek(e),this.handler?.getEntities){let r=this.handler.getEntities();return r?Array.from(r.values()):[]}return[]}compareFrames(e,r){let n=this.getFramePlayerState(e),i=this.getFrameEntities(e),a=new Map;i.forEach(u=>a.set(u.number,u));let o=this.getFramePlayerState(r),s=this.getFrameEntities(r),c=new Map;s.forEach(u=>c.set(u.number,u));let l={frameA:e,frameB:r,playerStateDiff:{origin:null,viewangles:null,health:null,ammo:null},entityDiffs:{added:[],removed:[],moved:[]}};n&&o&&((n.origin.x!==o.origin.x||n.origin.y!==o.origin.y||n.origin.z!==o.origin.z)&&(l.playerStateDiff.origin={x:o.origin.x-n.origin.x,y:o.origin.y-n.origin.y,z:o.origin.z-n.origin.z}),n.stats[1]!==o.stats[1]&&(l.playerStateDiff.health=o.stats[1]-n.stats[1]),n.stats[2]!==o.stats[2]&&(l.playerStateDiff.ammo=o.stats[2]-n.stats[2]));for(let[u,d]of c){let f=a.get(u);f?(f.origin.x!==d.origin.x||f.origin.y!==d.origin.y||f.origin.z!==d.origin.z)&&l.entityDiffs.moved.push({id:u,delta:{x:d.origin.x-f.origin.x,y:d.origin.y-f.origin.y,z:d.origin.z-f.origin.z}}):l.entityDiffs.added.push(u)}for(let[u,d]of a)c.has(u)||l.entityDiffs.removed.push(u);return l}getEntityTrajectory(e,r,n){let i=[],a=this.getCurrentFrame();for(this.seek(r);this.getCurrentFrame()<=n&&this.state!==3;){let o=null;if(e===-1){let s=this.getFramePlayerState(this.getCurrentFrame());s&&(o={...s.origin})}else if(this.handler?.getEntities){let s=this.handler.getEntities().get(e);s&&(o={...s.origin})}if(o&&i.push(o),this.getCurrentFrame()===n)break;this.stepForward()}return this.seek(a),i}getEvents(){return this.ensureAnalysis(),this.cachedEvents||[]}getDemoEvents(){return this.getEvents()}filterEvents(e,r){return this.getDemoEvents().filter(i=>!(i.type!==e||r!==void 0&&i.entityId!==r))}getEventSummary(){return this.ensureAnalysis(),this.cachedSummary||{totalKills:0,totalDeaths:0,damageDealt:0,damageReceived:0,weaponUsage:new Map}}getMetadata(){let e=this.getDemoHeader();if(!e)return null;let r=this.getDemoServerInfo(),n="Unknown";return this.cachedConfigStrings,{mapName:e.levelName,playerName:n,serverName:r.hostname,demoVersion:e.protocolVersion,tickRate:e.tickRate||10}}getDemoHeader(){return this.ensureAnalysis(),this.cachedHeader}getDemoConfigStrings(){return this.ensureAnalysis(),this.cachedConfigStrings||new Map}getDemoServerInfo(){return this.ensureAnalysis(),this.cachedServerInfo||{}}getDemoStatistics(){return this.ensureAnalysis(),this.cachedStatistics}getPlayerStatistics(e){return this.ensureAnalysis(),this.cachedPlayerStats?.get(e)||null}getWeaponStatistics(e){return this.ensureAnalysis(),this.cachedWeaponStats?.get(e)||null}ensureAnalysis(){if(!this.cachedEvents&&this.buffer){let r=new Ka(this.buffer).analyze();this.cachedEvents=r.events,this.cachedSummary=r.summary,this.cachedHeader=r.header,this.cachedConfigStrings=r.configStrings,this.cachedServerInfo=r.serverInfo,this.cachedStatistics=r.statistics,this.cachedPlayerStats=r.playerStats,this.cachedWeaponStats=r.weaponStats}}setCameraMode(e){this.cameraMode=e}getCameraMode(){return this.cameraMode}setThirdPersonDistance(e){this.thirdPersonDistance=e}setThirdPersonOffset(e){this.thirdPersonOffset=e}async playWithTracking(e,r={}){if(this.tracker=e,e.startTracking(),r.fastForward)try{this.state===0&&this.reader,this.transitionState(1);let n=100,i=async()=>{if(this.state!==1)throw new Error("Playback stopped unexpectedly during fast forward");let a=0;for(;a<n;){if(!this.processNextFrame()){this.transitionState(0);let o=e.stopTracking();return this.tracker=null,this.callbacks?.onPlaybackComplete&&this.callbacks.onPlaybackComplete(),o}a++}return await new Promise(o=>setTimeout(o,0)),i()};return await i()}catch(n){throw this.transitionState(0),e.stopTracking(),this.tracker=null,n}else return new Promise((n,i)=>{let a=this.callbacks?.onPlaybackComplete,o=this.callbacks?.onPlaybackError,s=()=>{this.setCallbacks({...this.callbacks,onPlaybackComplete:a,onPlaybackError:o}),this.tracker=null};this.setCallbacks({...this.callbacks,onPlaybackComplete:()=>{let c=e.stopTracking();a&&a(),s(),n(c)},onPlaybackError:c=>{e.stopTracking(),o&&o(c),s(),i(c)}}),this.play()})}async playRangeWithTracking(e,r,n,i={}){this.tracker=n,n.startTracking();let a=e.type==="frame"?e.frame:this.timeToFrame(e.seconds),o=r.type==="frame"?r.frame:this.timeToFrame(r.seconds);if(i.fastForward)try{this.playFrom(e),this.transitionState(1);let s=100,c=async()=>{if(this.state!==1)throw new Error("Playback stopped unexpectedly during fast forward");let l=0;for(;l<s;){if(this.currentFrameIndex>=o||!this.processNextFrame()){this.transitionState(0);let u=n.stopTracking();return this.tracker=null,this.callbacks?.onPlaybackComplete&&this.callbacks.onPlaybackComplete(),u}l++}return await new Promise(u=>setTimeout(u,0)),c()};return await c()}catch(s){throw this.transitionState(0),n.stopTracking(),this.tracker=null,s}else return new Promise((s,c)=>{let l=this.callbacks?.onPlaybackComplete,u=this.callbacks?.onPlaybackError,d=()=>{this.setCallbacks({...this.callbacks,onPlaybackComplete:l,onPlaybackError:u}),this.tracker=null};this.setCallbacks({...this.callbacks,onPlaybackComplete:()=>{let f=n.stopTracking();l&&l(),d(),s(f)},onPlaybackError:f=>{n.stopTracking(),u&&u(f),d(),c(f)}}),this.playRange(e,r)})}};var Gs=class{constructor(){this.isRecording=!1;this.startTime=0;this.frameCount=0;this.filename=null;this.lastMessageSize=-1;this.messageBuffer=new oi(1024*1024)}startRecording(e,r=0){this.isRecording||(this.isRecording=!0,this.filename=e,this.startTime=r,this.frameCount=0,this.messageBuffer.reset(),console.log(`DemoRecorder: Started recording to ${e}`))}recordMessage(e){if(this.isRecording){this.messageBuffer.writeLong(e.byteLength);for(let r=0;r<e.length;r++)this.messageBuffer.writeByte(e[r]);this.frameCount++}}stopRecording(){return this.isRecording?(this.isRecording=!1,this.messageBuffer.writeLong(-1),console.log(`DemoRecorder: Stopped recording. Frames: ${this.frameCount}, Size: ${this.messageBuffer.getOffset()} bytes`),this.messageBuffer.getData()):null}getIsRecording(){return this.isRecording}};var Qc=class{constructor(e,r=34){this.writer=e||new oi(new Uint8Array(64*1024)),this.protocol=r}getData(){return this.writer.getData()}getOpcode(e){if(this.protocol===34)switch(e){case R.serverdata:return 13;case R.frame:return 5;case R.playerinfo:return 17;case R.packetentities:return 18;case R.deltapacketentities:return 19;case R.print:return 11;case R.centerprint:return 16;case R.stufftext:return 12;case R.sound:return 10;case R.temp_entity:return 9;case R.configstring:return 14;case R.spawnbaseline:return 15;case R.layout:return 7;case R.inventory:return 6;case R.muzzleflash:return 8;case R.muzzleflash2:return 20}return e}writeCommand(e,r){let n=r??this.protocol;n===34||n===0?this.writer.writeByte(this.getOpcode(e)):this.writer.writeByte(e)}writeServerData(e,r,n,i,a,o){this.writeCommand(R.serverdata),this.writer.writeLong(e),this.writer.writeLong(r),this.writer.writeByte(n),this.writer.writeString(i),this.writer.writeShort(a),this.writer.writeString(o)}writeConfigString(e,r){this.writeCommand(R.configstring),this.writer.writeShort(e),this.writer.writeString(r)}writeStuffText(e){this.writeCommand(R.stufftext),this.writer.writeString(e)}writeCenterPrint(e){this.writeCommand(R.centerprint),this.writer.writeString(e)}writePrint(e,r){this.writeCommand(R.print),this.writer.writeByte(e),this.writer.writeString(r)}writeLayout(e){this.writeCommand(R.layout),this.writer.writeString(e)}writeInventory(e){this.writeCommand(R.inventory);for(let r of e)this.writer.writeShort(r);for(let r=e.length;r<256;r++)this.writer.writeShort(0)}writeMuzzleFlash(e,r){this.writeCommand(R.muzzleflash),this.writer.writeShort(e),this.writer.writeByte(r)}writeMuzzleFlash2(e,r){this.writeCommand(R.muzzleflash2),this.writer.writeShort(e),this.writer.writeByte(r)}writeSound(e,r,n,i,a,o,s,c){this.writeCommand(R.sound),this.writer.writeByte(e),this.writer.writeByte(r),e&1&&this.writer.writeByte(n),e&2&&this.writer.writeByte(i),e&16&&this.writer.writeByte(a),e&8&&this.writer.writeShort(o),e&4&&(this.writer.writeCoord(s.x),this.writer.writeCoord(s.y),this.writer.writeCoord(s.z))}writeTempEntity(e,r,n,i,a,o,s,c,l){this.writeCommand(R.temp_entity),this.writer.writeByte(e),r&&this.writer.writePos(r)}writePlayerState(e){this.writeCommand(R.playerinfo);let r=0;e.pm_type!==0&&(r|=1),(e.origin.x!==0||e.origin.y!==0||e.origin.z!==0)&&(r|=2),(e.velocity.x!==0||e.velocity.y!==0||e.velocity.z!==0)&&(r|=4),e.pm_time!==0&&(r|=8),e.pm_flags!==0&&(r|=16),e.gravity!==0&&(r|=32),(e.delta_angles.x!==0||e.delta_angles.y!==0||e.delta_angles.z!==0)&&(r|=64),(e.viewoffset.x!==0||e.viewoffset.y!==0||e.viewoffset.z!==0)&&(r|=128),(e.viewangles.x!==0||e.viewangles.y!==0||e.viewangles.z!==0)&&(r|=256),(e.kick_angles.x!==0||e.kick_angles.y!==0||e.kick_angles.z!==0)&&(r|=512),e.gun_index!==0&&(r|=4096),(e.gun_frame!==0||e.gun_offset.x!==0||e.gun_offset.y!==0||e.gun_offset.z!==0||e.gun_angles.x!==0||e.gun_angles.y!==0||e.gun_angles.z!==0)&&(r|=8192),(e.blend[0]!==0||e.blend[1]!==0||e.blend[2]!==0||e.blend[3]!==0)&&(r|=1024),e.fov!==0&&(r|=2048),e.rdflags!==0&&(r|=16384),e.watertype!==0&&(r|=32768),this.writer.writeShort(r),r&1&&this.writer.writeByte(e.pm_type),r&2&&(this.writer.writeShort(e.origin.x/.125),this.writer.writeShort(e.origin.y/.125),this.writer.writeShort(e.origin.z/.125)),r&4&&(this.writer.writeShort(e.velocity.x/.125),this.writer.writeShort(e.velocity.y/.125),this.writer.writeShort(e.velocity.z/.125)),r&8&&this.writer.writeByte(e.pm_time),r&16&&this.writer.writeByte(e.pm_flags),r&32&&this.writer.writeShort(e.gravity),r&64&&(this.writer.writeShort(e.delta_angles.x/(180/32768)),this.writer.writeShort(e.delta_angles.y/(180/32768)),this.writer.writeShort(e.delta_angles.z/(180/32768))),r&128&&(this.writer.writeByte(e.viewoffset.x/.25),this.writer.writeByte(e.viewoffset.y/.25),this.writer.writeByte(e.viewoffset.z/.25)),r&256&&(this.writer.writeShort(e.viewangles.x/(360/65536)),this.writer.writeShort(e.viewangles.y/(360/65536)),this.writer.writeShort(e.viewangles.z/(360/65536))),r&512&&(this.writer.writeByte(e.kick_angles.x/.25),this.writer.writeByte(e.kick_angles.y/.25),this.writer.writeByte(e.kick_angles.z/.25)),r&4096&&this.writer.writeByte(e.gun_index),r&8192&&(this.writer.writeByte(e.gun_frame),this.writer.writeByte(e.gun_offset.x/.25),this.writer.writeByte(e.gun_offset.y/.25),this.writer.writeByte(e.gun_offset.z/.25),this.writer.writeByte(e.gun_angles.x/.25),this.writer.writeByte(e.gun_angles.y/.25),this.writer.writeByte(e.gun_angles.z/.25)),r&1024&&(this.writer.writeByte(e.blend[0]),this.writer.writeByte(e.blend[1]),this.writer.writeByte(e.blend[2]),this.writer.writeByte(e.blend[3])),r&2048&&this.writer.writeByte(e.fov),r&16384&&this.writer.writeByte(e.rdflags),r&32768&&this.writer.writeByte(e.watertype);let n=0;for(let i=0;i<32;i++)e.stats[i]!==0&&(n|=1<<i);this.writer.writeLong(n);for(let i=0;i<32;i++)n&1<<i&&this.writer.writeShort(e.stats[i])}writePacketEntities(e,r,n){this.writeCommand(r?R.deltapacketentities:R.packetentities);for(let i of e)this.writeDeltaEntity(Wr(),i,!0);this.writer.writeShort(0)}writeFrame(e,r){this.writeCommand(R.frame),this.writer.writeLong(e.serverFrame),this.writer.writeLong(e.deltaFrame),r!==26&&r!==25&&this.writer.writeByte(e.surpressCount),this.writer.writeByte(e.areaBytes),this.writer.writeBytes(e.areaBits),this.writePlayerState(e.playerState),this.writePacketEntities(e.packetEntities.entities,e.packetEntities.delta,r)}writeDeltaEntity(e,r,n){let i=0,a=0;(r.modelindex!==e.modelindex||n)&&(i|=Rt),(r.modelindex2!==e.modelindex2||n)&&(i|=Bt),(r.modelindex3!==e.modelindex3||n)&&(i|=Ft),(r.modelindex4!==e.modelindex4||n)&&(i|=It),(r.frame!==e.frame||n)&&(r.frame>=256?i|=Ct:i|=Et),(r.skinnum!==e.skinnum||n)&&(r.skinnum>=256?i|=Je:i|=Ze),(r.effects!==e.effects||n)&&(r.effects>=256?i|=Qe:i|=qe),(r.renderfx!==e.renderfx||n)&&(r.renderfx>=256?i|=je:i|=Ye),(r.origin.x!==e.origin.x||n)&&r.origin.x!==0&&(i|=St),(r.origin.y!==e.origin.y||n)&&r.origin.y!==0&&(i|=wt),(r.origin.z!==e.origin.z||n)&&r.origin.z!==0&&(i|=Tt),(r.angles.x!==e.angles.x||n)&&r.angles.x!==0&&(i|=Pt),(r.angles.y!==e.angles.y||n)&&r.angles.y!==0&&(i|=Mt),(r.angles.z!==e.angles.z||n)&&r.angles.z!==0&&(i|=At),(r.sound!==e.sound||n)&&(i|=Dt),(r.event!==e.event||n)&&(i|=Lt),(r.solid!==e.solid||n)&&(i|=kt),this.protocol!==34&&((r.alpha!==e.alpha||n)&&(i|=Ar),(r.scale!==e.scale||n)&&(i|=Tr),(r.instanceBits!==e.instanceBits||n)&&(i|=Pr),(r.loopVolume!==e.loopVolume||n)&&(i|=Rr),(r.loopAttenuation!==e.loopAttenuation||n)&&(a|=_n),(r.owner!==e.owner||n)&&(a|=Sn),(r.oldFrame!==e.oldFrame||n)&&(a|=wn)),a>0&&(i|=Ni),i&4278190080&&(i|=Lr),i&4294901760&&(i|=Er),i&4294967040&&(i|=Mr),this.writer.writeByte(i&255),i&Mr&&this.writer.writeByte(i>>8&255),i&Er&&this.writer.writeByte(i>>16&255),i&Lr&&this.writer.writeByte(i>>24&255),i&Ni&&this.writer.writeByte(a&255),r.number>=256?this.writer.writeShort(r.number):this.writer.writeByte(r.number),i&Rt&&this.writer.writeByte(r.modelindex),i&Bt&&this.writer.writeByte(r.modelindex2),i&Ft&&this.writer.writeByte(r.modelindex3),i&It&&this.writer.writeByte(r.modelindex4),i&Et&&this.writer.writeByte(r.frame),i&Ct&&this.writer.writeShort(r.frame),i&Ze&&this.writer.writeByte(r.skinnum),i&Je&&this.writer.writeShort(r.skinnum),i&qe&&this.writer.writeByte(r.effects),i&Qe&&this.writer.writeShort(r.effects),i&Ye&&this.writer.writeByte(r.renderfx),i&je&&this.writer.writeShort(r.renderfx),i&St&&this.writer.writeCoord(r.origin.x),i&wt&&this.writer.writeCoord(r.origin.y),i&Tt&&this.writer.writeCoord(r.origin.z),i&Pt&&this.writer.writeAngle(r.angles.x),i&Mt&&this.writer.writeAngle(r.angles.y),i&At&&this.writer.writeAngle(r.angles.z),i&Dt&&this.writer.writeByte(r.sound??0),i&Lt&&this.writer.writeByte(r.event??0),i&kt&&this.writer.writeShort(r.solid),this.protocol!==34&&(i&Ar&&this.writer.writeByte(r.alpha*255),i&Tr&&this.writer.writeFloat(r.scale),i&Pr&&this.writer.writeLong(r.instanceBits),i&Rr&&this.writer.writeByte(r.loopVolume*255),a&_n&&this.writer.writeByte(r.loopAttenuation*255),a&Sn&&this.writer.writeShort(r.owner),a&wn&&this.writer.writeShort(r.oldFrame))}};var Jc=class{static validate(e,r){if(r&&!r.toLowerCase().endsWith(".dm2"))return{valid:!1,error:"Invalid file extension (expected .dm2)"};if(e.byteLength<5)return{valid:!1,error:"File too small to be a valid demo"};let n=new DataView(e),i=n.getInt32(0,!0);if(i<=0||i>e.byteLength-4)return{valid:!1,error:`Invalid first block length: ${i}`};let a=n.getUint8(4);if(a!==R.serverdata)return{valid:!1,error:`First command is not svc_serverdata (expected ${R.serverdata}, got ${a})`};let o=-1;return i>=5&&(o=n.getInt32(5,!0)),{valid:!0,version:o}}};var eu=class{constructor(e){this.frames=[];this.configStrings=new Map;this.baselines=new Map;this.currentEntities=new Map;if(e){let r=new Qn(e.byteLength);r.append(new Uint8Array(e)),r.setReadPosition(0),this.parser=new xt(r,this)}else this.parser=new xt(new Qn,this)}extractClip(e,r,n,i){let a=new vr(e.buffer),o=[],s=0,c=r.frame??-1,l=n.frame??Number.MAX_SAFE_INTEGER,u=0,d=0;for(;a.nextBlock();){let p=a.getBlock().data,y=!1,v=-1,b=!1,x={onServerData:S=>{u=S,y=!0,b=!0},onConfigString:()=>{y=!0,b=!0},onSpawnBaseline:()=>{y=!0,b=!0},onFrame:S=>{v=S.serverFrame,b=!0,v>=c&&v<=l&&(y=!0)},onCenterPrint:()=>{b=!0},onStuffText:()=>{b=!0},onPrint:()=>{b=!0},onSound:()=>{b=!0},onTempEntity:()=>{b=!0},onLayout:()=>{b=!0},onInventory:()=>{b=!0},onMuzzleFlash:()=>{b=!0},onMuzzleFlash2:()=>{b=!0},onDisconnect:()=>{b=!0},onReconnect:()=>{b=!0},onDownload:()=>{b=!0}},_=new Qn(p.getLength());_.append(p.readData(p.getLength())),_.setReadPosition(0),p.seek(0);let w=new xt(_,x);u>0&&w.setProtocolVersion(u);try{w.parseMessage()}catch{}if(b||d>=c&&d<=l&&(y=!0),y){let S=new Uint8Array(4);new DataView(S.buffer).setUint32(0,p.getLength(),!0),o.push(S);let L=p.readData(p.getLength());o.push(L),s+=4+L.length}d++}let f=new Uint8Array(4);new DataView(f.buffer).setInt32(0,-1,!0),o.push(f),s+=4;let h=new Uint8Array(s),m=0;for(let g of o)h.set(g,m),m+=g.length;return h}extractDemoRange(e,r,n){return this.extractClip(e,{frame:r},{frame:n})}onServerData(e,r,n,i,a,o){this.serverData={protocol:e,serverCount:r,attractLoop:n,gameDir:i,playerNum:a,levelName:o}}onConfigString(e,r){this.configStrings.set(e,r)}onSpawnBaseline(e){this.baselines.set(e.number,e)}onFrame(e){this.frames.push(e)}onCenterPrint(e){}onStuffText(e){}onPrint(e,r){}onSound(e,r,n,i,a,o,s){}onTempEntity(e,r,n,i,a,o,s,c,l){}onLayout(e){}onInventory(e){}onMuzzleFlash(e,r){}onMuzzleFlash2(e,r){}onDisconnect(){}onReconnect(){}onDownload(e,r,n){}};function $0(t,e){let r=e.bits;t.bits=r,t.number=e.number,r&Rt&&(t.modelindex=e.modelindex),r&Bt&&(t.modelindex2=e.modelindex2),r&Ft&&(t.modelindex3=e.modelindex3),r&It&&(t.modelindex4=e.modelindex4),r&Et&&(t.frame=e.frame),r&Ct&&(t.frame=e.frame),r&Ze&&(t.skinnum=e.skinnum),r&Je&&(t.skinnum=e.skinnum),r&qe&&(t.effects=e.effects),r&Qe&&(t.effects=e.effects),r&Ye&&(t.renderfx=e.renderfx),r&je&&(t.renderfx=e.renderfx),r&St&&(t.origin.x=e.origin.x),r&wt&&(t.origin.y=e.origin.y),r&Tt&&(t.origin.z=e.origin.z),r&Pt&&(t.angles.x=e.angles.x),r&Mt&&(t.angles.y=e.angles.y),r&At&&(t.angles.z=e.angles.z),r&pr&&(t.old_origin.x=e.old_origin.x,t.old_origin.y=e.old_origin.y,t.old_origin.z=e.old_origin.z),r&Dt&&(t.sound=e.sound),r&Lt&&(t.event=e.event),r&kt&&(t.solid=e.solid),r&Ar&&(t.alpha=e.alpha),r&Tr&&(t.scale=e.scale),r&Pr&&(t.instanceBits=e.instanceBits),r&Rr&&(t.loopVolume=e.loopVolume)}var kf=(f=>(f.Unknown="unknown",f.BSP="bsp",f.MD2="md2",f.MD3="md3",f.WAL="wal",f.PCX="pcx",f.TGA="tga",f.WAV="wav",f.OGG="ogg",f.TXT="txt",f.CFG="cfg",f.DEM="dem",f))(kf||{}),K0={".bsp":"bsp",".md2":"md2",".md3":"md3",".wal":"wal",".pcx":"pcx",".tga":"tga",".wav":"wav",".ogg":"ogg",".txt":"txt",".cfg":"cfg",".dm2":"dem"};function Vs(t,e){if(t.length<e.length)return!1;for(let r=0;r<e.length;r++)if(t[r]!==e[r])return!1;return!0}var v2=[73,66,83,80],_2=[73,68,80,50],S2=[73,68,80,51];var w2=[82,73,70,70];var M2=[79,103,103,83];function Uf(t,e){let r=t.slice(t.lastIndexOf(".")).toLowerCase();if(e){if(Vs(e,v2))return"bsp";if(Vs(e,_2))return"md2";if(Vs(e,S2))return"md3";if(Vs(e,M2))return"ogg";if(e.length>128&&e[0]===10&&e[1]<6)return"pcx";if(Vs(e,w2)&&e.length>=12&&e[8]===87&&e[9]===65&&e[10]===86&&e[11]===69)return"wav"}return K0[r]?K0[r]:"unknown"}function zf(t){let e=Uf(t);return e==="txt"||e==="cfg"}function Y0(t){return!zf(t)}function A2(t,e,r,n,i){let a=new Uint8ClampedArray(n*i*4),o=e/n,s=r/i;for(let c=0;c<i;c++)for(let l=0;l<n;l++){let u=l*o,d=c*s,f=Math.floor(u),h=Math.floor(d),m=u-f,g=d-h,p=Math.min(f+1,e-1),y=Math.min(h+1,r-1),v=(h*e+f)*4,b=(h*e+p)*4,x=(y*e+f)*4,_=(y*e+p)*4,w=(c*n+l)*4;for(let S=0;S<4;S++){let A=t[v+S],L=t[b+S],M=t[x+S],P=t[_+S],I=A*(1-m)+L*m,D=M*(1-m)+P*m,B=I*(1-g)+D*g;a[w+S]=B}}return a}function E2(t,e,r,n,i,a,o,s,c,l,u){n=Math.floor(n),i=Math.floor(i),a=Math.floor(a),o=Math.floor(o);let d=Math.abs(a-n),f=Math.abs(o-i),h=n<a?1:-1,m=i<o?1:-1,g=d-f;for(;;){if(n>=0&&n<e&&i>=0&&i<r){let y=(i*e+n)*4,v=1-u/255;t[y]=s*(u/255)+t[y]*v,t[y+1]=c*(u/255)+t[y+1]*v,t[y+2]=l*(u/255)+t[y+2]*v,t[y+3]=255}if(n===a&&i===o)break;let p=2*g;p>-f&&(g-=f,n+=h),p<d&&(g+=d,i+=m)}}function q0(t,e,r,n,i){let s=(t.x-n.x)*.707-(t.y-n.y)*.707,c=(t.x-n.x)*.707+(t.y-n.y)*.707,l=t.z-n.z,u=.866,d=.5,f=c*u-l*d,h=c*d+l*u,m=e/2+s*i,g=r/2-h*i;return{x:m,y:g}}var tu=class{constructor(e){this.assetManager=e}async generateTextureThumbnail(e,r){try{let n=await this.assetManager.loadTexture(e);if(!n||n.levels.length===0)return null;let i=n.levels[0],a=i.width/i.height,o=r,s=r;a>1?s=Math.floor(r/a):o=Math.floor(r*a),o=Math.max(1,o),s=Math.max(1,s);let c=A2(i.rgba,i.width,i.height,o,s);return new ImageData(c,o,s)}catch(n){return console.error(`Failed to generate thumbnail for ${e}`,n),null}}async generateModelThumbnail(e,r){try{let n=[],i=[],a=e.split(".").pop()?.toLowerCase();if(a==="md2"){let p=await this.assetManager.loadMd2Model(e);if(!p||p.frames.length===0)return null;n=p.frames[0].vertices.map(v=>v.position);for(let v of p.triangles)i.push(v.vertexIndices[0],v.vertexIndices[1]),i.push(v.vertexIndices[1],v.vertexIndices[2]),i.push(v.vertexIndices[2],v.vertexIndices[0])}else if(a==="md3"){let p=await this.assetManager.loadMd3Model(e);if(!p||p.surfaces.length===0)return null;let y=0;for(let v of p.surfaces){if(v.vertices.length===0)continue;let b=v.vertices[0];n.push(...b.map(x=>({x:x.position.x,y:x.position.y,z:x.position.z})));for(let x of v.triangles)i.push(y+x.indices[0],y+x.indices[1]),i.push(y+x.indices[1],y+x.indices[2]),i.push(y+x.indices[2],y+x.indices[0]);y+=b.length}}else return null;if(n.length===0)return null;let o={x:1/0,y:1/0,z:1/0},s={x:-1/0,y:-1/0,z:-1/0};for(let p of n)o.x=Math.min(o.x,p.x),o.y=Math.min(o.y,p.y),o.z=Math.min(o.z,p.z),s.x=Math.max(s.x,p.x),s.y=Math.max(s.y,p.y),s.z=Math.max(s.z,p.z);let c={x:(o.x+s.x)/2,y:(o.y+s.y)/2,z:(o.z+s.z)/2},l=s.x-o.x,u=s.y-o.y,d=s.z-o.z,f=Math.max(l,u,d),h=Math.max(f,.001),m=r*.8/h,g=new Uint8ClampedArray(r*r*4);for(let p=0;p<i.length;p+=2){let y=i[p],v=i[p+1],b=n[y],x=n[v],_=q0(b,r,r,c,m),w=q0(x,r,r,c,m);E2(g,r,r,_.x,_.y,w.x,w.y,0,255,0,255)}return new ImageData(g,r,r)}catch(n){return console.error(`Failed to generate model thumbnail for ${e}`,n),null}}async getMapBounds(e,r){try{let n=lo(r);if(n.models.length>0){let i=n.models[0];return{mins:{x:i.mins[0],y:i.mins[1],z:i.mins[2]},maxs:{x:i.maxs[0],y:i.maxs[1],z:i.maxs[2]}}}return null}catch(n){return console.error("Failed to get map bounds",n),null}}async extractMapScreenshot(e){return null}};var ru=class{constructor(e){this.loader=e}async getMapStatistics(e){let r=await this.loader.load(e),n=r.faces.filter(o=>o.lightOffset!==-1).length,i=r.models[0],a=i?{mins:i.mins,maxs:i.maxs}:{mins:[0,0,0],maxs:[0,0,0]};return{entityCount:r.entities.entities.length,surfaceCount:r.faces.length,lightmapCount:n,vertexCount:r.vertices.length,bounds:a}}async getUsedTextures(e){let r=await this.loader.load(e),n=new Set;for(let i of r.texInfo)i.texture&&n.add(i.texture);return Array.from(n).sort()}async getUsedModels(e){let r=await this.loader.load(e),n=new Set;for(let i of r.entities.entities)i.properties.model&&!i.properties.model.startsWith("*")&&n.add(i.properties.model);return Array.from(n).sort()}async getUsedSounds(e){let r=await this.loader.load(e),n=new Set;for(let i of r.entities.entities){i.properties.noise&&n.add(i.properties.noise);for(let[a,o]of Object.entries(i.properties))(a==="noise"||a.endsWith("_sound")||a==="sound")&&typeof o=="string"&&n.add(o)}return Array.from(n).sort()}};function Z0(t){let e=[],r=0,n=t.length;function i(){for(;r<n&&/\s/.test(t[r]);)r++}function a(){if(i(),r>=n)return null;if(t[r]==='"'){r++;let o=r;for(;r<n&&t[r]!=='"';)t[r],r++;let s=t.substring(o,r);return r++,s}else{if(t[r]==="{"||t[r]==="}")return t[r++];{if(t.startsWith("//",r)){for(;r<n&&t[r]!==`
1121
1126
  `;)r++;return a()}let o=r;for(;r<n&&!/\s/.test(t[r])&&t[r]!=="}"&&t[r]!=="{";)r++;return t.substring(o,r)}}}for(;r<n;){let o=a();if(o===null)break;if(o==="{"){let s={};for(;;){let c=r,l=a();if(l==="}"||l===null)break;if(l==="{"){r=c;break}let u=a();if(u===null||u==="}"||u==="{"){u==="}"&&r--,u==="{"&&r--;break}s[l]=u}e.push({classname:s.classname,properties:s})}}return e}function j0(t){let e="";for(let r of t){e+=`{
1122
1127
  `;let i=Object.keys(r.properties).sort((a,o)=>a==="classname"?-1:o==="classname"?1:a==="origin"?-1:o==="origin"?1:a.localeCompare(o));for(let a of i){let o=r.properties[a];e+=`"${a}" "${o}"
1123
1128
  `}e+=`}
1124
- `}return e}function Q0(t){let e=[],r=[];if(t.properties.classname||e.push('Missing "classname" property'),t.properties.origin){let n=t.properties.origin.split(" ");(n.length!==3||n.some(i=>isNaN(parseFloat(i))))&&e.push(`Invalid origin format: "${t.properties.origin}"`)}return t.properties.angle&&isNaN(parseFloat(t.properties.angle))&&e.push(`Invalid angle format: "${t.properties.angle}"`),{valid:e.length===0,errors:e,warnings:r}}function J0(t,e,r,n="rgba8unorm"){let i=typeof GPUTextureUsage<"u"?GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC:17,a=t.createTexture({size:{width:e,height:r,depthOrArrayLayers:1},format:n,usage:i}),o=a.createView();return{texture:a,view:o,width:e,height:r}}async function eg(t,e){let r=e.width,n=e.height,i=4,a=r*i,o=256,s=Math.max(i*r,Math.ceil(r*i/o)*o),c=s*n,l=typeof GPUBufferUsage<"u"?GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ:9,u=t.createBuffer({size:c,usage:l}),d=t.createCommandEncoder();d.copyTextureToBuffer({texture:e},{buffer:u,bytesPerRow:s},{width:r,height:n,depthOrArrayLayers:1}),t.queue.submit([d.finish()]);let f=typeof GPUMapMode<"u"?GPUMapMode.READ:1;await u.mapAsync(f);let h=u.getMappedRange(),m=new Uint8Array(h),g=new Uint8ClampedArray(r*n*4);if(s===a)g.set(m);else for(let p=0;p<n;p++){let y=p*s,v=p*a;g.set(m.subarray(y,y+a),v)}return u.unmap(),g}var nu=class{constructor(e=800,r=600){this.width=0;this.height=0;this.collisionVis=null;this.debug=null;this.particleSystem=null;this.frameCount=0;this.callLog=[];this.width=e,this.height=r}renderFrame(e,r=[]){this.frameCount++,this.callLog.push(`renderFrame(frame=${this.frameCount}, entities=${r.length})`);let n=e.cameraState??e.camera.toState();this.callLog.push(` camera: pos=${n.position}, angles=${n.angles}`)}async registerPic(e,r){return this.callLog.push(`registerPic(${e})`),{width:256,height:256}}registerTexture(e,r){return this.callLog.push(`registerTexture(${e})`),{width:r.width,height:r.height}}begin2D(){this.callLog.push("begin2D()")}end2D(){this.callLog.push("end2D()")}drawPic(e,r,n,i){this.callLog.push(`drawPic(${e}, ${r})`)}drawString(e,r,n,i){this.callLog.push(`drawString(${e}, ${r}, "${n}")`)}drawCenterString(e,r){this.callLog.push(`drawCenterString(${e}, "${r}")`)}drawfillRect(e,r,n,i,a){this.callLog.push(`drawfillRect(${e}, ${r}, ${n}, ${i})`)}uploadBspGeometry(e){return this.callLog.push(`uploadBspGeometry(${e.faces.length})`),{surfaces:[],lightmaps:[]}}setEntityHighlight(e,r){}clearEntityHighlight(e){}highlightSurface(e,r){}removeSurfaceHighlight(e){}setDebugMode(e){}setBrightness(e){}setGamma(e){}setFullbright(e){}setAmbient(e){}setLightStyle(e,r){}setUnderwaterWarp(e){}setBloom(e){}setBloomIntensity(e){}setLodBias(e){}renderInstanced(e,r){}getPerformanceReport(){return{frameTimeMs:0,gpuTimeMs:0,cpuFrameTimeMs:0,drawCalls:0,triangles:0,vertices:0,textureBinds:0,shaderSwitches:0,visibleSurfaces:0,culledSurfaces:0,visibleEntities:0,culledEntities:0,memoryUsageMB:{textures:0,geometry:0,total:0}}}getMemoryUsage(){return{texturesBytes:0,geometryBytes:0,shadersBytes:0,buffersBytes:0,totalBytes:0}}dispose(){this.callLog.push("dispose()")}getCallLog(){return this.callLog}resetCallLog(){this.callLog=[]}getFrameCount(){return this.frameCount}};var iu=class{constructor(){this.coordinateSystem="opengl"}buildProjectionMatrix(e){let r=F.create();return F.perspective(r,e.fov*Ae,e.aspect,e.near,e.far),r}buildViewMatrix(e){let r=F.fromValues(0,0,-1,0,-1,0,0,0,0,1,0,0,0,0,0,1),[n,i,a]=e.angles,o=n*Ae,s=i*Ae,c=a*Ae,l=F.create();F.identity(l),F.rotateZ(l,l,-s),F.rotateY(l,l,-o),F.rotateX(l,l,-c);let u=F.create();F.multiply(u,r,l);let d=L.negate(L.create(),e.position),f=L.create();L.transformMat4(f,d,l);let h=L.fromValues(f[1]?-f[1]:0,f[2]||0,f[0]?-f[0]:0),m=F.clone(u);return m[12]=h[0],m[13]=h[1],m[14]=h[2],m}};var au=class{constructor(){this.coordinateSystem="quake"}buildProjectionMatrix(e){let r=F.create();return F.perspective(r,e.fov*Ae,e.aspect,e.near,e.far),r}buildViewMatrix(e){let[r,n,i]=e.angles,a=r*Ae,o=n*Ae,s=i*Ae,c=F.create();F.identity(c),F.rotateZ(c,c,o),F.rotateX(c,c,a),F.rotateY(c,c,s);let l=F.create();F.fromTranslation(l,[-e.position[0],-e.position[1],-e.position[2]]);let u=F.create();return F.multiply(u,c,l),u}};function tg(t,e){let r=t.buildViewMatrix(e),n=t.buildProjectionMatrix(e),i=F.create();return F.multiply(i,n,r),{view:r,projection:n,viewProjection:i}}function rg(t){return L.fromValues(-t[1],t[2],-t[0])}function ng(t){return L.fromValues(-t[1],t[2],-t[0])}var ou=class{constructor(e={}){this.width=0;this.height=0;this.collisionVis=null;this.debug=null;this.particleSystem=null;this.logs=[];switch(this.options={targetSystem:e.targetSystem??"quake",verbose:e.verbose??!0,validateTransforms:e.validateTransforms??!0},this.options.targetSystem){case"opengl":this.builder=new iu;break;case"webgpu":this.builder=new Ua;break;default:this.builder=new au}this.log(`LoggingRenderer initialized (target=${this.options.targetSystem})`)}renderFrame(e,r=[]){this.log(`
1129
+ `}return e}function Q0(t){let e=[],r=[];if(t.properties.classname||e.push('Missing "classname" property'),t.properties.origin){let n=t.properties.origin.split(" ");(n.length!==3||n.some(i=>isNaN(parseFloat(i))))&&e.push(`Invalid origin format: "${t.properties.origin}"`)}return t.properties.angle&&isNaN(parseFloat(t.properties.angle))&&e.push(`Invalid angle format: "${t.properties.angle}"`),{valid:e.length===0,errors:e,warnings:r}}function J0(t,e,r,n="rgba8unorm"){let i=typeof GPUTextureUsage<"u"?GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC:17,a=t.createTexture({size:{width:e,height:r,depthOrArrayLayers:1},format:n,usage:i}),o=a.createView();return{texture:a,view:o,width:e,height:r}}async function eg(t,e){let r=e.width,n=e.height,i=4,a=r*i,o=256,s=Math.max(i*r,Math.ceil(r*i/o)*o),c=s*n,l=typeof GPUBufferUsage<"u"?GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ:9,u=t.createBuffer({size:c,usage:l}),d=t.createCommandEncoder();d.copyTextureToBuffer({texture:e},{buffer:u,bytesPerRow:s},{width:r,height:n,depthOrArrayLayers:1}),t.queue.submit([d.finish()]);let f=typeof GPUMapMode<"u"?GPUMapMode.READ:1;await u.mapAsync(f);let h=u.getMappedRange(),m=new Uint8Array(h),g=new Uint8ClampedArray(r*n*4);if(s===a)g.set(m);else for(let p=0;p<n;p++){let y=p*s,v=p*a;g.set(m.subarray(y,y+a),v)}return u.unmap(),g}var nu=class{constructor(e=800,r=600){this.width=0;this.height=0;this.collisionVis=null;this.debug=null;this.particleSystem=null;this.frameCount=0;this.callLog=[];this.width=e,this.height=r}renderFrame(e,r=[]){this.frameCount++,this.callLog.push(`renderFrame(frame=${this.frameCount}, entities=${r.length})`);let n=e.cameraState??e.camera.toState();this.callLog.push(` camera: pos=${n.position}, angles=${n.angles}`)}async registerPic(e,r){return this.callLog.push(`registerPic(${e})`),{width:256,height:256}}registerTexture(e,r){return this.callLog.push(`registerTexture(${e})`),{width:r.width,height:r.height}}begin2D(){this.callLog.push("begin2D()")}end2D(){this.callLog.push("end2D()")}drawPic(e,r,n,i){this.callLog.push(`drawPic(${e}, ${r})`)}drawString(e,r,n,i){this.callLog.push(`drawString(${e}, ${r}, "${n}")`)}drawCenterString(e,r){this.callLog.push(`drawCenterString(${e}, "${r}")`)}drawfillRect(e,r,n,i,a){this.callLog.push(`drawfillRect(${e}, ${r}, ${n}, ${i})`)}uploadBspGeometry(e){return this.callLog.push(`uploadBspGeometry(${e.faces.length})`),{surfaces:[],lightmaps:[]}}setEntityHighlight(e,r){}clearEntityHighlight(e){}highlightSurface(e,r){}removeSurfaceHighlight(e){}setDebugMode(e){}setBrightness(e){}setGamma(e){}setFullbright(e){}setAmbient(e){}setLightStyle(e,r){}setUnderwaterWarp(e){}setBloom(e){}setBloomIntensity(e){}setLodBias(e){}renderInstanced(e,r){}getPerformanceReport(){return{frameTimeMs:0,gpuTimeMs:0,cpuFrameTimeMs:0,drawCalls:0,triangles:0,vertices:0,textureBinds:0,shaderSwitches:0,visibleSurfaces:0,culledSurfaces:0,visibleEntities:0,culledEntities:0,memoryUsageMB:{textures:0,geometry:0,total:0}}}getMemoryUsage(){return{texturesBytes:0,geometryBytes:0,shadersBytes:0,buffersBytes:0,totalBytes:0}}dispose(){this.callLog.push("dispose()")}getCallLog(){return this.callLog}resetCallLog(){this.callLog=[]}getFrameCount(){return this.frameCount}};var iu=class{constructor(){this.coordinateSystem="opengl"}buildProjectionMatrix(e){let r=F.create();return F.perspective(r,e.fov*Ae,e.aspect,e.near,e.far),r}buildViewMatrix(e){let r=F.fromValues(0,0,-1,0,-1,0,0,0,0,1,0,0,0,0,0,1),[n,i,a]=e.angles,o=n*Ae,s=i*Ae,c=a*Ae,l=F.create();F.identity(l),F.rotateZ(l,l,-s),F.rotateY(l,l,-o),F.rotateX(l,l,-c);let u=F.create();F.multiply(u,r,l);let d=T.negate(T.create(),e.position),f=T.create();T.transformMat4(f,d,l);let h=T.fromValues(f[1]?-f[1]:0,f[2]||0,f[0]?-f[0]:0),m=F.clone(u);return m[12]=h[0],m[13]=h[1],m[14]=h[2],m}};var au=class{constructor(){this.coordinateSystem="quake"}buildProjectionMatrix(e){let r=F.create();return F.perspective(r,e.fov*Ae,e.aspect,e.near,e.far),r}buildViewMatrix(e){let[r,n,i]=e.angles,a=r*Ae,o=n*Ae,s=i*Ae,c=F.create();F.identity(c),F.rotateZ(c,c,o),F.rotateX(c,c,a),F.rotateY(c,c,s);let l=F.create();F.fromTranslation(l,[-e.position[0],-e.position[1],-e.position[2]]);let u=F.create();return F.multiply(u,c,l),u}};function tg(t,e){let r=t.buildViewMatrix(e),n=t.buildProjectionMatrix(e),i=F.create();return F.multiply(i,n,r),{view:r,projection:n,viewProjection:i}}function rg(t){return T.fromValues(-t[1],t[2],-t[0])}function ng(t){return T.fromValues(-t[1],t[2],-t[0])}var ou=class{constructor(e={}){this.width=0;this.height=0;this.collisionVis=null;this.debug=null;this.particleSystem=null;this.logs=[];switch(this.options={targetSystem:e.targetSystem??"quake",verbose:e.verbose??!0,validateTransforms:e.validateTransforms??!0},this.options.targetSystem){case"opengl":this.builder=new iu;break;case"webgpu":this.builder=new Ua;break;default:this.builder=new au}this.log(`LoggingRenderer initialized (target=${this.options.targetSystem})`)}renderFrame(e,r=[]){this.log(`
1125
1130
  === FRAME START ===`);let n=e.cameraState??e.camera.toState();this.log("Camera State:"),this.log(` Position: ${this.formatVec3(n.position)} (Quake space)`),this.log(` Angles: ${this.formatVec3(n.angles)} (degrees)`),this.log(` FOV: ${n.fov}\xB0, Aspect: ${n.aspect.toFixed(2)}`);let i=tg(this.builder,n);this.log(`Matrices (${this.options.targetSystem}):`),this.options.verbose&&(this.log(" View Matrix:"),this.logMatrix(i.view),this.log(" Projection Matrix:"),this.logMatrix(i.projection)),this.options.validateTransforms&&this.validateCoordinateTransforms(n,i.view),this.log(`Entities: ${r.length}`),this.options.verbose&&r.length>0&&(r.slice(0,5).forEach((a,o)=>{this.log(` [${o}] type=${a.type}, model=${a.model??"none"}`)}),r.length>5&&this.log(` ... and ${r.length-5} more`)),this.log(`=== FRAME END ===
1126
1131
  `)}validateCoordinateTransforms(e,r){let n=e.position,i=rg(n),a=ng(n),o=[r[12],r[13],r[14]];switch(this.log("Transform Validation:"),this.log(` Quake position: ${this.formatVec3(n)}`),this.options.targetSystem){case"opengl":this.log(` Expected GL transform: ${this.formatVec3(i)}`);break;case"webgpu":this.log(` Expected WebGPU transform: ${this.formatVec3(a)}`);break}this.log(` Matrix translation: [${o.map(l=>l.toFixed(2)).join(", ")}]`);let s=Math.abs(n[0])+Math.abs(n[1])+Math.abs(n[2]),c=Math.abs(o[0])+Math.abs(o[1])+Math.abs(o[2]);s>0&&c/s>2&&this.log(" \u26A0\uFE0F WARNING: Matrix translation seems large relative to input - possible double-transform!")}formatVec3(e){return`[${e[0].toFixed(2)}, ${e[1].toFixed(2)}, ${e[2].toFixed(2)}]`}logMatrix(e){for(let r=0;r<4;r++){let n=[e[r],e[r+4],e[r+8],e[r+12]];this.log(` [${n.map(i=>i.toFixed(4).padStart(8)).join(" ")}]`)}}log(e){this.logs.push(e),this.options.verbose&&console.log(`[LogRenderer] ${e}`)}async registerPic(e,r){return this.log(`registerPic("${e}", ${r.byteLength} bytes)`),{width:256,height:256}}registerTexture(e,r){return this.log(`registerTexture("${e}", ${r.width}x${r.height})`),{width:r.width,height:r.height}}begin2D(){this.log("begin2D()")}end2D(){this.log("end2D()")}drawPic(e,r,n,i){this.log(`drawPic(${e}, ${r})`)}drawString(e,r,n,i){this.log(`drawString(${e}, ${r}, "${n}")`)}drawCenterString(e,r){this.log(`drawCenterString(${e}, "${r}")`)}drawfillRect(e,r,n,i,a){this.log(`drawfillRect(${e}, ${r}, ${n}x${i})`)}uploadBspGeometry(e){return this.log(`uploadBspGeometry(map with ${e.faces.length} faces)`),{surfaces:[],lightmaps:[]}}setEntityHighlight(e,r){}clearEntityHighlight(e){}highlightSurface(e,r){}removeSurfaceHighlight(e){}setDebugMode(e){}setBrightness(e){}setGamma(e){}setFullbright(e){}setAmbient(e){}setLightStyle(e,r){}setUnderwaterWarp(e){}setBloom(e){}setBloomIntensity(e){}setLodBias(e){}renderInstanced(e,r){}getPerformanceReport(){return{frameTimeMs:0,gpuTimeMs:0,cpuFrameTimeMs:0,drawCalls:0,triangles:0,vertices:0,textureBinds:0,shaderSwitches:0,visibleSurfaces:0,culledSurfaces:0,visibleEntities:0,culledEntities:0,memoryUsageMB:{textures:0,geometry:0,total:0}}}getMemoryUsage(){return{texturesBytes:0,geometryBytes:0,shadersBytes:0,buffersBytes:0,totalBytes:0}}dispose(){this.log("dispose()")}getLogs(){return this.logs}resetLogs(){this.logs=[]}printLogs(){console.log(this.logs.join(`
1127
- `))}};var Of=(o=>(o[o.Disconnected=0]="Disconnected",o[o.Connecting=1]="Connecting",o[o.Challenge=2]="Challenge",o[o.Connected=3]="Connected",o[o.Loading=4]="Loading",o[o.Active=5]="Active",o))(Of||{}),su=class{constructor(e){this.state=0;this.parser=null;this.listeners={};this.serverProtocol=0;this.serverCount=0;this.gameDir="";this.playerNum=0;this.levelName="";this.configStrings=new Map;this.baselines=new Map;this.entities=new Map;this.latestServerFrame=0;this.frameCRCs=new Map;this.currentPacketCRC=0;this.commandHistory=[];this.options=e,this.netchan=e.netchan??new oh}on(e,r){this.listeners[e]||(this.listeners[e]=[]),this.listeners[e].push(r)}off(e,r){this.listeners[e]&&(this.listeners[e]=this.listeners[e].filter(n=>n!==r))}emit(e,...r){this.listeners[e]&&this.listeners[e].forEach(n=>n(...r))}connect(){this.netchan.reset(),this.cleanup(),this.setState(1)}startProtocol(){this.state!==1&&this.connect(),this.setState(2),this.sendChallenge()}disconnect(){this.state!==0&&(this.setState(0),this.emit("disconnect"),this.cleanup())}cleanup(){this.configStrings.clear(),this.baselines.clear(),this.entities.clear(),this.commandHistory=[],this.latestServerFrame=0,this.parser=null,this.frameCRCs.clear()}getState(){return this.state}setState(e){this.state!==e&&(this.state=e,this.emit("state",e))}handleMessage(e){let r=this.netchan.process(new Uint8Array(e));if(!r||r.byteLength===0)return;this.currentPacketCRC=ah(r);let n=new Mn(r.buffer);this.parser=new xt(n,this),this.serverProtocol&&this.parser.setProtocolVersion(this.serverProtocol),this.parser.parseMessage()}sendUserCommand(e){if(this.state!==5)return;let r={...e,serverFrame:e.serverFrame??this.latestServerFrame};this.commandHistory.push(r),this.commandHistory.length>nh&&this.commandHistory.shift();let n=new oi;n.writeByte(ii.move);let i=this.frameCRCs.get(this.latestServerFrame)||0;n.writeByte(i),n.writeLong(this.latestServerFrame),ih(n,r),this.transmit(n.getData())}transmit(e){let r=this.netchan.transmit(e);this.emit("send",r)}sendChallenge(){let e=new no;e.writeByte(ii.stringcmd),e.writeString("getchallenge"),this.transmit(e.getData())}sendConnect(e){let r=new no;r.writeByte(ii.stringcmd);let n=`\\name\\${this.options.username}\\model\\${this.options.model}\\skin\\${this.options.skin}\\hand\\${this.options.hand??0}\\fov\\${this.options.fov??90}`;r.writeString(`connect ${Xr} ${e} ${n}`),this.transmit(r.getData())}sendNew(){let e=new no;e.writeByte(ii.stringcmd),e.writeString("new"),this.transmit(e.getData())}sendBegin(){let e=new no;e.writeByte(ii.stringcmd),e.writeString("begin"),this.transmit(e.getData())}onServerData(e,r,n,i,a,o){this.serverProtocol=e,this.serverCount=r,this.gameDir=i,this.playerNum=a,this.levelName=o,this.setState(3),this.emit("serverdata",{protocol:e,serverCount:r,gameDir:i,levelName:o}),this.sendNew(),this.setState(4)}onConfigString(e,r){this.configStrings.set(e,r)}onSpawnBaseline(e){this.baselines.set(e.number,e)}onStuffText(e){if(this.emit("stufftext",e),e.startsWith("precache")&&(this.sendBegin(),this.setState(5)),e.startsWith("challenge ")){let r=e.split(" ");if(r.length>1){let n=parseInt(r[1],10);this.sendConnect(n)}}}onFrame(e){e.serverFrame>this.latestServerFrame&&(this.latestServerFrame=e.serverFrame),this.frameCRCs.set(e.serverFrame,this.currentPacketCRC);let r=e.packetEntities;r.delta||this.entities.clear();for(let n of r.entities)this.entities.set(n.number,n);this.emit("frame",e)}onDisconnect(){this.disconnect()}onPrint(e,r){this.emit("print",r,e)}onCenterPrint(e){this.emit("centerprint",e)}onSound(e,r,n,i,a,o,s){this.emit("sound",{flags:e,soundNum:r,volume:n,attenuation:i,offset:a,ent:o,pos:s})}onTempEntity(e,r,n,i,a,o,s,c,l){this.emit("temp_entity",{type:e,pos:r,pos2:n,dir:i,cnt:a,color:o,ent:s})}onInventory(e){this.emit("inventory",e)}onMuzzleFlash(e,r){this.emit("muzzleflash",e,r)}onMuzzleFlash2(e,r){}onMuzzleFlash3(e,r){this.emit("muzzleflash",e,r)}onDownload(e,r,n){this.emit("download",e,r,n)}onReconnect(){}onLayout(e){}onSplitClient(e){}onConfigBlast(e,r){}onSpawnBaselineBlast(e){}onLevelRestart(){}onDamage(e){}onLocPrint(e,r,n){}onFog(e){}onWaitingForPlayers(e){}onBotChat(e){}onPoi(e,r){}onHelpPath(e){}onAchievement(e){}};function T2(t){return{init(){t.trace({x:0,y:0,z:0},{x:0,y:0,z:0})},shutdown(){},createMainLoop(e,r){return new ri(e,r)},setAreaPortalState(e,r){t.renderer&&t.renderer.setAreaPortalState&&t.renderer.setAreaPortalState(e,r)}}}return gg(L2);})();
1132
+ `))}};var Of=(o=>(o[o.Disconnected=0]="Disconnected",o[o.Connecting=1]="Connecting",o[o.Challenge=2]="Challenge",o[o.Connected=3]="Connected",o[o.Loading=4]="Loading",o[o.Active=5]="Active",o))(Of||{}),su=class{constructor(e){this.state=0;this.parser=null;this.listeners={};this.serverProtocol=0;this.serverCount=0;this.gameDir="";this.playerNum=0;this.levelName="";this.configStrings=new Map;this.baselines=new Map;this.entities=new Map;this.latestServerFrame=0;this.frameCRCs=new Map;this.currentPacketCRC=0;this.commandHistory=[];this.options=e,this.netchan=e.netchan??new oh}on(e,r){this.listeners[e]||(this.listeners[e]=[]),this.listeners[e].push(r)}off(e,r){this.listeners[e]&&(this.listeners[e]=this.listeners[e].filter(n=>n!==r))}emit(e,...r){this.listeners[e]&&this.listeners[e].forEach(n=>n(...r))}connect(){this.netchan.reset(),this.cleanup(),this.setState(1)}startProtocol(){this.state!==1&&this.connect(),this.setState(2),this.sendChallenge()}disconnect(){this.state!==0&&(this.setState(0),this.emit("disconnect"),this.cleanup())}cleanup(){this.configStrings.clear(),this.baselines.clear(),this.entities.clear(),this.commandHistory=[],this.latestServerFrame=0,this.parser=null,this.frameCRCs.clear()}getState(){return this.state}setState(e){this.state!==e&&(this.state=e,this.emit("state",e))}handleMessage(e){let r=this.netchan.process(new Uint8Array(e));if(!r||r.byteLength===0)return;this.currentPacketCRC=ah(r);let n=new Mn(r.buffer);this.parser=new xt(n,this),this.serverProtocol&&this.parser.setProtocolVersion(this.serverProtocol),this.parser.parseMessage()}sendUserCommand(e){if(this.state!==5)return;let r={...e,serverFrame:e.serverFrame??this.latestServerFrame};this.commandHistory.push(r),this.commandHistory.length>nh&&this.commandHistory.shift();let n=new oi;n.writeByte(ii.move);let i=this.frameCRCs.get(this.latestServerFrame)||0;n.writeByte(i),n.writeLong(this.latestServerFrame),ih(n,r),this.transmit(n.getData())}transmit(e){let r=this.netchan.transmit(e);this.emit("send",r)}sendChallenge(){let e=new no;e.writeByte(ii.stringcmd),e.writeString("getchallenge"),this.transmit(e.getData())}sendConnect(e){let r=new no;r.writeByte(ii.stringcmd);let n=`\\name\\${this.options.username}\\model\\${this.options.model}\\skin\\${this.options.skin}\\hand\\${this.options.hand??0}\\fov\\${this.options.fov??90}`;r.writeString(`connect ${Xr} ${e} ${n}`),this.transmit(r.getData())}sendNew(){let e=new no;e.writeByte(ii.stringcmd),e.writeString("new"),this.transmit(e.getData())}sendBegin(){let e=new no;e.writeByte(ii.stringcmd),e.writeString("begin"),this.transmit(e.getData())}onServerData(e,r,n,i,a,o){this.serverProtocol=e,this.serverCount=r,this.gameDir=i,this.playerNum=a,this.levelName=o,this.setState(3),this.emit("serverdata",{protocol:e,serverCount:r,gameDir:i,levelName:o}),this.sendNew(),this.setState(4)}onConfigString(e,r){this.configStrings.set(e,r)}onSpawnBaseline(e){this.baselines.set(e.number,e)}onStuffText(e){if(this.emit("stufftext",e),e.startsWith("precache")&&(this.sendBegin(),this.setState(5)),e.startsWith("challenge ")){let r=e.split(" ");if(r.length>1){let n=parseInt(r[1],10);this.sendConnect(n)}}}onFrame(e){e.serverFrame>this.latestServerFrame&&(this.latestServerFrame=e.serverFrame),this.frameCRCs.set(e.serverFrame,this.currentPacketCRC);let r=e.packetEntities;r.delta||this.entities.clear();for(let n of r.entities)this.entities.set(n.number,n);this.emit("frame",e)}onDisconnect(){this.disconnect()}onPrint(e,r){this.emit("print",r,e)}onCenterPrint(e){this.emit("centerprint",e)}onSound(e,r,n,i,a,o,s){this.emit("sound",{flags:e,soundNum:r,volume:n,attenuation:i,offset:a,ent:o,pos:s})}onTempEntity(e,r,n,i,a,o,s,c,l){this.emit("temp_entity",{type:e,pos:r,pos2:n,dir:i,cnt:a,color:o,ent:s})}onInventory(e){this.emit("inventory",e)}onMuzzleFlash(e,r){this.emit("muzzleflash",e,r)}onMuzzleFlash2(e,r){}onMuzzleFlash3(e,r){this.emit("muzzleflash",e,r)}onDownload(e,r,n){this.emit("download",e,r,n)}onReconnect(){}onLayout(e){}onSplitClient(e){}onConfigBlast(e,r){}onSpawnBaselineBlast(e){}onLevelRestart(){}onDamage(e){}onLocPrint(e,r,n){}onFog(e){}onWaitingForPlayers(e){}onBotChat(e){}onPoi(e,r){}onHelpPath(e){}onAchievement(e){}};function L2(t){return{init(){t.trace({x:0,y:0,z:0},{x:0,y:0,z:0})},shutdown(){},createMainLoop(e,r){return new ri(e,r)},setAreaPortalState(e,r){t.renderer&&t.renderer.setAreaPortalState&&t.renderer.setAreaPortalState(e,r)}}}return gg(T2);})();
1128
1133
  /*! Bundled license information:
1129
1134
 
1130
1135
  pako/dist/pako.esm.mjs: