minecraft-renderer 0.1.85 → 0.1.86

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.
@@ -21682,7 +21682,7 @@ void main() {
21682
21682
  vFogDepth = -mvPosition.z;
21683
21683
  #endif
21684
21684
  }
21685
- `,L1={u_atlas:{value:null},u_originDelta:{value:new Fe.Vector3},u_cameraOriginFrac:{value:new Fe.Vector3},u_skyLevel:{value:1},u_lightCurve:{value:tt.curve},u_minBrightness:{value:tt.minBrightness},u_lightGamma:{value:tt.gamma}};function l6(){return new Fe.ShaderMaterial({vertexShader:m9,fragmentShader:I1,uniforms:Fe.UniformsUtils.merge([Fe.UniformsLib.fog,L1]),transparent:!0,depthWrite:!0,depthTest:!0,vertexColors:!0,glslVersion:Fe.GLSL3,fog:!0})}function v6(){return new Fe.ShaderMaterial({vertexShader:a6,fragmentShader:I1,uniforms:Fe.UniformsUtils.merge([Fe.UniformsLib.fog,L1]),transparent:!1,depthWrite:!0,depthTest:!0,vertexColors:!0,glslVersion:Fe.GLSL3,fog:!0})}function c6(){return new Fe.ShaderMaterial({vertexShader:a6,fragmentShader:I1,uniforms:Fe.UniformsUtils.merge([Fe.UniformsLib.fog,L1]),transparent:!0,depthWrite:!0,depthTest:!0,vertexColors:!0,glslVersion:Fe.GLSL3,fog:!0})}function Mi(n,e,t,r,i){let{originDelta:s,cameraOriginFrac:o}=I0(e,t,r,i),l=n.uniforms.u_originDelta;l?.value?.set&&l.value.set(s.x,s.y,s.z);let a=n.uniforms.u_cameraOriginFrac;a?.value?.set&&a.value.set(o.x,o.y,o.z)}function Ti(n,e){let t=n.uniforms.u_skyLevel;t&&(t.value=e)}function Ci(n,e){if(e.curve!==void 0){let t=n.uniforms.u_lightCurve;t&&(t.value=e.curve)}if(e.minBrightness!==void 0){let t=n.uniforms.u_minBrightness;t&&(t.value=e.minBrightness)}if(e.gamma!==void 0){let t=n.uniforms.u_lightGamma;t&&(t.value=e.gamma)}}E();x();R();k();var p9=8,g9=.01;function H1(n,e,t,r,i){n.matrix.makeTranslation(e-i.x,t-i.y,r-i.z),n.matrixWorldNeedsUpdate=!0,n.frustumCulled=!1}function Bi(n,e,t,r,i,s,o,l,a,v){let c=n-r,u=e-i,f=t-s,m=p9+g9;return a.set(c-m,u-m,f-m),v.set(c+m,u+m,f+m),l.set(a,v),{visible:o.intersectsBox(l),distSq:c*c+u*u+f*f}}function d6(n,e,t,r,i,s,o,l,a,v,c){let{visible:u,distSq:f}=Bi(e,t,r,i,s,o,l,a,v,c);n.visible=u,n.renderOrder=-f}C1();E();x();R();k();import*as wt from"three";E();x();R();k();E();x();R();k();E();x();R();k();import*as Ne from"three";E();x();R();k();function f6(){return{counts:new Int32Array(Gt),offsets:new Int32Array(Gt)}}function b9(n,e){if(n.counts.length>=e)return;let t=n.counts.length;for(;t<e;)t*=2;n.counts=new Int32Array(t),n.offsets=new Int32Array(t)}function h6(n){let e=n.getExtension("WEBGL_multi_draw");return e?{tier:"A",ext:e}:{tier:"B",ext:null}}var u6=!1;function m6(n,e){u6||!e||(u6=!0)}function p6(n,e,t,r){let i=t.length;if(i===0)return;b9(r,i);let s=n.TRIANGLES,o=n.UNSIGNED_INT;for(let l=0;l<i;l++){let a=t[l];r.counts[l]=a.indexCount,r.offsets[l]=a.indexStart*4}if(e.tier==="A"&&e.ext){e.ext.multiDrawElementsWEBGL(s,r.counts,0,o,r.offsets,0,i);return}for(let l=0;l<i;l++)n.drawElements(s,r.counts[l],o,r.offsets[l])}var rt=4,He=6,ce=3,ht=2,Oe=1,y9=128e3,_9=128e3,g6=5e3,w9=.25,b6=rt*(ce*3+Oe*2+ht)*4+He*4,O1=.75,Gt=64;function D1(n,e,t){for(let r of n)for(let i=r.start;i<r.start+r.count;i++){let s=!1;for(let o of e)if(i>=o.start&&i<o.start+o.count){s=!0;break}}}function Pi(n,e){if(e.length===0)return n;let t=[];for(let r of n){let i=[r];for(let s of e){let o=[];for(let l of i){let a=l.start+l.count-1;if(s.end<l.start||s.start>a){o.push(l);continue}s.start>l.start&&o.push({start:l.start,count:s.start-l.start}),s.end<a&&o.push({start:s.end+1,count:a-s.end})}i=o}t.push(...i)}return t.filter(r=>r.count>0)}var nr=class{constructor(e,t,r){d(this,"mesh");d(this,"material");d(this,"growthIncrementQuads");d(this,"capacityQuads");d(this,"positions");d(this,"colors");d(this,"skyLights");d(this,"blockLights");d(this,"uvs");d(this,"aOrigin");d(this,"indices");d(this,"sectionSlots",new Map);d(this,"freeList",[]);d(this,"highWatermark",0);d(this,"pendingRanges",[]);d(this,"_spanScratch",[]);d(this,"renderOrigin",{x:0,y:0,z:0});d(this,"layoutVersion",0);d(this,"pendingMove",null);d(this,"pendingReplace",new Map);d(this,"uploadEpoch",0);d(this,"visibleIndexSpans",[]);d(this,"_drawScratch",f6());d(this,"multiDrawCaps",null);d(this,"debugOverlay",!1);this.material=e,this.growthIncrementQuads=r?.growthIncrementQuads??_9,this.capacityQuads=r?.initialCapacityQuads??y9;let i=this.capacityQuads*rt;this.positions=new Float32Array(i*ce),this.colors=new Float32Array(i*ce),this.skyLights=new Float32Array(i*Oe),this.blockLights=new Float32Array(i*Oe),this.uvs=new Float32Array(i*ht),this.aOrigin=new Float32Array(i*ce),this.indices=new Uint32Array(this.capacityQuads*He);let s=new Ne.BufferGeometry,o=(a,v,c)=>{let u=new Ne.BufferAttribute(a,v);return u.setUsage(Ne.DynamicDrawUsage),s.setAttribute(c,u),u};o(this.positions,ce,"position"),o(this.colors,ce,"color"),o(this.skyLights,Oe,"a_skyLight"),o(this.blockLights,Oe,"a_blockLight"),o(this.uvs,ht,"uv"),o(this.aOrigin,ce,"a_origin");let l=new Ne.BufferAttribute(this.indices,1);l.setUsage(Ne.DynamicDrawUsage),s.setIndex(l),s.setDrawRange(0,0),s.boundingSphere=new Ne.Sphere(new Ne.Vector3,1/0),this.mesh=new Ne.Mesh(s,[e]),this.mesh.name=r?.name??"globalLegacyOpaque",this.mesh.frustumCulled=!1,this.mesh.matrixAutoUpdate=!1,this.mesh.matrix.identity(),this.mesh.position.set(0,0,0),t.add(this.mesh),this.syncDefaultDrawGroups(),this.mesh.onAfterRender=(a,v,c,u,f)=>{if(this.visibleIndexSpans.length===0)return;let m=a.getContext();this.multiDrawCaps||(this.multiDrawCaps=h6(m),m6(this.multiDrawCaps.tier,this.debugOverlay)),p6(m,this.multiDrawCaps,this.visibleIndexSpans,this._drawScratch)}}setDebugOverlay(e){this.debugOverlay=e}suppressThreeDraw(){this.mesh.geometry.setDrawRange(0,3)}setVisibleIndexSpans(e){this.visibleIndexSpans=e}getVisibleIndexSpans(){return this.visibleIndexSpans}syncDefaultDrawGroups(){let e=this.mesh.geometry;e.clearGroups();let t=this.highWatermark*He;t>0&&e.addGroup(0,t,0),e.setDrawRange(0,t)}addSection(e,t,r,i,s){let o=t.positions.length/ce,l=o/rt;if(o===0||l*rt!==o)return this.removeSection(e),!1;if(t.indices.length%He!==0||t.indices.length/He!==l)return!1;let a=this.sectionSlots.has(e),v;if(a){let T=this.sectionSlots.get(e),P=this.pendingReplace.get(e),B=this.pendingMove?.key===e?this.pendingMove:void 0;P?(this.zeroAndFreeSlot(T.start,T.count),v={start:P.oldStart,count:P.oldCount},this.pendingReplace.delete(e)):B?(this.zeroAndFreeSlot(T.start,T.count),v={start:B.oldStart,count:B.count},this.pendingMove=null):v=T}l>this.capacityQuads&&this.growCapacity(l);let c=this.takeFreeSlot(l);c||(this.highWatermark+l>this.capacityQuads&&this.growCapacity(this.highWatermark+l),c={start:this.highWatermark,count:l},this.highWatermark+=l);let u=c.start*rt,f=u*ce,m=u*ht,g=u*Oe;this.positions.set(t.positions,f),this.colors.set(t.colors,f),this.skyLights.set(t.skyLights,g),this.blockLights.set(t.blockLights,g),this.uvs.set(t.uvs,m);let b=f,A=r-this.renderOrigin.x,y=i-this.renderOrigin.y,_=s-this.renderOrigin.z;for(let T=0;T<o;T++){let P=b+T*ce;this.aOrigin[P]=A,this.aOrigin[P+1]=y,this.aOrigin[P+2]=_}let S=c.start*He,C=u;for(let T=0;T<t.indices.length;T++)this.indices[S+T]=t.indices[T]+C;return this.sectionSlots.set(e,c),a&&v&&this.pendingReplace.set(e,{oldStart:v.start,oldCount:v.count}),this.markDirty(c.start,c.start+l-1),this.syncDefaultDrawGroups(),this.layoutVersion++,!0}getLayoutVersion(){return this.layoutVersion}getUploadEpoch(){return this.uploadEpoch}hasPendingReplace(){return this.pendingReplace.size>0}canUseFullDrawShortcut(){return this.pendingRanges.length===0&&this.interiorFreeQuads()===0&&this.pendingMove===null&&this.pendingReplace.size===0}isRangeFullyUploaded(e,t){return this.rangeFullyUploaded(e,t)}getPendingDirtyRanges(){return this.pendingRanges}getSectionDrawStart(e){let t=this.sectionSlots.get(e);if(!t)return;if(this.pendingMove?.key===e)return this.pendingMove.oldStart;let r=this.pendingReplace.get(e);if(r)return r.oldStart;if(this.rangeFullyUploaded(t.start,t.start+t.count-1))return t.start}getSectionDrawCount(e){let t=this.sectionSlots.get(e);if(!t)return;if(this.pendingMove?.key===e)return this.pendingMove.count;let r=this.pendingReplace.get(e);if(r)return r.oldCount;if(this.rangeFullyUploaded(t.start,t.start+t.count-1))return t.count}getPendingMove(){return this.pendingMove}compactStep(){if(this.pendingMove){let{newStart:l,count:a}=this.pendingMove;this.rangeFullyUploaded(l,l+a-1)&&this.finalizePendingMove();return}for(let l of[...this.pendingReplace.keys()]){let a=this.sectionSlots.get(l);a&&this.rangeFullyUploaded(a.start,a.start+a.count-1)&&this.finalizePendingReplace(l)}if(this.highWatermark===0||this.interiorFreeQuads()/this.highWatermark<=w9)return;let t=this.findMovableSection(g6);if(!t)return;let r=this.findLowestInteriorHole(t.start,t.count);if(!r)return;let i=this.reserveFreeSlotAt(r.index,t.count),s=t.start,o=i.start;this.copySectionRange(s,o,t.count),this.sectionSlots.set(t.key,{start:o,count:t.count}),this.markDirty(o,o+t.count-1),this.pendingMove={key:t.key,oldStart:s,newStart:o,count:t.count},this.layoutVersion++}updateDrawSpans(e,t){if(this.visibleIndexSpans=[],this.highWatermark===0)return;let r=this._spanScratch;r.length=0;let i=0;for(let o of e){let l=this.getSectionDrawStart(o.key),a=this.getSectionDrawCount(o.key),v=this.sectionSlots.get(o.key);l===void 0||a===void 0||!v||(r.push({start:l,count:a}),i+=a)}if(r.length===0)return;let s=(o,l)=>{this.visibleIndexSpans.push({indexStart:o*He,indexCount:l*He})};if(t==="opaque"){let o,l=r.map(v=>({...v})),a=this.canUseFullDrawShortcut()&&i>=this.highWatermark*O1;a?o=[{start:0,count:this.highWatermark}]:(r.sort((v,c)=>v.start-c.start),this.mergeOpaqueSpans(r),o=r),o=Pi(o,this.pendingRanges),a||D1(o,l,this.mesh.name);for(let v of o)s(v.start,v.count)}else{e.sort((o,l)=>l.distSq-o.distSq);for(let o of e){let l=this.getSectionDrawStart(o.key),a=this.getSectionDrawCount(o.key);l===void 0||a===void 0||s(l,a)}}}mergeOpaqueSpans(e){if(e.length<2)return;let t=0;for(;t<e.length-1;){let r=e[t],i=e[t+1];r.start+r.count===i.start?(r.count=i.start+i.count-r.start,e.splice(t+1,1)):t++}}hasSection(e){return this.sectionSlots.has(e)}getSectionSlot(e){return this.sectionSlots.get(e)}takeSectionData(e){let t=this.getSectionGeometryData(e);if(t)return this.removeSection(e),t}getSectionGeometryData(e){let t=this.sectionSlots.get(e);if(!t)return;let r=t.count*rt,i=t.start*rt,s=i*ce,o=i*ht,l=t.start*He,a=t.count*He,v=i*Oe,c=this.positions.slice(s,s+r*ce),u=this.colors.slice(s,s+r*ce),f=this.skyLights.slice(v,v+r*Oe),m=this.blockLights.slice(v,v+r*Oe),g=this.uvs.slice(o,o+r*ht),b=this.indices.slice(l,l+a),A=i;for(let C=0;C<b.length;C++)b[C]=b[C]-A;let y=this.aOrigin[s]+this.renderOrigin.x,_=this.aOrigin[s+1]+this.renderOrigin.y,S=this.aOrigin[s+2]+this.renderOrigin.z;return{positions:c,colors:u,skyLights:f,blockLights:m,uvs:g,indices:b,sx:y,sy:_,sz:S}}removeSection(e){let t=this.sectionSlots.get(e);if(!t)return;if(this.pendingReplace.has(e)){let s=this.pendingReplace.get(e);this.zeroAndFreeSlot(s.oldStart,s.oldCount),this.pendingReplace.delete(e)}if(this.pendingMove?.key===e){let{oldStart:s,count:o}=this.pendingMove;this.zeroAndFreeSlot(s,o),this.pendingMove=null}let r=t.start*He,i=t.count*He;for(let s=0;s<i;s++)this.indices[r+s]=0;this.markDirty(t.start,t.start+t.count-1),this.sectionSlots.delete(e),this.insertFreeSlot(t),this.shrinkHighWatermark(),this.syncDefaultDrawGroups(),this.layoutVersion++}hasPendingUploads(){return this.pendingRanges.length>0}uploadDirtyRange(){let e=this.pendingRanges[0];if(!e)return;let t=e.start,r=Math.min(e.end-e.start+1,g6),i=t*rt,s=r*rt,o=t*He,l=r*He,a=this.mesh.geometry,v=a.getAttribute("position");v.clearUpdateRanges(),v.addUpdateRange(i*ce,s*ce),v.needsUpdate=!0;let c=a.getAttribute("color");c.clearUpdateRanges(),c.addUpdateRange(i*ce,s*ce),c.needsUpdate=!0;let u=a.getAttribute("a_skyLight");u.clearUpdateRanges(),u.addUpdateRange(i*Oe,s*Oe),u.needsUpdate=!0;let f=a.getAttribute("a_blockLight");f.clearUpdateRanges(),f.addUpdateRange(i*Oe,s*Oe),f.needsUpdate=!0;let m=a.getAttribute("uv");m.clearUpdateRanges(),m.addUpdateRange(i*ht,s*ht),m.needsUpdate=!0;let g=a.getAttribute("a_origin");g.clearUpdateRanges(),g.addUpdateRange(i*ce,s*ce),g.needsUpdate=!0;let b=a.index;b.clearUpdateRanges(),b.addUpdateRange(o,l),b.needsUpdate=!0,t+r>e.end?this.pendingRanges.shift():e.start=t+r,this.uploadEpoch++}setRenderOrigin(e){this.renderOrigin={...e}}rebase(e){if(this.highWatermark!==0){for(let t of this.sectionSlots.values()){let r=t.start*rt,i=t.count*rt,s=r*ce;for(let o=0;o<i;o++){let l=s+o*ce;this.aOrigin[l]-=e.x,this.aOrigin[l+1]-=e.y,this.aOrigin[l+2]-=e.z}}this.markDirty(0,this.highWatermark-1),this.renderOrigin.x+=e.x,this.renderOrigin.y+=e.y,this.renderOrigin.z+=e.z}}setCameraOrigin(e,t,r){let{originDelta:i,cameraOriginFrac:s}=I0(this.renderOrigin,e,t,r),o=this.material.uniforms.u_originDelta;o?.value?.set&&o.value.set(i.x,i.y,i.z);let l=this.material.uniforms.u_cameraOriginFrac;l?.value?.set&&l.value.set(s.x,s.y,s.z)}getHighWatermark(){return this.highWatermark}getCapacityQuads(){return this.capacityQuads}getSectionCount(){return this.sectionSlots.size}getMemoryBytes(){return this.capacityQuads*b6}getUsedMemoryBytes(){return this.highWatermark*b6}reset(){this.sectionSlots.clear(),this.freeList.length=0,this.highWatermark=0,this.pendingRanges.length=0,this.pendingMove=null,this.pendingReplace.clear(),this.uploadEpoch=0,this.visibleIndexSpans=[],this.syncDefaultDrawGroups()}dispose(){this.mesh.parent?.remove(this.mesh),this.mesh.geometry.dispose(),this.reset()}markDirty(e,t){this.pendingRanges.push({start:e,end:t}),this.pendingRanges.sort((r,i)=>r.start-i.start),this.mergePendingRanges()}mergePendingRanges(){if(this.pendingRanges.length<2)return;let e=[],t=this.pendingRanges[0];for(let r=1;r<this.pendingRanges.length;r++){let i=this.pendingRanges[r];i.start<=t.end+1?t={start:t.start,end:Math.max(t.end,i.end)}:(e.push(t),t=i)}e.push(t),this.pendingRanges=e}takeFreeSlot(e){for(let t=0;t<this.freeList.length;t++){let r=this.freeList[t];if(r.count>=e){if(this.freeList.splice(t,1),r.count===e)return r;let i={start:r.start,count:e};return this.insertFreeSlot({start:r.start+e,count:r.count-e}),i}}}insertFreeSlot(e){this.freeList.push(e),this.freeList.sort((t,r)=>t.start-r.start),this.mergeFreeList()}mergeFreeList(){if(this.freeList.length<2)return;let e=[],t=this.freeList[0];for(let r=1;r<this.freeList.length;r++){let i=this.freeList[r];t.start+t.count===i.start?t={start:t.start,count:t.count+i.count}:(e.push(t),t=i)}e.push(t),this.freeList=e}shrinkHighWatermark(){for(;this.highWatermark>0;){let e=this.highWatermark-1,t=this.freeList.find(i=>i.start<=e&&i.start+i.count>e);if(!t||t.start+t.count!==this.highWatermark)break;this.highWatermark=t.start;let r=this.freeList.indexOf(t);this.freeList.splice(r,1)}}interiorFreeQuads(){let e=0;for(let t of this.freeList)t.start<this.highWatermark&&(e+=t.count);return e}findMovableSection(e){let t=[];for(let[s,o]of this.sectionSlots)t.push({key:s,start:o.start,count:o.count});if(t.length===0)return;t.sort((s,o)=>o.start!==s.start?o.start-s.start:o.start+o.count-(s.start+s.count));let r=t[0];if(r.count<=e&&this.findLowestInteriorHole(r.start,r.count))return r;let i=t.filter(s=>s.count<=e).sort((s,o)=>o.count-s.count);for(let s of i)if(this.findLowestInteriorHole(s.start,s.count))return s}findLowestInteriorHole(e,t){for(let r=0;r<this.freeList.length;r++){let i=this.freeList[r];if(i.start<e&&i.count>=t)return{start:i.start,count:i.count,index:r}}}reserveFreeSlotAt(e,t){let r=this.freeList[e];if(this.freeList.splice(e,1),r.count===t)return{start:r.start,count:t};let i={start:r.start,count:t};return this.insertFreeSlot({start:r.start+t,count:r.count-t}),i}copySectionRange(e,t,r){let i=e*rt,s=t*rt,o=r*rt,l=s-i,a=i*ce,v=s*ce,c=o*ce;this.positions.copyWithin(v,a,a+c),this.colors.copyWithin(v,a,a+c),this.aOrigin.copyWithin(v,a,a+c);let u=i*Oe,f=s*Oe,m=o*Oe;this.skyLights.copyWithin(f,u,u+m),this.blockLights.copyWithin(f,u,u+m);let g=i*ht,b=s*ht,A=o*ht;this.uvs.copyWithin(b,g,g+A);let y=e*He,_=t*He,S=r*He;for(let C=0;C<S;C++)this.indices[_+C]=this.indices[y+C]+l}rangeFullyUploaded(e,t){for(let r of this.pendingRanges)if(r.start<=t&&r.end>=e)return!1;return!0}zeroAndFreeSlot(e,t){let r=e*He,i=t*He;for(let s=0;s<i;s++)this.indices[r+s]=0;this.markDirty(e,e+t-1),this.insertFreeSlot({start:e,count:t})}finalizePendingReplace(e){let t=this.pendingReplace.get(e);t&&(this.zeroAndFreeSlot(t.oldStart,t.oldCount),this.pendingReplace.delete(e),this.shrinkHighWatermark(),this.syncDefaultDrawGroups(),this.layoutVersion++,this.uploadEpoch++)}finalizePendingMove(){let e=this.pendingMove;if(!e)return;let{oldStart:t,count:r}=e;this.zeroAndFreeSlot(t,r),this.shrinkHighWatermark(),this.syncDefaultDrawGroups(),this.pendingMove=null,this.layoutVersion++,this.uploadEpoch++}growCapacity(e){this.pendingMove&&this.finalizePendingMove();for(let A of[...this.pendingReplace.keys()])this.finalizePendingReplace(A);let t=this.capacityQuads;for(;t<e;)t+=this.growthIncrementQuads;let r=this.capacityQuads*rt,i=t*rt,s=new Float32Array(i*ce),o=new Float32Array(i*ce),l=new Float32Array(i*Oe),a=new Float32Array(i*Oe),v=new Float32Array(i*ht),c=new Float32Array(i*ce),u=new Uint32Array(t*He);s.set(this.positions),o.set(this.colors),l.set(this.skyLights),a.set(this.blockLights),v.set(this.uvs),c.set(this.aOrigin),u.set(this.indices),this.positions=s,this.colors=o,this.skyLights=l,this.blockLights=a,this.uvs=v,this.aOrigin=c,this.indices=u,this.capacityQuads=t;let f=this.mesh.geometry,m=(A,y,_)=>{f.getAttribute(_)&&f.deleteAttribute(_);let C=new Ne.BufferAttribute(A,y);C.setUsage(Ne.DynamicDrawUsage),f.setAttribute(_,C)};m(this.positions,ce,"position"),m(this.colors,ce,"color"),m(this.skyLights,Oe,"a_skyLight"),m(this.blockLights,Oe,"a_blockLight"),m(this.uvs,ht,"uv"),m(this.aOrigin,ce,"a_origin"),f.index&&f.setIndex(null);let b=new Ne.BufferAttribute(this.indices,1);b.setUsage(Ne.DynamicDrawUsage),f.setIndex(b),this.pendingRanges.length=0}};function A9(n){if(n.length<2)return;let e=0;for(;e<n.length-1;){let t=n[e],r=n[e+1];t.start+t.count===r.start?(t.count=r.start+r.count-t.start,n.splice(e+1,1)):e++}}function y6(n,e,t=!0,r,i=[]){if(n.length===0||e===0)return[];let s=0;for(let a of n)s+=a.count;let o;if(t&&s>=e*O1)o=[{start:0,count:e}];else{o=n.map(v=>({start:v.start,count:v.count})),o.sort((v,c)=>v.start-c.start);let a=o.map(v=>({...v}));return A9(o),o=Pi(o,i),D1(o,a,"globalBlockBuffer"),o}return Pi(o,i)}$t();function w6(){return{firsts:new Int32Array(Gt),counts:new Int32Array(Gt),instanceCounts:new Int32Array(Gt),baseInstances:new Int32Array(Gt)}}function A6(n){let e=n.getExtension("WEBGL_multi_draw_instanced_base_vertex_base_instance");if(e)return{tier:"A",ext:e};let t=n.getExtension("WEBGL_draw_instanced_base_vertex_base_instance");return t?{tier:"B",ext:t}:{tier:"C",ext:null}}var _6=!1;function E6(n,e){_6||!e||(_6=!0)}function x6(n,e,t,r,i){let s=t.length;if(s===0)return;let o=n.TRIANGLES;if(e.tier==="A"&&e.ext){let l=e.ext;for(let a=0;a<s;a++){let v=t[a];r.firsts[a]=0,r.counts[a]=Ut,r.instanceCounts[a]=v.count,r.baseInstances[a]=v.start}l.multiDrawArraysInstancedBaseInstanceWEBGL(o,r.firsts,0,r.counts,0,r.instanceCounts,0,r.baseInstances,0,s);return}if(e.tier==="B"&&e.ext){let l=e.ext;for(let a=0;a<s;a++){let v=t[a];l.drawArraysInstancedBaseInstanceWEBGL(o,0,Ut,v.count,v.start)}return}i?.(n,t)}$t();a5();var E9=512e3,x9=1e6,k6=15e3,k9=.25,sr=$3(),R6=16,Ii=class{constructor(e,t){d(this,"mesh");d(this,"capacityFaces");d(this,"w0");d(this,"w1");d(this,"w2");d(this,"w3");d(this,"sectionSlots",new Map);d(this,"freeList",[]);d(this,"highWatermark",0);d(this,"pendingRanges",[]);d(this,"pendingMove",null);d(this,"pendingReplace",new Map);d(this,"uploadEpoch",0);d(this,"visibleSpans",[]);d(this,"_drawScratch",w6());d(this,"multiDrawCaps",null);d(this,"tierCVao",null);d(this,"tierCAttrs",null);d(this,"tierCGl",null);d(this,"debugOverlay",!1);d(this,"layoutVersion",0);this.capacityFaces=E9,this.w0=new Uint32Array(this.capacityFaces),this.w1=new Uint32Array(this.capacityFaces),this.w2=new Uint32Array(this.capacityFaces),this.w3=new Uint32Array(this.capacityFaces),this.w2.fill(sr);let r=new wt.InstancedBufferGeometry,i=new Float32Array(Ut*3);r.setAttribute("position",new wt.BufferAttribute(i,3));let s=o=>{let l=new wt.InstancedBufferAttribute(o,1);return l.setUsage(wt.DynamicDrawUsage),l};r.setAttribute("a_w0",s(this.w0)),r.setAttribute("a_w1",s(this.w1)),r.setAttribute("a_w2",s(this.w2)),r.setAttribute("a_w3",s(this.w3)),r.instanceCount=0,this.mesh=new wt.Mesh(r,e),this.mesh.name="globalShaderCubes",this.mesh.frustumCulled=!1,this.mesh.matrixAutoUpdate=!1,this.mesh.matrix.identity(),this.mesh.position.set(0,0,0),t.add(this.mesh),this.mesh.onAfterRender=(o,l,a,v,c)=>{if(this.visibleSpans.length===0)return;let u=c,f=o.getContext();this.multiDrawCaps||(this.multiDrawCaps=A6(f),E6(this.multiDrawCaps.tier,this.debugOverlay)),x6(f,this.multiDrawCaps,this.visibleSpans,this._drawScratch,this.multiDrawCaps.tier==="C"?(m,g)=>this.drawTierCSpans(m,g,o,u):void 0)}}setDebugOverlay(e){this.debugOverlay=e}suppressThreeDraw(){let e=this.mesh.geometry;e.setDrawRange(0,Ut),e.instanceCount=0}setVisibleSpans(e){this.visibleSpans=e}getVisibleSpans(){return this.visibleSpans}forEachSectionSlot(e){for(let[t,r]of this.sectionSlots)e(t,r)}getSectionDrawStart(e){let t=this.sectionSlots.get(e);if(!t)return;if(this.pendingMove?.key===e)return this.pendingMove.oldStart;let r=this.pendingReplace.get(e);if(r)return r.oldStart;if(this.rangeFullyUploaded(t.start,t.start+t.count-1))return t.start}getSectionDrawCount(e){let t=this.sectionSlots.get(e);if(!t)return;if(this.pendingMove?.key===e)return this.pendingMove.count;let r=this.pendingReplace.get(e);if(r)return r.oldCount;if(this.rangeFullyUploaded(t.start,t.start+t.count-1))return t.count}getUploadEpoch(){return this.uploadEpoch}hasPendingReplace(){return this.pendingReplace.size>0}canUseFullDrawShortcut(){return this.pendingRanges.length===0&&this.interiorFreeFaces()===0&&this.pendingMove===null&&this.pendingReplace.size===0}isRangeFullyUploaded(e,t){return this.rangeFullyUploaded(e,t)}getPendingDirtyRanges(){return this.pendingRanges}getHighWatermark(){return this.highWatermark}getCapacityFaces(){return this.capacityFaces}getSectionCount(){return this.sectionSlots.size}getMemoryBytes(){return this.capacityFaces*R6}getUsedMemoryBytes(){return this.highWatermark*R6}hasPendingUploads(){return this.pendingRanges.length>0}getPendingMove(){return this.pendingMove}addSection(e,t,r){if(r<=0){this.removeSection(e);return}let i=this.sectionSlots.has(e),s;if(i){let a=this.sectionSlots.get(e),v=this.pendingReplace.get(e),c=this.pendingMove?.key===e?this.pendingMove:void 0;v?(this.zeroAndFreeSlot(a.start,a.count),s={start:v.oldStart,count:v.oldCount},this.pendingReplace.delete(e)):c?(this.zeroAndFreeSlot(a.start,a.count),s={start:c.oldStart,count:c.count},this.pendingMove=null):s=a}r>this.capacityFaces&&this.growCapacity(r);let o=this.takeFreeSlot(r);o||(this.highWatermark+r>this.capacityFaces&&this.growCapacity(this.highWatermark+r),o={start:this.highWatermark,count:r},this.highWatermark+=r);let l=4;for(let a=0;a<r;a++){let v=o.start+a,c=a*l;this.w0[v]=t[c],this.w1[v]=t[c+1],this.w2[v]=t[c+2],this.w3[v]=t[c+3]}this.sectionSlots.set(e,o),i&&s&&this.pendingReplace.set(e,{oldStart:s.start,oldCount:s.count}),this.markDirty(o.start,o.start+r-1),this.mesh.geometry.instanceCount=this.highWatermark,this.layoutVersion++}getLayoutVersion(){return this.layoutVersion}hasSection(e){return this.sectionSlots.has(e)}getSectionSlot(e){return this.sectionSlots.get(e)}getW0(){return this.w0}takeSectionData(e){let t=this.sectionSlots.get(e);if(!t)return;let r=4,i=new Uint32Array(t.count*r);for(let s=0;s<t.count;s++){let o=t.start+s,l=s*r;i[l]=this.w0[o],i[l+1]=this.w1[o],i[l+2]=this.w2[o],i[l+3]=this.w3[o]}return this.removeSection(e),{words:i,count:t.count}}removeSection(e){let t=this.sectionSlots.get(e);if(t){if(this.pendingReplace.has(e)){let r=this.pendingReplace.get(e);this.zeroAndFreeSlot(r.oldStart,r.oldCount),this.pendingReplace.delete(e)}if(this.pendingMove?.key===e){let{oldStart:r,count:i}=this.pendingMove;this.zeroAndFreeSlot(r,i),this.pendingMove=null}for(let r=t.start;r<t.start+t.count;r++)this.w0[r]=0,this.w1[r]=0,this.w2[r]=sr,this.w3[r]=0;this.markDirty(t.start,t.start+t.count-1),this.sectionSlots.delete(e),this.insertFreeSlot(t),this.shrinkHighWatermark(),this.mesh.geometry.instanceCount=this.highWatermark,this.layoutVersion++}}compactStep(){if(this.pendingMove){let{newStart:l,count:a}=this.pendingMove;this.rangeFullyUploaded(l,l+a-1)&&this.finalizePendingMove();return}for(let l of[...this.pendingReplace.keys()]){let a=this.sectionSlots.get(l);a&&this.rangeFullyUploaded(a.start,a.start+a.count-1)&&this.finalizePendingReplace(l)}if(this.highWatermark===0||this.interiorFreeFaces()/this.highWatermark<=k9)return;let t=this.findMovableSection(k6);if(!t)return;let r=this.findLowestInteriorHole(t.start,t.count);if(!r)return;let i=this.reserveFreeSlotAt(r.index,t.count),s=t.start,o=i.start;this.copySectionRange(s,o,t.count),this.sectionSlots.set(t.key,{start:o,count:t.count}),this.markDirty(o,o+t.count-1),this.pendingMove={key:t.key,oldStart:s,newStart:o,count:t.count},this.layoutVersion++}uploadDirtyRange(){let e=this.pendingRanges[0];if(!e)return;let t=e.start,r=Math.min(e.end-e.start+1,k6),i=this.mesh.geometry;for(let s of["a_w0","a_w1","a_w2","a_w3"]){let o=i.getAttribute(s);o.clearUpdateRanges(),o.addUpdateRange(t,r),o.needsUpdate=!0}t+r>e.end?this.pendingRanges.shift():e.start=t+r,this.uploadEpoch++}setCameraOrigin(e,t,r,i){let{originDelta:s,cameraOriginFrac:o}=I0(e,t,r,i),l=wi(e),a=this.mesh.material.uniforms.u_originDelta;a?.value?.set&&a.value.set(s.x,s.y,s.z);let v=this.mesh.material.uniforms.u_cameraOriginFrac;v?.value?.set&&v.value.set(o.x,o.y,o.z);let c=this.mesh.material.uniforms.u_sectionOriginRel;c?.value?.set&&c.value.set(l.x,l.y,l.z)}reset(){this.sectionSlots.clear(),this.freeList.length=0,this.highWatermark=0,this.pendingRanges.length=0,this.pendingMove=null,this.pendingReplace.clear(),this.uploadEpoch=0,this.visibleSpans=[],this.w0.fill(0),this.w1.fill(0),this.w2.fill(sr),this.w3.fill(0),this.mesh.geometry.instanceCount=0,this.invalidateTierCVao()}dispose(){this.invalidateTierCVao(),this.mesh.parent?.remove(this.mesh),this.mesh.geometry.dispose(),this.reset()}invalidateTierCVao(){this.tierCVao&&this.tierCGl&&this.tierCGl.deleteVertexArray(this.tierCVao),this.tierCVao=null,this.tierCAttrs=null}drawTierCSpans(e,t,r,i){if(this.ensureTierCVao(e,r,i),!this.tierCVao||!this.tierCAttrs)return;let s=this.tierCAttrs;e.bindVertexArray(this.tierCVao);for(let o of t){let l=o.start*4,a=v=>{e.bindBuffer(e.ARRAY_BUFFER,v.buffer),e.vertexAttribIPointer(v.loc,1,e.UNSIGNED_INT,4,l)};a(s.w0),a(s.w1),a(s.w2),a(s.w3),e.drawArraysInstanced(e.TRIANGLES,0,Ut,o.count)}e.bindVertexArray(null)}ensureTierCVao(e,t,r){this.tierCGl=e;let o=t.properties.get(r).currentProgram.program,l=e.getAttribLocation(o,"a_w0"),a=e.getAttribLocation(o,"a_w1"),v=e.getAttribLocation(o,"a_w2"),c=e.getAttribLocation(o,"a_w3"),u=S=>S<0?null:e.getVertexAttrib(S,e.VERTEX_ATTRIB_ARRAY_BUFFER_BINDING),f=u(l);if(this.tierCVao&&this.tierCAttrs&&f&&this.tierCAttrs.w0.buffer!==f&&this.invalidateTierCVao(),this.tierCVao)return;let m=u(l),g=u(a),b=u(v),A=u(c);if(!m||!g||!b||!A)return;let y=e.createVertexArray();if(!y)return;e.bindVertexArray(y);let _=(S,C)=>{e.enableVertexAttribArray(S),e.bindBuffer(e.ARRAY_BUFFER,C),e.vertexAttribIPointer(S,1,e.UNSIGNED_INT,4,0),e.vertexAttribDivisor(S,1)};_(l,m),_(a,g),_(v,b),_(c,A),e.bindVertexArray(null),this.tierCVao=y,this.tierCAttrs={w0:{loc:l,buffer:m},w1:{loc:a,buffer:g},w2:{loc:v,buffer:b},w3:{loc:c,buffer:A}}}markDirty(e,t){this.pendingRanges.push({start:e,end:t}),this.pendingRanges.sort((r,i)=>r.start-i.start),this.mergePendingRanges()}mergePendingRanges(){if(this.pendingRanges.length<2)return;let e=[],t=this.pendingRanges[0];for(let r=1;r<this.pendingRanges.length;r++){let i=this.pendingRanges[r];i.start<=t.end+1?t={start:t.start,end:Math.max(t.end,i.end)}:(e.push(t),t=i)}e.push(t),this.pendingRanges=e}takeFreeSlot(e){for(let t=0;t<this.freeList.length;t++){let r=this.freeList[t];if(r.count>=e){if(this.freeList.splice(t,1),r.count===e)return r;let i={start:r.start,count:e};return this.insertFreeSlot({start:r.start+e,count:r.count-e}),i}}}insertFreeSlot(e){this.freeList.push(e),this.freeList.sort((t,r)=>t.start-r.start),this.mergeFreeList()}mergeFreeList(){if(this.freeList.length<2)return;let e=[],t=this.freeList[0];for(let r=1;r<this.freeList.length;r++){let i=this.freeList[r];t.start+t.count===i.start?t={start:t.start,count:t.count+i.count}:(e.push(t),t=i)}e.push(t),this.freeList=e}interiorFreeFaces(){let e=0;for(let t of this.freeList)t.start<this.highWatermark&&(e+=t.count);return e}findMovableSection(e){let t=[];for(let[s,o]of this.sectionSlots)t.push({key:s,start:o.start,count:o.count});if(t.length===0)return;t.sort((s,o)=>o.start!==s.start?o.start-s.start:o.start+o.count-(s.start+s.count));let r=t[0];if(r.count<=e&&this.findLowestInteriorHole(r.start,r.count))return r;let i=t.filter(s=>s.count<=e).sort((s,o)=>o.count-s.count);for(let s of i)if(this.findLowestInteriorHole(s.start,s.count))return s}findLowestInteriorHole(e,t){for(let r=0;r<this.freeList.length;r++){let i=this.freeList[r];if(i.start<e&&i.count>=t)return{start:i.start,count:i.count,index:r}}}reserveFreeSlotAt(e,t){let r=this.freeList[e];if(this.freeList.splice(e,1),r.count===t)return{start:r.start,count:t};let i={start:r.start,count:t};return this.insertFreeSlot({start:r.start+t,count:r.count-t}),i}copySectionRange(e,t,r){this.w0.copyWithin(t,e,e+r),this.w1.copyWithin(t,e,e+r),this.w2.copyWithin(t,e,e+r),this.w3.copyWithin(t,e,e+r)}rangeFullyUploaded(e,t){for(let r of this.pendingRanges)if(r.start<=t&&r.end>=e)return!1;return!0}zeroAndFreeSlot(e,t){for(let r=e;r<e+t;r++)this.w0[r]=0,this.w1[r]=0,this.w2[r]=sr,this.w3[r]=0;this.markDirty(e,e+t-1),this.insertFreeSlot({start:e,count:t})}finalizePendingReplace(e){let t=this.pendingReplace.get(e);t&&(this.zeroAndFreeSlot(t.oldStart,t.oldCount),this.pendingReplace.delete(e),this.shrinkHighWatermark(),this.mesh.geometry.instanceCount=this.highWatermark,this.layoutVersion++,this.uploadEpoch++)}finalizePendingMove(){let e=this.pendingMove;if(!e)return;let{oldStart:t,count:r}=e;this.zeroAndFreeSlot(t,r),this.shrinkHighWatermark(),this.mesh.geometry.instanceCount=this.highWatermark,this.pendingMove=null,this.layoutVersion++,this.uploadEpoch++}shrinkHighWatermark(){for(;this.highWatermark>0;){let e=this.highWatermark-1,t=this.freeList.find(i=>i.start<=e&&i.start+i.count>e);if(!t||t.start+t.count!==this.highWatermark)break;this.highWatermark=t.start;let r=this.freeList.indexOf(t);this.freeList.splice(r,1)}}growCapacity(e){this.pendingMove&&this.finalizePendingMove();for(let v of[...this.pendingReplace.keys()])this.finalizePendingReplace(v);let t=this.capacityFaces;for(;t<e;)t+=x9;let r=new Uint32Array(t),i=new Uint32Array(t),s=new Uint32Array(t),o=new Uint32Array(t);r.set(this.w0),i.set(this.w1),s.set(this.w2),o.set(this.w3),s.fill(sr,this.w0.length),this.w0=r,this.w1=i,this.w2=s,this.w3=o,this.capacityFaces=t;let l=this.mesh.geometry,a=(v,c)=>{let u=l.getAttribute(c);u&&(l.deleteAttribute(c),"dispose"in u&&typeof u.dispose=="function"&&u.dispose());let f=new wt.InstancedBufferAttribute(v,1);f.setUsage(wt.DynamicDrawUsage),l.setAttribute(c,f)};a(this.w0,"a_w0"),a(this.w1,"a_w1"),a(this.w2,"a_w2"),a(this.w3,"a_w3"),this.pendingRanges.length=0,this.invalidateTierCVao()}};E();x();R();k();a5();$t();function S6(n,e,t,r,i){if(e<=0)return;let s=t-8,o=r-8,l=i-8,a=ki,v=16,c=16,u=16,f=-1,m=-1,g=-1;for(let T=0;T<e;T++){let P=n[T*a],B=P&(1<<P0.LX_BITS)-1,L=P>>P0.LY_SHIFT&(1<<P0.LY_BITS)-1,V=P>>P0.LZ_SHIFT&(1<<P0.LZ_BITS)-1;B<v&&(v=B),L<c&&(c=L),V<u&&(u=V),B>f&&(f=B),L>m&&(m=L),V>g&&(g=V)}if(f<0)return;let b=s+v,A=o+c,y=l+u,_=s+f+1,S=o+m+1,C=l+g+1;return{minX:b,minY:A,minZ:y,maxX:_,maxY:S,maxZ:C,cx:(b+_)*.5,cy:(A+S)*.5,cz:(y+C)*.5}}function R9(n,e,t,r,i,s,o,l,a){return n>=r&&n<=o&&e>=i&&e<=l&&t>=s&&t<=a}function M6(n,e,t,r,i,s,o,l,a,v,c,u,f){if(R9(n,e,t,o,l,a,v,c,u))return;let m=0,g=f;if(Math.abs(r)<1e-8){if(n<o||n>v)return}else{let b=1/r,A=(o-n)*b,y=(v-n)*b;if(A>y){let _=A;A=y,y=_}if(m=Math.max(m,A),g=Math.min(g,y),m>g)return}if(Math.abs(i)<1e-8){if(e<l||e>c)return}else{let b=1/i,A=(l-e)*b,y=(c-e)*b;if(A>y){let _=A;A=y,y=_}if(m=Math.max(m,A),g=Math.min(g,y),m>g)return}if(Math.abs(s)<1e-8){if(t<a||t>u)return}else{let b=1/s,A=(a-t)*b,y=(u-t)*b;if(A>y){let _=A;A=y,y=_}if(m=Math.max(m,A),g=Math.min(g,y),m>g)return}return m<=g&&m>=0?m:void 0}function T6(n,e,t,r,i,s,o,l,a,v,c,u,f){let m=f;if(Math.abs(r)>=1e-8){let g=r>0?(v-n)/r:(o-n)/r;g>1e-6&&(m=Math.min(m,g))}else if(n<o||n>v)return;if(Math.abs(i)>=1e-8){let g=i>0?(c-e)/i:(l-e)/i;g>1e-6&&(m=Math.min(m,g))}else if(e<l||e>c)return;if(Math.abs(s)>=1e-8){let g=s>0?(u-t)/s:(a-t)/s;g>1e-6&&(m=Math.min(m,g))}else if(t<a||t>u)return;return m<=f?m:void 0}E();x();R();k();import*as st from"three";E();x();R();k();bi();var Li=class{constructor(){d(this,"entries",new Set);d(this,"skyLevel",1);d(this,"lightmapParams",{...tt})}register(e){this.entries.add(e),this.applyBrightness(e)}unregister(e){for(let t of this.entries)if(t.material===e){this.entries.delete(t);break}}setSkyLevel(e){this.skyLevel=e,this.refreshAll()}setLightmapParams(e){this.lightmapParams={...this.lightmapParams,...e},this.refreshAll()}getSkyLevel(){return this.skyLevel}refreshAll(){for(let e of this.entries)this.applyBrightness(e)}applyBrightness(e){let t=k1(e.blockLightNorm,e.skyLightNorm,this.skyLevel,this.lightmapParams);e.material.color.setScalar(t)}};function C6(n,e,t,r,i=tt){let s=k1(e,t,r,i);return n.color.setScalar(s),s}var B6=20,P6=40,S9={white_banner:15,orange_banner:14,magenta_banner:13,light_blue_banner:12,yellow_banner:11,lime_banner:10,pink_banner:9,gray_banner:8,light_gray_banner:7,cyan_banner:6,purple_banner:5,blue_banner:4,brown_banner:3,green_banner:2,red_banner:1,black_banner:0},I6={0:"#1d1d21",1:"#b02e26",2:"#5e7c16",3:"#835432",4:"#3c44aa",5:"#8932b8",6:"#169c9c",7:"#9d9d97",8:"#474f52",9:"#f38baa",10:"#80c71f",11:"#fed83d",12:"#3ab3da",13:"#c74ebd",14:"#f9801d",15:"#f9fffe"};function M9(n){let e=n.replace("_wall_banner","_banner");return S9[e]??15}var T9=(n,e,t,r,i,s,o)=>{switch(n.fillStyle=t,e){case"bs":n.fillRect(r,i,s,o);break;case"ls":n.fillRect(r,i,s/3,o);break;case"rs":n.fillRect(r+s*2/3,i,s/3,o);break;case"ts":n.fillRect(r,i,s,o/3);break;case"ms":n.fillRect(r,i+o/3,s,o/3);break;case"drs":n.fillRect(r,i,s/2,o/2);break;case"dls":n.fillRect(r+s/2,i,s/2,o/2);break;case"ss":for(let l=0;l<s;l+=2)n.fillRect(r+l,i,1,o);break;case"cr":n.fillRect(r,i+o/3,s,o/3),n.fillRect(r+s/3,i,s/3,o);break;case"sc":n.fillRect(r,i+o/2-1,s,2),n.fillRect(r+s/2-1,i,2,o);break;default:n.fillRect(r,i,s,o)}};function C9(n,e){if(!e||e.length===0)return`banner_${n}_empty`;let t=e.map(r=>`${r.Pattern??"bs"}_${r.Color??0}`).join(",");return`banner_${n}_${t}`}var B9=(n,e,t=(r,i)=>Je(r,i))=>{let i=t(B6*1,P6*1),s=i.getContext("2d");if(s){if(s.imageSmoothingEnabled=!1,e?.Patterns&&e.Patterns.length>0)for(let o of e.Patterns){let l=o.Color??0,a=o.Pattern??"bs",v=I6[l]||I6[0];T9(s,a,v,0,0,B6*1,P6*1)}return i}},Hi=new Map;function L6(n,e,t){let r=M9(e),i=C9(r,t?.Patterns),s=Hi.get(i);if(s)return s.refCount++,s.texture;let o=B9(r,t);if(!o)return;let l=new st.Texture(o);return l.magFilter=st.NearestFilter,l.minFilter=st.NearestFilter,l.needsUpdate=!0,Hi.set(i,{texture:l,refCount:1}),l}function H6(n){for(let[e,t]of Hi.entries())if(t.texture===n){t.refCount--,t.refCount<=0&&(t.texture.dispose(),Hi.delete(e));return}}function O6(n,e,t,r,i=0,s=1,o=1){let c,u,f;t?(c=(-14.6+13.4)/2/16-.5,u=1-14.75/16-.5,f=1/2):(c=(1.4+29.4)/2/16,u=1-7.25/16-.5,f=0);let m=new st.MeshBasicMaterial({map:r,transparent:!0});C6(m,i,s,o);let g=new st.Mesh(new st.PlaneGeometry(.85,1.75),m);g.renderOrder=999;let b=.5/16,A=.25/16;t?g.position.set(0,c,u+A+.004):g.position.set(0,c,u+b/2+.004);let y=new st.Group;return y.rotation.set(0,-st.MathUtils.degToRad(e*(t?90:45/2)),0),y.add(g),y.bannerTexture=r,y.bannerMaterial=m,y.position.set(n.x+.5,n.y+f,n.z+.5),y}E();x();R();k();import*as or from"three";import P9 from"prismarine-chat";var l5=new Map;function I9(n,e,t){let r,i;return n&&"front_text"in n?(r=n.front_text?.messages??[],i=n.front_text?.color||"black"):(r=[n?.Text1,n?.Text2,n?.Text3,n?.Text4],i=n?.Color||"black"),`${e?1:0}|${t?1:0}|${i}|${r.join("\0")}`}function D6(n,e,t,r=!1){let i=I9(e,t,r),s=l5.get(i);if(s)return s.refCount++,s.texture;let o=P9(n.version),l=$2(e,t,o);if(!l)return;let a=new or.Texture(l);return a.magFilter=or.NearestFilter,a.minFilter=or.NearestFilter,a.needsUpdate=!0,l5.set(i,{texture:a,refCount:1}),a}function F6(n){for(let[e,t]of l5.entries())if(t.texture===n){t.refCount--,t.refCount<=0&&(t.texture.dispose(),l5.delete(e));return}}function z6(){for(let[,n]of l5)n.texture.dispose();l5.clear()}var Rt=class Rt{constructor(e,t,r,i,s=3){this.worldRenderer=e;this.scene=t;this.material=r;this.worldHeight=i;d(this,"renderOrigin",{x:0,y:0,z:0});d(this,"meshPool",[]);d(this,"activeSections",new Map);d(this,"sectionObjects",{});d(this,"waitingChunksToDisplay",{});d(this,"pendingNearReveal",new Map);d(this,"nearRevealTimers",new Map);d(this,"nearRevealGraceTimers",new Map);d(this,"poolSize");d(this,"maxPoolSize");d(this,"minPoolSize");d(this,"signHeadsRenderer");d(this,"blockEntityLightRegistry",new Li);d(this,"chunkBoxMaterial",new J.MeshBasicMaterial({color:0,transparent:!0,opacity:0}));d(this,"cubeShaderMaterial",null);d(this,"legacyShaderMaterial",null);d(this,"globalLegacyShaderMaterial",null);d(this,"globalLegacyBlendShaderMaterial",null);d(this,"_legacyCullFrustum",new J.Frustum);d(this,"_legacyCullProjScreen",new J.Matrix4);d(this,"_legacyCullBox",new J.Box3);d(this,"_legacyCullBoxMin",new J.Vector3);d(this,"_legacyCullBoxMax",new J.Vector3);d(this,"_visibleSectionSpans",[]);d(this,"legacyCullSections",new Map);d(this,"_lastCullFingerprint","");d(this,"lastBufferStateKey","");d(this,"cullDirty",!0);d(this,"_lastCullCamPos",new J.Vector3);d(this,"_lastCullCamQuat",new J.Quaternion);d(this,"_cullViewQuat",new J.Quaternion);d(this,"_cullCamInitialized",!1);d(this,"globalBlockBuffer",null);d(this,"globalLegacyBuffer",null);d(this,"globalLegacyBlendBuffer",null);d(this,"shaderSectionRaycastBoxes",new Map);d(this,"hits",0);d(this,"misses",0);d(this,"bypassPooling",!1);d(this,"renderTimes",[]);d(this,"maxRenderTimeSamples",30);d(this,"_performanceOverrideDistance");d(this,"lastPerformanceCheck",0);d(this,"performanceCheckInterval",2e3);this.updateViewDistance(s),this.signHeadsRenderer=new z1(e),this.initializePool()}get performanceOverrideDistance(){return this._performanceOverrideDistance??0}set performanceOverrideDistance(e){this._performanceOverrideDistance=e,this.updateSectionsVisibility()}initializePool(){for(let e=0;e<this.poolSize;e++){let t=new J.BufferGeometry,r=new J.Mesh(t,this.getLegacyShaderMaterial());r.visible=!1,r.matrixAutoUpdate=!1,r.name="pooled-section-mesh";let i={mesh:r,inUse:!1,lastUsedTime:0};this.meshPool.push(i)}}sectionHasRenderableContent(e){return e.positions.length>0||(e.blend?.positions.length??0)>0?!0:this.isShaderCubesGpuEnabled()?(e.shaderCubes?.count??0)>0:!1}isShaderCubesGpuEnabled(){return this.worldRenderer.shaderCubeBlocksEnabled()}syncCubeShaderUniforms(){if(!this.isShaderCubesGpuEnabled())return;let e=this.cubeShaderMaterial??this.getCubeShaderMaterial();if(!e)return;let t=this.material.map??null;e.uniforms.u_atlas.value=t;let r=Ri();if(!r)return;let{tintPalette:i}=r;i.isReady()||i.createTexture(),e.uniforms.u_tintPalette.value=i.getTexture(),e.uniforms.u_debugMode.value=this.worldRenderer.worldRendererConfig.shaderCubeDebugMode??0,e.needsUpdate=!0}syncLegacyShaderUniforms(){let e=this.material.map??null;this.legacyShaderMaterial&&(this.legacyShaderMaterial.uniforms.u_atlas.value=e,this.legacyShaderMaterial.needsUpdate=!0),this.globalLegacyShaderMaterial&&(this.globalLegacyShaderMaterial.uniforms.u_atlas.value=e,this.globalLegacyShaderMaterial.needsUpdate=!0),this.globalLegacyBlendShaderMaterial&&(this.globalLegacyBlendShaderMaterial.uniforms.u_atlas.value=e,this.globalLegacyBlendShaderMaterial.needsUpdate=!0)}setSkyLevel(e){let t=this.cubeShaderMaterial??(this.isShaderCubesGpuEnabled()?this.getCubeShaderMaterial():null);t&&_i(t,e),this.legacyShaderMaterial&&Ti(this.legacyShaderMaterial,e),this.globalLegacyShaderMaterial&&Ti(this.globalLegacyShaderMaterial,e),this.globalLegacyBlendShaderMaterial&&Ti(this.globalLegacyBlendShaderMaterial,e),this.blockEntityLightRegistry.setSkyLevel(e)}setShadingTheme(e,t){let r=this.cubeShaderMaterial??(this.isShaderCubesGpuEnabled()?this.getCubeShaderMaterial():null);r&&R1(r,e,t)}setBlockLightmapParams(e){let t=this.cubeShaderMaterial??(this.isShaderCubesGpuEnabled()?this.getCubeShaderMaterial():null);t&&Y3(t,e),this.legacyShaderMaterial&&Ci(this.legacyShaderMaterial,e),this.globalLegacyShaderMaterial&&Ci(this.globalLegacyShaderMaterial,e),this.globalLegacyBlendShaderMaterial&&Ci(this.globalLegacyBlendShaderMaterial,e),this.blockEntityLightRegistry.setLightmapParams(e)}getLegacyShaderMaterial(){return this.legacyShaderMaterial||(this.legacyShaderMaterial=l6(),this.syncLegacyShaderUniforms()),this.legacyShaderMaterial}getGlobalLegacyShaderMaterial(){return this.globalLegacyShaderMaterial||(this.globalLegacyShaderMaterial=v6(),this.syncLegacyShaderUniforms()),this.globalLegacyShaderMaterial}getGlobalLegacyBuffer(){return this.globalLegacyBuffer||(this.globalLegacyBuffer=new nr(this.getGlobalLegacyShaderMaterial(),this.scene),this.globalLegacyBuffer.setRenderOrigin(this.renderOrigin)),this.globalLegacyBuffer}getGlobalLegacyBlendShaderMaterial(){return this.globalLegacyBlendShaderMaterial||(this.globalLegacyBlendShaderMaterial=c6(),this.syncLegacyShaderUniforms()),this.globalLegacyBlendShaderMaterial}getGlobalLegacyBlendBuffer(){return this.globalLegacyBlendBuffer||(this.globalLegacyBlendBuffer=new nr(this.getGlobalLegacyBlendShaderMaterial(),this.scene,{name:"globalLegacyBlend",initialCapacityQuads:32e3,growthIncrementQuads:32e3}),this.globalLegacyBlendBuffer.setRenderOrigin(this.renderOrigin)),this.globalLegacyBlendBuffer}getRenderOrigin(){return this.renderOrigin}maybeRebase(e){let t=this.renderOrigin;if(Math.abs(e.x-t.x)<=Rt.REBASE_THRESHOLD&&Math.abs(e.y-t.y)<=Rt.REBASE_THRESHOLD&&Math.abs(e.z-t.z)<=Rt.REBASE_THRESHOLD)return;let r={x:Math.round(e.x/16)*16,y:Math.round(e.y/16)*16,z:Math.round(e.z/16)*16},i={x:r.x-t.x,y:r.y-t.y,z:r.z-t.z};this.globalLegacyBuffer?.rebase(i),this.globalLegacyBlendBuffer?.rebase(i);for(let s of this.activeSections.values()){let o=s.sectionKey;if(!o)continue;let l=this.sectionObjects[o];l&&H1(s.mesh,l.worldX??0,l.worldY??0,l.worldZ??0,r)}this.renderOrigin=r,this.globalLegacyBuffer?.setRenderOrigin(r),this.globalLegacyBlendBuffer?.setRenderOrigin(r)}sectionUsesPooledLegacyMesh(e){return this.activeSections.has(e)}registerLegacyCullSection(e,t,r,i){this.legacyCullSections.set(e,{worldX:t,worldY:r,worldZ:i})}maybeUnregisterLegacyCullSection(e){let t=this.globalLegacyBuffer?.hasSection(e)??!1,r=this.globalLegacyBlendBuffer?.hasSection(e)??!1;!t&&!r&&this.legacyCullSections.delete(e)}updatePooledLegacyCullState(e,t,r){for(let i of this.activeSections.values()){let s=i.sectionKey;if(!s)continue;let o=this.sectionObjects[s];o&&d6(i.mesh,o.worldX??0,o.worldY??0,o.worldZ??0,e,t,r,this._legacyCullFrustum,this._legacyCullBox,this._legacyCullBoxMin,this._legacyCullBoxMax)}}updateSectionCullAndSort(e,t,r,i){this._legacyCullProjScreen.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse),this._legacyCullFrustum.setFromProjectionMatrix(this._legacyCullProjScreen);let s=this._visibleSectionSpans;s.length=0;for(let[b]of this.legacyCullSections){let A=this.sectionObjects[b];if(!A?.visible||A.worldX===void 0)continue;let{visible:y,distSq:_}=Bi(A.worldX,A.worldY??0,A.worldZ??0,t,r,i,this._legacyCullFrustum,this._legacyCullBox,this._legacyCullBoxMin,this._legacyCullBoxMax);y&&s.push({key:b,distSq:_})}let o=this.globalLegacyBuffer,l=this.globalLegacyBlendBuffer,a=this.globalBlockBuffer,v=[];for(let b of s)o?.hasSection(b.key)&&v.push(b.key);v.sort();let c=s.filter(b=>l?.hasSection(b.key));c.sort((b,A)=>A.distSq-b.distSq);let u=c.map(b=>b.key),f=[],m=[];a&&a.forEachSectionSlot((b,A)=>{if(!this.sectionObjects[b]?.visible)return;let _=this.shaderSectionRaycastBoxes.get(b);if(!_)return;let{visible:S}=Bi(_.sectionCenterX,_.sectionCenterY,_.sectionCenterZ,t,r,i,this._legacyCullFrustum,this._legacyCullBox,this._legacyCullBoxMin,this._legacyCullBoxMax);if(!S)return;f.push(b);let C=a.getSectionDrawStart(b),T=a.getSectionDrawCount(b);C!==void 0&&T!==void 0&&m.push({start:C,count:T})}),f.sort();let g=[v.join(","),u.join(","),f.join(","),o?.getLayoutVersion()??0,l?.getLayoutVersion()??0,a?.getLayoutVersion()??0,o?.getUploadEpoch()??0,l?.getUploadEpoch()??0,a?.getUploadEpoch()??0].join("|");if(g===this._lastCullFingerprint&&!this.hasPendingBufferWork()){this.updatePooledLegacyCullState(t,r,i);return}if(this._lastCullFingerprint=g,o?.updateDrawSpans(s,"opaque"),l?.updateDrawSpans(s,"sortedBlend"),a){let b=y6(m,a.getHighWatermark(),a.canUseFullDrawShortcut(),(A,y)=>a.isRangeFullyUploaded(A,y),a.getPendingDirtyRanges());a.setVisibleSpans(b)}this.lastBufferStateKey=this.bufferStateKey(),this.updatePooledLegacyCullState(t,r,i)}bufferStateKey(){let e=this.globalBlockBuffer,t=this.globalLegacyBuffer,r=this.globalLegacyBlendBuffer;return[t?.getLayoutVersion()??0,t?.getUploadEpoch()??0,r?.getLayoutVersion()??0,r?.getUploadEpoch()??0,e?.getLayoutVersion()??0,e?.getUploadEpoch()??0].join("|")}markCullDirtyIfBufferStateChanged(){this.bufferStateKey()!==this.lastBufferStateKey&&this.markCullDirty()}markCullDirty(){this.cullDirty=!0}hasPendingBufferWork(){return[this.globalLegacyBuffer,this.globalLegacyBlendBuffer,this.globalBlockBuffer].some(t=>t!=null&&(t.hasPendingUploads()||t.hasPendingReplace()||t.getPendingMove()!=null))}updateCullDirtyFromCamera(e,t,r,i){if(e.getWorldQuaternion(this._cullViewQuat),!this._cullCamInitialized){this._lastCullCamPos.set(t,r,i),this._lastCullCamQuat.copy(this._cullViewQuat),this._cullCamInitialized=!0,this.cullDirty=!0;return}let s=this._lastCullCamPos.x!==t||this._lastCullCamPos.y!==r||this._lastCullCamPos.z!==i,o=this._lastCullCamQuat.x!==this._cullViewQuat.x||this._lastCullCamQuat.y!==this._cullViewQuat.y||this._lastCullCamQuat.z!==this._cullViewQuat.z||this._lastCullCamQuat.w!==this._cullViewQuat.w;(s||o)&&(this._lastCullCamPos.set(t,r,i),this._lastCullCamQuat.copy(this._cullViewQuat),this.markCullDirty())}clearCullDirty(){this.cullDirty=!1}setLegacyCameraOrigin(e,t,r){let i=this.renderOrigin;Mi(this.getLegacyShaderMaterial(),i,e,t,r),Mi(this.getGlobalLegacyShaderMaterial(),i,e,t,r),Mi(this.getGlobalLegacyBlendShaderMaterial(),i,e,t,r),this.globalLegacyBuffer?.setCameraOrigin(e,t,r),this.globalLegacyBlendBuffer?.setCameraOrigin(e,t,r);let s=this.cubeShaderMaterial;if(s){let{originDelta:o,cameraOriginFrac:l}=I0(i,e,t,r),a=wi(i),v=s.uniforms.u_originDelta;v?.value?.set&&v.value.set(o.x,o.y,o.z);let c=s.uniforms.u_cameraOriginFrac;c?.value?.set&&c.value.set(l.x,l.y,l.z);let u=s.uniforms.u_sectionOriginRel;u?.value?.set&&u.value.set(a.x,a.y,a.z)}}getCubeShaderMaterial(){if(!this.isShaderCubesGpuEnabled())return null;if(!this.cubeShaderMaterial){this.cubeShaderMaterial=yi(),this.syncCubeShaderUniforms();let e=this.worldRenderer.worldRendererConfig;R1(this.cubeShaderMaterial,e.shadingTheme,e.cardinalLight)}return this.cubeShaderMaterial}getGlobalBlockBuffer(){let e=this.getCubeShaderMaterial();return e?(this.globalBlockBuffer||(this.globalBlockBuffer=new Ii(e,this.scene)),this.globalBlockBuffer):null}shouldDeferLegacyOpaqueToPerSection(e){return this.shouldDeferShaderToPerSection(e)}shouldDeferShaderToPerSection(e){return this.worldRenderer.getModule("futuristicReveal")?.shouldDeferSectionGeometry?.(e)===!0}migrateDeferredShaderToGlobal(e){let t=this.sectionObjects[e];if(!t?.deferredShaderCubes)return;let{words:r,count:i}=t.deferredShaderCubes,s=t.worldX,o=t.worldY,l=t.worldZ;s!==void 0&&o!==void 0&&l!==void 0&&this.registerShaderSectionRaycastBox(e,r,i,s,o,l),this.getGlobalBlockBuffer()?.addSection(e,r,i),this.markCullDirty();let v=t.mesh===t.shaderMesh;t.shaderMesh&&(T1(t.shaderMesh),t.remove(t.shaderMesh),t.shaderMesh=void 0),delete t.deferredShaderCubes,v&&(t.mesh=void 0)}migrateDeferredLegacyToGlobal(e){let t=this.sectionObjects[e];if(t){if(t.deferredLegacyOpaque){let{positions:r,colors:i,skyLights:s,blockLights:o,uvs:l,indices:a}=t.deferredLegacyOpaque,v=t.worldX,c=t.worldY,u=t.worldZ;v!==void 0&&c!==void 0&&u!==void 0&&this.getGlobalLegacyBuffer().addSection(e,{positions:r,colors:i,skyLights:s,blockLights:o,uvs:l,indices:a},v,c,u)&&this.registerLegacyCullSection(e,v,c,u),delete t.deferredLegacyOpaque}if(t.deferredLegacyBlend){let{positions:r,colors:i,skyLights:s,blockLights:o,uvs:l,indices:a}=t.deferredLegacyBlend,v=t.worldX,c=t.worldY,u=t.worldZ;v!==void 0&&c!==void 0&&u!==void 0&&this.getGlobalLegacyBlendBuffer().addSection(e,{positions:r,colors:i,skyLights:s,blockLights:o,uvs:l,indices:a},v,c,u)&&this.registerLegacyCullSection(e,v,c,u),delete t.deferredLegacyBlend,t.hasBlendMesh=!1}if(!t.hasBlendMesh){let r=t.mesh===this.activeSections.get(e)?.mesh;this.releasePooledMesh(e),r&&(t.mesh=t.shaderMesh??void 0)}this.markCullDirty()}}registerShaderSectionRaycastBox(e,t,r,i,s,o){let l=S6(t,r,i,s,o);l?this.shaderSectionRaycastBoxes.set(e,{box:l,sectionCenterX:i,sectionCenterY:s,sectionCenterZ:o}):this.shaderSectionRaycastBoxes.delete(e)}unregisterShaderSectionRaycastBox(e){this.shaderSectionRaycastBoxes.delete(e)}uploadLegacyPooledMesh(e,t,r,i,s){let{mesh:o}=e,l=t;return this.updateGeometryAttribute(o.geometry,"position",l.positions,3),this.updateGeometryAttribute(o.geometry,"normal",l.normals,3),this.updateGeometryAttribute(o.geometry,"color",l.colors,3),this.updateGeometryAttribute(o.geometry,"a_skyLight",l.skyLights,1),this.updateGeometryAttribute(o.geometry,"a_blockLight",l.blockLights,1),this.updateGeometryAttribute(o.geometry,"uv",l.uvs,2),o.geometry.index=new J.BufferAttribute(l.indices,1),o.geometry.boundingBox=new J.Box3(new J.Vector3(-8,-8,-8),new J.Vector3(8,8,8)),o.geometry.boundingSphere=new J.Sphere(new J.Vector3(0,0,0),Math.sqrt(3*8**2)),H1(o,r,i,s,this.renderOrigin),o.visible=!1,o.name="mesh",e.lastUsedTime=performance.now(),o}acquirePooledSectionMesh(e){let t=this.activeSections.get(e);if(!t){if(t=this.acquireMesh(),!t)return null;this.activeSections.set(e,t),t.sectionKey=e}return t}updateSection(e,t){let r=t.positions.length>0,i=(t.blend?.positions.length??0)>0,s=r||i,o=t.shaderCubes,l=this.isShaderCubesGpuEnabled()&&(o?.count??0)>0,a=r&&this.shouldDeferLegacyOpaqueToPerSection(e),v=i&&this.shouldDeferLegacyOpaqueToPerSection(e),c=l&&this.shouldDeferShaderToPerSection(e),u=r&&!a,f=i&&!v,m=l&&!!o&&!c;if(!s&&!l)return this.releaseSection(e),null;let g=this.sectionObjects[e],b=g!=null;g&&this.cleanupSection(e,{forRemesh:!0}),b&&(m||this.globalBlockBuffer?.removeSection(e),u||this.globalLegacyBuffer?.removeSection(e),f||this.globalLegacyBlendBuffer?.removeSection(e),l&&o||this.unregisterShaderSectionRaycastBox(e),!u&&!f&&this.maybeUnregisterLegacyCullSection(e)),i||this.releasePooledMesh(e);let A,y,_,S=!1;if(r){let W={positions:t.positions,colors:t.colors,skyLights:t.skyLights,blockLights:t.blockLights,uvs:t.uvs,indices:t.indices};if(a){if(y={positions:new Float32Array(W.positions),colors:new Float32Array(W.colors),skyLights:new Float32Array(W.skyLights),blockLights:new Float32Array(W.blockLights),uvs:new Float32Array(W.uvs),indices:W.indices instanceof Uint32Array?new Uint32Array(W.indices):new Uint16Array(W.indices)},!i){let Q=this.acquirePooledSectionMesh(e);if(!Q)return null;A=this.uploadLegacyPooledMesh(Q,t,t.sx,t.sy,t.sz)}}else if(this.getGlobalLegacyBuffer().addSection(e,W,t.sx,t.sy,t.sz))this.registerLegacyCullSection(e,t.sx,t.sy,t.sz);else{let K=this.acquirePooledSectionMesh(e);if(!K)return null;A=this.uploadLegacyPooledMesh(K,t,t.sx,t.sy,t.sz)}}if(i&&t.blend){let W={positions:t.blend.positions,colors:t.blend.colors,skyLights:t.blend.skyLights,blockLights:t.blend.blockLights,uvs:t.blend.uvs,indices:t.blend.indices};if(v){_={positions:new Float32Array(W.positions),colors:new Float32Array(W.colors),skyLights:new Float32Array(W.skyLights),blockLights:new Float32Array(W.blockLights),uvs:new Float32Array(W.uvs),indices:W.indices instanceof Uint32Array?new Uint32Array(W.indices):new Uint16Array(W.indices)};let Q=this.acquirePooledSectionMesh(e);if(!Q)return null;let K=this.uploadLegacyPooledMesh(Q,t.blend,t.sx,t.sy,t.sz);A=A??K,S=!0}else if(this.getGlobalLegacyBlendBuffer().addSection(e,W,t.sx,t.sy,t.sz))this.registerLegacyCullSection(e,t.sx,t.sy,t.sz);else{let K=this.acquirePooledSectionMesh(e);if(!K)return null;let X=this.uploadLegacyPooledMesh(K,t.blend,t.sx,t.sy,t.sz);A=A??X,S=!0}}let C=l?this.getCubeShaderMaterial():null,T;l&&o&&(c&&C?(T=Si(o,C),T.visible=!0):this.getGlobalBlockBuffer()?.addSection(e,o.words,o.count)),g=new J.Group,A&&(g.add(A),g.mesh=A),T&&(g.add(T),g.shaderMesh=T,o&&(g.deferredShaderCubes={words:o.words,count:o.count}),g.mesh||(g.mesh=T)),y&&(g.deferredLegacyOpaque=y),_&&(g.deferredLegacyBlend=_),l&&o&&this.registerShaderSectionRaycastBox(e,o.words,o.count,t.sx,t.sy,t.sz);let P=0;r&&(P+=t.positions.length/3/4),i&&t.blend&&(P+=t.blend.positions.length/3/4),l&&o&&(P+=o.count),g.tilesCount=P,g.hasBlendMesh=S,g.blocksCount=t.blocksCount,g.worldX=t.sx,g.worldY=t.sy,g.worldZ=t.sz,g.sectionKey=e,g.name="chunk";try{if(Object.keys(t.signs).length>0){let W=new J.Group;W.name="signs";for(let[Q,{isWall:K,isHanging:X,rotation:ae}]of Object.entries(t.signs)){let oe=this.worldRenderer.blockEntities[Q];if(!oe)continue;let[ue,fe,me]=Q.split(","),ne=this.signHeadsRenderer.renderSign(new F1(+ue,+fe,+me),ae,K,X,Oi.simplify(oe));ne&&W.add(ne)}g.add(W),g.signsContainer=W}if(Object.keys(t.heads).length>0){let W=new J.Group;W.name="heads";for(let[Q,{isWall:K,rotation:X}]of Object.entries(t.heads)){let ae=this.worldRenderer.blockEntities[Q];if(!ae)continue;let[oe,ue,fe]=Q.split(","),me=this.signHeadsRenderer.renderHead(new F1(+oe,+ue,+fe),X,K,Oi.simplify(ae));me&&W.add(me)}g.add(W),g.headsContainer=W}if(Object.keys(t.banners).length>0){let W=new J.Group;W.name="banners",g.bannersContainer=W,g.add(W);for(let[Q,K]of Object.entries(t.banners)){let{isWall:X,rotation:ae,blockName:oe,blockLightNorm:ue=0,skyLightNorm:fe=1}=K,me=this.worldRenderer.blockEntities[Q];if(!me)continue;let[ne,Y,le]=Q.split(","),ge=L6(this.worldRenderer,oe,Oi.simplify(me));if(!ge)continue;let je=this.blockEntityLightRegistry.getSkyLevel(),xe=O6(new F1(+ne,+Y,+le),ae,X,ge,ue,fe,je);xe.bannerMaterial&&this.blockEntityLightRegistry.register({material:xe.bannerMaterial,blockLightNorm:ue,skyLightNorm:fe});let{x:ot,y:be,z:ct}=xe.position;this.worldRenderer.sceneOrigin.track(xe),xe.position.set(ot,be,ct),W.add(xe)}}}catch{}this.sectionObjects[e]=g,this.scene.add(g),g.matrixAutoUpdate=!1,this.worldRenderer.displayOptions?.inWorldRenderingConfig?.showChunkBorders&&this.updateBoxHelper(e,!0);let B=e.split(","),L=`${B[0]},${B[2]}`,V=!!this.worldRenderer.displayOptions?.inWorldRenderingConfig?._renderByChunks,z=!!this.worldRenderer.worldRendererConfig?.wasmMesher;if((V||z)&&!this.worldRenderer.finishedChunks[L]){g.visible=!1,g._waitingForChunkDisplay=!0;let W=this.waitingChunksToDisplay[L]??(this.waitingChunksToDisplay[L]=[]);W.includes(e)||W.push(e)}return this.markCullDirty(),g}finishChunkDisplay(e){if(!this.waitingChunksToDisplay[e]){this.tryRevealPending();return}if(this.isWasmGateActive()&&this.isBlockedByNearer(e,0)){this.pendingNearReveal.set(e,Date.now()),this.armNearRevealTimer(e),this.armExpectedGraceTimer(e),this.tryRevealPending();return}this.flushChunkDisplay(e),this.tryRevealPending()}flushChunkDisplay(e){let t=this.waitingChunksToDisplay[e];if(this.pendingNearReveal.delete(e),this.clearNearRevealTimer(e),this.clearExpectedGraceTimer(e),!!t){for(let r of t){let i=this.sectionObjects[r];i&&(i._waitingForChunkDisplay=!1,i.visible=!0)}delete this.waitingChunksToDisplay[e],this.markCullDirty()}}tryRevealPending(){if(this.pendingNearReveal.size===0)return;let e=Date.now();for(let[t,r]of[...this.pendingNearReveal])this.isBlockedByNearer(t,e-r)||this.flushChunkDisplay(t)}onChunkRemovedFromGate(e){this.pendingNearReveal.delete(e),this.clearNearRevealTimer(e),this.clearExpectedGraceTimer(e),delete this.waitingChunksToDisplay[e],this.tryRevealPending()}isWasmGateActive(){return!!this.worldRenderer.worldRendererConfig?.wasmMesher}isBlockedByNearer(e,t){let r=this.worldRenderer.viewerChunkPosition;if(!r)return!1;let i=e.split(",");if(i.length!==2)return!1;let s=Number(i[0]),o=Number(i[1]),l=Math.floor(r.x/16),a=Math.floor(r.z/16),v=(s>>4)-l,c=(o>>4)-a,u=v*v+c*c;if(u===0)return!1;let f=this.worldRenderer.finishedChunks,m=this.worldRenderer.loadedChunks,g=this.worldRenderer.viewDistance;if(t<Rt.EXPECTED_NEAR_GRACE_MS&&g>0){let A=g*g,y=Math.min(g,Math.ceil(Math.sqrt(Math.max(0,u-1))));for(let _=-y;_<=y;_++)for(let S=-y;S<=y;S++){let C=_*_+S*S;if(C>=u||C>A)continue;let T=l+_<<4,P=a+S<<4,B=`${T},${P}`;if(B!==e&&m[B]&&!f[B])return!0}return!1}for(let A in m){if(A===e||f[A])continue;let y=A.split(",");if(y.length!==2)continue;let _=(Number(y[0])>>4)-l,S=(Number(y[1])>>4)-a;if(_*_+S*S<u)return!0}return!1}armNearRevealTimer(e){if(this.nearRevealTimers.has(e))return;let t=setTimeout(()=>{this.nearRevealTimers.delete(e),this.pendingNearReveal.has(e)&&(this.flushChunkDisplay(e),this.tryRevealPending())},Rt.NEAR_REVEAL_TIMEOUT_MS);this.nearRevealTimers.set(e,t)}clearNearRevealTimer(e){let t=this.nearRevealTimers.get(e);t&&(clearTimeout(t),this.nearRevealTimers.delete(e))}armExpectedGraceTimer(e){if(this.nearRevealGraceTimers.has(e))return;let t=setTimeout(()=>{this.nearRevealGraceTimers.delete(e),this.pendingNearReveal.has(e)&&this.tryRevealPending()},Rt.EXPECTED_NEAR_GRACE_MS+50);this.nearRevealGraceTimers.set(e,t)}clearExpectedGraceTimer(e){let t=this.nearRevealGraceTimers.get(e);t&&(clearTimeout(t),this.nearRevealGraceTimers.delete(e))}cleanupSection(e,t){let r=this.sectionObjects[e];if(r){if(r._waitingForChunkDisplay){let i=e.split(","),s=`${i[0]},${i[2]}`,o=this.waitingChunksToDisplay[s];if(o){let l=o.indexOf(e);l!==-1&&o.splice(l,1),o.length===0&&delete this.waitingChunksToDisplay[s]}}if(r.bannersContainer){for(let i of r.bannersContainer.children){let s=i;s.bannerMaterial&&this.blockEntityLightRegistry.unregister(s.bannerMaterial),s.bannerTexture&&H6(s.bannerTexture)}this.disposeContainer(r.bannersContainer)}if(t?.forRemesh||(this.globalBlockBuffer?.removeSection(e),this.globalLegacyBuffer?.removeSection(e),this.globalLegacyBlendBuffer?.removeSection(e),this.maybeUnregisterLegacyCullSection(e),this.unregisterShaderSectionRaycastBox(e)),this.markCullDirty(),delete r.deferredLegacyOpaque,delete r.deferredLegacyBlend,r.shaderMesh&&(T1(r.shaderMesh),r.shaderMesh=void 0),delete r.deferredShaderCubes,r.signsContainer){for(let i of r.signsContainer.children){let s=i;s.signTexture&&F6(s.signTexture)}this.disposeContainer(r.signsContainer,!1)}if(r.headsContainer&&this.disposeContainer(r.headsContainer),this.worldRenderer.sceneOrigin.removeAndUntrackAll(r),this.scene.remove(r),r.boxHelper){this.worldRenderer.sceneOrigin.removeAndUntrack(r.boxHelper),this.scene.remove(r.boxHelper),r.boxHelper.geometry.dispose();let i=r.boxHelper.material;if(Array.isArray(i))for(let s of i)s.dispose();else i.dispose();r.boxHelper=void 0}delete this.sectionObjects[e],t?.forRemesh||this.worldRenderer.getModule("futuristicReveal")?.onSectionRemoved?.(e)}}releasePooledMesh(e){let t=this.activeSections.get(e);t&&(t.mesh.visible=!1,t.inUse=!1,t.sectionKey=void 0,t.lastUsedTime=0,this.clearGeometry(t.mesh.geometry),this.activeSections.delete(e),this.cleanupExcessMeshes())}releaseSection(e){this.cleanupSection(e);let t=this.activeSections.get(e);return t?(t.mesh.visible=!1,t.inUse=!1,t.sectionKey=void 0,t.lastUsedTime=0,this.clearGeometry(t.mesh.geometry),this.activeSections.delete(e),this.cleanupExcessMeshes(),!0):!1}getSectionObject(e){return this.sectionObjects[e]}updateBoxHelper(e,t,r=this.chunkBoxMaterial){let i=this.sectionObjects[e];if(i)if(t){if(!i.boxHelper){let s=new J.Mesh(new J.BoxGeometry(16,16,16),r),o=new J.BoxHelper(s,16776960);o.name="helper";let l=i.worldX??0,a=i.worldY??0,v=i.worldZ??0;this.worldRenderer.sceneOrigin.track(o,{updateMatrix:!0}),o.position.set(l,a,v),o.updateMatrix(),this.scene.add(o),i.boxHelper=o}i.boxHelper.visible=!0}else i.boxHelper&&(i.boxHelper.visible=!1)}updateAllBoxHelpers(e){for(let t of Object.keys(this.sectionObjects))this.updateBoxHelper(t,e)}getSectionMesh(e){return this.activeSections.get(e)?.mesh}hasSection(e){return this.activeSections.has(e)}updateViewDistance(e){let t=(e*2+1)**2,r=this.worldHeight/16,i=5;if(this.minPoolSize=Math.floor(t*i),this.maxPoolSize=Math.floor(t*r)+1,this.poolSize??(this.poolSize=this.minPoolSize),this.minPoolSize>this.poolSize){let s=Math.min(this.minPoolSize,this.maxPoolSize);this.expandPool(s)}}getGlobalBufferStats(){let e=r=>r?{used:r.getHighWatermark(),capacity:r.getCapacityQuads(),sections:r.getSectionCount(),usedBytes:r.getUsedMemoryBytes(),capacityBytes:r.getMemoryBytes()}:null,t=this.globalBlockBuffer;return{shaderFaces:t?{used:t.getHighWatermark(),capacity:t.getCapacityFaces(),sections:t.getSectionCount(),usedBytes:t.getUsedMemoryBytes(),capacityBytes:t.getMemoryBytes()}:null,legacyOpaque:e(this.globalLegacyBuffer),legacyBlend:e(this.globalLegacyBlendBuffer)}}getStats(){let e=this.meshPool.filter(i=>!i.inUse).length,t=this.hits+this.misses>0?(this.hits/(this.hits+this.misses)*100).toFixed(1):"0",r=this.getEstimatedMemoryUsage();return{poolSize:this.poolSize,activeCount:this.activeSections.size,freeCount:e,hitRate:`${t}%`,hits:this.hits,misses:this.misses,memoryUsage:r}}getTotalTiles(){return Object.values(this.sectionObjects).reduce((e,t)=>e+(t.tilesCount||0),0)}getTotalBlocks(){return Object.values(this.sectionObjects).reduce((e,t)=>e+(t.blocksCount||0),0)}getEstimatedMemoryUsage(){let e=0,t=0,r=0,i=0,s=0,o=0,l=0,a=this.globalBlockBuffer?.mesh.geometry;if(a)for(let f of["a_w0","a_w1","a_w2","a_w3"]){let m=a.getAttribute(f);if(m){let g=m.array.byteLength;l+=g,e+=g}}let v=this.globalLegacyBuffer?.getMemoryBytes()??0,c=this.globalLegacyBlendBuffer?.getMemoryBytes()??0;e+=v+c,t+=v+c;for(let f of Object.values(this.sectionObjects)){let m=f.shaderMesh?.geometry;if(m)for(let g of["a_w0","a_w1","a_w2","a_w3"]){let b=m.getAttribute(g);if(b){let A=b.array.byteLength;l+=A,e+=A}}}for(let f of this.meshPool)if(f.inUse&&f.mesh.geometry){let{geometry:m}=f.mesh,g=m.getAttribute("position");if(g){let _=g.array.byteLength;t+=_,e+=_}let b=m.getAttribute("normal");if(b){let _=b.array.byteLength;r+=_,e+=_}let A=m.getAttribute("color");if(A){let _=A.array.byteLength;i+=_,e+=_}let y=m.getAttribute("uv");if(y){let _=y.array.byteLength;s+=_,e+=_}if(m.index){let _=m.index.array.byteLength;o+=_,e+=_}}return{total:`${(e/(1024*1024)).toFixed(2)} MB`,breakdown:{position:`${(t/(1024*1024)).toFixed(2)} MB`,normal:`${(r/(1024*1024)).toFixed(2)} MB`,color:`${(i/(1024*1024)).toFixed(2)} MB`,uv:`${(s/(1024*1024)).toFixed(2)} MB`,index:`${(o/(1024*1024)).toFixed(2)} MB`,shaderInstances:`${(l/(1024*1024)).toFixed(2)} MB`}}}dispose(){let e=[...this.activeSections.keys()];for(let t of e)this.releaseSection(t);this.signHeadsRenderer.dispose();for(let t of this.meshPool)t.mesh.geometry.dispose();this.meshPool.length=0,this.activeSections.clear(),this.chunkBoxMaterial.dispose(),this.shaderSectionRaycastBoxes.clear(),this.lastBufferStateKey="",this.globalBlockBuffer?.dispose(),this.globalBlockBuffer=null,this.globalLegacyBuffer?.dispose(),this.globalLegacyBuffer=null,this.globalLegacyBlendBuffer?.dispose(),this.globalLegacyBlendBuffer=null,this.cubeShaderMaterial?.dispose(),this.cubeShaderMaterial=null,this.legacyShaderMaterial?.dispose(),this.legacyShaderMaterial=null,this.globalLegacyShaderMaterial?.dispose(),this.globalLegacyShaderMaterial=null,this.globalLegacyBlendShaderMaterial?.dispose(),this.globalLegacyBlendShaderMaterial=null,this.pendingNearReveal.clear();for(let t of this.nearRevealTimers.values())clearTimeout(t);this.nearRevealTimers.clear();for(let t of this.nearRevealGraceTimers.values())clearTimeout(t);this.nearRevealGraceTimers.clear()}acquireMesh(){if(this.bypassPooling){let t={mesh:new J.Mesh(new J.BufferGeometry,this.getLegacyShaderMaterial()),inUse:!0,lastUsedTime:performance.now()};return this.meshPool.push(t),this.poolSize++,t}for(let t of this.meshPool)if(!t.inUse)return t.inUse=!0,t.lastUsedTime=performance.now(),this.hits++,t;this.misses++;let e=Math.min(this.poolSize+16,this.maxPoolSize);e<=this.meshPool.length&&(e=this.meshPool.length+8,this.maxPoolSize=e),this.expandPool(e);for(let t=this.meshPool.length-1;t>=0;t--){let r=this.meshPool[t];if(!r.inUse)return r.inUse=!0,r.lastUsedTime=performance.now(),r}throw new Error("ChunkMeshManager: Failed to acquire mesh after pool expansion")}expandPool(e){let t=this.meshPool.length;this.poolSize=e;for(let r=t;r<e;r++){let i=new J.BufferGeometry,s=new J.Mesh(i,this.getLegacyShaderMaterial());s.visible=!1,s.matrixAutoUpdate=!1,s.name="pooled-section-mesh";let o={mesh:s,inUse:!1,lastUsedTime:0};this.meshPool.push(o)}}updateGeometryAttribute(e,t,r,i){let s=e.getAttribute(t);s&&s.count===r.length/i?(s.array.set(r),s.needsUpdate=!0):e.setAttribute(t,new J.BufferAttribute(r,i))}clearGeometry(e){let t=["position","normal","color","a_skyLight","a_blockLight","uv"];for(let r of t)e.hasAttribute(r)&&e.deleteAttribute(r);e.index&&e.setIndex(null),e.boundingBox=null,e.boundingSphere=null}cleanupExcessMeshes(){if(this.poolSize>this.maxPoolSize){let e=this.meshPool.filter(t=>!t.inUse).length;if(e>0){let t=Math.min(this.poolSize-this.maxPoolSize,e);for(let r=0;r<t;r++){let i=this.meshPool.findIndex(s=>!s.inUse);i!==-1&&(this.meshPool[i].mesh.geometry.dispose(),this.meshPool.splice(i,1),this.poolSize--)}}}}disposeContainer(e,t=!0){Se(e,t)}recordRenderTime(e){this.renderTimes.push(e),this.renderTimes.length>this.maxRenderTimeSamples&&this.renderTimes.shift();let t=performance.now();t-this.lastPerformanceCheck>this.performanceCheckInterval&&(this.checkPerformance(),this.lastPerformanceCheck=t)}getEffectiveRenderDistance(){return this.performanceOverrideDistance||this.worldRenderer.viewDistance}resetPerformanceOverride(){this.performanceOverrideDistance=void 0,this.renderTimes.length=0}getAverageRenderTime(){return this.renderTimes.length===0?0:this.renderTimes.reduce((e,t)=>e+t,0)/this.renderTimes.length}checkPerformance(){if(this.renderTimes.length<this.maxRenderTimeSamples)return;let e=this.getAverageRenderTime(),t=16.67,r=t*1.5;if(e>r){let i=this.worldRenderer.viewDistance,s=Math.max(1,Math.floor(i*.8));(!this.performanceOverrideDistance||s<this.performanceOverrideDistance)&&(this.performanceOverrideDistance=s)}else if(this.performanceOverrideDistance&&e<t*1.1){let i=this.worldRenderer.viewDistance,s=Math.min(i,this.performanceOverrideDistance+1);s!==this.performanceOverrideDistance&&(this.performanceOverrideDistance=s>=i?void 0:s)}}updateSectionsVisibility(){let e=this.worldRenderer.cameraSectionPos;for(let[t,r]of Object.entries(this.sectionObjects)){if(r._waitingForChunkDisplay){r.visible=!1;continue}if(!this.performanceOverrideDistance){r.visible=!0;continue}let[i,s,o]=t.split(",").map(Number),l={x:i/16,y:s/16,z:o/16},a=l.x-e.x,v=l.z-e.z,c=Math.floor(Math.hypot(a,v));r.visible=c<=this.performanceOverrideDistance}}};d(Rt,"REBASE_THRESHOLD",65536),d(Rt,"NEAR_REVEAL_TIMEOUT_MS",5e3),d(Rt,"EXPECTED_NEAR_GRACE_MS",1500);var ar=Rt,z1=class{constructor(e){this.worldRendererThree=e}dispose(){z6()}renderHead(e,t,r,i){let s;if(i.SkullOwner?s=i.SkullOwner.Properties?.textures?.[0]?.Value:s=i.profile?.properties?.find(o=>o.name==="textures")?.value,!!s)try{let l=JSON.parse(O.from(s,"base64").toString()).textures?.SKIN?.url,{skinTexturesProxy:a}=this.worldRendererThree.worldRendererConfig;a&&(l=l?.replace("http://textures.minecraft.net/",a).replace("https://textures.minecraft.net/",a));let v=Kt(this.worldRendererThree,l,Jt.head),c=new J.Group;return r&&v.position.set(0,.3125,.3125),v.position.y-=23/16,c.add(v),this.worldRendererThree.sceneOrigin.track(c),c.position.set(e.x+.5,e.y+.045,e.z+.5),c.rotation.set(0,-J.MathUtils.degToRad(t*(r?90:45/2)),0),c.scale.set(.8,.8,.8),c}catch{}}renderSign(e,t,r,i,s){let o=D6(this.worldRendererThree,s,i);if(!o)return;let l=new J.Mesh(new J.PlaneGeometry(1,1),new J.MeshBasicMaterial({map:o,transparent:!0}));l.renderOrder=999;let a=7/16,v=i?1.3:1;l.scale.set(1*v,a*v,1*v);let c=(i?2:1.5)/16,u=.25/16;r&&!i?l.position.set(0,0,-.5+c+u+1e-4):l.position.set(0,0,c/2+1e-4);let f=new J.Group;f.rotation.set(0,-J.MathUtils.degToRad(t*(r?90:45/2)),0),f.add(l),f.signTexture=o;let m=(i?10:8)/16,g=(i?0:r?4.333:9.333)/16,b=m/2+g;return this.worldRendererThree.sceneOrigin.track(f),f.position.set(e.x+.5,e.y+b,e.z+.5),f}};E();x();R();k();var Di=(n,e)=>e===0?1/0:e<0?Di(-n,-e):(1-(n-Math.floor(n)))/e,L9=(n,e,t,r,i,s,o,l,a,v,c,u)=>{let f=o-c,m=l-c,g=a-c,b=o+1+c,A=l+1+c,y=a+1+c,_=M6(n,e,t,r,i,s,f,m,g,b,A,y,v);if(_===void 0&&(_=T6(n,e,t,r,i,s,f,m,g,b,A,y,v)),_!==void 0)return Math.max(u,_)};function U6(n,e,t,r,i,s,o,l,a,v){if(o<=0)return;let c=Math.floor(n),u=Math.floor(e),f=Math.floor(t),m=r>0?1:r<0?-1:0,g=i>0?1:i<0?-1:0,b=s>0?1:s<0?-1:0,A=m!==0?Math.abs(1/r):1/0,y=g!==0?Math.abs(1/i):1/0,_=b!==0?Math.abs(1/s):1/0,S=m!==0?Di(n,r):1/0,C=g!==0?Di(e,i):1/0,T=b!==0?Di(t,s):1/0,P=(V,z,W)=>{if(!v(V,z,W))return;let Q=L9(n,e,t,r,i,s,V,z,W,o,l,a);if(!(Q===void 0||Q>o))return{distance:Q,blockX:V,blockY:z,blockZ:W}},B=P(c,u,f);if(B)return B;let L=0;for(;L<=o&&(S<C?S<T?(c+=m,L=S,S+=A):(f+=b,L=T,T+=_):C<T?(u+=g,L=C,C+=y):(f+=b,L=T,T+=_),!(L>o));)if(B=P(c,u,f),B)return B}E();x();R();k();E();x();R();k();import*as e0 from"three";var Fi={},G6=!1;function H9(){if(G6)return;let n=globalThis.loadedData?.tints;if(n){for(let e of Object.keys(n))Fi[e]=O9(n[e]);G6=!0}}function O9(n){let e={},t=V6(n.default??16777215);if(n.data)for(let r of n.data){let i=V6(r.color);for(let s of r.keys)e[s]=i}return new Proxy(e,{get(r,i){return r[i]??t}})}function V6(n){return[(n>>16&255)/255,(n>>8&255)/255,(n&255)/255]}function W6(n,e){return H9(),n==="grass_block"?[1,1,1]:n==="redstone_wire"?[1,1,1]:n==="birch_leaves"||n==="spruce_leaves"||n==="lily_pad"?Fi.constant?.[n]??[1,1,1]:n.includes("leaves")||n==="vine"?Fi.foliage?.[e]??[1,1,1]:["short_grass","tall_grass","fern","large_fern","sugar_cane","grass"].includes(n)?Fi.grass?.[e]??[1,1,1]:[1,1,1]}var D9=512,U1=1/20,G1=class{constructor(e){this.worldRenderer=e;d(this,"particles",[]);d(this,"sharedMaterial");d(this,"enabled",!1);d(this,"tickAccumulator",0);d(this,"nextParticleIndex",0);d(this,"render",e=>{if(!this.enabled)return;for(this.tickAccumulator+=e;this.tickAccumulator>=U1;)this.tickAccumulator-=U1,this.tickPhysics();let t=this.tickAccumulator/U1;this.updateVisuals(t)})}enable(){this.enabled||(this.enabled=!0,this.ensureMaterial())}disable(){this.enabled&&(this.enabled=!1)}dispose(){for(let e of this.particles)e.active&&this.worldRenderer.sceneOrigin.removeAndUntrack(e.mesh),e.mesh.geometry.dispose();this.particles=[],this.sharedMaterial?.dispose(),this.sharedMaterial=void 0,this.nextParticleIndex=0}spawnBlockBreakParticles(e,t,r,i,s,o="plains"){if(!this.enabled)return;let l=this.resolveBlockTexture(i);if(!l)return;let a=W6(i,o);for(let v=0;v<4;v++)for(let c=0;c<4;c++)for(let u=0;u<4;u++){let f=e+(v+.5)/4,m=t+(c+.5)/4,g=r+(u+.5)/4,b=f-e-.5,A=m-t-.5,y=g-r-.5;b+=(Math.random()*2-1)*.4,A+=(Math.random()*2-1)*.4,y+=(Math.random()*2-1)*.4;let _=(Math.random()+Math.random()+1)*.15,S=Math.sqrt(b*b+A*A+y*y),C=b/S*_*.4,T=A/S*_*.4+.1,P=y/S*_*.4,B=Math.floor(4/(Math.random()*.9+.1));this.createParticle(f,m,g,C,T,P,B,l,s,e,r,1,a)}}tickPhysics(){for(let e of this.particles){if(!e.active)continue;if(e.prevX=e.x,e.prevY=e.y,e.prevZ=e.z,e.age++,e.age>=e.maxAge){this.deactivateParticle(e);continue}e.yd-=.04,e.x+=e.xd,e.y+=e.yd,e.z+=e.zd;let t=this.getFloorY(e);e.y<=t?(e.y=t,e.yd=0,e.onGround=!0):e.onGround=!1,e.xd*=.98,e.yd*=.98,e.zd*=.98,e.onGround&&(e.xd*=.7,e.zd*=.7)}}updateVisuals(e){let t=this.worldRenderer.camera.position;for(let r of this.particles){if(!r.active)continue;let i=r.prevX+(r.x-r.prevX)*e,s=r.prevY+(r.y-r.prevY)*e,o=r.prevZ+(r.z-r.prevZ)*e;r.mesh.position.set(i,s,o),r.mesh.lookAt(t.x,t.y,t.z)}}spawnCrackParticle(e,t,r,i,s,o,l="plains"){if(!this.enabled)return;let a=this.resolveBlockTexture(s);if(!a)return;let v=W6(s,l),c=e+Math.random()*.8+.1,u=t+Math.random()*.8+.1,f=r+Math.random()*.8+.1;switch(i){case 0:u=t-.1;break;case 1:u=t+1+.1;break;case 2:f=r-.1;break;case 3:f=r+1+.1;break;case 4:c=e-.1;break;case 5:c=e+1+.1;break}let m=(Math.random()*2-1)*.4*.2,g=(Math.random()*2-1)*.4*.2+.1*.2,b=(Math.random()*2-1)*.4*.2,A=Math.floor(4/(Math.random()*.9+.1));this.createParticle(c,u,f,m,g,b,A,a,o,e,r,.6,v)}createParticle(e,t,r,i,s,o,l,a,v,c,u,f=1,m=[1,1,1]){this.ensureMaterial();let g=this.findInactiveParticle();g||(this.particles.length<D9?g=this.allocateParticle():g=this.recycleOldest());let b=Math.floor(Math.random()*4),A=Math.floor(Math.random()*4),y=a.u+b/4*a.su,_=a.v+A/4*a.sv,S=a.su/4,C=a.sv/4;this.setGeometryUVs(g.mesh.geometry,y,_,S,C),g.active=!0,g.x=e,g.y=t,g.z=r,g.prevX=e,g.prevY=t,g.prevZ=r,g.xd=i,g.yd=s,g.zd=o,g.age=0,g.maxAge=l,g.onGround=!1,g.floorMap=v,g.blockX=Math.floor(c),g.blockZ=Math.floor(u);let T=.1*(.5+Math.random()*.5)*2*f;g.mesh.scale.set(T,T,T),g.mesh.position.set(e,t,r),g.mesh.visible=!0;let P=.6*m[0],B=.6*m[1],L=.6*m[2],V=new Float32Array([P,B,L,P,B,L,P,B,L,P,B,L]),z=g.mesh.geometry.getAttribute("color");z?(z.set(V),z.needsUpdate=!0):g.mesh.geometry.setAttribute("color",new e0.Float32BufferAttribute(V,3)),this.worldRenderer.sceneOrigin.addAndTrack(g.mesh)}allocateParticle(){let e=new e0.PlaneGeometry(1,1),t=new e0.Mesh(e,this.sharedMaterial);t.visible=!1;let r={mesh:t,active:!1,x:0,y:0,z:0,prevX:0,prevY:0,prevZ:0,xd:0,yd:0,zd:0,age:0,maxAge:0,onGround:!1,floorMap:[],blockX:0,blockZ:0};return this.particles.push(r),r}findInactiveParticle(){for(let e=0;e<this.particles.length;e++){let t=(this.nextParticleIndex+e)%this.particles.length;if(!this.particles[t].active)return this.nextParticleIndex=(t+1)%this.particles.length,this.particles[t]}}recycleOldest(){let e=this.particles[0];for(let t of this.particles)t.age>e.age&&(e=t);return this.deactivateParticle(e),e}deactivateParticle(e){e.active&&(e.active=!1,e.mesh.visible=!1,this.worldRenderer.sceneOrigin.removeAndUntrack(e.mesh))}getFloorY(e){let t=Math.floor(e.x)-e.blockX,r=Math.floor(e.z)-e.blockZ;return t=Math.max(-2,Math.min(2,t)),r=Math.max(-2,Math.min(2,r)),e.floorMap[(r+2)*5+(t+2)]}resolveBlockTexture(e){let t=this.worldRenderer.resourcesManager.currentResources;if(!t)return null;let r=t.blocksAtlasJson,i=r.textures;if(i[e])return this.extractUV(i[e],r);for(let s of["_side","_top","_front","_0",""]){let o=e+s;if(i[o])return this.extractUV(i[o],r)}for(let s of Object.keys(i))if(s.startsWith(e))return this.extractUV(i[s],r);return null}extractUV(e,t){return{u:e.u,v:e.v,su:e.su??t.suSv,sv:e.sv??t.suSv}}setGeometryUVs(e,t,r,i,s){let o=e.getAttribute("uv");o.setXY(0,t,r),o.setXY(1,t+i,r),o.setXY(2,t,r+s),o.setXY(3,t+i,r+s),o.needsUpdate=!0}ensureMaterial(){if(this.sharedMaterial)return;let e=this.worldRenderer.material.map;e&&(this.sharedMaterial=new e0.MeshBasicMaterial({map:e,vertexColors:!0,transparent:!0,alphaTest:.1}))}},N6={id:"blockBreakParticles",controller:G1,enabledDefault:!0,cannotBeDisabled:!0,requiresHeightmap:!1};E();x();R();k();var V1=class{constructor(e){this.worldRenderer=e;d(this,"enabled",!1);d(this,"lastBobWalkDist",0);d(this,"lastBobTickTime",0);d(this,"render",()=>{if(!this.enabled)return;let e=this.worldRenderer.displayOptions.inWorldRenderingConfig,{perspective:t}=this.worldRenderer.playerStateReactive;if(e.viewBobbing&&t==="first_person"&&!this.worldRenderer.playerStateUtils.isSpectator()){this.worldRenderer.playerStateReactive.walkDist!==this.lastBobWalkDist&&(this.lastBobTickTime=performance.now(),this.lastBobWalkDist=this.worldRenderer.playerStateReactive.walkDist);let i=Math.min((performance.now()-this.lastBobTickTime)/50,1);this.worldRenderer.cameraShake.setCameraBobInput({walkDist:this.worldRenderer.playerStateReactive.walkDist,prevWalkDist:this.worldRenderer.playerStateReactive.prevWalkDist,bob:this.worldRenderer.playerStateReactive.bob,prevBob:this.worldRenderer.playerStateReactive.prevBob,partialTick:i})}else this.worldRenderer.cameraShake.setCameraBobInput(null)})}enable(){this.enabled=!0}disable(){this.enabled=!1,this.worldRenderer.cameraShake.setCameraBobInput(null);let{perspective:e}=this.worldRenderer.playerStateReactive;e==="first_person"&&this.worldRenderer.camera.position.set(0,0,0)}dispose(){this.disable()}},j6={id:"cameraBobbing",controller:V1,enabledDefault:!0,cannotBeDisabled:!0};E();x();R();k();import*as it from"three";var W1=2e3,Q6=32,Y6=32,zi=12,q6=24,Ui=1.2,F9=-5,N1=class{constructor(e){this.worldRenderer=e;d(this,"instancedMesh");d(this,"geometry");d(this,"material");d(this,"particles",[]);d(this,"enabled",!1);d(this,"dummy",new it.Matrix4);d(this,"tempPosition",new it.Vector3);d(this,"tempQuaternion",new it.Quaternion);d(this,"tempScale",new it.Vector3);d(this,"configUnsubs",[]);d(this,"render",e=>{if(!this.enabled||!this.instancedMesh||!this.material)return;let t=this.worldRenderer.getCameraPosition();this.instancedMesh.position.set(0,0,0);let r=this.worldRenderer.reactiveState.world.heightmaps,{dummy:i,tempPosition:s,tempQuaternion:o,tempScale:l}=this,a=NaN,v=NaN,c;for(let u=0;u<W1;u++){let f=this.particles[u];this.instancedMesh.getMatrixAt(u,i),i.decompose(s,o,l),s.addScaledVector(f.velocity,e);let m=s.y,g=Math.sqrt(s.x*s.x+s.z*s.z),b=t.x+s.x,A=t.y+s.y,y=t.z+s.z,_=Math.floor(b/16),S=Math.floor(y/16);(_!==a||S!==v)&&(c=r[`${_},${S}`],a=_,v=S);let C=(Math.floor(b)%16+16)%16,T=(Math.floor(y)%16+16)%16,P=c?.[T*16+C];if(g>Q6||P!==void 0&&P!==-32768&&A<=P+1+f.despawnOffset||m<F9){this.respawnParticle(s);let L=zi+Math.random()*(q6-zi);f.velocity.set((Math.random()-.5)*Ui,-L,(Math.random()-.5)*Ui),f.despawnOffset=Math.random()*.5}i.compose(s,o,l),this.instancedMesh.setMatrixAt(u,i)}this.instancedMesh.instanceMatrix.needsUpdate=!0});this.configUnsubs.push(this.worldRenderer.onReactiveConfigUpdated("rainColor",()=>this.syncRainAppearance()),this.worldRenderer.onReactiveConfigUpdated("rainOpacity",()=>this.syncRainAppearance()))}enable(){this.enabled||(this.enabled=!0,this.instancedMesh?(this.instancedMesh.visible=!0,this.syncRainAppearance()):this.createRain())}disable(){this.enabled&&(this.enabled=!1,this.instancedMesh&&(this.instancedMesh.visible=!1))}autoEnableCheck(){return this.worldRenderer.worldRendererConfig.isRaining===!0}dispose(){for(let e of this.configUnsubs)e();this.configUnsubs.length=0,this.instancedMesh&&this.worldRenderer.scene.remove(this.instancedMesh),this.geometry?.dispose(),this.material?.dispose(),this.instancedMesh=void 0,this.geometry=void 0,this.material=void 0,this.particles=[]}syncRainAppearance(){if(!this.material)return;let{rainColor:e,rainOpacity:t}=this.worldRenderer.worldRendererConfig;this.material.color.set(e),this.material.opacity=Math.max(0,Math.min(1,t)),this.material.needsUpdate=!0}createRain(){let{rainColor:e,rainOpacity:t}=this.worldRenderer.worldRendererConfig;this.geometry=new it.BoxGeometry(.03,.3,.03),this.material=new it.MeshBasicMaterial({color:e,transparent:!0,opacity:Math.max(0,Math.min(1,t)),depthWrite:!0,fog:!1}),this.instancedMesh=new it.InstancedMesh(this.geometry,this.material,W1),this.instancedMesh.name="rain-particles",this.instancedMesh.frustumCulled=!1;let r=new it.Matrix4,i=new it.Vector3;for(let s=0;s<W1;s++){this.respawnParticle(i),i.y=Math.random()*Y6,r.setPosition(i),this.instancedMesh.setMatrixAt(s,r);let o=zi+Math.random()*(q6-zi);this.particles.push({velocity:new it.Vector3((Math.random()-.5)*Ui,-o,(Math.random()-.5)*Ui),age:0,despawnOffset:Math.random()*.5})}this.instancedMesh.instanceMatrix.needsUpdate=!0,this.worldRenderer.scene.add(this.instancedMesh)}respawnParticle(e){let t=Math.random()*Math.PI*2,r=Math.random()*Q6;e.set(Math.cos(t)*r,Y6,Math.sin(t)*r)}},K6={id:"rain",controller:N1,enabledDefault:!1,requiresHeightmap:!0};E();x();R();k();import*as Te from"three";var J6=new Te.Color(13/255,234/255,238/255),z9=9,U9=12e3,G9=1500,V9=1e4,W9=350,N9=650,X6=120,Z6=280,j1=class{constructor(e){this.worldRenderer=e;d(this,"enabled",!0);d(this,"sections",new Map);d(this,"completed",new Set);d(this,"globalWaveStarted",!1);d(this,"globalWaveStartMs",0);d(this,"finishedChunkCount",0);d(this,"firstQueuedMs",null);d(this,"pulseTime",0);d(this,"wireframeMaterial",new Te.LineBasicMaterial({color:J6,transparent:!0,opacity:1,blending:Te.AdditiveBlending,depthWrite:!1}));d(this,"wireframeGlowMaterial",new Te.LineBasicMaterial({color:J6,transparent:!0,opacity:.55,blending:Te.AdditiveBlending,depthWrite:!1}));e.worldRendererConfig.futuristicReveal!==!0&&(this.enabled=!1)}autoEnableCheck(){return this.worldRenderer.worldRendererConfig.futuristicReveal===!0}enable(){this.autoEnableCheck()&&this.setEnabled(!0)}disable(){this.setEnabled(!1)}dispose(){this.reset(),this.wireframeMaterial.dispose(),this.wireframeGlowMaterial.dispose()}shouldDeferSectionGeometry(e){return this.enabled&&!this.completed.has(e)}onSectionMeshed(e,t,r){let i=r.children.find(s=>s.name==="mesh");i instanceof Te.Mesh&&this.onSectionMeshedMesh(e,t,i)}onChunkFinished(){this.enabled&&(this.finishedChunkCount++,this.tryStartGlobalWave(performance.now()))}onSectionRemoved(e){this.cancelSection(e,!0),this.completed.delete(e)}onWorldSwitched(){this.reset()}tick(e,t=performance.now()){if(!this.enabled||(this.tryStartGlobalWave(t),!this.globalWaveStarted&&this.firstQueuedMs!==null&&this.sections.size>0&&t-this.firstQueuedMs>=U9&&this.startGlobalWave(t),this.sections.size===0))return;this.pulseTime+=e*.001;let r=[];for(let i of this.sections.values()){if(t-i.phaseStartMs>V9){r.push(i);continue}if(i.phase==="queued"){this.globalWaveStarted&&t>=i.revealAtMs&&this.beginWireframe(i,t);continue}let s=t-i.phaseStartMs;if(i.phase==="wireframe"){this.animateWireframe(i,s),s>=i.wireframeMs&&this.beginFade(i,t);continue}if(i.phase==="fade"){let o=Math.min(1,s/i.fadeMs);this.animateFade(i,o),o>=1&&r.push(i)}}for(let i of r)this.finishSection(i)}setEnabled(e){e!==this.enabled&&(this.enabled=e,e||this.forceFinishAll())}onSectionMeshedMesh(e,t,r){if(!this.enabled||!t.positions?.length||this.completed.has(e))return;let i=this.sections.get(e);if(i){i.mesh=r,i.geometry=t,(i.phase==="wireframe"||i.phase==="fade")&&this.finishSection(i);return}let s=performance.now();this.firstQueuedMs===null&&(this.firstQueuedMs=s);let o=this.globalWaveStarted;this.sections.set(e,{key:e,geometry:t,phase:"queued",phaseStartMs:s,revealAtMs:this.globalWaveStarted?s:0,wireframeMs:o?X6:W9,fadeMs:o?Z6:N9,wireframeGroup:null,mesh:r,savedMaterial:null,pulseOffset:Math.random()*Math.PI*2}),r.visible=!1,this.setShaderMeshesVisible(e,!1),this.tryStartGlobalWave(s)}reset(){this.forceFinishAll(),this.sections.clear(),this.completed.clear(),this.globalWaveStarted=!1,this.globalWaveStartMs=0,this.finishedChunkCount=0,this.firstQueuedMs=null,this.pulseTime=0}forceFinishAll(){for(let e of[...this.sections.values()])this.finishSection(e);this.sections.clear(),this.unhideAllSectionMeshes()}tryStartGlobalWave(e){if(!this.globalWaveStarted&&this.sections.size!==0){if(this.finishedChunkCount>=z9){this.startGlobalWave(e);return}this.worldRenderer.allChunksFinished&&this.startGlobalWave(e)}}startGlobalWave(e){if(this.globalWaveStarted)return;this.globalWaveStarted=!0,this.globalWaveStartMs=e;let t=this.worldRenderer.getCameraPosition(),r=1,i=new Map;for(let[s,o]of this.sections){if(o.phase!=="queued")continue;let{sx:l,sy:a,sz:v}=o.geometry,c=Math.hypot(l-t.x,a-t.y,v-t.z);i.set(s,c),r=Math.max(r,c)}for(let[,s]of this.sections){if(s.phase!=="queued")continue;let o=i.get(s.key)??0;s.revealAtMs=e+o/r*G9,s.wireframeMs=X6,s.fadeMs=Z6}}beginWireframe(e,t){let r=e.mesh??this.getSectionMesh(e.key);if(e.mesh=r,!r){this.sections.delete(e.key);return}let i=this.createWireframeGeometry(e.geometry),s=new Te.LineSegments(i,this.wireframeMaterial.clone());this.worldRenderer.sceneOrigin.track(s),s.position.set(e.geometry.sx,e.geometry.sy,e.geometry.sz),s.name="scifi-wireframe",s.renderOrder=1e3;let o=new Te.LineSegments(i.clone(),this.wireframeGlowMaterial.clone());this.worldRenderer.sceneOrigin.track(o),o.position.copy(s.position),o.scale.setScalar(1.02),o.name="scifi-glow",o.renderOrder=999;let l=new Te.Group;l.name="scifi-reveal-group",l.add(s,o),this.worldRenderer.realScene.add(l),r.visible=!1,this.setShaderMeshesVisible(e.key,!1),e.wireframeGroup=l,e.phase="wireframe",e.phaseStartMs=t}beginFade(e,t){let r=e.mesh??this.getSectionMesh(e.key);if(e.mesh=r,r){r.visible=!0;let i=r.material;if(!Array.isArray(i)&&i&&typeof i.clone=="function"){e.savedMaterial=i;let s=i.clone();s.transparent=!0,s.opacity=0,s.needsUpdate=!0,r.material=s}}this.setShaderMeshesVisible(e.key,!0),e.phase="fade",e.phaseStartMs=t}animateWireframe(e,t){if(!e.wireframeGroup)return;let r=e.wireframeGroup.children[0],i=e.wireframeGroup.children[1],s=.6+.4*Math.sin(this.pulseTime*4+e.pulseOffset);if(r?.material){let o=r.material;o.opacity=s;let l=.85+.15*Math.sin(this.pulseTime*6+t*.002);o.color.setRGB(13/255*l,234/255*l,238/255*l)}i?.material&&(i.material.opacity=s*.4)}animateFade(e,t){let r=1-(1-t)**3;if(e.wireframeGroup){let s=e.wireframeGroup.children[0],o=e.wireframeGroup.children[1];s?.material&&(s.material.opacity=1-r),o?.material&&(o.material.opacity=(1-r)*.55)}let i=e.mesh;i&&e.savedMaterial&&!Array.isArray(i.material)&&(i.material.opacity=r),this.setShaderMeshesVisible(e.key,r>.001)}finishSection(e){let t=e.mesh??this.getSectionMesh(e.key);if(t){if(e.savedMaterial){let i=t.material;t.material=e.savedMaterial,i.dispose(),e.savedMaterial=null}t.visible=!0}this.setShaderMeshesVisible(e.key,!0);let{chunkMeshManager:r}=this.worldRenderer;r.migrateDeferredShaderToGlobal(e.key),r.migrateDeferredLegacyToGlobal(e.key),e.wireframeGroup&&(this.disposeWireframeGroup(e.wireframeGroup),e.wireframeGroup=null),this.sections.delete(e.key),this.completed.add(e.key)}cancelSection(e,t){let r=this.sections.get(e);if(r){if(r.wireframeGroup&&this.disposeWireframeGroup(r.wireframeGroup),t){let i=r.mesh??this.getSectionMesh(e);if(i){if(r.savedMaterial){let s=i.material;i.material=r.savedMaterial,s.dispose()}i.visible=!0}this.setShaderMeshesVisible(e,!0)}this.sections.delete(e)}}getSectionMesh(e){let t=this.worldRenderer.chunkMeshManager.sectionObjects[e];if(!t)return null;let r=t.children.find(i=>i.name==="mesh");return r instanceof Te.Mesh?r:null}getShaderMesh(e){let t=this.worldRenderer.chunkMeshManager.sectionObjects[e];if(!t)return null;let r=t.children.find(i=>i.name==="shaderMesh");return r instanceof Te.Mesh?r:null}setShaderMeshesVisible(e,t){let r=this.getShaderMesh(e);r&&(r.visible=t)}unhideAllSectionMeshes(){for(let e of Object.values(this.worldRenderer.chunkMeshManager.sectionObjects))e&&e.traverse(t=>{t instanceof Te.Mesh&&(t.name==="mesh"||t.name==="shaderMesh")&&(t.visible=!0)})}disposeWireframeGroup(e){this.worldRenderer.sceneOrigin.removeAndUntrackAll(e),this.worldRenderer.realScene.remove(e),e.traverse(t=>{let r=t;r.geometry?.dispose();let i=r.material;Array.isArray(i)?i.forEach(s=>s.dispose()):i?.dispose()}),e.clear()}createWireframeGeometry(e){let t=e.positions,r=e.indices,i=[],s=new Set;for(let l=0;l<r.length;l+=3){let a=r[l],v=r[l+1],c=r[l+2];this.addEdge(t,a,v,i,s),this.addEdge(t,v,c,i,s),this.addEdge(t,c,a,i,s)}let o=new Te.BufferGeometry;return o.setAttribute("position",new Te.Float32BufferAttribute(i,3)),o}addEdge(e,t,r,i,s){let o=Math.min(t,r),l=Math.max(t,r),a=`${o}-${l}`;s.has(a)||(s.add(a),i.push(e[t*3],e[t*3+1],e[t*3+2],e[r*3],e[r*3+1],e[r*3+2]))}},$6={id:"futuristicReveal",controller:j1,enabledDefault:!0};E();x();R();k();import*as Ce from"three";var j9=parseInt(Ce.REVISION.replaceAll(/\D+/g,""),10),Q1=class extends Ce.ShaderMaterial{constructor(){super({uniforms:{time:{value:0},fade:{value:1}},vertexShader:`
21685
+ `,L1={u_atlas:{value:null},u_originDelta:{value:new Fe.Vector3},u_cameraOriginFrac:{value:new Fe.Vector3},u_skyLevel:{value:1},u_lightCurve:{value:tt.curve},u_minBrightness:{value:tt.minBrightness},u_lightGamma:{value:tt.gamma}};function l6(){return new Fe.ShaderMaterial({vertexShader:m9,fragmentShader:I1,uniforms:Fe.UniformsUtils.merge([Fe.UniformsLib.fog,L1]),transparent:!0,depthWrite:!0,depthTest:!0,vertexColors:!0,glslVersion:Fe.GLSL3,fog:!0})}function v6(){return new Fe.ShaderMaterial({vertexShader:a6,fragmentShader:I1,uniforms:Fe.UniformsUtils.merge([Fe.UniformsLib.fog,L1]),transparent:!1,depthWrite:!0,depthTest:!0,vertexColors:!0,glslVersion:Fe.GLSL3,fog:!0})}function c6(){return new Fe.ShaderMaterial({vertexShader:a6,fragmentShader:I1,uniforms:Fe.UniformsUtils.merge([Fe.UniformsLib.fog,L1]),transparent:!0,depthWrite:!0,depthTest:!0,vertexColors:!0,glslVersion:Fe.GLSL3,fog:!0})}function Mi(n,e,t,r,i){let{originDelta:s,cameraOriginFrac:o}=I0(e,t,r,i),l=n.uniforms.u_originDelta;l?.value?.set&&l.value.set(s.x,s.y,s.z);let a=n.uniforms.u_cameraOriginFrac;a?.value?.set&&a.value.set(o.x,o.y,o.z)}function Ti(n,e){let t=n.uniforms.u_skyLevel;t&&(t.value=e)}function Ci(n,e){if(e.curve!==void 0){let t=n.uniforms.u_lightCurve;t&&(t.value=e.curve)}if(e.minBrightness!==void 0){let t=n.uniforms.u_minBrightness;t&&(t.value=e.minBrightness)}if(e.gamma!==void 0){let t=n.uniforms.u_lightGamma;t&&(t.value=e.gamma)}}E();x();R();k();var p9=8,g9=.01;function H1(n,e,t,r,i){n.matrix.makeTranslation(e-i.x,t-i.y,r-i.z),n.matrixWorldNeedsUpdate=!0,n.frustumCulled=!1}function Bi(n,e,t,r,i,s,o,l,a,v){let c=n-r,u=e-i,f=t-s,m=p9+g9;return a.set(c-m,u-m,f-m),v.set(c+m,u+m,f+m),l.set(a,v),{visible:o.intersectsBox(l),distSq:c*c+u*u+f*f}}function d6(n,e,t,r,i,s,o,l,a,v,c){let{visible:u,distSq:f}=Bi(e,t,r,i,s,o,l,a,v,c);n.visible=u,n.renderOrder=-f}C1();E();x();R();k();import*as wt from"three";E();x();R();k();E();x();R();k();E();x();R();k();import*as Ne from"three";E();x();R();k();function f6(){return{counts:new Int32Array(Gt),offsets:new Int32Array(Gt)}}function b9(n,e){if(n.counts.length>=e)return;let t=n.counts.length;for(;t<e;)t*=2;n.counts=new Int32Array(t),n.offsets=new Int32Array(t)}function h6(n){let e=n.getExtension("WEBGL_multi_draw");return e?{tier:"A",ext:e}:{tier:"B",ext:null}}var u6=!1;function m6(n,e){u6||!e||(u6=!0)}function p6(n,e,t,r){let i=t.length;if(i===0)return;b9(r,i);let s=n.TRIANGLES,o=n.UNSIGNED_INT;for(let l=0;l<i;l++){let a=t[l];r.counts[l]=a.indexCount,r.offsets[l]=a.indexStart*4}if(e.tier==="A"&&e.ext){e.ext.multiDrawElementsWEBGL(s,r.counts,0,o,r.offsets,0,i);return}for(let l=0;l<i;l++)n.drawElements(s,r.counts[l],o,r.offsets[l])}var rt=4,He=6,ce=3,ht=2,Oe=1,y9=128e3,_9=128e3,g6=5e3,w9=.25,b6=rt*(ce*3+Oe*2+ht)*4+He*4,O1=.75,Gt=64;function D1(n,e,t){for(let r of n)for(let i=r.start;i<r.start+r.count;i++){let s=!1;for(let o of e)if(i>=o.start&&i<o.start+o.count){s=!0;break}}}function Pi(n,e){if(e.length===0)return n;let t=[];for(let r of n){let i=[r];for(let s of e){let o=[];for(let l of i){let a=l.start+l.count-1;if(s.end<l.start||s.start>a){o.push(l);continue}s.start>l.start&&o.push({start:l.start,count:s.start-l.start}),s.end<a&&o.push({start:s.end+1,count:a-s.end})}i=o}t.push(...i)}return t.filter(r=>r.count>0)}var nr=class{constructor(e,t,r){d(this,"mesh");d(this,"material");d(this,"growthIncrementQuads");d(this,"capacityQuads");d(this,"positions");d(this,"colors");d(this,"skyLights");d(this,"blockLights");d(this,"uvs");d(this,"aOrigin");d(this,"indices");d(this,"sectionSlots",new Map);d(this,"freeList",[]);d(this,"highWatermark",0);d(this,"pendingRanges",[]);d(this,"_spanScratch",[]);d(this,"renderOrigin",{x:0,y:0,z:0});d(this,"layoutVersion",0);d(this,"pendingMove",null);d(this,"pendingReplace",new Map);d(this,"uploadEpoch",0);d(this,"visibleIndexSpans",[]);d(this,"_drawScratch",f6());d(this,"multiDrawCaps",null);d(this,"debugOverlay",!1);this.material=e,this.growthIncrementQuads=r?.growthIncrementQuads??_9,this.capacityQuads=r?.initialCapacityQuads??y9;let i=this.capacityQuads*rt;this.positions=new Float32Array(i*ce),this.colors=new Float32Array(i*ce),this.skyLights=new Float32Array(i*Oe),this.blockLights=new Float32Array(i*Oe),this.uvs=new Float32Array(i*ht),this.aOrigin=new Float32Array(i*ce),this.indices=new Uint32Array(this.capacityQuads*He);let s=new Ne.BufferGeometry,o=(a,v,c)=>{let u=new Ne.BufferAttribute(a,v);return u.setUsage(Ne.DynamicDrawUsage),s.setAttribute(c,u),u};o(this.positions,ce,"position"),o(this.colors,ce,"color"),o(this.skyLights,Oe,"a_skyLight"),o(this.blockLights,Oe,"a_blockLight"),o(this.uvs,ht,"uv"),o(this.aOrigin,ce,"a_origin");let l=new Ne.BufferAttribute(this.indices,1);l.setUsage(Ne.DynamicDrawUsage),s.setIndex(l),s.setDrawRange(0,0),s.boundingSphere=new Ne.Sphere(new Ne.Vector3,1/0),this.mesh=new Ne.Mesh(s,[e]),this.mesh.name=r?.name??"globalLegacyOpaque",this.mesh.frustumCulled=!1,this.mesh.matrixAutoUpdate=!1,this.mesh.matrix.identity(),this.mesh.position.set(0,0,0),t.add(this.mesh),this.syncDefaultDrawGroups(),this.mesh.onAfterRender=(a,v,c,u,f)=>{if(this.visibleIndexSpans.length===0)return;let m=a.getContext();this.multiDrawCaps||(this.multiDrawCaps=h6(m),m6(this.multiDrawCaps.tier,this.debugOverlay)),p6(m,this.multiDrawCaps,this.visibleIndexSpans,this._drawScratch)}}setDebugOverlay(e){this.debugOverlay=e}suppressThreeDraw(){this.mesh.geometry.setDrawRange(0,3)}setVisibleIndexSpans(e){this.visibleIndexSpans=e}getVisibleIndexSpans(){return this.visibleIndexSpans}syncDefaultDrawGroups(){let e=this.mesh.geometry;e.clearGroups();let t=this.highWatermark*He;t>0&&e.addGroup(0,t,0),e.setDrawRange(0,t)}addSection(e,t,r,i,s){let o=t.positions.length/ce,l=o/rt;if(o===0||l*rt!==o)return this.removeSection(e),!1;if(t.indices.length%He!==0||t.indices.length/He!==l)return!1;let a=this.sectionSlots.has(e),v;if(a){let T=this.sectionSlots.get(e),P=this.pendingReplace.get(e),B=this.pendingMove?.key===e?this.pendingMove:void 0;P?(this.zeroAndFreeSlot(T.start,T.count),v={start:P.oldStart,count:P.oldCount},this.pendingReplace.delete(e)):B?(this.zeroAndFreeSlot(T.start,T.count),v={start:B.oldStart,count:B.count},this.pendingMove=null):v=T}l>this.capacityQuads&&this.growCapacity(l);let c=this.takeFreeSlot(l);c||(this.highWatermark+l>this.capacityQuads&&this.growCapacity(this.highWatermark+l),c={start:this.highWatermark,count:l},this.highWatermark+=l);let u=c.start*rt,f=u*ce,m=u*ht,g=u*Oe;this.positions.set(t.positions,f),this.colors.set(t.colors,f),this.skyLights.set(t.skyLights,g),this.blockLights.set(t.blockLights,g),this.uvs.set(t.uvs,m);let b=f,A=r-this.renderOrigin.x,y=i-this.renderOrigin.y,_=s-this.renderOrigin.z;for(let T=0;T<o;T++){let P=b+T*ce;this.aOrigin[P]=A,this.aOrigin[P+1]=y,this.aOrigin[P+2]=_}let S=c.start*He,C=u;for(let T=0;T<t.indices.length;T++)this.indices[S+T]=t.indices[T]+C;return this.sectionSlots.set(e,c),a&&v&&this.pendingReplace.set(e,{oldStart:v.start,oldCount:v.count}),this.markDirty(c.start,c.start+l-1),this.syncDefaultDrawGroups(),this.layoutVersion++,!0}getLayoutVersion(){return this.layoutVersion}getUploadEpoch(){return this.uploadEpoch}hasPendingReplace(){return this.pendingReplace.size>0}canUseFullDrawShortcut(){return this.pendingRanges.length===0&&this.interiorFreeQuads()===0&&this.pendingMove===null&&this.pendingReplace.size===0}isRangeFullyUploaded(e,t){return this.rangeFullyUploaded(e,t)}getPendingDirtyRanges(){return this.pendingRanges}getSectionDrawStart(e){let t=this.sectionSlots.get(e);if(!t)return;if(this.pendingMove?.key===e)return this.pendingMove.oldStart;let r=this.pendingReplace.get(e);if(r)return r.oldStart;if(this.rangeFullyUploaded(t.start,t.start+t.count-1))return t.start}getSectionDrawCount(e){let t=this.sectionSlots.get(e);if(!t)return;if(this.pendingMove?.key===e)return this.pendingMove.count;let r=this.pendingReplace.get(e);if(r)return r.oldCount;if(this.rangeFullyUploaded(t.start,t.start+t.count-1))return t.count}getPendingMove(){return this.pendingMove}compactStep(){if(this.pendingMove){let{newStart:l,count:a}=this.pendingMove;this.rangeFullyUploaded(l,l+a-1)&&this.finalizePendingMove();return}for(let l of[...this.pendingReplace.keys()]){let a=this.sectionSlots.get(l);a&&this.rangeFullyUploaded(a.start,a.start+a.count-1)&&this.finalizePendingReplace(l)}if(this.highWatermark===0||this.interiorFreeQuads()/this.highWatermark<=w9)return;let t=this.findMovableSection(g6);if(!t)return;let r=this.findLowestInteriorHole(t.start,t.count);if(!r)return;let i=this.reserveFreeSlotAt(r.index,t.count),s=t.start,o=i.start;this.copySectionRange(s,o,t.count),this.sectionSlots.set(t.key,{start:o,count:t.count}),this.markDirty(o,o+t.count-1),this.pendingMove={key:t.key,oldStart:s,newStart:o,count:t.count},this.layoutVersion++}updateDrawSpans(e,t){if(this.visibleIndexSpans=[],this.highWatermark===0)return;let r=this._spanScratch;r.length=0;let i=0;for(let o of e){let l=this.getSectionDrawStart(o.key),a=this.getSectionDrawCount(o.key),v=this.sectionSlots.get(o.key);l===void 0||a===void 0||!v||(r.push({start:l,count:a}),i+=a)}if(r.length===0)return;let s=(o,l)=>{this.visibleIndexSpans.push({indexStart:o*He,indexCount:l*He})};if(t==="opaque"){let o,l=r.map(v=>({...v})),a=this.canUseFullDrawShortcut()&&i>=this.highWatermark*O1;a?o=[{start:0,count:this.highWatermark}]:(r.sort((v,c)=>v.start-c.start),this.mergeOpaqueSpans(r),o=r),o=Pi(o,this.pendingRanges),a||D1(o,l,this.mesh.name);for(let v of o)s(v.start,v.count)}else{e.sort((o,l)=>l.distSq-o.distSq);for(let o of e){let l=this.getSectionDrawStart(o.key),a=this.getSectionDrawCount(o.key);l===void 0||a===void 0||s(l,a)}}}mergeOpaqueSpans(e){if(e.length<2)return;let t=0;for(;t<e.length-1;){let r=e[t],i=e[t+1];r.start+r.count===i.start?(r.count=i.start+i.count-r.start,e.splice(t+1,1)):t++}}hasSection(e){return this.sectionSlots.has(e)}getSectionSlot(e){return this.sectionSlots.get(e)}takeSectionData(e){let t=this.getSectionGeometryData(e);if(t)return this.removeSection(e),t}getSectionGeometryData(e){let t=this.sectionSlots.get(e);if(!t)return;let r=t.count*rt,i=t.start*rt,s=i*ce,o=i*ht,l=t.start*He,a=t.count*He,v=i*Oe,c=this.positions.slice(s,s+r*ce),u=this.colors.slice(s,s+r*ce),f=this.skyLights.slice(v,v+r*Oe),m=this.blockLights.slice(v,v+r*Oe),g=this.uvs.slice(o,o+r*ht),b=this.indices.slice(l,l+a),A=i;for(let C=0;C<b.length;C++)b[C]=b[C]-A;let y=this.aOrigin[s]+this.renderOrigin.x,_=this.aOrigin[s+1]+this.renderOrigin.y,S=this.aOrigin[s+2]+this.renderOrigin.z;return{positions:c,colors:u,skyLights:f,blockLights:m,uvs:g,indices:b,sx:y,sy:_,sz:S}}removeSection(e){let t=this.sectionSlots.get(e);if(!t)return;if(this.pendingReplace.has(e)){let s=this.pendingReplace.get(e);this.zeroAndFreeSlot(s.oldStart,s.oldCount),this.pendingReplace.delete(e)}if(this.pendingMove?.key===e){let{oldStart:s,count:o}=this.pendingMove;this.zeroAndFreeSlot(s,o),this.pendingMove=null}let r=t.start*He,i=t.count*He;for(let s=0;s<i;s++)this.indices[r+s]=0;this.markDirty(t.start,t.start+t.count-1),this.sectionSlots.delete(e),this.insertFreeSlot(t),this.shrinkHighWatermark(),this.syncDefaultDrawGroups(),this.layoutVersion++}hasPendingUploads(){return this.pendingRanges.length>0}uploadDirtyRange(){let e=this.pendingRanges[0];if(!e)return;let t=e.start,r=Math.min(e.end-e.start+1,g6),i=t*rt,s=r*rt,o=t*He,l=r*He,a=this.mesh.geometry,v=a.getAttribute("position");v.clearUpdateRanges(),v.addUpdateRange(i*ce,s*ce),v.needsUpdate=!0;let c=a.getAttribute("color");c.clearUpdateRanges(),c.addUpdateRange(i*ce,s*ce),c.needsUpdate=!0;let u=a.getAttribute("a_skyLight");u.clearUpdateRanges(),u.addUpdateRange(i*Oe,s*Oe),u.needsUpdate=!0;let f=a.getAttribute("a_blockLight");f.clearUpdateRanges(),f.addUpdateRange(i*Oe,s*Oe),f.needsUpdate=!0;let m=a.getAttribute("uv");m.clearUpdateRanges(),m.addUpdateRange(i*ht,s*ht),m.needsUpdate=!0;let g=a.getAttribute("a_origin");g.clearUpdateRanges(),g.addUpdateRange(i*ce,s*ce),g.needsUpdate=!0;let b=a.index;b.clearUpdateRanges(),b.addUpdateRange(o,l),b.needsUpdate=!0,t+r>e.end?this.pendingRanges.shift():e.start=t+r,this.uploadEpoch++}setRenderOrigin(e){this.renderOrigin={...e}}rebase(e){if(this.highWatermark!==0){for(let t of this.sectionSlots.values()){let r=t.start*rt,i=t.count*rt,s=r*ce;for(let o=0;o<i;o++){let l=s+o*ce;this.aOrigin[l]-=e.x,this.aOrigin[l+1]-=e.y,this.aOrigin[l+2]-=e.z}}this.markDirty(0,this.highWatermark-1),this.renderOrigin.x+=e.x,this.renderOrigin.y+=e.y,this.renderOrigin.z+=e.z}}setCameraOrigin(e,t,r){let{originDelta:i,cameraOriginFrac:s}=I0(this.renderOrigin,e,t,r),o=this.material.uniforms.u_originDelta;o?.value?.set&&o.value.set(i.x,i.y,i.z);let l=this.material.uniforms.u_cameraOriginFrac;l?.value?.set&&l.value.set(s.x,s.y,s.z)}getHighWatermark(){return this.highWatermark}getCapacityQuads(){return this.capacityQuads}getSectionCount(){return this.sectionSlots.size}getMemoryBytes(){return this.capacityQuads*b6}getUsedMemoryBytes(){return this.highWatermark*b6}reset(){this.sectionSlots.clear(),this.freeList.length=0,this.highWatermark=0,this.pendingRanges.length=0,this.pendingMove=null,this.pendingReplace.clear(),this.uploadEpoch=0,this.visibleIndexSpans=[],this.syncDefaultDrawGroups()}dispose(){this.mesh.parent?.remove(this.mesh),this.mesh.geometry.dispose(),this.reset()}markDirty(e,t){this.pendingRanges.push({start:e,end:t}),this.pendingRanges.sort((r,i)=>r.start-i.start),this.mergePendingRanges()}mergePendingRanges(){if(this.pendingRanges.length<2)return;let e=[],t=this.pendingRanges[0];for(let r=1;r<this.pendingRanges.length;r++){let i=this.pendingRanges[r];i.start<=t.end+1?t={start:t.start,end:Math.max(t.end,i.end)}:(e.push(t),t=i)}e.push(t),this.pendingRanges=e}takeFreeSlot(e){for(let t=0;t<this.freeList.length;t++){let r=this.freeList[t];if(r.count>=e){if(this.freeList.splice(t,1),r.count===e)return r;let i={start:r.start,count:e};return this.insertFreeSlot({start:r.start+e,count:r.count-e}),i}}}insertFreeSlot(e){this.freeList.push(e),this.freeList.sort((t,r)=>t.start-r.start),this.mergeFreeList()}mergeFreeList(){if(this.freeList.length<2)return;let e=[],t=this.freeList[0];for(let r=1;r<this.freeList.length;r++){let i=this.freeList[r];t.start+t.count===i.start?t={start:t.start,count:t.count+i.count}:(e.push(t),t=i)}e.push(t),this.freeList=e}shrinkHighWatermark(){for(;this.highWatermark>0;){let e=this.highWatermark-1,t=this.freeList.find(i=>i.start<=e&&i.start+i.count>e);if(!t||t.start+t.count!==this.highWatermark)break;this.highWatermark=t.start;let r=this.freeList.indexOf(t);this.freeList.splice(r,1)}}interiorFreeQuads(){let e=0;for(let t of this.freeList)t.start<this.highWatermark&&(e+=t.count);return e}findMovableSection(e){let t=[];for(let[s,o]of this.sectionSlots)t.push({key:s,start:o.start,count:o.count});if(t.length===0)return;t.sort((s,o)=>o.start!==s.start?o.start-s.start:o.start+o.count-(s.start+s.count));let r=t[0];if(r.count<=e&&this.findLowestInteriorHole(r.start,r.count))return r;let i=t.filter(s=>s.count<=e).sort((s,o)=>o.count-s.count);for(let s of i)if(this.findLowestInteriorHole(s.start,s.count))return s}findLowestInteriorHole(e,t){for(let r=0;r<this.freeList.length;r++){let i=this.freeList[r];if(i.start<e&&i.count>=t)return{start:i.start,count:i.count,index:r}}}reserveFreeSlotAt(e,t){let r=this.freeList[e];if(this.freeList.splice(e,1),r.count===t)return{start:r.start,count:t};let i={start:r.start,count:t};return this.insertFreeSlot({start:r.start+t,count:r.count-t}),i}copySectionRange(e,t,r){let i=e*rt,s=t*rt,o=r*rt,l=s-i,a=i*ce,v=s*ce,c=o*ce;this.positions.copyWithin(v,a,a+c),this.colors.copyWithin(v,a,a+c),this.aOrigin.copyWithin(v,a,a+c);let u=i*Oe,f=s*Oe,m=o*Oe;this.skyLights.copyWithin(f,u,u+m),this.blockLights.copyWithin(f,u,u+m);let g=i*ht,b=s*ht,A=o*ht;this.uvs.copyWithin(b,g,g+A);let y=e*He,_=t*He,S=r*He;for(let C=0;C<S;C++)this.indices[_+C]=this.indices[y+C]+l}rangeFullyUploaded(e,t){for(let r of this.pendingRanges)if(r.start<=t&&r.end>=e)return!1;return!0}zeroAndFreeSlot(e,t){let r=e*He,i=t*He;for(let s=0;s<i;s++)this.indices[r+s]=0;this.markDirty(e,e+t-1),this.insertFreeSlot({start:e,count:t})}finalizePendingReplace(e){let t=this.pendingReplace.get(e);t&&(this.zeroAndFreeSlot(t.oldStart,t.oldCount),this.pendingReplace.delete(e),this.shrinkHighWatermark(),this.syncDefaultDrawGroups(),this.layoutVersion++,this.uploadEpoch++)}finalizePendingMove(){let e=this.pendingMove;if(!e)return;let{oldStart:t,count:r}=e;this.zeroAndFreeSlot(t,r),this.shrinkHighWatermark(),this.syncDefaultDrawGroups(),this.pendingMove=null,this.layoutVersion++,this.uploadEpoch++}growCapacity(e){this.pendingMove&&this.finalizePendingMove();for(let A of[...this.pendingReplace.keys()])this.finalizePendingReplace(A);let t=this.capacityQuads;for(;t<e;)t+=this.growthIncrementQuads;let r=this.capacityQuads*rt,i=t*rt,s=new Float32Array(i*ce),o=new Float32Array(i*ce),l=new Float32Array(i*Oe),a=new Float32Array(i*Oe),v=new Float32Array(i*ht),c=new Float32Array(i*ce),u=new Uint32Array(t*He);s.set(this.positions),o.set(this.colors),l.set(this.skyLights),a.set(this.blockLights),v.set(this.uvs),c.set(this.aOrigin),u.set(this.indices),this.positions=s,this.colors=o,this.skyLights=l,this.blockLights=a,this.uvs=v,this.aOrigin=c,this.indices=u,this.capacityQuads=t;let f=this.mesh.geometry,m=(A,y,_)=>{f.getAttribute(_)&&f.deleteAttribute(_);let C=new Ne.BufferAttribute(A,y);C.setUsage(Ne.DynamicDrawUsage),f.setAttribute(_,C)};m(this.positions,ce,"position"),m(this.colors,ce,"color"),m(this.skyLights,Oe,"a_skyLight"),m(this.blockLights,Oe,"a_blockLight"),m(this.uvs,ht,"uv"),m(this.aOrigin,ce,"a_origin"),f.index&&f.setIndex(null);let b=new Ne.BufferAttribute(this.indices,1);b.setUsage(Ne.DynamicDrawUsage),f.setIndex(b),this.pendingRanges.length=0}};function A9(n){if(n.length<2)return;let e=0;for(;e<n.length-1;){let t=n[e],r=n[e+1];t.start+t.count===r.start?(t.count=r.start+r.count-t.start,n.splice(e+1,1)):e++}}function y6(n,e,t=!0,r,i=[]){if(n.length===0||e===0)return[];let s=0;for(let a of n)s+=a.count;let o;if(t&&s>=e*O1)o=[{start:0,count:e}];else{o=n.map(v=>({start:v.start,count:v.count})),o.sort((v,c)=>v.start-c.start);let a=o.map(v=>({...v}));return A9(o),o=Pi(o,i),D1(o,a,"globalBlockBuffer"),o}return Pi(o,i)}$t();function w6(){return{firsts:new Int32Array(Gt),counts:new Int32Array(Gt),instanceCounts:new Int32Array(Gt),baseInstances:new Int32Array(Gt)}}function A6(n){let e=n.getExtension("WEBGL_multi_draw_instanced_base_vertex_base_instance");if(e)return{tier:"A",ext:e};let t=n.getExtension("WEBGL_draw_instanced_base_vertex_base_instance");return t?{tier:"B",ext:t}:{tier:"C",ext:null}}var _6=!1;function E6(n,e){_6||!e||(_6=!0)}function x6(n,e,t,r,i){let s=t.length;if(s===0)return;let o=n.TRIANGLES;if(e.tier==="A"&&e.ext){let l=e.ext;for(let a=0;a<s;a++){let v=t[a];r.firsts[a]=0,r.counts[a]=Ut,r.instanceCounts[a]=v.count,r.baseInstances[a]=v.start}l.multiDrawArraysInstancedBaseInstanceWEBGL(o,r.firsts,0,r.counts,0,r.instanceCounts,0,r.baseInstances,0,s);return}if(e.tier==="B"&&e.ext){let l=e.ext;for(let a=0;a<s;a++){let v=t[a];l.drawArraysInstancedBaseInstanceWEBGL(o,0,Ut,v.count,v.start)}return}i?.(n,t)}$t();a5();var E9=512e3,x9=1e6,k6=15e3,k9=.25,sr=$3(),R6=16,Ii=class{constructor(e,t){d(this,"mesh");d(this,"capacityFaces");d(this,"w0");d(this,"w1");d(this,"w2");d(this,"w3");d(this,"sectionSlots",new Map);d(this,"freeList",[]);d(this,"highWatermark",0);d(this,"pendingRanges",[]);d(this,"pendingMove",null);d(this,"pendingReplace",new Map);d(this,"uploadEpoch",0);d(this,"visibleSpans",[]);d(this,"_drawScratch",w6());d(this,"multiDrawCaps",null);d(this,"tierCVao",null);d(this,"tierCAttrs",null);d(this,"tierCGl",null);d(this,"debugOverlay",!1);d(this,"layoutVersion",0);this.capacityFaces=E9,this.w0=new Uint32Array(this.capacityFaces),this.w1=new Uint32Array(this.capacityFaces),this.w2=new Uint32Array(this.capacityFaces),this.w3=new Uint32Array(this.capacityFaces),this.w2.fill(sr);let r=new wt.InstancedBufferGeometry,i=new Float32Array(Ut*3);r.setAttribute("position",new wt.BufferAttribute(i,3));let s=o=>{let l=new wt.InstancedBufferAttribute(o,1);return l.setUsage(wt.DynamicDrawUsage),l};r.setAttribute("a_w0",s(this.w0)),r.setAttribute("a_w1",s(this.w1)),r.setAttribute("a_w2",s(this.w2)),r.setAttribute("a_w3",s(this.w3)),r.instanceCount=0,this.mesh=new wt.Mesh(r,e),this.mesh.name="globalShaderCubes",this.mesh.frustumCulled=!1,this.mesh.matrixAutoUpdate=!1,this.mesh.matrix.identity(),this.mesh.position.set(0,0,0),t.add(this.mesh),this.mesh.onAfterRender=(o,l,a,v,c)=>{if(this.visibleSpans.length===0)return;let u=c,f=o.getContext();this.multiDrawCaps||(this.multiDrawCaps=A6(f),E6(this.multiDrawCaps.tier,this.debugOverlay)),x6(f,this.multiDrawCaps,this.visibleSpans,this._drawScratch,this.multiDrawCaps.tier==="C"?(m,g)=>this.drawTierCSpans(m,g,o,u):void 0)}}setDebugOverlay(e){this.debugOverlay=e}suppressThreeDraw(){let e=this.mesh.geometry;e.setDrawRange(0,Ut),e.instanceCount=0}setVisibleSpans(e){this.visibleSpans=e}getVisibleSpans(){return this.visibleSpans}forEachSectionSlot(e){for(let[t,r]of this.sectionSlots)e(t,r)}getSectionDrawStart(e){let t=this.sectionSlots.get(e);if(!t)return;if(this.pendingMove?.key===e)return this.pendingMove.oldStart;let r=this.pendingReplace.get(e);if(r)return r.oldStart;if(this.rangeFullyUploaded(t.start,t.start+t.count-1))return t.start}getSectionDrawCount(e){let t=this.sectionSlots.get(e);if(!t)return;if(this.pendingMove?.key===e)return this.pendingMove.count;let r=this.pendingReplace.get(e);if(r)return r.oldCount;if(this.rangeFullyUploaded(t.start,t.start+t.count-1))return t.count}getUploadEpoch(){return this.uploadEpoch}hasPendingReplace(){return this.pendingReplace.size>0}canUseFullDrawShortcut(){return this.pendingRanges.length===0&&this.interiorFreeFaces()===0&&this.pendingMove===null&&this.pendingReplace.size===0}isRangeFullyUploaded(e,t){return this.rangeFullyUploaded(e,t)}getPendingDirtyRanges(){return this.pendingRanges}getHighWatermark(){return this.highWatermark}getCapacityFaces(){return this.capacityFaces}getSectionCount(){return this.sectionSlots.size}getMemoryBytes(){return this.capacityFaces*R6}getUsedMemoryBytes(){return this.highWatermark*R6}hasPendingUploads(){return this.pendingRanges.length>0}getPendingMove(){return this.pendingMove}addSection(e,t,r){if(r<=0){this.removeSection(e);return}let i=this.sectionSlots.has(e),s;if(i){let a=this.sectionSlots.get(e),v=this.pendingReplace.get(e),c=this.pendingMove?.key===e?this.pendingMove:void 0;v?(this.zeroAndFreeSlot(a.start,a.count),s={start:v.oldStart,count:v.oldCount},this.pendingReplace.delete(e)):c?(this.zeroAndFreeSlot(a.start,a.count),s={start:c.oldStart,count:c.count},this.pendingMove=null):s=a}r>this.capacityFaces&&this.growCapacity(r);let o=this.takeFreeSlot(r);o||(this.highWatermark+r>this.capacityFaces&&this.growCapacity(this.highWatermark+r),o={start:this.highWatermark,count:r},this.highWatermark+=r);let l=4;for(let a=0;a<r;a++){let v=o.start+a,c=a*l;this.w0[v]=t[c],this.w1[v]=t[c+1],this.w2[v]=t[c+2],this.w3[v]=t[c+3]}this.sectionSlots.set(e,o),i&&s&&this.pendingReplace.set(e,{oldStart:s.start,oldCount:s.count}),this.markDirty(o.start,o.start+r-1),this.mesh.geometry.instanceCount=this.highWatermark,this.layoutVersion++}getLayoutVersion(){return this.layoutVersion}hasSection(e){return this.sectionSlots.has(e)}getSectionSlot(e){return this.sectionSlots.get(e)}getW0(){return this.w0}takeSectionData(e){let t=this.sectionSlots.get(e);if(!t)return;let r=4,i=new Uint32Array(t.count*r);for(let s=0;s<t.count;s++){let o=t.start+s,l=s*r;i[l]=this.w0[o],i[l+1]=this.w1[o],i[l+2]=this.w2[o],i[l+3]=this.w3[o]}return this.removeSection(e),{words:i,count:t.count}}removeSection(e){let t=this.sectionSlots.get(e);if(t){if(this.pendingReplace.has(e)){let r=this.pendingReplace.get(e);this.zeroAndFreeSlot(r.oldStart,r.oldCount),this.pendingReplace.delete(e)}if(this.pendingMove?.key===e){let{oldStart:r,count:i}=this.pendingMove;this.zeroAndFreeSlot(r,i),this.pendingMove=null}for(let r=t.start;r<t.start+t.count;r++)this.w0[r]=0,this.w1[r]=0,this.w2[r]=sr,this.w3[r]=0;this.markDirty(t.start,t.start+t.count-1),this.sectionSlots.delete(e),this.insertFreeSlot(t),this.shrinkHighWatermark(),this.mesh.geometry.instanceCount=this.highWatermark,this.layoutVersion++}}compactStep(){if(this.pendingMove){let{newStart:l,count:a}=this.pendingMove;this.rangeFullyUploaded(l,l+a-1)&&this.finalizePendingMove();return}for(let l of[...this.pendingReplace.keys()]){let a=this.sectionSlots.get(l);a&&this.rangeFullyUploaded(a.start,a.start+a.count-1)&&this.finalizePendingReplace(l)}if(this.highWatermark===0||this.interiorFreeFaces()/this.highWatermark<=k9)return;let t=this.findMovableSection(k6);if(!t)return;let r=this.findLowestInteriorHole(t.start,t.count);if(!r)return;let i=this.reserveFreeSlotAt(r.index,t.count),s=t.start,o=i.start;this.copySectionRange(s,o,t.count),this.sectionSlots.set(t.key,{start:o,count:t.count}),this.markDirty(o,o+t.count-1),this.pendingMove={key:t.key,oldStart:s,newStart:o,count:t.count},this.layoutVersion++}uploadDirtyRange(){let e=this.pendingRanges[0];if(!e)return;let t=e.start,r=Math.min(e.end-e.start+1,k6),i=this.mesh.geometry;for(let s of["a_w0","a_w1","a_w2","a_w3"]){let o=i.getAttribute(s);o.clearUpdateRanges(),o.addUpdateRange(t,r),o.needsUpdate=!0}t+r>e.end?this.pendingRanges.shift():e.start=t+r,this.uploadEpoch++}setCameraOrigin(e,t,r,i){let{originDelta:s,cameraOriginFrac:o}=I0(e,t,r,i),l=wi(e),a=this.mesh.material.uniforms.u_originDelta;a?.value?.set&&a.value.set(s.x,s.y,s.z);let v=this.mesh.material.uniforms.u_cameraOriginFrac;v?.value?.set&&v.value.set(o.x,o.y,o.z);let c=this.mesh.material.uniforms.u_sectionOriginRel;c?.value?.set&&c.value.set(l.x,l.y,l.z)}reset(){this.sectionSlots.clear(),this.freeList.length=0,this.highWatermark=0,this.pendingRanges.length=0,this.pendingMove=null,this.pendingReplace.clear(),this.uploadEpoch=0,this.visibleSpans=[],this.w0.fill(0),this.w1.fill(0),this.w2.fill(sr),this.w3.fill(0),this.mesh.geometry.instanceCount=0,this.invalidateTierCVao()}dispose(){this.invalidateTierCVao(),this.mesh.parent?.remove(this.mesh),this.mesh.geometry.dispose(),this.reset()}invalidateTierCVao(){this.tierCVao&&this.tierCGl&&this.tierCGl.deleteVertexArray(this.tierCVao),this.tierCVao=null,this.tierCAttrs=null}drawTierCSpans(e,t,r,i){if(this.ensureTierCVao(e,r,i),!this.tierCVao||!this.tierCAttrs)return;let s=this.tierCAttrs;e.bindVertexArray(this.tierCVao);for(let o of t){let l=o.start*4,a=v=>{e.bindBuffer(e.ARRAY_BUFFER,v.buffer),e.vertexAttribIPointer(v.loc,1,e.UNSIGNED_INT,4,l)};a(s.w0),a(s.w1),a(s.w2),a(s.w3),e.drawArraysInstanced(e.TRIANGLES,0,Ut,o.count)}e.bindVertexArray(null)}ensureTierCVao(e,t,r){this.tierCGl=e;let o=t.properties.get(r).currentProgram.program,l=e.getAttribLocation(o,"a_w0"),a=e.getAttribLocation(o,"a_w1"),v=e.getAttribLocation(o,"a_w2"),c=e.getAttribLocation(o,"a_w3"),u=S=>S<0?null:e.getVertexAttrib(S,e.VERTEX_ATTRIB_ARRAY_BUFFER_BINDING),f=u(l);if(this.tierCVao&&this.tierCAttrs&&f&&this.tierCAttrs.w0.buffer!==f&&this.invalidateTierCVao(),this.tierCVao)return;let m=u(l),g=u(a),b=u(v),A=u(c);if(!m||!g||!b||!A)return;let y=e.createVertexArray();if(!y)return;e.bindVertexArray(y);let _=(S,C)=>{e.enableVertexAttribArray(S),e.bindBuffer(e.ARRAY_BUFFER,C),e.vertexAttribIPointer(S,1,e.UNSIGNED_INT,4,0),e.vertexAttribDivisor(S,1)};_(l,m),_(a,g),_(v,b),_(c,A),e.bindVertexArray(null),this.tierCVao=y,this.tierCAttrs={w0:{loc:l,buffer:m},w1:{loc:a,buffer:g},w2:{loc:v,buffer:b},w3:{loc:c,buffer:A}}}markDirty(e,t){this.pendingRanges.push({start:e,end:t}),this.pendingRanges.sort((r,i)=>r.start-i.start),this.mergePendingRanges()}mergePendingRanges(){if(this.pendingRanges.length<2)return;let e=[],t=this.pendingRanges[0];for(let r=1;r<this.pendingRanges.length;r++){let i=this.pendingRanges[r];i.start<=t.end+1?t={start:t.start,end:Math.max(t.end,i.end)}:(e.push(t),t=i)}e.push(t),this.pendingRanges=e}takeFreeSlot(e){for(let t=0;t<this.freeList.length;t++){let r=this.freeList[t];if(r.count>=e){if(this.freeList.splice(t,1),r.count===e)return r;let i={start:r.start,count:e};return this.insertFreeSlot({start:r.start+e,count:r.count-e}),i}}}insertFreeSlot(e){this.freeList.push(e),this.freeList.sort((t,r)=>t.start-r.start),this.mergeFreeList()}mergeFreeList(){if(this.freeList.length<2)return;let e=[],t=this.freeList[0];for(let r=1;r<this.freeList.length;r++){let i=this.freeList[r];t.start+t.count===i.start?t={start:t.start,count:t.count+i.count}:(e.push(t),t=i)}e.push(t),this.freeList=e}interiorFreeFaces(){let e=0;for(let t of this.freeList)t.start<this.highWatermark&&(e+=t.count);return e}findMovableSection(e){let t=[];for(let[s,o]of this.sectionSlots)t.push({key:s,start:o.start,count:o.count});if(t.length===0)return;t.sort((s,o)=>o.start!==s.start?o.start-s.start:o.start+o.count-(s.start+s.count));let r=t[0];if(r.count<=e&&this.findLowestInteriorHole(r.start,r.count))return r;let i=t.filter(s=>s.count<=e).sort((s,o)=>o.count-s.count);for(let s of i)if(this.findLowestInteriorHole(s.start,s.count))return s}findLowestInteriorHole(e,t){for(let r=0;r<this.freeList.length;r++){let i=this.freeList[r];if(i.start<e&&i.count>=t)return{start:i.start,count:i.count,index:r}}}reserveFreeSlotAt(e,t){let r=this.freeList[e];if(this.freeList.splice(e,1),r.count===t)return{start:r.start,count:t};let i={start:r.start,count:t};return this.insertFreeSlot({start:r.start+t,count:r.count-t}),i}copySectionRange(e,t,r){this.w0.copyWithin(t,e,e+r),this.w1.copyWithin(t,e,e+r),this.w2.copyWithin(t,e,e+r),this.w3.copyWithin(t,e,e+r)}rangeFullyUploaded(e,t){for(let r of this.pendingRanges)if(r.start<=t&&r.end>=e)return!1;return!0}zeroAndFreeSlot(e,t){for(let r=e;r<e+t;r++)this.w0[r]=0,this.w1[r]=0,this.w2[r]=sr,this.w3[r]=0;this.markDirty(e,e+t-1),this.insertFreeSlot({start:e,count:t})}finalizePendingReplace(e){let t=this.pendingReplace.get(e);t&&(this.zeroAndFreeSlot(t.oldStart,t.oldCount),this.pendingReplace.delete(e),this.shrinkHighWatermark(),this.mesh.geometry.instanceCount=this.highWatermark,this.layoutVersion++,this.uploadEpoch++)}finalizePendingMove(){let e=this.pendingMove;if(!e)return;let{oldStart:t,count:r}=e;this.zeroAndFreeSlot(t,r),this.shrinkHighWatermark(),this.mesh.geometry.instanceCount=this.highWatermark,this.pendingMove=null,this.layoutVersion++,this.uploadEpoch++}shrinkHighWatermark(){for(;this.highWatermark>0;){let e=this.highWatermark-1,t=this.freeList.find(i=>i.start<=e&&i.start+i.count>e);if(!t||t.start+t.count!==this.highWatermark)break;this.highWatermark=t.start;let r=this.freeList.indexOf(t);this.freeList.splice(r,1)}}growCapacity(e){this.pendingMove&&this.finalizePendingMove();for(let v of[...this.pendingReplace.keys()])this.finalizePendingReplace(v);let t=this.capacityFaces;for(;t<e;)t+=x9;let r=new Uint32Array(t),i=new Uint32Array(t),s=new Uint32Array(t),o=new Uint32Array(t);r.set(this.w0),i.set(this.w1),s.set(this.w2),o.set(this.w3),s.fill(sr,this.w0.length),this.w0=r,this.w1=i,this.w2=s,this.w3=o,this.capacityFaces=t;let l=this.mesh.geometry,a=(v,c)=>{let u=l.getAttribute(c);u&&(l.deleteAttribute(c),"dispose"in u&&typeof u.dispose=="function"&&u.dispose());let f=new wt.InstancedBufferAttribute(v,1);f.setUsage(wt.DynamicDrawUsage),l.setAttribute(c,f)};a(this.w0,"a_w0"),a(this.w1,"a_w1"),a(this.w2,"a_w2"),a(this.w3,"a_w3"),this.pendingRanges.length=0,this.invalidateTierCVao()}};E();x();R();k();a5();$t();function S6(n,e,t,r,i){if(e<=0)return;let s=t-8,o=r-8,l=i-8,a=ki,v=16,c=16,u=16,f=-1,m=-1,g=-1;for(let T=0;T<e;T++){let P=n[T*a],B=P&(1<<P0.LX_BITS)-1,L=P>>P0.LY_SHIFT&(1<<P0.LY_BITS)-1,V=P>>P0.LZ_SHIFT&(1<<P0.LZ_BITS)-1;B<v&&(v=B),L<c&&(c=L),V<u&&(u=V),B>f&&(f=B),L>m&&(m=L),V>g&&(g=V)}if(f<0)return;let b=s+v,A=o+c,y=l+u,_=s+f+1,S=o+m+1,C=l+g+1;return{minX:b,minY:A,minZ:y,maxX:_,maxY:S,maxZ:C,cx:(b+_)*.5,cy:(A+S)*.5,cz:(y+C)*.5}}function R9(n,e,t,r,i,s,o,l,a){return n>=r&&n<=o&&e>=i&&e<=l&&t>=s&&t<=a}function M6(n,e,t,r,i,s,o,l,a,v,c,u,f){if(R9(n,e,t,o,l,a,v,c,u))return;let m=0,g=f;if(Math.abs(r)<1e-8){if(n<o||n>v)return}else{let b=1/r,A=(o-n)*b,y=(v-n)*b;if(A>y){let _=A;A=y,y=_}if(m=Math.max(m,A),g=Math.min(g,y),m>g)return}if(Math.abs(i)<1e-8){if(e<l||e>c)return}else{let b=1/i,A=(l-e)*b,y=(c-e)*b;if(A>y){let _=A;A=y,y=_}if(m=Math.max(m,A),g=Math.min(g,y),m>g)return}if(Math.abs(s)<1e-8){if(t<a||t>u)return}else{let b=1/s,A=(a-t)*b,y=(u-t)*b;if(A>y){let _=A;A=y,y=_}if(m=Math.max(m,A),g=Math.min(g,y),m>g)return}return m<=g&&m>=0?m:void 0}function T6(n,e,t,r,i,s,o,l,a,v,c,u,f){let m=f;if(Math.abs(r)>=1e-8){let g=r>0?(v-n)/r:(o-n)/r;g>1e-6&&(m=Math.min(m,g))}else if(n<o||n>v)return;if(Math.abs(i)>=1e-8){let g=i>0?(c-e)/i:(l-e)/i;g>1e-6&&(m=Math.min(m,g))}else if(e<l||e>c)return;if(Math.abs(s)>=1e-8){let g=s>0?(u-t)/s:(a-t)/s;g>1e-6&&(m=Math.min(m,g))}else if(t<a||t>u)return;return m<=f?m:void 0}E();x();R();k();import*as st from"three";E();x();R();k();bi();var Li=class{constructor(){d(this,"entries",new Set);d(this,"skyLevel",1);d(this,"lightmapParams",{...tt})}register(e){this.entries.add(e),this.applyBrightness(e)}unregister(e){for(let t of this.entries)if(t.material===e){this.entries.delete(t);break}}setSkyLevel(e){this.skyLevel=e,this.refreshAll()}setLightmapParams(e){this.lightmapParams={...this.lightmapParams,...e},this.refreshAll()}getSkyLevel(){return this.skyLevel}refreshAll(){for(let e of this.entries)this.applyBrightness(e)}applyBrightness(e){let t=k1(e.blockLightNorm,e.skyLightNorm,this.skyLevel,this.lightmapParams);e.material.color.setScalar(t)}};function C6(n,e,t,r,i=tt){let s=k1(e,t,r,i);return n.color.setScalar(s),s}var B6=20,P6=40,S9={white_banner:15,orange_banner:14,magenta_banner:13,light_blue_banner:12,yellow_banner:11,lime_banner:10,pink_banner:9,gray_banner:8,light_gray_banner:7,cyan_banner:6,purple_banner:5,blue_banner:4,brown_banner:3,green_banner:2,red_banner:1,black_banner:0},I6={0:"#1d1d21",1:"#b02e26",2:"#5e7c16",3:"#835432",4:"#3c44aa",5:"#8932b8",6:"#169c9c",7:"#9d9d97",8:"#474f52",9:"#f38baa",10:"#80c71f",11:"#fed83d",12:"#3ab3da",13:"#c74ebd",14:"#f9801d",15:"#f9fffe"};function M9(n){let e=n.replace("_wall_banner","_banner");return S9[e]??15}var T9=(n,e,t,r,i,s,o)=>{switch(n.fillStyle=t,e){case"bs":n.fillRect(r,i,s,o);break;case"ls":n.fillRect(r,i,s/3,o);break;case"rs":n.fillRect(r+s*2/3,i,s/3,o);break;case"ts":n.fillRect(r,i,s,o/3);break;case"ms":n.fillRect(r,i+o/3,s,o/3);break;case"drs":n.fillRect(r,i,s/2,o/2);break;case"dls":n.fillRect(r+s/2,i,s/2,o/2);break;case"ss":for(let l=0;l<s;l+=2)n.fillRect(r+l,i,1,o);break;case"cr":n.fillRect(r,i+o/3,s,o/3),n.fillRect(r+s/3,i,s/3,o);break;case"sc":n.fillRect(r,i+o/2-1,s,2),n.fillRect(r+s/2-1,i,2,o);break;default:n.fillRect(r,i,s,o)}};function C9(n,e){if(!e||e.length===0)return`banner_${n}_empty`;let t=e.map(r=>`${r.Pattern??"bs"}_${r.Color??0}`).join(",");return`banner_${n}_${t}`}var B9=(n,e,t=(r,i)=>Je(r,i))=>{let i=t(B6*1,P6*1),s=i.getContext("2d");if(s){if(s.imageSmoothingEnabled=!1,e?.Patterns&&e.Patterns.length>0)for(let o of e.Patterns){let l=o.Color??0,a=o.Pattern??"bs",v=I6[l]||I6[0];T9(s,a,v,0,0,B6*1,P6*1)}return i}},Hi=new Map;function L6(n,e,t){let r=M9(e),i=C9(r,t?.Patterns),s=Hi.get(i);if(s)return s.refCount++,s.texture;let o=B9(r,t);if(!o)return;let l=new st.Texture(o);return l.magFilter=st.NearestFilter,l.minFilter=st.NearestFilter,l.needsUpdate=!0,Hi.set(i,{texture:l,refCount:1}),l}function H6(n){for(let[e,t]of Hi.entries())if(t.texture===n){t.refCount--,t.refCount<=0&&(t.texture.dispose(),Hi.delete(e));return}}function O6(n,e,t,r,i=0,s=1,o=1){let c,u,f;t?(c=(-14.6+13.4)/2/16-.5,u=1-14.75/16-.5,f=1/2):(c=(1.4+29.4)/2/16,u=1-7.25/16-.5,f=0);let m=new st.MeshBasicMaterial({map:r,transparent:!0});C6(m,i,s,o);let g=new st.Mesh(new st.PlaneGeometry(.85,1.75),m);g.renderOrder=999;let b=.5/16,A=.25/16;t?g.position.set(0,c,u+A+.004):g.position.set(0,c,u+b/2+.004);let y=new st.Group;return y.rotation.set(0,-st.MathUtils.degToRad(e*(t?90:45/2)),0),y.add(g),y.bannerTexture=r,y.bannerMaterial=m,y.position.set(n.x+.5,n.y+f,n.z+.5),y}E();x();R();k();import*as or from"three";import P9 from"prismarine-chat";var l5=new Map;function I9(n,e,t){let r,i;return n&&"front_text"in n?(r=n.front_text?.messages??[],i=n.front_text?.color||"black"):(r=[n?.Text1,n?.Text2,n?.Text3,n?.Text4],i=n?.Color||"black"),`${e?1:0}|${t?1:0}|${i}|${r.join("\0")}`}function D6(n,e,t,r=!1){let i=I9(e,t,r),s=l5.get(i);if(s)return s.refCount++,s.texture;let o=P9(n.version),l=$2(e,t,o);if(!l)return;let a=new or.Texture(l);return a.magFilter=or.NearestFilter,a.minFilter=or.NearestFilter,a.needsUpdate=!0,l5.set(i,{texture:a,refCount:1}),a}function F6(n){for(let[e,t]of l5.entries())if(t.texture===n){t.refCount--,t.refCount<=0&&(t.texture.dispose(),l5.delete(e));return}}function z6(){for(let[,n]of l5)n.texture.dispose();l5.clear()}var Rt=class Rt{constructor(e,t,r,i,s=3){this.worldRenderer=e;this.scene=t;this.material=r;this.worldHeight=i;d(this,"renderOrigin",{x:0,y:0,z:0});d(this,"meshPool",[]);d(this,"activeSections",new Map);d(this,"sectionObjects",{});d(this,"waitingChunksToDisplay",{});d(this,"pendingNearReveal",new Map);d(this,"nearRevealTimers",new Map);d(this,"nearRevealGraceTimers",new Map);d(this,"poolSize");d(this,"maxPoolSize");d(this,"minPoolSize");d(this,"signHeadsRenderer");d(this,"blockEntityLightRegistry",new Li);d(this,"chunkBoxMaterial",new J.MeshBasicMaterial({color:0,transparent:!0,opacity:0}));d(this,"cubeShaderMaterial",null);d(this,"legacyShaderMaterial",null);d(this,"globalLegacyShaderMaterial",null);d(this,"globalLegacyBlendShaderMaterial",null);d(this,"_legacyCullFrustum",new J.Frustum);d(this,"_legacyCullProjScreen",new J.Matrix4);d(this,"_legacyCullBox",new J.Box3);d(this,"_legacyCullBoxMin",new J.Vector3);d(this,"_legacyCullBoxMax",new J.Vector3);d(this,"_visibleSectionSpans",[]);d(this,"legacyCullSections",new Map);d(this,"_lastCullFingerprint","");d(this,"lastBufferStateKey","");d(this,"cullDirty",!0);d(this,"_lastCullCamPos",new J.Vector3);d(this,"_lastCullCamQuat",new J.Quaternion);d(this,"_cullViewQuat",new J.Quaternion);d(this,"_cullCamInitialized",!1);d(this,"globalBlockBuffer",null);d(this,"globalLegacyBuffer",null);d(this,"globalLegacyBlendBuffer",null);d(this,"shaderSectionRaycastBoxes",new Map);d(this,"hits",0);d(this,"misses",0);d(this,"bypassPooling",!1);d(this,"renderTimes",[]);d(this,"maxRenderTimeSamples",30);d(this,"_performanceOverrideDistance");d(this,"lastPerformanceCheck",0);d(this,"performanceCheckInterval",2e3);this.updateViewDistance(s),this.signHeadsRenderer=new z1(e),this.initializePool()}get performanceOverrideDistance(){return this._performanceOverrideDistance??0}set performanceOverrideDistance(e){this._performanceOverrideDistance=e,this.updateSectionsVisibility()}initializePool(){for(let e=0;e<this.poolSize;e++){let t=new J.BufferGeometry,r=new J.Mesh(t,this.getLegacyShaderMaterial());r.visible=!1,r.matrixAutoUpdate=!1,r.name="pooled-section-mesh";let i={mesh:r,inUse:!1,lastUsedTime:0};this.meshPool.push(i)}}sectionHasRenderableContent(e){return e.positions.length>0||(e.blend?.positions.length??0)>0?!0:this.isShaderCubesGpuEnabled()?(e.shaderCubes?.count??0)>0:!1}isShaderCubesGpuEnabled(){return this.worldRenderer.shaderCubeBlocksEnabled()}syncCubeShaderUniforms(){if(!this.isShaderCubesGpuEnabled())return;let e=this.cubeShaderMaterial??this.getCubeShaderMaterial();if(!e)return;let t=this.material.map??null;e.uniforms.u_atlas.value=t;let r=Ri();if(!r)return;let{tintPalette:i}=r;i.isReady()||i.createTexture(),e.uniforms.u_tintPalette.value=i.getTexture(),e.uniforms.u_debugMode.value=this.worldRenderer.worldRendererConfig.shaderCubeDebugMode??0,e.needsUpdate=!0}syncLegacyShaderUniforms(){let e=this.material.map??null;this.legacyShaderMaterial&&(this.legacyShaderMaterial.uniforms.u_atlas.value=e,this.legacyShaderMaterial.needsUpdate=!0),this.globalLegacyShaderMaterial&&(this.globalLegacyShaderMaterial.uniforms.u_atlas.value=e,this.globalLegacyShaderMaterial.needsUpdate=!0),this.globalLegacyBlendShaderMaterial&&(this.globalLegacyBlendShaderMaterial.uniforms.u_atlas.value=e,this.globalLegacyBlendShaderMaterial.needsUpdate=!0)}setSkyLevel(e){let t=this.cubeShaderMaterial??(this.isShaderCubesGpuEnabled()?this.getCubeShaderMaterial():null);t&&_i(t,e),this.legacyShaderMaterial&&Ti(this.legacyShaderMaterial,e),this.globalLegacyShaderMaterial&&Ti(this.globalLegacyShaderMaterial,e),this.globalLegacyBlendShaderMaterial&&Ti(this.globalLegacyBlendShaderMaterial,e),this.blockEntityLightRegistry.setSkyLevel(e)}setShadingTheme(e,t){let r=this.cubeShaderMaterial??(this.isShaderCubesGpuEnabled()?this.getCubeShaderMaterial():null);r&&R1(r,e,t)}setBlockLightmapParams(e){let t=this.cubeShaderMaterial??(this.isShaderCubesGpuEnabled()?this.getCubeShaderMaterial():null);t&&Y3(t,e),this.legacyShaderMaterial&&Ci(this.legacyShaderMaterial,e),this.globalLegacyShaderMaterial&&Ci(this.globalLegacyShaderMaterial,e),this.globalLegacyBlendShaderMaterial&&Ci(this.globalLegacyBlendShaderMaterial,e),this.blockEntityLightRegistry.setLightmapParams(e)}getLegacyShaderMaterial(){return this.legacyShaderMaterial||(this.legacyShaderMaterial=l6(),this.syncLegacyShaderUniforms()),this.legacyShaderMaterial}getGlobalLegacyShaderMaterial(){return this.globalLegacyShaderMaterial||(this.globalLegacyShaderMaterial=v6(),this.syncLegacyShaderUniforms()),this.globalLegacyShaderMaterial}getGlobalLegacyBuffer(){return this.globalLegacyBuffer||(this.globalLegacyBuffer=new nr(this.getGlobalLegacyShaderMaterial(),this.scene),this.globalLegacyBuffer.setRenderOrigin(this.renderOrigin)),this.globalLegacyBuffer}getGlobalLegacyBlendShaderMaterial(){return this.globalLegacyBlendShaderMaterial||(this.globalLegacyBlendShaderMaterial=c6(),this.syncLegacyShaderUniforms()),this.globalLegacyBlendShaderMaterial}getGlobalLegacyBlendBuffer(){return this.globalLegacyBlendBuffer||(this.globalLegacyBlendBuffer=new nr(this.getGlobalLegacyBlendShaderMaterial(),this.scene,{name:"globalLegacyBlend",initialCapacityQuads:32e3,growthIncrementQuads:32e3}),this.globalLegacyBlendBuffer.setRenderOrigin(this.renderOrigin)),this.globalLegacyBlendBuffer}getRenderOrigin(){return this.renderOrigin}maybeRebase(e){let t=this.renderOrigin;if(Math.abs(e.x-t.x)<=Rt.REBASE_THRESHOLD&&Math.abs(e.y-t.y)<=Rt.REBASE_THRESHOLD&&Math.abs(e.z-t.z)<=Rt.REBASE_THRESHOLD)return;let r={x:Math.round(e.x/16)*16,y:Math.round(e.y/16)*16,z:Math.round(e.z/16)*16},i={x:r.x-t.x,y:r.y-t.y,z:r.z-t.z};this.globalLegacyBuffer?.rebase(i),this.globalLegacyBlendBuffer?.rebase(i);for(let s of this.activeSections.values()){let o=s.sectionKey;if(!o)continue;let l=this.sectionObjects[o];l&&H1(s.mesh,l.worldX??0,l.worldY??0,l.worldZ??0,r)}this.renderOrigin=r,this.globalLegacyBuffer?.setRenderOrigin(r),this.globalLegacyBlendBuffer?.setRenderOrigin(r)}sectionUsesPooledLegacyMesh(e){return this.activeSections.has(e)}registerLegacyCullSection(e,t,r,i){this.legacyCullSections.set(e,{worldX:t,worldY:r,worldZ:i})}maybeUnregisterLegacyCullSection(e){let t=this.globalLegacyBuffer?.hasSection(e)??!1,r=this.globalLegacyBlendBuffer?.hasSection(e)??!1;!t&&!r&&this.legacyCullSections.delete(e)}updatePooledLegacyCullState(e,t,r){for(let i of this.activeSections.values()){let s=i.sectionKey;if(!s)continue;let o=this.sectionObjects[s];o&&d6(i.mesh,o.worldX??0,o.worldY??0,o.worldZ??0,e,t,r,this._legacyCullFrustum,this._legacyCullBox,this._legacyCullBoxMin,this._legacyCullBoxMax)}}updateSectionCullAndSort(e,t,r,i){this._legacyCullProjScreen.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse),this._legacyCullFrustum.setFromProjectionMatrix(this._legacyCullProjScreen);let s=this._visibleSectionSpans;s.length=0;for(let[b]of this.legacyCullSections){let A=this.sectionObjects[b];if(!A?.visible||A.worldX===void 0)continue;let{visible:y,distSq:_}=Bi(A.worldX,A.worldY??0,A.worldZ??0,t,r,i,this._legacyCullFrustum,this._legacyCullBox,this._legacyCullBoxMin,this._legacyCullBoxMax);y&&s.push({key:b,distSq:_})}let o=this.globalLegacyBuffer,l=this.globalLegacyBlendBuffer,a=this.globalBlockBuffer,v=[];for(let b of s)o?.hasSection(b.key)&&v.push(b.key);v.sort();let c=s.filter(b=>l?.hasSection(b.key));c.sort((b,A)=>A.distSq-b.distSq);let u=c.map(b=>b.key),f=[],m=[];a&&a.forEachSectionSlot((b,A)=>{if(!this.sectionObjects[b]?.visible)return;let _=this.shaderSectionRaycastBoxes.get(b);if(!_)return;let{visible:S}=Bi(_.sectionCenterX,_.sectionCenterY,_.sectionCenterZ,t,r,i,this._legacyCullFrustum,this._legacyCullBox,this._legacyCullBoxMin,this._legacyCullBoxMax);if(!S)return;f.push(b);let C=a.getSectionDrawStart(b),T=a.getSectionDrawCount(b);C!==void 0&&T!==void 0&&m.push({start:C,count:T})}),f.sort();let g=[v.join(","),u.join(","),f.join(","),o?.getLayoutVersion()??0,l?.getLayoutVersion()??0,a?.getLayoutVersion()??0,o?.getUploadEpoch()??0,l?.getUploadEpoch()??0,a?.getUploadEpoch()??0].join("|");if(g===this._lastCullFingerprint&&!this.hasPendingBufferWork()){this.updatePooledLegacyCullState(t,r,i);return}if(this._lastCullFingerprint=g,o?.updateDrawSpans(s,"opaque"),l?.updateDrawSpans(s,"sortedBlend"),a){let b=y6(m,a.getHighWatermark(),a.canUseFullDrawShortcut(),(A,y)=>a.isRangeFullyUploaded(A,y),a.getPendingDirtyRanges());a.setVisibleSpans(b)}this.lastBufferStateKey=this.bufferStateKey(),this.updatePooledLegacyCullState(t,r,i)}bufferStateKey(){let e=this.globalBlockBuffer,t=this.globalLegacyBuffer,r=this.globalLegacyBlendBuffer;return[t?.getLayoutVersion()??0,t?.getUploadEpoch()??0,r?.getLayoutVersion()??0,r?.getUploadEpoch()??0,e?.getLayoutVersion()??0,e?.getUploadEpoch()??0].join("|")}markCullDirtyIfBufferStateChanged(){this.bufferStateKey()!==this.lastBufferStateKey&&this.markCullDirty()}markCullDirty(){this.cullDirty=!0}hasPendingBufferWork(){return[this.globalLegacyBuffer,this.globalLegacyBlendBuffer,this.globalBlockBuffer].some(t=>t!=null&&(t.hasPendingUploads()||t.hasPendingReplace()||t.getPendingMove()!=null))}updateCullDirtyFromCamera(e,t,r,i){if(e.getWorldQuaternion(this._cullViewQuat),!this._cullCamInitialized){this._lastCullCamPos.set(t,r,i),this._lastCullCamQuat.copy(this._cullViewQuat),this._cullCamInitialized=!0,this.cullDirty=!0;return}let s=this._lastCullCamPos.x!==t||this._lastCullCamPos.y!==r||this._lastCullCamPos.z!==i,o=this._lastCullCamQuat.x!==this._cullViewQuat.x||this._lastCullCamQuat.y!==this._cullViewQuat.y||this._lastCullCamQuat.z!==this._cullViewQuat.z||this._lastCullCamQuat.w!==this._cullViewQuat.w;(s||o)&&(this._lastCullCamPos.set(t,r,i),this._lastCullCamQuat.copy(this._cullViewQuat),this.markCullDirty())}clearCullDirty(){this.cullDirty=!1}setLegacyCameraOrigin(e,t,r){let i=this.renderOrigin;Mi(this.getLegacyShaderMaterial(),i,e,t,r),Mi(this.getGlobalLegacyShaderMaterial(),i,e,t,r),Mi(this.getGlobalLegacyBlendShaderMaterial(),i,e,t,r),this.globalLegacyBuffer?.setCameraOrigin(e,t,r),this.globalLegacyBlendBuffer?.setCameraOrigin(e,t,r);let s=this.cubeShaderMaterial;if(s){let{originDelta:o,cameraOriginFrac:l}=I0(i,e,t,r),a=wi(i),v=s.uniforms.u_originDelta;v?.value?.set&&v.value.set(o.x,o.y,o.z);let c=s.uniforms.u_cameraOriginFrac;c?.value?.set&&c.value.set(l.x,l.y,l.z);let u=s.uniforms.u_sectionOriginRel;u?.value?.set&&u.value.set(a.x,a.y,a.z)}}getCubeShaderMaterial(){if(!this.isShaderCubesGpuEnabled())return null;if(!this.cubeShaderMaterial){this.cubeShaderMaterial=yi(),this.syncCubeShaderUniforms();let e=this.worldRenderer.worldRendererConfig;R1(this.cubeShaderMaterial,e.shadingTheme,e.cardinalLight)}return this.cubeShaderMaterial}getGlobalBlockBuffer(){let e=this.getCubeShaderMaterial();return e?(this.globalBlockBuffer||(this.globalBlockBuffer=new Ii(e,this.scene)),this.globalBlockBuffer):null}shouldDeferLegacyOpaqueToPerSection(e){return this.shouldDeferShaderToPerSection(e)}shouldDeferShaderToPerSection(e){return this.worldRenderer.getModule("futuristicReveal")?.shouldDeferSectionGeometry?.(e)===!0}migrateDeferredShaderToGlobal(e){let t=this.sectionObjects[e];if(!t?.deferredShaderCubes)return;let{words:r,count:i}=t.deferredShaderCubes,s=t.worldX,o=t.worldY,l=t.worldZ;s!==void 0&&o!==void 0&&l!==void 0&&this.registerShaderSectionRaycastBox(e,r,i,s,o,l),this.getGlobalBlockBuffer()?.addSection(e,r,i),this.markCullDirty();let v=t.mesh===t.shaderMesh;t.shaderMesh&&(T1(t.shaderMesh),t.remove(t.shaderMesh),t.shaderMesh=void 0),delete t.deferredShaderCubes,v&&(t.mesh=void 0)}migrateDeferredLegacyToGlobal(e){let t=this.sectionObjects[e];if(t){if(t.deferredLegacyOpaque){let{positions:r,colors:i,skyLights:s,blockLights:o,uvs:l,indices:a}=t.deferredLegacyOpaque,v=t.worldX,c=t.worldY,u=t.worldZ;v!==void 0&&c!==void 0&&u!==void 0&&this.getGlobalLegacyBuffer().addSection(e,{positions:r,colors:i,skyLights:s,blockLights:o,uvs:l,indices:a},v,c,u)&&this.registerLegacyCullSection(e,v,c,u),delete t.deferredLegacyOpaque}if(t.deferredLegacyBlend){let{positions:r,colors:i,skyLights:s,blockLights:o,uvs:l,indices:a}=t.deferredLegacyBlend,v=t.worldX,c=t.worldY,u=t.worldZ;v!==void 0&&c!==void 0&&u!==void 0&&this.getGlobalLegacyBlendBuffer().addSection(e,{positions:r,colors:i,skyLights:s,blockLights:o,uvs:l,indices:a},v,c,u)&&this.registerLegacyCullSection(e,v,c,u),delete t.deferredLegacyBlend,t.hasBlendMesh=!1}if(!t.hasBlendMesh){let r=t.mesh===this.activeSections.get(e)?.mesh;this.releasePooledMesh(e),r&&(t.mesh=t.shaderMesh??void 0)}this.markCullDirty()}}registerShaderSectionRaycastBox(e,t,r,i,s,o){let l=S6(t,r,i,s,o);l?this.shaderSectionRaycastBoxes.set(e,{box:l,sectionCenterX:i,sectionCenterY:s,sectionCenterZ:o}):this.shaderSectionRaycastBoxes.delete(e)}unregisterShaderSectionRaycastBox(e){this.shaderSectionRaycastBoxes.delete(e)}uploadLegacyPooledMesh(e,t,r,i,s){let{mesh:o}=e,l=t;return this.updateGeometryAttribute(o.geometry,"position",l.positions,3),this.updateGeometryAttribute(o.geometry,"normal",l.normals,3),this.updateGeometryAttribute(o.geometry,"color",l.colors,3),this.updateGeometryAttribute(o.geometry,"a_skyLight",l.skyLights,1),this.updateGeometryAttribute(o.geometry,"a_blockLight",l.blockLights,1),this.updateGeometryAttribute(o.geometry,"uv",l.uvs,2),o.geometry.index=new J.BufferAttribute(l.indices,1),o.geometry.boundingBox=new J.Box3(new J.Vector3(-8,-8,-8),new J.Vector3(8,8,8)),o.geometry.boundingSphere=new J.Sphere(new J.Vector3(0,0,0),Math.sqrt(3*8**2)),H1(o,r,i,s,this.renderOrigin),o.visible=!1,o.name="mesh",e.lastUsedTime=performance.now(),o}acquirePooledSectionMesh(e){let t=this.activeSections.get(e);if(!t){if(t=this.acquireMesh(),!t)return null;this.activeSections.set(e,t),t.sectionKey=e}return t}updateSection(e,t){let r=t.positions.length>0,i=(t.blend?.positions.length??0)>0,s=r||i,o=t.shaderCubes,l=this.isShaderCubesGpuEnabled()&&(o?.count??0)>0,a=r&&this.shouldDeferLegacyOpaqueToPerSection(e),v=i&&this.shouldDeferLegacyOpaqueToPerSection(e),c=l&&this.shouldDeferShaderToPerSection(e),u=r&&!a,f=i&&!v,m=l&&!!o&&!c;if(!s&&!l)return this.releaseSection(e),null;let g=this.sectionObjects[e],b=g!=null;g&&this.cleanupSection(e,{forRemesh:!0}),b&&(m||this.globalBlockBuffer?.removeSection(e),u||this.globalLegacyBuffer?.removeSection(e),f||this.globalLegacyBlendBuffer?.removeSection(e),l&&o||this.unregisterShaderSectionRaycastBox(e),!u&&!f&&this.maybeUnregisterLegacyCullSection(e)),i||this.releasePooledMesh(e);let A,y,_,S=!1;if(r){let W={positions:t.positions,colors:t.colors,skyLights:t.skyLights,blockLights:t.blockLights,uvs:t.uvs,indices:t.indices};if(a){if(y={positions:new Float32Array(W.positions),colors:new Float32Array(W.colors),skyLights:new Float32Array(W.skyLights),blockLights:new Float32Array(W.blockLights),uvs:new Float32Array(W.uvs),indices:W.indices instanceof Uint32Array?new Uint32Array(W.indices):new Uint16Array(W.indices)},!i){let Q=this.acquirePooledSectionMesh(e);if(!Q)return null;A=this.uploadLegacyPooledMesh(Q,t,t.sx,t.sy,t.sz)}}else if(this.getGlobalLegacyBuffer().addSection(e,W,t.sx,t.sy,t.sz))this.registerLegacyCullSection(e,t.sx,t.sy,t.sz);else{let K=this.acquirePooledSectionMesh(e);if(!K)return null;A=this.uploadLegacyPooledMesh(K,t,t.sx,t.sy,t.sz)}}if(i&&t.blend){let W={positions:t.blend.positions,colors:t.blend.colors,skyLights:t.blend.skyLights,blockLights:t.blend.blockLights,uvs:t.blend.uvs,indices:t.blend.indices};if(v){_={positions:new Float32Array(W.positions),colors:new Float32Array(W.colors),skyLights:new Float32Array(W.skyLights),blockLights:new Float32Array(W.blockLights),uvs:new Float32Array(W.uvs),indices:W.indices instanceof Uint32Array?new Uint32Array(W.indices):new Uint16Array(W.indices)};let Q=this.acquirePooledSectionMesh(e);if(!Q)return null;let K=this.uploadLegacyPooledMesh(Q,t.blend,t.sx,t.sy,t.sz);A=A??K,S=!0}else if(this.getGlobalLegacyBlendBuffer().addSection(e,W,t.sx,t.sy,t.sz))this.registerLegacyCullSection(e,t.sx,t.sy,t.sz);else{let K=this.acquirePooledSectionMesh(e);if(!K)return null;let X=this.uploadLegacyPooledMesh(K,t.blend,t.sx,t.sy,t.sz);A=A??X,S=!0}}let C=l?this.getCubeShaderMaterial():null,T;l&&o&&(c&&C?(T=Si(o,C),T.visible=!0):this.getGlobalBlockBuffer()?.addSection(e,o.words,o.count)),g=new J.Group,A&&(g.add(A),g.mesh=A),T&&(g.add(T),g.shaderMesh=T,o&&(g.deferredShaderCubes={words:o.words,count:o.count}),g.mesh||(g.mesh=T)),y&&(g.deferredLegacyOpaque=y),_&&(g.deferredLegacyBlend=_),l&&o&&this.registerShaderSectionRaycastBox(e,o.words,o.count,t.sx,t.sy,t.sz);let P=0;r&&(P+=t.positions.length/3/4),i&&t.blend&&(P+=t.blend.positions.length/3/4),l&&o&&(P+=o.count),g.tilesCount=P,g.hasBlendMesh=S,g.blocksCount=t.blocksCount,g.worldX=t.sx,g.worldY=t.sy,g.worldZ=t.sz,g.sectionKey=e,g.name="chunk";try{if(Object.keys(t.signs).length>0){let W=new J.Group;W.name="signs";for(let[Q,{isWall:K,isHanging:X,rotation:ae}]of Object.entries(t.signs)){let oe=this.worldRenderer.blockEntities[Q];if(!oe)continue;let[ue,fe,me]=Q.split(","),ne=this.signHeadsRenderer.renderSign(new F1(+ue,+fe,+me),ae,K,X,Oi.simplify(oe));ne&&W.add(ne)}g.add(W),g.signsContainer=W}if(Object.keys(t.heads).length>0){let W=new J.Group;W.name="heads";for(let[Q,{isWall:K,rotation:X}]of Object.entries(t.heads)){let ae=this.worldRenderer.blockEntities[Q];if(!ae)continue;let[oe,ue,fe]=Q.split(","),me=this.signHeadsRenderer.renderHead(new F1(+oe,+ue,+fe),X,K,Oi.simplify(ae));me&&W.add(me)}g.add(W),g.headsContainer=W}if(Object.keys(t.banners).length>0){let W=new J.Group;W.name="banners",g.bannersContainer=W,g.add(W);for(let[Q,K]of Object.entries(t.banners)){let{isWall:X,rotation:ae,blockName:oe,blockLightNorm:ue=0,skyLightNorm:fe=1}=K,me=this.worldRenderer.blockEntities[Q];if(!me)continue;let[ne,Y,le]=Q.split(","),ge=L6(this.worldRenderer,oe,Oi.simplify(me));if(!ge)continue;let je=this.blockEntityLightRegistry.getSkyLevel(),xe=O6(new F1(+ne,+Y,+le),ae,X,ge,ue,fe,je);xe.bannerMaterial&&this.blockEntityLightRegistry.register({material:xe.bannerMaterial,blockLightNorm:ue,skyLightNorm:fe});let{x:ot,y:be,z:ct}=xe.position;this.worldRenderer.sceneOrigin.track(xe),xe.position.set(ot,be,ct),W.add(xe)}}}catch{}this.sectionObjects[e]=g,this.scene.add(g),g.matrixAutoUpdate=!1,this.worldRenderer.displayOptions?.inWorldRenderingConfig?.showChunkBorders&&this.updateBoxHelper(e,!0);let B=e.split(","),L=`${B[0]},${B[2]}`,V=!!this.worldRenderer.displayOptions?.inWorldRenderingConfig?._renderByChunks,z=!!this.worldRenderer.worldRendererConfig?.wasmMesher;if((V||z)&&!this.worldRenderer.finishedChunks[L]){g.visible=!1,g._waitingForChunkDisplay=!0;let W=this.waitingChunksToDisplay[L]??(this.waitingChunksToDisplay[L]=[]);W.includes(e)||W.push(e)}return this.markCullDirty(),g}finishChunkDisplay(e){if(!this.waitingChunksToDisplay[e]){this.tryRevealPending();return}if(this.isWasmGateActive()&&this.isBlockedByNearer(e,0)){this.pendingNearReveal.set(e,Date.now()),this.armNearRevealTimer(e),this.armExpectedGraceTimer(e),this.tryRevealPending();return}this.flushChunkDisplay(e),this.tryRevealPending()}flushChunkDisplay(e){let t=this.waitingChunksToDisplay[e];if(this.pendingNearReveal.delete(e),this.clearNearRevealTimer(e),this.clearExpectedGraceTimer(e),!!t){for(let r of t){let i=this.sectionObjects[r];i&&(i._waitingForChunkDisplay=!1,i.visible=!0)}delete this.waitingChunksToDisplay[e],this.markCullDirty()}}tryRevealPending(){if(this.pendingNearReveal.size===0)return;let e=Date.now();for(let[t,r]of[...this.pendingNearReveal])this.isBlockedByNearer(t,e-r)||this.flushChunkDisplay(t)}onChunkRemovedFromGate(e){this.pendingNearReveal.delete(e),this.clearNearRevealTimer(e),this.clearExpectedGraceTimer(e),delete this.waitingChunksToDisplay[e],this.tryRevealPending()}isWasmGateActive(){return!!this.worldRenderer.worldRendererConfig?.wasmMesher}isBlockedByNearer(e,t){let r=this.worldRenderer.viewerChunkPosition;if(!r)return!1;let i=e.split(",");if(i.length!==2)return!1;let s=Number(i[0]),o=Number(i[1]),l=Math.floor(r.x/16),a=Math.floor(r.z/16),v=(s>>4)-l,c=(o>>4)-a,u=v*v+c*c;if(u===0)return!1;let f=this.worldRenderer.finishedChunks,m=this.worldRenderer.loadedChunks,g=this.worldRenderer.viewDistance;if(t<Rt.EXPECTED_NEAR_GRACE_MS&&g>0){let A=g*g,y=Math.min(g,Math.ceil(Math.sqrt(Math.max(0,u-1))));for(let _=-y;_<=y;_++)for(let S=-y;S<=y;S++){let C=_*_+S*S;if(C>=u||C>A)continue;let T=l+_<<4,P=a+S<<4,B=`${T},${P}`;if(B!==e&&m[B]&&!f[B])return!0}return!1}for(let A in m){if(A===e||f[A])continue;let y=A.split(",");if(y.length!==2)continue;let _=(Number(y[0])>>4)-l,S=(Number(y[1])>>4)-a;if(_*_+S*S<u)return!0}return!1}armNearRevealTimer(e){if(this.nearRevealTimers.has(e))return;let t=setTimeout(()=>{this.nearRevealTimers.delete(e),this.pendingNearReveal.has(e)&&(this.flushChunkDisplay(e),this.tryRevealPending())},Rt.NEAR_REVEAL_TIMEOUT_MS);this.nearRevealTimers.set(e,t)}clearNearRevealTimer(e){let t=this.nearRevealTimers.get(e);t&&(clearTimeout(t),this.nearRevealTimers.delete(e))}armExpectedGraceTimer(e){if(this.nearRevealGraceTimers.has(e))return;let t=setTimeout(()=>{this.nearRevealGraceTimers.delete(e),this.pendingNearReveal.has(e)&&this.tryRevealPending()},Rt.EXPECTED_NEAR_GRACE_MS+50);this.nearRevealGraceTimers.set(e,t)}clearExpectedGraceTimer(e){let t=this.nearRevealGraceTimers.get(e);t&&(clearTimeout(t),this.nearRevealGraceTimers.delete(e))}cleanupSection(e,t){let r=this.sectionObjects[e];if(r){if(r._waitingForChunkDisplay){let i=e.split(","),s=`${i[0]},${i[2]}`,o=this.waitingChunksToDisplay[s];if(o){let l=o.indexOf(e);l!==-1&&o.splice(l,1),o.length===0&&delete this.waitingChunksToDisplay[s]}}if(r.bannersContainer){for(let i of r.bannersContainer.children){let s=i;s.bannerMaterial&&this.blockEntityLightRegistry.unregister(s.bannerMaterial),s.bannerTexture&&H6(s.bannerTexture)}this.disposeContainer(r.bannersContainer)}if(t?.forRemesh||(this.globalBlockBuffer?.removeSection(e),this.globalLegacyBuffer?.removeSection(e),this.globalLegacyBlendBuffer?.removeSection(e),this.maybeUnregisterLegacyCullSection(e),this.unregisterShaderSectionRaycastBox(e)),this.markCullDirty(),delete r.deferredLegacyOpaque,delete r.deferredLegacyBlend,r.shaderMesh&&(T1(r.shaderMesh),r.shaderMesh=void 0),delete r.deferredShaderCubes,r.signsContainer){for(let i of r.signsContainer.children){let s=i;s.signTexture&&F6(s.signTexture)}this.disposeContainer(r.signsContainer,!1)}if(r.headsContainer&&this.disposeContainer(r.headsContainer),this.worldRenderer.sceneOrigin.removeAndUntrackAll(r),this.scene.remove(r),r.boxHelper){this.worldRenderer.sceneOrigin.removeAndUntrack(r.boxHelper),this.scene.remove(r.boxHelper),r.boxHelper.geometry.dispose();let i=r.boxHelper.material;if(Array.isArray(i))for(let s of i)s.dispose();else i.dispose();r.boxHelper=void 0}delete this.sectionObjects[e],t?.forRemesh||this.worldRenderer.getModule("futuristicReveal")?.onSectionRemoved?.(e)}}releasePooledMesh(e){let t=this.activeSections.get(e);t&&(t.mesh.visible=!1,t.inUse=!1,t.sectionKey=void 0,t.lastUsedTime=0,this.clearGeometry(t.mesh.geometry),this.activeSections.delete(e),this.cleanupExcessMeshes())}releaseSection(e){this.cleanupSection(e);let t=this.activeSections.get(e);return t?(t.mesh.visible=!1,t.inUse=!1,t.sectionKey=void 0,t.lastUsedTime=0,this.clearGeometry(t.mesh.geometry),this.activeSections.delete(e),this.cleanupExcessMeshes(),!0):!1}getSectionObject(e){return this.sectionObjects[e]}updateBoxHelper(e,t,r=this.chunkBoxMaterial){let i=this.sectionObjects[e];if(i)if(t){if(!i.boxHelper){let s=new J.Mesh(new J.BoxGeometry(16,16,16),r),o=new J.BoxHelper(s,16776960);o.name="helper";let l=i.worldX??0,a=i.worldY??0,v=i.worldZ??0;this.worldRenderer.sceneOrigin.track(o,{updateMatrix:!0}),o.position.set(l,a,v),o.updateMatrix(),this.scene.add(o),i.boxHelper=o}i.boxHelper.visible=!0}else i.boxHelper&&(i.boxHelper.visible=!1)}updateAllBoxHelpers(e){for(let t of Object.keys(this.sectionObjects))this.updateBoxHelper(t,e)}getSectionMesh(e){return this.activeSections.get(e)?.mesh}hasSection(e){return this.activeSections.has(e)}updateViewDistance(e){let t=(e*2+1)**2,r=this.worldHeight/16,i=5;if(this.minPoolSize=Math.floor(t*i),this.maxPoolSize=Math.floor(t*r)+1,this.poolSize??(this.poolSize=this.minPoolSize),this.minPoolSize>this.poolSize){let s=Math.min(this.minPoolSize,this.maxPoolSize);this.expandPool(s)}}getGlobalBufferStats(){let e=r=>r?{used:r.getHighWatermark(),capacity:r.getCapacityQuads(),sections:r.getSectionCount(),usedBytes:r.getUsedMemoryBytes(),capacityBytes:r.getMemoryBytes()}:null,t=this.globalBlockBuffer;return{shaderFaces:t?{used:t.getHighWatermark(),capacity:t.getCapacityFaces(),sections:t.getSectionCount(),usedBytes:t.getUsedMemoryBytes(),capacityBytes:t.getMemoryBytes()}:null,legacyOpaque:e(this.globalLegacyBuffer),legacyBlend:e(this.globalLegacyBlendBuffer)}}getStats(){let e=this.meshPool.filter(i=>!i.inUse).length,t=this.hits+this.misses>0?(this.hits/(this.hits+this.misses)*100).toFixed(1):"0",r=this.getEstimatedMemoryUsage();return{poolSize:this.poolSize,activeCount:this.activeSections.size,freeCount:e,hitRate:`${t}%`,hits:this.hits,misses:this.misses,memoryUsage:r}}getTotalTiles(){return Object.values(this.sectionObjects).reduce((e,t)=>e+(t.tilesCount||0),0)}getTotalBlocks(){return Object.values(this.sectionObjects).reduce((e,t)=>e+(t.blocksCount||0),0)}getEstimatedMemoryUsage(){let e=0,t=0,r=0,i=0,s=0,o=0,l=0,a=this.globalBlockBuffer?.mesh.geometry;if(a)for(let f of["a_w0","a_w1","a_w2","a_w3"]){let m=a.getAttribute(f);if(m){let g=m.array.byteLength;l+=g,e+=g}}let v=this.globalLegacyBuffer?.getMemoryBytes()??0,c=this.globalLegacyBlendBuffer?.getMemoryBytes()??0;e+=v+c,t+=v+c;for(let f of Object.values(this.sectionObjects)){let m=f.shaderMesh?.geometry;if(m)for(let g of["a_w0","a_w1","a_w2","a_w3"]){let b=m.getAttribute(g);if(b){let A=b.array.byteLength;l+=A,e+=A}}}for(let f of this.meshPool)if(f.inUse&&f.mesh.geometry){let{geometry:m}=f.mesh,g=m.getAttribute("position");if(g){let _=g.array.byteLength;t+=_,e+=_}let b=m.getAttribute("normal");if(b){let _=b.array.byteLength;r+=_,e+=_}let A=m.getAttribute("color");if(A){let _=A.array.byteLength;i+=_,e+=_}let y=m.getAttribute("uv");if(y){let _=y.array.byteLength;s+=_,e+=_}if(m.index){let _=m.index.array.byteLength;o+=_,e+=_}}return{total:`${(e/(1024*1024)).toFixed(2)} MB`,breakdown:{position:`${(t/(1024*1024)).toFixed(2)} MB`,normal:`${(r/(1024*1024)).toFixed(2)} MB`,color:`${(i/(1024*1024)).toFixed(2)} MB`,uv:`${(s/(1024*1024)).toFixed(2)} MB`,index:`${(o/(1024*1024)).toFixed(2)} MB`,shaderInstances:`${(l/(1024*1024)).toFixed(2)} MB`}}}dispose(){let e=[...this.activeSections.keys()];for(let t of e)this.releaseSection(t);this.signHeadsRenderer.dispose();for(let t of this.meshPool)t.mesh.geometry.dispose();this.meshPool.length=0,this.activeSections.clear(),this.chunkBoxMaterial.dispose(),this.shaderSectionRaycastBoxes.clear(),this.lastBufferStateKey="",this.globalBlockBuffer?.dispose(),this.globalBlockBuffer=null,this.globalLegacyBuffer?.dispose(),this.globalLegacyBuffer=null,this.globalLegacyBlendBuffer?.dispose(),this.globalLegacyBlendBuffer=null,this.cubeShaderMaterial?.dispose(),this.cubeShaderMaterial=null,this.legacyShaderMaterial?.dispose(),this.legacyShaderMaterial=null,this.globalLegacyShaderMaterial?.dispose(),this.globalLegacyShaderMaterial=null,this.globalLegacyBlendShaderMaterial?.dispose(),this.globalLegacyBlendShaderMaterial=null,this.pendingNearReveal.clear();for(let t of this.nearRevealTimers.values())clearTimeout(t);this.nearRevealTimers.clear();for(let t of this.nearRevealGraceTimers.values())clearTimeout(t);this.nearRevealGraceTimers.clear()}acquireMesh(){if(this.bypassPooling){let t={mesh:new J.Mesh(new J.BufferGeometry,this.getLegacyShaderMaterial()),inUse:!0,lastUsedTime:performance.now()};return this.meshPool.push(t),this.poolSize++,t}for(let t of this.meshPool)if(!t.inUse)return t.inUse=!0,t.lastUsedTime=performance.now(),this.hits++,t;this.misses++;let e=Math.min(this.poolSize+16,this.maxPoolSize);e<=this.meshPool.length&&(e=this.meshPool.length+8,this.maxPoolSize=e),this.expandPool(e);for(let t=this.meshPool.length-1;t>=0;t--){let r=this.meshPool[t];if(!r.inUse)return r.inUse=!0,r.lastUsedTime=performance.now(),r}throw new Error("ChunkMeshManager: Failed to acquire mesh after pool expansion")}expandPool(e){let t=this.meshPool.length;this.poolSize=e;for(let r=t;r<e;r++){let i=new J.BufferGeometry,s=new J.Mesh(i,this.getLegacyShaderMaterial());s.visible=!1,s.matrixAutoUpdate=!1,s.name="pooled-section-mesh";let o={mesh:s,inUse:!1,lastUsedTime:0};this.meshPool.push(o)}}updateGeometryAttribute(e,t,r,i){let s=e.getAttribute(t);s&&s.count===r.length/i?(s.array.set(r),s.needsUpdate=!0):e.setAttribute(t,new J.BufferAttribute(r,i))}clearGeometry(e){let t=["position","normal","color","a_skyLight","a_blockLight","uv"];for(let r of t)e.hasAttribute(r)&&e.deleteAttribute(r);e.index&&e.setIndex(null),e.boundingBox=null,e.boundingSphere=null}cleanupExcessMeshes(){if(this.poolSize>this.maxPoolSize){let e=this.meshPool.filter(t=>!t.inUse).length;if(e>0){let t=Math.min(this.poolSize-this.maxPoolSize,e);for(let r=0;r<t;r++){let i=this.meshPool.findIndex(s=>!s.inUse);i!==-1&&(this.meshPool[i].mesh.geometry.dispose(),this.meshPool.splice(i,1),this.poolSize--)}}}}disposeContainer(e,t=!0){Se(e,t)}recordRenderTime(e){this.renderTimes.push(e),this.renderTimes.length>this.maxRenderTimeSamples&&this.renderTimes.shift();let t=performance.now();t-this.lastPerformanceCheck>this.performanceCheckInterval&&(this.checkPerformance(),this.lastPerformanceCheck=t)}getEffectiveRenderDistance(){return this.performanceOverrideDistance||this.worldRenderer.viewDistance}resetPerformanceOverride(){this.performanceOverrideDistance=void 0,this.renderTimes.length=0}getAverageRenderTime(){return this.renderTimes.length===0?0:this.renderTimes.reduce((e,t)=>e+t,0)/this.renderTimes.length}checkPerformance(){if(this.renderTimes.length<this.maxRenderTimeSamples)return;let e=this.getAverageRenderTime(),t=16.67,r=t*1.5;if(e>r){let i=this.worldRenderer.viewDistance,s=Math.max(1,Math.floor(i*.8));(!this.performanceOverrideDistance||s<this.performanceOverrideDistance)&&(this.performanceOverrideDistance=s)}else if(this.performanceOverrideDistance&&e<t*1.1){let i=this.worldRenderer.viewDistance,s=Math.min(i,this.performanceOverrideDistance+1);s!==this.performanceOverrideDistance&&(this.performanceOverrideDistance=s>=i?void 0:s)}}updateSectionsVisibility(){let e=this.worldRenderer.cameraSectionPos;for(let[t,r]of Object.entries(this.sectionObjects)){if(r._waitingForChunkDisplay){r.visible=!1;continue}if(!this.performanceOverrideDistance){r.visible=!0;continue}let[i,s,o]=t.split(",").map(Number),l={x:i/16,y:s/16,z:o/16},a=l.x-e.x,v=l.z-e.z,c=Math.floor(Math.hypot(a,v));r.visible=c<=this.performanceOverrideDistance}}};d(Rt,"REBASE_THRESHOLD",65536),d(Rt,"NEAR_REVEAL_TIMEOUT_MS",5e3),d(Rt,"EXPECTED_NEAR_GRACE_MS",1500);var ar=Rt,z1=class{constructor(e){this.worldRendererThree=e}dispose(){z6()}renderHead(e,t,r,i){let s;if(i.SkullOwner?s=i.SkullOwner.Properties?.textures?.[0]?.Value:s=i.profile?.properties?.find(o=>o.name==="textures")?.value,!!s)try{let l=JSON.parse(O.from(s,"base64").toString()).textures?.SKIN?.url,{skinTexturesProxy:a}=this.worldRendererThree.worldRendererConfig;a&&(l=l?.replace("http://textures.minecraft.net/",a).replace("https://textures.minecraft.net/",a));let v=Kt(this.worldRendererThree,l,Jt.head),c=new J.Group;return r&&v.position.set(0,.3125,.3125),v.position.y-=23/16,c.add(v),this.worldRendererThree.sceneOrigin.track(c),c.position.set(e.x+.5,e.y+.045,e.z+.5),c.rotation.set(0,-J.MathUtils.degToRad(t*(r?90:45/2)),0),c.scale.set(.8,.8,.8),c}catch{}}renderSign(e,t,r,i,s){let o=D6(this.worldRendererThree,s,i);if(!o)return;let l=new J.Mesh(new J.PlaneGeometry(1,1),new J.MeshBasicMaterial({map:o,transparent:!0}));l.renderOrder=999;let a=7/16,v=i?1.3:1;l.scale.set(1*v,a*v,1*v);let c=(i?2:1.5)/16,u=.25/16;r&&!i?l.position.set(0,0,-.5+c+u+1e-4):l.position.set(0,0,c/2+1e-4);let f=new J.Group;f.rotation.set(0,-J.MathUtils.degToRad(t*(r?90:45/2)),0),f.add(l),f.signTexture=o;let m=(i?10:8)/16,g=(i?0:r?4.333:9.333)/16,b=m/2+g;return this.worldRendererThree.sceneOrigin.track(f),f.position.set(e.x+.5,e.y+b,e.z+.5),f}};E();x();R();k();var Di=(n,e)=>e===0?1/0:e<0?Di(-n,-e):(1-(n-Math.floor(n)))/e,L9=(n,e,t,r,i,s,o,l,a,v,c,u)=>{let f=o-c,m=l-c,g=a-c,b=o+1+c,A=l+1+c,y=a+1+c,_=M6(n,e,t,r,i,s,f,m,g,b,A,y,v);if(_===void 0&&(_=T6(n,e,t,r,i,s,f,m,g,b,A,y,v)),_!==void 0)return Math.max(u,_)};function U6(n,e,t,r,i,s,o,l,a,v){if(o<=0)return;let c=Math.floor(n),u=Math.floor(e),f=Math.floor(t),m=r>0?1:r<0?-1:0,g=i>0?1:i<0?-1:0,b=s>0?1:s<0?-1:0,A=m!==0?Math.abs(1/r):1/0,y=g!==0?Math.abs(1/i):1/0,_=b!==0?Math.abs(1/s):1/0,S=m!==0?Di(n,r):1/0,C=g!==0?Di(e,i):1/0,T=b!==0?Di(t,s):1/0,P=(V,z,W)=>{if(!v(V,z,W))return;let Q=L9(n,e,t,r,i,s,V,z,W,o,l,a);if(!(Q===void 0||Q>o))return{distance:Q,blockX:V,blockY:z,blockZ:W}},B=P(c,u,f);if(B)return B;let L=0;for(;L<=o&&(S<C?S<T?(c+=m,L=S,S+=A):(f+=b,L=T,T+=_):C<T?(u+=g,L=C,C+=y):(f+=b,L=T,T+=_),!(L>o));)if(B=P(c,u,f),B)return B}E();x();R();k();E();x();R();k();import*as e0 from"three";var Fi={},G6=!1;function H9(){if(G6)return;let n=globalThis.loadedData?.tints;if(n){for(let e of Object.keys(n))Fi[e]=O9(n[e]);G6=!0}}function O9(n){let e={},t=V6(n.default??16777215);if(n.data)for(let r of n.data){let i=V6(r.color);for(let s of r.keys)e[s]=i}return new Proxy(e,{get(r,i){return r[i]??t}})}function V6(n){return[(n>>16&255)/255,(n>>8&255)/255,(n&255)/255]}function W6(n,e){return H9(),n==="grass_block"?[1,1,1]:n==="redstone_wire"?[1,1,1]:n==="birch_leaves"||n==="spruce_leaves"||n==="lily_pad"?Fi.constant?.[n]??[1,1,1]:n.includes("leaves")||n==="vine"?Fi.foliage?.[e]??[1,1,1]:["short_grass","tall_grass","fern","large_fern","sugar_cane","grass"].includes(n)?Fi.grass?.[e]??[1,1,1]:[1,1,1]}var D9=512,U1=1/20,G1=class{constructor(e){this.worldRenderer=e;d(this,"particles",[]);d(this,"sharedMaterial");d(this,"enabled",!1);d(this,"tickAccumulator",0);d(this,"nextParticleIndex",0);d(this,"render",e=>{if(!this.enabled)return;for(this.tickAccumulator+=e;this.tickAccumulator>=U1;)this.tickAccumulator-=U1,this.tickPhysics();let t=this.tickAccumulator/U1;this.updateVisuals(t)})}enable(){this.enabled||(this.enabled=!0,this.ensureMaterial())}disable(){this.enabled&&(this.enabled=!1)}dispose(){for(let e of this.particles)e.active&&this.worldRenderer.sceneOrigin.removeAndUntrack(e.mesh),e.mesh.geometry.dispose();this.particles=[],this.sharedMaterial?.dispose(),this.sharedMaterial=void 0,this.nextParticleIndex=0}spawnBlockBreakParticles(e,t,r,i,s,o="plains"){if(!this.enabled)return;let l=this.resolveBlockTexture(i);if(!l)return;let a=W6(i,o);for(let v=0;v<4;v++)for(let c=0;c<4;c++)for(let u=0;u<4;u++){let f=e+(v+.5)/4,m=t+(c+.5)/4,g=r+(u+.5)/4,b=f-e-.5,A=m-t-.5,y=g-r-.5;b+=(Math.random()*2-1)*.4,A+=(Math.random()*2-1)*.4,y+=(Math.random()*2-1)*.4;let _=(Math.random()+Math.random()+1)*.15,S=Math.sqrt(b*b+A*A+y*y),C=b/S*_*.4,T=A/S*_*.4+.1,P=y/S*_*.4,B=Math.floor(4/(Math.random()*.9+.1));this.createParticle(f,m,g,C,T,P,B,l,s,e,r,1,a)}}tickPhysics(){for(let e of this.particles){if(!e.active)continue;if(e.prevX=e.x,e.prevY=e.y,e.prevZ=e.z,e.age++,e.age>=e.maxAge){this.deactivateParticle(e);continue}e.yd-=.04,e.x+=e.xd,e.y+=e.yd,e.z+=e.zd;let t=this.getFloorY(e);e.y<=t?(e.y=t,e.yd=0,e.onGround=!0):e.onGround=!1,e.xd*=.98,e.yd*=.98,e.zd*=.98,e.onGround&&(e.xd*=.7,e.zd*=.7)}}updateVisuals(e){let t=this.worldRenderer.camera.position;for(let r of this.particles){if(!r.active)continue;let i=r.prevX+(r.x-r.prevX)*e,s=r.prevY+(r.y-r.prevY)*e,o=r.prevZ+(r.z-r.prevZ)*e;r.mesh.position.set(i,s,o),r.mesh.lookAt(t.x,t.y,t.z)}}spawnCrackParticle(e,t,r,i,s,o,l="plains"){if(!this.enabled)return;let a=this.resolveBlockTexture(s);if(!a)return;let v=W6(s,l),c=e+Math.random()*.8+.1,u=t+Math.random()*.8+.1,f=r+Math.random()*.8+.1;switch(i){case 0:u=t-.1;break;case 1:u=t+1+.1;break;case 2:f=r-.1;break;case 3:f=r+1+.1;break;case 4:c=e-.1;break;case 5:c=e+1+.1;break}let m=(Math.random()*2-1)*.4*.2,g=(Math.random()*2-1)*.4*.2+.1*.2,b=(Math.random()*2-1)*.4*.2,A=Math.floor(4/(Math.random()*.9+.1));this.createParticle(c,u,f,m,g,b,A,a,o,e,r,.6,v)}createParticle(e,t,r,i,s,o,l,a,v,c,u,f=1,m=[1,1,1]){this.ensureMaterial();let g=this.findInactiveParticle();g||(this.particles.length<D9?g=this.allocateParticle():g=this.recycleOldest());let b=Math.floor(Math.random()*4),A=Math.floor(Math.random()*4),y=a.u+b/4*a.su,_=a.v+A/4*a.sv,S=a.su/4,C=a.sv/4;this.setGeometryUVs(g.mesh.geometry,y,_,S,C),g.active=!0,g.x=e,g.y=t,g.z=r,g.prevX=e,g.prevY=t,g.prevZ=r,g.xd=i,g.yd=s,g.zd=o,g.age=0,g.maxAge=l,g.onGround=!1,g.floorMap=v,g.blockX=Math.floor(c),g.blockZ=Math.floor(u);let T=.1*(.5+Math.random()*.5)*2*f;g.mesh.scale.set(T,T,T),g.mesh.position.set(e,t,r),g.mesh.visible=!0;let P=.6*m[0],B=.6*m[1],L=.6*m[2],V=new Float32Array([P,B,L,P,B,L,P,B,L,P,B,L]),z=g.mesh.geometry.getAttribute("color");z?(z.set(V),z.needsUpdate=!0):g.mesh.geometry.setAttribute("color",new e0.Float32BufferAttribute(V,3)),this.worldRenderer.sceneOrigin.addAndTrack(g.mesh)}allocateParticle(){let e=new e0.PlaneGeometry(1,1),t=new e0.Mesh(e,this.sharedMaterial);t.visible=!1;let r={mesh:t,active:!1,x:0,y:0,z:0,prevX:0,prevY:0,prevZ:0,xd:0,yd:0,zd:0,age:0,maxAge:0,onGround:!1,floorMap:[],blockX:0,blockZ:0};return this.particles.push(r),r}findInactiveParticle(){for(let e=0;e<this.particles.length;e++){let t=(this.nextParticleIndex+e)%this.particles.length;if(!this.particles[t].active)return this.nextParticleIndex=(t+1)%this.particles.length,this.particles[t]}}recycleOldest(){let e=this.particles[0];for(let t of this.particles)t.age>e.age&&(e=t);return this.deactivateParticle(e),e}deactivateParticle(e){e.active&&(e.active=!1,e.mesh.visible=!1,this.worldRenderer.sceneOrigin.removeAndUntrack(e.mesh))}getFloorY(e){let t=Math.floor(e.x)-e.blockX,r=Math.floor(e.z)-e.blockZ;return t=Math.max(-2,Math.min(2,t)),r=Math.max(-2,Math.min(2,r)),e.floorMap[(r+2)*5+(t+2)]}resolveBlockTexture(e){let t=this.worldRenderer.resourcesManager.currentResources;if(!t)return null;let r=t.blocksAtlasJson,i=r.textures;if(i[e])return this.extractUV(i[e],r);for(let s of["_side","_top","_front","_0",""]){let o=e+s;if(i[o])return this.extractUV(i[o],r)}for(let s of Object.keys(i))if(s.startsWith(e))return this.extractUV(i[s],r);return null}extractUV(e,t){return{u:e.u,v:e.v,su:e.su??t.suSv,sv:e.sv??t.suSv}}setGeometryUVs(e,t,r,i,s){let o=e.getAttribute("uv");o.setXY(0,t,r),o.setXY(1,t+i,r),o.setXY(2,t,r+s),o.setXY(3,t+i,r+s),o.needsUpdate=!0}ensureMaterial(){if(this.sharedMaterial)return;let e=this.worldRenderer.material.map;e&&(this.sharedMaterial=new e0.MeshBasicMaterial({map:e,vertexColors:!0,transparent:!0,alphaTest:.1}))}},N6={id:"blockBreakParticles",controller:G1,enabledDefault:!0,cannotBeDisabled:!0,requiresHeightmap:!1};E();x();R();k();var V1=class{constructor(e){this.worldRenderer=e;d(this,"enabled",!1);d(this,"lastBobWalkDist",0);d(this,"lastBobTickTime",0);d(this,"render",()=>{if(!this.enabled)return;let e=this.worldRenderer.displayOptions.inWorldRenderingConfig,{perspective:t}=this.worldRenderer.playerStateReactive;if(e.viewBobbing&&t==="first_person"&&!this.worldRenderer.playerStateUtils.isSpectator()){this.worldRenderer.playerStateReactive.walkDist!==this.lastBobWalkDist&&(this.lastBobTickTime=performance.now(),this.lastBobWalkDist=this.worldRenderer.playerStateReactive.walkDist);let i=Math.min((performance.now()-this.lastBobTickTime)/50,1);this.worldRenderer.cameraShake.setCameraBobInput({walkDist:this.worldRenderer.playerStateReactive.walkDist,prevWalkDist:this.worldRenderer.playerStateReactive.prevWalkDist,bob:this.worldRenderer.playerStateReactive.bob,prevBob:this.worldRenderer.playerStateReactive.prevBob,partialTick:i})}else this.worldRenderer.cameraShake.setCameraBobInput(null)})}enable(){this.enabled=!0}disable(){this.enabled=!1,this.worldRenderer.cameraShake.setCameraBobInput(null);let{perspective:e}=this.worldRenderer.playerStateReactive;e==="first_person"&&this.worldRenderer.camera.position.set(0,0,0)}dispose(){this.disable()}},j6={id:"cameraBobbing",controller:V1,enabledDefault:!0,cannotBeDisabled:!0};E();x();R();k();import*as it from"three";var W1=2e3,Q6=32,Y6=32,zi=12,q6=24,Ui=1.2,F9=-5,N1=class{constructor(e){this.worldRenderer=e;d(this,"instancedMesh");d(this,"geometry");d(this,"material");d(this,"particles",[]);d(this,"enabled",!1);d(this,"dummy",new it.Matrix4);d(this,"tempPosition",new it.Vector3);d(this,"tempQuaternion",new it.Quaternion);d(this,"tempScale",new it.Vector3);d(this,"configUnsubs",[]);d(this,"render",e=>{if(!this.enabled||!this.instancedMesh||!this.material)return;let t=this.worldRenderer.getCameraPosition();this.instancedMesh.position.set(0,0,0);let r=this.worldRenderer.reactiveState.world.heightmaps,{dummy:i,tempPosition:s,tempQuaternion:o,tempScale:l}=this,a=NaN,v=NaN,c;for(let u=0;u<W1;u++){let f=this.particles[u];this.instancedMesh.getMatrixAt(u,i),i.decompose(s,o,l),s.addScaledVector(f.velocity,e);let m=s.y,g=Math.sqrt(s.x*s.x+s.z*s.z),b=t.x+s.x,A=t.y+s.y,y=t.z+s.z,_=Math.floor(b/16),S=Math.floor(y/16);(_!==a||S!==v)&&(c=r[`${_},${S}`],a=_,v=S);let C=(Math.floor(b)%16+16)%16,T=(Math.floor(y)%16+16)%16,P=c?.[T*16+C];if(g>Q6||P!==void 0&&P!==-32768&&A<=P+1+f.despawnOffset||m<F9){this.respawnParticle(s);let L=zi+Math.random()*(q6-zi);f.velocity.set((Math.random()-.5)*Ui,-L,(Math.random()-.5)*Ui),f.despawnOffset=Math.random()*.5}i.compose(s,o,l),this.instancedMesh.setMatrixAt(u,i)}this.instancedMesh.instanceMatrix.needsUpdate=!0});this.configUnsubs.push(this.worldRenderer.onReactiveConfigUpdated("rainColor",()=>this.syncRainAppearance()),this.worldRenderer.onReactiveConfigUpdated("rainOpacity",()=>this.syncRainAppearance()))}enable(){this.enabled||(this.enabled=!0,this.instancedMesh?(this.instancedMesh.visible=!0,this.syncRainAppearance()):this.createRain())}disable(){this.enabled&&(this.enabled=!1,this.instancedMesh&&(this.instancedMesh.visible=!1))}autoEnableCheck(){return this.worldRenderer.worldRendererConfig.isRaining===!0}dispose(){for(let e of this.configUnsubs)e();this.configUnsubs.length=0,this.instancedMesh&&this.worldRenderer.scene.remove(this.instancedMesh),this.geometry?.dispose(),this.material?.dispose(),this.instancedMesh=void 0,this.geometry=void 0,this.material=void 0,this.particles=[]}syncRainAppearance(){if(!this.material)return;let{rainColor:e,rainOpacity:t}=this.worldRenderer.worldRendererConfig;this.material.color.set(e),this.material.opacity=Math.max(0,Math.min(1,t)),this.material.needsUpdate=!0}createRain(){let{rainColor:e,rainOpacity:t}=this.worldRenderer.worldRendererConfig;this.geometry=new it.BoxGeometry(.03,.3,.03),this.material=new it.MeshBasicMaterial({color:e,transparent:!0,opacity:Math.max(0,Math.min(1,t)),depthWrite:!0,fog:!1}),this.instancedMesh=new it.InstancedMesh(this.geometry,this.material,W1),this.instancedMesh.name="rain-particles",this.instancedMesh.frustumCulled=!1;let r=new it.Matrix4,i=new it.Vector3;for(let s=0;s<W1;s++){this.respawnParticle(i),i.y=Math.random()*Y6,r.setPosition(i),this.instancedMesh.setMatrixAt(s,r);let o=zi+Math.random()*(q6-zi);this.particles.push({velocity:new it.Vector3((Math.random()-.5)*Ui,-o,(Math.random()-.5)*Ui),age:0,despawnOffset:Math.random()*.5})}this.instancedMesh.instanceMatrix.needsUpdate=!0,this.worldRenderer.scene.add(this.instancedMesh)}respawnParticle(e){let t=Math.random()*Math.PI*2,r=Math.random()*Q6;e.set(Math.cos(t)*r,Y6,Math.sin(t)*r)}},K6={id:"rain",controller:N1,enabledDefault:!1,requiresHeightmap:!0};E();x();R();k();import*as Te from"three";var J6=new Te.Color(13/255,234/255,238/255),z9=9,U9=12e3,G9=1500,V9=1e4,W9=350,N9=650,X6=120,Z6=280,j1=class{constructor(e){this.worldRenderer=e;d(this,"enabled",!0);d(this,"sections",new Map);d(this,"completed",new Set);d(this,"globalWaveStarted",!1);d(this,"globalWaveStartMs",0);d(this,"finishedChunkCount",0);d(this,"firstQueuedMs",null);d(this,"pulseTime",0);d(this,"wireframeMaterial",new Te.LineBasicMaterial({color:J6,transparent:!0,opacity:1,blending:Te.AdditiveBlending,depthWrite:!1}));d(this,"wireframeGlowMaterial",new Te.LineBasicMaterial({color:J6,transparent:!0,opacity:.55,blending:Te.AdditiveBlending,depthWrite:!1}));e.worldRendererConfig.futuristicReveal!==!0&&(this.enabled=!1)}autoEnableCheck(){return this.worldRenderer.worldRendererConfig.futuristicReveal===!0}enable(){this.autoEnableCheck()&&this.setEnabled(!0)}disable(){this.setEnabled(!1)}dispose(){this.reset(),this.wireframeMaterial.dispose(),this.wireframeGlowMaterial.dispose()}shouldDeferSectionGeometry(e){return this.enabled&&!this.completed.has(e)}onSectionMeshed(e,t,r){let i=r.children.find(s=>s.name==="mesh");i instanceof Te.Mesh&&this.onSectionMeshedMesh(e,t,i)}onChunkFinished(){this.enabled&&(this.finishedChunkCount++,this.tryStartGlobalWave(performance.now()))}onSectionRemoved(e){this.cancelSection(e,!0),this.completed.delete(e)}onWorldSwitched(){this.reset()}tick(e,t=performance.now()){if(!this.enabled||(this.tryStartGlobalWave(t),!this.globalWaveStarted&&this.firstQueuedMs!==null&&this.sections.size>0&&t-this.firstQueuedMs>=U9&&this.startGlobalWave(t),this.sections.size===0))return;this.pulseTime+=e*.001;let r=[];for(let i of this.sections.values()){if(t-i.phaseStartMs>V9){r.push(i);continue}if(i.phase==="queued"){this.globalWaveStarted&&t>=i.revealAtMs&&this.beginWireframe(i,t);continue}let s=t-i.phaseStartMs;if(i.phase==="wireframe"){this.animateWireframe(i,s),s>=i.wireframeMs&&this.beginFade(i,t);continue}if(i.phase==="fade"){let o=Math.min(1,s/i.fadeMs);this.animateFade(i,o),o>=1&&r.push(i)}}for(let i of r)this.finishSection(i)}setEnabled(e){e!==this.enabled&&(this.enabled=e,e||this.forceFinishAll())}onSectionMeshedMesh(e,t,r){if(!this.enabled||!t.positions?.length||this.completed.has(e))return;let i=this.sections.get(e);if(i){i.mesh=r,i.geometry=t,(i.phase==="wireframe"||i.phase==="fade")&&this.finishSection(i);return}let s=performance.now();this.firstQueuedMs===null&&(this.firstQueuedMs=s);let o=this.globalWaveStarted;this.sections.set(e,{key:e,geometry:t,phase:"queued",phaseStartMs:s,revealAtMs:this.globalWaveStarted?s:0,wireframeMs:o?X6:W9,fadeMs:o?Z6:N9,wireframeGroup:null,mesh:r,savedMaterial:null,pulseOffset:Math.random()*Math.PI*2}),r.visible=!1,this.setShaderMeshesVisible(e,!1),this.tryStartGlobalWave(s)}reset(){this.forceFinishAll(),this.sections.clear(),this.completed.clear(),this.globalWaveStarted=!1,this.globalWaveStartMs=0,this.finishedChunkCount=0,this.firstQueuedMs=null,this.pulseTime=0}forceFinishAll(){for(let e of[...this.sections.values()])this.finishSection(e);this.sections.clear(),this.unhideAllSectionMeshes()}tryStartGlobalWave(e){if(!this.globalWaveStarted&&this.sections.size!==0){if(this.finishedChunkCount>=z9){this.startGlobalWave(e);return}this.worldRenderer.allChunksFinished&&this.startGlobalWave(e)}}startGlobalWave(e){if(this.globalWaveStarted)return;this.globalWaveStarted=!0,this.globalWaveStartMs=e;let t=this.worldRenderer.getCameraPosition(),r=1,i=new Map;for(let[s,o]of this.sections){if(o.phase!=="queued")continue;let{sx:l,sy:a,sz:v}=o.geometry,c=Math.hypot(l-t.x,a-t.y,v-t.z);i.set(s,c),r=Math.max(r,c)}for(let[,s]of this.sections){if(s.phase!=="queued")continue;let o=i.get(s.key)??0;s.revealAtMs=e+o/r*G9,s.wireframeMs=X6,s.fadeMs=Z6}}beginWireframe(e,t){let r=e.mesh??this.getSectionMesh(e.key);if(e.mesh=r,!r){this.sections.delete(e.key);return}let i=this.createWireframeGeometry(e.geometry),s=new Te.LineSegments(i,this.wireframeMaterial.clone());this.worldRenderer.sceneOrigin.track(s),s.position.set(e.geometry.sx,e.geometry.sy,e.geometry.sz),s.name="scifi-wireframe",s.renderOrder=1e3;let o=new Te.LineSegments(i.clone(),this.wireframeGlowMaterial.clone());this.worldRenderer.sceneOrigin.track(o),o.position.copy(s.position),o.scale.setScalar(1.02),o.name="scifi-glow",o.renderOrder=999;let l=new Te.Group;l.name="scifi-reveal-group",l.add(s,o),this.worldRenderer.realScene.add(l),r.visible=!1,this.setShaderMeshesVisible(e.key,!1),e.wireframeGroup=l,e.phase="wireframe",e.phaseStartMs=t}beginFade(e,t){let r=e.mesh??this.getSectionMesh(e.key);if(e.mesh=r,r){r.visible=!0;let i=r.material;if(!Array.isArray(i)&&i&&typeof i.clone=="function"){e.savedMaterial=i;let s=i.clone();s.transparent=!0,s.opacity=0,s.needsUpdate=!0,r.material=s}}this.setShaderMeshesVisible(e.key,!0),e.phase="fade",e.phaseStartMs=t}animateWireframe(e,t){if(!e.wireframeGroup)return;let r=e.wireframeGroup.children[0],i=e.wireframeGroup.children[1],s=.6+.4*Math.sin(this.pulseTime*4+e.pulseOffset);if(r?.material){let o=r.material;o.opacity=s;let l=.85+.15*Math.sin(this.pulseTime*6+t*.002);o.color.setRGB(13/255*l,234/255*l,238/255*l)}i?.material&&(i.material.opacity=s*.4)}animateFade(e,t){let r=1-(1-t)**3;if(e.wireframeGroup){let s=e.wireframeGroup.children[0],o=e.wireframeGroup.children[1];s?.material&&(s.material.opacity=1-r),o?.material&&(o.material.opacity=(1-r)*.55)}let i=e.mesh;i&&e.savedMaterial&&!Array.isArray(i.material)&&(i.material.opacity=r),this.setShaderMeshesVisible(e.key,r>.001)}finishSection(e){let t=e.mesh??this.getSectionMesh(e.key);if(t){if(e.savedMaterial){let i=t.material;t.material=e.savedMaterial,i.dispose(),e.savedMaterial=null}t.visible=!0}this.setShaderMeshesVisible(e.key,!0);let{chunkMeshManager:r}=this.worldRenderer;r.migrateDeferredShaderToGlobal(e.key),r.migrateDeferredLegacyToGlobal(e.key),e.wireframeGroup&&(this.disposeWireframeGroup(e.wireframeGroup),e.wireframeGroup=null),this.sections.delete(e.key),this.completed.add(e.key)}cancelSection(e,t){let r=this.sections.get(e);if(r){if(r.wireframeGroup&&this.disposeWireframeGroup(r.wireframeGroup),t){let i=r.mesh??this.getSectionMesh(e);if(i){if(r.savedMaterial){let s=i.material;i.material=r.savedMaterial,s.dispose()}i.visible=!0}this.setShaderMeshesVisible(e,!0)}this.sections.delete(e)}}getSectionMesh(e){let t=this.worldRenderer.chunkMeshManager.sectionObjects[e];if(!t)return null;let r=t.children.find(i=>i.name==="mesh");return r instanceof Te.Mesh?r:null}getShaderMesh(e){let t=this.worldRenderer.chunkMeshManager.sectionObjects[e];if(!t)return null;let r=t.children.find(i=>i.name==="shaderMesh");return r instanceof Te.Mesh?r:null}setShaderMeshesVisible(e,t){let r=this.getShaderMesh(e);r&&(r.visible=t)}unhideAllSectionMeshes(){for(let e of Object.values(this.worldRenderer.chunkMeshManager.sectionObjects))e&&e.traverse(t=>{t instanceof Te.Mesh&&(t.name==="mesh"||t.name==="shaderMesh")&&(t.visible=!0)})}disposeWireframeGroup(e){this.worldRenderer.sceneOrigin.removeAndUntrackAll(e),this.worldRenderer.realScene.remove(e),e.traverse(t=>{let r=t;r.geometry?.dispose();let i=r.material;Array.isArray(i)?i.forEach(s=>s.dispose()):i?.dispose()}),e.clear()}createWireframeGeometry(e){let t=e.positions,r=e.indices,i=[],s=new Set;for(let l=0;l<r.length;l+=3){let a=r[l],v=r[l+1],c=r[l+2];this.addEdge(t,a,v,i,s),this.addEdge(t,v,c,i,s),this.addEdge(t,c,a,i,s)}let o=new Te.BufferGeometry;return o.setAttribute("position",new Te.Float32BufferAttribute(i,3)),o}addEdge(e,t,r,i,s){let o=Math.min(t,r),l=Math.max(t,r),a=`${o}-${l}`;s.has(a)||(s.add(a),i.push(e[t*3],e[t*3+1],e[t*3+2],e[r*3],e[r*3+1],e[r*3+2]))}},$6={id:"futuristicReveal",controller:j1,enabledDefault:!0};E();x();R();k();import*as Ce from"three";var j9=parseInt(Ce.REVISION.replaceAll(/\D+/g,""),10),Q1=class extends Ce.ShaderMaterial{constructor(){super({uniforms:{time:{value:0}},vertexShader:`
21686
21686
  uniform float time;
21687
21687
  attribute float size;
21688
21688
  varying vec3 vColor;
@@ -21694,17 +21694,13 @@ void main() {
21694
21694
  gl_Position = projectionMatrix * mvPosition;
21695
21695
  }`,fragmentShader:`
21696
21696
  uniform sampler2D pointTexture;
21697
- uniform float fade;
21698
21697
  varying vec3 vColor;
21699
21698
  void main() {
21700
- // fade scales star brightness (0 = invisible). With additive blending this is
21701
- // the only way to dim stars \u2014 scene fog never reaches this shader. Driven by the
21702
- // rain state so stars disappear in rain like in vanilla.
21703
- gl_FragColor = vec4(vColor * fade, 1.0);
21699
+ gl_FragColor = vec4(vColor, 1.0);
21704
21700
 
21705
21701
  #include <tonemapping_fragment>
21706
21702
  #include <${j9>=154?"colorspace_fragment":"encodings_fragment"}>
21707
- }`})}},Y1=class{constructor(e){this.worldRenderer=e;d(this,"points");d(this,"timer",new Ce.Timer);d(this,"enabled",!1);d(this,"currentTime");d(this,"fade",1);d(this,"enablementCheck",()=>this.currentTime?this.currentTime>13500&&this.currentTime<23e3:!1);d(this,"render",e=>{if(!this.points)return;this.points.position.set(0,0,0);let t=this.points.material;this.timer.update(performance.now()),t.uniforms.time.value=this.timer.getElapsed()*.2;let r=this.worldRenderer.worldRendererConfig.isRaining?0:1,i=Math.min(1,e*2);this.fade+=(r-this.fade)*i,t.uniforms.fade.value=this.fade})}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 Ce.BufferGeometry,l=b=>new Ce.Vector3().setFromSpherical(new Ce.Spherical(b,Math.acos(1-Math.random()*2),Math.random()*2*Math.PI)),a=[],v=[],c=Array.from({length:r},()=>(.5+.5*Math.random())*i),u=new Ce.Color,f=e+t,m=t/r;for(let b=0;b<r;b++)f-=m*Math.random(),a.push(...l(f).toArray()),u.setHSL(b/r,s,.9),v.push(u.r,u.g,u.b);o.setAttribute("position",new Ce.Float32BufferAttribute(a,3)),o.setAttribute("color",new Ce.Float32BufferAttribute(v,3)),o.setAttribute("size",new Ce.Float32BufferAttribute(c,1));let g=new Q1;g.blending=Ce.AdditiveBlending,g.depthTest=!0,g.depthWrite=!1,g.transparent=!0,this.points=new Ce.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)}},e7={id:"starfield",controller:Y1,enabledDefault:!0,cannotBeDisabled:!0};var t7={starfield:e7,futuristicReveal:$6,rain:K6,cameraBobbing:j6,blockBreakParticles:N6};var At=class At extends Hr{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,"cameraSectionPos",new t0(0,0,0));d(this,"holdingBlock");d(this,"holdingBlockLeft");d(this,"scene",new Z.Scene);d(this,"ambientLight",new Z.AmbientLight(13421772,At.LEGACY_TO_PHYSICAL_LIGHT));d(this,"directionalLight",new Z.DirectionalLight(16777215,.5*At.LEGACY_TO_PHYSICAL_LIGHT));d(this,"entities",new ii(this,globalThis.mcData));d(this,"performanceMonitor");d(this,"cameraGroupVr");d(this,"material",new Z.MeshBasicMaterial({vertexColors:!0,transparent:!0,alphaTest:.1}));d(this,"itemsTexture");d(this,"cursorBlock");d(this,"onRender",[]);d(this,"lastRenderTime",0);d(this,"lastSciFiTickMs",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 mi(this.scene));d(this,"cameraWorldPos",{x:0,y:0,z:0});d(this,"_cameraPositionAccessWarned",!1);d(this,"_tmpCameraPos",new Z.Vector3);d(this,"currentPosTween");d(this,"currentRotTween");d(this,"_tpDirection",new Z.Vector3);d(this,"_tpPitchQuat",new Z.Quaternion);d(this,"_tpYawQuat",new Z.Quaternion);d(this,"_tpFinalQuat",new Z.Quaternion);d(this,"_tpScenePos",new Z.Vector3);d(this,"_tpAxisX",new Z.Vector3(1,0,0));d(this,"_tpAxisY",new Z.Vector3(0,1,0));d(this,"_tpChunkWorldPos",new Z.Vector3);d(this,"debugOverlayAdded",!1);d(this,"debugRaycastHelper");d(this,"debugHitPoint");d(this,"prevFramePerspective",null);this.performanceMonitor=new _5(this.reactiveState.world.instabilityFactors),this.renderer=t;let s=At.getRendererInfo(t)??"...";i.rendererState.renderer=s,this.chunkMeshManager=new ar(this,this.scene,this.material,this.worldSizeParams.worldHeight,this.viewDistance),this.onRenderDistanceChanged=o=>{this.chunkMeshManager.updateViewDistance(o)},typeof window<"u"&&(window.setBlockLightmap=o=>{this.chunkMeshManager.setBlockLightmapParams(o)}),this.syncSkyLevelFromTime(this.timeOfTheDay),this.cursorBlock=new ni(this),this.holdingBlock=Z5(this),this.holdingBlockLeft=Z5(this,!0);for(let o of Object.values(t7))this.registerModule(o);this.skyboxRenderer=new fi(this.realScene,!1,null),this.skyboxRenderer.init(),this.addDebugOverlay(),this.resetScene(),this.init(),this.soundSystem=new oi(this),this.cameraShake=new ai(this,this.onRender),this.media=new li(this),this.fireworksLegacy=new di(this),this.waypoints=new ci(this),this.cinimaticScript=new ui(this,(o,l,a)=>this.setCinimaticCamera(o,l,a),o=>this.setCinimaticFov(o),()=>({position:new t0(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 hi(this.realScene,this.sceneOrigin),this.renderUpdateEmitter.on("chunkFinished",o=>{this.finishChunk(o)}),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}setRain(t){this.worldRendererConfig.isRaining=t,this.toggleModule("rain",t)}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,v,c)=>Math.abs(a)>i||Math.abs(v)>i||Math.abs(c)>i,o=()=>{!r._cameraPositionAccessWarned&&typeof H<"u"},l=new Proxy(t,{set(a,v,c){return(v==="x"||v==="y"||v==="z")&&typeof c=="number"&&Math.abs(c)>i&&o(),a[v]=c,!0},get(a,v,c){let u=a[v];return v==="set"?function(f,m,g){return s(f,m,g)&&o(),a.set(f,m,g)}:v==="setX"||v==="setY"||v==="setZ"?function(f){return Math.abs(f)>i&&o(),a[v](f)}:v==="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:l,configurable:!0,enumerable:!0})}worldSwitchActions(){this.onWorldSwitched.push(()=>{this.getModule("futuristicReveal")?.onWorldSwitched?.(),this.protocolCustomBlocks.clear(),this.sectionsOffsetsAnimations={},this.waypoints.clear(),this.cinimaticScript.stopScript(),this.fireworks.clear(),this.syncSkyLevelFromTime(this.timeOfTheDay)})}downloadWorldGeometry(){B1(this,new Z.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 Z.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 Z.Vector2);this.camera=new Z.PerspectiveCamera(75,t.x/t.y,.1,1e3),this._wrapCameraPositionWithWarning(),this.cameraContainer=new Z.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*At.LEGACY_TO_PHYSICAL_LIGHT)}),this.onReactivePlayerStateUpdated("directionalLight",t=>{t&&(this.directionalLight.intensity=t*At.LEGACY_TO_PHYSICAL_LIGHT)}),this.onReactivePlayerStateUpdated("lookingAtBlock",t=>{this.cursorBlock.setHighlightCursorBlock(t?new t0(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 t0(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",i=>{this.updateShowChunksBorder(i)}),this.onReactiveConfigUpdated("defaultSkybox",i=>{this.skyboxRenderer.updateDefaultSkybox(i)}),this.onReactiveConfigUpdated("shaderCubeDebugMode",()=>{this.chunkMeshManager.syncCubeShaderUniforms(),this.chunkMeshManager.syncLegacyShaderUniforms()});let t=()=>{let i=this.worldRendererConfig;this.chunkMeshManager.setShadingTheme(i.shadingTheme,i.cardinalLight)};this.onReactiveConfigUpdated("shadingTheme",t),this.onReactiveConfigUpdated("cardinalLight",t),this.onReactiveConfigUpdated("futuristicReveal",()=>{this.updateModulesFromConfig()});let r=this.displayOptions.inWorldRenderingConfig.handRenderer;this.onReactiveConfigUpdated("handRenderer",i=>{if(i===r)return;r=i;let s=this.holdingBlock.ready,o=this.holdingBlockLeft.ready;this.holdingBlock.dispose(),this.holdingBlockLeft.dispose(),this.holdingBlock=Z5(this),this.holdingBlockLeft=Z5(this,!0),s&&(this.holdingBlock.ready=!0,this.holdingBlock.updateItem()),o&&(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=Qt(t.blocksAtlasImage);s.needsUpdate=!0,s.flipY=!1,this.material.map=s,this.chunkMeshManager.syncCubeShaderUniforms(),this.chunkMeshManager.syncLegacyShaderUniforms();let o=Qt(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 Z.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),this.syncSkyLevelFromTime(t)}syncSkyLevelFromTime(t){let r=Ht(t)/15;this.chunkMeshManager.setSkyLevel(r)}onDayCycleSkyLightChanged(t){}biomeUpdated(t){t?.temperature!==void 0&&this.skyboxRenderer.updateTemperature(t.temperature)}biomeReset(){this.skyboxRenderer.updateTemperature(A1)}getItemRenderData(t,r){return U3(t,r,this.resourcesManager,this.playerStateReactive)}async demoModel(){let t=cursorBlockRel(0,1,0).position,r=await D5();w2(r,t);let i=new Z.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 Z.BoxHelper(r,16776960);r.add(i),this.realScene.add(r)}addDebugOverlay(){if(this.debugOverlayAdded)return;this.debugOverlayAdded=!0;let t=E0("debug-overlay",80,0,void 0,{className:A0});setInterval(()=>{if(t.setVisibility(this.displayAdvancedStats),this.displayAdvancedStats){let r=v=>new Intl.NumberFormat("en-US",{}).format(v),i=v=>new Intl.NumberFormat("en-US",{notation:"compact",maximumFractionDigits:1}).format(v),s="";s+=`TE: ${r(this.renderer.info.memory.textures)} `;let o=this.chunkMeshManager.getGlobalBufferStats();if(o.shaderFaces){let v=o.shaderFaces;s+=`CUBE: ${i(v.used)}/${i(v.capacity)}f `}if(o.legacyOpaque){let v=o.legacyOpaque;s+=`LEG-O: ${i(v.used)}/${i(v.capacity)}q `}if(o.legacyBlend){let v=o.legacyBlend;s+=`LEG-B: ${i(v.used)}/${i(v.capacity)}q `}s+=`MEM: ${this.chunkMeshManager.getEstimatedMemoryUsage().total} `;let l=this.cameraCollisionBlockCache.getAllocatedBytes();l>0&&(s+=`CAM: ${i(l)}b `);let a=$i(this.reactiveState.world.instabilityFactors);a&&(s+=`PF: ${a} `),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)),v=r.mesh??r.shaderMesh??r.children.find(c=>c.name==="mesh"||c.name==="shaderMesh");v&&(v.renderOrder=a)}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),this.getModule("futuristicReveal")?.onChunkFinished?.()}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<At.MAX_SECTION_UPDATE_BUFFER_MS){let[a,v,c]=s.split(",").map(Number),u=[`${a-16},${v},${c}`,`${a+16},${v},${c}`,`${a},${v-r},${c}`,`${a},${v+r},${c}`,`${a},${v},${c-16}`,`${a},${v},${c+16}`],f=!1;for(let m of u)if(this.sectionsWaiting.has(m)&&!this.pendingSectionUpdates.has(m)&&this.sectionObjects[m]){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 l=o.key.split(","),a=`${l[0]},${l[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}let v=this.chunkMeshManager.updateSection(o.key,o.geometry);this.updatePosDataChunk(o.key),v&&this.getModule("futuristicReveal")?.onSectionMeshed?.(o.key,o.geometry,v)}}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}let s=this.chunkMeshManager.updateSection(t.key,t.geometry);this.updatePosDataChunk(t.key),s&&this.getModule("futuristicReveal")?.onSectionMeshed?.(t.key,t.geometry,s)}}getCameraPosition(t){return(t??this._tmpCameraPos).set(this.cameraWorldPos.x,this.cameraWorldPos.y,this.cameraWorldPos.z)}getSectionCameraPosition(){let t=this.getCameraPosition();return new t0(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 Z.Vector3(this.cameraWorldPos.x,this.cameraWorldPos.y,this.cameraWorldPos.z));let s=this.playerStateReactive.perspective==="third_person_back",o=4,l=this._tpDirection.set(0,0,-1),a=this._tpPitchQuat.setFromAxisAngle(this._tpAxisX,i),v=this._tpYawQuat.setFromAxisAngle(this._tpAxisY,r),c=this._tpFinalQuat.multiplyQuaternions(v,a);l.applyQuaternion(c),s&&l.multiplyScalar(-1),this.DEBUG_RAYCAST&&this.debugRaycast(t,l,o);let u=.25,f=.05,m=.4,g=this.cameraCollisionBlockCache,b=U6(t.x,t.y,t.z,l.x,l.y,l.z,o,u,f,(y,_,S)=>g.isSolidBlock(y,_,S)),A=o;return b!==void 0&&(A=Math.min(A,b.distance)),A<m&&(A=m),new t0(t.x+l.x*A,t.y+l.y*A,t.z+l.z*A)}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 Z.Vector3(this.sceneOrigin.toSceneX(t.x),this.sceneOrigin.toSceneY(t.y),this.sceneOrigin.toSceneZ(t.z));this.debugRaycastHelper=new Z.ArrowHelper(r.clone().normalize(),s,i,16711680,i*.1,i*.05),this.realScene.add(this.debugRaycastHelper);let o=new Z.SphereGeometry(.2,8,8),l=new Z.MeshBasicMaterial({color:65280});this.debugHitPoint=new Z.Mesh(o,l),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,l=Math.min(o/At.FOV_TRANSITION_MS,1),a=v=>1-(1-v)**3;this.animatedFov+=(i-this.animatedFov)*a(l),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 ze(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,l=Math.PI/2;s.yaw<l&&r>Math.PI+l?o=-Math.PI*2:r<l&&s.yaw>Math.PI+l&&(o=Math.PI*2),this.currentRotTween?.stop(),this.currentRotTween=new ze(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 Z.Vector3(this.cameraWorldPos.x,this.cameraWorldPos.y,this.cameraWorldPos.z),l=this.getThirdPersonCamera(o,r,i),a=o.distanceTo(new Z.Vector3(l.x,l.y,l.z)),v=s==="third_person_back"?a:-a;this.camera.position.set(0,0,v),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:l}=this.reactiveDebugParams,a=this.getSectionHeight(),v=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,m,g]=c.split(",").map(Number),b=s&&t!==void 0?m<=v+t:o&&r!==void 0?m>=v-r:l&&i!==void 0?Math.abs(m-v)<=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 S=this.renderer.getSize(new Z.Vector2);this.camera.aspect=S.width/S.height,this.camera.updateProjectionMatrix()}let o=0;if(!this.reactiveDebugParams.disableEntities){let S=performance.now();this.entities.render(),o=performance.now()-S}let l=this.cameraGroupVr instanceof Z.Group?this.cameraGroupVr.children.find(S=>S instanceof Z.PerspectiveCamera):this.camera;this.applyPendingSectionUpdates();let a=performance.now(),v=a-this.lastSciFiTickMs;this.lastSciFiTickMs=a,this.getModule("futuristicReveal")?.tick?.(v,a);let c=this.cameraWorldPos.x,u=this.cameraWorldPos.y,f=this.cameraWorldPos.z;this.chunkMeshManager.maybeRebase({x:c,y:u,z:f});let m=this.chunkMeshManager.getRenderOrigin(),g=this.chunkMeshManager.globalBlockBuffer;g&&(g.setCameraOrigin(m,c,u,f),g.setDebugOverlay(this.displayOptions.inWorldRenderingConfig.enableDebugOverlay),g.compactStep(),g.hasPendingUploads()&&g.uploadDirtyRange(),g.suppressThreeDraw());let b=this.chunkMeshManager.globalLegacyBuffer;b&&(b.setDebugOverlay(this.displayOptions.inWorldRenderingConfig.enableDebugOverlay),b.compactStep(),b.hasPendingUploads()&&b.uploadDirtyRange(),b.suppressThreeDraw());let A=this.chunkMeshManager.globalLegacyBlendBuffer;A&&(A.setDebugOverlay(this.displayOptions.inWorldRenderingConfig.enableDebugOverlay),A.compactStep(),A.hasPendingUploads()&&A.uploadDirtyRange(),A.suppressThreeDraw()),this.chunkMeshManager.markCullDirtyIfBufferStateChanged(),this.chunkMeshManager.setLegacyCameraOrigin(c,u,f),this.chunkMeshManager.updateCullDirtyFromCamera(l,c,u,f),this.chunkMeshManager.cullDirty&&(this.chunkMeshManager.updateSectionCullAndSort(l,this.cameraWorldPos.x,this.cameraWorldPos.y,this.cameraWorldPos.z),this.chunkMeshManager.clearCullDirty()),this.renderer.render(this.scene,l),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 S of this.fountains)this.sectionObjects[S.sectionId]&&!this.sectionObjects[S.sectionId].foutain&&(S.createParticles(this.sectionObjects[S.sectionId]),this.sectionObjects[S.sectionId].foutain=!0),S.render();this.waypoints.render(),this.fireworks.update();for(let S of this.onRender)S(i);let _=performance.now()-r;this.worldRendererConfig.autoLowerRenderDistance&&this.chunkMeshManager.recordRenderTime(_),this.renderTimeAvgCount++,this.renderTimeAvg=(this.renderTimeAvg*(this.renderTimeAvgCount-1)+_)/this.renderTimeAvgCount,this.renderTimeMax=Math.max(this.renderTimeMax,_),this.performanceMonitor.onFrame({totalMs:_,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(l=>l.name==="textures")?.value,!!o)try{let a=JSON.parse(O.from(o,"base64").toString()).textures?.SKIN?.url,{skinTexturesProxy:v}=this.worldRendererConfig;v&&(a=a?.replace("http://textures.minecraft.net/",v).replace("https://textures.minecraft.net/",v));let c=Kt(this,a,Jt.head),u=new Z.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,-Z.MathUtils.degToRad(r*(i?90:45/2)),0),u.scale.set(.8,.8,.8),u}catch{}}lightUpdate(t,r){for(let i=this.worldSizeParams.minY;i<this.worldSizeParams.worldHeight;i+=16)this.setSectionDirty(new t0(t,i,r))}rerenderAllChunks(){for(let t of Object.keys(this.sectionObjects)){let[r,i,s]=t.split(",").map(Number);this.setSectionDirty(new t0(r,i,s))}}updateShowChunksBorder(t){this.chunkMeshManager.updateAllBoxHelpers(t)}resetWorld(){super.resetWorld(),this.pendingSectionUpdates.clear(),this.pendingSectionBufferStartTimes.clear(),this.chunkMeshManager.dispose(),this.chunkMeshManager=new ar(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]=En(t);return Object.fromEntries(Object.entries(this.sectionObjects).map(([l,a])=>{let[v,c,u]=l.split(",").map(Number),[f,m,g]=En({x:v,y:c,z:u});return[r?`${f-i},${m-s},${g-o}`:`${f-i},${g-o}`,a]}))}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.clearPendingSectionUpdatesForChunk(t,r);let i=this.getSectionHeight(),s=this.worldMinYRender;for(let o=s;o<this.worldSizeParams.worldHeight;o+=i){let l=`${t},${o},${r}`;this.chunkMeshManager.sectionObjects[l]&&this.chunkMeshManager.releaseSection(l)}this.chunkMeshManager.onChunkRemovedFromGate(`${t},${r}`)}updateViewerPosition(t){super.updateViewerPosition(t),this.chunkMeshManager.pendingNearReveal.size>0&&this.chunkMeshManager.tryRevealPending()}onViewerChunkPositionChanged(){this.chunkMeshManager.tryRevealPending()}setSectionDirty(...t){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,l,a=this.sceneOrigin.getWorldPosition(t);a?(s=a.x,o=a.y,l=a.z):(s=this.sceneOrigin.toWorldX(t.position.x),o=this.sceneOrigin.toWorldY(t.position.y),l=this.sceneOrigin.toWorldZ(t.position.z));let v=Math.floor(s/16)*16,c=Math.floor(l/16)*16,u=Math.floor(o/i)*i,f=`${v},${c}`,m=`${v},${u},${c}`;return!!this.finishedChunks[f]||!!this.sectionObjects[m]}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(At,"LEGACY_TO_PHYSICAL_LIGHT",Math.PI),d(At,"FOV_TRANSITION_MS",200),d(At,"MAX_SECTION_UPDATE_BUFFER_MS",500);var L0=At;E();x();R();k();E();x();R();k();var r0="1.21.4";E();x();R();k();function H0(n,e){n.aspect=e.width/e.height,n.updateProjectionMatrix()}E();x();R();k();function q1(n,e=!1){return n?.mode?n.mode:e?"worldBlocks":Mt.mode}E();x();R();k();import*as de from"three";E();x();R();k();function K1(...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 J1=new Date,r7=J1.getMonth()===11&&J1.getDate()>=24&&J1.getDate()<=26,Q9=["panorama_3.webp","panorama_1.webp","panorama_4.webp","panorama_5.webp","panorama_0.webp","panorama_2.webp"],Y9=200,v5=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 de.Scene,this.scene.background=new de.Color(3294568);let t=new de.AmbientLight(13421772);this.scene.add(t);let r=new de.DirectionalLight(16777215,.5);r.position.set(1,1,.5).normalize(),r.castShadow=!0,this.scene.add(r),this.camera=new de.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&&H0(this.camera,this.documentRenderer.canvas)}dispose(){this.scene.clear(),this.panoramaGroup=null,this.startTimes.clear()}buildCubemap(){let e=new de.BoxGeometry(1e3,1e3,1e3),t=[];for(let s of Q9)(async()=>{let l=K1("background",r7?"christmas":"",s),a=await y0(l),v=Qt(a);v.matrixAutoUpdate=!1,v.matrix.set(-1,0,1,0,1,0,0,0,1),v.wrapS=de.ClampToEdgeWrapping,v.wrapT=de.ClampToEdgeWrapping,v.minFilter=de.LinearFilter,v.magFilter=de.LinearFilter;let c=new de.MeshBasicMaterial({map:v,transparent:!0,side:de.DoubleSide,depthWrite:!1,opacity:0});this.startTimes.set(c,Date.now()),t.push(c)})().catch(l=>{});let r=new de.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 l=Date.now()-o;s.opacity=Math.min(1,l/Y9)}}};let i=new de.Object3D;if(i.add(r),!r7)for(let s=0;s<20;s++){let o=new zt("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 l=Math.random()*.01;o.children[0].onBeforeRender=()=>{o.rotation.y+=l,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 y0(K1("background","panorama_0.webp")),t=Qt(e),r=new de.Mesh(new de.PlaneGeometry(1e3,1e3),new de.MeshBasicMaterial({map:t}));r.position.set(0,0,-500),this.scene.add(r)}};E();x();R();k();import*as N from"three";var i7=.1,Z1={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"]},n7={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 N.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 N.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 N.Color(n*.4,0,n),ambient:393232,dir:10040319,pt1:11158783,pt2:4456618,name:"THE END"},cyber:{bg:792610,fog:792610,fogD:.008,blocks:[65535,4521932,11206468,6741503,8978278,65450],emit:[666163,668450,665656],nebula:[1192e3,1587240,1323588],galFn:n=>new N.Color(n*.15,n*.85,n*.95),ambient:1716288,dir:6750156,pt1:4521966,pt2:10092356,name:"CYBER",starColor:13431039,starOpacity:.75,galaxyOpacity:.62,nebulaOpacity:.36,edgeLineColor:4521949,blockOpacity:[.38,.54]},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 N.Color;return n<.4?e.lerpColors(new N.Color(16054527),new N.Color(14215423),n/.4):n<.75?e.lerpColors(new N.Color(14215423),new N.Color(11061488),(n-.4)/.35):e.lerpColors(new N.Color(11061488),new N.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]}},q9={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}},K9={cruise:1,barrel:1.6,dive:2.2,orbit:.7,snake:1.4},J9=250,Gi=1e4,Vi=3e3,c5=n=>n[Math.floor(Math.random()*n.length)],X1=n=>"#"+n.toString(16).padStart(6,"0"),s7=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,X1(n.top)),n.mid!=null&&s.addColorStop(.45,X1(n.mid)),s.addColorStop(1,X1(n.bottom)),t.fillStyle=s,t.fillRect(0,0,r,i);let o=new N.CanvasTexture(e);return o.needsUpdate=!0,o},O0=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 N.Group);d(this,"galaxy");d(this,"nebula");d(this,"stars");d(this,"galGeo");d(this,"nebGeo");d(this,"bGeo",new N.BoxGeometry(1,1,1));d(this,"eGeo",new N.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);d(this,"texturesApplied",!1);d(this,"textureLoadInProgress",!1);d(this,"onAssetsTexturesUpdated");let i=Mt;this.curScene=t.initialScene??i.v2Scene,this.curCam=t.initialCamera??i.v2Camera,this.blockGroup=t.initialBlockGroup??i.v2BlockGroup,this.cameraSpeed=t.initialCameraSpeed??T5.camera,this.blockSpeed=t.initialBlockSpeed??T5.block,this.useMinecraftTextures=t.useMinecraftTextures??i.minecraftTextures,this.resourcesManager=t.resourcesManager;let s=n7[this.curScene];this.scene=new N.Scene,this.scene.fog=new N.FogExp2(s.fog,s.fogD),this.applyScenePalette(s),this.camera=new N.PerspectiveCamera(80,this.documentRenderer.canvas.width/this.documentRenderer.canvas.height,.1,700),this.ambient=new N.AmbientLight(s.ambient,2.5),this.scene.add(this.ambient),this.dir=new N.DirectionalLight(s.dir,4),this.dir.position.set(1,1,0),this.scene.add(this.dir),this.pt1=new N.PointLight(s.pt1,5,100),this.scene.add(this.pt1),this.pt2=new N.PointLight(s.pt2,4,80),this.pt2.position.set(30,20,-30),this.scene.add(this.pt2);for(let f=0;f<J9;f++)this.spawnBlock(s,!0);if(!this.useMinecraftTextures){let f=s.edgeLineColor??62975;for(let m=0;m<40;m++){let g=new N.LineBasicMaterial({color:f,transparent:!0,opacity:.25});c5(this.blocks).mesh.add(new N.LineSegments(this.eGeo,g))}}this.scene.add(this.bGroup);let o=new N.BufferGeometry,l=new Float32Array(5e3*3);for(let f=0;f<5e3*3;f++)l[f]=(Math.random()-.5)*500;o.setAttribute("position",new N.BufferAttribute(l,3)),this.stars=new N.Points(o,new N.PointsMaterial({color:s.starColor??16777215,size:.3,transparent:!0,opacity:s.starOpacity??.7,sizeAttenuation:!0})),this.scene.add(this.stars),this.galGeo=new N.BufferGeometry;let a=new Float32Array(Gi*3),v=new Float32Array(Gi*3);for(let f=0;f<Gi;f++){let m=f%3,g=Math.random(),b=m/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 _=.2+g*.8,S=s.galFn(_);v[f*3]=S.r,v[f*3+1]=S.g,v[f*3+2]=S.b}this.galGeo.setAttribute("position",new N.BufferAttribute(a,3)),this.galGeo.setAttribute("color",new N.BufferAttribute(v,3)),this.galaxy=new N.Points(this.galGeo,new N.PointsMaterial({size:.9,vertexColors:!0,transparent:!0,opacity:s.galaxyOpacity??.55,sizeAttenuation:!0})),this.scene.add(this.galaxy),this.nebGeo=new N.BufferGeometry;let c=new Float32Array(Vi*3),u=new Float32Array(Vi*3);for(let f=0;f<Vi;f++){let m=25+Math.random()*110,g=Math.random()*Math.PI*2,b=(Math.random()-.5)*Math.PI*.5;c[f*3]=m*Math.cos(g)*Math.cos(b),c[f*3+1]=m*Math.sin(b)*.6,c[f*3+2]=m*Math.sin(g)*Math.cos(b)-80;let A=new N.Color(c5(s.nebula));u[f*3]=A.r,u[f*3+1]=A.g,u[f*3+2]=A.b}this.nebGeo.setAttribute("position",new N.BufferAttribute(c,3)),this.nebGeo.setAttribute("color",new N.BufferAttribute(u,3)),this.nebula=new N.Points(this.nebGeo,new N.PointsMaterial({size:3,vertexColors:!0,transparent:!0,opacity:s.nebulaOpacity??.3,sizeAttenuation:!0})),this.scene.add(this.nebula),this.addBackgroundTextPlane(),this.setupMouseTracking()}async init(){this.useMinecraftTextures&&this.scheduleMinecraftTextureLoad()}scheduleMinecraftTextureLoad(){!this.useMinecraftTextures||this.disposed||this.texturesApplied||this.textureLoadInProgress||this.tryApplyMinecraftTextures()}attachAssetsListener(){let e=this.resourcesManager;!e||this.onAssetsTexturesUpdated||(this.onAssetsTexturesUpdated=()=>this.scheduleMinecraftTextureLoad(),e.on("assetsTexturesUpdated",this.onAssetsTexturesUpdated))}detachAssetsListener(){let e=this.resourcesManager;!e||!this.onAssetsTexturesUpdated||(e.off("assetsTexturesUpdated",this.onAssetsTexturesUpdated),this.onAssetsTexturesUpdated=void 0)}hasBlockAtlas(e){let t=e.currentResources;return!!(t?.blocksAtlasImage&&t.blocksAtlasJson)}async ensureAtlasReady(e){if(await this.ensureMcDataLoaded(),this.hasBlockAtlas(e))return!0;if(typeof document>"u"&&e!==this.resourcesManager)return!1;e.currentConfig={...e.currentConfig,version:r0,noInventoryGui:!0};try{await e.updateAssetsData?.({})}catch{return!1}return this.hasBlockAtlas(e)}async tryApplyMinecraftTextures(){if(!(this.disposed||!this.useMinecraftTextures||this.texturesApplied)){this.textureLoadInProgress=!0;try{let e=this.resourcesManager??new Et;if(!await this.ensureAtlasReady(e)){this.resourcesManager&&this.attachAssetsListener();return}if(this.disposed)return;this.applyMinecraftTexturesFromAtlas(e),this.texturesApplied=!0,this.detachAssetsListener()}catch{this.useMinecraftTextures=!1,this.detachAssetsListener()}finally{this.textureLoadInProgress=!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=s7(e.gradientBg);s&&(this.gradientSkyTexture.dispose(),this.gradientSkyTexture=s,this.gradientSky.material.map=s,this.gradientSky.material.needsUpdate=!0)}}else{let s=s7(e.gradientBg);s?(this.gradientSkyTexture=s,this.gradientSky=new N.Mesh(new N.PlaneGeometry(900,700),new N.MeshBasicMaterial({map:s,depthWrite:!1,side:N.DoubleSide})),this.gradientSky.position.set(0,0,-280),this.gradientSky.renderOrder=-1e3,this.scene.add(this.gradientSky)):this.scene.background=new N.Color(e.bg)}else this.scene.background=new N.Color(e.bg),this.gradientSky&&(this.gradientSky.visible=!1);this.scene.fog instanceof N.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 N.CanvasTexture(r),o=new N.Mesh(new N.PlaneGeometry(280,105),new N.MeshBasicMaterial({map:s,transparent:!0,opacity:1,depthWrite:!1,side:N.DoubleSide,blending:N.AdditiveBlending}));o.position.set(8,4,-320),this.scene.add(o)}spawnBlock(e,t,r){let i=this.createBlockMaterial(e,r),s=new N.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 l={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(l),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 N.MeshBasicMaterial({color:c5(e.blocks),transparent:!0,opacity:r+Math.random()*(i-r),depthWrite:!1,blending:N.AdditiveBlending})}removeBlockEdgeLines(){for(let e of this.blocks){let t=e.mesh.children.filter(r=>r instanceof N.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}applyMinecraftTexturesFromAtlas(e){let t=e.currentResources;if(!t?.blocksAtlasImage||!t.blocksAtlasJson)throw new Error("Block atlas not available");let r=t.blocksAtlasJson,i=r.textures;this.atlasTexture=Qt(t.blocksAtlasImage),this.atlasTexture.flipY=!1,this.atlasTexture.needsUpdate=!0;for(let s of Z1[this.blockGroup]){let o=this.resolveBlockAtlasUv(s,i,r);if(!o)continue;let l=this.atlasTexture.clone();l.flipY=!1,l.offset.set(o.u,o.v),l.repeat.set(o.su,o.sv),l.needsUpdate=!0;let a=s.includes("glass"),v=new N.MeshBasicMaterial({map:l,side:N.DoubleSide,transparent:a,opacity:a?.85:1,alphaTest:a?.08:0,depthWrite:!0,toneMapped:!1});this.blockMaterialPool.set(s,v)}if(this.blockMaterialPool.size===0)throw new Error("No block textures resolved from atlas (check block names vs atlas keys)");this.removeBlockEdgeLines();for(let s of this.blocks){let o=c5([...this.blockMaterialPool.keys()]);s.minecraftBlockName=o,s.mesh.material=this.blockMaterialPool.get(o).clone()}}setScene(e){if(!m0.includes(e)||e===this.curScene||this.transitioning)return;this.transitioning=!0,this.curScene=e;let t=n7[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 N.MeshBasicMaterial&&s.mesh.material.color.set(c5(t.blocks));let r=this.nebGeo.attributes.color;for(let s=0;s<Vi;s++){let o=new N.Color(c5(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<Gi;s++){let o=.2+Math.random()*.8,l=t.galFn(o);i.setXYZ(s,l.r,l.g,l.b)}i.needsUpdate=!0,this.transitioning=!1},150)}setCamera(e){p0.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(g0.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(),this.texturesApplied=!1,this.scheduleMinecraftTextureLoad()}}getSceneId(){return this.curScene}getCameraId(){return this.curCam}getBlockGroupId(){return this.blockGroup}update(e,t){t&&H0(this.camera,this.documentRenderer.canvas);let r=q9[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*i7,l=this.my*i7,a=r.pos(this.camT,o,l),v=r.look(this.camT,o,l);this.camera.position.set(a.x,a.y,a.z),this.camera.lookAt(v.x,v.y,v.z),this.camera.rotation.z=r.roll(this.camT,o);let c=K9[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 N.MeshBasicMaterial){let f=u.mesh.userData.baseOpacity??.38;u.mesh.userData.baseOpacity==null&&(u.mesh.userData.baseOpacity=f);let m=.88+Math.abs(Math.sin(this.animTime*8e-4+u.mesh.position.x*.3))*.12;u.mesh.material.opacity=f*m}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.detachAssetsListener(),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();R();k();import*as u5 from"three";import{Vec3 as a7}from"vec3";E();x();R();k();import X9 from"prismarine-world";import Z9 from"prismarine-chunk";var o7=n=>{let e=X9(n),t=Z9(n),r=new e(n).sync,i=$9(r);for(let s of i)if(s.startsWith("set")&&s!=="setColumn"){let o=r[s].bind(r);r[s]=(...l)=>{let a=l[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(...l)}}return r};function $9(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 d5=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",L0);this._scene=new u5.Scene,this._scene.background=new u5.Color(3294568),this._camera=new u5.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=r0,t=new Et;if(t.currentConfig={version:e,noInventoryGui:!0},await t.updateAssetsData?.({}),this.abortSignal.aborted)return;let r=o7(e),s=b7("prismarine-block")(e),l=globalThis.mcData.blocksArray.filter(m=>{if(!m.name.includes("stained_glass"))return!1;let g=s.fromStateId(m.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,v=100,c=100;for(let m=-v;m<v;m++)for(let g=-c;g<c;g++){let b=l[Math.floor(Math.random()*l.length)];r.setBlockStateId(new a7(m,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 a7(...this._camera.position.toArray()),f=new f0(r,2,u);this.abortSignal.aborted||(this.worldRenderer=new this.WorldRendererClass(this.documentRenderer.renderer,this.options,{version:e,worldView:f,inWorldRenderingConfig:w5,playerStateReactive:So().reactive,rendererState:v0().reactive,nonReactiveState:v0().nonReactive,resourcesManager:t}),this.worldRenderer instanceof L0&&(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&&H0(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,l=s.clientX/window.innerWidth-.5,a=-(s.clientY/window.innerHeight-.5);i?.stop(),i=new ze(e.position).to({x:t+l*o,y:r+a*o},0),i.start(),e.updateProjectionMatrix()},{signal:this.abortSignal})}};E();x();R();k();import*as l7 from"three";var f5=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=q1(r,i)}get v2(){return this.active instanceof O0?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 l7.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"v2":return new O0(this.documentRenderer,{useMinecraftTextures:e.useMinecraftTextures,initialScene:e.v2Scene,initialCamera:e.v2Camera,initialBlockGroup:e.v2BlockGroup,initialCameraSpeed:e.v2CameraSpeed,initialBlockSpeed:e.v2BlockSpeed,resourcesManager:e.resourcesManager},this.abortController.signal);case"worldBlocks":return new d5(this.documentRenderer,this.options,this.abortController.signal);default:return new v5(this.documentRenderer)}}dispose(){this.active?.dispose(),this.active=void 0,this.abortController.abort()}};lr.ColorManagement.enabled=!1;globalThis.THREE=lr;var v7=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),applyTemporaryPlayerSkinOverride:n.entities.applyTemporaryPlayerSkinOverride.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:n.setRain.bind(n),spawnBlockBreakParticles(e,t,r,i,s,o){n.getModule("blockBreakParticles")?.spawnBlockBreakParticles(e,t,r,i,s,o)},spawnBlockCrackParticle(e,t,r,i,s,o,l){n.getModule("blockBreakParticles")?.spawnCrackParticle(e,t,r,i,s,o,l)},async loadGeometryExport(e){let{applyWorldGeometryExport:t}=await Promise.resolve().then(()=>(P1(),o6));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}}}}),tc=[],Wi=(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)}},c7=()=>{let n,e=null,t=null,r=null,i=null,s=(c,u)=>{c.hello,ve?n=L5(c,tc,globalThis):n=c,e=new k5(n,u?.canvas),globalThis.renderer=e.renderer,globalThis.documentRenderer=e,globalThis.threeJsBackend=v,Wi("default",v)},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 f5(e,{...n},u,!!H.env.SINGLE_FILE_BUILD_MODE),Wi("menuBackgroundCreated",t),await t.start(u),Wi("menuBackgroundReady",t)},l=async c=>{if(!e)throw new Error("Document renderer not initialized");t&&(t.dispose(),t=null),r&&(r.destroy(),r=null,i=null,globalThis.world=void 0,globalThis.frameTimingCollector=void 0);let f=ve?L5(c,[Et,u0],globalThis):c;e.nonReactiveState=f.nonReactiveState,globalThis.resourcesManager=f.resourcesManager,r=new L0(e.renderer,n,f),await r.worldReadyPromise,i=f.inWorldRenderingConfig.enableDebugOverlay?new Tr(f.nonReactiveState):null,globalThis.frameTimingCollector=i;let m=e.render;e.render=function(g){m.call(this,g),i?.markFrameStart(),f.inWorldRenderingConfig.paused||r?.render(g),i?.markFrameEnd(),i?.markFrameDisplay()},e.inWorldRenderingConfig=f.inWorldRenderingConfig,globalThis.world=r,Wi("worldReady",r)},a=()=>{t&&(t.dispose(),t=null),e&&e.dispose(),r&&(r.destroy(),r=null)},v={id:"threejs",displayName:`three.js ${lr.REVISION}`,startMenuBackground:o,startWorld:l,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 v7(r)}};return{main:{init:s,backend:v},workerProxy(){return r2({init(c,u){s(c,{canvas:u})},updateSizeExternal(c,u,f){e?.updateSizeExternal(c,u,f)},startMenuBackground:o,startWorld:l,disconnect:a,setRendering:v.setRendering,updateCamera(c,u,f){let m=c?new ec(c.x,c.y,c.z):null;i?.markCameraUpdate(!m),v.updateCamera(m,u,f)},async callBackendMethod(c,...u){if(!r)throw new Error("World renderer not initialized");let m=v7(r)[c];if(!m)throw new Error(`Backend method ${String(c)} is unavailable`);return m(...u)}})}}};var Ni=n=>{let{main:e}=c7();return e.init(n),e.backend};Ni.id="threejs";Ni.displayName="three.js Blocking";Ni.description="Simple, old and stable main thread graphics backend providing balanced performance on top of WebGL2.";E();x();R();k();import*as d7 from"three";function rc(n){let e="threeWorker.js",t;if(H.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 ji=async n=>{let e={onMessage:a=>{}},t=rc(a=>{e.onMessage(a)}),r=i2(t),i=vn();i.onSizeChanged((a,v)=>{r.updateSizeExternal(a,v,window.devicePixelRatio||1)});let s=I5(n,t);try{r.init(s,i.canvas)}catch(a){throw _0(s),a}let o=new Proxy({},{get(a,v){if(typeof v=="string")return async(...c)=>r.callBackendMethod(v,...c)}});return{id:"threejs",displayName:`three.js ${d7.REVISION}`,async startMenuBackground(a){let v=a?.resourcesManager?.currentResources?.mcData;if(v){let u={...w0,items:"itemsArray",entities:"entitiesArray"};await Pn([t],r0,u,v)}let c=I5(a??{},t);try{await r.startMenuBackground(structuredClone(c))}catch(u){throw _0(c),u}},async startWorld(a){let v=a.worldView;e.onMessage=g=>{g?.type==="reloadLoadedChunks"&&v.reloadLoadedChunks().catch(b=>{})};let c={...w0,items:"itemsArray",entities:"entitiesArray"};await Pn([t],a.version,c,a.resourcesManager.currentResources.mcData),a.inWorldRenderingConfig.__syncToWorker=!0,a.playerStateReactive&&(a.playerStateReactive.__syncToWorker=!0),a.rendererState&&(a.rendererState.__syncFromWorker=!0),a.nonReactiveState&&(a.nonReactiveState.__syncFromWorker=!0),a.nonReactiveState.__syncFromWorkerInterval=200;let u=I5(a,t);try{await r.startWorld(structuredClone(u))}catch(g){throw _0(u),g}r.updateSizeExternal(i.size.width,i.size.height,window.devicePixelRatio||1);let f=E0("fps");setInterval(()=>{let{fps:g,avgRenderTime:b,worstRenderTime:A}=a.nonReactiveState;f.updateText(`FPS: ${g.toFixed(0)} (${b.toFixed(0)}ms/${A.toFixed(0)}ms)`),a.nonReactiveState.fps=0},1e3);let m=E0("downloaded-chunks",100,140,20,{className:A0});setInterval(()=>{let g=(n.config.statsVisible??0)>1;m.setVisibility(g),g&&m.updateText(a.nonReactiveState.world.chunksFullInfo)},200)},disconnect(){i.destroy(),r.disconnect(),t.terminate()},setRendering(a){r.setRendering(a)},updateCamera(a,v,c){r.updateCamera(a?{x:a.x,y:a.y,z:a.z}:null,v,c)},soundSystem:void 0,backendMethods:o}};ji.id="threejs-off-thread";ji.displayName="three.js Multi-thread EXPERIMENTAL";ji.description=["(UNSTABLE, DO NOT USE ON ANDROID).","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{No as AppViewer,v5 as ClassicMenuBackground,k5 as DocumentRenderer,Zi as HIGH_TEXTURE_COUNT,gr as LONG_RENDER_TIME_MS,Xi as LOW_FPS_THRESHOLD,j0 as LoadedResourcesTransferrable,A0 as MC_RENDERER_DEBUG_OVERLAY_CLASS,r0 as MENU_BACKGROUND_MC_VERSION,T5 as MENU_BACKGROUND_MOTION_DEFAULTS,Mt as MENU_BACKGROUND_OPTION_DEFAULTS,Z1 as MINECRAFT_BLOCK_GROUPS,g0 as MINECRAFT_BLOCK_GROUP_IDS,M5 as MINECRAFT_BLOCK_GROUP_LABELS,f5 as MenuBackgroundRenderer,_5 as PerformanceMonitor,jo as RENDERER_DEFAULT_OPTIONS,Qo as RENDERER_OPTIONS_META,Yo as RENDERER_RENDER_GUI_SECTIONS,Et as ResourcesManager,O0 as V2MenuBackground,p0 as V2_CAMERA_IDS,S5 as V2_CAMERA_LABELS,m0 as V2_SCENE_IDS,R5 as V2_SCENE_LABELS,d5 as WorldBlocksMenuBackground,f0 as WorldView,u0 as WorldViewWorker,vn as addCanvasForWorker,el as applyMenuBackgroundLiveOptions,lm as applyRendererEnableLighting,sl as applyRendererOptions,om as applyRendererWorldViewOptions,V0 as chunkPos,ji as createGraphicsBackendOffThread,Ni as createGraphicsBackendSingleThread,dd as createWorldRendererConfig,ko as defaultGraphicsBackendConfig,Ji as defaultPerformanceInstabilityFactors,w5 as defaultWorldRendererConfig,To as delayedIterator,$i as formatPerformanceFactorsDebug,v0 as getDefaultRendererState,Xo as getInitialPlayerState,ll as getInitialPlayerStateRenderer,al as getPlayerStateUtils,ve as isWebWorker,sm as menuBackgroundOptionsFromStorage,It as menuBackgroundSpeedToMultiplier,N7 as migrateRendererOptions,un as rendererShaderCubeDebugModeToValue,B7 as sectionPos,am as subscribeRendererOptions};
21703
+ }`})}},Y1=class{constructor(e){this.worldRenderer=e;d(this,"points");d(this,"timer",new Ce.Timer);d(this,"enabled",!1);d(this,"currentTime");d(this,"enablementCheck",()=>this.currentTime?this.currentTime>13500&&this.currentTime<23e3:!1);d(this,"render",()=>{if(!this.points)return;this.points.position.set(0,0,0);let e=this.points.material;this.timer.update(performance.now()),e.uniforms.time.value=this.timer.getElapsed()*.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 Ce.BufferGeometry,l=b=>new Ce.Vector3().setFromSpherical(new Ce.Spherical(b,Math.acos(1-Math.random()*2),Math.random()*2*Math.PI)),a=[],v=[],c=Array.from({length:r},()=>(.5+.5*Math.random())*i),u=new Ce.Color,f=e+t,m=t/r;for(let b=0;b<r;b++)f-=m*Math.random(),a.push(...l(f).toArray()),u.setHSL(b/r,s,.9),v.push(u.r,u.g,u.b);o.setAttribute("position",new Ce.Float32BufferAttribute(a,3)),o.setAttribute("color",new Ce.Float32BufferAttribute(v,3)),o.setAttribute("size",new Ce.Float32BufferAttribute(c,1));let g=new Q1;g.blending=Ce.AdditiveBlending,g.depthTest=!0,g.depthWrite=!1,g.transparent=!0,this.points=new Ce.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)}},e7={id:"starfield",controller:Y1,enabledDefault:!0,cannotBeDisabled:!0};var t7={starfield:e7,futuristicReveal:$6,rain:K6,cameraBobbing:j6,blockBreakParticles:N6};var At=class At extends Hr{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,"cameraSectionPos",new t0(0,0,0));d(this,"holdingBlock");d(this,"holdingBlockLeft");d(this,"scene",new Z.Scene);d(this,"ambientLight",new Z.AmbientLight(13421772,At.LEGACY_TO_PHYSICAL_LIGHT));d(this,"directionalLight",new Z.DirectionalLight(16777215,.5*At.LEGACY_TO_PHYSICAL_LIGHT));d(this,"entities",new ii(this,globalThis.mcData));d(this,"performanceMonitor");d(this,"cameraGroupVr");d(this,"material",new Z.MeshBasicMaterial({vertexColors:!0,transparent:!0,alphaTest:.1}));d(this,"itemsTexture");d(this,"cursorBlock");d(this,"onRender",[]);d(this,"lastRenderTime",0);d(this,"lastSciFiTickMs",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 mi(this.scene));d(this,"cameraWorldPos",{x:0,y:0,z:0});d(this,"_cameraPositionAccessWarned",!1);d(this,"_tmpCameraPos",new Z.Vector3);d(this,"currentPosTween");d(this,"currentRotTween");d(this,"_tpDirection",new Z.Vector3);d(this,"_tpPitchQuat",new Z.Quaternion);d(this,"_tpYawQuat",new Z.Quaternion);d(this,"_tpFinalQuat",new Z.Quaternion);d(this,"_tpScenePos",new Z.Vector3);d(this,"_tpAxisX",new Z.Vector3(1,0,0));d(this,"_tpAxisY",new Z.Vector3(0,1,0));d(this,"_tpChunkWorldPos",new Z.Vector3);d(this,"debugOverlayAdded",!1);d(this,"debugRaycastHelper");d(this,"debugHitPoint");d(this,"prevFramePerspective",null);this.performanceMonitor=new _5(this.reactiveState.world.instabilityFactors),this.renderer=t;let s=At.getRendererInfo(t)??"...";i.rendererState.renderer=s,this.chunkMeshManager=new ar(this,this.scene,this.material,this.worldSizeParams.worldHeight,this.viewDistance),this.onRenderDistanceChanged=o=>{this.chunkMeshManager.updateViewDistance(o)},typeof window<"u"&&(window.setBlockLightmap=o=>{this.chunkMeshManager.setBlockLightmapParams(o)}),this.syncSkyLevelFromTime(this.timeOfTheDay),this.cursorBlock=new ni(this),this.holdingBlock=Z5(this),this.holdingBlockLeft=Z5(this,!0);for(let o of Object.values(t7))this.registerModule(o);this.skyboxRenderer=new fi(this.realScene,!1,null),this.skyboxRenderer.init(),this.addDebugOverlay(),this.resetScene(),this.init(),this.soundSystem=new oi(this),this.cameraShake=new ai(this,this.onRender),this.media=new li(this),this.fireworksLegacy=new di(this),this.waypoints=new ci(this),this.cinimaticScript=new ui(this,(o,l,a)=>this.setCinimaticCamera(o,l,a),o=>this.setCinimaticFov(o),()=>({position:new t0(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 hi(this.realScene,this.sceneOrigin),this.renderUpdateEmitter.on("chunkFinished",o=>{this.finishChunk(o)}),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}setRain(t){this.worldRendererConfig.isRaining=t,this.toggleModule("rain",t)}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,v,c)=>Math.abs(a)>i||Math.abs(v)>i||Math.abs(c)>i,o=()=>{!r._cameraPositionAccessWarned&&typeof H<"u"},l=new Proxy(t,{set(a,v,c){return(v==="x"||v==="y"||v==="z")&&typeof c=="number"&&Math.abs(c)>i&&o(),a[v]=c,!0},get(a,v,c){let u=a[v];return v==="set"?function(f,m,g){return s(f,m,g)&&o(),a.set(f,m,g)}:v==="setX"||v==="setY"||v==="setZ"?function(f){return Math.abs(f)>i&&o(),a[v](f)}:v==="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:l,configurable:!0,enumerable:!0})}worldSwitchActions(){this.onWorldSwitched.push(()=>{this.getModule("futuristicReveal")?.onWorldSwitched?.(),this.protocolCustomBlocks.clear(),this.sectionsOffsetsAnimations={},this.waypoints.clear(),this.cinimaticScript.stopScript(),this.fireworks.clear(),this.syncSkyLevelFromTime(this.timeOfTheDay)})}downloadWorldGeometry(){B1(this,new Z.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 Z.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 Z.Vector2);this.camera=new Z.PerspectiveCamera(75,t.x/t.y,.1,1e3),this._wrapCameraPositionWithWarning(),this.cameraContainer=new Z.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*At.LEGACY_TO_PHYSICAL_LIGHT)}),this.onReactivePlayerStateUpdated("directionalLight",t=>{t&&(this.directionalLight.intensity=t*At.LEGACY_TO_PHYSICAL_LIGHT)}),this.onReactivePlayerStateUpdated("lookingAtBlock",t=>{this.cursorBlock.setHighlightCursorBlock(t?new t0(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 t0(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",i=>{this.updateShowChunksBorder(i)}),this.onReactiveConfigUpdated("defaultSkybox",i=>{this.skyboxRenderer.updateDefaultSkybox(i)}),this.onReactiveConfigUpdated("shaderCubeDebugMode",()=>{this.chunkMeshManager.syncCubeShaderUniforms(),this.chunkMeshManager.syncLegacyShaderUniforms()});let t=()=>{let i=this.worldRendererConfig;this.chunkMeshManager.setShadingTheme(i.shadingTheme,i.cardinalLight)};this.onReactiveConfigUpdated("shadingTheme",t),this.onReactiveConfigUpdated("cardinalLight",t),this.onReactiveConfigUpdated("futuristicReveal",()=>{this.updateModulesFromConfig()});let r=this.displayOptions.inWorldRenderingConfig.handRenderer;this.onReactiveConfigUpdated("handRenderer",i=>{if(i===r)return;r=i;let s=this.holdingBlock.ready,o=this.holdingBlockLeft.ready;this.holdingBlock.dispose(),this.holdingBlockLeft.dispose(),this.holdingBlock=Z5(this),this.holdingBlockLeft=Z5(this,!0),s&&(this.holdingBlock.ready=!0,this.holdingBlock.updateItem()),o&&(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=Qt(t.blocksAtlasImage);s.needsUpdate=!0,s.flipY=!1,this.material.map=s,this.chunkMeshManager.syncCubeShaderUniforms(),this.chunkMeshManager.syncLegacyShaderUniforms();let o=Qt(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 Z.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),this.syncSkyLevelFromTime(t)}syncSkyLevelFromTime(t){let r=Ht(t)/15;this.chunkMeshManager.setSkyLevel(r)}onDayCycleSkyLightChanged(t){}biomeUpdated(t){t?.temperature!==void 0&&this.skyboxRenderer.updateTemperature(t.temperature)}biomeReset(){this.skyboxRenderer.updateTemperature(A1)}getItemRenderData(t,r){return U3(t,r,this.resourcesManager,this.playerStateReactive)}async demoModel(){let t=cursorBlockRel(0,1,0).position,r=await D5();w2(r,t);let i=new Z.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 Z.BoxHelper(r,16776960);r.add(i),this.realScene.add(r)}addDebugOverlay(){if(this.debugOverlayAdded)return;this.debugOverlayAdded=!0;let t=E0("debug-overlay",80,0,void 0,{className:A0});setInterval(()=>{if(t.setVisibility(this.displayAdvancedStats),this.displayAdvancedStats){let r=v=>new Intl.NumberFormat("en-US",{}).format(v),i=v=>new Intl.NumberFormat("en-US",{notation:"compact",maximumFractionDigits:1}).format(v),s="";s+=`TE: ${r(this.renderer.info.memory.textures)} `;let o=this.chunkMeshManager.getGlobalBufferStats();if(o.shaderFaces){let v=o.shaderFaces;s+=`CUBE: ${i(v.used)}/${i(v.capacity)}f `}if(o.legacyOpaque){let v=o.legacyOpaque;s+=`LEG-O: ${i(v.used)}/${i(v.capacity)}q `}if(o.legacyBlend){let v=o.legacyBlend;s+=`LEG-B: ${i(v.used)}/${i(v.capacity)}q `}s+=`MEM: ${this.chunkMeshManager.getEstimatedMemoryUsage().total} `;let l=this.cameraCollisionBlockCache.getAllocatedBytes();l>0&&(s+=`CAM: ${i(l)}b `);let a=$i(this.reactiveState.world.instabilityFactors);a&&(s+=`PF: ${a} `),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)),v=r.mesh??r.shaderMesh??r.children.find(c=>c.name==="mesh"||c.name==="shaderMesh");v&&(v.renderOrder=a)}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),this.getModule("futuristicReveal")?.onChunkFinished?.()}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<At.MAX_SECTION_UPDATE_BUFFER_MS){let[a,v,c]=s.split(",").map(Number),u=[`${a-16},${v},${c}`,`${a+16},${v},${c}`,`${a},${v-r},${c}`,`${a},${v+r},${c}`,`${a},${v},${c-16}`,`${a},${v},${c+16}`],f=!1;for(let m of u)if(this.sectionsWaiting.has(m)&&!this.pendingSectionUpdates.has(m)&&this.sectionObjects[m]){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 l=o.key.split(","),a=`${l[0]},${l[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}let v=this.chunkMeshManager.updateSection(o.key,o.geometry);this.updatePosDataChunk(o.key),v&&this.getModule("futuristicReveal")?.onSectionMeshed?.(o.key,o.geometry,v)}}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}let s=this.chunkMeshManager.updateSection(t.key,t.geometry);this.updatePosDataChunk(t.key),s&&this.getModule("futuristicReveal")?.onSectionMeshed?.(t.key,t.geometry,s)}}getCameraPosition(t){return(t??this._tmpCameraPos).set(this.cameraWorldPos.x,this.cameraWorldPos.y,this.cameraWorldPos.z)}getSectionCameraPosition(){let t=this.getCameraPosition();return new t0(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 Z.Vector3(this.cameraWorldPos.x,this.cameraWorldPos.y,this.cameraWorldPos.z));let s=this.playerStateReactive.perspective==="third_person_back",o=4,l=this._tpDirection.set(0,0,-1),a=this._tpPitchQuat.setFromAxisAngle(this._tpAxisX,i),v=this._tpYawQuat.setFromAxisAngle(this._tpAxisY,r),c=this._tpFinalQuat.multiplyQuaternions(v,a);l.applyQuaternion(c),s&&l.multiplyScalar(-1),this.DEBUG_RAYCAST&&this.debugRaycast(t,l,o);let u=.25,f=.05,m=.4,g=this.cameraCollisionBlockCache,b=U6(t.x,t.y,t.z,l.x,l.y,l.z,o,u,f,(y,_,S)=>g.isSolidBlock(y,_,S)),A=o;return b!==void 0&&(A=Math.min(A,b.distance)),A<m&&(A=m),new t0(t.x+l.x*A,t.y+l.y*A,t.z+l.z*A)}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 Z.Vector3(this.sceneOrigin.toSceneX(t.x),this.sceneOrigin.toSceneY(t.y),this.sceneOrigin.toSceneZ(t.z));this.debugRaycastHelper=new Z.ArrowHelper(r.clone().normalize(),s,i,16711680,i*.1,i*.05),this.realScene.add(this.debugRaycastHelper);let o=new Z.SphereGeometry(.2,8,8),l=new Z.MeshBasicMaterial({color:65280});this.debugHitPoint=new Z.Mesh(o,l),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,l=Math.min(o/At.FOV_TRANSITION_MS,1),a=v=>1-(1-v)**3;this.animatedFov+=(i-this.animatedFov)*a(l),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 ze(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,l=Math.PI/2;s.yaw<l&&r>Math.PI+l?o=-Math.PI*2:r<l&&s.yaw>Math.PI+l&&(o=Math.PI*2),this.currentRotTween?.stop(),this.currentRotTween=new ze(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 Z.Vector3(this.cameraWorldPos.x,this.cameraWorldPos.y,this.cameraWorldPos.z),l=this.getThirdPersonCamera(o,r,i),a=o.distanceTo(new Z.Vector3(l.x,l.y,l.z)),v=s==="third_person_back"?a:-a;this.camera.position.set(0,0,v),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:l}=this.reactiveDebugParams,a=this.getSectionHeight(),v=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,m,g]=c.split(",").map(Number),b=s&&t!==void 0?m<=v+t:o&&r!==void 0?m>=v-r:l&&i!==void 0?Math.abs(m-v)<=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 S=this.renderer.getSize(new Z.Vector2);this.camera.aspect=S.width/S.height,this.camera.updateProjectionMatrix()}let o=0;if(!this.reactiveDebugParams.disableEntities){let S=performance.now();this.entities.render(),o=performance.now()-S}let l=this.cameraGroupVr instanceof Z.Group?this.cameraGroupVr.children.find(S=>S instanceof Z.PerspectiveCamera):this.camera;this.applyPendingSectionUpdates();let a=performance.now(),v=a-this.lastSciFiTickMs;this.lastSciFiTickMs=a,this.getModule("futuristicReveal")?.tick?.(v,a);let c=this.cameraWorldPos.x,u=this.cameraWorldPos.y,f=this.cameraWorldPos.z;this.chunkMeshManager.maybeRebase({x:c,y:u,z:f});let m=this.chunkMeshManager.getRenderOrigin(),g=this.chunkMeshManager.globalBlockBuffer;g&&(g.setCameraOrigin(m,c,u,f),g.setDebugOverlay(this.displayOptions.inWorldRenderingConfig.enableDebugOverlay),g.compactStep(),g.hasPendingUploads()&&g.uploadDirtyRange(),g.suppressThreeDraw());let b=this.chunkMeshManager.globalLegacyBuffer;b&&(b.setDebugOverlay(this.displayOptions.inWorldRenderingConfig.enableDebugOverlay),b.compactStep(),b.hasPendingUploads()&&b.uploadDirtyRange(),b.suppressThreeDraw());let A=this.chunkMeshManager.globalLegacyBlendBuffer;A&&(A.setDebugOverlay(this.displayOptions.inWorldRenderingConfig.enableDebugOverlay),A.compactStep(),A.hasPendingUploads()&&A.uploadDirtyRange(),A.suppressThreeDraw()),this.chunkMeshManager.markCullDirtyIfBufferStateChanged(),this.chunkMeshManager.setLegacyCameraOrigin(c,u,f),this.chunkMeshManager.updateCullDirtyFromCamera(l,c,u,f),this.chunkMeshManager.cullDirty&&(this.chunkMeshManager.updateSectionCullAndSort(l,this.cameraWorldPos.x,this.cameraWorldPos.y,this.cameraWorldPos.z),this.chunkMeshManager.clearCullDirty()),this.renderer.render(this.scene,l),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 S of this.fountains)this.sectionObjects[S.sectionId]&&!this.sectionObjects[S.sectionId].foutain&&(S.createParticles(this.sectionObjects[S.sectionId]),this.sectionObjects[S.sectionId].foutain=!0),S.render();this.waypoints.render(),this.fireworks.update();for(let S of this.onRender)S(i);let _=performance.now()-r;this.worldRendererConfig.autoLowerRenderDistance&&this.chunkMeshManager.recordRenderTime(_),this.renderTimeAvgCount++,this.renderTimeAvg=(this.renderTimeAvg*(this.renderTimeAvgCount-1)+_)/this.renderTimeAvgCount,this.renderTimeMax=Math.max(this.renderTimeMax,_),this.performanceMonitor.onFrame({totalMs:_,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(l=>l.name==="textures")?.value,!!o)try{let a=JSON.parse(O.from(o,"base64").toString()).textures?.SKIN?.url,{skinTexturesProxy:v}=this.worldRendererConfig;v&&(a=a?.replace("http://textures.minecraft.net/",v).replace("https://textures.minecraft.net/",v));let c=Kt(this,a,Jt.head),u=new Z.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,-Z.MathUtils.degToRad(r*(i?90:45/2)),0),u.scale.set(.8,.8,.8),u}catch{}}lightUpdate(t,r){for(let i=this.worldSizeParams.minY;i<this.worldSizeParams.worldHeight;i+=16)this.setSectionDirty(new t0(t,i,r))}rerenderAllChunks(){for(let t of Object.keys(this.sectionObjects)){let[r,i,s]=t.split(",").map(Number);this.setSectionDirty(new t0(r,i,s))}}updateShowChunksBorder(t){this.chunkMeshManager.updateAllBoxHelpers(t)}resetWorld(){super.resetWorld(),this.pendingSectionUpdates.clear(),this.pendingSectionBufferStartTimes.clear(),this.chunkMeshManager.dispose(),this.chunkMeshManager=new ar(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]=En(t);return Object.fromEntries(Object.entries(this.sectionObjects).map(([l,a])=>{let[v,c,u]=l.split(",").map(Number),[f,m,g]=En({x:v,y:c,z:u});return[r?`${f-i},${m-s},${g-o}`:`${f-i},${g-o}`,a]}))}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.clearPendingSectionUpdatesForChunk(t,r);let i=this.getSectionHeight(),s=this.worldMinYRender;for(let o=s;o<this.worldSizeParams.worldHeight;o+=i){let l=`${t},${o},${r}`;this.chunkMeshManager.sectionObjects[l]&&this.chunkMeshManager.releaseSection(l)}this.chunkMeshManager.onChunkRemovedFromGate(`${t},${r}`)}updateViewerPosition(t){super.updateViewerPosition(t),this.chunkMeshManager.pendingNearReveal.size>0&&this.chunkMeshManager.tryRevealPending()}onViewerChunkPositionChanged(){this.chunkMeshManager.tryRevealPending()}setSectionDirty(...t){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,l,a=this.sceneOrigin.getWorldPosition(t);a?(s=a.x,o=a.y,l=a.z):(s=this.sceneOrigin.toWorldX(t.position.x),o=this.sceneOrigin.toWorldY(t.position.y),l=this.sceneOrigin.toWorldZ(t.position.z));let v=Math.floor(s/16)*16,c=Math.floor(l/16)*16,u=Math.floor(o/i)*i,f=`${v},${c}`,m=`${v},${u},${c}`;return!!this.finishedChunks[f]||!!this.sectionObjects[m]}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(At,"LEGACY_TO_PHYSICAL_LIGHT",Math.PI),d(At,"FOV_TRANSITION_MS",200),d(At,"MAX_SECTION_UPDATE_BUFFER_MS",500);var L0=At;E();x();R();k();E();x();R();k();var r0="1.21.4";E();x();R();k();function H0(n,e){n.aspect=e.width/e.height,n.updateProjectionMatrix()}E();x();R();k();function q1(n,e=!1){return n?.mode?n.mode:e?"worldBlocks":Mt.mode}E();x();R();k();import*as de from"three";E();x();R();k();function K1(...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 J1=new Date,r7=J1.getMonth()===11&&J1.getDate()>=24&&J1.getDate()<=26,Q9=["panorama_3.webp","panorama_1.webp","panorama_4.webp","panorama_5.webp","panorama_0.webp","panorama_2.webp"],Y9=200,v5=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 de.Scene,this.scene.background=new de.Color(3294568);let t=new de.AmbientLight(13421772);this.scene.add(t);let r=new de.DirectionalLight(16777215,.5);r.position.set(1,1,.5).normalize(),r.castShadow=!0,this.scene.add(r),this.camera=new de.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&&H0(this.camera,this.documentRenderer.canvas)}dispose(){this.scene.clear(),this.panoramaGroup=null,this.startTimes.clear()}buildCubemap(){let e=new de.BoxGeometry(1e3,1e3,1e3),t=[];for(let s of Q9)(async()=>{let l=K1("background",r7?"christmas":"",s),a=await y0(l),v=Qt(a);v.matrixAutoUpdate=!1,v.matrix.set(-1,0,1,0,1,0,0,0,1),v.wrapS=de.ClampToEdgeWrapping,v.wrapT=de.ClampToEdgeWrapping,v.minFilter=de.LinearFilter,v.magFilter=de.LinearFilter;let c=new de.MeshBasicMaterial({map:v,transparent:!0,side:de.DoubleSide,depthWrite:!1,opacity:0});this.startTimes.set(c,Date.now()),t.push(c)})().catch(l=>{});let r=new de.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 l=Date.now()-o;s.opacity=Math.min(1,l/Y9)}}};let i=new de.Object3D;if(i.add(r),!r7)for(let s=0;s<20;s++){let o=new zt("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 l=Math.random()*.01;o.children[0].onBeforeRender=()=>{o.rotation.y+=l,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 y0(K1("background","panorama_0.webp")),t=Qt(e),r=new de.Mesh(new de.PlaneGeometry(1e3,1e3),new de.MeshBasicMaterial({map:t}));r.position.set(0,0,-500),this.scene.add(r)}};E();x();R();k();import*as N from"three";var i7=.1,Z1={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"]},n7={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 N.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 N.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 N.Color(n*.4,0,n),ambient:393232,dir:10040319,pt1:11158783,pt2:4456618,name:"THE END"},cyber:{bg:792610,fog:792610,fogD:.008,blocks:[65535,4521932,11206468,6741503,8978278,65450],emit:[666163,668450,665656],nebula:[1192e3,1587240,1323588],galFn:n=>new N.Color(n*.15,n*.85,n*.95),ambient:1716288,dir:6750156,pt1:4521966,pt2:10092356,name:"CYBER",starColor:13431039,starOpacity:.75,galaxyOpacity:.62,nebulaOpacity:.36,edgeLineColor:4521949,blockOpacity:[.38,.54]},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 N.Color;return n<.4?e.lerpColors(new N.Color(16054527),new N.Color(14215423),n/.4):n<.75?e.lerpColors(new N.Color(14215423),new N.Color(11061488),(n-.4)/.35):e.lerpColors(new N.Color(11061488),new N.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]}},q9={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}},K9={cruise:1,barrel:1.6,dive:2.2,orbit:.7,snake:1.4},J9=250,Gi=1e4,Vi=3e3,c5=n=>n[Math.floor(Math.random()*n.length)],X1=n=>"#"+n.toString(16).padStart(6,"0"),s7=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,X1(n.top)),n.mid!=null&&s.addColorStop(.45,X1(n.mid)),s.addColorStop(1,X1(n.bottom)),t.fillStyle=s,t.fillRect(0,0,r,i);let o=new N.CanvasTexture(e);return o.needsUpdate=!0,o},O0=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 N.Group);d(this,"galaxy");d(this,"nebula");d(this,"stars");d(this,"galGeo");d(this,"nebGeo");d(this,"bGeo",new N.BoxGeometry(1,1,1));d(this,"eGeo",new N.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);d(this,"texturesApplied",!1);d(this,"textureLoadInProgress",!1);d(this,"onAssetsTexturesUpdated");let i=Mt;this.curScene=t.initialScene??i.v2Scene,this.curCam=t.initialCamera??i.v2Camera,this.blockGroup=t.initialBlockGroup??i.v2BlockGroup,this.cameraSpeed=t.initialCameraSpeed??T5.camera,this.blockSpeed=t.initialBlockSpeed??T5.block,this.useMinecraftTextures=t.useMinecraftTextures??i.minecraftTextures,this.resourcesManager=t.resourcesManager;let s=n7[this.curScene];this.scene=new N.Scene,this.scene.fog=new N.FogExp2(s.fog,s.fogD),this.applyScenePalette(s),this.camera=new N.PerspectiveCamera(80,this.documentRenderer.canvas.width/this.documentRenderer.canvas.height,.1,700),this.ambient=new N.AmbientLight(s.ambient,2.5),this.scene.add(this.ambient),this.dir=new N.DirectionalLight(s.dir,4),this.dir.position.set(1,1,0),this.scene.add(this.dir),this.pt1=new N.PointLight(s.pt1,5,100),this.scene.add(this.pt1),this.pt2=new N.PointLight(s.pt2,4,80),this.pt2.position.set(30,20,-30),this.scene.add(this.pt2);for(let f=0;f<J9;f++)this.spawnBlock(s,!0);if(!this.useMinecraftTextures){let f=s.edgeLineColor??62975;for(let m=0;m<40;m++){let g=new N.LineBasicMaterial({color:f,transparent:!0,opacity:.25});c5(this.blocks).mesh.add(new N.LineSegments(this.eGeo,g))}}this.scene.add(this.bGroup);let o=new N.BufferGeometry,l=new Float32Array(5e3*3);for(let f=0;f<5e3*3;f++)l[f]=(Math.random()-.5)*500;o.setAttribute("position",new N.BufferAttribute(l,3)),this.stars=new N.Points(o,new N.PointsMaterial({color:s.starColor??16777215,size:.3,transparent:!0,opacity:s.starOpacity??.7,sizeAttenuation:!0})),this.scene.add(this.stars),this.galGeo=new N.BufferGeometry;let a=new Float32Array(Gi*3),v=new Float32Array(Gi*3);for(let f=0;f<Gi;f++){let m=f%3,g=Math.random(),b=m/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 _=.2+g*.8,S=s.galFn(_);v[f*3]=S.r,v[f*3+1]=S.g,v[f*3+2]=S.b}this.galGeo.setAttribute("position",new N.BufferAttribute(a,3)),this.galGeo.setAttribute("color",new N.BufferAttribute(v,3)),this.galaxy=new N.Points(this.galGeo,new N.PointsMaterial({size:.9,vertexColors:!0,transparent:!0,opacity:s.galaxyOpacity??.55,sizeAttenuation:!0})),this.scene.add(this.galaxy),this.nebGeo=new N.BufferGeometry;let c=new Float32Array(Vi*3),u=new Float32Array(Vi*3);for(let f=0;f<Vi;f++){let m=25+Math.random()*110,g=Math.random()*Math.PI*2,b=(Math.random()-.5)*Math.PI*.5;c[f*3]=m*Math.cos(g)*Math.cos(b),c[f*3+1]=m*Math.sin(b)*.6,c[f*3+2]=m*Math.sin(g)*Math.cos(b)-80;let A=new N.Color(c5(s.nebula));u[f*3]=A.r,u[f*3+1]=A.g,u[f*3+2]=A.b}this.nebGeo.setAttribute("position",new N.BufferAttribute(c,3)),this.nebGeo.setAttribute("color",new N.BufferAttribute(u,3)),this.nebula=new N.Points(this.nebGeo,new N.PointsMaterial({size:3,vertexColors:!0,transparent:!0,opacity:s.nebulaOpacity??.3,sizeAttenuation:!0})),this.scene.add(this.nebula),this.addBackgroundTextPlane(),this.setupMouseTracking()}async init(){this.useMinecraftTextures&&this.scheduleMinecraftTextureLoad()}scheduleMinecraftTextureLoad(){!this.useMinecraftTextures||this.disposed||this.texturesApplied||this.textureLoadInProgress||this.tryApplyMinecraftTextures()}attachAssetsListener(){let e=this.resourcesManager;!e||this.onAssetsTexturesUpdated||(this.onAssetsTexturesUpdated=()=>this.scheduleMinecraftTextureLoad(),e.on("assetsTexturesUpdated",this.onAssetsTexturesUpdated))}detachAssetsListener(){let e=this.resourcesManager;!e||!this.onAssetsTexturesUpdated||(e.off("assetsTexturesUpdated",this.onAssetsTexturesUpdated),this.onAssetsTexturesUpdated=void 0)}hasBlockAtlas(e){let t=e.currentResources;return!!(t?.blocksAtlasImage&&t.blocksAtlasJson)}async ensureAtlasReady(e){if(await this.ensureMcDataLoaded(),this.hasBlockAtlas(e))return!0;if(typeof document>"u"&&e!==this.resourcesManager)return!1;e.currentConfig={...e.currentConfig,version:r0,noInventoryGui:!0};try{await e.updateAssetsData?.({})}catch{return!1}return this.hasBlockAtlas(e)}async tryApplyMinecraftTextures(){if(!(this.disposed||!this.useMinecraftTextures||this.texturesApplied)){this.textureLoadInProgress=!0;try{let e=this.resourcesManager??new Et;if(!await this.ensureAtlasReady(e)){this.resourcesManager&&this.attachAssetsListener();return}if(this.disposed)return;this.applyMinecraftTexturesFromAtlas(e),this.texturesApplied=!0,this.detachAssetsListener()}catch{this.useMinecraftTextures=!1,this.detachAssetsListener()}finally{this.textureLoadInProgress=!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=s7(e.gradientBg);s&&(this.gradientSkyTexture.dispose(),this.gradientSkyTexture=s,this.gradientSky.material.map=s,this.gradientSky.material.needsUpdate=!0)}}else{let s=s7(e.gradientBg);s?(this.gradientSkyTexture=s,this.gradientSky=new N.Mesh(new N.PlaneGeometry(900,700),new N.MeshBasicMaterial({map:s,depthWrite:!1,side:N.DoubleSide})),this.gradientSky.position.set(0,0,-280),this.gradientSky.renderOrder=-1e3,this.scene.add(this.gradientSky)):this.scene.background=new N.Color(e.bg)}else this.scene.background=new N.Color(e.bg),this.gradientSky&&(this.gradientSky.visible=!1);this.scene.fog instanceof N.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 N.CanvasTexture(r),o=new N.Mesh(new N.PlaneGeometry(280,105),new N.MeshBasicMaterial({map:s,transparent:!0,opacity:1,depthWrite:!1,side:N.DoubleSide,blending:N.AdditiveBlending}));o.position.set(8,4,-320),this.scene.add(o)}spawnBlock(e,t,r){let i=this.createBlockMaterial(e,r),s=new N.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 l={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(l),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 N.MeshBasicMaterial({color:c5(e.blocks),transparent:!0,opacity:r+Math.random()*(i-r),depthWrite:!1,blending:N.AdditiveBlending})}removeBlockEdgeLines(){for(let e of this.blocks){let t=e.mesh.children.filter(r=>r instanceof N.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}applyMinecraftTexturesFromAtlas(e){let t=e.currentResources;if(!t?.blocksAtlasImage||!t.blocksAtlasJson)throw new Error("Block atlas not available");let r=t.blocksAtlasJson,i=r.textures;this.atlasTexture=Qt(t.blocksAtlasImage),this.atlasTexture.flipY=!1,this.atlasTexture.needsUpdate=!0;for(let s of Z1[this.blockGroup]){let o=this.resolveBlockAtlasUv(s,i,r);if(!o)continue;let l=this.atlasTexture.clone();l.flipY=!1,l.offset.set(o.u,o.v),l.repeat.set(o.su,o.sv),l.needsUpdate=!0;let a=s.includes("glass"),v=new N.MeshBasicMaterial({map:l,side:N.DoubleSide,transparent:a,opacity:a?.85:1,alphaTest:a?.08:0,depthWrite:!0,toneMapped:!1});this.blockMaterialPool.set(s,v)}if(this.blockMaterialPool.size===0)throw new Error("No block textures resolved from atlas (check block names vs atlas keys)");this.removeBlockEdgeLines();for(let s of this.blocks){let o=c5([...this.blockMaterialPool.keys()]);s.minecraftBlockName=o,s.mesh.material=this.blockMaterialPool.get(o).clone()}}setScene(e){if(!m0.includes(e)||e===this.curScene||this.transitioning)return;this.transitioning=!0,this.curScene=e;let t=n7[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 N.MeshBasicMaterial&&s.mesh.material.color.set(c5(t.blocks));let r=this.nebGeo.attributes.color;for(let s=0;s<Vi;s++){let o=new N.Color(c5(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<Gi;s++){let o=.2+Math.random()*.8,l=t.galFn(o);i.setXYZ(s,l.r,l.g,l.b)}i.needsUpdate=!0,this.transitioning=!1},150)}setCamera(e){p0.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(g0.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(),this.texturesApplied=!1,this.scheduleMinecraftTextureLoad()}}getSceneId(){return this.curScene}getCameraId(){return this.curCam}getBlockGroupId(){return this.blockGroup}update(e,t){t&&H0(this.camera,this.documentRenderer.canvas);let r=q9[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*i7,l=this.my*i7,a=r.pos(this.camT,o,l),v=r.look(this.camT,o,l);this.camera.position.set(a.x,a.y,a.z),this.camera.lookAt(v.x,v.y,v.z),this.camera.rotation.z=r.roll(this.camT,o);let c=K9[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 N.MeshBasicMaterial){let f=u.mesh.userData.baseOpacity??.38;u.mesh.userData.baseOpacity==null&&(u.mesh.userData.baseOpacity=f);let m=.88+Math.abs(Math.sin(this.animTime*8e-4+u.mesh.position.x*.3))*.12;u.mesh.material.opacity=f*m}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.detachAssetsListener(),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();R();k();import*as u5 from"three";import{Vec3 as a7}from"vec3";E();x();R();k();import X9 from"prismarine-world";import Z9 from"prismarine-chunk";var o7=n=>{let e=X9(n),t=Z9(n),r=new e(n).sync,i=$9(r);for(let s of i)if(s.startsWith("set")&&s!=="setColumn"){let o=r[s].bind(r);r[s]=(...l)=>{let a=l[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(...l)}}return r};function $9(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 d5=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",L0);this._scene=new u5.Scene,this._scene.background=new u5.Color(3294568),this._camera=new u5.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=r0,t=new Et;if(t.currentConfig={version:e,noInventoryGui:!0},await t.updateAssetsData?.({}),this.abortSignal.aborted)return;let r=o7(e),s=b7("prismarine-block")(e),l=globalThis.mcData.blocksArray.filter(m=>{if(!m.name.includes("stained_glass"))return!1;let g=s.fromStateId(m.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,v=100,c=100;for(let m=-v;m<v;m++)for(let g=-c;g<c;g++){let b=l[Math.floor(Math.random()*l.length)];r.setBlockStateId(new a7(m,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 a7(...this._camera.position.toArray()),f=new f0(r,2,u);this.abortSignal.aborted||(this.worldRenderer=new this.WorldRendererClass(this.documentRenderer.renderer,this.options,{version:e,worldView:f,inWorldRenderingConfig:w5,playerStateReactive:So().reactive,rendererState:v0().reactive,nonReactiveState:v0().nonReactive,resourcesManager:t}),this.worldRenderer instanceof L0&&(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&&H0(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,l=s.clientX/window.innerWidth-.5,a=-(s.clientY/window.innerHeight-.5);i?.stop(),i=new ze(e.position).to({x:t+l*o,y:r+a*o},0),i.start(),e.updateProjectionMatrix()},{signal:this.abortSignal})}};E();x();R();k();import*as l7 from"three";var f5=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=q1(r,i)}get v2(){return this.active instanceof O0?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 l7.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"v2":return new O0(this.documentRenderer,{useMinecraftTextures:e.useMinecraftTextures,initialScene:e.v2Scene,initialCamera:e.v2Camera,initialBlockGroup:e.v2BlockGroup,initialCameraSpeed:e.v2CameraSpeed,initialBlockSpeed:e.v2BlockSpeed,resourcesManager:e.resourcesManager},this.abortController.signal);case"worldBlocks":return new d5(this.documentRenderer,this.options,this.abortController.signal);default:return new v5(this.documentRenderer)}}dispose(){this.active?.dispose(),this.active=void 0,this.abortController.abort()}};lr.ColorManagement.enabled=!1;globalThis.THREE=lr;var v7=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),applyTemporaryPlayerSkinOverride:n.entities.applyTemporaryPlayerSkinOverride.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:n.setRain.bind(n),spawnBlockBreakParticles(e,t,r,i,s,o){n.getModule("blockBreakParticles")?.spawnBlockBreakParticles(e,t,r,i,s,o)},spawnBlockCrackParticle(e,t,r,i,s,o,l){n.getModule("blockBreakParticles")?.spawnCrackParticle(e,t,r,i,s,o,l)},async loadGeometryExport(e){let{applyWorldGeometryExport:t}=await Promise.resolve().then(()=>(P1(),o6));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}}}}),tc=[],Wi=(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)}},c7=()=>{let n,e=null,t=null,r=null,i=null,s=(c,u)=>{c.hello,ve?n=L5(c,tc,globalThis):n=c,e=new k5(n,u?.canvas),globalThis.renderer=e.renderer,globalThis.documentRenderer=e,globalThis.threeJsBackend=v,Wi("default",v)},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 f5(e,{...n},u,!!H.env.SINGLE_FILE_BUILD_MODE),Wi("menuBackgroundCreated",t),await t.start(u),Wi("menuBackgroundReady",t)},l=async c=>{if(!e)throw new Error("Document renderer not initialized");t&&(t.dispose(),t=null),r&&(r.destroy(),r=null,i=null,globalThis.world=void 0,globalThis.frameTimingCollector=void 0);let f=ve?L5(c,[Et,u0],globalThis):c;e.nonReactiveState=f.nonReactiveState,globalThis.resourcesManager=f.resourcesManager,r=new L0(e.renderer,n,f),await r.worldReadyPromise,i=f.inWorldRenderingConfig.enableDebugOverlay?new Tr(f.nonReactiveState):null,globalThis.frameTimingCollector=i;let m=e.render;e.render=function(g){m.call(this,g),i?.markFrameStart(),f.inWorldRenderingConfig.paused||r?.render(g),i?.markFrameEnd(),i?.markFrameDisplay()},e.inWorldRenderingConfig=f.inWorldRenderingConfig,globalThis.world=r,Wi("worldReady",r)},a=()=>{t&&(t.dispose(),t=null),e&&e.dispose(),r&&(r.destroy(),r=null)},v={id:"threejs",displayName:`three.js ${lr.REVISION}`,startMenuBackground:o,startWorld:l,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 v7(r)}};return{main:{init:s,backend:v},workerProxy(){return r2({init(c,u){s(c,{canvas:u})},updateSizeExternal(c,u,f){e?.updateSizeExternal(c,u,f)},startMenuBackground:o,startWorld:l,disconnect:a,setRendering:v.setRendering,updateCamera(c,u,f){let m=c?new ec(c.x,c.y,c.z):null;i?.markCameraUpdate(!m),v.updateCamera(m,u,f)},async callBackendMethod(c,...u){if(!r)throw new Error("World renderer not initialized");let m=v7(r)[c];if(!m)throw new Error(`Backend method ${String(c)} is unavailable`);return m(...u)}})}}};var Ni=n=>{let{main:e}=c7();return e.init(n),e.backend};Ni.id="threejs";Ni.displayName="three.js Blocking";Ni.description="Simple, old and stable main thread graphics backend providing balanced performance on top of WebGL2.";E();x();R();k();import*as d7 from"three";function rc(n){let e="threeWorker.js",t;if(H.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 ji=async n=>{let e={onMessage:a=>{}},t=rc(a=>{e.onMessage(a)}),r=i2(t),i=vn();i.onSizeChanged((a,v)=>{r.updateSizeExternal(a,v,window.devicePixelRatio||1)});let s=I5(n,t);try{r.init(s,i.canvas)}catch(a){throw _0(s),a}let o=new Proxy({},{get(a,v){if(typeof v=="string")return async(...c)=>r.callBackendMethod(v,...c)}});return{id:"threejs",displayName:`three.js ${d7.REVISION}`,async startMenuBackground(a){let v=a?.resourcesManager?.currentResources?.mcData;if(v){let u={...w0,items:"itemsArray",entities:"entitiesArray"};await Pn([t],r0,u,v)}let c=I5(a??{},t);try{await r.startMenuBackground(structuredClone(c))}catch(u){throw _0(c),u}},async startWorld(a){let v=a.worldView;e.onMessage=g=>{g?.type==="reloadLoadedChunks"&&v.reloadLoadedChunks().catch(b=>{})};let c={...w0,items:"itemsArray",entities:"entitiesArray"};await Pn([t],a.version,c,a.resourcesManager.currentResources.mcData),a.inWorldRenderingConfig.__syncToWorker=!0,a.playerStateReactive&&(a.playerStateReactive.__syncToWorker=!0),a.rendererState&&(a.rendererState.__syncFromWorker=!0),a.nonReactiveState&&(a.nonReactiveState.__syncFromWorker=!0),a.nonReactiveState.__syncFromWorkerInterval=200;let u=I5(a,t);try{await r.startWorld(structuredClone(u))}catch(g){throw _0(u),g}r.updateSizeExternal(i.size.width,i.size.height,window.devicePixelRatio||1);let f=E0("fps");setInterval(()=>{let{fps:g,avgRenderTime:b,worstRenderTime:A}=a.nonReactiveState;f.updateText(`FPS: ${g.toFixed(0)} (${b.toFixed(0)}ms/${A.toFixed(0)}ms)`),a.nonReactiveState.fps=0},1e3);let m=E0("downloaded-chunks",100,140,20,{className:A0});setInterval(()=>{let g=(n.config.statsVisible??0)>1;m.setVisibility(g),g&&m.updateText(a.nonReactiveState.world.chunksFullInfo)},200)},disconnect(){i.destroy(),r.disconnect(),t.terminate()},setRendering(a){r.setRendering(a)},updateCamera(a,v,c){r.updateCamera(a?{x:a.x,y:a.y,z:a.z}:null,v,c)},soundSystem:void 0,backendMethods:o}};ji.id="threejs-off-thread";ji.displayName="three.js Multi-thread EXPERIMENTAL";ji.description=["(UNSTABLE, DO NOT USE ON ANDROID).","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{No as AppViewer,v5 as ClassicMenuBackground,k5 as DocumentRenderer,Zi as HIGH_TEXTURE_COUNT,gr as LONG_RENDER_TIME_MS,Xi as LOW_FPS_THRESHOLD,j0 as LoadedResourcesTransferrable,A0 as MC_RENDERER_DEBUG_OVERLAY_CLASS,r0 as MENU_BACKGROUND_MC_VERSION,T5 as MENU_BACKGROUND_MOTION_DEFAULTS,Mt as MENU_BACKGROUND_OPTION_DEFAULTS,Z1 as MINECRAFT_BLOCK_GROUPS,g0 as MINECRAFT_BLOCK_GROUP_IDS,M5 as MINECRAFT_BLOCK_GROUP_LABELS,f5 as MenuBackgroundRenderer,_5 as PerformanceMonitor,jo as RENDERER_DEFAULT_OPTIONS,Qo as RENDERER_OPTIONS_META,Yo as RENDERER_RENDER_GUI_SECTIONS,Et as ResourcesManager,O0 as V2MenuBackground,p0 as V2_CAMERA_IDS,S5 as V2_CAMERA_LABELS,m0 as V2_SCENE_IDS,R5 as V2_SCENE_LABELS,d5 as WorldBlocksMenuBackground,f0 as WorldView,u0 as WorldViewWorker,vn as addCanvasForWorker,el as applyMenuBackgroundLiveOptions,lm as applyRendererEnableLighting,sl as applyRendererOptions,om as applyRendererWorldViewOptions,V0 as chunkPos,ji as createGraphicsBackendOffThread,Ni as createGraphicsBackendSingleThread,dd as createWorldRendererConfig,ko as defaultGraphicsBackendConfig,Ji as defaultPerformanceInstabilityFactors,w5 as defaultWorldRendererConfig,To as delayedIterator,$i as formatPerformanceFactorsDebug,v0 as getDefaultRendererState,Xo as getInitialPlayerState,ll as getInitialPlayerStateRenderer,al as getPlayerStateUtils,ve as isWebWorker,sm as menuBackgroundOptionsFromStorage,It as menuBackgroundSpeedToMultiplier,N7 as migrateRendererOptions,un as rendererShaderCubeDebugModeToValue,B7 as sectionPos,am as subscribeRendererOptions};
21708
21704
  /*! Bundled license information:
21709
21705
 
21710
21706
  @jspm/core/nodelibs/browser/chunk-DtuTasat.js: