minecraft-renderer 0.1.56 → 0.1.57

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.
@@ -282,7 +282,7 @@ void main() {
282
282
  applyFog();
283
283
  writeLogDepth();
284
284
  }
285
- `;q1=6,ft={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},X3={TEX_INDEX_BITS:12,DIAGONAL_FLAG_SHIFT:12,SECTION_Y_SHIFT:13,SECTION_Y_BITS:5,EMPTY_SHIFT:18,SPARE_BITS:13}});var Z1,$3=X0(()=>{"use strict";E();x();k();R();Z1=class{constructor(e){d(this,"atlasWidth");d(this,"atlasHeight");d(this,"tileSize");d(this,"tilesPerRow");d(this,"maxTiles");d(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 ce from"three";var X1,ea=X0(()=>{"use strict";E();x();k();R();X1=class n{constructor(){d(this,"entries",[{r:1,g:1,b:1}]);d(this,"colorToIndex",new Map);d(this,"categoryBiomeToIndex",new Map);d(this,"texture",null);d(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),v=`${i}:${s}`,a=this.categoryBiomeToIndex.get(v);if(a!==void 0)return a;let l=this.colorToIndex.get(o);if(l!==void 0)return this.categoryBiomeToIndex.set(v,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(v,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 ce.DataTexture(e,256,1,ce.RGBAFormat,ce.FloatType);return t.minFilter=ce.NearestFilter,t.magFilter=ce.NearestFilter,t.wrapS=ce.ClampToEdgeWrapping,t.wrapT=ce.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,v=(i&255)/255;return[s,o,v]}if(e.grass){let i=r(e.grass.default);for(let{keys:s,color:o}of e.grass.data??[]){let v=r(o);for(let a of s)t.add(v[0],v[1],v[2],"grass",a)}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 v=r(o);for(let a of s)t.add(v[0],v[1],v[2],"foliage",a)}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 v=r(o);for(let a of s)t.add(v[0],v[1],v[2],"redstone",a)}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 v=r(o);for(let a of s)t.add(v[0],v[1],v[2],"constant",a)}t.add(i[0],i[1],i[2],"constant","default")}return t}}});import ta from"mc-assets/dist/blocksAtlases.json";function wv(){let n=globalThis.loadedData?.tints;return n||(ra||(ra=!0),null)}function tr(){let n=wv();if(!n)return null;if($1||($1=X1.fromTintsData(n),$1.createTexture()),!zi){let e=ta.latest??ta;zi=new Z1({width:e.width,height:e.height,tileSize:e.tileSize??16,suSv:e.suSv??16,textures:e.textures??{}})}return{tintPalette:$1,textureIndexMapping:zi}}function ia(){return 1<<X3.EMPTY_SHIFT>>>0}var er,$1,zi,ra,Kt=X0(()=>{"use strict";E();x();k();R();ht();$3();ea();er=4,$1=null,zi=null,ra=!1});import*as B0 from"three";function Av(n,e){let t=new B0.InstancedBufferGeometry,r=new Float32Array(q1*3);t.setAttribute("position",new B0.BufferAttribute(r,3));let i=new Uint32Array(e),s=new Uint32Array(e),o=new Uint32Array(e),v=new Uint32Array(e),a=er;for(let l=0;l<e;l++)i[l]=n[l*a],s[l]=n[l*a+1],o[l]=n[l*a+2],v[l]=n[l*a+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(v,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 Ev(n){n.raycast=(e,t)=>{let{geometry:r}=n;if(!r.boundingBox||(na.copy(r.boundingBox).applyMatrix4(n.matrixWorld),!e.ray.intersectBox(na,Li)))return;let i=e.ray.origin.distanceTo(Li);t.push({distance:i,point:Li.clone(),object:n})}}function rr(n,e){let t=Av(n.words,n.count),r=new B0.Mesh(t,e);return r.name="shaderMesh",r.matrixAutoUpdate=!1,r.frustumCulled=!1,Ev(r),r}function Ui(n){n.geometry.dispose()}var na,Li,Gi=X0(()=>{"use strict";E();x();k();R();ht();Kt();na=new B0.Box3,Li=new B0.Vector3});var ca={};K5(ca,{applyWorldGeometryExport:()=>kv,createMeshesFromExport:()=>va,downloadWorldGeometry:()=>Ni,exportWorldGeometry:()=>oa,loadTextureFromDataUrl:()=>la,loadWorldGeometryFromUrl:()=>xv});import*as P0 from"three";function oa(n,e,t,r=!1){let i=[];for(let[o,v]of Object.entries(n.sectionObjects)){let a=v.children.find(A=>A.name==="mesh");if(!a?.geometry)continue;let{geometry:l}=a,c=l.getAttribute("position"),u=l.getAttribute("normal"),f=l.getAttribute("color"),p=l.getAttribute("uv"),g=l.index;if(!c||!g)continue;let b=n.sceneOrigin.getWorldPosition(a);i.push({key:o,position:{x:b?.x??n.sceneOrigin.toWorldX(a.position.x),y:b?.y??n.sceneOrigin.toWorldY(a.position.y),z:b?.z??n.sceneOrigin.toWorldZ(a.position.z)},geometry:{positions:[...c.array],normals:u?[...u.array]:[],colors:f?[...f.array]:[],uvs:p?[...p.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"),v=n.material.map,{image:a}=v;a&&(o.width=a.width,o.height=a.height,o.getContext("2d").drawImage(a,0,0),s.textureAtlasDataUrl=o.toDataURL("image/png"))}return s}function Ni(n,e,t,r="world-geometry.json",i=!1){let s=oa(n,e,t,i),o=JSON.stringify(s),v=new Blob([o],{type:"application/json"}),a=URL.createObjectURL(v),l=document.createElement("a");l.href=a,l.download=r,l.click(),URL.revokeObjectURL(a)}async function xv(n){let e=await fetch(n);if(!e.ok)throw new Error(`Failed to fetch world geometry: ${e.statusText}`);return e.json()}function aa(n){let e=n.map??n.map;if(!e)return null;let t=J1();t.uniforms.u_atlas.value=e;let r=tr();if(!r)return null;let{tintPalette:i}=r;return i.isReady()||i.createTexture(),t.uniforms.u_tintPalette.value=i.getTexture(),t}function va(n,e,t){let r=[],i=t??aa(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 u=Math.max(...s.geometry.indices)>65535?Uint32Array:Uint16Array;l.setIndex(new P0.BufferAttribute(new u(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 a=s.shaderCubes;if(a&&a.count>0&&i){let l=rr(a,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 la(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 kv(n,e){let{scene:t,renderUpdateEmitter:r,material:i}=n,s=t.getObjectByName(sa);s&&(t.remove(s),Rv(s));let o=!!e.textureAtlasDataUrl,v;if(o&&e.textureAtlasDataUrl){let u=await la(e.textureAtlasDataUrl);v=new P0.MeshLambertMaterial({map:u,vertexColors:!0,transparent:!0,alphaTest:.1}),v.name="geometry-export-material"}else v=i;let a=e.sections.some(u=>(u.shaderCubes?.count??0)>0)?aa(v):null,l=va(e,v,a),c=new P0.Group;c.name=sa,o&&(c.userData.geometryExportMaterial=v);for(let u of l)c.add(u);return t.add(c),r.emit("update"),l.length}var sa,Rv,Wi=X0(()=>{"use strict";E();x();k();R();Kt();ht();Gi();sa="geometry-export-root";Rv=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 B2}from"valtio";E();x();k();R();E();x();k();R();var br=()=>({longRenderTime:!1,constantLongRenderTime:!1,tooManyEntities:!1,tooManyTextures:!1,unknownReason:!1});E();x();k();R();var $5=30;var yr=45,_r=100;E();x();k();R();var o5=class{constructor(e){this.factors=e;d(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,v=s>=8&&o/s>=.65,a=e.loadedTextureCount>=100,l=t&&e.entitiesMs>=8&&r<=20,u=t&&!(i||v||l||a);this.factors.longRenderTime=i,this.factors.constantLongRenderTime=v,this.factors.tooManyEntities=l,this.factors.tooManyTextures=a,this.factors.unknownReason=u}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 n6=[{key:"longRenderTime",code:"LR"},{key:"constantLongRenderTime",code:"CLR"},{key:"tooManyEntities",code:"ENT"},{key:"tooManyTextures",code:"TEX"},{key:"unknownReason",code:"UNK"}];function wr(n){let e=n6.filter(({key:t})=>n[t]).map(({code:t})=>t);return e.length>0?e.join("+"):""}var a5={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:{}},P2={fpsLimit:void 0,sceneBackground:"lightblue",timeoutRendering:!1},dl=(n={})=>B2({...a5,...n}),Ke=()=>({reactive:B2({world:{chunksLoaded:new Set,heightmaps:new Map,allChunksLoaded:!1,mesherWork:!1,instabilityFactors:br(),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 s6}from"valtio";var Ar=()=>s6({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}),I2=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"}}),H2=()=>({reactive:Ar()});E();x();k();R();import{Vec3 as b6}from"vec3";import{proxy as q2}from"valtio";E();x();k();R();E();x();k();R();E();x();k();R();E();x();k();R();var e1={},O2=!1;function o6(){if(O2)return e1;O2=!0;var n=typeof Reflect=="object"?Reflect:null,e=n&&typeof n.apply=="function"?n.apply:function(M,I,B){return Function.prototype.apply.call(M,I,B)},t;n&&typeof n.ownKeys=="function"?t=n.ownKeys:Object.getOwnPropertySymbols?t=function(M){return Object.getOwnPropertyNames(M).concat(Object.getOwnPropertySymbols(M))}:t=function(M){return Object.getOwnPropertyNames(M)};function r(C){}var i=Number.isNaN||function(M){return M!==M};function s(){s.init.call(this)}e1=s,e1.once=y,s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var o=10;function v(C){if(typeof C!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof C)}Object.defineProperty(s,"defaultMaxListeners",{enumerable:!0,get:function(){return o},set:function(C){if(typeof C!="number"||C<0||i(C))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+C+".");o=C}}),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(M){if(typeof M!="number"||M<0||i(M))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+M+".");return this._maxListeners=M,this};function a(C){return C._maxListeners===void 0?s.defaultMaxListeners:C._maxListeners}s.prototype.getMaxListeners=function(){return a(this)},s.prototype.emit=function(M){for(var I=[],B=1;B<arguments.length;B++)I.push(arguments[B]);var H=M==="error",G=this._events;if(G!==void 0)H=H&&G.error===void 0;else if(!H)return!1;if(H){var O;if(I.length>0&&(O=I[0]),O instanceof Error)throw O;var j=new Error("Unhandled error."+(O?" ("+O.message+")":""));throw j.context=O,j}var J=G[M];if(J===void 0)return!1;if(typeof J=="function")e(J,this,I);else for(var Z=J.length,e0=g(J,Z),B=0;B<Z;++B)e(e0[B],this,I);return!0};function l(C,M,I,B){var H,G,O;if(v(I),G=C._events,G===void 0?(G=C._events=Object.create(null),C._eventsCount=0):(G.newListener!==void 0&&(C.emit("newListener",M,I.listener?I.listener:I),G=C._events),O=G[M]),O===void 0)O=G[M]=I,++C._eventsCount;else if(typeof O=="function"?O=G[M]=B?[I,O]:[O,I]:B?O.unshift(I):O.push(I),H=a(C),H>0&&O.length>H&&!O.warned){O.warned=!0;var j=new Error("Possible EventEmitter memory leak detected. "+O.length+" "+String(M)+" listeners added. Use emitter.setMaxListeners() to increase limit");j.name="MaxListenersExceededWarning",j.emitter=C,j.type=M,j.count=O.length}return C}s.prototype.addListener=function(M,I){return l(this,M,I,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(M,I){return l(this,M,I,!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 u(C,M,I){var B={fired:!1,wrapFn:void 0,target:C,type:M,listener:I},H=c.bind(B);return H.listener=I,B.wrapFn=H,H}s.prototype.once=function(M,I){return v(I),this.on(M,u(this,M,I)),this},s.prototype.prependOnceListener=function(M,I){return v(I),this.prependListener(M,u(this,M,I)),this},s.prototype.removeListener=function(M,I){var B,H,G,O,j;if(v(I),H=this._events,H===void 0)return this;if(B=H[M],B===void 0)return this;if(B===I||B.listener===I)--this._eventsCount===0?this._events=Object.create(null):(delete H[M],H.removeListener&&this.emit("removeListener",M,B.listener||I));else if(typeof B!="function"){for(G=-1,O=B.length-1;O>=0;O--)if(B[O]===I||B[O].listener===I){j=B[O].listener,G=O;break}if(G<0)return this;G===0?B.shift():b(B,G),B.length===1&&(H[M]=B[0]),H.removeListener!==void 0&&this.emit("removeListener",M,j||I)}return this},s.prototype.off=s.prototype.removeListener,s.prototype.removeAllListeners=function(M){var I,B,H;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[M]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete B[M]),this;if(arguments.length===0){var G=Object.keys(B),O;for(H=0;H<G.length;++H)O=G[H],O!=="removeListener"&&this.removeAllListeners(O);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(I=B[M],typeof I=="function")this.removeListener(M,I);else if(I!==void 0)for(H=I.length-1;H>=0;H--)this.removeListener(M,I[H]);return this};function f(C,M,I){var B=C._events;if(B===void 0)return[];var H=B[M];return H===void 0?[]:typeof H=="function"?I?[H.listener||H]:[H]:I?A(H):g(H,H.length)}s.prototype.listeners=function(M){return f(this,M,!0)},s.prototype.rawListeners=function(M){return f(this,M,!1)},s.listenerCount=function(C,M){return typeof C.listenerCount=="function"?C.listenerCount(M):p.call(C,M)},s.prototype.listenerCount=p;function p(C){var M=this._events;if(M!==void 0){var I=M[C];if(typeof I=="function")return 1;if(I!==void 0)return I.length}return 0}s.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]};function g(C,M){for(var I=new Array(M),B=0;B<M;++B)I[B]=C[B];return I}function b(C,M){for(;M+1<C.length;M++)C[M]=C[M+1];C.pop()}function A(C){for(var M=new Array(C.length),I=0;I<M.length;++I)M[I]=C[I].listener||C[I];return M}function y(C,M){return new Promise(function(I,B){function H(O){C.removeListener(M,G),B(O)}function G(){typeof C.removeListener=="function"&&C.removeListener("error",H),I([].slice.call(arguments))}S(C,M,G,{once:!0}),M!=="error"&&w(C,H,{once:!0})})}function w(C,M,I){typeof C.on=="function"&&S(C,"error",M,I)}function S(C,M,I,B){if(typeof C.on=="function")B.once?C.once(M,I):C.on(M,I);else if(typeof C.addEventListener=="function")C.addEventListener(M,function H(G){B.once&&C.removeEventListener(M,H),I(G)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof C)}return e1}var t1=o6();t1.once;t1.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)})};t1.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,u)=>r.push({resolve:c,reject:u}))},async return(){n.removeListener(e,v),n.removeListener("error",a),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,v),n.removeListener("error",a)},[Symbol.asyncIterator](){return this}};return n.on(e,v),n.on("error",a),o;function v(...l){let c=r.shift();c?c.resolve(createIterResult(l,!1)):t.push(l)}function a(l){s=!0;let c=r.shift();c?c.reject(l):i=l,o.return()}};var{EventEmitter:Je,defaultMaxListeners:Tl,init:Ml,listenerCount:Sl,on:Cl,once:Bl}=t1;import{Vec3 as qe}from"vec3";E();x();k();R();function v5(n){let e=n*2+1;if(e<=0)return[];let t=[],r=0,i=0,s=0,o=-1;for(let v=0;v<e*e;v++){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 a=s;s=-o,o=a}r+=s,i+=o}return t}E();x();k();R();function Er(n,e=0){if(e>16)return;if(n==null)return n;let t=typeof n;if(t==="function"||t==="symbol")return;if(t==="bigint")return n.toString();if(t!=="object"||n instanceof ArrayBuffer)return n;if(ArrayBuffer.isView(n)){let s=n;return s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength)}if(n instanceof Date)return n.toISOString();if(Array.isArray(n))return n.map(s=>Er(s,e+1)).filter(s=>s!==void 0);let r=n;if(typeof r.x=="number"&&typeof r.y=="number"&&typeof r.z=="number"&&!("w"in r))return{x:r.x,y:r.y,z:r.z};let i={};for(let s of Object.keys(r)){if(s==="_client"||s==="_events"||s==="_eventsCount")continue;let o=Er(r[s],e+1);o!==void 0&&(i[s]=o)}return i}function r1(n){return n.map(e=>Er(e))}var xt=n=>[Math.floor(n.x/16),Math.floor(n.z/16)],a6=n=>[Math.floor(n.x/16),Math.floor(n.y/16),Math.floor(n.z/16)],F2=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)},l5=class l5 extends Je{static restoreTransferred(e,t){let r=new l5;return t&&t.addEventListener("message",({data:i})=>{i.class===l5.restorerName&&i.type==="event"&&r.emit(i.eventName,...i.args)}),r}};d(l5,"restorerName","WorldViewWorker");var Ze=l5,Xe=class extends Je{constructor(t,r,i=new qe(0,0,0)){super();this.world=t;this.viewDistance=r;d(this,"spiralNumber",0);d(this,"gotPanicLastTime",!1);d(this,"panicChunksReload",()=>{});d(this,"loadedChunks",{});d(this,"inLoading",!1);d(this,"chunkReceiveTimes",[]);d(this,"lastChunkReceiveTime",0);d(this,"lastChunkReceiveTimeAvg",0);d(this,"panicTimeout");d(this,"lastPos");d(this,"eventListeners",{});d(this,"debugChunksInfo",{});d(this,"waitingSpiralChunksLoad",{});d(this,"addWaitTime",1);d(this,"keepChunksDistance",0);d(this,"isPlayground",!1);d(this,"allowPositionUpdate",!0);d(this,"lastBiomeId",null);d(this,"lastPosCheck",null);this.lastPos=new qe(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:Ze.restorerName,type:"event",eventName:i,args:r1(s)})}}return{__restorer:Ze.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]=xt(t),o=v5(this.viewDistance).map(([v,a])=>new qe((i+v)*16,0,(s+a)*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 F2(t,this.addWaitTime,async o=>{!s||this.loadedChunks[`${o.x},${o.z}`]||(this.world.getColumnAt(o)||(s=await new Promise(v=>{this.waitingSpiralChunksLoad[`${o.x},${o.z}`]=v})),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]=xt(this.lastPos),v=Math.abs(s-Math.floor(t.x/16)),a=Math.abs(o-Math.floor(t.z/16));if(v<=this.viewDistance&&a<=this.viewDistance){let u=await this.world.getColumnAt(t.y!==void 0?t:new qe(t.x,0,t.z));if(u){let f=u.toJson(),p={minY:u.minY??0,worldHeight:u.worldHeight??256};this.emit("loadChunk",{x:t.x,z:t.z,chunk:f,blockEntities:u.blockEntities,worldConfig:p,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[v,a,l]=s.split(",").map(Number);return t.world.getBlock(new qe(v,a,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]=xt(this.lastPos),[v,a]=xt(t);if(s!==v||o!==a||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[p,g]=f.split(",").map(Number),b=new qe(p,0,g),[A,y]=xt(b),w=Math.abs(v-A),S=Math.abs(a-y);(w>c||S>c)&&l.push(b)}for(let f of l)this.unloadChunk(f);let u=v5(this.viewDistance).map(([f,p])=>{let g=new qe((v+f)*16,0,(a+p)*16);if(!this.loadedChunks[`${g.x},${g.z}`])return g}).filter(f=>!!f);this.lastPos.update(t),this._loadChunks(u,t)}else this.emit("chunkPosUpdate",{pos:t}),this.lastPos.update(t)}};E();x();k();R();E();x();k();R();import Y2 from"minecraft-data";import v6 from"mc-assets/dist/blocksAtlases.json";import l6 from"mc-assets/dist/itemsAtlases.json";import Br from"mc-assets/dist/itemDefinitions.json";import c6 from"mc-assets/dist/blocksAtlasLatest.png";import d6 from"mc-assets/dist/blocksAtlasLegacy.png";import u6 from"mc-assets/dist/itemsAtlasLatest.png";import f6 from"mc-assets/dist/itemsAtlasLegacy.png";import h6 from"mc-assets/dist/textureReplacements/christmas";import{AtlasParser as $e}from"mc-assets/dist/atlasParser";import W2 from"mc-assets/dist/worldBlockProvider";E();x();k();R();var Mr=n5(D2(),1);import*as s1 from"three";E();x();k();R();E();x();k();R();var i1=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,v=0;this.context&&(o=Math.min(o,e),v=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(v.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 z2=class n1{constructor({logsPerSecond:e=20,samplesLog:t=100,samplesGraph:r=10,precision:i=2,minimal:s=!1,horizontal:o=!0,mode:v=0}={}){this.mode=v,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 n1.Panel("FPS","#0ff","#002"),0),this.msPanel=this.addPanel(new n1.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",a=>{a.preventDefault(),this.showPanel(++this.mode%this.container.children.length)},!1),this.mode=v,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 n1.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 v=0;v<t.logs.length;v++)r+=t.logs[v],t.logs[v]>i&&(i=t.logs[v]);let s=0,o=.01;for(let v=0;v<t.graph.length;v++)s+=t.graph[v],t.graph[v]>o&&(o=t.graph[v]);e&&e.update(r/Math.min(t.logs.length,this.samplesLog),s/Math.min(t.graph.length,this.samplesGraph),i,o,this.precision)}}};z2.Panel=i1;var L2=z2;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}}}}),c5=function(){return performance.now()},kt=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=c5()),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}(),Rt={Linear:function(n,e){var t=n.length-1,r=t*e,i=Math.floor(r),s=Rt.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=Rt.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=Rt.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=Rt.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,v=i*i,a=i*v;return(2*e-2*t+s+o)*a+(-3*e+3*t-2*s-o)*v+s*i+e}}},U2=function(){function n(){}return n.nextId=function(){return n._nextId++},n._nextId=0,n}(),kr=new kt,F0=function(){function n(e,t){t===void 0&&(t=kr),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=Rt.Linear,this._chainedTweens=[],this._onStartCallbackFired=!1,this._onEveryStartCallbackFired=!1,this._id=U2.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=c5()),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 v=e[o],a=Array.isArray(v),l=a?"array":typeof v,c=!a&&Array.isArray(r[o]);if(!(l==="undefined"||l==="function")){if(c){var u=r[o];if(u.length===0)continue;for(var f=[v],p=0,g=u.length;p<g;p+=1){var b=this._handleRelativeValue(v,u[p]);if(isNaN(b)){c=!1;break}f.push(b)}c&&(r[o]=f)}if((l==="object"||a)&&v&&!c){t[o]=a?[]:{};var A=v;for(var y in A)t[o][y]=A[y];i[o]=a?[]:{};var u=r[o];if(!this._isDynamic){var w={};for(var y in u)w[y]=u[y];r[o]=u=w}this._setupProperties(A,t[o],u,i[o],s)}else(typeof t[o]>"u"||s)&&(t[o]=v),a||(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=c5()),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=c5()),!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=kr),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=Rt.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=c5()),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 v=0,a=this._chainedTweens.length;v<a;v++)this._chainedTweens[v].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,v=r[s],a=Array.isArray(e[s]),l=Array.isArray(v),c=!a&&l;c?e[s]=this._interpolationFunction(v,i):typeof v=="object"&&v?this._updateProperties(e[s],o,v,i):(v=this._handleRelativeValue(o,v),typeof v=="number"&&(e[s]=o+(v-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 Rc=U2.nextId,pe=kr,kc=pe.getAll.bind(pe),Tc=pe.removeAll.bind(pe),Mc=pe.add.bind(pe),Sc=pe.remove.bind(pe),G2=pe.update.bind(pe);E();x();k();R();function Tr(n){if(n==="high-performance")return"high-performance";if(n==="low-power")return"low-power"}var a0=typeof globalThis.WorkerGlobalScope<"u"&&globalThis instanceof globalThis.WorkerGlobalScope,Sr=class{constructor(e,t=0){this.canvas=e;d(this,"stats");d(this,"stats2");d(this,"statsGl");d(this,"total",0);d(this,"denseMode");this.stats=new Mr.default,this.stats2=new Mr.default,this.statsGl=new L2({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()}},d5=class{constructor(e,t,r){this.initOptions=e;this.externalCanvas=t;d(this,"canvas");d(this,"renderer");d(this,"animationFrameId");d(this,"timeoutId");d(this,"lastRenderTime",0);d(this,"previousCanvasWidth",0);d(this,"previousCanvasHeight",0);d(this,"currentWidth",0);d(this,"currentHeight",0);d(this,"pendingResize",!1);d(this,"renderedFps",0);d(this,"fpsInterval");d(this,"stats");d(this,"paused",!1);d(this,"disconnected",!1);d(this,"preRender",()=>{});d(this,"render",e=>{});d(this,"postRender",()=>{});d(this,"sizeChanged",()=>{});d(this,"droppedFpsPercentage",0);d(this,"config");d(this,"onRender",[]);d(this,"inWorldRenderingConfig");d(this,"nonReactiveState");this.config=e.config,t?this.canvas=t:this.addToPage();try{let s=e.getRendererOptions?.()?.gpuPreference??"default";this.renderer=new s1.WebGLRenderer({canvas:this.canvas,preserveDrawingBuffer:!0,logarithmicDepthBuffer:!0,powerPreference:Tr(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=s1.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&&!a0&&(this.stats=new Sr(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=N2(),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(),G2(),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 N2(){let n=document.createElement("canvas");return n.id="viewer-canvas",document.body.appendChild(n),n}var Cr=()=>{let n=N2(),e=n.transferControlToOffscreen(),t=!1,r=(o,v)=>{},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}}}};import{ItemsRenderer as V2}from"mc-assets/dist/itemsRenderer";import{getLoadedItemDefinitionsStore as Pr}from"mc-assets/dist/stores";var o1=null;function Q2(n){return a0?((!o1||typeof o1.get!="function")&&(o1=Pr(Br)),o1):(K2(n),n.itemsDefinitionsStore)}function K2(n){a0||typeof n.itemsDefinitionsStore?.get=="function"||(n.itemsDefinitionsStore=Pr(n.sourceItemDefinitionsJson??Br))}var Tt=class{constructor(e){d(this,"sourceItemDefinitionsJson",Br);d(this,"itemsDefinitionsStore",Pr(this.sourceItemDefinitionsJson));d(this,"allReady",!1);d(this,"itemsAtlasImage");d(this,"blocksAtlasImage");d(this,"blocksAtlasJson");d(this,"itemsAtlasJson");d(this,"customBlockStates");d(this,"customModels");d(this,"customItemModelNames",{});d(this,"customTextures",{});d(this,"guiAtlas",null);d(this,"guiAtlasVersion",0);d(this,"itemsRenderer");d(this,"worldBlockProvider");d(this,"blockstatesModels",null);d(this,"version");d(this,"texturesVersion");d(this,"mcData");if(e){let t={...e};delete t.itemsDefinitionsStore,delete t.sourceItemDefinitionsJson,Object.assign(this,t),K2(this)}if(this.version){let t=globalThis.loadedData??globalThis.mcData;a0&&t?.entitiesByName?this.mcData=t:this.mcData=Y2(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"||t==="itemsDefinitionsStore"||t==="sourceItemDefinitionsJson"||(e[t]=this[t]));return e.customTextures={},delete e.itemsDefinitionsStore,delete e.sourceItemDefinitionsJson,e}},j2="1.21.4",Be=class Be extends Je{constructor(){super(...arguments);d(this,"sourceBlockStatesModels",null);d(this,"sourceBlocksAtlases",v6);d(this,"sourceItemsAtlases",l6);d(this,"currentResources");d(this,"itemsAtlasParser");d(this,"blocksAtlasParser");d(this,"currentConfig");d(this,"abortController",new AbortController);d(this,"_promiseAssetsReadyResolvers",Promise.withResolvers())}rebuildWorkerRenderers(t){if(a0&&!(!t.version||!t.blockstatesModels||!t.blocksAtlasJson)){if(this.blocksAtlasParser=new $e({latest:t.blocksAtlasJson},""),t.itemsAtlasJson)this.itemsAtlasParser=new $e({latest:t.itemsAtlasJson},"");else if(!this.itemsAtlasParser?.atlas?.latest){if(!this.sourceItemsAtlases||Object.keys(this.sourceItemsAtlases).length===0)return;this.itemsAtlasParser=new $e(this.sourceItemsAtlases,"")}t.itemsRenderer=new V2(t.version,t.blockstatesModels,this.itemsAtlasParser,this.blocksAtlasParser),t.worldBlockProvider=W2(t.blockstatesModels,this.blocksAtlasParser.atlas,j2)}}static restoreTransferred(t,r){let i=new Be,s=o=>{i.currentResources=new Tt(o),i.rebuildWorkerRenderers(i.currentResources)};return s(t.currentResources),r&&r.addEventListener("message",({data:o})=>{o.class===Be.restorerName&&(o.type==="newResources"&&s(o.currentResources),o.type==="event"&&i.emit(o.eventName,...o.args))}),i}enrichTransferSnapshot(t){return t&&(this.itemsAtlasParser?.atlas?.latest&&(t.itemsAtlasJson=this.itemsAtlasParser.atlas.latest),this.blocksAtlasParser?.atlas?.latest&&(t.blocksAtlasJson=this.blocksAtlasParser.atlas.latest),t)}prepareForTransfer(t){if(t){let r=this.emit.bind(this);this.emit=(i,...s)=>{if(r(i,...s),t.postMessage({class:Be.restorerName,type:"event",eventName:i,args:r1(s)}),i==="assetsTexturesUpdated"||i==="assetsInventoryReady"){let o=this.enrichTransferSnapshot(this.currentResources?.prepareForTransfer());t.postMessage({class:Be.restorerName,type:"newResources",currentResources:o})}}}return{__restorer:Be.restorerName,currentResources:this.enrichTransferSnapshot(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=Y2(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 V2(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,h6);let s=new $e(this.sourceBlocksAtlases,c6,d6),o=Object.keys(t.customTextures.blocks?.textures??{}),{atlas:v,canvas:a}=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 $e({latest:v},a.toDataURL()),t.blocksAtlasImage=await createImageBitmap(a),t.blocksAtlasJson=this.blocksAtlasParser.atlas.latest,t.worldBlockProvider=W2(t.blockstatesModels,this.blocksAtlasParser.atlas,j2)}async recreateItemsAtlas(t=this.currentResources){let r=new $e(this.sourceItemsAtlases,u6,f6),i=Object.keys(t.customTextures.items?.textures??{}),{atlas:s,canvas:o}=await r.makeNewAtlas(t.texturesVersion,v=>{let a=t.customTextures.items?.textures[v];if(a)return a},t.customTextures.items?.tileSize,void 0,i);this.itemsAtlasParser=new $e({latest:s},o.toDataURL()),t.itemsAtlasImage=await createImageBitmap(o),t.itemsAtlasJson=this.itemsAtlasParser.atlas.latest}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}};d(Be,"restorerName","ResourcesManager");var fe=Be;E();x();k();R();var oe=class extends Error{constructor(t,r){super(t);d(this,"failure");this.name="MesherWorkerPreloadError",this.failure=r}};function m6(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 p6=45e3,g6=1e4;async function J2(n){if(F.env.SINGLE_FILE_BUILD)return;let e=n?.fetchTimeoutMs??p6,t=n?.pingTimeoutMs??g6,r=n?.script??"mesher.js",i=new URL(r,document.baseURI).href,s;try{let u=new AbortController,f=window.setTimeout(()=>u.abort(),e);try{s=await fetch(i,{credentials:"same-origin",cache:"force-cache",signal:u.signal})}finally{clearTimeout(f)}}catch(u){let f=u;throw f?.name==="AbortError"?new oe(`Mesher script fetch timed out after ${e}ms (${i}).`,{phase:"fetch",code:"timeout"}):new oe(`Mesher script fetch failed (network): ${f?.message??u}. URL: ${i}`,{phase:"fetch",code:"network",detail:String(f?.message??u)})}if(!s.ok)throw new oe(`Mesher script HTTP ${s.status} ${s.statusText}: ${i}`,{phase:"fetch",code:"bad-status",status:s.status});let o=s.headers.get("content-type")??"",v=await s.arrayBuffer();if(v.byteLength===0)throw new oe(`Mesher script response was empty: ${i}`,{phase:"fetch",code:"invalid-body",hint:"empty"});let a=Math.min(1024,v.byteLength),l=new TextDecoder().decode(v.slice(0,a)).trimStart();if(l.startsWith("<!DOCTYPE")||l.startsWith("<html")||l.startsWith("<HTML"))throw new oe(`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(u){let f=u instanceof Error?u.message:String(u);throw new oe(`Could not construct Worker for mesher (${i}): ${f}`,{phase:"worker",code:"construct-failed",message:f})}await new Promise((u,f)=>{let p=!1,g=window.setTimeout(()=>{p||(p=!0,b(),f(new oe(`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 M=c;c=void 0,M&&(M.removeEventListener("message",w),M.removeEventListener("error",S),M.removeEventListener("messageerror",C),M.terminate())},A=()=>{p||(p=!0,b(),u())},y=M=>{p||(p=!0,b(),f(M))};function w(M){m6(M.data)&&A()}function S(M){y(new oe(`Mesher worker script failed to load or threw during startup: ${M.message||"unknown"} @ ${i}`,{phase:"worker",code:"script-error",message:M.message}))}function C(){y(new oe(`Mesher worker message channel error (structured clone / deserialization). URL: ${i}`,{phase:"ping",code:"messageerror"}))}c.addEventListener("message",w),c.addEventListener("error",S),c.addEventListener("messageerror",C);try{c.postMessage({type:"mc-web-ping",t:performance.now(),workerIndex:0})}catch(M){let I=M instanceof Error?M.message:String(M);y(new oe(`Failed to post mc-web-ping to mesher worker: ${I}`,{phase:"ping",code:"post-failed",detail:I}))}})}var Z2=class{constructor(e={},t=new fe){this.resourcesManager=t;d(this,"waitBackendLoadPromises",[]);d(this,"onWorldStart");d(this,"onBeforeWorldStart");d(this,"worldView");d(this,"config");d(this,"menuBackgroundOptions");d(this,"inWorldRenderingConfig");d(this,"backend");d(this,"backendLoader");d(this,"currentState");d(this,"currentDisplay",null);d(this,"playerState",{reactive:Ar()});d(this,"rendererState");d(this,"nonReactiveState");d(this,"worldReady");d(this,"resolveWorldReady");d(this,"lastCamUpdate",0);d(this,"getRendererOptions");this.config={...P2,...e.config},this.menuBackgroundOptions={...e.config?.menuBackground,...e.menuBackground},this.inWorldRenderingConfig=q2({...a5,...e.rendererConfig});let r=Ke();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 J2({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 b6(0,64,0);this.worldView=new Xe(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 v;if(this.backend){let a=this.backend.startWorld(o);a&&typeof a.then=="function"&&(v=a)}return this.currentState={method:"startWorld",args:[o]},await v,this.resolveWorldReady(),this.onWorldStart?.(),!!v}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=q2(Ke().reactive),this.nonReactiveState=Ke().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 S6}from"valtio/vanilla";E();x();k();R();E();x();k();R();var et=["galaxy","nether","end","cyber","light"],tt=["cruise","barrel","dive","orbit","snake"],u5={galaxy:"Galaxy",nether:"Nether",end:"The End",cyber:"Cyber",light:"Light Space"},f5={cruise:"Cruise",barrel:"Barrel",dive:"Dive",orbit:"Orbit",snake:"Snake"},rt=["mixed","stainedGlass","wool","construction","glow","world"],h5={mixed:"Mixed",stainedGlass:"Stained glass",wool:"Wool",construction:"Construction",glow:"Glow",world:"World (grass & ores)"};E();x();k();R();var ge={mode:"futuristic",minecraftTextures:!0,futuristicScene:"light",futuristicCamera:"dive",futuristicBlockGroup:"stainedGlass",futuristicCameraSpeedPercent:80,futuristicBlockSpeedPercent:40},we=n=>n/100,m5={camera:we(ge.futuristicCameraSpeedPercent),block:we(ge.futuristicBlockSpeedPercent)};var y6={off:0,holes:1,texIndex:2,faces:3,atlasAlpha:4};function Ir(n){return y6[n]}var it=ge,X2={rendererWorldPerformance:"normal",rendererMeshersCountOverride:null,starfieldRendering:!0,defaultSkybox:!0,menuBackgroundMode:it.mode,menuBackgroundMinecraftTextures:it.minecraftTextures,menuBackgroundFuturisticScene:it.futuristicScene,menuBackgroundFuturisticCamera:it.futuristicCamera,menuBackgroundFuturisticBlockGroup:it.futuristicBlockGroup,menuBackgroundFuturisticCameraSpeed:it.futuristicCameraSpeedPercent,menuBackgroundFuturisticBlockSpeed:it.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 _6(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 $2={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:et.map(n=>[n,u5[n]])},menuBackgroundFuturisticCamera:{possibleValues:tt.map(n=>[n,f5[n]])},menuBackgroundFuturisticBlockGroup:{possibleValues:rt.map(n=>[n,h5[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"]]}},es=[{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 Hr(n,e,t,r,i){let s=n.getImageData(e,t,r,i);for(let o=0;o<r;o++)for(let v=0;v<i;v++){let a=(o+v*r)*4;if(s.data[a+3]!==255)return!0}return!1}function a1(n){return n/64}function ts(n,e,t){if(t){if(Hr(n,0,0,e,e))return}else if(Hr(n,0,0,e,e/2))return;let r=a1(e),i=(s,o,v,a)=>n.clearRect(s*r,o*r,v*r,a*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 w6(n,e){n.save(),n.scale(-1,1);let t=a1(e),r=(i,s,o,v,a,l)=>n.drawImage(n.canvas,i*t,s*t,o*t,v*t,-a*t,l*t,-o*t,v*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 Or(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),w6(r,i),ts(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),ts(r,n.width,!0)}function A6(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 Fr(n,e){let t=A6(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 E6(n,e,t,r,i){let s=n.getImageData(e,t,r,i);for(let o=0;o<r;o++)for(let v=0;v<i;v++){let a=(o+v*r)*4;if(!(s.data[a+0]===0&&s.data[a+1]===0&&s.data[a+2]===0&&s.data[a+3]===255))return!1}return!0}function x6(n,e,t,r,i){let s=n.getImageData(e,t,r,i);for(let o=0;o<r;o++)for(let v=0;v<i;v++){let a=(o+v*r)*4;if(!(s.data[a+0]===255&&s.data[a+1]===255&&s.data[a+2]===255&&s.data[a+3]===255))return!1}return!0}function Dr(n){let e=a1(n.width),t=n.getContext("2d",{willReadFrequently:!0}),r=(v,a,l,c)=>Hr(t,v*e,a*e,l*e,c*e),i=(v,a,l,c)=>E6(t,v*e,a*e,l*e,c*e),s=(v,a,l,c)=>x6(t,v*e,a*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 zr(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=a1(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 T6 from"mc-assets/dist/other-textures/latest/entity/player/wide/steve.png";E();x();k();R();import*as he from"three";E();x();k();R();var R6=()=>{if(typeof OffscreenCanvas>"u")return!1;try{let n=new OffscreenCanvas(1,1);return(n.getContext("webgl2")||n.getContext("webgl"))!==null}catch{return!1}},k6=R6(),V0=(n,e)=>{if(k6||typeof document>"u")return new OffscreenCanvas(n,e);let t=document.createElement("canvas");return t.width=n,t.height=e,t};async function nt(n){let t=await(await fetch(n)).blob();return createImageBitmap(t)}var k0=(n,e=!1)=>{n instanceof he.Mesh&&(n.geometry?.dispose?.(),n.material?.dispose?.()),n.children&&n.children.forEach(t=>k0(t,e)),e&&n instanceof he.Mesh&&n.material?.map?.dispose?.()},Lr={},rs={},p5=n=>{let e=new he.Texture,t=nt(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}},Mt=async n=>p5(n).texture,Pe=n=>{let e=V0(n.width,n.height);e.getContext("2d").drawImage(n,0,0);let r=new he.Texture(e);return r.magFilter=he.NearestFilter,r.minFilter=he.NearestFilter,r};function St(n){let{texture:e,promise:t}=p5(n);return e.magFilter=he.NearestFilter,e.minFilter=he.NearestFilter,t.catch(r=>{}),e}async function v1(n,e,t){if(!Lr[n]){let{promise:i,resolve:s}=Promise.withResolvers(),o=p5(n);Lr[n]=o.texture,o.promise.then(s),rs[n]=i}e(Lr[n]),rs[n].then(()=>{t?.()})}var re=T6,Ku=Mt(re),is={apiEnabled:!0},l1=n=>{Object.assign(is,n)};async function Ie(n,e){if(!is.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 Ae(n){n.startsWith("data:")||(n=await M6(n.replace("http://","https://")));let e=await nt(n),t=V0(64,64);return Or(t,e),{canvas:t,image:e}}var M6=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:we(n.menuBackgroundFuturisticCameraSpeed),futuristicBlockSpeed:we(n.menuBackgroundFuturisticBlockSpeed)}}function C6(n,e){let t=n.futuristic;t&&(t.setScene?.(e.menuBackgroundFuturisticScene),t.setCamera?.(e.menuBackgroundFuturisticCamera),t.setBlockGroup?.(e.menuBackgroundFuturisticBlockGroup),t.setCameraSpeed?.(we(e.menuBackgroundFuturisticCameraSpeed)),t.setBlockSpeed?.(we(e.menuBackgroundFuturisticBlockSpeed)))}function B6(n){return n.rendererMesher!=="legacy-js"}function P6(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 I6(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 H6(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 O6(n,e,t={}){let r=n.inWorldRenderingConfig,i=B6(e);r.showChunkBorders=e.showChunkBorders,r.futuristicReveal=e.rendererFuturisticReveal,P6(n,e,i),r.renderEntities=e.renderEntities,H6(n,e,t),I6(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,l1({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=Ir(e.rendererShaderCubeDebugMode)}function of(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 af(n,e,t={}){n.bindRendererOptions(()=>e);let r=t.getWindowFocused?.()??!0,i=()=>{let s=e;if(O6(n,s,{isSafari:t.isSafari,isCypress:t.isCypress,windowFocused:r}),n.currentDisplay==="menu"){let o=n.backend?.getMenuBackground?.();o&&C6(o,s)}};return i(),t.onRegisterFocusHandlers?.({onFocus:()=>{r=!0,i()},onBlur:()=>{r=!1,i()}}),S6(e,i)}function vf(n,e,t){n.inWorldRenderingConfig.enableLighting=!t||e}E();x();k();R();import{proxy as F6}from"valtio";var ns=()=>F6({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}),D6=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"}}),z6=()=>({reactive:ns()}),ss=(n,e,t)=>({...e,"minecraft:date":new Date});E();x();k();R();E();x();k();R();import*as V5 from"three";import{Vec3 as e9}from"vec3";E();x();k();R();import{proxy as L6,getVersion as as,subscribe as vs}from"valtio";import{Vec3 as ls}from"vec3";function cs(n,e){let t=e??globalThis;return t.addEventListener("message",r=>{let{type:i,args:s,msgId:o}=r.data;if(n[i]){let v=n[i](...s);v instanceof Promise&&v.then(a=>{t.postMessage({type:"result",msgId:o,args:[a]})})}}),null}var ds=(n,e=!0)=>{let t=0;return new Proxy({},{get(r,i){return i==="transfer"?(...s)=>new Proxy({},{get(o,v){return(...a)=>{n.postMessage({type:v,args:a},s)}}}):(...s)=>{let o=t++,v=e?s.filter(a=>a instanceof ArrayBuffer||a instanceof MessagePort||typeof ImageBitmap<"u"&&a instanceof ImageBitmap||typeof OffscreenCanvas<"u"&&a instanceof OffscreenCanvas||typeof ImageData<"u"&&a instanceof ImageData):[];return n.postMessage({type:i,msgId:o,args:s},v),{then(a){let l=({data:c})=>{c.type==="result"&&c.msgId===o&&(a(c.args[0]),n.removeEventListener("message",l))};n.addEventListener("message",l)}}}}})};var us=(n,e,t,r)=>{try{t.postMessage({type:"sync",syncId:n,value:c1(e)}),g5.toWorker++,globalThis.debugSyncMessagesOutgoing??(globalThis.debugSyncMessagesOutgoing=0),globalThis.debugSyncMessagesOutgoing++}catch{Ct(e)}},g5={toWorker:0,fromWorker:0};typeof window<"u"&&setInterval(()=>{globalThis.debugWorkerSyncStats={...g5},g5.toWorker=0,g5.fromWorker=0},1e3);var U6=()=>Math.random().toString(36).slice(2,15)+Math.random().toString(36).slice(2,15),fs=(n,e,t)=>{Object.assign(n,d1(e,[],t,!1))},os=(n,e,t,r,i)=>{if(!n.__syncToWorker&&!n.__syncFromWorker&&!r)return;let s=U6();if(n.__syncId=s,n.__syncToWorker||r){let o=()=>{us(s,e,t,`toWorker:${i}`)};r&&vs(e,o);let v=n.__syncToWorkerInterval??0;v>0&&setInterval(o,v)}e.__syncFromWorker&&t.addEventListener("message",o=>{o.data.type==="sync"&&o.data.syncId===s&&(g5.fromWorker++,fs(e,o.data.value,t))})},hs=n=>({__restorer:"Map",__mapEntries:Array.from(n.entries())}),ms=n=>({__restorer:"Set",__setValues:[...n]}),ps=n=>n instanceof Set||Object.prototype.toString.call(n)==="[object Set]",gs=n=>n instanceof Map||Object.prototype.toString.call(n)==="[object Map]",G6=n=>Object.keys(n).filter(e=>!e.startsWith("__")).sort((e,t)=>Number(e)-Number(t)).map(e=>n[e]),c1=n=>{if(gs(n))return hs(n);if(ps(n))return ms(n);if(as(n)===void 0)return n;if(Array.isArray(n))return n.map(c1);if(typeof n=="object"&&n!==null){let e={};for(let t in n)Object.prototype.hasOwnProperty.call(n,t)&&(e[t]=c1(n[t]));return e}return n},b5=(n,e,t=!0,r=!0,i=!1)=>{var v,a;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 WeakMap||n[l]instanceof WeakSet,gs(n[l])){o[l]=hs(n[l]);continue}if(ps(n[l])){o[l]=ms(n[l]);continue}if(n[l]instanceof ls){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=as(n[l])!==void 0;o[l]=c?c1(n[l]):n[l];let u=n[l].__syncToWorker!==!1&&!i&&c&&!n[l].__syncFromWorker;if((v=o[l]).__syncToWorker??(v.__syncToWorker=u),c&&((a=o[l]).__valtio??(a.__valtio=!0)),o[l].__syncToWorker&&c){os(o[l],s[l],e,!0,l);continue}os(o[l],s[l],e,!1,l),o[l]=b5(o[l],e,t,!1,c)}}return o},Ct=(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&&Ct(n[t],[...e,t]);try{structuredClone(n[t])}catch{}}},N6=(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&&fs(n,i.data.value,e)}),n.__syncFromWorker){let i=()=>{us(r,n,e,`fromWorker:${t}`)};n.__valtio&&vs(n,i);let s=n.__syncFromWorkerInterval??0;s>0&&setInterval(i,s)}},W6=[{restorerName:"Map",restoreTransferred(n,e){if(Array.isArray(n))return new Map(n);let t=n.__mapEntries??n.entries;return Array.isArray(t)?new Map(t):t!=null&&typeof t=="object"&&typeof t!="function"?new Map(Object.entries(t)):new Map}},{restorerName:"Set",restoreTransferred(n,e){if(Array.isArray(n))return new Set(n);let t=n.__setValues??n.values;return Array.isArray(t)?new Set(t):t!=null&&typeof t=="object"&&typeof t!="function"?new Set(G6(t)):new Set}},{restorerName:"Vec3",restoreTransferred(n,e){return new ls(n.x,n.y,n.z)}}];var d1=(n,e,t,r=!0)=>{let i=[...W6,...e],s=(o,v)=>{if(o==null||typeof o!="object")return o;if(o.__restorer){let a=i.find(c=>c.restorerName?c.restorerName===o.__restorer:c.name===o.__restorer);if(a)return a.restoreTransferred(o,t);let l=new Error(`Restorer ${o.__restorer} not found`);if(typeof r=="function")r(l);else if(r)throw l;return o}if(Array.isArray(o))return o.map((a,l)=>s(a,`${v}[${l}]`));for(let a in o){if(!Object.prototype.hasOwnProperty.call(o,a))continue;let l=o[a];l!=null&&typeof l=="object"&&(o[a]=s(l,`${v}.${a}`))}return o.__valtio&&(o=L6(o)),N6(o,t,v),o};return s(n,"root")};E();x();k();R();var u1=class{constructor(e){this.nonReactiveState=e;d(this,"events",[]);d(this,"frozenEvents",[]);d(this,"lastSecondEvents",[]);d(this,"currentFrameStartTime",null);d(this,"lastInteractionTime",0);d(this,"lastSecondUpdateTime",0);d(this,"timeWindowMs",5e3);d(this,"lastSecondWindowMs",1e3);d(this,"maxEvents",500);d(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 Ue}from"vec3";import jv from"prismarine-chat";E();x();k();R();var V6=(n,e)=>{try{return JSON.parse(n)}catch{return null}},j6={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"},f1=(n,e,t,r=s=>{},i=(s,o)=>V0(s,o))=>{let v=[16,9],a=v[0]-v[1],l=a/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 u=i(16*40,a*40),f=u.getContext("2d");r(f);let p=("front_text"in n?n.front_text.color:n.Color)||"black";for(let[g,b]of c.slice(0,4).entries())b!=="null"&&Ur(b,t,u,64,p,64*(g+1)+(e?0:-8));return u},Ur=(n,e,t,r,i,s=0)=>{let o=!1,v=typeof n=="string"&&(n?.startsWith("{")||n?.startsWith('"'))?V6(n??'""',"sign text"):n;if(!v||typeof v!="object"&&typeof v!="string")return;let a=t.getContext("2d");if(!a)throw new Error("Could not get 2d context");a.imageSmoothingEnabled=!1,a.font=`${r}px mojangles`;let l=new e(v),c=[],u=!1,f="",p=s,g=[],b=(S,C)=>{S.text!==null&&S.text!==void 0&&S.text;let M=S.text===null||S.text===void 0?void 0:String(S.text),I={color:S.color??C?.color,underlined:S.underlined??C?.underlined,strikethrough:S.strikethrough??C?.strikethrough,bold:S.bold??C?.bold,italic:S.italic??C?.italic};if(u=u||I.underlined||I.strikethrough||!1,M?.includes(`
285
+ `;q1=6,ft={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},X3={TEX_INDEX_BITS:12,DIAGONAL_FLAG_SHIFT:12,SECTION_Y_SHIFT:13,SECTION_Y_BITS:5,EMPTY_SHIFT:18,SPARE_BITS:13}});var Z1,$3=X0(()=>{"use strict";E();x();k();R();Z1=class{constructor(e){d(this,"atlasWidth");d(this,"atlasHeight");d(this,"tileSize");d(this,"tilesPerRow");d(this,"maxTiles");d(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 ce from"three";var X1,ea=X0(()=>{"use strict";E();x();k();R();X1=class n{constructor(){d(this,"entries",[{r:1,g:1,b:1}]);d(this,"colorToIndex",new Map);d(this,"categoryBiomeToIndex",new Map);d(this,"texture",null);d(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),v=`${i}:${s}`,a=this.categoryBiomeToIndex.get(v);if(a!==void 0)return a;let l=this.colorToIndex.get(o);if(l!==void 0)return this.categoryBiomeToIndex.set(v,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(v,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 ce.DataTexture(e,256,1,ce.RGBAFormat,ce.FloatType);return t.minFilter=ce.NearestFilter,t.magFilter=ce.NearestFilter,t.wrapS=ce.ClampToEdgeWrapping,t.wrapT=ce.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,v=(i&255)/255;return[s,o,v]}if(e.grass){let i=r(e.grass.default);for(let{keys:s,color:o}of e.grass.data??[]){let v=r(o);for(let a of s)t.add(v[0],v[1],v[2],"grass",a)}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 v=r(o);for(let a of s)t.add(v[0],v[1],v[2],"foliage",a)}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 v=r(o);for(let a of s)t.add(v[0],v[1],v[2],"redstone",a)}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 v=r(o);for(let a of s)t.add(v[0],v[1],v[2],"constant",a)}t.add(i[0],i[1],i[2],"constant","default")}return t}}});import ta from"mc-assets/dist/blocksAtlases.json";function wv(){let n=globalThis.loadedData?.tints;return n||(ra||(ra=!0),null)}function tr(){let n=wv();if(!n)return null;if($1||($1=X1.fromTintsData(n),$1.createTexture()),!zi){let e=ta.latest??ta;zi=new Z1({width:e.width,height:e.height,tileSize:e.tileSize??16,suSv:e.suSv??16,textures:e.textures??{}})}return{tintPalette:$1,textureIndexMapping:zi}}function ia(){return 1<<X3.EMPTY_SHIFT>>>0}var er,$1,zi,ra,Kt=X0(()=>{"use strict";E();x();k();R();ht();$3();ea();er=4,$1=null,zi=null,ra=!1});import*as B0 from"three";function Av(n,e){let t=new B0.InstancedBufferGeometry,r=new Float32Array(q1*3);t.setAttribute("position",new B0.BufferAttribute(r,3));let i=new Uint32Array(e),s=new Uint32Array(e),o=new Uint32Array(e),v=new Uint32Array(e),a=er;for(let l=0;l<e;l++)i[l]=n[l*a],s[l]=n[l*a+1],o[l]=n[l*a+2],v[l]=n[l*a+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(v,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 Ev(n){n.raycast=(e,t)=>{let{geometry:r}=n;if(!r.boundingBox||(na.copy(r.boundingBox).applyMatrix4(n.matrixWorld),!e.ray.intersectBox(na,Li)))return;let i=e.ray.origin.distanceTo(Li);t.push({distance:i,point:Li.clone(),object:n})}}function rr(n,e){let t=Av(n.words,n.count),r=new B0.Mesh(t,e);return r.name="shaderMesh",r.matrixAutoUpdate=!1,r.frustumCulled=!1,Ev(r),r}function Ui(n){n.geometry.dispose()}var na,Li,Gi=X0(()=>{"use strict";E();x();k();R();ht();Kt();na=new B0.Box3,Li=new B0.Vector3});var ca={};K5(ca,{applyWorldGeometryExport:()=>kv,createMeshesFromExport:()=>va,downloadWorldGeometry:()=>Ni,exportWorldGeometry:()=>oa,loadTextureFromDataUrl:()=>la,loadWorldGeometryFromUrl:()=>xv});import*as P0 from"three";function oa(n,e,t,r=!1){let i=[];for(let[o,v]of Object.entries(n.sectionObjects)){let a=v.children.find(A=>A.name==="mesh");if(!a?.geometry)continue;let{geometry:l}=a,c=l.getAttribute("position"),u=l.getAttribute("normal"),f=l.getAttribute("color"),p=l.getAttribute("uv"),g=l.index;if(!c||!g)continue;let b=n.sceneOrigin.getWorldPosition(a);i.push({key:o,position:{x:b?.x??n.sceneOrigin.toWorldX(a.position.x),y:b?.y??n.sceneOrigin.toWorldY(a.position.y),z:b?.z??n.sceneOrigin.toWorldZ(a.position.z)},geometry:{positions:[...c.array],normals:u?[...u.array]:[],colors:f?[...f.array]:[],uvs:p?[...p.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"),v=n.material.map,{image:a}=v;a&&(o.width=a.width,o.height=a.height,o.getContext("2d").drawImage(a,0,0),s.textureAtlasDataUrl=o.toDataURL("image/png"))}return s}function Ni(n,e,t,r="world-geometry.json",i=!1){let s=oa(n,e,t,i),o=JSON.stringify(s),v=new Blob([o],{type:"application/json"}),a=URL.createObjectURL(v),l=document.createElement("a");l.href=a,l.download=r,l.click(),URL.revokeObjectURL(a)}async function xv(n){let e=await fetch(n);if(!e.ok)throw new Error(`Failed to fetch world geometry: ${e.statusText}`);return e.json()}function aa(n){let e=n.map??n.map;if(!e)return null;let t=J1();t.uniforms.u_atlas.value=e;let r=tr();if(!r)return null;let{tintPalette:i}=r;return i.isReady()||i.createTexture(),t.uniforms.u_tintPalette.value=i.getTexture(),t}function va(n,e,t){let r=[],i=t??aa(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 u=Math.max(...s.geometry.indices)>65535?Uint32Array:Uint16Array;l.setIndex(new P0.BufferAttribute(new u(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 a=s.shaderCubes;if(a&&a.count>0&&i){let l=rr(a,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 la(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 kv(n,e){let{scene:t,renderUpdateEmitter:r,material:i}=n,s=t.getObjectByName(sa);s&&(t.remove(s),Rv(s));let o=!!e.textureAtlasDataUrl,v;if(o&&e.textureAtlasDataUrl){let u=await la(e.textureAtlasDataUrl);v=new P0.MeshLambertMaterial({map:u,vertexColors:!0,transparent:!0,alphaTest:.1}),v.name="geometry-export-material"}else v=i;let a=e.sections.some(u=>(u.shaderCubes?.count??0)>0)?aa(v):null,l=va(e,v,a),c=new P0.Group;c.name=sa,o&&(c.userData.geometryExportMaterial=v);for(let u of l)c.add(u);return t.add(c),r.emit("update"),l.length}var sa,Rv,Wi=X0(()=>{"use strict";E();x();k();R();Kt();ht();Gi();sa="geometry-export-root";Rv=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 B2}from"valtio";E();x();k();R();E();x();k();R();var br=()=>({longRenderTime:!1,constantLongRenderTime:!1,tooManyEntities:!1,tooManyTextures:!1,unknownReason:!1});E();x();k();R();var $5=30;var yr=45,_r=100;E();x();k();R();var o5=class{constructor(e){this.factors=e;d(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,v=s>=8&&o/s>=.65,a=e.loadedTextureCount>=100,l=t&&e.entitiesMs>=8&&r<=20,u=t&&!(i||v||l||a);this.factors.longRenderTime=i,this.factors.constantLongRenderTime=v,this.factors.tooManyEntities=l,this.factors.tooManyTextures=a,this.factors.unknownReason=u}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 n6=[{key:"longRenderTime",code:"LR"},{key:"constantLongRenderTime",code:"CLR"},{key:"tooManyEntities",code:"ENT"},{key:"tooManyTextures",code:"TEX"},{key:"unknownReason",code:"UNK"}];function wr(n){let e=n6.filter(({key:t})=>n[t]).map(({code:t})=>t);return e.length>0?e.join("+"):""}var a5={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:{}},P2={fpsLimit:void 0,sceneBackground:"lightblue",timeoutRendering:!1},dl=(n={})=>B2({...a5,...n}),Ke=()=>({reactive:B2({world:{chunksLoaded:new Set,heightmaps:new Map,allChunksLoaded:!1,mesherWork:!1,instabilityFactors:br(),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 s6}from"valtio";var Ar=()=>s6({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}),I2=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"}}),H2=()=>({reactive:Ar()});E();x();k();R();import{Vec3 as b6}from"vec3";import{proxy as q2}from"valtio";E();x();k();R();E();x();k();R();E();x();k();R();E();x();k();R();var e1={},O2=!1;function o6(){if(O2)return e1;O2=!0;var n=typeof Reflect=="object"?Reflect:null,e=n&&typeof n.apply=="function"?n.apply:function(M,I,B){return Function.prototype.apply.call(M,I,B)},t;n&&typeof n.ownKeys=="function"?t=n.ownKeys:Object.getOwnPropertySymbols?t=function(M){return Object.getOwnPropertyNames(M).concat(Object.getOwnPropertySymbols(M))}:t=function(M){return Object.getOwnPropertyNames(M)};function r(C){}var i=Number.isNaN||function(M){return M!==M};function s(){s.init.call(this)}e1=s,e1.once=y,s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var o=10;function v(C){if(typeof C!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof C)}Object.defineProperty(s,"defaultMaxListeners",{enumerable:!0,get:function(){return o},set:function(C){if(typeof C!="number"||C<0||i(C))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+C+".");o=C}}),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(M){if(typeof M!="number"||M<0||i(M))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+M+".");return this._maxListeners=M,this};function a(C){return C._maxListeners===void 0?s.defaultMaxListeners:C._maxListeners}s.prototype.getMaxListeners=function(){return a(this)},s.prototype.emit=function(M){for(var I=[],B=1;B<arguments.length;B++)I.push(arguments[B]);var H=M==="error",G=this._events;if(G!==void 0)H=H&&G.error===void 0;else if(!H)return!1;if(H){var O;if(I.length>0&&(O=I[0]),O instanceof Error)throw O;var j=new Error("Unhandled error."+(O?" ("+O.message+")":""));throw j.context=O,j}var J=G[M];if(J===void 0)return!1;if(typeof J=="function")e(J,this,I);else for(var Z=J.length,e0=g(J,Z),B=0;B<Z;++B)e(e0[B],this,I);return!0};function l(C,M,I,B){var H,G,O;if(v(I),G=C._events,G===void 0?(G=C._events=Object.create(null),C._eventsCount=0):(G.newListener!==void 0&&(C.emit("newListener",M,I.listener?I.listener:I),G=C._events),O=G[M]),O===void 0)O=G[M]=I,++C._eventsCount;else if(typeof O=="function"?O=G[M]=B?[I,O]:[O,I]:B?O.unshift(I):O.push(I),H=a(C),H>0&&O.length>H&&!O.warned){O.warned=!0;var j=new Error("Possible EventEmitter memory leak detected. "+O.length+" "+String(M)+" listeners added. Use emitter.setMaxListeners() to increase limit");j.name="MaxListenersExceededWarning",j.emitter=C,j.type=M,j.count=O.length}return C}s.prototype.addListener=function(M,I){return l(this,M,I,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(M,I){return l(this,M,I,!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 u(C,M,I){var B={fired:!1,wrapFn:void 0,target:C,type:M,listener:I},H=c.bind(B);return H.listener=I,B.wrapFn=H,H}s.prototype.once=function(M,I){return v(I),this.on(M,u(this,M,I)),this},s.prototype.prependOnceListener=function(M,I){return v(I),this.prependListener(M,u(this,M,I)),this},s.prototype.removeListener=function(M,I){var B,H,G,O,j;if(v(I),H=this._events,H===void 0)return this;if(B=H[M],B===void 0)return this;if(B===I||B.listener===I)--this._eventsCount===0?this._events=Object.create(null):(delete H[M],H.removeListener&&this.emit("removeListener",M,B.listener||I));else if(typeof B!="function"){for(G=-1,O=B.length-1;O>=0;O--)if(B[O]===I||B[O].listener===I){j=B[O].listener,G=O;break}if(G<0)return this;G===0?B.shift():b(B,G),B.length===1&&(H[M]=B[0]),H.removeListener!==void 0&&this.emit("removeListener",M,j||I)}return this},s.prototype.off=s.prototype.removeListener,s.prototype.removeAllListeners=function(M){var I,B,H;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[M]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete B[M]),this;if(arguments.length===0){var G=Object.keys(B),O;for(H=0;H<G.length;++H)O=G[H],O!=="removeListener"&&this.removeAllListeners(O);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(I=B[M],typeof I=="function")this.removeListener(M,I);else if(I!==void 0)for(H=I.length-1;H>=0;H--)this.removeListener(M,I[H]);return this};function f(C,M,I){var B=C._events;if(B===void 0)return[];var H=B[M];return H===void 0?[]:typeof H=="function"?I?[H.listener||H]:[H]:I?A(H):g(H,H.length)}s.prototype.listeners=function(M){return f(this,M,!0)},s.prototype.rawListeners=function(M){return f(this,M,!1)},s.listenerCount=function(C,M){return typeof C.listenerCount=="function"?C.listenerCount(M):p.call(C,M)},s.prototype.listenerCount=p;function p(C){var M=this._events;if(M!==void 0){var I=M[C];if(typeof I=="function")return 1;if(I!==void 0)return I.length}return 0}s.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]};function g(C,M){for(var I=new Array(M),B=0;B<M;++B)I[B]=C[B];return I}function b(C,M){for(;M+1<C.length;M++)C[M]=C[M+1];C.pop()}function A(C){for(var M=new Array(C.length),I=0;I<M.length;++I)M[I]=C[I].listener||C[I];return M}function y(C,M){return new Promise(function(I,B){function H(O){C.removeListener(M,G),B(O)}function G(){typeof C.removeListener=="function"&&C.removeListener("error",H),I([].slice.call(arguments))}S(C,M,G,{once:!0}),M!=="error"&&w(C,H,{once:!0})})}function w(C,M,I){typeof C.on=="function"&&S(C,"error",M,I)}function S(C,M,I,B){if(typeof C.on=="function")B.once?C.once(M,I):C.on(M,I);else if(typeof C.addEventListener=="function")C.addEventListener(M,function H(G){B.once&&C.removeEventListener(M,H),I(G)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof C)}return e1}var t1=o6();t1.once;t1.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)})};t1.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,u)=>r.push({resolve:c,reject:u}))},async return(){n.removeListener(e,v),n.removeListener("error",a),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,v),n.removeListener("error",a)},[Symbol.asyncIterator](){return this}};return n.on(e,v),n.on("error",a),o;function v(...l){let c=r.shift();c?c.resolve(createIterResult(l,!1)):t.push(l)}function a(l){s=!0;let c=r.shift();c?c.reject(l):i=l,o.return()}};var{EventEmitter:Je,defaultMaxListeners:Tl,init:Ml,listenerCount:Sl,on:Cl,once:Bl}=t1;import{Vec3 as qe}from"vec3";E();x();k();R();function v5(n){let e=n*2+1;if(e<=0)return[];let t=[],r=0,i=0,s=0,o=-1;for(let v=0;v<e*e;v++){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 a=s;s=-o,o=a}r+=s,i+=o}return t}E();x();k();R();function Er(n,e=0){if(e>16)return;if(n==null)return n;let t=typeof n;if(t==="function"||t==="symbol")return;if(t==="bigint")return n.toString();if(t!=="object"||n instanceof ArrayBuffer)return n;if(ArrayBuffer.isView(n)){let s=n;return s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength)}if(n instanceof Date)return n.toISOString();if(Array.isArray(n))return n.map(s=>Er(s,e+1)).filter(s=>s!==void 0);let r=n;if(typeof r.x=="number"&&typeof r.y=="number"&&typeof r.z=="number"&&!("w"in r))return{x:r.x,y:r.y,z:r.z};let i={};for(let s of Object.keys(r)){if(s==="_client"||s==="_events"||s==="_eventsCount")continue;let o=Er(r[s],e+1);o!==void 0&&(i[s]=o)}return i}function r1(n){return n.map(e=>Er(e))}var xt=n=>[Math.floor(n.x/16),Math.floor(n.z/16)],a6=n=>[Math.floor(n.x/16),Math.floor(n.y/16),Math.floor(n.z/16)],F2=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)},l5=class l5 extends Je{static restoreTransferred(e,t){let r=new l5;return t&&t.addEventListener("message",({data:i})=>{i.class===l5.restorerName&&i.type==="event"&&r.emit(i.eventName,...i.args)}),r}};d(l5,"restorerName","WorldViewWorker");var Ze=l5,Xe=class extends Je{constructor(t,r,i=new qe(0,0,0)){super();this.world=t;this.viewDistance=r;d(this,"spiralNumber",0);d(this,"gotPanicLastTime",!1);d(this,"panicChunksReload",()=>{});d(this,"loadedChunks",{});d(this,"inLoading",!1);d(this,"chunkReceiveTimes",[]);d(this,"lastChunkReceiveTime",0);d(this,"lastChunkReceiveTimeAvg",0);d(this,"panicTimeout");d(this,"lastPos");d(this,"eventListeners",{});d(this,"debugChunksInfo",{});d(this,"waitingSpiralChunksLoad",{});d(this,"addWaitTime",1);d(this,"keepChunksDistance",0);d(this,"isPlayground",!1);d(this,"allowPositionUpdate",!0);d(this,"lastBiomeId",null);d(this,"lastPosCheck",null);this.lastPos=new qe(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:Ze.restorerName,type:"event",eventName:i,args:r1(s)})}}return{__restorer:Ze.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]=xt(t),o=v5(this.viewDistance).map(([v,a])=>new qe((i+v)*16,0,(s+a)*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 F2(t,this.addWaitTime,async o=>{!s||this.loadedChunks[`${o.x},${o.z}`]||(this.world.getColumnAt(o)||(s=await new Promise(v=>{this.waitingSpiralChunksLoad[`${o.x},${o.z}`]=v})),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]=xt(this.lastPos),v=Math.abs(s-Math.floor(t.x/16)),a=Math.abs(o-Math.floor(t.z/16));if(v<=this.viewDistance&&a<=this.viewDistance){let u=await this.world.getColumnAt(t.y!==void 0?t:new qe(t.x,0,t.z));if(u){let f=u.toJson(),p={minY:u.minY??0,worldHeight:u.worldHeight??256};this.emit("loadChunk",{x:t.x,z:t.z,chunk:f,blockEntities:u.blockEntities,worldConfig:p,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[v,a,l]=s.split(",").map(Number);return t.world.getBlock(new qe(v,a,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]=xt(this.lastPos),[v,a]=xt(t);if(s!==v||o!==a||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[p,g]=f.split(",").map(Number),b=new qe(p,0,g),[A,y]=xt(b),w=Math.abs(v-A),S=Math.abs(a-y);(w>c||S>c)&&l.push(b)}for(let f of l)this.unloadChunk(f);let u=v5(this.viewDistance).map(([f,p])=>{let g=new qe((v+f)*16,0,(a+p)*16);if(!this.loadedChunks[`${g.x},${g.z}`])return g}).filter(f=>!!f);this.lastPos.update(t),this._loadChunks(u,t)}else this.emit("chunkPosUpdate",{pos:t}),this.lastPos.update(t)}};E();x();k();R();E();x();k();R();import Y2 from"minecraft-data";import v6 from"mc-assets/dist/blocksAtlases.json";import l6 from"mc-assets/dist/itemsAtlases.json";import Br from"mc-assets/dist/itemDefinitions.json";import c6 from"mc-assets/dist/blocksAtlasLatest.png";import d6 from"mc-assets/dist/blocksAtlasLegacy.png";import u6 from"mc-assets/dist/itemsAtlasLatest.png";import f6 from"mc-assets/dist/itemsAtlasLegacy.png";import h6 from"mc-assets/dist/textureReplacements/christmas";import{AtlasParser as $e}from"mc-assets/dist/atlasParser";import W2 from"mc-assets/dist/worldBlockProvider";E();x();k();R();var Mr=n5(D2(),1);import*as s1 from"three";E();x();k();R();E();x();k();R();var i1=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,v=0;this.context&&(o=Math.min(o,e),v=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(v.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 z2=class n1{constructor({logsPerSecond:e=20,samplesLog:t=100,samplesGraph:r=10,precision:i=2,minimal:s=!1,horizontal:o=!0,mode:v=0}={}){this.mode=v,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 n1.Panel("FPS","#0ff","#002"),0),this.msPanel=this.addPanel(new n1.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",a=>{a.preventDefault(),this.showPanel(++this.mode%this.container.children.length)},!1),this.mode=v,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 n1.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 v=0;v<t.logs.length;v++)r+=t.logs[v],t.logs[v]>i&&(i=t.logs[v]);let s=0,o=.01;for(let v=0;v<t.graph.length;v++)s+=t.graph[v],t.graph[v]>o&&(o=t.graph[v]);e&&e.update(r/Math.min(t.logs.length,this.samplesLog),s/Math.min(t.graph.length,this.samplesGraph),i,o,this.precision)}}};z2.Panel=i1;var L2=z2;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}}}}),c5=function(){return performance.now()},kt=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=c5()),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}(),Rt={Linear:function(n,e){var t=n.length-1,r=t*e,i=Math.floor(r),s=Rt.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=Rt.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=Rt.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=Rt.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,v=i*i,a=i*v;return(2*e-2*t+s+o)*a+(-3*e+3*t-2*s-o)*v+s*i+e}}},U2=function(){function n(){}return n.nextId=function(){return n._nextId++},n._nextId=0,n}(),kr=new kt,F0=function(){function n(e,t){t===void 0&&(t=kr),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=Rt.Linear,this._chainedTweens=[],this._onStartCallbackFired=!1,this._onEveryStartCallbackFired=!1,this._id=U2.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=c5()),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 v=e[o],a=Array.isArray(v),l=a?"array":typeof v,c=!a&&Array.isArray(r[o]);if(!(l==="undefined"||l==="function")){if(c){var u=r[o];if(u.length===0)continue;for(var f=[v],p=0,g=u.length;p<g;p+=1){var b=this._handleRelativeValue(v,u[p]);if(isNaN(b)){c=!1;break}f.push(b)}c&&(r[o]=f)}if((l==="object"||a)&&v&&!c){t[o]=a?[]:{};var A=v;for(var y in A)t[o][y]=A[y];i[o]=a?[]:{};var u=r[o];if(!this._isDynamic){var w={};for(var y in u)w[y]=u[y];r[o]=u=w}this._setupProperties(A,t[o],u,i[o],s)}else(typeof t[o]>"u"||s)&&(t[o]=v),a||(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=c5()),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=c5()),!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=kr),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=Rt.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=c5()),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 v=0,a=this._chainedTweens.length;v<a;v++)this._chainedTweens[v].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,v=r[s],a=Array.isArray(e[s]),l=Array.isArray(v),c=!a&&l;c?e[s]=this._interpolationFunction(v,i):typeof v=="object"&&v?this._updateProperties(e[s],o,v,i):(v=this._handleRelativeValue(o,v),typeof v=="number"&&(e[s]=o+(v-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 Rc=U2.nextId,pe=kr,kc=pe.getAll.bind(pe),Tc=pe.removeAll.bind(pe),Mc=pe.add.bind(pe),Sc=pe.remove.bind(pe),G2=pe.update.bind(pe);E();x();k();R();function Tr(n){if(n==="high-performance")return"high-performance";if(n==="low-power")return"low-power"}var a0=typeof globalThis.WorkerGlobalScope<"u"&&globalThis instanceof globalThis.WorkerGlobalScope,Sr=class{constructor(e,t=0){this.canvas=e;d(this,"stats");d(this,"stats2");d(this,"statsGl");d(this,"total",0);d(this,"denseMode");this.stats=new Mr.default,this.stats2=new Mr.default,this.statsGl=new L2({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()}},d5=class{constructor(e,t,r){this.initOptions=e;this.externalCanvas=t;d(this,"canvas");d(this,"renderer");d(this,"animationFrameId");d(this,"timeoutId");d(this,"lastRenderTime",0);d(this,"previousCanvasWidth",0);d(this,"previousCanvasHeight",0);d(this,"currentWidth",0);d(this,"currentHeight",0);d(this,"pendingResize",!1);d(this,"renderedFps",0);d(this,"fpsInterval");d(this,"stats");d(this,"paused",!1);d(this,"disconnected",!1);d(this,"preRender",()=>{});d(this,"render",e=>{});d(this,"postRender",()=>{});d(this,"sizeChanged",()=>{});d(this,"droppedFpsPercentage",0);d(this,"config");d(this,"onRender",[]);d(this,"inWorldRenderingConfig");d(this,"nonReactiveState");this.config=e.config,t?this.canvas=t:this.addToPage();try{let s=e.getRendererOptions?.()?.gpuPreference??"default";this.renderer=new s1.WebGLRenderer({canvas:this.canvas,preserveDrawingBuffer:!0,logarithmicDepthBuffer:!0,powerPreference:Tr(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=s1.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&&!a0&&(this.stats=new Sr(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=N2(),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(),G2(),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 N2(){let n=document.createElement("canvas");return n.id="viewer-canvas",document.body.appendChild(n),n}var Cr=()=>{let n=N2(),e=n.transferControlToOffscreen(),t=!1,r=(o,v)=>{},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}}}};import{ItemsRenderer as V2}from"mc-assets/dist/itemsRenderer";import{getLoadedItemDefinitionsStore as Pr}from"mc-assets/dist/stores";var o1=null;function Q2(n){return a0?((!o1||typeof o1.get!="function")&&(o1=Pr(Br)),o1):(K2(n),n.itemsDefinitionsStore)}function K2(n){a0||typeof n.itemsDefinitionsStore?.get=="function"||(n.itemsDefinitionsStore=Pr(n.sourceItemDefinitionsJson??Br))}var Tt=class{constructor(e){d(this,"sourceItemDefinitionsJson",Br);d(this,"itemsDefinitionsStore",Pr(this.sourceItemDefinitionsJson));d(this,"allReady",!1);d(this,"itemsAtlasImage");d(this,"blocksAtlasImage");d(this,"blocksAtlasJson");d(this,"itemsAtlasJson");d(this,"customBlockStates");d(this,"customModels");d(this,"customItemModelNames",{});d(this,"customTextures",{});d(this,"guiAtlas",null);d(this,"guiAtlasVersion",0);d(this,"itemsRenderer");d(this,"worldBlockProvider");d(this,"blockstatesModels",null);d(this,"version");d(this,"texturesVersion");d(this,"mcData");if(e){let t={...e};delete t.itemsDefinitionsStore,delete t.sourceItemDefinitionsJson,Object.assign(this,t),K2(this)}if(this.version){let t=globalThis.loadedData??globalThis.mcData;a0&&t?.entitiesByName?this.mcData=t:this.mcData=Y2(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"||t==="itemsDefinitionsStore"||t==="sourceItemDefinitionsJson"||(e[t]=this[t]));return e.customTextures={},delete e.itemsDefinitionsStore,delete e.sourceItemDefinitionsJson,e}},j2="1.21.4",Be=class Be extends Je{constructor(){super(...arguments);d(this,"sourceBlockStatesModels",null);d(this,"sourceBlocksAtlases",v6);d(this,"sourceItemsAtlases",l6);d(this,"currentResources");d(this,"itemsAtlasParser");d(this,"blocksAtlasParser");d(this,"currentConfig");d(this,"abortController",new AbortController);d(this,"_promiseAssetsReadyResolvers",Promise.withResolvers())}rebuildWorkerRenderers(t){if(a0&&!(!t.version||!t.blockstatesModels||!t.blocksAtlasJson)){if(this.blocksAtlasParser=new $e({latest:t.blocksAtlasJson},""),t.itemsAtlasJson)this.itemsAtlasParser=new $e({latest:t.itemsAtlasJson},"");else if(!this.itemsAtlasParser?.atlas?.latest){if(!this.sourceItemsAtlases||Object.keys(this.sourceItemsAtlases).length===0)return;this.itemsAtlasParser=new $e(this.sourceItemsAtlases,"")}t.itemsRenderer=new V2(t.version,t.blockstatesModels,this.itemsAtlasParser,this.blocksAtlasParser),t.worldBlockProvider=W2(t.blockstatesModels,this.blocksAtlasParser.atlas,j2)}}static restoreTransferred(t,r){let i=new Be,s=o=>{i.currentResources=new Tt(o),i.rebuildWorkerRenderers(i.currentResources)};return s(t.currentResources),r&&r.addEventListener("message",({data:o})=>{o.class===Be.restorerName&&(o.type==="newResources"&&s(o.currentResources),o.type==="event"&&i.emit(o.eventName,...o.args))}),i}enrichTransferSnapshot(t){return t&&(this.itemsAtlasParser?.atlas?.latest&&(t.itemsAtlasJson=this.itemsAtlasParser.atlas.latest),this.blocksAtlasParser?.atlas?.latest&&(t.blocksAtlasJson=this.blocksAtlasParser.atlas.latest),t)}prepareForTransfer(t){if(t){let r=this.emit.bind(this);this.emit=(i,...s)=>{if(r(i,...s),t.postMessage({class:Be.restorerName,type:"event",eventName:i,args:r1(s)}),i==="assetsTexturesUpdated"||i==="assetsInventoryReady"){let o=this.enrichTransferSnapshot(this.currentResources?.prepareForTransfer());t.postMessage({class:Be.restorerName,type:"newResources",currentResources:o})}}}return{__restorer:Be.restorerName,currentResources:this.enrichTransferSnapshot(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=Y2(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 V2(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,h6);let s=new $e(this.sourceBlocksAtlases,c6,d6),o=Object.keys(t.customTextures.blocks?.textures??{}),{atlas:v,canvas:a}=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 $e({latest:v},a.toDataURL()),t.blocksAtlasImage=await createImageBitmap(a),t.blocksAtlasJson=this.blocksAtlasParser.atlas.latest,t.worldBlockProvider=W2(t.blockstatesModels,this.blocksAtlasParser.atlas,j2)}async recreateItemsAtlas(t=this.currentResources){let r=new $e(this.sourceItemsAtlases,u6,f6),i=Object.keys(t.customTextures.items?.textures??{}),{atlas:s,canvas:o}=await r.makeNewAtlas(t.texturesVersion,v=>{let a=t.customTextures.items?.textures[v];if(a)return a},t.customTextures.items?.tileSize,void 0,i);this.itemsAtlasParser=new $e({latest:s},o.toDataURL()),t.itemsAtlasImage=await createImageBitmap(o),t.itemsAtlasJson=this.itemsAtlasParser.atlas.latest}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}};d(Be,"restorerName","ResourcesManager");var fe=Be;E();x();k();R();var oe=class extends Error{constructor(t,r){super(t);d(this,"failure");this.name="MesherWorkerPreloadError",this.failure=r}};function m6(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 p6=45e3,g6=1e4;async function J2(n){if(F.env.SINGLE_FILE_BUILD)return;let e=n?.fetchTimeoutMs??p6,t=n?.pingTimeoutMs??g6,r=n?.script??"mesher.js",i=new URL(r,document.baseURI).href,s;try{let u=new AbortController,f=window.setTimeout(()=>u.abort(),e);try{s=await fetch(i,{credentials:"same-origin",cache:"force-cache",signal:u.signal})}finally{clearTimeout(f)}}catch(u){let f=u;throw f?.name==="AbortError"?new oe(`Mesher script fetch timed out after ${e}ms (${i}).`,{phase:"fetch",code:"timeout"}):new oe(`Mesher script fetch failed (network): ${f?.message??u}. URL: ${i}`,{phase:"fetch",code:"network",detail:String(f?.message??u)})}if(!s.ok)throw new oe(`Mesher script HTTP ${s.status} ${s.statusText}: ${i}`,{phase:"fetch",code:"bad-status",status:s.status});let o=s.headers.get("content-type")??"",v=await s.arrayBuffer();if(v.byteLength===0)throw new oe(`Mesher script response was empty: ${i}`,{phase:"fetch",code:"invalid-body",hint:"empty"});let a=Math.min(1024,v.byteLength),l=new TextDecoder().decode(v.slice(0,a)).trimStart();if(l.startsWith("<!DOCTYPE")||l.startsWith("<html")||l.startsWith("<HTML"))throw new oe(`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(u){let f=u instanceof Error?u.message:String(u);throw new oe(`Could not construct Worker for mesher (${i}): ${f}`,{phase:"worker",code:"construct-failed",message:f})}await new Promise((u,f)=>{let p=!1,g=window.setTimeout(()=>{p||(p=!0,b(),f(new oe(`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 M=c;c=void 0,M&&(M.removeEventListener("message",w),M.removeEventListener("error",S),M.removeEventListener("messageerror",C),M.terminate())},A=()=>{p||(p=!0,b(),u())},y=M=>{p||(p=!0,b(),f(M))};function w(M){m6(M.data)&&A()}function S(M){y(new oe(`Mesher worker script failed to load or threw during startup: ${M.message||"unknown"} @ ${i}`,{phase:"worker",code:"script-error",message:M.message}))}function C(){y(new oe(`Mesher worker message channel error (structured clone / deserialization). URL: ${i}`,{phase:"ping",code:"messageerror"}))}c.addEventListener("message",w),c.addEventListener("error",S),c.addEventListener("messageerror",C);try{c.postMessage({type:"mc-web-ping",t:performance.now(),workerIndex:0})}catch(M){let I=M instanceof Error?M.message:String(M);y(new oe(`Failed to post mc-web-ping to mesher worker: ${I}`,{phase:"ping",code:"post-failed",detail:I}))}})}var Z2=class{constructor(e={},t=new fe){this.resourcesManager=t;d(this,"waitBackendLoadPromises",[]);d(this,"onWorldStart");d(this,"onBeforeWorldStart");d(this,"worldView");d(this,"config");d(this,"menuBackgroundOptions");d(this,"inWorldRenderingConfig");d(this,"backend");d(this,"backendLoader");d(this,"currentState");d(this,"currentDisplay",null);d(this,"playerState",{reactive:Ar()});d(this,"rendererState");d(this,"nonReactiveState");d(this,"worldReady");d(this,"resolveWorldReady");d(this,"lastCamUpdate",0);d(this,"getRendererOptions");this.config={...P2,...e.config},this.menuBackgroundOptions={...e.config?.menuBackground,...e.menuBackground},this.inWorldRenderingConfig=q2({...a5,...e.rendererConfig});let r=Ke();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 J2({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 b6(0,64,0);this.worldView=new Xe(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 v;if(this.backend){let a=this.backend.startWorld(o);a&&typeof a.then=="function"&&(v=a)}return this.currentState={method:"startWorld",args:[o]},await v,this.resolveWorldReady(),this.onWorldStart?.(),!!v}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=q2(Ke().reactive),this.nonReactiveState=Ke().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 S6}from"valtio/vanilla";E();x();k();R();E();x();k();R();var et=["galaxy","nether","end","cyber","light"],tt=["cruise","barrel","dive","orbit","snake"],u5={galaxy:"Galaxy",nether:"Nether",end:"The End",cyber:"Cyber",light:"Light Space"},f5={cruise:"Cruise",barrel:"Barrel",dive:"Dive",orbit:"Orbit",snake:"Snake"},rt=["mixed","stainedGlass","wool","construction","glow","world"],h5={mixed:"Mixed",stainedGlass:"Stained glass",wool:"Wool",construction:"Construction",glow:"Glow",world:"World (grass & ores)"};E();x();k();R();var ge={mode:"futuristic",minecraftTextures:!0,futuristicScene:"light",futuristicCamera:"dive",futuristicBlockGroup:"stainedGlass",futuristicCameraSpeedPercent:80,futuristicBlockSpeedPercent:40},we=n=>n/100,m5={camera:we(ge.futuristicCameraSpeedPercent),block:we(ge.futuristicBlockSpeedPercent)};var y6={off:0,holes:1,texIndex:2,faces:3,atlasAlpha:4};function Ir(n){return y6[n]}var it=ge,X2={rendererWorldPerformance:"normal",rendererMeshersCountOverride:null,starfieldRendering:!0,defaultSkybox:!0,menuBackgroundMode:it.mode,menuBackgroundMinecraftTextures:it.minecraftTextures,menuBackgroundFuturisticScene:it.futuristicScene,menuBackgroundFuturisticCamera:it.futuristicCamera,menuBackgroundFuturisticBlockGroup:it.futuristicBlockGroup,menuBackgroundFuturisticCameraSpeed:it.futuristicCameraSpeedPercent,menuBackgroundFuturisticBlockSpeed:it.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 _6(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 $2={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:et.map(n=>[n,u5[n]])},menuBackgroundFuturisticCamera:{possibleValues:tt.map(n=>[n,f5[n]])},menuBackgroundFuturisticBlockGroup:{possibleValues:rt.map(n=>[n,h5[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"},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"]]}},es=[{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 Hr(n,e,t,r,i){let s=n.getImageData(e,t,r,i);for(let o=0;o<r;o++)for(let v=0;v<i;v++){let a=(o+v*r)*4;if(s.data[a+3]!==255)return!0}return!1}function a1(n){return n/64}function ts(n,e,t){if(t){if(Hr(n,0,0,e,e))return}else if(Hr(n,0,0,e,e/2))return;let r=a1(e),i=(s,o,v,a)=>n.clearRect(s*r,o*r,v*r,a*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 w6(n,e){n.save(),n.scale(-1,1);let t=a1(e),r=(i,s,o,v,a,l)=>n.drawImage(n.canvas,i*t,s*t,o*t,v*t,-a*t,l*t,-o*t,v*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 Or(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),w6(r,i),ts(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),ts(r,n.width,!0)}function A6(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 Fr(n,e){let t=A6(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 E6(n,e,t,r,i){let s=n.getImageData(e,t,r,i);for(let o=0;o<r;o++)for(let v=0;v<i;v++){let a=(o+v*r)*4;if(!(s.data[a+0]===0&&s.data[a+1]===0&&s.data[a+2]===0&&s.data[a+3]===255))return!1}return!0}function x6(n,e,t,r,i){let s=n.getImageData(e,t,r,i);for(let o=0;o<r;o++)for(let v=0;v<i;v++){let a=(o+v*r)*4;if(!(s.data[a+0]===255&&s.data[a+1]===255&&s.data[a+2]===255&&s.data[a+3]===255))return!1}return!0}function Dr(n){let e=a1(n.width),t=n.getContext("2d",{willReadFrequently:!0}),r=(v,a,l,c)=>Hr(t,v*e,a*e,l*e,c*e),i=(v,a,l,c)=>E6(t,v*e,a*e,l*e,c*e),s=(v,a,l,c)=>x6(t,v*e,a*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 zr(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=a1(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 T6 from"mc-assets/dist/other-textures/latest/entity/player/wide/steve.png";E();x();k();R();import*as he from"three";E();x();k();R();var R6=()=>{if(typeof OffscreenCanvas>"u")return!1;try{let n=new OffscreenCanvas(1,1);return(n.getContext("webgl2")||n.getContext("webgl"))!==null}catch{return!1}},k6=R6(),V0=(n,e)=>{if(k6||typeof document>"u")return new OffscreenCanvas(n,e);let t=document.createElement("canvas");return t.width=n,t.height=e,t};async function nt(n){let t=await(await fetch(n)).blob();return createImageBitmap(t)}var k0=(n,e=!1)=>{n instanceof he.Mesh&&(n.geometry?.dispose?.(),n.material?.dispose?.()),n.children&&n.children.forEach(t=>k0(t,e)),e&&n instanceof he.Mesh&&n.material?.map?.dispose?.()},Lr={},rs={},p5=n=>{let e=new he.Texture,t=nt(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}},Mt=async n=>p5(n).texture,Pe=n=>{let e=V0(n.width,n.height);e.getContext("2d").drawImage(n,0,0);let r=new he.Texture(e);return r.magFilter=he.NearestFilter,r.minFilter=he.NearestFilter,r};function St(n){let{texture:e,promise:t}=p5(n);return e.magFilter=he.NearestFilter,e.minFilter=he.NearestFilter,t.catch(r=>{}),e}async function v1(n,e,t){if(!Lr[n]){let{promise:i,resolve:s}=Promise.withResolvers(),o=p5(n);Lr[n]=o.texture,o.promise.then(s),rs[n]=i}e(Lr[n]),rs[n].then(()=>{t?.()})}var re=T6,Ku=Mt(re),is={apiEnabled:!0},l1=n=>{Object.assign(is,n)};async function Ie(n,e){if(!is.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 Ae(n){n.startsWith("data:")||(n=await M6(n.replace("http://","https://")));let e=await nt(n),t=V0(64,64);return Or(t,e),{canvas:t,image:e}}var M6=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:we(n.menuBackgroundFuturisticCameraSpeed),futuristicBlockSpeed:we(n.menuBackgroundFuturisticBlockSpeed)}}function C6(n,e){let t=n.futuristic;t&&(t.setScene?.(e.menuBackgroundFuturisticScene),t.setCamera?.(e.menuBackgroundFuturisticCamera),t.setBlockGroup?.(e.menuBackgroundFuturisticBlockGroup),t.setCameraSpeed?.(we(e.menuBackgroundFuturisticCameraSpeed)),t.setBlockSpeed?.(we(e.menuBackgroundFuturisticBlockSpeed)))}function B6(n){return n.rendererMesher!=="legacy-js"}function P6(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 I6(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 H6(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 O6(n,e,t={}){let r=n.inWorldRenderingConfig,i=B6(e);r.showChunkBorders=e.showChunkBorders,r.futuristicReveal=e.rendererFuturisticReveal,P6(n,e,i),r.renderEntities=e.renderEntities,H6(n,e,t),I6(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,l1({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=Ir(e.rendererShaderCubeDebugMode)}function of(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 af(n,e,t={}){n.bindRendererOptions(()=>e);let r=t.getWindowFocused?.()??!0,i=()=>{let s=e;if(O6(n,s,{isSafari:t.isSafari,isCypress:t.isCypress,windowFocused:r}),n.currentDisplay==="menu"){let o=n.backend?.getMenuBackground?.();o&&C6(o,s)}};return i(),t.onRegisterFocusHandlers?.({onFocus:()=>{r=!0,i()},onBlur:()=>{r=!1,i()}}),S6(e,i)}function vf(n,e,t){n.inWorldRenderingConfig.enableLighting=!t||e}E();x();k();R();import{proxy as F6}from"valtio";var ns=()=>F6({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}),D6=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"}}),z6=()=>({reactive:ns()}),ss=(n,e,t)=>({...e,"minecraft:date":new Date});E();x();k();R();E();x();k();R();import*as V5 from"three";import{Vec3 as e9}from"vec3";E();x();k();R();import{proxy as L6,getVersion as as,subscribe as vs}from"valtio";import{Vec3 as ls}from"vec3";function cs(n,e){let t=e??globalThis;return t.addEventListener("message",r=>{let{type:i,args:s,msgId:o}=r.data;if(n[i]){let v=n[i](...s);v instanceof Promise&&v.then(a=>{t.postMessage({type:"result",msgId:o,args:[a]})})}}),null}var ds=(n,e=!0)=>{let t=0;return new Proxy({},{get(r,i){return i==="transfer"?(...s)=>new Proxy({},{get(o,v){return(...a)=>{n.postMessage({type:v,args:a},s)}}}):(...s)=>{let o=t++,v=e?s.filter(a=>a instanceof ArrayBuffer||a instanceof MessagePort||typeof ImageBitmap<"u"&&a instanceof ImageBitmap||typeof OffscreenCanvas<"u"&&a instanceof OffscreenCanvas||typeof ImageData<"u"&&a instanceof ImageData):[];return n.postMessage({type:i,msgId:o,args:s},v),{then(a){let l=({data:c})=>{c.type==="result"&&c.msgId===o&&(a(c.args[0]),n.removeEventListener("message",l))};n.addEventListener("message",l)}}}}})};var us=(n,e,t,r)=>{try{t.postMessage({type:"sync",syncId:n,value:c1(e)}),g5.toWorker++,globalThis.debugSyncMessagesOutgoing??(globalThis.debugSyncMessagesOutgoing=0),globalThis.debugSyncMessagesOutgoing++}catch{Ct(e)}},g5={toWorker:0,fromWorker:0};typeof window<"u"&&setInterval(()=>{globalThis.debugWorkerSyncStats={...g5},g5.toWorker=0,g5.fromWorker=0},1e3);var U6=()=>Math.random().toString(36).slice(2,15)+Math.random().toString(36).slice(2,15),fs=(n,e,t)=>{Object.assign(n,d1(e,[],t,!1))},os=(n,e,t,r,i)=>{if(!n.__syncToWorker&&!n.__syncFromWorker&&!r)return;let s=U6();if(n.__syncId=s,n.__syncToWorker||r){let o=()=>{us(s,e,t,`toWorker:${i}`)};r&&vs(e,o);let v=n.__syncToWorkerInterval??0;v>0&&setInterval(o,v)}e.__syncFromWorker&&t.addEventListener("message",o=>{o.data.type==="sync"&&o.data.syncId===s&&(g5.fromWorker++,fs(e,o.data.value,t))})},hs=n=>({__restorer:"Map",__mapEntries:Array.from(n.entries())}),ms=n=>({__restorer:"Set",__setValues:[...n]}),ps=n=>n instanceof Set||Object.prototype.toString.call(n)==="[object Set]",gs=n=>n instanceof Map||Object.prototype.toString.call(n)==="[object Map]",G6=n=>Object.keys(n).filter(e=>!e.startsWith("__")).sort((e,t)=>Number(e)-Number(t)).map(e=>n[e]),c1=n=>{if(gs(n))return hs(n);if(ps(n))return ms(n);if(as(n)===void 0)return n;if(Array.isArray(n))return n.map(c1);if(typeof n=="object"&&n!==null){let e={};for(let t in n)Object.prototype.hasOwnProperty.call(n,t)&&(e[t]=c1(n[t]));return e}return n},b5=(n,e,t=!0,r=!0,i=!1)=>{var v,a;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 WeakMap||n[l]instanceof WeakSet,gs(n[l])){o[l]=hs(n[l]);continue}if(ps(n[l])){o[l]=ms(n[l]);continue}if(n[l]instanceof ls){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=as(n[l])!==void 0;o[l]=c?c1(n[l]):n[l];let u=n[l].__syncToWorker!==!1&&!i&&c&&!n[l].__syncFromWorker;if((v=o[l]).__syncToWorker??(v.__syncToWorker=u),c&&((a=o[l]).__valtio??(a.__valtio=!0)),o[l].__syncToWorker&&c){os(o[l],s[l],e,!0,l);continue}os(o[l],s[l],e,!1,l),o[l]=b5(o[l],e,t,!1,c)}}return o},Ct=(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&&Ct(n[t],[...e,t]);try{structuredClone(n[t])}catch{}}},N6=(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&&fs(n,i.data.value,e)}),n.__syncFromWorker){let i=()=>{us(r,n,e,`fromWorker:${t}`)};n.__valtio&&vs(n,i);let s=n.__syncFromWorkerInterval??0;s>0&&setInterval(i,s)}},W6=[{restorerName:"Map",restoreTransferred(n,e){if(Array.isArray(n))return new Map(n);let t=n.__mapEntries??n.entries;return Array.isArray(t)?new Map(t):t!=null&&typeof t=="object"&&typeof t!="function"?new Map(Object.entries(t)):new Map}},{restorerName:"Set",restoreTransferred(n,e){if(Array.isArray(n))return new Set(n);let t=n.__setValues??n.values;return Array.isArray(t)?new Set(t):t!=null&&typeof t=="object"&&typeof t!="function"?new Set(G6(t)):new Set}},{restorerName:"Vec3",restoreTransferred(n,e){return new ls(n.x,n.y,n.z)}}];var d1=(n,e,t,r=!0)=>{let i=[...W6,...e],s=(o,v)=>{if(o==null||typeof o!="object")return o;if(o.__restorer){let a=i.find(c=>c.restorerName?c.restorerName===o.__restorer:c.name===o.__restorer);if(a)return a.restoreTransferred(o,t);let l=new Error(`Restorer ${o.__restorer} not found`);if(typeof r=="function")r(l);else if(r)throw l;return o}if(Array.isArray(o))return o.map((a,l)=>s(a,`${v}[${l}]`));for(let a in o){if(!Object.prototype.hasOwnProperty.call(o,a))continue;let l=o[a];l!=null&&typeof l=="object"&&(o[a]=s(l,`${v}.${a}`))}return o.__valtio&&(o=L6(o)),N6(o,t,v),o};return s(n,"root")};E();x();k();R();var u1=class{constructor(e){this.nonReactiveState=e;d(this,"events",[]);d(this,"frozenEvents",[]);d(this,"lastSecondEvents",[]);d(this,"currentFrameStartTime",null);d(this,"lastInteractionTime",0);d(this,"lastSecondUpdateTime",0);d(this,"timeWindowMs",5e3);d(this,"lastSecondWindowMs",1e3);d(this,"maxEvents",500);d(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 Ue}from"vec3";import jv from"prismarine-chat";E();x();k();R();var V6=(n,e)=>{try{return JSON.parse(n)}catch{return null}},j6={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"},f1=(n,e,t,r=s=>{},i=(s,o)=>V0(s,o))=>{let v=[16,9],a=v[0]-v[1],l=a/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 u=i(16*40,a*40),f=u.getContext("2d");r(f);let p=("front_text"in n?n.front_text.color:n.Color)||"black";for(let[g,b]of c.slice(0,4).entries())b!=="null"&&Ur(b,t,u,64,p,64*(g+1)+(e?0:-8));return u},Ur=(n,e,t,r,i,s=0)=>{let o=!1,v=typeof n=="string"&&(n?.startsWith("{")||n?.startsWith('"'))?V6(n??'""',"sign text"):n;if(!v||typeof v!="object"&&typeof v!="string")return;let a=t.getContext("2d");if(!a)throw new Error("Could not get 2d context");a.imageSmoothingEnabled=!1,a.font=`${r}px mojangles`;let l=new e(v),c=[],u=!1,f="",p=s,g=[],b=(S,C)=>{S.text!==null&&S.text!==void 0&&S.text;let M=S.text===null||S.text===void 0?void 0:String(S.text),I={color:S.color??C?.color,underlined:S.underlined??C?.underlined,strikethrough:S.strikethrough??C?.strikethrough,bold:S.bold??C?.bold,italic:S.italic??C?.italic};if(u=u||I.underlined||I.strikethrough||!1,M?.includes(`
286
286
  `))for(let B of M.split(`
287
287
  `))A(B,I),p+=r,f="";else M&&A(M,I);if(S.extra)for(let B of S.extra)b(B,I)},A=(S,C)=>{o||(o=S.trim()!==""),f+=S,g[p]=a.measureText(f).width;let M=C.color??i;M.startsWith("#")||(M=j6[M.toLowerCase()]||M),c.push({fontStyle:`${C.bold?"bold":""} ${C.italic?"italic":""}`,fillStyle:M,underlineStyle:C.underlined??!1,strikeStyle:C.strikethrough??!1,offset:p,text:S})};if(b(l),!u&&!l.toString().trim())return;let y=0,w=0;for(let{fillStyle:S,fontStyle:C,underlineStyle:M,strikeStyle:I,offset:B,text:H}of c){w!==B&&(y=0),w=B,a.fillStyle=S,a.textRendering="optimizeLegibility",a.font=`${C} ${r}px mojangles`;let G=g[B]??a.measureText(H).width,O=(t.width-G)/2+y;a.fillText(H,O,B),I&&(a.lineWidth=r/8,a.strokeStyle=S,a.beginPath(),a.moveTo(O,B-a.lineWidth*2.5),a.lineTo(O+a.measureText(H).width,B-a.lineWidth*2.5),a.stroke()),M&&(a.lineWidth=r/8,a.strokeStyle=S,a.beginPath(),a.moveTo(O,B+a.lineWidth),a.lineTo(O+a.measureText(H).width,B+a.lineWidth),a.stroke()),y+=a.measureText(H).width}return o};E();x();k();R();function Bt(n){let e=Math.floor(n.x/16),t=Math.floor(n.z/16);return[e,t]}function Gr(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 _5}from"vec3";import{subscribeKey as jr}from"valtio/utils";import{proxy as q6,subscribe as Z6}from"valtio";E();x();k();R();var st={blocks:"blocksArray",blockCollisionShapes:"blockCollisionShapes",biomes:"biomesArray",tints:"tints"};E();x();k();R();var bs=16;var ys=(n,e)=>e?`${n}:${e}`:String(n);E();x();k();R();var _s=0,Ee={},Nr=40,y5="mc-renderer-debug-overlay",Pt=(n,e=80,t=_s,r=Nr,i)=>{if(a0)return{updateText(){},setVisibility(){}};let s=document.createElement("div");return s.style.position="fixed",s.style.top=`${r??Nr}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),Ee[n]=s,r===void 0&&t===_s&&(Nr+=20),{updateText(o){s.innerText!==o&&(s.innerText=o)},setVisibility(o){s.style.display=o?"block":"none"}}};var Wr=(n,e)=>{a0||!Ee[n]||(Ee[n].innerText=e)},ws=n=>{if(!a0)for(let e in Ee)Ee[e].style.display=n?"block":"none"},As=()=>{if(!a0)for(let n in Ee)Y6(n)},Y6=n=>{a0||!Ee[n]||(Ee[n].remove(),delete Ee[n])};E();x();k();R();var Q6=n=>{let e=n%24e3/24e3-.25;return e<0&&(e+=1),e>1&&(e-=1),e+(1-Math.cos(e*Math.PI))/2},K6=n=>{let e=(n%24e3+24e3)%24e3,t=Q6(e),i=Math.cos(t*Math.PI*2)*.5+.5,s=Math.round(4+i*11);return Math.max(4,Math.min(15,s))},Vr=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)}}},J6=()=>{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=K6(e),i=Vr(e)}};typeof window<"u"&&(window.debugSkyLight=J6);function w5(n,e){return(n%e+e)%e}var xe=class xe{constructor(e,t,r){this.resourcesManager=e;this.displayOptions=t;this.initOptions=r;d(this,"worldReadyResolvers",Promise.withResolvers());d(this,"worldReadyPromise",this.worldReadyResolvers.promise);d(this,"timeOfTheDay",0);d(this,"worldSizeParams",{minY:0,worldHeight:256});d(this,"reactiveDebugParams",q6({stopRendering:!1,chunksRenderAboveOverride:void 0,chunksRenderAboveEnabled:!1,chunksRenderBelowOverride:void 0,chunksRenderBelowEnabled:!1,chunksRenderDistanceOverride:void 0,chunksRenderDistanceEnabled:!1,disableEntities:!1}));d(this,"active",!1);d(this,"loadedChunks",{});d(this,"finishedChunks",{});d(this,"finishedSections",{});d(this,"sectionsWaiting",new Map);d(this,"queuedChunks",new Set);d(this,"queuedFunctions",[]);d(this,"renderUpdateEmitter",new Je);d(this,"customTexturesDataUrl");d(this,"workers",[]);d(this,"viewerChunkPosition");d(this,"lastViewerChunkGridX");d(this,"lastViewerChunkGridZ");d(this,"lastCamUpdate",0);d(this,"droppedFpsPercentage",0);d(this,"initialChunkLoadWasStartedIn");d(this,"initialChunksLoad",!0);d(this,"enableChunksLoadDelay",!1);d(this,"texturesVersion");d(this,"viewDistance",-1);d(this,"onRenderDistanceChanged");d(this,"chunksLength",0);d(this,"allChunksFinished",!1);d(this,"messageQueue",[]);d(this,"isProcessingQueue",!1);d(this,"ONMESSAGE_TIME_LIMIT",30);d(this,"handleResize",()=>{});d(this,"highestBlocksByChunks",new Map);d(this,"blockEntities",{});d(this,"workersProcessAverageTime",0);d(this,"workersProcessAverageTimeCount",0);d(this,"maxWorkersProcessTime",0);d(this,"workersPreAverageTime",0);d(this,"workersWasmAverageTime",0);d(this,"workersPostAverageTime",0);d(this,"workersPhaseSampleCount",0);d(this,"workersPreTargetConvertAverageTime",0);d(this,"workersPreNeighborConvertAverageTime",0);d(this,"workersPreNeighborCountAverage",0);d(this,"workersPreTypedArrayBuildAverageTime",0);d(this,"workersPreOtherAverageTime",0);d(this,"workersPreCacheHitsTotal",0);d(this,"workersPreCacheMissesTotal",0);d(this,"geometryReceiveCount",{});d(this,"allLoadedIn");d(this,"onWorldSwitched",[]);d(this,"renderTimeMax",0);d(this,"renderTimeAvg",0);d(this,"renderTimeAvgCount",0);d(this,"edgeChunks",{});d(this,"lastAddChunk",null);d(this,"neighborChunkUpdates",!0);d(this,"lastChunkDistance",0);d(this,"debugStopGeometryUpdate",!1);d(this,"protocolCustomBlocks",new Map);d(this,"heightmapDebounceTimers",new Map);d(this,"sectionDirtyCount",new Map);d(this,"sectionDirtyTimers",new Map);d(this,"sectionDirtyPendingArgs",new Map);d(this,"blockStateModelInfo",new Map);d(this,"worldBlockProvider");d(this,"soundSystem");d(this,"worldRendererConfig");d(this,"playerStateReactive");d(this,"playerStateUtils");d(this,"reactiveState");d(this,"mesherLogReader");d(this,"forceCallFromMesherReplayer",!1);d(this,"stopMesherMessagesProcessing",!1);d(this,"abortController",new AbortController);d(this,"lastRendered",0);d(this,"renderingActive",!0);d(this,"geometryReceiveCountPerSec",0);d(this,"mesherLogger",{contents:[],active:new URL(location.href).searchParams.get("mesherlog")==="true"});d(this,"currentRenderedFrames",0);d(this,"fpsAverage",0);d(this,"lastFps",0);d(this,"fpsWorst");d(this,"fpsSamples",0);d(this,"backendInfoReport","-");d(this,"chunksFullInfo","-");d(this,"workerCustomHandleTime",0);d(this,"queueAwaited",!1);d(this,"toWorkerMessagesQueue",{});this.snapshotInitialValues(),this.worldRendererConfig=t.inWorldRenderingConfig,this.playerStateReactive=t.playerStateReactive,this.playerStateUtils=I2(this.playerStateReactive),this.reactiveState=t.rendererState,this.renderUpdateEmitter.on("update",()=>{let o=Object.keys(this.finishedChunks).length;Wr("loaded-chunks",`${o}/${this.chunksLength} chunks (${this.lastChunkDistance}/${this.viewDistance})`)}),Pt("downloaded-chunks",100,140,20,{className:y5}),this.connect(this.displayOptions.worldView);let i=setInterval(()=>{this.geometryReceiveCountPerSec=Object.values(this.geometryReceiveCount).reduce((o,v)=>o+v,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 _5(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=ys(t,s),v=this.blockStateModelInfo.get(o);return{customBlockName:s,modelInfo:v}}initWorkers(e=this.worldRendererConfig.mesherWorkers){for(let t=0;t<e+0;t++){let r=X6(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]),jr(this.playerStateReactive,e,t)}onReactiveConfigUpdated(e,t){t(this.worldRendererConfig[e]),e==="*"?Z6(this.worldRendererConfig,t):jr(this.worldRendererConfig,e,t)}onReactiveDebugUpdated(e,t){t(this.reactiveDebugParams[e]),jr(this.reactiveDebugParams,e,t)}watchReactivePlayerState(){this.onReactivePlayerStateUpdated("backgroundColor",e=>{this.changeBackgroundColor(e)}),this.onReactivePlayerStateUpdated("cardinalLight",e=>{this.changeCardinalLight(e)})}watchReactiveConfig(){this.onReactiveConfigUpdated("fetchPlayerSkins",e=>{l1({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 _5(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 v=!0,a=this.getSectionHeight();for(let l=this.worldMinYRender;l<this.worldSizeParams.worldHeight;l+=a)if(!this.finishedSections[`${s[0]},${l},${s[2]}`]){v=!1;break}if(v){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 v=++this.workersPhaseSampleCount;this.workersPreAverageTime=(this.workersPreAverageTime*(v-1)+t.pre)/v,this.workersWasmAverageTime=(this.workersWasmAverageTime*(v-1)+t.wasm)/v,this.workersPostAverageTime=(this.workersPostAverageTime*(v-1)+t.post)/v;let a=typeof t.preTargetConvert=="number"?t.preTargetConvert:0,l=typeof t.preNeighborConvert=="number"?t.preNeighborConvert:0,c=typeof t.preNeighborCount=="number"?t.preNeighborCount:0,u=typeof t.preTypedArrayBuild=="number"?t.preTypedArrayBuild:0,f=typeof t.preOther=="number"?t.preOther:0,p=typeof t.preCacheHits=="number"?t.preCacheHits:0,g=typeof t.preCacheMisses=="number"?t.preCacheMisses:0;if(this.workersPreTargetConvertAverageTime=(this.workersPreTargetConvertAverageTime*(v-1)+a)/v,this.workersPreNeighborConvertAverageTime=(this.workersPreNeighborConvertAverageTime*(v-1)+l)/v,this.workersPreNeighborCountAverage=(this.workersPreNeighborCountAverage*(v-1)+c)/v,this.workersPreTypedArrayBuildAverageTime=(this.workersPreTypedArrayBuildAverageTime*(v-1)+u)/v,this.workersPreOtherAverageTime=(this.workersPreOtherAverageTime*(v-1)+f)/v,this.workersPreCacheHitsTotal+=p,this.workersPreCacheMissesTotal+=g,this.worldRendererConfig.debugWasmPerf&&v%xe.PHASE_PERF_LOG_INTERVAL===0){let b=this.workersPreAverageTime+this.workersWasmAverageTime+this.workersPostAverageTime,A=b>0?this.workersPreAverageTime/b*100:0,y=b>0?this.workersWasmAverageTime/b*100:0,w=b>0?this.workersPostAverageTime/b*100:0,S=this.workersPreAverageTime,C=S>0?this.workersPreTargetConvertAverageTime/S*100:0,M=S>0?this.workersPreNeighborConvertAverageTime/S*100:0,I=S>0?this.workersPreTypedArrayBuildAverageTime/S*100:0,B=S>0?this.workersPreOtherAverageTime/S*100:0,H=this.workersPreNeighborCountAverage,G=H>0?this.workersPreNeighborConvertAverageTime/H: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]=Bt(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:Vr(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;xs(this.workers,this.version,st,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 bs}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,Wr("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 v=this.getSectionHeight(),a=16;for(let l=this.worldMinYRender;l<this.worldSizeParams.worldHeight;l+=v){let c=new _5(e,l,t);this.setSectionDirty(c),this.neighborChunkUpdates&&(!i||this.worldRendererConfig.smoothLighting)&&(this.setSectionDirty(c.offset(-a,0,0)),this.setSectionDirty(c.offset(a,0,0)),this.setSectionDirty(c.offset(0,0,-a)),this.setSectionDirty(c.offset(0,0,a)))}}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,v]of this.sectionDirtyTimers)o.startsWith(`${e},`)&&o.endsWith(`,${t}`)&&(clearTimeout(v),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 _5(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,v=Math.floor(e.z/16)*16;this.queuedChunks.has(`${o},${v}`)&&await new Promise(a=>{this.queuedFunctions.push(()=>{a()})}),this.loadedChunks[`${o},${v}`],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:v,isLightUpdate:a})=>{this.worldSizeParams=v,this.queuedChunks.add(`${i},${s}`);let l=[i,s,o,a];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 _5(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:v5(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}`,v=this.protocolCustomBlocks.get(s)||{};for(let a of this.workers)a.postMessage({type:"blockUpdate",pos:e,stateId:t,customBlockModels:v});if(this.anyModuleRequiresHeightmap()){let a=Math.floor(e.x/16)*16,l=Math.floor(e.z/16)*16,c=`${a},${l}`;if(!this.worldRendererConfig.wasmMesher){let u=this.heightmapDebounceTimers.get(c);u&&clearTimeout(u),this.heightmapDebounceTimers.set(c,setTimeout(()=>{this.heightmapDebounceTimers.delete(c),this.workers[0]?.postMessage({type:"getHeightmap",x:a,z:l})},100))}}if(this.logWorkerWork(`-> blockUpdate ${JSON.stringify({pos:e,stateId:t,customBlockModels:v})}`),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 w5(Math.floor(e.x/16)+Math.floor(e.z/16),this.workers.length);if(t){let v=`${Math.floor(e.x/16)*16},${Math.floor(e.y/i)*i},${Math.floor(e.z/16)*16}`;if(this.sectionsWaiting.get(v)&&!this.finishedSections[v]){let l=this.workers.length-1;return w5(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 w5(Math.floor(e.x/16)+Math.floor(e.y/i)+Math.floor(e.z/16),o)}if(this.worldRendererConfig.wasmMesher)return w5(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 w5(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(),v=`${Math.floor(e.x/s)*s},${Math.floor(e.y/o)*o},${Math.floor(e.z/s)*s}`,a=(this.sectionDirtyCount.get(v)??0)+1;this.sectionDirtyCount.set(v,a),a<=xe.GEOMETRY_THROTTLE_THRESHOLD?(this._dispatchDirtyImmediate(e,t,r),this.sectionDirtyTimers.has(v)||this.sectionDirtyTimers.set(v,setTimeout(()=>{let l=this.sectionDirtyPendingArgs.get(v);this.sectionDirtyCount.delete(v),this.sectionDirtyTimers.delete(v),this.sectionDirtyPendingArgs.delete(v),l&&this._dispatchDirtyImmediate(l.pos,l.value,l.useChangeWorker)},xe.GEOMETRY_THROTTLE_DELAY))):(this.sectionDirtyPendingArgs.set(v,{pos:e,value:t,useChangeWorker:r}),this.sectionDirtyTimers.has(v)||this.sectionDirtyTimers.set(v,setTimeout(()=>{let l=this.sectionDirtyPendingArgs.get(v);this.sectionDirtyCount.delete(v),this.sectionDirtyTimers.delete(v),this.sectionDirtyPendingArgs.delete(v),l&&this._dispatchDirtyImmediate(l.pos,l.value,l.useChangeWorker)},xe.GEOMETRY_THROTTLE_DELAY)))}_dispatchDirtyImmediate(e,t,r){var a;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 v=this.getWorkerNumber(e,r&&(this.mesherLogger.active||this.worldRendererConfig.dedicatedChangeWorker));this.sectionsWaiting.set(o,(this.sectionsWaiting.get(o)??0)+1),this.forceCallFromMesherReplayer?this.workers[v].postMessage({type:"dirty",x:e.x,y:e.y,z:e.z,value:t,config:this.getMesherConfig()}):((a=this.toWorkerMessagesQueue)[v]??(a[v]=[]),this.toWorkerMessagesQueue[v].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()}};d(xe,"PHASE_PERF_LOG_INTERVAL",64),d(xe,"GEOMETRY_THROTTLE_THRESHOLD",1),d(xe,"GEOMETRY_THROTTLE_DELAY",100);var h1=xe,X6=(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},Es=!1,xs=(n,e,t=st,r)=>{let i={version:JSON.parse(JSON.stringify(r.version))};for(let[s,o]of Object.entries(t))i[s]=r[o];"tints"in t&&!i.tints&&!Es&&(Es=!0);for(let s of n)s.postMessage({type:"mcData",mcData:i})},Yr=(n,e,t=st,r,i=1e4)=>Promise.all(n.map(s=>new Promise((o,v)=>{let a=setTimeout(()=>{s.removeEventListener("message",l),v(new Error(`mcData transfer timeout (${i}ms)`))},i),l=({data:c})=>{c?.type==="mcDataApplied"&&(clearTimeout(a),s.removeEventListener("message",l),o())};s.addEventListener("message",l),xs([s],e,t,r)}))).then(()=>{});E();x();k();R();import{Vec3 as $6}from"vec3";import*as ie from"three";E();x();k();R();function m1(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,v=(s+2)%3,a=[[0,0,0],[0,0,0],[0,0,0]];return a[s][s]=1,a[o][o]=r,a[o][v]=-i,a[v][o]=+i,a[v][v]=r,a}function Qr(n,e){return e?[n[0]+e[0],n[1]+e[1],n[2]+e[2]]:n}function Kr(n,e){return e?[n[0]-e[0],n[1]-e[1],n[2]-e[2]]:n}function It(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 Rs(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],v=n[1][1],a=n[2][1],l=n[0][2],c=n[1][2],u=n[2][2],f=e[0][0],p=e[1][0],g=e[2][0],b=e[0][1],A=e[1][1],y=e[2][1],w=e[0][2],S=e[1][2],C=e[2][2];return t[0][0]=r*f+i*b+s*w,t[1][0]=r*p+i*A+s*S,t[2][0]=r*g+i*y+s*C,t[0][1]=o*f+v*b+a*w,t[1][1]=o*p+v*A+a*S,t[2][1]=o*g+v*y+a*C,t[0][2]=l*f+c*b+u*w,t[1][2]=l*p+c*A+u*S,t[2][2]=l*g+c*y+u*C,t}var Jr={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 e7(n,e,t,r,i,s,o,v){let a=new $6(0,0,0);for(let l in n.faces){let c=n.faces[l],{corners:u,mask1:f,mask2:p}=Jr[l],g=It(r,Jr[l].dir);if(c.cullface&&v[l])continue;let b=n.from[0],A=n.from[1],y=n.from[2],w=n.to[0],S=n.to[1],C=n.to[2],M=c.texture,{u:I}=M,{v:B}=M,{su:H}=M,{sv:G}=M,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,Z=Math.cos(J*Math.PI/180),e0=-Math.sin(J*Math.PI/180),u0=null,c0=null;n.rotation&&(u0=m1(n.rotation.axis,n.rotation.angle),c0=Kr(n.rotation.origin,It(u0,n.rotation.origin)));let p0=[],g0=1;for(let E0 of u){let n0=[E0[0]?w:b,E0[1]?S:A,E0[2]?C:y];n0=Qr(It(u0,n0),c0),n0=Qr(It(r,n0),i),n0=n0.map(G0=>G0/16),t.positions.push(n0[0],n0[1],n0[2]),t.normals.push(...g);let Y=(E0[3]-.5)*Z-(E0[4]-.5)*e0+.5,o0=(E0[3]-.5)*e0+(E0[4]-.5)*Z+.5;t.uvs.push(Y*H+I,o0*G+B);let b0=1;e&&(b0=4/4*(15/15),p0.push(3)),t.colors.push(g0*j[0]*b0,g0*j[1]*b0,g0*j[2]*b0)}e&&p0[0]+p0[3]>=p0[1]+p0[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 t7=(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[u,f]of n.entries()){let p=f[i[u]]??f[0];if(!p)continue;let g=null,b=null;for(let y of["x","y","z"])y in p&&(g?g=Rs(g,m1(y,-(p[y]??0))):g=m1(y,-(p[y]??0)));g&&(b=[8,8,8],b=Kr(b,It(g,b)));let A=p.ao??!0;for(let y of p.elements??[])e7(y,A,l,g,b,e,t,s)}let c=l.positions.length/3;for(let u=0;u<l.t_positions.length/12;u++)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},r7=(...n)=>{let t={geometry:t7(...n)},r=new ie.BufferGeometry;return r.setAttribute("position",new ie.BufferAttribute(t.geometry.positions,3)),r.setAttribute("normal",new ie.BufferAttribute(t.geometry.normals,3)),r.setAttribute("color",new ie.BufferAttribute(t.geometry.colors,3)),r.setAttribute("uv",new ie.BufferAttribute(t.geometry.uvs,2)),r.setIndex(t.geometry.indices),r.name="block-geometry",r},qr=(n,...e)=>{let t=r7(...e),r=new ie.Mesh(t,n);r.position.set(-.5,-.5,-.5);let i=new ie.Group;return i.add(r),i.rotation.set(0,-ie.MathUtils.degToRad(90),0,"ZYX"),globalThis.mesh=i,i},ks=(n,e)=>{n.position.set(e.x+.5,e.y+.5,e.z+.5)};E();x();k();R();import*as D0 from"three";var A5=async(n,e)=>{let t;if(!n&&!e){let{canvas:l}=await Ae(re);t=new D0.CanvasTexture(l)}else{if(n||(n=await Ie(e,"skin")),!n)return;let{canvas:l}=await Ae(n);t=new D0.CanvasTexture(l)}t.magFilter=D0.NearestFilter,t.minFilter=D0.NearestFilter;let r=!1,s=i7(40,16,r?-2:-3,-2,-2,r?3:4,12,4,64,64),o=new D0.MeshStandardMaterial;o.map=t,o.needsUpdate=!0;let v=new D0.Mesh(s,o),a=new D0.Group;return a.add(v),a};function i7(n,e,t,r,i,s,o,v,a,l,c=!1){let u=t/16,f=r/16,p=i/16,g=(t+s)/16,b=(r+o)/16,A=(i+v)/16;c&&([u,g]=[g,u]);let y=[[u,f,p],[g,f,p],[g,b,p],[u,b,p],[u,f,A],[g,f,A],[g,b,A],[u,b,A]],w=n,S=n+v,C=n+v+s,M=n+v+s+s,I=n+v+s+v,B=n+v+s+v+s,H=e,G=e+v,O=e+v+o,j=[{vi:[5,4,0,1],uv:[S,H,C,G],n:[0,-1,0]},{vi:[2,3,7,6],uv:[C,G,M,H],n:[0,1,0]},{vi:[0,4,7,3],uv:[w,G,S,O],n:[-1,0,0]},{vi:[1,0,3,2],uv:[S,G,C,O],n:[0,0,-1]},{vi:[5,1,2,6],uv:[C,G,I,O],n:[1,0,0]},{vi:[4,5,6,7],uv:[I,G,B,O],n:[0,0,1]}],J=[],Z=[],e0=[],u0=[];for(let p0=0;p0<j.length;p0++){let g0=j[p0],E0=p0*4,[n0,Y,o0,b0]=g0.uv,G0=[[o0/a,1-Y/l],[n0/a,1-Y/l],[n0/a,1-b0/l],[o0/a,1-b0/l]],O0=c?[3,2,1,0]:[0,1,2,3],Z0=c?-g0.n[0]:g0.n[0];for(let f0=0;f0<4;f0++){let ue=y[g0.vi[O0[f0]]];J.push(ue[0],ue[1],ue[2]),Z.push(G0[f0][0],G0[f0][1]),e0.push(Z0,g0.n[1],g0.n[2])}u0.push(E0,E0+1,E0+2,E0,E0+2,E0+3)}let c0=new D0.BufferGeometry;return c0.setAttribute("position",new D0.Float32BufferAttribute(J,3)),c0.setAttribute("uv",new D0.Float32BufferAttribute(Z,2)),c0.setAttribute("normal",new D0.Float32BufferAttribute(e0,3)),c0.setIndex(u0),c0}E();x();k();R();E();x();k();R();import*as C0 from"three";E();x();k();R();E();x();k();R();var He=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)}},Zr=class extends He{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 Xr(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 n7={isPrimitive:!0,match:n=>typeof n=="string",fromHexString:Xr,toHexString:Xr},x5={isPrimitive:!0,match:n=>typeof n=="number",fromHexString:n=>parseInt(n.substring(1),16),toHexString:n=>"#"+n.toString(16).padStart(6,0)},s7={isPrimitive:!1,match:n=>Array.isArray(n),fromHexString(n,e,t=1){let r=x5.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 x5.toHexString(i)}},o7={isPrimitive:!1,match:n=>Object(n)===n,fromHexString(n,e,t=1){let r=x5.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 x5.toHexString(i)}},a7=[n7,x5,s7,o7];function v7(n){return a7.find(e=>e.match(n))}var $r=class extends He{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=v7(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=Xr(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}},E5=class extends He{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}},ei=class extends He{constructor(e,t,r,i,s,o){super(e,t,r,"number"),this._initInput(),this.min(i),this.max(s);let v=o!==void 0;this.step(v?o:this._getImplicitStep(),v),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 w=parseFloat(this.$input.value);isNaN(w)||(this._stepExplicit&&(w=this._snap(w)),this.setValue(this._clamp(w)))},r=w=>{let S=parseFloat(this.$input.value);isNaN(S)||(this._snapClampSetValue(S+w),this.$input.value=this.getValue())},i=w=>{w.key==="Enter"&&this.$input.blur(),w.code==="ArrowUp"&&(w.preventDefault(),r(this._step*this._arrowKeyMultiplier(w))),w.code==="ArrowDown"&&(w.preventDefault(),r(this._step*this._arrowKeyMultiplier(w)*-1))},s=w=>{this._inputFocused&&(w.preventDefault(),r(this._step*this._normalizeMouseWheel(w)))},o=!1,v,a,l,c,u,f=5,p=w=>{v=w.clientX,a=l=w.clientY,o=!0,c=this.getValue(),u=0,window.addEventListener("mousemove",g),window.addEventListener("mouseup",b)},g=w=>{if(o){let S=w.clientX-v,C=w.clientY-a;Math.abs(C)>f?(w.preventDefault(),this.$input.blur(),o=!1,this._setDraggingStyle(!0,"vertical")):Math.abs(S)>f&&b()}if(!o){let S=w.clientY-l;u-=S*this._step*this._arrowKeyMultiplier(w),c+u>this._max?u=this._max-c:c+u<this._min&&(u=this._min-c),this._snapClampSetValue(c+u)}l=w.clientY},b=()=>{this._setDraggingStyle(!1,"vertical"),this._callOnFinishChange(),window.removeEventListener("mousemove",g),window.removeEventListener("mouseup",b)},A=()=>{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",p),this.$input.addEventListener("focus",A),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,w,S,C,M)=>(y-w)/(S-w)*(M-C)+C,t=y=>{let w=this.$slider.getBoundingClientRect(),S=e(y,w.left,w.right,this._min,this._max);this._snapClampSetValue(S)},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,v,a,l=y=>{y.preventDefault(),this._setDraggingStyle(!0),t(y.touches[0].clientX),o=!1},c=y=>{y.touches.length>1||(this._hasScrollBar?(v=y.touches[0].clientX,a=y.touches[0].clientY,o=!0):l(y),window.addEventListener("touchmove",u,{passive:!1}),window.addEventListener("touchend",f))},u=y=>{if(o){let w=y.touches[0].clientX-v,S=y.touches[0].clientY-a;Math.abs(w)>Math.abs(S)?l(y):(window.removeEventListener("touchmove",u),window.removeEventListener("touchend",f))}else y.preventDefault(),t(y.touches[0].clientX)},f=()=>{this._callOnFinishChange(),this._setDraggingStyle(!1),window.removeEventListener("touchmove",u),window.removeEventListener("touchend",f)},p=this._callOnFinishChange.bind(this),g=400,b,A=y=>{if(Math.abs(y.deltaX)<Math.abs(y.deltaY)&&this._hasScrollBar)return;y.preventDefault();let S=this._normalizeMouseWheel(y)*this._step;this._snapClampSetValue(this.getValue()+S),this.$input.value=this.getValue(),clearTimeout(b),b=setTimeout(p,g)};this.$slider.addEventListener("mousedown",r),this.$slider.addEventListener("touchstart",c,{passive:!1}),this.$slider.addEventListener("wheel",A,{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}},ti=class extends He{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}},ri=class extends He{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}},l7=`.lil-gui {
@@ -21505,7 +21505,7 @@ void main() {
21505
21505
 
21506
21506
  #include <tonemapping_fragment>
21507
21507
  #include <${Vv>=154?"colorspace_fragment":"encodings_fragment"}>
21508
- }`})}},en=class{constructor(e){this.worldRenderer=e;d(this,"points");d(this,"clock",new M0.Clock);d(this,"enabled",!1);d(this,"currentTime");d(this,"enablementCheck",()=>this.currentTime?this.currentTime>13500&&this.currentTime<23e3:!1);d(this,"render",e=>{this.points&&(this.points.position.set(0,0,0),this.points.material.uniforms.time.value=this.clock.getElapsedTime()*.2)})}enable(){this.enabled||(this.enabled=!0,this.updateVisibility())}disable(){this.enabled&&(this.enabled=!1,this.removeStars())}toggle(){return this.enabled?this.disable():this.enable(),this.enabled}updateTimeOfDay(e){this.currentTime=e,this.enabled&&this.updateVisibility()}updateVisibility(){if(!this.enabled)return;let e=this.enablementCheck?.()??!1;e&&!this.points?this.createStars():!e&&this.points&&this.removeStars()}createStars(){if(this.points)return;let e=80,t=50,r=7e3,i=7,s=10,o=new M0.BufferGeometry,v=b=>new M0.Vector3().setFromSpherical(new M0.Spherical(b,Math.acos(1-Math.random()*2),Math.random()*2*Math.PI)),a=[],l=[],c=Array.from({length:r},()=>(.5+.5*Math.random())*i),u=new M0.Color,f=e+t,p=t/r;for(let b=0;b<r;b++)f-=p*Math.random(),a.push(...v(f).toArray()),u.setHSL(b/r,s,.9),l.push(u.r,u.g,u.b);o.setAttribute("position",new M0.Float32BufferAttribute(a,3)),o.setAttribute("color",new M0.Float32BufferAttribute(l,3)),o.setAttribute("size",new M0.Float32BufferAttribute(c,1));let g=new $i;g.blending=M0.AdditiveBlending,g.depthTest=!0,g.depthWrite=!1,g.transparent=!0,this.points=new M0.Points(o,g),this.points.renderOrder=-1,this.worldRenderer.scene.add(this.points)}dispose(){this.removeStars()}removeStars(){this.points&&(this.points.geometry.dispose(),this.points.material.dispose(),this.worldRenderer.scene.remove(this.points),this.points=void 0)}},Ca={id:"starfield",controller:en,enabledDefault:!0,cannotBeDisabled:!0};var Ba={starfield:Ca,futuristicReveal:Sa,rain:Ta,cameraBobbing:Ea,blockBreakParticles:Aa};var pt=class pt extends h1{constructor(t,r,i){if(!i.resourcesManager)throw new Error("resourcesManager is required in displayOptions");super(i.resourcesManager,i,r);this.renderer=t;this.initOptions=r;this.displayOptions=i;d(this,"outputFormat","threeJs");d(this,"chunkMeshManager");d(this,"chunkTextures",new Map);d(this,"signsCache",new Map);d(this,"cameraSectionPos",new Ue(0,0,0));d(this,"holdingBlock");d(this,"holdingBlockLeft");d(this,"scene",new Q.Scene);d(this,"ambientLight",new Q.AmbientLight(13421772));d(this,"directionalLight",new Q.DirectionalLight(16777215,.5));d(this,"entities",new F1(this,globalThis.mcData));d(this,"performanceMonitor");d(this,"cameraGroupVr");d(this,"material",new Q.MeshBasicMaterial({vertexColors:!0,transparent:!0,alphaTest:.1}));d(this,"itemsTexture");d(this,"cursorBlock");d(this,"onRender",[]);d(this,"lastRenderTime",0);d(this,"animatedFov",0);d(this,"lastFovAnimTime",0);d(this,"cameraShake");d(this,"cameraContainer");d(this,"media");d(this,"waypoints");d(this,"cinimaticScript");d(this,"camera");d(this,"renderTimeAvg",0);d(this,"pendingSectionUpdates",new Map);d(this,"pendingSectionBufferStartTimes",new Map);d(this,"modules",{});d(this,"sectionsOffsetsAnimations",{});d(this,"fountains",[]);d(this,"fireworksLegacy");d(this,"DEBUG_RAYCAST",!1);d(this,"skyboxRenderer");d(this,"fireworks");d(this,"sceneOrigin",new K1(this.scene));d(this,"cameraWorldPos",{x:0,y:0,z:0});d(this,"_cameraPositionAccessWarned",!1);d(this,"_tmpCameraPos",new Q.Vector3);d(this,"currentPosTween");d(this,"currentRotTween");d(this,"_tpDirection",new Q.Vector3);d(this,"_tpPitchQuat",new Q.Quaternion);d(this,"_tpYawQuat",new Q.Quaternion);d(this,"_tpFinalQuat",new Q.Quaternion);d(this,"_tpScenePos",new Q.Vector3);d(this,"_tpAxisX",new Q.Vector3(1,0,0));d(this,"_tpAxisY",new Q.Vector3(0,1,0));d(this,"_tpRaycaster",new Q.Raycaster);d(this,"_tpChunkWorldPos",new Q.Vector3);d(this,"debugOverlayAdded",!1);d(this,"debugRaycastHelper");d(this,"debugHitPoint");d(this,"prevFramePerspective",null);this.performanceMonitor=new o5(this.reactiveState.world.instabilityFactors),this.renderer=t,i.rendererState.renderer=pt.getRendererInfo(t)??"...",this.chunkMeshManager=new W5(this,this.scene,this.material,this.worldSizeParams.worldHeight,this.viewDistance),this.onRenderDistanceChanged=s=>{this.chunkMeshManager.updateViewDistance(s)},this.cursorBlock=new D1(this),this.holdingBlock=D5(this),this.holdingBlockLeft=D5(this,!0);for(let s of Object.values(Ba))this.registerModule(s);this.skyboxRenderer=new Y1(this.realScene,!1,null),this.skyboxRenderer.init(),this.addDebugOverlay(),this.resetScene(),this.init(),this.soundSystem=new L1(this),this.cameraShake=new U1(this,this.onRender),this.media=new G1(this),this.fireworksLegacy=new V1(this),this.waypoints=new W1(this),this.cinimaticScript=new j1(this,(s,o,v)=>this.setCinimaticCamera(s,o,v),s=>this.setCinimaticFov(s),()=>({position:new Ue(this.cameraWorldPos.x,this.cameraWorldPos.y,this.cameraWorldPos.z),yaw:this.cameraShake.getBaseRotation().yaw,pitch:this.cameraShake.getBaseRotation().pitch,fov:this.camera.fov})),this.fireworks=new Q1(this.realScene,this.sceneOrigin),this.renderUpdateEmitter.on("chunkFinished",s=>{this.finishChunk(s)}),this.worldSwitchActions(),this.initializeModules()}isShaderCubeBlocksEnabled(){return this.worldRendererConfig.shaderCubeBlocks===!0&&!!this.renderer?.capabilities?.isWebGL2}get sectionObjects(){return this.chunkMeshManager.sectionObjects}get realScene(){return this.scene}get waitingChunksToDisplay(){return this.chunkMeshManager.waitingChunksToDisplay}get estimatedMemoryUsage(){return this.chunkMeshManager.getEstimatedMemoryUsage().total}get tilesRendered(){return this.chunkMeshManager.getTotalTiles()}get blocksRendered(){return this.chunkMeshManager.getTotalBlocks()}registerModule(t){if(t.id in this.modules)return;let r=new t.controller(this),i={manifest:t,controller:r,enabled:!1,toggle:()=>this.toggleModule(t.id)};this.modules[t.id]=i,t.enabledDefault&&this.toggleModule(t.id,!0)}enableModule(t){let r=this.modules[t];r&&(r.enabled||(r.enabled=!0,r.controller.enable(),r.controller.render&&this.onRender.push(r.controller.render)))}disableModule(t){let r=this.modules[t];if(r&&!r.manifest.cannotBeDisabled&&r.enabled&&(r.enabled=!1,r.controller.disable(),r.controller.render)){let i=this.onRender.indexOf(r.controller.render);i>-1&&this.onRender.splice(i,1)}}toggleModule(t,r){let i=this.modules[t];if(!i)return!1;let s=r!==void 0?r:!i.enabled;if(s===i.enabled)return i.enabled;if(!s&&i.manifest.cannotBeDisabled)return!0;if(i.enabled=s,s)i.controller.enable(),i.controller.render&&!this.onRender.includes(i.controller.render)&&this.onRender.push(i.controller.render);else if(i.controller.disable(),i.controller.render){let o=this.onRender.indexOf(i.controller.render);o>-1&&this.onRender.splice(o,1)}return s}disposeModules(){for(let t of Object.values(this.modules))t.controller.dispose();this.modules={}}initializeModules(){this.updateModulesFromConfig()}getModule(t){return this.modules[t]?.controller}anyModuleRequiresHeightmap(){return Object.values(this.modules).some(t=>t.enabled&&t.manifest.requiresHeightmap)}get cameraObject(){return this.cameraGroupVr??this.cameraContainer}_wrapCameraPositionWithWarning(){let t=this.camera.position,r=this,i=20,s=(a,l,c)=>Math.abs(a)>i||Math.abs(l)>i||Math.abs(c)>i,o=()=>{!r._cameraPositionAccessWarned&&typeof F<"u"},v=new Proxy(t,{set(a,l,c){return(l==="x"||l==="y"||l==="z")&&typeof c=="number"&&Math.abs(c)>i&&o(),a[l]=c,!0},get(a,l,c){let u=a[l];return l==="set"?function(f,p,g){return s(f,p,g)&&o(),a.set(f,p,g)}:l==="setX"||l==="setY"||l==="setZ"?function(f){return Math.abs(f)>i&&o(),a[l](f)}:l==="copy"?function(f){return s(f.x,f.y,f.z)&&o(),a.copy(f)}:typeof u=="function"?u.bind(a):u}});Object.defineProperty(this.camera,"position",{value:v,configurable:!0,enumerable:!0})}worldSwitchActions(){this.onWorldSwitched.push(()=>{this.protocolCustomBlocks.clear(),this.sectionsOffsetsAnimations={},this.waypoints.clear(),this.cinimaticScript.stopScript(),this.fireworks.clear()})}downloadWorldGeometry(){Ni(this,new Q.Vector3(this.cameraWorldPos.x,this.cameraWorldPos.y,this.cameraWorldPos.z),this.cameraShake.getBaseRotation(),"world-geometry.json")}updateEntity(t,r=!1){let i={rotation:{head:{x:t.headPitch??t.pitch,y:t.headYaw,z:0}}};r?this.entities.updateEntityPosition(t,!1,i):this.entities.update(t,i)}updatePlayerEntity(t){this.entities.handlePlayerEntity(t)}resetScene(){this.sceneOrigin.update(0,0,0),this.cameraWorldPos.x=0,this.cameraWorldPos.y=0,this.cameraWorldPos.z=0,this.scene.matrixAutoUpdate=!1,this.scene.background=new Q.Color(this.initOptions.config.sceneBackground),this.scene.add(this.ambientLight),this.directionalLight.position.set(1,1,.5).normalize(),this.directionalLight.castShadow=!0,this.scene.add(this.directionalLight);let t=this.renderer.getSize(new Q.Vector2);this.camera=new Q.PerspectiveCamera(75,t.x/t.y,.1,1e3),this._wrapCameraPositionWithWarning(),this.cameraContainer=new Q.Object3D,this.cameraContainer.add(this.camera),this.scene.add(this.cameraContainer)}watchReactivePlayerState(){super.watchReactivePlayerState(),this.onReactivePlayerStateUpdated("inWater",t=>{this.skyboxRenderer.updateWaterState(t,this.playerStateReactive.waterBreathing)}),this.onReactivePlayerStateUpdated("waterBreathing",t=>{this.skyboxRenderer.updateWaterState(this.playerStateReactive.inWater,t)}),this.onReactivePlayerStateUpdated("ambientLight",t=>{t&&(this.ambientLight.intensity=t)}),this.onReactivePlayerStateUpdated("directionalLight",t=>{t&&(this.directionalLight.intensity=t)}),this.onReactivePlayerStateUpdated("lookingAtBlock",t=>{this.cursorBlock.setHighlightCursorBlock(t?new Ue(t.x,t.y,t.z):null,t?.shapes)}),this.onReactivePlayerStateUpdated("diggingBlock",t=>{this.cursorBlock.updateBreakAnimation(t?{x:t.x,y:t.y,z:t.z}:void 0,t?.stage??null,t?.mergedShape)}),this.onReactivePlayerStateUpdated("perspective",t=>{let r=new Ue(this.cameraWorldPos.x,this.cameraWorldPos.y,this.cameraWorldPos.z);this.updateCamera(r,this.cameraShake.getBaseRotation().yaw,this.cameraShake.getBaseRotation().pitch)})}watchReactiveConfig(){super.watchReactiveConfig(),this.onReactiveConfigUpdated("showChunkBorders",r=>{this.updateShowChunksBorder(r)}),this.onReactiveConfigUpdated("defaultSkybox",r=>{this.skyboxRenderer.updateDefaultSkybox(r)}),this.onReactiveConfigUpdated("shaderCubeDebugMode",()=>{this.chunkMeshManager.syncCubeShaderUniforms()}),this.onReactiveConfigUpdated("futuristicReveal",()=>{this.updateModulesFromConfig()});let t=this.displayOptions.inWorldRenderingConfig.handRenderer;this.onReactiveConfigUpdated("handRenderer",r=>{if(r===t)return;t=r;let i=this.holdingBlock.ready,s=this.holdingBlockLeft.ready;this.holdingBlock.dispose(),this.holdingBlockLeft.dispose(),this.holdingBlock=D5(this),this.holdingBlockLeft=D5(this,!0),i&&(this.holdingBlock.ready=!0,this.holdingBlock.updateItem()),s&&(this.holdingBlockLeft.ready=!0,this.holdingBlockLeft.updateItem())}),this.onReactiveConfigUpdated("*",()=>{this.updateModulesFromConfig()}),this.updateModulesFromConfig()}updateModulesFromConfig(){let{moduleStates:t}=this.worldRendererConfig;for(let[r,i]of Object.entries(this.modules)){let s=t[r];if(s==="enabled"){i.enabled||this.toggleModule(r,!0);continue}if(s==="disabled"){i.enabled&&!i.manifest.cannotBeDisabled&&this.toggleModule(r,!1);continue}if(s==="auto"||s===void 0)if(i.controller.autoEnableCheck){let o=i.controller.autoEnableCheck();o&&!i.enabled?this.toggleModule(r,!0):!o&&i.enabled&&!i.manifest.cannotBeDisabled&&this.toggleModule(r,!1)}else{let o=i.manifest.enabledDefault??!1;o&&!i.enabled?this.toggleModule(r,!0):!o&&i.enabled&&!i.manifest.cannotBeDisabled&&this.toggleModule(r,!1)}}}changeHandSwingingState(t,r=!1){let i=r?this.holdingBlockLeft:this.holdingBlock;t?i.startSwing():i.stopSwing()}async updateAssetsData(){let t=this.resourcesManager.currentResources,r=this.material.map,i=this.itemsTexture,s=Pe(t.blocksAtlasImage);s.needsUpdate=!0,s.flipY=!1,this.material.map=s,this.chunkMeshManager.syncCubeShaderUniforms();let o=Pe(t.itemsAtlasImage);o.needsUpdate=!0,o.flipY=!1,this.itemsTexture=o,r&&r.dispose(),i&&i.dispose(),await super.updateAssetsData(),this.onAllTexturesLoaded(),Object.keys(this.loadedChunks).length>0&&this.rerenderAllChunks()}onAllTexturesLoaded(){this.holdingBlock.ready=!0,this.holdingBlock.updateItem(),this.holdingBlockLeft.ready=!0,this.holdingBlockLeft.updateItem()}changeBackgroundColor(t){this.realScene.background=new Q.Color(t[0],t[1],t[2])}changeCardinalLight(t){this.worldRendererConfig.cardinalLight=t}timeUpdated(t){let r=this.getModule("starfield");r?.updateTimeOfDay&&r.updateTimeOfDay(t),this.skyboxRenderer.updateTime(t)}biomeUpdated(t){t?.temperature!==void 0&&this.skyboxRenderer.updateTemperature(t.temperature)}biomeReset(){this.skyboxRenderer.updateTemperature(Oi)}getItemRenderData(t,r){return Y3(t,r,this.resourcesManager,this.playerStateReactive)}async demoModel(){let t=cursorBlockRel(0,1,0).position,r=await A5();ks(r,t);let i=new Q.BoxHelper(r,16776960);r.add(i),this.realScene.add(r)}demoItem(){let t=cursorBlockRel(0,1,0).position,{mesh:r}=this.entities.getItemMesh({itemId:541},{});r.position.set(t.x+.5,t.y+.5,t.z+.5);let i=new Q.BoxHelper(r,16776960);r.add(i),this.realScene.add(r)}addDebugOverlay(){if(this.debugOverlayAdded)return;this.debugOverlayAdded=!0;let t=Pt("debug-overlay",80,0,void 0,{className:y5});setInterval(()=>{if(t.setVisibility(this.displayAdvancedStats),this.displayAdvancedStats){let r=a=>new Intl.NumberFormat("en-US",{}).format(a),i=a=>new Intl.NumberFormat("en-US",{notation:"compact",maximumFractionDigits:1}).format(a),s="";s+=`TE: ${r(this.renderer.info.memory.textures)} `,s+=`F: ${i(this.tilesRendered)} `,s+=`B: ${i(this.blocksRendered)} `,s+=`MEM: ${this.chunkMeshManager.getEstimatedMemoryUsage().total} `;let o=this.chunkMeshManager.getStats();s+=`POOL: ${o.activeCount}/${o.poolSize} `;let v=wr(this.reactiveState.world.instabilityFactors);v&&(s+=`PF: ${v} `),t.updateText(s),this.backendInfoReport=s}},200)}updatePosDataChunk(t){let r=this.sectionObjects[t];if(!r)return;let[i,s,o]=t.split(",").map(c=>Math.floor(+c/16)),a=500-(Math.abs(i-this.cameraSectionPos.x)+Math.abs(s-this.cameraSectionPos.y)+Math.abs(o-this.cameraSectionPos.z)),l=r.mesh??r.shaderMesh??r.children.find(c=>c.name==="mesh"||c.name==="shaderMesh");l&&(l.renderOrder=a)}updateViewerPosition(t){this.viewerChunkPosition=t}cameraSectionPositionUpdate(){for(let t in this.sectionObjects)this.sectionObjects[t]&&this.updatePosDataChunk(t)}getDir(t,r){return t===r?0:t<r?1:-1}finishChunk(t){this.chunkMeshManager.finishChunkDisplay(t)}applyPendingSectionUpdates(){if(this.pendingSectionUpdates.size===0)return;let t=performance.now(),r=this.getSectionHeight(),i=[];for(let s of this.pendingSectionUpdates.keys()){let o=this.pendingSectionBufferStartTimes.get(s)??t;if(t-o<pt.MAX_SECTION_UPDATE_BUFFER_MS){let[a,l,c]=s.split(",").map(Number),u=[`${a-16},${l},${c}`,`${a+16},${l},${c}`,`${a},${l-r},${c}`,`${a},${l+r},${c}`,`${a},${l},${c-16}`,`${a},${l},${c+16}`],f=!1;for(let p of u)if(this.sectionsWaiting.has(p)&&!this.pendingSectionUpdates.has(p)&&this.sectionObjects[p]){f=!0;break}if(f)continue}i.push(s)}if(i.length!==0)for(let s of i){let o=this.pendingSectionUpdates.get(s);this.pendingSectionUpdates.delete(s),this.pendingSectionBufferStartTimes.delete(s);let v=o.key.split(","),a=`${v[0]},${v[2]}`;if(!this.loadedChunks[a]||!this.active){this.chunkMeshManager.releaseSection(o.key);continue}if(!this.chunkMeshManager.sectionHasRenderableContent(o.geometry)){this.chunkMeshManager.releaseSection(o.key);continue}this.chunkMeshManager.updateSection(o.key,o.geometry),this.updatePosDataChunk(o.key)}}clearPendingSectionUpdatesForChunk(t,r){for(let i of[...this.pendingSectionUpdates.keys()])i.startsWith(`${t},`)&&i.endsWith(`,${r}`)&&(this.pendingSectionUpdates.delete(i),this.pendingSectionBufferStartTimes.delete(i))}handleWorkerMessage(t){if(t.type==="geometry"){let r=t.key.split(","),i=`${r[0]},${r[2]}`;if(!this.loadedChunks[i]||!this.active){this.pendingSectionUpdates.delete(t.key),this.pendingSectionBufferStartTimes.delete(t.key);return}if(this.sectionObjects[t.key]){this.pendingSectionUpdates.set(t.key,t),this.pendingSectionBufferStartTimes.has(t.key)||this.pendingSectionBufferStartTimes.set(t.key,performance.now());return}if(!this.chunkMeshManager.sectionHasRenderableContent(t.geometry)){this.chunkMeshManager.releaseSection(t.key);return}this.chunkMeshManager.updateSection(t.key,t.geometry),this.updatePosDataChunk(t.key)}}getSignTexture(t,r,i,s=!1){let o=Bt(t),v=this.chunkTextures.get(`${o[0]},${o[1]}`);v||(v={},this.chunkTextures.set(`${o[0]},${o[1]}`,v));let a=`${t.x},${t.y},${t.z}`;if(v[a])return v[a];let l=jv(this.version),c=f1(r,i,l);if(!c)return;let u=new Q.Texture(c);return u.magFilter=Q.NearestFilter,u.minFilter=Q.NearestFilter,u.needsUpdate=!0,v[a]=u,u}getCameraPosition(t){return(t??this._tmpCameraPos).set(this.cameraWorldPos.x,this.cameraWorldPos.y,this.cameraWorldPos.z)}getSectionCameraPosition(){let t=this.getCameraPosition();return new Ue(Math.floor(t.x/16),Math.floor(t.y/16),Math.floor(t.z/16))}updateCameraSectionPos(){let t=this.getSectionCameraPosition();this.cameraSectionPos.equals(t)||(this.cameraSectionPos=t,this.cameraSectionPositionUpdate())}setFirstPersonCamera(t,r,i){let s=this.playerStateReactive.eyeHeight;this.updateCamera(t?.offset(0,s,0)??null,r,i),this.updateCameraSectionPos()}getThirdPersonCamera(t,r,i){t??(t=new Q.Vector3(this.cameraWorldPos.x,this.cameraWorldPos.y,this.cameraWorldPos.z));let s=this.playerStateReactive.perspective==="third_person_back",o=4,v=this._tpDirection.set(0,0,-1),a=this._tpPitchQuat.setFromAxisAngle(this._tpAxisX,i),l=this._tpYawQuat.setFromAxisAngle(this._tpAxisY,r),c=this._tpFinalQuat.multiplyQuaternions(l,a);v.applyQuaternion(c),s&&v.multiplyScalar(-1),this.DEBUG_RAYCAST&&this.debugRaycast(t,v,o);let u=this._tpScenePos.set(this.sceneOrigin.toSceneX(t.x),this.sceneOrigin.toSceneY(t.y),this.sceneOrigin.toSceneZ(t.z)),f=this._tpRaycaster;f.set(u,v),f.far=o;let p=80,g=p*p,b=t.x,A=t.y,y=t.z,w=[];for(let B of Object.values(this.sectionObjects)){if(B.name!=="chunk"||!B.visible||B.worldX===void 0)continue;let H=B.worldX-b,G=B.worldY-A,O=B.worldZ-y;if(H*H+G*G+O*O>g)continue;let j=B.children.find(J=>J.name==="mesh"||J.name==="shaderMesh");j&&w.push(j)}let S=f.intersectObjects(w,!1),C=o;S.length>0&&(C=Math.max(.5,S[0].distance-.2));let M=this.chunkMeshManager.raycastShaderSectionAABBs(t,v,C,p);return M!==void 0&&(C=Math.max(.5,M-.2)),new Ue(t.x+v.x*C,t.y+v.y*C,t.z+v.z*C)}debugRaycast(t,r,i){this.debugRaycastHelper&&(this.realScene.remove(this.debugRaycastHelper),this.debugRaycastHelper=void 0),this.debugHitPoint&&(this.realScene.remove(this.debugHitPoint),this.debugHitPoint=void 0);let s=new Q.Vector3(this.sceneOrigin.toSceneX(t.x),this.sceneOrigin.toSceneY(t.y),this.sceneOrigin.toSceneZ(t.z));this.debugRaycastHelper=new Q.ArrowHelper(r.clone().normalize(),s,i,16711680,i*.1,i*.05),this.realScene.add(this.debugRaycastHelper);let o=new Q.SphereGeometry(.2,8,8),v=new Q.MeshBasicMaterial({color:65280});this.debugHitPoint=new Q.Mesh(o,v),this.debugHitPoint.position.copy(s).add(r.clone().multiplyScalar(i)),this.realScene.add(this.debugHitPoint)}setCinimaticCamera(t,r,i){this.cameraWorldPos.x=t.x,this.cameraWorldPos.y=t.y,this.cameraWorldPos.z=t.z,this.sceneOrigin.update(t.x,t.y,t.z),this.cameraObject.position.set(0,0,0),this.cameraShake.setBaseRotation(i,r),this.updateCameraSectionPos()}setCinimaticFov(t){this.animatedFov=t,this.camera.fov=t,this.camera.updateProjectionMatrix()}updateSmoothFov(){if(this.cinimaticScript.running)return;let t=this.displayOptions.inWorldRenderingConfig.fov,r=this.playerStateReactive.fovMultiplier,i=t*(Number.isFinite(r)?r:1),s=performance.now();if(this.animatedFov===0&&(this.animatedFov=i),Math.abs(this.animatedFov-i)>=.01){let o=s-this.lastFovAnimTime,v=Math.min(o/pt.FOV_TRANSITION_MS,1),a=l=>1-(1-l)**3;this.animatedFov+=(i-this.animatedFov)*a(v),Math.abs(this.animatedFov-i)<.01&&(this.animatedFov=i)}else this.animatedFov=i;this.lastFovAnimTime=s,this.camera.fov!==this.animatedFov&&(this.camera.fov=this.animatedFov,this.camera.updateProjectionMatrix())}updateCamera(t,r,i){if(!this.cinimaticScript.running){if(t){this.renderer.xr.isPresenting&&(t.y-=this.camera.position.y),this.currentPosTween?.stop();let s=this.displayOptions.inWorldRenderingConfig.instantCameraUpdate?0:this.playerStateUtils.isSpectatingEntity()?150:50;this.currentPosTween=new F0(this.cameraWorldPos).to({x:t.x,y:t.y,z:t.z},s).onUpdate(()=>{this.sceneOrigin.update(this.cameraWorldPos.x,this.cameraWorldPos.y,this.cameraWorldPos.z),this.cameraObject.position.set(0,0,0)}).start()}if(this.playerStateUtils.isSpectatingEntity()){let s=this.cameraShake.getBaseRotation(),o=0,v=Math.PI/2;s.yaw<v&&r>Math.PI+v?o=-Math.PI*2:r<v&&s.yaw>Math.PI+v&&(o=Math.PI*2),this.currentRotTween?.stop(),this.currentRotTween=new F0(s).to({pitch:i,yaw:r+o},100).onUpdate(a=>this.cameraShake.setBaseRotation(a.pitch,a.yaw-o)).start()}else{this.currentRotTween?.stop(),this.cameraShake.setBaseRotation(i,r);let{perspective:s}=this.playerStateReactive;if(s==="third_person_back"||s==="third_person_front"){let o=new Q.Vector3(this.cameraWorldPos.x,this.cameraWorldPos.y,this.cameraWorldPos.z),v=this.getThirdPersonCamera(o,r,i),a=o.distanceTo(new Q.Vector3(v.x,v.y,v.z)),l=s==="third_person_back"?a:-a;this.camera.position.set(0,0,l),s==="third_person_front"?this.camera.rotation.set(0,Math.PI,0):this.camera.rotation.set(0,0,0)}else this.camera.position.z=0,this.camera.rotation.set(0,0,0),this.debugRaycastHelper&&(this.realScene.remove(this.debugRaycastHelper),this.debugRaycastHelper=void 0),this.debugHitPoint&&(this.realScene.remove(this.debugHitPoint),this.debugHitPoint=void 0)}this.updateCameraSectionPos()}}debugChunksVisibilityOverride(){let{chunksRenderAboveOverride:t,chunksRenderBelowOverride:r,chunksRenderDistanceOverride:i,chunksRenderAboveEnabled:s,chunksRenderBelowEnabled:o,chunksRenderDistanceEnabled:v}=this.reactiveDebugParams,a=this.getSectionHeight(),l=this.cameraSectionPos.y*a;if(this.displayOptions.inWorldRenderingConfig.enableDebugOverlay&&t!==void 0||r!==void 0||i!==void 0)for(let[c,u]of Object.entries(this.sectionObjects)){if(u._waitingForChunkDisplay)continue;let[f,p,g]=c.split(",").map(Number),b=s&&t!==void 0?p<=l+t:o&&r!==void 0?p>=l-r:v&&i!==void 0?Math.abs(p-l)<=i:!0;u.visible=b}else this.chunkMeshManager.updateSectionsVisibility()}render(t=!1){if(this.currentRenderedFrames++,this.reactiveDebugParams.stopRendering)return;this.debugChunksVisibilityOverride();let r=performance.now();this.lastRendered=performance.now();let i=this.lastRenderTime>0?Math.min(Math.max((r-this.lastRenderTime)/1e3,0),.1):1/60;this.lastRenderTime=r,this.cursorBlock.render(),this.updateSectionOffsets();let s=this.getCameraPosition();if(this.skyboxRenderer.update(s,this.viewDistance),this.updateSmoothFov(),t){let u=this.renderer.getSize(new Q.Vector2);this.camera.aspect=u.width/u.height,this.camera.updateProjectionMatrix()}let o=0;if(!this.reactiveDebugParams.disableEntities){let u=performance.now();this.entities.render(),o=performance.now()-u}let v=this.cameraGroupVr instanceof Q.Group?this.cameraGroupVr.children.find(u=>u instanceof Q.PerspectiveCamera):this.camera;this.applyPendingSectionUpdates();let a=this.chunkMeshManager.globalBlockBuffer;a&&(a.setCameraOrigin(this.cameraWorldPos.x,this.cameraWorldPos.y,this.cameraWorldPos.z),a.uploadDirtyRange()),this.renderer.render(this.scene,v),this.displayOptions.inWorldRenderingConfig.showHand&&this.playerStateReactive.gameMode!=="spectator"&&this.playerStateReactive.perspective==="first_person"&&!this.renderer.xr.isPresenting&&(this.holdingBlock.render(this.camera,this.renderer,this.ambientLight,this.directionalLight),this.holdingBlockLeft.render(this.camera,this.renderer,this.ambientLight,this.directionalLight));for(let u of this.fountains)this.sectionObjects[u.sectionId]&&!this.sectionObjects[u.sectionId].foutain&&(u.createParticles(this.sectionObjects[u.sectionId]),this.sectionObjects[u.sectionId].foutain=!0),u.render();this.waypoints.render(),this.fireworks.update();for(let u of this.onRender)u(i);let c=performance.now()-r;this.worldRendererConfig.autoLowerRenderDistance&&this.chunkMeshManager.recordRenderTime(c),this.renderTimeAvgCount++,this.renderTimeAvg=(this.renderTimeAvg*(this.renderTimeAvgCount-1)+c)/this.renderTimeAvgCount,this.renderTimeMax=Math.max(this.renderTimeMax,c),this.performanceMonitor.onFrame({totalMs:c,entitiesMs:o,loadedTextureCount:this.renderer.info.memory.textures,fps:this.lastFps})}renderHead(t,r,i,s){let o;if(s.SkullOwner?o=s.SkullOwner.Properties?.textures?.[0]?.Value:o=s.profile?.properties?.find(v=>v.name==="textures")?.value,!!o)try{let a=JSON.parse(z.from(o,"base64").toString()).textures?.SKIN?.url,{skinTexturesProxy:l}=this.worldRendererConfig;l&&(a=a?.replace("http://textures.minecraft.net/",l).replace("https://textures.minecraft.net/",l));let c=Oe(this,a,Fe.head),u=new Q.Group;return i&&c.position.set(0,.3125,.3125),c.position.y-=23/16,u.add(c),this.sceneOrigin.track(u),u.position.set(t.x+.5,t.y+.045,t.z+.5),u.rotation.set(0,-Q.MathUtils.degToRad(r*(i?90:45/2)),0),u.scale.set(.8,.8,.8),u}catch{}}renderSign(t,r,i,s,o){let v=this.getSignTexture(t,o,s);if(!v)return;let a=new Q.Mesh(new Q.PlaneGeometry(1,1),new Q.MeshBasicMaterial({map:v,transparent:!0}));a.renderOrder=999;let l=7/16,c=s?1.3:1;a.scale.set(1*c,l*c,1*c);let u=(s?2:1.5)/16,f=.25/16;i&&!s?a.position.set(0,0,-.5+u+f+1e-4):a.position.set(0,0,u/2+1e-4);let p=new Q.Group;p.rotation.set(0,-Q.MathUtils.degToRad(r*(i?90:45/2)),0),p.add(a);let g=(s?10:8)/16,b=(s?0:i?4.333:9.333)/16,A=g/2+b;return this.sceneOrigin.track(p),p.position.set(t.x+.5,t.y+A,t.z+.5),p}lightUpdate(t,r){for(let i=this.worldSizeParams.minY;i<this.worldSizeParams.worldHeight;i+=16)this.setSectionDirty(new Ue(t,i,r))}rerenderAllChunks(){for(let t of Object.keys(this.sectionObjects)){let[r,i,s]=t.split(",").map(Number);this.setSectionDirty(new Ue(r,i,s))}}updateShowChunksBorder(t){this.chunkMeshManager.updateAllBoxHelpers(t)}resetWorld(){super.resetWorld(),this.pendingSectionUpdates.clear(),this.pendingSectionBufferStartTimes.clear(),this.chunkMeshManager.dispose(),this.chunkMeshManager=new W5(this,this.scene,this.material,this.worldSizeParams.worldHeight,this.viewDistance),this.debugRaycastHelper&&(this.realScene.remove(this.debugRaycastHelper),this.debugRaycastHelper=void 0),this.debugHitPoint&&(this.realScene.remove(this.debugHitPoint),this.debugHitPoint=void 0)}getLoadedChunksRelative(t,r=!1){let[i,s,o]=Gr(t);return Object.fromEntries(Object.entries(this.sectionObjects).map(([v,a])=>{let[l,c,u]=v.split(",").map(Number),[f,p,g]=Gr({x:l,y:c,z:u});return[r?`${f-i},${p-s},${g-o}`:`${f-i},${g-o}`,a]}))}cleanChunkTextures(t,r){let i=this.chunkTextures.get(`${Math.floor(t/16)},${Math.floor(r/16)}`)??{};for(let s of Object.keys(i))i[s].dispose(),delete i[s];this.chunkMeshManager.cleanSignChunkTextures(t,r)}readdChunks(){for(let t of Object.keys(this.sectionObjects))this.scene.remove(this.sectionObjects[t]);setTimeout(()=>{for(let t of Object.keys(this.sectionObjects))this.scene.add(this.sectionObjects[t])},500)}disableUpdates(t=this.scene.children){for(let r of t)r.matrixWorldNeedsUpdate=!1,this.disableUpdates(r.children??[])}removeColumn(t,r){super.removeColumn(t,r),this.cleanChunkTextures(t,r),this.clearPendingSectionUpdatesForChunk(t,r);let i=this.getSectionHeight(),s=this.worldMinYRender;for(let o=s;o<this.worldSizeParams.worldHeight;o+=i){let v=`${t},${o},${r}`;this.chunkMeshManager.sectionObjects[v]&&this.chunkMeshManager.releaseSection(v)}this.chunkMeshManager.onChunkRemovedFromGate(`${t},${r}`)}updateViewerPosition(t){super.updateViewerPosition(t),this.chunkMeshManager.pendingNearReveal.size>0&&this.chunkMeshManager.tryRevealPending()}onViewerChunkPositionChanged(){this.chunkMeshManager.tryRevealPending()}setSectionDirty(...t){let[r]=t;this.cleanChunkTextures(r.x,r.z),super.setSectionDirty(...t)}static getRendererInfo(t){try{let r=t.getContext();return`${r.getParameter(r.getExtension("WEBGL_debug_renderer_info").UNMASKED_RENDERER_WEBGL)}`}catch{}}worldStop(){this.media.onWorldStop()}destroy(){this.performanceMonitor?.reset(),this.pendingSectionUpdates.clear(),this.pendingSectionBufferStartTimes.clear(),this.chunkMeshManager.dispose(),this.disposeModules(),this.fireworksLegacy.destroy(),super.destroy(),this.skyboxRenderer.dispose(),this.fireworks.dispose()}shouldObjectVisible(t){let i=this.getSectionHeight(),s,o,v,a=this.sceneOrigin.getWorldPosition(t);a?(s=a.x,o=a.y,v=a.z):(s=this.sceneOrigin.toWorldX(t.position.x),o=this.sceneOrigin.toWorldY(t.position.y),v=this.sceneOrigin.toWorldZ(t.position.z));let l=Math.floor(s/16)*16,c=Math.floor(v/16)*16,u=Math.floor(o/i)*i,f=`${l},${c}`,p=`${l},${u},${c}`;return!!this.finishedChunks[f]||!!this.sectionObjects[p]}handleUserClick(t){this.media.handleUserClick(t)}updateSectionOffsets(){let t=performance.now();for(let[r,i]of Object.entries(this.sectionsOffsetsAnimations)){let s=(t-i.time)/1e3;i.time=t,i.currentOffsetX+=i.speedX*s,i.currentOffsetY+=i.speedY*s,i.currentOffsetZ+=i.speedZ*s,i.limitX!==void 0&&(i.speedX>0?i.currentOffsetX=Math.min(i.currentOffsetX,i.limitX):i.currentOffsetX=Math.max(i.currentOffsetX,i.limitX)),i.limitY!==void 0&&(i.speedY>0?i.currentOffsetY=Math.min(i.currentOffsetY,i.limitY):i.currentOffsetY=Math.max(i.currentOffsetY,i.limitY)),i.limitZ!==void 0&&(i.speedZ>0?i.currentOffsetZ=Math.min(i.currentOffsetZ,i.limitZ):i.currentOffsetZ=Math.max(i.currentOffsetZ,i.limitZ));let o=this.sectionObjects[r];o&&(o.position.set(i.currentOffsetX,i.currentOffsetY,i.currentOffsetZ),o.updateMatrix())}}reloadWorld(){this.entities.reloadEntities()}};d(pt,"FOV_TRANSITION_MS",200),d(pt,"MAX_SECTION_UPDATE_BUFFER_MS",500);var gt=pt;E();x();k();R();E();x();k();R();var Ge="1.21.4";E();x();k();R();function bt(n,e){n.aspect=e.width/e.height,n.updateProjectionMatrix()}E();x();k();R();function tn(n,e=!1){return n?.mode?n.mode:e?"worldBlocks":ge.mode}E();x();k();R();import*as v0 from"three";E();x();k();R();function rn(...n){let e=n.filter(r=>r.length>0).join("/"),t=typeof globalThis.location<"u"&&globalThis.location.href?globalThis.location.href:typeof import.meta<"u"&&import.meta.url?import.meta.url:`/${e}`;try{return new URL(e,t).href}catch{return`/${e}`}}var nn=new Date,Pa=nn.getMonth()===11&&nn.getDate()>=24&&nn.getDate()<=26,Yv=["panorama_3.webp","panorama_1.webp","panorama_4.webp","panorama_5.webp","panorama_0.webp","panorama_2.webp"],Qv=200,Jt=class{constructor(e){this.documentRenderer=e;d(this,"scene");d(this,"camera");d(this,"startTimes",new Map);d(this,"time",0);d(this,"panoramaGroup",null);this.scene=new v0.Scene,this.scene.background=new v0.Color(3294568);let t=new v0.AmbientLight(13421772);this.scene.add(t);let r=new v0.DirectionalLight(16777215,.5);r.position.set(1,1,.5).normalize(),r.castShadow=!0,this.scene.add(r),this.camera=new v0.PerspectiveCamera(85,e.canvas.width/e.canvas.height,.05,1e3),this.camera.position.set(0,0,0),this.camera.rotation.set(0,0,0)}async init(){this.buildCubemap()}update(e,t){t&&bt(this.camera,this.documentRenderer.canvas)}dispose(){this.scene.clear(),this.panoramaGroup=null,this.startTimes.clear()}buildCubemap(){let e=new v0.BoxGeometry(1e3,1e3,1e3),t=[];for(let s of Yv)(async()=>{let v=rn("background",Pa?"christmas":"",s),a=await nt(v),l=Pe(a);l.matrixAutoUpdate=!1,l.matrix.set(-1,0,1,0,1,0,0,0,1),l.wrapS=v0.ClampToEdgeWrapping,l.wrapT=v0.ClampToEdgeWrapping,l.minFilter=v0.LinearFilter,l.magFilter=v0.LinearFilter;let c=new v0.MeshBasicMaterial({map:l,transparent:!0,side:v0.DoubleSide,depthWrite:!1,opacity:0});this.startTimes.set(c,Date.now()),t.push(c)})().catch(v=>{});let r=new v0.Mesh(e,t);r.onBeforeRender=()=>{this.time+=.01,r.rotation.y=Math.PI+this.time*.01,r.rotation.z=Math.sin(-this.time*.001)*.001;for(let s of t){let o=this.startTimes.get(s);if(o){let v=Date.now()-o;s.opacity=Math.min(1,v/Qv)}}};let i=new v0.Object3D;if(i.add(r),!Pa)for(let s=0;s<20;s++){let o=new Te("1.16.4","squid").mesh;o.position.set(Math.random()*30-15,Math.random()*20-10,Math.random()*10-17),o.rotation.set(0,Math.PI+Math.random(),-Math.PI/4,"ZYX");let v=Math.random()*.01;o.children[0].onBeforeRender=()=>{o.rotation.y+=v,o.rotation.z=Math.cos(r.rotation.y*3)*Math.PI/4-Math.PI/2},i.add(o)}this.scene.add(i),this.panoramaGroup=i}async debugImageInFrontOfCamera(){let e=await nt(rn("background","panorama_0.webp")),t=Pe(e),r=new v0.Mesh(new v0.PlaneGeometry(1e3,1e3),new v0.MeshBasicMaterial({map:t}));r.position.set(0,0,-500),this.scene.add(r)}};E();x();k();R();import*as V from"three";var Ia=.1,on={mixed:["white_wool","cyan_wool","blue_wool","purple_wool","white_stained_glass","cyan_stained_glass","blue_stained_glass","purple_stained_glass","glowstone","sea_lantern","amethyst_block","copper_block","gold_block","diamond_block"],stainedGlass:["white_stained_glass","orange_stained_glass","magenta_stained_glass","light_blue_stained_glass","yellow_stained_glass","lime_stained_glass","pink_stained_glass","gray_stained_glass","light_gray_stained_glass","cyan_stained_glass","purple_stained_glass","blue_stained_glass","brown_stained_glass","green_stained_glass","red_stained_glass","black_stained_glass"],wool:["white_wool","orange_wool","magenta_wool","light_blue_wool","yellow_wool","lime_wool","pink_wool","gray_wool","light_gray_wool","cyan_wool","purple_wool","blue_wool","brown_wool","green_wool","red_wool","black_wool"],construction:["copper_block","exposed_copper","weathered_copper","oxidized_copper","cut_copper","exposed_cut_copper","weathered_cut_copper","oxidized_cut_copper","iron_block","gold_block","diamond_block","emerald_block","netherite_block","lapis_block","redstone_block","coal_block","quartz_block","amethyst_block","bricks","stone_bricks","deepslate_bricks","polished_blackstone"],glow:["glowstone","sea_lantern","shroomlight","ochre_froglight","verdant_froglight","pearlescent_froglight","redstone_lamp","beacon"],world:["grass_block","podzol","mycelium","dirt","coarse_dirt","rooted_dirt","mud","clay","stone","cobblestone","mossy_cobblestone","deepslate","cobbled_deepslate","tuff","calcite","sand","red_sand","gravel","snow_block","coal_ore","deepslate_coal_ore","iron_ore","deepslate_iron_ore","copper_ore","deepslate_copper_ore","gold_ore","deepslate_gold_ore","diamond_ore","deepslate_diamond_ore","emerald_ore","deepslate_emerald_ore","lapis_ore","deepslate_lapis_ore","redstone_ore","deepslate_redstone_ore","nether_gold_ore","ancient_debris","oak_log","birch_log","spruce_log","jungle_log","acacia_log","dark_oak_log","mangrove_log","cherry_log","netherrack","soul_sand","basalt","end_stone"]},Ha={galaxy:{bg:132114,fog:132114,fogD:.011,blocks:[61695,54527,47359,59647,2280703,43263],emit:[13158,8789,6724],nebula:[4403,1114146,4386],galFn:n=>new V.Color(n*.05,n*.2,n),ambient:264216,dir:3368703,pt1:43775,pt2:16729343,name:"GALAXY"},nether:{bg:917760,fog:917760,fogD:.016,blocks:[16720384,16737792,16750848,13373696,16729122,16755200],emit:[2230272,1114112,3346688],nebula:[1704960,851968,1705984],galFn:n=>new V.Color(n,n*.15,0),ambient:1573376,dir:16724736,pt1:16729088,pt2:16755200,name:"NETHER"},end:{bg:0,fog:0,fogD:.009,blocks:[7807658,11158732,5570679,14527231,3342421,12299007],emit:[655381,1572901,327696],nebula:[524312,851989,262158],galFn:n=>new V.Color(n*.4,0,n),ambient:393232,dir:10040319,pt1:11158783,pt2:4456618,name:"THE END"},cyber:{bg:2566,fog:2566,fogD:.01,blocks:[65535,65416,11206400,52479,6749952,65518],emit:[8721,6656,6690],nebula:[6674,5120,4634],galFn:n=>new V.Color(0,n,n*.6),ambient:6669,dir:65450,pt1:65484,pt2:4521728,name:"CYBER"},light:{bg:8951984,fog:7899296,fogD:.006,gradientBg:{top:14214392,mid:10531016,bottom:6846608,radial:!0},blocks:[15266559,13691135,12114175,10537208,8960240,7383272,10012927,12640511,15792383,7909608,14216447,14739711],emit:[6854864,8958176,11061488,12638456],nebula:[9480392,11059424,12637420,14215416,7901360],galFn:n=>{let e=new V.Color;return n<.4?e.lerpColors(new V.Color(16054527),new V.Color(14215423),n/.4):n<.75?e.lerpColors(new V.Color(14215423),new V.Color(11061488),(n-.4)/.35):e.lerpColors(new V.Color(11061488),new V.Color(9482464),(n-.75)/.25),e},ambient:7899296,dir:13688040,pt1:11061503,pt2:13162751,name:"LIGHT",starColor:15266047,starOpacity:.5,galaxyOpacity:.7,nebulaOpacity:.32,edgeLineColor:10010856,blockOpacity:[.42,.56]}},Kv={cruise:{pos:(n,e,t)=>({x:Math.sin(n*.28)*18+Math.cos(n*.11)*7+e*10,y:Math.sin(n*.19)*6+Math.cos(n*.31)*3+t*6,z:0}),look:(n,e,t)=>({x:Math.sin((n+.18)*.28)*18+e*8,y:Math.sin((n+.18)*.19)*6+t*4,z:-25}),roll:(n,e=0)=>e*.05+Math.sin(n*.22)*.015,spd:.18},barrel:{pos:(n,e,t)=>{let i=n*2.4;return{x:Math.cos(i)*10+e*4,y:Math.sin(i)*10+t*4,z:Math.sin(n*.4)*8}},look:n=>({x:Math.sin(n*.5)*5,y:Math.cos(n*.5)*5,z:-30}),roll:n=>n*2.4+Math.PI*.5,spd:.24},dive:{pos:(n,e,t)=>({x:Math.sin(n*.6)*30+e*8,y:Math.cos(n*.4)*18+t*6,z:Math.sin(n*.3)*12}),look:(n,e,t)=>({x:Math.sin(n*.6+.2)*30+e*6,y:Math.cos(n*.4+.2)*18-8+t*4,z:-35}),roll:(n,e=0)=>e*.08+Math.sin(n*.6)*.12,spd:.3},orbit:{pos:(n,e,t)=>({x:Math.cos(n*.5)*20+e*5,y:Math.sin(n*.25)*10+t*5,z:Math.sin(n*.5)*20}),look:()=>({x:0,y:0,z:-60}),roll:n=>Math.sin(n*.5)*.08,spd:.15},snake:{pos:(n,e,t)=>({x:Math.sin(n*1.1)*22+Math.sin(n*.37)*8+e*10,y:Math.sin(n*.7)*10+e*4+t*8,z:0}),look:(n,e,t)=>{let r=n+.12;return{x:Math.sin(r*1.1)*22+Math.sin(r*.37)*8+e*8,y:Math.sin(r*.7)*10+t*6,z:-22}},roll:(n,e=0)=>e*.1+Math.sin(n*1.1)*.06,spd:.22}},Jv={cruise:1,barrel:1.6,dive:2.2,orbit:.7,snake:1.4},qv=250,lr=1e4,cr=3e3,qt=n=>n[Math.floor(Math.random()*n.length)],sn=n=>"#"+n.toString(16).padStart(6,"0"),Oa=n=>{if(typeof document>"u")return null;let e=document.createElement("canvas");e.width=4,e.height=512;let t=e.getContext("2d");if(!t)return null;let r=e.width,i=e.height,s=n.radial?t.createRadialGradient(r/2,i*.32,0,r/2,i*.32,i*.85):t.createLinearGradient(0,0,0,i);s.addColorStop(0,sn(n.top)),n.mid!=null&&s.addColorStop(.45,sn(n.mid)),s.addColorStop(1,sn(n.bottom)),t.fillStyle=s,t.fillRect(0,0,r,i);let o=new V.CanvasTexture(e);return o.needsUpdate=!0,o},yt=class{constructor(e,t={},r){this.documentRenderer=e;this.abortSignal=r;d(this,"scene");d(this,"camera");d(this,"ambient");d(this,"dir");d(this,"pt1");d(this,"pt2");d(this,"blocks",[]);d(this,"bGroup",new V.Group);d(this,"galaxy");d(this,"nebula");d(this,"stars");d(this,"galGeo");d(this,"nebGeo");d(this,"bGeo",new V.BoxGeometry(1,1,1));d(this,"eGeo",new V.EdgesGeometry(this.bGeo));d(this,"curScene");d(this,"curCam");d(this,"blockGroup");d(this,"cameraSpeed");d(this,"blockSpeed");d(this,"camT",0);d(this,"mx",0);d(this,"my",0);d(this,"tmx",0);d(this,"tmy",0);d(this,"transitioning",!1);d(this,"useMinecraftTextures",!1);d(this,"resourcesManager");d(this,"atlasTexture",null);d(this,"blockMaterialPool",new Map);d(this,"gradientSky",null);d(this,"gradientSkyTexture",null);d(this,"disposed",!1);d(this,"animTime",0);let i=ge;this.curScene=t.initialScene??i.futuristicScene,this.curCam=t.initialCamera??i.futuristicCamera,this.blockGroup=t.initialBlockGroup??i.futuristicBlockGroup,this.cameraSpeed=t.initialCameraSpeed??m5.camera,this.blockSpeed=t.initialBlockSpeed??m5.block,this.useMinecraftTextures=t.useMinecraftTextures??i.minecraftTextures,this.resourcesManager=t.resourcesManager;let s=Ha[this.curScene];this.scene=new V.Scene,this.scene.fog=new V.FogExp2(s.fog,s.fogD),this.applyScenePalette(s),this.camera=new V.PerspectiveCamera(80,this.documentRenderer.canvas.width/this.documentRenderer.canvas.height,.1,700),this.ambient=new V.AmbientLight(s.ambient,2.5),this.scene.add(this.ambient),this.dir=new V.DirectionalLight(s.dir,4),this.dir.position.set(1,1,0),this.scene.add(this.dir),this.pt1=new V.PointLight(s.pt1,5,100),this.scene.add(this.pt1),this.pt2=new V.PointLight(s.pt2,4,80),this.pt2.position.set(30,20,-30),this.scene.add(this.pt2);for(let f=0;f<qv;f++)this.spawnBlock(s,!0);if(!this.useMinecraftTextures){let f=s.edgeLineColor??62975;for(let p=0;p<40;p++){let g=new V.LineBasicMaterial({color:f,transparent:!0,opacity:.25});qt(this.blocks).mesh.add(new V.LineSegments(this.eGeo,g))}}this.scene.add(this.bGroup);let o=new V.BufferGeometry,v=new Float32Array(5e3*3);for(let f=0;f<5e3*3;f++)v[f]=(Math.random()-.5)*500;o.setAttribute("position",new V.BufferAttribute(v,3)),this.stars=new V.Points(o,new V.PointsMaterial({color:s.starColor??16777215,size:.3,transparent:!0,opacity:s.starOpacity??.7,sizeAttenuation:!0})),this.scene.add(this.stars),this.galGeo=new V.BufferGeometry;let a=new Float32Array(lr*3),l=new Float32Array(lr*3);for(let f=0;f<lr;f++){let p=f%3,g=Math.random(),b=p/3*Math.PI*2+g*Math.PI*5,A=g*90+Math.random()*10,y=(1-g)*18;a[f*3]=Math.cos(b)*A+(Math.random()-.5)*y,a[f*3+1]=(Math.random()-.5)*7,a[f*3+2]=Math.sin(b)*A+(Math.random()-.5)*y-180;let w=.2+g*.8,S=s.galFn(w);l[f*3]=S.r,l[f*3+1]=S.g,l[f*3+2]=S.b}this.galGeo.setAttribute("position",new V.BufferAttribute(a,3)),this.galGeo.setAttribute("color",new V.BufferAttribute(l,3)),this.galaxy=new V.Points(this.galGeo,new V.PointsMaterial({size:.9,vertexColors:!0,transparent:!0,opacity:s.galaxyOpacity??.55,sizeAttenuation:!0})),this.scene.add(this.galaxy),this.nebGeo=new V.BufferGeometry;let c=new Float32Array(cr*3),u=new Float32Array(cr*3);for(let f=0;f<cr;f++){let p=25+Math.random()*110,g=Math.random()*Math.PI*2,b=(Math.random()-.5)*Math.PI*.5;c[f*3]=p*Math.cos(g)*Math.cos(b),c[f*3+1]=p*Math.sin(b)*.6,c[f*3+2]=p*Math.sin(g)*Math.cos(b)-80;let A=new V.Color(qt(s.nebula));u[f*3]=A.r,u[f*3+1]=A.g,u[f*3+2]=A.b}this.nebGeo.setAttribute("position",new V.BufferAttribute(c,3)),this.nebGeo.setAttribute("color",new V.BufferAttribute(u,3)),this.nebula=new V.Points(this.nebGeo,new V.PointsMaterial({size:3,vertexColors:!0,transparent:!0,opacity:s.nebulaOpacity??.3,sizeAttenuation:!0})),this.scene.add(this.nebula),this.addBackgroundTextPlane(),this.setupMouseTracking()}async init(){if(this.useMinecraftTextures)try{await this.loadMinecraftTextures()}catch{this.useMinecraftTextures=!1}}applyScenePalette(e){if(this.documentRenderer.renderer.setClearColor(e.bg),e.gradientBg)if(this.scene.background=null,this.gradientSky){if(this.gradientSky.visible=!0,this.gradientSkyTexture&&e.gradientBg){let s=Oa(e.gradientBg);s&&(this.gradientSkyTexture.dispose(),this.gradientSkyTexture=s,this.gradientSky.material.map=s,this.gradientSky.material.needsUpdate=!0)}}else{let s=Oa(e.gradientBg);s?(this.gradientSkyTexture=s,this.gradientSky=new V.Mesh(new V.PlaneGeometry(900,700),new V.MeshBasicMaterial({map:s,depthWrite:!1,side:V.DoubleSide})),this.gradientSky.position.set(0,0,-280),this.gradientSky.renderOrder=-1e3,this.scene.add(this.gradientSky)):this.scene.background=new V.Color(e.bg)}else this.scene.background=new V.Color(e.bg),this.gradientSky&&(this.gradientSky.visible=!1);this.scene.fog instanceof V.FogExp2&&(this.scene.fog.color.set(e.fog),this.scene.fog.density=e.fogD);let t=this.stars?.material;t&&(t.color.set(e.starColor??16777215),t.opacity=e.starOpacity??.7);let r=this.galaxy?.material;r&&(r.opacity=e.galaxyOpacity??.55);let i=this.nebula?.material;i&&(i.opacity=e.nebulaOpacity??.3)}setupMouseTracking(){let e=r=>{let i=typeof window<"u"?window.innerWidth:this.documentRenderer.canvas.width,s=typeof window<"u"?window.innerHeight:this.documentRenderer.canvas.height;this.tmx=(r.clientX/i-.5)*2,this.tmy=-(r.clientY/s-.5)*2};(typeof document<"u"?document:void 0)?.addEventListener("mousemove",e,{signal:this.abortSignal})}addBackgroundTextPlane(){let r=typeof document<"u"?document.createElement("canvas"):null;if(!r)return;r.width=2048,r.height=768;let i=r.getContext("2d");if(!i)return;i.clearRect(0,0,2048,768),i.save(),i.font="bold 560px Orbitron, sans-serif",i.textAlign="center",i.textBaseline="middle",i.shadowColor="rgba(0,200,255,0.35)",i.shadowBlur=80,i.fillStyle="rgba(255,255,255,0.055)",i.fillText("V2",2048*.28,768*.5),i.restore(),i.save(),i.font="bold 148px Orbitron, sans-serif",i.textAlign="center",i.textBaseline="middle",i.shadowColor="rgba(0,200,255,0.2)",i.shadowBlur=40,i.fillStyle="rgba(255,255,255,0.038)",i.fillText("by ZARDOY",2048*.72,768*.52),i.restore();let s=new V.CanvasTexture(r),o=new V.Mesh(new V.PlaneGeometry(280,105),new V.MeshBasicMaterial({map:s,transparent:!0,opacity:1,depthWrite:!1,side:V.DoubleSide,blending:V.AdditiveBlending}));o.position.set(8,4,-320),this.scene.add(o)}spawnBlock(e,t,r){let i=this.createBlockMaterial(e,r),s=new V.Mesh(this.bGeo,i),o=.3+Math.random()*3;s.scale.setScalar(o),s.position.set((Math.random()-.5)*140,(Math.random()-.5)*70,t?-(Math.random()*140):-155-Math.random()*30),s.rotation.set(Math.random()*Math.PI*2,Math.random()*Math.PI*2,Math.random()*Math.PI*2);let v={mesh:s,spd:.04+Math.random()*.12,dx:(Math.random()-.5)*.012,dy:(Math.random()-.5)*.008,rx:(Math.random()-.5)*.012,ry:(Math.random()-.5)*.012,rz:(Math.random()-.5)*.01,minecraftBlockName:r};this.blocks.push(v),this.bGroup.add(s)}createBlockMaterial(e,t){if(this.useMinecraftTextures&&t){let s=this.blockMaterialPool.get(t);if(s)return s.clone()}let[r,i]=e.blockOpacity??[.32,.46];return new V.MeshBasicMaterial({color:qt(e.blocks),transparent:!0,opacity:r+Math.random()*(i-r),depthWrite:!1,blending:V.AdditiveBlending})}removeBlockEdgeLines(){for(let e of this.blocks){let t=e.mesh.children.filter(r=>r instanceof V.LineSegments);for(let r of t){e.mesh.remove(r),r.geometry?.dispose();let i=r.material;Array.isArray(i)?i.forEach(s=>s.dispose()):i.dispose()}}}async ensureMcDataLoaded(){let e=globalThis._LOAD_MC_DATA;e&&await e()}resolveBlockAtlasUv(e,t,r){let i=s=>{let o=t[s];return o?{u:o.u,v:o.v,su:o.su??r.suSv,sv:o.sv??r.suSv}:null};if(t[e])return i(e);for(let s of["_top","_side","_front","_0"]){let o=i(`${e}${s}`);if(o)return o}for(let s of Object.keys(t))if(s.startsWith(e))return i(s);return null}async loadMinecraftTextures(){await this.ensureMcDataLoaded();let e=this.resourcesManager??new fe;if(!e.currentResources?.blocksAtlasImage){if(typeof document>"u")throw new Error("Menu atlas missing in worker; pass resourcesManager from main thread");e.currentConfig={...e.currentConfig,version:Ge,noInventoryGui:!0},await e.updateAssetsData?.({})}let r=e.currentResources;if(!r?.blocksAtlasImage||!r.blocksAtlasJson)throw new Error("Block atlas not available");let i=r.blocksAtlasJson,s=i.textures;this.atlasTexture=Pe(r.blocksAtlasImage),this.atlasTexture.flipY=!1,this.atlasTexture.needsUpdate=!0;for(let o of on[this.blockGroup]){let v=this.resolveBlockAtlasUv(o,s,i);if(!v)continue;let a=this.atlasTexture.clone();a.flipY=!1,a.offset.set(v.u,v.v),a.repeat.set(v.su,v.sv),a.needsUpdate=!0;let l=o.includes("glass"),c=new V.MeshBasicMaterial({map:a,side:V.DoubleSide,transparent:l,opacity:l?.85:1,alphaTest:l?.08:0,depthWrite:!0,toneMapped:!1});this.blockMaterialPool.set(o,c)}if(this.blockMaterialPool.size===0)throw new Error("No block textures resolved from atlas (check block names vs atlas keys)");this.removeBlockEdgeLines();for(let o of this.blocks){let v=qt([...this.blockMaterialPool.keys()]);o.minecraftBlockName=v,o.mesh.material=this.blockMaterialPool.get(v).clone()}}setScene(e){if(!et.includes(e)||e===this.curScene||this.transitioning)return;this.transitioning=!0,this.curScene=e;let t=Ha[e];setTimeout(()=>{if(this.disposed)return;this.applyScenePalette(t),this.ambient.color.set(t.ambient),this.dir.color.set(t.dir),this.pt1.color.set(t.pt1),this.pt2.color.set(t.pt2);for(let s of this.blocks)this.useMinecraftTextures&&s.minecraftBlockName||s.mesh.material instanceof V.MeshBasicMaterial&&s.mesh.material.color.set(qt(t.blocks));let r=this.nebGeo.attributes.color;for(let s=0;s<cr;s++){let o=new V.Color(qt(t.nebula));r.setXYZ(s,o.r,o.g,o.b)}r.needsUpdate=!0;let i=this.galGeo.attributes.color;for(let s=0;s<lr;s++){let o=.2+Math.random()*.8,v=t.galFn(o);i.setXYZ(s,v.r,v.g,v.b)}i.needsUpdate=!0,this.transitioning=!1},150)}setCamera(e){tt.includes(e)&&(this.curCam=e)}setCameraSpeed(e){this.cameraSpeed=Math.max(0,e)}setBlockSpeed(e){this.blockSpeed=Math.max(0,e)}async setBlockGroup(e){if(rt.includes(e)&&e!==this.blockGroup&&(this.blockGroup=e,!(!this.useMinecraftTextures||this.disposed))){for(let t of this.blockMaterialPool.values())t.map?.dispose(),t.dispose();this.blockMaterialPool.clear();try{await this.loadMinecraftTextures()}catch{}}}getSceneId(){return this.curScene}getCameraId(){return this.curCam}getBlockGroupId(){return this.blockGroup}update(e,t){t&&bt(this.camera,this.documentRenderer.canvas);let r=Kv[this.curCam],i=this.cameraSpeed,s=this.blockSpeed;this.camT+=e*r.spd*i,this.mx+=(this.tmx-this.mx)*.05,this.my+=(this.tmy-this.my)*.05;let o=this.mx*Ia,v=this.my*Ia,a=r.pos(this.camT,o,v),l=r.look(this.camT,o,v);this.camera.position.set(a.x,a.y,a.z),this.camera.lookAt(l.x,l.y,l.z),this.camera.rotation.z=r.roll(this.camT,o);let c=Jv[this.curCam]*s;this.animTime+=e*1e3*s;for(let u of this.blocks){if(u.mesh.position.z+=u.spd*c*60*e,u.mesh.position.x+=u.dx*60*e*s,u.mesh.position.y+=u.dy*60*e*s,u.mesh.rotation.x+=u.rx*c,u.mesh.rotation.y+=u.ry*c,u.mesh.rotation.z+=u.rz,!this.useMinecraftTextures&&u.mesh.material instanceof V.MeshBasicMaterial){let f=u.mesh.userData.baseOpacity??.38;u.mesh.userData.baseOpacity==null&&(u.mesh.userData.baseOpacity=f);let p=.88+Math.abs(Math.sin(this.animTime*8e-4+u.mesh.position.x*.3))*.12;u.mesh.material.opacity=f*p}u.mesh.position.z>this.camera.position.z+15&&u.mesh.position.set((Math.random()-.5)*140,(Math.random()-.5)*70,this.camera.position.z-155-Math.random()*30)}this.pt1.position.set(Math.sin(this.camT*.8)*25+this.camera.position.x,Math.cos(this.camT*.6)*12+this.camera.position.y,this.camera.position.z-18),this.pt2.position.set(Math.cos(this.camT*.5)*20+this.camera.position.x,Math.sin(this.camT*.9)*15+this.camera.position.y,this.camera.position.z-30),this.galaxy.rotation.y+=e*.006*s,this.nebula.rotation.y-=e*.003*s,this.stars.rotation.y+=e*4e-4*s}dispose(){this.disposed=!0,this.scene.clear(),this.bGeo.dispose(),this.eGeo.dispose(),this.galGeo.dispose(),this.nebGeo.dispose(),this.gradientSkyTexture?.dispose(),this.atlasTexture?.dispose();for(let e of this.blockMaterialPool.values())e.map?.dispose(),e.dispose();this.blockMaterialPool.clear()}};E();x();k();R();import*as Xt from"three";import{Vec3 as Da}from"vec3";E();x();k();R();import Zv from"prismarine-world";import Xv from"prismarine-chunk";var Fa=n=>{let e=Zv(n),t=Xv(n),r=new e(n).sync,i=$v(r);for(let s of i)if(s.startsWith("set")&&s!=="setColumn"){let o=r[s].bind(r);r[s]=(...v)=>{let a=v[0];a.x!==void 0&&!r.getColumnAt(a)&&r.setColumn(Math.floor(a.x/16),Math.floor(a.z/16),new t(void 0)),o(...v)}}return r};function $v(n){let e=new Set,t=n;do for(let r of Object.getOwnPropertyNames(t))typeof n[r]=="function"&&r!=="constructor"&&e.add(r);while(t=Object.getPrototypeOf(t));return[...e]}var Zt=class{constructor(e,t,r){this.documentRenderer=e;this.options=t;this.abortSignal=r;d(this,"_scene");d(this,"_camera");d(this,"worldRenderer");d(this,"WorldRendererClass",gt);this._scene=new Xt.Scene,this._scene.background=new Xt.Color(3294568),this._camera=new Xt.PerspectiveCamera(85,e.canvas.width/e.canvas.height,.05,1e3),this.camera.position.set(0,0,0),this.camera.rotation.set(0,0,0)}get scene(){return this._scene}get camera(){return this._camera}async init(){let e=Ge,t=new fe;if(t.currentConfig={version:e,noInventoryGui:!0},await t.updateAssetsData?.({}),this.abortSignal.aborted)return;let r=Fa(e),s=Ka("prismarine-block")(e),v=globalThis.mcData.blocksArray.filter(p=>{if(!p.name.includes("stained_glass"))return!1;let g=s.fromStateId(p.defaultState,0);if(g.shapes?.length!==1)return!1;let b=g.shapes[0];return b[0]===0&&b[1]===0&&b[2]===0&&b[3]===1&&b[4]===1&&b[5]===1}),a=-15,l=100,c=100;for(let p=-l;p<l;p++)for(let g=-c;g<c;g++){let b=v[Math.floor(Math.random()*v.length)];r.setBlockStateId(new Da(p,g,a),b.defaultState)}this._camera.updateProjectionMatrix(),this._camera.position.set(.5,c/2+.5,.5),this._camera.rotation.set(0,0,0);let u=new Da(...this._camera.position.toArray()),f=new Xe(r,2,u);this.abortSignal.aborted||(this.worldRenderer=new this.WorldRendererClass(this.documentRenderer.renderer,this.options,{version:e,worldView:f,inWorldRenderingConfig:a5,playerStateReactive:H2().reactive,rendererState:Ke().reactive,nonReactiveState:Ke().nonReactive,resourcesManager:t}),this.worldRenderer instanceof gt&&(this._scene=this.worldRenderer.realScene,this._camera=this.worldRenderer.camera),f.init(u),await this.worldRenderer.waitForChunksToRender(),!this.abortSignal.aborted&&this.setupMouseParallax())}update(e,t){t&&bt(this.camera,this.documentRenderer.canvas)}dispose(){this.worldRenderer?.destroy(),this.worldRenderer=void 0,this._scene.clear()}setupMouseParallax(){let e=this._camera,t=e.position.x,r=e.position.y,i;document.body.addEventListener("pointermove",s=>{if(s.pointerType!=="mouse")return;let o=.2,v=s.clientX/window.innerWidth-.5,a=-(s.clientY/window.innerHeight-.5);i?.stop(),i=new F0(e.position).to({x:t+v*o,y:r+a*o},0),i.start(),e.updateProjectionMatrix()},{signal:this.abortSignal})}};E();x();k();R();import*as za from"three";var $t=class{constructor(e,t,r={},i=!1){this.documentRenderer=e;this.options=t;d(this,"active");d(this,"abortController",new AbortController);d(this,"mode");d(this,"lastFrameTime",0);this.mode=tn(r,i)}get futuristic(){return this.active instanceof yt?this.active:void 0}get scene(){return this.active?.scene}get camera(){return this.active?.camera}async start(e={}){this.active=this.createImplementation(e),await this.active.init(),this.active.scene.background instanceof za.Color&&this.documentRenderer.renderer.setClearColor(this.active.scene.background),this.lastFrameTime=performance.now(),this.documentRenderer.render=(t=!1)=>{let r=performance.now(),i=Math.min((r-this.lastFrameTime)/1e3,.05);this.lastFrameTime=r;let s=this.active;s&&(s.update(i,t),this.documentRenderer.renderer.render(s.scene,s.camera))}}createImplementation(e){switch(this.mode){case"futuristic":return new yt(this.documentRenderer,{useMinecraftTextures:e.useMinecraftTextures,initialScene:e.futuristicScene,initialCamera:e.futuristicCamera,initialBlockGroup:e.futuristicBlockGroup,initialCameraSpeed:e.futuristicCameraSpeed,initialBlockSpeed:e.futuristicBlockSpeed,resourcesManager:e.resourcesManager},this.abortController.signal);case"worldBlocks":return new Zt(this.documentRenderer,this.options,this.abortController.signal);default:return new Jt(this.documentRenderer)}}dispose(){this.active?.dispose(),this.active=void 0,this.abortController.abort()}};V5.ColorManagement.enabled=!1;globalThis.THREE=V5;var La=n=>({updateMap:n.entities.updateMap.bind(n.entities),updateCustomBlock:n.updateCustomBlock.bind(n),getBlockInfo:n.getBlockInfo.bind(n),playEntityAnimation:n.entities.playAnimation.bind(n.entities),damageEntity:n.entities.handleDamageEvent.bind(n.entities),updatePlayerSkin:n.entities.updatePlayerSkin.bind(n.entities),changeHandSwingingState:n.changeHandSwingingState.bind(n),getHighestBlocks:n.getHighestBlocks.bind(n),reloadWorld:n.reloadWorld.bind(n),updateEntityModel:n.entities.updateEntityModel.bind(n.entities),playEntityModelAnimation:n.entities.playEntityModelAnimation.bind(n.entities),addMedia:n.media.addMedia.bind(n.media),destroyMedia:n.media.destroyMedia.bind(n.media),setControlMode:n.media.setControlMode.bind(n.media),setVideoPlaying:n.media.setVideoPlaying.bind(n.media),setVideoSeeking:n.media.setVideoSeeking.bind(n.media),setVideoVolume:n.media.setVideoVolume.bind(n.media),setVideoSpeed:n.media.setVideoSpeed.bind(n.media),handleUserClick:n.media.handleUserClick.bind(n.media),addSectionAnimation(e,t){n.sectionsOffsetsAnimations[e]=t},removeSectionAnimation(e){delete n.sectionsOffsetsAnimations[e]},shakeFromDamage:n.cameraShake.shakeFromDamage.bind(n.cameraShake),onPageInteraction:n.media.onPageInteraction.bind(n.media),downloadMesherLog:n.downloadMesherLog.bind(n),explodeFirework:n.fireworksLegacy.explode.bind(n.fireworksLegacy),explodeFireworkFacingCamera:n.fireworksLegacy.explodeFacingCamera.bind(n.fireworksLegacy),addWaypoint:n.waypoints.addWaypoint.bind(n.waypoints),removeWaypoint:n.waypoints.removeWaypoint.bind(n.waypoints),startCinimaticScript:n.cinimaticScript.startScript.bind(n.cinimaticScript),stopCinimaticScript:n.cinimaticScript.stopScript.bind(n.cinimaticScript),launchFirework:n.fireworks.launchFirework.bind(n.fireworks),setSkyboxImage:n.skyboxRenderer.setSkyboxImage.bind(n.skyboxRenderer),setRain:e=>n.toggleModule("rain",e),spawnBlockBreakParticles(e,t,r,i,s,o){n.getModule("blockBreakParticles")?.spawnBlockBreakParticles(e,t,r,i,s,o)},spawnBlockCrackParticle(e,t,r,i,s,o,v){n.getModule("blockBreakParticles")?.spawnCrackParticle(e,t,r,i,s,o,v)},async loadGeometryExport(e){let{applyWorldGeometryExport:t}=await Promise.resolve().then(()=>(Wi(),ca));return t(n,e)},feedChunkPacket(e){let{kind:t,...r}=e,i={type:t,...r};for(let s of n.workers)s.postMessage(i)}}),t9=[],dr=(n,...e)=>{for(let t of Object.values(globalThis.loadedMods??{}))try{t.threeJsBackendModule?.[n]?.(...e)}catch(r){let i=`[mod three.js] Error calling ${n} on ${t.name}: ${r}`;throw new Error(i)}},Ua=()=>{let n,e=null,t=null,r=null,i=null,s=(c,u)=>{a0?n=d1(c,t9,globalThis):n=c,e=new d5(n,u?.canvas),globalThis.renderer=e.renderer,globalThis.documentRenderer=e,globalThis.threeJsBackend=l,dr("default",l)},o=async c=>{if(!e)throw new Error("Document renderer not initialized");r&&(r.destroy(),r=null,i=null,globalThis.world=void 0,globalThis.frameTimingCollector=void 0),t&&(t.dispose(),t=null);let u={...n.config.menuBackground,...c};t=new $t(e,{...n},u,!!F.env.SINGLE_FILE_BUILD_MODE),dr("menuBackgroundCreated",t),await t.start(u),dr("menuBackgroundReady",t)},v=async c=>{let f=a0?d1(c,[fe,Ze],globalThis):c;if(!e)throw new Error("Document renderer not initialized");e.nonReactiveState=f.nonReactiveState,globalThis.resourcesManager=f.resourcesManager,t&&(t.dispose(),t=null),r=new gt(e.renderer,n,f),await r.worldReadyPromise,i=new u1(f.nonReactiveState),globalThis.frameTimingCollector=i;let p=e.render;e.render=function(g){p.call(this,g),i?.markFrameStart(),f.inWorldRenderingConfig.paused||r?.render(g),i?.markFrameEnd(),i?.markFrameDisplay()},e.inWorldRenderingConfig=f.inWorldRenderingConfig,globalThis.world=r,dr("worldReady",r)},a=()=>{t&&(t.dispose(),t=null),e&&e.dispose(),r&&(r.destroy(),r=null)},l={id:"threejs",displayName:`three.js ${V5.REVISION}`,startMenuBackground:o,startWorld:v,disconnect:a,setRendering(c){e.setPaused(!c),r&&(r.renderingActive=c)},getMenuBackground:()=>t??void 0,getDebugOverlay:()=>({get entitiesString(){return r?.entities.getDebugString()},get left(){return{"Geo Memory":r?.chunkMeshManager.getEstimatedMemoryUsage().total??"-"}}}),updateCamera(c,u,f){i?.markCameraUpdate(!c),r?.setFirstPersonCamera(c,u,f)},get soundSystem(){return r?.soundSystem},get backendMethods(){if(r)return La(r)}};return{main:{init:s,backend:l},workerProxy(){return cs({init(c,u){s(c,{canvas:u})},updateSizeExternal(c,u,f){e?.updateSizeExternal(c,u,f)},startMenuBackground:o,startWorld:v,disconnect:a,setRendering:l.setRendering,updateCamera(c,u,f){let p=c?new e9(c.x,c.y,c.z):null;i?.markCameraUpdate(!p),l.updateCamera(p,u,f)},async callBackendMethod(c,...u){if(!r)throw new Error("World renderer not initialized");let p=La(r)[c];if(!p)throw new Error(`Backend method ${String(c)} is unavailable`);return p(...u)}})}}};var ur=n=>{let{main:e}=Ua();return e.init(n),e.backend};ur.id="threejs";ur.displayName="three.js Blocking";ur.description="Simple, old and stable main thread graphics backend providing balanced performance on top of WebGL2.";E();x();k();R();import*as Ga from"three";function r9(n){let e="threeWorker.js",t;if(F.env.SINGLE_FILE_BUILD){let r=document.getElementById("three-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}var fr=async n=>{let e=r9(()=>{}),t=ds(e),r=Cr();r.onSizeChanged((v,a)=>{t.updateSizeExternal(v,a,window.devicePixelRatio||1)});let i=b5(n,e);try{t.init(i,r.canvas)}catch(v){throw Ct(i),v}let s=new Proxy({},{get(v,a){if(typeof a=="string")return async(...l)=>t.callBackendMethod(a,...l)}});return{id:"threejs",displayName:`three.js ${Ga.REVISION}`,async startMenuBackground(v){let a=v?.resourcesManager?.currentResources?.mcData;if(a){let c={...st,items:"itemsArray",entities:"entitiesArray"};await Yr([e],Ge,c,a)}let l=b5(v??{},e);try{await t.startMenuBackground(structuredClone(l))}catch(c){throw Ct(l),c}},async startWorld(v){let a={...st,items:"itemsArray",entities:"entitiesArray"};await Yr([e],v.version,a,v.resourcesManager.currentResources.mcData),v.inWorldRenderingConfig.__syncToWorker=!0,v.playerStateReactive&&(v.playerStateReactive.__syncToWorker=!0),v.rendererState&&(v.rendererState.__syncFromWorker=!0),v.nonReactiveState&&(v.nonReactiveState.__syncFromWorker=!0),v.nonReactiveState.__syncFromWorkerInterval=200;let l=b5(v,e);try{await t.startWorld(structuredClone(l))}catch(u){throw Ct(l),u}t.updateSizeExternal(r.size.width,r.size.height,window.devicePixelRatio||1);let c=Pt("fps");setInterval(()=>{let{fps:u,avgRenderTime:f,worstRenderTime:p}=v.nonReactiveState;c.updateText(`FPS: ${u.toFixed(0)} (${f.toFixed(0)}ms/${p.toFixed(0)}ms)`),v.nonReactiveState.fps=0},1e3)},disconnect(){r.destroy(),t.disconnect(),e.terminate()},setRendering(v){t.setRendering(v)},updateCamera(v,a,l){t.updateCamera(v?{x:v.x,y:v.y,z:v.z}:null,a,l)},soundSystem:void 0,backendMethods:s}};fr.id="threejs-off-thread";fr.displayName="three.js Multi-thread";fr.description=["Edge-cutting technology that uses a dedicated thread for graphics.","Slightly higher power and RAM usage.","More stable FPS (mid-range devices), but possible inputlag if TPS is low.","On low-end devices it might result in device throttling and stuttering."].join(" ");export{Z2 as AppViewer,Jt as ClassicMenuBackground,d5 as DocumentRenderer,tt as FUTURISTIC_CAMERA_IDS,f5 as FUTURISTIC_CAMERA_LABELS,et as FUTURISTIC_SCENE_IDS,u5 as FUTURISTIC_SCENE_LABELS,yt as FuturisticMenuBackground,_r as HIGH_TEXTURE_COUNT,$5 as LONG_RENDER_TIME_MS,yr as LOW_FPS_THRESHOLD,Tt as LoadedResourcesTransferrable,y5 as MC_RENDERER_DEBUG_OVERLAY_CLASS,Ge as MENU_BACKGROUND_MC_VERSION,m5 as MENU_BACKGROUND_MOTION_DEFAULTS,ge as MENU_BACKGROUND_OPTION_DEFAULTS,on as MINECRAFT_BLOCK_GROUPS,rt as MINECRAFT_BLOCK_GROUP_IDS,h5 as MINECRAFT_BLOCK_GROUP_LABELS,$t as MenuBackgroundRenderer,o5 as PerformanceMonitor,X2 as RENDERER_DEFAULT_OPTIONS,$2 as RENDERER_OPTIONS_META,es as RENDERER_RENDER_GUI_SECTIONS,fe as ResourcesManager,Zt as WorldBlocksMenuBackground,Xe as WorldView,Ze as WorldViewWorker,Cr as addCanvasForWorker,C6 as applyMenuBackgroundLiveOptions,vf as applyRendererEnableLighting,O6 as applyRendererOptions,of as applyRendererWorldViewOptions,xt as chunkPos,fr as createGraphicsBackendOffThread,ur as createGraphicsBackendSingleThread,dl as createWorldRendererConfig,P2 as defaultGraphicsBackendConfig,br as defaultPerformanceInstabilityFactors,a5 as defaultWorldRendererConfig,F2 as delayedIterator,wr as formatPerformanceFactorsDebug,Ke as getDefaultRendererState,ns as getInitialPlayerState,z6 as getInitialPlayerStateRenderer,D6 as getPlayerStateUtils,a0 as isWebWorker,sf as menuBackgroundOptionsFromStorage,we as menuBackgroundSpeedToMultiplier,_6 as migrateRendererOptions,Ir as rendererShaderCubeDebugModeToValue,a6 as sectionPos,af as subscribeRendererOptions};
21508
+ }`})}},en=class{constructor(e){this.worldRenderer=e;d(this,"points");d(this,"clock",new M0.Clock);d(this,"enabled",!1);d(this,"currentTime");d(this,"enablementCheck",()=>this.currentTime?this.currentTime>13500&&this.currentTime<23e3:!1);d(this,"render",e=>{this.points&&(this.points.position.set(0,0,0),this.points.material.uniforms.time.value=this.clock.getElapsedTime()*.2)})}enable(){this.enabled||(this.enabled=!0,this.updateVisibility())}disable(){this.enabled&&(this.enabled=!1,this.removeStars())}toggle(){return this.enabled?this.disable():this.enable(),this.enabled}updateTimeOfDay(e){this.currentTime=e,this.enabled&&this.updateVisibility()}updateVisibility(){if(!this.enabled)return;let e=this.enablementCheck?.()??!1;e&&!this.points?this.createStars():!e&&this.points&&this.removeStars()}createStars(){if(this.points)return;let e=80,t=50,r=7e3,i=7,s=10,o=new M0.BufferGeometry,v=b=>new M0.Vector3().setFromSpherical(new M0.Spherical(b,Math.acos(1-Math.random()*2),Math.random()*2*Math.PI)),a=[],l=[],c=Array.from({length:r},()=>(.5+.5*Math.random())*i),u=new M0.Color,f=e+t,p=t/r;for(let b=0;b<r;b++)f-=p*Math.random(),a.push(...v(f).toArray()),u.setHSL(b/r,s,.9),l.push(u.r,u.g,u.b);o.setAttribute("position",new M0.Float32BufferAttribute(a,3)),o.setAttribute("color",new M0.Float32BufferAttribute(l,3)),o.setAttribute("size",new M0.Float32BufferAttribute(c,1));let g=new $i;g.blending=M0.AdditiveBlending,g.depthTest=!0,g.depthWrite=!1,g.transparent=!0,this.points=new M0.Points(o,g),this.points.renderOrder=-1,this.worldRenderer.scene.add(this.points)}dispose(){this.removeStars()}removeStars(){this.points&&(this.points.geometry.dispose(),this.points.material.dispose(),this.worldRenderer.scene.remove(this.points),this.points=void 0)}},Ca={id:"starfield",controller:en,enabledDefault:!0,cannotBeDisabled:!0};var Ba={starfield:Ca,futuristicReveal:Sa,rain:Ta,cameraBobbing:Ea,blockBreakParticles:Aa};var pt=class pt extends h1{constructor(t,r,i){if(!i.resourcesManager)throw new Error("resourcesManager is required in displayOptions");super(i.resourcesManager,i,r);this.renderer=t;this.initOptions=r;this.displayOptions=i;d(this,"outputFormat","threeJs");d(this,"chunkMeshManager");d(this,"chunkTextures",new Map);d(this,"signsCache",new Map);d(this,"cameraSectionPos",new Ue(0,0,0));d(this,"holdingBlock");d(this,"holdingBlockLeft");d(this,"scene",new Q.Scene);d(this,"ambientLight",new Q.AmbientLight(13421772));d(this,"directionalLight",new Q.DirectionalLight(16777215,.5));d(this,"entities",new F1(this,globalThis.mcData));d(this,"performanceMonitor");d(this,"cameraGroupVr");d(this,"material",new Q.MeshBasicMaterial({vertexColors:!0,transparent:!0,alphaTest:.1}));d(this,"itemsTexture");d(this,"cursorBlock");d(this,"onRender",[]);d(this,"lastRenderTime",0);d(this,"animatedFov",0);d(this,"lastFovAnimTime",0);d(this,"cameraShake");d(this,"cameraContainer");d(this,"media");d(this,"waypoints");d(this,"cinimaticScript");d(this,"camera");d(this,"renderTimeAvg",0);d(this,"pendingSectionUpdates",new Map);d(this,"pendingSectionBufferStartTimes",new Map);d(this,"modules",{});d(this,"sectionsOffsetsAnimations",{});d(this,"fountains",[]);d(this,"fireworksLegacy");d(this,"DEBUG_RAYCAST",!1);d(this,"skyboxRenderer");d(this,"fireworks");d(this,"sceneOrigin",new K1(this.scene));d(this,"cameraWorldPos",{x:0,y:0,z:0});d(this,"_cameraPositionAccessWarned",!1);d(this,"_tmpCameraPos",new Q.Vector3);d(this,"currentPosTween");d(this,"currentRotTween");d(this,"_tpDirection",new Q.Vector3);d(this,"_tpPitchQuat",new Q.Quaternion);d(this,"_tpYawQuat",new Q.Quaternion);d(this,"_tpFinalQuat",new Q.Quaternion);d(this,"_tpScenePos",new Q.Vector3);d(this,"_tpAxisX",new Q.Vector3(1,0,0));d(this,"_tpAxisY",new Q.Vector3(0,1,0));d(this,"_tpRaycaster",new Q.Raycaster);d(this,"_tpChunkWorldPos",new Q.Vector3);d(this,"debugOverlayAdded",!1);d(this,"debugRaycastHelper");d(this,"debugHitPoint");d(this,"prevFramePerspective",null);this.performanceMonitor=new o5(this.reactiveState.world.instabilityFactors),this.renderer=t,i.rendererState.renderer=pt.getRendererInfo(t)??"...",this.chunkMeshManager=new W5(this,this.scene,this.material,this.worldSizeParams.worldHeight,this.viewDistance),this.onRenderDistanceChanged=s=>{this.chunkMeshManager.updateViewDistance(s)},this.cursorBlock=new D1(this),this.holdingBlock=D5(this),this.holdingBlockLeft=D5(this,!0);for(let s of Object.values(Ba))this.registerModule(s);this.skyboxRenderer=new Y1(this.realScene,!1,null),this.skyboxRenderer.init(),this.addDebugOverlay(),this.resetScene(),this.init(),this.soundSystem=new L1(this),this.cameraShake=new U1(this,this.onRender),this.media=new G1(this),this.fireworksLegacy=new V1(this),this.waypoints=new W1(this),this.cinimaticScript=new j1(this,(s,o,v)=>this.setCinimaticCamera(s,o,v),s=>this.setCinimaticFov(s),()=>({position:new Ue(this.cameraWorldPos.x,this.cameraWorldPos.y,this.cameraWorldPos.z),yaw:this.cameraShake.getBaseRotation().yaw,pitch:this.cameraShake.getBaseRotation().pitch,fov:this.camera.fov})),this.fireworks=new Q1(this.realScene,this.sceneOrigin),this.renderUpdateEmitter.on("chunkFinished",s=>{this.finishChunk(s)}),this.worldSwitchActions(),this.initializeModules()}isShaderCubeBlocksEnabled(){return this.worldRendererConfig.shaderCubeBlocks===!0&&!!this.renderer?.capabilities?.isWebGL2}get sectionObjects(){return this.chunkMeshManager.sectionObjects}get realScene(){return this.scene}get waitingChunksToDisplay(){return this.chunkMeshManager.waitingChunksToDisplay}get estimatedMemoryUsage(){return this.chunkMeshManager.getEstimatedMemoryUsage().total}get tilesRendered(){return this.chunkMeshManager.getTotalTiles()}get blocksRendered(){return this.chunkMeshManager.getTotalBlocks()}registerModule(t){if(t.id in this.modules)return;let r=new t.controller(this),i={manifest:t,controller:r,enabled:!1,toggle:()=>this.toggleModule(t.id)};this.modules[t.id]=i,t.enabledDefault&&this.toggleModule(t.id,!0)}enableModule(t){let r=this.modules[t];r&&(r.enabled||(r.enabled=!0,r.controller.enable(),r.controller.render&&this.onRender.push(r.controller.render)))}disableModule(t){let r=this.modules[t];if(r&&!r.manifest.cannotBeDisabled&&r.enabled&&(r.enabled=!1,r.controller.disable(),r.controller.render)){let i=this.onRender.indexOf(r.controller.render);i>-1&&this.onRender.splice(i,1)}}toggleModule(t,r){let i=this.modules[t];if(!i)return!1;let s=r!==void 0?r:!i.enabled;if(s===i.enabled)return i.enabled;if(!s&&i.manifest.cannotBeDisabled)return!0;if(i.enabled=s,s)i.controller.enable(),i.controller.render&&!this.onRender.includes(i.controller.render)&&this.onRender.push(i.controller.render);else if(i.controller.disable(),i.controller.render){let o=this.onRender.indexOf(i.controller.render);o>-1&&this.onRender.splice(o,1)}return s}disposeModules(){for(let t of Object.values(this.modules))t.controller.dispose();this.modules={}}initializeModules(){this.updateModulesFromConfig()}getModule(t){return this.modules[t]?.controller}anyModuleRequiresHeightmap(){return Object.values(this.modules).some(t=>t.enabled&&t.manifest.requiresHeightmap)}get cameraObject(){return this.cameraGroupVr??this.cameraContainer}_wrapCameraPositionWithWarning(){let t=this.camera.position,r=this,i=20,s=(a,l,c)=>Math.abs(a)>i||Math.abs(l)>i||Math.abs(c)>i,o=()=>{!r._cameraPositionAccessWarned&&typeof F<"u"},v=new Proxy(t,{set(a,l,c){return(l==="x"||l==="y"||l==="z")&&typeof c=="number"&&Math.abs(c)>i&&o(),a[l]=c,!0},get(a,l,c){let u=a[l];return l==="set"?function(f,p,g){return s(f,p,g)&&o(),a.set(f,p,g)}:l==="setX"||l==="setY"||l==="setZ"?function(f){return Math.abs(f)>i&&o(),a[l](f)}:l==="copy"?function(f){return s(f.x,f.y,f.z)&&o(),a.copy(f)}:typeof u=="function"?u.bind(a):u}});Object.defineProperty(this.camera,"position",{value:v,configurable:!0,enumerable:!0})}worldSwitchActions(){this.onWorldSwitched.push(()=>{this.protocolCustomBlocks.clear(),this.sectionsOffsetsAnimations={},this.waypoints.clear(),this.cinimaticScript.stopScript(),this.fireworks.clear()})}downloadWorldGeometry(){Ni(this,new Q.Vector3(this.cameraWorldPos.x,this.cameraWorldPos.y,this.cameraWorldPos.z),this.cameraShake.getBaseRotation(),"world-geometry.json")}updateEntity(t,r=!1){let i={rotation:{head:{x:t.headPitch??t.pitch,y:t.headYaw,z:0}}};r?this.entities.updateEntityPosition(t,!1,i):this.entities.update(t,i)}updatePlayerEntity(t){this.entities.handlePlayerEntity(t)}resetScene(){this.sceneOrigin.update(0,0,0),this.cameraWorldPos.x=0,this.cameraWorldPos.y=0,this.cameraWorldPos.z=0,this.scene.matrixAutoUpdate=!1,this.scene.background=new Q.Color(this.initOptions.config.sceneBackground),this.scene.add(this.ambientLight),this.directionalLight.position.set(1,1,.5).normalize(),this.directionalLight.castShadow=!0,this.scene.add(this.directionalLight);let t=this.renderer.getSize(new Q.Vector2);this.camera=new Q.PerspectiveCamera(75,t.x/t.y,.1,1e3),this._wrapCameraPositionWithWarning(),this.cameraContainer=new Q.Object3D,this.cameraContainer.add(this.camera),this.scene.add(this.cameraContainer)}watchReactivePlayerState(){super.watchReactivePlayerState(),this.onReactivePlayerStateUpdated("inWater",t=>{this.skyboxRenderer.updateWaterState(t,this.playerStateReactive.waterBreathing)}),this.onReactivePlayerStateUpdated("waterBreathing",t=>{this.skyboxRenderer.updateWaterState(this.playerStateReactive.inWater,t)}),this.onReactivePlayerStateUpdated("ambientLight",t=>{t&&(this.ambientLight.intensity=t)}),this.onReactivePlayerStateUpdated("directionalLight",t=>{t&&(this.directionalLight.intensity=t)}),this.onReactivePlayerStateUpdated("lookingAtBlock",t=>{this.cursorBlock.setHighlightCursorBlock(t?new Ue(t.x,t.y,t.z):null,t?.shapes)}),this.onReactivePlayerStateUpdated("diggingBlock",t=>{this.cursorBlock.updateBreakAnimation(t?{x:t.x,y:t.y,z:t.z}:void 0,t?.stage??null,t?.mergedShape)}),this.onReactivePlayerStateUpdated("perspective",t=>{let r=new Ue(this.cameraWorldPos.x,this.cameraWorldPos.y,this.cameraWorldPos.z);this.updateCamera(r,this.cameraShake.getBaseRotation().yaw,this.cameraShake.getBaseRotation().pitch)})}watchReactiveConfig(){super.watchReactiveConfig(),this.onReactiveConfigUpdated("showChunkBorders",r=>{this.updateShowChunksBorder(r)}),this.onReactiveConfigUpdated("defaultSkybox",r=>{this.skyboxRenderer.updateDefaultSkybox(r)}),this.onReactiveConfigUpdated("shaderCubeDebugMode",()=>{this.chunkMeshManager.syncCubeShaderUniforms()}),this.onReactiveConfigUpdated("futuristicReveal",()=>{this.updateModulesFromConfig()});let t=this.displayOptions.inWorldRenderingConfig.handRenderer;this.onReactiveConfigUpdated("handRenderer",r=>{if(r===t)return;t=r;let i=this.holdingBlock.ready,s=this.holdingBlockLeft.ready;this.holdingBlock.dispose(),this.holdingBlockLeft.dispose(),this.holdingBlock=D5(this),this.holdingBlockLeft=D5(this,!0),i&&(this.holdingBlock.ready=!0,this.holdingBlock.updateItem()),s&&(this.holdingBlockLeft.ready=!0,this.holdingBlockLeft.updateItem())}),this.onReactiveConfigUpdated("*",()=>{this.updateModulesFromConfig()}),this.updateModulesFromConfig()}updateModulesFromConfig(){let{moduleStates:t}=this.worldRendererConfig;for(let[r,i]of Object.entries(this.modules)){let s=t[r];if(s==="enabled"){i.enabled||this.toggleModule(r,!0);continue}if(s==="disabled"){i.enabled&&!i.manifest.cannotBeDisabled&&this.toggleModule(r,!1);continue}if(s==="auto"||s===void 0)if(i.controller.autoEnableCheck){let o=i.controller.autoEnableCheck();o&&!i.enabled?this.toggleModule(r,!0):!o&&i.enabled&&!i.manifest.cannotBeDisabled&&this.toggleModule(r,!1)}else{let o=i.manifest.enabledDefault??!1;o&&!i.enabled?this.toggleModule(r,!0):!o&&i.enabled&&!i.manifest.cannotBeDisabled&&this.toggleModule(r,!1)}}}changeHandSwingingState(t,r=!1){let i=r?this.holdingBlockLeft:this.holdingBlock;t?i.startSwing():i.stopSwing()}async updateAssetsData(){let t=this.resourcesManager.currentResources,r=this.material.map,i=this.itemsTexture,s=Pe(t.blocksAtlasImage);s.needsUpdate=!0,s.flipY=!1,this.material.map=s,this.chunkMeshManager.syncCubeShaderUniforms();let o=Pe(t.itemsAtlasImage);o.needsUpdate=!0,o.flipY=!1,this.itemsTexture=o,r&&r.dispose(),i&&i.dispose(),await super.updateAssetsData(),this.onAllTexturesLoaded(),Object.keys(this.loadedChunks).length>0&&this.rerenderAllChunks()}onAllTexturesLoaded(){this.holdingBlock.ready=!0,this.holdingBlock.updateItem(),this.holdingBlockLeft.ready=!0,this.holdingBlockLeft.updateItem()}changeBackgroundColor(t){this.realScene.background=new Q.Color(t[0],t[1],t[2])}changeCardinalLight(t){this.worldRendererConfig.cardinalLight=t}timeUpdated(t){let r=this.getModule("starfield");r?.updateTimeOfDay&&r.updateTimeOfDay(t),this.skyboxRenderer.updateTime(t)}biomeUpdated(t){t?.temperature!==void 0&&this.skyboxRenderer.updateTemperature(t.temperature)}biomeReset(){this.skyboxRenderer.updateTemperature(Oi)}getItemRenderData(t,r){return Y3(t,r,this.resourcesManager,this.playerStateReactive)}async demoModel(){let t=cursorBlockRel(0,1,0).position,r=await A5();ks(r,t);let i=new Q.BoxHelper(r,16776960);r.add(i),this.realScene.add(r)}demoItem(){let t=cursorBlockRel(0,1,0).position,{mesh:r}=this.entities.getItemMesh({itemId:541},{});r.position.set(t.x+.5,t.y+.5,t.z+.5);let i=new Q.BoxHelper(r,16776960);r.add(i),this.realScene.add(r)}addDebugOverlay(){if(this.debugOverlayAdded)return;this.debugOverlayAdded=!0;let t=Pt("debug-overlay",80,0,void 0,{className:y5});setInterval(()=>{if(t.setVisibility(this.displayAdvancedStats),this.displayAdvancedStats){let r=a=>new Intl.NumberFormat("en-US",{}).format(a),i=a=>new Intl.NumberFormat("en-US",{notation:"compact",maximumFractionDigits:1}).format(a),s="";s+=`TE: ${r(this.renderer.info.memory.textures)} `,s+=`F: ${i(this.tilesRendered)} `,s+=`B: ${i(this.blocksRendered)} `,s+=`MEM: ${this.chunkMeshManager.getEstimatedMemoryUsage().total} `;let o=this.chunkMeshManager.getStats();s+=`POOL: ${o.activeCount}/${o.poolSize} `;let v=wr(this.reactiveState.world.instabilityFactors);v&&(s+=`PF: ${v} `),t.updateText(s),this.backendInfoReport=s}},200)}updatePosDataChunk(t){let r=this.sectionObjects[t];if(!r)return;let[i,s,o]=t.split(",").map(c=>Math.floor(+c/16)),a=500-(Math.abs(i-this.cameraSectionPos.x)+Math.abs(s-this.cameraSectionPos.y)+Math.abs(o-this.cameraSectionPos.z)),l=r.mesh??r.shaderMesh??r.children.find(c=>c.name==="mesh"||c.name==="shaderMesh");l&&(l.renderOrder=a)}updateViewerPosition(t){this.viewerChunkPosition=t}cameraSectionPositionUpdate(){for(let t in this.sectionObjects)this.sectionObjects[t]&&this.updatePosDataChunk(t)}getDir(t,r){return t===r?0:t<r?1:-1}finishChunk(t){this.chunkMeshManager.finishChunkDisplay(t)}applyPendingSectionUpdates(){if(this.pendingSectionUpdates.size===0)return;let t=performance.now(),r=this.getSectionHeight(),i=[];for(let s of this.pendingSectionUpdates.keys()){let o=this.pendingSectionBufferStartTimes.get(s)??t;if(t-o<pt.MAX_SECTION_UPDATE_BUFFER_MS){let[a,l,c]=s.split(",").map(Number),u=[`${a-16},${l},${c}`,`${a+16},${l},${c}`,`${a},${l-r},${c}`,`${a},${l+r},${c}`,`${a},${l},${c-16}`,`${a},${l},${c+16}`],f=!1;for(let p of u)if(this.sectionsWaiting.has(p)&&!this.pendingSectionUpdates.has(p)&&this.sectionObjects[p]){f=!0;break}if(f)continue}i.push(s)}if(i.length!==0)for(let s of i){let o=this.pendingSectionUpdates.get(s);this.pendingSectionUpdates.delete(s),this.pendingSectionBufferStartTimes.delete(s);let v=o.key.split(","),a=`${v[0]},${v[2]}`;if(!this.loadedChunks[a]||!this.active){this.chunkMeshManager.releaseSection(o.key);continue}if(!this.chunkMeshManager.sectionHasRenderableContent(o.geometry)){this.chunkMeshManager.releaseSection(o.key);continue}this.chunkMeshManager.updateSection(o.key,o.geometry),this.updatePosDataChunk(o.key)}}clearPendingSectionUpdatesForChunk(t,r){for(let i of[...this.pendingSectionUpdates.keys()])i.startsWith(`${t},`)&&i.endsWith(`,${r}`)&&(this.pendingSectionUpdates.delete(i),this.pendingSectionBufferStartTimes.delete(i))}handleWorkerMessage(t){if(t.type==="geometry"){let r=t.key.split(","),i=`${r[0]},${r[2]}`;if(!this.loadedChunks[i]||!this.active){this.pendingSectionUpdates.delete(t.key),this.pendingSectionBufferStartTimes.delete(t.key);return}if(this.sectionObjects[t.key]){this.pendingSectionUpdates.set(t.key,t),this.pendingSectionBufferStartTimes.has(t.key)||this.pendingSectionBufferStartTimes.set(t.key,performance.now());return}if(!this.chunkMeshManager.sectionHasRenderableContent(t.geometry)){this.chunkMeshManager.releaseSection(t.key);return}this.chunkMeshManager.updateSection(t.key,t.geometry),this.updatePosDataChunk(t.key)}}getSignTexture(t,r,i,s=!1){let o=Bt(t),v=this.chunkTextures.get(`${o[0]},${o[1]}`);v||(v={},this.chunkTextures.set(`${o[0]},${o[1]}`,v));let a=`${t.x},${t.y},${t.z}`;if(v[a])return v[a];let l=jv(this.version),c=f1(r,i,l);if(!c)return;let u=new Q.Texture(c);return u.magFilter=Q.NearestFilter,u.minFilter=Q.NearestFilter,u.needsUpdate=!0,v[a]=u,u}getCameraPosition(t){return(t??this._tmpCameraPos).set(this.cameraWorldPos.x,this.cameraWorldPos.y,this.cameraWorldPos.z)}getSectionCameraPosition(){let t=this.getCameraPosition();return new Ue(Math.floor(t.x/16),Math.floor(t.y/16),Math.floor(t.z/16))}updateCameraSectionPos(){let t=this.getSectionCameraPosition();this.cameraSectionPos.equals(t)||(this.cameraSectionPos=t,this.cameraSectionPositionUpdate())}setFirstPersonCamera(t,r,i){let s=this.playerStateReactive.eyeHeight;this.updateCamera(t?.offset(0,s,0)??null,r,i),this.updateCameraSectionPos()}getThirdPersonCamera(t,r,i){t??(t=new Q.Vector3(this.cameraWorldPos.x,this.cameraWorldPos.y,this.cameraWorldPos.z));let s=this.playerStateReactive.perspective==="third_person_back",o=4,v=this._tpDirection.set(0,0,-1),a=this._tpPitchQuat.setFromAxisAngle(this._tpAxisX,i),l=this._tpYawQuat.setFromAxisAngle(this._tpAxisY,r),c=this._tpFinalQuat.multiplyQuaternions(l,a);v.applyQuaternion(c),s&&v.multiplyScalar(-1),this.DEBUG_RAYCAST&&this.debugRaycast(t,v,o);let u=this._tpScenePos.set(this.sceneOrigin.toSceneX(t.x),this.sceneOrigin.toSceneY(t.y),this.sceneOrigin.toSceneZ(t.z)),f=this._tpRaycaster;f.set(u,v),f.far=o;let p=80,g=p*p,b=t.x,A=t.y,y=t.z,w=[];for(let B of Object.values(this.sectionObjects)){if(B.name!=="chunk"||!B.visible||B.worldX===void 0)continue;let H=B.worldX-b,G=B.worldY-A,O=B.worldZ-y;if(H*H+G*G+O*O>g)continue;let j=B.children.find(J=>J.name==="mesh"||J.name==="shaderMesh");j&&w.push(j)}let S=f.intersectObjects(w,!1),C=o;S.length>0&&(C=Math.max(.5,S[0].distance-.2));let M=this.chunkMeshManager.raycastShaderSectionAABBs(t,v,C,p);return M!==void 0&&(C=Math.max(.5,M-.2)),new Ue(t.x+v.x*C,t.y+v.y*C,t.z+v.z*C)}debugRaycast(t,r,i){this.debugRaycastHelper&&(this.realScene.remove(this.debugRaycastHelper),this.debugRaycastHelper=void 0),this.debugHitPoint&&(this.realScene.remove(this.debugHitPoint),this.debugHitPoint=void 0);let s=new Q.Vector3(this.sceneOrigin.toSceneX(t.x),this.sceneOrigin.toSceneY(t.y),this.sceneOrigin.toSceneZ(t.z));this.debugRaycastHelper=new Q.ArrowHelper(r.clone().normalize(),s,i,16711680,i*.1,i*.05),this.realScene.add(this.debugRaycastHelper);let o=new Q.SphereGeometry(.2,8,8),v=new Q.MeshBasicMaterial({color:65280});this.debugHitPoint=new Q.Mesh(o,v),this.debugHitPoint.position.copy(s).add(r.clone().multiplyScalar(i)),this.realScene.add(this.debugHitPoint)}setCinimaticCamera(t,r,i){this.cameraWorldPos.x=t.x,this.cameraWorldPos.y=t.y,this.cameraWorldPos.z=t.z,this.sceneOrigin.update(t.x,t.y,t.z),this.cameraObject.position.set(0,0,0),this.cameraShake.setBaseRotation(i,r),this.updateCameraSectionPos()}setCinimaticFov(t){this.animatedFov=t,this.camera.fov=t,this.camera.updateProjectionMatrix()}updateSmoothFov(){if(this.cinimaticScript.running)return;let t=this.displayOptions.inWorldRenderingConfig.fov,r=this.playerStateReactive.fovMultiplier,i=t*(Number.isFinite(r)?r:1),s=performance.now();if(this.animatedFov===0&&(this.animatedFov=i),Math.abs(this.animatedFov-i)>=.01){let o=s-this.lastFovAnimTime,v=Math.min(o/pt.FOV_TRANSITION_MS,1),a=l=>1-(1-l)**3;this.animatedFov+=(i-this.animatedFov)*a(v),Math.abs(this.animatedFov-i)<.01&&(this.animatedFov=i)}else this.animatedFov=i;this.lastFovAnimTime=s,this.camera.fov!==this.animatedFov&&(this.camera.fov=this.animatedFov,this.camera.updateProjectionMatrix())}updateCamera(t,r,i){if(!this.cinimaticScript.running){if(t){this.renderer.xr.isPresenting&&(t.y-=this.camera.position.y),this.currentPosTween?.stop();let s=this.displayOptions.inWorldRenderingConfig.instantCameraUpdate?0:this.playerStateUtils.isSpectatingEntity()?150:50;this.currentPosTween=new F0(this.cameraWorldPos).to({x:t.x,y:t.y,z:t.z},s).onUpdate(()=>{this.sceneOrigin.update(this.cameraWorldPos.x,this.cameraWorldPos.y,this.cameraWorldPos.z),this.cameraObject.position.set(0,0,0)}).start()}if(this.playerStateUtils.isSpectatingEntity()){let s=this.cameraShake.getBaseRotation(),o=0,v=Math.PI/2;s.yaw<v&&r>Math.PI+v?o=-Math.PI*2:r<v&&s.yaw>Math.PI+v&&(o=Math.PI*2),this.currentRotTween?.stop(),this.currentRotTween=new F0(s).to({pitch:i,yaw:r+o},100).onUpdate(a=>this.cameraShake.setBaseRotation(a.pitch,a.yaw-o)).start()}else{this.currentRotTween?.stop(),this.cameraShake.setBaseRotation(i,r);let{perspective:s}=this.playerStateReactive;if(s==="third_person_back"||s==="third_person_front"){let o=new Q.Vector3(this.cameraWorldPos.x,this.cameraWorldPos.y,this.cameraWorldPos.z),v=this.getThirdPersonCamera(o,r,i),a=o.distanceTo(new Q.Vector3(v.x,v.y,v.z)),l=s==="third_person_back"?a:-a;this.camera.position.set(0,0,l),s==="third_person_front"?this.camera.rotation.set(0,Math.PI,0):this.camera.rotation.set(0,0,0)}else this.camera.position.z=0,this.camera.rotation.set(0,0,0),this.debugRaycastHelper&&(this.realScene.remove(this.debugRaycastHelper),this.debugRaycastHelper=void 0),this.debugHitPoint&&(this.realScene.remove(this.debugHitPoint),this.debugHitPoint=void 0)}this.updateCameraSectionPos()}}debugChunksVisibilityOverride(){let{chunksRenderAboveOverride:t,chunksRenderBelowOverride:r,chunksRenderDistanceOverride:i,chunksRenderAboveEnabled:s,chunksRenderBelowEnabled:o,chunksRenderDistanceEnabled:v}=this.reactiveDebugParams,a=this.getSectionHeight(),l=this.cameraSectionPos.y*a;if(this.displayOptions.inWorldRenderingConfig.enableDebugOverlay&&t!==void 0||r!==void 0||i!==void 0)for(let[c,u]of Object.entries(this.sectionObjects)){if(u._waitingForChunkDisplay)continue;let[f,p,g]=c.split(",").map(Number),b=s&&t!==void 0?p<=l+t:o&&r!==void 0?p>=l-r:v&&i!==void 0?Math.abs(p-l)<=i:!0;u.visible=b}else this.chunkMeshManager.updateSectionsVisibility()}render(t=!1){if(this.currentRenderedFrames++,this.reactiveDebugParams.stopRendering)return;this.debugChunksVisibilityOverride();let r=performance.now();this.lastRendered=performance.now();let i=this.lastRenderTime>0?Math.min(Math.max((r-this.lastRenderTime)/1e3,0),.1):1/60;this.lastRenderTime=r,this.cursorBlock.render(),this.updateSectionOffsets();let s=this.getCameraPosition();if(this.skyboxRenderer.update(s,this.viewDistance),this.updateSmoothFov(),t){let u=this.renderer.getSize(new Q.Vector2);this.camera.aspect=u.width/u.height,this.camera.updateProjectionMatrix()}let o=0;if(!this.reactiveDebugParams.disableEntities){let u=performance.now();this.entities.render(),o=performance.now()-u}let v=this.cameraGroupVr instanceof Q.Group?this.cameraGroupVr.children.find(u=>u instanceof Q.PerspectiveCamera):this.camera;this.applyPendingSectionUpdates();let a=this.chunkMeshManager.globalBlockBuffer;a&&(a.setCameraOrigin(this.cameraWorldPos.x,this.cameraWorldPos.y,this.cameraWorldPos.z),a.uploadDirtyRange()),this.renderer.render(this.scene,v),this.displayOptions.inWorldRenderingConfig.showHand&&this.playerStateReactive.gameMode!=="spectator"&&this.playerStateReactive.perspective==="first_person"&&!this.renderer.xr.isPresenting&&(this.holdingBlock.render(this.camera,this.renderer,this.ambientLight,this.directionalLight),this.holdingBlockLeft.render(this.camera,this.renderer,this.ambientLight,this.directionalLight));for(let u of this.fountains)this.sectionObjects[u.sectionId]&&!this.sectionObjects[u.sectionId].foutain&&(u.createParticles(this.sectionObjects[u.sectionId]),this.sectionObjects[u.sectionId].foutain=!0),u.render();this.waypoints.render(),this.fireworks.update();for(let u of this.onRender)u(i);let c=performance.now()-r;this.worldRendererConfig.autoLowerRenderDistance&&this.chunkMeshManager.recordRenderTime(c),this.renderTimeAvgCount++,this.renderTimeAvg=(this.renderTimeAvg*(this.renderTimeAvgCount-1)+c)/this.renderTimeAvgCount,this.renderTimeMax=Math.max(this.renderTimeMax,c),this.performanceMonitor.onFrame({totalMs:c,entitiesMs:o,loadedTextureCount:this.renderer.info.memory.textures,fps:this.lastFps})}renderHead(t,r,i,s){let o;if(s.SkullOwner?o=s.SkullOwner.Properties?.textures?.[0]?.Value:o=s.profile?.properties?.find(v=>v.name==="textures")?.value,!!o)try{let a=JSON.parse(z.from(o,"base64").toString()).textures?.SKIN?.url,{skinTexturesProxy:l}=this.worldRendererConfig;l&&(a=a?.replace("http://textures.minecraft.net/",l).replace("https://textures.minecraft.net/",l));let c=Oe(this,a,Fe.head),u=new Q.Group;return i&&c.position.set(0,.3125,.3125),c.position.y-=23/16,u.add(c),this.sceneOrigin.track(u),u.position.set(t.x+.5,t.y+.045,t.z+.5),u.rotation.set(0,-Q.MathUtils.degToRad(r*(i?90:45/2)),0),u.scale.set(.8,.8,.8),u}catch{}}renderSign(t,r,i,s,o){let v=this.getSignTexture(t,o,s);if(!v)return;let a=new Q.Mesh(new Q.PlaneGeometry(1,1),new Q.MeshBasicMaterial({map:v,transparent:!0}));a.renderOrder=999;let l=7/16,c=s?1.3:1;a.scale.set(1*c,l*c,1*c);let u=(s?2:1.5)/16,f=.25/16;i&&!s?a.position.set(0,0,-.5+u+f+1e-4):a.position.set(0,0,u/2+1e-4);let p=new Q.Group;p.rotation.set(0,-Q.MathUtils.degToRad(r*(i?90:45/2)),0),p.add(a);let g=(s?10:8)/16,b=(s?0:i?4.333:9.333)/16,A=g/2+b;return this.sceneOrigin.track(p),p.position.set(t.x+.5,t.y+A,t.z+.5),p}lightUpdate(t,r){for(let i=this.worldSizeParams.minY;i<this.worldSizeParams.worldHeight;i+=16)this.setSectionDirty(new Ue(t,i,r))}rerenderAllChunks(){for(let t of Object.keys(this.sectionObjects)){let[r,i,s]=t.split(",").map(Number);this.setSectionDirty(new Ue(r,i,s))}}updateShowChunksBorder(t){this.chunkMeshManager.updateAllBoxHelpers(t)}resetWorld(){super.resetWorld(),this.pendingSectionUpdates.clear(),this.pendingSectionBufferStartTimes.clear(),this.chunkMeshManager.dispose(),this.chunkMeshManager=new W5(this,this.scene,this.material,this.worldSizeParams.worldHeight,this.viewDistance),this.debugRaycastHelper&&(this.realScene.remove(this.debugRaycastHelper),this.debugRaycastHelper=void 0),this.debugHitPoint&&(this.realScene.remove(this.debugHitPoint),this.debugHitPoint=void 0)}getLoadedChunksRelative(t,r=!1){let[i,s,o]=Gr(t);return Object.fromEntries(Object.entries(this.sectionObjects).map(([v,a])=>{let[l,c,u]=v.split(",").map(Number),[f,p,g]=Gr({x:l,y:c,z:u});return[r?`${f-i},${p-s},${g-o}`:`${f-i},${g-o}`,a]}))}cleanChunkTextures(t,r){let i=this.chunkTextures.get(`${Math.floor(t/16)},${Math.floor(r/16)}`)??{};for(let s of Object.keys(i))i[s].dispose(),delete i[s];this.chunkMeshManager.cleanSignChunkTextures(t,r)}readdChunks(){for(let t of Object.keys(this.sectionObjects))this.scene.remove(this.sectionObjects[t]);setTimeout(()=>{for(let t of Object.keys(this.sectionObjects))this.scene.add(this.sectionObjects[t])},500)}disableUpdates(t=this.scene.children){for(let r of t)r.matrixWorldNeedsUpdate=!1,this.disableUpdates(r.children??[])}removeColumn(t,r){super.removeColumn(t,r),this.cleanChunkTextures(t,r),this.clearPendingSectionUpdatesForChunk(t,r);let i=this.getSectionHeight(),s=this.worldMinYRender;for(let o=s;o<this.worldSizeParams.worldHeight;o+=i){let v=`${t},${o},${r}`;this.chunkMeshManager.sectionObjects[v]&&this.chunkMeshManager.releaseSection(v)}this.chunkMeshManager.onChunkRemovedFromGate(`${t},${r}`)}updateViewerPosition(t){super.updateViewerPosition(t),this.chunkMeshManager.pendingNearReveal.size>0&&this.chunkMeshManager.tryRevealPending()}onViewerChunkPositionChanged(){this.chunkMeshManager.tryRevealPending()}setSectionDirty(...t){let[r]=t;this.cleanChunkTextures(r.x,r.z),super.setSectionDirty(...t)}static getRendererInfo(t){try{let r=t.getContext();return`${r.getParameter(r.getExtension("WEBGL_debug_renderer_info").UNMASKED_RENDERER_WEBGL)}`}catch{}}worldStop(){this.media.onWorldStop()}destroy(){this.performanceMonitor?.reset(),this.pendingSectionUpdates.clear(),this.pendingSectionBufferStartTimes.clear(),this.chunkMeshManager.dispose(),this.disposeModules(),this.fireworksLegacy.destroy(),super.destroy(),this.skyboxRenderer.dispose(),this.fireworks.dispose()}shouldObjectVisible(t){let i=this.getSectionHeight(),s,o,v,a=this.sceneOrigin.getWorldPosition(t);a?(s=a.x,o=a.y,v=a.z):(s=this.sceneOrigin.toWorldX(t.position.x),o=this.sceneOrigin.toWorldY(t.position.y),v=this.sceneOrigin.toWorldZ(t.position.z));let l=Math.floor(s/16)*16,c=Math.floor(v/16)*16,u=Math.floor(o/i)*i,f=`${l},${c}`,p=`${l},${u},${c}`;return!!this.finishedChunks[f]||!!this.sectionObjects[p]}handleUserClick(t){this.media.handleUserClick(t)}updateSectionOffsets(){let t=performance.now();for(let[r,i]of Object.entries(this.sectionsOffsetsAnimations)){let s=(t-i.time)/1e3;i.time=t,i.currentOffsetX+=i.speedX*s,i.currentOffsetY+=i.speedY*s,i.currentOffsetZ+=i.speedZ*s,i.limitX!==void 0&&(i.speedX>0?i.currentOffsetX=Math.min(i.currentOffsetX,i.limitX):i.currentOffsetX=Math.max(i.currentOffsetX,i.limitX)),i.limitY!==void 0&&(i.speedY>0?i.currentOffsetY=Math.min(i.currentOffsetY,i.limitY):i.currentOffsetY=Math.max(i.currentOffsetY,i.limitY)),i.limitZ!==void 0&&(i.speedZ>0?i.currentOffsetZ=Math.min(i.currentOffsetZ,i.limitZ):i.currentOffsetZ=Math.max(i.currentOffsetZ,i.limitZ));let o=this.sectionObjects[r];o&&(o.position.set(i.currentOffsetX,i.currentOffsetY,i.currentOffsetZ),o.updateMatrix())}}reloadWorld(){this.entities.reloadEntities()}};d(pt,"FOV_TRANSITION_MS",200),d(pt,"MAX_SECTION_UPDATE_BUFFER_MS",500);var gt=pt;E();x();k();R();E();x();k();R();var Ge="1.21.4";E();x();k();R();function bt(n,e){n.aspect=e.width/e.height,n.updateProjectionMatrix()}E();x();k();R();function tn(n,e=!1){return n?.mode?n.mode:e?"worldBlocks":ge.mode}E();x();k();R();import*as v0 from"three";E();x();k();R();function rn(...n){let e=n.filter(r=>r.length>0).join("/"),t=typeof globalThis.location<"u"&&globalThis.location.href?globalThis.location.href:typeof import.meta<"u"&&import.meta.url?import.meta.url:`/${e}`;try{return new URL(e,t).href}catch{return`/${e}`}}var nn=new Date,Pa=nn.getMonth()===11&&nn.getDate()>=24&&nn.getDate()<=26,Yv=["panorama_3.webp","panorama_1.webp","panorama_4.webp","panorama_5.webp","panorama_0.webp","panorama_2.webp"],Qv=200,Jt=class{constructor(e){this.documentRenderer=e;d(this,"scene");d(this,"camera");d(this,"startTimes",new Map);d(this,"time",0);d(this,"panoramaGroup",null);this.scene=new v0.Scene,this.scene.background=new v0.Color(3294568);let t=new v0.AmbientLight(13421772);this.scene.add(t);let r=new v0.DirectionalLight(16777215,.5);r.position.set(1,1,.5).normalize(),r.castShadow=!0,this.scene.add(r),this.camera=new v0.PerspectiveCamera(85,e.canvas.width/e.canvas.height,.05,1e3),this.camera.position.set(0,0,0),this.camera.rotation.set(0,0,0)}async init(){this.buildCubemap()}update(e,t){t&&bt(this.camera,this.documentRenderer.canvas)}dispose(){this.scene.clear(),this.panoramaGroup=null,this.startTimes.clear()}buildCubemap(){let e=new v0.BoxGeometry(1e3,1e3,1e3),t=[];for(let s of Yv)(async()=>{let v=rn("background",Pa?"christmas":"",s),a=await nt(v),l=Pe(a);l.matrixAutoUpdate=!1,l.matrix.set(-1,0,1,0,1,0,0,0,1),l.wrapS=v0.ClampToEdgeWrapping,l.wrapT=v0.ClampToEdgeWrapping,l.minFilter=v0.LinearFilter,l.magFilter=v0.LinearFilter;let c=new v0.MeshBasicMaterial({map:l,transparent:!0,side:v0.DoubleSide,depthWrite:!1,opacity:0});this.startTimes.set(c,Date.now()),t.push(c)})().catch(v=>{});let r=new v0.Mesh(e,t);r.onBeforeRender=()=>{this.time+=.01,r.rotation.y=Math.PI+this.time*.01,r.rotation.z=Math.sin(-this.time*.001)*.001;for(let s of t){let o=this.startTimes.get(s);if(o){let v=Date.now()-o;s.opacity=Math.min(1,v/Qv)}}};let i=new v0.Object3D;if(i.add(r),!Pa)for(let s=0;s<20;s++){let o=new Te("1.16.4","squid").mesh;o.position.set(Math.random()*30-15,Math.random()*20-10,Math.random()*10-17),o.rotation.set(0,Math.PI+Math.random(),-Math.PI/4,"ZYX");let v=Math.random()*.01;o.children[0].onBeforeRender=()=>{o.rotation.y+=v,o.rotation.z=Math.cos(r.rotation.y*3)*Math.PI/4-Math.PI/2},i.add(o)}this.scene.add(i),this.panoramaGroup=i}async debugImageInFrontOfCamera(){let e=await nt(rn("background","panorama_0.webp")),t=Pe(e),r=new v0.Mesh(new v0.PlaneGeometry(1e3,1e3),new v0.MeshBasicMaterial({map:t}));r.position.set(0,0,-500),this.scene.add(r)}};E();x();k();R();import*as V from"three";var Ia=.1,on={mixed:["white_wool","cyan_wool","blue_wool","purple_wool","white_stained_glass","cyan_stained_glass","blue_stained_glass","purple_stained_glass","glowstone","sea_lantern","amethyst_block","copper_block","gold_block","diamond_block"],stainedGlass:["white_stained_glass","orange_stained_glass","magenta_stained_glass","light_blue_stained_glass","yellow_stained_glass","lime_stained_glass","pink_stained_glass","gray_stained_glass","light_gray_stained_glass","cyan_stained_glass","purple_stained_glass","blue_stained_glass","brown_stained_glass","green_stained_glass","red_stained_glass","black_stained_glass"],wool:["white_wool","orange_wool","magenta_wool","light_blue_wool","yellow_wool","lime_wool","pink_wool","gray_wool","light_gray_wool","cyan_wool","purple_wool","blue_wool","brown_wool","green_wool","red_wool","black_wool"],construction:["copper_block","exposed_copper","weathered_copper","oxidized_copper","cut_copper","exposed_cut_copper","weathered_cut_copper","oxidized_cut_copper","iron_block","gold_block","diamond_block","emerald_block","netherite_block","lapis_block","redstone_block","coal_block","quartz_block","amethyst_block","bricks","stone_bricks","deepslate_bricks","polished_blackstone"],glow:["glowstone","sea_lantern","shroomlight","ochre_froglight","verdant_froglight","pearlescent_froglight","redstone_lamp","beacon"],world:["grass_block","podzol","mycelium","dirt","coarse_dirt","rooted_dirt","mud","clay","stone","cobblestone","mossy_cobblestone","deepslate","cobbled_deepslate","tuff","calcite","sand","red_sand","gravel","snow_block","coal_ore","deepslate_coal_ore","iron_ore","deepslate_iron_ore","copper_ore","deepslate_copper_ore","gold_ore","deepslate_gold_ore","diamond_ore","deepslate_diamond_ore","emerald_ore","deepslate_emerald_ore","lapis_ore","deepslate_lapis_ore","redstone_ore","deepslate_redstone_ore","nether_gold_ore","ancient_debris","oak_log","birch_log","spruce_log","jungle_log","acacia_log","dark_oak_log","mangrove_log","cherry_log","netherrack","soul_sand","basalt","end_stone"]},Ha={galaxy:{bg:132114,fog:132114,fogD:.011,blocks:[61695,54527,47359,59647,2280703,43263],emit:[13158,8789,6724],nebula:[4403,1114146,4386],galFn:n=>new V.Color(n*.05,n*.2,n),ambient:264216,dir:3368703,pt1:43775,pt2:16729343,name:"GALAXY"},nether:{bg:917760,fog:917760,fogD:.016,blocks:[16720384,16737792,16750848,13373696,16729122,16755200],emit:[2230272,1114112,3346688],nebula:[1704960,851968,1705984],galFn:n=>new V.Color(n,n*.15,0),ambient:1573376,dir:16724736,pt1:16729088,pt2:16755200,name:"NETHER"},end:{bg:0,fog:0,fogD:.009,blocks:[7807658,11158732,5570679,14527231,3342421,12299007],emit:[655381,1572901,327696],nebula:[524312,851989,262158],galFn:n=>new V.Color(n*.4,0,n),ambient:393232,dir:10040319,pt1:11158783,pt2:4456618,name:"THE END"},cyber:{bg:2566,fog:2566,fogD:.01,blocks:[65535,65416,11206400,52479,6749952,65518],emit:[8721,6656,6690],nebula:[6674,5120,4634],galFn:n=>new V.Color(0,n,n*.6),ambient:6669,dir:65450,pt1:65484,pt2:4521728,name:"CYBER"},light:{bg:8951984,fog:7899296,fogD:.006,gradientBg:{top:14214392,mid:10531016,bottom:6846608,radial:!0},blocks:[15266559,13691135,12114175,10537208,8960240,7383272,10012927,12640511,15792383,7909608,14216447,14739711],emit:[6854864,8958176,11061488,12638456],nebula:[9480392,11059424,12637420,14215416,7901360],galFn:n=>{let e=new V.Color;return n<.4?e.lerpColors(new V.Color(16054527),new V.Color(14215423),n/.4):n<.75?e.lerpColors(new V.Color(14215423),new V.Color(11061488),(n-.4)/.35):e.lerpColors(new V.Color(11061488),new V.Color(9482464),(n-.75)/.25),e},ambient:7899296,dir:13688040,pt1:11061503,pt2:13162751,name:"LIGHT",starColor:15266047,starOpacity:.5,galaxyOpacity:.7,nebulaOpacity:.32,edgeLineColor:10010856,blockOpacity:[.42,.56]}},Kv={cruise:{pos:(n,e,t)=>({x:Math.sin(n*.28)*18+Math.cos(n*.11)*7+e*10,y:Math.sin(n*.19)*6+Math.cos(n*.31)*3+t*6,z:0}),look:(n,e,t)=>({x:Math.sin((n+.18)*.28)*18+e*8,y:Math.sin((n+.18)*.19)*6+t*4,z:-25}),roll:(n,e=0)=>e*.05+Math.sin(n*.22)*.015,spd:.18},barrel:{pos:(n,e,t)=>{let i=n*2.4;return{x:Math.cos(i)*10+e*4,y:Math.sin(i)*10+t*4,z:Math.sin(n*.4)*8}},look:n=>({x:Math.sin(n*.5)*5,y:Math.cos(n*.5)*5,z:-30}),roll:n=>n*2.4+Math.PI*.5,spd:.24},dive:{pos:(n,e,t)=>({x:Math.sin(n*.6)*30+e*8,y:Math.cos(n*.4)*18+t*6,z:Math.sin(n*.3)*12}),look:(n,e,t)=>({x:Math.sin(n*.6+.2)*30+e*6,y:Math.cos(n*.4+.2)*18-8+t*4,z:-35}),roll:(n,e=0)=>e*.08+Math.sin(n*.6)*.12,spd:.3},orbit:{pos:(n,e,t)=>({x:Math.cos(n*.5)*20+e*5,y:Math.sin(n*.25)*10+t*5,z:Math.sin(n*.5)*20}),look:()=>({x:0,y:0,z:-60}),roll:n=>Math.sin(n*.5)*.08,spd:.15},snake:{pos:(n,e,t)=>({x:Math.sin(n*1.1)*22+Math.sin(n*.37)*8+e*10,y:Math.sin(n*.7)*10+e*4+t*8,z:0}),look:(n,e,t)=>{let r=n+.12;return{x:Math.sin(r*1.1)*22+Math.sin(r*.37)*8+e*8,y:Math.sin(r*.7)*10+t*6,z:-22}},roll:(n,e=0)=>e*.1+Math.sin(n*1.1)*.06,spd:.22}},Jv={cruise:1,barrel:1.6,dive:2.2,orbit:.7,snake:1.4},qv=250,lr=1e4,cr=3e3,qt=n=>n[Math.floor(Math.random()*n.length)],sn=n=>"#"+n.toString(16).padStart(6,"0"),Oa=n=>{if(typeof document>"u")return null;let e=document.createElement("canvas");e.width=4,e.height=512;let t=e.getContext("2d");if(!t)return null;let r=e.width,i=e.height,s=n.radial?t.createRadialGradient(r/2,i*.32,0,r/2,i*.32,i*.85):t.createLinearGradient(0,0,0,i);s.addColorStop(0,sn(n.top)),n.mid!=null&&s.addColorStop(.45,sn(n.mid)),s.addColorStop(1,sn(n.bottom)),t.fillStyle=s,t.fillRect(0,0,r,i);let o=new V.CanvasTexture(e);return o.needsUpdate=!0,o},yt=class{constructor(e,t={},r){this.documentRenderer=e;this.abortSignal=r;d(this,"scene");d(this,"camera");d(this,"ambient");d(this,"dir");d(this,"pt1");d(this,"pt2");d(this,"blocks",[]);d(this,"bGroup",new V.Group);d(this,"galaxy");d(this,"nebula");d(this,"stars");d(this,"galGeo");d(this,"nebGeo");d(this,"bGeo",new V.BoxGeometry(1,1,1));d(this,"eGeo",new V.EdgesGeometry(this.bGeo));d(this,"curScene");d(this,"curCam");d(this,"blockGroup");d(this,"cameraSpeed");d(this,"blockSpeed");d(this,"camT",0);d(this,"mx",0);d(this,"my",0);d(this,"tmx",0);d(this,"tmy",0);d(this,"transitioning",!1);d(this,"useMinecraftTextures",!1);d(this,"resourcesManager");d(this,"atlasTexture",null);d(this,"blockMaterialPool",new Map);d(this,"gradientSky",null);d(this,"gradientSkyTexture",null);d(this,"disposed",!1);d(this,"animTime",0);let i=ge;this.curScene=t.initialScene??i.futuristicScene,this.curCam=t.initialCamera??i.futuristicCamera,this.blockGroup=t.initialBlockGroup??i.futuristicBlockGroup,this.cameraSpeed=t.initialCameraSpeed??m5.camera,this.blockSpeed=t.initialBlockSpeed??m5.block,this.useMinecraftTextures=t.useMinecraftTextures??i.minecraftTextures,this.resourcesManager=t.resourcesManager;let s=Ha[this.curScene];this.scene=new V.Scene,this.scene.fog=new V.FogExp2(s.fog,s.fogD),this.applyScenePalette(s),this.camera=new V.PerspectiveCamera(80,this.documentRenderer.canvas.width/this.documentRenderer.canvas.height,.1,700),this.ambient=new V.AmbientLight(s.ambient,2.5),this.scene.add(this.ambient),this.dir=new V.DirectionalLight(s.dir,4),this.dir.position.set(1,1,0),this.scene.add(this.dir),this.pt1=new V.PointLight(s.pt1,5,100),this.scene.add(this.pt1),this.pt2=new V.PointLight(s.pt2,4,80),this.pt2.position.set(30,20,-30),this.scene.add(this.pt2);for(let f=0;f<qv;f++)this.spawnBlock(s,!0);if(!this.useMinecraftTextures){let f=s.edgeLineColor??62975;for(let p=0;p<40;p++){let g=new V.LineBasicMaterial({color:f,transparent:!0,opacity:.25});qt(this.blocks).mesh.add(new V.LineSegments(this.eGeo,g))}}this.scene.add(this.bGroup);let o=new V.BufferGeometry,v=new Float32Array(5e3*3);for(let f=0;f<5e3*3;f++)v[f]=(Math.random()-.5)*500;o.setAttribute("position",new V.BufferAttribute(v,3)),this.stars=new V.Points(o,new V.PointsMaterial({color:s.starColor??16777215,size:.3,transparent:!0,opacity:s.starOpacity??.7,sizeAttenuation:!0})),this.scene.add(this.stars),this.galGeo=new V.BufferGeometry;let a=new Float32Array(lr*3),l=new Float32Array(lr*3);for(let f=0;f<lr;f++){let p=f%3,g=Math.random(),b=p/3*Math.PI*2+g*Math.PI*5,A=g*90+Math.random()*10,y=(1-g)*18;a[f*3]=Math.cos(b)*A+(Math.random()-.5)*y,a[f*3+1]=(Math.random()-.5)*7,a[f*3+2]=Math.sin(b)*A+(Math.random()-.5)*y-180;let w=.2+g*.8,S=s.galFn(w);l[f*3]=S.r,l[f*3+1]=S.g,l[f*3+2]=S.b}this.galGeo.setAttribute("position",new V.BufferAttribute(a,3)),this.galGeo.setAttribute("color",new V.BufferAttribute(l,3)),this.galaxy=new V.Points(this.galGeo,new V.PointsMaterial({size:.9,vertexColors:!0,transparent:!0,opacity:s.galaxyOpacity??.55,sizeAttenuation:!0})),this.scene.add(this.galaxy),this.nebGeo=new V.BufferGeometry;let c=new Float32Array(cr*3),u=new Float32Array(cr*3);for(let f=0;f<cr;f++){let p=25+Math.random()*110,g=Math.random()*Math.PI*2,b=(Math.random()-.5)*Math.PI*.5;c[f*3]=p*Math.cos(g)*Math.cos(b),c[f*3+1]=p*Math.sin(b)*.6,c[f*3+2]=p*Math.sin(g)*Math.cos(b)-80;let A=new V.Color(qt(s.nebula));u[f*3]=A.r,u[f*3+1]=A.g,u[f*3+2]=A.b}this.nebGeo.setAttribute("position",new V.BufferAttribute(c,3)),this.nebGeo.setAttribute("color",new V.BufferAttribute(u,3)),this.nebula=new V.Points(this.nebGeo,new V.PointsMaterial({size:3,vertexColors:!0,transparent:!0,opacity:s.nebulaOpacity??.3,sizeAttenuation:!0})),this.scene.add(this.nebula),this.addBackgroundTextPlane(),this.setupMouseTracking()}async init(){if(this.useMinecraftTextures)try{await this.loadMinecraftTextures()}catch{this.useMinecraftTextures=!1}}applyScenePalette(e){if(this.documentRenderer.renderer.setClearColor(e.bg),e.gradientBg)if(this.scene.background=null,this.gradientSky){if(this.gradientSky.visible=!0,this.gradientSkyTexture&&e.gradientBg){let s=Oa(e.gradientBg);s&&(this.gradientSkyTexture.dispose(),this.gradientSkyTexture=s,this.gradientSky.material.map=s,this.gradientSky.material.needsUpdate=!0)}}else{let s=Oa(e.gradientBg);s?(this.gradientSkyTexture=s,this.gradientSky=new V.Mesh(new V.PlaneGeometry(900,700),new V.MeshBasicMaterial({map:s,depthWrite:!1,side:V.DoubleSide})),this.gradientSky.position.set(0,0,-280),this.gradientSky.renderOrder=-1e3,this.scene.add(this.gradientSky)):this.scene.background=new V.Color(e.bg)}else this.scene.background=new V.Color(e.bg),this.gradientSky&&(this.gradientSky.visible=!1);this.scene.fog instanceof V.FogExp2&&(this.scene.fog.color.set(e.fog),this.scene.fog.density=e.fogD);let t=this.stars?.material;t&&(t.color.set(e.starColor??16777215),t.opacity=e.starOpacity??.7);let r=this.galaxy?.material;r&&(r.opacity=e.galaxyOpacity??.55);let i=this.nebula?.material;i&&(i.opacity=e.nebulaOpacity??.3)}setupMouseTracking(){let e=r=>{let i=typeof window<"u"?window.innerWidth:this.documentRenderer.canvas.width,s=typeof window<"u"?window.innerHeight:this.documentRenderer.canvas.height;this.tmx=(r.clientX/i-.5)*2,this.tmy=-(r.clientY/s-.5)*2};(typeof document<"u"?document:void 0)?.addEventListener("mousemove",e,{signal:this.abortSignal})}addBackgroundTextPlane(){let r=typeof document<"u"?document.createElement("canvas"):null;if(!r)return;r.width=2048,r.height=768;let i=r.getContext("2d");if(!i)return;i.clearRect(0,0,2048,768),i.save(),i.font="bold 560px Orbitron, sans-serif",i.textAlign="center",i.textBaseline="middle",i.shadowColor="rgba(0,200,255,0.35)",i.shadowBlur=80,i.fillStyle="rgba(255,255,255,0.055)",i.fillText("V2",2048*.28,768*.5),i.restore(),i.save(),i.font="bold 148px Orbitron, sans-serif",i.textAlign="center",i.textBaseline="middle",i.shadowColor="rgba(0,200,255,0.2)",i.shadowBlur=40,i.fillStyle="rgba(255,255,255,0.038)",i.fillText("by ZARDOY",2048*.72,768*.52),i.restore();let s=new V.CanvasTexture(r),o=new V.Mesh(new V.PlaneGeometry(280,105),new V.MeshBasicMaterial({map:s,transparent:!0,opacity:1,depthWrite:!1,side:V.DoubleSide,blending:V.AdditiveBlending}));o.position.set(8,4,-320),this.scene.add(o)}spawnBlock(e,t,r){let i=this.createBlockMaterial(e,r),s=new V.Mesh(this.bGeo,i),o=.3+Math.random()*3;s.scale.setScalar(o),s.position.set((Math.random()-.5)*140,(Math.random()-.5)*70,t?-(Math.random()*140):-155-Math.random()*30),s.rotation.set(Math.random()*Math.PI*2,Math.random()*Math.PI*2,Math.random()*Math.PI*2);let v={mesh:s,spd:.04+Math.random()*.12,dx:(Math.random()-.5)*.012,dy:(Math.random()-.5)*.008,rx:(Math.random()-.5)*.012,ry:(Math.random()-.5)*.012,rz:(Math.random()-.5)*.01,minecraftBlockName:r};this.blocks.push(v),this.bGroup.add(s)}createBlockMaterial(e,t){if(this.useMinecraftTextures&&t){let s=this.blockMaterialPool.get(t);if(s)return s.clone()}let[r,i]=e.blockOpacity??[.32,.46];return new V.MeshBasicMaterial({color:qt(e.blocks),transparent:!0,opacity:r+Math.random()*(i-r),depthWrite:!1,blending:V.AdditiveBlending})}removeBlockEdgeLines(){for(let e of this.blocks){let t=e.mesh.children.filter(r=>r instanceof V.LineSegments);for(let r of t){e.mesh.remove(r),r.geometry?.dispose();let i=r.material;Array.isArray(i)?i.forEach(s=>s.dispose()):i.dispose()}}}async ensureMcDataLoaded(){let e=globalThis._LOAD_MC_DATA;e&&await e()}resolveBlockAtlasUv(e,t,r){let i=s=>{let o=t[s];return o?{u:o.u,v:o.v,su:o.su??r.suSv,sv:o.sv??r.suSv}:null};if(t[e])return i(e);for(let s of["_top","_side","_front","_0"]){let o=i(`${e}${s}`);if(o)return o}for(let s of Object.keys(t))if(s.startsWith(e))return i(s);return null}async loadMinecraftTextures(){await this.ensureMcDataLoaded();let e=this.resourcesManager??new fe;if(!e.currentResources?.blocksAtlasImage){if(typeof document>"u")throw new Error("Menu atlas missing in worker; pass resourcesManager from main thread");e.currentConfig={...e.currentConfig,version:Ge,noInventoryGui:!0},await e.updateAssetsData?.({})}let r=e.currentResources;if(!r?.blocksAtlasImage||!r.blocksAtlasJson)throw new Error("Block atlas not available");let i=r.blocksAtlasJson,s=i.textures;this.atlasTexture=Pe(r.blocksAtlasImage),this.atlasTexture.flipY=!1,this.atlasTexture.needsUpdate=!0;for(let o of on[this.blockGroup]){let v=this.resolveBlockAtlasUv(o,s,i);if(!v)continue;let a=this.atlasTexture.clone();a.flipY=!1,a.offset.set(v.u,v.v),a.repeat.set(v.su,v.sv),a.needsUpdate=!0;let l=o.includes("glass"),c=new V.MeshBasicMaterial({map:a,side:V.DoubleSide,transparent:l,opacity:l?.85:1,alphaTest:l?.08:0,depthWrite:!0,toneMapped:!1});this.blockMaterialPool.set(o,c)}if(this.blockMaterialPool.size===0)throw new Error("No block textures resolved from atlas (check block names vs atlas keys)");this.removeBlockEdgeLines();for(let o of this.blocks){let v=qt([...this.blockMaterialPool.keys()]);o.minecraftBlockName=v,o.mesh.material=this.blockMaterialPool.get(v).clone()}}setScene(e){if(!et.includes(e)||e===this.curScene||this.transitioning)return;this.transitioning=!0,this.curScene=e;let t=Ha[e];setTimeout(()=>{if(this.disposed)return;this.applyScenePalette(t),this.ambient.color.set(t.ambient),this.dir.color.set(t.dir),this.pt1.color.set(t.pt1),this.pt2.color.set(t.pt2);for(let s of this.blocks)this.useMinecraftTextures&&s.minecraftBlockName||s.mesh.material instanceof V.MeshBasicMaterial&&s.mesh.material.color.set(qt(t.blocks));let r=this.nebGeo.attributes.color;for(let s=0;s<cr;s++){let o=new V.Color(qt(t.nebula));r.setXYZ(s,o.r,o.g,o.b)}r.needsUpdate=!0;let i=this.galGeo.attributes.color;for(let s=0;s<lr;s++){let o=.2+Math.random()*.8,v=t.galFn(o);i.setXYZ(s,v.r,v.g,v.b)}i.needsUpdate=!0,this.transitioning=!1},150)}setCamera(e){tt.includes(e)&&(this.curCam=e)}setCameraSpeed(e){this.cameraSpeed=Math.max(0,e)}setBlockSpeed(e){this.blockSpeed=Math.max(0,e)}async setBlockGroup(e){if(rt.includes(e)&&e!==this.blockGroup&&(this.blockGroup=e,!(!this.useMinecraftTextures||this.disposed))){for(let t of this.blockMaterialPool.values())t.map?.dispose(),t.dispose();this.blockMaterialPool.clear();try{await this.loadMinecraftTextures()}catch{}}}getSceneId(){return this.curScene}getCameraId(){return this.curCam}getBlockGroupId(){return this.blockGroup}update(e,t){t&&bt(this.camera,this.documentRenderer.canvas);let r=Kv[this.curCam],i=this.cameraSpeed,s=this.blockSpeed;this.camT+=e*r.spd*i,this.mx+=(this.tmx-this.mx)*.05,this.my+=(this.tmy-this.my)*.05;let o=this.mx*Ia,v=this.my*Ia,a=r.pos(this.camT,o,v),l=r.look(this.camT,o,v);this.camera.position.set(a.x,a.y,a.z),this.camera.lookAt(l.x,l.y,l.z),this.camera.rotation.z=r.roll(this.camT,o);let c=Jv[this.curCam]*s;this.animTime+=e*1e3*s;for(let u of this.blocks){if(u.mesh.position.z+=u.spd*c*60*e,u.mesh.position.x+=u.dx*60*e*s,u.mesh.position.y+=u.dy*60*e*s,u.mesh.rotation.x+=u.rx*c,u.mesh.rotation.y+=u.ry*c,u.mesh.rotation.z+=u.rz,!this.useMinecraftTextures&&u.mesh.material instanceof V.MeshBasicMaterial){let f=u.mesh.userData.baseOpacity??.38;u.mesh.userData.baseOpacity==null&&(u.mesh.userData.baseOpacity=f);let p=.88+Math.abs(Math.sin(this.animTime*8e-4+u.mesh.position.x*.3))*.12;u.mesh.material.opacity=f*p}u.mesh.position.z>this.camera.position.z+15&&u.mesh.position.set((Math.random()-.5)*140,(Math.random()-.5)*70,this.camera.position.z-155-Math.random()*30)}this.pt1.position.set(Math.sin(this.camT*.8)*25+this.camera.position.x,Math.cos(this.camT*.6)*12+this.camera.position.y,this.camera.position.z-18),this.pt2.position.set(Math.cos(this.camT*.5)*20+this.camera.position.x,Math.sin(this.camT*.9)*15+this.camera.position.y,this.camera.position.z-30),this.galaxy.rotation.y+=e*.006*s,this.nebula.rotation.y-=e*.003*s,this.stars.rotation.y+=e*4e-4*s}dispose(){this.disposed=!0,this.scene.clear(),this.bGeo.dispose(),this.eGeo.dispose(),this.galGeo.dispose(),this.nebGeo.dispose(),this.gradientSkyTexture?.dispose(),this.atlasTexture?.dispose();for(let e of this.blockMaterialPool.values())e.map?.dispose(),e.dispose();this.blockMaterialPool.clear()}};E();x();k();R();import*as Xt from"three";import{Vec3 as Da}from"vec3";E();x();k();R();import Zv from"prismarine-world";import Xv from"prismarine-chunk";var Fa=n=>{let e=Zv(n),t=Xv(n),r=new e(n).sync,i=$v(r);for(let s of i)if(s.startsWith("set")&&s!=="setColumn"){let o=r[s].bind(r);r[s]=(...v)=>{let a=v[0];a.x!==void 0&&!r.getColumnAt(a)&&r.setColumn(Math.floor(a.x/16),Math.floor(a.z/16),new t(void 0)),o(...v)}}return r};function $v(n){let e=new Set,t=n;do for(let r of Object.getOwnPropertyNames(t))typeof n[r]=="function"&&r!=="constructor"&&e.add(r);while(t=Object.getPrototypeOf(t));return[...e]}var Zt=class{constructor(e,t,r){this.documentRenderer=e;this.options=t;this.abortSignal=r;d(this,"_scene");d(this,"_camera");d(this,"worldRenderer");d(this,"WorldRendererClass",gt);this._scene=new Xt.Scene,this._scene.background=new Xt.Color(3294568),this._camera=new Xt.PerspectiveCamera(85,e.canvas.width/e.canvas.height,.05,1e3),this.camera.position.set(0,0,0),this.camera.rotation.set(0,0,0)}get scene(){return this._scene}get camera(){return this._camera}async init(){let e=Ge,t=new fe;if(t.currentConfig={version:e,noInventoryGui:!0},await t.updateAssetsData?.({}),this.abortSignal.aborted)return;let r=Fa(e),s=Ka("prismarine-block")(e),v=globalThis.mcData.blocksArray.filter(p=>{if(!p.name.includes("stained_glass"))return!1;let g=s.fromStateId(p.defaultState,0);if(g.shapes?.length!==1)return!1;let b=g.shapes[0];return b[0]===0&&b[1]===0&&b[2]===0&&b[3]===1&&b[4]===1&&b[5]===1}),a=-15,l=100,c=100;for(let p=-l;p<l;p++)for(let g=-c;g<c;g++){let b=v[Math.floor(Math.random()*v.length)];r.setBlockStateId(new Da(p,g,a),b.defaultState)}this._camera.updateProjectionMatrix(),this._camera.position.set(.5,c/2+.5,.5),this._camera.rotation.set(0,0,0);let u=new Da(...this._camera.position.toArray()),f=new Xe(r,2,u);this.abortSignal.aborted||(this.worldRenderer=new this.WorldRendererClass(this.documentRenderer.renderer,this.options,{version:e,worldView:f,inWorldRenderingConfig:a5,playerStateReactive:H2().reactive,rendererState:Ke().reactive,nonReactiveState:Ke().nonReactive,resourcesManager:t}),this.worldRenderer instanceof gt&&(this._scene=this.worldRenderer.realScene,this._camera=this.worldRenderer.camera),f.init(u),await this.worldRenderer.waitForChunksToRender(),!this.abortSignal.aborted&&this.setupMouseParallax())}update(e,t){t&&bt(this.camera,this.documentRenderer.canvas)}dispose(){this.worldRenderer?.destroy(),this.worldRenderer=void 0,this._scene.clear()}setupMouseParallax(){let e=this._camera,t=e.position.x,r=e.position.y,i;document.body.addEventListener("pointermove",s=>{if(s.pointerType!=="mouse")return;let o=.2,v=s.clientX/window.innerWidth-.5,a=-(s.clientY/window.innerHeight-.5);i?.stop(),i=new F0(e.position).to({x:t+v*o,y:r+a*o},0),i.start(),e.updateProjectionMatrix()},{signal:this.abortSignal})}};E();x();k();R();import*as za from"three";var $t=class{constructor(e,t,r={},i=!1){this.documentRenderer=e;this.options=t;d(this,"active");d(this,"abortController",new AbortController);d(this,"mode");d(this,"lastFrameTime",0);this.mode=tn(r,i)}get futuristic(){return this.active instanceof yt?this.active:void 0}get scene(){return this.active?.scene}get camera(){return this.active?.camera}async start(e={}){this.active=this.createImplementation(e),await this.active.init(),this.active.scene.background instanceof za.Color&&this.documentRenderer.renderer.setClearColor(this.active.scene.background),this.lastFrameTime=performance.now(),this.documentRenderer.render=(t=!1)=>{let r=performance.now(),i=Math.min((r-this.lastFrameTime)/1e3,.05);this.lastFrameTime=r;let s=this.active;s&&(s.update(i,t),this.documentRenderer.renderer.render(s.scene,s.camera))}}createImplementation(e){switch(this.mode){case"futuristic":return new yt(this.documentRenderer,{useMinecraftTextures:e.useMinecraftTextures,initialScene:e.futuristicScene,initialCamera:e.futuristicCamera,initialBlockGroup:e.futuristicBlockGroup,initialCameraSpeed:e.futuristicCameraSpeed,initialBlockSpeed:e.futuristicBlockSpeed,resourcesManager:e.resourcesManager},this.abortController.signal);case"worldBlocks":return new Zt(this.documentRenderer,this.options,this.abortController.signal);default:return new Jt(this.documentRenderer)}}dispose(){this.active?.dispose(),this.active=void 0,this.abortController.abort()}};V5.ColorManagement.enabled=!1;globalThis.THREE=V5;var La=n=>({updateMap:n.entities.updateMap.bind(n.entities),updateCustomBlock:n.updateCustomBlock.bind(n),getBlockInfo:n.getBlockInfo.bind(n),playEntityAnimation:n.entities.playAnimation.bind(n.entities),damageEntity:n.entities.handleDamageEvent.bind(n.entities),updatePlayerSkin:n.entities.updatePlayerSkin.bind(n.entities),changeHandSwingingState:n.changeHandSwingingState.bind(n),getHighestBlocks:n.getHighestBlocks.bind(n),reloadWorld:n.reloadWorld.bind(n),updateEntityModel:n.entities.updateEntityModel.bind(n.entities),playEntityModelAnimation:n.entities.playEntityModelAnimation.bind(n.entities),addMedia:n.media.addMedia.bind(n.media),destroyMedia:n.media.destroyMedia.bind(n.media),setControlMode:n.media.setControlMode.bind(n.media),setVideoPlaying:n.media.setVideoPlaying.bind(n.media),setVideoSeeking:n.media.setVideoSeeking.bind(n.media),setVideoVolume:n.media.setVideoVolume.bind(n.media),setVideoSpeed:n.media.setVideoSpeed.bind(n.media),handleUserClick:n.media.handleUserClick.bind(n.media),addSectionAnimation(e,t){n.sectionsOffsetsAnimations[e]=t},removeSectionAnimation(e){delete n.sectionsOffsetsAnimations[e]},shakeFromDamage:n.cameraShake.shakeFromDamage.bind(n.cameraShake),onPageInteraction:n.media.onPageInteraction.bind(n.media),downloadMesherLog:n.downloadMesherLog.bind(n),explodeFirework:n.fireworksLegacy.explode.bind(n.fireworksLegacy),explodeFireworkFacingCamera:n.fireworksLegacy.explodeFacingCamera.bind(n.fireworksLegacy),addWaypoint:n.waypoints.addWaypoint.bind(n.waypoints),removeWaypoint:n.waypoints.removeWaypoint.bind(n.waypoints),startCinimaticScript:n.cinimaticScript.startScript.bind(n.cinimaticScript),stopCinimaticScript:n.cinimaticScript.stopScript.bind(n.cinimaticScript),launchFirework:n.fireworks.launchFirework.bind(n.fireworks),setSkyboxImage:n.skyboxRenderer.setSkyboxImage.bind(n.skyboxRenderer),setRain:e=>n.toggleModule("rain",e),spawnBlockBreakParticles(e,t,r,i,s,o){n.getModule("blockBreakParticles")?.spawnBlockBreakParticles(e,t,r,i,s,o)},spawnBlockCrackParticle(e,t,r,i,s,o,v){n.getModule("blockBreakParticles")?.spawnCrackParticle(e,t,r,i,s,o,v)},async loadGeometryExport(e){let{applyWorldGeometryExport:t}=await Promise.resolve().then(()=>(Wi(),ca));return t(n,e)},feedChunkPacket(e){let{kind:t,...r}=e,i={type:t,...r};for(let s of n.workers)s.postMessage(i)},getChunksDebugState(){let e={};for(let t of Object.keys(n.sectionObjects)){let[r,,i]=t.split(",").map(Number);e[`${r},${i}`]=!0}return{loadedSectionsChunks:e,loadedChunks:{...n.loadedChunks},finishedChunks:{...n.finishedChunks}}}}),t9=[],dr=(n,...e)=>{for(let t of Object.values(globalThis.loadedMods??{}))try{t.threeJsBackendModule?.[n]?.(...e)}catch(r){let i=`[mod three.js] Error calling ${n} on ${t.name}: ${r}`;throw new Error(i)}},Ua=()=>{let n,e=null,t=null,r=null,i=null,s=(c,u)=>{a0?n=d1(c,t9,globalThis):n=c,e=new d5(n,u?.canvas),globalThis.renderer=e.renderer,globalThis.documentRenderer=e,globalThis.threeJsBackend=l,dr("default",l)},o=async c=>{if(!e)throw new Error("Document renderer not initialized");r&&(r.destroy(),r=null,i=null,globalThis.world=void 0,globalThis.frameTimingCollector=void 0),t&&(t.dispose(),t=null);let u={...n.config.menuBackground,...c};t=new $t(e,{...n},u,!!F.env.SINGLE_FILE_BUILD_MODE),dr("menuBackgroundCreated",t),await t.start(u),dr("menuBackgroundReady",t)},v=async c=>{let f=a0?d1(c,[fe,Ze],globalThis):c;if(!e)throw new Error("Document renderer not initialized");e.nonReactiveState=f.nonReactiveState,globalThis.resourcesManager=f.resourcesManager,t&&(t.dispose(),t=null),r=new gt(e.renderer,n,f),await r.worldReadyPromise,i=new u1(f.nonReactiveState),globalThis.frameTimingCollector=i;let p=e.render;e.render=function(g){p.call(this,g),i?.markFrameStart(),f.inWorldRenderingConfig.paused||r?.render(g),i?.markFrameEnd(),i?.markFrameDisplay()},e.inWorldRenderingConfig=f.inWorldRenderingConfig,globalThis.world=r,dr("worldReady",r)},a=()=>{t&&(t.dispose(),t=null),e&&e.dispose(),r&&(r.destroy(),r=null)},l={id:"threejs",displayName:`three.js ${V5.REVISION}`,startMenuBackground:o,startWorld:v,disconnect:a,setRendering(c){e.setPaused(!c),r&&(r.renderingActive=c)},getMenuBackground:()=>t??void 0,getDebugOverlay:()=>({get entitiesString(){return r?.entities.getDebugString()},get left(){return{"Geo Memory":r?.chunkMeshManager.getEstimatedMemoryUsage().total??"-"}}}),updateCamera(c,u,f){i?.markCameraUpdate(!c),r?.setFirstPersonCamera(c,u,f)},get soundSystem(){return r?.soundSystem},get backendMethods(){if(r)return La(r)}};return{main:{init:s,backend:l},workerProxy(){return cs({init(c,u){s(c,{canvas:u})},updateSizeExternal(c,u,f){e?.updateSizeExternal(c,u,f)},startMenuBackground:o,startWorld:v,disconnect:a,setRendering:l.setRendering,updateCamera(c,u,f){let p=c?new e9(c.x,c.y,c.z):null;i?.markCameraUpdate(!p),l.updateCamera(p,u,f)},async callBackendMethod(c,...u){if(!r)throw new Error("World renderer not initialized");let p=La(r)[c];if(!p)throw new Error(`Backend method ${String(c)} is unavailable`);return p(...u)}})}}};var ur=n=>{let{main:e}=Ua();return e.init(n),e.backend};ur.id="threejs";ur.displayName="three.js Blocking";ur.description="Simple, old and stable main thread graphics backend providing balanced performance on top of WebGL2.";E();x();k();R();import*as Ga from"three";function r9(n){let e="threeWorker.js",t;if(F.env.SINGLE_FILE_BUILD){let r=document.getElementById("three-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}var fr=async n=>{let e=r9(()=>{}),t=ds(e),r=Cr();r.onSizeChanged((v,a)=>{t.updateSizeExternal(v,a,window.devicePixelRatio||1)});let i=b5(n,e);try{t.init(i,r.canvas)}catch(v){throw Ct(i),v}let s=new Proxy({},{get(v,a){if(typeof a=="string")return async(...l)=>t.callBackendMethod(a,...l)}});return{id:"threejs",displayName:`three.js ${Ga.REVISION}`,async startMenuBackground(v){let a=v?.resourcesManager?.currentResources?.mcData;if(a){let c={...st,items:"itemsArray",entities:"entitiesArray"};await Yr([e],Ge,c,a)}let l=b5(v??{},e);try{await t.startMenuBackground(structuredClone(l))}catch(c){throw Ct(l),c}},async startWorld(v){let a={...st,items:"itemsArray",entities:"entitiesArray"};await Yr([e],v.version,a,v.resourcesManager.currentResources.mcData),v.inWorldRenderingConfig.__syncToWorker=!0,v.playerStateReactive&&(v.playerStateReactive.__syncToWorker=!0),v.rendererState&&(v.rendererState.__syncFromWorker=!0),v.nonReactiveState&&(v.nonReactiveState.__syncFromWorker=!0),v.nonReactiveState.__syncFromWorkerInterval=200;let l=b5(v,e);try{await t.startWorld(structuredClone(l))}catch(u){throw Ct(l),u}t.updateSizeExternal(r.size.width,r.size.height,window.devicePixelRatio||1);let c=Pt("fps");setInterval(()=>{let{fps:u,avgRenderTime:f,worstRenderTime:p}=v.nonReactiveState;c.updateText(`FPS: ${u.toFixed(0)} (${f.toFixed(0)}ms/${p.toFixed(0)}ms)`),v.nonReactiveState.fps=0},1e3)},disconnect(){r.destroy(),t.disconnect(),e.terminate()},setRendering(v){t.setRendering(v)},updateCamera(v,a,l){t.updateCamera(v?{x:v.x,y:v.y,z:v.z}:null,a,l)},soundSystem:void 0,backendMethods:s}};fr.id="threejs-off-thread";fr.displayName="three.js Multi-thread";fr.description=["Edge-cutting technology that uses a dedicated thread for graphics.","Slightly higher power and RAM usage.","More stable FPS (mid-range devices), but possible inputlag if TPS is low.","On low-end devices it might result in device throttling and stuttering."].join(" ");export{Z2 as AppViewer,Jt as ClassicMenuBackground,d5 as DocumentRenderer,tt as FUTURISTIC_CAMERA_IDS,f5 as FUTURISTIC_CAMERA_LABELS,et as FUTURISTIC_SCENE_IDS,u5 as FUTURISTIC_SCENE_LABELS,yt as FuturisticMenuBackground,_r as HIGH_TEXTURE_COUNT,$5 as LONG_RENDER_TIME_MS,yr as LOW_FPS_THRESHOLD,Tt as LoadedResourcesTransferrable,y5 as MC_RENDERER_DEBUG_OVERLAY_CLASS,Ge as MENU_BACKGROUND_MC_VERSION,m5 as MENU_BACKGROUND_MOTION_DEFAULTS,ge as MENU_BACKGROUND_OPTION_DEFAULTS,on as MINECRAFT_BLOCK_GROUPS,rt as MINECRAFT_BLOCK_GROUP_IDS,h5 as MINECRAFT_BLOCK_GROUP_LABELS,$t as MenuBackgroundRenderer,o5 as PerformanceMonitor,X2 as RENDERER_DEFAULT_OPTIONS,$2 as RENDERER_OPTIONS_META,es as RENDERER_RENDER_GUI_SECTIONS,fe as ResourcesManager,Zt as WorldBlocksMenuBackground,Xe as WorldView,Ze as WorldViewWorker,Cr as addCanvasForWorker,C6 as applyMenuBackgroundLiveOptions,vf as applyRendererEnableLighting,O6 as applyRendererOptions,of as applyRendererWorldViewOptions,xt as chunkPos,fr as createGraphicsBackendOffThread,ur as createGraphicsBackendSingleThread,dl as createWorldRendererConfig,P2 as defaultGraphicsBackendConfig,br as defaultPerformanceInstabilityFactors,a5 as defaultWorldRendererConfig,F2 as delayedIterator,wr as formatPerformanceFactorsDebug,Ke as getDefaultRendererState,ns as getInitialPlayerState,z6 as getInitialPlayerStateRenderer,D6 as getPlayerStateUtils,a0 as isWebWorker,sf as menuBackgroundOptionsFromStorage,we as menuBackgroundSpeedToMultiplier,_6 as migrateRendererOptions,Ir as rendererShaderCubeDebugModeToValue,a6 as sectionPos,af as subscribeRendererOptions};
21509
21509
  /*! Bundled license information:
21510
21510
 
21511
21511
  @jspm/core/nodelibs/browser/chunk-DtuTasat.js: