minecraft-renderer 0.1.52 → 0.1.53
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/minecraft-renderer.js +2 -2
- package/dist/minecraft-renderer.js.meta.json +1 -1
- package/dist/threeWorker.js +2 -2
- package/package.json +1 -1
- package/src/graphicsBackend/rendererDefaultOptions.ts +9 -2
- package/src/graphicsBackend/rendererOptionsSync.ts +1 -0
- package/src/three/modules/rain.ts +2 -1
|
@@ -282,7 +282,7 @@ void main() {
|
|
|
282
282
|
applyFog();
|
|
283
283
|
writeLogDepth();
|
|
284
284
|
}
|
|
285
|
-
`;tr=6,ht={LX_BITS:4,LY_BITS:4,LZ_BITS:4,FACE_BITS:3,TINT_BITS:8,AO_BITS_PER_CORNER:2,NUM_CORNERS:4,LX_SHIFT:0,LY_SHIFT:4,LZ_SHIFT:8,FACE_SHIFT:12,TINT_SHIFT:15,AO_SHIFT:23,TRANSPARENT_SHIFT:31},K3={TEX_INDEX_BITS:12,DIAGONAL_FLAG_SHIFT:12,SECTION_Y_SHIFT:13,SECTION_Y_BITS:5,EMPTY_SHIFT:18,SPARE_BITS:13}});var rr,J3=ee(()=>{"use strict";E();x();k();R();rr=class{constructor(e){u(this,"atlasWidth");u(this,"atlasHeight");u(this,"tileSize");u(this,"tilesPerRow");u(this,"maxTiles");u(this,"valid");this.atlasWidth=e.width,this.atlasHeight=e.height,this.tileSize=e.tileSize,this.tilesPerRow=Math.floor(this.atlasWidth/this.tileSize),this.maxTiles=this.tilesPerRow*Math.floor(this.atlasHeight/this.tileSize),this.valid=this.atlasWidth===1024&&this.atlasHeight===1024&&this.tileSize===16&&this.maxTiles<=4096}isValid(){return this.valid}getTilesPerRow(){return this.tilesPerRow}tileIndexFromPixelCoords(e,t){if(!this.valid)return-1;let r=Math.floor(e/this.tileSize),i=Math.floor(t/this.tileSize);if(r<0||r>=this.tilesPerRow||i<0)return-1;let s=i*this.tilesPerRow+r;return s>=this.maxTiles?-1:s}tileIndexFromTextureEntry(e){return!this.valid||e.su!==this.tileSize||e.sv!==this.tileSize?-1:this.tileIndexFromPixelCoords(e.u,e.v)}tileIndexFromTextureName(e,t){if(!this.valid)return-1;let r=t.textures[e];if(!r&&e.includes(":")&&(r=t.textures[e.split(":")[1]]),!r&&e.includes("/")&&(r=t.textures[e.split("/")[1]]),r||(r=t.textures[`block/${e}`]),!r){let i=e.replace(/^block\//,"");r=t.textures[i]}return r?this.tileIndexFromTextureEntry(r):-1}}});import*as de from"three";var ir,q3=ee(()=>{"use strict";E();x();k();R();ir=class n{constructor(){u(this,"entries",[{r:1,g:1,b:1}]);u(this,"colorToIndex",new Map);u(this,"categoryBiomeToIndex",new Map);u(this,"texture",null);u(this,"ready",!1)}packColor(e,t,r){let i=Math.round(e*255),s=Math.round(t*255),o=Math.round(r*255);return i<<16|s<<8|o}add(e,t,r,i,s){let o=this.packColor(e,t,r),a=`${i}:${s}`,v=this.categoryBiomeToIndex.get(a);if(v!==void 0)return v;let l=this.colorToIndex.get(o);if(l!==void 0)return this.categoryBiomeToIndex.set(a,l),l;let c=this.entries.length;return this.entries.push({r:e,g:t,b:r}),this.colorToIndex.set(o,c),this.categoryBiomeToIndex.set(a,c),c}getTintIndex(e,t,r,i){return e===void 0?0:e===0?t==="redstone_wire"?this.categoryBiomeToIndex.get(`redstone:${r.power}`)??this.categoryBiomeToIndex.get("redstone:0")??0:t==="birch_leaves"||t==="spruce_leaves"||t==="lily_pad"?this.categoryBiomeToIndex.get(`constant:${t}`)??this.categoryBiomeToIndex.get("constant:default")??0:t.includes("leaves")||t==="vine"?this.categoryBiomeToIndex.get(`foliage:${i}`)??this.categoryBiomeToIndex.get("foliage:plains")??0:this.categoryBiomeToIndex.get(`grass:${i}`)??this.categoryBiomeToIndex.get("grass:plains")??0:0}getEntry(e){return this.entries[e]??this.entries[0]}get size(){return this.entries.length}buildTextureData(){let e=new Float32Array(1024);for(let t=0;t<this.entries.length&&t<256;t++){let r=this.entries[t];e[t*4]=r.r,e[t*4+1]=r.g,e[t*4+2]=r.b,e[t*4+3]=1}return e}createTexture(){this.texture&&(this.texture.dispose(),this.texture=null,this.ready=!1);let e=this.buildTextureData(),t=new de.DataTexture(e,256,1,de.RGBAFormat,de.FloatType);return t.minFilter=de.NearestFilter,t.magFilter=de.NearestFilter,t.wrapS=de.ClampToEdgeWrapping,t.wrapT=de.ClampToEdgeWrapping,t.needsUpdate=!0,this.texture=t,this.ready=!0,t}getTexture(){return this.texture}isReady(){return this.ready}static fromTintsData(e){let t=new n;function r(i){let s=(i>>16&255)/255,o=(i>>8&255)/255,a=(i&255)/255;return[s,o,a]}if(e.grass){let i=r(e.grass.default);for(let{keys:s,color:o}of e.grass.data??[]){let a=r(o);for(let v of s)t.add(a[0],a[1],a[2],"grass",v)}t.add(i[0],i[1],i[2],"grass","plains")}if(e.foliage){let i=r(e.foliage.default);for(let{keys:s,color:o}of e.foliage.data??[]){let a=r(o);for(let v of s)t.add(a[0],a[1],a[2],"foliage",v)}t.add(i[0],i[1],i[2],"foliage","plains")}if(e.redstone){let i=r(e.redstone.default);for(let{keys:s,color:o}of e.redstone.data??[]){let a=r(o);for(let v of s)t.add(a[0],a[1],a[2],"redstone",v)}t.add(i[0],i[1],i[2],"redstone","0")}if(e.constant){let i=r(e.constant.default);for(let{keys:s,color:o}of e.constant.data??[]){let a=r(o);for(let v of s)t.add(a[0],a[1],a[2],"constant",v)}t.add(i[0],i[1],i[2],"constant","default")}return t}}});import Z3 from"mc-assets/dist/blocksAtlases.json";function Av(){let n=globalThis.loadedData?.tints;if(!n)throw new Error("shaderCubeBridge: globalThis.loadedData.tints is not available yet");return n}function or(){if(nr||(nr=ir.fromTintsData(Av()),nr.createTexture()),!Gi){let n=Z3.latest??Z3;Gi=new rr({width:n.width,height:n.height,tileSize:n.tileSize??16,suSv:n.suSv??16,textures:n.textures??{}})}return{tintPalette:nr,textureIndexMapping:Gi}}function X3(){return 1<<K3.EMPTY_SHIFT>>>0}var sr,nr,Gi,Qt=ee(()=>{"use strict";E();x();k();R();mt();J3();q3();sr=4,nr=null,Gi=null});import*as B0 from"three";function Ev(n,e){let t=new B0.InstancedBufferGeometry,r=new Float32Array(tr*3);t.setAttribute("position",new B0.BufferAttribute(r,3));let i=new Uint32Array(e),s=new Uint32Array(e),o=new Uint32Array(e),a=new Uint32Array(e),v=sr;for(let l=0;l<e;l++)i[l]=n[l*v],s[l]=n[l*v+1],o[l]=n[l*v+2],a[l]=n[l*v+3];return t.setAttribute("a_w0",new B0.InstancedBufferAttribute(i,1)),t.setAttribute("a_w1",new B0.InstancedBufferAttribute(s,1)),t.setAttribute("a_w2",new B0.InstancedBufferAttribute(o,1)),t.setAttribute("a_w3",new B0.InstancedBufferAttribute(a,1)),t.instanceCount=e,t.boundingBox=new B0.Box3(new B0.Vector3(-8,-8,-8),new B0.Vector3(8,8,8)),t.boundingSphere=new B0.Sphere(new B0.Vector3(0,0,0),Math.sqrt(3*8**2)),t}function xv(n){n.raycast=(e,t)=>{let{geometry:r}=n;if(!r.boundingBox||($3.copy(r.boundingBox).applyMatrix4(n.matrixWorld),!e.ray.intersectBox($3,Ni)))return;let i=e.ray.origin.distanceTo(Ni);t.push({distance:i,point:Ni.clone(),object:n})}}function ar(n,e){let t=Ev(n.words,n.count),r=new B0.Mesh(t,e);return r.name="shaderMesh",r.matrixAutoUpdate=!1,r.frustumCulled=!1,xv(r),r}function Wi(n){n.geometry.dispose()}var $3,Ni,Vi=ee(()=>{"use strict";E();x();k();R();mt();Qt();$3=new B0.Box3,Ni=new B0.Vector3});var sa={};Z5(sa,{applyWorldGeometryExport:()=>Tv,createMeshesFromExport:()=>ia,downloadWorldGeometry:()=>ji,exportWorldGeometry:()=>ta,loadTextureFromDataUrl:()=>na,loadWorldGeometryFromUrl:()=>Rv});import*as P0 from"three";function ta(n,e,t,r=!1){let i=[];for(let[o,a]of Object.entries(n.sectionObjects)){let v=a.children.find(w=>w.name==="mesh");if(!v?.geometry)continue;let{geometry:l}=v,c=l.getAttribute("position"),d=l.getAttribute("normal"),f=l.getAttribute("color"),m=l.getAttribute("uv"),g=l.index;if(!c||!g)continue;let b=n.sceneOrigin.getWorldPosition(v);i.push({key:o,position:{x:b?.x??n.sceneOrigin.toWorldX(v.position.x),y:b?.y??n.sceneOrigin.toWorldY(v.position.y),z:b?.z??n.sceneOrigin.toWorldZ(v.position.z)},geometry:{positions:[...c.array],normals:d?[...d.array]:[],colors:f?[...f.array]:[],uvs:m?[...m.array]:[],indices:[...g.array]}})}let s={version:n.version??"unknown",exportedAt:new Date().toISOString(),camera:{position:e,rotation:t},sections:i};if(r&&n.material.map){let o=document.createElement("canvas"),a=n.material.map,{image:v}=a;v&&(o.width=v.width,o.height=v.height,o.getContext("2d").drawImage(v,0,0),s.textureAtlasDataUrl=o.toDataURL("image/png"))}return s}function ji(n,e,t,r="world-geometry.json",i=!1){let s=ta(n,e,t,i),o=JSON.stringify(s),a=new Blob([o],{type:"application/json"}),v=URL.createObjectURL(a),l=document.createElement("a");l.href=v,l.download=r,l.click(),URL.revokeObjectURL(v)}async function Rv(n){let e=await fetch(n);if(!e.ok)throw new Error(`Failed to fetch world geometry: ${e.statusText}`);return e.json()}function ra(n){let e=n.map??n.map;if(!e)return null;let t=er();t.uniforms.u_atlas.value=e;let{tintPalette:r}=or();return r.isReady()||r.createTexture(),t.uniforms.u_tintPalette.value=r.getTexture(),t}function ia(n,e,t){let r=[],i=t??ra(e);for(let s of n.sections){let o=new P0.Group;if(o.name="chunk",s.geometry.positions.length>0&&s.geometry.indices.length>0){let l=new P0.BufferGeometry;l.setAttribute("position",new P0.Float32BufferAttribute(s.geometry.positions,3)),s.geometry.normals.length&&l.setAttribute("normal",new P0.Float32BufferAttribute(s.geometry.normals,3)),s.geometry.colors.length&&l.setAttribute("color",new P0.Float32BufferAttribute(s.geometry.colors,3)),s.geometry.uvs.length&&l.setAttribute("uv",new P0.Float32BufferAttribute(s.geometry.uvs,2));let d=Math.max(...s.geometry.indices)>65535?Uint32Array:Uint16Array;l.setIndex(new P0.BufferAttribute(new d(s.geometry.indices),1));let f=new P0.Mesh(l,e);f.position.set(s.position.x,s.position.y,s.position.z),f.name="mesh",o.add(f)}let v=s.shaderCubes;if(v&&v.count>0&&i){let l=ar(v,i);l.position.set(s.position.x,s.position.y,s.position.z),o.add(l)}o.children.length>0&&r.push(o)}return r}async function na(n){return new Promise((e,t)=>{let r=new Image;r.onload=()=>{let i=new P0.Texture(r);i.magFilter=P0.NearestFilter,i.minFilter=P0.NearestFilter,i.needsUpdate=!0,i.flipY=!1,e(i)},r.onerror=t,r.src=n})}async function Tv(n,e){let{scene:t,renderUpdateEmitter:r,material:i}=n,s=t.getObjectByName(ea);s&&(t.remove(s),kv(s));let o=!!e.textureAtlasDataUrl,a;if(o&&e.textureAtlasDataUrl){let d=await na(e.textureAtlasDataUrl);a=new P0.MeshLambertMaterial({map:d,vertexColors:!0,transparent:!0,alphaTest:.1}),a.name="geometry-export-material"}else a=i;let v=e.sections.some(d=>(d.shaderCubes?.count??0)>0)?ra(a):null,l=ia(e,a,v),c=new P0.Group;c.name=ea,o&&(c.userData.geometryExportMaterial=a);for(let d of l)c.add(d);return t.add(c),r.emit("update"),l.length}var ea,kv,Yi=ee(()=>{"use strict";E();x();k();R();Qt();mt();Vi();ea="geometry-export-root";kv=n=>{n.traverse(t=>{t.isMesh&&t.geometry?.dispose()});let e=n.userData?.geometryExportMaterial;e&&(e.map?.dispose?.(),e.dispose?.())}});E();x();k();R();E();x();k();R();E();x();k();R();E();x();k();R();import{proxy as G2}from"valtio";E();x();k();R();E();x();k();R();var xr=()=>({longRenderTime:!1,constantLongRenderTime:!1,tooManyEntities:!1,tooManyTextures:!1,unknownReason:!1});E();x();k();R();var r1=30;var Rr=45,kr=100;E();x();k();R();var a5=class{constructor(e){this.factors=e;u(this,"renderTimeHistory",[])}onFrame(e){this.pushRenderTime(e.totalMs),this.recompute(e)}pushRenderTime(e){this.renderTimeHistory.push(e),this.renderTimeHistory.length>24&&this.renderTimeHistory.shift()}recompute(e){let t=e.fps>0&&e.fps<=45,r=Math.max(0,e.totalMs-e.entitiesMs),i=e.totalMs>=30,s=this.renderTimeHistory.length,o=this.renderTimeHistory.filter(f=>f>=30).length,a=s>=8&&o/s>=.65,v=e.loadedTextureCount>=100,l=t&&e.entitiesMs>=8&&r<=20,d=t&&!(i||a||l||v);this.factors.longRenderTime=i,this.factors.constantLongRenderTime=a,this.factors.tooManyEntities=l,this.factors.tooManyTextures=v,this.factors.unknownReason=d}reset(){this.renderTimeHistory.length=0,this.factors.longRenderTime=!1,this.factors.constantLongRenderTime=!1,this.factors.tooManyEntities=!1,this.factors.tooManyTextures=!1,this.factors.unknownReason=!1}};E();x();k();R();var r6=[{key:"longRenderTime",code:"LR"},{key:"constantLongRenderTime",code:"CLR"},{key:"tooManyEntities",code:"ENT"},{key:"tooManyTextures",code:"TEX"},{key:"unknownReason",code:"UNK"}];function Tr(n){let e=r6.filter(({key:t})=>n[t]).map(({code:t})=>t);return e.length>0?e.join("+"):""}var v5={paused:!1,showChunkBorders:!1,enableDebugOverlay:!1,debugWasmPerf:!1,debugModelVariant:void 0,futuristicReveal:!1,wasmMesher:!0,shaderCubeBlocks:!1,shaderCubeDebugMode:0,mesherWorkers:1,addChunksBatchWaitTime:200,_experimentalSmoothChunkLoading:!0,_renderByChunks:!1,autoLowerRenderDistance:!1,disableMesherConversionCache:!1,dedicatedChangeWorker:!1,shadingTheme:"high-contrast",cardinalLight:"default",dayCycle:!0,smoothLighting:!0,enableLighting:!0,starfield:!0,defaultSkybox:!0,renderEntities:!0,extraBlockRenderers:!0,foreground:!0,fov:75,volume:1,showHand:!1,viewBobbing:!1,handRenderer:"vanilla",renderEars:!0,highlightBlockColor:"blue",fetchPlayerSkins:!0,skinTexturesProxy:void 0,vrSupport:!0,vrPageGameRendering:!0,clipWorldBelowY:void 0,isPlayground:!1,instantCameraUpdate:!1,isRaining:!1,moduleStates:{}},N2={fpsLimit:void 0,sceneBackground:"lightblue",timeoutRendering:!1},kc=(n={})=>G2({...v5,...n}),Ze=()=>({reactive:G2({world:{chunksLoaded:new Set,heightmaps:new Map,allChunksLoaded:!1,mesherWork:!1,instabilityFactors:xr(),intersectMedia:null},renderer:"...",preventEscapeMenu:!1}),nonReactive:{fps:0,worstRenderTime:0,avgRenderTime:0,world:{chunksLoaded:new Set,chunksTotalNumber:0},renderer:{timeline:{live:[],frozen:[],lastSecond:[]}}}});E();x();k();R();import{proxy as i6}from"valtio";var Mr=()=>i6({playerSkin:void 0,inWater:!1,waterBreathing:!1,backgroundColor:[0,0,0],ambientLight:0,directionalLight:0,eyeHeight:0,gameMode:void 0,lookingAtBlock:void 0,diggingBlock:void 0,movementState:"NOT_MOVING",onGround:!0,sneaking:!1,flying:!1,sprinting:!1,walkDist:0,prevWalkDist:0,bob:0,prevBob:0,itemUsageTicks:0,username:"",onlineMode:!1,cardinalLight:"default",lightingDisabled:!1,shouldHideHand:!1,heldItemMain:void 0,heldItemOff:void 0,perspective:"first_person",onFire:!1,fovMultiplier:1,cameraSpectatingEntity:void 0,team:void 0}),W2=n=>({isSpectator(){return n.gameMode==="spectator"},isSpectatingEntity(){return n.cameraSpectatingEntity!==void 0&&n.gameMode==="spectator"},isThirdPerson(){return this.isSpectatingEntity()?!1:n.perspective==="third_person_back"||n.perspective==="third_person_front"}}),V2=()=>({reactive:Mr()});E();x();k();R();import{Vec3 as w6}from"vec3";import{proxy as J2}from"valtio";E();x();k();R();E();x();k();R();E();x();k();R();E();x();k();R();var i1={},j2=!1;function n6(){if(j2)return i1;j2=!0;var n=typeof Reflect=="object"?Reflect:null,e=n&&typeof n.apply=="function"?n.apply:function(S,H,B){return Function.prototype.apply.call(S,H,B)},t;n&&typeof n.ownKeys=="function"?t=n.ownKeys:Object.getOwnPropertySymbols?t=function(S){return Object.getOwnPropertyNames(S).concat(Object.getOwnPropertySymbols(S))}:t=function(S){return Object.getOwnPropertyNames(S)};function r(M){}var i=Number.isNaN||function(S){return S!==S};function s(){s.init.call(this)}i1=s,i1.once=y,s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var o=10;function a(M){if(typeof M!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof M)}Object.defineProperty(s,"defaultMaxListeners",{enumerable:!0,get:function(){return o},set:function(M){if(typeof M!="number"||M<0||i(M))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+M+".");o=M}}),s.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},s.prototype.setMaxListeners=function(S){if(typeof S!="number"||S<0||i(S))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+S+".");return this._maxListeners=S,this};function v(M){return M._maxListeners===void 0?s.defaultMaxListeners:M._maxListeners}s.prototype.getMaxListeners=function(){return v(this)},s.prototype.emit=function(S){for(var H=[],B=1;B<arguments.length;B++)H.push(arguments[B]);var I=S==="error",G=this._events;if(G!==void 0)I=I&&G.error===void 0;else if(!I)return!1;if(I){var O;if(H.length>0&&(O=H[0]),O instanceof Error)throw O;var j=new Error("Unhandled error."+(O?" ("+O.message+")":""));throw j.context=O,j}var J=G[S];if(J===void 0)return!1;if(typeof J=="function")e(J,this,H);else for(var X=J.length,t0=g(J,X),B=0;B<X;++B)e(t0[B],this,H);return!0};function l(M,S,H,B){var I,G,O;if(a(H),G=M._events,G===void 0?(G=M._events=Object.create(null),M._eventsCount=0):(G.newListener!==void 0&&(M.emit("newListener",S,H.listener?H.listener:H),G=M._events),O=G[S]),O===void 0)O=G[S]=H,++M._eventsCount;else if(typeof O=="function"?O=G[S]=B?[H,O]:[O,H]:B?O.unshift(H):O.push(H),I=v(M),I>0&&O.length>I&&!O.warned){O.warned=!0;var j=new Error("Possible EventEmitter memory leak detected. "+O.length+" "+String(S)+" listeners added. Use emitter.setMaxListeners() to increase limit");j.name="MaxListenersExceededWarning",j.emitter=M,j.type=S,j.count=O.length}return M}s.prototype.addListener=function(S,H){return l(this,S,H,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(S,H){return l(this,S,H,!0)};function c(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function d(M,S,H){var B={fired:!1,wrapFn:void 0,target:M,type:S,listener:H},I=c.bind(B);return I.listener=H,B.wrapFn=I,I}s.prototype.once=function(S,H){return a(H),this.on(S,d(this,S,H)),this},s.prototype.prependOnceListener=function(S,H){return a(H),this.prependListener(S,d(this,S,H)),this},s.prototype.removeListener=function(S,H){var B,I,G,O,j;if(a(H),I=this._events,I===void 0)return this;if(B=I[S],B===void 0)return this;if(B===H||B.listener===H)--this._eventsCount===0?this._events=Object.create(null):(delete I[S],I.removeListener&&this.emit("removeListener",S,B.listener||H));else if(typeof B!="function"){for(G=-1,O=B.length-1;O>=0;O--)if(B[O]===H||B[O].listener===H){j=B[O].listener,G=O;break}if(G<0)return this;G===0?B.shift():b(B,G),B.length===1&&(I[S]=B[0]),I.removeListener!==void 0&&this.emit("removeListener",S,j||H)}return this},s.prototype.off=s.prototype.removeListener,s.prototype.removeAllListeners=function(S){var H,B,I;if(B=this._events,B===void 0)return this;if(B.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):B[S]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete B[S]),this;if(arguments.length===0){var G=Object.keys(B),O;for(I=0;I<G.length;++I)O=G[I],O!=="removeListener"&&this.removeAllListeners(O);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(H=B[S],typeof H=="function")this.removeListener(S,H);else if(H!==void 0)for(I=H.length-1;I>=0;I--)this.removeListener(S,H[I]);return this};function f(M,S,H){var B=M._events;if(B===void 0)return[];var I=B[S];return I===void 0?[]:typeof I=="function"?H?[I.listener||I]:[I]:H?w(I):g(I,I.length)}s.prototype.listeners=function(S){return f(this,S,!0)},s.prototype.rawListeners=function(S){return f(this,S,!1)},s.listenerCount=function(M,S){return typeof M.listenerCount=="function"?M.listenerCount(S):m.call(M,S)},s.prototype.listenerCount=m;function m(M){var S=this._events;if(S!==void 0){var H=S[M];if(typeof H=="function")return 1;if(H!==void 0)return H.length}return 0}s.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]};function g(M,S){for(var H=new Array(S),B=0;B<S;++B)H[B]=M[B];return H}function b(M,S){for(;S+1<M.length;S++)M[S]=M[S+1];M.pop()}function w(M){for(var S=new Array(M.length),H=0;H<S.length;++H)S[H]=M[H].listener||M[H];return S}function y(M,S){return new Promise(function(H,B){function I(O){M.removeListener(S,G),B(O)}function G(){typeof M.removeListener=="function"&&M.removeListener("error",I),H([].slice.call(arguments))}C(M,S,G,{once:!0}),S!=="error"&&A(M,I,{once:!0})})}function A(M,S,H){typeof M.on=="function"&&C(M,"error",S,H)}function C(M,S,H,B){if(typeof M.on=="function")B.once?M.once(S,H):M.on(S,H);else if(typeof M.addEventListener=="function")M.addEventListener(S,function I(G){B.once&&M.removeEventListener(S,I),H(G)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof M)}return i1}var n1=n6();n1.once;n1.once=function(n,e){return new Promise((t,r)=>{function i(...o){s!==void 0&&n.removeListener("error",s),t(o)}let s;e!=="error"&&(s=o=>{n.removeListener(name,i),r(o)},n.once("error",s)),n.once(e,i)})};n1.on=function(n,e){let t=[],r=[],i=null,s=!1,o={async next(){let l=t.shift();if(l)return createIterResult(l,!1);if(i){let c=Promise.reject(i);return i=null,c}return s?createIterResult(void 0,!0):new Promise((c,d)=>r.push({resolve:c,reject:d}))},async return(){n.removeListener(e,a),n.removeListener("error",v),s=!0;for(let l of r)l.resolve(createIterResult(void 0,!0));return createIterResult(void 0,!0)},throw(l){i=l,n.removeListener(e,a),n.removeListener("error",v)},[Symbol.asyncIterator](){return this}};return n.on(e,a),n.on("error",v),o;function a(...l){let c=r.shift();c?c.resolve(createIterResult(l,!1)):t.push(l)}function v(l){s=!0;let c=r.shift();c?c.reject(l):i=l,o.return()}};var{EventEmitter:Xe,defaultMaxListeners:Nc,init:Wc,listenerCount:Vc,on:jc,once:Yc}=n1;import{Vec3 as $e}from"vec3";E();x();k();R();function l5(n){let e=n*2+1;if(e<=0)return[];let t=[],r=0,i=0,s=0,o=-1;for(let a=0;a<e*e;a++){if(Math.abs(r)<=e/2&&Math.abs(i)<=e/2&&t.push([r,i]),r===i||r<0&&r===-i||r>0&&r===1-i){let v=s;s=-o,o=v}r+=s,i+=o}return t}var kt=n=>[Math.floor(n.x/16),Math.floor(n.z/16)],s6=n=>[Math.floor(n.x/16),Math.floor(n.y/16),Math.floor(n.z/16)],Y2=async(n,e,t,r=1)=>{for(let i=0;i<n.length;i+=r)e&&await new Promise(s=>setTimeout(s,e)),await t(n[i],i)},c5=class c5 extends Xe{static restoreTransferred(e,t){let r=new c5;return t&&t.addEventListener("message",({data:i})=>{i.class===c5.restorerName&&i.type==="event"&&r.emit(i.eventName,...i.args)}),r}};u(c5,"restorerName","WorldViewWorker");var et=c5,tt=class extends Xe{constructor(t,r,i=new $e(0,0,0)){super();this.world=t;this.viewDistance=r;u(this,"spiralNumber",0);u(this,"gotPanicLastTime",!1);u(this,"panicChunksReload",()=>{});u(this,"loadedChunks",{});u(this,"inLoading",!1);u(this,"chunkReceiveTimes",[]);u(this,"lastChunkReceiveTime",0);u(this,"lastChunkReceiveTimeAvg",0);u(this,"panicTimeout");u(this,"lastPos");u(this,"eventListeners",{});u(this,"debugChunksInfo",{});u(this,"waitingSpiralChunksLoad",{});u(this,"addWaitTime",1);u(this,"keepChunksDistance",0);u(this,"isPlayground",!1);u(this,"allowPositionUpdate",!0);u(this,"lastBiomeId",null);u(this,"lastPosCheck",null);this.lastPos=new $e(0,0,0).update(i)}prepareForTransfer(t){if(t){let r=this.emit.bind(this);this.emit=(i,...s)=>{r(i,...s),t.postMessage({class:et.restorerName,type:"event",eventName:i,args:s})}}return{__restorer:et.restorerName}}setBlockStateId(t,r){let i=this.world.setBlockStateId(t,r);if(i&&typeof i.then=="function")throw new Error("setBlockStateId returned promise (not supported)");this.emit("blockUpdate",{pos:t,stateId:r})}updateViewDistance(t){this.viewDistance=t,this.emit("renderDistance",t)}async init(t,r){this.updateViewDistance(this.viewDistance),this.emit("chunkPosUpdate",{pos:t}),r?.time?.timeOfDay!==void 0&&this.emit("time",r.time.timeOfDay),r?.entity&&this.emit("playerEntity",r.entity),this.emitterGotConnected(r);let[i,s]=kt(t),o=l5(this.viewDistance).map(([a,v])=>new $e((i+a)*16,0,(s+v)*16));this.lastPos.update(t),await this._loadChunks(o,t)}chunkProgress(){if(this.panicTimeout&&clearTimeout(this.panicTimeout),this.chunkReceiveTimes.length>=5){let t=this.chunkReceiveTimes.reduce((i,s)=>i+s,0)/this.chunkReceiveTimes.length;this.lastChunkReceiveTimeAvg=t;let r=t*2+1e3;this.panicTimeout&&clearTimeout(this.panicTimeout),this.panicTimeout=setTimeout(()=>{!this.gotPanicLastTime&&this.inLoading&&(this.gotPanicLastTime=!0,this.panicChunksReload())},r)}}async _loadChunks(t,r){this.spiralNumber++;let{spiralNumber:i}=this;for(let o of Object.keys(this.waitingSpiralChunksLoad))this.waitingSpiralChunksLoad[o](!1),delete this.waitingSpiralChunksLoad[o];let s=!0;this.inLoading=!0,await Y2(t,this.addWaitTime,async o=>{!s||this.loadedChunks[`${o.x},${o.z}`]||(this.world.getColumnAt(o)||(s=await new Promise(a=>{this.waitingSpiralChunksLoad[`${o.x},${o.z}`]=a})),s&&(await this.loadChunk(o,void 0,`spiral ${i} from ${r.x},${r.z}`),this.chunkProgress()))}),this.panicTimeout&&clearTimeout(this.panicTimeout),this.inLoading=!1,this.gotPanicLastTime=!1,this.chunkReceiveTimes=[],this.lastChunkReceiveTime=0}async loadChunk(t,r=!1,i="spiral"){var l,c;let[s,o]=kt(this.lastPos),a=Math.abs(s-Math.floor(t.x/16)),v=Math.abs(o-Math.floor(t.z/16));if(a<=this.viewDistance&&v<=this.viewDistance){let d=await this.world.getColumnAt(t.y!==void 0?t:new $e(t.x,0,t.z));if(d){let f=d.toJson(),m={minY:d.minY??0,worldHeight:d.worldHeight??256};this.emit("loadChunk",{x:t.x,z:t.z,chunk:f,blockEntities:d.blockEntities,worldConfig:m,isLightUpdate:r}),this.loadedChunks[`${t.x},${t.z}`]=!0,(l=this.debugChunksInfo)[c=`${t.x},${t.z}`]??(l[c]={loads:[]}),this.debugChunksInfo[`${t.x},${t.z}`].loads.push({dataLength:f.length,reason:i,time:Date.now()})}else this.isPlayground&&this.emit("markAsLoaded",{x:t.x,z:t.z})}}unloadAllChunks(){for(let t of Object.keys(this.loadedChunks)){let[r,i]=t.split(",").map(Number);this.unloadChunk({x:r,z:i})}}unloadChunk(t){this.emit("unloadChunk",{x:t.x,z:t.z}),delete this.loadedChunks[`${t.x},${t.z}`],delete this.debugChunksInfo[`${t.x},${t.z}`]}emitterGotConnected(t){typeof globalThis.WorkerGlobalScope<"u"&&globalThis instanceof globalThis.WorkerGlobalScope||!t||this.emit("blockEntities",new Proxy({},{get(i,s,o){if(typeof s!="string")return;let[a,v,l]=s.split(",").map(Number);return t.world.getBlock(new $e(a,v,l))?.entity}}))}updateBiome(t){try{if(!this.world.getBiome)return;let r=this.world.getBiome(t);r!==this.lastBiomeId&&(this.lastBiomeId=r,this.emit("biomeReset"))}catch{}}async updatePosition(t,r=!1){if(!this.allowPositionUpdate)return;let i=t.floored();if(!r&&this.lastPosCheck&&this.lastPosCheck.equals(i))return;this.lastPosCheck=i,this.updateBiome(t);let[s,o]=kt(this.lastPos),[a,v]=kt(t);if(s!==a||o!==v||r){this.emit("chunkPosUpdate",{pos:t});let l=[],c=r?this.viewDistance:this.viewDistance+this.keepChunksDistance;for(let f of Object.keys(this.loadedChunks)){let[m,g]=f.split(",").map(Number),b=new $e(m,0,g),[w,y]=kt(b),A=Math.abs(a-w),C=Math.abs(v-y);(A>c||C>c)&&l.push(b)}for(let f of l)this.unloadChunk(f);let d=l5(this.viewDistance).map(([f,m])=>{let g=new $e((a+f)*16,0,(v+m)*16);if(!this.loadedChunks[`${g.x},${g.z}`])return g}).filter(f=>!!f);this.lastPos.update(t),this._loadChunks(d,t)}else this.emit("chunkPosUpdate",{pos:t}),this.lastPos.update(t)}};E();x();k();R();E();x();k();R();import Q2 from"minecraft-data";import o6 from"mc-assets/dist/blocksAtlases.json";import a6 from"mc-assets/dist/itemsAtlases.json";import v6 from"mc-assets/dist/itemDefinitions.json";import l6 from"mc-assets/dist/blocksAtlasLatest.png";import c6 from"mc-assets/dist/blocksAtlasLegacy.png";import d6 from"mc-assets/dist/itemsAtlasLatest.png";import u6 from"mc-assets/dist/itemsAtlasLegacy.png";import f6 from"mc-assets/dist/textureReplacements/christmas";import{AtlasParser as s1}from"mc-assets/dist/atlasParser";import h6 from"mc-assets/dist/worldBlockProvider";import{ItemsRenderer as m6}from"mc-assets/dist/itemsRenderer";import{getLoadedItemDefinitionsStore as p6}from"mc-assets";var Tt=class{constructor(e){u(this,"sourceItemDefinitionsJson",v6);u(this,"itemsDefinitionsStore",p6(this.sourceItemDefinitionsJson));u(this,"allReady",!1);u(this,"itemsAtlasImage");u(this,"blocksAtlasImage");u(this,"blocksAtlasJson");u(this,"customBlockStates");u(this,"customModels");u(this,"customItemModelNames",{});u(this,"customTextures",{});u(this,"guiAtlas",null);u(this,"guiAtlasVersion",0);u(this,"itemsRenderer");u(this,"worldBlockProvider");u(this,"blockstatesModels",null);u(this,"version");u(this,"texturesVersion");u(this,"mcData");e&&(Object.assign(this,e),this.mcData=Q2(this.version))}prepareForTransfer(){let e={};for(let t in this)Object.prototype.hasOwnProperty.call(this,t)&&typeof this[t]!="function"&&(t==="itemsRenderer"||t==="worldBlockProvider"||t==="mcData"||(e[t]=this[t]));return e.customTextures={},e}},g6="1.21.4",Pe=class Pe extends Xe{constructor(){super(...arguments);u(this,"sourceBlockStatesModels",null);u(this,"sourceBlocksAtlases",o6);u(this,"sourceItemsAtlases",a6);u(this,"currentResources");u(this,"itemsAtlasParser");u(this,"blocksAtlasParser");u(this,"currentConfig");u(this,"abortController",new AbortController);u(this,"_promiseAssetsReadyResolvers",Promise.withResolvers())}static restoreTransferred(t,r){let i=new Pe,s=o=>{i.currentResources=new Tt(o)};return s(t.currentResources),r&&r.addEventListener("message",({data:o})=>{o.class===Pe.restorerName&&(o.type==="newResources"&&s(o.currentResources),o.type==="event"&&i.emit(o.eventName,...o.args))}),i}prepareForTransfer(t){if(t){let r=this.emit.bind(this);this.emit=(i,...s)=>{r(i,...s),t.postMessage({class:Pe.restorerName,type:"event",eventName:i,args:s}),(i==="assetsTexturesUpdated"||i==="assetsInventoryReady")&&t.postMessage({class:Pe.restorerName,type:"newResources",currentResources:this.currentResources?.prepareForTransfer()})}}return{__restorer:Pe.restorerName,currentResources:this.currentResources?.prepareForTransfer()}}get promiseAssetsReady(){return this._promiseAssetsReadyResolvers.promise}async loadSourceData(t=this.currentConfig?.version){if(!t)throw new Error("No version loaded");this.sourceBlockStatesModels??(this.sourceBlockStatesModels=(await import("mc-assets/dist/blockStatesModels.json")).default)}resetResources(){this.currentResources=new Tt}async updateAssetsData(t,r=!1){if(!this.currentConfig)throw new Error("No config loaded");this._promiseAssetsReadyResolvers=Promise.withResolvers();let i=new AbortController;if(await this.loadSourceData(this.currentConfig.version),i.signal.aborted)return;let s=this.currentResources??new Tt;s.version=this.currentConfig.version,s.texturesVersion=this.currentConfig.texturesVersion??s.version,s.mcData=Q2(s.version),s.blockstatesModels={blockstates:{},models:{}},s.blockstatesModels.blockstates.latest={...this.sourceBlockStatesModels.blockstates.latest,...s.customBlockStates},s.blockstatesModels.models.latest={...this.sourceBlockStatesModels.models.latest,...s.customModels},await Promise.all([this.recreateBlockAtlas(s),this.recreateItemsAtlas(s)]),!i.signal.aborted&&(s.version&&s.blockstatesModels&&this.itemsAtlasParser&&this.blocksAtlasParser&&(s.itemsRenderer=new m6(s.version,s.blockstatesModels,this.itemsAtlasParser,this.blocksAtlasParser)),!i.signal.aborted&&(this.currentResources=s,s.allReady=!0,r||this.emit("assetsTexturesUpdated"),this.currentConfig.noInventoryGui?this._promiseAssetsReadyResolvers.resolve():(this.emit("assetsInventoryStarted"),this.generateGuiTextures().then(()=>{i.signal.aborted||(r||this.emit("assetsInventoryReady"),this._promiseAssetsReadyResolvers.resolve())}))))}async recreateBlockAtlas(t=this.currentResources){let r={},i=new Date;(i.getMonth()===11&&i.getDate()>=24||i.getMonth()===0&&i.getDate()<=6)&&Object.assign(r,f6);let s=new s1(this.sourceBlocksAtlases,l6,c6),o=Object.keys(t.customTextures.blocks?.textures??{}),{atlas:a,canvas:v}=await s.makeNewAtlas(t.texturesVersion,l=>{if(this.currentConfig.includeOnlyBlocks&&!this.currentConfig.includeOnlyBlocks.includes(l))return!1;let c=t.customTextures.blocks?.textures[l];return r[l]??c},void 0,void 0,o,{needHorizontalIndexes:!!this.currentConfig.includeOnlyBlocks});this.blocksAtlasParser=new s1({latest:a},v.toDataURL()),t.blocksAtlasImage=await createImageBitmap(v),t.blocksAtlasJson=this.blocksAtlasParser.atlas.latest,t.worldBlockProvider=h6(t.blockstatesModels,this.blocksAtlasParser.atlas,g6)}async recreateItemsAtlas(t=this.currentResources){let r=new s1(this.sourceItemsAtlases,d6,u6),i=Object.keys(t.customTextures.items?.textures??{}),{atlas:s,canvas:o}=await r.makeNewAtlas(t.texturesVersion,a=>{let v=t.customTextures.items?.textures[a];if(v)return v},t.customTextures.items?.tileSize,void 0,i);this.itemsAtlasParser=new s1({latest:s},o.toDataURL()),t.itemsAtlasImage=await createImageBitmap(o)}async generateGuiTextures(){}async downloadDebugAtlas(t=!1){if(!this.currentResources)throw new Error("No resources loaded");let s=await(t?this.itemsAtlasParser:this.blocksAtlasParser).createDebugImage(!0),o=document.createElement("a");o.href=s,o.download=`atlas-debug-${t?"items":"blocks"}.png`,o.click()}destroy(){this.abortController.abort(),this.currentResources=void 0,this.abortController=new AbortController}};u(Pe,"restorerName","ResourcesManager");var he=Pe;E();x();k();R();var ae=class extends Error{constructor(t,r){super(t);u(this,"failure");this.name="MesherWorkerPreloadError",this.failure=r}};function b6(n){return!n||typeof n!="object"?!1:n.type==="mc-web-pong"?!0:Array.isArray(n)?n.some(e=>e&&typeof e=="object"&&e.type==="mc-web-pong"):!1}var y6=45e3,_6=1e4;async function K2(n){if(F.env.SINGLE_FILE_BUILD)return;let e=n?.fetchTimeoutMs??y6,t=n?.pingTimeoutMs??_6,r=n?.script??"mesher.js",i=new URL(r,document.baseURI).href,s;try{let d=new AbortController,f=window.setTimeout(()=>d.abort(),e);try{s=await fetch(i,{credentials:"same-origin",cache:"force-cache",signal:d.signal})}finally{clearTimeout(f)}}catch(d){let f=d;throw f?.name==="AbortError"?new ae(`Mesher script fetch timed out after ${e}ms (${i}).`,{phase:"fetch",code:"timeout"}):new ae(`Mesher script fetch failed (network): ${f?.message??d}. URL: ${i}`,{phase:"fetch",code:"network",detail:String(f?.message??d)})}if(!s.ok)throw new ae(`Mesher script HTTP ${s.status} ${s.statusText}: ${i}`,{phase:"fetch",code:"bad-status",status:s.status});let o=s.headers.get("content-type")??"",a=await s.arrayBuffer();if(a.byteLength===0)throw new ae(`Mesher script response was empty: ${i}`,{phase:"fetch",code:"invalid-body",hint:"empty"});let v=Math.min(1024,a.byteLength),l=new TextDecoder().decode(a.slice(0,v)).trimStart();if(l.startsWith("<!DOCTYPE")||l.startsWith("<html")||l.startsWith("<HTML"))throw new ae(`Mesher URL returned HTML (wrong path, redirect, or SPA fallback), not JavaScript: ${i}`,{phase:"fetch",code:"invalid-body",hint:"html"});o.length>0&&/javascript|ecmascript/i.test(o);let c;try{c=new Worker(i)}catch(d){let f=d instanceof Error?d.message:String(d);throw new ae(`Could not construct Worker for mesher (${i}): ${f}`,{phase:"worker",code:"construct-failed",message:f})}await new Promise((d,f)=>{let m=!1,g=window.setTimeout(()=>{m||(m=!0,b(),f(new ae(`Mesher worker did not reply with mc-web-pong within ${t}ms (wrong script, SW stale cache, worker blocked, or COEP/CORP). URL: ${i}`,{phase:"ping",code:"timeout"})))},t),b=()=>{clearTimeout(g);let S=c;c=void 0,S&&(S.removeEventListener("message",A),S.removeEventListener("error",C),S.removeEventListener("messageerror",M),S.terminate())},w=()=>{m||(m=!0,b(),d())},y=S=>{m||(m=!0,b(),f(S))};function A(S){b6(S.data)&&w()}function C(S){y(new ae(`Mesher worker script failed to load or threw during startup: ${S.message||"unknown"} @ ${i}`,{phase:"worker",code:"script-error",message:S.message}))}function M(){y(new ae(`Mesher worker message channel error (structured clone / deserialization). URL: ${i}`,{phase:"ping",code:"messageerror"}))}c.addEventListener("message",A),c.addEventListener("error",C),c.addEventListener("messageerror",M);try{c.postMessage({type:"mc-web-ping",t:performance.now(),workerIndex:0})}catch(S){let H=S instanceof Error?S.message:String(S);y(new ae(`Failed to post mc-web-ping to mesher worker: ${H}`,{phase:"ping",code:"post-failed",detail:H}))}})}var q2=class{constructor(e={},t=new he){this.resourcesManager=t;u(this,"waitBackendLoadPromises",[]);u(this,"onWorldStart");u(this,"onBeforeWorldStart");u(this,"worldView");u(this,"config");u(this,"menuBackgroundOptions");u(this,"inWorldRenderingConfig");u(this,"backend");u(this,"backendLoader");u(this,"currentState");u(this,"currentDisplay",null);u(this,"playerState",{reactive:Mr()});u(this,"rendererState");u(this,"nonReactiveState");u(this,"worldReady");u(this,"resolveWorldReady");u(this,"lastCamUpdate",0);u(this,"getRendererOptions");this.config={...N2,...e.config},this.menuBackgroundOptions={...e.config?.menuBackground,...e.menuBackground},this.inWorldRenderingConfig=J2({...v5,...e.rendererConfig});let r=Ze();this.rendererState=r.reactive,this.nonReactiveState=r.nonReactive,this.initWorldReadyPromise()}initWorldReadyPromise(){let{promise:e,resolve:t}=Promise.withResolvers();this.worldReady=e,this.resolveWorldReady=t}preloadWorkers(){let e=this.inWorldRenderingConfig.wasmMesher?"mesherWasm.js":"mesher.js";return K2({script:e})}bindRendererOptions(e){this.getRendererOptions=e}async loadBackend(e){this.backend&&this.disconnectBackend(),await Promise.all(this.waitBackendLoadPromises),this.waitBackendLoadPromises=[],this.backendLoader=e;let t={config:this.config,getRendererOptions:this.getRendererOptions,callbacks:{displayCriticalError:i=>{},setRendererSpecificSettings:(i,s)=>{},fireCustomEvent:(i,...s)=>{}},rendererSpecificSettings:{}},r=e(t);if(this.backend=await Promise.resolve(r),this.currentState)if(this.currentState.method==="startMenuBackground")this.startMenuBackground(...this.currentState.args);else{let{method:i,args:s}=this.currentState;this.backend[i](...s)}}async startWorld(e,t,r=this.playerState.reactive,i){if(this.currentDisplay==="world")throw new Error("World already started");this.currentDisplay="world";let s=i??new w6(0,64,0);this.worldView=new tt(e,t,s),this.worldView.isPlayground=this.inWorldRenderingConfig.isPlayground;let o={version:this.resourcesManager?.currentConfig?.version??"1.20.4",worldView:this.worldView,inWorldRenderingConfig:this.inWorldRenderingConfig,playerStateReactive:r,rendererState:this.rendererState,nonReactiveState:this.nonReactiveState,resourcesManager:this.resourcesManager};this.onBeforeWorldStart?.();let a;if(this.backend){let v=this.backend.startWorld(o);v&&typeof v.then=="function"&&(a=v)}return this.currentState={method:"startWorld",args:[o]},await a,this.resolveWorldReady(),this.onWorldStart?.(),!!a}startMenuBackground(e){if(this.currentDisplay==="menu")return;let t={...this.menuBackgroundOptions,...e,resourcesManager:e?.resourcesManager??this.resourcesManager};this.backend&&(this.currentDisplay="menu",this.backend.startMenuBackground(t)),this.currentState={method:"startMenuBackground",args:[t]}}resetBackend(e=!1){this.disconnectBackend(e),this.backendLoader&&this.loadBackend(this.backendLoader)}disconnectBackend(e=!1){e&&(this.currentState=void 0,this.currentDisplay=null,this.worldView=void 0),this.backend&&(this.backend.disconnect(),this.backend=void 0),this.currentDisplay=null,this.initWorldReadyPromise(),this.rendererState=J2(Ze().reactive),this.nonReactiveState=Ze().nonReactive}updateCamera(e,t,r){this.backend?.updateCamera(e,t,r)}setRendering(e){this.backend?.setRendering(e)}async startWithBot(e,t){await this.startWorld(e.world,t),this.worldView&&typeof this.worldView.listenToBot=="function"&&this.worldView.listenToBot(e)}destroyAll(){this.disconnectBackend(!0),this.resourcesManager&&typeof this.resourcesManager.destroy=="function"&&this.resourcesManager.destroy()}get utils(){let e=this.backend;return{async waitingForChunks(){if(!e?.worldState?.allChunksLoaded)return new Promise(t=>{let r=setInterval(()=>{e?.worldState?.allChunksLoaded&&(clearInterval(r),t())},100)})}}}destroy(){this.disconnectBackend(!0)}};E();x();k();R();import{subscribe as P6}from"valtio/vanilla";E();x();k();R();E();x();k();R();var rt=["galaxy","nether","end","cyber","light"],it=["cruise","barrel","dive","orbit","snake"],d5={galaxy:"Galaxy",nether:"Nether",end:"The End",cyber:"Cyber",light:"Light Space"},u5={cruise:"Cruise",barrel:"Barrel",dive:"Dive",orbit:"Orbit",snake:"Snake"},nt=["mixed","stainedGlass","wool","construction","glow","world"],f5={mixed:"Mixed",stainedGlass:"Stained glass",wool:"Wool",construction:"Construction",glow:"Glow",world:"World (grass & ores)"};E();x();k();R();var pe={mode:"futuristic",minecraftTextures:!0,futuristicScene:"light",futuristicCamera:"dive",futuristicBlockGroup:"stainedGlass",futuristicCameraSpeedPercent:80,futuristicBlockSpeedPercent:40},Ae=n=>n/100,h5={camera:Ae(pe.futuristicCameraSpeedPercent),block:Ae(pe.futuristicBlockSpeedPercent)};var A6={off:0,holes:1,texIndex:2,faces:3,atlasAlpha:4};function Sr(n){return A6[n]}var st=pe,Z2={rendererWorldPerformance:"normal",rendererMeshersCountOverride:null,starfieldRendering:!0,defaultSkybox:!0,menuBackgroundMode:st.mode,menuBackgroundMinecraftTextures:st.minecraftTextures,menuBackgroundFuturisticScene:st.futuristicScene,menuBackgroundFuturisticCamera:st.futuristicCamera,menuBackgroundFuturisticBlockGroup:st.futuristicBlockGroup,menuBackgroundFuturisticCameraSpeed:st.futuristicCameraSpeedPercent,menuBackgroundFuturisticBlockSpeed:st.futuristicBlockSpeedPercent,rendererFuturisticReveal:!1,rendererPerfDebugOverlay:!1,disableBlockEntityTextures:!1,rendererMesher:"wasm",rendererShaderCubeDebugMode:"off",showChunkBorders:!1,renderEntities:!0,renderDebug:"basic",frameLimit:!1,backgroundRendering:"20fps",vanillaLook:!1,smoothLighting:!0,newVersionsLighting:!1,vrSupport:!0,vrPageGameRendering:!1,clipWorldBelowY:void 0,highlightBlockColor:"auto",loadPlayerSkins:!0,renderEars:!0,showHand:!0,viewBobbing:!0,dayCycleAndLighting:!0,keepChunksDistance:1,gpuPreference:"default",fov:75};function E6(n){n.highPerformanceGpu&&(n.gpuPreference="high-performance",delete n.highPerformanceGpu),n.rendererMesher!=="wasm"&&n.rendererMesher!=="legacy-js"&&(typeof n.rendererWasmMesher=="boolean"?n.rendererMesher=n.rendererWasmMesher?"wasm":"legacy-js":typeof n.wasmExperimentalMesher=="boolean"&&(n.rendererMesher=n.wasmExperimentalMesher?"wasm":"legacy-js")),delete n.wasmExperimentalMesher,delete n.rendererWasmMesher}var X2={menuBackgroundMode:{possibleValues:[["classic","Classic"],["futuristic","Futuristic"]],requiresRestart:!0},menuBackgroundMinecraftTextures:{text:"Minecraft block textures",tooltip:"Use block atlas on futuristic menu cubes (loads assets on menu)"},menuBackgroundFuturisticScene:{possibleValues:rt.map(n=>[n,d5[n]])},menuBackgroundFuturisticCamera:{possibleValues:it.map(n=>[n,u5[n]])},menuBackgroundFuturisticBlockGroup:{possibleValues:nt.map(n=>[n,f5[n]]),text:"Block pool",tooltip:"Block set for textured menu cubes (requires Minecraft textures)"},menuBackgroundFuturisticCameraSpeed:{text:"Camera speed",tooltip:"Orbit / fly-through camera path speed. 0 freezes the path; mouse parallax still works.",min:0,max:200,unit:"%"},menuBackgroundFuturisticBlockSpeed:{text:"Block speed",tooltip:"Floating blocks and sky rotation. Independent of camera path speed.",min:0,max:200,unit:"%"},rendererWorldPerformance:{text:"World performance",tooltip:"Background workers for chunk geometry. Reload to apply.",requiresRestart:!0,possibleValues:[["low-energy","Low Energy"],["normal","Normal"],["maximum","Maximum"]]},starfieldRendering:{text:"Starfield"},defaultSkybox:{text:"Default skybox"},rendererFuturisticReveal:{text:"Futuristic world reveal"},rendererPerfDebugOverlay:{text:"Performance debug overlay"},disableBlockEntityTextures:{text:"Disable block entity textures",tooltip:"Skips signs, banners, heads, maps, etc."},rendererMesher:{possibleValues:[["wasm","WASM"],["legacy-js","Legacy JS"]],text:"Mesher pipeline",tooltip:"WASM is faster. Use JS if WASM is not working. Requires reload.",requiresRestart:!0},rendererShaderCubeDebugMode:{text:"Shader cube debug",tooltip:"Instanced cube path visualization (requires shader cubes enabled).",possibleValues:[["off","Off"],["holes","Hole test (red)"],["texIndex","Tile index colors"],["faces","Face id colors"],["atlasAlpha","Atlas alpha"]]},showChunkBorders:{text:"Chunk borders"},renderEntities:{text:"Render entities"},renderDebug:{possibleValues:["advanced","basic","none"]},frameLimit:{text:"Frame limit",tooltip:"false = VSync / unlimited when focused"},backgroundRendering:{text:"Background FPS limit",possibleValues:[["full","NO"],["5fps","5 FPS"],["20fps","20 FPS"]]},vanillaLook:{text:"Vanilla shading",tooltip:"On: Minecraft-style face shading. Off: higher-contrast client shading."},smoothLighting:{},newVersionsLighting:{text:"Lighting in newer versions"},vrSupport:{text:"VR support",tooltip:"Shows VR entry; does not force VR on."},vrPageGameRendering:{text:"VR page game rendering"},clipWorldBelowY:{text:"Clip world below Y"},highlightBlockColor:{possibleValues:[["auto","Auto"],["blue","Blue"],["classic","Classic"]]},loadPlayerSkins:{},renderEars:{tooltip:"Deadmau5 ears when the skin texture includes them"},showHand:{},viewBobbing:{},dayCycleAndLighting:{text:"Day cycle"},keepChunksDistance:{text:"Keep chunks distance",tooltip:"Extra distance before unloading chunks",max:5,unit:""},fov:{min:30,max:110,unit:"\xB0",text:"Field of view"},gpuPreference:{text:"GPU preference",tooltip:"WebGL power preference. Requires reload / backend restart to apply.",requiresRestart:!0,possibleValues:[["default","Auto"],["high-performance","Dedicated"],["low-power","Low power"]]}},$2=[{title:"World rendering",keys:["rendererWorldPerformance","starfieldRendering","defaultSkybox","disableBlockEntityTextures","showChunkBorders","renderEntities","smoothLighting","vanillaLook","newVersionsLighting","dayCycleAndLighting","loadPlayerSkins","renderEars","showHand","viewBobbing","fov","keepChunksDistance","highlightBlockColor","clipWorldBelowY"]},{title:"Frame pacing",keys:["frameLimit","backgroundRendering","renderDebug","gpuPreference"]},{title:"VR",keys:["vrSupport","vrPageGameRendering"]},{title:"Menu background",keys:["menuBackgroundMode","menuBackgroundMinecraftTextures","menuBackgroundFuturisticScene","menuBackgroundFuturisticCamera","menuBackgroundFuturisticBlockGroup","menuBackgroundFuturisticCameraSpeed","menuBackgroundFuturisticBlockSpeed"]},{title:"Mesher",keys:["rendererMesher"]},{title:"Renderer debug",keys:["rendererFuturisticReveal","rendererPerfDebugOverlay","rendererShaderCubeDebugMode"]}];E();x();k();R();E();x();k();R();E();x();k();R();E();x();k();R();function Cr(n,e,t,r,i){let s=n.getImageData(e,t,r,i);for(let o=0;o<r;o++)for(let a=0;a<i;a++){let v=(o+a*r)*4;if(s.data[v+3]!==255)return!0}return!1}function o1(n){return n/64}function es(n,e,t){if(t){if(Cr(n,0,0,e,e))return}else if(Cr(n,0,0,e,e/2))return;let r=o1(e),i=(s,o,a,v)=>n.clearRect(s*r,o*r,a*r,v*r);i(40,0,8,8),i(48,0,8,8),i(32,8,8,8),i(40,8,8,8),i(48,8,8,8),i(56,8,8,8),t&&(i(4,32,4,4),i(8,32,4,4),i(0,36,4,12),i(4,36,4,12),i(8,36,4,12),i(12,36,4,12),i(20,32,8,4),i(28,32,8,4),i(16,36,4,12),i(20,36,8,12),i(28,36,4,12),i(32,36,8,12),i(44,32,4,4),i(48,32,4,4),i(40,36,4,12),i(44,36,4,12),i(48,36,4,12),i(52,36,12,12),i(4,48,4,4),i(8,48,4,4),i(0,52,4,12),i(4,52,4,12),i(8,52,4,12),i(12,52,4,12),i(52,48,4,4),i(56,48,4,4),i(48,52,4,12),i(52,52,4,12),i(56,52,4,12),i(60,52,4,12))}function x6(n,e){n.save(),n.scale(-1,1);let t=o1(e),r=(i,s,o,a,v,l)=>n.drawImage(n.canvas,i*t,s*t,o*t,a*t,-v*t,l*t,-o*t,a*t);r(4,16,4,4,20,48),r(8,16,4,4,24,48),r(0,20,4,12,24,52),r(4,20,4,12,20,52),r(8,20,4,12,16,52),r(12,20,4,12,28,52),r(44,16,4,4,36,48),r(48,16,4,4,40,48),r(40,20,4,12,40,52),r(44,20,4,12,36,52),r(48,20,4,12,32,52),r(52,20,4,12,44,52),n.restore()}function Br(n,e){let t=!1;if(e.width!==e.height)if(e.width===2*e.height)t=!0;else throw new Error(`Bad skin size: ${e.width}x${e.height}`);let r=n.getContext("2d",{willReadFrequently:!0});if(t){let i=e.width;n.width=i,n.height=i,r.clearRect(0,0,i,i),r.drawImage(e,0,0,i,i/2),x6(r,i),es(r,n.width,!1)}else n.width=e.width,n.height=e.height,r.clearRect(0,0,e.width,e.height),r.drawImage(e,0,0,n.width,n.height),es(r,n.width,!0)}function R6(n){if(n.width===2*n.height)return n.width/64;if(n.width*17===n.height*22)return n.width/22;if(n.width*11===n.height*23)return n.width/46;throw new Error(`Bad cape size: ${n.width}x${n.height}`)}function Pr(n,e){let t=R6(e);n.width=64*t,n.height=32*t;let r=n.getContext("2d",{willReadFrequently:!0});r.clearRect(0,0,n.width,n.height),r.drawImage(e,0,0,e.width,e.height)}function k6(n,e,t,r,i){let s=n.getImageData(e,t,r,i);for(let o=0;o<r;o++)for(let a=0;a<i;a++){let v=(o+a*r)*4;if(!(s.data[v+0]===0&&s.data[v+1]===0&&s.data[v+2]===0&&s.data[v+3]===255))return!1}return!0}function T6(n,e,t,r,i){let s=n.getImageData(e,t,r,i);for(let o=0;o<r;o++)for(let a=0;a<i;a++){let v=(o+a*r)*4;if(!(s.data[v+0]===255&&s.data[v+1]===255&&s.data[v+2]===255&&s.data[v+3]===255))return!1}return!0}function Ir(n){let e=o1(n.width),t=n.getContext("2d",{willReadFrequently:!0}),r=(a,v,l,c)=>Cr(t,a*e,v*e,l*e,c*e),i=(a,v,l,c)=>k6(t,a*e,v*e,l*e,c*e),s=(a,v,l,c)=>T6(t,a*e,v*e,l*e,c*e);return r(50,16,2,4)||r(54,20,2,12)||r(42,48,2,4)||r(46,52,2,12)||i(50,16,2,4)&&i(54,20,2,12)&&i(42,48,2,4)&&i(46,52,2,12)||s(50,16,2,4)&&s(54,20,2,12)&&s(42,48,2,4)&&s(46,52,2,12)?"slim":"default"}function Hr(n,e){if(e.width!==e.height&&e.width!==2*e.height)throw new Error(`Bad skin size: ${e.width}x${e.height}`);let t=o1(e.width),r=14*t,i=7*t;n.width=r,n.height=i;let s=n.getContext("2d",{willReadFrequently:!0});s.clearRect(0,0,r,i),s.drawImage(e,24*t,0,r,i,0,0,r,i)}E();x();k();R();import C6 from"mc-assets/dist/other-textures/latest/entity/player/wide/steve.png";E();x();k();R();import*as Ee from"three";E();x();k();R();var M6=()=>{if(typeof OffscreenCanvas>"u")return!1;try{let n=new OffscreenCanvas(1,1);return(n.getContext("webgl2")||n.getContext("webgl"))!==null}catch{return!1}},S6=M6(),V0=(n,e)=>{if(S6)return new OffscreenCanvas(n,e);let t=document.createElement("canvas");return t.width=n,t.height=e,t};async function a1(n){let t=await(await fetch(n)).blob();return createImageBitmap(t)}var R0=(n,e=!1)=>{n instanceof Ee.Mesh&&(n.geometry?.dispose?.(),n.material?.dispose?.()),n.children&&n.children.forEach(t=>R0(t,e)),e&&n instanceof Ee.Mesh&&n.material?.map?.dispose?.()},Or={},ts={},v1=n=>{let e=new Ee.Texture,t=a1(n).then(r=>{let i=new OffscreenCanvas(r.width,r.height);return i.getContext("2d").drawImage(r,0,0),e.source.data=i,e.needsUpdate=!0,e});return{texture:e,promise:t}},Ie=async n=>v1(n).texture,m5=n=>{let e=V0(n.width,n.height);e.getContext("2d").drawImage(n,0,0);let r=new Ee.Texture(e);return r.magFilter=Ee.NearestFilter,r.minFilter=Ee.NearestFilter,r};async function l1(n,e,t){if(!Or[n]){let{promise:i,resolve:s}=Promise.withResolvers(),o=v1(n);Or[n]=o.texture,o.promise.then(s),ts[n]=i}e(Or[n]),ts[n].then(()=>{t?.()})}var ge=C6,yf=Ie(ge),rs={apiEnabled:!0},c1=n=>{Object.assign(rs,n)};async function He(n,e){if(!rs.apiEnabled||e==="cape")return;let t=`https://playerdb.co/api/player/minecraft/${n}`,r=await fetch(t);return r.ok?(await r.json()).data.player.skin_texture:void 0}async function ot(n){n.startsWith("data:")||(n=await B6(n.replace("http://","https://")));let e=await a1(n),t=V0(64,64);return Br(t,e),{canvas:t,image:e}}var B6=async n=>{let t=await(await fetch(n,{})).arrayBuffer();return`data:image/png;base64,${z.from(t).toString("base64")}`};function Sf(n){return{mode:n.menuBackgroundMode,useMinecraftTextures:n.menuBackgroundMinecraftTextures,futuristicScene:n.menuBackgroundFuturisticScene,futuristicCamera:n.menuBackgroundFuturisticCamera,futuristicBlockGroup:n.menuBackgroundFuturisticBlockGroup,futuristicCameraSpeed:Ae(n.menuBackgroundFuturisticCameraSpeed),futuristicBlockSpeed:Ae(n.menuBackgroundFuturisticBlockSpeed)}}function I6(n,e){let t=n.futuristic;t&&(t.setScene?.(e.menuBackgroundFuturisticScene),t.setCamera?.(e.menuBackgroundFuturisticCamera),t.setBlockGroup?.(e.menuBackgroundFuturisticBlockGroup),t.setCameraSpeed?.(Ae(e.menuBackgroundFuturisticCameraSpeed)),t.setBlockSpeed?.(Ae(e.menuBackgroundFuturisticBlockSpeed)))}function H6(n){return n.rendererMesher!=="legacy-js"}function O6(n,e,t){let r=n.inWorldRenderingConfig,i=e.rendererMeshersCountOverride,s=o=>{r.mesherWorkers=i??o};switch(e.rendererWorldPerformance){case"low-energy":s(1),r.dedicatedChangeWorker=!1;break;case"normal":s(2),r.dedicatedChangeWorker=!t;break;case"maximum":s(Math.max(3,Math.min(navigator.hardwareConcurrency??0,8))),r.dedicatedChangeWorker=!t;break}}function F6(n,e,t){let r=e.backgroundRendering,i=e.frameLimit;t?n.config.fpsLimit=i||void 0:r==="5fps"?n.config.fpsLimit=5:r==="20fps"?n.config.fpsLimit=20:n.config.fpsLimit=void 0}function D6(n,e,t){let{renderDebug:r}=e;r==="none"||t.isCypress?n.config.statsVisible=0:r==="basic"?n.config.statsVisible=1:r==="advanced"&&(n.config.statsVisible=2)}function z6(n,e,t={}){let r=n.inWorldRenderingConfig,i=H6(e);r.showChunkBorders=e.showChunkBorders,r.futuristicReveal=e.rendererFuturisticReveal,O6(n,e,i),r.renderEntities=e.renderEntities,D6(n,e,t),F6(n,e,t.windowFocused!==!1),r.vrSupport=e.vrSupport,r.vrPageGameRendering=e.vrPageGameRendering,r.enableDebugOverlay=e.rendererPerfDebugOverlay,r.clipWorldBelowY=e.clipWorldBelowY,r.extraBlockRenderers=!e.disableBlockEntityTextures,r.fetchPlayerSkins=e.loadPlayerSkins,r.highlightBlockColor=e.highlightBlockColor,r.wasmMesher=i,r.disableMesherConversionCache=!!t.isSafari,c1({apiEnabled:e.loadPlayerSkins}),r.smoothLighting=e.smoothLighting,r.shadingTheme=e.vanillaLook?"vanilla":"high-contrast",r.starfield=e.starfieldRendering,r.defaultSkybox=e.defaultSkybox,r.fov=e.fov,r.shaderCubeDebugMode=Sr(e.rendererShaderCubeDebugMode)}function Cf(n,e,t){e.keepChunksDistance=t.keepChunksDistance;let r=n.inWorldRenderingConfig;r.renderEars=t.renderEars,r.showHand=t.showHand,r.viewBobbing=t.viewBobbing,r.dayCycle=t.dayCycleAndLighting}function Bf(n,e,t={}){n.bindRendererOptions(()=>e);let r=t.getWindowFocused?.()??!0,i=()=>{let s=e;if(z6(n,s,{isSafari:t.isSafari,isCypress:t.isCypress,windowFocused:r}),n.currentDisplay==="menu"){let o=n.backend?.getMenuBackground?.();o&&I6(o,s)}};return i(),t.onRegisterFocusHandlers?.({onFocus:()=>{r=!0,i()},onBlur:()=>{r=!1,i()}}),P6(e,i)}function Pf(n,e,t){n.inWorldRenderingConfig.enableLighting=!t||e}E();x();k();R();import{proxy as L6}from"valtio";var is=()=>L6({playerSkin:void 0,inWater:!1,waterBreathing:!1,backgroundColor:[0,0,0],ambientLight:0,directionalLight:0,eyeHeight:0,gameMode:void 0,lookingAtBlock:void 0,diggingBlock:void 0,movementState:"NOT_MOVING",onGround:!0,sneaking:!1,flying:!1,sprinting:!1,walkDist:0,prevWalkDist:0,bob:0,prevBob:0,itemUsageTicks:0,username:"",onlineMode:!1,cardinalLight:"default",lightingDisabled:!1,shouldHideHand:!1,heldItemMain:void 0,heldItemOff:void 0,perspective:"first_person",onFire:!1,fovMultiplier:1,cameraSpectatingEntity:void 0,team:void 0}),U6=n=>({isSpectator(){return n.gameMode==="spectator"},isSpectatingEntity(){return n.cameraSpectatingEntity!==void 0&&n.gameMode==="spectator"},isThirdPerson(){return this.isSpectatingEntity()?!1:n.perspective==="third_person_back"||n.perspective==="third_person_front"}}),G6=()=>({reactive:is()}),ns=(n,e,t)=>({...e,"minecraft:date":new Date});E();x();k();R();E();x();k();R();import*as Q5 from"three";import{Vec3 as ml}from"vec3";E();x();k();R();import{proxy as N6,getVersion as os,subscribe as as}from"valtio";import{Vec3 as vs}from"vec3";function ls(n,e){let t=e??globalThis;return t.addEventListener("message",r=>{let{type:i,args:s,msgId:o}=r.data;if(n[i]){let a=n[i](...s);a instanceof Promise&&a.then(v=>{t.postMessage({type:"result",msgId:o,args:[v]})})}}),null}var cs=(n,e=!0)=>{let t=0;return new Proxy({},{get(r,i){return i==="transfer"?(...s)=>new Proxy({},{get(o,a){return(...v)=>{n.postMessage({type:a,args:v},s)}}}):(...s)=>{let o=t++,a=e?s.filter(v=>v instanceof ArrayBuffer||v instanceof MessagePort||typeof ImageBitmap<"u"&&v instanceof ImageBitmap||typeof OffscreenCanvas<"u"&&v instanceof OffscreenCanvas||typeof ImageData<"u"&&v instanceof ImageData):[];return n.postMessage({type:i,msgId:o,args:s},a),{then(v){let l=({data:c})=>{c.type==="result"&&c.msgId===o&&(v(c.args[0]),n.removeEventListener("message",l))};n.addEventListener("message",l)}}}}})};var ds=(n,e,t,r)=>{try{t.postMessage({type:"sync",syncId:n,value:d1(e)}),p5.toWorker++,globalThis.debugSyncMessagesOutgoing??(globalThis.debugSyncMessagesOutgoing=0),globalThis.debugSyncMessagesOutgoing++}catch{g5(e)}},p5={toWorker:0,fromWorker:0};typeof window<"u"&&setInterval(()=>{globalThis.debugWorkerSyncStats={...p5},p5.toWorker=0,p5.fromWorker=0},1e3);var W6=()=>Math.random().toString(36).slice(2,15)+Math.random().toString(36).slice(2,15),ss=(n,e,t,r,i)=>{if(!n.__syncToWorker&&!n.__syncFromWorker&&!r)return;let s=W6();if(n.__syncId=s,n.__syncToWorker||r){let o=()=>{ds(s,e,t,`toWorker:${i}`)};r&&as(e,o);let a=n.__syncToWorkerInterval??0;a>0&&setInterval(o,a)}e.__syncFromWorker&&t.addEventListener("message",o=>{o.data.type==="sync"&&o.data.syncId===s&&(p5.fromWorker++,Object.assign(e,o.data.value))})},d1=n=>{if(os(n)===void 0)return n;if(Array.isArray(n))return n.map(d1);if(typeof n=="object"&&n!==null){let e={};for(let t in n)Object.prototype.hasOwnProperty.call(n,t)&&(e[t]=d1(n[t]));return e}return n},u1=(n,e,t=!0,r=!0,i=!1)=>{var a,v;let s=n,o={};for(let l in n)if(Object.prototype.hasOwnProperty.call(n,l)){if(t&&typeof n[l]=="function")continue;if(n[l]instanceof Date||n[l]instanceof RegExp||n[l]instanceof Map||n[l]instanceof WeakMap||n[l]instanceof WeakSet,n[l]instanceof Set){o[l]=[...n[l]],o[l].__restorer="Set";continue}if(n[l]instanceof vs){o[l]={x:n[l].x,y:n[l].y,z:n[l].z},o[l].__restorer="Vec3";continue}if(o[l]=n[l],typeof n[l]=="object"&&n[l]!==null){if(n[l].prepareForTransfer){o[l]=n[l].prepareForTransfer(e);continue}let c=os(n[l])!==void 0;o[l]=c?d1(n[l]):n[l];let d=n[l].__syncToWorker!==!1&&!i&&c&&!n[l].__syncFromWorker;if((a=o[l]).__syncToWorker??(a.__syncToWorker=d),c&&((v=o[l]).__valtio??(v.__valtio=!0)),o[l].__syncToWorker&&c){ss(o[l],s[l],e,!0,l);continue}ss(o[l],s[l],e,!1,l),o[l]=u1(o[l],e,t,!1,c)}}return o},g5=(n,e=[])=>{for(let t in n)if(Object.prototype.hasOwnProperty.call(n,t)){if(!n[t])continue;typeof n[t]=="object"&&n[t]!==null&&g5(n[t],[...e,t]);try{structuredClone(n[t])}catch{}}},V6=(n,e,t)=>{if(!n.__syncId)return;let r=n.__syncId;if(n.__syncToWorker&&e.addEventListener("message",i=>{i.data.type==="sync"&&i.data.syncId===r&&Object.assign(n,i.data.value)}),n.__syncFromWorker){let i=()=>{ds(r,n,e,`fromWorker:${t}`)};n.__valtio&&as(n,i);let s=n.__syncFromWorkerInterval??0;s>0&&setInterval(i,s)}},j6=[{restorerName:"Set",restoreTransferred(n,e){return new Set(n)}},{restorerName:"Vec3",restoreTransferred(n,e){return new vs(n.x,n.y,n.z)}}];var f1=(n,e,t,r=!0)=>{let i=[...j6,...e];for(let s in n)if(Object.prototype.hasOwnProperty.call(n,s)){if(!n[s])continue;if(typeof n[s]=="object"&&n[s]!==null&&f1(n[s],i,t,r),n[s].__restorer){let o=i.find(a=>a.restorerName?a.restorerName===n[s].__restorer:a.name===n[s].__restorer);if(o)n[s]=o.restoreTransferred(n[s],t);else{let a=new Error(`Restorer ${n[s].__restorer} not found`);if(typeof r=="function")r(a);else if(r)throw a}}n[s].__valtio&&(n[s]=N6(n[s])),V6(n[s],t,s)}return n};E();x();k();R();var h1=class{constructor(e){this.nonReactiveState=e;u(this,"events",[]);u(this,"frozenEvents",[]);u(this,"lastSecondEvents",[]);u(this,"currentFrameStartTime",null);u(this,"lastInteractionTime",0);u(this,"lastSecondUpdateTime",0);u(this,"timeWindowMs",5e3);u(this,"lastSecondWindowMs",1e3);u(this,"maxEvents",500);u(this,"lastSecondUpdateInterval",1e3);this.nonReactiveState.renderer||(this.nonReactiveState.renderer={timeline:{live:[],frozen:[],lastSecond:[]}}),this.nonReactiveState.renderer.timeline||(this.nonReactiveState.renderer.timeline={live:[],frozen:[],lastSecond:[]}),setInterval(()=>{this.updateLastSecondTimeline()},this.lastSecondUpdateInterval)}markFrameStart(){this.currentFrameStartTime=performance.now(),this.addEvent({type:"frameStart",timestamp:this.currentFrameStartTime})}markFrameEnd(){if(!this.currentFrameStartTime)return;let e=performance.now(),t=e-this.currentFrameStartTime;this.addEvent({type:"frameEnd",timestamp:e,duration:t}),this.currentFrameStartTime=null}markCameraUpdate(e){if(!e)return;let t=performance.now();this.lastInteractionTime=t,this.addEvent({type:"cameraUpdate",timestamp:t}),this.frozenEvents=[...this.events],this.trimEvents(this.frozenEvents),this.syncFrozenEvents()}markFrameDisplay(){this.addEvent({type:"frameDisplay",timestamp:performance.now()})}addEvent(e){this.events.push(e),this.lastSecondEvents.push(e),this.trimEvents(this.events),this.trimLastSecondEvents(),this.syncLiveEvents()}trimEvents(e){let r=performance.now()-this.timeWindowMs;for(;e.length>0&&e[0].timestamp<r;)e.shift();e.length>this.maxEvents&&e.splice(0,e.length-this.maxEvents)}trimLastSecondEvents(){let t=performance.now()-this.lastSecondWindowMs;for(;this.lastSecondEvents.length>0&&this.lastSecondEvents[0].timestamp<t;)this.lastSecondEvents.shift()}updateLastSecondTimeline(){let e=performance.now();e-this.lastSecondUpdateTime<this.lastSecondUpdateInterval||(this.lastSecondUpdateTime=e,this.trimLastSecondEvents(),this.syncLastSecondEvents())}syncLiveEvents(){this.nonReactiveState.renderer.timeline.live=[...this.events]}syncFrozenEvents(){this.nonReactiveState.renderer.timeline.frozen=[...this.frozenEvents]}syncLastSecondEvents(){this.nonReactiveState.renderer.timeline.lastSecond=[...this.lastSecondEvents]}clear(){this.events=[],this.frozenEvents=[],this.lastSecondEvents=[],this.syncLiveEvents(),this.syncFrozenEvents(),this.syncLastSecondEvents()}};E();x();k();R();import*as Q from"three";import{Vec3 as Ne}from"vec3";import Yv from"prismarine-chat";E();x();k();R();var H0=Object.freeze({Linear:Object.freeze({None:function(n){return n},In:function(n){return this.None(n)},Out:function(n){return this.None(n)},InOut:function(n){return this.None(n)}}),Quadratic:Object.freeze({In:function(n){return n*n},Out:function(n){return n*(2-n)},InOut:function(n){return(n*=2)<1?.5*n*n:-.5*(--n*(n-2)-1)}}),Cubic:Object.freeze({In:function(n){return n*n*n},Out:function(n){return--n*n*n+1},InOut:function(n){return(n*=2)<1?.5*n*n*n:.5*((n-=2)*n*n+2)}}),Quartic:Object.freeze({In:function(n){return n*n*n*n},Out:function(n){return 1- --n*n*n*n},InOut:function(n){return(n*=2)<1?.5*n*n*n*n:-.5*((n-=2)*n*n*n-2)}}),Quintic:Object.freeze({In:function(n){return n*n*n*n*n},Out:function(n){return--n*n*n*n*n+1},InOut:function(n){return(n*=2)<1?.5*n*n*n*n*n:.5*((n-=2)*n*n*n*n+2)}}),Sinusoidal:Object.freeze({In:function(n){return 1-Math.sin((1-n)*Math.PI/2)},Out:function(n){return Math.sin(n*Math.PI/2)},InOut:function(n){return .5*(1-Math.sin(Math.PI*(.5-n)))}}),Exponential:Object.freeze({In:function(n){return n===0?0:Math.pow(1024,n-1)},Out:function(n){return n===1?1:1-Math.pow(2,-10*n)},InOut:function(n){return n===0?0:n===1?1:(n*=2)<1?.5*Math.pow(1024,n-1):.5*(-Math.pow(2,-10*(n-1))+2)}}),Circular:Object.freeze({In:function(n){return 1-Math.sqrt(1-n*n)},Out:function(n){return Math.sqrt(1- --n*n)},InOut:function(n){return(n*=2)<1?-.5*(Math.sqrt(1-n*n)-1):.5*(Math.sqrt(1-(n-=2)*n)+1)}}),Elastic:Object.freeze({In:function(n){return n===0?0:n===1?1:-Math.pow(2,10*(n-1))*Math.sin((n-1.1)*5*Math.PI)},Out:function(n){return n===0?0:n===1?1:Math.pow(2,-10*n)*Math.sin((n-.1)*5*Math.PI)+1},InOut:function(n){return n===0?0:n===1?1:(n*=2,n<1?-.5*Math.pow(2,10*(n-1))*Math.sin((n-1.1)*5*Math.PI):.5*Math.pow(2,-10*(n-1))*Math.sin((n-1.1)*5*Math.PI)+1)}}),Back:Object.freeze({In:function(n){var e=1.70158;return n===1?1:n*n*((e+1)*n-e)},Out:function(n){var e=1.70158;return n===0?0:--n*n*((e+1)*n+e)+1},InOut:function(n){var e=2.5949095;return(n*=2)<1?.5*(n*n*((e+1)*n-e)):.5*((n-=2)*n*((e+1)*n+e)+2)}}),Bounce:Object.freeze({In:function(n){return 1-H0.Bounce.Out(1-n)},Out:function(n){return n<.36363636363636365?7.5625*n*n:n<.7272727272727273?7.5625*(n-=.5454545454545454)*n+.75:n<.9090909090909091?7.5625*(n-=.8181818181818182)*n+.9375:7.5625*(n-=.9545454545454546)*n+.984375},InOut:function(n){return n<.5?H0.Bounce.In(n*2)*.5:H0.Bounce.Out(n*2-1)*.5+.5}}),generatePow:function(n){return n===void 0&&(n=4),n=n<Number.EPSILON?Number.EPSILON:n,n=n>1e4?1e4:n,{In:function(e){return Math.pow(e,n)},Out:function(e){return 1-Math.pow(1-e,n)},InOut:function(e){return e<.5?Math.pow(e*2,n)/2:(1-Math.pow(2-e*2,n))/2+.5}}}}),b5=function(){return performance.now()},St=function(){function n(){this._tweens={},this._tweensAddedDuringUpdate={}}return n.prototype.getAll=function(){var e=this;return Object.keys(this._tweens).map(function(t){return e._tweens[t]})},n.prototype.removeAll=function(){this._tweens={}},n.prototype.add=function(e){this._tweens[e.getId()]=e,this._tweensAddedDuringUpdate[e.getId()]=e},n.prototype.remove=function(e){delete this._tweens[e.getId()],delete this._tweensAddedDuringUpdate[e.getId()]},n.prototype.update=function(e,t){e===void 0&&(e=b5()),t===void 0&&(t=!1);var r=Object.keys(this._tweens);if(r.length===0)return!1;for(;r.length>0;){this._tweensAddedDuringUpdate={};for(var i=0;i<r.length;i++){var s=this._tweens[r[i]],o=!t;s&&s.update(e,o)===!1&&!t&&delete this._tweens[r[i]]}r=Object.keys(this._tweensAddedDuringUpdate)}return!0},n}(),Mt={Linear:function(n,e){var t=n.length-1,r=t*e,i=Math.floor(r),s=Mt.Utils.Linear;return e<0?s(n[0],n[1],r):e>1?s(n[t],n[t-1],t-r):s(n[i],n[i+1>t?t:i+1],r-i)},Bezier:function(n,e){for(var t=0,r=n.length-1,i=Math.pow,s=Mt.Utils.Bernstein,o=0;o<=r;o++)t+=i(1-e,r-o)*i(e,o)*n[o]*s(r,o);return t},CatmullRom:function(n,e){var t=n.length-1,r=t*e,i=Math.floor(r),s=Mt.Utils.CatmullRom;return n[0]===n[t]?(e<0&&(i=Math.floor(r=t*(1+e))),s(n[(i-1+t)%t],n[i],n[(i+1)%t],n[(i+2)%t],r-i)):e<0?n[0]-(s(n[0],n[0],n[1],n[1],-r)-n[0]):e>1?n[t]-(s(n[t],n[t],n[t-1],n[t-1],r-t)-n[t]):s(n[i?i-1:0],n[i],n[t<i+1?t:i+1],n[t<i+2?t:i+2],r-i)},Utils:{Linear:function(n,e,t){return(e-n)*t+n},Bernstein:function(n,e){var t=Mt.Utils.Factorial;return t(n)/t(e)/t(n-e)},Factorial:function(){var n=[1];return function(e){var t=1;if(n[e])return n[e];for(var r=e;r>1;r--)t*=r;return n[e]=t,t}}(),CatmullRom:function(n,e,t,r,i){var s=(t-n)*.5,o=(r-e)*.5,a=i*i,v=i*a;return(2*e-2*t+s+o)*v+(-3*e+3*t-2*s-o)*a+s*i+e}}},us=function(){function n(){}return n.nextId=function(){return n._nextId++},n._nextId=0,n}(),Fr=new St,F0=function(){function n(e,t){t===void 0&&(t=Fr),this._object=e,this._group=t,this._isPaused=!1,this._pauseStart=0,this._valuesStart={},this._valuesEnd={},this._valuesStartRepeat={},this._duration=1e3,this._isDynamic=!1,this._initialRepeat=0,this._repeat=0,this._yoyo=!1,this._isPlaying=!1,this._reversed=!1,this._delayTime=0,this._startTime=0,this._easingFunction=H0.Linear.None,this._interpolationFunction=Mt.Linear,this._chainedTweens=[],this._onStartCallbackFired=!1,this._onEveryStartCallbackFired=!1,this._id=us.nextId(),this._isChainStopped=!1,this._propertiesAreSetUp=!1,this._goToEnd=!1}return n.prototype.getId=function(){return this._id},n.prototype.isPlaying=function(){return this._isPlaying},n.prototype.isPaused=function(){return this._isPaused},n.prototype.to=function(e,t){if(t===void 0&&(t=1e3),this._isPlaying)throw new Error("Can not call Tween.to() while Tween is already started or paused. Stop the Tween first.");return this._valuesEnd=e,this._propertiesAreSetUp=!1,this._duration=t,this},n.prototype.duration=function(e){return e===void 0&&(e=1e3),this._duration=e,this},n.prototype.dynamic=function(e){return e===void 0&&(e=!1),this._isDynamic=e,this},n.prototype.start=function(e,t){if(e===void 0&&(e=b5()),t===void 0&&(t=!1),this._isPlaying)return this;if(this._group&&this._group.add(this),this._repeat=this._initialRepeat,this._reversed){this._reversed=!1;for(var r in this._valuesStartRepeat)this._swapEndStartRepeatValues(r),this._valuesStart[r]=this._valuesStartRepeat[r]}if(this._isPlaying=!0,this._isPaused=!1,this._onStartCallbackFired=!1,this._onEveryStartCallbackFired=!1,this._isChainStopped=!1,this._startTime=e,this._startTime+=this._delayTime,!this._propertiesAreSetUp||t){if(this._propertiesAreSetUp=!0,!this._isDynamic){var i={};for(var s in this._valuesEnd)i[s]=this._valuesEnd[s];this._valuesEnd=i}this._setupProperties(this._object,this._valuesStart,this._valuesEnd,this._valuesStartRepeat,t)}return this},n.prototype.startFromCurrentValues=function(e){return this.start(e,!0)},n.prototype._setupProperties=function(e,t,r,i,s){for(var o in r){var a=e[o],v=Array.isArray(a),l=v?"array":typeof a,c=!v&&Array.isArray(r[o]);if(!(l==="undefined"||l==="function")){if(c){var d=r[o];if(d.length===0)continue;for(var f=[a],m=0,g=d.length;m<g;m+=1){var b=this._handleRelativeValue(a,d[m]);if(isNaN(b)){c=!1;break}f.push(b)}c&&(r[o]=f)}if((l==="object"||v)&&a&&!c){t[o]=v?[]:{};var w=a;for(var y in w)t[o][y]=w[y];i[o]=v?[]:{};var d=r[o];if(!this._isDynamic){var A={};for(var y in d)A[y]=d[y];r[o]=d=A}this._setupProperties(w,t[o],d,i[o],s)}else(typeof t[o]>"u"||s)&&(t[o]=a),v||(t[o]*=1),c?i[o]=r[o].slice().reverse():i[o]=t[o]||0}}},n.prototype.stop=function(){return this._isChainStopped||(this._isChainStopped=!0,this.stopChainedTweens()),this._isPlaying?(this._group&&this._group.remove(this),this._isPlaying=!1,this._isPaused=!1,this._onStopCallback&&this._onStopCallback(this._object),this):this},n.prototype.end=function(){return this._goToEnd=!0,this.update(1/0),this},n.prototype.pause=function(e){return e===void 0&&(e=b5()),this._isPaused||!this._isPlaying?this:(this._isPaused=!0,this._pauseStart=e,this._group&&this._group.remove(this),this)},n.prototype.resume=function(e){return e===void 0&&(e=b5()),!this._isPaused||!this._isPlaying?this:(this._isPaused=!1,this._startTime+=e-this._pauseStart,this._pauseStart=0,this._group&&this._group.add(this),this)},n.prototype.stopChainedTweens=function(){for(var e=0,t=this._chainedTweens.length;e<t;e++)this._chainedTweens[e].stop();return this},n.prototype.group=function(e){return e===void 0&&(e=Fr),this._group=e,this},n.prototype.delay=function(e){return e===void 0&&(e=0),this._delayTime=e,this},n.prototype.repeat=function(e){return e===void 0&&(e=0),this._initialRepeat=e,this._repeat=e,this},n.prototype.repeatDelay=function(e){return this._repeatDelayTime=e,this},n.prototype.yoyo=function(e){return e===void 0&&(e=!1),this._yoyo=e,this},n.prototype.easing=function(e){return e===void 0&&(e=H0.Linear.None),this._easingFunction=e,this},n.prototype.interpolation=function(e){return e===void 0&&(e=Mt.Linear),this._interpolationFunction=e,this},n.prototype.chain=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return this._chainedTweens=e,this},n.prototype.onStart=function(e){return this._onStartCallback=e,this},n.prototype.onEveryStart=function(e){return this._onEveryStartCallback=e,this},n.prototype.onUpdate=function(e){return this._onUpdateCallback=e,this},n.prototype.onRepeat=function(e){return this._onRepeatCallback=e,this},n.prototype.onComplete=function(e){return this._onCompleteCallback=e,this},n.prototype.onStop=function(e){return this._onStopCallback=e,this},n.prototype.update=function(e,t){if(e===void 0&&(e=b5()),t===void 0&&(t=!0),this._isPaused)return!0;var r,i,s=this._startTime+this._duration;if(!this._goToEnd&&!this._isPlaying){if(e>s)return!1;t&&this.start(e,!0)}if(this._goToEnd=!1,e<this._startTime)return!0;this._onStartCallbackFired===!1&&(this._onStartCallback&&this._onStartCallback(this._object),this._onStartCallbackFired=!0),this._onEveryStartCallbackFired===!1&&(this._onEveryStartCallback&&this._onEveryStartCallback(this._object),this._onEveryStartCallbackFired=!0),i=(e-this._startTime)/this._duration,i=this._duration===0||i>1?1:i;var o=this._easingFunction(i);if(this._updateProperties(this._object,this._valuesStart,this._valuesEnd,o),this._onUpdateCallback&&this._onUpdateCallback(this._object,i),i===1)if(this._repeat>0){isFinite(this._repeat)&&this._repeat--;for(r in this._valuesStartRepeat)!this._yoyo&&typeof this._valuesEnd[r]=="string"&&(this._valuesStartRepeat[r]=this._valuesStartRepeat[r]+parseFloat(this._valuesEnd[r])),this._yoyo&&this._swapEndStartRepeatValues(r),this._valuesStart[r]=this._valuesStartRepeat[r];return this._yoyo&&(this._reversed=!this._reversed),this._repeatDelayTime!==void 0?this._startTime=e+this._repeatDelayTime:this._startTime=e+this._delayTime,this._onRepeatCallback&&this._onRepeatCallback(this._object),this._onEveryStartCallbackFired=!1,!0}else{this._onCompleteCallback&&this._onCompleteCallback(this._object);for(var a=0,v=this._chainedTweens.length;a<v;a++)this._chainedTweens[a].start(this._startTime+this._duration,!1);return this._isPlaying=!1,!1}return!0},n.prototype._updateProperties=function(e,t,r,i){for(var s in r)if(t[s]!==void 0){var o=t[s]||0,a=r[s],v=Array.isArray(e[s]),l=Array.isArray(a),c=!v&&l;c?e[s]=this._interpolationFunction(a,i):typeof a=="object"&&a?this._updateProperties(e[s],o,a,i):(a=this._handleRelativeValue(o,a),typeof a=="number"&&(e[s]=o+(a-o)*i))}},n.prototype._handleRelativeValue=function(e,t){return typeof t!="string"?t:t.charAt(0)==="+"||t.charAt(0)==="-"?e+parseFloat(t):parseFloat(t)},n.prototype._swapEndStartRepeatValues=function(e){var t=this._valuesStartRepeat[e],r=this._valuesEnd[e];typeof r=="string"?this._valuesStartRepeat[e]=this._valuesStartRepeat[e]+parseFloat(r):this._valuesStartRepeat[e]=this._valuesEnd[e],this._valuesEnd[e]=t},n}();var mh=us.nextId,be=Fr,ph=be.getAll.bind(be),gh=be.removeAll.bind(be),bh=be.add.bind(be),yh=be.remove.bind(be),fs=be.update.bind(be);E();x();k();R();var Y6=(n,e)=>{try{return JSON.parse(n)}catch{return null}},Q6={black:"#000000",dark_blue:"#0000AA",dark_green:"#00AA00",dark_aqua:"#00AAAA",dark_red:"#AA0000",dark_purple:"#AA00AA",gold:"#FFAA00",gray:"#AAAAAA",dark_gray:"#555555",blue:"#5555FF",green:"#55FF55",aqua:"#55FFFF",red:"#FF5555",light_purple:"#FF55FF",yellow:"#FFFF55",white:"#FFFFFF"},m1=(n,e,t,r=s=>{},i=(s,o)=>V0(s,o))=>{let a=[16,9],v=a[0]-a[1],l=v/16,c="front_text"in n?n.front_text.messages:[n.Text1,n.Text2,n.Text3,n.Text4];if(!c.some(g=>g!=="null"))return;let d=i(16*40,v*40),f=d.getContext("2d");r(f);let m=("front_text"in n?n.front_text.color:n.Color)||"black";for(let[g,b]of c.slice(0,4).entries())b!=="null"&&Dr(b,t,d,64,m,64*(g+1)+(e?0:-8));return d},Dr=(n,e,t,r,i,s=0)=>{let o=!1,a=typeof n=="string"&&(n?.startsWith("{")||n?.startsWith('"'))?Y6(n??'""',"sign text"):n;if(!a||typeof a!="object"&&typeof a!="string")return;let v=t.getContext("2d");if(!v)throw new Error("Could not get 2d context");v.imageSmoothingEnabled=!1,v.font=`${r}px mojangles`;let l=new e(a),c=[],d=!1,f="",m=s,g=[],b=(C,M)=>{C.text!==null&&C.text!==void 0&&C.text;let S=C.text===null||C.text===void 0?void 0:String(C.text),H={color:C.color??M?.color,underlined:C.underlined??M?.underlined,strikethrough:C.strikethrough??M?.strikethrough,bold:C.bold??M?.bold,italic:C.italic??M?.italic};if(d=d||H.underlined||H.strikethrough||!1,S?.includes(`
|
|
285
|
+
`;tr=6,ht={LX_BITS:4,LY_BITS:4,LZ_BITS:4,FACE_BITS:3,TINT_BITS:8,AO_BITS_PER_CORNER:2,NUM_CORNERS:4,LX_SHIFT:0,LY_SHIFT:4,LZ_SHIFT:8,FACE_SHIFT:12,TINT_SHIFT:15,AO_SHIFT:23,TRANSPARENT_SHIFT:31},K3={TEX_INDEX_BITS:12,DIAGONAL_FLAG_SHIFT:12,SECTION_Y_SHIFT:13,SECTION_Y_BITS:5,EMPTY_SHIFT:18,SPARE_BITS:13}});var rr,J3=ee(()=>{"use strict";E();x();k();R();rr=class{constructor(e){u(this,"atlasWidth");u(this,"atlasHeight");u(this,"tileSize");u(this,"tilesPerRow");u(this,"maxTiles");u(this,"valid");this.atlasWidth=e.width,this.atlasHeight=e.height,this.tileSize=e.tileSize,this.tilesPerRow=Math.floor(this.atlasWidth/this.tileSize),this.maxTiles=this.tilesPerRow*Math.floor(this.atlasHeight/this.tileSize),this.valid=this.atlasWidth===1024&&this.atlasHeight===1024&&this.tileSize===16&&this.maxTiles<=4096}isValid(){return this.valid}getTilesPerRow(){return this.tilesPerRow}tileIndexFromPixelCoords(e,t){if(!this.valid)return-1;let r=Math.floor(e/this.tileSize),i=Math.floor(t/this.tileSize);if(r<0||r>=this.tilesPerRow||i<0)return-1;let s=i*this.tilesPerRow+r;return s>=this.maxTiles?-1:s}tileIndexFromTextureEntry(e){return!this.valid||e.su!==this.tileSize||e.sv!==this.tileSize?-1:this.tileIndexFromPixelCoords(e.u,e.v)}tileIndexFromTextureName(e,t){if(!this.valid)return-1;let r=t.textures[e];if(!r&&e.includes(":")&&(r=t.textures[e.split(":")[1]]),!r&&e.includes("/")&&(r=t.textures[e.split("/")[1]]),r||(r=t.textures[`block/${e}`]),!r){let i=e.replace(/^block\//,"");r=t.textures[i]}return r?this.tileIndexFromTextureEntry(r):-1}}});import*as de from"three";var ir,q3=ee(()=>{"use strict";E();x();k();R();ir=class n{constructor(){u(this,"entries",[{r:1,g:1,b:1}]);u(this,"colorToIndex",new Map);u(this,"categoryBiomeToIndex",new Map);u(this,"texture",null);u(this,"ready",!1)}packColor(e,t,r){let i=Math.round(e*255),s=Math.round(t*255),o=Math.round(r*255);return i<<16|s<<8|o}add(e,t,r,i,s){let o=this.packColor(e,t,r),a=`${i}:${s}`,v=this.categoryBiomeToIndex.get(a);if(v!==void 0)return v;let l=this.colorToIndex.get(o);if(l!==void 0)return this.categoryBiomeToIndex.set(a,l),l;let c=this.entries.length;return this.entries.push({r:e,g:t,b:r}),this.colorToIndex.set(o,c),this.categoryBiomeToIndex.set(a,c),c}getTintIndex(e,t,r,i){return e===void 0?0:e===0?t==="redstone_wire"?this.categoryBiomeToIndex.get(`redstone:${r.power}`)??this.categoryBiomeToIndex.get("redstone:0")??0:t==="birch_leaves"||t==="spruce_leaves"||t==="lily_pad"?this.categoryBiomeToIndex.get(`constant:${t}`)??this.categoryBiomeToIndex.get("constant:default")??0:t.includes("leaves")||t==="vine"?this.categoryBiomeToIndex.get(`foliage:${i}`)??this.categoryBiomeToIndex.get("foliage:plains")??0:this.categoryBiomeToIndex.get(`grass:${i}`)??this.categoryBiomeToIndex.get("grass:plains")??0:0}getEntry(e){return this.entries[e]??this.entries[0]}get size(){return this.entries.length}buildTextureData(){let e=new Float32Array(1024);for(let t=0;t<this.entries.length&&t<256;t++){let r=this.entries[t];e[t*4]=r.r,e[t*4+1]=r.g,e[t*4+2]=r.b,e[t*4+3]=1}return e}createTexture(){this.texture&&(this.texture.dispose(),this.texture=null,this.ready=!1);let e=this.buildTextureData(),t=new de.DataTexture(e,256,1,de.RGBAFormat,de.FloatType);return t.minFilter=de.NearestFilter,t.magFilter=de.NearestFilter,t.wrapS=de.ClampToEdgeWrapping,t.wrapT=de.ClampToEdgeWrapping,t.needsUpdate=!0,this.texture=t,this.ready=!0,t}getTexture(){return this.texture}isReady(){return this.ready}static fromTintsData(e){let t=new n;function r(i){let s=(i>>16&255)/255,o=(i>>8&255)/255,a=(i&255)/255;return[s,o,a]}if(e.grass){let i=r(e.grass.default);for(let{keys:s,color:o}of e.grass.data??[]){let a=r(o);for(let v of s)t.add(a[0],a[1],a[2],"grass",v)}t.add(i[0],i[1],i[2],"grass","plains")}if(e.foliage){let i=r(e.foliage.default);for(let{keys:s,color:o}of e.foliage.data??[]){let a=r(o);for(let v of s)t.add(a[0],a[1],a[2],"foliage",v)}t.add(i[0],i[1],i[2],"foliage","plains")}if(e.redstone){let i=r(e.redstone.default);for(let{keys:s,color:o}of e.redstone.data??[]){let a=r(o);for(let v of s)t.add(a[0],a[1],a[2],"redstone",v)}t.add(i[0],i[1],i[2],"redstone","0")}if(e.constant){let i=r(e.constant.default);for(let{keys:s,color:o}of e.constant.data??[]){let a=r(o);for(let v of s)t.add(a[0],a[1],a[2],"constant",v)}t.add(i[0],i[1],i[2],"constant","default")}return t}}});import Z3 from"mc-assets/dist/blocksAtlases.json";function Av(){let n=globalThis.loadedData?.tints;if(!n)throw new Error("shaderCubeBridge: globalThis.loadedData.tints is not available yet");return n}function or(){if(nr||(nr=ir.fromTintsData(Av()),nr.createTexture()),!Gi){let n=Z3.latest??Z3;Gi=new rr({width:n.width,height:n.height,tileSize:n.tileSize??16,suSv:n.suSv??16,textures:n.textures??{}})}return{tintPalette:nr,textureIndexMapping:Gi}}function X3(){return 1<<K3.EMPTY_SHIFT>>>0}var sr,nr,Gi,Qt=ee(()=>{"use strict";E();x();k();R();mt();J3();q3();sr=4,nr=null,Gi=null});import*as B0 from"three";function Ev(n,e){let t=new B0.InstancedBufferGeometry,r=new Float32Array(tr*3);t.setAttribute("position",new B0.BufferAttribute(r,3));let i=new Uint32Array(e),s=new Uint32Array(e),o=new Uint32Array(e),a=new Uint32Array(e),v=sr;for(let l=0;l<e;l++)i[l]=n[l*v],s[l]=n[l*v+1],o[l]=n[l*v+2],a[l]=n[l*v+3];return t.setAttribute("a_w0",new B0.InstancedBufferAttribute(i,1)),t.setAttribute("a_w1",new B0.InstancedBufferAttribute(s,1)),t.setAttribute("a_w2",new B0.InstancedBufferAttribute(o,1)),t.setAttribute("a_w3",new B0.InstancedBufferAttribute(a,1)),t.instanceCount=e,t.boundingBox=new B0.Box3(new B0.Vector3(-8,-8,-8),new B0.Vector3(8,8,8)),t.boundingSphere=new B0.Sphere(new B0.Vector3(0,0,0),Math.sqrt(3*8**2)),t}function xv(n){n.raycast=(e,t)=>{let{geometry:r}=n;if(!r.boundingBox||($3.copy(r.boundingBox).applyMatrix4(n.matrixWorld),!e.ray.intersectBox($3,Ni)))return;let i=e.ray.origin.distanceTo(Ni);t.push({distance:i,point:Ni.clone(),object:n})}}function ar(n,e){let t=Ev(n.words,n.count),r=new B0.Mesh(t,e);return r.name="shaderMesh",r.matrixAutoUpdate=!1,r.frustumCulled=!1,xv(r),r}function Wi(n){n.geometry.dispose()}var $3,Ni,Vi=ee(()=>{"use strict";E();x();k();R();mt();Qt();$3=new B0.Box3,Ni=new B0.Vector3});var sa={};Z5(sa,{applyWorldGeometryExport:()=>Tv,createMeshesFromExport:()=>ia,downloadWorldGeometry:()=>ji,exportWorldGeometry:()=>ta,loadTextureFromDataUrl:()=>na,loadWorldGeometryFromUrl:()=>Rv});import*as P0 from"three";function ta(n,e,t,r=!1){let i=[];for(let[o,a]of Object.entries(n.sectionObjects)){let v=a.children.find(w=>w.name==="mesh");if(!v?.geometry)continue;let{geometry:l}=v,c=l.getAttribute("position"),d=l.getAttribute("normal"),f=l.getAttribute("color"),m=l.getAttribute("uv"),g=l.index;if(!c||!g)continue;let b=n.sceneOrigin.getWorldPosition(v);i.push({key:o,position:{x:b?.x??n.sceneOrigin.toWorldX(v.position.x),y:b?.y??n.sceneOrigin.toWorldY(v.position.y),z:b?.z??n.sceneOrigin.toWorldZ(v.position.z)},geometry:{positions:[...c.array],normals:d?[...d.array]:[],colors:f?[...f.array]:[],uvs:m?[...m.array]:[],indices:[...g.array]}})}let s={version:n.version??"unknown",exportedAt:new Date().toISOString(),camera:{position:e,rotation:t},sections:i};if(r&&n.material.map){let o=document.createElement("canvas"),a=n.material.map,{image:v}=a;v&&(o.width=v.width,o.height=v.height,o.getContext("2d").drawImage(v,0,0),s.textureAtlasDataUrl=o.toDataURL("image/png"))}return s}function ji(n,e,t,r="world-geometry.json",i=!1){let s=ta(n,e,t,i),o=JSON.stringify(s),a=new Blob([o],{type:"application/json"}),v=URL.createObjectURL(a),l=document.createElement("a");l.href=v,l.download=r,l.click(),URL.revokeObjectURL(v)}async function Rv(n){let e=await fetch(n);if(!e.ok)throw new Error(`Failed to fetch world geometry: ${e.statusText}`);return e.json()}function ra(n){let e=n.map??n.map;if(!e)return null;let t=er();t.uniforms.u_atlas.value=e;let{tintPalette:r}=or();return r.isReady()||r.createTexture(),t.uniforms.u_tintPalette.value=r.getTexture(),t}function ia(n,e,t){let r=[],i=t??ra(e);for(let s of n.sections){let o=new P0.Group;if(o.name="chunk",s.geometry.positions.length>0&&s.geometry.indices.length>0){let l=new P0.BufferGeometry;l.setAttribute("position",new P0.Float32BufferAttribute(s.geometry.positions,3)),s.geometry.normals.length&&l.setAttribute("normal",new P0.Float32BufferAttribute(s.geometry.normals,3)),s.geometry.colors.length&&l.setAttribute("color",new P0.Float32BufferAttribute(s.geometry.colors,3)),s.geometry.uvs.length&&l.setAttribute("uv",new P0.Float32BufferAttribute(s.geometry.uvs,2));let d=Math.max(...s.geometry.indices)>65535?Uint32Array:Uint16Array;l.setIndex(new P0.BufferAttribute(new d(s.geometry.indices),1));let f=new P0.Mesh(l,e);f.position.set(s.position.x,s.position.y,s.position.z),f.name="mesh",o.add(f)}let v=s.shaderCubes;if(v&&v.count>0&&i){let l=ar(v,i);l.position.set(s.position.x,s.position.y,s.position.z),o.add(l)}o.children.length>0&&r.push(o)}return r}async function na(n){return new Promise((e,t)=>{let r=new Image;r.onload=()=>{let i=new P0.Texture(r);i.magFilter=P0.NearestFilter,i.minFilter=P0.NearestFilter,i.needsUpdate=!0,i.flipY=!1,e(i)},r.onerror=t,r.src=n})}async function Tv(n,e){let{scene:t,renderUpdateEmitter:r,material:i}=n,s=t.getObjectByName(ea);s&&(t.remove(s),kv(s));let o=!!e.textureAtlasDataUrl,a;if(o&&e.textureAtlasDataUrl){let d=await na(e.textureAtlasDataUrl);a=new P0.MeshLambertMaterial({map:d,vertexColors:!0,transparent:!0,alphaTest:.1}),a.name="geometry-export-material"}else a=i;let v=e.sections.some(d=>(d.shaderCubes?.count??0)>0)?ra(a):null,l=ia(e,a,v),c=new P0.Group;c.name=ea,o&&(c.userData.geometryExportMaterial=a);for(let d of l)c.add(d);return t.add(c),r.emit("update"),l.length}var ea,kv,Yi=ee(()=>{"use strict";E();x();k();R();Qt();mt();Vi();ea="geometry-export-root";kv=n=>{n.traverse(t=>{t.isMesh&&t.geometry?.dispose()});let e=n.userData?.geometryExportMaterial;e&&(e.map?.dispose?.(),e.dispose?.())}});E();x();k();R();E();x();k();R();E();x();k();R();E();x();k();R();import{proxy as G2}from"valtio";E();x();k();R();E();x();k();R();var xr=()=>({longRenderTime:!1,constantLongRenderTime:!1,tooManyEntities:!1,tooManyTextures:!1,unknownReason:!1});E();x();k();R();var r1=30;var Rr=45,kr=100;E();x();k();R();var a5=class{constructor(e){this.factors=e;u(this,"renderTimeHistory",[])}onFrame(e){this.pushRenderTime(e.totalMs),this.recompute(e)}pushRenderTime(e){this.renderTimeHistory.push(e),this.renderTimeHistory.length>24&&this.renderTimeHistory.shift()}recompute(e){let t=e.fps>0&&e.fps<=45,r=Math.max(0,e.totalMs-e.entitiesMs),i=e.totalMs>=30,s=this.renderTimeHistory.length,o=this.renderTimeHistory.filter(f=>f>=30).length,a=s>=8&&o/s>=.65,v=e.loadedTextureCount>=100,l=t&&e.entitiesMs>=8&&r<=20,d=t&&!(i||a||l||v);this.factors.longRenderTime=i,this.factors.constantLongRenderTime=a,this.factors.tooManyEntities=l,this.factors.tooManyTextures=v,this.factors.unknownReason=d}reset(){this.renderTimeHistory.length=0,this.factors.longRenderTime=!1,this.factors.constantLongRenderTime=!1,this.factors.tooManyEntities=!1,this.factors.tooManyTextures=!1,this.factors.unknownReason=!1}};E();x();k();R();var r6=[{key:"longRenderTime",code:"LR"},{key:"constantLongRenderTime",code:"CLR"},{key:"tooManyEntities",code:"ENT"},{key:"tooManyTextures",code:"TEX"},{key:"unknownReason",code:"UNK"}];function Tr(n){let e=r6.filter(({key:t})=>n[t]).map(({code:t})=>t);return e.length>0?e.join("+"):""}var v5={paused:!1,showChunkBorders:!1,enableDebugOverlay:!1,debugWasmPerf:!1,debugModelVariant:void 0,futuristicReveal:!1,wasmMesher:!0,shaderCubeBlocks:!1,shaderCubeDebugMode:0,mesherWorkers:1,addChunksBatchWaitTime:200,_experimentalSmoothChunkLoading:!0,_renderByChunks:!1,autoLowerRenderDistance:!1,disableMesherConversionCache:!1,dedicatedChangeWorker:!1,shadingTheme:"high-contrast",cardinalLight:"default",dayCycle:!0,smoothLighting:!0,enableLighting:!0,starfield:!0,defaultSkybox:!0,renderEntities:!0,extraBlockRenderers:!0,foreground:!0,fov:75,volume:1,showHand:!1,viewBobbing:!1,handRenderer:"vanilla",renderEars:!0,highlightBlockColor:"blue",fetchPlayerSkins:!0,skinTexturesProxy:void 0,vrSupport:!0,vrPageGameRendering:!0,clipWorldBelowY:void 0,isPlayground:!1,instantCameraUpdate:!1,isRaining:!1,moduleStates:{}},N2={fpsLimit:void 0,sceneBackground:"lightblue",timeoutRendering:!1},kc=(n={})=>G2({...v5,...n}),Ze=()=>({reactive:G2({world:{chunksLoaded:new Set,heightmaps:new Map,allChunksLoaded:!1,mesherWork:!1,instabilityFactors:xr(),intersectMedia:null},renderer:"...",preventEscapeMenu:!1}),nonReactive:{fps:0,worstRenderTime:0,avgRenderTime:0,world:{chunksLoaded:new Set,chunksTotalNumber:0},renderer:{timeline:{live:[],frozen:[],lastSecond:[]}}}});E();x();k();R();import{proxy as i6}from"valtio";var Mr=()=>i6({playerSkin:void 0,inWater:!1,waterBreathing:!1,backgroundColor:[0,0,0],ambientLight:0,directionalLight:0,eyeHeight:0,gameMode:void 0,lookingAtBlock:void 0,diggingBlock:void 0,movementState:"NOT_MOVING",onGround:!0,sneaking:!1,flying:!1,sprinting:!1,walkDist:0,prevWalkDist:0,bob:0,prevBob:0,itemUsageTicks:0,username:"",onlineMode:!1,cardinalLight:"default",lightingDisabled:!1,shouldHideHand:!1,heldItemMain:void 0,heldItemOff:void 0,perspective:"first_person",onFire:!1,fovMultiplier:1,cameraSpectatingEntity:void 0,team:void 0}),W2=n=>({isSpectator(){return n.gameMode==="spectator"},isSpectatingEntity(){return n.cameraSpectatingEntity!==void 0&&n.gameMode==="spectator"},isThirdPerson(){return this.isSpectatingEntity()?!1:n.perspective==="third_person_back"||n.perspective==="third_person_front"}}),V2=()=>({reactive:Mr()});E();x();k();R();import{Vec3 as w6}from"vec3";import{proxy as J2}from"valtio";E();x();k();R();E();x();k();R();E();x();k();R();E();x();k();R();var i1={},j2=!1;function n6(){if(j2)return i1;j2=!0;var n=typeof Reflect=="object"?Reflect:null,e=n&&typeof n.apply=="function"?n.apply:function(S,H,B){return Function.prototype.apply.call(S,H,B)},t;n&&typeof n.ownKeys=="function"?t=n.ownKeys:Object.getOwnPropertySymbols?t=function(S){return Object.getOwnPropertyNames(S).concat(Object.getOwnPropertySymbols(S))}:t=function(S){return Object.getOwnPropertyNames(S)};function r(M){}var i=Number.isNaN||function(S){return S!==S};function s(){s.init.call(this)}i1=s,i1.once=y,s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var o=10;function a(M){if(typeof M!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof M)}Object.defineProperty(s,"defaultMaxListeners",{enumerable:!0,get:function(){return o},set:function(M){if(typeof M!="number"||M<0||i(M))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+M+".");o=M}}),s.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},s.prototype.setMaxListeners=function(S){if(typeof S!="number"||S<0||i(S))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+S+".");return this._maxListeners=S,this};function v(M){return M._maxListeners===void 0?s.defaultMaxListeners:M._maxListeners}s.prototype.getMaxListeners=function(){return v(this)},s.prototype.emit=function(S){for(var H=[],B=1;B<arguments.length;B++)H.push(arguments[B]);var I=S==="error",G=this._events;if(G!==void 0)I=I&&G.error===void 0;else if(!I)return!1;if(I){var O;if(H.length>0&&(O=H[0]),O instanceof Error)throw O;var j=new Error("Unhandled error."+(O?" ("+O.message+")":""));throw j.context=O,j}var J=G[S];if(J===void 0)return!1;if(typeof J=="function")e(J,this,H);else for(var X=J.length,t0=g(J,X),B=0;B<X;++B)e(t0[B],this,H);return!0};function l(M,S,H,B){var I,G,O;if(a(H),G=M._events,G===void 0?(G=M._events=Object.create(null),M._eventsCount=0):(G.newListener!==void 0&&(M.emit("newListener",S,H.listener?H.listener:H),G=M._events),O=G[S]),O===void 0)O=G[S]=H,++M._eventsCount;else if(typeof O=="function"?O=G[S]=B?[H,O]:[O,H]:B?O.unshift(H):O.push(H),I=v(M),I>0&&O.length>I&&!O.warned){O.warned=!0;var j=new Error("Possible EventEmitter memory leak detected. "+O.length+" "+String(S)+" listeners added. Use emitter.setMaxListeners() to increase limit");j.name="MaxListenersExceededWarning",j.emitter=M,j.type=S,j.count=O.length}return M}s.prototype.addListener=function(S,H){return l(this,S,H,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(S,H){return l(this,S,H,!0)};function c(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function d(M,S,H){var B={fired:!1,wrapFn:void 0,target:M,type:S,listener:H},I=c.bind(B);return I.listener=H,B.wrapFn=I,I}s.prototype.once=function(S,H){return a(H),this.on(S,d(this,S,H)),this},s.prototype.prependOnceListener=function(S,H){return a(H),this.prependListener(S,d(this,S,H)),this},s.prototype.removeListener=function(S,H){var B,I,G,O,j;if(a(H),I=this._events,I===void 0)return this;if(B=I[S],B===void 0)return this;if(B===H||B.listener===H)--this._eventsCount===0?this._events=Object.create(null):(delete I[S],I.removeListener&&this.emit("removeListener",S,B.listener||H));else if(typeof B!="function"){for(G=-1,O=B.length-1;O>=0;O--)if(B[O]===H||B[O].listener===H){j=B[O].listener,G=O;break}if(G<0)return this;G===0?B.shift():b(B,G),B.length===1&&(I[S]=B[0]),I.removeListener!==void 0&&this.emit("removeListener",S,j||H)}return this},s.prototype.off=s.prototype.removeListener,s.prototype.removeAllListeners=function(S){var H,B,I;if(B=this._events,B===void 0)return this;if(B.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):B[S]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete B[S]),this;if(arguments.length===0){var G=Object.keys(B),O;for(I=0;I<G.length;++I)O=G[I],O!=="removeListener"&&this.removeAllListeners(O);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(H=B[S],typeof H=="function")this.removeListener(S,H);else if(H!==void 0)for(I=H.length-1;I>=0;I--)this.removeListener(S,H[I]);return this};function f(M,S,H){var B=M._events;if(B===void 0)return[];var I=B[S];return I===void 0?[]:typeof I=="function"?H?[I.listener||I]:[I]:H?w(I):g(I,I.length)}s.prototype.listeners=function(S){return f(this,S,!0)},s.prototype.rawListeners=function(S){return f(this,S,!1)},s.listenerCount=function(M,S){return typeof M.listenerCount=="function"?M.listenerCount(S):m.call(M,S)},s.prototype.listenerCount=m;function m(M){var S=this._events;if(S!==void 0){var H=S[M];if(typeof H=="function")return 1;if(H!==void 0)return H.length}return 0}s.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]};function g(M,S){for(var H=new Array(S),B=0;B<S;++B)H[B]=M[B];return H}function b(M,S){for(;S+1<M.length;S++)M[S]=M[S+1];M.pop()}function w(M){for(var S=new Array(M.length),H=0;H<S.length;++H)S[H]=M[H].listener||M[H];return S}function y(M,S){return new Promise(function(H,B){function I(O){M.removeListener(S,G),B(O)}function G(){typeof M.removeListener=="function"&&M.removeListener("error",I),H([].slice.call(arguments))}C(M,S,G,{once:!0}),S!=="error"&&A(M,I,{once:!0})})}function A(M,S,H){typeof M.on=="function"&&C(M,"error",S,H)}function C(M,S,H,B){if(typeof M.on=="function")B.once?M.once(S,H):M.on(S,H);else if(typeof M.addEventListener=="function")M.addEventListener(S,function I(G){B.once&&M.removeEventListener(S,I),H(G)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof M)}return i1}var n1=n6();n1.once;n1.once=function(n,e){return new Promise((t,r)=>{function i(...o){s!==void 0&&n.removeListener("error",s),t(o)}let s;e!=="error"&&(s=o=>{n.removeListener(name,i),r(o)},n.once("error",s)),n.once(e,i)})};n1.on=function(n,e){let t=[],r=[],i=null,s=!1,o={async next(){let l=t.shift();if(l)return createIterResult(l,!1);if(i){let c=Promise.reject(i);return i=null,c}return s?createIterResult(void 0,!0):new Promise((c,d)=>r.push({resolve:c,reject:d}))},async return(){n.removeListener(e,a),n.removeListener("error",v),s=!0;for(let l of r)l.resolve(createIterResult(void 0,!0));return createIterResult(void 0,!0)},throw(l){i=l,n.removeListener(e,a),n.removeListener("error",v)},[Symbol.asyncIterator](){return this}};return n.on(e,a),n.on("error",v),o;function a(...l){let c=r.shift();c?c.resolve(createIterResult(l,!1)):t.push(l)}function v(l){s=!0;let c=r.shift();c?c.reject(l):i=l,o.return()}};var{EventEmitter:Xe,defaultMaxListeners:Nc,init:Wc,listenerCount:Vc,on:jc,once:Yc}=n1;import{Vec3 as $e}from"vec3";E();x();k();R();function l5(n){let e=n*2+1;if(e<=0)return[];let t=[],r=0,i=0,s=0,o=-1;for(let a=0;a<e*e;a++){if(Math.abs(r)<=e/2&&Math.abs(i)<=e/2&&t.push([r,i]),r===i||r<0&&r===-i||r>0&&r===1-i){let v=s;s=-o,o=v}r+=s,i+=o}return t}var kt=n=>[Math.floor(n.x/16),Math.floor(n.z/16)],s6=n=>[Math.floor(n.x/16),Math.floor(n.y/16),Math.floor(n.z/16)],Y2=async(n,e,t,r=1)=>{for(let i=0;i<n.length;i+=r)e&&await new Promise(s=>setTimeout(s,e)),await t(n[i],i)},c5=class c5 extends Xe{static restoreTransferred(e,t){let r=new c5;return t&&t.addEventListener("message",({data:i})=>{i.class===c5.restorerName&&i.type==="event"&&r.emit(i.eventName,...i.args)}),r}};u(c5,"restorerName","WorldViewWorker");var et=c5,tt=class extends Xe{constructor(t,r,i=new $e(0,0,0)){super();this.world=t;this.viewDistance=r;u(this,"spiralNumber",0);u(this,"gotPanicLastTime",!1);u(this,"panicChunksReload",()=>{});u(this,"loadedChunks",{});u(this,"inLoading",!1);u(this,"chunkReceiveTimes",[]);u(this,"lastChunkReceiveTime",0);u(this,"lastChunkReceiveTimeAvg",0);u(this,"panicTimeout");u(this,"lastPos");u(this,"eventListeners",{});u(this,"debugChunksInfo",{});u(this,"waitingSpiralChunksLoad",{});u(this,"addWaitTime",1);u(this,"keepChunksDistance",0);u(this,"isPlayground",!1);u(this,"allowPositionUpdate",!0);u(this,"lastBiomeId",null);u(this,"lastPosCheck",null);this.lastPos=new $e(0,0,0).update(i)}prepareForTransfer(t){if(t){let r=this.emit.bind(this);this.emit=(i,...s)=>{r(i,...s),t.postMessage({class:et.restorerName,type:"event",eventName:i,args:s})}}return{__restorer:et.restorerName}}setBlockStateId(t,r){let i=this.world.setBlockStateId(t,r);if(i&&typeof i.then=="function")throw new Error("setBlockStateId returned promise (not supported)");this.emit("blockUpdate",{pos:t,stateId:r})}updateViewDistance(t){this.viewDistance=t,this.emit("renderDistance",t)}async init(t,r){this.updateViewDistance(this.viewDistance),this.emit("chunkPosUpdate",{pos:t}),r?.time?.timeOfDay!==void 0&&this.emit("time",r.time.timeOfDay),r?.entity&&this.emit("playerEntity",r.entity),this.emitterGotConnected(r);let[i,s]=kt(t),o=l5(this.viewDistance).map(([a,v])=>new $e((i+a)*16,0,(s+v)*16));this.lastPos.update(t),await this._loadChunks(o,t)}chunkProgress(){if(this.panicTimeout&&clearTimeout(this.panicTimeout),this.chunkReceiveTimes.length>=5){let t=this.chunkReceiveTimes.reduce((i,s)=>i+s,0)/this.chunkReceiveTimes.length;this.lastChunkReceiveTimeAvg=t;let r=t*2+1e3;this.panicTimeout&&clearTimeout(this.panicTimeout),this.panicTimeout=setTimeout(()=>{!this.gotPanicLastTime&&this.inLoading&&(this.gotPanicLastTime=!0,this.panicChunksReload())},r)}}async _loadChunks(t,r){this.spiralNumber++;let{spiralNumber:i}=this;for(let o of Object.keys(this.waitingSpiralChunksLoad))this.waitingSpiralChunksLoad[o](!1),delete this.waitingSpiralChunksLoad[o];let s=!0;this.inLoading=!0,await Y2(t,this.addWaitTime,async o=>{!s||this.loadedChunks[`${o.x},${o.z}`]||(this.world.getColumnAt(o)||(s=await new Promise(a=>{this.waitingSpiralChunksLoad[`${o.x},${o.z}`]=a})),s&&(await this.loadChunk(o,void 0,`spiral ${i} from ${r.x},${r.z}`),this.chunkProgress()))}),this.panicTimeout&&clearTimeout(this.panicTimeout),this.inLoading=!1,this.gotPanicLastTime=!1,this.chunkReceiveTimes=[],this.lastChunkReceiveTime=0}async loadChunk(t,r=!1,i="spiral"){var l,c;let[s,o]=kt(this.lastPos),a=Math.abs(s-Math.floor(t.x/16)),v=Math.abs(o-Math.floor(t.z/16));if(a<=this.viewDistance&&v<=this.viewDistance){let d=await this.world.getColumnAt(t.y!==void 0?t:new $e(t.x,0,t.z));if(d){let f=d.toJson(),m={minY:d.minY??0,worldHeight:d.worldHeight??256};this.emit("loadChunk",{x:t.x,z:t.z,chunk:f,blockEntities:d.blockEntities,worldConfig:m,isLightUpdate:r}),this.loadedChunks[`${t.x},${t.z}`]=!0,(l=this.debugChunksInfo)[c=`${t.x},${t.z}`]??(l[c]={loads:[]}),this.debugChunksInfo[`${t.x},${t.z}`].loads.push({dataLength:f.length,reason:i,time:Date.now()})}else this.isPlayground&&this.emit("markAsLoaded",{x:t.x,z:t.z})}}unloadAllChunks(){for(let t of Object.keys(this.loadedChunks)){let[r,i]=t.split(",").map(Number);this.unloadChunk({x:r,z:i})}}unloadChunk(t){this.emit("unloadChunk",{x:t.x,z:t.z}),delete this.loadedChunks[`${t.x},${t.z}`],delete this.debugChunksInfo[`${t.x},${t.z}`]}emitterGotConnected(t){typeof globalThis.WorkerGlobalScope<"u"&&globalThis instanceof globalThis.WorkerGlobalScope||!t||this.emit("blockEntities",new Proxy({},{get(i,s,o){if(typeof s!="string")return;let[a,v,l]=s.split(",").map(Number);return t.world.getBlock(new $e(a,v,l))?.entity}}))}updateBiome(t){try{if(!this.world.getBiome)return;let r=this.world.getBiome(t);r!==this.lastBiomeId&&(this.lastBiomeId=r,this.emit("biomeReset"))}catch{}}async updatePosition(t,r=!1){if(!this.allowPositionUpdate)return;let i=t.floored();if(!r&&this.lastPosCheck&&this.lastPosCheck.equals(i))return;this.lastPosCheck=i,this.updateBiome(t);let[s,o]=kt(this.lastPos),[a,v]=kt(t);if(s!==a||o!==v||r){this.emit("chunkPosUpdate",{pos:t});let l=[],c=r?this.viewDistance:this.viewDistance+this.keepChunksDistance;for(let f of Object.keys(this.loadedChunks)){let[m,g]=f.split(",").map(Number),b=new $e(m,0,g),[w,y]=kt(b),A=Math.abs(a-w),C=Math.abs(v-y);(A>c||C>c)&&l.push(b)}for(let f of l)this.unloadChunk(f);let d=l5(this.viewDistance).map(([f,m])=>{let g=new $e((a+f)*16,0,(v+m)*16);if(!this.loadedChunks[`${g.x},${g.z}`])return g}).filter(f=>!!f);this.lastPos.update(t),this._loadChunks(d,t)}else this.emit("chunkPosUpdate",{pos:t}),this.lastPos.update(t)}};E();x();k();R();E();x();k();R();import Q2 from"minecraft-data";import o6 from"mc-assets/dist/blocksAtlases.json";import a6 from"mc-assets/dist/itemsAtlases.json";import v6 from"mc-assets/dist/itemDefinitions.json";import l6 from"mc-assets/dist/blocksAtlasLatest.png";import c6 from"mc-assets/dist/blocksAtlasLegacy.png";import d6 from"mc-assets/dist/itemsAtlasLatest.png";import u6 from"mc-assets/dist/itemsAtlasLegacy.png";import f6 from"mc-assets/dist/textureReplacements/christmas";import{AtlasParser as s1}from"mc-assets/dist/atlasParser";import h6 from"mc-assets/dist/worldBlockProvider";import{ItemsRenderer as m6}from"mc-assets/dist/itemsRenderer";import{getLoadedItemDefinitionsStore as p6}from"mc-assets";var Tt=class{constructor(e){u(this,"sourceItemDefinitionsJson",v6);u(this,"itemsDefinitionsStore",p6(this.sourceItemDefinitionsJson));u(this,"allReady",!1);u(this,"itemsAtlasImage");u(this,"blocksAtlasImage");u(this,"blocksAtlasJson");u(this,"customBlockStates");u(this,"customModels");u(this,"customItemModelNames",{});u(this,"customTextures",{});u(this,"guiAtlas",null);u(this,"guiAtlasVersion",0);u(this,"itemsRenderer");u(this,"worldBlockProvider");u(this,"blockstatesModels",null);u(this,"version");u(this,"texturesVersion");u(this,"mcData");e&&(Object.assign(this,e),this.mcData=Q2(this.version))}prepareForTransfer(){let e={};for(let t in this)Object.prototype.hasOwnProperty.call(this,t)&&typeof this[t]!="function"&&(t==="itemsRenderer"||t==="worldBlockProvider"||t==="mcData"||(e[t]=this[t]));return e.customTextures={},e}},g6="1.21.4",Pe=class Pe extends Xe{constructor(){super(...arguments);u(this,"sourceBlockStatesModels",null);u(this,"sourceBlocksAtlases",o6);u(this,"sourceItemsAtlases",a6);u(this,"currentResources");u(this,"itemsAtlasParser");u(this,"blocksAtlasParser");u(this,"currentConfig");u(this,"abortController",new AbortController);u(this,"_promiseAssetsReadyResolvers",Promise.withResolvers())}static restoreTransferred(t,r){let i=new Pe,s=o=>{i.currentResources=new Tt(o)};return s(t.currentResources),r&&r.addEventListener("message",({data:o})=>{o.class===Pe.restorerName&&(o.type==="newResources"&&s(o.currentResources),o.type==="event"&&i.emit(o.eventName,...o.args))}),i}prepareForTransfer(t){if(t){let r=this.emit.bind(this);this.emit=(i,...s)=>{r(i,...s),t.postMessage({class:Pe.restorerName,type:"event",eventName:i,args:s}),(i==="assetsTexturesUpdated"||i==="assetsInventoryReady")&&t.postMessage({class:Pe.restorerName,type:"newResources",currentResources:this.currentResources?.prepareForTransfer()})}}return{__restorer:Pe.restorerName,currentResources:this.currentResources?.prepareForTransfer()}}get promiseAssetsReady(){return this._promiseAssetsReadyResolvers.promise}async loadSourceData(t=this.currentConfig?.version){if(!t)throw new Error("No version loaded");this.sourceBlockStatesModels??(this.sourceBlockStatesModels=(await import("mc-assets/dist/blockStatesModels.json")).default)}resetResources(){this.currentResources=new Tt}async updateAssetsData(t,r=!1){if(!this.currentConfig)throw new Error("No config loaded");this._promiseAssetsReadyResolvers=Promise.withResolvers();let i=new AbortController;if(await this.loadSourceData(this.currentConfig.version),i.signal.aborted)return;let s=this.currentResources??new Tt;s.version=this.currentConfig.version,s.texturesVersion=this.currentConfig.texturesVersion??s.version,s.mcData=Q2(s.version),s.blockstatesModels={blockstates:{},models:{}},s.blockstatesModels.blockstates.latest={...this.sourceBlockStatesModels.blockstates.latest,...s.customBlockStates},s.blockstatesModels.models.latest={...this.sourceBlockStatesModels.models.latest,...s.customModels},await Promise.all([this.recreateBlockAtlas(s),this.recreateItemsAtlas(s)]),!i.signal.aborted&&(s.version&&s.blockstatesModels&&this.itemsAtlasParser&&this.blocksAtlasParser&&(s.itemsRenderer=new m6(s.version,s.blockstatesModels,this.itemsAtlasParser,this.blocksAtlasParser)),!i.signal.aborted&&(this.currentResources=s,s.allReady=!0,r||this.emit("assetsTexturesUpdated"),this.currentConfig.noInventoryGui?this._promiseAssetsReadyResolvers.resolve():(this.emit("assetsInventoryStarted"),this.generateGuiTextures().then(()=>{i.signal.aborted||(r||this.emit("assetsInventoryReady"),this._promiseAssetsReadyResolvers.resolve())}))))}async recreateBlockAtlas(t=this.currentResources){let r={},i=new Date;(i.getMonth()===11&&i.getDate()>=24||i.getMonth()===0&&i.getDate()<=6)&&Object.assign(r,f6);let s=new s1(this.sourceBlocksAtlases,l6,c6),o=Object.keys(t.customTextures.blocks?.textures??{}),{atlas:a,canvas:v}=await s.makeNewAtlas(t.texturesVersion,l=>{if(this.currentConfig.includeOnlyBlocks&&!this.currentConfig.includeOnlyBlocks.includes(l))return!1;let c=t.customTextures.blocks?.textures[l];return r[l]??c},void 0,void 0,o,{needHorizontalIndexes:!!this.currentConfig.includeOnlyBlocks});this.blocksAtlasParser=new s1({latest:a},v.toDataURL()),t.blocksAtlasImage=await createImageBitmap(v),t.blocksAtlasJson=this.blocksAtlasParser.atlas.latest,t.worldBlockProvider=h6(t.blockstatesModels,this.blocksAtlasParser.atlas,g6)}async recreateItemsAtlas(t=this.currentResources){let r=new s1(this.sourceItemsAtlases,d6,u6),i=Object.keys(t.customTextures.items?.textures??{}),{atlas:s,canvas:o}=await r.makeNewAtlas(t.texturesVersion,a=>{let v=t.customTextures.items?.textures[a];if(v)return v},t.customTextures.items?.tileSize,void 0,i);this.itemsAtlasParser=new s1({latest:s},o.toDataURL()),t.itemsAtlasImage=await createImageBitmap(o)}async generateGuiTextures(){}async downloadDebugAtlas(t=!1){if(!this.currentResources)throw new Error("No resources loaded");let s=await(t?this.itemsAtlasParser:this.blocksAtlasParser).createDebugImage(!0),o=document.createElement("a");o.href=s,o.download=`atlas-debug-${t?"items":"blocks"}.png`,o.click()}destroy(){this.abortController.abort(),this.currentResources=void 0,this.abortController=new AbortController}};u(Pe,"restorerName","ResourcesManager");var he=Pe;E();x();k();R();var ae=class extends Error{constructor(t,r){super(t);u(this,"failure");this.name="MesherWorkerPreloadError",this.failure=r}};function b6(n){return!n||typeof n!="object"?!1:n.type==="mc-web-pong"?!0:Array.isArray(n)?n.some(e=>e&&typeof e=="object"&&e.type==="mc-web-pong"):!1}var y6=45e3,_6=1e4;async function K2(n){if(F.env.SINGLE_FILE_BUILD)return;let e=n?.fetchTimeoutMs??y6,t=n?.pingTimeoutMs??_6,r=n?.script??"mesher.js",i=new URL(r,document.baseURI).href,s;try{let d=new AbortController,f=window.setTimeout(()=>d.abort(),e);try{s=await fetch(i,{credentials:"same-origin",cache:"force-cache",signal:d.signal})}finally{clearTimeout(f)}}catch(d){let f=d;throw f?.name==="AbortError"?new ae(`Mesher script fetch timed out after ${e}ms (${i}).`,{phase:"fetch",code:"timeout"}):new ae(`Mesher script fetch failed (network): ${f?.message??d}. URL: ${i}`,{phase:"fetch",code:"network",detail:String(f?.message??d)})}if(!s.ok)throw new ae(`Mesher script HTTP ${s.status} ${s.statusText}: ${i}`,{phase:"fetch",code:"bad-status",status:s.status});let o=s.headers.get("content-type")??"",a=await s.arrayBuffer();if(a.byteLength===0)throw new ae(`Mesher script response was empty: ${i}`,{phase:"fetch",code:"invalid-body",hint:"empty"});let v=Math.min(1024,a.byteLength),l=new TextDecoder().decode(a.slice(0,v)).trimStart();if(l.startsWith("<!DOCTYPE")||l.startsWith("<html")||l.startsWith("<HTML"))throw new ae(`Mesher URL returned HTML (wrong path, redirect, or SPA fallback), not JavaScript: ${i}`,{phase:"fetch",code:"invalid-body",hint:"html"});o.length>0&&/javascript|ecmascript/i.test(o);let c;try{c=new Worker(i)}catch(d){let f=d instanceof Error?d.message:String(d);throw new ae(`Could not construct Worker for mesher (${i}): ${f}`,{phase:"worker",code:"construct-failed",message:f})}await new Promise((d,f)=>{let m=!1,g=window.setTimeout(()=>{m||(m=!0,b(),f(new ae(`Mesher worker did not reply with mc-web-pong within ${t}ms (wrong script, SW stale cache, worker blocked, or COEP/CORP). URL: ${i}`,{phase:"ping",code:"timeout"})))},t),b=()=>{clearTimeout(g);let S=c;c=void 0,S&&(S.removeEventListener("message",A),S.removeEventListener("error",C),S.removeEventListener("messageerror",M),S.terminate())},w=()=>{m||(m=!0,b(),d())},y=S=>{m||(m=!0,b(),f(S))};function A(S){b6(S.data)&&w()}function C(S){y(new ae(`Mesher worker script failed to load or threw during startup: ${S.message||"unknown"} @ ${i}`,{phase:"worker",code:"script-error",message:S.message}))}function M(){y(new ae(`Mesher worker message channel error (structured clone / deserialization). URL: ${i}`,{phase:"ping",code:"messageerror"}))}c.addEventListener("message",A),c.addEventListener("error",C),c.addEventListener("messageerror",M);try{c.postMessage({type:"mc-web-ping",t:performance.now(),workerIndex:0})}catch(S){let H=S instanceof Error?S.message:String(S);y(new ae(`Failed to post mc-web-ping to mesher worker: ${H}`,{phase:"ping",code:"post-failed",detail:H}))}})}var q2=class{constructor(e={},t=new he){this.resourcesManager=t;u(this,"waitBackendLoadPromises",[]);u(this,"onWorldStart");u(this,"onBeforeWorldStart");u(this,"worldView");u(this,"config");u(this,"menuBackgroundOptions");u(this,"inWorldRenderingConfig");u(this,"backend");u(this,"backendLoader");u(this,"currentState");u(this,"currentDisplay",null);u(this,"playerState",{reactive:Mr()});u(this,"rendererState");u(this,"nonReactiveState");u(this,"worldReady");u(this,"resolveWorldReady");u(this,"lastCamUpdate",0);u(this,"getRendererOptions");this.config={...N2,...e.config},this.menuBackgroundOptions={...e.config?.menuBackground,...e.menuBackground},this.inWorldRenderingConfig=J2({...v5,...e.rendererConfig});let r=Ze();this.rendererState=r.reactive,this.nonReactiveState=r.nonReactive,this.initWorldReadyPromise()}initWorldReadyPromise(){let{promise:e,resolve:t}=Promise.withResolvers();this.worldReady=e,this.resolveWorldReady=t}preloadWorkers(){let e=this.inWorldRenderingConfig.wasmMesher?"mesherWasm.js":"mesher.js";return K2({script:e})}bindRendererOptions(e){this.getRendererOptions=e}async loadBackend(e){this.backend&&this.disconnectBackend(),await Promise.all(this.waitBackendLoadPromises),this.waitBackendLoadPromises=[],this.backendLoader=e;let t={config:this.config,getRendererOptions:this.getRendererOptions,callbacks:{displayCriticalError:i=>{},setRendererSpecificSettings:(i,s)=>{},fireCustomEvent:(i,...s)=>{}},rendererSpecificSettings:{}},r=e(t);if(this.backend=await Promise.resolve(r),this.currentState)if(this.currentState.method==="startMenuBackground")this.startMenuBackground(...this.currentState.args);else{let{method:i,args:s}=this.currentState;this.backend[i](...s)}}async startWorld(e,t,r=this.playerState.reactive,i){if(this.currentDisplay==="world")throw new Error("World already started");this.currentDisplay="world";let s=i??new w6(0,64,0);this.worldView=new tt(e,t,s),this.worldView.isPlayground=this.inWorldRenderingConfig.isPlayground;let o={version:this.resourcesManager?.currentConfig?.version??"1.20.4",worldView:this.worldView,inWorldRenderingConfig:this.inWorldRenderingConfig,playerStateReactive:r,rendererState:this.rendererState,nonReactiveState:this.nonReactiveState,resourcesManager:this.resourcesManager};this.onBeforeWorldStart?.();let a;if(this.backend){let v=this.backend.startWorld(o);v&&typeof v.then=="function"&&(a=v)}return this.currentState={method:"startWorld",args:[o]},await a,this.resolveWorldReady(),this.onWorldStart?.(),!!a}startMenuBackground(e){if(this.currentDisplay==="menu")return;let t={...this.menuBackgroundOptions,...e,resourcesManager:e?.resourcesManager??this.resourcesManager};this.backend&&(this.currentDisplay="menu",this.backend.startMenuBackground(t)),this.currentState={method:"startMenuBackground",args:[t]}}resetBackend(e=!1){this.disconnectBackend(e),this.backendLoader&&this.loadBackend(this.backendLoader)}disconnectBackend(e=!1){e&&(this.currentState=void 0,this.currentDisplay=null,this.worldView=void 0),this.backend&&(this.backend.disconnect(),this.backend=void 0),this.currentDisplay=null,this.initWorldReadyPromise(),this.rendererState=J2(Ze().reactive),this.nonReactiveState=Ze().nonReactive}updateCamera(e,t,r){this.backend?.updateCamera(e,t,r)}setRendering(e){this.backend?.setRendering(e)}async startWithBot(e,t){await this.startWorld(e.world,t),this.worldView&&typeof this.worldView.listenToBot=="function"&&this.worldView.listenToBot(e)}destroyAll(){this.disconnectBackend(!0),this.resourcesManager&&typeof this.resourcesManager.destroy=="function"&&this.resourcesManager.destroy()}get utils(){let e=this.backend;return{async waitingForChunks(){if(!e?.worldState?.allChunksLoaded)return new Promise(t=>{let r=setInterval(()=>{e?.worldState?.allChunksLoaded&&(clearInterval(r),t())},100)})}}}destroy(){this.disconnectBackend(!0)}};E();x();k();R();import{subscribe as P6}from"valtio/vanilla";E();x();k();R();E();x();k();R();var rt=["galaxy","nether","end","cyber","light"],it=["cruise","barrel","dive","orbit","snake"],d5={galaxy:"Galaxy",nether:"Nether",end:"The End",cyber:"Cyber",light:"Light Space"},u5={cruise:"Cruise",barrel:"Barrel",dive:"Dive",orbit:"Orbit",snake:"Snake"},nt=["mixed","stainedGlass","wool","construction","glow","world"],f5={mixed:"Mixed",stainedGlass:"Stained glass",wool:"Wool",construction:"Construction",glow:"Glow",world:"World (grass & ores)"};E();x();k();R();var pe={mode:"futuristic",minecraftTextures:!0,futuristicScene:"light",futuristicCamera:"dive",futuristicBlockGroup:"stainedGlass",futuristicCameraSpeedPercent:80,futuristicBlockSpeedPercent:40},Ae=n=>n/100,h5={camera:Ae(pe.futuristicCameraSpeedPercent),block:Ae(pe.futuristicBlockSpeedPercent)};var A6={off:0,holes:1,texIndex:2,faces:3,atlasAlpha:4};function Sr(n){return A6[n]}var st=pe,Z2={rendererWorldPerformance:"normal",rendererMeshersCountOverride:null,starfieldRendering:!0,defaultSkybox:!0,menuBackgroundMode:st.mode,menuBackgroundMinecraftTextures:st.minecraftTextures,menuBackgroundFuturisticScene:st.futuristicScene,menuBackgroundFuturisticCamera:st.futuristicCamera,menuBackgroundFuturisticBlockGroup:st.futuristicBlockGroup,menuBackgroundFuturisticCameraSpeed:st.futuristicCameraSpeedPercent,menuBackgroundFuturisticBlockSpeed:st.futuristicBlockSpeedPercent,rendererFuturisticReveal:!1,rendererPerfDebugOverlay:!1,disableBlockEntityTextures:!1,rendererMesher:"wasm",rendererShaderCubeBlocks:!1,rendererShaderCubeDebugMode:"off",showChunkBorders:!1,renderEntities:!0,renderDebug:"basic",frameLimit:!1,backgroundRendering:"20fps",vanillaLook:!1,smoothLighting:!0,newVersionsLighting:!1,vrSupport:!0,vrPageGameRendering:!1,clipWorldBelowY:void 0,highlightBlockColor:"auto",loadPlayerSkins:!0,renderEars:!0,showHand:!0,viewBobbing:!0,dayCycleAndLighting:!0,keepChunksDistance:1,gpuPreference:"default",fov:75};function E6(n){n.highPerformanceGpu&&(n.gpuPreference="high-performance",delete n.highPerformanceGpu),n.rendererMesher!=="wasm"&&n.rendererMesher!=="legacy-js"&&(typeof n.rendererWasmMesher=="boolean"?n.rendererMesher=n.rendererWasmMesher?"wasm":"legacy-js":typeof n.wasmExperimentalMesher=="boolean"&&(n.rendererMesher=n.wasmExperimentalMesher?"wasm":"legacy-js")),delete n.wasmExperimentalMesher,delete n.rendererWasmMesher}var X2={menuBackgroundMode:{possibleValues:[["classic","Classic"],["futuristic","Futuristic"]],requiresRestart:!0},menuBackgroundMinecraftTextures:{text:"Minecraft block textures",tooltip:"Use block atlas on futuristic menu cubes (loads assets on menu)"},menuBackgroundFuturisticScene:{possibleValues:rt.map(n=>[n,d5[n]])},menuBackgroundFuturisticCamera:{possibleValues:it.map(n=>[n,u5[n]])},menuBackgroundFuturisticBlockGroup:{possibleValues:nt.map(n=>[n,f5[n]]),text:"Block pool",tooltip:"Block set for textured menu cubes (requires Minecraft textures)"},menuBackgroundFuturisticCameraSpeed:{text:"Camera speed",tooltip:"Orbit / fly-through camera path speed. 0 freezes the path; mouse parallax still works.",min:0,max:200,unit:"%"},menuBackgroundFuturisticBlockSpeed:{text:"Block speed",tooltip:"Floating blocks and sky rotation. Independent of camera path speed.",min:0,max:200,unit:"%"},rendererWorldPerformance:{text:"World performance",tooltip:"Background workers for chunk geometry. Reload to apply.",requiresRestart:!0,possibleValues:[["low-energy","Low Energy"],["normal","Normal"],["maximum","Maximum"]]},starfieldRendering:{text:"Starfield"},defaultSkybox:{text:"Default skybox"},rendererFuturisticReveal:{text:"Futuristic world reveal"},rendererPerfDebugOverlay:{text:"Performance debug overlay"},disableBlockEntityTextures:{text:"Disable block entity textures",tooltip:"Skips signs, banners, heads, maps, etc."},rendererMesher:{possibleValues:[["wasm","WASM"],["legacy-js","Legacy JS"]],text:"Mesher pipeline",tooltip:"WASM is faster. Use JS if WASM is not working. Requires reload.",requiresRestart:!0},rendererShaderCubeBlocks:{text:"Instanced shader cubes",tooltip:"Render full blocks through the global GPU instanced path. Requires WASM mesher and WebGL2.",requiresChunksReload:!0},rendererShaderCubeDebugMode:{text:"Shader cube debug",tooltip:"Instanced cube path visualization (requires shader cubes enabled).",possibleValues:[["off","Off"],["holes","Hole test (red)"],["texIndex","Tile index colors"],["faces","Face id colors"],["atlasAlpha","Atlas alpha"]]},showChunkBorders:{text:"Chunk borders"},renderEntities:{text:"Render entities"},renderDebug:{possibleValues:["advanced","basic","none"]},frameLimit:{text:"Frame limit",tooltip:"false = VSync / unlimited when focused"},backgroundRendering:{text:"Background FPS limit",possibleValues:[["full","NO"],["5fps","5 FPS"],["20fps","20 FPS"]]},vanillaLook:{text:"Vanilla shading",tooltip:"On: Minecraft-style face shading. Off: higher-contrast client shading."},smoothLighting:{},newVersionsLighting:{text:"Lighting in newer versions"},vrSupport:{text:"VR support",tooltip:"Shows VR entry; does not force VR on."},vrPageGameRendering:{text:"VR page game rendering"},clipWorldBelowY:{text:"Clip world below Y"},highlightBlockColor:{possibleValues:[["auto","Auto"],["blue","Blue"],["classic","Classic"]]},loadPlayerSkins:{},renderEars:{tooltip:"Deadmau5 ears when the skin texture includes them"},showHand:{},viewBobbing:{},dayCycleAndLighting:{text:"Day cycle"},keepChunksDistance:{text:"Keep chunks distance",tooltip:"Extra distance before unloading chunks",max:5,unit:""},fov:{min:30,max:110,unit:"\xB0",text:"FOV (Field of View)"},gpuPreference:{text:"GPU preference",tooltip:"WebGL power preference. Requires reload / backend restart to apply.",requiresRestart:!0,possibleValues:[["default","Auto"],["high-performance","Dedicated"],["low-power","Low power"]]}},$2=[{title:"World rendering",keys:["rendererWorldPerformance","starfieldRendering","defaultSkybox","disableBlockEntityTextures","showChunkBorders","renderEntities","smoothLighting","vanillaLook","newVersionsLighting","dayCycleAndLighting","loadPlayerSkins","renderEars","showHand","viewBobbing","fov","keepChunksDistance","highlightBlockColor","clipWorldBelowY"]},{title:"Frame pacing",keys:["frameLimit","backgroundRendering","renderDebug","gpuPreference"]},{title:"VR",keys:["vrSupport","vrPageGameRendering"]},{title:"Menu background",keys:["menuBackgroundMode","menuBackgroundMinecraftTextures","menuBackgroundFuturisticScene","menuBackgroundFuturisticCamera","menuBackgroundFuturisticBlockGroup","menuBackgroundFuturisticCameraSpeed","menuBackgroundFuturisticBlockSpeed"]},{title:"Mesher",keys:["rendererMesher","rendererShaderCubeBlocks"]},{title:"Renderer debug",keys:["rendererFuturisticReveal","rendererPerfDebugOverlay","rendererShaderCubeDebugMode"]}];E();x();k();R();E();x();k();R();E();x();k();R();E();x();k();R();function Cr(n,e,t,r,i){let s=n.getImageData(e,t,r,i);for(let o=0;o<r;o++)for(let a=0;a<i;a++){let v=(o+a*r)*4;if(s.data[v+3]!==255)return!0}return!1}function o1(n){return n/64}function es(n,e,t){if(t){if(Cr(n,0,0,e,e))return}else if(Cr(n,0,0,e,e/2))return;let r=o1(e),i=(s,o,a,v)=>n.clearRect(s*r,o*r,a*r,v*r);i(40,0,8,8),i(48,0,8,8),i(32,8,8,8),i(40,8,8,8),i(48,8,8,8),i(56,8,8,8),t&&(i(4,32,4,4),i(8,32,4,4),i(0,36,4,12),i(4,36,4,12),i(8,36,4,12),i(12,36,4,12),i(20,32,8,4),i(28,32,8,4),i(16,36,4,12),i(20,36,8,12),i(28,36,4,12),i(32,36,8,12),i(44,32,4,4),i(48,32,4,4),i(40,36,4,12),i(44,36,4,12),i(48,36,4,12),i(52,36,12,12),i(4,48,4,4),i(8,48,4,4),i(0,52,4,12),i(4,52,4,12),i(8,52,4,12),i(12,52,4,12),i(52,48,4,4),i(56,48,4,4),i(48,52,4,12),i(52,52,4,12),i(56,52,4,12),i(60,52,4,12))}function x6(n,e){n.save(),n.scale(-1,1);let t=o1(e),r=(i,s,o,a,v,l)=>n.drawImage(n.canvas,i*t,s*t,o*t,a*t,-v*t,l*t,-o*t,a*t);r(4,16,4,4,20,48),r(8,16,4,4,24,48),r(0,20,4,12,24,52),r(4,20,4,12,20,52),r(8,20,4,12,16,52),r(12,20,4,12,28,52),r(44,16,4,4,36,48),r(48,16,4,4,40,48),r(40,20,4,12,40,52),r(44,20,4,12,36,52),r(48,20,4,12,32,52),r(52,20,4,12,44,52),n.restore()}function Br(n,e){let t=!1;if(e.width!==e.height)if(e.width===2*e.height)t=!0;else throw new Error(`Bad skin size: ${e.width}x${e.height}`);let r=n.getContext("2d",{willReadFrequently:!0});if(t){let i=e.width;n.width=i,n.height=i,r.clearRect(0,0,i,i),r.drawImage(e,0,0,i,i/2),x6(r,i),es(r,n.width,!1)}else n.width=e.width,n.height=e.height,r.clearRect(0,0,e.width,e.height),r.drawImage(e,0,0,n.width,n.height),es(r,n.width,!0)}function R6(n){if(n.width===2*n.height)return n.width/64;if(n.width*17===n.height*22)return n.width/22;if(n.width*11===n.height*23)return n.width/46;throw new Error(`Bad cape size: ${n.width}x${n.height}`)}function Pr(n,e){let t=R6(e);n.width=64*t,n.height=32*t;let r=n.getContext("2d",{willReadFrequently:!0});r.clearRect(0,0,n.width,n.height),r.drawImage(e,0,0,e.width,e.height)}function k6(n,e,t,r,i){let s=n.getImageData(e,t,r,i);for(let o=0;o<r;o++)for(let a=0;a<i;a++){let v=(o+a*r)*4;if(!(s.data[v+0]===0&&s.data[v+1]===0&&s.data[v+2]===0&&s.data[v+3]===255))return!1}return!0}function T6(n,e,t,r,i){let s=n.getImageData(e,t,r,i);for(let o=0;o<r;o++)for(let a=0;a<i;a++){let v=(o+a*r)*4;if(!(s.data[v+0]===255&&s.data[v+1]===255&&s.data[v+2]===255&&s.data[v+3]===255))return!1}return!0}function Ir(n){let e=o1(n.width),t=n.getContext("2d",{willReadFrequently:!0}),r=(a,v,l,c)=>Cr(t,a*e,v*e,l*e,c*e),i=(a,v,l,c)=>k6(t,a*e,v*e,l*e,c*e),s=(a,v,l,c)=>T6(t,a*e,v*e,l*e,c*e);return r(50,16,2,4)||r(54,20,2,12)||r(42,48,2,4)||r(46,52,2,12)||i(50,16,2,4)&&i(54,20,2,12)&&i(42,48,2,4)&&i(46,52,2,12)||s(50,16,2,4)&&s(54,20,2,12)&&s(42,48,2,4)&&s(46,52,2,12)?"slim":"default"}function Hr(n,e){if(e.width!==e.height&&e.width!==2*e.height)throw new Error(`Bad skin size: ${e.width}x${e.height}`);let t=o1(e.width),r=14*t,i=7*t;n.width=r,n.height=i;let s=n.getContext("2d",{willReadFrequently:!0});s.clearRect(0,0,r,i),s.drawImage(e,24*t,0,r,i,0,0,r,i)}E();x();k();R();import C6 from"mc-assets/dist/other-textures/latest/entity/player/wide/steve.png";E();x();k();R();import*as Ee from"three";E();x();k();R();var M6=()=>{if(typeof OffscreenCanvas>"u")return!1;try{let n=new OffscreenCanvas(1,1);return(n.getContext("webgl2")||n.getContext("webgl"))!==null}catch{return!1}},S6=M6(),V0=(n,e)=>{if(S6)return new OffscreenCanvas(n,e);let t=document.createElement("canvas");return t.width=n,t.height=e,t};async function a1(n){let t=await(await fetch(n)).blob();return createImageBitmap(t)}var R0=(n,e=!1)=>{n instanceof Ee.Mesh&&(n.geometry?.dispose?.(),n.material?.dispose?.()),n.children&&n.children.forEach(t=>R0(t,e)),e&&n instanceof Ee.Mesh&&n.material?.map?.dispose?.()},Or={},ts={},v1=n=>{let e=new Ee.Texture,t=a1(n).then(r=>{let i=new OffscreenCanvas(r.width,r.height);return i.getContext("2d").drawImage(r,0,0),e.source.data=i,e.needsUpdate=!0,e});return{texture:e,promise:t}},Ie=async n=>v1(n).texture,m5=n=>{let e=V0(n.width,n.height);e.getContext("2d").drawImage(n,0,0);let r=new Ee.Texture(e);return r.magFilter=Ee.NearestFilter,r.minFilter=Ee.NearestFilter,r};async function l1(n,e,t){if(!Or[n]){let{promise:i,resolve:s}=Promise.withResolvers(),o=v1(n);Or[n]=o.texture,o.promise.then(s),ts[n]=i}e(Or[n]),ts[n].then(()=>{t?.()})}var ge=C6,yf=Ie(ge),rs={apiEnabled:!0},c1=n=>{Object.assign(rs,n)};async function He(n,e){if(!rs.apiEnabled||e==="cape")return;let t=`https://playerdb.co/api/player/minecraft/${n}`,r=await fetch(t);return r.ok?(await r.json()).data.player.skin_texture:void 0}async function ot(n){n.startsWith("data:")||(n=await B6(n.replace("http://","https://")));let e=await a1(n),t=V0(64,64);return Br(t,e),{canvas:t,image:e}}var B6=async n=>{let t=await(await fetch(n,{})).arrayBuffer();return`data:image/png;base64,${z.from(t).toString("base64")}`};function Sf(n){return{mode:n.menuBackgroundMode,useMinecraftTextures:n.menuBackgroundMinecraftTextures,futuristicScene:n.menuBackgroundFuturisticScene,futuristicCamera:n.menuBackgroundFuturisticCamera,futuristicBlockGroup:n.menuBackgroundFuturisticBlockGroup,futuristicCameraSpeed:Ae(n.menuBackgroundFuturisticCameraSpeed),futuristicBlockSpeed:Ae(n.menuBackgroundFuturisticBlockSpeed)}}function I6(n,e){let t=n.futuristic;t&&(t.setScene?.(e.menuBackgroundFuturisticScene),t.setCamera?.(e.menuBackgroundFuturisticCamera),t.setBlockGroup?.(e.menuBackgroundFuturisticBlockGroup),t.setCameraSpeed?.(Ae(e.menuBackgroundFuturisticCameraSpeed)),t.setBlockSpeed?.(Ae(e.menuBackgroundFuturisticBlockSpeed)))}function H6(n){return n.rendererMesher!=="legacy-js"}function O6(n,e,t){let r=n.inWorldRenderingConfig,i=e.rendererMeshersCountOverride,s=o=>{r.mesherWorkers=i??o};switch(e.rendererWorldPerformance){case"low-energy":s(1),r.dedicatedChangeWorker=!1;break;case"normal":s(2),r.dedicatedChangeWorker=!t;break;case"maximum":s(Math.max(3,Math.min(navigator.hardwareConcurrency??0,8))),r.dedicatedChangeWorker=!t;break}}function F6(n,e,t){let r=e.backgroundRendering,i=e.frameLimit;t?n.config.fpsLimit=i||void 0:r==="5fps"?n.config.fpsLimit=5:r==="20fps"?n.config.fpsLimit=20:n.config.fpsLimit=void 0}function D6(n,e,t){let{renderDebug:r}=e;r==="none"||t.isCypress?n.config.statsVisible=0:r==="basic"?n.config.statsVisible=1:r==="advanced"&&(n.config.statsVisible=2)}function z6(n,e,t={}){let r=n.inWorldRenderingConfig,i=H6(e);r.showChunkBorders=e.showChunkBorders,r.futuristicReveal=e.rendererFuturisticReveal,O6(n,e,i),r.renderEntities=e.renderEntities,D6(n,e,t),F6(n,e,t.windowFocused!==!1),r.vrSupport=e.vrSupport,r.vrPageGameRendering=e.vrPageGameRendering,r.enableDebugOverlay=e.rendererPerfDebugOverlay,r.clipWorldBelowY=e.clipWorldBelowY,r.extraBlockRenderers=!e.disableBlockEntityTextures,r.fetchPlayerSkins=e.loadPlayerSkins,r.highlightBlockColor=e.highlightBlockColor,r.wasmMesher=i,r.shaderCubeBlocks=e.rendererShaderCubeBlocks&&i,r.disableMesherConversionCache=!!t.isSafari,c1({apiEnabled:e.loadPlayerSkins}),r.smoothLighting=e.smoothLighting,r.shadingTheme=e.vanillaLook?"vanilla":"high-contrast",r.starfield=e.starfieldRendering,r.defaultSkybox=e.defaultSkybox,r.fov=e.fov,r.shaderCubeDebugMode=Sr(e.rendererShaderCubeDebugMode)}function Cf(n,e,t){e.keepChunksDistance=t.keepChunksDistance;let r=n.inWorldRenderingConfig;r.renderEars=t.renderEars,r.showHand=t.showHand,r.viewBobbing=t.viewBobbing,r.dayCycle=t.dayCycleAndLighting}function Bf(n,e,t={}){n.bindRendererOptions(()=>e);let r=t.getWindowFocused?.()??!0,i=()=>{let s=e;if(z6(n,s,{isSafari:t.isSafari,isCypress:t.isCypress,windowFocused:r}),n.currentDisplay==="menu"){let o=n.backend?.getMenuBackground?.();o&&I6(o,s)}};return i(),t.onRegisterFocusHandlers?.({onFocus:()=>{r=!0,i()},onBlur:()=>{r=!1,i()}}),P6(e,i)}function Pf(n,e,t){n.inWorldRenderingConfig.enableLighting=!t||e}E();x();k();R();import{proxy as L6}from"valtio";var is=()=>L6({playerSkin:void 0,inWater:!1,waterBreathing:!1,backgroundColor:[0,0,0],ambientLight:0,directionalLight:0,eyeHeight:0,gameMode:void 0,lookingAtBlock:void 0,diggingBlock:void 0,movementState:"NOT_MOVING",onGround:!0,sneaking:!1,flying:!1,sprinting:!1,walkDist:0,prevWalkDist:0,bob:0,prevBob:0,itemUsageTicks:0,username:"",onlineMode:!1,cardinalLight:"default",lightingDisabled:!1,shouldHideHand:!1,heldItemMain:void 0,heldItemOff:void 0,perspective:"first_person",onFire:!1,fovMultiplier:1,cameraSpectatingEntity:void 0,team:void 0}),U6=n=>({isSpectator(){return n.gameMode==="spectator"},isSpectatingEntity(){return n.cameraSpectatingEntity!==void 0&&n.gameMode==="spectator"},isThirdPerson(){return this.isSpectatingEntity()?!1:n.perspective==="third_person_back"||n.perspective==="third_person_front"}}),G6=()=>({reactive:is()}),ns=(n,e,t)=>({...e,"minecraft:date":new Date});E();x();k();R();E();x();k();R();import*as Q5 from"three";import{Vec3 as ml}from"vec3";E();x();k();R();import{proxy as N6,getVersion as os,subscribe as as}from"valtio";import{Vec3 as vs}from"vec3";function ls(n,e){let t=e??globalThis;return t.addEventListener("message",r=>{let{type:i,args:s,msgId:o}=r.data;if(n[i]){let a=n[i](...s);a instanceof Promise&&a.then(v=>{t.postMessage({type:"result",msgId:o,args:[v]})})}}),null}var cs=(n,e=!0)=>{let t=0;return new Proxy({},{get(r,i){return i==="transfer"?(...s)=>new Proxy({},{get(o,a){return(...v)=>{n.postMessage({type:a,args:v},s)}}}):(...s)=>{let o=t++,a=e?s.filter(v=>v instanceof ArrayBuffer||v instanceof MessagePort||typeof ImageBitmap<"u"&&v instanceof ImageBitmap||typeof OffscreenCanvas<"u"&&v instanceof OffscreenCanvas||typeof ImageData<"u"&&v instanceof ImageData):[];return n.postMessage({type:i,msgId:o,args:s},a),{then(v){let l=({data:c})=>{c.type==="result"&&c.msgId===o&&(v(c.args[0]),n.removeEventListener("message",l))};n.addEventListener("message",l)}}}}})};var ds=(n,e,t,r)=>{try{t.postMessage({type:"sync",syncId:n,value:d1(e)}),p5.toWorker++,globalThis.debugSyncMessagesOutgoing??(globalThis.debugSyncMessagesOutgoing=0),globalThis.debugSyncMessagesOutgoing++}catch{g5(e)}},p5={toWorker:0,fromWorker:0};typeof window<"u"&&setInterval(()=>{globalThis.debugWorkerSyncStats={...p5},p5.toWorker=0,p5.fromWorker=0},1e3);var W6=()=>Math.random().toString(36).slice(2,15)+Math.random().toString(36).slice(2,15),ss=(n,e,t,r,i)=>{if(!n.__syncToWorker&&!n.__syncFromWorker&&!r)return;let s=W6();if(n.__syncId=s,n.__syncToWorker||r){let o=()=>{ds(s,e,t,`toWorker:${i}`)};r&&as(e,o);let a=n.__syncToWorkerInterval??0;a>0&&setInterval(o,a)}e.__syncFromWorker&&t.addEventListener("message",o=>{o.data.type==="sync"&&o.data.syncId===s&&(p5.fromWorker++,Object.assign(e,o.data.value))})},d1=n=>{if(os(n)===void 0)return n;if(Array.isArray(n))return n.map(d1);if(typeof n=="object"&&n!==null){let e={};for(let t in n)Object.prototype.hasOwnProperty.call(n,t)&&(e[t]=d1(n[t]));return e}return n},u1=(n,e,t=!0,r=!0,i=!1)=>{var a,v;let s=n,o={};for(let l in n)if(Object.prototype.hasOwnProperty.call(n,l)){if(t&&typeof n[l]=="function")continue;if(n[l]instanceof Date||n[l]instanceof RegExp||n[l]instanceof Map||n[l]instanceof WeakMap||n[l]instanceof WeakSet,n[l]instanceof Set){o[l]=[...n[l]],o[l].__restorer="Set";continue}if(n[l]instanceof vs){o[l]={x:n[l].x,y:n[l].y,z:n[l].z},o[l].__restorer="Vec3";continue}if(o[l]=n[l],typeof n[l]=="object"&&n[l]!==null){if(n[l].prepareForTransfer){o[l]=n[l].prepareForTransfer(e);continue}let c=os(n[l])!==void 0;o[l]=c?d1(n[l]):n[l];let d=n[l].__syncToWorker!==!1&&!i&&c&&!n[l].__syncFromWorker;if((a=o[l]).__syncToWorker??(a.__syncToWorker=d),c&&((v=o[l]).__valtio??(v.__valtio=!0)),o[l].__syncToWorker&&c){ss(o[l],s[l],e,!0,l);continue}ss(o[l],s[l],e,!1,l),o[l]=u1(o[l],e,t,!1,c)}}return o},g5=(n,e=[])=>{for(let t in n)if(Object.prototype.hasOwnProperty.call(n,t)){if(!n[t])continue;typeof n[t]=="object"&&n[t]!==null&&g5(n[t],[...e,t]);try{structuredClone(n[t])}catch{}}},V6=(n,e,t)=>{if(!n.__syncId)return;let r=n.__syncId;if(n.__syncToWorker&&e.addEventListener("message",i=>{i.data.type==="sync"&&i.data.syncId===r&&Object.assign(n,i.data.value)}),n.__syncFromWorker){let i=()=>{ds(r,n,e,`fromWorker:${t}`)};n.__valtio&&as(n,i);let s=n.__syncFromWorkerInterval??0;s>0&&setInterval(i,s)}},j6=[{restorerName:"Set",restoreTransferred(n,e){return new Set(n)}},{restorerName:"Vec3",restoreTransferred(n,e){return new vs(n.x,n.y,n.z)}}];var f1=(n,e,t,r=!0)=>{let i=[...j6,...e];for(let s in n)if(Object.prototype.hasOwnProperty.call(n,s)){if(!n[s])continue;if(typeof n[s]=="object"&&n[s]!==null&&f1(n[s],i,t,r),n[s].__restorer){let o=i.find(a=>a.restorerName?a.restorerName===n[s].__restorer:a.name===n[s].__restorer);if(o)n[s]=o.restoreTransferred(n[s],t);else{let a=new Error(`Restorer ${n[s].__restorer} not found`);if(typeof r=="function")r(a);else if(r)throw a}}n[s].__valtio&&(n[s]=N6(n[s])),V6(n[s],t,s)}return n};E();x();k();R();var h1=class{constructor(e){this.nonReactiveState=e;u(this,"events",[]);u(this,"frozenEvents",[]);u(this,"lastSecondEvents",[]);u(this,"currentFrameStartTime",null);u(this,"lastInteractionTime",0);u(this,"lastSecondUpdateTime",0);u(this,"timeWindowMs",5e3);u(this,"lastSecondWindowMs",1e3);u(this,"maxEvents",500);u(this,"lastSecondUpdateInterval",1e3);this.nonReactiveState.renderer||(this.nonReactiveState.renderer={timeline:{live:[],frozen:[],lastSecond:[]}}),this.nonReactiveState.renderer.timeline||(this.nonReactiveState.renderer.timeline={live:[],frozen:[],lastSecond:[]}),setInterval(()=>{this.updateLastSecondTimeline()},this.lastSecondUpdateInterval)}markFrameStart(){this.currentFrameStartTime=performance.now(),this.addEvent({type:"frameStart",timestamp:this.currentFrameStartTime})}markFrameEnd(){if(!this.currentFrameStartTime)return;let e=performance.now(),t=e-this.currentFrameStartTime;this.addEvent({type:"frameEnd",timestamp:e,duration:t}),this.currentFrameStartTime=null}markCameraUpdate(e){if(!e)return;let t=performance.now();this.lastInteractionTime=t,this.addEvent({type:"cameraUpdate",timestamp:t}),this.frozenEvents=[...this.events],this.trimEvents(this.frozenEvents),this.syncFrozenEvents()}markFrameDisplay(){this.addEvent({type:"frameDisplay",timestamp:performance.now()})}addEvent(e){this.events.push(e),this.lastSecondEvents.push(e),this.trimEvents(this.events),this.trimLastSecondEvents(),this.syncLiveEvents()}trimEvents(e){let r=performance.now()-this.timeWindowMs;for(;e.length>0&&e[0].timestamp<r;)e.shift();e.length>this.maxEvents&&e.splice(0,e.length-this.maxEvents)}trimLastSecondEvents(){let t=performance.now()-this.lastSecondWindowMs;for(;this.lastSecondEvents.length>0&&this.lastSecondEvents[0].timestamp<t;)this.lastSecondEvents.shift()}updateLastSecondTimeline(){let e=performance.now();e-this.lastSecondUpdateTime<this.lastSecondUpdateInterval||(this.lastSecondUpdateTime=e,this.trimLastSecondEvents(),this.syncLastSecondEvents())}syncLiveEvents(){this.nonReactiveState.renderer.timeline.live=[...this.events]}syncFrozenEvents(){this.nonReactiveState.renderer.timeline.frozen=[...this.frozenEvents]}syncLastSecondEvents(){this.nonReactiveState.renderer.timeline.lastSecond=[...this.lastSecondEvents]}clear(){this.events=[],this.frozenEvents=[],this.lastSecondEvents=[],this.syncLiveEvents(),this.syncFrozenEvents(),this.syncLastSecondEvents()}};E();x();k();R();import*as Q from"three";import{Vec3 as Ne}from"vec3";import Yv from"prismarine-chat";E();x();k();R();var H0=Object.freeze({Linear:Object.freeze({None:function(n){return n},In:function(n){return this.None(n)},Out:function(n){return this.None(n)},InOut:function(n){return this.None(n)}}),Quadratic:Object.freeze({In:function(n){return n*n},Out:function(n){return n*(2-n)},InOut:function(n){return(n*=2)<1?.5*n*n:-.5*(--n*(n-2)-1)}}),Cubic:Object.freeze({In:function(n){return n*n*n},Out:function(n){return--n*n*n+1},InOut:function(n){return(n*=2)<1?.5*n*n*n:.5*((n-=2)*n*n+2)}}),Quartic:Object.freeze({In:function(n){return n*n*n*n},Out:function(n){return 1- --n*n*n*n},InOut:function(n){return(n*=2)<1?.5*n*n*n*n:-.5*((n-=2)*n*n*n-2)}}),Quintic:Object.freeze({In:function(n){return n*n*n*n*n},Out:function(n){return--n*n*n*n*n+1},InOut:function(n){return(n*=2)<1?.5*n*n*n*n*n:.5*((n-=2)*n*n*n*n+2)}}),Sinusoidal:Object.freeze({In:function(n){return 1-Math.sin((1-n)*Math.PI/2)},Out:function(n){return Math.sin(n*Math.PI/2)},InOut:function(n){return .5*(1-Math.sin(Math.PI*(.5-n)))}}),Exponential:Object.freeze({In:function(n){return n===0?0:Math.pow(1024,n-1)},Out:function(n){return n===1?1:1-Math.pow(2,-10*n)},InOut:function(n){return n===0?0:n===1?1:(n*=2)<1?.5*Math.pow(1024,n-1):.5*(-Math.pow(2,-10*(n-1))+2)}}),Circular:Object.freeze({In:function(n){return 1-Math.sqrt(1-n*n)},Out:function(n){return Math.sqrt(1- --n*n)},InOut:function(n){return(n*=2)<1?-.5*(Math.sqrt(1-n*n)-1):.5*(Math.sqrt(1-(n-=2)*n)+1)}}),Elastic:Object.freeze({In:function(n){return n===0?0:n===1?1:-Math.pow(2,10*(n-1))*Math.sin((n-1.1)*5*Math.PI)},Out:function(n){return n===0?0:n===1?1:Math.pow(2,-10*n)*Math.sin((n-.1)*5*Math.PI)+1},InOut:function(n){return n===0?0:n===1?1:(n*=2,n<1?-.5*Math.pow(2,10*(n-1))*Math.sin((n-1.1)*5*Math.PI):.5*Math.pow(2,-10*(n-1))*Math.sin((n-1.1)*5*Math.PI)+1)}}),Back:Object.freeze({In:function(n){var e=1.70158;return n===1?1:n*n*((e+1)*n-e)},Out:function(n){var e=1.70158;return n===0?0:--n*n*((e+1)*n+e)+1},InOut:function(n){var e=2.5949095;return(n*=2)<1?.5*(n*n*((e+1)*n-e)):.5*((n-=2)*n*((e+1)*n+e)+2)}}),Bounce:Object.freeze({In:function(n){return 1-H0.Bounce.Out(1-n)},Out:function(n){return n<.36363636363636365?7.5625*n*n:n<.7272727272727273?7.5625*(n-=.5454545454545454)*n+.75:n<.9090909090909091?7.5625*(n-=.8181818181818182)*n+.9375:7.5625*(n-=.9545454545454546)*n+.984375},InOut:function(n){return n<.5?H0.Bounce.In(n*2)*.5:H0.Bounce.Out(n*2-1)*.5+.5}}),generatePow:function(n){return n===void 0&&(n=4),n=n<Number.EPSILON?Number.EPSILON:n,n=n>1e4?1e4:n,{In:function(e){return Math.pow(e,n)},Out:function(e){return 1-Math.pow(1-e,n)},InOut:function(e){return e<.5?Math.pow(e*2,n)/2:(1-Math.pow(2-e*2,n))/2+.5}}}}),b5=function(){return performance.now()},St=function(){function n(){this._tweens={},this._tweensAddedDuringUpdate={}}return n.prototype.getAll=function(){var e=this;return Object.keys(this._tweens).map(function(t){return e._tweens[t]})},n.prototype.removeAll=function(){this._tweens={}},n.prototype.add=function(e){this._tweens[e.getId()]=e,this._tweensAddedDuringUpdate[e.getId()]=e},n.prototype.remove=function(e){delete this._tweens[e.getId()],delete this._tweensAddedDuringUpdate[e.getId()]},n.prototype.update=function(e,t){e===void 0&&(e=b5()),t===void 0&&(t=!1);var r=Object.keys(this._tweens);if(r.length===0)return!1;for(;r.length>0;){this._tweensAddedDuringUpdate={};for(var i=0;i<r.length;i++){var s=this._tweens[r[i]],o=!t;s&&s.update(e,o)===!1&&!t&&delete this._tweens[r[i]]}r=Object.keys(this._tweensAddedDuringUpdate)}return!0},n}(),Mt={Linear:function(n,e){var t=n.length-1,r=t*e,i=Math.floor(r),s=Mt.Utils.Linear;return e<0?s(n[0],n[1],r):e>1?s(n[t],n[t-1],t-r):s(n[i],n[i+1>t?t:i+1],r-i)},Bezier:function(n,e){for(var t=0,r=n.length-1,i=Math.pow,s=Mt.Utils.Bernstein,o=0;o<=r;o++)t+=i(1-e,r-o)*i(e,o)*n[o]*s(r,o);return t},CatmullRom:function(n,e){var t=n.length-1,r=t*e,i=Math.floor(r),s=Mt.Utils.CatmullRom;return n[0]===n[t]?(e<0&&(i=Math.floor(r=t*(1+e))),s(n[(i-1+t)%t],n[i],n[(i+1)%t],n[(i+2)%t],r-i)):e<0?n[0]-(s(n[0],n[0],n[1],n[1],-r)-n[0]):e>1?n[t]-(s(n[t],n[t],n[t-1],n[t-1],r-t)-n[t]):s(n[i?i-1:0],n[i],n[t<i+1?t:i+1],n[t<i+2?t:i+2],r-i)},Utils:{Linear:function(n,e,t){return(e-n)*t+n},Bernstein:function(n,e){var t=Mt.Utils.Factorial;return t(n)/t(e)/t(n-e)},Factorial:function(){var n=[1];return function(e){var t=1;if(n[e])return n[e];for(var r=e;r>1;r--)t*=r;return n[e]=t,t}}(),CatmullRom:function(n,e,t,r,i){var s=(t-n)*.5,o=(r-e)*.5,a=i*i,v=i*a;return(2*e-2*t+s+o)*v+(-3*e+3*t-2*s-o)*a+s*i+e}}},us=function(){function n(){}return n.nextId=function(){return n._nextId++},n._nextId=0,n}(),Fr=new St,F0=function(){function n(e,t){t===void 0&&(t=Fr),this._object=e,this._group=t,this._isPaused=!1,this._pauseStart=0,this._valuesStart={},this._valuesEnd={},this._valuesStartRepeat={},this._duration=1e3,this._isDynamic=!1,this._initialRepeat=0,this._repeat=0,this._yoyo=!1,this._isPlaying=!1,this._reversed=!1,this._delayTime=0,this._startTime=0,this._easingFunction=H0.Linear.None,this._interpolationFunction=Mt.Linear,this._chainedTweens=[],this._onStartCallbackFired=!1,this._onEveryStartCallbackFired=!1,this._id=us.nextId(),this._isChainStopped=!1,this._propertiesAreSetUp=!1,this._goToEnd=!1}return n.prototype.getId=function(){return this._id},n.prototype.isPlaying=function(){return this._isPlaying},n.prototype.isPaused=function(){return this._isPaused},n.prototype.to=function(e,t){if(t===void 0&&(t=1e3),this._isPlaying)throw new Error("Can not call Tween.to() while Tween is already started or paused. Stop the Tween first.");return this._valuesEnd=e,this._propertiesAreSetUp=!1,this._duration=t,this},n.prototype.duration=function(e){return e===void 0&&(e=1e3),this._duration=e,this},n.prototype.dynamic=function(e){return e===void 0&&(e=!1),this._isDynamic=e,this},n.prototype.start=function(e,t){if(e===void 0&&(e=b5()),t===void 0&&(t=!1),this._isPlaying)return this;if(this._group&&this._group.add(this),this._repeat=this._initialRepeat,this._reversed){this._reversed=!1;for(var r in this._valuesStartRepeat)this._swapEndStartRepeatValues(r),this._valuesStart[r]=this._valuesStartRepeat[r]}if(this._isPlaying=!0,this._isPaused=!1,this._onStartCallbackFired=!1,this._onEveryStartCallbackFired=!1,this._isChainStopped=!1,this._startTime=e,this._startTime+=this._delayTime,!this._propertiesAreSetUp||t){if(this._propertiesAreSetUp=!0,!this._isDynamic){var i={};for(var s in this._valuesEnd)i[s]=this._valuesEnd[s];this._valuesEnd=i}this._setupProperties(this._object,this._valuesStart,this._valuesEnd,this._valuesStartRepeat,t)}return this},n.prototype.startFromCurrentValues=function(e){return this.start(e,!0)},n.prototype._setupProperties=function(e,t,r,i,s){for(var o in r){var a=e[o],v=Array.isArray(a),l=v?"array":typeof a,c=!v&&Array.isArray(r[o]);if(!(l==="undefined"||l==="function")){if(c){var d=r[o];if(d.length===0)continue;for(var f=[a],m=0,g=d.length;m<g;m+=1){var b=this._handleRelativeValue(a,d[m]);if(isNaN(b)){c=!1;break}f.push(b)}c&&(r[o]=f)}if((l==="object"||v)&&a&&!c){t[o]=v?[]:{};var w=a;for(var y in w)t[o][y]=w[y];i[o]=v?[]:{};var d=r[o];if(!this._isDynamic){var A={};for(var y in d)A[y]=d[y];r[o]=d=A}this._setupProperties(w,t[o],d,i[o],s)}else(typeof t[o]>"u"||s)&&(t[o]=a),v||(t[o]*=1),c?i[o]=r[o].slice().reverse():i[o]=t[o]||0}}},n.prototype.stop=function(){return this._isChainStopped||(this._isChainStopped=!0,this.stopChainedTweens()),this._isPlaying?(this._group&&this._group.remove(this),this._isPlaying=!1,this._isPaused=!1,this._onStopCallback&&this._onStopCallback(this._object),this):this},n.prototype.end=function(){return this._goToEnd=!0,this.update(1/0),this},n.prototype.pause=function(e){return e===void 0&&(e=b5()),this._isPaused||!this._isPlaying?this:(this._isPaused=!0,this._pauseStart=e,this._group&&this._group.remove(this),this)},n.prototype.resume=function(e){return e===void 0&&(e=b5()),!this._isPaused||!this._isPlaying?this:(this._isPaused=!1,this._startTime+=e-this._pauseStart,this._pauseStart=0,this._group&&this._group.add(this),this)},n.prototype.stopChainedTweens=function(){for(var e=0,t=this._chainedTweens.length;e<t;e++)this._chainedTweens[e].stop();return this},n.prototype.group=function(e){return e===void 0&&(e=Fr),this._group=e,this},n.prototype.delay=function(e){return e===void 0&&(e=0),this._delayTime=e,this},n.prototype.repeat=function(e){return e===void 0&&(e=0),this._initialRepeat=e,this._repeat=e,this},n.prototype.repeatDelay=function(e){return this._repeatDelayTime=e,this},n.prototype.yoyo=function(e){return e===void 0&&(e=!1),this._yoyo=e,this},n.prototype.easing=function(e){return e===void 0&&(e=H0.Linear.None),this._easingFunction=e,this},n.prototype.interpolation=function(e){return e===void 0&&(e=Mt.Linear),this._interpolationFunction=e,this},n.prototype.chain=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return this._chainedTweens=e,this},n.prototype.onStart=function(e){return this._onStartCallback=e,this},n.prototype.onEveryStart=function(e){return this._onEveryStartCallback=e,this},n.prototype.onUpdate=function(e){return this._onUpdateCallback=e,this},n.prototype.onRepeat=function(e){return this._onRepeatCallback=e,this},n.prototype.onComplete=function(e){return this._onCompleteCallback=e,this},n.prototype.onStop=function(e){return this._onStopCallback=e,this},n.prototype.update=function(e,t){if(e===void 0&&(e=b5()),t===void 0&&(t=!0),this._isPaused)return!0;var r,i,s=this._startTime+this._duration;if(!this._goToEnd&&!this._isPlaying){if(e>s)return!1;t&&this.start(e,!0)}if(this._goToEnd=!1,e<this._startTime)return!0;this._onStartCallbackFired===!1&&(this._onStartCallback&&this._onStartCallback(this._object),this._onStartCallbackFired=!0),this._onEveryStartCallbackFired===!1&&(this._onEveryStartCallback&&this._onEveryStartCallback(this._object),this._onEveryStartCallbackFired=!0),i=(e-this._startTime)/this._duration,i=this._duration===0||i>1?1:i;var o=this._easingFunction(i);if(this._updateProperties(this._object,this._valuesStart,this._valuesEnd,o),this._onUpdateCallback&&this._onUpdateCallback(this._object,i),i===1)if(this._repeat>0){isFinite(this._repeat)&&this._repeat--;for(r in this._valuesStartRepeat)!this._yoyo&&typeof this._valuesEnd[r]=="string"&&(this._valuesStartRepeat[r]=this._valuesStartRepeat[r]+parseFloat(this._valuesEnd[r])),this._yoyo&&this._swapEndStartRepeatValues(r),this._valuesStart[r]=this._valuesStartRepeat[r];return this._yoyo&&(this._reversed=!this._reversed),this._repeatDelayTime!==void 0?this._startTime=e+this._repeatDelayTime:this._startTime=e+this._delayTime,this._onRepeatCallback&&this._onRepeatCallback(this._object),this._onEveryStartCallbackFired=!1,!0}else{this._onCompleteCallback&&this._onCompleteCallback(this._object);for(var a=0,v=this._chainedTweens.length;a<v;a++)this._chainedTweens[a].start(this._startTime+this._duration,!1);return this._isPlaying=!1,!1}return!0},n.prototype._updateProperties=function(e,t,r,i){for(var s in r)if(t[s]!==void 0){var o=t[s]||0,a=r[s],v=Array.isArray(e[s]),l=Array.isArray(a),c=!v&&l;c?e[s]=this._interpolationFunction(a,i):typeof a=="object"&&a?this._updateProperties(e[s],o,a,i):(a=this._handleRelativeValue(o,a),typeof a=="number"&&(e[s]=o+(a-o)*i))}},n.prototype._handleRelativeValue=function(e,t){return typeof t!="string"?t:t.charAt(0)==="+"||t.charAt(0)==="-"?e+parseFloat(t):parseFloat(t)},n.prototype._swapEndStartRepeatValues=function(e){var t=this._valuesStartRepeat[e],r=this._valuesEnd[e];typeof r=="string"?this._valuesStartRepeat[e]=this._valuesStartRepeat[e]+parseFloat(r):this._valuesStartRepeat[e]=this._valuesEnd[e],this._valuesEnd[e]=t},n}();var mh=us.nextId,be=Fr,ph=be.getAll.bind(be),gh=be.removeAll.bind(be),bh=be.add.bind(be),yh=be.remove.bind(be),fs=be.update.bind(be);E();x();k();R();var Y6=(n,e)=>{try{return JSON.parse(n)}catch{return null}},Q6={black:"#000000",dark_blue:"#0000AA",dark_green:"#00AA00",dark_aqua:"#00AAAA",dark_red:"#AA0000",dark_purple:"#AA00AA",gold:"#FFAA00",gray:"#AAAAAA",dark_gray:"#555555",blue:"#5555FF",green:"#55FF55",aqua:"#55FFFF",red:"#FF5555",light_purple:"#FF55FF",yellow:"#FFFF55",white:"#FFFFFF"},m1=(n,e,t,r=s=>{},i=(s,o)=>V0(s,o))=>{let a=[16,9],v=a[0]-a[1],l=v/16,c="front_text"in n?n.front_text.messages:[n.Text1,n.Text2,n.Text3,n.Text4];if(!c.some(g=>g!=="null"))return;let d=i(16*40,v*40),f=d.getContext("2d");r(f);let m=("front_text"in n?n.front_text.color:n.Color)||"black";for(let[g,b]of c.slice(0,4).entries())b!=="null"&&Dr(b,t,d,64,m,64*(g+1)+(e?0:-8));return d},Dr=(n,e,t,r,i,s=0)=>{let o=!1,a=typeof n=="string"&&(n?.startsWith("{")||n?.startsWith('"'))?Y6(n??'""',"sign text"):n;if(!a||typeof a!="object"&&typeof a!="string")return;let v=t.getContext("2d");if(!v)throw new Error("Could not get 2d context");v.imageSmoothingEnabled=!1,v.font=`${r}px mojangles`;let l=new e(a),c=[],d=!1,f="",m=s,g=[],b=(C,M)=>{C.text!==null&&C.text!==void 0&&C.text;let S=C.text===null||C.text===void 0?void 0:String(C.text),H={color:C.color??M?.color,underlined:C.underlined??M?.underlined,strikethrough:C.strikethrough??M?.strikethrough,bold:C.bold??M?.bold,italic:C.italic??M?.italic};if(d=d||H.underlined||H.strikethrough||!1,S?.includes(`
|
|
286
286
|
`))for(let B of S.split(`
|
|
287
287
|
`))w(B,H),m+=r,f="";else S&&w(S,H);if(C.extra)for(let B of C.extra)b(B,H)},w=(C,M)=>{o||(o=C.trim()!==""),f+=C,g[m]=v.measureText(f).width;let S=M.color??i;S.startsWith("#")||(S=Q6[S.toLowerCase()]||S),c.push({fontStyle:`${M.bold?"bold":""} ${M.italic?"italic":""}`,fillStyle:S,underlineStyle:M.underlined??!1,strikeStyle:M.strikethrough??!1,offset:m,text:C})};if(b(l),!d&&!l.toString().trim())return;let y=0,A=0;for(let{fillStyle:C,fontStyle:M,underlineStyle:S,strikeStyle:H,offset:B,text:I}of c){A!==B&&(y=0),A=B,v.fillStyle=C,v.textRendering="optimizeLegibility",v.font=`${M} ${r}px mojangles`;let G=g[B]??v.measureText(I).width,O=(t.width-G)/2+y;v.fillText(I,O,B),H&&(v.lineWidth=r/8,v.strokeStyle=C,v.beginPath(),v.moveTo(O,B-v.lineWidth*2.5),v.lineTo(O+v.measureText(I).width,B-v.lineWidth*2.5),v.stroke()),S&&(v.lineWidth=r/8,v.strokeStyle=C,v.beginPath(),v.moveTo(O,B+v.lineWidth),v.lineTo(O+v.measureText(I).width,B+v.lineWidth),v.stroke()),y+=v.measureText(I).width}return o};E();x();k();R();function Ct(n){let e=Math.floor(n.x/16),t=Math.floor(n.z/16);return[e,t]}function zr(n){let e=Math.floor(n.x/16),t=Math.floor(n.y/16),r=Math.floor(n.z/16);return[e,t,r]}E();x();k();R();import{Vec3 as A5}from"vec3";import{subscribeKey as Kr}from"valtio/utils";import{proxy as X6,subscribe as $6}from"valtio";E();x();k();R();var y5={blocks:"blocksArray",blockCollisionShapes:"blockCollisionShapes",biomes:"biomesArray"};E();x();k();R();var hs=16;var ms=(n,e)=>e?`${n}:${e}`:String(n);E();x();k();R();E();x();k();R();var Nr=s5(ps(),1);import*as b1 from"three";E();x();k();R();E();x();k();R();var p1=class{constructor(e,t,r){this.name=e,this.fg=t,this.bg=r,this.PR=Math.round(window.devicePixelRatio||1),this.WIDTH=90*this.PR,this.HEIGHT=48*this.PR,this.TEXT_X=3*this.PR,this.TEXT_Y=2*this.PR,this.GRAPH_X=3*this.PR,this.GRAPH_Y=15*this.PR,this.GRAPH_WIDTH=84*this.PR,this.GRAPH_HEIGHT=30*this.PR,this.canvas=document.createElement("canvas"),this.canvas.width=90*this.PR,this.canvas.height=48*this.PR,this.canvas.style.width="90px",this.canvas.style.position="absolute",this.canvas.style.height="48px",this.canvas.style.cssText="width:90px;height:48px",this.context=this.canvas.getContext("2d"),this.context&&(this.context.font="bold "+9*this.PR+"px Helvetica,Arial,sans-serif",this.context.textBaseline="top",this.context.fillStyle=this.bg,this.context.fillRect(0,0,this.WIDTH,this.HEIGHT),this.context.fillStyle=this.fg,this.context.fillText(this.name,this.TEXT_X,this.TEXT_Y),this.context.fillRect(this.GRAPH_X,this.GRAPH_Y,this.GRAPH_WIDTH,this.GRAPH_HEIGHT),this.context.fillStyle=this.bg,this.context.globalAlpha=.9,this.context.fillRect(this.GRAPH_X,this.GRAPH_Y,this.GRAPH_WIDTH,this.GRAPH_HEIGHT))}update(e,t,r,i,s=0){let o=1/0,a=0;this.context&&(o=Math.min(o,e),a=Math.max(r,e),i=Math.max(i,t),this.context.fillStyle=this.bg,this.context.globalAlpha=1,this.context.fillRect(0,0,this.WIDTH,this.GRAPH_Y),this.context.fillStyle=this.fg,this.context.fillText(e.toFixed(s)+" "+this.name+" ("+o.toFixed(s)+"-"+parseFloat(a.toFixed(s))+")",this.TEXT_X,this.TEXT_Y),this.context.drawImage(this.canvas,this.GRAPH_X+this.PR,this.GRAPH_Y,this.GRAPH_WIDTH-this.PR,this.GRAPH_HEIGHT,this.GRAPH_X,this.GRAPH_Y,this.GRAPH_WIDTH-this.PR,this.GRAPH_HEIGHT),this.context.fillRect(this.GRAPH_X+this.GRAPH_WIDTH-this.PR,this.GRAPH_Y,this.PR,this.GRAPH_HEIGHT),this.context.fillStyle=this.bg,this.context.globalAlpha=.9,this.context.fillRect(this.GRAPH_X+this.GRAPH_WIDTH-this.PR,this.GRAPH_Y,this.PR,(1-t/i)*this.GRAPH_HEIGHT))}};var gs=class g1{constructor({logsPerSecond:e=20,samplesLog:t=100,samplesGraph:r=10,precision:i=2,minimal:s=!1,horizontal:o=!0,mode:a=0}={}){this.mode=a,this.horizontal=o,this.container=document.createElement("div"),this.container.style.cssText="position:fixed;top:0;left:0;opacity:0.9;z-index:10000;",s&&(this.container.style.cssText+="cursor:pointer"),this.gl=null,this.query=null,this.minimal=s,this.beginTime=(performance||Date).now(),this.prevTime=this.beginTime,this.prevCpuTime=this.beginTime,this.frames=0,this.averageCpu={logs:[],graph:[]},this.averageGpu={logs:[],graph:[]},this.queryCreated=!1,this.fpsPanel=this.addPanel(new g1.Panel("FPS","#0ff","#002"),0),this.msPanel=this.addPanel(new g1.Panel("CPU","#0f0","#020"),1),this.gpuPanel=null,this.samplesLog=t,this.samplesGraph=r,this.precision=i,this.logsPerSecond=e,this.minimal?(this.container.addEventListener("click",v=>{v.preventDefault(),this.showPanel(++this.mode%this.container.children.length)},!1),this.mode=a,this.showPanel(this.mode)):window.addEventListener("resize",()=>{this.resizePanel(this.fpsPanel,0),this.resizePanel(this.msPanel,1),this.gpuPanel&&this.resizePanel(this.gpuPanel,2)})}resizePanel(e,t){e.canvas.style.position="absolute",this.minimal?e.canvas.style.display="none":(e.canvas.style.display="block",this.horizontal?(e.canvas.style.top="0px",e.canvas.style.left=t*e.WIDTH/e.PR+"px"):(e.canvas.style.left="0px",e.canvas.style.top=t*e.HEIGHT/e.PR+"px"))}addPanel(e,t){return e.canvas&&(this.container.appendChild(e.canvas),this.resizePanel(e,t)),e}showPanel(e){for(let t=0;t<this.container.children.length;t++){let r=this.container.children[t];r.style.display=t===e?"block":"none"}this.mode=e}init(e){if(e){if(e instanceof WebGL2RenderingContext)this.gl=e;else if(e instanceof HTMLCanvasElement||e instanceof OffscreenCanvas){if(this.gl=e.getContext("webgl2"),!this.gl)return}else return;this.ext=this.gl.getExtension("EXT_disjoint_timer_query_webgl2"),this.ext&&(this.gpuPanel=this.addPanel(new g1.Panel("GPU","#ff0","#220"),2))}}begin(){if(this.beginProfiling("cpu-started"),!(!this.gl||!this.ext)){if(this.query){let e=this.gl.getQueryParameter(this.query,this.gl.QUERY_RESULT_AVAILABLE);if(this.disjoint=this.gl.getParameter(this.ext.GPU_DISJOINT_EXT),e&&!this.disjoint){this.ns=this.gl.getQueryParameter(this.query,this.gl.QUERY_RESULT);let t=this.ns*1e-6;(e||this.disjoint)&&(this.gl.deleteQuery(this.query),this.query=null),e&&this.addToAverage(t,this.averageGpu)}}this.query||(this.queryCreated=!0,this.query=this.gl.createQuery(),this.query&&this.gl.beginQuery(this.ext.TIME_ELAPSED_EXT,this.query))}}end(){this.beginTime=this.endInternal(),this.endProfiling("cpu-started","cpu-finished","cpu-duration",this.averageCpu),!(!this.gl||!this.ext)&&this.queryCreated&&this.gl.getQuery(this.ext.TIME_ELAPSED_EXT,this.gl.CURRENT_QUERY)&&this.gl.endQuery(this.ext.TIME_ELAPSED_EXT)}endInternal(){this.frames++;let e=(performance||Date).now();if(e>=this.prevCpuTime+1e3/this.logsPerSecond&&(this.updatePanel(this.msPanel,this.averageCpu),this.updatePanel(this.gpuPanel,this.averageGpu),this.prevCpuTime=e),e>=this.prevTime+1e3){let t=this.frames*1e3/(e-this.prevTime);this.fpsPanel.update(t,t,100,100,0),this.prevTime=e,this.frames=0}return e}addToAverage(e,t){t.logs.push(e),t.logs.length>this.samplesLog&&t.logs.shift(),t.graph.push(e),t.graph.length>this.samplesGraph&&t.graph.shift()}beginProfiling(e){window.performance&&window.performance.mark(e)}endProfiling(e,t,r,i){if(window.performance&&t){window.performance.mark(t);let s=performance.measure(r,e,t);this.addToAverage(s.duration,i)}}updatePanel(e,t){if(t.logs.length>0){let r=0,i=.01;for(let a=0;a<t.logs.length;a++)r+=t.logs[a],t.logs[a]>i&&(i=t.logs[a]);let s=0,o=.01;for(let a=0;a<t.graph.length;a++)s+=t.graph[a],t.graph[a]>o&&(o=t.graph[a]);e&&e.update(r/Math.min(t.logs.length,this.samplesLog),s/Math.min(t.graph.length,this.samplesGraph),i,o,this.precision)}}};gs.Panel=p1;var bs=gs;E();x();k();R();function Gr(n){if(n==="high-performance")return"high-performance";if(n==="low-power")return"low-power"}var k0=typeof globalThis.WorkerGlobalScope<"u"&&globalThis instanceof globalThis.WorkerGlobalScope,Wr=class{constructor(e,t=0){this.canvas=e;u(this,"stats");u(this,"stats2");u(this,"statsGl");u(this,"total",0);u(this,"denseMode");this.stats=new Nr.default,this.stats2=new Nr.default,this.statsGl=new bs({minimal:!0}),this.stats2.showPanel(2),this.denseMode=typeof F<"u"&&!0||typeof window<"u"&&window.innerHeight<500,this.initStats(),this.setVisibility(t)}addStat(e,t=80){e.style.position="absolute",this.denseMode&&(e.style.height="12px"),e.style.overflow="hidden",e.style.left="",e.style.top="0",e.style.right=`${this.total}px`,e.style.width="80px",e.style.zIndex="1",e.style.opacity="0.8";let r=document.getElementById("corner-indicator-stats"),i=r??document.body;r&&(e.style.position="relative"),i.appendChild(e),this.total+=t}initStats(){let e=this.stats2.dom.children.length===3;this.addStat(this.stats.dom),e&&this.addStat(this.stats2.dom),this.statsGl.init(this.canvas),this.statsGl.container.style.display="flex",this.statsGl.container.style.justifyContent="flex-end";let t=0;for(let r of this.statsGl.container.children){let i=r;t++===0&&(i.style.display="none"),i.style.position=""}}setVisibility(e){e>0?(this.stats.dom.style.display="block",this.stats2.dom.style.display=e>=2?"block":"none",this.statsGl.container.style.display=e>=2?"block":"none"):(this.stats.dom.style.display="none",this.stats2.dom.style.display="none",this.statsGl.container.style.display="none")}markStart(){this.stats.begin(),this.stats2.begin(),this.statsGl.begin()}markEnd(){this.stats.end(),this.stats2.end(),this.statsGl.end()}dispose(){this.stats.dom.remove(),this.stats2.dom.remove(),this.statsGl.container.remove()}},_5=class{constructor(e,t,r){this.initOptions=e;this.externalCanvas=t;u(this,"canvas");u(this,"renderer");u(this,"animationFrameId");u(this,"timeoutId");u(this,"lastRenderTime",0);u(this,"previousCanvasWidth",0);u(this,"previousCanvasHeight",0);u(this,"currentWidth",0);u(this,"currentHeight",0);u(this,"pendingResize",!1);u(this,"renderedFps",0);u(this,"fpsInterval");u(this,"stats");u(this,"paused",!1);u(this,"disconnected",!1);u(this,"preRender",()=>{});u(this,"render",e=>{});u(this,"postRender",()=>{});u(this,"sizeChanged",()=>{});u(this,"droppedFpsPercentage",0);u(this,"config");u(this,"onRender",[]);u(this,"inWorldRenderingConfig");u(this,"nonReactiveState");this.config=e.config,t?this.canvas=t:this.addToPage();try{let s=e.getRendererOptions?.()?.gpuPreference??"default";this.renderer=new b1.WebGLRenderer({canvas:this.canvas,preserveDrawingBuffer:!0,logarithmicDepthBuffer:!0,powerPreference:Gr(s)})}catch(s){throw e.callbacks.displayCriticalError(new Error(`Failed to create WebGL context, not possible to render (restart browser): ${s.message}`)),s}this.renderer.useLegacyLights=!0,this.renderer.outputColorSpace=b1.LinearSRGBColorSpace,t||(this.updatePixelRatio(),this.setupResizeListener()),this.sizeUpdated(),this.previousCanvasWidth=this.canvas.width,this.previousCanvasHeight=this.canvas.height;let i="WebGL2RenderingContext"in globalThis;!t&&i&&!k0&&(this.stats=new Wr(this.canvas,this.config.statsVisible)),this.setupFpsTracking(),this.startRenderLoop()}setupResizeListener(){if(typeof window>"u")return;let e,t=()=>{e&&clearTimeout(e),e=setTimeout(()=>{this.pendingResize=!0},16)};window.addEventListener("resize",t,{passive:!0})}updatePixelRatio(){if(typeof window>"u")return;let e=window.devicePixelRatio||1;this.renderer.capabilities.isWebGL2||(e=1),this.renderer.setPixelRatio(e)}sizeUpdated(){this.renderer.setSize(this.currentWidth,this.currentHeight,!1)}addToPage(){this.canvas=ys(),this.updateCanvasSize()}updateSizeExternal(e,t,r){this.currentWidth=e,this.currentHeight=t,this.renderer.setPixelRatio(r),this.sizeUpdated()}updateCanvasSize(){if(this.externalCanvas||typeof document>"u")return;let e=document.body.offsetWidth,t=document.body.offsetHeight;this.currentWidth!==e&&(this.currentWidth=e),this.currentHeight!==t&&(this.currentHeight=t)}setupFpsTracking(){let e=0;this.fpsInterval=setInterval(()=>{e>0&&(this.droppedFpsPercentage=this.renderedFps/e),e=Math.max(this.renderedFps,e),this.nonReactiveState&&(this.nonReactiveState.fps=this.renderedFps),this.renderedFps=0},1e3)}startRenderLoop(){let e=()=>{if(this.disconnected)return;if(this.config.timeoutRendering){let i=1e3/(this.config.fpsLimit?Math.min(this.config.fpsLimit,60):60);this.timeoutId=setTimeout(e,i)}else this.animationFrameId=requestAnimationFrame(e);if(this.paused||this.renderer.xr.isPresenting&&!this.inWorldRenderingConfig?.vrPageGameRendering)return;if(!this.config.timeoutRendering&&this.config.fpsLimit){let r=performance.now(),i=r-this.lastRenderTime,s=1e3/this.config.fpsLimit;if(i<s)return;this.lastRenderTime=r-i%s}let t=!1;this.pendingResize&&(this.updateCanvasSize(),this.pendingResize=!1),(this.previousCanvasWidth!==this.currentWidth||this.previousCanvasHeight!==this.currentHeight)&&(this.previousCanvasWidth=this.currentWidth,this.previousCanvasHeight=this.currentHeight,this.sizeUpdated(),t=!0),this.frameRender(t),this.config.statsVisible!==void 0&&this.stats?.setVisibility(this.config.statsVisible)};e()}frameRender(e){this.preRender(),this.stats?.markStart(),fs(),globalThis.freezeRender||this.render(e);for(let t of this.onRender)t(e);this.renderedFps++,this.stats?.markEnd(),this.postRender()}setPaused(e){this.paused=e}dispose(){this.disconnected=!0,this.animationFrameId&&cancelAnimationFrame(this.animationFrameId),this.timeoutId&&clearTimeout(this.timeoutId),this.canvas instanceof HTMLCanvasElement&&this.canvas.remove(),clearInterval(this.fpsInterval),this.stats?.dispose(),this.renderer.dispose()}};function ys(){let n=document.createElement("canvas");return n.id="viewer-canvas",document.body.appendChild(n),n}var Vr=()=>{let n=ys(),e=n.transferControlToOffscreen(),t=!1,r=(o,a)=>{},i={width:0,height:0},s=()=>{t||((i.width!==window.innerWidth||i.height!==window.innerHeight)&&(r(window.innerWidth,window.innerHeight),i={width:window.innerWidth,height:window.innerHeight}),requestAnimationFrame(s))};return requestAnimationFrame(s),{canvas:e,destroy(){t=!0,n.remove()},onSizeChanged(o){r=o},get size(){return{width:window.innerWidth,height:window.innerHeight}}}};var _s=0,xe={},jr=40,w5="mc-renderer-debug-overlay",Bt=(n,e=80,t=_s,r=jr,i)=>{if(k0)return{updateText(){},setVisibility(){}};let s=document.createElement("div");return s.style.position="fixed",s.style.top=`${r??jr}px`,s.style.right=`${t}px`,s.style.backgroundColor="rgba(0, 0, 0, 0.7)",s.style.color="white",s.style.padding="2px",s.style.fontFamily="monospace",s.style.fontSize="12px",i?.className?s.className=i.className:s.style.zIndex="100",s.style.pointerEvents="none",document.body.appendChild(s),xe[n]=s,r===void 0&&t===_s&&(jr+=20),{updateText(o){s.innerText!==o&&(s.innerText=o)},setVisibility(o){s.style.display=o?"block":"none"}}};var Yr=(n,e)=>{k0||!xe[n]||(xe[n].innerText=e)},ws=n=>{if(!k0)for(let e in xe)xe[e].style.display=n?"block":"none"},As=()=>{if(!k0)for(let n in xe)K6(n)},K6=n=>{k0||!xe[n]||(xe[n].remove(),delete xe[n])};E();x();k();R();var J6=n=>{let e=n%24e3/24e3-.25;return e<0&&(e+=1),e>1&&(e-=1),e+(1-Math.cos(e*Math.PI))/2},q6=n=>{let e=(n%24e3+24e3)%24e3,t=J6(e),i=Math.cos(t*Math.PI*2)*.5+.5,s=Math.round(4+i*11);return Math.max(4,Math.min(15,s))},Qr=n=>{let e=(n%24e3+24e3)%24e3;if(e>=0&&e<12e3)return 15;if(e>=12e3&&e<13e3){let t=(e-12e3)/1e3;return Math.round(15-t*11)}else{if(e>=13e3&&e<23e3)return 4;{let t=(e-23e3)/1e3;return Math.round(4+t*11)}}},Z6=()=>{let n=[{ticks:0,label:"6:00 AM (sunrise)"},{ticks:6e3,label:"12:00 PM (noon)"},{ticks:12e3,label:"6:00 PM (sunset starts)"},{ticks:12500,label:"6:30 PM (sunset mid)"},{ticks:13e3,label:"7:00 PM (night begins)"},{ticks:18e3,label:"12:00 AM (midnight)"},{ticks:19e3,label:"1:00 AM"},{ticks:23e3,label:"5:00 AM (dawn begins)"},{ticks:23500,label:"5:30 AM (dawn mid)"}];for(let{ticks:e,label:t}of n){let r=q6(e),i=Qr(e)}};typeof window<"u"&&(window.debugSkyLight=Z6);function E5(n,e){return(n%e+e)%e}var Re=class Re{constructor(e,t,r){this.resourcesManager=e;this.displayOptions=t;this.initOptions=r;u(this,"worldReadyResolvers",Promise.withResolvers());u(this,"worldReadyPromise",this.worldReadyResolvers.promise);u(this,"timeOfTheDay",0);u(this,"worldSizeParams",{minY:0,worldHeight:256});u(this,"reactiveDebugParams",X6({stopRendering:!1,chunksRenderAboveOverride:void 0,chunksRenderAboveEnabled:!1,chunksRenderBelowOverride:void 0,chunksRenderBelowEnabled:!1,chunksRenderDistanceOverride:void 0,chunksRenderDistanceEnabled:!1,disableEntities:!1}));u(this,"active",!1);u(this,"loadedChunks",{});u(this,"finishedChunks",{});u(this,"finishedSections",{});u(this,"sectionsWaiting",new Map);u(this,"queuedChunks",new Set);u(this,"queuedFunctions",[]);u(this,"renderUpdateEmitter",new Xe);u(this,"customTexturesDataUrl");u(this,"workers",[]);u(this,"viewerChunkPosition");u(this,"lastViewerChunkGridX");u(this,"lastViewerChunkGridZ");u(this,"lastCamUpdate",0);u(this,"droppedFpsPercentage",0);u(this,"initialChunkLoadWasStartedIn");u(this,"initialChunksLoad",!0);u(this,"enableChunksLoadDelay",!1);u(this,"texturesVersion");u(this,"viewDistance",-1);u(this,"onRenderDistanceChanged");u(this,"chunksLength",0);u(this,"allChunksFinished",!1);u(this,"messageQueue",[]);u(this,"isProcessingQueue",!1);u(this,"ONMESSAGE_TIME_LIMIT",30);u(this,"handleResize",()=>{});u(this,"highestBlocksByChunks",new Map);u(this,"blockEntities",{});u(this,"workersProcessAverageTime",0);u(this,"workersProcessAverageTimeCount",0);u(this,"maxWorkersProcessTime",0);u(this,"workersPreAverageTime",0);u(this,"workersWasmAverageTime",0);u(this,"workersPostAverageTime",0);u(this,"workersPhaseSampleCount",0);u(this,"workersPreTargetConvertAverageTime",0);u(this,"workersPreNeighborConvertAverageTime",0);u(this,"workersPreNeighborCountAverage",0);u(this,"workersPreTypedArrayBuildAverageTime",0);u(this,"workersPreOtherAverageTime",0);u(this,"workersPreCacheHitsTotal",0);u(this,"workersPreCacheMissesTotal",0);u(this,"geometryReceiveCount",{});u(this,"allLoadedIn");u(this,"onWorldSwitched",[]);u(this,"renderTimeMax",0);u(this,"renderTimeAvg",0);u(this,"renderTimeAvgCount",0);u(this,"edgeChunks",{});u(this,"lastAddChunk",null);u(this,"neighborChunkUpdates",!0);u(this,"lastChunkDistance",0);u(this,"debugStopGeometryUpdate",!1);u(this,"protocolCustomBlocks",new Map);u(this,"heightmapDebounceTimers",new Map);u(this,"sectionDirtyCount",new Map);u(this,"sectionDirtyTimers",new Map);u(this,"sectionDirtyPendingArgs",new Map);u(this,"blockStateModelInfo",new Map);u(this,"worldBlockProvider");u(this,"soundSystem");u(this,"worldRendererConfig");u(this,"playerStateReactive");u(this,"playerStateUtils");u(this,"reactiveState");u(this,"mesherLogReader");u(this,"forceCallFromMesherReplayer",!1);u(this,"stopMesherMessagesProcessing",!1);u(this,"abortController",new AbortController);u(this,"lastRendered",0);u(this,"renderingActive",!0);u(this,"geometryReceiveCountPerSec",0);u(this,"mesherLogger",{contents:[],active:new URL(location.href).searchParams.get("mesherlog")==="true"});u(this,"currentRenderedFrames",0);u(this,"fpsAverage",0);u(this,"lastFps",0);u(this,"fpsWorst");u(this,"fpsSamples",0);u(this,"backendInfoReport","-");u(this,"chunksFullInfo","-");u(this,"workerCustomHandleTime",0);u(this,"queueAwaited",!1);u(this,"toWorkerMessagesQueue",{});this.snapshotInitialValues(),this.worldRendererConfig=t.inWorldRenderingConfig,this.playerStateReactive=t.playerStateReactive,this.playerStateUtils=W2(this.playerStateReactive),this.reactiveState=t.rendererState,this.renderUpdateEmitter.on("update",()=>{let o=Object.keys(this.finishedChunks).length;Yr("loaded-chunks",`${o}/${this.chunksLength} chunks (${this.lastChunkDistance}/${this.viewDistance})`)}),Bt("downloaded-chunks",100,140,20,{className:w5}),this.connect(this.displayOptions.worldView);let i=setInterval(()=>{this.geometryReceiveCountPerSec=Object.values(this.geometryReceiveCount).reduce((o,a)=>o+a,0),this.geometryReceiveCount={},ws(this.displayAdvancedStats),this.updateChunksStats()},500),s=setInterval(()=>{this.fpsUpdate()},1e3);this.abortController.signal.addEventListener("abort",()=>{clearInterval(i),clearInterval(s)})}anyModuleRequiresHeightmap(){return!1}isShaderCubeBlocksEnabled(){return this.worldRendererConfig.shaderCubeBlocks===!0}shaderCubeBlocksEnabled(){return this.isShaderCubeBlocksEnabled()}get version(){return this.displayOptions.version}get displayAdvancedStats(){return(this.initOptions.config.statsVisible??0)>1}fpsUpdate(){this.fpsSamples++,this.fpsAverage=(this.fpsAverage*(this.fpsSamples-1)+this.currentRenderedFrames)/this.fpsSamples,this.fpsWorst===void 0?this.fpsWorst=this.currentRenderedFrames:this.fpsWorst=Math.min(this.fpsWorst,this.currentRenderedFrames),this.lastFps=this.currentRenderedFrames,this.displayOptions.nonReactiveState.fps=this.currentRenderedFrames,this.displayOptions.nonReactiveState.worstRenderTime=this.renderTimeMax,this.displayOptions.nonReactiveState.avgRenderTime=this.renderTimeAvg,this.currentRenderedFrames=0}logWorkerWork(e){this.mesherLogger.active&&this.mesherLogger.contents.push(typeof e=="function"?e():e)}async init(){if(this.active)throw new Error("WorldRendererCommon is already initialized");await Promise.all([this.resetWorkers(),(async()=>{this.resourcesManager.currentResources?.allReady&&await this.updateAssetsData()})()]),this.resourcesManager.on("assetsTexturesUpdated",async()=>{this.active&&await this.updateAssetsData()}),this.watchReactivePlayerState(),this.watchReactiveConfig(),this.worldReadyResolvers.resolve()}snapshotInitialValues(){}wasChunkSentToWorker(e){return this.loadedChunks[e]}async getHighestBlocks(e){return this.highestBlocksByChunks.get(e)}updateCustomBlock(e,t,r){if(this.protocolCustomBlocks.set(e,{...this.protocolCustomBlocks.get(e),[t]:r}),this.logWorkerWork(()=>`-> updateCustomBlock ${e} ${t} ${r} ${this.wasChunkSentToWorker(e)}`),this.wasChunkSentToWorker(e)){let[i,s,o]=t.split(",").map(Number);this.setBlockStateId(new A5(i,s,o),void 0)}}async getBlockInfo(e,t){let i=`${Math.floor(e.x/16)*16},${Math.floor(e.z/16)*16}`,s=this.protocolCustomBlocks.get(i)?.[`${e.x},${e.y},${e.z}`],o=ms(t,s),a=this.blockStateModelInfo.get(o);return{customBlockName:s,modelInfo:a}}initWorkers(e=this.worldRendererConfig.mesherWorkers){for(let t=0;t<e+0;t++){let r=e7(i=>{Array.isArray(i)?this.messageQueue.push(...i):this.messageQueue.push(i),this.processMessageQueue("worker")},this.worldRendererConfig.wasmMesher?"mesherWasm.js":"mesher.js");this.workers.push(r)}}onReactivePlayerStateUpdated(e,t,r=!0){return r&&t(this.playerStateReactive[e]),Kr(this.playerStateReactive,e,t)}onReactiveConfigUpdated(e,t){t(this.worldRendererConfig[e]),e==="*"?$6(this.worldRendererConfig,t):Kr(this.worldRendererConfig,e,t)}onReactiveDebugUpdated(e,t){t(this.reactiveDebugParams[e]),Kr(this.reactiveDebugParams,e,t)}watchReactivePlayerState(){this.onReactivePlayerStateUpdated("backgroundColor",e=>{this.changeBackgroundColor(e)}),this.onReactivePlayerStateUpdated("cardinalLight",e=>{this.changeCardinalLight(e)})}watchReactiveConfig(){this.onReactiveConfigUpdated("fetchPlayerSkins",e=>{c1({apiEnabled:e})})}async processMessageQueue(e){if(this.isProcessingQueue||this.messageQueue.length===0)return;if(this.logWorkerWork(`# ${e} processing queue`),this.lastRendered&&performance.now()-this.lastRendered>this.ONMESSAGE_TIME_LIMIT&&this.worldRendererConfig._experimentalSmoothChunkLoading&&this.renderingActive){let i=performance.now();await new Promise(s=>{requestAnimationFrame(s)}),this.logWorkerWork(`# processing got delayed by ${performance.now()-i}ms`)}this.isProcessingQueue=!0;let t=performance.now(),r=0;for(;this.messageQueue.length>0;){let i=this.stopMesherMessagesProcessing;if(!i){let s=this.messageQueue.shift();this.handleMessage(s),r++}if(i||performance.now()-t>this.ONMESSAGE_TIME_LIMIT&&this.renderingActive&&this.worldRendererConfig._experimentalSmoothChunkLoading){if(this.messageQueue.length>0){requestAnimationFrame(async()=>{this.isProcessingQueue=!1,this.processMessageQueue("queue-delay")});return}break}}this.isProcessingQueue=!1}handleMessage(e){var r,i;let t=e;if(this.active){if(this.mesherLogReader?.workerMessageReceived(t.type,t),t.type!=="geometry"||!this.debugStopGeometryUpdate){let s=performance.now();this.handleWorkerMessage(t),this.workerCustomHandleTime+=performance.now()-s}if(t.type==="geometry"){this.logWorkerWork(()=>`-> ${t.workerIndex} geometry ${t.key} ${JSON.stringify({dataSize:JSON.stringify(t).length})}`),(r=this.geometryReceiveCount)[i=t.workerIndex]??(r[i]=0),this.geometryReceiveCount[t.workerIndex]++;let s=t.key.split(",").map(Number);this.lastChunkDistance=Math.max(...this.getDistance(new A5(s[0],0,s[2])))}if(t.type==="sectionFinished"){if(this.logWorkerWork(`<- ${t.workerIndex} sectionFinished ${t.key} ${JSON.stringify({processTime:t.processTime})}`),!this.sectionsWaiting.has(t.key))throw new Error(`sectionFinished event for non-outstanding section ${t.key}`);this.sectionsWaiting.set(t.key,this.sectionsWaiting.get(t.key)-1),this.sectionsWaiting.get(t.key)===0&&(this.sectionsWaiting.delete(t.key),this.finishedSections[t.key]=!0);let s=t.key.split(",").map(Number),o=`${s[0]},${s[2]}`;if(this.loadedChunks[o]){let a=!0,v=this.getSectionHeight();for(let l=this.worldMinYRender;l<this.worldSizeParams.worldHeight;l+=v)if(!this.finishedSections[`${s[0]},${l},${s[2]}`]){a=!1;break}if(a){this.finishedChunks[o]=!0;let l=16;this.reactiveState.world.chunksLoaded.add(`${Math.floor(s[0]/l)},${Math.floor(s[2]/l)}`),this.renderUpdateEmitter.emit("chunkFinished",`${s[0]},${s[2]}`),this.checkAllFinished()}}if(this.renderUpdateEmitter.emit("update"),t.processTime&&(this.workersProcessAverageTimeCount++,this.workersProcessAverageTime=(this.workersProcessAverageTime*(this.workersProcessAverageTimeCount-1)+t.processTime)/this.workersProcessAverageTimeCount,this.maxWorkersProcessTime=Math.max(this.maxWorkersProcessTime,t.processTime)),typeof t.pre=="number"&&typeof t.wasm=="number"&&typeof t.post=="number"&&(t.pre>0||t.wasm>0||t.post>0)){let a=++this.workersPhaseSampleCount;this.workersPreAverageTime=(this.workersPreAverageTime*(a-1)+t.pre)/a,this.workersWasmAverageTime=(this.workersWasmAverageTime*(a-1)+t.wasm)/a,this.workersPostAverageTime=(this.workersPostAverageTime*(a-1)+t.post)/a;let v=typeof t.preTargetConvert=="number"?t.preTargetConvert:0,l=typeof t.preNeighborConvert=="number"?t.preNeighborConvert:0,c=typeof t.preNeighborCount=="number"?t.preNeighborCount:0,d=typeof t.preTypedArrayBuild=="number"?t.preTypedArrayBuild:0,f=typeof t.preOther=="number"?t.preOther:0,m=typeof t.preCacheHits=="number"?t.preCacheHits:0,g=typeof t.preCacheMisses=="number"?t.preCacheMisses:0;if(this.workersPreTargetConvertAverageTime=(this.workersPreTargetConvertAverageTime*(a-1)+v)/a,this.workersPreNeighborConvertAverageTime=(this.workersPreNeighborConvertAverageTime*(a-1)+l)/a,this.workersPreNeighborCountAverage=(this.workersPreNeighborCountAverage*(a-1)+c)/a,this.workersPreTypedArrayBuildAverageTime=(this.workersPreTypedArrayBuildAverageTime*(a-1)+d)/a,this.workersPreOtherAverageTime=(this.workersPreOtherAverageTime*(a-1)+f)/a,this.workersPreCacheHitsTotal+=m,this.workersPreCacheMissesTotal+=g,this.worldRendererConfig.debugWasmPerf&&a%Re.PHASE_PERF_LOG_INTERVAL===0){let b=this.workersPreAverageTime+this.workersWasmAverageTime+this.workersPostAverageTime,w=b>0?this.workersPreAverageTime/b*100:0,y=b>0?this.workersWasmAverageTime/b*100:0,A=b>0?this.workersPostAverageTime/b*100:0,C=this.workersPreAverageTime,M=C>0?this.workersPreTargetConvertAverageTime/C*100:0,S=C>0?this.workersPreNeighborConvertAverageTime/C*100:0,H=C>0?this.workersPreTypedArrayBuildAverageTime/C*100:0,B=C>0?this.workersPreOtherAverageTime/C*100:0,I=this.workersPreNeighborCountAverage,G=I>0?this.workersPreNeighborConvertAverageTime/I:0,O=this.workersPreCacheHitsTotal+this.workersPreCacheMissesTotal,j=O>0?this.workersPreCacheHitsTotal/O*100:0}}}if(t.type==="blockStateModelInfo")for(let[s,o]of Object.entries(t.info))this.blockStateModelInfo.set(s,o);t.type==="heightmap"&&this.reactiveState.world.heightmaps.set(t.key,new Int16Array(t.heightmap))}}downloadMesherLog(){let e=document.createElement("a");e.href="data:text/plain;charset=utf-8,"+encodeURIComponent(this.mesherLogger.contents.join(`
|
|
288
288
|
`)),e.download="mesher.log",e.click()}checkAllFinished(){this.sectionsWaiting.size===0&&(this.reactiveState.world.mesherWork=!1),Object.keys(this.finishedChunks).length>=this.chunksLength&&(this.allChunksLoaded?.(),this.allChunksFinished=!0,this.allLoadedIn??(this.allLoadedIn=Date.now()-this.initialChunkLoadWasStartedIn)),this.updateChunksStats()}changeHandSwingingState(e,t){}updateViewerPosition(e){this.viewerChunkPosition=e;for(let[i,s]of Object.entries(this.loadedChunks))s&&this.updatePosDataChunk?.(i);let t=Math.floor(e.x/16),r=Math.floor(e.z/16);(t!==this.lastViewerChunkGridX||r!==this.lastViewerChunkGridZ)&&(this.lastViewerChunkGridX=t,this.lastViewerChunkGridZ=r,this.onViewerChunkPositionChanged())}onViewerChunkPositionChanged(){}sendWorkers(e){for(let t of this.workers)t.postMessage(e)}getDistance(e){let[t,r]=Ct(this.viewerChunkPosition),i=16,s=Math.abs(t-Math.floor(e.x/i)),o=Math.abs(r-Math.floor(e.z/i));return[s,o]}resetWorld(){for(let e of this.workers)e.terminate();this.workers=[]}async resetWorkers(){this.resetWorld(),typeof document<"u"&&document?.readyState==="loading"&&await new Promise(e=>{document.addEventListener("DOMContentLoaded",e)}),this.initWorkers(),this.active=!0,this.sendMesherMcData()}getMesherConfig(){let e=this.timeOfTheDay,t=e<0||e>24e3?15:Qr(e);return{version:this.version,enableLighting:this.worldRendererConfig.enableLighting,skyLight:t,smoothLighting:this.worldRendererConfig.smoothLighting,shadingTheme:this.worldRendererConfig.shadingTheme,cardinalLight:this.worldRendererConfig.cardinalLight,outputFormat:this.outputFormat,debugModelVariant:this.worldRendererConfig.debugModelVariant,clipWorldBelowY:this.worldRendererConfig.clipWorldBelowY,disableBlockEntityTextures:!this.worldRendererConfig.extraBlockRenderers,worldMinY:this.worldMinYRender,worldMaxY:this.worldMinYRender+this.worldSizeParams.worldHeight,disableConversionCache:this.worldRendererConfig.disableMesherConversionCache,computeWireframeEdges:this.worldRendererConfig.futuristicReveal===!0,shaderCubeBlocks:this.isShaderCubeBlocksEnabled()}}sendMesherMcData(){let e=this.resourcesManager.currentResources.mcData;Jr(this.workers,this.version,y5,e),this.logWorkerWork("# mcData sent")}async updateAssetsData(){let e=this.resourcesManager.currentResources;if(this.workers.length===0)throw new Error("workers not initialized yet");for(let[t,r]of this.workers.entries()){let{blockstatesModels:i}=e;r.postMessage({type:"mesherData",workerIndex:t,blocksAtlas:{latest:e.blocksAtlasJson},blockstatesModels:i,config:this.getMesherConfig()})}this.logWorkerWork("# mesherData sent")}getSectionHeight(){return hs}get worldMinYRender(){let e=this.getSectionHeight();return Math.floor(Math.max(this.worldSizeParams.minY,this.worldRendererConfig.clipWorldBelowY??-1/0)/e)*e}updateChunksStats(){let e=Object.keys(this.finishedChunks);this.displayOptions.nonReactiveState.world.chunksLoaded=new Set(e),this.displayOptions.nonReactiveState.world.chunksTotalNumber=this.chunksLength,this.reactiveState.world.allChunksLoaded=this.allChunksFinished;let t=`Q: ${this.messageQueue.length} ${Object.keys(this.loadedChunks).length}/${Object.keys(this.finishedChunks).length}/${this.chunksLength} chunks (${this.workers.length}:${this.workersProcessAverageTime.toFixed(0)}ms/${this.geometryReceiveCountPerSec}ss/${this.allLoadedIn?.toFixed(1)??"-"}s)`;this.chunksFullInfo=t,Yr("downloaded-chunks",t)}addColumn(e,t,r,i){if(!this.active)return;if(this.workers.length===0)throw new Error("workers not initialized yet");this.initialChunksLoad=!1,this.initialChunkLoadWasStartedIn??(this.initialChunkLoadWasStartedIn=Date.now()),this.loadedChunks[`${e},${t}`]=!0,this.updateChunksStats();let s=`${e},${t}`,o=this.protocolCustomBlocks.get(s);for(let l of this.workers)l.postMessage({type:"chunk",x:e,z:t,chunk:r,customBlockModels:o||void 0});this.worldRendererConfig.wasmMesher||this.workers[0].postMessage({type:"getHeightmap",x:e,z:t}),this.logWorkerWork(()=>`-> chunk ${JSON.stringify({x:e,z:t,chunkLength:r.length,customBlockModelsLength:o?Object.keys(o).length:0})}`),this.mesherLogReader?.chunkReceived(e,t,r.length);let a=this.getSectionHeight(),v=16;for(let l=this.worldMinYRender;l<this.worldSizeParams.worldHeight;l+=a){let c=new A5(e,l,t);this.setSectionDirty(c),this.neighborChunkUpdates&&(!i||this.worldRendererConfig.smoothLighting)&&(this.setSectionDirty(c.offset(-v,0,0)),this.setSectionDirty(c.offset(v,0,0)),this.setSectionDirty(c.offset(0,0,-v)),this.setSectionDirty(c.offset(0,0,v)))}}markAsLoaded(e,t){this.loadedChunks[`${e},${t}`]=!0,this.finishedChunks[`${e},${t}`]=!0,this.logWorkerWork(`-> markAsLoaded ${JSON.stringify({x:e,z:t})}`),this.renderUpdateEmitter.emit("chunkFinished",`${e},${t}`),this.checkAllFinished()}removeColumn(e,t){delete this.loadedChunks[`${e},${t}`];let r=`${e},${t}`,i=this.heightmapDebounceTimers.get(r);i&&(clearTimeout(i),this.heightmapDebounceTimers.delete(r));for(let[o,a]of this.sectionDirtyTimers)o.startsWith(`${e},`)&&o.endsWith(`,${t}`)&&(clearTimeout(a),this.sectionDirtyTimers.delete(o),this.sectionDirtyCount.delete(o),this.sectionDirtyPendingArgs.delete(o));for(let o of this.workers)o.postMessage({type:"unloadChunk",x:e,z:t});this.logWorkerWork(`-> unloadChunk ${JSON.stringify({x:e,z:t})}`),delete this.finishedChunks[`${e},${t}`],this.allChunksFinished=Object.keys(this.finishedChunks).length===this.chunksLength,Object.keys(this.finishedChunks).length===0&&(this.allLoadedIn=void 0,this.initialChunkLoadWasStartedIn=void 0);let s=this.getSectionHeight();for(let o=this.worldSizeParams.minY;o<this.worldSizeParams.worldHeight;o+=s)this.setSectionDirty(new A5(e,o,t),!1),delete this.finishedSections[`${e},${o},${t}`];this.highestBlocksByChunks.delete(`${e},${t}`),this.reactiveState.world.heightmaps.delete(`${Math.floor(e/16)},${Math.floor(t/16)}`),this.updateChunksStats(),Object.keys(this.loadedChunks).length===0&&(this.mesherLogger.contents=[],this.logWorkerWork("# all chunks unloaded. New log started"),this.mesherLogReader?.maybeStartReplay())}setBlockStateId(e,t,r=!0){(async()=>{let o=Math.floor(e.x/16)*16,a=Math.floor(e.z/16)*16;this.queuedChunks.has(`${o},${a}`)&&await new Promise(v=>{this.queuedFunctions.push(()=>{v()})}),this.loadedChunks[`${o},${a}`],this.setBlockStateIdInner(e,t,r)})()}updateEntity(e,t=!1){}lightUpdate(e,t){}connect(e){let t=e;t.on("entity",i=>{this.updateEntity(i,!1)}),t.on("entityMoved",i=>{this.updateEntity(i,!0)}),t.on("playerEntity",i=>{this.updatePlayerEntity?.(i)});let r=null;t.on("loadChunk",({x:i,z:s,chunk:o,worldConfig:a,isLightUpdate:v})=>{this.worldSizeParams=a,this.queuedChunks.add(`${i},${s}`);let l=[i,s,o,v];r||(r={data:[],timeout:setTimeout(()=>{for(let c of r.data)this.queuedChunks.delete(`${c[0]},${c[1]}`),this.addColumn(...c);for(let c of this.queuedFunctions)c();this.queuedFunctions=[],r=null},this.worldRendererConfig.addChunksBatchWaitTime)}),r.data.push(l)}),t.on("blockEntities",i=>{this.blockEntities=i}),t.on("unloadChunk",({x:i,z:s})=>{this.removeColumn(i,s)}),t.on("blockUpdate",({pos:i,stateId:s})=>{this.setBlockStateId(new A5(i.x,i.y,i.z),s)}),t.on("chunkPosUpdate",({pos:i})=>{this.updateViewerPosition(i)}),t.on("end",()=>{this.worldStop?.()}),t.on("renderDistance",i=>{this.viewDistance=i,this.chunksLength=i===0?1:l5(i).length,this.allChunksFinished=Object.keys(this.finishedChunks).length===this.chunksLength,this.onRenderDistanceChanged?.(i)}),t.on("markAsLoaded",({x:i,z:s})=>{this.markAsLoaded(i,s)}),t.on("updateLight",({pos:i})=>{this.lightUpdate(i.x,i.z)}),t.on("onWorldSwitch",()=>{for(let i of this.onWorldSwitched)try{i()}catch(s){setTimeout(()=>{throw s},0)}}),t.on("time",i=>{this.worldRendererConfig.dayCycle&&(this.timeUpdated?.(i),this.timeOfTheDay=i)}),t.on("biomeUpdate",({biome:i})=>{this.biomeUpdated?.(i)}),t.on("biomeReset",()=>{this.biomeReset?.()})}setBlockStateIdInner(e,t,r=!0){let s=`${Math.floor(e.x/16)*16},${Math.floor(e.z/16)*16}`,o=`${e.x},${e.y},${e.z}`,a=this.protocolCustomBlocks.get(s)||{};for(let v of this.workers)v.postMessage({type:"blockUpdate",pos:e,stateId:t,customBlockModels:a});if(this.anyModuleRequiresHeightmap()){let v=Math.floor(e.x/16)*16,l=Math.floor(e.z/16)*16,c=`${v},${l}`;if(!this.worldRendererConfig.wasmMesher){let d=this.heightmapDebounceTimers.get(c);d&&clearTimeout(d),this.heightmapDebounceTimers.set(c,setTimeout(()=>{this.heightmapDebounceTimers.delete(c),this.workers[0]?.postMessage({type:"getHeightmap",x:v,z:l})},100))}}if(this.logWorkerWork(`-> blockUpdate ${JSON.stringify({pos:e,stateId:t,customBlockModels:a})}`),this.setSectionDirty(e,!0,!0),this.neighborChunkUpdates){let l=this.getSectionHeight();e.x&15||this.setSectionDirty(e.offset(-16,0,0),!0,!0),(e.x&15)===15&&this.setSectionDirty(e.offset(16,0,0),!0,!0),e.y&l-1||this.setSectionDirty(e.offset(0,-l,0),!0,!0),(e.y&l-1)===l-1&&this.setSectionDirty(e.offset(0,l,0),!0,!0),e.z&15||this.setSectionDirty(e.offset(0,0,-16),!0,!0),(e.z&15)===15&&this.setSectionDirty(e.offset(0,0,16),!0,!0),r&&(!(e.x&15)&&!(e.z&15)&&this.setSectionDirty(e.offset(-16,0,-16),!0,!0),(e.x&15)===15&&!(e.z&15)&&this.setSectionDirty(e.offset(16,0,-16),!0,!0),!(e.x&15)&&(e.z&15)===15&&this.setSectionDirty(e.offset(-16,0,16),!0,!0),(e.x&15)===15&&(e.z&15)===15&&this.setSectionDirty(e.offset(16,0,16),!0,!0),!(e.x&15)&&!(e.y&l-1)&&this.setSectionDirty(e.offset(-16,-l,0),!0,!0),(e.x&15)===15&&!(e.y&l-1)&&this.setSectionDirty(e.offset(16,-l,0),!0,!0),!(e.z&15)&&!(e.y&l-1)&&this.setSectionDirty(e.offset(0,-l,-16),!0,!0),(e.z&15)===15&&!(e.y&l-1)&&this.setSectionDirty(e.offset(0,-l,16),!0,!0),!(e.y&l-1)&&!(e.x&15)&&!(e.z&15)&&this.setSectionDirty(e.offset(-16,-l,-16),!0,!0),!(e.y&l-1)&&(e.x&15)===15&&!(e.z&15)&&this.setSectionDirty(e.offset(16,-l,-16),!0,!0),!(e.y&l-1)&&!(e.x&15)&&(e.z&15)===15&&this.setSectionDirty(e.offset(-16,-l,16),!0,!0),!(e.y&l-1)&&(e.x&15)===15&&(e.z&15)===15&&this.setSectionDirty(e.offset(16,-l,16),!0,!0))}}getWorkerNumber(e,t=!1){let i=this.getSectionHeight();if(this.worldRendererConfig.dedicatedChangeWorker&&this.workers.length>1){if(this.worldRendererConfig.wasmMesher)return E5(Math.floor(e.x/16)+Math.floor(e.z/16),this.workers.length);if(t){let a=`${Math.floor(e.x/16)*16},${Math.floor(e.y/i)*i},${Math.floor(e.z/16)*16}`;if(this.sectionsWaiting.get(a)&&!this.finishedSections[a]){let l=this.workers.length-1;return E5(Math.floor(e.x/16)+Math.floor(e.y/i)+Math.floor(e.z/16),l)}return this.workers.length-1}let o=this.workers.length-1;return E5(Math.floor(e.x/16)+Math.floor(e.y/i)+Math.floor(e.z/16),o)}if(this.worldRendererConfig.wasmMesher)return E5(Math.floor(e.x/16)+Math.floor(e.z/16),this.workers.length);if(t){let o=`${Math.floor(e.x/16)*16},${Math.floor(e.y/i)*i},${Math.floor(e.z/16)*16}`;if(!(this.sectionsWaiting.get(o)&&!this.finishedSections[o]))return 0}return E5(Math.floor(e.x/16)+Math.floor(e.y/i)+Math.floor(e.z/16),this.workers.length)}async debugGetWorkerCustomBlockModel(e){let t=[];for(let r of this.workers)t.push(new Promise(i=>{r.addEventListener("message",s=>{s.data.type==="customBlockModel"&&i(s.data.customBlockModel)})})),r.postMessage({type:"getCustomBlockModel",pos:e});return Promise.all(t)}setSectionDirty(e,t=!0,r=!1){if(!this.forceCallFromMesherReplayer&&this.mesherLogReader)return;if(this.viewDistance===-1)throw new Error("viewDistance not set");let i=this.getDistance(e);if(!this.workers.length||i[0]>this.viewDistance||i[1]>this.viewDistance)return;if(!t){this._dispatchDirtyImmediate(e,t,r);return}let s=16,o=this.getSectionHeight(),a=`${Math.floor(e.x/s)*s},${Math.floor(e.y/o)*o},${Math.floor(e.z/s)*s}`,v=(this.sectionDirtyCount.get(a)??0)+1;this.sectionDirtyCount.set(a,v),v<=Re.GEOMETRY_THROTTLE_THRESHOLD?(this._dispatchDirtyImmediate(e,t,r),this.sectionDirtyTimers.has(a)||this.sectionDirtyTimers.set(a,setTimeout(()=>{let l=this.sectionDirtyPendingArgs.get(a);this.sectionDirtyCount.delete(a),this.sectionDirtyTimers.delete(a),this.sectionDirtyPendingArgs.delete(a),l&&this._dispatchDirtyImmediate(l.pos,l.value,l.useChangeWorker)},Re.GEOMETRY_THROTTLE_DELAY))):(this.sectionDirtyPendingArgs.set(a,{pos:e,value:t,useChangeWorker:r}),this.sectionDirtyTimers.has(a)||this.sectionDirtyTimers.set(a,setTimeout(()=>{let l=this.sectionDirtyPendingArgs.get(a);this.sectionDirtyCount.delete(a),this.sectionDirtyTimers.delete(a),this.sectionDirtyPendingArgs.delete(a),l&&this._dispatchDirtyImmediate(l.pos,l.value,l.useChangeWorker)},Re.GEOMETRY_THROTTLE_DELAY)))}_dispatchDirtyImmediate(e,t,r){var v;this.reactiveState.world.mesherWork=!0;let i=16,s=this.getSectionHeight(),o=`${Math.floor(e.x/i)*i},${Math.floor(e.y/s)*s},${Math.floor(e.z/i)*i}`;this.renderUpdateEmitter.emit("dirty",e,t);let a=this.getWorkerNumber(e,r&&(this.mesherLogger.active||this.worldRendererConfig.dedicatedChangeWorker));this.sectionsWaiting.set(o,(this.sectionsWaiting.get(o)??0)+1),this.forceCallFromMesherReplayer?this.workers[a].postMessage({type:"dirty",x:e.x,y:e.y,z:e.z,value:t,config:this.getMesherConfig()}):((v=this.toWorkerMessagesQueue)[a]??(v[a]=[]),this.toWorkerMessagesQueue[a].push({type:"dirty",x:e.x,y:e.y,z:e.z,value:t,config:this.getMesherConfig()}),this.dispatchMessages())}dispatchMessages(){this.queueAwaited||(this.queueAwaited=!0,setTimeout(()=>{for(let e in this.toWorkerMessagesQueue){let t=this.workers[Number(e)],r=this.toWorkerMessagesQueue[e];t.postMessage(r);for(let i of r)this.logWorkerWork(`-> ${e} dispatchMessages ${i.type} ${JSON.stringify({x:i.x,y:i.y,z:i.z,value:i.value})}`)}this.toWorkerMessagesQueue={},this.queueAwaited=!1}))}async waitForChunksToRender(){return new Promise((e,t)=>{if([...this.sectionsWaiting].length===0){e();return}let r=()=>{this.sectionsWaiting.size===0&&(this.renderUpdateEmitter.removeListener("update",r),e())};this.renderUpdateEmitter.on("update",r)})}async waitForChunkToLoad(e){return new Promise((t,r)=>{let s=`${Math.floor(e.x/16)*16},${Math.floor(e.z/16)*16}`;if(this.loadedChunks[s]){t();return}let o=()=>{this.loadedChunks[s]&&(this.renderUpdateEmitter.removeListener("update",o),t())};this.renderUpdateEmitter.on("update",o)})}destroy(){for(let e of this.heightmapDebounceTimers.values())clearTimeout(e);this.heightmapDebounceTimers.clear();for(let e of this.sectionDirtyTimers.values())clearTimeout(e);this.sectionDirtyTimers.clear(),this.sectionDirtyCount.clear(),this.sectionDirtyPendingArgs.clear();for(let e of this.workers)e.terminate();this.workers=[],this.soundSystem&&(this.soundSystem.destroy(),this.soundSystem=void 0),this.active=!1,this.loadedChunks={},this.finishedChunks={},this.finishedSections={},this.sectionsWaiting.clear(),this.queuedChunks.clear(),this.blockStateModelInfo.clear(),this.renderUpdateEmitter.removeAllListeners(),this.abortController.abort(),As()}};u(Re,"PHASE_PERF_LOG_INTERVAL",64),u(Re,"GEOMETRY_THROTTLE_THRESHOLD",1),u(Re,"GEOMETRY_THROTTLE_DELAY",100);var y1=Re,e7=(n,e="mesher.js")=>{let t;if(F.env.SINGLE_FILE_BUILD){let r=document.getElementById("mesher-worker-code").textContent,i=new Blob([r],{type:"text/javascript"});t=new Worker(window.URL.createObjectURL(i))}else t=new Worker(e);return t.onmessage=({data:r})=>{n(r)},t.on&&t.on("message",r=>{t.onmessage({data:r})}),t},Jr=(n,e,t=y5,r)=>{let i={version:JSON.parse(JSON.stringify(r.version))};for(let[s,o]of Object.entries(t))i[s]=r[o];for(let s of n)s.postMessage({type:"mcData",mcData:i})};E();x();k();R();import{Vec3 as t7}from"vec3";import*as ne from"three";E();x();k();R();function _1(n,e){let t=e/180*Math.PI,r=Math.cos(t),i=Math.sin(t),s={x:0,y:1,z:2}[n],o=(s+1)%3,a=(s+2)%3,v=[[0,0,0],[0,0,0],[0,0,0]];return v[s][s]=1,v[o][o]=r,v[o][a]=-i,v[a][o]=+i,v[a][a]=r,v}function qr(n,e){return e?[n[0]+e[0],n[1]+e[1],n[2]+e[2]]:n}function Zr(n,e){return e?[n[0]-e[0],n[1]-e[1],n[2]-e[2]]:n}function Pt(n,e){return n?[n[0][0]*e[0]+n[0][1]*e[1]+n[0][2]*e[2],n[1][0]*e[0]+n[1][1]*e[1]+n[1][2]*e[2],n[2][0]*e[0]+n[2][1]*e[1]+n[2][2]*e[2]]:e}function Es(n,e){let t=[[0,0,0],[0,0,0],[0,0,0]],r=n[0][0],i=n[1][0],s=n[2][0],o=n[0][1],a=n[1][1],v=n[2][1],l=n[0][2],c=n[1][2],d=n[2][2],f=e[0][0],m=e[1][0],g=e[2][0],b=e[0][1],w=e[1][1],y=e[2][1],A=e[0][2],C=e[1][2],M=e[2][2];return t[0][0]=r*f+i*b+s*A,t[1][0]=r*m+i*w+s*C,t[2][0]=r*g+i*y+s*M,t[0][1]=o*f+a*b+v*A,t[1][1]=o*m+a*w+v*C,t[2][1]=o*g+a*y+v*M,t[0][2]=l*f+c*b+d*A,t[1][2]=l*m+c*w+d*C,t[2][2]=l*g+c*y+d*M,t}var Xr={up:{dir:[0,1,0],mask1:[1,1,0],mask2:[0,1,1],corners:[[0,1,1,0,1],[1,1,1,1,1],[0,1,0,0,0],[1,1,0,1,0]]},down:{dir:[0,-1,0],mask1:[1,1,0],mask2:[0,1,1],corners:[[1,0,1,0,1],[0,0,1,1,1],[1,0,0,0,0],[0,0,0,1,0]]},east:{dir:[1,0,0],mask1:[1,1,0],mask2:[1,0,1],corners:[[1,1,1,0,0],[1,0,1,0,1],[1,1,0,1,0],[1,0,0,1,1]]},west:{dir:[-1,0,0],mask1:[1,1,0],mask2:[1,0,1],corners:[[0,1,0,0,0],[0,0,0,0,1],[0,1,1,1,0],[0,0,1,1,1]]},north:{dir:[0,0,-1],mask1:[1,0,1],mask2:[0,1,1],corners:[[1,0,0,1,1],[0,0,0,0,1],[1,1,0,1,0],[0,1,0,0,0]]},south:{dir:[0,0,1],mask1:[1,0,1],mask2:[0,1,1],corners:[[0,0,1,0,1],[1,0,1,1,1],[0,1,1,0,0],[1,1,1,1,0]]}};function r7(n,e,t,r,i,s,o,a){let v=new t7(0,0,0);for(let l in n.faces){let c=n.faces[l],{corners:d,mask1:f,mask2:m}=Xr[l],g=Pt(r,Xr[l].dir);if(c.cullface&&a[l])continue;let b=n.from[0],w=n.from[1],y=n.from[2],A=n.to[0],C=n.to[1],M=n.to[2],S=c.texture,{u:H}=S,{v:B}=S,{su:I}=S,{sv:G}=S,O=Math.floor(t.positions.length/3),j=[1,1,1];c.tintindex!==void 0&&c.tintindex===0&&(j=[.5686274509803921,.7411764705882353,.34901960784313724]);let J=c.rotation||0,X=Math.cos(J*Math.PI/180),t0=-Math.sin(J*Math.PI/180),d0=null,l0=null;n.rotation&&(d0=_1(n.rotation.axis,n.rotation.angle),l0=Zr(n.rotation.origin,Pt(d0,n.rotation.origin)));let m0=[],p0=1;for(let A0 of d){let n0=[A0[0]?A:b,A0[1]?C:w,A0[2]?M:y];n0=qr(Pt(d0,n0),l0),n0=qr(Pt(r,n0),i),n0=n0.map(U0=>U0/16),t.positions.push(n0[0],n0[1],n0[2]),t.normals.push(...g);let Y=(A0[3]-.5)*X-(A0[4]-.5)*t0+.5,o0=(A0[3]-.5)*t0+(A0[4]-.5)*X+.5;t.uvs.push(Y*I+H,o0*G+B);let g0=1;e&&(g0=4/4*(15/15),m0.push(3)),t.colors.push(p0*j[0]*g0,p0*j[1]*g0,p0*j[2]*g0)}e&&m0[0]+m0[3]>=m0[1]+m0[2]?t.indices.push(O,O+3,O+2,O,O+1,O+3):t.indices.push(O,O+1,O+2,O+2,O+1,O+3)}}var i7=(n,e,t,r,i=[],s={})=>{let l={sx:.5,sy:.5,sz:.5,positions:[],normals:[],colors:[],uvs:[],t_positions:[],t_normals:[],t_colors:[],t_uvs:[],indices:[],tiles:{}};for(let[d,f]of n.entries()){let m=f[i[d]]??f[0];if(!m)continue;let g=null,b=null;for(let y of["x","y","z"])y in m&&(g?g=Es(g,_1(y,-(m[y]??0))):g=_1(y,-(m[y]??0)));g&&(b=[8,8,8],b=Zr(b,Pt(g,b)));let w=m.ao??!0;for(let y of m.elements??[])r7(y,w,l,g,b,e,t,s)}let c=l.positions.length/3;for(let d=0;d<l.t_positions.length/12;d++)l.indices.push(c,c+1,c+2,c+2,c+1,c+3,c,c+2,c+1,c+2,c+3,c+1),c+=4;return l.positions.push(...l.t_positions),l.normals.push(...l.t_normals),l.colors.push(...l.t_colors),l.uvs.push(...l.t_uvs),delete l.t_positions,delete l.t_normals,delete l.t_colors,delete l.t_uvs,l.positions=new Float32Array(l.positions),l.normals=new Float32Array(l.normals),l.colors=new Float32Array(l.colors),l.uvs=new Float32Array(l.uvs),l},n7=(...n)=>{let t={geometry:i7(...n)},r=new ne.BufferGeometry;return r.setAttribute("position",new ne.BufferAttribute(t.geometry.positions,3)),r.setAttribute("normal",new ne.BufferAttribute(t.geometry.normals,3)),r.setAttribute("color",new ne.BufferAttribute(t.geometry.colors,3)),r.setAttribute("uv",new ne.BufferAttribute(t.geometry.uvs,2)),r.setIndex(t.geometry.indices),r.name="block-geometry",r},$r=(n,...e)=>{let t=n7(...e),r=new ne.Mesh(t,n);r.position.set(-.5,-.5,-.5);let i=new ne.Group;return i.add(r),i.rotation.set(0,-ne.MathUtils.degToRad(90),0,"ZYX"),globalThis.mesh=i,i},xs=(n,e)=>{n.position.set(e.x+.5,e.y+.5,e.z+.5)};E();x();k();R();import*as N0 from"three";E();x();k();R();import Pi from"prismarine-nbt";import*as W from"three";E();x();k();R();E();x();k();R();import{BoxGeometry as j0,DoubleSide as si,FrontSide as ks,Group as le,Mesh as G0,MeshStandardMaterial as x5,Vector2 as w1}from"three";function oi(n,e,t,r,i,s,o,a){let v=(B,I,G,O)=>[new w1(B/o,1-O/a),new w1(G/o,1-O/a),new w1(G/o,1-I/a),new w1(B/o,1-I/a)],l=v(e+s,t,e+r+s,t+s),c=v(e+r+s,t,e+r*2+s,t+s),d=v(e,t+s,e+s,t+s+i),f=v(e+s,t+s,e+r+s,t+s+i),m=v(e+r+s,t+s,e+r+s*2,t+i+s),g=v(e+r+s*2,t+s,e+r*2+s*2,t+i+s),b=n.attributes.uv,w=[m[3],m[2],m[0],m[1]],y=[d[3],d[2],d[0],d[1]],A=[l[3],l[2],l[0],l[1]],C=[c[0],c[1],c[3],c[2]],M=[f[3],f[2],f[0],f[1]],S=[g[3],g[2],g[0],g[1]],H=[];for(let B of[w,y,A,C,M,S])for(let I of B)H.push(I.x,I.y);b.set(new Float32Array(H)),b.needsUpdate=!0}function ve(n,e,t,r,i,s){oi(n,e,t,r,i,s,64,64)}function ei(n,e,t,r,i,s){oi(n,e,t,r,i,s,64,32)}var ke=class extends le{constructor(e,t){super(),Object.defineProperty(this,"innerLayer",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"outerLayer",{enumerable:!0,configurable:!0,writable:!0,value:t}),e.name="inner",t.name="outer"}},ti=class extends le{constructor(){super(),Object.defineProperty(this,"head",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"rightArm",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"leftArm",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"rightLeg",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"leftLeg",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"modelListeners",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"slim",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_map",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"layer1Material",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"layer1MaterialBiased",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"layer2Material",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"layer2MaterialBiased",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.layer1Material=new x5({side:ks}),this.layer2Material=new x5({side:si,transparent:!0,alphaTest:1e-5}),this.layer1MaterialBiased=this.layer1Material.clone(),this.layer1MaterialBiased.polygonOffset=!0,this.layer1MaterialBiased.polygonOffsetFactor=1,this.layer1MaterialBiased.polygonOffsetUnits=1,this.layer2MaterialBiased=this.layer2Material.clone(),this.layer2MaterialBiased.polygonOffset=!0,this.layer2MaterialBiased.polygonOffsetFactor=1,this.layer2MaterialBiased.polygonOffsetUnits=1;let e=new j0(8,8,8);ve(e,0,0,8,8,8);let t=new G0(e,this.layer1Material),r=new j0(9,9,9);ve(r,32,0,8,8,8);let i=new G0(r,this.layer2Material);this.head=new ke(t,i),this.head.name="head",this.head.add(t,i),t.position.y=4,i.position.y=4,this.add(this.head);let s=new j0(8,12,4);ve(s,16,16,8,12,4);let o=new G0(s,this.layer1Material),a=new j0(8.5,12.5,4.5);ve(a,16,32,8,12,4);let v=new G0(a,this.layer2Material);this.body=new ke(o,v),this.body.name="body",this.body.add(o,v),this.body.position.y=-6,this.add(this.body);let l=new j0,c=new G0(l,this.layer1MaterialBiased);this.modelListeners.push(()=>{c.scale.x=this.slim?3:4,c.scale.y=12,c.scale.z=4,ve(l,40,16,this.slim?3:4,12,4)});let d=new j0,f=new G0(d,this.layer2MaterialBiased);this.modelListeners.push(()=>{f.scale.x=this.slim?3.5:4.5,f.scale.y=12.5,f.scale.z=4.5,ve(d,40,32,this.slim?3:4,12,4)});let m=new le;m.add(c,f),this.modelListeners.push(()=>{m.position.x=this.slim?-.5:-1}),m.position.y=-4,this.rightArm=new ke(c,f),this.rightArm.name="rightArm",this.rightArm.add(m),this.rightArm.position.x=-5,this.rightArm.position.y=-2,this.add(this.rightArm);let g=new j0,b=new G0(g,this.layer1MaterialBiased);this.modelListeners.push(()=>{b.scale.x=this.slim?3:4,b.scale.y=12,b.scale.z=4,ve(g,32,48,this.slim?3:4,12,4)});let w=new j0,y=new G0(w,this.layer2MaterialBiased);this.modelListeners.push(()=>{y.scale.x=this.slim?3.5:4.5,y.scale.y=12.5,y.scale.z=4.5,ve(w,48,48,this.slim?3:4,12,4)});let A=new le;A.add(b,y),this.modelListeners.push(()=>{A.position.x=this.slim?.5:1}),A.position.y=-4,this.leftArm=new ke(b,y),this.leftArm.name="leftArm",this.leftArm.add(A),this.leftArm.position.x=5,this.leftArm.position.y=-2,this.add(this.leftArm);let C=new j0(4,12,4);ve(C,0,16,4,12,4);let M=new G0(C,this.layer1MaterialBiased),S=new j0(4.5,12.5,4.5);ve(S,0,32,4,12,4);let H=new G0(S,this.layer2MaterialBiased),B=new le;B.add(M,H),B.position.y=-6,this.rightLeg=new ke(M,H),this.rightLeg.name="rightLeg",this.rightLeg.add(B),this.rightLeg.position.x=-1.9,this.rightLeg.position.y=-12,this.rightLeg.position.z=-.1,this.add(this.rightLeg);let I=new j0(4,12,4);ve(I,16,48,4,12,4);let G=new G0(I,this.layer1MaterialBiased),O=new j0(4.5,12.5,4.5);ve(O,0,48,4,12,4);let j=new G0(O,this.layer2MaterialBiased),J=new le;J.add(G,j),J.position.y=-6,this.leftLeg=new ke(G,j),this.leftLeg.name="leftLeg",this.leftLeg.add(J),this.leftLeg.position.x=1.9,this.leftLeg.position.y=-12,this.leftLeg.position.z=-.1,this.add(this.leftLeg),this.modelType="default"}get map(){return this._map}set map(e){this._map=e,this.layer1Material.map=e,this.layer1Material.needsUpdate=!0,this.layer1MaterialBiased.map=e,this.layer1MaterialBiased.needsUpdate=!0,this.layer2Material.map=e,this.layer2Material.needsUpdate=!0,this.layer2MaterialBiased.map=e,this.layer2MaterialBiased.needsUpdate=!0}get modelType(){return this.slim?"slim":"default"}set modelType(e){this.slim=e==="slim",this.modelListeners.forEach(t=>t())}getBodyParts(){return this.children.filter(e=>e instanceof ke)}setInnerLayerVisible(e){this.getBodyParts().forEach(t=>t.innerLayer.visible=e)}setOuterLayerVisible(e){this.getBodyParts().forEach(t=>t.outerLayer.visible=e)}resetJoints(){this.head.rotation.set(0,0,0),this.leftArm.rotation.set(0,0,0),this.rightArm.rotation.set(0,0,0),this.leftLeg.rotation.set(0,0,0),this.rightLeg.rotation.set(0,0,0),this.body.rotation.set(0,0,0),this.head.position.y=0,this.body.position.y=-6,this.body.position.z=0,this.rightArm.position.x=-5,this.rightArm.position.y=-2,this.rightArm.position.z=0,this.leftArm.position.x=5,this.leftArm.position.y=-2,this.leftArm.position.z=0,this.rightLeg.position.x=-1.9,this.rightLeg.position.y=-12,this.rightLeg.position.z=-.1,this.leftLeg.position.x=1.9,this.leftLeg.position.y=-12,this.leftLeg.position.z=-.1}},ri=class extends le{constructor(){super(),Object.defineProperty(this,"cape",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"material",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.material=new x5({side:si,transparent:!0,alphaTest:1e-5});let e=new j0(10,16,1);ei(e,0,0,10,16,1),this.cape=new G0(e,this.material),this.cape.position.y=-8,this.cape.position.z=.5,this.add(this.cape)}get map(){return this.material.map}set map(e){this.material.map=e,this.material.needsUpdate=!0}},ii=class extends le{constructor(){super(),Object.defineProperty(this,"leftWing",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"rightWing",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"material",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.material=new x5({side:si,transparent:!0,alphaTest:1e-5});let e=new j0(12,22,4);ei(e,22,0,10,20,2);let t=new G0(e,this.material);t.position.x=-5,t.position.y=-10,t.position.z=-1,this.leftWing=new le,this.leftWing.add(t),this.add(this.leftWing);let r=new j0(12,22,4);ei(r,22,0,10,20,2);let i=new G0(r,this.material);i.scale.x=-1,i.position.x=5,i.position.y=-10,i.position.z=-1,this.rightWing=new le,this.rightWing.add(i),this.add(this.rightWing),this.leftWing.position.x=5,this.leftWing.rotation.x=.2617994,this.resetJoints()}resetJoints(){this.leftWing.rotation.y=.01,this.leftWing.rotation.z=.2617994,this.updateRightWing()}updateRightWing(){this.rightWing.position.x=-this.leftWing.position.x,this.rightWing.position.y=this.leftWing.position.y,this.rightWing.rotation.x=this.leftWing.rotation.x,this.rightWing.rotation.y=-this.leftWing.rotation.y,this.rightWing.rotation.z=-this.leftWing.rotation.z}get map(){return this.material.map}set map(e){this.material.map=e,this.material.needsUpdate=!0}},ni=class extends le{constructor(){super(),Object.defineProperty(this,"rightEar",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"leftEar",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"material",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.material=new x5({side:ks});let e=new j0(8,8,4/3);oi(e,0,0,6,6,1,14,7),this.rightEar=new G0(e,this.material),this.rightEar.name="rightEar",this.rightEar.position.x=-6,this.add(this.rightEar),this.leftEar=new G0(e,this.material),this.leftEar.name="leftEar",this.leftEar.position.x=6,this.add(this.leftEar)}get map(){return this.material.map}set map(e){this.material.map=e,this.material.needsUpdate=!0}},Rs=10.8*Math.PI/180,R5=class extends le{constructor(){super(),Object.defineProperty(this,"skin",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cape",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"elytra",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ears",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.skin=new ti,this.skin.name="skin",this.skin.position.y=8,this.add(this.skin),this.cape=new ri,this.cape.name="cape",this.cape.position.y=8,this.cape.position.z=-2,this.cape.rotation.x=Rs,this.cape.rotation.y=Math.PI,this.add(this.cape),this.elytra=new ii,this.elytra.name="elytra",this.elytra.position.y=8,this.elytra.position.z=-2,this.elytra.visible=!1,this.add(this.elytra),this.ears=new ni,this.ears.name="ears",this.ears.position.y=10,this.ears.position.z=2/3,this.ears.visible=!1,this.skin.head.add(this.ears)}get backEquipment(){return this.cape.visible?"cape":this.elytra.visible?"elytra":null}set backEquipment(e){this.cape.visible=e==="cape",this.elytra.visible=e==="elytra"}resetJoints(){this.skin.resetJoints(),this.cape.rotation.x=Rs,this.cape.position.y=8,this.cape.position.z=-2,this.elytra.position.y=8,this.elytra.position.z=-2,this.elytra.rotation.x=0,this.elytra.resetJoints()}};E();x();k();R();import{Color as Vp,PointLight as jp,EquirectangularReflectionMapping as Yp,Group as Qp,NearestFilter as Kp,PerspectiveCamera as Jp,Scene as qp,Texture as Zp,Vector2 as Xp,WebGLRenderer as $p,AmbientLight as eg,CanvasTexture as tg,WebGLRenderTarget as rg,FloatType as ig,DepthTexture as ng,Clock as sg,Object3D as og,ColorManagement as ag}from"three";import{OrbitControls as lg}from"three/examples/jsm/controls/OrbitControls.js";import{EffectComposer as dg}from"three/examples/jsm/postprocessing/EffectComposer.js";import"three/examples/jsm/postprocessing/Pass.js";import{RenderPass as mg}from"three/examples/jsm/postprocessing/RenderPass.js";import{ShaderPass as gg}from"three/examples/jsm/postprocessing/ShaderPass.js";import{FXAAShader as yg}from"three/examples/jsm/shaders/FXAAShader.js";E();x();k();R();var A1=class{constructor(){Object.defineProperty(this,"speed",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"paused",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"progress",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"currentId",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"progress0",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"animationObjects",{enumerable:!0,configurable:!0,writable:!0,value:new Map})}update(e,t){if(this.paused)return;let r=t*this.speed;this.animate(e,r),this.animationObjects.forEach((i,s)=>{let o=this.progress0.get(s);i(e,this.progress-o,s)}),this.progress+=r}addAnimation(e){let t=this.currentId++;return this.progress0.set(t,this.progress),this.animationObjects.set(t,e),t}removeAnimation(e){e!=null&&(this.animationObjects.delete(e),this.progress0.delete(e))}};E();x();k();R();import{CanvasTexture as Sp,NearestFilter as Cp,Sprite as Bp,SpriteMaterial as Pp}from"three";E();x();k();R();var s7=Object.defineProperty,o7=(n,e,t)=>e in n?s7(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,y0=(n,e,t)=>(o7(n,typeof e!="symbol"?e+"":e,t),t);function ai(n){let e=[n];if(n.extra&&n.extra.length!==0)for(let t of n.extra)e.push(...ai(t));return e}var Z=class{constructor(n,e,t,r,i,s){this.key=n,this.value=e,this.name=t,this.code=r,this.cssForeground=i,this.cssBackground=s}applyToStyle(n){n[this.key]=this.value}matchStyle(n){return n[this.key]===this.value}static fromCode(n){let t="0123456789abcdefklmnor".indexOf(n);if(t)return this.list[t]}toString(){return`${Z.CONTROL_STRING}${this.code}`}},_0=Z;y0(_0,"CONTROL_STRING","\xA7");y0(_0,"BLACK",new Z("color","black","BLACK","0",{color:"#000000"},{color:"#000000"}));y0(_0,"DARK_BLUE",new Z("color","dark_blue","DARK_BLUE","1",{color:"#0000AA"},{color:"#00002A"}));y0(_0,"DARK_GREEN",new Z("color","dark_green","DARK_GREEN","2",{color:"#00AA00"},{color:"#002A00"}));y0(_0,"DARK_AQUA",new Z("color","dark_aqua","DARK_AQUA","3",{color:"#00AAAA"},{color:"#002A2A"}));y0(_0,"DARK_RED",new Z("color","dark_red","DARK_RED","4",{color:"#AA0000"},{color:"#2A0000"}));y0(_0,"DARK_PURPLE",new Z("color","dark_purple","DARK_PURPLE","5",{color:"#AA00AA"},{color:"#2A002A"}));y0(_0,"GOLD",new Z("color","gold","GOLD","6",{color:"#FFAA00"},{color:"#2A2A00"}));y0(_0,"GRAY",new Z("color","gray","GRAY","7",{color:"#AAAAAA"},{color:"#2A2A2A"}));y0(_0,"DARK_GRAY",new Z("color","dark_gray","DARK_GRAY","8",{color:"#555555"},{color:"#151515"}));y0(_0,"BLUE",new Z("color","blue","BLUE","9",{color:"#5555FF"},{color:"#15153F"}));y0(_0,"GREEN",new Z("color","green","GREEN","a",{color:"#55FF55"},{color:"#153F15"}));y0(_0,"AQUA",new Z("color","aqua","AQUA","b",{color:"#55FFFF"},{color:"#153F3F"}));y0(_0,"RED",new Z("color","red","RED","c",{color:"#FF5555"},{color:"#3F1515"}));y0(_0,"LIGHT_PURPLE",new Z("color","light_purple","LIGHT_PURPLE","d",{color:"#FF55FF"},{color:"#3F153F"}));y0(_0,"YELLOW",new Z("color","yellow","YELLOW","e",{color:"#FFFF55"},{color:"#3F3F15"}));y0(_0,"WHITE",new Z("color","white","WHITE","f",{color:"#FFFFFF"},{color:"#3F3F3F"}));y0(_0,"OBFUSCATED",new Z("obfuscated",!0,"OBFUSCATED","k",{}));y0(_0,"BOLD",new Z("bold",!0,"BOLD","l",{"font-weight":"bold"}));y0(_0,"STRIKETHROUGH",new Z("strikethrough",!0,"STRIKETHROUGH","m",{"text-decoration":"line-through"}));y0(_0,"UNDERLINE",new Z("underlined",!0,"UNDERLINE","n",{"text-decoration":"underline"}));y0(_0,"ITALIC",new Z("italic",!0,"ITALIC","o",{"font-style":"italic"}));y0(_0,"RESET",{name:"RESET",code:"r",applyToStyle(n){n.bold=!1,n.strikethrough=!1,n.underlined=!1,n.italic=!1,n.obfuscated=!1,n.color=void 0},matchStyle(n){return!1},cssBackground:{},cssForeground:{},toString(){return`${Z.CONTROL_STRING}r`}});y0(_0,"list",[Z.BLACK,Z.DARK_BLUE,Z.DARK_GREEN,Z.DARK_AQUA,Z.DARK_RED,Z.DARK_PURPLE,Z.GOLD,Z.GRAY,Z.DARK_GRAY,Z.BLUE,Z.GREEN,Z.AQUA,Z.RED,Z.LIGHT_PURPLE,Z.YELLOW,Z.WHITE,Z.OBFUSCATED,Z.BOLD,Z.STRIKETHROUGH,Z.UNDERLINE,Z.ITALIC,Z.RESET]);var F5=s5(vi(),1);ui();var g3=s5(Zs(),1);import b3 from"prismarine-chat";E();x();k();R();import*as C0 from"three";E();x();k();R();E();x();k();R();var Fe=class n{constructor(e,t,r,i,s="div"){this.parent=e,this.object=t,this.property=r,this._disabled=!1,this._hidden=!1,this.initialValue=this.getValue(),this.domElement=document.createElement("div"),this.domElement.classList.add("controller"),this.domElement.classList.add(i),this.$name=document.createElement("div"),this.$name.classList.add("name"),n.nextNameID=n.nextNameID||0,this.$name.id=`lil-gui-name-${++n.nextNameID}`,this.$widget=document.createElement(s),this.$widget.classList.add("widget"),this.$disable=this.$widget,this.domElement.appendChild(this.$name),this.domElement.appendChild(this.$widget),this.domElement.addEventListener("keydown",o=>o.stopPropagation()),this.domElement.addEventListener("keyup",o=>o.stopPropagation()),this.parent.children.push(this),this.parent.controllers.push(this),this.parent.$children.appendChild(this.domElement),this._listenCallback=this._listenCallback.bind(this),this.name(r)}name(e){return this._name=e,this.$name.innerHTML=e,this}onChange(e){return this._onChange=e,this}_callOnChange(){this.parent._callOnChange(this),this._onChange!==void 0&&this._onChange.call(this,this.getValue()),this._changed=!0}onFinishChange(e){return this._onFinishChange=e,this}_callOnFinishChange(){this._changed&&(this.parent._callOnFinishChange(this),this._onFinishChange!==void 0&&this._onFinishChange.call(this,this.getValue())),this._changed=!1}reset(){return this.setValue(this.initialValue),this._callOnFinishChange(),this}enable(e=!0){return this.disable(!e)}disable(e=!0){return e===this._disabled?this:(this._disabled=e,this.domElement.classList.toggle("disabled",e),this.$disable.toggleAttribute("disabled",e),this)}show(e=!0){return this._hidden=!e,this.domElement.style.display=this._hidden?"none":"",this}hide(){return this.show(!1)}options(e){let t=this.parent.add(this.object,this.property,e);return t.name(this._name),this.destroy(),t}min(e){return this}max(e){return this}step(e){return this}decimals(e){return this}listen(e=!0){return this._listening=e,this._listenCallbackID!==void 0&&(cancelAnimationFrame(this._listenCallbackID),this._listenCallbackID=void 0),this._listening&&this._listenCallback(),this}_listenCallback(){this._listenCallbackID=requestAnimationFrame(this._listenCallback);let e=this.save();e!==this._listenPrevValue&&this.updateDisplay(),this._listenPrevValue=e}getValue(){return this.object[this.property]}setValue(e){return this.object[this.property]=e,this._callOnChange(),this.updateDisplay(),this}updateDisplay(){return this}load(e){return this.setValue(e),this._callOnFinishChange(),this}save(){return this.getValue()}destroy(){this.listen(!1),this.parent.children.splice(this.parent.children.indexOf(this),1),this.parent.controllers.splice(this.parent.controllers.indexOf(this),1),this.parent.$children.removeChild(this.domElement)}},fi=class extends Fe{constructor(e,t,r){super(e,t,r,"boolean","label"),this.$input=document.createElement("input"),this.$input.setAttribute("type","checkbox"),this.$input.setAttribute("aria-labelledby",this.$name.id),this.$widget.appendChild(this.$input),this.$input.addEventListener("change",()=>{this.setValue(this.$input.checked),this._callOnFinishChange()}),this.$disable=this.$input,this.updateDisplay()}updateDisplay(){return this.$input.checked=this.getValue(),this}};function hi(n){let e,t;return(e=n.match(/(#|0x)?([a-f0-9]{6})/i))?t=e[2]:(e=n.match(/rgb\(\s*(\d*)\s*,\s*(\d*)\s*,\s*(\d*)\s*\)/))?t=parseInt(e[1]).toString(16).padStart(2,0)+parseInt(e[2]).toString(16).padStart(2,0)+parseInt(e[3]).toString(16).padStart(2,0):(e=n.match(/^#?([a-f0-9])([a-f0-9])([a-f0-9])$/i))&&(t=e[1]+e[1]+e[2]+e[2]+e[3]+e[3]),t?"#"+t:!1}var j7={isPrimitive:!0,match:n=>typeof n=="string",fromHexString:hi,toHexString:hi},B5={isPrimitive:!0,match:n=>typeof n=="number",fromHexString:n=>parseInt(n.substring(1),16),toHexString:n=>"#"+n.toString(16).padStart(6,0)},Y7={isPrimitive:!1,match:n=>Array.isArray(n),fromHexString(n,e,t=1){let r=B5.fromHexString(n);e[0]=(r>>16&255)/255*t,e[1]=(r>>8&255)/255*t,e[2]=(r&255)/255*t},toHexString([n,e,t],r=1){r=255/r;let i=n*r<<16^e*r<<8^t*r<<0;return B5.toHexString(i)}},Q7={isPrimitive:!1,match:n=>Object(n)===n,fromHexString(n,e,t=1){let r=B5.fromHexString(n);e.r=(r>>16&255)/255*t,e.g=(r>>8&255)/255*t,e.b=(r&255)/255*t},toHexString({r:n,g:e,b:t},r=1){r=255/r;let i=n*r<<16^e*r<<8^t*r<<0;return B5.toHexString(i)}},K7=[j7,B5,Y7,Q7];function J7(n){return K7.find(e=>e.match(n))}var mi=class extends Fe{constructor(e,t,r,i){super(e,t,r,"color"),this.$input=document.createElement("input"),this.$input.setAttribute("type","color"),this.$input.setAttribute("tabindex",-1),this.$input.setAttribute("aria-labelledby",this.$name.id),this.$text=document.createElement("input"),this.$text.setAttribute("type","text"),this.$text.setAttribute("spellcheck","false"),this.$text.setAttribute("aria-labelledby",this.$name.id),this.$display=document.createElement("div"),this.$display.classList.add("display"),this.$display.appendChild(this.$input),this.$widget.appendChild(this.$display),this.$widget.appendChild(this.$text),this._format=J7(this.initialValue),this._rgbScale=i,this._initialValueHexString=this.save(),this._textFocused=!1,this.$input.addEventListener("input",()=>{this._setValueFromHexString(this.$input.value)}),this.$input.addEventListener("blur",()=>{this._callOnFinishChange()}),this.$text.addEventListener("input",()=>{let s=hi(this.$text.value);s&&this._setValueFromHexString(s)}),this.$text.addEventListener("focus",()=>{this._textFocused=!0,this.$text.select()}),this.$text.addEventListener("blur",()=>{this._textFocused=!1,this.updateDisplay(),this._callOnFinishChange()}),this.$disable=this.$text,this.updateDisplay()}reset(){return this._setValueFromHexString(this._initialValueHexString),this}_setValueFromHexString(e){if(this._format.isPrimitive){let t=this._format.fromHexString(e);this.setValue(t)}else this._format.fromHexString(e,this.getValue(),this._rgbScale),this._callOnChange(),this.updateDisplay()}save(){return this._format.toHexString(this.getValue(),this._rgbScale)}load(e){return this._setValueFromHexString(e),this._callOnFinishChange(),this}updateDisplay(){return this.$input.value=this._format.toHexString(this.getValue(),this._rgbScale),this._textFocused||(this.$text.value=this.$input.value.substring(1)),this.$display.style.backgroundColor=this.$input.value,this}},C5=class extends Fe{constructor(e,t,r){super(e,t,r,"function"),this.$button=document.createElement("button"),this.$button.appendChild(this.$name),this.$widget.appendChild(this.$button),this.$button.addEventListener("click",i=>{i.preventDefault(),this.getValue().call(this.object),this._callOnChange()}),this.$button.addEventListener("touchstart",()=>{},{passive:!0}),this.$disable=this.$button}},pi=class extends Fe{constructor(e,t,r,i,s,o){super(e,t,r,"number"),this._initInput(),this.min(i),this.max(s);let a=o!==void 0;this.step(a?o:this._getImplicitStep(),a),this.updateDisplay()}decimals(e){return this._decimals=e,this.updateDisplay(),this}min(e){return this._min=e,this._onUpdateMinMax(),this}max(e){return this._max=e,this._onUpdateMinMax(),this}step(e,t=!0){return this._step=e,this._stepExplicit=t,this}updateDisplay(){let e=this.getValue();if(this._hasSlider){let t=(e-this._min)/(this._max-this._min);t=Math.max(0,Math.min(t,1)),this.$fill.style.width=t*100+"%"}return this._inputFocused||(this.$input.value=this._decimals===void 0?e:e.toFixed(this._decimals)),this}_initInput(){this.$input=document.createElement("input"),this.$input.setAttribute("type","text"),this.$input.setAttribute("aria-labelledby",this.$name.id),window.matchMedia("(pointer: coarse)").matches&&(this.$input.setAttribute("type","number"),this.$input.setAttribute("step","any")),this.$widget.appendChild(this.$input),this.$disable=this.$input;let t=()=>{let A=parseFloat(this.$input.value);isNaN(A)||(this._stepExplicit&&(A=this._snap(A)),this.setValue(this._clamp(A)))},r=A=>{let C=parseFloat(this.$input.value);isNaN(C)||(this._snapClampSetValue(C+A),this.$input.value=this.getValue())},i=A=>{A.key==="Enter"&&this.$input.blur(),A.code==="ArrowUp"&&(A.preventDefault(),r(this._step*this._arrowKeyMultiplier(A))),A.code==="ArrowDown"&&(A.preventDefault(),r(this._step*this._arrowKeyMultiplier(A)*-1))},s=A=>{this._inputFocused&&(A.preventDefault(),r(this._step*this._normalizeMouseWheel(A)))},o=!1,a,v,l,c,d,f=5,m=A=>{a=A.clientX,v=l=A.clientY,o=!0,c=this.getValue(),d=0,window.addEventListener("mousemove",g),window.addEventListener("mouseup",b)},g=A=>{if(o){let C=A.clientX-a,M=A.clientY-v;Math.abs(M)>f?(A.preventDefault(),this.$input.blur(),o=!1,this._setDraggingStyle(!0,"vertical")):Math.abs(C)>f&&b()}if(!o){let C=A.clientY-l;d-=C*this._step*this._arrowKeyMultiplier(A),c+d>this._max?d=this._max-c:c+d<this._min&&(d=this._min-c),this._snapClampSetValue(c+d)}l=A.clientY},b=()=>{this._setDraggingStyle(!1,"vertical"),this._callOnFinishChange(),window.removeEventListener("mousemove",g),window.removeEventListener("mouseup",b)},w=()=>{this._inputFocused=!0},y=()=>{this._inputFocused=!1,this.updateDisplay(),this._callOnFinishChange()};this.$input.addEventListener("input",t),this.$input.addEventListener("keydown",i),this.$input.addEventListener("wheel",s,{passive:!1}),this.$input.addEventListener("mousedown",m),this.$input.addEventListener("focus",w),this.$input.addEventListener("blur",y)}_initSlider(){this._hasSlider=!0,this.$slider=document.createElement("div"),this.$slider.classList.add("slider"),this.$fill=document.createElement("div"),this.$fill.classList.add("fill"),this.$slider.appendChild(this.$fill),this.$widget.insertBefore(this.$slider,this.$input),this.domElement.classList.add("hasSlider");let e=(y,A,C,M,S)=>(y-A)/(C-A)*(S-M)+M,t=y=>{let A=this.$slider.getBoundingClientRect(),C=e(y,A.left,A.right,this._min,this._max);this._snapClampSetValue(C)},r=y=>{this._setDraggingStyle(!0),t(y.clientX),window.addEventListener("mousemove",i),window.addEventListener("mouseup",s)},i=y=>{t(y.clientX)},s=()=>{this._callOnFinishChange(),this._setDraggingStyle(!1),window.removeEventListener("mousemove",i),window.removeEventListener("mouseup",s)},o=!1,a,v,l=y=>{y.preventDefault(),this._setDraggingStyle(!0),t(y.touches[0].clientX),o=!1},c=y=>{y.touches.length>1||(this._hasScrollBar?(a=y.touches[0].clientX,v=y.touches[0].clientY,o=!0):l(y),window.addEventListener("touchmove",d,{passive:!1}),window.addEventListener("touchend",f))},d=y=>{if(o){let A=y.touches[0].clientX-a,C=y.touches[0].clientY-v;Math.abs(A)>Math.abs(C)?l(y):(window.removeEventListener("touchmove",d),window.removeEventListener("touchend",f))}else y.preventDefault(),t(y.touches[0].clientX)},f=()=>{this._callOnFinishChange(),this._setDraggingStyle(!1),window.removeEventListener("touchmove",d),window.removeEventListener("touchend",f)},m=this._callOnFinishChange.bind(this),g=400,b,w=y=>{if(Math.abs(y.deltaX)<Math.abs(y.deltaY)&&this._hasScrollBar)return;y.preventDefault();let C=this._normalizeMouseWheel(y)*this._step;this._snapClampSetValue(this.getValue()+C),this.$input.value=this.getValue(),clearTimeout(b),b=setTimeout(m,g)};this.$slider.addEventListener("mousedown",r),this.$slider.addEventListener("touchstart",c,{passive:!1}),this.$slider.addEventListener("wheel",w,{passive:!1})}_setDraggingStyle(e,t="horizontal"){this.$slider&&this.$slider.classList.toggle("active",e),document.body.classList.toggle("lil-gui-dragging",e),document.body.classList.toggle(`lil-gui-${t}`,e)}_getImplicitStep(){return this._hasMin&&this._hasMax?(this._max-this._min)/1e3:.1}_onUpdateMinMax(){!this._hasSlider&&this._hasMin&&this._hasMax&&(this._stepExplicit||this.step(this._getImplicitStep(),!1),this._initSlider(),this.updateDisplay())}_normalizeMouseWheel(e){let{deltaX:t,deltaY:r}=e;return Math.floor(e.deltaY)!==e.deltaY&&e.wheelDelta&&(t=0,r=-e.wheelDelta/120,r*=this._stepExplicit?1:10),t+-r}_arrowKeyMultiplier(e){let t=this._stepExplicit?1:10;return e.shiftKey?t*=10:e.altKey&&(t/=10),t}_snap(e){let t=Math.round(e/this._step)*this._step;return parseFloat(t.toPrecision(15))}_clamp(e){return e<this._min&&(e=this._min),e>this._max&&(e=this._max),e}_snapClampSetValue(e){this.setValue(this._clamp(this._snap(e)))}get _hasScrollBar(){let e=this.parent.root.$children;return e.scrollHeight>e.clientHeight}get _hasMin(){return this._min!==void 0}get _hasMax(){return this._max!==void 0}},gi=class extends Fe{constructor(e,t,r,i){super(e,t,r,"option"),this.$select=document.createElement("select"),this.$select.setAttribute("aria-labelledby",this.$name.id),this.$display=document.createElement("div"),this.$display.classList.add("display"),this._values=Array.isArray(i)?i:Object.values(i),this._names=Array.isArray(i)?i:Object.keys(i),this._names.forEach(s=>{let o=document.createElement("option");o.innerHTML=s,this.$select.appendChild(o)}),this.$select.addEventListener("change",()=>{this.setValue(this._values[this.$select.selectedIndex]),this._callOnFinishChange()}),this.$select.addEventListener("focus",()=>{this.$display.classList.add("focus")}),this.$select.addEventListener("blur",()=>{this.$display.classList.remove("focus")}),this.$widget.appendChild(this.$select),this.$widget.appendChild(this.$display),this.$disable=this.$select,this.updateDisplay()}updateDisplay(){let e=this.getValue(),t=this._values.indexOf(e);return this.$select.selectedIndex=t,this.$display.innerHTML=t===-1?e:this._names[t],this}},bi=class extends Fe{constructor(e,t,r){super(e,t,r,"string"),this.$input=document.createElement("input"),this.$input.setAttribute("type","text"),this.$input.setAttribute("aria-labelledby",this.$name.id),this.$input.addEventListener("input",()=>{this.setValue(this.$input.value)}),this.$input.addEventListener("keydown",i=>{i.code==="Enter"&&this.$input.blur()}),this.$input.addEventListener("blur",()=>{this._callOnFinishChange()}),this.$widget.appendChild(this.$input),this.$disable=this.$input,this.updateDisplay()}updateDisplay(){return this.$input.value=this.getValue(),this}},q7=`.lil-gui {
|
|
@@ -21485,7 +21485,7 @@ void main() {
|
|
|
21485
21485
|
vec4 texColor = texture2D(texture, gl_PointCoord);
|
|
21486
21486
|
gl_FragColor = vColor * texColor;
|
|
21487
21487
|
}
|
|
21488
|
-
`,K0={textureSize:128,gravity:new r0.Vector3(0,-.005,0),friction:.998,defaultParticleSize:300,maxActiveFireworks:5},N5=n=>{let t=n*3;return{x:t,y:t+1,z:t+2}},W5=n=>{let t=n*4;return{r:t,g:t+1,b:t+2,a:t+3}},ft=(n=0,e=0)=>Math.floor(Math.random()*(n+1-e))+e,pv=(n,e,t,r)=>{n.save();let i=n.createRadialGradient(e,e,0,e,e,e);i.addColorStop(0,"rgba(255,255,255,1.0)"),i.addColorStop(.5,"rgba(255,255,255,0.5)"),i.addColorStop(1,"rgba(255,255,255,0)"),n.fillStyle=i,n.fillRect(0,0,t,r),n.restore()},gv=()=>{let n=K0.textureSize,e=V0(n,n),t=e.getContext("2d"),r=n/2;pv(t,r,e.width,e.height);let i=new r0.Texture(e);return i.needsUpdate=!0,i},bv=(n,e,t,r,i=K0.defaultParticleSize)=>{let s=new r0.BufferGeometry,o=[],a=[],v=[],l=[],c=[],d=Math.random()>.3?"single":"multiple",f=ft(100,20)*.01,m=()=>ft(100,1)*.01,g="red",b=Math.random();b>.66?g="red":b>.33?g="green":g="blue";for(let y=0;y<n;y++){let A=new r0.Vector3(0,0,0);if(o.push(A.x,A.y,A.z),a.push(e[y].x,e[y].y,e[y].z),t==="seed"){let C=e[y].y**2*.04;y===0&&(C*=1.1),l.push(C),c.push(C*.017),v.push(1,1,1,1)}else if(t==="trail"){let C=Math.random()*.1+.1;l.push(C),c.push(C*.017),v.push(1,1,1,1)}else{let C=ft(i,10)*.001;if(l.push(C),c.push(C*.017),d==="multiple")v.push(m(),m(),m(),1);else switch(g){case"red":v.push(f,.1,.1,1);break;case"green":v.push(.1,f,.1,1);break;case"blue":v.push(.1,.1,f,1);break}}}s.setAttribute("position",new r0.Float32BufferAttribute(o,3)),s.setAttribute("velocity",new r0.Float32BufferAttribute(a,3)),s.setAttribute("color",new r0.Float32BufferAttribute(v,4)),s.setAttribute("adjustSize",new r0.Float32BufferAttribute(l,1)),s.setAttribute("mass",new r0.Float32BufferAttribute(c,1));let w=new r0.RawShaderMaterial({uniforms:{size:{value:K0.textureSize},texture:{value:r}},transparent:!0,depthWrite:!1,blending:r0.AdditiveBlending,vertexShader:hv,fragmentShader:mv});return new r0.Points(s,w)},V5=class{constructor(e,t,r,i,s){u(this,"particleNum");u(this,"timerStartFading");u(this,"mesh");this.particleNum=e,this.timerStartFading=10,this.mesh=bv(e,t,r,i,s)}update(e){this.timerStartFading>0&&(this.timerStartFading-=.3);let t=this.mesh.geometry.attributes.position,r=this.mesh.geometry.attributes.velocity,i=this.mesh.geometry.attributes.color,s=this.mesh.geometry.attributes.mass,o=()=>Math.random()>.5?.98:.96,a=v=>Math.random()>.5?0:(1-v)*.1;for(let v=0;v<this.particleNum;v++){let{x:l,y:c,z:d}=N5(v);r.array[c]+=e.y-s.array[v],r.array[l]*=K0.friction,r.array[d]*=K0.friction,r.array[c]*=K0.friction,t.array[l]+=r.array[l],t.array[c]+=r.array[c],t.array[d]+=r.array[d];let{a:f}=W5(v);this.timerStartFading<=0&&(i.array[f]*=o()-a(i.array[f]),i.array[f]<.001&&(i.array[f]=0))}t.needsUpdate=!0,r.needsUpdate=!0,i.needsUpdate=!0}disposeAll(){this.mesh.geometry.dispose(),this.mesh.material.dispose()}},Li=class extends V5{constructor(e,t,r){super(e,t,"seed",r)}update(e){let t=this.mesh.geometry.attributes.position,r=this.mesh.geometry.attributes.velocity,i=this.mesh.geometry.attributes.color,s=this.mesh.geometry.attributes.mass,o=()=>Math.random()>.3?.99:.96,a=d=>Math.random()>.3?0:(1-d)*.1,v=()=>Math.random()>.5?.05:-.05,l=()=>Math.random()>.1,c=K0.friction*.98;for(let d=0;d<this.particleNum;d++){let{x:f,y:m,z:g}=N5(d);r.array[m]+=e.y-s.array[d],r.array[f]*=c,r.array[g]*=c,r.array[m]*=c,t.array[f]+=r.array[f],t.array[m]+=r.array[m],t.array[g]+=r.array[g],l()&&(t.array[f]+=v()),l()&&(t.array[g]+=v());let{a:b}=W5(d);i.array[b]*=o()-a(i.array[b]),i.array[b]<.001&&(i.array[b]=0)}t.needsUpdate=!0,r.needsUpdate=!0,i.needsUpdate=!0}},Ui=class extends V5{constructor(e,t,r){super(e,t,"trail",r)}update(e){let t=this.mesh.geometry.attributes.position,r=this.mesh.geometry.attributes.velocity,i=this.mesh.geometry.attributes.color,s=this.mesh.geometry.attributes.mass,o=()=>Math.random()>.3?.98:.95,a=()=>Math.random()>.5?.05:-.05,v=()=>Math.random()>.2;for(let l=0;l<this.particleNum;l++){let{x:c,y:d,z:f}=N5(l);r.array[d]+=e.y-s.array[l],r.array[c]*=K0.friction,r.array[f]*=K0.friction,r.array[d]*=K0.friction,t.array[c]+=r.array[c],t.array[d]+=r.array[d],t.array[f]+=r.array[f],v()&&(t.array[c]+=a()),v()&&(t.array[f]+=a());let{a:m}=W5(l);i.array[m]*=o(),i.array[m]<.001&&(i.array[m]=0)}t.needsUpdate=!0,r.needsUpdate=!0,i.needsUpdate=!0}},j5=class{constructor(e,t=K0.defaultParticleSize,r){u(this,"meshGroup");u(this,"isExplode");u(this,"petalsNum");u(this,"life");u(this,"seed");u(this,"flowerSizeRate");u(this,"flower");u(this,"texture");u(this,"particleSize");this.meshGroup=new r0.Group,this.isExplode=!1,this.texture=e,this.particleSize=t;let i=400,s=150;this.petalsNum=ft(i,s),this.life=150,this.seed=this.getSeed(r),this.meshGroup.add(this.seed.mesh),this.flowerSizeRate=r0.MathUtils.mapLinear(this.petalsNum,s,i,.4,.7)}getSeed(e){let r=[];for(let s=0;s<40;s++){let a=s===0?Math.random()*2.5+.9:Math.random()*2+.4,v=0;r.push(new r0.Vector3(0,a,v))}let i=new Li(40,r,this.texture);if(e)i.mesh.position.set(0,0,0);else{let s=Math.random()*80-40,o=-50,a=Math.random()*80-40;i.mesh.position.set(s,o,a)}return i}explode(e){this.isExplode=!0,this.flower=this.getFlower(e),this.meshGroup.add(this.flower.mesh),this.meshGroup.remove(this.seed.mesh),this.seed.disposeAll()}getFlower(e){let t=this.petalsNum,r=[],i;if(Math.random()>.5)for(let a=0;a<t;a++){i=ft(120,60)*.01;let v=r0.MathUtils.degToRad(Math.random()*180),l=r0.MathUtils.degToRad(Math.random()*360),c=Math.sin(v)*Math.cos(l)*i,d=Math.sin(v)*Math.sin(l)*i,f=Math.cos(v)*i,m=new r0.Vector3(c,d,f);m.multiplyScalar(this.flowerSizeRate),r.push(m)}else{let a=180/t,v=360*(Math.random()*20+1)/t,l=v,c=v;i=ft(120,60)*.01;for(let d=0;d<t;d++){let f=Math.sin(r0.MathUtils.degToRad(a*d)),m=Math.cos(r0.MathUtils.degToRad(a*d))*i,g=Math.cos(r0.MathUtils.degToRad(l*d))*f*i,b=Math.sin(r0.MathUtils.degToRad(c*d))*f*i,w=new r0.Vector3(g,b,m);w.multiplyScalar(this.flowerSizeRate),r.push(w)}}let o=new V5(t,r,"default",this.texture,this.particleSize);return o.mesh.position.set(e.x,e.y,e.z),o}update(e){this.isExplode?(this.flower.update(e),this.life>0&&(this.life-=1)):this.drawTail()}drawTail(){this.seed.update(K0.gravity);let e=this.seed.mesh.geometry.attributes.position,t=this.seed.mesh.geometry.attributes.velocity,r=0;for(let d=0,f=t.array.length;d<f;d++){let m=t.array[d];d%3===1&&m>0&&r++}if(!(r===0))return;let{x:s,y:o,z:a}=this.seed.mesh.position,v=new r0.Vector3(s,o,a),l=0,c;for(let d=0,f=e.array.length;d<f;d++){let m=e.array[d];d%3===1&&m>l&&(l=m,c=new r0.Vector3(e.array[d-1],m,e.array[d+2]))}c&&(v.add(c),this.explode(v))}},Yt=class extends j5{constructor(t,r=K0.defaultParticleSize,i){super(t,r,i);u(this,"tailMeshGroup");u(this,"tails");let s=150,o=100;this.petalsNum=ft(s,o),this.flowerSizeRate=r0.MathUtils.mapLinear(this.petalsNum,o,s,.4,.7),this.tailMeshGroup=new r0.Group,this.tails=[]}explode(t){this.isExplode=!0,this.flower=this.getFlower(t),this.tails=this.getTail(),this.meshGroup.add(this.flower.mesh),this.meshGroup.add(this.tailMeshGroup)}getTail(){let t=[],i=this.flower.mesh.geometry.attributes.color;for(let s=0;s<this.petalsNum;s++){let o=[];for(let S=0;S<20;S++)o.push(new r0.Vector3(0,0,0));let a=new Ui(20,o,this.texture),{r:v,g:l,b:c,a:d}=W5(s),f=i.array[v],m=i.array[l],g=i.array[c],b=i.array[d],w=a.mesh.geometry.attributes.position,y=a.mesh.geometry.attributes.color;for(let S=0;S<w.count;S++){let H=W5(S);y.array[H.r]=f,y.array[H.g]=m,y.array[H.b]=g,y.array[H.a]=b}let{x:A,y:C,z:M}=this.flower.mesh.position;a.mesh.position.set(A,C,M),t.push(a),this.tailMeshGroup.add(a.mesh)}return t}update(t){if(this.isExplode){this.flower.update(t);let r=this.flower.mesh.geometry.attributes.position;for(let i=0,s=this.tails.length;i<s;i++){let o=this.tails[i];o.update(t);let{x:a,y:v,z:l}=N5(i),c=new r0.Vector3(r.array[a],r.array[v],r.array[l]),d=o.mesh.geometry.attributes.position,f=o.mesh.geometry.attributes.velocity;for(let m=0;m<d.count;m++){let g=N5(m),b=new r0.Vector3,w=new r0.Vector3(d.array[g.x],d.array[g.y],d.array[g.z]),y=new r0.Vector3(f.array[g.x],f.array[g.y],f.array[g.z]);b.subVectors(c,w);let A=b.sub(y);A.normalize(),A.multiplyScalar(Math.random()*3e-4*this.life),f.array[g.x]+=A.x,f.array[g.y]+=A.y,f.array[g.z]+=A.z}f.needsUpdate=!0}this.life>0&&(this.life-=1.2)}else this.drawTail()}},X1=class{constructor(e,t,r){u(this,"fireworksInstances");u(this,"scene");u(this,"sceneOrigin");u(this,"texture");u(this,"particleSize");u(this,"maxFireworks");this.fireworksInstances=[],this.scene=e,this.sceneOrigin=t,this.texture=gv(),this.particleSize=r?.defaultParticleSize??K0.defaultParticleSize,this.maxFireworks=r?.maxActiveFireworks??K0.maxActiveFireworks}launchFirework(e){if(this.fireworksInstances.length>=this.maxFireworks)return;let t=e?.particleSize??this.particleSize,r=e?.position,i;e?.forceRich?i=new Yt(this.texture,t,r):e?.forceBasic?i=new j5(this.texture,t,r):i=Math.random()>.5?new j5(this.texture,t,r):new Yt(this.texture,t,r),this.fireworksInstances.push(i),r?(this.sceneOrigin.addAndTrack(i.meshGroup),i.meshGroup.position.set(r.x,r.y,r.z)):this.scene.add(i.meshGroup)}repositionAll(){}update(){let e=[];for(let t=this.fireworksInstances.length-1;t>=0;t--){let r=this.fireworksInstances[t];r.update(K0.gravity),r.isExplode&&e.push(t)}for(let t=0,r=e.length;t<r;t++){let i=e[t],s=this.fireworksInstances[i];if(s&&(s.meshGroup.remove(s.seed.mesh),s.seed.disposeAll(),s.life<=0)){if(this.sceneOrigin.removeAndUntrack(s.meshGroup),s instanceof Yt&&s.tailMeshGroup)for(let o of s.tails)o.disposeAll();s.flower?.disposeAll(),this.fireworksInstances.splice(i,1)}}}clear(){for(let e of this.fireworksInstances)if(this.sceneOrigin.removeAndUntrack(e.meshGroup),e.seed.disposeAll(),e.flower&&e.flower.disposeAll(),e instanceof Yt)for(let t of e.tails)t.disposeAll();this.fireworksInstances=[]}dispose(){this.clear(),this.texture.dispose()}};E();x();k();R();var Q3=Symbol("tracked-proxy"),yv=new Set(["add","addScalar","addScaledVector","addVectors","sub","subScalar","subVectors","multiply","multiplyScalar","multiplyVectors","divide","divideScalar","applyEuler","applyAxisAngle","applyMatrix3","applyMatrix4","applyNormalMatrix","applyQuaternion","negate","floor","ceil","round","roundToZero","min","max","clamp","clampLength","clampScalar","project","unproject","reflect","lerp","lerpVectors","cross","crossVectors","setFromMatrixPosition","setFromMatrixColumn","setFromMatrix3Column","setFromEuler","setFromSpherical","setFromSphericalCoords","setFromCylindrical","fromArray","fromBufferAttribute","setComponent","randomDirection","random"]),$1=class{constructor(e){u(this,"scene");u(this,"_x",0);u(this,"_y",0);u(this,"_z",0);u(this,"_tracked",new Set);u(this,"_worldCoords",new WeakMap);u(this,"_originalPositions",new WeakMap);u(this,"_trackOptions",new WeakMap);this.scene=e}get x(){return this._x}get y(){return this._y}get z(){return this._z}update(e,t,r){this._x=e,this._y=t,this._z=r;for(let i of this._tracked){let s=this._worldCoords.get(i);this._originalPositions.get(i).set(s.x-e,s.y-t,s.z-r),this._trackOptions.get(i)?.updateMatrix&&i.updateMatrix()}}track(e,t){let r=this._originalPositions.get(e)??e.position,i={x:0,y:0,z:0};this._originalPositions.set(e,r),this._worldCoords.set(e,i),t?this._trackOptions.set(e,t):this._trackOptions.delete(e);let s=this,o=t,a=new Proxy(r,{get(v,l,c){if(l===Q3)return i;if(l==="set")return(f,m,g)=>(i.x=f,i.y=m,i.z=g,v.set(f-s._x,m-s._y,g-s._z),o?.updateMatrix&&e.updateMatrix(),c);if(l==="copy")return f=>{let m=f[Q3],g=m?m.x:f.x,b=m?m.y:f.y,w=m?m.z:f.z;return i.x=g,i.y=b,i.z=w,v.set(g-s._x,b-s._y,w-s._z),o?.updateMatrix&&e.updateMatrix(),c};if(l==="setX")return f=>(i.x=f,v.x=f-s._x,o?.updateMatrix&&e.updateMatrix(),c);if(l==="setY")return f=>(i.y=f,v.y=f-s._y,o?.updateMatrix&&e.updateMatrix(),c);if(l==="setZ")return f=>(i.z=f,v.z=f-s._z,o?.updateMatrix&&e.updateMatrix(),c);if(typeof l=="string"&&yv.has(l))return()=>{throw new Error(`Cannot call position.${l}() on a tracked object. Use position.set(x, y, z) instead.`)};let d=v[l];return typeof d=="function"?d.bind(v):d},set(v,l,c){return l==="x"?(i.x=c,v.x=c-s._x,o?.updateMatrix&&e.updateMatrix(),!0):l==="y"?(i.y=c,v.y=c-s._y,o?.updateMatrix&&e.updateMatrix(),!0):l==="z"?(i.z=c,v.z=c-s._z,o?.updateMatrix&&e.updateMatrix(),!0):(v[l]=c,!0)}});Object.defineProperty(e,"position",{value:a,configurable:!0,enumerable:!0}),this._tracked.add(e)}untrack(e){let t=this._originalPositions.get(e);t&&(Object.defineProperty(e,"position",{value:t,configurable:!0,enumerable:!0}),this._tracked.delete(e),this._worldCoords.delete(e),this._originalPositions.delete(e),this._trackOptions.delete(e))}addAndTrack(e,t){this.track(e,t),this.scene.add(e)}removeAndUntrack(e){this.untrack(e),e.removeFromParent()}removeAndUntrackAll(e){e.traverse(t=>{this.untrack(t)}),e.removeFromParent()}getWorldPosition(e){let t=this._worldCoords.get(e);return t?{x:t.x,y:t.y,z:t.z}:void 0}clear(){for(let e of this._tracked)this.untrack(e)}get trackedCount(){return this._tracked.size}toSceneX(e){return e-this._x}toSceneY(e){return e-this._y}toSceneZ(e){return e-this._z}toWorldX(e){return e+this._x}toWorldY(e){return e+this._y}toWorldZ(e){return e+this._z}};Yi();E();x();k();R();Qt();mt();Vi();import Ov from"prismarine-chat";import*as $ from"three";import*as cr from"prismarine-nbt";import{Vec3 as Ki}from"vec3";E();x();k();R();mt();Qt();import*as ue from"three";var Mv=2e6,Qi=X3(),vr=class{constructor(e,t){u(this,"mesh");u(this,"capacityFaces");u(this,"w0");u(this,"w1");u(this,"w2");u(this,"w3");u(this,"sectionSlots",new Map);u(this,"freeList",[]);u(this,"highWatermark",0);u(this,"dirtyMin",1/0);u(this,"dirtyMax",-1);this.capacityFaces=Mv,this.w0=new Uint32Array(this.capacityFaces),this.w1=new Uint32Array(this.capacityFaces),this.w2=new Uint32Array(this.capacityFaces),this.w3=new Uint32Array(this.capacityFaces);let r=new ue.InstancedBufferGeometry,i=new Float32Array(tr*3);r.setAttribute("position",new ue.BufferAttribute(i,3));let s=o=>{let a=new ue.InstancedBufferAttribute(o,1);return a.setUsage(ue.DynamicDrawUsage),a};r.setAttribute("a_w0",s(this.w0)),r.setAttribute("a_w1",s(this.w1)),r.setAttribute("a_w2",s(this.w2)),r.setAttribute("a_w3",s(this.w3)),r.instanceCount=0,this.mesh=new ue.Mesh(r,e),this.mesh.name="globalShaderCubes",this.mesh.frustumCulled=!1,this.mesh.matrixAutoUpdate=!1,this.mesh.matrix.identity(),this.mesh.position.set(0,0,0),t.add(this.mesh)}addSection(e,t,r){if(r<=0){this.removeSection(e);return}this.sectionSlots.has(e)&&this.removeSection(e),r>this.capacityFaces&&this.growCapacity(r);let i=this.takeFreeSlot(r);i||(this.highWatermark+r>this.capacityFaces&&this.growCapacity(this.highWatermark+r),i={start:this.highWatermark,count:r},this.highWatermark+=r);let s=4;for(let o=0;o<r;o++){let a=i.start+o,v=o*s;this.w0[a]=t[v],this.w1[a]=t[v+1],this.w2[a]=t[v+2],this.w3[a]=t[v+3]}this.sectionSlots.set(e,i),this.markDirty(i.start,i.start+r-1),this.mesh.geometry.instanceCount=this.highWatermark}hasSection(e){return this.sectionSlots.has(e)}takeSectionData(e){let t=this.sectionSlots.get(e);if(!t)return;let r=4,i=new Uint32Array(t.count*r);for(let s=0;s<t.count;s++){let o=t.start+s,a=s*r;i[a]=this.w0[o],i[a+1]=this.w1[o],i[a+2]=this.w2[o],i[a+3]=this.w3[o]}return this.removeSection(e),{words:i,count:t.count}}removeSection(e){let t=this.sectionSlots.get(e);if(t){for(let r=t.start;r<t.start+t.count;r++)this.w0[r]=0,this.w1[r]=0,this.w2[r]=Qi,this.w3[r]=0;this.markDirty(t.start,t.start+t.count-1),this.sectionSlots.delete(e),this.insertFreeSlot(t),this.shrinkHighWatermark(),this.mesh.geometry.instanceCount=this.highWatermark}}uploadDirtyRange(){if(this.dirtyMin>this.dirtyMax)return;let e=this.dirtyMin,t=this.dirtyMax-this.dirtyMin+1,r=this.mesh.geometry;for(let i of["a_w0","a_w1","a_w2","a_w3"]){let s=r.getAttribute(i);s.updateRange.offset=e,s.updateRange.count=t,s.needsUpdate=!0}this.dirtyMin=1/0,this.dirtyMax=-1}setCameraOrigin(e,t,r){let i=Math.floor(e),s=Math.floor(t),o=Math.floor(r),a=this.mesh.material.uniforms.u_cameraOrigin;a?.value?.set&&a.value.set(i,s,o);let v=this.mesh.material.uniforms.u_cameraOriginFrac;v?.value?.set&&v.value.set(e-i,t-s,r-o)}reset(){this.sectionSlots.clear(),this.freeList.length=0,this.highWatermark=0,this.dirtyMin=1/0,this.dirtyMax=-1,this.w0.fill(0),this.w1.fill(0),this.w2.fill(Qi),this.w3.fill(0),this.mesh.geometry.instanceCount=0}dispose(){this.mesh.parent?.remove(this.mesh),this.mesh.geometry.dispose(),this.reset()}markDirty(e,t){e<this.dirtyMin&&(this.dirtyMin=e),t>this.dirtyMax&&(this.dirtyMax=t)}takeFreeSlot(e){for(let t=0;t<this.freeList.length;t++){let r=this.freeList[t];if(r.count>=e){if(this.freeList.splice(t,1),r.count===e)return r;let i={start:r.start,count:e};return this.insertFreeSlot({start:r.start+e,count:r.count-e}),i}}}insertFreeSlot(e){this.freeList.push(e),this.freeList.sort((t,r)=>t.start-r.start),this.mergeFreeList()}mergeFreeList(){if(this.freeList.length<2)return;let e=[],t=this.freeList[0];for(let r=1;r<this.freeList.length;r++){let i=this.freeList[r];t.start+t.count===i.start?t={start:t.start,count:t.count+i.count}:(e.push(t),t=i)}e.push(t),this.freeList=e}shrinkHighWatermark(){for(;this.highWatermark>0;){let e=this.highWatermark-1,t=this.freeList.find(i=>i.start<=e&&i.start+i.count>e);if(!t||t.start+t.count!==this.highWatermark)break;this.highWatermark=t.start;let r=this.freeList.indexOf(t);this.freeList.splice(r,1)}}growCapacity(e){let t=this.capacityFaces;for(;t<e;)t*=2;let r=new Uint32Array(t),i=new Uint32Array(t),s=new Uint32Array(t),o=new Uint32Array(t);r.set(this.w0),i.set(this.w1),s.set(this.w2),o.set(this.w3),s.fill(Qi,this.w0.length),this.w0=r,this.w1=i,this.w2=s,this.w3=o,this.capacityFaces=t;let a=this.mesh.geometry,v=(l,c)=>{let d=a.getAttribute(c);d&&(a.deleteAttribute(c),"dispose"in d&&typeof d.dispose=="function"&&d.dispose());let f=new ue.InstancedBufferAttribute(l,1);f.setUsage(ue.DynamicDrawUsage),a.setAttribute(c,f)};v(this.w0,"a_w0"),v(this.w1,"a_w1"),v(this.w2,"a_w2"),v(this.w3,"a_w3"),this.dirtyMin=0,this.dirtyMax=this.highWatermark-1}};E();x();k();R();Qt();mt();function oa(n,e,t,r,i){if(e<=0)return;let s=t-8,o=r-8,a=i-8,v=sr,l=16,c=16,d=16,f=-1,m=-1,g=-1;for(let S=0;S<e;S++){let H=n[S*v],B=H&(1<<ht.LX_BITS)-1,I=H>>ht.LY_SHIFT&(1<<ht.LY_BITS)-1,G=H>>ht.LZ_SHIFT&(1<<ht.LZ_BITS)-1;B<l&&(l=B),I<c&&(c=I),G<d&&(d=G),B>f&&(f=B),I>m&&(m=I),G>g&&(g=G)}if(f<0)return;let b=s+l,w=o+c,y=a+d,A=s+f+1,C=o+m+1,M=a+g+1;return{minX:b,minY:w,minZ:y,maxX:A,maxY:C,maxZ:M,cx:(b+A)*.5,cy:(w+C)*.5,cz:(y+M)*.5}}function Sv(n,e,t,r,i,s,o,a,v){return n>=r&&n<=o&&e>=i&&e<=a&&t>=s&&t<=v}function aa(n,e,t,r,i,s,o,a,v,l,c,d,f){if(Sv(n,e,t,o,a,v,l,c,d))return;let m=0,g=f;if(Math.abs(r)<1e-8){if(n<o||n>l)return}else{let b=1/r,w=(o-n)*b,y=(l-n)*b;if(w>y){let A=w;w=y,y=A}if(m=Math.max(m,w),g=Math.min(g,y),m>g)return}if(Math.abs(i)<1e-8){if(e<a||e>c)return}else{let b=1/i,w=(a-e)*b,y=(c-e)*b;if(w>y){let A=w;w=y,y=A}if(m=Math.max(m,w),g=Math.min(g,y),m>g)return}if(Math.abs(s)<1e-8){if(t<v||t>d)return}else{let b=1/s,w=(v-t)*b,y=(d-t)*b;if(w>y){let A=w;w=y,y=A}if(m=Math.max(m,w),g=Math.min(g,y),m>g)return}return m<=g&&m>=0?m:void 0}E();x();k();R();import*as X0 from"three";var va=20,la=40,Cv={white_banner:15,orange_banner:14,magenta_banner:13,light_blue_banner:12,yellow_banner:11,lime_banner:10,pink_banner:9,gray_banner:8,light_gray_banner:7,cyan_banner:6,purple_banner:5,blue_banner:4,brown_banner:3,green_banner:2,red_banner:1,black_banner:0},ca={0:"#1d1d21",1:"#b02e26",2:"#5e7c16",3:"#835432",4:"#3c44aa",5:"#8932b8",6:"#169c9c",7:"#9d9d97",8:"#474f52",9:"#f38baa",10:"#80c71f",11:"#fed83d",12:"#3ab3da",13:"#c74ebd",14:"#f9801d",15:"#f9fffe"};function Bv(n){let e=n.replace("_wall_banner","_banner");return Cv[e]??15}var Pv=(n,e,t,r,i,s,o)=>{switch(n.fillStyle=t,e){case"bs":n.fillRect(r,i,s,o);break;case"ls":n.fillRect(r,i,s/3,o);break;case"rs":n.fillRect(r+s*2/3,i,s/3,o);break;case"ts":n.fillRect(r,i,s,o/3);break;case"ms":n.fillRect(r,i+o/3,s,o/3);break;case"drs":n.fillRect(r,i,s/2,o/2);break;case"dls":n.fillRect(r+s/2,i,s/2,o/2);break;case"ss":for(let a=0;a<s;a+=2)n.fillRect(r+a,i,1,o);break;case"cr":n.fillRect(r,i+o/3,s,o/3),n.fillRect(r+s/3,i,s/3,o);break;case"sc":n.fillRect(r,i+o/2-1,s,2),n.fillRect(r+s/2-1,i,2,o);break;default:n.fillRect(r,i,s,o)}};function Iv(n,e){if(!e||e.length===0)return`banner_${n}_empty`;let t=e.map(r=>`${r.Pattern??"bs"}_${r.Color??0}`).join(",");return`banner_${n}_${t}`}var Hv=(n,e,t=(r,i)=>V0(r,i))=>{let i=t(va*1,la*1),s=i.getContext("2d");if(s){if(s.imageSmoothingEnabled=!1,e?.Patterns&&e.Patterns.length>0)for(let o of e.Patterns){let a=o.Color??0,v=o.Pattern??"bs",l=ca[a]||ca[0];Pv(s,v,l,0,0,va*1,la*1)}return i}},lr=new Map;function da(n,e,t){let r=Bv(e),i=Iv(r,t?.Patterns),s=lr.get(i);if(s)return s.refCount++,s.texture;let o=Hv(r,t);if(!o)return;let a=new X0.Texture(o);return a.magFilter=X0.NearestFilter,a.minFilter=X0.NearestFilter,a.needsUpdate=!0,lr.set(i,{texture:a,refCount:1}),a}function ua(n){for(let[e,t]of lr.entries())if(t.texture===n){t.refCount--,t.refCount<=0&&(t.texture.dispose(),lr.delete(e));return}}function fa(n,e,t,r){let a,v,l;t?(a=(-14.6+13.4)/2/16-.5,v=1-14.75/16-.5,l=1/2):(a=(1.4+29.4)/2/16,v=1-7.25/16-.5,l=0);let c=new X0.Mesh(new X0.PlaneGeometry(.85,1.75),new X0.MeshBasicMaterial({map:r,transparent:!0}));c.renderOrder=999;let d=.5/16,f=.25/16;t?c.position.set(0,a,v+f+.004):c.position.set(0,a,v+d/2+.004);let m=new X0.Group;return m.rotation.set(0,-X0.MathUtils.degToRad(e*(t?90:45/2)),0),m.add(c),m.bannerTexture=r,m.position.set(n.x+.5,n.y+l,n.z+.5),m}var pt=class pt{constructor(e,t,r,i,s=3){this.worldRenderer=e;this.scene=t;this.material=r;this.worldHeight=i;u(this,"meshPool",[]);u(this,"activeSections",new Map);u(this,"sectionObjects",{});u(this,"waitingChunksToDisplay",{});u(this,"pendingNearReveal",new Map);u(this,"nearRevealTimers",new Map);u(this,"nearRevealGraceTimers",new Map);u(this,"poolSize");u(this,"maxPoolSize");u(this,"minPoolSize");u(this,"signHeadsRenderer");u(this,"chunkBoxMaterial",new $.MeshBasicMaterial({color:0,transparent:!0,opacity:0}));u(this,"cubeShaderMaterial",null);u(this,"globalBlockBuffer",null);u(this,"shaderSectionRaycastBoxes",new Map);u(this,"hits",0);u(this,"misses",0);u(this,"bypassPooling",!1);u(this,"renderTimes",[]);u(this,"maxRenderTimeSamples",30);u(this,"_performanceOverrideDistance");u(this,"lastPerformanceCheck",0);u(this,"performanceCheckInterval",2e3);this.updateViewDistance(s),this.signHeadsRenderer=new Ji(e),this.initializePool()}get performanceOverrideDistance(){return this._performanceOverrideDistance??0}set performanceOverrideDistance(e){this._performanceOverrideDistance=e,this.updateSectionsVisibility()}initializePool(){for(let e=0;e<this.poolSize;e++){let t=new $.BufferGeometry,r=new $.Mesh(t,this.material);r.visible=!1,r.matrixAutoUpdate=!1,r.name="pooled-section-mesh";let i={mesh:r,inUse:!1,lastUsedTime:0};this.meshPool.push(i)}}sectionHasRenderableContent(e){return e.positions.length>0?!0:this.isShaderCubesGpuEnabled()?(e.shaderCubes?.count??0)>0:!1}isShaderCubesGpuEnabled(){return this.worldRenderer.shaderCubeBlocksEnabled()}syncCubeShaderUniforms(){if(!this.isShaderCubesGpuEnabled())return;let e=this.cubeShaderMaterial??this.getCubeShaderMaterial();if(!e)return;let t=this.material.map??null;e.uniforms.u_atlas.value=t;let{tintPalette:r}=or();r.isReady()||r.createTexture(),e.uniforms.u_tintPalette.value=r.getTexture(),e.uniforms.u_debugMode.value=this.worldRenderer.worldRendererConfig.shaderCubeDebugMode??0,e.needsUpdate=!0}getCubeShaderMaterial(){return this.isShaderCubesGpuEnabled()?(this.cubeShaderMaterial||(this.cubeShaderMaterial=er(),this.syncCubeShaderUniforms()),this.cubeShaderMaterial):null}getGlobalBlockBuffer(){let e=this.getCubeShaderMaterial();return e?(this.globalBlockBuffer||(this.globalBlockBuffer=new vr(e,this.scene)),this.globalBlockBuffer):null}shouldDeferShaderToPerSection(e){let t=this.worldRenderer.getModule("futuristicReveal");return t?t.isInInitialRevealCampaign?.()?!0:t.shouldUseRevealEffect?.(e)===!0:!1}migrateDeferredShaderToGlobal(e){let t=this.sectionObjects[e];if(!t?.deferredShaderCubes)return;let{words:r,count:i}=t.deferredShaderCubes,s=t.worldX,o=t.worldY,a=t.worldZ;s!==void 0&&o!==void 0&&a!==void 0&&this.registerShaderSectionRaycastBox(e,r,i,s,o,a),this.getGlobalBlockBuffer()?.addSection(e,r,i);let l=t.mesh===t.shaderMesh;t.shaderMesh&&(Wi(t.shaderMesh),t.remove(t.shaderMesh),t.shaderMesh=void 0),delete t.deferredShaderCubes,l&&(t.mesh=void 0)}registerShaderSectionRaycastBox(e,t,r,i,s,o){let a=oa(t,r,i,s,o);a?this.shaderSectionRaycastBoxes.set(e,a):this.shaderSectionRaycastBoxes.delete(e)}unregisterShaderSectionRaycastBox(e){this.shaderSectionRaycastBoxes.delete(e)}raycastShaderSectionAABBs(e,t,r,i=80){let s=e.x,o=e.y,a=e.z,v=t.x,l=t.y,c=t.z,d=i*i,f=r,m=!1;for(let[g,b]of this.shaderSectionRaycastBoxes){let w=this.sectionObjects[g];if(w&&!w.visible)continue;let y=b.cx-s,A=b.cy-o,C=b.cz-a;if(y*y+A*A+C*C>d)continue;let M=aa(s,o,a,v,l,c,b.minX,b.minY,b.minZ,b.maxX,b.maxY,b.maxZ,f);M!==void 0&&M<f&&(f=M,m=!0)}return m?f:void 0}updateSection(e,t){let r=t.positions.length>0,i=t.shaderCubes,s=this.isShaderCubesGpuEnabled()&&(i?.count??0)>0;if(!r&&!s)return this.releaseSection(e),null;let o=this.sectionObjects[e];o&&this.cleanupSection(e),r||this.releasePooledMesh(e);let a;if(r){let w=this.activeSections.get(e);if(!w){if(w=this.acquireMesh(),!w)return null;this.activeSections.set(e,w),w.sectionKey=e}let{mesh:y}=w;this.updateGeometryAttribute(y.geometry,"position",t.positions,3),this.updateGeometryAttribute(y.geometry,"normal",t.normals,3),this.updateGeometryAttribute(y.geometry,"color",t.colors,3),this.updateGeometryAttribute(y.geometry,"uv",t.uvs,2),y.geometry.index=new $.BufferAttribute(t.indices,1),y.geometry.boundingBox=new $.Box3(new $.Vector3(-8,-8,-8),new $.Vector3(8,8,8)),y.geometry.boundingSphere=new $.Sphere(new $.Vector3(0,0,0),Math.sqrt(3*8**2)),this.worldRenderer.sceneOrigin.track(y,{updateMatrix:!0}),y.position.set(t.sx,t.sy,t.sz),y.updateMatrix(),y.visible=!0,y.name="mesh",w.lastUsedTime=performance.now(),a=y}let v=s?this.getCubeShaderMaterial():null,l,c=s&&this.shouldDeferShaderToPerSection(e);s&&i&&(c&&v?(l=ar(i,v),l.visible=!0):this.getGlobalBlockBuffer()?.addSection(e,i.words,i.count)),o=new $.Group,a&&(o.add(a),o.mesh=a),l&&(o.add(l),o.shaderMesh=l,i&&(o.deferredShaderCubes={words:i.words,count:i.count}),o.mesh||(o.mesh=l)),s&&i&&this.registerShaderSectionRaycastBox(e,i.words,i.count,t.sx,t.sy,t.sz);let d=0;r&&(d+=t.positions.length/3/4),s&&i&&(d+=i.count),o.tilesCount=d,o.blocksCount=t.blocksCount,o.worldX=t.sx,o.worldY=t.sy,o.worldZ=t.sz,o.sectionKey=e,o.name="chunk";try{if(Object.keys(t.signs).length>0){let w=new $.Group;w.name="signs";for(let[y,{isWall:A,isHanging:C,rotation:M}]of Object.entries(t.signs)){let S=this.worldRenderer.blockEntities[y];if(!S)continue;let[H,B,I]=y.split(","),G=this.signHeadsRenderer.renderSign(new Ki(+H,+B,+I),M,A,C,cr.simplify(S));G&&w.add(G)}o.add(w),o.signsContainer=w}if(Object.keys(t.heads).length>0){let w=new $.Group;w.name="heads";for(let[y,{isWall:A,rotation:C}]of Object.entries(t.heads)){let M=this.worldRenderer.blockEntities[y];if(!M)continue;let[S,H,B]=y.split(","),I=this.signHeadsRenderer.renderHead(new Ki(+S,+H,+B),C,A,cr.simplify(M));I&&w.add(I)}o.add(w),o.headsContainer=w}if(Object.keys(t.banners).length>0){let w=new $.Group;w.name="banners",o.bannersContainer=w,o.add(w);for(let[y,{isWall:A,rotation:C,blockName:M}]of Object.entries(t.banners)){let S=this.worldRenderer.blockEntities[y];if(!S)continue;let[H,B,I]=y.split(","),G=da(this.worldRenderer,M,cr.simplify(S));if(!G)continue;let O=fa(new Ki(+H,+B,+I),C,A,G),{x:j,y:J,z:X}=O.position;this.worldRenderer.sceneOrigin.track(O),O.position.set(j,J,X),w.add(O)}}}catch{}this.sectionObjects[e]=o,this.scene.add(o),o.matrixAutoUpdate=!1,this.worldRenderer.displayOptions?.inWorldRenderingConfig?.showChunkBorders&&this.updateBoxHelper(e,!0);let f=e.split(","),m=`${f[0]},${f[2]}`,g=!!this.worldRenderer.displayOptions?.inWorldRenderingConfig?._renderByChunks,b=!!this.worldRenderer.worldRendererConfig?.wasmMesher;if((g||b)&&!this.worldRenderer.finishedChunks[m]){o.visible=!1,o._waitingForChunkDisplay=!0;let w=this.waitingChunksToDisplay[m]??(this.waitingChunksToDisplay[m]=[]);w.includes(e)||w.push(e)}return o}finishChunkDisplay(e){if(!this.waitingChunksToDisplay[e]){this.tryRevealPending();return}if(this.isWasmGateActive()&&this.isBlockedByNearer(e,0)){this.pendingNearReveal.set(e,Date.now()),this.armNearRevealTimer(e),this.armExpectedGraceTimer(e);return}this.flushChunkDisplay(e),this.tryRevealPending()}flushChunkDisplay(e){let t=this.waitingChunksToDisplay[e];if(this.pendingNearReveal.delete(e),this.clearNearRevealTimer(e),this.clearExpectedGraceTimer(e),!!t){for(let r of t){let i=this.sectionObjects[r];i&&(i._waitingForChunkDisplay=!1,i.visible=!0)}delete this.waitingChunksToDisplay[e]}}tryRevealPending(){if(this.pendingNearReveal.size===0)return;let e=Date.now();for(let[t,r]of[...this.pendingNearReveal])this.isBlockedByNearer(t,e-r)||this.flushChunkDisplay(t)}onChunkRemovedFromGate(e){this.pendingNearReveal.delete(e),this.clearNearRevealTimer(e),this.clearExpectedGraceTimer(e),delete this.waitingChunksToDisplay[e],this.tryRevealPending()}isWasmGateActive(){return!!this.worldRenderer.worldRendererConfig?.wasmMesher}isBlockedByNearer(e,t){let r=this.worldRenderer.viewerChunkPosition;if(!r)return!1;let i=e.split(",");if(i.length!==2)return!1;let s=Number(i[0]),o=Number(i[1]),a=Math.floor(r.x/16),v=Math.floor(r.z/16),l=(s>>4)-a,c=(o>>4)-v,d=l*l+c*c;if(d===0)return!1;let f=this.worldRenderer.finishedChunks,m=this.worldRenderer.loadedChunks,g=this.worldRenderer.viewDistance;if(t<pt.EXPECTED_NEAR_GRACE_MS&&g>0){let w=g*g,y=Math.min(g,Math.ceil(Math.sqrt(Math.max(0,d-1))));for(let A=-y;A<=y;A++)for(let C=-y;C<=y;C++){let M=A*A+C*C;if(M>=d||M>w)continue;let S=a+A<<4,H=v+C<<4,B=`${S},${H}`;if(B!==e&&!f[B])return!0}return!1}for(let w in m){if(w===e||f[w])continue;let y=w.split(",");if(y.length!==2)continue;let A=(Number(y[0])>>4)-a,C=(Number(y[1])>>4)-v;if(A*A+C*C<d)return!0}return!1}armNearRevealTimer(e){if(this.nearRevealTimers.has(e))return;let t=setTimeout(()=>{this.nearRevealTimers.delete(e),this.pendingNearReveal.has(e)&&(this.flushChunkDisplay(e),this.tryRevealPending())},pt.NEAR_REVEAL_TIMEOUT_MS);this.nearRevealTimers.set(e,t)}clearNearRevealTimer(e){let t=this.nearRevealTimers.get(e);t&&(clearTimeout(t),this.nearRevealTimers.delete(e))}armExpectedGraceTimer(e){if(this.nearRevealGraceTimers.has(e))return;let t=setTimeout(()=>{this.nearRevealGraceTimers.delete(e),this.pendingNearReveal.has(e)&&this.tryRevealPending()},pt.EXPECTED_NEAR_GRACE_MS+50);this.nearRevealGraceTimers.set(e,t)}clearExpectedGraceTimer(e){let t=this.nearRevealGraceTimers.get(e);t&&(clearTimeout(t),this.nearRevealGraceTimers.delete(e))}cleanupSection(e){let t=this.sectionObjects[e];if(t){if(t._waitingForChunkDisplay){let r=e.split(","),i=`${r[0]},${r[2]}`,s=this.waitingChunksToDisplay[i];if(s){let o=s.indexOf(e);o!==-1&&s.splice(o,1),s.length===0&&delete this.waitingChunksToDisplay[i]}}if(t.bannersContainer&&(t.bannersContainer.traverse(r=>{r.bannerTexture&&ua(r.bannerTexture)}),this.disposeContainer(t.bannersContainer)),this.globalBlockBuffer?.removeSection(e),this.unregisterShaderSectionRaycastBox(e),t.shaderMesh&&(Wi(t.shaderMesh),t.shaderMesh=void 0),delete t.deferredShaderCubes,t.signsContainer&&this.disposeContainer(t.signsContainer),t.headsContainer&&this.disposeContainer(t.headsContainer),this.worldRenderer.sceneOrigin.removeAndUntrackAll(t),this.scene.remove(t),t.boxHelper){this.worldRenderer.sceneOrigin.removeAndUntrack(t.boxHelper),this.scene.remove(t.boxHelper),t.boxHelper.geometry.dispose();let r=t.boxHelper.material;if(Array.isArray(r))for(let i of r)i.dispose();else r.dispose();t.boxHelper=void 0}delete this.sectionObjects[e]}}releasePooledMesh(e){let t=this.activeSections.get(e);t&&(t.mesh.visible=!1,t.inUse=!1,t.sectionKey=void 0,t.lastUsedTime=0,this.clearGeometry(t.mesh.geometry),this.activeSections.delete(e),this.cleanupExcessMeshes())}releaseSection(e){this.cleanupSection(e);let t=this.activeSections.get(e);return t?(t.mesh.visible=!1,t.inUse=!1,t.sectionKey=void 0,t.lastUsedTime=0,this.clearGeometry(t.mesh.geometry),this.activeSections.delete(e),this.cleanupExcessMeshes(),!0):!1}getSectionObject(e){return this.sectionObjects[e]}updateBoxHelper(e,t,r=this.chunkBoxMaterial){let i=this.sectionObjects[e];if(i?.mesh)if(t){if(!i.boxHelper){let s=new $.Mesh(new $.BoxGeometry(16,16,16),r),o=new $.BoxHelper(s,16776960);o.name="helper";let a=i.worldX??0,v=i.worldY??0,l=i.worldZ??0;this.worldRenderer.sceneOrigin.track(o,{updateMatrix:!0}),o.position.set(a,v,l),o.updateMatrix(),this.scene.add(o),i.boxHelper=o}i.boxHelper.visible=!0}else i.boxHelper&&(i.boxHelper.visible=!1)}updateAllBoxHelpers(e){for(let t of Object.keys(this.sectionObjects))this.updateBoxHelper(t,e)}cleanSignChunkTextures(e,t){this.signHeadsRenderer.cleanChunkTextures(e,t)}getSectionMesh(e){return this.activeSections.get(e)?.mesh}hasSection(e){return this.activeSections.has(e)}updateViewDistance(e){let t=(e*2+1)**2,r=this.worldHeight/16,i=5;if(this.minPoolSize=Math.floor(t*i),this.maxPoolSize=Math.floor(t*r)+1,this.poolSize??(this.poolSize=this.minPoolSize),this.minPoolSize>this.poolSize){let s=Math.min(this.minPoolSize,this.maxPoolSize);this.expandPool(s)}}getStats(){let e=this.meshPool.filter(i=>!i.inUse).length,t=this.hits+this.misses>0?(this.hits/(this.hits+this.misses)*100).toFixed(1):"0",r=this.getEstimatedMemoryUsage();return{poolSize:this.poolSize,activeCount:this.activeSections.size,freeCount:e,hitRate:`${t}%`,hits:this.hits,misses:this.misses,memoryUsage:r}}getTotalTiles(){return Object.values(this.sectionObjects).reduce((e,t)=>e+(t.tilesCount||0),0)}getTotalBlocks(){return Object.values(this.sectionObjects).reduce((e,t)=>e+(t.blocksCount||0),0)}getEstimatedMemoryUsage(){let e=0,t=0,r=0,i=0,s=0,o=0,a=0,v=this.globalBlockBuffer?.mesh.geometry;if(v)for(let c of["a_w0","a_w1","a_w2","a_w3"]){let d=v.getAttribute(c);if(d){let f=d.array.byteLength;a+=f,e+=f}}for(let c of Object.values(this.sectionObjects)){let d=c.shaderMesh?.geometry;if(d)for(let f of["a_w0","a_w1","a_w2","a_w3"]){let m=d.getAttribute(f);if(m){let g=m.array.byteLength;a+=g,e+=g}}}for(let c of this.meshPool)if(c.inUse&&c.mesh.geometry){let{geometry:d}=c.mesh,f=d.getAttribute("position");if(f){let w=f.array.byteLength;t+=w,e+=w}let m=d.getAttribute("normal");if(m){let w=m.array.byteLength;r+=w,e+=w}let g=d.getAttribute("color");if(g){let w=g.array.byteLength;i+=w,e+=w}let b=d.getAttribute("uv");if(b){let w=b.array.byteLength;s+=w,e+=w}if(d.index){let w=d.index.array.byteLength;o+=w,e+=w}}return{total:`${(e/(1024*1024)).toFixed(2)} MB`,breakdown:{position:`${(t/(1024*1024)).toFixed(2)} MB`,normal:`${(r/(1024*1024)).toFixed(2)} MB`,color:`${(i/(1024*1024)).toFixed(2)} MB`,uv:`${(s/(1024*1024)).toFixed(2)} MB`,index:`${(o/(1024*1024)).toFixed(2)} MB`,shaderInstances:`${(a/(1024*1024)).toFixed(2)} MB`}}}dispose(){let e=[...this.activeSections.keys()];for(let t of e)this.releaseSection(t);this.signHeadsRenderer.dispose();for(let t of this.meshPool)t.mesh.geometry.dispose();this.meshPool.length=0,this.activeSections.clear(),this.chunkBoxMaterial.dispose(),this.shaderSectionRaycastBoxes.clear(),this.globalBlockBuffer?.dispose(),this.globalBlockBuffer=null,this.cubeShaderMaterial?.dispose(),this.cubeShaderMaterial=null,this.pendingNearReveal.clear();for(let t of this.nearRevealTimers.values())clearTimeout(t);this.nearRevealTimers.clear();for(let t of this.nearRevealGraceTimers.values())clearTimeout(t);this.nearRevealGraceTimers.clear()}acquireMesh(){if(this.bypassPooling){let t={mesh:new $.Mesh(new $.BufferGeometry,this.material),inUse:!0,lastUsedTime:performance.now()};return this.meshPool.push(t),this.poolSize++,t}for(let t of this.meshPool)if(!t.inUse)return t.inUse=!0,t.lastUsedTime=performance.now(),this.hits++,t;this.misses++;let e=Math.min(this.poolSize+16,this.maxPoolSize);e<=this.meshPool.length&&(e=this.meshPool.length+8,this.maxPoolSize=e),this.expandPool(e);for(let t=this.meshPool.length-1;t>=0;t--){let r=this.meshPool[t];if(!r.inUse)return r.inUse=!0,r.lastUsedTime=performance.now(),r}throw new Error("ChunkMeshManager: Failed to acquire mesh after pool expansion")}expandPool(e){let t=this.meshPool.length;this.poolSize=e;for(let r=t;r<e;r++){let i=new $.BufferGeometry,s=new $.Mesh(i,this.material);s.visible=!1,s.matrixAutoUpdate=!1,s.name="pooled-section-mesh";let o={mesh:s,inUse:!1,lastUsedTime:0};this.meshPool.push(o)}}updateGeometryAttribute(e,t,r,i){let s=e.getAttribute(t);s&&s.count===r.length/i?(s.array.set(r),s.needsUpdate=!0):e.setAttribute(t,new $.BufferAttribute(r,i))}clearGeometry(e){let t=["position","normal","color","uv"];for(let r of t)e.hasAttribute(r)&&e.deleteAttribute(r);e.index&&e.setIndex(null),e.boundingBox=null,e.boundingSphere=null}cleanupExcessMeshes(){if(this.poolSize>this.maxPoolSize){let e=this.meshPool.filter(t=>!t.inUse).length;if(e>0){let t=Math.min(this.poolSize-this.maxPoolSize,e);for(let r=0;r<t;r++){let i=this.meshPool.findIndex(s=>!s.inUse);i!==-1&&(this.meshPool[i].mesh.geometry.dispose(),this.meshPool.splice(i,1),this.poolSize--)}}}}disposeContainer(e){R0(e,!0)}recordRenderTime(e){this.renderTimes.push(e),this.renderTimes.length>this.maxRenderTimeSamples&&this.renderTimes.shift();let t=performance.now();t-this.lastPerformanceCheck>this.performanceCheckInterval&&(this.checkPerformance(),this.lastPerformanceCheck=t)}getEffectiveRenderDistance(){return this.performanceOverrideDistance||this.worldRenderer.viewDistance}resetPerformanceOverride(){this.performanceOverrideDistance=void 0,this.renderTimes.length=0}getAverageRenderTime(){return this.renderTimes.length===0?0:this.renderTimes.reduce((e,t)=>e+t,0)/this.renderTimes.length}checkPerformance(){if(this.renderTimes.length<this.maxRenderTimeSamples)return;let e=this.getAverageRenderTime(),t=16.67,r=t*1.5;if(e>r){let i=this.worldRenderer.viewDistance,s=Math.max(1,Math.floor(i*.8));(!this.performanceOverrideDistance||s<this.performanceOverrideDistance)&&(this.performanceOverrideDistance=s)}else if(this.performanceOverrideDistance&&e<t*1.1){let i=this.worldRenderer.viewDistance,s=Math.min(i,this.performanceOverrideDistance+1);s!==this.performanceOverrideDistance&&(this.performanceOverrideDistance=s>=i?void 0:s)}}updateSectionsVisibility(){let e=this.worldRenderer.cameraSectionPos;for(let[t,r]of Object.entries(this.sectionObjects)){if(r._waitingForChunkDisplay){r.visible=!1;continue}if(!this.performanceOverrideDistance){r.visible=!0;continue}let[i,s,o]=t.split(",").map(Number),a={x:i/16,y:s/16,z:o/16},v=a.x-e.x,l=a.z-e.z,c=Math.floor(Math.hypot(v,l));r.visible=c<=this.performanceOverrideDistance}}};u(pt,"NEAR_REVEAL_TIMEOUT_MS",5e3),u(pt,"EXPECTED_NEAR_GRACE_MS",1500);var Y5=pt,Ji=class{constructor(e){this.worldRendererThree=e;u(this,"chunkTextures",new Map)}dispose(){for(let[,e]of this.chunkTextures)for(let t of Object.keys(e))e[t].dispose();this.chunkTextures.clear()}renderHead(e,t,r,i){let s;if(i.SkullOwner?s=i.SkullOwner.Properties?.textures?.[0]?.Value:s=i.profile?.properties?.find(o=>o.name==="textures")?.value,!!s)try{let a=JSON.parse(z.from(s,"base64").toString()).textures?.SKIN?.url,{skinTexturesProxy:v}=this.worldRendererThree.worldRendererConfig;v&&(a=a?.replace("http://textures.minecraft.net/",v).replace("https://textures.minecraft.net/",v));let l=De(this.worldRendererThree,a,ze.head),c=new $.Group;return r&&l.position.set(0,.3125,.3125),l.position.y-=23/16,c.add(l),this.worldRendererThree.sceneOrigin.track(c),c.position.set(e.x+.5,e.y+.045,e.z+.5),c.rotation.set(0,-$.MathUtils.degToRad(t*(r?90:45/2)),0),c.scale.set(.8,.8,.8),c}catch{}}renderSign(e,t,r,i,s){let o=this.getSignTexture(e,s,i);if(!o)return;let a=new $.Mesh(new $.PlaneGeometry(1,1),new $.MeshBasicMaterial({map:o,transparent:!0}));a.renderOrder=999;let v=7/16,l=i?1.3:1;a.scale.set(1*l,v*l,1*l);let c=(i?2:1.5)/16,d=.25/16;r&&!i?a.position.set(0,0,-.5+c+d+1e-4):a.position.set(0,0,c/2+1e-4);let f=new $.Group;f.rotation.set(0,-$.MathUtils.degToRad(t*(r?90:45/2)),0),f.add(a);let m=(i?10:8)/16,g=(i?0:r?4.333:9.333)/16,b=m/2+g;return this.worldRendererThree.sceneOrigin.track(f),f.position.set(e.x+.5,e.y+b,e.z+.5),f}getSignTexture(e,t,r,i=!1){let s=Ct(e),o=this.chunkTextures.get(`${s[0]},${s[1]}`);o||(o={},this.chunkTextures.set(`${s[0]},${s[1]}`,o));let a=`${e.x},${e.y},${e.z}`;if(o[a])return o[a];let v=Ov(this.worldRendererThree.version),l=m1(t,r,v);if(!l)return;let c=new $.Texture(l);return c.magFilter=$.NearestFilter,c.minFilter=$.NearestFilter,c.needsUpdate=!0,o[a]=c,c}cleanChunkTextures(e,t){let r=`${Math.floor(e/16)},${Math.floor(t/16)}`,i=this.chunkTextures.get(r);if(i)for(let s of Object.keys(i))i[s].dispose(),delete i[s]}};E();x();k();R();E();x();k();R();import*as Ge from"three";var dr={},ha=!1;function Fv(){if(ha)return;let n=globalThis.loadedData?.tints;if(n){for(let e of Object.keys(n))dr[e]=Dv(n[e]);ha=!0}}function Dv(n){let e={},t=ma(n.default??16777215);if(n.data)for(let r of n.data){let i=ma(r.color);for(let s of r.keys)e[s]=i}return new Proxy(e,{get(r,i){return r[i]??t}})}function ma(n){return[(n>>16&255)/255,(n>>8&255)/255,(n&255)/255]}function pa(n,e){return Fv(),n==="grass_block"?[1,1,1]:n==="redstone_wire"?[1,1,1]:n==="birch_leaves"||n==="spruce_leaves"||n==="lily_pad"?dr.constant?.[n]??[1,1,1]:n.includes("leaves")||n==="vine"?dr.foliage?.[e]??[1,1,1]:["short_grass","tall_grass","fern","large_fern","sugar_cane","grass"].includes(n)?dr.grass?.[e]??[1,1,1]:[1,1,1]}var zv=512,qi=1/20,Zi=class{constructor(e){this.worldRenderer=e;u(this,"particles",[]);u(this,"sharedMaterial");u(this,"enabled",!1);u(this,"tickAccumulator",0);u(this,"nextParticleIndex",0);u(this,"render",e=>{if(!this.enabled)return;for(this.tickAccumulator+=e;this.tickAccumulator>=qi;)this.tickAccumulator-=qi,this.tickPhysics();let t=this.tickAccumulator/qi;this.updateVisuals(t)})}enable(){this.enabled||(this.enabled=!0,this.ensureMaterial())}disable(){this.enabled&&(this.enabled=!1)}dispose(){for(let e of this.particles)e.active&&this.worldRenderer.sceneOrigin.removeAndUntrack(e.mesh),e.mesh.geometry.dispose();this.particles=[],this.sharedMaterial?.dispose(),this.sharedMaterial=void 0,this.nextParticleIndex=0}spawnBlockBreakParticles(e,t,r,i,s,o="plains"){if(!this.enabled)return;let a=this.resolveBlockTexture(i);if(!a)return;let v=pa(i,o);for(let l=0;l<4;l++)for(let c=0;c<4;c++)for(let d=0;d<4;d++){let f=e+(l+.5)/4,m=t+(c+.5)/4,g=r+(d+.5)/4,b=f-e-.5,w=m-t-.5,y=g-r-.5;b+=(Math.random()*2-1)*.4,w+=(Math.random()*2-1)*.4,y+=(Math.random()*2-1)*.4;let A=(Math.random()+Math.random()+1)*.15,C=Math.sqrt(b*b+w*w+y*y),M=b/C*A*.4,S=w/C*A*.4+.1,H=y/C*A*.4,B=Math.floor(4/(Math.random()*.9+.1));this.createParticle(f,m,g,M,S,H,B,a,s,e,r,1,v)}}tickPhysics(){for(let e of this.particles){if(!e.active)continue;if(e.prevX=e.x,e.prevY=e.y,e.prevZ=e.z,e.age++,e.age>=e.maxAge){this.deactivateParticle(e);continue}e.yd-=.04,e.x+=e.xd,e.y+=e.yd,e.z+=e.zd;let t=this.getFloorY(e);e.y<=t?(e.y=t,e.yd=0,e.onGround=!0):e.onGround=!1,e.xd*=.98,e.yd*=.98,e.zd*=.98,e.onGround&&(e.xd*=.7,e.zd*=.7)}}updateVisuals(e){let t=this.worldRenderer.camera.position;for(let r of this.particles){if(!r.active)continue;let i=r.prevX+(r.x-r.prevX)*e,s=r.prevY+(r.y-r.prevY)*e,o=r.prevZ+(r.z-r.prevZ)*e;r.mesh.position.set(i,s,o),r.mesh.lookAt(t.x,t.y,t.z)}}spawnCrackParticle(e,t,r,i,s,o,a="plains"){if(!this.enabled)return;let v=this.resolveBlockTexture(s);if(!v)return;let l=pa(s,a),c=e+Math.random()*.8+.1,d=t+Math.random()*.8+.1,f=r+Math.random()*.8+.1;switch(i){case 0:d=t-.1;break;case 1:d=t+1+.1;break;case 2:f=r-.1;break;case 3:f=r+1+.1;break;case 4:c=e-.1;break;case 5:c=e+1+.1;break}let m=(Math.random()*2-1)*.4*.2,g=(Math.random()*2-1)*.4*.2+.1*.2,b=(Math.random()*2-1)*.4*.2,w=Math.floor(4/(Math.random()*.9+.1));this.createParticle(c,d,f,m,g,b,w,v,o,e,r,.6,l)}createParticle(e,t,r,i,s,o,a,v,l,c,d,f=1,m=[1,1,1]){this.ensureMaterial();let g=this.findInactiveParticle();g||(this.particles.length<zv?g=this.allocateParticle():g=this.recycleOldest());let b=Math.floor(Math.random()*4),w=Math.floor(Math.random()*4),y=v.u+b/4*v.su,A=v.v+w/4*v.sv,C=v.su/4,M=v.sv/4;this.setGeometryUVs(g.mesh.geometry,y,A,C,M),g.active=!0,g.x=e,g.y=t,g.z=r,g.prevX=e,g.prevY=t,g.prevZ=r,g.xd=i,g.yd=s,g.zd=o,g.age=0,g.maxAge=a,g.onGround=!1,g.floorMap=l,g.blockX=Math.floor(c),g.blockZ=Math.floor(d);let S=.1*(.5+Math.random()*.5)*2*f;g.mesh.scale.set(S,S,S),g.mesh.position.set(e,t,r),g.mesh.visible=!0;let H=.6*m[0],B=.6*m[1],I=.6*m[2],G=new Float32Array([H,B,I,H,B,I,H,B,I,H,B,I]),O=g.mesh.geometry.getAttribute("color");O?(O.set(G),O.needsUpdate=!0):g.mesh.geometry.setAttribute("color",new Ge.Float32BufferAttribute(G,3)),this.worldRenderer.sceneOrigin.addAndTrack(g.mesh)}allocateParticle(){let e=new Ge.PlaneGeometry(1,1),t=new Ge.Mesh(e,this.sharedMaterial);t.visible=!1;let r={mesh:t,active:!1,x:0,y:0,z:0,prevX:0,prevY:0,prevZ:0,xd:0,yd:0,zd:0,age:0,maxAge:0,onGround:!1,floorMap:[],blockX:0,blockZ:0};return this.particles.push(r),r}findInactiveParticle(){for(let e=0;e<this.particles.length;e++){let t=(this.nextParticleIndex+e)%this.particles.length;if(!this.particles[t].active)return this.nextParticleIndex=(t+1)%this.particles.length,this.particles[t]}}recycleOldest(){let e=this.particles[0];for(let t of this.particles)t.age>e.age&&(e=t);return this.deactivateParticle(e),e}deactivateParticle(e){e.active&&(e.active=!1,e.mesh.visible=!1,this.worldRenderer.sceneOrigin.removeAndUntrack(e.mesh))}getFloorY(e){let t=Math.floor(e.x)-e.blockX,r=Math.floor(e.z)-e.blockZ;return t=Math.max(-2,Math.min(2,t)),r=Math.max(-2,Math.min(2,r)),e.floorMap[(r+2)*5+(t+2)]}resolveBlockTexture(e){let t=this.worldRenderer.resourcesManager.currentResources;if(!t)return null;let r=t.blocksAtlasJson,i=r.textures;if(i[e])return this.extractUV(i[e],r);for(let s of["_side","_top","_front","_0",""]){let o=e+s;if(i[o])return this.extractUV(i[o],r)}for(let s of Object.keys(i))if(s.startsWith(e))return this.extractUV(i[s],r);return null}extractUV(e,t){return{u:e.u,v:e.v,su:e.su??t.suSv,sv:e.sv??t.suSv}}setGeometryUVs(e,t,r,i,s){let o=e.getAttribute("uv");o.setXY(0,t,r),o.setXY(1,t+i,r),o.setXY(2,t,r+s),o.setXY(3,t+i,r+s),o.needsUpdate=!0}ensureMaterial(){if(this.sharedMaterial)return;let e=this.worldRenderer.material.map;e&&(this.sharedMaterial=new Ge.MeshBasicMaterial({map:e,vertexColors:!0,transparent:!0,alphaTest:.1}))}},ga={id:"blockBreakParticles",controller:Zi,enabledDefault:!0,cannotBeDisabled:!0,requiresHeightmap:!1};E();x();k();R();var Xi=class{constructor(e){this.worldRenderer=e;u(this,"enabled",!1);u(this,"lastBobWalkDist",0);u(this,"lastBobTickTime",0);u(this,"render",()=>{if(!this.enabled)return;let e=this.worldRenderer.displayOptions.inWorldRenderingConfig,{perspective:t}=this.worldRenderer.playerStateReactive;if(e.viewBobbing&&t==="first_person"&&!this.worldRenderer.playerStateUtils.isSpectator()){this.worldRenderer.playerStateReactive.walkDist!==this.lastBobWalkDist&&(this.lastBobTickTime=performance.now(),this.lastBobWalkDist=this.worldRenderer.playerStateReactive.walkDist);let i=Math.min((performance.now()-this.lastBobTickTime)/50,1);this.worldRenderer.cameraShake.setCameraBobInput({walkDist:this.worldRenderer.playerStateReactive.walkDist,prevWalkDist:this.worldRenderer.playerStateReactive.prevWalkDist,bob:this.worldRenderer.playerStateReactive.bob,prevBob:this.worldRenderer.playerStateReactive.prevBob,partialTick:i})}else this.worldRenderer.cameraShake.setCameraBobInput(null)})}enable(){this.enabled=!0}disable(){this.enabled=!1,this.worldRenderer.cameraShake.setCameraBobInput(null);let{perspective:e}=this.worldRenderer.playerStateReactive;e==="first_person"&&this.worldRenderer.camera.position.set(0,0,0)}dispose(){this.disable()}},ba={id:"cameraBobbing",controller:Xi,enabledDefault:!0,cannotBeDisabled:!0};E();x();k();R();import*as I0 from"three";var $i=2e3,ya=32,_a=32,ur=12,wa=24,fr=1.2,Lv=-5;var en=class{constructor(e){this.worldRenderer=e;u(this,"instancedMesh");u(this,"geometry");u(this,"material");u(this,"particles",[]);u(this,"enabled",!1);u(this,"dummy",new I0.Matrix4);u(this,"tempPosition",new I0.Vector3);u(this,"tempQuaternion",new I0.Quaternion);u(this,"tempScale",new I0.Vector3);u(this,"render",e=>{if(!this.enabled||!this.instancedMesh||!this.material)return;this.syncMaterialToSceneFog();let t=this.worldRenderer.getCameraPosition();this.instancedMesh.position.set(0,0,0);let r=this.worldRenderer.reactiveState.world.heightmaps,{dummy:i,tempPosition:s,tempQuaternion:o,tempScale:a}=this,v=NaN,l=NaN,c;for(let d=0;d<$i;d++){let f=this.particles[d];this.instancedMesh.getMatrixAt(d,i),i.decompose(s,o,a),s.addScaledVector(f.velocity,e);let m=s.y,g=Math.sqrt(s.x*s.x+s.z*s.z),b=t.x+s.x,w=t.y+s.y,y=t.z+s.z,A=Math.floor(b/16),C=Math.floor(y/16);(A!==v||C!==l)&&(c=r.get(`${A},${C}`),v=A,l=C);let M=(Math.floor(b)%16+16)%16,S=(Math.floor(y)%16+16)%16,H=c?.[S*16+M];if(g>ya||H!==void 0&&H!==-32768&&w<=H+1+f.despawnOffset||m<Lv){this.respawnParticle(s);let I=ur+Math.random()*(wa-ur);f.velocity.set((Math.random()-.5)*fr,-I,(Math.random()-.5)*fr),f.despawnOffset=Math.random()*.5}i.compose(s,o,a),this.instancedMesh.setMatrixAt(d,i)}this.instancedMesh.instanceMatrix.needsUpdate=!0})}enable(){this.enabled||(this.enabled=!0,this.instancedMesh?this.instancedMesh.visible=!0:this.createRain())}disable(){this.enabled&&(this.enabled=!1,this.instancedMesh&&(this.instancedMesh.visible=!1))}autoEnableCheck(){return this.worldRenderer.worldRendererConfig.isRaining===!0}dispose(){this.instancedMesh&&this.worldRenderer.scene.remove(this.instancedMesh),this.geometry?.dispose(),this.material?.dispose(),this.instancedMesh=void 0,this.geometry=void 0,this.material=void 0,this.particles=[]}syncMaterialToSceneFog(){if(!this.material)return;let e=this.worldRenderer.scene.fog;e instanceof I0.Fog||e instanceof I0.FogExp2?this.material.color.copy(e.color):this.material.color.set(13426158),this.material.fog=!0}createRain(){this.geometry=new I0.BoxGeometry(.03,.3,.03),this.material=new I0.MeshBasicMaterial({color:13426158,transparent:!0,opacity:.35,depthWrite:!1,fog:!0}),this.instancedMesh=new I0.InstancedMesh(this.geometry,this.material,$i),this.instancedMesh.name="rain-particles",this.instancedMesh.frustumCulled=!1,this.syncMaterialToSceneFog();let e=new I0.Matrix4,t=new I0.Vector3;for(let r=0;r<$i;r++){this.respawnParticle(t),t.y=Math.random()*_a,e.setPosition(t),this.instancedMesh.setMatrixAt(r,e);let i=ur+Math.random()*(wa-ur);this.particles.push({velocity:new I0.Vector3((Math.random()-.5)*fr,-i,(Math.random()-.5)*fr),age:0,despawnOffset:Math.random()*.5})}this.instancedMesh.instanceMatrix.needsUpdate=!0,this.worldRenderer.scene.add(this.instancedMesh)}respawnParticle(e){let t=Math.random()*Math.PI*2,r=Math.random()*ya;e.set(Math.cos(t)*r,_a,Math.sin(t)*r)}},Aa={id:"rain",controller:en,enabledDefault:!1,requiresHeightmap:!0};E();x();k();R();import*as w0 from"three";var Ea=new w0.Color(13/255,234/255,238/255),Uv=9;var Gv=350,Nv=650;var Wv=120,Vv=280,tn=class{constructor(e){this.worldRenderer=e;u(this,"pendingGeometries",new Map);u(this,"revealingSections",new Map);u(this,"finishedChunkCount",0);u(this,"revealTriggered",!1);u(this,"revealStartTime",0);u(this,"enabled",!1);u(this,"onWorldSwitchedCb",null);u(this,"patched",!1);u(this,"initialWaveDone",!1);u(this,"initialRevealWaveSettled",!1);u(this,"wireframeMaterial");u(this,"wireframeGlowMaterial");u(this,"pulseTime",0);u(this,"revealedChunks",new Set);u(this,"originalFinishChunk",null);u(this,"originalDestroy",null);u(this,"originalSceneAdd",null);u(this,"originalHandleWorkerMessage",null);u(this,"render",e=>{this.enabled&&this.update(e*1e3)});this.wireframeMaterial=new w0.LineBasicMaterial({color:Ea,transparent:!0,opacity:1,blending:w0.AdditiveBlending,depthWrite:!1}),this.wireframeGlowMaterial=new w0.LineBasicMaterial({color:Ea,transparent:!0,opacity:.55,blending:w0.AdditiveBlending,depthWrite:!1})}isFuturisticRevealConfigured(){return this.worldRenderer.worldRendererConfig.futuristicReveal===!0}isInInitialRevealCampaign(){return this.enabled&&!this.initialRevealWaveSettled}autoEnableCheck(){return this.isFuturisticRevealConfigured()}enable(){if(this.isFuturisticRevealConfigured()&&!(this.enabled&&this.patched)){if(this.enabled&&!this.patched){this.patchWorldRenderer();return}this.enabled=!0,this.patchWorldRenderer()}}disable(){this.enabled&&(this.enabled=!1,this.unpatchWorldRenderer(),this.reset())}toggle(){return this.enabled?this.disable():this.enable(),this.enabled}dispose(){this.disable(),this.wireframeMaterial.dispose(),this.wireframeGlowMaterial.dispose()}patchWorldRenderer(){if(this.patched)return;this.patched=!0;let e=this.worldRenderer;this.onWorldSwitchedCb=()=>this.reset(),e.onWorldSwitched.push(this.onWorldSwitchedCb),this.originalFinishChunk=e.finishChunk.bind(e),e.finishChunk=t=>{this.originalFinishChunk(t),this.onChunkFinished(t)},this.originalDestroy=e.destroy.bind(e),e.destroy=()=>{this.dispose(),this.originalDestroy()},this.originalHandleWorkerMessage=e.handleWorkerMessage.bind(e),e.handleWorkerMessage=t=>{this.originalHandleWorkerMessage(t),this.enabled&&t?.type==="geometry"&&Promise.resolve().then(()=>{try{this.registerSection(t.key,t.geometry)}catch{}})},this.originalSceneAdd=e.scene.add.bind(e.scene),e.scene.add=(...t)=>{let r=this.originalSceneAdd(...t);for(let i of t)this.checkAndPatchMesh(i);return r}}unpatchWorldRenderer(){let e=this.worldRenderer;if(this.originalFinishChunk&&(e.finishChunk=this.originalFinishChunk,this.originalFinishChunk=null),this.originalDestroy&&(e.destroy=this.originalDestroy,this.originalDestroy=null),this.originalHandleWorkerMessage&&(e.handleWorkerMessage=this.originalHandleWorkerMessage,this.originalHandleWorkerMessage=null),this.originalSceneAdd&&(e.scene.add=this.originalSceneAdd,this.originalSceneAdd=null),this.onWorldSwitchedCb){let t=e.onWorldSwitched.indexOf(this.onWorldSwitchedCb);t!==-1&&e.onWorldSwitched.splice(t,1),this.onWorldSwitchedCb=null}this.patched=!1}checkAndPatchMesh(e){if(e instanceof w0.Mesh&&(e.name==="mesh"||e.name==="shaderMesh")){let t=this.findSectionKeyForMesh(e);t&&this.shouldUseRevealEffect(t)&&(e.visible=!1,e.hiddenByReveal=!0)}for(let t of e.children)this.checkAndPatchMesh(t)}findSectionKeyForMesh(e){let t=e;for(;t;){let{sectionKey:m}=t;if(m&&this.worldRenderer.chunkMeshManager.sectionObjects[m]===t)return m;t=t.parent}let r=this.worldRenderer.sceneOrigin.getWorldPosition(e),i=r?.x??this.worldRenderer.sceneOrigin.toWorldX(e.position.x),s=r?.y??this.worldRenderer.sceneOrigin.toWorldY(e.position.y),o=r?.z??this.worldRenderer.sceneOrigin.toWorldZ(e.position.z),a=16,v=this.worldRenderer.getSectionHeight(),l=Math.floor(i/a)*a,c=Math.floor(s/v)*v,d=Math.floor(o/a)*a,f=`${l},${c},${d}`;return this.worldRenderer.chunkMeshManager.sectionObjects[f]?f:null}get scene(){return this.worldRenderer.realScene}getCameraPosition(){return this.worldRenderer.getCameraPosition()}sectionHasRevealContent(e){return(e.wireframePositions?.length??0)>0||(e.positions?.length??0)>0?!0:(e.shaderCubes?.count??0)>0}getSectionRenderMeshes(e){let t=this.worldRenderer.chunkMeshManager.sectionObjects[e];if(!t)return[];let r=[];for(let i of["mesh","shaderMesh"]){let s=t.children.find(o=>o.name===i);s instanceof w0.Mesh&&r.push(s)}return r}hideSectionRenderMeshes(e){let t=this.getSectionRenderMeshes(e);for(let r of t)r.visible=!1,r.hiddenByReveal=!0;return t}setMeshFadeOpacity(e,t){if(e.name==="shaderMesh"){e.visible=t>.001;return}let r=e.material;if(!Array.isArray(r))if(r.originalMaterial)r.opacity=t,r.transparent=!0,r.needsUpdate=!0;else{r.originalMaterial=r;let i=r.clone();i.transparent=!0,i.opacity=t,i.needsUpdate=!0,e.material=i}}restoreMeshMaterial(e){let t=e.originalMaterial;if(!t)return;let r=e.material;e.material=t,r!==t&&r.dispose(),delete e.originalMaterial}onChunkFinished(e){this.finishedChunkCount++,!this.revealTriggered&&this.finishedChunkCount>=Uv&&this.triggerReveal()}registerSection(e,t){if(!(this.revealedChunks.has(e)||this.revealingSections.has(e))){if(this.revealTriggered&&this.initialWaveDone){this.revealedChunks.add(e);return}this.revealTriggered?this.startSectionReveal(e,t):this.pendingGeometries.set(e,t)}}shouldUseRevealEffect(e){return!this.enabled||this.revealTriggered&&this.initialWaveDone?!1:!this.revealedChunks.has(e)&&!this.revealingSections.has(e)}triggerReveal(){this.revealTriggered=!0,this.initialWaveDone=!0,this.revealStartTime=performance.now();let e=this.getCameraPosition(),t=[...this.pendingGeometries.entries()];this.pendingGeometries.clear();let r=t.map(([s,o])=>{let a=Math.hypot(o.sx-e.x,o.sy-e.y,o.sz-e.z);return{key:s,geometry:o,distance:a}}).sort((s,o)=>s.distance-o.distance),i=r.at(-1)?.distance||1;for(let{key:s,geometry:o,distance:a}of r){let v=a/i*1500;setTimeout(()=>{!this.revealedChunks.has(s)&&!this.revealingSections.has(s)&&this.startSectionReveal(s,o)},v)}}startSectionReveal(e,t){if(!this.sectionHasRevealContent(t)||this.revealingSections.has(e)||this.revealedChunks.has(e))return;let r=this.createWireframeGeometry(t),i=this.worldRenderer.chunkMeshManager.globalBlockBuffer,s=i?.hasSection(e)?i.takeSectionData(e):void 0,o=this.hideSectionRenderMeshes(e),a=new w0.LineSegments(r,this.wireframeMaterial.clone());this.worldRenderer.sceneOrigin.track(a),a.position.set(t.sx,t.sy,t.sz),a.name="scifi-wireframe",a.renderOrder=1e3;let v=new w0.LineSegments(r.clone(),this.wireframeGlowMaterial.clone());this.worldRenderer.sceneOrigin.track(v),v.position.set(t.sx,t.sy,t.sz),v.scale.set(1.02,1.02,1.02),v.name="scifi-glow",v.renderOrder=999;let l=new w0.Group;l.add(a),l.add(v),l.name="scifi-reveal-group",l.sectionKey=e,this.scene.add(l);let c=this.initialWaveDone?Wv:Gv,d=this.initialWaveDone?Vv:Nv,f={key:e,wireframeGroup:l,revealStartTime:performance.now(),phase:"wireframe",renderMeshRefs:o,globalShaderRestore:s,wireframeMs:c,revealMs:d};setTimeout(()=>{for(let m of this.getSectionRenderMeshes(e))m.hiddenByReveal||this.hideSectionRenderMeshes(e)},0),this.revealingSections.set(e,f)}createSectionBoundsWireframe(){let r=[[-8,-8,-8],[8,-8,-8],[-8,8,-8],[8,8,-8],[-8,-8,8],[8,-8,8],[-8,8,8],[8,8,8]],i=[[0,1],[1,3],[3,2],[2,0],[4,5],[5,7],[7,6],[6,4],[0,4],[1,5],[2,6],[3,7]],s=[];for(let[a,v]of i)s.push(...r[a],...r[v]);let o=new w0.BufferGeometry;return o.setAttribute("position",new w0.Float32BufferAttribute(s,3)),o}createWireframeGeometry(e){if(e.wireframePositions&&e.wireframePositions.length>0){let a=new w0.BufferGeometry;return a.setAttribute("position",new w0.Float32BufferAttribute(e.wireframePositions,3)),a}let t=e.positions,r=e.indices;if(!t?.length||!r?.length)return this.createSectionBoundsWireframe();let i=[],s=new Set;for(let a=0;a<r.length;a+=3){let v=r[a],l=r[a+1],c=r[a+2];this.addEdge(t,v,l,i,s),this.addEdge(t,l,c,i,s),this.addEdge(t,c,v,i,s)}let o=new w0.BufferGeometry;return o.setAttribute("position",new w0.Float32BufferAttribute(i,3)),o}addEdge(e,t,r,i,s){let o=Math.min(t,r),a=Math.max(t,r),v=`${o}-${a}`;s.has(v)||(s.add(v),i.push(e[t*3],e[t*3+1],e[t*3+2],e[r*3],e[r*3+1],e[r*3+2]))}update(e){if(!this.enabled||this.revealingSections.size===0)return;this.pulseTime+=e*.001;let t=performance.now(),r=.6+.4*Math.sin(this.pulseTime*4),i=[];for(let[s,o]of this.revealingSections){let a=t-o.revealStartTime;if(o.phase==="wireframe"){let v=o.wireframeGroup.children[0],l=o.wireframeGroup.children[1];if(v?.material){let c=v.material;c.opacity=r;let d=.85+.15*Math.sin(this.pulseTime*6+a*.002);c.color.setRGB(13/255*d,234/255*d,238/255*d)}if(l?.material){let c=l.material;c.opacity=r*.4}if(a>o.wireframeMs){o.phase="transitioning",o.renderMeshRefs=this.getSectionRenderMeshes(s);for(let c of o.renderMeshRefs)c.visible=!0,this.setMeshFadeOpacity(c,0)}}else if(o.phase==="transitioning"){let v=a-o.wireframeMs,l=Math.min(1,v/o.revealMs),c=1-(1-l)**3,d=o.wireframeGroup.children[0],f=o.wireframeGroup.children[1];if(d?.material){let m=d.material;m.opacity=1-c}if(f?.material){let m=f.material;m.opacity=(1-c)*.55}for(let m of o.renderMeshRefs)this.setMeshFadeOpacity(m,c);l>=1&&(o.phase="complete",i.push(o))}}for(let s of i)this.completeReveal(s)}completeReveal(e){this.revealingSections.delete(e.key),this.revealedChunks.add(e.key),this.revealTriggered&&this.revealingSections.size===0&&(this.initialRevealWaveSettled=!0);for(let t of e.renderMeshRefs)this.restoreMeshMaterial(t),t.visible=!0,delete t.hiddenByReveal;this.worldRenderer.chunkMeshManager.migrateDeferredShaderToGlobal(e.key),e.globalShaderRestore&&this.worldRenderer.chunkMeshManager.globalBlockBuffer?.addSection(e.key,e.globalShaderRestore.words,e.globalShaderRestore.count),this.disposeWireframeGroup(e.wireframeGroup)}disposeWireframeGroup(e){this.worldRenderer.sceneOrigin.removeAndUntrackAll(e);let t=[];e.traverse(r=>{t.push(r)});for(let r of t){let i=r;if(i.geometry&&i.geometry.dispose(),i.material){let s=i.material;if(Array.isArray(s))for(let o of s)o.dispose();else s&&typeof s.dispose=="function"&&s.dispose()}}e.clear()}reset(){for(let e of this.revealingSections.values())this.disposeWireframeGroup(e.wireframeGroup);this.pendingGeometries.clear(),this.revealingSections.clear(),this.revealedChunks.clear(),this.finishedChunkCount=0,this.revealTriggered=!1,this.initialWaveDone=!1,this.initialRevealWaveSettled=!1,this.revealStartTime=0,this.pulseTime=0}forceCompleteAll(){let e=[...this.revealingSections.values()];for(let t of e){t.renderMeshRefs=this.getSectionRenderMeshes(t.key);for(let r of t.renderMeshRefs)this.restoreMeshMaterial(r),r.visible=!0,delete r.hiddenByReveal;this.completeReveal(t)}}debugGetWireframeGroups(){let e=[];return this.scene.traverse(t=>{t.name==="scifi-reveal-group"&&e.push(t)}),e}debugForceCleanup(){let e=this.debugGetWireframeGroups();for(let t of e)this.disposeWireframeGroup(t);for(let t of this.revealingSections.values())this.disposeWireframeGroup(t.wireframeGroup);this.revealingSections.clear()}debugStatus(){let e=this.debugGetWireframeGroups(),t=new Set(this.revealingSections.keys()),r=e.filter(i=>!t.has(i.sectionKey));return{revealTriggered:this.revealTriggered,finishedChunkCount:this.finishedChunkCount,pendingGeometries:this.pendingGeometries.size,revealingSections:this.revealingSections.size,revealedChunks:this.revealedChunks.size,wireframeGroupsInScene:e.length,orphanedWireframeGroups:r.length,orphanedKeys:r.map(i=>i.sectionKey),sections:[...this.revealingSections.entries()].map(([i,s])=>({key:i,phase:s.phase,renderMeshCount:s.renderMeshRefs.length,wireframeInScene:s.wireframeGroup.parent!==null}))}}debugLog(){}},xa={id:"futuristicReveal",controller:tn,enabledDefault:!0};E();x();k();R();import*as M0 from"three";var jv=parseInt(M0.REVISION.replaceAll(/\D+/g,""),10),rn=class extends M0.ShaderMaterial{constructor(){super({uniforms:{time:{value:0},fade:{value:1}},vertexShader:`
|
|
21488
|
+
`,K0={textureSize:128,gravity:new r0.Vector3(0,-.005,0),friction:.998,defaultParticleSize:300,maxActiveFireworks:5},N5=n=>{let t=n*3;return{x:t,y:t+1,z:t+2}},W5=n=>{let t=n*4;return{r:t,g:t+1,b:t+2,a:t+3}},ft=(n=0,e=0)=>Math.floor(Math.random()*(n+1-e))+e,pv=(n,e,t,r)=>{n.save();let i=n.createRadialGradient(e,e,0,e,e,e);i.addColorStop(0,"rgba(255,255,255,1.0)"),i.addColorStop(.5,"rgba(255,255,255,0.5)"),i.addColorStop(1,"rgba(255,255,255,0)"),n.fillStyle=i,n.fillRect(0,0,t,r),n.restore()},gv=()=>{let n=K0.textureSize,e=V0(n,n),t=e.getContext("2d"),r=n/2;pv(t,r,e.width,e.height);let i=new r0.Texture(e);return i.needsUpdate=!0,i},bv=(n,e,t,r,i=K0.defaultParticleSize)=>{let s=new r0.BufferGeometry,o=[],a=[],v=[],l=[],c=[],d=Math.random()>.3?"single":"multiple",f=ft(100,20)*.01,m=()=>ft(100,1)*.01,g="red",b=Math.random();b>.66?g="red":b>.33?g="green":g="blue";for(let y=0;y<n;y++){let A=new r0.Vector3(0,0,0);if(o.push(A.x,A.y,A.z),a.push(e[y].x,e[y].y,e[y].z),t==="seed"){let C=e[y].y**2*.04;y===0&&(C*=1.1),l.push(C),c.push(C*.017),v.push(1,1,1,1)}else if(t==="trail"){let C=Math.random()*.1+.1;l.push(C),c.push(C*.017),v.push(1,1,1,1)}else{let C=ft(i,10)*.001;if(l.push(C),c.push(C*.017),d==="multiple")v.push(m(),m(),m(),1);else switch(g){case"red":v.push(f,.1,.1,1);break;case"green":v.push(.1,f,.1,1);break;case"blue":v.push(.1,.1,f,1);break}}}s.setAttribute("position",new r0.Float32BufferAttribute(o,3)),s.setAttribute("velocity",new r0.Float32BufferAttribute(a,3)),s.setAttribute("color",new r0.Float32BufferAttribute(v,4)),s.setAttribute("adjustSize",new r0.Float32BufferAttribute(l,1)),s.setAttribute("mass",new r0.Float32BufferAttribute(c,1));let w=new r0.RawShaderMaterial({uniforms:{size:{value:K0.textureSize},texture:{value:r}},transparent:!0,depthWrite:!1,blending:r0.AdditiveBlending,vertexShader:hv,fragmentShader:mv});return new r0.Points(s,w)},V5=class{constructor(e,t,r,i,s){u(this,"particleNum");u(this,"timerStartFading");u(this,"mesh");this.particleNum=e,this.timerStartFading=10,this.mesh=bv(e,t,r,i,s)}update(e){this.timerStartFading>0&&(this.timerStartFading-=.3);let t=this.mesh.geometry.attributes.position,r=this.mesh.geometry.attributes.velocity,i=this.mesh.geometry.attributes.color,s=this.mesh.geometry.attributes.mass,o=()=>Math.random()>.5?.98:.96,a=v=>Math.random()>.5?0:(1-v)*.1;for(let v=0;v<this.particleNum;v++){let{x:l,y:c,z:d}=N5(v);r.array[c]+=e.y-s.array[v],r.array[l]*=K0.friction,r.array[d]*=K0.friction,r.array[c]*=K0.friction,t.array[l]+=r.array[l],t.array[c]+=r.array[c],t.array[d]+=r.array[d];let{a:f}=W5(v);this.timerStartFading<=0&&(i.array[f]*=o()-a(i.array[f]),i.array[f]<.001&&(i.array[f]=0))}t.needsUpdate=!0,r.needsUpdate=!0,i.needsUpdate=!0}disposeAll(){this.mesh.geometry.dispose(),this.mesh.material.dispose()}},Li=class extends V5{constructor(e,t,r){super(e,t,"seed",r)}update(e){let t=this.mesh.geometry.attributes.position,r=this.mesh.geometry.attributes.velocity,i=this.mesh.geometry.attributes.color,s=this.mesh.geometry.attributes.mass,o=()=>Math.random()>.3?.99:.96,a=d=>Math.random()>.3?0:(1-d)*.1,v=()=>Math.random()>.5?.05:-.05,l=()=>Math.random()>.1,c=K0.friction*.98;for(let d=0;d<this.particleNum;d++){let{x:f,y:m,z:g}=N5(d);r.array[m]+=e.y-s.array[d],r.array[f]*=c,r.array[g]*=c,r.array[m]*=c,t.array[f]+=r.array[f],t.array[m]+=r.array[m],t.array[g]+=r.array[g],l()&&(t.array[f]+=v()),l()&&(t.array[g]+=v());let{a:b}=W5(d);i.array[b]*=o()-a(i.array[b]),i.array[b]<.001&&(i.array[b]=0)}t.needsUpdate=!0,r.needsUpdate=!0,i.needsUpdate=!0}},Ui=class extends V5{constructor(e,t,r){super(e,t,"trail",r)}update(e){let t=this.mesh.geometry.attributes.position,r=this.mesh.geometry.attributes.velocity,i=this.mesh.geometry.attributes.color,s=this.mesh.geometry.attributes.mass,o=()=>Math.random()>.3?.98:.95,a=()=>Math.random()>.5?.05:-.05,v=()=>Math.random()>.2;for(let l=0;l<this.particleNum;l++){let{x:c,y:d,z:f}=N5(l);r.array[d]+=e.y-s.array[l],r.array[c]*=K0.friction,r.array[f]*=K0.friction,r.array[d]*=K0.friction,t.array[c]+=r.array[c],t.array[d]+=r.array[d],t.array[f]+=r.array[f],v()&&(t.array[c]+=a()),v()&&(t.array[f]+=a());let{a:m}=W5(l);i.array[m]*=o(),i.array[m]<.001&&(i.array[m]=0)}t.needsUpdate=!0,r.needsUpdate=!0,i.needsUpdate=!0}},j5=class{constructor(e,t=K0.defaultParticleSize,r){u(this,"meshGroup");u(this,"isExplode");u(this,"petalsNum");u(this,"life");u(this,"seed");u(this,"flowerSizeRate");u(this,"flower");u(this,"texture");u(this,"particleSize");this.meshGroup=new r0.Group,this.isExplode=!1,this.texture=e,this.particleSize=t;let i=400,s=150;this.petalsNum=ft(i,s),this.life=150,this.seed=this.getSeed(r),this.meshGroup.add(this.seed.mesh),this.flowerSizeRate=r0.MathUtils.mapLinear(this.petalsNum,s,i,.4,.7)}getSeed(e){let r=[];for(let s=0;s<40;s++){let a=s===0?Math.random()*2.5+.9:Math.random()*2+.4,v=0;r.push(new r0.Vector3(0,a,v))}let i=new Li(40,r,this.texture);if(e)i.mesh.position.set(0,0,0);else{let s=Math.random()*80-40,o=-50,a=Math.random()*80-40;i.mesh.position.set(s,o,a)}return i}explode(e){this.isExplode=!0,this.flower=this.getFlower(e),this.meshGroup.add(this.flower.mesh),this.meshGroup.remove(this.seed.mesh),this.seed.disposeAll()}getFlower(e){let t=this.petalsNum,r=[],i;if(Math.random()>.5)for(let a=0;a<t;a++){i=ft(120,60)*.01;let v=r0.MathUtils.degToRad(Math.random()*180),l=r0.MathUtils.degToRad(Math.random()*360),c=Math.sin(v)*Math.cos(l)*i,d=Math.sin(v)*Math.sin(l)*i,f=Math.cos(v)*i,m=new r0.Vector3(c,d,f);m.multiplyScalar(this.flowerSizeRate),r.push(m)}else{let a=180/t,v=360*(Math.random()*20+1)/t,l=v,c=v;i=ft(120,60)*.01;for(let d=0;d<t;d++){let f=Math.sin(r0.MathUtils.degToRad(a*d)),m=Math.cos(r0.MathUtils.degToRad(a*d))*i,g=Math.cos(r0.MathUtils.degToRad(l*d))*f*i,b=Math.sin(r0.MathUtils.degToRad(c*d))*f*i,w=new r0.Vector3(g,b,m);w.multiplyScalar(this.flowerSizeRate),r.push(w)}}let o=new V5(t,r,"default",this.texture,this.particleSize);return o.mesh.position.set(e.x,e.y,e.z),o}update(e){this.isExplode?(this.flower.update(e),this.life>0&&(this.life-=1)):this.drawTail()}drawTail(){this.seed.update(K0.gravity);let e=this.seed.mesh.geometry.attributes.position,t=this.seed.mesh.geometry.attributes.velocity,r=0;for(let d=0,f=t.array.length;d<f;d++){let m=t.array[d];d%3===1&&m>0&&r++}if(!(r===0))return;let{x:s,y:o,z:a}=this.seed.mesh.position,v=new r0.Vector3(s,o,a),l=0,c;for(let d=0,f=e.array.length;d<f;d++){let m=e.array[d];d%3===1&&m>l&&(l=m,c=new r0.Vector3(e.array[d-1],m,e.array[d+2]))}c&&(v.add(c),this.explode(v))}},Yt=class extends j5{constructor(t,r=K0.defaultParticleSize,i){super(t,r,i);u(this,"tailMeshGroup");u(this,"tails");let s=150,o=100;this.petalsNum=ft(s,o),this.flowerSizeRate=r0.MathUtils.mapLinear(this.petalsNum,o,s,.4,.7),this.tailMeshGroup=new r0.Group,this.tails=[]}explode(t){this.isExplode=!0,this.flower=this.getFlower(t),this.tails=this.getTail(),this.meshGroup.add(this.flower.mesh),this.meshGroup.add(this.tailMeshGroup)}getTail(){let t=[],i=this.flower.mesh.geometry.attributes.color;for(let s=0;s<this.petalsNum;s++){let o=[];for(let S=0;S<20;S++)o.push(new r0.Vector3(0,0,0));let a=new Ui(20,o,this.texture),{r:v,g:l,b:c,a:d}=W5(s),f=i.array[v],m=i.array[l],g=i.array[c],b=i.array[d],w=a.mesh.geometry.attributes.position,y=a.mesh.geometry.attributes.color;for(let S=0;S<w.count;S++){let H=W5(S);y.array[H.r]=f,y.array[H.g]=m,y.array[H.b]=g,y.array[H.a]=b}let{x:A,y:C,z:M}=this.flower.mesh.position;a.mesh.position.set(A,C,M),t.push(a),this.tailMeshGroup.add(a.mesh)}return t}update(t){if(this.isExplode){this.flower.update(t);let r=this.flower.mesh.geometry.attributes.position;for(let i=0,s=this.tails.length;i<s;i++){let o=this.tails[i];o.update(t);let{x:a,y:v,z:l}=N5(i),c=new r0.Vector3(r.array[a],r.array[v],r.array[l]),d=o.mesh.geometry.attributes.position,f=o.mesh.geometry.attributes.velocity;for(let m=0;m<d.count;m++){let g=N5(m),b=new r0.Vector3,w=new r0.Vector3(d.array[g.x],d.array[g.y],d.array[g.z]),y=new r0.Vector3(f.array[g.x],f.array[g.y],f.array[g.z]);b.subVectors(c,w);let A=b.sub(y);A.normalize(),A.multiplyScalar(Math.random()*3e-4*this.life),f.array[g.x]+=A.x,f.array[g.y]+=A.y,f.array[g.z]+=A.z}f.needsUpdate=!0}this.life>0&&(this.life-=1.2)}else this.drawTail()}},X1=class{constructor(e,t,r){u(this,"fireworksInstances");u(this,"scene");u(this,"sceneOrigin");u(this,"texture");u(this,"particleSize");u(this,"maxFireworks");this.fireworksInstances=[],this.scene=e,this.sceneOrigin=t,this.texture=gv(),this.particleSize=r?.defaultParticleSize??K0.defaultParticleSize,this.maxFireworks=r?.maxActiveFireworks??K0.maxActiveFireworks}launchFirework(e){if(this.fireworksInstances.length>=this.maxFireworks)return;let t=e?.particleSize??this.particleSize,r=e?.position,i;e?.forceRich?i=new Yt(this.texture,t,r):e?.forceBasic?i=new j5(this.texture,t,r):i=Math.random()>.5?new j5(this.texture,t,r):new Yt(this.texture,t,r),this.fireworksInstances.push(i),r?(this.sceneOrigin.addAndTrack(i.meshGroup),i.meshGroup.position.set(r.x,r.y,r.z)):this.scene.add(i.meshGroup)}repositionAll(){}update(){let e=[];for(let t=this.fireworksInstances.length-1;t>=0;t--){let r=this.fireworksInstances[t];r.update(K0.gravity),r.isExplode&&e.push(t)}for(let t=0,r=e.length;t<r;t++){let i=e[t],s=this.fireworksInstances[i];if(s&&(s.meshGroup.remove(s.seed.mesh),s.seed.disposeAll(),s.life<=0)){if(this.sceneOrigin.removeAndUntrack(s.meshGroup),s instanceof Yt&&s.tailMeshGroup)for(let o of s.tails)o.disposeAll();s.flower?.disposeAll(),this.fireworksInstances.splice(i,1)}}}clear(){for(let e of this.fireworksInstances)if(this.sceneOrigin.removeAndUntrack(e.meshGroup),e.seed.disposeAll(),e.flower&&e.flower.disposeAll(),e instanceof Yt)for(let t of e.tails)t.disposeAll();this.fireworksInstances=[]}dispose(){this.clear(),this.texture.dispose()}};E();x();k();R();var Q3=Symbol("tracked-proxy"),yv=new Set(["add","addScalar","addScaledVector","addVectors","sub","subScalar","subVectors","multiply","multiplyScalar","multiplyVectors","divide","divideScalar","applyEuler","applyAxisAngle","applyMatrix3","applyMatrix4","applyNormalMatrix","applyQuaternion","negate","floor","ceil","round","roundToZero","min","max","clamp","clampLength","clampScalar","project","unproject","reflect","lerp","lerpVectors","cross","crossVectors","setFromMatrixPosition","setFromMatrixColumn","setFromMatrix3Column","setFromEuler","setFromSpherical","setFromSphericalCoords","setFromCylindrical","fromArray","fromBufferAttribute","setComponent","randomDirection","random"]),$1=class{constructor(e){u(this,"scene");u(this,"_x",0);u(this,"_y",0);u(this,"_z",0);u(this,"_tracked",new Set);u(this,"_worldCoords",new WeakMap);u(this,"_originalPositions",new WeakMap);u(this,"_trackOptions",new WeakMap);this.scene=e}get x(){return this._x}get y(){return this._y}get z(){return this._z}update(e,t,r){this._x=e,this._y=t,this._z=r;for(let i of this._tracked){let s=this._worldCoords.get(i);this._originalPositions.get(i).set(s.x-e,s.y-t,s.z-r),this._trackOptions.get(i)?.updateMatrix&&i.updateMatrix()}}track(e,t){let r=this._originalPositions.get(e)??e.position,i={x:0,y:0,z:0};this._originalPositions.set(e,r),this._worldCoords.set(e,i),t?this._trackOptions.set(e,t):this._trackOptions.delete(e);let s=this,o=t,a=new Proxy(r,{get(v,l,c){if(l===Q3)return i;if(l==="set")return(f,m,g)=>(i.x=f,i.y=m,i.z=g,v.set(f-s._x,m-s._y,g-s._z),o?.updateMatrix&&e.updateMatrix(),c);if(l==="copy")return f=>{let m=f[Q3],g=m?m.x:f.x,b=m?m.y:f.y,w=m?m.z:f.z;return i.x=g,i.y=b,i.z=w,v.set(g-s._x,b-s._y,w-s._z),o?.updateMatrix&&e.updateMatrix(),c};if(l==="setX")return f=>(i.x=f,v.x=f-s._x,o?.updateMatrix&&e.updateMatrix(),c);if(l==="setY")return f=>(i.y=f,v.y=f-s._y,o?.updateMatrix&&e.updateMatrix(),c);if(l==="setZ")return f=>(i.z=f,v.z=f-s._z,o?.updateMatrix&&e.updateMatrix(),c);if(typeof l=="string"&&yv.has(l))return()=>{throw new Error(`Cannot call position.${l}() on a tracked object. Use position.set(x, y, z) instead.`)};let d=v[l];return typeof d=="function"?d.bind(v):d},set(v,l,c){return l==="x"?(i.x=c,v.x=c-s._x,o?.updateMatrix&&e.updateMatrix(),!0):l==="y"?(i.y=c,v.y=c-s._y,o?.updateMatrix&&e.updateMatrix(),!0):l==="z"?(i.z=c,v.z=c-s._z,o?.updateMatrix&&e.updateMatrix(),!0):(v[l]=c,!0)}});Object.defineProperty(e,"position",{value:a,configurable:!0,enumerable:!0}),this._tracked.add(e)}untrack(e){let t=this._originalPositions.get(e);t&&(Object.defineProperty(e,"position",{value:t,configurable:!0,enumerable:!0}),this._tracked.delete(e),this._worldCoords.delete(e),this._originalPositions.delete(e),this._trackOptions.delete(e))}addAndTrack(e,t){this.track(e,t),this.scene.add(e)}removeAndUntrack(e){this.untrack(e),e.removeFromParent()}removeAndUntrackAll(e){e.traverse(t=>{this.untrack(t)}),e.removeFromParent()}getWorldPosition(e){let t=this._worldCoords.get(e);return t?{x:t.x,y:t.y,z:t.z}:void 0}clear(){for(let e of this._tracked)this.untrack(e)}get trackedCount(){return this._tracked.size}toSceneX(e){return e-this._x}toSceneY(e){return e-this._y}toSceneZ(e){return e-this._z}toWorldX(e){return e+this._x}toWorldY(e){return e+this._y}toWorldZ(e){return e+this._z}};Yi();E();x();k();R();Qt();mt();Vi();import Ov from"prismarine-chat";import*as $ from"three";import*as cr from"prismarine-nbt";import{Vec3 as Ki}from"vec3";E();x();k();R();mt();Qt();import*as ue from"three";var Mv=2e6,Qi=X3(),vr=class{constructor(e,t){u(this,"mesh");u(this,"capacityFaces");u(this,"w0");u(this,"w1");u(this,"w2");u(this,"w3");u(this,"sectionSlots",new Map);u(this,"freeList",[]);u(this,"highWatermark",0);u(this,"dirtyMin",1/0);u(this,"dirtyMax",-1);this.capacityFaces=Mv,this.w0=new Uint32Array(this.capacityFaces),this.w1=new Uint32Array(this.capacityFaces),this.w2=new Uint32Array(this.capacityFaces),this.w3=new Uint32Array(this.capacityFaces);let r=new ue.InstancedBufferGeometry,i=new Float32Array(tr*3);r.setAttribute("position",new ue.BufferAttribute(i,3));let s=o=>{let a=new ue.InstancedBufferAttribute(o,1);return a.setUsage(ue.DynamicDrawUsage),a};r.setAttribute("a_w0",s(this.w0)),r.setAttribute("a_w1",s(this.w1)),r.setAttribute("a_w2",s(this.w2)),r.setAttribute("a_w3",s(this.w3)),r.instanceCount=0,this.mesh=new ue.Mesh(r,e),this.mesh.name="globalShaderCubes",this.mesh.frustumCulled=!1,this.mesh.matrixAutoUpdate=!1,this.mesh.matrix.identity(),this.mesh.position.set(0,0,0),t.add(this.mesh)}addSection(e,t,r){if(r<=0){this.removeSection(e);return}this.sectionSlots.has(e)&&this.removeSection(e),r>this.capacityFaces&&this.growCapacity(r);let i=this.takeFreeSlot(r);i||(this.highWatermark+r>this.capacityFaces&&this.growCapacity(this.highWatermark+r),i={start:this.highWatermark,count:r},this.highWatermark+=r);let s=4;for(let o=0;o<r;o++){let a=i.start+o,v=o*s;this.w0[a]=t[v],this.w1[a]=t[v+1],this.w2[a]=t[v+2],this.w3[a]=t[v+3]}this.sectionSlots.set(e,i),this.markDirty(i.start,i.start+r-1),this.mesh.geometry.instanceCount=this.highWatermark}hasSection(e){return this.sectionSlots.has(e)}takeSectionData(e){let t=this.sectionSlots.get(e);if(!t)return;let r=4,i=new Uint32Array(t.count*r);for(let s=0;s<t.count;s++){let o=t.start+s,a=s*r;i[a]=this.w0[o],i[a+1]=this.w1[o],i[a+2]=this.w2[o],i[a+3]=this.w3[o]}return this.removeSection(e),{words:i,count:t.count}}removeSection(e){let t=this.sectionSlots.get(e);if(t){for(let r=t.start;r<t.start+t.count;r++)this.w0[r]=0,this.w1[r]=0,this.w2[r]=Qi,this.w3[r]=0;this.markDirty(t.start,t.start+t.count-1),this.sectionSlots.delete(e),this.insertFreeSlot(t),this.shrinkHighWatermark(),this.mesh.geometry.instanceCount=this.highWatermark}}uploadDirtyRange(){if(this.dirtyMin>this.dirtyMax)return;let e=this.dirtyMin,t=this.dirtyMax-this.dirtyMin+1,r=this.mesh.geometry;for(let i of["a_w0","a_w1","a_w2","a_w3"]){let s=r.getAttribute(i);s.updateRange.offset=e,s.updateRange.count=t,s.needsUpdate=!0}this.dirtyMin=1/0,this.dirtyMax=-1}setCameraOrigin(e,t,r){let i=Math.floor(e),s=Math.floor(t),o=Math.floor(r),a=this.mesh.material.uniforms.u_cameraOrigin;a?.value?.set&&a.value.set(i,s,o);let v=this.mesh.material.uniforms.u_cameraOriginFrac;v?.value?.set&&v.value.set(e-i,t-s,r-o)}reset(){this.sectionSlots.clear(),this.freeList.length=0,this.highWatermark=0,this.dirtyMin=1/0,this.dirtyMax=-1,this.w0.fill(0),this.w1.fill(0),this.w2.fill(Qi),this.w3.fill(0),this.mesh.geometry.instanceCount=0}dispose(){this.mesh.parent?.remove(this.mesh),this.mesh.geometry.dispose(),this.reset()}markDirty(e,t){e<this.dirtyMin&&(this.dirtyMin=e),t>this.dirtyMax&&(this.dirtyMax=t)}takeFreeSlot(e){for(let t=0;t<this.freeList.length;t++){let r=this.freeList[t];if(r.count>=e){if(this.freeList.splice(t,1),r.count===e)return r;let i={start:r.start,count:e};return this.insertFreeSlot({start:r.start+e,count:r.count-e}),i}}}insertFreeSlot(e){this.freeList.push(e),this.freeList.sort((t,r)=>t.start-r.start),this.mergeFreeList()}mergeFreeList(){if(this.freeList.length<2)return;let e=[],t=this.freeList[0];for(let r=1;r<this.freeList.length;r++){let i=this.freeList[r];t.start+t.count===i.start?t={start:t.start,count:t.count+i.count}:(e.push(t),t=i)}e.push(t),this.freeList=e}shrinkHighWatermark(){for(;this.highWatermark>0;){let e=this.highWatermark-1,t=this.freeList.find(i=>i.start<=e&&i.start+i.count>e);if(!t||t.start+t.count!==this.highWatermark)break;this.highWatermark=t.start;let r=this.freeList.indexOf(t);this.freeList.splice(r,1)}}growCapacity(e){let t=this.capacityFaces;for(;t<e;)t*=2;let r=new Uint32Array(t),i=new Uint32Array(t),s=new Uint32Array(t),o=new Uint32Array(t);r.set(this.w0),i.set(this.w1),s.set(this.w2),o.set(this.w3),s.fill(Qi,this.w0.length),this.w0=r,this.w1=i,this.w2=s,this.w3=o,this.capacityFaces=t;let a=this.mesh.geometry,v=(l,c)=>{let d=a.getAttribute(c);d&&(a.deleteAttribute(c),"dispose"in d&&typeof d.dispose=="function"&&d.dispose());let f=new ue.InstancedBufferAttribute(l,1);f.setUsage(ue.DynamicDrawUsage),a.setAttribute(c,f)};v(this.w0,"a_w0"),v(this.w1,"a_w1"),v(this.w2,"a_w2"),v(this.w3,"a_w3"),this.dirtyMin=0,this.dirtyMax=this.highWatermark-1}};E();x();k();R();Qt();mt();function oa(n,e,t,r,i){if(e<=0)return;let s=t-8,o=r-8,a=i-8,v=sr,l=16,c=16,d=16,f=-1,m=-1,g=-1;for(let S=0;S<e;S++){let H=n[S*v],B=H&(1<<ht.LX_BITS)-1,I=H>>ht.LY_SHIFT&(1<<ht.LY_BITS)-1,G=H>>ht.LZ_SHIFT&(1<<ht.LZ_BITS)-1;B<l&&(l=B),I<c&&(c=I),G<d&&(d=G),B>f&&(f=B),I>m&&(m=I),G>g&&(g=G)}if(f<0)return;let b=s+l,w=o+c,y=a+d,A=s+f+1,C=o+m+1,M=a+g+1;return{minX:b,minY:w,minZ:y,maxX:A,maxY:C,maxZ:M,cx:(b+A)*.5,cy:(w+C)*.5,cz:(y+M)*.5}}function Sv(n,e,t,r,i,s,o,a,v){return n>=r&&n<=o&&e>=i&&e<=a&&t>=s&&t<=v}function aa(n,e,t,r,i,s,o,a,v,l,c,d,f){if(Sv(n,e,t,o,a,v,l,c,d))return;let m=0,g=f;if(Math.abs(r)<1e-8){if(n<o||n>l)return}else{let b=1/r,w=(o-n)*b,y=(l-n)*b;if(w>y){let A=w;w=y,y=A}if(m=Math.max(m,w),g=Math.min(g,y),m>g)return}if(Math.abs(i)<1e-8){if(e<a||e>c)return}else{let b=1/i,w=(a-e)*b,y=(c-e)*b;if(w>y){let A=w;w=y,y=A}if(m=Math.max(m,w),g=Math.min(g,y),m>g)return}if(Math.abs(s)<1e-8){if(t<v||t>d)return}else{let b=1/s,w=(v-t)*b,y=(d-t)*b;if(w>y){let A=w;w=y,y=A}if(m=Math.max(m,w),g=Math.min(g,y),m>g)return}return m<=g&&m>=0?m:void 0}E();x();k();R();import*as X0 from"three";var va=20,la=40,Cv={white_banner:15,orange_banner:14,magenta_banner:13,light_blue_banner:12,yellow_banner:11,lime_banner:10,pink_banner:9,gray_banner:8,light_gray_banner:7,cyan_banner:6,purple_banner:5,blue_banner:4,brown_banner:3,green_banner:2,red_banner:1,black_banner:0},ca={0:"#1d1d21",1:"#b02e26",2:"#5e7c16",3:"#835432",4:"#3c44aa",5:"#8932b8",6:"#169c9c",7:"#9d9d97",8:"#474f52",9:"#f38baa",10:"#80c71f",11:"#fed83d",12:"#3ab3da",13:"#c74ebd",14:"#f9801d",15:"#f9fffe"};function Bv(n){let e=n.replace("_wall_banner","_banner");return Cv[e]??15}var Pv=(n,e,t,r,i,s,o)=>{switch(n.fillStyle=t,e){case"bs":n.fillRect(r,i,s,o);break;case"ls":n.fillRect(r,i,s/3,o);break;case"rs":n.fillRect(r+s*2/3,i,s/3,o);break;case"ts":n.fillRect(r,i,s,o/3);break;case"ms":n.fillRect(r,i+o/3,s,o/3);break;case"drs":n.fillRect(r,i,s/2,o/2);break;case"dls":n.fillRect(r+s/2,i,s/2,o/2);break;case"ss":for(let a=0;a<s;a+=2)n.fillRect(r+a,i,1,o);break;case"cr":n.fillRect(r,i+o/3,s,o/3),n.fillRect(r+s/3,i,s/3,o);break;case"sc":n.fillRect(r,i+o/2-1,s,2),n.fillRect(r+s/2-1,i,2,o);break;default:n.fillRect(r,i,s,o)}};function Iv(n,e){if(!e||e.length===0)return`banner_${n}_empty`;let t=e.map(r=>`${r.Pattern??"bs"}_${r.Color??0}`).join(",");return`banner_${n}_${t}`}var Hv=(n,e,t=(r,i)=>V0(r,i))=>{let i=t(va*1,la*1),s=i.getContext("2d");if(s){if(s.imageSmoothingEnabled=!1,e?.Patterns&&e.Patterns.length>0)for(let o of e.Patterns){let a=o.Color??0,v=o.Pattern??"bs",l=ca[a]||ca[0];Pv(s,v,l,0,0,va*1,la*1)}return i}},lr=new Map;function da(n,e,t){let r=Bv(e),i=Iv(r,t?.Patterns),s=lr.get(i);if(s)return s.refCount++,s.texture;let o=Hv(r,t);if(!o)return;let a=new X0.Texture(o);return a.magFilter=X0.NearestFilter,a.minFilter=X0.NearestFilter,a.needsUpdate=!0,lr.set(i,{texture:a,refCount:1}),a}function ua(n){for(let[e,t]of lr.entries())if(t.texture===n){t.refCount--,t.refCount<=0&&(t.texture.dispose(),lr.delete(e));return}}function fa(n,e,t,r){let a,v,l;t?(a=(-14.6+13.4)/2/16-.5,v=1-14.75/16-.5,l=1/2):(a=(1.4+29.4)/2/16,v=1-7.25/16-.5,l=0);let c=new X0.Mesh(new X0.PlaneGeometry(.85,1.75),new X0.MeshBasicMaterial({map:r,transparent:!0}));c.renderOrder=999;let d=.5/16,f=.25/16;t?c.position.set(0,a,v+f+.004):c.position.set(0,a,v+d/2+.004);let m=new X0.Group;return m.rotation.set(0,-X0.MathUtils.degToRad(e*(t?90:45/2)),0),m.add(c),m.bannerTexture=r,m.position.set(n.x+.5,n.y+l,n.z+.5),m}var pt=class pt{constructor(e,t,r,i,s=3){this.worldRenderer=e;this.scene=t;this.material=r;this.worldHeight=i;u(this,"meshPool",[]);u(this,"activeSections",new Map);u(this,"sectionObjects",{});u(this,"waitingChunksToDisplay",{});u(this,"pendingNearReveal",new Map);u(this,"nearRevealTimers",new Map);u(this,"nearRevealGraceTimers",new Map);u(this,"poolSize");u(this,"maxPoolSize");u(this,"minPoolSize");u(this,"signHeadsRenderer");u(this,"chunkBoxMaterial",new $.MeshBasicMaterial({color:0,transparent:!0,opacity:0}));u(this,"cubeShaderMaterial",null);u(this,"globalBlockBuffer",null);u(this,"shaderSectionRaycastBoxes",new Map);u(this,"hits",0);u(this,"misses",0);u(this,"bypassPooling",!1);u(this,"renderTimes",[]);u(this,"maxRenderTimeSamples",30);u(this,"_performanceOverrideDistance");u(this,"lastPerformanceCheck",0);u(this,"performanceCheckInterval",2e3);this.updateViewDistance(s),this.signHeadsRenderer=new Ji(e),this.initializePool()}get performanceOverrideDistance(){return this._performanceOverrideDistance??0}set performanceOverrideDistance(e){this._performanceOverrideDistance=e,this.updateSectionsVisibility()}initializePool(){for(let e=0;e<this.poolSize;e++){let t=new $.BufferGeometry,r=new $.Mesh(t,this.material);r.visible=!1,r.matrixAutoUpdate=!1,r.name="pooled-section-mesh";let i={mesh:r,inUse:!1,lastUsedTime:0};this.meshPool.push(i)}}sectionHasRenderableContent(e){return e.positions.length>0?!0:this.isShaderCubesGpuEnabled()?(e.shaderCubes?.count??0)>0:!1}isShaderCubesGpuEnabled(){return this.worldRenderer.shaderCubeBlocksEnabled()}syncCubeShaderUniforms(){if(!this.isShaderCubesGpuEnabled())return;let e=this.cubeShaderMaterial??this.getCubeShaderMaterial();if(!e)return;let t=this.material.map??null;e.uniforms.u_atlas.value=t;let{tintPalette:r}=or();r.isReady()||r.createTexture(),e.uniforms.u_tintPalette.value=r.getTexture(),e.uniforms.u_debugMode.value=this.worldRenderer.worldRendererConfig.shaderCubeDebugMode??0,e.needsUpdate=!0}getCubeShaderMaterial(){return this.isShaderCubesGpuEnabled()?(this.cubeShaderMaterial||(this.cubeShaderMaterial=er(),this.syncCubeShaderUniforms()),this.cubeShaderMaterial):null}getGlobalBlockBuffer(){let e=this.getCubeShaderMaterial();return e?(this.globalBlockBuffer||(this.globalBlockBuffer=new vr(e,this.scene)),this.globalBlockBuffer):null}shouldDeferShaderToPerSection(e){let t=this.worldRenderer.getModule("futuristicReveal");return t?t.isInInitialRevealCampaign?.()?!0:t.shouldUseRevealEffect?.(e)===!0:!1}migrateDeferredShaderToGlobal(e){let t=this.sectionObjects[e];if(!t?.deferredShaderCubes)return;let{words:r,count:i}=t.deferredShaderCubes,s=t.worldX,o=t.worldY,a=t.worldZ;s!==void 0&&o!==void 0&&a!==void 0&&this.registerShaderSectionRaycastBox(e,r,i,s,o,a),this.getGlobalBlockBuffer()?.addSection(e,r,i);let l=t.mesh===t.shaderMesh;t.shaderMesh&&(Wi(t.shaderMesh),t.remove(t.shaderMesh),t.shaderMesh=void 0),delete t.deferredShaderCubes,l&&(t.mesh=void 0)}registerShaderSectionRaycastBox(e,t,r,i,s,o){let a=oa(t,r,i,s,o);a?this.shaderSectionRaycastBoxes.set(e,a):this.shaderSectionRaycastBoxes.delete(e)}unregisterShaderSectionRaycastBox(e){this.shaderSectionRaycastBoxes.delete(e)}raycastShaderSectionAABBs(e,t,r,i=80){let s=e.x,o=e.y,a=e.z,v=t.x,l=t.y,c=t.z,d=i*i,f=r,m=!1;for(let[g,b]of this.shaderSectionRaycastBoxes){let w=this.sectionObjects[g];if(w&&!w.visible)continue;let y=b.cx-s,A=b.cy-o,C=b.cz-a;if(y*y+A*A+C*C>d)continue;let M=aa(s,o,a,v,l,c,b.minX,b.minY,b.minZ,b.maxX,b.maxY,b.maxZ,f);M!==void 0&&M<f&&(f=M,m=!0)}return m?f:void 0}updateSection(e,t){let r=t.positions.length>0,i=t.shaderCubes,s=this.isShaderCubesGpuEnabled()&&(i?.count??0)>0;if(!r&&!s)return this.releaseSection(e),null;let o=this.sectionObjects[e];o&&this.cleanupSection(e),r||this.releasePooledMesh(e);let a;if(r){let w=this.activeSections.get(e);if(!w){if(w=this.acquireMesh(),!w)return null;this.activeSections.set(e,w),w.sectionKey=e}let{mesh:y}=w;this.updateGeometryAttribute(y.geometry,"position",t.positions,3),this.updateGeometryAttribute(y.geometry,"normal",t.normals,3),this.updateGeometryAttribute(y.geometry,"color",t.colors,3),this.updateGeometryAttribute(y.geometry,"uv",t.uvs,2),y.geometry.index=new $.BufferAttribute(t.indices,1),y.geometry.boundingBox=new $.Box3(new $.Vector3(-8,-8,-8),new $.Vector3(8,8,8)),y.geometry.boundingSphere=new $.Sphere(new $.Vector3(0,0,0),Math.sqrt(3*8**2)),this.worldRenderer.sceneOrigin.track(y,{updateMatrix:!0}),y.position.set(t.sx,t.sy,t.sz),y.updateMatrix(),y.visible=!0,y.name="mesh",w.lastUsedTime=performance.now(),a=y}let v=s?this.getCubeShaderMaterial():null,l,c=s&&this.shouldDeferShaderToPerSection(e);s&&i&&(c&&v?(l=ar(i,v),l.visible=!0):this.getGlobalBlockBuffer()?.addSection(e,i.words,i.count)),o=new $.Group,a&&(o.add(a),o.mesh=a),l&&(o.add(l),o.shaderMesh=l,i&&(o.deferredShaderCubes={words:i.words,count:i.count}),o.mesh||(o.mesh=l)),s&&i&&this.registerShaderSectionRaycastBox(e,i.words,i.count,t.sx,t.sy,t.sz);let d=0;r&&(d+=t.positions.length/3/4),s&&i&&(d+=i.count),o.tilesCount=d,o.blocksCount=t.blocksCount,o.worldX=t.sx,o.worldY=t.sy,o.worldZ=t.sz,o.sectionKey=e,o.name="chunk";try{if(Object.keys(t.signs).length>0){let w=new $.Group;w.name="signs";for(let[y,{isWall:A,isHanging:C,rotation:M}]of Object.entries(t.signs)){let S=this.worldRenderer.blockEntities[y];if(!S)continue;let[H,B,I]=y.split(","),G=this.signHeadsRenderer.renderSign(new Ki(+H,+B,+I),M,A,C,cr.simplify(S));G&&w.add(G)}o.add(w),o.signsContainer=w}if(Object.keys(t.heads).length>0){let w=new $.Group;w.name="heads";for(let[y,{isWall:A,rotation:C}]of Object.entries(t.heads)){let M=this.worldRenderer.blockEntities[y];if(!M)continue;let[S,H,B]=y.split(","),I=this.signHeadsRenderer.renderHead(new Ki(+S,+H,+B),C,A,cr.simplify(M));I&&w.add(I)}o.add(w),o.headsContainer=w}if(Object.keys(t.banners).length>0){let w=new $.Group;w.name="banners",o.bannersContainer=w,o.add(w);for(let[y,{isWall:A,rotation:C,blockName:M}]of Object.entries(t.banners)){let S=this.worldRenderer.blockEntities[y];if(!S)continue;let[H,B,I]=y.split(","),G=da(this.worldRenderer,M,cr.simplify(S));if(!G)continue;let O=fa(new Ki(+H,+B,+I),C,A,G),{x:j,y:J,z:X}=O.position;this.worldRenderer.sceneOrigin.track(O),O.position.set(j,J,X),w.add(O)}}}catch{}this.sectionObjects[e]=o,this.scene.add(o),o.matrixAutoUpdate=!1,this.worldRenderer.displayOptions?.inWorldRenderingConfig?.showChunkBorders&&this.updateBoxHelper(e,!0);let f=e.split(","),m=`${f[0]},${f[2]}`,g=!!this.worldRenderer.displayOptions?.inWorldRenderingConfig?._renderByChunks,b=!!this.worldRenderer.worldRendererConfig?.wasmMesher;if((g||b)&&!this.worldRenderer.finishedChunks[m]){o.visible=!1,o._waitingForChunkDisplay=!0;let w=this.waitingChunksToDisplay[m]??(this.waitingChunksToDisplay[m]=[]);w.includes(e)||w.push(e)}return o}finishChunkDisplay(e){if(!this.waitingChunksToDisplay[e]){this.tryRevealPending();return}if(this.isWasmGateActive()&&this.isBlockedByNearer(e,0)){this.pendingNearReveal.set(e,Date.now()),this.armNearRevealTimer(e),this.armExpectedGraceTimer(e);return}this.flushChunkDisplay(e),this.tryRevealPending()}flushChunkDisplay(e){let t=this.waitingChunksToDisplay[e];if(this.pendingNearReveal.delete(e),this.clearNearRevealTimer(e),this.clearExpectedGraceTimer(e),!!t){for(let r of t){let i=this.sectionObjects[r];i&&(i._waitingForChunkDisplay=!1,i.visible=!0)}delete this.waitingChunksToDisplay[e]}}tryRevealPending(){if(this.pendingNearReveal.size===0)return;let e=Date.now();for(let[t,r]of[...this.pendingNearReveal])this.isBlockedByNearer(t,e-r)||this.flushChunkDisplay(t)}onChunkRemovedFromGate(e){this.pendingNearReveal.delete(e),this.clearNearRevealTimer(e),this.clearExpectedGraceTimer(e),delete this.waitingChunksToDisplay[e],this.tryRevealPending()}isWasmGateActive(){return!!this.worldRenderer.worldRendererConfig?.wasmMesher}isBlockedByNearer(e,t){let r=this.worldRenderer.viewerChunkPosition;if(!r)return!1;let i=e.split(",");if(i.length!==2)return!1;let s=Number(i[0]),o=Number(i[1]),a=Math.floor(r.x/16),v=Math.floor(r.z/16),l=(s>>4)-a,c=(o>>4)-v,d=l*l+c*c;if(d===0)return!1;let f=this.worldRenderer.finishedChunks,m=this.worldRenderer.loadedChunks,g=this.worldRenderer.viewDistance;if(t<pt.EXPECTED_NEAR_GRACE_MS&&g>0){let w=g*g,y=Math.min(g,Math.ceil(Math.sqrt(Math.max(0,d-1))));for(let A=-y;A<=y;A++)for(let C=-y;C<=y;C++){let M=A*A+C*C;if(M>=d||M>w)continue;let S=a+A<<4,H=v+C<<4,B=`${S},${H}`;if(B!==e&&!f[B])return!0}return!1}for(let w in m){if(w===e||f[w])continue;let y=w.split(",");if(y.length!==2)continue;let A=(Number(y[0])>>4)-a,C=(Number(y[1])>>4)-v;if(A*A+C*C<d)return!0}return!1}armNearRevealTimer(e){if(this.nearRevealTimers.has(e))return;let t=setTimeout(()=>{this.nearRevealTimers.delete(e),this.pendingNearReveal.has(e)&&(this.flushChunkDisplay(e),this.tryRevealPending())},pt.NEAR_REVEAL_TIMEOUT_MS);this.nearRevealTimers.set(e,t)}clearNearRevealTimer(e){let t=this.nearRevealTimers.get(e);t&&(clearTimeout(t),this.nearRevealTimers.delete(e))}armExpectedGraceTimer(e){if(this.nearRevealGraceTimers.has(e))return;let t=setTimeout(()=>{this.nearRevealGraceTimers.delete(e),this.pendingNearReveal.has(e)&&this.tryRevealPending()},pt.EXPECTED_NEAR_GRACE_MS+50);this.nearRevealGraceTimers.set(e,t)}clearExpectedGraceTimer(e){let t=this.nearRevealGraceTimers.get(e);t&&(clearTimeout(t),this.nearRevealGraceTimers.delete(e))}cleanupSection(e){let t=this.sectionObjects[e];if(t){if(t._waitingForChunkDisplay){let r=e.split(","),i=`${r[0]},${r[2]}`,s=this.waitingChunksToDisplay[i];if(s){let o=s.indexOf(e);o!==-1&&s.splice(o,1),s.length===0&&delete this.waitingChunksToDisplay[i]}}if(t.bannersContainer&&(t.bannersContainer.traverse(r=>{r.bannerTexture&&ua(r.bannerTexture)}),this.disposeContainer(t.bannersContainer)),this.globalBlockBuffer?.removeSection(e),this.unregisterShaderSectionRaycastBox(e),t.shaderMesh&&(Wi(t.shaderMesh),t.shaderMesh=void 0),delete t.deferredShaderCubes,t.signsContainer&&this.disposeContainer(t.signsContainer),t.headsContainer&&this.disposeContainer(t.headsContainer),this.worldRenderer.sceneOrigin.removeAndUntrackAll(t),this.scene.remove(t),t.boxHelper){this.worldRenderer.sceneOrigin.removeAndUntrack(t.boxHelper),this.scene.remove(t.boxHelper),t.boxHelper.geometry.dispose();let r=t.boxHelper.material;if(Array.isArray(r))for(let i of r)i.dispose();else r.dispose();t.boxHelper=void 0}delete this.sectionObjects[e]}}releasePooledMesh(e){let t=this.activeSections.get(e);t&&(t.mesh.visible=!1,t.inUse=!1,t.sectionKey=void 0,t.lastUsedTime=0,this.clearGeometry(t.mesh.geometry),this.activeSections.delete(e),this.cleanupExcessMeshes())}releaseSection(e){this.cleanupSection(e);let t=this.activeSections.get(e);return t?(t.mesh.visible=!1,t.inUse=!1,t.sectionKey=void 0,t.lastUsedTime=0,this.clearGeometry(t.mesh.geometry),this.activeSections.delete(e),this.cleanupExcessMeshes(),!0):!1}getSectionObject(e){return this.sectionObjects[e]}updateBoxHelper(e,t,r=this.chunkBoxMaterial){let i=this.sectionObjects[e];if(i?.mesh)if(t){if(!i.boxHelper){let s=new $.Mesh(new $.BoxGeometry(16,16,16),r),o=new $.BoxHelper(s,16776960);o.name="helper";let a=i.worldX??0,v=i.worldY??0,l=i.worldZ??0;this.worldRenderer.sceneOrigin.track(o,{updateMatrix:!0}),o.position.set(a,v,l),o.updateMatrix(),this.scene.add(o),i.boxHelper=o}i.boxHelper.visible=!0}else i.boxHelper&&(i.boxHelper.visible=!1)}updateAllBoxHelpers(e){for(let t of Object.keys(this.sectionObjects))this.updateBoxHelper(t,e)}cleanSignChunkTextures(e,t){this.signHeadsRenderer.cleanChunkTextures(e,t)}getSectionMesh(e){return this.activeSections.get(e)?.mesh}hasSection(e){return this.activeSections.has(e)}updateViewDistance(e){let t=(e*2+1)**2,r=this.worldHeight/16,i=5;if(this.minPoolSize=Math.floor(t*i),this.maxPoolSize=Math.floor(t*r)+1,this.poolSize??(this.poolSize=this.minPoolSize),this.minPoolSize>this.poolSize){let s=Math.min(this.minPoolSize,this.maxPoolSize);this.expandPool(s)}}getStats(){let e=this.meshPool.filter(i=>!i.inUse).length,t=this.hits+this.misses>0?(this.hits/(this.hits+this.misses)*100).toFixed(1):"0",r=this.getEstimatedMemoryUsage();return{poolSize:this.poolSize,activeCount:this.activeSections.size,freeCount:e,hitRate:`${t}%`,hits:this.hits,misses:this.misses,memoryUsage:r}}getTotalTiles(){return Object.values(this.sectionObjects).reduce((e,t)=>e+(t.tilesCount||0),0)}getTotalBlocks(){return Object.values(this.sectionObjects).reduce((e,t)=>e+(t.blocksCount||0),0)}getEstimatedMemoryUsage(){let e=0,t=0,r=0,i=0,s=0,o=0,a=0,v=this.globalBlockBuffer?.mesh.geometry;if(v)for(let c of["a_w0","a_w1","a_w2","a_w3"]){let d=v.getAttribute(c);if(d){let f=d.array.byteLength;a+=f,e+=f}}for(let c of Object.values(this.sectionObjects)){let d=c.shaderMesh?.geometry;if(d)for(let f of["a_w0","a_w1","a_w2","a_w3"]){let m=d.getAttribute(f);if(m){let g=m.array.byteLength;a+=g,e+=g}}}for(let c of this.meshPool)if(c.inUse&&c.mesh.geometry){let{geometry:d}=c.mesh,f=d.getAttribute("position");if(f){let w=f.array.byteLength;t+=w,e+=w}let m=d.getAttribute("normal");if(m){let w=m.array.byteLength;r+=w,e+=w}let g=d.getAttribute("color");if(g){let w=g.array.byteLength;i+=w,e+=w}let b=d.getAttribute("uv");if(b){let w=b.array.byteLength;s+=w,e+=w}if(d.index){let w=d.index.array.byteLength;o+=w,e+=w}}return{total:`${(e/(1024*1024)).toFixed(2)} MB`,breakdown:{position:`${(t/(1024*1024)).toFixed(2)} MB`,normal:`${(r/(1024*1024)).toFixed(2)} MB`,color:`${(i/(1024*1024)).toFixed(2)} MB`,uv:`${(s/(1024*1024)).toFixed(2)} MB`,index:`${(o/(1024*1024)).toFixed(2)} MB`,shaderInstances:`${(a/(1024*1024)).toFixed(2)} MB`}}}dispose(){let e=[...this.activeSections.keys()];for(let t of e)this.releaseSection(t);this.signHeadsRenderer.dispose();for(let t of this.meshPool)t.mesh.geometry.dispose();this.meshPool.length=0,this.activeSections.clear(),this.chunkBoxMaterial.dispose(),this.shaderSectionRaycastBoxes.clear(),this.globalBlockBuffer?.dispose(),this.globalBlockBuffer=null,this.cubeShaderMaterial?.dispose(),this.cubeShaderMaterial=null,this.pendingNearReveal.clear();for(let t of this.nearRevealTimers.values())clearTimeout(t);this.nearRevealTimers.clear();for(let t of this.nearRevealGraceTimers.values())clearTimeout(t);this.nearRevealGraceTimers.clear()}acquireMesh(){if(this.bypassPooling){let t={mesh:new $.Mesh(new $.BufferGeometry,this.material),inUse:!0,lastUsedTime:performance.now()};return this.meshPool.push(t),this.poolSize++,t}for(let t of this.meshPool)if(!t.inUse)return t.inUse=!0,t.lastUsedTime=performance.now(),this.hits++,t;this.misses++;let e=Math.min(this.poolSize+16,this.maxPoolSize);e<=this.meshPool.length&&(e=this.meshPool.length+8,this.maxPoolSize=e),this.expandPool(e);for(let t=this.meshPool.length-1;t>=0;t--){let r=this.meshPool[t];if(!r.inUse)return r.inUse=!0,r.lastUsedTime=performance.now(),r}throw new Error("ChunkMeshManager: Failed to acquire mesh after pool expansion")}expandPool(e){let t=this.meshPool.length;this.poolSize=e;for(let r=t;r<e;r++){let i=new $.BufferGeometry,s=new $.Mesh(i,this.material);s.visible=!1,s.matrixAutoUpdate=!1,s.name="pooled-section-mesh";let o={mesh:s,inUse:!1,lastUsedTime:0};this.meshPool.push(o)}}updateGeometryAttribute(e,t,r,i){let s=e.getAttribute(t);s&&s.count===r.length/i?(s.array.set(r),s.needsUpdate=!0):e.setAttribute(t,new $.BufferAttribute(r,i))}clearGeometry(e){let t=["position","normal","color","uv"];for(let r of t)e.hasAttribute(r)&&e.deleteAttribute(r);e.index&&e.setIndex(null),e.boundingBox=null,e.boundingSphere=null}cleanupExcessMeshes(){if(this.poolSize>this.maxPoolSize){let e=this.meshPool.filter(t=>!t.inUse).length;if(e>0){let t=Math.min(this.poolSize-this.maxPoolSize,e);for(let r=0;r<t;r++){let i=this.meshPool.findIndex(s=>!s.inUse);i!==-1&&(this.meshPool[i].mesh.geometry.dispose(),this.meshPool.splice(i,1),this.poolSize--)}}}}disposeContainer(e){R0(e,!0)}recordRenderTime(e){this.renderTimes.push(e),this.renderTimes.length>this.maxRenderTimeSamples&&this.renderTimes.shift();let t=performance.now();t-this.lastPerformanceCheck>this.performanceCheckInterval&&(this.checkPerformance(),this.lastPerformanceCheck=t)}getEffectiveRenderDistance(){return this.performanceOverrideDistance||this.worldRenderer.viewDistance}resetPerformanceOverride(){this.performanceOverrideDistance=void 0,this.renderTimes.length=0}getAverageRenderTime(){return this.renderTimes.length===0?0:this.renderTimes.reduce((e,t)=>e+t,0)/this.renderTimes.length}checkPerformance(){if(this.renderTimes.length<this.maxRenderTimeSamples)return;let e=this.getAverageRenderTime(),t=16.67,r=t*1.5;if(e>r){let i=this.worldRenderer.viewDistance,s=Math.max(1,Math.floor(i*.8));(!this.performanceOverrideDistance||s<this.performanceOverrideDistance)&&(this.performanceOverrideDistance=s)}else if(this.performanceOverrideDistance&&e<t*1.1){let i=this.worldRenderer.viewDistance,s=Math.min(i,this.performanceOverrideDistance+1);s!==this.performanceOverrideDistance&&(this.performanceOverrideDistance=s>=i?void 0:s)}}updateSectionsVisibility(){let e=this.worldRenderer.cameraSectionPos;for(let[t,r]of Object.entries(this.sectionObjects)){if(r._waitingForChunkDisplay){r.visible=!1;continue}if(!this.performanceOverrideDistance){r.visible=!0;continue}let[i,s,o]=t.split(",").map(Number),a={x:i/16,y:s/16,z:o/16},v=a.x-e.x,l=a.z-e.z,c=Math.floor(Math.hypot(v,l));r.visible=c<=this.performanceOverrideDistance}}};u(pt,"NEAR_REVEAL_TIMEOUT_MS",5e3),u(pt,"EXPECTED_NEAR_GRACE_MS",1500);var Y5=pt,Ji=class{constructor(e){this.worldRendererThree=e;u(this,"chunkTextures",new Map)}dispose(){for(let[,e]of this.chunkTextures)for(let t of Object.keys(e))e[t].dispose();this.chunkTextures.clear()}renderHead(e,t,r,i){let s;if(i.SkullOwner?s=i.SkullOwner.Properties?.textures?.[0]?.Value:s=i.profile?.properties?.find(o=>o.name==="textures")?.value,!!s)try{let a=JSON.parse(z.from(s,"base64").toString()).textures?.SKIN?.url,{skinTexturesProxy:v}=this.worldRendererThree.worldRendererConfig;v&&(a=a?.replace("http://textures.minecraft.net/",v).replace("https://textures.minecraft.net/",v));let l=De(this.worldRendererThree,a,ze.head),c=new $.Group;return r&&l.position.set(0,.3125,.3125),l.position.y-=23/16,c.add(l),this.worldRendererThree.sceneOrigin.track(c),c.position.set(e.x+.5,e.y+.045,e.z+.5),c.rotation.set(0,-$.MathUtils.degToRad(t*(r?90:45/2)),0),c.scale.set(.8,.8,.8),c}catch{}}renderSign(e,t,r,i,s){let o=this.getSignTexture(e,s,i);if(!o)return;let a=new $.Mesh(new $.PlaneGeometry(1,1),new $.MeshBasicMaterial({map:o,transparent:!0}));a.renderOrder=999;let v=7/16,l=i?1.3:1;a.scale.set(1*l,v*l,1*l);let c=(i?2:1.5)/16,d=.25/16;r&&!i?a.position.set(0,0,-.5+c+d+1e-4):a.position.set(0,0,c/2+1e-4);let f=new $.Group;f.rotation.set(0,-$.MathUtils.degToRad(t*(r?90:45/2)),0),f.add(a);let m=(i?10:8)/16,g=(i?0:r?4.333:9.333)/16,b=m/2+g;return this.worldRendererThree.sceneOrigin.track(f),f.position.set(e.x+.5,e.y+b,e.z+.5),f}getSignTexture(e,t,r,i=!1){let s=Ct(e),o=this.chunkTextures.get(`${s[0]},${s[1]}`);o||(o={},this.chunkTextures.set(`${s[0]},${s[1]}`,o));let a=`${e.x},${e.y},${e.z}`;if(o[a])return o[a];let v=Ov(this.worldRendererThree.version),l=m1(t,r,v);if(!l)return;let c=new $.Texture(l);return c.magFilter=$.NearestFilter,c.minFilter=$.NearestFilter,c.needsUpdate=!0,o[a]=c,c}cleanChunkTextures(e,t){let r=`${Math.floor(e/16)},${Math.floor(t/16)}`,i=this.chunkTextures.get(r);if(i)for(let s of Object.keys(i))i[s].dispose(),delete i[s]}};E();x();k();R();E();x();k();R();import*as Ge from"three";var dr={},ha=!1;function Fv(){if(ha)return;let n=globalThis.loadedData?.tints;if(n){for(let e of Object.keys(n))dr[e]=Dv(n[e]);ha=!0}}function Dv(n){let e={},t=ma(n.default??16777215);if(n.data)for(let r of n.data){let i=ma(r.color);for(let s of r.keys)e[s]=i}return new Proxy(e,{get(r,i){return r[i]??t}})}function ma(n){return[(n>>16&255)/255,(n>>8&255)/255,(n&255)/255]}function pa(n,e){return Fv(),n==="grass_block"?[1,1,1]:n==="redstone_wire"?[1,1,1]:n==="birch_leaves"||n==="spruce_leaves"||n==="lily_pad"?dr.constant?.[n]??[1,1,1]:n.includes("leaves")||n==="vine"?dr.foliage?.[e]??[1,1,1]:["short_grass","tall_grass","fern","large_fern","sugar_cane","grass"].includes(n)?dr.grass?.[e]??[1,1,1]:[1,1,1]}var zv=512,qi=1/20,Zi=class{constructor(e){this.worldRenderer=e;u(this,"particles",[]);u(this,"sharedMaterial");u(this,"enabled",!1);u(this,"tickAccumulator",0);u(this,"nextParticleIndex",0);u(this,"render",e=>{if(!this.enabled)return;for(this.tickAccumulator+=e;this.tickAccumulator>=qi;)this.tickAccumulator-=qi,this.tickPhysics();let t=this.tickAccumulator/qi;this.updateVisuals(t)})}enable(){this.enabled||(this.enabled=!0,this.ensureMaterial())}disable(){this.enabled&&(this.enabled=!1)}dispose(){for(let e of this.particles)e.active&&this.worldRenderer.sceneOrigin.removeAndUntrack(e.mesh),e.mesh.geometry.dispose();this.particles=[],this.sharedMaterial?.dispose(),this.sharedMaterial=void 0,this.nextParticleIndex=0}spawnBlockBreakParticles(e,t,r,i,s,o="plains"){if(!this.enabled)return;let a=this.resolveBlockTexture(i);if(!a)return;let v=pa(i,o);for(let l=0;l<4;l++)for(let c=0;c<4;c++)for(let d=0;d<4;d++){let f=e+(l+.5)/4,m=t+(c+.5)/4,g=r+(d+.5)/4,b=f-e-.5,w=m-t-.5,y=g-r-.5;b+=(Math.random()*2-1)*.4,w+=(Math.random()*2-1)*.4,y+=(Math.random()*2-1)*.4;let A=(Math.random()+Math.random()+1)*.15,C=Math.sqrt(b*b+w*w+y*y),M=b/C*A*.4,S=w/C*A*.4+.1,H=y/C*A*.4,B=Math.floor(4/(Math.random()*.9+.1));this.createParticle(f,m,g,M,S,H,B,a,s,e,r,1,v)}}tickPhysics(){for(let e of this.particles){if(!e.active)continue;if(e.prevX=e.x,e.prevY=e.y,e.prevZ=e.z,e.age++,e.age>=e.maxAge){this.deactivateParticle(e);continue}e.yd-=.04,e.x+=e.xd,e.y+=e.yd,e.z+=e.zd;let t=this.getFloorY(e);e.y<=t?(e.y=t,e.yd=0,e.onGround=!0):e.onGround=!1,e.xd*=.98,e.yd*=.98,e.zd*=.98,e.onGround&&(e.xd*=.7,e.zd*=.7)}}updateVisuals(e){let t=this.worldRenderer.camera.position;for(let r of this.particles){if(!r.active)continue;let i=r.prevX+(r.x-r.prevX)*e,s=r.prevY+(r.y-r.prevY)*e,o=r.prevZ+(r.z-r.prevZ)*e;r.mesh.position.set(i,s,o),r.mesh.lookAt(t.x,t.y,t.z)}}spawnCrackParticle(e,t,r,i,s,o,a="plains"){if(!this.enabled)return;let v=this.resolveBlockTexture(s);if(!v)return;let l=pa(s,a),c=e+Math.random()*.8+.1,d=t+Math.random()*.8+.1,f=r+Math.random()*.8+.1;switch(i){case 0:d=t-.1;break;case 1:d=t+1+.1;break;case 2:f=r-.1;break;case 3:f=r+1+.1;break;case 4:c=e-.1;break;case 5:c=e+1+.1;break}let m=(Math.random()*2-1)*.4*.2,g=(Math.random()*2-1)*.4*.2+.1*.2,b=(Math.random()*2-1)*.4*.2,w=Math.floor(4/(Math.random()*.9+.1));this.createParticle(c,d,f,m,g,b,w,v,o,e,r,.6,l)}createParticle(e,t,r,i,s,o,a,v,l,c,d,f=1,m=[1,1,1]){this.ensureMaterial();let g=this.findInactiveParticle();g||(this.particles.length<zv?g=this.allocateParticle():g=this.recycleOldest());let b=Math.floor(Math.random()*4),w=Math.floor(Math.random()*4),y=v.u+b/4*v.su,A=v.v+w/4*v.sv,C=v.su/4,M=v.sv/4;this.setGeometryUVs(g.mesh.geometry,y,A,C,M),g.active=!0,g.x=e,g.y=t,g.z=r,g.prevX=e,g.prevY=t,g.prevZ=r,g.xd=i,g.yd=s,g.zd=o,g.age=0,g.maxAge=a,g.onGround=!1,g.floorMap=l,g.blockX=Math.floor(c),g.blockZ=Math.floor(d);let S=.1*(.5+Math.random()*.5)*2*f;g.mesh.scale.set(S,S,S),g.mesh.position.set(e,t,r),g.mesh.visible=!0;let H=.6*m[0],B=.6*m[1],I=.6*m[2],G=new Float32Array([H,B,I,H,B,I,H,B,I,H,B,I]),O=g.mesh.geometry.getAttribute("color");O?(O.set(G),O.needsUpdate=!0):g.mesh.geometry.setAttribute("color",new Ge.Float32BufferAttribute(G,3)),this.worldRenderer.sceneOrigin.addAndTrack(g.mesh)}allocateParticle(){let e=new Ge.PlaneGeometry(1,1),t=new Ge.Mesh(e,this.sharedMaterial);t.visible=!1;let r={mesh:t,active:!1,x:0,y:0,z:0,prevX:0,prevY:0,prevZ:0,xd:0,yd:0,zd:0,age:0,maxAge:0,onGround:!1,floorMap:[],blockX:0,blockZ:0};return this.particles.push(r),r}findInactiveParticle(){for(let e=0;e<this.particles.length;e++){let t=(this.nextParticleIndex+e)%this.particles.length;if(!this.particles[t].active)return this.nextParticleIndex=(t+1)%this.particles.length,this.particles[t]}}recycleOldest(){let e=this.particles[0];for(let t of this.particles)t.age>e.age&&(e=t);return this.deactivateParticle(e),e}deactivateParticle(e){e.active&&(e.active=!1,e.mesh.visible=!1,this.worldRenderer.sceneOrigin.removeAndUntrack(e.mesh))}getFloorY(e){let t=Math.floor(e.x)-e.blockX,r=Math.floor(e.z)-e.blockZ;return t=Math.max(-2,Math.min(2,t)),r=Math.max(-2,Math.min(2,r)),e.floorMap[(r+2)*5+(t+2)]}resolveBlockTexture(e){let t=this.worldRenderer.resourcesManager.currentResources;if(!t)return null;let r=t.blocksAtlasJson,i=r.textures;if(i[e])return this.extractUV(i[e],r);for(let s of["_side","_top","_front","_0",""]){let o=e+s;if(i[o])return this.extractUV(i[o],r)}for(let s of Object.keys(i))if(s.startsWith(e))return this.extractUV(i[s],r);return null}extractUV(e,t){return{u:e.u,v:e.v,su:e.su??t.suSv,sv:e.sv??t.suSv}}setGeometryUVs(e,t,r,i,s){let o=e.getAttribute("uv");o.setXY(0,t,r),o.setXY(1,t+i,r),o.setXY(2,t,r+s),o.setXY(3,t+i,r+s),o.needsUpdate=!0}ensureMaterial(){if(this.sharedMaterial)return;let e=this.worldRenderer.material.map;e&&(this.sharedMaterial=new Ge.MeshBasicMaterial({map:e,vertexColors:!0,transparent:!0,alphaTest:.1}))}},ga={id:"blockBreakParticles",controller:Zi,enabledDefault:!0,cannotBeDisabled:!0,requiresHeightmap:!1};E();x();k();R();var Xi=class{constructor(e){this.worldRenderer=e;u(this,"enabled",!1);u(this,"lastBobWalkDist",0);u(this,"lastBobTickTime",0);u(this,"render",()=>{if(!this.enabled)return;let e=this.worldRenderer.displayOptions.inWorldRenderingConfig,{perspective:t}=this.worldRenderer.playerStateReactive;if(e.viewBobbing&&t==="first_person"&&!this.worldRenderer.playerStateUtils.isSpectator()){this.worldRenderer.playerStateReactive.walkDist!==this.lastBobWalkDist&&(this.lastBobTickTime=performance.now(),this.lastBobWalkDist=this.worldRenderer.playerStateReactive.walkDist);let i=Math.min((performance.now()-this.lastBobTickTime)/50,1);this.worldRenderer.cameraShake.setCameraBobInput({walkDist:this.worldRenderer.playerStateReactive.walkDist,prevWalkDist:this.worldRenderer.playerStateReactive.prevWalkDist,bob:this.worldRenderer.playerStateReactive.bob,prevBob:this.worldRenderer.playerStateReactive.prevBob,partialTick:i})}else this.worldRenderer.cameraShake.setCameraBobInput(null)})}enable(){this.enabled=!0}disable(){this.enabled=!1,this.worldRenderer.cameraShake.setCameraBobInput(null);let{perspective:e}=this.worldRenderer.playerStateReactive;e==="first_person"&&this.worldRenderer.camera.position.set(0,0,0)}dispose(){this.disable()}},ba={id:"cameraBobbing",controller:Xi,enabledDefault:!0,cannotBeDisabled:!0};E();x();k();R();import*as I0 from"three";var $i=2e3,ya=32,_a=32,ur=12,wa=24,fr=1.2,Lv=-5;var en=class{constructor(e){this.worldRenderer=e;u(this,"instancedMesh");u(this,"geometry");u(this,"material");u(this,"particles",[]);u(this,"enabled",!1);u(this,"dummy",new I0.Matrix4);u(this,"tempPosition",new I0.Vector3);u(this,"tempQuaternion",new I0.Quaternion);u(this,"tempScale",new I0.Vector3);u(this,"render",e=>{if(!this.enabled||!this.instancedMesh||!this.material)return;this.syncMaterialToSceneFog();let t=this.worldRenderer.getCameraPosition();this.instancedMesh.position.set(0,0,0);let r=this.worldRenderer.reactiveState.world.heightmaps,{dummy:i,tempPosition:s,tempQuaternion:o,tempScale:a}=this,v=NaN,l=NaN,c;for(let d=0;d<$i;d++){let f=this.particles[d];this.instancedMesh.getMatrixAt(d,i),i.decompose(s,o,a),s.addScaledVector(f.velocity,e);let m=s.y,g=Math.sqrt(s.x*s.x+s.z*s.z),b=t.x+s.x,w=t.y+s.y,y=t.z+s.z,A=Math.floor(b/16),C=Math.floor(y/16);(A!==v||C!==l)&&(c=r.get(`${A},${C}`),v=A,l=C);let M=(Math.floor(b)%16+16)%16,S=(Math.floor(y)%16+16)%16,H=c?.[S*16+M];if(g>ya||H!==void 0&&H!==-32768&&w<=H+1+f.despawnOffset||m<Lv){this.respawnParticle(s);let I=ur+Math.random()*(wa-ur);f.velocity.set((Math.random()-.5)*fr,-I,(Math.random()-.5)*fr),f.despawnOffset=Math.random()*.5}i.compose(s,o,a),this.instancedMesh.setMatrixAt(d,i)}this.instancedMesh.instanceMatrix.needsUpdate=!0})}enable(){this.enabled||(this.enabled=!0,this.instancedMesh?this.instancedMesh.visible=!0:this.createRain())}disable(){this.enabled&&(this.enabled=!1,this.instancedMesh&&(this.instancedMesh.visible=!1))}autoEnableCheck(){return this.worldRenderer.worldRendererConfig.isRaining===!0}dispose(){this.instancedMesh&&this.worldRenderer.scene.remove(this.instancedMesh),this.geometry?.dispose(),this.material?.dispose(),this.instancedMesh=void 0,this.geometry=void 0,this.material=void 0,this.particles=[]}syncMaterialToSceneFog(){if(!this.material)return;let e=this.worldRenderer.scene.fog;e instanceof I0.Fog||e instanceof I0.FogExp2?this.material.color.copy(e.color):this.material.color.set(13426158),this.material.fog=!0}createRain(){this.geometry=new I0.BoxGeometry(.03,.3,.03),this.material=new I0.MeshBasicMaterial({color:13426158,transparent:!0,opacity:.35,depthWrite:!0,fog:!0}),this.instancedMesh=new I0.InstancedMesh(this.geometry,this.material,$i),this.instancedMesh.name="rain-particles",this.instancedMesh.frustumCulled=!1,this.syncMaterialToSceneFog();let e=new I0.Matrix4,t=new I0.Vector3;for(let r=0;r<$i;r++){this.respawnParticle(t),t.y=Math.random()*_a,e.setPosition(t),this.instancedMesh.setMatrixAt(r,e);let i=ur+Math.random()*(wa-ur);this.particles.push({velocity:new I0.Vector3((Math.random()-.5)*fr,-i,(Math.random()-.5)*fr),age:0,despawnOffset:Math.random()*.5})}this.instancedMesh.instanceMatrix.needsUpdate=!0,this.worldRenderer.scene.add(this.instancedMesh)}respawnParticle(e){let t=Math.random()*Math.PI*2,r=Math.random()*ya;e.set(Math.cos(t)*r,_a,Math.sin(t)*r)}},Aa={id:"rain",controller:en,enabledDefault:!1,requiresHeightmap:!0};E();x();k();R();import*as w0 from"three";var Ea=new w0.Color(13/255,234/255,238/255),Uv=9;var Gv=350,Nv=650;var Wv=120,Vv=280,tn=class{constructor(e){this.worldRenderer=e;u(this,"pendingGeometries",new Map);u(this,"revealingSections",new Map);u(this,"finishedChunkCount",0);u(this,"revealTriggered",!1);u(this,"revealStartTime",0);u(this,"enabled",!1);u(this,"onWorldSwitchedCb",null);u(this,"patched",!1);u(this,"initialWaveDone",!1);u(this,"initialRevealWaveSettled",!1);u(this,"wireframeMaterial");u(this,"wireframeGlowMaterial");u(this,"pulseTime",0);u(this,"revealedChunks",new Set);u(this,"originalFinishChunk",null);u(this,"originalDestroy",null);u(this,"originalSceneAdd",null);u(this,"originalHandleWorkerMessage",null);u(this,"render",e=>{this.enabled&&this.update(e*1e3)});this.wireframeMaterial=new w0.LineBasicMaterial({color:Ea,transparent:!0,opacity:1,blending:w0.AdditiveBlending,depthWrite:!1}),this.wireframeGlowMaterial=new w0.LineBasicMaterial({color:Ea,transparent:!0,opacity:.55,blending:w0.AdditiveBlending,depthWrite:!1})}isFuturisticRevealConfigured(){return this.worldRenderer.worldRendererConfig.futuristicReveal===!0}isInInitialRevealCampaign(){return this.enabled&&!this.initialRevealWaveSettled}autoEnableCheck(){return this.isFuturisticRevealConfigured()}enable(){if(this.isFuturisticRevealConfigured()&&!(this.enabled&&this.patched)){if(this.enabled&&!this.patched){this.patchWorldRenderer();return}this.enabled=!0,this.patchWorldRenderer()}}disable(){this.enabled&&(this.enabled=!1,this.unpatchWorldRenderer(),this.reset())}toggle(){return this.enabled?this.disable():this.enable(),this.enabled}dispose(){this.disable(),this.wireframeMaterial.dispose(),this.wireframeGlowMaterial.dispose()}patchWorldRenderer(){if(this.patched)return;this.patched=!0;let e=this.worldRenderer;this.onWorldSwitchedCb=()=>this.reset(),e.onWorldSwitched.push(this.onWorldSwitchedCb),this.originalFinishChunk=e.finishChunk.bind(e),e.finishChunk=t=>{this.originalFinishChunk(t),this.onChunkFinished(t)},this.originalDestroy=e.destroy.bind(e),e.destroy=()=>{this.dispose(),this.originalDestroy()},this.originalHandleWorkerMessage=e.handleWorkerMessage.bind(e),e.handleWorkerMessage=t=>{this.originalHandleWorkerMessage(t),this.enabled&&t?.type==="geometry"&&Promise.resolve().then(()=>{try{this.registerSection(t.key,t.geometry)}catch{}})},this.originalSceneAdd=e.scene.add.bind(e.scene),e.scene.add=(...t)=>{let r=this.originalSceneAdd(...t);for(let i of t)this.checkAndPatchMesh(i);return r}}unpatchWorldRenderer(){let e=this.worldRenderer;if(this.originalFinishChunk&&(e.finishChunk=this.originalFinishChunk,this.originalFinishChunk=null),this.originalDestroy&&(e.destroy=this.originalDestroy,this.originalDestroy=null),this.originalHandleWorkerMessage&&(e.handleWorkerMessage=this.originalHandleWorkerMessage,this.originalHandleWorkerMessage=null),this.originalSceneAdd&&(e.scene.add=this.originalSceneAdd,this.originalSceneAdd=null),this.onWorldSwitchedCb){let t=e.onWorldSwitched.indexOf(this.onWorldSwitchedCb);t!==-1&&e.onWorldSwitched.splice(t,1),this.onWorldSwitchedCb=null}this.patched=!1}checkAndPatchMesh(e){if(e instanceof w0.Mesh&&(e.name==="mesh"||e.name==="shaderMesh")){let t=this.findSectionKeyForMesh(e);t&&this.shouldUseRevealEffect(t)&&(e.visible=!1,e.hiddenByReveal=!0)}for(let t of e.children)this.checkAndPatchMesh(t)}findSectionKeyForMesh(e){let t=e;for(;t;){let{sectionKey:m}=t;if(m&&this.worldRenderer.chunkMeshManager.sectionObjects[m]===t)return m;t=t.parent}let r=this.worldRenderer.sceneOrigin.getWorldPosition(e),i=r?.x??this.worldRenderer.sceneOrigin.toWorldX(e.position.x),s=r?.y??this.worldRenderer.sceneOrigin.toWorldY(e.position.y),o=r?.z??this.worldRenderer.sceneOrigin.toWorldZ(e.position.z),a=16,v=this.worldRenderer.getSectionHeight(),l=Math.floor(i/a)*a,c=Math.floor(s/v)*v,d=Math.floor(o/a)*a,f=`${l},${c},${d}`;return this.worldRenderer.chunkMeshManager.sectionObjects[f]?f:null}get scene(){return this.worldRenderer.realScene}getCameraPosition(){return this.worldRenderer.getCameraPosition()}sectionHasRevealContent(e){return(e.wireframePositions?.length??0)>0||(e.positions?.length??0)>0?!0:(e.shaderCubes?.count??0)>0}getSectionRenderMeshes(e){let t=this.worldRenderer.chunkMeshManager.sectionObjects[e];if(!t)return[];let r=[];for(let i of["mesh","shaderMesh"]){let s=t.children.find(o=>o.name===i);s instanceof w0.Mesh&&r.push(s)}return r}hideSectionRenderMeshes(e){let t=this.getSectionRenderMeshes(e);for(let r of t)r.visible=!1,r.hiddenByReveal=!0;return t}setMeshFadeOpacity(e,t){if(e.name==="shaderMesh"){e.visible=t>.001;return}let r=e.material;if(!Array.isArray(r))if(r.originalMaterial)r.opacity=t,r.transparent=!0,r.needsUpdate=!0;else{r.originalMaterial=r;let i=r.clone();i.transparent=!0,i.opacity=t,i.needsUpdate=!0,e.material=i}}restoreMeshMaterial(e){let t=e.originalMaterial;if(!t)return;let r=e.material;e.material=t,r!==t&&r.dispose(),delete e.originalMaterial}onChunkFinished(e){this.finishedChunkCount++,!this.revealTriggered&&this.finishedChunkCount>=Uv&&this.triggerReveal()}registerSection(e,t){if(!(this.revealedChunks.has(e)||this.revealingSections.has(e))){if(this.revealTriggered&&this.initialWaveDone){this.revealedChunks.add(e);return}this.revealTriggered?this.startSectionReveal(e,t):this.pendingGeometries.set(e,t)}}shouldUseRevealEffect(e){return!this.enabled||this.revealTriggered&&this.initialWaveDone?!1:!this.revealedChunks.has(e)&&!this.revealingSections.has(e)}triggerReveal(){this.revealTriggered=!0,this.initialWaveDone=!0,this.revealStartTime=performance.now();let e=this.getCameraPosition(),t=[...this.pendingGeometries.entries()];this.pendingGeometries.clear();let r=t.map(([s,o])=>{let a=Math.hypot(o.sx-e.x,o.sy-e.y,o.sz-e.z);return{key:s,geometry:o,distance:a}}).sort((s,o)=>s.distance-o.distance),i=r.at(-1)?.distance||1;for(let{key:s,geometry:o,distance:a}of r){let v=a/i*1500;setTimeout(()=>{!this.revealedChunks.has(s)&&!this.revealingSections.has(s)&&this.startSectionReveal(s,o)},v)}}startSectionReveal(e,t){if(!this.sectionHasRevealContent(t)||this.revealingSections.has(e)||this.revealedChunks.has(e))return;let r=this.createWireframeGeometry(t),i=this.worldRenderer.chunkMeshManager.globalBlockBuffer,s=i?.hasSection(e)?i.takeSectionData(e):void 0,o=this.hideSectionRenderMeshes(e),a=new w0.LineSegments(r,this.wireframeMaterial.clone());this.worldRenderer.sceneOrigin.track(a),a.position.set(t.sx,t.sy,t.sz),a.name="scifi-wireframe",a.renderOrder=1e3;let v=new w0.LineSegments(r.clone(),this.wireframeGlowMaterial.clone());this.worldRenderer.sceneOrigin.track(v),v.position.set(t.sx,t.sy,t.sz),v.scale.set(1.02,1.02,1.02),v.name="scifi-glow",v.renderOrder=999;let l=new w0.Group;l.add(a),l.add(v),l.name="scifi-reveal-group",l.sectionKey=e,this.scene.add(l);let c=this.initialWaveDone?Wv:Gv,d=this.initialWaveDone?Vv:Nv,f={key:e,wireframeGroup:l,revealStartTime:performance.now(),phase:"wireframe",renderMeshRefs:o,globalShaderRestore:s,wireframeMs:c,revealMs:d};setTimeout(()=>{for(let m of this.getSectionRenderMeshes(e))m.hiddenByReveal||this.hideSectionRenderMeshes(e)},0),this.revealingSections.set(e,f)}createSectionBoundsWireframe(){let r=[[-8,-8,-8],[8,-8,-8],[-8,8,-8],[8,8,-8],[-8,-8,8],[8,-8,8],[-8,8,8],[8,8,8]],i=[[0,1],[1,3],[3,2],[2,0],[4,5],[5,7],[7,6],[6,4],[0,4],[1,5],[2,6],[3,7]],s=[];for(let[a,v]of i)s.push(...r[a],...r[v]);let o=new w0.BufferGeometry;return o.setAttribute("position",new w0.Float32BufferAttribute(s,3)),o}createWireframeGeometry(e){if(e.wireframePositions&&e.wireframePositions.length>0){let a=new w0.BufferGeometry;return a.setAttribute("position",new w0.Float32BufferAttribute(e.wireframePositions,3)),a}let t=e.positions,r=e.indices;if(!t?.length||!r?.length)return this.createSectionBoundsWireframe();let i=[],s=new Set;for(let a=0;a<r.length;a+=3){let v=r[a],l=r[a+1],c=r[a+2];this.addEdge(t,v,l,i,s),this.addEdge(t,l,c,i,s),this.addEdge(t,c,v,i,s)}let o=new w0.BufferGeometry;return o.setAttribute("position",new w0.Float32BufferAttribute(i,3)),o}addEdge(e,t,r,i,s){let o=Math.min(t,r),a=Math.max(t,r),v=`${o}-${a}`;s.has(v)||(s.add(v),i.push(e[t*3],e[t*3+1],e[t*3+2],e[r*3],e[r*3+1],e[r*3+2]))}update(e){if(!this.enabled||this.revealingSections.size===0)return;this.pulseTime+=e*.001;let t=performance.now(),r=.6+.4*Math.sin(this.pulseTime*4),i=[];for(let[s,o]of this.revealingSections){let a=t-o.revealStartTime;if(o.phase==="wireframe"){let v=o.wireframeGroup.children[0],l=o.wireframeGroup.children[1];if(v?.material){let c=v.material;c.opacity=r;let d=.85+.15*Math.sin(this.pulseTime*6+a*.002);c.color.setRGB(13/255*d,234/255*d,238/255*d)}if(l?.material){let c=l.material;c.opacity=r*.4}if(a>o.wireframeMs){o.phase="transitioning",o.renderMeshRefs=this.getSectionRenderMeshes(s);for(let c of o.renderMeshRefs)c.visible=!0,this.setMeshFadeOpacity(c,0)}}else if(o.phase==="transitioning"){let v=a-o.wireframeMs,l=Math.min(1,v/o.revealMs),c=1-(1-l)**3,d=o.wireframeGroup.children[0],f=o.wireframeGroup.children[1];if(d?.material){let m=d.material;m.opacity=1-c}if(f?.material){let m=f.material;m.opacity=(1-c)*.55}for(let m of o.renderMeshRefs)this.setMeshFadeOpacity(m,c);l>=1&&(o.phase="complete",i.push(o))}}for(let s of i)this.completeReveal(s)}completeReveal(e){this.revealingSections.delete(e.key),this.revealedChunks.add(e.key),this.revealTriggered&&this.revealingSections.size===0&&(this.initialRevealWaveSettled=!0);for(let t of e.renderMeshRefs)this.restoreMeshMaterial(t),t.visible=!0,delete t.hiddenByReveal;this.worldRenderer.chunkMeshManager.migrateDeferredShaderToGlobal(e.key),e.globalShaderRestore&&this.worldRenderer.chunkMeshManager.globalBlockBuffer?.addSection(e.key,e.globalShaderRestore.words,e.globalShaderRestore.count),this.disposeWireframeGroup(e.wireframeGroup)}disposeWireframeGroup(e){this.worldRenderer.sceneOrigin.removeAndUntrackAll(e);let t=[];e.traverse(r=>{t.push(r)});for(let r of t){let i=r;if(i.geometry&&i.geometry.dispose(),i.material){let s=i.material;if(Array.isArray(s))for(let o of s)o.dispose();else s&&typeof s.dispose=="function"&&s.dispose()}}e.clear()}reset(){for(let e of this.revealingSections.values())this.disposeWireframeGroup(e.wireframeGroup);this.pendingGeometries.clear(),this.revealingSections.clear(),this.revealedChunks.clear(),this.finishedChunkCount=0,this.revealTriggered=!1,this.initialWaveDone=!1,this.initialRevealWaveSettled=!1,this.revealStartTime=0,this.pulseTime=0}forceCompleteAll(){let e=[...this.revealingSections.values()];for(let t of e){t.renderMeshRefs=this.getSectionRenderMeshes(t.key);for(let r of t.renderMeshRefs)this.restoreMeshMaterial(r),r.visible=!0,delete r.hiddenByReveal;this.completeReveal(t)}}debugGetWireframeGroups(){let e=[];return this.scene.traverse(t=>{t.name==="scifi-reveal-group"&&e.push(t)}),e}debugForceCleanup(){let e=this.debugGetWireframeGroups();for(let t of e)this.disposeWireframeGroup(t);for(let t of this.revealingSections.values())this.disposeWireframeGroup(t.wireframeGroup);this.revealingSections.clear()}debugStatus(){let e=this.debugGetWireframeGroups(),t=new Set(this.revealingSections.keys()),r=e.filter(i=>!t.has(i.sectionKey));return{revealTriggered:this.revealTriggered,finishedChunkCount:this.finishedChunkCount,pendingGeometries:this.pendingGeometries.size,revealingSections:this.revealingSections.size,revealedChunks:this.revealedChunks.size,wireframeGroupsInScene:e.length,orphanedWireframeGroups:r.length,orphanedKeys:r.map(i=>i.sectionKey),sections:[...this.revealingSections.entries()].map(([i,s])=>({key:i,phase:s.phase,renderMeshCount:s.renderMeshRefs.length,wireframeInScene:s.wireframeGroup.parent!==null}))}}debugLog(){}},xa={id:"futuristicReveal",controller:tn,enabledDefault:!0};E();x();k();R();import*as M0 from"three";var jv=parseInt(M0.REVISION.replaceAll(/\D+/g,""),10),rn=class extends M0.ShaderMaterial{constructor(){super({uniforms:{time:{value:0},fade:{value:1}},vertexShader:`
|
|
21489
21489
|
uniform float time;
|
|
21490
21490
|
attribute float size;
|
|
21491
21491
|
varying vec3 vColor;
|