@splnlss/3d-story-viewer 0.5.2 → 0.5.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/viewer.cjs +1 -1
- package/build/viewer.js +1 -1
- package/package.json +1 -1
package/build/viewer.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e,t=Object.defineProperty,n=(e,n,r)=>((e,n,r)=>n in e?t(e,n,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[n]=r)(e,"symbol"!=typeof n?n+"":n,r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("./index-CMipzbxp.cjs");r.ShaderChunk.bayer_dither_hash_pars_fragment="#ifdef USE_HASH\nuniform float hashOpacity;varying float vCameraDistance;float bayerDitherPattern(vec2 p){float bayerMatrix[16];bayerMatrix[0]=0.0;bayerMatrix[1]=8.0;bayerMatrix[2]=2.0;bayerMatrix[3]=10.0;bayerMatrix[4]=12.0;bayerMatrix[5]=4.0;bayerMatrix[6]=14.0;bayerMatrix[7]=6.0;bayerMatrix[8]=3.0;bayerMatrix[9]=11.0;bayerMatrix[10]=1.0;bayerMatrix[11]=9.0;bayerMatrix[12]=15.0;bayerMatrix[13]=7.0;bayerMatrix[14]=13.0;bayerMatrix[15]=5.0;int x=int(mod(p.x,4.0));int y=int(mod(p.y,4.0));int index=x+y*4;return bayerMatrix[index]/16.0;}\n#endif\n",r.ShaderChunk.bayer_dither_hash_fragment="#ifdef USE_HASH\nfloat hashAmount=smoothstep(5e4,1e2,vCameraDistance)*0.75+0.1;float ditherValue=bayerDitherPattern(gl_FragCoord.xy);if(hashAmount<ditherValue){discard;}\n#endif\n",r.ShaderChunk.bayer_dither_hash_pars_vertex="#ifdef USE_HASH\nvarying float vCameraDistance;\n#endif\n",r.ShaderChunk.bayer_dither_hash_vertex="#ifdef USE_HASH\nvCameraDistance=-mvPosition.z;\n#endif\n";const i=new r.OrthographicCamera(-1,1,1,-1,0,1);class s extends r.BufferGeometry{constructor(){super(),this.setAttribute("position",new r.Float32BufferAttribute([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new r.Float32BufferAttribute([0,2,0,0,2,0],2))}}const a=new s;class o{constructor(e){this._mesh=new r.Mesh(a,e)}dispose(){this._mesh.geometry.dispose()}render(e){e.render(this._mesh,i)}get material(){return this._mesh.material}set material(e){this._mesh.material=e}}const l={POSITION:["byte","byte normalized","unsigned byte","unsigned byte normalized","short","short normalized","unsigned short","unsigned short normalized"],NORMAL:["byte normalized","short normalized"],TANGENT:["byte normalized","short normalized"],TEXCOORD:["byte","byte normalized","unsigned byte","short","short normalized","unsigned short"]};class c{constructor(){this.textureUtils=null,this.pluginCallbacks=[],this.register((function(e){return new $(e)})),this.register((function(e){return new G(e)})),this.register((function(e){return new W(e)})),this.register((function(e){return new X(e)})),this.register((function(e){return new Y(e)})),this.register((function(e){return new K(e)})),this.register((function(e){return new q(e)})),this.register((function(e){return new H(e)})),this.register((function(e){return new j(e)})),this.register((function(e){return new Q(e)})),this.register((function(e){return new Z(e)})),this.register((function(e){return new J(e)})),this.register((function(e){return new ee(e)})),this.register((function(e){return new te(e)}))}register(e){return-1===this.pluginCallbacks.indexOf(e)&&this.pluginCallbacks.push(e),this}unregister(e){return-1!==this.pluginCallbacks.indexOf(e)&&this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(e),1),this}setTextureUtils(e){return this.textureUtils=e,this}parse(e,t,n,r){const i=new N,s=[];for(let a=0,o=this.pluginCallbacks.length;a<o;a++)s.push(this.pluginCallbacks[a](i));i.setPlugins(s),i.setTextureUtils(this.textureUtils),i.writeAsync(e,t,r).catch(n)}parseAsync(e,t){const n=this;return new Promise((function(r,i){n.parse(e,r,i,t)}))}}const u=0,h=1,d=2,p=3,m=4,f=5120,g=5121,x=5122,y=5123,v=5124,b=5125,w=5126,T=34962,S=34963,_=9728,M=9729,A=9984,E=9985,C=9986,R=9987,D=33071,k=33648,I=10497,P="KHR_mesh_quantization",L={};L[r.NearestFilter]=_,L[r.NearestMipmapNearestFilter]=A,L[r.NearestMipmapLinearFilter]=C,L[r.LinearFilter]=M,L[r.LinearMipmapNearestFilter]=E,L[r.LinearMipmapLinearFilter]=R,L[r.ClampToEdgeWrapping]=D,L[r.RepeatWrapping]=I,L[r.MirroredRepeatWrapping]=k;const U={scale:"scale",position:"translation",quaternion:"rotation",morphTargetInfluences:"weights"},F=new r.Color;function z(e,t){return e.length===t.length&&e.every((function(e,n){return e===t[n]}))}function B(e){return 4*Math.ceil(e/4)}function V(e,t=0){const n=B(e.byteLength);if(n!==e.byteLength){const r=new Uint8Array(n);if(r.set(new Uint8Array(e)),0!==t)for(let i=e.byteLength;i<n;i++)r[i]=t;return r.buffer}return e}function O(){return"undefined"==typeof document&&"undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(1,1):document.createElement("canvas")}class N{constructor(){this.plugins=[],this.options={},this.pending=[],this.buffers=[],this.byteOffset=0,this.buffers=[],this.nodeMap=new Map,this.skins=[],this.extensionsUsed={},this.extensionsRequired={},this.uids=new Map,this.uid=0,this.json={asset:{version:"2.0",generator:"THREE.GLTFExporter r"+r.REVISION}},this.cache={meshes:new Map,attributes:new Map,attributesNormalized:new Map,materials:new Map,textures:new Map,images:new Map},this.textureUtils=null}setPlugins(e){this.plugins=e}setTextureUtils(e){this.textureUtils=e}async writeAsync(e,t,n={}){this.options=Object.assign({binary:!1,trs:!1,onlyVisible:!0,maxTextureSize:1/0,animations:[],includeCustomExtensions:!1},n),this.options.animations.length>0&&(this.options.trs=!0),await this.processInputAsync(e),await Promise.all(this.pending);const r=this,i=r.buffers,s=r.json;n=r.options;const a=r.extensionsUsed,o=r.extensionsRequired,l=new Blob(i,{type:"application/octet-stream"}),c=Object.keys(a),u=Object.keys(o);if(c.length>0&&(s.extensionsUsed=c),u.length>0&&(s.extensionsRequired=u),s.buffers&&s.buffers.length>0&&(s.buffers[0].byteLength=l.size),!0===n.binary){const e=new FileReader;e.readAsArrayBuffer(l),e.onloadend=function(){const n=V(e.result),r=new DataView(new ArrayBuffer(8));r.setUint32(0,n.byteLength,!0),r.setUint32(4,5130562,!0);const i=V((a=JSON.stringify(s),(new TextEncoder).encode(a).buffer),32);var a;const o=new DataView(new ArrayBuffer(8));o.setUint32(0,i.byteLength,!0),o.setUint32(4,1313821514,!0);const l=new ArrayBuffer(12),c=new DataView(l);c.setUint32(0,1179937895,!0),c.setUint32(4,2,!0);const u=12+o.byteLength+i.byteLength+r.byteLength+n.byteLength;c.setUint32(8,u,!0);const h=new Blob([l,o,i,r,n],{type:"application/octet-stream"}),d=new FileReader;d.readAsArrayBuffer(h),d.onloadend=function(){t(d.result)}}}else if(s.buffers&&s.buffers.length>0){const e=new FileReader;e.readAsDataURL(l),e.onloadend=function(){const n=e.result;s.buffers[0].uri=n,t(s)}}else t(s)}serializeUserData(e,t){if(0===Object.keys(e.userData).length)return;const n=this.options,r=this.extensionsUsed;try{const i=JSON.parse(JSON.stringify(e.userData));if(n.includeCustomExtensions&&i.gltfExtensions){void 0===t.extensions&&(t.extensions={});for(const e in i.gltfExtensions)t.extensions[e]=i.gltfExtensions[e],r[e]=!0;delete i.gltfExtensions}Object.keys(i).length>0&&(t.extras=i)}catch(i){}}getUID(e,t=!1){if(!1===this.uids.has(e)){const t=new Map;t.set(!0,this.uid++),t.set(!1,this.uid++),this.uids.set(e,t)}return this.uids.get(e).get(t)}isNormalizedNormalAttribute(e){if(this.cache.attributesNormalized.has(e))return!1;const t=new r.Vector3;for(let n=0,r=e.count;n<r;n++)if(Math.abs(t.fromBufferAttribute(e,n).length()-1)>5e-4)return!1;return!0}createNormalizedNormalAttribute(e){const t=this.cache;if(t.attributesNormalized.has(e))return t.attributesNormalized.get(e);const n=e.clone(),i=new r.Vector3;for(let r=0,s=n.count;r<s;r++)i.fromBufferAttribute(n,r),0===i.x&&0===i.y&&0===i.z?i.setX(1):i.normalize(),n.setXYZ(r,i.x,i.y,i.z);return t.attributesNormalized.set(e,n),n}applyTextureTransform(e,t){let n=!1;const r={};0===t.offset.x&&0===t.offset.y||(r.offset=t.offset.toArray(),n=!0),0!==t.rotation&&(r.rotation=t.rotation,n=!0),1===t.repeat.x&&1===t.repeat.y||(r.scale=t.repeat.toArray(),n=!0),n&&(e.extensions=e.extensions||{},e.extensions.KHR_texture_transform=r,this.extensionsUsed.KHR_texture_transform=!0)}async buildMetalRoughTextureAsync(e,t){if(e===t)return e;function n(e){return e.colorSpace===r.SRGBColorSpace?function(e){return e<.04045?.0773993808*e:Math.pow(.9478672986*e+.0521327014,2.4)}:function(e){return e}}e instanceof r.CompressedTexture&&(e=await this.decompressTextureAsync(e)),t instanceof r.CompressedTexture&&(t=await this.decompressTextureAsync(t));const i=e?e.image:null,s=t?t.image:null,a=Math.max(i?i.width:0,s?s.width:0),o=Math.max(i?i.height:0,s?s.height:0),l=O();l.width=a,l.height=o;const c=l.getContext("2d",{willReadFrequently:!0});c.fillStyle="#00ffff",c.fillRect(0,0,a,o);const u=c.getImageData(0,0,a,o);if(i){c.drawImage(i,0,0,a,o);const t=n(e),r=c.getImageData(0,0,a,o).data;for(let e=2;e<r.length;e+=4)u.data[e]=256*t(r[e]/256)}if(s){c.drawImage(s,0,0,a,o);const e=n(t),r=c.getImageData(0,0,a,o).data;for(let t=1;t<r.length;t+=4)u.data[t]=256*e(r[t]/256)}c.putImageData(u,0,0);const h=(e||t).clone();return h.source=new r.Source(l),h.colorSpace=r.NoColorSpace,h.channel=(e||t).channel,e&&t&&(e.channel,t.channel),h}async buildNormalMapTextureAsync(e,t,n){e instanceof r.CompressedTexture&&(e=await this.decompressTextureAsync(e));const i=e.image,s=O();s.width=i.width,s.height=i.height;const a=s.getContext("2d",{willReadFrequently:!0});a.drawImage(i,0,0,s.width,s.height);const o=a.getImageData(0,0,s.width,s.height),l=o.data;for(let r=0;r<l.length;r+=4)t&&(l[r+0]=255-l[r+0]),n&&(l[r+1]=255-l[r+1]);a.putImageData(o,0,0);const c=e.clone();return c.source=new r.Source(s),c}async decompressTextureAsync(e,t=1/0){if(null===this.textureUtils)throw new Error("THREE.GLTFExporter: setTextureUtils() must be called to process compressed textures.");return await this.textureUtils.decompress(e,t)}processBuffer(e){const t=this.json,n=this.buffers;return t.buffers||(t.buffers=[{byteLength:0}]),n.push(e),0}processBufferView(e,t,n,i,s){const a=this.json;let o;switch(a.bufferViews||(a.bufferViews=[]),t){case f:case g:o=1;break;case x:case y:o=2;break;default:o=4}let l=e.itemSize*o;s===T&&(l=4*Math.ceil(l/4));const c=B(i*l),u=new DataView(new ArrayBuffer(c));let h=0;for(let p=n;p<n+i;p++){for(let n=0;n<e.itemSize;n++){let i;e.itemSize>4?i=e.array[p*e.itemSize+n]:(0===n?i=e.getX(p):1===n?i=e.getY(p):2===n?i=e.getZ(p):3===n&&(i=e.getW(p)),!0===e.normalized&&(i=r.MathUtils.normalize(i,e.array))),t===w?u.setFloat32(h,i,!0):t===v?u.setInt32(h,i,!0):t===b?u.setUint32(h,i,!0):t===x?u.setInt16(h,i,!0):t===y?u.setUint16(h,i,!0):t===f?u.setInt8(h,i):t===g&&u.setUint8(h,i),h+=o}h%l!=0&&(h+=l-h%l)}const d={buffer:this.processBuffer(u.buffer),byteOffset:this.byteOffset,byteLength:c};void 0!==s&&(d.target=s),s===T&&(d.byteStride=l),this.byteOffset+=c,a.bufferViews.push(d);return{id:a.bufferViews.length-1,byteLength:0}}processBufferViewImage(e){const t=this,n=t.json;return n.bufferViews||(n.bufferViews=[]),new Promise((function(r){const i=new FileReader;i.readAsArrayBuffer(e),i.onloadend=function(){const e=V(i.result),s={buffer:t.processBuffer(e),byteOffset:t.byteOffset,byteLength:e.byteLength};t.byteOffset+=e.byteLength,r(n.bufferViews.push(s)-1)}}))}processAccessor(e,t,n,i){const s=this.json;let a;if(e.array.constructor===Float32Array)a=w;else if(e.array.constructor===Int32Array)a=v;else if(e.array.constructor===Uint32Array)a=b;else if(e.array.constructor===Int16Array)a=x;else if(e.array.constructor===Uint16Array)a=y;else if(e.array.constructor===Int8Array)a=f;else{if(e.array.constructor!==Uint8Array)throw new Error("THREE.GLTFExporter: Unsupported bufferAttribute component type: "+e.array.constructor.name);a=g}if(void 0===n&&(n=0),void 0!==i&&i!==1/0||(i=e.count),0===i)return null;const o=function(e,t,n){const i={min:new Array(e.itemSize).fill(Number.POSITIVE_INFINITY),max:new Array(e.itemSize).fill(Number.NEGATIVE_INFINITY)};for(let s=t;s<t+n;s++)for(let t=0;t<e.itemSize;t++){let n;e.itemSize>4?n=e.array[s*e.itemSize+t]:(0===t?n=e.getX(s):1===t?n=e.getY(s):2===t?n=e.getZ(s):3===t&&(n=e.getW(s)),!0===e.normalized&&(n=r.MathUtils.normalize(n,e.array))),i.min[t]=Math.min(i.min[t],n),i.max[t]=Math.max(i.max[t],n)}return i}(e,n,i);let l;void 0!==t&&(l=e===t.index?S:T);const c=this.processBufferView(e,a,n,i,l),u={bufferView:c.id,byteOffset:c.byteOffset,componentType:a,count:i,max:o.max,min:o.min,type:{1:"SCALAR",2:"VEC2",3:"VEC3",4:"VEC4",9:"MAT3",16:"MAT4"}[e.itemSize]};return!0===e.normalized&&(u.normalized=!0),s.accessors||(s.accessors=[]),s.accessors.push(u)-1}processImage(e,t,n,i="image/png"){if(null!==e){const t=this,s=t.cache,a=t.json,o=t.options,l=t.pending;s.images.has(e)||s.images.set(e,{});const c=s.images.get(e),u=i+":flipY/"+n.toString();if(void 0!==c[u])return c[u];a.images||(a.images=[]);const h={mimeType:i},d=O();d.width=Math.min(e.width,o.maxTextureSize),d.height=Math.min(e.height,o.maxTextureSize);const p=d.getContext("2d",{willReadFrequently:!0});if(!0===n&&(p.translate(0,d.height),p.scale(1,-1)),void 0!==e.data){r.RGBAFormat,e.width>o.maxTextureSize||(e.height,o.maxTextureSize);const t=new Uint8ClampedArray(e.height*e.width*4);for(let n=0;n<t.length;n+=4)t[n+0]=e.data[n+0],t[n+1]=e.data[n+1],t[n+2]=e.data[n+2],t[n+3]=e.data[n+3];p.putImageData(new ImageData(t,e.width,e.height),0,0)}else{if(!("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap||"undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas))throw new Error("THREE.GLTFExporter: Invalid image type. Use HTMLImageElement, HTMLCanvasElement, ImageBitmap or OffscreenCanvas.");p.drawImage(e,0,0,d.width,d.height)}!0===o.binary?l.push(function(e,t){if("undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas){let n;return"image/jpeg"===t?n=.92:"image/webp"===t&&(n=.8),e.convertToBlob({type:t,quality:n})}return new Promise((n=>e.toBlob(n,t)))}(d,i).then((e=>t.processBufferViewImage(e))).then((e=>{h.bufferView=e}))):h.uri=r.ImageUtils.getDataURL(d,i);const m=a.images.push(h)-1;return c[u]=m,m}throw new Error("THREE.GLTFExporter: No valid image data found. Unable to process texture.")}processSampler(e){const t=this.json;t.samplers||(t.samplers=[]);const n={magFilter:L[e.magFilter],minFilter:L[e.minFilter],wrapS:L[e.wrapS],wrapT:L[e.wrapT]};return t.samplers.push(n)-1}async processTextureAsync(e){const t=this.options,n=this.cache,i=this.json;if(n.textures.has(e))return n.textures.get(e);i.textures||(i.textures=[]),e instanceof r.CompressedTexture&&(e=await this.decompressTextureAsync(e,t.maxTextureSize));const s=e.userData.mimeType,a=this.processImage(e.image,e.format,e.flipY,s),o={sampler:this.processSampler(e)};"image/webp"===s?(o.extensions=o.extensions||{},o.extensions.EXT_texture_webp={source:a},this.extensionsUsed.EXT_texture_webp=!0,this.extensionsRequired.EXT_texture_webp=!0):o.source=a,e.name&&(o.name=e.name),await this._invokeAllAsync((async function(t){t.writeTexture&&await t.writeTexture(e,o)}));const l=i.textures.push(o)-1;return n.textures.set(e,l),l}async processMaterialAsync(e,t){const n=this.cache,i=this.json,s=void 0!==t&&t.hasAttribute("tangent"),a=e.normalMap?e.uuid+":"+s:e.uuid;if(n.materials.has(a))return n.materials.get(a);if(e.isShaderMaterial)return null;i.materials||(i.materials=[]);const o={pbrMetallicRoughness:{}};!0!==e.isMeshStandardMaterial&&e.isMeshBasicMaterial;const l=e.color.toArray().concat([e.opacity]);if(z(l,[1,1,1,1])||(o.pbrMetallicRoughness.baseColorFactor=l),e.isMeshStandardMaterial?(o.pbrMetallicRoughness.metallicFactor=e.metalness,o.pbrMetallicRoughness.roughnessFactor=e.roughness):(o.pbrMetallicRoughness.metallicFactor=0,o.pbrMetallicRoughness.roughnessFactor=1),e.metalnessMap||e.roughnessMap){const t=await this.buildMetalRoughTextureAsync(e.metalnessMap,e.roughnessMap),n={index:await this.processTextureAsync(t),texCoord:t.channel};this.applyTextureTransform(n,t),o.pbrMetallicRoughness.metallicRoughnessTexture=n}if(e.map){const t={index:await this.processTextureAsync(e.map),texCoord:e.map.channel};this.applyTextureTransform(t,e.map),o.pbrMetallicRoughness.baseColorTexture=t}if(e.emissive){const t=e.emissive;if(Math.max(t.r,t.g,t.b)>0&&(o.emissiveFactor=e.emissive.toArray()),e.emissiveMap){const t={index:await this.processTextureAsync(e.emissiveMap),texCoord:e.emissiveMap.channel};this.applyTextureTransform(t,e.emissiveMap),o.emissiveTexture=t}}if(e.normalMap){const t=e.normalScale,n=t.x<0,r=s?t.y<0:t.y>0;let i=e.normalMap;(n||r)&&(i=await this.buildNormalMapTextureAsync(e.normalMap,n,r));const a={index:await this.processTextureAsync(i),texCoord:e.normalMap.channel};1!==Math.abs(t.x)&&(a.scale=Math.abs(t.x)),this.applyTextureTransform(a,e.normalMap),o.normalTexture=a}if(e.aoMap){const t={index:await this.processTextureAsync(e.aoMap),texCoord:e.aoMap.channel};1!==e.aoMapIntensity&&(t.strength=e.aoMapIntensity),this.applyTextureTransform(t,e.aoMap),o.occlusionTexture=t}e.transparent?o.alphaMode="BLEND":e.alphaTest>0&&(o.alphaMode="MASK",o.alphaCutoff=e.alphaTest),e.side===r.DoubleSide&&(o.doubleSided=!0),""!==e.name&&(o.name=e.name),this.serializeUserData(e,o),await this._invokeAllAsync((async function(t){t.writeMaterialAsync&&await t.writeMaterialAsync(e,o)}));const c=i.materials.push(o)-1;return n.materials.set(a,c),c}async processMeshAsync(e){const t=this.cache,n=this.json,r=[e.geometry.uuid];if(Array.isArray(e.material))for(let c=0,u=e.material.length;c<u;c++)r.push(e.material[c].uuid);else r.push(e.material.uuid);const i=r.join(":");if(t.meshes.has(i))return t.meshes.get(i);const s=e.geometry;let a;a=e.isLineSegments?h:e.isLineLoop?d:e.isLine?p:e.isPoints?u:e.material.wireframe?h:m;const o={},l={},f=[],g=[],x={uv:"TEXCOORD_0",uv1:"TEXCOORD_1",uv2:"TEXCOORD_2",uv3:"TEXCOORD_3",color:"COLOR_0",skinWeight:"WEIGHTS_0",skinIndex:"JOINTS_0"},y=s.getAttribute("normal");void 0===y||this.isNormalizedNormalAttribute(y)||s.setAttribute("normal",this.createNormalizedNormalAttribute(y));let v=null;for(let u in s.attributes){if("morph"===u.slice(0,5))continue;const e=s.attributes[u];u=x[u]||u.toUpperCase();if(/^(POSITION|NORMAL|TANGENT|TEXCOORD_\d+|COLOR_\d+|JOINTS_\d+|WEIGHTS_\d+)$/.test(u)||u.startsWith("_")||(u="_"+u),t.attributes.has(this.getUID(e))){l[u]=t.attributes.get(this.getUID(e));continue}v=null;const n=e.array;"JOINTS_0"!==u||n instanceof Uint16Array||n instanceof Uint8Array?(n instanceof Uint32Array||n instanceof Int32Array)&&!u.startsWith("_")&&(v=c.Utils.toTypedBufferAttribute(e,Float32Array)):v=c.Utils.toTypedBufferAttribute(e,Uint16Array);const r=this.processAccessor(v||e,s);null!==r&&(u.startsWith("_")||this.detectMeshQuantization(u,e),l[u]=r,t.attributes.set(this.getUID(e),r))}if(void 0!==y&&s.setAttribute("normal",y),0===Object.keys(l).length)return null;if(void 0!==e.morphTargetInfluences&&e.morphTargetInfluences.length>0){const n=[],r=[],i={};if(void 0!==e.morphTargetDictionary)for(const t in e.morphTargetDictionary)i[e.morphTargetDictionary[t]]=t;for(let a=0;a<e.morphTargetInfluences.length;++a){const o={};let l=!1;for(const e in s.morphAttributes){if("position"!==e&&"normal"!==e){l||(l=!0);continue}const n=s.morphAttributes[e][a],r=e.toUpperCase(),i=s.attributes[e];if(t.attributes.has(this.getUID(n,!0))){o[r]=t.attributes.get(this.getUID(n,!0));continue}const c=n.clone();if(!s.morphTargetsRelative)for(let e=0,t=n.count;e<t;e++)for(let r=0;r<n.itemSize;r++)0===r&&c.setX(e,n.getX(e)-i.getX(e)),1===r&&c.setY(e,n.getY(e)-i.getY(e)),2===r&&c.setZ(e,n.getZ(e)-i.getZ(e)),3===r&&c.setW(e,n.getW(e)-i.getW(e));o[r]=this.processAccessor(c,s),t.attributes.set(this.getUID(i,!0),o[r])}g.push(o),n.push(e.morphTargetInfluences[a]),void 0!==e.morphTargetDictionary&&r.push(i[a])}o.weights=n,r.length>0&&(o.extras={},o.extras.targetNames=r)}const b=Array.isArray(e.material);if(b&&0===s.groups.length)return null;let w=!1;if(b&&null===s.index){const e=[];for(let t=0,n=s.attributes.position.count;t<n;t++)e[t]=t;s.setIndex(e),w=!0}const T=b?e.material:[e.material],S=b?s.groups:[{materialIndex:0,start:void 0,count:void 0}];for(let c=0,u=S.length;c<u;c++){const e={mode:a,attributes:l};if(this.serializeUserData(s,e),g.length>0&&(e.targets=g),null!==s.index){let n=this.getUID(s.index);void 0===S[c].start&&void 0===S[c].count||(n+=":"+S[c].start+":"+S[c].count),t.attributes.has(n)?e.indices=t.attributes.get(n):(e.indices=this.processAccessor(s.index,s,S[c].start,S[c].count),t.attributes.set(n,e.indices)),null===e.indices&&delete e.indices}const n=await this.processMaterialAsync(T[S[c].materialIndex],s);null!==n&&(e.material=n),f.push(e)}!0===w&&s.setIndex(null),o.primitives=f,n.meshes||(n.meshes=[]),await this._invokeAllAsync((function(t){t.writeMesh&&t.writeMesh(e,o)}));const _=n.meshes.push(o)-1;return t.meshes.set(i,_),_}detectMeshQuantization(e,t){if(this.extensionsUsed[P])return;let n;switch(t.array.constructor){case Int8Array:n="byte";break;case Uint8Array:n="unsigned byte";break;case Int16Array:n="short";break;case Uint16Array:n="unsigned short";break;default:return}t.normalized&&(n+=" normalized");const r=e.split("_",1)[0];l[r]&&l[r].includes(n)&&(this.extensionsUsed[P]=!0,this.extensionsRequired[P]=!0)}processCamera(e){const t=this.json;t.cameras||(t.cameras=[]);const n=e.isOrthographicCamera,i={type:n?"orthographic":"perspective"};return n?i.orthographic={xmag:2*e.right,ymag:2*e.top,zfar:e.far<=0?.001:e.far,znear:e.near<0?0:e.near}:i.perspective={aspectRatio:e.aspect,yfov:r.MathUtils.degToRad(e.fov),zfar:e.far<=0?.001:e.far,znear:e.near<0?0:e.near},""!==e.name&&(i.name=e.type),t.cameras.push(i)-1}processAnimation(e,t){const n=this.json,i=this.nodeMap;n.animations||(n.animations=[]);const s=(e=c.Utils.mergeMorphTargetTracks(e.clone(),t)).tracks,a=[],o=[];for(let c=0;c<s.length;++c){const e=s[c],n=r.PropertyBinding.parseTrackName(e.name);let l=r.PropertyBinding.findNode(t,n.nodeName);const u=U[n.propertyName];if("bones"===n.objectName&&(l=!0===l.isSkinnedMesh?l.skeleton.getBoneByName(n.objectIndex):void 0),!l||!u)continue;const h=1;let d,p=e.values.length/e.times.length;u===U.morphTargetInfluences&&(p/=l.morphTargetInfluences.length),!0===e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline?(d="CUBICSPLINE",p/=3):d=e.getInterpolation()===r.InterpolateDiscrete?"STEP":"LINEAR",o.push({input:this.processAccessor(new r.BufferAttribute(e.times,h)),output:this.processAccessor(new r.BufferAttribute(e.values,p)),interpolation:d}),a.push({sampler:o.length-1,target:{node:i.get(l),path:u}})}const l={name:e.name||"clip_"+n.animations.length,samplers:o,channels:a};return this.serializeUserData(e,l),n.animations.push(l),n.animations.length-1}processSkin(e){const t=this.json,n=this.nodeMap,i=t.nodes[n.get(e)],s=e.skeleton;if(void 0===s)return null;const a=e.skeleton.bones[0];if(void 0===a)return null;const o=[],l=new Float32Array(16*s.bones.length),c=new r.Matrix4;for(let r=0;r<s.bones.length;++r)o.push(n.get(s.bones[r])),c.copy(s.boneInverses[r]),c.multiply(e.bindMatrix).toArray(l,16*r);void 0===t.skins&&(t.skins=[]),t.skins.push({inverseBindMatrices:this.processAccessor(new r.BufferAttribute(l,16)),joints:o,skeleton:n.get(a)});return i.skin=t.skins.length-1}async processNodeAsync(e){const t=this.json,n=this.options,r=this.nodeMap;if(t.nodes||(t.nodes=[]),null!==e.pivot)return await this._processNodeWithPivotAsync(e);const i={};if(n.trs){const t=e.quaternion.toArray(),n=e.position.toArray(),r=e.scale.toArray();z(t,[0,0,0,1])||(i.rotation=t),z(n,[0,0,0])||(i.translation=n),z(r,[1,1,1])||(i.scale=r)}else e.matrixAutoUpdate&&e.updateMatrix(),!1===z(e.matrix.elements,[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1])&&(i.matrix=e.matrix.elements);if(""!==e.name&&(i.name=String(e.name)),this.serializeUserData(e,i),e.isMesh||e.isLine||e.isPoints){const t=await this.processMeshAsync(e);null!==t&&(i.mesh=t)}else e.isCamera&&(i.camera=this.processCamera(e));e.isSkinnedMesh&&this.skins.push(e);const s=t.nodes.push(i)-1;if(r.set(e,s),e.children.length>0){const t=[];for(let r=0,i=e.children.length;r<i;r++){const i=e.children[r];if(i.visible||!1===n.onlyVisible){const e=await this.processNodeAsync(i);null!==e&&t.push(e)}}t.length>0&&(i.children=t)}return await this._invokeAllAsync((function(t){t.writeNode&&t.writeNode(e,i)})),s}async _processNodeWithPivotAsync(e){const t=this.json,n=this.options,r=this.nodeMap,i=e.pivot,s={},a=e.quaternion.toArray(),o=[e.position.x+i.x,e.position.y+i.y,e.position.z+i.z],l=e.scale.toArray();z(a,[0,0,0,1])||(s.rotation=a),z(o,[0,0,0])||(s.translation=o),z(l,[1,1,1])||(s.scale=l),s.extras={pivot:i.toArray()},""!==e.name&&(s.name=String(e.name)),this.serializeUserData(e,s);const c=t.nodes.push(s)-1;r.set(e,c);const u={},h=[-i.x,-i.y,-i.z];if(z(h,[0,0,0])||(u.translation=h),e.isMesh||e.isLine||e.isPoints){const t=await this.processMeshAsync(e);null!==t&&(u.mesh=t)}else e.isCamera&&(u.camera=this.processCamera(e));e.isSkinnedMesh&&this.skins.push(e);const d=[t.nodes.push(u)-1];if(e.children.length>0){const t=[];for(let r=0,i=e.children.length;r<i;r++){const i=e.children[r];if(i.visible||!1===n.onlyVisible){const e=await this.processNodeAsync(i);null!==e&&t.push(e)}}t.length>0&&(u.children=t)}return s.children=d,await this._invokeAllAsync((function(t){t.writeNode&&t.writeNode(e,s)})),c}async processSceneAsync(e){const t=this.json,n=this.options;t.scenes||(t.scenes=[],t.scene=0);const r={};""!==e.name&&(r.name=e.name),t.scenes.push(r);const i=[];for(let s=0,a=e.children.length;s<a;s++){const t=e.children[s];if(t.visible||!1===n.onlyVisible){const e=await this.processNodeAsync(t);null!==e&&i.push(e)}}i.length>0&&(r.nodes=i),this.serializeUserData(e,r)}async processObjectsAsync(e){const t=new r.Scene;t.name="AuxScene";for(let n=0;n<e.length;n++)t.children.push(e[n]);await this.processSceneAsync(t)}async processInputAsync(e){const t=this.options;e=e instanceof Array?e:[e],await this._invokeAllAsync((function(t){t.beforeParse&&t.beforeParse(e)}));const n=[];for(let i=0;i<e.length;i++)e[i]instanceof r.Scene?await this.processSceneAsync(e[i]):n.push(e[i]);n.length>0&&await this.processObjectsAsync(n);for(let r=0;r<this.skins.length;++r)this.processSkin(this.skins[r]);if(1===e.length)for(let r=0;r<t.animations.length;++r)this.processAnimation(t.animations[r],e[0]);else for(let r=0;r<e.length;r++){const n=t.animations[r]||[];for(let t=0;t<n.length;++t)this.processAnimation(n[t],e[r])}await this._invokeAllAsync((function(t){t.afterParse&&t.afterParse(e)}))}async _invokeAllAsync(e){for(let t=0,n=this.plugins.length;t<n;t++)await e(this.plugins[t])}}class ${constructor(e){this.writer=e,this.name="KHR_lights_punctual"}writeNode(e,t){if(!e.isLight)return;if(!e.isDirectionalLight&&!e.isPointLight&&!e.isSpotLight)return;const n=this.writer,r=n.json,i=n.extensionsUsed,s={};e.name&&(s.name=e.name),s.color=e.color.toArray(),s.intensity=e.intensity,e.isDirectionalLight?s.type="directional":e.isPointLight?(s.type="point",e.distance>0&&(s.range=e.distance)):e.isSpotLight&&(s.type="spot",e.distance>0&&(s.range=e.distance),s.spot={},s.spot.innerConeAngle=(1-e.penumbra)*e.angle,s.spot.outerConeAngle=e.angle),void 0!==e.decay&&e.decay,e.target&&(e.target.parent!==e||0!==e.target.position.x||0!==e.target.position.y||e.target.position.z),i[this.name]||(r.extensions=r.extensions||{},r.extensions[this.name]={lights:[]},i[this.name]=!0);const a=r.extensions[this.name].lights;a.push(s),t.extensions=t.extensions||{},t.extensions[this.name]={light:a.length-1}}}let G=class{constructor(e){this.writer=e,this.name="KHR_materials_unlit"}async writeMaterialAsync(e,t){if(!e.isMeshBasicMaterial)return;const n=this.writer.extensionsUsed;t.extensions=t.extensions||{},t.extensions[this.name]={},n[this.name]=!0,t.pbrMetallicRoughness.metallicFactor=0,t.pbrMetallicRoughness.roughnessFactor=.9}},q=class{constructor(e){this.writer=e,this.name="KHR_materials_clearcoat"}async writeMaterialAsync(e,t){if(!e.isMeshPhysicalMaterial||0===e.clearcoat)return;const n=this.writer,r=n.extensionsUsed,i={};if(i.clearcoatFactor=e.clearcoat,e.clearcoatMap){const t={index:await n.processTextureAsync(e.clearcoatMap),texCoord:e.clearcoatMap.channel};n.applyTextureTransform(t,e.clearcoatMap),i.clearcoatTexture=t}if(i.clearcoatRoughnessFactor=e.clearcoatRoughness,e.clearcoatRoughnessMap){const t={index:await n.processTextureAsync(e.clearcoatRoughnessMap),texCoord:e.clearcoatRoughnessMap.channel};n.applyTextureTransform(t,e.clearcoatRoughnessMap),i.clearcoatRoughnessTexture=t}if(e.clearcoatNormalMap){const t={index:await n.processTextureAsync(e.clearcoatNormalMap),texCoord:e.clearcoatNormalMap.channel};1!==e.clearcoatNormalScale.x&&(t.scale=e.clearcoatNormalScale.x),n.applyTextureTransform(t,e.clearcoatNormalMap),i.clearcoatNormalTexture=t}t.extensions=t.extensions||{},t.extensions[this.name]=i,r[this.name]=!0}},H=class{constructor(e){this.writer=e,this.name="KHR_materials_dispersion"}async writeMaterialAsync(e,t){if(!e.isMeshPhysicalMaterial||0===e.dispersion)return;const n=this.writer.extensionsUsed,r={};r.dispersion=e.dispersion,t.extensions=t.extensions||{},t.extensions[this.name]=r,n[this.name]=!0}},j=class{constructor(e){this.writer=e,this.name="KHR_materials_iridescence"}async writeMaterialAsync(e,t){if(!e.isMeshPhysicalMaterial||0===e.iridescence)return;const n=this.writer,r=n.extensionsUsed,i={};if(i.iridescenceFactor=e.iridescence,e.iridescenceMap){const t={index:await n.processTextureAsync(e.iridescenceMap),texCoord:e.iridescenceMap.channel};n.applyTextureTransform(t,e.iridescenceMap),i.iridescenceTexture=t}if(i.iridescenceIor=e.iridescenceIOR,i.iridescenceThicknessMinimum=e.iridescenceThicknessRange[0],i.iridescenceThicknessMaximum=e.iridescenceThicknessRange[1],e.iridescenceThicknessMap){const t={index:await n.processTextureAsync(e.iridescenceThicknessMap),texCoord:e.iridescenceThicknessMap.channel};n.applyTextureTransform(t,e.iridescenceThicknessMap),i.iridescenceThicknessTexture=t}t.extensions=t.extensions||{},t.extensions[this.name]=i,r[this.name]=!0}},W=class{constructor(e){this.writer=e,this.name="KHR_materials_transmission"}async writeMaterialAsync(e,t){if(!e.isMeshPhysicalMaterial||0===e.transmission)return;const n=this.writer,r=n.extensionsUsed,i={};if(i.transmissionFactor=e.transmission,e.transmissionMap){const t={index:await n.processTextureAsync(e.transmissionMap),texCoord:e.transmissionMap.channel};n.applyTextureTransform(t,e.transmissionMap),i.transmissionTexture=t}t.extensions=t.extensions||{},t.extensions[this.name]=i,r[this.name]=!0}},X=class{constructor(e){this.writer=e,this.name="KHR_materials_volume"}async writeMaterialAsync(e,t){if(!e.isMeshPhysicalMaterial||0===e.transmission)return;const n=this.writer,r=n.extensionsUsed,i={};if(i.thicknessFactor=e.thickness,e.thicknessMap){const t={index:await n.processTextureAsync(e.thicknessMap),texCoord:e.thicknessMap.channel};n.applyTextureTransform(t,e.thicknessMap),i.thicknessTexture=t}e.attenuationDistance!==1/0&&(i.attenuationDistance=e.attenuationDistance),i.attenuationColor=e.attenuationColor.toArray(),t.extensions=t.extensions||{},t.extensions[this.name]=i,r[this.name]=!0}},Y=class{constructor(e){this.writer=e,this.name="KHR_materials_ior"}async writeMaterialAsync(e,t){if(!e.isMeshPhysicalMaterial||1.5===e.ior)return;const n=this.writer.extensionsUsed,r={};r.ior=e.ior,t.extensions=t.extensions||{},t.extensions[this.name]=r,n[this.name]=!0}},K=class{constructor(e){this.writer=e,this.name="KHR_materials_specular"}async writeMaterialAsync(e,t){if(!e.isMeshPhysicalMaterial||1===e.specularIntensity&&e.specularColor.equals(F)&&!e.specularIntensityMap&&!e.specularColorMap)return;const n=this.writer,r=n.extensionsUsed,i={};if(e.specularIntensityMap){const t={index:await n.processTextureAsync(e.specularIntensityMap),texCoord:e.specularIntensityMap.channel};n.applyTextureTransform(t,e.specularIntensityMap),i.specularTexture=t}if(e.specularColorMap){const t={index:await n.processTextureAsync(e.specularColorMap),texCoord:e.specularColorMap.channel};n.applyTextureTransform(t,e.specularColorMap),i.specularColorTexture=t}i.specularFactor=e.specularIntensity,i.specularColorFactor=e.specularColor.toArray(),t.extensions=t.extensions||{},t.extensions[this.name]=i,r[this.name]=!0}},Q=class{constructor(e){this.writer=e,this.name="KHR_materials_sheen"}async writeMaterialAsync(e,t){if(!e.isMeshPhysicalMaterial||0==e.sheen)return;const n=this.writer,r=n.extensionsUsed,i={};if(e.sheenRoughnessMap){const t={index:await n.processTextureAsync(e.sheenRoughnessMap),texCoord:e.sheenRoughnessMap.channel};n.applyTextureTransform(t,e.sheenRoughnessMap),i.sheenRoughnessTexture=t}if(e.sheenColorMap){const t={index:await n.processTextureAsync(e.sheenColorMap),texCoord:e.sheenColorMap.channel};n.applyTextureTransform(t,e.sheenColorMap),i.sheenColorTexture=t}i.sheenRoughnessFactor=e.sheenRoughness,i.sheenColorFactor=e.sheenColor.toArray(),t.extensions=t.extensions||{},t.extensions[this.name]=i,r[this.name]=!0}},Z=class{constructor(e){this.writer=e,this.name="KHR_materials_anisotropy"}async writeMaterialAsync(e,t){if(!e.isMeshPhysicalMaterial||0==e.anisotropy)return;const n=this.writer,r=n.extensionsUsed,i={};if(e.anisotropyMap){const t={index:await n.processTextureAsync(e.anisotropyMap)};n.applyTextureTransform(t,e.anisotropyMap),i.anisotropyTexture=t}i.anisotropyStrength=e.anisotropy,i.anisotropyRotation=e.anisotropyRotation,t.extensions=t.extensions||{},t.extensions[this.name]=i,r[this.name]=!0}},J=class{constructor(e){this.writer=e,this.name="KHR_materials_emissive_strength"}async writeMaterialAsync(e,t){if(!e.isMeshStandardMaterial||1===e.emissiveIntensity)return;const n=this.writer.extensionsUsed,r={};r.emissiveStrength=e.emissiveIntensity,t.extensions=t.extensions||{},t.extensions[this.name]=r,n[this.name]=!0}},ee=class{constructor(e){this.writer=e,this.name="EXT_materials_bump"}async writeMaterialAsync(e,t){if(!e.isMeshStandardMaterial||1===e.bumpScale&&!e.bumpMap)return;const n=this.writer,r=n.extensionsUsed,i={};if(e.bumpMap){const t={index:await n.processTextureAsync(e.bumpMap),texCoord:e.bumpMap.channel};n.applyTextureTransform(t,e.bumpMap),i.bumpTexture=t}i.bumpFactor=e.bumpScale,t.extensions=t.extensions||{},t.extensions[this.name]=i,r[this.name]=!0}},te=class{constructor(e){this.writer=e,this.name="EXT_mesh_gpu_instancing"}writeNode(e,t){if(!e.isInstancedMesh)return;const n=this.writer,i=e,s=new Float32Array(3*i.count),a=new Float32Array(4*i.count),o=new Float32Array(3*i.count),l=new r.Matrix4,c=new r.Vector3,u=new r.Quaternion,h=new r.Vector3;for(let r=0;r<i.count;r++)i.getMatrixAt(r,l),l.decompose(c,u,h),c.toArray(s,3*r),u.toArray(a,4*r),h.toArray(o,3*r);const d={TRANSLATION:n.processAccessor(new r.BufferAttribute(s,3)),ROTATION:n.processAccessor(new r.BufferAttribute(a,4)),SCALE:n.processAccessor(new r.BufferAttribute(o,3))};i.instanceColor&&(d._COLOR_0=n.processAccessor(i.instanceColor)),t.extensions=t.extensions||{},t.extensions[this.name]={attributes:d},n.extensionsUsed[this.name]=!0,n.extensionsRequired[this.name]=!0}};c.Utils={insertKeyframe:function(e,t){const n=.001,r=e.getValueSize(),i=new e.TimeBufferType(e.times.length+1),s=new e.ValueBufferType(e.values.length+r),a=e.createInterpolant(new e.ValueBufferType(r));let o;if(0===e.times.length){i[0]=t;for(let e=0;e<r;e++)s[e]=0;o=0}else if(t<e.times[0]){if(Math.abs(e.times[0]-t)<n)return 0;i[0]=t,i.set(e.times,1),s.set(a.evaluate(t),0),s.set(e.values,r),o=0}else if(t>e.times[e.times.length-1]){if(Math.abs(e.times[e.times.length-1]-t)<n)return e.times.length-1;i[i.length-1]=t,i.set(e.times,0),s.set(e.values,0),s.set(a.evaluate(t),e.values.length),o=i.length-1}else for(let l=0;l<e.times.length;l++){if(Math.abs(e.times[l]-t)<n)return l;if(e.times[l]<t&&e.times[l+1]>t){i.set(e.times.slice(0,l+1),0),i[l+1]=t,i.set(e.times.slice(l+1),l+2),s.set(e.values.slice(0,(l+1)*r),0),s.set(a.evaluate(t),(l+1)*r),s.set(e.values.slice((l+1)*r),(l+2)*r),o=l+1;break}}return e.times=i,e.values=s,o},mergeMorphTargetTracks:function(e,t){const n=[],i={},s=e.tracks;for(let a=0;a<s.length;++a){let e=s[a];const o=r.PropertyBinding.parseTrackName(e.name),l=r.PropertyBinding.findNode(t,o.nodeName);if("morphTargetInfluences"!==o.propertyName||void 0===o.propertyIndex){n.push(e);continue}if(e.createInterpolant!==e.InterpolantFactoryMethodDiscrete&&e.createInterpolant!==e.InterpolantFactoryMethodLinear){if(e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline)throw new Error("THREE.GLTFExporter: Cannot merge tracks with glTF CUBICSPLINE interpolation.");e=e.clone(),e.setInterpolation(r.InterpolateLinear)}const c=l.morphTargetInfluences.length,u=l.morphTargetDictionary[o.propertyIndex];if(void 0===u)throw new Error("THREE.GLTFExporter: Morph target name not found: "+o.propertyIndex);let h;if(void 0===i[l.uuid]){h=e.clone();const t=new h.ValueBufferType(c*h.times.length);for(let e=0;e<h.times.length;e++)t[e*c+u]=h.values[e];h.name=(o.nodeName||"")+".morphTargetInfluences",h.values=t,i[l.uuid]=h,n.push(h);continue}const d=e.createInterpolant(new e.ValueBufferType(1));h=i[l.uuid];for(let t=0;t<h.times.length;t++)h.values[t*c+u]=d.evaluate(h.times[t]);for(let t=0;t<e.times.length;t++){const n=this.insertKeyframe(h,e.times[t]);h.values[n*c+u]=e.values[t]}}return e.tracks=n,e},toTypedBufferAttribute:function(e,t){const n=new r.BufferAttribute(new t(e.count*e.itemSize),e.itemSize,!1);if(!e.normalized&&!e.isInterleavedBufferAttribute)return n.array.set(e.array),n;for(let r=0,i=e.count;r<i;r++)for(let t=0;t<e.itemSize;t++)n.setComponent(r,t,e.getComponent(r,t));return n}};const ne=9,re=15,ie=16,se=22,ae=37,oe=43,le=76,ce=83,ue=91,he=97,de=100,pe=103,me=109,fe=122,ge=123,xe=131,ye=132,ve=133,be=134,we=137,Te=138,Se=139,_e=140,Me=141,Ae=142,Ee=145,Ce=146,Re=148,De=152,ke=153,Ie=154,Pe=155,Le=156,Ue=157,Fe=158,ze=165,Be=166,Ve=1000054e3,Oe=1000054001,Ne=1000054004,$e=1000054005,Ge=1000066e3,qe=1000066004;class He{constructor(e,t,n,r){this._dataView=void 0,this._littleEndian=void 0,this._offset=void 0,this._dataView=new DataView(e.buffer,e.byteOffset+t,n),this._littleEndian=r,this._offset=0}_nextUint8(){const e=this._dataView.getUint8(this._offset);return this._offset+=1,e}_nextUint16(){const e=this._dataView.getUint16(this._offset,this._littleEndian);return this._offset+=2,e}_nextUint32(){const e=this._dataView.getUint32(this._offset,this._littleEndian);return this._offset+=4,e}_nextUint64(){const e=this._dataView.getUint32(this._offset,this._littleEndian)+2**32*this._dataView.getUint32(this._offset+4,this._littleEndian);return this._offset+=8,e}_nextInt32(){const e=this._dataView.getInt32(this._offset,this._littleEndian);return this._offset+=4,e}_nextUint8Array(e){const t=new Uint8Array(this._dataView.buffer,this._dataView.byteOffset+this._offset,e);return this._offset+=e,t}_skip(e){return this._offset+=e,this}_scan(e,t=0){const n=this._offset;let r=0;for(;this._dataView.getUint8(this._offset)!==t&&r<e;)r++,this._offset++;return r<e&&this._offset++,new Uint8Array(this._dataView.buffer,this._dataView.byteOffset+n,r)}}const je=[171,75,84,88,32,50,48,187,13,10,26,10];function We(e){return(new TextDecoder).decode(e)}function Xe(e,t){if(t===r.TrianglesDrawMode)return e;if(t===r.TriangleFanDrawMode||t===r.TriangleStripDrawMode){let n=e.getIndex();if(null===n){const t=[],r=e.getAttribute("position");if(void 0===r)return e;for(let e=0;e<r.count;e++)t.push(e);e.setIndex(t),n=e.getIndex()}const i=n.count-2,s=[];if(t===r.TriangleFanDrawMode)for(let e=1;e<=i;e++)s.push(n.getX(0)),s.push(n.getX(e)),s.push(n.getX(e+1));else for(let e=0;e<i;e++)e%2==0?(s.push(n.getX(e)),s.push(n.getX(e+1)),s.push(n.getX(e+2))):(s.push(n.getX(e+2)),s.push(n.getX(e+1)),s.push(n.getX(e)));s.length;const a=e.clone();return a.setIndex(s),a.clearGroups(),a}return e}const Ye=new WeakMap,Ke="undefined"==typeof document?require("url").pathToFileURL(__dirname+"/assets/viewer/draco-decoder-c55a594e8ffd.wasm").href:new URL("assets/viewer/draco-decoder-c55a594e8ffd.wasm",document.currentScript&&"SCRIPT"===document.currentScript.tagName.toUpperCase()&&document.currentScript.src||document.baseURI).href,Qe="undefined"==typeof document?require("url").pathToFileURL(__dirname+"/assets/viewer/draco-wasm-wrapper-e8049906ef3f.js").href:new URL("assets/viewer/draco-wasm-wrapper-e8049906ef3f.js",document.currentScript&&"SCRIPT"===document.currentScript.tagName.toUpperCase()&&document.currentScript.src||document.baseURI).href,Ze="undefined"==typeof document?require("url").pathToFileURL(__dirname+"/assets/viewer/draco-decoder-30e4d486fa02.js").href:new URL("assets/viewer/draco-decoder-30e4d486fa02.js",document.currentScript&&"SCRIPT"===document.currentScript.tagName.toUpperCase()&&document.currentScript.src||document.baseURI).href;class Je extends r.Loader{constructor(e){super(e),this.decoderPaths={js:Qe,wasm:Ke,dep_js:Ze},this.decoderConfig={},this.decoderBinary=null,this.decoderPending=null,this.workerLimit=4,this.workerPool=[],this.workerNextTaskID=1,this.workerSourceURL="",this.defaultAttributeIDs={position:"POSITION",normal:"NORMAL",color:"COLOR",uv:"TEX_COORD"},this.defaultAttributeTypes={position:"Float32Array",normal:"Float32Array",color:"Float32Array",uv:"Float32Array"}}setDecoderPath(e){const{decoderPaths:t}=this;return"object"==typeof e?(t.js=e.js,t.wasm=e.wasm,t.dep_js=null):(t.js=r.LoaderUtils.resolveURL("draco_wasm_wrapper.js",e),t.wasm=r.LoaderUtils.resolveURL("draco_decoder.wasm",e),t.dep_js=r.LoaderUtils.resolveURL("draco_decoder.js",e)),this}setDecoderConfig(e){return this.decoderConfig=e,this}setWorkerLimit(e){return this.workerLimit=e,this}load(e,t,n,i){const s=new r.FileLoader(this.manager);s.setPath(this.path),s.setResponseType("arraybuffer"),s.setRequestHeader(this.requestHeader),s.setWithCredentials(this.withCredentials),s.load(e,(e=>{this.parse(e,t,i)}),n,i)}parse(e,t,n=()=>{}){this.decodeDracoFile(e,t,null,null,r.SRGBColorSpace,n).catch(n)}decodeDracoFile(e,t,n,i,s=r.LinearSRGBColorSpace,a=()=>{}){const o={attributeIDs:n||this.defaultAttributeIDs,attributeTypes:i||this.defaultAttributeTypes,useUniqueIDs:!!n,vertexColorSpace:s};return this.decodeGeometry(e,o).then(t).catch(a)}decodeGeometry(e,t){const n=JSON.stringify(t);if(Ye.has(e)){const t=Ye.get(e);if(t.key===n)return t.promise;if(0===e.byteLength)throw new Error("THREE.DRACOLoader: Unable to re-decode a buffer with different settings. Buffer has already been transferred.")}let r;const i=this.workerNextTaskID++,s=e.byteLength,a=this._getWorker(i,s).then((n=>(r=n,new Promise(((n,s)=>{r._callbacks[i]={resolve:n,reject:s},r.postMessage({type:"decode",id:i,taskConfig:t,buffer:e},[e])}))))).then((e=>this._createGeometry(e.geometry)));return a.catch((()=>!0)).then((()=>{r&&i&&this._releaseTask(r,i)})),Ye.set(e,{key:n,promise:a}),a}_createGeometry(e){const t=new r.BufferGeometry;e.index&&t.setIndex(new r.BufferAttribute(e.index.array,1));for(let n=0;n<e.attributes.length;n++){const{name:i,array:s,itemSize:a,stride:o,vertexColorSpace:l}=e.attributes[n];let c;if(a===o)c=new r.BufferAttribute(s,a);else{const e=new r.InterleavedBuffer(s,o);c=new r.InterleavedBufferAttribute(e,a,0)}"color"===i&&(this._assignVertexColorSpace(c,l),c.normalized=s instanceof Float32Array==!1),t.setAttribute(i,c)}return t}_assignVertexColorSpace(e,t){if(t!==r.SRGBColorSpace)return;const n=new r.Color;for(let i=0,s=e.count;i<s;i++)n.fromBufferAttribute(e,i),r.ColorManagement.colorSpaceToWorking(n,r.SRGBColorSpace),e.setXYZ(i,n.r,n.g,n.b)}_loadLibrary(e,t){const n=new r.FileLoader(this.manager);return n.setResponseType(t),n.setWithCredentials(this.withCredentials),new Promise(((t,r)=>{n.load(e,t,void 0,r)}))}preload(){return this._initDecoder(),this}_initDecoder(){if(this.decoderPending)return this.decoderPending;const e="object"!=typeof WebAssembly||"js"===this.decoderConfig.type,t=[],{decoderPaths:n}=this;if(e){if(null===n.dep_js)throw new Error("THREE.DRACOLoader: WebAssembly is required when using a custom decoder paths.");t.push(this._loadLibrary(n.dep_js,"text"))}else t.push(this._loadLibrary(n.js,"text")),t.push(this._loadLibrary(n.wasm,"arraybuffer"));return this.decoderPending=Promise.all(t).then((t=>{const n=t[0];e||(this.decoderConfig.wasmBinary=t[1]);const r=et.toString(),i=["/* draco decoder */",n,"","/* worker */",r.substring(r.indexOf("{")+1,r.lastIndexOf("}"))].join("\n");this.workerSourceURL=URL.createObjectURL(new Blob([i]))})),this.decoderPending}_getWorker(e,t){return this._initDecoder().then((()=>{if(this.workerPool.length<this.workerLimit){const e=new Worker(this.workerSourceURL);e._callbacks={},e._taskCosts={},e._taskLoad=0,e.postMessage({type:"init",decoderConfig:this.decoderConfig}),e.onmessage=function(t){const n=t.data;switch(n.type){case"decode":e._callbacks[n.id].resolve(n);break;case"error":e._callbacks[n.id].reject(n)}},this.workerPool.push(e)}else this.workerPool.sort((function(e,t){return e._taskLoad>t._taskLoad?-1:1}));const n=this.workerPool[this.workerPool.length-1];return n._taskCosts[e]=t,n._taskLoad+=t,n}))}_releaseTask(e,t){e._taskLoad-=e._taskCosts[t],delete e._callbacks[t],delete e._taskCosts[t]}debug(){}dispose(){for(let e=0;e<this.workerPool.length;++e)this.workerPool[e].terminate();return this.workerPool.length=0,""!==this.workerSourceURL&&URL.revokeObjectURL(this.workerSourceURL),this}}function et(){let e,t;function n(e,t,n,r,i,s){const a=n.num_points(),o=s.num_components(),l=function(e,t){switch(t){case Float32Array:return e.DT_FLOAT32;case Int8Array:return e.DT_INT8;case Int16Array:return e.DT_INT16;case Int32Array:return e.DT_INT32;case Uint8Array:return e.DT_UINT8;case Uint16Array:return e.DT_UINT16;case Uint32Array:return e.DT_UINT32}}(e,i),c=o*i.BYTES_PER_ELEMENT,u=4*Math.ceil(c/4),h=u/i.BYTES_PER_ELEMENT,d=a*c,p=a*u,m=e._malloc(d);t.GetAttributeDataArrayForAllPoints(n,s,l,d,m);const f=new i(e.HEAPF32.buffer,m,d/i.BYTES_PER_ELEMENT);let g;if(c===u)g=f.slice();else{g=new i(p/i.BYTES_PER_ELEMENT);let e=0;for(let t=0,n=f.length;t<n;t++){for(let n=0;n<o;n++)g[e+n]=f[t*o+n];e+=h}}return e._free(m),{name:r,count:a,itemSize:o,array:g,stride:h}}onmessage=function(r){const i=r.data;switch(i.type){case"init":e=i.decoderConfig,t=new Promise((function(t){e.onModuleLoaded=function(e){t({draco:e})},DracoDecoderModule(e)}));break;case"decode":const r=i.buffer,s=i.taskConfig;t.then((e=>{const t=e.draco,a=new t.Decoder;try{const e=function(e,t,r,i){const s=i.attributeIDs,a=i.attributeTypes;let o,l;const c=t.GetEncodedGeometryType(r);if(c===e.TRIANGULAR_MESH)o=new e.Mesh,l=t.DecodeArrayToMesh(r,r.byteLength,o);else{if(c!==e.POINT_CLOUD)throw new Error("THREE.DRACOLoader: Unexpected geometry type.");o=new e.PointCloud,l=t.DecodeArrayToPointCloud(r,r.byteLength,o)}if(!l.ok()||0===o.ptr)throw new Error("THREE.DRACOLoader: Decoding failed: "+l.error_msg());const u={index:null,attributes:[]};for(const h in s){const r=self[a[h]];let l,c;if(i.useUniqueIDs)c=s[h],l=t.GetAttributeByUniqueId(o,c);else{if(c=t.GetAttributeId(o,e[s[h]]),-1===c)continue;l=t.GetAttribute(o,c)}const d=n(e,t,o,h,r,l);"color"===h&&(d.vertexColorSpace=i.vertexColorSpace),u.attributes.push(d)}c===e.TRIANGULAR_MESH&&(u.index=function(e,t,n){const r=n.num_faces(),i=3*r,s=4*i,a=e._malloc(s);t.GetTrianglesUInt32Array(n,s,a);const o=new Uint32Array(e.HEAPF32.buffer,a,i).slice();return e._free(a),{array:o,itemSize:1}}(e,t,o));return e.destroy(o),u}(t,a,new Int8Array(r),s),o=e.attributes.map((e=>e.array.buffer));e.index&&o.push(e.index.array.buffer),self.postMessage({type:"decode",id:i.id,geometry:e},o)}catch(o){self.postMessage({type:"error",id:i.id,error:o.message})}finally{t.destroy(a)}}))}}}function tt(e){const t=new Map,n=new Map,r=e.clone();return nt(e,r,(function(e,r){t.set(r,e),n.set(e,r)})),r.traverse((function(e){if(!e.isSkinnedMesh)return;const r=e,i=t.get(e),s=i.skeleton.bones;r.skeleton=i.skeleton.clone(),r.bindMatrix.copy(i.bindMatrix),r.skeleton.bones=s.map((function(e){return n.get(e)})),r.bind(r.skeleton,r.bindMatrix)})),r}function nt(e,t,n){n(e,t);for(let r=0;r<e.children.length;r++)nt(e.children[r],t.children[r],n)}class rt extends r.Loader{constructor(e){super(e),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register((function(e){return new ut(e)})),this.register((function(e){return new ht(e)})),this.register((function(e){return new bt(e)})),this.register((function(e){return new wt(e)})),this.register((function(e){return new Tt(e)})),this.register((function(e){return new pt(e)})),this.register((function(e){return new mt(e)})),this.register((function(e){return new ft(e)})),this.register((function(e){return new gt(e)})),this.register((function(e){return new ct(e)})),this.register((function(e){return new xt(e)})),this.register((function(e){return new dt(e)})),this.register((function(e){return new vt(e)})),this.register((function(e){return new yt(e)})),this.register((function(e){return new ot(e)})),this.register((function(e){return new St(e,at.EXT_MESHOPT_COMPRESSION)})),this.register((function(e){return new St(e,at.KHR_MESHOPT_COMPRESSION)})),this.register((function(e){return new _t(e)}))}load(e,t,n,i){const s=this;let a;if(""!==this.resourcePath)a=this.resourcePath;else if(""!==this.path){const t=r.LoaderUtils.extractUrlBase(e);a=r.LoaderUtils.resolveURL(t,this.path)}else a=r.LoaderUtils.extractUrlBase(e);this.manager.itemStart(e);const o=function(t){i&&i(t),s.manager.itemError(e),s.manager.itemEnd(e)},l=new r.FileLoader(this.manager);l.setPath(this.path),l.setResponseType("arraybuffer"),l.setRequestHeader(this.requestHeader),l.setWithCredentials(this.withCredentials),l.load(e,(function(n){try{s.parse(n,a,(function(n){t(n),s.manager.itemEnd(e)}),o)}catch(r){o(r)}}),n,o)}setDRACOLoader(e){return this.dracoLoader=e,this}setKTX2Loader(e){return this.ktx2Loader=e,this}setMeshoptDecoder(e){return this.meshoptDecoder=e,this}register(e){return-1===this.pluginCallbacks.indexOf(e)&&this.pluginCallbacks.push(e),this}unregister(e){return-1!==this.pluginCallbacks.indexOf(e)&&this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(e),1),this}parse(e,t,n,r){let i;const s={},a={},o=new TextDecoder;if("string"==typeof e)i=JSON.parse(e);else if(e instanceof ArrayBuffer){if(o.decode(new Uint8Array(e,0,4))===Mt){try{s[at.KHR_BINARY_GLTF]=new Ct(e)}catch(c){return void(r&&r(c))}i=JSON.parse(s[at.KHR_BINARY_GLTF].content)}else i=JSON.parse(o.decode(e))}else i=e;if(void 0===i.asset||i.asset.version[0]<2)return void(r&&r(new Error("THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported.")));const l=new Jt(i,{path:t||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});l.fileLoader.setRequestHeader(this.requestHeader);for(let u=0;u<this.pluginCallbacks.length;u++){const e=this.pluginCallbacks[u](l);e.name,a[e.name]=e,s[e.name]=!0}if(i.extensionsUsed)for(let u=0;u<i.extensionsUsed.length;++u){const e=i.extensionsUsed[u],t=i.extensionsRequired||[];switch(e){case at.KHR_MATERIALS_UNLIT:s[e]=new lt;break;case at.KHR_DRACO_MESH_COMPRESSION:s[e]=new Rt(i,this.dracoLoader);break;case at.KHR_TEXTURE_TRANSFORM:s[e]=new Dt;break;case at.KHR_MESH_QUANTIZATION:s[e]=new kt;break;default:t.indexOf(e)>=0&&a[e]}}l.setExtensions(s),l.setPlugins(a),l.parse(n,r)}parseAsync(e,t){const n=this;return new Promise((function(r,i){n.parse(e,t,r,i)}))}}function it(){let e={};return{get:function(t){return e[t]},add:function(t,n){e[t]=n},remove:function(t){delete e[t]},removeAll:function(){e={}}}}function st(e,t,n){const r=e.json.materials[t];return r.extensions&&r.extensions[n]?r.extensions[n]:null}const at={KHR_BINARY_GLTF:"KHR_binary_glTF",KHR_DRACO_MESH_COMPRESSION:"KHR_draco_mesh_compression",KHR_LIGHTS_PUNCTUAL:"KHR_lights_punctual",KHR_MATERIALS_CLEARCOAT:"KHR_materials_clearcoat",KHR_MATERIALS_DISPERSION:"KHR_materials_dispersion",KHR_MATERIALS_IOR:"KHR_materials_ior",KHR_MATERIALS_SHEEN:"KHR_materials_sheen",KHR_MATERIALS_SPECULAR:"KHR_materials_specular",KHR_MATERIALS_TRANSMISSION:"KHR_materials_transmission",KHR_MATERIALS_IRIDESCENCE:"KHR_materials_iridescence",KHR_MATERIALS_ANISOTROPY:"KHR_materials_anisotropy",KHR_MATERIALS_UNLIT:"KHR_materials_unlit",KHR_MATERIALS_VOLUME:"KHR_materials_volume",KHR_TEXTURE_BASISU:"KHR_texture_basisu",KHR_TEXTURE_TRANSFORM:"KHR_texture_transform",KHR_MESH_QUANTIZATION:"KHR_mesh_quantization",KHR_MATERIALS_EMISSIVE_STRENGTH:"KHR_materials_emissive_strength",EXT_MATERIALS_BUMP:"EXT_materials_bump",EXT_TEXTURE_WEBP:"EXT_texture_webp",EXT_TEXTURE_AVIF:"EXT_texture_avif",EXT_MESHOPT_COMPRESSION:"EXT_meshopt_compression",KHR_MESHOPT_COMPRESSION:"KHR_meshopt_compression",EXT_MESH_GPU_INSTANCING:"EXT_mesh_gpu_instancing"};class ot{constructor(e){this.parser=e,this.name=at.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){const e=this.parser,t=this.parser.json.nodes||[];for(let n=0,r=t.length;n<r;n++){const r=t[n];r.extensions&&r.extensions[this.name]&&void 0!==r.extensions[this.name].light&&e._addNodeRef(this.cache,r.extensions[this.name].light)}}_loadLight(e){const t=this.parser,n="light:"+e;let i=t.cache.get(n);if(i)return i;const s=t.json,a=((s.extensions&&s.extensions[this.name]||{}).lights||[])[e];let o;const l=new r.Color(16777215);void 0!==a.color&&l.setRGB(a.color[0],a.color[1],a.color[2],r.LinearSRGBColorSpace);const c=void 0!==a.range?a.range:0;switch(a.type){case"directional":o=new r.DirectionalLight(l),o.target.position.set(0,0,-1),o.add(o.target);break;case"point":o=new r.PointLight(l),o.distance=c;break;case"spot":o=new r.SpotLight(l),o.distance=c,a.spot=a.spot||{},a.spot.innerConeAngle=void 0!==a.spot.innerConeAngle?a.spot.innerConeAngle:0,a.spot.outerConeAngle=void 0!==a.spot.outerConeAngle?a.spot.outerConeAngle:Math.PI/4,o.angle=a.spot.outerConeAngle,o.penumbra=1-a.spot.innerConeAngle/a.spot.outerConeAngle,o.target.position.set(0,0,-1),o.add(o.target);break;default:throw new Error("THREE.GLTFLoader: Unexpected light type: "+a.type)}return o.position.set(0,0,0),Wt(o,a),void 0!==a.intensity&&(o.intensity=a.intensity),o.name=t.createUniqueName(a.name||"light_"+e),i=Promise.resolve(o),t.cache.add(n,i),i}getDependency(e,t){if("light"===e)return this._loadLight(t)}createNodeAttachment(e){const t=this,n=this.parser,r=n.json.nodes[e],i=(r.extensions&&r.extensions[this.name]||{}).light;return void 0===i?null:this._loadLight(i).then((function(e){return n._getNodeRef(t.cache,i,e)}))}}class lt{constructor(){this.name=at.KHR_MATERIALS_UNLIT}getMaterialType(){return r.MeshBasicMaterial}extendParams(e,t,n){const i=[];e.color=new r.Color(1,1,1),e.opacity=1;const s=t.pbrMetallicRoughness;if(s){if(Array.isArray(s.baseColorFactor)){const t=s.baseColorFactor;e.color.setRGB(t[0],t[1],t[2],r.LinearSRGBColorSpace),e.opacity=t[3]}void 0!==s.baseColorTexture&&i.push(n.assignTexture(e,"map",s.baseColorTexture,r.SRGBColorSpace))}return Promise.all(i)}}class ct{constructor(e){this.parser=e,this.name=at.KHR_MATERIALS_EMISSIVE_STRENGTH}extendMaterialParams(e,t){const n=st(this.parser,e,this.name);return null===n||void 0!==n.emissiveStrength&&(t.emissiveIntensity=n.emissiveStrength),Promise.resolve()}}class ut{constructor(e){this.parser=e,this.name=at.KHR_MATERIALS_CLEARCOAT}getMaterialType(e){return null!==st(this.parser,e,this.name)?r.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=st(this.parser,e,this.name);if(null===n)return Promise.resolve();const i=[];if(void 0!==n.clearcoatFactor&&(t.clearcoat=n.clearcoatFactor),void 0!==n.clearcoatTexture&&i.push(this.parser.assignTexture(t,"clearcoatMap",n.clearcoatTexture)),void 0!==n.clearcoatRoughnessFactor&&(t.clearcoatRoughness=n.clearcoatRoughnessFactor),void 0!==n.clearcoatRoughnessTexture&&i.push(this.parser.assignTexture(t,"clearcoatRoughnessMap",n.clearcoatRoughnessTexture)),void 0!==n.clearcoatNormalTexture&&(i.push(this.parser.assignTexture(t,"clearcoatNormalMap",n.clearcoatNormalTexture)),void 0!==n.clearcoatNormalTexture.scale)){const e=n.clearcoatNormalTexture.scale;t.clearcoatNormalScale=new r.Vector2(e,e)}return Promise.all(i)}}class ht{constructor(e){this.parser=e,this.name=at.KHR_MATERIALS_DISPERSION}getMaterialType(e){return null!==st(this.parser,e,this.name)?r.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=st(this.parser,e,this.name);return null===n||(t.dispersion=void 0!==n.dispersion?n.dispersion:0),Promise.resolve()}}class dt{constructor(e){this.parser=e,this.name=at.KHR_MATERIALS_IRIDESCENCE}getMaterialType(e){return null!==st(this.parser,e,this.name)?r.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=st(this.parser,e,this.name);if(null===n)return Promise.resolve();const r=[];return void 0!==n.iridescenceFactor&&(t.iridescence=n.iridescenceFactor),void 0!==n.iridescenceTexture&&r.push(this.parser.assignTexture(t,"iridescenceMap",n.iridescenceTexture)),void 0!==n.iridescenceIor&&(t.iridescenceIOR=n.iridescenceIor),void 0===t.iridescenceThicknessRange&&(t.iridescenceThicknessRange=[100,400]),void 0!==n.iridescenceThicknessMinimum&&(t.iridescenceThicknessRange[0]=n.iridescenceThicknessMinimum),void 0!==n.iridescenceThicknessMaximum&&(t.iridescenceThicknessRange[1]=n.iridescenceThicknessMaximum),void 0!==n.iridescenceThicknessTexture&&r.push(this.parser.assignTexture(t,"iridescenceThicknessMap",n.iridescenceThicknessTexture)),Promise.all(r)}}class pt{constructor(e){this.parser=e,this.name=at.KHR_MATERIALS_SHEEN}getMaterialType(e){return null!==st(this.parser,e,this.name)?r.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=st(this.parser,e,this.name);if(null===n)return Promise.resolve();const i=[];if(t.sheenColor=new r.Color(0,0,0),t.sheenRoughness=0,t.sheen=1,void 0!==n.sheenColorFactor){const e=n.sheenColorFactor;t.sheenColor.setRGB(e[0],e[1],e[2],r.LinearSRGBColorSpace)}return void 0!==n.sheenRoughnessFactor&&(t.sheenRoughness=n.sheenRoughnessFactor),void 0!==n.sheenColorTexture&&i.push(this.parser.assignTexture(t,"sheenColorMap",n.sheenColorTexture,r.SRGBColorSpace)),void 0!==n.sheenRoughnessTexture&&i.push(this.parser.assignTexture(t,"sheenRoughnessMap",n.sheenRoughnessTexture)),Promise.all(i)}}class mt{constructor(e){this.parser=e,this.name=at.KHR_MATERIALS_TRANSMISSION}getMaterialType(e){return null!==st(this.parser,e,this.name)?r.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=st(this.parser,e,this.name);if(null===n)return Promise.resolve();const r=[];return void 0!==n.transmissionFactor&&(t.transmission=n.transmissionFactor),void 0!==n.transmissionTexture&&r.push(this.parser.assignTexture(t,"transmissionMap",n.transmissionTexture)),Promise.all(r)}}class ft{constructor(e){this.parser=e,this.name=at.KHR_MATERIALS_VOLUME}getMaterialType(e){return null!==st(this.parser,e,this.name)?r.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=st(this.parser,e,this.name);if(null===n)return Promise.resolve();const i=[];t.thickness=void 0!==n.thicknessFactor?n.thicknessFactor:0,void 0!==n.thicknessTexture&&i.push(this.parser.assignTexture(t,"thicknessMap",n.thicknessTexture)),t.attenuationDistance=n.attenuationDistance||1/0;const s=n.attenuationColor||[1,1,1];return t.attenuationColor=(new r.Color).setRGB(s[0],s[1],s[2],r.LinearSRGBColorSpace),Promise.all(i)}}class gt{constructor(e){this.parser=e,this.name=at.KHR_MATERIALS_IOR}getMaterialType(e){return null!==st(this.parser,e,this.name)?r.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=st(this.parser,e,this.name);return null===n||(t.ior=void 0!==n.ior?n.ior:1.5,0===t.ior&&(t.ior=1e3)),Promise.resolve()}}class xt{constructor(e){this.parser=e,this.name=at.KHR_MATERIALS_SPECULAR}getMaterialType(e){return null!==st(this.parser,e,this.name)?r.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=st(this.parser,e,this.name);if(null===n)return Promise.resolve();const i=[];t.specularIntensity=void 0!==n.specularFactor?n.specularFactor:1,void 0!==n.specularTexture&&i.push(this.parser.assignTexture(t,"specularIntensityMap",n.specularTexture));const s=n.specularColorFactor||[1,1,1];return t.specularColor=(new r.Color).setRGB(s[0],s[1],s[2],r.LinearSRGBColorSpace),void 0!==n.specularColorTexture&&i.push(this.parser.assignTexture(t,"specularColorMap",n.specularColorTexture,r.SRGBColorSpace)),Promise.all(i)}}class yt{constructor(e){this.parser=e,this.name=at.EXT_MATERIALS_BUMP}getMaterialType(e){return null!==st(this.parser,e,this.name)?r.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=st(this.parser,e,this.name);if(null===n)return Promise.resolve();const r=[];return t.bumpScale=void 0!==n.bumpFactor?n.bumpFactor:1,void 0!==n.bumpTexture&&r.push(this.parser.assignTexture(t,"bumpMap",n.bumpTexture)),Promise.all(r)}}class vt{constructor(e){this.parser=e,this.name=at.KHR_MATERIALS_ANISOTROPY}getMaterialType(e){return null!==st(this.parser,e,this.name)?r.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=st(this.parser,e,this.name);if(null===n)return Promise.resolve();const r=[];return void 0!==n.anisotropyStrength&&(t.anisotropy=n.anisotropyStrength),void 0!==n.anisotropyRotation&&(t.anisotropyRotation=n.anisotropyRotation),void 0!==n.anisotropyTexture&&r.push(this.parser.assignTexture(t,"anisotropyMap",n.anisotropyTexture)),Promise.all(r)}}class bt{constructor(e){this.parser=e,this.name=at.KHR_TEXTURE_BASISU}loadTexture(e){const t=this.parser,n=t.json,r=n.textures[e];if(!r.extensions||!r.extensions[this.name])return null;const i=r.extensions[this.name],s=t.options.ktx2Loader;if(!s){if(n.extensionsRequired&&n.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");return null}return t.loadTextureImage(e,i.source,s)}}class wt{constructor(e){this.parser=e,this.name=at.EXT_TEXTURE_WEBP}loadTexture(e){const t=this.name,n=this.parser,r=n.json,i=r.textures[e];if(!i.extensions||!i.extensions[t])return null;const s=i.extensions[t],a=r.images[s.source];let o=n.textureLoader;if(a.uri){const e=n.options.manager.getHandler(a.uri);null!==e&&(o=e)}return n.loadTextureImage(e,s.source,o)}}class Tt{constructor(e){this.parser=e,this.name=at.EXT_TEXTURE_AVIF}loadTexture(e){const t=this.name,n=this.parser,r=n.json,i=r.textures[e];if(!i.extensions||!i.extensions[t])return null;const s=i.extensions[t],a=r.images[s.source];let o=n.textureLoader;if(a.uri){const e=n.options.manager.getHandler(a.uri);null!==e&&(o=e)}return n.loadTextureImage(e,s.source,o)}}class St{constructor(e,t){this.name=t,this.parser=e}loadBufferView(e){const t=this.parser.json,n=t.bufferViews[e];if(n.extensions&&n.extensions[this.name]){const e=n.extensions[this.name],r=this.parser.getDependency("buffer",e.buffer),i=this.parser.options.meshoptDecoder;if(!i||!i.supported){if(t.extensionsRequired&&t.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files");return null}return r.then((function(t){const n=e.byteOffset||0,r=e.byteLength||0,s=e.count,a=e.byteStride,o=new Uint8Array(t,n,r);return i.decodeGltfBufferAsync?i.decodeGltfBufferAsync(s,a,o,e.mode,e.filter).then((function(e){return e.buffer})):i.ready.then((function(){const t=new ArrayBuffer(s*a);return i.decodeGltfBuffer(new Uint8Array(t),s,a,o,e.mode,e.filter),t}))}))}return null}}class _t{constructor(e){this.name=at.EXT_MESH_GPU_INSTANCING,this.parser=e}createNodeMesh(e){const t=this.parser.json,n=t.nodes[e];if(!n.extensions||!n.extensions[this.name]||void 0===n.mesh)return null;const i=t.meshes[n.mesh];for(const r of i.primitives)if(r.mode!==Ut.TRIANGLES&&r.mode!==Ut.TRIANGLE_STRIP&&r.mode!==Ut.TRIANGLE_FAN&&void 0!==r.mode)return null;const s=n.extensions[this.name].attributes,a=[],o={};for(const r in s)a.push(this.parser.getDependency("accessor",s[r]).then((e=>(o[r]=e,o[r]))));return a.length<1?null:(a.push(this.parser.createNodeMesh(e)),Promise.all(a).then((e=>{const t=e.pop(),n=t.isGroup?t.children:[t],i=e[0].count,s=[];for(const a of n){const e=new r.Matrix4,t=new r.Vector3,n=new r.Quaternion,l=new r.Vector3(1,1,1),c=new r.InstancedMesh(a.geometry,a.material,i);for(let r=0;r<i;r++)o.TRANSLATION&&t.fromBufferAttribute(o.TRANSLATION,r),o.ROTATION&&n.fromBufferAttribute(o.ROTATION,r),o.SCALE&&l.fromBufferAttribute(o.SCALE,r),c.setMatrixAt(r,e.compose(t,n,l));for(const i in o)if("_COLOR_0"===i){const e=o[i];c.instanceColor=new r.InstancedBufferAttribute(e.array,e.itemSize,e.normalized)}else"TRANSLATION"!==i&&"ROTATION"!==i&&"SCALE"!==i&&a.geometry.setAttribute(i,o[i]);r.Object3D.prototype.copy.call(c,a),this.parser.assignFinalMaterial(c),s.push(c)}return t.isGroup?(t.clear(),t.add(...s),t):s[0]})))}}const Mt="glTF",At=1313821514,Et=5130562;class Ct{constructor(e){this.name=at.KHR_BINARY_GLTF,this.content=null,this.body=null;const t=new DataView(e,0,12),n=new TextDecoder;if(this.header={magic:n.decode(new Uint8Array(e.slice(0,4))),version:t.getUint32(4,!0),length:t.getUint32(8,!0)},this.header.magic!==Mt)throw new Error("THREE.GLTFLoader: Unsupported glTF-Binary header.");if(this.header.version<2)throw new Error("THREE.GLTFLoader: Legacy binary file detected.");const r=this.header.length-12,i=new DataView(e,12);let s=0;for(;s<r;){const t=i.getUint32(s,!0);s+=4;const r=i.getUint32(s,!0);if(s+=4,r===At){const r=new Uint8Array(e,12+s,t);this.content=n.decode(r)}else if(r===Et){const n=12+s;this.body=e.slice(n,n+t)}s+=t}if(null===this.content)throw new Error("THREE.GLTFLoader: JSON content not found.")}}class Rt{constructor(e,t){if(!t)throw new Error("THREE.GLTFLoader: No DRACOLoader instance provided.");this.name=at.KHR_DRACO_MESH_COMPRESSION,this.json=e,this.dracoLoader=t,this.dracoLoader.preload()}decodePrimitive(e,t){const n=this.json,i=this.dracoLoader,s=e.extensions[this.name].bufferView,a=e.extensions[this.name].attributes,o={},l={},c={};for(const r in a){const e=Ot[r]||r.toLowerCase();o[e]=a[r]}for(const r in e.attributes){const t=Ot[r]||r.toLowerCase();if(void 0!==a[r]){const i=n.accessors[e.attributes[r]],s=Ft[i.componentType];c[t]=s.name,l[t]=!0===i.normalized}}return t.getDependency("bufferView",s).then((function(e){return new Promise((function(t,n){i.decodeDracoFile(e,(function(e){for(const t in e.attributes){const n=e.attributes[t],r=l[t];void 0!==r&&(n.normalized=r)}t(e)}),o,c,r.LinearSRGBColorSpace,n)}))}))}}class Dt{constructor(){this.name=at.KHR_TEXTURE_TRANSFORM}extendTexture(e,t){return void 0!==t.texCoord&&t.texCoord!==e.channel||void 0!==t.offset||void 0!==t.rotation||void 0!==t.scale?(e=e.clone(),void 0!==t.texCoord&&(e.channel=t.texCoord),void 0!==t.offset&&e.offset.fromArray(t.offset),void 0!==t.rotation&&(e.rotation=t.rotation),void 0!==t.scale&&e.repeat.fromArray(t.scale),e.needsUpdate=!0,e):e}}class kt{constructor(){this.name=at.KHR_MESH_QUANTIZATION}}class It extends r.Interpolant{constructor(e,t,n,r){super(e,t,n,r)}copySampleValue_(e){const t=this.resultBuffer,n=this.sampleValues,r=this.valueSize,i=e*r*3+r;for(let s=0;s!==r;s++)t[s]=n[i+s];return t}interpolate_(e,t,n,r){const i=this.resultBuffer,s=this.sampleValues,a=this.valueSize,o=2*a,l=3*a,c=r-t,u=(n-t)/c,h=u*u,d=h*u,p=e*l,m=p-l,f=-2*d+3*h,g=d-h,x=1-f,y=g-h+u;for(let v=0;v!==a;v++){const e=s[m+v+a],t=s[m+v+o]*c,n=s[p+v+a],r=s[p+v]*c;i[v]=x*e+y*t+f*n+g*r}return i}}const Pt=new r.Quaternion;class Lt extends It{interpolate_(e,t,n,r){const i=super.interpolate_(e,t,n,r);return Pt.fromArray(i).normalize().toArray(i),i}}const Ut={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6},Ft={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},zt={9728:r.NearestFilter,9729:r.LinearFilter,9984:r.NearestMipmapNearestFilter,9985:r.LinearMipmapNearestFilter,9986:r.NearestMipmapLinearFilter,9987:r.LinearMipmapLinearFilter},Bt={33071:r.ClampToEdgeWrapping,33648:r.MirroredRepeatWrapping,10497:r.RepeatWrapping},Vt={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},Ot={POSITION:"position",NORMAL:"normal",TANGENT:"tangent",TEXCOORD_0:"uv",TEXCOORD_1:"uv1",TEXCOORD_2:"uv2",TEXCOORD_3:"uv3",COLOR_0:"color",WEIGHTS_0:"skinWeight",JOINTS_0:"skinIndex"},Nt={scale:"scale",translation:"position",rotation:"quaternion",weights:"morphTargetInfluences"},$t={CUBICSPLINE:void 0,LINEAR:r.InterpolateLinear,STEP:r.InterpolateDiscrete},Gt="OPAQUE",qt="MASK",Ht="BLEND";function jt(e,t,n){for(const r in n.extensions)void 0===e[r]&&(t.userData.gltfExtensions=t.userData.gltfExtensions||{},t.userData.gltfExtensions[r]=n.extensions[r])}function Wt(e,t){void 0!==t.extras&&"object"==typeof t.extras&&Object.assign(e.userData,t.extras)}function Xt(e,t){if(e.updateMorphTargets(),void 0!==t.weights)for(let n=0,r=t.weights.length;n<r;n++)e.morphTargetInfluences[n]=t.weights[n];if(t.extras&&Array.isArray(t.extras.targetNames)){const n=t.extras.targetNames;if(e.morphTargetInfluences.length===n.length){e.morphTargetDictionary={};for(let t=0,r=n.length;t<r;t++)e.morphTargetDictionary[n[t]]=t}}}function Yt(e){let t;const n=e.extensions&&e.extensions[at.KHR_DRACO_MESH_COMPRESSION];if(t=n?"draco:"+n.bufferView+":"+n.indices+":"+Kt(n.attributes):e.indices+":"+Kt(e.attributes)+":"+e.mode,void 0!==e.targets)for(let r=0,i=e.targets.length;r<i;r++)t+=":"+Kt(e.targets[r]);return t}function Kt(e){let t="";const n=Object.keys(e).sort();for(let r=0,i=n.length;r<i;r++)t+=n[r]+":"+e[n[r]]+";";return t}function Qt(e){switch(e){case Int8Array:return 1/127;case Uint8Array:return 1/255;case Int16Array:return 1/32767;case Uint16Array:return 1/65535;default:throw new Error("THREE.GLTFLoader: Unsupported normalized accessor component type.")}}const Zt=new r.Matrix4;class Jt{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new it,this.associations=new Map,this.primitiveCache={},this.nodeCache={},this.meshCache={refs:{},uses:{}},this.cameraCache={refs:{},uses:{}},this.lightCache={refs:{},uses:{}},this.sourceCache={},this.textureCache={},this.nodeNamesUsed={};let n=!1,i=-1,s=!1,a=-1;if("undefined"!=typeof navigator&&void 0!==navigator.userAgent){const e=navigator.userAgent;n=!0===/^((?!chrome|android).)*safari/i.test(e);const t=e.match(/Version\/(\d+)/);i=n&&t?parseInt(t[1],10):-1,s=e.indexOf("Firefox")>-1,a=s?e.match(/Firefox\/([0-9]+)\./)[1]:-1}"undefined"==typeof createImageBitmap||n&&i<17||s&&a<98?this.textureLoader=new r.TextureLoader(this.options.manager):this.textureLoader=new r.ImageBitmapLoader(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new r.FileLoader(this.options.manager),this.fileLoader.setResponseType("arraybuffer"),"use-credentials"===this.options.crossOrigin&&this.fileLoader.setWithCredentials(!0)}setExtensions(e){this.extensions=e}setPlugins(e){this.plugins=e}parse(e,t){const n=this,r=this.json,i=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll((function(e){return e._markDefs&&e._markDefs()})),Promise.all(this._invokeAll((function(e){return e.beforeRoot&&e.beforeRoot()}))).then((function(){return Promise.all([n.getDependencies("scene"),n.getDependencies("animation"),n.getDependencies("camera")])})).then((function(t){const s={scene:t[0][r.scene||0],scenes:t[0],animations:t[1],cameras:t[2],asset:r.asset,parser:n,userData:{}};return jt(i,s,r),Wt(s,r),Promise.all(n._invokeAll((function(e){return e.afterRoot&&e.afterRoot(s)}))).then((function(){for(const e of s.scenes)e.updateMatrixWorld();e(s)}))})).catch(t)}_markDefs(){const e=this.json.nodes||[],t=this.json.skins||[],n=this.json.meshes||[];for(let r=0,i=t.length;r<i;r++){const n=t[r].joints;for(let t=0,r=n.length;t<r;t++)e[n[t]].isBone=!0}for(let r=0,i=e.length;r<i;r++){const t=e[r];void 0!==t.mesh&&(this._addNodeRef(this.meshCache,t.mesh),void 0!==t.skin&&(n[t.mesh].isSkinnedMesh=!0)),void 0!==t.camera&&this._addNodeRef(this.cameraCache,t.camera)}}_addNodeRef(e,t){void 0!==t&&(void 0===e.refs[t]&&(e.refs[t]=e.uses[t]=0),e.refs[t]++)}_getNodeRef(e,t,n){if(e.refs[t]<=1)return n;const r=n.clone(),i=(e,t)=>{const n=this.associations.get(e);null!=n&&this.associations.set(t,n);for(const[r,s]of e.children.entries())i(s,t.children[r])};return i(n,r),r.name+="_instance_"+e.uses[t]++,r}_invokeOne(e){const t=Object.values(this.plugins);t.push(this);for(let n=0;n<t.length;n++){const r=e(t[n]);if(r)return r}return null}_invokeAll(e){const t=Object.values(this.plugins);t.unshift(this);const n=[];for(let r=0;r<t.length;r++){const i=e(t[r]);i&&n.push(i)}return n}getDependency(e,t){const n=e+":"+t;let r=this.cache.get(n);if(!r){switch(e){case"scene":r=this.loadScene(t);break;case"node":r=this._invokeOne((function(e){return e.loadNode&&e.loadNode(t)}));break;case"mesh":r=this._invokeOne((function(e){return e.loadMesh&&e.loadMesh(t)}));break;case"accessor":r=this.loadAccessor(t);break;case"bufferView":r=this._invokeOne((function(e){return e.loadBufferView&&e.loadBufferView(t)}));break;case"buffer":r=this.loadBuffer(t);break;case"material":r=this._invokeOne((function(e){return e.loadMaterial&&e.loadMaterial(t)}));break;case"texture":r=this._invokeOne((function(e){return e.loadTexture&&e.loadTexture(t)}));break;case"skin":r=this.loadSkin(t);break;case"animation":r=this._invokeOne((function(e){return e.loadAnimation&&e.loadAnimation(t)}));break;case"camera":r=this.loadCamera(t);break;default:if(r=this._invokeOne((function(n){return n!=this&&n.getDependency&&n.getDependency(e,t)})),!r)throw new Error("Unknown type: "+e)}this.cache.add(n,r)}return r}getDependencies(e){let t=this.cache.get(e);if(!t){const n=this,r=this.json[e+("mesh"===e?"es":"s")]||[];t=Promise.all(r.map((function(t,r){return n.getDependency(e,r)}))),this.cache.add(e,t)}return t}loadBuffer(e){const t=this.json.buffers[e],n=this.fileLoader;if(t.type&&"arraybuffer"!==t.type)throw new Error("THREE.GLTFLoader: "+t.type+" buffer type is not supported.");if(void 0===t.uri&&0===e)return Promise.resolve(this.extensions[at.KHR_BINARY_GLTF].body);const i=this.options;return new Promise((function(e,s){n.load(r.LoaderUtils.resolveURL(t.uri,i.path),e,void 0,(function(){s(new Error('THREE.GLTFLoader: Failed to load buffer "'+t.uri+'".'))}))}))}loadBufferView(e){const t=this.json.bufferViews[e];return this.getDependency("buffer",t.buffer).then((function(e){const n=t.byteLength||0,r=t.byteOffset||0;return e.slice(r,r+n)}))}loadAccessor(e){const t=this,n=this.json,i=this.json.accessors[e];if(void 0===i.bufferView&&void 0===i.sparse){const e=Vt[i.type],t=Ft[i.componentType],n=!0===i.normalized,s=new t(i.count*e);return Promise.resolve(new r.BufferAttribute(s,e,n))}const s=[];return void 0!==i.bufferView?s.push(this.getDependency("bufferView",i.bufferView)):s.push(null),void 0!==i.sparse&&(s.push(this.getDependency("bufferView",i.sparse.indices.bufferView)),s.push(this.getDependency("bufferView",i.sparse.values.bufferView))),Promise.all(s).then((function(e){const s=e[0],a=Vt[i.type],o=Ft[i.componentType],l=o.BYTES_PER_ELEMENT,c=l*a,u=i.byteOffset||0,h=void 0!==i.bufferView?n.bufferViews[i.bufferView].byteStride:void 0,d=!0===i.normalized;let p,m;if(h&&h!==c){const e=Math.floor(u/h),n="InterleavedBuffer:"+i.bufferView+":"+i.componentType+":"+e+":"+i.count;let c=t.cache.get(n);c||(p=new o(s,e*h,i.count*h/l),c=new r.InterleavedBuffer(p,h/l),t.cache.add(n,c)),m=new r.InterleavedBufferAttribute(c,a,u%h/l,d)}else p=null===s?new o(i.count*a):new o(s,u,i.count*a),m=new r.BufferAttribute(p,a,d);if(void 0!==i.sparse){const t=Vt.SCALAR,n=Ft[i.sparse.indices.componentType],l=i.sparse.indices.byteOffset||0,c=i.sparse.values.byteOffset||0,u=new n(e[1],l,i.sparse.count*t),h=new o(e[2],c,i.sparse.count*a);null!==s&&(m=new r.BufferAttribute(m.array.slice(),m.itemSize,m.normalized)),m.normalized=!1;for(let e=0,r=u.length;e<r;e++){const t=u[e];if(m.setX(t,h[e*a]),a>=2&&m.setY(t,h[e*a+1]),a>=3&&m.setZ(t,h[e*a+2]),a>=4&&m.setW(t,h[e*a+3]),a>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}m.normalized=d}return m}))}loadTexture(e){const t=this.json,n=this.options,r=t.textures[e].source,i=t.images[r];let s=this.textureLoader;if(i.uri){const e=n.manager.getHandler(i.uri);null!==e&&(s=e)}return this.loadTextureImage(e,r,s)}loadTextureImage(e,t,n){const i=this,s=this.json,a=s.textures[e],o=s.images[t],l=(o.uri||o.bufferView)+":"+a.sampler;if(this.textureCache[l])return this.textureCache[l];const c=this.loadImageSource(t,n).then((function(t){t.flipY=!1,t.name=a.name||o.name||"",""===t.name&&"string"==typeof o.uri&&!1===o.uri.startsWith("data:image/")&&(t.name=o.uri);const n=(s.samplers||{})[a.sampler]||{};return t.magFilter=zt[n.magFilter]||r.LinearFilter,t.minFilter=zt[n.minFilter]||r.LinearMipmapLinearFilter,t.wrapS=Bt[n.wrapS]||r.RepeatWrapping,t.wrapT=Bt[n.wrapT]||r.RepeatWrapping,t.generateMipmaps=!t.isCompressedTexture&&t.minFilter!==r.NearestFilter&&t.minFilter!==r.LinearFilter,i.associations.set(t,{textures:e}),t})).catch((function(){return null}));return this.textureCache[l]=c,c}loadImageSource(e,t){const n=this,i=this.json,s=this.options;if(void 0!==this.sourceCache[e])return this.sourceCache[e].then((e=>e.clone()));const a=i.images[e],o=self.URL||self.webkitURL;let l=a.uri||"",c=!1;if(void 0!==a.bufferView)l=n.getDependency("bufferView",a.bufferView).then((function(e){c=!0;const t=new Blob([e],{type:a.mimeType});return l=o.createObjectURL(t),l}));else if(void 0===a.uri)throw new Error("THREE.GLTFLoader: Image "+e+" is missing URI and bufferView");const u=Promise.resolve(l).then((function(e){return new Promise((function(n,i){let a=n;!0===t.isImageBitmapLoader&&(a=function(e){const t=new r.Texture(e);t.needsUpdate=!0,n(t)}),t.load(r.LoaderUtils.resolveURL(e,s.path),a,void 0,i)}))})).then((function(e){var t;return!0===c&&o.revokeObjectURL(l),Wt(e,a),e.userData.mimeType=a.mimeType||((t=a.uri).search(/\.jpe?g($|\?)/i)>0||0===t.search(/^data\:image\/jpeg/)?"image/jpeg":t.search(/\.webp($|\?)/i)>0||0===t.search(/^data\:image\/webp/)?"image/webp":t.search(/\.ktx2($|\?)/i)>0||0===t.search(/^data\:image\/ktx2/)?"image/ktx2":"image/png"),e})).catch((function(e){throw e}));return this.sourceCache[e]=u,u}assignTexture(e,t,n,r){const i=this;return this.getDependency("texture",n.index).then((function(s){if(!s)return null;if(void 0!==n.texCoord&&n.texCoord>0&&((s=s.clone()).channel=n.texCoord),i.extensions[at.KHR_TEXTURE_TRANSFORM]){const e=void 0!==n.extensions?n.extensions[at.KHR_TEXTURE_TRANSFORM]:void 0;if(e){const t=i.associations.get(s);s=i.extensions[at.KHR_TEXTURE_TRANSFORM].extendTexture(s,e),i.associations.set(s,t)}}return void 0!==r&&(s.colorSpace=r),e[t]=s,s}))}assignFinalMaterial(e){const t=e.geometry;let n=e.material;const i=void 0===t.attributes.tangent,s=void 0!==t.attributes.color,a=void 0===t.attributes.normal;if(e.isPoints){const e="PointsMaterial:"+n.uuid;let t=this.cache.get(e);t||(t=new r.PointsMaterial,r.Material.prototype.copy.call(t,n),t.color.copy(n.color),t.map=n.map,t.sizeAttenuation=!1,this.cache.add(e,t)),n=t}else if(e.isLine){const e="LineBasicMaterial:"+n.uuid;let t=this.cache.get(e);t||(t=new r.LineBasicMaterial,r.Material.prototype.copy.call(t,n),t.color.copy(n.color),t.map=n.map,this.cache.add(e,t)),n=t}if(i||s||a){let e="ClonedMaterial:"+n.uuid+":";i&&(e+="derivative-tangents:"),s&&(e+="vertex-colors:"),a&&(e+="flat-shading:");let t=this.cache.get(e);t||(t=n.clone(),s&&(t.vertexColors=!0),a&&(t.flatShading=!0),i&&(t.normalScale&&(t.normalScale.y*=-1),t.clearcoatNormalScale&&(t.clearcoatNormalScale.y*=-1)),this.cache.add(e,t),this.associations.set(t,this.associations.get(n))),n=t}e.material=n}getMaterialType(){return r.MeshStandardMaterial}loadMaterial(e){const t=this,n=this.json,i=this.extensions,s=n.materials[e];let a;const o={},l=[];if((s.extensions||{})[at.KHR_MATERIALS_UNLIT]){const e=i[at.KHR_MATERIALS_UNLIT];a=e.getMaterialType(),l.push(e.extendParams(o,s,t))}else{const n=s.pbrMetallicRoughness||{};if(o.color=new r.Color(1,1,1),o.opacity=1,Array.isArray(n.baseColorFactor)){const e=n.baseColorFactor;o.color.setRGB(e[0],e[1],e[2],r.LinearSRGBColorSpace),o.opacity=e[3]}void 0!==n.baseColorTexture&&l.push(t.assignTexture(o,"map",n.baseColorTexture,r.SRGBColorSpace)),o.metalness=void 0!==n.metallicFactor?n.metallicFactor:1,o.roughness=void 0!==n.roughnessFactor?n.roughnessFactor:1,void 0!==n.metallicRoughnessTexture&&(l.push(t.assignTexture(o,"metalnessMap",n.metallicRoughnessTexture)),l.push(t.assignTexture(o,"roughnessMap",n.metallicRoughnessTexture))),a=this._invokeOne((function(t){return t.getMaterialType&&t.getMaterialType(e)})),l.push(Promise.all(this._invokeAll((function(t){return t.extendMaterialParams&&t.extendMaterialParams(e,o)}))))}!0===s.doubleSided&&(o.side=r.DoubleSide);const c=s.alphaMode||Gt;if(c===Ht?(o.transparent=!0,o.depthWrite=!1):(o.transparent=!1,c===qt&&(o.alphaTest=void 0!==s.alphaCutoff?s.alphaCutoff:.5)),void 0!==s.normalTexture&&a!==r.MeshBasicMaterial&&(l.push(t.assignTexture(o,"normalMap",s.normalTexture)),o.normalScale=new r.Vector2(1,1),void 0!==s.normalTexture.scale)){const e=s.normalTexture.scale;o.normalScale.set(e,e)}if(void 0!==s.occlusionTexture&&a!==r.MeshBasicMaterial&&(l.push(t.assignTexture(o,"aoMap",s.occlusionTexture)),void 0!==s.occlusionTexture.strength&&(o.aoMapIntensity=s.occlusionTexture.strength)),void 0!==s.emissiveFactor&&a!==r.MeshBasicMaterial){const e=s.emissiveFactor;o.emissive=(new r.Color).setRGB(e[0],e[1],e[2],r.LinearSRGBColorSpace)}return void 0!==s.emissiveTexture&&a!==r.MeshBasicMaterial&&l.push(t.assignTexture(o,"emissiveMap",s.emissiveTexture,r.SRGBColorSpace)),Promise.all(l).then((function(){const n=new a(o);return s.name&&(n.name=s.name),Wt(n,s),t.associations.set(n,{materials:e}),s.extensions&&jt(i,n,s),n}))}createUniqueName(e){const t=r.PropertyBinding.sanitizeNodeName(e||"");return t in this.nodeNamesUsed?t+"_"+ ++this.nodeNamesUsed[t]:(this.nodeNamesUsed[t]=0,t)}loadGeometries(e){const t=this,n=this.extensions,i=this.primitiveCache;function s(e){return n[at.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(e,t).then((function(n){return en(n,e,t)}))}const a=[];for(let o=0,l=e.length;o<l;o++){const n=e[o],l=Yt(n),c=i[l];if(c)a.push(c.promise);else{let e;e=n.extensions&&n.extensions[at.KHR_DRACO_MESH_COMPRESSION]?s(n):en(new r.BufferGeometry,n,t),i[l]={primitive:n,promise:e},a.push(e)}}return Promise.all(a)}loadMesh(e){const t=this,n=this.json,i=this.extensions,s=n.meshes[e],a=s.primitives,o=[];for(let c=0,u=a.length;c<u;c++){const e=void 0===a[c].material?(void 0===(l=this.cache).DefaultMaterial&&(l.DefaultMaterial=new r.MeshStandardMaterial({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:r.FrontSide})),l.DefaultMaterial):this.getDependency("material",a[c].material);o.push(e)}var l;return o.push(t.loadGeometries(a)),Promise.all(o).then((function(n){const o=n.slice(0,n.length-1),l=n[n.length-1],c=[];for(let h=0,d=l.length;h<d;h++){const n=l[h],u=a[h];let d;const p=o[h];if(u.mode===Ut.TRIANGLES||u.mode===Ut.TRIANGLE_STRIP||u.mode===Ut.TRIANGLE_FAN||void 0===u.mode)d=!0===s.isSkinnedMesh?new r.SkinnedMesh(n,p):new r.Mesh(n,p),!0===d.isSkinnedMesh&&d.normalizeSkinWeights(),u.mode===Ut.TRIANGLE_STRIP?d.geometry=Xe(d.geometry,r.TriangleStripDrawMode):u.mode===Ut.TRIANGLE_FAN&&(d.geometry=Xe(d.geometry,r.TriangleFanDrawMode));else if(u.mode===Ut.LINES)d=new r.LineSegments(n,p);else if(u.mode===Ut.LINE_STRIP)d=new r.Line(n,p);else if(u.mode===Ut.LINE_LOOP)d=new r.LineLoop(n,p);else{if(u.mode!==Ut.POINTS)throw new Error("THREE.GLTFLoader: Primitive mode unsupported: "+u.mode);d=new r.Points(n,p)}Object.keys(d.geometry.morphAttributes).length>0&&Xt(d,s),d.name=t.createUniqueName(s.name||"mesh_"+e),Wt(d,s),u.extensions&&jt(i,d,u),t.assignFinalMaterial(d),c.push(d)}for(let r=0,i=c.length;r<i;r++)t.associations.set(c[r],{meshes:e,primitives:r});if(1===c.length)return s.extensions&&jt(i,c[0],s),c[0];const u=new r.Group;s.extensions&&jt(i,u,s),t.associations.set(u,{meshes:e});for(let e=0,t=c.length;e<t;e++)u.add(c[e]);return u}))}loadCamera(e){let t;const n=this.json.cameras[e],i=n[n.type];if(i)return"perspective"===n.type?t=new r.PerspectiveCamera(r.MathUtils.radToDeg(i.yfov),i.aspectRatio||1,i.znear||1,i.zfar||2e6):"orthographic"===n.type&&(t=new r.OrthographicCamera(-i.xmag,i.xmag,i.ymag,-i.ymag,i.znear,i.zfar)),n.name&&(t.name=this.createUniqueName(n.name)),Wt(t,n),Promise.resolve(t)}loadSkin(e){const t=this.json.skins[e],n=[];for(let r=0,i=t.joints.length;r<i;r++)n.push(this._loadNodeShallow(t.joints[r]));return void 0!==t.inverseBindMatrices?n.push(this.getDependency("accessor",t.inverseBindMatrices)):n.push(null),Promise.all(n).then((function(e){const t=e.pop(),n=e,i=[],s=[];for(let a=0,o=n.length;a<o;a++){const e=n[a];if(e){i.push(e);const n=new r.Matrix4;null!==t&&n.fromArray(t.array,16*a),s.push(n)}}return new r.Skeleton(i,s)}))}loadAnimation(e){const t=this.json,n=this,i=t.animations[e],s=i.name?i.name:"animation_"+e,a=[],o=[],l=[],c=[],u=[];for(let r=0,h=i.channels.length;r<h;r++){const e=i.channels[r],t=i.samplers[e.sampler],n=e.target,s=n.node,h=void 0!==i.parameters?i.parameters[t.input]:t.input,d=void 0!==i.parameters?i.parameters[t.output]:t.output;void 0!==n.node&&(a.push(this.getDependency("node",s)),o.push(this.getDependency("accessor",h)),l.push(this.getDependency("accessor",d)),c.push(t),u.push(n))}return Promise.all([Promise.all(a),Promise.all(o),Promise.all(l),Promise.all(c),Promise.all(u)]).then((function(e){const t=e[0],a=e[1],o=e[2],l=e[3],c=e[4],u=[];for(let r=0,i=t.length;r<i;r++){const e=t[r],i=a[r],s=o[r],h=l[r],d=c[r];if(void 0===e)continue;e.updateMatrix&&e.updateMatrix();const p=n._createAnimationTracks(e,i,s,h,d);if(p)for(let t=0;t<p.length;t++)u.push(p[t])}const h=new r.AnimationClip(s,void 0,u);return Wt(h,i),h}))}createNodeMesh(e){const t=this.json,n=this,r=t.nodes[e];return void 0===r.mesh?null:n.getDependency("mesh",r.mesh).then((function(e){const t=n._getNodeRef(n.meshCache,r.mesh,e);return void 0!==r.weights&&t.traverse((function(e){if(e.isMesh)for(let t=0,n=r.weights.length;t<n;t++)e.morphTargetInfluences[t]=r.weights[t]})),t}))}loadNode(e){const t=this,n=this.json.nodes[e],i=t._loadNodeShallow(e),s=[],a=n.children||[];for(let r=0,l=a.length;r<l;r++)s.push(t.getDependency("node",a[r]));const o=void 0===n.skin?Promise.resolve(null):t.getDependency("skin",n.skin);return Promise.all([i,Promise.all(s),o]).then((function(e){const t=e[0],n=e[1],i=e[2];null!==i&&t.traverse((function(e){e.isSkinnedMesh&&e.bind(i,Zt)}));for(let r=0,s=n.length;r<s;r++)t.add(n[r]);if(void 0!==t.userData.pivot&&n.length>0){const e=t.userData.pivot,i=n[0];t.pivot=(new r.Vector3).fromArray(e),t.position.x-=e[0],t.position.y-=e[1],t.position.z-=e[2],i.position.set(0,0,0),delete t.userData.pivot}return t}))}_loadNodeShallow(e){const t=this.json,n=this.extensions,i=this;if(void 0!==this.nodeCache[e])return this.nodeCache[e];const s=t.nodes[e],a=s.name?i.createUniqueName(s.name):"",o=[],l=i._invokeOne((function(t){return t.createNodeMesh&&t.createNodeMesh(e)}));return l&&o.push(l),void 0!==s.camera&&o.push(i.getDependency("camera",s.camera).then((function(e){return i._getNodeRef(i.cameraCache,s.camera,e)}))),i._invokeAll((function(t){return t.createNodeAttachment&&t.createNodeAttachment(e)})).forEach((function(e){o.push(e)})),this.nodeCache[e]=Promise.all(o).then((function(t){let o;if(o=!0===s.isBone?new r.Bone:t.length>1?new r.Group:1===t.length?t[0]:new r.Object3D,o!==t[0])for(let e=0,n=t.length;e<n;e++)o.add(t[e]);if(s.name&&(o.userData.name=s.name,o.name=a),Wt(o,s),s.extensions&&jt(n,o,s),void 0!==s.matrix){const e=new r.Matrix4;e.fromArray(s.matrix),o.applyMatrix4(e)}else void 0!==s.translation&&o.position.fromArray(s.translation),void 0!==s.rotation&&o.quaternion.fromArray(s.rotation),void 0!==s.scale&&o.scale.fromArray(s.scale);if(i.associations.has(o)){if(void 0!==s.mesh&&i.meshCache.refs[s.mesh]>1){const e=i.associations.get(o);i.associations.set(o,{...e})}}else i.associations.set(o,{});return i.associations.get(o).nodes=e,o})),this.nodeCache[e]}loadScene(e){const t=this.extensions,n=this.json.scenes[e],i=this,s=new r.Group;n.name&&(s.name=i.createUniqueName(n.name)),Wt(s,n),n.extensions&&jt(t,s,n);const a=n.nodes||[],o=[];for(let r=0,l=a.length;r<l;r++)o.push(i.getDependency("node",a[r]));return Promise.all(o).then((function(e){for(let t=0,n=e.length;t<n;t++){const n=e[t];null!==n.parent?s.add(tt(n)):s.add(n)}return i.associations=(e=>{const t=new Map;for(const[n,s]of i.associations)(n instanceof r.Material||n instanceof r.Texture)&&t.set(n,s);return e.traverse((e=>{const n=i.associations.get(e);null!=n&&t.set(e,n)})),t})(s),s}))}_createAnimationTracks(e,t,n,i,s){const a=[],o=e.name?e.name:e.uuid,l=[];function c(e){e.morphTargetInfluences&&l.push(e.name?e.name:e.uuid)}let u;switch(Nt[s.path]===Nt.weights?(c(e),e.isGroup&&e.children.forEach(c)):l.push(o),Nt[s.path]){case Nt.weights:u=r.NumberKeyframeTrack;break;case Nt.rotation:u=r.QuaternionKeyframeTrack;break;case Nt.translation:case Nt.scale:u=r.VectorKeyframeTrack;break;default:if(1===n.itemSize)u=r.NumberKeyframeTrack;else u=r.VectorKeyframeTrack}const h=void 0!==i.interpolation?$t[i.interpolation]:r.InterpolateLinear,d=this._getArrayFromAccessor(n);for(let r=0,p=l.length;r<p;r++){const e=new u(l[r]+"."+Nt[s.path],t.array,d,h);"CUBICSPLINE"===i.interpolation&&this._createCubicSplineTrackInterpolant(e),a.push(e)}return a}_getArrayFromAccessor(e){let t=e.array;if(e.normalized){const e=Qt(t.constructor),n=new Float32Array(t.length);for(let r=0,i=t.length;r<i;r++)n[r]=t[r]*e;t=n}return t}_createCubicSplineTrackInterpolant(e){e.createInterpolant=function(e){return new(this instanceof r.QuaternionKeyframeTrack?Lt:It)(this.times,this.values,this.getValueSize()/3,e)},e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}}function en(e,t,n){const i=t.attributes,s=[];function a(t,r){return n.getDependency("accessor",t).then((function(t){e.setAttribute(r,t)}))}for(const r in i){const t=Ot[r]||r.toLowerCase();t in e.attributes||s.push(a(i[r],t))}if(void 0!==t.indices&&!e.index){const r=n.getDependency("accessor",t.indices).then((function(t){e.setIndex(t)}));s.push(r)}return r.ColorManagement.workingColorSpace,r.LinearSRGBColorSpace,Wt(e,t),function(e,t,n){const i=t.attributes,s=new r.Box3;if(void 0===i.POSITION)return;{const e=n.json.accessors[i.POSITION],t=e.min,a=e.max;if(void 0===t||void 0===a)return;if(s.set(new r.Vector3(t[0],t[1],t[2]),new r.Vector3(a[0],a[1],a[2])),e.normalized){const t=Qt(Ft[e.componentType]);s.min.multiplyScalar(t),s.max.multiplyScalar(t)}}const a=t.targets;if(void 0!==a){const e=new r.Vector3,t=new r.Vector3;for(let r=0,i=a.length;r<i;r++){const i=a[r];if(void 0!==i.POSITION){const r=n.json.accessors[i.POSITION],s=r.min,a=r.max;if(void 0!==s&&void 0!==a){if(t.setX(Math.max(Math.abs(s[0]),Math.abs(a[0]))),t.setY(Math.max(Math.abs(s[1]),Math.abs(a[1]))),t.setZ(Math.max(Math.abs(s[2]),Math.abs(a[2]))),r.normalized){const e=Qt(Ft[r.componentType]);t.multiplyScalar(e)}e.max(t)}}}s.expandByVector(e)}e.boundingBox=s;const o=new r.Sphere;s.getCenter(o.center),o.radius=s.min.distanceTo(s.max)/2,e.boundingSphere=o}(e,t,n),Promise.all(s).then((function(){return void 0!==t.targets?function(e,t,n){let r=!1,i=!1,s=!1;for(let c=0,u=t.length;c<u;c++){const e=t[c];if(void 0!==e.POSITION&&(r=!0),void 0!==e.NORMAL&&(i=!0),void 0!==e.COLOR_0&&(s=!0),r&&i&&s)break}if(!r&&!i&&!s)return Promise.resolve(e);const a=[],o=[],l=[];for(let c=0,u=t.length;c<u;c++){const u=t[c];if(r){const t=void 0!==u.POSITION?n.getDependency("accessor",u.POSITION):e.attributes.position;a.push(t)}if(i){const t=void 0!==u.NORMAL?n.getDependency("accessor",u.NORMAL):e.attributes.normal;o.push(t)}if(s){const t=void 0!==u.COLOR_0?n.getDependency("accessor",u.COLOR_0):e.attributes.color;l.push(t)}}return Promise.all([Promise.all(a),Promise.all(o),Promise.all(l)]).then((function(t){const n=t[0],a=t[1],o=t[2];return r&&(e.morphAttributes.position=n),i&&(e.morphAttributes.normal=a),s&&(e.morphAttributes.color=o),e.morphTargetsRelative=!0,e}))}(e,t.targets,n):e}))}class tn extends r.DataTextureLoader{constructor(e){super(e),this.type=r.HalfFloatType}parse(e){const t=function(e,t){switch(e){case 1:throw new Error("THREE.HDRLoader: Read Error: "+(t||""));case 2:throw new Error("THREE.HDRLoader: Write Error: "+(t||""));case 3:throw new Error("THREE.HDRLoader: Bad File Format: "+(t||""));default:throw new Error("THREE.HDRLoader: Memory Error: "+(t||""))}},n=function(e,t,n){t=t||1024;let r=e.pos,i=-1,s=0,a="",o=String.fromCharCode.apply(null,new Uint16Array(e.subarray(r,r+128)));for(;0>(i=o.indexOf("\n"))&&s<t&&r<e.byteLength;)a+=o,s+=o.length,r+=128,o=String.fromCharCode.apply(null,new Uint16Array(e.subarray(r,r+128)));return-1<i&&(e.pos+=s+i+1,a+o.slice(0,i))},i=function(e,t,n,r){const i=e[t+3],s=Math.pow(2,i-128)/255;n[r+0]=e[t+0]*s,n[r+1]=e[t+1]*s,n[r+2]=e[t+2]*s,n[r+3]=1},s=function(e,t,n,i){const s=e[t+3],a=Math.pow(2,s-128)/255;n[i+0]=r.DataUtils.toHalfFloat(Math.min(e[t+0]*a,65504)),n[i+1]=r.DataUtils.toHalfFloat(Math.min(e[t+1]*a,65504)),n[i+2]=r.DataUtils.toHalfFloat(Math.min(e[t+2]*a,65504)),n[i+3]=r.DataUtils.toHalfFloat(1)},a=new Uint8Array(e);a.pos=0;const o=function(e){const r=/^\s*GAMMA\s*=\s*(\d+(\.\d+)?)\s*$/,i=/^\s*EXPOSURE\s*=\s*(\d+(\.\d+)?)\s*$/,s=/^\s*FORMAT=(\S+)\s*$/,a=/^\s*\-Y\s+(\d+)\s+\+X\s+(\d+)\s*$/,o={valid:0,string:"",comments:"",programtype:"RGBE",format:"",gamma:1,exposure:1,width:0,height:0};let l,c;for((e.pos>=e.byteLength||!(l=n(e)))&&t(1,"no header found"),(c=l.match(/^#\?(\S+)/))||t(3,"bad initial token"),o.valid|=1,o.programtype=c[1],o.string+=l+"\n";l=n(e),!1!==l;)if(o.string+=l+"\n","#"!==l.charAt(0)){if((c=l.match(r))&&(o.gamma=parseFloat(c[1])),(c=l.match(i))&&(o.exposure=parseFloat(c[1])),(c=l.match(s))&&(o.valid|=2,o.format=c[1]),(c=l.match(a))&&(o.valid|=4,o.height=parseInt(c[1],10),o.width=parseInt(c[2],10)),2&o.valid&&4&o.valid)break}else o.comments+=l+"\n";return 2&o.valid||t(3,"missing format specifier"),4&o.valid||t(3,"missing image size specifier"),o}(a),l=o.width,c=o.height,u=function(e,n,r){const i=n;if(i<8||i>32767||2!==e[0]||2!==e[1]||128&e[2])return new Uint8Array(e);i!==(e[2]<<8|e[3])&&t(3,"wrong scanline width");const s=new Uint8Array(4*n*r);s.length||t(4,"unable to allocate buffer space");let a=0,o=0;const l=4*i,c=new Uint8Array(4),u=new Uint8Array(l);let h=r;for(;h>0&&o<e.byteLength;){o+4>e.byteLength&&t(1),c[0]=e[o++],c[1]=e[o++],c[2]=e[o++],c[3]=e[o++],2==c[0]&&2==c[1]&&(c[2]<<8|c[3])==i||t(3,"bad rgbe scanline format");let n,r=0;for(;r<l&&o<e.byteLength;){n=e[o++];const i=n>128;if(i&&(n-=128),(0===n||r+n>l)&&t(3,"bad scanline data"),i){const t=e[o++];for(let e=0;e<n;e++)u[r++]=t}else u.set(e.subarray(o,o+n),r),r+=n,o+=n}const d=i;for(let e=0;e<d;e++){let t=0;s[a]=u[e+t],t+=i,s[a+1]=u[e+t],t+=i,s[a+2]=u[e+t],t+=i,s[a+3]=u[e+t],a+=4}h--}return s}(a.subarray(a.pos),l,c);let h,d,p;switch(this.type){case r.FloatType:p=u.length/4;const e=new Float32Array(4*p);for(let n=0;n<p;n++)i(u,4*n,e,4*n);h=e,d=r.FloatType;break;case r.HalfFloatType:p=u.length/4;const t=new Uint16Array(4*p);for(let n=0;n<p;n++)s(u,4*n,t,4*n);h=t,d=r.HalfFloatType;break;default:throw new Error("THREE.HDRLoader: Unsupported type: "+this.type)}return{width:l,height:c,data:h,header:o.string,gamma:o.gamma,exposure:o.exposure,type:d,colorSpace:r.LinearSRGBColorSpace,minFilter:r.LinearFilter,magFilter:r.LinearFilter,generateMipmaps:!1,flipY:!0}}setDataType(e){return this.type=e,this}}let nn,rn,sn,an=class{constructor(e=4){this.pool=e,this.queue=[],this.workers=[],this.workersResolve=[],this.workerStatus=0,this.workerCreator=null}_initWorker(e){if(!this.workers[e]){const t=this.workerCreator();t.addEventListener("message",this._onMessage.bind(this,e)),this.workers[e]=t}}_getIdleWorker(){for(let e=0;e<this.pool;e++)if(!(this.workerStatus&1<<e))return e;return-1}_onMessage(e,t){const n=this.workersResolve[e];if(n&&n(t),this.queue.length){const{resolve:t,msg:n,transfer:r}=this.queue.shift();this.workersResolve[e]=t,this.workers[e].postMessage(n,r)}else this.workerStatus^=1<<e}setWorkerCreator(e){this.workerCreator=e}setWorkerLimit(e){this.pool=e}postMessage(e,t){return new Promise((n=>{const r=this._getIdleWorker();-1!==r?(this._initWorker(r),this.workerStatus|=1<<r,this.workersResolve[r]=n,this.workers[r].postMessage(e,t)):this.queue.push({resolve:n,msg:e,transfer:t})}))}dispose(){this.workers.forEach((e=>e.terminate())),this.workersResolve.length=0,this.workers.length=0,this.queue.length=0,this.workerStatus=0}};const on={env:{emscripten_notify_memory_growth:function(e){sn=new Uint8Array(rn.exports.memory.buffer)}}};let ln=class{init(){return nn||(nn="undefined"!=typeof fetch?fetch("undefined"==typeof document?require("url").pathToFileURL(__dirname+"/assets/viewer/zstd-decoder-67d12d34f82e.wasm").href:new URL("assets/viewer/zstd-decoder-67d12d34f82e.wasm",document.currentScript&&"SCRIPT"===document.currentScript.tagName.toUpperCase()&&document.currentScript.src||document.baseURI).href).then((e=>e.arrayBuffer())).then((e=>WebAssembly.instantiate(e,on))).then(this._init):fetch("undefined"==typeof document?require("url").pathToFileURL(__dirname+"/assets/viewer/zstd-decoder-67d12d34f82e.wasm").href:new URL("assets/viewer/zstd-decoder-67d12d34f82e.wasm",document.currentScript&&"SCRIPT"===document.currentScript.tagName.toUpperCase()&&document.currentScript.src||document.baseURI).href).then((e=>e.arrayBuffer())).then((e=>WebAssembly.instantiate(e,on))).then(this._init),nn)}_init(e){rn=e.instance,on.env.emscripten_notify_memory_growth(0)}decode(e,t=0){if(!rn)throw new Error("ZSTDDecoder: Await .init() before decoding.");const n=e.byteLength,r=rn.exports.malloc(n);sn.set(e,r),t=t||Number(rn.exports.ZSTD_findDecompressedSize(r,n));const i=rn.exports.malloc(t),s=rn.exports.ZSTD_decompress(i,t,r,n),a=sn.slice(i,i+s);return rn.exports.free(r),rn.exports.free(i),a}};r.ColorManagement.spaces[r.SRGBColorSpace];const cn="undefined"==typeof document?require("url").pathToFileURL(__dirname+"/assets/viewer/basis-transcoder-6cf17dc88935.wasm").href:new URL("assets/viewer/basis-transcoder-6cf17dc88935.wasm",document.currentScript&&"SCRIPT"===document.currentScript.tagName.toUpperCase()&&document.currentScript.src||document.baseURI).href,un="undefined"==typeof document?require("url").pathToFileURL(__dirname+"/assets/viewer/basis-transcoder-8478b5b6d6b7.js").href:new URL("assets/viewer/basis-transcoder-8478b5b6d6b7.js",document.currentScript&&"SCRIPT"===document.currentScript.tagName.toUpperCase()&&document.currentScript.src||document.baseURI).href,hn=new WeakMap;let dn;class pn extends r.Loader{constructor(e){super(e),this.transcoderPath="",this.transcoderBinary=null,this.transcoderPending=null,this.workerPool=new an,this.workerSourceURL="",this.workerConfig=null}setTranscoderPath(e){return this.transcoderPath=e,this}setWorkerLimit(e){return this.workerPool.setWorkerLimit(e),this}async detectSupportAsync(e){return await e.init(),this.detectSupport(e)}detectSupport(e){return!0===e.isWebGPURenderer?this.workerConfig={astcSupported:e.hasFeature("texture-compression-astc"),astcHDRSupported:!1,etc1Supported:e.hasFeature("texture-compression-etc1"),etc2Supported:e.hasFeature("texture-compression-etc2"),dxtSupported:e.hasFeature("texture-compression-s3tc"),bptcSupported:e.hasFeature("texture-compression-bc"),pvrtcSupported:e.hasFeature("texture-compression-pvrtc")}:(this.workerConfig={astcSupported:e.extensions.has("WEBGL_compressed_texture_astc"),astcHDRSupported:e.extensions.has("WEBGL_compressed_texture_astc")&&e.extensions.get("WEBGL_compressed_texture_astc").getSupportedProfiles().includes("hdr"),etc1Supported:e.extensions.has("WEBGL_compressed_texture_etc1"),etc2Supported:e.extensions.has("WEBGL_compressed_texture_etc"),dxtSupported:e.extensions.has("WEBGL_compressed_texture_s3tc"),bptcSupported:e.extensions.has("EXT_texture_compression_bptc"),pvrtcSupported:e.extensions.has("WEBGL_compressed_texture_pvrtc")||e.extensions.has("WEBKIT_WEBGL_compressed_texture_pvrtc")},"undefined"!=typeof navigator&&void 0!==navigator.platform&&void 0!==navigator.userAgent&&navigator.platform.indexOf("Linux")>=0&&navigator.userAgent.indexOf("Android")<0&&this.workerConfig.astcSupported&&this.workerConfig.etc2Supported&&this.workerConfig.bptcSupported&&this.workerConfig.dxtSupported&&(this.workerConfig.astcSupported=!1,this.workerConfig.etc1Supported=!1,this.workerConfig.etc2Supported=!1)),this}init(){if(!this.transcoderPending){const e=new r.FileLoader(this.manager);e.setWithCredentials(this.withCredentials);const t=new r.FileLoader(this.manager);let n,i;t.setWithCredentials(this.withCredentials),t.setResponseType("arraybuffer"),""===this.transcoderPath?(n=e.loadAsync(un),i=t.loadAsync(cn)):(e.setPath(this.transcoderPath),n=e.loadAsync("basis_transcoder.js"),t.setPath(this.transcoderPath),i=t.loadAsync("basis_transcoder.wasm")),this.transcoderPending=Promise.all([n,i]).then((([e,t])=>{const n=pn.BasisWorker.toString(),r=["/* constants */","let _EngineFormat = "+JSON.stringify(pn.EngineFormat),"let _EngineType = "+JSON.stringify(pn.EngineType),"let _TranscoderFormat = "+JSON.stringify(pn.TranscoderFormat),"let _BasisFormat = "+JSON.stringify(pn.BasisFormat),"/* basis_transcoder.js */",e,"/* worker */",n.substring(n.indexOf("{")+1,n.lastIndexOf("}"))].join("\n");this.workerSourceURL=URL.createObjectURL(new Blob([r])),this.transcoderBinary=t,this.workerPool.setWorkerCreator((()=>{const e=new Worker(this.workerSourceURL),t=this.transcoderBinary.slice(0);return e.postMessage({type:"init",config:this.workerConfig,transcoderBinary:t},[t]),e}))}))}return this.transcoderPending}load(e,t,n,i){if(null===this.workerConfig)throw new Error("THREE.KTX2Loader: Missing initialization with `.detectSupport( renderer )`.");const s=new r.FileLoader(this.manager);s.setPath(this.path),s.setCrossOrigin(this.crossOrigin),s.setWithCredentials(this.withCredentials),s.setRequestHeader(this.requestHeader),s.setResponseType("arraybuffer"),s.load(e,(e=>{this.parse(e,t,i)}),n,i)}parse(e,t,n){if(null===this.workerConfig)throw new Error("THREE.KTX2Loader: Missing initialization with `.detectSupport( renderer )`.");if(hn.has(e)){return hn.get(e).promise.then(t).catch(n)}this._createTexture(e).then((e=>t?t(e):null)).catch(n)}_createTextureFrom(e,t){const{type:n,error:i,data:{faces:s,width:a,height:o,format:l,type:c,dfdFlags:u}}=e;if("error"===n)return Promise.reject(i);let h;if(6===t.faceCount)h=new r.CompressedCubeTexture(s,l,c);else{const e=s[0].mipmaps;h=t.layerCount>1?new r.CompressedArrayTexture(e,a,o,t.layerCount,l,c):new r.CompressedTexture(e,a,o,l,c)}return h.minFilter=1===s[0].mipmaps.length?r.LinearFilter:r.LinearMipmapLinearFilter,h.magFilter=r.LinearFilter,h.generateMipmaps=!1,h.needsUpdate=!0,h.colorSpace=yn(t),h.premultiplyAlpha=!!(1&u),h}async _createTexture(e,t={}){const n=function(e){const t=new Uint8Array(e.buffer,e.byteOffset,je.length);if(t[0]!==je[0]||t[1]!==je[1]||t[2]!==je[2]||t[3]!==je[3]||t[4]!==je[4]||t[5]!==je[5]||t[6]!==je[6]||t[7]!==je[7]||t[8]!==je[8]||t[9]!==je[9]||t[10]!==je[10]||t[11]!==je[11])throw new Error("Missing KTX 2.0 identifier.");const n={vkFormat:0,typeSize:1,pixelWidth:0,pixelHeight:0,pixelDepth:0,layerCount:0,faceCount:1,levelCount:0,supercompressionScheme:0,levels:[],dataFormatDescriptor:[{vendorId:0,descriptorType:0,versionNumber:2,colorModel:0,colorPrimaries:1,transferFunction:2,flags:0,texelBlockDimension:[0,0,0,0],bytesPlane:[0,0,0,0,0,0,0,0],samples:[]}],keyValue:{},globalData:null},r=17*Uint32Array.BYTES_PER_ELEMENT,i=new He(e,je.length,r,!0);n.vkFormat=i._nextUint32(),n.typeSize=i._nextUint32(),n.pixelWidth=i._nextUint32(),n.pixelHeight=i._nextUint32(),n.pixelDepth=i._nextUint32(),n.layerCount=i._nextUint32(),n.faceCount=i._nextUint32(),n.levelCount=i._nextUint32(),n.supercompressionScheme=i._nextUint32();const s=i._nextUint32(),a=i._nextUint32(),o=i._nextUint32(),l=i._nextUint32(),c=i._nextUint64(),u=i._nextUint64(),h=3*Math.max(n.levelCount,1)*8,d=new He(e,je.length+r,h,!0);for(let z=0,B=Math.max(n.levelCount,1);z<B;z++)n.levels.push({levelData:new Uint8Array(e.buffer,e.byteOffset+d._nextUint64(),d._nextUint64()),uncompressedByteLength:d._nextUint64()});const p=new He(e,s,a,!0);p._skip(4);const m=p._nextUint16(),f=p._nextUint16(),g=p._nextUint16(),x=p._nextUint16(),y={vendorId:m,descriptorType:f,versionNumber:g,colorModel:p._nextUint8(),colorPrimaries:p._nextUint8(),transferFunction:p._nextUint8(),flags:p._nextUint8(),texelBlockDimension:[p._nextUint8(),p._nextUint8(),p._nextUint8(),p._nextUint8()],bytesPlane:[p._nextUint8(),p._nextUint8(),p._nextUint8(),p._nextUint8(),p._nextUint8(),p._nextUint8(),p._nextUint8(),p._nextUint8()],samples:[]},v=(x/4-6)/4;for(let z=0;z<v;z++){const e={bitOffset:p._nextUint16(),bitLength:p._nextUint8(),channelType:p._nextUint8(),samplePosition:[p._nextUint8(),p._nextUint8(),p._nextUint8(),p._nextUint8()],sampleLower:Number.NEGATIVE_INFINITY,sampleUpper:Number.POSITIVE_INFINITY};64&e.channelType?(e.sampleLower=p._nextInt32(),e.sampleUpper=p._nextInt32()):(e.sampleLower=p._nextUint32(),e.sampleUpper=p._nextUint32()),y.samples[z]=e}n.dataFormatDescriptor.length=0,n.dataFormatDescriptor.push(y);const b=new He(e,o,l,!0);for(;b._offset<l;){const e=b._nextUint32(),t=b._scan(e),r=We(t);if(n.keyValue[r]=b._nextUint8Array(e-t.byteLength-1),r.match(/^ktx/i)){const e=We(n.keyValue[r]);n.keyValue[r]=e.substring(0,e.lastIndexOf("\0"))}b._skip(e%4?4-e%4:0)}if(u<=0)return n;const w=new He(e,c,u,!0),T=w._nextUint16(),S=w._nextUint16(),_=w._nextUint32(),M=w._nextUint32(),A=w._nextUint32(),E=w._nextUint32(),C=[];for(let z=0,B=Math.max(n.levelCount,1);z<B;z++)C.push({imageFlags:w._nextUint32(),rgbSliceByteOffset:w._nextUint32(),rgbSliceByteLength:w._nextUint32(),alphaSliceByteOffset:w._nextUint32(),alphaSliceByteLength:w._nextUint32()});const R=c+w._offset,D=R+_,k=D+M,I=k+A,P=new Uint8Array(e.buffer,e.byteOffset+R,_),L=new Uint8Array(e.buffer,e.byteOffset+D,M),U=new Uint8Array(e.buffer,e.byteOffset+k,A),F=new Uint8Array(e.buffer,e.byteOffset+I,E);return n.globalData={endpointCount:T,selectorCount:S,imageDescs:C,endpointsData:P,selectorsData:L,tablesData:U,extendedData:F},n}(new Uint8Array(e)),i=n.vkFormat===Ge&&167===n.dataFormatDescriptor[0].colorModel;if(!(0===n.vkFormat||i&&!this.workerConfig.astcHDRSupported))return async function(e){const{vkFormat:t}=e;if(void 0===gn[t])throw new Error("THREE.KTX2Loader: Unsupported vkFormat: "+t);xn[t];let n;2===e.supercompressionScheme&&(dn||(dn=new Promise((async e=>{const t=new ln;await t.init(),e(t)}))),n=await dn);const i=[];for(let o=0;o<e.levels.length;o++){const s=Math.max(1,e.pixelWidth>>o),a=Math.max(1,e.pixelHeight>>o),l=e.pixelDepth?Math.max(1,e.pixelDepth>>o):0,c=e.levels[o];let u,h;if(0===e.supercompressionScheme)u=c.levelData;else{if(2!==e.supercompressionScheme)throw new Error("THREE.KTX2Loader: Unsupported supercompressionScheme.");u=n.decode(c.levelData,c.uncompressedByteLength)}h=xn[t]===r.FloatType?new Float32Array(u.buffer,u.byteOffset,u.byteLength/Float32Array.BYTES_PER_ELEMENT):xn[t]===r.HalfFloatType||xn[t]===r.UnsignedShortType?new Uint16Array(u.buffer,u.byteOffset,u.byteLength/Uint16Array.BYTES_PER_ELEMENT):xn[t]===r.UnsignedInt5999Type||xn[t]===r.UnsignedInt101111Type?new Uint32Array(u.buffer,u.byteOffset,u.byteLength/Uint32Array.BYTES_PER_ELEMENT):u,i.push({data:h,width:s,height:a,depth:l})}const s=0===e.levelCount||i.length>1;let a;if(mn.has(gn[t]))a=0===e.pixelDepth?new r.DataTexture(i[0].data,e.pixelWidth,e.pixelHeight):new r.Data3DTexture(i[0].data,e.pixelWidth,e.pixelHeight,e.pixelDepth),a.minFilter=s?r.NearestMipmapNearestFilter:r.NearestFilter,a.magFilter=r.NearestFilter,a.generateMipmaps=0===e.levelCount,a.normalized=fn.has(t);else{if(e.pixelDepth>0)throw new Error("THREE.KTX2Loader: Unsupported pixelDepth.");a=new r.CompressedTexture(i,e.pixelWidth,e.pixelHeight),a.minFilter=s?r.LinearMipmapLinearFilter:r.LinearFilter,a.magFilter=r.LinearFilter}return a.mipmaps=i,a.type=xn[t],a.format=gn[t],a.colorSpace=yn(e),a.needsUpdate=!0,Promise.resolve(a)}(n);const s=t,a=this.init().then((()=>this.workerPool.postMessage({type:"transcode",buffer:e,taskConfig:s},[e]))).then((e=>this._createTextureFrom(e.data,n)));return hn.set(e,{promise:a}),a}dispose(){this.workerPool.dispose(),this.workerSourceURL&&URL.revokeObjectURL(this.workerSourceURL)}}pn.BasisFormat={ETC1S:0,UASTC:1,UASTC_HDR:2},pn.TranscoderFormat={ETC1:0,ETC2:1,BC1:2,BC3:3,BC4:4,BC5:5,BC7_M6_OPAQUE_ONLY:6,BC7_M5:7,PVRTC1_4_RGB:8,PVRTC1_4_RGBA:9,ASTC_4x4:10,ATC_RGB:11,ATC_RGBA_INTERPOLATED_ALPHA:12,RGBA32:13,RGB565:14,BGR565:15,RGBA4444:16,BC6H:22,RGB_HALF:24,RGBA_HALF:25},pn.EngineFormat={RGBAFormat:r.RGBAFormat,RGBA_ASTC_4x4_Format:r.RGBA_ASTC_4x4_Format,RGB_BPTC_UNSIGNED_Format:r.RGB_BPTC_UNSIGNED_Format,RGBA_BPTC_Format:r.RGBA_BPTC_Format,RGBA_ETC2_EAC_Format:r.RGBA_ETC2_EAC_Format,RGBA_PVRTC_4BPPV1_Format:r.RGBA_PVRTC_4BPPV1_Format,RGBA_S3TC_DXT5_Format:r.RGBA_S3TC_DXT5_Format,RGB_ETC1_Format:r.RGB_ETC1_Format,RGB_ETC2_Format:r.RGB_ETC2_Format,RGB_PVRTC_4BPPV1_Format:r.RGB_PVRTC_4BPPV1_Format,RGBA_S3TC_DXT1_Format:r.RGBA_S3TC_DXT1_Format},pn.EngineType={UnsignedByteType:r.UnsignedByteType,HalfFloatType:r.HalfFloatType,FloatType:r.FloatType},pn.BasisWorker=function(){let e,t,n;const r=_EngineFormat,i=_EngineType,s=_TranscoderFormat,a=_BasisFormat;self.addEventListener("message",(function(r){const s=r.data;switch(s.type){case"init":e=s.config,o=s.transcoderBinary,t=new Promise((e=>{n={wasmBinary:o,onRuntimeInitialized:e},BASIS(n)})).then((()=>{n.initializeBasis(),n.KTX2File}));break;case"transcode":t.then((()=>{try{const{faces:t,buffers:r,width:o,height:h,hasAlpha:d,format:p,type:m,dfdFlags:f}=function(t){const r=new n.KTX2File(new Uint8Array(t));function s(){r.close(),r.delete()}if(!r.isValid())throw s(),new Error("THREE.KTX2Loader:\tInvalid or unsupported .ktx2 file");let o;if(r.isUASTC())o=a.UASTC;else if(r.isETC1S())o=a.ETC1S;else{if(!r.isHDR())throw new Error("THREE.KTX2Loader: Unknown Basis encoding");o=a.UASTC_HDR}const h=r.getWidth(),d=r.getHeight(),p=r.getLayers()||1,m=r.getLevels(),f=r.getFaces(),g=r.getHasAlpha(),x=r.getDFDFlags(),{transcoderFormat:y,engineFormat:v,engineType:b}=function(t,n,r,i){const s=l[t];for(let a=0;a<s.length;a++){const o=s[a];if(o.if&&!e[o.if])continue;if(!o.basisFormat.includes(t))continue;if(i&&o.transcoderFormat.length<2)continue;if(o.needsPowerOfTwo&&(!c(n)||!c(r)))continue;return{transcoderFormat:o.transcoderFormat[i?1:0],engineFormat:o.engineFormat[i?1:0],engineType:o.engineType[0]}}throw new Error("THREE.KTX2Loader: Failed to identify transcoding target.")}(o,h,d,g);if(!h||!d||!m)throw s(),new Error("THREE.KTX2Loader:\tInvalid texture");if(!r.startTranscoding())throw s(),new Error("THREE.KTX2Loader: .startTranscoding failed");const w=[],T=[];for(let e=0;e<f;e++){const t=[];for(let n=0;n<m;n++){const a=[];let o,l;for(let t=0;t<p;t++){const c=r.getImageLevelInfo(n,t,e);0===e&&0===n&&0===t&&(c.origWidth%4!=0||c.origHeight),m>1?(o=c.origWidth,l=c.origHeight):(o=c.width,l=c.height);let u=new Uint8Array(r.getImageTranscodedSizeInBytes(n,t,0,y));const h=r.transcodeImage(u,n,t,e,y,0,-1,-1);if(b===i.HalfFloatType&&(u=new Uint16Array(u.buffer,u.byteOffset,u.byteLength/Uint16Array.BYTES_PER_ELEMENT)),!h)throw s(),new Error("THREE.KTX2Loader: .transcodeImage failed.");a.push(u)}const c=u(a);t.push({data:c,width:o,height:l}),T.push(c.buffer)}w.push({mipmaps:t,width:h,height:d,format:v,type:b})}return s(),{faces:w,buffers:T,width:h,height:d,hasAlpha:g,dfdFlags:x,format:v,type:b}}(s.buffer);self.postMessage({type:"transcode",id:s.id,data:{faces:t,width:o,height:h,hasAlpha:d,format:p,type:m,dfdFlags:f}},r)}catch(t){self.postMessage({type:"error",id:s.id,error:t.message})}}))}var o}));const o=[{if:"astcSupported",basisFormat:[a.UASTC],transcoderFormat:[s.ASTC_4x4,s.ASTC_4x4],engineFormat:[r.RGBA_ASTC_4x4_Format,r.RGBA_ASTC_4x4_Format],engineType:[i.UnsignedByteType],priorityETC1S:1/0,priorityUASTC:1,needsPowerOfTwo:!1},{if:"bptcSupported",basisFormat:[a.ETC1S,a.UASTC],transcoderFormat:[s.BC7_M5,s.BC7_M5],engineFormat:[r.RGBA_BPTC_Format,r.RGBA_BPTC_Format],engineType:[i.UnsignedByteType],priorityETC1S:3,priorityUASTC:2,needsPowerOfTwo:!1},{if:"dxtSupported",basisFormat:[a.ETC1S,a.UASTC],transcoderFormat:[s.BC1,s.BC3],engineFormat:[r.RGBA_S3TC_DXT1_Format,r.RGBA_S3TC_DXT5_Format],engineType:[i.UnsignedByteType],priorityETC1S:4,priorityUASTC:5,needsPowerOfTwo:!1},{if:"etc2Supported",basisFormat:[a.ETC1S,a.UASTC],transcoderFormat:[s.ETC1,s.ETC2],engineFormat:[r.RGB_ETC2_Format,r.RGBA_ETC2_EAC_Format],engineType:[i.UnsignedByteType],priorityETC1S:1,priorityUASTC:3,needsPowerOfTwo:!1},{if:"etc1Supported",basisFormat:[a.ETC1S,a.UASTC],transcoderFormat:[s.ETC1],engineFormat:[r.RGB_ETC1_Format],engineType:[i.UnsignedByteType],priorityETC1S:2,priorityUASTC:4,needsPowerOfTwo:!1},{if:"pvrtcSupported",basisFormat:[a.ETC1S,a.UASTC],transcoderFormat:[s.PVRTC1_4_RGB,s.PVRTC1_4_RGBA],engineFormat:[r.RGB_PVRTC_4BPPV1_Format,r.RGBA_PVRTC_4BPPV1_Format],engineType:[i.UnsignedByteType],priorityETC1S:5,priorityUASTC:6,needsPowerOfTwo:!0},{if:"bptcSupported",basisFormat:[a.UASTC_HDR],transcoderFormat:[s.BC6H],engineFormat:[r.RGB_BPTC_UNSIGNED_Format],engineType:[i.HalfFloatType],priorityHDR:1,needsPowerOfTwo:!1},{basisFormat:[a.ETC1S,a.UASTC],transcoderFormat:[s.RGBA32,s.RGBA32],engineFormat:[r.RGBAFormat,r.RGBAFormat],engineType:[i.UnsignedByteType,i.UnsignedByteType],priorityETC1S:100,priorityUASTC:100,needsPowerOfTwo:!1},{basisFormat:[a.UASTC_HDR],transcoderFormat:[s.RGBA_HALF],engineFormat:[r.RGBAFormat],engineType:[i.HalfFloatType],priorityHDR:100,needsPowerOfTwo:!1}],l={[a.ETC1S]:o.filter((e=>e.basisFormat.includes(a.ETC1S))).sort(((e,t)=>e.priorityETC1S-t.priorityETC1S)),[a.UASTC]:o.filter((e=>e.basisFormat.includes(a.UASTC))).sort(((e,t)=>e.priorityUASTC-t.priorityUASTC)),[a.UASTC_HDR]:o.filter((e=>e.basisFormat.includes(a.UASTC_HDR))).sort(((e,t)=>e.priorityHDR-t.priorityHDR))};function c(e){return e<=2||!(e&e-1)&&0!==e}function u(e){if(1===e.length)return e[0];let t=0;for(let i=0;i<e.length;i++){t+=e[i].byteLength}const n=new Uint8Array(t);let r=0;for(let i=0;i<e.length;i++){const t=e[i];n.set(t,r),r+=t.byteLength}return n}};const mn=new Set([r.RGBAFormat,r.RGBFormat,r.RGFormat,r.RedFormat]),fn=new Set([91]),gn={[me]:r.RGBAFormat,[pe]:r.RGFormat,[de]:r.RedFormat,[he]:r.RGBAFormat,[ce]:r.RGFormat,[le]:r.RedFormat,[ue]:r.RGBAFormat,[oe]:r.RGBAFormat,[ae]:r.RGBAFormat,[se]:r.RGFormat,[ie]:r.RGFormat,[re]:r.RedFormat,[ne]:r.RedFormat,[ge]:r.RGBFormat,[fe]:r.RGBFormat,[De]:r.RGBA_ETC2_EAC_Format,[Re]:r.RGB_ETC2_Format,[ke]:r.R11_EAC_Format,[Ie]:r.SIGNED_R11_EAC_Format,[Pe]:r.RG11_EAC_Format,[Le]:r.SIGNED_RG11_EAC_Format,[Ge]:r.RGBA_ASTC_4x4_Format,[Fe]:r.RGBA_ASTC_4x4_Format,[Ue]:r.RGBA_ASTC_4x4_Format,[qe]:r.RGBA_ASTC_6x6_Format,[Be]:r.RGBA_ASTC_6x6_Format,[ze]:r.RGBA_ASTC_6x6_Format,[be]:r.RGBA_S3TC_DXT1_Format,[ve]:r.RGBA_S3TC_DXT1_Format,[ye]:r.RGB_S3TC_DXT1_Format,[xe]:r.RGB_S3TC_DXT1_Format,[Te]:r.RGBA_S3TC_DXT5_Format,[we]:r.RGBA_S3TC_DXT5_Format,[_e]:r.SIGNED_RED_RGTC1_Format,[Se]:r.RED_RGTC1_Format,[Ae]:r.SIGNED_RED_GREEN_RGTC2_Format,[Me]:r.RED_GREEN_RGTC2_Format,[Ce]:r.RGBA_BPTC_Format,[Ee]:r.RGBA_BPTC_Format,[$e]:r.RGBA_PVRTC_4BPPV1_Format,[Oe]:r.RGBA_PVRTC_4BPPV1_Format,[Ne]:r.RGBA_PVRTC_2BPPV1_Format,[Ve]:r.RGBA_PVRTC_2BPPV1_Format},xn={[me]:r.FloatType,[pe]:r.FloatType,[de]:r.FloatType,[he]:r.HalfFloatType,[ce]:r.HalfFloatType,[le]:r.HalfFloatType,[ue]:r.UnsignedShortType,[oe]:r.UnsignedByteType,[ae]:r.UnsignedByteType,[se]:r.UnsignedByteType,[ie]:r.UnsignedByteType,[re]:r.UnsignedByteType,[ne]:r.UnsignedByteType,[ge]:r.UnsignedInt5999Type,[fe]:r.UnsignedInt101111Type,[De]:r.UnsignedByteType,[Re]:r.UnsignedByteType,[ke]:r.UnsignedByteType,[Ie]:r.UnsignedByteType,[Pe]:r.UnsignedByteType,[Le]:r.UnsignedByteType,[Ge]:r.HalfFloatType,[Fe]:r.UnsignedByteType,[Ue]:r.UnsignedByteType,[qe]:r.HalfFloatType,[Be]:r.UnsignedByteType,[ze]:r.UnsignedByteType,[be]:r.UnsignedByteType,[ve]:r.UnsignedByteType,[ye]:r.UnsignedByteType,[xe]:r.UnsignedByteType,[Te]:r.UnsignedByteType,[we]:r.UnsignedByteType,[_e]:r.UnsignedByteType,[Se]:r.UnsignedByteType,[Ae]:r.UnsignedByteType,[Me]:r.UnsignedByteType,[Ce]:r.UnsignedByteType,[Ee]:r.UnsignedByteType,[$e]:r.UnsignedByteType,[Oe]:r.UnsignedByteType,[Ne]:r.UnsignedByteType,[Ve]:r.UnsignedByteType};function yn(e){const t=e.dataFormatDescriptor[0];return 1===t.colorPrimaries?2===t.transferFunction?r.SRGBColorSpace:r.LinearSRGBColorSpace:10===t.colorPrimaries?2===t.transferFunction?"display-p3":"display-p3-linear":(t.colorPrimaries,r.NoColorSpace)}class vn extends tn{constructor(e){super(e)}}class bn extends r.Object3D{constructor(e=document.createElement("div")){super(),this.isCSS2DObject=!0,this.element=e,this.element.style.position="absolute",this.element.style.userSelect="none",this.element.setAttribute("draggable",!1),this.center=new r.Vector2(.5,.5),this.addEventListener("removed",(function(){this.traverse((function(e){e.element&&e.element instanceof e.element.ownerDocument.defaultView.Element&&null!==e.element.parentNode&&e.element.remove()}))}))}copy(e,t){return super.copy(e,t),this.element=e.element.cloneNode(!0),this.center=e.center,this}}const wn=new r.Vector3,Tn=new r.Matrix4,Sn=new r.Matrix4,_n=new r.Vector3,Mn=new r.Vector3;class An{constructor(e={}){const t=this;let n,r,i,s;const a={objects:new WeakMap},o=void 0!==e.element?e.element:document.createElement("div");function l(e){e.isCSS2DObject&&(e.element.style.display="none");for(let t=0,n=e.children.length;t<n;t++)l(e.children[t])}function c(e,n,r){if(!1!==e.visible){if(e.isCSS2DObject){wn.setFromMatrixPosition(e.matrixWorld),wn.applyMatrix4(Sn);const l=wn.z>=-1&&wn.z<=1&&!0===e.layers.test(r.layers),c=e.element;c.style.display=!0===l?"":"none",!0===l&&(e.onBeforeRender(t,n,r),c.style.transform="translate("+-100*e.center.x+"%,"+-100*e.center.y+"%)translate("+(wn.x*i+i)+"px,"+(-wn.y*s+s)+"px)",c.parentNode!==o&&o.appendChild(c),e.onAfterRender(t,n,r));const h={distanceToCameraSquared:u(r,e)};a.objects.set(e,h)}for(let t=0,i=e.children.length;t<i;t++)c(e.children[t],n,r)}else l(e)}function u(e,t){return _n.setFromMatrixPosition(e.matrixWorld),Mn.setFromMatrixPosition(t.matrixWorld),_n.distanceToSquared(Mn)}o.style.overflow="hidden",this.domElement=o,this.sortObjects=!0,this.getSize=function(){return{width:n,height:r}},this.render=function(e,t){!0===e.matrixWorldAutoUpdate&&e.updateMatrixWorld(),null===t.parent&&!0===t.matrixWorldAutoUpdate&&t.updateMatrixWorld(),Tn.copy(t.matrixWorldInverse),Sn.multiplyMatrices(t.projectionMatrix,Tn),c(e,e,t),this.sortObjects&&function(e){const t=function(e){const t=[];return e.traverseVisible((function(e){e.isCSS2DObject&&t.push(e)})),t}(e).sort((function(e,t){if(e.renderOrder!==t.renderOrder)return t.renderOrder-e.renderOrder;return a.objects.get(e).distanceToCameraSquared-a.objects.get(t).distanceToCameraSquared})),n=t.length;for(let r=0,i=t.length;r<i;r++)t[r].element.style.zIndex=n-r}(e)},this.setSize=function(e,t){n=e,r=t,i=n/2,s=r/2,o.style.width=e+"px",o.style.height=t+"px"}}}class En extends r.InstancedBufferGeometry{constructor(e,t){super(),this.ordering=e,this.setAttribute("position",new r.BufferAttribute(Cn,3)),this.setIndex(new r.BufferAttribute(Rn,1)),this._maxInstanceCount=e.length,this.instanceCount=t,this.attribute=new r.InstancedBufferAttribute(e,1,!1,1),this.attribute.setUsage(r.DynamicDrawUsage),this.setAttribute("splatIndex",this.attribute)}update(e,t){this.ordering=e,this.attribute.array=e,this.instanceCount=t,this.attribute.addUpdateRange(0,t),this.attribute.needsUpdate=!0}}const Cn=new Float32Array([-1,-1,0,1,-1,0,1,1,0,-1,1,0]),Rn=new Uint16Array([0,1,2,0,2,3]),Dn="undefined"==typeof document?require("url").pathToFileURL(__dirname+"/assets/viewer/spark-old-worker-932b4a2c87ca.js").href:new URL("assets/viewer/spark-old-worker-932b4a2c87ca.js",document.currentScript&&"SCRIPT"===document.currentScript.tagName.toUpperCase()&&document.currentScript.src||document.baseURI).href,kn="undefined"==typeof document?require("url").pathToFileURL(__dirname+"/assets/viewer/spark-worker-015de49d2d00.wasm").href:new URL("assets/viewer/spark-worker-015de49d2d00.wasm",document.currentScript&&"SCRIPT"===document.currentScript.tagName.toUpperCase()&&document.currentScript.src||document.baseURI).href;function In(e){const t=new URL(Dn);return t.searchParams.set("wasm",kn),new Worker(t,{name:null==e?void 0:e.name})}var Pn=Uint8Array,Ln=Uint16Array,Un=Int32Array,Fn=new Pn([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),zn=new Pn([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),Bn=new Pn([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Vn=function(e,t){for(var n=new Ln(31),r=0;r<31;++r)n[r]=t+=1<<e[r-1];var i=new Un(n[30]);for(r=1;r<30;++r)for(var s=n[r];s<n[r+1];++s)i[s]=s-n[r]<<5|r;return{b:n,r:i}},On=Vn(Fn,2),Nn=On.b,$n=On.r;Nn[28]=258,$n[258]=28;for(var Gn=Vn(zn,0).b,qn=new Ln(32768),Hn=0;Hn<32768;++Hn){var jn=(43690&Hn)>>1|(21845&Hn)<<1;jn=(61680&(jn=(52428&jn)>>2|(13107&jn)<<2))>>4|(3855&jn)<<4,qn[Hn]=((65280&jn)>>8|(255&jn)<<8)>>1}var Wn=function(e,t,n){for(var r=e.length,i=0,s=new Ln(t);i<r;++i)e[i]&&++s[e[i]-1];var a,o=new Ln(t);for(i=1;i<t;++i)o[i]=o[i-1]+s[i-1]<<1;a=new Ln(1<<t);var l=15-t;for(i=0;i<r;++i)if(e[i])for(var c=i<<4|e[i],u=t-e[i],h=o[e[i]-1]++<<u,d=h|(1<<u)-1;h<=d;++h)a[qn[h]>>l]=c;return a},Xn=new Pn(288);for(Hn=0;Hn<144;++Hn)Xn[Hn]=8;for(Hn=144;Hn<256;++Hn)Xn[Hn]=9;for(Hn=256;Hn<280;++Hn)Xn[Hn]=7;for(Hn=280;Hn<288;++Hn)Xn[Hn]=8;var Yn=new Pn(32);for(Hn=0;Hn<32;++Hn)Yn[Hn]=5;var Kn=Wn(Xn,9),Qn=Wn(Yn,5),Zn=function(e){for(var t=e[0],n=1;n<e.length;++n)e[n]>t&&(t=e[n]);return t},Jn=function(e,t,n){var r=t/8|0;return(e[r]|e[r+1]<<8)>>(7&t)&n},er=function(e,t){var n=t/8|0;return(e[n]|e[n+1]<<8|e[n+2]<<16)>>(7&t)},tr=function(e){return(e+7)/8|0},nr=function(e,t,n){return(null==t||t<0)&&(t=0),(null==n||n>e.length)&&(n=e.length),new Pn(e.subarray(t,n))},rr=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],ir=function(e,t,n){var r=new Error(t||rr[e]);if(r.code=e,Error.captureStackTrace&&Error.captureStackTrace(r,ir),!n)throw r;return r},sr=function(e,t,n,r){var i=e.length,s=r?r.length:0;if(!i||t.f&&!t.l)return n||new Pn(0);var a=!n,o=a||2!=t.i,l=t.i;a&&(n=new Pn(3*i));var c=function(e){var t=n.length;if(e>t){var r=new Pn(Math.max(2*t,e));r.set(n),n=r}},u=t.f||0,h=t.p||0,d=t.b||0,p=t.l,m=t.d,f=t.m,g=t.n,x=8*i;do{if(!p){u=Jn(e,h,1);var y=Jn(e,h+1,3);if(h+=3,!y){var v=e[(D=tr(h)+4)-4]|e[D-3]<<8,b=D+v;if(b>i){l&&ir(0);break}o&&c(d+v),n.set(e.subarray(D,b),d),t.b=d+=v,t.p=h=8*b,t.f=u;continue}if(1==y)p=Kn,m=Qn,f=9,g=5;else if(2==y){var w=Jn(e,h,31)+257,T=Jn(e,h+10,15)+4,S=w+Jn(e,h+5,31)+1;h+=14;for(var _=new Pn(S),M=new Pn(19),A=0;A<T;++A)M[Bn[A]]=Jn(e,h+3*A,7);h+=3*T;var E=Zn(M),C=(1<<E)-1,R=Wn(M,E);for(A=0;A<S;){var D,k=R[Jn(e,h,C)];if(h+=15&k,(D=k>>4)<16)_[A++]=D;else{var I=0,P=0;for(16==D?(P=3+Jn(e,h,3),h+=2,I=_[A-1]):17==D?(P=3+Jn(e,h,7),h+=3):18==D&&(P=11+Jn(e,h,127),h+=7);P--;)_[A++]=I}}var L=_.subarray(0,w),U=_.subarray(w);f=Zn(L),g=Zn(U),p=Wn(L,f),m=Wn(U,g)}else ir(1);if(h>x){l&&ir(0);break}}o&&c(d+131072);for(var F=(1<<f)-1,z=(1<<g)-1,B=h;;B=h){var V=(I=p[er(e,h)&F])>>4;if((h+=15&I)>x){l&&ir(0);break}if(I||ir(2),V<256)n[d++]=V;else{if(256==V){B=h,p=null;break}var O=V-254;if(V>264){var N=Fn[A=V-257];O=Jn(e,h,(1<<N)-1)+Nn[A],h+=N}var $=m[er(e,h)&z],G=$>>4;$||ir(3),h+=15&$;U=Gn[G];if(G>3){N=zn[G];U+=er(e,h)&(1<<N)-1,h+=N}if(h>x){l&&ir(0);break}o&&c(d+131072);var q=d+O;if(d<U){var H=s-U,j=Math.min(U,q);for(H+d<0&&ir(3);d<j;++d)n[d]=r[H+d]}for(;d<q;++d)n[d]=n[d-U]}}t.l=p,t.p=B,t.b=d,t.f=u,p&&(u=1,t.m=f,t.d=m,t.n=g)}while(!u);return d!=n.length&&a?nr(n,0,d):n.subarray(0,d)},ar=new Pn(0),or=function(e,t){return e[t]|e[t+1]<<8},lr=function(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0},cr=function(e,t){return lr(e,t)+4294967296*lr(e,t+4)},ur=function(){function e(e,t){"function"==typeof e&&(t=e,e={}),this.ondata=t;var n=e&&e.dictionary&&e.dictionary.subarray(-32768);this.s={i:0,b:n?n.length:0},this.o=new Pn(32768),this.p=new Pn(0),n&&this.o.set(n)}return e.prototype.e=function(e){if(this.ondata||ir(5),this.d&&ir(4),this.p.length){if(e.length){var t=new Pn(this.p.length+e.length);t.set(this.p),t.set(e,this.p.length),this.p=t}}else this.p=e},e.prototype.c=function(e){this.s.i=+(this.d=e||!1);var t=this.s.b,n=sr(this.p,this.s,this.o);this.ondata(nr(n,t,this.s.b),this.d),this.o=nr(n,this.s.b-32768),this.s.b=this.o.length,this.p=nr(this.p,this.s.p/8|0),this.s.p&=7},e.prototype.push=function(e,t){this.e(e),this.c(t)},e}();function hr(e,t){return sr(e,{i:2},t&&t.out,t&&t.dictionary)}var dr=function(){function e(e,t){this.v=1,this.r=0,ur.call(this,e,t)}return e.prototype.push=function(e,t){if(ur.prototype.e.call(this,e),this.r+=e.length,this.v){var n=this.p.subarray(this.v-1),r=n.length>3?function(e){31==e[0]&&139==e[1]&&8==e[2]||ir(6,"invalid gzip data");var t=e[3],n=10;4&t&&(n+=2+(e[10]|e[11]<<8));for(var r=(t>>3&1)+(t>>4&1);r>0;r-=!e[n++]);return n+(2&t)}(n):4;if(r>n.length){if(!t)return}else this.v>1&&this.onmember&&this.onmember(this.r-n.length);this.p=n.subarray(r),this.v=0}ur.prototype.c.call(this,t),!this.s.f||this.s.l||t||(this.v=tr(this.s.p)+9,this.s={i:0},this.o=new Pn(0),this.push(new Pn(0),t))},e}(),pr="undefined"!=typeof TextDecoder&&new TextDecoder;try{pr.decode(ar,{stream:!0})}catch(Jm){}function mr(e,t){if(t){for(var n="",r=0;r<e.length;r+=16384)n+=String.fromCharCode.apply(null,e.subarray(r,r+16384));return n}if(pr)return pr.decode(e);var i=function(e){for(var t="",n=0;;){var r=e[n++],i=(r>127)+(r>223)+(r>239);if(n+i>e.length)return{s:t,r:nr(e,n-1)};i?3==i?(r=((15&r)<<18|(63&e[n++])<<12|(63&e[n++])<<6|63&e[n++])-65536,t+=String.fromCharCode(55296|r>>10,56320|1023&r)):t+=1&i?String.fromCharCode((31&r)<<6|63&e[n++]):String.fromCharCode((15&r)<<12|(63&e[n++])<<6|63&e[n++]):t+=String.fromCharCode(r)}}(e),s=i.s;return(n=i.r).length&&ir(8),s}var fr=function(e,t){return t+30+or(e,t+26)+or(e,t+28)},gr=function(e,t,n){var r=or(e,t+28),i=mr(e.subarray(t+46,t+46+r),!(2048&or(e,t+8))),s=t+46+r,a=lr(e,t+20),o=n&&4294967295==a?xr(e,s):[a,lr(e,t+24),lr(e,t+42)],l=o[0],c=o[1],u=o[2];return[or(e,t+10),l,c,i,s+or(e,t+30)+or(e,t+32),u]},xr=function(e,t){for(;1!=or(e,t);t+=4+or(e,t+2));return[cr(e,t+12),cr(e,t+4),cr(e,t+20)]};const yr=-12,vr=Math.exp(-30),br=2048,wr=2048;var Tr=(e=>(e.PLY="ply",e.SPZ="spz",e.SPLAT="splat",e.KSPLAT="ksplat",e.PCSOGS="pcsogs",e.PCSOGSZIP="pcsogszip",e.RAD="rad",e))(Tr||{});const Sr={rgbMin:0,rgbMax:1,lnScaleMin:yr,lnScaleMax:9,sh1Max:1,sh2Max:1,sh3Max:1,lodOpacity:!1};function _r(e){return"int"===e||"ivec2"===e||"ivec3"===e||"ivec4"===e}function Mr(e){return"uint"===e||"uvec2"===e||"uvec3"===e||"uvec4"===e}function Ar(e){return function(e){return"float"===e||"vec2"===e||"vec3"===e||"vec4"===e}(e)||function(e){return"mat2"===e||"mat2x2"===e||"mat2x3"===e||"mat2x4"===e||"mat3"===e||"mat3x2"===e||"mat3x3"===e||"mat3x4"===e||"mat4"===e||"mat4x2"===e||"mat4x3"===e||"mat4x4"===e}(e)}function Er(e){return"mat2"===e||"mat2x2"===e}function Cr(e){return"mat3"===e||"mat3x3"===e}function Rr(e){return"mat4"===e||"mat4x4"===e}function Dr(e){return Math.trunc(e).toString()}function kr(e){return`${Math.max(0,Math.trunc(e)).toString()}u`}function Ir(e){return e===Number.POSITIVE_INFINITY?"INFINITY":e===Number.NEGATIVE_INFINITY?"-INFINITY":Number.isInteger(e)?e.toFixed(1):e.toString()}function Pr(e){if(e instanceof Lr)return e.type;return e.dynoOut().type}class Lr{constructor(e){this.__isDynoValue=!0,this.type=e}}class Ur extends Lr{constructor(e,t){super(e.outTypes[t]),this.dyno=e,this.key=t}}class Fr extends Lr{constructor(e,t){super(e),this.literal=t}getLiteral(){return this.literal}}class zr extends Fr{constructor(e,t){super(e,""),this.value=t}getLiteral(){const{type:e,value:t}=this;switch(e){case"bool":return t?"true":"false";case"uint":return kr(t);case"int":return Dr(t);case"float":return Ir(t);case"bvec2":{const e=t;return`bvec2(${e[0]}, ${e[1]})`}case"uvec2":{if(t instanceof r.Vector2)return`uvec2(${kr(t.x)}, ${kr(t.y)})`;const e=t;return`uvec2(${kr(e[0])}, ${kr(e[1])})`}case"ivec2":{if(t instanceof r.Vector2)return`ivec2(${Dr(t.x)}, ${Dr(t.y)})`;const e=t;return`ivec2(${Dr(e[0])}, ${Dr(e[1])})`}case"vec2":{if(t instanceof r.Vector2)return`vec2(${Ir(t.x)}, ${Ir(t.y)})`;const e=t;return`vec2(${Ir(e[0])}, ${Ir(e[1])})`}case"bvec3":{const e=t;return`bvec3(${e[0]}, ${e[1]}, ${e[2]})`}case"uvec3":{if(t instanceof r.Vector3)return`uvec3(${kr(t.x)}, ${kr(t.y)}, ${kr(t.z)})`;const e=t;return`uvec3(${kr(e[0])}, ${kr(e[1])}, ${kr(e[2])})`}case"ivec3":{if(t instanceof r.Vector3)return`ivec3(${Dr(t.x)}, ${Dr(t.y)}, ${Dr(t.z)})`;const e=t;return`ivec3(${Dr(e[0])}, ${Dr(e[1])}, ${Dr(e[2])})`}case"vec3":{if(t instanceof r.Vector3)return`vec3(${Ir(t.x)}, ${Ir(t.y)}, ${Ir(t.z)})`;const e=t;return`vec3(${Ir(e[0])}, ${Ir(e[1])}, ${Ir(e[2])})`}case"bvec4":{const e=t;return`bvec4(${e[0]}, ${e[1]}, ${e[2]}, ${e[3]})`}case"uvec4":{if(t instanceof r.Vector4)return`uvec4(${kr(t.x)}, ${kr(t.y)}, ${kr(t.z)}, ${kr(t.w)})`;const e=t;return`uvec4(${kr(e[0])}, ${kr(e[1])}, ${kr(e[2])}, ${kr(e[3])})`}case"ivec4":{if(t instanceof r.Vector4)return`ivec4(${Dr(t.x)}, ${Dr(t.y)}, ${Dr(t.z)}, ${Dr(t.w)})`;const e=t;return`ivec4(${Dr(e[0])}, ${Dr(e[1])}, ${Dr(e[2])}, ${Dr(e[3])})`}case"vec4":{if(t instanceof r.Vector4)return`vec4(${Ir(t.x)}, ${Ir(t.y)}, ${Ir(t.z)}, ${Ir(t.w)})`;if(t instanceof r.Quaternion)return`vec4(${Ir(t.x)}, ${Ir(t.y)}, ${Ir(t.z)}, ${Ir(t.w)})`;const e=t;return`vec4(${Ir(e[0])}, ${Ir(e[1])}, ${Ir(e[2])}, ${Ir(e[3])})`}case"mat2":case"mat2x2":{const n=t,i=n instanceof r.Matrix2?n.elements:t;return`${e}(${new Array(4).fill(0).map(((e,t)=>Ir(i[t]))).join(", ")})`}case"mat2x3":{const n=t;return`${e}(${new Array(6).fill(0).map(((e,t)=>Ir(n[t]))).join(", ")})`}case"mat2x4":{const n=t;return`${e}(${new Array(8).fill(0).map(((e,t)=>Ir(n[t]))).join(", ")})`}case"mat3":case"mat3x3":{const n=t,i=n instanceof r.Matrix3?n.elements:t;return`${e}(${new Array(9).fill(0).map(((e,t)=>Ir(i[t]))).join(", ")})`}case"mat3x2":{const n=t;return`${e}(${new Array(6).fill(0).map(((e,t)=>Ir(n[t]))).join(", ")})`}case"mat3x4":{const n=t;return`${e}(${new Array(12).fill(0).map(((e,t)=>Ir(n[t]))).join(", ")})`}case"mat4":case"mat4x4":{const n=t,i=n instanceof r.Matrix4?n.elements:t;return`${e}(${new Array(16).fill(0).map(((e,t)=>Ir(i[t]))).join(", ")})`}case"mat4x2":{const n=t;return`${e}(${new Array(8).fill(0).map(((e,t)=>Ir(n[t]))).join(", ")})`}case"mat4x3":{const n=t;return`${e}(${new Array(12).fill(0).map(((e,t)=>Ir(n[t]))).join(", ")})`}default:throw new Error(`Type not implemented: ${String(e)}`)}}}function Br(e,t){return new zr(e,t)}function Vr(e){const t=String(e);if(function(e){return"bool"===e||"bvec2"===e||"bvec3"===e||"bvec4"===e}(e))return`${t}(false)`;if(Ar(e))return`${t}(0.0)`;if(_r(e))return`${t}(0)`;if(Mr(e))return`${t}(0u)`;throw new Error(`Type not implemented: ${t}`)}const Or=" ";class Nr{constructor({indent:e}={}){this.globals=new Set,this.statements=[],this.uniforms={},this.declares=new Set,this.updaters=[],this.sequence=0,this.indent=Or,this.indent=e??Or}nextSequence(){return this.sequence++}}class $r{constructor({inTypes:e,outTypes:t,inputs:n,update:r,globals:i,statements:s,generate:a}){this.inTypes=e??{},this.outTypes=t??{},this.inputs=n??{},this.update=r,this.globals=i,this.statements=s,this.generate=a??(({inputs:e,outputs:t,compile:n})=>{var r,i;return{globals:null==(r=this.globals)?void 0:r.call(this,{inputs:e,outputs:t,compile:n}),statements:null==(i=this.statements)?void 0:i.call(this,{inputs:e,outputs:t,compile:n})}})}get outputs(){const e={};for(const t in this.outTypes)e[t]=new Ur(this,t);return e}apply(e){return Object.assign(this.inputs,e),this.outputs}compile({inputs:e,outputs:t,compile:n}){const r=[`// ${this.constructor.name}(${Object.values(e).join(", ")}) => (${Object.values(t).join(", ")})`],i=[];for(const l in t){const e=t[l];e&&!n.declares.has(e)&&(n.declares.add(e),i.push(l))}const{globals:s,statements:a,uniforms:o}=this.generate({inputs:e,outputs:t,compile:n});for(const l of s??[])n.globals.add(l);for(const l in o)n.uniforms[l]=o[l];this.update&&n.updaters.push(this.update);for(const l of i){const e=t[l];e&&(n.uniforms[e]||r.push(`${jr(e,this.outTypes[l])};`))}return(null==a?void 0:a.length)&&(r.push("{"),r.push(...a.map((e=>n.indent+e))),r.push("}")),r}}class Gr extends $r{constructor({inTypes:e,outTypes:t,inputs:n,update:r,globals:i,construct:s}){super({inTypes:e,outTypes:t,inputs:n,update:r,globals:i,generate:e=>this.generateBlock(e)}),this.construct=s}generateBlock({inputs:e,outputs:t,compile:n}){var r,i;const s={},a={};for(const m in e)null!=e[m]&&(s[m]=new Fr(this.inTypes[m],e[m]));for(const m in t)null!=t[m]&&(a[m]=new Lr(this.outTypes[m]));const o={roots:[]},l=this.construct(s,a,o);for(const m of(null==(r=this.globals)?void 0:r.call(this,{inputs:e,outputs:t,compile:n}))??[])n.globals.add(m);const c=[],u=new Map;function h(e,t,r){let i=u.get(e);if(!i){i={sequence:n.nextSequence(),outNames:new Map,newOuts:new Set},u.set(e,i);for(const t in e.inputs){let n=e.inputs[t];for(;n;){if(n instanceof Lr){n instanceof Ur&&h(n.dyno,n.key);break}if("function"!=typeof n.dynoOut)throw new Error(`dynoOut is not a function for ${n.constructor.name}`);n=n.dynoOut()}}c.push(e)}t&&(r||i.newOuts.add(t),i.outNames.set(t,r??`${t}_${i.sequence}`))}for(const m of o.roots)h(m);for(const m in a){let e=(null==l?void 0:l[m])??a[m];for(;e;){if(e instanceof Lr){e instanceof Ur&&h(e.dyno,e.key,t[m]);break}e=e.dynoOut()}a[m]=e}const d=[];for(const m of c){const e={},t={};for(const n in m.inputs){let t=m.inputs[n];for(;t;){if(t instanceof Lr){if(t instanceof Fr)e[n]=t.getLiteral();else if(t instanceof Ur){const r=null==(i=u.get(t.dyno))?void 0:i.outNames.get(t.key);if(!r)throw new Error(`Source not found for ${t.dyno.constructor.name}.${t.key}`);e[n]=r}break}t=t.dynoOut()}}const r=u.get(m)??{outNames:new Map};for(const[n,i]of r.outNames.entries())t[n]=i;const s=m.compile({inputs:e,outputs:t,compile:n});d.push(s)}const p=[];for(const m in t)a[m]instanceof Fr&&p.push(`${t[m]} = ${a[m].getLiteral()};`);p.length>0&&d.push(p);return{statements:d.flatMap(((e,t)=>0===t?e:["",...e]))}}}function qr(e,t,n,{update:r,globals:i}={}){return new Gr({inTypes:e,outTypes:t,construct:n,update:r,globals:i})}function Hr({inTypes:e,outTypes:t,inputs:n,update:r,globals:i,statements:s,generate:a}){return new $r({inTypes:e,outTypes:t,inputs:n,update:r,globals:i,statements:s,generate:a})}function jr(e,t,n){const r="string"==typeof t?t:t.type;if(!r)throw new Error(`Invalid DynoType: ${String(t)}`);return`${r} ${e}${null!=n?`[${n}]`:""}`}function Wr(e){var t;let n=!1;const r=e.split("\n").map((e=>{const t=e.trimEnd();return n?t:t.length>0?(n=!0,t):null})).filter((e=>null!=e));for(;r.length>0&&0===r[r.length-1].length;)r.pop();if(0===r.length)return[];const i=null==(t=r[0].match(/^\s*/))?void 0:t[0];if(!i)return r;const s=new RegExp(`^${i}`);return r.map((e=>e.replace(s,"")))}function Xr(e){return Wr(e).join("\n")}class Yr extends $r{constructor({a:e,outKey:t,outTypeFunc:n}){const r={a:Pr(e)},i=n(Pr(e));super({inTypes:r,outTypes:{[t]:i},inputs:{a:e}}),this.outKey=t}dynoOut(){return new Ur(this,this.outKey)}}class Kr extends $r{constructor({a:e,b:t,outKey:n,outTypeFunc:r}){const i={a:Pr(e),b:Pr(t)},s=r(Pr(e),Pr(t));super({inTypes:i,outTypes:{[n]:s},inputs:{a:e,b:t}}),this.outKey=n}dynoOut(){return new Ur(this,this.outKey)}}const Qr=Number.parseInt(r.REVISION)>=179,Zr=new Float32Array(1),Jr=new Uint32Array(Zr.buffer),ei="Float16Array"in globalThis,ti=ei?new globalThis.Float16Array(1):null,ni=new Uint16Array(null==ti?void 0:ti.buffer);function ri(e){return Zr[0]=e,Jr[0]}function ii(e){return Jr[0]=e,Zr[0]}const si=ei?function(e){return ti[0]=e,ni[0]}:function(e){Zr[0]=e;const t=Jr[0],n=t>>23&255,r=8388607&t,i=(t>>31&1)<<15;if(255===n)return 0!==r?32767|i:31744|i;const s=n-127+15;if(s>=31)return 31744|i;if(s<=0){if(s<-10)return i;return i|(8388608|r)>>1-s+13}return i|s<<10|r>>13},ai=ei?function(e){return ni[0]=e,ti[0]}:function(e){const t=e>>15&1,n=e>>10&31,r=1023&e;let i;if(0===n)if(0===r)i=t<<31;else{let e=r,n=-14;for(;!(1024&e);)e<<=1,n--;e&=1023;i=t<<31|n+127<<23|e<<13}else if(31===n)i=0===r?t<<31|2139095040:t<<31|2143289344;else{i=t<<31|n-15+127<<23|r<<13}return Jr[0]=i,Zr[0]};function oi(e){return Math.max(0,Math.min(255,Math.round(255*e)))}function li(e){const t=[],n=new Set;return function e(r){r&&"object"==typeof r&&!n.has(r)&&(n.add(r),r instanceof ArrayBuffer?t.push(r):ArrayBuffer.isView(r)?t.push(r.buffer):Array.isArray(r)?r.forEach(e):Object.values(r).forEach(e))}(e),t}class ci{constructor({allocate:e,dispose:t,valid:n}){this.items=[],this.allocate=e,this.dispose=t,this.valid=n}alloc(e){for(;;){const t=this.items.pop();if(!t)break;if(this.valid(t,e))return t;this.dispose&&this.dispose(t)}return this.allocate(e)}free(e){this.items.push(e)}disposeAll(){let e;for(e=this.items.pop();e;)this.dispose&&this.dispose(e),e=this.items.pop()}}function ui(e,t,n,r,i,s,a,o,l,c,u,h,d,p,m,f){const g=4*t,[x,y]=e;x[g]=ri(n),x[g+1]=ri(r),x[g+2]=ri(i),x[g+3]=si(d),y[g]=si(p)|si(m)<<16,y[g+1]=si(f)|si(Math.log(s))<<16,y[g+2]=si(Math.log(a))|si(Math.log(o))<<16,y[g+3]=function(e,t,n,r){const i=Math.sqrt(e*e+t*t+n*n+r*r),s=(r<0?-e:e)/i,a=(r<0?-t:t)/i,o=(r<0?-n:n)/i,l=(r<0?-r:r)/i,c=2*Math.acos(l),u=Math.sqrt(s*s+a*a+o*o),h=u<1e-6?1:s/u,d=u<1e-6?0:a/u,p=u<1e-6?0:o/u,m=Math.abs(h)+Math.abs(d)+Math.abs(p);let f=h/m,g=d/m;if(p<0){const e=f;f=(1-Math.abs(g))*(f>=0?1:-1),g=(1-Math.abs(e))*(g>=0?1:-1)}const x=.5*f+.5,y=.5*g+.5,v=Math.round(1023*x),b=Math.round(1023*y);return Math.round(c*(4095/Math.PI))<<20|b<<10|v}(l,c,u,h)}function hi(e,t){const n=mi,r=4*t,[i,s]=e;return n.center.x=ii(i[r]),n.center.y=ii(i[r+1]),n.center.z=ii(i[r+2]),n.opacity=ai(65535&i[r+3]),n.color.r=ai(65535&s[r]),n.color.g=ai(s[r]>>>16),n.color.b=ai(65535&s[r+1]),n.scales.x=Math.exp(ai(s[r+1]>>>16)),n.scales.y=Math.exp(ai(65535&s[r+2])),n.scales.z=Math.exp(ai(s[r+2]>>>16)),function(e,t){const n=e>>>20&4095;let r=2*((1023&e)/1023-.5),i=2*((e>>>10&1023)/1023-.5);const s=1-(Math.abs(r)+Math.abs(i)),a=Math.max(-s,0);r+=r>=0?-a:a,i+=i>=0?-a:a;const o=Math.sqrt(r*r+i*i+s*s),l=o<1e-6?0:r/o,c=o<1e-6?0:i/o,u=o<1e-6?0:s/o,h=n/4095*Math.PI*.5,d=Math.sin(h),p=Math.cos(h);t.set(l*d,c*d,u*d,p)}(s[r+3],n.quaternion),n}function di(e,t,n,r,i,s,a,o,l,c,u,h,d,p,m,f,g){const x=(null==g?void 0:g.rgbMin)??0,y=((null==g?void 0:g.rgbMax)??1)-x,v=oi((p-x)/y),b=oi((m-x)/y),w=oi((f-x)/y),T=oi((null==g?void 0:g.lodOpacity)?.5*d:d),S=function(e){const t=Ti.copy(e).normalize();t.w<0&&t.set(-t.x,-t.y,-t.z,-t.w);const n=2*Math.acos(t.w),r=Math.sqrt(t.x*t.x+t.y*t.y+t.z*t.z),i=r<1e-6?Si.set(1,0,0):Si.set(t.x,t.y,t.z).divideScalar(r),s=Math.abs(i.x)+Math.abs(i.y)+Math.abs(i.z);let a=i.x/s,o=i.y/s;if(i.z<0){const e=a;a=(1-Math.abs(o))*(a>=0?1:-1),o=(1-Math.abs(e))*(o>=0?1:-1)}const l=.5*a+.5,c=.5*o+.5,u=Math.round(255*l),h=Math.round(255*c);return Math.round(n*(255/Math.PI))<<16|h<<8|u}(pi.set(l,c,u,h)),_=255&S,M=S>>>8&255,A=S>>>16&255,E=(null==g?void 0:g.lnScaleMin)??yr,C=254/(((null==g?void 0:g.lnScaleMax)??9)-E),R=s<vr?0:Math.min(255,Math.max(1,Math.round((Math.log(s)-E)*C)+1)),D=a<vr?0:Math.min(255,Math.max(1,Math.round((Math.log(a)-E)*C)+1)),k=o<vr?0:Math.min(255,Math.max(1,Math.round((Math.log(o)-E)*C)+1)),I=si(n),P=si(r),L=si(i),U=4*t;e[U]=v|b<<8|w<<16|T<<24,e[U+1]=I|P<<16,e[U+2]=L|_<<16|M<<24,e[U+3]=R|D<<8|k<<16|A<<24}const pi=new r.Quaternion,mi={center:new r.Vector3,scales:new r.Vector3,quaternion:new r.Quaternion,color:new r.Color,opacity:0};function fi(e,t,n){const r=mi,i=4*t,s=e[i],a=e[i+1],o=e[i+2],l=e[i+3],c=(null==n?void 0:n.rgbMin)??0,u=((null==n?void 0:n.rgbMax)??1)-c;r.color.set(c+(255&s)/255*u,c+(s>>>8&255)/255*u,c+(s>>>16&255)/255*u),r.opacity=(s>>>24&255)/255,(null==n?void 0:n.lodOpacity)&&(r.opacity=2*r.opacity),r.center.set(ai(65535&a),ai(a>>>16&65535),ai(65535&o));const h=(null==n?void 0:n.lnScaleMin)??yr,d=(((null==n?void 0:n.lnScaleMax)??9)-h)/254,p=255&l;r.scales.x=0===p?0:Math.exp(h+(p-1)*d);const m=l>>>8&255;r.scales.y=0===m?0:Math.exp(h+(m-1)*d);const f=l>>>16&255;r.scales.z=0===f?0:Math.exp(h+(f-1)*d);return function(e,t){const n=e>>>16&255;let r=2*((255&e)/255-.5),i=2*((e>>>8&255)/255-.5);const s=1-(Math.abs(r)+Math.abs(i)),a=Math.max(-s,0);r+=r>=0?-a:a,i+=i>=0?-a:a;const o=Si.set(r,i,s).normalize(),l=n/255*Math.PI*.5,c=Math.sin(l),u=Math.cos(l);t.set(o.x*c,o.y*c,o.z*c,u)}(o>>>16&65535|l>>>8&16711680,r.quaternion),r}function gi(e){const t=br,n=Math.max(1,Math.min(wr,Math.ceil(e/t))),r=Math.ceil(e/(t*n));return{width:t,height:n,depth:r,maxSplats:t*n*r}}function xi(){return!navigator.platform.toLowerCase().startsWith("win")&&(navigator.maxTouchPoints>0||/Mobi|Android|iPhone|iPad|iPod|Opera Mini|IEMobile/.test(navigator.userAgent))}function yi(){return/iPhone|iPad/.test(navigator.userAgent)}function vi(e){const t=new r.Clock(e.autoStart);return t.startTime=e.startTime,t.oldTime=e.oldTime,t.elapsedTime=e.elapsedTime,t.running=e.running,t}const bi=Xr("\n precision highp float;\n\n in vec3 position;\n\n void main() {\n gl_Position = vec4(position.xy, 0.0, 1.0);\n }\n");function wi({matrix1:e,matrix2:t,maxDistance:n,minCoorient:i}){const{distance:s,coorient:a}=function(e,t){const[n,i]=[new r.Vector3,new r.Quaternion],[s,a]=[new r.Vector3,new r.Quaternion];return e.decompose(n,i,new r.Vector3),t.decompose(s,a,new r.Vector3),{distance:n.distanceTo(s),coorient:Math.abs(i.dot(a))}}(e,t);return s<=n&&(null==i||a>=i)}const Ti=new r.Quaternion,Si=new r.Vector3;class _i{constructor(){this.messages={},this.messageIdNext=0,this.worker=new In,this.worker.onmessage=e=>this.onMessage(e)}makeMessageId(){return++this.messageIdNext}makeMessagePromiseId(){const e=this.makeMessageId(),t=new Promise(((t,n)=>{this.messages[e]={resolve:t,reject:n}}));return{id:e,promise:t}}onMessage(e){const{id:t,result:n,error:r}=e.data,i=this.messages[t];i&&(delete this.messages[t],r?i.reject(r):i.resolve(n))}async call(e,t){const{id:n,promise:r}=this.makeMessagePromiseId();return this.worker.postMessage({name:e,args:t,id:n},{transfer:li(t)}),r}}let Mi=0;const Ai=[],Ei=[];async function Ci(e){const t=await async function(){const e=Ai.shift();if(e)return e;if(Mi<4){const e=new _i;return Mi+=1,e}return new Promise((e=>{Ei.push(e)}))}();try{return await e(t)}finally{!function(e){if(Mi>4)return void(Mi-=1);const t=Ei.shift();t?t(e):Ai.push(e)}(t)}}const Ri="undefined"==typeof document?require("url").pathToFileURL(__dirname+"/assets/viewer/spark-worker-5ec8a483b87c.js").href:new URL("assets/viewer/spark-worker-5ec8a483b87c.js",document.currentScript&&"SCRIPT"===document.currentScript.tagName.toUpperCase()&&document.currentScript.src||document.baseURI).href,Di="undefined"==typeof document?require("url").pathToFileURL(__dirname+"/assets/viewer/spark-worker-015de49d2d00.wasm").href:new URL("assets/viewer/spark-worker-015de49d2d00.wasm",document.currentScript&&"SCRIPT"===document.currentScript.tagName.toUpperCase()&&document.currentScript.src||document.baseURI).href;function ki(e){const t=new URL(Ri);return t.searchParams.set("wasm",Di),new Worker(t,{name:null==e?void 0:e.name})}const Ii=class e{constructor(){this.queue=null,this.messages={},this.worker=new ki,this.worker.onmessage=e=>this.onMessage(e)}onMessage(e){var t;const{id:n,result:r,error:i,status:s}=e.data,a=this.messages[n];a&&(void 0!==i?(delete this.messages[n],a.reject(i)):void 0!==s?null==(t=a.onStatus)||t.call(a,s):(delete this.messages[n],a.resolve(r)))}tryExclusive(e){return null==this.queue?this.exclusive(e):null}async exclusive(e){const t=this.queue;null!=t?await new Promise((e=>{t.push((()=>e(void 0)))})):this.queue=[];try{return await e(this)}finally{if(null!=this.queue)if(0===this.queue.length)this.queue=null;else{this.queue.shift()()}}}async call(t,n,r={}){const i=++e.currentId,s=new Promise(((e,t)=>{this.messages[i]={resolve:e,reject:t,onStatus:r.onStatus}}));return this.worker.postMessage({id:i,name:t,args:n},{transfer:li(n)}),await s}dispose(){this.worker.terminate();const e=Object.values(this.messages);this.messages={};for(const t of e)t.reject(new Error("Worker terminate"))}};Ii.currentId=0;let Pi=Ii;const Li=new class{constructor(e=4){this.numWorkers=0,this.freelist=[],this.queue=[],this.maxWorkers=e}async withWorker(e){const t=await this.allocWorker();try{return await e(t)}finally{this.freeWorker(t)}}async allocWorker(){const e=this.freelist.pop();if(e)return e;if(this.numWorkers<this.maxWorkers){const e=new Pi;return this.numWorkers+=1,e}return new Promise((e=>{this.queue.push(e)}))}freeWorker(e){if(this.numWorkers>this.maxWorkers)return void(this.numWorkers-=1);const t=this.queue.shift();t?t(e):this.freelist.push(e)}},Ui={type:"Gsplat"},Fi={type:"CovSplat"},zi={type:"PackedSplats"},Bi={type:"ExtSplats"},Vi=(e,t)=>new Ki({packedSplats:e,index:t}),Oi=e=>new ts({gsplat:e}),Ni=e=>new ns({gsplat:e}),$i=({gsplat:e,flags:t,index:n,center:r,scales:i,quaternion:s,rgba:a,rgb:o,opacity:l,x:c,y:u,z:h,r:d,g:p,b:m})=>new rs({gsplat:e,flags:t,index:n,center:r,scales:i,quaternion:s,rgba:a,rgb:o,opacity:l,x:c,y:u,z:h,r:d,g:p,b:m}),Gi=(e,{scale:t,rotate:n,translate:r,recolor:i})=>new is({gsplat:e,scale:t,rotate:n,translate:r,recolor:i}),qi=e=>new cs({index:e}),Hi=e=>new us({index:e}),ji=Xr("\n struct Gsplat {\n vec3 center;\n uint flags;\n vec3 scales;\n int index;\n vec4 quaternion;\n vec4 rgba;\n };\n const uint GSPLAT_FLAG_ACTIVE = 1u << 0u;\n\n bool isGsplatActive(uint flags) {\n return (flags & GSPLAT_FLAG_ACTIVE) != 0u;\n }\n"),Wi=Xr("\n struct CovSplat {\n vec3 center;\n uint flags;\n vec4 rgba;\n vec3 xxyyzz;\n int index;\n vec3 xyxzyz;\n };\n\n bool isCovSplatActive(uint flags) {\n return (flags & GSPLAT_FLAG_ACTIVE) != 0u;\n }\n"),Xi=Xr("\n struct PackedSplats {\n usampler2DArray textureArray;\n int numSplats;\n vec4 rgbMinMaxLnScaleMinMax;\n bool lodOpacity;\n };\n"),Yi=Xr("\n bool readPackedArray(usampler2DArray texture, int numSplats, vec4 rgbMinMaxLnScaleMinMax, int index, out Gsplat gsplat) {\n if ((index >= 0) && (index < numSplats)) {\n uvec4 packedData = texelFetch(texture, splatTexCoord(index), 0);\n unpackSplatEncoding(packedData, gsplat.center, gsplat.scales, gsplat.quaternion, gsplat.rgba, rgbMinMaxLnScaleMinMax);\n return true;\n } else {\n return false;\n }\n }\n");class Ki extends $r{constructor({packedSplats:e,index:t}){super({inTypes:{packedSplats:zi,index:"int"},outTypes:{gsplat:Ui},inputs:{packedSplats:e,index:t},globals:()=>[ji,Xi,Yi],statements:({inputs:e,outputs:t})=>{const{gsplat:n}=t;if(!n)return[];const{packedSplats:r,index:i}=e;let s;return s=r&&i?Wr(`\n ${n}.flags = 0u;\n if (readPackedArray(${r}.textureArray, ${r}.numSplats, ${r}.rgbMinMaxLnScaleMinMax, ${i}, ${n})) {\n if (${r}.lodOpacity) {\n ${n}.rgba.a = 2.0 * ${n}.rgba.a;\n }\n bool zeroSize = all(equal(${n}.scales, vec3(0.0, 0.0, 0.0)));\n ${n}.flags = zeroSize ? 0u : GSPLAT_FLAG_ACTIVE;\n }\n `):[`${n}.flags = 0u;`],s.push(`${n}.index = ${i??"0"};`),s}})}dynoOut(){return new Ur(this,"gsplat")}}class Qi extends $r{constructor({packedSplats:e,index:t,base:n,count:r}){super({inTypes:{packedSplats:zi,index:"int",base:"int",count:"int"},outTypes:{gsplat:Ui},inputs:{packedSplats:e,index:t,base:n,count:r},globals:()=>[ji,Xi,Yi],statements:({inputs:e,outputs:t})=>{const{gsplat:n}=t;if(!n)return[];const{packedSplats:r,index:i,base:s,count:a}=e;let o;return o=r&&i&&s&&a?Wr(`\n ${n}.flags = 0u;\n if (readPackedArray(${r}.textureArray, ${r}.numSplats, ${r}.rgbMinMaxLnScaleMinMax, ${i}, ${n})) {\n if (${r}.lodOpacity) {\n ${n}.rgba.a = 2.0 * ${n}.rgba.a;\n }\n bool zeroSize = all(equal(${n}.scales, vec3(0.0, 0.0, 0.0)));\n ${n}.flags = zeroSize ? 0u : GSPLAT_FLAG_ACTIVE;\n }\n `):[`${n}.flags = 0u;`],o.push(`${n}.index = ${i??"0"};`),o}})}dynoOut(){return new Ur(this,"gsplat")}}const Zi=Xr("\n struct ExtSplats {\n usampler2DArray textureArray1;\n usampler2DArray textureArray2;\n int numSplats;\n };\n"),Ji=Xr("\n void readExtArrays(usampler2DArray texture1, usampler2DArray texture2, int numSplats, int index, out Gsplat gsplat) {\n gsplat.flags = 0u;\n if ((index >= 0) && (index < numSplats)) {\n ivec3 coord = splatTexCoord(index);\n uvec4 packed1 = texelFetch(texture1, coord, 0);\n uvec4 packed2 = texelFetch(texture2, coord, 0);\n unpackSplatExt(packed1, packed2, gsplat.center, gsplat.scales, gsplat.quaternion, gsplat.rgba);\n gsplat.flags = all(equal(gsplat.scales, vec3(0.0, 0.0, 0.0))) ? 0u : GSPLAT_FLAG_ACTIVE;\n gsplat.index = index;\n }\n }\n");class es extends $r{constructor({extSplats:e,index:t}){super({inTypes:{extSplats:Bi,index:"int"},outTypes:{gsplat:Ui},inputs:{extSplats:e,index:t},globals:()=>[ji,Zi,Ji],statements:({inputs:e,outputs:t})=>{const{gsplat:n}=t;if(!n)return[`${n}.flags = 0u;`];const{extSplats:r,index:i}=e;return r&&i?Wr(`\n readExtArrays(${r}.textureArray1, ${r}.textureArray2, ${r}.numSplats, ${i}, ${n});\n `):[`${n}.flags = 0u;`]}})}dynoOut(){return new Ur(this,"gsplat")}}Xr("\n void readCovArrays(usampler2DArray texture1, usampler2DArray texture2, int numSplats, int index, out CovSplat covsplat) {\n covsplat.flags = 0u;\n if ((index >= 0) && (index < numSplats)) {\n ivec3 coord = splatTexCoord(index);\n uvec4 packed1 = texelFetch(texture1, coord, 0);\n uvec4 packed2 = texelFetch(texture2, coord, 0);\n unpackSplatExtCov(packed1, packed2, covsplat.center, covsplat.rgba, covsplat.xxyyzz, covsplat.xyxzyz);\n covsplat.flags = (all(equal(covsplat.xxyyzz, vec3(0.0))) && all(equal(covsplat.xyxzyz, vec3(0.0)))) ? 0u : GSPLAT_FLAG_ACTIVE;\n gsplat.index = index;\n }\n }\n");class ts extends $r{constructor({gsplat:e}){super({inTypes:{gsplat:Ui},outTypes:{covsplat:Fi},inputs:{gsplat:e},globals:()=>[ji,Wi],statements:({inputs:e,outputs:t})=>{const{gsplat:n}=e,{covsplat:r}=t;return n?Wr(`\n ${r}.flags = 0u;\n if (isGsplatActive(${n}.flags)) {\n ${r}.flags = ${n}.flags;\n ${r}.index = ${n}.index;\n ${r}.rgba = ${n}.rgba;\n ${r}.center = ${n}.center;\n mat3 m = scaleQuaternionToMatrix(${n}.scales, ${n}.quaternion);\n m = m * transpose(m);\n ${r}.xxyyzz = vec3(m[0][0], m[1][1], m[2][2]);\n ${r}.xyxzyz = vec3(m[0][1], m[0][2], m[1][2]);\n }\n `):[`${r}.flags = 0u;`]}})}dynoOut(){return new Ur(this,"covsplat")}}class ns extends $r{constructor({gsplat:e}){super({inTypes:{gsplat:Ui},outTypes:{flags:"uint",active:"bool",index:"int",center:"vec3",scales:"vec3",quaternion:"vec4",rgba:"vec4",rgb:"vec3",opacity:"float",x:"float",y:"float",z:"float",r:"float",g:"float",b:"float"},inputs:{gsplat:e},globals:()=>[ji],statements:({inputs:e,outputs:t})=>{const{gsplat:n}=e,{flags:r,active:i,index:s,center:a,scales:o,quaternion:l,rgba:c,rgb:u,opacity:h,x:d,y:p,z:m,r:f,g:g,b:x}=t;return[r?`${r} = ${n?`${n}.flags`:"0u"};`:null,i?`${i} = isGsplatActive(${n?`${n}.flags`:"0u"});`:null,s?`${s} = ${n?`${n}.index`:"0"};`:null,a?`${a} = ${n?`${n}.center`:"vec3(0.0, 0.0, 0.0)"};`:null,o?`${o} = ${n?`${n}.scales`:"vec3(0.0, 0.0, 0.0)"};`:null,l?`${l} = ${n?`${n}.quaternion`:"vec4(0.0, 0.0, 0.0, 1.0)"};`:null,c?`${c} = ${n?`${n}.rgba`:"vec4(0.0, 0.0, 0.0, 0.0)"};`:null,u?`${u} = ${n?`${n}.rgba.rgb`:"vec3(0.0, 0.0, 0.0)"};`:null,h?`${h} = ${n?`${n}.rgba.a`:"0.0"};`:null,d?`${d} = ${n?`${n}.center.x`:"0.0"};`:null,p?`${p} = ${n?`${n}.center.y`:"0.0"};`:null,m?`${m} = ${n?`${n}.center.z`:"0.0"};`:null,f?`${f} = ${n?`${n}.rgba.r`:"0.0"};`:null,g?`${g} = ${n?`${n}.rgba.g`:"0.0"};`:null,x?`${x} = ${n?`${n}.rgba.b`:"0.0"};`:null].filter(Boolean)}})}}class rs extends $r{constructor({gsplat:e,flags:t,index:n,center:r,scales:i,quaternion:s,rgba:a,rgb:o,opacity:l,x:c,y:u,z:h,r:d,g:p,b:m}){super({inTypes:{gsplat:Ui,flags:"uint",index:"int",center:"vec3",scales:"vec3",quaternion:"vec4",rgba:"vec4",rgb:"vec3",opacity:"float",x:"float",y:"float",z:"float",r:"float",g:"float",b:"float"},outTypes:{gsplat:Ui},inputs:{gsplat:e,flags:t,index:n,center:r,scales:i,quaternion:s,rgba:a,rgb:o,opacity:l,x:c,y:u,z:h,r:d,g:p,b:m},globals:()=>[ji],statements:({inputs:e,outputs:t})=>{const{gsplat:n}=t;if(!n)return[];const{gsplat:r,flags:i,index:s,center:a,scales:o,quaternion:l,rgba:c,rgb:u,opacity:h,x:d,y:p,z:m,r:f,g:g,b:x}=e;return[`${n}.flags = ${i??(r?`${r}.flags`:"0u")};`,`${n}.index = ${s??(r?`${r}.index`:"0")};`,`${n}.center = ${a??(r?`${r}.center`:"vec3(0.0, 0.0, 0.0)")};`,`${n}.scales = ${o??(r?`${r}.scales`:"vec3(0.0, 0.0, 0.0)")};`,`${n}.quaternion = ${l??(r?`${r}.quaternion`:"vec4(0.0, 0.0, 0.0, 1.0)")};`,`${n}.rgba = ${c??(r?`${r}.rgba`:"vec4(0.0, 0.0, 0.0, 0.0)")};`,u?`${n}.rgba.rgb = ${u};`:null,h?`${n}.rgba.a = ${h};`:null,d?`${n}.center.x = ${d};`:null,p?`${n}.center.y = ${p};`:null,m?`${n}.center.z = ${m};`:null,f?`${n}.rgba.r = ${f};`:null,g?`${n}.rgba.g = ${g};`:null,x?`${n}.rgba.b = ${x};`:null].filter(Boolean)}})}dynoOut(){return new Ur(this,"gsplat")}}Xr("\n vec3 gsplatNormal(vec3 scales, vec4 quaternion) {\n float minScale = min(scales.x, min(scales.y, scales.z));\n vec3 normal;\n if (scales.z == minScale) {\n normal = vec3(0.0, 0.0, 1.0);\n } else if (scales.y == minScale) {\n normal = vec3(0.0, 1.0, 0.0);\n } else {\n normal = vec3(1.0, 0.0, 0.0);\n }\n return quatVec(quaternion, normal);\n }\n");class is extends $r{constructor({gsplat:e,scale:t,rotate:n,translate:r,recolor:i}){super({inTypes:{gsplat:Ui,scale:"float",rotate:"vec4",translate:"vec3",recolor:"vec4"},outTypes:{gsplat:Ui},inputs:{gsplat:e,scale:t,rotate:n,translate:r,recolor:i},globals:()=>[ji],statements:({inputs:e,outputs:t,compile:n})=>{const{gsplat:r}=t;if(!r||!e.gsplat)return[];const{scale:i,rotate:s,translate:a,recolor:o}=e,l=n.indent;return[`${r} = ${e.gsplat};`,`if (isGsplatActive(${r}.flags)) {`,i?`${l}${r}.center *= ${i};`:null,s?`${l}${r}.center = quatVec(${s}, ${r}.center);`:null,a?`${l}${r}.center += ${a};`:null,i?`${l}${r}.scales *= ${i};`:null,s?`${l}${r}.quaternion = quatQuat(${s}, ${r}.quaternion);`:null,o?`${l}${r}.rgba *= ${o};`:null,"}"].filter(Boolean)}})}dynoOut(){return new Ur(this,"gsplat")}}const ss=e=>new os({covsplat:e}),as=({covsplat:e,flags:t,index:n,center:r,rgba:i,rgb:s,opacity:a,x:o,y:l,z:c,r:u,g:h,b:d})=>new ls({covsplat:e,flags:t,index:n,center:r,rgba:i,rgb:s,opacity:a,x:o,y:l,z:c,r:u,g:h,b:d});class os extends $r{constructor({covsplat:e}){super({inTypes:{covsplat:Fi},outTypes:{flags:"uint",active:"bool",index:"int",center:"vec3",rgba:"vec4",rgb:"vec3",opacity:"float",x:"float",y:"float",z:"float",r:"float",g:"float",b:"float"},inputs:{covsplat:e},globals:()=>[Wi],statements:({inputs:e,outputs:t})=>{const{covsplat:n}=e,{flags:r,active:i,index:s,center:a,rgba:o,rgb:l,opacity:c,x:u,y:h,z:d,r:p,g:m,b:f}=t;return[r?`${r} = ${n?`${n}.flags`:"0u"};`:null,i?`${i} = isCovSplatActive(${n?`${n}.flags`:"0u"});`:null,s?`${s} = ${n?`${n}.index`:"0"};`:null,a?`${a} = ${n?`${n}.center`:"vec3(0.0, 0.0, 0.0)"};`:null,o?`${o} = ${n?`${n}.rgba`:"vec4(0.0, 0.0, 0.0, 0.0)"};`:null,l?`${l} = ${n?`${n}.rgba.rgb`:"vec3(0.0, 0.0, 0.0)"};`:null,c?`${c} = ${n?`${n}.rgba.a`:"0.0"};`:null,u?`${u} = ${n?`${n}.center.x`:"0.0"};`:null,h?`${h} = ${n?`${n}.center.y`:"0.0"};`:null,d?`${d} = ${n?`${n}.center.z`:"0.0"};`:null,p?`${p} = ${n?`${n}.rgba.r`:"0.0"};`:null,m?`${m} = ${n?`${n}.rgba.g`:"0.0"};`:null,f?`${f} = ${n?`${n}.rgba.b`:"0.0"};`:null].filter(Boolean)}})}}class ls extends $r{constructor({covsplat:e,flags:t,index:n,center:r,rgba:i,rgb:s,opacity:a,x:o,y:l,z:c,r:u,g:h,b:d}){super({inTypes:{covsplat:Fi,flags:"uint",index:"int",center:"vec3",rgba:"vec4",rgb:"vec3",opacity:"float",x:"float",y:"float",z:"float",r:"float",g:"float",b:"float"},outTypes:{covsplat:Fi},inputs:{covsplat:e,flags:t,index:n,center:r,rgba:i,rgb:s,opacity:a,x:o,y:l,z:c,r:u,g:h,b:d},globals:()=>[Wi],statements:({inputs:e,outputs:t})=>{const{covsplat:n}=t;if(!n)return[];const{covsplat:r,flags:i,index:s,center:a,rgba:o,rgb:l,opacity:c,x:u,y:h,z:d,r:p,g:m,b:f}=e;return[`${n}.flags = ${i??(r?`${r}.flags`:"0u")};`,`${n}.index = ${s??(r?`${r}.index`:"0")};`,`${n}.center = ${a??(r?`${r}.center`:"vec3(0.0, 0.0, 0.0)")};`,`${n}.rgba = ${o??(r?`${r}.rgba`:"vec4(0.0, 0.0, 0.0, 0.0)")};`,l?`${n}.rgba.rgb = ${l};`:null,c?`${n}.rgba.a = ${c};`:null,u?`${n}.center.x = ${u};`:null,h?`${n}.center.y = ${h};`:null,d?`${n}.center.z = ${d};`:null,p?`${n}.rgba.r = ${p};`:null,m?`${n}.rgba.g = ${m};`:null,f?`${n}.rgba.b = ${f};`:null,`${n}.xxyyzz = ${r?`${r}.xxyyzz`:"vec3(0.0, 0.0, 0.0)"};`,`${n}.xyxzyz = ${r?`${r}.xyxzyz`:"vec3(0.0, 0.0, 0.0)"};`].filter(Boolean)}})}dynoOut(){return new Ur(this,"covsplat")}}class cs extends $r{constructor({index:e}){super({inTypes:{index:"int"},outTypes:{coord:"ivec3"},inputs:{index:e},statements:({inputs:e,outputs:t})=>{const{index:n}=e,{coord:r}=t;return n&&r?[`${r} = splatTexCoord(${n});`]:[]}})}dynoOut(){return new Ur(this,"coord")}}class us extends $r{constructor({index:e}){super({inTypes:{index:"int"},outTypes:{coord:"ivec3"},inputs:{index:e},statements:({inputs:e,outputs:t})=>{const{index:n}=e,{coord:r}=t;return n&&r?[`${r} = pagedSplatTexCoord(${n});`]:[]}})}dynoOut(){return new Ur(this,"coord")}}const hs=(e,t)=>new ps({gsplat:e,rgbMinMaxLnScaleMinMax:t}),ds=e=>new gs({covsplat:e});class ps extends $r{constructor({gsplat:e,rgbMinMaxLnScaleMinMax:t}){super({inTypes:{gsplat:Ui,rgbMinMaxLnScaleMinMax:"vec4"},inputs:{gsplat:e,rgbMinMaxLnScaleMinMax:t},globals:()=>[ji],statements:({inputs:e,outputs:t})=>{const{gsplat:n,rgbMinMaxLnScaleMinMax:r}=e;return n&&r?Wr(`\n if (isGsplatActive(${n}.flags)) {\n target = packSplatEncoding(${n}.center, ${n}.scales, ${n}.quaternion, ${n}.rgba, ${r});\n } else {\n target = uvec4(0u, 0u, 0u, 0u);\n }\n `):["target = uvec4(0u, 0u, 0u, 0u);"]}})}}class ms extends $r{constructor({covsplat:e,rgbMinMaxLnScaleMinMax:t}){super({inTypes:{covsplat:Fi,rgbMinMaxLnScaleMinMax:"vec4"},inputs:{covsplat:e,rgbMinMaxLnScaleMinMax:t},globals:()=>[Wi],statements:({inputs:e})=>{const{covsplat:t,rgbMinMaxLnScaleMinMax:n}=e;return t&&n?Wr(`\n if (isCovSplatActive(${t}.flags)) {\n target = packSplatCovEncoding(${t}.center, ${t}.rgba, ${t}.xxyyzz, ${t}.xyxzyz, ${n});\n } else {\n target = uvec4(0u);\n }\n `):["target = uvec4(0u);"]}})}}class fs extends $r{constructor({gsplat:e}){super({inTypes:{gsplat:Ui},inputs:{gsplat:e},globals:()=>[ji],statements:({inputs:e})=>{const{gsplat:t}=e;return t?Wr(`\n if (isGsplatActive(${t}.flags)) {\n packSplatExt(target, target2, ${t}.center, ${t}.scales, ${t}.quaternion, ${t}.rgba);\n } else {\n target = uvec4(0u);\n target2 = uvec4(0u);\n }\n `):["target = uvec4(0u);","target2 = uvec4(0u);"]}})}}class gs extends $r{constructor({covsplat:e}){super({inTypes:{covsplat:Fi},inputs:{covsplat:e},globals:()=>[Wi],statements:({inputs:e})=>{const{covsplat:t}=e;return t?Wr(`\n if (isCovSplatActive(${t}.flags)) {\n packSplatExtCov(target, target2, ${t}.center, ${t}.rgba, ${t}.xxyyzz, ${t}.xyxzyz);\n } else {\n target = uvec4(0u);\n target2 = uvec4(0u);\n }\n `):["target = uvec4(0u);","target2 = uvec4(0u);"]}})}}class xs extends $r{constructor({gsplat:e,viewCenter:t,viewDir:n,sortRadial:r}){super({inTypes:{gsplat:Ui,viewCenter:"vec3",viewDir:"vec3",sortRadial:"bool"},inputs:{gsplat:e,viewCenter:t,viewDir:n,sortRadial:r},globals:()=>[ji],statements:({inputs:e})=>{const{gsplat:t,viewCenter:n,viewDir:r,sortRadial:i}=e;return t&&n&&r&&i?Wr(`\n float metric = 1.0 / 0.0;\n if (isGsplatActive(${t}.flags)) {\n vec3 center = ${t}.center - ${n};\n if (${i}) {\n metric = length(center);\n } else {\n float bias = 100.0; // reduce popping\n metric = dot(center, ${r}) + bias;\n }\n }\n target3 = floatToVec4(metric);\n `):[]}})}}class ys extends $r{constructor({covsplat:e,viewCenter:t,viewDir:n,sortRadial:r}){super({inTypes:{covsplat:Fi,viewCenter:"vec3",viewDir:"vec3",sortRadial:"bool"},inputs:{covsplat:e,viewCenter:t,viewDir:n,sortRadial:r},globals:()=>[Wi],statements:({inputs:e})=>{const{covsplat:t,viewCenter:n,viewDir:r,sortRadial:i}=e;return t&&n&&r&&i?Wr(`\n float metric = 1.0 / 0.0;\n if (isCovSplatActive(${t}.flags)) {\n vec3 center = ${t}.center - ${n};\n if (${i}) {\n metric = length(center);\n } else {\n float bias = 100.0; // reduce popping\n metric = dot(center, ${r}) + bias;\n }\n }\n target3 = floatToVec4(metric);\n `):[]}})}}class vs extends $r{constructor({rgba8:e}){super({inTypes:{rgba8:"vec4"},inputs:{rgba8:e},statements:({inputs:e,outputs:t})=>[`target = ${e.rgba8??"vec4(0.0, 0.0, 0.0, 0.0)"};`]})}dynoOut(){return new Ur(this,"rgba8")}}class bs extends $r{constructor({key:e,type:t,count:n,value:r,update:i,globals:s}){e=e??"value",super({outTypes:{[e]:t},update:()=>{if(i){const e=i(this.value);void 0!==e&&(this.value=e)}this.uniform.value=this.value},generate:({inputs:r,outputs:i})=>{const a=(null==s?void 0:s({inputs:r,outputs:i}))??[],o={},l=i[e];return l&&(a.push(`uniform ${jr(l,t,n)};`),o[l]=this.uniform),{globals:a,uniforms:o}}}),this.type=t,this.count=n,this.value=r,this.uniform={value:r},this.outKey=e}dynoOut(){return new Ur(this,this.outKey)}}class ws extends bs{constructor({key:e,value:t,update:n}){super({key:e,type:"bool",value:t,update:n})}}class Ts extends bs{constructor({key:e,value:t,update:n}){super({key:e,type:"int",value:t,update:n})}}class Ss extends bs{constructor({key:e,value:t,update:n}){super({key:e,type:"float",value:t,update:n})}}class _s extends bs{constructor({key:e,value:t,update:n}){super({key:e,type:"vec3",value:t,update:n})}}class Ms extends bs{constructor({key:e,value:t,update:n}){super({key:e,type:"vec4",value:t,update:n})}}class As extends bs{constructor({key:e,value:t,update:n}){super({key:e,type:"mat3",value:t,update:n})}}class Es extends bs{constructor({key:e,value:t,update:n}){super({key:e,type:"usampler2D",value:t,update:n})}}class Cs extends bs{constructor({key:e,value:t,update:n}){super({key:e,type:"usampler2DArray",value:t,update:n})}}class Rs{constructor({graph:e,inputs:t,outputs:n,template:r,consoleLog:i}){this.graph=e,this.template=r,this.inputs=t??{},this.outputs=n??{};const s=new Nr({indent:this.template.indent});for(const o in this.outputs)this.outputs[o]&&s.declares.add(this.outputs[o]);const a=e.compile({inputs:this.inputs,outputs:this.outputs,compile:s});this.shader=r.generate({globals:s.globals,statements:a}),this.uniforms=s.uniforms,this.updaters=s.updaters}prepareMaterial(){return function(e){let t=ks.get(e);if(t)return t;return t=new r.RawShaderMaterial({glslVersion:r.GLSL3,vertexShader:bi,fragmentShader:e.shader,uniforms:e.uniforms}),ks.set(e,t),t}(this)}update(){for(const e of this.updaters)e()}}class Ds{constructor(e){const t=e.match(/^([ \t]*)\{\{\s*GLOBALS\s*\}\}/m),n=e.match(/^([ \t]*)\{\{\s*STATEMENTS\s*\}\}/m);if(!t||!n)throw new Error("Template must contain {{ GLOBALS }} and {{ STATEMENTS }}");this.before=e.substring(0,t.index),this.between=e.substring(t.index+t[0].length,n.index),this.after=e.substring(n.index+n[0].length),this.indent=n[1]}generate({globals:e,statements:t}){return this.before+Array.from(e).join("\n\n")+this.between+t.map((e=>this.indent+e)).join("\n")+this.after}}const ks=new WeakMap;function Is(e,t,n="add"){const r=()=>{throw new Error(`Invalid ${n} types: ${e}, ${t}`)};if(e===t)return e;if("int"===e){if(_r(t))return t;r()}if("int"===t){if(_r(e))return e;r()}if("uint"===e){if(Mr(t))return t;r()}if("uint"===t){if(Mr(e))return e;r()}if("float"===e){if(Ar(t))return t;r()}if("float"===t){if(Ar(e))return e;r()}throw new Error(`Invalid ${n} types: ${e}, ${t}`)}function Ps(e,t){return Is(e,t,"sub")}function Ls(e,t){const n=()=>{throw new Error(`Invalid mul types: ${e}, ${t}`)};if("int"===e){if(_r(t))return t;n()}if("int"===t){if(_r(e))return e;n()}if("uint"===e){if(Mr(t))return t;n()}if("uint"===t){if(Mr(e))return e;n()}if("float"===e){if(Ar(t))return t;n()}if("float"===t){if(Ar(e))return e;n()}if(_r(e)||Mr(e)||_r(t)||Mr(t)){if(e===t)return e;n()}if("vec2"===e){if("vec2"===t||Er(t))return"vec2";if("mat3x2"===t)return"vec3";if("mat4x2"===t)return"vec4";n()}if("vec3"===e){if("mat2x3"===t)return"vec2";if("vec3"===t||Cr(t))return"vec3";if("mat4x3"===t)return"vec4";n()}if("vec4"===e){if("mat2x4"===t)return"vec2";if("mat3x4"===t)return"vec3";if("vec4"===t||Rr(t))return"vec4";n()}if("vec2"===t){if(Er(e))return"vec2";if("mat2x3"===e)return"vec3";if("mat2x4"===e)return"vec4";n()}if("vec3"===t){if("mat3x2"===e)return"vec2";if(Cr(e))return"vec3";if("mat3x4"===e)return"vec4";n()}if("vec4"===t){if("mat4x2"===e)return"vec2";if("mat4x3"===e)return"vec3";if(Rr(e))return"vec4";n()}if(Er(e)){if(Er(t))return"mat2";if("mat3x2"===t)return"mat3x2";if("mat4x2"===t)return"mat4x2";n()}if("mat2x3"===e){if(Er(t))return"mat2x3";if("mat3x2"===t)return"mat3";if("mat4x2"===t)return"mat4x3";n()}if("mat2x4"===e){if(Er(t))return"mat2x4";if("mat3x2"===t)return"mat3x4";if("mat4x2"===t)return"mat4";n()}if("mat3x2"===e){if("mat2x3"===t)return"mat2";if(Cr(t))return"mat3x2";if("mat4x3"===t)return"mat4x2";n()}if(Cr(e)){if("mat2x3"===t)return"mat2x3";if(Cr(t))return"mat3";if("mat4x3"===t)return"mat4x3";n()}if("mat3x4"===e){if("mat2x3"===t)return"mat2x4";if(Cr(t))return"mat3x4";if("mat4x3"===t)return"mat4";n()}if("mat4x2"===e){if("mat2x4"===t)return"mat2";if("mat3x4"===t)return"mat3x2";if(Rr(t))return"mat4x2";n()}if("mat4x3"===e){if("mat2x4"===t)return"mat2x3";if("mat3x4"===t)return"mat3";if(Rr(t))return"mat4x3";n()}if(Rr(e)){if("mat2x4"===t)return"mat2x4";if("mat3x4"===t)return"mat3x4";if(Rr(t))return"mat4";n()}throw new Error(`Invalid mul types: ${e}, ${t}`)}const Us=(e,t)=>new Bs({a:e,b:t}),Fs=(e,t)=>new Vs({a:e,b:t}),zs=(e,t)=>new Os({a:e,b:t});class Bs extends Kr{constructor({a:e,b:t}){super({a:e,b:t,outKey:"sum",outTypeFunc:Is}),this.statements=({inputs:e,outputs:t})=>[`${t.sum} = ${e.a} + ${e.b};`]}}class Vs extends Kr{constructor({a:e,b:t}){super({a:e,b:t,outKey:"difference",outTypeFunc:Ps}),this.statements=({inputs:e,outputs:t})=>[`${t.difference} = ${e.a} - ${e.b};`]}}class Os extends Kr{constructor({a:e,b:t}){super({a:e,b:t,outKey:"product",outTypeFunc:Ls}),this.statements=({inputs:e,outputs:t})=>[`${t.product} = ${e.a} * ${e.b};`]}}const Ns=e=>new qs({value:e});class $s extends Yr{constructor({value:e}){super({a:e,outKey:"uint",outTypeFunc:()=>"uint"}),this.statements=({inputs:e,outputs:t})=>[`${t.uint} = floatBitsToUint(${e.a});`]}}class Gs extends Yr{constructor({value:e}){super({a:e,outKey:"uint",outTypeFunc:()=>"uint"}),this.statements=({inputs:e,outputs:t})=>[`${t.uint} = packHalf2x16(${e.a});`]}}class qs extends Yr{constructor({value:e}){super({a:e,outKey:"rgba8",outTypeFunc:()=>"vec4"}),this.statements=({inputs:e,outputs:t})=>[`uvec4 uRgba = uvec4(${e.a} & 0xffu, (${e.a} >> 8u) & 0xffu, (${e.a} >> 16u) & 0xffu, (${e.a} >> 24u) & 0xffu);`,`${t.rgba8} = vec4(uRgba) / 255.0;`]}}const Hs=e=>new js({a:e});class js extends Yr{constructor({a:e}){super({a:e,outTypeFunc:e=>e,outKey:"normalize"}),this.statements=({inputs:e,outputs:t})=>[`${t.normalize} = normalize(${e.a});`]}}class Ws extends $r{constructor({vector:e,vectorType:t,x:n,y:r,z:i,w:s,r:a,g:o,b:l,a:c}){if(!e&&!t)throw new Error("Either vector or vectorType must be provided");const u=t??Pr(e),h=function(e){switch(e){case"vec2":case"vec3":case"vec4":return"float";case"ivec2":case"ivec3":case"ivec4":return"int";case"uvec2":case"uvec3":case"uvec4":return"uint";default:throw new Error(`Invalid vector type: ${e}`)}}(u),d=function(e){switch(e){case"vec2":case"ivec2":case"uvec2":return 2;case"vec3":case"ivec3":case"uvec3":return 3;case"vec4":case"ivec4":case"uvec4":return 4;default:throw new Error(`Invalid vector type: ${e}`)}}(u),p={vector:u,x:h,y:h,r:h,g:h},m={vector:e,x:n,y:r,r:a,g:o};d>=3&&(Object.assign(p,{z:h,b:h}),Object.assign(m,{z:i,b:l})),d>=4&&(Object.assign(p,{w:h,a:h}),Object.assign(m,{w:s,a:c})),super({inTypes:p,outTypes:{vector:u},inputs:m}),this.statements=({inputs:e,outputs:t})=>{const{vector:n}=t,{vector:r,x:i,y:s,z:a,w:o,r:l,g:c,b:u,a:p}=e,m=[`${n}.x = ${i??l??(r?`${r}.x`:Vr(h))};`,`${n}.y = ${s??c??(r?`${r}.y`:Vr(h))};`];return d>=3&&m.push(`${n}.z = ${a??u??(r?`${r}.z`:Vr(h))};`),d>=4&&m.push(`${n}.w = ${o??p??(r?`${r}.w`:Vr(h))};`),m}}dynoOut(){return new Ur(this,"vector")}}class Xs extends $r{constructor({position:e,scale:t,scales:n,rotate:r,translate:i}){super({inTypes:{position:"vec3",scale:"float",scales:"vec3",rotate:"vec4",translate:"vec3"},outTypes:{position:"vec3"},inputs:{position:e,scale:t,scales:n,rotate:r,translate:i},statements:({inputs:e,outputs:t})=>{const{position:n}=t;if(!n)return[];const{scale:r,scales:i,rotate:s,translate:a}=e;return[`${n} = ${e.position??"vec3(0.0, 0.0, 0.0)"};`,r?`${n} *= ${r};`:null,i?`${n} *= ${i};`:null,s?`${n} = quatVec(${s}, ${n});`:null,a?`${n} += ${a};`:null].filter(Boolean)}})}}class Ys extends $r{constructor({dir:e,scale:t,scales:n,rotate:r}){super({inTypes:{dir:"vec3",scale:"float",scales:"vec3",rotate:"vec4"},outTypes:{dir:"vec3"},inputs:{dir:e,scale:t,scales:n,rotate:r},statements:({inputs:e,outputs:t})=>{const{dir:n}=t;if(!n)return[];const{scale:r,scales:i,rotate:s}=e;return[`${n} = ${e.dir??"vec3(0.0, 0.0, 0.0)"};`,r?`${n} *= ${r};`:null,i?`${n} *= ${i};`:null,s?`${n} = quatVec(${s}, ${n});`:null].filter(Boolean)}})}}const Ks=class e{constructor(t={}){this.maxSplats=0,this.numSplats=0,this.extra={},this.maxSh=3,this.isInitialized=!1,this.extArrays=[new Uint32Array(0),new Uint32Array(0)],this.textures=[e.emptyTexture,e.emptyTexture],this.extra={},this.dyno=new Zs({extSplats:this}),this.dynoNumSh=new Ts({key:"numSh",value:0,update:()=>Math.min(this.getNumSh(),this.maxSh)}),this.initialized=Promise.resolve(this),this.reinitialize(t)}reinitialize(e){this.isInitialized=!1,this.extra={},this.maxSplats=e.maxSplats??0,this.lod=e.lod,this.nonLod=e.nonLod,e.url||e.fileBytes||e.stream||e.construct?this.initialized=this.asyncInitialize(e).then((()=>(this.isInitialized=!0,this))):(this.initialize(e),this.isInitialized=!0,this.initialized=Promise.resolve(this))}initialize(e){this.extra=e.extra??{},this.lodSplats=e.lodSplats,e.extArrays?(this.extArrays=e.extArrays,this.maxSplats=Math.floor(Math.min(this.extArrays[0].length/4,this.extArrays[1].length/4)),this.numSplats=e.numSplats??this.maxSplats,this.maxSplats=Math.floor(this.maxSplats/br)*br,this.numSplats=Math.min(this.maxSplats,e.numSplats??Number.POSITIVE_INFINITY),this.updateTextures()):(this.maxSplats=e.maxSplats??0,this.numSplats=0,this.extArrays=[new Uint32Array(0),new Uint32Array(0)])}async asyncInitialize(e){const{url:t,fileBytes:n,fileType:r,fileName:i,stream:s,streamLength:a,construct:o,lod:l,nonLod:c,lodAbove:u}=e;this.lod=l,this.nonLod=c;const h=new po;if((n||t||s)&&await h.loadInternalAsync({extSplats:this,url:t,fileBytes:n,fileType:r,fileName:i,stream:s,streamLength:a,onProgress:e.onProgress,lodAbove:u}),o){const e=o(this);e instanceof Promise&&await e}}dispose(){this.textures[0]!==e.emptyTexture&&(this.textures[0].dispose(),this.textures[0].source.data=null,this.textures[0]=e.emptyTexture),this.textures[1]!==e.emptyTexture&&(this.textures[1].dispose(),this.textures[1].source.data=null,this.textures[1]=e.emptyTexture),this.extArrays=[new Uint32Array(0),new Uint32Array(0)];for(const e in this.extra){const t=this.extra[e];if(t instanceof bs){const e=t.value;(null==e?void 0:e.isTexture)&&(e.dispose(),e.source.data=null)}}this.extra={},this.disposeLodSplats()}prepareFetchSplat(){}getNumSplats(){return this.numSplats}hasRgbDir(){return Math.min(this.getNumSh(),this.maxSh)>0}getNumSh(){return this.extra.sh1?this.extra.sh2?this.extra.sh3a&&this.extra.sh3b?3:2:1:0}setMaxSh(e){this.maxSh=e}fetchSplat({index:e,viewOrigin:t}){let n=((e,t)=>new es({extSplats:e,index:t}))(this.dyno,e);if(this.hasRgbDir()&&t){const r=Ni(n).outputs.center,i=Hs(Fs(r,t)),{sh1Texture:s,sh2Texture:a,sh3TextureA:o,sh3TextureB:l}=this.ensureShTextures();let{rgb:c}=na({coord:qi(e),viewDir:i,numSh:this.dynoNumSh,sh1Texture:s,sh2Texture:a,sh3TextureA:o,sh3TextureB:l});c=Us(c,Ni(n).outputs.rgb),n=$i({gsplat:n,rgb:c})}return n}ensureShTextures(){if(!this.extra.sh1)return{};let e=this.extra.sh1Texture;if(!e){let t=this.extra.sh1;const{width:n,height:i,depth:s,maxSplats:a}=gi(t.length/4);if(t.length<4*a){const e=new Uint32Array(4*a);e.set(t),this.extra.sh1=e,t=e}const o=ra(t,n,i,s,r.RGBAIntegerFormat,r.UnsignedIntType,"RGBA32UI");e=new Cs({value:o,key:"sh1"}),this.extra.sh1Texture=e}if(!this.extra.sh2)return{sh1Texture:e};let t=this.extra.sh2Texture;if(!t){let e=this.extra.sh2;const{width:n,height:i,depth:s,maxSplats:a}=gi(e.length/4);if(e.length<4*a){const t=new Uint32Array(4*a);t.set(e),this.extra.sh2=t,e=t}const o=ra(e,n,i,s,r.RGBAIntegerFormat,r.UnsignedIntType,"RGBA32UI");t=new Cs({value:o,key:"sh2"}),this.extra.sh2Texture=t}if(!this.extra.sh3a||!this.extra.sh3b)return{sh1Texture:e,sh2Texture:t};let n=this.extra.sh3TextureA;if(!n){let e=this.extra.sh3a;const{width:t,height:i,depth:s,maxSplats:a}=gi(e.length/4);if(e.length<4*a){const t=new Uint32Array(4*a);t.set(e),this.extra.sh3a=t,e=t}const o=ra(e,t,i,s,r.RGBAIntegerFormat,r.UnsignedIntType,"RGBA32UI");n=new Cs({value:o,key:"sh3"}),this.extra.sh3TextureA=n}let i=this.extra.sh3TextureB;if(!i){let e=this.extra.sh3b;const{width:t,height:n,depth:s,maxSplats:a}=gi(e.length/4);if(e.length<4*a){const t=new Uint32Array(4*a);t.set(e),this.extra.sh3b=t,e=t}const o=ra(e,t,n,s,r.RGBAIntegerFormat,r.UnsignedIntType,"RGBA32UI");i=new Cs({value:o,key:"sh3b"}),this.extra.sh3TextureB=i}return{sh1Texture:e,sh2Texture:t,sh3TextureA:n,sh3TextureB:i}}ensureSplats(e){const t=e<=this.maxSplats?this.maxSplats:Math.max(e,2*this.maxSplats),n=this.extArrays[0]?this.extArrays[0].length/4:0;if(!this.extArrays[0]||t>n){this.maxSplats=gi(t).maxSplats;const e=new Uint32Array(4*this.maxSplats),n=new Uint32Array(4*this.maxSplats);this.extArrays[0]&&(e.set(this.extArrays[0]),n.set(this.extArrays[1])),this.extArrays[0]=e,this.extArrays[1]=n}return this.extArrays}getSplat(e){if(e>=this.numSplats)throw new Error("Invalid index");return hi(this.extArrays,e)}setSplat(e,t,n,r,i,s){ui(this.ensureSplats(e+1),e,t.x,t.y,t.z,n.x,n.y,n.z,r.x,r.y,r.z,r.w,i,s.r,s.g,s.b),this.numSplats=Math.max(this.numSplats,e+1)}pushSplat(e,t,n,r,i){ui(this.ensureSplats(this.numSplats+1),this.numSplats,e.x,e.y,e.z,t.x,t.y,t.z,n.x,n.y,n.z,n.w,r,i.r,i.g,i.b),++this.numSplats}forEachSplat(e){if(this.numSplats)for(let t=0;t<this.numSplats;++t){const n=hi(this.extArrays,t);e(t,n.center,n.scales,n.quaternion,n.opacity,n.color)}}updateTextures(){if(this.textures[0]!==e.emptyTexture){const{width:t,height:n,depth:r}=this.textures[0].image;this.maxSplats!==t*n*r&&(this.textures[0].dispose(),this.textures[0]=e.emptyTexture,this.textures[1].dispose(),this.textures[1]=e.emptyTexture)}if(this.textures[0]===e.emptyTexture){const{width:e,height:t,depth:n}=gi(this.maxSplats);this.textures[0]=ra(this.extArrays[0],e,t,n,r.RGBAIntegerFormat,r.UnsignedIntType,"RGBA32UI"),this.textures[1]=ra(this.extArrays[1],e,t,n,r.RGBAIntegerFormat,r.UnsignedIntType,"RGBA32UI")}else this.extArrays[0].buffer!==this.textures[0].image.data.buffer&&(this.textures[0].image.data=new Uint8Array(this.extArrays[0].buffer),this.textures[1].image.data=new Uint8Array(this.extArrays[1].buffer),this.textures[0].needsUpdate=!0,this.textures[1].needsUpdate=!0)}extractSplats(t,n){const r=gi(t.length).maxSplats,i=new e({maxSplats:r});for(let e=0;e<t.length;e++){const r=this.getSplat(t[e]);if(n){let n=.61803398875*(t[e]>>>16);n-=Math.floor(n);const i=Math.max(0,Math.min(1,Math.abs(6*n-3)-1)),s=Math.max(0,Math.min(1,Math.abs(6*n+1)-1)),a=Math.max(0,Math.min(1,Math.abs(6*n-1)-1));r.color.r*=i,r.color.g*=s,r.color.b*=a}i.pushSplat(r.center,r.scales,r.quaternion,r.opacity,r.color)}return i}disposeLodSplats(){this.lodSplats&&(this.lodSplats.dispose(),this.lodSplats=void 0)}async createLodSplats({rgbaArray:t,quality:n}={}){const r="number"==typeof this.lod?Math.max(1.1,Math.min(2,this.lod)):n?1.75:1.5,i=[this.extArrays[0].slice(),this.extArrays[1].slice()],s=t?(await t.getArray()).slice():void 0,a={sh1:this.extra.sh1?this.extra.sh1.slice():void 0,sh2:this.extra.sh2?this.extra.sh2.slice():void 0,sh3:this.extra.sh3?this.extra.sh3.slice():void 0},o=await Li.withWorker((async e=>await e.call(n?"qualityLodExtSplats":"tinyLodExtSplats",{numSplats:this.numSplats,extArrays:i,extra:a,lodBase:r,rgba:s}))),l=new e(o);this.lodSplats&&this.lodSplats.dispose(),this.lodSplats=l,this.nonLod=!0,this.lod=!n||"quality"}};Ks.emptyArray=(()=>{const{width:e,height:t,depth:n,maxSplats:i}=gi(1),s=new Uint32Array(4*i),a=new r.DataArrayTexture(s,e,t,n);return a.format=r.RGBAIntegerFormat,a.type=r.UnsignedIntType,a.internalFormat="RGBA32UI",a.needsUpdate=!0,a})(),Ks.emptyTexture=ra(null,1,1,1,r.RGBAIntegerFormat,r.UnsignedIntType,"RGBA32UI"),Ks.emptyUint32x4=(()=>{const{width:e,height:t,depth:n,maxSplats:i}=gi(1),s=new Uint32Array(4*i),a=new r.DataArrayTexture(s,e,t,n);return a.format=r.RGBAIntegerFormat,a.type=r.UnsignedIntType,a.internalFormat="RGBA32UI",a.needsUpdate=!0,a})();let Qs=Ks;class Zs extends bs{constructor({extSplats:e}={}){super({key:"extSplats",type:Bi,globals:()=>[Zi],value:{textureArray1:Qs.emptyTexture,textureArray2:Qs.emptyTexture,numSplats:0},update:e=>{var t,n,r;return e.textureArray1=(null==(t=this.extSplats)?void 0:t.textures[0])??Qs.emptyTexture,e.textureArray2=(null==(n=this.extSplats)?void 0:n.textures[1])??Qs.emptyTexture,e.numSplats=(null==(r=this.extSplats)?void 0:r.numSplats)??0,e}}),this.extSplats=e}}const Js=Xr("\n vec3 evaluateExtSH1(uvec4 packedData, vec3 viewDir) {\n vec3 sh1_0 = decodeExtRgb(packedData.x);\n vec3 sh1_1 = decodeExtRgb(packedData.y);\n vec3 sh1_2 = decodeExtRgb(packedData.z);\n\n return sh1_0 * (-0.4886025 * viewDir.y)\n + sh1_1 * (0.4886025 * viewDir.z)\n + sh1_2 * (-0.4886025 * viewDir.x);\n }\n"),ea=Xr("\n vec3 evaluateExtSH12(uvec4 packed1, uvec4 packed2, vec3 viewDir) {\n vec3 sh1_0 = decodeExtRgb(packed1.x);\n vec3 sh1_1 = decodeExtRgb(packed1.y);\n vec3 sh1_2 = decodeExtRgb(packed1.z);\n\n vec3 sh2_0 = decodeExtRgb(packed1.w);\n vec3 sh2_1 = decodeExtRgb(packed2.x);\n vec3 sh2_2 = decodeExtRgb(packed2.y);\n vec3 sh2_3 = decodeExtRgb(packed2.z);\n vec3 sh2_4 = decodeExtRgb(packed2.w);\n\n vec3 sh1Rgb = sh1_0 * (-0.4886025 * viewDir.y)\n + sh1_1 * (0.4886025 * viewDir.z)\n + sh1_2 * (-0.4886025 * viewDir.x);\n\n vec3 sh2Rgb = sh2_0 * (1.0925484 * viewDir.x * viewDir.y)\n + sh2_1 * (-1.0925484 * viewDir.y * viewDir.z)\n + sh2_2 * (0.3153915 * (2.0 * viewDir.z * viewDir.z - viewDir.x * viewDir.x - viewDir.y * viewDir.y))\n + sh2_3 * (-1.0925484 * viewDir.x * viewDir.z)\n + sh2_4 * (0.5462742 * (viewDir.x * viewDir.x - viewDir.y * viewDir.y));\n\n return sh1Rgb + sh2Rgb;\n }\n"),ta=Xr("\n vec3 evaluateExtSH3(uvec4 packedA, uvec4 packedB, vec3 viewDir) {\n vec3 sh3_0 = decodeExtRgb(packedA.x);\n vec3 sh3_1 = decodeExtRgb(packedA.y);\n vec3 sh3_2 = decodeExtRgb(packedA.z);\n vec3 sh3_3 = decodeExtRgb(packedA.w);\n vec3 sh3_4 = decodeExtRgb(packedB.x);\n vec3 sh3_5 = decodeExtRgb(packedB.y);\n vec3 sh3_6 = decodeExtRgb(packedB.z);\n\n float xx = viewDir.x * viewDir.x;\n float yy = viewDir.y * viewDir.y;\n float zz = viewDir.z * viewDir.z;\n float xy = viewDir.x * viewDir.y;\n float yz = viewDir.y * viewDir.z;\n float zx = viewDir.z * viewDir.x;\n\n return sh3_0 * (-0.5900436 * viewDir.y * (3.0 * xx - yy))\n + sh3_1 * (2.8906114 * xy * viewDir.z) +\n + sh3_2 * (-0.4570458 * viewDir.y * (4.0 * zz - xx - yy))\n + sh3_3 * (0.3731763 * viewDir.z * (2.0 * zz - 3.0 * xx - 3.0 * yy))\n + sh3_4 * (-0.4570458 * viewDir.x * (4.0 * zz - xx - yy))\n + sh3_5 * (1.4453057 * viewDir.z * (xx - yy))\n + sh3_6 * (-0.5900436 * viewDir.x * (xx - 3.0 * yy));\n }\n");function na({coord:e,viewDir:t,numSh:n,sh1Texture:r,sh2Texture:i,sh3TextureA:s,sh3TextureB:a}){return new $r({inTypes:{coord:"ivec3",viewDir:"vec3",numSh:"int",sh1Texture:"usampler2DArray",sh2Texture:"usampler2DArray",sh3TextureA:"usampler2DArray",sh3TextureB:"usampler2DArray"},outTypes:{rgb:"vec3"},inputs:{coord:e,viewDir:t,numSh:n,sh1Texture:r,sh2Texture:i,sh3TextureA:s,sh3TextureB:a},globals:()=>[Js,ea,ta],statements:({inputs:e,outputs:t})=>{const n=["vec3 rgb = vec3(0.0);"];return e.sh1Texture&&(e.sh2Texture?(n.push(...Wr(`\n if (${e.numSh} == 1) {\n rgb = evaluateExtSH1(texelFetch(${e.sh1Texture}, ${e.coord}, 0), ${e.viewDir});\n } else if (${e.numSh} >= 2) {\n rgb = evaluateExtSH12(texelFetch(${e.sh1Texture}, ${e.coord}, 0), texelFetch(${e.sh2Texture}, ${e.coord}, 0), ${e.viewDir});\n `)),e.sh3TextureA&&e.sh3TextureB&&n.push(...Wr(`\n if (${e.numSh} >= 3) {\n rgb += evaluateExtSH3(texelFetch(${e.sh3TextureA}, ${e.coord}, 0), texelFetch(${e.sh3TextureB}, ${e.coord}, 0), ${e.viewDir});\n }\n `)),n.push("}")):n.push(...Wr(`\n if (${e.numSh} >= 1) {\n rgb = evaluateExtSH1(texelFetch(${e.sh1Texture}, ${e.coord}, 0), ${e.viewDir});\n }\n `))),n.push(`${t.rgb} = rgb;`),n}}).outputs}function ra(e,t,n,i,s,a,o){const l=new r.DataArrayTexture(e,t,n,i);return l.format=s,l.type=a,l.internalFormat=o,l.needsUpdate=!0,l}function ia(e){const t=Ta.decode_rad_header(e);if(t[2])throw xa(t[1]);return xa(t[0])}function sa(e,t,n,r,i,s,a,o,l,c){return Ta.raycast_ext_buffers(e,t,n,r,i,s,a,o,l,c)}function aa(e,t,n,r,i,s,a,o,l,c,u,h,d){return Ta.raycast_packed_buffer(e,t,n,r,i,s,a,o,l,c,u,h,d)}function oa(){const e={__proto__:null,__wbg_Error_2e59b1b37a9a34c3:function(e,t){return Error(pa(e,t))},__wbg___wbindgen_throw_81fc77679af83bc6:function(e,t){throw new Error(pa(e,t))},__wbg_error_a6fa202b58aa1cd3:function(e,t){let n,r;try{n=e,r=t}finally{Ta.__wbindgen_free(n,r,1)}},__wbg_length_0c32cb8543c8e4c8:function(e){return e.length},__wbg_length_1e701798fdcaa3b4:function(e){return e.length},__wbg_length_fd4646b401926788:function(e){return e.length},__wbg_new_227d7c05414eb861:function(){return new Error},__wbg_new_4f9fafbb3909af72:function(){return new Object},__wbg_new_f3c9df4f38f3f798:function(){return new Array},__wbg_new_with_length_26bffbe236bf73f9:function(e){return new Float32Array(e>>>0)},__wbg_prototypesetcall_3e05eb9545565046:function(e,t,n){var r,i;Uint8Array.prototype.set.call((r=e,i=t,r>>>=0,ga().subarray(r/1,r/1+i)),n)},__wbg_prototypesetcall_e42275e601e14eeb:function(e,t,n){Uint32Array.prototype.set.call(ca(e,t),n)},__wbg_set_6be42768c690e380:function(e,t,n){e[t]=n},__wbg_set_6c60b2e8ad0e9383:function(e,t,n){e[t>>>0]=n},__wbg_set_8ee2d34facb8466e:function(){return function(e,t){try{return e.apply(this,t)}catch(Jm){const t=function(e){const t=Ta.__externref_table_alloc();return Ta.__wbindgen_externrefs.set(t,e),t}(Jm);Ta.__wbindgen_exn_store(t)}}((function(e,t,n){return Reflect.set(e,t,n)}),arguments)},__wbg_set_a98c8da6557e63de:function(e,t,n){e.set(la(t,n))},__wbg_stack_3b0d974bbf31e44f:function(e,t){const n=function(e,t,n){if(void 0===n){const n=wa.encode(e),r=t(n.length,1)>>>0;return ga().subarray(r,r+n.length).set(n),Sa=n.length,r}let r=e.length,i=t(r,1)>>>0;const s=ga();let a=0;for(;a<r;a++){const t=e.charCodeAt(a);if(t>127)break;s[i+a]=t}if(a!==r){0!==a&&(e=e.slice(a)),i=n(i,r,r=a+3*e.length,1)>>>0;const t=ga().subarray(i+a,i+r);a+=wa.encodeInto(e,t).written,i=n(i,r,a,1)>>>0}return Sa=a,i}(t.stack,Ta.__wbindgen_malloc,Ta.__wbindgen_realloc),r=Sa;ha().setInt32(e+4,r,!0),ha().setInt32(e+0,n,!0)},__wbg_subarray_d51e89458b3fdbf6:function(e,t,n){return e.subarray(t>>>0,n>>>0)},__wbindgen_cast_0000000000000001:function(e){return e},__wbindgen_cast_0000000000000002:function(e,t){return la(e,t)},__wbindgen_cast_0000000000000003:function(e,t){return ca(e,t)},__wbindgen_cast_0000000000000004:function(e,t){return pa(e,t)},__wbindgen_cast_0000000000000005:function(e){return BigInt.asUintN(64,e)},__wbindgen_init_externref_table:function(){const e=Ta.__wbindgen_externrefs,t=e.grow(4);e.set(0,void 0),e.set(t+0,void 0),e.set(t+1,null),e.set(t+2,!0),e.set(t+3,!1)}};return{__proto__:null,"./spark_rs_bg.js":e}}function la(e,t){return e>>>=0,function(){null!==da&&0!==da.byteLength||(da=new Float32Array(Ta.memory.buffer));return da}().subarray(e/4,e/4+t)}function ca(e,t){return e>>>=0,function(){null!==ma&&0!==ma.byteLength||(ma=new Uint32Array(Ta.memory.buffer));return ma}().subarray(e/4,e/4+t)}let ua=null;function ha(){return(null===ua||!0===ua.buffer.detached||void 0===ua.buffer.detached&&ua.buffer!==Ta.memory.buffer)&&(ua=new DataView(Ta.memory.buffer)),ua}let da=null;function pa(e,t){return function(e,t){ba+=t,ba>=va&&(ya=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}),ya.decode(),ba=t);return ya.decode(ga().subarray(e,e+t))}(e>>>=0,t)}let ma=null;let fa=null;function ga(){return null!==fa&&0!==fa.byteLength||(fa=new Uint8Array(Ta.memory.buffer)),fa}function xa(e){const t=Ta.__wbindgen_externrefs.get(e);return Ta.__externref_table_dealloc(e),t}let ya=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0});ya.decode();const va=2146435072;let ba=0;const wa=new TextEncoder;"encodeInto"in wa||(wa.encodeInto=function(e,t){const n=wa.encode(e);return t.set(n),{read:e.length,written:n.length}});let Ta,Sa=0;async function _a(e){if(void 0!==Ta)return Ta;void 0!==e&&Object.getPrototypeOf(e)===Object.prototype&&({module_or_path:e}=e),void 0===e&&(e="undefined"==typeof document?require("url").pathToFileURL(__dirname+"/assets/viewer/spark-8b93f8c03d97.wasm").href:new URL("assets/viewer/spark-8b93f8c03d97.wasm",document.currentScript&&"SCRIPT"===document.currentScript.tagName.toUpperCase()&&document.currentScript.src||document.baseURI).href);const t=oa();("string"==typeof e||"function"==typeof Request&&e instanceof Request||"function"==typeof URL&&e instanceof URL)&&(e=fetch(e));const{instance:n,module:r}=await async function(e,t){if("function"==typeof Response&&e instanceof Response){if("function"==typeof WebAssembly.instantiateStreaming)try{return await WebAssembly.instantiateStreaming(e,t)}catch(Jm){if(!e.ok||!function(e){switch(e){case"basic":case"cors":case"default":return!0}return!1}(e.type)||"application/wasm"===e.headers.get("Content-Type"))throw Jm}const n=await e.arrayBuffer();return await WebAssembly.instantiate(n,t)}{const n=await WebAssembly.instantiate(e,t);return n instanceof WebAssembly.Instance?{instance:n,module:e}:n}}(await e,t);return function(e){return Ta=e.exports,ua=null,da=null,ma=null,fa=null,Ta.__wbindgen_start(),Ta}(n)}let Ma=null;function Aa(){return Ma||(r.ShaderChunk.splatDefines="const float LN_SCALE_MIN = -12.0;\nconst float LN_SCALE_MAX = 9.0;\n\nconst uint SPLAT_TEX_WIDTH_BITS = 11u;\nconst uint SPLAT_TEX_HEIGHT_BITS = 11u;\nconst uint SPLAT_TEX_DEPTH_BITS = 11u;\nconst uint SPLAT_TEX_LAYER_BITS = SPLAT_TEX_WIDTH_BITS + SPLAT_TEX_HEIGHT_BITS;\n\nconst uint SPLAT_TEX_WIDTH = 1u << SPLAT_TEX_WIDTH_BITS;\nconst uint SPLAT_TEX_HEIGHT = 1u << SPLAT_TEX_HEIGHT_BITS;\nconst uint SPLAT_TEX_DEPTH = 1u << SPLAT_TEX_DEPTH_BITS;\n\nconst uint SPLAT_TEX_WIDTH_MASK = SPLAT_TEX_WIDTH - 1u;\nconst uint SPLAT_TEX_HEIGHT_MASK = SPLAT_TEX_HEIGHT - 1u;\nconst uint SPLAT_TEX_DEPTH_MASK = SPLAT_TEX_DEPTH - 1u;\n\nconst uint F16_INF = 0x7c00u;\nconst float PI = 3.1415926535897932384626433832795;\n\nconst float INFINITY = 1.0 / 0.0;\nconst float NEG_INFINITY = -INFINITY;\n\nfloat sqr(float x) {\n return x * x;\n}\n\nfloat pow4(float x) {\n float x2 = x * x;\n return x2 * x2;\n}\n\nfloat pow8(float x) {\n float x4 = pow4(x);\n return x4 * x4;\n}\n\nvec3 srgbToLinear(vec3 rgb) {\n return pow(rgb, vec3(2.2));\n}\n\nvec3 linearToSrgb(vec3 rgb) {\n return pow(rgb, vec3(1.0 / 2.2));\n}\n\nuint encodeQuatOctXy88R8(vec4 q) {\n \n if (q.w < 0.0) {\n q = -q;\n }\n \n float theta = 2.0 * acos(q.w);\n float halfTheta = theta * 0.5;\n float s = sin(halfTheta);\n \n vec3 axis = (abs(s) < 1e-6) ? vec3(1.0, 0.0, 0.0) : q.xyz / s;\n \n \n \n float sum = abs(axis.x) + abs(axis.y) + abs(axis.z);\n vec2 p = vec2(axis.x, axis.y) / sum;\n \n if (axis.z < 0.0) {\n float oldPx = p.x;\n p.x = (1.0 - abs(p.y)) * (p.x >= 0.0 ? 1.0 : -1.0);\n p.y = (1.0 - abs(oldPx)) * (p.y >= 0.0 ? 1.0 : -1.0);\n }\n \n float u_f = p.x * 0.5 + 0.5;\n float v_f = p.y * 0.5 + 0.5;\n \n uint quantU = uint(clamp(round(u_f * 255.0), 0.0, 255.0));\n uint quantV = uint(clamp(round(v_f * 255.0), 0.0, 255.0));\n \n \n \n uint angleInt = uint(clamp(round((theta / 3.14159265359) * 255.0), 0.0, 255.0));\n \n \n return (angleInt << 16u) | (quantV << 8u) | quantU;\n}\n\nvec4 decodeQuatOctXy88R8(uint encoded) {\n \n uint quantU = encoded & uint(0xFFu); \n uint quantV = (encoded >> 8u) & uint(0xFFu); \n uint angleInt = encoded >> 16u; \n\n \n float u_f = float(quantU) / 255.0;\n float v_f = float(quantV) / 255.0;\n vec2 f = vec2(u_f * 2.0 - 1.0, v_f * 2.0 - 1.0);\n\n vec3 axis = vec3(f.xy, 1.0 - abs(f.x) - abs(f.y));\n float t = max(-axis.z, 0.0);\n axis.x += (axis.x >= 0.0) ? -t : t;\n axis.y += (axis.y >= 0.0) ? -t : t;\n axis = normalize(axis);\n \n \n float theta = (float(angleInt) / 255.0) * 3.14159265359;\n float halfTheta = theta * 0.5;\n float s = sin(halfTheta);\n float w = cos(halfTheta);\n \n return vec4(axis * s, w);\n}\n\nuint encodeQuatOctXy1010R12(vec4 q) {\n \n if (q.w < 0.0) {\n q = -q;\n }\n \n float halfTheta = acos(q.w);\n float theta = 2.0 * halfTheta;\n float s = sin(halfTheta);\n \n vec3 axis = (abs(s) < 1e-6) ? vec3(1.0, 0.0, 0.0) : q.xyz / s;\n \n \n \n float sum = abs(axis.x) + abs(axis.y) + abs(axis.z);\n vec2 p = vec2(axis.x, axis.y) / sum;\n \n if (axis.z < 0.0) {\n float oldPx = p.x;\n p.x = (1.0 - abs(p.y)) * (p.x >= 0.0 ? 1.0 : -1.0);\n p.y = (1.0 - abs(oldPx)) * (p.y >= 0.0 ? 1.0 : -1.0);\n }\n \n float u_f = p.x * 0.5 + 0.5;\n float v_f = p.y * 0.5 + 0.5;\n \n uint quantU = uint(clamp(round(u_f * 1023.0), 0.0, 1023.0));\n uint quantV = uint(clamp(round(v_f * 1023.0), 0.0, 1023.0));\n \n \n \n uint angleInt = uint(clamp(round((theta / PI) * 4095.0), 0.0, 4095.0));\n \n \n return (angleInt << 20u) | (quantV << 10u) | quantU;\n}\n\nvec4 decodeQuatOctXy1010R12(uint encoded) {\n \n uint quantU = encoded & uint(0x3FFu); \n uint quantV = (encoded >> 10u) & uint(0x3FFu); \n uint angleInt = encoded >> 20u; \n\n \n float u_f = float(quantU) / 1023.0;\n float v_f = float(quantV) / 1023.0;\n vec2 f = vec2(u_f * 2.0 - 1.0, v_f * 2.0 - 1.0);\n\n vec3 axis = vec3(f.xy, 1.0 - abs(f.x) - abs(f.y));\n float t = max(-axis.z, 0.0);\n axis.x += (axis.x >= 0.0) ? -t : t;\n axis.y += (axis.y >= 0.0) ? -t : t;\n axis = normalize(axis);\n \n \n float theta = (float(angleInt) / 4095.0) * PI;\n float halfTheta = theta * 0.5;\n float s = sin(halfTheta);\n float w = cos(halfTheta);\n \n return vec4(axis * s, w);\n}\n\nuvec4 packSplatEncoding(\n vec3 center, vec3 scales, vec4 quaternion, vec4 rgba, vec4 rgbMinMaxLnScaleMinMax\n) {\n float rgbMin = rgbMinMaxLnScaleMinMax.x;\n float rgbMax = rgbMinMaxLnScaleMinMax.y;\n vec3 encRgb = (rgba.rgb - vec3(rgbMin)) / (rgbMax - rgbMin);\n uvec4 uRgba = uvec4(round(clamp(vec4(encRgb, rgba.a) * 255.0, 0.0, 255.0)));\n\n uint uQuat = encodeQuatOctXy88R8(quaternion);\n \n \n uvec3 uQuat3 = uvec3(uQuat & 0xffu, (uQuat >> 8u) & 0xffu, (uQuat >> 16u) & 0xffu);\n\n \n float lnScaleMin = rgbMinMaxLnScaleMinMax.z;\n float lnScaleMax = rgbMinMaxLnScaleMinMax.w;\n float lnScaleScale = 254.0 / (lnScaleMax - lnScaleMin);\n uvec3 uScales = uvec3(\n (scales.x == 0.0) ? 0u : uint(round(clamp((log(scales.x) - lnScaleMin) * lnScaleScale, 0.0, 254.0))) + 1u,\n (scales.y == 0.0) ? 0u : uint(round(clamp((log(scales.y) - lnScaleMin) * lnScaleScale, 0.0, 254.0))) + 1u,\n (scales.z == 0.0) ? 0u : uint(round(clamp((log(scales.z) - lnScaleMin) * lnScaleScale, 0.0, 254.0))) + 1u\n );\n\n \n uint word0 = uRgba.r | (uRgba.g << 8u) | (uRgba.b << 16u) | (uRgba.a << 24u);\n uint word1 = packHalf2x16(center.xy);\n uint word2 = packHalf2x16(vec2(center.z, 0.0)) | (uQuat3.x << 16u) | (uQuat3.y << 24u);\n uint word3 = uScales.x | (uScales.y << 8u) | (uScales.z << 16u) | (uQuat3.z << 24u);\n return uvec4(word0, word1, word2, word3);\n}\n\nuvec4 packSplat(vec3 center, vec3 scales, vec4 quaternion, vec4 rgba) {\n return packSplatEncoding(center, scales, quaternion, rgba, vec4(0.0, 1.0, LN_SCALE_MIN, LN_SCALE_MAX));\n}\n\nvoid unpackSplatEncoding(uvec4 packedData, out vec3 center, out vec3 scales, out vec4 quaternion, out vec4 rgba, vec4 rgbMinMaxLnScaleMinMax) {\n uint word0 = packedData.x, word1 = packedData.y, word2 = packedData.z, word3 = packedData.w;\n\n uvec4 uRgba = uvec4(word0 & 0xffu, (word0 >> 8u) & 0xffu, (word0 >> 16u) & 0xffu, (word0 >> 24u) & 0xffu);\n float rgbMin = rgbMinMaxLnScaleMinMax.x;\n float rgbMax = rgbMinMaxLnScaleMinMax.y;\n rgba = (vec4(uRgba) / 255.0);\n rgba.rgb = rgba.rgb * (rgbMax - rgbMin) + rgbMin;\n\n center = vec4(\n unpackHalf2x16(word1),\n unpackHalf2x16(word2 & 0xffffu)\n ).xyz;\n\n uvec3 uScales = uvec3(word3 & 0xffu, (word3 >> 8u) & 0xffu, (word3 >> 16u) & 0xffu);\n float lnScaleMin = rgbMinMaxLnScaleMinMax.z;\n float lnScaleMax = rgbMinMaxLnScaleMinMax.w;\n float lnScaleScale = (lnScaleMax - lnScaleMin) / 254.0;\n scales = vec3(\n (uScales.x == 0u) ? 0.0 : exp(lnScaleMin + float(uScales.x - 1u) * lnScaleScale),\n (uScales.y == 0u) ? 0.0 : exp(lnScaleMin + float(uScales.y - 1u) * lnScaleScale),\n (uScales.z == 0u) ? 0.0 : exp(lnScaleMin + float(uScales.z - 1u) * lnScaleScale)\n );\n\n uint uQuat = ((word2 >> 16u) & 0xFFFFu) | ((word3 >> 8u) & 0xFF0000u);\n quaternion = decodeQuatOctXy88R8(uQuat);\n \n \n}\n\nvoid unpackSplat(uvec4 packedData, out vec3 center, out vec3 scales, out vec4 quaternion, out vec4 rgba) {\n unpackSplatEncoding(packedData, center, scales, quaternion, rgba, vec4(0.0, 1.0, LN_SCALE_MIN, LN_SCALE_MAX));\n}\n\nuvec4 packSplatCovEncoding(\n vec3 center, vec4 rgba, vec3 xxyyzz, vec3 xyxzyz, vec4 rgbMinMaxLnScaleMinMax\n) {\n float rgbMin = rgbMinMaxLnScaleMinMax.x;\n float rgbMax = rgbMinMaxLnScaleMinMax.y;\n vec3 encRgb = (rgba.rgb - vec3(rgbMin)) / (rgbMax - rgbMin);\n uvec4 uRgba = uvec4(round(clamp(vec4(encRgb, rgba.a) * 255.0, 0.0, 255.0)));\n\n float lnScaleMin = rgbMinMaxLnScaleMinMax.z;\n float lnScaleMax = rgbMinMaxLnScaleMinMax.w;\n float diagScale = 255.0 / (2.0 * (lnScaleMax - lnScaleMin));\n uvec3 uXxyyzz = uvec3(round(clamp((log(xxyyzz) - 2.0 * lnScaleMin) * diagScale, 0.0, 255.0)));\n\n vec3 xyxzyzCor = vec3(\n clamp(xyxzyz.x / sqrt(xxyyzz.x * xxyyzz.y), -1.0, 1.0),\n clamp(xyxzyz.y / sqrt(xxyyzz.x * xxyyzz.z), -1.0, 1.0),\n clamp(xyxzyz.z / sqrt(xxyyzz.y * xxyyzz.z), -1.0, 1.0)\n );\n ivec3 iXyxzyzCor = ivec3(round(xyxzyzCor * 127.0));\n\n \n uint word0 = uRgba.r | (uRgba.g << 8u) | (uRgba.b << 16u) | (uRgba.a << 24u);\n uint word1 = packHalf2x16(center.xy);\n uint word2 = packHalf2x16(vec2(center.z, 0.0)) |\n ((uint(iXyxzyzCor.y) & 0xffu) << 16u) |\n ((uint(iXyxzyzCor.z) & 0xffu) << 24u);\n uint word3 =\n uXxyyzz.x | (uXxyyzz.y << 8u) | (uXxyyzz.z << 16u) |\n ((uint(iXyxzyzCor.x) & 0xffu) << 24u);\n return uvec4(word0, word1, word2, word3);\n}\n\nvoid unpackSplatCovEncoding(uvec4 packedData, out vec3 center, out vec4 rgba, out vec3 xxyyzz, out vec3 xyxzyz, vec4 rgbMinMaxLnScaleMinMax) {\n uint word0 = packedData.x, word1 = packedData.y, word2 = packedData.z, word3 = packedData.w;\n\n uvec4 uRgba = uvec4(word0 & 0xffu, (word0 >> 8u) & 0xffu, (word0 >> 16u) & 0xffu, (word0 >> 24u) & 0xffu);\n float rgbMin = rgbMinMaxLnScaleMinMax.x;\n float rgbMax = rgbMinMaxLnScaleMinMax.y;\n rgba = (vec4(uRgba) / 255.0);\n rgba.rgb = rgba.rgb * (rgbMax - rgbMin) + rgbMin;\n\n center = vec3(\n unpackHalf2x16(word1),\n unpackHalf2x16(word2 & 0xffffu).x\n );\n\n uvec3 uXxyyzz = uvec3(word3 & 0xffu, (word3 >> 8u) & 0xffu, (word3 >> 16u) & 0xffu);\n ivec3 iXyxzyzCor = ivec3(int(word3) >> 24, int(word2 << 8u) >> 24, int(word2) >> 24);\n\n float lnScaleMin = rgbMinMaxLnScaleMinMax.z;\n float lnScaleMax = rgbMinMaxLnScaleMinMax.w;\n float diagScale = 2.0 * (lnScaleMax - lnScaleMin) / 255.0;\n xxyyzz = exp(2.0 * lnScaleMin + vec3(uXxyyzz) * diagScale);\n\n vec3 xyxzyzCor = vec3(iXyxzyzCor) / 127.0;\n xyxzyz = xyxzyzCor * vec3(\n sqrt(xxyyzz.x * xxyyzz.y),\n sqrt(xxyyzz.x * xxyyzz.z),\n sqrt(xxyyzz.y * xxyyzz.z)\n );\n}\n\nvoid packSplatExtCov(\n out uvec4 packedData, out uvec4 packedData2,\n vec3 center, vec4 rgba, vec3 xxyyzz, vec3 xyxzyz\n) {\n packedData.x = floatBitsToUint(center.x);\n packedData.y = floatBitsToUint(center.y);\n packedData.z = floatBitsToUint(center.z);\n packedData.w = packHalf2x16(vec2(rgba.a, rgba.b));\n packedData2.x = packHalf2x16(rgba.rg);\n\n vec3 xyxzyzCor = vec3(\n clamp(xyxzyz.x / sqrt(xxyyzz.x * xxyyzz.y), -1.0, 1.0),\n clamp(xyxzyz.y / sqrt(xxyyzz.x * xxyyzz.z), -1.0, 1.0),\n clamp(xyxzyz.z / sqrt(xxyyzz.y * xxyyzz.z), -1.0, 1.0)\n );\n xyxzyzCor = sign(xyxzyzCor) * clamp(log(abs(xyxzyzCor)), -100.0, -0.0000001);\n xxyyzz = log(xxyyzz);\n\n packedData2.y = packHalf2x16(vec2(xxyyzz.x, xxyyzz.y));\n packedData2.z = packHalf2x16(vec2(xxyyzz.z, xyxzyzCor.x));\n packedData2.w = packHalf2x16(vec2(xyxzyzCor.y, xyxzyzCor.z));\n}\n\nvoid unpackSplatExtCov(\n uvec4 packedData, uvec4 packedData2,\n out vec3 center, out vec4 rgba, out vec3 xxyyzz, out vec3 xyxzyz\n) {\n center.x = uintBitsToFloat(packedData.x);\n center.y = uintBitsToFloat(packedData.y);\n center.z = uintBitsToFloat(packedData.z);\n\n vec2 ab = unpackHalf2x16(packedData.w);\n vec2 rg = unpackHalf2x16(packedData2.x);\n rgba = vec4(rg, ab.y, ab.x);\n\n vec2 xxyy = unpackHalf2x16(packedData2.y);\n vec2 zzxy = unpackHalf2x16(packedData2.z);\n vec2 xzyz = unpackHalf2x16(packedData2.w);\n xxyyzz = exp(vec3(xxyy.x, xxyy.y, zzxy.x));\n xyxzyz = vec3(zzxy.y, xzyz.x, xzyz.y);\n xyxzyz = -sign(xyxzyz) * exp(-abs(xyxzyz));\n xyxzyz *= vec3(\n sqrt(xxyyzz.x * xxyyzz.y),\n sqrt(xxyyzz.x * xxyyzz.z),\n sqrt(xxyyzz.y * xxyyzz.z)\n );\n}\n\nvoid packSplatExt(\n out uvec4 packedData, out uvec4 packedData2,\n vec3 center, vec3 scales, vec4 quaternion, vec4 rgba\n) {\n packedData.x = floatBitsToUint(center.x);\n packedData.y = floatBitsToUint(center.y);\n packedData.z = floatBitsToUint(center.z);\n packedData.w = packHalf2x16(vec2(rgba.a, 0.0));\n\n packedData2.x = packHalf2x16(rgba.rg);\n packedData2.y = packHalf2x16(vec2(rgba.b, log(scales.x)));\n packedData2.z = packHalf2x16(log(scales.yz));\n packedData2.w = encodeQuatOctXy1010R12(quaternion);\n}\n\nvec4 unpackSplatExtCenterAlpha(uvec4 packedData) {\n return vec4(\n uintBitsToFloat(packedData.x),\n uintBitsToFloat(packedData.y),\n uintBitsToFloat(packedData.z),\n unpackHalf2x16(packedData.w).x\n );\n}\n\nfloat unpackSplatExtAlpha(uvec4 packedData) {\n return unpackHalf2x16(packedData.w).x;\n}\n\nvoid unpackSplatExt(\n uvec4 packedData, uvec4 packedData2,\n out vec3 center, out vec3 scales, out vec4 quaternion, out vec4 rgba\n) {\n center.x = uintBitsToFloat(packedData.x);\n center.y = uintBitsToFloat(packedData.y);\n center.z = uintBitsToFloat(packedData.z);\n rgba.a = unpackHalf2x16(packedData.w).x;\n\n rgba.rg = unpackHalf2x16(packedData2.x);\n vec2 split = unpackHalf2x16(packedData2.y);\n rgba.b = split.x;\n scales.x = exp(split.y);\n scales.yz = exp(unpackHalf2x16(packedData2.z));\n quaternion = decodeQuatOctXy1010R12(packedData2.w);\n}\n\nuint encodeExtRgb(vec3 rgb) {\n vec3 absRgb = abs(rgb);\n float maxAbs = max(absRgb.r, max(absRgb.g, absRgb.b));\n\n int base = clamp(int(floor(log2(maxAbs))) + 15, 0, 31);\n float divisor = exp2(float(base - 15)) / 255.0;\n\n uvec3 uRgb = uvec3(round(clamp(absRgb / divisor, 0.0, 255.0)));\n uint expSigns = (uint(base) << 3u) | ((rgb.r < 0.0 ? 0x1u : 0u) | (rgb.g < 0.0 ? 0x2u : 0u) | (rgb.b < 0.0 ? 0x4u : 0u));\n return uRgb.r | (uRgb.g << 8u) | (uRgb.b << 16u) | (expSigns << 24u);\n}\n\nvec3 decodeExtRgb(uint encoded) {\n uint biasedBase = (encoded >> 27u) & 0x1fu;\n float divisor = exp2(float(int(biasedBase) - 15)) / 255.0;\n\n vec3 rgb = vec3(uvec3(encoded & 0xffu, (encoded >> 8u) & 0xffu, (encoded >> 16u) & 0xffu));\n rgb *= divisor;\n\n return vec3(\n ((encoded & 0x1000000u) != 0u) ? -rgb.r : rgb.r,\n ((encoded & 0x2000000u) != 0u) ? -rgb.g : rgb.g,\n ((encoded & 0x4000000u) != 0u) ? -rgb.b : rgb.b\n );\n}\n\nvec3 quatVec(vec4 q, vec3 v) {\n \n vec3 t = 2.0 * cross(q.xyz, v);\n return v + q.w * t + cross(q.xyz, t);\n}\n\nvec4 quatQuat(vec4 q1, vec4 q2) {\n return vec4(\n q1.w * q2.x + q1.x * q2.w + q1.y * q2.z - q1.z * q2.y,\n q1.w * q2.y - q1.x * q2.z + q1.y * q2.w + q1.z * q2.x,\n q1.w * q2.z + q1.x * q2.y - q1.y * q2.x + q1.z * q2.w,\n q1.w * q2.w - q1.x * q2.x - q1.y * q2.y - q1.z * q2.z\n );\n}\n\nmat3 quaternionToMatrix(vec4 q) {\n return mat3(\n (1.0 - 2.0 * (q.y * q.y + q.z * q.z)),\n (2.0 * (q.x * q.y + q.w * q.z)),\n (2.0 * (q.x * q.z - q.w * q.y)),\n (2.0 * (q.x * q.y - q.w * q.z)),\n (1.0 - 2.0 * (q.x * q.x + q.z * q.z)),\n (2.0 * (q.y * q.z + q.w * q.x)),\n (2.0 * (q.x * q.z + q.w * q.y)),\n (2.0 * (q.y * q.z - q.w * q.x)),\n (1.0 - 2.0 * (q.x * q.x + q.y * q.y))\n );\n}\n\nmat3 scaleQuaternionToMatrix(vec3 s, vec4 q) {\n \n return mat3(\n s.x * (1.0 - 2.0 * (q.y * q.y + q.z * q.z)),\n s.x * (2.0 * (q.x * q.y + q.w * q.z)),\n s.x * (2.0 * (q.x * q.z - q.w * q.y)),\n s.y * (2.0 * (q.x * q.y - q.w * q.z)),\n s.y * (1.0 - 2.0 * (q.x * q.x + q.z * q.z)),\n s.y * (2.0 * (q.y * q.z + q.w * q.x)),\n s.z * (2.0 * (q.x * q.z + q.w * q.y)),\n s.z * (2.0 * (q.y * q.z - q.w * q.x)),\n s.z * (1.0 - 2.0 * (q.x * q.x + q.y * q.y))\n );\n}\n\nvec4 slerp(vec4 q1, vec4 q2, float t) {\n \n float cosHalfTheta = dot(q1, q2);\n\n \n if (abs(cosHalfTheta) >= 0.999) {\n return q1;\n }\n \n \n \n if (cosHalfTheta < 0.0) {\n q2 = -q2;\n cosHalfTheta = -cosHalfTheta;\n }\n\n \n float halfTheta = acos(cosHalfTheta);\n float sinHalfTheta = sqrt(1.0 - cosHalfTheta * cosHalfTheta);\n\n \n float ratioA = sin((1.0 - t) * halfTheta) / sinHalfTheta;\n float ratioB = sin(t * halfTheta) / sinHalfTheta;\n\n \n return q1 * ratioA + q2 * ratioB;\n}\n\nivec3 splatTexCoord(int index) {\n uint x = uint(index) & SPLAT_TEX_WIDTH_MASK;\n uint y = (uint(index) >> SPLAT_TEX_WIDTH_BITS) & SPLAT_TEX_HEIGHT_MASK;\n uint z = uint(index) >> SPLAT_TEX_LAYER_BITS;\n return ivec3(x, y, z);\n}\n\nivec3 pagedSplatTexCoord(int index) {\n return ivec3(index & 255, (index >> 8) & 255, index >> 16);\n}\n\nvec4 uintToVec4(uint u32) {\n uvec4 bytes = uvec4(\n u32 & 0xFFu,\n (u32 >> 8u) & 0xFFu,\n (u32 >> 16u) & 0xFFu,\n (u32 >> 24u) & 0xFFu\n );\n return vec4(bytes) / 255.0;\n}\n\nvec4 floatToVec4(float f) {\n uint u32 = floatBitsToUint(f);\n return uintToVec4(u32);\n}\n\nvec3 debugColorHue(uint i) {\n \n float hue = fract(float(i) * 0.61803398875);\n \n vec3 rgb = clamp(abs(mod(hue*6.0 + vec3(0.0,4.0,2.0), 6.0) - 3.0) - 1.0, 0.0, 1.0);\n return mix(vec3(1.0), rgb, 0.85); \n}",Ma={oldSplatVertex:"precision highp float;\nprecision highp int;\nprecision highp usampler2DArray;\n\n#include <splatDefines>\n\nattribute uint splatIndex;\n\nout vec4 vRgba;\nout vec2 vSplatUv;\nout vec3 vNdc;\nflat out uint vSplatIndex;\n\nuniform vec2 renderSize;\nuniform uint numSplats;\nuniform vec4 renderToViewQuat;\nuniform vec3 renderToViewPos;\nuniform float maxStdDev;\nuniform float minPixelRadius;\nuniform float maxPixelRadius;\nuniform float time;\nuniform float deltaTime;\nuniform bool debugFlag;\nuniform float minAlpha;\nuniform bool stochastic;\nuniform bool enable2DGS;\nuniform float blurAmount;\nuniform float preBlurAmount;\nuniform float focalDistance;\nuniform float apertureAngle;\nuniform float clipXY;\nuniform float focalAdjustment;\n\nuniform usampler2DArray packedSplats;\nuniform vec4 rgbMinMaxLnScaleMinMax;\n\nvoid main() {\n \n gl_Position = vec4(0.0, 0.0, 2.0, 1.0);\n\n if (uint(gl_InstanceID) >= numSplats) {\n return;\n }\n\n ivec3 texCoord;\n if (stochastic) {\n texCoord = ivec3(\n uint(gl_InstanceID) & SPLAT_TEX_WIDTH_MASK,\n (uint(gl_InstanceID) >> SPLAT_TEX_WIDTH_BITS) & SPLAT_TEX_HEIGHT_MASK,\n (uint(gl_InstanceID) >> SPLAT_TEX_LAYER_BITS)\n );\n } else {\n if (splatIndex == 0xffffffffu) {\n \n return;\n }\n texCoord = ivec3(\n splatIndex & SPLAT_TEX_WIDTH_MASK,\n (splatIndex >> SPLAT_TEX_WIDTH_BITS) & SPLAT_TEX_HEIGHT_MASK,\n splatIndex >> SPLAT_TEX_LAYER_BITS\n );\n }\n uvec4 packedData = texelFetch(packedSplats, texCoord, 0);\n\n vec3 center, scales;\n vec4 quaternion, rgba;\n unpackSplatEncoding(packedData, center, scales, quaternion, rgba, rgbMinMaxLnScaleMinMax);\n\n if (rgba.a < minAlpha) {\n return;\n }\n bvec3 zeroScales = equal(scales, vec3(0.0));\n if (all(zeroScales)) {\n return;\n }\n\n \n vec3 viewCenter = quatVec(renderToViewQuat, center) + renderToViewPos;\n\n \n if (viewCenter.z >= 0.0) {\n return;\n }\n\n \n vec4 clipCenter = projectionMatrix * vec4(viewCenter, 1.0);\n\n \n if (abs(clipCenter.z) >= clipCenter.w) {\n return;\n }\n\n \n float clip = clipXY * clipCenter.w;\n if (abs(clipCenter.x) > clip || abs(clipCenter.y) > clip) {\n return;\n }\n\n \n vSplatIndex = splatIndex;\n\n \n vec4 viewQuaternion = quatQuat(renderToViewQuat, quaternion);\n\n if (enable2DGS && any(zeroScales)) {\n vRgba = rgba;\n vSplatUv = position.xy * maxStdDev;\n\n vec3 offset;\n if (zeroScales.z) {\n offset = vec3(vSplatUv.xy * scales.xy, 0.0);\n } else if (zeroScales.y) {\n offset = vec3(vSplatUv.x * scales.x, 0.0, vSplatUv.y * scales.z);\n } else {\n offset = vec3(0.0, vSplatUv.xy * scales.yz);\n }\n\n vec3 viewPos = viewCenter + quatVec(viewQuaternion, offset);\n gl_Position = projectionMatrix * vec4(viewPos, 1.0);\n vNdc = gl_Position.xyz / gl_Position.w;\n return;\n }\n\n \n vec3 ndcCenter = clipCenter.xyz / clipCenter.w;\n\n \n mat3 RS = scaleQuaternionToMatrix(scales, viewQuaternion);\n mat3 cov3D = RS * transpose(RS);\n\n \n vec2 scaledRenderSize = renderSize * focalAdjustment;\n vec2 focal = 0.5 * scaledRenderSize * vec2(projectionMatrix[0][0], projectionMatrix[1][1]);\n\n mat3 J;\n if(isOrthographic) {\n J = mat3(\n focal.x, 0.0, 0.0,\n 0.0, focal.y, 0.0,\n 0.0, 0.0, 0.0\n );\n } else {\n float invZ = 1.0 / viewCenter.z;\n vec2 J1 = focal * invZ;\n vec2 J2 = -(J1 * viewCenter.xy) * invZ;\n J = mat3(\n J1.x, 0.0, J2.x,\n 0.0, J1.y, J2.y,\n 0.0, 0.0, 0.0\n );\n }\n\n \n \n \n \n \n \n \n mat3 cov2D = transpose(J) * cov3D * J;\n float a = cov2D[0][0];\n float d = cov2D[1][1];\n float b = cov2D[0][1];\n\n \n a += preBlurAmount;\n d += preBlurAmount;\n\n float fullBlurAmount = blurAmount;\n if ((focalDistance > 0.0) && (apertureAngle > 0.0)) {\n float focusRadius = maxPixelRadius;\n if (viewCenter.z < 0.0) {\n float focusBlur = abs((-viewCenter.z - focalDistance) / viewCenter.z);\n float apertureRadius = focal.x * tan(0.5 * apertureAngle);\n focusRadius = focusBlur * apertureRadius;\n }\n fullBlurAmount = clamp(sqr(focusRadius), blurAmount, sqr(maxPixelRadius));\n }\n\n \n float detOrig = a * d - b * b;\n a += fullBlurAmount;\n d += fullBlurAmount;\n float det = a * d - b * b;\n\n \n float blurAdjust = sqrt(max(0.0, detOrig / det));\n rgba.a *= blurAdjust;\n if (rgba.a < minAlpha) {\n return;\n }\n\n \n float eigenAvg = 0.5 * (a + d);\n float eigenDelta = sqrt(max(0.0, eigenAvg * eigenAvg - det));\n float eigen1 = eigenAvg + eigenDelta;\n float eigen2 = eigenAvg - eigenDelta;\n\n vec2 eigenVec1 = normalize(vec2((abs(b) < 0.001) ? 1.0 : b, eigen1 - a));\n vec2 eigenVec2 = vec2(eigenVec1.y, -eigenVec1.x);\n\n float scale1 = min(maxPixelRadius, maxStdDev * sqrt(eigen1));\n float scale2 = min(maxPixelRadius, maxStdDev * sqrt(eigen2));\n if (scale1 < minPixelRadius && scale2 < minPixelRadius) {\n return;\n }\n\n \n vec2 pixelOffset = position.x * eigenVec1 * scale1 + position.y * eigenVec2 * scale2;\n vec2 ndcOffset = (2.0 / scaledRenderSize) * pixelOffset;\n vec3 ndc = vec3(ndcCenter.xy + ndcOffset, ndcCenter.z);\n\n vRgba = rgba;\n vSplatUv = position.xy * maxStdDev;\n vNdc = ndc;\n gl_Position = vec4(ndc.xy * clipCenter.w, clipCenter.zw);\n}",oldSplatFragment:"precision highp float;\nprecision highp int;\n\n#include <splatDefines>\n\nuniform float near;\nuniform float far;\nuniform bool encodeLinear;\nuniform float time;\nuniform bool debugFlag;\nuniform float maxStdDev;\nuniform float minAlpha;\nuniform bool stochastic;\nuniform bool disableFalloff;\nuniform float falloff;\n\nuniform bool splatTexEnable;\nuniform sampler3D splatTexture;\nuniform mat2 splatTexMul;\nuniform vec2 splatTexAdd;\nuniform float splatTexNear;\nuniform float splatTexFar;\nuniform float splatTexMid;\n\nout vec4 fragColor;\n\nin vec4 vRgba;\nin vec2 vSplatUv;\nin vec3 vNdc;\nflat in uint vSplatIndex;\n\nvoid main() {\n vec4 rgba = vRgba;\n\n float z = dot(vSplatUv, vSplatUv);\n if (!splatTexEnable) {\n if (z > (maxStdDev * maxStdDev)) {\n discard;\n }\n } else {\n vec2 uv = splatTexMul * vSplatUv + splatTexAdd;\n float ndcZ = vNdc.z;\n float depth = (2.0 * near * far) / (far + near - ndcZ * (far - near));\n float clampedFar = max(splatTexFar, splatTexNear);\n float clampedDepth = clamp(depth, splatTexNear, clampedFar);\n float logDepth = log2(clampedDepth + 1.0);\n float logNear = log2(splatTexNear + 1.0);\n float logFar = log2(clampedFar + 1.0);\n\n float texZ;\n if (splatTexMid > 0.0) {\n float clampedMid = clamp(splatTexMid, splatTexNear, clampedFar);\n float logMid = log2(clampedMid + 1.0);\n texZ = (clampedDepth <= clampedMid) ?\n (0.5 * ((logDepth - logNear) / (logMid - logNear))) :\n (0.5 * ((logDepth - logMid) / (logFar - logMid)) + 0.5);\n } else {\n texZ = (logDepth - logNear) / (logFar - logNear);\n }\n\n vec4 modulate = texture(splatTexture, vec3(uv, 1.0 - texZ));\n rgba *= modulate;\n }\n\n rgba.a *= mix(1.0, exp(-0.5 * z), falloff);\n\n if (rgba.a < minAlpha) {\n discard;\n }\n if (encodeLinear) {\n rgba.rgb = srgbToLinear(rgba.rgb);\n }\n\n if (stochastic) {\n const bool STEADY = false;\n uint uTime = STEADY ? 0u : floatBitsToUint(time);\n uvec2 coord = uvec2(gl_FragCoord.xy);\n uint state = uTime + 0x9e3779b9u * coord.x + 0x85ebca6bu * coord.y + 0xc2b2ae35u * uint(vSplatIndex);\n state = state * 747796405u + 2891336453u;\n uint hash = ((state >> ((state >> 28u) + 4u)) ^ state) * 277803737u;\n hash = (hash >> 22u) ^ hash;\n float rand = float(hash) / 4294967296.0;\n if (rand < rgba.a) {\n fragColor = vec4(rgba.rgb, 1.0);\n } else {\n discard;\n }\n } else {\n #ifdef PREMULTIPLIED_ALPHA\n fragColor = vec4(rgba.rgb * rgba.a, rgba.a);\n #else\n fragColor = rgba;\n #endif\n }\n}",splatVertex:"precision highp float;\nprecision highp int;\nprecision highp usampler2DArray;\n\n#include <splatDefines>\n\nout vec4 vRgba;\nout vec2 vSplatUv;\nout vec3 vNdc;\nflat out uint vSplatIndex;\nflat out float adjustedStdDev;\n\nuniform vec2 renderSize;\nuniform vec4 renderToViewQuat;\nuniform vec3 renderToViewPos;\nuniform mat3 renderToViewBasis;\nuniform float maxStdDev;\nuniform float minPixelRadius;\nuniform float maxPixelRadius;\nuniform bool enableExtSplats;\nuniform bool enableCovSplats;\nuniform float time;\nuniform float deltaTime;\nuniform bool debugFlag;\nuniform float minAlpha;\nuniform bool enable2DGS;\nuniform bool lodInflate;\nuniform float blurAmount;\nuniform float preBlurAmount;\nuniform float focalDistance;\nuniform float apertureAngle;\nuniform float clipXY;\nuniform float focalAdjustment;\n\nuniform usampler2D ordering;\nuniform usampler2DArray extSplats;\nuniform usampler2DArray extSplats2;\n\nbool isPerspectiveMatrix( mat4 m ) {\n return m[ 2 ][ 3 ] == -1.0;\n}\n\n#include <logdepthbuf_pars_vertex>\n\nvoid main() {\n \n gl_Position = vec4(0.0, 0.0, 2.0, 1.0);\n\n ivec2 orderingCoord = ivec2((gl_InstanceID >> 2) & 4095, gl_InstanceID >> 14);\n uint splatIndex = texelFetch(ordering, orderingCoord, 0)[gl_InstanceID & 3];\n if (splatIndex == 0xffffffffu) {\n \n return;\n }\n\n ivec3 texCoord = splatTexCoord(int(splatIndex));\n vec3 center, scales, xxyyzz, xyxzyz;\n vec4 quaternion, rgba;\n mat3 cov3D;\n bvec3 zeroScales = bvec3(false);\n\n if (enableExtSplats) {\n uvec4 ext1 = texelFetch(extSplats, texCoord, 0);\n float alpha = unpackSplatExtAlpha(ext1);\n if ((alpha == 0.0) || (alpha < minAlpha)) {\n return;\n }\n uvec4 ext2 = texelFetch(extSplats2, texCoord, 0);\n\n if (!enableCovSplats) {\n unpackSplatExt(ext1, ext2, center, scales, quaternion, rgba);\n zeroScales = equal(scales, vec3(0.0));\n if (all(zeroScales)) {\n return;\n }\n } else {\n unpackSplatExtCov(ext1, ext2, center, rgba, xxyyzz, xyxzyz);\n if (all(equal(xxyyzz, vec3(0.0))) && all(equal(xyxzyz, vec3(0.0)))) {\n return;\n }\n }\n } else {\n uvec4 packedData = texelFetch(extSplats, texCoord, 0);\n if (!enableCovSplats) {\n unpackSplatEncoding(packedData, center, scales, quaternion, rgba, vec4(0.0, 1.0, LN_SCALE_MIN, LN_SCALE_MAX));\n zeroScales = equal(scales, vec3(0.0));\n if (all(zeroScales)) {\n return;\n }\n } else {\n unpackSplatCovEncoding(packedData, center, rgba, xxyyzz, xyxzyz, vec4(0.0, 1.0, LN_SCALE_MIN, LN_SCALE_MAX));\n if (all(equal(xxyyzz, vec3(0.0))) && all(equal(xyxzyz, vec3(0.0)))) {\n return;\n }\n }\n\n rgba.a *= 2.0;\n if ((rgba.a == 0.0) || (rgba.a < minAlpha)) {\n return;\n }\n }\n\n adjustedStdDev = maxStdDev;\n if (rgba.a > 1.0) {\n \n rgba.a = min(rgba.a * 4.0 - 3.0, 5.0);\n\n if (lodInflate) {\n \n float opacity = exp((rgba.a * rgba.a - 1.0) / 2.718281828459045);\n float rescale = pow(opacity, 1.0 / 3.0);\n scales *= rescale;\n rgba.a = 1.0;\n }\n\n \n adjustedStdDev = maxStdDev + 0.7 * (rgba.a - 1.0);\n }\n\n \n vec3 viewCenter = (!enableCovSplats ? quatVec(renderToViewQuat, center) : (renderToViewBasis * center)) + renderToViewPos;\n\n \n if (viewCenter.z >= 0.0) {\n return;\n }\n\n \n vec4 clipCenter = projectionMatrix * vec4(viewCenter, 1.0);\n\n \n if (abs(clipCenter.z) >= clipCenter.w) {\n return;\n }\n\n \n float clip = clipXY * clipCenter.w;\n if (abs(clipCenter.x) > clip || abs(clipCenter.y) > clip) {\n return;\n }\n\n vRgba = rgba;\n vSplatUv = position.xy * adjustedStdDev;\n\n \n vSplatIndex = splatIndex;\n\n if (!enableCovSplats) {\n \n vec4 viewQuaternion = quatQuat(renderToViewQuat, quaternion);\n\n if (enable2DGS && any(zeroScales)) {\n vec3 offset;\n if (zeroScales.z) {\n offset = vec3(vSplatUv.xy * scales.xy, 0.0);\n } else if (zeroScales.y) {\n offset = vec3(vSplatUv.x * scales.x, 0.0, vSplatUv.y * scales.z);\n } else {\n offset = vec3(0.0, vSplatUv.xy * scales.yz);\n }\n\n vec3 viewPos = viewCenter + quatVec(viewQuaternion, offset);\n gl_Position = projectionMatrix * vec4(viewPos, 1.0);\n vNdc = gl_Position.xyz / gl_Position.w;\n\n #include <logdepthbuf_vertex>\n return;\n }\n\n \n mat3 RS = scaleQuaternionToMatrix(scales, viewQuaternion);\n cov3D = RS * transpose(RS);\n } else {\n cov3D = mat3(\n xxyyzz.x, xyxzyz.x, xyxzyz.y,\n xyxzyz.x, xxyyzz.y, xyxzyz.z,\n xyxzyz.y, xyxzyz.z, xxyyzz.z\n );\n cov3D = renderToViewBasis * cov3D * transpose(renderToViewBasis);\n }\n\n \n vec2 scaledRenderSize = renderSize * focalAdjustment;\n vec2 focal = 0.5 * scaledRenderSize * vec2(projectionMatrix[0][0], projectionMatrix[1][1]);\n\n mat3 J;\n if (isOrthographic) {\n J = mat3(\n focal.x, 0.0, 0.0,\n 0.0, focal.y, 0.0,\n 0.0, 0.0, 0.0\n );\n } else {\n float invZ = 1.0 / viewCenter.z;\n vec2 J1 = focal * invZ;\n vec2 J2 = -(J1 * viewCenter.xy) * invZ;\n J = mat3(\n J1.x, 0.0, J2.x,\n 0.0, J1.y, J2.y,\n 0.0, 0.0, 0.0\n );\n }\n\n \n \n mat3 cov2D = transpose(J) * cov3D * J;\n float a = cov2D[0][0];\n float d = cov2D[1][1];\n float b = cov2D[0][1];\n\n \n a += preBlurAmount;\n d += preBlurAmount;\n\n float fullBlurAmount = blurAmount;\n if ((focalDistance > 0.0) && (apertureAngle > 0.0)) {\n float focusRadius = maxPixelRadius;\n if (viewCenter.z < 0.0) {\n float focusBlur = abs((-viewCenter.z - focalDistance) / viewCenter.z);\n float apertureRadius = focal.x * tan(0.5 * apertureAngle);\n focusRadius = focusBlur * apertureRadius;\n }\n fullBlurAmount = clamp(sqr(focusRadius), blurAmount, sqr(maxPixelRadius));\n }\n\n \n float detOrig = a * d - b * b;\n a += fullBlurAmount;\n d += fullBlurAmount;\n float det = a * d - b * b;\n\n \n float blurAdjust = sqrt(max(0.0, detOrig / det));\n rgba.a *= blurAdjust;\n if (rgba.a < minAlpha) {\n return;\n }\n vRgba.a = rgba.a;\n\n \n float eigenAvg = 0.5 * (a + d);\n float eigenDelta = sqrt(max(0.0, eigenAvg * eigenAvg - det));\n float eigen1 = eigenAvg + eigenDelta;\n float eigen2 = eigenAvg - eigenDelta;\n\n vec2 eigenVec1 = (abs(b) > 0.001) ? normalize(vec2(b, eigen1 - a))\n : ((a >= d) ? vec2(1.0, 0.0) : vec2(0.0, 1.0));\n vec2 eigenVec2 = vec2(eigenVec1.y, -eigenVec1.x);\n\n float scale1 = min(maxPixelRadius, adjustedStdDev * sqrt(eigen1));\n float scale2 = min(maxPixelRadius, adjustedStdDev * sqrt(eigen2));\n if (scale1 < minPixelRadius && scale2 < minPixelRadius) {\n return;\n }\n\n \n vec2 pixelOffset = position.x * eigenVec1 * scale1 + position.y * eigenVec2 * scale2;\n vec2 ndcOffset = (2.0 / scaledRenderSize) * pixelOffset;\n\n \n vec3 ndcCenter = clipCenter.xyz / clipCenter.w;\n vec3 ndc = vec3(ndcCenter.xy + ndcOffset, ndcCenter.z);\n\n vNdc = ndc;\n gl_Position = vec4(ndc.xy * clipCenter.w, clipCenter.zw);\n\n #include <logdepthbuf_vertex>\n}",splatFragment:"precision highp float;\nprecision highp int;\n\n#include <splatDefines>\n\nuniform float near;\nuniform float far;\nuniform bool encodeLinear;\nuniform float time;\nuniform bool debugFlag;\nuniform float maxStdDev;\nuniform float minAlpha;\nuniform bool disableFalloff;\nuniform float falloff;\n\nout vec4 fragColor;\n\nin vec4 vRgba;\nin vec2 vSplatUv;\nin vec3 vNdc;\nflat in uint vSplatIndex;\nflat in float adjustedStdDev;\n\n#include <logdepthbuf_pars_fragment>\n\nvoid main() {\n vec4 rgba = vRgba;\n\n float z2 = dot(vSplatUv, vSplatUv);\n if (z2 > (adjustedStdDev * adjustedStdDev)) {\n discard;\n }\n\n if (false) {\n \n float a = rgba.a;\n float shifted = sqrt(z2) - max(0.0, a - 1.0);\n float exponent = -0.5 * max(1.0, a) * sqr(max(0.0, shifted));\n float min1a = min(1.0, a);\n rgba.a = mix(min1a, min1a * exp(exponent), falloff);\n } else {\n \n if (rgba.a <= 1.0) {\n rgba.a = mix(rgba.a, rgba.a * exp(-0.5 * z2), falloff);\n } else {\n float a = exp((rgba.a*rgba.a - 1.0) / 2.718281828459045);\n float alpha = 1.0 - pow(1.0 - exp(-0.5 * z2), a);\n rgba.a = mix(1.0, alpha, falloff);\n }\n }\n\n if (rgba.a < minAlpha) {\n discard;\n }\n if (encodeLinear) {\n rgba.rgb = srgbToLinear(rgba.rgb);\n }\n\n #ifdef PREMULTIPLIED_ALPHA\n fragColor = vec4(rgba.rgb * rgba.a, rgba.a);\n #else\n fragColor = rgba;\n #endif\n\n #include <logdepthbuf_fragment>\n}",computeVec4Template:"precision highp float;\nprecision highp int;\nprecision highp sampler2D;\nprecision highp usampler2D;\nprecision highp isampler2D;\nprecision highp sampler2DArray;\nprecision highp usampler2DArray;\nprecision highp isampler2DArray;\nprecision highp sampler3D;\nprecision highp usampler3D;\nprecision highp isampler3D;\n\n#include <splatDefines>\n\nuniform uint targetLayer;\nuniform int targetBase;\nuniform int targetCount;\n\nout vec4 target;\n\n{{ GLOBALS }}\n\nvoid computeReadback(int _index) {\n {{ STATEMENTS }}\n}\n\nvoid main() {\n int targetIndex = int(targetLayer << SPLAT_TEX_LAYER_BITS) + int(uint(gl_FragCoord.y) << SPLAT_TEX_WIDTH_BITS) + int(gl_FragCoord.x);\n int index = targetIndex - targetBase;\n\n if ((index >= 0) && (index < targetCount)) {\n computeReadback(index);\n } else {\n target = vec4(0.0, 0.0, 0.0, 0.0);\n }\n}",computeUvec4Vec4Template:"precision highp float;\nprecision highp int;\nprecision highp sampler2D;\nprecision highp usampler2D;\nprecision highp isampler2D;\nprecision highp sampler2DArray;\nprecision highp usampler2DArray;\nprecision highp isampler2DArray;\nprecision highp sampler3D;\nprecision highp usampler3D;\nprecision highp isampler3D;\n\n#include <splatDefines>\n\nuniform uint targetLayer;\nuniform int targetBase;\nuniform int targetCount;\n\nlayout(location = 0) out uvec4 target;\nlayout(location = 1) out vec4 target3;\n\n{{ GLOBALS }}\n\nvoid produceSplat(int _index) {\n {{ STATEMENTS }}\n}\n\nvoid main() {\n int targetIndex = int(targetLayer << SPLAT_TEX_LAYER_BITS) + int(uint(gl_FragCoord.y) << SPLAT_TEX_WIDTH_BITS) + int(gl_FragCoord.x);\n int index = targetIndex - targetBase;\n\n \n target = uvec4(0u, 0u, 0u, 0u);\n\n \n target3 = floatToVec4(1.0 / 0.0);\n\n if ((index >= 0) && (index < targetCount)) {\n produceSplat(index);\n }\n}",computeUvec4x2Vec4Template:"precision highp float;\nprecision highp int;\nprecision highp sampler2D;\nprecision highp usampler2D;\nprecision highp isampler2D;\nprecision highp sampler2DArray;\nprecision highp usampler2DArray;\nprecision highp isampler2DArray;\nprecision highp sampler3D;\nprecision highp usampler3D;\nprecision highp isampler3D;\n\n#include <splatDefines>\n\nuniform uint targetLayer;\nuniform int targetBase;\nuniform int targetCount;\n\nlayout(location = 0) out uvec4 target;\nlayout(location = 1) out uvec4 target2;\nlayout(location = 2) out vec4 target3;\n\n{{ GLOBALS }}\n\nvoid produceSplat(int _index) {\n {{ STATEMENTS }}\n}\n\nvoid main() {\n int targetIndex = int(targetLayer << SPLAT_TEX_LAYER_BITS) + int(uint(gl_FragCoord.y) << SPLAT_TEX_WIDTH_BITS) + int(gl_FragCoord.x);\n int index = targetIndex - targetBase;\n\n \n target = uvec4(0u, 0u, 0u, 0u);\n target2 = uvec4(0u, 0u, 0u, 0u);\n\n \n target3 = floatToVec4(1.0 / 0.0);\n\n if ((index >= 0) && (index < targetCount)) {\n produceSplat(index);\n }\n}",computeUvec4Template:"precision highp float;\nprecision highp int;\nprecision highp sampler2D;\nprecision highp usampler2D;\nprecision highp isampler2D;\nprecision highp sampler2DArray;\nprecision highp usampler2DArray;\nprecision highp isampler2DArray;\nprecision highp sampler3D;\nprecision highp usampler3D;\nprecision highp isampler3D;\n\n#include <splatDefines>\n\nuniform uint targetLayer;\nuniform int targetBase;\nuniform int targetCount;\n\nout uvec4 target;\n\n{{ GLOBALS }}\n\nvoid produceSplat(int _index) {\n {{ STATEMENTS }}\n}\n\nvoid main() {\n int targetIndex = int(targetLayer << SPLAT_TEX_LAYER_BITS) + int(uint(gl_FragCoord.y) << SPLAT_TEX_WIDTH_BITS) + int(gl_FragCoord.x);\n int index = targetIndex - targetBase;\n\n target = uvec4(0u, 0u, 0u, 0u);\n if ((index >= 0) && (index < targetCount)) {\n produceSplat(index);\n }\n}"}),Ma}const Ea=class e{constructor({renderer:e}={}){this.renderer=e,this.capacity=0,this.count=0}dispose(){this.target&&(this.target.dispose(),this.target=void 0)}static ensureBuffer(e,t){const n=4*(Math.ceil(Math.max(1,e)/br)*br);if(t.byteLength>=n)return t;const r=new ArrayBuffer(n);if(t instanceof ArrayBuffer)return r;return new(0,t.constructor)(r)}ensureBuffer(t,n){return e.ensureBuffer(t,n)}ensureCapacity(e){const{width:t,height:n,depth:i,maxSplats:s}=gi(e);(!this.target||s>this.capacity)&&(this.dispose(),this.capacity=s,this.target=new r.WebGLArrayRenderTarget(t,n,i,{depthBuffer:!1,stencilBuffer:!1,generateMipmaps:!1,magFilter:r.NearestFilter,minFilter:r.NearestFilter}),this.target.texture.format=r.RGBAFormat,this.target.texture.type=r.UnsignedByteType,this.target.texture.internalFormat="RGBA8",this.target.scissorTest=!0)}prepareProgramMaterial(t){let n=e.readbackProgram.get(t);if(!n){const r=qr({index:"int"},{rgba8:"vec4"},(({index:e})=>{t.inputs.index=e;return{rgba8:new vs({rgba8:t.outputs.rgba8})}}));e.programTemplate||(e.programTemplate=new Ds(Aa().computeVec4Template)),n=new Rs({graph:r,inputs:{index:"_index"},outputs:{rgba8:"target"},template:e.programTemplate}),Object.assign(n.uniforms,{targetLayer:{value:0},targetBase:{value:0},targetCount:{value:0}}),e.readbackProgram.set(t,n)}const r=n.prepareMaterial();return e.fullScreenQuad.material=r,{program:n,material:r}}saveRenderState(e){return{target:e.getRenderTarget(),xrEnabled:e.xr.enabled,autoClear:e.autoClear}}resetRenderState(e,t){e.setRenderTarget(t.target),e.xr.enabled=t.xrEnabled,e.autoClear=t.autoClear}process({count:t,material:n}){const r=this.renderer;if(!r)throw new Error("No renderer");if(!this.target)throw new Error("No target");const i=4194304;n.uniforms.targetBase.value=0,n.uniforms.targetCount.value=t;let s=0;for(;s<t;){const a=Math.floor(s/i),o=a*i,l=Math.min(wr,Math.ceil((t-o)/br));n.uniforms.targetLayer.value=a,this.target.scissor.set(0,0,br,l),r.setRenderTarget(this.target,a),r.xr.enabled=!1,r.autoClear=!1,e.fullScreenQuad.render(r),s+=br*l}this.count=t}async read({readback:e}){const t=this.renderer;if(!t)throw new Error("No renderer");if(!this.target)throw new Error("No target");const n=Math.ceil(this.count/br)*br;if(e.byteLength<4*n)throw new Error(`Readback buffer too small: ${e.byteLength} < ${4*n}`);const r=new Uint8Array(e instanceof ArrayBuffer?e:e.buffer),i=4194304;let s=0;const a=[];for(;s<this.count;){const e=Math.floor(s/i),n=e*i,o=Math.min(wr,Math.ceil((this.count-n)/br));t.setRenderTarget(this.target,e);const l=br*o*4,c=r.subarray(4*n,4*n+l),u=null==t?void 0:t.readRenderTargetPixelsAsync(this.target,0,0,br,o,c);a.push(u),s+=br*o}return Promise.all(a).then((()=>e))}render({reader:e,count:t,renderer:n}){if(this.renderer=n||this.renderer,!this.renderer)throw new Error("No renderer");this.ensureCapacity(t);const{program:r,material:i}=this.prepareProgramMaterial(e);r.update();const s=this.saveRenderState(this.renderer);this.process({count:t,material:i}),this.resetRenderState(this.renderer,s)}async readback({readback:e}){if(!this.renderer)throw new Error("No renderer");const t=this.saveRenderState(this.renderer),n=this.read({readback:e});return this.resetRenderState(this.renderer,t),n}async renderReadback({reader:e,count:t,renderer:n,readback:r}){if(this.renderer=n||this.renderer,!this.renderer)throw new Error("No renderer");this.ensureCapacity(t);const{program:i,material:s}=this.prepareProgramMaterial(e);i.update();const a=this.saveRenderState(this.renderer);this.process({count:t,material:s});const o=this.read({readback:r});return this.resetRenderState(this.renderer,a),o}getTexture(){var e;return null==(e=this.target)?void 0:e.texture}};Ea.programTemplate=null,Ea.readbackProgram=new WeakMap,Ea.fullScreenQuad=new o(new r.RawShaderMaterial({visible:!1}));let Ca=Ea;const Ra=class e{constructor(t={}){if(this.capacity=0,this.count=0,this.array=null,this.readback=null,this.source=null,this.needsUpdate=!0,this.dyno=new bs({key:"rgbaArray",type:ka,globals:()=>[Ia],value:{texture:e.getEmpty(),count:0},update:e=>(e.texture=this.getTexture(),e.count=this.count,e)}),t.array){this.array=t.array;const e=Math.floor(this.array.length/4);this.capacity=Math.ceil(e/br)*br,this.capacity>e&&(this.array=new Uint8Array(4*this.capacity),this.array.set(t.array)),this.count=Math.min(e,t.count??Number.POSITIVE_INFINITY)}else this.capacity=t.capacity??0,this.count=0}dispose(){this.readback&&(this.readback.dispose(),this.readback=null),this.source&&(this.source.dispose(),this.source=null)}ensureCapacity(e){var t;if(!this.array||e>((null==(t=this.array)?void 0:t.length)??0)/4){this.capacity=gi(e).maxSplats;const t=new Uint8Array(4*this.capacity);this.array&&t.set(this.array),this.array=t}return this.array}getTexture(){var t;let n=null==(t=this.readback)?void 0:t.getTexture();return(this.source||this.array)&&(n=this.maybeUpdateSource()),n??e.getEmpty()}maybeUpdateSource(){if(!this.array)throw new Error("No array");if(this.needsUpdate||!this.source){if(this.needsUpdate=!1,this.source){const{width:e,height:t,depth:n}=this.source.image;this.capacity!==e*t*n&&(this.source.dispose(),this.source=null)}if(this.source)this.array.buffer!==this.source.image.data.buffer&&(this.source.image.data=new Uint8Array(this.array.buffer));else{const{width:e,height:t,depth:n}=gi(this.capacity);this.source=new r.DataArrayTexture(this.array,e,t,n),this.source.format=r.RGBAFormat,this.source.type=r.UnsignedByteType,this.source.internalFormat="RGBA8",this.source.needsUpdate=!0}this.source.needsUpdate=!0}return this.source}render({reader:e,count:t,renderer:n}){this.readback||(this.readback=new Ca({renderer:n})),this.readback.render({reader:e,count:t,renderer:n}),this.capacity=this.readback.capacity,this.count=this.readback.count}fromPackedSplats({packedSplats:t,base:n,count:r,renderer:i}){const{dynoSplats:s,dynoBase:a,dynoCount:o,reader:l}=e.makeDynos();return s.packedSplats=t,a.value=n,o.value=r,this.render({reader:l,count:r,renderer:i}),this}async read(){if(!this.readback)throw new Error("No readback");(!this.array||this.array.length<4*this.count)&&(this.array=new Uint8Array(4*this.capacity));return(await this.readback.readback({readback:this.array})).subarray(0,4*this.count)}async getArray(){if(this.readback)return await this.read();if(this.array)return this.array;throw new Error("No array")}static getEmpty(){if(!e.emptySource){const t=new Uint8Array(4);e.emptySource=new r.DataArrayTexture(t,1,1,1),e.emptySource.format=r.RGBAFormat,e.emptySource.type=r.UnsignedByteType,e.emptySource.internalFormat="RGBA8",e.emptySource.needsUpdate=!0}return e.emptySource}static makeDynos(){if(!e.dynos){const t=new go,n=new Ts({value:0}),r=new Ts({value:0}),i=qr({index:"int"},{rgba8:"vec4"},(({index:e})=>{if(!e)throw new Error("index is undefined");e=Us(e,n);const i=((e,t,n,r)=>new Qi({packedSplats:e,index:t,base:n,count:r}))(t,e,n,r);return{rgba8:Ni(i).outputs.rgba}}));e.dynos={dynoSplats:t,dynoBase:n,dynoCount:r,reader:i}}return e.dynos}};Ra.emptySource=null,Ra.dynos=null;let Da=Ra;const ka={type:"RgbaArray"},Ia=Xr("\n struct RgbaArray {\n sampler2DArray texture;\n int count;\n };\n");function Pa(e){switch(e){case"all":return 0;case"plane":return 1;case"sphere":return 2;case"box":return 3;case"ellipsoid":return 4;case"cylinder":return 5;case"capsule":return 6;case"infinite_cone":return 7;default:throw new Error(`Unknown SDF type: ${e}`)}}function La(e){switch(e){case"multiply":return 0;case"set_rgb":return 1;case"add_rgba":return 2;default:throw new Error(`Unknown blend mode: ${e}`)}}class Ua extends r.Object3D{constructor(e={}){super();const{type:t,invert:n,opacity:i,color:s,displace:a,radius:o}=e;this.type=t??"sphere",this.invert=n??!1,this.opacity=i??1,this.color=s??new r.Color(1,1,1),this.displace=a??new r.Vector3(0,0,0),this.radius=o??0}}const Fa=class e extends r.Object3D{constructor(t={}){const{name:n,rgbaBlendMode:r="multiply",sdfSmooth:i=0,softEdge:s=0,invert:a=!1,sdfs:o=null}=t;super(),this.rgbaBlendMode=r,this.sdfSmooth=i,this.softEdge=s,this.invert=a,this.sdfs=o,this.ordering=e.nextOrdering++,this.name=n??`Edit ${this.ordering}`}addSdf(e){null==this.sdfs&&(this.sdfs=[]),this.sdfs.includes(e)||this.sdfs.push(e)}removeSdf(e){null!=this.sdfs&&(this.sdfs=this.sdfs.filter((t=>t!==e)))}};Fa.nextOrdering=1;let za=Fa;class Ba{constructor({maxSdfs:e,maxEdits:t}){this.maxSdfs=Math.max(16,e??0),this.numSdfs=0,this.sdfData=new Uint32Array(8*this.maxSdfs*4),this.sdfFloatData=new Float32Array(this.sdfData.buffer),this.sdfTexture=this.newSdfTexture(this.sdfData,this.maxSdfs),this.dynoSdfArray=new bs({key:"sdfArray",type:Va,globals:()=>[Oa],value:{numSdfs:0,sdfTexture:this.sdfTexture},update:e=>(e.numSdfs=this.numSdfs,e.sdfTexture=this.sdfTexture,e)}),this.maxEdits=Math.max(16,t??0),this.numEdits=0,this.editData=new Uint32Array(4*this.maxEdits),this.editFloatData=new Float32Array(this.editData.buffer),this.dynoNumEdits=new Ts({value:0}),this.dynoEdits=this.newEdits(this.editData,this.maxEdits)}newSdfTexture(e,t){const n=new r.DataTexture(e,8,t,r.RGBAIntegerFormat,r.UnsignedIntType);return n.internalFormat="RGBA32UI",n.needsUpdate=!0,n}newEdits(e,t){return new bs({key:"edits",type:"uvec4",count:t,globals:()=>[Na],value:e})}ensureCapacity({maxSdfs:e,maxEdits:t}){let n=!1;return e>this.sdfTexture.image.height&&(this.sdfTexture.dispose(),this.maxSdfs=Math.max(2*this.maxSdfs,e),this.sdfData=new Uint32Array(8*this.maxSdfs*4),this.sdfFloatData=new Float32Array(this.sdfData.buffer),this.sdfTexture=this.newSdfTexture(this.sdfData,this.maxSdfs)),t>(this.dynoEdits.count??0)&&(this.maxEdits=Math.max(2*this.maxEdits,t),this.editData=new Uint32Array(4*this.maxEdits),this.editFloatData=new Float32Array(this.editData.buffer),this.dynoEdits=this.newEdits(this.editData,this.maxEdits),n=!0),n}updateEditData(e,t){const n=this.editData[e]!==t;return this.editData[e]=t,n}updateEditFloatData(e,t){$a[0]=t;const n=this.editFloatData[e]!==$a[0];return n&&(this.editFloatData[e]=$a[0]),n}encodeEdit(e,{sdfFirst:t,sdfCount:n,invert:r,rgbaBlendMode:i,softEdge:s,sdfSmooth:a}){const o=4*e;let l=!1;return l=this.updateEditData(o+0,i|(r?256:0))||l,l=this.updateEditData(o+1,t|n<<16)||l,l=this.updateEditFloatData(o+2,s)||l,l=this.updateEditFloatData(o+3,a)||l,l}updateSdfData(e,t){const n=this.sdfData[e]!==t;return this.sdfData[e]=t,n}updateSdfFloatData(e,t){$a[0]=t;const n=this.sdfFloatData[e]!==$a[0];return n&&(this.sdfFloatData[e]=$a[0]),n}encodeSdf(e,{sdfType:t,invert:n,center:r,quaternion:i,scale:s,sizes:a},o){const l=32*e,c=t|(n?256:0);let u=!1;u=this.updateSdfFloatData(l+0,(null==r?void 0:r.x)??0)||u,u=this.updateSdfFloatData(l+1,(null==r?void 0:r.y)??0)||u,u=this.updateSdfFloatData(l+2,(null==r?void 0:r.z)??0)||u,u=this.updateSdfData(l+3,c)||u,u=this.updateSdfFloatData(l+4,(null==i?void 0:i.x)??0)||u,u=this.updateSdfFloatData(l+5,(null==i?void 0:i.y)??0)||u,u=this.updateSdfFloatData(l+6,(null==i?void 0:i.z)??0)||u,u=this.updateSdfFloatData(l+7,(null==i?void 0:i.w)??0)||u,u=this.updateSdfFloatData(l+8,(null==s?void 0:s.x)??0)||u,u=this.updateSdfFloatData(l+9,(null==s?void 0:s.y)??0)||u,u=this.updateSdfFloatData(l+10,(null==s?void 0:s.z)??0)||u,u=this.updateSdfData(l+11,0)||u,u=this.updateSdfFloatData(l+12,(null==a?void 0:a.x)??0)||u,u=this.updateSdfFloatData(l+13,(null==a?void 0:a.y)??0)||u,u=this.updateSdfFloatData(l+14,(null==a?void 0:a.z)??0)||u,u=this.updateSdfFloatData(l+15,(null==a?void 0:a.w)??0)||u;const h=Math.min(4,o.length);for(let d=0;d<h;++d){const e=l+16+4*d;u=this.updateSdfFloatData(e+0,o[d].x)||u,u=this.updateSdfFloatData(e+1,o[d].y)||u,u=this.updateSdfFloatData(e+2,o[d].z)||u,u=this.updateSdfFloatData(e+3,o[d].w)||u}return u}update(e){const t=e.reduce(((e,{sdfs:t})=>e+t.length),0),n=this.ensureCapacity({maxEdits:e.length,maxSdfs:t}),i=[new r.Vector4,new r.Vector4],s=new r.Vector3,a=new r.Quaternion,o=new r.Vector3,l=new r.Vector4;let c=0,u=n;e.length!==this.dynoNumEdits.value&&(this.dynoNumEdits.value=e.length,this.numEdits=e.length,u=!0);for(const[r,{edit:h,sdfs:d}]of e.entries()){u=this.encodeEdit(r,{sdfFirst:c,sdfCount:d.length,invert:h.invert,rgbaBlendMode:La(h.rgbaBlendMode),softEdge:h.softEdge,sdfSmooth:h.sdfSmooth})||u;let e=!1;for(const t of d){l.set(t.scale.x,t.scale.y,t.scale.z,t.radius),t.scale.setScalar(1),t.updateMatrixWorld();t.matrixWorld.clone().invert().decompose(s,a,o),t.scale.set(l.x,l.y,l.z),t.updateMatrixWorld(),i[0].set(t.color.r,t.color.g,t.color.b,t.opacity),i[1].set(t.displace.x,t.displace.y,t.displace.z,1),e=this.encodeSdf(c,{sdfType:Pa(t.type),invert:t.invert,center:s,quaternion:a,scale:o,sizes:l},i)||e,c+=1}this.numSdfs=c,e&&(this.sdfTexture.needsUpdate=!0),u||(u=e)}return{updated:u,dynoUpdated:n}}modify(e){return function(e,t,n,r){const i=new $r({inTypes:{gsplat:Ui,sdfArray:Va,numEdits:"int",rgbaDisplaceEdits:"uvec4"},outTypes:{gsplat:Ui},globals:()=>[Oa,Na],inputs:{gsplat:e,sdfArray:t,numEdits:n,rgbaDisplaceEdits:r},statements:({inputs:e,outputs:t})=>{const{sdfArray:n,numEdits:r,rgbaDisplaceEdits:i}=e,{gsplat:s}=t;return Wr(`\n ${s} = ${e.gsplat};\n if (isGsplatActive(${s}.flags)) {\n for (int editIndex = 0; editIndex < ${r}; ++editIndex) {\n applyPackedRgbaDisplaceEdit(\n ${i}[editIndex], ${n}.sdfTexture, ${n}.numSdfs,\n ${s}.center, ${s}.rgba\n );\n }\n }\n `)}});return i.outputs.gsplat}(e,this.dynoSdfArray,this.dynoNumEdits,this.dynoEdits)}modifyCov(e){return function(e,t,n,r){const i=new $r({inTypes:{covsplat:Fi,sdfArray:Va,numEdits:"int",rgbaDisplaceEdits:"uvec4"},outTypes:{covsplat:Fi},globals:()=>[Oa,Na],inputs:{covsplat:e,sdfArray:t,numEdits:n,rgbaDisplaceEdits:r},statements:({inputs:e,outputs:t})=>{const{sdfArray:n,numEdits:r,rgbaDisplaceEdits:i}=e,{covsplat:s}=t;return Wr(`\n ${s} = ${e.covsplat};\n if (isCovSplatActive(${s}.flags)) {\n for (int editIndex = 0; editIndex < ${r}; ++editIndex) {\n applyPackedRgbaDisplaceEdit(\n ${i}[editIndex], ${n}.sdfTexture, ${n}.numSdfs,\n ${s}.center, ${s}.rgba\n );\n }\n }\n `)}});return i.outputs.covsplat}(e,this.dynoSdfArray,this.dynoNumEdits,this.dynoEdits)}}const Va={type:"SdfArray"},Oa=Xr("\n struct SdfArray {\n int numSdfs;\n usampler2D sdfTexture;\n };\n\n void unpackSdfArray(\n usampler2D sdfTexture, int sdfIndex, out uint flags,\n out vec3 center, out vec4 quaternion, out vec3 scale, out vec4 sizes,\n int numValues, out vec4 values[4]\n ) {\n uvec4 temp = texelFetch(sdfTexture, ivec2(0, sdfIndex), 0);\n flags = temp.w;\n center = vec3(uintBitsToFloat(temp.x), uintBitsToFloat(temp.y), uintBitsToFloat(temp.z));\n\n temp = texelFetch(sdfTexture, ivec2(1, sdfIndex), 0);\n quaternion = vec4(uintBitsToFloat(temp.x), uintBitsToFloat(temp.y), uintBitsToFloat(temp.z), uintBitsToFloat(temp.w));\n\n temp = texelFetch(sdfTexture, ivec2(2, sdfIndex), 0);\n scale = vec3(uintBitsToFloat(temp.x), uintBitsToFloat(temp.y), uintBitsToFloat(temp.z));\n\n temp = texelFetch(sdfTexture, ivec2(3, sdfIndex), 0);\n sizes = vec4(uintBitsToFloat(temp.x), uintBitsToFloat(temp.y), uintBitsToFloat(temp.z), uintBitsToFloat(temp.w));\n\n for (int i = 0; i < numValues; ++i) {\n temp = texelFetch(sdfTexture, ivec2(4 + i, sdfIndex), 0);\n values[i] = vec4(uintBitsToFloat(temp.x), uintBitsToFloat(temp.y), uintBitsToFloat(temp.z), uintBitsToFloat(temp.w));\n }\n }\n\n const uint SDF_FLAG_TYPE = 0xFFu;\n const uint SDF_FLAG_INVERT = 1u << 8u;\n\n const uint SDF_TYPE_ALL = 0u;\n const uint SDF_TYPE_PLANE = 1u;\n const uint SDF_TYPE_SPHERE = 2u;\n const uint SDF_TYPE_BOX = 3u;\n const uint SDF_TYPE_ELLIPSOID = 4u;\n const uint SDF_TYPE_CYLINDER = 5u;\n const uint SDF_TYPE_CAPSULE = 6u;\n const uint SDF_TYPE_INFINITE_CONE = 7u;\n\n float evaluateSdfArray(\n usampler2D sdfTexture, int numSdfs, int sdfFirst, int sdfCount, vec3 pos,\n float smoothK, int numValues, out vec4 outValues[4]\n ) {\n float distanceAccum = (smoothK == 0.0) ? 1.0 / 0.0 : 0.0;\n float maxExp = -1.0 / 0.0;\n for (int i = 0; i < numValues; ++i) {\n outValues[i] = vec4(0.0);\n }\n\n uint flags;\n vec3 center, scale;\n vec4 quaternion, sizes;\n vec4 values[4];\n\n int sdfLast = min(sdfFirst + sdfCount, numSdfs);\n for (int index = sdfFirst; index < sdfLast; ++index) {\n unpackSdfArray(sdfTexture, index, flags, center, quaternion, scale, sizes, numValues, values);\n uint sdfType = flags & SDF_FLAG_TYPE;\n vec3 sdfPos = quatVec(quaternion, pos * scale) + center;\n\n float distance;\n switch (sdfType) {\n case SDF_TYPE_ALL:\n distance = -1.0 / 0.0;\n break;\n case SDF_TYPE_PLANE: {\n distance = sdfPos.z;\n break;\n }\n case SDF_TYPE_SPHERE: {\n distance = length(sdfPos) - sizes.w;\n break;\n }\n case SDF_TYPE_BOX: {\n vec3 q = abs(sdfPos) - sizes.xyz + sizes.w;\n distance = length(max(q, 0.0)) + min(max(q.x, max(q.y, q.z)), 0.0) - sizes.w;\n break;\n }\n case SDF_TYPE_ELLIPSOID: {\n vec3 sizes = sizes.xyz;\n float k0 = length(sdfPos / sizes);\n float k1 = length(sdfPos / dot(sizes, sizes));\n distance = k0 * (k0 - 1.0) / k1;\n break;\n }\n case SDF_TYPE_CYLINDER: {\n vec2 d = abs(vec2(length(sdfPos.xz), sdfPos.y)) - sizes.wy;\n distance = min(max(d.x, d.y), 0.0) + length(max(d, 0.0));\n break;\n }\n case SDF_TYPE_CAPSULE: {\n sdfPos.y -= clamp(sdfPos.y, -0.5 * sizes.y, 0.5 * sizes.y);\n distance = length(sdfPos) - sizes.w;\n break;\n }\n case SDF_TYPE_INFINITE_CONE: {\n float angle = 0.25 * PI * sizes.w;\n vec2 c = vec2(sin(angle), cos(angle));\n vec2 q = vec2(length(sdfPos.xy), -sdfPos.z);\n float d = length(q - c * max(dot(q, c), 0.0));\n distance = d * (((q.x * c.y - q.y * c.x) < 0.0) ? -1.0 : 1.0);\n break;\n }\n }\n\n if ((flags & SDF_FLAG_INVERT) != 0u) {\n distance = -distance;\n }\n\n if (smoothK == 0.0) {\n if (distance < distanceAccum) {\n distanceAccum = distance;\n for (int i = 0; i < numValues; ++i) {\n outValues[i] = values[i];\n }\n }\n } else {\n float scaledDistance = -distance / smoothK;\n if (scaledDistance > maxExp) {\n float scale = exp(maxExp - scaledDistance);\n distanceAccum *= scale;\n for (int i = 0; i < numValues; ++i) {\n outValues[i] *= scale;\n }\n maxExp = scaledDistance;\n }\n\n float weight = exp(scaledDistance - maxExp);\n distanceAccum += weight;\n for (int i = 0; i < numValues; ++i) {\n outValues[i] += weight * values[i];\n }\n }\n }\n\n if (smoothK == 0.0) {\n return distanceAccum;\n } else {\n // Very distant SDFs may result in 0 accumulation\n if (distanceAccum == 0.0) {\n return 1.0 / 0.0;\n }\n for (int i = 0; i < numValues; ++i) {\n outValues[i] /= distanceAccum;\n }\n return (-log(distanceAccum) - maxExp) * smoothK;\n }\n }\n\n float modulateSdfArray(\n usampler2D sdfTexture, int numSdfs, int sdfFirst, int sdfCount, vec3 pos,\n float smoothK, int numValues, out vec4 values[4],\n float softEdge, bool invert\n ) {\n float distance = evaluateSdfArray(sdfTexture, numSdfs, sdfFirst, sdfCount, pos, smoothK, numValues, values);\n if (invert) {\n distance = -distance;\n }\n\n return (softEdge == 0.0) ? ((distance < 0.0) ? 1.0 : 0.0)\n : clamp(-distance / softEdge + 0.5, 0.0, 1.0);\n }\n"),Na=Xr("\n const uint EDIT_FLAG_BLEND = 0xFFu;\n const uint EDIT_BLEND_MULTIPLY = 0u;\n const uint EDIT_BLEND_SET_RGB = 1u;\n const uint EDIT_BLEND_ADD_RGBA = 2u;\n const uint EDIT_FLAG_INVERT = 0x100u;\n\n void decodeEdit(\n uvec4 packedEdit, out int sdfFirst, out int sdfCount,\n out bool invert, out uint rgbaBlendMode, out float softEdge, out float sdfSmooth\n ) {\n rgbaBlendMode = packedEdit.x & EDIT_FLAG_BLEND;\n invert = (packedEdit.x & EDIT_FLAG_INVERT) != 0u;\n\n sdfFirst = int(packedEdit.y & 0xFFFFu);\n sdfCount = int(packedEdit.y >> 16u);\n\n softEdge = uintBitsToFloat(packedEdit.z);\n sdfSmooth = uintBitsToFloat(packedEdit.w);\n }\n\n void applyRgbaDisplaceEdit(\n usampler2D sdfTexture, int numSdfs, int sdfFirst, int sdfCount, inout vec3 pos,\n float smoothK, float softEdge, bool invert, uint rgbaBlendMode, inout vec4 rgba\n ) {\n vec4 values[4];\n float modulate = modulateSdfArray(sdfTexture, numSdfs, sdfFirst, sdfCount, pos, smoothK, 2, values, softEdge, invert);\n // On Android, moving values[0] is necessary to work around a compiler bug.\n vec4 sdfRgba = values[0];\n vec4 sdfDisplaceScale = values[1];\n\n vec4 target;\n switch (rgbaBlendMode) {\n case EDIT_BLEND_MULTIPLY:\n target = rgba * sdfRgba;\n break;\n case EDIT_BLEND_SET_RGB:\n target = vec4(sdfRgba.rgb, rgba.a * sdfRgba.a);\n break;\n case EDIT_BLEND_ADD_RGBA:\n target = rgba + sdfRgba;\n break;\n default:\n // Debug output if blend mode not set\n target = vec4(fract(pos), 1.0);\n }\n rgba = mix(rgba, target, modulate);\n pos += sdfDisplaceScale.xyz * modulate;\n }\n\n void applyPackedRgbaDisplaceEdit(uvec4 packedEdit, usampler2D sdfTexture, int numSdfs, inout vec3 pos, inout vec4 rgba) {\n int sdfFirst, sdfCount;\n bool invert;\n uint rgbaBlendMode;\n float softEdge, sdfSmooth;\n decodeEdit(packedEdit, sdfFirst, sdfCount, invert, rgbaBlendMode, softEdge, sdfSmooth);\n applyRgbaDisplaceEdit(sdfTexture, numSdfs, sdfFirst, sdfCount, pos, sdfSmooth, softEdge, invert, rgbaBlendMode, rgba);\n }\n");const $a=new Float32Array(1);class Ga{constructor(e){this.modifier=e,this.cache=new Map}apply(e){let t=this.cache.get(e);return t||(t=qr({index:"int"},{gsplat:Ui},(({index:t})=>{const{gsplat:n}=e.apply({index:t});return this.modifier.apply({gsplat:n})})),this.cache.set(e,t)),t}}class qa{constructor(){this.scale=new Ss({value:Number.NEGATIVE_INFINITY}),this.rotate=new Ms({value:new r.Quaternion(Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY)}),this.translate=new _s({value:new r.Vector3(Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY)})}apply(e){return((e,{scale:t,scales:n,rotate:r,translate:i})=>new Xs({position:e,scale:t,scales:n,rotate:r,translate:i}).outputs.position)(e,{scale:this.scale,rotate:this.rotate,translate:this.translate})}applyDir(e){return((e,{scale:t,scales:n,rotate:r})=>new Ys({dir:e,scale:t,scales:n,rotate:r}).outputs.dir)(e,{rotate:this.rotate})}applyGsplat(e){return Gi(e,{scale:this.scale,rotate:this.rotate,translate:this.translate})}updateFromMatrix(e){const t=new r.Vector3,n=new r.Quaternion,i=new r.Vector3;e.decompose(i,n,t);const s=(t.x+t.y+t.z)/3;let a=!1;return s!==this.scale.value&&(this.scale.value=s,a=!0),i.equals(this.translate.value)||(this.translate.value.copy(i),a=!0),n.equals(this.rotate.value)||(this.rotate.value.copy(n),a=!0),a}update(e){return e.updateMatrixWorld(),this.updateFromMatrix(e.matrixWorld)}}class Ha{constructor(){this.basis=new As({value:new r.Matrix3}),this.offset=new _s({value:new r.Vector3})}apply(e){const t=zs(this.basis,e);return Us(t,this.offset)}applyDir(e){return zs(this.basis,e)}applyCovSplat(e){return new $r({inTypes:{covsplat:Fi,basis:"mat3",offset:"vec3"},outTypes:{covsplat:Fi},inputs:{covsplat:e,basis:this.basis,offset:this.offset},statements:({inputs:e,outputs:t})=>{const{covsplat:n,basis:r,offset:i}=e;return n&&r&&i?Wr(`\n ${t.covsplat}.flags = 0u;\n if (isCovSplatActive(${n}.flags)) {\n ${t.covsplat}.flags = ${n}.flags;\n ${t.covsplat}.index = ${n}.index;\n ${t.covsplat}.rgba = ${n}.rgba;\n\n ${t.covsplat}.center = ${r} * ${n}.center + ${i};\n \n mat3 cov = mat3(\n ${n}.xxyyzz.x, ${n}.xyxzyz.x, ${n}.xyxzyz.y,\n ${n}.xyxzyz.x, ${n}.xxyyzz.y, ${n}.xyxzyz.z,\n ${n}.xyxzyz.y, ${n}.xyxzyz.z, ${n}.xxyyzz.z\n );\n cov = ${r} * cov * transpose(${r});\n ${t.covsplat}.xxyyzz = vec3(cov[0][0], cov[1][1], cov[2][2]);\n ${t.covsplat}.xyxzyz = vec3(cov[0][1], cov[0][2], cov[1][2]);\n }\n `):[`${t.covsplat}.flags = 0u;`]}}).outputs.covsplat}updateFromMatrix(e){const t=(new r.Matrix3).setFromMatrix4(e),n=(new r.Vector3).setFromMatrixColumn(e,3),i=!t.equals(this.basis.value)||!n.equals(this.offset.value);return i&&(this.basis.value.copy(t),this.offset.value.copy(n)),i}update(e){return e.updateMatrixWorld(),this.updateFromMatrix(e.matrixWorld)}}class ja extends r.Object3D{constructor({numSplats:e,generator:t,covGenerator:n,construct:r,update:i}){if(super(),this.numSplats=e??0,this.generator=t,this.covGenerator=n,this.frameUpdate=i,this.version=0,this.mappingVersion=0,r){const e=r(this);Object.assign(this,e)}}updateVersion(){this.version+=1}updateMappingVersion(){this.mappingVersion+=1,this.version+=1}set needsUpdate(e){e&&this.updateVersion()}}const Wa=class e{constructor({extSplats:e,covSplats:t}={}){if(this.time=0,this.deltaTime=0,this.viewToWorld=new r.Matrix4,this.viewOrigin=new r.Vector3,this.viewDirection=new r.Vector3,this.maxSplats=0,this.numSplats=0,this.target=null,this.mapping=[],this.version=-1,this.mappingVersion=-1,this.readback=null,this.readbackSplats=[],!Qr)throw new Error("Spark requires THREE.js r179 or above");this.extSplats=e??!0,this.covSplats=t??!1}dispose(){this.target&&(this.target.dispose(),this.target=null)}getTextures(){return this.target?this.target.textures:e.emptyTextures}generateMapping(e){let t=0;const n=e.map((e=>{const n=t,r=Math.ceil(e/br)*br;return t+=r,{base:n,count:e}}));return{maxSplats:t,mapping:n}}ensureGenerate({maxSplats:e}){if(this.target&&(e??1)<=this.maxSplats)return!1;this.dispose();const t=gi(e??1),{width:n,height:i,depth:s}=t;if(this.maxSplats=t.maxSplats,this.target=new r.WebGLArrayRenderTarget(n,i,s,{depthBuffer:!1,stencilBuffer:!1,generateMipmaps:!1,magFilter:r.NearestFilter,minFilter:r.NearestFilter,format:r.RGBAIntegerFormat,type:r.UnsignedIntType}),this.target.scissorTest=!0,this.extSplats){const e=this.target.texture.clone(),t=this.target.texture.clone();t.format=r.RGBAFormat,t.type=r.UnsignedByteType,t.internalFormat="RGBA8",this.target.textures=[this.target.texture,e,t]}else{const e=this.target.texture.clone();e.format=r.RGBAFormat,e.type=r.UnsignedByteType,e.internalFormat="RGBA8",this.target.textures=[this.target.texture,e]}return!0}saveRenderState(e){return{target:e.getRenderTarget(),xrEnabled:e.xr.enabled,autoClear:e.autoClear}}resetRenderState(e,t){e.setRenderTarget(t.target),e.xr.enabled=t.xrEnabled,e.autoClear=t.autoClear}prepareProgramMaterial(t,n){const r=t??n;if(!r)throw new Error("Either generator or covGenerator must be provided");let i=e.generatorProgram.get(r);if(!i){const s=qr({index:"int"},{},(({index:r},i,{roots:s})=>{if(t&&(t.inputs.index=r),n&&(n.inputs.index=r),this.extSplats)if(this.covSplats)if(n){const e=ds(n.outputs.covsplat);s.push(e)}else{if(!t)throw new Error("Generator must be provided");{const e=Oi(t.outputs.gsplat),n=ds(e);s.push(n)}}else{if(!t)throw new Error("Generator must be provided");{const e=(a=t.outputs.gsplat,new fs({gsplat:a}));s.push(e)}}else{if(this.covSplats){let r;if(n)r=n.outputs.covsplat;else{if(!t)throw new Error("Generator must be provided");r=Oi(t.outputs.gsplat)}const i=Fs(ss(r).outputs.center,e.viewCenterUniform),a=zs(ss(r).outputs.opacity,Br("float",.5));r=as({covsplat:r,center:i,opacity:a});const o=((e,t)=>new ms({covsplat:e,rgbMinMaxLnScaleMinMax:t}))(r,Br("vec4",[0,1,yr,9]));s.push(o)}else{if(!t)throw new Error("Generator must be provided");{const n=Fs(Ni(t.outputs.gsplat).outputs.center,e.viewCenterUniform),r=zs(Ni(t.outputs.gsplat).outputs.opacity,Br("float",.5)),i=$i({gsplat:t.outputs.gsplat,center:n,opacity:r}),a=hs(i,Br("vec4",[0,1,yr,9]));s.push(a)}}if(!t)throw new Error("Generator must be provided")}var a,o,l,c,u;if(t){const n=((e,t,n,r)=>new xs({gsplat:e,viewCenter:t,viewDir:n,sortRadial:r}))(t.outputs.gsplat,e.viewCenterUniform,e.viewDirUniform,e.sortRadialUniform);s.push(n)}if(n){const t=(o=n.outputs.covsplat,l=e.viewCenterUniform,c=e.viewDirUniform,u=e.sortRadialUniform,new ys({covsplat:o,viewCenter:l,viewDir:c,sortRadial:u}));s.push(t)}}));i=new Rs({graph:s,inputs:{index:"_index"},outputs:{},template:this.extSplats?e.programExtTemplate:e.programTemplate}),e.generatorProgram.set(r,i)}Object.assign(i.uniforms,{targetLayer:{value:0},targetBase:{value:0},targetCount:{value:0}});const s=i.prepareMaterial();return e.fullScreenQuad.material=s,{program:i,material:s}}generate({generator:t,covGenerator:n,base:r,count:i,renderer:s}){if(!this.target)throw new Error("Target must be initialized with ensureGenerate");if(r+i>this.maxSplats)throw new Error("Base + count exceeds maxSplats");const{program:a,material:o}=this.prepareProgramMaterial(t,n);a.update();const l=this.saveRenderState(s),c=Math.ceil((r+i)/br)*br,u=4194304;for(o.uniforms.targetBase.value=r,o.uniforms.targetCount.value=i;r<c;){const t=Math.floor(r/u);o.uniforms.targetLayer.value=t;const n=t*u,i=Math.floor((r-n)/br),a=Math.min(wr,Math.ceil((c-n)/br));this.target.scissor.set(0,i,br,a-i),s.setRenderTarget(this.target,t),s.xr.enabled=!1,s.autoClear=!1,e.fullScreenQuad.render(s),r+=br*(a-i)}return this.resetRenderState(s,l),{nextBase:c}}prepareGenerate({renderer:t,scene:n,time:r,camera:i,sortRadial:s,renderSize:a,previous:o,lodInstances:l}){var c;this.viewToWorld.copy(i.matrixWorld),i.getWorldPosition(this.viewOrigin),i.getWorldDirection(this.viewDirection),e.viewCenterUniform.value.copy(this.viewOrigin),e.viewDirUniform.value.copy(this.viewDirection),e.sortRadialUniform.value=s,this.time=r,this.deltaTime=r-o.time;const u=[];n.traverse((e=>{e instanceof ja&&(i.layers&&!i.layers.test(e.layers)||u.push(e))}));const h=new Set;n.traverseVisible((e=>{if(e instanceof za){let t=e.parent;for(;null!=t&&!(t instanceof lo);)t=t.parent;null==t&&h.add(e)}}));const d=Array.from(h);for(const e of u)try{null==(c=e.frameUpdate)||c.call(e,{renderer:t,object:e,time:this.time,deltaTime:this.deltaTime,viewToWorld:this.viewToWorld,camera:i,renderSize:a,globalEdits:d,lodIndices:l&&e instanceof lo?l.get(e):void 0})}catch(b){e.generator=void 0,e.covGenerator=void 0,e.generatorError=b}const p=[];n.traverseVisible((e=>{e instanceof ja&&(i.layers&&!i.layers.test(e.layers)||p.push(e))}));const m=p.map((e=>e.numSplats)),{maxSplats:f,mapping:g}=this.generateMapping(m),x=o.mapping.reduce(((e,t)=>(e.set(t.node,t),e)),new Map);this.mapping=[],this.numSplats=0,g.forEach((({base:e,count:t},n)=>{const r=p[n],i=x.get(r);i&&i.count!==r.numSplats&&r.updateMappingVersion();const{generator:s,covGenerator:a}=r;if((s||a)&&t>0){const{version:n,mappingVersion:i}=r;this.mapping.push({node:r,generator:s,covGenerator:a,version:n,mappingVersion:i,base:e,count:t}),this.numSplats=Math.max(this.numSplats,e+t)}}));const{splatsUpdated:y,mappingUpdated:v}=o.checkVersions(this.mapping);return this.version=o.version+(y?1:0),this.mappingVersion=o.mappingVersion+(v?1:0),{sameMapping:!v,version:this.version,mappingVersion:this.mappingVersion,visibleGenerators:p,generate:()=>{this.ensureGenerate({maxSplats:f});for(const{node:e,base:n,count:r}of this.mapping){const{generator:i,covGenerator:s}=e;(i||s)&&r>0&&this.generate({generator:i,covGenerator:s,base:n,count:r,renderer:t})}},readback:async()=>{const e=this.getTextures();0===this.readbackSplats.length&&(this.readbackSplats=[new Cs({value:e[0],key:"extSplats"}),new Cs({value:e[1],key:"extSplats"})]),this.readbackSplats[0].value=e[0],this.readbackSplats[1].value=e[1],this.readback||(this.readback=new Ca({renderer:t}));const n=this.readback,r=this.extSplats?8:4,i=n.ensureBuffer(this.numSplats*r,new Uint32Array(0)),s=qr({index:"int"},{rgba8:"vec4"},(({index:e})=>({rgba8:new $r({inTypes:{index:"int",extSplats1:"usampler2DArray",extSplats2:"usampler2DArray"},outTypes:{rgba8:"vec4"},inputs:{index:e,extSplats1:this.readbackSplats[0],extSplats2:this.readbackSplats[1]},statements:({inputs:e,outputs:t})=>this.extSplats?Wr(`\n int indexDiv8 = ${e.index} >> 3;\n ivec3 coord = splatTexCoord(indexDiv8);\n uvec4 packedData;\n if ((${e.index} & 4) == 0) {\n packedData = texelFetch(${e.extSplats1}, coord, 0);\n } else {\n packedData = texelFetch(${e.extSplats2}, coord, 0);\n }\n\n int indexMod4 = ${e.index} & 3;\n uint data = (indexMod4 == 0) ? packedData.x\n : (indexMod4 == 1) ? packedData.y\n : (indexMod4 == 2) ? packedData.z\n : packedData.w;\n ${t.rgba8} = uintToVec4(data);\n `):Wr(`\n int indexDiv4 = ${e.index} >> 2;\n ivec3 coord = splatTexCoord(indexDiv4);\n uvec4 packedData = texelFetch(${e.extSplats1}, coord, 0);\n\n int indexMod4 = ${e.index} & 3;\n uint data = (indexMod4 == 0) ? packedData.x\n : (indexMod4 == 1) ? packedData.y\n : (indexMod4 == 2) ? packedData.z\n : packedData.w;\n ${t.rgba8} = uintToVec4(data);\n `)}).outputs.rgba8})));return await n.renderReadback({reader:s,count:this.numSplats*r,renderer:t,readback:i})}}}checkVersions(e){if(this.mapping.length!==e.length)return{splatsUpdated:!0,mappingUpdated:!0};const t=this.mapping.some(((t,n)=>{const r=e[n];return t.node!==r.node||t.base!==r.base||t.count!==r.count||t.mappingVersion!==r.mappingVersion}));if(t)return{splatsUpdated:!0,mappingUpdated:!0};return{splatsUpdated:this.mapping.some(((t,n)=>t.version!==e[n].version)),mappingUpdated:t}}};Wa.viewCenterUniform=new _s({value:new r.Vector3}),Wa.viewDirUniform=new _s({value:new r.Vector3}),Wa.sortRadialUniform=new ws({value:!0}),Wa.emptyTexture=(()=>{const{width:e,height:t,depth:n,maxSplats:i}=gi(1),s=new Uint32Array(4*i),a=new r.DataArrayTexture(s,e,t,n);return a.format=r.RGBAIntegerFormat,a.type=r.UnsignedIntType,a.internalFormat="RGBA32UI",a.needsUpdate=!0,a})(),Wa.emptyTextures=[Wa.emptyTexture,Wa.emptyTexture],Wa.programExtTemplate=new Ds(Aa().computeUvec4x2Vec4Template),Wa.programTemplate=new Ds(Aa().computeUvec4Vec4Template),Wa.generatorProgram=new WeakMap,Wa.fullScreenQuad=new o(new r.RawShaderMaterial({visible:!1}));let Xa=Wa;class Ya extends r.InstancedBufferGeometry{constructor(){super(),this.setAttribute("position",new r.BufferAttribute(Ka,3)),this.setIndex(new r.BufferAttribute(Qa,1))}}const Ka=new Float32Array([-1,-1,0,1,-1,0,1,1,0,-1,1,0]),Qa=new Uint16Array([0,1,2,0,2,3]),Za=class e extends r.Mesh{constructor(t){if(!t)throw new Error("SparkRenderer options are required");if(!t.renderer)throw new Error("renderer is required in SparkRenderer options");const n=e.makeUniforms();Object.assign(n,t.extraUniforms??{});const i=Aa(),s=t.premultipliedAlpha??!0,a=new Ya,o=new r.ShaderMaterial({glslVersion:r.GLSL3,vertexShader:t.vertexShader??i.splatVertex,fragmentShader:t.fragmentShader??i.splatFragment,uniforms:n,premultipliedAlpha:s,transparent:t.transparent??!0,depthTest:t.depthTest??!0,depthWrite:t.depthWrite??!1,side:r.DoubleSide,allowOverride:!1});super(a,o),this.renderSize=new r.Vector2,this.lastFrame=-1,this.updateTimeoutId=-1,this.orderingTexture=null,this.maxSplats=0,this.activeSplats=0,this.accumulators=[],this.sorting=!1,this.sortDirty=!1,this.lastSortTime=0,this.sortWorker=null,this.sortTimeoutId=-1,this.sortedCenter=(new r.Vector3).setScalar(Number.NEGATIVE_INFINITY),this.sortedDir=(new r.Vector3).setScalar(0),this.readback32=new Uint32Array(0),this.lastLodRaycastTime=0,this.lodWorker=null,this.lodMeshes=[],this.lodDirty=!1,this.lodIds=new Map,this.lodIdToSplats=new Map,this.lodInitQueue=[],this.lodInstances=new Map,this.lodUpdates=[],this.lastTraverseTime=0,this.pagerId=0,this.superXY=1,this.flushAfterGenerate=!1,this.flushAfterRead=!1,this.readPause=1,this.sortPause=0,this.sortDelay=0,this.pageSizeWarning=!1,this.material=o,this.uniforms=n,this.frustumCulled=!1,this.renderer=t.renderer,this.onDirty=t.onDirty,this.dirty=!0,this.autoUpdate=t.autoUpdate??!0,this.preUpdate=t.preUpdate??!0,this.maxStdDev=t.maxStdDev??Math.sqrt(8),this.minPixelRadius=t.minPixelRadius??0,this.maxPixelRadius=t.maxPixelRadius??512,this.accumExtSplats=t.accumExtSplats??!1,this.covSplats=t.covSplats??!1,this.minAlpha=t.minAlpha??1/255*.5,this.enable2DGS=t.enable2DGS??!1,this.preBlurAmount=t.preBlurAmount??0,this.blurAmount=t.blurAmount??.3,this.focalDistance=t.focalDistance??0,this.apertureAngle=t.apertureAngle??0,this.falloff=t.falloff??1,this.clipXY=t.clipXY??1.4,this.focalAdjustment=t.focalAdjustment??1,this.encodeLinear=t.encodeLinear??!1,this.sortRadial=t.sortRadial??!0,this.minSortIntervalMs=t.minSortIntervalMs??0,this.enableLod=t.enableLod??!0,this.enableDriveLod=t.enableDriveLod??this.enableLod,this.enableLodFetching=t.enableLodFetching??!0,this.lodSplatCount=t.lodSplatCount,this.lodSplatScale=t.lodSplatScale??1,this.lodRenderScale=t.lodRenderScale??1,this.lodInflate=t.lodInflate??!1,this.pagedExtSplats=t.pagedExtSplats??!1;const l=xi()?yi()?96:128:256;this.maxPagedSplats=t.maxPagedSplats??65536*l,this.numLodFetchers=t.numLodFetchers??3,this.behindFoveate=t.behindFoveate??.2,this.coneFov0=t.coneFov0??90,this.coneFov=t.coneFov??120,this.coneFoveate=t.coneFoveate??.4,this.lodRaycast=void 0===t.lodRaycast?xi()?1e4:25e3:t.lodRaycast,this.lodRaycastIntervalMs=t.lodRaycastIntervalMs??500,this.clock=t.clock?vi(t.clock):new r.Clock;const c={extSplats:this.accumExtSplats,covSplats:this.covSplats};if(this.display=new Xa(c),this.current=this.display,this.accumulators.push(new Xa(c)),this.accumulators.push(new Xa(c)),t.target){const{width:e,height:n,doubleBuffer:i,superXY:s,...a}=t.target,o=Math.max(1,Math.min(4,s??1));if(e*o>8192||n*o>8192)throw new Error("Target size too large");this.superXY=o;const l=e*o,c=n*o,u={format:r.RGBAFormat,type:r.UnsignedByteType,colorSpace:r.SRGBColorSpace,...a};this.target=new r.WebGLRenderTarget(l,c,u),i&&(this.backTarget=new r.WebGLRenderTarget(l,c,u)),this.encodeLinear=t.encodeLinear??!0}}static makeUniforms(){return{renderSize:{value:new r.Vector2},near:{value:.1},far:{value:1e3},renderToViewQuat:{value:new r.Quaternion},renderToViewPos:{value:new r.Vector3},renderToViewBasis:{value:new r.Matrix3},renderToViewOffset:{value:new r.Vector3},maxStdDev:{value:1},minPixelRadius:{value:0},maxPixelRadius:{value:512},minAlpha:{value:1/255*.5},enable2DGS:{value:!1},lodInflate:{value:!1},preBlurAmount:{value:0},blurAmount:{value:.3},focalDistance:{value:0},apertureAngle:{value:0},falloff:{value:1},clipXY:{value:1.4},focalAdjustment:{value:1},encodeLinear:{value:!1},ordering:{type:"t",value:e.emptyOrdering},enableExtSplats:{value:!1},enableCovSplats:{value:!1},extSplats:{type:"t",value:Xa.emptyTexture},extSplats2:{type:"t",value:Xa.emptyTexture},time:{value:0},deltaTime:{value:0},debugFlag:{value:!1}}}dispose(){this.target&&(this.target.dispose(),this.target=void 0),this.backTarget&&(this.backTarget.dispose(),this.backTarget=void 0),this.orderingTexture&&(this.orderingTexture.dispose(),this.orderingTexture=null);const e=new Set;e.add(this.display),e.add(this.current);for(const n of this.accumulators)e.add(n);for(const n of e)n.dispose();const t=this.lodInstances.values();this.lodInstances.clear();for(const n of t)n.texture.dispose();this.sortWorker&&(this.sortWorker.dispose(),this.sortWorker=null),this.lodWorker&&(this.lodWorker.dispose(),this.lodWorker=null),this.pager&&(this.pager.dispose(),this.pager=void 0)}setDirty(){var e;this.dirty||(this.dirty=!0,null==(e=this.onDirty)||e.call(this))}onBeforeRender(t,n,i){var s;const a=e.sparkOverride??this,o=t.info.render.frame,l=o!==a.lastFrame;if(a.lastFrame=o,a.target)a.renderSize.set(a.target.width,a.target.height);else{const e=t.getDrawingBufferSize(a.renderSize);if(t.xr.isPresenting&&1===e.x&&1===e.y){const n=null==(s=t.xr.getSession())?void 0:s.renderState.baseLayer;n&&(e.x=n.framebufferWidth,e.y=n.framebufferHeight)}}this.uniforms.renderSize.value.copy(a.renderSize);const c=i;this.uniforms.near.value=c.near,this.uniforms.far.value=c.far;this.geometry.instanceCount=a.activeSplats;const u=new r.Matrix4;this.display.extSplats||u.makeTranslation(a.display.viewOrigin);const h=i.matrixWorld.clone().invert().multiply(u);if(h.decompose(this.uniforms.renderToViewPos.value,this.uniforms.renderToViewQuat.value,new r.Vector3),this.uniforms.renderToViewBasis.value.setFromMatrix4(h),this.uniforms.maxStdDev.value=a.maxStdDev,this.uniforms.minPixelRadius.value=a.minPixelRadius,this.uniforms.maxPixelRadius.value=a.maxPixelRadius,this.uniforms.minAlpha.value=a.minAlpha,this.uniforms.enable2DGS.value=a.enable2DGS,this.uniforms.lodInflate.value=a.lodInflate,this.uniforms.preBlurAmount.value=a.preBlurAmount,this.uniforms.blurAmount.value=a.blurAmount,this.uniforms.focalDistance.value=a.focalDistance,this.uniforms.apertureAngle.value=a.apertureAngle,this.uniforms.falloff.value=a.falloff,this.uniforms.clipXY.value=a.clipXY,this.uniforms.focalAdjustment.value=a.focalAdjustment,this.uniforms.encodeLinear.value=a.encodeLinear,this.uniforms.ordering.value=a.orderingTexture??e.emptyOrdering,this.uniforms.enableExtSplats.value=this.display.extSplats,this.uniforms.enableCovSplats.value=this.display.covSplats,this.display.extSplats){const e=a.display.getTextures();this.uniforms.extSplats.value=e[0],this.uniforms.extSplats2.value=e[1]}else{const e=a.display.getTextures();this.uniforms.extSplats.value=e[0],this.uniforms.extSplats2.value=e[0]}if(this.uniforms.time.value=a.display.time,this.uniforms.deltaTime.value=a.display.deltaTime,this.uniforms.debugFlag.value=performance.now()/1e3%2<1,a.autoUpdate&&l){const e=a.preUpdate&&!t.xr.isPresenting,r=t.xr.isPresenting?t.xr.getCamera():i;e?a.updateInternal({scene:n,camera:r,autoUpdate:!0}):-1===a.updateTimeoutId&&(a.updateTimeoutId=setTimeout((()=>{a.updateTimeoutId=-1,a.updateInternal({scene:n,camera:r,autoUpdate:!0})}),1))}a.dirty=!1}clearSplats(){this.activeSplats=0,this.display.numSplats=0,this.setDirty()}async update({scene:e,camera:t}){await this.updateInternal({scene:e,camera:t,autoUpdate:!1})}async updateInternal({scene:e,camera:t,autoUpdate:n}){const i=this.renderer,s=this.time??this.clock.getElapsedTime(),a=t.getWorldPosition(new r.Vector3),o=t.getWorldDirection(new r.Vector3),l=a.distanceTo(this.sortedCenter)>.001||o.dot(this.sortedDir)<.999,c=this.accumulators.pop();if(!c)throw new Error("No next accumulator");if(c===this.current)throw new Error("Next accumulator is the same as the current accumulator");const{version:u,mappingVersion:h,visibleGenerators:d,generate:p}=c.prepareGenerate({renderer:i,scene:e,time:s,camera:t,sortRadial:this.sortRadial??!0,renderSize:this.renderSize,previous:this.current,lodInstances:this.enableLod?this.lodInstances:void 0});let m=!0;const f=l||u!==this.current.version;if(n&&!f&&(m=!1),h!==this.display.mappingVersion&&this.sorting&&(m=!1),m){if(p(),this.flushAfterGenerate){i.getContext().flush()}this.display.mappingVersion===c.mappingVersion?(this.accumulators.push(this.display),this.display=c):this.display!==this.current&&this.accumulators.push(this.current),this.current=c,this.sortDirty=!0,this.setDirty()}else this.accumulators.push(c);this.enableDriveLod&&this.driveLod({visibleGenerators:d,camera:t,scene:e}),await this.driveSort()}async driveSort(){if(this.sorting||!this.sortDirty)return;-1!==this.sortTimeoutId&&(clearTimeout(this.sortTimeoutId),this.sortTimeoutId=-1);const e=performance.now(),t=this.lastSortTime?this.lastSortTime+this.minSortIntervalMs:e;if(e<t)return void(this.sortTimeoutId=setTimeout((()=>{this.sortTimeoutId=-1,this.driveSort()}),t-e));this.sorting=!0,this.sortDirty=!1,this.lastSortTime=e,this.readPause>0&&await new Promise((e=>setTimeout(e,this.readPause)));const n=this.current;this.sortedCenter.copy(n.viewOrigin),this.sortedDir.copy(n.viewDirection);const{numSplats:i,maxSplats:s}=n,a=Math.max(1,Math.ceil(s/16384)),o=16384*a;this.maxSplats=Math.max(this.maxSplats,o);const l=new Uint32Array(this.maxSplats),c=Ca.ensureBuffer(s,this.readback32);this.readback32=c,await this.readbackDepth({current:n,renderer:this.renderer,numSplats:i,readback:c}),this.sortPause>0&&await new Promise((e=>setTimeout(e,this.sortPause))),this.sortWorker||(this.sortWorker=new Pi);const u=await this.sortWorker.call("sortSplats32",{numSplats:i,readback:c,ordering:l});if(this.sortDelay>0&&await new Promise((e=>setTimeout(e,this.sortDelay))),this.readback32=u.readback,this.activeSplats=u.activeSplats,this.orderingTexture&&a>this.orderingTexture.image.height&&(this.orderingTexture.dispose(),this.orderingTexture=null),this.orderingTexture){const e=this.renderer,t=e.getContext();if(e.properties.has(this.orderingTexture)){const n=e.properties.get(this.orderingTexture).__webglTexture;if(!n)throw new Error("ordering texture not found");e.state.activeTexture(t.TEXTURE0),e.state.bindTexture(t.TEXTURE_2D,n),t.bindBuffer(t.PIXEL_UNPACK_BUFFER,null),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texSubImage2D(t.TEXTURE_2D,0,0,0,4096,a,t.RGBA_INTEGER,t.UNSIGNED_INT,u.ordering),e.state.bindTexture(t.TEXTURE_2D,null)}else this.orderingTexture.needsUpdate=!0}else{const e=new r.DataTexture(u.ordering,4096,a,r.RGBAIntegerFormat,r.UnsignedIntType);e.internalFormat="RGBA32UI",e.needsUpdate=!0,this.orderingTexture=e}this.current.mappingVersion===n.mappingVersion&&this.current.mappingVersion!==this.display.mappingVersion&&(this.accumulators.push(this.display),this.display=this.current),this.sorting=!1,this.setDirty(),this.driveSort()}ensureLodWorker(){return this.lodWorker||(this.lodWorker=new Pi),this.lodWorker}defaultSplatTarget(){return navigator.xr&&/Oculus/.test(navigator.userAgent)?5e5:navigator.xr&&yi()&&/Safari/.test(navigator.userAgent)&&xi()?75e4:/Android/.test(navigator.userAgent)||/Tizen/.test(navigator.userAgent)?1e6:yi()?15e5:25e5}driveLod({visibleGenerators:e,camera:t,scene:n}){var i,s;const a=this.defaultSplatTarget(),o=(this.lodSplatCount??a)*this.lodSplatScale;let l=0;if(t instanceof r.PerspectiveCamera){const e=Math.tan(.5*t.fov*Math.PI/180);l=2*e/this.renderSize.y}else if(t instanceof r.OrthographicCamera){const e=(t.top-t.bottom)/t.zoom,n=(t.right-t.left)/t.zoom,r=e/Math.max(1,this.renderSize.y),i=n/Math.max(1,this.renderSize.x);l=Math.min(i,r)}l*=this.lodRenderScale;const c=new r.Vector3,u=new r.Quaternion;if(this.current.viewToWorld.decompose(c,u,new r.Vector3),this.lodPosOverride&&c.copy(this.lodPosOverride),this.lodQuatOverride&&u.copy(this.lodQuatOverride).normalize(),this.lastLod){this.lastLod.pixelScaleLimit===l&&this.lastLod.maxSplats===o||(this.lodDirty=!0);const e=c.distanceTo(this.lastLod.pos),t=Math.max(0,1-e/1),n=u.dot(this.lastLod.quat);t*Math.max(0,1-(1-n)/.01)<.999&&(this.lodDirty=!0)}const h=this.enableLod?e.filter((e=>{var t,n;return e instanceof lo&&((null==(t=e.packedSplats)?void 0:t.lodSplats)||(null==(n=e.extSplats)?void 0:n.lodSplats)||e.paged)&&!1!==e.enableLod})):[],d=h.some((e=>e.paged));(this.lodMeshes.length!==h.length||h.some(((e,t)=>e!==this.lodMeshes[t].mesh||e.version>this.lodMeshes[t].version)))&&(this.lodDirty=!0),this.lodMeshes=h.map((e=>({mesh:e,version:e.version+1}))),this.lodInitQueue=[];const p=performance.now();for(const r of h){const e=(null==(i=r.packedSplats)?void 0:i.lodSplats)??(null==(s=r.extSplats)?void 0:s.lodSplats)??r.paged;if(e){const t=this.lodIds.get(e);t?t.lastTouched=p:this.lodInitQueue.push(e)}}this.ensureLodWorker().tryExclusive((async e=>{if(d&&!this.pager){this.pager=new no({renderer:this.renderer,extSplats:this.pagedExtSplats,maxSplats:this.maxPagedSplats,numFetchers:this.numLodFetchers});const{lodId:t}=await e.call("newLodTree",{capacity:this.pager.maxSplats});this.pagerId=t}if(this.pager)for(const{mesh:t}of this.lodMeshes)t.paged&&!t.paged.pager&&(t.paged.pager=this.pager);if(this.lodInitQueue.length>0){const t=this.lodInitQueue;for(this.lodInitQueue=[];t.length>0;){const n=t.shift();n&&(await this.initLodTree(e,n),this.lodDirty=!0)}}if(this.pager){const e=this.pager.consumeLodTreeUpdates();for(const{splats:t,page:n,chunk:r,numSplats:i,lodTree:s}of e){const e=this.lodIds.get(t);e&&(s&&0===r&&(e.rootPage=n),this.lodUpdates.push({lodId:e.lodId,pageBase:n*this.pager.pageSplats,chunkBase:r*this.pager.pageSplats,count:i,lodTreeData:s}))}}if(this.lodUpdates.length>0){const t=this.lodUpdates;this.lodUpdates=[],await e.call("updateLodTrees",{ranges:t}),this.lodDirty=!0}if(this.lodDirty){const t=performance.now(),n=new r.Vector3;if(this.lastLod){const e=Math.max(1,t-this.lastLod.timestamp);n.copy(c).sub(this.lastLod.pos).multiplyScalar(this.lastTraverseTime/e)}this.lastLod={pos:c,quat:u,pixelScaleLimit:l,maxSplats:o,timestamp:t},this.lodDirty=!1,await this.updateLodInstances(e,n,h,o,c,u,l),this.currentLod=this.lastLod,this.setDirty()}await this.cleanupLodTrees(e)}))}async initLodTree(e,t){if(t instanceof fo||t instanceof Qs){const{lodId:n}=await e.call("initLodTree",{numSplats:t.numSplats??0,lodTree:t.extra.lodTree.slice()});this.lodIds.set(t,{lodId:n,lastTouched:performance.now()}),this.lodIdToSplats.set(n,t)}else{const{lodId:n}=await e.call("newSharedLodTree",{lodId:this.pagerId});this.lodIds.set(t,{lodId:n,lastTouched:performance.now()}),this.lodIdToSplats.set(n,t)}}async updateLodInstances(e,t,n,i,s,a,o){const l=new Map,c=(new r.Matrix4).compose(s,a,(new r.Vector3).setScalar(1)),u=n.reduce(((e,t)=>{var n,r;l.set(t.uuid,t);const i=t.matrixWorld.clone().invert().multiply(c),s=(null==(n=t.packedSplats)?void 0:n.lodSplats)??(null==(r=t.extSplats)?void 0:r.lodSplats)??t.paged;if(!s)return e;const a=this.lodIds.get(s);return a?(this.pager&&t.paged&&void 0===a.rootPage||(e[t.uuid]={instanceId:t.uuid,lodId:a.lodId,rootPage:a.rootPage,viewToObjectCols:i.elements,lodScale:t.lodScale,behindFoveate:t.behindFoveate??this.behindFoveate,coneFov0:t.coneFov0??this.coneFov0,coneFov:t.coneFov??this.coneFov,coneFoveate:t.coneFoveate??this.coneFoveate}),e):e}),{}),h=performance.now(),d=await e.call("traverseLodTrees",{maxSplats:i,pixelScaleLimit:o,lastPixelLimit:this.lastPixelLimit,instances:u});this.lastTraverseTime=performance.now()-h;const{keyIndices:p,chunks:m,pixelLimit:f}=d;this.lastPixelLimit=f;const g=Object.values(p).reduce(((e,{numSplats:t})=>e+t),0);if(this.updateLodIndices(l,p),this.pager){this.pager.processUploads();const e=n.map((e=>{if(!e.paged||!this.pager)return null;const t=e.getWorldPosition(new r.Vector3);return{splats:e.paged,distance:t.distanceTo(s)}})).filter((e=>null!==e));!this.pageSizeWarning&&e.length>this.pager.maxPages&&(this.pageSizeWarning=!0),e.sort(((e,t)=>e.distance-t.distance)),this.pager.fetchPriority=e.map((({splats:e})=>({splats:e,chunk:0})));for(const[t,n]of m){const e=this.lodIdToSplats.get(t);e instanceof eo&&0!==n&&this.pager.fetchPriority.push({splats:e,chunk:n})}this.pager.autoDrive=this.enableLodFetching,this.enableLodFetching&&this.pager.driveFetchers()}if(this.lodRaycast&&performance.now()-this.lastLodRaycastTime>=this.lodRaycastIntervalMs){this.lastLodRaycastTime=performance.now();performance.now();const t=await e.call("traverseLodTrees",{maxSplats:Math.min(this.lodRaycast,Math.round(.1*g)),pixelScaleLimit:o,instances:u});performance.now();const{keyIndices:n}=t;Object.values(n).reduce(((e,{numSplats:t})=>e+t),0);for(const[e,r]of Object.entries(n)){l.get(e).raycastIndices=r}}}async cleanupLodTrees(e){const t=performance.now();let n=null;for(const[r,i]of this.lodIds.entries())(null==n||i.lastTouched<n.lastTouched)&&(n={splats:r,lastTouched:i.lastTouched,lodId:i.lodId});if(n&&!(n.lastTouched>t-3e3)){this.lodIds.delete(n.splats),this.lodIdToSplats.delete(n.lodId);for(const[e,t]of this.lodInstances.entries())t.lodId===n.lodId&&(t.texture.dispose(),this.lodInstances.delete(e));await e.call("disposeLodTree",{lodId:n.lodId})}}updateLodIndices(e,t){for(const[n,i]of Object.entries(t)){const{lodId:t,numSplats:s,indices:a}=i,o=e.get(n);if(o.paged)o.paged.update(s,a);else{let e=this.lodInstances.get(o);e&&a.length>e.indices.length&&(e.texture.dispose(),e=void 0);const n=Math.ceil(a.length/16384);if(e){e.numSplats=s;const t=this.renderer,r=t.getContext();if(t.properties.has(e.texture)){const i=t.properties.get(e.texture).__webglTexture;if(!i)throw new Error("lodIndices texture not found");t.state.activeTexture(r.TEXTURE0),t.state.bindTexture(r.TEXTURE_2D,i),r.bindBuffer(r.PIXEL_UNPACK_BUFFER,null),r.pixelStorei(r.UNPACK_FLIP_Y_WEBGL,!1),r.texSubImage2D(r.TEXTURE_2D,0,0,0,4096,n,r.RGBA_INTEGER,r.UNSIGNED_INT,a),t.state.bindTexture(r.TEXTURE_2D,null)}}else{const i=16384*n;if(a.length!==i)throw new Error("Indices length != capacity");const l=new r.DataTexture(a,4096,n,r.RGBAIntegerFormat,r.UnsignedIntType);l.internalFormat="RGBA32UI",l.needsUpdate=!0,e={lodId:t,numSplats:s,indices:a,texture:l},this.lodInstances.set(o,e)}}o.updateMappingVersion()}}async readbackDepth({current:e,renderer:t,numSplats:n,readback:r}){if(!t)throw new Error("No renderer");if(!e.target)throw new Error("No target");const i=Math.ceil(n/br)*br;if(r.byteLength<4*i)throw new Error(`Readback buffer too small: ${r.byteLength} < ${4*i}`);const s=new Uint8Array(r.buffer),a=this.saveRenderState(t),o=4194304;let l=0;const c=[];for(;l<n;){const r=Math.floor(l/o),i=r*o,a=Math.min(wr,Math.ceil((n-i)/br)),u=br*a*4,h=s.subarray(4*i,4*i+u);t.setRenderTarget(e.target,r);const d=t.readRenderTargetPixelsAsync(e.target,0,0,br,a,h,void 0,e.extSplats?2:1);if(c.push(d),this.flushAfterRead){t.getContext().flush()}l+=br*a}return this.resetRenderState(t,a),Promise.all(c).then((()=>r))}saveRenderState(e){return{target:e.getRenderTarget(),xrEnabled:e.xr.enabled,autoClear:e.autoClear}}resetRenderState(e,t){e.setRenderTarget(t.target),e.xr.enabled=t.xrEnabled,e.autoClear=t.autoClear}render(t,n){try{e.sparkOverride=this,this.renderer.render(t,n)}finally{e.sparkOverride=void 0}}renderTarget({scene:t,camera:n}){const r=this.backTarget??this.target;if(!r)throw new Error("No target");const i=this.renderer.getRenderTarget();try{this.renderer.setRenderTarget(r),e.sparkOverride=this,this.renderer.render(t,n)}finally{e.sparkOverride=void 0,this.renderer.setRenderTarget(i)}return r!==this.target&&([this.target,this.backTarget]=[this.backTarget,this.target]),r}async readTarget(){if(!this.target)throw new Error("Must initialize with target");const{width:e,height:t}=this.target,n=e*t*4;(!this.superPixels||this.superPixels.length<n)&&(this.superPixels=new Uint8Array(n));const r=this.superPixels;await this.renderer.readRenderTargetPixelsAsync(this.target,0,0,e,t,r);const{superXY:i}=this;if(1===i)return r;const s=e/i,a=t/i,o=s*a*4;(!this.targetPixels||this.targetPixels.length<o)&&(this.targetPixels=new Uint8Array(o));const l=this.targetPixels,c=i*i;for(let u=0;u<a;u++){const t=u*s;for(let n=0;n<s;n++){const s=n*i;let a=0,o=0,h=0,d=0;for(let t=0;t<i;t++){const n=(u*i+t)*e;for(let e=0;e<i;e++){const t=4*(n+s+e);a+=r[t],o+=r[t+1],h+=r[t+2],d+=r[t+3]}}const p=4*(t+n);l[p]=a/c,l[p+1]=o/c,l[p+2]=h/c,l[p+3]=d/c}}return l}async renderReadTarget({scene:e,camera:t}){return this.renderTarget({scene:e,camera:t}),this.readTarget()}async renderCubeMap({scene:t,worldCenter:n,size:i=256,near:s=.1,far:a=1e3,hideObjects:o=[],update:l=!0,filter:c=!1}){if(!e.cubeRender||e.cubeRender.target.width!==i||e.cubeRender.near!==s||e.cubeRender.far!==a){e.cubeRender&&e.cubeRender.target.dispose();const t=new r.WebGLCubeRenderTarget(i,{format:r.RGBAFormat,type:r.UnsignedByteType,generateMipmaps:c,minFilter:c?r.LinearMipMapLinearFilter:r.LinearFilter,magFilter:r.LinearFilter,colorSpace:c?r.LinearSRGBColorSpace:r.SRGBColorSpace}),n=new r.CubeCamera(s,a,t);e.cubeRender={target:t,cubeCamera:n,near:s,far:a}}const{target:u,cubeCamera:h}=e.cubeRender;h.position.copy(n);const d=new Map;for(const e of o)d.set(e,e.visible),e.visible=!1;if(l){const e=new r.Camera;e.position.copy(n),await this.update({scene:t,camera:e})}try{e.sparkOverride=this,h.update(this.renderer,t)}finally{e.sparkOverride=void 0}for(const[e,r]of d.entries())e.visible=r;return u.texture}async readCubeTargets(){if(!e.cubeRender)throw new Error("No cube render");const t=e.cubeRender.target.texture,n=[],r=[];for(let i=0;i<t.images.length;++i){const{width:s,height:a}=t.images[i],o=new Uint8Array(s*a*4);r.push(o);const l=this.renderer.readRenderTargetPixelsAsync(e.cubeRender.target,0,0,s,a,o,i);n.push(l)}return await Promise.all(n),r}async renderEnvMap({scene:t,worldCenter:n,size:i=256,near:s=.1,far:a=1e3,hideObjects:o=[],update:l=!0}){var c;const u=await this.renderCubeMap({scene:t,worldCenter:n,size:i,near:s,far:a,hideObjects:o,update:l,filter:!0});return e.pmrem||(e.pmrem=new r.PMREMGenerator(this.renderer)),null==(c=e.pmrem)?void 0:c.fromCubemap(u).texture}recurseSetEnvMap(e,t){e.traverse((e=>{if(e instanceof r.Mesh)if(Array.isArray(e.material))for(const n of e.material)n instanceof r.MeshStandardMaterial&&(n.envMap=t);else e.material instanceof r.MeshStandardMaterial&&(e.material.envMap=t)}))}async getLodTreeLevel(e,t,n=!1){var r,i;const s=this.lodInstances.get(e);if(!s)return null;const a=await this.ensureLodWorker().exclusive((async e=>await e.call("getLodTreeLevel",{lodId:s.lodId,level:t})));if(null==(r=e.packedSplats)?void 0:r.lodSplats){const t=e.packedSplats.lodSplats.extractSplats(a.indices,n);return new lo({packedSplats:t})}if(null==(i=e.extSplats)?void 0:i.lodSplats){const t=e.extSplats.lodSplats.extractSplats(a.indices,n);return new lo({extSplats:t})}throw new Error("Only LoD-enabled PackedSplats and ExtSplats are supported")}get premultipliedAlpha(){return this.material.premultipliedAlpha}set premultipliedAlpha(e){this.material.premultipliedAlpha!==e&&(this.material.premultipliedAlpha=e,this.material.needsUpdate=!0)}};Za.emptyOrdering=(()=>{const e=new Uint32Array(16384),t=new r.DataTexture(e,4096,1);return t.format=r.RGBAIntegerFormat,t.type=r.UnsignedIntType,t.internalFormat="RGBA32UI",t.needsUpdate=!0,t})(),Za.cubeRender=null,Za.pmrem=null;let Ja=Za;class eo{constructor(e){var t;if(this.pager=e.pager,this.rootUrl=e.rootUrl??"",this.requestHeader=e.requestHeader,this.withCredentials=e.withCredentials,this.numSh=0,this.maxSh=(null==(t=e.pager)?void 0:t.maxSh)??3,this.numSplats=0,this.dynoNumSplats=new Ts({value:0}),this.dynoIndices=new Es({value:no.emptyIndicesTexture}),this.rgbMinMaxLnScaleMinMax=new Ms({value:new r.Vector4(0,1,yr,9)}),this.lodOpacity=new ws({value:!1}),this.dynoNumSh=new Ts({value:0}),this.shMax=new _s({value:new r.Vector3}),this.fileBytes=e.fileBytes,this.fileType=e.fileType,!this.fileType&&this.fileBytes&&(this.fileType=function(e){const t=new DataView(e.buffer).getUint32(0,!0);if(7957616==(16777215&t))return Tr.PLY;if(559903==(16777215&t)){const t=function(e,t){const n=[];let r=0,i=null;const s=new dr(((e,s)=>{if(n.push(e),r+=e.length,s||r>=t){const e=new Uint8Array(r);let s=0;for(const t of n)e.set(t,s),s+=t.length;i=e.slice(0,t)}}));let a=0;for(;null==i&&a<e.length;){const t=e.slice(a,a+1024);s.push(t,!1),a+=1024}if(null==i&&(s.push(new Uint8Array,!0),null==i))throw new Error("Failed to decompress partial gzip");return i}(e,4);return 1347635022===new DataView(t.buffer).getUint32(0,!0)?Tr.SPZ:void 0}if(67324752===t)return function(e){try{const t=e instanceof ArrayBuffer?new Uint8Array(e):e;let n=null;const r=function(e,t){for(var n={},r=e.length-22;101010256!=lr(e,r);--r)(!r||e.length-r>65558)&&ir(13);var i=or(e,r+8);if(!i)return{};var s=lr(e,r+16),a=4294967295==s||65535==i;if(a){var o=lr(e,r-12);(a=101075792==lr(e,o))&&(i=lr(e,o+32),s=lr(e,o+48))}for(var l=t&&t.filter,c=0;c<i;++c){var u=gr(e,s,a),h=u[0],d=u[1],p=u[2],m=u[3],f=u[4],g=u[5],x=fr(e,g);s=f,l&&!l({name:m,size:d,originalSize:p,compression:h})||(h?8==h?n[m]=hr(e.subarray(x,x+d),{out:new Pn(p)}):ir(14,"unknown compression type "+h):n[m]=nr(e,x,x+d))}return n}(t,{filter:({name:e})=>"meta.json"===e.split(/[\\/]/).pop()&&(n=e,!0)});if(!n)return;const i=function(e){try{let t;if("string"==typeof e)t=e;else{const n=e instanceof ArrayBuffer?new Uint8Array(e):e;if(n.length>65536)return;t=(new TextDecoder).decode(n)}const n=JSON.parse(t);if(!n||"object"!=typeof n||Array.isArray(n))return;const r=2===n.version;for(const e of["means","scales","quats","sh0"]){if(!n[e]||"object"!=typeof n[e]||Array.isArray(n[e]))return;if(r){if(!n[e].files)return;if(("scales"===e||"sh0"===e)&&!n[e].codebook)return;if(!("means"!==e||n[e].mins&&n[e].maxs))return}else{if(!n[e].shape||!n[e].files)return;if(!("quats"===e||n[e].mins&&n[e].maxs))return}}return n}catch{return}}(r[n]);if(!i)return;return{name:n,json:i}}catch{return}}(e)?Tr.PCSOGSZIP:void 0;if(809779538===t)return Tr.RAD;return}(this.fileBytes)),!this.fileType&&this.rootUrl&&(this.fileType=function(e){const t=function(e){const t=e.split(/[?#]/,1)[0],n=Math.max(t.lastIndexOf("/"),t.lastIndexOf("\\")),r=t.slice(n+1),i=r.lastIndexOf(".");if(i<=0||i===r.length-1)return"";return r.slice(i+1).toLowerCase()}(e);if("ply"===t)return Tr.PLY;if("spz"===t)return Tr.SPZ;if("splat"===t)return Tr.SPLAT;if("ksplat"===t)return Tr.KSPLAT;if("sog"===t)return Tr.PCSOGSZIP;if("rad"===t)return Tr.RAD;return}(this.rootUrl)),!this.fileType)throw new Error("Unable to determine file type");this.fileType===Tr.RAD&&(this.radMetaPromise=this.getRadMeta())}dispose(){this.dynoIndices.value!==no.emptyIndicesTexture&&(this.dynoIndices.value.dispose(),this.dynoIndices.value=no.emptyIndicesTexture)}setMaxSh(e){this.maxSh=e}getRadMeta(){return this.radMetaPromise||(this.radMetaPromise=(async()=>{if(await io,this.fileBytes){const e=ia(this.fileBytes.slice(0,1048576));if(e)return e;throw new Error("Failed to decode RAD header")}if(!this.rootUrl)throw new Error("No url or fileBytes provided");for(const e of[65536,262144,1048576]){const t=ia(await so({url:this.rootUrl,requestHeader:this.requestHeader,withCredentials:this.withCredentials,offset:0,bytes:e}));if(t)return t}throw new Error("Failed to decode RAD header")})().then((e=>e)),this.radMetaPromise.catch((e=>{}))),this.radMetaPromise}chunkUrl(e){return this.rootUrl.replace(/-lod-0\./,`-lod-${e}.`)}async fetchDecodeChunk(e){let t;if(this.fileType===Tr.RAD){const{meta:n,chunksStart:r}=await this.getRadMeta();if(e<0||e>=n.chunks.length)throw new Error(`Chunk index out of range: ${e} (max: ${n.chunks.length-1})`);let{offset:i,bytes:s,filename:a}=n.chunks[e];if(a){if(this.fileBytes)throw new Error("Chunked RAD file not supported with fileBytes");const e=new URL(this.rootUrl,window.location.href).toString(),n=new URL(a,e).toString();t=await so({url:n,requestHeader:this.requestHeader,withCredentials:this.withCredentials})}else if(i+=r,this.fileBytes){if(i<0||i+s>this.fileBytes.length)throw new Error(`Invalid chunk offset or bytes: ${i} + ${s} > ${this.fileBytes.length}`);t=this.fileBytes.slice(i,i+s)}else{if(!this.rootUrl)throw new Error("No url or fileBytes provided");t=await so({url:this.rootUrl,requestHeader:this.requestHeader,withCredentials:this.withCredentials,offset:i,bytes:s})}}else if(this.fileBytes);else{if(!this.rootUrl)throw new Error("No url or fileBytes provided");{const n=this.chunkUrl(e),r=new Request(n,{headers:this.requestHeader?new Headers(this.requestHeader):void 0,credentials:this.withCredentials?"include":"same-origin"}),i=await fetch(r);if(!i.ok||!i.body)throw new Error(`Failed to fetch "${n}": ${i.status} ${i.statusText}`);t=new Uint8Array(await i.arrayBuffer())}}return await Li.withWorker((async n=>{var r,i,s,a,o;if(!this.pager)throw new Error("PagedSplats.pager not set");if(!this.pager.extSplats){const a=(await n.call("loadPackedSplats",{fileBytes:t,pathName:this.chunkUrl(e),sh1Codes:null==(r=this.sh1Codes)?void 0:r.slice(),sh2Codes:null==(i=this.sh2Codes)?void 0:i.slice(),sh3Codes:null==(s=this.sh3Codes)?void 0:s.slice()})).lodSplats;return this.splatEncoding||(this.splatEncoding=a.splatEncoding,this.numSh=a.extra.sh3?3:a.extra.sh2?2:a.extra.sh1?1:0,this.rgbMinMaxLnScaleMinMax.value.set(this.splatEncoding.rgbMin??0,this.splatEncoding.rgbMax??1,this.splatEncoding.lnScaleMin??yr,this.splatEncoding.lnScaleMax??9),this.lodOpacity.value=this.splatEncoding.lodOpacity??!1,this.shMax.value.set(this.splatEncoding.sh1Max??1,this.splatEncoding.sh2Max??1,this.splatEncoding.sh3Max??1)),this.sh1Codes=a.extra.sh1Codes??this.sh1Codes,this.sh2Codes=a.extra.sh2Codes??this.sh2Codes,this.sh3Codes=a.extra.sh3Codes??this.sh3Codes,a}const l=this.sh3Codes,c=(await n.call("loadExtSplats",{fileBytes:t,pathName:this.chunkUrl(e),sh1Codes:null==(a=this.sh1Codes)?void 0:a.slice(),sh2Codes:null==(o=this.sh2Codes)?void 0:o.slice(),sh3Codes:l?[l[0].slice(),l[1].slice()]:void 0})).lodSplats;return this.splatEncoding||(this.splatEncoding=Sr,this.numSh=c.extra.sh3a&&c.extra.sh3b?3:c.extra.sh2?2:c.extra.sh1?1:0),this.sh1Codes=c.extra.sh1Codes??this.sh1Codes,this.sh2Codes=c.extra.sh2Codes??this.sh2Codes,this.sh3Codes=c.extra.sh3Codes??this.sh3Codes,c}))}update(e,t){if(!this.pager)throw new Error("PagedSplats.pager not set");const n=this.pager.renderer;this.numSplats=e,this.dynoNumSplats.value=this.numSplats;const i=Math.ceil(e/16384);let s=this.dynoIndices.value===no.emptyIndicesTexture?void 0:this.dynoIndices.value;if(s&&i>s.image.height&&(s.dispose(),s=void 0),s){s.image.data.set(t.subarray(0,e));const r=n.getContext();n.state.activeTexture(r.TEXTURE0),n.state.bindTexture(r.TEXTURE_2D,ro(n,s)),r.bindBuffer(r.PIXEL_UNPACK_BUFFER,null),r.pixelStorei(r.UNPACK_FLIP_Y_WEBGL,!1),r.texSubImage2D(r.TEXTURE_2D,0,0,0,4096,i,r.RGBA_INTEGER,r.UNSIGNED_INT,t),n.state.bindTexture(r.TEXTURE_2D,null)}else s=new r.DataTexture(t,4096,i,r.RGBAIntegerFormat,r.UnsignedIntType),s.internalFormat="RGBA32UI",s.needsUpdate=!0,n.initTexture(s),this.dynoIndices.value=s}prepareFetchSplat(){}getNumSplats(){return this.numSplats}hasRgbDir(){return!!this.pager&&Math.min(this.numSh,this.pager.maxSh)>0}getNumSh(){return this.numSh}fetchSplat({index:e,viewOrigin:t}){if(!this.pager)throw new Error("PagedSplats.pager not set");const n=this.pager.readIndex.apply({index:e,numSplats:this.dynoNumSplats,indices:this.dynoIndices}).index;return this.pager.extSplats?this.hasRgbDir()&&t?(this.dynoNumSh.value=Math.min(this.numSh,this.maxSh,this.pager.maxSh),this.pager.readSplatExtDir.apply({index:n,viewOrigin:t,numSh:this.dynoNumSh}).gsplat):this.pager.readSplatExt.apply({index:n}).gsplat:this.hasRgbDir()&&t?(this.dynoNumSh.value=Math.min(this.numSh,this.maxSh,this.pager.maxSh),this.pager.readSplatDir.apply({index:n,rgbMinMaxLnScaleMinMax:this.rgbMinMaxLnScaleMinMax,lodOpacity:this.lodOpacity,viewOrigin:t,numSh:this.dynoNumSh,shMax:this.shMax}).gsplat):this.pager.readSplat.apply({index:n,rgbMinMaxLnScaleMinMax:this.rgbMinMaxLnScaleMinMax,lodOpacity:this.lodOpacity}).gsplat}forEachSplat(e){if(!this.pager||!this.numSplats)return;const t=this.pager.extSplats,n=this.dynoIndices.value.image.data,r=this.pager.packedTexture.value.image.data,i=[r,this.pager.extTexture.value.image.data];for(let s=0;s<this.numSplats;++s){const a=n[s],o=t?hi(i,a):fi(r,a,this.splatEncoding);e(s,o.center,o.scales,o.quaternion,o.opacity,o.color)}}}const to=class e{constructor(t){this.fetchPause=0,this.splatsChunkToPage=new Map,this.pageToSplatsChunk=[],this.renderer=t.renderer,this.extSplats=t.extSplats??!1,this.pageSplats=65536,this.maxSplats=t.maxSplats??16777216,this.maxPages=Math.ceil(this.maxSplats/this.pageSplats),this.maxSplats=this.maxPages*this.pageSplats,this.maxSh=t.maxSh??3,this.curSh=0,this.autoDrive=t.autoDrive??!0,this.numFetchers=t.numFetchers??3,this.splatsChunkToPage=new Map,this.pageToSplatsChunk=new Array(this.maxPages),this.pageFreelist=Array.from({length:this.maxPages},((e,t)=>t)),this.pageLru=new Set,this.freeablePages=[],this.newUploads=[],this.readyUploads=[],this.lodTreeUpdates=[],this.fetchers=[],this.fetched=[],this.fetchPriority=[],this.packedTexture=new Cs({value:this.newUint32ArrayTexture(new Uint32Array(256*this.maxPages*256*4),256,256,this.maxPages,r.RGBAIntegerFormat,r.UnsignedIntType,"RGBA32UI")}),this.extTexture=new Cs({value:this.extSplats?this.newUint32ArrayTexture(new Uint32Array(256*this.maxPages*256*4),256,256,this.maxPages,r.RGBAIntegerFormat,r.UnsignedIntType,"RGBA32UI"):e.emptyExtTexture}),this.sh1Texture=new Cs({value:this.extSplats?e.emptyExtSh1Texture:e.emptySh1Texture}),this.sh2Texture=new Cs({value:this.extSplats?e.emptyExtSh2Texture:e.emptySh2Texture}),this.sh3Texture=new Cs({value:this.extSplats?e.emptyExtSh3Texture:e.emptySh3Texture}),this.sh3TextureB=new Cs({value:e.emptyExtSh3BTexture}),this.readIndex=qr({index:"int",numSplats:"int",indices:"usampler2D"},{index:"int"},(({index:e,numSplats:t,indices:n})=>new $r({inTypes:{index:"int",numSplats:"int",indices:"usampler2D"},outTypes:{index:"int"},inputs:{index:e,numSplats:t,indices:n},statements:({inputs:e,outputs:t})=>Wr(`\n if (${e.index} >= ${e.numSplats}) {\n return;\n }\n\n ivec2 indexCoord = ivec2((${e.index} >> 2) & 4095, ${e.index} >> 14);\n uint index = texelFetch(${e.indices}, indexCoord, 0)[${e.index} & 3];\n ${t.index} = int(index);\n `)}).outputs)),this.readSplat=qr({index:"int",rgbMinMaxLnScaleMinMax:"vec4",lodOpacity:"bool"},{gsplat:Ui},(({index:e,rgbMinMaxLnScaleMinMax:t,lodOpacity:n})=>new $r({inTypes:{index:"int",packedTexture:"usampler2DArray",rgbMinMaxLnScaleMinMax:"vec4",lodOpacity:"bool"},outTypes:{gsplat:Ui},inputs:{index:e,packedTexture:this.packedTexture,rgbMinMaxLnScaleMinMax:t,lodOpacity:n},globals:()=>[ji],statements:({inputs:e,outputs:t})=>Wr(`\n int index = ${e.index};\n ivec3 splatCoord = pagedSplatTexCoord(index);\n uvec4 packedData = texelFetch(${e.packedTexture}, splatCoord, 0);\n\n unpackSplatEncoding(packedData, ${t.gsplat}.center, ${t.gsplat}.scales, ${t.gsplat}.quaternion, ${t.gsplat}.rgba, ${e.rgbMinMaxLnScaleMinMax});\n if ((${t.gsplat}.rgba.a == 0.0) || all(equal(${t.gsplat}.scales, vec3(0.0, 0.0, 0.0)))) {\n return;\n }\n \n ${t.gsplat}.index = index;\n ${t.gsplat}.flags = GSPLAT_FLAG_ACTIVE;\n if (${e.lodOpacity}) {\n ${t.gsplat}.rgba.a *= 2.0;\n }\n `)}).outputs)),this.readSplatDir=qr({index:"int",rgbMinMaxLnScaleMinMax:"vec4",lodOpacity:"bool",viewOrigin:"vec3",numSh:"int",shMax:"vec3"},{gsplat:Ui},(({index:e,rgbMinMaxLnScaleMinMax:t,lodOpacity:n,viewOrigin:r,numSh:i,shMax:s})=>{if(!(e&&t&&n&&r&&i&&s))throw new Error("index and viewOrigin are required");let a=this.readSplat.apply({index:e,rgbMinMaxLnScaleMinMax:t,lodOpacity:n}).gsplat;const o=Ni(a).outputs.center,l=Hs(Fs(o,r));let c=bo({coord:Hi(e),viewDir:l,numSh:i,sh1Texture:this.sh1Texture,sh2Texture:this.sh2Texture,sh3Texture:this.sh3Texture,shMax:s}).rgb;return c=Us(c,Ni(a).outputs.rgb),a=$i({gsplat:a,rgb:c}),{gsplat:a}})),this.readSplatExt=qr({index:"int"},{gsplat:Ui},(({index:e})=>new $r({inTypes:{index:"int",extTexture1:"usampler2DArray",extTexture2:"usampler2DArray"},outTypes:{gsplat:Ui},inputs:{index:e,extTexture1:this.packedTexture,extTexture2:this.extTexture},globals:()=>[ji],statements:({inputs:e,outputs:t})=>Wr(`\n int index = ${e.index};\n ivec3 splatCoord = ivec3(index & 255, (index >> 8) & 255, index >> 16);\n uvec4 ext1 = texelFetch(${e.extTexture1}, splatCoord, 0);\n float alpha = unpackSplatExtAlpha(ext1);\n if (alpha == 0.0) {\n return;\n }\n\n uvec4 ext2 = texelFetch(${e.extTexture2}, splatCoord, 0);\n unpackSplatExt(ext1, ext2, ${t.gsplat}.center, ${t.gsplat}.scales, ${t.gsplat}.quaternion, ${t.gsplat}.rgba);\n if (all(equal(${t.gsplat}.scales, vec3(0.0, 0.0, 0.0)))) {\n return;\n }\n\n ${t.gsplat}.index = index;\n ${t.gsplat}.flags = GSPLAT_FLAG_ACTIVE;\n `)}).outputs)),this.readSplatExtDir=qr({index:"int",viewOrigin:"vec3",numSh:"int"},{gsplat:Ui},(({index:e,viewOrigin:t,numSh:n})=>{if(!e||!t||!n)throw new Error("index and viewOrigin are required");let r=this.readSplatExt.apply({index:e}).gsplat;const i=Ni(r).outputs.center,s=Hs(Fs(i,t));let a=na({coord:Hi(e),viewDir:s,numSh:n,sh1Texture:this.sh1Texture,sh2Texture:this.sh2Texture,sh3TextureA:this.sh3Texture,sh3TextureB:this.sh3TextureB}).rgb;return a=Us(a,Ni(r).outputs.rgb),r=$i({gsplat:r,rgb:a}),{gsplat:r}}))}dispose(){this.autoDrive=!1,this.numFetchers=0,this.packedTexture.value.dispose(),this.packedTexture.value.source.data=null,this.extTexture.value!==e.emptyExtTexture&&(this.extTexture.value.dispose(),this.extTexture.value.source.data=null),this.extSplats?(this.sh1Texture.value!==e.emptyExtSh1Texture&&(this.sh1Texture.value.dispose(),this.sh1Texture.value.source.data=null),this.sh2Texture.value!==e.emptyExtSh2Texture&&(this.sh2Texture.value.dispose(),this.sh2Texture.value.source.data=null),this.sh3Texture.value!==e.emptyExtSh3Texture&&(this.sh3Texture.value.dispose(),this.sh3Texture.value.source.data=null),this.sh3TextureB.value!==e.emptyExtSh3BTexture&&(this.sh3TextureB.value.dispose(),this.sh3TextureB.value.source.data=null)):(this.sh1Texture.value!==e.emptySh1Texture&&(this.sh1Texture.value.dispose(),this.sh1Texture.value.source.data=null),this.sh2Texture.value!==e.emptySh2Texture&&(this.sh2Texture.value.dispose(),this.sh2Texture.value.source.data=null),this.sh3Texture.value!==e.emptySh3Texture&&(this.sh3Texture.value.dispose(),this.sh3Texture.value.source.data=null))}ensureShTextures(t){this.curSh=Math.max(this.curSh,t),this.extSplats?this.curSh>=1&&this.sh1Texture.value===e.emptyExtSh1Texture&&(this.sh1Texture.value=this.newUint32ArrayTexture(new Uint32Array(256*this.maxPages*256*4),256,256,this.maxPages,r.RGBAIntegerFormat,r.UnsignedIntType,"RGBA32UI")):this.curSh>=1&&this.sh1Texture.value===e.emptySh1Texture&&(this.sh1Texture.value=this.newUint32ArrayTexture(new Uint32Array(256*this.maxPages*256*2),256,256,this.maxPages,r.RGIntegerFormat,r.UnsignedIntType,"RG32UI")),this.curSh>=2&&this.sh2Texture.value===(this.extSplats?e.emptyExtSh2Texture:e.emptySh2Texture)&&(this.sh2Texture.value=this.newUint32ArrayTexture(new Uint32Array(256*this.maxPages*256*4),256,256,this.maxPages,r.RGBAIntegerFormat,r.UnsignedIntType,"RGBA32UI")),this.extSplats?this.curSh>=3&&(this.sh3Texture.value===e.emptyExtSh3Texture&&(this.sh3Texture.value=this.newUint32ArrayTexture(new Uint32Array(256*this.maxPages*256*4),256,256,this.maxPages,r.RGBAIntegerFormat,r.UnsignedIntType,"RGBA32UI")),this.sh3TextureB.value===e.emptyExtSh3BTexture&&(this.sh3TextureB.value=this.newUint32ArrayTexture(new Uint32Array(256*this.maxPages*256*4),256,256,this.maxPages,r.RGBAIntegerFormat,r.UnsignedIntType,"RGBA32UI"))):this.curSh>=3&&this.sh3Texture.value===e.emptySh3Texture&&(this.sh3Texture.value=this.newUint32ArrayTexture(new Uint32Array(256*this.maxPages*256*4),256,256,this.maxPages,r.RGBAIntegerFormat,r.UnsignedIntType,"RGBA32UI"))}allocatePage(){return this.pageFreelist.shift()}freePage(e){this.pageFreelist.push(e)}getSplatsChunk(e,t){const n=this.splatsChunkToPage.get(e);if(n)return n[t]}insertSplatsChunkPage(e,t,n,r){this.splatsChunkToPage.has(e)||this.splatsChunkToPage.set(e,[]);const i=this.splatsChunkToPage.get(e);if(!i)throw new Error("impossible");t>=i.length&&(i.length=t+1);const s={page:n,lru:r};return i[t]=s,this.pageLru.add(s),this.pageToSplatsChunk[n]={splats:e,chunk:t,time:performance.now()},this.pageToSplatsChunk[n]}removeSplatsChunkPage(e,t,n){const r=this.splatsChunkToPage.get(e);if(!r)throw new Error("impossible");const i=r[t];if(!i)throw new Error(`pageLru not found for splats: ${e}, chunk: ${t}, page: ${n}`);for(this.pageLru.delete(i),r[t]=void 0;r.length>0&&void 0===r[r.length-1];)r.pop();for(0===r.length&&this.splatsChunkToPage.delete(e),this.pageToSplatsChunk[n]=void 0;this.pageToSplatsChunk.length>0&&void 0===this.pageToSplatsChunk[this.pageToSplatsChunk.length-1];)this.pageToSplatsChunk.pop()}uploadPage(t,n,r,i){const s=t*this.pageSplats;if(this.packedTexture.value.image.data.subarray(4*s,4*s+n.length).set(n),this.packedTexture.value.addLayerUpdate(t),this.packedTexture.value.needsUpdate=!0,i){this.extTexture.value.image.data.subarray(4*s,4*s+i.length).set(i),this.extTexture.value.addLayerUpdate(t),this.extTexture.value.needsUpdate=!0}const a=this.extSplats?r.sh3a&&r.sh3b?3:r.sh2?2:r.sh1?1:0:r.sh3?3:r.sh2?2:r.sh1?1:0;if(this.ensureShTextures(a),this.extSplats){if(this.sh1Texture.value!==e.emptyExtSh1Texture&&r.sh1){const e=r.sh1;this.sh1Texture.value.image.data.subarray(4*s,4*s+e.length).set(e),this.sh1Texture.value.addLayerUpdate(t),this.sh1Texture.value.needsUpdate=!0}}else if(this.sh1Texture.value!==e.emptySh1Texture&&r.sh1){const e=r.sh1;this.sh1Texture.value.image.data.subarray(2*s,2*s+e.length).set(e),this.sh1Texture.value.addLayerUpdate(t),this.sh1Texture.value.needsUpdate=!0}if(this.sh2Texture.value!==e.emptySh2Texture&&r.sh2){const e=r.sh2;this.sh2Texture.value.image.data.subarray(4*s,4*s+e.length).set(e),this.sh2Texture.value.addLayerUpdate(t),this.sh2Texture.value.needsUpdate=!0}if(this.extSplats){if(this.sh3Texture.value!==e.emptyExtSh3Texture&&r.sh3a){const e=r.sh3a;this.sh3Texture.value.image.data.subarray(4*s,4*s+e.length).set(e),this.sh3Texture.value.addLayerUpdate(t),this.sh3Texture.value.needsUpdate=!0}if(this.sh3TextureB.value!==e.emptyExtSh3BTexture&&r.sh3b){const e=r.sh3b;this.sh3TextureB.value.image.data.subarray(4*s,4*s+e.length).set(e),this.sh3TextureB.value.addLayerUpdate(t),this.sh3TextureB.value.needsUpdate=!0}}else if(this.sh3Texture.value!==e.emptySh3Texture&&r.sh3){const e=r.sh3;this.sh3Texture.value.image.data.subarray(4*s,4*s+e.length).set(e),this.sh3Texture.value.addLayerUpdate(t),this.sh3Texture.value.needsUpdate=!0}}getGlTexture(e){return ro(this.renderer,e)}newUint32ArrayTexture(e,t,n,i,s,a,o){const l=new r.DataArrayTexture(e,t,n,i);return l.format=s,l.type=a,l.internalFormat=o,l.needsUpdate=!0,this.renderer.initTexture(l),l}driveFetchers(){const e=[],t=[];let n=0;for(const{splats:s,chunk:a}of this.fetchPriority){const r=this.getSplatsChunk(s,a);if(r)n>=this.maxPages?t.push(r):e.push(r),n+=1;else if(this.fetched.some((({splats:e,chunk:t})=>s===e&&a===t))||this.fetchers.some((({splats:e,chunk:t})=>s===e&&a===t)))n+=1;else if(n<this.maxPages&&this.fetchers.length<this.numFetchers){n+=1;const e=s.fetchDecodeChunk(a).then((async e=>{this.fetched.push({splats:s,chunk:a,data:e}),this.fetchPause>0&&await new Promise((e=>setTimeout(e,this.fetchPause)))}),(async e=>{const t=250+500*Math.random();await new Promise((e=>setTimeout(e,t)))})).finally((()=>{this.fetchers=this.fetchers.filter((({splats:e,chunk:t})=>s!==e||a!==t)),this.processFetched()}));this.fetchers.push({splats:s,chunk:a,promise:e}),e.then((e=>{this.autoDrive&&this.driveFetchers()}))}}const r=performance.now();for(const s of t.reverse())s.lru=r,this.pageLru.delete(s),this.pageLru.add(s);const i=new Set(this.pageLru);for(const s of e.reverse())i.delete(s),s.lru=r,this.pageLru.delete(s),this.pageLru.add(s);this.freeablePages=Array.from(i).map((({page:e})=>e))}allocateFreeable(){const e=this.freeablePages.shift();if(void 0===e)return;const t=this.pageToSplatsChunk[e];if(!t)throw new Error(`splatsChunk not found for page: ${e}`);const{splats:n,chunk:r}=t;return this.removeSplatsChunkPage(n,r,e),this.lodTreeUpdates.push({splats:n,page:e,chunk:r,numSplats:this.pageSplats}),e}processFetched(){const e=performance.now();for(;;){const t=this.fetched.shift();if(!t)break;const{splats:n,chunk:r,data:i}=t;let s=this.allocatePage();if(void 0===s&&(s=this.allocateFreeable(),void 0===s))return;this.insertSplatsChunkPage(n,r,s,e);const{numSplats:a,extra:o}=i;if(this.lodTreeUpdates.push({splats:n,page:s,chunk:r,numSplats:a,lodTree:o.lodTree}),this.extSplats){const e=i.extArrays,t=e[0],n=e[1];this.newUploads.push({page:s,numSplats:a,packedArray:t,extArray:n,extra:o})}else{const e=i.packedArray;this.newUploads.push({page:s,numSplats:a,packedArray:e,extra:o})}}}processUploads(){for(;;){const e=this.readyUploads.shift();if(!e)break;const{page:t,numSplats:n,packedArray:r,extArray:i,extra:s}=e;this.uploadPage(t,r,s,i)}}consumeLodTreeUpdates(){const e=this.lodTreeUpdates;return this.lodTreeUpdates=[],this.readyUploads.push(...this.newUploads),this.newUploads=[],e}};to.emptyUint32x4=(()=>{const{width:e,height:t,depth:n,maxSplats:i}=gi(1),s=new Uint32Array(4*i),a=new r.DataArrayTexture(s,e,t,n);return a.format=r.RGBAIntegerFormat,a.type=r.UnsignedIntType,a.internalFormat="RGBA32UI",a.needsUpdate=!0,a})(),to.emptyUint32x2=(()=>{const{width:e,height:t,depth:n,maxSplats:i}=gi(1),s=new Uint32Array(2*i),a=new r.DataArrayTexture(s,e,t,n);return a.format=r.RGIntegerFormat,a.type=r.UnsignedIntType,a.internalFormat="RG32UI",a.needsUpdate=!0,a})(),to.emptyIndicesTexture=(()=>{const e=new Uint32Array(16384),t=new r.DataTexture(e,4096,1);return t.format=r.RGBAIntegerFormat,t.type=r.UnsignedIntType,t.internalFormat="RGBA32UI",t.needsUpdate=!0,t})(),to.emptyPackedTexture=to.emptyUint32x4,to.emptyExtTexture=to.emptyUint32x4,to.emptySh1Texture=to.emptyUint32x2,to.emptySh2Texture=to.emptyUint32x4,to.emptySh3Texture=to.emptyUint32x4,to.emptyExtSh1Texture=to.emptyUint32x4,to.emptyExtSh2Texture=to.emptyUint32x4,to.emptyExtSh3Texture=to.emptyUint32x4,to.emptyExtSh3BTexture=to.emptyUint32x4;let no=to;function ro(e,t){if(!e.properties.has(t))throw new Error("texture not found");const n=e.properties.get(t).__webglTexture;if(!n)throw new Error("texture not found");return n}const io=_a();async function so({url:e,requestHeader:t,withCredentials:n,offset:r,bytes:i}){const s=new Request(e,{headers:t?new Headers(t):void 0,credentials:n?"include":"same-origin"});void 0!==r&&void 0!==i&&s.headers.set("Range",`bytes=${r}-${r+i-1}`);const a=await fetch(s);if(!a.ok||!a.body)throw new Error(`Failed to fetch "${e}": ${a.status} ${a.statusText}`);return new Uint8Array(await a.arrayBuffer())}class ao{constructor(){this.fetchDyno=new $r({inTypes:{},outTypes:{gsplat:Ui},globals:()=>[ji],statements:({outputs:e})=>Wr(`\n ${e.gsplat}.flags = 0u;\n return;\n `)}).outputs.gsplat}prepareFetchSplat(){}dispose(){}getNumSplats(){return 0}hasRgbDir(){return!1}getNumSh(){return 0}setMaxSh(e){}fetchSplat({index:e}){return this.fetchDyno}forEachSplat(){}}const oo=class e extends ja{constructor(e={}){if(super({update:e=>this.update(e)}),this.isInitialized=!1,this.recolor=new r.Color(1,1,1),this.opacity=1,this.generatorDirty=!0,this.enableViewToObject=!1,this.enableViewToWorld=!1,this.enableWorldToView=!1,this.skinning=null,this.edits=null,this.rgbaDisplaceEdits=null,this.splatRgba=null,this.maxSh=3,this.showLodPageDyno=new Ts({value:0}),e.splats)this.splats=e.splats,this.numSplats=e.splats.getNumSplats();else if(e.paged){e.extSplats;const t=e.url??"";if(!0===e.paged)this.paged=new eo({rootUrl:t});else if(e.paged instanceof eo)this.paged=e.paged;else{if(!(e.paged instanceof no))throw new Error("Invalid paged option");this.paged=new eo({rootUrl:t,pager:e.paged})}this.splats=this.paged}else e.extSplats?(this.extSplats=e.extSplats instanceof Qs?e.extSplats:new Qs,e.extSplats=this.extSplats,this.numSplats=this.extSplats.numSplats,this.splats=this.extSplats):e.packedSplats?(this.packedSplats=e.packedSplats,this.packedSplats.splatEncoding=e.splatEncoding??{...Sr},this.splats=this.packedSplats):this.packedSplats=new fo;if(this.editable=e.editable??!0,this.raycastable=e.raycastable??!0,this.minRaycastOpacity=e.minRaycastOpacity??.2,this.onFrame=e.onFrame,this.context={transform:new qa,viewToWorld:new qa,worldToView:new qa,viewToObject:new qa,covTransform:new Ha,covViewToWorld:new Ha,covWorldToView:new Ha,covViewToObject:new Ha,recolor:new Ms({value:(new r.Vector4).setScalar(Number.NEGATIVE_INFINITY)}),time:new Ss({value:0}),deltaTime:new Ss({value:0}),numSplats:new Ts({value:0}),splats:new ao,enableLod:new ws({value:!1}),lodIndices:new Es({value:ho,key:"lodIndices"})},this.covSplats=e.covSplats??!1,this.covSplats&&!this.extSplats)throw new Error("CovSplats requires ExtSplats");if(this.objectModifiers=e.objectModifier?[e.objectModifier]:void 0,this.worldModifiers=e.worldModifier?[e.worldModifier]:void 0,e.objectModifiers&&(this.objectModifiers=e.objectModifiers),e.worldModifiers&&(this.worldModifiers=e.worldModifiers),this.enableLod=e.enableLod,this.lodScale=e.lodScale??1,this.behindFoveate=e.behindFoveate,this.coneFov0=e.coneFov0,this.coneFov=e.coneFov,this.coneFoveate=e.coneFoveate,this.updateGenerator(),e.url||e.fileBytes||e.stream||e.constructSplats||e.packedSplats&&!e.packedSplats.isInitialized||this.extSplats&&!this.extSplats.isInitialized)this.initialized=this.asyncInitialize(e).then((async()=>{if(this.updateGenerator(),this.isInitialized=!0,e.onLoad){const t=e.onLoad(this);t instanceof Promise&&await t}return this}));else if(this.isInitialized=!0,this.initialized=Promise.resolve(this),e.onLoad){const t=e.onLoad(this);t instanceof Promise&&(this.initialized=t.then((()=>this)))}}async asyncInitialize(e){const{url:t,fileBytes:n,fileType:r,fileName:i,stream:s,streamLength:a,maxSplats:o,constructSplats:l,onProgress:c,splatEncoding:u,lod:h,nonLod:d,lodAbove:p}=e;if(this.packedSplats){if(t||n||s||l){const e={url:t,fileBytes:n,fileType:r,fileName:i,stream:s,streamLength:a,maxSplats:o,construct:l,onProgress:c,splatEncoding:u,lod:h,nonLod:d,lodAbove:p};this.packedSplats.reinitialize(e)}await this.packedSplats.initialized,this.splats=this.packedSplats}else if(this.extSplats&&(t||n||s||l)){const e=l;this.extSplats.reinitialize({url:t,fileBytes:n,fileType:r,fileName:i,stream:s,streamLength:a,maxSplats:o,construct:e,onProgress:c,lod:h,nonLod:d,lodAbove:p}),await this.extSplats.initialized,this.splats=this.extSplats}this.splats&&(this.numSplats=this.splats.getNumSplats(),this.updateGenerator())}static async staticInitialize(){await _a(),e.isStaticInitialized=!0}pushSplat(e,t,n,r,i){this.packedSplats?this.packedSplats.pushSplat(e,t,n,r,i):this.extSplats&&this.extSplats.pushSplat(e,t,n,r,i)}forEachSplat(e){var t;null==(t=this.splats)||t.forEachSplat(e)}dispose(){this.splats&&this.splats!==this.packedSplats&&this.splats!==this.extSplats&&(this.splats.dispose(),this.splats=void 0),this.packedSplats&&(this.packedSplats.dispose(),this.packedSplats=void 0),this.extSplats&&(this.extSplats.dispose(),this.extSplats=void 0)}getBoundingBox(e=!0){var t;if(!this.initialized)throw new Error("Cannot get bounding box before SplatMesh is initialized");const n=new r.Vector3(Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY),i=new r.Vector3(Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY),s=new r.Vector3,a=[-1,1];null==(t=this.splats)||t.forEachSplat((function(t,r,o,l,c,u){if(e)n.min(r),i.max(r);else for(const e of a)for(const t of a)for(const c of a)s.set(e*o.x,t*o.y,c*o.z),s.applyQuaternion(l),s.add(r),n.min(s),i.max(s)}));return new r.Box3(n,i)}set objectModifier(e){this.objectModifiers=e?[e]:void 0}set worldModifier(e){this.worldModifiers=e?[e]:void 0}constructGenerator(e){if(this.covSplats)return this.constructCovGenerator(e);const{transform:t,viewToObject:n,recolor:r}=e,i=qr({index:"int"},{gsplat:Ui},(({index:i})=>{if(!i)throw new Error("index is undefined");i=co(e.lodIndices,i,e.numSplats,e.enableLod,this.showLodPageDyno),e.splats.setMaxSh(this.maxSh),e.splats.prepareFetchSplat();let s=e.splats.fetchSplat({index:i,viewOrigin:n.translate});if(this.splatRgba&&(s=uo(s,this.splatRgba.dyno,i,e.enableLod)),this.skinning&&(s=this.skinning.modify(s)),this.objectModifiers)for(const e of this.objectModifiers)s=e.apply({gsplat:s}).gsplat;s=t.applyGsplat(s);const a=zs(r,Ni(s).outputs.rgba);if(s=$i({gsplat:s,rgba:a}),this.rgbaDisplaceEdits&&(s=this.rgbaDisplaceEdits.modify(s)),this.worldModifiers)for(const e of this.worldModifiers)s=e.apply({gsplat:s}).gsplat;return{gsplat:s}}));this.generator=i,this.covGenerator=void 0}constructCovGenerator(e){const{covTransform:t,covViewToObject:n,recolor:r}=e,i=qr({index:"int"},{covsplat:Fi},(({index:i})=>{if(!i)throw new Error("index is undefined");i=co(e.lodIndices,i,e.numSplats,e.enableLod,this.showLodPageDyno),e.splats.prepareFetchSplat();let s=e.splats.fetchSplat({index:i,viewOrigin:n.offset});if(this.splatRgba&&(s=uo(s,this.splatRgba.dyno,i,e.enableLod)),this.objectModifiers)for(const e of this.objectModifiers)s=e.apply({gsplat:s}).gsplat;let a=Oi(s);if(this.skinning&&(a=this.skinning.modifyCov(a)),this.covObjectModifiers)for(const e of this.covObjectModifiers)a=e.apply({covsplat:a}).covsplat;a=t.applyCovSplat(a);const o=zs(r,ss(a).outputs.rgba);if(a=as({covsplat:a,rgba:o}),this.rgbaDisplaceEdits&&(a=this.rgbaDisplaceEdits.modifyCov(a)),this.covWorldModifiers)for(const e of this.covWorldModifiers)a=e.apply({covsplat:a}).covsplat;return{covsplat:a}}));this.generator=void 0,this.covGenerator=i}updateGenerator(){this.generatorDirty=!0}update({renderer:t,time:n,deltaTime:i,viewToWorld:s,camera:a,renderSize:o,globalEdits:l,lodIndices:c}){var u,h,d;this.context.time.value=n,this.context.deltaTime.value=i,e.dynoTime.value=n,this.showLodPageDyno.value=this.showLodPage??-1;const p=this.splats??this.packedSplats??this.extSplats;p&&(this.context.splats=p),this.numSplats=this.context.splats.getNumSplats();let m=!1;const f=(null==(u=this.packedSplats)?void 0:u.lodSplats)??(null==(h=this.extSplats)?void 0:h.lodSplats);if(this.context.enableLod.value=null!=f&&null!=c,!1===this.enableLod&&(this.context.enableLod.value=!1),this.context.lodIndices.value=(null==c?void 0:c.texture)??ho,this.context.enableLod.value&&f&&(this.context.splats=f,this.numSplats=(null==c?void 0:c.numSplats)??0),this.context.numSplats.value=this.numSplats,this.context.splats!==this.lastSplats&&(this.lastSplats=this.context.splats,this.generatorDirty=!0),this.covSplats){this.context.covTransform.update(this)&&(m=!0),this.context.covViewToWorld.updateFromMatrix(s)&&this.enableViewToWorld&&(m=!0);const e=s.clone().invert();this.context.covWorldToView.updateFromMatrix(e)&&this.enableWorldToView&&(m=!0);const t=this.matrixWorld.clone().invert().multiply(s);this.context.covViewToObject.updateFromMatrix(t)&&(this.enableViewToObject||this.context.splats.hasRgbDir())&&(m=!0)}else{this.context.transform.update(this)&&(m=!0),this.context.viewToWorld.updateFromMatrix(s)&&this.enableViewToWorld&&(m=!0);const e=s.clone().invert();this.context.worldToView.updateFromMatrix(e)&&this.enableWorldToView&&(m=!0);const t=(new r.Matrix4).compose(this.context.transform.translate.value,this.context.transform.rotate.value,(new r.Vector3).setScalar(this.context.transform.scale.value)).invert().multiply(s);this.context.viewToObject.updateFromMatrix(t)&&(this.enableViewToObject||this.context.splats.hasRgbDir())&&(m=!0)}const g=new r.Vector4(this.recolor.r,this.recolor.g,this.recolor.b,this.opacity);g.equals(this.context.recolor.value)||(this.context.recolor.value.copy(g),m=!0);const x=this.editable?(this.edits??[]).concat(l):[];this.editable&&!this.edits&&this.traverseVisible((e=>{e instanceof za&&x.push(e)})),x.sort(((e,t)=>e.ordering-t.ordering));const y=x.map((e=>{if(null!=e.sdfs)return{edit:e,sdfs:e.sdfs};const t=[];return e.traverseVisible((e=>{e instanceof Ua&&t.push(e)})),{edit:e,sdfs:t}}));if(y.length>0&&!this.rgbaDisplaceEdits){const e=y.length,t=y.reduce(((e,t)=>e+t.sdfs.length),0);this.rgbaDisplaceEdits=new Ba({maxEdits:e,maxSdfs:t}),this.generatorDirty=!0}if(this.rgbaDisplaceEdits){const e=this.rgbaDisplaceEdits.update(y);m||(m=e.updated),e.dynoUpdated&&(this.generatorDirty=!0)}this.generatorDirty&&(this.constructGenerator(this.context),this.generatorDirty=!1,m=!0),m&&this.updateVersion(),null==(d=this.onFrame)||d.call(this,{mesh:this,time:n,deltaTime:i})}raycast(t,n){var i,s,a,o,l,c,u,h,d,p,m,f,g,x,y,v,b,w,T,S,_,M,A;if(!e.isStaticInitialized||!this.raycastable||!this.packedSplats&&!this.extSplats&&!this.paged)return;const E=null!=this.paged,C=E?(null==(s=null==(i=this.paged)?void 0:i.pager)?void 0:s.extSplats)??!1:null!=this.extSplats,{near:R,far:D,ray:k}=t,I=this.matrixWorld.clone().invert(),P=(new r.Matrix3).setFromMatrix4(I),L=k.origin.clone().applyMatrix4(I),U=k.direction.clone().applyMatrix3(P),F=Ta.get_raycast_buffer(),z=F.length/4;let B=0;const V=(null==(a=this.raycastIndices)?void 0:a.numSplats)??(E?null==(o=this.paged)?void 0:o.numSplats:this.context.numSplats.value)??0,O=(null==(l=this.raycastIndices)?void 0:l.indices)??(E?null==(c=this.paged)?void 0:c.dynoIndices.value.image.data:this.context.enableLod.value?this.context.lodIndices.value.image.data:null)??null;if(C){const e=Ta.get_raycast_buffer2(),t=E?null==(y=null==(x=this.paged)?void 0:x.pager)?void 0:y.packedTexture.value.image.data:O?null==(b=null==(v=this.extSplats)?void 0:v.lodSplats)?void 0:b.extArrays[0]:null==(w=this.extSplats)?void 0:w.extArrays[0],n=E?null==(S=null==(T=this.paged)?void 0:T.pager)?void 0:S.extTexture.value.image.data:O?null==(M=null==(_=this.extSplats)?void 0:_.lodSplats)?void 0:M.extArrays[1]:null==(A=this.extSplats)?void 0:A.extArrays[1];if(!t||!n)return;for(let r=0;r<V;r+=z){const i=Math.min(z,V-r);if(O)for(let a=0;a<i;++a){const i=4*a,s=4*O[r+a];F[i]=t[s],F[i+1]=t[s+1],F[i+2]=t[s+2],F[i+3]=t[s+3],e[i]=n[s],e[i+1]=n[s+1],e[i+2]=n[s+2],e[i+3]=n[s+3]}else F.set(t.subarray(4*r,4*(r+i))),e.set(n.subarray(4*r,4*(r+i)));const s=sa(L.x,L.y,L.z,U.x,U.y,U.z,this.minRaycastOpacity,R,D,i);B=this.appendRaycastBuffer(B,s)}}else{const e=E?null==(h=null==(u=this.paged)?void 0:u.pager)?void 0:h.packedTexture.value.image.data:O?null==(p=null==(d=this.packedSplats)?void 0:d.lodSplats)?void 0:p.packedArray:null==(m=this.packedSplats)?void 0:m.packedArray;if(!e)return;const t=E?null==(f=this.paged)?void 0:f.splatEncoding:null==(g=this.packedSplats)?void 0:g.splatEncoding;for(let n=0;n<V;n+=z){const r=Math.min(z,V-n);if(O)for(let t=0;t<r;++t){const r=4*t,i=4*O[n+t];F[r]=e[i],F[r+1]=e[i+1],F[r+2]=e[i+2],F[r+3]=e[i+3]}else F.set(e.subarray(4*n,4*(n+r)));const i=aa(L.x,L.y,L.z,U.x,U.y,U.z,this.minRaycastOpacity,R,D,r,(null==t?void 0:t.lnScaleMin)??yr,(null==t?void 0:t.lnScaleMax)??9,(null==t?void 0:t.lodOpacity)??!1);B=this.appendRaycastBuffer(B,i)}}for(const r of e.raycastBuffer.subarray(0,B)){const e=k.direction.clone().multiplyScalar(r).add(k.origin);n.push({distance:r,point:e,object:this})}}appendRaycastBuffer(t,n){const r=t+n.length;let i=e.raycastBuffer.length;if(r>i){for(;i<r;)i*=2;const n=new Float32Array(i);n.set(e.raycastBuffer.subarray(0,t)),e.raycastBuffer=n}return e.raycastBuffer.set(n,t),t+n.length}async createLodSplats({rgbaArray:e,quality:t}={}){this.packedSplats?await this.packedSplats.createLodSplats({quality:t,rgbaArray:e}):this.extSplats&&await this.extSplats.createLodSplats({quality:t,rgbaArray:e})}};oo.staticInitialized=oo.staticInitialize(),oo.isStaticInitialized=!1,oo.dynoTime=new Ss({value:0}),oo.raycastBuffer=new Float32Array(1024);let lo=oo;function co(e,t,n,r,i){return Hr({inTypes:{lodIndices:"usampler2D",index:"int",numSplats:"int",enableLod:"bool",showLodPage:"int"},outTypes:{index:"int"},inputs:{lodIndices:e,index:t,numSplats:n,enableLod:r,showLodPage:i},statements:({inputs:e,outputs:t})=>Wr(`\n int index = ${e.index};\n if (${e.showLodPage} < 0) {\n if (index >= ${e.numSplats}) {\n return;\n }\n if (${e.enableLod}) {\n ivec2 lodIndexCoord = ivec2((index >> 2) & 4095, index >> 14);\n uint splatIndex = texelFetch(${e.lodIndices}, lodIndexCoord, 0)[index & 3];\n ${t.index} = int(splatIndex);\n } else {\n ${t.index} = index;\n }\n } else {\n int start = ${e.showLodPage} << 16;\n if (index >= 65536) {\n return;\n }\n ${t.index} = start + index;\n }\n `)}).outputs.index}function uo(e,t,n,r){return Hr({inTypes:{gsplat:Ui,rgba:ka,index:"int",enableLod:"bool"},outTypes:{gsplat:Ui},inputs:{gsplat:e,rgba:t,index:n,enableLod:r},statements:({inputs:e,outputs:t})=>Wr(`\n ${t.gsplat} = ${e.gsplat};\n if (!${e.enableLod} && (${e.index} >= 0) && (${e.index} < ${e.rgba}.count)) {\n ${t.gsplat}.rgba = texelFetch(${e.rgba}.texture, splatTexCoord(${e.index}), 0);\n }\n `)}).outputs.gsplat}const ho=(()=>{const e=new r.DataTexture(new Uint32Array(16384),4096,1,r.RGBAIntegerFormat,r.UnsignedIntType);return e.internalFormat="RGBA32UI",e.needsUpdate=!0,e})();new r.BufferGeometry,new r.ShaderMaterial,(()=>{try{new Function("return 42;")}catch(Jm){return!1}})();class po extends r.Loader{constructor(e){super(e),this.fileLoader=new r.FileLoader(e)}load(e,t,n,r){return this.loadInternal({url:e,onLoad:t,onProgress:n,onError:r})}async loadAsync(e,t){return new Promise(((n,r)=>{this.load(e,(e=>{n(e)}),t,r)}))}parse(e){return new lo({packedSplats:e})}loadInternal({packedSplats:e,extSplats:t,url:n,fileBytes:r,fileType:i,fileName:s,stream:a,streamLength:o,onLoad:l,onProgress:c,onError:u,lod:h,nonLod:d,lodAbove:p,lodBase:m}){r instanceof ArrayBuffer&&(r=new Uint8Array(r));const f=r?void 0:this.manager.resolveURL((this.path??"")+(n??""));let g=null==a?void 0:a.getReader();this.manager.itemStart(f??""),Li.withWorker((async n=>{const u=(null==e?void 0:e.lod)??(null==t?void 0:t.lod);u&&(h=u);const x=(null==e?void 0:e.nonLod)??(null==t?void 0:t.nonLod);void 0!==x&&(d=x);const y=f?new URL(f,window.location.href).toString():void 0,v=await n.call(t?"loadExtSplats":"loadPackedSplats",{url:y,requestHeader:this.requestHeader,withCredentials:this.withCredentials,fileBytes:null==r?void 0:r.slice(),fileType:i,pathName:f||s,chunked:void 0!==a,chunkedLength:o,encoding:null==e?void 0:e.splatEncoding,lod:h,lodBase:m,nonLod:d,lodAbove:p},{onStatus:async e=>{const{loaded:t,total:r}=e;if(void 0!==t&&c&&c(new ProgressEvent("progress",{lengthComputable:0!==r,loaded:t,total:r})),e.nextChunk){let e;if(g){const{done:t,value:n}=await g.read();t?(g.releaseLock(),g=void 0,e=new Uint8Array(0)):e=n}else e=new Uint8Array(0);n.call("nextChunk",{chunk:e})}}});if(v.lodSplats&&(v.lodSplats=t?new Qs({...v.lodSplats}):new fo({...v.lodSplats,maxSplats:null==e?void 0:e.maxSplats})),t){const e={...v};t.initialize(e),null==l||l(t)}else{const t={...v};e?(e.initialize(t),null==l||l(e)):null==l||l(new fo(t))}})).catch((e=>{this.manager.itemError(f??""),null==u||u(e)})).finally((()=>{this.manager.itemEnd(f??"")}))}async loadInternalAsync({packedSplats:e,extSplats:t,url:n,fileBytes:r,fileType:i,fileName:s,stream:a,streamLength:o,onProgress:l,lod:c,nonLod:u,lodAbove:h,lodBase:d}){return new Promise(((p,m)=>{this.loadInternal({packedSplats:e,extSplats:t,url:n,fileBytes:r,fileType:i,fileName:s,stream:a,streamLength:o,onLoad:p,onProgress:l,onError:m,lod:c,nonLod:u,lodAbove:h,lodBase:d})}))}}const mo=class e{constructor(e={}){this.maxSplats=0,this.numSplats=0,this.packedArray=null,this.maxSh=3,this.isInitialized=!1,this.target=null,this.source=null,this.needsUpdate=!0,this.extra={},this.dyno=new go({packedSplats:this}),this.dynoRgbMinMaxLnScaleMinMax=new Ms({key:"rgbMinMaxLnScaleMinMax",value:new r.Vector4(0,1,yr,9),update:e=>{var t,n,r,i;return e.set((null==(t=this.splatEncoding)?void 0:t.rgbMin)??0,(null==(n=this.splatEncoding)?void 0:n.rgbMax)??1,(null==(r=this.splatEncoding)?void 0:r.lnScaleMin)??yr,(null==(i=this.splatEncoding)?void 0:i.lnScaleMax)??9),e}}),this.dynoNumSh=new Ts({key:"numSh",value:0,update:()=>Math.min(this.getNumSh(),this.maxSh)}),this.dynoShMax=new _s({key:"shMax",value:new r.Vector3,update:e=>{var t,n,r;return e.set((null==(t=this.splatEncoding)?void 0:t.sh1Max)??1,(null==(n=this.splatEncoding)?void 0:n.sh2Max)??1,(null==(r=this.splatEncoding)?void 0:r.sh3Max)??1),e}}),this.initialized=Promise.resolve(this),this.reinitialize(e)}reinitialize(e){this.isInitialized=!1,this.extra={},this.maxSplats=e.maxSplats??0,this.splatEncoding=e.splatEncoding,this.lod=e.lod,this.nonLod=e.nonLod,e.url||e.fileBytes||e.stream||e.construct?this.initialized=this.asyncInitialize(e).then((()=>(this.isInitialized=!0,this))):(this.initialize(e),this.isInitialized=!0,this.initialized=Promise.resolve(this))}initialize(e){this.extra=e.extra??{},this.splatEncoding=e.splatEncoding??this.splatEncoding,this.lodSplats=e.lodSplats,e.packedArray?(this.packedArray=e.packedArray,this.numSplats=e.numSplats??this.packedArray.length/4,this.maxSplats=Math.floor(this.packedArray.length/4),this.maxSplats=Math.floor(this.maxSplats/br)*br,this.numSplats=Math.min(this.maxSplats,e.numSplats??Number.POSITIVE_INFINITY)):(this.maxSplats=e.maxSplats??0,this.numSplats=0)}async asyncInitialize(e){const{url:t,fileBytes:n,fileType:r,fileName:i,stream:s,streamLength:a,construct:o,lod:l,nonLod:c,lodAbove:u}=e;this.lod=l,this.nonLod=c;const h=new po;if((n||t||s)&&await h.loadInternalAsync({packedSplats:this,url:t,fileBytes:n,fileType:r,fileName:i,stream:s,streamLength:a,onProgress:e.onProgress,lodAbove:u}),o){const e=o(this);e instanceof Promise&&await e}}dispose(){this.target&&(this.target.dispose(),this.target.texture.source.data=null,this.target=null),this.source&&(this.source.dispose(),this.source.source.data=null,this.source=null),this.packedArray=null;for(const e in this.extra){const t=this.extra[e];if(t instanceof bs){const e=t.value;(null==e?void 0:e.isTexture)&&(e.dispose(),e.source.data=null)}}this.extra={},this.disposeLodSplats()}prepareFetchSplat(){}getNumSplats(){return this.numSplats}hasRgbDir(){return Math.min(this.getNumSh(),this.maxSh)>0}getNumSh(){return this.extra.sh1?this.extra.sh2?this.extra.sh3?3:2:1:0}setMaxSh(e){this.maxSh=e}fetchSplat({index:e,viewOrigin:t}){let n=Vi(this.dyno,e);if(this.hasRgbDir()&&t){const r=Ni(n).outputs.center,i=Hs(Fs(r,t)),{sh1Texture:s,sh2Texture:a,sh3Texture:o}=this.ensureShTextures();let{rgb:l}=bo({coord:qi(e),viewDir:i,numSh:this.dynoNumSh,sh1Texture:s,sh2Texture:a,sh3Texture:o,shMax:this.dynoShMax});l=Us(l,Ni(n).outputs.rgb),n=$i({gsplat:n,rgb:l})}return n}ensureShTextures(){if(!this.extra.sh1)return{};let e=this.extra.sh1Texture;if(!e){let t=this.extra.sh1;const{width:n,height:i,depth:s,maxSplats:a}=gi(t.length/2);if(t.length<2*a){const e=new Uint32Array(2*a);e.set(t),this.extra.sh1=e,t=e}const o=new r.DataArrayTexture(t,n,i,s);o.format=r.RGIntegerFormat,o.type=r.UnsignedIntType,o.internalFormat="RG32UI",o.needsUpdate=!0,e=new Cs({value:o,key:"sh1"}),this.extra.sh1Texture=e}if(!this.extra.sh2)return{sh1Texture:e};let t=this.extra.sh2Texture;if(!t){let e=this.extra.sh2;const{width:n,height:i,depth:s,maxSplats:a}=gi(e.length/4);if(e.length<4*a){const t=new Uint32Array(4*a);t.set(e),this.extra.sh2=t,e=t}const o=new r.DataArrayTexture(e,n,i,s);o.format=r.RGBAIntegerFormat,o.type=r.UnsignedIntType,o.internalFormat="RGBA32UI",o.needsUpdate=!0,t=new Cs({value:o,key:"sh2"}),this.extra.sh2Texture=t}if(!this.extra.sh3)return{sh1Texture:e,sh2Texture:t};let n=this.extra.sh3Texture;if(!n){let e=this.extra.sh3;const{width:t,height:i,depth:s,maxSplats:a}=gi(e.length/4);if(e.length<4*a){const t=new Uint32Array(4*a);t.set(e),this.extra.sh3=t,e=t}const o=new r.DataArrayTexture(e,t,i,s);o.format=r.RGBAIntegerFormat,o.type=r.UnsignedIntType,o.internalFormat="RGBA32UI",o.needsUpdate=!0,n=new Cs({value:o,key:"sh3"}),this.extra.sh3Texture=n}return{sh1Texture:e,sh2Texture:t,sh3Texture:n}}ensureSplats(e){const t=e<=this.maxSplats?this.maxSplats:Math.max(e,2*this.maxSplats),n=this.packedArray?this.packedArray.length/4:0;if(!this.packedArray||t>n){this.maxSplats=gi(t).maxSplats;const e=new Uint32Array(4*this.maxSplats);this.packedArray&&e.set(this.packedArray),this.packedArray=e}return this.packedArray}ensureSplatsSh(e,t){let n,r;if(0===e)return this.ensureSplats(t);if(1===e)n=2,r="sh1";else if(2===e)n=4,r="sh2";else{if(3!==e)throw new Error(`Invalid level: ${e}`);n=4,r="sh3"}let i=this.extra[r]?this.extra[r].length/n:0;const s=t<=i?i:Math.max(t,2*i);if(!this.extra[r]||s>i){i=gi(s).maxSplats;const e=new Uint32Array(i*n);this.extra[r]&&e.set(this.extra[r]),this.extra[r]=e}return this.extra[r]}getSplat(e){if(!this.packedArray||e>=this.numSplats)throw new Error("Invalid index");return fi(this.packedArray,e,this.splatEncoding)}setSplat(e,t,n,r,i,s){di(this.ensureSplats(e+1),e,t.x,t.y,t.z,n.x,n.y,n.z,r.x,r.y,r.z,r.w,i,s.r,s.g,s.b),this.numSplats=Math.max(this.numSplats,e+1)}pushSplat(e,t,n,r,i){di(this.ensureSplats(this.numSplats+1),this.numSplats,e.x,e.y,e.z,t.x,t.y,t.z,n.x,n.y,n.z,n.w,r,i.r,i.g,i.b),++this.numSplats}forEachSplat(e){if(this.packedArray&&this.numSplats)for(let t=0;t<this.numSplats;++t){const n=fi(this.packedArray,t,this.splatEncoding);e(t,n.center,n.scales,n.quaternion,n.opacity,n.color)}}ensureGenerate(e){if(this.target&&(e??1)<=this.maxSplats)return!1;this.target&&this.target.dispose();const t=gi(e??1),{width:n,height:i,depth:s}=t;return this.maxSplats=t.maxSplats,this.target=new r.WebGLArrayRenderTarget(n,i,s,{depthBuffer:!1,stencilBuffer:!1,generateMipmaps:!1,magFilter:r.NearestFilter,minFilter:r.NearestFilter}),this.target.texture.format=r.RGBAIntegerFormat,this.target.texture.type=r.UnsignedIntType,this.target.texture.internalFormat="RGBA32UI",this.target.scissorTest=!0,!0}generateMapping(e){let t=0;const n=e.map((e=>{const n=t,r=Math.ceil(e/br)*br;return t+=r,{base:n,count:e}}));return{maxSplats:t,mapping:n}}getTexture(){if(this.target)return this.target.texture;if(this.source||this.packedArray){return this.maybeUpdateSource()}return e.getEmptyArray}maybeUpdateSource(){if(!this.packedArray)throw new Error("No packed splats");if(this.needsUpdate||!this.source){if(this.needsUpdate=!1,this.source){const{width:e,height:t,depth:n}=this.source.image;this.maxSplats!==e*t*n&&(this.source.dispose(),this.source=null)}if(this.source)this.packedArray.buffer!==this.source.image.data.buffer&&(this.source.image.data=new Uint8Array(this.packedArray.buffer));else{const{width:e,height:t,depth:n}=gi(this.maxSplats);this.source=new r.DataArrayTexture(this.packedArray,e,t,n),this.source.format=r.RGBAIntegerFormat,this.source.type=r.UnsignedIntType,this.source.internalFormat="RGBA32UI",this.source.needsUpdate=!0}this.source.needsUpdate=!0}return this.source}prepareProgramMaterial(t){let n=e.generatorProgram.get(t);if(!n){const r=qr({index:"int"},{},(({index:e},n,{roots:r})=>{t.inputs.index=e;const i=t.outputs.gsplat,s=hs(i,this.dynoRgbMinMaxLnScaleMinMax);r.push(s)}));e.programTemplate||(e.programTemplate=new Ds(Aa().computeUvec4Template)),n=new Rs({graph:r,inputs:{index:"_index"},outputs:{output:"target"},template:e.programTemplate}),Object.assign(n.uniforms,{targetLayer:{value:0},targetBase:{value:0},targetCount:{value:0}}),e.generatorProgram.set(t,n)}const r=n.prepareMaterial();return e.fullScreenQuad.material=r,{program:n,material:r}}saveRenderState(e){return{target:e.getRenderTarget(),xrEnabled:e.xr.enabled,autoClear:e.autoClear}}resetRenderState(e,t){e.setRenderTarget(t.target),e.xr.enabled=t.xrEnabled,e.autoClear=t.autoClear}generate({generator:t,base:n,count:r,renderer:i}){if(!this.target)throw new Error("Target must be initialized with ensureSplats");if(n+r>this.maxSplats)throw new Error("Base + count exceeds maxSplats");const{program:s,material:a}=this.prepareProgramMaterial(t);s.update();const o=this.saveRenderState(i),l=Math.ceil((n+r)/br)*br,c=4194304;for(a.uniforms.targetBase.value=n,a.uniforms.targetCount.value=r;n<l;){const t=Math.floor(n/c);a.uniforms.targetLayer.value=t;const r=t*c,s=Math.floor((n-r)/br),o=Math.min(wr,Math.ceil((l-r)/br));this.target.scissor.set(0,s,br,o-s),i.setRenderTarget(this.target,t),i.xr.enabled=!1,i.autoClear=!1,e.fullScreenQuad.render(i),n+=br*(o-s)}return this.resetRenderState(i,o),{nextBase:l}}disposeLodSplats(){this.lodSplats&&(this.lodSplats.dispose(),this.lodSplats=void 0)}async createLodSplats({rgbaArray:t,quality:n}={}){const r="number"==typeof this.lod?Math.max(1.1,Math.min(2,this.lod)):n?1.75:1.5,i=this.packedArray.slice(),s=t?(await t.getArray()).slice():void 0,a={sh1:this.extra.sh1?this.extra.sh1.slice():void 0,sh2:this.extra.sh2?this.extra.sh2.slice():void 0,sh3:this.extra.sh3?this.extra.sh3.slice():void 0},o=await Li.withWorker((async e=>await e.call(n?"qualityLodPackedSplats":"tinyLodPackedSplats",{numSplats:this.numSplats,packedArray:i,extra:a,lodBase:r,rgba:s,encoding:this.splatEncoding??Sr}))),l=new e(o);this.lodSplats&&this.lodSplats.dispose(),this.lodSplats=l,this.nonLod=!0,this.lod=!n||"quality"}extractSplats(t,n){const r=gi(t.length).maxSplats,i=new e({maxSplats:r});for(let e=0;e<t.length;e++){const r=this.getSplat(t[e]);if(n){let n=.61803398875*(t[e]>>>16);n-=Math.floor(n);const i=Math.max(0,Math.min(1,Math.abs(6*n-3)-1)),s=Math.max(0,Math.min(1,Math.abs(6*n+1)-1)),a=Math.max(0,Math.min(1,Math.abs(6*n-1)-1));r.color.r*=i,r.color.g*=s,r.color.b*=a}i.pushSplat(r.center,r.scales,r.quaternion,r.opacity,r.color)}return i}};mo.getEmptyArray=(()=>{const{width:e,height:t,depth:n,maxSplats:i}=gi(1),s=new Uint32Array(4*i),a=new r.DataArrayTexture(s,e,t,n);return a.format=r.RGBAIntegerFormat,a.type=r.UnsignedIntType,a.internalFormat="RGBA32UI",a.needsUpdate=!0,a})(),mo.programTemplate=null,mo.generatorProgram=new WeakMap,mo.fullScreenQuad=new o(new r.RawShaderMaterial({visible:!1})),mo.emptyUint32x4=(()=>{const{width:e,height:t,depth:n,maxSplats:i}=gi(1),s=new Uint32Array(4*i),a=new r.DataArrayTexture(s,e,t,n);return a.format=r.RGBAIntegerFormat,a.type=r.UnsignedIntType,a.internalFormat="RGBA32UI",a.needsUpdate=!0,a})(),mo.emptyUint32x2=(()=>{const{width:e,height:t,depth:n,maxSplats:i}=gi(1),s=new Uint32Array(2*i),a=new r.DataArrayTexture(s,e,t,n);return a.format=r.RGIntegerFormat,a.type=r.UnsignedIntType,a.internalFormat="RG32UI",a.needsUpdate=!0,a})();let fo=mo;class go extends bs{constructor({packedSplats:e}={}){super({key:"packedSplats",type:zi,globals:()=>[Xi],value:{textureArray:fo.getEmptyArray,numSplats:0,rgbMinMaxLnScaleMinMax:new r.Vector4(0,1,yr,9),lodOpacity:!1},update:e=>{var t,n,r,i,s,a,o,l,c,u,h,d;return e.textureArray=(null==(t=this.packedSplats)?void 0:t.getTexture())??fo.getEmptyArray,e.numSplats=(null==(n=this.packedSplats)?void 0:n.numSplats)??0,e.rgbMinMaxLnScaleMinMax.set((null==(i=null==(r=this.packedSplats)?void 0:r.splatEncoding)?void 0:i.rgbMin)??0,(null==(a=null==(s=this.packedSplats)?void 0:s.splatEncoding)?void 0:a.rgbMax)??1,(null==(l=null==(o=this.packedSplats)?void 0:o.splatEncoding)?void 0:l.lnScaleMin)??yr,(null==(u=null==(c=this.packedSplats)?void 0:c.splatEncoding)?void 0:u.lnScaleMax)??9),e.lodOpacity=(null==(d=null==(h=this.packedSplats)?void 0:h.splatEncoding)?void 0:d.lodOpacity)??!1,e}}),this.packedSplats=e}}const xo=Xr("\n vec3 evaluatePackedSH1(uvec2 packedData, vec3 viewDir, float sh1Max) {\n // Extract sint7 values packed into 2 x uint32\n vec3 sh1_0 = vec3(ivec3(\n int(packedData.x << 25u) >> 25,\n int(packedData.x << 18u) >> 25,\n int(packedData.x << 11u) >> 25\n ));\n vec3 sh1_1 = vec3(ivec3(\n int(packedData.x << 4u) >> 25,\n int((packedData.x >> 3u) | (packedData.y << 29u)) >> 25,\n int(packedData.y << 22u) >> 25\n ));\n vec3 sh1_2 = vec3(ivec3(\n int(packedData.y << 15u) >> 25,\n int(packedData.y << 8u) >> 25,\n int(packedData.y << 1u) >> 25\n ));\n\n vec3 rgb = sh1_0 * (-0.4886025 * viewDir.y)\n + sh1_1 * (0.4886025 * viewDir.z)\n + sh1_2 * (-0.4886025 * viewDir.x);\n return rgb * (sh1Max / 63.0);\n }\n"),yo=Xr("\n vec3 evaluatePackedSH2(uvec4 packedData, vec3 viewDir, float sh2Max) {\n // Extract sint8 values packed into 4 x uint32\n vec3 sh2_0 = vec3(ivec3(\n int(packedData.x << 24u) >> 24,\n int(packedData.x << 16u) >> 24,\n int(packedData.x << 8u) >> 24\n ));\n vec3 sh2_1 = vec3(ivec3(\n int(packedData.x) >> 24,\n int(packedData.y << 24u) >> 24,\n int(packedData.y << 16u) >> 24\n ));\n vec3 sh2_2 = vec3(ivec3(\n int(packedData.y << 8u) >> 24,\n int(packedData.y) >> 24,\n int(packedData.z << 24u) >> 24\n ));\n vec3 sh2_3 = vec3(ivec3(\n int(packedData.z << 16u) >> 24,\n int(packedData.z << 8u) >> 24,\n int(packedData.z) >> 24\n ));\n vec3 sh2_4 = vec3(ivec3(\n int(packedData.w << 24u) >> 24,\n int(packedData.w << 16u) >> 24,\n int(packedData.w << 8u) >> 24\n ));\n\n vec3 rgb = sh2_0 * (1.0925484 * viewDir.x * viewDir.y)\n + sh2_1 * (-1.0925484 * viewDir.y * viewDir.z)\n + sh2_2 * (0.3153915 * (2.0 * viewDir.z * viewDir.z - viewDir.x * viewDir.x - viewDir.y * viewDir.y))\n + sh2_3 * (-1.0925484 * viewDir.x * viewDir.z)\n + sh2_4 * (0.5462742 * (viewDir.x * viewDir.x - viewDir.y * viewDir.y));\n return rgb * (sh2Max / 127.0);\n }\n"),vo=Xr("\n vec3 evaluatePackedSH3(uvec4 packedData, vec3 viewDir, float sh3Max) {\n // Extract sint6 values packed into 4 x uint32\n vec3 sh3_0 = vec3(ivec3(\n int(packedData.x << 26u) >> 26,\n int(packedData.x << 20u) >> 26,\n int(packedData.x << 14u) >> 26\n ));\n vec3 sh3_1 = vec3(ivec3(\n int(packedData.x << 8u) >> 26,\n int(packedData.x << 2u) >> 26,\n int((packedData.x >> 4u) | (packedData.y << 28u)) >> 26\n ));\n vec3 sh3_2 = vec3(ivec3(\n int(packedData.y << 22u) >> 26,\n int(packedData.y << 16u) >> 26,\n int(packedData.y << 10u) >> 26\n ));\n vec3 sh3_3 = vec3(ivec3(\n int(packedData.y << 4u) >> 26,\n int((packedData.y >> 2u) | (packedData.z << 30u)) >> 26,\n int(packedData.z << 24u) >> 26\n ));\n vec3 sh3_4 = vec3(ivec3(\n int(packedData.z << 18u) >> 26,\n int(packedData.z << 12u) >> 26,\n int(packedData.z << 6u) >> 26\n ));\n vec3 sh3_5 = vec3(ivec3(\n int(packedData.z) >> 26,\n int(packedData.w << 26u) >> 26,\n int(packedData.w << 20u) >> 26\n ));\n vec3 sh3_6 = vec3(ivec3(\n int(packedData.w << 14u) >> 26,\n int(packedData.w << 8u) >> 26,\n int(packedData.w << 2u) >> 26\n ));\n\n float xx = viewDir.x * viewDir.x;\n float yy = viewDir.y * viewDir.y;\n float zz = viewDir.z * viewDir.z;\n float xy = viewDir.x * viewDir.y;\n float yz = viewDir.y * viewDir.z;\n float zx = viewDir.z * viewDir.x;\n\n vec3 rgb = sh3_0 * (-0.5900436 * viewDir.y * (3.0 * xx - yy))\n + sh3_1 * (2.8906114 * xy * viewDir.z) +\n + sh3_2 * (-0.4570458 * viewDir.y * (4.0 * zz - xx - yy))\n + sh3_3 * (0.3731763 * viewDir.z * (2.0 * zz - 3.0 * xx - 3.0 * yy))\n + sh3_4 * (-0.4570458 * viewDir.x * (4.0 * zz - xx - yy))\n + sh3_5 * (1.4453057 * viewDir.z * (xx - yy))\n + sh3_6 * (-0.5900436 * viewDir.x * (xx - 3.0 * yy));\n return rgb * (sh3Max / 31.0);\n }\n");function bo({coord:e,viewDir:t,numSh:n,sh1Texture:r,sh2Texture:i,sh3Texture:s,shMax:a}){return new $r({inTypes:{coord:"ivec3",viewDir:"vec3",numSh:"int",sh1Texture:"usampler2DArray",sh2Texture:"usampler2DArray",sh3Texture:"usampler2DArray",shMax:"vec3"},outTypes:{rgb:"vec3"},inputs:{coord:e,viewDir:t,numSh:n,sh1Texture:r,sh2Texture:i,sh3Texture:s,shMax:a},globals:()=>[xo,yo,vo],statements:({inputs:e,outputs:t})=>{const n=["vec3 rgb = vec3(0.0);"];return e.sh1Texture&&(n.push(...Wr(`\n if (${e.numSh} >= 1) {\n vec3 sh1Rgb = evaluatePackedSH1(texelFetch(${e.sh1Texture}, ${e.coord}, 0).rg, ${e.viewDir}, ${e.shMax}.x);\n rgb += sh1Rgb;\n `)),e.sh2Texture&&(n.push(...Wr(`\n if (${e.numSh} >= 2) {\n vec3 sh2Rgb = evaluatePackedSH2(texelFetch(${e.sh2Texture}, ${e.coord}, 0), ${e.viewDir}, ${e.shMax}.y);\n rgb += sh2Rgb;\n `)),e.sh3Texture&&n.push(...Wr(`\n if (${e.numSh} >= 3) {\n vec3 sh3Rgb = evaluatePackedSH3(texelFetch(${e.sh3Texture}, ${e.coord}, 0), ${e.viewDir}, ${e.shMax}.z);\n rgb += sh3Rgb;\n }\n `)),n.push("}")),n.push("}")),n.push(`${t.rgb} = rgb;`),n}}).outputs}const wo=class e{constructor(e){if(this.lastTime=null,this.encodeLinear=!1,this.superXY=1,this.display=null,this.sorting=null,this.pending=null,this.sortingCheck=!1,this.readback16=new Uint16Array(0),this.readback32=new Uint32Array(0),this.spark=e.spark,this.camera=e.camera,this.viewToWorld=e.viewToWorld??new r.Matrix4,e.target){const{width:t,height:n,doubleBuffer:i}=e.target,s=Math.max(1,Math.min(4,e.target.superXY??1));if(this.superXY=s,t*s>8192||n*s>8192)throw new Error("Target size too large");this.target=new r.WebGLRenderTarget(t*s,n*s,{format:r.RGBAFormat,type:r.UnsignedByteType,colorSpace:r.SRGBColorSpace}),i&&(this.back=new r.WebGLRenderTarget(t*s,n*s,{format:r.RGBAFormat,type:r.UnsignedByteType,colorSpace:r.SRGBColorSpace})),this.encodeLinear=!0}this.onTextureUpdated=e.onTextureUpdated,this.sortRadial=e.sortRadial??!0,this.sortDistance=e.sortDistance,this.sortCoorient=e.sortCoorient,this.depthBias=e.depthBias,this.sort360=e.sort360,this.sort32=e.sort32,this.stochastic=e.stochastic??!1,this.orderingFreelist=new ci({allocate:e=>new Uint32Array(e),valid:(e,t)=>e.length===t}),this.autoUpdate=!1,this.setAutoUpdate(e.autoUpdate??!1)}dispose(){var e;this.setAutoUpdate(!1),this.target&&(this.target.dispose(),this.target=void 0),this.back&&(this.back.dispose(),this.back=void 0),this.display&&(this.spark.releaseAccumulator(this.display.accumulator),this.display.geometry.dispose(),this.display=null),(null==(e=this.pending)?void 0:e.accumulator)&&(this.spark.releaseAccumulator(this.pending.accumulator),this.pending=null)}setAutoUpdate(e){!this.autoUpdate&&e?this.spark.autoViewpoints.push(this):this.autoUpdate&&!e&&(this.spark.autoViewpoints=this.spark.autoViewpoints.filter((e=>e!==this))),this.autoUpdate=e}async prepare({scene:e,camera:t,viewToWorld:n,update:r,forceOrigin:i}){for(n?this.viewToWorld=n:(this.camera=t??this.camera,this.camera&&(this.camera.updateMatrixWorld(),this.viewToWorld=this.camera.matrixWorld.clone()));r??1;){const t=i?this.viewToWorld:this.spark.matrixWorld;if(this.spark.updateInternal({scene:e,originToWorld:t}))break;await new Promise((e=>setTimeout(e,10)))}const s=this.spark.active;s.refCount+=1,await this.sortUpdate({accumulator:s,viewToWorld:this.viewToWorld}),this.spark.releaseAccumulator(s)}renderTarget({scene:e,camera:t}){var n;const i=this.back??this.target;if(!i)throw new Error("Must initialize SparkViewpoint with target");if(!(t=t??this.camera))throw new Error("Must provide camera");if(t instanceof r.PerspectiveCamera){const e=(new r.PerspectiveCamera).copy(t,!1);e.aspect=i.width/i.height,e.updateProjectionMatrix(),t=e}this.viewToWorld=t.matrixWorld.clone();const s=this.spark.renderer.getRenderTarget();try{this.spark.renderer.setRenderTarget(i),this.spark.prepareViewpoint(this),this.spark.renderer.render(e,t)}finally{this.spark.prepareViewpoint(this.spark.defaultView),this.spark.renderer.setRenderTarget(s)}i!==this.target&&([this.target,this.back]=[this.back,this.target]),null==(n=this.onTextureUpdated)||n.call(this,i.texture)}async readTarget(){if(!this.target)throw new Error("Must initialize SparkViewpoint with target");const{width:e,height:t}=this.target,n=e*t*4;(!this.superPixels||this.superPixels.length<n)&&(this.superPixels=new Uint8Array(n)),await this.spark.renderer.readRenderTargetPixelsAsync(this.target,0,0,e,t,this.superPixels);const{superXY:r}=this;if(1===r)return this.superPixels;const i=e/r,s=t/r,a=i*s*4;(!this.pixels||this.pixels.length<a)&&(this.pixels=new Uint8Array(a));const{superPixels:o,pixels:l}=this,c=r*r;for(let u=0;u<s;u++){const e=u*i;for(let t=0;t<i;t++){const n=t*r;let i=0,s=0,a=0,h=0;for(let e=0;e<r;e++){const t=(u*r+e)*this.target.width;for(let e=0;e<r;e++){const r=4*(t+n+e);i+=o[r],s+=o[r+1],a+=o[r+2],h+=o[r+3]}}const d=4*(e+t);l[d]=i/c,l[d+1]=s/c,l[d+2]=a/c,l[d+3]=h/c}}return l}async prepareRenderPixels({scene:e,camera:t,viewToWorld:n,update:r,forceOrigin:i}){return await this.prepare({scene:e,camera:t,viewToWorld:n,update:r,forceOrigin:i}),this.renderTarget({scene:e,camera:t}),this.readTarget()}autoPoll({accumulator:e}){var t,n,r;this.camera&&(this.camera.updateMatrixWorld(),this.viewToWorld=this.camera.matrixWorld.clone());let i=!1,s=!1;if(this.display){if(e){i=!0;const{mappingVersion:t}=this.display.accumulator;e.mappingVersion===t&&(e.refCount+=1,this.spark.releaseAccumulator(this.display.accumulator),this.display.accumulator=e,this.display.viewToWorld.copy(this.viewToWorld),s=!0,this.spark.viewpoint===this&&this.spark.prepareViewpoint(this))}}else i=!0;const a=(null==(t=this.sorting)?void 0:t.viewToWorld)??(null==(n=this.display)?void 0:n.viewToWorld);a&&!wi({matrix1:this.viewToWorld,matrix2:a,maxDistance:this.sortDistance??.01,minCoorient:this.sortCoorient??this.sortRadial?.99:.999})&&(i=!0),i&&(e&&(e.refCount+=1),(null==(r=this.pending)?void 0:r.accumulator)&&this.spark.releaseAccumulator(this.pending.accumulator),this.pending={accumulator:e,viewToWorld:this.viewToWorld,displayed:s},this.driveSort())}async driveSort(){for(var e;;){if(this.sorting||!this.pending)return;const{viewToWorld:t,displayed:n}=this.pending;let r=this.pending.accumulator;if(r||(r=(null==(e=this.display)?void 0:e.accumulator)??this.spark.active,r.refCount+=1),this.pending=null,!r)throw new Error("No accumulator to sort");this.sorting={viewToWorld:t},await this.sortUpdate({accumulator:r,viewToWorld:t,displayed:n}),this.sorting=null,this.spark.releaseAccumulator(r)}}async sortUpdate({accumulator:t,viewToWorld:n,displayed:r=!1}){if(this.sortingCheck)throw new Error("Only one sort at a time");this.sortingCheck=!0,t=t??this.spark.active;const{numSplats:i,maxSplats:s}=t.splats;let a=0,o=this.orderingFreelist.alloc(s);if(this.stochastic){a=i;for(let e=0;e<i;++e)o[e]=e}else if(i>0){const{reader:r,doubleSortReader:l,sort32Reader:c,dynoSortRadial:u,dynoOrigin:h,dynoDirection:d,dynoDepthBias:p,dynoSort360:m,dynoSplats:f}=e.makeSorter(),g=this.sort32??!1;let x;if(g)this.readback32=r.ensureBuffer(s,this.readback32),x=this.readback32;else{const e=Math.ceil(s/2);this.readback16=r.ensureBuffer(e,this.readback16),x=this.readback16}const y=t.toWorld.clone().invert(),v=n.clone().premultiply(y);u.value=!!this.sort360||this.sortRadial,h.value.set(0,0,0).applyMatrix4(v),d.value.set(0,0,-1).applyMatrix4(v).sub(h.value).normalize(),p.value=this.depthBias??1,m.value=this.sort360??!1,f.packedSplats=t.splats;const b=g?c:l,w=g?i:Math.ceil(i/2);await r.renderReadback({renderer:this.spark.renderer,reader:b,count:w,readback:x});const T=await Ci((async e=>{const t=g?"sort32Splats":"sortDoubleSplats";return e.call(t,{maxSplats:s,numSplats:i,readback:x,ordering:o})}));g?this.readback32=T.readback:this.readback16=T.readback,o=T.ordering,a=T.activeSplats}this.updateDisplay({accumulator:t,viewToWorld:n,ordering:o,activeSplats:a,displayed:r}),this.sortingCheck=!1}updateDisplay({accumulator:e,viewToWorld:t,ordering:n,activeSplats:r,displayed:i=!1}){if(this.display){i||e===this.display.accumulator||(e.refCount+=1,this.spark.releaseAccumulator(this.display.accumulator),this.display.accumulator=e),this.display.viewToWorld=t;const s=this.display.geometry.ordering;s.length===n.length?this.display.geometry.update(n,r):(this.display.geometry.dispose(),this.display.geometry=new En(n,r)),this.orderingFreelist.free(s)}else e.refCount+=1,this.display={accumulator:e,viewToWorld:t,geometry:new En(n,r)};this.spark.viewpoint===this&&this.spark.prepareViewpoint(this)}static makeSorter(){if(!e.dynos){const t=new ws({value:!0}),n=new _s({value:new r.Vector3}),i=new _s({value:new r.Vector3}),s=new Ss({value:1}),a=new ws({value:!1}),o=new go,l=new Ca,c=qr({index:"int"},{rgba8:"vec4"},(({index:e})=>{if(!e)throw new Error("No index");const r={sortRadial:t,sortOrigin:n,sortDirection:i,sortDepthBias:s,sort360:a},l=zs(e,Br("int",2)),c=(({vector:e,vectorType:t,x:n,y:r,z:i,w:s,r:a,g:o,b:l,a:c})=>new Ws({vector:e,vectorType:t,x:n,y:r,z:i,w:s,r:a,g:o,b:l,a:c}))({vectorType:"vec2",x:_o({gsplat:Vi(o,l),...r}),y:_o({gsplat:Vi(o,Us(l,Br("int",1))),...r})});return{rgba8:Ns(new Gs({value:c}))}})),u=qr({index:"int"},{rgba8:"vec4"},(({index:e})=>{if(!e)throw new Error("No index");const r={sortRadial:t,sortOrigin:n,sortDirection:i,sortDepthBias:s,sort360:a},l=_o({gsplat:Vi(o,e),...r});return{rgba8:Ns(new $s({value:l}))}}));e.dynos={dynoSortRadial:t,dynoOrigin:n,dynoDirection:i,dynoDepthBias:s,dynoSort360:a,dynoSplats:o,reader:l,doubleSortReader:c,sort32Reader:u}}return e.dynos}};wo.EMPTY_TEXTURE=new r.Texture,wo.dynos=null;let To=wo;const So=Xr("\n float computeSort(Gsplat gsplat, bool sortRadial, vec3 sortOrigin, vec3 sortDirection, float sortDepthBias, bool sort360) {\n if (!isGsplatActive(gsplat.flags)) {\n return INFINITY;\n }\n\n vec3 center = gsplat.center - sortOrigin;\n float biasedDepth = dot(center, sortDirection) + sortDepthBias;\n if (!sort360 && (biasedDepth <= 0.0)) {\n return INFINITY;\n }\n\n return sortRadial ? length(center) : biasedDepth;\n }\n");function _o({gsplat:e,sortRadial:t,sortOrigin:n,sortDirection:r,sortDepthBias:i,sort360:s}){return Hr({inTypes:{gsplat:Ui,sortRadial:"bool",sortOrigin:"vec3",sortDirection:"vec3",sortDepthBias:"float",sort360:"bool"},outTypes:{metric:"float"},globals:()=>[ji,So],inputs:{gsplat:e,sortRadial:t,sortOrigin:n,sortDirection:r,sortDepthBias:i,sort360:s},statements:({inputs:e,outputs:t})=>{const{gsplat:n,sortRadial:r,sortOrigin:i,sortDirection:s,sortDepthBias:a,sort360:o}=e;return Wr(`\n ${t.metric} = computeSort(${n}, ${r}, ${i}, ${s}, ${a}, ${o});\n `)}}).outputs.metric}class Mo{constructor(){this.splats=new fo,this.toWorld=new r.Matrix4,this.mapping=[],this.refCount=0,this.splatsVersion=-1,this.mappingVersion=-1}ensureGenerate(e){this.splats.ensureGenerate(e)&&(this.mapping=[])}generateSplats({renderer:e,modifier:t,generators:n,forceUpdate:r,originToWorld:i}){const s=this.mapping.reduce(((e,t)=>(e.set(t.node,t),e)),new Map);let a=0,o=0;for(const{node:c,generator:u,version:h,base:d,count:p}of n){const n=s.get(c);if((r||u!==(null==n?void 0:n.generator)||h!==(null==n?void 0:n.version)||d!==(null==n?void 0:n.base)||p!==(null==n?void 0:n.count))&&u&&p>0){const n=t.apply(u);try{this.splats.generate({generator:n,base:d,count:p,renderer:e})}catch(l){c.generator=void 0,c.generatorError=l}a+=1}o=Math.max(o,d+p)}return this.splats.numSplats=o,this.toWorld.copy(i),this.mapping=n,0!==a}hasCorrespondence(e){return this.mapping.length===e.mapping.length&&this.mapping.every((({node:t,base:n,count:r},i)=>{const{node:s,base:a,count:o}=e.mapping[i];return t===s&&n===a&&r===o}))}}const Ao=class e extends r.Mesh{constructor(t){const n=e.makeUniforms(),i=Aa(),s=t.premultipliedAlpha??!0,a=new r.ShaderMaterial({glslVersion:r.GLSL3,vertexShader:i.oldSplatVertex,fragmentShader:i.oldSplatFragment,uniforms:n,premultipliedAlpha:s,transparent:!0,depthTest:!0,depthWrite:!1,side:r.DoubleSide});super(Eo,a),this.splatTexture=null,this.autoViewpoints=[],this.rotateToAccumulator=new Ms({value:new r.Quaternion}),this.translateToAccumulator=new _s({value:new r.Vector3}),this.lastFrame=-1,this.lastUpdateTime=null,this.defaultCameras=[],this.lastStochastic=null,this.pendingUpdate={scene:null,originToWorld:new r.Matrix4,timeoutId:-1},this.envViewpoint=null,this.frustumCulled=!1,this.renderer=t.renderer,this.material=a,this.uniforms=n;const o=qr({gsplat:Ui},{gsplat:Ui},(({gsplat:e})=>{if(!e)throw new Error("gsplat not defined");return{gsplat:e=Gi(e,{rotate:this.rotateToAccumulator,translate:this.translateToAccumulator})}}));this.modifier=new Ga(o),this.premultipliedAlpha=s,this.autoUpdate=t.autoUpdate??!0,this.preUpdate=t.preUpdate??!1,this.needsUpdate=!1,this.originDistance=t.originDistance??1,this.maxStdDev=t.maxStdDev??Math.sqrt(8),this.minPixelRadius=t.minPixelRadius??0,this.maxPixelRadius=t.maxPixelRadius??512,this.minAlpha=t.minAlpha??1/255*.5,this.enable2DGS=t.enable2DGS??!1,this.preBlurAmount=t.preBlurAmount??0,this.blurAmount=t.blurAmount??.3,this.focalDistance=t.focalDistance??0,this.apertureAngle=t.apertureAngle??0,this.falloff=t.falloff??1,this.clipXY=t.clipXY??1.4,this.focalAdjustment=t.focalAdjustment??1,this.splatEncoding=t.splatEncoding??{...Sr},this.active=new Mo,this.active.refCount=1,this.accumulatorCount=1,this.freeAccumulators=[];for(let e=0;e<1;++e)this.freeAccumulators.push(new Mo),this.accumulatorCount+=1;this.defaultView=new To({...t.view,autoUpdate:!0,spark:this}),this.viewpoint=this.defaultView,this.prepareViewpoint(this.viewpoint),this.clock=t.clock?vi(t.clock):new r.Clock}static makeUniforms(){return{renderSize:{value:new r.Vector2},near:{value:.1},far:{value:1e3},numSplats:{value:0},renderToViewQuat:{value:new r.Quaternion},renderToViewPos:{value:new r.Vector3},maxStdDev:{value:1},minPixelRadius:{value:0},maxPixelRadius:{value:512},minAlpha:{value:1/255*.5},stochastic:{value:!1},enable2DGS:{value:!1},preBlurAmount:{value:0},blurAmount:{value:.3},focalDistance:{value:0},apertureAngle:{value:0},falloff:{value:1},clipXY:{value:1.4},focalAdjustment:{value:1},splatTexEnable:{value:!1},splatTexture:{type:"t",value:e.EMPTY_SPLAT_TEXTURE},splatTexMul:{value:new r.Matrix2},splatTexAdd:{value:new r.Vector2},splatTexNear:{value:.1},splatTexFar:{value:1e3},splatTexMid:{value:0},packedSplats:{type:"t",value:fo.getEmptyArray},rgbMinMaxLnScaleMinMax:{value:new r.Vector4},time:{value:0},deltaTime:{value:0},encodeLinear:{value:!1},debugFlag:{value:!1}}}canAllocAccumulator(){return this.freeAccumulators.length>0||this.accumulatorCount<5}maybeAllocAccumulator(){let e=this.freeAccumulators.pop();if(void 0===e){if(this.accumulatorCount>=5)return null;e=new Mo,this.accumulatorCount+=1}return e.refCount=1,e}releaseAccumulator(e){e.refCount-=1,0===e.refCount&&this.freeAccumulators.push(e)}newViewpoint(e){return new To({...e,spark:this})}onBeforeRender(t,n,i){var s,a;const o=this.time??this.clock.getElapsedTime(),l=o-(this.viewpoint.lastTime??o);this.viewpoint.lastTime=o;const c=t.info.render.frame,u=c!==this.lastFrame;this.lastFrame=c;const h=this.viewpoint;if(h===this.defaultView){if(u)if(t.xr.isPresenting){const e=t.xr.getCamera().cameras;this.defaultCameras=e.map((e=>e.matrixWorld)),this.defaultView.viewToWorld=function(e){if(0===e.length)return null;const t=new r.Vector3,n=new r.Quaternion,i=new r.Vector3,s=[],a=[];for(const r of e)r.decompose(t,n,i),s.push(t),a.push(n);return(new r.Matrix4).compose(function(e){const t=new r.Vector3;for(const n of e)t.add(n);return t.divideScalar(e.length)}(s),function(e){if(0===e.length)return new r.Quaternion;const t=e[0].clone();for(let n=1;n<e.length;n++)e[n].dot(e[0])<0?(t.x-=e[n].x,t.y-=e[n].y,t.z-=e[n].z,t.w-=e[n].w):(t.x+=e[n].x,t.y+=e[n].y,t.z+=e[n].z,t.w+=e[n].w);return t.normalize()}(a),new r.Vector3(1,1,1))}(this.defaultCameras)??new r.Matrix4}else this.defaultView.viewToWorld=i.matrixWorld.clone(),this.defaultCameras=[this.defaultView.viewToWorld];this.autoUpdate&&this.update({scene:n,viewToWorld:this.defaultView.viewToWorld})}if(u&&(this.material.premultipliedAlpha!==this.premultipliedAlpha&&(this.material.premultipliedAlpha=this.premultipliedAlpha,this.material.needsUpdate=!0),this.uniforms.time.value=o,this.uniforms.deltaTime.value=l,this.uniforms.debugFlag.value=performance.now()/1e3%2<1,h.display&&h.stochastic&&(this.geometry.instanceCount=this.uniforms.numSplats.value)),h.target)this.uniforms.renderSize.value.set(h.target.width,h.target.height);else{const e=t.getDrawingBufferSize(this.uniforms.renderSize.value);if(1===e.x&&1===e.y){const n=null==(s=t.xr.getSession())?void 0:s.renderState.baseLayer;n&&(e.x=n.framebufferWidth,e.y=n.framebufferHeight)}}const d=i;if(this.uniforms.near.value=d.near,this.uniforms.far.value=d.far,this.uniforms.encodeLinear.value=h.encodeLinear,this.uniforms.maxStdDev.value=this.maxStdDev,this.uniforms.minPixelRadius.value=this.minPixelRadius,this.uniforms.maxPixelRadius.value=this.maxPixelRadius,this.uniforms.minAlpha.value=this.minAlpha,this.uniforms.stochastic.value=h.stochastic,this.uniforms.enable2DGS.value=this.enable2DGS,this.uniforms.preBlurAmount.value=this.preBlurAmount,this.uniforms.blurAmount.value=this.blurAmount,this.uniforms.focalDistance.value=this.focalDistance,this.uniforms.apertureAngle.value=this.apertureAngle,this.uniforms.falloff.value=this.falloff,this.uniforms.clipXY.value=this.clipXY,this.uniforms.focalAdjustment.value=this.focalAdjustment,this.lastStochastic!==!h.stochastic&&(this.lastStochastic=!h.stochastic,this.material.transparent=!h.stochastic,this.material.depthWrite=h.stochastic,this.material.needsUpdate=!0),this.splatTexture){const{enable:t,texture:n,multiply:r,add:i,near:s,far:a,mid:o}=this.splatTexture;t&&n?(this.uniforms.splatTexEnable.value=!0,this.uniforms.splatTexture.value=n,r?this.uniforms.splatTexMul.value.fromArray(r.elements):this.uniforms.splatTexMul.value.set(.5/this.maxStdDev,0,0,.5/this.maxStdDev),this.uniforms.splatTexAdd.value.set((null==i?void 0:i.x)??.5,(null==i?void 0:i.y)??.5),this.uniforms.splatTexNear.value=s??this.uniforms.near.value,this.uniforms.splatTexFar.value=a??this.uniforms.far.value,this.uniforms.splatTexMid.value=o??0):(this.uniforms.splatTexEnable.value=!1,this.uniforms.splatTexture.value=e.EMPTY_SPLAT_TEXTURE)}else this.uniforms.splatTexEnable.value=!1,this.uniforms.splatTexture.value=e.EMPTY_SPLAT_TEXTURE;const p=(null==(a=h.display)?void 0:a.accumulator.toWorld)??new r.Matrix4,m=i.matrixWorld.clone().invert();p.clone().premultiply(m).decompose(this.uniforms.renderToViewPos.value,this.uniforms.renderToViewQuat.value,new r.Vector3)}prepareViewpoint(e){var t,n,r,i;if(this.viewpoint=e??this.viewpoint,this.viewpoint.display){const{accumulator:e,geometry:s}=this.viewpoint.display;this.uniforms.numSplats.value=e.splats.numSplats,this.uniforms.packedSplats.value=e.splats.getTexture(),this.uniforms.rgbMinMaxLnScaleMinMax.value.set((null==(t=e.splats.splatEncoding)?void 0:t.rgbMin)??0,(null==(n=e.splats.splatEncoding)?void 0:n.rgbMax)??1,(null==(r=e.splats.splatEncoding)?void 0:r.lnScaleMin)??yr,(null==(i=e.splats.splatEncoding)?void 0:i.lnScaleMax)??9),this.geometry=s,this.material.transparent=!this.viewpoint.stochastic,this.material.depthWrite=this.viewpoint.stochastic,this.material.needsUpdate=!0}else this.uniforms.numSplats.value=0,this.uniforms.packedSplats.value=fo.getEmptyArray,this.geometry=Eo}update({scene:e,viewToWorld:t}){const n=this.matrixWorld;this.preUpdate?this.updateInternal({scene:e,originToWorld:n.clone(),viewToWorld:t}):(this.pendingUpdate.scene=e,this.pendingUpdate.originToWorld.copy(n),-1===this.pendingUpdate.timeoutId&&(this.pendingUpdate.timeoutId=setTimeout((()=>{const{scene:e,originToWorld:n}=this.pendingUpdate;this.pendingUpdate.scene=null,this.pendingUpdate.timeoutId=-1;if(this.updateInternal({scene:e,originToWorld:n,viewToWorld:t})){this.renderer.getContext().flush()}}),1)))}updateInternal({scene:e,originToWorld:t,viewToWorld:n}){var i;if(!this.canAllocAccumulator())return!1;t||(t=this.active.toWorld),n=n??t.clone();const s=this.time??this.clock.getElapsedTime(),a=s-(this.lastUpdateTime??s);this.lastUpdateTime=s;const o=this.active.mapping.reduce(((e,t)=>(e.set(t.node,t),e)),new Map),{generators:l,visibleGenerators:c,globalEdits:u}=this.compileScene(e);for(const r of l)null==(i=r.frameUpdate)||i.call(r,{renderer:this.renderer,object:r,time:s,deltaTime:a,viewToWorld:n,globalEdits:u});const h=new Set(c.map((e=>e.uuid)));for(const r of l){const e=o.get(r),t=r.generator&&h.has(r.uuid)?r.numSplats:0;(this.needsUpdate||r.generator!==(null==e?void 0:e.generator)||t!==(null==e?void 0:e.count))&&r.updateVersion()}const d=!wi({matrix1:t,matrix2:this.active.toWorld,maxDistance:this.originDistance}),p=this.needsUpdate||d||l.length!==o.size||l.some((e=>{var t;return e.version!==(null==(t=o.get(e))?void 0:t.version)}));this.needsUpdate=!1;let m=null;if(p){if(m=this.maybeAllocAccumulator(),!m)throw new Error("Unreachable");const e=!wi({matrix1:t,matrix2:m.toWorld,maxDistance:1e-5,minCoorient:.99999}),n=c.map(((e,t)=>{const n=o.get(e);return n?[e.version-n.version,n.base,e]:[Number.POSITIVE_INFINITY,e.version,e]})).sort(((e,t)=>e[0]!==t[0]?e[0]-t[0]:e[1]-t[1])).map((([e,t,n])=>n)),i=n.map((e=>e.numSplats)),{maxSplats:s,mapping:a}=m.splats.generateMapping(i),l=n.map(((e,t)=>{const{base:n,count:r}=a[t];return{node:e,generator:e.generator,version:e.version,base:n,count:r}}));t.clone().invert().decompose(this.translateToAccumulator.value,this.rotateToAccumulator.value,new r.Vector3),m.ensureGenerate(s),m.splats.splatEncoding={...this.splatEncoding},m.generateSplats({renderer:this.renderer,modifier:this.modifier,generators:l,forceUpdate:e,originToWorld:t}),m.splatsVersion=this.active.splatsVersion+1;const u=m.hasCorrespondence(this.active);m.mappingVersion=this.active.mappingVersion+(u?0:1),this.releaseAccumulator(this.active),this.active=m,this.prepareViewpoint()}return setTimeout((()=>{for(const e of this.autoViewpoints)e.autoPoll({accumulator:m??void 0})}),1),!0}compileScene(e){const t=[];e.traverse((e=>{e instanceof ja&&t.push(e)}));const n=[];e.traverseVisible((e=>{e instanceof ja&&n.push(e)}));const r=new Set;return e.traverseVisible((e=>{if(e instanceof za){let t=e.parent;for(;null!=t&&!(t instanceof lo);)t=t.parent;null==t&&r.add(e)}})),{generators:t,visibleGenerators:n,globalEdits:Array.from(r)}}async renderEnvMap({renderer:t,scene:n,worldCenter:i,size:s=256,near:a=.1,far:o=1e3,hideObjects:l=[],update:c=!1}){var u,h;if(this.envViewpoint||(this.envViewpoint=this.newViewpoint({sort360:!0})),!e.cubeRender||e.cubeRender.target.width!==s||e.cubeRender.near!==a||e.cubeRender.far!==o){e.cubeRender&&e.cubeRender.target.dispose();const t=new r.WebGLCubeRenderTarget(s,{format:r.RGBAFormat,generateMipmaps:!0,minFilter:r.LinearMipMapLinearFilter}),n=new r.CubeCamera(a,o,t);e.cubeRender={target:t,camera:n,near:a,far:o}}e.pmrem||(e.pmrem=new r.PMREMGenerator(t??this.renderer));const d=(new r.Matrix4).setPosition(i);await(null==(u=this.envViewpoint)?void 0:u.prepare({scene:n,viewToWorld:d,update:c}));const{target:p,camera:m}=e.cubeRender;m.position.copy(i);const f=new Map;for(const e of l)f.set(e,e.visible),e.visible=!1;this.prepareViewpoint(this.envViewpoint),m.update(t??this.renderer,n),this.prepareViewpoint(this.defaultView);for(const[e,r]of f.entries())e.visible=r;return null==(h=e.pmrem)?void 0:h.fromCubemap(p.texture).texture}recurseSetEnvMap(e,t){e.traverse((e=>{if(e instanceof r.Mesh)if(Array.isArray(e.material))for(const n of e.material)n instanceof r.MeshStandardMaterial&&(n.envMap=t);else e.material instanceof r.MeshStandardMaterial&&(e.material.envMap=t)}))}getRgba({generator:e,rgba:t}){const n=this.active.mapping.find((({node:t})=>t===e));if(!n)throw new Error("Generator not found");return(t=t??new Da).fromPackedSplats({packedSplats:this.active.splats,base:n.base,count:n.count,renderer:this.renderer}),t}async readRgba({generator:e,rgba:t}){return(t=this.getRgba({generator:e,rgba:t})).read()}};Ao.cubeRender=null,Ao.pmrem=null,Ao.EMPTY_SPLAT_TEXTURE=new r.Data3DTexture;const Eo=new En(new Uint32Array(1),0);qr({packedSplats:zi,index:"int"},{gsplat:Ui},(({packedSplats:e,index:t})=>{if(!e||!t)throw new Error("Invalid input");return{gsplat:Vi(e,t)}})),new r.Matrix4,Xr("\n struct GsplatSkinning {\n int numSplats;\n int numBones;\n usampler2DArray skinTexture;\n sampler2D boneTexture;\n };\n"),Xr("\n void applyGsplatSkinning(\n int numSplats, int numBones,\n usampler2DArray skinTexture, sampler2D boneTexture,\n int splatIndex, inout vec3 center, inout vec4 quaternion\n ) {\n if ((splatIndex < 0) || (splatIndex >= numSplats)) {\n return;\n }\n\n uvec4 skinData = texelFetch(skinTexture, splatTexCoord(splatIndex), 0);\n\n float weights[4];\n weights[0] = float(skinData.x & 0xffu) / 255.0;\n weights[1] = float(skinData.y & 0xffu) / 255.0;\n weights[2] = float(skinData.z & 0xffu) / 255.0;\n weights[3] = float(skinData.w & 0xffu) / 255.0;\n\n uint boneIndices[4];\n boneIndices[0] = (skinData.x >> 8u) & 0xffu;\n boneIndices[1] = (skinData.y >> 8u) & 0xffu;\n boneIndices[2] = (skinData.z >> 8u) & 0xffu;\n boneIndices[3] = (skinData.w >> 8u) & 0xffu;\n\n vec4 quat = vec4(0.0);\n vec4 dual = vec4(0.0);\n for (int i = 0; i < 4; i++) {\n if (weights[i] > 0.0) {\n int boneIndex = int(boneIndices[i]);\n vec4 boneQuat = vec4(0.0, 0.0, 0.0, 1.0);\n vec4 boneDual = vec4(0.0);\n if (boneIndex < numBones) {\n boneQuat = texelFetch(boneTexture, ivec2(0, boneIndex), 0);\n boneDual = texelFetch(boneTexture, ivec2(1, boneIndex), 0);\n }\n\n if ((i > 0) && (dot(quat, boneQuat) < 0.0)) {\n // Flip sign if next blend is pointing in the opposite direction\n boneQuat = -boneQuat;\n boneDual = -boneDual;\n }\n quat += weights[i] * boneQuat;\n dual += weights[i] * boneDual;\n }\n }\n\n // Normalize dual quaternion\n float norm = length(quat);\n quat /= norm;\n dual /= norm;\n vec3 translate = vec3(\n 2.0 * (-dual.w * quat.x + dual.x * quat.w - dual.y * quat.z + dual.z * quat.y),\n 2.0 * (-dual.w * quat.y + dual.x * quat.z + dual.y * quat.w - dual.z * quat.x),\n 2.0 * (-dual.w * quat.z - dual.x * quat.y + dual.y * quat.x + dual.z * quat.w)\n );\n\n center = quatVec(quat, center) + translate;\n quaternion = quatQuat(quat, quaternion);\n }\n"),Xr("\n void applyCovSplatDQSkinning(\n int numSplats, int numBones,\n usampler2DArray skinTexture, sampler2D boneTexture,\n int splatIndex, inout vec3 center, inout vec3 xxyyzz, inout vec3 xyxzyz\n ) {\n if ((splatIndex < 0) || (splatIndex >= numSplats)) {\n return;\n }\n\n uvec4 skinData = texelFetch(skinTexture, splatTexCoord(splatIndex), 0);\n\n float weights[4];\n weights[0] = float(skinData.x & 0xffu) / 255.0;\n weights[1] = float(skinData.y & 0xffu) / 255.0;\n weights[2] = float(skinData.z & 0xffu) / 255.0;\n weights[3] = float(skinData.w & 0xffu) / 255.0;\n\n uint boneIndices[4];\n boneIndices[0] = (skinData.x >> 8u) & 0xffu;\n boneIndices[1] = (skinData.y >> 8u) & 0xffu;\n boneIndices[2] = (skinData.z >> 8u) & 0xffu;\n boneIndices[3] = (skinData.w >> 8u) & 0xffu;\n\n vec4 quat = vec4(0.0);\n vec4 dual = vec4(0.0);\n for (int i = 0; i < 4; i++) {\n if (weights[i] > 0.0) {\n int boneIndex = int(boneIndices[i]);\n vec4 boneQuat = vec4(0.0, 0.0, 0.0, 1.0);\n vec4 boneDual = vec4(0.0);\n if (boneIndex < numBones) {\n boneQuat = texelFetch(boneTexture, ivec2(0, boneIndex), 0);\n boneDual = texelFetch(boneTexture, ivec2(1, boneIndex), 0);\n }\n\n if ((i > 0) && (dot(quat, boneQuat) < 0.0)) {\n // Flip sign if next blend is pointing in the opposite direction\n boneQuat = -boneQuat;\n boneDual = -boneDual;\n }\n quat += weights[i] * boneQuat;\n dual += weights[i] * boneDual;\n }\n }\n\n // Normalize dual quaternion\n float norm = length(quat);\n quat /= norm;\n dual /= norm;\n vec3 translate = vec3(\n 2.0 * (-dual.w * quat.x + dual.x * quat.w - dual.y * quat.z + dual.z * quat.y),\n 2.0 * (-dual.w * quat.y + dual.x * quat.z + dual.y * quat.w - dual.z * quat.x),\n 2.0 * (-dual.w * quat.z - dual.x * quat.y + dual.y * quat.x + dual.z * quat.w)\n );\n mat3 basis = quaternionToMatrix(quat);\n\n center = quatVec(quat, center) + translate;\n\n mat3 cov = mat3(xxyyzz.x, xyxzyz.x, xyxzyz.y, xyxzyz.x, xxyyzz.y, xyxzyz.z, xyxzyz.y, xyxzyz.z, xxyyzz.z);\n cov = basis * cov * transpose(basis);\n xxyyzz = vec3(cov[0][0], cov[1][1], cov[2][2]);\n xyxzyz = vec3(cov[0][1], cov[0][2], cov[1][2]);\n }\n"),Xr("\n void applyCovSplatLBSkinning(\n int numSplats, int numBones,\n usampler2DArray skinTexture, sampler2D boneTexture,\n int splatIndex, inout vec3 center, inout vec3 xxyyzz, inout vec3 xyxzyz\n ) {\n if ((splatIndex < 0) || (splatIndex >= numSplats)) {\n return;\n }\n\n uvec4 skinData = texelFetch(skinTexture, splatTexCoord(splatIndex), 0);\n\n float weights[4];\n weights[0] = float(skinData.x & 0xffu) / 255.0;\n weights[1] = float(skinData.y & 0xffu) / 255.0;\n weights[2] = float(skinData.z & 0xffu) / 255.0;\n weights[3] = float(skinData.w & 0xffu) / 255.0;\n\n uint boneIndices[4];\n boneIndices[0] = (skinData.x >> 8u) & 0xffu;\n boneIndices[1] = (skinData.y >> 8u) & 0xffu;\n boneIndices[2] = (skinData.z >> 8u) & 0xffu;\n boneIndices[3] = (skinData.w >> 8u) & 0xffu;\n\n mat3 basis = mat3(0.0);\n vec3 offset = vec3(0.0);\n\n for (int i = 0; i < 4; i++) {\n if (weights[i] > 0.0) {\n int boneIndex = int(boneIndices[i]);\n if (boneIndex < numBones) {\n vec4 v0 = texelFetch(boneTexture, ivec2(0, boneIndex), 0);\n vec4 v1 = texelFetch(boneTexture, ivec2(1, boneIndex), 0);\n vec4 v2 = texelFetch(boneTexture, ivec2(2, boneIndex), 0);\n basis += weights[i] * mat3(v0.x, v0.y, v0.z, v0.w, v1.x, v1.y, v1.z, v1.w, v2.x);\n offset += weights[i] * vec3(v2.y, v2.z, v2.w);\n }\n }\n }\n\n center = basis * center + offset;\n\n mat3 cov = mat3(xxyyzz.x, xyxzyz.x, xyxzyz.y, xyxzyz.x, xxyyzz.y, xyxzyz.z, xyxzyz.y, xyxzyz.z, xxyyzz.z);\n cov = basis * cov * transpose(basis);\n xxyyzz = vec3(cov[0][0], cov[1][1], cov[2][2]);\n xyxzyz = vec3(cov[0][1], cov[0][2], cov[1][2]);\n }\n"),new r.Vector3(-1,-3,1).normalize(),new r.Color(1,1,1),new r.Color(.5,.5,1),new r.Color(1,1,1),new r.Color(.25,.25,.5);var Co=(e=>(e.w="wrist",e.t0="thumb-metacarpal",e.t1="thumb-phalanx-proximal",e.t2="thumb-phalanx-distal",e.t3="thumb-tip",e.i0="index-finger-metacarpal",e.i1="index-finger-phalanx-proximal",e.i2="index-finger-phalanx-intermediate",e.i3="index-finger-phalanx-distal",e.i4="index-finger-tip",e.m0="middle-finger-metacarpal",e.m1="middle-finger-phalanx-proximal",e.m2="middle-finger-phalanx-intermediate",e.m3="middle-finger-phalanx-distal",e.m4="middle-finger-tip",e.r0="ring-finger-metacarpal",e.r1="ring-finger-phalanx-proximal",e.r2="ring-finger-phalanx-intermediate",e.r3="ring-finger-phalanx-distal",e.r4="ring-finger-tip",e.p0="pinky-finger-metacarpal",e.p1="pinky-finger-phalanx-proximal",e.p2="pinky-finger-phalanx-intermediate",e.p3="pinky-finger-phalanx-distal",e.p4="pinky-finger-tip",e))(Co||{});Object.keys(Co).length;var Ro=(e=>(e.w="wrist",e.t0="thumb-metacarpal",e.t1="thumb-phalanx-proximal",e.t2="thumb-phalanx-distal",e.t3="thumb-tip",e.i0="index-finger-metacarpal",e.i1="index-finger-phalanx-proximal",e.i2="index-finger-phalanx-intermediate",e.i3="index-finger-phalanx-distal",e.i4="index-finger-tip",e.m0="middle-finger-metacarpal",e.m1="middle-finger-phalanx-proximal",e.m2="middle-finger-phalanx-intermediate",e.m3="middle-finger-phalanx-distal",e.m4="middle-finger-tip",e.r0="ring-finger-metacarpal",e.r1="ring-finger-phalanx-proximal",e.r2="ring-finger-phalanx-intermediate",e.r3="ring-finger-phalanx-distal",e.r4="ring-finger-tip",e.p0="pinky-finger-metacarpal",e.p1="pinky-finger-phalanx-proximal",e.p2="pinky-finger-phalanx-intermediate",e.p3="pinky-finger-phalanx-distal",e.p4="pinky-finger-tip",e))(Ro||{});Object.keys(Ro).length;class Do{constructor(){this.listeners={}}addEventListener(e,t){const n=this.listeners;void 0===n[e]&&(n[e]=[]),-1===n[e].indexOf(t)&&n[e].push(t)}hasEventListener(e,t){const n=this.listeners;return void 0!==n[e]&&-1!==n[e].indexOf(t)}removeEventListener(e,t){const n=this.listeners[e];if(void 0!==n){const e=n.indexOf(t);-1!==e&&n.splice(e,1)}}dispatchEvent(e){const t=this.listeners[e.type];if(void 0!==t){e.target=this;const n=t.slice(0);for(let t=0,r=n.length;t<r;t+=1)n[t].call(this,e)}}}function ko(e){return!(!e||"object"!=typeof e)&&0===Object.keys(e).length}function Io(e,t){if(e===t)return!0;if(null===e||"object"!=typeof e||null===t||"object"!=typeof t)return!1;const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let i of n)if(!r.includes(i)||!Io(e[i],t[i]))return!1;return!0}const Po="defined",Lo="updated",Uo="deleted";class Fo extends Do{constructor(e){super(),this.initialValues={},this.values={},this.define(e)}define(e={},t=!0){const n={};for(const r in e)if(Object.hasOwnProperty.call(e,r)){const i=e[r];Object.hasOwnProperty.call(this.initialValues,r)?t&&(this.initialValues[r]=i,this.values[r]=i,n[r]=i):(this.initialValues[r]=i,this.values[r]=i,n[r]=i)}return ko(n)||this.dispatchEvent({type:Po,values:n}),n}update(e={},t={}){let n={};const r={},i=t.force||!1,s=t.dryrun||!1;for(const a in e)if(Object.hasOwnProperty.call(e,a)){let t=e[a];Object.hasOwnProperty.call(this.initialValues,a)&&(void 0===t&&(t=this.initialValues[a]),Io(this.values[a],t)&&!i||(r[a]=this.values[a],s||(this.values[a]=t),n[a]=t))}return s||ko(n)||this.dispatchEvent({type:Lo,values:this.values,changes:n,before:r}),n}get(e){let t={};if(e){Array.isArray(e)||(e=[e]);for(let n=0;n<e.length;n++){const r=e[n];Object.hasOwnProperty.call(this.values,r)&&(t[r]=this.values[r])}}else t={...this.values};return 1==e.length?t[e[0]]:t}reset(e){const t={},n={};if(e){Array.isArray(e)||(e=[e]);for(let r=0;r<e.length;r++){const i=e[r];Object.hasOwnProperty.call(this.initialValues,i)&&(n[i]=this.values[i],this.values[i]=this.initialValues[i],t[i]=this.initialValues[i])}}else for(const r in this.initialValues)Object.hasOwnProperty.call(this.initialValues,r)&&(this.values[r]=this.initialValues[r],t[r]=this.initialValues[r]);return ko(t)||this.dispatchEvent({type:Lo,values:this.values,changes:t,before:n}),t}delete(e=[]){const t={};Array.isArray(e)||(e=[e]);for(let n=0;n<e.length;n++){const r=e[n];Object.hasOwnProperty.call(this.values,r)&&(t[r]=this.values[r],delete this.values[r],delete this.initialValues[r])}return ko(t)||this.dispatchEvent({type:Uo,deleted:t}),t}clone(){const e=new Fo(this.initialValues);return e.update(this.values),e}}new Fo;class zo extends r.Mesh{constructor(){super(new r.PlaneGeometry(0,0),new Bo),this.renderOrder=1/0}onBeforeRender(e){const t=this.material.uniforms;e.getSize(t.resolution.value)}updateMatrixWorld(){this.matrixWorld.makeTranslation(this.position)}dispose(){this.geometry.dispose(),this.material.dispose()}}class Bo extends r.ShaderMaterial{constructor(){super({depthWrite:!1,depthTest:!1,transparent:!0,uniforms:{resolution:{value:new r.Vector2},size:{value:15},thickness:{value:2},opacity:{value:1}},vertexShader:"\n\n\t\t\t\tuniform float size;\n\t\t\t\tuniform float thickness;\n\t\t\t\tuniform vec2 resolution;\n\t\t\t\tvarying vec2 vUv;\n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tvUv = uv;\n\n\t\t\t\t\tfloat aspect = resolution.x / resolution.y;\n\t\t\t\t\tvec2 offset = uv * 2.0 - vec2( 1.0 );\n\t\t\t\t\toffset.y *= aspect;\n\n\t\t\t\t\tvec4 screenPoint = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n\t\t\t\t\tscreenPoint.xy += offset * ( size + thickness ) * screenPoint.w / resolution.x;\n\n\t\t\t\t\tgl_Position = screenPoint;\n\n\t\t\t\t}\n\t\t\t",fragmentShader:"\n\n\t\t\t\tuniform float size;\n\t\t\t\tuniform float thickness;\n\t\t\t\tuniform float opacity;\n\n\t\t\t\tvarying vec2 vUv;\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tfloat ht = 0.5 * thickness;\n\t\t\t\t\tfloat planeDim = size + thickness;\n\t\t\t\t\tfloat offset = ( planeDim - ht - 2.0 ) / planeDim;\n\t\t\t\t\tfloat texelThickness = ht / planeDim;\n\n\t\t\t\t\tvec2 vec = vUv * 2.0 - vec2( 1.0 );\n\t\t\t\t\tfloat dist = abs( length( vec ) - offset );\n\t\t\t\t\tfloat fw = fwidth( dist ) * 0.5;\n\t\t\t\t\tfloat a = smoothstep( texelThickness - fw, texelThickness + fw, dist );\n\n\t\t\t\t\tgl_FragColor = vec4( 1, 1, 1, opacity * ( 1.0 - a ) );\n\n\t\t\t\t}\n\t\t\t"})}}const Vo=new r.Vector2,Oo=new r.Vector2;class No{constructor(){this.domElement=null,this.buttons=0,this.pointerType=null,this.pointerOrder=[],this.previousPositions={},this.pointerPositions={},this.startPositions={},this.pointerSetThisFrame={},this.hoverPosition=new r.Vector2,this.hoverSet=!1}reset(){this.buttons=0,this.pointerType=null,this.pointerOrder=[],this.previousPositions={},this.pointerPositions={},this.startPositions={},this.pointerSetThisFrame={},this.hoverPosition=new r.Vector2,this.hoverSet=!1}updateFrame(){const{previousPositions:e,pointerPositions:t}=this;for(const n in t)e[n].copy(t[n])}setHoverEvent(e){"mouse"!==e.pointerType&&"wheel"!==e.type||(this.getAdjustedPointer(e,this.hoverPosition),this.hoverSet=!0)}getLatestPoint(e){return null!==this.pointerType?(this.getCenterPoint(e),e):this.hoverSet?(e.copy(this.hoverPosition),e):null}getAdjustedPointer(e,t){const n=(this.domElement?this.domElement:e.target).getBoundingClientRect(),r=e.clientX-n.left,i=e.clientY-n.top;t.set(r,i)}addPointer(e){const t=e.pointerId,n=new r.Vector2;this.getAdjustedPointer(e,n),this.pointerOrder.push(t),this.pointerPositions[t]=n,this.previousPositions[t]=n.clone(),this.startPositions[t]=n.clone(),1===this.getPointerCount()&&(this.pointerType=e.pointerType,this.buttons=e.buttons)}updatePointer(e){const t=e.pointerId;return t in this.pointerPositions&&(this.getAdjustedPointer(e,this.pointerPositions[t]),!0)}deletePointer(e){const t=e.pointerId,n=this.pointerOrder;n.splice(n.indexOf(t),1),delete this.pointerPositions[t],delete this.previousPositions[t],delete this.startPositions[t],0===this.getPointerCount()&&(this.buttons=0,this.pointerType=null)}getPointerCount(){return this.pointerOrder.length}getCenterPoint(e,t=this.pointerPositions){const n=this.pointerOrder;if(1===this.getPointerCount()||"mouse"===this.getPointerType()){const r=n[0];return e.copy(t[r]),e}if(2===this.getPointerCount()){const n=this.pointerOrder[0],r=this.pointerOrder[1],i=t[n],s=t[r];return e.addVectors(i,s).multiplyScalar(.5),e}return null}getPreviousCenterPoint(e){return this.getCenterPoint(e,this.previousPositions)}getStartCenterPoint(e){return this.getCenterPoint(e,this.startPositions)}getMoveDistance(){return this.getCenterPoint(Vo),this.getPreviousCenterPoint(Oo),Vo.sub(Oo).length()}getTouchPointerDistance(e=this.pointerPositions){if(this.getPointerCount()<=1||"mouse"===this.getPointerType())return 0;const{pointerOrder:t}=this,n=t[0],r=t[1],i=e[n],s=e[r];return i.distanceTo(s)}getPreviousTouchPointerDistance(){return this.getTouchPointerDistance(this.previousPositions)}getStartTouchPointerDistance(){return this.getTouchPointerDistance(this.startPositions)}getPointerType(){return this.pointerType}isPointerTouch(){return"touch"===this.getPointerType()}getPointerButtons(){return this.buttons}isLeftClicked(){return Boolean(1&this.buttons)}isRightClicked(){return Boolean(2&this.buttons)}}const $o=new r.Matrix4;function Go(e,t,n){return n.makeTranslation(-e.x,-e.y,-e.z),$o.makeRotationFromQuaternion(t),n.premultiply($o),$o.makeTranslation(e.x,e.y,e.z),n.premultiply($o),n}function qo(e,t,n){n.x=e.x/t.clientWidth*2-1,n.y=-e.y/t.clientHeight*2+1,n.isVector3&&(n.z=0)}function Ho(e,t,n){const i=e instanceof r.Ray?e:e.ray,{origin:s,direction:a}=i;s.set(t.x,t.y,-1).unproject(n),a.set(t.x,t.y,1).unproject(n).sub(s),e.isRay||(e.near=0,e.far=a.length(),e.camera=n),a.normalize()}const jo=.05,Wo=.025,Xo=new r.Matrix4,Yo=new r.Matrix4,Ko=new r.Vector3,Qo=new r.Vector3,Zo=new r.Vector3,Jo=new r.Vector3,el=new r.Vector3,tl=new r.Vector3,nl=new r.Vector3,rl=new r.Vector3,il=new r.Quaternion,sl=new r.Plane,al=new r.Vector3,ol=new r.Vector3,ll=new r.Vector3,cl=new r.Quaternion,ul=new r.Ray,hl=new r.Vector2,dl=new r.Vector2,pl=new r.Vector2,ml=new r.Vector2,fl=new r.Vector2,gl=new r.Vector2,xl={type:"change"},yl={type:"start"},vl={type:"end"};class bl extends r.EventDispatcher{get enabled(){return this._enabled}set enabled(e){e!==this.enabled&&(this._enabled=e,this.resetState(),this.pointerTracker.reset(),this.enabled||(this.dragInertia.set(0,0,0),this.rotationInertia.set(0,0)))}constructor(e=null,t=null,n=null,i=null){super(),this.isEnvironmentControls=!0,this.domElement=null,this.camera=null,this.scene=null,this.tilesRenderer=null,this._enabled=!0,this.cameraRadius=5,this.rotationSpeed=1,this.minAltitude=0,this.maxAltitude=.45*Math.PI,this.minDistance=10,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.zoomSpeed=1,this.adjustHeight=!0,this.enableDamping=!1,this.dampingFactor=.15,this.fallbackPlane=new r.Plane(new r.Vector3(0,1,0),0),this.useFallbackPlane=!0,this.scaleZoomOrientationAtEdges=!1,this.autoAdjustCameraRotation=!0,this.state=0,this.pointerTracker=new No,this.needsUpdate=!1,this.actionHeightOffset=0,this.pivotPoint=new r.Vector3,this.zoomDirectionSet=!1,this.zoomPointSet=!1,this.zoomDirection=new r.Vector3,this.zoomPoint=new r.Vector3,this.zoomDelta=0,this.rotationInertiaPivot=new r.Vector3,this.rotationInertia=new r.Vector2,this.dragInertia=new r.Vector3,this.inertiaTargetDistance=1/0,this.inertiaStableFrames=0,this.pivotMesh=new zo,this.pivotMesh.raycast=()=>{},this.pivotMesh.scale.setScalar(.25),this.raycaster=new r.Raycaster,this.raycaster.firstHitOnly=!0,this.up=new r.Vector3(0,1,0),this.clock=new r.Clock,this._detachCallback=null,this._upInitialized=!1,this._lastUsedState=0,this._zoomPointWasSet=!1,this._tilesOnChangeCallback=()=>this.zoomPointSet=!1,n&&this.attach(n),t&&this.setCamera(t),e&&this.setScene(e),i&&this.setTilesRenderer(i)}setScene(e){this.scene=e}setCamera(e){this.camera=e,this._upInitialized=!1,this.zoomDirectionSet=!1,this.zoomPointSet=!1,this.needsUpdate=!0,this.raycaster.camera=e,this.resetState()}setTilesRenderer(e){this.tilesRenderer=e,null!==this.tilesRenderer&&this.setScene(this.tilesRenderer.group)}attach(e){if(this.domElement)throw new Error("EnvironmentControls: Controls already attached to element");this.domElement=e,this.pointerTracker.domElement=e,e.style.touchAction="none";const t=e=>{this.enabled&&e.preventDefault()},n=e=>{if(!this.enabled)return;e.preventDefault();const{camera:t,raycaster:n,domElement:r,up:i,pivotMesh:s,pointerTracker:a,scene:o,pivotPoint:l,enabled:c}=this;if(a.addPointer(e),this.needsUpdate=!0,a.isPointerTouch())if(s.visible=!1,0===a.getPointerCount())r.setPointerCapture(e.pointerId);else if(a.getPointerCount()>2)return void this.resetState();a.getCenterPoint(dl),qo(dl,r,dl),Ho(n,dl,t);const u=Math.abs(n.ray.direction.dot(i));if(u<jo||u<Wo)return;const h=this._raycast(n);h&&(2===a.getPointerCount()||a.isRightClicked()||a.isLeftClicked()&&e.shiftKey?(this.setState(a.isPointerTouch()?4:2),l.copy(h.point),s.position.copy(h.point),s.visible=!a.isPointerTouch()&&c,s.updateMatrixWorld(),o.add(s)):a.isLeftClicked()&&(this.setState(1),l.copy(h.point),s.position.copy(h.point),s.updateMatrixWorld(),o.add(s)))};let r=!1;const i=e=>{const{pointerTracker:t}=this;if(!this.enabled)return;e.preventDefault();const{pivotMesh:n,enabled:i}=this;this.zoomDirectionSet=!1,this.zoomPointSet=!1,0!==this.state&&(this.needsUpdate=!0),t.setHoverEvent(e),t.updatePointer(e)&&(t.isPointerTouch()&&2===t.getPointerCount()&&(r||(r=!0,queueMicrotask((()=>{r=!1,t.getCenterPoint(fl);const e=t.getStartTouchPointerDistance(),s=t.getTouchPointerDistance(),a=s-e;if(0===this.state||4===this.state){t.getCenterPoint(fl),t.getStartCenterPoint(gl);const e=2*window.devicePixelRatio,n=fl.distanceTo(gl);(Math.abs(a)>e||n>e)&&(Math.abs(a)>n?(this.setState(3),this.zoomDirectionSet=!1):this.setState(2))}if(3===this.state){const e=t.getPreviousTouchPointerDistance();this.zoomDelta+=s-e,n.visible=!1}else 2===this.state&&(n.visible=i)})))),this.dispatchEvent(xl))},s=t=>{const{pointerTracker:n}=this;this.enabled&&0!==n.getPointerCount()&&(n.deletePointer(t),"touch"===n.getPointerType()&&0===n.getPointerCount()&&e.releasePointerCapture(t.pointerId),this.resetState(),this.needsUpdate=!0)},a=e=>{if(!this.enabled)return;e.preventDefault();const{pointerTracker:t}=this;let n;switch(t.setHoverEvent(e),t.updatePointer(e),this.dispatchEvent(yl),e.deltaMode){case 2:n=800*e.deltaY;break;case 1:n=40*e.deltaY;break;case 0:n=e.deltaY}const r=Math.sign(n),i=Math.abs(n);this.zoomDelta-=.25*r*i,this.needsUpdate=!0,this._lastUsedState=3,this.dispatchEvent(vl)},o=e=>{this.enabled&&this.resetState()};e.addEventListener("contextmenu",t),e.addEventListener("pointerdown",n),e.addEventListener("wheel",a,{passive:!1});const l=e.getRootNode();l.addEventListener("pointermove",i),l.addEventListener("pointerup",s),l.addEventListener("pointerleave",o),this._detachCallback=()=>{e.removeEventListener("contextmenu",t),e.removeEventListener("pointerdown",n),e.removeEventListener("wheel",a),l.removeEventListener("pointermove",i),l.removeEventListener("pointerup",s),l.removeEventListener("pointerleave",o)}}detach(){this.domElement=null,this._detachCallback&&(this._detachCallback(),this._detachCallback=null,this.pointerTracker.reset())}getUpDirection(e,t){t.copy(this.up)}getCameraUpDirection(e){this.getUpDirection(this.camera.position,e)}getPivotPoint(e){let t=null;3===this._lastUsedState?this._zoomPointWasSet&&(t=e.copy(this.zoomPoint)):2!==this._lastUsedState&&1!==this._lastUsedState||(t=e.copy(this.pivotPoint));const{camera:n,raycaster:r}=this;null!==t&&(Qo.copy(t).project(n),(Qo.x<-1||Qo.x>1||Qo.y<-1||Qo.y>1)&&(t=null)),Ho(r,{x:0,y:0},n);const i=this._raycast(r);return i&&(null===t||i.distance<t.distanceTo(r.ray.origin))&&(t=e.copy(i.point)),t}resetState(){0!==this.state&&this.dispatchEvent(vl),this.state=0,this.pivotMesh.removeFromParent(),this.pivotMesh.visible=this.enabled,this.actionHeightOffset=0,this.pointerTracker.reset()}setState(e=this.state,t=!0){this.state!==e&&(0===this.state&&t&&this.dispatchEvent(yl),this.pivotMesh.visible=this.enabled,this.dragInertia.set(0,0,0),this.rotationInertia.set(0,0),this.inertiaStableFrames=0,this.state=e,0!==e&&4!==e&&(this._lastUsedState=e))}update(e=Math.min(this.clock.getDelta(),.064)){if(!this.enabled||!this.camera||0===e)return;const{camera:t,cameraRadius:n,pivotPoint:r,up:i,state:s,adjustHeight:a,autoAdjustCameraRotation:o}=this;t.updateMatrixWorld(),this.getCameraUpDirection(al),this._upInitialized||(this._upInitialized=!0,this.up.copy(al)),this.zoomPointSet=!1;const l=this._inertiaNeedsUpdate(),c=this.needsUpdate||l;if(this.needsUpdate||l){const n=this.zoomDelta;this._updateZoom(),this._updatePosition(e),this._updateRotation(e),1===s||2===s?(el.set(0,0,-1).transformDirection(t.matrixWorld),this.inertiaTargetDistance=Qo.copy(r).sub(t.position).dot(el)):0===s&&this._updateInertia(e),(0!==s||0!==n||l)&&this.dispatchEvent(xl),this.needsUpdate=!1}const u=t.isOrthographicCamera?null:a&&this._getPointBelowCamera()||null;if(this.getCameraUpDirection(al),this._setFrame(al),(1===this.state||2===this.state)&&0!==this.actionHeightOffset){const{actionHeightOffset:e}=this;t.position.addScaledVector(i,-e),r.addScaledVector(i,-e),u&&(u.distance-=e)}if(this.actionHeightOffset=0,u){const e=u.distance;if(e<n){const s=n-e;t.position.addScaledVector(i,s),r.addScaledVector(i,s),this.actionHeightOffset=s}}this.pointerTracker.updateFrame(),c&&o&&(this.getCameraUpDirection(al),this._alignCameraUp(al,1),this.getCameraUpDirection(al),this._clampRotation(al))}adjustCamera(e){const{adjustHeight:t,cameraRadius:n}=this;if(e.isPerspectiveCamera){this.getUpDirection(e.position,al);const r=t&&this._getPointBelowCamera(e.position,al)||null;if(r){const t=r.distance;t<n&&e.position.addScaledVector(al,n-t)}}}dispose(){this.detach()}_updateInertia(e){const{rotationInertia:t,pivotPoint:n,dragInertia:r,enableDamping:i,dampingFactor:s,camera:a,cameraRadius:o,minDistance:l,inertiaTargetDistance:c}=this;if(!this.enableDamping||this.inertiaStableFrames>1)return r.set(0,0,0),void t.set(0,0,0);const u=Math.pow(2,-e/s),h=Math.max(a.near,o,l,c),d=25e-5;if(t.lengthSq()>0){Ho(ul,Qo.set(0,0,-1),a),ul.applyMatrix4(a.matrixWorldInverse),ul.direction.normalize(),ul.recast(-ul.direction.dot(ul.origin)).at(h/ul.direction.z,Qo),Qo.applyMatrix4(a.matrixWorld),Ho(ul,Ko.set(d,d,-1),a),ul.applyMatrix4(a.matrixWorldInverse),ul.direction.normalize(),ul.recast(-ul.direction.dot(ul.origin)).at(h/ul.direction.z,Ko),Ko.applyMatrix4(a.matrixWorld),Qo.sub(n).normalize(),Ko.sub(n).normalize();const r=Qo.angleTo(Ko)/e;t.multiplyScalar(u),(t.lengthSq()<r**2||!i)&&t.set(0,0)}if(r.lengthSq()>0){Ho(ul,Qo.set(0,0,-1),a),ul.applyMatrix4(a.matrixWorldInverse),ul.direction.normalize(),ul.recast(-ul.direction.dot(ul.origin)).at(h/ul.direction.z,Qo),Qo.applyMatrix4(a.matrixWorld),Ho(ul,Ko.set(d,d,-1),a),ul.applyMatrix4(a.matrixWorldInverse),ul.direction.normalize(),ul.recast(-ul.direction.dot(ul.origin)).at(h/ul.direction.z,Ko),Ko.applyMatrix4(a.matrixWorld);const t=Qo.distanceTo(Ko)/e;r.multiplyScalar(u),(r.lengthSq()<t**2||!i)&&r.set(0,0,0)}t.lengthSq()>0&&this._applyRotation(t.x*e,t.y*e,n),r.lengthSq()>0&&(a.position.addScaledVector(r,e),a.updateMatrixWorld())}_inertiaNeedsUpdate(){const{rotationInertia:e,dragInertia:t}=this;return 0!==e.lengthSq()||0!==t.lengthSq()}_updateZoom(){const{zoomPoint:e,zoomDirection:t,camera:n,minDistance:r,maxDistance:i,pointerTracker:s,domElement:a,minZoom:o,maxZoom:l,zoomSpeed:c,state:u}=this;let h=this.zoomDelta;if(this.zoomDelta=0,s.getLatestPoint(dl)&&(0!==h||3===u))if(this.rotationInertia.set(0,0),this.dragInertia.set(0,0,0),n.isOrthographicCamera){this._updateZoomDirection();const e=this.zoomPointSet||this._updateZoomPoint();ol.unproject(n);const t=Math.pow(.95,Math.abs(.05*h));let r=h>0?1/Math.abs(t):t;r*=c,r>1?l<n.zoom*r&&(r=1):o>n.zoom*r&&(r=1),n.zoom*=r,n.updateProjectionMatrix(),e&&(qo(dl,a,ll),ll.unproject(n),n.position.sub(ll).add(ol),n.updateMatrixWorld())}else{this._updateZoomDirection();const s=Qo.copy(t);if(this.zoomPointSet||this._updateZoomPoint()){const s=e.distanceTo(n.position);if(h<0){const e=Math.min(0,s-i);h=h*s*c*.0025,h=Math.max(h,e)}else{const e=Math.max(0,s-r);h=h*Math.max(s-r,0)*c*.0025,h=Math.min(h,e)}n.position.addScaledVector(t,h),n.updateMatrixWorld()}else{const e=this._getPointBelowCamera();if(e){const t=e.distance;s.set(0,0,-1).transformDirection(n.matrixWorld),n.position.addScaledVector(s,h*t*.01),n.updateMatrixWorld()}}}}_updateZoomDirection(){if(this.zoomDirectionSet)return;const{domElement:e,raycaster:t,camera:n,zoomDirection:r,pointerTracker:i}=this;i.getLatestPoint(dl),qo(dl,e,ol),Ho(t,ol,n),r.copy(t.ray.direction).normalize(),this.zoomDirectionSet=!0}_updateZoomPoint(){const{camera:e,zoomDirectionSet:t,zoomDirection:n,raycaster:r,zoomPoint:i,pointerTracker:s,domElement:a}=this;if(this._zoomPointWasSet=!1,!t)return!1;e.isOrthographicCamera&&s.getLatestPoint(hl)?(qo(hl,a,hl),Ho(r,hl,e)):(r.ray.origin.copy(e.position),r.ray.direction.copy(n),r.near=0,r.far=1/0);const o=this._raycast(r);return!!o&&(i.copy(o.point),this.zoomPointSet=!0,this._zoomPointWasSet=!0,!0)}_getPointBelowCamera(e=this.camera.position,t=this.up){const{raycaster:n}=this;n.ray.direction.copy(t).multiplyScalar(-1),n.ray.origin.copy(e).addScaledVector(t,1e5),n.near=0,n.far=1/0;const r=this._raycast(n);return r&&(r.distance-=1e5),r}_updatePosition(e){const{raycaster:t,camera:n,pivotPoint:r,up:i,pointerTracker:s,domElement:a,state:o,dragInertia:l}=this;if(1===o){if(s.getCenterPoint(dl),qo(dl,a,dl),sl.setFromNormalAndCoplanarPoint(i,r),Ho(t,dl,n),Math.abs(t.ray.direction.dot(i))<jo){const e=Math.acos(jo);rl.crossVectors(t.ray.direction,i).normalize(),t.ray.direction.copy(i).applyAxisAngle(rl,e).multiplyScalar(-1)}if(this.getUpDirection(r,al),Math.abs(t.ray.direction.dot(al))<Wo){const e=Math.acos(Wo);rl.crossVectors(t.ray.direction,al).normalize(),t.ray.direction.copy(al).applyAxisAngle(rl,e).multiplyScalar(-1)}t.ray.intersectPlane(sl,Qo)&&(Ko.subVectors(r,Qo),n.position.add(Ko),n.updateMatrixWorld(),Ko.multiplyScalar(1/e),s.getMoveDistance()/e<2*window.devicePixelRatio?this.inertiaStableFrames++:(l.copy(Ko),this.inertiaStableFrames=0))}}_updateRotation(e){const{pivotPoint:t,pointerTracker:n,domElement:r,state:i,rotationInertia:s}=this;2===i&&(n.getCenterPoint(dl),n.getPreviousCenterPoint(pl),ml.subVectors(dl,pl).multiplyScalar(2*Math.PI/r.clientHeight),this._applyRotation(ml.x,ml.y,t),ml.multiplyScalar(1/e),n.getMoveDistance()/e<2*window.devicePixelRatio?this.inertiaStableFrames++:(s.copy(ml),this.inertiaStableFrames=0))}_applyRotation(e,t,n){if(0===e&&0===t)return;const{camera:r,minAltitude:i,maxAltitude:s,rotationSpeed:a}=this,o=-e*a;let l,c=t*a;if(el.set(0,0,1).transformDirection(r.matrixWorld),tl.set(1,0,0).transformDirection(r.matrixWorld),this.getUpDirection(n,al),al.dot(el)>1-1e-10)l=0;else{Qo.crossVectors(al,el).normalize();l=Math.sign(Qo.dot(tl))*al.angleTo(el)}c>0?(c=Math.min(l-i,c),c=Math.max(0,c)):(c=Math.max(l-s,c),c=Math.min(0,c)),il.setFromAxisAngle(al,o),Go(n,il,Xo),r.matrixWorld.premultiply(Xo),tl.set(1,0,0).transformDirection(r.matrixWorld),il.setFromAxisAngle(tl,-c),Go(n,il,Xo),r.matrixWorld.premultiply(Xo),r.matrixWorld.decompose(r.position,r.quaternion,Qo)}_setFrame(e){const{up:t,camera:n,zoomPoint:i,zoomDirectionSet:s,zoomPointSet:a,scaleZoomOrientationAtEdges:o}=this;if(s&&(a||this._updateZoomPoint())){if(il.setFromUnitVectors(t,e),o){this.getUpDirection(i,Qo);let e=Math.max(Qo.dot(t)-.6,0)/.4;e=r.MathUtils.mapLinear(e,0,.5,0,1),e=Math.min(e,1),n.isOrthographicCamera&&(e*=.1),il.slerp(cl,1-e)}Go(i,il,Xo),n.updateMatrixWorld(),n.matrixWorld.premultiply(Xo),n.matrixWorld.decompose(n.position,n.quaternion,Qo),this.zoomDirectionSet=!1,this._updateZoomDirection()}t.copy(e),n.updateMatrixWorld()}_raycast(e){const{scene:t,useFallbackPlane:n,fallbackPlane:r}=this,i=e.intersectObject(t)[0]||null;if(i)return i;if(n){const t=r;if(e.ray.intersectPlane(t,Qo)){return{point:Qo.clone(),distance:e.ray.origin.distanceTo(Qo)}}}return null}_alignCameraUp(e,t=1){const{camera:n,state:i,pivotPoint:s,zoomPoint:a,zoomPointSet:o}=this;n.updateMatrixWorld(),el.set(0,0,-1).transformDirection(n.matrixWorld),tl.set(-1,0,0).transformDirection(n.matrixWorld);let l=r.MathUtils.mapLinear(1-Math.abs(el.dot(e)),0,.2,0,1);l=r.MathUtils.clamp(l,0,1),t*=l,nl.crossVectors(e,el),nl.lerp(tl,1-t).normalize(),il.setFromUnitVectors(tl,nl),n.quaternion.premultiply(il);let c=null;1===i||2===i?c=Zo.copy(s):o&&(c=Zo.copy(a)),c&&(Yo.copy(n.matrixWorld).invert(),Qo.copy(c).applyMatrix4(Yo),n.updateMatrixWorld(),Qo.applyMatrix4(n.matrixWorld),Jo.subVectors(c,Qo),n.position.add(Jo)),n.updateMatrixWorld()}_clampRotation(e){const{camera:t,minAltitude:n,maxAltitude:r,state:i,pivotPoint:s,zoomPoint:a,zoomPointSet:o}=this;let l,c;if(t.updateMatrixWorld(),el.set(0,0,1).transformDirection(t.matrixWorld),tl.set(1,0,0).transformDirection(t.matrixWorld),e.dot(el)>1-1e-10)l=0;else{Qo.crossVectors(e,el);l=Math.sign(Qo.dot(tl))*e.angleTo(el)}if(l>r)c=r;else{if(!(l<n))return;c=n}el.copy(e),il.setFromAxisAngle(tl,c),el.applyQuaternion(il).normalize(),Qo.crossVectors(el,tl).normalize(),Xo.makeBasis(tl,Qo,el),t.quaternion.setFromRotationMatrix(Xo);let u=null;1===i||2===i?u=Zo.copy(s):o&&(u=Zo.copy(a)),u&&(Yo.copy(t.matrixWorld).invert(),Qo.copy(u).applyMatrix4(Yo),t.updateMatrixWorld(),Qo.applyMatrix4(t.matrixWorld),Jo.subVectors(u,Qo),t.position.add(Jo)),t.updateMatrixWorld()}}const wl=new r.Spherical,Tl=new r.Vector3,Sl=new r.Vector3,_l=new r.Vector3,Ml=new r.Matrix4,Al=new r.Matrix4,El=new r.Sphere,Cl=new r.Euler,Rl=new r.Vector3,Dl=new r.Vector3,kl=new r.Vector3,Il=new r.Vector3,Pl=new r.Ray;class Ll{constructor(e=1,t=1,n=1){this.name="",this.radius=new r.Vector3(e,t,n)}intersectRay(e,t){return Ml.makeScale(...this.radius).invert(),El.center.set(0,0,0),El.radius=1,Pl.copy(e).applyMatrix4(Ml),Pl.intersectSphere(El,t)?(Ml.makeScale(...this.radius),t.applyMatrix4(Ml),t):null}getEastNorthUpFrame(e,t,n,r){return n.isMatrix4&&(r=n,n=0),this.getEastNorthUpAxes(e,t,Rl,Dl,kl),this.getCartographicToPosition(e,t,n,Il),r.makeBasis(Rl,Dl,kl).setPosition(Il)}getOrientedEastNorthUpFrame(e,t,n,r,i,s,a){return this.getObjectFrame(e,t,n,r,i,s,a,0)}getObjectFrame(e,t,n,r,i,s,a,o=2){return this.getEastNorthUpFrame(e,t,n,Ml),Cl.set(i,s,-r,"ZXY"),a.makeRotationFromEuler(Cl).premultiply(Ml),1===o?(Cl.set(Math.PI/2,0,0,"XYZ"),Al.makeRotationFromEuler(Cl),a.multiply(Al)):2===o&&(Cl.set(-Math.PI/2,0,Math.PI,"XYZ"),Al.makeRotationFromEuler(Cl),a.multiply(Al)),a}getCartographicFromObjectFrame(e,t,n=2){return 1===n?(Cl.set(-Math.PI/2,0,0,"XYZ"),Al.makeRotationFromEuler(Cl).premultiply(e)):2===n?(Cl.set(-Math.PI/2,0,Math.PI,"XYZ"),Al.makeRotationFromEuler(Cl).premultiply(e)):Al.copy(e),Il.setFromMatrixPosition(Al),this.getPositionToCartographic(Il,t),this.getEastNorthUpFrame(t.lat,t.lon,0,Ml).invert(),Al.premultiply(Ml),Cl.setFromRotationMatrix(Al,"ZXY"),t.azimuth=-Cl.z,t.elevation=Cl.x,t.roll=Cl.y,t}getEastNorthUpAxes(e,t,n,r,i,s=Il){this.getCartographicToPosition(e,t,0,s),this.getCartographicToNormal(e,t,i),n.set(-s.y,s.x,0).normalize(),r.crossVectors(i,n).normalize()}getCartographicToPosition(e,t,n,r){this.getCartographicToNormal(e,t,Tl);const i=this.radius;Sl.copy(Tl),Sl.x*=i.x**2,Sl.y*=i.y**2,Sl.z*=i.z**2;const s=Math.sqrt(Tl.dot(Sl));return Sl.divideScalar(s),r.copy(Sl).addScaledVector(Tl,n)}getPositionToCartographic(e,t){this.getPositionToSurfacePoint(e,Sl),this.getPositionToNormal(Sl,Tl);const n=_l.subVectors(e,Sl);return t.lon=Math.atan2(Tl.y,Tl.x),t.lat=Math.asin(Tl.z),t.height=Math.sign(n.dot(e))*n.length(),t}getCartographicToNormal(e,t,n){return wl.set(1,-e+Math.PI/2,t),n.setFromSpherical(wl).normalize(),function(e){const{x:t,y:n,z:r}=e;e.x=r,e.y=t,e.z=n}(n),n}getPositionToNormal(e,t){const n=this.radius;return t.copy(e),t.x/=n.x**2,t.y/=n.y**2,t.z/=n.z**2,t.normalize(),t}getPositionToSurfacePoint(e,t){const n=this.radius,r=1/n.x**2,i=1/n.y**2,s=1/n.z**2,a=e.x*e.x*r,o=e.y*e.y*i,l=e.z*e.z*s,c=a+o+l,u=Math.sqrt(1/c),h=Sl.copy(e).multiplyScalar(u);if(c<.1)return isFinite(u)?t.copy(h):null;const d=_l.set(h.x*r*2,h.y*i*2,h.z*s*2);let p,m,f,g,x,y,v,b,w,T,S,_=(1-u)*e.length()/(.5*d.length()),M=0;do{_-=M,f=1/(1+_*r),g=1/(1+_*i),x=1/(1+_*s),y=f*f,v=g*g,b=x*x,w=y*f,T=v*g,S=b*x,p=a*y+o*v+l*b-1,m=a*w*r+o*T*i+l*S*s;M=p/(-2*m)}while(Math.abs(p)>1e-12);return t.set(e.x*f,e.y*g,e.z*x)}calculateHorizonDistance(e,t){const n=this.calculateEffectiveRadius(e);return Math.sqrt(2*n*t+t**2)}calculateEffectiveRadius(e){const t=this.radius.x,n=1-this.radius.z**2/t**2,i=e*r.MathUtils.DEG2RAD,s=Math.sin(i)**2;return t/Math.sqrt(1-n*s)}getPositionElevation(e){this.getPositionToSurfacePoint(e,Sl);const t=_l.subVectors(e,Sl);return Math.sign(t.dot(e))*t.length()}closestPointToRayEstimate(e,t){return this.intersectRay(e,t)?t:(Ml.makeScale(...this.radius).invert(),Pl.copy(e).applyMatrix4(Ml),Sl.set(0,0,0),Pl.closestPointToPoint(Sl,t).normalize(),Ml.makeScale(...this.radius),t.applyMatrix4(Ml))}copy(e){return this.radius.copy(e.radius),this}clone(){return(new this.constructor).copy(this)}}function Ul(e){if(!e)return null;let t=e.length,n=e.indexOf("?"),r=e.indexOf("#");-1!==n&&(t=Math.min(t,n)),-1!==r&&(t=Math.min(t,r));let i=e.lastIndexOf(".",t),s=e.lastIndexOf("/",t),a=e.indexOf("://");return-1!==a&&a+2===s||-1===i||i<s?null:e.substring(i+1,t)||null}var Fl=(n(e=class{static setXRSession(e){e!==this.session&&(this.flushPending(),this.session=e)}static requestAnimationFrame(e){let t,{session:n,pending:r}=this,i=()=>{r.delete(t),e()};return t=n?n.requestAnimationFrame(i):requestAnimationFrame(i),r.set(t,e),t}static cancelAnimationFrame(e){let{pending:t,session:n}=this;t.delete(e),n?n.cancelAnimationFrame(e):cancelAnimationFrame(e)}static flushPending(){this.pending.forEach(((e,t)=>{e(),this.cancelAnimationFrame(t)}))}},"pending",new Map),n(e,"session",null),e),zl=2**30,Bl=class{get unloadPriorityCallback(){return this._unloadPriorityCallback}set unloadPriorityCallback(e){1===e.length?this._unloadPriorityCallback=(t,n)=>{let r=e(t),i=e(n);return r<i?-1:+(r>i)}:this._unloadPriorityCallback=e}constructor(){this.minSize=6e3,this.maxSize=8e3,this.minBytesSize=.3*zl,this.maxBytesSize=.4*zl,this.unloadPercent=.05,this.autoMarkUnused=!0,this.itemSet=new Map,this.itemList=[],this.usedSet=new Set,this.callbacks=new Map,this.unloadingHandle=-1,this.cachedBytes=0,this.bytesMap=new Map,this.loadedSet=new Set,this._unloadPriorityCallback=null;let e=this.itemSet;this.defaultPriorityCallback=t=>e.get(t)}isFull(){return this.itemSet.size>=this.maxSize||this.cachedBytes>=this.maxBytesSize}getMemoryUsage(e){return this.bytesMap.get(e)||0}setMemoryUsage(e,t){let{bytesMap:n,itemSet:r}=this;r.has(e)&&(this.cachedBytes-=n.get(e)||0,n.set(e,t),this.cachedBytes+=t)}add(e,t){let n=this.itemSet;if(n.has(e)||this.isFull())return!1;let r=this.usedSet,i=this.itemList,s=this.callbacks;return i.push(e),r.add(e),n.set(e,Date.now()),s.set(e,t),!0}has(e){return this.itemSet.has(e)}remove(e){let t=this.usedSet,n=this.itemSet,r=this.itemList,i=this.bytesMap,s=this.callbacks,a=this.loadedSet;if(n.has(e)){this.cachedBytes-=i.get(e)||0,i.delete(e),s.get(e)(e);let o=r.indexOf(e);return r.splice(o,1),t.delete(e),n.delete(e),s.delete(e),a.delete(e),!0}return!1}setLoaded(e,t){let{itemSet:n,loadedSet:r}=this;n.has(e)&&(!0===t?r.add(e):r.delete(e))}markUsed(e){let t=this.itemSet,n=this.usedSet;t.has(e)&&!n.has(e)&&(t.set(e,Date.now()),n.add(e))}markUnused(e){this.usedSet.delete(e)}markAllUnused(){this.usedSet.clear()}isUsed(e){return this.usedSet.has(e)}unloadUnusedContent(){let{unloadPercent:e,minSize:t,maxSize:n,itemList:r,itemSet:i,usedSet:s,loadedSet:a,callbacks:o,bytesMap:l,minBytesSize:c,maxBytesSize:u}=this,h=r.length-s.size,d=r.length-a.size,p=Math.max(Math.min(r.length-t,h),0),m=this.cachedBytes-c,f=this.unloadPriorityCallback||this.defaultPriorityCallback,g=!1,x=p>0&&h>0||d&&r.length>n;if(h&&this.cachedBytes>c||d&&this.cachedBytes>u||x){r.sort(((e,t)=>{let n=s.has(e);if(n===s.has(t)){let n=a.has(e);return n===a.has(t)?-f(e,t):n?1:-1}return n?1:-1}));let d=Math.max(t*e,p*e),x=Math.ceil(Math.min(d,h,p)),y=Math.max(e*m,e*c),v=Math.min(y,m),b=0,w=0;for(;this.cachedBytes-w>u||r.length-b>n;){let e=r[b],t=l.get(e)||0;if(s.has(e)&&a.has(e)||this.cachedBytes-w-t<u&&r.length-b<=n)break;w+=t,b++}for(;w<v||b<x;){let e=r[b],t=l.get(e)||0;if(s.has(e)||this.cachedBytes-w-t<c&&b>=x)break;w+=t,b++}r.splice(0,b).forEach((e=>{this.cachedBytes-=l.get(e)||0,o.get(e)(e),l.delete(e),i.delete(e),o.delete(e),a.delete(e),s.delete(e)})),g=b<p||w<m&&b<h,g&&(g=b>0)}g&&(this.unloadingHandle=Fl.requestAnimationFrame((()=>this.scheduleUnload())))}scheduleUnload(){Fl.cancelAnimationFrame(this.unloadingHandle),this.scheduled||(this.scheduled=!0,queueMicrotask((()=>{this.scheduled=!1,this.unloadUnusedContent()})))}},Vl=class extends DOMException{constructor(){super("PriorityQueue: Item removed","AbortError")}},Ol=class{get running(){return 0!==this.items.length||0!==this.currJobs}constructor(){this.maxJobs=6,this.items=[],this.callbacks=new Map,this.currJobs=0,this.scheduled=!1,this.autoUpdate=!0,this.priorityCallback=null,this._schedulingCallback=e=>{Fl.requestAnimationFrame(e)},this._runjobs=()=>{this.scheduled=!1,this.tryRunJobs()}}sort(){let e=this.priorityCallback,t=this.items;null!==e&&t.sort(e)}has(e){return this.callbacks.has(e)}add(e,t){let n={callback:t,reject:null,resolve:null,promise:null};return n.promise=new Promise(((t,r)=>{let i=this.items,s=this.callbacks;n.resolve=t,n.reject=r,i.unshift(e),s.set(e,n),this.autoUpdate&&this.scheduleJobRun()})),n.promise}remove(e){let t=this.items,n=this.callbacks,r=t.indexOf(e);if(-1!==r){let i=n.get(e);i.promise.catch((e=>{if("AbortError"!==e.name)throw e})),i.reject(new Vl),t.splice(r,1),n.delete(e)}}removeByFilter(e){let{items:t}=this;for(let n=0;n<t.length;n++){let r=t[n];e(r)&&(this.remove(r),n--)}}tryRunJobs(){this.sort();let e=this.items,t=this.callbacks,n=this.maxJobs,r=0,i=()=>{this.currJobs--,this.autoUpdate&&this.scheduleJobRun()};for(;n>this.currJobs&&e.length>0&&r<n;){this.currJobs++,r++;let n,a=e.pop(),{callback:o,resolve:l,reject:c}=t.get(a);t.delete(a);try{n=o(a)}catch(s){c(s),i()}n instanceof Promise?n.then(l).catch(c).finally(i):(l(n),i())}}flush(e){let{items:t,callbacks:n}=this,r=t.indexOf(e);if(!n.has(e))return;let i,{callback:s,resolve:a,reject:o}=n.get(e);n.delete(e),t.splice(r,1);try{i=s(e)}catch(l){return void o(l)}return i instanceof Promise?i.then(a).catch(o):a(i),i}scheduleJobRun(){this.scheduled||(this.scheduled=(this._schedulingCallback(this._runjobs),!0))}},Nl=6378137,$l=6356752.314245179,Gl={inView:!1,error:1/0,distanceFromCamera:1/0};function ql(e){return 4===e||-1===e}function Hl(e,t){return jl(e)&&e.traversal.lastFrameVisited===t&&e.traversal.used}function jl(e){return!!e.traversal}function Wl(e){let{children:t}=e,n=0===t.length||jl(t[t.length-1]),r=!e.internal.hasUnrenderableContent||ql(e.internal.loadingState);return n&&r}function Xl(e){return e.traversal.unconditionallyRefine}function Yl(e,t){if(jl(e)&&(t.ensureChildrenArePreprocessed(e),e.traversal.lastFrameVisited!==t.frameCount&&(e.traversal.wasInFrustum=e.traversal.inFrustum,e.traversal.wasSetActive=e.traversal.active,e.traversal.wasSetVisible=e.traversal.visible,e.traversal.usedLastFrame=e.traversal.used,e.traversal.lastFrameVisited=t.frameCount,e.traversal.used=!1,e.traversal.inFrustum=!1,e.traversal.isLeaf=!1,e.traversal.visible=!1,e.traversal.active=!1,e.traversal.error=1/0,e.traversal.distanceFromCamera=1/0,e.traversal.allChildrenReady=!1,e.traversal.allChildrenLoaded=!1,e.traversal.kicked=!1,e.traversal.allUsedChildrenProcessed=!1,t.calculateTileViewErrorWithPlugin(e,Gl),e.traversal.inFrustum=Gl.inView,e.traversal.error=Gl.error,e.traversal.distanceFromCamera=Gl.distanceFromCamera,e.traversal.unconditionallyRefine=e.internal.hasUnrenderableContent,!e.traversal.unconditionallyRefine))){let t=e.parent;for(;t&&t.traversal.unconditionallyRefine;)t=t.parent;t&&t.geometricError<=e.geometricError&&(e.traversal.unconditionallyRefine=!0)}}function Kl(e,t,n=!1){if(Yl(e,t),n?t.markTileUsed(e):Zl(e),Xl(e)&&Wl(e)){let r=e.children;for(let e=0,i=r.length;e<i;e++)Kl(r[e],t,n)}}function Ql(e,t){if(Yl(e,t),e.traversal.usedLastFrame&&(Zl(e),e.traversal.wasSetActive&&(e.traversal.active=!0),(!e.traversal.active||Xl(e))&&Wl(e))){let n=e.children;for(let e=0,r=n.length;e<r;e++)Ql(n[e],t)}}function Zl(e){e.traversal.used=!0}function Jl(e,t){let{frameCount:n}=t,{children:r}=e;for(let i=0,s=r.length;i<s;i++){let e=r[i];Hl(e,n)&&(e.traversal.active&&(e.traversal.kicked=!0,e.traversal.active=!1),Jl(e,t))}}function ec(e){return!Xl(e)&&(!e.internal.hasContent||ql(e.internal.loadingState))}function tc(e,t){if(Yl(e,t),!e.traversal.inFrustum)return;let n=e.parent;if(n&&"ADD"===n.refine&&e.geometricError>0&&e.traversal.error*(n.geometricError/e.geometricError)<=t.errorTarget)return;if(!function(e,t){return!(e.traversal.error<=t.errorTarget&&!Xl(e)||t.maxDepth>0&&e.internal.depth+1>=t.maxDepth||!Wl(e))}(e,t))return void Zl(e);let r=!1,i=!1,s=e.children;for(let a=0,o=s.length;a<o;a++){let e=s[a];tc(e,t),r||(r=Hl(e,t.frameCount)),i||(i=e.traversal.inFrustum)}if("REPLACE"!==e.refine||i||0===s.length){if(Zl(e),"REPLACE"===e.refine&&r&&(t.loadSiblings||t.loadAncestors))for(let a=0,o=s.length;a<o;a++)Kl(s[a],t)}else{e.traversal.inFrustum=!1,t.markTileUsed(e);for(let e=0,n=s.length;e<n;e++)Kl(s[e],t,!0)}}function nc(e,t){let n=t.frameCount;if(!Hl(e,n))return;let r=e.children,i=!1;for(let a=0,o=r.length;a<o;a++){let e=r[a];i||(i=Hl(e,n))}if(i){for(let e=0,n=r.length;e<n;e++)nc(r[e],t);let i=!0;for(let e=0,t=r.length;e<t;e++){let t=r[e];if(Hl(t,n)){let e=!Xl(t),n=!t.internal.hasContent||ql(t.internal.loadingState);e&&n||t.traversal.allChildrenLoaded||(i=!1)}}e.traversal.allChildrenLoaded=i}else e.traversal.isLeaf=!0;let s=!0;for(let a=0,o=r.length;a<o;a++){let e=r[a];Hl(e,t.frameCount)&&!e.traversal.allUsedChildrenProcessed&&(s=!1)}e.traversal.allUsedChildrenProcessed=s&&Wl(e)}function rc(e,t){if(!Hl(e,t.frameCount))return;let n=e.children;if("REPLACE"===e.refine&&t.loadAncestors&&!e.traversal.allChildrenLoaded&&!Xl(e)&&(e.traversal.isLeaf=!0),e.traversal.isLeaf){if(!Xl(e)&&(e.traversal.active=!0,Wl(e)&&e.internal.hasContent&&!ql(e.internal.loadingState)))for(let e=0,r=n.length;e<r;e++)Ql(n[e],t);return}let r=n.length>0;for(let i=0,s=n.length;i<s;i++){let e=n[i];rc(e,t),Hl(e,t.frameCount)&&(!e.traversal.active||!ec(e))&&!e.traversal.allChildrenReady&&(r=!1)}e.traversal.allChildrenReady=r,"REPLACE"===e.refine&&!r&&e.traversal.wasSetActive&&ec(e)&&(e.traversal.active=!0,Jl(e,t))}function ic(e,t){Yl(e,t);let n=Hl(e,t.frameCount);if(n&&(e.internal.hasUnrenderableContent&&(t.markTileUsed(e),t.queueTileForDownload(e)),e.internal.hasRenderableContent&&"ADD"===e.refine&&(e.traversal.active=!0),(e.traversal.active||e.traversal.kicked)&&e.internal.hasContent&&(t.markTileUsed(e),e.traversal.allUsedChildrenProcessed&&t.queueTileForDownload(e),4!==e.internal.loadingState&&(e.traversal.active=!1)),t.loadAncestors&&e.internal.hasContent&&(t.markTileUsed(e),t.queueTileForDownload(e)),e.internal.virtualChildCount>0&&e.internal.hasContent&&t.markTileUsed(e),e.traversal.visible=e.internal.hasRenderableContent&&e.traversal.active&&e.traversal.inFrustum&&4===e.internal.loadingState,t.stats.used++,e.traversal.inFrustum&&t.stats.inFrustum++),n||jl(e)&&e.traversal.usedLastFrame){let r=!1,i=!1;n?(r=e.traversal.active,i=t.displayActiveTiles&&e.traversal.active||e.traversal.visible):Yl(e,t),e.internal.hasRenderableContent&&4===e.internal.loadingState?(r&&t.stats.active++,i&&t.stats.visible++,e.traversal.wasSetActive!==r&&t.invokeOnePlugin((t=>t.setTileActive&&t.setTileActive(e,r))),e.traversal.wasSetVisible!==i&&t.invokeOnePlugin((t=>t.setTileVisible&&t.setTileVisible(e,i)))):e.internal.hasRenderableContent||(i=e.traversal.isLeaf,e.traversal.wasSetVisible!==i&&t.invokeOnePlugin((t=>t.setEmptyTileVisible&&t.setEmptyTileVisible(e,i)))),e.traversal.visible=i,e.traversal.active=r;let s=e.children;for(let e=0,n=s.length;e<n;e++){ic(s[e],t)}}}function sc(e,t){tc(e,t),nc(e,t),rc(e,t),ic(e,t)}function ac(e,t=null,n=null){let r=[];for(r.push(e),r.push(null),r.push(0);r.length>0;){let e=r.pop(),i=r.pop(),s=r.pop();if(t&&t(s,i,e))return void(n&&n(s,i,e));let a=s.children;if(a)for(let t=a.length-1;t>=0;t--)r.push(a[t]),r.push(s),r.push(e+1);n&&n(s,i,e)}}var oc=Symbol("PLUGIN_REGISTERED"),lc={inView:!0,error:0,distance:1/0},cc=(e,t)=>{let n=e.priority??1/0,r=t.priority??1/0;if(n!==r)return n>r?1:-1;if(!e.internal||!t.internal)return 0;let i=e.internal.renderer,s=t.internal.renderer,a=!i.loadAncestors,o=!s.loadAncestors;return a&&o?((e,t)=>e.traversal.used===t.traversal.used?e.traversal.inFrustum===t.traversal.inFrustum?e.internal.hasUnrenderableContent===t.internal.hasUnrenderableContent?e.traversal.distanceFromCamera===t.traversal.distanceFromCamera?e.internal.depthFromRenderedParent===t.internal.depthFromRenderedParent?0:e.internal.depthFromRenderedParent>t.internal.depthFromRenderedParent?-1:1:e.traversal.distanceFromCamera>t.traversal.distanceFromCamera?-1:1:e.internal.hasUnrenderableContent?1:-1:e.traversal.inFrustum?1:-1:e.traversal.used?1:-1)(e,t):((e,t)=>{let n=e.priority||0,r=t.priority||0;return n===r?e.traversal&&t.traversal?e.traversal.used===t.traversal.used?e.traversal.error===t.traversal.error?e.traversal.distanceFromCamera===t.traversal.distanceFromCamera?e.internal.depthFromRenderedParent===t.internal.depthFromRenderedParent?0:e.internal.depthFromRenderedParent>t.internal.depthFromRenderedParent?-1:1:e.traversal.distanceFromCamera>t.traversal.distanceFromCamera?-1:1:e.traversal.error>t.traversal.error?1:-1:e.traversal.used?1:-1:0:n>r?1:-1})(e,t)},uc=new Bl;uc.unloadPriorityCallback=(e,t)=>e.traversal.lastFrameVisited===t.traversal.lastFrameVisited?e.internal.depthFromRenderedParent===t.internal.depthFromRenderedParent?e.internal.loadingState===t.internal.loadingState?e.internal.hasUnrenderableContent===t.internal.hasUnrenderableContent?e.traversal.error===t.traversal.error?0:e.traversal.error>t.traversal.error?-1:1:e.internal.hasUnrenderableContent?-1:1:e.internal.loadingState>t.internal.loadingState?-1:1:e.internal.depthFromRenderedParent>t.internal.depthFromRenderedParent?1:-1:e.traversal.lastFrameVisited>t.traversal.lastFrameVisited?-1:1;var hc=new Ol;hc.maxJobs=25,hc.priorityCallback=cc;var dc=new Ol;dc.maxJobs=5,dc.priorityCallback=cc;var pc=new Ol;pc.maxJobs=25,pc.priorityCallback=(e,t)=>{let n=e.parent,r=t.parent;return n===r?0:n?r?cc(n,r):-1:1};var mc=class{get root(){let e=this.rootTileset;return e?e.root:null}get loadProgress(){let{stats:e,isLoading:t}=this,n=e.queued+e.downloading+e.parsing,r=e.inCacheSinceLoad+ +!!t;return 0===r?1:1-n/r}constructor(e=null){this.rootLoadingState=0,this.rootTileset=null,this.rootURL=e,this.fetchOptions={},this.plugins=[],this.queuedTiles=[],this.cachedSinceLoadComplete=new Set,this.isLoading=!1,this.processedTiles=new WeakSet,this.visibleTiles=new Set,this.activeTiles=new Set,this.usedSet=new Set,this.loadingTiles=new Set,this.lruCache=uc,this.downloadQueue=hc,this.parseQueue=dc,this.processNodeQueue=pc,this.stats={inCacheSinceLoad:0,inCache:0,queued:0,downloading:0,parsing:0,loaded:0,failed:0,inFrustum:0,used:0,active:0,visible:0,tilesProcessed:0},this.frameCount=0,this._dispatchNeedsUpdateEvent=function(e){let t=null;return()=>{null===t&&(t=Fl.requestAnimationFrame((()=>{t=null,e()})))}}((()=>{this.dispatchEvent({type:"needs-update"})})),this.errorTarget=16,this.displayActiveTiles=!1,this.maxDepth=1/0,this.loadSiblings=!0,this.loadAncestors=!0,this.maxTilesProcessed=250}registerPlugin(e){if(!0===e[oc])throw Error("TilesRendererBase: A plugin can only be registered to a single tileset");let t=this.plugins,n=e.priority||0,r=t.length;for(let i=0;i<t.length;i++)if((t[i].priority||0)>n){r=i;break}t.splice(r,0,e),e[oc]=!0,e.init&&e.init(this)}unregisterPlugin(e){let t=this.plugins;if("string"==typeof e&&(e=this.getPluginByName(e)),t.includes(e)){let n=t.indexOf(e);return t.splice(n,1),e.dispose&&e.dispose(),!0}return!1}getPluginByName(e){return this.plugins.find((t=>t.name===e))||null}invokeOnePlugin(e){let t=[...this.plugins,this];for(let n=0;n<t.length;n++){let r=e(t[n]);if(r)return r}return null}invokeAllPlugins(e){let t=[...this.plugins,this],n=[];for(let r=0;r<t.length;r++){let i=e(t[r]);i&&n.push(i)}return 0===n.length?null:Promise.all(n)}traverse(e,t,n=!0){this.root&&ac(this.root,((t,...r)=>(n&&this.ensureChildrenArePreprocessed(t,!0),!!e&&e(t,...r))),t)}getAttributions(e=[]){return this.invokeAllPlugins((t=>t!==this&&t.getAttributions&&t.getAttributions(e))),e}update(){let{lruCache:e,usedSet:t,stats:n,root:r,downloadQueue:i,parseQueue:s,processNodeQueue:a}=this;if(0===this.rootLoadingState&&(this.rootLoadingState=2,this.invokeOnePlugin((e=>e.loadRootTileset&&e.loadRootTileset())).then((e=>{let t=this.rootURL;null!==t&&this.invokeAllPlugins((e=>t=e.preprocessURL?e.preprocessURL(t,null):t)),this.rootLoadingState=4,this.rootTileset=e,this.dispatchEvent({type:"needs-update"}),this.dispatchEvent({type:"load-tileset",tileset:e,url:t}),this.dispatchEvent({type:"load-root-tileset",tileset:e,url:t})})).catch((e=>{this.rootLoadingState=-1,this.rootTileset=null,this.dispatchEvent({type:"load-error",tile:null,error:e,url:this.rootURL})}))),!r)return;let o=null;if(this.invokeAllPlugins((e=>{if(e.doTilesNeedUpdate){let t=e.doTilesNeedUpdate();o=null===o?t:!(!o&&!t)}})),!1===o)return this.dispatchEvent({type:"update-before"}),void this.dispatchEvent({type:"update-after"});this.dispatchEvent({type:"update-before"}),n.inFrustum=0,n.used=0,n.active=0,n.visible=0,n.tilesProcessed=0,this.frameCount++,t.forEach((t=>e.markUnused(t))),t.clear(),this.prepareForTraversal(),sc(r,this),this.removeUnusedPendingTiles();let l=this.queuedTiles;l.sort(e.unloadPriorityCallback);for(let c=0,u=l.length;c<u&&!e.isFull();c++)this.requestTileContents(l[c]);l.length=0,e.scheduleUnload(),!1===(i.running||s.running||a.running)&&!0===this.isLoading&&(this.cachedSinceLoadComplete.clear(),n.inCacheSinceLoad=0,this.dispatchEvent({type:"tiles-load-end"}),this.isLoading=!1),this.dispatchEvent({type:"update-after"})}resetFailedTiles(){-1===this.rootLoadingState&&(this.rootLoadingState=0);let e=this.stats;0!==e.failed&&(this.traverse((e=>{-1===e.internal.loadingState&&(e.internal.loadingState=0)}),null,!1),e.failed=0)}calculateTileViewErrorWithPlugin(e,t){this.calculateTileViewError(e,t);let n=null,r=0,i=1/0;this.invokeAllPlugins((t=>{t!==this&&t.calculateTileViewError&&(lc.inView=!0,lc.error=0,lc.distance=1/0,t.calculateTileViewError(e,lc)&&(null===n&&(n=!0),n&&(n=lc.inView),lc.inView&&(i=Math.min(i,lc.distance),r=Math.max(r,lc.error))))})),t.inView&&!1!==n?(t.error=Math.max(t.error,r),t.distanceFromCamera=Math.min(t.distanceFromCamera,i)):n?(t.inView=!0,t.error=r,t.distanceFromCamera=i):t.inView=!1}dispose(){[...this.plugins].forEach((e=>{this.unregisterPlugin(e)}));let e=this.lruCache,t=[];this.traverse((e=>(t.push(e),!1)),null,!1);for(let n=0,r=t.length;n<r;n++)e.remove(t[n]);this.stats={queued:0,parsing:0,downloading:0,failed:0,inFrustum:0,traversed:0,used:0,active:0,visible:0},this.frameCount=0,this.loadingTiles.clear()}calculateBytesUsed(e,t){return 0}dispatchEvent(e){}addEventListener(e,t){}removeEventListener(e,t){}parseTile(e,t,n){return null}prepareForTraversal(){}disposeTile(e){e.traversal.visible&&(e.internal.hasRenderableContent?this.invokeOnePlugin((t=>t.setTileVisible&&t.setTileVisible(e,!1))):this.invokeOnePlugin((t=>t.setEmptyTileVisible&&t.setEmptyTileVisible(e,!1))),e.traversal.visible=!1),e.traversal.active&&e.internal.hasRenderableContent&&this.invokeOnePlugin((t=>t.setTileActive&&t.setTileActive(e,!1))),e.traversal.active=!1;let{scene:t}=e.engineData;t&&this.dispatchEvent({type:"dispose-model",scene:t,tile:e})}preprocessNode(e,t,n=null){var r;if(this.processedTiles.add(e),this.stats.tilesProcessed++,e.content&&(!("uri"in e.content)&&"url"in e.content&&(e.content.uri=e.content.url,delete e.content.url),e.content.boundingVolume&&!("box"in e.content.boundingVolume||"sphere"in e.content.boundingVolume||"region"in e.content.boundingVolume)&&delete e.content.boundingVolume),e.parent=n,e.children=e.children||[],e.internal={hasContent:!1,hasRenderableContent:!1,hasUnrenderableContent:!1,loadingState:0,basePath:t,depth:-1,depthFromRenderedParent:-1,isVirtual:!1,virtualChildCount:0,renderer:this,...e.internal},null==(r=e.content)?void 0:r.uri){let t=Ul(e.content.uri),n=!(!t||!/json$/.test(t));e.internal.hasContent=!0,e.internal.hasUnrenderableContent=n,e.internal.hasRenderableContent=!n}else e.internal.hasContent=!1,e.internal.hasUnrenderableContent=!1,e.internal.hasRenderableContent=!1;n?(e.internal.depth=n.internal.depth+1,e.internal.depthFromRenderedParent=n.internal.depthFromRenderedParent+ +!!e.internal.hasRenderableContent):(e.internal.depth=0,e.internal.depthFromRenderedParent=+!!e.internal.hasRenderableContent),e.traversal={distanceFromCamera:1/0,error:1/0,inFrustum:!1,wasInFrustum:!1,isLeaf:!1,used:!1,usedLastFrame:!1,visible:!1,wasSetVisible:!1,active:!1,wasSetActive:!1,allChildrenReady:!1,allChildrenLoaded:!1,kicked:!1,allUsedChildrenProcessed:!1,lastFrameVisited:-1},e.refine=null===n?e.refine||"REPLACE":e.refine||n.refine,e.engineData={scene:null,metadata:null,boundingVolume:null},Object.defineProperty(e,"cached",{get(){return this.engineData},enumerable:!1,configurable:!0}),this.invokeAllPlugins((r=>{r!==this&&r.preprocessNode&&r.preprocessNode(e,t,n)}))}setTileActive(e,t){t?this.activeTiles.add(e):this.activeTiles.delete(e)}setTileVisible(e,t){t?this.visibleTiles.add(e):this.visibleTiles.delete(e),this.dispatchEvent({type:"tile-visibility-change",scene:e.engineData.scene,tile:e,visible:t})}calculateTileViewError(e,t){}removeUnusedPendingTiles(){let{lruCache:e,loadingTiles:t}=this,n=[];for(let r of t)!e.isUsed(r)&&1===r.internal.loadingState&&n.push(r);for(let r=0;r<n.length;r++)e.remove(n[r])}queueTileForDownload(e){0!==e.internal.loadingState||this.lruCache.isFull()||this.queuedTiles.push(e)}markTileUsed(e){this.usedSet.add(e),this.lruCache.markUsed(e)}fetchData(e,t){return fetch(e,t)}ensureChildrenArePreprocessed(e,t=this.stats.tilesProcessed<this.maxTilesProcessed){let n=e.children;if(0===n.length||n[n.length-1].traversal)return;let r=t=>{for(let n=0,r=t.length;n<r;n++){let r=t[n];r&&!r.traversal&&this.preprocessNode(r,e.internal.basePath,e)}};t?(this.processNodeQueue.remove(e),r(n)):this.processNodeQueue.has(e)||this.processNodeQueue.add(e,(e=>{r(e.children),this._dispatchNeedsUpdateEvent()}))}getBytesUsed(e){let t=0;return this.invokeAllPlugins((n=>{n.calculateBytesUsed&&(t+=n.calculateBytesUsed(e,e.engineData.scene)||0)})),t}recalculateBytesUsed(e=null){let{lruCache:t,processedTiles:n}=this;null===e?t.itemSet.forEach((e=>{n.has(e)&&t.setMemoryUsage(e,this.getBytesUsed(e))})):t.setMemoryUsage(e,this.getBytesUsed(e))}preprocessTileset(e,t,n=null){let[r,i]=e.asset.version.split(".").map((e=>parseInt(e))),s=t.replace(/\/[^/]*$/,"");s=new URL(s,window.location.href).toString(),this.preprocessNode(e.root,s,n)}loadRootTileset(){let e=this.rootURL;return this.invokeAllPlugins((t=>e=t.preprocessURL?t.preprocessURL(e,null):e)),this.invokeOnePlugin((t=>t.fetchData&&t.fetchData(e,this.fetchOptions))).then((t=>{if(!(t instanceof Response))return t;if(t.ok)return t.json();throw Error(`TilesRenderer: Failed to load tileset "${e}" with status ${t.status} : ${t.statusText}`)})).then((t=>(this.preprocessTileset(t,e),t)))}requestTileContents(e){if(0!==e.internal.loadingState)return;let t=!1,n=null,r=new URL(e.content.uri,e.internal.basePath+"/").toString();this.invokeAllPlugins((t=>r=t.preprocessURL?t.preprocessURL(r,e):r));let i=this.stats,s=this.lruCache,a=this.downloadQueue,o=this.parseQueue,l=this.loadingTiles,c=Ul(r),u=new AbortController,h=u.signal;return s.add(e,(n=>{u.abort(),t?n.children.length=0:this.invokeAllPlugins((e=>{e.disposeTile&&e.disposeTile(n)})),i.inCache--,this.cachedSinceLoadComplete.has(e)&&(this.cachedSinceLoadComplete.delete(e),i.inCacheSinceLoad--),1===n.internal.loadingState?i.queued--:2===n.internal.loadingState?i.downloading--:3===n.internal.loadingState?i.parsing--:4===n.internal.loadingState&&i.loaded--,n.internal.loadingState=0,o.remove(n),a.remove(n),l.delete(n)}))?(this.isLoading||(this.isLoading=!0,this.dispatchEvent({type:"tiles-load-start"})),s.setMemoryUsage(e,this.getBytesUsed(e)),this.cachedSinceLoadComplete.add(e),i.inCacheSinceLoad++,i.inCache++,i.queued++,e.internal.loadingState=1,l.add(e),a.add(e,(t=>{if(h.aborted)return Promise.resolve();e.internal.loadingState=2,i.downloading++,i.queued--;let n=this.invokeOnePlugin((e=>e.fetchData&&e.fetchData(r,{...this.fetchOptions,signal:h})));return this.dispatchEvent({type:"tile-download-start",tile:e,url:r,get uri(){return this.url}}),n})).then((e=>{if(!h.aborted){if(!(e instanceof Response))return e;if(e.ok)return"json"===c?e.json():e.arrayBuffer();throw Error(`Failed to load model with error code ${e.status}`)}})).then((s=>{if(!h.aborted)return i.downloading--,i.parsing++,e.internal.loadingState=3,o.add(e,(i=>h.aborted?Promise.resolve():"json"===c&&s.root?(this.preprocessTileset(s,r,e),e.children.push(s.root),n=s,t=!0,Promise.resolve()):this.invokeOnePlugin((e=>e.parseTile&&e.parseTile(s,i,c,r,h)))))})).then((()=>{if(h.aborted)return;i.parsing--,i.loaded++,e.internal.loadingState=4,l.delete(e),s.setLoaded(e,!0);let a=this.getBytesUsed(e);0===s.getMemoryUsage(e)&&a>0&&s.isFull()?s.remove(e):(s.setMemoryUsage(e,a),this.dispatchEvent({type:"needs-update"}),t&&this.dispatchEvent({type:"load-tileset",tileset:n,url:r}),e.engineData.scene&&this.dispatchEvent({type:"load-model",scene:e.engineData.scene,tile:e,url:r}))})).catch((t=>{h.aborted||("AbortError"===t.name?s.remove(e):(o.remove(e),a.remove(e),1===e.internal.loadingState?i.queued--:2===e.internal.loadingState?i.downloading--:3===e.internal.loadingState?i.parsing--:4===e.internal.loadingState&&i.loaded--,i.failed++,e.internal.loadingState=-1,l.delete(e),s.setLoaded(e,!0),this.dispatchEvent({type:"load-error",tile:e,error:t,url:r})))}))):void 0}};function fc(e){if(null===e||e.byteLength<4)return"";let t;if(t=e instanceof DataView?e:new DataView(e),"{"===String.fromCharCode(t.getUint8(0)))return null;let n="";for(let r=0;r<4;r++)n+=String.fromCharCode(t.getUint8(r));return n}var gc=new TextDecoder;function xc(e){return gc.decode(e)}function yc(e){return e.replace(/[\\/][^\\/]+$/,"")+"/"}var vc=class{constructor(){this.fetchOptions={},this.workingPath=""}loadAsync(e){return fetch(e,this.fetchOptions).then((t=>{if(!t.ok)throw Error(`Failed to load file "${e}" with status ${t.status} : ${t.statusText}`);return t.arrayBuffer()})).then((t=>(""===this.workingPath&&(this.workingPath=yc(e)),this.parse(t))))}resolveExternalURL(e){return new URL(e,this.workingPath).href}parse(e){throw Error("LoaderBase: Parse not implemented.")}};function bc(e,t,n,r,i,s){let a;switch(r){case"SCALAR":a=1;break;case"VEC2":a=2;break;case"VEC3":a=3;break;case"VEC4":a=4;break;default:throw Error(`FeatureTable : Feature type not provided for "${s}".`)}let o,l=n*a;switch(i){case"BYTE":o=new Int8Array(e,t,l);break;case"UNSIGNED_BYTE":o=new Uint8Array(e,t,l);break;case"SHORT":o=new Int16Array(e,t,l);break;case"UNSIGNED_SHORT":o=new Uint16Array(e,t,l);break;case"INT":o=new Int32Array(e,t,l);break;case"UNSIGNED_INT":o=new Uint32Array(e,t,l);break;case"FLOAT":o=new Float32Array(e,t,l);break;case"DOUBLE":o=new Float64Array(e,t,l);break;default:throw Error(`FeatureTable : Feature component type not provided for "${s}".`)}return o}var wc=class{constructor(e,t,n,r){this.buffer=e,this.binOffset=t+n,this.binLength=r;let i=null;if(0!==n){let r=new Uint8Array(e,t,n);i=JSON.parse(xc(r))}else i={};this.header=i}getKeys(){return Object.keys(this.header).filter((e=>"extensions"!==e))}getData(e,t,n=null,r=null){let i=this.header;if(!(e in i))return null;let s=i[e];if(!(s instanceof Object)||Array.isArray(s))return s;{let{buffer:i,binOffset:a,binLength:o}=this,l=s.byteOffset||0,c=s.type||r,u=s.componentType||n;if("type"in s&&r&&s.type!==r)throw Error("FeatureTable: Specified type does not match expected type.");let h=a+l,d=bc(i,h,t,c,u,e);if(h+d.byteLength>a+o)throw Error("FeatureTable: Feature data read outside binary body length.");return d}}getBuffer(e,t){let{buffer:n,binOffset:r}=this;return n.slice(r+e,r+e+t)}},Tc=class{constructor(e){this.batchTable=e;let t=e.header.extensions["3DTILES_batch_table_hierarchy"];this.classes=t.classes;for(let r of this.classes){let e=r.instances;for(let t in e)r.instances[t]=this._parseProperty(e[t],r.length,t)}if(this.instancesLength=t.instancesLength,this.classIds=this._parseProperty(t.classIds,this.instancesLength,"classIds"),t.parentCounts?this.parentCounts=this._parseProperty(t.parentCounts,this.instancesLength,"parentCounts"):this.parentCounts=Array(this.instancesLength).fill(1),t.parentIds){let e=this.parentCounts.reduce(((e,t)=>e+t),0);this.parentIds=this._parseProperty(t.parentIds,e,"parentIds")}else this.parentIds=null;this.instancesIds=[];let n={};for(let r of this.classIds)n[r]=n[r]??0,this.instancesIds.push(n[r]),n[r]++}_parseProperty(e,t,n){if(Array.isArray(e))return e;{let{buffer:r,binOffset:i}=this.batchTable;return bc(r,i+e.byteOffset,t,"SCALAR",e.componentType||"UNSIGNED_SHORT",n)}}getDataFromId(e,t={}){let n=this.parentCounts[e];if(this.parentIds&&n>0){let r=0;for(let t=0;t<e;t++)r+=this.parentCounts[t];for(let i=0;i<n;i++){let n=this.parentIds[r+i];n!==e&&this.getDataFromId(n,t)}}let r=this.classIds[e],i=this.classes[r].instances,s=this.classes[r].name,a=this.instancesIds[e];for(let o in i)t[s]=t[s]||{},t[s][o]=i[o][a];return t}},Sc=class extends wc{constructor(e,t,n,r,i){super(e,n,r,i),this.count=t,this.extensions={};let s=this.header.extensions;s&&s["3DTILES_batch_table_hierarchy"]&&(this.extensions["3DTILES_batch_table_hierarchy"]=new Tc(this))}getDataFromId(e,t={}){if(e<0||e>=this.count)throw Error(`BatchTable: id value "${e}" out of bounds for "${this.count}" features number.`);for(let n of this.getKeys())t[n]=super.getData(n,this.count)[e];for(let n in this.extensions){let r=this.extensions[n];r.getDataFromId instanceof Function&&(t[n]=t[n]||{},r.getDataFromId(e,t[n]))}return t}getPropertyArray(e){return super.getData(e,this.count)}},_c=class extends vc{parse(e){let t=new DataView(e),n=(fc(t),t.getUint32(4,!0)),r=t.getUint32(8,!0),i=t.getUint32(12,!0),s=t.getUint32(16,!0),a=t.getUint32(20,!0),o=t.getUint32(24,!0),l=new wc(e.slice(28,28+i+s),0,i,s),c=28+i+s,u=new Sc(e.slice(c,c+a+o),l.getData("BATCH_LENGTH"),0,a,o),h=c+a+o;return{version:n,featureTable:l,batchTable:u,glbBytes:new Uint8Array(e,h,r-h)}}},Mc=class extends vc{parse(e){let t=new DataView(e),n=(fc(t),t.getUint32(4,!0)),r=t.getUint32(8,!0),i=t.getUint32(12,!0),s=t.getUint32(16,!0),a=t.getUint32(20,!0),o=t.getUint32(24,!0),l=t.getUint32(28,!0),c=new wc(e.slice(32,32+i+s),0,i,s),u=32+i+s,h=new Sc(e.slice(u,u+a+o),c.getData("INSTANCES_LENGTH"),0,a,o),d=u+a+o,p=new Uint8Array(e,d,r-d),m=null,f=null,g=null;if(l)m=p,f=Promise.resolve();else{let e=this.resolveExternalURL(xc(p));g=yc(e),f=fetch(e,this.fetchOptions).then((t=>{if(!t.ok)throw Error(`I3DMLoaderBase : Failed to load file "${e}" with status ${t.status} : ${t.statusText}`);return t.arrayBuffer()})).then((e=>{m=new Uint8Array(e)}))}return f.then((()=>({version:n,featureTable:c,batchTable:h,glbBytes:m,gltfWorkingPath:g})))}},Ac=class extends vc{parse(e){let t=new DataView(e),n=(fc(t),t.getUint32(4,!0)),r=(t.getUint32(8,!0),t.getUint32(12,!0)),i=t.getUint32(16,!0),s=t.getUint32(20,!0),a=t.getUint32(24,!0),o=new wc(e.slice(28,28+r+i),0,r,i),l=28+r+i,c=new Sc(e.slice(l,l+s+a),o.getData("BATCH_LENGTH")||o.getData("POINTS_LENGTH"),0,s,a);return Promise.resolve({version:n,featureTable:o,batchTable:c})}},Ec=class extends vc{parse(e){let t=new DataView(e),n=(fc(t),t.getUint32(4,!0)),r=(t.getUint32(8,!0),t.getUint32(12,!0)),i=[],s=16;for(let a=0;a<r;a++){let t=new DataView(e,s,12),n=fc(t),r=t.getUint32(4,!0),a=t.getUint32(8,!0),o=new Uint8Array(e,s,a);i.push({type:n,buffer:o,version:r}),s+=a}return{version:n,tiles:i}}};const Cc=new Ll(Nl,Nl,$l);Cc.name="WGS84 Earth";const Rc=new r.Matrix4,Dc=new r.Matrix4,kc=new r.Vector3,Ic=new r.Vector3,Pc=new r.Vector3,Lc=new r.Vector3,Uc=new r.Vector3,Fc=new r.Vector3,zc=new r.Quaternion,Bc=new r.Vector3,Vc=new r.Vector3,Oc=new r.Ray,Nc=new Ll,$c=new r.Vector2,Gc={};class qc extends bl{get tilesGroup(){return this.ellipsoidFrame}get ellipsoidFrame(){return this.ellipsoidGroup.matrixWorld}get ellipsoidFrameInverse(){const{ellipsoidGroup:e,ellipsoidFrame:t,_ellipsoidFrameInverse:n}=this;return e.matrixWorldInverse?e.matrixWorldInverse:n.copy(t).invert()}constructor(e=null,t=null,n=null,i=null){super(e,t,n),this.isGlobeControls=!0,this._dragMode=0,this._rotationMode=0,this.maxZoom=.01,this.nearMargin=.25,this.farMargin=0,this.useFallbackPlane=!1,this.autoAdjustCameraRotation=!1,this.globeInertia=new r.Quaternion,this.globeInertiaFactor=0,this.ellipsoid=Cc.clone(),this.ellipsoidGroup=new r.Group,this._ellipsoidFrameInverse=new r.Matrix4,null!==i&&this.setTilesRenderer(i)}setTilesRenderer(e){super.setTilesRenderer(e),null!==e&&this.setEllipsoid(e.ellipsoid,e.group)}setEllipsoid(e,t){this.ellipsoid=e||Cc.clone(),this.ellipsoidGroup=t||new r.Group}getPivotPoint(e){const{camera:t,ellipsoidFrame:n,ellipsoidFrameInverse:r,ellipsoid:i}=this;return Lc.set(0,0,-1).transformDirection(t.matrixWorld),Oc.origin.copy(t.position),Oc.direction.copy(Lc),Oc.applyMatrix4(r),i.closestPointToRayEstimate(Oc,Ic).applyMatrix4(n),(null===super.getPivotPoint(e)||kc.subVectors(e,Oc.origin).dot(Oc.direction)>kc.subVectors(Ic,Oc.origin).dot(Oc.direction))&&e.copy(Ic),e}getVectorToCenter(e){const{ellipsoidFrame:t,camera:n}=this;return e.setFromMatrixPosition(t).sub(n.position)}getDistanceToCenter(){return this.getVectorToCenter(Ic).length()}getUpDirection(e,t){const{ellipsoidFrame:n,ellipsoidFrameInverse:r,ellipsoid:i}=this;Ic.copy(e).applyMatrix4(r),i.getPositionToNormal(Ic,t),t.transformDirection(n)}getCameraUpDirection(e){const{ellipsoidFrame:t,ellipsoidFrameInverse:n,ellipsoid:r,camera:i}=this;i.isOrthographicCamera?(this._getVirtualOrthoCameraPosition(Ic),Ic.applyMatrix4(n),r.getPositionToNormal(Ic,e),e.transformDirection(t)):this.getUpDirection(i.position,e)}update(e=Math.min(this.clock.getDelta(),.064)){if(!this.enabled||!this.camera||0===e)return;const{camera:t,pivotMesh:n}=this;this._isNearControls()?this.scaleZoomOrientationAtEdges=this.zoomDelta<0:(0!==this.state&&1!==this._dragMode&&1!==this._rotationMode&&(n.visible=!1),this.scaleZoomOrientationAtEdges=!1);const r=this.needsUpdate||this._inertiaNeedsUpdate();super.update(e),this.adjustCamera(t),r&&this._isNearControls()&&(this.getCameraUpDirection(Fc),this._alignCameraUp(Fc,1),this.getCameraUpDirection(Fc),this._clampRotation(Fc))}adjustCamera(e){super.adjustCamera(e);const{ellipsoidFrame:t,ellipsoidFrameInverse:n,ellipsoid:i,nearMargin:s,farMargin:a}=this,o=Math.max(...i.radius);if(e.isPerspectiveCamera){const l=Ic.setFromMatrixPosition(t).sub(e.position).length(),c=s*o,u=r.MathUtils.clamp((l-o)/c,0,1),h=r.MathUtils.lerp(1,1e3,u);e.near=Math.max(h,l-o-c),kc.copy(e.position).applyMatrix4(n),i.getPositionToCartographic(kc,Gc);const d=Math.max(i.getPositionElevation(kc),2550),p=i.calculateHorizonDistance(Gc.lat,d);e.far=p+.1+o*a,e.updateProjectionMatrix()}else{this._getVirtualOrthoCameraPosition(e.position,e),e.updateMatrixWorld(),Rc.copy(e.matrixWorld).invert(),Ic.setFromMatrixPosition(t).applyMatrix4(Rc);const n=-Ic.z;e.near=n-o*(1+s),e.far=n+.1+o*a,e.position.addScaledVector(Lc,e.near),e.far-=e.near,e.near=0,e.updateProjectionMatrix(),e.updateMatrixWorld()}}setState(...e){super.setState(...e),this._dragMode=0,this._rotationMode=0}_updateInertia(e){super._updateInertia(e);const{globeInertia:t,enableDamping:n,dampingFactor:r,camera:i,cameraRadius:s,minDistance:a,inertiaTargetDistance:o,ellipsoidFrame:l}=this;if(!this.enableDamping||this.inertiaStableFrames>1)return this.globeInertiaFactor=0,void this.globeInertia.identity();const c=Math.pow(2,-e/r),u=Math.max(i.near,s,a,o),h=25e-5;if(Pc.setFromMatrixPosition(l),0!==this.globeInertiaFactor){Ho(Oc,Ic.set(0,0,-1),i),Oc.applyMatrix4(i.matrixWorldInverse),Oc.direction.normalize(),Oc.recast(-Oc.direction.dot(Oc.origin)).at(u/Oc.direction.z,Ic),Ic.applyMatrix4(i.matrixWorld),Ho(Oc,kc.set(h,h,-1),i),Oc.applyMatrix4(i.matrixWorldInverse),Oc.direction.normalize(),Oc.recast(-Oc.direction.dot(Oc.origin)).at(u/Oc.direction.z,kc),kc.applyMatrix4(i.matrixWorld),Ic.sub(Pc).normalize(),kc.sub(Pc).normalize(),this.globeInertiaFactor*=c;const r=Ic.angleTo(kc)/e;(2*Math.acos(t.w)*this.globeInertiaFactor<r||!n)&&(this.globeInertiaFactor=0,t.identity())}0!==this.globeInertiaFactor&&(1!==t.w||0===t.x&&0===t.y&&0===t.z||(t.w=Math.min(t.w,1-1e-9)),Pc.setFromMatrixPosition(l),zc.identity().slerp(t,this.globeInertiaFactor*e),Go(Pc,zc,Dc),i.matrixWorld.premultiply(Dc),i.matrixWorld.decompose(i.position,i.quaternion,Ic))}_inertiaNeedsUpdate(){return super._inertiaNeedsUpdate()||0!==this.globeInertiaFactor}_updatePosition(e){if(1===this.state){0===this._dragMode&&(this._dragMode=this._isNearControls()?1:-1);const{raycaster:t,camera:n,pivotPoint:r,pointerTracker:i,domElement:s,ellipsoidFrame:a,ellipsoidFrameInverse:o}=this,l=kc,c=Uc;i.getCenterPoint($c),qo($c,s,$c),Ho(t,$c,n),t.ray.applyMatrix4(o);const u=Ic.copy(r).applyMatrix4(o).length();if(Nc.radius.setScalar(u),!Nc.intersectRay(t.ray,Ic))return this.resetState(),void this._updateInertia(e);Ic.applyMatrix4(a),Pc.setFromMatrixPosition(a),l.subVectors(r,Pc).normalize(),c.subVectors(Ic,Pc).normalize(),zc.setFromUnitVectors(c,l),Go(Pc,zc,Dc),n.matrixWorld.premultiply(Dc),n.matrixWorld.decompose(n.position,n.quaternion,Ic),i.getMoveDistance()/e<2*window.devicePixelRatio?this.inertiaStableFrames++:(this.globeInertia.copy(zc),this.globeInertiaFactor=1/e,this.inertiaStableFrames=0)}}_updateRotation(...e){1===this._rotationMode||this._isNearControls()?(this._rotationMode=1,super._updateRotation(...e)):(this.pivotMesh.visible=!1,this._rotationMode=-1)}_updateZoom(){const{zoomDelta:e,ellipsoid:t,zoomSpeed:n,zoomPoint:i,camera:s,maxZoom:a,state:o}=this;if(3!==o&&0===e)return;this.rotationInertia.set(0,0),this.dragInertia.set(0,0,0),this.globeInertia.identity(),this.globeInertiaFactor=0;const l=r.MathUtils.clamp(r.MathUtils.mapLinear(Math.abs(e),0,20,0,1),0,1);if(this._isNearControls()||e>0){if(this._updateZoomDirection(),e<0&&(this.zoomPointSet||this._updateZoomPoint())){Lc.set(0,0,-1).transformDirection(s.matrixWorld).normalize(),Vc.copy(this.up).multiplyScalar(-1),this.getUpDirection(i,Bc);const e=r.MathUtils.clamp(r.MathUtils.mapLinear(-Bc.dot(Vc),1,.95,0,1),0,1),t=1-Lc.dot(Vc),n=s.isOrthographicCamera?.05:1,a=r.MathUtils.clamp(3*l,0,1),o=Math.min(e*t*n*a,.1);Vc.lerpVectors(Lc,Vc,o).normalize(),zc.setFromUnitVectors(Lc,Vc),Go(i,zc,Dc),s.matrixWorld.premultiply(Dc),s.matrixWorld.decompose(s.position,s.quaternion,Vc),this.zoomDirection.subVectors(i,s.position).normalize()}super._updateZoom()}else if(s.isPerspectiveCamera){const i=this._getPerspectiveTransitionDistance(),s=this._getMaxPerspectiveDistance(),a=r.MathUtils.mapLinear(this.getDistanceToCenter(),i,s,0,1);this._tiltTowardsCenter(r.MathUtils.lerp(0,.4,a*l)),this._alignCameraUpToNorth(r.MathUtils.lerp(0,.2,a*l));const o=e*(this.getDistanceToCenter()-t.radius.x)*n*.0025,c=Math.max(o,Math.min(this.getDistanceToCenter()-s,0));this.getVectorToCenter(Ic).normalize(),this.camera.position.addScaledVector(Ic,c),this.camera.updateMatrixWorld(),this.zoomDelta=0}else{const e=this._getOrthographicTransitionZoom(),t=this._getMinOrthographicZoom(),i=r.MathUtils.mapLinear(s.zoom,e,t,0,1);this._tiltTowardsCenter(r.MathUtils.lerp(0,.4,i*l)),this._alignCameraUpToNorth(r.MathUtils.lerp(0,.2,i*l));const o=this.zoomDelta,c=Math.pow(.95,Math.abs(.05*o)),u=o>0?1/Math.abs(c):c,h=t/s.zoom,d=Math.max(u*n,Math.min(h,1));s.zoom=Math.min(a,s.zoom*d),s.updateProjectionMatrix(),this.zoomDelta=0,this.zoomDirectionSet=!1}}_alignCameraUpToNorth(e){const{ellipsoidFrame:t}=this;Fc.set(0,0,1).transformDirection(t),this._alignCameraUp(Fc,e)}_tiltTowardsCenter(e){const{camera:t,ellipsoidFrame:n}=this;Lc.set(0,0,-1).transformDirection(t.matrixWorld).normalize(),Ic.setFromMatrixPosition(n).sub(t.position).normalize(),Ic.lerp(Lc,1-e).normalize(),zc.setFromUnitVectors(Lc,Ic),t.quaternion.premultiply(zc),t.updateMatrixWorld()}_getPerspectiveTransitionDistance(){const{camera:e,ellipsoid:t}=this;if(!e.isPerspectiveCamera)throw new Error;const n=Math.max(...t.radius),i=2*Math.atan(Math.tan(r.MathUtils.DEG2RAD*e.fov*.5)*e.aspect),s=n/Math.tan(r.MathUtils.DEG2RAD*e.fov*.5),a=n/Math.tan(.5*i);return Math.max(s,a)}_getMaxPerspectiveDistance(){const{camera:e,ellipsoid:t}=this;if(!e.isPerspectiveCamera)throw new Error;const n=Math.max(...t.radius),i=2*Math.atan(Math.tan(r.MathUtils.DEG2RAD*e.fov*.5)*e.aspect),s=n/Math.tan(r.MathUtils.DEG2RAD*e.fov*.5),a=n/Math.tan(.5*i);return 2*Math.max(s,a)}_getOrthographicTransitionZoom(){const{camera:e,ellipsoid:t}=this;if(!e.isOrthographicCamera)throw new Error;const n=e.top-e.bottom,r=e.right-e.left;return 2*Math.max(n,r)/(2*Math.max(...t.radius))}_getMinOrthographicZoom(){const{camera:e,ellipsoid:t}=this;if(!e.isOrthographicCamera)throw new Error;const n=e.top-e.bottom,r=e.right-e.left;return.7*Math.min(n,r)/(2*Math.max(...t.radius))}_getVirtualOrthoCameraPosition(e,t=this.camera){const{ellipsoidFrame:n,ellipsoidFrameInverse:r,ellipsoid:i}=this;if(!t.isOrthographicCamera)throw new Error;Oc.origin.copy(t.position),Oc.direction.set(0,0,-1).transformDirection(t.matrixWorld),Oc.applyMatrix4(r),i.closestPointToRayEstimate(Oc,kc).applyMatrix4(n);const s=t.top-t.bottom,a=t.right-t.left,o=Math.max(s,a)/t.zoom;Lc.set(0,0,-1).transformDirection(t.matrixWorld);const l=kc.sub(t.position).dot(Lc);e.copy(t.position).addScaledVector(Lc,l-4*o)}_isNearControls(){const{camera:e}=this;return e.isPerspectiveCamera?this.getDistanceToCenter()<this._getPerspectiveTransitionDistance():e.zoom>this._getOrthographicTransitionZoom()}_raycast(e){const t=super._raycast(e);if(null===t){const{ellipsoid:t,ellipsoidFrame:n,ellipsoidFrameInverse:r}=this;Oc.copy(e.ray).applyMatrix4(r);const i=t.intersectRay(Oc,Ic);return null!==i?{point:i.clone().applyMatrix4(n)}:null}return t}}var Hc=class extends _c{constructor(e=r.DefaultLoadingManager){super(),this.manager=e,this.adjustmentTransform=new r.Matrix4}parse(e){let t=super.parse(e),n=t.glbBytes.slice().buffer;return new Promise(((e,r)=>{let i=this.manager,s=this.fetchOptions,a=i.getHandler("path.gltf")||new rt(i);"include"===s.credentials&&"cors"===s.mode&&a.setCrossOrigin("use-credentials"),"credentials"in s&&a.setWithCredentials("include"===s.credentials),s.headers&&a.setRequestHeader(s.headers);let o=this.workingPath;!/[\\/]$/.test(o)&&o.length&&(o+="/");let l=this.adjustmentTransform;a.parse(n,o,(n=>{let{batchTable:r,featureTable:i}=t,{scene:s}=n,a=i.getData("RTC_CENTER",1,"FLOAT","VEC3");a&&(s.position.x+=a[0],s.position.y+=a[1],s.position.z+=a[2]),n.scene.updateMatrix(),n.scene.matrix.multiply(l),n.scene.matrix.decompose(n.scene.position,n.scene.quaternion,n.scene.scale),n.batchTable=r,n.featureTable=i,s.batchTable=r,s.featureTable=i,e(n)}),r)}))}};function jc(e){let t=e>>11,n=e>>5&63,r=31&e;return[Math.round(t/31*255),Math.round(n/63*255),Math.round(r/31*255)]}var Wc=new r.Vector2;function Xc(e,t,n=new r.Vector3){Wc.set(e,t).divideScalar(256).multiplyScalar(2).subScalar(1),n.set(Wc.x,Wc.y,1-Math.abs(Wc.x)-Math.abs(Wc.y));let i=r.MathUtils.clamp(-n.z,0,1);return n.x>=0?n.setX(n.x-i):n.setX(n.x+i),n.y>=0?n.setY(n.y-i):n.setY(n.y+i),n.normalize(),n}var Yc={RGB:"color",POSITION:"position"},Kc=class extends Ac{constructor(e=r.DefaultLoadingManager){super(),this.manager=e}parse(e){return super.parse(e).then((async e=>{let t,{featureTable:n,batchTable:i}=e,s=new r.PointsMaterial,a=n.header.extensions,o=new r.Vector3;if(a&&a["3DTILES_draco_point_compression"]){let{byteOffset:e,byteLength:r,properties:i}=a["3DTILES_draco_point_compression"],o=this.manager.getHandler("draco.drc");if(null==o)throw Error("PNTSLoader: dracoLoader not available.");let l={};for(let t in i)if(t in Yc&&t in i){l[Yc[t]]=i[t]}let c={attributeIDs:l,attributeTypes:{position:"Float32Array",color:"Uint8Array"},useUniqueIDs:!0},u=n.getBuffer(e,r);t=await o.decodeGeometry(u,c),t.attributes.color&&(s.vertexColors=!0)}else{let e=n.getData("POINTS_LENGTH"),i=n.getData("POSITION",e,"FLOAT","VEC3"),a=n.getData("NORMAL",e,"FLOAT","VEC3"),l=n.getData("NORMAL",e,"UNSIGNED_BYTE","VEC2"),c=n.getData("RGB",e,"UNSIGNED_BYTE","VEC3"),u=n.getData("RGBA",e,"UNSIGNED_BYTE","VEC4"),h=n.getData("RGB565",e,"UNSIGNED_SHORT","SCALAR"),d=n.getData("CONSTANT_RGBA",e,"UNSIGNED_BYTE","VEC4"),p=n.getData("POSITION_QUANTIZED",e,"UNSIGNED_SHORT","VEC3"),m=n.getData("QUANTIZED_VOLUME_SCALE",e,"FLOAT","VEC3"),f=n.getData("QUANTIZED_VOLUME_OFFSET",e,"FLOAT","VEC3");if(t=new r.BufferGeometry,p){let n=new Float32Array(3*e);for(let t=0;t<e;t++)for(let e=0;e<3;e++){let r=3*t+e;n[r]=p[r]/65535*m[e]}o.x=f[0],o.y=f[1],o.z=f[2],t.setAttribute("position",new r.BufferAttribute(n,3,!1))}else t.setAttribute("position",new r.BufferAttribute(i,3,!1));if(null!==a)t.setAttribute("normal",new r.BufferAttribute(a,3,!1));else if(null!==l){let n=new Float32Array(3*e),i=new r.Vector3;for(let t=0;t<e;t++){let e=Xc(l[2*t],l[2*t+1],i);n[3*t]=e.x,n[3*t+1]=e.y,n[3*t+2]=e.z}t.setAttribute("normal",new r.BufferAttribute(n,3,!1))}if(null!==u)t.setAttribute("color",new r.BufferAttribute(u,4,!0)),s.vertexColors=!0,s.transparent=!0,s.depthWrite=!1;else if(null!==c)t.setAttribute("color",new r.BufferAttribute(c,3,!0)),s.vertexColors=!0;else if(null!==h){let n=new Uint8Array(3*e);for(let t=0;t<e;t++){let e=jc(h[t]);for(let r=0;r<3;r++){n[3*t+r]=e[r]}}t.setAttribute("color",new r.BufferAttribute(n,3,!0)),s.vertexColors=!0}else if(null!==d){s.color=new r.Color(d[0],d[1],d[2]);let e=d[3]/255;e<1&&(s.opacity=e,s.transparent=!0,s.depthWrite=!1)}}let l=new r.Points(t,s);l.position.copy(o),e.scene=l,e.scene.featureTable=n,e.scene.batchTable=i;let c=n.getData("RTC_CENTER",1,"FLOAT","VEC3");return c&&(e.scene.position.x+=c[0],e.scene.position.y+=c[1],e.scene.position.z+=c[2]),e}))}};var Qc=new r.Spherical,Zc=new r.Vector3,Jc=new r.Vector3,eu=new r.Vector3,tu=new r.Matrix4,nu=new r.Matrix4,ru=new r.Sphere,iu=new r.Euler,su=new r.Vector3,au=new r.Vector3,ou=new r.Vector3,lu=new r.Vector3,cu=new r.Ray,uu=class{constructor(e=1,t=1,n=1){this.name="",this.radius=new r.Vector3(e,t,n)}intersectRay(e,t){return tu.makeScale(...this.radius).invert(),ru.center.set(0,0,0),ru.radius=1,cu.copy(e).applyMatrix4(tu),cu.intersectSphere(ru,t)?(tu.makeScale(...this.radius),t.applyMatrix4(tu),t):null}getEastNorthUpFrame(e,t,n,r){return n.isMatrix4&&(r=n,n=0),this.getEastNorthUpAxes(e,t,su,au,ou),this.getCartographicToPosition(e,t,n,lu),r.makeBasis(su,au,ou).setPosition(lu)}getOrientedEastNorthUpFrame(e,t,n,r,i,s,a){return this.getObjectFrame(e,t,n,r,i,s,a,0)}getObjectFrame(e,t,n,r,i,s,a,o=2){return this.getEastNorthUpFrame(e,t,n,tu),iu.set(i,s,-r,"ZXY"),a.makeRotationFromEuler(iu).premultiply(tu),1===o?(iu.set(Math.PI/2,0,0,"XYZ"),nu.makeRotationFromEuler(iu),a.multiply(nu)):2===o&&(iu.set(-Math.PI/2,0,Math.PI,"XYZ"),nu.makeRotationFromEuler(iu),a.multiply(nu)),a}getCartographicFromObjectFrame(e,t,n=2){return 1===n?(iu.set(-Math.PI/2,0,0,"XYZ"),nu.makeRotationFromEuler(iu).premultiply(e)):2===n?(iu.set(-Math.PI/2,0,Math.PI,"XYZ"),nu.makeRotationFromEuler(iu).premultiply(e)):nu.copy(e),lu.setFromMatrixPosition(nu),this.getPositionToCartographic(lu,t),this.getEastNorthUpFrame(t.lat,t.lon,0,tu).invert(),nu.premultiply(tu),iu.setFromRotationMatrix(nu,"ZXY"),t.azimuth=-iu.z,t.elevation=iu.x,t.roll=iu.y,t}getEastNorthUpAxes(e,t,n,r,i,s=lu){this.getCartographicToPosition(e,t,0,s),this.getCartographicToNormal(e,t,i),n.set(-s.y,s.x,0).normalize(),r.crossVectors(i,n).normalize()}getCartographicToPosition(e,t,n,r){this.getCartographicToNormal(e,t,Zc);let i=this.radius;Jc.copy(Zc),Jc.x*=i.x**2,Jc.y*=i.y**2,Jc.z*=i.z**2;let s=Math.sqrt(Zc.dot(Jc));return Jc.divideScalar(s),r.copy(Jc).addScaledVector(Zc,n)}getPositionToCartographic(e,t){this.getPositionToSurfacePoint(e,Jc),this.getPositionToNormal(Jc,Zc);let n=eu.subVectors(e,Jc);return t.lon=Math.atan2(Zc.y,Zc.x),t.lat=Math.asin(Zc.z),t.height=Math.sign(n.dot(e))*n.length(),t}getCartographicToNormal(e,t,n){return Qc.set(1,function(e){return-e+Math.PI/2}(e),t),n.setFromSpherical(Qc).normalize(),function(e){let{x:t,y:n,z:r}=e;e.x=r,e.y=t,e.z=n}(n),n}getPositionToNormal(e,t){let n=this.radius;return t.copy(e),t.x/=n.x**2,t.y/=n.y**2,t.z/=n.z**2,t.normalize(),t}getPositionToSurfacePoint(e,t){let n=this.radius,r=1/n.x**2,i=1/n.y**2,s=1/n.z**2,a=e.x*e.x*r,o=e.y*e.y*i,l=e.z*e.z*s,c=a+o+l,u=Math.sqrt(1/c),h=Jc.copy(e).multiplyScalar(u);if(c<.1)return isFinite(u)?t.copy(h):null;let d,p,m,f,g,x,y,v,b,w,T,S=eu.set(h.x*r*2,h.y*i*2,h.z*s*2),_=(1-u)*e.length()/(.5*S.length()),M=0;do{_-=M,m=1/(1+_*r),f=1/(1+_*i),g=1/(1+_*s),x=m*m,y=f*f,v=g*g,b=x*m,w=y*f,T=v*g,d=a*x+o*y+l*v-1,p=a*b*r+o*w*i+l*T*s,M=d/(-2*p)}while(Math.abs(d)>1e-12);return t.set(e.x*m,e.y*f,e.z*g)}calculateHorizonDistance(e,t){let n=this.calculateEffectiveRadius(e);return Math.sqrt(2*n*t+t**2)}calculateEffectiveRadius(e){let t=this.radius.x,n=1-this.radius.z**2/t**2,i=e*r.MathUtils.DEG2RAD,s=Math.sin(i)**2;return t/Math.sqrt(1-n*s)}getPositionElevation(e){this.getPositionToSurfacePoint(e,Jc);let t=eu.subVectors(e,Jc);return Math.sign(t.dot(e))*t.length()}closestPointToRayEstimate(e,t){return this.intersectRay(e,t)?t:(tu.makeScale(...this.radius).invert(),cu.copy(e).applyMatrix4(tu),Jc.set(0,0,0),cu.closestPointToPoint(Jc,t).normalize(),tu.makeScale(...this.radius),t.applyMatrix4(tu))}copy(e){return this.radius.copy(e.radius),this}clone(){return(new this.constructor).copy(this)}},hu=new uu(Nl,Nl,$l);hu.name="WGS84 Earth";var du=new r.Vector3,pu=new r.Vector3,mu=new r.Vector3,fu=new r.Vector3,gu=new r.Quaternion,xu=new r.Vector3,yu=new r.Matrix4,vu=new r.Matrix4,bu=new r.Vector3,wu=new r.Matrix4,Tu=new r.Quaternion,Su={};function _u(e,t,n,r){if(e=e/n*2-1,t=t/n*2-1,r.x=e,r.y=t,r.z=1-Math.abs(e)-Math.abs(t),r.z<0){let e=r.x;r.x=(1-Math.abs(r.y))*(e>=0?1:-1),r.y=(1-Math.abs(e))*(r.y>=0?1:-1)}return r.normalize(),r}var Mu=class extends Mc{constructor(e=r.DefaultLoadingManager){super(),this.manager=e,this.adjustmentTransform=new r.Matrix4,this.ellipsoid=hu.clone()}resolveExternalURL(e){return this.manager.resolveURL(super.resolveExternalURL(e))}parse(e){return super.parse(e).then((e=>{let{featureTable:t,batchTable:n}=e,i=e.glbBytes.slice().buffer;return new Promise(((s,a)=>{let o=this.fetchOptions,l=this.manager,c=l.getHandler("path.gltf")||new rt(l);"include"===o.credentials&&"cors"===o.mode&&c.setCrossOrigin("use-credentials"),"credentials"in o&&c.setWithCredentials("include"===o.credentials),o.headers&&c.setRequestHeader(o.headers);let u=e.gltfWorkingPath??this.workingPath;/[\\/]$/.test(u)||(u+="/");let h=this.adjustmentTransform;c.parse(i,u,(e=>{let i=t.getData("INSTANCES_LENGTH"),a=t.getData("POSITION",i,"FLOAT","VEC3"),o=t.getData("POSITION_QUANTIZED",i,"UNSIGNED_SHORT","VEC3"),l=t.getData("QUANTIZED_VOLUME_OFFSET",1,"FLOAT","VEC3"),c=t.getData("QUANTIZED_VOLUME_SCALE",1,"FLOAT","VEC3"),u=t.getData("NORMAL_UP",i,"FLOAT","VEC3"),d=t.getData("NORMAL_RIGHT",i,"FLOAT","VEC3"),p=t.getData("NORMAL_UP_OCT32P",i,"UNSIGNED_SHORT","VEC2"),m=t.getData("NORMAL_RIGHT_OCT32P",i,"UNSIGNED_SHORT","VEC2"),f=t.getData("SCALE_NON_UNIFORM",i,"FLOAT","VEC3"),g=t.getData("SCALE",i,"FLOAT","SCALAR"),x=t.getData("RTC_CENTER",1,"FLOAT","VEC3"),y=t.getData("EAST_NORTH_UP");if(!a&&o){a=new Float32Array(3*i);for(let e=0;e<i;e++)a[3*e+0]=l[0]+o[3*e+0]/65535*c[0],a[3*e+1]=l[1]+o[3*e+1]/65535*c[1],a[3*e+2]=l[2]+o[3*e+2]/65535*c[2]}let v=new r.Vector3;for(let t=0;t<i;t++)v.x+=a[3*t+0]/i,v.y+=a[3*t+1]/i,v.z+=a[3*t+2]/i;let b=[],w=[];e.scene.updateMatrixWorld(),e.scene.traverse((e=>{if(e.isMesh){w.push(e);let{geometry:t,material:n}=e,s=new r.InstancedMesh(t,n,i);s.position.copy(v),x&&(s.position.x+=x[0],s.position.y+=x[1],s.position.z+=x[2]),b.push(s)}}));for(let t=0;t<i;t++){fu.set(a[3*t+0]-v.x,a[3*t+1]-v.y,a[3*t+2]-v.z),gu.identity(),u&&d?(pu.set(u[3*t+0],u[3*t+1],u[3*t+2]),mu.set(d[3*t+0],d[3*t+1],d[3*t+2]),du.crossVectors(mu,pu).normalize(),yu.makeBasis(mu,pu,du),gu.setFromRotationMatrix(yu)):p&&m&&(_u(p[2*t+0],p[2*t+1],65535,pu),_u(m[2*t+0],m[2*t+1],65535,mu),du.crossVectors(mu,pu).normalize(),yu.makeBasis(mu,pu,du),gu.setFromRotationMatrix(yu)),xu.set(1,1,1),f&&xu.set(f[3*t+0],f[3*t+1],f[3*t+2]),g&&xu.multiplyScalar(g[t]);for(let e=0,n=b.length;e<n;e++){let n=b[e];Tu.copy(gu),y&&(n.updateMatrixWorld(),bu.copy(fu).applyMatrix4(n.matrixWorld),this.ellipsoid.getPositionToCartographic(bu,Su),this.ellipsoid.getEastNorthUpFrame(Su.lat,Su.lon,wu),Tu.setFromRotationMatrix(wu)),yu.compose(fu,Tu,xu).multiply(h);let r=w[e];vu.multiplyMatrices(yu,r.matrixWorld),n.setMatrixAt(t,vu)}}e.scene.clear(),e.scene.add(...b),e.batchTable=n,e.featureTable=t,e.scene.batchTable=n,e.scene.featureTable=t,s(e)}),a)}))}))}},Au=class extends Ec{constructor(e=r.DefaultLoadingManager){super(),this.manager=e,this.adjustmentTransform=new r.Matrix4,this.ellipsoid=hu.clone()}parse(e){let t=super.parse(e),{manager:n,ellipsoid:i,adjustmentTransform:s}=this,a=[];for(let r in t.tiles){let{type:e,buffer:o}=t.tiles[r];switch(e){case"b3dm":{let e=o.slice(),t=new Hc(n);t.workingPath=this.workingPath,t.fetchOptions=this.fetchOptions,t.adjustmentTransform.copy(s);let r=t.parse(e.buffer);a.push(r);break}case"pnts":{let e=o.slice(),t=new Kc(n);t.workingPath=this.workingPath,t.fetchOptions=this.fetchOptions;let r=t.parse(e.buffer);a.push(r);break}case"i3dm":{let e=o.slice(),t=new Mu(n);t.workingPath=this.workingPath,t.fetchOptions=this.fetchOptions,t.ellipsoid.copy(i),t.adjustmentTransform.copy(s);let r=t.parse(e.buffer);a.push(r);break}}}return Promise.all(a).then((e=>{let t=new r.Group;return e.forEach((e=>{t.add(e.scene)})),{tiles:e,scene:t}}))}},Eu=new r.Matrix4,Cu=class extends r.Group{constructor(e){super(),this.isTilesGroup=!0,this.name="TilesRenderer.TilesGroup",this.tilesRenderer=e,this.matrixWorldInverse=new r.Matrix4}raycast(e,t){return this.tilesRenderer.raycast(e,t),!1}updateMatrixWorld(e){if(this.matrixAutoUpdate&&this.updateMatrix(),this.matrixWorldNeedsUpdate||e){null===this.parent?Eu.copy(this.matrix):Eu.multiplyMatrices(this.parent.matrixWorld,this.matrix),this.matrixWorldNeedsUpdate=!1;let e=Eu.elements,t=this.matrixWorld.elements,n=!1;for(let r=0;r<16;r++){let i=e[r],s=t[r];if(Math.abs(i-s)>2**-52){n=!0;break}}if(n){this.matrixWorld.copy(Eu),this.matrixWorldInverse.copy(Eu).invert();let e=this.children;for(let i=0,s=e.length;i<s;i++)e[i].updateMatrixWorld();let{tilesRenderer:t}=this,{activeTiles:n,visibleTiles:r}=t;n.forEach((e=>{r.has(e)||e.engineData.scene.updateMatrixWorld(!0)}))}}}updateWorldMatrix(e,t){this.parent&&e&&this.parent.updateWorldMatrix(e,!1),this.updateMatrixWorld(!0)}},Ru=new r.Ray;function Du(e,t,n,r,i=null){if(!function(e){return"traversal"in e}(t))return;let{group:s,activeTiles:a}=e,{boundingVolume:o}=t.engineData;if(null===i&&(i=Ru).copy(n.ray).applyMatrix4(s.matrixWorldInverse),!t.traversal.used||!o.intersectsRay(i))return;a.has(t)&&function(e,t,n,r){let{scene:i}=e.engineData;n.invokeOnePlugin((n=>n.raycastTile&&n.raycastTile(e,i,t,r)))||t.intersectObject(i,!0,r)}(t,n,e,r);let l=t.children;for(let c=0,u=l.length;c<u;c++)Du(e,l[c],n,r,i)}var ku=new r.Vector3,Iu=new r.Vector3,Pu=new r.Vector3,Lu=new r.Ray,Uu=class{constructor(e=new r.Box3,t=new r.Matrix4){this.box=e.clone(),this.transform=t.clone(),this.inverseTransform=new r.Matrix4,this.points=Array(8).fill().map((()=>new r.Vector3)),this.planes=[,,,,,,].fill().map((()=>new r.Plane))}copy(e){return this.box.copy(e.box),this.transform.copy(e.transform),this.update(),this}clone(){return(new this.constructor).copy(this)}clampPoint(e,t){return t.copy(e).applyMatrix4(this.inverseTransform).clamp(this.box.min,this.box.max).applyMatrix4(this.transform)}distanceToPoint(e){return this.clampPoint(e,Pu).distanceTo(e)}containsPoint(e){return Pu.copy(e).applyMatrix4(this.inverseTransform),this.box.containsPoint(Pu)}intersectsRay(e){return Lu.copy(e).applyMatrix4(this.inverseTransform),Lu.intersectsBox(this.box)}intersectRay(e,t){return Lu.copy(e).applyMatrix4(this.inverseTransform),Lu.intersectBox(this.box,t)?(t.applyMatrix4(this.transform),t):null}update(){let{points:e,inverseTransform:t,transform:n,box:r}=this;t.copy(n).invert();let{min:i,max:s}=r,a=0;for(let o=-1;o<=1;o+=2)for(let t=-1;t<=1;t+=2)for(let r=-1;r<=1;r+=2)e[a].set(o<0?i.x:s.x,t<0?i.y:s.y,r<0?i.z:s.z).applyMatrix4(n),a++;this.updatePlanes()}updatePlanes(){ku.copy(this.box.min).applyMatrix4(this.transform),Iu.copy(this.box.max).applyMatrix4(this.transform),Pu.set(0,0,1).transformDirection(this.transform),this.planes[0].setFromNormalAndCoplanarPoint(Pu,ku),this.planes[1].setFromNormalAndCoplanarPoint(Pu,Iu).negate(),Pu.set(0,1,0).transformDirection(this.transform),this.planes[2].setFromNormalAndCoplanarPoint(Pu,ku),this.planes[3].setFromNormalAndCoplanarPoint(Pu,Iu).negate(),Pu.set(1,0,0).transformDirection(this.transform),this.planes[4].setFromNormalAndCoplanarPoint(Pu,ku),this.planes[5].setFromNormalAndCoplanarPoint(Pu,Iu).negate()}intersectsSphere(e){return this.clampPoint(e.center,Pu),Pu.distanceToSquared(e.center)<=e.radius*e.radius}intersectsFrustum(e){return this._intersectsPlaneShape(e.planes,e.points)}intersectsOBB(e){return this._intersectsPlaneShape(e.planes,e.points)}_intersectsPlaneShape(e,t){let n=this.points,r=this.planes;for(let i=0;i<6;i++){let t=e[i],r=-1/0;for(let e=0;e<8;e++){let i=n[e],s=t.distanceToPoint(i);r=r<s?s:r}if(r<0)return!1}for(let i=0;i<6;i++){let e=r[i],n=-1/0;for(let r=0;r<8;r++){let i=t[r],s=e.distanceToPoint(i);n=n<s?s:n}if(n<0)return!1}return!0}},Fu=Math.PI,zu=Fu/2,Bu=new r.Vector3,Vu=new r.Vector3,Ou=new r.Vector3,Nu=new r.Vector3,$u=new r.Matrix4,Gu=new r.Box3,qu=new r.Matrix4;function Hu(e,t){t.radius=Math.max(t.radius,e.distanceToSquared(t.center))}function ju(e){return e.x!==e.y}var Wu=class extends uu{constructor(e=1,t=1,n=1,r=-zu,i=zu,s=0,a=2*Fu,o=0,l=0){super(e,t,n),this.latStart=r,this.latEnd=i,this.lonStart=s,this.lonEnd=a,this.heightStart=o,this.heightEnd=l}getBoundingBox(e,t){ju(this.radius);let n,{latStart:r,latEnd:i,lonStart:s,lonEnd:a,heightStart:o,heightEnd:l}=this,c=.5*(r+i),u=.5*(s+a),h=r>0,d=i<0;n=h?r:d?i:0;let{min:p,max:m}=e;p.setScalar(1/0),m.setScalar(-1/0),a-s<=Fu?(this.getCartographicToNormal(c,u,Ou),Vu.set(0,0,1),Bu.crossVectors(Vu,Ou).normalize(),Vu.crossVectors(Ou,Bu).normalize(),t.makeBasis(Bu,Vu,Ou),$u.copy(t).invert(),this.getCartographicToPosition(n,s,l,Nu).applyMatrix4($u),m.x=Math.abs(Nu.x),p.x=-m.x,this.getCartographicToPosition(i,s,l,Nu).applyMatrix4($u),m.y=Nu.y,this.getCartographicToPosition(i,u,l,Nu).applyMatrix4($u),m.y=Math.max(Nu.y,m.y),this.getCartographicToPosition(r,s,l,Nu).applyMatrix4($u),p.y=Nu.y,this.getCartographicToPosition(r,u,l,Nu).applyMatrix4($u),p.y=Math.min(Nu.y,p.y),this.getCartographicToPosition(c,u,l,Nu).applyMatrix4($u),m.z=Nu.z,this.getCartographicToPosition(r,s,o,Nu).applyMatrix4($u),p.z=Nu.z,this.getCartographicToPosition(i,s,o,Nu).applyMatrix4($u),p.z=Math.min(Nu.z,p.z)):(this.getCartographicToPosition(n,u,l,Ou),Ou.z=0,Ou.length()<1e-10?Ou.set(1,0,0):Ou.normalize(),Vu.set(0,0,1),Bu.crossVectors(Ou,Vu).normalize(),t.makeBasis(Bu,Vu,Ou),$u.copy(t).invert(),this.getCartographicToPosition(n,u+zu,l,Nu).applyMatrix4($u),m.x=Math.abs(Nu.x),p.x=-m.x,this.getCartographicToPosition(i,0,d?o:l,Nu).applyMatrix4($u),m.y=Nu.y,this.getCartographicToPosition(r,0,h?o:l,Nu).applyMatrix4($u),p.y=Nu.y,this.getCartographicToPosition(n,u,l,Nu).applyMatrix4($u),m.z=Nu.z,this.getCartographicToPosition(n,a,l,Nu).applyMatrix4($u),p.z=Nu.z),e.getCenter(Nu),e.min.sub(Nu).multiplyScalar(1.0000000000001),e.max.sub(Nu).multiplyScalar(1.0000000000001),Nu.applyMatrix4(t),t.setPosition(Nu)}getBoundingSphere(e){ju(this.radius),this.getBoundingBox(Gu,qu),e.center.setFromMatrixPosition(qu),e.radius=0;let t,{latStart:n,latEnd:r,lonStart:i,lonEnd:s,heightStart:a,heightEnd:o}=this,l=.5*(n+r),c=.5*(i+s);t=n>0?n:r<0?r:0,this.getCartographicToPosition(t,i,o,Nu),Hu(Nu,e),this.getCartographicToPosition(r,i,o,Nu),Hu(Nu,e),this.getCartographicToPosition(r,c,o,Nu),Hu(Nu,e),this.getCartographicToPosition(n,i,o,Nu),Hu(Nu,e),this.getCartographicToPosition(n,c,o,Nu),Hu(Nu,e),this.getCartographicToPosition(l,c,o,Nu),Hu(Nu,e),this.getCartographicToPosition(n,i,a,Nu),Hu(Nu,e),s-i>Fu&&(this.getCartographicToPosition(t,c+Fu,o,Nu),Hu(Nu,e)),e.radius=1.0000000000001*Math.sqrt(e.radius)}},Xu=new r.Vector3,Yu=new r.Vector3,Ku=new r.Vector3,Qu=new r.Vector3,Zu=new r.Vector3,Ju=class{constructor(){this.sphere=null,this.obb=null,this.region=null,this.regionObb=null}intersectsRay(e){let t=this.sphere,n=this.obb||this.regionObb;return!(t&&!e.intersectsSphere(t)||n&&!n.intersectsRay(e))}intersectRay(e,t=null){let n=this.sphere,r=this.obb||this.regionObb,i=-1/0,s=-1/0;n&&e.intersectSphere(n,Qu)&&(i=n.containsPoint(e.origin)?0:e.origin.distanceToSquared(Qu)),r&&r.intersectRay(e,Zu)&&(s=r.containsPoint(e.origin)?0:e.origin.distanceToSquared(Zu));let a=Math.max(i,s);return a===-1/0?null:(e.at(Math.sqrt(a),t),t)}distanceToPoint(e){let t=this.sphere,n=this.obb||this.regionObb,r=-1/0,i=-1/0;return t&&(r=Math.max(t.distanceToPoint(e),0)),n&&(i=n.distanceToPoint(e)),r>i?r:i}intersectsFrustum(e){let t=this.obb||this.regionObb,n=this.sphere;return!(n&&!e.intersectsSphere(n)||t&&!t.intersectsFrustum(e))&&!(!n&&!t)}intersectsSphere(e){let t=this.obb||this.regionObb,n=this.sphere;return!(n&&!n.intersectsSphere(e)||t&&!t.intersectsSphere(e))&&!(!n&&!t)}intersectsOBB(e){let t=this.obb||this.regionObb,n=this.sphere;return!(n&&!e.intersectsSphere(n)||t&&!t.intersectsOBB(e))&&!(!n&&!t)}getOBB(e,t){let n=this.obb||this.regionObb;n?(e.copy(n.box),t.copy(n.transform)):(this.getAABB(e),t.identity())}getAABB(e){if(this.sphere)this.sphere.getBoundingBox(e);else{let t=this.obb||this.regionObb;e.copy(t.box).applyMatrix4(t.transform)}}getSphere(e){if(this.sphere)e.copy(this.sphere);else if(this.region)this.region.getBoundingSphere(e);else{let t=this.obb||this.regionObb;t.box.getBoundingSphere(e),e.applyMatrix4(t.transform)}}setObbData(e,t){let n=new Uu;Xu.set(e[3],e[4],e[5]),Yu.set(e[6],e[7],e[8]),Ku.set(e[9],e[10],e[11]);let r=Xu.length(),i=Yu.length(),s=Ku.length();Xu.normalize(),Yu.normalize(),Ku.normalize(),0===r&&Xu.crossVectors(Yu,Ku),0===i&&Yu.crossVectors(Xu,Ku),0===s&&Ku.crossVectors(Xu,Yu),n.transform.set(Xu.x,Yu.x,Ku.x,e[0],Xu.y,Yu.y,Ku.y,e[1],Xu.z,Yu.z,Ku.z,e[2],0,0,0,1).premultiply(t),n.box.min.set(-r,-i,-s),n.box.max.set(r,i,s),n.update(),this.obb=n}setSphereData(e,t,n,i,s){let a=new r.Sphere;a.center.set(e,t,n),a.radius=i,a.applyMatrix4(s),this.sphere=a}setRegionData(e,t,n,r,i,s,a){let o=new Wu(...e.radius,n,i,t,r,s,a),l=new Uu;o.getBoundingBox(l.box,l.transform),l.update(),this.region=o,this.regionObb=l}},eh=new r.Matrix3;var th=class extends r.Frustum{constructor(){super(),this.points=Array(8).fill().map((()=>new r.Vector3))}setFromProjectionMatrix(...e){return super.setFromProjectionMatrix(...e),this.calculateFrustumPoints(),this}calculateFrustumPoints(){let{planes:e,points:t}=this;[[e[0],e[3],e[4]],[e[1],e[3],e[4]],[e[0],e[2],e[4]],[e[1],e[2],e[4]],[e[0],e[3],e[5]],[e[1],e[3],e[5]],[e[0],e[2],e[5]],[e[1],e[2],e[5]]].forEach(((e,n)=>{!function(e,t,n,r){let i=eh.set(e.normal.x,e.normal.y,e.normal.z,t.normal.x,t.normal.y,t.normal.z,n.normal.x,n.normal.y,n.normal.z);r.set(-e.constant,-t.constant,-n.constant),r.applyMatrix3(i.invert())}(e[0],e[1],e[2],t[n])}))}};function nh(e,t,n,i){try{return r.TextureUtils.getByteLength(e,t,n,i)}catch{return 0}}function rh(e){var t,n;if(!e)return 0;if(e.isExternalTexture)return(null==(t=e.userData)?void 0:t.byteLength)??0;let{format:r,type:i,image:s,mipmaps:a}=e;if(e.isCompressedTexture&&Array.isArray(a)&&a.length>0){let e=0;for(let t of a)(null==(n=null==t?void 0:t.data)?void 0:n.byteLength)?e+=t.data.byteLength:e+=nh(t.width,t.height,r,i);return e}if(!s)return 0;let o=nh(s.width,s.height,r,i);return o*=e.generateMipmaps?4/3:1,o}var ih=Symbol("INITIAL_FRUSTUM_CULLED"),sh=new r.Matrix4,ah=new r.Vector3,oh=new r.Vector2,lh=new r.Vector3(1,0,0),ch=new r.Vector3(0,1,0),uh=()=>null;function hh(e,t){e.traverse((e=>{e.frustumCulled=e[ih]&&t}))}var dh=class extends mc{get autoDisableRendererCulling(){return this._autoDisableRendererCulling}set autoDisableRendererCulling(e){this._autoDisableRendererCulling!==e&&(super._autoDisableRendererCulling=e,this.forEachLoadedModel((t=>{hh(t,!e)})))}constructor(...e){super(...e),this.accelerateRaycast=!0,this.group=new Cu(this),this.ellipsoid=hu.clone(),this.cameras=[],this.cameraMap=new Map,this.cameraInfo=[],this._upRotationMatrix=new r.Matrix4,this._bytesUsed=new WeakMap,this._autoDisableRendererCulling=!0,this.manager=new r.LoadingManager,this._listeners={}}addEventListener(e,t){r.EventDispatcher.prototype.addEventListener.call(this,e,t)}hasEventListener(e,t){return r.EventDispatcher.prototype.hasEventListener.call(this,e,t)}removeEventListener(e,t){r.EventDispatcher.prototype.removeEventListener.call(this,e,t)}dispatchEvent(e){r.EventDispatcher.prototype.dispatchEvent.call(this,e)}getBoundingBox(e){if(!this.root)return!1;let t=this.root.engineData.boundingVolume;return!!t&&(t.getAABB(e),!0)}getOrientedBoundingBox(e,t){if(!this.root)return!1;let n=this.root.engineData.boundingVolume;return!!n&&(n.getOBB(e,t),!0)}getBoundingSphere(e){if(!this.root)return!1;let t=this.root.engineData.boundingVolume;return!!t&&(t.getSphere(e),!0)}forEachLoadedModel(e){this.traverse((t=>{let n=t.engineData&&t.engineData.scene;n&&e(n,t)}),null,!1)}raycast(e,t){if(this.root)if(this.accelerateRaycast)Du(this,this.root,e,t);else{let n=e.firstHitOnly?[]:t;for(let t of this.activeTiles){let{scene:r}=t.engineData;this.invokeOnePlugin((i=>i.raycastTile&&i.raycastTile(t,r,e,n)))||e.intersectObject(r,!0,n)}e.firstHitOnly&&n.length>0&&(n.sort(((e,t)=>e.distance-t.distance)),t.push(n[0]))}}hasCamera(e){return this.cameraMap.has(e)}setCamera(e){let t=this.cameras,n=this.cameraMap;return!n.has(e)&&(n.set(e,new r.Vector2),t.push(e),this.dispatchEvent({type:"add-camera",camera:e}),!0)}setResolution(e,t,n){let r=this.cameraMap;if(!r.has(e))return!1;let i=t.isVector2?t.x:t,s=t.isVector2?t.y:n,a=r.get(e);return(a.width!==i||a.height!==s)&&(a.set(i,s),this.dispatchEvent({type:"camera-resolution-change"})),!0}getResolution(e,t){let n=this.cameraMap.get(e);return n?t.copy(n):null}setResolutionFromRenderer(e,t){return t.getSize(oh),this.setResolution(e,oh.x,oh.y)}deleteCamera(e){let t=this.cameras,n=this.cameraMap;if(n.has(e)){let r=t.indexOf(e);return t.splice(r,1),n.delete(e),this.dispatchEvent({type:"delete-camera",camera:e}),!0}return!1}loadRootTileset(...e){return super.loadRootTileset(...e).then((e=>{let{asset:t,extensions:n={}}=e;switch((t&&t.gltfUpAxis||"y").toLowerCase()){case"x":this._upRotationMatrix.makeRotationAxis(ch,-Math.PI/2);break;case"y":this._upRotationMatrix.makeRotationAxis(lh,Math.PI/2)}if("3DTILES_ellipsoid"in n){let e=n["3DTILES_ellipsoid"],{ellipsoid:t}=this;t.name=e.body,e.radii?t.radius.set(...e.radii):t.radius.set(1,1,1)}return e}))}prepareForTraversal(){let e=this.group,t=this.cameras,n=this.cameraMap,i=this.cameraInfo;for(;i.length>t.length;)i.pop();for(;i.length<t.length;)i.push({frustum:new th,isOrthographic:!1,sseDenominator:-1,position:new r.Vector3,invScale:-1,pixelSize:0});ah.setFromMatrixScale(e.matrixWorldInverse),Math.abs(Math.max(ah.x-ah.y,ah.x-ah.z));for(let r=0,s=i.length;r<s;r++){let s=t[r],a=i[r],o=a.frustum,l=a.position,c=n.get(s);0===c.width||c.height;let u=s.projectionMatrix.elements;if(a.isOrthographic=1===u[15],a.isOrthographic){let e=2/u[0],t=2/u[5];a.pixelSize=Math.max(t/c.height,e/c.width)}else a.sseDenominator=2/u[5]/c.height;sh.copy(e.matrixWorld),sh.premultiply(s.matrixWorldInverse),sh.premultiply(s.projectionMatrix),o.setFromProjectionMatrix(sh,s.coordinateSystem,s.reversedDepth),l.set(0,0,0),l.applyMatrix4(s.matrixWorld),l.applyMatrix4(e.matrixWorldInverse)}}update(){if(super.update(),0===this.cameras.length&&this.root){let e=!1;this.invokeAllPlugins((t=>e||(e=!(t===this||!t.calculateTileViewError))))}}preprocessNode(e,t,n=null){super.preprocessNode(e,t,n);let i=new r.Matrix4;if(e.transform){let t=e.transform;for(let e=0;e<16;e++)i.elements[e]=t[e]}n&&i.premultiply(n.engineData.transform);let s=(new r.Matrix4).copy(i).invert(),a=new Ju;"sphere"in e.boundingVolume&&a.setSphereData(...e.boundingVolume.sphere,i),"box"in e.boundingVolume&&a.setObbData(e.boundingVolume.box,i),"region"in e.boundingVolume&&a.setRegionData(this.ellipsoid,...e.boundingVolume.region),e.engineData.transform=i,e.engineData.transformInverse=s,e.engineData.boundingVolume=a,e.engineData.geometry=null,e.engineData.materials=null,e.engineData.textures=null,e.toJSON=uh}async parseTile(e,t,n,i,s){let a=t.engineData,o=yc(i),l=this.fetchOptions,c=this.manager,u=null,h=a.transform,d=this._upRotationMatrix,p=(fc(e)||n).toLowerCase();switch(p){case"b3dm":{let t=new Hc(c);t.workingPath=o,t.fetchOptions=l,t.adjustmentTransform.copy(d),u=t.parse(e);break}case"pnts":{let t=new Kc(c);t.workingPath=o,t.fetchOptions=l,u=t.parse(e);break}case"i3dm":{let t=new Mu(c);t.workingPath=o,t.fetchOptions=l,t.adjustmentTransform.copy(d),t.ellipsoid.copy(this.ellipsoid),u=t.parse(e);break}case"cmpt":{let t=new Au(c);t.workingPath=o,t.fetchOptions=l,t.adjustmentTransform.copy(d),t.ellipsoid.copy(this.ellipsoid),u=t.parse(e).then((e=>e.scene));break}case"gltf":case"glb":{let t=c.getHandler("path.gltf")||c.getHandler("path.glb")||new rt(c);t.setWithCredentials("include"===l.credentials),t.setRequestHeader(l.headers||{}),"include"===l.credentials&&"cors"===l.mode&&t.setCrossOrigin("use-credentials");let n=t.resourcePath||t.path||o;!/[\\/]$/.test(n)&&n.length&&(n+="/"),u=t.parseAsync(e,n).then((e=>{e.scene=e.scene||new r.Group;let{scene:t}=e;return t.updateMatrix(),t.matrix.multiply(d).decompose(t.position,t.quaternion,t.scale),e}));break}default:u=this.invokeOnePlugin((r=>r.parseToMesh&&r.parseToMesh(e,t,n,i,s)))}let m,f,g=await u;if(null===g)throw Error(`TilesRenderer: Content type "${p}" not supported.`);g.isObject3D?(m=g,f=null):(m=g.scene,f=g),m.updateMatrix(),m.matrix.premultiply(h),m.matrix.decompose(m.position,m.quaternion,m.scale),await this.invokeAllPlugins((e=>e.processTileModel&&e.processTileModel(m,t))),m.traverse((e=>{e[ih]=e.frustumCulled,e.userData.tile=t})),hh(m,!this.autoDisableRendererCulling);let x=[],y=[],v=[];if(m.traverse((e=>{if(e.geometry&&y.push(e.geometry),e.material){let t=e.material;x.push(e.material);for(let e in t){let n=t[e];n&&n.isTexture&&v.push(n)}}})),s.aborted)for(let r=0,b=v.length;r<b;r++){let e=v[r];e.image instanceof ImageBitmap&&e.image.close(),e.dispose()}else a.materials=x,a.geometry=y,a.textures=v,a.scene=m,a.metadata=f}disposeTile(e){super.disposeTile(e);let t=e.engineData;if(t.scene){let e=t.materials,n=t.geometry,r=t.textures,i=t.scene.parent;t.scene.traverse((e=>{e.userData.meshFeatures&&e.userData.meshFeatures.dispose(),e.userData.structuralMetadata&&e.userData.structuralMetadata.dispose()}));for(let t=0,s=n.length;t<s;t++)n[t].dispose();for(let t=0,s=e.length;t<s;t++)e[t].dispose();for(let t=0,s=r.length;t<s;t++){let e=r[t];e.image instanceof ImageBitmap&&e.image.close(),e.dispose()}i&&i.remove(t.scene),t.scene=null,t.materials=null,t.textures=null,t.geometry=null,t.metadata=null}}setTileActive(e,t){super.setTileActive(e,t);let n=e.engineData.scene;n&&(t?(n.parent=this.group,n.updateMatrixWorld(!0)):n.parent=null)}setTileVisible(e,t){let n=e.engineData.scene,{activeTiles:r,group:i}=this;n&&(t?i.add(n):(i.remove(n),r.has(e)&&(n.parent=i))),super.setTileVisible(e,t)}calculateBytesUsed(e,t){let n=this._bytesUsed;return!n.has(e)&&t&&n.set(e,function(e){let t=new Set,n=0;return e.traverse((e=>{if(e.geometry&&!t.has(e.geometry)&&(n+=function(e){let t=0;for(const r in e.attributes){const n=e.getAttribute(r);t+=n.count*n.itemSize*n.array.BYTES_PER_ELEMENT}const n=e.getIndex();return t+=n?n.count*n.itemSize*n.array.BYTES_PER_ELEMENT:0,t}(e.geometry),t.add(e.geometry)),e.material){let r=e.material;for(let e in r){let i=r[e];i&&i.isTexture&&!t.has(i)&&(n+=rh(i),t.add(i))}}})),n}(t)),n.get(e)??null}calculateTileViewError(e,t){let n=e.engineData,r=this.cameras,i=this.cameraInfo,s=n.boundingVolume,a=!1,o=0,l=1/0,c=0,u=1/0;for(let h=0,d=r.length;h<d;h++){let t,n,r=i[h];if(r.isOrthographic){let i=r.pixelSize;t=e.geometricError/i,n=1/0}else{let i=r.sseDenominator;n=s.distanceToPoint(r.position),t=0===n?1/0:e.geometricError/(n*i)}let d=i[h].frustum;s.intersectsFrustum(d)&&(a=!0,o=Math.max(o,t),l=Math.min(l,n)),c=Math.max(c,t),u=Math.min(u,n)}a?(t.inView=!0,t.error=o,t.distanceFromCamera=l):(t.inView=!1,t.error=c,t.distanceFromCamera=u)}dispose(){super.dispose(),this.group.removeFromParent()}},ph=class{constructor(e={}){let{apiToken:t,autoRefreshToken:n=!1}=e;this.apiToken=t,this.autoRefreshToken=n,this.authURL=null,this._tokenRefreshPromise=null,this._bearerToken=null,this._bearerHostname=null}async fetch(e,t){await this._tokenRefreshPromise;let n={...t},r=null!==this._bearerHostname&&new URL(e).host===this._bearerHostname;r&&(n.headers={...n.headers,Authorization:this._bearerToken});let i=await fetch(e,n);return r&&i.status>=400&&i.status<=499&&this.autoRefreshToken?(await this.refreshToken(t),n.headers.Authorization=this._bearerToken,fetch(e,n)):i}refreshToken(e){if(null===this._tokenRefreshPromise){let t=new URL(this.authURL);t.searchParams.set("access_token",this.apiToken),this._tokenRefreshPromise=fetch(t,e).then((e=>{if(!e.ok)throw Error(`CesiumIonAuthPlugin: Failed to load data with error code ${e.status}`);return e.json()})).then((e=>(e.accessToken&&e.url&&(this._bearerToken=`Bearer ${e.accessToken}`,this._bearerHostname=new URL(e.url).host),this._tokenRefreshPromise=null,e)))}return this._tokenRefreshPromise}},mh="https://tile.googleapis.com/v1/createSession",fh=class{get isMapTilesSession(){return this.authURL===mh}constructor(e={}){let{apiToken:t,sessionOptions:n=null,autoRefreshToken:r=!1}=e;this.apiToken=t,this.autoRefreshToken=r,this.authURL=mh,this.sessionToken=null,this.sessionOptions=n,this._tokenRefreshPromise=null,this._authHostname=null}async fetch(e,t){null===this.sessionToken&&this.isMapTilesSession&&this.refreshToken(t),await this._tokenRefreshPromise,null===this._authHostname&&(this._authHostname=new URL(this.authURL).host);let n=new URL(e),r=n.host===this._authHostname;r&&(n.searchParams.set("key",this.apiToken),this.sessionToken&&n.searchParams.set("session",this.sessionToken));let i=await fetch(n,t);return r&&i.status>=400&&i.status<=499&&this.autoRefreshToken&&(await this.refreshToken(t),this.sessionToken&&n.searchParams.set("session",this.sessionToken),i=await fetch(n,t)),null!==this.sessionToken||this.isMapTilesSession?i:i.json().then((e=>(this.sessionToken=gh(e),e)))}refreshToken(e){if(null===this._tokenRefreshPromise){let t=new URL(this.authURL);t.searchParams.set("key",this.apiToken);let n={...e};this.isMapTilesSession&&(n.method="POST",n.body=JSON.stringify(this.sessionOptions),n.headers=n.headers||{},n.headers={...n.headers,"Content-Type":"application/json"}),this._tokenRefreshPromise=fetch(t,n).then((e=>{if(!e.ok)throw Error(`GoogleCloudAuth: Failed to load data with error code ${e.status}`);return e.json()})).then((e=>(this.sessionToken=gh(e),this._tokenRefreshPromise=null,e)))}return this._tokenRefreshPromise}};function gh(e){if("session"in e)return e.session;{let t=null;return ac(e.root,(e=>{if(e.content&&e.content.uri){let[,n]=e.content.uri.split("?");return t=new URLSearchParams(n).get("session"),!0}return!1})),t}}var xh=class{constructor(){this.creditsCount={}}_adjustAttributions(e,t){let n=this.creditsCount,r=e.split(/;/g);for(let i=0,s=r.length;i<s;i++){let e=r[i];e in n||(n[e]=0),n[e]+=t?1:-1,n[e]<=0&&delete n[e]}}addAttributions(e){this._adjustAttributions(e,!0)}removeAttributions(e){this._adjustAttributions(e,!1)}toString(){return Object.entries(this.creditsCount).sort(((e,t)=>{let n=e[1];return t[1]-n})).map((e=>e[0])).join("; ")}},yh=class{constructor({apiToken:e,sessionOptions:t=null,autoRefreshToken:n=!1,logoUrl:r=null,useRecommendedSettings:i=!0}){this.name="GOOGLE_CLOUD_AUTH_PLUGIN",this.apiToken=e,this.useRecommendedSettings=i,this.logoUrl=r,this.auth=new fh({apiToken:e,autoRefreshToken:n,sessionOptions:t}),this.tiles=null,this._visibilityChangeCallback=null,this._attributionsManager=new xh,this._logoAttribution={value:"",type:"image",collapsible:!1},this._attribution={value:"",type:"string",collapsible:!0}}init(e){let{useRecommendedSettings:t,auth:n}=this;e.resetFailedTiles(),e.rootURL??(e.rootURL="https://tile.googleapis.com/v1/3dtiles/root.json"),n.sessionOptions||(n.authURL=e.rootURL),t&&!n.isMapTilesSession&&(e.errorTarget=20),this.tiles=e,this._visibilityChangeCallback=({tile:e,visible:t})=>{var n,r;let i=(null==(r=null==(n=e.engineData.metadata)?void 0:n.asset)?void 0:r.copyright)||"";t?this._attributionsManager.addAttributions(i):this._attributionsManager.removeAttributions(i)},e.addEventListener("tile-visibility-change",this._visibilityChangeCallback)}getAttributions(e){this.tiles.visibleTiles.size>0&&(this.logoUrl&&(this._logoAttribution.value=this.logoUrl,e.push(this._logoAttribution)),this._attribution.value=this._attributionsManager.toString(),e.push(this._attribution))}dispose(){this.tiles.removeEventListener("tile-visibility-change",this._visibilityChangeCallback)}async fetchData(e,t){return this.auth.fetch(e,t)}},vh=class{get apiToken(){return this.auth.apiToken}set apiToken(e){this.auth.apiToken=e}get autoRefreshToken(){return this.auth.autoRefreshToken}set autoRefreshToken(e){this.auth.autoRefreshToken=e}constructor(e={}){let{apiToken:t,assetId:n=null,autoRefreshToken:r=!1,useRecommendedSettings:i=!0,assetTypeHandler:s=(e,t,n)=>{}}=e;this.name="CESIUM_ION_AUTH_PLUGIN",this.auth=new ph({apiToken:t,autoRefreshToken:r}),this.assetId=n,this.autoRefreshToken=r,this.useRecommendedSettings=i,this.assetTypeHandler=s,this.tiles=null,this._tileSetVersion=-1,this._attributions=[]}init(e){null!==this.assetId&&(e.rootURL=`https://api.cesium.com/v1/assets/${this.assetId}/endpoint`),this.tiles=e,this.auth.authURL=e.rootURL,e.resetFailedTiles()}loadRootTileset(){return this.auth.refreshToken().then((e=>(this._initializeFromAsset(e),this.tiles.invokeOnePlugin((e=>e!==this&&e.loadRootTileset&&e.loadRootTileset()))))).catch((e=>{this.tiles.dispatchEvent({type:"load-error",tile:null,error:e,url:this.auth.authURL})}))}preprocessURL(e){return e=new URL(e),/^http/.test(e.protocol)&&-1!=this._tileSetVersion&&e.searchParams.set("v",this._tileSetVersion),e.toString()}fetchData(e,t){return null===this.tiles.getPluginByName("GOOGLE_CLOUD_AUTH_PLUGIN")?this.auth.fetch(e,t):null}getAttributions(e){this.tiles.visibleTiles.size>0&&e.push(...this._attributions)}_initializeFromAsset(e){let t=this.tiles;if("externalType"in e){let n=new URL(e.options.url);t.rootURL=e.options.url,t.registerPlugin(new yh({apiToken:n.searchParams.get("key"),autoRefreshToken:this.autoRefreshToken,useRecommendedSettings:this.useRecommendedSettings}))}else{"3DTILES"!==e.type&&this.assetTypeHandler(e.type,t,e),t.rootURL=e.url;let n=new URL(e.url);n.searchParams.has("v")&&-1===this._tileSetVersion&&(this._tileSetVersion=n.searchParams.get("v")),e.attributions&&(this._attributions=e.attributions.map((e=>({value:e.html,type:"html",collapsible:e.collapsible}))))}}};function bh(e){return"OCTREE"===e.implicitTilingData.root.implicitTiling.subdivisionScheme}function wh(e){return bh(e)?8:4}var Th=class{constructor(e,t){this.parent=e,this.children=[],this.geometricError=0,this.boundingVolume=null;let[n,r,i]=function(e,t){if(!e)return[0,0,0];let n=e.implicitTilingData.x,r=e.implicitTilingData.y,i=e.implicitTilingData.z;return[2*n+t%2,2*r+Math.floor(t/2)%2,bh(e)?2*i+Math.floor(t/4)%2:0]}(e,t);this.implicitTilingData={level:e.implicitTilingData.level+1,root:e.implicitTilingData.root,subtreeIdx:t,x:n,y:r,z:i}}static clone(e){return{parent:e.parent,children:[],geometricError:e.geometricError,boundingVolume:e.boundingVolume,implicitTilingData:{...e.implicitTilingData}}}},Sh=class extends vc{constructor(e){super(),this.tile=e,this.rootTile=e.implicitTilingData.root,this.workingPath=null}parseBuffer(e){let t=new DataView(e),n=0;fc(t);n+=4;let r=t.getUint32(n,!0);n+=4;let i=t.getUint32(n,!0);n+=8;let s=t.getUint32(n,!0);n+=8;let a=JSON.parse(xc(new Uint8Array(e,n,i)));return n+=i,{version:r,subtreeJson:a,subtreeByte:e.slice(n,n+s)}}async parse(e){let t=this.parseBuffer(e),n=t.subtreeJson;n.contentAvailabilityHeaders=[].concat(n.contentAvailability);let r=this.preprocessBuffers(n.buffers),i=this.preprocessBufferViews(n.bufferViews,r);this.markActiveBufferViews(n,i);let s=await this.requestActiveBuffers(r,t.subtreeByte),a=this.parseActiveBufferViews(i,s);this.parseAvailability(t,n,a),this.expandSubtree(this.tile,t)}markActiveBufferViews(e,t){let n,r=e.tileAvailability;isNaN(r.bitstream)?isNaN(r.bufferView)||(n=t[r.bufferView]):n=t[r.bitstream],n&&(n.isActive=!0,n.bufferHeader.isActive=!0);let i=e.contentAvailabilityHeaders;for(let a=0;a<i.length;a++)n=void 0,isNaN(i[a].bitstream)?isNaN(i[a].bufferView)||(n=t[i[a].bufferView]):n=t[i[a].bitstream],n&&(n.isActive=!0,n.bufferHeader.isActive=!0);n=void 0;let s=e.childSubtreeAvailability;isNaN(s.bitstream)?isNaN(s.bufferView)||(n=t[s.bufferView]):n=t[s.bitstream],n&&(n.isActive=!0,n.bufferHeader.isActive=!0)}async requestActiveBuffers(e,t){let n=[];for(let s=0;s<e.length;s++){let r=e[s];if(r.isActive)if(r.isExternal){let e=this.parseImplicitURIBuffer(this.tile,this.rootTile.implicitTiling.subtrees.uri,r.uri),t=fetch(e,this.fetchOptions).then((e=>{if(!e.ok)throw Error(`SUBTREELoader: Failed to load external buffer from ${r.uri} with error code ${e.status}.`);return e.arrayBuffer()})).then((e=>new Uint8Array(e)));n.push(t)}else n.push(Promise.resolve(new Uint8Array(t)));else n.push(Promise.resolve())}let r=await Promise.all(n),i={};for(let s=0;s<r.length;s++){let e=r[s];e&&(i[s]=e)}return i}parseActiveBufferViews(e,t){let n={};for(let r=0;r<e.length;r++){let i=e[r];if(!i.isActive)continue;let s=i.byteOffset,a=s+i.byteLength;n[r]=t[i.buffer].slice(s,a)}return n}preprocessBuffers(e=[]){for(let t=0;t<e.length;t++){let n=e[t];n.isActive=!1,n.isExternal=!!n.uri}return e}preprocessBufferViews(e=[],t){for(let n=0;n<e.length;n++){let r=e[n];r.bufferHeader=t[r.buffer],r.isActive=!1,r.isExternal=r.bufferHeader.isExternal}return e}parseAvailability(e,t,n){let r=wh(this.rootTile),i=this.rootTile.implicitTiling.subtreeLevels,s=(r**+i-1)/(r-1),a=r**+i;e._tileAvailability=this.parseAvailabilityBitstream(t.tileAvailability,n,s),e._contentAvailabilityBitstreams=[];for(let o=0;o<t.contentAvailabilityHeaders.length;o++){let r=this.parseAvailabilityBitstream(t.contentAvailabilityHeaders[o],n,s);e._contentAvailabilityBitstreams.push(r)}e._childSubtreeAvailability=this.parseAvailabilityBitstream(t.childSubtreeAvailability,n,a)}parseAvailabilityBitstream(e,t,n){if(!isNaN(e.constant))return{constant:!!e.constant,lengthBits:n};let r;return isNaN(e.bitstream)?isNaN(e.bufferView)||(r=t[e.bufferView]):r=t[e.bitstream],{bitstream:r,lengthBits:n}}expandSubtree(e,t){let n=Th.clone(e);for(let s=0;t&&s<t._contentAvailabilityBitstreams.length;s++)if(t&&this.getBit(t._contentAvailabilityBitstreams[s],0)){n.content={uri:this.parseImplicitURI(e,this.rootTile.content.uri)};break}e.children.push(n);let r=this.transcodeSubtreeTiles(n,t),i=this.listChildSubtrees(t,r);for(let s=0;s<i.length;s++){let e=i[s],t=e.tile,n=this.deriveChildTile(null,t,null,e.childMortonIndex);n.content={uri:this.parseImplicitURI(n,this.rootTile.implicitTiling.subtrees.uri)},t.children.push(n)}}transcodeSubtreeTiles(e,t){let n=[e],r=[];for(let i=1;i<this.rootTile.implicitTiling.subtreeLevels;i++){let e=wh(this.rootTile),s=(e**+i-1)/(e-1),a=e*n.length;for(let i=0;i<a;i++){let a=s+i,o=n[i>>Math.log2(e)];if(!this.getBit(t._tileAvailability,a)){r.push(void 0);continue}let l=this.deriveChildTile(t,o,a,i);o.children.push(l),r.push(l)}n=r,r=[]}return n}deriveChildTile(e,t,n,r){let i=new Th(t,r);i.boundingVolume=this.getTileBoundingVolume(i),i.geometricError=this.getGeometricError(i);for(let s=0;e&&s<e._contentAvailabilityBitstreams.length;s++)if(e&&this.getBit(e._contentAvailabilityBitstreams[s],n)){i.content={uri:this.parseImplicitURI(i,this.rootTile.content.uri)};break}return i}getBit(e,t){if(t<0||t>=e.lengthBits)throw Error("Bit index out of bounds.");if(void 0!==e.constant)return e.constant;let n=t>>3,r=t%8;return 1==(new Uint8Array(e.bitstream)[n]>>r&1)}getTileBoundingVolume(e){let t={};if(this.rootTile.boundingVolume.region){let n=[...this.rootTile.boundingVolume.region],r=n[0],i=n[2],s=n[1],a=n[3],o=(i-r)/2**e.implicitTilingData.level,l=(a-s)/2**e.implicitTilingData.level;n[0]=r+o*e.implicitTilingData.x,n[2]=r+o*(e.implicitTilingData.x+1),n[1]=s+l*e.implicitTilingData.y,n[3]=s+l*(e.implicitTilingData.y+1);for(let e=0;e<4;e++){let t=n[e];t<-Math.PI?n[e]+=2*Math.PI:t>Math.PI&&(n[e]-=2*Math.PI)}if(bh(e)){let t=n[4],r=(n[5]-t)/2**e.implicitTilingData.level;n[4]=t+r*e.implicitTilingData.z,n[5]=t+r*(e.implicitTilingData.z+1)}t.region=n}if(this.rootTile.boundingVolume.box){let n=[...this.rootTile.boundingVolume.box],r=2**e.implicitTilingData.level-1,i=2**-e.implicitTilingData.level,s=bh(e)?3:2;for(let t=0;t<s;t++){n[3+3*t+0]*=i,n[3+3*t+1]*=i,n[3+3*t+2]*=i;let s=n[3+3*t+0],a=n[3+3*t+1],o=n[3+3*t+2],l=0===t?e.implicitTilingData.x:1===t?e.implicitTilingData.y:e.implicitTilingData.z;n[0]+=2*s*(-.5*r+l),n[1]+=2*a*(-.5*r+l),n[2]+=2*o*(-.5*r+l)}t.box=n}return t}getGeometricError(e){return this.rootTile.geometricError/2**e.implicitTilingData.level}listChildSubtrees(e,t){let n=[],r=wh(this.rootTile);for(let i=0;i<t.length;i++){let s=t[i];if(void 0!==s)for(let t=0;t<r;t++){let a=i*r+t;this.getBit(e._childSubtreeAvailability,a)&&n.push({tile:s,childMortonIndex:a})}}return n}parseImplicitURI(e,t){return t=(t=(t=(t=t.replace("{level}",e.implicitTilingData.level)).replace("{x}",e.implicitTilingData.x)).replace("{y}",e.implicitTilingData.y)).replace("{z}",e.implicitTilingData.z)}parseImplicitURIBuffer(e,t,n){let r=this.parseImplicitURI(e,t),i=new URL(r,this.workingPath+"/");return i.pathname=i.pathname.substring(0,i.pathname.lastIndexOf("/")),new URL(i.pathname+"/"+n,this.workingPath+"/").toString()}},_h=class{constructor(){this.name="IMPLICIT_TILING_PLUGIN"}init(e){this.tiles=e}preprocessNode(e,t,n){var r;e.implicitTiling?(e.internal.hasUnrenderableContent=!0,e.internal.hasRenderableContent=!1,e.implicitTilingData={root:e,subtreeIdx:0,x:0,y:0,z:0,level:0}):/.subtree$/i.test(null==(r=e.content)?void 0:r.uri)&&(e.internal.hasUnrenderableContent=!0,e.internal.hasRenderableContent=!1)}parseTile(e,t,n){if(/^subtree$/i.test(n)){let n=new Sh(t);return n.workingPath=t.internal.basePath,n.fetchOptions=this.tiles.fetchOptions,n.parse(e)}}preprocessURL(e,t){if(t&&t.implicitTiling){let e=t.implicitTiling.subtrees.uri.replace("{level}",t.implicitTilingData.level).replace("{x}",t.implicitTilingData.x).replace("{y}",t.implicitTilingData.y).replace("{z}",t.implicitTilingData.z);return new URL(e,t.internal.basePath+"/").toString()}return e}disposeTile(e){var t;/.subtree$/i.test(null==(t=e.content)?void 0:t.uri)&&(e.children.forEach((e=>{this.tiles.processNodeQueue.remove(e)})),e.children.length=0)}};function Mh(e){return e>>1^-(1&e)}var Ah=class extends vc{constructor(...e){super(...e),this.fetchOptions.header={Accept:"application/vnd.quantized-mesh,application/octet-stream;q=0.9"}}loadAsync(...e){let{fetchOptions:t}=this;return t.header=t.header||{},t.header.Accept="application/vnd.quantized-mesh,application/octet-stream;q=0.9",t.header.Accept+=";extensions=octvertexnormals-watermask-metadata",super.loadAsync(...e)}parse(e){let t=0,n=new DataView(e),r=()=>{let e=n.getFloat64(t,!0);return t+=8,e},i=()=>{let e=n.getFloat32(t,!0);return t+=4,e},s=()=>{let e=n.getUint32(t,!0);return t+=4,e},a=()=>{let e=n.getUint8(t);return t+=1,e},o=(n,r)=>{let i=new r(e,t,n);return t+=n*r.BYTES_PER_ELEMENT,i},l={center:[r(),r(),r()],minHeight:i(),maxHeight:i(),sphereCenter:[r(),r(),r()],sphereRadius:r(),horizonOcclusionPoint:[r(),r(),r()]},c=s(),u=o(c,Uint16Array),h=o(c,Uint16Array),d=o(c,Uint16Array),p=new Float32Array(c),m=new Float32Array(c),f=new Float32Array(c),g=0,x=0,y=0,v=32767;for(let P=0;P<c;++P)g+=Mh(u[P]),x+=Mh(h[P]),y+=Mh(d[P]),p[P]=g/v,m[P]=x/v,f[P]=y/v;let b=c>65536,w=b?Uint32Array:Uint16Array;t=b?4*Math.ceil(t/4):2*Math.ceil(t/2);let T=o(3*s(),w),S=0;for(var _=0;_<T.length;++_){let e=T[_];T[_]=S-e,0===e&&++S}let M=(e,t)=>m[t]-m[e],A=(e,t)=>p[e]-p[t],E=o(s(),w);E.sort(M);let C=o(s(),w);C.sort(A);let R=o(s(),w);R.sort(((e,t)=>-M(e,t)));let D=o(s(),w);D.sort(((e,t)=>-A(e,t)));let k={westIndices:E,southIndices:C,eastIndices:R,northIndices:D},I={};for(;t<n.byteLength;){let e=a(),t=s();if(1===e){let t=o(2*c,Uint8Array),n=new Float32Array(3*c);for(let e=0;e<c;e++){let r=t[2*e+0]/255*2-1,i=t[2*e+1]/255*2-1,s=1-(Math.abs(r)+Math.abs(i));if(s<0){let e=r;r=(1-Math.abs(i))*Eh(e),i=(1-Math.abs(e))*Eh(i)}let a=Math.sqrt(r*r+i*i+s*s);n[3*e+0]=r/a,n[3*e+1]=i/a,n[3*e+2]=s/a}I.octvertexnormals={extensionId:e,normals:n}}else if(2===e){let n=1===t?1:256;I.watermask={extensionId:e,mask:o(n*n,Uint8Array),size:n}}else if(4===e){let t=o(s(),Uint8Array),n=(new TextDecoder).decode(t);I.metadata={extensionId:e,json:JSON.parse(n)}}}return{header:l,indices:T,vertexData:{u:p,v:m,height:f},edgeIndices:k,extensions:I}}};function Eh(e){return e<0?-1:1}var Ch=new r.Vector3,Rh=new r.Vector3;var Dh=class{get isMercator(){return"EPSG:3857"===this.scheme}get isCartographic(){return"none"!==this.scheme}constructor(e="EPSG:4326"){this.scheme=e,this.tileCountX=1,this.tileCountY=1,this.setScheme(e)}setScheme(e){switch(this.scheme=e,e){case"CRS:84":case"EPSG:4326":this.tileCountX=2,this.tileCountY=1;break;case"EPSG:3857":case"none":this.tileCountX=1,this.tileCountY=1;break;default:throw Error(`ProjectionScheme: Unknown projection scheme "${e}"`)}}convertNormalizedToLatitude(e){if("none"===this.scheme)return e;if(this.isMercator){let t=r.MathUtils.mapLinear(e,0,1,-1,1);return 2*Math.atan(Math.exp(t*Math.PI))-Math.PI/2}return r.MathUtils.mapLinear(e,0,1,-Math.PI/2,Math.PI/2)}convertNormalizedToLongitude(e){return"none"===this.scheme?e:r.MathUtils.mapLinear(e,0,1,-Math.PI,Math.PI)}convertLatitudeToNormalized(e){return"none"===this.scheme?e:this.isMercator?.5+1*Math.log(Math.tan(Math.PI/4+e/2))/(2*Math.PI):r.MathUtils.mapLinear(e,-Math.PI/2,Math.PI/2,0,1)}convertLongitudeToNormalized(e){return"none"===this.scheme?e:(e+Math.PI)/(2*Math.PI)}getLongitudeDerivativeAtNormalized(e){return"none"===this.scheme?1:2*Math.PI}getLatitudeDerivativeAtNormalized(e){if("none"===this.scheme)return 1;{let t=1e-5,n=e-t;return n<0&&(n=e+t),this.isMercator?Math.abs(this.convertNormalizedToLatitude(e)-this.convertNormalizedToLatitude(n))/t:Math.PI}}getBounds(){return"none"===this.scheme?[0,0,1,1]:[this.convertNormalizedToLongitude(0),this.convertNormalizedToLatitude(0),this.convertNormalizedToLongitude(1),this.convertNormalizedToLatitude(1)]}toNormalizedPoint(e,t){let n=[e,t];return n[0]=this.convertLongitudeToNormalized(n[0]),n[1]=this.convertLatitudeToNormalized(n[1]),n}toNormalizedRange(e){return[...this.toNormalizedPoint(e[0],e[1]),...this.toNormalizedPoint(e[2],e[3])]}toCartographicPoint(e,t){let n=[e,t];return n[0]=this.convertNormalizedToLongitude(n[0]),n[1]=this.convertNormalizedToLatitude(n[1]),n}toCartographicRange(e){return[...this.toCartographicPoint(e[0],e[1]),...this.toCartographicPoint(e[2],e[3])]}clampToBounds(e,t=!1){let n,i=[...e];n=t?[0,0,1,1]:this.getBounds();let[s,a,o,l]=n;return i[0]=r.MathUtils.clamp(i[0],s,o),i[2]=r.MathUtils.clamp(i[2],s,o),i[1]=r.MathUtils.clamp(i[1],a,l),i[3]=r.MathUtils.clamp(i[3],a,l),i}};function kh(e,t){let[n,r,i,s]=e,[a,o,l,c]=t;return!(n>=l||i<=a||r>=c||s<=o)}var Ih=class{get levelCount(){return this._levels.length}get maxLevel(){return this.levelCount-1}get minLevel(){let e=this._levels;for(let t=0;t<e.length;t++)if(null!==e[t])return t;return-1}get contentBounds(){return this._contentBounds??this.projection.getBounds()}get aspectRatio(){let{pixelWidth:e,pixelHeight:t}=this.getLevel(this.maxLevel);return e/t}constructor(){this.flipY=!1,this.pixelOverlap=0,this._contentBounds=null,this.projection=new Dh("none"),this._levels=[]}setLevel(e,t={}){let n=this._levels;for(;n.length<e;)n.push(null);let{tileSplitX:r=2,tileSplitY:i=2}=t,{tilePixelWidth:s=256,tilePixelHeight:a=256,tileCountX:o=r**e,tileCountY:l=i**e,tileBounds:c=null}=t,{pixelWidth:u=s*o,pixelHeight:h=a*l}=t;n[e]={tilePixelWidth:s,tilePixelHeight:a,pixelWidth:u,pixelHeight:h,tileCountX:o,tileCountY:l,tileSplitX:r,tileSplitY:i,tileBounds:c}}generateLevels(e,t,n,r={}){let{minLevel:i=0,tilePixelWidth:s=256,tilePixelHeight:a=256}=r,o=e-1,{pixelWidth:l=s*t*2**o,pixelHeight:c=a*n*2**o}=r;for(let u=i;u<e;u++){let t=e-u-1,n=Math.ceil(l*2**-t),r=Math.ceil(c*2**-t),i=Math.ceil(n/s),o=Math.ceil(r/a);this.setLevel(u,{tilePixelWidth:s,tilePixelHeight:a,pixelWidth:n,pixelHeight:r,tileCountX:i,tileCountY:o})}}getLevel(e){return this._levels[e]}setContentBounds(e,t,n,r){this._contentBounds=[e,t,n,r]}setProjection(e){this.projection=e}getTileAtPoint(e,t,n,i=!1){let{flipY:s}=this,{tileCountY:a,tileBounds:o,pixelHeight:l,pixelWidth:c,tilePixelHeight:u,tilePixelWidth:h}=this.getLevel(n),d=h/c,p=u/l;if(i||([e,t]=this.toNormalizedPoint(e,t)),o){let n=this.toNormalizedRange(o);e=r.MathUtils.mapLinear(e,n[0],n[2],0,1),t=r.MathUtils.mapLinear(t,n[1],n[3],0,1)}let m=Math.floor(e/d),f=Math.floor(t/p);return s&&(f=a-1-f),[m,f]}getTilesInRange(e,t,n,i,s,a=!1){let o=[e,t,n,i],l=this.getContentBounds(a),c=this.getLevel(s).tileBounds;if(!kh(o,l)||c&&(a&&(c=this.toNormalizedRange(c)),!kh(o,l)))return[0,0,-1,-1];let[u,h,d,p]=this.clampToContentBounds(o,a),m=this.getTileAtPoint(u,h,s,a),f=this.getTileAtPoint(d,p,s,a);this.flipY&&([m[1],f[1]]=[f[1],m[1]]);let{tileCountX:g,tileCountY:x}=this.getLevel(s),[y,v]=m,[b,w]=f;return b<0||w<0||y>=g||v>=x?[0,0,-1,-1]:[r.MathUtils.clamp(y,0,g-1),r.MathUtils.clamp(v,0,x-1),r.MathUtils.clamp(b,0,g-1),r.MathUtils.clamp(w,0,x-1)]}getTileExists(e,t,n){let[r,i,s,a]=this.contentBounds,[o,l,c,u]=this.getTileBounds(e,t,n);return!(o>=c||l>=u)&&o<=s&&l<=a&&c>=r&&u>=i}getContentBounds(e=!1){let{projection:t}=this,n=[...this.contentBounds];return e&&(n[0]=t.convertLongitudeToNormalized(n[0]),n[1]=t.convertLatitudeToNormalized(n[1]),n[2]=t.convertLongitudeToNormalized(n[2]),n[3]=t.convertLatitudeToNormalized(n[3])),n}getTileContentUVBounds(e,t,n){let[i,s,a,o]=this.getTileBounds(e,t,n,!0,!0),[l,c,u,h]=this.getTileBounds(e,t,n,!0,!1);return[r.MathUtils.mapLinear(i,l,u,0,1),r.MathUtils.mapLinear(s,c,h,0,1),r.MathUtils.mapLinear(a,l,u,0,1),r.MathUtils.mapLinear(o,c,h,0,1)]}getTileBounds(e,t,n,i=!1,s=!0){let{flipY:a,pixelOverlap:o,projection:l}=this,{tilePixelWidth:c,tilePixelHeight:u,pixelWidth:h,pixelHeight:d,tileBounds:p}=this.getLevel(n),m=c*e-o,f=u*t-o,g=m+c+2*o,x=f+u+2*o;if(m=Math.max(m,0),f=Math.max(f,0),g=Math.min(g,h),x=Math.min(x,d),m/=h,g/=h,f/=d,x/=d,a){let e=(x-f)/2,t=1-(f+x)/2;f=t-e,x=t+e}let y=[m,f,g,x];if(p){let e=this.toNormalizedRange(p);y[0]=r.MathUtils.mapLinear(y[0],0,1,e[0],e[2]),y[2]=r.MathUtils.mapLinear(y[2],0,1,e[0],e[2]),y[1]=r.MathUtils.mapLinear(y[1],0,1,e[1],e[3]),y[3]=r.MathUtils.mapLinear(y[3],0,1,e[1],e[3])}return s&&(y=this.clampToBounds(y,!0)),i||(y[0]=l.convertNormalizedToLongitude(y[0]),y[1]=l.convertNormalizedToLatitude(y[1]),y[2]=l.convertNormalizedToLongitude(y[2]),y[3]=l.convertNormalizedToLatitude(y[3])),y}toNormalizedPoint(e,t){return this.projection.toNormalizedPoint(e,t)}toNormalizedRange(e){return this.projection.toNormalizedRange(e)}toCartographicPoint(e,t){return this.projection.toCartographicPoint(e,t)}toCartographicRange(e){return this.projection.toCartographicRange(e)}clampToContentBounds(e,t=!1){let n=[...e],[i,s,a,o]=this.getContentBounds(t);return n[0]=r.MathUtils.clamp(n[0],i,a),n[1]=r.MathUtils.clamp(n[1],s,o),n[2]=r.MathUtils.clamp(n[2],i,a),n[3]=r.MathUtils.clamp(n[3],s,o),n}clampToBounds(e,t=!1){return this.projection.clampToBounds(e,t)}},Ph=Symbol("TILE_X"),Lh=Symbol("TILE_Y"),Uh=Symbol("TILE_LEVEL"),Fh=Symbol("OVERLAY_RANGE"),zh=Symbol("OVERLAY_LEVEL"),Bh=new r.Vector3,Vh=new r.Vector3,Oh=new r.Sphere,Nh=class{constructor(e={}){let{overlay:t=null,shape:n="ellipsoid",endCaps:r=!0,center:i=!0,useRecommendedSettings:s=!0,applyOverlayTexture:a=!1}=e;this.priority=-10,this.tiles=null,this.overlay=t,this.shape=n,this.endCaps=r,this.center=i,this.useRecommendedSettings=s,this.applyOverlayTexture=a,this._tiling=null}init(e){this.useRecommendedSettings&&(e.errorTarget=1),this.tiles=e}async loadRootTileset(){let{overlay:e}=this;return e?(await e.init(),this._tiling=e.tiling||this._createDefaultTiling()):this._tiling=this._createDefaultTiling(),this.getTileset()}async parseToMesh(e,t,n,r,i){if("generated_surface"!==n)return null;let s;s=this._useEllipsoid()?this._createEllipsoidMesh(t):this._createPlanarMesh(t);let{overlay:a,applyOverlayTexture:o}=this;if(a&&o){let e=t[Ph],n=t[Lh],r=t[Uh],o=this._tiling.getTileBounds(e,n,r,!0,!1);if(a.hasContent(o,r)){try{await a.lockTexture(o,r)}catch(l){if("AbortError"!==l.name)throw l;return null}let e=a.getTexture(o,r);if(t[Fh]=o,t[zh]=r,i.aborted)return a.releaseTexture(o,r),delete t[Fh],delete t[zh],null;s.material.map=e,s.material.needsUpdate=!0}}return s}preprocessNode(e){let t=this._tiling.maxLevel;e[Uh]<t&&null!==e.parent&&this.expandChildren(e)}disposeTile(e){let t=e[Fh];this.overlay&&t&&(this.overlay.releaseTexture(t,e[zh]),delete e[Fh],delete e[zh])}dispose(){this.tiles.forEachLoadedModel(((e,t)=>{this.disposeTile(t)}))}getCartographicFromPosition(e,t={}){let{_tiling:n}=this,{projection:r}=n;if(!r.isCartographic)throw Error("GeneratedSurfacePlugin: getCartographicFromPosition requires a cartographic projection.");if(this._useEllipsoid())return this.tiles.ellipsoid.getPositionToCartographic(e,t);let{center:i}=this,s=e.x/n.aspectRatio+(i?.5:0),a=e.y+(i?.5:0);return t.lat=r.convertNormalizedToLatitude(a),t.lon=r.convertNormalizedToLongitude(s),t}getPositionFromCartographic(e,t,n=new r.Vector3){let{_tiling:i}=this,{projection:s}=i;if(!s.isCartographic)throw Error("GeneratedSurfacePlugin: getPositionFromCartographic requires a cartographic projection.");if(this._useEllipsoid())return this.tiles.ellipsoid.getCartographicToPosition(e,t,0,n);let{center:a}=this,o=s.convertLongitudeToNormalized(t),l=s.convertLatitudeToNormalized(e);return n.x=(o-(a?.5:0))*i.aspectRatio,n.y=l-(a?.5:0),n.z=0,n}_useEllipsoid(){return this._tiling.projection.isCartographic&&"ellipsoid"===this.shape}_createPlanarMesh(e){let t=e[Ph],n=e[Lh],i=e[Uh],s=e.boundingVolume.box,a=1,o=1,l=0,c=0,u=0;s&&([l,c,u]=s,a=s[3],o=s[7]);let h=new r.PlaneGeometry(2*a,2*o),d=new r.Mesh(h,new r.MeshBasicMaterial);d.position.set(l,c,u);let p=this._tiling.getTileContentUVBounds(t,n,i),{uv:m}=h.attributes;for(let f=0;f<m.count;f++)m.setXY(f,r.MathUtils.mapLinear(m.getX(f),0,1,p[0],p[2]),r.MathUtils.mapLinear(m.getY(f),0,1,p[1],p[3]));return d}_createEllipsoidMesh(e){let{tiles:t,endCaps:n,_tiling:i}=this,{projection:s}=i,a=e[Uh],o=e[Ph],l=e[Lh],[c,u,h,d]=e.boundingVolume.region,p=Math.max(15,Math.ceil((d-u)*r.MathUtils.RAD2DEG*.25)),m=Math.max(30,Math.ceil((h-c)*r.MathUtils.RAD2DEG*.25)),f=m+3,g=p+3,x=new r.PlaneGeometry(1,1,m+2,p+2),[y,v,b,w]=i.getTileBounds(o,l,a,!0,!0),T=i.getTileContentUVBounds(o,l,a),{position:S,normal:_,uv:M}=x.attributes,A=S.count;e.engineData.boundingVolume.getSphere(Oh);for(let C=0;C<A;C++){let i=C%f,a=Math.floor(C/f),o=0===i||i===f-1||0===a||a===g-1,l=(Math.max(1,Math.min(f-2,i))-1)/m,c=1-(Math.max(1,Math.min(g-2,a))-1)/p,h=s.convertNormalizedToLongitude(r.MathUtils.mapLinear(l,0,1,y,b)),x=s.convertNormalizedToLatitude(r.MathUtils.mapLinear(c,0,1,v,w));if(s.isMercator&&n&&(1===w&&1===c&&(x=Math.PI/2),0===v&&0===c&&(x=-Math.PI/2)),s.isMercator&&0!==c&&1!==c){let e=s.convertNormalizedToLatitude(1),t=1/p,n=r.MathUtils.mapLinear(c-t,0,1,u,d),i=r.MathUtils.mapLinear(c+t,0,1,u,d);x>e&&n<e&&(x=e),x<-e&&i>-e&&(x=-e)}t.ellipsoid.getCartographicToPosition(x,h,0,Bh).sub(Oh.center),t.ellipsoid.getCartographicToNormal(x,h,Vh),o&&Bh.addScaledVector(Vh,-e.geometricError);let A=r.MathUtils.mapLinear(s.convertLongitudeToNormalized(h),y,b,T[0],T[2]),E=r.MathUtils.mapLinear(s.convertLatitudeToNormalized(x),v,w,T[1],T[3]);S.setXYZ(C,Bh.x,Bh.y,Bh.z),_.setXYZ(C,Vh.x,Vh.y,Vh.z),M.setXY(C,A,E)}let E=new r.Mesh(x,new r.MeshBasicMaterial);return E.position.copy(Oh.center),E}getTileset(){let{tiles:e,_tiling:t}=this,n=t.minLevel,{tileCountX:r,tileCountY:i}=t.getLevel(n),s=[];for(let o=0;o<r;o++)for(let e=0;e<i;e++){let t=this.createChild(o,e,n);null!==t&&s.push(t)}let a={asset:{version:"1.1"},geometricError:1/0,root:{refine:"REPLACE",geometricError:1/0,boundingVolume:this.createBoundingVolume(0,0,-1),children:s,[Uh]:-1,[Ph]:0,[Lh]:0}};return e.preprocessTileset(a,""),a}getUrl(){return"tile.generated_surface"}fetchData(e){if(/generated_surface/.test(e))return new ArrayBuffer}createBoundingVolume(e,t,n,r=0){let{_tiling:i}=this,s=-1===n;if(this._useEllipsoid()){let a,o,{endCaps:l}=this;return s?(a=i.getContentBounds(!0),o=i.getContentBounds()):(a=i.getTileBounds(e,t,n,!0,!0),o=i.getTileBounds(e,t,n,!1,!0)),l&&(1===a[3]&&(o[3]=Math.PI/2),0===a[1]&&(o[1]=-Math.PI/2)),{region:[...o,-r,1]}}{let r,{center:a}=this;r=s?i.getContentBounds(!0):i.getTileBounds(e,t,n,!0);let[o,l,c,u]=r,h=(c-o)/2,d=(u-l)/2,p=o+h,m=l+d;return a&&(p-=.5,m-=.5),p*=i.aspectRatio,h*=i.aspectRatio,{box:[p,m,0,h,0,0,0,d,0,0,0,0]}}}createChild(e,t,n){let{_tiling:r}=this,{projection:i}=r;if(!r.getTileExists(e,t,n))return null;let s,a=this._useEllipsoid();if(a){let[a,o,l,c]=r.getTileBounds(e,t,n,!0),{tilePixelWidth:u,tilePixelHeight:h}=r.getLevel(n),d=(l-a)/u,p=(c-o)/h,[,m,f,g]=r.getTileBounds(e,t,n),x=m>0==g>0?Math.min(Math.abs(m),Math.abs(g)):0,y=i.convertLatitudeToNormalized(x),v=i.getLongitudeDerivativeAtNormalized(a),b=i.getLatitudeDerivativeAtNormalized(y),[w,T]=function(e,t,n){let r=1e-5,i=n+r,s=t+r;Math.abs(s)>Math.PI/2&&(s-=r),e.getCartographicToPosition(t,n,0,Ch),e.getCartographicToPosition(s,n,0,Rh);let a=Ch.distanceTo(Rh)/r;return e.getCartographicToPosition(t,i,0,Rh),[Ch.distanceTo(Rh)/r,a]}(this.tiles.ellipsoid,x,f);s=Math.max(d*v*w,p*b*T)}else{let{pixelWidth:e,pixelHeight:t}=r.getLevel(n);s=Math.max(r.aspectRatio/e,1/t)}return{refine:"REPLACE",geometricError:s,boundingVolume:this.createBoundingVolume(e,t,n,a?s:0),content:{uri:this.getUrl(e,t,n)},children:[],[Ph]:e,[Lh]:t,[Uh]:n}}expandChildren(e){let t=e[Uh],n=e[Ph],r=e[Lh],{tileSplitX:i,tileSplitY:s}=this._tiling.getLevel(t);for(let a=0;a<i;a++)for(let o=0;o<s;o++){let l=this.createChild(i*n+a,s*r+o,t+1);l&&e.children.push(l)}}_createDefaultTiling(){let e=new Ih;if("ellipsoid"===this.shape){let t=new Dh("EPSG:3857");e.setProjection(t),e.generateLevels(20,t.tileCountX,t.tileCountY)}else{let t=new Dh("none");e.setProjection(t),e.generateLevels(20,1,1)}return e}},$h=class extends DOMException{constructor(){super("DataCache: Item removed","AbortError")}};function Gh(...e){return e.join("_")}var qh=class{constructor(){this.cache={},this.count=0,this.cachedBytes=0,this.active=0}fetchItem(e,t){}disposeItem(e,t){}getMemoryUsage(e){return 0}setData(...e){let{cache:t}=this,n=e.pop(),r=Gh(...e);if(r in t)throw Error(`DataCache: "${r}" is already present.`);return this.cache[r]={abortController:new AbortController,result:n,count:1,bytes:this.getMemoryUsage(n)},this.count++,this.cachedBytes+=this.cache[r].bytes,n}lock(...e){let{cache:t}=this,n=Gh(...e);if(n in t)t[n].count++;else{let t=new AbortController,r={abortController:t,result:null,count:1,bytes:0,args:e};this.active++,r.result=this.fetchItem(e,t.signal),r.result instanceof Promise?r.result=r.result.then((e=>(t.signal.throwIfAborted(),r.result=e,r.bytes=this.getMemoryUsage(e),this.cachedBytes+=r.bytes,e))).finally((()=>{this.active--})):(this.active--,r.bytes=this.getMemoryUsage(r.result),this.cachedBytes+=r.bytes),this.cache[n]=r,this.count++}return t[n].result}release(...e){let t=Gh(...e);this.releaseViaFullKey(t)}get(...e){let{cache:t}=this,n=Gh(...e);return n in t&&t[n].count>0?t[n].result:null}has(...e){let{cache:t}=this;return Gh(...e)in t}forEachItem(e){let{cache:t}=this;for(let n in t){let r=t[n];r.result instanceof Promise||e(r.result,r.args)}}dispose(){let{cache:e}=this;for(let t in e){let{abortController:n}=e[t];n.abort(new $h),this.releaseViaFullKey(t,!0)}this.cache={}}releaseViaFullKey(e,t=!1){let{cache:n}=this;if(e in n&&n[e].count>0){let r=n[e];if(r.count--,0===r.count||t){let i=()=>{if(n[e]!==r)return;let{result:t,abortController:i}=r;i.abort(new $h),t instanceof Promise?t.then((e=>{this.disposeItem(e,r.args)})).catch((()=>{this.disposeItem(null,r.args)})).finally((()=>{this.count--,this.cachedBytes-=r.bytes})):(this.disposeItem(t,r.args),this.count--,this.cachedBytes-=r.bytes),delete n[e]};t?i():queueMicrotask((()=>{0===r.count&&i()}))}return!0}throw Error("DataCache: Attempting to release key that does not exist")}},Hh=class extends qh{constructor(e={}){super();let{fetchOptions:t={}}=e;this.tiling=new Ih,this.fetchOptions=t,this.fetchData=(...e)=>fetch(...e)}init(){}async processBufferToTexture(e){let t=new Blob([e]),n=new r.Texture(await createImageBitmap(t,{premultiplyAlpha:"none",colorSpaceConversion:"none",imageOrientation:"flipY"}));return n.generateMipmaps=!1,n.colorSpace=r.SRGBColorSpace,n.needsUpdate=!0,n}getMemoryUsage(e){let{format:t,type:n,image:i,generateMipmaps:s}=e,{width:a,height:o}=i,l=r.TextureUtils.getByteLength(a,o,t,n);return s?4*l/3:l}fetchItem(e,t){let n={...this.fetchOptions,signal:t},r=this.getUrl(...e);return this.fetchData(r,n).then((e=>e.arrayBuffer())).then((e=>this.processBufferToTexture(e)))}disposeItem(e){e&&(e.dispose(),e.image instanceof ImageBitmap&&e.image.close())}getUrl(...e){}},jh=class extends Hh{constructor(e={}){let{url:t=null,...n}=e;super(n),this.tileSets=null,this.extension=null,this.url=t}getUrl(e,t,n){let{url:r,extension:i,tileSets:s,tiling:a}=this;return new URL(`${parseInt(s[n-a.minLevel].href)}/${e}/${t}.${i}`,r).toString()}init(){let{url:e}=this;return this.fetchData(new URL("tilemapresource.xml",e),this.fetchOptions).then((e=>e.text())).then((t=>{let{tiling:n}=this,i=(new DOMParser).parseFromString(t,"text/xml"),s=i.querySelector("BoundingBox"),a=i.querySelector("TileFormat"),o=[...i.querySelector("TileSets").querySelectorAll("TileSet")].map((e=>({href:parseInt(e.getAttribute("href")),unitsPerPixel:parseFloat(e.getAttribute("units-per-pixel")),order:parseInt(e.getAttribute("order"))}))).sort(((e,t)=>e.order-t.order)),l=parseFloat(s.getAttribute("minx"))*r.MathUtils.DEG2RAD,c=parseFloat(s.getAttribute("maxx"))*r.MathUtils.DEG2RAD,u=parseFloat(s.getAttribute("miny"))*r.MathUtils.DEG2RAD,h=parseFloat(s.getAttribute("maxy"))*r.MathUtils.DEG2RAD,d=parseInt(a.getAttribute("width")),p=parseInt(a.getAttribute("height")),m=a.getAttribute("extension"),f=i.querySelector("SRS").textContent;this.extension=m,this.url=e,this.tileSets=o,n.setProjection(new Dh(f)),n.setContentBounds(l,u,c,h),o.forEach((({order:e})=>{n.setLevel(e,{tileCountX:n.projection.tileCountX*2**e,tilePixelWidth:d,tilePixelHeight:p})}))}))}};function Wh(e,t,n,r){let[i,s,a,o]=e;s+=1e-8,i+=1e-8,o-=1e-8,a-=1e-8;let l=Math.max(Math.min(t,n.maxLevel),n.minLevel),[c,u,h,d]=n.getTilesInRange(i,s,a,o,l,!0);for(let p=c;p<=h;p++)for(let e=u;e<=d;e++)r(p,e,l)}var Xh=["a","b","c"],Yh=new r.Vector4,Kh=new r.Vector4,Qh=new r.Vector4,Zh=new r.Vector4,Jh=class{constructor(){this.attributeList=null,this.splitOperations=[],this.trianglePool=new ed}forEachSplitPermutation(e){let{splitOperations:t}=this,n=(r=0)=>{r>=t.length?e():(t[r].keepPositive=!0,n(r+1),t[r].keepPositive=!1,n(r+1))};n()}addSplitOperation(e,t=!0){this.splitOperations.push({callback:e,keepPositive:t})}clearSplitOperations(){this.splitOperations.length=0}clipObject(e){let t=e.clone(),n=[];return t.traverse((e=>{e.isMesh&&(e.geometry=this.clip(e).geometry,0==(e.geometry.index?e.geometry.index.count/3:e.attributes.position.count/3)&&n.push(e))})),n.forEach((e=>{e.removeFromParent()})),t}clip(e,t=null){let n=this.getClippedData(e,t);return this.constructMesh(n.attributes,n.index,e)}getClippedData(e,t=null,n={}){let{trianglePool:r,splitOperations:i,attributeList:s}=this,a=e.geometry,o=a.attributes.position,l=a.index,c=0,u={};n.index=n.index||[],n.vertexIsClipped=n.vertexIsClipped||[],n.attributes=n.attributes||{};for(let m in a.attributes)null!==s&&(s instanceof Function&&!s(m)||Array.isArray(s)&&!s.includes(m))||(n.attributes[m]=[]);let h=0,d=l?l.count:o.count;null!==t&&(h=t.start,d=t.count);for(let m=h,f=h+d;m<f;m+=3){let t=m+0,n=m+1,s=m+2;l&&(t=l.getX(t),n=l.getX(n),s=l.getX(s));let o=r.get();o.initFromIndices(t,n,s);let c=[o];for(let r=0;r<i.length;r++){let{keepPositive:t,callback:n}=i[r],s=[];for(let r=0;r<c.length;r++){let i=c[r],{indices:o,barycoord:l}=i;i.clipValues.a=n(a,o.a,o.b,o.c,l.a,e.matrixWorld),i.clipValues.b=n(a,o.a,o.b,o.c,l.b,e.matrixWorld),i.clipValues.c=n(a,o.a,o.b,o.c,l.c,e.matrixWorld),this.splitTriangle(i,!t,s)}c=s}for(let e=0,r=c.length;e<r;e++){p(c[e],a)}r.reset()}return n;function p(e,t){for(let r=0;r<3;r++){let i=e.getVertexHash(r,t);i in u||(u[i]=c,c++,e.getVertexData(r,t,n.attributes),n.vertexIsClipped.push(0===e.clipValues[Xh[r]]));let s=u[i];n.index.push(s)}}}constructMesh(e,t,n){let i=n.geometry,s=new r.BufferGeometry,a=e.position.length/3>65535?new Uint32Array(t):new Uint16Array(t);s.setIndex(new r.BufferAttribute(a,1,!1));for(let l in e){let t=i.getAttribute(l),n=new r.BufferAttribute(new t.array.constructor(e[l]),t.itemSize,t.normalized);n.gpuType=t.gpuType,s.setAttribute(l,n)}let o=new r.Mesh(s,n.material.clone());return o.position.copy(n.position),o.quaternion.copy(n.quaternion),o.scale.copy(n.scale),o}splitTriangle(e,t,n){let{trianglePool:i}=this,s=[],a=[],o=[];for(let l=0;l<3;l++){let t=Xh[l],n=Xh[(l+1)%3],i=e.clipValues[t],c=e.clipValues[n];(i<0!=c<0||0===i)&&(s.push(l),a.push([t,n]),i===c?o.push(0):o.push(r.MathUtils.mapLinear(0,i,c,0,1)))}if(2!==s.length)Math.min(e.clipValues.a,e.clipValues.b,e.clipValues.c)<0===t&&n.push(e);else if(2===s.length){let r,l,c=i.get().initFromTriangle(e),u=i.get().initFromTriangle(e),h=i.get().initFromTriangle(e);(s[0]+1)%3===s[1]?(c.lerpVertexFromEdge(e,a[0][0],a[0][1],o[0],"a"),c.copyVertex(e,a[0][1],"b"),c.lerpVertexFromEdge(e,a[1][0],a[1][1],o[1],"c"),c.clipValues.a=0,c.clipValues.c=0,u.lerpVertexFromEdge(e,a[0][0],a[0][1],o[0],"a"),u.copyVertex(e,a[1][1],"b"),u.copyVertex(e,a[0][0],"c"),u.clipValues.a=0,h.lerpVertexFromEdge(e,a[0][0],a[0][1],o[0],"a"),h.lerpVertexFromEdge(e,a[1][0],a[1][1],o[1],"b"),h.copyVertex(e,a[1][1],"c"),h.clipValues.a=0,h.clipValues.b=0):(c.lerpVertexFromEdge(e,a[0][0],a[0][1],o[0],"a"),c.lerpVertexFromEdge(e,a[1][0],a[1][1],o[1],"b"),c.copyVertex(e,a[0][0],"c"),c.clipValues.a=0,c.clipValues.b=0,u.lerpVertexFromEdge(e,a[0][0],a[0][1],o[0],"a"),u.copyVertex(e,a[0][1],"b"),u.lerpVertexFromEdge(e,a[1][0],a[1][1],o[1],"c"),u.clipValues.a=0,u.clipValues.c=0,h.copyVertex(e,a[0][1],"a"),h.copyVertex(e,a[1][0],"b"),h.lerpVertexFromEdge(e,a[1][0],a[1][1],o[1],"c"),h.clipValues.c=0),r=Math.min(c.clipValues.a,c.clipValues.b,c.clipValues.c),l=r<0,l===t&&n.push(c),r=Math.min(u.clipValues.a,u.clipValues.b,u.clipValues.c),l=r<0,l===t&&n.push(u),r=Math.min(h.clipValues.a,h.clipValues.b,h.clipValues.c),l=r<0,l===t&&n.push(h)}}},ed=class{constructor(){this.pool=[],this.index=0}get(){if(this.index>=this.pool.length){let e=new td;this.pool.push(e)}let e=this.pool[this.index];return this.index++,e}reset(){this.index=0}},td=class{constructor(){this.indices={a:-1,b:-1,c:-1},this.clipValues={a:-1,b:-1,c:-1},this.barycoord=new r.Triangle}getVertexHash(e,t){let{barycoord:n,indices:r}=this,i=n[Xh[e]];if(1===i.x)return r[Xh[0]];if(1===i.y)return r[Xh[1]];if(1===i.z)return r[Xh[2]];{let{attributes:e}=t,n="";for(let t in e){let s=e[t];switch(nd(s,r.a,r.b,r.c,i,Yh),("normal"===t||"tangent"===t||"bitangent"===t)&&Yh.normalize(),s.itemSize){case 4:n+=rd(Yh.x,Yh.y,Yh.z,Yh.w);break;case 3:n+=rd(Yh.x,Yh.y,Yh.z);break;case 2:n+=rd(Yh.x,Yh.y);break;case 1:n+=rd(Yh.x)}n+="|"}return n}}getVertexData(e,t,n){let{barycoord:r,indices:i}=this,s=r[Xh[e]],{attributes:a}=t;for(let o in a){if(!n[o])continue;let e=a[o],t=n[o];switch(nd(e,i.a,i.b,i.c,s,Yh),("normal"===o||"tangent"===o||"bitangent"===o)&&Yh.normalize(),e.itemSize){case 4:t.push(Yh.x,Yh.y,Yh.z,Yh.w);break;case 3:t.push(Yh.x,Yh.y,Yh.z);break;case 2:t.push(Yh.x,Yh.y);break;case 1:t.push(Yh.x)}}}initFromTriangle(e){return this.initFromIndices(e.indices.a,e.indices.b,e.indices.c)}initFromIndices(e,t,n){return this.indices.a=e,this.indices.b=t,this.indices.c=n,this.clipValues.a=-1,this.clipValues.b=-1,this.clipValues.c=-1,this.barycoord.a.set(1,0,0),this.barycoord.b.set(0,1,0),this.barycoord.c.set(0,0,1),this}lerpVertexFromEdge(e,t,n,i,s){this.clipValues[s]=r.MathUtils.lerp(e.clipValues[t],e.clipValues[n],i),this.barycoord[s].lerpVectors(e.barycoord[t],e.barycoord[n],i)}copyVertex(e,t,n){this.clipValues[n]=e.clipValues[t],this.barycoord[n].copy(e.barycoord[t])}};function nd(e,t,n,r,i,s){switch(Kh.fromBufferAttribute(e,t),Qh.fromBufferAttribute(e,n),Zh.fromBufferAttribute(e,r),s.set(0,0,0,0).addScaledVector(Kh,i.x).addScaledVector(Qh,i.y).addScaledVector(Zh,i.z),e.itemSize){case 3:Yh.w=0;break;case 2:Yh.w=0,Yh.z=0;break;case 1:Yh.w=0,Yh.z=0,Yh.y=0}return s}function rd(...e){let t="";for(let n=0,r=e.length;n<r;n++)t+=~~(1e5*e[n]+.5),n!==r-1&&(t+="_");return t}var id=class{constructor(){this.canvas=null,this.context=null,this.range=[0,0,1,1]}setTarget(e,t){this.canvas=e.image,this.context=e.image.getContext("2d"),this.range=[...t]}draw(e,t){let{canvas:n,range:i,context:s}=this,{width:a,height:o}=n,{image:l}=e,c=Math.round(r.MathUtils.mapLinear(t[0],i[0],i[2],0,a)),u=Math.round(r.MathUtils.mapLinear(t[1],i[1],i[3],0,o)),h=Math.round(r.MathUtils.mapLinear(t[2],i[0],i[2],0,a))-c,d=Math.round(r.MathUtils.mapLinear(t[3],i[1],i[3],0,o))-u;l instanceof ImageBitmap?(s.save(),s.translate(c,o-u),s.scale(1,-1),s.drawImage(l,0,0,h,d),s.restore()):s.drawImage(l,c,o-u,h,-d)}clear(){let{context:e,canvas:t}=this;e.clearRect(0,0,t.width,t.height)}};var sd=class extends qh{hasContent(...e){return!0}},ad=class extends sd{constructor(e){super(),this.tiledImageSource=e,this.tileComposer=new id,this.resolution=256}hasContent(e,t,n,r,i){let s=this.tiledImageSource.tiling,a=0;return Wh([e,t,n,r],i,s,(()=>{a++})),0!==a}async fetchItem([e,t,n,i,s],a){let{tiledImageSource:o,tileComposer:l}=this,c=[e,t,n,i],u=o.tiling;await this._markImages(c,s,!1),null==a||a.throwIfAborted();let h=null;if(Wh(c,s,u,((e,t,n)=>{(function(e,t,n=0){if(e.length!==t.length)return!1;for(let r=0,i=e.length;r<i;r++)if(Math.abs(e[r]-t[r])>n)return!1;return!0})(u.getTileBounds(e,t,n,!0,!1),c,1e-10)&&(h=[e,t,n])})),null!==h){let[e,t,n]=h;return o.get(e,t,n).clone()}let d=document.createElement("canvas");d.width=this.resolution,d.height=this.resolution;let p=new r.CanvasTexture(d);return p.colorSpace=r.SRGBColorSpace,p.generateMipmaps=!1,l.setTarget(p,c),l.clear(16777215,0),Wh(c,s,u,((e,t,n)=>{let r=u.getTileBounds(e,t,n,!0,!1),i=o.get(e,t,n);l.draw(i,r)})),p}disposeItem(e,[t,n,r,i,s]){e&&e.dispose(),this._markImages([t,n,r,i],s,!0)}dispose(){super.dispose(),this.tiledImageSource.dispose()}_markImages(e,t,n=!1){let r=this.tiledImageSource,i=r.tiling,s=[];Wh(e,t,i,((e,t,i)=>{n?r.release(e,t,i):s.push(r.lock(e,t,i))}));let a=s.filter((e=>e instanceof Promise));return 0===a.length?null:Promise.all(a)}},od=new Ol;od.maxJobs=10,od.priorityCallback=(e,t)=>{let n=e.tile,r=t.tile,i=n.internal.renderer,s=r.internal.renderer,a=i.visibleTiles.has(n);return a===s.visibleTiles.has(r)?cc(n,r):a?1:-1};var ld=class{get isPlanarProjection(){return!!this.frame}constructor(e={}){let{opacity:t=1,color:n=16777215,frame:i=null,preprocessURL:s=null,alphaMask:a=!1,alphaInvert:o=!1}=e;this.preprocessURL=s,this.opacity=t,this.color=new r.Color(n),this.frame=null===i?null:i.clone(),this.alphaMask=a,this.alphaInvert=o,this.downloadQueue=hc,this._whenReady=null,this.isReady=!1,this.isInitialized=!1,this._visibleRegionCounts=new Map}init(){return this.isInitialized||(this.isInitialized=!0,this._whenReady=this._init().then((()=>this.isReady=!0))),this._whenReady}whenReady(){return this._whenReady}_init(){return Promise.resolve()}fetch(e,t={}){this.preprocessURL&&(e=this.preprocessURL(e));let n={priority:-performance.now()},r=this.downloadQueue.add(n,(()=>fetch(e,t)));return t.signal&&t.signal.addEventListener("abort",(()=>this.downloadQueue.remove(n)),{once:!0}),r}getAttributions(e){}hasContent(e,t=null){return!1}async getTexture(e,t=null){return null}async lockTexture(e,t=null){return null}lockTextureSafe(e){let t=this.lockTexture(e);return t instanceof Promise&&t.catch((e=>{if("AbortError"!==e.name)throw e})),t}releaseTexture(e,t=null){}shouldSplit(e,t=null){return!1}setResolution(e){}setRegionVisible(e,t){let{_visibleRegionCounts:n}=this,r=e.join("_"),i=n.get(r);if(i||(i={range:[...e],count:0},n.set(r,i)),i.count+=t?1:-1,i.count<0)throw Error();0===i.count&&n.delete(r)}},cd=class extends ld{get tiling(){return this.imageSource.tiling}get projection(){return this.tiling.projection}get aspectRatio(){return this.tiling&&this.isReady?this.tiling.aspectRatio:1}get fetchOptions(){return this.imageSource.fetchOptions}set fetchOptions(e){this.imageSource.fetchOptions=e}constructor(e={}){let{imageSource:t=null,...n}=e;super(n),this.imageSource=t,this.regionImageSource=null}_init(){return this._initImageSource().then((()=>{this.imageSource.fetchData=(...e)=>this.fetch(...e),this.regionImageSource=new ad(this.imageSource)}))}_initImageSource(){return this.imageSource.init()}calculateLevel(e,t=null){let[n,r,i,s]=e,a=i-n,o=s-r;null===t&&(t=this.regionImageSource.resolution);let l=0,c=this.tiling.maxLevel;for(;l<c;l++){let e=t/a,n=t/o,r=this.tiling.getLevel(l);if(null==r)continue;let{pixelWidth:i,pixelHeight:s}=r;if(i>=e||s>=n)break}return l}hasContent(e,t=this.calculateLevel(e)){return this.regionImageSource.hasContent(...e,t)}getTexture(e,t=this.calculateLevel(e)){return this.regionImageSource.get(...e,t)}lockTexture(e,t=this.calculateLevel(e)){return this.regionImageSource.lock(...e,t)}releaseTexture(e,t=this.calculateLevel(e)){this.regionImageSource.release(...e,t)}shouldSplit(e,t=this.calculateLevel(e)){return this.tiling.maxLevel>t}setResolution(e){this.regionImageSource.resolution=e}},ud=class extends cd{constructor(e={}){super(e),this.imageSource=new jh(e)}},hd=new r.Vector3,dd=new r.Triangle,pd=new r.Vector3,md=new r.Vector3,fd=class extends Ah{constructor(e=r.DefaultLoadingManager){super(),this.manager=e,this.ellipsoid=new uu,this.skirtLength=1e3,this.smoothSkirtNormals=!0,this.generateNormals=!0,this.solid=!1,this.minLat=-Math.PI/2,this.maxLat=Math.PI/2,this.minLon=-Math.PI,this.maxLon=Math.PI}parse(e){let{ellipsoid:t,solid:n,skirtLength:i,smoothSkirtNormals:s,generateNormals:a,minLat:o,maxLat:l,minLon:c,maxLon:u}=this,{header:h,indices:d,vertexData:p,edgeIndices:m,extensions:f}=super.parse(e),g=new r.BufferGeometry,x=new r.MeshStandardMaterial,y=new r.Mesh(g,x);y.position.set(...h.center);let v="octvertexnormals"in f,b=v||a,w=p.u.length,T=[],S=[],_=[],M=[],A=0,E=0;for(let r=0;r<w;r++)R(r,pd),D(pd.x,pd.y,pd.z,md),S.push(pd.x,pd.y),T.push(...md);for(let r=0,I=d.length;r<I;r++)_.push(d[r]);if(b)if(v){let e=f.octvertexnormals.normals;for(let t=0,n=e.length;t<n;t++)M.push(e[t])}else{let e=new r.BufferGeometry,t=d.length>21845?new Uint32Array(d):new Uint16Array(d);e.setIndex(new r.BufferAttribute(t,1,!1)),e.setAttribute("position",new r.BufferAttribute(new Float32Array(T),3,!1)),e.computeVertexNormals();let n=e.getAttribute("normal").array;f.octvertexnormals={normals:n};for(let r=0,i=n.length;r<i;r++)M.push(n[r])}if(g.addGroup(A,d.length,E),A+=d.length,E++,n){let e=T.length/3;for(let t=0;t<w;t++)R(t,pd),D(pd.x,pd.y,pd.z,md,-i),S.push(pd.x,pd.y),T.push(...md);for(let t=d.length-1;t>=0;t--)_.push(d[t]+e);if(b){let e=f.octvertexnormals.normals;for(let t=0,n=e.length;t<n;t++)M.push(-e[t])}g.addGroup(A,d.length,E),A+=d.length,E++}if(i>0){let e,{westIndices:t,eastIndices:n,southIndices:r,northIndices:i}=m,s=k(t);e=T.length/3,S.push(...s.uv),T.push(...s.positions);for(let c=0,u=s.indices.length;c<u;c++)_.push(s.indices[c]+e);let a=k(n);e=T.length/3,S.push(...a.uv),T.push(...a.positions);for(let c=0,u=a.indices.length;c<u;c++)_.push(a.indices[c]+e);let o=k(r);e=T.length/3,S.push(...o.uv),T.push(...o.positions);for(let c=0,u=o.indices.length;c<u;c++)_.push(o.indices[c]+e);let l=k(i);e=T.length/3,S.push(...l.uv),T.push(...l.positions);for(let c=0,u=l.indices.length;c<u;c++)_.push(l.indices[c]+e);b&&(M.push(...s.normals),M.push(...a.normals),M.push(...o.normals),M.push(...l.normals)),g.addGroup(A,d.length,E),A+=d.length,E++}for(let r=0,I=T.length;r<I;r+=3)T[r+0]-=h.center[0],T[r+1]-=h.center[1],T[r+2]-=h.center[2];let C=T.length/3>65535?new Uint32Array(_):new Uint16Array(_);if(g.setIndex(new r.BufferAttribute(C,1,!1)),g.setAttribute("position",new r.BufferAttribute(new Float32Array(T),3,!1)),g.setAttribute("uv",new r.BufferAttribute(new Float32Array(S),2,!1)),b&&g.setAttribute("normal",new r.BufferAttribute(new Float32Array(M),3,!1)),"watermask"in f){let{mask:e,size:t}=f.watermask,n=new Uint8Array(2*t*t);for(let r=0,s=e.length;r<s;r++){let t=255===e[r]?0:255;n[2*r+0]=t,n[2*r+1]=t}let i=new r.DataTexture(n,t,t,r.RGFormat,r.UnsignedByteType);i.flipY=!0,i.minFilter=r.LinearMipMapLinearFilter,i.magFilter=r.LinearFilter,i.needsUpdate=!0,x.roughnessMap=i}return y.userData.minHeight=h.minHeight,y.userData.maxHeight=h.maxHeight,"metadata"in f&&(y.userData.metadata=f.metadata.json),y;function R(e,t){return t.x=p.u[e],t.y=p.v[e],t.z=p.height[e],t}function D(e,n,i,s,a=0){let d=r.MathUtils.lerp(h.minHeight,h.maxHeight,i),p=r.MathUtils.lerp(c,u,e),m=r.MathUtils.lerp(o,l,n);return t.getCartographicToPosition(m,p,d+a,s),s}function k(e){let t=[],n=[],r=[],a=[],o=[];for(let s=0,u=e.length;s<u;s++)R(e[s],pd),t.push(pd.x,pd.y),r.push(pd.x,pd.y),D(pd.x,pd.y,pd.z,md),n.push(...md),D(pd.x,pd.y,pd.z,md,-i),a.push(...md);let l=e.length-1;for(let i=0;i<l;i++){let t=i,n=i+1,r=i+e.length,s=i+e.length+1;o.push(t,r,n),o.push(n,r,s)}let c=null;if(b){let t=(n.length+a.length)/3;if(s){c=Array(3*t);let n=f.octvertexnormals.normals,r=c.length/2;for(let i=0,s=t/2;i<s;i++){let t=e[i],s=3*i,a=n[3*t+0],o=n[3*t+1],l=n[3*t+2];c[s+0]=a,c[s+1]=o,c[s+2]=l,c[r+s+0]=a,c[r+s+1]=o,c[r+s+2]=l}}else{c=[],dd.a.fromArray(n,0),dd.b.fromArray(a,0),dd.c.fromArray(n,3),dd.getNormal(hd);for(let e=0;e<t;e++)c.push(...hd)}}return{uv:[...t,...r],positions:[...n,...a],indices:o,normals:c}}}},gd={},xd=new r.Vector3,yd=new r.Vector3,vd=new r.Vector3,bd=new r.Vector3,wd=new r.Vector3,Td=new r.Vector3,Sd=new r.Vector3,_d=new r.Vector2,Md=new r.Vector2,Ad=new r.Vector2,Ed=class extends Jh{constructor(){super(),this.ellipsoid=new uu,this.skirtLength=1e3,this.smoothSkirtNormals=!0,this.solid=!1,this.minLat=-Math.PI/2,this.maxLat=Math.PI/2,this.minLon=-Math.PI,this.maxLon=Math.PI,this.attributeList=["position","normal","uv"]}clipToQuadrant(e,t,n){let{solid:r,skirtLength:i,ellipsoid:s,smoothSkirtNormals:a}=this;this.clearSplitOperations(),this.addSplitOperation(Cd("x"),!t),this.addSplitOperation(Cd("y"),!n);let o,l,c=e.geometry.groups[0],u=this.getClippedData(e,c);if(this.adjustVertices(u,e.position,0),r){o={index:u.index.slice().reverse(),attributes:{}};for(let e in u.attributes)o.attributes[e]=u.attributes[e].slice();let t=o.attributes.normal;if(t)for(let e=0;e<t.length;e+=3)t[e+0]*=-1,t[e+1]*=-1,t[e+2]*=-1;this.adjustVertices(o,e.position,-i)}if(i>0){l={index:[],attributes:{position:[],normal:[],uv:[]}};let t=0,n={},r=(e,r,i)=>{let s=rd(...e,...i,...r);s in n||(n[s]=t,t++,l.attributes.position.push(...e),l.attributes.normal.push(...i),l.attributes.uv.push(...r)),l.index.push(n[s])},o=u.index,c=u.attributes.uv,h=u.attributes.position,d=u.attributes.normal,p=u.index.length/3;for(let l=0;l<p;l++){let t=3*l;for(let n=0;n<3;n++){let l=(n+1)%3,u=o[t+n],p=o[t+l];if(_d.fromArray(c,2*u),Md.fromArray(c,2*p),_d.x===Md.x&&(0===_d.x||.5===_d.x||1===_d.x)||_d.y===Md.y&&(0===_d.y||.5===_d.y||1===_d.y)){yd.fromArray(h,3*u),vd.fromArray(h,3*p);let t=yd,n=vd,o=bd.copy(yd),l=wd.copy(vd);Td.copy(o).add(e.position),s.getPositionToNormal(Td,Td),o.addScaledVector(Td,-i),Td.copy(l).add(e.position),s.getPositionToNormal(Td,Td),l.addScaledVector(Td,-i),a&&d?(Td.fromArray(d,3*u),Sd.fromArray(d,3*p)):(Td.subVectors(t,n),Sd.subVectors(t,o).cross(Td).normalize(),Td.copy(Sd)),r(n,Md,Sd),r(t,_d,Td),r(o,_d,Td),r(n,Md,Sd),r(o,_d,Td),r(l,Md,Sd)}}}}let h=u.index.length,d=u;if(o){let{index:e,attributes:t}=o,n=d.attributes.position.length/3;for(let r=0,i=e.length;r<i;r++)d.index.push(e[r]+n);for(let r in u.attributes)d.attributes[r].push(...t[r])}if(l){let{index:e,attributes:t}=l,n=d.attributes.position.length/3;for(let r=0,i=e.length;r<i;r++)d.index.push(e[r]+n);for(let r in u.attributes)d.attributes[r].push(...t[r])}let p=t?0:-.5,m=n?0:-.5,f=d.attributes.uv;for(let v=0,b=f.length;v<b;v+=2)f[v]=2*(f[v]+p),f[v+1]=2*(f[v+1]+m);let g=this.constructMesh(d.attributes,d.index,e);g.userData.minHeight=e.userData.minHeight,g.userData.maxHeight=e.userData.maxHeight;let x=0,y=0;return g.geometry.addGroup(y,h,x),y+=h,x++,o&&(g.geometry.addGroup(y,o.index.length,x),y+=o.index.length,x++),l&&(g.geometry.addGroup(y,l.index.length,x),y+=l.index.length,x++),g}adjustVertices(e,t,n){let{ellipsoid:i,minLat:s,maxLat:a,minLon:o,maxLon:l}=this,{attributes:c,vertexIsClipped:u}=e,h=c.position,d=c.uv,p=h.length/3;for(let m=0;m<p;m++){let e=_d.fromArray(d,2*m);u&&u[m]&&(Math.abs(e.x-.5)<1e-10&&(e.x=.5),Math.abs(e.y-.5)<1e-10&&(e.y=.5),_d.toArray(d,2*m));let c=r.MathUtils.lerp(s,a,e.y),p=r.MathUtils.lerp(o,l,e.x),f=xd.fromArray(h,3*m).add(t);i.getPositionToCartographic(f,gd),i.getCartographicToPosition(c,p,gd.height+n,f),f.sub(t),f.toArray(h,3*m)}}};function Cd(e){return(t,n,r,i,s)=>{let a=t.attributes.uv;return _d.fromBufferAttribute(a,n),Md.fromBufferAttribute(a,r),Ad.fromBufferAttribute(a,i),_d[e]*s.x+Md[e]*s.y+Ad[e]*s.z-.5}}var Rd=Symbol("TILE_X"),Dd=Symbol("TILE_Y"),kd=Symbol("TILE_LEVEL"),Id=Symbol("TILE_AVAILABLE"),Pd=Symbol("TILE_SPLIT_SOURCE_SCENE"),Ld=new r.Vector3;function Ud(e){let{available:t=null,maxzoom:n=null}=e;return null===n?t.length-1:n}function Fd(e,t){let n=e[kd],r=function(e){let{metadataAvailability:t=-1}=e;return t}(t);return n<Ud(t)&&-1!==r&&n%r==0}var zd=class{constructor(e={}){let{useRecommendedSettings:t=!0,skirtLength:n=null,smoothSkirtNormals:r=!0,generateNormals:i=!0,solid:s=!1}=e;this.name="QUANTIZED_MESH_PLUGIN",this.priority=-1e3,this.tiles=null,this.layer=null,this.useRecommendedSettings=t,this.skirtLength=n,this.smoothSkirtNormals=r,this.solid=s,this.generateNormals=i,this.attribution=null,this.tiling=new Ih,this.projection=new Dh}init(e){e.fetchOptions.headers=e.fetchOptions.headers||{},e.fetchOptions.headers.Accept="application/vnd.quantized-mesh,application/octet-stream;q=0.9",this.useRecommendedSettings&&(e.errorTarget=2),this.tiles=e}loadRootTileset(){let{tiles:e}=this,t=new URL("layer.json",new URL(e.rootURL,location.href));return e.invokeAllPlugins((e=>t=e.preprocessURL?e.preprocessURL(t,null):t)),e.invokeOnePlugin((e=>e.fetchData&&e.fetchData(t,this.tiles.fetchOptions))).then((e=>e.json())).then((e=>{this.layer=e;let{projection:t="EPSG:4326",extensions:n=[],attribution:r="",available:i=null}=e,{tiling:s,tiles:a,projection:o}=this;r&&(this.attribution={value:r,type:"string",collapsible:!0}),n.length>0&&(a.fetchOptions.headers.Accept+=`;extensions=${n.join("-")}`),o.setScheme(t);let{tileCountX:l,tileCountY:c}=o;s.setProjection(o),s.generateLevels(Ud(e)+1,l,c);let u=[];for(let p=0;p<l;p++){let e=this.createChild(0,p,0,i);e&&u.push(e)}let h={asset:{version:"1.1"},geometricError:1/0,root:{refine:"REPLACE",geometricError:1/0,boundingVolume:{region:[...this.tiling.getContentBounds(),-1e4,1e4]},children:u,[Id]:i,[kd]:-1}},d=a.rootURL;return a.invokeAllPlugins((e=>d=e.preprocessURL?e.preprocessURL(d,null):d)),a.preprocessTileset(h,d),h}))}parseToMesh(e,t,n,r){let i,{skirtLength:s,solid:a,smoothSkirtNormals:o,generateNormals:l,tiles:c}=this,u=c.ellipsoid;if("quantized_tile_split"===n){let e=new URL(r).searchParams,n="true"===e.get("left"),l="true"===e.get("bottom"),c=new Ed;c.ellipsoid.copy(u),c.solid=a,c.smoothSkirtNormals=o,c.skirtLength=null===s?t.geometricError:s;let[h,d,p,m]=t.parent.boundingVolume.region;c.minLat=d,c.maxLat=m,c.minLon=h,c.maxLon=p;let f=t.parent.engineData.scene||t.parent[Pd];i=c.clipToQuadrant(f,n,l)}else{if("terrain"!==n)return;{let n=new fd(c.manager);n.ellipsoid.copy(u),n.solid=a,n.smoothSkirtNormals=o,n.generateNormals=l,n.skirtLength=null===s?t.geometricError:s;let[r,h,d,p]=t.boundingVolume.region;n.minLat=h,n.maxLat=p,n.minLon=r,n.maxLon=d,i=n.parse(e)}}let{minHeight:h,maxHeight:d,metadata:p}=i.userData;return t.boundingVolume.region[4]=h,t.boundingVolume.region[5]=d,t.engineData.boundingVolume.setRegionData(u,...t.boundingVolume.region),p&&("geometricerror"in p&&(t.geometricError=p.geometricerror),Fd(t,this.layer)&&"available"in p&&0===t.children.length&&(t[Id]=[...Array(t[kd]+1).fill(null),...p.available])),t[Pd]=i,this.expandChildren(t),i}getAttributions(e){this.attribution&&e.push(this.attribution)}createChild(e,t,n,r){let{tiles:i,layer:s,tiling:a,projection:o}=this,l=i.ellipsoid,c=null===r&&0===e||function(e,t,n,r){if(e&&t<e.length){let i=e[t];for(let e=0,t=i.length;e<t;e++){let{startX:t,startY:s,endX:a,endY:o}=i[e];if(n>=t&&n<=a&&r>=s&&r<=o)return!0}}return!1}(r,e,t,n),u=function(e,t,n,r,i){return i.tiles[0].replace(/{\s*z\s*}/g,n).replace(/{\s*x\s*}/g,e).replace(/{\s*y\s*}/g,t).replace(/{\s*version\s*}/g,r)}(t,n,e,1,s),h=[...a.getTileBounds(t,n,e),-1e4,1e4],[,d,,p,,m]=h,f=d>0==p>0?Math.min(Math.abs(d),Math.abs(p)):0;l.getCartographicToPosition(f,0,m,Ld),Ld.z=0;let g=o.tileCountX,x=2*Math.max(...l.radius)*Math.PI*.25/(65*g)/2**e,y={[Id]:null,[kd]:e,[Rd]:t,[Dd]:n,refine:"REPLACE",geometricError:x,boundingVolume:{region:h},content:c?{uri:u}:null,children:[]};return Fd(y,s)||(y[Id]=r),y}expandChildren(e){let t=e[kd],n=e[Rd],r=e[Dd],i=e[Id];if(t>=this.tiling.maxLevel)return;let s=!1;for(let a=0;a<2;a++)for(let o=0;o<2;o++){let l=this.createChild(t+1,2*n+a,2*r+o,i);null===l.content?(l.content={uri:`tile.quantized_tile_split?bottom=${0===o}&left=${0===a}`},l.internal={isVirtual:!0},e.internal.virtualChildCount++,e.children.push(l)):(e.children.push(l),s=!0)}s||(e.children.length-=e.internal.virtualChildCount,e.internal.virtualChildCount=0)}fetchData(e,t){if(/quantized_tile_split/.test(e))return new ArrayBuffer}disposeTile(e){let{tiles:t,layer:n}=this;if(delete e[Pd],Fd(e,n)&&(e[Id]=null),Id in e){let{virtualChildCount:n}=e.internal,r=e.children.length;for(let i=r-n;i<r;i++)t.processNodeQueue.remove(e.children[i]);e.children.length=0,e.internal.virtualChildCount=0}}},Bd=class extends vh{constructor(e={}){super({assetTypeHandler:(e,t,n)=>{if("TERRAIN"===e&&null===t.getPluginByName("QUANTIZED_MESH_PLUGIN"))t.registerPlugin(new zd({useRecommendedSettings:this.useRecommendedSettings}));else if("IMAGERY"===e&&null===t.getPluginByName("GENERATED_SURFACE_PLUGIN")){let e=new ud({url:t.rootURL});t.registerPlugin(new Nh({shape:"ellipsoid",overlay:e}))}},...e})}},Vd=new r.Matrix4,Od=class{constructor(){this.name="UPDATE_ON_CHANGE_PLUGIN",this.tiles=null,this.needsUpdate=!1,this.cameraMatrices=new Map}init(e){this.tiles=e,this._needsUpdateCallback=()=>{this.needsUpdate=!0},this._onCameraAdd=({camera:e})=>{this.needsUpdate=!0,this.cameraMatrices.set(e,new r.Matrix4)},this._onCameraDelete=({camera:e})=>{this.needsUpdate=!0,this.cameraMatrices.delete(e)},e.addEventListener("needs-update",this._needsUpdateCallback),e.addEventListener("add-camera",this._onCameraAdd),e.addEventListener("delete-camera",this._onCameraDelete),e.addEventListener("camera-resolution-change",this._needsUpdateCallback),e.cameras.forEach((e=>{this._onCameraAdd({camera:e})}))}doTilesNeedUpdate(){let e=this.tiles,t=!1;this.cameraMatrices.forEach(((n,r)=>{Vd.copy(e.group.matrixWorld).premultiply(r.matrixWorldInverse).premultiply(r.projectionMatrixInverse),t||(t=!Vd.equals(n)),n.copy(Vd)}));let n=this.needsUpdate;return this.needsUpdate=!1,n||t}preprocessNode(){this.needsUpdate=!0}dispose(){let e=this.tiles;e.removeEventListener("camera-resolution-change",this._needsUpdateCallback),e.removeEventListener("needs-update",this._needsUpdateCallback),e.removeEventListener("add-camera",this._onCameraAdd),e.removeEventListener("delete-camera",this._onCameraDelete)}},Nd=new r.Vector3;function $d(e,t){if(e.isInterleavedBufferAttribute||e.array instanceof t)return e;let n=t===Int8Array||t===Int16Array||t===Int32Array?-1:0,i=new r.BufferAttribute(new t(e.count*e.itemSize),e.itemSize,!0),s=e.itemSize,a=e.count;for(let o=0;o<a;o++)for(let t=0;t<s;t++){let s=r.MathUtils.clamp(e.getComponent(o,t),n,1);i.setComponent(o,t,s)}return i}var Gd=class{constructor(e){this._options={generateNormals:!1,disableMipmaps:!0,compressIndex:!0,compressNormals:!1,compressUvs:!1,compressPosition:!1,uvType:Int8Array,normalType:Int8Array,positionType:Int16Array,...e},this.name="TILES_COMPRESSION_PLUGIN",this.priority=-100}processTileModel(e,t){let{generateNormals:n,disableMipmaps:i,compressIndex:s,compressUvs:a,compressNormals:o,compressPosition:l,uvType:c,normalType:u,positionType:h}=this._options;e.traverse((e=>{if(e.material&&i){let t=e.material;for(let e in t){let n=t[e];n&&n.isTexture&&n.generateMipmaps&&(n.generateMipmaps=!1,n.minFilter=r.LinearFilter)}}if(e.geometry){let t=e.geometry,i=t.attributes;if(a){let{uv:e,uv1:t,uv2:n,uv3:r}=i;e&&(i.uv=$d(e,c)),t&&(i.uv1=$d(t,c)),n&&(i.uv2=$d(n,c)),r&&(i.uv3=$d(r,c))}if(n&&!i.normals&&t.computeVertexNormals(),o&&i.normals&&(i.normals=$d(i.normals,u)),l&&function(e,t=Int16Array){let n=e.geometry,i=n.attributes,s=i.position;if(s.isInterleavedBufferAttribute||s.array instanceof t)return s;let a=new r.BufferAttribute(new t(s.count*s.itemSize),s.itemSize,!1),o=s.itemSize,l=s.count;n.computeBoundingBox();let c=n.boundingBox,{min:u,max:h}=c,d=2**(8*t.BYTES_PER_ELEMENT-1)-1,p=-d;for(let m=0;m<l;m++)for(let e=0;e<o;e++){let t=0===e?"x":1===e?"y":"z",n=u[t],i=h[t],o=r.MathUtils.mapLinear(s.getComponent(m,e),n,i,p,d);a.setComponent(m,e,o)}c.getCenter(Nd).multiply(e.scale).applyQuaternion(e.quaternion),e.position.add(Nd),e.scale.x*=.5*(h.x-u.x)/d,e.scale.y*=.5*(h.y-u.y)/d,e.scale.z*=.5*(h.z-u.z)/d,i.position=a,e.geometry.boundingBox=null,e.geometry.boundingSphere=null,e.updateMatrixWorld()}(e,h),s&&t.index){let e=i.position.count,n=t.index,s=e>65535?Uint32Array:e>255?Uint16Array:Uint8Array;if(!(n.array instanceof s)){let e=new s(t.index.count);e.set(n.array);let i=new r.BufferAttribute(e,1);t.setIndex(i)}}}}))}};function qd(e,t,n){return e&&t in e?e[t]:n}function Hd(e){return"BOOLEAN"!==e&&"STRING"!==e&&"ENUM"!==e}function jd(e){return/^VEC/.test(e)}function Wd(e){return/^MAT/.test(e)}function Xd(e,t,n,r=null){return Wd(n)||jd(n)?r.fromArray(e,t):e[t]}function Yd(e){let{type:t,componentType:n}=e;switch(t){case"SCALAR":return"INT64"===n?0n:0;case"VEC2":return new r.Vector2;case"VEC3":return new r.Vector3;case"VEC4":return new r.Vector4;case"MAT2":return new r.Matrix2;case"MAT3":return new r.Matrix3;case"MAT4":return new r.Matrix4;case"BOOLEAN":return!1;case"STRING":return"";case"ENUM":return 0}}function Kd(e,t){if(null==t)return!1;switch(e){case"SCALAR":case"ENUM":return"number"==typeof t||"bigint"==typeof t;case"VEC2":return t.isVector2;case"VEC3":return t.isVector3;case"VEC4":return t.isVector4;case"MAT2":return t.isMatrix2;case"MAT3":return t.isMatrix3;case"MAT4":return t.isMatrix4;case"BOOLEAN":return"boolean"==typeof t;case"STRING":return"string"==typeof t}throw Error("ClassProperty: invalid type.")}function Qd(e,t=null){switch(e){case"INT8":return Int8Array;case"INT16":return Int16Array;case"INT32":return Int32Array;case"INT64":return BigInt64Array;case"UINT8":return Uint8Array;case"UINT16":return Uint16Array;case"UINT32":return Uint32Array;case"UINT64":return BigUint64Array;case"FLOAT32":return Float32Array;case"FLOAT64":return Float64Array}switch(t){case"BOOLEAN":case"STRING":return Uint8Array}throw Error("ClassProperty: invalid type.")}function Zd(e,t=null){let n=e.default,r=e.type;if(t||(t=Yd(e)),null===n){switch(r){case"SCALAR":return 0;case"VEC2":return t.set(0,0);case"VEC3":return t.set(0,0,0);case"VEC4":return t.set(0,0,0,0);case"MAT2":case"MAT3":case"MAT4":return t.identity();case"BOOLEAN":return!1;case"STRING":case"ENUM":return""}throw Error("ClassProperty: invalid type.")}if(Wd(r))t.fromArray(n);else{if(!jd(r))return n;t.fromArray(n)}}function Jd(e,t){if(null===e.noData)return t;let n=e.noData,r=e.type;if(Array.isArray(t))for(let s=0,a=t.length;s<a;s++)t[s]=i(t[s]);else t=i(t);return t;function i(t){return function(e){if(Wd(r)){let t=e.elements;for(let e=0,r=n.length;e<r;e++)if(n[e]!==t[e])return!1;return!0}if(jd(r)){for(let t=0,r=n.length;t<r;t++)if(n[t]!==e.getComponent(t))return!1;return!0}return n===e}(t)&&(t=Zd(e,t)),t}}function ep(e,t){let{type:n,componentType:r,scale:i,offset:s,normalized:a}=e;if(Array.isArray(t))for(let c=0,u=t.length;c<u;c++)t[c]=o(t[c]);else t=o(t);return t;function o(e){return e=Wd(n)?function(e){let t=e.elements;for(let n=0,r=t.length;n<r;n++)t[n]=l(t[n]);return e}(e):jd(n)?function(e){return e.x=l(e.x),e.y=l(e.y),"z"in e&&(e.z=l(e.z)),"w"in e&&(e.w=l(e.w)),e}(e):l(e)}function l(e){return a&&(e=function(e,t){switch(e){case"INT8":return Math.max(t/127,-1);case"INT16":return Math.max(t,32767,-1);case"INT32":return Math.max(t/2147483647,-1);case"INT64":return Math.max(Number(t)/0x8000000000000000,-1);case"UINT8":return t/255;case"UINT16":return t/65535;case"UINT32":return t/4294967295;case"UINT64":return Number(t)/0x10000000000000000}}(r,e)),(a||function(e){return/^FLOAT/.test(e)}(r))&&(e=e*i+s),e}}function tp(e,t,n=null){if(e.array){Array.isArray(t)||(t=Array(e.count||0)),t.length=null===n?e.count:n;for(let n=0,r=t.length;n<r;n++)Kd(e.type,t[n])||(t[n]=Yd(e))}else Kd(e.type,t)||(t=Yd(e));return t}function np(e,t){for(let n in t)n in e||delete t[n];for(let n in e){let r=e[n];t[n]=tp(r,t[n])}}var rp=class{constructor(e,t,n=null){this.name=t.name||null,this.description=t.description||null,this.type=t.type,this.componentType=t.componentType||null,this.enumType=t.enumType||null,this.array=t.array||!1,this.count=t.count||0,this.normalized=t.normalized||!1,this.offset=t.offset||0,this.scale=qd(t,"scale",1),this.max=qd(t,"max",1/0),this.min=qd(t,"min",-1/0),this.required=t.required||!1,this.noData=qd(t,"noData",null),this.default=qd(t,"default",null),this.semantic=qd(t,"semantic",null),this.enumSet=null,this.accessorProperty=n,n&&(this.offset=qd(n,"offset",this.offset),this.scale=qd(n,"scale",this.scale),this.max=qd(n,"max",this.max),this.min=qd(n,"min",this.min)),"ENUM"===t.type&&(this.enumSet=e[this.enumType],null===this.componentType&&(this.componentType=qd(this.enumSet,"valueType","UINT16")))}shapeToProperty(e,t=null){return tp(this,e,t)}resolveDefaultElement(e){return Zd(this,e)}resolveDefault(e){return function(e,t=null){if(e.array){(t=t&&Array.isArray(t)?t:[]).length=e.count;for(let n=0,r=t.length;n<r;n++)t[n]=Zd(e,t[n])}else t=Zd(e,t);return t}(this,e)}resolveNoData(e){return Jd(this,e)}resolveEnumsToStrings(e){let t=this.enumSet;if("ENUM"===this.type)if(Array.isArray(e))for(let r=0,i=e.length;r<i;r++)e[r]=n(e[r]);else e=n(e);return e;function n(e){let n=t.values.find((t=>t.value===e));return null===n?"":n.name}}adjustValueScaleOffset(e){return Hd(this.type)?ep(this,e):e}},ip=class{constructor(e,t={},n={},r=null){this.definition=e,this.class=t[e.class],this.className=e.class,this.enums=n,this.data=r,this.name="name"in e?e.name:null,this.properties=null}getPropertyNames(){return Object.keys(this.class.properties)}includesData(e){return!!this.definition.properties[e]}dispose(){}_initProperties(e=rp){let t={};for(let n in this.class.properties)t[n]=new e(this.enums,this.class.properties[n],this.definition.properties[n]);this.properties=t}},sp=class extends rp{constructor(e,t,n=null){super(e,t,n),this.attribute=(null==n?void 0:n.attribute)??null}},ap=class extends ip{constructor(...e){super(...e),this.isPropertyAttributeAccessor=!0,this._initProperties(sp)}getData(e,t,n={}){let r=this.properties;np(r,n);for(let i in r)n[i]=this.getPropertyValue(i,e,t,n[i]);return n}getPropertyValue(e,t,n,r=null){if(t>=this.count)throw Error("PropertyAttributeAccessor: Requested index is outside the range of the buffer.");let i=this.properties[e],s=i.type;if(!i)throw Error("PropertyAttributeAccessor: Requested class property does not exist.");if(!this.definition.properties[e])return i.resolveDefault(r);r=i.shapeToProperty(r);let a=n.getAttribute(i.attribute.toLowerCase());if(Wd(s)){let e=r.elements;for(let n=e.length;0<n;)e[0]=a.getComponent(t,0)}else if(jd(s))r.fromBufferAttribute(a,t);else{if("SCALAR"!==s&&"ENUM"!==s)throw Error("StructuredMetadata.PropertyAttributeAccessor: BOOLEAN and STRING types are not supported by property attributes.");r=a.getX(t)}return r=i.adjustValueScaleOffset(r),r=i.resolveEnumsToStrings(r),r=i.resolveNoData(r)}},op=class extends rp{constructor(e,t,n=null){super(e,t,n),this.values=(null==n?void 0:n.values)??null,this.valueLength=function(e){switch(e){case"ENUM":case"SCALAR":return 1;case"VEC2":return 2;case"VEC3":return 3;case"VEC4":case"MAT2":return 4;case"MAT3":return 9;case"MAT4":return 16;default:return-1}}(this.type),this.arrayOffsets=qd(n,"arrayOffsets",null),this.stringOffsets=qd(n,"stringOffsets",null),this.arrayOffsetType=qd(n,"arrayOffsetType","UINT32"),this.stringOffsetType=qd(n,"stringOffsetType","UINT32")}getArrayLengthFromId(e,t){let n=this.count;if(null!==this.arrayOffsets){let{arrayOffsets:r,arrayOffsetType:i}=this,s=new(Qd(i))(e[r]);n=s[t+1]-s[t]}return n}getIndexOffsetFromId(e,t){let n=t;if(this.arrayOffsets){let{arrayOffsets:t,arrayOffsetType:r}=this;n=new(Qd(r))(e[t])[n]}else this.array&&(n*=this.count);return n}},lp=class extends ip{constructor(...e){super(...e),this.isPropertyTableAccessor=!0,this.count=this.definition.count,this._initProperties(op)}getData(e,t={}){let n=this.properties;np(n,t);for(let r in n)t[r]=this.getPropertyValue(r,e,t[r]);return t}_readValueAtIndex(e,t,n,r=null){let i=this.properties[e],{componentType:s,type:a}=i,o=this.data,l=o[i.values],c=new(Qd(s,a))(l),u=i.getIndexOffsetFromId(o,t);if(Hd(a)||"ENUM"===a)return Xd(c,(u+n)*i.valueLength,a,r);if("STRING"===a){let e=u+n,t=0;if(null!==i.stringOffsets){let{stringOffsets:n,stringOffsetType:r}=i,s=new(Qd(r))(o[n]);t=s[e+1]-s[e],e=s[e]}let s=new Uint8Array(c.buffer,e,t);r=(new TextDecoder).decode(s)}else if("BOOLEAN"===a){let e=u+n,t=e%8;r=1==(c[Math.floor(e/8)]>>t&1)}return r}getPropertyValue(e,t,n=null){if(t>=this.count)throw Error("PropertyTableAccessor: Requested index is outside the range of the table.");let r=this.properties[e];if(!r)throw Error("PropertyTableAccessor: Requested property does not exist.");if(!this.definition.properties[e])return r.resolveDefault(n);let i=r.array,s=this.data,a=r.getArrayLengthFromId(s,t);if(n=r.shapeToProperty(n,a),i)for(let o=0,l=n.length;o<l;o++)n[o]=this._readValueAtIndex(e,t,o,n[o]);else n=this._readValueAtIndex(e,t,0,n);return n=r.adjustValueScaleOffset(n),n=r.resolveEnumsToStrings(n),n=r.resolveNoData(n)}},cp=new r.Box2,up=class{constructor(){this._renderer=new r.WebGLRenderer,this._target=new r.WebGLRenderTarget(1,1),this._texTarget=new r.WebGLRenderTarget,this._quad=new o(new r.ShaderMaterial({blending:r.CustomBlending,blendDst:r.ZeroFactor,blendSrc:r.OneFactor,uniforms:{map:{value:null},pixel:{value:new r.Vector2}},vertexShader:"\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n\n\t\t\t\t}\n\t\t\t",fragmentShader:"\n\t\t\t\tuniform sampler2D map;\n\t\t\t\tuniform ivec2 pixel;\n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tgl_FragColor = texelFetch( map, pixel, 0 );\n\n\t\t\t\t}\n\t\t\t"}))}increaseSizeTo(e){this._target.setSize(Math.max(this._target.width,e),1)}readDataAsync(e){let{_renderer:t,_target:n}=this;return t.readRenderTargetPixelsAsync(n,0,0,e.length/4,1,e)}readData(e){let{_renderer:t,_target:n}=this;t.readRenderTargetPixels(n,0,0,e.length/4,1,e)}renderPixelToTarget(e,t,n){let{_renderer:r,_target:i}=this;cp.min.copy(t),cp.max.copy(t),cp.max.x+=1,cp.max.y+=1,r.initRenderTarget(i),r.copyTextureToTexture(e,i.texture,cp,n,0)}},hp=new class{constructor(){let e=null;Object.getOwnPropertyNames(up.prototype).forEach((t=>{"constructor"!==t&&(this[t]=(...n)=>(e||(e=new up),e[t](...n)))}))}},dp=new r.Vector2,pp=new r.Vector2,mp=new r.Vector2;function fp(e,t,n=[,,,]){let r=3*t,i=3*t+1,s=3*t+2;return e.index&&(r=e.index.getX(r),i=e.index.getX(i),s=e.index.getX(s)),n[0]=r,n[1]=i,n[2]=s,n}function gp(e,t,n,r,i){let[s,a,o]=r,l=function(e,t){return 0===t?e.getAttribute("uv"):e.getAttribute(`uv${t}`)}(e,t);dp.fromBufferAttribute(l,s),pp.fromBufferAttribute(l,a),mp.fromBufferAttribute(l,o),i.set(0,0,0).addScaledVector(dp,n.x).addScaledVector(pp,n.y).addScaledVector(mp,n.z)}function xp(e,t,n,r){let i=e.x-Math.floor(e.x),s=e.y-Math.floor(e.y),a=Math.floor(i*t%t),o=Math.floor(s*n%n);return r.set(a,o),r}var yp=new r.Vector2,vp=new r.Vector2,bp=new r.Vector2,wp=class extends rp{constructor(e,t,n=null){super(e,t,n),this.channels=qd(n,"channels",[0]),this.index=qd(n,"index",null),this.texCoord=qd(n,"texCoord",null),this.valueLength=parseInt(this.type.replace(/[^0-9]/g,""))||1}readDataFromBuffer(e,t,n=null){let r=this.type;if("BOOLEAN"===r||"STRING"===r)throw Error("PropertyTextureAccessor: BOOLEAN and STRING types not supported.");return Xd(e,t*this.valueLength,r,n)}},Tp=class extends ip{constructor(...e){super(...e),this.isPropertyTextureAccessor=!0,this._asyncRead=!1,this._initProperties(wp)}getData(e,t,n,r={}){let i=this.properties;np(i,r);let s=Object.keys(i),a=s.map((e=>r[e]));return this.getPropertyValuesAtTexel(s,e,t,n,a),s.forEach(((e,t)=>r[e]=a[t])),r}async getDataAsync(e,t,n,r={}){let i=this.properties;np(i,r);let s=Object.keys(i),a=s.map((e=>r[e]));return await this.getPropertyValuesAtTexelAsync(s,e,t,n,a),s.forEach(((e,t)=>r[e]=a[t])),r}getPropertyValuesAtTexelAsync(...e){this._asyncRead=!0;let t=this.getPropertyValuesAtTexel(...e);return this._asyncRead=!1,t}getPropertyValuesAtTexel(e,t,n,r,i=[]){for(;i.length<e.length;)i.push(null);i.length=e.length,hp.increaseSizeTo(i.length);let s=this.data,a=this.definition.properties,o=this.properties,l=fp(r,t);for(let h=0,d=e.length;h<d;h++){let t=e[h];if(!a[t])continue;let i=o[t],c=s[i.index];gp(r,i.texCoord,n,l,yp),xp(yp,c.image.width,c.image.height,vp),bp.set(h,0),hp.renderPixelToTarget(c,vp,bp)}let c=new Uint8Array(4*e.length);return this._asyncRead?hp.readDataAsync(c).then((()=>(u.call(this),i))):(hp.readData(c),u.call(this),i);function u(){for(let t=0,n=e.length;t<n;t++){let n=e[t],r=o[n],s=r.type;if(i[t]=tp(r,i[t]),!r)throw Error("PropertyTextureAccessor: Requested property does not exist.");if(!a[n]){i[t]=r.resolveDefault(i);continue}let l=r.valueLength*(r.count||1),u=r.channels.map((e=>c[4*t+e])),h=new(Qd(r.componentType,s))(l);if(new Uint8Array(h.buffer).set(u),r.array){let e=i[t];for(let t=0,n=e.length;t<n;t++)e[t]=r.readDataFromBuffer(h,t,e[t])}else i[t]=r.readDataFromBuffer(h,0,i[t]);i[t]=r.adjustValueScaleOffset(i[t]),i[t]=r.resolveEnumsToStrings(i[t]),i[t]=r.resolveNoData(i[t])}}}dispose(){this.data.forEach((e=>{e&&(e.dispose(),e.image instanceof ImageBitmap&&e.image.close())}))}},Sp=class{constructor(e,t,n,r=null,i=null){let{schema:s,propertyTables:a=[],propertyTextures:o=[],propertyAttributes:l=[]}=e,{enums:c,classes:u}=s,h=a.map((e=>new lp(e,u,c,n))),d=[],p=[];r&&(r.propertyTextures&&(d=r.propertyTextures.map((e=>new Tp(o[e],u,c,t)))),r.propertyAttributes&&(p=r.propertyAttributes.map((e=>new ap(l[e],u,c))))),this.schema=s,this.tableAccessors=h,this.textureAccessors=d,this.attributeAccessors=p,this.object=i,this.textures=t,this.nodeMetadata=r}getPropertyTableData(e,t,n=null){if(Array.isArray(e)){n||(n=[]);let r=Math.min(e.length,t.length);n.length=r;for(let i=0;i<r;i++){let r=this.tableAccessors[e[i]];n[i]=r.getData(t[i],n[i])}}else n||(n={}),n=this.tableAccessors[e].getData(t,n);if(Array.isArray(e)!==Array.isArray(n)||Array.isArray(e)!==Array.isArray(t))throw Error("StructuralMetadata: Scalar and array inputs cannot be mixed.");return n}getPropertyTableInfo(e=null){if(null===e&&(e=this.tableAccessors.map(((e,t)=>t))),Array.isArray(e))return e.map((e=>{let t=this.tableAccessors[e];return{name:t.name,className:t.definition.class}}));{let t=this.tableAccessors[e];return{name:t.name,className:t.definition.class}}}getPropertyTextureData(e,t,n=[]){let r=this.textureAccessors;n.length=r.length;for(let i=0;i<r.length;i++)n[i]=r[i].getData(e,t,this.object.geometry,n[i]);return n}async getPropertyTextureDataAsync(e,t,n=[]){let r=this.textureAccessors;n.length=r.length;let i=[];for(let s=0;s<r.length;s++){let a=r[s].getDataAsync(e,t,this.object.geometry,n[s]).then((e=>{n[s]=e}));i.push(a)}return await Promise.all(i),n}getPropertyTextureInfo(){return this.textureAccessors}getPropertyAttributeData(e,t=[]){let n=this.attributeAccessors;t.length=n.length;for(let r=0;r<n.length;r++)t[r]=n[r].getData(e,this.object.geometry,t[r]);return t}getPropertyAttributeInfo(){return this.attributeAccessors.map((e=>({name:e.name,className:e.definition.class})))}dispose(){this.textureAccessors.forEach((e=>e.dispose())),this.tableAccessors.forEach((e=>e.dispose())),this.attributeAccessors.forEach((e=>e.dispose()))}},_p="EXT_structural_metadata";function Mp(e,t=[]){var n;let r=(null==(n=e.json.textures)?void 0:n.length)||0,i=Array(r).fill(null);return t.forEach((({properties:t})=>{for(let n in t){let{index:r}=t[n];null===i[r]&&(i[r]=e.loadTexture(r))}})),Promise.all(i)}function Ap(e,t=[]){var n;let r=(null==(n=e.json.bufferViews)?void 0:n.length)||0,i=Array(r).fill(null);return t.forEach((({properties:t})=>{for(let n in t){let{values:r,arrayOffsets:s,stringOffsets:a}=t[n];null===i[r]&&(i[r]=e.getDependency("bufferView",r)),null===i[s]&&(i[s]=e.getDependency("bufferView",s)),null===i[a]&&(i[a]=e.getDependency("bufferView",a))}})),Promise.all(i)}var Ep=class{constructor(e){this.parser=e,this.name=_p}async afterRoot({scene:e,parser:t}){let n=t.json.extensionsUsed;if(!n||!n.includes(_p))return;let i=null,s=t.json.extensions[_p];if(s.schemaUri){let{manager:e,path:n,requestHeader:a,crossOrigin:o}=t.options,l=new URL(s.schemaUri,n).toString(),c=new r.FileLoader(e);c.setCrossOrigin(o),c.setResponseType("json"),c.setRequestHeader(a),i=c.loadAsync(l).then((e=>{s={...s,schema:e}}))}let[a,o]=await Promise.all([Mp(t,s.propertyTextures),Ap(t,s.propertyTables),i]),l=new Sp(s,a,o);e.userData.structuralMetadata=l,e.traverse((e=>{var n;if(t.associations.has(e)){let{meshes:r,primitives:i}=t.associations.get(e),c=null==(n=t.json.meshes[r])?void 0:n.primitives[i];if(c&&c.extensions&&c.extensions[_p]){let t=c.extensions[_p];e.userData.structuralMetadata=new Sp(s,a,o,t,e)}else e.userData.structuralMetadata=l}}))}},Cp=new r.Vector2,Rp=new r.Vector2,Dp=new r.Vector2;var kp=class{constructor(e,t,n){this.geometry=e,this.textures=t,this.data=n,this._asyncRead=!1,this.featureIds=n.featureIds.map((e=>{let{texture:t,...n}=e,r={label:null,propertyTable:null,nullFeatureId:null,...n};return t&&(r.texture={texCoord:0,channels:[0],...t}),r}))}getTextures(){return this.textures}getFeatureInfo(){return this.featureIds}getFeaturesAsync(...e){this._asyncRead=!0;let t=this.getFeatures(...e);return this._asyncRead=!1,t}getFeatures(e,t){let{geometry:n,textures:r,featureIds:i}=this,s=Array(i.length).fill(null),a=i.length;hp.increaseSizeTo(a);let o=fp(n,e),l=o[function(e){return e.x>e.y&&e.x>e.z?0:e.y>e.z?1:2}(t)];for(let h=0,d=i.length;h<d;h++){let e=i[h],a="nullFeatureId"in e?e.nullFeatureId:null;if("texture"in e){let i=r[e.texture.index];gp(n,e.texture.texCoord,t,o,Cp),xp(Cp,i.image.width,i.image.height,Rp),Dp.set(h,0),hp.renderPixelToTarget(r[e.texture.index],Rp,Dp)}else if("attribute"in e){let t=n.getAttribute(`_feature_id_${e.attribute}`).getX(l);t!==a&&(s[h]=t)}else{let e=l;e!==a&&(s[h]=e)}}let c=new Uint8Array(4*a);return this._asyncRead?hp.readDataAsync(c).then((()=>(u(),s))):(hp.readData(c),u(),s);function u(){let e=new Uint32Array(1);for(let t=0,n=i.length;t<n;t++){let n=i[t],r="nullFeatureId"in n?n.nullFeatureId:null;if("texture"in n){let{channels:i}=n.texture,a=i.map((e=>c[4*t+e]));new Uint8Array(e.buffer).set(a);let o=e[0];o!==r&&(s[t]=o)}}}}dispose(){this.textures.forEach((e=>{e&&(e.dispose(),e.image instanceof ImageBitmap&&e.image.close())}))}},Ip="EXT_mesh_features";function Pp(e,t,n){e.traverse((e=>{var r;if(t.associations.has(e)){let{meshes:i,primitives:s}=t.associations.get(e),a=null==(r=t.json.meshes[i])?void 0:r.primitives[s];a&&a.extensions&&a.extensions[Ip]&&n(e,a.extensions[Ip])}}))}var Lp=class{constructor(e){this.parser=e,this.name=Ip}async afterRoot({scene:e,parser:t}){var n;let r=t.json.extensionsUsed;if(!r||!r.includes(Ip))return;let i=(null==(n=t.json.textures)?void 0:n.length)||0,s=Array(i).fill(null);Pp(e,t,((e,{featureIds:n})=>{n.forEach((e=>{if(e.texture&&null===s[e.texture.index]){let n=e.texture.index;s[n]=t.loadTexture(n)}}))}));let a=await Promise.all(s);Pp(e,t,((e,t)=>{e.userData.meshFeatures=new kp(e.geometry,a,t)}))}},Up=class{constructor(){this.name="CESIUM_RTC"}afterRoot(e){if(e.parser.json.extensions&&e.parser.json.extensions.CESIUM_RTC){let{center:t}=e.parser.json.extensions.CESIUM_RTC;t&&(e.scene.position.x+=t[0],e.scene.position.y+=t[1],e.scene.position.z+=t[2])}}},Fp=class{constructor(e){e={metadata:!0,rtc:!0,plugins:[],dracoLoader:null,ktxLoader:null,meshoptDecoder:null,autoDispose:!0,...e},this.tiles=null,this.metadata=e.metadata,this.rtc=e.rtc,this.plugins=e.plugins,this.dracoLoader=e.dracoLoader,this.ktxLoader=e.ktxLoader,this.meshoptDecoder=e.meshoptDecoder,this._gltfRegex=/\.(gltf|glb)$/g,this._dracoRegex=/\.drc$/g,this._loader=null}init(e){let t=new rt(e.manager);this.dracoLoader&&(t.setDRACOLoader(this.dracoLoader),e.manager.addHandler(this._dracoRegex,this.dracoLoader)),this.ktxLoader&&t.setKTX2Loader(this.ktxLoader),this.meshoptDecoder&&t.setMeshoptDecoder(this.meshoptDecoder),this.rtc&&t.register((()=>new Up)),this.metadata&&(t.register((()=>new Ep)),t.register((()=>new Lp))),this.plugins.forEach((e=>t.register(e))),e.manager.addHandler(this._gltfRegex,t),this.tiles=e,this._loader=t}dispose(){this.tiles.manager.removeHandler(this._gltfRegex),this.tiles.manager.removeHandler(this._dracoRegex),this.autoDispose&&(this.ktxLoader.dispose(),this.dracoLoader.dispose())}},zp=class{set delay(e){this.deferCallbacks.delay=e}get delay(){return this.deferCallbacks.delay}set bytesTarget(e){this.lruCache.minBytesSize=e}get bytesTarget(){return this.lruCache.minBytesSize}get estimatedGpuBytes(){return this.lruCache.cachedBytes}constructor(e={}){let{delay:t=0,bytesTarget:n=0}=e;this.name="UNLOAD_TILES_PLUGIN",this.tiles=null,this.lruCache=new Bl,this.deferCallbacks=new Bp,this.delay=t,this.bytesTarget=n}init(e){this.tiles=e;let{lruCache:t,deferCallbacks:n}=this,r=t=>{let n=t.engineData.scene;e.visibleTiles.has(t)||e.invokeOnePlugin((e=>e.unloadTileFromGPU&&e.unloadTileFromGPU(n,t)))};this._onUpdateBefore=()=>{t.unloadPriorityCallback=e.lruCache.unloadPriorityCallback,t.minSize=1/0,t.maxSize=1/0,t.maxBytesSize=1/0,t.unloadPercent=1,t.autoMarkUnused=!1},this._onVisibilityChangeCallback=({tile:i,scene:s,visible:a})=>{a?(t.add(i,r),t.setMemoryUsage(i,e.calculateBytesUsed(i,s)||1),e.markTileUsed(i),n.cancel(i)):n.run(i)},this._onDisposeModel=({tile:e})=>{t.remove(e),n.cancel(e)},n.callback=e=>{t.markUnused(e),t.scheduleUnload()},e.forEachLoadedModel(((t,n)=>{let r=e.visibleTiles.has(n);this._onVisibilityChangeCallback({tile:n,visible:r})})),e.addEventListener("tile-visibility-change",this._onVisibilityChangeCallback),e.addEventListener("update-before",this._onUpdateBefore),e.addEventListener("dispose-model",this._onDisposeModel)}unloadTileFromGPU(e,t){e&&e.traverse((e=>{if(e.material){let t=e.material;t.dispose();for(let e in t){let n=t[e];n&&n.isTexture&&n.dispose()}}e.geometry&&e.geometry.dispose()}))}dispose(){let{lruCache:e,tiles:t,deferCallbacks:n}=this;t.removeEventListener("tile-visibility-change",this._onVisibilityChangeCallback),t.removeEventListener("update-before",this._onUpdateBefore),t.removeEventListener("dispose-model",this._onDisposeModel),n.cancelAll(),e.minBytesSize=0,e.minSize=0,e.maxSize=0,e.markAllUnused(),e.scheduleUnload()}},Bp=class{constructor(e=()=>{}){this.map=new Map,this.callback=e,this.delay=0}run(e){let{map:t,delay:n}=this;if(t.has(e))throw Error("DeferCallbackManager: Callback already initialized.");0===n?this.callback(e):t.set(e,setTimeout((()=>{this.callback(e),t.delete(e)}),n))}cancel(e){let{map:t}=this;t.has(e)&&(clearTimeout(t.get(e)),t.delete(e))}cancelAll(){this.map.forEach(((e,t)=>{this.cancel(t)}))}},{clamp:Vp}=r.MathUtils,Op=class{constructor(){this.duration=250,this.fadeCount=0,this._lastTick=-1,this._fadeState=new Map,this.onFadeComplete=null,this.onFadeStart=null,this.onFadeSetComplete=null,this.onFadeSetStart=null}deleteObject(e){e&&this.completeFade(e)}guaranteeState(e){let t=this._fadeState;return!t.has(e)&&(t.set(e,{fadeInTarget:0,fadeOutTarget:0,fadeIn:0,fadeOut:0}),!0)}completeFade(e){let t=this._fadeState;if(!t.has(e))return;let n=0===t.get(e).fadeOutTarget;t.delete(e),this.fadeCount--,this.onFadeComplete&&this.onFadeComplete(e,n),0===this.fadeCount&&this.onFadeSetComplete&&this.onFadeSetComplete()}completeAllFades(){this._fadeState.forEach(((e,t)=>{this.completeFade(t)}))}forEachObject(e){this._fadeState.forEach(((t,n)=>{e(n,t)}))}fadeIn(e){let t=this.guaranteeState(e),n=this._fadeState.get(e);n.fadeInTarget=1,n.fadeOutTarget=0,n.fadeOut=0,t&&(this.fadeCount++,1===this.fadeCount&&this.onFadeSetStart&&this.onFadeSetStart(),this.onFadeStart&&this.onFadeStart(e))}fadeOut(e){let t=this.guaranteeState(e),n=this._fadeState.get(e);n.fadeOutTarget=1,t&&(n.fadeInTarget=1,n.fadeIn=1,this.fadeCount++,1===this.fadeCount&&this.onFadeSetStart&&this.onFadeSetStart(),this.onFadeStart&&this.onFadeStart(e))}isFading(e){return this._fadeState.has(e)}isFadingOut(e){let t=this._fadeState.get(e);return t&&1===t.fadeOutTarget}update(){let e=window.performance.now();-1===this._lastTick&&(this._lastTick=e);let t=Vp((e-this._lastTick)/this.duration,0,1);this._lastTick=e,this._fadeState.forEach(((e,n)=>{let{fadeOutTarget:r,fadeInTarget:i}=e,{fadeOut:s,fadeIn:a}=e,o=Math.sign(i-a);a=Vp(a+o*t,0,1);let l=Math.sign(r-s);s=Vp(s+l*t,0,1),e.fadeIn=a,e.fadeOut=s,((1===s||0===s)&&(1===a||0===a)||s>=a)&&this.completeFade(n)}))}},Np=Symbol("FADE_PARAMS");function $p(e,t){if(e[Np])return e[Np];let n={fadeIn:{value:0},fadeOut:{value:0},fadeTexture:{value:null}};return e[Np]=n,e.defines={...e.defines||{},FEATURE_FADE:0},e.onBeforeCompile=e=>{t&&t(e),e.uniforms={...e.uniforms,...n},e.vertexShader=e.vertexShader.replace(/void\s+main\(\)\s+{/,(e=>`\n\t\t\t\t\t#ifdef USE_BATCHING_FRAG\n\n\t\t\t\t\tvarying float vBatchId;\n\n\t\t\t\t\t#endif\n\n\t\t\t\t\t${e}\n\n\t\t\t\t\t\t#ifdef USE_BATCHING_FRAG\n\n\t\t\t\t\t\t// add 0.5 to the value to avoid floating error that may cause flickering\n\t\t\t\t\t\tvBatchId = getIndirectIndex( gl_DrawID ) + 0.5;\n\n\t\t\t\t\t\t#endif\n\t\t\t\t`)),e.fragmentShader=e.fragmentShader.replace(/void main\(/,(e=>`\n\t\t\t\t#if FEATURE_FADE\n\n\t\t\t\t// adapted from https://www.shadertoy.com/view/Mlt3z8\n\t\t\t\tfloat bayerDither2x2( vec2 v ) {\n\n\t\t\t\t\treturn mod( 3.0 * v.y + 2.0 * v.x, 4.0 );\n\n\t\t\t\t}\n\n\t\t\t\tfloat bayerDither4x4( vec2 v ) {\n\n\t\t\t\t\tvec2 P1 = mod( v, 2.0 );\n\t\t\t\t\tvec2 P2 = floor( 0.5 * mod( v, 4.0 ) );\n\t\t\t\t\treturn 4.0 * bayerDither2x2( P1 ) + bayerDither2x2( P2 );\n\n\t\t\t\t}\n\n\t\t\t\t// the USE_BATCHING define is not available in fragment shaders\n\t\t\t\t#ifdef USE_BATCHING_FRAG\n\n\t\t\t\t// functions for reading the fade state of a given batch id\n\t\t\t\tuniform sampler2D fadeTexture;\n\t\t\t\tvarying float vBatchId;\n\t\t\t\tvec2 getFadeValues( const in float i ) {\n\n\t\t\t\t\tint size = textureSize( fadeTexture, 0 ).x;\n\t\t\t\t\tint j = int( i );\n\t\t\t\t\tint x = j % size;\n\t\t\t\t\tint y = j / size;\n\t\t\t\t\treturn texelFetch( fadeTexture, ivec2( x, y ), 0 ).rg;\n\n\t\t\t\t}\n\n\t\t\t\t#else\n\n\t\t\t\tuniform float fadeIn;\n\t\t\t\tuniform float fadeOut;\n\n\t\t\t\t#endif\n\n\t\t\t\t#endif\n\n\t\t\t\t${e}\n\t\t\t`)).replace(/#include <dithering_fragment>/,(e=>`\n\n\t\t\t\t${e}\n\n\t\t\t\t#if FEATURE_FADE\n\n\t\t\t\t#ifdef USE_BATCHING_FRAG\n\n\t\t\t\tvec2 fadeValues = getFadeValues( vBatchId );\n\t\t\t\tfloat fadeIn = fadeValues.r;\n\t\t\t\tfloat fadeOut = fadeValues.g;\n\n\t\t\t\t#endif\n\n\t\t\t\tfloat bayerValue = bayerDither4x4( floor( mod( gl_FragCoord.xy, 4.0 ) ) );\n\t\t\t\tfloat bayerBins = 16.0;\n\t\t\t\tfloat dither = ( 0.5 + bayerValue ) / bayerBins;\n\t\t\t\tif ( dither >= fadeIn ) {\n\n\t\t\t\t\tdiscard;\n\n\t\t\t\t}\n\n\t\t\t\tif ( dither < fadeOut ) {\n\n\t\t\t\t\tdiscard;\n\n\t\t\t\t}\n\n\t\t\t\t#endif\n\n\t\t\t`))},n}var Gp=class{constructor(){this._fadeParams=new WeakMap,this.fading=0}setFade(e,t,n){if(!e)return;let r=this._fadeParams;e.traverse((e=>{let i=e.material;if(i&&r.has(i)){let e=r.get(i);e.fadeIn.value=t,e.fadeOut.value=n;let s=Number(!(0===t||1===t)||!(0===n||1===n));i.defines.FEATURE_FADE!==s&&(this.fading+=1===s?1:-1,i.defines.FEATURE_FADE=s,i.needsUpdate=!0)}}))}prepareScene(e){e.traverse((e=>{e.material&&this.prepareMaterial(e.material)}))}deleteScene(e){if(!e)return;this.setFade(e,1,0);let t=this._fadeParams;e.traverse((e=>{let n=e.material;n&&t.delete(n)}))}prepareMaterial(e){let t=this._fadeParams;t.has(e)||t.set(e,$p(e,e.onBeforeCompile))}},qp=class{constructor(e,t=new r.MeshBasicMaterial){this.other=e,this.material=t,this.visible=!0,this.parent=null,this._instanceInfo=[],this._visibilityChanged=!0;let n=new Proxy(this,{get(t,r){if(r in t)return t[r];{let i=e[r];return i instanceof Function?(...e)=>(t.syncInstances(),i.call(n,...e)):e[r]}},set:(t,n,r)=>(n in t?t[n]=r:e[n]=r,!0),deleteProperty:(t,n)=>n in t?delete t[n]:delete e[n]});return n}syncInstances(){let e=this._instanceInfo,t=this.other._instanceInfo;for(;t.length>e.length;){let n=e.length;e.push(new Proxy({visible:!1},{get:(e,r)=>r in e?e[r]:t[n][r],set:(e,r,i)=>(r in e?e[r]=i:t[n][r]=i,!0)}))}}},Hp=class extends qp{constructor(...e){super(...e);let t=this.material,n=$p(t,t.onBeforeCompile);t.defines.FEATURE_FADE=1,t.defines.USE_BATCHING_FRAG=1,t.needsUpdate=!0,this.fadeTexture=null,this._fadeParams=n}setFadeAt(e,t,n){this._initFadeTexture(),this.fadeTexture.setValueAt(e,255*t,255*n)}_initFadeTexture(){let e=Math.sqrt(this._maxInstanceCount);e=Math.ceil(e);let t=e*e*2,n=this.fadeTexture;if(!n||n.image.data.length!==t){let i=new jp(new Uint8Array(t),e,e,r.RGFormat,r.UnsignedByteType);if(n){n.dispose();let e=n.image.data,t=this.fadeTexture.image.data,r=Math.min(e.length,t.length);t.set(new e.constructor(e.buffer,0,r))}this.fadeTexture=i,this._fadeParams.fadeTexture.value=i,i.needsUpdate=!0}}dispose(){this.fadeTexture&&this.fadeTexture.dispose()}},jp=class extends r.DataTexture{setValueAt(e,...t){let{data:n,width:r,height:i}=this.image,s=Math.floor(n.length/(r*i)),a=!1;for(let o=0;o<s;o++){let r=e*s+o,i=n[r],l=t[o]||0;i!==l&&(n[r]=l,a=!0)}a&&(this.needsUpdate=!0)}},Wp=Symbol("HAS_POPPED_IN");var Xp=new r.Vector3,Yp=new r.Vector3,Kp=new r.Quaternion,Qp=new r.Quaternion,Zp=new r.Vector3;function Jp(){let e=this._fadeManager,t=this._fadeMaterialManager,n=this._fadingBefore,r=this._prevCameraTransforms,{tiles:i,maximumFadeOutTiles:s,batchedMesh:a}=this,{cameras:o}=i;e.update();let l=e.fadeCount;if(0!==n&&0!==l&&(i.dispatchEvent({type:"fade-change"}),i.dispatchEvent({type:"needs-render"})),s<this._fadingOutCount){let t=!0;o.forEach((e=>{if(!r.has(e))return;let n=e.matrixWorld,i=r.get(e);n.decompose(Yp,Qp,Zp),i.decompose(Xp,Kp,Zp);let s=Qp.angleTo(Kp),a=Yp.distanceTo(Xp);t&&(t=s>.25||a>.1)})),t&&e.completeAllFades()}if(o.forEach((e=>{r.get(e).copy(e.matrixWorld)})),e.forEachObject(((e,{fadeIn:n,fadeOut:r})=>{let s=e.engineData.scene;i.markTileUsed(e),s&&t.setFade(s,n,r),this.forEachBatchIds(e,((e,t,i)=>{t.setFadeAt(e,n,r),t.setVisibleAt(e,!0),i.batchedMesh.setVisibleAt(e,!1)}))})),a){let e=i.getPluginByName("BATCHED_TILES_PLUGIN").batchedMesh.material;a.material.map=e.map}}var em=class{get fadeDuration(){return this._fadeManager.duration}set fadeDuration(e){this._fadeManager.duration=Number(e)}get fadingTiles(){return this._fadeManager.fadeCount}constructor(e){e={maximumFadeOutTiles:50,fadeRootTiles:!1,fadeDuration:250,...e},this.name="FADE_TILES_PLUGIN",this.priority=-2,this.tiles=null,this.batchedMesh=null,this._quickFadeTiles=new Set,this._fadeManager=new Op,this._fadeMaterialManager=new Gp,this._prevCameraTransforms=null,this._fadingOutCount=0,this.maximumFadeOutTiles=e.maximumFadeOutTiles,this.fadeRootTiles=e.fadeRootTiles,this.fadeDuration=e.fadeDuration}init(e){this._onLoadModel=({scene:e})=>{this._fadeMaterialManager.prepareScene(e)},this._onDisposeModel=({tile:e,scene:t})=>{this.tiles.visibleTiles.has(e)&&this._quickFadeTiles.add(e.parent),this._fadeManager.deleteObject(e),this._fadeMaterialManager.deleteScene(t)},this._onAddCamera=({camera:e})=>{this._prevCameraTransforms.set(e,new r.Matrix4)},this._onDeleteCamera=({camera:e})=>{this._prevCameraTransforms.delete(e)},this._onTileVisibilityChange=({tile:e})=>{this.forEachBatchIds(e,((e,t,n)=>{t.setFadeAt(e,0,0),t.setVisibleAt(e,!1),n.batchedMesh.setVisibleAt(e,!1)}))},this._onUpdateBefore=()=>{this._fadingBefore=this._fadeManager.fadeCount},this._onUpdateAfter=()=>{Jp.call(this)},e.addEventListener("load-model",this._onLoadModel),e.addEventListener("dispose-model",this._onDisposeModel),e.addEventListener("add-camera",this._onAddCamera),e.addEventListener("delete-camera",this._onDeleteCamera),e.addEventListener("update-before",this._onUpdateBefore),e.addEventListener("update-after",this._onUpdateAfter),e.addEventListener("tile-visibility-change",this._onTileVisibilityChange);let t=this._fadeManager;t.onFadeSetStart=()=>{e.dispatchEvent({type:"fade-start"}),e.dispatchEvent({type:"needs-render"})},t.onFadeSetComplete=()=>{e.dispatchEvent({type:"fade-end"}),e.dispatchEvent({type:"needs-render"})},t.onFadeComplete=(t,n)=>{this._fadeMaterialManager.setFade(t.engineData.scene,0,0),this.forEachBatchIds(t,((e,t,r)=>{t.setFadeAt(e,0,0),t.setVisibleAt(e,!1),r.batchedMesh.setVisibleAt(e,n)})),n||(e.invokeOnePlugin((e=>e!==this&&e.setTileVisible&&e.setTileVisible(t,!1))),this._fadingOutCount--)};let n=new Map;e.cameras.forEach((e=>{n.set(e,new r.Matrix4)})),e.forEachLoadedModel(((e,t)=>{this._onLoadModel({scene:e})})),this.tiles=e,this._fadeManager=t,this._prevCameraTransforms=n}initBatchedMesh(){var e;let t=null==(e=this.tiles.getPluginByName("BATCHED_TILES_PLUGIN"))?void 0:e.batchedMesh;if(t){if(null===this.batchedMesh){this._onBatchedMeshDispose=()=>{this.batchedMesh.dispose(),this.batchedMesh.removeFromParent(),this.batchedMesh=null,t.removeEventListener("dispose",this._onBatchedMeshDispose)};let e=t.material.clone();e.onBeforeCompile=t.material.onBeforeCompile,this.batchedMesh=new Hp(t,e),this.tiles.group.add(this.batchedMesh)}}else null!==this.batchedMesh&&(this._onBatchedMeshDispose(),this._onBatchedMeshDispose=null)}setTileVisible(e,t){let n=this._fadeManager,r=n.isFading(e);if(!function(e){let t=e;for(;t;){if(t.traversal.wasSetActive)return t.traversal.wasInFrustum;t=t.parent}return!1}(e))return r&&n.completeFade(e),!1;if(n.isFadingOut(e)&&this._fadingOutCount--,t?1===e.internal.depthFromRenderedParent?((e[Wp]||this.fadeRootTiles)&&this._fadeManager.fadeIn(e),e[Wp]=!0):this._fadeManager.fadeIn(e):(this._fadingOutCount++,n.fadeOut(e)),this._quickFadeTiles.has(e)&&(this._fadeManager.completeFade(e),this._quickFadeTiles.delete(e)),r)return!0;let i=this._fadeManager.isFading(e);return!(t||!i)}dispose(){let e=this.tiles;this._fadeManager.completeAllFades(),null!==this.batchedMesh&&this._onBatchedMeshDispose(),e.removeEventListener("load-model",this._onLoadModel),e.removeEventListener("dispose-model",this._onDisposeModel),e.removeEventListener("add-camera",this._onAddCamera),e.removeEventListener("delete-camera",this._onDeleteCamera),e.removeEventListener("update-before",this._onUpdateBefore),e.removeEventListener("update-after",this._onUpdateAfter),e.removeEventListener("tile-visibility-change",this._onTileVisibilityChange),e.forEachLoadedModel(((e,t)=>{this._fadeManager.deleteObject(t)}))}forEachBatchIds(e,t){if(this.initBatchedMesh(),this.batchedMesh){let n=this.tiles.getPluginByName("BATCHED_TILES_PLUGIN"),r=n.getTileBatchIds(e);r&&r.forEach((e=>{t(e,this.batchedMesh,n)}))}}};new o(new r.MeshBasicMaterial),new r.DataTexture(new Uint8Array([255,255,255,255]),1,1).needsUpdate=!0;const tm=`https://unpkg.com/three@0.${r.REVISION}.x`,nm="#include <opaque_fragment>",rm=`\n float grayscale = dot(outgoingLight, vec3(0.299, 0.587, 0.114));\n outgoingLight = vec3(grayscale);\n ${nm}\n`;function im(e){const t=e.onBeforeCompile;e.onBeforeCompile=n=>{t.call(e,n),n.fragmentShader=n.fragmentShader.replace(nm,rm)},e.needsUpdate=!0}class sm extends Do{constructor(e,t,n,r={}){super(),this.scene=e,this.camera=t,this.renderer=n,this.tiles=null,this.apiToken=r.apiToken,this.googleMapsToken=r.googleMapsToken,this.initTiles()}initTiles(){this.tiles&&(this.scene.remove(this.tiles.group),this.tiles.dispose(),this.tiles=null),this.dracoLoader=new Je,this.dracoLoader.setDecoderPath(`${tm}/examples/jsm/libs/draco/gltf/`),this.tiles=new dh,this.tiles.errorTarget=40,this.tiles.registerPlugin(new yh({apiToken:this.googleMapsToken,autoRefreshToken:!0})),this.tiles.registerPlugin(new Gd),this.tiles.registerPlugin(new Od),this.tiles.registerPlugin(new zp),this.tiles.registerPlugin(new em),this.tiles.registerPlugin(new Fp({dracoLoader:this.dracoLoader})),this.scene.add(this.tiles.group),this.tiles.setResolutionFromRenderer(this.camera,this.renderer),this.tiles.setCamera(this.camera),this.tiles.addEventListener("load-model",(({scene:e})=>{e.traverse((e=>{Array.isArray(e.material)?e.material.forEach(im):e.material&&im(e.material),e.layers.set(0)}))}))}update(){this.tiles&&(this.tiles.setResolutionFromRenderer(this.camera,this.renderer),this.tiles.setCamera(this.camera),this.tiles.errorTarget=20,this.tiles.update())}dispose(){var e,t;this.tiles&&(this.scene.remove(this.tiles.group),this.tiles.dispose(),this.tiles=null),null==(t=null==(e=this.dracoLoader)?void 0:e.dispose)||t.call(e),this.listeners={}}}var am=Object.freeze({Linear:Object.freeze({None:function(e){return e},In:function(e){return e},Out:function(e){return e},InOut:function(e){return e}}),Quadratic:Object.freeze({In:function(e){return e*e},Out:function(e){return e*(2-e)},InOut:function(e){return(e*=2)<1?.5*e*e:-.5*(--e*(e-2)-1)}}),Cubic:Object.freeze({In:function(e){return e*e*e},Out:function(e){return--e*e*e+1},InOut:function(e){return(e*=2)<1?.5*e*e*e:.5*((e-=2)*e*e+2)}}),Quartic:Object.freeze({In:function(e){return e*e*e*e},Out:function(e){return 1- --e*e*e*e},InOut:function(e){return(e*=2)<1?.5*e*e*e*e:-.5*((e-=2)*e*e*e-2)}}),Quintic:Object.freeze({In:function(e){return e*e*e*e*e},Out:function(e){return--e*e*e*e*e+1},InOut:function(e){return(e*=2)<1?.5*e*e*e*e*e:.5*((e-=2)*e*e*e*e+2)}}),Sinusoidal:Object.freeze({In:function(e){return 1-Math.sin((1-e)*Math.PI/2)},Out:function(e){return Math.sin(e*Math.PI/2)},InOut:function(e){return.5*(1-Math.sin(Math.PI*(.5-e)))}}),Exponential:Object.freeze({In:function(e){return 0===e?0:Math.pow(1024,e-1)},Out:function(e){return 1===e?1:1-Math.pow(2,-10*e)},InOut:function(e){return 0===e?0:1===e?1:(e*=2)<1?.5*Math.pow(1024,e-1):.5*(2-Math.pow(2,-10*(e-1)))}}),Circular:Object.freeze({In:function(e){return 1-Math.sqrt(1-e*e)},Out:function(e){return Math.sqrt(1- --e*e)},InOut:function(e){return(e*=2)<1?-.5*(Math.sqrt(1-e*e)-1):.5*(Math.sqrt(1-(e-=2)*e)+1)}}),Elastic:Object.freeze({In:function(e){return 0===e?0:1===e?1:-Math.pow(2,10*(e-1))*Math.sin(5*(e-1.1)*Math.PI)},Out:function(e){return 0===e?0:1===e?1:Math.pow(2,-10*e)*Math.sin(5*(e-.1)*Math.PI)+1},InOut:function(e){return 0===e?0:1===e?1:(e*=2)<1?-.5*Math.pow(2,10*(e-1))*Math.sin(5*(e-1.1)*Math.PI):.5*Math.pow(2,-10*(e-1))*Math.sin(5*(e-1.1)*Math.PI)+1}}),Back:Object.freeze({In:function(e){var t=1.70158;return 1===e?1:e*e*((t+1)*e-t)},Out:function(e){var t=1.70158;return 0===e?0:--e*e*((t+1)*e+t)+1},InOut:function(e){var t=2.5949095;return(e*=2)<1?e*e*((t+1)*e-t)*.5:.5*((e-=2)*e*((t+1)*e+t)+2)}}),Bounce:Object.freeze({In:function(e){return 1-am.Bounce.Out(1-e)},Out:function(e){return e<1/2.75?7.5625*e*e:e<2/2.75?7.5625*(e-=1.5/2.75)*e+.75:e<2.5/2.75?7.5625*(e-=2.25/2.75)*e+.9375:7.5625*(e-=2.625/2.75)*e+.984375},InOut:function(e){return e<.5?.5*am.Bounce.In(2*e):.5*am.Bounce.Out(2*e-1)+.5}}),generatePow:function(e){return void 0===e&&(e=4),e=(e=e<Number.EPSILON?Number.EPSILON:e)>1e4?1e4:e,{In:function(t){return Math.pow(t,e)},Out:function(t){return 1-Math.pow(1-t,e)},InOut:function(t){return t<.5?Math.pow(2*t,e)/2:(1-Math.pow(2-2*t,e))/2+.5}}}}),om=function(){return performance.now()},lm=function(){function e(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this._tweens={},this._tweensAddedDuringUpdate={},this.add.apply(this,e)}return e.prototype.getAll=function(){var e=this;return Object.keys(this._tweens).map((function(t){return e._tweens[t]}))},e.prototype.removeAll=function(){this._tweens={}},e.prototype.add=function(){for(var e,t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];for(var r=0,i=t;r<i.length;r++){var s=i[r];null===(e=s._group)||void 0===e||e.remove(s),s._group=this,this._tweens[s.getId()]=s,this._tweensAddedDuringUpdate[s.getId()]=s}},e.prototype.remove=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];for(var n=0,r=e;n<r.length;n++){var i=r[n];i._group=void 0,delete this._tweens[i.getId()],delete this._tweensAddedDuringUpdate[i.getId()]}},e.prototype.allStopped=function(){return this.getAll().every((function(e){return!e.isPlaying()}))},e.prototype.update=function(e,t){void 0===e&&(e=om()),void 0===t&&(t=!0);var n=Object.keys(this._tweens);if(0!==n.length)for(;n.length>0;){this._tweensAddedDuringUpdate={};for(var r=0;r<n.length;r++){var i=this._tweens[n[r]],s=!t;i&&!1===i.update(e,s)&&!t&&this.remove(i)}n=Object.keys(this._tweensAddedDuringUpdate)}},e}(),cm={Linear:function(e,t){var n=e.length-1,r=n*t,i=Math.floor(r),s=cm.Utils.Linear;return t<0?s(e[0],e[1],r):t>1?s(e[n],e[n-1],n-r):s(e[i],e[i+1>n?n:i+1],r-i)},Utils:{Linear:function(e,t,n){return(t-e)*n+e}}},um=function(){function e(){}return e.nextId=function(){return e._nextId++},e._nextId=0,e}(),hm=new lm,dm=function(){function e(e,t){this._isPaused=!1,this._pauseStart=0,this._valuesStart={},this._valuesEnd={},this._valuesStartRepeat={},this._duration=1e3,this._isDynamic=!1,this._initialRepeat=0,this._repeat=0,this._yoyo=!1,this._isPlaying=!1,this._reversed=!1,this._delayTime=0,this._startTime=0,this._easingFunction=am.Linear.None,this._interpolationFunction=cm.Linear,this._chainedTweens=[],this._onStartCallbackFired=!1,this._onEveryStartCallbackFired=!1,this._id=um.nextId(),this._isChainStopped=!1,this._propertiesAreSetUp=!1,this._goToEnd=!1,this._object=e,"object"==typeof t?(this._group=t,t.add(this)):!0===t&&(this._group=hm,hm.add(this))}return e.prototype.getId=function(){return this._id},e.prototype.isPlaying=function(){return this._isPlaying},e.prototype.isPaused=function(){return this._isPaused},e.prototype.getDuration=function(){return this._duration},e.prototype.to=function(e,t){if(void 0===t&&(t=1e3),this._isPlaying)throw new Error("Can not call Tween.to() while Tween is already started or paused. Stop the Tween first.");return this._valuesEnd=e,this._propertiesAreSetUp=!1,this._duration=t<0?0:t,this},e.prototype.duration=function(e){return void 0===e&&(e=1e3),this._duration=e<0?0:e,this},e.prototype.dynamic=function(e){return void 0===e&&(e=!1),this._isDynamic=e,this},e.prototype.start=function(e,t){if(void 0===e&&(e=om()),void 0===t&&(t=!1),this._isPlaying)return this;if(this._repeat=this._initialRepeat,this._reversed)for(var n in this._reversed=!1,this._valuesStartRepeat)this._swapEndStartRepeatValues(n),this._valuesStart[n]=this._valuesStartRepeat[n];if(this._isPlaying=!0,this._isPaused=!1,this._onStartCallbackFired=!1,this._onEveryStartCallbackFired=!1,this._isChainStopped=!1,this._startTime=e,this._startTime+=this._delayTime,!this._propertiesAreSetUp||t){if(this._propertiesAreSetUp=!0,!this._isDynamic){var r={};for(var i in this._valuesEnd)r[i]=this._valuesEnd[i];this._valuesEnd=r}this._setupProperties(this._object,this._valuesStart,this._valuesEnd,this._valuesStartRepeat,t)}return this},e.prototype.startFromCurrentValues=function(e){return this.start(e,!0)},e.prototype._setupProperties=function(e,t,n,r,i){for(var s in n){var a=e[s],o=Array.isArray(a),l=o?"array":typeof a,c=!o&&Array.isArray(n[s]);if("undefined"!==l&&"function"!==l){if(c){if(0===(g=n[s]).length)continue;for(var u=[a],h=0,d=g.length;h<d;h+=1){var p=this._handleRelativeValue(a,g[h]);if(isNaN(p)){c=!1;break}u.push(p)}c&&(n[s]=u)}if("object"!==l&&!o||!a||c)(void 0===t[s]||i)&&(t[s]=a),o||(t[s]*=1),r[s]=c?n[s].slice().reverse():t[s]||0;else{t[s]=o?[]:{};var m=a;for(var f in m)t[s][f]=m[f];r[s]=o?[]:{};var g=n[s];if(!this._isDynamic){var x={};for(var f in g)x[f]=g[f];n[s]=g=x}this._setupProperties(m,t[s],g,r[s],i)}}}},e.prototype.stop=function(){return this._isChainStopped||(this._isChainStopped=!0,this.stopChainedTweens()),this._isPlaying?(this._isPlaying=!1,this._isPaused=!1,this._onStopCallback&&this._onStopCallback(this._object),this):this},e.prototype.end=function(){return this._goToEnd=!0,this.update(this._startTime+this._duration),this},e.prototype.pause=function(e){return void 0===e&&(e=om()),this._isPaused||!this._isPlaying||(this._isPaused=!0,this._pauseStart=e),this},e.prototype.resume=function(e){return void 0===e&&(e=om()),this._isPaused&&this._isPlaying?(this._isPaused=!1,this._startTime+=e-this._pauseStart,this._pauseStart=0,this):this},e.prototype.stopChainedTweens=function(){for(var e=0,t=this._chainedTweens.length;e<t;e++)this._chainedTweens[e].stop();return this},e.prototype.group=function(e){return e?(e.add(this),this):this},e.prototype.remove=function(){var e;return null===(e=this._group)||void 0===e||e.remove(this),this},e.prototype.delay=function(e){return void 0===e&&(e=0),this._delayTime=e,this},e.prototype.repeat=function(e){return void 0===e&&(e=0),this._initialRepeat=e,this._repeat=e,this},e.prototype.repeatDelay=function(e){return this._repeatDelayTime=e,this},e.prototype.yoyo=function(e){return void 0===e&&(e=!1),this._yoyo=e,this},e.prototype.easing=function(e){return void 0===e&&(e=am.Linear.None),this._easingFunction=e,this},e.prototype.interpolation=function(e){return void 0===e&&(e=cm.Linear),this._interpolationFunction=e,this},e.prototype.chain=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return this._chainedTweens=e,this},e.prototype.onStart=function(e){return this._onStartCallback=e,this},e.prototype.onEveryStart=function(e){return this._onEveryStartCallback=e,this},e.prototype.onUpdate=function(e){return this._onUpdateCallback=e,this},e.prototype.onRepeat=function(e){return this._onRepeatCallback=e,this},e.prototype.onComplete=function(e){return this._onCompleteCallback=e,this},e.prototype.onStop=function(e){return this._onStopCallback=e,this},e.prototype.update=function(t,n){var r,i,s=this;if(void 0===t&&(t=om()),void 0===n&&(n=e.autoStartOnUpdate),this._isPaused)return!0;if(!this._goToEnd&&!this._isPlaying){if(!n)return!1;this.start(t,!0)}if(this._goToEnd=!1,t<this._startTime)return!0;!1===this._onStartCallbackFired&&(this._onStartCallback&&this._onStartCallback(this._object),this._onStartCallbackFired=!0),!1===this._onEveryStartCallbackFired&&(this._onEveryStartCallback&&this._onEveryStartCallback(this._object),this._onEveryStartCallbackFired=!0);var a=t-this._startTime,o=this._duration+(null!==(r=this._repeatDelayTime)&&void 0!==r?r:this._delayTime),l=this._duration+this._repeat*o,c=function(){if(0===s._duration)return 1;if(a>l)return 1;var e=Math.trunc(a/o),t=a-e*o,n=Math.min(t/s._duration,1);return 0===n&&a===s._duration?1:n}(),u=this._easingFunction(c);if(this._updateProperties(this._object,this._valuesStart,this._valuesEnd,u),this._onUpdateCallback&&this._onUpdateCallback(this._object,c),0===this._duration||a>=this._duration){if(this._repeat>0){var h=Math.min(Math.trunc((a-this._duration)/o)+1,this._repeat);for(i in isFinite(this._repeat)&&(this._repeat-=h),this._valuesStartRepeat)this._yoyo||"string"!=typeof this._valuesEnd[i]||(this._valuesStartRepeat[i]=this._valuesStartRepeat[i]+parseFloat(this._valuesEnd[i])),this._yoyo&&this._swapEndStartRepeatValues(i),this._valuesStart[i]=this._valuesStartRepeat[i];return this._yoyo&&(this._reversed=!this._reversed),this._startTime+=o*h,this._onRepeatCallback&&this._onRepeatCallback(this._object),this._onEveryStartCallbackFired=!1,!0}this._onCompleteCallback&&this._onCompleteCallback(this._object);for(var d=0,p=this._chainedTweens.length;d<p;d++)this._chainedTweens[d].start(this._startTime+this._duration,!1);return this._isPlaying=!1,!1}return!0},e.prototype._updateProperties=function(e,t,n,r){for(var i in n)if(void 0!==t[i]){var s=t[i]||0,a=n[i],o=Array.isArray(e[i]),l=Array.isArray(a);!o&&l?e[i]=this._interpolationFunction(a,r):"object"==typeof a&&a?this._updateProperties(e[i],s,a,r):"number"==typeof(a=this._handleRelativeValue(s,a))&&(e[i]=s+(a-s)*r)}},e.prototype._handleRelativeValue=function(e,t){return"string"!=typeof t?t:"+"===t.charAt(0)||"-"===t.charAt(0)?e+parseFloat(t):parseFloat(t)},e.prototype._swapEndStartRepeatValues=function(e){var t=this._valuesStartRepeat[e],n=this._valuesEnd[e];this._valuesStartRepeat[e]="string"==typeof n?this._valuesStartRepeat[e]+parseFloat(n):this._valuesEnd[e],this._valuesEnd[e]=t},e.autoStartOnUpdate=!1,e}();um.nextId;var pm=hm;pm.getAll.bind(pm),pm.removeAll.bind(pm),pm.add.bind(pm),pm.remove.bind(pm),pm.update.bind(pm);const mm={CESIUM:void 0,GOOGLEMAPS:void 0},fm=2e3;({Easing:am}).Easing.Quartic.InOut;function gm(e,t={}){return new Promise(((n,i)=>{const s=new vn;s.setDataType(t.floatType||r.HalfFloatType),s.load(e,(e=>{n(e)}),(e=>{}),(e=>{i(e)}))}))}var xm,ym,vm={exports:{}};function bm(e,t,n){const r=6378137,i=.081819190842622,s=r*r,a=i*i,o=Math.sqrt(s*(1-a)),l=o*o,c=Math.sqrt((s-l)/l),u=Math.sqrt(e*e+t*t),h=Math.atan2(r*n,o*u),d=Math.atan2(t,e),p=Math.atan2(n+c*c*o*Math.sin(h)**3,u-a*r*Math.cos(h)**3),m=r/Math.sqrt(1-a*Math.sin(p)*Math.sin(p)),f=u/Math.cos(p)-m;return{lon:d*(180/Math.PI),lat:p*(180/Math.PI),alt:f}}function wm(e,t,n){const r=.081819190842622,i=r*r,s=t*(Math.PI/180),a=e*(Math.PI/180),o=6378137/Math.sqrt(1-i*Math.sin(s)**2);return[(o+n)*Math.cos(s)*Math.cos(a),(o+n)*Math.cos(s)*Math.sin(a),((1-i)*o+n)*Math.sin(s)]}function Tm(e,t){const n=r.MathUtils.degToRad(e),i=r.MathUtils.degToRad(t);return new r.Vector3(Math.cos(i)*Math.cos(n),Math.cos(i)*Math.sin(n),Math.sin(i)).normalize()}function Sm(e,t,n,i,s){const a=Tm(e,t);n+=90;const o=new r.Vector3(0,0,1),l=o.clone().sub(a.clone().multiplyScalar(o.dot(a))).normalize(),c=(new r.Vector3).crossVectors(l,a).normalize(),u=(new r.Matrix4).makeBasis(c,l,a),h=new r.Euler(r.MathUtils.degToRad(n),r.MathUtils.degToRad(s),r.MathUtils.degToRad(i),"ZYX"),d=(new r.Quaternion).setFromEuler(h);return(new r.Quaternion).setFromRotationMatrix(u).multiply(d)}function _m(e,t){const n=(new r.Vector3).subVectors(t,e).normalize(),i=e.clone().normalize();Math.abs(n.dot(i))>.99&&i.set(0,0,1);const s=(new r.Vector3).crossVectors(n,i).normalize();return(new r.Vector3).crossVectors(s,n).normalize()}xm||(xm=1,vm.exports=((ym=function(){function e(e){return r.appendChild(e.dom),e}function t(e){for(var t=0;t<r.children.length;t++)r.children[t].style.display=t===e?"block":"none";n=e}var n=0,r=document.createElement("div");r.style.cssText="position:fixed;top:0;left:0;cursor:pointer;opacity:0.9;z-index:10000",r.addEventListener("click",(function(e){e.preventDefault(),t(++n%r.children.length)}),!1);var i=(performance||Date).now(),s=i,a=0,o=e(new ym.Panel("FPS","#0ff","#002")),l=e(new ym.Panel("MS","#0f0","#020"));if(self.performance&&self.performance.memory)var c=e(new ym.Panel("MB","#f08","#201"));return t(0),{REVISION:16,dom:r,addPanel:e,showPanel:t,begin:function(){i=(performance||Date).now()},end:function(){a++;var e=(performance||Date).now();if(l.update(e-i,200),e>s+1e3&&(o.update(1e3*a/(e-s),100),s=e,a=0,c)){var t=performance.memory;c.update(t.usedJSHeapSize/1048576,t.jsHeapSizeLimit/1048576)}return e},update:function(){i=this.end()},domElement:r,setMode:t}}).Panel=function(e,t,n){var r=1/0,i=0,s=Math.round,a=s(window.devicePixelRatio||1),o=80*a,l=48*a,c=3*a,u=2*a,h=3*a,d=15*a,p=74*a,m=30*a,f=document.createElement("canvas");f.width=o,f.height=l,f.style.cssText="width:80px;height:48px";var g=f.getContext("2d");return g.font="bold "+9*a+"px Helvetica,Arial,sans-serif",g.textBaseline="top",g.fillStyle=n,g.fillRect(0,0,o,l),g.fillStyle=t,g.fillText(e,c,u),g.fillRect(h,d,p,m),g.fillStyle=n,g.globalAlpha=.9,g.fillRect(h,d,p,m),{dom:f,update:function(l,x){r=Math.min(r,l),i=Math.max(i,l),g.fillStyle=n,g.globalAlpha=1,g.fillRect(0,0,o,d),g.fillStyle=t,g.fillText(s(l)+" "+e+" ("+s(r)+"-"+s(i)+")",c,u),g.drawImage(f,h+a,d,p-a,m,h,d,p-a,m),g.fillRect(h+p-a,d,a,m),g.fillStyle=n,g.globalAlpha=.9,g.fillRect(h+p-a,d,a,s((1-l/x)*m))}}},ym));class Mm extends Do{constructor(e){super(),this.camera=e,this.lookAt=new r.Vector3,this.cameraTween=null,this.lookAtTween=null,this.is2D=!1}animateTo(e,t,n=fm){return new Promise(((i,s)=>{const a=this.camera.position.clone(),o=this.camera.quaternion.clone(),l=e.clone(),c=t.clone(),u=l.clone().sub(a).length(),h=c.clone().multiply(o.clone().invert()),d=Math.acos(Math.min(1,h.w));if(u<1&&d<1)i();else{const e=new r.Vector3(0,0,.25*-u).applyQuaternion(o).add(a),t=new r.Vector3(0,0,.25*-u).applyQuaternion(c).add(l),s=_m(a,e),h=_m(l,t);this.camera.up.copy(s),this.lookAt.copy(e),this.lookAtTween=new dm(this.lookAt).to(t,n).easing(am.Quartic.InOut).onComplete((()=>{this.lookAt.copy(t),this.lookAtTween=null})).start(),this.cameraTween=new dm(this.camera).to({position:l,up:h},n).easing(am.Quartic.InOut).onComplete((()=>{this.camera.position.copy(l),this.cameraTween=null,i()})).start()}}))}update(e){this.cameraUpTween&&this.cameraUpTween.update(e),this.cameraTween&&this.cameraTween.update(e),this.lookAtTween&&this.lookAtTween.update(e),(this.cameraTween||this.lookAtTween)&&this.camera.lookAt(this.lookAt)}cancel(){this.cameraTween&&(this.cameraTween.stop(),this.cameraTween=null),this.lookAtTween&&(this.lookAtTween.stop(),this.lookAtTween=null),this.cameraUpTween&&(this.cameraUpTween.stop(),this.cameraUpTween=null)}}class Am extends r.Mesh{constructor(){const e=new r.ShaderMaterial({name:"SkyMaterial",uniforms:{turbidity:{value:5},rayleigh:{value:1},mieCoefficient:{value:.005},mieDirectionalG:{value:.5},sunPosition:{value:new r.Vector3},up:{value:new r.Vector3(0,1,0)},surfaceUp:{value:new r.Vector3(0,1,0)}},vertexShader:"uniform vec3 sunPosition;uniform float rayleigh;uniform float turbidity;uniform float mieCoefficient;uniform vec3 up;varying vec3 vWorldPosition;varying vec3 vSunDirection;varying float vSunfade;varying vec3 vBetaR;varying vec3 vBetaM;varying float vSunE;const float e=2.71828182845904523536028747135266249775724709369995957;const float pi=3.141592653589793238462643383279502884197169;const vec3 lambda=vec3(680E-9,550E-9,450E-9);const vec3 totalRayleigh=vec3(5.804542996261093E-6,1.3562911419845635E-5,3.0265902468824876E-5);const float v=4.0;const vec3 K=vec3(0.686,0.678,0.666);const vec3 MieConst=vec3(1.8399918514433978E14,2.7798023919660528E14,4.0790479543861094E14);const float cutoffAngle=1.6110731556870734;const float steepness=1.5;const float EE=1000.0;float sunIntensity(float zenithAngleCos){zenithAngleCos=clamp(zenithAngleCos,-1.0,1.0);return EE*max(0.0,1.0-pow(e,-((cutoffAngle-acos(zenithAngleCos))/steepness)));}vec3 totalMie(float T){float c=(0.2*T)*10E-18;return 0.434*c*MieConst;}void main(){vec4 worldPosition=modelMatrix*vec4(position,1.0);vWorldPosition=worldPosition.xyz;gl_Position=projectionMatrix*modelViewMatrix*vec4(position,1.0);gl_Position.z=gl_Position.w;vSunDirection=normalize(sunPosition);vSunE=sunIntensity(dot(vSunDirection,up));vSunfade=1.0-clamp(1.0-exp((sunPosition.y/450000.0)),0.0,1.0);float rayleighCoefficient=rayleigh-(1.0*(1.0-vSunfade));vBetaR=totalRayleigh*rayleighCoefficient;vBetaM=totalMie(turbidity)*mieCoefficient;}",fragmentShader:"varying vec3 vWorldPosition;varying vec3 vSunDirection;varying float vSunfade;varying vec3 vBetaR;varying vec3 vBetaM;varying float vSunE;uniform float mieDirectionalG;uniform vec3 up;uniform vec3 surfaceUp;const float pi=3.141592653589793238462643383279502884197169;const float n=1.0003;const float N=2.545E25;const float rayleighZenithLength=8.4E3;const float mieZenithLength=1.25E3;const float sunAngularDiameterCos=0.999956676946448443553574619906976478926848692873900859324;const float THREE_OVER_SIXTEENPI=0.05968310365946075;const float ONE_OVER_FOURPI=0.07957747154594767;float rayleighPhase(float cosTheta){return THREE_OVER_SIXTEENPI*(1.0+pow(cosTheta,2.0));}float hgPhase(float cosTheta,float g){float g2=pow(g,2.0);float inverse=1.0/pow(1.0-2.0*g*cosTheta+g2,1.5);return ONE_OVER_FOURPI*((1.0-g2)*inverse);}void main(){vec3 direction=normalize(vWorldPosition-cameraPosition);float zenithAngle=acos(max(0.0,dot(surfaceUp,direction)));float inverse=1.0/(cos(zenithAngle)+0.15*pow(93.885-((zenithAngle*180.0)/pi),-1.253));float sR=rayleighZenithLength*inverse;float sM=mieZenithLength*inverse;vec3 Fex=exp(-(vBetaR*sR+vBetaM*sM));float cosTheta=dot(direction,vSunDirection);float rPhase=rayleighPhase(cosTheta*0.5+0.5);vec3 betaRTheta=vBetaR*rPhase;float mPhase=hgPhase(cosTheta,mieDirectionalG);vec3 betaMTheta=vBetaM*mPhase;vec3 Lin=pow(vSunE*((betaRTheta+betaMTheta)/(vBetaR+vBetaM))*(1.0-Fex),vec3(1.5));Lin*=mix(vec3(1.0),pow(vSunE*((betaRTheta+betaMTheta)/(vBetaR+vBetaM))*Fex,vec3(1.0/2.0)),clamp(pow(1.0-dot(up,vSunDirection),5.0),0.0,1.0));float theta=acos(direction.y);float phi=atan(direction.z,direction.x);vec2 uv=vec2(phi,theta)/vec2(2.0*pi,pi)+vec2(0.5,0.0);vec3 L0=vec3(0.1)*Fex;float sundisk=smoothstep(sunAngularDiameterCos,sunAngularDiameterCos+0.00002,cosTheta);L0+=(vSunE*19000.0*Fex)*sundisk;vec3 texColor=(Lin+L0)*0.04+vec3(0.0,0.0003,0.00075);vec3 retColor=pow(texColor,vec3(1.0/(1.2+(1.2*vSunfade))));gl_FragColor=vec4(retColor,1.0);\n#include <tonemapping_fragment>\n#include <colorspace_fragment>\n}",side:r.BackSide,depthWrite:!1});super(new r.BoxGeometry(1,1,1),e),this.isSky=!0,this.type="Sky",this.material=e}setSurfaceUp(e){this.material.uniforms.surfaceUp.value.copy(e)}}class Em extends r.Object3D{constructor(){super(),this.type="ContentLayer",this.isContentLayer=!0,this.labels=new Set}setLabels(e){this.labels.clear();for(let t=0;t<e.length;t++)this.labels.add(e[t])}setEnabled(e){this.visible=e}update(){}dispose(){}disposeObjectResources(e=this){e.traverse((e=>{var t,n,r,i;if(null==(n=null==(t=e.geometry)?void 0:t.dispose)||n.call(t),!e.material)return;const s=Array.isArray(e.material)?e.material:[e.material];for(const a of s){for(const e of Object.values(a))(null==e?void 0:e.isTexture)&&(null==(r=e.dispose)||r.call(e));null==(i=a.dispose)||i.call(a)}}))}}const Cm=`https://unpkg.com/three@0.${r.REVISION}.x`;class Rm extends Em{constructor(e,t={}){super(),this.type="TilesLayer",this.isTilesLayer=!0;const n=(null==t?void 0:t.renderOrder)??0,i=(null==t?void 0:t.implicit)??!1,s="overlay"==(null==t?void 0:t.blendeMode),a=(null==t?void 0:t.offset)??{lon:0,lat:0,alt:0};this.firstSet=(null==t?void 0:t.firstSet)??null,this.camera=(null==t?void 0:t.camera)??null,this.renderer=(null==t?void 0:t.renderer)??null,this.dracoLoader=new Je,this.dracoLoader.setDecoderPath(`${Cm}/examples/jsm/libs/draco/gltf/`),this.ktx2loader=new pn,this.ktx2loader.setTranscoderPath(`${Cm}/examples/jsm/libs/basis/`),this.ktx2loader.detectSupport(this.renderer),this.layers.set(n);const o=new dh(e);e.startsWith("http")||o.registerPlugin(new Bd({apiToken:Tokens.CESIUM,assetId:e,autoRefreshToken:!0})),i&&o.registerPlugin(new _h),o.registerPlugin(new Fp({rtc:!0,dracoLoader:this.dracoLoader,ktxLoader:this.ktx2loader})),o.errorTarget=20,this.firstSet&&(o.lruCache=this.firstSet.lruCache,o.downloadQueue=this.firstSet.downloadQueue,o.parseQueue=this.firstSet.parseQueue,o.processNodeQueue=this.firstSet.processNodeQueue),o.setCamera(this.camera),o.setResolutionFromRenderer(this.camera,this.renderer),o.addEventListener("load-model",(e=>{if(0===e.tile.__depth){const t=e.tile.cached.scene.position,n=bm(...t.toArray()),i={lon:n.lon+a.lon,lat:n.lat+a.lat,alt:n.alt+a.alt},s=wm(i.lon,i.lat,i.alt),l=(new r.Vector3).fromArray(s).sub(t);o.group.position.add(l)}e.scene.traverse((e=>{e.layers.mask=this.layers.mask,e.material&&(e.material.isPointsMaterial?(e.material.sizeAttenuation=!0,e.material.size=.2,e.material.map=(new r.TextureLoader).load("/assets/viewer/dot.png",(e=>{})),e.material.alphaTest=.1,e.material.transparent=!0,e.material.onBeforeCompile=e=>{e.vertexShader="uniform float size;uniform float scale;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\n#ifdef USE_POINTS_UV\nvarying vec2 vUv;uniform mat3 uvTransform;\n#endif\nvoid main(){\n#ifdef USE_POINTS_UV\nvUv=(uvTransform*vec3(uv,1)).xy;\n#endif\n#include <color_vertex>\n#include <morphinstance_vertex>\n#include <morphcolor_vertex>\n#include <begin_vertex>\n#include <morphtarget_vertex>\n#include <project_vertex>\ngl_PointSize=size;bool isPerspective=isPerspectiveMatrix(projectionMatrix);if(isPerspective){gl_PointSize*=(scale/-mvPosition.z);gl_PointSize=max(gl_PointSize,5.0);}\n#include <logdepthbuf_vertex>\n#include <clipping_planes_vertex>\n#include <worldpos_vertex>\n#include <fog_vertex>\n}",e.fragmentShader="uniform vec3 diffuse;uniform float opacity;\n#include <common>\n#include <color_pars_fragment>\n#include <map_particle_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main(){vec4 diffuseColor=vec4(diffuse,opacity);\n#include <clipping_planes_fragment>\nvec3 outgoingLight=vec3(0.0);\n#include <logdepthbuf_fragment>\n#include <map_particle_fragment>\n#include <color_fragment>\n#include <alphatest_fragment>\n#include <alphahash_fragment>\noutgoingLight=diffuseColor.rgb;\n#include <opaque_fragment>\n#include <tonemapping_fragment>\n#include <colorspace_fragment>\n#include <fog_fragment>\n#include <premultiplied_alpha_fragment>\n}"}):(e.material.onBeforeCompile=e=>{s&&(e.vertexShader="#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main(){\n#include <uv_vertex>\n#include <color_vertex>\n#include <morphinstance_vertex>\n#include <morphcolor_vertex>\n#include <batching_vertex>\n#if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )\n#include <beginnormal_vertex>\n#include <morphnormal_vertex>\n#include <skinbase_vertex>\n#include <skinnormal_vertex>\n#include <defaultnormal_vertex>\n#endif\n#include <begin_vertex>\n#include <morphtarget_vertex>\n#include <skinning_vertex>\n#include <project_vertex>\n#include <logdepthbuf_vertex>\n#include <clipping_planes_vertex>\n#include <worldpos_vertex>\n#include <envmap_vertex>\n#include <fog_vertex>\n}",e.fragmentShader="uniform vec3 diffuse;uniform float opacity;\n#ifndef FLAT_SHADED\nvarying vec3 vNormal;\n#endif\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nuniform float overlayMode;void main(){vec4 diffuseColor=vec4(diffuse,opacity);\n#include <clipping_planes_fragment>\n#include <logdepthbuf_fragment>\n#include <map_fragment>\n#include <color_fragment>\n#include <alphamap_fragment>\n#include <alphatest_fragment>\n#include <alphahash_fragment>\n#include <specularmap_fragment>\nReflectedLight reflectedLight=ReflectedLight(vec3(0.0),vec3(0.0),vec3(0.0),vec3(0.0));\n#ifdef USE_LIGHTMAP\nvec4 lightMapTexel=texture2D(lightMap,vLightMapUv);reflectedLight.indirectDiffuse+=lightMapTexel.rgb*lightMapIntensity*RECIPROCAL_PI;\n#else\nreflectedLight.indirectDiffuse+=vec3(1.0);\n#endif\n#include <aomap_fragment>\nreflectedLight.indirectDiffuse*=diffuseColor.rgb;vec3 outgoingLight=reflectedLight.indirectDiffuse;\n#include <envmap_fragment>\n#include <opaque_fragment>\n#include <tonemapping_fragment>\n#include <colorspace_fragment>\n#include <fog_fragment>\n#include <premultiplied_alpha_fragment>\ngl_FragColor=mix(gl_FragColor,vec4(gl_FragColor.rgb,gl_FragColor.a*pow(gl_FragColor.b,0.667)),overlayMode);}",e.uniforms.overlayMode={value:s?1:0})},s&&(e.material.transparent=!0,e.material.alphaTest=.1)))}))})),o.addEventListener("load-tile-set",(e=>{})),this.tiles=o,this.add(o.group)}update(){super.update(),this.visible&&this.tiles.update()}dispose(){var e,t,n,r;super.dispose(),this.tiles&&(this.tiles.dispose(),this.remove(this.tiles.group),this.tiles=null),null==(t=null==(e=this.dracoLoader)?void 0:e.dispose)||t.call(e),null==(r=null==(n=this.ktx2loader)?void 0:n.dispose)||r.call(n)}}class Dm extends Em{constructor(e,t={}){super(),this.type="MeshLayer",this.isMeshLayer=!0;const n=(null==t?void 0:t.renderOrder)??0;null==t||t.offset;(new rt).load(e,(e=>{const t=e.scene;e.scene.layers.set(6);for(let n=0;n<t.children[0].children.length;n++){const e=t.children[0].children[n];e.layers.set(6),e.material.transparent=!0,e.material.onBeforeCompile=e=>{e.fragmentShader="uniform vec3 diffuse;uniform float opacity;\n#ifndef FLAT_SHADED\nvarying vec3 vNormal;\n#endif\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main(){vec4 diffuseColor=vec4(diffuse,opacity);\n#include <clipping_planes_fragment>\n#include <logdepthbuf_fragment>\n#include <map_fragment>\n#include <alphamap_fragment>\n#include <alphatest_fragment>\n#include <alphahash_fragment>\n#include <specularmap_fragment>\nReflectedLight reflectedLight=ReflectedLight(vec3(0.0),vec3(0.0),vec3(0.0),vec3(0.0));\n#ifdef USE_LIGHTMAP\nvec4 lightMapTexel=texture2D(lightMap,vLightMapUv);reflectedLight.indirectDiffuse+=lightMapTexel.rgb*lightMapIntensity*RECIPROCAL_PI;\n#else\nreflectedLight.indirectDiffuse+=vec3(1.0);\n#endif\n#include <aomap_fragment>\nreflectedLight.indirectDiffuse*=diffuseColor.rgb;vec3 outgoingLight=reflectedLight.indirectDiffuse;\n#include <envmap_fragment>\n#include <opaque_fragment>\n#include <tonemapping_fragment>\n#include <colorspace_fragment>\n#include <fog_fragment>\n#include <premultiplied_alpha_fragment>\n#include <dithering_fragment>\n#ifdef USE_COLOR\ngl_FragColor.a=vColor.r;\n#endif\n}"}}this.mesh=t,this.add(t)})),this.layers.set(n)}dispose(){this.mesh&&(this.disposeObjectResources(this.mesh),this.mesh.removeFromParent(),this.mesh=null)}}var km="#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvarying float vOpacity;void main(){\n#include <uv_vertex>\n#include <color_vertex>\n#include <morphinstance_vertex>\n#include <morphcolor_vertex>\n#include <batching_vertex>\n#if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )\n#include <beginnormal_vertex>\n#include <morphnormal_vertex>\n#include <skinbase_vertex>\n#include <skinnormal_vertex>\n#include <defaultnormal_vertex>\n#endif\n#include <begin_vertex>\n#include <morphtarget_vertex>\n#include <skinning_vertex>\n#include <project_vertex>\n#include <logdepthbuf_vertex>\n#include <clipping_planes_vertex>\n#include <worldpos_vertex>\n#include <envmap_vertex>\n#include <fog_vertex>\nvOpacity=smoothstep(100.0,500.0,-mvPosition.z);}",Im="uniform vec3 diffuse;uniform float opacity;\n#ifndef FLAT_SHADED\nvarying vec3 vNormal;\n#endif\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvarying float vOpacity;void main(){vec4 diffuseColor=vec4(diffuse,opacity);\n#include <clipping_planes_fragment>\n#include <logdepthbuf_fragment>\n#include <map_fragment>\n#include <color_fragment>\n#include <alphamap_fragment>\n#include <alphatest_fragment>\n#include <alphahash_fragment>\n#include <specularmap_fragment>\nReflectedLight reflectedLight=ReflectedLight(vec3(0.0),vec3(0.0),vec3(0.0),vec3(0.0));\n#ifdef USE_LIGHTMAP\nvec4 lightMapTexel=texture2D(lightMap,vLightMapUv);reflectedLight.indirectDiffuse+=lightMapTexel.rgb*lightMapIntensity*RECIPROCAL_PI;\n#else\nreflectedLight.indirectDiffuse+=vec3(1.0);\n#endif\n#include <aomap_fragment>\nreflectedLight.indirectDiffuse*=diffuseColor.rgb;vec3 outgoingLight=reflectedLight.indirectDiffuse;\n#include <envmap_fragment>\n#include <opaque_fragment>\n#include <tonemapping_fragment>\n#include <colorspace_fragment>\n#include <fog_fragment>\n#include <premultiplied_alpha_fragment>\n#include <dithering_fragment>\ngl_FragColor.a*=vOpacity;}";const Pm=new class{constructor(e=4){this.limit=e,this.queue=[],this.workers=[],this.workersResolve=[],this.workerStatus=0,this.workerCreator=null}initWorker(e){if(!this.workers[e]){const t=this.workerCreator();t.addEventListener("message",this.onMessage.bind(this,e)),this.workers[e]=t}}getIdleWorker(){for(let e=0;e<this.limit;e++)if(!(this.workerStatus&1<<e))return e;return-1}onMessage(e,t){const n=this.workersResolve[e];if(n&&n(t),this.queue.length){const{resolve:t,msg:n,transfer:r}=this.queue.shift();this.workersResolve[e]=t,this.workers[e].postMessage(n,r)}else this.workerStatus^=1<<e}setWorkerCreator(e){this.workerCreator=e}setWorkerLimit(e){this.limit=e}postMessage(e,t){return new Promise((n=>{const r=this.getIdleWorker();-1!==r?(this.initWorker(r),this.workerStatus|=1<<r,this.workersResolve[r]=n,this.workers[r].postMessage(e,t)):this.queue.push({resolve:n,msg:e,transfer:t})}))}dispose(){this.workers.forEach((e=>e.terminate())),this.workersResolve.length=0,this.workers.length=0,this.queue.length=0,this.workerStatus=0}};function Lm(e=new Date(-864e13),t=new Date(864e13),n,r){return n&&r?n<=t&&r>e:n?n<=t:!r||r>e}Pm.setWorkerCreator((function(e){return new Worker("/assets/viewer/geojson.worker-bpUFQjm2.js",{name:null==e?void 0:e.name})}));class Um extends r.Object3D{constructor(e,t={}){var n,i,s;super(),this.type="ArrowFeature",this.isArrowFeature=!0,this.timeStart=(null==(n=null==e?void 0:e.properties)?void 0:n.timeStart)?new Date(e.properties.timeStart):null,this.timeEnd=(null==(i=null==e?void 0:e.properties)?void 0:i.timeEnd)?new Date(e.properties.timeEnd):null;const a=(null==t?void 0:t.renderOrder)??0,o=(null==(s=null==e?void 0:e.properties)?void 0:s.color)??15955057;Pm.postMessage({type:"arrow",data:e,color:o}).then((e=>{const{success:t,code:n,error:i,meshVertexBuffer:s}=e.data;if(t){const e=new r.BufferGeometry;e.setAttribute("position",new r.BufferAttribute(s,3));const t=new r.MeshBasicMaterial({color:o,side:r.DoubleSide,depthTest:!1,opacity:.75,transparent:!0,toneMapped:!1});t.onBeforeCompile=e=>{e.vertexShader=km,e.fragmentShader=Im};const n=new r.Mesh(e,t);n.layers.set(a),this.add(n)}}))}}class Fm extends r.Object3D{constructor(e,t={}){var n,i,s;super(),this.type="PerimeterFeature",this.isPerimeterFeature=!0,this.timeStart=(null==(n=null==e?void 0:e.properties)?void 0:n.timeStart)?new Date(e.properties.timeStart):null,this.timeEnd=(null==(i=null==e?void 0:e.properties)?void 0:i.timeEnd)?new Date(e.properties.timeEnd):null;const a=(null==t?void 0:t.renderOrder)??0,o=(null==(s=null==e?void 0:e.properties)?void 0:s.color)??15955057;Pm.postMessage({type:"perimeter",data:e,color:o}).then((e=>{const{success:t,code:n,error:i,lineVertexBuffer:s,lineVertexRGBBuffer:o,meshVertexBuffer:l,meshVertexRGBBuffer:c,meshIndexBuffer:u}=e.data;if(t){const e=new r.BufferGeometry;e.setAttribute("position",new r.BufferAttribute(l,3)),e.setAttribute("color",new r.BufferAttribute(c,3,!0)),e.setIndex(new r.BufferAttribute(u,1));const t=new r.MeshBasicMaterial({opacity:.2,transparent:!0,side:r.DoubleSide,depthTest:!1,vertexColors:!0,toneMapped:!1});t.onBeforeCompile=e=>{e.vertexShader=km,e.fragmentShader=Im};const n=new r.Mesh(e,t);n.layers.set(a);const i=new r.BufferGeometry;i.setAttribute("position",new r.BufferAttribute(s,3)),i.setAttribute("color",new r.BufferAttribute(o,3,!0));const h=new r.LineSegments(i,new r.LineBasicMaterial({vertexColors:!0,toneMapped:!1}));h.layers.set(a),h.add(n),this.add(h)}}))}}class zm extends Em{constructor(e,t={}){var n;super(),this.type="GeojsonLayer",this.isGeojsonLayer=!0;for(let r=0;r<(null==(n=e.features)?void 0:n.length);r++){const n=e.features[r];switch(n.properties.type){case"arrow":const e=new Um(n,t);this.add(e);break;case"perimeter":const r=new Fm(n,t);this.add(r)}}}setTimeFrame(e,t){e&&!e.isDate&&(e=new Date(e)),t&&!t.isDate&&(t=new Date(t));for(let n=0;n<this.children.length;n++){const r=this.children[n],i=r.timeStart,s=r.timeEnd;r.visible=Lm(e,t,i,s)}}dispose(){this.disposeObjectResources(),this.clear()}}const Bm=new Set(["ply","sog"]);function Vm(e,t){return Array.isArray(e)&&e.length===t&&e.every(Number.isFinite)}function Om(e,t){if("string"!=typeof e||0===e.trim().length)throw new Error(`${t} must be a non-empty string.`)}function Nm(e){var t,n,r,i;if(!e||"object"!=typeof e)throw new Error("Gaussian splat layer definition must be an object.");if(Om(e.id,"id"),Om(e.name,"name"),"gaussian-splat"!==e.type)throw new Error('type must be "gaussian-splat".');if(!Array.isArray(e.labels)||!e.labels.every((e=>"string"==typeof e)))throw new Error("labels must be an array of strings.");if(Om(null==(t=e.data)?void 0:t.url,"data.url"),!Bm.has(null==(n=e.data)?void 0:n.format))throw new Error('data.format must be "ply" or "sog".');if(0!==((null==(r=e.options)?void 0:r.renderOrder)??0))throw new Error("Gaussian splat layers only support renderOrder 0.");const s=null==(i=e.options)?void 0:i.transform,a=null==s?void 0:s.anchor;if(!(a&&Number.isFinite(a.longitude)&&Number.isFinite(a.latitude)&&Number.isFinite(a.altitude)))throw new Error("options.transform.anchor must contain finite longitude, latitude, and altitude values.");if(a.longitude<-180||a.longitude>180||a.latitude<-90||a.latitude>90)throw new Error("Anchor longitude must be within [-180, 180] and latitude within [-90, 90].");const o=s.translationENU??[0,0,0],l=s.rotationDegrees??[0,0,0],c=s.scale??1;if(!Vm(o,3))throw new Error("translationENU must be a finite three-number tuple.");if(!Vm(l,3))throw new Error("rotationDegrees must be a finite three-number tuple.");if(!Number.isFinite(c)||c<=0)throw new Error("scale must be a finite positive number.");return{...e,labels:[...e.labels],data:{...e.data},options:{...e.options,renderOrder:0,transform:{anchor:{...a},translationENU:[...o],rotationDegrees:[...l],scale:c}}}}function $m(e){const{anchor:t,translationENU:n,rotationDegrees:i,scale:s}=e,a=t.longitude*Math.PI/180,o=t.latitude*Math.PI/180,l=new r.Vector3(-Math.sin(a),Math.cos(a),0).normalize(),c=new r.Vector3(Math.cos(o)*Math.cos(a),Math.cos(o)*Math.sin(a),Math.sin(o)).normalize(),u=(new r.Vector3).crossVectors(c,l).normalize(),h=(new r.Matrix4).makeBasis(l,u,c);h.setPosition((new r.Vector3).fromArray(function(e,t,n){const r=.0066943799901414,i=t*Math.PI/180,s=e*Math.PI/180,a=6378137/Math.sqrt(1-r*Math.sin(i)**2);return[(a+n)*Math.cos(i)*Math.cos(s),(a+n)*Math.cos(i)*Math.sin(s),(.9933056200098586*a+n)*Math.sin(i)]}(t.longitude,t.latitude,t.altitude)));const d=(new r.Quaternion).setFromEuler(new r.Euler(i[0]*Math.PI/180,i[1]*Math.PI/180,i[2]*Math.PI/180,"XYZ")),p=(new r.Matrix4).compose((new r.Vector3).fromArray(n),d,new r.Vector3(s,s,s));return h.multiply(p)}const Gm={ply:Tr.PLY,sog:Tr.PCSOGSZIP};class qm extends Em{constructor(e,t={}){super(),this.type="GaussianSplatLayer",this.isGaussianSplatLayer=!0,this.contentLayerId=e.id,this.definition=e,this.callbacks=t,this.loadState="idle",this.loadAttempt=0,this.abortController=null,this.splatMesh=null,this.visible=!1,this.layers.set(0),this.setLabels(e.labels),this.transformMatrix=$m(e.options.transform)}setEnabled(e){if("disposed"===this.loadState)return;const t=this.visible;this.visible=e,!e||t||"idle"!==this.loadState&&"error"!==this.loadState||this.load()}async load(){var e,t,n,r,i,s,a,o,l;if("loading"===this.loadState||"ready"===this.loadState||"disposed"===this.loadState)return;const c=++this.loadAttempt;this.loadState="loading",this.abortController=new AbortController;let u=null;try{null==(t=(e=this.callbacks).onStart)||t.call(e,this),null==(r=(n=this.callbacks).ensureRenderer)||r.call(n);const a=await fetch(this.definition.data.url,{signal:this.abortController.signal});if(!a.ok)throw new Error(`Failed to load Gaussian splat: ${a.status} ${a.statusText}`);if(!a.body)throw new Error("Failed to load Gaussian splat: response body is unavailable.");const o=a.headers.get("Content-Length"),l=null===o?void 0:Number.parseInt(o,10);if(u=new lo({stream:a.body,streamLength:Number.isFinite(l)&&l>=0?l:void 0,fileType:Gm[this.definition.data.format],onProgress:e=>{var t,n;"disposed"!==this.loadState&&c===this.loadAttempt&&(null==(n=(t=this.callbacks).onProgress)||n.call(t,this,{loaded:e.loaded,total:e.total,lengthComputable:e.lengthComputable}))}}),u.layers.set(0),u.matrix.copy(this.transformMatrix),u.matrix.decompose(u.position,u.quaternion,u.scale),u.matrixAutoUpdate=!1,u.matrixWorldNeedsUpdate=!0,this.splatMesh=u,this.add(u),await u.initialized,"disposed"===this.loadState||c!==this.loadAttempt)return void this.disposeMesh(u);this.abortController=null,this.loadState="ready",null==(s=(i=this.callbacks).onReady)||s.call(i,this)}catch(h){this.disposeMesh(u);const e=null==(a=this.abortController)?void 0:a.signal.aborted;if(this.abortController=null,"disposed"===this.loadState||c!==this.loadAttempt||e)return;this.loadState="error",null==(l=(o=this.callbacks).onError)||l.call(o,this,function(e){return e instanceof Error?e:new Error(String(e))}(h))}}disposeMesh(e){e&&!e.userData.gaussianSplatDisposed&&(e.userData.gaussianSplatDisposed=!0,e.removeFromParent(),e.dispose(),this.splatMesh===e&&(this.splatMesh=null))}dispose(){var e;"disposed"!==this.loadState&&(this.loadState="disposed",this.loadAttempt++,null==(e=this.abortController)||e.abort(),this.abortController=null,this.disposeMesh(this.splatMesh),this.callbacks={})}}const Hm=document.createElement("canvas");Hm.width=128,Hm.height=128;const jm=Hm.getContext("2d"),Wm=Hm.width/2,Xm=Hm.height/2,Ym=Math.min(Hm.width,Hm.height)/2,Km="0, 0, 0",Qm=jm.createRadialGradient(Wm,Xm,0,Wm,Xm,Ym);Qm.addColorStop(0,`rgba(${Km}, 1)`),Qm.addColorStop(.5,`rgba(${Km}, 0.25)`),Qm.addColorStop(1,`rgba(${Km}, 0)`),jm.fillStyle=Qm,jm.fillRect(0,0,Hm.width,Hm.height);const Zm={APPENDED:"viewer-appended",READY:"viewer-ready",ANIMATED:"viewer-animated",TRANSITIONED:"viewer-transitioned",CONTENT_LAYER_LOAD_START:"content-layer-load-start",CONTENT_LAYER_LOAD_PROGRESS:"content-layer-load-progress",CONTENT_LAYER_READY:"content-layer-ready",CONTENT_LAYER_ERROR:"content-layer-error"};exports.computeElevation=r.computeElevation,exports.Viewer=class extends Do{constructor(e,t={}){super(),this.isViewer=!0,this.type="viewer",this.disposed=!1,this.sparkRenderer=null,mm.CESIUM=t.cesiumToken||void 0,mm.GOOGLEMAPS=t.googleMapsToken||void 0,this.state=new Fo({time:{type:"f",value:0},loaded:!1,added:!1}),this.renderer=new r.WebGLRenderer({antialias:!0,powerPreference:"high-performance"}),this.renderer.setClearColor(16777215,1),this.renderer.toneMapping=r.AgXToneMapping,this.renderer.outputColorSpace=r.SRGBColorSpace,this.renderer.toneMappingExposure=1,this.renderer.supportedFloatType=this.renderer.getContext().getSupportedExtensions().indexOf("OES_texture_float_linear")>=0?r.FloatType:r.HalfFloatType,this.renderer.autoClear=!1,this.css2DRenderer=new An,this.css2DRenderer.domElement.style.setProperty("position","absolute"),this.css2DRenderer.domElement.style.setProperty("left","0"),this.css2DRenderer.domElement.style.setProperty("top","0"),this.css2DRenderer.domElement.style.setProperty("pointer-events","none"),this.clock=new r.Clock,this.camera=new r.PerspectiveCamera(90,1,10,1e8),this.camera.up.set(0,0,1),this.camera.position.fromArray(wm(-105.18896,39.93,9e3)),this.camera.lookAt((new r.Vector3).fromArray(wm(-105.18896,40,0))),this.cameraForward=new r.Vector3,this.cameraRight=new r.Vector3,this.cameraUp=new r.Vector3,this.scene=new r.Scene,this.content=new r.Group,this.scene.add(this.content),this.topLayerIndex=0,this.enabledLayers=[],this.labels=new Map,this.features=new Map,this.globeControls=new qc(this.scene,this.camera,this.renderer.domElement),this.globeControls.enableDamping=!0,this._onGlobeControlsStart=()=>{this.transitionControls.cancel()},this.globeControls.addEventListener("start",this._onGlobeControlsStart),this.transitionControls=new Mm(this.camera),this.globeManager=new sm(this.scene,this.camera,this.renderer,{apiToken:mm.CESIUM,googleMapsToken:mm.GOOGLEMAPS}),this.globeControls.setTilesRenderer(this.globeManager.tiles),this.cameraCoords={},this.pointerCoords={},this.pointerXYZ=new r.Vector3,this.keysDown={},this.keysEnabled=!0,this.movementKeys={BOOST:["ShiftLeft","ShiftRight"],FRONT:["KeyW"],BACK:["KeyS"],LEFT:["KeyA"],RIGHT:["KeyD"],UP:["KeyE"],DOWN:["KeyQ"]},this.movementState={BOOST:!1,FRONT:!1,BACK:!1,LEFT:!1,RIGHT:!1,UP:!1,DOWN:!1},this._onKeyDown=e=>{this.keysDown[e.code]=!0,this.updateMovementState()},this._onKeyUp=e=>{this.keysDown[e.code]=!1,this.updateMovementState()},this._onResize=e=>{this.resizeView(e)},window.addEventListener("keydown",this._onKeyDown),window.addEventListener("keyup",this._onKeyUp),window.addEventListener("resize",this._onResize),this.setAnimate(),e&&this.appendTo(e),this.sky=new Am,this.sky.scale.setScalar(2e7),this.scene.add(this.sky);const n=r.MathUtils.degToRad(80),i=r.MathUtils.degToRad(180),s=(new r.Vector3).setFromSphericalCoords(1,n,i);this.sky.material.uniforms.sunPosition.value=s,this.pointerRaycaster=new r.Raycaster,this._onPointerMove=e=>{const t={};t.x=e.clientX/window.innerWidth*2-1,t.y=-e.clientY/window.innerHeight*2+1,this.pointerRaycaster.setFromCamera(t,this.camera);const n=this.pointerRaycaster.intersectObject(this.globeManager.tiles.group,!0);if(n.length>0){const e=n[0];e?(this.pointerCoords=bm(e.point.x,e.point.y,e.point.z),this.pointerXYZ.copy(e.point)):this.pointerCoords={}}else this.pointerCoords={}},window.addEventListener("pointermove",this._onPointerMove)}updateMovementState(){if(this.keysEnabled)for(const e in this.movementKeys){this.movementState[e]=!1;for(let t=0;t<this.movementKeys[e].length;t++){const n=this.movementKeys[e][t];if(this.keysDown[n]){this.movementState[e]=!0;break}}}}getElevation(e,t){const n=(new r.Vector3).fromArray(wm(e,t,1e4)),i=(new r.Vector3).sub(n).normalize(),s=new r.Raycaster;s.ray.set(n,i);const a=this.globeControls.raycast(s);return bm(a.point.x,a.point.y,a.point.z)}updateCoordsElevation(e){for(let t=0;t<e.length;t++){const[n,r]=e[t];e[t][2]=this.getElevation(n,r).alt}return e}setBackgroundColor(e){this.renderer.setClearColor(e,0)}appendTo(e){this.container=e,this.container.appendChild(this.renderer.domElement),this.container.appendChild(this.css2DRenderer.domElement),this.resizeView(),this.dispatchEvent({type:Zm.APPENDED})}updateCameraDirections(){const e=new r.Matrix4;e.extractRotation(this.camera.matrixWorld),this.cameraForward.set(0,0,-1).applyMatrix4(e),this.cameraRight.set(1,0,0).applyMatrix4(e),this.cameraUp.set(0,1,0).applyMatrix4(e)}setAnimate(e=!0){e?this.renderer.setAnimationLoop(((e,t)=>{this.animate(e)})):this.renderer.setAnimationLoop(null)}resizeView(e){if(this.container){const e=this.container.offsetWidth,t=this.container.offsetHeight;this.camera.aspect=e/t,this.camera.updateProjectionMatrix(),this.renderer.setSize(e,t),this.css2DRenderer.setSize(e,t),this.renderer.render(this.scene,this.camera),this.css2DRenderer.render(this.scene,this.camera)}}async loadEnv(e){const t=await new gm(e,{floatType:this.renderer.supportedFloatType});t.mapping=r.EquirectangularReflectionMapping,this.scene.environment=t,this.scene.environmentRotation.set(Math.PI/2,0,0)}clearContentLayers(){for(var e;this.content.children.length>0;){const t=this.content.children[0];null==(e=t.dispose)||e.call(t),this.content.remove(t)}this.disposeSparkRenderer()}ensureSparkRenderer(){return this.sparkRenderer||(this.sparkRenderer=new Ja({renderer:this.renderer}),this.sparkRenderer.layers.set(0),this.scene.add(this.sparkRenderer)),this.sparkRenderer}disposeSparkRenderer(){var e,t;this.sparkRenderer&&(this.sparkRenderer.removeFromParent(),null==(t=(e=this.sparkRenderer).clearSplats)||t.call(e),this.sparkRenderer.dispose(),this.sparkRenderer=null)}defineContentLayers(e=[]){var t,n,r;this.topLayerIndex=0,this.clearContentLayers();for(let s=0;s<e.length;s++){const a=e[s];try{const e="gaussian-splat"===(null==a?void 0:a.type)?Nm(a):a;switch(this.topLayerIndex=Math.max(this.topLayerIndex,(null==(t=null==e?void 0:e.options)?void 0:t.renderOrder)??0),null==e?void 0:e.type){case"3d-tiles":{const t=new Rm(e.data.url,{camera:this.camera,renderer:this.renderer,...e.options});t.setLabels(e.labels),null==(n=t.setTimeFrame)||n.call(t,this.timeFrameStart,this.timeFrameEnd),t.setEnabled(!1),this.content.add(t);break}case"mesh":{const t=new Dm(e.data.url,{...e.options});t.setLabels(e.labels),t.setEnabled(!1),this.content.add(t);break}case"geojson":{const t=new zm(e.data,e.options);t.setLabels(e.labels),null==(r=t.setTimeFrame)||r.call(t,this.timeFrameStart,this.timeFrameEnd),t.setEnabled(!1),this.content.add(t);break}case"gaussian-splat":{const t=new qm(e,{ensureRenderer:()=>this.ensureSparkRenderer(),onStart:e=>this.dispatchEvent({type:Zm.CONTENT_LAYER_LOAD_START,layerId:e.contentLayerId}),onProgress:(e,t)=>this.dispatchEvent({type:Zm.CONTENT_LAYER_LOAD_PROGRESS,layerId:e.contentLayerId,progress:t}),onReady:e=>this.dispatchEvent({type:Zm.CONTENT_LAYER_READY,layerId:e.contentLayerId}),onError:(e,t)=>this.dispatchEvent({type:Zm.CONTENT_LAYER_ERROR,layerId:e.contentLayerId,error:t})});this.content.add(t);break}default:throw new Error(`Unsupported content layer type: ${String(null==e?void 0:e.type)}`)}}catch(i){this.dispatchEvent({type:Zm.CONTENT_LAYER_ERROR,layerId:"string"==typeof(null==a?void 0:a.id)&&a.id.length>0?a.id:null,error:i instanceof Error?i:new Error(String(i))})}}this.globeControls.pivotMesh.layers.set(this.topLayerIndex),this.enableContentLayers(this.enabledLayers)}enableContentLayers(e=[]){this.enabledLayers=e;for(let t=0;t<this.content.children.length;t++){const n=this.content.children[t];let r=!1;for(let t=0;t<e.length;t++){const i=e[t];if(n.labels.has(i)){r=!0;break}}n.setEnabled(r)}}setTimeFrame(e,t){var n;this.timeFrameStart=e?new Date(e):null,this.timeFrameEnd=t?new Date(t):null;for(let r=0;r<this.content.children.length;r++){const e=this.content.children[r];null==(n=e.setTimeFrame)||n.call(e,this.timeFrameStart,this.timeFrameEnd)}}updateLabel(e,t={}){const n=(null==t?void 0:t.element)??document.createElement("div"),i=(null==t?void 0:t.lat)??0,s=(null==t?void 0:t.lon)??0,a=(null==t?void 0:t.alt)??0,o=(null==t?void 0:t.visible)??!0,l=(null==t?void 0:t.hovered)??!1,c=(null==t?void 0:t.selected)??!1;let u=null;if(this.labels.has(e))u=this.labels.get(e);else{u=new bn(n),u.position.fromArray(wm(s,i,a));const t=new r.Mesh(new r.PlaneGeometry(1e3,1e3),new r.MeshBasicMaterial({map:new r.CanvasTexture(Hm),opacity:1,transparent:!0,side:r.DoubleSide}));t.layers.set(this.topLayerIndex),u.add(t),u.lookAt(0,0,0),this.scene.add(u),this.labels.set(e,u)}return u.visible=o,l?u.element.classList.add("hovered"):u.element.classList.remove("hovered"),c?u.element.classList.add("selected"):u.element.classList.remove("selected"),u.element}animate(e){this.stats&&this.stats.begin(),this.transitionControls.update(e),this.state.get("time").value=e;const t=this.clock.getDelta();this.globeControls.update(),this.camera.updateMatrixWorld(),this.updateCameraDirections(),this.sky.setSurfaceUp(Tm(this.cameraCoords.lon,this.cameraCoords.lat));const n=this.movementState.BOOST?5:1;this.movementState.FRONT&&this.camera.position.addScaledVector(this.cameraForward,100*t*n),this.movementState.BACK&&this.camera.position.addScaledVector(this.cameraForward,-100*t*n),this.movementState.LEFT&&this.camera.position.addScaledVector(this.cameraRight,-100*t*n),this.movementState.RIGHT&&this.camera.position.addScaledVector(this.cameraRight,100*t*n),this.movementState.UP&&this.camera.position.addScaledVector(this.cameraUp,100*t*n),this.movementState.DOWN&&this.camera.position.addScaledVector(this.cameraUp,-100*t*n),this.globeManager.update();for(let r=0;r<this.content.children.length;r++){this.content.children[r].update()}for(const[i,s]of this.labels)if(s.element){s.element.classList.remove("far"),s.element.classList.remove("mid"),s.element.classList.remove("close");const e=(new r.Vector3).subVectors(s.position,this.camera.position).dot(this.cameraForward);s.scale.setScalar(e/1e4),s.children[0].material.opacity=Math.min(Math.max(1-e/2e3,.1),1),e>3200?s.element.classList.add("far"):e>1e3?s.element.classList.add("mid"):s.element.classList.add("close")}for(let r=0;r<this.topLayerIndex+1;r++)this.camera.layers.set(r),0==r?(this.renderer.clear(),this.render()):(this.renderer.clearDepth(),this.renderer.render(this.scene,this.camera));this.cameraCoords=function(e,t,n,i){const{lon:s,lat:a,alt:o}=bm(e,t,n),l=s*(Math.PI/180),c=a*(Math.PI/180),u=new r.Vector3(Math.cos(c)*Math.cos(l),Math.cos(c)*Math.sin(l),Math.sin(c)),h=new r.Vector3(0,0,1),d=h.clone().sub(u.clone().multiplyScalar(h.dot(u))).normalize(),p=(new r.Vector3).crossVectors(d,u).normalize(),m=(new r.Matrix4).makeBasis(p,d,u),f=(new r.Quaternion).setFromRotationMatrix(m).clone().invert().multiply(i),g=(new r.Euler).setFromQuaternion(f,"ZYX");return{lon:s,lat:a,alt:o,pitch:r.MathUtils.radToDeg(g.x)-90,yaw:r.MathUtils.radToDeg(g.z),roll:r.MathUtils.radToDeg(g.y)}}(this.camera.position.x,this.camera.position.y,this.camera.position.z,this.camera.quaternion),this.dispatchEvent({type:Zm.ANIMATED,time:e,deltaTime:t}),this.stats&&this.stats.end()}render(){this.renderer.render(this.scene,this.camera),this.css2DRenderer.render(this.scene,this.camera),!0===this.state.get("added")&&!1===this.state.get("ready")&&(this.state.update({ready:!0}),window.setTimeout((()=>{this.dispatchEvent({type:Zm.READY})}),0))}getCameraPivot(){let e=null;const t=new r.Raycaster;t.setFromCamera({x:0,y:0},this.camera);const n=t.intersectObject(this.globeManager.tiles.group,!0);if(n.length>0){const t=n[0];t&&(e=t.point.clone())}return e||(e=(new r.Vector3).subVectors(this.camera.position,this.cameraForward.clone().multiplyScalar(2e3))),e}async alignCamera(e,t,n,i=this.cameraCoords.pitch,s=this.cameraCoords.yaw,a=this.cameraCoords.roll,o=fm){const l=(new r.Vector3).fromArray(wm(e,t,n)),c=Sm(e,t,i,s,a);return this.transitionControls.animateTo(l,c,o).then((()=>{this.dispatchEvent({type:Zm.TRANSITIONED,lon:e,lat:t,alt:n,pitch:i,yaw:s,roll:a})}))}async focusCamera(e,t,n,i=2e3,s=this.cameraCoords.pitch,a=fm){const o=(new r.Vector3).fromArray(wm(e,t,n)),l=Sm(e,t,s,0,0),c=new r.Vector3(0,0,1).applyQuaternion(l);return o.addScaledVector(c,i),this.transitionControls.animateTo(o,l,a).then((()=>{this.dispatchEvent({type:Zm.TRANSITIONED,lon:e,lat:t,alt:n})}))}async angleCamera(e=this.cameraCoords.pitch,t=this.cameraCoords.yaw,n=fm){const i=this.getCameraPivot(),{lon:s,lat:a,alt:o}=bm(i.x,i.y,i.z),l=this.camera.position.distanceTo(i),c=(new r.Vector3).fromArray(wm(s,a,o)),u=Sm(s,a,e,t,0),h=new r.Vector3(0,0,1).applyQuaternion(u);return c.addScaledVector(h,l),this.transitionControls.animateTo(c,u,n).then((()=>{this.dispatchEvent({type:Zm.TRANSITIONED,lon:s,lat:a,alt:o})}))}setViewMode(e="3d"){"3d"==e?(this.globeControls.rotationSpeed=1,this.angleCamera(-60,void 0,500)):(this.globeControls.rotationSpeed=0,this.angleCamera(-90,0,500))}exportScene(){return e=this.scene,void(new c).parse(e,(e=>{const t=new Blob([e],{type:"application/octet-stream"}),n=URL.createObjectURL(t),r=document.createElement("a");r.href=n,r.download="scene.glb",document.body.appendChild(r),r.click(),document.body.removeChild(r)}),(e=>{}),{binary:!0});var e}saveScreenshot(e="screenshot"){for(let r=0;r<this.topLayerIndex+1;r++)this.camera.layers.set(r),0==r?(this.renderer.clear(),this.render()):(this.renderer.clearDepth(),this.renderer.render(this.scene,this.camera));const t=this.renderer.domElement.toDataURL(),n=document.createElement("a");n.setAttribute("href",t),n.setAttribute("target","_blank"),n.setAttribute("download",`${e}.png`),n.click()}dispose(){var e,t,n,r,i,s,a,o,l,c,u,h,d,p,m;if(!this.disposed){this.disposed=!0,this.setAnimate(!1),this.transitionControls.cancel(),this.clearContentLayers(),window.removeEventListener("keydown",this._onKeyDown),window.removeEventListener("keyup",this._onKeyUp),window.removeEventListener("resize",this._onResize),window.removeEventListener("pointermove",this._onPointerMove),this.globeControls.removeEventListener("start",this._onGlobeControlsStart),this.globeControls.dispose(),this.globeManager.dispose();for(const e of this.labels.values())e.traverse((e=>{var t,n,r,i,s;if(null==(n=null==(t=e.geometry)?void 0:t.dispose)||n.call(t),e.material){const t=Array.isArray(e.material)?e.material:[e.material];for(const e of t)null==(i=null==(r=e.map)?void 0:r.dispose)||i.call(r),null==(s=e.dispose)||s.call(e)}})),e.removeFromParent();this.labels.clear(),this.features.clear(),null==(t=null==(e=this.scene.environment)?void 0:e.dispose)||t.call(e),this.scene.environment=null,null==(i=null==(r=null==(n=this.sky)?void 0:n.geometry)?void 0:r.dispose)||i.call(r),null==(o=null==(a=null==(s=this.sky)?void 0:s.material)?void 0:a.dispose)||o.call(a),null==(l=this.sky)||l.removeFromParent(),null==(u=null==(c=this.stats)?void 0:c.dom)||u.remove(),this.css2DRenderer.domElement.remove(),this.renderer.domElement.remove(),null==(d=null==(h=this.renderer.renderLists)?void 0:h.dispose)||d.call(h),this.renderer.dispose(),null==(m=(p=this.renderer).forceContextLoss)||m.call(p),this.container=null,this.listeners={}}}},exports.ViewerEvents=Zm;
|
|
1
|
+
"use strict";var e,t=Object.defineProperty,n=(e,n,r)=>((e,n,r)=>n in e?t(e,n,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[n]=r)(e,"symbol"!=typeof n?n+"":n,r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("./index-CMipzbxp.cjs");r.ShaderChunk.bayer_dither_hash_pars_fragment="#ifdef USE_HASH\nuniform float hashOpacity;varying float vCameraDistance;float bayerDitherPattern(vec2 p){float bayerMatrix[16];bayerMatrix[0]=0.0;bayerMatrix[1]=8.0;bayerMatrix[2]=2.0;bayerMatrix[3]=10.0;bayerMatrix[4]=12.0;bayerMatrix[5]=4.0;bayerMatrix[6]=14.0;bayerMatrix[7]=6.0;bayerMatrix[8]=3.0;bayerMatrix[9]=11.0;bayerMatrix[10]=1.0;bayerMatrix[11]=9.0;bayerMatrix[12]=15.0;bayerMatrix[13]=7.0;bayerMatrix[14]=13.0;bayerMatrix[15]=5.0;int x=int(mod(p.x,4.0));int y=int(mod(p.y,4.0));int index=x+y*4;return bayerMatrix[index]/16.0;}\n#endif\n",r.ShaderChunk.bayer_dither_hash_fragment="#ifdef USE_HASH\nfloat hashAmount=smoothstep(5e4,1e2,vCameraDistance)*0.75+0.1;float ditherValue=bayerDitherPattern(gl_FragCoord.xy);if(hashAmount<ditherValue){discard;}\n#endif\n",r.ShaderChunk.bayer_dither_hash_pars_vertex="#ifdef USE_HASH\nvarying float vCameraDistance;\n#endif\n",r.ShaderChunk.bayer_dither_hash_vertex="#ifdef USE_HASH\nvCameraDistance=-mvPosition.z;\n#endif\n";const i=new r.OrthographicCamera(-1,1,1,-1,0,1);class s extends r.BufferGeometry{constructor(){super(),this.setAttribute("position",new r.Float32BufferAttribute([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new r.Float32BufferAttribute([0,2,0,0,2,0],2))}}const a=new s;class o{constructor(e){this._mesh=new r.Mesh(a,e)}dispose(){this._mesh.geometry.dispose()}render(e){e.render(this._mesh,i)}get material(){return this._mesh.material}set material(e){this._mesh.material=e}}const l={POSITION:["byte","byte normalized","unsigned byte","unsigned byte normalized","short","short normalized","unsigned short","unsigned short normalized"],NORMAL:["byte normalized","short normalized"],TANGENT:["byte normalized","short normalized"],TEXCOORD:["byte","byte normalized","unsigned byte","short","short normalized","unsigned short"]};class c{constructor(){this.textureUtils=null,this.pluginCallbacks=[],this.register((function(e){return new $(e)})),this.register((function(e){return new G(e)})),this.register((function(e){return new W(e)})),this.register((function(e){return new X(e)})),this.register((function(e){return new Y(e)})),this.register((function(e){return new K(e)})),this.register((function(e){return new q(e)})),this.register((function(e){return new H(e)})),this.register((function(e){return new j(e)})),this.register((function(e){return new Q(e)})),this.register((function(e){return new Z(e)})),this.register((function(e){return new J(e)})),this.register((function(e){return new ee(e)})),this.register((function(e){return new te(e)}))}register(e){return-1===this.pluginCallbacks.indexOf(e)&&this.pluginCallbacks.push(e),this}unregister(e){return-1!==this.pluginCallbacks.indexOf(e)&&this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(e),1),this}setTextureUtils(e){return this.textureUtils=e,this}parse(e,t,n,r){const i=new N,s=[];for(let a=0,o=this.pluginCallbacks.length;a<o;a++)s.push(this.pluginCallbacks[a](i));i.setPlugins(s),i.setTextureUtils(this.textureUtils),i.writeAsync(e,t,r).catch(n)}parseAsync(e,t){const n=this;return new Promise((function(r,i){n.parse(e,r,i,t)}))}}const u=0,h=1,d=2,p=3,m=4,f=5120,g=5121,x=5122,y=5123,v=5124,b=5125,w=5126,T=34962,S=34963,_=9728,M=9729,A=9984,E=9985,C=9986,R=9987,D=33071,k=33648,I=10497,P="KHR_mesh_quantization",L={};L[r.NearestFilter]=_,L[r.NearestMipmapNearestFilter]=A,L[r.NearestMipmapLinearFilter]=C,L[r.LinearFilter]=M,L[r.LinearMipmapNearestFilter]=E,L[r.LinearMipmapLinearFilter]=R,L[r.ClampToEdgeWrapping]=D,L[r.RepeatWrapping]=I,L[r.MirroredRepeatWrapping]=k;const U={scale:"scale",position:"translation",quaternion:"rotation",morphTargetInfluences:"weights"},F=new r.Color;function z(e,t){return e.length===t.length&&e.every((function(e,n){return e===t[n]}))}function B(e){return 4*Math.ceil(e/4)}function V(e,t=0){const n=B(e.byteLength);if(n!==e.byteLength){const r=new Uint8Array(n);if(r.set(new Uint8Array(e)),0!==t)for(let i=e.byteLength;i<n;i++)r[i]=t;return r.buffer}return e}function O(){return"undefined"==typeof document&&"undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(1,1):document.createElement("canvas")}class N{constructor(){this.plugins=[],this.options={},this.pending=[],this.buffers=[],this.byteOffset=0,this.buffers=[],this.nodeMap=new Map,this.skins=[],this.extensionsUsed={},this.extensionsRequired={},this.uids=new Map,this.uid=0,this.json={asset:{version:"2.0",generator:"THREE.GLTFExporter r"+r.REVISION}},this.cache={meshes:new Map,attributes:new Map,attributesNormalized:new Map,materials:new Map,textures:new Map,images:new Map},this.textureUtils=null}setPlugins(e){this.plugins=e}setTextureUtils(e){this.textureUtils=e}async writeAsync(e,t,n={}){this.options=Object.assign({binary:!1,trs:!1,onlyVisible:!0,maxTextureSize:1/0,animations:[],includeCustomExtensions:!1},n),this.options.animations.length>0&&(this.options.trs=!0),await this.processInputAsync(e),await Promise.all(this.pending);const r=this,i=r.buffers,s=r.json;n=r.options;const a=r.extensionsUsed,o=r.extensionsRequired,l=new Blob(i,{type:"application/octet-stream"}),c=Object.keys(a),u=Object.keys(o);if(c.length>0&&(s.extensionsUsed=c),u.length>0&&(s.extensionsRequired=u),s.buffers&&s.buffers.length>0&&(s.buffers[0].byteLength=l.size),!0===n.binary){const e=new FileReader;e.readAsArrayBuffer(l),e.onloadend=function(){const n=V(e.result),r=new DataView(new ArrayBuffer(8));r.setUint32(0,n.byteLength,!0),r.setUint32(4,5130562,!0);const i=V((a=JSON.stringify(s),(new TextEncoder).encode(a).buffer),32);var a;const o=new DataView(new ArrayBuffer(8));o.setUint32(0,i.byteLength,!0),o.setUint32(4,1313821514,!0);const l=new ArrayBuffer(12),c=new DataView(l);c.setUint32(0,1179937895,!0),c.setUint32(4,2,!0);const u=12+o.byteLength+i.byteLength+r.byteLength+n.byteLength;c.setUint32(8,u,!0);const h=new Blob([l,o,i,r,n],{type:"application/octet-stream"}),d=new FileReader;d.readAsArrayBuffer(h),d.onloadend=function(){t(d.result)}}}else if(s.buffers&&s.buffers.length>0){const e=new FileReader;e.readAsDataURL(l),e.onloadend=function(){const n=e.result;s.buffers[0].uri=n,t(s)}}else t(s)}serializeUserData(e,t){if(0===Object.keys(e.userData).length)return;const n=this.options,r=this.extensionsUsed;try{const i=JSON.parse(JSON.stringify(e.userData));if(n.includeCustomExtensions&&i.gltfExtensions){void 0===t.extensions&&(t.extensions={});for(const e in i.gltfExtensions)t.extensions[e]=i.gltfExtensions[e],r[e]=!0;delete i.gltfExtensions}Object.keys(i).length>0&&(t.extras=i)}catch(i){}}getUID(e,t=!1){if(!1===this.uids.has(e)){const t=new Map;t.set(!0,this.uid++),t.set(!1,this.uid++),this.uids.set(e,t)}return this.uids.get(e).get(t)}isNormalizedNormalAttribute(e){if(this.cache.attributesNormalized.has(e))return!1;const t=new r.Vector3;for(let n=0,r=e.count;n<r;n++)if(Math.abs(t.fromBufferAttribute(e,n).length()-1)>5e-4)return!1;return!0}createNormalizedNormalAttribute(e){const t=this.cache;if(t.attributesNormalized.has(e))return t.attributesNormalized.get(e);const n=e.clone(),i=new r.Vector3;for(let r=0,s=n.count;r<s;r++)i.fromBufferAttribute(n,r),0===i.x&&0===i.y&&0===i.z?i.setX(1):i.normalize(),n.setXYZ(r,i.x,i.y,i.z);return t.attributesNormalized.set(e,n),n}applyTextureTransform(e,t){let n=!1;const r={};0===t.offset.x&&0===t.offset.y||(r.offset=t.offset.toArray(),n=!0),0!==t.rotation&&(r.rotation=t.rotation,n=!0),1===t.repeat.x&&1===t.repeat.y||(r.scale=t.repeat.toArray(),n=!0),n&&(e.extensions=e.extensions||{},e.extensions.KHR_texture_transform=r,this.extensionsUsed.KHR_texture_transform=!0)}async buildMetalRoughTextureAsync(e,t){if(e===t)return e;function n(e){return e.colorSpace===r.SRGBColorSpace?function(e){return e<.04045?.0773993808*e:Math.pow(.9478672986*e+.0521327014,2.4)}:function(e){return e}}e instanceof r.CompressedTexture&&(e=await this.decompressTextureAsync(e)),t instanceof r.CompressedTexture&&(t=await this.decompressTextureAsync(t));const i=e?e.image:null,s=t?t.image:null,a=Math.max(i?i.width:0,s?s.width:0),o=Math.max(i?i.height:0,s?s.height:0),l=O();l.width=a,l.height=o;const c=l.getContext("2d",{willReadFrequently:!0});c.fillStyle="#00ffff",c.fillRect(0,0,a,o);const u=c.getImageData(0,0,a,o);if(i){c.drawImage(i,0,0,a,o);const t=n(e),r=c.getImageData(0,0,a,o).data;for(let e=2;e<r.length;e+=4)u.data[e]=256*t(r[e]/256)}if(s){c.drawImage(s,0,0,a,o);const e=n(t),r=c.getImageData(0,0,a,o).data;for(let t=1;t<r.length;t+=4)u.data[t]=256*e(r[t]/256)}c.putImageData(u,0,0);const h=(e||t).clone();return h.source=new r.Source(l),h.colorSpace=r.NoColorSpace,h.channel=(e||t).channel,e&&t&&(e.channel,t.channel),h}async buildNormalMapTextureAsync(e,t,n){e instanceof r.CompressedTexture&&(e=await this.decompressTextureAsync(e));const i=e.image,s=O();s.width=i.width,s.height=i.height;const a=s.getContext("2d",{willReadFrequently:!0});a.drawImage(i,0,0,s.width,s.height);const o=a.getImageData(0,0,s.width,s.height),l=o.data;for(let r=0;r<l.length;r+=4)t&&(l[r+0]=255-l[r+0]),n&&(l[r+1]=255-l[r+1]);a.putImageData(o,0,0);const c=e.clone();return c.source=new r.Source(s),c}async decompressTextureAsync(e,t=1/0){if(null===this.textureUtils)throw new Error("THREE.GLTFExporter: setTextureUtils() must be called to process compressed textures.");return await this.textureUtils.decompress(e,t)}processBuffer(e){const t=this.json,n=this.buffers;return t.buffers||(t.buffers=[{byteLength:0}]),n.push(e),0}processBufferView(e,t,n,i,s){const a=this.json;let o;switch(a.bufferViews||(a.bufferViews=[]),t){case f:case g:o=1;break;case x:case y:o=2;break;default:o=4}let l=e.itemSize*o;s===T&&(l=4*Math.ceil(l/4));const c=B(i*l),u=new DataView(new ArrayBuffer(c));let h=0;for(let p=n;p<n+i;p++){for(let n=0;n<e.itemSize;n++){let i;e.itemSize>4?i=e.array[p*e.itemSize+n]:(0===n?i=e.getX(p):1===n?i=e.getY(p):2===n?i=e.getZ(p):3===n&&(i=e.getW(p)),!0===e.normalized&&(i=r.MathUtils.normalize(i,e.array))),t===w?u.setFloat32(h,i,!0):t===v?u.setInt32(h,i,!0):t===b?u.setUint32(h,i,!0):t===x?u.setInt16(h,i,!0):t===y?u.setUint16(h,i,!0):t===f?u.setInt8(h,i):t===g&&u.setUint8(h,i),h+=o}h%l!=0&&(h+=l-h%l)}const d={buffer:this.processBuffer(u.buffer),byteOffset:this.byteOffset,byteLength:c};void 0!==s&&(d.target=s),s===T&&(d.byteStride=l),this.byteOffset+=c,a.bufferViews.push(d);return{id:a.bufferViews.length-1,byteLength:0}}processBufferViewImage(e){const t=this,n=t.json;return n.bufferViews||(n.bufferViews=[]),new Promise((function(r){const i=new FileReader;i.readAsArrayBuffer(e),i.onloadend=function(){const e=V(i.result),s={buffer:t.processBuffer(e),byteOffset:t.byteOffset,byteLength:e.byteLength};t.byteOffset+=e.byteLength,r(n.bufferViews.push(s)-1)}}))}processAccessor(e,t,n,i){const s=this.json;let a;if(e.array.constructor===Float32Array)a=w;else if(e.array.constructor===Int32Array)a=v;else if(e.array.constructor===Uint32Array)a=b;else if(e.array.constructor===Int16Array)a=x;else if(e.array.constructor===Uint16Array)a=y;else if(e.array.constructor===Int8Array)a=f;else{if(e.array.constructor!==Uint8Array)throw new Error("THREE.GLTFExporter: Unsupported bufferAttribute component type: "+e.array.constructor.name);a=g}if(void 0===n&&(n=0),void 0!==i&&i!==1/0||(i=e.count),0===i)return null;const o=function(e,t,n){const i={min:new Array(e.itemSize).fill(Number.POSITIVE_INFINITY),max:new Array(e.itemSize).fill(Number.NEGATIVE_INFINITY)};for(let s=t;s<t+n;s++)for(let t=0;t<e.itemSize;t++){let n;e.itemSize>4?n=e.array[s*e.itemSize+t]:(0===t?n=e.getX(s):1===t?n=e.getY(s):2===t?n=e.getZ(s):3===t&&(n=e.getW(s)),!0===e.normalized&&(n=r.MathUtils.normalize(n,e.array))),i.min[t]=Math.min(i.min[t],n),i.max[t]=Math.max(i.max[t],n)}return i}(e,n,i);let l;void 0!==t&&(l=e===t.index?S:T);const c=this.processBufferView(e,a,n,i,l),u={bufferView:c.id,byteOffset:c.byteOffset,componentType:a,count:i,max:o.max,min:o.min,type:{1:"SCALAR",2:"VEC2",3:"VEC3",4:"VEC4",9:"MAT3",16:"MAT4"}[e.itemSize]};return!0===e.normalized&&(u.normalized=!0),s.accessors||(s.accessors=[]),s.accessors.push(u)-1}processImage(e,t,n,i="image/png"){if(null!==e){const t=this,s=t.cache,a=t.json,o=t.options,l=t.pending;s.images.has(e)||s.images.set(e,{});const c=s.images.get(e),u=i+":flipY/"+n.toString();if(void 0!==c[u])return c[u];a.images||(a.images=[]);const h={mimeType:i},d=O();d.width=Math.min(e.width,o.maxTextureSize),d.height=Math.min(e.height,o.maxTextureSize);const p=d.getContext("2d",{willReadFrequently:!0});if(!0===n&&(p.translate(0,d.height),p.scale(1,-1)),void 0!==e.data){r.RGBAFormat,e.width>o.maxTextureSize||(e.height,o.maxTextureSize);const t=new Uint8ClampedArray(e.height*e.width*4);for(let n=0;n<t.length;n+=4)t[n+0]=e.data[n+0],t[n+1]=e.data[n+1],t[n+2]=e.data[n+2],t[n+3]=e.data[n+3];p.putImageData(new ImageData(t,e.width,e.height),0,0)}else{if(!("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap||"undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas))throw new Error("THREE.GLTFExporter: Invalid image type. Use HTMLImageElement, HTMLCanvasElement, ImageBitmap or OffscreenCanvas.");p.drawImage(e,0,0,d.width,d.height)}!0===o.binary?l.push(function(e,t){if("undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas){let n;return"image/jpeg"===t?n=.92:"image/webp"===t&&(n=.8),e.convertToBlob({type:t,quality:n})}return new Promise((n=>e.toBlob(n,t)))}(d,i).then((e=>t.processBufferViewImage(e))).then((e=>{h.bufferView=e}))):h.uri=r.ImageUtils.getDataURL(d,i);const m=a.images.push(h)-1;return c[u]=m,m}throw new Error("THREE.GLTFExporter: No valid image data found. Unable to process texture.")}processSampler(e){const t=this.json;t.samplers||(t.samplers=[]);const n={magFilter:L[e.magFilter],minFilter:L[e.minFilter],wrapS:L[e.wrapS],wrapT:L[e.wrapT]};return t.samplers.push(n)-1}async processTextureAsync(e){const t=this.options,n=this.cache,i=this.json;if(n.textures.has(e))return n.textures.get(e);i.textures||(i.textures=[]),e instanceof r.CompressedTexture&&(e=await this.decompressTextureAsync(e,t.maxTextureSize));const s=e.userData.mimeType,a=this.processImage(e.image,e.format,e.flipY,s),o={sampler:this.processSampler(e)};"image/webp"===s?(o.extensions=o.extensions||{},o.extensions.EXT_texture_webp={source:a},this.extensionsUsed.EXT_texture_webp=!0,this.extensionsRequired.EXT_texture_webp=!0):o.source=a,e.name&&(o.name=e.name),await this._invokeAllAsync((async function(t){t.writeTexture&&await t.writeTexture(e,o)}));const l=i.textures.push(o)-1;return n.textures.set(e,l),l}async processMaterialAsync(e,t){const n=this.cache,i=this.json,s=void 0!==t&&t.hasAttribute("tangent"),a=e.normalMap?e.uuid+":"+s:e.uuid;if(n.materials.has(a))return n.materials.get(a);if(e.isShaderMaterial)return null;i.materials||(i.materials=[]);const o={pbrMetallicRoughness:{}};!0!==e.isMeshStandardMaterial&&e.isMeshBasicMaterial;const l=e.color.toArray().concat([e.opacity]);if(z(l,[1,1,1,1])||(o.pbrMetallicRoughness.baseColorFactor=l),e.isMeshStandardMaterial?(o.pbrMetallicRoughness.metallicFactor=e.metalness,o.pbrMetallicRoughness.roughnessFactor=e.roughness):(o.pbrMetallicRoughness.metallicFactor=0,o.pbrMetallicRoughness.roughnessFactor=1),e.metalnessMap||e.roughnessMap){const t=await this.buildMetalRoughTextureAsync(e.metalnessMap,e.roughnessMap),n={index:await this.processTextureAsync(t),texCoord:t.channel};this.applyTextureTransform(n,t),o.pbrMetallicRoughness.metallicRoughnessTexture=n}if(e.map){const t={index:await this.processTextureAsync(e.map),texCoord:e.map.channel};this.applyTextureTransform(t,e.map),o.pbrMetallicRoughness.baseColorTexture=t}if(e.emissive){const t=e.emissive;if(Math.max(t.r,t.g,t.b)>0&&(o.emissiveFactor=e.emissive.toArray()),e.emissiveMap){const t={index:await this.processTextureAsync(e.emissiveMap),texCoord:e.emissiveMap.channel};this.applyTextureTransform(t,e.emissiveMap),o.emissiveTexture=t}}if(e.normalMap){const t=e.normalScale,n=t.x<0,r=s?t.y<0:t.y>0;let i=e.normalMap;(n||r)&&(i=await this.buildNormalMapTextureAsync(e.normalMap,n,r));const a={index:await this.processTextureAsync(i),texCoord:e.normalMap.channel};1!==Math.abs(t.x)&&(a.scale=Math.abs(t.x)),this.applyTextureTransform(a,e.normalMap),o.normalTexture=a}if(e.aoMap){const t={index:await this.processTextureAsync(e.aoMap),texCoord:e.aoMap.channel};1!==e.aoMapIntensity&&(t.strength=e.aoMapIntensity),this.applyTextureTransform(t,e.aoMap),o.occlusionTexture=t}e.transparent?o.alphaMode="BLEND":e.alphaTest>0&&(o.alphaMode="MASK",o.alphaCutoff=e.alphaTest),e.side===r.DoubleSide&&(o.doubleSided=!0),""!==e.name&&(o.name=e.name),this.serializeUserData(e,o),await this._invokeAllAsync((async function(t){t.writeMaterialAsync&&await t.writeMaterialAsync(e,o)}));const c=i.materials.push(o)-1;return n.materials.set(a,c),c}async processMeshAsync(e){const t=this.cache,n=this.json,r=[e.geometry.uuid];if(Array.isArray(e.material))for(let c=0,u=e.material.length;c<u;c++)r.push(e.material[c].uuid);else r.push(e.material.uuid);const i=r.join(":");if(t.meshes.has(i))return t.meshes.get(i);const s=e.geometry;let a;a=e.isLineSegments?h:e.isLineLoop?d:e.isLine?p:e.isPoints?u:e.material.wireframe?h:m;const o={},l={},f=[],g=[],x={uv:"TEXCOORD_0",uv1:"TEXCOORD_1",uv2:"TEXCOORD_2",uv3:"TEXCOORD_3",color:"COLOR_0",skinWeight:"WEIGHTS_0",skinIndex:"JOINTS_0"},y=s.getAttribute("normal");void 0===y||this.isNormalizedNormalAttribute(y)||s.setAttribute("normal",this.createNormalizedNormalAttribute(y));let v=null;for(let u in s.attributes){if("morph"===u.slice(0,5))continue;const e=s.attributes[u];u=x[u]||u.toUpperCase();if(/^(POSITION|NORMAL|TANGENT|TEXCOORD_\d+|COLOR_\d+|JOINTS_\d+|WEIGHTS_\d+)$/.test(u)||u.startsWith("_")||(u="_"+u),t.attributes.has(this.getUID(e))){l[u]=t.attributes.get(this.getUID(e));continue}v=null;const n=e.array;"JOINTS_0"!==u||n instanceof Uint16Array||n instanceof Uint8Array?(n instanceof Uint32Array||n instanceof Int32Array)&&!u.startsWith("_")&&(v=c.Utils.toTypedBufferAttribute(e,Float32Array)):v=c.Utils.toTypedBufferAttribute(e,Uint16Array);const r=this.processAccessor(v||e,s);null!==r&&(u.startsWith("_")||this.detectMeshQuantization(u,e),l[u]=r,t.attributes.set(this.getUID(e),r))}if(void 0!==y&&s.setAttribute("normal",y),0===Object.keys(l).length)return null;if(void 0!==e.morphTargetInfluences&&e.morphTargetInfluences.length>0){const n=[],r=[],i={};if(void 0!==e.morphTargetDictionary)for(const t in e.morphTargetDictionary)i[e.morphTargetDictionary[t]]=t;for(let a=0;a<e.morphTargetInfluences.length;++a){const o={};let l=!1;for(const e in s.morphAttributes){if("position"!==e&&"normal"!==e){l||(l=!0);continue}const n=s.morphAttributes[e][a],r=e.toUpperCase(),i=s.attributes[e];if(t.attributes.has(this.getUID(n,!0))){o[r]=t.attributes.get(this.getUID(n,!0));continue}const c=n.clone();if(!s.morphTargetsRelative)for(let e=0,t=n.count;e<t;e++)for(let r=0;r<n.itemSize;r++)0===r&&c.setX(e,n.getX(e)-i.getX(e)),1===r&&c.setY(e,n.getY(e)-i.getY(e)),2===r&&c.setZ(e,n.getZ(e)-i.getZ(e)),3===r&&c.setW(e,n.getW(e)-i.getW(e));o[r]=this.processAccessor(c,s),t.attributes.set(this.getUID(i,!0),o[r])}g.push(o),n.push(e.morphTargetInfluences[a]),void 0!==e.morphTargetDictionary&&r.push(i[a])}o.weights=n,r.length>0&&(o.extras={},o.extras.targetNames=r)}const b=Array.isArray(e.material);if(b&&0===s.groups.length)return null;let w=!1;if(b&&null===s.index){const e=[];for(let t=0,n=s.attributes.position.count;t<n;t++)e[t]=t;s.setIndex(e),w=!0}const T=b?e.material:[e.material],S=b?s.groups:[{materialIndex:0,start:void 0,count:void 0}];for(let c=0,u=S.length;c<u;c++){const e={mode:a,attributes:l};if(this.serializeUserData(s,e),g.length>0&&(e.targets=g),null!==s.index){let n=this.getUID(s.index);void 0===S[c].start&&void 0===S[c].count||(n+=":"+S[c].start+":"+S[c].count),t.attributes.has(n)?e.indices=t.attributes.get(n):(e.indices=this.processAccessor(s.index,s,S[c].start,S[c].count),t.attributes.set(n,e.indices)),null===e.indices&&delete e.indices}const n=await this.processMaterialAsync(T[S[c].materialIndex],s);null!==n&&(e.material=n),f.push(e)}!0===w&&s.setIndex(null),o.primitives=f,n.meshes||(n.meshes=[]),await this._invokeAllAsync((function(t){t.writeMesh&&t.writeMesh(e,o)}));const _=n.meshes.push(o)-1;return t.meshes.set(i,_),_}detectMeshQuantization(e,t){if(this.extensionsUsed[P])return;let n;switch(t.array.constructor){case Int8Array:n="byte";break;case Uint8Array:n="unsigned byte";break;case Int16Array:n="short";break;case Uint16Array:n="unsigned short";break;default:return}t.normalized&&(n+=" normalized");const r=e.split("_",1)[0];l[r]&&l[r].includes(n)&&(this.extensionsUsed[P]=!0,this.extensionsRequired[P]=!0)}processCamera(e){const t=this.json;t.cameras||(t.cameras=[]);const n=e.isOrthographicCamera,i={type:n?"orthographic":"perspective"};return n?i.orthographic={xmag:2*e.right,ymag:2*e.top,zfar:e.far<=0?.001:e.far,znear:e.near<0?0:e.near}:i.perspective={aspectRatio:e.aspect,yfov:r.MathUtils.degToRad(e.fov),zfar:e.far<=0?.001:e.far,znear:e.near<0?0:e.near},""!==e.name&&(i.name=e.type),t.cameras.push(i)-1}processAnimation(e,t){const n=this.json,i=this.nodeMap;n.animations||(n.animations=[]);const s=(e=c.Utils.mergeMorphTargetTracks(e.clone(),t)).tracks,a=[],o=[];for(let c=0;c<s.length;++c){const e=s[c],n=r.PropertyBinding.parseTrackName(e.name);let l=r.PropertyBinding.findNode(t,n.nodeName);const u=U[n.propertyName];if("bones"===n.objectName&&(l=!0===l.isSkinnedMesh?l.skeleton.getBoneByName(n.objectIndex):void 0),!l||!u)continue;const h=1;let d,p=e.values.length/e.times.length;u===U.morphTargetInfluences&&(p/=l.morphTargetInfluences.length),!0===e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline?(d="CUBICSPLINE",p/=3):d=e.getInterpolation()===r.InterpolateDiscrete?"STEP":"LINEAR",o.push({input:this.processAccessor(new r.BufferAttribute(e.times,h)),output:this.processAccessor(new r.BufferAttribute(e.values,p)),interpolation:d}),a.push({sampler:o.length-1,target:{node:i.get(l),path:u}})}const l={name:e.name||"clip_"+n.animations.length,samplers:o,channels:a};return this.serializeUserData(e,l),n.animations.push(l),n.animations.length-1}processSkin(e){const t=this.json,n=this.nodeMap,i=t.nodes[n.get(e)],s=e.skeleton;if(void 0===s)return null;const a=e.skeleton.bones[0];if(void 0===a)return null;const o=[],l=new Float32Array(16*s.bones.length),c=new r.Matrix4;for(let r=0;r<s.bones.length;++r)o.push(n.get(s.bones[r])),c.copy(s.boneInverses[r]),c.multiply(e.bindMatrix).toArray(l,16*r);void 0===t.skins&&(t.skins=[]),t.skins.push({inverseBindMatrices:this.processAccessor(new r.BufferAttribute(l,16)),joints:o,skeleton:n.get(a)});return i.skin=t.skins.length-1}async processNodeAsync(e){const t=this.json,n=this.options,r=this.nodeMap;if(t.nodes||(t.nodes=[]),null!==e.pivot)return await this._processNodeWithPivotAsync(e);const i={};if(n.trs){const t=e.quaternion.toArray(),n=e.position.toArray(),r=e.scale.toArray();z(t,[0,0,0,1])||(i.rotation=t),z(n,[0,0,0])||(i.translation=n),z(r,[1,1,1])||(i.scale=r)}else e.matrixAutoUpdate&&e.updateMatrix(),!1===z(e.matrix.elements,[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1])&&(i.matrix=e.matrix.elements);if(""!==e.name&&(i.name=String(e.name)),this.serializeUserData(e,i),e.isMesh||e.isLine||e.isPoints){const t=await this.processMeshAsync(e);null!==t&&(i.mesh=t)}else e.isCamera&&(i.camera=this.processCamera(e));e.isSkinnedMesh&&this.skins.push(e);const s=t.nodes.push(i)-1;if(r.set(e,s),e.children.length>0){const t=[];for(let r=0,i=e.children.length;r<i;r++){const i=e.children[r];if(i.visible||!1===n.onlyVisible){const e=await this.processNodeAsync(i);null!==e&&t.push(e)}}t.length>0&&(i.children=t)}return await this._invokeAllAsync((function(t){t.writeNode&&t.writeNode(e,i)})),s}async _processNodeWithPivotAsync(e){const t=this.json,n=this.options,r=this.nodeMap,i=e.pivot,s={},a=e.quaternion.toArray(),o=[e.position.x+i.x,e.position.y+i.y,e.position.z+i.z],l=e.scale.toArray();z(a,[0,0,0,1])||(s.rotation=a),z(o,[0,0,0])||(s.translation=o),z(l,[1,1,1])||(s.scale=l),s.extras={pivot:i.toArray()},""!==e.name&&(s.name=String(e.name)),this.serializeUserData(e,s);const c=t.nodes.push(s)-1;r.set(e,c);const u={},h=[-i.x,-i.y,-i.z];if(z(h,[0,0,0])||(u.translation=h),e.isMesh||e.isLine||e.isPoints){const t=await this.processMeshAsync(e);null!==t&&(u.mesh=t)}else e.isCamera&&(u.camera=this.processCamera(e));e.isSkinnedMesh&&this.skins.push(e);const d=[t.nodes.push(u)-1];if(e.children.length>0){const t=[];for(let r=0,i=e.children.length;r<i;r++){const i=e.children[r];if(i.visible||!1===n.onlyVisible){const e=await this.processNodeAsync(i);null!==e&&t.push(e)}}t.length>0&&(u.children=t)}return s.children=d,await this._invokeAllAsync((function(t){t.writeNode&&t.writeNode(e,s)})),c}async processSceneAsync(e){const t=this.json,n=this.options;t.scenes||(t.scenes=[],t.scene=0);const r={};""!==e.name&&(r.name=e.name),t.scenes.push(r);const i=[];for(let s=0,a=e.children.length;s<a;s++){const t=e.children[s];if(t.visible||!1===n.onlyVisible){const e=await this.processNodeAsync(t);null!==e&&i.push(e)}}i.length>0&&(r.nodes=i),this.serializeUserData(e,r)}async processObjectsAsync(e){const t=new r.Scene;t.name="AuxScene";for(let n=0;n<e.length;n++)t.children.push(e[n]);await this.processSceneAsync(t)}async processInputAsync(e){const t=this.options;e=e instanceof Array?e:[e],await this._invokeAllAsync((function(t){t.beforeParse&&t.beforeParse(e)}));const n=[];for(let i=0;i<e.length;i++)e[i]instanceof r.Scene?await this.processSceneAsync(e[i]):n.push(e[i]);n.length>0&&await this.processObjectsAsync(n);for(let r=0;r<this.skins.length;++r)this.processSkin(this.skins[r]);if(1===e.length)for(let r=0;r<t.animations.length;++r)this.processAnimation(t.animations[r],e[0]);else for(let r=0;r<e.length;r++){const n=t.animations[r]||[];for(let t=0;t<n.length;++t)this.processAnimation(n[t],e[r])}await this._invokeAllAsync((function(t){t.afterParse&&t.afterParse(e)}))}async _invokeAllAsync(e){for(let t=0,n=this.plugins.length;t<n;t++)await e(this.plugins[t])}}class ${constructor(e){this.writer=e,this.name="KHR_lights_punctual"}writeNode(e,t){if(!e.isLight)return;if(!e.isDirectionalLight&&!e.isPointLight&&!e.isSpotLight)return;const n=this.writer,r=n.json,i=n.extensionsUsed,s={};e.name&&(s.name=e.name),s.color=e.color.toArray(),s.intensity=e.intensity,e.isDirectionalLight?s.type="directional":e.isPointLight?(s.type="point",e.distance>0&&(s.range=e.distance)):e.isSpotLight&&(s.type="spot",e.distance>0&&(s.range=e.distance),s.spot={},s.spot.innerConeAngle=(1-e.penumbra)*e.angle,s.spot.outerConeAngle=e.angle),void 0!==e.decay&&e.decay,e.target&&(e.target.parent!==e||0!==e.target.position.x||0!==e.target.position.y||e.target.position.z),i[this.name]||(r.extensions=r.extensions||{},r.extensions[this.name]={lights:[]},i[this.name]=!0);const a=r.extensions[this.name].lights;a.push(s),t.extensions=t.extensions||{},t.extensions[this.name]={light:a.length-1}}}let G=class{constructor(e){this.writer=e,this.name="KHR_materials_unlit"}async writeMaterialAsync(e,t){if(!e.isMeshBasicMaterial)return;const n=this.writer.extensionsUsed;t.extensions=t.extensions||{},t.extensions[this.name]={},n[this.name]=!0,t.pbrMetallicRoughness.metallicFactor=0,t.pbrMetallicRoughness.roughnessFactor=.9}},q=class{constructor(e){this.writer=e,this.name="KHR_materials_clearcoat"}async writeMaterialAsync(e,t){if(!e.isMeshPhysicalMaterial||0===e.clearcoat)return;const n=this.writer,r=n.extensionsUsed,i={};if(i.clearcoatFactor=e.clearcoat,e.clearcoatMap){const t={index:await n.processTextureAsync(e.clearcoatMap),texCoord:e.clearcoatMap.channel};n.applyTextureTransform(t,e.clearcoatMap),i.clearcoatTexture=t}if(i.clearcoatRoughnessFactor=e.clearcoatRoughness,e.clearcoatRoughnessMap){const t={index:await n.processTextureAsync(e.clearcoatRoughnessMap),texCoord:e.clearcoatRoughnessMap.channel};n.applyTextureTransform(t,e.clearcoatRoughnessMap),i.clearcoatRoughnessTexture=t}if(e.clearcoatNormalMap){const t={index:await n.processTextureAsync(e.clearcoatNormalMap),texCoord:e.clearcoatNormalMap.channel};1!==e.clearcoatNormalScale.x&&(t.scale=e.clearcoatNormalScale.x),n.applyTextureTransform(t,e.clearcoatNormalMap),i.clearcoatNormalTexture=t}t.extensions=t.extensions||{},t.extensions[this.name]=i,r[this.name]=!0}},H=class{constructor(e){this.writer=e,this.name="KHR_materials_dispersion"}async writeMaterialAsync(e,t){if(!e.isMeshPhysicalMaterial||0===e.dispersion)return;const n=this.writer.extensionsUsed,r={};r.dispersion=e.dispersion,t.extensions=t.extensions||{},t.extensions[this.name]=r,n[this.name]=!0}},j=class{constructor(e){this.writer=e,this.name="KHR_materials_iridescence"}async writeMaterialAsync(e,t){if(!e.isMeshPhysicalMaterial||0===e.iridescence)return;const n=this.writer,r=n.extensionsUsed,i={};if(i.iridescenceFactor=e.iridescence,e.iridescenceMap){const t={index:await n.processTextureAsync(e.iridescenceMap),texCoord:e.iridescenceMap.channel};n.applyTextureTransform(t,e.iridescenceMap),i.iridescenceTexture=t}if(i.iridescenceIor=e.iridescenceIOR,i.iridescenceThicknessMinimum=e.iridescenceThicknessRange[0],i.iridescenceThicknessMaximum=e.iridescenceThicknessRange[1],e.iridescenceThicknessMap){const t={index:await n.processTextureAsync(e.iridescenceThicknessMap),texCoord:e.iridescenceThicknessMap.channel};n.applyTextureTransform(t,e.iridescenceThicknessMap),i.iridescenceThicknessTexture=t}t.extensions=t.extensions||{},t.extensions[this.name]=i,r[this.name]=!0}},W=class{constructor(e){this.writer=e,this.name="KHR_materials_transmission"}async writeMaterialAsync(e,t){if(!e.isMeshPhysicalMaterial||0===e.transmission)return;const n=this.writer,r=n.extensionsUsed,i={};if(i.transmissionFactor=e.transmission,e.transmissionMap){const t={index:await n.processTextureAsync(e.transmissionMap),texCoord:e.transmissionMap.channel};n.applyTextureTransform(t,e.transmissionMap),i.transmissionTexture=t}t.extensions=t.extensions||{},t.extensions[this.name]=i,r[this.name]=!0}},X=class{constructor(e){this.writer=e,this.name="KHR_materials_volume"}async writeMaterialAsync(e,t){if(!e.isMeshPhysicalMaterial||0===e.transmission)return;const n=this.writer,r=n.extensionsUsed,i={};if(i.thicknessFactor=e.thickness,e.thicknessMap){const t={index:await n.processTextureAsync(e.thicknessMap),texCoord:e.thicknessMap.channel};n.applyTextureTransform(t,e.thicknessMap),i.thicknessTexture=t}e.attenuationDistance!==1/0&&(i.attenuationDistance=e.attenuationDistance),i.attenuationColor=e.attenuationColor.toArray(),t.extensions=t.extensions||{},t.extensions[this.name]=i,r[this.name]=!0}},Y=class{constructor(e){this.writer=e,this.name="KHR_materials_ior"}async writeMaterialAsync(e,t){if(!e.isMeshPhysicalMaterial||1.5===e.ior)return;const n=this.writer.extensionsUsed,r={};r.ior=e.ior,t.extensions=t.extensions||{},t.extensions[this.name]=r,n[this.name]=!0}},K=class{constructor(e){this.writer=e,this.name="KHR_materials_specular"}async writeMaterialAsync(e,t){if(!e.isMeshPhysicalMaterial||1===e.specularIntensity&&e.specularColor.equals(F)&&!e.specularIntensityMap&&!e.specularColorMap)return;const n=this.writer,r=n.extensionsUsed,i={};if(e.specularIntensityMap){const t={index:await n.processTextureAsync(e.specularIntensityMap),texCoord:e.specularIntensityMap.channel};n.applyTextureTransform(t,e.specularIntensityMap),i.specularTexture=t}if(e.specularColorMap){const t={index:await n.processTextureAsync(e.specularColorMap),texCoord:e.specularColorMap.channel};n.applyTextureTransform(t,e.specularColorMap),i.specularColorTexture=t}i.specularFactor=e.specularIntensity,i.specularColorFactor=e.specularColor.toArray(),t.extensions=t.extensions||{},t.extensions[this.name]=i,r[this.name]=!0}},Q=class{constructor(e){this.writer=e,this.name="KHR_materials_sheen"}async writeMaterialAsync(e,t){if(!e.isMeshPhysicalMaterial||0==e.sheen)return;const n=this.writer,r=n.extensionsUsed,i={};if(e.sheenRoughnessMap){const t={index:await n.processTextureAsync(e.sheenRoughnessMap),texCoord:e.sheenRoughnessMap.channel};n.applyTextureTransform(t,e.sheenRoughnessMap),i.sheenRoughnessTexture=t}if(e.sheenColorMap){const t={index:await n.processTextureAsync(e.sheenColorMap),texCoord:e.sheenColorMap.channel};n.applyTextureTransform(t,e.sheenColorMap),i.sheenColorTexture=t}i.sheenRoughnessFactor=e.sheenRoughness,i.sheenColorFactor=e.sheenColor.toArray(),t.extensions=t.extensions||{},t.extensions[this.name]=i,r[this.name]=!0}},Z=class{constructor(e){this.writer=e,this.name="KHR_materials_anisotropy"}async writeMaterialAsync(e,t){if(!e.isMeshPhysicalMaterial||0==e.anisotropy)return;const n=this.writer,r=n.extensionsUsed,i={};if(e.anisotropyMap){const t={index:await n.processTextureAsync(e.anisotropyMap)};n.applyTextureTransform(t,e.anisotropyMap),i.anisotropyTexture=t}i.anisotropyStrength=e.anisotropy,i.anisotropyRotation=e.anisotropyRotation,t.extensions=t.extensions||{},t.extensions[this.name]=i,r[this.name]=!0}},J=class{constructor(e){this.writer=e,this.name="KHR_materials_emissive_strength"}async writeMaterialAsync(e,t){if(!e.isMeshStandardMaterial||1===e.emissiveIntensity)return;const n=this.writer.extensionsUsed,r={};r.emissiveStrength=e.emissiveIntensity,t.extensions=t.extensions||{},t.extensions[this.name]=r,n[this.name]=!0}},ee=class{constructor(e){this.writer=e,this.name="EXT_materials_bump"}async writeMaterialAsync(e,t){if(!e.isMeshStandardMaterial||1===e.bumpScale&&!e.bumpMap)return;const n=this.writer,r=n.extensionsUsed,i={};if(e.bumpMap){const t={index:await n.processTextureAsync(e.bumpMap),texCoord:e.bumpMap.channel};n.applyTextureTransform(t,e.bumpMap),i.bumpTexture=t}i.bumpFactor=e.bumpScale,t.extensions=t.extensions||{},t.extensions[this.name]=i,r[this.name]=!0}},te=class{constructor(e){this.writer=e,this.name="EXT_mesh_gpu_instancing"}writeNode(e,t){if(!e.isInstancedMesh)return;const n=this.writer,i=e,s=new Float32Array(3*i.count),a=new Float32Array(4*i.count),o=new Float32Array(3*i.count),l=new r.Matrix4,c=new r.Vector3,u=new r.Quaternion,h=new r.Vector3;for(let r=0;r<i.count;r++)i.getMatrixAt(r,l),l.decompose(c,u,h),c.toArray(s,3*r),u.toArray(a,4*r),h.toArray(o,3*r);const d={TRANSLATION:n.processAccessor(new r.BufferAttribute(s,3)),ROTATION:n.processAccessor(new r.BufferAttribute(a,4)),SCALE:n.processAccessor(new r.BufferAttribute(o,3))};i.instanceColor&&(d._COLOR_0=n.processAccessor(i.instanceColor)),t.extensions=t.extensions||{},t.extensions[this.name]={attributes:d},n.extensionsUsed[this.name]=!0,n.extensionsRequired[this.name]=!0}};c.Utils={insertKeyframe:function(e,t){const n=.001,r=e.getValueSize(),i=new e.TimeBufferType(e.times.length+1),s=new e.ValueBufferType(e.values.length+r),a=e.createInterpolant(new e.ValueBufferType(r));let o;if(0===e.times.length){i[0]=t;for(let e=0;e<r;e++)s[e]=0;o=0}else if(t<e.times[0]){if(Math.abs(e.times[0]-t)<n)return 0;i[0]=t,i.set(e.times,1),s.set(a.evaluate(t),0),s.set(e.values,r),o=0}else if(t>e.times[e.times.length-1]){if(Math.abs(e.times[e.times.length-1]-t)<n)return e.times.length-1;i[i.length-1]=t,i.set(e.times,0),s.set(e.values,0),s.set(a.evaluate(t),e.values.length),o=i.length-1}else for(let l=0;l<e.times.length;l++){if(Math.abs(e.times[l]-t)<n)return l;if(e.times[l]<t&&e.times[l+1]>t){i.set(e.times.slice(0,l+1),0),i[l+1]=t,i.set(e.times.slice(l+1),l+2),s.set(e.values.slice(0,(l+1)*r),0),s.set(a.evaluate(t),(l+1)*r),s.set(e.values.slice((l+1)*r),(l+2)*r),o=l+1;break}}return e.times=i,e.values=s,o},mergeMorphTargetTracks:function(e,t){const n=[],i={},s=e.tracks;for(let a=0;a<s.length;++a){let e=s[a];const o=r.PropertyBinding.parseTrackName(e.name),l=r.PropertyBinding.findNode(t,o.nodeName);if("morphTargetInfluences"!==o.propertyName||void 0===o.propertyIndex){n.push(e);continue}if(e.createInterpolant!==e.InterpolantFactoryMethodDiscrete&&e.createInterpolant!==e.InterpolantFactoryMethodLinear){if(e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline)throw new Error("THREE.GLTFExporter: Cannot merge tracks with glTF CUBICSPLINE interpolation.");e=e.clone(),e.setInterpolation(r.InterpolateLinear)}const c=l.morphTargetInfluences.length,u=l.morphTargetDictionary[o.propertyIndex];if(void 0===u)throw new Error("THREE.GLTFExporter: Morph target name not found: "+o.propertyIndex);let h;if(void 0===i[l.uuid]){h=e.clone();const t=new h.ValueBufferType(c*h.times.length);for(let e=0;e<h.times.length;e++)t[e*c+u]=h.values[e];h.name=(o.nodeName||"")+".morphTargetInfluences",h.values=t,i[l.uuid]=h,n.push(h);continue}const d=e.createInterpolant(new e.ValueBufferType(1));h=i[l.uuid];for(let t=0;t<h.times.length;t++)h.values[t*c+u]=d.evaluate(h.times[t]);for(let t=0;t<e.times.length;t++){const n=this.insertKeyframe(h,e.times[t]);h.values[n*c+u]=e.values[t]}}return e.tracks=n,e},toTypedBufferAttribute:function(e,t){const n=new r.BufferAttribute(new t(e.count*e.itemSize),e.itemSize,!1);if(!e.normalized&&!e.isInterleavedBufferAttribute)return n.array.set(e.array),n;for(let r=0,i=e.count;r<i;r++)for(let t=0;t<e.itemSize;t++)n.setComponent(r,t,e.getComponent(r,t));return n}};const ne=9,re=15,ie=16,se=22,ae=37,oe=43,le=76,ce=83,ue=91,he=97,de=100,pe=103,me=109,fe=122,ge=123,xe=131,ye=132,ve=133,be=134,we=137,Te=138,Se=139,_e=140,Me=141,Ae=142,Ee=145,Ce=146,Re=148,De=152,ke=153,Ie=154,Pe=155,Le=156,Ue=157,Fe=158,ze=165,Be=166,Ve=1000054e3,Oe=1000054001,Ne=1000054004,$e=1000054005,Ge=1000066e3,qe=1000066004;class He{constructor(e,t,n,r){this._dataView=void 0,this._littleEndian=void 0,this._offset=void 0,this._dataView=new DataView(e.buffer,e.byteOffset+t,n),this._littleEndian=r,this._offset=0}_nextUint8(){const e=this._dataView.getUint8(this._offset);return this._offset+=1,e}_nextUint16(){const e=this._dataView.getUint16(this._offset,this._littleEndian);return this._offset+=2,e}_nextUint32(){const e=this._dataView.getUint32(this._offset,this._littleEndian);return this._offset+=4,e}_nextUint64(){const e=this._dataView.getUint32(this._offset,this._littleEndian)+2**32*this._dataView.getUint32(this._offset+4,this._littleEndian);return this._offset+=8,e}_nextInt32(){const e=this._dataView.getInt32(this._offset,this._littleEndian);return this._offset+=4,e}_nextUint8Array(e){const t=new Uint8Array(this._dataView.buffer,this._dataView.byteOffset+this._offset,e);return this._offset+=e,t}_skip(e){return this._offset+=e,this}_scan(e,t=0){const n=this._offset;let r=0;for(;this._dataView.getUint8(this._offset)!==t&&r<e;)r++,this._offset++;return r<e&&this._offset++,new Uint8Array(this._dataView.buffer,this._dataView.byteOffset+n,r)}}const je=[171,75,84,88,32,50,48,187,13,10,26,10];function We(e){return(new TextDecoder).decode(e)}function Xe(e,t){if(t===r.TrianglesDrawMode)return e;if(t===r.TriangleFanDrawMode||t===r.TriangleStripDrawMode){let n=e.getIndex();if(null===n){const t=[],r=e.getAttribute("position");if(void 0===r)return e;for(let e=0;e<r.count;e++)t.push(e);e.setIndex(t),n=e.getIndex()}const i=n.count-2,s=[];if(t===r.TriangleFanDrawMode)for(let e=1;e<=i;e++)s.push(n.getX(0)),s.push(n.getX(e)),s.push(n.getX(e+1));else for(let e=0;e<i;e++)e%2==0?(s.push(n.getX(e)),s.push(n.getX(e+1)),s.push(n.getX(e+2))):(s.push(n.getX(e+2)),s.push(n.getX(e+1)),s.push(n.getX(e)));s.length;const a=e.clone();return a.setIndex(s),a.clearGroups(),a}return e}const Ye=new WeakMap,Ke="undefined"==typeof document?require("url").pathToFileURL(__dirname+"/assets/viewer/draco-decoder-c55a594e8ffd.wasm").href:new URL("assets/viewer/draco-decoder-c55a594e8ffd.wasm",document.currentScript&&"SCRIPT"===document.currentScript.tagName.toUpperCase()&&document.currentScript.src||document.baseURI).href,Qe="undefined"==typeof document?require("url").pathToFileURL(__dirname+"/assets/viewer/draco-wasm-wrapper-e8049906ef3f.js").href:new URL("assets/viewer/draco-wasm-wrapper-e8049906ef3f.js",document.currentScript&&"SCRIPT"===document.currentScript.tagName.toUpperCase()&&document.currentScript.src||document.baseURI).href,Ze="undefined"==typeof document?require("url").pathToFileURL(__dirname+"/assets/viewer/draco-decoder-30e4d486fa02.js").href:new URL("assets/viewer/draco-decoder-30e4d486fa02.js",document.currentScript&&"SCRIPT"===document.currentScript.tagName.toUpperCase()&&document.currentScript.src||document.baseURI).href;class Je extends r.Loader{constructor(e){super(e),this.decoderPaths={js:Qe,wasm:Ke,dep_js:Ze},this.decoderConfig={},this.decoderBinary=null,this.decoderPending=null,this.workerLimit=4,this.workerPool=[],this.workerNextTaskID=1,this.workerSourceURL="",this.defaultAttributeIDs={position:"POSITION",normal:"NORMAL",color:"COLOR",uv:"TEX_COORD"},this.defaultAttributeTypes={position:"Float32Array",normal:"Float32Array",color:"Float32Array",uv:"Float32Array"}}setDecoderPath(e){const{decoderPaths:t}=this;return"object"==typeof e?(t.js=e.js,t.wasm=e.wasm,t.dep_js=null):(t.js=r.LoaderUtils.resolveURL("draco_wasm_wrapper.js",e),t.wasm=r.LoaderUtils.resolveURL("draco_decoder.wasm",e),t.dep_js=r.LoaderUtils.resolveURL("draco_decoder.js",e)),this}setDecoderConfig(e){return this.decoderConfig=e,this}setWorkerLimit(e){return this.workerLimit=e,this}load(e,t,n,i){const s=new r.FileLoader(this.manager);s.setPath(this.path),s.setResponseType("arraybuffer"),s.setRequestHeader(this.requestHeader),s.setWithCredentials(this.withCredentials),s.load(e,(e=>{this.parse(e,t,i)}),n,i)}parse(e,t,n=()=>{}){this.decodeDracoFile(e,t,null,null,r.SRGBColorSpace,n).catch(n)}decodeDracoFile(e,t,n,i,s=r.LinearSRGBColorSpace,a=()=>{}){const o={attributeIDs:n||this.defaultAttributeIDs,attributeTypes:i||this.defaultAttributeTypes,useUniqueIDs:!!n,vertexColorSpace:s};return this.decodeGeometry(e,o).then(t).catch(a)}decodeGeometry(e,t){const n=JSON.stringify(t);if(Ye.has(e)){const t=Ye.get(e);if(t.key===n)return t.promise;if(0===e.byteLength)throw new Error("THREE.DRACOLoader: Unable to re-decode a buffer with different settings. Buffer has already been transferred.")}let r;const i=this.workerNextTaskID++,s=e.byteLength,a=this._getWorker(i,s).then((n=>(r=n,new Promise(((n,s)=>{r._callbacks[i]={resolve:n,reject:s},r.postMessage({type:"decode",id:i,taskConfig:t,buffer:e},[e])}))))).then((e=>this._createGeometry(e.geometry)));return a.catch((()=>!0)).then((()=>{r&&i&&this._releaseTask(r,i)})),Ye.set(e,{key:n,promise:a}),a}_createGeometry(e){const t=new r.BufferGeometry;e.index&&t.setIndex(new r.BufferAttribute(e.index.array,1));for(let n=0;n<e.attributes.length;n++){const{name:i,array:s,itemSize:a,stride:o,vertexColorSpace:l}=e.attributes[n];let c;if(a===o)c=new r.BufferAttribute(s,a);else{const e=new r.InterleavedBuffer(s,o);c=new r.InterleavedBufferAttribute(e,a,0)}"color"===i&&(this._assignVertexColorSpace(c,l),c.normalized=s instanceof Float32Array==!1),t.setAttribute(i,c)}return t}_assignVertexColorSpace(e,t){if(t!==r.SRGBColorSpace)return;const n=new r.Color;for(let i=0,s=e.count;i<s;i++)n.fromBufferAttribute(e,i),r.ColorManagement.colorSpaceToWorking(n,r.SRGBColorSpace),e.setXYZ(i,n.r,n.g,n.b)}_loadLibrary(e,t){const n=new r.FileLoader(this.manager);return n.setResponseType(t),n.setWithCredentials(this.withCredentials),new Promise(((t,r)=>{n.load(e,t,void 0,r)}))}preload(){return this._initDecoder(),this}_initDecoder(){if(this.decoderPending)return this.decoderPending;const e="object"!=typeof WebAssembly||"js"===this.decoderConfig.type,t=[],{decoderPaths:n}=this;if(e){if(null===n.dep_js)throw new Error("THREE.DRACOLoader: WebAssembly is required when using a custom decoder paths.");t.push(this._loadLibrary(n.dep_js,"text"))}else t.push(this._loadLibrary(n.js,"text")),t.push(this._loadLibrary(n.wasm,"arraybuffer"));return this.decoderPending=Promise.all(t).then((t=>{const n=t[0];e||(this.decoderConfig.wasmBinary=t[1]);const r=et.toString(),i=["/* draco decoder */",n,"","/* worker */",r.substring(r.indexOf("{")+1,r.lastIndexOf("}"))].join("\n");this.workerSourceURL=URL.createObjectURL(new Blob([i]))})),this.decoderPending}_getWorker(e,t){return this._initDecoder().then((()=>{if(this.workerPool.length<this.workerLimit){const e=new Worker(this.workerSourceURL);e._callbacks={},e._taskCosts={},e._taskLoad=0,e.postMessage({type:"init",decoderConfig:this.decoderConfig}),e.onmessage=function(t){const n=t.data;switch(n.type){case"decode":e._callbacks[n.id].resolve(n);break;case"error":e._callbacks[n.id].reject(n)}},this.workerPool.push(e)}else this.workerPool.sort((function(e,t){return e._taskLoad>t._taskLoad?-1:1}));const n=this.workerPool[this.workerPool.length-1];return n._taskCosts[e]=t,n._taskLoad+=t,n}))}_releaseTask(e,t){e._taskLoad-=e._taskCosts[t],delete e._callbacks[t],delete e._taskCosts[t]}debug(){}dispose(){for(let e=0;e<this.workerPool.length;++e)this.workerPool[e].terminate();return this.workerPool.length=0,""!==this.workerSourceURL&&URL.revokeObjectURL(this.workerSourceURL),this}}function et(){let e,t;function n(e,t,n,r,i,s){const a=n.num_points(),o=s.num_components(),l=function(e,t){switch(t){case Float32Array:return e.DT_FLOAT32;case Int8Array:return e.DT_INT8;case Int16Array:return e.DT_INT16;case Int32Array:return e.DT_INT32;case Uint8Array:return e.DT_UINT8;case Uint16Array:return e.DT_UINT16;case Uint32Array:return e.DT_UINT32}}(e,i),c=o*i.BYTES_PER_ELEMENT,u=4*Math.ceil(c/4),h=u/i.BYTES_PER_ELEMENT,d=a*c,p=a*u,m=e._malloc(d);t.GetAttributeDataArrayForAllPoints(n,s,l,d,m);const f=new i(e.HEAPF32.buffer,m,d/i.BYTES_PER_ELEMENT);let g;if(c===u)g=f.slice();else{g=new i(p/i.BYTES_PER_ELEMENT);let e=0;for(let t=0,n=f.length;t<n;t++){for(let n=0;n<o;n++)g[e+n]=f[t*o+n];e+=h}}return e._free(m),{name:r,count:a,itemSize:o,array:g,stride:h}}onmessage=function(r){const i=r.data;switch(i.type){case"init":e=i.decoderConfig,t=new Promise((function(t){e.onModuleLoaded=function(e){t({draco:e})},DracoDecoderModule(e)}));break;case"decode":const r=i.buffer,s=i.taskConfig;t.then((e=>{const t=e.draco,a=new t.Decoder;try{const e=function(e,t,r,i){const s=i.attributeIDs,a=i.attributeTypes;let o,l;const c=t.GetEncodedGeometryType(r);if(c===e.TRIANGULAR_MESH)o=new e.Mesh,l=t.DecodeArrayToMesh(r,r.byteLength,o);else{if(c!==e.POINT_CLOUD)throw new Error("THREE.DRACOLoader: Unexpected geometry type.");o=new e.PointCloud,l=t.DecodeArrayToPointCloud(r,r.byteLength,o)}if(!l.ok()||0===o.ptr)throw new Error("THREE.DRACOLoader: Decoding failed: "+l.error_msg());const u={index:null,attributes:[]};for(const h in s){const r=self[a[h]];let l,c;if(i.useUniqueIDs)c=s[h],l=t.GetAttributeByUniqueId(o,c);else{if(c=t.GetAttributeId(o,e[s[h]]),-1===c)continue;l=t.GetAttribute(o,c)}const d=n(e,t,o,h,r,l);"color"===h&&(d.vertexColorSpace=i.vertexColorSpace),u.attributes.push(d)}c===e.TRIANGULAR_MESH&&(u.index=function(e,t,n){const r=n.num_faces(),i=3*r,s=4*i,a=e._malloc(s);t.GetTrianglesUInt32Array(n,s,a);const o=new Uint32Array(e.HEAPF32.buffer,a,i).slice();return e._free(a),{array:o,itemSize:1}}(e,t,o));return e.destroy(o),u}(t,a,new Int8Array(r),s),o=e.attributes.map((e=>e.array.buffer));e.index&&o.push(e.index.array.buffer),self.postMessage({type:"decode",id:i.id,geometry:e},o)}catch(o){self.postMessage({type:"error",id:i.id,error:o.message})}finally{t.destroy(a)}}))}}}function tt(e){const t=new Map,n=new Map,r=e.clone();return nt(e,r,(function(e,r){t.set(r,e),n.set(e,r)})),r.traverse((function(e){if(!e.isSkinnedMesh)return;const r=e,i=t.get(e),s=i.skeleton.bones;r.skeleton=i.skeleton.clone(),r.bindMatrix.copy(i.bindMatrix),r.skeleton.bones=s.map((function(e){return n.get(e)})),r.bind(r.skeleton,r.bindMatrix)})),r}function nt(e,t,n){n(e,t);for(let r=0;r<e.children.length;r++)nt(e.children[r],t.children[r],n)}class rt extends r.Loader{constructor(e){super(e),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register((function(e){return new ut(e)})),this.register((function(e){return new ht(e)})),this.register((function(e){return new bt(e)})),this.register((function(e){return new wt(e)})),this.register((function(e){return new Tt(e)})),this.register((function(e){return new pt(e)})),this.register((function(e){return new mt(e)})),this.register((function(e){return new ft(e)})),this.register((function(e){return new gt(e)})),this.register((function(e){return new ct(e)})),this.register((function(e){return new xt(e)})),this.register((function(e){return new dt(e)})),this.register((function(e){return new vt(e)})),this.register((function(e){return new yt(e)})),this.register((function(e){return new ot(e)})),this.register((function(e){return new St(e,at.EXT_MESHOPT_COMPRESSION)})),this.register((function(e){return new St(e,at.KHR_MESHOPT_COMPRESSION)})),this.register((function(e){return new _t(e)}))}load(e,t,n,i){const s=this;let a;if(""!==this.resourcePath)a=this.resourcePath;else if(""!==this.path){const t=r.LoaderUtils.extractUrlBase(e);a=r.LoaderUtils.resolveURL(t,this.path)}else a=r.LoaderUtils.extractUrlBase(e);this.manager.itemStart(e);const o=function(t){i&&i(t),s.manager.itemError(e),s.manager.itemEnd(e)},l=new r.FileLoader(this.manager);l.setPath(this.path),l.setResponseType("arraybuffer"),l.setRequestHeader(this.requestHeader),l.setWithCredentials(this.withCredentials),l.load(e,(function(n){try{s.parse(n,a,(function(n){t(n),s.manager.itemEnd(e)}),o)}catch(r){o(r)}}),n,o)}setDRACOLoader(e){return this.dracoLoader=e,this}setKTX2Loader(e){return this.ktx2Loader=e,this}setMeshoptDecoder(e){return this.meshoptDecoder=e,this}register(e){return-1===this.pluginCallbacks.indexOf(e)&&this.pluginCallbacks.push(e),this}unregister(e){return-1!==this.pluginCallbacks.indexOf(e)&&this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(e),1),this}parse(e,t,n,r){let i;const s={},a={},o=new TextDecoder;if("string"==typeof e)i=JSON.parse(e);else if(e instanceof ArrayBuffer){if(o.decode(new Uint8Array(e,0,4))===Mt){try{s[at.KHR_BINARY_GLTF]=new Ct(e)}catch(c){return void(r&&r(c))}i=JSON.parse(s[at.KHR_BINARY_GLTF].content)}else i=JSON.parse(o.decode(e))}else i=e;if(void 0===i.asset||i.asset.version[0]<2)return void(r&&r(new Error("THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported.")));const l=new Jt(i,{path:t||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});l.fileLoader.setRequestHeader(this.requestHeader);for(let u=0;u<this.pluginCallbacks.length;u++){const e=this.pluginCallbacks[u](l);e.name,a[e.name]=e,s[e.name]=!0}if(i.extensionsUsed)for(let u=0;u<i.extensionsUsed.length;++u){const e=i.extensionsUsed[u],t=i.extensionsRequired||[];switch(e){case at.KHR_MATERIALS_UNLIT:s[e]=new lt;break;case at.KHR_DRACO_MESH_COMPRESSION:s[e]=new Rt(i,this.dracoLoader);break;case at.KHR_TEXTURE_TRANSFORM:s[e]=new Dt;break;case at.KHR_MESH_QUANTIZATION:s[e]=new kt;break;default:t.indexOf(e)>=0&&a[e]}}l.setExtensions(s),l.setPlugins(a),l.parse(n,r)}parseAsync(e,t){const n=this;return new Promise((function(r,i){n.parse(e,t,r,i)}))}}function it(){let e={};return{get:function(t){return e[t]},add:function(t,n){e[t]=n},remove:function(t){delete e[t]},removeAll:function(){e={}}}}function st(e,t,n){const r=e.json.materials[t];return r.extensions&&r.extensions[n]?r.extensions[n]:null}const at={KHR_BINARY_GLTF:"KHR_binary_glTF",KHR_DRACO_MESH_COMPRESSION:"KHR_draco_mesh_compression",KHR_LIGHTS_PUNCTUAL:"KHR_lights_punctual",KHR_MATERIALS_CLEARCOAT:"KHR_materials_clearcoat",KHR_MATERIALS_DISPERSION:"KHR_materials_dispersion",KHR_MATERIALS_IOR:"KHR_materials_ior",KHR_MATERIALS_SHEEN:"KHR_materials_sheen",KHR_MATERIALS_SPECULAR:"KHR_materials_specular",KHR_MATERIALS_TRANSMISSION:"KHR_materials_transmission",KHR_MATERIALS_IRIDESCENCE:"KHR_materials_iridescence",KHR_MATERIALS_ANISOTROPY:"KHR_materials_anisotropy",KHR_MATERIALS_UNLIT:"KHR_materials_unlit",KHR_MATERIALS_VOLUME:"KHR_materials_volume",KHR_TEXTURE_BASISU:"KHR_texture_basisu",KHR_TEXTURE_TRANSFORM:"KHR_texture_transform",KHR_MESH_QUANTIZATION:"KHR_mesh_quantization",KHR_MATERIALS_EMISSIVE_STRENGTH:"KHR_materials_emissive_strength",EXT_MATERIALS_BUMP:"EXT_materials_bump",EXT_TEXTURE_WEBP:"EXT_texture_webp",EXT_TEXTURE_AVIF:"EXT_texture_avif",EXT_MESHOPT_COMPRESSION:"EXT_meshopt_compression",KHR_MESHOPT_COMPRESSION:"KHR_meshopt_compression",EXT_MESH_GPU_INSTANCING:"EXT_mesh_gpu_instancing"};class ot{constructor(e){this.parser=e,this.name=at.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){const e=this.parser,t=this.parser.json.nodes||[];for(let n=0,r=t.length;n<r;n++){const r=t[n];r.extensions&&r.extensions[this.name]&&void 0!==r.extensions[this.name].light&&e._addNodeRef(this.cache,r.extensions[this.name].light)}}_loadLight(e){const t=this.parser,n="light:"+e;let i=t.cache.get(n);if(i)return i;const s=t.json,a=((s.extensions&&s.extensions[this.name]||{}).lights||[])[e];let o;const l=new r.Color(16777215);void 0!==a.color&&l.setRGB(a.color[0],a.color[1],a.color[2],r.LinearSRGBColorSpace);const c=void 0!==a.range?a.range:0;switch(a.type){case"directional":o=new r.DirectionalLight(l),o.target.position.set(0,0,-1),o.add(o.target);break;case"point":o=new r.PointLight(l),o.distance=c;break;case"spot":o=new r.SpotLight(l),o.distance=c,a.spot=a.spot||{},a.spot.innerConeAngle=void 0!==a.spot.innerConeAngle?a.spot.innerConeAngle:0,a.spot.outerConeAngle=void 0!==a.spot.outerConeAngle?a.spot.outerConeAngle:Math.PI/4,o.angle=a.spot.outerConeAngle,o.penumbra=1-a.spot.innerConeAngle/a.spot.outerConeAngle,o.target.position.set(0,0,-1),o.add(o.target);break;default:throw new Error("THREE.GLTFLoader: Unexpected light type: "+a.type)}return o.position.set(0,0,0),Wt(o,a),void 0!==a.intensity&&(o.intensity=a.intensity),o.name=t.createUniqueName(a.name||"light_"+e),i=Promise.resolve(o),t.cache.add(n,i),i}getDependency(e,t){if("light"===e)return this._loadLight(t)}createNodeAttachment(e){const t=this,n=this.parser,r=n.json.nodes[e],i=(r.extensions&&r.extensions[this.name]||{}).light;return void 0===i?null:this._loadLight(i).then((function(e){return n._getNodeRef(t.cache,i,e)}))}}class lt{constructor(){this.name=at.KHR_MATERIALS_UNLIT}getMaterialType(){return r.MeshBasicMaterial}extendParams(e,t,n){const i=[];e.color=new r.Color(1,1,1),e.opacity=1;const s=t.pbrMetallicRoughness;if(s){if(Array.isArray(s.baseColorFactor)){const t=s.baseColorFactor;e.color.setRGB(t[0],t[1],t[2],r.LinearSRGBColorSpace),e.opacity=t[3]}void 0!==s.baseColorTexture&&i.push(n.assignTexture(e,"map",s.baseColorTexture,r.SRGBColorSpace))}return Promise.all(i)}}class ct{constructor(e){this.parser=e,this.name=at.KHR_MATERIALS_EMISSIVE_STRENGTH}extendMaterialParams(e,t){const n=st(this.parser,e,this.name);return null===n||void 0!==n.emissiveStrength&&(t.emissiveIntensity=n.emissiveStrength),Promise.resolve()}}class ut{constructor(e){this.parser=e,this.name=at.KHR_MATERIALS_CLEARCOAT}getMaterialType(e){return null!==st(this.parser,e,this.name)?r.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=st(this.parser,e,this.name);if(null===n)return Promise.resolve();const i=[];if(void 0!==n.clearcoatFactor&&(t.clearcoat=n.clearcoatFactor),void 0!==n.clearcoatTexture&&i.push(this.parser.assignTexture(t,"clearcoatMap",n.clearcoatTexture)),void 0!==n.clearcoatRoughnessFactor&&(t.clearcoatRoughness=n.clearcoatRoughnessFactor),void 0!==n.clearcoatRoughnessTexture&&i.push(this.parser.assignTexture(t,"clearcoatRoughnessMap",n.clearcoatRoughnessTexture)),void 0!==n.clearcoatNormalTexture&&(i.push(this.parser.assignTexture(t,"clearcoatNormalMap",n.clearcoatNormalTexture)),void 0!==n.clearcoatNormalTexture.scale)){const e=n.clearcoatNormalTexture.scale;t.clearcoatNormalScale=new r.Vector2(e,e)}return Promise.all(i)}}class ht{constructor(e){this.parser=e,this.name=at.KHR_MATERIALS_DISPERSION}getMaterialType(e){return null!==st(this.parser,e,this.name)?r.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=st(this.parser,e,this.name);return null===n||(t.dispersion=void 0!==n.dispersion?n.dispersion:0),Promise.resolve()}}class dt{constructor(e){this.parser=e,this.name=at.KHR_MATERIALS_IRIDESCENCE}getMaterialType(e){return null!==st(this.parser,e,this.name)?r.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=st(this.parser,e,this.name);if(null===n)return Promise.resolve();const r=[];return void 0!==n.iridescenceFactor&&(t.iridescence=n.iridescenceFactor),void 0!==n.iridescenceTexture&&r.push(this.parser.assignTexture(t,"iridescenceMap",n.iridescenceTexture)),void 0!==n.iridescenceIor&&(t.iridescenceIOR=n.iridescenceIor),void 0===t.iridescenceThicknessRange&&(t.iridescenceThicknessRange=[100,400]),void 0!==n.iridescenceThicknessMinimum&&(t.iridescenceThicknessRange[0]=n.iridescenceThicknessMinimum),void 0!==n.iridescenceThicknessMaximum&&(t.iridescenceThicknessRange[1]=n.iridescenceThicknessMaximum),void 0!==n.iridescenceThicknessTexture&&r.push(this.parser.assignTexture(t,"iridescenceThicknessMap",n.iridescenceThicknessTexture)),Promise.all(r)}}class pt{constructor(e){this.parser=e,this.name=at.KHR_MATERIALS_SHEEN}getMaterialType(e){return null!==st(this.parser,e,this.name)?r.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=st(this.parser,e,this.name);if(null===n)return Promise.resolve();const i=[];if(t.sheenColor=new r.Color(0,0,0),t.sheenRoughness=0,t.sheen=1,void 0!==n.sheenColorFactor){const e=n.sheenColorFactor;t.sheenColor.setRGB(e[0],e[1],e[2],r.LinearSRGBColorSpace)}return void 0!==n.sheenRoughnessFactor&&(t.sheenRoughness=n.sheenRoughnessFactor),void 0!==n.sheenColorTexture&&i.push(this.parser.assignTexture(t,"sheenColorMap",n.sheenColorTexture,r.SRGBColorSpace)),void 0!==n.sheenRoughnessTexture&&i.push(this.parser.assignTexture(t,"sheenRoughnessMap",n.sheenRoughnessTexture)),Promise.all(i)}}class mt{constructor(e){this.parser=e,this.name=at.KHR_MATERIALS_TRANSMISSION}getMaterialType(e){return null!==st(this.parser,e,this.name)?r.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=st(this.parser,e,this.name);if(null===n)return Promise.resolve();const r=[];return void 0!==n.transmissionFactor&&(t.transmission=n.transmissionFactor),void 0!==n.transmissionTexture&&r.push(this.parser.assignTexture(t,"transmissionMap",n.transmissionTexture)),Promise.all(r)}}class ft{constructor(e){this.parser=e,this.name=at.KHR_MATERIALS_VOLUME}getMaterialType(e){return null!==st(this.parser,e,this.name)?r.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=st(this.parser,e,this.name);if(null===n)return Promise.resolve();const i=[];t.thickness=void 0!==n.thicknessFactor?n.thicknessFactor:0,void 0!==n.thicknessTexture&&i.push(this.parser.assignTexture(t,"thicknessMap",n.thicknessTexture)),t.attenuationDistance=n.attenuationDistance||1/0;const s=n.attenuationColor||[1,1,1];return t.attenuationColor=(new r.Color).setRGB(s[0],s[1],s[2],r.LinearSRGBColorSpace),Promise.all(i)}}class gt{constructor(e){this.parser=e,this.name=at.KHR_MATERIALS_IOR}getMaterialType(e){return null!==st(this.parser,e,this.name)?r.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=st(this.parser,e,this.name);return null===n||(t.ior=void 0!==n.ior?n.ior:1.5,0===t.ior&&(t.ior=1e3)),Promise.resolve()}}class xt{constructor(e){this.parser=e,this.name=at.KHR_MATERIALS_SPECULAR}getMaterialType(e){return null!==st(this.parser,e,this.name)?r.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=st(this.parser,e,this.name);if(null===n)return Promise.resolve();const i=[];t.specularIntensity=void 0!==n.specularFactor?n.specularFactor:1,void 0!==n.specularTexture&&i.push(this.parser.assignTexture(t,"specularIntensityMap",n.specularTexture));const s=n.specularColorFactor||[1,1,1];return t.specularColor=(new r.Color).setRGB(s[0],s[1],s[2],r.LinearSRGBColorSpace),void 0!==n.specularColorTexture&&i.push(this.parser.assignTexture(t,"specularColorMap",n.specularColorTexture,r.SRGBColorSpace)),Promise.all(i)}}class yt{constructor(e){this.parser=e,this.name=at.EXT_MATERIALS_BUMP}getMaterialType(e){return null!==st(this.parser,e,this.name)?r.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=st(this.parser,e,this.name);if(null===n)return Promise.resolve();const r=[];return t.bumpScale=void 0!==n.bumpFactor?n.bumpFactor:1,void 0!==n.bumpTexture&&r.push(this.parser.assignTexture(t,"bumpMap",n.bumpTexture)),Promise.all(r)}}class vt{constructor(e){this.parser=e,this.name=at.KHR_MATERIALS_ANISOTROPY}getMaterialType(e){return null!==st(this.parser,e,this.name)?r.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=st(this.parser,e,this.name);if(null===n)return Promise.resolve();const r=[];return void 0!==n.anisotropyStrength&&(t.anisotropy=n.anisotropyStrength),void 0!==n.anisotropyRotation&&(t.anisotropyRotation=n.anisotropyRotation),void 0!==n.anisotropyTexture&&r.push(this.parser.assignTexture(t,"anisotropyMap",n.anisotropyTexture)),Promise.all(r)}}class bt{constructor(e){this.parser=e,this.name=at.KHR_TEXTURE_BASISU}loadTexture(e){const t=this.parser,n=t.json,r=n.textures[e];if(!r.extensions||!r.extensions[this.name])return null;const i=r.extensions[this.name],s=t.options.ktx2Loader;if(!s){if(n.extensionsRequired&&n.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");return null}return t.loadTextureImage(e,i.source,s)}}class wt{constructor(e){this.parser=e,this.name=at.EXT_TEXTURE_WEBP}loadTexture(e){const t=this.name,n=this.parser,r=n.json,i=r.textures[e];if(!i.extensions||!i.extensions[t])return null;const s=i.extensions[t],a=r.images[s.source];let o=n.textureLoader;if(a.uri){const e=n.options.manager.getHandler(a.uri);null!==e&&(o=e)}return n.loadTextureImage(e,s.source,o)}}class Tt{constructor(e){this.parser=e,this.name=at.EXT_TEXTURE_AVIF}loadTexture(e){const t=this.name,n=this.parser,r=n.json,i=r.textures[e];if(!i.extensions||!i.extensions[t])return null;const s=i.extensions[t],a=r.images[s.source];let o=n.textureLoader;if(a.uri){const e=n.options.manager.getHandler(a.uri);null!==e&&(o=e)}return n.loadTextureImage(e,s.source,o)}}class St{constructor(e,t){this.name=t,this.parser=e}loadBufferView(e){const t=this.parser.json,n=t.bufferViews[e];if(n.extensions&&n.extensions[this.name]){const e=n.extensions[this.name],r=this.parser.getDependency("buffer",e.buffer),i=this.parser.options.meshoptDecoder;if(!i||!i.supported){if(t.extensionsRequired&&t.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files");return null}return r.then((function(t){const n=e.byteOffset||0,r=e.byteLength||0,s=e.count,a=e.byteStride,o=new Uint8Array(t,n,r);return i.decodeGltfBufferAsync?i.decodeGltfBufferAsync(s,a,o,e.mode,e.filter).then((function(e){return e.buffer})):i.ready.then((function(){const t=new ArrayBuffer(s*a);return i.decodeGltfBuffer(new Uint8Array(t),s,a,o,e.mode,e.filter),t}))}))}return null}}class _t{constructor(e){this.name=at.EXT_MESH_GPU_INSTANCING,this.parser=e}createNodeMesh(e){const t=this.parser.json,n=t.nodes[e];if(!n.extensions||!n.extensions[this.name]||void 0===n.mesh)return null;const i=t.meshes[n.mesh];for(const r of i.primitives)if(r.mode!==Ut.TRIANGLES&&r.mode!==Ut.TRIANGLE_STRIP&&r.mode!==Ut.TRIANGLE_FAN&&void 0!==r.mode)return null;const s=n.extensions[this.name].attributes,a=[],o={};for(const r in s)a.push(this.parser.getDependency("accessor",s[r]).then((e=>(o[r]=e,o[r]))));return a.length<1?null:(a.push(this.parser.createNodeMesh(e)),Promise.all(a).then((e=>{const t=e.pop(),n=t.isGroup?t.children:[t],i=e[0].count,s=[];for(const a of n){const e=new r.Matrix4,t=new r.Vector3,n=new r.Quaternion,l=new r.Vector3(1,1,1),c=new r.InstancedMesh(a.geometry,a.material,i);for(let r=0;r<i;r++)o.TRANSLATION&&t.fromBufferAttribute(o.TRANSLATION,r),o.ROTATION&&n.fromBufferAttribute(o.ROTATION,r),o.SCALE&&l.fromBufferAttribute(o.SCALE,r),c.setMatrixAt(r,e.compose(t,n,l));for(const i in o)if("_COLOR_0"===i){const e=o[i];c.instanceColor=new r.InstancedBufferAttribute(e.array,e.itemSize,e.normalized)}else"TRANSLATION"!==i&&"ROTATION"!==i&&"SCALE"!==i&&a.geometry.setAttribute(i,o[i]);r.Object3D.prototype.copy.call(c,a),this.parser.assignFinalMaterial(c),s.push(c)}return t.isGroup?(t.clear(),t.add(...s),t):s[0]})))}}const Mt="glTF",At=1313821514,Et=5130562;class Ct{constructor(e){this.name=at.KHR_BINARY_GLTF,this.content=null,this.body=null;const t=new DataView(e,0,12),n=new TextDecoder;if(this.header={magic:n.decode(new Uint8Array(e.slice(0,4))),version:t.getUint32(4,!0),length:t.getUint32(8,!0)},this.header.magic!==Mt)throw new Error("THREE.GLTFLoader: Unsupported glTF-Binary header.");if(this.header.version<2)throw new Error("THREE.GLTFLoader: Legacy binary file detected.");const r=this.header.length-12,i=new DataView(e,12);let s=0;for(;s<r;){const t=i.getUint32(s,!0);s+=4;const r=i.getUint32(s,!0);if(s+=4,r===At){const r=new Uint8Array(e,12+s,t);this.content=n.decode(r)}else if(r===Et){const n=12+s;this.body=e.slice(n,n+t)}s+=t}if(null===this.content)throw new Error("THREE.GLTFLoader: JSON content not found.")}}class Rt{constructor(e,t){if(!t)throw new Error("THREE.GLTFLoader: No DRACOLoader instance provided.");this.name=at.KHR_DRACO_MESH_COMPRESSION,this.json=e,this.dracoLoader=t,this.dracoLoader.preload()}decodePrimitive(e,t){const n=this.json,i=this.dracoLoader,s=e.extensions[this.name].bufferView,a=e.extensions[this.name].attributes,o={},l={},c={};for(const r in a){const e=Ot[r]||r.toLowerCase();o[e]=a[r]}for(const r in e.attributes){const t=Ot[r]||r.toLowerCase();if(void 0!==a[r]){const i=n.accessors[e.attributes[r]],s=Ft[i.componentType];c[t]=s.name,l[t]=!0===i.normalized}}return t.getDependency("bufferView",s).then((function(e){return new Promise((function(t,n){i.decodeDracoFile(e,(function(e){for(const t in e.attributes){const n=e.attributes[t],r=l[t];void 0!==r&&(n.normalized=r)}t(e)}),o,c,r.LinearSRGBColorSpace,n)}))}))}}class Dt{constructor(){this.name=at.KHR_TEXTURE_TRANSFORM}extendTexture(e,t){return void 0!==t.texCoord&&t.texCoord!==e.channel||void 0!==t.offset||void 0!==t.rotation||void 0!==t.scale?(e=e.clone(),void 0!==t.texCoord&&(e.channel=t.texCoord),void 0!==t.offset&&e.offset.fromArray(t.offset),void 0!==t.rotation&&(e.rotation=t.rotation),void 0!==t.scale&&e.repeat.fromArray(t.scale),e.needsUpdate=!0,e):e}}class kt{constructor(){this.name=at.KHR_MESH_QUANTIZATION}}class It extends r.Interpolant{constructor(e,t,n,r){super(e,t,n,r)}copySampleValue_(e){const t=this.resultBuffer,n=this.sampleValues,r=this.valueSize,i=e*r*3+r;for(let s=0;s!==r;s++)t[s]=n[i+s];return t}interpolate_(e,t,n,r){const i=this.resultBuffer,s=this.sampleValues,a=this.valueSize,o=2*a,l=3*a,c=r-t,u=(n-t)/c,h=u*u,d=h*u,p=e*l,m=p-l,f=-2*d+3*h,g=d-h,x=1-f,y=g-h+u;for(let v=0;v!==a;v++){const e=s[m+v+a],t=s[m+v+o]*c,n=s[p+v+a],r=s[p+v]*c;i[v]=x*e+y*t+f*n+g*r}return i}}const Pt=new r.Quaternion;class Lt extends It{interpolate_(e,t,n,r){const i=super.interpolate_(e,t,n,r);return Pt.fromArray(i).normalize().toArray(i),i}}const Ut={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6},Ft={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},zt={9728:r.NearestFilter,9729:r.LinearFilter,9984:r.NearestMipmapNearestFilter,9985:r.LinearMipmapNearestFilter,9986:r.NearestMipmapLinearFilter,9987:r.LinearMipmapLinearFilter},Bt={33071:r.ClampToEdgeWrapping,33648:r.MirroredRepeatWrapping,10497:r.RepeatWrapping},Vt={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},Ot={POSITION:"position",NORMAL:"normal",TANGENT:"tangent",TEXCOORD_0:"uv",TEXCOORD_1:"uv1",TEXCOORD_2:"uv2",TEXCOORD_3:"uv3",COLOR_0:"color",WEIGHTS_0:"skinWeight",JOINTS_0:"skinIndex"},Nt={scale:"scale",translation:"position",rotation:"quaternion",weights:"morphTargetInfluences"},$t={CUBICSPLINE:void 0,LINEAR:r.InterpolateLinear,STEP:r.InterpolateDiscrete},Gt="OPAQUE",qt="MASK",Ht="BLEND";function jt(e,t,n){for(const r in n.extensions)void 0===e[r]&&(t.userData.gltfExtensions=t.userData.gltfExtensions||{},t.userData.gltfExtensions[r]=n.extensions[r])}function Wt(e,t){void 0!==t.extras&&"object"==typeof t.extras&&Object.assign(e.userData,t.extras)}function Xt(e,t){if(e.updateMorphTargets(),void 0!==t.weights)for(let n=0,r=t.weights.length;n<r;n++)e.morphTargetInfluences[n]=t.weights[n];if(t.extras&&Array.isArray(t.extras.targetNames)){const n=t.extras.targetNames;if(e.morphTargetInfluences.length===n.length){e.morphTargetDictionary={};for(let t=0,r=n.length;t<r;t++)e.morphTargetDictionary[n[t]]=t}}}function Yt(e){let t;const n=e.extensions&&e.extensions[at.KHR_DRACO_MESH_COMPRESSION];if(t=n?"draco:"+n.bufferView+":"+n.indices+":"+Kt(n.attributes):e.indices+":"+Kt(e.attributes)+":"+e.mode,void 0!==e.targets)for(let r=0,i=e.targets.length;r<i;r++)t+=":"+Kt(e.targets[r]);return t}function Kt(e){let t="";const n=Object.keys(e).sort();for(let r=0,i=n.length;r<i;r++)t+=n[r]+":"+e[n[r]]+";";return t}function Qt(e){switch(e){case Int8Array:return 1/127;case Uint8Array:return 1/255;case Int16Array:return 1/32767;case Uint16Array:return 1/65535;default:throw new Error("THREE.GLTFLoader: Unsupported normalized accessor component type.")}}const Zt=new r.Matrix4;class Jt{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new it,this.associations=new Map,this.primitiveCache={},this.nodeCache={},this.meshCache={refs:{},uses:{}},this.cameraCache={refs:{},uses:{}},this.lightCache={refs:{},uses:{}},this.sourceCache={},this.textureCache={},this.nodeNamesUsed={};let n=!1,i=-1,s=!1,a=-1;if("undefined"!=typeof navigator&&void 0!==navigator.userAgent){const e=navigator.userAgent;n=!0===/^((?!chrome|android).)*safari/i.test(e);const t=e.match(/Version\/(\d+)/);i=n&&t?parseInt(t[1],10):-1,s=e.indexOf("Firefox")>-1,a=s?e.match(/Firefox\/([0-9]+)\./)[1]:-1}"undefined"==typeof createImageBitmap||n&&i<17||s&&a<98?this.textureLoader=new r.TextureLoader(this.options.manager):this.textureLoader=new r.ImageBitmapLoader(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new r.FileLoader(this.options.manager),this.fileLoader.setResponseType("arraybuffer"),"use-credentials"===this.options.crossOrigin&&this.fileLoader.setWithCredentials(!0)}setExtensions(e){this.extensions=e}setPlugins(e){this.plugins=e}parse(e,t){const n=this,r=this.json,i=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll((function(e){return e._markDefs&&e._markDefs()})),Promise.all(this._invokeAll((function(e){return e.beforeRoot&&e.beforeRoot()}))).then((function(){return Promise.all([n.getDependencies("scene"),n.getDependencies("animation"),n.getDependencies("camera")])})).then((function(t){const s={scene:t[0][r.scene||0],scenes:t[0],animations:t[1],cameras:t[2],asset:r.asset,parser:n,userData:{}};return jt(i,s,r),Wt(s,r),Promise.all(n._invokeAll((function(e){return e.afterRoot&&e.afterRoot(s)}))).then((function(){for(const e of s.scenes)e.updateMatrixWorld();e(s)}))})).catch(t)}_markDefs(){const e=this.json.nodes||[],t=this.json.skins||[],n=this.json.meshes||[];for(let r=0,i=t.length;r<i;r++){const n=t[r].joints;for(let t=0,r=n.length;t<r;t++)e[n[t]].isBone=!0}for(let r=0,i=e.length;r<i;r++){const t=e[r];void 0!==t.mesh&&(this._addNodeRef(this.meshCache,t.mesh),void 0!==t.skin&&(n[t.mesh].isSkinnedMesh=!0)),void 0!==t.camera&&this._addNodeRef(this.cameraCache,t.camera)}}_addNodeRef(e,t){void 0!==t&&(void 0===e.refs[t]&&(e.refs[t]=e.uses[t]=0),e.refs[t]++)}_getNodeRef(e,t,n){if(e.refs[t]<=1)return n;const r=n.clone(),i=(e,t)=>{const n=this.associations.get(e);null!=n&&this.associations.set(t,n);for(const[r,s]of e.children.entries())i(s,t.children[r])};return i(n,r),r.name+="_instance_"+e.uses[t]++,r}_invokeOne(e){const t=Object.values(this.plugins);t.push(this);for(let n=0;n<t.length;n++){const r=e(t[n]);if(r)return r}return null}_invokeAll(e){const t=Object.values(this.plugins);t.unshift(this);const n=[];for(let r=0;r<t.length;r++){const i=e(t[r]);i&&n.push(i)}return n}getDependency(e,t){const n=e+":"+t;let r=this.cache.get(n);if(!r){switch(e){case"scene":r=this.loadScene(t);break;case"node":r=this._invokeOne((function(e){return e.loadNode&&e.loadNode(t)}));break;case"mesh":r=this._invokeOne((function(e){return e.loadMesh&&e.loadMesh(t)}));break;case"accessor":r=this.loadAccessor(t);break;case"bufferView":r=this._invokeOne((function(e){return e.loadBufferView&&e.loadBufferView(t)}));break;case"buffer":r=this.loadBuffer(t);break;case"material":r=this._invokeOne((function(e){return e.loadMaterial&&e.loadMaterial(t)}));break;case"texture":r=this._invokeOne((function(e){return e.loadTexture&&e.loadTexture(t)}));break;case"skin":r=this.loadSkin(t);break;case"animation":r=this._invokeOne((function(e){return e.loadAnimation&&e.loadAnimation(t)}));break;case"camera":r=this.loadCamera(t);break;default:if(r=this._invokeOne((function(n){return n!=this&&n.getDependency&&n.getDependency(e,t)})),!r)throw new Error("Unknown type: "+e)}this.cache.add(n,r)}return r}getDependencies(e){let t=this.cache.get(e);if(!t){const n=this,r=this.json[e+("mesh"===e?"es":"s")]||[];t=Promise.all(r.map((function(t,r){return n.getDependency(e,r)}))),this.cache.add(e,t)}return t}loadBuffer(e){const t=this.json.buffers[e],n=this.fileLoader;if(t.type&&"arraybuffer"!==t.type)throw new Error("THREE.GLTFLoader: "+t.type+" buffer type is not supported.");if(void 0===t.uri&&0===e)return Promise.resolve(this.extensions[at.KHR_BINARY_GLTF].body);const i=this.options;return new Promise((function(e,s){n.load(r.LoaderUtils.resolveURL(t.uri,i.path),e,void 0,(function(){s(new Error('THREE.GLTFLoader: Failed to load buffer "'+t.uri+'".'))}))}))}loadBufferView(e){const t=this.json.bufferViews[e];return this.getDependency("buffer",t.buffer).then((function(e){const n=t.byteLength||0,r=t.byteOffset||0;return e.slice(r,r+n)}))}loadAccessor(e){const t=this,n=this.json,i=this.json.accessors[e];if(void 0===i.bufferView&&void 0===i.sparse){const e=Vt[i.type],t=Ft[i.componentType],n=!0===i.normalized,s=new t(i.count*e);return Promise.resolve(new r.BufferAttribute(s,e,n))}const s=[];return void 0!==i.bufferView?s.push(this.getDependency("bufferView",i.bufferView)):s.push(null),void 0!==i.sparse&&(s.push(this.getDependency("bufferView",i.sparse.indices.bufferView)),s.push(this.getDependency("bufferView",i.sparse.values.bufferView))),Promise.all(s).then((function(e){const s=e[0],a=Vt[i.type],o=Ft[i.componentType],l=o.BYTES_PER_ELEMENT,c=l*a,u=i.byteOffset||0,h=void 0!==i.bufferView?n.bufferViews[i.bufferView].byteStride:void 0,d=!0===i.normalized;let p,m;if(h&&h!==c){const e=Math.floor(u/h),n="InterleavedBuffer:"+i.bufferView+":"+i.componentType+":"+e+":"+i.count;let c=t.cache.get(n);c||(p=new o(s,e*h,i.count*h/l),c=new r.InterleavedBuffer(p,h/l),t.cache.add(n,c)),m=new r.InterleavedBufferAttribute(c,a,u%h/l,d)}else p=null===s?new o(i.count*a):new o(s,u,i.count*a),m=new r.BufferAttribute(p,a,d);if(void 0!==i.sparse){const t=Vt.SCALAR,n=Ft[i.sparse.indices.componentType],l=i.sparse.indices.byteOffset||0,c=i.sparse.values.byteOffset||0,u=new n(e[1],l,i.sparse.count*t),h=new o(e[2],c,i.sparse.count*a);null!==s&&(m=new r.BufferAttribute(m.array.slice(),m.itemSize,m.normalized)),m.normalized=!1;for(let e=0,r=u.length;e<r;e++){const t=u[e];if(m.setX(t,h[e*a]),a>=2&&m.setY(t,h[e*a+1]),a>=3&&m.setZ(t,h[e*a+2]),a>=4&&m.setW(t,h[e*a+3]),a>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}m.normalized=d}return m}))}loadTexture(e){const t=this.json,n=this.options,r=t.textures[e].source,i=t.images[r];let s=this.textureLoader;if(i.uri){const e=n.manager.getHandler(i.uri);null!==e&&(s=e)}return this.loadTextureImage(e,r,s)}loadTextureImage(e,t,n){const i=this,s=this.json,a=s.textures[e],o=s.images[t],l=(o.uri||o.bufferView)+":"+a.sampler;if(this.textureCache[l])return this.textureCache[l];const c=this.loadImageSource(t,n).then((function(t){t.flipY=!1,t.name=a.name||o.name||"",""===t.name&&"string"==typeof o.uri&&!1===o.uri.startsWith("data:image/")&&(t.name=o.uri);const n=(s.samplers||{})[a.sampler]||{};return t.magFilter=zt[n.magFilter]||r.LinearFilter,t.minFilter=zt[n.minFilter]||r.LinearMipmapLinearFilter,t.wrapS=Bt[n.wrapS]||r.RepeatWrapping,t.wrapT=Bt[n.wrapT]||r.RepeatWrapping,t.generateMipmaps=!t.isCompressedTexture&&t.minFilter!==r.NearestFilter&&t.minFilter!==r.LinearFilter,i.associations.set(t,{textures:e}),t})).catch((function(){return null}));return this.textureCache[l]=c,c}loadImageSource(e,t){const n=this,i=this.json,s=this.options;if(void 0!==this.sourceCache[e])return this.sourceCache[e].then((e=>e.clone()));const a=i.images[e],o=self.URL||self.webkitURL;let l=a.uri||"",c=!1;if(void 0!==a.bufferView)l=n.getDependency("bufferView",a.bufferView).then((function(e){c=!0;const t=new Blob([e],{type:a.mimeType});return l=o.createObjectURL(t),l}));else if(void 0===a.uri)throw new Error("THREE.GLTFLoader: Image "+e+" is missing URI and bufferView");const u=Promise.resolve(l).then((function(e){return new Promise((function(n,i){let a=n;!0===t.isImageBitmapLoader&&(a=function(e){const t=new r.Texture(e);t.needsUpdate=!0,n(t)}),t.load(r.LoaderUtils.resolveURL(e,s.path),a,void 0,i)}))})).then((function(e){var t;return!0===c&&o.revokeObjectURL(l),Wt(e,a),e.userData.mimeType=a.mimeType||((t=a.uri).search(/\.jpe?g($|\?)/i)>0||0===t.search(/^data\:image\/jpeg/)?"image/jpeg":t.search(/\.webp($|\?)/i)>0||0===t.search(/^data\:image\/webp/)?"image/webp":t.search(/\.ktx2($|\?)/i)>0||0===t.search(/^data\:image\/ktx2/)?"image/ktx2":"image/png"),e})).catch((function(e){throw e}));return this.sourceCache[e]=u,u}assignTexture(e,t,n,r){const i=this;return this.getDependency("texture",n.index).then((function(s){if(!s)return null;if(void 0!==n.texCoord&&n.texCoord>0&&((s=s.clone()).channel=n.texCoord),i.extensions[at.KHR_TEXTURE_TRANSFORM]){const e=void 0!==n.extensions?n.extensions[at.KHR_TEXTURE_TRANSFORM]:void 0;if(e){const t=i.associations.get(s);s=i.extensions[at.KHR_TEXTURE_TRANSFORM].extendTexture(s,e),i.associations.set(s,t)}}return void 0!==r&&(s.colorSpace=r),e[t]=s,s}))}assignFinalMaterial(e){const t=e.geometry;let n=e.material;const i=void 0===t.attributes.tangent,s=void 0!==t.attributes.color,a=void 0===t.attributes.normal;if(e.isPoints){const e="PointsMaterial:"+n.uuid;let t=this.cache.get(e);t||(t=new r.PointsMaterial,r.Material.prototype.copy.call(t,n),t.color.copy(n.color),t.map=n.map,t.sizeAttenuation=!1,this.cache.add(e,t)),n=t}else if(e.isLine){const e="LineBasicMaterial:"+n.uuid;let t=this.cache.get(e);t||(t=new r.LineBasicMaterial,r.Material.prototype.copy.call(t,n),t.color.copy(n.color),t.map=n.map,this.cache.add(e,t)),n=t}if(i||s||a){let e="ClonedMaterial:"+n.uuid+":";i&&(e+="derivative-tangents:"),s&&(e+="vertex-colors:"),a&&(e+="flat-shading:");let t=this.cache.get(e);t||(t=n.clone(),s&&(t.vertexColors=!0),a&&(t.flatShading=!0),i&&(t.normalScale&&(t.normalScale.y*=-1),t.clearcoatNormalScale&&(t.clearcoatNormalScale.y*=-1)),this.cache.add(e,t),this.associations.set(t,this.associations.get(n))),n=t}e.material=n}getMaterialType(){return r.MeshStandardMaterial}loadMaterial(e){const t=this,n=this.json,i=this.extensions,s=n.materials[e];let a;const o={},l=[];if((s.extensions||{})[at.KHR_MATERIALS_UNLIT]){const e=i[at.KHR_MATERIALS_UNLIT];a=e.getMaterialType(),l.push(e.extendParams(o,s,t))}else{const n=s.pbrMetallicRoughness||{};if(o.color=new r.Color(1,1,1),o.opacity=1,Array.isArray(n.baseColorFactor)){const e=n.baseColorFactor;o.color.setRGB(e[0],e[1],e[2],r.LinearSRGBColorSpace),o.opacity=e[3]}void 0!==n.baseColorTexture&&l.push(t.assignTexture(o,"map",n.baseColorTexture,r.SRGBColorSpace)),o.metalness=void 0!==n.metallicFactor?n.metallicFactor:1,o.roughness=void 0!==n.roughnessFactor?n.roughnessFactor:1,void 0!==n.metallicRoughnessTexture&&(l.push(t.assignTexture(o,"metalnessMap",n.metallicRoughnessTexture)),l.push(t.assignTexture(o,"roughnessMap",n.metallicRoughnessTexture))),a=this._invokeOne((function(t){return t.getMaterialType&&t.getMaterialType(e)})),l.push(Promise.all(this._invokeAll((function(t){return t.extendMaterialParams&&t.extendMaterialParams(e,o)}))))}!0===s.doubleSided&&(o.side=r.DoubleSide);const c=s.alphaMode||Gt;if(c===Ht?(o.transparent=!0,o.depthWrite=!1):(o.transparent=!1,c===qt&&(o.alphaTest=void 0!==s.alphaCutoff?s.alphaCutoff:.5)),void 0!==s.normalTexture&&a!==r.MeshBasicMaterial&&(l.push(t.assignTexture(o,"normalMap",s.normalTexture)),o.normalScale=new r.Vector2(1,1),void 0!==s.normalTexture.scale)){const e=s.normalTexture.scale;o.normalScale.set(e,e)}if(void 0!==s.occlusionTexture&&a!==r.MeshBasicMaterial&&(l.push(t.assignTexture(o,"aoMap",s.occlusionTexture)),void 0!==s.occlusionTexture.strength&&(o.aoMapIntensity=s.occlusionTexture.strength)),void 0!==s.emissiveFactor&&a!==r.MeshBasicMaterial){const e=s.emissiveFactor;o.emissive=(new r.Color).setRGB(e[0],e[1],e[2],r.LinearSRGBColorSpace)}return void 0!==s.emissiveTexture&&a!==r.MeshBasicMaterial&&l.push(t.assignTexture(o,"emissiveMap",s.emissiveTexture,r.SRGBColorSpace)),Promise.all(l).then((function(){const n=new a(o);return s.name&&(n.name=s.name),Wt(n,s),t.associations.set(n,{materials:e}),s.extensions&&jt(i,n,s),n}))}createUniqueName(e){const t=r.PropertyBinding.sanitizeNodeName(e||"");return t in this.nodeNamesUsed?t+"_"+ ++this.nodeNamesUsed[t]:(this.nodeNamesUsed[t]=0,t)}loadGeometries(e){const t=this,n=this.extensions,i=this.primitiveCache;function s(e){return n[at.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(e,t).then((function(n){return en(n,e,t)}))}const a=[];for(let o=0,l=e.length;o<l;o++){const n=e[o],l=Yt(n),c=i[l];if(c)a.push(c.promise);else{let e;e=n.extensions&&n.extensions[at.KHR_DRACO_MESH_COMPRESSION]?s(n):en(new r.BufferGeometry,n,t),i[l]={primitive:n,promise:e},a.push(e)}}return Promise.all(a)}loadMesh(e){const t=this,n=this.json,i=this.extensions,s=n.meshes[e],a=s.primitives,o=[];for(let c=0,u=a.length;c<u;c++){const e=void 0===a[c].material?(void 0===(l=this.cache).DefaultMaterial&&(l.DefaultMaterial=new r.MeshStandardMaterial({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:r.FrontSide})),l.DefaultMaterial):this.getDependency("material",a[c].material);o.push(e)}var l;return o.push(t.loadGeometries(a)),Promise.all(o).then((function(n){const o=n.slice(0,n.length-1),l=n[n.length-1],c=[];for(let h=0,d=l.length;h<d;h++){const n=l[h],u=a[h];let d;const p=o[h];if(u.mode===Ut.TRIANGLES||u.mode===Ut.TRIANGLE_STRIP||u.mode===Ut.TRIANGLE_FAN||void 0===u.mode)d=!0===s.isSkinnedMesh?new r.SkinnedMesh(n,p):new r.Mesh(n,p),!0===d.isSkinnedMesh&&d.normalizeSkinWeights(),u.mode===Ut.TRIANGLE_STRIP?d.geometry=Xe(d.geometry,r.TriangleStripDrawMode):u.mode===Ut.TRIANGLE_FAN&&(d.geometry=Xe(d.geometry,r.TriangleFanDrawMode));else if(u.mode===Ut.LINES)d=new r.LineSegments(n,p);else if(u.mode===Ut.LINE_STRIP)d=new r.Line(n,p);else if(u.mode===Ut.LINE_LOOP)d=new r.LineLoop(n,p);else{if(u.mode!==Ut.POINTS)throw new Error("THREE.GLTFLoader: Primitive mode unsupported: "+u.mode);d=new r.Points(n,p)}Object.keys(d.geometry.morphAttributes).length>0&&Xt(d,s),d.name=t.createUniqueName(s.name||"mesh_"+e),Wt(d,s),u.extensions&&jt(i,d,u),t.assignFinalMaterial(d),c.push(d)}for(let r=0,i=c.length;r<i;r++)t.associations.set(c[r],{meshes:e,primitives:r});if(1===c.length)return s.extensions&&jt(i,c[0],s),c[0];const u=new r.Group;s.extensions&&jt(i,u,s),t.associations.set(u,{meshes:e});for(let e=0,t=c.length;e<t;e++)u.add(c[e]);return u}))}loadCamera(e){let t;const n=this.json.cameras[e],i=n[n.type];if(i)return"perspective"===n.type?t=new r.PerspectiveCamera(r.MathUtils.radToDeg(i.yfov),i.aspectRatio||1,i.znear||1,i.zfar||2e6):"orthographic"===n.type&&(t=new r.OrthographicCamera(-i.xmag,i.xmag,i.ymag,-i.ymag,i.znear,i.zfar)),n.name&&(t.name=this.createUniqueName(n.name)),Wt(t,n),Promise.resolve(t)}loadSkin(e){const t=this.json.skins[e],n=[];for(let r=0,i=t.joints.length;r<i;r++)n.push(this._loadNodeShallow(t.joints[r]));return void 0!==t.inverseBindMatrices?n.push(this.getDependency("accessor",t.inverseBindMatrices)):n.push(null),Promise.all(n).then((function(e){const t=e.pop(),n=e,i=[],s=[];for(let a=0,o=n.length;a<o;a++){const e=n[a];if(e){i.push(e);const n=new r.Matrix4;null!==t&&n.fromArray(t.array,16*a),s.push(n)}}return new r.Skeleton(i,s)}))}loadAnimation(e){const t=this.json,n=this,i=t.animations[e],s=i.name?i.name:"animation_"+e,a=[],o=[],l=[],c=[],u=[];for(let r=0,h=i.channels.length;r<h;r++){const e=i.channels[r],t=i.samplers[e.sampler],n=e.target,s=n.node,h=void 0!==i.parameters?i.parameters[t.input]:t.input,d=void 0!==i.parameters?i.parameters[t.output]:t.output;void 0!==n.node&&(a.push(this.getDependency("node",s)),o.push(this.getDependency("accessor",h)),l.push(this.getDependency("accessor",d)),c.push(t),u.push(n))}return Promise.all([Promise.all(a),Promise.all(o),Promise.all(l),Promise.all(c),Promise.all(u)]).then((function(e){const t=e[0],a=e[1],o=e[2],l=e[3],c=e[4],u=[];for(let r=0,i=t.length;r<i;r++){const e=t[r],i=a[r],s=o[r],h=l[r],d=c[r];if(void 0===e)continue;e.updateMatrix&&e.updateMatrix();const p=n._createAnimationTracks(e,i,s,h,d);if(p)for(let t=0;t<p.length;t++)u.push(p[t])}const h=new r.AnimationClip(s,void 0,u);return Wt(h,i),h}))}createNodeMesh(e){const t=this.json,n=this,r=t.nodes[e];return void 0===r.mesh?null:n.getDependency("mesh",r.mesh).then((function(e){const t=n._getNodeRef(n.meshCache,r.mesh,e);return void 0!==r.weights&&t.traverse((function(e){if(e.isMesh)for(let t=0,n=r.weights.length;t<n;t++)e.morphTargetInfluences[t]=r.weights[t]})),t}))}loadNode(e){const t=this,n=this.json.nodes[e],i=t._loadNodeShallow(e),s=[],a=n.children||[];for(let r=0,l=a.length;r<l;r++)s.push(t.getDependency("node",a[r]));const o=void 0===n.skin?Promise.resolve(null):t.getDependency("skin",n.skin);return Promise.all([i,Promise.all(s),o]).then((function(e){const t=e[0],n=e[1],i=e[2];null!==i&&t.traverse((function(e){e.isSkinnedMesh&&e.bind(i,Zt)}));for(let r=0,s=n.length;r<s;r++)t.add(n[r]);if(void 0!==t.userData.pivot&&n.length>0){const e=t.userData.pivot,i=n[0];t.pivot=(new r.Vector3).fromArray(e),t.position.x-=e[0],t.position.y-=e[1],t.position.z-=e[2],i.position.set(0,0,0),delete t.userData.pivot}return t}))}_loadNodeShallow(e){const t=this.json,n=this.extensions,i=this;if(void 0!==this.nodeCache[e])return this.nodeCache[e];const s=t.nodes[e],a=s.name?i.createUniqueName(s.name):"",o=[],l=i._invokeOne((function(t){return t.createNodeMesh&&t.createNodeMesh(e)}));return l&&o.push(l),void 0!==s.camera&&o.push(i.getDependency("camera",s.camera).then((function(e){return i._getNodeRef(i.cameraCache,s.camera,e)}))),i._invokeAll((function(t){return t.createNodeAttachment&&t.createNodeAttachment(e)})).forEach((function(e){o.push(e)})),this.nodeCache[e]=Promise.all(o).then((function(t){let o;if(o=!0===s.isBone?new r.Bone:t.length>1?new r.Group:1===t.length?t[0]:new r.Object3D,o!==t[0])for(let e=0,n=t.length;e<n;e++)o.add(t[e]);if(s.name&&(o.userData.name=s.name,o.name=a),Wt(o,s),s.extensions&&jt(n,o,s),void 0!==s.matrix){const e=new r.Matrix4;e.fromArray(s.matrix),o.applyMatrix4(e)}else void 0!==s.translation&&o.position.fromArray(s.translation),void 0!==s.rotation&&o.quaternion.fromArray(s.rotation),void 0!==s.scale&&o.scale.fromArray(s.scale);if(i.associations.has(o)){if(void 0!==s.mesh&&i.meshCache.refs[s.mesh]>1){const e=i.associations.get(o);i.associations.set(o,{...e})}}else i.associations.set(o,{});return i.associations.get(o).nodes=e,o})),this.nodeCache[e]}loadScene(e){const t=this.extensions,n=this.json.scenes[e],i=this,s=new r.Group;n.name&&(s.name=i.createUniqueName(n.name)),Wt(s,n),n.extensions&&jt(t,s,n);const a=n.nodes||[],o=[];for(let r=0,l=a.length;r<l;r++)o.push(i.getDependency("node",a[r]));return Promise.all(o).then((function(e){for(let t=0,n=e.length;t<n;t++){const n=e[t];null!==n.parent?s.add(tt(n)):s.add(n)}return i.associations=(e=>{const t=new Map;for(const[n,s]of i.associations)(n instanceof r.Material||n instanceof r.Texture)&&t.set(n,s);return e.traverse((e=>{const n=i.associations.get(e);null!=n&&t.set(e,n)})),t})(s),s}))}_createAnimationTracks(e,t,n,i,s){const a=[],o=e.name?e.name:e.uuid,l=[];function c(e){e.morphTargetInfluences&&l.push(e.name?e.name:e.uuid)}let u;switch(Nt[s.path]===Nt.weights?(c(e),e.isGroup&&e.children.forEach(c)):l.push(o),Nt[s.path]){case Nt.weights:u=r.NumberKeyframeTrack;break;case Nt.rotation:u=r.QuaternionKeyframeTrack;break;case Nt.translation:case Nt.scale:u=r.VectorKeyframeTrack;break;default:if(1===n.itemSize)u=r.NumberKeyframeTrack;else u=r.VectorKeyframeTrack}const h=void 0!==i.interpolation?$t[i.interpolation]:r.InterpolateLinear,d=this._getArrayFromAccessor(n);for(let r=0,p=l.length;r<p;r++){const e=new u(l[r]+"."+Nt[s.path],t.array,d,h);"CUBICSPLINE"===i.interpolation&&this._createCubicSplineTrackInterpolant(e),a.push(e)}return a}_getArrayFromAccessor(e){let t=e.array;if(e.normalized){const e=Qt(t.constructor),n=new Float32Array(t.length);for(let r=0,i=t.length;r<i;r++)n[r]=t[r]*e;t=n}return t}_createCubicSplineTrackInterpolant(e){e.createInterpolant=function(e){return new(this instanceof r.QuaternionKeyframeTrack?Lt:It)(this.times,this.values,this.getValueSize()/3,e)},e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}}function en(e,t,n){const i=t.attributes,s=[];function a(t,r){return n.getDependency("accessor",t).then((function(t){e.setAttribute(r,t)}))}for(const r in i){const t=Ot[r]||r.toLowerCase();t in e.attributes||s.push(a(i[r],t))}if(void 0!==t.indices&&!e.index){const r=n.getDependency("accessor",t.indices).then((function(t){e.setIndex(t)}));s.push(r)}return r.ColorManagement.workingColorSpace,r.LinearSRGBColorSpace,Wt(e,t),function(e,t,n){const i=t.attributes,s=new r.Box3;if(void 0===i.POSITION)return;{const e=n.json.accessors[i.POSITION],t=e.min,a=e.max;if(void 0===t||void 0===a)return;if(s.set(new r.Vector3(t[0],t[1],t[2]),new r.Vector3(a[0],a[1],a[2])),e.normalized){const t=Qt(Ft[e.componentType]);s.min.multiplyScalar(t),s.max.multiplyScalar(t)}}const a=t.targets;if(void 0!==a){const e=new r.Vector3,t=new r.Vector3;for(let r=0,i=a.length;r<i;r++){const i=a[r];if(void 0!==i.POSITION){const r=n.json.accessors[i.POSITION],s=r.min,a=r.max;if(void 0!==s&&void 0!==a){if(t.setX(Math.max(Math.abs(s[0]),Math.abs(a[0]))),t.setY(Math.max(Math.abs(s[1]),Math.abs(a[1]))),t.setZ(Math.max(Math.abs(s[2]),Math.abs(a[2]))),r.normalized){const e=Qt(Ft[r.componentType]);t.multiplyScalar(e)}e.max(t)}}}s.expandByVector(e)}e.boundingBox=s;const o=new r.Sphere;s.getCenter(o.center),o.radius=s.min.distanceTo(s.max)/2,e.boundingSphere=o}(e,t,n),Promise.all(s).then((function(){return void 0!==t.targets?function(e,t,n){let r=!1,i=!1,s=!1;for(let c=0,u=t.length;c<u;c++){const e=t[c];if(void 0!==e.POSITION&&(r=!0),void 0!==e.NORMAL&&(i=!0),void 0!==e.COLOR_0&&(s=!0),r&&i&&s)break}if(!r&&!i&&!s)return Promise.resolve(e);const a=[],o=[],l=[];for(let c=0,u=t.length;c<u;c++){const u=t[c];if(r){const t=void 0!==u.POSITION?n.getDependency("accessor",u.POSITION):e.attributes.position;a.push(t)}if(i){const t=void 0!==u.NORMAL?n.getDependency("accessor",u.NORMAL):e.attributes.normal;o.push(t)}if(s){const t=void 0!==u.COLOR_0?n.getDependency("accessor",u.COLOR_0):e.attributes.color;l.push(t)}}return Promise.all([Promise.all(a),Promise.all(o),Promise.all(l)]).then((function(t){const n=t[0],a=t[1],o=t[2];return r&&(e.morphAttributes.position=n),i&&(e.morphAttributes.normal=a),s&&(e.morphAttributes.color=o),e.morphTargetsRelative=!0,e}))}(e,t.targets,n):e}))}class tn extends r.DataTextureLoader{constructor(e){super(e),this.type=r.HalfFloatType}parse(e){const t=function(e,t){switch(e){case 1:throw new Error("THREE.HDRLoader: Read Error: "+(t||""));case 2:throw new Error("THREE.HDRLoader: Write Error: "+(t||""));case 3:throw new Error("THREE.HDRLoader: Bad File Format: "+(t||""));default:throw new Error("THREE.HDRLoader: Memory Error: "+(t||""))}},n=function(e,t,n){t=t||1024;let r=e.pos,i=-1,s=0,a="",o=String.fromCharCode.apply(null,new Uint16Array(e.subarray(r,r+128)));for(;0>(i=o.indexOf("\n"))&&s<t&&r<e.byteLength;)a+=o,s+=o.length,r+=128,o=String.fromCharCode.apply(null,new Uint16Array(e.subarray(r,r+128)));return-1<i&&(e.pos+=s+i+1,a+o.slice(0,i))},i=function(e,t,n,r){const i=e[t+3],s=Math.pow(2,i-128)/255;n[r+0]=e[t+0]*s,n[r+1]=e[t+1]*s,n[r+2]=e[t+2]*s,n[r+3]=1},s=function(e,t,n,i){const s=e[t+3],a=Math.pow(2,s-128)/255;n[i+0]=r.DataUtils.toHalfFloat(Math.min(e[t+0]*a,65504)),n[i+1]=r.DataUtils.toHalfFloat(Math.min(e[t+1]*a,65504)),n[i+2]=r.DataUtils.toHalfFloat(Math.min(e[t+2]*a,65504)),n[i+3]=r.DataUtils.toHalfFloat(1)},a=new Uint8Array(e);a.pos=0;const o=function(e){const r=/^\s*GAMMA\s*=\s*(\d+(\.\d+)?)\s*$/,i=/^\s*EXPOSURE\s*=\s*(\d+(\.\d+)?)\s*$/,s=/^\s*FORMAT=(\S+)\s*$/,a=/^\s*\-Y\s+(\d+)\s+\+X\s+(\d+)\s*$/,o={valid:0,string:"",comments:"",programtype:"RGBE",format:"",gamma:1,exposure:1,width:0,height:0};let l,c;for((e.pos>=e.byteLength||!(l=n(e)))&&t(1,"no header found"),(c=l.match(/^#\?(\S+)/))||t(3,"bad initial token"),o.valid|=1,o.programtype=c[1],o.string+=l+"\n";l=n(e),!1!==l;)if(o.string+=l+"\n","#"!==l.charAt(0)){if((c=l.match(r))&&(o.gamma=parseFloat(c[1])),(c=l.match(i))&&(o.exposure=parseFloat(c[1])),(c=l.match(s))&&(o.valid|=2,o.format=c[1]),(c=l.match(a))&&(o.valid|=4,o.height=parseInt(c[1],10),o.width=parseInt(c[2],10)),2&o.valid&&4&o.valid)break}else o.comments+=l+"\n";return 2&o.valid||t(3,"missing format specifier"),4&o.valid||t(3,"missing image size specifier"),o}(a),l=o.width,c=o.height,u=function(e,n,r){const i=n;if(i<8||i>32767||2!==e[0]||2!==e[1]||128&e[2])return new Uint8Array(e);i!==(e[2]<<8|e[3])&&t(3,"wrong scanline width");const s=new Uint8Array(4*n*r);s.length||t(4,"unable to allocate buffer space");let a=0,o=0;const l=4*i,c=new Uint8Array(4),u=new Uint8Array(l);let h=r;for(;h>0&&o<e.byteLength;){o+4>e.byteLength&&t(1),c[0]=e[o++],c[1]=e[o++],c[2]=e[o++],c[3]=e[o++],2==c[0]&&2==c[1]&&(c[2]<<8|c[3])==i||t(3,"bad rgbe scanline format");let n,r=0;for(;r<l&&o<e.byteLength;){n=e[o++];const i=n>128;if(i&&(n-=128),(0===n||r+n>l)&&t(3,"bad scanline data"),i){const t=e[o++];for(let e=0;e<n;e++)u[r++]=t}else u.set(e.subarray(o,o+n),r),r+=n,o+=n}const d=i;for(let e=0;e<d;e++){let t=0;s[a]=u[e+t],t+=i,s[a+1]=u[e+t],t+=i,s[a+2]=u[e+t],t+=i,s[a+3]=u[e+t],a+=4}h--}return s}(a.subarray(a.pos),l,c);let h,d,p;switch(this.type){case r.FloatType:p=u.length/4;const e=new Float32Array(4*p);for(let n=0;n<p;n++)i(u,4*n,e,4*n);h=e,d=r.FloatType;break;case r.HalfFloatType:p=u.length/4;const t=new Uint16Array(4*p);for(let n=0;n<p;n++)s(u,4*n,t,4*n);h=t,d=r.HalfFloatType;break;default:throw new Error("THREE.HDRLoader: Unsupported type: "+this.type)}return{width:l,height:c,data:h,header:o.string,gamma:o.gamma,exposure:o.exposure,type:d,colorSpace:r.LinearSRGBColorSpace,minFilter:r.LinearFilter,magFilter:r.LinearFilter,generateMipmaps:!1,flipY:!0}}setDataType(e){return this.type=e,this}}let nn,rn,sn,an=class{constructor(e=4){this.pool=e,this.queue=[],this.workers=[],this.workersResolve=[],this.workerStatus=0,this.workerCreator=null}_initWorker(e){if(!this.workers[e]){const t=this.workerCreator();t.addEventListener("message",this._onMessage.bind(this,e)),this.workers[e]=t}}_getIdleWorker(){for(let e=0;e<this.pool;e++)if(!(this.workerStatus&1<<e))return e;return-1}_onMessage(e,t){const n=this.workersResolve[e];if(n&&n(t),this.queue.length){const{resolve:t,msg:n,transfer:r}=this.queue.shift();this.workersResolve[e]=t,this.workers[e].postMessage(n,r)}else this.workerStatus^=1<<e}setWorkerCreator(e){this.workerCreator=e}setWorkerLimit(e){this.pool=e}postMessage(e,t){return new Promise((n=>{const r=this._getIdleWorker();-1!==r?(this._initWorker(r),this.workerStatus|=1<<r,this.workersResolve[r]=n,this.workers[r].postMessage(e,t)):this.queue.push({resolve:n,msg:e,transfer:t})}))}dispose(){this.workers.forEach((e=>e.terminate())),this.workersResolve.length=0,this.workers.length=0,this.queue.length=0,this.workerStatus=0}};const on={env:{emscripten_notify_memory_growth:function(e){sn=new Uint8Array(rn.exports.memory.buffer)}}};let ln=class{init(){return nn||(nn="undefined"!=typeof fetch?fetch("undefined"==typeof document?require("url").pathToFileURL(__dirname+"/assets/viewer/zstd-decoder-67d12d34f82e.wasm").href:new URL("assets/viewer/zstd-decoder-67d12d34f82e.wasm",document.currentScript&&"SCRIPT"===document.currentScript.tagName.toUpperCase()&&document.currentScript.src||document.baseURI).href).then((e=>e.arrayBuffer())).then((e=>WebAssembly.instantiate(e,on))).then(this._init):fetch("undefined"==typeof document?require("url").pathToFileURL(__dirname+"/assets/viewer/zstd-decoder-67d12d34f82e.wasm").href:new URL("assets/viewer/zstd-decoder-67d12d34f82e.wasm",document.currentScript&&"SCRIPT"===document.currentScript.tagName.toUpperCase()&&document.currentScript.src||document.baseURI).href).then((e=>e.arrayBuffer())).then((e=>WebAssembly.instantiate(e,on))).then(this._init),nn)}_init(e){rn=e.instance,on.env.emscripten_notify_memory_growth(0)}decode(e,t=0){if(!rn)throw new Error("ZSTDDecoder: Await .init() before decoding.");const n=e.byteLength,r=rn.exports.malloc(n);sn.set(e,r),t=t||Number(rn.exports.ZSTD_findDecompressedSize(r,n));const i=rn.exports.malloc(t),s=rn.exports.ZSTD_decompress(i,t,r,n),a=sn.slice(i,i+s);return rn.exports.free(r),rn.exports.free(i),a}};r.ColorManagement.spaces[r.SRGBColorSpace];const cn="undefined"==typeof document?require("url").pathToFileURL(__dirname+"/assets/viewer/basis-transcoder-6cf17dc88935.wasm").href:new URL("assets/viewer/basis-transcoder-6cf17dc88935.wasm",document.currentScript&&"SCRIPT"===document.currentScript.tagName.toUpperCase()&&document.currentScript.src||document.baseURI).href,un="undefined"==typeof document?require("url").pathToFileURL(__dirname+"/assets/viewer/basis-transcoder-8478b5b6d6b7.js").href:new URL("assets/viewer/basis-transcoder-8478b5b6d6b7.js",document.currentScript&&"SCRIPT"===document.currentScript.tagName.toUpperCase()&&document.currentScript.src||document.baseURI).href,hn=new WeakMap;let dn;class pn extends r.Loader{constructor(e){super(e),this.transcoderPath="",this.transcoderBinary=null,this.transcoderPending=null,this.workerPool=new an,this.workerSourceURL="",this.workerConfig=null}setTranscoderPath(e){return this.transcoderPath=e,this}setWorkerLimit(e){return this.workerPool.setWorkerLimit(e),this}async detectSupportAsync(e){return await e.init(),this.detectSupport(e)}detectSupport(e){return!0===e.isWebGPURenderer?this.workerConfig={astcSupported:e.hasFeature("texture-compression-astc"),astcHDRSupported:!1,etc1Supported:e.hasFeature("texture-compression-etc1"),etc2Supported:e.hasFeature("texture-compression-etc2"),dxtSupported:e.hasFeature("texture-compression-s3tc"),bptcSupported:e.hasFeature("texture-compression-bc"),pvrtcSupported:e.hasFeature("texture-compression-pvrtc")}:(this.workerConfig={astcSupported:e.extensions.has("WEBGL_compressed_texture_astc"),astcHDRSupported:e.extensions.has("WEBGL_compressed_texture_astc")&&e.extensions.get("WEBGL_compressed_texture_astc").getSupportedProfiles().includes("hdr"),etc1Supported:e.extensions.has("WEBGL_compressed_texture_etc1"),etc2Supported:e.extensions.has("WEBGL_compressed_texture_etc"),dxtSupported:e.extensions.has("WEBGL_compressed_texture_s3tc"),bptcSupported:e.extensions.has("EXT_texture_compression_bptc"),pvrtcSupported:e.extensions.has("WEBGL_compressed_texture_pvrtc")||e.extensions.has("WEBKIT_WEBGL_compressed_texture_pvrtc")},"undefined"!=typeof navigator&&void 0!==navigator.platform&&void 0!==navigator.userAgent&&navigator.platform.indexOf("Linux")>=0&&navigator.userAgent.indexOf("Android")<0&&this.workerConfig.astcSupported&&this.workerConfig.etc2Supported&&this.workerConfig.bptcSupported&&this.workerConfig.dxtSupported&&(this.workerConfig.astcSupported=!1,this.workerConfig.etc1Supported=!1,this.workerConfig.etc2Supported=!1)),this}init(){if(!this.transcoderPending){const e=new r.FileLoader(this.manager);e.setWithCredentials(this.withCredentials);const t=new r.FileLoader(this.manager);let n,i;t.setWithCredentials(this.withCredentials),t.setResponseType("arraybuffer"),""===this.transcoderPath?(n=e.loadAsync(un),i=t.loadAsync(cn)):(e.setPath(this.transcoderPath),n=e.loadAsync("basis_transcoder.js"),t.setPath(this.transcoderPath),i=t.loadAsync("basis_transcoder.wasm")),this.transcoderPending=Promise.all([n,i]).then((([e,t])=>{const n=pn.BasisWorker.toString(),r=["/* constants */","let _EngineFormat = "+JSON.stringify(pn.EngineFormat),"let _EngineType = "+JSON.stringify(pn.EngineType),"let _TranscoderFormat = "+JSON.stringify(pn.TranscoderFormat),"let _BasisFormat = "+JSON.stringify(pn.BasisFormat),"/* basis_transcoder.js */",e,"/* worker */",n.substring(n.indexOf("{")+1,n.lastIndexOf("}"))].join("\n");this.workerSourceURL=URL.createObjectURL(new Blob([r])),this.transcoderBinary=t,this.workerPool.setWorkerCreator((()=>{const e=new Worker(this.workerSourceURL),t=this.transcoderBinary.slice(0);return e.postMessage({type:"init",config:this.workerConfig,transcoderBinary:t},[t]),e}))}))}return this.transcoderPending}load(e,t,n,i){if(null===this.workerConfig)throw new Error("THREE.KTX2Loader: Missing initialization with `.detectSupport( renderer )`.");const s=new r.FileLoader(this.manager);s.setPath(this.path),s.setCrossOrigin(this.crossOrigin),s.setWithCredentials(this.withCredentials),s.setRequestHeader(this.requestHeader),s.setResponseType("arraybuffer"),s.load(e,(e=>{this.parse(e,t,i)}),n,i)}parse(e,t,n){if(null===this.workerConfig)throw new Error("THREE.KTX2Loader: Missing initialization with `.detectSupport( renderer )`.");if(hn.has(e)){return hn.get(e).promise.then(t).catch(n)}this._createTexture(e).then((e=>t?t(e):null)).catch(n)}_createTextureFrom(e,t){const{type:n,error:i,data:{faces:s,width:a,height:o,format:l,type:c,dfdFlags:u}}=e;if("error"===n)return Promise.reject(i);let h;if(6===t.faceCount)h=new r.CompressedCubeTexture(s,l,c);else{const e=s[0].mipmaps;h=t.layerCount>1?new r.CompressedArrayTexture(e,a,o,t.layerCount,l,c):new r.CompressedTexture(e,a,o,l,c)}return h.minFilter=1===s[0].mipmaps.length?r.LinearFilter:r.LinearMipmapLinearFilter,h.magFilter=r.LinearFilter,h.generateMipmaps=!1,h.needsUpdate=!0,h.colorSpace=yn(t),h.premultiplyAlpha=!!(1&u),h}async _createTexture(e,t={}){const n=function(e){const t=new Uint8Array(e.buffer,e.byteOffset,je.length);if(t[0]!==je[0]||t[1]!==je[1]||t[2]!==je[2]||t[3]!==je[3]||t[4]!==je[4]||t[5]!==je[5]||t[6]!==je[6]||t[7]!==je[7]||t[8]!==je[8]||t[9]!==je[9]||t[10]!==je[10]||t[11]!==je[11])throw new Error("Missing KTX 2.0 identifier.");const n={vkFormat:0,typeSize:1,pixelWidth:0,pixelHeight:0,pixelDepth:0,layerCount:0,faceCount:1,levelCount:0,supercompressionScheme:0,levels:[],dataFormatDescriptor:[{vendorId:0,descriptorType:0,versionNumber:2,colorModel:0,colorPrimaries:1,transferFunction:2,flags:0,texelBlockDimension:[0,0,0,0],bytesPlane:[0,0,0,0,0,0,0,0],samples:[]}],keyValue:{},globalData:null},r=17*Uint32Array.BYTES_PER_ELEMENT,i=new He(e,je.length,r,!0);n.vkFormat=i._nextUint32(),n.typeSize=i._nextUint32(),n.pixelWidth=i._nextUint32(),n.pixelHeight=i._nextUint32(),n.pixelDepth=i._nextUint32(),n.layerCount=i._nextUint32(),n.faceCount=i._nextUint32(),n.levelCount=i._nextUint32(),n.supercompressionScheme=i._nextUint32();const s=i._nextUint32(),a=i._nextUint32(),o=i._nextUint32(),l=i._nextUint32(),c=i._nextUint64(),u=i._nextUint64(),h=3*Math.max(n.levelCount,1)*8,d=new He(e,je.length+r,h,!0);for(let z=0,B=Math.max(n.levelCount,1);z<B;z++)n.levels.push({levelData:new Uint8Array(e.buffer,e.byteOffset+d._nextUint64(),d._nextUint64()),uncompressedByteLength:d._nextUint64()});const p=new He(e,s,a,!0);p._skip(4);const m=p._nextUint16(),f=p._nextUint16(),g=p._nextUint16(),x=p._nextUint16(),y={vendorId:m,descriptorType:f,versionNumber:g,colorModel:p._nextUint8(),colorPrimaries:p._nextUint8(),transferFunction:p._nextUint8(),flags:p._nextUint8(),texelBlockDimension:[p._nextUint8(),p._nextUint8(),p._nextUint8(),p._nextUint8()],bytesPlane:[p._nextUint8(),p._nextUint8(),p._nextUint8(),p._nextUint8(),p._nextUint8(),p._nextUint8(),p._nextUint8(),p._nextUint8()],samples:[]},v=(x/4-6)/4;for(let z=0;z<v;z++){const e={bitOffset:p._nextUint16(),bitLength:p._nextUint8(),channelType:p._nextUint8(),samplePosition:[p._nextUint8(),p._nextUint8(),p._nextUint8(),p._nextUint8()],sampleLower:Number.NEGATIVE_INFINITY,sampleUpper:Number.POSITIVE_INFINITY};64&e.channelType?(e.sampleLower=p._nextInt32(),e.sampleUpper=p._nextInt32()):(e.sampleLower=p._nextUint32(),e.sampleUpper=p._nextUint32()),y.samples[z]=e}n.dataFormatDescriptor.length=0,n.dataFormatDescriptor.push(y);const b=new He(e,o,l,!0);for(;b._offset<l;){const e=b._nextUint32(),t=b._scan(e),r=We(t);if(n.keyValue[r]=b._nextUint8Array(e-t.byteLength-1),r.match(/^ktx/i)){const e=We(n.keyValue[r]);n.keyValue[r]=e.substring(0,e.lastIndexOf("\0"))}b._skip(e%4?4-e%4:0)}if(u<=0)return n;const w=new He(e,c,u,!0),T=w._nextUint16(),S=w._nextUint16(),_=w._nextUint32(),M=w._nextUint32(),A=w._nextUint32(),E=w._nextUint32(),C=[];for(let z=0,B=Math.max(n.levelCount,1);z<B;z++)C.push({imageFlags:w._nextUint32(),rgbSliceByteOffset:w._nextUint32(),rgbSliceByteLength:w._nextUint32(),alphaSliceByteOffset:w._nextUint32(),alphaSliceByteLength:w._nextUint32()});const R=c+w._offset,D=R+_,k=D+M,I=k+A,P=new Uint8Array(e.buffer,e.byteOffset+R,_),L=new Uint8Array(e.buffer,e.byteOffset+D,M),U=new Uint8Array(e.buffer,e.byteOffset+k,A),F=new Uint8Array(e.buffer,e.byteOffset+I,E);return n.globalData={endpointCount:T,selectorCount:S,imageDescs:C,endpointsData:P,selectorsData:L,tablesData:U,extendedData:F},n}(new Uint8Array(e)),i=n.vkFormat===Ge&&167===n.dataFormatDescriptor[0].colorModel;if(!(0===n.vkFormat||i&&!this.workerConfig.astcHDRSupported))return async function(e){const{vkFormat:t}=e;if(void 0===gn[t])throw new Error("THREE.KTX2Loader: Unsupported vkFormat: "+t);xn[t];let n;2===e.supercompressionScheme&&(dn||(dn=new Promise((async e=>{const t=new ln;await t.init(),e(t)}))),n=await dn);const i=[];for(let o=0;o<e.levels.length;o++){const s=Math.max(1,e.pixelWidth>>o),a=Math.max(1,e.pixelHeight>>o),l=e.pixelDepth?Math.max(1,e.pixelDepth>>o):0,c=e.levels[o];let u,h;if(0===e.supercompressionScheme)u=c.levelData;else{if(2!==e.supercompressionScheme)throw new Error("THREE.KTX2Loader: Unsupported supercompressionScheme.");u=n.decode(c.levelData,c.uncompressedByteLength)}h=xn[t]===r.FloatType?new Float32Array(u.buffer,u.byteOffset,u.byteLength/Float32Array.BYTES_PER_ELEMENT):xn[t]===r.HalfFloatType||xn[t]===r.UnsignedShortType?new Uint16Array(u.buffer,u.byteOffset,u.byteLength/Uint16Array.BYTES_PER_ELEMENT):xn[t]===r.UnsignedInt5999Type||xn[t]===r.UnsignedInt101111Type?new Uint32Array(u.buffer,u.byteOffset,u.byteLength/Uint32Array.BYTES_PER_ELEMENT):u,i.push({data:h,width:s,height:a,depth:l})}const s=0===e.levelCount||i.length>1;let a;if(mn.has(gn[t]))a=0===e.pixelDepth?new r.DataTexture(i[0].data,e.pixelWidth,e.pixelHeight):new r.Data3DTexture(i[0].data,e.pixelWidth,e.pixelHeight,e.pixelDepth),a.minFilter=s?r.NearestMipmapNearestFilter:r.NearestFilter,a.magFilter=r.NearestFilter,a.generateMipmaps=0===e.levelCount,a.normalized=fn.has(t);else{if(e.pixelDepth>0)throw new Error("THREE.KTX2Loader: Unsupported pixelDepth.");a=new r.CompressedTexture(i,e.pixelWidth,e.pixelHeight),a.minFilter=s?r.LinearMipmapLinearFilter:r.LinearFilter,a.magFilter=r.LinearFilter}return a.mipmaps=i,a.type=xn[t],a.format=gn[t],a.colorSpace=yn(e),a.needsUpdate=!0,Promise.resolve(a)}(n);const s=t,a=this.init().then((()=>this.workerPool.postMessage({type:"transcode",buffer:e,taskConfig:s},[e]))).then((e=>this._createTextureFrom(e.data,n)));return hn.set(e,{promise:a}),a}dispose(){this.workerPool.dispose(),this.workerSourceURL&&URL.revokeObjectURL(this.workerSourceURL)}}pn.BasisFormat={ETC1S:0,UASTC:1,UASTC_HDR:2},pn.TranscoderFormat={ETC1:0,ETC2:1,BC1:2,BC3:3,BC4:4,BC5:5,BC7_M6_OPAQUE_ONLY:6,BC7_M5:7,PVRTC1_4_RGB:8,PVRTC1_4_RGBA:9,ASTC_4x4:10,ATC_RGB:11,ATC_RGBA_INTERPOLATED_ALPHA:12,RGBA32:13,RGB565:14,BGR565:15,RGBA4444:16,BC6H:22,RGB_HALF:24,RGBA_HALF:25},pn.EngineFormat={RGBAFormat:r.RGBAFormat,RGBA_ASTC_4x4_Format:r.RGBA_ASTC_4x4_Format,RGB_BPTC_UNSIGNED_Format:r.RGB_BPTC_UNSIGNED_Format,RGBA_BPTC_Format:r.RGBA_BPTC_Format,RGBA_ETC2_EAC_Format:r.RGBA_ETC2_EAC_Format,RGBA_PVRTC_4BPPV1_Format:r.RGBA_PVRTC_4BPPV1_Format,RGBA_S3TC_DXT5_Format:r.RGBA_S3TC_DXT5_Format,RGB_ETC1_Format:r.RGB_ETC1_Format,RGB_ETC2_Format:r.RGB_ETC2_Format,RGB_PVRTC_4BPPV1_Format:r.RGB_PVRTC_4BPPV1_Format,RGBA_S3TC_DXT1_Format:r.RGBA_S3TC_DXT1_Format},pn.EngineType={UnsignedByteType:r.UnsignedByteType,HalfFloatType:r.HalfFloatType,FloatType:r.FloatType},pn.BasisWorker=function(){let e,t,n;const r=_EngineFormat,i=_EngineType,s=_TranscoderFormat,a=_BasisFormat;self.addEventListener("message",(function(r){const s=r.data;switch(s.type){case"init":e=s.config,o=s.transcoderBinary,t=new Promise((e=>{n={wasmBinary:o,onRuntimeInitialized:e},BASIS(n)})).then((()=>{n.initializeBasis(),n.KTX2File}));break;case"transcode":t.then((()=>{try{const{faces:t,buffers:r,width:o,height:h,hasAlpha:d,format:p,type:m,dfdFlags:f}=function(t){const r=new n.KTX2File(new Uint8Array(t));function s(){r.close(),r.delete()}if(!r.isValid())throw s(),new Error("THREE.KTX2Loader:\tInvalid or unsupported .ktx2 file");let o;if(r.isUASTC())o=a.UASTC;else if(r.isETC1S())o=a.ETC1S;else{if(!r.isHDR())throw new Error("THREE.KTX2Loader: Unknown Basis encoding");o=a.UASTC_HDR}const h=r.getWidth(),d=r.getHeight(),p=r.getLayers()||1,m=r.getLevels(),f=r.getFaces(),g=r.getHasAlpha(),x=r.getDFDFlags(),{transcoderFormat:y,engineFormat:v,engineType:b}=function(t,n,r,i){const s=l[t];for(let a=0;a<s.length;a++){const o=s[a];if(o.if&&!e[o.if])continue;if(!o.basisFormat.includes(t))continue;if(i&&o.transcoderFormat.length<2)continue;if(o.needsPowerOfTwo&&(!c(n)||!c(r)))continue;return{transcoderFormat:o.transcoderFormat[i?1:0],engineFormat:o.engineFormat[i?1:0],engineType:o.engineType[0]}}throw new Error("THREE.KTX2Loader: Failed to identify transcoding target.")}(o,h,d,g);if(!h||!d||!m)throw s(),new Error("THREE.KTX2Loader:\tInvalid texture");if(!r.startTranscoding())throw s(),new Error("THREE.KTX2Loader: .startTranscoding failed");const w=[],T=[];for(let e=0;e<f;e++){const t=[];for(let n=0;n<m;n++){const a=[];let o,l;for(let t=0;t<p;t++){const c=r.getImageLevelInfo(n,t,e);0===e&&0===n&&0===t&&(c.origWidth%4!=0||c.origHeight),m>1?(o=c.origWidth,l=c.origHeight):(o=c.width,l=c.height);let u=new Uint8Array(r.getImageTranscodedSizeInBytes(n,t,0,y));const h=r.transcodeImage(u,n,t,e,y,0,-1,-1);if(b===i.HalfFloatType&&(u=new Uint16Array(u.buffer,u.byteOffset,u.byteLength/Uint16Array.BYTES_PER_ELEMENT)),!h)throw s(),new Error("THREE.KTX2Loader: .transcodeImage failed.");a.push(u)}const c=u(a);t.push({data:c,width:o,height:l}),T.push(c.buffer)}w.push({mipmaps:t,width:h,height:d,format:v,type:b})}return s(),{faces:w,buffers:T,width:h,height:d,hasAlpha:g,dfdFlags:x,format:v,type:b}}(s.buffer);self.postMessage({type:"transcode",id:s.id,data:{faces:t,width:o,height:h,hasAlpha:d,format:p,type:m,dfdFlags:f}},r)}catch(t){self.postMessage({type:"error",id:s.id,error:t.message})}}))}var o}));const o=[{if:"astcSupported",basisFormat:[a.UASTC],transcoderFormat:[s.ASTC_4x4,s.ASTC_4x4],engineFormat:[r.RGBA_ASTC_4x4_Format,r.RGBA_ASTC_4x4_Format],engineType:[i.UnsignedByteType],priorityETC1S:1/0,priorityUASTC:1,needsPowerOfTwo:!1},{if:"bptcSupported",basisFormat:[a.ETC1S,a.UASTC],transcoderFormat:[s.BC7_M5,s.BC7_M5],engineFormat:[r.RGBA_BPTC_Format,r.RGBA_BPTC_Format],engineType:[i.UnsignedByteType],priorityETC1S:3,priorityUASTC:2,needsPowerOfTwo:!1},{if:"dxtSupported",basisFormat:[a.ETC1S,a.UASTC],transcoderFormat:[s.BC1,s.BC3],engineFormat:[r.RGBA_S3TC_DXT1_Format,r.RGBA_S3TC_DXT5_Format],engineType:[i.UnsignedByteType],priorityETC1S:4,priorityUASTC:5,needsPowerOfTwo:!1},{if:"etc2Supported",basisFormat:[a.ETC1S,a.UASTC],transcoderFormat:[s.ETC1,s.ETC2],engineFormat:[r.RGB_ETC2_Format,r.RGBA_ETC2_EAC_Format],engineType:[i.UnsignedByteType],priorityETC1S:1,priorityUASTC:3,needsPowerOfTwo:!1},{if:"etc1Supported",basisFormat:[a.ETC1S,a.UASTC],transcoderFormat:[s.ETC1],engineFormat:[r.RGB_ETC1_Format],engineType:[i.UnsignedByteType],priorityETC1S:2,priorityUASTC:4,needsPowerOfTwo:!1},{if:"pvrtcSupported",basisFormat:[a.ETC1S,a.UASTC],transcoderFormat:[s.PVRTC1_4_RGB,s.PVRTC1_4_RGBA],engineFormat:[r.RGB_PVRTC_4BPPV1_Format,r.RGBA_PVRTC_4BPPV1_Format],engineType:[i.UnsignedByteType],priorityETC1S:5,priorityUASTC:6,needsPowerOfTwo:!0},{if:"bptcSupported",basisFormat:[a.UASTC_HDR],transcoderFormat:[s.BC6H],engineFormat:[r.RGB_BPTC_UNSIGNED_Format],engineType:[i.HalfFloatType],priorityHDR:1,needsPowerOfTwo:!1},{basisFormat:[a.ETC1S,a.UASTC],transcoderFormat:[s.RGBA32,s.RGBA32],engineFormat:[r.RGBAFormat,r.RGBAFormat],engineType:[i.UnsignedByteType,i.UnsignedByteType],priorityETC1S:100,priorityUASTC:100,needsPowerOfTwo:!1},{basisFormat:[a.UASTC_HDR],transcoderFormat:[s.RGBA_HALF],engineFormat:[r.RGBAFormat],engineType:[i.HalfFloatType],priorityHDR:100,needsPowerOfTwo:!1}],l={[a.ETC1S]:o.filter((e=>e.basisFormat.includes(a.ETC1S))).sort(((e,t)=>e.priorityETC1S-t.priorityETC1S)),[a.UASTC]:o.filter((e=>e.basisFormat.includes(a.UASTC))).sort(((e,t)=>e.priorityUASTC-t.priorityUASTC)),[a.UASTC_HDR]:o.filter((e=>e.basisFormat.includes(a.UASTC_HDR))).sort(((e,t)=>e.priorityHDR-t.priorityHDR))};function c(e){return e<=2||!(e&e-1)&&0!==e}function u(e){if(1===e.length)return e[0];let t=0;for(let i=0;i<e.length;i++){t+=e[i].byteLength}const n=new Uint8Array(t);let r=0;for(let i=0;i<e.length;i++){const t=e[i];n.set(t,r),r+=t.byteLength}return n}};const mn=new Set([r.RGBAFormat,r.RGBFormat,r.RGFormat,r.RedFormat]),fn=new Set([91]),gn={[me]:r.RGBAFormat,[pe]:r.RGFormat,[de]:r.RedFormat,[he]:r.RGBAFormat,[ce]:r.RGFormat,[le]:r.RedFormat,[ue]:r.RGBAFormat,[oe]:r.RGBAFormat,[ae]:r.RGBAFormat,[se]:r.RGFormat,[ie]:r.RGFormat,[re]:r.RedFormat,[ne]:r.RedFormat,[ge]:r.RGBFormat,[fe]:r.RGBFormat,[De]:r.RGBA_ETC2_EAC_Format,[Re]:r.RGB_ETC2_Format,[ke]:r.R11_EAC_Format,[Ie]:r.SIGNED_R11_EAC_Format,[Pe]:r.RG11_EAC_Format,[Le]:r.SIGNED_RG11_EAC_Format,[Ge]:r.RGBA_ASTC_4x4_Format,[Fe]:r.RGBA_ASTC_4x4_Format,[Ue]:r.RGBA_ASTC_4x4_Format,[qe]:r.RGBA_ASTC_6x6_Format,[Be]:r.RGBA_ASTC_6x6_Format,[ze]:r.RGBA_ASTC_6x6_Format,[be]:r.RGBA_S3TC_DXT1_Format,[ve]:r.RGBA_S3TC_DXT1_Format,[ye]:r.RGB_S3TC_DXT1_Format,[xe]:r.RGB_S3TC_DXT1_Format,[Te]:r.RGBA_S3TC_DXT5_Format,[we]:r.RGBA_S3TC_DXT5_Format,[_e]:r.SIGNED_RED_RGTC1_Format,[Se]:r.RED_RGTC1_Format,[Ae]:r.SIGNED_RED_GREEN_RGTC2_Format,[Me]:r.RED_GREEN_RGTC2_Format,[Ce]:r.RGBA_BPTC_Format,[Ee]:r.RGBA_BPTC_Format,[$e]:r.RGBA_PVRTC_4BPPV1_Format,[Oe]:r.RGBA_PVRTC_4BPPV1_Format,[Ne]:r.RGBA_PVRTC_2BPPV1_Format,[Ve]:r.RGBA_PVRTC_2BPPV1_Format},xn={[me]:r.FloatType,[pe]:r.FloatType,[de]:r.FloatType,[he]:r.HalfFloatType,[ce]:r.HalfFloatType,[le]:r.HalfFloatType,[ue]:r.UnsignedShortType,[oe]:r.UnsignedByteType,[ae]:r.UnsignedByteType,[se]:r.UnsignedByteType,[ie]:r.UnsignedByteType,[re]:r.UnsignedByteType,[ne]:r.UnsignedByteType,[ge]:r.UnsignedInt5999Type,[fe]:r.UnsignedInt101111Type,[De]:r.UnsignedByteType,[Re]:r.UnsignedByteType,[ke]:r.UnsignedByteType,[Ie]:r.UnsignedByteType,[Pe]:r.UnsignedByteType,[Le]:r.UnsignedByteType,[Ge]:r.HalfFloatType,[Fe]:r.UnsignedByteType,[Ue]:r.UnsignedByteType,[qe]:r.HalfFloatType,[Be]:r.UnsignedByteType,[ze]:r.UnsignedByteType,[be]:r.UnsignedByteType,[ve]:r.UnsignedByteType,[ye]:r.UnsignedByteType,[xe]:r.UnsignedByteType,[Te]:r.UnsignedByteType,[we]:r.UnsignedByteType,[_e]:r.UnsignedByteType,[Se]:r.UnsignedByteType,[Ae]:r.UnsignedByteType,[Me]:r.UnsignedByteType,[Ce]:r.UnsignedByteType,[Ee]:r.UnsignedByteType,[$e]:r.UnsignedByteType,[Oe]:r.UnsignedByteType,[Ne]:r.UnsignedByteType,[Ve]:r.UnsignedByteType};function yn(e){const t=e.dataFormatDescriptor[0];return 1===t.colorPrimaries?2===t.transferFunction?r.SRGBColorSpace:r.LinearSRGBColorSpace:10===t.colorPrimaries?2===t.transferFunction?"display-p3":"display-p3-linear":(t.colorPrimaries,r.NoColorSpace)}class vn extends tn{constructor(e){super(e)}}class bn extends r.Object3D{constructor(e=document.createElement("div")){super(),this.isCSS2DObject=!0,this.element=e,this.element.style.position="absolute",this.element.style.userSelect="none",this.element.setAttribute("draggable",!1),this.center=new r.Vector2(.5,.5),this.addEventListener("removed",(function(){this.traverse((function(e){e.element&&e.element instanceof e.element.ownerDocument.defaultView.Element&&null!==e.element.parentNode&&e.element.remove()}))}))}copy(e,t){return super.copy(e,t),this.element=e.element.cloneNode(!0),this.center=e.center,this}}const wn=new r.Vector3,Tn=new r.Matrix4,Sn=new r.Matrix4,_n=new r.Vector3,Mn=new r.Vector3;class An{constructor(e={}){const t=this;let n,r,i,s;const a={objects:new WeakMap},o=void 0!==e.element?e.element:document.createElement("div");function l(e){e.isCSS2DObject&&(e.element.style.display="none");for(let t=0,n=e.children.length;t<n;t++)l(e.children[t])}function c(e,n,r){if(!1!==e.visible){if(e.isCSS2DObject){wn.setFromMatrixPosition(e.matrixWorld),wn.applyMatrix4(Sn);const l=wn.z>=-1&&wn.z<=1&&!0===e.layers.test(r.layers),c=e.element;c.style.display=!0===l?"":"none",!0===l&&(e.onBeforeRender(t,n,r),c.style.transform="translate("+-100*e.center.x+"%,"+-100*e.center.y+"%)translate("+(wn.x*i+i)+"px,"+(-wn.y*s+s)+"px)",c.parentNode!==o&&o.appendChild(c),e.onAfterRender(t,n,r));const h={distanceToCameraSquared:u(r,e)};a.objects.set(e,h)}for(let t=0,i=e.children.length;t<i;t++)c(e.children[t],n,r)}else l(e)}function u(e,t){return _n.setFromMatrixPosition(e.matrixWorld),Mn.setFromMatrixPosition(t.matrixWorld),_n.distanceToSquared(Mn)}o.style.overflow="hidden",this.domElement=o,this.sortObjects=!0,this.getSize=function(){return{width:n,height:r}},this.render=function(e,t){!0===e.matrixWorldAutoUpdate&&e.updateMatrixWorld(),null===t.parent&&!0===t.matrixWorldAutoUpdate&&t.updateMatrixWorld(),Tn.copy(t.matrixWorldInverse),Sn.multiplyMatrices(t.projectionMatrix,Tn),c(e,e,t),this.sortObjects&&function(e){const t=function(e){const t=[];return e.traverseVisible((function(e){e.isCSS2DObject&&t.push(e)})),t}(e).sort((function(e,t){if(e.renderOrder!==t.renderOrder)return t.renderOrder-e.renderOrder;return a.objects.get(e).distanceToCameraSquared-a.objects.get(t).distanceToCameraSquared})),n=t.length;for(let r=0,i=t.length;r<i;r++)t[r].element.style.zIndex=n-r}(e)},this.setSize=function(e,t){n=e,r=t,i=n/2,s=r/2,o.style.width=e+"px",o.style.height=t+"px"}}}class En extends r.InstancedBufferGeometry{constructor(e,t){super(),this.ordering=e,this.setAttribute("position",new r.BufferAttribute(Cn,3)),this.setIndex(new r.BufferAttribute(Rn,1)),this._maxInstanceCount=e.length,this.instanceCount=t,this.attribute=new r.InstancedBufferAttribute(e,1,!1,1),this.attribute.setUsage(r.DynamicDrawUsage),this.setAttribute("splatIndex",this.attribute)}update(e,t){this.ordering=e,this.attribute.array=e,this.instanceCount=t,this.attribute.addUpdateRange(0,t),this.attribute.needsUpdate=!0}}const Cn=new Float32Array([-1,-1,0,1,-1,0,1,1,0,-1,1,0]),Rn=new Uint16Array([0,1,2,0,2,3]),Dn="undefined"==typeof document?require("url").pathToFileURL(__dirname+"/assets/viewer/spark-old-worker-932b4a2c87ca.js").href:new URL("assets/viewer/spark-old-worker-932b4a2c87ca.js",document.currentScript&&"SCRIPT"===document.currentScript.tagName.toUpperCase()&&document.currentScript.src||document.baseURI).href,kn="undefined"==typeof document?require("url").pathToFileURL(__dirname+"/assets/viewer/spark-worker-015de49d2d00.wasm").href:new URL("assets/viewer/spark-worker-015de49d2d00.wasm",document.currentScript&&"SCRIPT"===document.currentScript.tagName.toUpperCase()&&document.currentScript.src||document.baseURI).href;function In(e){const t=new URL(Dn);return t.searchParams.set("wasm",kn),new Worker(t,{name:null==e?void 0:e.name})}var Pn=Uint8Array,Ln=Uint16Array,Un=Int32Array,Fn=new Pn([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),zn=new Pn([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),Bn=new Pn([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Vn=function(e,t){for(var n=new Ln(31),r=0;r<31;++r)n[r]=t+=1<<e[r-1];var i=new Un(n[30]);for(r=1;r<30;++r)for(var s=n[r];s<n[r+1];++s)i[s]=s-n[r]<<5|r;return{b:n,r:i}},On=Vn(Fn,2),Nn=On.b,$n=On.r;Nn[28]=258,$n[258]=28;for(var Gn=Vn(zn,0).b,qn=new Ln(32768),Hn=0;Hn<32768;++Hn){var jn=(43690&Hn)>>1|(21845&Hn)<<1;jn=(61680&(jn=(52428&jn)>>2|(13107&jn)<<2))>>4|(3855&jn)<<4,qn[Hn]=((65280&jn)>>8|(255&jn)<<8)>>1}var Wn=function(e,t,n){for(var r=e.length,i=0,s=new Ln(t);i<r;++i)e[i]&&++s[e[i]-1];var a,o=new Ln(t);for(i=1;i<t;++i)o[i]=o[i-1]+s[i-1]<<1;a=new Ln(1<<t);var l=15-t;for(i=0;i<r;++i)if(e[i])for(var c=i<<4|e[i],u=t-e[i],h=o[e[i]-1]++<<u,d=h|(1<<u)-1;h<=d;++h)a[qn[h]>>l]=c;return a},Xn=new Pn(288);for(Hn=0;Hn<144;++Hn)Xn[Hn]=8;for(Hn=144;Hn<256;++Hn)Xn[Hn]=9;for(Hn=256;Hn<280;++Hn)Xn[Hn]=7;for(Hn=280;Hn<288;++Hn)Xn[Hn]=8;var Yn=new Pn(32);for(Hn=0;Hn<32;++Hn)Yn[Hn]=5;var Kn=Wn(Xn,9),Qn=Wn(Yn,5),Zn=function(e){for(var t=e[0],n=1;n<e.length;++n)e[n]>t&&(t=e[n]);return t},Jn=function(e,t,n){var r=t/8|0;return(e[r]|e[r+1]<<8)>>(7&t)&n},er=function(e,t){var n=t/8|0;return(e[n]|e[n+1]<<8|e[n+2]<<16)>>(7&t)},tr=function(e){return(e+7)/8|0},nr=function(e,t,n){return(null==t||t<0)&&(t=0),(null==n||n>e.length)&&(n=e.length),new Pn(e.subarray(t,n))},rr=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],ir=function(e,t,n){var r=new Error(t||rr[e]);if(r.code=e,Error.captureStackTrace&&Error.captureStackTrace(r,ir),!n)throw r;return r},sr=function(e,t,n,r){var i=e.length,s=r?r.length:0;if(!i||t.f&&!t.l)return n||new Pn(0);var a=!n,o=a||2!=t.i,l=t.i;a&&(n=new Pn(3*i));var c=function(e){var t=n.length;if(e>t){var r=new Pn(Math.max(2*t,e));r.set(n),n=r}},u=t.f||0,h=t.p||0,d=t.b||0,p=t.l,m=t.d,f=t.m,g=t.n,x=8*i;do{if(!p){u=Jn(e,h,1);var y=Jn(e,h+1,3);if(h+=3,!y){var v=e[(D=tr(h)+4)-4]|e[D-3]<<8,b=D+v;if(b>i){l&&ir(0);break}o&&c(d+v),n.set(e.subarray(D,b),d),t.b=d+=v,t.p=h=8*b,t.f=u;continue}if(1==y)p=Kn,m=Qn,f=9,g=5;else if(2==y){var w=Jn(e,h,31)+257,T=Jn(e,h+10,15)+4,S=w+Jn(e,h+5,31)+1;h+=14;for(var _=new Pn(S),M=new Pn(19),A=0;A<T;++A)M[Bn[A]]=Jn(e,h+3*A,7);h+=3*T;var E=Zn(M),C=(1<<E)-1,R=Wn(M,E);for(A=0;A<S;){var D,k=R[Jn(e,h,C)];if(h+=15&k,(D=k>>4)<16)_[A++]=D;else{var I=0,P=0;for(16==D?(P=3+Jn(e,h,3),h+=2,I=_[A-1]):17==D?(P=3+Jn(e,h,7),h+=3):18==D&&(P=11+Jn(e,h,127),h+=7);P--;)_[A++]=I}}var L=_.subarray(0,w),U=_.subarray(w);f=Zn(L),g=Zn(U),p=Wn(L,f),m=Wn(U,g)}else ir(1);if(h>x){l&&ir(0);break}}o&&c(d+131072);for(var F=(1<<f)-1,z=(1<<g)-1,B=h;;B=h){var V=(I=p[er(e,h)&F])>>4;if((h+=15&I)>x){l&&ir(0);break}if(I||ir(2),V<256)n[d++]=V;else{if(256==V){B=h,p=null;break}var O=V-254;if(V>264){var N=Fn[A=V-257];O=Jn(e,h,(1<<N)-1)+Nn[A],h+=N}var $=m[er(e,h)&z],G=$>>4;$||ir(3),h+=15&$;U=Gn[G];if(G>3){N=zn[G];U+=er(e,h)&(1<<N)-1,h+=N}if(h>x){l&&ir(0);break}o&&c(d+131072);var q=d+O;if(d<U){var H=s-U,j=Math.min(U,q);for(H+d<0&&ir(3);d<j;++d)n[d]=r[H+d]}for(;d<q;++d)n[d]=n[d-U]}}t.l=p,t.p=B,t.b=d,t.f=u,p&&(u=1,t.m=f,t.d=m,t.n=g)}while(!u);return d!=n.length&&a?nr(n,0,d):n.subarray(0,d)},ar=new Pn(0),or=function(e,t){return e[t]|e[t+1]<<8},lr=function(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0},cr=function(e,t){return lr(e,t)+4294967296*lr(e,t+4)},ur=function(){function e(e,t){"function"==typeof e&&(t=e,e={}),this.ondata=t;var n=e&&e.dictionary&&e.dictionary.subarray(-32768);this.s={i:0,b:n?n.length:0},this.o=new Pn(32768),this.p=new Pn(0),n&&this.o.set(n)}return e.prototype.e=function(e){if(this.ondata||ir(5),this.d&&ir(4),this.p.length){if(e.length){var t=new Pn(this.p.length+e.length);t.set(this.p),t.set(e,this.p.length),this.p=t}}else this.p=e},e.prototype.c=function(e){this.s.i=+(this.d=e||!1);var t=this.s.b,n=sr(this.p,this.s,this.o);this.ondata(nr(n,t,this.s.b),this.d),this.o=nr(n,this.s.b-32768),this.s.b=this.o.length,this.p=nr(this.p,this.s.p/8|0),this.s.p&=7},e.prototype.push=function(e,t){this.e(e),this.c(t)},e}();function hr(e,t){return sr(e,{i:2},t&&t.out,t&&t.dictionary)}var dr=function(){function e(e,t){this.v=1,this.r=0,ur.call(this,e,t)}return e.prototype.push=function(e,t){if(ur.prototype.e.call(this,e),this.r+=e.length,this.v){var n=this.p.subarray(this.v-1),r=n.length>3?function(e){31==e[0]&&139==e[1]&&8==e[2]||ir(6,"invalid gzip data");var t=e[3],n=10;4&t&&(n+=2+(e[10]|e[11]<<8));for(var r=(t>>3&1)+(t>>4&1);r>0;r-=!e[n++]);return n+(2&t)}(n):4;if(r>n.length){if(!t)return}else this.v>1&&this.onmember&&this.onmember(this.r-n.length);this.p=n.subarray(r),this.v=0}ur.prototype.c.call(this,t),!this.s.f||this.s.l||t||(this.v=tr(this.s.p)+9,this.s={i:0},this.o=new Pn(0),this.push(new Pn(0),t))},e}(),pr="undefined"!=typeof TextDecoder&&new TextDecoder;try{pr.decode(ar,{stream:!0})}catch(Jm){}function mr(e,t){if(t){for(var n="",r=0;r<e.length;r+=16384)n+=String.fromCharCode.apply(null,e.subarray(r,r+16384));return n}if(pr)return pr.decode(e);var i=function(e){for(var t="",n=0;;){var r=e[n++],i=(r>127)+(r>223)+(r>239);if(n+i>e.length)return{s:t,r:nr(e,n-1)};i?3==i?(r=((15&r)<<18|(63&e[n++])<<12|(63&e[n++])<<6|63&e[n++])-65536,t+=String.fromCharCode(55296|r>>10,56320|1023&r)):t+=1&i?String.fromCharCode((31&r)<<6|63&e[n++]):String.fromCharCode((15&r)<<12|(63&e[n++])<<6|63&e[n++]):t+=String.fromCharCode(r)}}(e),s=i.s;return(n=i.r).length&&ir(8),s}var fr=function(e,t){return t+30+or(e,t+26)+or(e,t+28)},gr=function(e,t,n){var r=or(e,t+28),i=mr(e.subarray(t+46,t+46+r),!(2048&or(e,t+8))),s=t+46+r,a=lr(e,t+20),o=n&&4294967295==a?xr(e,s):[a,lr(e,t+24),lr(e,t+42)],l=o[0],c=o[1],u=o[2];return[or(e,t+10),l,c,i,s+or(e,t+30)+or(e,t+32),u]},xr=function(e,t){for(;1!=or(e,t);t+=4+or(e,t+2));return[cr(e,t+12),cr(e,t+4),cr(e,t+20)]};const yr=-12,vr=Math.exp(-30),br=2048,wr=2048;var Tr=(e=>(e.PLY="ply",e.SPZ="spz",e.SPLAT="splat",e.KSPLAT="ksplat",e.PCSOGS="pcsogs",e.PCSOGSZIP="pcsogszip",e.RAD="rad",e))(Tr||{});const Sr={rgbMin:0,rgbMax:1,lnScaleMin:yr,lnScaleMax:9,sh1Max:1,sh2Max:1,sh3Max:1,lodOpacity:!1};function _r(e){return"int"===e||"ivec2"===e||"ivec3"===e||"ivec4"===e}function Mr(e){return"uint"===e||"uvec2"===e||"uvec3"===e||"uvec4"===e}function Ar(e){return function(e){return"float"===e||"vec2"===e||"vec3"===e||"vec4"===e}(e)||function(e){return"mat2"===e||"mat2x2"===e||"mat2x3"===e||"mat2x4"===e||"mat3"===e||"mat3x2"===e||"mat3x3"===e||"mat3x4"===e||"mat4"===e||"mat4x2"===e||"mat4x3"===e||"mat4x4"===e}(e)}function Er(e){return"mat2"===e||"mat2x2"===e}function Cr(e){return"mat3"===e||"mat3x3"===e}function Rr(e){return"mat4"===e||"mat4x4"===e}function Dr(e){return Math.trunc(e).toString()}function kr(e){return`${Math.max(0,Math.trunc(e)).toString()}u`}function Ir(e){return e===Number.POSITIVE_INFINITY?"INFINITY":e===Number.NEGATIVE_INFINITY?"-INFINITY":Number.isInteger(e)?e.toFixed(1):e.toString()}function Pr(e){if(e instanceof Lr)return e.type;return e.dynoOut().type}class Lr{constructor(e){this.__isDynoValue=!0,this.type=e}}class Ur extends Lr{constructor(e,t){super(e.outTypes[t]),this.dyno=e,this.key=t}}class Fr extends Lr{constructor(e,t){super(e),this.literal=t}getLiteral(){return this.literal}}class zr extends Fr{constructor(e,t){super(e,""),this.value=t}getLiteral(){const{type:e,value:t}=this;switch(e){case"bool":return t?"true":"false";case"uint":return kr(t);case"int":return Dr(t);case"float":return Ir(t);case"bvec2":{const e=t;return`bvec2(${e[0]}, ${e[1]})`}case"uvec2":{if(t instanceof r.Vector2)return`uvec2(${kr(t.x)}, ${kr(t.y)})`;const e=t;return`uvec2(${kr(e[0])}, ${kr(e[1])})`}case"ivec2":{if(t instanceof r.Vector2)return`ivec2(${Dr(t.x)}, ${Dr(t.y)})`;const e=t;return`ivec2(${Dr(e[0])}, ${Dr(e[1])})`}case"vec2":{if(t instanceof r.Vector2)return`vec2(${Ir(t.x)}, ${Ir(t.y)})`;const e=t;return`vec2(${Ir(e[0])}, ${Ir(e[1])})`}case"bvec3":{const e=t;return`bvec3(${e[0]}, ${e[1]}, ${e[2]})`}case"uvec3":{if(t instanceof r.Vector3)return`uvec3(${kr(t.x)}, ${kr(t.y)}, ${kr(t.z)})`;const e=t;return`uvec3(${kr(e[0])}, ${kr(e[1])}, ${kr(e[2])})`}case"ivec3":{if(t instanceof r.Vector3)return`ivec3(${Dr(t.x)}, ${Dr(t.y)}, ${Dr(t.z)})`;const e=t;return`ivec3(${Dr(e[0])}, ${Dr(e[1])}, ${Dr(e[2])})`}case"vec3":{if(t instanceof r.Vector3)return`vec3(${Ir(t.x)}, ${Ir(t.y)}, ${Ir(t.z)})`;const e=t;return`vec3(${Ir(e[0])}, ${Ir(e[1])}, ${Ir(e[2])})`}case"bvec4":{const e=t;return`bvec4(${e[0]}, ${e[1]}, ${e[2]}, ${e[3]})`}case"uvec4":{if(t instanceof r.Vector4)return`uvec4(${kr(t.x)}, ${kr(t.y)}, ${kr(t.z)}, ${kr(t.w)})`;const e=t;return`uvec4(${kr(e[0])}, ${kr(e[1])}, ${kr(e[2])}, ${kr(e[3])})`}case"ivec4":{if(t instanceof r.Vector4)return`ivec4(${Dr(t.x)}, ${Dr(t.y)}, ${Dr(t.z)}, ${Dr(t.w)})`;const e=t;return`ivec4(${Dr(e[0])}, ${Dr(e[1])}, ${Dr(e[2])}, ${Dr(e[3])})`}case"vec4":{if(t instanceof r.Vector4)return`vec4(${Ir(t.x)}, ${Ir(t.y)}, ${Ir(t.z)}, ${Ir(t.w)})`;if(t instanceof r.Quaternion)return`vec4(${Ir(t.x)}, ${Ir(t.y)}, ${Ir(t.z)}, ${Ir(t.w)})`;const e=t;return`vec4(${Ir(e[0])}, ${Ir(e[1])}, ${Ir(e[2])}, ${Ir(e[3])})`}case"mat2":case"mat2x2":{const n=t,i=n instanceof r.Matrix2?n.elements:t;return`${e}(${new Array(4).fill(0).map(((e,t)=>Ir(i[t]))).join(", ")})`}case"mat2x3":{const n=t;return`${e}(${new Array(6).fill(0).map(((e,t)=>Ir(n[t]))).join(", ")})`}case"mat2x4":{const n=t;return`${e}(${new Array(8).fill(0).map(((e,t)=>Ir(n[t]))).join(", ")})`}case"mat3":case"mat3x3":{const n=t,i=n instanceof r.Matrix3?n.elements:t;return`${e}(${new Array(9).fill(0).map(((e,t)=>Ir(i[t]))).join(", ")})`}case"mat3x2":{const n=t;return`${e}(${new Array(6).fill(0).map(((e,t)=>Ir(n[t]))).join(", ")})`}case"mat3x4":{const n=t;return`${e}(${new Array(12).fill(0).map(((e,t)=>Ir(n[t]))).join(", ")})`}case"mat4":case"mat4x4":{const n=t,i=n instanceof r.Matrix4?n.elements:t;return`${e}(${new Array(16).fill(0).map(((e,t)=>Ir(i[t]))).join(", ")})`}case"mat4x2":{const n=t;return`${e}(${new Array(8).fill(0).map(((e,t)=>Ir(n[t]))).join(", ")})`}case"mat4x3":{const n=t;return`${e}(${new Array(12).fill(0).map(((e,t)=>Ir(n[t]))).join(", ")})`}default:throw new Error(`Type not implemented: ${String(e)}`)}}}function Br(e,t){return new zr(e,t)}function Vr(e){const t=String(e);if(function(e){return"bool"===e||"bvec2"===e||"bvec3"===e||"bvec4"===e}(e))return`${t}(false)`;if(Ar(e))return`${t}(0.0)`;if(_r(e))return`${t}(0)`;if(Mr(e))return`${t}(0u)`;throw new Error(`Type not implemented: ${t}`)}const Or=" ";class Nr{constructor({indent:e}={}){this.globals=new Set,this.statements=[],this.uniforms={},this.declares=new Set,this.updaters=[],this.sequence=0,this.indent=Or,this.indent=e??Or}nextSequence(){return this.sequence++}}class $r{constructor({inTypes:e,outTypes:t,inputs:n,update:r,globals:i,statements:s,generate:a}){this.inTypes=e??{},this.outTypes=t??{},this.inputs=n??{},this.update=r,this.globals=i,this.statements=s,this.generate=a??(({inputs:e,outputs:t,compile:n})=>{var r,i;return{globals:null==(r=this.globals)?void 0:r.call(this,{inputs:e,outputs:t,compile:n}),statements:null==(i=this.statements)?void 0:i.call(this,{inputs:e,outputs:t,compile:n})}})}get outputs(){const e={};for(const t in this.outTypes)e[t]=new Ur(this,t);return e}apply(e){return Object.assign(this.inputs,e),this.outputs}compile({inputs:e,outputs:t,compile:n}){const r=[`// ${this.constructor.name}(${Object.values(e).join(", ")}) => (${Object.values(t).join(", ")})`],i=[];for(const l in t){const e=t[l];e&&!n.declares.has(e)&&(n.declares.add(e),i.push(l))}const{globals:s,statements:a,uniforms:o}=this.generate({inputs:e,outputs:t,compile:n});for(const l of s??[])n.globals.add(l);for(const l in o)n.uniforms[l]=o[l];this.update&&n.updaters.push(this.update);for(const l of i){const e=t[l];e&&(n.uniforms[e]||r.push(`${jr(e,this.outTypes[l])};`))}return(null==a?void 0:a.length)&&(r.push("{"),r.push(...a.map((e=>n.indent+e))),r.push("}")),r}}class Gr extends $r{constructor({inTypes:e,outTypes:t,inputs:n,update:r,globals:i,construct:s}){super({inTypes:e,outTypes:t,inputs:n,update:r,globals:i,generate:e=>this.generateBlock(e)}),this.construct=s}generateBlock({inputs:e,outputs:t,compile:n}){var r,i;const s={},a={};for(const m in e)null!=e[m]&&(s[m]=new Fr(this.inTypes[m],e[m]));for(const m in t)null!=t[m]&&(a[m]=new Lr(this.outTypes[m]));const o={roots:[]},l=this.construct(s,a,o);for(const m of(null==(r=this.globals)?void 0:r.call(this,{inputs:e,outputs:t,compile:n}))??[])n.globals.add(m);const c=[],u=new Map;function h(e,t,r){let i=u.get(e);if(!i){i={sequence:n.nextSequence(),outNames:new Map,newOuts:new Set},u.set(e,i);for(const t in e.inputs){let n=e.inputs[t];for(;n;){if(n instanceof Lr){n instanceof Ur&&h(n.dyno,n.key);break}if("function"!=typeof n.dynoOut)throw new Error(`dynoOut is not a function for ${n.constructor.name}`);n=n.dynoOut()}}c.push(e)}t&&(r||i.newOuts.add(t),i.outNames.set(t,r??`${t}_${i.sequence}`))}for(const m of o.roots)h(m);for(const m in a){let e=(null==l?void 0:l[m])??a[m];for(;e;){if(e instanceof Lr){e instanceof Ur&&h(e.dyno,e.key,t[m]);break}e=e.dynoOut()}a[m]=e}const d=[];for(const m of c){const e={},t={};for(const n in m.inputs){let t=m.inputs[n];for(;t;){if(t instanceof Lr){if(t instanceof Fr)e[n]=t.getLiteral();else if(t instanceof Ur){const r=null==(i=u.get(t.dyno))?void 0:i.outNames.get(t.key);if(!r)throw new Error(`Source not found for ${t.dyno.constructor.name}.${t.key}`);e[n]=r}break}t=t.dynoOut()}}const r=u.get(m)??{outNames:new Map};for(const[n,i]of r.outNames.entries())t[n]=i;const s=m.compile({inputs:e,outputs:t,compile:n});d.push(s)}const p=[];for(const m in t)a[m]instanceof Fr&&p.push(`${t[m]} = ${a[m].getLiteral()};`);p.length>0&&d.push(p);return{statements:d.flatMap(((e,t)=>0===t?e:["",...e]))}}}function qr(e,t,n,{update:r,globals:i}={}){return new Gr({inTypes:e,outTypes:t,construct:n,update:r,globals:i})}function Hr({inTypes:e,outTypes:t,inputs:n,update:r,globals:i,statements:s,generate:a}){return new $r({inTypes:e,outTypes:t,inputs:n,update:r,globals:i,statements:s,generate:a})}function jr(e,t,n){const r="string"==typeof t?t:t.type;if(!r)throw new Error(`Invalid DynoType: ${String(t)}`);return`${r} ${e}${null!=n?`[${n}]`:""}`}function Wr(e){var t;let n=!1;const r=e.split("\n").map((e=>{const t=e.trimEnd();return n?t:t.length>0?(n=!0,t):null})).filter((e=>null!=e));for(;r.length>0&&0===r[r.length-1].length;)r.pop();if(0===r.length)return[];const i=null==(t=r[0].match(/^\s*/))?void 0:t[0];if(!i)return r;const s=new RegExp(`^${i}`);return r.map((e=>e.replace(s,"")))}function Xr(e){return Wr(e).join("\n")}class Yr extends $r{constructor({a:e,outKey:t,outTypeFunc:n}){const r={a:Pr(e)},i=n(Pr(e));super({inTypes:r,outTypes:{[t]:i},inputs:{a:e}}),this.outKey=t}dynoOut(){return new Ur(this,this.outKey)}}class Kr extends $r{constructor({a:e,b:t,outKey:n,outTypeFunc:r}){const i={a:Pr(e),b:Pr(t)},s=r(Pr(e),Pr(t));super({inTypes:i,outTypes:{[n]:s},inputs:{a:e,b:t}}),this.outKey=n}dynoOut(){return new Ur(this,this.outKey)}}const Qr=Number.parseInt(r.REVISION)>=179,Zr=new Float32Array(1),Jr=new Uint32Array(Zr.buffer),ei="Float16Array"in globalThis,ti=ei?new globalThis.Float16Array(1):null,ni=new Uint16Array(null==ti?void 0:ti.buffer);function ri(e){return Zr[0]=e,Jr[0]}function ii(e){return Jr[0]=e,Zr[0]}const si=ei?function(e){return ti[0]=e,ni[0]}:function(e){Zr[0]=e;const t=Jr[0],n=t>>23&255,r=8388607&t,i=(t>>31&1)<<15;if(255===n)return 0!==r?32767|i:31744|i;const s=n-127+15;if(s>=31)return 31744|i;if(s<=0){if(s<-10)return i;return i|(8388608|r)>>1-s+13}return i|s<<10|r>>13},ai=ei?function(e){return ni[0]=e,ti[0]}:function(e){const t=e>>15&1,n=e>>10&31,r=1023&e;let i;if(0===n)if(0===r)i=t<<31;else{let e=r,n=-14;for(;!(1024&e);)e<<=1,n--;e&=1023;i=t<<31|n+127<<23|e<<13}else if(31===n)i=0===r?t<<31|2139095040:t<<31|2143289344;else{i=t<<31|n-15+127<<23|r<<13}return Jr[0]=i,Zr[0]};function oi(e){return Math.max(0,Math.min(255,Math.round(255*e)))}function li(e){const t=[],n=new Set;return function e(r){r&&"object"==typeof r&&!n.has(r)&&(n.add(r),r instanceof ArrayBuffer?t.push(r):ArrayBuffer.isView(r)?t.push(r.buffer):Array.isArray(r)?r.forEach(e):Object.values(r).forEach(e))}(e),t}class ci{constructor({allocate:e,dispose:t,valid:n}){this.items=[],this.allocate=e,this.dispose=t,this.valid=n}alloc(e){for(;;){const t=this.items.pop();if(!t)break;if(this.valid(t,e))return t;this.dispose&&this.dispose(t)}return this.allocate(e)}free(e){this.items.push(e)}disposeAll(){let e;for(e=this.items.pop();e;)this.dispose&&this.dispose(e),e=this.items.pop()}}function ui(e,t,n,r,i,s,a,o,l,c,u,h,d,p,m,f){const g=4*t,[x,y]=e;x[g]=ri(n),x[g+1]=ri(r),x[g+2]=ri(i),x[g+3]=si(d),y[g]=si(p)|si(m)<<16,y[g+1]=si(f)|si(Math.log(s))<<16,y[g+2]=si(Math.log(a))|si(Math.log(o))<<16,y[g+3]=function(e,t,n,r){const i=Math.sqrt(e*e+t*t+n*n+r*r),s=(r<0?-e:e)/i,a=(r<0?-t:t)/i,o=(r<0?-n:n)/i,l=(r<0?-r:r)/i,c=2*Math.acos(l),u=Math.sqrt(s*s+a*a+o*o),h=u<1e-6?1:s/u,d=u<1e-6?0:a/u,p=u<1e-6?0:o/u,m=Math.abs(h)+Math.abs(d)+Math.abs(p);let f=h/m,g=d/m;if(p<0){const e=f;f=(1-Math.abs(g))*(f>=0?1:-1),g=(1-Math.abs(e))*(g>=0?1:-1)}const x=.5*f+.5,y=.5*g+.5,v=Math.round(1023*x),b=Math.round(1023*y);return Math.round(c*(4095/Math.PI))<<20|b<<10|v}(l,c,u,h)}function hi(e,t){const n=mi,r=4*t,[i,s]=e;return n.center.x=ii(i[r]),n.center.y=ii(i[r+1]),n.center.z=ii(i[r+2]),n.opacity=ai(65535&i[r+3]),n.color.r=ai(65535&s[r]),n.color.g=ai(s[r]>>>16),n.color.b=ai(65535&s[r+1]),n.scales.x=Math.exp(ai(s[r+1]>>>16)),n.scales.y=Math.exp(ai(65535&s[r+2])),n.scales.z=Math.exp(ai(s[r+2]>>>16)),function(e,t){const n=e>>>20&4095;let r=2*((1023&e)/1023-.5),i=2*((e>>>10&1023)/1023-.5);const s=1-(Math.abs(r)+Math.abs(i)),a=Math.max(-s,0);r+=r>=0?-a:a,i+=i>=0?-a:a;const o=Math.sqrt(r*r+i*i+s*s),l=o<1e-6?0:r/o,c=o<1e-6?0:i/o,u=o<1e-6?0:s/o,h=n/4095*Math.PI*.5,d=Math.sin(h),p=Math.cos(h);t.set(l*d,c*d,u*d,p)}(s[r+3],n.quaternion),n}function di(e,t,n,r,i,s,a,o,l,c,u,h,d,p,m,f,g){const x=(null==g?void 0:g.rgbMin)??0,y=((null==g?void 0:g.rgbMax)??1)-x,v=oi((p-x)/y),b=oi((m-x)/y),w=oi((f-x)/y),T=oi((null==g?void 0:g.lodOpacity)?.5*d:d),S=function(e){const t=Ti.copy(e).normalize();t.w<0&&t.set(-t.x,-t.y,-t.z,-t.w);const n=2*Math.acos(t.w),r=Math.sqrt(t.x*t.x+t.y*t.y+t.z*t.z),i=r<1e-6?Si.set(1,0,0):Si.set(t.x,t.y,t.z).divideScalar(r),s=Math.abs(i.x)+Math.abs(i.y)+Math.abs(i.z);let a=i.x/s,o=i.y/s;if(i.z<0){const e=a;a=(1-Math.abs(o))*(a>=0?1:-1),o=(1-Math.abs(e))*(o>=0?1:-1)}const l=.5*a+.5,c=.5*o+.5,u=Math.round(255*l),h=Math.round(255*c);return Math.round(n*(255/Math.PI))<<16|h<<8|u}(pi.set(l,c,u,h)),_=255&S,M=S>>>8&255,A=S>>>16&255,E=(null==g?void 0:g.lnScaleMin)??yr,C=254/(((null==g?void 0:g.lnScaleMax)??9)-E),R=s<vr?0:Math.min(255,Math.max(1,Math.round((Math.log(s)-E)*C)+1)),D=a<vr?0:Math.min(255,Math.max(1,Math.round((Math.log(a)-E)*C)+1)),k=o<vr?0:Math.min(255,Math.max(1,Math.round((Math.log(o)-E)*C)+1)),I=si(n),P=si(r),L=si(i),U=4*t;e[U]=v|b<<8|w<<16|T<<24,e[U+1]=I|P<<16,e[U+2]=L|_<<16|M<<24,e[U+3]=R|D<<8|k<<16|A<<24}const pi=new r.Quaternion,mi={center:new r.Vector3,scales:new r.Vector3,quaternion:new r.Quaternion,color:new r.Color,opacity:0};function fi(e,t,n){const r=mi,i=4*t,s=e[i],a=e[i+1],o=e[i+2],l=e[i+3],c=(null==n?void 0:n.rgbMin)??0,u=((null==n?void 0:n.rgbMax)??1)-c;r.color.set(c+(255&s)/255*u,c+(s>>>8&255)/255*u,c+(s>>>16&255)/255*u),r.opacity=(s>>>24&255)/255,(null==n?void 0:n.lodOpacity)&&(r.opacity=2*r.opacity),r.center.set(ai(65535&a),ai(a>>>16&65535),ai(65535&o));const h=(null==n?void 0:n.lnScaleMin)??yr,d=(((null==n?void 0:n.lnScaleMax)??9)-h)/254,p=255&l;r.scales.x=0===p?0:Math.exp(h+(p-1)*d);const m=l>>>8&255;r.scales.y=0===m?0:Math.exp(h+(m-1)*d);const f=l>>>16&255;r.scales.z=0===f?0:Math.exp(h+(f-1)*d);return function(e,t){const n=e>>>16&255;let r=2*((255&e)/255-.5),i=2*((e>>>8&255)/255-.5);const s=1-(Math.abs(r)+Math.abs(i)),a=Math.max(-s,0);r+=r>=0?-a:a,i+=i>=0?-a:a;const o=Si.set(r,i,s).normalize(),l=n/255*Math.PI*.5,c=Math.sin(l),u=Math.cos(l);t.set(o.x*c,o.y*c,o.z*c,u)}(o>>>16&65535|l>>>8&16711680,r.quaternion),r}function gi(e){const t=br,n=Math.max(1,Math.min(wr,Math.ceil(e/t))),r=Math.ceil(e/(t*n));return{width:t,height:n,depth:r,maxSplats:t*n*r}}function xi(){return!navigator.platform.toLowerCase().startsWith("win")&&(navigator.maxTouchPoints>0||/Mobi|Android|iPhone|iPad|iPod|Opera Mini|IEMobile/.test(navigator.userAgent))}function yi(){return/iPhone|iPad/.test(navigator.userAgent)}function vi(e){const t=new r.Clock(e.autoStart);return t.startTime=e.startTime,t.oldTime=e.oldTime,t.elapsedTime=e.elapsedTime,t.running=e.running,t}const bi=Xr("\n precision highp float;\n\n in vec3 position;\n\n void main() {\n gl_Position = vec4(position.xy, 0.0, 1.0);\n }\n");function wi({matrix1:e,matrix2:t,maxDistance:n,minCoorient:i}){const{distance:s,coorient:a}=function(e,t){const[n,i]=[new r.Vector3,new r.Quaternion],[s,a]=[new r.Vector3,new r.Quaternion];return e.decompose(n,i,new r.Vector3),t.decompose(s,a,new r.Vector3),{distance:n.distanceTo(s),coorient:Math.abs(i.dot(a))}}(e,t);return s<=n&&(null==i||a>=i)}const Ti=new r.Quaternion,Si=new r.Vector3;class _i{constructor(){this.messages={},this.messageIdNext=0,this.worker=new In,this.worker.onmessage=e=>this.onMessage(e)}makeMessageId(){return++this.messageIdNext}makeMessagePromiseId(){const e=this.makeMessageId(),t=new Promise(((t,n)=>{this.messages[e]={resolve:t,reject:n}}));return{id:e,promise:t}}onMessage(e){const{id:t,result:n,error:r}=e.data,i=this.messages[t];i&&(delete this.messages[t],r?i.reject(r):i.resolve(n))}async call(e,t){const{id:n,promise:r}=this.makeMessagePromiseId();return this.worker.postMessage({name:e,args:t,id:n},{transfer:li(t)}),r}}let Mi=0;const Ai=[],Ei=[];async function Ci(e){const t=await async function(){const e=Ai.shift();if(e)return e;if(Mi<4){const e=new _i;return Mi+=1,e}return new Promise((e=>{Ei.push(e)}))}();try{return await e(t)}finally{!function(e){if(Mi>4)return void(Mi-=1);const t=Ei.shift();t?t(e):Ai.push(e)}(t)}}const Ri="undefined"==typeof document?require("url").pathToFileURL(__dirname+"/assets/viewer/spark-worker-5ec8a483b87c.js").href:new URL("assets/viewer/spark-worker-5ec8a483b87c.js",document.currentScript&&"SCRIPT"===document.currentScript.tagName.toUpperCase()&&document.currentScript.src||document.baseURI).href,Di="undefined"==typeof document?require("url").pathToFileURL(__dirname+"/assets/viewer/spark-worker-015de49d2d00.wasm").href:new URL("assets/viewer/spark-worker-015de49d2d00.wasm",document.currentScript&&"SCRIPT"===document.currentScript.tagName.toUpperCase()&&document.currentScript.src||document.baseURI).href;function ki(e){const t=new URL(Ri);return t.searchParams.set("wasm",Di),new Worker(t,{name:null==e?void 0:e.name})}const Ii=class e{constructor(){this.queue=null,this.messages={},this.worker=new ki,this.worker.onmessage=e=>this.onMessage(e)}onMessage(e){var t;const{id:n,result:r,error:i,status:s}=e.data,a=this.messages[n];a&&(void 0!==i?(delete this.messages[n],a.reject(i)):void 0!==s?null==(t=a.onStatus)||t.call(a,s):(delete this.messages[n],a.resolve(r)))}tryExclusive(e){return null==this.queue?this.exclusive(e):null}async exclusive(e){const t=this.queue;null!=t?await new Promise((e=>{t.push((()=>e(void 0)))})):this.queue=[];try{return await e(this)}finally{if(null!=this.queue)if(0===this.queue.length)this.queue=null;else{this.queue.shift()()}}}async call(t,n,r={}){const i=++e.currentId,s=new Promise(((e,t)=>{this.messages[i]={resolve:e,reject:t,onStatus:r.onStatus}}));return this.worker.postMessage({id:i,name:t,args:n},{transfer:li(n)}),await s}dispose(){this.worker.terminate();const e=Object.values(this.messages);this.messages={};for(const t of e)t.reject(new Error("Worker terminate"))}};Ii.currentId=0;let Pi=Ii;const Li=new class{constructor(e=4){this.numWorkers=0,this.freelist=[],this.queue=[],this.maxWorkers=e}async withWorker(e){const t=await this.allocWorker();try{return await e(t)}finally{this.freeWorker(t)}}async allocWorker(){const e=this.freelist.pop();if(e)return e;if(this.numWorkers<this.maxWorkers){const e=new Pi;return this.numWorkers+=1,e}return new Promise((e=>{this.queue.push(e)}))}freeWorker(e){if(this.numWorkers>this.maxWorkers)return void(this.numWorkers-=1);const t=this.queue.shift();t?t(e):this.freelist.push(e)}},Ui={type:"Gsplat"},Fi={type:"CovSplat"},zi={type:"PackedSplats"},Bi={type:"ExtSplats"},Vi=(e,t)=>new Ki({packedSplats:e,index:t}),Oi=e=>new ts({gsplat:e}),Ni=e=>new ns({gsplat:e}),$i=({gsplat:e,flags:t,index:n,center:r,scales:i,quaternion:s,rgba:a,rgb:o,opacity:l,x:c,y:u,z:h,r:d,g:p,b:m})=>new rs({gsplat:e,flags:t,index:n,center:r,scales:i,quaternion:s,rgba:a,rgb:o,opacity:l,x:c,y:u,z:h,r:d,g:p,b:m}),Gi=(e,{scale:t,rotate:n,translate:r,recolor:i})=>new is({gsplat:e,scale:t,rotate:n,translate:r,recolor:i}),qi=e=>new cs({index:e}),Hi=e=>new us({index:e}),ji=Xr("\n struct Gsplat {\n vec3 center;\n uint flags;\n vec3 scales;\n int index;\n vec4 quaternion;\n vec4 rgba;\n };\n const uint GSPLAT_FLAG_ACTIVE = 1u << 0u;\n\n bool isGsplatActive(uint flags) {\n return (flags & GSPLAT_FLAG_ACTIVE) != 0u;\n }\n"),Wi=Xr("\n struct CovSplat {\n vec3 center;\n uint flags;\n vec4 rgba;\n vec3 xxyyzz;\n int index;\n vec3 xyxzyz;\n };\n\n bool isCovSplatActive(uint flags) {\n return (flags & GSPLAT_FLAG_ACTIVE) != 0u;\n }\n"),Xi=Xr("\n struct PackedSplats {\n usampler2DArray textureArray;\n int numSplats;\n vec4 rgbMinMaxLnScaleMinMax;\n bool lodOpacity;\n };\n"),Yi=Xr("\n bool readPackedArray(usampler2DArray texture, int numSplats, vec4 rgbMinMaxLnScaleMinMax, int index, out Gsplat gsplat) {\n if ((index >= 0) && (index < numSplats)) {\n uvec4 packedData = texelFetch(texture, splatTexCoord(index), 0);\n unpackSplatEncoding(packedData, gsplat.center, gsplat.scales, gsplat.quaternion, gsplat.rgba, rgbMinMaxLnScaleMinMax);\n return true;\n } else {\n return false;\n }\n }\n");class Ki extends $r{constructor({packedSplats:e,index:t}){super({inTypes:{packedSplats:zi,index:"int"},outTypes:{gsplat:Ui},inputs:{packedSplats:e,index:t},globals:()=>[ji,Xi,Yi],statements:({inputs:e,outputs:t})=>{const{gsplat:n}=t;if(!n)return[];const{packedSplats:r,index:i}=e;let s;return s=r&&i?Wr(`\n ${n}.flags = 0u;\n if (readPackedArray(${r}.textureArray, ${r}.numSplats, ${r}.rgbMinMaxLnScaleMinMax, ${i}, ${n})) {\n if (${r}.lodOpacity) {\n ${n}.rgba.a = 2.0 * ${n}.rgba.a;\n }\n bool zeroSize = all(equal(${n}.scales, vec3(0.0, 0.0, 0.0)));\n ${n}.flags = zeroSize ? 0u : GSPLAT_FLAG_ACTIVE;\n }\n `):[`${n}.flags = 0u;`],s.push(`${n}.index = ${i??"0"};`),s}})}dynoOut(){return new Ur(this,"gsplat")}}class Qi extends $r{constructor({packedSplats:e,index:t,base:n,count:r}){super({inTypes:{packedSplats:zi,index:"int",base:"int",count:"int"},outTypes:{gsplat:Ui},inputs:{packedSplats:e,index:t,base:n,count:r},globals:()=>[ji,Xi,Yi],statements:({inputs:e,outputs:t})=>{const{gsplat:n}=t;if(!n)return[];const{packedSplats:r,index:i,base:s,count:a}=e;let o;return o=r&&i&&s&&a?Wr(`\n ${n}.flags = 0u;\n if (readPackedArray(${r}.textureArray, ${r}.numSplats, ${r}.rgbMinMaxLnScaleMinMax, ${i}, ${n})) {\n if (${r}.lodOpacity) {\n ${n}.rgba.a = 2.0 * ${n}.rgba.a;\n }\n bool zeroSize = all(equal(${n}.scales, vec3(0.0, 0.0, 0.0)));\n ${n}.flags = zeroSize ? 0u : GSPLAT_FLAG_ACTIVE;\n }\n `):[`${n}.flags = 0u;`],o.push(`${n}.index = ${i??"0"};`),o}})}dynoOut(){return new Ur(this,"gsplat")}}const Zi=Xr("\n struct ExtSplats {\n usampler2DArray textureArray1;\n usampler2DArray textureArray2;\n int numSplats;\n };\n"),Ji=Xr("\n void readExtArrays(usampler2DArray texture1, usampler2DArray texture2, int numSplats, int index, out Gsplat gsplat) {\n gsplat.flags = 0u;\n if ((index >= 0) && (index < numSplats)) {\n ivec3 coord = splatTexCoord(index);\n uvec4 packed1 = texelFetch(texture1, coord, 0);\n uvec4 packed2 = texelFetch(texture2, coord, 0);\n unpackSplatExt(packed1, packed2, gsplat.center, gsplat.scales, gsplat.quaternion, gsplat.rgba);\n gsplat.flags = all(equal(gsplat.scales, vec3(0.0, 0.0, 0.0))) ? 0u : GSPLAT_FLAG_ACTIVE;\n gsplat.index = index;\n }\n }\n");class es extends $r{constructor({extSplats:e,index:t}){super({inTypes:{extSplats:Bi,index:"int"},outTypes:{gsplat:Ui},inputs:{extSplats:e,index:t},globals:()=>[ji,Zi,Ji],statements:({inputs:e,outputs:t})=>{const{gsplat:n}=t;if(!n)return[`${n}.flags = 0u;`];const{extSplats:r,index:i}=e;return r&&i?Wr(`\n readExtArrays(${r}.textureArray1, ${r}.textureArray2, ${r}.numSplats, ${i}, ${n});\n `):[`${n}.flags = 0u;`]}})}dynoOut(){return new Ur(this,"gsplat")}}Xr("\n void readCovArrays(usampler2DArray texture1, usampler2DArray texture2, int numSplats, int index, out CovSplat covsplat) {\n covsplat.flags = 0u;\n if ((index >= 0) && (index < numSplats)) {\n ivec3 coord = splatTexCoord(index);\n uvec4 packed1 = texelFetch(texture1, coord, 0);\n uvec4 packed2 = texelFetch(texture2, coord, 0);\n unpackSplatExtCov(packed1, packed2, covsplat.center, covsplat.rgba, covsplat.xxyyzz, covsplat.xyxzyz);\n covsplat.flags = (all(equal(covsplat.xxyyzz, vec3(0.0))) && all(equal(covsplat.xyxzyz, vec3(0.0)))) ? 0u : GSPLAT_FLAG_ACTIVE;\n gsplat.index = index;\n }\n }\n");class ts extends $r{constructor({gsplat:e}){super({inTypes:{gsplat:Ui},outTypes:{covsplat:Fi},inputs:{gsplat:e},globals:()=>[ji,Wi],statements:({inputs:e,outputs:t})=>{const{gsplat:n}=e,{covsplat:r}=t;return n?Wr(`\n ${r}.flags = 0u;\n if (isGsplatActive(${n}.flags)) {\n ${r}.flags = ${n}.flags;\n ${r}.index = ${n}.index;\n ${r}.rgba = ${n}.rgba;\n ${r}.center = ${n}.center;\n mat3 m = scaleQuaternionToMatrix(${n}.scales, ${n}.quaternion);\n m = m * transpose(m);\n ${r}.xxyyzz = vec3(m[0][0], m[1][1], m[2][2]);\n ${r}.xyxzyz = vec3(m[0][1], m[0][2], m[1][2]);\n }\n `):[`${r}.flags = 0u;`]}})}dynoOut(){return new Ur(this,"covsplat")}}class ns extends $r{constructor({gsplat:e}){super({inTypes:{gsplat:Ui},outTypes:{flags:"uint",active:"bool",index:"int",center:"vec3",scales:"vec3",quaternion:"vec4",rgba:"vec4",rgb:"vec3",opacity:"float",x:"float",y:"float",z:"float",r:"float",g:"float",b:"float"},inputs:{gsplat:e},globals:()=>[ji],statements:({inputs:e,outputs:t})=>{const{gsplat:n}=e,{flags:r,active:i,index:s,center:a,scales:o,quaternion:l,rgba:c,rgb:u,opacity:h,x:d,y:p,z:m,r:f,g:g,b:x}=t;return[r?`${r} = ${n?`${n}.flags`:"0u"};`:null,i?`${i} = isGsplatActive(${n?`${n}.flags`:"0u"});`:null,s?`${s} = ${n?`${n}.index`:"0"};`:null,a?`${a} = ${n?`${n}.center`:"vec3(0.0, 0.0, 0.0)"};`:null,o?`${o} = ${n?`${n}.scales`:"vec3(0.0, 0.0, 0.0)"};`:null,l?`${l} = ${n?`${n}.quaternion`:"vec4(0.0, 0.0, 0.0, 1.0)"};`:null,c?`${c} = ${n?`${n}.rgba`:"vec4(0.0, 0.0, 0.0, 0.0)"};`:null,u?`${u} = ${n?`${n}.rgba.rgb`:"vec3(0.0, 0.0, 0.0)"};`:null,h?`${h} = ${n?`${n}.rgba.a`:"0.0"};`:null,d?`${d} = ${n?`${n}.center.x`:"0.0"};`:null,p?`${p} = ${n?`${n}.center.y`:"0.0"};`:null,m?`${m} = ${n?`${n}.center.z`:"0.0"};`:null,f?`${f} = ${n?`${n}.rgba.r`:"0.0"};`:null,g?`${g} = ${n?`${n}.rgba.g`:"0.0"};`:null,x?`${x} = ${n?`${n}.rgba.b`:"0.0"};`:null].filter(Boolean)}})}}class rs extends $r{constructor({gsplat:e,flags:t,index:n,center:r,scales:i,quaternion:s,rgba:a,rgb:o,opacity:l,x:c,y:u,z:h,r:d,g:p,b:m}){super({inTypes:{gsplat:Ui,flags:"uint",index:"int",center:"vec3",scales:"vec3",quaternion:"vec4",rgba:"vec4",rgb:"vec3",opacity:"float",x:"float",y:"float",z:"float",r:"float",g:"float",b:"float"},outTypes:{gsplat:Ui},inputs:{gsplat:e,flags:t,index:n,center:r,scales:i,quaternion:s,rgba:a,rgb:o,opacity:l,x:c,y:u,z:h,r:d,g:p,b:m},globals:()=>[ji],statements:({inputs:e,outputs:t})=>{const{gsplat:n}=t;if(!n)return[];const{gsplat:r,flags:i,index:s,center:a,scales:o,quaternion:l,rgba:c,rgb:u,opacity:h,x:d,y:p,z:m,r:f,g:g,b:x}=e;return[`${n}.flags = ${i??(r?`${r}.flags`:"0u")};`,`${n}.index = ${s??(r?`${r}.index`:"0")};`,`${n}.center = ${a??(r?`${r}.center`:"vec3(0.0, 0.0, 0.0)")};`,`${n}.scales = ${o??(r?`${r}.scales`:"vec3(0.0, 0.0, 0.0)")};`,`${n}.quaternion = ${l??(r?`${r}.quaternion`:"vec4(0.0, 0.0, 0.0, 1.0)")};`,`${n}.rgba = ${c??(r?`${r}.rgba`:"vec4(0.0, 0.0, 0.0, 0.0)")};`,u?`${n}.rgba.rgb = ${u};`:null,h?`${n}.rgba.a = ${h};`:null,d?`${n}.center.x = ${d};`:null,p?`${n}.center.y = ${p};`:null,m?`${n}.center.z = ${m};`:null,f?`${n}.rgba.r = ${f};`:null,g?`${n}.rgba.g = ${g};`:null,x?`${n}.rgba.b = ${x};`:null].filter(Boolean)}})}dynoOut(){return new Ur(this,"gsplat")}}Xr("\n vec3 gsplatNormal(vec3 scales, vec4 quaternion) {\n float minScale = min(scales.x, min(scales.y, scales.z));\n vec3 normal;\n if (scales.z == minScale) {\n normal = vec3(0.0, 0.0, 1.0);\n } else if (scales.y == minScale) {\n normal = vec3(0.0, 1.0, 0.0);\n } else {\n normal = vec3(1.0, 0.0, 0.0);\n }\n return quatVec(quaternion, normal);\n }\n");class is extends $r{constructor({gsplat:e,scale:t,rotate:n,translate:r,recolor:i}){super({inTypes:{gsplat:Ui,scale:"float",rotate:"vec4",translate:"vec3",recolor:"vec4"},outTypes:{gsplat:Ui},inputs:{gsplat:e,scale:t,rotate:n,translate:r,recolor:i},globals:()=>[ji],statements:({inputs:e,outputs:t,compile:n})=>{const{gsplat:r}=t;if(!r||!e.gsplat)return[];const{scale:i,rotate:s,translate:a,recolor:o}=e,l=n.indent;return[`${r} = ${e.gsplat};`,`if (isGsplatActive(${r}.flags)) {`,i?`${l}${r}.center *= ${i};`:null,s?`${l}${r}.center = quatVec(${s}, ${r}.center);`:null,a?`${l}${r}.center += ${a};`:null,i?`${l}${r}.scales *= ${i};`:null,s?`${l}${r}.quaternion = quatQuat(${s}, ${r}.quaternion);`:null,o?`${l}${r}.rgba *= ${o};`:null,"}"].filter(Boolean)}})}dynoOut(){return new Ur(this,"gsplat")}}const ss=e=>new os({covsplat:e}),as=({covsplat:e,flags:t,index:n,center:r,rgba:i,rgb:s,opacity:a,x:o,y:l,z:c,r:u,g:h,b:d})=>new ls({covsplat:e,flags:t,index:n,center:r,rgba:i,rgb:s,opacity:a,x:o,y:l,z:c,r:u,g:h,b:d});class os extends $r{constructor({covsplat:e}){super({inTypes:{covsplat:Fi},outTypes:{flags:"uint",active:"bool",index:"int",center:"vec3",rgba:"vec4",rgb:"vec3",opacity:"float",x:"float",y:"float",z:"float",r:"float",g:"float",b:"float"},inputs:{covsplat:e},globals:()=>[Wi],statements:({inputs:e,outputs:t})=>{const{covsplat:n}=e,{flags:r,active:i,index:s,center:a,rgba:o,rgb:l,opacity:c,x:u,y:h,z:d,r:p,g:m,b:f}=t;return[r?`${r} = ${n?`${n}.flags`:"0u"};`:null,i?`${i} = isCovSplatActive(${n?`${n}.flags`:"0u"});`:null,s?`${s} = ${n?`${n}.index`:"0"};`:null,a?`${a} = ${n?`${n}.center`:"vec3(0.0, 0.0, 0.0)"};`:null,o?`${o} = ${n?`${n}.rgba`:"vec4(0.0, 0.0, 0.0, 0.0)"};`:null,l?`${l} = ${n?`${n}.rgba.rgb`:"vec3(0.0, 0.0, 0.0)"};`:null,c?`${c} = ${n?`${n}.rgba.a`:"0.0"};`:null,u?`${u} = ${n?`${n}.center.x`:"0.0"};`:null,h?`${h} = ${n?`${n}.center.y`:"0.0"};`:null,d?`${d} = ${n?`${n}.center.z`:"0.0"};`:null,p?`${p} = ${n?`${n}.rgba.r`:"0.0"};`:null,m?`${m} = ${n?`${n}.rgba.g`:"0.0"};`:null,f?`${f} = ${n?`${n}.rgba.b`:"0.0"};`:null].filter(Boolean)}})}}class ls extends $r{constructor({covsplat:e,flags:t,index:n,center:r,rgba:i,rgb:s,opacity:a,x:o,y:l,z:c,r:u,g:h,b:d}){super({inTypes:{covsplat:Fi,flags:"uint",index:"int",center:"vec3",rgba:"vec4",rgb:"vec3",opacity:"float",x:"float",y:"float",z:"float",r:"float",g:"float",b:"float"},outTypes:{covsplat:Fi},inputs:{covsplat:e,flags:t,index:n,center:r,rgba:i,rgb:s,opacity:a,x:o,y:l,z:c,r:u,g:h,b:d},globals:()=>[Wi],statements:({inputs:e,outputs:t})=>{const{covsplat:n}=t;if(!n)return[];const{covsplat:r,flags:i,index:s,center:a,rgba:o,rgb:l,opacity:c,x:u,y:h,z:d,r:p,g:m,b:f}=e;return[`${n}.flags = ${i??(r?`${r}.flags`:"0u")};`,`${n}.index = ${s??(r?`${r}.index`:"0")};`,`${n}.center = ${a??(r?`${r}.center`:"vec3(0.0, 0.0, 0.0)")};`,`${n}.rgba = ${o??(r?`${r}.rgba`:"vec4(0.0, 0.0, 0.0, 0.0)")};`,l?`${n}.rgba.rgb = ${l};`:null,c?`${n}.rgba.a = ${c};`:null,u?`${n}.center.x = ${u};`:null,h?`${n}.center.y = ${h};`:null,d?`${n}.center.z = ${d};`:null,p?`${n}.rgba.r = ${p};`:null,m?`${n}.rgba.g = ${m};`:null,f?`${n}.rgba.b = ${f};`:null,`${n}.xxyyzz = ${r?`${r}.xxyyzz`:"vec3(0.0, 0.0, 0.0)"};`,`${n}.xyxzyz = ${r?`${r}.xyxzyz`:"vec3(0.0, 0.0, 0.0)"};`].filter(Boolean)}})}dynoOut(){return new Ur(this,"covsplat")}}class cs extends $r{constructor({index:e}){super({inTypes:{index:"int"},outTypes:{coord:"ivec3"},inputs:{index:e},statements:({inputs:e,outputs:t})=>{const{index:n}=e,{coord:r}=t;return n&&r?[`${r} = splatTexCoord(${n});`]:[]}})}dynoOut(){return new Ur(this,"coord")}}class us extends $r{constructor({index:e}){super({inTypes:{index:"int"},outTypes:{coord:"ivec3"},inputs:{index:e},statements:({inputs:e,outputs:t})=>{const{index:n}=e,{coord:r}=t;return n&&r?[`${r} = pagedSplatTexCoord(${n});`]:[]}})}dynoOut(){return new Ur(this,"coord")}}const hs=(e,t)=>new ps({gsplat:e,rgbMinMaxLnScaleMinMax:t}),ds=e=>new gs({covsplat:e});class ps extends $r{constructor({gsplat:e,rgbMinMaxLnScaleMinMax:t}){super({inTypes:{gsplat:Ui,rgbMinMaxLnScaleMinMax:"vec4"},inputs:{gsplat:e,rgbMinMaxLnScaleMinMax:t},globals:()=>[ji],statements:({inputs:e,outputs:t})=>{const{gsplat:n,rgbMinMaxLnScaleMinMax:r}=e;return n&&r?Wr(`\n if (isGsplatActive(${n}.flags)) {\n target = packSplatEncoding(${n}.center, ${n}.scales, ${n}.quaternion, ${n}.rgba, ${r});\n } else {\n target = uvec4(0u, 0u, 0u, 0u);\n }\n `):["target = uvec4(0u, 0u, 0u, 0u);"]}})}}class ms extends $r{constructor({covsplat:e,rgbMinMaxLnScaleMinMax:t}){super({inTypes:{covsplat:Fi,rgbMinMaxLnScaleMinMax:"vec4"},inputs:{covsplat:e,rgbMinMaxLnScaleMinMax:t},globals:()=>[Wi],statements:({inputs:e})=>{const{covsplat:t,rgbMinMaxLnScaleMinMax:n}=e;return t&&n?Wr(`\n if (isCovSplatActive(${t}.flags)) {\n target = packSplatCovEncoding(${t}.center, ${t}.rgba, ${t}.xxyyzz, ${t}.xyxzyz, ${n});\n } else {\n target = uvec4(0u);\n }\n `):["target = uvec4(0u);"]}})}}class fs extends $r{constructor({gsplat:e}){super({inTypes:{gsplat:Ui},inputs:{gsplat:e},globals:()=>[ji],statements:({inputs:e})=>{const{gsplat:t}=e;return t?Wr(`\n if (isGsplatActive(${t}.flags)) {\n packSplatExt(target, target2, ${t}.center, ${t}.scales, ${t}.quaternion, ${t}.rgba);\n } else {\n target = uvec4(0u);\n target2 = uvec4(0u);\n }\n `):["target = uvec4(0u);","target2 = uvec4(0u);"]}})}}class gs extends $r{constructor({covsplat:e}){super({inTypes:{covsplat:Fi},inputs:{covsplat:e},globals:()=>[Wi],statements:({inputs:e})=>{const{covsplat:t}=e;return t?Wr(`\n if (isCovSplatActive(${t}.flags)) {\n packSplatExtCov(target, target2, ${t}.center, ${t}.rgba, ${t}.xxyyzz, ${t}.xyxzyz);\n } else {\n target = uvec4(0u);\n target2 = uvec4(0u);\n }\n `):["target = uvec4(0u);","target2 = uvec4(0u);"]}})}}class xs extends $r{constructor({gsplat:e,viewCenter:t,viewDir:n,sortRadial:r}){super({inTypes:{gsplat:Ui,viewCenter:"vec3",viewDir:"vec3",sortRadial:"bool"},inputs:{gsplat:e,viewCenter:t,viewDir:n,sortRadial:r},globals:()=>[ji],statements:({inputs:e})=>{const{gsplat:t,viewCenter:n,viewDir:r,sortRadial:i}=e;return t&&n&&r&&i?Wr(`\n float metric = 1.0 / 0.0;\n if (isGsplatActive(${t}.flags)) {\n vec3 center = ${t}.center - ${n};\n if (${i}) {\n metric = length(center);\n } else {\n float bias = 100.0; // reduce popping\n metric = dot(center, ${r}) + bias;\n }\n }\n target3 = floatToVec4(metric);\n `):[]}})}}class ys extends $r{constructor({covsplat:e,viewCenter:t,viewDir:n,sortRadial:r}){super({inTypes:{covsplat:Fi,viewCenter:"vec3",viewDir:"vec3",sortRadial:"bool"},inputs:{covsplat:e,viewCenter:t,viewDir:n,sortRadial:r},globals:()=>[Wi],statements:({inputs:e})=>{const{covsplat:t,viewCenter:n,viewDir:r,sortRadial:i}=e;return t&&n&&r&&i?Wr(`\n float metric = 1.0 / 0.0;\n if (isCovSplatActive(${t}.flags)) {\n vec3 center = ${t}.center - ${n};\n if (${i}) {\n metric = length(center);\n } else {\n float bias = 100.0; // reduce popping\n metric = dot(center, ${r}) + bias;\n }\n }\n target3 = floatToVec4(metric);\n `):[]}})}}class vs extends $r{constructor({rgba8:e}){super({inTypes:{rgba8:"vec4"},inputs:{rgba8:e},statements:({inputs:e,outputs:t})=>[`target = ${e.rgba8??"vec4(0.0, 0.0, 0.0, 0.0)"};`]})}dynoOut(){return new Ur(this,"rgba8")}}class bs extends $r{constructor({key:e,type:t,count:n,value:r,update:i,globals:s}){e=e??"value",super({outTypes:{[e]:t},update:()=>{if(i){const e=i(this.value);void 0!==e&&(this.value=e)}this.uniform.value=this.value},generate:({inputs:r,outputs:i})=>{const a=(null==s?void 0:s({inputs:r,outputs:i}))??[],o={},l=i[e];return l&&(a.push(`uniform ${jr(l,t,n)};`),o[l]=this.uniform),{globals:a,uniforms:o}}}),this.type=t,this.count=n,this.value=r,this.uniform={value:r},this.outKey=e}dynoOut(){return new Ur(this,this.outKey)}}class ws extends bs{constructor({key:e,value:t,update:n}){super({key:e,type:"bool",value:t,update:n})}}class Ts extends bs{constructor({key:e,value:t,update:n}){super({key:e,type:"int",value:t,update:n})}}class Ss extends bs{constructor({key:e,value:t,update:n}){super({key:e,type:"float",value:t,update:n})}}class _s extends bs{constructor({key:e,value:t,update:n}){super({key:e,type:"vec3",value:t,update:n})}}class Ms extends bs{constructor({key:e,value:t,update:n}){super({key:e,type:"vec4",value:t,update:n})}}class As extends bs{constructor({key:e,value:t,update:n}){super({key:e,type:"mat3",value:t,update:n})}}class Es extends bs{constructor({key:e,value:t,update:n}){super({key:e,type:"usampler2D",value:t,update:n})}}class Cs extends bs{constructor({key:e,value:t,update:n}){super({key:e,type:"usampler2DArray",value:t,update:n})}}class Rs{constructor({graph:e,inputs:t,outputs:n,template:r,consoleLog:i}){this.graph=e,this.template=r,this.inputs=t??{},this.outputs=n??{};const s=new Nr({indent:this.template.indent});for(const o in this.outputs)this.outputs[o]&&s.declares.add(this.outputs[o]);const a=e.compile({inputs:this.inputs,outputs:this.outputs,compile:s});this.shader=r.generate({globals:s.globals,statements:a}),this.uniforms=s.uniforms,this.updaters=s.updaters}prepareMaterial(){return function(e){let t=ks.get(e);if(t)return t;return t=new r.RawShaderMaterial({glslVersion:r.GLSL3,vertexShader:bi,fragmentShader:e.shader,uniforms:e.uniforms}),ks.set(e,t),t}(this)}update(){for(const e of this.updaters)e()}}class Ds{constructor(e){const t=e.match(/^([ \t]*)\{\{\s*GLOBALS\s*\}\}/m),n=e.match(/^([ \t]*)\{\{\s*STATEMENTS\s*\}\}/m);if(!t||!n)throw new Error("Template must contain {{ GLOBALS }} and {{ STATEMENTS }}");this.before=e.substring(0,t.index),this.between=e.substring(t.index+t[0].length,n.index),this.after=e.substring(n.index+n[0].length),this.indent=n[1]}generate({globals:e,statements:t}){return this.before+Array.from(e).join("\n\n")+this.between+t.map((e=>this.indent+e)).join("\n")+this.after}}const ks=new WeakMap;function Is(e,t,n="add"){const r=()=>{throw new Error(`Invalid ${n} types: ${e}, ${t}`)};if(e===t)return e;if("int"===e){if(_r(t))return t;r()}if("int"===t){if(_r(e))return e;r()}if("uint"===e){if(Mr(t))return t;r()}if("uint"===t){if(Mr(e))return e;r()}if("float"===e){if(Ar(t))return t;r()}if("float"===t){if(Ar(e))return e;r()}throw new Error(`Invalid ${n} types: ${e}, ${t}`)}function Ps(e,t){return Is(e,t,"sub")}function Ls(e,t){const n=()=>{throw new Error(`Invalid mul types: ${e}, ${t}`)};if("int"===e){if(_r(t))return t;n()}if("int"===t){if(_r(e))return e;n()}if("uint"===e){if(Mr(t))return t;n()}if("uint"===t){if(Mr(e))return e;n()}if("float"===e){if(Ar(t))return t;n()}if("float"===t){if(Ar(e))return e;n()}if(_r(e)||Mr(e)||_r(t)||Mr(t)){if(e===t)return e;n()}if("vec2"===e){if("vec2"===t||Er(t))return"vec2";if("mat3x2"===t)return"vec3";if("mat4x2"===t)return"vec4";n()}if("vec3"===e){if("mat2x3"===t)return"vec2";if("vec3"===t||Cr(t))return"vec3";if("mat4x3"===t)return"vec4";n()}if("vec4"===e){if("mat2x4"===t)return"vec2";if("mat3x4"===t)return"vec3";if("vec4"===t||Rr(t))return"vec4";n()}if("vec2"===t){if(Er(e))return"vec2";if("mat2x3"===e)return"vec3";if("mat2x4"===e)return"vec4";n()}if("vec3"===t){if("mat3x2"===e)return"vec2";if(Cr(e))return"vec3";if("mat3x4"===e)return"vec4";n()}if("vec4"===t){if("mat4x2"===e)return"vec2";if("mat4x3"===e)return"vec3";if(Rr(e))return"vec4";n()}if(Er(e)){if(Er(t))return"mat2";if("mat3x2"===t)return"mat3x2";if("mat4x2"===t)return"mat4x2";n()}if("mat2x3"===e){if(Er(t))return"mat2x3";if("mat3x2"===t)return"mat3";if("mat4x2"===t)return"mat4x3";n()}if("mat2x4"===e){if(Er(t))return"mat2x4";if("mat3x2"===t)return"mat3x4";if("mat4x2"===t)return"mat4";n()}if("mat3x2"===e){if("mat2x3"===t)return"mat2";if(Cr(t))return"mat3x2";if("mat4x3"===t)return"mat4x2";n()}if(Cr(e)){if("mat2x3"===t)return"mat2x3";if(Cr(t))return"mat3";if("mat4x3"===t)return"mat4x3";n()}if("mat3x4"===e){if("mat2x3"===t)return"mat2x4";if(Cr(t))return"mat3x4";if("mat4x3"===t)return"mat4";n()}if("mat4x2"===e){if("mat2x4"===t)return"mat2";if("mat3x4"===t)return"mat3x2";if(Rr(t))return"mat4x2";n()}if("mat4x3"===e){if("mat2x4"===t)return"mat2x3";if("mat3x4"===t)return"mat3";if(Rr(t))return"mat4x3";n()}if(Rr(e)){if("mat2x4"===t)return"mat2x4";if("mat3x4"===t)return"mat3x4";if(Rr(t))return"mat4";n()}throw new Error(`Invalid mul types: ${e}, ${t}`)}const Us=(e,t)=>new Bs({a:e,b:t}),Fs=(e,t)=>new Vs({a:e,b:t}),zs=(e,t)=>new Os({a:e,b:t});class Bs extends Kr{constructor({a:e,b:t}){super({a:e,b:t,outKey:"sum",outTypeFunc:Is}),this.statements=({inputs:e,outputs:t})=>[`${t.sum} = ${e.a} + ${e.b};`]}}class Vs extends Kr{constructor({a:e,b:t}){super({a:e,b:t,outKey:"difference",outTypeFunc:Ps}),this.statements=({inputs:e,outputs:t})=>[`${t.difference} = ${e.a} - ${e.b};`]}}class Os extends Kr{constructor({a:e,b:t}){super({a:e,b:t,outKey:"product",outTypeFunc:Ls}),this.statements=({inputs:e,outputs:t})=>[`${t.product} = ${e.a} * ${e.b};`]}}const Ns=e=>new qs({value:e});class $s extends Yr{constructor({value:e}){super({a:e,outKey:"uint",outTypeFunc:()=>"uint"}),this.statements=({inputs:e,outputs:t})=>[`${t.uint} = floatBitsToUint(${e.a});`]}}class Gs extends Yr{constructor({value:e}){super({a:e,outKey:"uint",outTypeFunc:()=>"uint"}),this.statements=({inputs:e,outputs:t})=>[`${t.uint} = packHalf2x16(${e.a});`]}}class qs extends Yr{constructor({value:e}){super({a:e,outKey:"rgba8",outTypeFunc:()=>"vec4"}),this.statements=({inputs:e,outputs:t})=>[`uvec4 uRgba = uvec4(${e.a} & 0xffu, (${e.a} >> 8u) & 0xffu, (${e.a} >> 16u) & 0xffu, (${e.a} >> 24u) & 0xffu);`,`${t.rgba8} = vec4(uRgba) / 255.0;`]}}const Hs=e=>new js({a:e});class js extends Yr{constructor({a:e}){super({a:e,outTypeFunc:e=>e,outKey:"normalize"}),this.statements=({inputs:e,outputs:t})=>[`${t.normalize} = normalize(${e.a});`]}}class Ws extends $r{constructor({vector:e,vectorType:t,x:n,y:r,z:i,w:s,r:a,g:o,b:l,a:c}){if(!e&&!t)throw new Error("Either vector or vectorType must be provided");const u=t??Pr(e),h=function(e){switch(e){case"vec2":case"vec3":case"vec4":return"float";case"ivec2":case"ivec3":case"ivec4":return"int";case"uvec2":case"uvec3":case"uvec4":return"uint";default:throw new Error(`Invalid vector type: ${e}`)}}(u),d=function(e){switch(e){case"vec2":case"ivec2":case"uvec2":return 2;case"vec3":case"ivec3":case"uvec3":return 3;case"vec4":case"ivec4":case"uvec4":return 4;default:throw new Error(`Invalid vector type: ${e}`)}}(u),p={vector:u,x:h,y:h,r:h,g:h},m={vector:e,x:n,y:r,r:a,g:o};d>=3&&(Object.assign(p,{z:h,b:h}),Object.assign(m,{z:i,b:l})),d>=4&&(Object.assign(p,{w:h,a:h}),Object.assign(m,{w:s,a:c})),super({inTypes:p,outTypes:{vector:u},inputs:m}),this.statements=({inputs:e,outputs:t})=>{const{vector:n}=t,{vector:r,x:i,y:s,z:a,w:o,r:l,g:c,b:u,a:p}=e,m=[`${n}.x = ${i??l??(r?`${r}.x`:Vr(h))};`,`${n}.y = ${s??c??(r?`${r}.y`:Vr(h))};`];return d>=3&&m.push(`${n}.z = ${a??u??(r?`${r}.z`:Vr(h))};`),d>=4&&m.push(`${n}.w = ${o??p??(r?`${r}.w`:Vr(h))};`),m}}dynoOut(){return new Ur(this,"vector")}}class Xs extends $r{constructor({position:e,scale:t,scales:n,rotate:r,translate:i}){super({inTypes:{position:"vec3",scale:"float",scales:"vec3",rotate:"vec4",translate:"vec3"},outTypes:{position:"vec3"},inputs:{position:e,scale:t,scales:n,rotate:r,translate:i},statements:({inputs:e,outputs:t})=>{const{position:n}=t;if(!n)return[];const{scale:r,scales:i,rotate:s,translate:a}=e;return[`${n} = ${e.position??"vec3(0.0, 0.0, 0.0)"};`,r?`${n} *= ${r};`:null,i?`${n} *= ${i};`:null,s?`${n} = quatVec(${s}, ${n});`:null,a?`${n} += ${a};`:null].filter(Boolean)}})}}class Ys extends $r{constructor({dir:e,scale:t,scales:n,rotate:r}){super({inTypes:{dir:"vec3",scale:"float",scales:"vec3",rotate:"vec4"},outTypes:{dir:"vec3"},inputs:{dir:e,scale:t,scales:n,rotate:r},statements:({inputs:e,outputs:t})=>{const{dir:n}=t;if(!n)return[];const{scale:r,scales:i,rotate:s}=e;return[`${n} = ${e.dir??"vec3(0.0, 0.0, 0.0)"};`,r?`${n} *= ${r};`:null,i?`${n} *= ${i};`:null,s?`${n} = quatVec(${s}, ${n});`:null].filter(Boolean)}})}}const Ks=class e{constructor(t={}){this.maxSplats=0,this.numSplats=0,this.extra={},this.maxSh=3,this.isInitialized=!1,this.extArrays=[new Uint32Array(0),new Uint32Array(0)],this.textures=[e.emptyTexture,e.emptyTexture],this.extra={},this.dyno=new Zs({extSplats:this}),this.dynoNumSh=new Ts({key:"numSh",value:0,update:()=>Math.min(this.getNumSh(),this.maxSh)}),this.initialized=Promise.resolve(this),this.reinitialize(t)}reinitialize(e){this.isInitialized=!1,this.extra={},this.maxSplats=e.maxSplats??0,this.lod=e.lod,this.nonLod=e.nonLod,e.url||e.fileBytes||e.stream||e.construct?this.initialized=this.asyncInitialize(e).then((()=>(this.isInitialized=!0,this))):(this.initialize(e),this.isInitialized=!0,this.initialized=Promise.resolve(this))}initialize(e){this.extra=e.extra??{},this.lodSplats=e.lodSplats,e.extArrays?(this.extArrays=e.extArrays,this.maxSplats=Math.floor(Math.min(this.extArrays[0].length/4,this.extArrays[1].length/4)),this.numSplats=e.numSplats??this.maxSplats,this.maxSplats=Math.floor(this.maxSplats/br)*br,this.numSplats=Math.min(this.maxSplats,e.numSplats??Number.POSITIVE_INFINITY),this.updateTextures()):(this.maxSplats=e.maxSplats??0,this.numSplats=0,this.extArrays=[new Uint32Array(0),new Uint32Array(0)])}async asyncInitialize(e){const{url:t,fileBytes:n,fileType:r,fileName:i,stream:s,streamLength:a,construct:o,lod:l,nonLod:c,lodAbove:u}=e;this.lod=l,this.nonLod=c;const h=new po;if((n||t||s)&&await h.loadInternalAsync({extSplats:this,url:t,fileBytes:n,fileType:r,fileName:i,stream:s,streamLength:a,onProgress:e.onProgress,lodAbove:u}),o){const e=o(this);e instanceof Promise&&await e}}dispose(){this.textures[0]!==e.emptyTexture&&(this.textures[0].dispose(),this.textures[0].source.data=null,this.textures[0]=e.emptyTexture),this.textures[1]!==e.emptyTexture&&(this.textures[1].dispose(),this.textures[1].source.data=null,this.textures[1]=e.emptyTexture),this.extArrays=[new Uint32Array(0),new Uint32Array(0)];for(const e in this.extra){const t=this.extra[e];if(t instanceof bs){const e=t.value;(null==e?void 0:e.isTexture)&&(e.dispose(),e.source.data=null)}}this.extra={},this.disposeLodSplats()}prepareFetchSplat(){}getNumSplats(){return this.numSplats}hasRgbDir(){return Math.min(this.getNumSh(),this.maxSh)>0}getNumSh(){return this.extra.sh1?this.extra.sh2?this.extra.sh3a&&this.extra.sh3b?3:2:1:0}setMaxSh(e){this.maxSh=e}fetchSplat({index:e,viewOrigin:t}){let n=((e,t)=>new es({extSplats:e,index:t}))(this.dyno,e);if(this.hasRgbDir()&&t){const r=Ni(n).outputs.center,i=Hs(Fs(r,t)),{sh1Texture:s,sh2Texture:a,sh3TextureA:o,sh3TextureB:l}=this.ensureShTextures();let{rgb:c}=na({coord:qi(e),viewDir:i,numSh:this.dynoNumSh,sh1Texture:s,sh2Texture:a,sh3TextureA:o,sh3TextureB:l});c=Us(c,Ni(n).outputs.rgb),n=$i({gsplat:n,rgb:c})}return n}ensureShTextures(){if(!this.extra.sh1)return{};let e=this.extra.sh1Texture;if(!e){let t=this.extra.sh1;const{width:n,height:i,depth:s,maxSplats:a}=gi(t.length/4);if(t.length<4*a){const e=new Uint32Array(4*a);e.set(t),this.extra.sh1=e,t=e}const o=ra(t,n,i,s,r.RGBAIntegerFormat,r.UnsignedIntType,"RGBA32UI");e=new Cs({value:o,key:"sh1"}),this.extra.sh1Texture=e}if(!this.extra.sh2)return{sh1Texture:e};let t=this.extra.sh2Texture;if(!t){let e=this.extra.sh2;const{width:n,height:i,depth:s,maxSplats:a}=gi(e.length/4);if(e.length<4*a){const t=new Uint32Array(4*a);t.set(e),this.extra.sh2=t,e=t}const o=ra(e,n,i,s,r.RGBAIntegerFormat,r.UnsignedIntType,"RGBA32UI");t=new Cs({value:o,key:"sh2"}),this.extra.sh2Texture=t}if(!this.extra.sh3a||!this.extra.sh3b)return{sh1Texture:e,sh2Texture:t};let n=this.extra.sh3TextureA;if(!n){let e=this.extra.sh3a;const{width:t,height:i,depth:s,maxSplats:a}=gi(e.length/4);if(e.length<4*a){const t=new Uint32Array(4*a);t.set(e),this.extra.sh3a=t,e=t}const o=ra(e,t,i,s,r.RGBAIntegerFormat,r.UnsignedIntType,"RGBA32UI");n=new Cs({value:o,key:"sh3"}),this.extra.sh3TextureA=n}let i=this.extra.sh3TextureB;if(!i){let e=this.extra.sh3b;const{width:t,height:n,depth:s,maxSplats:a}=gi(e.length/4);if(e.length<4*a){const t=new Uint32Array(4*a);t.set(e),this.extra.sh3b=t,e=t}const o=ra(e,t,n,s,r.RGBAIntegerFormat,r.UnsignedIntType,"RGBA32UI");i=new Cs({value:o,key:"sh3b"}),this.extra.sh3TextureB=i}return{sh1Texture:e,sh2Texture:t,sh3TextureA:n,sh3TextureB:i}}ensureSplats(e){const t=e<=this.maxSplats?this.maxSplats:Math.max(e,2*this.maxSplats),n=this.extArrays[0]?this.extArrays[0].length/4:0;if(!this.extArrays[0]||t>n){this.maxSplats=gi(t).maxSplats;const e=new Uint32Array(4*this.maxSplats),n=new Uint32Array(4*this.maxSplats);this.extArrays[0]&&(e.set(this.extArrays[0]),n.set(this.extArrays[1])),this.extArrays[0]=e,this.extArrays[1]=n}return this.extArrays}getSplat(e){if(e>=this.numSplats)throw new Error("Invalid index");return hi(this.extArrays,e)}setSplat(e,t,n,r,i,s){ui(this.ensureSplats(e+1),e,t.x,t.y,t.z,n.x,n.y,n.z,r.x,r.y,r.z,r.w,i,s.r,s.g,s.b),this.numSplats=Math.max(this.numSplats,e+1)}pushSplat(e,t,n,r,i){ui(this.ensureSplats(this.numSplats+1),this.numSplats,e.x,e.y,e.z,t.x,t.y,t.z,n.x,n.y,n.z,n.w,r,i.r,i.g,i.b),++this.numSplats}forEachSplat(e){if(this.numSplats)for(let t=0;t<this.numSplats;++t){const n=hi(this.extArrays,t);e(t,n.center,n.scales,n.quaternion,n.opacity,n.color)}}updateTextures(){if(this.textures[0]!==e.emptyTexture){const{width:t,height:n,depth:r}=this.textures[0].image;this.maxSplats!==t*n*r&&(this.textures[0].dispose(),this.textures[0]=e.emptyTexture,this.textures[1].dispose(),this.textures[1]=e.emptyTexture)}if(this.textures[0]===e.emptyTexture){const{width:e,height:t,depth:n}=gi(this.maxSplats);this.textures[0]=ra(this.extArrays[0],e,t,n,r.RGBAIntegerFormat,r.UnsignedIntType,"RGBA32UI"),this.textures[1]=ra(this.extArrays[1],e,t,n,r.RGBAIntegerFormat,r.UnsignedIntType,"RGBA32UI")}else this.extArrays[0].buffer!==this.textures[0].image.data.buffer&&(this.textures[0].image.data=new Uint8Array(this.extArrays[0].buffer),this.textures[1].image.data=new Uint8Array(this.extArrays[1].buffer),this.textures[0].needsUpdate=!0,this.textures[1].needsUpdate=!0)}extractSplats(t,n){const r=gi(t.length).maxSplats,i=new e({maxSplats:r});for(let e=0;e<t.length;e++){const r=this.getSplat(t[e]);if(n){let n=.61803398875*(t[e]>>>16);n-=Math.floor(n);const i=Math.max(0,Math.min(1,Math.abs(6*n-3)-1)),s=Math.max(0,Math.min(1,Math.abs(6*n+1)-1)),a=Math.max(0,Math.min(1,Math.abs(6*n-1)-1));r.color.r*=i,r.color.g*=s,r.color.b*=a}i.pushSplat(r.center,r.scales,r.quaternion,r.opacity,r.color)}return i}disposeLodSplats(){this.lodSplats&&(this.lodSplats.dispose(),this.lodSplats=void 0)}async createLodSplats({rgbaArray:t,quality:n}={}){const r="number"==typeof this.lod?Math.max(1.1,Math.min(2,this.lod)):n?1.75:1.5,i=[this.extArrays[0].slice(),this.extArrays[1].slice()],s=t?(await t.getArray()).slice():void 0,a={sh1:this.extra.sh1?this.extra.sh1.slice():void 0,sh2:this.extra.sh2?this.extra.sh2.slice():void 0,sh3:this.extra.sh3?this.extra.sh3.slice():void 0},o=await Li.withWorker((async e=>await e.call(n?"qualityLodExtSplats":"tinyLodExtSplats",{numSplats:this.numSplats,extArrays:i,extra:a,lodBase:r,rgba:s}))),l=new e(o);this.lodSplats&&this.lodSplats.dispose(),this.lodSplats=l,this.nonLod=!0,this.lod=!n||"quality"}};Ks.emptyArray=(()=>{const{width:e,height:t,depth:n,maxSplats:i}=gi(1),s=new Uint32Array(4*i),a=new r.DataArrayTexture(s,e,t,n);return a.format=r.RGBAIntegerFormat,a.type=r.UnsignedIntType,a.internalFormat="RGBA32UI",a.needsUpdate=!0,a})(),Ks.emptyTexture=ra(null,1,1,1,r.RGBAIntegerFormat,r.UnsignedIntType,"RGBA32UI"),Ks.emptyUint32x4=(()=>{const{width:e,height:t,depth:n,maxSplats:i}=gi(1),s=new Uint32Array(4*i),a=new r.DataArrayTexture(s,e,t,n);return a.format=r.RGBAIntegerFormat,a.type=r.UnsignedIntType,a.internalFormat="RGBA32UI",a.needsUpdate=!0,a})();let Qs=Ks;class Zs extends bs{constructor({extSplats:e}={}){super({key:"extSplats",type:Bi,globals:()=>[Zi],value:{textureArray1:Qs.emptyTexture,textureArray2:Qs.emptyTexture,numSplats:0},update:e=>{var t,n,r;return e.textureArray1=(null==(t=this.extSplats)?void 0:t.textures[0])??Qs.emptyTexture,e.textureArray2=(null==(n=this.extSplats)?void 0:n.textures[1])??Qs.emptyTexture,e.numSplats=(null==(r=this.extSplats)?void 0:r.numSplats)??0,e}}),this.extSplats=e}}const Js=Xr("\n vec3 evaluateExtSH1(uvec4 packedData, vec3 viewDir) {\n vec3 sh1_0 = decodeExtRgb(packedData.x);\n vec3 sh1_1 = decodeExtRgb(packedData.y);\n vec3 sh1_2 = decodeExtRgb(packedData.z);\n\n return sh1_0 * (-0.4886025 * viewDir.y)\n + sh1_1 * (0.4886025 * viewDir.z)\n + sh1_2 * (-0.4886025 * viewDir.x);\n }\n"),ea=Xr("\n vec3 evaluateExtSH12(uvec4 packed1, uvec4 packed2, vec3 viewDir) {\n vec3 sh1_0 = decodeExtRgb(packed1.x);\n vec3 sh1_1 = decodeExtRgb(packed1.y);\n vec3 sh1_2 = decodeExtRgb(packed1.z);\n\n vec3 sh2_0 = decodeExtRgb(packed1.w);\n vec3 sh2_1 = decodeExtRgb(packed2.x);\n vec3 sh2_2 = decodeExtRgb(packed2.y);\n vec3 sh2_3 = decodeExtRgb(packed2.z);\n vec3 sh2_4 = decodeExtRgb(packed2.w);\n\n vec3 sh1Rgb = sh1_0 * (-0.4886025 * viewDir.y)\n + sh1_1 * (0.4886025 * viewDir.z)\n + sh1_2 * (-0.4886025 * viewDir.x);\n\n vec3 sh2Rgb = sh2_0 * (1.0925484 * viewDir.x * viewDir.y)\n + sh2_1 * (-1.0925484 * viewDir.y * viewDir.z)\n + sh2_2 * (0.3153915 * (2.0 * viewDir.z * viewDir.z - viewDir.x * viewDir.x - viewDir.y * viewDir.y))\n + sh2_3 * (-1.0925484 * viewDir.x * viewDir.z)\n + sh2_4 * (0.5462742 * (viewDir.x * viewDir.x - viewDir.y * viewDir.y));\n\n return sh1Rgb + sh2Rgb;\n }\n"),ta=Xr("\n vec3 evaluateExtSH3(uvec4 packedA, uvec4 packedB, vec3 viewDir) {\n vec3 sh3_0 = decodeExtRgb(packedA.x);\n vec3 sh3_1 = decodeExtRgb(packedA.y);\n vec3 sh3_2 = decodeExtRgb(packedA.z);\n vec3 sh3_3 = decodeExtRgb(packedA.w);\n vec3 sh3_4 = decodeExtRgb(packedB.x);\n vec3 sh3_5 = decodeExtRgb(packedB.y);\n vec3 sh3_6 = decodeExtRgb(packedB.z);\n\n float xx = viewDir.x * viewDir.x;\n float yy = viewDir.y * viewDir.y;\n float zz = viewDir.z * viewDir.z;\n float xy = viewDir.x * viewDir.y;\n float yz = viewDir.y * viewDir.z;\n float zx = viewDir.z * viewDir.x;\n\n return sh3_0 * (-0.5900436 * viewDir.y * (3.0 * xx - yy))\n + sh3_1 * (2.8906114 * xy * viewDir.z) +\n + sh3_2 * (-0.4570458 * viewDir.y * (4.0 * zz - xx - yy))\n + sh3_3 * (0.3731763 * viewDir.z * (2.0 * zz - 3.0 * xx - 3.0 * yy))\n + sh3_4 * (-0.4570458 * viewDir.x * (4.0 * zz - xx - yy))\n + sh3_5 * (1.4453057 * viewDir.z * (xx - yy))\n + sh3_6 * (-0.5900436 * viewDir.x * (xx - 3.0 * yy));\n }\n");function na({coord:e,viewDir:t,numSh:n,sh1Texture:r,sh2Texture:i,sh3TextureA:s,sh3TextureB:a}){return new $r({inTypes:{coord:"ivec3",viewDir:"vec3",numSh:"int",sh1Texture:"usampler2DArray",sh2Texture:"usampler2DArray",sh3TextureA:"usampler2DArray",sh3TextureB:"usampler2DArray"},outTypes:{rgb:"vec3"},inputs:{coord:e,viewDir:t,numSh:n,sh1Texture:r,sh2Texture:i,sh3TextureA:s,sh3TextureB:a},globals:()=>[Js,ea,ta],statements:({inputs:e,outputs:t})=>{const n=["vec3 rgb = vec3(0.0);"];return e.sh1Texture&&(e.sh2Texture?(n.push(...Wr(`\n if (${e.numSh} == 1) {\n rgb = evaluateExtSH1(texelFetch(${e.sh1Texture}, ${e.coord}, 0), ${e.viewDir});\n } else if (${e.numSh} >= 2) {\n rgb = evaluateExtSH12(texelFetch(${e.sh1Texture}, ${e.coord}, 0), texelFetch(${e.sh2Texture}, ${e.coord}, 0), ${e.viewDir});\n `)),e.sh3TextureA&&e.sh3TextureB&&n.push(...Wr(`\n if (${e.numSh} >= 3) {\n rgb += evaluateExtSH3(texelFetch(${e.sh3TextureA}, ${e.coord}, 0), texelFetch(${e.sh3TextureB}, ${e.coord}, 0), ${e.viewDir});\n }\n `)),n.push("}")):n.push(...Wr(`\n if (${e.numSh} >= 1) {\n rgb = evaluateExtSH1(texelFetch(${e.sh1Texture}, ${e.coord}, 0), ${e.viewDir});\n }\n `))),n.push(`${t.rgb} = rgb;`),n}}).outputs}function ra(e,t,n,i,s,a,o){const l=new r.DataArrayTexture(e,t,n,i);return l.format=s,l.type=a,l.internalFormat=o,l.needsUpdate=!0,l}function ia(e){const t=Ta.decode_rad_header(e);if(t[2])throw xa(t[1]);return xa(t[0])}function sa(e,t,n,r,i,s,a,o,l,c){return Ta.raycast_ext_buffers(e,t,n,r,i,s,a,o,l,c)}function aa(e,t,n,r,i,s,a,o,l,c,u,h,d){return Ta.raycast_packed_buffer(e,t,n,r,i,s,a,o,l,c,u,h,d)}function oa(){const e={__proto__:null,__wbg_Error_2e59b1b37a9a34c3:function(e,t){return Error(pa(e,t))},__wbg___wbindgen_throw_81fc77679af83bc6:function(e,t){throw new Error(pa(e,t))},__wbg_error_a6fa202b58aa1cd3:function(e,t){let n,r;try{n=e,r=t}finally{Ta.__wbindgen_free(n,r,1)}},__wbg_length_0c32cb8543c8e4c8:function(e){return e.length},__wbg_length_1e701798fdcaa3b4:function(e){return e.length},__wbg_length_fd4646b401926788:function(e){return e.length},__wbg_new_227d7c05414eb861:function(){return new Error},__wbg_new_4f9fafbb3909af72:function(){return new Object},__wbg_new_f3c9df4f38f3f798:function(){return new Array},__wbg_new_with_length_26bffbe236bf73f9:function(e){return new Float32Array(e>>>0)},__wbg_prototypesetcall_3e05eb9545565046:function(e,t,n){var r,i;Uint8Array.prototype.set.call((r=e,i=t,r>>>=0,ga().subarray(r/1,r/1+i)),n)},__wbg_prototypesetcall_e42275e601e14eeb:function(e,t,n){Uint32Array.prototype.set.call(ca(e,t),n)},__wbg_set_6be42768c690e380:function(e,t,n){e[t]=n},__wbg_set_6c60b2e8ad0e9383:function(e,t,n){e[t>>>0]=n},__wbg_set_8ee2d34facb8466e:function(){return function(e,t){try{return e.apply(this,t)}catch(Jm){const t=function(e){const t=Ta.__externref_table_alloc();return Ta.__wbindgen_externrefs.set(t,e),t}(Jm);Ta.__wbindgen_exn_store(t)}}((function(e,t,n){return Reflect.set(e,t,n)}),arguments)},__wbg_set_a98c8da6557e63de:function(e,t,n){e.set(la(t,n))},__wbg_stack_3b0d974bbf31e44f:function(e,t){const n=function(e,t,n){if(void 0===n){const n=wa.encode(e),r=t(n.length,1)>>>0;return ga().subarray(r,r+n.length).set(n),Sa=n.length,r}let r=e.length,i=t(r,1)>>>0;const s=ga();let a=0;for(;a<r;a++){const t=e.charCodeAt(a);if(t>127)break;s[i+a]=t}if(a!==r){0!==a&&(e=e.slice(a)),i=n(i,r,r=a+3*e.length,1)>>>0;const t=ga().subarray(i+a,i+r);a+=wa.encodeInto(e,t).written,i=n(i,r,a,1)>>>0}return Sa=a,i}(t.stack,Ta.__wbindgen_malloc,Ta.__wbindgen_realloc),r=Sa;ha().setInt32(e+4,r,!0),ha().setInt32(e+0,n,!0)},__wbg_subarray_d51e89458b3fdbf6:function(e,t,n){return e.subarray(t>>>0,n>>>0)},__wbindgen_cast_0000000000000001:function(e){return e},__wbindgen_cast_0000000000000002:function(e,t){return la(e,t)},__wbindgen_cast_0000000000000003:function(e,t){return ca(e,t)},__wbindgen_cast_0000000000000004:function(e,t){return pa(e,t)},__wbindgen_cast_0000000000000005:function(e){return BigInt.asUintN(64,e)},__wbindgen_init_externref_table:function(){const e=Ta.__wbindgen_externrefs,t=e.grow(4);e.set(0,void 0),e.set(t+0,void 0),e.set(t+1,null),e.set(t+2,!0),e.set(t+3,!1)}};return{__proto__:null,"./spark_rs_bg.js":e}}function la(e,t){return e>>>=0,function(){null!==da&&0!==da.byteLength||(da=new Float32Array(Ta.memory.buffer));return da}().subarray(e/4,e/4+t)}function ca(e,t){return e>>>=0,function(){null!==ma&&0!==ma.byteLength||(ma=new Uint32Array(Ta.memory.buffer));return ma}().subarray(e/4,e/4+t)}let ua=null;function ha(){return(null===ua||!0===ua.buffer.detached||void 0===ua.buffer.detached&&ua.buffer!==Ta.memory.buffer)&&(ua=new DataView(Ta.memory.buffer)),ua}let da=null;function pa(e,t){return function(e,t){ba+=t,ba>=va&&(ya=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}),ya.decode(),ba=t);return ya.decode(ga().subarray(e,e+t))}(e>>>=0,t)}let ma=null;let fa=null;function ga(){return null!==fa&&0!==fa.byteLength||(fa=new Uint8Array(Ta.memory.buffer)),fa}function xa(e){const t=Ta.__wbindgen_externrefs.get(e);return Ta.__externref_table_dealloc(e),t}let ya=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0});ya.decode();const va=2146435072;let ba=0;const wa=new TextEncoder;"encodeInto"in wa||(wa.encodeInto=function(e,t){const n=wa.encode(e);return t.set(n),{read:e.length,written:n.length}});let Ta,Sa=0;async function _a(e){if(void 0!==Ta)return Ta;void 0!==e&&Object.getPrototypeOf(e)===Object.prototype&&({module_or_path:e}=e),void 0===e&&(e="undefined"==typeof document?require("url").pathToFileURL(__dirname+"/assets/viewer/spark-8b93f8c03d97.wasm").href:new URL("assets/viewer/spark-8b93f8c03d97.wasm",document.currentScript&&"SCRIPT"===document.currentScript.tagName.toUpperCase()&&document.currentScript.src||document.baseURI).href);const t=oa();("string"==typeof e||"function"==typeof Request&&e instanceof Request||"function"==typeof URL&&e instanceof URL)&&(e=fetch(e));const{instance:n,module:r}=await async function(e,t){if("function"==typeof Response&&e instanceof Response){if("function"==typeof WebAssembly.instantiateStreaming)try{return await WebAssembly.instantiateStreaming(e,t)}catch(Jm){if(!e.ok||!function(e){switch(e){case"basic":case"cors":case"default":return!0}return!1}(e.type)||"application/wasm"===e.headers.get("Content-Type"))throw Jm}const n=await e.arrayBuffer();return await WebAssembly.instantiate(n,t)}{const n=await WebAssembly.instantiate(e,t);return n instanceof WebAssembly.Instance?{instance:n,module:e}:n}}(await e,t);return function(e){return Ta=e.exports,ua=null,da=null,ma=null,fa=null,Ta.__wbindgen_start(),Ta}(n)}let Ma=null;function Aa(){return Ma||(r.ShaderChunk.splatDefines="const float LN_SCALE_MIN = -12.0;\nconst float LN_SCALE_MAX = 9.0;\n\nconst uint SPLAT_TEX_WIDTH_BITS = 11u;\nconst uint SPLAT_TEX_HEIGHT_BITS = 11u;\nconst uint SPLAT_TEX_DEPTH_BITS = 11u;\nconst uint SPLAT_TEX_LAYER_BITS = SPLAT_TEX_WIDTH_BITS + SPLAT_TEX_HEIGHT_BITS;\n\nconst uint SPLAT_TEX_WIDTH = 1u << SPLAT_TEX_WIDTH_BITS;\nconst uint SPLAT_TEX_HEIGHT = 1u << SPLAT_TEX_HEIGHT_BITS;\nconst uint SPLAT_TEX_DEPTH = 1u << SPLAT_TEX_DEPTH_BITS;\n\nconst uint SPLAT_TEX_WIDTH_MASK = SPLAT_TEX_WIDTH - 1u;\nconst uint SPLAT_TEX_HEIGHT_MASK = SPLAT_TEX_HEIGHT - 1u;\nconst uint SPLAT_TEX_DEPTH_MASK = SPLAT_TEX_DEPTH - 1u;\n\nconst uint F16_INF = 0x7c00u;\nconst float PI = 3.1415926535897932384626433832795;\n\nconst float INFINITY = 1.0 / 0.0;\nconst float NEG_INFINITY = -INFINITY;\n\nfloat sqr(float x) {\n return x * x;\n}\n\nfloat pow4(float x) {\n float x2 = x * x;\n return x2 * x2;\n}\n\nfloat pow8(float x) {\n float x4 = pow4(x);\n return x4 * x4;\n}\n\nvec3 srgbToLinear(vec3 rgb) {\n return pow(rgb, vec3(2.2));\n}\n\nvec3 linearToSrgb(vec3 rgb) {\n return pow(rgb, vec3(1.0 / 2.2));\n}\n\nuint encodeQuatOctXy88R8(vec4 q) {\n \n if (q.w < 0.0) {\n q = -q;\n }\n \n float theta = 2.0 * acos(q.w);\n float halfTheta = theta * 0.5;\n float s = sin(halfTheta);\n \n vec3 axis = (abs(s) < 1e-6) ? vec3(1.0, 0.0, 0.0) : q.xyz / s;\n \n \n \n float sum = abs(axis.x) + abs(axis.y) + abs(axis.z);\n vec2 p = vec2(axis.x, axis.y) / sum;\n \n if (axis.z < 0.0) {\n float oldPx = p.x;\n p.x = (1.0 - abs(p.y)) * (p.x >= 0.0 ? 1.0 : -1.0);\n p.y = (1.0 - abs(oldPx)) * (p.y >= 0.0 ? 1.0 : -1.0);\n }\n \n float u_f = p.x * 0.5 + 0.5;\n float v_f = p.y * 0.5 + 0.5;\n \n uint quantU = uint(clamp(round(u_f * 255.0), 0.0, 255.0));\n uint quantV = uint(clamp(round(v_f * 255.0), 0.0, 255.0));\n \n \n \n uint angleInt = uint(clamp(round((theta / 3.14159265359) * 255.0), 0.0, 255.0));\n \n \n return (angleInt << 16u) | (quantV << 8u) | quantU;\n}\n\nvec4 decodeQuatOctXy88R8(uint encoded) {\n \n uint quantU = encoded & uint(0xFFu); \n uint quantV = (encoded >> 8u) & uint(0xFFu); \n uint angleInt = encoded >> 16u; \n\n \n float u_f = float(quantU) / 255.0;\n float v_f = float(quantV) / 255.0;\n vec2 f = vec2(u_f * 2.0 - 1.0, v_f * 2.0 - 1.0);\n\n vec3 axis = vec3(f.xy, 1.0 - abs(f.x) - abs(f.y));\n float t = max(-axis.z, 0.0);\n axis.x += (axis.x >= 0.0) ? -t : t;\n axis.y += (axis.y >= 0.0) ? -t : t;\n axis = normalize(axis);\n \n \n float theta = (float(angleInt) / 255.0) * 3.14159265359;\n float halfTheta = theta * 0.5;\n float s = sin(halfTheta);\n float w = cos(halfTheta);\n \n return vec4(axis * s, w);\n}\n\nuint encodeQuatOctXy1010R12(vec4 q) {\n \n if (q.w < 0.0) {\n q = -q;\n }\n \n float halfTheta = acos(q.w);\n float theta = 2.0 * halfTheta;\n float s = sin(halfTheta);\n \n vec3 axis = (abs(s) < 1e-6) ? vec3(1.0, 0.0, 0.0) : q.xyz / s;\n \n \n \n float sum = abs(axis.x) + abs(axis.y) + abs(axis.z);\n vec2 p = vec2(axis.x, axis.y) / sum;\n \n if (axis.z < 0.0) {\n float oldPx = p.x;\n p.x = (1.0 - abs(p.y)) * (p.x >= 0.0 ? 1.0 : -1.0);\n p.y = (1.0 - abs(oldPx)) * (p.y >= 0.0 ? 1.0 : -1.0);\n }\n \n float u_f = p.x * 0.5 + 0.5;\n float v_f = p.y * 0.5 + 0.5;\n \n uint quantU = uint(clamp(round(u_f * 1023.0), 0.0, 1023.0));\n uint quantV = uint(clamp(round(v_f * 1023.0), 0.0, 1023.0));\n \n \n \n uint angleInt = uint(clamp(round((theta / PI) * 4095.0), 0.0, 4095.0));\n \n \n return (angleInt << 20u) | (quantV << 10u) | quantU;\n}\n\nvec4 decodeQuatOctXy1010R12(uint encoded) {\n \n uint quantU = encoded & uint(0x3FFu); \n uint quantV = (encoded >> 10u) & uint(0x3FFu); \n uint angleInt = encoded >> 20u; \n\n \n float u_f = float(quantU) / 1023.0;\n float v_f = float(quantV) / 1023.0;\n vec2 f = vec2(u_f * 2.0 - 1.0, v_f * 2.0 - 1.0);\n\n vec3 axis = vec3(f.xy, 1.0 - abs(f.x) - abs(f.y));\n float t = max(-axis.z, 0.0);\n axis.x += (axis.x >= 0.0) ? -t : t;\n axis.y += (axis.y >= 0.0) ? -t : t;\n axis = normalize(axis);\n \n \n float theta = (float(angleInt) / 4095.0) * PI;\n float halfTheta = theta * 0.5;\n float s = sin(halfTheta);\n float w = cos(halfTheta);\n \n return vec4(axis * s, w);\n}\n\nuvec4 packSplatEncoding(\n vec3 center, vec3 scales, vec4 quaternion, vec4 rgba, vec4 rgbMinMaxLnScaleMinMax\n) {\n float rgbMin = rgbMinMaxLnScaleMinMax.x;\n float rgbMax = rgbMinMaxLnScaleMinMax.y;\n vec3 encRgb = (rgba.rgb - vec3(rgbMin)) / (rgbMax - rgbMin);\n uvec4 uRgba = uvec4(round(clamp(vec4(encRgb, rgba.a) * 255.0, 0.0, 255.0)));\n\n uint uQuat = encodeQuatOctXy88R8(quaternion);\n \n \n uvec3 uQuat3 = uvec3(uQuat & 0xffu, (uQuat >> 8u) & 0xffu, (uQuat >> 16u) & 0xffu);\n\n \n float lnScaleMin = rgbMinMaxLnScaleMinMax.z;\n float lnScaleMax = rgbMinMaxLnScaleMinMax.w;\n float lnScaleScale = 254.0 / (lnScaleMax - lnScaleMin);\n uvec3 uScales = uvec3(\n (scales.x == 0.0) ? 0u : uint(round(clamp((log(scales.x) - lnScaleMin) * lnScaleScale, 0.0, 254.0))) + 1u,\n (scales.y == 0.0) ? 0u : uint(round(clamp((log(scales.y) - lnScaleMin) * lnScaleScale, 0.0, 254.0))) + 1u,\n (scales.z == 0.0) ? 0u : uint(round(clamp((log(scales.z) - lnScaleMin) * lnScaleScale, 0.0, 254.0))) + 1u\n );\n\n \n uint word0 = uRgba.r | (uRgba.g << 8u) | (uRgba.b << 16u) | (uRgba.a << 24u);\n uint word1 = packHalf2x16(center.xy);\n uint word2 = packHalf2x16(vec2(center.z, 0.0)) | (uQuat3.x << 16u) | (uQuat3.y << 24u);\n uint word3 = uScales.x | (uScales.y << 8u) | (uScales.z << 16u) | (uQuat3.z << 24u);\n return uvec4(word0, word1, word2, word3);\n}\n\nuvec4 packSplat(vec3 center, vec3 scales, vec4 quaternion, vec4 rgba) {\n return packSplatEncoding(center, scales, quaternion, rgba, vec4(0.0, 1.0, LN_SCALE_MIN, LN_SCALE_MAX));\n}\n\nvoid unpackSplatEncoding(uvec4 packedData, out vec3 center, out vec3 scales, out vec4 quaternion, out vec4 rgba, vec4 rgbMinMaxLnScaleMinMax) {\n uint word0 = packedData.x, word1 = packedData.y, word2 = packedData.z, word3 = packedData.w;\n\n uvec4 uRgba = uvec4(word0 & 0xffu, (word0 >> 8u) & 0xffu, (word0 >> 16u) & 0xffu, (word0 >> 24u) & 0xffu);\n float rgbMin = rgbMinMaxLnScaleMinMax.x;\n float rgbMax = rgbMinMaxLnScaleMinMax.y;\n rgba = (vec4(uRgba) / 255.0);\n rgba.rgb = rgba.rgb * (rgbMax - rgbMin) + rgbMin;\n\n center = vec4(\n unpackHalf2x16(word1),\n unpackHalf2x16(word2 & 0xffffu)\n ).xyz;\n\n uvec3 uScales = uvec3(word3 & 0xffu, (word3 >> 8u) & 0xffu, (word3 >> 16u) & 0xffu);\n float lnScaleMin = rgbMinMaxLnScaleMinMax.z;\n float lnScaleMax = rgbMinMaxLnScaleMinMax.w;\n float lnScaleScale = (lnScaleMax - lnScaleMin) / 254.0;\n scales = vec3(\n (uScales.x == 0u) ? 0.0 : exp(lnScaleMin + float(uScales.x - 1u) * lnScaleScale),\n (uScales.y == 0u) ? 0.0 : exp(lnScaleMin + float(uScales.y - 1u) * lnScaleScale),\n (uScales.z == 0u) ? 0.0 : exp(lnScaleMin + float(uScales.z - 1u) * lnScaleScale)\n );\n\n uint uQuat = ((word2 >> 16u) & 0xFFFFu) | ((word3 >> 8u) & 0xFF0000u);\n quaternion = decodeQuatOctXy88R8(uQuat);\n \n \n}\n\nvoid unpackSplat(uvec4 packedData, out vec3 center, out vec3 scales, out vec4 quaternion, out vec4 rgba) {\n unpackSplatEncoding(packedData, center, scales, quaternion, rgba, vec4(0.0, 1.0, LN_SCALE_MIN, LN_SCALE_MAX));\n}\n\nuvec4 packSplatCovEncoding(\n vec3 center, vec4 rgba, vec3 xxyyzz, vec3 xyxzyz, vec4 rgbMinMaxLnScaleMinMax\n) {\n float rgbMin = rgbMinMaxLnScaleMinMax.x;\n float rgbMax = rgbMinMaxLnScaleMinMax.y;\n vec3 encRgb = (rgba.rgb - vec3(rgbMin)) / (rgbMax - rgbMin);\n uvec4 uRgba = uvec4(round(clamp(vec4(encRgb, rgba.a) * 255.0, 0.0, 255.0)));\n\n float lnScaleMin = rgbMinMaxLnScaleMinMax.z;\n float lnScaleMax = rgbMinMaxLnScaleMinMax.w;\n float diagScale = 255.0 / (2.0 * (lnScaleMax - lnScaleMin));\n uvec3 uXxyyzz = uvec3(round(clamp((log(xxyyzz) - 2.0 * lnScaleMin) * diagScale, 0.0, 255.0)));\n\n vec3 xyxzyzCor = vec3(\n clamp(xyxzyz.x / sqrt(xxyyzz.x * xxyyzz.y), -1.0, 1.0),\n clamp(xyxzyz.y / sqrt(xxyyzz.x * xxyyzz.z), -1.0, 1.0),\n clamp(xyxzyz.z / sqrt(xxyyzz.y * xxyyzz.z), -1.0, 1.0)\n );\n ivec3 iXyxzyzCor = ivec3(round(xyxzyzCor * 127.0));\n\n \n uint word0 = uRgba.r | (uRgba.g << 8u) | (uRgba.b << 16u) | (uRgba.a << 24u);\n uint word1 = packHalf2x16(center.xy);\n uint word2 = packHalf2x16(vec2(center.z, 0.0)) |\n ((uint(iXyxzyzCor.y) & 0xffu) << 16u) |\n ((uint(iXyxzyzCor.z) & 0xffu) << 24u);\n uint word3 =\n uXxyyzz.x | (uXxyyzz.y << 8u) | (uXxyyzz.z << 16u) |\n ((uint(iXyxzyzCor.x) & 0xffu) << 24u);\n return uvec4(word0, word1, word2, word3);\n}\n\nvoid unpackSplatCovEncoding(uvec4 packedData, out vec3 center, out vec4 rgba, out vec3 xxyyzz, out vec3 xyxzyz, vec4 rgbMinMaxLnScaleMinMax) {\n uint word0 = packedData.x, word1 = packedData.y, word2 = packedData.z, word3 = packedData.w;\n\n uvec4 uRgba = uvec4(word0 & 0xffu, (word0 >> 8u) & 0xffu, (word0 >> 16u) & 0xffu, (word0 >> 24u) & 0xffu);\n float rgbMin = rgbMinMaxLnScaleMinMax.x;\n float rgbMax = rgbMinMaxLnScaleMinMax.y;\n rgba = (vec4(uRgba) / 255.0);\n rgba.rgb = rgba.rgb * (rgbMax - rgbMin) + rgbMin;\n\n center = vec3(\n unpackHalf2x16(word1),\n unpackHalf2x16(word2 & 0xffffu).x\n );\n\n uvec3 uXxyyzz = uvec3(word3 & 0xffu, (word3 >> 8u) & 0xffu, (word3 >> 16u) & 0xffu);\n ivec3 iXyxzyzCor = ivec3(int(word3) >> 24, int(word2 << 8u) >> 24, int(word2) >> 24);\n\n float lnScaleMin = rgbMinMaxLnScaleMinMax.z;\n float lnScaleMax = rgbMinMaxLnScaleMinMax.w;\n float diagScale = 2.0 * (lnScaleMax - lnScaleMin) / 255.0;\n xxyyzz = exp(2.0 * lnScaleMin + vec3(uXxyyzz) * diagScale);\n\n vec3 xyxzyzCor = vec3(iXyxzyzCor) / 127.0;\n xyxzyz = xyxzyzCor * vec3(\n sqrt(xxyyzz.x * xxyyzz.y),\n sqrt(xxyyzz.x * xxyyzz.z),\n sqrt(xxyyzz.y * xxyyzz.z)\n );\n}\n\nvoid packSplatExtCov(\n out uvec4 packedData, out uvec4 packedData2,\n vec3 center, vec4 rgba, vec3 xxyyzz, vec3 xyxzyz\n) {\n packedData.x = floatBitsToUint(center.x);\n packedData.y = floatBitsToUint(center.y);\n packedData.z = floatBitsToUint(center.z);\n packedData.w = packHalf2x16(vec2(rgba.a, rgba.b));\n packedData2.x = packHalf2x16(rgba.rg);\n\n vec3 xyxzyzCor = vec3(\n clamp(xyxzyz.x / sqrt(xxyyzz.x * xxyyzz.y), -1.0, 1.0),\n clamp(xyxzyz.y / sqrt(xxyyzz.x * xxyyzz.z), -1.0, 1.0),\n clamp(xyxzyz.z / sqrt(xxyyzz.y * xxyyzz.z), -1.0, 1.0)\n );\n xyxzyzCor = sign(xyxzyzCor) * clamp(log(abs(xyxzyzCor)), -100.0, -0.0000001);\n xxyyzz = log(xxyyzz);\n\n packedData2.y = packHalf2x16(vec2(xxyyzz.x, xxyyzz.y));\n packedData2.z = packHalf2x16(vec2(xxyyzz.z, xyxzyzCor.x));\n packedData2.w = packHalf2x16(vec2(xyxzyzCor.y, xyxzyzCor.z));\n}\n\nvoid unpackSplatExtCov(\n uvec4 packedData, uvec4 packedData2,\n out vec3 center, out vec4 rgba, out vec3 xxyyzz, out vec3 xyxzyz\n) {\n center.x = uintBitsToFloat(packedData.x);\n center.y = uintBitsToFloat(packedData.y);\n center.z = uintBitsToFloat(packedData.z);\n\n vec2 ab = unpackHalf2x16(packedData.w);\n vec2 rg = unpackHalf2x16(packedData2.x);\n rgba = vec4(rg, ab.y, ab.x);\n\n vec2 xxyy = unpackHalf2x16(packedData2.y);\n vec2 zzxy = unpackHalf2x16(packedData2.z);\n vec2 xzyz = unpackHalf2x16(packedData2.w);\n xxyyzz = exp(vec3(xxyy.x, xxyy.y, zzxy.x));\n xyxzyz = vec3(zzxy.y, xzyz.x, xzyz.y);\n xyxzyz = -sign(xyxzyz) * exp(-abs(xyxzyz));\n xyxzyz *= vec3(\n sqrt(xxyyzz.x * xxyyzz.y),\n sqrt(xxyyzz.x * xxyyzz.z),\n sqrt(xxyyzz.y * xxyyzz.z)\n );\n}\n\nvoid packSplatExt(\n out uvec4 packedData, out uvec4 packedData2,\n vec3 center, vec3 scales, vec4 quaternion, vec4 rgba\n) {\n packedData.x = floatBitsToUint(center.x);\n packedData.y = floatBitsToUint(center.y);\n packedData.z = floatBitsToUint(center.z);\n packedData.w = packHalf2x16(vec2(rgba.a, 0.0));\n\n packedData2.x = packHalf2x16(rgba.rg);\n packedData2.y = packHalf2x16(vec2(rgba.b, log(scales.x)));\n packedData2.z = packHalf2x16(log(scales.yz));\n packedData2.w = encodeQuatOctXy1010R12(quaternion);\n}\n\nvec4 unpackSplatExtCenterAlpha(uvec4 packedData) {\n return vec4(\n uintBitsToFloat(packedData.x),\n uintBitsToFloat(packedData.y),\n uintBitsToFloat(packedData.z),\n unpackHalf2x16(packedData.w).x\n );\n}\n\nfloat unpackSplatExtAlpha(uvec4 packedData) {\n return unpackHalf2x16(packedData.w).x;\n}\n\nvoid unpackSplatExt(\n uvec4 packedData, uvec4 packedData2,\n out vec3 center, out vec3 scales, out vec4 quaternion, out vec4 rgba\n) {\n center.x = uintBitsToFloat(packedData.x);\n center.y = uintBitsToFloat(packedData.y);\n center.z = uintBitsToFloat(packedData.z);\n rgba.a = unpackHalf2x16(packedData.w).x;\n\n rgba.rg = unpackHalf2x16(packedData2.x);\n vec2 split = unpackHalf2x16(packedData2.y);\n rgba.b = split.x;\n scales.x = exp(split.y);\n scales.yz = exp(unpackHalf2x16(packedData2.z));\n quaternion = decodeQuatOctXy1010R12(packedData2.w);\n}\n\nuint encodeExtRgb(vec3 rgb) {\n vec3 absRgb = abs(rgb);\n float maxAbs = max(absRgb.r, max(absRgb.g, absRgb.b));\n\n int base = clamp(int(floor(log2(maxAbs))) + 15, 0, 31);\n float divisor = exp2(float(base - 15)) / 255.0;\n\n uvec3 uRgb = uvec3(round(clamp(absRgb / divisor, 0.0, 255.0)));\n uint expSigns = (uint(base) << 3u) | ((rgb.r < 0.0 ? 0x1u : 0u) | (rgb.g < 0.0 ? 0x2u : 0u) | (rgb.b < 0.0 ? 0x4u : 0u));\n return uRgb.r | (uRgb.g << 8u) | (uRgb.b << 16u) | (expSigns << 24u);\n}\n\nvec3 decodeExtRgb(uint encoded) {\n uint biasedBase = (encoded >> 27u) & 0x1fu;\n float divisor = exp2(float(int(biasedBase) - 15)) / 255.0;\n\n vec3 rgb = vec3(uvec3(encoded & 0xffu, (encoded >> 8u) & 0xffu, (encoded >> 16u) & 0xffu));\n rgb *= divisor;\n\n return vec3(\n ((encoded & 0x1000000u) != 0u) ? -rgb.r : rgb.r,\n ((encoded & 0x2000000u) != 0u) ? -rgb.g : rgb.g,\n ((encoded & 0x4000000u) != 0u) ? -rgb.b : rgb.b\n );\n}\n\nvec3 quatVec(vec4 q, vec3 v) {\n \n vec3 t = 2.0 * cross(q.xyz, v);\n return v + q.w * t + cross(q.xyz, t);\n}\n\nvec4 quatQuat(vec4 q1, vec4 q2) {\n return vec4(\n q1.w * q2.x + q1.x * q2.w + q1.y * q2.z - q1.z * q2.y,\n q1.w * q2.y - q1.x * q2.z + q1.y * q2.w + q1.z * q2.x,\n q1.w * q2.z + q1.x * q2.y - q1.y * q2.x + q1.z * q2.w,\n q1.w * q2.w - q1.x * q2.x - q1.y * q2.y - q1.z * q2.z\n );\n}\n\nmat3 quaternionToMatrix(vec4 q) {\n return mat3(\n (1.0 - 2.0 * (q.y * q.y + q.z * q.z)),\n (2.0 * (q.x * q.y + q.w * q.z)),\n (2.0 * (q.x * q.z - q.w * q.y)),\n (2.0 * (q.x * q.y - q.w * q.z)),\n (1.0 - 2.0 * (q.x * q.x + q.z * q.z)),\n (2.0 * (q.y * q.z + q.w * q.x)),\n (2.0 * (q.x * q.z + q.w * q.y)),\n (2.0 * (q.y * q.z - q.w * q.x)),\n (1.0 - 2.0 * (q.x * q.x + q.y * q.y))\n );\n}\n\nmat3 scaleQuaternionToMatrix(vec3 s, vec4 q) {\n \n return mat3(\n s.x * (1.0 - 2.0 * (q.y * q.y + q.z * q.z)),\n s.x * (2.0 * (q.x * q.y + q.w * q.z)),\n s.x * (2.0 * (q.x * q.z - q.w * q.y)),\n s.y * (2.0 * (q.x * q.y - q.w * q.z)),\n s.y * (1.0 - 2.0 * (q.x * q.x + q.z * q.z)),\n s.y * (2.0 * (q.y * q.z + q.w * q.x)),\n s.z * (2.0 * (q.x * q.z + q.w * q.y)),\n s.z * (2.0 * (q.y * q.z - q.w * q.x)),\n s.z * (1.0 - 2.0 * (q.x * q.x + q.y * q.y))\n );\n}\n\nvec4 slerp(vec4 q1, vec4 q2, float t) {\n \n float cosHalfTheta = dot(q1, q2);\n\n \n if (abs(cosHalfTheta) >= 0.999) {\n return q1;\n }\n \n \n \n if (cosHalfTheta < 0.0) {\n q2 = -q2;\n cosHalfTheta = -cosHalfTheta;\n }\n\n \n float halfTheta = acos(cosHalfTheta);\n float sinHalfTheta = sqrt(1.0 - cosHalfTheta * cosHalfTheta);\n\n \n float ratioA = sin((1.0 - t) * halfTheta) / sinHalfTheta;\n float ratioB = sin(t * halfTheta) / sinHalfTheta;\n\n \n return q1 * ratioA + q2 * ratioB;\n}\n\nivec3 splatTexCoord(int index) {\n uint x = uint(index) & SPLAT_TEX_WIDTH_MASK;\n uint y = (uint(index) >> SPLAT_TEX_WIDTH_BITS) & SPLAT_TEX_HEIGHT_MASK;\n uint z = uint(index) >> SPLAT_TEX_LAYER_BITS;\n return ivec3(x, y, z);\n}\n\nivec3 pagedSplatTexCoord(int index) {\n return ivec3(index & 255, (index >> 8) & 255, index >> 16);\n}\n\nvec4 uintToVec4(uint u32) {\n uvec4 bytes = uvec4(\n u32 & 0xFFu,\n (u32 >> 8u) & 0xFFu,\n (u32 >> 16u) & 0xFFu,\n (u32 >> 24u) & 0xFFu\n );\n return vec4(bytes) / 255.0;\n}\n\nvec4 floatToVec4(float f) {\n uint u32 = floatBitsToUint(f);\n return uintToVec4(u32);\n}\n\nvec3 debugColorHue(uint i) {\n \n float hue = fract(float(i) * 0.61803398875);\n \n vec3 rgb = clamp(abs(mod(hue*6.0 + vec3(0.0,4.0,2.0), 6.0) - 3.0) - 1.0, 0.0, 1.0);\n return mix(vec3(1.0), rgb, 0.85); \n}",Ma={oldSplatVertex:"precision highp float;\nprecision highp int;\nprecision highp usampler2DArray;\n\n#include <splatDefines>\n\nattribute uint splatIndex;\n\nout vec4 vRgba;\nout vec2 vSplatUv;\nout vec3 vNdc;\nflat out uint vSplatIndex;\n\nuniform vec2 renderSize;\nuniform uint numSplats;\nuniform vec4 renderToViewQuat;\nuniform vec3 renderToViewPos;\nuniform float maxStdDev;\nuniform float minPixelRadius;\nuniform float maxPixelRadius;\nuniform float time;\nuniform float deltaTime;\nuniform bool debugFlag;\nuniform float minAlpha;\nuniform bool stochastic;\nuniform bool enable2DGS;\nuniform float blurAmount;\nuniform float preBlurAmount;\nuniform float focalDistance;\nuniform float apertureAngle;\nuniform float clipXY;\nuniform float focalAdjustment;\n\nuniform usampler2DArray packedSplats;\nuniform vec4 rgbMinMaxLnScaleMinMax;\n\nvoid main() {\n \n gl_Position = vec4(0.0, 0.0, 2.0, 1.0);\n\n if (uint(gl_InstanceID) >= numSplats) {\n return;\n }\n\n ivec3 texCoord;\n if (stochastic) {\n texCoord = ivec3(\n uint(gl_InstanceID) & SPLAT_TEX_WIDTH_MASK,\n (uint(gl_InstanceID) >> SPLAT_TEX_WIDTH_BITS) & SPLAT_TEX_HEIGHT_MASK,\n (uint(gl_InstanceID) >> SPLAT_TEX_LAYER_BITS)\n );\n } else {\n if (splatIndex == 0xffffffffu) {\n \n return;\n }\n texCoord = ivec3(\n splatIndex & SPLAT_TEX_WIDTH_MASK,\n (splatIndex >> SPLAT_TEX_WIDTH_BITS) & SPLAT_TEX_HEIGHT_MASK,\n splatIndex >> SPLAT_TEX_LAYER_BITS\n );\n }\n uvec4 packedData = texelFetch(packedSplats, texCoord, 0);\n\n vec3 center, scales;\n vec4 quaternion, rgba;\n unpackSplatEncoding(packedData, center, scales, quaternion, rgba, rgbMinMaxLnScaleMinMax);\n\n if (rgba.a < minAlpha) {\n return;\n }\n bvec3 zeroScales = equal(scales, vec3(0.0));\n if (all(zeroScales)) {\n return;\n }\n\n \n vec3 viewCenter = quatVec(renderToViewQuat, center) + renderToViewPos;\n\n \n if (viewCenter.z >= 0.0) {\n return;\n }\n\n \n vec4 clipCenter = projectionMatrix * vec4(viewCenter, 1.0);\n\n \n if (abs(clipCenter.z) >= clipCenter.w) {\n return;\n }\n\n \n float clip = clipXY * clipCenter.w;\n if (abs(clipCenter.x) > clip || abs(clipCenter.y) > clip) {\n return;\n }\n\n \n vSplatIndex = splatIndex;\n\n \n vec4 viewQuaternion = quatQuat(renderToViewQuat, quaternion);\n\n if (enable2DGS && any(zeroScales)) {\n vRgba = rgba;\n vSplatUv = position.xy * maxStdDev;\n\n vec3 offset;\n if (zeroScales.z) {\n offset = vec3(vSplatUv.xy * scales.xy, 0.0);\n } else if (zeroScales.y) {\n offset = vec3(vSplatUv.x * scales.x, 0.0, vSplatUv.y * scales.z);\n } else {\n offset = vec3(0.0, vSplatUv.xy * scales.yz);\n }\n\n vec3 viewPos = viewCenter + quatVec(viewQuaternion, offset);\n gl_Position = projectionMatrix * vec4(viewPos, 1.0);\n vNdc = gl_Position.xyz / gl_Position.w;\n return;\n }\n\n \n vec3 ndcCenter = clipCenter.xyz / clipCenter.w;\n\n \n mat3 RS = scaleQuaternionToMatrix(scales, viewQuaternion);\n mat3 cov3D = RS * transpose(RS);\n\n \n vec2 scaledRenderSize = renderSize * focalAdjustment;\n vec2 focal = 0.5 * scaledRenderSize * vec2(projectionMatrix[0][0], projectionMatrix[1][1]);\n\n mat3 J;\n if(isOrthographic) {\n J = mat3(\n focal.x, 0.0, 0.0,\n 0.0, focal.y, 0.0,\n 0.0, 0.0, 0.0\n );\n } else {\n float invZ = 1.0 / viewCenter.z;\n vec2 J1 = focal * invZ;\n vec2 J2 = -(J1 * viewCenter.xy) * invZ;\n J = mat3(\n J1.x, 0.0, J2.x,\n 0.0, J1.y, J2.y,\n 0.0, 0.0, 0.0\n );\n }\n\n \n \n \n \n \n \n \n mat3 cov2D = transpose(J) * cov3D * J;\n float a = cov2D[0][0];\n float d = cov2D[1][1];\n float b = cov2D[0][1];\n\n \n a += preBlurAmount;\n d += preBlurAmount;\n\n float fullBlurAmount = blurAmount;\n if ((focalDistance > 0.0) && (apertureAngle > 0.0)) {\n float focusRadius = maxPixelRadius;\n if (viewCenter.z < 0.0) {\n float focusBlur = abs((-viewCenter.z - focalDistance) / viewCenter.z);\n float apertureRadius = focal.x * tan(0.5 * apertureAngle);\n focusRadius = focusBlur * apertureRadius;\n }\n fullBlurAmount = clamp(sqr(focusRadius), blurAmount, sqr(maxPixelRadius));\n }\n\n \n float detOrig = a * d - b * b;\n a += fullBlurAmount;\n d += fullBlurAmount;\n float det = a * d - b * b;\n\n \n float blurAdjust = sqrt(max(0.0, detOrig / det));\n rgba.a *= blurAdjust;\n if (rgba.a < minAlpha) {\n return;\n }\n\n \n float eigenAvg = 0.5 * (a + d);\n float eigenDelta = sqrt(max(0.0, eigenAvg * eigenAvg - det));\n float eigen1 = eigenAvg + eigenDelta;\n float eigen2 = eigenAvg - eigenDelta;\n\n vec2 eigenVec1 = normalize(vec2((abs(b) < 0.001) ? 1.0 : b, eigen1 - a));\n vec2 eigenVec2 = vec2(eigenVec1.y, -eigenVec1.x);\n\n float scale1 = min(maxPixelRadius, maxStdDev * sqrt(eigen1));\n float scale2 = min(maxPixelRadius, maxStdDev * sqrt(eigen2));\n if (scale1 < minPixelRadius && scale2 < minPixelRadius) {\n return;\n }\n\n \n vec2 pixelOffset = position.x * eigenVec1 * scale1 + position.y * eigenVec2 * scale2;\n vec2 ndcOffset = (2.0 / scaledRenderSize) * pixelOffset;\n vec3 ndc = vec3(ndcCenter.xy + ndcOffset, ndcCenter.z);\n\n vRgba = rgba;\n vSplatUv = position.xy * maxStdDev;\n vNdc = ndc;\n gl_Position = vec4(ndc.xy * clipCenter.w, clipCenter.zw);\n}",oldSplatFragment:"precision highp float;\nprecision highp int;\n\n#include <splatDefines>\n\nuniform float near;\nuniform float far;\nuniform bool encodeLinear;\nuniform float time;\nuniform bool debugFlag;\nuniform float maxStdDev;\nuniform float minAlpha;\nuniform bool stochastic;\nuniform bool disableFalloff;\nuniform float falloff;\n\nuniform bool splatTexEnable;\nuniform sampler3D splatTexture;\nuniform mat2 splatTexMul;\nuniform vec2 splatTexAdd;\nuniform float splatTexNear;\nuniform float splatTexFar;\nuniform float splatTexMid;\n\nout vec4 fragColor;\n\nin vec4 vRgba;\nin vec2 vSplatUv;\nin vec3 vNdc;\nflat in uint vSplatIndex;\n\nvoid main() {\n vec4 rgba = vRgba;\n\n float z = dot(vSplatUv, vSplatUv);\n if (!splatTexEnable) {\n if (z > (maxStdDev * maxStdDev)) {\n discard;\n }\n } else {\n vec2 uv = splatTexMul * vSplatUv + splatTexAdd;\n float ndcZ = vNdc.z;\n float depth = (2.0 * near * far) / (far + near - ndcZ * (far - near));\n float clampedFar = max(splatTexFar, splatTexNear);\n float clampedDepth = clamp(depth, splatTexNear, clampedFar);\n float logDepth = log2(clampedDepth + 1.0);\n float logNear = log2(splatTexNear + 1.0);\n float logFar = log2(clampedFar + 1.0);\n\n float texZ;\n if (splatTexMid > 0.0) {\n float clampedMid = clamp(splatTexMid, splatTexNear, clampedFar);\n float logMid = log2(clampedMid + 1.0);\n texZ = (clampedDepth <= clampedMid) ?\n (0.5 * ((logDepth - logNear) / (logMid - logNear))) :\n (0.5 * ((logDepth - logMid) / (logFar - logMid)) + 0.5);\n } else {\n texZ = (logDepth - logNear) / (logFar - logNear);\n }\n\n vec4 modulate = texture(splatTexture, vec3(uv, 1.0 - texZ));\n rgba *= modulate;\n }\n\n rgba.a *= mix(1.0, exp(-0.5 * z), falloff);\n\n if (rgba.a < minAlpha) {\n discard;\n }\n if (encodeLinear) {\n rgba.rgb = srgbToLinear(rgba.rgb);\n }\n\n if (stochastic) {\n const bool STEADY = false;\n uint uTime = STEADY ? 0u : floatBitsToUint(time);\n uvec2 coord = uvec2(gl_FragCoord.xy);\n uint state = uTime + 0x9e3779b9u * coord.x + 0x85ebca6bu * coord.y + 0xc2b2ae35u * uint(vSplatIndex);\n state = state * 747796405u + 2891336453u;\n uint hash = ((state >> ((state >> 28u) + 4u)) ^ state) * 277803737u;\n hash = (hash >> 22u) ^ hash;\n float rand = float(hash) / 4294967296.0;\n if (rand < rgba.a) {\n fragColor = vec4(rgba.rgb, 1.0);\n } else {\n discard;\n }\n } else {\n #ifdef PREMULTIPLIED_ALPHA\n fragColor = vec4(rgba.rgb * rgba.a, rgba.a);\n #else\n fragColor = rgba;\n #endif\n }\n}",splatVertex:"precision highp float;\nprecision highp int;\nprecision highp usampler2DArray;\n\n#include <splatDefines>\n\nout vec4 vRgba;\nout vec2 vSplatUv;\nout vec3 vNdc;\nflat out uint vSplatIndex;\nflat out float adjustedStdDev;\n\nuniform vec2 renderSize;\nuniform vec4 renderToViewQuat;\nuniform vec3 renderToViewPos;\nuniform mat3 renderToViewBasis;\nuniform float maxStdDev;\nuniform float minPixelRadius;\nuniform float maxPixelRadius;\nuniform bool enableExtSplats;\nuniform bool enableCovSplats;\nuniform float time;\nuniform float deltaTime;\nuniform bool debugFlag;\nuniform float minAlpha;\nuniform bool enable2DGS;\nuniform bool lodInflate;\nuniform float blurAmount;\nuniform float preBlurAmount;\nuniform float focalDistance;\nuniform float apertureAngle;\nuniform float clipXY;\nuniform float focalAdjustment;\n\nuniform usampler2D ordering;\nuniform usampler2DArray extSplats;\nuniform usampler2DArray extSplats2;\n\nbool isPerspectiveMatrix( mat4 m ) {\n return m[ 2 ][ 3 ] == -1.0;\n}\n\n#include <logdepthbuf_pars_vertex>\n\nvoid main() {\n \n gl_Position = vec4(0.0, 0.0, 2.0, 1.0);\n\n ivec2 orderingCoord = ivec2((gl_InstanceID >> 2) & 4095, gl_InstanceID >> 14);\n uint splatIndex = texelFetch(ordering, orderingCoord, 0)[gl_InstanceID & 3];\n if (splatIndex == 0xffffffffu) {\n \n return;\n }\n\n ivec3 texCoord = splatTexCoord(int(splatIndex));\n vec3 center, scales, xxyyzz, xyxzyz;\n vec4 quaternion, rgba;\n mat3 cov3D;\n bvec3 zeroScales = bvec3(false);\n\n if (enableExtSplats) {\n uvec4 ext1 = texelFetch(extSplats, texCoord, 0);\n float alpha = unpackSplatExtAlpha(ext1);\n if ((alpha == 0.0) || (alpha < minAlpha)) {\n return;\n }\n uvec4 ext2 = texelFetch(extSplats2, texCoord, 0);\n\n if (!enableCovSplats) {\n unpackSplatExt(ext1, ext2, center, scales, quaternion, rgba);\n zeroScales = equal(scales, vec3(0.0));\n if (all(zeroScales)) {\n return;\n }\n } else {\n unpackSplatExtCov(ext1, ext2, center, rgba, xxyyzz, xyxzyz);\n if (all(equal(xxyyzz, vec3(0.0))) && all(equal(xyxzyz, vec3(0.0)))) {\n return;\n }\n }\n } else {\n uvec4 packedData = texelFetch(extSplats, texCoord, 0);\n if (!enableCovSplats) {\n unpackSplatEncoding(packedData, center, scales, quaternion, rgba, vec4(0.0, 1.0, LN_SCALE_MIN, LN_SCALE_MAX));\n zeroScales = equal(scales, vec3(0.0));\n if (all(zeroScales)) {\n return;\n }\n } else {\n unpackSplatCovEncoding(packedData, center, rgba, xxyyzz, xyxzyz, vec4(0.0, 1.0, LN_SCALE_MIN, LN_SCALE_MAX));\n if (all(equal(xxyyzz, vec3(0.0))) && all(equal(xyxzyz, vec3(0.0)))) {\n return;\n }\n }\n\n rgba.a *= 2.0;\n if ((rgba.a == 0.0) || (rgba.a < minAlpha)) {\n return;\n }\n }\n\n adjustedStdDev = maxStdDev;\n if (rgba.a > 1.0) {\n \n rgba.a = min(rgba.a * 4.0 - 3.0, 5.0);\n\n if (lodInflate) {\n \n float opacity = exp((rgba.a * rgba.a - 1.0) / 2.718281828459045);\n float rescale = pow(opacity, 1.0 / 3.0);\n scales *= rescale;\n rgba.a = 1.0;\n }\n\n \n adjustedStdDev = maxStdDev + 0.7 * (rgba.a - 1.0);\n }\n\n \n vec3 viewCenter = (!enableCovSplats ? quatVec(renderToViewQuat, center) : (renderToViewBasis * center)) + renderToViewPos;\n\n \n if (viewCenter.z >= 0.0) {\n return;\n }\n\n \n vec4 clipCenter = projectionMatrix * vec4(viewCenter, 1.0);\n\n \n if (abs(clipCenter.z) >= clipCenter.w) {\n return;\n }\n\n \n float clip = clipXY * clipCenter.w;\n if (abs(clipCenter.x) > clip || abs(clipCenter.y) > clip) {\n return;\n }\n\n vRgba = rgba;\n vSplatUv = position.xy * adjustedStdDev;\n\n \n vSplatIndex = splatIndex;\n\n if (!enableCovSplats) {\n \n vec4 viewQuaternion = quatQuat(renderToViewQuat, quaternion);\n\n if (enable2DGS && any(zeroScales)) {\n vec3 offset;\n if (zeroScales.z) {\n offset = vec3(vSplatUv.xy * scales.xy, 0.0);\n } else if (zeroScales.y) {\n offset = vec3(vSplatUv.x * scales.x, 0.0, vSplatUv.y * scales.z);\n } else {\n offset = vec3(0.0, vSplatUv.xy * scales.yz);\n }\n\n vec3 viewPos = viewCenter + quatVec(viewQuaternion, offset);\n gl_Position = projectionMatrix * vec4(viewPos, 1.0);\n vNdc = gl_Position.xyz / gl_Position.w;\n\n #include <logdepthbuf_vertex>\n return;\n }\n\n \n mat3 RS = scaleQuaternionToMatrix(scales, viewQuaternion);\n cov3D = RS * transpose(RS);\n } else {\n cov3D = mat3(\n xxyyzz.x, xyxzyz.x, xyxzyz.y,\n xyxzyz.x, xxyyzz.y, xyxzyz.z,\n xyxzyz.y, xyxzyz.z, xxyyzz.z\n );\n cov3D = renderToViewBasis * cov3D * transpose(renderToViewBasis);\n }\n\n \n vec2 scaledRenderSize = renderSize * focalAdjustment;\n vec2 focal = 0.5 * scaledRenderSize * vec2(projectionMatrix[0][0], projectionMatrix[1][1]);\n\n mat3 J;\n if (isOrthographic) {\n J = mat3(\n focal.x, 0.0, 0.0,\n 0.0, focal.y, 0.0,\n 0.0, 0.0, 0.0\n );\n } else {\n float invZ = 1.0 / viewCenter.z;\n vec2 J1 = focal * invZ;\n vec2 J2 = -(J1 * viewCenter.xy) * invZ;\n J = mat3(\n J1.x, 0.0, J2.x,\n 0.0, J1.y, J2.y,\n 0.0, 0.0, 0.0\n );\n }\n\n \n \n mat3 cov2D = transpose(J) * cov3D * J;\n float a = cov2D[0][0];\n float d = cov2D[1][1];\n float b = cov2D[0][1];\n\n \n a += preBlurAmount;\n d += preBlurAmount;\n\n float fullBlurAmount = blurAmount;\n if ((focalDistance > 0.0) && (apertureAngle > 0.0)) {\n float focusRadius = maxPixelRadius;\n if (viewCenter.z < 0.0) {\n float focusBlur = abs((-viewCenter.z - focalDistance) / viewCenter.z);\n float apertureRadius = focal.x * tan(0.5 * apertureAngle);\n focusRadius = focusBlur * apertureRadius;\n }\n fullBlurAmount = clamp(sqr(focusRadius), blurAmount, sqr(maxPixelRadius));\n }\n\n \n float detOrig = a * d - b * b;\n a += fullBlurAmount;\n d += fullBlurAmount;\n float det = a * d - b * b;\n\n \n float blurAdjust = sqrt(max(0.0, detOrig / det));\n rgba.a *= blurAdjust;\n if (rgba.a < minAlpha) {\n return;\n }\n vRgba.a = rgba.a;\n\n \n float eigenAvg = 0.5 * (a + d);\n float eigenDelta = sqrt(max(0.0, eigenAvg * eigenAvg - det));\n float eigen1 = eigenAvg + eigenDelta;\n float eigen2 = eigenAvg - eigenDelta;\n\n vec2 eigenVec1 = (abs(b) > 0.001) ? normalize(vec2(b, eigen1 - a))\n : ((a >= d) ? vec2(1.0, 0.0) : vec2(0.0, 1.0));\n vec2 eigenVec2 = vec2(eigenVec1.y, -eigenVec1.x);\n\n float scale1 = min(maxPixelRadius, adjustedStdDev * sqrt(eigen1));\n float scale2 = min(maxPixelRadius, adjustedStdDev * sqrt(eigen2));\n if (scale1 < minPixelRadius && scale2 < minPixelRadius) {\n return;\n }\n\n \n vec2 pixelOffset = position.x * eigenVec1 * scale1 + position.y * eigenVec2 * scale2;\n vec2 ndcOffset = (2.0 / scaledRenderSize) * pixelOffset;\n\n \n vec3 ndcCenter = clipCenter.xyz / clipCenter.w;\n vec3 ndc = vec3(ndcCenter.xy + ndcOffset, ndcCenter.z);\n\n vNdc = ndc;\n gl_Position = vec4(ndc.xy * clipCenter.w, clipCenter.zw);\n\n #include <logdepthbuf_vertex>\n}",splatFragment:"precision highp float;\nprecision highp int;\n\n#include <splatDefines>\n\nuniform float near;\nuniform float far;\nuniform bool encodeLinear;\nuniform float time;\nuniform bool debugFlag;\nuniform float maxStdDev;\nuniform float minAlpha;\nuniform bool disableFalloff;\nuniform float falloff;\n\nout vec4 fragColor;\n\nin vec4 vRgba;\nin vec2 vSplatUv;\nin vec3 vNdc;\nflat in uint vSplatIndex;\nflat in float adjustedStdDev;\n\n#include <logdepthbuf_pars_fragment>\n\nvoid main() {\n vec4 rgba = vRgba;\n\n float z2 = dot(vSplatUv, vSplatUv);\n if (z2 > (adjustedStdDev * adjustedStdDev)) {\n discard;\n }\n\n if (false) {\n \n float a = rgba.a;\n float shifted = sqrt(z2) - max(0.0, a - 1.0);\n float exponent = -0.5 * max(1.0, a) * sqr(max(0.0, shifted));\n float min1a = min(1.0, a);\n rgba.a = mix(min1a, min1a * exp(exponent), falloff);\n } else {\n \n if (rgba.a <= 1.0) {\n rgba.a = mix(rgba.a, rgba.a * exp(-0.5 * z2), falloff);\n } else {\n float a = exp((rgba.a*rgba.a - 1.0) / 2.718281828459045);\n float alpha = 1.0 - pow(1.0 - exp(-0.5 * z2), a);\n rgba.a = mix(1.0, alpha, falloff);\n }\n }\n\n if (rgba.a < minAlpha) {\n discard;\n }\n if (encodeLinear) {\n rgba.rgb = srgbToLinear(rgba.rgb);\n }\n\n #ifdef PREMULTIPLIED_ALPHA\n fragColor = vec4(rgba.rgb * rgba.a, rgba.a);\n #else\n fragColor = rgba;\n #endif\n\n #include <logdepthbuf_fragment>\n}",computeVec4Template:"precision highp float;\nprecision highp int;\nprecision highp sampler2D;\nprecision highp usampler2D;\nprecision highp isampler2D;\nprecision highp sampler2DArray;\nprecision highp usampler2DArray;\nprecision highp isampler2DArray;\nprecision highp sampler3D;\nprecision highp usampler3D;\nprecision highp isampler3D;\n\n#include <splatDefines>\n\nuniform uint targetLayer;\nuniform int targetBase;\nuniform int targetCount;\n\nout vec4 target;\n\n{{ GLOBALS }}\n\nvoid computeReadback(int _index) {\n {{ STATEMENTS }}\n}\n\nvoid main() {\n int targetIndex = int(targetLayer << SPLAT_TEX_LAYER_BITS) + int(uint(gl_FragCoord.y) << SPLAT_TEX_WIDTH_BITS) + int(gl_FragCoord.x);\n int index = targetIndex - targetBase;\n\n if ((index >= 0) && (index < targetCount)) {\n computeReadback(index);\n } else {\n target = vec4(0.0, 0.0, 0.0, 0.0);\n }\n}",computeUvec4Vec4Template:"precision highp float;\nprecision highp int;\nprecision highp sampler2D;\nprecision highp usampler2D;\nprecision highp isampler2D;\nprecision highp sampler2DArray;\nprecision highp usampler2DArray;\nprecision highp isampler2DArray;\nprecision highp sampler3D;\nprecision highp usampler3D;\nprecision highp isampler3D;\n\n#include <splatDefines>\n\nuniform uint targetLayer;\nuniform int targetBase;\nuniform int targetCount;\n\nlayout(location = 0) out uvec4 target;\nlayout(location = 1) out vec4 target3;\n\n{{ GLOBALS }}\n\nvoid produceSplat(int _index) {\n {{ STATEMENTS }}\n}\n\nvoid main() {\n int targetIndex = int(targetLayer << SPLAT_TEX_LAYER_BITS) + int(uint(gl_FragCoord.y) << SPLAT_TEX_WIDTH_BITS) + int(gl_FragCoord.x);\n int index = targetIndex - targetBase;\n\n \n target = uvec4(0u, 0u, 0u, 0u);\n\n \n target3 = floatToVec4(1.0 / 0.0);\n\n if ((index >= 0) && (index < targetCount)) {\n produceSplat(index);\n }\n}",computeUvec4x2Vec4Template:"precision highp float;\nprecision highp int;\nprecision highp sampler2D;\nprecision highp usampler2D;\nprecision highp isampler2D;\nprecision highp sampler2DArray;\nprecision highp usampler2DArray;\nprecision highp isampler2DArray;\nprecision highp sampler3D;\nprecision highp usampler3D;\nprecision highp isampler3D;\n\n#include <splatDefines>\n\nuniform uint targetLayer;\nuniform int targetBase;\nuniform int targetCount;\n\nlayout(location = 0) out uvec4 target;\nlayout(location = 1) out uvec4 target2;\nlayout(location = 2) out vec4 target3;\n\n{{ GLOBALS }}\n\nvoid produceSplat(int _index) {\n {{ STATEMENTS }}\n}\n\nvoid main() {\n int targetIndex = int(targetLayer << SPLAT_TEX_LAYER_BITS) + int(uint(gl_FragCoord.y) << SPLAT_TEX_WIDTH_BITS) + int(gl_FragCoord.x);\n int index = targetIndex - targetBase;\n\n \n target = uvec4(0u, 0u, 0u, 0u);\n target2 = uvec4(0u, 0u, 0u, 0u);\n\n \n target3 = floatToVec4(1.0 / 0.0);\n\n if ((index >= 0) && (index < targetCount)) {\n produceSplat(index);\n }\n}",computeUvec4Template:"precision highp float;\nprecision highp int;\nprecision highp sampler2D;\nprecision highp usampler2D;\nprecision highp isampler2D;\nprecision highp sampler2DArray;\nprecision highp usampler2DArray;\nprecision highp isampler2DArray;\nprecision highp sampler3D;\nprecision highp usampler3D;\nprecision highp isampler3D;\n\n#include <splatDefines>\n\nuniform uint targetLayer;\nuniform int targetBase;\nuniform int targetCount;\n\nout uvec4 target;\n\n{{ GLOBALS }}\n\nvoid produceSplat(int _index) {\n {{ STATEMENTS }}\n}\n\nvoid main() {\n int targetIndex = int(targetLayer << SPLAT_TEX_LAYER_BITS) + int(uint(gl_FragCoord.y) << SPLAT_TEX_WIDTH_BITS) + int(gl_FragCoord.x);\n int index = targetIndex - targetBase;\n\n target = uvec4(0u, 0u, 0u, 0u);\n if ((index >= 0) && (index < targetCount)) {\n produceSplat(index);\n }\n}"}),Ma}const Ea=class e{constructor({renderer:e}={}){this.renderer=e,this.capacity=0,this.count=0}dispose(){this.target&&(this.target.dispose(),this.target=void 0)}static ensureBuffer(e,t){const n=4*(Math.ceil(Math.max(1,e)/br)*br);if(t.byteLength>=n)return t;const r=new ArrayBuffer(n);if(t instanceof ArrayBuffer)return r;return new(0,t.constructor)(r)}ensureBuffer(t,n){return e.ensureBuffer(t,n)}ensureCapacity(e){const{width:t,height:n,depth:i,maxSplats:s}=gi(e);(!this.target||s>this.capacity)&&(this.dispose(),this.capacity=s,this.target=new r.WebGLArrayRenderTarget(t,n,i,{depthBuffer:!1,stencilBuffer:!1,generateMipmaps:!1,magFilter:r.NearestFilter,minFilter:r.NearestFilter}),this.target.texture.format=r.RGBAFormat,this.target.texture.type=r.UnsignedByteType,this.target.texture.internalFormat="RGBA8",this.target.scissorTest=!0)}prepareProgramMaterial(t){let n=e.readbackProgram.get(t);if(!n){const r=qr({index:"int"},{rgba8:"vec4"},(({index:e})=>{t.inputs.index=e;return{rgba8:new vs({rgba8:t.outputs.rgba8})}}));e.programTemplate||(e.programTemplate=new Ds(Aa().computeVec4Template)),n=new Rs({graph:r,inputs:{index:"_index"},outputs:{rgba8:"target"},template:e.programTemplate}),Object.assign(n.uniforms,{targetLayer:{value:0},targetBase:{value:0},targetCount:{value:0}}),e.readbackProgram.set(t,n)}const r=n.prepareMaterial();return e.fullScreenQuad.material=r,{program:n,material:r}}saveRenderState(e){return{target:e.getRenderTarget(),xrEnabled:e.xr.enabled,autoClear:e.autoClear}}resetRenderState(e,t){e.setRenderTarget(t.target),e.xr.enabled=t.xrEnabled,e.autoClear=t.autoClear}process({count:t,material:n}){const r=this.renderer;if(!r)throw new Error("No renderer");if(!this.target)throw new Error("No target");const i=4194304;n.uniforms.targetBase.value=0,n.uniforms.targetCount.value=t;let s=0;for(;s<t;){const a=Math.floor(s/i),o=a*i,l=Math.min(wr,Math.ceil((t-o)/br));n.uniforms.targetLayer.value=a,this.target.scissor.set(0,0,br,l),r.setRenderTarget(this.target,a),r.xr.enabled=!1,r.autoClear=!1,e.fullScreenQuad.render(r),s+=br*l}this.count=t}async read({readback:e}){const t=this.renderer;if(!t)throw new Error("No renderer");if(!this.target)throw new Error("No target");const n=Math.ceil(this.count/br)*br;if(e.byteLength<4*n)throw new Error(`Readback buffer too small: ${e.byteLength} < ${4*n}`);const r=new Uint8Array(e instanceof ArrayBuffer?e:e.buffer),i=4194304;let s=0;const a=[];for(;s<this.count;){const e=Math.floor(s/i),n=e*i,o=Math.min(wr,Math.ceil((this.count-n)/br));t.setRenderTarget(this.target,e);const l=br*o*4,c=r.subarray(4*n,4*n+l),u=null==t?void 0:t.readRenderTargetPixelsAsync(this.target,0,0,br,o,c);a.push(u),s+=br*o}return Promise.all(a).then((()=>e))}render({reader:e,count:t,renderer:n}){if(this.renderer=n||this.renderer,!this.renderer)throw new Error("No renderer");this.ensureCapacity(t);const{program:r,material:i}=this.prepareProgramMaterial(e);r.update();const s=this.saveRenderState(this.renderer);this.process({count:t,material:i}),this.resetRenderState(this.renderer,s)}async readback({readback:e}){if(!this.renderer)throw new Error("No renderer");const t=this.saveRenderState(this.renderer),n=this.read({readback:e});return this.resetRenderState(this.renderer,t),n}async renderReadback({reader:e,count:t,renderer:n,readback:r}){if(this.renderer=n||this.renderer,!this.renderer)throw new Error("No renderer");this.ensureCapacity(t);const{program:i,material:s}=this.prepareProgramMaterial(e);i.update();const a=this.saveRenderState(this.renderer);this.process({count:t,material:s});const o=this.read({readback:r});return this.resetRenderState(this.renderer,a),o}getTexture(){var e;return null==(e=this.target)?void 0:e.texture}};Ea.programTemplate=null,Ea.readbackProgram=new WeakMap,Ea.fullScreenQuad=new o(new r.RawShaderMaterial({visible:!1}));let Ca=Ea;const Ra=class e{constructor(t={}){if(this.capacity=0,this.count=0,this.array=null,this.readback=null,this.source=null,this.needsUpdate=!0,this.dyno=new bs({key:"rgbaArray",type:ka,globals:()=>[Ia],value:{texture:e.getEmpty(),count:0},update:e=>(e.texture=this.getTexture(),e.count=this.count,e)}),t.array){this.array=t.array;const e=Math.floor(this.array.length/4);this.capacity=Math.ceil(e/br)*br,this.capacity>e&&(this.array=new Uint8Array(4*this.capacity),this.array.set(t.array)),this.count=Math.min(e,t.count??Number.POSITIVE_INFINITY)}else this.capacity=t.capacity??0,this.count=0}dispose(){this.readback&&(this.readback.dispose(),this.readback=null),this.source&&(this.source.dispose(),this.source=null)}ensureCapacity(e){var t;if(!this.array||e>((null==(t=this.array)?void 0:t.length)??0)/4){this.capacity=gi(e).maxSplats;const t=new Uint8Array(4*this.capacity);this.array&&t.set(this.array),this.array=t}return this.array}getTexture(){var t;let n=null==(t=this.readback)?void 0:t.getTexture();return(this.source||this.array)&&(n=this.maybeUpdateSource()),n??e.getEmpty()}maybeUpdateSource(){if(!this.array)throw new Error("No array");if(this.needsUpdate||!this.source){if(this.needsUpdate=!1,this.source){const{width:e,height:t,depth:n}=this.source.image;this.capacity!==e*t*n&&(this.source.dispose(),this.source=null)}if(this.source)this.array.buffer!==this.source.image.data.buffer&&(this.source.image.data=new Uint8Array(this.array.buffer));else{const{width:e,height:t,depth:n}=gi(this.capacity);this.source=new r.DataArrayTexture(this.array,e,t,n),this.source.format=r.RGBAFormat,this.source.type=r.UnsignedByteType,this.source.internalFormat="RGBA8",this.source.needsUpdate=!0}this.source.needsUpdate=!0}return this.source}render({reader:e,count:t,renderer:n}){this.readback||(this.readback=new Ca({renderer:n})),this.readback.render({reader:e,count:t,renderer:n}),this.capacity=this.readback.capacity,this.count=this.readback.count}fromPackedSplats({packedSplats:t,base:n,count:r,renderer:i}){const{dynoSplats:s,dynoBase:a,dynoCount:o,reader:l}=e.makeDynos();return s.packedSplats=t,a.value=n,o.value=r,this.render({reader:l,count:r,renderer:i}),this}async read(){if(!this.readback)throw new Error("No readback");(!this.array||this.array.length<4*this.count)&&(this.array=new Uint8Array(4*this.capacity));return(await this.readback.readback({readback:this.array})).subarray(0,4*this.count)}async getArray(){if(this.readback)return await this.read();if(this.array)return this.array;throw new Error("No array")}static getEmpty(){if(!e.emptySource){const t=new Uint8Array(4);e.emptySource=new r.DataArrayTexture(t,1,1,1),e.emptySource.format=r.RGBAFormat,e.emptySource.type=r.UnsignedByteType,e.emptySource.internalFormat="RGBA8",e.emptySource.needsUpdate=!0}return e.emptySource}static makeDynos(){if(!e.dynos){const t=new go,n=new Ts({value:0}),r=new Ts({value:0}),i=qr({index:"int"},{rgba8:"vec4"},(({index:e})=>{if(!e)throw new Error("index is undefined");e=Us(e,n);const i=((e,t,n,r)=>new Qi({packedSplats:e,index:t,base:n,count:r}))(t,e,n,r);return{rgba8:Ni(i).outputs.rgba}}));e.dynos={dynoSplats:t,dynoBase:n,dynoCount:r,reader:i}}return e.dynos}};Ra.emptySource=null,Ra.dynos=null;let Da=Ra;const ka={type:"RgbaArray"},Ia=Xr("\n struct RgbaArray {\n sampler2DArray texture;\n int count;\n };\n");function Pa(e){switch(e){case"all":return 0;case"plane":return 1;case"sphere":return 2;case"box":return 3;case"ellipsoid":return 4;case"cylinder":return 5;case"capsule":return 6;case"infinite_cone":return 7;default:throw new Error(`Unknown SDF type: ${e}`)}}function La(e){switch(e){case"multiply":return 0;case"set_rgb":return 1;case"add_rgba":return 2;default:throw new Error(`Unknown blend mode: ${e}`)}}class Ua extends r.Object3D{constructor(e={}){super();const{type:t,invert:n,opacity:i,color:s,displace:a,radius:o}=e;this.type=t??"sphere",this.invert=n??!1,this.opacity=i??1,this.color=s??new r.Color(1,1,1),this.displace=a??new r.Vector3(0,0,0),this.radius=o??0}}const Fa=class e extends r.Object3D{constructor(t={}){const{name:n,rgbaBlendMode:r="multiply",sdfSmooth:i=0,softEdge:s=0,invert:a=!1,sdfs:o=null}=t;super(),this.rgbaBlendMode=r,this.sdfSmooth=i,this.softEdge=s,this.invert=a,this.sdfs=o,this.ordering=e.nextOrdering++,this.name=n??`Edit ${this.ordering}`}addSdf(e){null==this.sdfs&&(this.sdfs=[]),this.sdfs.includes(e)||this.sdfs.push(e)}removeSdf(e){null!=this.sdfs&&(this.sdfs=this.sdfs.filter((t=>t!==e)))}};Fa.nextOrdering=1;let za=Fa;class Ba{constructor({maxSdfs:e,maxEdits:t}){this.maxSdfs=Math.max(16,e??0),this.numSdfs=0,this.sdfData=new Uint32Array(8*this.maxSdfs*4),this.sdfFloatData=new Float32Array(this.sdfData.buffer),this.sdfTexture=this.newSdfTexture(this.sdfData,this.maxSdfs),this.dynoSdfArray=new bs({key:"sdfArray",type:Va,globals:()=>[Oa],value:{numSdfs:0,sdfTexture:this.sdfTexture},update:e=>(e.numSdfs=this.numSdfs,e.sdfTexture=this.sdfTexture,e)}),this.maxEdits=Math.max(16,t??0),this.numEdits=0,this.editData=new Uint32Array(4*this.maxEdits),this.editFloatData=new Float32Array(this.editData.buffer),this.dynoNumEdits=new Ts({value:0}),this.dynoEdits=this.newEdits(this.editData,this.maxEdits)}newSdfTexture(e,t){const n=new r.DataTexture(e,8,t,r.RGBAIntegerFormat,r.UnsignedIntType);return n.internalFormat="RGBA32UI",n.needsUpdate=!0,n}newEdits(e,t){return new bs({key:"edits",type:"uvec4",count:t,globals:()=>[Na],value:e})}ensureCapacity({maxSdfs:e,maxEdits:t}){let n=!1;return e>this.sdfTexture.image.height&&(this.sdfTexture.dispose(),this.maxSdfs=Math.max(2*this.maxSdfs,e),this.sdfData=new Uint32Array(8*this.maxSdfs*4),this.sdfFloatData=new Float32Array(this.sdfData.buffer),this.sdfTexture=this.newSdfTexture(this.sdfData,this.maxSdfs)),t>(this.dynoEdits.count??0)&&(this.maxEdits=Math.max(2*this.maxEdits,t),this.editData=new Uint32Array(4*this.maxEdits),this.editFloatData=new Float32Array(this.editData.buffer),this.dynoEdits=this.newEdits(this.editData,this.maxEdits),n=!0),n}updateEditData(e,t){const n=this.editData[e]!==t;return this.editData[e]=t,n}updateEditFloatData(e,t){$a[0]=t;const n=this.editFloatData[e]!==$a[0];return n&&(this.editFloatData[e]=$a[0]),n}encodeEdit(e,{sdfFirst:t,sdfCount:n,invert:r,rgbaBlendMode:i,softEdge:s,sdfSmooth:a}){const o=4*e;let l=!1;return l=this.updateEditData(o+0,i|(r?256:0))||l,l=this.updateEditData(o+1,t|n<<16)||l,l=this.updateEditFloatData(o+2,s)||l,l=this.updateEditFloatData(o+3,a)||l,l}updateSdfData(e,t){const n=this.sdfData[e]!==t;return this.sdfData[e]=t,n}updateSdfFloatData(e,t){$a[0]=t;const n=this.sdfFloatData[e]!==$a[0];return n&&(this.sdfFloatData[e]=$a[0]),n}encodeSdf(e,{sdfType:t,invert:n,center:r,quaternion:i,scale:s,sizes:a},o){const l=32*e,c=t|(n?256:0);let u=!1;u=this.updateSdfFloatData(l+0,(null==r?void 0:r.x)??0)||u,u=this.updateSdfFloatData(l+1,(null==r?void 0:r.y)??0)||u,u=this.updateSdfFloatData(l+2,(null==r?void 0:r.z)??0)||u,u=this.updateSdfData(l+3,c)||u,u=this.updateSdfFloatData(l+4,(null==i?void 0:i.x)??0)||u,u=this.updateSdfFloatData(l+5,(null==i?void 0:i.y)??0)||u,u=this.updateSdfFloatData(l+6,(null==i?void 0:i.z)??0)||u,u=this.updateSdfFloatData(l+7,(null==i?void 0:i.w)??0)||u,u=this.updateSdfFloatData(l+8,(null==s?void 0:s.x)??0)||u,u=this.updateSdfFloatData(l+9,(null==s?void 0:s.y)??0)||u,u=this.updateSdfFloatData(l+10,(null==s?void 0:s.z)??0)||u,u=this.updateSdfData(l+11,0)||u,u=this.updateSdfFloatData(l+12,(null==a?void 0:a.x)??0)||u,u=this.updateSdfFloatData(l+13,(null==a?void 0:a.y)??0)||u,u=this.updateSdfFloatData(l+14,(null==a?void 0:a.z)??0)||u,u=this.updateSdfFloatData(l+15,(null==a?void 0:a.w)??0)||u;const h=Math.min(4,o.length);for(let d=0;d<h;++d){const e=l+16+4*d;u=this.updateSdfFloatData(e+0,o[d].x)||u,u=this.updateSdfFloatData(e+1,o[d].y)||u,u=this.updateSdfFloatData(e+2,o[d].z)||u,u=this.updateSdfFloatData(e+3,o[d].w)||u}return u}update(e){const t=e.reduce(((e,{sdfs:t})=>e+t.length),0),n=this.ensureCapacity({maxEdits:e.length,maxSdfs:t}),i=[new r.Vector4,new r.Vector4],s=new r.Vector3,a=new r.Quaternion,o=new r.Vector3,l=new r.Vector4;let c=0,u=n;e.length!==this.dynoNumEdits.value&&(this.dynoNumEdits.value=e.length,this.numEdits=e.length,u=!0);for(const[r,{edit:h,sdfs:d}]of e.entries()){u=this.encodeEdit(r,{sdfFirst:c,sdfCount:d.length,invert:h.invert,rgbaBlendMode:La(h.rgbaBlendMode),softEdge:h.softEdge,sdfSmooth:h.sdfSmooth})||u;let e=!1;for(const t of d){l.set(t.scale.x,t.scale.y,t.scale.z,t.radius),t.scale.setScalar(1),t.updateMatrixWorld();t.matrixWorld.clone().invert().decompose(s,a,o),t.scale.set(l.x,l.y,l.z),t.updateMatrixWorld(),i[0].set(t.color.r,t.color.g,t.color.b,t.opacity),i[1].set(t.displace.x,t.displace.y,t.displace.z,1),e=this.encodeSdf(c,{sdfType:Pa(t.type),invert:t.invert,center:s,quaternion:a,scale:o,sizes:l},i)||e,c+=1}this.numSdfs=c,e&&(this.sdfTexture.needsUpdate=!0),u||(u=e)}return{updated:u,dynoUpdated:n}}modify(e){return function(e,t,n,r){const i=new $r({inTypes:{gsplat:Ui,sdfArray:Va,numEdits:"int",rgbaDisplaceEdits:"uvec4"},outTypes:{gsplat:Ui},globals:()=>[Oa,Na],inputs:{gsplat:e,sdfArray:t,numEdits:n,rgbaDisplaceEdits:r},statements:({inputs:e,outputs:t})=>{const{sdfArray:n,numEdits:r,rgbaDisplaceEdits:i}=e,{gsplat:s}=t;return Wr(`\n ${s} = ${e.gsplat};\n if (isGsplatActive(${s}.flags)) {\n for (int editIndex = 0; editIndex < ${r}; ++editIndex) {\n applyPackedRgbaDisplaceEdit(\n ${i}[editIndex], ${n}.sdfTexture, ${n}.numSdfs,\n ${s}.center, ${s}.rgba\n );\n }\n }\n `)}});return i.outputs.gsplat}(e,this.dynoSdfArray,this.dynoNumEdits,this.dynoEdits)}modifyCov(e){return function(e,t,n,r){const i=new $r({inTypes:{covsplat:Fi,sdfArray:Va,numEdits:"int",rgbaDisplaceEdits:"uvec4"},outTypes:{covsplat:Fi},globals:()=>[Oa,Na],inputs:{covsplat:e,sdfArray:t,numEdits:n,rgbaDisplaceEdits:r},statements:({inputs:e,outputs:t})=>{const{sdfArray:n,numEdits:r,rgbaDisplaceEdits:i}=e,{covsplat:s}=t;return Wr(`\n ${s} = ${e.covsplat};\n if (isCovSplatActive(${s}.flags)) {\n for (int editIndex = 0; editIndex < ${r}; ++editIndex) {\n applyPackedRgbaDisplaceEdit(\n ${i}[editIndex], ${n}.sdfTexture, ${n}.numSdfs,\n ${s}.center, ${s}.rgba\n );\n }\n }\n `)}});return i.outputs.covsplat}(e,this.dynoSdfArray,this.dynoNumEdits,this.dynoEdits)}}const Va={type:"SdfArray"},Oa=Xr("\n struct SdfArray {\n int numSdfs;\n usampler2D sdfTexture;\n };\n\n void unpackSdfArray(\n usampler2D sdfTexture, int sdfIndex, out uint flags,\n out vec3 center, out vec4 quaternion, out vec3 scale, out vec4 sizes,\n int numValues, out vec4 values[4]\n ) {\n uvec4 temp = texelFetch(sdfTexture, ivec2(0, sdfIndex), 0);\n flags = temp.w;\n center = vec3(uintBitsToFloat(temp.x), uintBitsToFloat(temp.y), uintBitsToFloat(temp.z));\n\n temp = texelFetch(sdfTexture, ivec2(1, sdfIndex), 0);\n quaternion = vec4(uintBitsToFloat(temp.x), uintBitsToFloat(temp.y), uintBitsToFloat(temp.z), uintBitsToFloat(temp.w));\n\n temp = texelFetch(sdfTexture, ivec2(2, sdfIndex), 0);\n scale = vec3(uintBitsToFloat(temp.x), uintBitsToFloat(temp.y), uintBitsToFloat(temp.z));\n\n temp = texelFetch(sdfTexture, ivec2(3, sdfIndex), 0);\n sizes = vec4(uintBitsToFloat(temp.x), uintBitsToFloat(temp.y), uintBitsToFloat(temp.z), uintBitsToFloat(temp.w));\n\n for (int i = 0; i < numValues; ++i) {\n temp = texelFetch(sdfTexture, ivec2(4 + i, sdfIndex), 0);\n values[i] = vec4(uintBitsToFloat(temp.x), uintBitsToFloat(temp.y), uintBitsToFloat(temp.z), uintBitsToFloat(temp.w));\n }\n }\n\n const uint SDF_FLAG_TYPE = 0xFFu;\n const uint SDF_FLAG_INVERT = 1u << 8u;\n\n const uint SDF_TYPE_ALL = 0u;\n const uint SDF_TYPE_PLANE = 1u;\n const uint SDF_TYPE_SPHERE = 2u;\n const uint SDF_TYPE_BOX = 3u;\n const uint SDF_TYPE_ELLIPSOID = 4u;\n const uint SDF_TYPE_CYLINDER = 5u;\n const uint SDF_TYPE_CAPSULE = 6u;\n const uint SDF_TYPE_INFINITE_CONE = 7u;\n\n float evaluateSdfArray(\n usampler2D sdfTexture, int numSdfs, int sdfFirst, int sdfCount, vec3 pos,\n float smoothK, int numValues, out vec4 outValues[4]\n ) {\n float distanceAccum = (smoothK == 0.0) ? 1.0 / 0.0 : 0.0;\n float maxExp = -1.0 / 0.0;\n for (int i = 0; i < numValues; ++i) {\n outValues[i] = vec4(0.0);\n }\n\n uint flags;\n vec3 center, scale;\n vec4 quaternion, sizes;\n vec4 values[4];\n\n int sdfLast = min(sdfFirst + sdfCount, numSdfs);\n for (int index = sdfFirst; index < sdfLast; ++index) {\n unpackSdfArray(sdfTexture, index, flags, center, quaternion, scale, sizes, numValues, values);\n uint sdfType = flags & SDF_FLAG_TYPE;\n vec3 sdfPos = quatVec(quaternion, pos * scale) + center;\n\n float distance;\n switch (sdfType) {\n case SDF_TYPE_ALL:\n distance = -1.0 / 0.0;\n break;\n case SDF_TYPE_PLANE: {\n distance = sdfPos.z;\n break;\n }\n case SDF_TYPE_SPHERE: {\n distance = length(sdfPos) - sizes.w;\n break;\n }\n case SDF_TYPE_BOX: {\n vec3 q = abs(sdfPos) - sizes.xyz + sizes.w;\n distance = length(max(q, 0.0)) + min(max(q.x, max(q.y, q.z)), 0.0) - sizes.w;\n break;\n }\n case SDF_TYPE_ELLIPSOID: {\n vec3 sizes = sizes.xyz;\n float k0 = length(sdfPos / sizes);\n float k1 = length(sdfPos / dot(sizes, sizes));\n distance = k0 * (k0 - 1.0) / k1;\n break;\n }\n case SDF_TYPE_CYLINDER: {\n vec2 d = abs(vec2(length(sdfPos.xz), sdfPos.y)) - sizes.wy;\n distance = min(max(d.x, d.y), 0.0) + length(max(d, 0.0));\n break;\n }\n case SDF_TYPE_CAPSULE: {\n sdfPos.y -= clamp(sdfPos.y, -0.5 * sizes.y, 0.5 * sizes.y);\n distance = length(sdfPos) - sizes.w;\n break;\n }\n case SDF_TYPE_INFINITE_CONE: {\n float angle = 0.25 * PI * sizes.w;\n vec2 c = vec2(sin(angle), cos(angle));\n vec2 q = vec2(length(sdfPos.xy), -sdfPos.z);\n float d = length(q - c * max(dot(q, c), 0.0));\n distance = d * (((q.x * c.y - q.y * c.x) < 0.0) ? -1.0 : 1.0);\n break;\n }\n }\n\n if ((flags & SDF_FLAG_INVERT) != 0u) {\n distance = -distance;\n }\n\n if (smoothK == 0.0) {\n if (distance < distanceAccum) {\n distanceAccum = distance;\n for (int i = 0; i < numValues; ++i) {\n outValues[i] = values[i];\n }\n }\n } else {\n float scaledDistance = -distance / smoothK;\n if (scaledDistance > maxExp) {\n float scale = exp(maxExp - scaledDistance);\n distanceAccum *= scale;\n for (int i = 0; i < numValues; ++i) {\n outValues[i] *= scale;\n }\n maxExp = scaledDistance;\n }\n\n float weight = exp(scaledDistance - maxExp);\n distanceAccum += weight;\n for (int i = 0; i < numValues; ++i) {\n outValues[i] += weight * values[i];\n }\n }\n }\n\n if (smoothK == 0.0) {\n return distanceAccum;\n } else {\n // Very distant SDFs may result in 0 accumulation\n if (distanceAccum == 0.0) {\n return 1.0 / 0.0;\n }\n for (int i = 0; i < numValues; ++i) {\n outValues[i] /= distanceAccum;\n }\n return (-log(distanceAccum) - maxExp) * smoothK;\n }\n }\n\n float modulateSdfArray(\n usampler2D sdfTexture, int numSdfs, int sdfFirst, int sdfCount, vec3 pos,\n float smoothK, int numValues, out vec4 values[4],\n float softEdge, bool invert\n ) {\n float distance = evaluateSdfArray(sdfTexture, numSdfs, sdfFirst, sdfCount, pos, smoothK, numValues, values);\n if (invert) {\n distance = -distance;\n }\n\n return (softEdge == 0.0) ? ((distance < 0.0) ? 1.0 : 0.0)\n : clamp(-distance / softEdge + 0.5, 0.0, 1.0);\n }\n"),Na=Xr("\n const uint EDIT_FLAG_BLEND = 0xFFu;\n const uint EDIT_BLEND_MULTIPLY = 0u;\n const uint EDIT_BLEND_SET_RGB = 1u;\n const uint EDIT_BLEND_ADD_RGBA = 2u;\n const uint EDIT_FLAG_INVERT = 0x100u;\n\n void decodeEdit(\n uvec4 packedEdit, out int sdfFirst, out int sdfCount,\n out bool invert, out uint rgbaBlendMode, out float softEdge, out float sdfSmooth\n ) {\n rgbaBlendMode = packedEdit.x & EDIT_FLAG_BLEND;\n invert = (packedEdit.x & EDIT_FLAG_INVERT) != 0u;\n\n sdfFirst = int(packedEdit.y & 0xFFFFu);\n sdfCount = int(packedEdit.y >> 16u);\n\n softEdge = uintBitsToFloat(packedEdit.z);\n sdfSmooth = uintBitsToFloat(packedEdit.w);\n }\n\n void applyRgbaDisplaceEdit(\n usampler2D sdfTexture, int numSdfs, int sdfFirst, int sdfCount, inout vec3 pos,\n float smoothK, float softEdge, bool invert, uint rgbaBlendMode, inout vec4 rgba\n ) {\n vec4 values[4];\n float modulate = modulateSdfArray(sdfTexture, numSdfs, sdfFirst, sdfCount, pos, smoothK, 2, values, softEdge, invert);\n // On Android, moving values[0] is necessary to work around a compiler bug.\n vec4 sdfRgba = values[0];\n vec4 sdfDisplaceScale = values[1];\n\n vec4 target;\n switch (rgbaBlendMode) {\n case EDIT_BLEND_MULTIPLY:\n target = rgba * sdfRgba;\n break;\n case EDIT_BLEND_SET_RGB:\n target = vec4(sdfRgba.rgb, rgba.a * sdfRgba.a);\n break;\n case EDIT_BLEND_ADD_RGBA:\n target = rgba + sdfRgba;\n break;\n default:\n // Debug output if blend mode not set\n target = vec4(fract(pos), 1.0);\n }\n rgba = mix(rgba, target, modulate);\n pos += sdfDisplaceScale.xyz * modulate;\n }\n\n void applyPackedRgbaDisplaceEdit(uvec4 packedEdit, usampler2D sdfTexture, int numSdfs, inout vec3 pos, inout vec4 rgba) {\n int sdfFirst, sdfCount;\n bool invert;\n uint rgbaBlendMode;\n float softEdge, sdfSmooth;\n decodeEdit(packedEdit, sdfFirst, sdfCount, invert, rgbaBlendMode, softEdge, sdfSmooth);\n applyRgbaDisplaceEdit(sdfTexture, numSdfs, sdfFirst, sdfCount, pos, sdfSmooth, softEdge, invert, rgbaBlendMode, rgba);\n }\n");const $a=new Float32Array(1);class Ga{constructor(e){this.modifier=e,this.cache=new Map}apply(e){let t=this.cache.get(e);return t||(t=qr({index:"int"},{gsplat:Ui},(({index:t})=>{const{gsplat:n}=e.apply({index:t});return this.modifier.apply({gsplat:n})})),this.cache.set(e,t)),t}}class qa{constructor(){this.scale=new Ss({value:Number.NEGATIVE_INFINITY}),this.rotate=new Ms({value:new r.Quaternion(Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY)}),this.translate=new _s({value:new r.Vector3(Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY)})}apply(e){return((e,{scale:t,scales:n,rotate:r,translate:i})=>new Xs({position:e,scale:t,scales:n,rotate:r,translate:i}).outputs.position)(e,{scale:this.scale,rotate:this.rotate,translate:this.translate})}applyDir(e){return((e,{scale:t,scales:n,rotate:r})=>new Ys({dir:e,scale:t,scales:n,rotate:r}).outputs.dir)(e,{rotate:this.rotate})}applyGsplat(e){return Gi(e,{scale:this.scale,rotate:this.rotate,translate:this.translate})}updateFromMatrix(e){const t=new r.Vector3,n=new r.Quaternion,i=new r.Vector3;e.decompose(i,n,t);const s=(t.x+t.y+t.z)/3;let a=!1;return s!==this.scale.value&&(this.scale.value=s,a=!0),i.equals(this.translate.value)||(this.translate.value.copy(i),a=!0),n.equals(this.rotate.value)||(this.rotate.value.copy(n),a=!0),a}update(e){return e.updateMatrixWorld(),this.updateFromMatrix(e.matrixWorld)}}class Ha{constructor(){this.basis=new As({value:new r.Matrix3}),this.offset=new _s({value:new r.Vector3})}apply(e){const t=zs(this.basis,e);return Us(t,this.offset)}applyDir(e){return zs(this.basis,e)}applyCovSplat(e){return new $r({inTypes:{covsplat:Fi,basis:"mat3",offset:"vec3"},outTypes:{covsplat:Fi},inputs:{covsplat:e,basis:this.basis,offset:this.offset},statements:({inputs:e,outputs:t})=>{const{covsplat:n,basis:r,offset:i}=e;return n&&r&&i?Wr(`\n ${t.covsplat}.flags = 0u;\n if (isCovSplatActive(${n}.flags)) {\n ${t.covsplat}.flags = ${n}.flags;\n ${t.covsplat}.index = ${n}.index;\n ${t.covsplat}.rgba = ${n}.rgba;\n\n ${t.covsplat}.center = ${r} * ${n}.center + ${i};\n \n mat3 cov = mat3(\n ${n}.xxyyzz.x, ${n}.xyxzyz.x, ${n}.xyxzyz.y,\n ${n}.xyxzyz.x, ${n}.xxyyzz.y, ${n}.xyxzyz.z,\n ${n}.xyxzyz.y, ${n}.xyxzyz.z, ${n}.xxyyzz.z\n );\n cov = ${r} * cov * transpose(${r});\n ${t.covsplat}.xxyyzz = vec3(cov[0][0], cov[1][1], cov[2][2]);\n ${t.covsplat}.xyxzyz = vec3(cov[0][1], cov[0][2], cov[1][2]);\n }\n `):[`${t.covsplat}.flags = 0u;`]}}).outputs.covsplat}updateFromMatrix(e){const t=(new r.Matrix3).setFromMatrix4(e),n=(new r.Vector3).setFromMatrixColumn(e,3),i=!t.equals(this.basis.value)||!n.equals(this.offset.value);return i&&(this.basis.value.copy(t),this.offset.value.copy(n)),i}update(e){return e.updateMatrixWorld(),this.updateFromMatrix(e.matrixWorld)}}class ja extends r.Object3D{constructor({numSplats:e,generator:t,covGenerator:n,construct:r,update:i}){if(super(),this.numSplats=e??0,this.generator=t,this.covGenerator=n,this.frameUpdate=i,this.version=0,this.mappingVersion=0,r){const e=r(this);Object.assign(this,e)}}updateVersion(){this.version+=1}updateMappingVersion(){this.mappingVersion+=1,this.version+=1}set needsUpdate(e){e&&this.updateVersion()}}const Wa=class e{constructor({extSplats:e,covSplats:t}={}){if(this.time=0,this.deltaTime=0,this.viewToWorld=new r.Matrix4,this.viewOrigin=new r.Vector3,this.viewDirection=new r.Vector3,this.maxSplats=0,this.numSplats=0,this.target=null,this.mapping=[],this.version=-1,this.mappingVersion=-1,this.readback=null,this.readbackSplats=[],!Qr)throw new Error("Spark requires THREE.js r179 or above");this.extSplats=e??!0,this.covSplats=t??!1}dispose(){this.target&&(this.target.dispose(),this.target=null)}getTextures(){return this.target?this.target.textures:e.emptyTextures}generateMapping(e){let t=0;const n=e.map((e=>{const n=t,r=Math.ceil(e/br)*br;return t+=r,{base:n,count:e}}));return{maxSplats:t,mapping:n}}ensureGenerate({maxSplats:e}){if(this.target&&(e??1)<=this.maxSplats)return!1;this.dispose();const t=gi(e??1),{width:n,height:i,depth:s}=t;if(this.maxSplats=t.maxSplats,this.target=new r.WebGLArrayRenderTarget(n,i,s,{depthBuffer:!1,stencilBuffer:!1,generateMipmaps:!1,magFilter:r.NearestFilter,minFilter:r.NearestFilter,format:r.RGBAIntegerFormat,type:r.UnsignedIntType}),this.target.scissorTest=!0,this.extSplats){const e=this.target.texture.clone(),t=this.target.texture.clone();t.format=r.RGBAFormat,t.type=r.UnsignedByteType,t.internalFormat="RGBA8",this.target.textures=[this.target.texture,e,t]}else{const e=this.target.texture.clone();e.format=r.RGBAFormat,e.type=r.UnsignedByteType,e.internalFormat="RGBA8",this.target.textures=[this.target.texture,e]}return!0}saveRenderState(e){return{target:e.getRenderTarget(),xrEnabled:e.xr.enabled,autoClear:e.autoClear}}resetRenderState(e,t){e.setRenderTarget(t.target),e.xr.enabled=t.xrEnabled,e.autoClear=t.autoClear}prepareProgramMaterial(t,n){const r=t??n;if(!r)throw new Error("Either generator or covGenerator must be provided");let i=e.generatorProgram.get(r);if(!i){const s=qr({index:"int"},{},(({index:r},i,{roots:s})=>{if(t&&(t.inputs.index=r),n&&(n.inputs.index=r),this.extSplats)if(this.covSplats)if(n){const e=ds(n.outputs.covsplat);s.push(e)}else{if(!t)throw new Error("Generator must be provided");{const e=Oi(t.outputs.gsplat),n=ds(e);s.push(n)}}else{if(!t)throw new Error("Generator must be provided");{const e=(a=t.outputs.gsplat,new fs({gsplat:a}));s.push(e)}}else{if(this.covSplats){let r;if(n)r=n.outputs.covsplat;else{if(!t)throw new Error("Generator must be provided");r=Oi(t.outputs.gsplat)}const i=Fs(ss(r).outputs.center,e.viewCenterUniform),a=zs(ss(r).outputs.opacity,Br("float",.5));r=as({covsplat:r,center:i,opacity:a});const o=((e,t)=>new ms({covsplat:e,rgbMinMaxLnScaleMinMax:t}))(r,Br("vec4",[0,1,yr,9]));s.push(o)}else{if(!t)throw new Error("Generator must be provided");{const n=Fs(Ni(t.outputs.gsplat).outputs.center,e.viewCenterUniform),r=zs(Ni(t.outputs.gsplat).outputs.opacity,Br("float",.5)),i=$i({gsplat:t.outputs.gsplat,center:n,opacity:r}),a=hs(i,Br("vec4",[0,1,yr,9]));s.push(a)}}if(!t)throw new Error("Generator must be provided")}var a,o,l,c,u;if(t){const n=((e,t,n,r)=>new xs({gsplat:e,viewCenter:t,viewDir:n,sortRadial:r}))(t.outputs.gsplat,e.viewCenterUniform,e.viewDirUniform,e.sortRadialUniform);s.push(n)}if(n){const t=(o=n.outputs.covsplat,l=e.viewCenterUniform,c=e.viewDirUniform,u=e.sortRadialUniform,new ys({covsplat:o,viewCenter:l,viewDir:c,sortRadial:u}));s.push(t)}}));i=new Rs({graph:s,inputs:{index:"_index"},outputs:{},template:this.extSplats?e.programExtTemplate:e.programTemplate}),e.generatorProgram.set(r,i)}Object.assign(i.uniforms,{targetLayer:{value:0},targetBase:{value:0},targetCount:{value:0}});const s=i.prepareMaterial();return e.fullScreenQuad.material=s,{program:i,material:s}}generate({generator:t,covGenerator:n,base:r,count:i,renderer:s}){if(!this.target)throw new Error("Target must be initialized with ensureGenerate");if(r+i>this.maxSplats)throw new Error("Base + count exceeds maxSplats");const{program:a,material:o}=this.prepareProgramMaterial(t,n);a.update();const l=this.saveRenderState(s),c=Math.ceil((r+i)/br)*br,u=4194304;for(o.uniforms.targetBase.value=r,o.uniforms.targetCount.value=i;r<c;){const t=Math.floor(r/u);o.uniforms.targetLayer.value=t;const n=t*u,i=Math.floor((r-n)/br),a=Math.min(wr,Math.ceil((c-n)/br));this.target.scissor.set(0,i,br,a-i),s.setRenderTarget(this.target,t),s.xr.enabled=!1,s.autoClear=!1,e.fullScreenQuad.render(s),r+=br*(a-i)}return this.resetRenderState(s,l),{nextBase:c}}prepareGenerate({renderer:t,scene:n,time:r,camera:i,sortRadial:s,renderSize:a,previous:o,lodInstances:l}){var c;this.viewToWorld.copy(i.matrixWorld),i.getWorldPosition(this.viewOrigin),i.getWorldDirection(this.viewDirection),e.viewCenterUniform.value.copy(this.viewOrigin),e.viewDirUniform.value.copy(this.viewDirection),e.sortRadialUniform.value=s,this.time=r,this.deltaTime=r-o.time;const u=[];n.traverse((e=>{e instanceof ja&&(i.layers&&!i.layers.test(e.layers)||u.push(e))}));const h=new Set;n.traverseVisible((e=>{if(e instanceof za){let t=e.parent;for(;null!=t&&!(t instanceof lo);)t=t.parent;null==t&&h.add(e)}}));const d=Array.from(h);for(const e of u)try{null==(c=e.frameUpdate)||c.call(e,{renderer:t,object:e,time:this.time,deltaTime:this.deltaTime,viewToWorld:this.viewToWorld,camera:i,renderSize:a,globalEdits:d,lodIndices:l&&e instanceof lo?l.get(e):void 0})}catch(b){e.generator=void 0,e.covGenerator=void 0,e.generatorError=b}const p=[];n.traverseVisible((e=>{e instanceof ja&&(i.layers&&!i.layers.test(e.layers)||p.push(e))}));const m=p.map((e=>e.numSplats)),{maxSplats:f,mapping:g}=this.generateMapping(m),x=o.mapping.reduce(((e,t)=>(e.set(t.node,t),e)),new Map);this.mapping=[],this.numSplats=0,g.forEach((({base:e,count:t},n)=>{const r=p[n],i=x.get(r);i&&i.count!==r.numSplats&&r.updateMappingVersion();const{generator:s,covGenerator:a}=r;if((s||a)&&t>0){const{version:n,mappingVersion:i}=r;this.mapping.push({node:r,generator:s,covGenerator:a,version:n,mappingVersion:i,base:e,count:t}),this.numSplats=Math.max(this.numSplats,e+t)}}));const{splatsUpdated:y,mappingUpdated:v}=o.checkVersions(this.mapping);return this.version=o.version+(y?1:0),this.mappingVersion=o.mappingVersion+(v?1:0),{sameMapping:!v,version:this.version,mappingVersion:this.mappingVersion,visibleGenerators:p,generate:()=>{this.ensureGenerate({maxSplats:f});for(const{node:e,base:n,count:r}of this.mapping){const{generator:i,covGenerator:s}=e;(i||s)&&r>0&&this.generate({generator:i,covGenerator:s,base:n,count:r,renderer:t})}},readback:async()=>{const e=this.getTextures();0===this.readbackSplats.length&&(this.readbackSplats=[new Cs({value:e[0],key:"extSplats"}),new Cs({value:e[1],key:"extSplats"})]),this.readbackSplats[0].value=e[0],this.readbackSplats[1].value=e[1],this.readback||(this.readback=new Ca({renderer:t}));const n=this.readback,r=this.extSplats?8:4,i=n.ensureBuffer(this.numSplats*r,new Uint32Array(0)),s=qr({index:"int"},{rgba8:"vec4"},(({index:e})=>({rgba8:new $r({inTypes:{index:"int",extSplats1:"usampler2DArray",extSplats2:"usampler2DArray"},outTypes:{rgba8:"vec4"},inputs:{index:e,extSplats1:this.readbackSplats[0],extSplats2:this.readbackSplats[1]},statements:({inputs:e,outputs:t})=>this.extSplats?Wr(`\n int indexDiv8 = ${e.index} >> 3;\n ivec3 coord = splatTexCoord(indexDiv8);\n uvec4 packedData;\n if ((${e.index} & 4) == 0) {\n packedData = texelFetch(${e.extSplats1}, coord, 0);\n } else {\n packedData = texelFetch(${e.extSplats2}, coord, 0);\n }\n\n int indexMod4 = ${e.index} & 3;\n uint data = (indexMod4 == 0) ? packedData.x\n : (indexMod4 == 1) ? packedData.y\n : (indexMod4 == 2) ? packedData.z\n : packedData.w;\n ${t.rgba8} = uintToVec4(data);\n `):Wr(`\n int indexDiv4 = ${e.index} >> 2;\n ivec3 coord = splatTexCoord(indexDiv4);\n uvec4 packedData = texelFetch(${e.extSplats1}, coord, 0);\n\n int indexMod4 = ${e.index} & 3;\n uint data = (indexMod4 == 0) ? packedData.x\n : (indexMod4 == 1) ? packedData.y\n : (indexMod4 == 2) ? packedData.z\n : packedData.w;\n ${t.rgba8} = uintToVec4(data);\n `)}).outputs.rgba8})));return await n.renderReadback({reader:s,count:this.numSplats*r,renderer:t,readback:i})}}}checkVersions(e){if(this.mapping.length!==e.length)return{splatsUpdated:!0,mappingUpdated:!0};const t=this.mapping.some(((t,n)=>{const r=e[n];return t.node!==r.node||t.base!==r.base||t.count!==r.count||t.mappingVersion!==r.mappingVersion}));if(t)return{splatsUpdated:!0,mappingUpdated:!0};return{splatsUpdated:this.mapping.some(((t,n)=>t.version!==e[n].version)),mappingUpdated:t}}};Wa.viewCenterUniform=new _s({value:new r.Vector3}),Wa.viewDirUniform=new _s({value:new r.Vector3}),Wa.sortRadialUniform=new ws({value:!0}),Wa.emptyTexture=(()=>{const{width:e,height:t,depth:n,maxSplats:i}=gi(1),s=new Uint32Array(4*i),a=new r.DataArrayTexture(s,e,t,n);return a.format=r.RGBAIntegerFormat,a.type=r.UnsignedIntType,a.internalFormat="RGBA32UI",a.needsUpdate=!0,a})(),Wa.emptyTextures=[Wa.emptyTexture,Wa.emptyTexture],Wa.programExtTemplate=new Ds(Aa().computeUvec4x2Vec4Template),Wa.programTemplate=new Ds(Aa().computeUvec4Vec4Template),Wa.generatorProgram=new WeakMap,Wa.fullScreenQuad=new o(new r.RawShaderMaterial({visible:!1}));let Xa=Wa;class Ya extends r.InstancedBufferGeometry{constructor(){super(),this.setAttribute("position",new r.BufferAttribute(Ka,3)),this.setIndex(new r.BufferAttribute(Qa,1))}}const Ka=new Float32Array([-1,-1,0,1,-1,0,1,1,0,-1,1,0]),Qa=new Uint16Array([0,1,2,0,2,3]),Za=class e extends r.Mesh{constructor(t){if(!t)throw new Error("SparkRenderer options are required");if(!t.renderer)throw new Error("renderer is required in SparkRenderer options");const n=e.makeUniforms();Object.assign(n,t.extraUniforms??{});const i=Aa(),s=t.premultipliedAlpha??!0,a=new Ya,o=new r.ShaderMaterial({glslVersion:r.GLSL3,vertexShader:t.vertexShader??i.splatVertex,fragmentShader:t.fragmentShader??i.splatFragment,uniforms:n,premultipliedAlpha:s,transparent:t.transparent??!0,depthTest:t.depthTest??!0,depthWrite:t.depthWrite??!1,side:r.DoubleSide,allowOverride:!1});super(a,o),this.renderSize=new r.Vector2,this.lastFrame=-1,this.updateTimeoutId=-1,this.orderingTexture=null,this.maxSplats=0,this.activeSplats=0,this.accumulators=[],this.sorting=!1,this.sortDirty=!1,this.lastSortTime=0,this.sortWorker=null,this.sortTimeoutId=-1,this.sortedCenter=(new r.Vector3).setScalar(Number.NEGATIVE_INFINITY),this.sortedDir=(new r.Vector3).setScalar(0),this.readback32=new Uint32Array(0),this.lastLodRaycastTime=0,this.lodWorker=null,this.lodMeshes=[],this.lodDirty=!1,this.lodIds=new Map,this.lodIdToSplats=new Map,this.lodInitQueue=[],this.lodInstances=new Map,this.lodUpdates=[],this.lastTraverseTime=0,this.pagerId=0,this.superXY=1,this.flushAfterGenerate=!1,this.flushAfterRead=!1,this.readPause=1,this.sortPause=0,this.sortDelay=0,this.pageSizeWarning=!1,this.material=o,this.uniforms=n,this.frustumCulled=!1,this.renderer=t.renderer,this.onDirty=t.onDirty,this.dirty=!0,this.autoUpdate=t.autoUpdate??!0,this.preUpdate=t.preUpdate??!0,this.maxStdDev=t.maxStdDev??Math.sqrt(8),this.minPixelRadius=t.minPixelRadius??0,this.maxPixelRadius=t.maxPixelRadius??512,this.accumExtSplats=t.accumExtSplats??!1,this.covSplats=t.covSplats??!1,this.minAlpha=t.minAlpha??1/255*.5,this.enable2DGS=t.enable2DGS??!1,this.preBlurAmount=t.preBlurAmount??0,this.blurAmount=t.blurAmount??.3,this.focalDistance=t.focalDistance??0,this.apertureAngle=t.apertureAngle??0,this.falloff=t.falloff??1,this.clipXY=t.clipXY??1.4,this.focalAdjustment=t.focalAdjustment??1,this.encodeLinear=t.encodeLinear??!1,this.sortRadial=t.sortRadial??!0,this.minSortIntervalMs=t.minSortIntervalMs??0,this.enableLod=t.enableLod??!0,this.enableDriveLod=t.enableDriveLod??this.enableLod,this.enableLodFetching=t.enableLodFetching??!0,this.lodSplatCount=t.lodSplatCount,this.lodSplatScale=t.lodSplatScale??1,this.lodRenderScale=t.lodRenderScale??1,this.lodInflate=t.lodInflate??!1,this.pagedExtSplats=t.pagedExtSplats??!1;const l=xi()?yi()?96:128:256;this.maxPagedSplats=t.maxPagedSplats??65536*l,this.numLodFetchers=t.numLodFetchers??3,this.behindFoveate=t.behindFoveate??.2,this.coneFov0=t.coneFov0??90,this.coneFov=t.coneFov??120,this.coneFoveate=t.coneFoveate??.4,this.lodRaycast=void 0===t.lodRaycast?xi()?1e4:25e3:t.lodRaycast,this.lodRaycastIntervalMs=t.lodRaycastIntervalMs??500,this.clock=t.clock?vi(t.clock):new r.Clock;const c={extSplats:this.accumExtSplats,covSplats:this.covSplats};if(this.display=new Xa(c),this.current=this.display,this.accumulators.push(new Xa(c)),this.accumulators.push(new Xa(c)),t.target){const{width:e,height:n,doubleBuffer:i,superXY:s,...a}=t.target,o=Math.max(1,Math.min(4,s??1));if(e*o>8192||n*o>8192)throw new Error("Target size too large");this.superXY=o;const l=e*o,c=n*o,u={format:r.RGBAFormat,type:r.UnsignedByteType,colorSpace:r.SRGBColorSpace,...a};this.target=new r.WebGLRenderTarget(l,c,u),i&&(this.backTarget=new r.WebGLRenderTarget(l,c,u)),this.encodeLinear=t.encodeLinear??!0}}static makeUniforms(){return{renderSize:{value:new r.Vector2},near:{value:.1},far:{value:1e3},renderToViewQuat:{value:new r.Quaternion},renderToViewPos:{value:new r.Vector3},renderToViewBasis:{value:new r.Matrix3},renderToViewOffset:{value:new r.Vector3},maxStdDev:{value:1},minPixelRadius:{value:0},maxPixelRadius:{value:512},minAlpha:{value:1/255*.5},enable2DGS:{value:!1},lodInflate:{value:!1},preBlurAmount:{value:0},blurAmount:{value:.3},focalDistance:{value:0},apertureAngle:{value:0},falloff:{value:1},clipXY:{value:1.4},focalAdjustment:{value:1},encodeLinear:{value:!1},ordering:{type:"t",value:e.emptyOrdering},enableExtSplats:{value:!1},enableCovSplats:{value:!1},extSplats:{type:"t",value:Xa.emptyTexture},extSplats2:{type:"t",value:Xa.emptyTexture},time:{value:0},deltaTime:{value:0},debugFlag:{value:!1}}}dispose(){this.target&&(this.target.dispose(),this.target=void 0),this.backTarget&&(this.backTarget.dispose(),this.backTarget=void 0),this.orderingTexture&&(this.orderingTexture.dispose(),this.orderingTexture=null);const e=new Set;e.add(this.display),e.add(this.current);for(const n of this.accumulators)e.add(n);for(const n of e)n.dispose();const t=this.lodInstances.values();this.lodInstances.clear();for(const n of t)n.texture.dispose();this.sortWorker&&(this.sortWorker.dispose(),this.sortWorker=null),this.lodWorker&&(this.lodWorker.dispose(),this.lodWorker=null),this.pager&&(this.pager.dispose(),this.pager=void 0)}setDirty(){var e;this.dirty||(this.dirty=!0,null==(e=this.onDirty)||e.call(this))}onBeforeRender(t,n,i){var s;const a=e.sparkOverride??this,o=t.info.render.frame,l=o!==a.lastFrame;if(a.lastFrame=o,a.target)a.renderSize.set(a.target.width,a.target.height);else{const e=t.getDrawingBufferSize(a.renderSize);if(t.xr.isPresenting&&1===e.x&&1===e.y){const n=null==(s=t.xr.getSession())?void 0:s.renderState.baseLayer;n&&(e.x=n.framebufferWidth,e.y=n.framebufferHeight)}}this.uniforms.renderSize.value.copy(a.renderSize);const c=i;this.uniforms.near.value=c.near,this.uniforms.far.value=c.far;this.geometry.instanceCount=a.activeSplats;const u=new r.Matrix4;this.display.extSplats||u.makeTranslation(a.display.viewOrigin);const h=i.matrixWorld.clone().invert().multiply(u);if(h.decompose(this.uniforms.renderToViewPos.value,this.uniforms.renderToViewQuat.value,new r.Vector3),this.uniforms.renderToViewBasis.value.setFromMatrix4(h),this.uniforms.maxStdDev.value=a.maxStdDev,this.uniforms.minPixelRadius.value=a.minPixelRadius,this.uniforms.maxPixelRadius.value=a.maxPixelRadius,this.uniforms.minAlpha.value=a.minAlpha,this.uniforms.enable2DGS.value=a.enable2DGS,this.uniforms.lodInflate.value=a.lodInflate,this.uniforms.preBlurAmount.value=a.preBlurAmount,this.uniforms.blurAmount.value=a.blurAmount,this.uniforms.focalDistance.value=a.focalDistance,this.uniforms.apertureAngle.value=a.apertureAngle,this.uniforms.falloff.value=a.falloff,this.uniforms.clipXY.value=a.clipXY,this.uniforms.focalAdjustment.value=a.focalAdjustment,this.uniforms.encodeLinear.value=a.encodeLinear,this.uniforms.ordering.value=a.orderingTexture??e.emptyOrdering,this.uniforms.enableExtSplats.value=this.display.extSplats,this.uniforms.enableCovSplats.value=this.display.covSplats,this.display.extSplats){const e=a.display.getTextures();this.uniforms.extSplats.value=e[0],this.uniforms.extSplats2.value=e[1]}else{const e=a.display.getTextures();this.uniforms.extSplats.value=e[0],this.uniforms.extSplats2.value=e[0]}if(this.uniforms.time.value=a.display.time,this.uniforms.deltaTime.value=a.display.deltaTime,this.uniforms.debugFlag.value=performance.now()/1e3%2<1,a.autoUpdate&&l){const e=a.preUpdate&&!t.xr.isPresenting,r=t.xr.isPresenting?t.xr.getCamera():i;e?a.updateInternal({scene:n,camera:r,autoUpdate:!0}):-1===a.updateTimeoutId&&(a.updateTimeoutId=setTimeout((()=>{a.updateTimeoutId=-1,a.updateInternal({scene:n,camera:r,autoUpdate:!0})}),1))}a.dirty=!1}clearSplats(){this.activeSplats=0,this.display.numSplats=0,this.setDirty()}async update({scene:e,camera:t}){await this.updateInternal({scene:e,camera:t,autoUpdate:!1})}async updateInternal({scene:e,camera:t,autoUpdate:n}){const i=this.renderer,s=this.time??this.clock.getElapsedTime(),a=t.getWorldPosition(new r.Vector3),o=t.getWorldDirection(new r.Vector3),l=a.distanceTo(this.sortedCenter)>.001||o.dot(this.sortedDir)<.999,c=this.accumulators.pop();if(!c)throw new Error("No next accumulator");if(c===this.current)throw new Error("Next accumulator is the same as the current accumulator");const{version:u,mappingVersion:h,visibleGenerators:d,generate:p}=c.prepareGenerate({renderer:i,scene:e,time:s,camera:t,sortRadial:this.sortRadial??!0,renderSize:this.renderSize,previous:this.current,lodInstances:this.enableLod?this.lodInstances:void 0});let m=!0;const f=l||u!==this.current.version;if(n&&!f&&(m=!1),h!==this.display.mappingVersion&&this.sorting&&(m=!1),m){if(p(),this.flushAfterGenerate){i.getContext().flush()}this.display.mappingVersion===c.mappingVersion?(this.accumulators.push(this.display),this.display=c):this.display!==this.current&&this.accumulators.push(this.current),this.current=c,this.sortDirty=!0,this.setDirty()}else this.accumulators.push(c);this.enableDriveLod&&this.driveLod({visibleGenerators:d,camera:t,scene:e}),await this.driveSort()}async driveSort(){if(this.sorting||!this.sortDirty)return;-1!==this.sortTimeoutId&&(clearTimeout(this.sortTimeoutId),this.sortTimeoutId=-1);const e=performance.now(),t=this.lastSortTime?this.lastSortTime+this.minSortIntervalMs:e;if(e<t)return void(this.sortTimeoutId=setTimeout((()=>{this.sortTimeoutId=-1,this.driveSort()}),t-e));this.sorting=!0,this.sortDirty=!1,this.lastSortTime=e,this.readPause>0&&await new Promise((e=>setTimeout(e,this.readPause)));const n=this.current;this.sortedCenter.copy(n.viewOrigin),this.sortedDir.copy(n.viewDirection);const{numSplats:i,maxSplats:s}=n,a=Math.max(1,Math.ceil(s/16384)),o=16384*a;this.maxSplats=Math.max(this.maxSplats,o);const l=new Uint32Array(this.maxSplats),c=Ca.ensureBuffer(s,this.readback32);this.readback32=c,await this.readbackDepth({current:n,renderer:this.renderer,numSplats:i,readback:c}),this.sortPause>0&&await new Promise((e=>setTimeout(e,this.sortPause))),this.sortWorker||(this.sortWorker=new Pi);const u=await this.sortWorker.call("sortSplats32",{numSplats:i,readback:c,ordering:l});if(this.sortDelay>0&&await new Promise((e=>setTimeout(e,this.sortDelay))),this.readback32=u.readback,this.activeSplats=u.activeSplats,this.orderingTexture&&a>this.orderingTexture.image.height&&(this.orderingTexture.dispose(),this.orderingTexture=null),this.orderingTexture){const e=this.renderer,t=e.getContext();if(e.properties.has(this.orderingTexture)){const n=e.properties.get(this.orderingTexture).__webglTexture;if(!n)throw new Error("ordering texture not found");e.state.activeTexture(t.TEXTURE0),e.state.bindTexture(t.TEXTURE_2D,n),t.bindBuffer(t.PIXEL_UNPACK_BUFFER,null),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texSubImage2D(t.TEXTURE_2D,0,0,0,4096,a,t.RGBA_INTEGER,t.UNSIGNED_INT,u.ordering),e.state.bindTexture(t.TEXTURE_2D,null)}else this.orderingTexture.needsUpdate=!0}else{const e=new r.DataTexture(u.ordering,4096,a,r.RGBAIntegerFormat,r.UnsignedIntType);e.internalFormat="RGBA32UI",e.needsUpdate=!0,this.orderingTexture=e}this.current.mappingVersion===n.mappingVersion&&this.current.mappingVersion!==this.display.mappingVersion&&(this.accumulators.push(this.display),this.display=this.current),this.sorting=!1,this.setDirty(),this.driveSort()}ensureLodWorker(){return this.lodWorker||(this.lodWorker=new Pi),this.lodWorker}defaultSplatTarget(){return navigator.xr&&/Oculus/.test(navigator.userAgent)?5e5:navigator.xr&&yi()&&/Safari/.test(navigator.userAgent)&&xi()?75e4:/Android/.test(navigator.userAgent)||/Tizen/.test(navigator.userAgent)?1e6:yi()?15e5:25e5}driveLod({visibleGenerators:e,camera:t,scene:n}){var i,s;const a=this.defaultSplatTarget(),o=(this.lodSplatCount??a)*this.lodSplatScale;let l=0;if(t instanceof r.PerspectiveCamera){const e=Math.tan(.5*t.fov*Math.PI/180);l=2*e/this.renderSize.y}else if(t instanceof r.OrthographicCamera){const e=(t.top-t.bottom)/t.zoom,n=(t.right-t.left)/t.zoom,r=e/Math.max(1,this.renderSize.y),i=n/Math.max(1,this.renderSize.x);l=Math.min(i,r)}l*=this.lodRenderScale;const c=new r.Vector3,u=new r.Quaternion;if(this.current.viewToWorld.decompose(c,u,new r.Vector3),this.lodPosOverride&&c.copy(this.lodPosOverride),this.lodQuatOverride&&u.copy(this.lodQuatOverride).normalize(),this.lastLod){this.lastLod.pixelScaleLimit===l&&this.lastLod.maxSplats===o||(this.lodDirty=!0);const e=c.distanceTo(this.lastLod.pos),t=Math.max(0,1-e/1),n=u.dot(this.lastLod.quat);t*Math.max(0,1-(1-n)/.01)<.999&&(this.lodDirty=!0)}const h=this.enableLod?e.filter((e=>{var t,n;return e instanceof lo&&((null==(t=e.packedSplats)?void 0:t.lodSplats)||(null==(n=e.extSplats)?void 0:n.lodSplats)||e.paged)&&!1!==e.enableLod})):[],d=h.some((e=>e.paged));(this.lodMeshes.length!==h.length||h.some(((e,t)=>e!==this.lodMeshes[t].mesh||e.version>this.lodMeshes[t].version)))&&(this.lodDirty=!0),this.lodMeshes=h.map((e=>({mesh:e,version:e.version+1}))),this.lodInitQueue=[];const p=performance.now();for(const r of h){const e=(null==(i=r.packedSplats)?void 0:i.lodSplats)??(null==(s=r.extSplats)?void 0:s.lodSplats)??r.paged;if(e){const t=this.lodIds.get(e);t?t.lastTouched=p:this.lodInitQueue.push(e)}}this.ensureLodWorker().tryExclusive((async e=>{if(d&&!this.pager){this.pager=new no({renderer:this.renderer,extSplats:this.pagedExtSplats,maxSplats:this.maxPagedSplats,numFetchers:this.numLodFetchers});const{lodId:t}=await e.call("newLodTree",{capacity:this.pager.maxSplats});this.pagerId=t}if(this.pager)for(const{mesh:t}of this.lodMeshes)t.paged&&!t.paged.pager&&(t.paged.pager=this.pager);if(this.lodInitQueue.length>0){const t=this.lodInitQueue;for(this.lodInitQueue=[];t.length>0;){const n=t.shift();n&&(await this.initLodTree(e,n),this.lodDirty=!0)}}if(this.pager){const e=this.pager.consumeLodTreeUpdates();for(const{splats:t,page:n,chunk:r,numSplats:i,lodTree:s}of e){const e=this.lodIds.get(t);e&&(s&&0===r&&(e.rootPage=n),this.lodUpdates.push({lodId:e.lodId,pageBase:n*this.pager.pageSplats,chunkBase:r*this.pager.pageSplats,count:i,lodTreeData:s}))}}if(this.lodUpdates.length>0){const t=this.lodUpdates;this.lodUpdates=[],await e.call("updateLodTrees",{ranges:t}),this.lodDirty=!0}if(this.lodDirty){const t=performance.now(),n=new r.Vector3;if(this.lastLod){const e=Math.max(1,t-this.lastLod.timestamp);n.copy(c).sub(this.lastLod.pos).multiplyScalar(this.lastTraverseTime/e)}this.lastLod={pos:c,quat:u,pixelScaleLimit:l,maxSplats:o,timestamp:t},this.lodDirty=!1,await this.updateLodInstances(e,n,h,o,c,u,l),this.currentLod=this.lastLod,this.setDirty()}await this.cleanupLodTrees(e)}))}async initLodTree(e,t){if(t instanceof fo||t instanceof Qs){const{lodId:n}=await e.call("initLodTree",{numSplats:t.numSplats??0,lodTree:t.extra.lodTree.slice()});this.lodIds.set(t,{lodId:n,lastTouched:performance.now()}),this.lodIdToSplats.set(n,t)}else{const{lodId:n}=await e.call("newSharedLodTree",{lodId:this.pagerId});this.lodIds.set(t,{lodId:n,lastTouched:performance.now()}),this.lodIdToSplats.set(n,t)}}async updateLodInstances(e,t,n,i,s,a,o){const l=new Map,c=(new r.Matrix4).compose(s,a,(new r.Vector3).setScalar(1)),u=n.reduce(((e,t)=>{var n,r;l.set(t.uuid,t);const i=t.matrixWorld.clone().invert().multiply(c),s=(null==(n=t.packedSplats)?void 0:n.lodSplats)??(null==(r=t.extSplats)?void 0:r.lodSplats)??t.paged;if(!s)return e;const a=this.lodIds.get(s);return a?(this.pager&&t.paged&&void 0===a.rootPage||(e[t.uuid]={instanceId:t.uuid,lodId:a.lodId,rootPage:a.rootPage,viewToObjectCols:i.elements,lodScale:t.lodScale,behindFoveate:t.behindFoveate??this.behindFoveate,coneFov0:t.coneFov0??this.coneFov0,coneFov:t.coneFov??this.coneFov,coneFoveate:t.coneFoveate??this.coneFoveate}),e):e}),{}),h=performance.now(),d=await e.call("traverseLodTrees",{maxSplats:i,pixelScaleLimit:o,lastPixelLimit:this.lastPixelLimit,instances:u});this.lastTraverseTime=performance.now()-h;const{keyIndices:p,chunks:m,pixelLimit:f}=d;this.lastPixelLimit=f;const g=Object.values(p).reduce(((e,{numSplats:t})=>e+t),0);if(this.updateLodIndices(l,p),this.pager){this.pager.processUploads();const e=n.map((e=>{if(!e.paged||!this.pager)return null;const t=e.getWorldPosition(new r.Vector3);return{splats:e.paged,distance:t.distanceTo(s)}})).filter((e=>null!==e));!this.pageSizeWarning&&e.length>this.pager.maxPages&&(this.pageSizeWarning=!0),e.sort(((e,t)=>e.distance-t.distance)),this.pager.fetchPriority=e.map((({splats:e})=>({splats:e,chunk:0})));for(const[t,n]of m){const e=this.lodIdToSplats.get(t);e instanceof eo&&0!==n&&this.pager.fetchPriority.push({splats:e,chunk:n})}this.pager.autoDrive=this.enableLodFetching,this.enableLodFetching&&this.pager.driveFetchers()}if(this.lodRaycast&&performance.now()-this.lastLodRaycastTime>=this.lodRaycastIntervalMs){this.lastLodRaycastTime=performance.now();performance.now();const t=await e.call("traverseLodTrees",{maxSplats:Math.min(this.lodRaycast,Math.round(.1*g)),pixelScaleLimit:o,instances:u});performance.now();const{keyIndices:n}=t;Object.values(n).reduce(((e,{numSplats:t})=>e+t),0);for(const[e,r]of Object.entries(n)){l.get(e).raycastIndices=r}}}async cleanupLodTrees(e){const t=performance.now();let n=null;for(const[r,i]of this.lodIds.entries())(null==n||i.lastTouched<n.lastTouched)&&(n={splats:r,lastTouched:i.lastTouched,lodId:i.lodId});if(n&&!(n.lastTouched>t-3e3)){this.lodIds.delete(n.splats),this.lodIdToSplats.delete(n.lodId);for(const[e,t]of this.lodInstances.entries())t.lodId===n.lodId&&(t.texture.dispose(),this.lodInstances.delete(e));await e.call("disposeLodTree",{lodId:n.lodId})}}updateLodIndices(e,t){for(const[n,i]of Object.entries(t)){const{lodId:t,numSplats:s,indices:a}=i,o=e.get(n);if(o.paged)o.paged.update(s,a);else{let e=this.lodInstances.get(o);e&&a.length>e.indices.length&&(e.texture.dispose(),e=void 0);const n=Math.ceil(a.length/16384);if(e){e.numSplats=s;const t=this.renderer,r=t.getContext();if(t.properties.has(e.texture)){const i=t.properties.get(e.texture).__webglTexture;if(!i)throw new Error("lodIndices texture not found");t.state.activeTexture(r.TEXTURE0),t.state.bindTexture(r.TEXTURE_2D,i),r.bindBuffer(r.PIXEL_UNPACK_BUFFER,null),r.pixelStorei(r.UNPACK_FLIP_Y_WEBGL,!1),r.texSubImage2D(r.TEXTURE_2D,0,0,0,4096,n,r.RGBA_INTEGER,r.UNSIGNED_INT,a),t.state.bindTexture(r.TEXTURE_2D,null)}}else{const i=16384*n;if(a.length!==i)throw new Error("Indices length != capacity");const l=new r.DataTexture(a,4096,n,r.RGBAIntegerFormat,r.UnsignedIntType);l.internalFormat="RGBA32UI",l.needsUpdate=!0,e={lodId:t,numSplats:s,indices:a,texture:l},this.lodInstances.set(o,e)}}o.updateMappingVersion()}}async readbackDepth({current:e,renderer:t,numSplats:n,readback:r}){if(!t)throw new Error("No renderer");if(!e.target)throw new Error("No target");const i=Math.ceil(n/br)*br;if(r.byteLength<4*i)throw new Error(`Readback buffer too small: ${r.byteLength} < ${4*i}`);const s=new Uint8Array(r.buffer),a=this.saveRenderState(t),o=4194304;let l=0;const c=[];for(;l<n;){const r=Math.floor(l/o),i=r*o,a=Math.min(wr,Math.ceil((n-i)/br)),u=br*a*4,h=s.subarray(4*i,4*i+u);t.setRenderTarget(e.target,r);const d=t.readRenderTargetPixelsAsync(e.target,0,0,br,a,h,void 0,e.extSplats?2:1);if(c.push(d),this.flushAfterRead){t.getContext().flush()}l+=br*a}return this.resetRenderState(t,a),Promise.all(c).then((()=>r))}saveRenderState(e){return{target:e.getRenderTarget(),xrEnabled:e.xr.enabled,autoClear:e.autoClear}}resetRenderState(e,t){e.setRenderTarget(t.target),e.xr.enabled=t.xrEnabled,e.autoClear=t.autoClear}render(t,n){try{e.sparkOverride=this,this.renderer.render(t,n)}finally{e.sparkOverride=void 0}}renderTarget({scene:t,camera:n}){const r=this.backTarget??this.target;if(!r)throw new Error("No target");const i=this.renderer.getRenderTarget();try{this.renderer.setRenderTarget(r),e.sparkOverride=this,this.renderer.render(t,n)}finally{e.sparkOverride=void 0,this.renderer.setRenderTarget(i)}return r!==this.target&&([this.target,this.backTarget]=[this.backTarget,this.target]),r}async readTarget(){if(!this.target)throw new Error("Must initialize with target");const{width:e,height:t}=this.target,n=e*t*4;(!this.superPixels||this.superPixels.length<n)&&(this.superPixels=new Uint8Array(n));const r=this.superPixels;await this.renderer.readRenderTargetPixelsAsync(this.target,0,0,e,t,r);const{superXY:i}=this;if(1===i)return r;const s=e/i,a=t/i,o=s*a*4;(!this.targetPixels||this.targetPixels.length<o)&&(this.targetPixels=new Uint8Array(o));const l=this.targetPixels,c=i*i;for(let u=0;u<a;u++){const t=u*s;for(let n=0;n<s;n++){const s=n*i;let a=0,o=0,h=0,d=0;for(let t=0;t<i;t++){const n=(u*i+t)*e;for(let e=0;e<i;e++){const t=4*(n+s+e);a+=r[t],o+=r[t+1],h+=r[t+2],d+=r[t+3]}}const p=4*(t+n);l[p]=a/c,l[p+1]=o/c,l[p+2]=h/c,l[p+3]=d/c}}return l}async renderReadTarget({scene:e,camera:t}){return this.renderTarget({scene:e,camera:t}),this.readTarget()}async renderCubeMap({scene:t,worldCenter:n,size:i=256,near:s=.1,far:a=1e3,hideObjects:o=[],update:l=!0,filter:c=!1}){if(!e.cubeRender||e.cubeRender.target.width!==i||e.cubeRender.near!==s||e.cubeRender.far!==a){e.cubeRender&&e.cubeRender.target.dispose();const t=new r.WebGLCubeRenderTarget(i,{format:r.RGBAFormat,type:r.UnsignedByteType,generateMipmaps:c,minFilter:c?r.LinearMipMapLinearFilter:r.LinearFilter,magFilter:r.LinearFilter,colorSpace:c?r.LinearSRGBColorSpace:r.SRGBColorSpace}),n=new r.CubeCamera(s,a,t);e.cubeRender={target:t,cubeCamera:n,near:s,far:a}}const{target:u,cubeCamera:h}=e.cubeRender;h.position.copy(n);const d=new Map;for(const e of o)d.set(e,e.visible),e.visible=!1;if(l){const e=new r.Camera;e.position.copy(n),await this.update({scene:t,camera:e})}try{e.sparkOverride=this,h.update(this.renderer,t)}finally{e.sparkOverride=void 0}for(const[e,r]of d.entries())e.visible=r;return u.texture}async readCubeTargets(){if(!e.cubeRender)throw new Error("No cube render");const t=e.cubeRender.target.texture,n=[],r=[];for(let i=0;i<t.images.length;++i){const{width:s,height:a}=t.images[i],o=new Uint8Array(s*a*4);r.push(o);const l=this.renderer.readRenderTargetPixelsAsync(e.cubeRender.target,0,0,s,a,o,i);n.push(l)}return await Promise.all(n),r}async renderEnvMap({scene:t,worldCenter:n,size:i=256,near:s=.1,far:a=1e3,hideObjects:o=[],update:l=!0}){var c;const u=await this.renderCubeMap({scene:t,worldCenter:n,size:i,near:s,far:a,hideObjects:o,update:l,filter:!0});return e.pmrem||(e.pmrem=new r.PMREMGenerator(this.renderer)),null==(c=e.pmrem)?void 0:c.fromCubemap(u).texture}recurseSetEnvMap(e,t){e.traverse((e=>{if(e instanceof r.Mesh)if(Array.isArray(e.material))for(const n of e.material)n instanceof r.MeshStandardMaterial&&(n.envMap=t);else e.material instanceof r.MeshStandardMaterial&&(e.material.envMap=t)}))}async getLodTreeLevel(e,t,n=!1){var r,i;const s=this.lodInstances.get(e);if(!s)return null;const a=await this.ensureLodWorker().exclusive((async e=>await e.call("getLodTreeLevel",{lodId:s.lodId,level:t})));if(null==(r=e.packedSplats)?void 0:r.lodSplats){const t=e.packedSplats.lodSplats.extractSplats(a.indices,n);return new lo({packedSplats:t})}if(null==(i=e.extSplats)?void 0:i.lodSplats){const t=e.extSplats.lodSplats.extractSplats(a.indices,n);return new lo({extSplats:t})}throw new Error("Only LoD-enabled PackedSplats and ExtSplats are supported")}get premultipliedAlpha(){return this.material.premultipliedAlpha}set premultipliedAlpha(e){this.material.premultipliedAlpha!==e&&(this.material.premultipliedAlpha=e,this.material.needsUpdate=!0)}};Za.emptyOrdering=(()=>{const e=new Uint32Array(16384),t=new r.DataTexture(e,4096,1);return t.format=r.RGBAIntegerFormat,t.type=r.UnsignedIntType,t.internalFormat="RGBA32UI",t.needsUpdate=!0,t})(),Za.cubeRender=null,Za.pmrem=null;let Ja=Za;class eo{constructor(e){var t;if(this.pager=e.pager,this.rootUrl=e.rootUrl??"",this.requestHeader=e.requestHeader,this.withCredentials=e.withCredentials,this.numSh=0,this.maxSh=(null==(t=e.pager)?void 0:t.maxSh)??3,this.numSplats=0,this.dynoNumSplats=new Ts({value:0}),this.dynoIndices=new Es({value:no.emptyIndicesTexture}),this.rgbMinMaxLnScaleMinMax=new Ms({value:new r.Vector4(0,1,yr,9)}),this.lodOpacity=new ws({value:!1}),this.dynoNumSh=new Ts({value:0}),this.shMax=new _s({value:new r.Vector3}),this.fileBytes=e.fileBytes,this.fileType=e.fileType,!this.fileType&&this.fileBytes&&(this.fileType=function(e){const t=new DataView(e.buffer).getUint32(0,!0);if(7957616==(16777215&t))return Tr.PLY;if(559903==(16777215&t)){const t=function(e,t){const n=[];let r=0,i=null;const s=new dr(((e,s)=>{if(n.push(e),r+=e.length,s||r>=t){const e=new Uint8Array(r);let s=0;for(const t of n)e.set(t,s),s+=t.length;i=e.slice(0,t)}}));let a=0;for(;null==i&&a<e.length;){const t=e.slice(a,a+1024);s.push(t,!1),a+=1024}if(null==i&&(s.push(new Uint8Array,!0),null==i))throw new Error("Failed to decompress partial gzip");return i}(e,4);return 1347635022===new DataView(t.buffer).getUint32(0,!0)?Tr.SPZ:void 0}if(67324752===t)return function(e){try{const t=e instanceof ArrayBuffer?new Uint8Array(e):e;let n=null;const r=function(e,t){for(var n={},r=e.length-22;101010256!=lr(e,r);--r)(!r||e.length-r>65558)&&ir(13);var i=or(e,r+8);if(!i)return{};var s=lr(e,r+16),a=4294967295==s||65535==i;if(a){var o=lr(e,r-12);(a=101075792==lr(e,o))&&(i=lr(e,o+32),s=lr(e,o+48))}for(var l=t&&t.filter,c=0;c<i;++c){var u=gr(e,s,a),h=u[0],d=u[1],p=u[2],m=u[3],f=u[4],g=u[5],x=fr(e,g);s=f,l&&!l({name:m,size:d,originalSize:p,compression:h})||(h?8==h?n[m]=hr(e.subarray(x,x+d),{out:new Pn(p)}):ir(14,"unknown compression type "+h):n[m]=nr(e,x,x+d))}return n}(t,{filter:({name:e})=>"meta.json"===e.split(/[\\/]/).pop()&&(n=e,!0)});if(!n)return;const i=function(e){try{let t;if("string"==typeof e)t=e;else{const n=e instanceof ArrayBuffer?new Uint8Array(e):e;if(n.length>65536)return;t=(new TextDecoder).decode(n)}const n=JSON.parse(t);if(!n||"object"!=typeof n||Array.isArray(n))return;const r=2===n.version;for(const e of["means","scales","quats","sh0"]){if(!n[e]||"object"!=typeof n[e]||Array.isArray(n[e]))return;if(r){if(!n[e].files)return;if(("scales"===e||"sh0"===e)&&!n[e].codebook)return;if(!("means"!==e||n[e].mins&&n[e].maxs))return}else{if(!n[e].shape||!n[e].files)return;if(!("quats"===e||n[e].mins&&n[e].maxs))return}}return n}catch{return}}(r[n]);if(!i)return;return{name:n,json:i}}catch{return}}(e)?Tr.PCSOGSZIP:void 0;if(809779538===t)return Tr.RAD;return}(this.fileBytes)),!this.fileType&&this.rootUrl&&(this.fileType=function(e){const t=function(e){const t=e.split(/[?#]/,1)[0],n=Math.max(t.lastIndexOf("/"),t.lastIndexOf("\\")),r=t.slice(n+1),i=r.lastIndexOf(".");if(i<=0||i===r.length-1)return"";return r.slice(i+1).toLowerCase()}(e);if("ply"===t)return Tr.PLY;if("spz"===t)return Tr.SPZ;if("splat"===t)return Tr.SPLAT;if("ksplat"===t)return Tr.KSPLAT;if("sog"===t)return Tr.PCSOGSZIP;if("rad"===t)return Tr.RAD;return}(this.rootUrl)),!this.fileType)throw new Error("Unable to determine file type");this.fileType===Tr.RAD&&(this.radMetaPromise=this.getRadMeta())}dispose(){this.dynoIndices.value!==no.emptyIndicesTexture&&(this.dynoIndices.value.dispose(),this.dynoIndices.value=no.emptyIndicesTexture)}setMaxSh(e){this.maxSh=e}getRadMeta(){return this.radMetaPromise||(this.radMetaPromise=(async()=>{if(await io,this.fileBytes){const e=ia(this.fileBytes.slice(0,1048576));if(e)return e;throw new Error("Failed to decode RAD header")}if(!this.rootUrl)throw new Error("No url or fileBytes provided");for(const e of[65536,262144,1048576]){const t=ia(await so({url:this.rootUrl,requestHeader:this.requestHeader,withCredentials:this.withCredentials,offset:0,bytes:e}));if(t)return t}throw new Error("Failed to decode RAD header")})().then((e=>e)),this.radMetaPromise.catch((e=>{}))),this.radMetaPromise}chunkUrl(e){return this.rootUrl.replace(/-lod-0\./,`-lod-${e}.`)}async fetchDecodeChunk(e){let t;if(this.fileType===Tr.RAD){const{meta:n,chunksStart:r}=await this.getRadMeta();if(e<0||e>=n.chunks.length)throw new Error(`Chunk index out of range: ${e} (max: ${n.chunks.length-1})`);let{offset:i,bytes:s,filename:a}=n.chunks[e];if(a){if(this.fileBytes)throw new Error("Chunked RAD file not supported with fileBytes");const e=new URL(this.rootUrl,window.location.href).toString(),n=new URL(a,e).toString();t=await so({url:n,requestHeader:this.requestHeader,withCredentials:this.withCredentials})}else if(i+=r,this.fileBytes){if(i<0||i+s>this.fileBytes.length)throw new Error(`Invalid chunk offset or bytes: ${i} + ${s} > ${this.fileBytes.length}`);t=this.fileBytes.slice(i,i+s)}else{if(!this.rootUrl)throw new Error("No url or fileBytes provided");t=await so({url:this.rootUrl,requestHeader:this.requestHeader,withCredentials:this.withCredentials,offset:i,bytes:s})}}else if(this.fileBytes);else{if(!this.rootUrl)throw new Error("No url or fileBytes provided");{const n=this.chunkUrl(e),r=new Request(n,{headers:this.requestHeader?new Headers(this.requestHeader):void 0,credentials:this.withCredentials?"include":"same-origin"}),i=await fetch(r);if(!i.ok||!i.body)throw new Error(`Failed to fetch "${n}": ${i.status} ${i.statusText}`);t=new Uint8Array(await i.arrayBuffer())}}return await Li.withWorker((async n=>{var r,i,s,a,o;if(!this.pager)throw new Error("PagedSplats.pager not set");if(!this.pager.extSplats){const a=(await n.call("loadPackedSplats",{fileBytes:t,pathName:this.chunkUrl(e),sh1Codes:null==(r=this.sh1Codes)?void 0:r.slice(),sh2Codes:null==(i=this.sh2Codes)?void 0:i.slice(),sh3Codes:null==(s=this.sh3Codes)?void 0:s.slice()})).lodSplats;return this.splatEncoding||(this.splatEncoding=a.splatEncoding,this.numSh=a.extra.sh3?3:a.extra.sh2?2:a.extra.sh1?1:0,this.rgbMinMaxLnScaleMinMax.value.set(this.splatEncoding.rgbMin??0,this.splatEncoding.rgbMax??1,this.splatEncoding.lnScaleMin??yr,this.splatEncoding.lnScaleMax??9),this.lodOpacity.value=this.splatEncoding.lodOpacity??!1,this.shMax.value.set(this.splatEncoding.sh1Max??1,this.splatEncoding.sh2Max??1,this.splatEncoding.sh3Max??1)),this.sh1Codes=a.extra.sh1Codes??this.sh1Codes,this.sh2Codes=a.extra.sh2Codes??this.sh2Codes,this.sh3Codes=a.extra.sh3Codes??this.sh3Codes,a}const l=this.sh3Codes,c=(await n.call("loadExtSplats",{fileBytes:t,pathName:this.chunkUrl(e),sh1Codes:null==(a=this.sh1Codes)?void 0:a.slice(),sh2Codes:null==(o=this.sh2Codes)?void 0:o.slice(),sh3Codes:l?[l[0].slice(),l[1].slice()]:void 0})).lodSplats;return this.splatEncoding||(this.splatEncoding=Sr,this.numSh=c.extra.sh3a&&c.extra.sh3b?3:c.extra.sh2?2:c.extra.sh1?1:0),this.sh1Codes=c.extra.sh1Codes??this.sh1Codes,this.sh2Codes=c.extra.sh2Codes??this.sh2Codes,this.sh3Codes=c.extra.sh3Codes??this.sh3Codes,c}))}update(e,t){if(!this.pager)throw new Error("PagedSplats.pager not set");const n=this.pager.renderer;this.numSplats=e,this.dynoNumSplats.value=this.numSplats;const i=Math.ceil(e/16384);let s=this.dynoIndices.value===no.emptyIndicesTexture?void 0:this.dynoIndices.value;if(s&&i>s.image.height&&(s.dispose(),s=void 0),s){s.image.data.set(t.subarray(0,e));const r=n.getContext();n.state.activeTexture(r.TEXTURE0),n.state.bindTexture(r.TEXTURE_2D,ro(n,s)),r.bindBuffer(r.PIXEL_UNPACK_BUFFER,null),r.pixelStorei(r.UNPACK_FLIP_Y_WEBGL,!1),r.texSubImage2D(r.TEXTURE_2D,0,0,0,4096,i,r.RGBA_INTEGER,r.UNSIGNED_INT,t),n.state.bindTexture(r.TEXTURE_2D,null)}else s=new r.DataTexture(t,4096,i,r.RGBAIntegerFormat,r.UnsignedIntType),s.internalFormat="RGBA32UI",s.needsUpdate=!0,n.initTexture(s),this.dynoIndices.value=s}prepareFetchSplat(){}getNumSplats(){return this.numSplats}hasRgbDir(){return!!this.pager&&Math.min(this.numSh,this.pager.maxSh)>0}getNumSh(){return this.numSh}fetchSplat({index:e,viewOrigin:t}){if(!this.pager)throw new Error("PagedSplats.pager not set");const n=this.pager.readIndex.apply({index:e,numSplats:this.dynoNumSplats,indices:this.dynoIndices}).index;return this.pager.extSplats?this.hasRgbDir()&&t?(this.dynoNumSh.value=Math.min(this.numSh,this.maxSh,this.pager.maxSh),this.pager.readSplatExtDir.apply({index:n,viewOrigin:t,numSh:this.dynoNumSh}).gsplat):this.pager.readSplatExt.apply({index:n}).gsplat:this.hasRgbDir()&&t?(this.dynoNumSh.value=Math.min(this.numSh,this.maxSh,this.pager.maxSh),this.pager.readSplatDir.apply({index:n,rgbMinMaxLnScaleMinMax:this.rgbMinMaxLnScaleMinMax,lodOpacity:this.lodOpacity,viewOrigin:t,numSh:this.dynoNumSh,shMax:this.shMax}).gsplat):this.pager.readSplat.apply({index:n,rgbMinMaxLnScaleMinMax:this.rgbMinMaxLnScaleMinMax,lodOpacity:this.lodOpacity}).gsplat}forEachSplat(e){if(!this.pager||!this.numSplats)return;const t=this.pager.extSplats,n=this.dynoIndices.value.image.data,r=this.pager.packedTexture.value.image.data,i=[r,this.pager.extTexture.value.image.data];for(let s=0;s<this.numSplats;++s){const a=n[s],o=t?hi(i,a):fi(r,a,this.splatEncoding);e(s,o.center,o.scales,o.quaternion,o.opacity,o.color)}}}const to=class e{constructor(t){this.fetchPause=0,this.splatsChunkToPage=new Map,this.pageToSplatsChunk=[],this.renderer=t.renderer,this.extSplats=t.extSplats??!1,this.pageSplats=65536,this.maxSplats=t.maxSplats??16777216,this.maxPages=Math.ceil(this.maxSplats/this.pageSplats),this.maxSplats=this.maxPages*this.pageSplats,this.maxSh=t.maxSh??3,this.curSh=0,this.autoDrive=t.autoDrive??!0,this.numFetchers=t.numFetchers??3,this.splatsChunkToPage=new Map,this.pageToSplatsChunk=new Array(this.maxPages),this.pageFreelist=Array.from({length:this.maxPages},((e,t)=>t)),this.pageLru=new Set,this.freeablePages=[],this.newUploads=[],this.readyUploads=[],this.lodTreeUpdates=[],this.fetchers=[],this.fetched=[],this.fetchPriority=[],this.packedTexture=new Cs({value:this.newUint32ArrayTexture(new Uint32Array(256*this.maxPages*256*4),256,256,this.maxPages,r.RGBAIntegerFormat,r.UnsignedIntType,"RGBA32UI")}),this.extTexture=new Cs({value:this.extSplats?this.newUint32ArrayTexture(new Uint32Array(256*this.maxPages*256*4),256,256,this.maxPages,r.RGBAIntegerFormat,r.UnsignedIntType,"RGBA32UI"):e.emptyExtTexture}),this.sh1Texture=new Cs({value:this.extSplats?e.emptyExtSh1Texture:e.emptySh1Texture}),this.sh2Texture=new Cs({value:this.extSplats?e.emptyExtSh2Texture:e.emptySh2Texture}),this.sh3Texture=new Cs({value:this.extSplats?e.emptyExtSh3Texture:e.emptySh3Texture}),this.sh3TextureB=new Cs({value:e.emptyExtSh3BTexture}),this.readIndex=qr({index:"int",numSplats:"int",indices:"usampler2D"},{index:"int"},(({index:e,numSplats:t,indices:n})=>new $r({inTypes:{index:"int",numSplats:"int",indices:"usampler2D"},outTypes:{index:"int"},inputs:{index:e,numSplats:t,indices:n},statements:({inputs:e,outputs:t})=>Wr(`\n if (${e.index} >= ${e.numSplats}) {\n return;\n }\n\n ivec2 indexCoord = ivec2((${e.index} >> 2) & 4095, ${e.index} >> 14);\n uint index = texelFetch(${e.indices}, indexCoord, 0)[${e.index} & 3];\n ${t.index} = int(index);\n `)}).outputs)),this.readSplat=qr({index:"int",rgbMinMaxLnScaleMinMax:"vec4",lodOpacity:"bool"},{gsplat:Ui},(({index:e,rgbMinMaxLnScaleMinMax:t,lodOpacity:n})=>new $r({inTypes:{index:"int",packedTexture:"usampler2DArray",rgbMinMaxLnScaleMinMax:"vec4",lodOpacity:"bool"},outTypes:{gsplat:Ui},inputs:{index:e,packedTexture:this.packedTexture,rgbMinMaxLnScaleMinMax:t,lodOpacity:n},globals:()=>[ji],statements:({inputs:e,outputs:t})=>Wr(`\n int index = ${e.index};\n ivec3 splatCoord = pagedSplatTexCoord(index);\n uvec4 packedData = texelFetch(${e.packedTexture}, splatCoord, 0);\n\n unpackSplatEncoding(packedData, ${t.gsplat}.center, ${t.gsplat}.scales, ${t.gsplat}.quaternion, ${t.gsplat}.rgba, ${e.rgbMinMaxLnScaleMinMax});\n if ((${t.gsplat}.rgba.a == 0.0) || all(equal(${t.gsplat}.scales, vec3(0.0, 0.0, 0.0)))) {\n return;\n }\n \n ${t.gsplat}.index = index;\n ${t.gsplat}.flags = GSPLAT_FLAG_ACTIVE;\n if (${e.lodOpacity}) {\n ${t.gsplat}.rgba.a *= 2.0;\n }\n `)}).outputs)),this.readSplatDir=qr({index:"int",rgbMinMaxLnScaleMinMax:"vec4",lodOpacity:"bool",viewOrigin:"vec3",numSh:"int",shMax:"vec3"},{gsplat:Ui},(({index:e,rgbMinMaxLnScaleMinMax:t,lodOpacity:n,viewOrigin:r,numSh:i,shMax:s})=>{if(!(e&&t&&n&&r&&i&&s))throw new Error("index and viewOrigin are required");let a=this.readSplat.apply({index:e,rgbMinMaxLnScaleMinMax:t,lodOpacity:n}).gsplat;const o=Ni(a).outputs.center,l=Hs(Fs(o,r));let c=bo({coord:Hi(e),viewDir:l,numSh:i,sh1Texture:this.sh1Texture,sh2Texture:this.sh2Texture,sh3Texture:this.sh3Texture,shMax:s}).rgb;return c=Us(c,Ni(a).outputs.rgb),a=$i({gsplat:a,rgb:c}),{gsplat:a}})),this.readSplatExt=qr({index:"int"},{gsplat:Ui},(({index:e})=>new $r({inTypes:{index:"int",extTexture1:"usampler2DArray",extTexture2:"usampler2DArray"},outTypes:{gsplat:Ui},inputs:{index:e,extTexture1:this.packedTexture,extTexture2:this.extTexture},globals:()=>[ji],statements:({inputs:e,outputs:t})=>Wr(`\n int index = ${e.index};\n ivec3 splatCoord = ivec3(index & 255, (index >> 8) & 255, index >> 16);\n uvec4 ext1 = texelFetch(${e.extTexture1}, splatCoord, 0);\n float alpha = unpackSplatExtAlpha(ext1);\n if (alpha == 0.0) {\n return;\n }\n\n uvec4 ext2 = texelFetch(${e.extTexture2}, splatCoord, 0);\n unpackSplatExt(ext1, ext2, ${t.gsplat}.center, ${t.gsplat}.scales, ${t.gsplat}.quaternion, ${t.gsplat}.rgba);\n if (all(equal(${t.gsplat}.scales, vec3(0.0, 0.0, 0.0)))) {\n return;\n }\n\n ${t.gsplat}.index = index;\n ${t.gsplat}.flags = GSPLAT_FLAG_ACTIVE;\n `)}).outputs)),this.readSplatExtDir=qr({index:"int",viewOrigin:"vec3",numSh:"int"},{gsplat:Ui},(({index:e,viewOrigin:t,numSh:n})=>{if(!e||!t||!n)throw new Error("index and viewOrigin are required");let r=this.readSplatExt.apply({index:e}).gsplat;const i=Ni(r).outputs.center,s=Hs(Fs(i,t));let a=na({coord:Hi(e),viewDir:s,numSh:n,sh1Texture:this.sh1Texture,sh2Texture:this.sh2Texture,sh3TextureA:this.sh3Texture,sh3TextureB:this.sh3TextureB}).rgb;return a=Us(a,Ni(r).outputs.rgb),r=$i({gsplat:r,rgb:a}),{gsplat:r}}))}dispose(){this.autoDrive=!1,this.numFetchers=0,this.packedTexture.value.dispose(),this.packedTexture.value.source.data=null,this.extTexture.value!==e.emptyExtTexture&&(this.extTexture.value.dispose(),this.extTexture.value.source.data=null),this.extSplats?(this.sh1Texture.value!==e.emptyExtSh1Texture&&(this.sh1Texture.value.dispose(),this.sh1Texture.value.source.data=null),this.sh2Texture.value!==e.emptyExtSh2Texture&&(this.sh2Texture.value.dispose(),this.sh2Texture.value.source.data=null),this.sh3Texture.value!==e.emptyExtSh3Texture&&(this.sh3Texture.value.dispose(),this.sh3Texture.value.source.data=null),this.sh3TextureB.value!==e.emptyExtSh3BTexture&&(this.sh3TextureB.value.dispose(),this.sh3TextureB.value.source.data=null)):(this.sh1Texture.value!==e.emptySh1Texture&&(this.sh1Texture.value.dispose(),this.sh1Texture.value.source.data=null),this.sh2Texture.value!==e.emptySh2Texture&&(this.sh2Texture.value.dispose(),this.sh2Texture.value.source.data=null),this.sh3Texture.value!==e.emptySh3Texture&&(this.sh3Texture.value.dispose(),this.sh3Texture.value.source.data=null))}ensureShTextures(t){this.curSh=Math.max(this.curSh,t),this.extSplats?this.curSh>=1&&this.sh1Texture.value===e.emptyExtSh1Texture&&(this.sh1Texture.value=this.newUint32ArrayTexture(new Uint32Array(256*this.maxPages*256*4),256,256,this.maxPages,r.RGBAIntegerFormat,r.UnsignedIntType,"RGBA32UI")):this.curSh>=1&&this.sh1Texture.value===e.emptySh1Texture&&(this.sh1Texture.value=this.newUint32ArrayTexture(new Uint32Array(256*this.maxPages*256*2),256,256,this.maxPages,r.RGIntegerFormat,r.UnsignedIntType,"RG32UI")),this.curSh>=2&&this.sh2Texture.value===(this.extSplats?e.emptyExtSh2Texture:e.emptySh2Texture)&&(this.sh2Texture.value=this.newUint32ArrayTexture(new Uint32Array(256*this.maxPages*256*4),256,256,this.maxPages,r.RGBAIntegerFormat,r.UnsignedIntType,"RGBA32UI")),this.extSplats?this.curSh>=3&&(this.sh3Texture.value===e.emptyExtSh3Texture&&(this.sh3Texture.value=this.newUint32ArrayTexture(new Uint32Array(256*this.maxPages*256*4),256,256,this.maxPages,r.RGBAIntegerFormat,r.UnsignedIntType,"RGBA32UI")),this.sh3TextureB.value===e.emptyExtSh3BTexture&&(this.sh3TextureB.value=this.newUint32ArrayTexture(new Uint32Array(256*this.maxPages*256*4),256,256,this.maxPages,r.RGBAIntegerFormat,r.UnsignedIntType,"RGBA32UI"))):this.curSh>=3&&this.sh3Texture.value===e.emptySh3Texture&&(this.sh3Texture.value=this.newUint32ArrayTexture(new Uint32Array(256*this.maxPages*256*4),256,256,this.maxPages,r.RGBAIntegerFormat,r.UnsignedIntType,"RGBA32UI"))}allocatePage(){return this.pageFreelist.shift()}freePage(e){this.pageFreelist.push(e)}getSplatsChunk(e,t){const n=this.splatsChunkToPage.get(e);if(n)return n[t]}insertSplatsChunkPage(e,t,n,r){this.splatsChunkToPage.has(e)||this.splatsChunkToPage.set(e,[]);const i=this.splatsChunkToPage.get(e);if(!i)throw new Error("impossible");t>=i.length&&(i.length=t+1);const s={page:n,lru:r};return i[t]=s,this.pageLru.add(s),this.pageToSplatsChunk[n]={splats:e,chunk:t,time:performance.now()},this.pageToSplatsChunk[n]}removeSplatsChunkPage(e,t,n){const r=this.splatsChunkToPage.get(e);if(!r)throw new Error("impossible");const i=r[t];if(!i)throw new Error(`pageLru not found for splats: ${e}, chunk: ${t}, page: ${n}`);for(this.pageLru.delete(i),r[t]=void 0;r.length>0&&void 0===r[r.length-1];)r.pop();for(0===r.length&&this.splatsChunkToPage.delete(e),this.pageToSplatsChunk[n]=void 0;this.pageToSplatsChunk.length>0&&void 0===this.pageToSplatsChunk[this.pageToSplatsChunk.length-1];)this.pageToSplatsChunk.pop()}uploadPage(t,n,r,i){const s=t*this.pageSplats;if(this.packedTexture.value.image.data.subarray(4*s,4*s+n.length).set(n),this.packedTexture.value.addLayerUpdate(t),this.packedTexture.value.needsUpdate=!0,i){this.extTexture.value.image.data.subarray(4*s,4*s+i.length).set(i),this.extTexture.value.addLayerUpdate(t),this.extTexture.value.needsUpdate=!0}const a=this.extSplats?r.sh3a&&r.sh3b?3:r.sh2?2:r.sh1?1:0:r.sh3?3:r.sh2?2:r.sh1?1:0;if(this.ensureShTextures(a),this.extSplats){if(this.sh1Texture.value!==e.emptyExtSh1Texture&&r.sh1){const e=r.sh1;this.sh1Texture.value.image.data.subarray(4*s,4*s+e.length).set(e),this.sh1Texture.value.addLayerUpdate(t),this.sh1Texture.value.needsUpdate=!0}}else if(this.sh1Texture.value!==e.emptySh1Texture&&r.sh1){const e=r.sh1;this.sh1Texture.value.image.data.subarray(2*s,2*s+e.length).set(e),this.sh1Texture.value.addLayerUpdate(t),this.sh1Texture.value.needsUpdate=!0}if(this.sh2Texture.value!==e.emptySh2Texture&&r.sh2){const e=r.sh2;this.sh2Texture.value.image.data.subarray(4*s,4*s+e.length).set(e),this.sh2Texture.value.addLayerUpdate(t),this.sh2Texture.value.needsUpdate=!0}if(this.extSplats){if(this.sh3Texture.value!==e.emptyExtSh3Texture&&r.sh3a){const e=r.sh3a;this.sh3Texture.value.image.data.subarray(4*s,4*s+e.length).set(e),this.sh3Texture.value.addLayerUpdate(t),this.sh3Texture.value.needsUpdate=!0}if(this.sh3TextureB.value!==e.emptyExtSh3BTexture&&r.sh3b){const e=r.sh3b;this.sh3TextureB.value.image.data.subarray(4*s,4*s+e.length).set(e),this.sh3TextureB.value.addLayerUpdate(t),this.sh3TextureB.value.needsUpdate=!0}}else if(this.sh3Texture.value!==e.emptySh3Texture&&r.sh3){const e=r.sh3;this.sh3Texture.value.image.data.subarray(4*s,4*s+e.length).set(e),this.sh3Texture.value.addLayerUpdate(t),this.sh3Texture.value.needsUpdate=!0}}getGlTexture(e){return ro(this.renderer,e)}newUint32ArrayTexture(e,t,n,i,s,a,o){const l=new r.DataArrayTexture(e,t,n,i);return l.format=s,l.type=a,l.internalFormat=o,l.needsUpdate=!0,this.renderer.initTexture(l),l}driveFetchers(){const e=[],t=[];let n=0;for(const{splats:s,chunk:a}of this.fetchPriority){const r=this.getSplatsChunk(s,a);if(r)n>=this.maxPages?t.push(r):e.push(r),n+=1;else if(this.fetched.some((({splats:e,chunk:t})=>s===e&&a===t))||this.fetchers.some((({splats:e,chunk:t})=>s===e&&a===t)))n+=1;else if(n<this.maxPages&&this.fetchers.length<this.numFetchers){n+=1;const e=s.fetchDecodeChunk(a).then((async e=>{this.fetched.push({splats:s,chunk:a,data:e}),this.fetchPause>0&&await new Promise((e=>setTimeout(e,this.fetchPause)))}),(async e=>{const t=250+500*Math.random();await new Promise((e=>setTimeout(e,t)))})).finally((()=>{this.fetchers=this.fetchers.filter((({splats:e,chunk:t})=>s!==e||a!==t)),this.processFetched()}));this.fetchers.push({splats:s,chunk:a,promise:e}),e.then((e=>{this.autoDrive&&this.driveFetchers()}))}}const r=performance.now();for(const s of t.reverse())s.lru=r,this.pageLru.delete(s),this.pageLru.add(s);const i=new Set(this.pageLru);for(const s of e.reverse())i.delete(s),s.lru=r,this.pageLru.delete(s),this.pageLru.add(s);this.freeablePages=Array.from(i).map((({page:e})=>e))}allocateFreeable(){const e=this.freeablePages.shift();if(void 0===e)return;const t=this.pageToSplatsChunk[e];if(!t)throw new Error(`splatsChunk not found for page: ${e}`);const{splats:n,chunk:r}=t;return this.removeSplatsChunkPage(n,r,e),this.lodTreeUpdates.push({splats:n,page:e,chunk:r,numSplats:this.pageSplats}),e}processFetched(){const e=performance.now();for(;;){const t=this.fetched.shift();if(!t)break;const{splats:n,chunk:r,data:i}=t;let s=this.allocatePage();if(void 0===s&&(s=this.allocateFreeable(),void 0===s))return;this.insertSplatsChunkPage(n,r,s,e);const{numSplats:a,extra:o}=i;if(this.lodTreeUpdates.push({splats:n,page:s,chunk:r,numSplats:a,lodTree:o.lodTree}),this.extSplats){const e=i.extArrays,t=e[0],n=e[1];this.newUploads.push({page:s,numSplats:a,packedArray:t,extArray:n,extra:o})}else{const e=i.packedArray;this.newUploads.push({page:s,numSplats:a,packedArray:e,extra:o})}}}processUploads(){for(;;){const e=this.readyUploads.shift();if(!e)break;const{page:t,numSplats:n,packedArray:r,extArray:i,extra:s}=e;this.uploadPage(t,r,s,i)}}consumeLodTreeUpdates(){const e=this.lodTreeUpdates;return this.lodTreeUpdates=[],this.readyUploads.push(...this.newUploads),this.newUploads=[],e}};to.emptyUint32x4=(()=>{const{width:e,height:t,depth:n,maxSplats:i}=gi(1),s=new Uint32Array(4*i),a=new r.DataArrayTexture(s,e,t,n);return a.format=r.RGBAIntegerFormat,a.type=r.UnsignedIntType,a.internalFormat="RGBA32UI",a.needsUpdate=!0,a})(),to.emptyUint32x2=(()=>{const{width:e,height:t,depth:n,maxSplats:i}=gi(1),s=new Uint32Array(2*i),a=new r.DataArrayTexture(s,e,t,n);return a.format=r.RGIntegerFormat,a.type=r.UnsignedIntType,a.internalFormat="RG32UI",a.needsUpdate=!0,a})(),to.emptyIndicesTexture=(()=>{const e=new Uint32Array(16384),t=new r.DataTexture(e,4096,1);return t.format=r.RGBAIntegerFormat,t.type=r.UnsignedIntType,t.internalFormat="RGBA32UI",t.needsUpdate=!0,t})(),to.emptyPackedTexture=to.emptyUint32x4,to.emptyExtTexture=to.emptyUint32x4,to.emptySh1Texture=to.emptyUint32x2,to.emptySh2Texture=to.emptyUint32x4,to.emptySh3Texture=to.emptyUint32x4,to.emptyExtSh1Texture=to.emptyUint32x4,to.emptyExtSh2Texture=to.emptyUint32x4,to.emptyExtSh3Texture=to.emptyUint32x4,to.emptyExtSh3BTexture=to.emptyUint32x4;let no=to;function ro(e,t){if(!e.properties.has(t))throw new Error("texture not found");const n=e.properties.get(t).__webglTexture;if(!n)throw new Error("texture not found");return n}const io=_a();async function so({url:e,requestHeader:t,withCredentials:n,offset:r,bytes:i}){const s=new Request(e,{headers:t?new Headers(t):void 0,credentials:n?"include":"same-origin"});void 0!==r&&void 0!==i&&s.headers.set("Range",`bytes=${r}-${r+i-1}`);const a=await fetch(s);if(!a.ok||!a.body)throw new Error(`Failed to fetch "${e}": ${a.status} ${a.statusText}`);return new Uint8Array(await a.arrayBuffer())}class ao{constructor(){this.fetchDyno=new $r({inTypes:{},outTypes:{gsplat:Ui},globals:()=>[ji],statements:({outputs:e})=>Wr(`\n ${e.gsplat}.flags = 0u;\n return;\n `)}).outputs.gsplat}prepareFetchSplat(){}dispose(){}getNumSplats(){return 0}hasRgbDir(){return!1}getNumSh(){return 0}setMaxSh(e){}fetchSplat({index:e}){return this.fetchDyno}forEachSplat(){}}const oo=class e extends ja{constructor(e={}){if(super({update:e=>this.update(e)}),this.isInitialized=!1,this.recolor=new r.Color(1,1,1),this.opacity=1,this.generatorDirty=!0,this.enableViewToObject=!1,this.enableViewToWorld=!1,this.enableWorldToView=!1,this.skinning=null,this.edits=null,this.rgbaDisplaceEdits=null,this.splatRgba=null,this.maxSh=3,this.showLodPageDyno=new Ts({value:0}),e.splats)this.splats=e.splats,this.numSplats=e.splats.getNumSplats();else if(e.paged){e.extSplats;const t=e.url??"";if(!0===e.paged)this.paged=new eo({rootUrl:t});else if(e.paged instanceof eo)this.paged=e.paged;else{if(!(e.paged instanceof no))throw new Error("Invalid paged option");this.paged=new eo({rootUrl:t,pager:e.paged})}this.splats=this.paged}else e.extSplats?(this.extSplats=e.extSplats instanceof Qs?e.extSplats:new Qs,e.extSplats=this.extSplats,this.numSplats=this.extSplats.numSplats,this.splats=this.extSplats):e.packedSplats?(this.packedSplats=e.packedSplats,this.packedSplats.splatEncoding=e.splatEncoding??{...Sr},this.splats=this.packedSplats):this.packedSplats=new fo;if(this.editable=e.editable??!0,this.raycastable=e.raycastable??!0,this.minRaycastOpacity=e.minRaycastOpacity??.2,this.onFrame=e.onFrame,this.context={transform:new qa,viewToWorld:new qa,worldToView:new qa,viewToObject:new qa,covTransform:new Ha,covViewToWorld:new Ha,covWorldToView:new Ha,covViewToObject:new Ha,recolor:new Ms({value:(new r.Vector4).setScalar(Number.NEGATIVE_INFINITY)}),time:new Ss({value:0}),deltaTime:new Ss({value:0}),numSplats:new Ts({value:0}),splats:new ao,enableLod:new ws({value:!1}),lodIndices:new Es({value:ho,key:"lodIndices"})},this.covSplats=e.covSplats??!1,this.covSplats&&!this.extSplats)throw new Error("CovSplats requires ExtSplats");if(this.objectModifiers=e.objectModifier?[e.objectModifier]:void 0,this.worldModifiers=e.worldModifier?[e.worldModifier]:void 0,e.objectModifiers&&(this.objectModifiers=e.objectModifiers),e.worldModifiers&&(this.worldModifiers=e.worldModifiers),this.enableLod=e.enableLod,this.lodScale=e.lodScale??1,this.behindFoveate=e.behindFoveate,this.coneFov0=e.coneFov0,this.coneFov=e.coneFov,this.coneFoveate=e.coneFoveate,this.updateGenerator(),e.url||e.fileBytes||e.stream||e.constructSplats||e.packedSplats&&!e.packedSplats.isInitialized||this.extSplats&&!this.extSplats.isInitialized)this.initialized=this.asyncInitialize(e).then((async()=>{if(this.updateGenerator(),this.isInitialized=!0,e.onLoad){const t=e.onLoad(this);t instanceof Promise&&await t}return this}));else if(this.isInitialized=!0,this.initialized=Promise.resolve(this),e.onLoad){const t=e.onLoad(this);t instanceof Promise&&(this.initialized=t.then((()=>this)))}}async asyncInitialize(e){const{url:t,fileBytes:n,fileType:r,fileName:i,stream:s,streamLength:a,maxSplats:o,constructSplats:l,onProgress:c,splatEncoding:u,lod:h,nonLod:d,lodAbove:p}=e;if(this.packedSplats){if(t||n||s||l){const e={url:t,fileBytes:n,fileType:r,fileName:i,stream:s,streamLength:a,maxSplats:o,construct:l,onProgress:c,splatEncoding:u,lod:h,nonLod:d,lodAbove:p};this.packedSplats.reinitialize(e)}await this.packedSplats.initialized,this.splats=this.packedSplats}else if(this.extSplats&&(t||n||s||l)){const e=l;this.extSplats.reinitialize({url:t,fileBytes:n,fileType:r,fileName:i,stream:s,streamLength:a,maxSplats:o,construct:e,onProgress:c,lod:h,nonLod:d,lodAbove:p}),await this.extSplats.initialized,this.splats=this.extSplats}this.splats&&(this.numSplats=this.splats.getNumSplats(),this.updateGenerator())}static async staticInitialize(){await _a(),e.isStaticInitialized=!0}pushSplat(e,t,n,r,i){this.packedSplats?this.packedSplats.pushSplat(e,t,n,r,i):this.extSplats&&this.extSplats.pushSplat(e,t,n,r,i)}forEachSplat(e){var t;null==(t=this.splats)||t.forEachSplat(e)}dispose(){this.splats&&this.splats!==this.packedSplats&&this.splats!==this.extSplats&&(this.splats.dispose(),this.splats=void 0),this.packedSplats&&(this.packedSplats.dispose(),this.packedSplats=void 0),this.extSplats&&(this.extSplats.dispose(),this.extSplats=void 0)}getBoundingBox(e=!0){var t;if(!this.initialized)throw new Error("Cannot get bounding box before SplatMesh is initialized");const n=new r.Vector3(Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY),i=new r.Vector3(Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY),s=new r.Vector3,a=[-1,1];null==(t=this.splats)||t.forEachSplat((function(t,r,o,l,c,u){if(e)n.min(r),i.max(r);else for(const e of a)for(const t of a)for(const c of a)s.set(e*o.x,t*o.y,c*o.z),s.applyQuaternion(l),s.add(r),n.min(s),i.max(s)}));return new r.Box3(n,i)}set objectModifier(e){this.objectModifiers=e?[e]:void 0}set worldModifier(e){this.worldModifiers=e?[e]:void 0}constructGenerator(e){if(this.covSplats)return this.constructCovGenerator(e);const{transform:t,viewToObject:n,recolor:r}=e,i=qr({index:"int"},{gsplat:Ui},(({index:i})=>{if(!i)throw new Error("index is undefined");i=co(e.lodIndices,i,e.numSplats,e.enableLod,this.showLodPageDyno),e.splats.setMaxSh(this.maxSh),e.splats.prepareFetchSplat();let s=e.splats.fetchSplat({index:i,viewOrigin:n.translate});if(this.splatRgba&&(s=uo(s,this.splatRgba.dyno,i,e.enableLod)),this.skinning&&(s=this.skinning.modify(s)),this.objectModifiers)for(const e of this.objectModifiers)s=e.apply({gsplat:s}).gsplat;s=t.applyGsplat(s);const a=zs(r,Ni(s).outputs.rgba);if(s=$i({gsplat:s,rgba:a}),this.rgbaDisplaceEdits&&(s=this.rgbaDisplaceEdits.modify(s)),this.worldModifiers)for(const e of this.worldModifiers)s=e.apply({gsplat:s}).gsplat;return{gsplat:s}}));this.generator=i,this.covGenerator=void 0}constructCovGenerator(e){const{covTransform:t,covViewToObject:n,recolor:r}=e,i=qr({index:"int"},{covsplat:Fi},(({index:i})=>{if(!i)throw new Error("index is undefined");i=co(e.lodIndices,i,e.numSplats,e.enableLod,this.showLodPageDyno),e.splats.prepareFetchSplat();let s=e.splats.fetchSplat({index:i,viewOrigin:n.offset});if(this.splatRgba&&(s=uo(s,this.splatRgba.dyno,i,e.enableLod)),this.objectModifiers)for(const e of this.objectModifiers)s=e.apply({gsplat:s}).gsplat;let a=Oi(s);if(this.skinning&&(a=this.skinning.modifyCov(a)),this.covObjectModifiers)for(const e of this.covObjectModifiers)a=e.apply({covsplat:a}).covsplat;a=t.applyCovSplat(a);const o=zs(r,ss(a).outputs.rgba);if(a=as({covsplat:a,rgba:o}),this.rgbaDisplaceEdits&&(a=this.rgbaDisplaceEdits.modifyCov(a)),this.covWorldModifiers)for(const e of this.covWorldModifiers)a=e.apply({covsplat:a}).covsplat;return{covsplat:a}}));this.generator=void 0,this.covGenerator=i}updateGenerator(){this.generatorDirty=!0}update({renderer:t,time:n,deltaTime:i,viewToWorld:s,camera:a,renderSize:o,globalEdits:l,lodIndices:c}){var u,h,d;this.context.time.value=n,this.context.deltaTime.value=i,e.dynoTime.value=n,this.showLodPageDyno.value=this.showLodPage??-1;const p=this.splats??this.packedSplats??this.extSplats;p&&(this.context.splats=p),this.numSplats=this.context.splats.getNumSplats();let m=!1;const f=(null==(u=this.packedSplats)?void 0:u.lodSplats)??(null==(h=this.extSplats)?void 0:h.lodSplats);if(this.context.enableLod.value=null!=f&&null!=c,!1===this.enableLod&&(this.context.enableLod.value=!1),this.context.lodIndices.value=(null==c?void 0:c.texture)??ho,this.context.enableLod.value&&f&&(this.context.splats=f,this.numSplats=(null==c?void 0:c.numSplats)??0),this.context.numSplats.value=this.numSplats,this.context.splats!==this.lastSplats&&(this.lastSplats=this.context.splats,this.generatorDirty=!0),this.covSplats){this.context.covTransform.update(this)&&(m=!0),this.context.covViewToWorld.updateFromMatrix(s)&&this.enableViewToWorld&&(m=!0);const e=s.clone().invert();this.context.covWorldToView.updateFromMatrix(e)&&this.enableWorldToView&&(m=!0);const t=this.matrixWorld.clone().invert().multiply(s);this.context.covViewToObject.updateFromMatrix(t)&&(this.enableViewToObject||this.context.splats.hasRgbDir())&&(m=!0)}else{this.context.transform.update(this)&&(m=!0),this.context.viewToWorld.updateFromMatrix(s)&&this.enableViewToWorld&&(m=!0);const e=s.clone().invert();this.context.worldToView.updateFromMatrix(e)&&this.enableWorldToView&&(m=!0);const t=(new r.Matrix4).compose(this.context.transform.translate.value,this.context.transform.rotate.value,(new r.Vector3).setScalar(this.context.transform.scale.value)).invert().multiply(s);this.context.viewToObject.updateFromMatrix(t)&&(this.enableViewToObject||this.context.splats.hasRgbDir())&&(m=!0)}const g=new r.Vector4(this.recolor.r,this.recolor.g,this.recolor.b,this.opacity);g.equals(this.context.recolor.value)||(this.context.recolor.value.copy(g),m=!0);const x=this.editable?(this.edits??[]).concat(l):[];this.editable&&!this.edits&&this.traverseVisible((e=>{e instanceof za&&x.push(e)})),x.sort(((e,t)=>e.ordering-t.ordering));const y=x.map((e=>{if(null!=e.sdfs)return{edit:e,sdfs:e.sdfs};const t=[];return e.traverseVisible((e=>{e instanceof Ua&&t.push(e)})),{edit:e,sdfs:t}}));if(y.length>0&&!this.rgbaDisplaceEdits){const e=y.length,t=y.reduce(((e,t)=>e+t.sdfs.length),0);this.rgbaDisplaceEdits=new Ba({maxEdits:e,maxSdfs:t}),this.generatorDirty=!0}if(this.rgbaDisplaceEdits){const e=this.rgbaDisplaceEdits.update(y);m||(m=e.updated),e.dynoUpdated&&(this.generatorDirty=!0)}this.generatorDirty&&(this.constructGenerator(this.context),this.generatorDirty=!1,m=!0),m&&this.updateVersion(),null==(d=this.onFrame)||d.call(this,{mesh:this,time:n,deltaTime:i})}raycast(t,n){var i,s,a,o,l,c,u,h,d,p,m,f,g,x,y,v,b,w,T,S,_,M,A;if(!e.isStaticInitialized||!this.raycastable||!this.packedSplats&&!this.extSplats&&!this.paged)return;const E=null!=this.paged,C=E?(null==(s=null==(i=this.paged)?void 0:i.pager)?void 0:s.extSplats)??!1:null!=this.extSplats,{near:R,far:D,ray:k}=t,I=this.matrixWorld.clone().invert(),P=(new r.Matrix3).setFromMatrix4(I),L=k.origin.clone().applyMatrix4(I),U=k.direction.clone().applyMatrix3(P),F=Ta.get_raycast_buffer(),z=F.length/4;let B=0;const V=(null==(a=this.raycastIndices)?void 0:a.numSplats)??(E?null==(o=this.paged)?void 0:o.numSplats:this.context.numSplats.value)??0,O=(null==(l=this.raycastIndices)?void 0:l.indices)??(E?null==(c=this.paged)?void 0:c.dynoIndices.value.image.data:this.context.enableLod.value?this.context.lodIndices.value.image.data:null)??null;if(C){const e=Ta.get_raycast_buffer2(),t=E?null==(y=null==(x=this.paged)?void 0:x.pager)?void 0:y.packedTexture.value.image.data:O?null==(b=null==(v=this.extSplats)?void 0:v.lodSplats)?void 0:b.extArrays[0]:null==(w=this.extSplats)?void 0:w.extArrays[0],n=E?null==(S=null==(T=this.paged)?void 0:T.pager)?void 0:S.extTexture.value.image.data:O?null==(M=null==(_=this.extSplats)?void 0:_.lodSplats)?void 0:M.extArrays[1]:null==(A=this.extSplats)?void 0:A.extArrays[1];if(!t||!n)return;for(let r=0;r<V;r+=z){const i=Math.min(z,V-r);if(O)for(let a=0;a<i;++a){const i=4*a,s=4*O[r+a];F[i]=t[s],F[i+1]=t[s+1],F[i+2]=t[s+2],F[i+3]=t[s+3],e[i]=n[s],e[i+1]=n[s+1],e[i+2]=n[s+2],e[i+3]=n[s+3]}else F.set(t.subarray(4*r,4*(r+i))),e.set(n.subarray(4*r,4*(r+i)));const s=sa(L.x,L.y,L.z,U.x,U.y,U.z,this.minRaycastOpacity,R,D,i);B=this.appendRaycastBuffer(B,s)}}else{const e=E?null==(h=null==(u=this.paged)?void 0:u.pager)?void 0:h.packedTexture.value.image.data:O?null==(p=null==(d=this.packedSplats)?void 0:d.lodSplats)?void 0:p.packedArray:null==(m=this.packedSplats)?void 0:m.packedArray;if(!e)return;const t=E?null==(f=this.paged)?void 0:f.splatEncoding:null==(g=this.packedSplats)?void 0:g.splatEncoding;for(let n=0;n<V;n+=z){const r=Math.min(z,V-n);if(O)for(let t=0;t<r;++t){const r=4*t,i=4*O[n+t];F[r]=e[i],F[r+1]=e[i+1],F[r+2]=e[i+2],F[r+3]=e[i+3]}else F.set(e.subarray(4*n,4*(n+r)));const i=aa(L.x,L.y,L.z,U.x,U.y,U.z,this.minRaycastOpacity,R,D,r,(null==t?void 0:t.lnScaleMin)??yr,(null==t?void 0:t.lnScaleMax)??9,(null==t?void 0:t.lodOpacity)??!1);B=this.appendRaycastBuffer(B,i)}}for(const r of e.raycastBuffer.subarray(0,B)){const e=k.direction.clone().multiplyScalar(r).add(k.origin);n.push({distance:r,point:e,object:this})}}appendRaycastBuffer(t,n){const r=t+n.length;let i=e.raycastBuffer.length;if(r>i){for(;i<r;)i*=2;const n=new Float32Array(i);n.set(e.raycastBuffer.subarray(0,t)),e.raycastBuffer=n}return e.raycastBuffer.set(n,t),t+n.length}async createLodSplats({rgbaArray:e,quality:t}={}){this.packedSplats?await this.packedSplats.createLodSplats({quality:t,rgbaArray:e}):this.extSplats&&await this.extSplats.createLodSplats({quality:t,rgbaArray:e})}};oo.staticInitialized=oo.staticInitialize(),oo.isStaticInitialized=!1,oo.dynoTime=new Ss({value:0}),oo.raycastBuffer=new Float32Array(1024);let lo=oo;function co(e,t,n,r,i){return Hr({inTypes:{lodIndices:"usampler2D",index:"int",numSplats:"int",enableLod:"bool",showLodPage:"int"},outTypes:{index:"int"},inputs:{lodIndices:e,index:t,numSplats:n,enableLod:r,showLodPage:i},statements:({inputs:e,outputs:t})=>Wr(`\n int index = ${e.index};\n if (${e.showLodPage} < 0) {\n if (index >= ${e.numSplats}) {\n return;\n }\n if (${e.enableLod}) {\n ivec2 lodIndexCoord = ivec2((index >> 2) & 4095, index >> 14);\n uint splatIndex = texelFetch(${e.lodIndices}, lodIndexCoord, 0)[index & 3];\n ${t.index} = int(splatIndex);\n } else {\n ${t.index} = index;\n }\n } else {\n int start = ${e.showLodPage} << 16;\n if (index >= 65536) {\n return;\n }\n ${t.index} = start + index;\n }\n `)}).outputs.index}function uo(e,t,n,r){return Hr({inTypes:{gsplat:Ui,rgba:ka,index:"int",enableLod:"bool"},outTypes:{gsplat:Ui},inputs:{gsplat:e,rgba:t,index:n,enableLod:r},statements:({inputs:e,outputs:t})=>Wr(`\n ${t.gsplat} = ${e.gsplat};\n if (!${e.enableLod} && (${e.index} >= 0) && (${e.index} < ${e.rgba}.count)) {\n ${t.gsplat}.rgba = texelFetch(${e.rgba}.texture, splatTexCoord(${e.index}), 0);\n }\n `)}).outputs.gsplat}const ho=(()=>{const e=new r.DataTexture(new Uint32Array(16384),4096,1,r.RGBAIntegerFormat,r.UnsignedIntType);return e.internalFormat="RGBA32UI",e.needsUpdate=!0,e})();new r.BufferGeometry,new r.ShaderMaterial,(()=>{try{new Function("return 42;")}catch(Jm){return!1}})();class po extends r.Loader{constructor(e){super(e),this.fileLoader=new r.FileLoader(e)}load(e,t,n,r){return this.loadInternal({url:e,onLoad:t,onProgress:n,onError:r})}async loadAsync(e,t){return new Promise(((n,r)=>{this.load(e,(e=>{n(e)}),t,r)}))}parse(e){return new lo({packedSplats:e})}loadInternal({packedSplats:e,extSplats:t,url:n,fileBytes:r,fileType:i,fileName:s,stream:a,streamLength:o,onLoad:l,onProgress:c,onError:u,lod:h,nonLod:d,lodAbove:p,lodBase:m}){r instanceof ArrayBuffer&&(r=new Uint8Array(r));const f=r?void 0:this.manager.resolveURL((this.path??"")+(n??""));let g=null==a?void 0:a.getReader();this.manager.itemStart(f??""),Li.withWorker((async n=>{const u=(null==e?void 0:e.lod)??(null==t?void 0:t.lod);u&&(h=u);const x=(null==e?void 0:e.nonLod)??(null==t?void 0:t.nonLod);void 0!==x&&(d=x);const y=f?new URL(f,window.location.href).toString():void 0,v=await n.call(t?"loadExtSplats":"loadPackedSplats",{url:y,requestHeader:this.requestHeader,withCredentials:this.withCredentials,fileBytes:null==r?void 0:r.slice(),fileType:i,pathName:f||s,chunked:void 0!==a,chunkedLength:o,encoding:null==e?void 0:e.splatEncoding,lod:h,lodBase:m,nonLod:d,lodAbove:p},{onStatus:async e=>{const{loaded:t,total:r}=e;if(void 0!==t&&c&&c(new ProgressEvent("progress",{lengthComputable:0!==r,loaded:t,total:r})),e.nextChunk){let e;if(g){const{done:t,value:n}=await g.read();t?(g.releaseLock(),g=void 0,e=new Uint8Array(0)):e=n}else e=new Uint8Array(0);n.call("nextChunk",{chunk:e})}}});if(v.lodSplats&&(v.lodSplats=t?new Qs({...v.lodSplats}):new fo({...v.lodSplats,maxSplats:null==e?void 0:e.maxSplats})),t){const e={...v};t.initialize(e),null==l||l(t)}else{const t={...v};e?(e.initialize(t),null==l||l(e)):null==l||l(new fo(t))}})).catch((e=>{this.manager.itemError(f??""),null==u||u(e)})).finally((()=>{this.manager.itemEnd(f??"")}))}async loadInternalAsync({packedSplats:e,extSplats:t,url:n,fileBytes:r,fileType:i,fileName:s,stream:a,streamLength:o,onProgress:l,lod:c,nonLod:u,lodAbove:h,lodBase:d}){return new Promise(((p,m)=>{this.loadInternal({packedSplats:e,extSplats:t,url:n,fileBytes:r,fileType:i,fileName:s,stream:a,streamLength:o,onLoad:p,onProgress:l,onError:m,lod:c,nonLod:u,lodAbove:h,lodBase:d})}))}}const mo=class e{constructor(e={}){this.maxSplats=0,this.numSplats=0,this.packedArray=null,this.maxSh=3,this.isInitialized=!1,this.target=null,this.source=null,this.needsUpdate=!0,this.extra={},this.dyno=new go({packedSplats:this}),this.dynoRgbMinMaxLnScaleMinMax=new Ms({key:"rgbMinMaxLnScaleMinMax",value:new r.Vector4(0,1,yr,9),update:e=>{var t,n,r,i;return e.set((null==(t=this.splatEncoding)?void 0:t.rgbMin)??0,(null==(n=this.splatEncoding)?void 0:n.rgbMax)??1,(null==(r=this.splatEncoding)?void 0:r.lnScaleMin)??yr,(null==(i=this.splatEncoding)?void 0:i.lnScaleMax)??9),e}}),this.dynoNumSh=new Ts({key:"numSh",value:0,update:()=>Math.min(this.getNumSh(),this.maxSh)}),this.dynoShMax=new _s({key:"shMax",value:new r.Vector3,update:e=>{var t,n,r;return e.set((null==(t=this.splatEncoding)?void 0:t.sh1Max)??1,(null==(n=this.splatEncoding)?void 0:n.sh2Max)??1,(null==(r=this.splatEncoding)?void 0:r.sh3Max)??1),e}}),this.initialized=Promise.resolve(this),this.reinitialize(e)}reinitialize(e){this.isInitialized=!1,this.extra={},this.maxSplats=e.maxSplats??0,this.splatEncoding=e.splatEncoding,this.lod=e.lod,this.nonLod=e.nonLod,e.url||e.fileBytes||e.stream||e.construct?this.initialized=this.asyncInitialize(e).then((()=>(this.isInitialized=!0,this))):(this.initialize(e),this.isInitialized=!0,this.initialized=Promise.resolve(this))}initialize(e){this.extra=e.extra??{},this.splatEncoding=e.splatEncoding??this.splatEncoding,this.lodSplats=e.lodSplats,e.packedArray?(this.packedArray=e.packedArray,this.numSplats=e.numSplats??this.packedArray.length/4,this.maxSplats=Math.floor(this.packedArray.length/4),this.maxSplats=Math.floor(this.maxSplats/br)*br,this.numSplats=Math.min(this.maxSplats,e.numSplats??Number.POSITIVE_INFINITY)):(this.maxSplats=e.maxSplats??0,this.numSplats=0)}async asyncInitialize(e){const{url:t,fileBytes:n,fileType:r,fileName:i,stream:s,streamLength:a,construct:o,lod:l,nonLod:c,lodAbove:u}=e;this.lod=l,this.nonLod=c;const h=new po;if((n||t||s)&&await h.loadInternalAsync({packedSplats:this,url:t,fileBytes:n,fileType:r,fileName:i,stream:s,streamLength:a,onProgress:e.onProgress,lodAbove:u}),o){const e=o(this);e instanceof Promise&&await e}}dispose(){this.target&&(this.target.dispose(),this.target.texture.source.data=null,this.target=null),this.source&&(this.source.dispose(),this.source.source.data=null,this.source=null),this.packedArray=null;for(const e in this.extra){const t=this.extra[e];if(t instanceof bs){const e=t.value;(null==e?void 0:e.isTexture)&&(e.dispose(),e.source.data=null)}}this.extra={},this.disposeLodSplats()}prepareFetchSplat(){}getNumSplats(){return this.numSplats}hasRgbDir(){return Math.min(this.getNumSh(),this.maxSh)>0}getNumSh(){return this.extra.sh1?this.extra.sh2?this.extra.sh3?3:2:1:0}setMaxSh(e){this.maxSh=e}fetchSplat({index:e,viewOrigin:t}){let n=Vi(this.dyno,e);if(this.hasRgbDir()&&t){const r=Ni(n).outputs.center,i=Hs(Fs(r,t)),{sh1Texture:s,sh2Texture:a,sh3Texture:o}=this.ensureShTextures();let{rgb:l}=bo({coord:qi(e),viewDir:i,numSh:this.dynoNumSh,sh1Texture:s,sh2Texture:a,sh3Texture:o,shMax:this.dynoShMax});l=Us(l,Ni(n).outputs.rgb),n=$i({gsplat:n,rgb:l})}return n}ensureShTextures(){if(!this.extra.sh1)return{};let e=this.extra.sh1Texture;if(!e){let t=this.extra.sh1;const{width:n,height:i,depth:s,maxSplats:a}=gi(t.length/2);if(t.length<2*a){const e=new Uint32Array(2*a);e.set(t),this.extra.sh1=e,t=e}const o=new r.DataArrayTexture(t,n,i,s);o.format=r.RGIntegerFormat,o.type=r.UnsignedIntType,o.internalFormat="RG32UI",o.needsUpdate=!0,e=new Cs({value:o,key:"sh1"}),this.extra.sh1Texture=e}if(!this.extra.sh2)return{sh1Texture:e};let t=this.extra.sh2Texture;if(!t){let e=this.extra.sh2;const{width:n,height:i,depth:s,maxSplats:a}=gi(e.length/4);if(e.length<4*a){const t=new Uint32Array(4*a);t.set(e),this.extra.sh2=t,e=t}const o=new r.DataArrayTexture(e,n,i,s);o.format=r.RGBAIntegerFormat,o.type=r.UnsignedIntType,o.internalFormat="RGBA32UI",o.needsUpdate=!0,t=new Cs({value:o,key:"sh2"}),this.extra.sh2Texture=t}if(!this.extra.sh3)return{sh1Texture:e,sh2Texture:t};let n=this.extra.sh3Texture;if(!n){let e=this.extra.sh3;const{width:t,height:i,depth:s,maxSplats:a}=gi(e.length/4);if(e.length<4*a){const t=new Uint32Array(4*a);t.set(e),this.extra.sh3=t,e=t}const o=new r.DataArrayTexture(e,t,i,s);o.format=r.RGBAIntegerFormat,o.type=r.UnsignedIntType,o.internalFormat="RGBA32UI",o.needsUpdate=!0,n=new Cs({value:o,key:"sh3"}),this.extra.sh3Texture=n}return{sh1Texture:e,sh2Texture:t,sh3Texture:n}}ensureSplats(e){const t=e<=this.maxSplats?this.maxSplats:Math.max(e,2*this.maxSplats),n=this.packedArray?this.packedArray.length/4:0;if(!this.packedArray||t>n){this.maxSplats=gi(t).maxSplats;const e=new Uint32Array(4*this.maxSplats);this.packedArray&&e.set(this.packedArray),this.packedArray=e}return this.packedArray}ensureSplatsSh(e,t){let n,r;if(0===e)return this.ensureSplats(t);if(1===e)n=2,r="sh1";else if(2===e)n=4,r="sh2";else{if(3!==e)throw new Error(`Invalid level: ${e}`);n=4,r="sh3"}let i=this.extra[r]?this.extra[r].length/n:0;const s=t<=i?i:Math.max(t,2*i);if(!this.extra[r]||s>i){i=gi(s).maxSplats;const e=new Uint32Array(i*n);this.extra[r]&&e.set(this.extra[r]),this.extra[r]=e}return this.extra[r]}getSplat(e){if(!this.packedArray||e>=this.numSplats)throw new Error("Invalid index");return fi(this.packedArray,e,this.splatEncoding)}setSplat(e,t,n,r,i,s){di(this.ensureSplats(e+1),e,t.x,t.y,t.z,n.x,n.y,n.z,r.x,r.y,r.z,r.w,i,s.r,s.g,s.b),this.numSplats=Math.max(this.numSplats,e+1)}pushSplat(e,t,n,r,i){di(this.ensureSplats(this.numSplats+1),this.numSplats,e.x,e.y,e.z,t.x,t.y,t.z,n.x,n.y,n.z,n.w,r,i.r,i.g,i.b),++this.numSplats}forEachSplat(e){if(this.packedArray&&this.numSplats)for(let t=0;t<this.numSplats;++t){const n=fi(this.packedArray,t,this.splatEncoding);e(t,n.center,n.scales,n.quaternion,n.opacity,n.color)}}ensureGenerate(e){if(this.target&&(e??1)<=this.maxSplats)return!1;this.target&&this.target.dispose();const t=gi(e??1),{width:n,height:i,depth:s}=t;return this.maxSplats=t.maxSplats,this.target=new r.WebGLArrayRenderTarget(n,i,s,{depthBuffer:!1,stencilBuffer:!1,generateMipmaps:!1,magFilter:r.NearestFilter,minFilter:r.NearestFilter}),this.target.texture.format=r.RGBAIntegerFormat,this.target.texture.type=r.UnsignedIntType,this.target.texture.internalFormat="RGBA32UI",this.target.scissorTest=!0,!0}generateMapping(e){let t=0;const n=e.map((e=>{const n=t,r=Math.ceil(e/br)*br;return t+=r,{base:n,count:e}}));return{maxSplats:t,mapping:n}}getTexture(){if(this.target)return this.target.texture;if(this.source||this.packedArray){return this.maybeUpdateSource()}return e.getEmptyArray}maybeUpdateSource(){if(!this.packedArray)throw new Error("No packed splats");if(this.needsUpdate||!this.source){if(this.needsUpdate=!1,this.source){const{width:e,height:t,depth:n}=this.source.image;this.maxSplats!==e*t*n&&(this.source.dispose(),this.source=null)}if(this.source)this.packedArray.buffer!==this.source.image.data.buffer&&(this.source.image.data=new Uint8Array(this.packedArray.buffer));else{const{width:e,height:t,depth:n}=gi(this.maxSplats);this.source=new r.DataArrayTexture(this.packedArray,e,t,n),this.source.format=r.RGBAIntegerFormat,this.source.type=r.UnsignedIntType,this.source.internalFormat="RGBA32UI",this.source.needsUpdate=!0}this.source.needsUpdate=!0}return this.source}prepareProgramMaterial(t){let n=e.generatorProgram.get(t);if(!n){const r=qr({index:"int"},{},(({index:e},n,{roots:r})=>{t.inputs.index=e;const i=t.outputs.gsplat,s=hs(i,this.dynoRgbMinMaxLnScaleMinMax);r.push(s)}));e.programTemplate||(e.programTemplate=new Ds(Aa().computeUvec4Template)),n=new Rs({graph:r,inputs:{index:"_index"},outputs:{output:"target"},template:e.programTemplate}),Object.assign(n.uniforms,{targetLayer:{value:0},targetBase:{value:0},targetCount:{value:0}}),e.generatorProgram.set(t,n)}const r=n.prepareMaterial();return e.fullScreenQuad.material=r,{program:n,material:r}}saveRenderState(e){return{target:e.getRenderTarget(),xrEnabled:e.xr.enabled,autoClear:e.autoClear}}resetRenderState(e,t){e.setRenderTarget(t.target),e.xr.enabled=t.xrEnabled,e.autoClear=t.autoClear}generate({generator:t,base:n,count:r,renderer:i}){if(!this.target)throw new Error("Target must be initialized with ensureSplats");if(n+r>this.maxSplats)throw new Error("Base + count exceeds maxSplats");const{program:s,material:a}=this.prepareProgramMaterial(t);s.update();const o=this.saveRenderState(i),l=Math.ceil((n+r)/br)*br,c=4194304;for(a.uniforms.targetBase.value=n,a.uniforms.targetCount.value=r;n<l;){const t=Math.floor(n/c);a.uniforms.targetLayer.value=t;const r=t*c,s=Math.floor((n-r)/br),o=Math.min(wr,Math.ceil((l-r)/br));this.target.scissor.set(0,s,br,o-s),i.setRenderTarget(this.target,t),i.xr.enabled=!1,i.autoClear=!1,e.fullScreenQuad.render(i),n+=br*(o-s)}return this.resetRenderState(i,o),{nextBase:l}}disposeLodSplats(){this.lodSplats&&(this.lodSplats.dispose(),this.lodSplats=void 0)}async createLodSplats({rgbaArray:t,quality:n}={}){const r="number"==typeof this.lod?Math.max(1.1,Math.min(2,this.lod)):n?1.75:1.5,i=this.packedArray.slice(),s=t?(await t.getArray()).slice():void 0,a={sh1:this.extra.sh1?this.extra.sh1.slice():void 0,sh2:this.extra.sh2?this.extra.sh2.slice():void 0,sh3:this.extra.sh3?this.extra.sh3.slice():void 0},o=await Li.withWorker((async e=>await e.call(n?"qualityLodPackedSplats":"tinyLodPackedSplats",{numSplats:this.numSplats,packedArray:i,extra:a,lodBase:r,rgba:s,encoding:this.splatEncoding??Sr}))),l=new e(o);this.lodSplats&&this.lodSplats.dispose(),this.lodSplats=l,this.nonLod=!0,this.lod=!n||"quality"}extractSplats(t,n){const r=gi(t.length).maxSplats,i=new e({maxSplats:r});for(let e=0;e<t.length;e++){const r=this.getSplat(t[e]);if(n){let n=.61803398875*(t[e]>>>16);n-=Math.floor(n);const i=Math.max(0,Math.min(1,Math.abs(6*n-3)-1)),s=Math.max(0,Math.min(1,Math.abs(6*n+1)-1)),a=Math.max(0,Math.min(1,Math.abs(6*n-1)-1));r.color.r*=i,r.color.g*=s,r.color.b*=a}i.pushSplat(r.center,r.scales,r.quaternion,r.opacity,r.color)}return i}};mo.getEmptyArray=(()=>{const{width:e,height:t,depth:n,maxSplats:i}=gi(1),s=new Uint32Array(4*i),a=new r.DataArrayTexture(s,e,t,n);return a.format=r.RGBAIntegerFormat,a.type=r.UnsignedIntType,a.internalFormat="RGBA32UI",a.needsUpdate=!0,a})(),mo.programTemplate=null,mo.generatorProgram=new WeakMap,mo.fullScreenQuad=new o(new r.RawShaderMaterial({visible:!1})),mo.emptyUint32x4=(()=>{const{width:e,height:t,depth:n,maxSplats:i}=gi(1),s=new Uint32Array(4*i),a=new r.DataArrayTexture(s,e,t,n);return a.format=r.RGBAIntegerFormat,a.type=r.UnsignedIntType,a.internalFormat="RGBA32UI",a.needsUpdate=!0,a})(),mo.emptyUint32x2=(()=>{const{width:e,height:t,depth:n,maxSplats:i}=gi(1),s=new Uint32Array(2*i),a=new r.DataArrayTexture(s,e,t,n);return a.format=r.RGIntegerFormat,a.type=r.UnsignedIntType,a.internalFormat="RG32UI",a.needsUpdate=!0,a})();let fo=mo;class go extends bs{constructor({packedSplats:e}={}){super({key:"packedSplats",type:zi,globals:()=>[Xi],value:{textureArray:fo.getEmptyArray,numSplats:0,rgbMinMaxLnScaleMinMax:new r.Vector4(0,1,yr,9),lodOpacity:!1},update:e=>{var t,n,r,i,s,a,o,l,c,u,h,d;return e.textureArray=(null==(t=this.packedSplats)?void 0:t.getTexture())??fo.getEmptyArray,e.numSplats=(null==(n=this.packedSplats)?void 0:n.numSplats)??0,e.rgbMinMaxLnScaleMinMax.set((null==(i=null==(r=this.packedSplats)?void 0:r.splatEncoding)?void 0:i.rgbMin)??0,(null==(a=null==(s=this.packedSplats)?void 0:s.splatEncoding)?void 0:a.rgbMax)??1,(null==(l=null==(o=this.packedSplats)?void 0:o.splatEncoding)?void 0:l.lnScaleMin)??yr,(null==(u=null==(c=this.packedSplats)?void 0:c.splatEncoding)?void 0:u.lnScaleMax)??9),e.lodOpacity=(null==(d=null==(h=this.packedSplats)?void 0:h.splatEncoding)?void 0:d.lodOpacity)??!1,e}}),this.packedSplats=e}}const xo=Xr("\n vec3 evaluatePackedSH1(uvec2 packedData, vec3 viewDir, float sh1Max) {\n // Extract sint7 values packed into 2 x uint32\n vec3 sh1_0 = vec3(ivec3(\n int(packedData.x << 25u) >> 25,\n int(packedData.x << 18u) >> 25,\n int(packedData.x << 11u) >> 25\n ));\n vec3 sh1_1 = vec3(ivec3(\n int(packedData.x << 4u) >> 25,\n int((packedData.x >> 3u) | (packedData.y << 29u)) >> 25,\n int(packedData.y << 22u) >> 25\n ));\n vec3 sh1_2 = vec3(ivec3(\n int(packedData.y << 15u) >> 25,\n int(packedData.y << 8u) >> 25,\n int(packedData.y << 1u) >> 25\n ));\n\n vec3 rgb = sh1_0 * (-0.4886025 * viewDir.y)\n + sh1_1 * (0.4886025 * viewDir.z)\n + sh1_2 * (-0.4886025 * viewDir.x);\n return rgb * (sh1Max / 63.0);\n }\n"),yo=Xr("\n vec3 evaluatePackedSH2(uvec4 packedData, vec3 viewDir, float sh2Max) {\n // Extract sint8 values packed into 4 x uint32\n vec3 sh2_0 = vec3(ivec3(\n int(packedData.x << 24u) >> 24,\n int(packedData.x << 16u) >> 24,\n int(packedData.x << 8u) >> 24\n ));\n vec3 sh2_1 = vec3(ivec3(\n int(packedData.x) >> 24,\n int(packedData.y << 24u) >> 24,\n int(packedData.y << 16u) >> 24\n ));\n vec3 sh2_2 = vec3(ivec3(\n int(packedData.y << 8u) >> 24,\n int(packedData.y) >> 24,\n int(packedData.z << 24u) >> 24\n ));\n vec3 sh2_3 = vec3(ivec3(\n int(packedData.z << 16u) >> 24,\n int(packedData.z << 8u) >> 24,\n int(packedData.z) >> 24\n ));\n vec3 sh2_4 = vec3(ivec3(\n int(packedData.w << 24u) >> 24,\n int(packedData.w << 16u) >> 24,\n int(packedData.w << 8u) >> 24\n ));\n\n vec3 rgb = sh2_0 * (1.0925484 * viewDir.x * viewDir.y)\n + sh2_1 * (-1.0925484 * viewDir.y * viewDir.z)\n + sh2_2 * (0.3153915 * (2.0 * viewDir.z * viewDir.z - viewDir.x * viewDir.x - viewDir.y * viewDir.y))\n + sh2_3 * (-1.0925484 * viewDir.x * viewDir.z)\n + sh2_4 * (0.5462742 * (viewDir.x * viewDir.x - viewDir.y * viewDir.y));\n return rgb * (sh2Max / 127.0);\n }\n"),vo=Xr("\n vec3 evaluatePackedSH3(uvec4 packedData, vec3 viewDir, float sh3Max) {\n // Extract sint6 values packed into 4 x uint32\n vec3 sh3_0 = vec3(ivec3(\n int(packedData.x << 26u) >> 26,\n int(packedData.x << 20u) >> 26,\n int(packedData.x << 14u) >> 26\n ));\n vec3 sh3_1 = vec3(ivec3(\n int(packedData.x << 8u) >> 26,\n int(packedData.x << 2u) >> 26,\n int((packedData.x >> 4u) | (packedData.y << 28u)) >> 26\n ));\n vec3 sh3_2 = vec3(ivec3(\n int(packedData.y << 22u) >> 26,\n int(packedData.y << 16u) >> 26,\n int(packedData.y << 10u) >> 26\n ));\n vec3 sh3_3 = vec3(ivec3(\n int(packedData.y << 4u) >> 26,\n int((packedData.y >> 2u) | (packedData.z << 30u)) >> 26,\n int(packedData.z << 24u) >> 26\n ));\n vec3 sh3_4 = vec3(ivec3(\n int(packedData.z << 18u) >> 26,\n int(packedData.z << 12u) >> 26,\n int(packedData.z << 6u) >> 26\n ));\n vec3 sh3_5 = vec3(ivec3(\n int(packedData.z) >> 26,\n int(packedData.w << 26u) >> 26,\n int(packedData.w << 20u) >> 26\n ));\n vec3 sh3_6 = vec3(ivec3(\n int(packedData.w << 14u) >> 26,\n int(packedData.w << 8u) >> 26,\n int(packedData.w << 2u) >> 26\n ));\n\n float xx = viewDir.x * viewDir.x;\n float yy = viewDir.y * viewDir.y;\n float zz = viewDir.z * viewDir.z;\n float xy = viewDir.x * viewDir.y;\n float yz = viewDir.y * viewDir.z;\n float zx = viewDir.z * viewDir.x;\n\n vec3 rgb = sh3_0 * (-0.5900436 * viewDir.y * (3.0 * xx - yy))\n + sh3_1 * (2.8906114 * xy * viewDir.z) +\n + sh3_2 * (-0.4570458 * viewDir.y * (4.0 * zz - xx - yy))\n + sh3_3 * (0.3731763 * viewDir.z * (2.0 * zz - 3.0 * xx - 3.0 * yy))\n + sh3_4 * (-0.4570458 * viewDir.x * (4.0 * zz - xx - yy))\n + sh3_5 * (1.4453057 * viewDir.z * (xx - yy))\n + sh3_6 * (-0.5900436 * viewDir.x * (xx - 3.0 * yy));\n return rgb * (sh3Max / 31.0);\n }\n");function bo({coord:e,viewDir:t,numSh:n,sh1Texture:r,sh2Texture:i,sh3Texture:s,shMax:a}){return new $r({inTypes:{coord:"ivec3",viewDir:"vec3",numSh:"int",sh1Texture:"usampler2DArray",sh2Texture:"usampler2DArray",sh3Texture:"usampler2DArray",shMax:"vec3"},outTypes:{rgb:"vec3"},inputs:{coord:e,viewDir:t,numSh:n,sh1Texture:r,sh2Texture:i,sh3Texture:s,shMax:a},globals:()=>[xo,yo,vo],statements:({inputs:e,outputs:t})=>{const n=["vec3 rgb = vec3(0.0);"];return e.sh1Texture&&(n.push(...Wr(`\n if (${e.numSh} >= 1) {\n vec3 sh1Rgb = evaluatePackedSH1(texelFetch(${e.sh1Texture}, ${e.coord}, 0).rg, ${e.viewDir}, ${e.shMax}.x);\n rgb += sh1Rgb;\n `)),e.sh2Texture&&(n.push(...Wr(`\n if (${e.numSh} >= 2) {\n vec3 sh2Rgb = evaluatePackedSH2(texelFetch(${e.sh2Texture}, ${e.coord}, 0), ${e.viewDir}, ${e.shMax}.y);\n rgb += sh2Rgb;\n `)),e.sh3Texture&&n.push(...Wr(`\n if (${e.numSh} >= 3) {\n vec3 sh3Rgb = evaluatePackedSH3(texelFetch(${e.sh3Texture}, ${e.coord}, 0), ${e.viewDir}, ${e.shMax}.z);\n rgb += sh3Rgb;\n }\n `)),n.push("}")),n.push("}")),n.push(`${t.rgb} = rgb;`),n}}).outputs}const wo=class e{constructor(e){if(this.lastTime=null,this.encodeLinear=!1,this.superXY=1,this.display=null,this.sorting=null,this.pending=null,this.sortingCheck=!1,this.readback16=new Uint16Array(0),this.readback32=new Uint32Array(0),this.spark=e.spark,this.camera=e.camera,this.viewToWorld=e.viewToWorld??new r.Matrix4,e.target){const{width:t,height:n,doubleBuffer:i}=e.target,s=Math.max(1,Math.min(4,e.target.superXY??1));if(this.superXY=s,t*s>8192||n*s>8192)throw new Error("Target size too large");this.target=new r.WebGLRenderTarget(t*s,n*s,{format:r.RGBAFormat,type:r.UnsignedByteType,colorSpace:r.SRGBColorSpace}),i&&(this.back=new r.WebGLRenderTarget(t*s,n*s,{format:r.RGBAFormat,type:r.UnsignedByteType,colorSpace:r.SRGBColorSpace})),this.encodeLinear=!0}this.onTextureUpdated=e.onTextureUpdated,this.sortRadial=e.sortRadial??!0,this.sortDistance=e.sortDistance,this.sortCoorient=e.sortCoorient,this.depthBias=e.depthBias,this.sort360=e.sort360,this.sort32=e.sort32,this.stochastic=e.stochastic??!1,this.orderingFreelist=new ci({allocate:e=>new Uint32Array(e),valid:(e,t)=>e.length===t}),this.autoUpdate=!1,this.setAutoUpdate(e.autoUpdate??!1)}dispose(){var e;this.setAutoUpdate(!1),this.target&&(this.target.dispose(),this.target=void 0),this.back&&(this.back.dispose(),this.back=void 0),this.display&&(this.spark.releaseAccumulator(this.display.accumulator),this.display.geometry.dispose(),this.display=null),(null==(e=this.pending)?void 0:e.accumulator)&&(this.spark.releaseAccumulator(this.pending.accumulator),this.pending=null)}setAutoUpdate(e){!this.autoUpdate&&e?this.spark.autoViewpoints.push(this):this.autoUpdate&&!e&&(this.spark.autoViewpoints=this.spark.autoViewpoints.filter((e=>e!==this))),this.autoUpdate=e}async prepare({scene:e,camera:t,viewToWorld:n,update:r,forceOrigin:i}){for(n?this.viewToWorld=n:(this.camera=t??this.camera,this.camera&&(this.camera.updateMatrixWorld(),this.viewToWorld=this.camera.matrixWorld.clone()));r??1;){const t=i?this.viewToWorld:this.spark.matrixWorld;if(this.spark.updateInternal({scene:e,originToWorld:t}))break;await new Promise((e=>setTimeout(e,10)))}const s=this.spark.active;s.refCount+=1,await this.sortUpdate({accumulator:s,viewToWorld:this.viewToWorld}),this.spark.releaseAccumulator(s)}renderTarget({scene:e,camera:t}){var n;const i=this.back??this.target;if(!i)throw new Error("Must initialize SparkViewpoint with target");if(!(t=t??this.camera))throw new Error("Must provide camera");if(t instanceof r.PerspectiveCamera){const e=(new r.PerspectiveCamera).copy(t,!1);e.aspect=i.width/i.height,e.updateProjectionMatrix(),t=e}this.viewToWorld=t.matrixWorld.clone();const s=this.spark.renderer.getRenderTarget();try{this.spark.renderer.setRenderTarget(i),this.spark.prepareViewpoint(this),this.spark.renderer.render(e,t)}finally{this.spark.prepareViewpoint(this.spark.defaultView),this.spark.renderer.setRenderTarget(s)}i!==this.target&&([this.target,this.back]=[this.back,this.target]),null==(n=this.onTextureUpdated)||n.call(this,i.texture)}async readTarget(){if(!this.target)throw new Error("Must initialize SparkViewpoint with target");const{width:e,height:t}=this.target,n=e*t*4;(!this.superPixels||this.superPixels.length<n)&&(this.superPixels=new Uint8Array(n)),await this.spark.renderer.readRenderTargetPixelsAsync(this.target,0,0,e,t,this.superPixels);const{superXY:r}=this;if(1===r)return this.superPixels;const i=e/r,s=t/r,a=i*s*4;(!this.pixels||this.pixels.length<a)&&(this.pixels=new Uint8Array(a));const{superPixels:o,pixels:l}=this,c=r*r;for(let u=0;u<s;u++){const e=u*i;for(let t=0;t<i;t++){const n=t*r;let i=0,s=0,a=0,h=0;for(let e=0;e<r;e++){const t=(u*r+e)*this.target.width;for(let e=0;e<r;e++){const r=4*(t+n+e);i+=o[r],s+=o[r+1],a+=o[r+2],h+=o[r+3]}}const d=4*(e+t);l[d]=i/c,l[d+1]=s/c,l[d+2]=a/c,l[d+3]=h/c}}return l}async prepareRenderPixels({scene:e,camera:t,viewToWorld:n,update:r,forceOrigin:i}){return await this.prepare({scene:e,camera:t,viewToWorld:n,update:r,forceOrigin:i}),this.renderTarget({scene:e,camera:t}),this.readTarget()}autoPoll({accumulator:e}){var t,n,r;this.camera&&(this.camera.updateMatrixWorld(),this.viewToWorld=this.camera.matrixWorld.clone());let i=!1,s=!1;if(this.display){if(e){i=!0;const{mappingVersion:t}=this.display.accumulator;e.mappingVersion===t&&(e.refCount+=1,this.spark.releaseAccumulator(this.display.accumulator),this.display.accumulator=e,this.display.viewToWorld.copy(this.viewToWorld),s=!0,this.spark.viewpoint===this&&this.spark.prepareViewpoint(this))}}else i=!0;const a=(null==(t=this.sorting)?void 0:t.viewToWorld)??(null==(n=this.display)?void 0:n.viewToWorld);a&&!wi({matrix1:this.viewToWorld,matrix2:a,maxDistance:this.sortDistance??.01,minCoorient:this.sortCoorient??this.sortRadial?.99:.999})&&(i=!0),i&&(e&&(e.refCount+=1),(null==(r=this.pending)?void 0:r.accumulator)&&this.spark.releaseAccumulator(this.pending.accumulator),this.pending={accumulator:e,viewToWorld:this.viewToWorld,displayed:s},this.driveSort())}async driveSort(){for(var e;;){if(this.sorting||!this.pending)return;const{viewToWorld:t,displayed:n}=this.pending;let r=this.pending.accumulator;if(r||(r=(null==(e=this.display)?void 0:e.accumulator)??this.spark.active,r.refCount+=1),this.pending=null,!r)throw new Error("No accumulator to sort");this.sorting={viewToWorld:t},await this.sortUpdate({accumulator:r,viewToWorld:t,displayed:n}),this.sorting=null,this.spark.releaseAccumulator(r)}}async sortUpdate({accumulator:t,viewToWorld:n,displayed:r=!1}){if(this.sortingCheck)throw new Error("Only one sort at a time");this.sortingCheck=!0,t=t??this.spark.active;const{numSplats:i,maxSplats:s}=t.splats;let a=0,o=this.orderingFreelist.alloc(s);if(this.stochastic){a=i;for(let e=0;e<i;++e)o[e]=e}else if(i>0){const{reader:r,doubleSortReader:l,sort32Reader:c,dynoSortRadial:u,dynoOrigin:h,dynoDirection:d,dynoDepthBias:p,dynoSort360:m,dynoSplats:f}=e.makeSorter(),g=this.sort32??!1;let x;if(g)this.readback32=r.ensureBuffer(s,this.readback32),x=this.readback32;else{const e=Math.ceil(s/2);this.readback16=r.ensureBuffer(e,this.readback16),x=this.readback16}const y=t.toWorld.clone().invert(),v=n.clone().premultiply(y);u.value=!!this.sort360||this.sortRadial,h.value.set(0,0,0).applyMatrix4(v),d.value.set(0,0,-1).applyMatrix4(v).sub(h.value).normalize(),p.value=this.depthBias??1,m.value=this.sort360??!1,f.packedSplats=t.splats;const b=g?c:l,w=g?i:Math.ceil(i/2);await r.renderReadback({renderer:this.spark.renderer,reader:b,count:w,readback:x});const T=await Ci((async e=>{const t=g?"sort32Splats":"sortDoubleSplats";return e.call(t,{maxSplats:s,numSplats:i,readback:x,ordering:o})}));g?this.readback32=T.readback:this.readback16=T.readback,o=T.ordering,a=T.activeSplats}this.updateDisplay({accumulator:t,viewToWorld:n,ordering:o,activeSplats:a,displayed:r}),this.sortingCheck=!1}updateDisplay({accumulator:e,viewToWorld:t,ordering:n,activeSplats:r,displayed:i=!1}){if(this.display){i||e===this.display.accumulator||(e.refCount+=1,this.spark.releaseAccumulator(this.display.accumulator),this.display.accumulator=e),this.display.viewToWorld=t;const s=this.display.geometry.ordering;s.length===n.length?this.display.geometry.update(n,r):(this.display.geometry.dispose(),this.display.geometry=new En(n,r)),this.orderingFreelist.free(s)}else e.refCount+=1,this.display={accumulator:e,viewToWorld:t,geometry:new En(n,r)};this.spark.viewpoint===this&&this.spark.prepareViewpoint(this)}static makeSorter(){if(!e.dynos){const t=new ws({value:!0}),n=new _s({value:new r.Vector3}),i=new _s({value:new r.Vector3}),s=new Ss({value:1}),a=new ws({value:!1}),o=new go,l=new Ca,c=qr({index:"int"},{rgba8:"vec4"},(({index:e})=>{if(!e)throw new Error("No index");const r={sortRadial:t,sortOrigin:n,sortDirection:i,sortDepthBias:s,sort360:a},l=zs(e,Br("int",2)),c=(({vector:e,vectorType:t,x:n,y:r,z:i,w:s,r:a,g:o,b:l,a:c})=>new Ws({vector:e,vectorType:t,x:n,y:r,z:i,w:s,r:a,g:o,b:l,a:c}))({vectorType:"vec2",x:_o({gsplat:Vi(o,l),...r}),y:_o({gsplat:Vi(o,Us(l,Br("int",1))),...r})});return{rgba8:Ns(new Gs({value:c}))}})),u=qr({index:"int"},{rgba8:"vec4"},(({index:e})=>{if(!e)throw new Error("No index");const r={sortRadial:t,sortOrigin:n,sortDirection:i,sortDepthBias:s,sort360:a},l=_o({gsplat:Vi(o,e),...r});return{rgba8:Ns(new $s({value:l}))}}));e.dynos={dynoSortRadial:t,dynoOrigin:n,dynoDirection:i,dynoDepthBias:s,dynoSort360:a,dynoSplats:o,reader:l,doubleSortReader:c,sort32Reader:u}}return e.dynos}};wo.EMPTY_TEXTURE=new r.Texture,wo.dynos=null;let To=wo;const So=Xr("\n float computeSort(Gsplat gsplat, bool sortRadial, vec3 sortOrigin, vec3 sortDirection, float sortDepthBias, bool sort360) {\n if (!isGsplatActive(gsplat.flags)) {\n return INFINITY;\n }\n\n vec3 center = gsplat.center - sortOrigin;\n float biasedDepth = dot(center, sortDirection) + sortDepthBias;\n if (!sort360 && (biasedDepth <= 0.0)) {\n return INFINITY;\n }\n\n return sortRadial ? length(center) : biasedDepth;\n }\n");function _o({gsplat:e,sortRadial:t,sortOrigin:n,sortDirection:r,sortDepthBias:i,sort360:s}){return Hr({inTypes:{gsplat:Ui,sortRadial:"bool",sortOrigin:"vec3",sortDirection:"vec3",sortDepthBias:"float",sort360:"bool"},outTypes:{metric:"float"},globals:()=>[ji,So],inputs:{gsplat:e,sortRadial:t,sortOrigin:n,sortDirection:r,sortDepthBias:i,sort360:s},statements:({inputs:e,outputs:t})=>{const{gsplat:n,sortRadial:r,sortOrigin:i,sortDirection:s,sortDepthBias:a,sort360:o}=e;return Wr(`\n ${t.metric} = computeSort(${n}, ${r}, ${i}, ${s}, ${a}, ${o});\n `)}}).outputs.metric}class Mo{constructor(){this.splats=new fo,this.toWorld=new r.Matrix4,this.mapping=[],this.refCount=0,this.splatsVersion=-1,this.mappingVersion=-1}ensureGenerate(e){this.splats.ensureGenerate(e)&&(this.mapping=[])}generateSplats({renderer:e,modifier:t,generators:n,forceUpdate:r,originToWorld:i}){const s=this.mapping.reduce(((e,t)=>(e.set(t.node,t),e)),new Map);let a=0,o=0;for(const{node:c,generator:u,version:h,base:d,count:p}of n){const n=s.get(c);if((r||u!==(null==n?void 0:n.generator)||h!==(null==n?void 0:n.version)||d!==(null==n?void 0:n.base)||p!==(null==n?void 0:n.count))&&u&&p>0){const n=t.apply(u);try{this.splats.generate({generator:n,base:d,count:p,renderer:e})}catch(l){c.generator=void 0,c.generatorError=l}a+=1}o=Math.max(o,d+p)}return this.splats.numSplats=o,this.toWorld.copy(i),this.mapping=n,0!==a}hasCorrespondence(e){return this.mapping.length===e.mapping.length&&this.mapping.every((({node:t,base:n,count:r},i)=>{const{node:s,base:a,count:o}=e.mapping[i];return t===s&&n===a&&r===o}))}}const Ao=class e extends r.Mesh{constructor(t){const n=e.makeUniforms(),i=Aa(),s=t.premultipliedAlpha??!0,a=new r.ShaderMaterial({glslVersion:r.GLSL3,vertexShader:i.oldSplatVertex,fragmentShader:i.oldSplatFragment,uniforms:n,premultipliedAlpha:s,transparent:!0,depthTest:!0,depthWrite:!1,side:r.DoubleSide});super(Eo,a),this.splatTexture=null,this.autoViewpoints=[],this.rotateToAccumulator=new Ms({value:new r.Quaternion}),this.translateToAccumulator=new _s({value:new r.Vector3}),this.lastFrame=-1,this.lastUpdateTime=null,this.defaultCameras=[],this.lastStochastic=null,this.pendingUpdate={scene:null,originToWorld:new r.Matrix4,timeoutId:-1},this.envViewpoint=null,this.frustumCulled=!1,this.renderer=t.renderer,this.material=a,this.uniforms=n;const o=qr({gsplat:Ui},{gsplat:Ui},(({gsplat:e})=>{if(!e)throw new Error("gsplat not defined");return{gsplat:e=Gi(e,{rotate:this.rotateToAccumulator,translate:this.translateToAccumulator})}}));this.modifier=new Ga(o),this.premultipliedAlpha=s,this.autoUpdate=t.autoUpdate??!0,this.preUpdate=t.preUpdate??!1,this.needsUpdate=!1,this.originDistance=t.originDistance??1,this.maxStdDev=t.maxStdDev??Math.sqrt(8),this.minPixelRadius=t.minPixelRadius??0,this.maxPixelRadius=t.maxPixelRadius??512,this.minAlpha=t.minAlpha??1/255*.5,this.enable2DGS=t.enable2DGS??!1,this.preBlurAmount=t.preBlurAmount??0,this.blurAmount=t.blurAmount??.3,this.focalDistance=t.focalDistance??0,this.apertureAngle=t.apertureAngle??0,this.falloff=t.falloff??1,this.clipXY=t.clipXY??1.4,this.focalAdjustment=t.focalAdjustment??1,this.splatEncoding=t.splatEncoding??{...Sr},this.active=new Mo,this.active.refCount=1,this.accumulatorCount=1,this.freeAccumulators=[];for(let e=0;e<1;++e)this.freeAccumulators.push(new Mo),this.accumulatorCount+=1;this.defaultView=new To({...t.view,autoUpdate:!0,spark:this}),this.viewpoint=this.defaultView,this.prepareViewpoint(this.viewpoint),this.clock=t.clock?vi(t.clock):new r.Clock}static makeUniforms(){return{renderSize:{value:new r.Vector2},near:{value:.1},far:{value:1e3},numSplats:{value:0},renderToViewQuat:{value:new r.Quaternion},renderToViewPos:{value:new r.Vector3},maxStdDev:{value:1},minPixelRadius:{value:0},maxPixelRadius:{value:512},minAlpha:{value:1/255*.5},stochastic:{value:!1},enable2DGS:{value:!1},preBlurAmount:{value:0},blurAmount:{value:.3},focalDistance:{value:0},apertureAngle:{value:0},falloff:{value:1},clipXY:{value:1.4},focalAdjustment:{value:1},splatTexEnable:{value:!1},splatTexture:{type:"t",value:e.EMPTY_SPLAT_TEXTURE},splatTexMul:{value:new r.Matrix2},splatTexAdd:{value:new r.Vector2},splatTexNear:{value:.1},splatTexFar:{value:1e3},splatTexMid:{value:0},packedSplats:{type:"t",value:fo.getEmptyArray},rgbMinMaxLnScaleMinMax:{value:new r.Vector4},time:{value:0},deltaTime:{value:0},encodeLinear:{value:!1},debugFlag:{value:!1}}}canAllocAccumulator(){return this.freeAccumulators.length>0||this.accumulatorCount<5}maybeAllocAccumulator(){let e=this.freeAccumulators.pop();if(void 0===e){if(this.accumulatorCount>=5)return null;e=new Mo,this.accumulatorCount+=1}return e.refCount=1,e}releaseAccumulator(e){e.refCount-=1,0===e.refCount&&this.freeAccumulators.push(e)}newViewpoint(e){return new To({...e,spark:this})}onBeforeRender(t,n,i){var s,a;const o=this.time??this.clock.getElapsedTime(),l=o-(this.viewpoint.lastTime??o);this.viewpoint.lastTime=o;const c=t.info.render.frame,u=c!==this.lastFrame;this.lastFrame=c;const h=this.viewpoint;if(h===this.defaultView){if(u)if(t.xr.isPresenting){const e=t.xr.getCamera().cameras;this.defaultCameras=e.map((e=>e.matrixWorld)),this.defaultView.viewToWorld=function(e){if(0===e.length)return null;const t=new r.Vector3,n=new r.Quaternion,i=new r.Vector3,s=[],a=[];for(const r of e)r.decompose(t,n,i),s.push(t),a.push(n);return(new r.Matrix4).compose(function(e){const t=new r.Vector3;for(const n of e)t.add(n);return t.divideScalar(e.length)}(s),function(e){if(0===e.length)return new r.Quaternion;const t=e[0].clone();for(let n=1;n<e.length;n++)e[n].dot(e[0])<0?(t.x-=e[n].x,t.y-=e[n].y,t.z-=e[n].z,t.w-=e[n].w):(t.x+=e[n].x,t.y+=e[n].y,t.z+=e[n].z,t.w+=e[n].w);return t.normalize()}(a),new r.Vector3(1,1,1))}(this.defaultCameras)??new r.Matrix4}else this.defaultView.viewToWorld=i.matrixWorld.clone(),this.defaultCameras=[this.defaultView.viewToWorld];this.autoUpdate&&this.update({scene:n,viewToWorld:this.defaultView.viewToWorld})}if(u&&(this.material.premultipliedAlpha!==this.premultipliedAlpha&&(this.material.premultipliedAlpha=this.premultipliedAlpha,this.material.needsUpdate=!0),this.uniforms.time.value=o,this.uniforms.deltaTime.value=l,this.uniforms.debugFlag.value=performance.now()/1e3%2<1,h.display&&h.stochastic&&(this.geometry.instanceCount=this.uniforms.numSplats.value)),h.target)this.uniforms.renderSize.value.set(h.target.width,h.target.height);else{const e=t.getDrawingBufferSize(this.uniforms.renderSize.value);if(1===e.x&&1===e.y){const n=null==(s=t.xr.getSession())?void 0:s.renderState.baseLayer;n&&(e.x=n.framebufferWidth,e.y=n.framebufferHeight)}}const d=i;if(this.uniforms.near.value=d.near,this.uniforms.far.value=d.far,this.uniforms.encodeLinear.value=h.encodeLinear,this.uniforms.maxStdDev.value=this.maxStdDev,this.uniforms.minPixelRadius.value=this.minPixelRadius,this.uniforms.maxPixelRadius.value=this.maxPixelRadius,this.uniforms.minAlpha.value=this.minAlpha,this.uniforms.stochastic.value=h.stochastic,this.uniforms.enable2DGS.value=this.enable2DGS,this.uniforms.preBlurAmount.value=this.preBlurAmount,this.uniforms.blurAmount.value=this.blurAmount,this.uniforms.focalDistance.value=this.focalDistance,this.uniforms.apertureAngle.value=this.apertureAngle,this.uniforms.falloff.value=this.falloff,this.uniforms.clipXY.value=this.clipXY,this.uniforms.focalAdjustment.value=this.focalAdjustment,this.lastStochastic!==!h.stochastic&&(this.lastStochastic=!h.stochastic,this.material.transparent=!h.stochastic,this.material.depthWrite=h.stochastic,this.material.needsUpdate=!0),this.splatTexture){const{enable:t,texture:n,multiply:r,add:i,near:s,far:a,mid:o}=this.splatTexture;t&&n?(this.uniforms.splatTexEnable.value=!0,this.uniforms.splatTexture.value=n,r?this.uniforms.splatTexMul.value.fromArray(r.elements):this.uniforms.splatTexMul.value.set(.5/this.maxStdDev,0,0,.5/this.maxStdDev),this.uniforms.splatTexAdd.value.set((null==i?void 0:i.x)??.5,(null==i?void 0:i.y)??.5),this.uniforms.splatTexNear.value=s??this.uniforms.near.value,this.uniforms.splatTexFar.value=a??this.uniforms.far.value,this.uniforms.splatTexMid.value=o??0):(this.uniforms.splatTexEnable.value=!1,this.uniforms.splatTexture.value=e.EMPTY_SPLAT_TEXTURE)}else this.uniforms.splatTexEnable.value=!1,this.uniforms.splatTexture.value=e.EMPTY_SPLAT_TEXTURE;const p=(null==(a=h.display)?void 0:a.accumulator.toWorld)??new r.Matrix4,m=i.matrixWorld.clone().invert();p.clone().premultiply(m).decompose(this.uniforms.renderToViewPos.value,this.uniforms.renderToViewQuat.value,new r.Vector3)}prepareViewpoint(e){var t,n,r,i;if(this.viewpoint=e??this.viewpoint,this.viewpoint.display){const{accumulator:e,geometry:s}=this.viewpoint.display;this.uniforms.numSplats.value=e.splats.numSplats,this.uniforms.packedSplats.value=e.splats.getTexture(),this.uniforms.rgbMinMaxLnScaleMinMax.value.set((null==(t=e.splats.splatEncoding)?void 0:t.rgbMin)??0,(null==(n=e.splats.splatEncoding)?void 0:n.rgbMax)??1,(null==(r=e.splats.splatEncoding)?void 0:r.lnScaleMin)??yr,(null==(i=e.splats.splatEncoding)?void 0:i.lnScaleMax)??9),this.geometry=s,this.material.transparent=!this.viewpoint.stochastic,this.material.depthWrite=this.viewpoint.stochastic,this.material.needsUpdate=!0}else this.uniforms.numSplats.value=0,this.uniforms.packedSplats.value=fo.getEmptyArray,this.geometry=Eo}update({scene:e,viewToWorld:t}){const n=this.matrixWorld;this.preUpdate?this.updateInternal({scene:e,originToWorld:n.clone(),viewToWorld:t}):(this.pendingUpdate.scene=e,this.pendingUpdate.originToWorld.copy(n),-1===this.pendingUpdate.timeoutId&&(this.pendingUpdate.timeoutId=setTimeout((()=>{const{scene:e,originToWorld:n}=this.pendingUpdate;this.pendingUpdate.scene=null,this.pendingUpdate.timeoutId=-1;if(this.updateInternal({scene:e,originToWorld:n,viewToWorld:t})){this.renderer.getContext().flush()}}),1)))}updateInternal({scene:e,originToWorld:t,viewToWorld:n}){var i;if(!this.canAllocAccumulator())return!1;t||(t=this.active.toWorld),n=n??t.clone();const s=this.time??this.clock.getElapsedTime(),a=s-(this.lastUpdateTime??s);this.lastUpdateTime=s;const o=this.active.mapping.reduce(((e,t)=>(e.set(t.node,t),e)),new Map),{generators:l,visibleGenerators:c,globalEdits:u}=this.compileScene(e);for(const r of l)null==(i=r.frameUpdate)||i.call(r,{renderer:this.renderer,object:r,time:s,deltaTime:a,viewToWorld:n,globalEdits:u});const h=new Set(c.map((e=>e.uuid)));for(const r of l){const e=o.get(r),t=r.generator&&h.has(r.uuid)?r.numSplats:0;(this.needsUpdate||r.generator!==(null==e?void 0:e.generator)||t!==(null==e?void 0:e.count))&&r.updateVersion()}const d=!wi({matrix1:t,matrix2:this.active.toWorld,maxDistance:this.originDistance}),p=this.needsUpdate||d||l.length!==o.size||l.some((e=>{var t;return e.version!==(null==(t=o.get(e))?void 0:t.version)}));this.needsUpdate=!1;let m=null;if(p){if(m=this.maybeAllocAccumulator(),!m)throw new Error("Unreachable");const e=!wi({matrix1:t,matrix2:m.toWorld,maxDistance:1e-5,minCoorient:.99999}),n=c.map(((e,t)=>{const n=o.get(e);return n?[e.version-n.version,n.base,e]:[Number.POSITIVE_INFINITY,e.version,e]})).sort(((e,t)=>e[0]!==t[0]?e[0]-t[0]:e[1]-t[1])).map((([e,t,n])=>n)),i=n.map((e=>e.numSplats)),{maxSplats:s,mapping:a}=m.splats.generateMapping(i),l=n.map(((e,t)=>{const{base:n,count:r}=a[t];return{node:e,generator:e.generator,version:e.version,base:n,count:r}}));t.clone().invert().decompose(this.translateToAccumulator.value,this.rotateToAccumulator.value,new r.Vector3),m.ensureGenerate(s),m.splats.splatEncoding={...this.splatEncoding},m.generateSplats({renderer:this.renderer,modifier:this.modifier,generators:l,forceUpdate:e,originToWorld:t}),m.splatsVersion=this.active.splatsVersion+1;const u=m.hasCorrespondence(this.active);m.mappingVersion=this.active.mappingVersion+(u?0:1),this.releaseAccumulator(this.active),this.active=m,this.prepareViewpoint()}return setTimeout((()=>{for(const e of this.autoViewpoints)e.autoPoll({accumulator:m??void 0})}),1),!0}compileScene(e){const t=[];e.traverse((e=>{e instanceof ja&&t.push(e)}));const n=[];e.traverseVisible((e=>{e instanceof ja&&n.push(e)}));const r=new Set;return e.traverseVisible((e=>{if(e instanceof za){let t=e.parent;for(;null!=t&&!(t instanceof lo);)t=t.parent;null==t&&r.add(e)}})),{generators:t,visibleGenerators:n,globalEdits:Array.from(r)}}async renderEnvMap({renderer:t,scene:n,worldCenter:i,size:s=256,near:a=.1,far:o=1e3,hideObjects:l=[],update:c=!1}){var u,h;if(this.envViewpoint||(this.envViewpoint=this.newViewpoint({sort360:!0})),!e.cubeRender||e.cubeRender.target.width!==s||e.cubeRender.near!==a||e.cubeRender.far!==o){e.cubeRender&&e.cubeRender.target.dispose();const t=new r.WebGLCubeRenderTarget(s,{format:r.RGBAFormat,generateMipmaps:!0,minFilter:r.LinearMipMapLinearFilter}),n=new r.CubeCamera(a,o,t);e.cubeRender={target:t,camera:n,near:a,far:o}}e.pmrem||(e.pmrem=new r.PMREMGenerator(t??this.renderer));const d=(new r.Matrix4).setPosition(i);await(null==(u=this.envViewpoint)?void 0:u.prepare({scene:n,viewToWorld:d,update:c}));const{target:p,camera:m}=e.cubeRender;m.position.copy(i);const f=new Map;for(const e of l)f.set(e,e.visible),e.visible=!1;this.prepareViewpoint(this.envViewpoint),m.update(t??this.renderer,n),this.prepareViewpoint(this.defaultView);for(const[e,r]of f.entries())e.visible=r;return null==(h=e.pmrem)?void 0:h.fromCubemap(p.texture).texture}recurseSetEnvMap(e,t){e.traverse((e=>{if(e instanceof r.Mesh)if(Array.isArray(e.material))for(const n of e.material)n instanceof r.MeshStandardMaterial&&(n.envMap=t);else e.material instanceof r.MeshStandardMaterial&&(e.material.envMap=t)}))}getRgba({generator:e,rgba:t}){const n=this.active.mapping.find((({node:t})=>t===e));if(!n)throw new Error("Generator not found");return(t=t??new Da).fromPackedSplats({packedSplats:this.active.splats,base:n.base,count:n.count,renderer:this.renderer}),t}async readRgba({generator:e,rgba:t}){return(t=this.getRgba({generator:e,rgba:t})).read()}};Ao.cubeRender=null,Ao.pmrem=null,Ao.EMPTY_SPLAT_TEXTURE=new r.Data3DTexture;const Eo=new En(new Uint32Array(1),0);qr({packedSplats:zi,index:"int"},{gsplat:Ui},(({packedSplats:e,index:t})=>{if(!e||!t)throw new Error("Invalid input");return{gsplat:Vi(e,t)}})),new r.Matrix4,Xr("\n struct GsplatSkinning {\n int numSplats;\n int numBones;\n usampler2DArray skinTexture;\n sampler2D boneTexture;\n };\n"),Xr("\n void applyGsplatSkinning(\n int numSplats, int numBones,\n usampler2DArray skinTexture, sampler2D boneTexture,\n int splatIndex, inout vec3 center, inout vec4 quaternion\n ) {\n if ((splatIndex < 0) || (splatIndex >= numSplats)) {\n return;\n }\n\n uvec4 skinData = texelFetch(skinTexture, splatTexCoord(splatIndex), 0);\n\n float weights[4];\n weights[0] = float(skinData.x & 0xffu) / 255.0;\n weights[1] = float(skinData.y & 0xffu) / 255.0;\n weights[2] = float(skinData.z & 0xffu) / 255.0;\n weights[3] = float(skinData.w & 0xffu) / 255.0;\n\n uint boneIndices[4];\n boneIndices[0] = (skinData.x >> 8u) & 0xffu;\n boneIndices[1] = (skinData.y >> 8u) & 0xffu;\n boneIndices[2] = (skinData.z >> 8u) & 0xffu;\n boneIndices[3] = (skinData.w >> 8u) & 0xffu;\n\n vec4 quat = vec4(0.0);\n vec4 dual = vec4(0.0);\n for (int i = 0; i < 4; i++) {\n if (weights[i] > 0.0) {\n int boneIndex = int(boneIndices[i]);\n vec4 boneQuat = vec4(0.0, 0.0, 0.0, 1.0);\n vec4 boneDual = vec4(0.0);\n if (boneIndex < numBones) {\n boneQuat = texelFetch(boneTexture, ivec2(0, boneIndex), 0);\n boneDual = texelFetch(boneTexture, ivec2(1, boneIndex), 0);\n }\n\n if ((i > 0) && (dot(quat, boneQuat) < 0.0)) {\n // Flip sign if next blend is pointing in the opposite direction\n boneQuat = -boneQuat;\n boneDual = -boneDual;\n }\n quat += weights[i] * boneQuat;\n dual += weights[i] * boneDual;\n }\n }\n\n // Normalize dual quaternion\n float norm = length(quat);\n quat /= norm;\n dual /= norm;\n vec3 translate = vec3(\n 2.0 * (-dual.w * quat.x + dual.x * quat.w - dual.y * quat.z + dual.z * quat.y),\n 2.0 * (-dual.w * quat.y + dual.x * quat.z + dual.y * quat.w - dual.z * quat.x),\n 2.0 * (-dual.w * quat.z - dual.x * quat.y + dual.y * quat.x + dual.z * quat.w)\n );\n\n center = quatVec(quat, center) + translate;\n quaternion = quatQuat(quat, quaternion);\n }\n"),Xr("\n void applyCovSplatDQSkinning(\n int numSplats, int numBones,\n usampler2DArray skinTexture, sampler2D boneTexture,\n int splatIndex, inout vec3 center, inout vec3 xxyyzz, inout vec3 xyxzyz\n ) {\n if ((splatIndex < 0) || (splatIndex >= numSplats)) {\n return;\n }\n\n uvec4 skinData = texelFetch(skinTexture, splatTexCoord(splatIndex), 0);\n\n float weights[4];\n weights[0] = float(skinData.x & 0xffu) / 255.0;\n weights[1] = float(skinData.y & 0xffu) / 255.0;\n weights[2] = float(skinData.z & 0xffu) / 255.0;\n weights[3] = float(skinData.w & 0xffu) / 255.0;\n\n uint boneIndices[4];\n boneIndices[0] = (skinData.x >> 8u) & 0xffu;\n boneIndices[1] = (skinData.y >> 8u) & 0xffu;\n boneIndices[2] = (skinData.z >> 8u) & 0xffu;\n boneIndices[3] = (skinData.w >> 8u) & 0xffu;\n\n vec4 quat = vec4(0.0);\n vec4 dual = vec4(0.0);\n for (int i = 0; i < 4; i++) {\n if (weights[i] > 0.0) {\n int boneIndex = int(boneIndices[i]);\n vec4 boneQuat = vec4(0.0, 0.0, 0.0, 1.0);\n vec4 boneDual = vec4(0.0);\n if (boneIndex < numBones) {\n boneQuat = texelFetch(boneTexture, ivec2(0, boneIndex), 0);\n boneDual = texelFetch(boneTexture, ivec2(1, boneIndex), 0);\n }\n\n if ((i > 0) && (dot(quat, boneQuat) < 0.0)) {\n // Flip sign if next blend is pointing in the opposite direction\n boneQuat = -boneQuat;\n boneDual = -boneDual;\n }\n quat += weights[i] * boneQuat;\n dual += weights[i] * boneDual;\n }\n }\n\n // Normalize dual quaternion\n float norm = length(quat);\n quat /= norm;\n dual /= norm;\n vec3 translate = vec3(\n 2.0 * (-dual.w * quat.x + dual.x * quat.w - dual.y * quat.z + dual.z * quat.y),\n 2.0 * (-dual.w * quat.y + dual.x * quat.z + dual.y * quat.w - dual.z * quat.x),\n 2.0 * (-dual.w * quat.z - dual.x * quat.y + dual.y * quat.x + dual.z * quat.w)\n );\n mat3 basis = quaternionToMatrix(quat);\n\n center = quatVec(quat, center) + translate;\n\n mat3 cov = mat3(xxyyzz.x, xyxzyz.x, xyxzyz.y, xyxzyz.x, xxyyzz.y, xyxzyz.z, xyxzyz.y, xyxzyz.z, xxyyzz.z);\n cov = basis * cov * transpose(basis);\n xxyyzz = vec3(cov[0][0], cov[1][1], cov[2][2]);\n xyxzyz = vec3(cov[0][1], cov[0][2], cov[1][2]);\n }\n"),Xr("\n void applyCovSplatLBSkinning(\n int numSplats, int numBones,\n usampler2DArray skinTexture, sampler2D boneTexture,\n int splatIndex, inout vec3 center, inout vec3 xxyyzz, inout vec3 xyxzyz\n ) {\n if ((splatIndex < 0) || (splatIndex >= numSplats)) {\n return;\n }\n\n uvec4 skinData = texelFetch(skinTexture, splatTexCoord(splatIndex), 0);\n\n float weights[4];\n weights[0] = float(skinData.x & 0xffu) / 255.0;\n weights[1] = float(skinData.y & 0xffu) / 255.0;\n weights[2] = float(skinData.z & 0xffu) / 255.0;\n weights[3] = float(skinData.w & 0xffu) / 255.0;\n\n uint boneIndices[4];\n boneIndices[0] = (skinData.x >> 8u) & 0xffu;\n boneIndices[1] = (skinData.y >> 8u) & 0xffu;\n boneIndices[2] = (skinData.z >> 8u) & 0xffu;\n boneIndices[3] = (skinData.w >> 8u) & 0xffu;\n\n mat3 basis = mat3(0.0);\n vec3 offset = vec3(0.0);\n\n for (int i = 0; i < 4; i++) {\n if (weights[i] > 0.0) {\n int boneIndex = int(boneIndices[i]);\n if (boneIndex < numBones) {\n vec4 v0 = texelFetch(boneTexture, ivec2(0, boneIndex), 0);\n vec4 v1 = texelFetch(boneTexture, ivec2(1, boneIndex), 0);\n vec4 v2 = texelFetch(boneTexture, ivec2(2, boneIndex), 0);\n basis += weights[i] * mat3(v0.x, v0.y, v0.z, v0.w, v1.x, v1.y, v1.z, v1.w, v2.x);\n offset += weights[i] * vec3(v2.y, v2.z, v2.w);\n }\n }\n }\n\n center = basis * center + offset;\n\n mat3 cov = mat3(xxyyzz.x, xyxzyz.x, xyxzyz.y, xyxzyz.x, xxyyzz.y, xyxzyz.z, xyxzyz.y, xyxzyz.z, xxyyzz.z);\n cov = basis * cov * transpose(basis);\n xxyyzz = vec3(cov[0][0], cov[1][1], cov[2][2]);\n xyxzyz = vec3(cov[0][1], cov[0][2], cov[1][2]);\n }\n"),new r.Vector3(-1,-3,1).normalize(),new r.Color(1,1,1),new r.Color(.5,.5,1),new r.Color(1,1,1),new r.Color(.25,.25,.5);var Co=(e=>(e.w="wrist",e.t0="thumb-metacarpal",e.t1="thumb-phalanx-proximal",e.t2="thumb-phalanx-distal",e.t3="thumb-tip",e.i0="index-finger-metacarpal",e.i1="index-finger-phalanx-proximal",e.i2="index-finger-phalanx-intermediate",e.i3="index-finger-phalanx-distal",e.i4="index-finger-tip",e.m0="middle-finger-metacarpal",e.m1="middle-finger-phalanx-proximal",e.m2="middle-finger-phalanx-intermediate",e.m3="middle-finger-phalanx-distal",e.m4="middle-finger-tip",e.r0="ring-finger-metacarpal",e.r1="ring-finger-phalanx-proximal",e.r2="ring-finger-phalanx-intermediate",e.r3="ring-finger-phalanx-distal",e.r4="ring-finger-tip",e.p0="pinky-finger-metacarpal",e.p1="pinky-finger-phalanx-proximal",e.p2="pinky-finger-phalanx-intermediate",e.p3="pinky-finger-phalanx-distal",e.p4="pinky-finger-tip",e))(Co||{});Object.keys(Co).length;var Ro=(e=>(e.w="wrist",e.t0="thumb-metacarpal",e.t1="thumb-phalanx-proximal",e.t2="thumb-phalanx-distal",e.t3="thumb-tip",e.i0="index-finger-metacarpal",e.i1="index-finger-phalanx-proximal",e.i2="index-finger-phalanx-intermediate",e.i3="index-finger-phalanx-distal",e.i4="index-finger-tip",e.m0="middle-finger-metacarpal",e.m1="middle-finger-phalanx-proximal",e.m2="middle-finger-phalanx-intermediate",e.m3="middle-finger-phalanx-distal",e.m4="middle-finger-tip",e.r0="ring-finger-metacarpal",e.r1="ring-finger-phalanx-proximal",e.r2="ring-finger-phalanx-intermediate",e.r3="ring-finger-phalanx-distal",e.r4="ring-finger-tip",e.p0="pinky-finger-metacarpal",e.p1="pinky-finger-phalanx-proximal",e.p2="pinky-finger-phalanx-intermediate",e.p3="pinky-finger-phalanx-distal",e.p4="pinky-finger-tip",e))(Ro||{});Object.keys(Ro).length;class Do{constructor(){this.listeners={}}addEventListener(e,t){const n=this.listeners;void 0===n[e]&&(n[e]=[]),-1===n[e].indexOf(t)&&n[e].push(t)}hasEventListener(e,t){const n=this.listeners;return void 0!==n[e]&&-1!==n[e].indexOf(t)}removeEventListener(e,t){const n=this.listeners[e];if(void 0!==n){const e=n.indexOf(t);-1!==e&&n.splice(e,1)}}dispatchEvent(e){const t=this.listeners[e.type];if(void 0!==t){e.target=this;const n=t.slice(0);for(let t=0,r=n.length;t<r;t+=1)n[t].call(this,e)}}}function ko(e){return!(!e||"object"!=typeof e)&&0===Object.keys(e).length}function Io(e,t){if(e===t)return!0;if(null===e||"object"!=typeof e||null===t||"object"!=typeof t)return!1;const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let i of n)if(!r.includes(i)||!Io(e[i],t[i]))return!1;return!0}const Po="defined",Lo="updated",Uo="deleted";class Fo extends Do{constructor(e){super(),this.initialValues={},this.values={},this.define(e)}define(e={},t=!0){const n={};for(const r in e)if(Object.hasOwnProperty.call(e,r)){const i=e[r];Object.hasOwnProperty.call(this.initialValues,r)?t&&(this.initialValues[r]=i,this.values[r]=i,n[r]=i):(this.initialValues[r]=i,this.values[r]=i,n[r]=i)}return ko(n)||this.dispatchEvent({type:Po,values:n}),n}update(e={},t={}){let n={};const r={},i=t.force||!1,s=t.dryrun||!1;for(const a in e)if(Object.hasOwnProperty.call(e,a)){let t=e[a];Object.hasOwnProperty.call(this.initialValues,a)&&(void 0===t&&(t=this.initialValues[a]),Io(this.values[a],t)&&!i||(r[a]=this.values[a],s||(this.values[a]=t),n[a]=t))}return s||ko(n)||this.dispatchEvent({type:Lo,values:this.values,changes:n,before:r}),n}get(e){let t={};if(e){Array.isArray(e)||(e=[e]);for(let n=0;n<e.length;n++){const r=e[n];Object.hasOwnProperty.call(this.values,r)&&(t[r]=this.values[r])}}else t={...this.values};return 1==e.length?t[e[0]]:t}reset(e){const t={},n={};if(e){Array.isArray(e)||(e=[e]);for(let r=0;r<e.length;r++){const i=e[r];Object.hasOwnProperty.call(this.initialValues,i)&&(n[i]=this.values[i],this.values[i]=this.initialValues[i],t[i]=this.initialValues[i])}}else for(const r in this.initialValues)Object.hasOwnProperty.call(this.initialValues,r)&&(this.values[r]=this.initialValues[r],t[r]=this.initialValues[r]);return ko(t)||this.dispatchEvent({type:Lo,values:this.values,changes:t,before:n}),t}delete(e=[]){const t={};Array.isArray(e)||(e=[e]);for(let n=0;n<e.length;n++){const r=e[n];Object.hasOwnProperty.call(this.values,r)&&(t[r]=this.values[r],delete this.values[r],delete this.initialValues[r])}return ko(t)||this.dispatchEvent({type:Uo,deleted:t}),t}clone(){const e=new Fo(this.initialValues);return e.update(this.values),e}}new Fo;class zo extends r.Mesh{constructor(){super(new r.PlaneGeometry(0,0),new Bo),this.renderOrder=1/0}onBeforeRender(e){const t=this.material.uniforms;e.getSize(t.resolution.value)}updateMatrixWorld(){this.matrixWorld.makeTranslation(this.position)}dispose(){this.geometry.dispose(),this.material.dispose()}}class Bo extends r.ShaderMaterial{constructor(){super({depthWrite:!1,depthTest:!1,transparent:!0,uniforms:{resolution:{value:new r.Vector2},size:{value:15},thickness:{value:2},opacity:{value:1}},vertexShader:"\n\n\t\t\t\tuniform float size;\n\t\t\t\tuniform float thickness;\n\t\t\t\tuniform vec2 resolution;\n\t\t\t\tvarying vec2 vUv;\n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tvUv = uv;\n\n\t\t\t\t\tfloat aspect = resolution.x / resolution.y;\n\t\t\t\t\tvec2 offset = uv * 2.0 - vec2( 1.0 );\n\t\t\t\t\toffset.y *= aspect;\n\n\t\t\t\t\tvec4 screenPoint = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n\t\t\t\t\tscreenPoint.xy += offset * ( size + thickness ) * screenPoint.w / resolution.x;\n\n\t\t\t\t\tgl_Position = screenPoint;\n\n\t\t\t\t}\n\t\t\t",fragmentShader:"\n\n\t\t\t\tuniform float size;\n\t\t\t\tuniform float thickness;\n\t\t\t\tuniform float opacity;\n\n\t\t\t\tvarying vec2 vUv;\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tfloat ht = 0.5 * thickness;\n\t\t\t\t\tfloat planeDim = size + thickness;\n\t\t\t\t\tfloat offset = ( planeDim - ht - 2.0 ) / planeDim;\n\t\t\t\t\tfloat texelThickness = ht / planeDim;\n\n\t\t\t\t\tvec2 vec = vUv * 2.0 - vec2( 1.0 );\n\t\t\t\t\tfloat dist = abs( length( vec ) - offset );\n\t\t\t\t\tfloat fw = fwidth( dist ) * 0.5;\n\t\t\t\t\tfloat a = smoothstep( texelThickness - fw, texelThickness + fw, dist );\n\n\t\t\t\t\tgl_FragColor = vec4( 1, 1, 1, opacity * ( 1.0 - a ) );\n\n\t\t\t\t}\n\t\t\t"})}}const Vo=new r.Vector2,Oo=new r.Vector2;class No{constructor(){this.domElement=null,this.buttons=0,this.pointerType=null,this.pointerOrder=[],this.previousPositions={},this.pointerPositions={},this.startPositions={},this.pointerSetThisFrame={},this.hoverPosition=new r.Vector2,this.hoverSet=!1}reset(){this.buttons=0,this.pointerType=null,this.pointerOrder=[],this.previousPositions={},this.pointerPositions={},this.startPositions={},this.pointerSetThisFrame={},this.hoverPosition=new r.Vector2,this.hoverSet=!1}updateFrame(){const{previousPositions:e,pointerPositions:t}=this;for(const n in t)e[n].copy(t[n])}setHoverEvent(e){"mouse"!==e.pointerType&&"wheel"!==e.type||(this.getAdjustedPointer(e,this.hoverPosition),this.hoverSet=!0)}getLatestPoint(e){return null!==this.pointerType?(this.getCenterPoint(e),e):this.hoverSet?(e.copy(this.hoverPosition),e):null}getAdjustedPointer(e,t){const n=(this.domElement?this.domElement:e.target).getBoundingClientRect(),r=e.clientX-n.left,i=e.clientY-n.top;t.set(r,i)}addPointer(e){const t=e.pointerId,n=new r.Vector2;this.getAdjustedPointer(e,n),this.pointerOrder.push(t),this.pointerPositions[t]=n,this.previousPositions[t]=n.clone(),this.startPositions[t]=n.clone(),1===this.getPointerCount()&&(this.pointerType=e.pointerType,this.buttons=e.buttons)}updatePointer(e){const t=e.pointerId;return t in this.pointerPositions&&(this.getAdjustedPointer(e,this.pointerPositions[t]),!0)}deletePointer(e){const t=e.pointerId,n=this.pointerOrder;n.splice(n.indexOf(t),1),delete this.pointerPositions[t],delete this.previousPositions[t],delete this.startPositions[t],0===this.getPointerCount()&&(this.buttons=0,this.pointerType=null)}getPointerCount(){return this.pointerOrder.length}getCenterPoint(e,t=this.pointerPositions){const n=this.pointerOrder;if(1===this.getPointerCount()||"mouse"===this.getPointerType()){const r=n[0];return e.copy(t[r]),e}if(2===this.getPointerCount()){const n=this.pointerOrder[0],r=this.pointerOrder[1],i=t[n],s=t[r];return e.addVectors(i,s).multiplyScalar(.5),e}return null}getPreviousCenterPoint(e){return this.getCenterPoint(e,this.previousPositions)}getStartCenterPoint(e){return this.getCenterPoint(e,this.startPositions)}getMoveDistance(){return this.getCenterPoint(Vo),this.getPreviousCenterPoint(Oo),Vo.sub(Oo).length()}getTouchPointerDistance(e=this.pointerPositions){if(this.getPointerCount()<=1||"mouse"===this.getPointerType())return 0;const{pointerOrder:t}=this,n=t[0],r=t[1],i=e[n],s=e[r];return i.distanceTo(s)}getPreviousTouchPointerDistance(){return this.getTouchPointerDistance(this.previousPositions)}getStartTouchPointerDistance(){return this.getTouchPointerDistance(this.startPositions)}getPointerType(){return this.pointerType}isPointerTouch(){return"touch"===this.getPointerType()}getPointerButtons(){return this.buttons}isLeftClicked(){return Boolean(1&this.buttons)}isRightClicked(){return Boolean(2&this.buttons)}}const $o=new r.Matrix4;function Go(e,t,n){return n.makeTranslation(-e.x,-e.y,-e.z),$o.makeRotationFromQuaternion(t),n.premultiply($o),$o.makeTranslation(e.x,e.y,e.z),n.premultiply($o),n}function qo(e,t,n){n.x=e.x/t.clientWidth*2-1,n.y=-e.y/t.clientHeight*2+1,n.isVector3&&(n.z=0)}function Ho(e,t,n){const i=e instanceof r.Ray?e:e.ray,{origin:s,direction:a}=i;s.set(t.x,t.y,-1).unproject(n),a.set(t.x,t.y,1).unproject(n).sub(s),e.isRay||(e.near=0,e.far=a.length(),e.camera=n),a.normalize()}const jo=.05,Wo=.025,Xo=new r.Matrix4,Yo=new r.Matrix4,Ko=new r.Vector3,Qo=new r.Vector3,Zo=new r.Vector3,Jo=new r.Vector3,el=new r.Vector3,tl=new r.Vector3,nl=new r.Vector3,rl=new r.Vector3,il=new r.Quaternion,sl=new r.Plane,al=new r.Vector3,ol=new r.Vector3,ll=new r.Vector3,cl=new r.Quaternion,ul=new r.Ray,hl=new r.Vector2,dl=new r.Vector2,pl=new r.Vector2,ml=new r.Vector2,fl=new r.Vector2,gl=new r.Vector2,xl={type:"change"},yl={type:"start"},vl={type:"end"};class bl extends r.EventDispatcher{get enabled(){return this._enabled}set enabled(e){e!==this.enabled&&(this._enabled=e,this.resetState(),this.pointerTracker.reset(),this.enabled||(this.dragInertia.set(0,0,0),this.rotationInertia.set(0,0)))}constructor(e=null,t=null,n=null,i=null){super(),this.isEnvironmentControls=!0,this.domElement=null,this.camera=null,this.scene=null,this.tilesRenderer=null,this._enabled=!0,this.cameraRadius=5,this.rotationSpeed=1,this.minAltitude=0,this.maxAltitude=.45*Math.PI,this.minDistance=10,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.zoomSpeed=1,this.adjustHeight=!0,this.enableDamping=!1,this.dampingFactor=.15,this.fallbackPlane=new r.Plane(new r.Vector3(0,1,0),0),this.useFallbackPlane=!0,this.scaleZoomOrientationAtEdges=!1,this.autoAdjustCameraRotation=!0,this.state=0,this.pointerTracker=new No,this.needsUpdate=!1,this.actionHeightOffset=0,this.pivotPoint=new r.Vector3,this.zoomDirectionSet=!1,this.zoomPointSet=!1,this.zoomDirection=new r.Vector3,this.zoomPoint=new r.Vector3,this.zoomDelta=0,this.rotationInertiaPivot=new r.Vector3,this.rotationInertia=new r.Vector2,this.dragInertia=new r.Vector3,this.inertiaTargetDistance=1/0,this.inertiaStableFrames=0,this.pivotMesh=new zo,this.pivotMesh.raycast=()=>{},this.pivotMesh.scale.setScalar(.25),this.raycaster=new r.Raycaster,this.raycaster.firstHitOnly=!0,this.up=new r.Vector3(0,1,0),this.clock=new r.Clock,this._detachCallback=null,this._upInitialized=!1,this._lastUsedState=0,this._zoomPointWasSet=!1,this._tilesOnChangeCallback=()=>this.zoomPointSet=!1,n&&this.attach(n),t&&this.setCamera(t),e&&this.setScene(e),i&&this.setTilesRenderer(i)}setScene(e){this.scene=e}setCamera(e){this.camera=e,this._upInitialized=!1,this.zoomDirectionSet=!1,this.zoomPointSet=!1,this.needsUpdate=!0,this.raycaster.camera=e,this.resetState()}setTilesRenderer(e){this.tilesRenderer=e,null!==this.tilesRenderer&&this.setScene(this.tilesRenderer.group)}attach(e){if(this.domElement)throw new Error("EnvironmentControls: Controls already attached to element");this.domElement=e,this.pointerTracker.domElement=e,e.style.touchAction="none";const t=e=>{this.enabled&&e.preventDefault()},n=e=>{if(!this.enabled)return;e.preventDefault();const{camera:t,raycaster:n,domElement:r,up:i,pivotMesh:s,pointerTracker:a,scene:o,pivotPoint:l,enabled:c}=this;if(a.addPointer(e),this.needsUpdate=!0,a.isPointerTouch())if(s.visible=!1,0===a.getPointerCount())r.setPointerCapture(e.pointerId);else if(a.getPointerCount()>2)return void this.resetState();a.getCenterPoint(dl),qo(dl,r,dl),Ho(n,dl,t);const u=Math.abs(n.ray.direction.dot(i));if(u<jo||u<Wo)return;const h=this._raycast(n);h&&(2===a.getPointerCount()||a.isRightClicked()||a.isLeftClicked()&&e.shiftKey?(this.setState(a.isPointerTouch()?4:2),l.copy(h.point),s.position.copy(h.point),s.visible=!a.isPointerTouch()&&c,s.updateMatrixWorld(),o.add(s)):a.isLeftClicked()&&(this.setState(1),l.copy(h.point),s.position.copy(h.point),s.updateMatrixWorld(),o.add(s)))};let r=!1;const i=e=>{const{pointerTracker:t}=this;if(!this.enabled)return;e.preventDefault();const{pivotMesh:n,enabled:i}=this;this.zoomDirectionSet=!1,this.zoomPointSet=!1,0!==this.state&&(this.needsUpdate=!0),t.setHoverEvent(e),t.updatePointer(e)&&(t.isPointerTouch()&&2===t.getPointerCount()&&(r||(r=!0,queueMicrotask((()=>{r=!1,t.getCenterPoint(fl);const e=t.getStartTouchPointerDistance(),s=t.getTouchPointerDistance(),a=s-e;if(0===this.state||4===this.state){t.getCenterPoint(fl),t.getStartCenterPoint(gl);const e=2*window.devicePixelRatio,n=fl.distanceTo(gl);(Math.abs(a)>e||n>e)&&(Math.abs(a)>n?(this.setState(3),this.zoomDirectionSet=!1):this.setState(2))}if(3===this.state){const e=t.getPreviousTouchPointerDistance();this.zoomDelta+=s-e,n.visible=!1}else 2===this.state&&(n.visible=i)})))),this.dispatchEvent(xl))},s=t=>{const{pointerTracker:n}=this;this.enabled&&0!==n.getPointerCount()&&(n.deletePointer(t),"touch"===n.getPointerType()&&0===n.getPointerCount()&&e.releasePointerCapture(t.pointerId),this.resetState(),this.needsUpdate=!0)},a=e=>{if(!this.enabled)return;e.preventDefault();const{pointerTracker:t}=this;let n;switch(t.setHoverEvent(e),t.updatePointer(e),this.dispatchEvent(yl),e.deltaMode){case 2:n=800*e.deltaY;break;case 1:n=40*e.deltaY;break;case 0:n=e.deltaY}const r=Math.sign(n),i=Math.abs(n);this.zoomDelta-=.25*r*i,this.needsUpdate=!0,this._lastUsedState=3,this.dispatchEvent(vl)},o=e=>{this.enabled&&this.resetState()};e.addEventListener("contextmenu",t),e.addEventListener("pointerdown",n),e.addEventListener("wheel",a,{passive:!1});const l=e.getRootNode();l.addEventListener("pointermove",i),l.addEventListener("pointerup",s),l.addEventListener("pointerleave",o),this._detachCallback=()=>{e.removeEventListener("contextmenu",t),e.removeEventListener("pointerdown",n),e.removeEventListener("wheel",a),l.removeEventListener("pointermove",i),l.removeEventListener("pointerup",s),l.removeEventListener("pointerleave",o)}}detach(){this.domElement=null,this._detachCallback&&(this._detachCallback(),this._detachCallback=null,this.pointerTracker.reset())}getUpDirection(e,t){t.copy(this.up)}getCameraUpDirection(e){this.getUpDirection(this.camera.position,e)}getPivotPoint(e){let t=null;3===this._lastUsedState?this._zoomPointWasSet&&(t=e.copy(this.zoomPoint)):2!==this._lastUsedState&&1!==this._lastUsedState||(t=e.copy(this.pivotPoint));const{camera:n,raycaster:r}=this;null!==t&&(Qo.copy(t).project(n),(Qo.x<-1||Qo.x>1||Qo.y<-1||Qo.y>1)&&(t=null)),Ho(r,{x:0,y:0},n);const i=this._raycast(r);return i&&(null===t||i.distance<t.distanceTo(r.ray.origin))&&(t=e.copy(i.point)),t}resetState(){0!==this.state&&this.dispatchEvent(vl),this.state=0,this.pivotMesh.removeFromParent(),this.pivotMesh.visible=this.enabled,this.actionHeightOffset=0,this.pointerTracker.reset()}setState(e=this.state,t=!0){this.state!==e&&(0===this.state&&t&&this.dispatchEvent(yl),this.pivotMesh.visible=this.enabled,this.dragInertia.set(0,0,0),this.rotationInertia.set(0,0),this.inertiaStableFrames=0,this.state=e,0!==e&&4!==e&&(this._lastUsedState=e))}update(e=Math.min(this.clock.getDelta(),.064)){if(!this.enabled||!this.camera||0===e)return;const{camera:t,cameraRadius:n,pivotPoint:r,up:i,state:s,adjustHeight:a,autoAdjustCameraRotation:o}=this;t.updateMatrixWorld(),this.getCameraUpDirection(al),this._upInitialized||(this._upInitialized=!0,this.up.copy(al)),this.zoomPointSet=!1;const l=this._inertiaNeedsUpdate(),c=this.needsUpdate||l;if(this.needsUpdate||l){const n=this.zoomDelta;this._updateZoom(),this._updatePosition(e),this._updateRotation(e),1===s||2===s?(el.set(0,0,-1).transformDirection(t.matrixWorld),this.inertiaTargetDistance=Qo.copy(r).sub(t.position).dot(el)):0===s&&this._updateInertia(e),(0!==s||0!==n||l)&&this.dispatchEvent(xl),this.needsUpdate=!1}const u=t.isOrthographicCamera?null:a&&this._getPointBelowCamera()||null;if(this.getCameraUpDirection(al),this._setFrame(al),(1===this.state||2===this.state)&&0!==this.actionHeightOffset){const{actionHeightOffset:e}=this;t.position.addScaledVector(i,-e),r.addScaledVector(i,-e),u&&(u.distance-=e)}if(this.actionHeightOffset=0,u){const e=u.distance;if(e<n){const s=n-e;t.position.addScaledVector(i,s),r.addScaledVector(i,s),this.actionHeightOffset=s}}this.pointerTracker.updateFrame(),c&&o&&(this.getCameraUpDirection(al),this._alignCameraUp(al,1),this.getCameraUpDirection(al),this._clampRotation(al))}adjustCamera(e){const{adjustHeight:t,cameraRadius:n}=this;if(e.isPerspectiveCamera){this.getUpDirection(e.position,al);const r=t&&this._getPointBelowCamera(e.position,al)||null;if(r){const t=r.distance;t<n&&e.position.addScaledVector(al,n-t)}}}dispose(){this.detach()}_updateInertia(e){const{rotationInertia:t,pivotPoint:n,dragInertia:r,enableDamping:i,dampingFactor:s,camera:a,cameraRadius:o,minDistance:l,inertiaTargetDistance:c}=this;if(!this.enableDamping||this.inertiaStableFrames>1)return r.set(0,0,0),void t.set(0,0,0);const u=Math.pow(2,-e/s),h=Math.max(a.near,o,l,c),d=25e-5;if(t.lengthSq()>0){Ho(ul,Qo.set(0,0,-1),a),ul.applyMatrix4(a.matrixWorldInverse),ul.direction.normalize(),ul.recast(-ul.direction.dot(ul.origin)).at(h/ul.direction.z,Qo),Qo.applyMatrix4(a.matrixWorld),Ho(ul,Ko.set(d,d,-1),a),ul.applyMatrix4(a.matrixWorldInverse),ul.direction.normalize(),ul.recast(-ul.direction.dot(ul.origin)).at(h/ul.direction.z,Ko),Ko.applyMatrix4(a.matrixWorld),Qo.sub(n).normalize(),Ko.sub(n).normalize();const r=Qo.angleTo(Ko)/e;t.multiplyScalar(u),(t.lengthSq()<r**2||!i)&&t.set(0,0)}if(r.lengthSq()>0){Ho(ul,Qo.set(0,0,-1),a),ul.applyMatrix4(a.matrixWorldInverse),ul.direction.normalize(),ul.recast(-ul.direction.dot(ul.origin)).at(h/ul.direction.z,Qo),Qo.applyMatrix4(a.matrixWorld),Ho(ul,Ko.set(d,d,-1),a),ul.applyMatrix4(a.matrixWorldInverse),ul.direction.normalize(),ul.recast(-ul.direction.dot(ul.origin)).at(h/ul.direction.z,Ko),Ko.applyMatrix4(a.matrixWorld);const t=Qo.distanceTo(Ko)/e;r.multiplyScalar(u),(r.lengthSq()<t**2||!i)&&r.set(0,0,0)}t.lengthSq()>0&&this._applyRotation(t.x*e,t.y*e,n),r.lengthSq()>0&&(a.position.addScaledVector(r,e),a.updateMatrixWorld())}_inertiaNeedsUpdate(){const{rotationInertia:e,dragInertia:t}=this;return 0!==e.lengthSq()||0!==t.lengthSq()}_updateZoom(){const{zoomPoint:e,zoomDirection:t,camera:n,minDistance:r,maxDistance:i,pointerTracker:s,domElement:a,minZoom:o,maxZoom:l,zoomSpeed:c,state:u}=this;let h=this.zoomDelta;if(this.zoomDelta=0,s.getLatestPoint(dl)&&(0!==h||3===u))if(this.rotationInertia.set(0,0),this.dragInertia.set(0,0,0),n.isOrthographicCamera){this._updateZoomDirection();const e=this.zoomPointSet||this._updateZoomPoint();ol.unproject(n);const t=Math.pow(.95,Math.abs(.05*h));let r=h>0?1/Math.abs(t):t;r*=c,r>1?l<n.zoom*r&&(r=1):o>n.zoom*r&&(r=1),n.zoom*=r,n.updateProjectionMatrix(),e&&(qo(dl,a,ll),ll.unproject(n),n.position.sub(ll).add(ol),n.updateMatrixWorld())}else{this._updateZoomDirection();const s=Qo.copy(t);if(this.zoomPointSet||this._updateZoomPoint()){const s=e.distanceTo(n.position);if(h<0){const e=Math.min(0,s-i);h=h*s*c*.0025,h=Math.max(h,e)}else{const e=Math.max(0,s-r);h=h*Math.max(s-r,0)*c*.0025,h=Math.min(h,e)}n.position.addScaledVector(t,h),n.updateMatrixWorld()}else{const e=this._getPointBelowCamera();if(e){const t=e.distance;s.set(0,0,-1).transformDirection(n.matrixWorld),n.position.addScaledVector(s,h*t*.01),n.updateMatrixWorld()}}}}_updateZoomDirection(){if(this.zoomDirectionSet)return;const{domElement:e,raycaster:t,camera:n,zoomDirection:r,pointerTracker:i}=this;i.getLatestPoint(dl),qo(dl,e,ol),Ho(t,ol,n),r.copy(t.ray.direction).normalize(),this.zoomDirectionSet=!0}_updateZoomPoint(){const{camera:e,zoomDirectionSet:t,zoomDirection:n,raycaster:r,zoomPoint:i,pointerTracker:s,domElement:a}=this;if(this._zoomPointWasSet=!1,!t)return!1;e.isOrthographicCamera&&s.getLatestPoint(hl)?(qo(hl,a,hl),Ho(r,hl,e)):(r.ray.origin.copy(e.position),r.ray.direction.copy(n),r.near=0,r.far=1/0);const o=this._raycast(r);return!!o&&(i.copy(o.point),this.zoomPointSet=!0,this._zoomPointWasSet=!0,!0)}_getPointBelowCamera(e=this.camera.position,t=this.up){const{raycaster:n}=this;n.ray.direction.copy(t).multiplyScalar(-1),n.ray.origin.copy(e).addScaledVector(t,1e5),n.near=0,n.far=1/0;const r=this._raycast(n);return r&&(r.distance-=1e5),r}_updatePosition(e){const{raycaster:t,camera:n,pivotPoint:r,up:i,pointerTracker:s,domElement:a,state:o,dragInertia:l}=this;if(1===o){if(s.getCenterPoint(dl),qo(dl,a,dl),sl.setFromNormalAndCoplanarPoint(i,r),Ho(t,dl,n),Math.abs(t.ray.direction.dot(i))<jo){const e=Math.acos(jo);rl.crossVectors(t.ray.direction,i).normalize(),t.ray.direction.copy(i).applyAxisAngle(rl,e).multiplyScalar(-1)}if(this.getUpDirection(r,al),Math.abs(t.ray.direction.dot(al))<Wo){const e=Math.acos(Wo);rl.crossVectors(t.ray.direction,al).normalize(),t.ray.direction.copy(al).applyAxisAngle(rl,e).multiplyScalar(-1)}t.ray.intersectPlane(sl,Qo)&&(Ko.subVectors(r,Qo),n.position.add(Ko),n.updateMatrixWorld(),Ko.multiplyScalar(1/e),s.getMoveDistance()/e<2*window.devicePixelRatio?this.inertiaStableFrames++:(l.copy(Ko),this.inertiaStableFrames=0))}}_updateRotation(e){const{pivotPoint:t,pointerTracker:n,domElement:r,state:i,rotationInertia:s}=this;2===i&&(n.getCenterPoint(dl),n.getPreviousCenterPoint(pl),ml.subVectors(dl,pl).multiplyScalar(2*Math.PI/r.clientHeight),this._applyRotation(ml.x,ml.y,t),ml.multiplyScalar(1/e),n.getMoveDistance()/e<2*window.devicePixelRatio?this.inertiaStableFrames++:(s.copy(ml),this.inertiaStableFrames=0))}_applyRotation(e,t,n){if(0===e&&0===t)return;const{camera:r,minAltitude:i,maxAltitude:s,rotationSpeed:a}=this,o=-e*a;let l,c=t*a;if(el.set(0,0,1).transformDirection(r.matrixWorld),tl.set(1,0,0).transformDirection(r.matrixWorld),this.getUpDirection(n,al),al.dot(el)>1-1e-10)l=0;else{Qo.crossVectors(al,el).normalize();l=Math.sign(Qo.dot(tl))*al.angleTo(el)}c>0?(c=Math.min(l-i,c),c=Math.max(0,c)):(c=Math.max(l-s,c),c=Math.min(0,c)),il.setFromAxisAngle(al,o),Go(n,il,Xo),r.matrixWorld.premultiply(Xo),tl.set(1,0,0).transformDirection(r.matrixWorld),il.setFromAxisAngle(tl,-c),Go(n,il,Xo),r.matrixWorld.premultiply(Xo),r.matrixWorld.decompose(r.position,r.quaternion,Qo)}_setFrame(e){const{up:t,camera:n,zoomPoint:i,zoomDirectionSet:s,zoomPointSet:a,scaleZoomOrientationAtEdges:o}=this;if(s&&(a||this._updateZoomPoint())){if(il.setFromUnitVectors(t,e),o){this.getUpDirection(i,Qo);let e=Math.max(Qo.dot(t)-.6,0)/.4;e=r.MathUtils.mapLinear(e,0,.5,0,1),e=Math.min(e,1),n.isOrthographicCamera&&(e*=.1),il.slerp(cl,1-e)}Go(i,il,Xo),n.updateMatrixWorld(),n.matrixWorld.premultiply(Xo),n.matrixWorld.decompose(n.position,n.quaternion,Qo),this.zoomDirectionSet=!1,this._updateZoomDirection()}t.copy(e),n.updateMatrixWorld()}_raycast(e){const{scene:t,useFallbackPlane:n,fallbackPlane:r}=this,i=e.intersectObject(t)[0]||null;if(i)return i;if(n){const t=r;if(e.ray.intersectPlane(t,Qo)){return{point:Qo.clone(),distance:e.ray.origin.distanceTo(Qo)}}}return null}_alignCameraUp(e,t=1){const{camera:n,state:i,pivotPoint:s,zoomPoint:a,zoomPointSet:o}=this;n.updateMatrixWorld(),el.set(0,0,-1).transformDirection(n.matrixWorld),tl.set(-1,0,0).transformDirection(n.matrixWorld);let l=r.MathUtils.mapLinear(1-Math.abs(el.dot(e)),0,.2,0,1);l=r.MathUtils.clamp(l,0,1),t*=l,nl.crossVectors(e,el),nl.lerp(tl,1-t).normalize(),il.setFromUnitVectors(tl,nl),n.quaternion.premultiply(il);let c=null;1===i||2===i?c=Zo.copy(s):o&&(c=Zo.copy(a)),c&&(Yo.copy(n.matrixWorld).invert(),Qo.copy(c).applyMatrix4(Yo),n.updateMatrixWorld(),Qo.applyMatrix4(n.matrixWorld),Jo.subVectors(c,Qo),n.position.add(Jo)),n.updateMatrixWorld()}_clampRotation(e){const{camera:t,minAltitude:n,maxAltitude:r,state:i,pivotPoint:s,zoomPoint:a,zoomPointSet:o}=this;let l,c;if(t.updateMatrixWorld(),el.set(0,0,1).transformDirection(t.matrixWorld),tl.set(1,0,0).transformDirection(t.matrixWorld),e.dot(el)>1-1e-10)l=0;else{Qo.crossVectors(e,el);l=Math.sign(Qo.dot(tl))*e.angleTo(el)}if(l>r)c=r;else{if(!(l<n))return;c=n}el.copy(e),il.setFromAxisAngle(tl,c),el.applyQuaternion(il).normalize(),Qo.crossVectors(el,tl).normalize(),Xo.makeBasis(tl,Qo,el),t.quaternion.setFromRotationMatrix(Xo);let u=null;1===i||2===i?u=Zo.copy(s):o&&(u=Zo.copy(a)),u&&(Yo.copy(t.matrixWorld).invert(),Qo.copy(u).applyMatrix4(Yo),t.updateMatrixWorld(),Qo.applyMatrix4(t.matrixWorld),Jo.subVectors(u,Qo),t.position.add(Jo)),t.updateMatrixWorld()}}const wl=new r.Spherical,Tl=new r.Vector3,Sl=new r.Vector3,_l=new r.Vector3,Ml=new r.Matrix4,Al=new r.Matrix4,El=new r.Sphere,Cl=new r.Euler,Rl=new r.Vector3,Dl=new r.Vector3,kl=new r.Vector3,Il=new r.Vector3,Pl=new r.Ray;class Ll{constructor(e=1,t=1,n=1){this.name="",this.radius=new r.Vector3(e,t,n)}intersectRay(e,t){return Ml.makeScale(...this.radius).invert(),El.center.set(0,0,0),El.radius=1,Pl.copy(e).applyMatrix4(Ml),Pl.intersectSphere(El,t)?(Ml.makeScale(...this.radius),t.applyMatrix4(Ml),t):null}getEastNorthUpFrame(e,t,n,r){return n.isMatrix4&&(r=n,n=0),this.getEastNorthUpAxes(e,t,Rl,Dl,kl),this.getCartographicToPosition(e,t,n,Il),r.makeBasis(Rl,Dl,kl).setPosition(Il)}getOrientedEastNorthUpFrame(e,t,n,r,i,s,a){return this.getObjectFrame(e,t,n,r,i,s,a,0)}getObjectFrame(e,t,n,r,i,s,a,o=2){return this.getEastNorthUpFrame(e,t,n,Ml),Cl.set(i,s,-r,"ZXY"),a.makeRotationFromEuler(Cl).premultiply(Ml),1===o?(Cl.set(Math.PI/2,0,0,"XYZ"),Al.makeRotationFromEuler(Cl),a.multiply(Al)):2===o&&(Cl.set(-Math.PI/2,0,Math.PI,"XYZ"),Al.makeRotationFromEuler(Cl),a.multiply(Al)),a}getCartographicFromObjectFrame(e,t,n=2){return 1===n?(Cl.set(-Math.PI/2,0,0,"XYZ"),Al.makeRotationFromEuler(Cl).premultiply(e)):2===n?(Cl.set(-Math.PI/2,0,Math.PI,"XYZ"),Al.makeRotationFromEuler(Cl).premultiply(e)):Al.copy(e),Il.setFromMatrixPosition(Al),this.getPositionToCartographic(Il,t),this.getEastNorthUpFrame(t.lat,t.lon,0,Ml).invert(),Al.premultiply(Ml),Cl.setFromRotationMatrix(Al,"ZXY"),t.azimuth=-Cl.z,t.elevation=Cl.x,t.roll=Cl.y,t}getEastNorthUpAxes(e,t,n,r,i,s=Il){this.getCartographicToPosition(e,t,0,s),this.getCartographicToNormal(e,t,i),n.set(-s.y,s.x,0).normalize(),r.crossVectors(i,n).normalize()}getCartographicToPosition(e,t,n,r){this.getCartographicToNormal(e,t,Tl);const i=this.radius;Sl.copy(Tl),Sl.x*=i.x**2,Sl.y*=i.y**2,Sl.z*=i.z**2;const s=Math.sqrt(Tl.dot(Sl));return Sl.divideScalar(s),r.copy(Sl).addScaledVector(Tl,n)}getPositionToCartographic(e,t){this.getPositionToSurfacePoint(e,Sl),this.getPositionToNormal(Sl,Tl);const n=_l.subVectors(e,Sl);return t.lon=Math.atan2(Tl.y,Tl.x),t.lat=Math.asin(Tl.z),t.height=Math.sign(n.dot(e))*n.length(),t}getCartographicToNormal(e,t,n){return wl.set(1,-e+Math.PI/2,t),n.setFromSpherical(wl).normalize(),function(e){const{x:t,y:n,z:r}=e;e.x=r,e.y=t,e.z=n}(n),n}getPositionToNormal(e,t){const n=this.radius;return t.copy(e),t.x/=n.x**2,t.y/=n.y**2,t.z/=n.z**2,t.normalize(),t}getPositionToSurfacePoint(e,t){const n=this.radius,r=1/n.x**2,i=1/n.y**2,s=1/n.z**2,a=e.x*e.x*r,o=e.y*e.y*i,l=e.z*e.z*s,c=a+o+l,u=Math.sqrt(1/c),h=Sl.copy(e).multiplyScalar(u);if(c<.1)return isFinite(u)?t.copy(h):null;const d=_l.set(h.x*r*2,h.y*i*2,h.z*s*2);let p,m,f,g,x,y,v,b,w,T,S,_=(1-u)*e.length()/(.5*d.length()),M=0;do{_-=M,f=1/(1+_*r),g=1/(1+_*i),x=1/(1+_*s),y=f*f,v=g*g,b=x*x,w=y*f,T=v*g,S=b*x,p=a*y+o*v+l*b-1,m=a*w*r+o*T*i+l*S*s;M=p/(-2*m)}while(Math.abs(p)>1e-12);return t.set(e.x*f,e.y*g,e.z*x)}calculateHorizonDistance(e,t){const n=this.calculateEffectiveRadius(e);return Math.sqrt(2*n*t+t**2)}calculateEffectiveRadius(e){const t=this.radius.x,n=1-this.radius.z**2/t**2,i=e*r.MathUtils.DEG2RAD,s=Math.sin(i)**2;return t/Math.sqrt(1-n*s)}getPositionElevation(e){this.getPositionToSurfacePoint(e,Sl);const t=_l.subVectors(e,Sl);return Math.sign(t.dot(e))*t.length()}closestPointToRayEstimate(e,t){return this.intersectRay(e,t)?t:(Ml.makeScale(...this.radius).invert(),Pl.copy(e).applyMatrix4(Ml),Sl.set(0,0,0),Pl.closestPointToPoint(Sl,t).normalize(),Ml.makeScale(...this.radius),t.applyMatrix4(Ml))}copy(e){return this.radius.copy(e.radius),this}clone(){return(new this.constructor).copy(this)}}function Ul(e){if(!e)return null;let t=e.length,n=e.indexOf("?"),r=e.indexOf("#");-1!==n&&(t=Math.min(t,n)),-1!==r&&(t=Math.min(t,r));let i=e.lastIndexOf(".",t),s=e.lastIndexOf("/",t),a=e.indexOf("://");return-1!==a&&a+2===s||-1===i||i<s?null:e.substring(i+1,t)||null}var Fl=(n(e=class{static setXRSession(e){e!==this.session&&(this.flushPending(),this.session=e)}static requestAnimationFrame(e){let t,{session:n,pending:r}=this,i=()=>{r.delete(t),e()};return t=n?n.requestAnimationFrame(i):requestAnimationFrame(i),r.set(t,e),t}static cancelAnimationFrame(e){let{pending:t,session:n}=this;t.delete(e),n?n.cancelAnimationFrame(e):cancelAnimationFrame(e)}static flushPending(){this.pending.forEach(((e,t)=>{e(),this.cancelAnimationFrame(t)}))}},"pending",new Map),n(e,"session",null),e),zl=2**30,Bl=class{get unloadPriorityCallback(){return this._unloadPriorityCallback}set unloadPriorityCallback(e){1===e.length?this._unloadPriorityCallback=(t,n)=>{let r=e(t),i=e(n);return r<i?-1:+(r>i)}:this._unloadPriorityCallback=e}constructor(){this.minSize=6e3,this.maxSize=8e3,this.minBytesSize=.3*zl,this.maxBytesSize=.4*zl,this.unloadPercent=.05,this.autoMarkUnused=!0,this.itemSet=new Map,this.itemList=[],this.usedSet=new Set,this.callbacks=new Map,this.unloadingHandle=-1,this.cachedBytes=0,this.bytesMap=new Map,this.loadedSet=new Set,this._unloadPriorityCallback=null;let e=this.itemSet;this.defaultPriorityCallback=t=>e.get(t)}isFull(){return this.itemSet.size>=this.maxSize||this.cachedBytes>=this.maxBytesSize}getMemoryUsage(e){return this.bytesMap.get(e)||0}setMemoryUsage(e,t){let{bytesMap:n,itemSet:r}=this;r.has(e)&&(this.cachedBytes-=n.get(e)||0,n.set(e,t),this.cachedBytes+=t)}add(e,t){let n=this.itemSet;if(n.has(e)||this.isFull())return!1;let r=this.usedSet,i=this.itemList,s=this.callbacks;return i.push(e),r.add(e),n.set(e,Date.now()),s.set(e,t),!0}has(e){return this.itemSet.has(e)}remove(e){let t=this.usedSet,n=this.itemSet,r=this.itemList,i=this.bytesMap,s=this.callbacks,a=this.loadedSet;if(n.has(e)){this.cachedBytes-=i.get(e)||0,i.delete(e),s.get(e)(e);let o=r.indexOf(e);return r.splice(o,1),t.delete(e),n.delete(e),s.delete(e),a.delete(e),!0}return!1}setLoaded(e,t){let{itemSet:n,loadedSet:r}=this;n.has(e)&&(!0===t?r.add(e):r.delete(e))}markUsed(e){let t=this.itemSet,n=this.usedSet;t.has(e)&&!n.has(e)&&(t.set(e,Date.now()),n.add(e))}markUnused(e){this.usedSet.delete(e)}markAllUnused(){this.usedSet.clear()}isUsed(e){return this.usedSet.has(e)}unloadUnusedContent(){let{unloadPercent:e,minSize:t,maxSize:n,itemList:r,itemSet:i,usedSet:s,loadedSet:a,callbacks:o,bytesMap:l,minBytesSize:c,maxBytesSize:u}=this,h=r.length-s.size,d=r.length-a.size,p=Math.max(Math.min(r.length-t,h),0),m=this.cachedBytes-c,f=this.unloadPriorityCallback||this.defaultPriorityCallback,g=!1,x=p>0&&h>0||d&&r.length>n;if(h&&this.cachedBytes>c||d&&this.cachedBytes>u||x){r.sort(((e,t)=>{let n=s.has(e);if(n===s.has(t)){let n=a.has(e);return n===a.has(t)?-f(e,t):n?1:-1}return n?1:-1}));let d=Math.max(t*e,p*e),x=Math.ceil(Math.min(d,h,p)),y=Math.max(e*m,e*c),v=Math.min(y,m),b=0,w=0;for(;this.cachedBytes-w>u||r.length-b>n;){let e=r[b],t=l.get(e)||0;if(s.has(e)&&a.has(e)||this.cachedBytes-w-t<u&&r.length-b<=n)break;w+=t,b++}for(;w<v||b<x;){let e=r[b],t=l.get(e)||0;if(s.has(e)||this.cachedBytes-w-t<c&&b>=x)break;w+=t,b++}r.splice(0,b).forEach((e=>{this.cachedBytes-=l.get(e)||0,o.get(e)(e),l.delete(e),i.delete(e),o.delete(e),a.delete(e),s.delete(e)})),g=b<p||w<m&&b<h,g&&(g=b>0)}g&&(this.unloadingHandle=Fl.requestAnimationFrame((()=>this.scheduleUnload())))}scheduleUnload(){Fl.cancelAnimationFrame(this.unloadingHandle),this.scheduled||(this.scheduled=!0,queueMicrotask((()=>{this.scheduled=!1,this.unloadUnusedContent()})))}},Vl=class extends DOMException{constructor(){super("PriorityQueue: Item removed","AbortError")}},Ol=class{get running(){return 0!==this.items.length||0!==this.currJobs}constructor(){this.maxJobs=6,this.items=[],this.callbacks=new Map,this.currJobs=0,this.scheduled=!1,this.autoUpdate=!0,this.priorityCallback=null,this._schedulingCallback=e=>{Fl.requestAnimationFrame(e)},this._runjobs=()=>{this.scheduled=!1,this.tryRunJobs()}}sort(){let e=this.priorityCallback,t=this.items;null!==e&&t.sort(e)}has(e){return this.callbacks.has(e)}add(e,t){let n={callback:t,reject:null,resolve:null,promise:null};return n.promise=new Promise(((t,r)=>{let i=this.items,s=this.callbacks;n.resolve=t,n.reject=r,i.unshift(e),s.set(e,n),this.autoUpdate&&this.scheduleJobRun()})),n.promise}remove(e){let t=this.items,n=this.callbacks,r=t.indexOf(e);if(-1!==r){let i=n.get(e);i.promise.catch((e=>{if("AbortError"!==e.name)throw e})),i.reject(new Vl),t.splice(r,1),n.delete(e)}}removeByFilter(e){let{items:t}=this;for(let n=0;n<t.length;n++){let r=t[n];e(r)&&(this.remove(r),n--)}}tryRunJobs(){this.sort();let e=this.items,t=this.callbacks,n=this.maxJobs,r=0,i=()=>{this.currJobs--,this.autoUpdate&&this.scheduleJobRun()};for(;n>this.currJobs&&e.length>0&&r<n;){this.currJobs++,r++;let n,a=e.pop(),{callback:o,resolve:l,reject:c}=t.get(a);t.delete(a);try{n=o(a)}catch(s){c(s),i()}n instanceof Promise?n.then(l).catch(c).finally(i):(l(n),i())}}flush(e){let{items:t,callbacks:n}=this,r=t.indexOf(e);if(!n.has(e))return;let i,{callback:s,resolve:a,reject:o}=n.get(e);n.delete(e),t.splice(r,1);try{i=s(e)}catch(l){return void o(l)}return i instanceof Promise?i.then(a).catch(o):a(i),i}scheduleJobRun(){this.scheduled||(this.scheduled=(this._schedulingCallback(this._runjobs),!0))}},Nl=6378137,$l=6356752.314245179,Gl={inView:!1,error:1/0,distanceFromCamera:1/0};function ql(e){return 4===e||-1===e}function Hl(e,t){return jl(e)&&e.traversal.lastFrameVisited===t&&e.traversal.used}function jl(e){return!!e.traversal}function Wl(e){let{children:t}=e,n=0===t.length||jl(t[t.length-1]),r=!e.internal.hasUnrenderableContent||ql(e.internal.loadingState);return n&&r}function Xl(e){return e.traversal.unconditionallyRefine}function Yl(e,t){if(jl(e)&&(t.ensureChildrenArePreprocessed(e),e.traversal.lastFrameVisited!==t.frameCount&&(e.traversal.wasInFrustum=e.traversal.inFrustum,e.traversal.wasSetActive=e.traversal.active,e.traversal.wasSetVisible=e.traversal.visible,e.traversal.usedLastFrame=e.traversal.used,e.traversal.lastFrameVisited=t.frameCount,e.traversal.used=!1,e.traversal.inFrustum=!1,e.traversal.isLeaf=!1,e.traversal.visible=!1,e.traversal.active=!1,e.traversal.error=1/0,e.traversal.distanceFromCamera=1/0,e.traversal.allChildrenReady=!1,e.traversal.allChildrenLoaded=!1,e.traversal.kicked=!1,e.traversal.allUsedChildrenProcessed=!1,t.calculateTileViewErrorWithPlugin(e,Gl),e.traversal.inFrustum=Gl.inView,e.traversal.error=Gl.error,e.traversal.distanceFromCamera=Gl.distanceFromCamera,e.traversal.unconditionallyRefine=e.internal.hasUnrenderableContent,!e.traversal.unconditionallyRefine))){let t=e.parent;for(;t&&t.traversal.unconditionallyRefine;)t=t.parent;t&&t.geometricError<=e.geometricError&&(e.traversal.unconditionallyRefine=!0)}}function Kl(e,t,n=!1){if(Yl(e,t),n?t.markTileUsed(e):Zl(e),Xl(e)&&Wl(e)){let r=e.children;for(let e=0,i=r.length;e<i;e++)Kl(r[e],t,n)}}function Ql(e,t){if(Yl(e,t),e.traversal.usedLastFrame&&(Zl(e),e.traversal.wasSetActive&&(e.traversal.active=!0),(!e.traversal.active||Xl(e))&&Wl(e))){let n=e.children;for(let e=0,r=n.length;e<r;e++)Ql(n[e],t)}}function Zl(e){e.traversal.used=!0}function Jl(e,t){let{frameCount:n}=t,{children:r}=e;for(let i=0,s=r.length;i<s;i++){let e=r[i];Hl(e,n)&&(e.traversal.active&&(e.traversal.kicked=!0,e.traversal.active=!1),Jl(e,t))}}function ec(e){return!Xl(e)&&(!e.internal.hasContent||ql(e.internal.loadingState))}function tc(e,t){if(Yl(e,t),!e.traversal.inFrustum)return;let n=e.parent;if(n&&"ADD"===n.refine&&e.geometricError>0&&e.traversal.error*(n.geometricError/e.geometricError)<=t.errorTarget)return;if(!function(e,t){return!(e.traversal.error<=t.errorTarget&&!Xl(e)||t.maxDepth>0&&e.internal.depth+1>=t.maxDepth||!Wl(e))}(e,t))return void Zl(e);let r=!1,i=!1,s=e.children;for(let a=0,o=s.length;a<o;a++){let e=s[a];tc(e,t),r||(r=Hl(e,t.frameCount)),i||(i=e.traversal.inFrustum)}if("REPLACE"!==e.refine||i||0===s.length){if(Zl(e),"REPLACE"===e.refine&&r&&(t.loadSiblings||t.loadAncestors))for(let a=0,o=s.length;a<o;a++)Kl(s[a],t)}else{e.traversal.inFrustum=!1,t.markTileUsed(e);for(let e=0,n=s.length;e<n;e++)Kl(s[e],t,!0)}}function nc(e,t){let n=t.frameCount;if(!Hl(e,n))return;let r=e.children,i=!1;for(let a=0,o=r.length;a<o;a++){let e=r[a];i||(i=Hl(e,n))}if(i){for(let e=0,n=r.length;e<n;e++)nc(r[e],t);let i=!0;for(let e=0,t=r.length;e<t;e++){let t=r[e];if(Hl(t,n)){let e=!Xl(t),n=!t.internal.hasContent||ql(t.internal.loadingState);e&&n||t.traversal.allChildrenLoaded||(i=!1)}}e.traversal.allChildrenLoaded=i}else e.traversal.isLeaf=!0;let s=!0;for(let a=0,o=r.length;a<o;a++){let e=r[a];Hl(e,t.frameCount)&&!e.traversal.allUsedChildrenProcessed&&(s=!1)}e.traversal.allUsedChildrenProcessed=s&&Wl(e)}function rc(e,t){if(!Hl(e,t.frameCount))return;let n=e.children;if("REPLACE"===e.refine&&t.loadAncestors&&!e.traversal.allChildrenLoaded&&!Xl(e)&&(e.traversal.isLeaf=!0),e.traversal.isLeaf){if(!Xl(e)&&(e.traversal.active=!0,Wl(e)&&e.internal.hasContent&&!ql(e.internal.loadingState)))for(let e=0,r=n.length;e<r;e++)Ql(n[e],t);return}let r=n.length>0;for(let i=0,s=n.length;i<s;i++){let e=n[i];rc(e,t),Hl(e,t.frameCount)&&(!e.traversal.active||!ec(e))&&!e.traversal.allChildrenReady&&(r=!1)}e.traversal.allChildrenReady=r,"REPLACE"===e.refine&&!r&&e.traversal.wasSetActive&&ec(e)&&(e.traversal.active=!0,Jl(e,t))}function ic(e,t){Yl(e,t);let n=Hl(e,t.frameCount);if(n&&(e.internal.hasUnrenderableContent&&(t.markTileUsed(e),t.queueTileForDownload(e)),e.internal.hasRenderableContent&&"ADD"===e.refine&&(e.traversal.active=!0),(e.traversal.active||e.traversal.kicked)&&e.internal.hasContent&&(t.markTileUsed(e),e.traversal.allUsedChildrenProcessed&&t.queueTileForDownload(e),4!==e.internal.loadingState&&(e.traversal.active=!1)),t.loadAncestors&&e.internal.hasContent&&(t.markTileUsed(e),t.queueTileForDownload(e)),e.internal.virtualChildCount>0&&e.internal.hasContent&&t.markTileUsed(e),e.traversal.visible=e.internal.hasRenderableContent&&e.traversal.active&&e.traversal.inFrustum&&4===e.internal.loadingState,t.stats.used++,e.traversal.inFrustum&&t.stats.inFrustum++),n||jl(e)&&e.traversal.usedLastFrame){let r=!1,i=!1;n?(r=e.traversal.active,i=t.displayActiveTiles&&e.traversal.active||e.traversal.visible):Yl(e,t),e.internal.hasRenderableContent&&4===e.internal.loadingState?(r&&t.stats.active++,i&&t.stats.visible++,e.traversal.wasSetActive!==r&&t.invokeOnePlugin((t=>t.setTileActive&&t.setTileActive(e,r))),e.traversal.wasSetVisible!==i&&t.invokeOnePlugin((t=>t.setTileVisible&&t.setTileVisible(e,i)))):e.internal.hasRenderableContent||(i=e.traversal.isLeaf,e.traversal.wasSetVisible!==i&&t.invokeOnePlugin((t=>t.setEmptyTileVisible&&t.setEmptyTileVisible(e,i)))),e.traversal.visible=i,e.traversal.active=r;let s=e.children;for(let e=0,n=s.length;e<n;e++){ic(s[e],t)}}}function sc(e,t){tc(e,t),nc(e,t),rc(e,t),ic(e,t)}function ac(e,t=null,n=null){let r=[];for(r.push(e),r.push(null),r.push(0);r.length>0;){let e=r.pop(),i=r.pop(),s=r.pop();if(t&&t(s,i,e))return void(n&&n(s,i,e));let a=s.children;if(a)for(let t=a.length-1;t>=0;t--)r.push(a[t]),r.push(s),r.push(e+1);n&&n(s,i,e)}}var oc=Symbol("PLUGIN_REGISTERED"),lc={inView:!0,error:0,distance:1/0},cc=(e,t)=>{let n=e.priority??1/0,r=t.priority??1/0;if(n!==r)return n>r?1:-1;if(!e.internal||!t.internal)return 0;let i=e.internal.renderer,s=t.internal.renderer,a=!i.loadAncestors,o=!s.loadAncestors;return a&&o?((e,t)=>e.traversal.used===t.traversal.used?e.traversal.inFrustum===t.traversal.inFrustum?e.internal.hasUnrenderableContent===t.internal.hasUnrenderableContent?e.traversal.distanceFromCamera===t.traversal.distanceFromCamera?e.internal.depthFromRenderedParent===t.internal.depthFromRenderedParent?0:e.internal.depthFromRenderedParent>t.internal.depthFromRenderedParent?-1:1:e.traversal.distanceFromCamera>t.traversal.distanceFromCamera?-1:1:e.internal.hasUnrenderableContent?1:-1:e.traversal.inFrustum?1:-1:e.traversal.used?1:-1)(e,t):((e,t)=>{let n=e.priority||0,r=t.priority||0;return n===r?e.traversal&&t.traversal?e.traversal.used===t.traversal.used?e.traversal.error===t.traversal.error?e.traversal.distanceFromCamera===t.traversal.distanceFromCamera?e.internal.depthFromRenderedParent===t.internal.depthFromRenderedParent?0:e.internal.depthFromRenderedParent>t.internal.depthFromRenderedParent?-1:1:e.traversal.distanceFromCamera>t.traversal.distanceFromCamera?-1:1:e.traversal.error>t.traversal.error?1:-1:e.traversal.used?1:-1:0:n>r?1:-1})(e,t)},uc=new Bl;uc.unloadPriorityCallback=(e,t)=>e.traversal.lastFrameVisited===t.traversal.lastFrameVisited?e.internal.depthFromRenderedParent===t.internal.depthFromRenderedParent?e.internal.loadingState===t.internal.loadingState?e.internal.hasUnrenderableContent===t.internal.hasUnrenderableContent?e.traversal.error===t.traversal.error?0:e.traversal.error>t.traversal.error?-1:1:e.internal.hasUnrenderableContent?-1:1:e.internal.loadingState>t.internal.loadingState?-1:1:e.internal.depthFromRenderedParent>t.internal.depthFromRenderedParent?1:-1:e.traversal.lastFrameVisited>t.traversal.lastFrameVisited?-1:1;var hc=new Ol;hc.maxJobs=25,hc.priorityCallback=cc;var dc=new Ol;dc.maxJobs=5,dc.priorityCallback=cc;var pc=new Ol;pc.maxJobs=25,pc.priorityCallback=(e,t)=>{let n=e.parent,r=t.parent;return n===r?0:n?r?cc(n,r):-1:1};var mc=class{get root(){let e=this.rootTileset;return e?e.root:null}get loadProgress(){let{stats:e,isLoading:t}=this,n=e.queued+e.downloading+e.parsing,r=e.inCacheSinceLoad+ +!!t;return 0===r?1:1-n/r}constructor(e=null){this.rootLoadingState=0,this.rootTileset=null,this.rootURL=e,this.fetchOptions={},this.plugins=[],this.queuedTiles=[],this.cachedSinceLoadComplete=new Set,this.isLoading=!1,this.processedTiles=new WeakSet,this.visibleTiles=new Set,this.activeTiles=new Set,this.usedSet=new Set,this.loadingTiles=new Set,this.lruCache=uc,this.downloadQueue=hc,this.parseQueue=dc,this.processNodeQueue=pc,this.stats={inCacheSinceLoad:0,inCache:0,queued:0,downloading:0,parsing:0,loaded:0,failed:0,inFrustum:0,used:0,active:0,visible:0,tilesProcessed:0},this.frameCount=0,this._dispatchNeedsUpdateEvent=function(e){let t=null;return()=>{null===t&&(t=Fl.requestAnimationFrame((()=>{t=null,e()})))}}((()=>{this.dispatchEvent({type:"needs-update"})})),this.errorTarget=16,this.displayActiveTiles=!1,this.maxDepth=1/0,this.loadSiblings=!0,this.loadAncestors=!0,this.maxTilesProcessed=250}registerPlugin(e){if(!0===e[oc])throw Error("TilesRendererBase: A plugin can only be registered to a single tileset");let t=this.plugins,n=e.priority||0,r=t.length;for(let i=0;i<t.length;i++)if((t[i].priority||0)>n){r=i;break}t.splice(r,0,e),e[oc]=!0,e.init&&e.init(this)}unregisterPlugin(e){let t=this.plugins;if("string"==typeof e&&(e=this.getPluginByName(e)),t.includes(e)){let n=t.indexOf(e);return t.splice(n,1),e.dispose&&e.dispose(),!0}return!1}getPluginByName(e){return this.plugins.find((t=>t.name===e))||null}invokeOnePlugin(e){let t=[...this.plugins,this];for(let n=0;n<t.length;n++){let r=e(t[n]);if(r)return r}return null}invokeAllPlugins(e){let t=[...this.plugins,this],n=[];for(let r=0;r<t.length;r++){let i=e(t[r]);i&&n.push(i)}return 0===n.length?null:Promise.all(n)}traverse(e,t,n=!0){this.root&&ac(this.root,((t,...r)=>(n&&this.ensureChildrenArePreprocessed(t,!0),!!e&&e(t,...r))),t)}getAttributions(e=[]){return this.invokeAllPlugins((t=>t!==this&&t.getAttributions&&t.getAttributions(e))),e}update(){let{lruCache:e,usedSet:t,stats:n,root:r,downloadQueue:i,parseQueue:s,processNodeQueue:a}=this;if(0===this.rootLoadingState&&(this.rootLoadingState=2,this.invokeOnePlugin((e=>e.loadRootTileset&&e.loadRootTileset())).then((e=>{let t=this.rootURL;null!==t&&this.invokeAllPlugins((e=>t=e.preprocessURL?e.preprocessURL(t,null):t)),this.rootLoadingState=4,this.rootTileset=e,this.dispatchEvent({type:"needs-update"}),this.dispatchEvent({type:"load-tileset",tileset:e,url:t}),this.dispatchEvent({type:"load-root-tileset",tileset:e,url:t})})).catch((e=>{this.rootLoadingState=-1,this.rootTileset=null,this.dispatchEvent({type:"load-error",tile:null,error:e,url:this.rootURL})}))),!r)return;let o=null;if(this.invokeAllPlugins((e=>{if(e.doTilesNeedUpdate){let t=e.doTilesNeedUpdate();o=null===o?t:!(!o&&!t)}})),!1===o)return this.dispatchEvent({type:"update-before"}),void this.dispatchEvent({type:"update-after"});this.dispatchEvent({type:"update-before"}),n.inFrustum=0,n.used=0,n.active=0,n.visible=0,n.tilesProcessed=0,this.frameCount++,t.forEach((t=>e.markUnused(t))),t.clear(),this.prepareForTraversal(),sc(r,this),this.removeUnusedPendingTiles();let l=this.queuedTiles;l.sort(e.unloadPriorityCallback);for(let c=0,u=l.length;c<u&&!e.isFull();c++)this.requestTileContents(l[c]);l.length=0,e.scheduleUnload(),!1===(i.running||s.running||a.running)&&!0===this.isLoading&&(this.cachedSinceLoadComplete.clear(),n.inCacheSinceLoad=0,this.dispatchEvent({type:"tiles-load-end"}),this.isLoading=!1),this.dispatchEvent({type:"update-after"})}resetFailedTiles(){-1===this.rootLoadingState&&(this.rootLoadingState=0);let e=this.stats;0!==e.failed&&(this.traverse((e=>{-1===e.internal.loadingState&&(e.internal.loadingState=0)}),null,!1),e.failed=0)}calculateTileViewErrorWithPlugin(e,t){this.calculateTileViewError(e,t);let n=null,r=0,i=1/0;this.invokeAllPlugins((t=>{t!==this&&t.calculateTileViewError&&(lc.inView=!0,lc.error=0,lc.distance=1/0,t.calculateTileViewError(e,lc)&&(null===n&&(n=!0),n&&(n=lc.inView),lc.inView&&(i=Math.min(i,lc.distance),r=Math.max(r,lc.error))))})),t.inView&&!1!==n?(t.error=Math.max(t.error,r),t.distanceFromCamera=Math.min(t.distanceFromCamera,i)):n?(t.inView=!0,t.error=r,t.distanceFromCamera=i):t.inView=!1}dispose(){[...this.plugins].forEach((e=>{this.unregisterPlugin(e)}));let e=this.lruCache,t=[];this.traverse((e=>(t.push(e),!1)),null,!1);for(let n=0,r=t.length;n<r;n++)e.remove(t[n]);this.stats={queued:0,parsing:0,downloading:0,failed:0,inFrustum:0,traversed:0,used:0,active:0,visible:0},this.frameCount=0,this.loadingTiles.clear()}calculateBytesUsed(e,t){return 0}dispatchEvent(e){}addEventListener(e,t){}removeEventListener(e,t){}parseTile(e,t,n){return null}prepareForTraversal(){}disposeTile(e){e.traversal.visible&&(e.internal.hasRenderableContent?this.invokeOnePlugin((t=>t.setTileVisible&&t.setTileVisible(e,!1))):this.invokeOnePlugin((t=>t.setEmptyTileVisible&&t.setEmptyTileVisible(e,!1))),e.traversal.visible=!1),e.traversal.active&&e.internal.hasRenderableContent&&this.invokeOnePlugin((t=>t.setTileActive&&t.setTileActive(e,!1))),e.traversal.active=!1;let{scene:t}=e.engineData;t&&this.dispatchEvent({type:"dispose-model",scene:t,tile:e})}preprocessNode(e,t,n=null){var r;if(this.processedTiles.add(e),this.stats.tilesProcessed++,e.content&&(!("uri"in e.content)&&"url"in e.content&&(e.content.uri=e.content.url,delete e.content.url),e.content.boundingVolume&&!("box"in e.content.boundingVolume||"sphere"in e.content.boundingVolume||"region"in e.content.boundingVolume)&&delete e.content.boundingVolume),e.parent=n,e.children=e.children||[],e.internal={hasContent:!1,hasRenderableContent:!1,hasUnrenderableContent:!1,loadingState:0,basePath:t,depth:-1,depthFromRenderedParent:-1,isVirtual:!1,virtualChildCount:0,renderer:this,...e.internal},null==(r=e.content)?void 0:r.uri){let t=Ul(e.content.uri),n=!(!t||!/json$/.test(t));e.internal.hasContent=!0,e.internal.hasUnrenderableContent=n,e.internal.hasRenderableContent=!n}else e.internal.hasContent=!1,e.internal.hasUnrenderableContent=!1,e.internal.hasRenderableContent=!1;n?(e.internal.depth=n.internal.depth+1,e.internal.depthFromRenderedParent=n.internal.depthFromRenderedParent+ +!!e.internal.hasRenderableContent):(e.internal.depth=0,e.internal.depthFromRenderedParent=+!!e.internal.hasRenderableContent),e.traversal={distanceFromCamera:1/0,error:1/0,inFrustum:!1,wasInFrustum:!1,isLeaf:!1,used:!1,usedLastFrame:!1,visible:!1,wasSetVisible:!1,active:!1,wasSetActive:!1,allChildrenReady:!1,allChildrenLoaded:!1,kicked:!1,allUsedChildrenProcessed:!1,lastFrameVisited:-1},e.refine=null===n?e.refine||"REPLACE":e.refine||n.refine,e.engineData={scene:null,metadata:null,boundingVolume:null},Object.defineProperty(e,"cached",{get(){return this.engineData},enumerable:!1,configurable:!0}),this.invokeAllPlugins((r=>{r!==this&&r.preprocessNode&&r.preprocessNode(e,t,n)}))}setTileActive(e,t){t?this.activeTiles.add(e):this.activeTiles.delete(e)}setTileVisible(e,t){t?this.visibleTiles.add(e):this.visibleTiles.delete(e),this.dispatchEvent({type:"tile-visibility-change",scene:e.engineData.scene,tile:e,visible:t})}calculateTileViewError(e,t){}removeUnusedPendingTiles(){let{lruCache:e,loadingTiles:t}=this,n=[];for(let r of t)!e.isUsed(r)&&1===r.internal.loadingState&&n.push(r);for(let r=0;r<n.length;r++)e.remove(n[r])}queueTileForDownload(e){0!==e.internal.loadingState||this.lruCache.isFull()||this.queuedTiles.push(e)}markTileUsed(e){this.usedSet.add(e),this.lruCache.markUsed(e)}fetchData(e,t){return fetch(e,t)}ensureChildrenArePreprocessed(e,t=this.stats.tilesProcessed<this.maxTilesProcessed){let n=e.children;if(0===n.length||n[n.length-1].traversal)return;let r=t=>{for(let n=0,r=t.length;n<r;n++){let r=t[n];r&&!r.traversal&&this.preprocessNode(r,e.internal.basePath,e)}};t?(this.processNodeQueue.remove(e),r(n)):this.processNodeQueue.has(e)||this.processNodeQueue.add(e,(e=>{r(e.children),this._dispatchNeedsUpdateEvent()}))}getBytesUsed(e){let t=0;return this.invokeAllPlugins((n=>{n.calculateBytesUsed&&(t+=n.calculateBytesUsed(e,e.engineData.scene)||0)})),t}recalculateBytesUsed(e=null){let{lruCache:t,processedTiles:n}=this;null===e?t.itemSet.forEach((e=>{n.has(e)&&t.setMemoryUsage(e,this.getBytesUsed(e))})):t.setMemoryUsage(e,this.getBytesUsed(e))}preprocessTileset(e,t,n=null){let[r,i]=e.asset.version.split(".").map((e=>parseInt(e))),s=t.replace(/\/[^/]*$/,"");s=new URL(s,window.location.href).toString(),this.preprocessNode(e.root,s,n)}loadRootTileset(){let e=this.rootURL;return this.invokeAllPlugins((t=>e=t.preprocessURL?t.preprocessURL(e,null):e)),this.invokeOnePlugin((t=>t.fetchData&&t.fetchData(e,this.fetchOptions))).then((t=>{if(!(t instanceof Response))return t;if(t.ok)return t.json();throw Error(`TilesRenderer: Failed to load tileset "${e}" with status ${t.status} : ${t.statusText}`)})).then((t=>(this.preprocessTileset(t,e),t)))}requestTileContents(e){if(0!==e.internal.loadingState)return;let t=!1,n=null,r=new URL(e.content.uri,e.internal.basePath+"/").toString();this.invokeAllPlugins((t=>r=t.preprocessURL?t.preprocessURL(r,e):r));let i=this.stats,s=this.lruCache,a=this.downloadQueue,o=this.parseQueue,l=this.loadingTiles,c=Ul(r),u=new AbortController,h=u.signal;return s.add(e,(n=>{u.abort(),t?n.children.length=0:this.invokeAllPlugins((e=>{e.disposeTile&&e.disposeTile(n)})),i.inCache--,this.cachedSinceLoadComplete.has(e)&&(this.cachedSinceLoadComplete.delete(e),i.inCacheSinceLoad--),1===n.internal.loadingState?i.queued--:2===n.internal.loadingState?i.downloading--:3===n.internal.loadingState?i.parsing--:4===n.internal.loadingState&&i.loaded--,n.internal.loadingState=0,o.remove(n),a.remove(n),l.delete(n)}))?(this.isLoading||(this.isLoading=!0,this.dispatchEvent({type:"tiles-load-start"})),s.setMemoryUsage(e,this.getBytesUsed(e)),this.cachedSinceLoadComplete.add(e),i.inCacheSinceLoad++,i.inCache++,i.queued++,e.internal.loadingState=1,l.add(e),a.add(e,(t=>{if(h.aborted)return Promise.resolve();e.internal.loadingState=2,i.downloading++,i.queued--;let n=this.invokeOnePlugin((e=>e.fetchData&&e.fetchData(r,{...this.fetchOptions,signal:h})));return this.dispatchEvent({type:"tile-download-start",tile:e,url:r,get uri(){return this.url}}),n})).then((e=>{if(!h.aborted){if(!(e instanceof Response))return e;if(e.ok)return"json"===c?e.json():e.arrayBuffer();throw Error(`Failed to load model with error code ${e.status}`)}})).then((s=>{if(!h.aborted)return i.downloading--,i.parsing++,e.internal.loadingState=3,o.add(e,(i=>h.aborted?Promise.resolve():"json"===c&&s.root?(this.preprocessTileset(s,r,e),e.children.push(s.root),n=s,t=!0,Promise.resolve()):this.invokeOnePlugin((e=>e.parseTile&&e.parseTile(s,i,c,r,h)))))})).then((()=>{if(h.aborted)return;i.parsing--,i.loaded++,e.internal.loadingState=4,l.delete(e),s.setLoaded(e,!0);let a=this.getBytesUsed(e);0===s.getMemoryUsage(e)&&a>0&&s.isFull()?s.remove(e):(s.setMemoryUsage(e,a),this.dispatchEvent({type:"needs-update"}),t&&this.dispatchEvent({type:"load-tileset",tileset:n,url:r}),e.engineData.scene&&this.dispatchEvent({type:"load-model",scene:e.engineData.scene,tile:e,url:r}))})).catch((t=>{h.aborted||("AbortError"===t.name?s.remove(e):(o.remove(e),a.remove(e),1===e.internal.loadingState?i.queued--:2===e.internal.loadingState?i.downloading--:3===e.internal.loadingState?i.parsing--:4===e.internal.loadingState&&i.loaded--,i.failed++,e.internal.loadingState=-1,l.delete(e),s.setLoaded(e,!0),this.dispatchEvent({type:"load-error",tile:e,error:t,url:r})))}))):void 0}};function fc(e){if(null===e||e.byteLength<4)return"";let t;if(t=e instanceof DataView?e:new DataView(e),"{"===String.fromCharCode(t.getUint8(0)))return null;let n="";for(let r=0;r<4;r++)n+=String.fromCharCode(t.getUint8(r));return n}var gc=new TextDecoder;function xc(e){return gc.decode(e)}function yc(e){return e.replace(/[\\/][^\\/]+$/,"")+"/"}var vc=class{constructor(){this.fetchOptions={},this.workingPath=""}loadAsync(e){return fetch(e,this.fetchOptions).then((t=>{if(!t.ok)throw Error(`Failed to load file "${e}" with status ${t.status} : ${t.statusText}`);return t.arrayBuffer()})).then((t=>(""===this.workingPath&&(this.workingPath=yc(e)),this.parse(t))))}resolveExternalURL(e){return new URL(e,this.workingPath).href}parse(e){throw Error("LoaderBase: Parse not implemented.")}};function bc(e,t,n,r,i,s){let a;switch(r){case"SCALAR":a=1;break;case"VEC2":a=2;break;case"VEC3":a=3;break;case"VEC4":a=4;break;default:throw Error(`FeatureTable : Feature type not provided for "${s}".`)}let o,l=n*a;switch(i){case"BYTE":o=new Int8Array(e,t,l);break;case"UNSIGNED_BYTE":o=new Uint8Array(e,t,l);break;case"SHORT":o=new Int16Array(e,t,l);break;case"UNSIGNED_SHORT":o=new Uint16Array(e,t,l);break;case"INT":o=new Int32Array(e,t,l);break;case"UNSIGNED_INT":o=new Uint32Array(e,t,l);break;case"FLOAT":o=new Float32Array(e,t,l);break;case"DOUBLE":o=new Float64Array(e,t,l);break;default:throw Error(`FeatureTable : Feature component type not provided for "${s}".`)}return o}var wc=class{constructor(e,t,n,r){this.buffer=e,this.binOffset=t+n,this.binLength=r;let i=null;if(0!==n){let r=new Uint8Array(e,t,n);i=JSON.parse(xc(r))}else i={};this.header=i}getKeys(){return Object.keys(this.header).filter((e=>"extensions"!==e))}getData(e,t,n=null,r=null){let i=this.header;if(!(e in i))return null;let s=i[e];if(!(s instanceof Object)||Array.isArray(s))return s;{let{buffer:i,binOffset:a,binLength:o}=this,l=s.byteOffset||0,c=s.type||r,u=s.componentType||n;if("type"in s&&r&&s.type!==r)throw Error("FeatureTable: Specified type does not match expected type.");let h=a+l,d=bc(i,h,t,c,u,e);if(h+d.byteLength>a+o)throw Error("FeatureTable: Feature data read outside binary body length.");return d}}getBuffer(e,t){let{buffer:n,binOffset:r}=this;return n.slice(r+e,r+e+t)}},Tc=class{constructor(e){this.batchTable=e;let t=e.header.extensions["3DTILES_batch_table_hierarchy"];this.classes=t.classes;for(let r of this.classes){let e=r.instances;for(let t in e)r.instances[t]=this._parseProperty(e[t],r.length,t)}if(this.instancesLength=t.instancesLength,this.classIds=this._parseProperty(t.classIds,this.instancesLength,"classIds"),t.parentCounts?this.parentCounts=this._parseProperty(t.parentCounts,this.instancesLength,"parentCounts"):this.parentCounts=Array(this.instancesLength).fill(1),t.parentIds){let e=this.parentCounts.reduce(((e,t)=>e+t),0);this.parentIds=this._parseProperty(t.parentIds,e,"parentIds")}else this.parentIds=null;this.instancesIds=[];let n={};for(let r of this.classIds)n[r]=n[r]??0,this.instancesIds.push(n[r]),n[r]++}_parseProperty(e,t,n){if(Array.isArray(e))return e;{let{buffer:r,binOffset:i}=this.batchTable;return bc(r,i+e.byteOffset,t,"SCALAR",e.componentType||"UNSIGNED_SHORT",n)}}getDataFromId(e,t={}){let n=this.parentCounts[e];if(this.parentIds&&n>0){let r=0;for(let t=0;t<e;t++)r+=this.parentCounts[t];for(let i=0;i<n;i++){let n=this.parentIds[r+i];n!==e&&this.getDataFromId(n,t)}}let r=this.classIds[e],i=this.classes[r].instances,s=this.classes[r].name,a=this.instancesIds[e];for(let o in i)t[s]=t[s]||{},t[s][o]=i[o][a];return t}},Sc=class extends wc{constructor(e,t,n,r,i){super(e,n,r,i),this.count=t,this.extensions={};let s=this.header.extensions;s&&s["3DTILES_batch_table_hierarchy"]&&(this.extensions["3DTILES_batch_table_hierarchy"]=new Tc(this))}getDataFromId(e,t={}){if(e<0||e>=this.count)throw Error(`BatchTable: id value "${e}" out of bounds for "${this.count}" features number.`);for(let n of this.getKeys())t[n]=super.getData(n,this.count)[e];for(let n in this.extensions){let r=this.extensions[n];r.getDataFromId instanceof Function&&(t[n]=t[n]||{},r.getDataFromId(e,t[n]))}return t}getPropertyArray(e){return super.getData(e,this.count)}},_c=class extends vc{parse(e){let t=new DataView(e),n=(fc(t),t.getUint32(4,!0)),r=t.getUint32(8,!0),i=t.getUint32(12,!0),s=t.getUint32(16,!0),a=t.getUint32(20,!0),o=t.getUint32(24,!0),l=new wc(e.slice(28,28+i+s),0,i,s),c=28+i+s,u=new Sc(e.slice(c,c+a+o),l.getData("BATCH_LENGTH"),0,a,o),h=c+a+o;return{version:n,featureTable:l,batchTable:u,glbBytes:new Uint8Array(e,h,r-h)}}},Mc=class extends vc{parse(e){let t=new DataView(e),n=(fc(t),t.getUint32(4,!0)),r=t.getUint32(8,!0),i=t.getUint32(12,!0),s=t.getUint32(16,!0),a=t.getUint32(20,!0),o=t.getUint32(24,!0),l=t.getUint32(28,!0),c=new wc(e.slice(32,32+i+s),0,i,s),u=32+i+s,h=new Sc(e.slice(u,u+a+o),c.getData("INSTANCES_LENGTH"),0,a,o),d=u+a+o,p=new Uint8Array(e,d,r-d),m=null,f=null,g=null;if(l)m=p,f=Promise.resolve();else{let e=this.resolveExternalURL(xc(p));g=yc(e),f=fetch(e,this.fetchOptions).then((t=>{if(!t.ok)throw Error(`I3DMLoaderBase : Failed to load file "${e}" with status ${t.status} : ${t.statusText}`);return t.arrayBuffer()})).then((e=>{m=new Uint8Array(e)}))}return f.then((()=>({version:n,featureTable:c,batchTable:h,glbBytes:m,gltfWorkingPath:g})))}},Ac=class extends vc{parse(e){let t=new DataView(e),n=(fc(t),t.getUint32(4,!0)),r=(t.getUint32(8,!0),t.getUint32(12,!0)),i=t.getUint32(16,!0),s=t.getUint32(20,!0),a=t.getUint32(24,!0),o=new wc(e.slice(28,28+r+i),0,r,i),l=28+r+i,c=new Sc(e.slice(l,l+s+a),o.getData("BATCH_LENGTH")||o.getData("POINTS_LENGTH"),0,s,a);return Promise.resolve({version:n,featureTable:o,batchTable:c})}},Ec=class extends vc{parse(e){let t=new DataView(e),n=(fc(t),t.getUint32(4,!0)),r=(t.getUint32(8,!0),t.getUint32(12,!0)),i=[],s=16;for(let a=0;a<r;a++){let t=new DataView(e,s,12),n=fc(t),r=t.getUint32(4,!0),a=t.getUint32(8,!0),o=new Uint8Array(e,s,a);i.push({type:n,buffer:o,version:r}),s+=a}return{version:n,tiles:i}}};const Cc=new Ll(Nl,Nl,$l);Cc.name="WGS84 Earth";const Rc=new r.Matrix4,Dc=new r.Matrix4,kc=new r.Vector3,Ic=new r.Vector3,Pc=new r.Vector3,Lc=new r.Vector3,Uc=new r.Vector3,Fc=new r.Vector3,zc=new r.Quaternion,Bc=new r.Vector3,Vc=new r.Vector3,Oc=new r.Ray,Nc=new Ll,$c=new r.Vector2,Gc={};class qc extends bl{get tilesGroup(){return this.ellipsoidFrame}get ellipsoidFrame(){return this.ellipsoidGroup.matrixWorld}get ellipsoidFrameInverse(){const{ellipsoidGroup:e,ellipsoidFrame:t,_ellipsoidFrameInverse:n}=this;return e.matrixWorldInverse?e.matrixWorldInverse:n.copy(t).invert()}constructor(e=null,t=null,n=null,i=null){super(e,t,n),this.isGlobeControls=!0,this._dragMode=0,this._rotationMode=0,this.maxZoom=.01,this.nearMargin=.25,this.farMargin=0,this.useFallbackPlane=!1,this.autoAdjustCameraRotation=!1,this.globeInertia=new r.Quaternion,this.globeInertiaFactor=0,this.ellipsoid=Cc.clone(),this.ellipsoidGroup=new r.Group,this._ellipsoidFrameInverse=new r.Matrix4,null!==i&&this.setTilesRenderer(i)}setTilesRenderer(e){super.setTilesRenderer(e),null!==e&&this.setEllipsoid(e.ellipsoid,e.group)}setEllipsoid(e,t){this.ellipsoid=e||Cc.clone(),this.ellipsoidGroup=t||new r.Group}getPivotPoint(e){const{camera:t,ellipsoidFrame:n,ellipsoidFrameInverse:r,ellipsoid:i}=this;return Lc.set(0,0,-1).transformDirection(t.matrixWorld),Oc.origin.copy(t.position),Oc.direction.copy(Lc),Oc.applyMatrix4(r),i.closestPointToRayEstimate(Oc,Ic).applyMatrix4(n),(null===super.getPivotPoint(e)||kc.subVectors(e,Oc.origin).dot(Oc.direction)>kc.subVectors(Ic,Oc.origin).dot(Oc.direction))&&e.copy(Ic),e}getVectorToCenter(e){const{ellipsoidFrame:t,camera:n}=this;return e.setFromMatrixPosition(t).sub(n.position)}getDistanceToCenter(){return this.getVectorToCenter(Ic).length()}getUpDirection(e,t){const{ellipsoidFrame:n,ellipsoidFrameInverse:r,ellipsoid:i}=this;Ic.copy(e).applyMatrix4(r),i.getPositionToNormal(Ic,t),t.transformDirection(n)}getCameraUpDirection(e){const{ellipsoidFrame:t,ellipsoidFrameInverse:n,ellipsoid:r,camera:i}=this;i.isOrthographicCamera?(this._getVirtualOrthoCameraPosition(Ic),Ic.applyMatrix4(n),r.getPositionToNormal(Ic,e),e.transformDirection(t)):this.getUpDirection(i.position,e)}update(e=Math.min(this.clock.getDelta(),.064)){if(!this.enabled||!this.camera||0===e)return;const{camera:t,pivotMesh:n}=this;this._isNearControls()?this.scaleZoomOrientationAtEdges=this.zoomDelta<0:(0!==this.state&&1!==this._dragMode&&1!==this._rotationMode&&(n.visible=!1),this.scaleZoomOrientationAtEdges=!1);const r=this.needsUpdate||this._inertiaNeedsUpdate();super.update(e),this.adjustCamera(t),r&&this._isNearControls()&&(this.getCameraUpDirection(Fc),this._alignCameraUp(Fc,1),this.getCameraUpDirection(Fc),this._clampRotation(Fc))}adjustCamera(e){super.adjustCamera(e);const{ellipsoidFrame:t,ellipsoidFrameInverse:n,ellipsoid:i,nearMargin:s,farMargin:a}=this,o=Math.max(...i.radius);if(e.isPerspectiveCamera){const l=Ic.setFromMatrixPosition(t).sub(e.position).length(),c=s*o,u=r.MathUtils.clamp((l-o)/c,0,1),h=r.MathUtils.lerp(1,1e3,u);e.near=Math.max(h,l-o-c),kc.copy(e.position).applyMatrix4(n),i.getPositionToCartographic(kc,Gc);const d=Math.max(i.getPositionElevation(kc),2550),p=i.calculateHorizonDistance(Gc.lat,d);e.far=p+.1+o*a,e.updateProjectionMatrix()}else{this._getVirtualOrthoCameraPosition(e.position,e),e.updateMatrixWorld(),Rc.copy(e.matrixWorld).invert(),Ic.setFromMatrixPosition(t).applyMatrix4(Rc);const n=-Ic.z;e.near=n-o*(1+s),e.far=n+.1+o*a,e.position.addScaledVector(Lc,e.near),e.far-=e.near,e.near=0,e.updateProjectionMatrix(),e.updateMatrixWorld()}}setState(...e){super.setState(...e),this._dragMode=0,this._rotationMode=0}_updateInertia(e){super._updateInertia(e);const{globeInertia:t,enableDamping:n,dampingFactor:r,camera:i,cameraRadius:s,minDistance:a,inertiaTargetDistance:o,ellipsoidFrame:l}=this;if(!this.enableDamping||this.inertiaStableFrames>1)return this.globeInertiaFactor=0,void this.globeInertia.identity();const c=Math.pow(2,-e/r),u=Math.max(i.near,s,a,o),h=25e-5;if(Pc.setFromMatrixPosition(l),0!==this.globeInertiaFactor){Ho(Oc,Ic.set(0,0,-1),i),Oc.applyMatrix4(i.matrixWorldInverse),Oc.direction.normalize(),Oc.recast(-Oc.direction.dot(Oc.origin)).at(u/Oc.direction.z,Ic),Ic.applyMatrix4(i.matrixWorld),Ho(Oc,kc.set(h,h,-1),i),Oc.applyMatrix4(i.matrixWorldInverse),Oc.direction.normalize(),Oc.recast(-Oc.direction.dot(Oc.origin)).at(u/Oc.direction.z,kc),kc.applyMatrix4(i.matrixWorld),Ic.sub(Pc).normalize(),kc.sub(Pc).normalize(),this.globeInertiaFactor*=c;const r=Ic.angleTo(kc)/e;(2*Math.acos(t.w)*this.globeInertiaFactor<r||!n)&&(this.globeInertiaFactor=0,t.identity())}0!==this.globeInertiaFactor&&(1!==t.w||0===t.x&&0===t.y&&0===t.z||(t.w=Math.min(t.w,1-1e-9)),Pc.setFromMatrixPosition(l),zc.identity().slerp(t,this.globeInertiaFactor*e),Go(Pc,zc,Dc),i.matrixWorld.premultiply(Dc),i.matrixWorld.decompose(i.position,i.quaternion,Ic))}_inertiaNeedsUpdate(){return super._inertiaNeedsUpdate()||0!==this.globeInertiaFactor}_updatePosition(e){if(1===this.state){0===this._dragMode&&(this._dragMode=this._isNearControls()?1:-1);const{raycaster:t,camera:n,pivotPoint:r,pointerTracker:i,domElement:s,ellipsoidFrame:a,ellipsoidFrameInverse:o}=this,l=kc,c=Uc;i.getCenterPoint($c),qo($c,s,$c),Ho(t,$c,n),t.ray.applyMatrix4(o);const u=Ic.copy(r).applyMatrix4(o).length();if(Nc.radius.setScalar(u),!Nc.intersectRay(t.ray,Ic))return this.resetState(),void this._updateInertia(e);Ic.applyMatrix4(a),Pc.setFromMatrixPosition(a),l.subVectors(r,Pc).normalize(),c.subVectors(Ic,Pc).normalize(),zc.setFromUnitVectors(c,l),Go(Pc,zc,Dc),n.matrixWorld.premultiply(Dc),n.matrixWorld.decompose(n.position,n.quaternion,Ic),i.getMoveDistance()/e<2*window.devicePixelRatio?this.inertiaStableFrames++:(this.globeInertia.copy(zc),this.globeInertiaFactor=1/e,this.inertiaStableFrames=0)}}_updateRotation(...e){1===this._rotationMode||this._isNearControls()?(this._rotationMode=1,super._updateRotation(...e)):(this.pivotMesh.visible=!1,this._rotationMode=-1)}_updateZoom(){const{zoomDelta:e,ellipsoid:t,zoomSpeed:n,zoomPoint:i,camera:s,maxZoom:a,state:o}=this;if(3!==o&&0===e)return;this.rotationInertia.set(0,0),this.dragInertia.set(0,0,0),this.globeInertia.identity(),this.globeInertiaFactor=0;const l=r.MathUtils.clamp(r.MathUtils.mapLinear(Math.abs(e),0,20,0,1),0,1);if(this._isNearControls()||e>0){if(this._updateZoomDirection(),e<0&&(this.zoomPointSet||this._updateZoomPoint())){Lc.set(0,0,-1).transformDirection(s.matrixWorld).normalize(),Vc.copy(this.up).multiplyScalar(-1),this.getUpDirection(i,Bc);const e=r.MathUtils.clamp(r.MathUtils.mapLinear(-Bc.dot(Vc),1,.95,0,1),0,1),t=1-Lc.dot(Vc),n=s.isOrthographicCamera?.05:1,a=r.MathUtils.clamp(3*l,0,1),o=Math.min(e*t*n*a,.1);Vc.lerpVectors(Lc,Vc,o).normalize(),zc.setFromUnitVectors(Lc,Vc),Go(i,zc,Dc),s.matrixWorld.premultiply(Dc),s.matrixWorld.decompose(s.position,s.quaternion,Vc),this.zoomDirection.subVectors(i,s.position).normalize()}super._updateZoom()}else if(s.isPerspectiveCamera){const i=this._getPerspectiveTransitionDistance(),s=this._getMaxPerspectiveDistance(),a=r.MathUtils.mapLinear(this.getDistanceToCenter(),i,s,0,1);this._tiltTowardsCenter(r.MathUtils.lerp(0,.4,a*l)),this._alignCameraUpToNorth(r.MathUtils.lerp(0,.2,a*l));const o=e*(this.getDistanceToCenter()-t.radius.x)*n*.0025,c=Math.max(o,Math.min(this.getDistanceToCenter()-s,0));this.getVectorToCenter(Ic).normalize(),this.camera.position.addScaledVector(Ic,c),this.camera.updateMatrixWorld(),this.zoomDelta=0}else{const e=this._getOrthographicTransitionZoom(),t=this._getMinOrthographicZoom(),i=r.MathUtils.mapLinear(s.zoom,e,t,0,1);this._tiltTowardsCenter(r.MathUtils.lerp(0,.4,i*l)),this._alignCameraUpToNorth(r.MathUtils.lerp(0,.2,i*l));const o=this.zoomDelta,c=Math.pow(.95,Math.abs(.05*o)),u=o>0?1/Math.abs(c):c,h=t/s.zoom,d=Math.max(u*n,Math.min(h,1));s.zoom=Math.min(a,s.zoom*d),s.updateProjectionMatrix(),this.zoomDelta=0,this.zoomDirectionSet=!1}}_alignCameraUpToNorth(e){const{ellipsoidFrame:t}=this;Fc.set(0,0,1).transformDirection(t),this._alignCameraUp(Fc,e)}_tiltTowardsCenter(e){const{camera:t,ellipsoidFrame:n}=this;Lc.set(0,0,-1).transformDirection(t.matrixWorld).normalize(),Ic.setFromMatrixPosition(n).sub(t.position).normalize(),Ic.lerp(Lc,1-e).normalize(),zc.setFromUnitVectors(Lc,Ic),t.quaternion.premultiply(zc),t.updateMatrixWorld()}_getPerspectiveTransitionDistance(){const{camera:e,ellipsoid:t}=this;if(!e.isPerspectiveCamera)throw new Error;const n=Math.max(...t.radius),i=2*Math.atan(Math.tan(r.MathUtils.DEG2RAD*e.fov*.5)*e.aspect),s=n/Math.tan(r.MathUtils.DEG2RAD*e.fov*.5),a=n/Math.tan(.5*i);return Math.max(s,a)}_getMaxPerspectiveDistance(){const{camera:e,ellipsoid:t}=this;if(!e.isPerspectiveCamera)throw new Error;const n=Math.max(...t.radius),i=2*Math.atan(Math.tan(r.MathUtils.DEG2RAD*e.fov*.5)*e.aspect),s=n/Math.tan(r.MathUtils.DEG2RAD*e.fov*.5),a=n/Math.tan(.5*i);return 2*Math.max(s,a)}_getOrthographicTransitionZoom(){const{camera:e,ellipsoid:t}=this;if(!e.isOrthographicCamera)throw new Error;const n=e.top-e.bottom,r=e.right-e.left;return 2*Math.max(n,r)/(2*Math.max(...t.radius))}_getMinOrthographicZoom(){const{camera:e,ellipsoid:t}=this;if(!e.isOrthographicCamera)throw new Error;const n=e.top-e.bottom,r=e.right-e.left;return.7*Math.min(n,r)/(2*Math.max(...t.radius))}_getVirtualOrthoCameraPosition(e,t=this.camera){const{ellipsoidFrame:n,ellipsoidFrameInverse:r,ellipsoid:i}=this;if(!t.isOrthographicCamera)throw new Error;Oc.origin.copy(t.position),Oc.direction.set(0,0,-1).transformDirection(t.matrixWorld),Oc.applyMatrix4(r),i.closestPointToRayEstimate(Oc,kc).applyMatrix4(n);const s=t.top-t.bottom,a=t.right-t.left,o=Math.max(s,a)/t.zoom;Lc.set(0,0,-1).transformDirection(t.matrixWorld);const l=kc.sub(t.position).dot(Lc);e.copy(t.position).addScaledVector(Lc,l-4*o)}_isNearControls(){const{camera:e}=this;return e.isPerspectiveCamera?this.getDistanceToCenter()<this._getPerspectiveTransitionDistance():e.zoom>this._getOrthographicTransitionZoom()}_raycast(e){const t=super._raycast(e);if(null===t){const{ellipsoid:t,ellipsoidFrame:n,ellipsoidFrameInverse:r}=this;Oc.copy(e.ray).applyMatrix4(r);const i=t.intersectRay(Oc,Ic);return null!==i?{point:i.clone().applyMatrix4(n)}:null}return t}}var Hc=class extends _c{constructor(e=r.DefaultLoadingManager){super(),this.manager=e,this.adjustmentTransform=new r.Matrix4}parse(e){let t=super.parse(e),n=t.glbBytes.slice().buffer;return new Promise(((e,r)=>{let i=this.manager,s=this.fetchOptions,a=i.getHandler("path.gltf")||new rt(i);"include"===s.credentials&&"cors"===s.mode&&a.setCrossOrigin("use-credentials"),"credentials"in s&&a.setWithCredentials("include"===s.credentials),s.headers&&a.setRequestHeader(s.headers);let o=this.workingPath;!/[\\/]$/.test(o)&&o.length&&(o+="/");let l=this.adjustmentTransform;a.parse(n,o,(n=>{let{batchTable:r,featureTable:i}=t,{scene:s}=n,a=i.getData("RTC_CENTER",1,"FLOAT","VEC3");a&&(s.position.x+=a[0],s.position.y+=a[1],s.position.z+=a[2]),n.scene.updateMatrix(),n.scene.matrix.multiply(l),n.scene.matrix.decompose(n.scene.position,n.scene.quaternion,n.scene.scale),n.batchTable=r,n.featureTable=i,s.batchTable=r,s.featureTable=i,e(n)}),r)}))}};function jc(e){let t=e>>11,n=e>>5&63,r=31&e;return[Math.round(t/31*255),Math.round(n/63*255),Math.round(r/31*255)]}var Wc=new r.Vector2;function Xc(e,t,n=new r.Vector3){Wc.set(e,t).divideScalar(256).multiplyScalar(2).subScalar(1),n.set(Wc.x,Wc.y,1-Math.abs(Wc.x)-Math.abs(Wc.y));let i=r.MathUtils.clamp(-n.z,0,1);return n.x>=0?n.setX(n.x-i):n.setX(n.x+i),n.y>=0?n.setY(n.y-i):n.setY(n.y+i),n.normalize(),n}var Yc={RGB:"color",POSITION:"position"},Kc=class extends Ac{constructor(e=r.DefaultLoadingManager){super(),this.manager=e}parse(e){return super.parse(e).then((async e=>{let t,{featureTable:n,batchTable:i}=e,s=new r.PointsMaterial,a=n.header.extensions,o=new r.Vector3;if(a&&a["3DTILES_draco_point_compression"]){let{byteOffset:e,byteLength:r,properties:i}=a["3DTILES_draco_point_compression"],o=this.manager.getHandler("draco.drc");if(null==o)throw Error("PNTSLoader: dracoLoader not available.");let l={};for(let t in i)if(t in Yc&&t in i){l[Yc[t]]=i[t]}let c={attributeIDs:l,attributeTypes:{position:"Float32Array",color:"Uint8Array"},useUniqueIDs:!0},u=n.getBuffer(e,r);t=await o.decodeGeometry(u,c),t.attributes.color&&(s.vertexColors=!0)}else{let e=n.getData("POINTS_LENGTH"),i=n.getData("POSITION",e,"FLOAT","VEC3"),a=n.getData("NORMAL",e,"FLOAT","VEC3"),l=n.getData("NORMAL",e,"UNSIGNED_BYTE","VEC2"),c=n.getData("RGB",e,"UNSIGNED_BYTE","VEC3"),u=n.getData("RGBA",e,"UNSIGNED_BYTE","VEC4"),h=n.getData("RGB565",e,"UNSIGNED_SHORT","SCALAR"),d=n.getData("CONSTANT_RGBA",e,"UNSIGNED_BYTE","VEC4"),p=n.getData("POSITION_QUANTIZED",e,"UNSIGNED_SHORT","VEC3"),m=n.getData("QUANTIZED_VOLUME_SCALE",e,"FLOAT","VEC3"),f=n.getData("QUANTIZED_VOLUME_OFFSET",e,"FLOAT","VEC3");if(t=new r.BufferGeometry,p){let n=new Float32Array(3*e);for(let t=0;t<e;t++)for(let e=0;e<3;e++){let r=3*t+e;n[r]=p[r]/65535*m[e]}o.x=f[0],o.y=f[1],o.z=f[2],t.setAttribute("position",new r.BufferAttribute(n,3,!1))}else t.setAttribute("position",new r.BufferAttribute(i,3,!1));if(null!==a)t.setAttribute("normal",new r.BufferAttribute(a,3,!1));else if(null!==l){let n=new Float32Array(3*e),i=new r.Vector3;for(let t=0;t<e;t++){let e=Xc(l[2*t],l[2*t+1],i);n[3*t]=e.x,n[3*t+1]=e.y,n[3*t+2]=e.z}t.setAttribute("normal",new r.BufferAttribute(n,3,!1))}if(null!==u)t.setAttribute("color",new r.BufferAttribute(u,4,!0)),s.vertexColors=!0,s.transparent=!0,s.depthWrite=!1;else if(null!==c)t.setAttribute("color",new r.BufferAttribute(c,3,!0)),s.vertexColors=!0;else if(null!==h){let n=new Uint8Array(3*e);for(let t=0;t<e;t++){let e=jc(h[t]);for(let r=0;r<3;r++){n[3*t+r]=e[r]}}t.setAttribute("color",new r.BufferAttribute(n,3,!0)),s.vertexColors=!0}else if(null!==d){s.color=new r.Color(d[0],d[1],d[2]);let e=d[3]/255;e<1&&(s.opacity=e,s.transparent=!0,s.depthWrite=!1)}}let l=new r.Points(t,s);l.position.copy(o),e.scene=l,e.scene.featureTable=n,e.scene.batchTable=i;let c=n.getData("RTC_CENTER",1,"FLOAT","VEC3");return c&&(e.scene.position.x+=c[0],e.scene.position.y+=c[1],e.scene.position.z+=c[2]),e}))}};var Qc=new r.Spherical,Zc=new r.Vector3,Jc=new r.Vector3,eu=new r.Vector3,tu=new r.Matrix4,nu=new r.Matrix4,ru=new r.Sphere,iu=new r.Euler,su=new r.Vector3,au=new r.Vector3,ou=new r.Vector3,lu=new r.Vector3,cu=new r.Ray,uu=class{constructor(e=1,t=1,n=1){this.name="",this.radius=new r.Vector3(e,t,n)}intersectRay(e,t){return tu.makeScale(...this.radius).invert(),ru.center.set(0,0,0),ru.radius=1,cu.copy(e).applyMatrix4(tu),cu.intersectSphere(ru,t)?(tu.makeScale(...this.radius),t.applyMatrix4(tu),t):null}getEastNorthUpFrame(e,t,n,r){return n.isMatrix4&&(r=n,n=0),this.getEastNorthUpAxes(e,t,su,au,ou),this.getCartographicToPosition(e,t,n,lu),r.makeBasis(su,au,ou).setPosition(lu)}getOrientedEastNorthUpFrame(e,t,n,r,i,s,a){return this.getObjectFrame(e,t,n,r,i,s,a,0)}getObjectFrame(e,t,n,r,i,s,a,o=2){return this.getEastNorthUpFrame(e,t,n,tu),iu.set(i,s,-r,"ZXY"),a.makeRotationFromEuler(iu).premultiply(tu),1===o?(iu.set(Math.PI/2,0,0,"XYZ"),nu.makeRotationFromEuler(iu),a.multiply(nu)):2===o&&(iu.set(-Math.PI/2,0,Math.PI,"XYZ"),nu.makeRotationFromEuler(iu),a.multiply(nu)),a}getCartographicFromObjectFrame(e,t,n=2){return 1===n?(iu.set(-Math.PI/2,0,0,"XYZ"),nu.makeRotationFromEuler(iu).premultiply(e)):2===n?(iu.set(-Math.PI/2,0,Math.PI,"XYZ"),nu.makeRotationFromEuler(iu).premultiply(e)):nu.copy(e),lu.setFromMatrixPosition(nu),this.getPositionToCartographic(lu,t),this.getEastNorthUpFrame(t.lat,t.lon,0,tu).invert(),nu.premultiply(tu),iu.setFromRotationMatrix(nu,"ZXY"),t.azimuth=-iu.z,t.elevation=iu.x,t.roll=iu.y,t}getEastNorthUpAxes(e,t,n,r,i,s=lu){this.getCartographicToPosition(e,t,0,s),this.getCartographicToNormal(e,t,i),n.set(-s.y,s.x,0).normalize(),r.crossVectors(i,n).normalize()}getCartographicToPosition(e,t,n,r){this.getCartographicToNormal(e,t,Zc);let i=this.radius;Jc.copy(Zc),Jc.x*=i.x**2,Jc.y*=i.y**2,Jc.z*=i.z**2;let s=Math.sqrt(Zc.dot(Jc));return Jc.divideScalar(s),r.copy(Jc).addScaledVector(Zc,n)}getPositionToCartographic(e,t){this.getPositionToSurfacePoint(e,Jc),this.getPositionToNormal(Jc,Zc);let n=eu.subVectors(e,Jc);return t.lon=Math.atan2(Zc.y,Zc.x),t.lat=Math.asin(Zc.z),t.height=Math.sign(n.dot(e))*n.length(),t}getCartographicToNormal(e,t,n){return Qc.set(1,function(e){return-e+Math.PI/2}(e),t),n.setFromSpherical(Qc).normalize(),function(e){let{x:t,y:n,z:r}=e;e.x=r,e.y=t,e.z=n}(n),n}getPositionToNormal(e,t){let n=this.radius;return t.copy(e),t.x/=n.x**2,t.y/=n.y**2,t.z/=n.z**2,t.normalize(),t}getPositionToSurfacePoint(e,t){let n=this.radius,r=1/n.x**2,i=1/n.y**2,s=1/n.z**2,a=e.x*e.x*r,o=e.y*e.y*i,l=e.z*e.z*s,c=a+o+l,u=Math.sqrt(1/c),h=Jc.copy(e).multiplyScalar(u);if(c<.1)return isFinite(u)?t.copy(h):null;let d,p,m,f,g,x,y,v,b,w,T,S=eu.set(h.x*r*2,h.y*i*2,h.z*s*2),_=(1-u)*e.length()/(.5*S.length()),M=0;do{_-=M,m=1/(1+_*r),f=1/(1+_*i),g=1/(1+_*s),x=m*m,y=f*f,v=g*g,b=x*m,w=y*f,T=v*g,d=a*x+o*y+l*v-1,p=a*b*r+o*w*i+l*T*s,M=d/(-2*p)}while(Math.abs(d)>1e-12);return t.set(e.x*m,e.y*f,e.z*g)}calculateHorizonDistance(e,t){let n=this.calculateEffectiveRadius(e);return Math.sqrt(2*n*t+t**2)}calculateEffectiveRadius(e){let t=this.radius.x,n=1-this.radius.z**2/t**2,i=e*r.MathUtils.DEG2RAD,s=Math.sin(i)**2;return t/Math.sqrt(1-n*s)}getPositionElevation(e){this.getPositionToSurfacePoint(e,Jc);let t=eu.subVectors(e,Jc);return Math.sign(t.dot(e))*t.length()}closestPointToRayEstimate(e,t){return this.intersectRay(e,t)?t:(tu.makeScale(...this.radius).invert(),cu.copy(e).applyMatrix4(tu),Jc.set(0,0,0),cu.closestPointToPoint(Jc,t).normalize(),tu.makeScale(...this.radius),t.applyMatrix4(tu))}copy(e){return this.radius.copy(e.radius),this}clone(){return(new this.constructor).copy(this)}},hu=new uu(Nl,Nl,$l);hu.name="WGS84 Earth";var du=new r.Vector3,pu=new r.Vector3,mu=new r.Vector3,fu=new r.Vector3,gu=new r.Quaternion,xu=new r.Vector3,yu=new r.Matrix4,vu=new r.Matrix4,bu=new r.Vector3,wu=new r.Matrix4,Tu=new r.Quaternion,Su={};function _u(e,t,n,r){if(e=e/n*2-1,t=t/n*2-1,r.x=e,r.y=t,r.z=1-Math.abs(e)-Math.abs(t),r.z<0){let e=r.x;r.x=(1-Math.abs(r.y))*(e>=0?1:-1),r.y=(1-Math.abs(e))*(r.y>=0?1:-1)}return r.normalize(),r}var Mu=class extends Mc{constructor(e=r.DefaultLoadingManager){super(),this.manager=e,this.adjustmentTransform=new r.Matrix4,this.ellipsoid=hu.clone()}resolveExternalURL(e){return this.manager.resolveURL(super.resolveExternalURL(e))}parse(e){return super.parse(e).then((e=>{let{featureTable:t,batchTable:n}=e,i=e.glbBytes.slice().buffer;return new Promise(((s,a)=>{let o=this.fetchOptions,l=this.manager,c=l.getHandler("path.gltf")||new rt(l);"include"===o.credentials&&"cors"===o.mode&&c.setCrossOrigin("use-credentials"),"credentials"in o&&c.setWithCredentials("include"===o.credentials),o.headers&&c.setRequestHeader(o.headers);let u=e.gltfWorkingPath??this.workingPath;/[\\/]$/.test(u)||(u+="/");let h=this.adjustmentTransform;c.parse(i,u,(e=>{let i=t.getData("INSTANCES_LENGTH"),a=t.getData("POSITION",i,"FLOAT","VEC3"),o=t.getData("POSITION_QUANTIZED",i,"UNSIGNED_SHORT","VEC3"),l=t.getData("QUANTIZED_VOLUME_OFFSET",1,"FLOAT","VEC3"),c=t.getData("QUANTIZED_VOLUME_SCALE",1,"FLOAT","VEC3"),u=t.getData("NORMAL_UP",i,"FLOAT","VEC3"),d=t.getData("NORMAL_RIGHT",i,"FLOAT","VEC3"),p=t.getData("NORMAL_UP_OCT32P",i,"UNSIGNED_SHORT","VEC2"),m=t.getData("NORMAL_RIGHT_OCT32P",i,"UNSIGNED_SHORT","VEC2"),f=t.getData("SCALE_NON_UNIFORM",i,"FLOAT","VEC3"),g=t.getData("SCALE",i,"FLOAT","SCALAR"),x=t.getData("RTC_CENTER",1,"FLOAT","VEC3"),y=t.getData("EAST_NORTH_UP");if(!a&&o){a=new Float32Array(3*i);for(let e=0;e<i;e++)a[3*e+0]=l[0]+o[3*e+0]/65535*c[0],a[3*e+1]=l[1]+o[3*e+1]/65535*c[1],a[3*e+2]=l[2]+o[3*e+2]/65535*c[2]}let v=new r.Vector3;for(let t=0;t<i;t++)v.x+=a[3*t+0]/i,v.y+=a[3*t+1]/i,v.z+=a[3*t+2]/i;let b=[],w=[];e.scene.updateMatrixWorld(),e.scene.traverse((e=>{if(e.isMesh){w.push(e);let{geometry:t,material:n}=e,s=new r.InstancedMesh(t,n,i);s.position.copy(v),x&&(s.position.x+=x[0],s.position.y+=x[1],s.position.z+=x[2]),b.push(s)}}));for(let t=0;t<i;t++){fu.set(a[3*t+0]-v.x,a[3*t+1]-v.y,a[3*t+2]-v.z),gu.identity(),u&&d?(pu.set(u[3*t+0],u[3*t+1],u[3*t+2]),mu.set(d[3*t+0],d[3*t+1],d[3*t+2]),du.crossVectors(mu,pu).normalize(),yu.makeBasis(mu,pu,du),gu.setFromRotationMatrix(yu)):p&&m&&(_u(p[2*t+0],p[2*t+1],65535,pu),_u(m[2*t+0],m[2*t+1],65535,mu),du.crossVectors(mu,pu).normalize(),yu.makeBasis(mu,pu,du),gu.setFromRotationMatrix(yu)),xu.set(1,1,1),f&&xu.set(f[3*t+0],f[3*t+1],f[3*t+2]),g&&xu.multiplyScalar(g[t]);for(let e=0,n=b.length;e<n;e++){let n=b[e];Tu.copy(gu),y&&(n.updateMatrixWorld(),bu.copy(fu).applyMatrix4(n.matrixWorld),this.ellipsoid.getPositionToCartographic(bu,Su),this.ellipsoid.getEastNorthUpFrame(Su.lat,Su.lon,wu),Tu.setFromRotationMatrix(wu)),yu.compose(fu,Tu,xu).multiply(h);let r=w[e];vu.multiplyMatrices(yu,r.matrixWorld),n.setMatrixAt(t,vu)}}e.scene.clear(),e.scene.add(...b),e.batchTable=n,e.featureTable=t,e.scene.batchTable=n,e.scene.featureTable=t,s(e)}),a)}))}))}},Au=class extends Ec{constructor(e=r.DefaultLoadingManager){super(),this.manager=e,this.adjustmentTransform=new r.Matrix4,this.ellipsoid=hu.clone()}parse(e){let t=super.parse(e),{manager:n,ellipsoid:i,adjustmentTransform:s}=this,a=[];for(let r in t.tiles){let{type:e,buffer:o}=t.tiles[r];switch(e){case"b3dm":{let e=o.slice(),t=new Hc(n);t.workingPath=this.workingPath,t.fetchOptions=this.fetchOptions,t.adjustmentTransform.copy(s);let r=t.parse(e.buffer);a.push(r);break}case"pnts":{let e=o.slice(),t=new Kc(n);t.workingPath=this.workingPath,t.fetchOptions=this.fetchOptions;let r=t.parse(e.buffer);a.push(r);break}case"i3dm":{let e=o.slice(),t=new Mu(n);t.workingPath=this.workingPath,t.fetchOptions=this.fetchOptions,t.ellipsoid.copy(i),t.adjustmentTransform.copy(s);let r=t.parse(e.buffer);a.push(r);break}}}return Promise.all(a).then((e=>{let t=new r.Group;return e.forEach((e=>{t.add(e.scene)})),{tiles:e,scene:t}}))}},Eu=new r.Matrix4,Cu=class extends r.Group{constructor(e){super(),this.isTilesGroup=!0,this.name="TilesRenderer.TilesGroup",this.tilesRenderer=e,this.matrixWorldInverse=new r.Matrix4}raycast(e,t){return this.tilesRenderer.raycast(e,t),!1}updateMatrixWorld(e){if(this.matrixAutoUpdate&&this.updateMatrix(),this.matrixWorldNeedsUpdate||e){null===this.parent?Eu.copy(this.matrix):Eu.multiplyMatrices(this.parent.matrixWorld,this.matrix),this.matrixWorldNeedsUpdate=!1;let e=Eu.elements,t=this.matrixWorld.elements,n=!1;for(let r=0;r<16;r++){let i=e[r],s=t[r];if(Math.abs(i-s)>2**-52){n=!0;break}}if(n){this.matrixWorld.copy(Eu),this.matrixWorldInverse.copy(Eu).invert();let e=this.children;for(let i=0,s=e.length;i<s;i++)e[i].updateMatrixWorld();let{tilesRenderer:t}=this,{activeTiles:n,visibleTiles:r}=t;n.forEach((e=>{r.has(e)||e.engineData.scene.updateMatrixWorld(!0)}))}}}updateWorldMatrix(e,t){this.parent&&e&&this.parent.updateWorldMatrix(e,!1),this.updateMatrixWorld(!0)}},Ru=new r.Ray;function Du(e,t,n,r,i=null){if(!function(e){return"traversal"in e}(t))return;let{group:s,activeTiles:a}=e,{boundingVolume:o}=t.engineData;if(null===i&&(i=Ru).copy(n.ray).applyMatrix4(s.matrixWorldInverse),!t.traversal.used||!o.intersectsRay(i))return;a.has(t)&&function(e,t,n,r){let{scene:i}=e.engineData;n.invokeOnePlugin((n=>n.raycastTile&&n.raycastTile(e,i,t,r)))||t.intersectObject(i,!0,r)}(t,n,e,r);let l=t.children;for(let c=0,u=l.length;c<u;c++)Du(e,l[c],n,r,i)}var ku=new r.Vector3,Iu=new r.Vector3,Pu=new r.Vector3,Lu=new r.Ray,Uu=class{constructor(e=new r.Box3,t=new r.Matrix4){this.box=e.clone(),this.transform=t.clone(),this.inverseTransform=new r.Matrix4,this.points=Array(8).fill().map((()=>new r.Vector3)),this.planes=[,,,,,,].fill().map((()=>new r.Plane))}copy(e){return this.box.copy(e.box),this.transform.copy(e.transform),this.update(),this}clone(){return(new this.constructor).copy(this)}clampPoint(e,t){return t.copy(e).applyMatrix4(this.inverseTransform).clamp(this.box.min,this.box.max).applyMatrix4(this.transform)}distanceToPoint(e){return this.clampPoint(e,Pu).distanceTo(e)}containsPoint(e){return Pu.copy(e).applyMatrix4(this.inverseTransform),this.box.containsPoint(Pu)}intersectsRay(e){return Lu.copy(e).applyMatrix4(this.inverseTransform),Lu.intersectsBox(this.box)}intersectRay(e,t){return Lu.copy(e).applyMatrix4(this.inverseTransform),Lu.intersectBox(this.box,t)?(t.applyMatrix4(this.transform),t):null}update(){let{points:e,inverseTransform:t,transform:n,box:r}=this;t.copy(n).invert();let{min:i,max:s}=r,a=0;for(let o=-1;o<=1;o+=2)for(let t=-1;t<=1;t+=2)for(let r=-1;r<=1;r+=2)e[a].set(o<0?i.x:s.x,t<0?i.y:s.y,r<0?i.z:s.z).applyMatrix4(n),a++;this.updatePlanes()}updatePlanes(){ku.copy(this.box.min).applyMatrix4(this.transform),Iu.copy(this.box.max).applyMatrix4(this.transform),Pu.set(0,0,1).transformDirection(this.transform),this.planes[0].setFromNormalAndCoplanarPoint(Pu,ku),this.planes[1].setFromNormalAndCoplanarPoint(Pu,Iu).negate(),Pu.set(0,1,0).transformDirection(this.transform),this.planes[2].setFromNormalAndCoplanarPoint(Pu,ku),this.planes[3].setFromNormalAndCoplanarPoint(Pu,Iu).negate(),Pu.set(1,0,0).transformDirection(this.transform),this.planes[4].setFromNormalAndCoplanarPoint(Pu,ku),this.planes[5].setFromNormalAndCoplanarPoint(Pu,Iu).negate()}intersectsSphere(e){return this.clampPoint(e.center,Pu),Pu.distanceToSquared(e.center)<=e.radius*e.radius}intersectsFrustum(e){return this._intersectsPlaneShape(e.planes,e.points)}intersectsOBB(e){return this._intersectsPlaneShape(e.planes,e.points)}_intersectsPlaneShape(e,t){let n=this.points,r=this.planes;for(let i=0;i<6;i++){let t=e[i],r=-1/0;for(let e=0;e<8;e++){let i=n[e],s=t.distanceToPoint(i);r=r<s?s:r}if(r<0)return!1}for(let i=0;i<6;i++){let e=r[i],n=-1/0;for(let r=0;r<8;r++){let i=t[r],s=e.distanceToPoint(i);n=n<s?s:n}if(n<0)return!1}return!0}},Fu=Math.PI,zu=Fu/2,Bu=new r.Vector3,Vu=new r.Vector3,Ou=new r.Vector3,Nu=new r.Vector3,$u=new r.Matrix4,Gu=new r.Box3,qu=new r.Matrix4;function Hu(e,t){t.radius=Math.max(t.radius,e.distanceToSquared(t.center))}function ju(e){return e.x!==e.y}var Wu=class extends uu{constructor(e=1,t=1,n=1,r=-zu,i=zu,s=0,a=2*Fu,o=0,l=0){super(e,t,n),this.latStart=r,this.latEnd=i,this.lonStart=s,this.lonEnd=a,this.heightStart=o,this.heightEnd=l}getBoundingBox(e,t){ju(this.radius);let n,{latStart:r,latEnd:i,lonStart:s,lonEnd:a,heightStart:o,heightEnd:l}=this,c=.5*(r+i),u=.5*(s+a),h=r>0,d=i<0;n=h?r:d?i:0;let{min:p,max:m}=e;p.setScalar(1/0),m.setScalar(-1/0),a-s<=Fu?(this.getCartographicToNormal(c,u,Ou),Vu.set(0,0,1),Bu.crossVectors(Vu,Ou).normalize(),Vu.crossVectors(Ou,Bu).normalize(),t.makeBasis(Bu,Vu,Ou),$u.copy(t).invert(),this.getCartographicToPosition(n,s,l,Nu).applyMatrix4($u),m.x=Math.abs(Nu.x),p.x=-m.x,this.getCartographicToPosition(i,s,l,Nu).applyMatrix4($u),m.y=Nu.y,this.getCartographicToPosition(i,u,l,Nu).applyMatrix4($u),m.y=Math.max(Nu.y,m.y),this.getCartographicToPosition(r,s,l,Nu).applyMatrix4($u),p.y=Nu.y,this.getCartographicToPosition(r,u,l,Nu).applyMatrix4($u),p.y=Math.min(Nu.y,p.y),this.getCartographicToPosition(c,u,l,Nu).applyMatrix4($u),m.z=Nu.z,this.getCartographicToPosition(r,s,o,Nu).applyMatrix4($u),p.z=Nu.z,this.getCartographicToPosition(i,s,o,Nu).applyMatrix4($u),p.z=Math.min(Nu.z,p.z)):(this.getCartographicToPosition(n,u,l,Ou),Ou.z=0,Ou.length()<1e-10?Ou.set(1,0,0):Ou.normalize(),Vu.set(0,0,1),Bu.crossVectors(Ou,Vu).normalize(),t.makeBasis(Bu,Vu,Ou),$u.copy(t).invert(),this.getCartographicToPosition(n,u+zu,l,Nu).applyMatrix4($u),m.x=Math.abs(Nu.x),p.x=-m.x,this.getCartographicToPosition(i,0,d?o:l,Nu).applyMatrix4($u),m.y=Nu.y,this.getCartographicToPosition(r,0,h?o:l,Nu).applyMatrix4($u),p.y=Nu.y,this.getCartographicToPosition(n,u,l,Nu).applyMatrix4($u),m.z=Nu.z,this.getCartographicToPosition(n,a,l,Nu).applyMatrix4($u),p.z=Nu.z),e.getCenter(Nu),e.min.sub(Nu).multiplyScalar(1.0000000000001),e.max.sub(Nu).multiplyScalar(1.0000000000001),Nu.applyMatrix4(t),t.setPosition(Nu)}getBoundingSphere(e){ju(this.radius),this.getBoundingBox(Gu,qu),e.center.setFromMatrixPosition(qu),e.radius=0;let t,{latStart:n,latEnd:r,lonStart:i,lonEnd:s,heightStart:a,heightEnd:o}=this,l=.5*(n+r),c=.5*(i+s);t=n>0?n:r<0?r:0,this.getCartographicToPosition(t,i,o,Nu),Hu(Nu,e),this.getCartographicToPosition(r,i,o,Nu),Hu(Nu,e),this.getCartographicToPosition(r,c,o,Nu),Hu(Nu,e),this.getCartographicToPosition(n,i,o,Nu),Hu(Nu,e),this.getCartographicToPosition(n,c,o,Nu),Hu(Nu,e),this.getCartographicToPosition(l,c,o,Nu),Hu(Nu,e),this.getCartographicToPosition(n,i,a,Nu),Hu(Nu,e),s-i>Fu&&(this.getCartographicToPosition(t,c+Fu,o,Nu),Hu(Nu,e)),e.radius=1.0000000000001*Math.sqrt(e.radius)}},Xu=new r.Vector3,Yu=new r.Vector3,Ku=new r.Vector3,Qu=new r.Vector3,Zu=new r.Vector3,Ju=class{constructor(){this.sphere=null,this.obb=null,this.region=null,this.regionObb=null}intersectsRay(e){let t=this.sphere,n=this.obb||this.regionObb;return!(t&&!e.intersectsSphere(t)||n&&!n.intersectsRay(e))}intersectRay(e,t=null){let n=this.sphere,r=this.obb||this.regionObb,i=-1/0,s=-1/0;n&&e.intersectSphere(n,Qu)&&(i=n.containsPoint(e.origin)?0:e.origin.distanceToSquared(Qu)),r&&r.intersectRay(e,Zu)&&(s=r.containsPoint(e.origin)?0:e.origin.distanceToSquared(Zu));let a=Math.max(i,s);return a===-1/0?null:(e.at(Math.sqrt(a),t),t)}distanceToPoint(e){let t=this.sphere,n=this.obb||this.regionObb,r=-1/0,i=-1/0;return t&&(r=Math.max(t.distanceToPoint(e),0)),n&&(i=n.distanceToPoint(e)),r>i?r:i}intersectsFrustum(e){let t=this.obb||this.regionObb,n=this.sphere;return!(n&&!e.intersectsSphere(n)||t&&!t.intersectsFrustum(e))&&!(!n&&!t)}intersectsSphere(e){let t=this.obb||this.regionObb,n=this.sphere;return!(n&&!n.intersectsSphere(e)||t&&!t.intersectsSphere(e))&&!(!n&&!t)}intersectsOBB(e){let t=this.obb||this.regionObb,n=this.sphere;return!(n&&!e.intersectsSphere(n)||t&&!t.intersectsOBB(e))&&!(!n&&!t)}getOBB(e,t){let n=this.obb||this.regionObb;n?(e.copy(n.box),t.copy(n.transform)):(this.getAABB(e),t.identity())}getAABB(e){if(this.sphere)this.sphere.getBoundingBox(e);else{let t=this.obb||this.regionObb;e.copy(t.box).applyMatrix4(t.transform)}}getSphere(e){if(this.sphere)e.copy(this.sphere);else if(this.region)this.region.getBoundingSphere(e);else{let t=this.obb||this.regionObb;t.box.getBoundingSphere(e),e.applyMatrix4(t.transform)}}setObbData(e,t){let n=new Uu;Xu.set(e[3],e[4],e[5]),Yu.set(e[6],e[7],e[8]),Ku.set(e[9],e[10],e[11]);let r=Xu.length(),i=Yu.length(),s=Ku.length();Xu.normalize(),Yu.normalize(),Ku.normalize(),0===r&&Xu.crossVectors(Yu,Ku),0===i&&Yu.crossVectors(Xu,Ku),0===s&&Ku.crossVectors(Xu,Yu),n.transform.set(Xu.x,Yu.x,Ku.x,e[0],Xu.y,Yu.y,Ku.y,e[1],Xu.z,Yu.z,Ku.z,e[2],0,0,0,1).premultiply(t),n.box.min.set(-r,-i,-s),n.box.max.set(r,i,s),n.update(),this.obb=n}setSphereData(e,t,n,i,s){let a=new r.Sphere;a.center.set(e,t,n),a.radius=i,a.applyMatrix4(s),this.sphere=a}setRegionData(e,t,n,r,i,s,a){let o=new Wu(...e.radius,n,i,t,r,s,a),l=new Uu;o.getBoundingBox(l.box,l.transform),l.update(),this.region=o,this.regionObb=l}},eh=new r.Matrix3;var th=class extends r.Frustum{constructor(){super(),this.points=Array(8).fill().map((()=>new r.Vector3))}setFromProjectionMatrix(...e){return super.setFromProjectionMatrix(...e),this.calculateFrustumPoints(),this}calculateFrustumPoints(){let{planes:e,points:t}=this;[[e[0],e[3],e[4]],[e[1],e[3],e[4]],[e[0],e[2],e[4]],[e[1],e[2],e[4]],[e[0],e[3],e[5]],[e[1],e[3],e[5]],[e[0],e[2],e[5]],[e[1],e[2],e[5]]].forEach(((e,n)=>{!function(e,t,n,r){let i=eh.set(e.normal.x,e.normal.y,e.normal.z,t.normal.x,t.normal.y,t.normal.z,n.normal.x,n.normal.y,n.normal.z);r.set(-e.constant,-t.constant,-n.constant),r.applyMatrix3(i.invert())}(e[0],e[1],e[2],t[n])}))}};function nh(e,t,n,i){try{return r.TextureUtils.getByteLength(e,t,n,i)}catch{return 0}}function rh(e){var t,n;if(!e)return 0;if(e.isExternalTexture)return(null==(t=e.userData)?void 0:t.byteLength)??0;let{format:r,type:i,image:s,mipmaps:a}=e;if(e.isCompressedTexture&&Array.isArray(a)&&a.length>0){let e=0;for(let t of a)(null==(n=null==t?void 0:t.data)?void 0:n.byteLength)?e+=t.data.byteLength:e+=nh(t.width,t.height,r,i);return e}if(!s)return 0;let o=nh(s.width,s.height,r,i);return o*=e.generateMipmaps?4/3:1,o}var ih=Symbol("INITIAL_FRUSTUM_CULLED"),sh=new r.Matrix4,ah=new r.Vector3,oh=new r.Vector2,lh=new r.Vector3(1,0,0),ch=new r.Vector3(0,1,0),uh=()=>null;function hh(e,t){e.traverse((e=>{e.frustumCulled=e[ih]&&t}))}var dh=class extends mc{get autoDisableRendererCulling(){return this._autoDisableRendererCulling}set autoDisableRendererCulling(e){this._autoDisableRendererCulling!==e&&(super._autoDisableRendererCulling=e,this.forEachLoadedModel((t=>{hh(t,!e)})))}constructor(...e){super(...e),this.accelerateRaycast=!0,this.group=new Cu(this),this.ellipsoid=hu.clone(),this.cameras=[],this.cameraMap=new Map,this.cameraInfo=[],this._upRotationMatrix=new r.Matrix4,this._bytesUsed=new WeakMap,this._autoDisableRendererCulling=!0,this.manager=new r.LoadingManager,this._listeners={}}addEventListener(e,t){r.EventDispatcher.prototype.addEventListener.call(this,e,t)}hasEventListener(e,t){return r.EventDispatcher.prototype.hasEventListener.call(this,e,t)}removeEventListener(e,t){r.EventDispatcher.prototype.removeEventListener.call(this,e,t)}dispatchEvent(e){r.EventDispatcher.prototype.dispatchEvent.call(this,e)}getBoundingBox(e){if(!this.root)return!1;let t=this.root.engineData.boundingVolume;return!!t&&(t.getAABB(e),!0)}getOrientedBoundingBox(e,t){if(!this.root)return!1;let n=this.root.engineData.boundingVolume;return!!n&&(n.getOBB(e,t),!0)}getBoundingSphere(e){if(!this.root)return!1;let t=this.root.engineData.boundingVolume;return!!t&&(t.getSphere(e),!0)}forEachLoadedModel(e){this.traverse((t=>{let n=t.engineData&&t.engineData.scene;n&&e(n,t)}),null,!1)}raycast(e,t){if(this.root)if(this.accelerateRaycast)Du(this,this.root,e,t);else{let n=e.firstHitOnly?[]:t;for(let t of this.activeTiles){let{scene:r}=t.engineData;this.invokeOnePlugin((i=>i.raycastTile&&i.raycastTile(t,r,e,n)))||e.intersectObject(r,!0,n)}e.firstHitOnly&&n.length>0&&(n.sort(((e,t)=>e.distance-t.distance)),t.push(n[0]))}}hasCamera(e){return this.cameraMap.has(e)}setCamera(e){let t=this.cameras,n=this.cameraMap;return!n.has(e)&&(n.set(e,new r.Vector2),t.push(e),this.dispatchEvent({type:"add-camera",camera:e}),!0)}setResolution(e,t,n){let r=this.cameraMap;if(!r.has(e))return!1;let i=t.isVector2?t.x:t,s=t.isVector2?t.y:n,a=r.get(e);return(a.width!==i||a.height!==s)&&(a.set(i,s),this.dispatchEvent({type:"camera-resolution-change"})),!0}getResolution(e,t){let n=this.cameraMap.get(e);return n?t.copy(n):null}setResolutionFromRenderer(e,t){return t.getSize(oh),this.setResolution(e,oh.x,oh.y)}deleteCamera(e){let t=this.cameras,n=this.cameraMap;if(n.has(e)){let r=t.indexOf(e);return t.splice(r,1),n.delete(e),this.dispatchEvent({type:"delete-camera",camera:e}),!0}return!1}loadRootTileset(...e){return super.loadRootTileset(...e).then((e=>{let{asset:t,extensions:n={}}=e;switch((t&&t.gltfUpAxis||"y").toLowerCase()){case"x":this._upRotationMatrix.makeRotationAxis(ch,-Math.PI/2);break;case"y":this._upRotationMatrix.makeRotationAxis(lh,Math.PI/2)}if("3DTILES_ellipsoid"in n){let e=n["3DTILES_ellipsoid"],{ellipsoid:t}=this;t.name=e.body,e.radii?t.radius.set(...e.radii):t.radius.set(1,1,1)}return e}))}prepareForTraversal(){let e=this.group,t=this.cameras,n=this.cameraMap,i=this.cameraInfo;for(;i.length>t.length;)i.pop();for(;i.length<t.length;)i.push({frustum:new th,isOrthographic:!1,sseDenominator:-1,position:new r.Vector3,invScale:-1,pixelSize:0});ah.setFromMatrixScale(e.matrixWorldInverse),Math.abs(Math.max(ah.x-ah.y,ah.x-ah.z));for(let r=0,s=i.length;r<s;r++){let s=t[r],a=i[r],o=a.frustum,l=a.position,c=n.get(s);0===c.width||c.height;let u=s.projectionMatrix.elements;if(a.isOrthographic=1===u[15],a.isOrthographic){let e=2/u[0],t=2/u[5];a.pixelSize=Math.max(t/c.height,e/c.width)}else a.sseDenominator=2/u[5]/c.height;sh.copy(e.matrixWorld),sh.premultiply(s.matrixWorldInverse),sh.premultiply(s.projectionMatrix),o.setFromProjectionMatrix(sh,s.coordinateSystem,s.reversedDepth),l.set(0,0,0),l.applyMatrix4(s.matrixWorld),l.applyMatrix4(e.matrixWorldInverse)}}update(){if(super.update(),0===this.cameras.length&&this.root){let e=!1;this.invokeAllPlugins((t=>e||(e=!(t===this||!t.calculateTileViewError))))}}preprocessNode(e,t,n=null){super.preprocessNode(e,t,n);let i=new r.Matrix4;if(e.transform){let t=e.transform;for(let e=0;e<16;e++)i.elements[e]=t[e]}n&&i.premultiply(n.engineData.transform);let s=(new r.Matrix4).copy(i).invert(),a=new Ju;"sphere"in e.boundingVolume&&a.setSphereData(...e.boundingVolume.sphere,i),"box"in e.boundingVolume&&a.setObbData(e.boundingVolume.box,i),"region"in e.boundingVolume&&a.setRegionData(this.ellipsoid,...e.boundingVolume.region),e.engineData.transform=i,e.engineData.transformInverse=s,e.engineData.boundingVolume=a,e.engineData.geometry=null,e.engineData.materials=null,e.engineData.textures=null,e.toJSON=uh}async parseTile(e,t,n,i,s){let a=t.engineData,o=yc(i),l=this.fetchOptions,c=this.manager,u=null,h=a.transform,d=this._upRotationMatrix,p=(fc(e)||n).toLowerCase();switch(p){case"b3dm":{let t=new Hc(c);t.workingPath=o,t.fetchOptions=l,t.adjustmentTransform.copy(d),u=t.parse(e);break}case"pnts":{let t=new Kc(c);t.workingPath=o,t.fetchOptions=l,u=t.parse(e);break}case"i3dm":{let t=new Mu(c);t.workingPath=o,t.fetchOptions=l,t.adjustmentTransform.copy(d),t.ellipsoid.copy(this.ellipsoid),u=t.parse(e);break}case"cmpt":{let t=new Au(c);t.workingPath=o,t.fetchOptions=l,t.adjustmentTransform.copy(d),t.ellipsoid.copy(this.ellipsoid),u=t.parse(e).then((e=>e.scene));break}case"gltf":case"glb":{let t=c.getHandler("path.gltf")||c.getHandler("path.glb")||new rt(c);t.setWithCredentials("include"===l.credentials),t.setRequestHeader(l.headers||{}),"include"===l.credentials&&"cors"===l.mode&&t.setCrossOrigin("use-credentials");let n=t.resourcePath||t.path||o;!/[\\/]$/.test(n)&&n.length&&(n+="/"),u=t.parseAsync(e,n).then((e=>{e.scene=e.scene||new r.Group;let{scene:t}=e;return t.updateMatrix(),t.matrix.multiply(d).decompose(t.position,t.quaternion,t.scale),e}));break}default:u=this.invokeOnePlugin((r=>r.parseToMesh&&r.parseToMesh(e,t,n,i,s)))}let m,f,g=await u;if(null===g)throw Error(`TilesRenderer: Content type "${p}" not supported.`);g.isObject3D?(m=g,f=null):(m=g.scene,f=g),m.updateMatrix(),m.matrix.premultiply(h),m.matrix.decompose(m.position,m.quaternion,m.scale),await this.invokeAllPlugins((e=>e.processTileModel&&e.processTileModel(m,t))),m.traverse((e=>{e[ih]=e.frustumCulled,e.userData.tile=t})),hh(m,!this.autoDisableRendererCulling);let x=[],y=[],v=[];if(m.traverse((e=>{if(e.geometry&&y.push(e.geometry),e.material){let t=e.material;x.push(e.material);for(let e in t){let n=t[e];n&&n.isTexture&&v.push(n)}}})),s.aborted)for(let r=0,b=v.length;r<b;r++){let e=v[r];e.image instanceof ImageBitmap&&e.image.close(),e.dispose()}else a.materials=x,a.geometry=y,a.textures=v,a.scene=m,a.metadata=f}disposeTile(e){super.disposeTile(e);let t=e.engineData;if(t.scene){let e=t.materials,n=t.geometry,r=t.textures,i=t.scene.parent;t.scene.traverse((e=>{e.userData.meshFeatures&&e.userData.meshFeatures.dispose(),e.userData.structuralMetadata&&e.userData.structuralMetadata.dispose()}));for(let t=0,s=n.length;t<s;t++)n[t].dispose();for(let t=0,s=e.length;t<s;t++)e[t].dispose();for(let t=0,s=r.length;t<s;t++){let e=r[t];e.image instanceof ImageBitmap&&e.image.close(),e.dispose()}i&&i.remove(t.scene),t.scene=null,t.materials=null,t.textures=null,t.geometry=null,t.metadata=null}}setTileActive(e,t){super.setTileActive(e,t);let n=e.engineData.scene;n&&(t?(n.parent=this.group,n.updateMatrixWorld(!0)):n.parent=null)}setTileVisible(e,t){let n=e.engineData.scene,{activeTiles:r,group:i}=this;n&&(t?i.add(n):(i.remove(n),r.has(e)&&(n.parent=i))),super.setTileVisible(e,t)}calculateBytesUsed(e,t){let n=this._bytesUsed;return!n.has(e)&&t&&n.set(e,function(e){let t=new Set,n=0;return e.traverse((e=>{if(e.geometry&&!t.has(e.geometry)&&(n+=function(e){let t=0;for(const r in e.attributes){const n=e.getAttribute(r);t+=n.count*n.itemSize*n.array.BYTES_PER_ELEMENT}const n=e.getIndex();return t+=n?n.count*n.itemSize*n.array.BYTES_PER_ELEMENT:0,t}(e.geometry),t.add(e.geometry)),e.material){let r=e.material;for(let e in r){let i=r[e];i&&i.isTexture&&!t.has(i)&&(n+=rh(i),t.add(i))}}})),n}(t)),n.get(e)??null}calculateTileViewError(e,t){let n=e.engineData,r=this.cameras,i=this.cameraInfo,s=n.boundingVolume,a=!1,o=0,l=1/0,c=0,u=1/0;for(let h=0,d=r.length;h<d;h++){let t,n,r=i[h];if(r.isOrthographic){let i=r.pixelSize;t=e.geometricError/i,n=1/0}else{let i=r.sseDenominator;n=s.distanceToPoint(r.position),t=0===n?1/0:e.geometricError/(n*i)}let d=i[h].frustum;s.intersectsFrustum(d)&&(a=!0,o=Math.max(o,t),l=Math.min(l,n)),c=Math.max(c,t),u=Math.min(u,n)}a?(t.inView=!0,t.error=o,t.distanceFromCamera=l):(t.inView=!1,t.error=c,t.distanceFromCamera=u)}dispose(){super.dispose(),this.group.removeFromParent()}},ph=class{constructor(e={}){let{apiToken:t,autoRefreshToken:n=!1}=e;this.apiToken=t,this.autoRefreshToken=n,this.authURL=null,this._tokenRefreshPromise=null,this._bearerToken=null,this._bearerHostname=null}async fetch(e,t){await this._tokenRefreshPromise;let n={...t},r=null!==this._bearerHostname&&new URL(e).host===this._bearerHostname;r&&(n.headers={...n.headers,Authorization:this._bearerToken});let i=await fetch(e,n);return r&&i.status>=400&&i.status<=499&&this.autoRefreshToken?(await this.refreshToken(t),n.headers.Authorization=this._bearerToken,fetch(e,n)):i}refreshToken(e){if(null===this._tokenRefreshPromise){let t=new URL(this.authURL);t.searchParams.set("access_token",this.apiToken),this._tokenRefreshPromise=fetch(t,e).then((e=>{if(!e.ok)throw Error(`CesiumIonAuthPlugin: Failed to load data with error code ${e.status}`);return e.json()})).then((e=>(e.accessToken&&e.url&&(this._bearerToken=`Bearer ${e.accessToken}`,this._bearerHostname=new URL(e.url).host),this._tokenRefreshPromise=null,e)))}return this._tokenRefreshPromise}},mh="https://tile.googleapis.com/v1/createSession",fh=class{get isMapTilesSession(){return this.authURL===mh}constructor(e={}){let{apiToken:t,sessionOptions:n=null,autoRefreshToken:r=!1}=e;this.apiToken=t,this.autoRefreshToken=r,this.authURL=mh,this.sessionToken=null,this.sessionOptions=n,this._tokenRefreshPromise=null,this._authHostname=null}async fetch(e,t){null===this.sessionToken&&this.isMapTilesSession&&this.refreshToken(t),await this._tokenRefreshPromise,null===this._authHostname&&(this._authHostname=new URL(this.authURL).host);let n=new URL(e),r=n.host===this._authHostname;r&&(n.searchParams.set("key",this.apiToken),this.sessionToken&&n.searchParams.set("session",this.sessionToken));let i=await fetch(n,t);return r&&i.status>=400&&i.status<=499&&this.autoRefreshToken&&(await this.refreshToken(t),this.sessionToken&&n.searchParams.set("session",this.sessionToken),i=await fetch(n,t)),null!==this.sessionToken||this.isMapTilesSession?i:i.json().then((e=>(this.sessionToken=gh(e),e)))}refreshToken(e){if(null===this._tokenRefreshPromise){let t=new URL(this.authURL);t.searchParams.set("key",this.apiToken);let n={...e};this.isMapTilesSession&&(n.method="POST",n.body=JSON.stringify(this.sessionOptions),n.headers=n.headers||{},n.headers={...n.headers,"Content-Type":"application/json"}),this._tokenRefreshPromise=fetch(t,n).then((e=>{if(!e.ok)throw Error(`GoogleCloudAuth: Failed to load data with error code ${e.status}`);return e.json()})).then((e=>(this.sessionToken=gh(e),this._tokenRefreshPromise=null,e)))}return this._tokenRefreshPromise}};function gh(e){if("session"in e)return e.session;{let t=null;return ac(e.root,(e=>{if(e.content&&e.content.uri){let[,n]=e.content.uri.split("?");return t=new URLSearchParams(n).get("session"),!0}return!1})),t}}var xh=class{constructor(){this.creditsCount={}}_adjustAttributions(e,t){let n=this.creditsCount,r=e.split(/;/g);for(let i=0,s=r.length;i<s;i++){let e=r[i];e in n||(n[e]=0),n[e]+=t?1:-1,n[e]<=0&&delete n[e]}}addAttributions(e){this._adjustAttributions(e,!0)}removeAttributions(e){this._adjustAttributions(e,!1)}toString(){return Object.entries(this.creditsCount).sort(((e,t)=>{let n=e[1];return t[1]-n})).map((e=>e[0])).join("; ")}},yh=class{constructor({apiToken:e,sessionOptions:t=null,autoRefreshToken:n=!1,logoUrl:r=null,useRecommendedSettings:i=!0}){this.name="GOOGLE_CLOUD_AUTH_PLUGIN",this.apiToken=e,this.useRecommendedSettings=i,this.logoUrl=r,this.auth=new fh({apiToken:e,autoRefreshToken:n,sessionOptions:t}),this.tiles=null,this._visibilityChangeCallback=null,this._attributionsManager=new xh,this._logoAttribution={value:"",type:"image",collapsible:!1},this._attribution={value:"",type:"string",collapsible:!0}}init(e){let{useRecommendedSettings:t,auth:n}=this;e.resetFailedTiles(),e.rootURL??(e.rootURL="https://tile.googleapis.com/v1/3dtiles/root.json"),n.sessionOptions||(n.authURL=e.rootURL),t&&!n.isMapTilesSession&&(e.errorTarget=20),this.tiles=e,this._visibilityChangeCallback=({tile:e,visible:t})=>{var n,r;let i=(null==(r=null==(n=e.engineData.metadata)?void 0:n.asset)?void 0:r.copyright)||"";t?this._attributionsManager.addAttributions(i):this._attributionsManager.removeAttributions(i)},e.addEventListener("tile-visibility-change",this._visibilityChangeCallback)}getAttributions(e){this.tiles.visibleTiles.size>0&&(this.logoUrl&&(this._logoAttribution.value=this.logoUrl,e.push(this._logoAttribution)),this._attribution.value=this._attributionsManager.toString(),e.push(this._attribution))}dispose(){this.tiles.removeEventListener("tile-visibility-change",this._visibilityChangeCallback)}async fetchData(e,t){return this.auth.fetch(e,t)}},vh=class{get apiToken(){return this.auth.apiToken}set apiToken(e){this.auth.apiToken=e}get autoRefreshToken(){return this.auth.autoRefreshToken}set autoRefreshToken(e){this.auth.autoRefreshToken=e}constructor(e={}){let{apiToken:t,assetId:n=null,autoRefreshToken:r=!1,useRecommendedSettings:i=!0,assetTypeHandler:s=(e,t,n)=>{}}=e;this.name="CESIUM_ION_AUTH_PLUGIN",this.auth=new ph({apiToken:t,autoRefreshToken:r}),this.assetId=n,this.autoRefreshToken=r,this.useRecommendedSettings=i,this.assetTypeHandler=s,this.tiles=null,this._tileSetVersion=-1,this._attributions=[]}init(e){null!==this.assetId&&(e.rootURL=`https://api.cesium.com/v1/assets/${this.assetId}/endpoint`),this.tiles=e,this.auth.authURL=e.rootURL,e.resetFailedTiles()}loadRootTileset(){return this.auth.refreshToken().then((e=>(this._initializeFromAsset(e),this.tiles.invokeOnePlugin((e=>e!==this&&e.loadRootTileset&&e.loadRootTileset()))))).catch((e=>{this.tiles.dispatchEvent({type:"load-error",tile:null,error:e,url:this.auth.authURL})}))}preprocessURL(e){return e=new URL(e),/^http/.test(e.protocol)&&-1!=this._tileSetVersion&&e.searchParams.set("v",this._tileSetVersion),e.toString()}fetchData(e,t){return null===this.tiles.getPluginByName("GOOGLE_CLOUD_AUTH_PLUGIN")?this.auth.fetch(e,t):null}getAttributions(e){this.tiles.visibleTiles.size>0&&e.push(...this._attributions)}_initializeFromAsset(e){let t=this.tiles;if("externalType"in e){let n=new URL(e.options.url);t.rootURL=e.options.url,t.registerPlugin(new yh({apiToken:n.searchParams.get("key"),autoRefreshToken:this.autoRefreshToken,useRecommendedSettings:this.useRecommendedSettings}))}else{"3DTILES"!==e.type&&this.assetTypeHandler(e.type,t,e),t.rootURL=e.url;let n=new URL(e.url);n.searchParams.has("v")&&-1===this._tileSetVersion&&(this._tileSetVersion=n.searchParams.get("v")),e.attributions&&(this._attributions=e.attributions.map((e=>({value:e.html,type:"html",collapsible:e.collapsible}))))}}};function bh(e){return"OCTREE"===e.implicitTilingData.root.implicitTiling.subdivisionScheme}function wh(e){return bh(e)?8:4}var Th=class{constructor(e,t){this.parent=e,this.children=[],this.geometricError=0,this.boundingVolume=null;let[n,r,i]=function(e,t){if(!e)return[0,0,0];let n=e.implicitTilingData.x,r=e.implicitTilingData.y,i=e.implicitTilingData.z;return[2*n+t%2,2*r+Math.floor(t/2)%2,bh(e)?2*i+Math.floor(t/4)%2:0]}(e,t);this.implicitTilingData={level:e.implicitTilingData.level+1,root:e.implicitTilingData.root,subtreeIdx:t,x:n,y:r,z:i}}static clone(e){return{parent:e.parent,children:[],geometricError:e.geometricError,boundingVolume:e.boundingVolume,implicitTilingData:{...e.implicitTilingData}}}},Sh=class extends vc{constructor(e){super(),this.tile=e,this.rootTile=e.implicitTilingData.root,this.workingPath=null}parseBuffer(e){let t=new DataView(e),n=0;fc(t);n+=4;let r=t.getUint32(n,!0);n+=4;let i=t.getUint32(n,!0);n+=8;let s=t.getUint32(n,!0);n+=8;let a=JSON.parse(xc(new Uint8Array(e,n,i)));return n+=i,{version:r,subtreeJson:a,subtreeByte:e.slice(n,n+s)}}async parse(e){let t=this.parseBuffer(e),n=t.subtreeJson;n.contentAvailabilityHeaders=[].concat(n.contentAvailability);let r=this.preprocessBuffers(n.buffers),i=this.preprocessBufferViews(n.bufferViews,r);this.markActiveBufferViews(n,i);let s=await this.requestActiveBuffers(r,t.subtreeByte),a=this.parseActiveBufferViews(i,s);this.parseAvailability(t,n,a),this.expandSubtree(this.tile,t)}markActiveBufferViews(e,t){let n,r=e.tileAvailability;isNaN(r.bitstream)?isNaN(r.bufferView)||(n=t[r.bufferView]):n=t[r.bitstream],n&&(n.isActive=!0,n.bufferHeader.isActive=!0);let i=e.contentAvailabilityHeaders;for(let a=0;a<i.length;a++)n=void 0,isNaN(i[a].bitstream)?isNaN(i[a].bufferView)||(n=t[i[a].bufferView]):n=t[i[a].bitstream],n&&(n.isActive=!0,n.bufferHeader.isActive=!0);n=void 0;let s=e.childSubtreeAvailability;isNaN(s.bitstream)?isNaN(s.bufferView)||(n=t[s.bufferView]):n=t[s.bitstream],n&&(n.isActive=!0,n.bufferHeader.isActive=!0)}async requestActiveBuffers(e,t){let n=[];for(let s=0;s<e.length;s++){let r=e[s];if(r.isActive)if(r.isExternal){let e=this.parseImplicitURIBuffer(this.tile,this.rootTile.implicitTiling.subtrees.uri,r.uri),t=fetch(e,this.fetchOptions).then((e=>{if(!e.ok)throw Error(`SUBTREELoader: Failed to load external buffer from ${r.uri} with error code ${e.status}.`);return e.arrayBuffer()})).then((e=>new Uint8Array(e)));n.push(t)}else n.push(Promise.resolve(new Uint8Array(t)));else n.push(Promise.resolve())}let r=await Promise.all(n),i={};for(let s=0;s<r.length;s++){let e=r[s];e&&(i[s]=e)}return i}parseActiveBufferViews(e,t){let n={};for(let r=0;r<e.length;r++){let i=e[r];if(!i.isActive)continue;let s=i.byteOffset,a=s+i.byteLength;n[r]=t[i.buffer].slice(s,a)}return n}preprocessBuffers(e=[]){for(let t=0;t<e.length;t++){let n=e[t];n.isActive=!1,n.isExternal=!!n.uri}return e}preprocessBufferViews(e=[],t){for(let n=0;n<e.length;n++){let r=e[n];r.bufferHeader=t[r.buffer],r.isActive=!1,r.isExternal=r.bufferHeader.isExternal}return e}parseAvailability(e,t,n){let r=wh(this.rootTile),i=this.rootTile.implicitTiling.subtreeLevels,s=(r**+i-1)/(r-1),a=r**+i;e._tileAvailability=this.parseAvailabilityBitstream(t.tileAvailability,n,s),e._contentAvailabilityBitstreams=[];for(let o=0;o<t.contentAvailabilityHeaders.length;o++){let r=this.parseAvailabilityBitstream(t.contentAvailabilityHeaders[o],n,s);e._contentAvailabilityBitstreams.push(r)}e._childSubtreeAvailability=this.parseAvailabilityBitstream(t.childSubtreeAvailability,n,a)}parseAvailabilityBitstream(e,t,n){if(!isNaN(e.constant))return{constant:!!e.constant,lengthBits:n};let r;return isNaN(e.bitstream)?isNaN(e.bufferView)||(r=t[e.bufferView]):r=t[e.bitstream],{bitstream:r,lengthBits:n}}expandSubtree(e,t){let n=Th.clone(e);for(let s=0;t&&s<t._contentAvailabilityBitstreams.length;s++)if(t&&this.getBit(t._contentAvailabilityBitstreams[s],0)){n.content={uri:this.parseImplicitURI(e,this.rootTile.content.uri)};break}e.children.push(n);let r=this.transcodeSubtreeTiles(n,t),i=this.listChildSubtrees(t,r);for(let s=0;s<i.length;s++){let e=i[s],t=e.tile,n=this.deriveChildTile(null,t,null,e.childMortonIndex);n.content={uri:this.parseImplicitURI(n,this.rootTile.implicitTiling.subtrees.uri)},t.children.push(n)}}transcodeSubtreeTiles(e,t){let n=[e],r=[];for(let i=1;i<this.rootTile.implicitTiling.subtreeLevels;i++){let e=wh(this.rootTile),s=(e**+i-1)/(e-1),a=e*n.length;for(let i=0;i<a;i++){let a=s+i,o=n[i>>Math.log2(e)];if(!this.getBit(t._tileAvailability,a)){r.push(void 0);continue}let l=this.deriveChildTile(t,o,a,i);o.children.push(l),r.push(l)}n=r,r=[]}return n}deriveChildTile(e,t,n,r){let i=new Th(t,r);i.boundingVolume=this.getTileBoundingVolume(i),i.geometricError=this.getGeometricError(i);for(let s=0;e&&s<e._contentAvailabilityBitstreams.length;s++)if(e&&this.getBit(e._contentAvailabilityBitstreams[s],n)){i.content={uri:this.parseImplicitURI(i,this.rootTile.content.uri)};break}return i}getBit(e,t){if(t<0||t>=e.lengthBits)throw Error("Bit index out of bounds.");if(void 0!==e.constant)return e.constant;let n=t>>3,r=t%8;return 1==(new Uint8Array(e.bitstream)[n]>>r&1)}getTileBoundingVolume(e){let t={};if(this.rootTile.boundingVolume.region){let n=[...this.rootTile.boundingVolume.region],r=n[0],i=n[2],s=n[1],a=n[3],o=(i-r)/2**e.implicitTilingData.level,l=(a-s)/2**e.implicitTilingData.level;n[0]=r+o*e.implicitTilingData.x,n[2]=r+o*(e.implicitTilingData.x+1),n[1]=s+l*e.implicitTilingData.y,n[3]=s+l*(e.implicitTilingData.y+1);for(let e=0;e<4;e++){let t=n[e];t<-Math.PI?n[e]+=2*Math.PI:t>Math.PI&&(n[e]-=2*Math.PI)}if(bh(e)){let t=n[4],r=(n[5]-t)/2**e.implicitTilingData.level;n[4]=t+r*e.implicitTilingData.z,n[5]=t+r*(e.implicitTilingData.z+1)}t.region=n}if(this.rootTile.boundingVolume.box){let n=[...this.rootTile.boundingVolume.box],r=2**e.implicitTilingData.level-1,i=2**-e.implicitTilingData.level,s=bh(e)?3:2;for(let t=0;t<s;t++){n[3+3*t+0]*=i,n[3+3*t+1]*=i,n[3+3*t+2]*=i;let s=n[3+3*t+0],a=n[3+3*t+1],o=n[3+3*t+2],l=0===t?e.implicitTilingData.x:1===t?e.implicitTilingData.y:e.implicitTilingData.z;n[0]+=2*s*(-.5*r+l),n[1]+=2*a*(-.5*r+l),n[2]+=2*o*(-.5*r+l)}t.box=n}return t}getGeometricError(e){return this.rootTile.geometricError/2**e.implicitTilingData.level}listChildSubtrees(e,t){let n=[],r=wh(this.rootTile);for(let i=0;i<t.length;i++){let s=t[i];if(void 0!==s)for(let t=0;t<r;t++){let a=i*r+t;this.getBit(e._childSubtreeAvailability,a)&&n.push({tile:s,childMortonIndex:a})}}return n}parseImplicitURI(e,t){return t=(t=(t=(t=t.replace("{level}",e.implicitTilingData.level)).replace("{x}",e.implicitTilingData.x)).replace("{y}",e.implicitTilingData.y)).replace("{z}",e.implicitTilingData.z)}parseImplicitURIBuffer(e,t,n){let r=this.parseImplicitURI(e,t),i=new URL(r,this.workingPath+"/");return i.pathname=i.pathname.substring(0,i.pathname.lastIndexOf("/")),new URL(i.pathname+"/"+n,this.workingPath+"/").toString()}},_h=class{constructor(){this.name="IMPLICIT_TILING_PLUGIN"}init(e){this.tiles=e}preprocessNode(e,t,n){var r;e.implicitTiling?(e.internal.hasUnrenderableContent=!0,e.internal.hasRenderableContent=!1,e.implicitTilingData={root:e,subtreeIdx:0,x:0,y:0,z:0,level:0}):/.subtree$/i.test(null==(r=e.content)?void 0:r.uri)&&(e.internal.hasUnrenderableContent=!0,e.internal.hasRenderableContent=!1)}parseTile(e,t,n){if(/^subtree$/i.test(n)){let n=new Sh(t);return n.workingPath=t.internal.basePath,n.fetchOptions=this.tiles.fetchOptions,n.parse(e)}}preprocessURL(e,t){if(t&&t.implicitTiling){let e=t.implicitTiling.subtrees.uri.replace("{level}",t.implicitTilingData.level).replace("{x}",t.implicitTilingData.x).replace("{y}",t.implicitTilingData.y).replace("{z}",t.implicitTilingData.z);return new URL(e,t.internal.basePath+"/").toString()}return e}disposeTile(e){var t;/.subtree$/i.test(null==(t=e.content)?void 0:t.uri)&&(e.children.forEach((e=>{this.tiles.processNodeQueue.remove(e)})),e.children.length=0)}};function Mh(e){return e>>1^-(1&e)}var Ah=class extends vc{constructor(...e){super(...e),this.fetchOptions.header={Accept:"application/vnd.quantized-mesh,application/octet-stream;q=0.9"}}loadAsync(...e){let{fetchOptions:t}=this;return t.header=t.header||{},t.header.Accept="application/vnd.quantized-mesh,application/octet-stream;q=0.9",t.header.Accept+=";extensions=octvertexnormals-watermask-metadata",super.loadAsync(...e)}parse(e){let t=0,n=new DataView(e),r=()=>{let e=n.getFloat64(t,!0);return t+=8,e},i=()=>{let e=n.getFloat32(t,!0);return t+=4,e},s=()=>{let e=n.getUint32(t,!0);return t+=4,e},a=()=>{let e=n.getUint8(t);return t+=1,e},o=(n,r)=>{let i=new r(e,t,n);return t+=n*r.BYTES_PER_ELEMENT,i},l={center:[r(),r(),r()],minHeight:i(),maxHeight:i(),sphereCenter:[r(),r(),r()],sphereRadius:r(),horizonOcclusionPoint:[r(),r(),r()]},c=s(),u=o(c,Uint16Array),h=o(c,Uint16Array),d=o(c,Uint16Array),p=new Float32Array(c),m=new Float32Array(c),f=new Float32Array(c),g=0,x=0,y=0,v=32767;for(let P=0;P<c;++P)g+=Mh(u[P]),x+=Mh(h[P]),y+=Mh(d[P]),p[P]=g/v,m[P]=x/v,f[P]=y/v;let b=c>65536,w=b?Uint32Array:Uint16Array;t=b?4*Math.ceil(t/4):2*Math.ceil(t/2);let T=o(3*s(),w),S=0;for(var _=0;_<T.length;++_){let e=T[_];T[_]=S-e,0===e&&++S}let M=(e,t)=>m[t]-m[e],A=(e,t)=>p[e]-p[t],E=o(s(),w);E.sort(M);let C=o(s(),w);C.sort(A);let R=o(s(),w);R.sort(((e,t)=>-M(e,t)));let D=o(s(),w);D.sort(((e,t)=>-A(e,t)));let k={westIndices:E,southIndices:C,eastIndices:R,northIndices:D},I={};for(;t<n.byteLength;){let e=a(),t=s();if(1===e){let t=o(2*c,Uint8Array),n=new Float32Array(3*c);for(let e=0;e<c;e++){let r=t[2*e+0]/255*2-1,i=t[2*e+1]/255*2-1,s=1-(Math.abs(r)+Math.abs(i));if(s<0){let e=r;r=(1-Math.abs(i))*Eh(e),i=(1-Math.abs(e))*Eh(i)}let a=Math.sqrt(r*r+i*i+s*s);n[3*e+0]=r/a,n[3*e+1]=i/a,n[3*e+2]=s/a}I.octvertexnormals={extensionId:e,normals:n}}else if(2===e){let n=1===t?1:256;I.watermask={extensionId:e,mask:o(n*n,Uint8Array),size:n}}else if(4===e){let t=o(s(),Uint8Array),n=(new TextDecoder).decode(t);I.metadata={extensionId:e,json:JSON.parse(n)}}}return{header:l,indices:T,vertexData:{u:p,v:m,height:f},edgeIndices:k,extensions:I}}};function Eh(e){return e<0?-1:1}var Ch=new r.Vector3,Rh=new r.Vector3;var Dh=class{get isMercator(){return"EPSG:3857"===this.scheme}get isCartographic(){return"none"!==this.scheme}constructor(e="EPSG:4326"){this.scheme=e,this.tileCountX=1,this.tileCountY=1,this.setScheme(e)}setScheme(e){switch(this.scheme=e,e){case"CRS:84":case"EPSG:4326":this.tileCountX=2,this.tileCountY=1;break;case"EPSG:3857":case"none":this.tileCountX=1,this.tileCountY=1;break;default:throw Error(`ProjectionScheme: Unknown projection scheme "${e}"`)}}convertNormalizedToLatitude(e){if("none"===this.scheme)return e;if(this.isMercator){let t=r.MathUtils.mapLinear(e,0,1,-1,1);return 2*Math.atan(Math.exp(t*Math.PI))-Math.PI/2}return r.MathUtils.mapLinear(e,0,1,-Math.PI/2,Math.PI/2)}convertNormalizedToLongitude(e){return"none"===this.scheme?e:r.MathUtils.mapLinear(e,0,1,-Math.PI,Math.PI)}convertLatitudeToNormalized(e){return"none"===this.scheme?e:this.isMercator?.5+1*Math.log(Math.tan(Math.PI/4+e/2))/(2*Math.PI):r.MathUtils.mapLinear(e,-Math.PI/2,Math.PI/2,0,1)}convertLongitudeToNormalized(e){return"none"===this.scheme?e:(e+Math.PI)/(2*Math.PI)}getLongitudeDerivativeAtNormalized(e){return"none"===this.scheme?1:2*Math.PI}getLatitudeDerivativeAtNormalized(e){if("none"===this.scheme)return 1;{let t=1e-5,n=e-t;return n<0&&(n=e+t),this.isMercator?Math.abs(this.convertNormalizedToLatitude(e)-this.convertNormalizedToLatitude(n))/t:Math.PI}}getBounds(){return"none"===this.scheme?[0,0,1,1]:[this.convertNormalizedToLongitude(0),this.convertNormalizedToLatitude(0),this.convertNormalizedToLongitude(1),this.convertNormalizedToLatitude(1)]}toNormalizedPoint(e,t){let n=[e,t];return n[0]=this.convertLongitudeToNormalized(n[0]),n[1]=this.convertLatitudeToNormalized(n[1]),n}toNormalizedRange(e){return[...this.toNormalizedPoint(e[0],e[1]),...this.toNormalizedPoint(e[2],e[3])]}toCartographicPoint(e,t){let n=[e,t];return n[0]=this.convertNormalizedToLongitude(n[0]),n[1]=this.convertNormalizedToLatitude(n[1]),n}toCartographicRange(e){return[...this.toCartographicPoint(e[0],e[1]),...this.toCartographicPoint(e[2],e[3])]}clampToBounds(e,t=!1){let n,i=[...e];n=t?[0,0,1,1]:this.getBounds();let[s,a,o,l]=n;return i[0]=r.MathUtils.clamp(i[0],s,o),i[2]=r.MathUtils.clamp(i[2],s,o),i[1]=r.MathUtils.clamp(i[1],a,l),i[3]=r.MathUtils.clamp(i[3],a,l),i}};function kh(e,t){let[n,r,i,s]=e,[a,o,l,c]=t;return!(n>=l||i<=a||r>=c||s<=o)}var Ih=class{get levelCount(){return this._levels.length}get maxLevel(){return this.levelCount-1}get minLevel(){let e=this._levels;for(let t=0;t<e.length;t++)if(null!==e[t])return t;return-1}get contentBounds(){return this._contentBounds??this.projection.getBounds()}get aspectRatio(){let{pixelWidth:e,pixelHeight:t}=this.getLevel(this.maxLevel);return e/t}constructor(){this.flipY=!1,this.pixelOverlap=0,this._contentBounds=null,this.projection=new Dh("none"),this._levels=[]}setLevel(e,t={}){let n=this._levels;for(;n.length<e;)n.push(null);let{tileSplitX:r=2,tileSplitY:i=2}=t,{tilePixelWidth:s=256,tilePixelHeight:a=256,tileCountX:o=r**e,tileCountY:l=i**e,tileBounds:c=null}=t,{pixelWidth:u=s*o,pixelHeight:h=a*l}=t;n[e]={tilePixelWidth:s,tilePixelHeight:a,pixelWidth:u,pixelHeight:h,tileCountX:o,tileCountY:l,tileSplitX:r,tileSplitY:i,tileBounds:c}}generateLevels(e,t,n,r={}){let{minLevel:i=0,tilePixelWidth:s=256,tilePixelHeight:a=256}=r,o=e-1,{pixelWidth:l=s*t*2**o,pixelHeight:c=a*n*2**o}=r;for(let u=i;u<e;u++){let t=e-u-1,n=Math.ceil(l*2**-t),r=Math.ceil(c*2**-t),i=Math.ceil(n/s),o=Math.ceil(r/a);this.setLevel(u,{tilePixelWidth:s,tilePixelHeight:a,pixelWidth:n,pixelHeight:r,tileCountX:i,tileCountY:o})}}getLevel(e){return this._levels[e]}setContentBounds(e,t,n,r){this._contentBounds=[e,t,n,r]}setProjection(e){this.projection=e}getTileAtPoint(e,t,n,i=!1){let{flipY:s}=this,{tileCountY:a,tileBounds:o,pixelHeight:l,pixelWidth:c,tilePixelHeight:u,tilePixelWidth:h}=this.getLevel(n),d=h/c,p=u/l;if(i||([e,t]=this.toNormalizedPoint(e,t)),o){let n=this.toNormalizedRange(o);e=r.MathUtils.mapLinear(e,n[0],n[2],0,1),t=r.MathUtils.mapLinear(t,n[1],n[3],0,1)}let m=Math.floor(e/d),f=Math.floor(t/p);return s&&(f=a-1-f),[m,f]}getTilesInRange(e,t,n,i,s,a=!1){let o=[e,t,n,i],l=this.getContentBounds(a),c=this.getLevel(s).tileBounds;if(!kh(o,l)||c&&(a&&(c=this.toNormalizedRange(c)),!kh(o,l)))return[0,0,-1,-1];let[u,h,d,p]=this.clampToContentBounds(o,a),m=this.getTileAtPoint(u,h,s,a),f=this.getTileAtPoint(d,p,s,a);this.flipY&&([m[1],f[1]]=[f[1],m[1]]);let{tileCountX:g,tileCountY:x}=this.getLevel(s),[y,v]=m,[b,w]=f;return b<0||w<0||y>=g||v>=x?[0,0,-1,-1]:[r.MathUtils.clamp(y,0,g-1),r.MathUtils.clamp(v,0,x-1),r.MathUtils.clamp(b,0,g-1),r.MathUtils.clamp(w,0,x-1)]}getTileExists(e,t,n){let[r,i,s,a]=this.contentBounds,[o,l,c,u]=this.getTileBounds(e,t,n);return!(o>=c||l>=u)&&o<=s&&l<=a&&c>=r&&u>=i}getContentBounds(e=!1){let{projection:t}=this,n=[...this.contentBounds];return e&&(n[0]=t.convertLongitudeToNormalized(n[0]),n[1]=t.convertLatitudeToNormalized(n[1]),n[2]=t.convertLongitudeToNormalized(n[2]),n[3]=t.convertLatitudeToNormalized(n[3])),n}getTileContentUVBounds(e,t,n){let[i,s,a,o]=this.getTileBounds(e,t,n,!0,!0),[l,c,u,h]=this.getTileBounds(e,t,n,!0,!1);return[r.MathUtils.mapLinear(i,l,u,0,1),r.MathUtils.mapLinear(s,c,h,0,1),r.MathUtils.mapLinear(a,l,u,0,1),r.MathUtils.mapLinear(o,c,h,0,1)]}getTileBounds(e,t,n,i=!1,s=!0){let{flipY:a,pixelOverlap:o,projection:l}=this,{tilePixelWidth:c,tilePixelHeight:u,pixelWidth:h,pixelHeight:d,tileBounds:p}=this.getLevel(n),m=c*e-o,f=u*t-o,g=m+c+2*o,x=f+u+2*o;if(m=Math.max(m,0),f=Math.max(f,0),g=Math.min(g,h),x=Math.min(x,d),m/=h,g/=h,f/=d,x/=d,a){let e=(x-f)/2,t=1-(f+x)/2;f=t-e,x=t+e}let y=[m,f,g,x];if(p){let e=this.toNormalizedRange(p);y[0]=r.MathUtils.mapLinear(y[0],0,1,e[0],e[2]),y[2]=r.MathUtils.mapLinear(y[2],0,1,e[0],e[2]),y[1]=r.MathUtils.mapLinear(y[1],0,1,e[1],e[3]),y[3]=r.MathUtils.mapLinear(y[3],0,1,e[1],e[3])}return s&&(y=this.clampToBounds(y,!0)),i||(y[0]=l.convertNormalizedToLongitude(y[0]),y[1]=l.convertNormalizedToLatitude(y[1]),y[2]=l.convertNormalizedToLongitude(y[2]),y[3]=l.convertNormalizedToLatitude(y[3])),y}toNormalizedPoint(e,t){return this.projection.toNormalizedPoint(e,t)}toNormalizedRange(e){return this.projection.toNormalizedRange(e)}toCartographicPoint(e,t){return this.projection.toCartographicPoint(e,t)}toCartographicRange(e){return this.projection.toCartographicRange(e)}clampToContentBounds(e,t=!1){let n=[...e],[i,s,a,o]=this.getContentBounds(t);return n[0]=r.MathUtils.clamp(n[0],i,a),n[1]=r.MathUtils.clamp(n[1],s,o),n[2]=r.MathUtils.clamp(n[2],i,a),n[3]=r.MathUtils.clamp(n[3],s,o),n}clampToBounds(e,t=!1){return this.projection.clampToBounds(e,t)}},Ph=Symbol("TILE_X"),Lh=Symbol("TILE_Y"),Uh=Symbol("TILE_LEVEL"),Fh=Symbol("OVERLAY_RANGE"),zh=Symbol("OVERLAY_LEVEL"),Bh=new r.Vector3,Vh=new r.Vector3,Oh=new r.Sphere,Nh=class{constructor(e={}){let{overlay:t=null,shape:n="ellipsoid",endCaps:r=!0,center:i=!0,useRecommendedSettings:s=!0,applyOverlayTexture:a=!1}=e;this.priority=-10,this.tiles=null,this.overlay=t,this.shape=n,this.endCaps=r,this.center=i,this.useRecommendedSettings=s,this.applyOverlayTexture=a,this._tiling=null}init(e){this.useRecommendedSettings&&(e.errorTarget=1),this.tiles=e}async loadRootTileset(){let{overlay:e}=this;return e?(await e.init(),this._tiling=e.tiling||this._createDefaultTiling()):this._tiling=this._createDefaultTiling(),this.getTileset()}async parseToMesh(e,t,n,r,i){if("generated_surface"!==n)return null;let s;s=this._useEllipsoid()?this._createEllipsoidMesh(t):this._createPlanarMesh(t);let{overlay:a,applyOverlayTexture:o}=this;if(a&&o){let e=t[Ph],n=t[Lh],r=t[Uh],o=this._tiling.getTileBounds(e,n,r,!0,!1);if(a.hasContent(o,r)){try{await a.lockTexture(o,r)}catch(l){if("AbortError"!==l.name)throw l;return null}let e=a.getTexture(o,r);if(t[Fh]=o,t[zh]=r,i.aborted)return a.releaseTexture(o,r),delete t[Fh],delete t[zh],null;s.material.map=e,s.material.needsUpdate=!0}}return s}preprocessNode(e){let t=this._tiling.maxLevel;e[Uh]<t&&null!==e.parent&&this.expandChildren(e)}disposeTile(e){let t=e[Fh];this.overlay&&t&&(this.overlay.releaseTexture(t,e[zh]),delete e[Fh],delete e[zh])}dispose(){this.tiles.forEachLoadedModel(((e,t)=>{this.disposeTile(t)}))}getCartographicFromPosition(e,t={}){let{_tiling:n}=this,{projection:r}=n;if(!r.isCartographic)throw Error("GeneratedSurfacePlugin: getCartographicFromPosition requires a cartographic projection.");if(this._useEllipsoid())return this.tiles.ellipsoid.getPositionToCartographic(e,t);let{center:i}=this,s=e.x/n.aspectRatio+(i?.5:0),a=e.y+(i?.5:0);return t.lat=r.convertNormalizedToLatitude(a),t.lon=r.convertNormalizedToLongitude(s),t}getPositionFromCartographic(e,t,n=new r.Vector3){let{_tiling:i}=this,{projection:s}=i;if(!s.isCartographic)throw Error("GeneratedSurfacePlugin: getPositionFromCartographic requires a cartographic projection.");if(this._useEllipsoid())return this.tiles.ellipsoid.getCartographicToPosition(e,t,0,n);let{center:a}=this,o=s.convertLongitudeToNormalized(t),l=s.convertLatitudeToNormalized(e);return n.x=(o-(a?.5:0))*i.aspectRatio,n.y=l-(a?.5:0),n.z=0,n}_useEllipsoid(){return this._tiling.projection.isCartographic&&"ellipsoid"===this.shape}_createPlanarMesh(e){let t=e[Ph],n=e[Lh],i=e[Uh],s=e.boundingVolume.box,a=1,o=1,l=0,c=0,u=0;s&&([l,c,u]=s,a=s[3],o=s[7]);let h=new r.PlaneGeometry(2*a,2*o),d=new r.Mesh(h,new r.MeshBasicMaterial);d.position.set(l,c,u);let p=this._tiling.getTileContentUVBounds(t,n,i),{uv:m}=h.attributes;for(let f=0;f<m.count;f++)m.setXY(f,r.MathUtils.mapLinear(m.getX(f),0,1,p[0],p[2]),r.MathUtils.mapLinear(m.getY(f),0,1,p[1],p[3]));return d}_createEllipsoidMesh(e){let{tiles:t,endCaps:n,_tiling:i}=this,{projection:s}=i,a=e[Uh],o=e[Ph],l=e[Lh],[c,u,h,d]=e.boundingVolume.region,p=Math.max(15,Math.ceil((d-u)*r.MathUtils.RAD2DEG*.25)),m=Math.max(30,Math.ceil((h-c)*r.MathUtils.RAD2DEG*.25)),f=m+3,g=p+3,x=new r.PlaneGeometry(1,1,m+2,p+2),[y,v,b,w]=i.getTileBounds(o,l,a,!0,!0),T=i.getTileContentUVBounds(o,l,a),{position:S,normal:_,uv:M}=x.attributes,A=S.count;e.engineData.boundingVolume.getSphere(Oh);for(let C=0;C<A;C++){let i=C%f,a=Math.floor(C/f),o=0===i||i===f-1||0===a||a===g-1,l=(Math.max(1,Math.min(f-2,i))-1)/m,c=1-(Math.max(1,Math.min(g-2,a))-1)/p,h=s.convertNormalizedToLongitude(r.MathUtils.mapLinear(l,0,1,y,b)),x=s.convertNormalizedToLatitude(r.MathUtils.mapLinear(c,0,1,v,w));if(s.isMercator&&n&&(1===w&&1===c&&(x=Math.PI/2),0===v&&0===c&&(x=-Math.PI/2)),s.isMercator&&0!==c&&1!==c){let e=s.convertNormalizedToLatitude(1),t=1/p,n=r.MathUtils.mapLinear(c-t,0,1,u,d),i=r.MathUtils.mapLinear(c+t,0,1,u,d);x>e&&n<e&&(x=e),x<-e&&i>-e&&(x=-e)}t.ellipsoid.getCartographicToPosition(x,h,0,Bh).sub(Oh.center),t.ellipsoid.getCartographicToNormal(x,h,Vh),o&&Bh.addScaledVector(Vh,-e.geometricError);let A=r.MathUtils.mapLinear(s.convertLongitudeToNormalized(h),y,b,T[0],T[2]),E=r.MathUtils.mapLinear(s.convertLatitudeToNormalized(x),v,w,T[1],T[3]);S.setXYZ(C,Bh.x,Bh.y,Bh.z),_.setXYZ(C,Vh.x,Vh.y,Vh.z),M.setXY(C,A,E)}let E=new r.Mesh(x,new r.MeshBasicMaterial);return E.position.copy(Oh.center),E}getTileset(){let{tiles:e,_tiling:t}=this,n=t.minLevel,{tileCountX:r,tileCountY:i}=t.getLevel(n),s=[];for(let o=0;o<r;o++)for(let e=0;e<i;e++){let t=this.createChild(o,e,n);null!==t&&s.push(t)}let a={asset:{version:"1.1"},geometricError:1/0,root:{refine:"REPLACE",geometricError:1/0,boundingVolume:this.createBoundingVolume(0,0,-1),children:s,[Uh]:-1,[Ph]:0,[Lh]:0}};return e.preprocessTileset(a,""),a}getUrl(){return"tile.generated_surface"}fetchData(e){if(/generated_surface/.test(e))return new ArrayBuffer}createBoundingVolume(e,t,n,r=0){let{_tiling:i}=this,s=-1===n;if(this._useEllipsoid()){let a,o,{endCaps:l}=this;return s?(a=i.getContentBounds(!0),o=i.getContentBounds()):(a=i.getTileBounds(e,t,n,!0,!0),o=i.getTileBounds(e,t,n,!1,!0)),l&&(1===a[3]&&(o[3]=Math.PI/2),0===a[1]&&(o[1]=-Math.PI/2)),{region:[...o,-r,1]}}{let r,{center:a}=this;r=s?i.getContentBounds(!0):i.getTileBounds(e,t,n,!0);let[o,l,c,u]=r,h=(c-o)/2,d=(u-l)/2,p=o+h,m=l+d;return a&&(p-=.5,m-=.5),p*=i.aspectRatio,h*=i.aspectRatio,{box:[p,m,0,h,0,0,0,d,0,0,0,0]}}}createChild(e,t,n){let{_tiling:r}=this,{projection:i}=r;if(!r.getTileExists(e,t,n))return null;let s,a=this._useEllipsoid();if(a){let[a,o,l,c]=r.getTileBounds(e,t,n,!0),{tilePixelWidth:u,tilePixelHeight:h}=r.getLevel(n),d=(l-a)/u,p=(c-o)/h,[,m,f,g]=r.getTileBounds(e,t,n),x=m>0==g>0?Math.min(Math.abs(m),Math.abs(g)):0,y=i.convertLatitudeToNormalized(x),v=i.getLongitudeDerivativeAtNormalized(a),b=i.getLatitudeDerivativeAtNormalized(y),[w,T]=function(e,t,n){let r=1e-5,i=n+r,s=t+r;Math.abs(s)>Math.PI/2&&(s-=r),e.getCartographicToPosition(t,n,0,Ch),e.getCartographicToPosition(s,n,0,Rh);let a=Ch.distanceTo(Rh)/r;return e.getCartographicToPosition(t,i,0,Rh),[Ch.distanceTo(Rh)/r,a]}(this.tiles.ellipsoid,x,f);s=Math.max(d*v*w,p*b*T)}else{let{pixelWidth:e,pixelHeight:t}=r.getLevel(n);s=Math.max(r.aspectRatio/e,1/t)}return{refine:"REPLACE",geometricError:s,boundingVolume:this.createBoundingVolume(e,t,n,a?s:0),content:{uri:this.getUrl(e,t,n)},children:[],[Ph]:e,[Lh]:t,[Uh]:n}}expandChildren(e){let t=e[Uh],n=e[Ph],r=e[Lh],{tileSplitX:i,tileSplitY:s}=this._tiling.getLevel(t);for(let a=0;a<i;a++)for(let o=0;o<s;o++){let l=this.createChild(i*n+a,s*r+o,t+1);l&&e.children.push(l)}}_createDefaultTiling(){let e=new Ih;if("ellipsoid"===this.shape){let t=new Dh("EPSG:3857");e.setProjection(t),e.generateLevels(20,t.tileCountX,t.tileCountY)}else{let t=new Dh("none");e.setProjection(t),e.generateLevels(20,1,1)}return e}},$h=class extends DOMException{constructor(){super("DataCache: Item removed","AbortError")}};function Gh(...e){return e.join("_")}var qh=class{constructor(){this.cache={},this.count=0,this.cachedBytes=0,this.active=0}fetchItem(e,t){}disposeItem(e,t){}getMemoryUsage(e){return 0}setData(...e){let{cache:t}=this,n=e.pop(),r=Gh(...e);if(r in t)throw Error(`DataCache: "${r}" is already present.`);return this.cache[r]={abortController:new AbortController,result:n,count:1,bytes:this.getMemoryUsage(n)},this.count++,this.cachedBytes+=this.cache[r].bytes,n}lock(...e){let{cache:t}=this,n=Gh(...e);if(n in t)t[n].count++;else{let t=new AbortController,r={abortController:t,result:null,count:1,bytes:0,args:e};this.active++,r.result=this.fetchItem(e,t.signal),r.result instanceof Promise?r.result=r.result.then((e=>(t.signal.throwIfAborted(),r.result=e,r.bytes=this.getMemoryUsage(e),this.cachedBytes+=r.bytes,e))).finally((()=>{this.active--})):(this.active--,r.bytes=this.getMemoryUsage(r.result),this.cachedBytes+=r.bytes),this.cache[n]=r,this.count++}return t[n].result}release(...e){let t=Gh(...e);this.releaseViaFullKey(t)}get(...e){let{cache:t}=this,n=Gh(...e);return n in t&&t[n].count>0?t[n].result:null}has(...e){let{cache:t}=this;return Gh(...e)in t}forEachItem(e){let{cache:t}=this;for(let n in t){let r=t[n];r.result instanceof Promise||e(r.result,r.args)}}dispose(){let{cache:e}=this;for(let t in e){let{abortController:n}=e[t];n.abort(new $h),this.releaseViaFullKey(t,!0)}this.cache={}}releaseViaFullKey(e,t=!1){let{cache:n}=this;if(e in n&&n[e].count>0){let r=n[e];if(r.count--,0===r.count||t){let i=()=>{if(n[e]!==r)return;let{result:t,abortController:i}=r;i.abort(new $h),t instanceof Promise?t.then((e=>{this.disposeItem(e,r.args)})).catch((()=>{this.disposeItem(null,r.args)})).finally((()=>{this.count--,this.cachedBytes-=r.bytes})):(this.disposeItem(t,r.args),this.count--,this.cachedBytes-=r.bytes),delete n[e]};t?i():queueMicrotask((()=>{0===r.count&&i()}))}return!0}throw Error("DataCache: Attempting to release key that does not exist")}},Hh=class extends qh{constructor(e={}){super();let{fetchOptions:t={}}=e;this.tiling=new Ih,this.fetchOptions=t,this.fetchData=(...e)=>fetch(...e)}init(){}async processBufferToTexture(e){let t=new Blob([e]),n=new r.Texture(await createImageBitmap(t,{premultiplyAlpha:"none",colorSpaceConversion:"none",imageOrientation:"flipY"}));return n.generateMipmaps=!1,n.colorSpace=r.SRGBColorSpace,n.needsUpdate=!0,n}getMemoryUsage(e){let{format:t,type:n,image:i,generateMipmaps:s}=e,{width:a,height:o}=i,l=r.TextureUtils.getByteLength(a,o,t,n);return s?4*l/3:l}fetchItem(e,t){let n={...this.fetchOptions,signal:t},r=this.getUrl(...e);return this.fetchData(r,n).then((e=>e.arrayBuffer())).then((e=>this.processBufferToTexture(e)))}disposeItem(e){e&&(e.dispose(),e.image instanceof ImageBitmap&&e.image.close())}getUrl(...e){}},jh=class extends Hh{constructor(e={}){let{url:t=null,...n}=e;super(n),this.tileSets=null,this.extension=null,this.url=t}getUrl(e,t,n){let{url:r,extension:i,tileSets:s,tiling:a}=this;return new URL(`${parseInt(s[n-a.minLevel].href)}/${e}/${t}.${i}`,r).toString()}init(){let{url:e}=this;return this.fetchData(new URL("tilemapresource.xml",e),this.fetchOptions).then((e=>e.text())).then((t=>{let{tiling:n}=this,i=(new DOMParser).parseFromString(t,"text/xml"),s=i.querySelector("BoundingBox"),a=i.querySelector("TileFormat"),o=[...i.querySelector("TileSets").querySelectorAll("TileSet")].map((e=>({href:parseInt(e.getAttribute("href")),unitsPerPixel:parseFloat(e.getAttribute("units-per-pixel")),order:parseInt(e.getAttribute("order"))}))).sort(((e,t)=>e.order-t.order)),l=parseFloat(s.getAttribute("minx"))*r.MathUtils.DEG2RAD,c=parseFloat(s.getAttribute("maxx"))*r.MathUtils.DEG2RAD,u=parseFloat(s.getAttribute("miny"))*r.MathUtils.DEG2RAD,h=parseFloat(s.getAttribute("maxy"))*r.MathUtils.DEG2RAD,d=parseInt(a.getAttribute("width")),p=parseInt(a.getAttribute("height")),m=a.getAttribute("extension"),f=i.querySelector("SRS").textContent;this.extension=m,this.url=e,this.tileSets=o,n.setProjection(new Dh(f)),n.setContentBounds(l,u,c,h),o.forEach((({order:e})=>{n.setLevel(e,{tileCountX:n.projection.tileCountX*2**e,tilePixelWidth:d,tilePixelHeight:p})}))}))}};function Wh(e,t,n,r){let[i,s,a,o]=e;s+=1e-8,i+=1e-8,o-=1e-8,a-=1e-8;let l=Math.max(Math.min(t,n.maxLevel),n.minLevel),[c,u,h,d]=n.getTilesInRange(i,s,a,o,l,!0);for(let p=c;p<=h;p++)for(let e=u;e<=d;e++)r(p,e,l)}var Xh=["a","b","c"],Yh=new r.Vector4,Kh=new r.Vector4,Qh=new r.Vector4,Zh=new r.Vector4,Jh=class{constructor(){this.attributeList=null,this.splitOperations=[],this.trianglePool=new ed}forEachSplitPermutation(e){let{splitOperations:t}=this,n=(r=0)=>{r>=t.length?e():(t[r].keepPositive=!0,n(r+1),t[r].keepPositive=!1,n(r+1))};n()}addSplitOperation(e,t=!0){this.splitOperations.push({callback:e,keepPositive:t})}clearSplitOperations(){this.splitOperations.length=0}clipObject(e){let t=e.clone(),n=[];return t.traverse((e=>{e.isMesh&&(e.geometry=this.clip(e).geometry,0==(e.geometry.index?e.geometry.index.count/3:e.attributes.position.count/3)&&n.push(e))})),n.forEach((e=>{e.removeFromParent()})),t}clip(e,t=null){let n=this.getClippedData(e,t);return this.constructMesh(n.attributes,n.index,e)}getClippedData(e,t=null,n={}){let{trianglePool:r,splitOperations:i,attributeList:s}=this,a=e.geometry,o=a.attributes.position,l=a.index,c=0,u={};n.index=n.index||[],n.vertexIsClipped=n.vertexIsClipped||[],n.attributes=n.attributes||{};for(let m in a.attributes)null!==s&&(s instanceof Function&&!s(m)||Array.isArray(s)&&!s.includes(m))||(n.attributes[m]=[]);let h=0,d=l?l.count:o.count;null!==t&&(h=t.start,d=t.count);for(let m=h,f=h+d;m<f;m+=3){let t=m+0,n=m+1,s=m+2;l&&(t=l.getX(t),n=l.getX(n),s=l.getX(s));let o=r.get();o.initFromIndices(t,n,s);let c=[o];for(let r=0;r<i.length;r++){let{keepPositive:t,callback:n}=i[r],s=[];for(let r=0;r<c.length;r++){let i=c[r],{indices:o,barycoord:l}=i;i.clipValues.a=n(a,o.a,o.b,o.c,l.a,e.matrixWorld),i.clipValues.b=n(a,o.a,o.b,o.c,l.b,e.matrixWorld),i.clipValues.c=n(a,o.a,o.b,o.c,l.c,e.matrixWorld),this.splitTriangle(i,!t,s)}c=s}for(let e=0,r=c.length;e<r;e++){p(c[e],a)}r.reset()}return n;function p(e,t){for(let r=0;r<3;r++){let i=e.getVertexHash(r,t);i in u||(u[i]=c,c++,e.getVertexData(r,t,n.attributes),n.vertexIsClipped.push(0===e.clipValues[Xh[r]]));let s=u[i];n.index.push(s)}}}constructMesh(e,t,n){let i=n.geometry,s=new r.BufferGeometry,a=e.position.length/3>65535?new Uint32Array(t):new Uint16Array(t);s.setIndex(new r.BufferAttribute(a,1,!1));for(let l in e){let t=i.getAttribute(l),n=new r.BufferAttribute(new t.array.constructor(e[l]),t.itemSize,t.normalized);n.gpuType=t.gpuType,s.setAttribute(l,n)}let o=new r.Mesh(s,n.material.clone());return o.position.copy(n.position),o.quaternion.copy(n.quaternion),o.scale.copy(n.scale),o}splitTriangle(e,t,n){let{trianglePool:i}=this,s=[],a=[],o=[];for(let l=0;l<3;l++){let t=Xh[l],n=Xh[(l+1)%3],i=e.clipValues[t],c=e.clipValues[n];(i<0!=c<0||0===i)&&(s.push(l),a.push([t,n]),i===c?o.push(0):o.push(r.MathUtils.mapLinear(0,i,c,0,1)))}if(2!==s.length)Math.min(e.clipValues.a,e.clipValues.b,e.clipValues.c)<0===t&&n.push(e);else if(2===s.length){let r,l,c=i.get().initFromTriangle(e),u=i.get().initFromTriangle(e),h=i.get().initFromTriangle(e);(s[0]+1)%3===s[1]?(c.lerpVertexFromEdge(e,a[0][0],a[0][1],o[0],"a"),c.copyVertex(e,a[0][1],"b"),c.lerpVertexFromEdge(e,a[1][0],a[1][1],o[1],"c"),c.clipValues.a=0,c.clipValues.c=0,u.lerpVertexFromEdge(e,a[0][0],a[0][1],o[0],"a"),u.copyVertex(e,a[1][1],"b"),u.copyVertex(e,a[0][0],"c"),u.clipValues.a=0,h.lerpVertexFromEdge(e,a[0][0],a[0][1],o[0],"a"),h.lerpVertexFromEdge(e,a[1][0],a[1][1],o[1],"b"),h.copyVertex(e,a[1][1],"c"),h.clipValues.a=0,h.clipValues.b=0):(c.lerpVertexFromEdge(e,a[0][0],a[0][1],o[0],"a"),c.lerpVertexFromEdge(e,a[1][0],a[1][1],o[1],"b"),c.copyVertex(e,a[0][0],"c"),c.clipValues.a=0,c.clipValues.b=0,u.lerpVertexFromEdge(e,a[0][0],a[0][1],o[0],"a"),u.copyVertex(e,a[0][1],"b"),u.lerpVertexFromEdge(e,a[1][0],a[1][1],o[1],"c"),u.clipValues.a=0,u.clipValues.c=0,h.copyVertex(e,a[0][1],"a"),h.copyVertex(e,a[1][0],"b"),h.lerpVertexFromEdge(e,a[1][0],a[1][1],o[1],"c"),h.clipValues.c=0),r=Math.min(c.clipValues.a,c.clipValues.b,c.clipValues.c),l=r<0,l===t&&n.push(c),r=Math.min(u.clipValues.a,u.clipValues.b,u.clipValues.c),l=r<0,l===t&&n.push(u),r=Math.min(h.clipValues.a,h.clipValues.b,h.clipValues.c),l=r<0,l===t&&n.push(h)}}},ed=class{constructor(){this.pool=[],this.index=0}get(){if(this.index>=this.pool.length){let e=new td;this.pool.push(e)}let e=this.pool[this.index];return this.index++,e}reset(){this.index=0}},td=class{constructor(){this.indices={a:-1,b:-1,c:-1},this.clipValues={a:-1,b:-1,c:-1},this.barycoord=new r.Triangle}getVertexHash(e,t){let{barycoord:n,indices:r}=this,i=n[Xh[e]];if(1===i.x)return r[Xh[0]];if(1===i.y)return r[Xh[1]];if(1===i.z)return r[Xh[2]];{let{attributes:e}=t,n="";for(let t in e){let s=e[t];switch(nd(s,r.a,r.b,r.c,i,Yh),("normal"===t||"tangent"===t||"bitangent"===t)&&Yh.normalize(),s.itemSize){case 4:n+=rd(Yh.x,Yh.y,Yh.z,Yh.w);break;case 3:n+=rd(Yh.x,Yh.y,Yh.z);break;case 2:n+=rd(Yh.x,Yh.y);break;case 1:n+=rd(Yh.x)}n+="|"}return n}}getVertexData(e,t,n){let{barycoord:r,indices:i}=this,s=r[Xh[e]],{attributes:a}=t;for(let o in a){if(!n[o])continue;let e=a[o],t=n[o];switch(nd(e,i.a,i.b,i.c,s,Yh),("normal"===o||"tangent"===o||"bitangent"===o)&&Yh.normalize(),e.itemSize){case 4:t.push(Yh.x,Yh.y,Yh.z,Yh.w);break;case 3:t.push(Yh.x,Yh.y,Yh.z);break;case 2:t.push(Yh.x,Yh.y);break;case 1:t.push(Yh.x)}}}initFromTriangle(e){return this.initFromIndices(e.indices.a,e.indices.b,e.indices.c)}initFromIndices(e,t,n){return this.indices.a=e,this.indices.b=t,this.indices.c=n,this.clipValues.a=-1,this.clipValues.b=-1,this.clipValues.c=-1,this.barycoord.a.set(1,0,0),this.barycoord.b.set(0,1,0),this.barycoord.c.set(0,0,1),this}lerpVertexFromEdge(e,t,n,i,s){this.clipValues[s]=r.MathUtils.lerp(e.clipValues[t],e.clipValues[n],i),this.barycoord[s].lerpVectors(e.barycoord[t],e.barycoord[n],i)}copyVertex(e,t,n){this.clipValues[n]=e.clipValues[t],this.barycoord[n].copy(e.barycoord[t])}};function nd(e,t,n,r,i,s){switch(Kh.fromBufferAttribute(e,t),Qh.fromBufferAttribute(e,n),Zh.fromBufferAttribute(e,r),s.set(0,0,0,0).addScaledVector(Kh,i.x).addScaledVector(Qh,i.y).addScaledVector(Zh,i.z),e.itemSize){case 3:Yh.w=0;break;case 2:Yh.w=0,Yh.z=0;break;case 1:Yh.w=0,Yh.z=0,Yh.y=0}return s}function rd(...e){let t="";for(let n=0,r=e.length;n<r;n++)t+=~~(1e5*e[n]+.5),n!==r-1&&(t+="_");return t}var id=class{constructor(){this.canvas=null,this.context=null,this.range=[0,0,1,1]}setTarget(e,t){this.canvas=e.image,this.context=e.image.getContext("2d"),this.range=[...t]}draw(e,t){let{canvas:n,range:i,context:s}=this,{width:a,height:o}=n,{image:l}=e,c=Math.round(r.MathUtils.mapLinear(t[0],i[0],i[2],0,a)),u=Math.round(r.MathUtils.mapLinear(t[1],i[1],i[3],0,o)),h=Math.round(r.MathUtils.mapLinear(t[2],i[0],i[2],0,a))-c,d=Math.round(r.MathUtils.mapLinear(t[3],i[1],i[3],0,o))-u;l instanceof ImageBitmap?(s.save(),s.translate(c,o-u),s.scale(1,-1),s.drawImage(l,0,0,h,d),s.restore()):s.drawImage(l,c,o-u,h,-d)}clear(){let{context:e,canvas:t}=this;e.clearRect(0,0,t.width,t.height)}};var sd=class extends qh{hasContent(...e){return!0}},ad=class extends sd{constructor(e){super(),this.tiledImageSource=e,this.tileComposer=new id,this.resolution=256}hasContent(e,t,n,r,i){let s=this.tiledImageSource.tiling,a=0;return Wh([e,t,n,r],i,s,(()=>{a++})),0!==a}async fetchItem([e,t,n,i,s],a){let{tiledImageSource:o,tileComposer:l}=this,c=[e,t,n,i],u=o.tiling;await this._markImages(c,s,!1),null==a||a.throwIfAborted();let h=null;if(Wh(c,s,u,((e,t,n)=>{(function(e,t,n=0){if(e.length!==t.length)return!1;for(let r=0,i=e.length;r<i;r++)if(Math.abs(e[r]-t[r])>n)return!1;return!0})(u.getTileBounds(e,t,n,!0,!1),c,1e-10)&&(h=[e,t,n])})),null!==h){let[e,t,n]=h;return o.get(e,t,n).clone()}let d=document.createElement("canvas");d.width=this.resolution,d.height=this.resolution;let p=new r.CanvasTexture(d);return p.colorSpace=r.SRGBColorSpace,p.generateMipmaps=!1,l.setTarget(p,c),l.clear(16777215,0),Wh(c,s,u,((e,t,n)=>{let r=u.getTileBounds(e,t,n,!0,!1),i=o.get(e,t,n);l.draw(i,r)})),p}disposeItem(e,[t,n,r,i,s]){e&&e.dispose(),this._markImages([t,n,r,i],s,!0)}dispose(){super.dispose(),this.tiledImageSource.dispose()}_markImages(e,t,n=!1){let r=this.tiledImageSource,i=r.tiling,s=[];Wh(e,t,i,((e,t,i)=>{n?r.release(e,t,i):s.push(r.lock(e,t,i))}));let a=s.filter((e=>e instanceof Promise));return 0===a.length?null:Promise.all(a)}},od=new Ol;od.maxJobs=10,od.priorityCallback=(e,t)=>{let n=e.tile,r=t.tile,i=n.internal.renderer,s=r.internal.renderer,a=i.visibleTiles.has(n);return a===s.visibleTiles.has(r)?cc(n,r):a?1:-1};var ld=class{get isPlanarProjection(){return!!this.frame}constructor(e={}){let{opacity:t=1,color:n=16777215,frame:i=null,preprocessURL:s=null,alphaMask:a=!1,alphaInvert:o=!1}=e;this.preprocessURL=s,this.opacity=t,this.color=new r.Color(n),this.frame=null===i?null:i.clone(),this.alphaMask=a,this.alphaInvert=o,this.downloadQueue=hc,this._whenReady=null,this.isReady=!1,this.isInitialized=!1,this._visibleRegionCounts=new Map}init(){return this.isInitialized||(this.isInitialized=!0,this._whenReady=this._init().then((()=>this.isReady=!0))),this._whenReady}whenReady(){return this._whenReady}_init(){return Promise.resolve()}fetch(e,t={}){this.preprocessURL&&(e=this.preprocessURL(e));let n={priority:-performance.now()},r=this.downloadQueue.add(n,(()=>fetch(e,t)));return t.signal&&t.signal.addEventListener("abort",(()=>this.downloadQueue.remove(n)),{once:!0}),r}getAttributions(e){}hasContent(e,t=null){return!1}async getTexture(e,t=null){return null}async lockTexture(e,t=null){return null}lockTextureSafe(e){let t=this.lockTexture(e);return t instanceof Promise&&t.catch((e=>{if("AbortError"!==e.name)throw e})),t}releaseTexture(e,t=null){}shouldSplit(e,t=null){return!1}setResolution(e){}setRegionVisible(e,t){let{_visibleRegionCounts:n}=this,r=e.join("_"),i=n.get(r);if(i||(i={range:[...e],count:0},n.set(r,i)),i.count+=t?1:-1,i.count<0)throw Error();0===i.count&&n.delete(r)}},cd=class extends ld{get tiling(){return this.imageSource.tiling}get projection(){return this.tiling.projection}get aspectRatio(){return this.tiling&&this.isReady?this.tiling.aspectRatio:1}get fetchOptions(){return this.imageSource.fetchOptions}set fetchOptions(e){this.imageSource.fetchOptions=e}constructor(e={}){let{imageSource:t=null,...n}=e;super(n),this.imageSource=t,this.regionImageSource=null}_init(){return this._initImageSource().then((()=>{this.imageSource.fetchData=(...e)=>this.fetch(...e),this.regionImageSource=new ad(this.imageSource)}))}_initImageSource(){return this.imageSource.init()}calculateLevel(e,t=null){let[n,r,i,s]=e,a=i-n,o=s-r;null===t&&(t=this.regionImageSource.resolution);let l=0,c=this.tiling.maxLevel;for(;l<c;l++){let e=t/a,n=t/o,r=this.tiling.getLevel(l);if(null==r)continue;let{pixelWidth:i,pixelHeight:s}=r;if(i>=e||s>=n)break}return l}hasContent(e,t=this.calculateLevel(e)){return this.regionImageSource.hasContent(...e,t)}getTexture(e,t=this.calculateLevel(e)){return this.regionImageSource.get(...e,t)}lockTexture(e,t=this.calculateLevel(e)){return this.regionImageSource.lock(...e,t)}releaseTexture(e,t=this.calculateLevel(e)){this.regionImageSource.release(...e,t)}shouldSplit(e,t=this.calculateLevel(e)){return this.tiling.maxLevel>t}setResolution(e){this.regionImageSource.resolution=e}},ud=class extends cd{constructor(e={}){super(e),this.imageSource=new jh(e)}},hd=new r.Vector3,dd=new r.Triangle,pd=new r.Vector3,md=new r.Vector3,fd=class extends Ah{constructor(e=r.DefaultLoadingManager){super(),this.manager=e,this.ellipsoid=new uu,this.skirtLength=1e3,this.smoothSkirtNormals=!0,this.generateNormals=!0,this.solid=!1,this.minLat=-Math.PI/2,this.maxLat=Math.PI/2,this.minLon=-Math.PI,this.maxLon=Math.PI}parse(e){let{ellipsoid:t,solid:n,skirtLength:i,smoothSkirtNormals:s,generateNormals:a,minLat:o,maxLat:l,minLon:c,maxLon:u}=this,{header:h,indices:d,vertexData:p,edgeIndices:m,extensions:f}=super.parse(e),g=new r.BufferGeometry,x=new r.MeshStandardMaterial,y=new r.Mesh(g,x);y.position.set(...h.center);let v="octvertexnormals"in f,b=v||a,w=p.u.length,T=[],S=[],_=[],M=[],A=0,E=0;for(let r=0;r<w;r++)R(r,pd),D(pd.x,pd.y,pd.z,md),S.push(pd.x,pd.y),T.push(...md);for(let r=0,I=d.length;r<I;r++)_.push(d[r]);if(b)if(v){let e=f.octvertexnormals.normals;for(let t=0,n=e.length;t<n;t++)M.push(e[t])}else{let e=new r.BufferGeometry,t=d.length>21845?new Uint32Array(d):new Uint16Array(d);e.setIndex(new r.BufferAttribute(t,1,!1)),e.setAttribute("position",new r.BufferAttribute(new Float32Array(T),3,!1)),e.computeVertexNormals();let n=e.getAttribute("normal").array;f.octvertexnormals={normals:n};for(let r=0,i=n.length;r<i;r++)M.push(n[r])}if(g.addGroup(A,d.length,E),A+=d.length,E++,n){let e=T.length/3;for(let t=0;t<w;t++)R(t,pd),D(pd.x,pd.y,pd.z,md,-i),S.push(pd.x,pd.y),T.push(...md);for(let t=d.length-1;t>=0;t--)_.push(d[t]+e);if(b){let e=f.octvertexnormals.normals;for(let t=0,n=e.length;t<n;t++)M.push(-e[t])}g.addGroup(A,d.length,E),A+=d.length,E++}if(i>0){let e,{westIndices:t,eastIndices:n,southIndices:r,northIndices:i}=m,s=k(t);e=T.length/3,S.push(...s.uv),T.push(...s.positions);for(let c=0,u=s.indices.length;c<u;c++)_.push(s.indices[c]+e);let a=k(n);e=T.length/3,S.push(...a.uv),T.push(...a.positions);for(let c=0,u=a.indices.length;c<u;c++)_.push(a.indices[c]+e);let o=k(r);e=T.length/3,S.push(...o.uv),T.push(...o.positions);for(let c=0,u=o.indices.length;c<u;c++)_.push(o.indices[c]+e);let l=k(i);e=T.length/3,S.push(...l.uv),T.push(...l.positions);for(let c=0,u=l.indices.length;c<u;c++)_.push(l.indices[c]+e);b&&(M.push(...s.normals),M.push(...a.normals),M.push(...o.normals),M.push(...l.normals)),g.addGroup(A,d.length,E),A+=d.length,E++}for(let r=0,I=T.length;r<I;r+=3)T[r+0]-=h.center[0],T[r+1]-=h.center[1],T[r+2]-=h.center[2];let C=T.length/3>65535?new Uint32Array(_):new Uint16Array(_);if(g.setIndex(new r.BufferAttribute(C,1,!1)),g.setAttribute("position",new r.BufferAttribute(new Float32Array(T),3,!1)),g.setAttribute("uv",new r.BufferAttribute(new Float32Array(S),2,!1)),b&&g.setAttribute("normal",new r.BufferAttribute(new Float32Array(M),3,!1)),"watermask"in f){let{mask:e,size:t}=f.watermask,n=new Uint8Array(2*t*t);for(let r=0,s=e.length;r<s;r++){let t=255===e[r]?0:255;n[2*r+0]=t,n[2*r+1]=t}let i=new r.DataTexture(n,t,t,r.RGFormat,r.UnsignedByteType);i.flipY=!0,i.minFilter=r.LinearMipMapLinearFilter,i.magFilter=r.LinearFilter,i.needsUpdate=!0,x.roughnessMap=i}return y.userData.minHeight=h.minHeight,y.userData.maxHeight=h.maxHeight,"metadata"in f&&(y.userData.metadata=f.metadata.json),y;function R(e,t){return t.x=p.u[e],t.y=p.v[e],t.z=p.height[e],t}function D(e,n,i,s,a=0){let d=r.MathUtils.lerp(h.minHeight,h.maxHeight,i),p=r.MathUtils.lerp(c,u,e),m=r.MathUtils.lerp(o,l,n);return t.getCartographicToPosition(m,p,d+a,s),s}function k(e){let t=[],n=[],r=[],a=[],o=[];for(let s=0,u=e.length;s<u;s++)R(e[s],pd),t.push(pd.x,pd.y),r.push(pd.x,pd.y),D(pd.x,pd.y,pd.z,md),n.push(...md),D(pd.x,pd.y,pd.z,md,-i),a.push(...md);let l=e.length-1;for(let i=0;i<l;i++){let t=i,n=i+1,r=i+e.length,s=i+e.length+1;o.push(t,r,n),o.push(n,r,s)}let c=null;if(b){let t=(n.length+a.length)/3;if(s){c=Array(3*t);let n=f.octvertexnormals.normals,r=c.length/2;for(let i=0,s=t/2;i<s;i++){let t=e[i],s=3*i,a=n[3*t+0],o=n[3*t+1],l=n[3*t+2];c[s+0]=a,c[s+1]=o,c[s+2]=l,c[r+s+0]=a,c[r+s+1]=o,c[r+s+2]=l}}else{c=[],dd.a.fromArray(n,0),dd.b.fromArray(a,0),dd.c.fromArray(n,3),dd.getNormal(hd);for(let e=0;e<t;e++)c.push(...hd)}}return{uv:[...t,...r],positions:[...n,...a],indices:o,normals:c}}}},gd={},xd=new r.Vector3,yd=new r.Vector3,vd=new r.Vector3,bd=new r.Vector3,wd=new r.Vector3,Td=new r.Vector3,Sd=new r.Vector3,_d=new r.Vector2,Md=new r.Vector2,Ad=new r.Vector2,Ed=class extends Jh{constructor(){super(),this.ellipsoid=new uu,this.skirtLength=1e3,this.smoothSkirtNormals=!0,this.solid=!1,this.minLat=-Math.PI/2,this.maxLat=Math.PI/2,this.minLon=-Math.PI,this.maxLon=Math.PI,this.attributeList=["position","normal","uv"]}clipToQuadrant(e,t,n){let{solid:r,skirtLength:i,ellipsoid:s,smoothSkirtNormals:a}=this;this.clearSplitOperations(),this.addSplitOperation(Cd("x"),!t),this.addSplitOperation(Cd("y"),!n);let o,l,c=e.geometry.groups[0],u=this.getClippedData(e,c);if(this.adjustVertices(u,e.position,0),r){o={index:u.index.slice().reverse(),attributes:{}};for(let e in u.attributes)o.attributes[e]=u.attributes[e].slice();let t=o.attributes.normal;if(t)for(let e=0;e<t.length;e+=3)t[e+0]*=-1,t[e+1]*=-1,t[e+2]*=-1;this.adjustVertices(o,e.position,-i)}if(i>0){l={index:[],attributes:{position:[],normal:[],uv:[]}};let t=0,n={},r=(e,r,i)=>{let s=rd(...e,...i,...r);s in n||(n[s]=t,t++,l.attributes.position.push(...e),l.attributes.normal.push(...i),l.attributes.uv.push(...r)),l.index.push(n[s])},o=u.index,c=u.attributes.uv,h=u.attributes.position,d=u.attributes.normal,p=u.index.length/3;for(let l=0;l<p;l++){let t=3*l;for(let n=0;n<3;n++){let l=(n+1)%3,u=o[t+n],p=o[t+l];if(_d.fromArray(c,2*u),Md.fromArray(c,2*p),_d.x===Md.x&&(0===_d.x||.5===_d.x||1===_d.x)||_d.y===Md.y&&(0===_d.y||.5===_d.y||1===_d.y)){yd.fromArray(h,3*u),vd.fromArray(h,3*p);let t=yd,n=vd,o=bd.copy(yd),l=wd.copy(vd);Td.copy(o).add(e.position),s.getPositionToNormal(Td,Td),o.addScaledVector(Td,-i),Td.copy(l).add(e.position),s.getPositionToNormal(Td,Td),l.addScaledVector(Td,-i),a&&d?(Td.fromArray(d,3*u),Sd.fromArray(d,3*p)):(Td.subVectors(t,n),Sd.subVectors(t,o).cross(Td).normalize(),Td.copy(Sd)),r(n,Md,Sd),r(t,_d,Td),r(o,_d,Td),r(n,Md,Sd),r(o,_d,Td),r(l,Md,Sd)}}}}let h=u.index.length,d=u;if(o){let{index:e,attributes:t}=o,n=d.attributes.position.length/3;for(let r=0,i=e.length;r<i;r++)d.index.push(e[r]+n);for(let r in u.attributes)d.attributes[r].push(...t[r])}if(l){let{index:e,attributes:t}=l,n=d.attributes.position.length/3;for(let r=0,i=e.length;r<i;r++)d.index.push(e[r]+n);for(let r in u.attributes)d.attributes[r].push(...t[r])}let p=t?0:-.5,m=n?0:-.5,f=d.attributes.uv;for(let v=0,b=f.length;v<b;v+=2)f[v]=2*(f[v]+p),f[v+1]=2*(f[v+1]+m);let g=this.constructMesh(d.attributes,d.index,e);g.userData.minHeight=e.userData.minHeight,g.userData.maxHeight=e.userData.maxHeight;let x=0,y=0;return g.geometry.addGroup(y,h,x),y+=h,x++,o&&(g.geometry.addGroup(y,o.index.length,x),y+=o.index.length,x++),l&&(g.geometry.addGroup(y,l.index.length,x),y+=l.index.length,x++),g}adjustVertices(e,t,n){let{ellipsoid:i,minLat:s,maxLat:a,minLon:o,maxLon:l}=this,{attributes:c,vertexIsClipped:u}=e,h=c.position,d=c.uv,p=h.length/3;for(let m=0;m<p;m++){let e=_d.fromArray(d,2*m);u&&u[m]&&(Math.abs(e.x-.5)<1e-10&&(e.x=.5),Math.abs(e.y-.5)<1e-10&&(e.y=.5),_d.toArray(d,2*m));let c=r.MathUtils.lerp(s,a,e.y),p=r.MathUtils.lerp(o,l,e.x),f=xd.fromArray(h,3*m).add(t);i.getPositionToCartographic(f,gd),i.getCartographicToPosition(c,p,gd.height+n,f),f.sub(t),f.toArray(h,3*m)}}};function Cd(e){return(t,n,r,i,s)=>{let a=t.attributes.uv;return _d.fromBufferAttribute(a,n),Md.fromBufferAttribute(a,r),Ad.fromBufferAttribute(a,i),_d[e]*s.x+Md[e]*s.y+Ad[e]*s.z-.5}}var Rd=Symbol("TILE_X"),Dd=Symbol("TILE_Y"),kd=Symbol("TILE_LEVEL"),Id=Symbol("TILE_AVAILABLE"),Pd=Symbol("TILE_SPLIT_SOURCE_SCENE"),Ld=new r.Vector3;function Ud(e){let{available:t=null,maxzoom:n=null}=e;return null===n?t.length-1:n}function Fd(e,t){let n=e[kd],r=function(e){let{metadataAvailability:t=-1}=e;return t}(t);return n<Ud(t)&&-1!==r&&n%r==0}var zd=class{constructor(e={}){let{useRecommendedSettings:t=!0,skirtLength:n=null,smoothSkirtNormals:r=!0,generateNormals:i=!0,solid:s=!1}=e;this.name="QUANTIZED_MESH_PLUGIN",this.priority=-1e3,this.tiles=null,this.layer=null,this.useRecommendedSettings=t,this.skirtLength=n,this.smoothSkirtNormals=r,this.solid=s,this.generateNormals=i,this.attribution=null,this.tiling=new Ih,this.projection=new Dh}init(e){e.fetchOptions.headers=e.fetchOptions.headers||{},e.fetchOptions.headers.Accept="application/vnd.quantized-mesh,application/octet-stream;q=0.9",this.useRecommendedSettings&&(e.errorTarget=2),this.tiles=e}loadRootTileset(){let{tiles:e}=this,t=new URL("layer.json",new URL(e.rootURL,location.href));return e.invokeAllPlugins((e=>t=e.preprocessURL?e.preprocessURL(t,null):t)),e.invokeOnePlugin((e=>e.fetchData&&e.fetchData(t,this.tiles.fetchOptions))).then((e=>e.json())).then((e=>{this.layer=e;let{projection:t="EPSG:4326",extensions:n=[],attribution:r="",available:i=null}=e,{tiling:s,tiles:a,projection:o}=this;r&&(this.attribution={value:r,type:"string",collapsible:!0}),n.length>0&&(a.fetchOptions.headers.Accept+=`;extensions=${n.join("-")}`),o.setScheme(t);let{tileCountX:l,tileCountY:c}=o;s.setProjection(o),s.generateLevels(Ud(e)+1,l,c);let u=[];for(let p=0;p<l;p++){let e=this.createChild(0,p,0,i);e&&u.push(e)}let h={asset:{version:"1.1"},geometricError:1/0,root:{refine:"REPLACE",geometricError:1/0,boundingVolume:{region:[...this.tiling.getContentBounds(),-1e4,1e4]},children:u,[Id]:i,[kd]:-1}},d=a.rootURL;return a.invokeAllPlugins((e=>d=e.preprocessURL?e.preprocessURL(d,null):d)),a.preprocessTileset(h,d),h}))}parseToMesh(e,t,n,r){let i,{skirtLength:s,solid:a,smoothSkirtNormals:o,generateNormals:l,tiles:c}=this,u=c.ellipsoid;if("quantized_tile_split"===n){let e=new URL(r).searchParams,n="true"===e.get("left"),l="true"===e.get("bottom"),c=new Ed;c.ellipsoid.copy(u),c.solid=a,c.smoothSkirtNormals=o,c.skirtLength=null===s?t.geometricError:s;let[h,d,p,m]=t.parent.boundingVolume.region;c.minLat=d,c.maxLat=m,c.minLon=h,c.maxLon=p;let f=t.parent.engineData.scene||t.parent[Pd];i=c.clipToQuadrant(f,n,l)}else{if("terrain"!==n)return;{let n=new fd(c.manager);n.ellipsoid.copy(u),n.solid=a,n.smoothSkirtNormals=o,n.generateNormals=l,n.skirtLength=null===s?t.geometricError:s;let[r,h,d,p]=t.boundingVolume.region;n.minLat=h,n.maxLat=p,n.minLon=r,n.maxLon=d,i=n.parse(e)}}let{minHeight:h,maxHeight:d,metadata:p}=i.userData;return t.boundingVolume.region[4]=h,t.boundingVolume.region[5]=d,t.engineData.boundingVolume.setRegionData(u,...t.boundingVolume.region),p&&("geometricerror"in p&&(t.geometricError=p.geometricerror),Fd(t,this.layer)&&"available"in p&&0===t.children.length&&(t[Id]=[...Array(t[kd]+1).fill(null),...p.available])),t[Pd]=i,this.expandChildren(t),i}getAttributions(e){this.attribution&&e.push(this.attribution)}createChild(e,t,n,r){let{tiles:i,layer:s,tiling:a,projection:o}=this,l=i.ellipsoid,c=null===r&&0===e||function(e,t,n,r){if(e&&t<e.length){let i=e[t];for(let e=0,t=i.length;e<t;e++){let{startX:t,startY:s,endX:a,endY:o}=i[e];if(n>=t&&n<=a&&r>=s&&r<=o)return!0}}return!1}(r,e,t,n),u=function(e,t,n,r,i){return i.tiles[0].replace(/{\s*z\s*}/g,n).replace(/{\s*x\s*}/g,e).replace(/{\s*y\s*}/g,t).replace(/{\s*version\s*}/g,r)}(t,n,e,1,s),h=[...a.getTileBounds(t,n,e),-1e4,1e4],[,d,,p,,m]=h,f=d>0==p>0?Math.min(Math.abs(d),Math.abs(p)):0;l.getCartographicToPosition(f,0,m,Ld),Ld.z=0;let g=o.tileCountX,x=2*Math.max(...l.radius)*Math.PI*.25/(65*g)/2**e,y={[Id]:null,[kd]:e,[Rd]:t,[Dd]:n,refine:"REPLACE",geometricError:x,boundingVolume:{region:h},content:c?{uri:u}:null,children:[]};return Fd(y,s)||(y[Id]=r),y}expandChildren(e){let t=e[kd],n=e[Rd],r=e[Dd],i=e[Id];if(t>=this.tiling.maxLevel)return;let s=!1;for(let a=0;a<2;a++)for(let o=0;o<2;o++){let l=this.createChild(t+1,2*n+a,2*r+o,i);null===l.content?(l.content={uri:`tile.quantized_tile_split?bottom=${0===o}&left=${0===a}`},l.internal={isVirtual:!0},e.internal.virtualChildCount++,e.children.push(l)):(e.children.push(l),s=!0)}s||(e.children.length-=e.internal.virtualChildCount,e.internal.virtualChildCount=0)}fetchData(e,t){if(/quantized_tile_split/.test(e))return new ArrayBuffer}disposeTile(e){let{tiles:t,layer:n}=this;if(delete e[Pd],Fd(e,n)&&(e[Id]=null),Id in e){let{virtualChildCount:n}=e.internal,r=e.children.length;for(let i=r-n;i<r;i++)t.processNodeQueue.remove(e.children[i]);e.children.length=0,e.internal.virtualChildCount=0}}},Bd=class extends vh{constructor(e={}){super({assetTypeHandler:(e,t,n)=>{if("TERRAIN"===e&&null===t.getPluginByName("QUANTIZED_MESH_PLUGIN"))t.registerPlugin(new zd({useRecommendedSettings:this.useRecommendedSettings}));else if("IMAGERY"===e&&null===t.getPluginByName("GENERATED_SURFACE_PLUGIN")){let e=new ud({url:t.rootURL});t.registerPlugin(new Nh({shape:"ellipsoid",overlay:e}))}},...e})}},Vd=new r.Matrix4,Od=class{constructor(){this.name="UPDATE_ON_CHANGE_PLUGIN",this.tiles=null,this.needsUpdate=!1,this.cameraMatrices=new Map}init(e){this.tiles=e,this._needsUpdateCallback=()=>{this.needsUpdate=!0},this._onCameraAdd=({camera:e})=>{this.needsUpdate=!0,this.cameraMatrices.set(e,new r.Matrix4)},this._onCameraDelete=({camera:e})=>{this.needsUpdate=!0,this.cameraMatrices.delete(e)},e.addEventListener("needs-update",this._needsUpdateCallback),e.addEventListener("add-camera",this._onCameraAdd),e.addEventListener("delete-camera",this._onCameraDelete),e.addEventListener("camera-resolution-change",this._needsUpdateCallback),e.cameras.forEach((e=>{this._onCameraAdd({camera:e})}))}doTilesNeedUpdate(){let e=this.tiles,t=!1;this.cameraMatrices.forEach(((n,r)=>{Vd.copy(e.group.matrixWorld).premultiply(r.matrixWorldInverse).premultiply(r.projectionMatrixInverse),t||(t=!Vd.equals(n)),n.copy(Vd)}));let n=this.needsUpdate;return this.needsUpdate=!1,n||t}preprocessNode(){this.needsUpdate=!0}dispose(){let e=this.tiles;e.removeEventListener("camera-resolution-change",this._needsUpdateCallback),e.removeEventListener("needs-update",this._needsUpdateCallback),e.removeEventListener("add-camera",this._onCameraAdd),e.removeEventListener("delete-camera",this._onCameraDelete)}},Nd=new r.Vector3;function $d(e,t){if(e.isInterleavedBufferAttribute||e.array instanceof t)return e;let n=t===Int8Array||t===Int16Array||t===Int32Array?-1:0,i=new r.BufferAttribute(new t(e.count*e.itemSize),e.itemSize,!0),s=e.itemSize,a=e.count;for(let o=0;o<a;o++)for(let t=0;t<s;t++){let s=r.MathUtils.clamp(e.getComponent(o,t),n,1);i.setComponent(o,t,s)}return i}var Gd=class{constructor(e){this._options={generateNormals:!1,disableMipmaps:!0,compressIndex:!0,compressNormals:!1,compressUvs:!1,compressPosition:!1,uvType:Int8Array,normalType:Int8Array,positionType:Int16Array,...e},this.name="TILES_COMPRESSION_PLUGIN",this.priority=-100}processTileModel(e,t){let{generateNormals:n,disableMipmaps:i,compressIndex:s,compressUvs:a,compressNormals:o,compressPosition:l,uvType:c,normalType:u,positionType:h}=this._options;e.traverse((e=>{if(e.material&&i){let t=e.material;for(let e in t){let n=t[e];n&&n.isTexture&&n.generateMipmaps&&(n.generateMipmaps=!1,n.minFilter=r.LinearFilter)}}if(e.geometry){let t=e.geometry,i=t.attributes;if(a){let{uv:e,uv1:t,uv2:n,uv3:r}=i;e&&(i.uv=$d(e,c)),t&&(i.uv1=$d(t,c)),n&&(i.uv2=$d(n,c)),r&&(i.uv3=$d(r,c))}if(n&&!i.normals&&t.computeVertexNormals(),o&&i.normals&&(i.normals=$d(i.normals,u)),l&&function(e,t=Int16Array){let n=e.geometry,i=n.attributes,s=i.position;if(s.isInterleavedBufferAttribute||s.array instanceof t)return s;let a=new r.BufferAttribute(new t(s.count*s.itemSize),s.itemSize,!1),o=s.itemSize,l=s.count;n.computeBoundingBox();let c=n.boundingBox,{min:u,max:h}=c,d=2**(8*t.BYTES_PER_ELEMENT-1)-1,p=-d;for(let m=0;m<l;m++)for(let e=0;e<o;e++){let t=0===e?"x":1===e?"y":"z",n=u[t],i=h[t],o=r.MathUtils.mapLinear(s.getComponent(m,e),n,i,p,d);a.setComponent(m,e,o)}c.getCenter(Nd).multiply(e.scale).applyQuaternion(e.quaternion),e.position.add(Nd),e.scale.x*=.5*(h.x-u.x)/d,e.scale.y*=.5*(h.y-u.y)/d,e.scale.z*=.5*(h.z-u.z)/d,i.position=a,e.geometry.boundingBox=null,e.geometry.boundingSphere=null,e.updateMatrixWorld()}(e,h),s&&t.index){let e=i.position.count,n=t.index,s=e>65535?Uint32Array:e>255?Uint16Array:Uint8Array;if(!(n.array instanceof s)){let e=new s(t.index.count);e.set(n.array);let i=new r.BufferAttribute(e,1);t.setIndex(i)}}}}))}};function qd(e,t,n){return e&&t in e?e[t]:n}function Hd(e){return"BOOLEAN"!==e&&"STRING"!==e&&"ENUM"!==e}function jd(e){return/^VEC/.test(e)}function Wd(e){return/^MAT/.test(e)}function Xd(e,t,n,r=null){return Wd(n)||jd(n)?r.fromArray(e,t):e[t]}function Yd(e){let{type:t,componentType:n}=e;switch(t){case"SCALAR":return"INT64"===n?0n:0;case"VEC2":return new r.Vector2;case"VEC3":return new r.Vector3;case"VEC4":return new r.Vector4;case"MAT2":return new r.Matrix2;case"MAT3":return new r.Matrix3;case"MAT4":return new r.Matrix4;case"BOOLEAN":return!1;case"STRING":return"";case"ENUM":return 0}}function Kd(e,t){if(null==t)return!1;switch(e){case"SCALAR":case"ENUM":return"number"==typeof t||"bigint"==typeof t;case"VEC2":return t.isVector2;case"VEC3":return t.isVector3;case"VEC4":return t.isVector4;case"MAT2":return t.isMatrix2;case"MAT3":return t.isMatrix3;case"MAT4":return t.isMatrix4;case"BOOLEAN":return"boolean"==typeof t;case"STRING":return"string"==typeof t}throw Error("ClassProperty: invalid type.")}function Qd(e,t=null){switch(e){case"INT8":return Int8Array;case"INT16":return Int16Array;case"INT32":return Int32Array;case"INT64":return BigInt64Array;case"UINT8":return Uint8Array;case"UINT16":return Uint16Array;case"UINT32":return Uint32Array;case"UINT64":return BigUint64Array;case"FLOAT32":return Float32Array;case"FLOAT64":return Float64Array}switch(t){case"BOOLEAN":case"STRING":return Uint8Array}throw Error("ClassProperty: invalid type.")}function Zd(e,t=null){let n=e.default,r=e.type;if(t||(t=Yd(e)),null===n){switch(r){case"SCALAR":return 0;case"VEC2":return t.set(0,0);case"VEC3":return t.set(0,0,0);case"VEC4":return t.set(0,0,0,0);case"MAT2":case"MAT3":case"MAT4":return t.identity();case"BOOLEAN":return!1;case"STRING":case"ENUM":return""}throw Error("ClassProperty: invalid type.")}if(Wd(r))t.fromArray(n);else{if(!jd(r))return n;t.fromArray(n)}}function Jd(e,t){if(null===e.noData)return t;let n=e.noData,r=e.type;if(Array.isArray(t))for(let s=0,a=t.length;s<a;s++)t[s]=i(t[s]);else t=i(t);return t;function i(t){return function(e){if(Wd(r)){let t=e.elements;for(let e=0,r=n.length;e<r;e++)if(n[e]!==t[e])return!1;return!0}if(jd(r)){for(let t=0,r=n.length;t<r;t++)if(n[t]!==e.getComponent(t))return!1;return!0}return n===e}(t)&&(t=Zd(e,t)),t}}function ep(e,t){let{type:n,componentType:r,scale:i,offset:s,normalized:a}=e;if(Array.isArray(t))for(let c=0,u=t.length;c<u;c++)t[c]=o(t[c]);else t=o(t);return t;function o(e){return e=Wd(n)?function(e){let t=e.elements;for(let n=0,r=t.length;n<r;n++)t[n]=l(t[n]);return e}(e):jd(n)?function(e){return e.x=l(e.x),e.y=l(e.y),"z"in e&&(e.z=l(e.z)),"w"in e&&(e.w=l(e.w)),e}(e):l(e)}function l(e){return a&&(e=function(e,t){switch(e){case"INT8":return Math.max(t/127,-1);case"INT16":return Math.max(t,32767,-1);case"INT32":return Math.max(t/2147483647,-1);case"INT64":return Math.max(Number(t)/0x8000000000000000,-1);case"UINT8":return t/255;case"UINT16":return t/65535;case"UINT32":return t/4294967295;case"UINT64":return Number(t)/0x10000000000000000}}(r,e)),(a||function(e){return/^FLOAT/.test(e)}(r))&&(e=e*i+s),e}}function tp(e,t,n=null){if(e.array){Array.isArray(t)||(t=Array(e.count||0)),t.length=null===n?e.count:n;for(let n=0,r=t.length;n<r;n++)Kd(e.type,t[n])||(t[n]=Yd(e))}else Kd(e.type,t)||(t=Yd(e));return t}function np(e,t){for(let n in t)n in e||delete t[n];for(let n in e){let r=e[n];t[n]=tp(r,t[n])}}var rp=class{constructor(e,t,n=null){this.name=t.name||null,this.description=t.description||null,this.type=t.type,this.componentType=t.componentType||null,this.enumType=t.enumType||null,this.array=t.array||!1,this.count=t.count||0,this.normalized=t.normalized||!1,this.offset=t.offset||0,this.scale=qd(t,"scale",1),this.max=qd(t,"max",1/0),this.min=qd(t,"min",-1/0),this.required=t.required||!1,this.noData=qd(t,"noData",null),this.default=qd(t,"default",null),this.semantic=qd(t,"semantic",null),this.enumSet=null,this.accessorProperty=n,n&&(this.offset=qd(n,"offset",this.offset),this.scale=qd(n,"scale",this.scale),this.max=qd(n,"max",this.max),this.min=qd(n,"min",this.min)),"ENUM"===t.type&&(this.enumSet=e[this.enumType],null===this.componentType&&(this.componentType=qd(this.enumSet,"valueType","UINT16")))}shapeToProperty(e,t=null){return tp(this,e,t)}resolveDefaultElement(e){return Zd(this,e)}resolveDefault(e){return function(e,t=null){if(e.array){(t=t&&Array.isArray(t)?t:[]).length=e.count;for(let n=0,r=t.length;n<r;n++)t[n]=Zd(e,t[n])}else t=Zd(e,t);return t}(this,e)}resolveNoData(e){return Jd(this,e)}resolveEnumsToStrings(e){let t=this.enumSet;if("ENUM"===this.type)if(Array.isArray(e))for(let r=0,i=e.length;r<i;r++)e[r]=n(e[r]);else e=n(e);return e;function n(e){let n=t.values.find((t=>t.value===e));return null===n?"":n.name}}adjustValueScaleOffset(e){return Hd(this.type)?ep(this,e):e}},ip=class{constructor(e,t={},n={},r=null){this.definition=e,this.class=t[e.class],this.className=e.class,this.enums=n,this.data=r,this.name="name"in e?e.name:null,this.properties=null}getPropertyNames(){return Object.keys(this.class.properties)}includesData(e){return!!this.definition.properties[e]}dispose(){}_initProperties(e=rp){let t={};for(let n in this.class.properties)t[n]=new e(this.enums,this.class.properties[n],this.definition.properties[n]);this.properties=t}},sp=class extends rp{constructor(e,t,n=null){super(e,t,n),this.attribute=(null==n?void 0:n.attribute)??null}},ap=class extends ip{constructor(...e){super(...e),this.isPropertyAttributeAccessor=!0,this._initProperties(sp)}getData(e,t,n={}){let r=this.properties;np(r,n);for(let i in r)n[i]=this.getPropertyValue(i,e,t,n[i]);return n}getPropertyValue(e,t,n,r=null){if(t>=this.count)throw Error("PropertyAttributeAccessor: Requested index is outside the range of the buffer.");let i=this.properties[e],s=i.type;if(!i)throw Error("PropertyAttributeAccessor: Requested class property does not exist.");if(!this.definition.properties[e])return i.resolveDefault(r);r=i.shapeToProperty(r);let a=n.getAttribute(i.attribute.toLowerCase());if(Wd(s)){let e=r.elements;for(let n=e.length;0<n;)e[0]=a.getComponent(t,0)}else if(jd(s))r.fromBufferAttribute(a,t);else{if("SCALAR"!==s&&"ENUM"!==s)throw Error("StructuredMetadata.PropertyAttributeAccessor: BOOLEAN and STRING types are not supported by property attributes.");r=a.getX(t)}return r=i.adjustValueScaleOffset(r),r=i.resolveEnumsToStrings(r),r=i.resolveNoData(r)}},op=class extends rp{constructor(e,t,n=null){super(e,t,n),this.values=(null==n?void 0:n.values)??null,this.valueLength=function(e){switch(e){case"ENUM":case"SCALAR":return 1;case"VEC2":return 2;case"VEC3":return 3;case"VEC4":case"MAT2":return 4;case"MAT3":return 9;case"MAT4":return 16;default:return-1}}(this.type),this.arrayOffsets=qd(n,"arrayOffsets",null),this.stringOffsets=qd(n,"stringOffsets",null),this.arrayOffsetType=qd(n,"arrayOffsetType","UINT32"),this.stringOffsetType=qd(n,"stringOffsetType","UINT32")}getArrayLengthFromId(e,t){let n=this.count;if(null!==this.arrayOffsets){let{arrayOffsets:r,arrayOffsetType:i}=this,s=new(Qd(i))(e[r]);n=s[t+1]-s[t]}return n}getIndexOffsetFromId(e,t){let n=t;if(this.arrayOffsets){let{arrayOffsets:t,arrayOffsetType:r}=this;n=new(Qd(r))(e[t])[n]}else this.array&&(n*=this.count);return n}},lp=class extends ip{constructor(...e){super(...e),this.isPropertyTableAccessor=!0,this.count=this.definition.count,this._initProperties(op)}getData(e,t={}){let n=this.properties;np(n,t);for(let r in n)t[r]=this.getPropertyValue(r,e,t[r]);return t}_readValueAtIndex(e,t,n,r=null){let i=this.properties[e],{componentType:s,type:a}=i,o=this.data,l=o[i.values],c=new(Qd(s,a))(l),u=i.getIndexOffsetFromId(o,t);if(Hd(a)||"ENUM"===a)return Xd(c,(u+n)*i.valueLength,a,r);if("STRING"===a){let e=u+n,t=0;if(null!==i.stringOffsets){let{stringOffsets:n,stringOffsetType:r}=i,s=new(Qd(r))(o[n]);t=s[e+1]-s[e],e=s[e]}let s=new Uint8Array(c.buffer,e,t);r=(new TextDecoder).decode(s)}else if("BOOLEAN"===a){let e=u+n,t=e%8;r=1==(c[Math.floor(e/8)]>>t&1)}return r}getPropertyValue(e,t,n=null){if(t>=this.count)throw Error("PropertyTableAccessor: Requested index is outside the range of the table.");let r=this.properties[e];if(!r)throw Error("PropertyTableAccessor: Requested property does not exist.");if(!this.definition.properties[e])return r.resolveDefault(n);let i=r.array,s=this.data,a=r.getArrayLengthFromId(s,t);if(n=r.shapeToProperty(n,a),i)for(let o=0,l=n.length;o<l;o++)n[o]=this._readValueAtIndex(e,t,o,n[o]);else n=this._readValueAtIndex(e,t,0,n);return n=r.adjustValueScaleOffset(n),n=r.resolveEnumsToStrings(n),n=r.resolveNoData(n)}},cp=new r.Box2,up=class{constructor(){this._renderer=new r.WebGLRenderer,this._target=new r.WebGLRenderTarget(1,1),this._texTarget=new r.WebGLRenderTarget,this._quad=new o(new r.ShaderMaterial({blending:r.CustomBlending,blendDst:r.ZeroFactor,blendSrc:r.OneFactor,uniforms:{map:{value:null},pixel:{value:new r.Vector2}},vertexShader:"\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n\n\t\t\t\t}\n\t\t\t",fragmentShader:"\n\t\t\t\tuniform sampler2D map;\n\t\t\t\tuniform ivec2 pixel;\n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tgl_FragColor = texelFetch( map, pixel, 0 );\n\n\t\t\t\t}\n\t\t\t"}))}increaseSizeTo(e){this._target.setSize(Math.max(this._target.width,e),1)}readDataAsync(e){let{_renderer:t,_target:n}=this;return t.readRenderTargetPixelsAsync(n,0,0,e.length/4,1,e)}readData(e){let{_renderer:t,_target:n}=this;t.readRenderTargetPixels(n,0,0,e.length/4,1,e)}renderPixelToTarget(e,t,n){let{_renderer:r,_target:i}=this;cp.min.copy(t),cp.max.copy(t),cp.max.x+=1,cp.max.y+=1,r.initRenderTarget(i),r.copyTextureToTexture(e,i.texture,cp,n,0)}},hp=new class{constructor(){let e=null;Object.getOwnPropertyNames(up.prototype).forEach((t=>{"constructor"!==t&&(this[t]=(...n)=>(e||(e=new up),e[t](...n)))}))}},dp=new r.Vector2,pp=new r.Vector2,mp=new r.Vector2;function fp(e,t,n=[,,,]){let r=3*t,i=3*t+1,s=3*t+2;return e.index&&(r=e.index.getX(r),i=e.index.getX(i),s=e.index.getX(s)),n[0]=r,n[1]=i,n[2]=s,n}function gp(e,t,n,r,i){let[s,a,o]=r,l=function(e,t){return 0===t?e.getAttribute("uv"):e.getAttribute(`uv${t}`)}(e,t);dp.fromBufferAttribute(l,s),pp.fromBufferAttribute(l,a),mp.fromBufferAttribute(l,o),i.set(0,0,0).addScaledVector(dp,n.x).addScaledVector(pp,n.y).addScaledVector(mp,n.z)}function xp(e,t,n,r){let i=e.x-Math.floor(e.x),s=e.y-Math.floor(e.y),a=Math.floor(i*t%t),o=Math.floor(s*n%n);return r.set(a,o),r}var yp=new r.Vector2,vp=new r.Vector2,bp=new r.Vector2,wp=class extends rp{constructor(e,t,n=null){super(e,t,n),this.channels=qd(n,"channels",[0]),this.index=qd(n,"index",null),this.texCoord=qd(n,"texCoord",null),this.valueLength=parseInt(this.type.replace(/[^0-9]/g,""))||1}readDataFromBuffer(e,t,n=null){let r=this.type;if("BOOLEAN"===r||"STRING"===r)throw Error("PropertyTextureAccessor: BOOLEAN and STRING types not supported.");return Xd(e,t*this.valueLength,r,n)}},Tp=class extends ip{constructor(...e){super(...e),this.isPropertyTextureAccessor=!0,this._asyncRead=!1,this._initProperties(wp)}getData(e,t,n,r={}){let i=this.properties;np(i,r);let s=Object.keys(i),a=s.map((e=>r[e]));return this.getPropertyValuesAtTexel(s,e,t,n,a),s.forEach(((e,t)=>r[e]=a[t])),r}async getDataAsync(e,t,n,r={}){let i=this.properties;np(i,r);let s=Object.keys(i),a=s.map((e=>r[e]));return await this.getPropertyValuesAtTexelAsync(s,e,t,n,a),s.forEach(((e,t)=>r[e]=a[t])),r}getPropertyValuesAtTexelAsync(...e){this._asyncRead=!0;let t=this.getPropertyValuesAtTexel(...e);return this._asyncRead=!1,t}getPropertyValuesAtTexel(e,t,n,r,i=[]){for(;i.length<e.length;)i.push(null);i.length=e.length,hp.increaseSizeTo(i.length);let s=this.data,a=this.definition.properties,o=this.properties,l=fp(r,t);for(let h=0,d=e.length;h<d;h++){let t=e[h];if(!a[t])continue;let i=o[t],c=s[i.index];gp(r,i.texCoord,n,l,yp),xp(yp,c.image.width,c.image.height,vp),bp.set(h,0),hp.renderPixelToTarget(c,vp,bp)}let c=new Uint8Array(4*e.length);return this._asyncRead?hp.readDataAsync(c).then((()=>(u.call(this),i))):(hp.readData(c),u.call(this),i);function u(){for(let t=0,n=e.length;t<n;t++){let n=e[t],r=o[n],s=r.type;if(i[t]=tp(r,i[t]),!r)throw Error("PropertyTextureAccessor: Requested property does not exist.");if(!a[n]){i[t]=r.resolveDefault(i);continue}let l=r.valueLength*(r.count||1),u=r.channels.map((e=>c[4*t+e])),h=new(Qd(r.componentType,s))(l);if(new Uint8Array(h.buffer).set(u),r.array){let e=i[t];for(let t=0,n=e.length;t<n;t++)e[t]=r.readDataFromBuffer(h,t,e[t])}else i[t]=r.readDataFromBuffer(h,0,i[t]);i[t]=r.adjustValueScaleOffset(i[t]),i[t]=r.resolveEnumsToStrings(i[t]),i[t]=r.resolveNoData(i[t])}}}dispose(){this.data.forEach((e=>{e&&(e.dispose(),e.image instanceof ImageBitmap&&e.image.close())}))}},Sp=class{constructor(e,t,n,r=null,i=null){let{schema:s,propertyTables:a=[],propertyTextures:o=[],propertyAttributes:l=[]}=e,{enums:c,classes:u}=s,h=a.map((e=>new lp(e,u,c,n))),d=[],p=[];r&&(r.propertyTextures&&(d=r.propertyTextures.map((e=>new Tp(o[e],u,c,t)))),r.propertyAttributes&&(p=r.propertyAttributes.map((e=>new ap(l[e],u,c))))),this.schema=s,this.tableAccessors=h,this.textureAccessors=d,this.attributeAccessors=p,this.object=i,this.textures=t,this.nodeMetadata=r}getPropertyTableData(e,t,n=null){if(Array.isArray(e)){n||(n=[]);let r=Math.min(e.length,t.length);n.length=r;for(let i=0;i<r;i++){let r=this.tableAccessors[e[i]];n[i]=r.getData(t[i],n[i])}}else n||(n={}),n=this.tableAccessors[e].getData(t,n);if(Array.isArray(e)!==Array.isArray(n)||Array.isArray(e)!==Array.isArray(t))throw Error("StructuralMetadata: Scalar and array inputs cannot be mixed.");return n}getPropertyTableInfo(e=null){if(null===e&&(e=this.tableAccessors.map(((e,t)=>t))),Array.isArray(e))return e.map((e=>{let t=this.tableAccessors[e];return{name:t.name,className:t.definition.class}}));{let t=this.tableAccessors[e];return{name:t.name,className:t.definition.class}}}getPropertyTextureData(e,t,n=[]){let r=this.textureAccessors;n.length=r.length;for(let i=0;i<r.length;i++)n[i]=r[i].getData(e,t,this.object.geometry,n[i]);return n}async getPropertyTextureDataAsync(e,t,n=[]){let r=this.textureAccessors;n.length=r.length;let i=[];for(let s=0;s<r.length;s++){let a=r[s].getDataAsync(e,t,this.object.geometry,n[s]).then((e=>{n[s]=e}));i.push(a)}return await Promise.all(i),n}getPropertyTextureInfo(){return this.textureAccessors}getPropertyAttributeData(e,t=[]){let n=this.attributeAccessors;t.length=n.length;for(let r=0;r<n.length;r++)t[r]=n[r].getData(e,this.object.geometry,t[r]);return t}getPropertyAttributeInfo(){return this.attributeAccessors.map((e=>({name:e.name,className:e.definition.class})))}dispose(){this.textureAccessors.forEach((e=>e.dispose())),this.tableAccessors.forEach((e=>e.dispose())),this.attributeAccessors.forEach((e=>e.dispose()))}},_p="EXT_structural_metadata";function Mp(e,t=[]){var n;let r=(null==(n=e.json.textures)?void 0:n.length)||0,i=Array(r).fill(null);return t.forEach((({properties:t})=>{for(let n in t){let{index:r}=t[n];null===i[r]&&(i[r]=e.loadTexture(r))}})),Promise.all(i)}function Ap(e,t=[]){var n;let r=(null==(n=e.json.bufferViews)?void 0:n.length)||0,i=Array(r).fill(null);return t.forEach((({properties:t})=>{for(let n in t){let{values:r,arrayOffsets:s,stringOffsets:a}=t[n];null===i[r]&&(i[r]=e.getDependency("bufferView",r)),null===i[s]&&(i[s]=e.getDependency("bufferView",s)),null===i[a]&&(i[a]=e.getDependency("bufferView",a))}})),Promise.all(i)}var Ep=class{constructor(e){this.parser=e,this.name=_p}async afterRoot({scene:e,parser:t}){let n=t.json.extensionsUsed;if(!n||!n.includes(_p))return;let i=null,s=t.json.extensions[_p];if(s.schemaUri){let{manager:e,path:n,requestHeader:a,crossOrigin:o}=t.options,l=new URL(s.schemaUri,n).toString(),c=new r.FileLoader(e);c.setCrossOrigin(o),c.setResponseType("json"),c.setRequestHeader(a),i=c.loadAsync(l).then((e=>{s={...s,schema:e}}))}let[a,o]=await Promise.all([Mp(t,s.propertyTextures),Ap(t,s.propertyTables),i]),l=new Sp(s,a,o);e.userData.structuralMetadata=l,e.traverse((e=>{var n;if(t.associations.has(e)){let{meshes:r,primitives:i}=t.associations.get(e),c=null==(n=t.json.meshes[r])?void 0:n.primitives[i];if(c&&c.extensions&&c.extensions[_p]){let t=c.extensions[_p];e.userData.structuralMetadata=new Sp(s,a,o,t,e)}else e.userData.structuralMetadata=l}}))}},Cp=new r.Vector2,Rp=new r.Vector2,Dp=new r.Vector2;var kp=class{constructor(e,t,n){this.geometry=e,this.textures=t,this.data=n,this._asyncRead=!1,this.featureIds=n.featureIds.map((e=>{let{texture:t,...n}=e,r={label:null,propertyTable:null,nullFeatureId:null,...n};return t&&(r.texture={texCoord:0,channels:[0],...t}),r}))}getTextures(){return this.textures}getFeatureInfo(){return this.featureIds}getFeaturesAsync(...e){this._asyncRead=!0;let t=this.getFeatures(...e);return this._asyncRead=!1,t}getFeatures(e,t){let{geometry:n,textures:r,featureIds:i}=this,s=Array(i.length).fill(null),a=i.length;hp.increaseSizeTo(a);let o=fp(n,e),l=o[function(e){return e.x>e.y&&e.x>e.z?0:e.y>e.z?1:2}(t)];for(let h=0,d=i.length;h<d;h++){let e=i[h],a="nullFeatureId"in e?e.nullFeatureId:null;if("texture"in e){let i=r[e.texture.index];gp(n,e.texture.texCoord,t,o,Cp),xp(Cp,i.image.width,i.image.height,Rp),Dp.set(h,0),hp.renderPixelToTarget(r[e.texture.index],Rp,Dp)}else if("attribute"in e){let t=n.getAttribute(`_feature_id_${e.attribute}`).getX(l);t!==a&&(s[h]=t)}else{let e=l;e!==a&&(s[h]=e)}}let c=new Uint8Array(4*a);return this._asyncRead?hp.readDataAsync(c).then((()=>(u(),s))):(hp.readData(c),u(),s);function u(){let e=new Uint32Array(1);for(let t=0,n=i.length;t<n;t++){let n=i[t],r="nullFeatureId"in n?n.nullFeatureId:null;if("texture"in n){let{channels:i}=n.texture,a=i.map((e=>c[4*t+e]));new Uint8Array(e.buffer).set(a);let o=e[0];o!==r&&(s[t]=o)}}}}dispose(){this.textures.forEach((e=>{e&&(e.dispose(),e.image instanceof ImageBitmap&&e.image.close())}))}},Ip="EXT_mesh_features";function Pp(e,t,n){e.traverse((e=>{var r;if(t.associations.has(e)){let{meshes:i,primitives:s}=t.associations.get(e),a=null==(r=t.json.meshes[i])?void 0:r.primitives[s];a&&a.extensions&&a.extensions[Ip]&&n(e,a.extensions[Ip])}}))}var Lp=class{constructor(e){this.parser=e,this.name=Ip}async afterRoot({scene:e,parser:t}){var n;let r=t.json.extensionsUsed;if(!r||!r.includes(Ip))return;let i=(null==(n=t.json.textures)?void 0:n.length)||0,s=Array(i).fill(null);Pp(e,t,((e,{featureIds:n})=>{n.forEach((e=>{if(e.texture&&null===s[e.texture.index]){let n=e.texture.index;s[n]=t.loadTexture(n)}}))}));let a=await Promise.all(s);Pp(e,t,((e,t)=>{e.userData.meshFeatures=new kp(e.geometry,a,t)}))}},Up=class{constructor(){this.name="CESIUM_RTC"}afterRoot(e){if(e.parser.json.extensions&&e.parser.json.extensions.CESIUM_RTC){let{center:t}=e.parser.json.extensions.CESIUM_RTC;t&&(e.scene.position.x+=t[0],e.scene.position.y+=t[1],e.scene.position.z+=t[2])}}},Fp=class{constructor(e){e={metadata:!0,rtc:!0,plugins:[],dracoLoader:null,ktxLoader:null,meshoptDecoder:null,autoDispose:!0,...e},this.tiles=null,this.metadata=e.metadata,this.rtc=e.rtc,this.plugins=e.plugins,this.dracoLoader=e.dracoLoader,this.ktxLoader=e.ktxLoader,this.meshoptDecoder=e.meshoptDecoder,this._gltfRegex=/\.(gltf|glb)$/g,this._dracoRegex=/\.drc$/g,this._loader=null}init(e){let t=new rt(e.manager);this.dracoLoader&&(t.setDRACOLoader(this.dracoLoader),e.manager.addHandler(this._dracoRegex,this.dracoLoader)),this.ktxLoader&&t.setKTX2Loader(this.ktxLoader),this.meshoptDecoder&&t.setMeshoptDecoder(this.meshoptDecoder),this.rtc&&t.register((()=>new Up)),this.metadata&&(t.register((()=>new Ep)),t.register((()=>new Lp))),this.plugins.forEach((e=>t.register(e))),e.manager.addHandler(this._gltfRegex,t),this.tiles=e,this._loader=t}dispose(){this.tiles.manager.removeHandler(this._gltfRegex),this.tiles.manager.removeHandler(this._dracoRegex),this.autoDispose&&(this.ktxLoader.dispose(),this.dracoLoader.dispose())}},zp=class{set delay(e){this.deferCallbacks.delay=e}get delay(){return this.deferCallbacks.delay}set bytesTarget(e){this.lruCache.minBytesSize=e}get bytesTarget(){return this.lruCache.minBytesSize}get estimatedGpuBytes(){return this.lruCache.cachedBytes}constructor(e={}){let{delay:t=0,bytesTarget:n=0}=e;this.name="UNLOAD_TILES_PLUGIN",this.tiles=null,this.lruCache=new Bl,this.deferCallbacks=new Bp,this.delay=t,this.bytesTarget=n}init(e){this.tiles=e;let{lruCache:t,deferCallbacks:n}=this,r=t=>{let n=t.engineData.scene;e.visibleTiles.has(t)||e.invokeOnePlugin((e=>e.unloadTileFromGPU&&e.unloadTileFromGPU(n,t)))};this._onUpdateBefore=()=>{t.unloadPriorityCallback=e.lruCache.unloadPriorityCallback,t.minSize=1/0,t.maxSize=1/0,t.maxBytesSize=1/0,t.unloadPercent=1,t.autoMarkUnused=!1},this._onVisibilityChangeCallback=({tile:i,scene:s,visible:a})=>{a?(t.add(i,r),t.setMemoryUsage(i,e.calculateBytesUsed(i,s)||1),e.markTileUsed(i),n.cancel(i)):n.run(i)},this._onDisposeModel=({tile:e})=>{t.remove(e),n.cancel(e)},n.callback=e=>{t.markUnused(e),t.scheduleUnload()},e.forEachLoadedModel(((t,n)=>{let r=e.visibleTiles.has(n);this._onVisibilityChangeCallback({tile:n,visible:r})})),e.addEventListener("tile-visibility-change",this._onVisibilityChangeCallback),e.addEventListener("update-before",this._onUpdateBefore),e.addEventListener("dispose-model",this._onDisposeModel)}unloadTileFromGPU(e,t){e&&e.traverse((e=>{if(e.material){let t=e.material;t.dispose();for(let e in t){let n=t[e];n&&n.isTexture&&n.dispose()}}e.geometry&&e.geometry.dispose()}))}dispose(){let{lruCache:e,tiles:t,deferCallbacks:n}=this;t.removeEventListener("tile-visibility-change",this._onVisibilityChangeCallback),t.removeEventListener("update-before",this._onUpdateBefore),t.removeEventListener("dispose-model",this._onDisposeModel),n.cancelAll(),e.minBytesSize=0,e.minSize=0,e.maxSize=0,e.markAllUnused(),e.scheduleUnload()}},Bp=class{constructor(e=()=>{}){this.map=new Map,this.callback=e,this.delay=0}run(e){let{map:t,delay:n}=this;if(t.has(e))throw Error("DeferCallbackManager: Callback already initialized.");0===n?this.callback(e):t.set(e,setTimeout((()=>{this.callback(e),t.delete(e)}),n))}cancel(e){let{map:t}=this;t.has(e)&&(clearTimeout(t.get(e)),t.delete(e))}cancelAll(){this.map.forEach(((e,t)=>{this.cancel(t)}))}},{clamp:Vp}=r.MathUtils,Op=class{constructor(){this.duration=250,this.fadeCount=0,this._lastTick=-1,this._fadeState=new Map,this.onFadeComplete=null,this.onFadeStart=null,this.onFadeSetComplete=null,this.onFadeSetStart=null}deleteObject(e){e&&this.completeFade(e)}guaranteeState(e){let t=this._fadeState;return!t.has(e)&&(t.set(e,{fadeInTarget:0,fadeOutTarget:0,fadeIn:0,fadeOut:0}),!0)}completeFade(e){let t=this._fadeState;if(!t.has(e))return;let n=0===t.get(e).fadeOutTarget;t.delete(e),this.fadeCount--,this.onFadeComplete&&this.onFadeComplete(e,n),0===this.fadeCount&&this.onFadeSetComplete&&this.onFadeSetComplete()}completeAllFades(){this._fadeState.forEach(((e,t)=>{this.completeFade(t)}))}forEachObject(e){this._fadeState.forEach(((t,n)=>{e(n,t)}))}fadeIn(e){let t=this.guaranteeState(e),n=this._fadeState.get(e);n.fadeInTarget=1,n.fadeOutTarget=0,n.fadeOut=0,t&&(this.fadeCount++,1===this.fadeCount&&this.onFadeSetStart&&this.onFadeSetStart(),this.onFadeStart&&this.onFadeStart(e))}fadeOut(e){let t=this.guaranteeState(e),n=this._fadeState.get(e);n.fadeOutTarget=1,t&&(n.fadeInTarget=1,n.fadeIn=1,this.fadeCount++,1===this.fadeCount&&this.onFadeSetStart&&this.onFadeSetStart(),this.onFadeStart&&this.onFadeStart(e))}isFading(e){return this._fadeState.has(e)}isFadingOut(e){let t=this._fadeState.get(e);return t&&1===t.fadeOutTarget}update(){let e=window.performance.now();-1===this._lastTick&&(this._lastTick=e);let t=Vp((e-this._lastTick)/this.duration,0,1);this._lastTick=e,this._fadeState.forEach(((e,n)=>{let{fadeOutTarget:r,fadeInTarget:i}=e,{fadeOut:s,fadeIn:a}=e,o=Math.sign(i-a);a=Vp(a+o*t,0,1);let l=Math.sign(r-s);s=Vp(s+l*t,0,1),e.fadeIn=a,e.fadeOut=s,((1===s||0===s)&&(1===a||0===a)||s>=a)&&this.completeFade(n)}))}},Np=Symbol("FADE_PARAMS");function $p(e,t){if(e[Np])return e[Np];let n={fadeIn:{value:0},fadeOut:{value:0},fadeTexture:{value:null}};return e[Np]=n,e.defines={...e.defines||{},FEATURE_FADE:0},e.onBeforeCompile=e=>{t&&t(e),e.uniforms={...e.uniforms,...n},e.vertexShader=e.vertexShader.replace(/void\s+main\(\)\s+{/,(e=>`\n\t\t\t\t\t#ifdef USE_BATCHING_FRAG\n\n\t\t\t\t\tvarying float vBatchId;\n\n\t\t\t\t\t#endif\n\n\t\t\t\t\t${e}\n\n\t\t\t\t\t\t#ifdef USE_BATCHING_FRAG\n\n\t\t\t\t\t\t// add 0.5 to the value to avoid floating error that may cause flickering\n\t\t\t\t\t\tvBatchId = getIndirectIndex( gl_DrawID ) + 0.5;\n\n\t\t\t\t\t\t#endif\n\t\t\t\t`)),e.fragmentShader=e.fragmentShader.replace(/void main\(/,(e=>`\n\t\t\t\t#if FEATURE_FADE\n\n\t\t\t\t// adapted from https://www.shadertoy.com/view/Mlt3z8\n\t\t\t\tfloat bayerDither2x2( vec2 v ) {\n\n\t\t\t\t\treturn mod( 3.0 * v.y + 2.0 * v.x, 4.0 );\n\n\t\t\t\t}\n\n\t\t\t\tfloat bayerDither4x4( vec2 v ) {\n\n\t\t\t\t\tvec2 P1 = mod( v, 2.0 );\n\t\t\t\t\tvec2 P2 = floor( 0.5 * mod( v, 4.0 ) );\n\t\t\t\t\treturn 4.0 * bayerDither2x2( P1 ) + bayerDither2x2( P2 );\n\n\t\t\t\t}\n\n\t\t\t\t// the USE_BATCHING define is not available in fragment shaders\n\t\t\t\t#ifdef USE_BATCHING_FRAG\n\n\t\t\t\t// functions for reading the fade state of a given batch id\n\t\t\t\tuniform sampler2D fadeTexture;\n\t\t\t\tvarying float vBatchId;\n\t\t\t\tvec2 getFadeValues( const in float i ) {\n\n\t\t\t\t\tint size = textureSize( fadeTexture, 0 ).x;\n\t\t\t\t\tint j = int( i );\n\t\t\t\t\tint x = j % size;\n\t\t\t\t\tint y = j / size;\n\t\t\t\t\treturn texelFetch( fadeTexture, ivec2( x, y ), 0 ).rg;\n\n\t\t\t\t}\n\n\t\t\t\t#else\n\n\t\t\t\tuniform float fadeIn;\n\t\t\t\tuniform float fadeOut;\n\n\t\t\t\t#endif\n\n\t\t\t\t#endif\n\n\t\t\t\t${e}\n\t\t\t`)).replace(/#include <dithering_fragment>/,(e=>`\n\n\t\t\t\t${e}\n\n\t\t\t\t#if FEATURE_FADE\n\n\t\t\t\t#ifdef USE_BATCHING_FRAG\n\n\t\t\t\tvec2 fadeValues = getFadeValues( vBatchId );\n\t\t\t\tfloat fadeIn = fadeValues.r;\n\t\t\t\tfloat fadeOut = fadeValues.g;\n\n\t\t\t\t#endif\n\n\t\t\t\tfloat bayerValue = bayerDither4x4( floor( mod( gl_FragCoord.xy, 4.0 ) ) );\n\t\t\t\tfloat bayerBins = 16.0;\n\t\t\t\tfloat dither = ( 0.5 + bayerValue ) / bayerBins;\n\t\t\t\tif ( dither >= fadeIn ) {\n\n\t\t\t\t\tdiscard;\n\n\t\t\t\t}\n\n\t\t\t\tif ( dither < fadeOut ) {\n\n\t\t\t\t\tdiscard;\n\n\t\t\t\t}\n\n\t\t\t\t#endif\n\n\t\t\t`))},n}var Gp=class{constructor(){this._fadeParams=new WeakMap,this.fading=0}setFade(e,t,n){if(!e)return;let r=this._fadeParams;e.traverse((e=>{let i=e.material;if(i&&r.has(i)){let e=r.get(i);e.fadeIn.value=t,e.fadeOut.value=n;let s=Number(!(0===t||1===t)||!(0===n||1===n));i.defines.FEATURE_FADE!==s&&(this.fading+=1===s?1:-1,i.defines.FEATURE_FADE=s,i.needsUpdate=!0)}}))}prepareScene(e){e.traverse((e=>{e.material&&this.prepareMaterial(e.material)}))}deleteScene(e){if(!e)return;this.setFade(e,1,0);let t=this._fadeParams;e.traverse((e=>{let n=e.material;n&&t.delete(n)}))}prepareMaterial(e){let t=this._fadeParams;t.has(e)||t.set(e,$p(e,e.onBeforeCompile))}},qp=class{constructor(e,t=new r.MeshBasicMaterial){this.other=e,this.material=t,this.visible=!0,this.parent=null,this._instanceInfo=[],this._visibilityChanged=!0;let n=new Proxy(this,{get(t,r){if(r in t)return t[r];{let i=e[r];return i instanceof Function?(...e)=>(t.syncInstances(),i.call(n,...e)):e[r]}},set:(t,n,r)=>(n in t?t[n]=r:e[n]=r,!0),deleteProperty:(t,n)=>n in t?delete t[n]:delete e[n]});return n}syncInstances(){let e=this._instanceInfo,t=this.other._instanceInfo;for(;t.length>e.length;){let n=e.length;e.push(new Proxy({visible:!1},{get:(e,r)=>r in e?e[r]:t[n][r],set:(e,r,i)=>(r in e?e[r]=i:t[n][r]=i,!0)}))}}},Hp=class extends qp{constructor(...e){super(...e);let t=this.material,n=$p(t,t.onBeforeCompile);t.defines.FEATURE_FADE=1,t.defines.USE_BATCHING_FRAG=1,t.needsUpdate=!0,this.fadeTexture=null,this._fadeParams=n}setFadeAt(e,t,n){this._initFadeTexture(),this.fadeTexture.setValueAt(e,255*t,255*n)}_initFadeTexture(){let e=Math.sqrt(this._maxInstanceCount);e=Math.ceil(e);let t=e*e*2,n=this.fadeTexture;if(!n||n.image.data.length!==t){let i=new jp(new Uint8Array(t),e,e,r.RGFormat,r.UnsignedByteType);if(n){n.dispose();let e=n.image.data,t=this.fadeTexture.image.data,r=Math.min(e.length,t.length);t.set(new e.constructor(e.buffer,0,r))}this.fadeTexture=i,this._fadeParams.fadeTexture.value=i,i.needsUpdate=!0}}dispose(){this.fadeTexture&&this.fadeTexture.dispose()}},jp=class extends r.DataTexture{setValueAt(e,...t){let{data:n,width:r,height:i}=this.image,s=Math.floor(n.length/(r*i)),a=!1;for(let o=0;o<s;o++){let r=e*s+o,i=n[r],l=t[o]||0;i!==l&&(n[r]=l,a=!0)}a&&(this.needsUpdate=!0)}},Wp=Symbol("HAS_POPPED_IN");var Xp=new r.Vector3,Yp=new r.Vector3,Kp=new r.Quaternion,Qp=new r.Quaternion,Zp=new r.Vector3;function Jp(){let e=this._fadeManager,t=this._fadeMaterialManager,n=this._fadingBefore,r=this._prevCameraTransforms,{tiles:i,maximumFadeOutTiles:s,batchedMesh:a}=this,{cameras:o}=i;e.update();let l=e.fadeCount;if(0!==n&&0!==l&&(i.dispatchEvent({type:"fade-change"}),i.dispatchEvent({type:"needs-render"})),s<this._fadingOutCount){let t=!0;o.forEach((e=>{if(!r.has(e))return;let n=e.matrixWorld,i=r.get(e);n.decompose(Yp,Qp,Zp),i.decompose(Xp,Kp,Zp);let s=Qp.angleTo(Kp),a=Yp.distanceTo(Xp);t&&(t=s>.25||a>.1)})),t&&e.completeAllFades()}if(o.forEach((e=>{r.get(e).copy(e.matrixWorld)})),e.forEachObject(((e,{fadeIn:n,fadeOut:r})=>{let s=e.engineData.scene;i.markTileUsed(e),s&&t.setFade(s,n,r),this.forEachBatchIds(e,((e,t,i)=>{t.setFadeAt(e,n,r),t.setVisibleAt(e,!0),i.batchedMesh.setVisibleAt(e,!1)}))})),a){let e=i.getPluginByName("BATCHED_TILES_PLUGIN").batchedMesh.material;a.material.map=e.map}}var em=class{get fadeDuration(){return this._fadeManager.duration}set fadeDuration(e){this._fadeManager.duration=Number(e)}get fadingTiles(){return this._fadeManager.fadeCount}constructor(e){e={maximumFadeOutTiles:50,fadeRootTiles:!1,fadeDuration:250,...e},this.name="FADE_TILES_PLUGIN",this.priority=-2,this.tiles=null,this.batchedMesh=null,this._quickFadeTiles=new Set,this._fadeManager=new Op,this._fadeMaterialManager=new Gp,this._prevCameraTransforms=null,this._fadingOutCount=0,this.maximumFadeOutTiles=e.maximumFadeOutTiles,this.fadeRootTiles=e.fadeRootTiles,this.fadeDuration=e.fadeDuration}init(e){this._onLoadModel=({scene:e})=>{this._fadeMaterialManager.prepareScene(e)},this._onDisposeModel=({tile:e,scene:t})=>{this.tiles.visibleTiles.has(e)&&this._quickFadeTiles.add(e.parent),this._fadeManager.deleteObject(e),this._fadeMaterialManager.deleteScene(t)},this._onAddCamera=({camera:e})=>{this._prevCameraTransforms.set(e,new r.Matrix4)},this._onDeleteCamera=({camera:e})=>{this._prevCameraTransforms.delete(e)},this._onTileVisibilityChange=({tile:e})=>{this.forEachBatchIds(e,((e,t,n)=>{t.setFadeAt(e,0,0),t.setVisibleAt(e,!1),n.batchedMesh.setVisibleAt(e,!1)}))},this._onUpdateBefore=()=>{this._fadingBefore=this._fadeManager.fadeCount},this._onUpdateAfter=()=>{Jp.call(this)},e.addEventListener("load-model",this._onLoadModel),e.addEventListener("dispose-model",this._onDisposeModel),e.addEventListener("add-camera",this._onAddCamera),e.addEventListener("delete-camera",this._onDeleteCamera),e.addEventListener("update-before",this._onUpdateBefore),e.addEventListener("update-after",this._onUpdateAfter),e.addEventListener("tile-visibility-change",this._onTileVisibilityChange);let t=this._fadeManager;t.onFadeSetStart=()=>{e.dispatchEvent({type:"fade-start"}),e.dispatchEvent({type:"needs-render"})},t.onFadeSetComplete=()=>{e.dispatchEvent({type:"fade-end"}),e.dispatchEvent({type:"needs-render"})},t.onFadeComplete=(t,n)=>{this._fadeMaterialManager.setFade(t.engineData.scene,0,0),this.forEachBatchIds(t,((e,t,r)=>{t.setFadeAt(e,0,0),t.setVisibleAt(e,!1),r.batchedMesh.setVisibleAt(e,n)})),n||(e.invokeOnePlugin((e=>e!==this&&e.setTileVisible&&e.setTileVisible(t,!1))),this._fadingOutCount--)};let n=new Map;e.cameras.forEach((e=>{n.set(e,new r.Matrix4)})),e.forEachLoadedModel(((e,t)=>{this._onLoadModel({scene:e})})),this.tiles=e,this._fadeManager=t,this._prevCameraTransforms=n}initBatchedMesh(){var e;let t=null==(e=this.tiles.getPluginByName("BATCHED_TILES_PLUGIN"))?void 0:e.batchedMesh;if(t){if(null===this.batchedMesh){this._onBatchedMeshDispose=()=>{this.batchedMesh.dispose(),this.batchedMesh.removeFromParent(),this.batchedMesh=null,t.removeEventListener("dispose",this._onBatchedMeshDispose)};let e=t.material.clone();e.onBeforeCompile=t.material.onBeforeCompile,this.batchedMesh=new Hp(t,e),this.tiles.group.add(this.batchedMesh)}}else null!==this.batchedMesh&&(this._onBatchedMeshDispose(),this._onBatchedMeshDispose=null)}setTileVisible(e,t){let n=this._fadeManager,r=n.isFading(e);if(!function(e){let t=e;for(;t;){if(t.traversal.wasSetActive)return t.traversal.wasInFrustum;t=t.parent}return!1}(e))return r&&n.completeFade(e),!1;if(n.isFadingOut(e)&&this._fadingOutCount--,t?1===e.internal.depthFromRenderedParent?((e[Wp]||this.fadeRootTiles)&&this._fadeManager.fadeIn(e),e[Wp]=!0):this._fadeManager.fadeIn(e):(this._fadingOutCount++,n.fadeOut(e)),this._quickFadeTiles.has(e)&&(this._fadeManager.completeFade(e),this._quickFadeTiles.delete(e)),r)return!0;let i=this._fadeManager.isFading(e);return!(t||!i)}dispose(){let e=this.tiles;this._fadeManager.completeAllFades(),null!==this.batchedMesh&&this._onBatchedMeshDispose(),e.removeEventListener("load-model",this._onLoadModel),e.removeEventListener("dispose-model",this._onDisposeModel),e.removeEventListener("add-camera",this._onAddCamera),e.removeEventListener("delete-camera",this._onDeleteCamera),e.removeEventListener("update-before",this._onUpdateBefore),e.removeEventListener("update-after",this._onUpdateAfter),e.removeEventListener("tile-visibility-change",this._onTileVisibilityChange),e.forEachLoadedModel(((e,t)=>{this._fadeManager.deleteObject(t)}))}forEachBatchIds(e,t){if(this.initBatchedMesh(),this.batchedMesh){let n=this.tiles.getPluginByName("BATCHED_TILES_PLUGIN"),r=n.getTileBatchIds(e);r&&r.forEach((e=>{t(e,this.batchedMesh,n)}))}}};new o(new r.MeshBasicMaterial),new r.DataTexture(new Uint8Array([255,255,255,255]),1,1).needsUpdate=!0;const tm=`https://unpkg.com/three@0.${r.REVISION}.x`,nm="#include <opaque_fragment>",rm=`\n float grayscale = dot(outgoingLight, vec3(0.299, 0.587, 0.114));\n outgoingLight = vec3(grayscale);\n ${nm}\n`;function im(e){const t=e.onBeforeCompile;e.onBeforeCompile=n=>{t.call(e,n),n.fragmentShader=n.fragmentShader.replace(nm,rm)},e.needsUpdate=!0}class sm extends Do{constructor(e,t,n,r={}){super(),this.scene=e,this.camera=t,this.renderer=n,this.tiles=null,this.apiToken=r.apiToken,this.googleMapsToken=r.googleMapsToken,this.initTiles()}initTiles(){this.tiles&&(this.scene.remove(this.tiles.group),this.tiles.dispose(),this.tiles=null),this.dracoLoader=new Je,this.dracoLoader.setDecoderPath(`${tm}/examples/jsm/libs/draco/gltf/`),this.tiles=new dh,this.tiles.errorTarget=40,this.tiles.registerPlugin(new yh({apiToken:this.googleMapsToken,autoRefreshToken:!0})),this.tiles.registerPlugin(new Gd),this.tiles.registerPlugin(new Od),this.tiles.registerPlugin(new zp),this.tiles.registerPlugin(new em),this.tiles.registerPlugin(new Fp({dracoLoader:this.dracoLoader})),this.scene.add(this.tiles.group),this.tiles.setResolutionFromRenderer(this.camera,this.renderer),this.tiles.setCamera(this.camera),this.tiles.addEventListener("load-model",(({scene:e})=>{e.traverse((e=>{Array.isArray(e.material)?e.material.forEach(im):e.material&&im(e.material),e.layers.set(0)}))}))}update(){this.tiles&&(this.tiles.setResolutionFromRenderer(this.camera,this.renderer),this.tiles.setCamera(this.camera),this.tiles.errorTarget=20,this.tiles.update())}dispose(){var e,t;this.tiles&&(this.scene.remove(this.tiles.group),this.tiles.dispose(),this.tiles=null),null==(t=null==(e=this.dracoLoader)?void 0:e.dispose)||t.call(e),this.listeners={}}}var am=Object.freeze({Linear:Object.freeze({None:function(e){return e},In:function(e){return e},Out:function(e){return e},InOut:function(e){return e}}),Quadratic:Object.freeze({In:function(e){return e*e},Out:function(e){return e*(2-e)},InOut:function(e){return(e*=2)<1?.5*e*e:-.5*(--e*(e-2)-1)}}),Cubic:Object.freeze({In:function(e){return e*e*e},Out:function(e){return--e*e*e+1},InOut:function(e){return(e*=2)<1?.5*e*e*e:.5*((e-=2)*e*e+2)}}),Quartic:Object.freeze({In:function(e){return e*e*e*e},Out:function(e){return 1- --e*e*e*e},InOut:function(e){return(e*=2)<1?.5*e*e*e*e:-.5*((e-=2)*e*e*e-2)}}),Quintic:Object.freeze({In:function(e){return e*e*e*e*e},Out:function(e){return--e*e*e*e*e+1},InOut:function(e){return(e*=2)<1?.5*e*e*e*e*e:.5*((e-=2)*e*e*e*e+2)}}),Sinusoidal:Object.freeze({In:function(e){return 1-Math.sin((1-e)*Math.PI/2)},Out:function(e){return Math.sin(e*Math.PI/2)},InOut:function(e){return.5*(1-Math.sin(Math.PI*(.5-e)))}}),Exponential:Object.freeze({In:function(e){return 0===e?0:Math.pow(1024,e-1)},Out:function(e){return 1===e?1:1-Math.pow(2,-10*e)},InOut:function(e){return 0===e?0:1===e?1:(e*=2)<1?.5*Math.pow(1024,e-1):.5*(2-Math.pow(2,-10*(e-1)))}}),Circular:Object.freeze({In:function(e){return 1-Math.sqrt(1-e*e)},Out:function(e){return Math.sqrt(1- --e*e)},InOut:function(e){return(e*=2)<1?-.5*(Math.sqrt(1-e*e)-1):.5*(Math.sqrt(1-(e-=2)*e)+1)}}),Elastic:Object.freeze({In:function(e){return 0===e?0:1===e?1:-Math.pow(2,10*(e-1))*Math.sin(5*(e-1.1)*Math.PI)},Out:function(e){return 0===e?0:1===e?1:Math.pow(2,-10*e)*Math.sin(5*(e-.1)*Math.PI)+1},InOut:function(e){return 0===e?0:1===e?1:(e*=2)<1?-.5*Math.pow(2,10*(e-1))*Math.sin(5*(e-1.1)*Math.PI):.5*Math.pow(2,-10*(e-1))*Math.sin(5*(e-1.1)*Math.PI)+1}}),Back:Object.freeze({In:function(e){var t=1.70158;return 1===e?1:e*e*((t+1)*e-t)},Out:function(e){var t=1.70158;return 0===e?0:--e*e*((t+1)*e+t)+1},InOut:function(e){var t=2.5949095;return(e*=2)<1?e*e*((t+1)*e-t)*.5:.5*((e-=2)*e*((t+1)*e+t)+2)}}),Bounce:Object.freeze({In:function(e){return 1-am.Bounce.Out(1-e)},Out:function(e){return e<1/2.75?7.5625*e*e:e<2/2.75?7.5625*(e-=1.5/2.75)*e+.75:e<2.5/2.75?7.5625*(e-=2.25/2.75)*e+.9375:7.5625*(e-=2.625/2.75)*e+.984375},InOut:function(e){return e<.5?.5*am.Bounce.In(2*e):.5*am.Bounce.Out(2*e-1)+.5}}),generatePow:function(e){return void 0===e&&(e=4),e=(e=e<Number.EPSILON?Number.EPSILON:e)>1e4?1e4:e,{In:function(t){return Math.pow(t,e)},Out:function(t){return 1-Math.pow(1-t,e)},InOut:function(t){return t<.5?Math.pow(2*t,e)/2:(1-Math.pow(2-2*t,e))/2+.5}}}}),om=function(){return performance.now()},lm=function(){function e(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this._tweens={},this._tweensAddedDuringUpdate={},this.add.apply(this,e)}return e.prototype.getAll=function(){var e=this;return Object.keys(this._tweens).map((function(t){return e._tweens[t]}))},e.prototype.removeAll=function(){this._tweens={}},e.prototype.add=function(){for(var e,t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];for(var r=0,i=t;r<i.length;r++){var s=i[r];null===(e=s._group)||void 0===e||e.remove(s),s._group=this,this._tweens[s.getId()]=s,this._tweensAddedDuringUpdate[s.getId()]=s}},e.prototype.remove=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];for(var n=0,r=e;n<r.length;n++){var i=r[n];i._group=void 0,delete this._tweens[i.getId()],delete this._tweensAddedDuringUpdate[i.getId()]}},e.prototype.allStopped=function(){return this.getAll().every((function(e){return!e.isPlaying()}))},e.prototype.update=function(e,t){void 0===e&&(e=om()),void 0===t&&(t=!0);var n=Object.keys(this._tweens);if(0!==n.length)for(;n.length>0;){this._tweensAddedDuringUpdate={};for(var r=0;r<n.length;r++){var i=this._tweens[n[r]],s=!t;i&&!1===i.update(e,s)&&!t&&this.remove(i)}n=Object.keys(this._tweensAddedDuringUpdate)}},e}(),cm={Linear:function(e,t){var n=e.length-1,r=n*t,i=Math.floor(r),s=cm.Utils.Linear;return t<0?s(e[0],e[1],r):t>1?s(e[n],e[n-1],n-r):s(e[i],e[i+1>n?n:i+1],r-i)},Utils:{Linear:function(e,t,n){return(t-e)*n+e}}},um=function(){function e(){}return e.nextId=function(){return e._nextId++},e._nextId=0,e}(),hm=new lm,dm=function(){function e(e,t){this._isPaused=!1,this._pauseStart=0,this._valuesStart={},this._valuesEnd={},this._valuesStartRepeat={},this._duration=1e3,this._isDynamic=!1,this._initialRepeat=0,this._repeat=0,this._yoyo=!1,this._isPlaying=!1,this._reversed=!1,this._delayTime=0,this._startTime=0,this._easingFunction=am.Linear.None,this._interpolationFunction=cm.Linear,this._chainedTweens=[],this._onStartCallbackFired=!1,this._onEveryStartCallbackFired=!1,this._id=um.nextId(),this._isChainStopped=!1,this._propertiesAreSetUp=!1,this._goToEnd=!1,this._object=e,"object"==typeof t?(this._group=t,t.add(this)):!0===t&&(this._group=hm,hm.add(this))}return e.prototype.getId=function(){return this._id},e.prototype.isPlaying=function(){return this._isPlaying},e.prototype.isPaused=function(){return this._isPaused},e.prototype.getDuration=function(){return this._duration},e.prototype.to=function(e,t){if(void 0===t&&(t=1e3),this._isPlaying)throw new Error("Can not call Tween.to() while Tween is already started or paused. Stop the Tween first.");return this._valuesEnd=e,this._propertiesAreSetUp=!1,this._duration=t<0?0:t,this},e.prototype.duration=function(e){return void 0===e&&(e=1e3),this._duration=e<0?0:e,this},e.prototype.dynamic=function(e){return void 0===e&&(e=!1),this._isDynamic=e,this},e.prototype.start=function(e,t){if(void 0===e&&(e=om()),void 0===t&&(t=!1),this._isPlaying)return this;if(this._repeat=this._initialRepeat,this._reversed)for(var n in this._reversed=!1,this._valuesStartRepeat)this._swapEndStartRepeatValues(n),this._valuesStart[n]=this._valuesStartRepeat[n];if(this._isPlaying=!0,this._isPaused=!1,this._onStartCallbackFired=!1,this._onEveryStartCallbackFired=!1,this._isChainStopped=!1,this._startTime=e,this._startTime+=this._delayTime,!this._propertiesAreSetUp||t){if(this._propertiesAreSetUp=!0,!this._isDynamic){var r={};for(var i in this._valuesEnd)r[i]=this._valuesEnd[i];this._valuesEnd=r}this._setupProperties(this._object,this._valuesStart,this._valuesEnd,this._valuesStartRepeat,t)}return this},e.prototype.startFromCurrentValues=function(e){return this.start(e,!0)},e.prototype._setupProperties=function(e,t,n,r,i){for(var s in n){var a=e[s],o=Array.isArray(a),l=o?"array":typeof a,c=!o&&Array.isArray(n[s]);if("undefined"!==l&&"function"!==l){if(c){if(0===(g=n[s]).length)continue;for(var u=[a],h=0,d=g.length;h<d;h+=1){var p=this._handleRelativeValue(a,g[h]);if(isNaN(p)){c=!1;break}u.push(p)}c&&(n[s]=u)}if("object"!==l&&!o||!a||c)(void 0===t[s]||i)&&(t[s]=a),o||(t[s]*=1),r[s]=c?n[s].slice().reverse():t[s]||0;else{t[s]=o?[]:{};var m=a;for(var f in m)t[s][f]=m[f];r[s]=o?[]:{};var g=n[s];if(!this._isDynamic){var x={};for(var f in g)x[f]=g[f];n[s]=g=x}this._setupProperties(m,t[s],g,r[s],i)}}}},e.prototype.stop=function(){return this._isChainStopped||(this._isChainStopped=!0,this.stopChainedTweens()),this._isPlaying?(this._isPlaying=!1,this._isPaused=!1,this._onStopCallback&&this._onStopCallback(this._object),this):this},e.prototype.end=function(){return this._goToEnd=!0,this.update(this._startTime+this._duration),this},e.prototype.pause=function(e){return void 0===e&&(e=om()),this._isPaused||!this._isPlaying||(this._isPaused=!0,this._pauseStart=e),this},e.prototype.resume=function(e){return void 0===e&&(e=om()),this._isPaused&&this._isPlaying?(this._isPaused=!1,this._startTime+=e-this._pauseStart,this._pauseStart=0,this):this},e.prototype.stopChainedTweens=function(){for(var e=0,t=this._chainedTweens.length;e<t;e++)this._chainedTweens[e].stop();return this},e.prototype.group=function(e){return e?(e.add(this),this):this},e.prototype.remove=function(){var e;return null===(e=this._group)||void 0===e||e.remove(this),this},e.prototype.delay=function(e){return void 0===e&&(e=0),this._delayTime=e,this},e.prototype.repeat=function(e){return void 0===e&&(e=0),this._initialRepeat=e,this._repeat=e,this},e.prototype.repeatDelay=function(e){return this._repeatDelayTime=e,this},e.prototype.yoyo=function(e){return void 0===e&&(e=!1),this._yoyo=e,this},e.prototype.easing=function(e){return void 0===e&&(e=am.Linear.None),this._easingFunction=e,this},e.prototype.interpolation=function(e){return void 0===e&&(e=cm.Linear),this._interpolationFunction=e,this},e.prototype.chain=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return this._chainedTweens=e,this},e.prototype.onStart=function(e){return this._onStartCallback=e,this},e.prototype.onEveryStart=function(e){return this._onEveryStartCallback=e,this},e.prototype.onUpdate=function(e){return this._onUpdateCallback=e,this},e.prototype.onRepeat=function(e){return this._onRepeatCallback=e,this},e.prototype.onComplete=function(e){return this._onCompleteCallback=e,this},e.prototype.onStop=function(e){return this._onStopCallback=e,this},e.prototype.update=function(t,n){var r,i,s=this;if(void 0===t&&(t=om()),void 0===n&&(n=e.autoStartOnUpdate),this._isPaused)return!0;if(!this._goToEnd&&!this._isPlaying){if(!n)return!1;this.start(t,!0)}if(this._goToEnd=!1,t<this._startTime)return!0;!1===this._onStartCallbackFired&&(this._onStartCallback&&this._onStartCallback(this._object),this._onStartCallbackFired=!0),!1===this._onEveryStartCallbackFired&&(this._onEveryStartCallback&&this._onEveryStartCallback(this._object),this._onEveryStartCallbackFired=!0);var a=t-this._startTime,o=this._duration+(null!==(r=this._repeatDelayTime)&&void 0!==r?r:this._delayTime),l=this._duration+this._repeat*o,c=function(){if(0===s._duration)return 1;if(a>l)return 1;var e=Math.trunc(a/o),t=a-e*o,n=Math.min(t/s._duration,1);return 0===n&&a===s._duration?1:n}(),u=this._easingFunction(c);if(this._updateProperties(this._object,this._valuesStart,this._valuesEnd,u),this._onUpdateCallback&&this._onUpdateCallback(this._object,c),0===this._duration||a>=this._duration){if(this._repeat>0){var h=Math.min(Math.trunc((a-this._duration)/o)+1,this._repeat);for(i in isFinite(this._repeat)&&(this._repeat-=h),this._valuesStartRepeat)this._yoyo||"string"!=typeof this._valuesEnd[i]||(this._valuesStartRepeat[i]=this._valuesStartRepeat[i]+parseFloat(this._valuesEnd[i])),this._yoyo&&this._swapEndStartRepeatValues(i),this._valuesStart[i]=this._valuesStartRepeat[i];return this._yoyo&&(this._reversed=!this._reversed),this._startTime+=o*h,this._onRepeatCallback&&this._onRepeatCallback(this._object),this._onEveryStartCallbackFired=!1,!0}this._onCompleteCallback&&this._onCompleteCallback(this._object);for(var d=0,p=this._chainedTweens.length;d<p;d++)this._chainedTweens[d].start(this._startTime+this._duration,!1);return this._isPlaying=!1,!1}return!0},e.prototype._updateProperties=function(e,t,n,r){for(var i in n)if(void 0!==t[i]){var s=t[i]||0,a=n[i],o=Array.isArray(e[i]),l=Array.isArray(a);!o&&l?e[i]=this._interpolationFunction(a,r):"object"==typeof a&&a?this._updateProperties(e[i],s,a,r):"number"==typeof(a=this._handleRelativeValue(s,a))&&(e[i]=s+(a-s)*r)}},e.prototype._handleRelativeValue=function(e,t){return"string"!=typeof t?t:"+"===t.charAt(0)||"-"===t.charAt(0)?e+parseFloat(t):parseFloat(t)},e.prototype._swapEndStartRepeatValues=function(e){var t=this._valuesStartRepeat[e],n=this._valuesEnd[e];this._valuesStartRepeat[e]="string"==typeof n?this._valuesStartRepeat[e]+parseFloat(n):this._valuesEnd[e],this._valuesEnd[e]=t},e.autoStartOnUpdate=!1,e}();um.nextId;var pm=hm;pm.getAll.bind(pm),pm.removeAll.bind(pm),pm.add.bind(pm),pm.remove.bind(pm),pm.update.bind(pm);const mm={CESIUM:void 0,GOOGLEMAPS:void 0},fm=2e3;({Easing:am}).Easing.Quartic.InOut;function gm(e,t={}){return new Promise(((n,i)=>{const s=new vn;s.setDataType(t.floatType||r.HalfFloatType),s.load(e,(e=>{n(e)}),(e=>{}),(e=>{i(e)}))}))}var xm,ym,vm={exports:{}};function bm(e,t,n){const r=6378137,i=.081819190842622,s=r*r,a=i*i,o=Math.sqrt(s*(1-a)),l=o*o,c=Math.sqrt((s-l)/l),u=Math.sqrt(e*e+t*t),h=Math.atan2(r*n,o*u),d=Math.atan2(t,e),p=Math.atan2(n+c*c*o*Math.sin(h)**3,u-a*r*Math.cos(h)**3),m=r/Math.sqrt(1-a*Math.sin(p)*Math.sin(p)),f=u/Math.cos(p)-m;return{lon:d*(180/Math.PI),lat:p*(180/Math.PI),alt:f}}function wm(e,t,n){const r=.081819190842622,i=r*r,s=t*(Math.PI/180),a=e*(Math.PI/180),o=6378137/Math.sqrt(1-i*Math.sin(s)**2);return[(o+n)*Math.cos(s)*Math.cos(a),(o+n)*Math.cos(s)*Math.sin(a),((1-i)*o+n)*Math.sin(s)]}function Tm(e,t){const n=r.MathUtils.degToRad(e),i=r.MathUtils.degToRad(t);return new r.Vector3(Math.cos(i)*Math.cos(n),Math.cos(i)*Math.sin(n),Math.sin(i)).normalize()}function Sm(e,t,n,i,s){const a=Tm(e,t);n+=90;const o=new r.Vector3(0,0,1),l=o.clone().sub(a.clone().multiplyScalar(o.dot(a))).normalize(),c=(new r.Vector3).crossVectors(l,a).normalize(),u=(new r.Matrix4).makeBasis(c,l,a),h=new r.Euler(r.MathUtils.degToRad(n),r.MathUtils.degToRad(s),r.MathUtils.degToRad(i),"ZYX"),d=(new r.Quaternion).setFromEuler(h);return(new r.Quaternion).setFromRotationMatrix(u).multiply(d)}function _m(e,t){const n=(new r.Vector3).subVectors(t,e).normalize(),i=e.clone().normalize();Math.abs(n.dot(i))>.99&&i.set(0,0,1);const s=(new r.Vector3).crossVectors(n,i).normalize();return(new r.Vector3).crossVectors(s,n).normalize()}xm||(xm=1,vm.exports=((ym=function(){function e(e){return r.appendChild(e.dom),e}function t(e){for(var t=0;t<r.children.length;t++)r.children[t].style.display=t===e?"block":"none";n=e}var n=0,r=document.createElement("div");r.style.cssText="position:fixed;top:0;left:0;cursor:pointer;opacity:0.9;z-index:10000",r.addEventListener("click",(function(e){e.preventDefault(),t(++n%r.children.length)}),!1);var i=(performance||Date).now(),s=i,a=0,o=e(new ym.Panel("FPS","#0ff","#002")),l=e(new ym.Panel("MS","#0f0","#020"));if(self.performance&&self.performance.memory)var c=e(new ym.Panel("MB","#f08","#201"));return t(0),{REVISION:16,dom:r,addPanel:e,showPanel:t,begin:function(){i=(performance||Date).now()},end:function(){a++;var e=(performance||Date).now();if(l.update(e-i,200),e>s+1e3&&(o.update(1e3*a/(e-s),100),s=e,a=0,c)){var t=performance.memory;c.update(t.usedJSHeapSize/1048576,t.jsHeapSizeLimit/1048576)}return e},update:function(){i=this.end()},domElement:r,setMode:t}}).Panel=function(e,t,n){var r=1/0,i=0,s=Math.round,a=s(window.devicePixelRatio||1),o=80*a,l=48*a,c=3*a,u=2*a,h=3*a,d=15*a,p=74*a,m=30*a,f=document.createElement("canvas");f.width=o,f.height=l,f.style.cssText="width:80px;height:48px";var g=f.getContext("2d");return g.font="bold "+9*a+"px Helvetica,Arial,sans-serif",g.textBaseline="top",g.fillStyle=n,g.fillRect(0,0,o,l),g.fillStyle=t,g.fillText(e,c,u),g.fillRect(h,d,p,m),g.fillStyle=n,g.globalAlpha=.9,g.fillRect(h,d,p,m),{dom:f,update:function(l,x){r=Math.min(r,l),i=Math.max(i,l),g.fillStyle=n,g.globalAlpha=1,g.fillRect(0,0,o,d),g.fillStyle=t,g.fillText(s(l)+" "+e+" ("+s(r)+"-"+s(i)+")",c,u),g.drawImage(f,h+a,d,p-a,m,h,d,p-a,m),g.fillRect(h+p-a,d,a,m),g.fillStyle=n,g.globalAlpha=.9,g.fillRect(h+p-a,d,a,s((1-l/x)*m))}}},ym));class Mm extends Do{constructor(e){super(),this.camera=e,this.lookAt=new r.Vector3,this.cameraTween=null,this.lookAtTween=null,this.is2D=!1}animateTo(e,t,n=fm){return new Promise(((i,s)=>{const a=this.camera.position.clone(),o=this.camera.quaternion.clone(),l=e.clone(),c=t.clone(),u=l.clone().sub(a).length(),h=c.clone().multiply(o.clone().invert()),d=Math.acos(Math.min(1,h.w));if(u<1&&d<1)i();else{const e=new r.Vector3(0,0,.25*-u).applyQuaternion(o).add(a),t=new r.Vector3(0,0,.25*-u).applyQuaternion(c).add(l),s=_m(a,e),h=_m(l,t);this.camera.up.copy(s),this.lookAt.copy(e),this.lookAtTween=new dm(this.lookAt).to(t,n).easing(am.Quartic.InOut).onComplete((()=>{this.lookAt.copy(t),this.lookAtTween=null})).start(),this.cameraTween=new dm(this.camera).to({position:l,up:h},n).easing(am.Quartic.InOut).onComplete((()=>{this.camera.position.copy(l),this.cameraTween=null,i()})).start()}}))}update(e){this.cameraUpTween&&this.cameraUpTween.update(e),this.cameraTween&&this.cameraTween.update(e),this.lookAtTween&&this.lookAtTween.update(e),(this.cameraTween||this.lookAtTween)&&this.camera.lookAt(this.lookAt)}cancel(){this.cameraTween&&(this.cameraTween.stop(),this.cameraTween=null),this.lookAtTween&&(this.lookAtTween.stop(),this.lookAtTween=null),this.cameraUpTween&&(this.cameraUpTween.stop(),this.cameraUpTween=null)}}class Am extends r.Mesh{constructor(){const e=new r.ShaderMaterial({name:"SkyMaterial",uniforms:{turbidity:{value:5},rayleigh:{value:1},mieCoefficient:{value:.005},mieDirectionalG:{value:.5},sunPosition:{value:new r.Vector3},up:{value:new r.Vector3(0,1,0)},surfaceUp:{value:new r.Vector3(0,1,0)}},vertexShader:"uniform vec3 sunPosition;uniform float rayleigh;uniform float turbidity;uniform float mieCoefficient;uniform vec3 up;varying vec3 vWorldPosition;varying vec3 vSunDirection;varying float vSunfade;varying vec3 vBetaR;varying vec3 vBetaM;varying float vSunE;const float e=2.71828182845904523536028747135266249775724709369995957;const float pi=3.141592653589793238462643383279502884197169;const vec3 lambda=vec3(680E-9,550E-9,450E-9);const vec3 totalRayleigh=vec3(5.804542996261093E-6,1.3562911419845635E-5,3.0265902468824876E-5);const float v=4.0;const vec3 K=vec3(0.686,0.678,0.666);const vec3 MieConst=vec3(1.8399918514433978E14,2.7798023919660528E14,4.0790479543861094E14);const float cutoffAngle=1.6110731556870734;const float steepness=1.5;const float EE=1000.0;float sunIntensity(float zenithAngleCos){zenithAngleCos=clamp(zenithAngleCos,-1.0,1.0);return EE*max(0.0,1.0-pow(e,-((cutoffAngle-acos(zenithAngleCos))/steepness)));}vec3 totalMie(float T){float c=(0.2*T)*10E-18;return 0.434*c*MieConst;}void main(){vec4 worldPosition=modelMatrix*vec4(position,1.0);vWorldPosition=worldPosition.xyz;gl_Position=projectionMatrix*modelViewMatrix*vec4(position,1.0);gl_Position.z=gl_Position.w;vSunDirection=normalize(sunPosition);vSunE=sunIntensity(dot(vSunDirection,up));vSunfade=1.0-clamp(1.0-exp((sunPosition.y/450000.0)),0.0,1.0);float rayleighCoefficient=rayleigh-(1.0*(1.0-vSunfade));vBetaR=totalRayleigh*rayleighCoefficient;vBetaM=totalMie(turbidity)*mieCoefficient;}",fragmentShader:"varying vec3 vWorldPosition;varying vec3 vSunDirection;varying float vSunfade;varying vec3 vBetaR;varying vec3 vBetaM;varying float vSunE;uniform float mieDirectionalG;uniform vec3 up;uniform vec3 surfaceUp;const float pi=3.141592653589793238462643383279502884197169;const float n=1.0003;const float N=2.545E25;const float rayleighZenithLength=8.4E3;const float mieZenithLength=1.25E3;const float sunAngularDiameterCos=0.999956676946448443553574619906976478926848692873900859324;const float THREE_OVER_SIXTEENPI=0.05968310365946075;const float ONE_OVER_FOURPI=0.07957747154594767;float rayleighPhase(float cosTheta){return THREE_OVER_SIXTEENPI*(1.0+pow(cosTheta,2.0));}float hgPhase(float cosTheta,float g){float g2=pow(g,2.0);float inverse=1.0/pow(1.0-2.0*g*cosTheta+g2,1.5);return ONE_OVER_FOURPI*((1.0-g2)*inverse);}void main(){vec3 direction=normalize(vWorldPosition-cameraPosition);float zenithAngle=acos(max(0.0,dot(surfaceUp,direction)));float inverse=1.0/(cos(zenithAngle)+0.15*pow(93.885-((zenithAngle*180.0)/pi),-1.253));float sR=rayleighZenithLength*inverse;float sM=mieZenithLength*inverse;vec3 Fex=exp(-(vBetaR*sR+vBetaM*sM));float cosTheta=dot(direction,vSunDirection);float rPhase=rayleighPhase(cosTheta*0.5+0.5);vec3 betaRTheta=vBetaR*rPhase;float mPhase=hgPhase(cosTheta,mieDirectionalG);vec3 betaMTheta=vBetaM*mPhase;vec3 Lin=pow(vSunE*((betaRTheta+betaMTheta)/(vBetaR+vBetaM))*(1.0-Fex),vec3(1.5));Lin*=mix(vec3(1.0),pow(vSunE*((betaRTheta+betaMTheta)/(vBetaR+vBetaM))*Fex,vec3(1.0/2.0)),clamp(pow(1.0-dot(up,vSunDirection),5.0),0.0,1.0));float theta=acos(direction.y);float phi=atan(direction.z,direction.x);vec2 uv=vec2(phi,theta)/vec2(2.0*pi,pi)+vec2(0.5,0.0);vec3 L0=vec3(0.1)*Fex;float sundisk=smoothstep(sunAngularDiameterCos,sunAngularDiameterCos+0.00002,cosTheta);L0+=(vSunE*19000.0*Fex)*sundisk;vec3 texColor=(Lin+L0)*0.04+vec3(0.0,0.0003,0.00075);vec3 retColor=pow(texColor,vec3(1.0/(1.2+(1.2*vSunfade))));gl_FragColor=vec4(retColor,1.0);\n#include <tonemapping_fragment>\n#include <colorspace_fragment>\n}",side:r.BackSide,depthWrite:!1});super(new r.BoxGeometry(1,1,1),e),this.isSky=!0,this.type="Sky",this.material=e}setSurfaceUp(e){this.material.uniforms.surfaceUp.value.copy(e)}}class Em extends r.Object3D{constructor(){super(),this.type="ContentLayer",this.isContentLayer=!0,this.labels=new Set}setLabels(e){this.labels.clear();for(let t=0;t<e.length;t++)this.labels.add(e[t])}setEnabled(e){this.visible=e}update(){}dispose(){}disposeObjectResources(e=this){e.traverse((e=>{var t,n,r,i;if(null==(n=null==(t=e.geometry)?void 0:t.dispose)||n.call(t),!e.material)return;const s=Array.isArray(e.material)?e.material:[e.material];for(const a of s){for(const e of Object.values(a))(null==e?void 0:e.isTexture)&&(null==(r=e.dispose)||r.call(e));null==(i=a.dispose)||i.call(a)}}))}}const Cm=`https://unpkg.com/three@0.${r.REVISION}.x`;class Rm extends Em{constructor(e,t={}){super(),this.type="TilesLayer",this.isTilesLayer=!0;const n=(null==t?void 0:t.renderOrder)??0,i=(null==t?void 0:t.implicit)??!1,s="overlay"==(null==t?void 0:t.blendeMode),a=(null==t?void 0:t.offset)??{lon:0,lat:0,alt:0};this.firstSet=(null==t?void 0:t.firstSet)??null,this.camera=(null==t?void 0:t.camera)??null,this.renderer=(null==t?void 0:t.renderer)??null,this.dracoLoader=new Je,this.dracoLoader.setDecoderPath(`${Cm}/examples/jsm/libs/draco/gltf/`),this.ktx2loader=new pn,this.ktx2loader.setTranscoderPath(`${Cm}/examples/jsm/libs/basis/`),this.ktx2loader.detectSupport(this.renderer),this.layers.set(n);const o=new dh(e);e.startsWith("http")||o.registerPlugin(new Bd({apiToken:Tokens.CESIUM,assetId:e,autoRefreshToken:!0})),i&&o.registerPlugin(new _h),o.registerPlugin(new Fp({rtc:!0,dracoLoader:this.dracoLoader,ktxLoader:this.ktx2loader})),o.errorTarget=20,this.firstSet&&(o.lruCache=this.firstSet.lruCache,o.downloadQueue=this.firstSet.downloadQueue,o.parseQueue=this.firstSet.parseQueue,o.processNodeQueue=this.firstSet.processNodeQueue),o.setCamera(this.camera),o.setResolutionFromRenderer(this.camera,this.renderer),o.addEventListener("load-model",(e=>{if(0===e.tile.__depth){const t=e.tile.cached.scene.position,n=bm(...t.toArray()),i={lon:n.lon+a.lon,lat:n.lat+a.lat,alt:n.alt+a.alt},s=wm(i.lon,i.lat,i.alt),l=(new r.Vector3).fromArray(s).sub(t);o.group.position.add(l)}e.scene.traverse((e=>{e.layers.mask=this.layers.mask,e.material&&(e.material.isPointsMaterial?(e.material.sizeAttenuation=!0,e.material.size=.2,e.material.map=(new r.TextureLoader).load("/assets/viewer/dot.png",(e=>{})),e.material.alphaTest=.1,e.material.transparent=!0,e.material.onBeforeCompile=e=>{e.vertexShader="uniform float size;uniform float scale;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\n#ifdef USE_POINTS_UV\nvarying vec2 vUv;uniform mat3 uvTransform;\n#endif\nvoid main(){\n#ifdef USE_POINTS_UV\nvUv=(uvTransform*vec3(uv,1)).xy;\n#endif\n#include <color_vertex>\n#include <morphinstance_vertex>\n#include <morphcolor_vertex>\n#include <begin_vertex>\n#include <morphtarget_vertex>\n#include <project_vertex>\ngl_PointSize=size;bool isPerspective=isPerspectiveMatrix(projectionMatrix);if(isPerspective){gl_PointSize*=(scale/-mvPosition.z);gl_PointSize=max(gl_PointSize,5.0);}\n#include <logdepthbuf_vertex>\n#include <clipping_planes_vertex>\n#include <worldpos_vertex>\n#include <fog_vertex>\n}",e.fragmentShader="uniform vec3 diffuse;uniform float opacity;\n#include <common>\n#include <color_pars_fragment>\n#include <map_particle_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main(){vec4 diffuseColor=vec4(diffuse,opacity);\n#include <clipping_planes_fragment>\nvec3 outgoingLight=vec3(0.0);\n#include <logdepthbuf_fragment>\n#include <map_particle_fragment>\n#include <color_fragment>\n#include <alphatest_fragment>\n#include <alphahash_fragment>\noutgoingLight=diffuseColor.rgb;\n#include <opaque_fragment>\n#include <tonemapping_fragment>\n#include <colorspace_fragment>\n#include <fog_fragment>\n#include <premultiplied_alpha_fragment>\n}"}):(e.material.onBeforeCompile=e=>{s&&(e.vertexShader="#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main(){\n#include <uv_vertex>\n#include <color_vertex>\n#include <morphinstance_vertex>\n#include <morphcolor_vertex>\n#include <batching_vertex>\n#if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )\n#include <beginnormal_vertex>\n#include <morphnormal_vertex>\n#include <skinbase_vertex>\n#include <skinnormal_vertex>\n#include <defaultnormal_vertex>\n#endif\n#include <begin_vertex>\n#include <morphtarget_vertex>\n#include <skinning_vertex>\n#include <project_vertex>\n#include <logdepthbuf_vertex>\n#include <clipping_planes_vertex>\n#include <worldpos_vertex>\n#include <envmap_vertex>\n#include <fog_vertex>\n}",e.fragmentShader="uniform vec3 diffuse;uniform float opacity;\n#ifndef FLAT_SHADED\nvarying vec3 vNormal;\n#endif\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nuniform float overlayMode;void main(){vec4 diffuseColor=vec4(diffuse,opacity);\n#include <clipping_planes_fragment>\n#include <logdepthbuf_fragment>\n#include <map_fragment>\n#include <color_fragment>\n#include <alphamap_fragment>\n#include <alphatest_fragment>\n#include <alphahash_fragment>\n#include <specularmap_fragment>\nReflectedLight reflectedLight=ReflectedLight(vec3(0.0),vec3(0.0),vec3(0.0),vec3(0.0));\n#ifdef USE_LIGHTMAP\nvec4 lightMapTexel=texture2D(lightMap,vLightMapUv);reflectedLight.indirectDiffuse+=lightMapTexel.rgb*lightMapIntensity*RECIPROCAL_PI;\n#else\nreflectedLight.indirectDiffuse+=vec3(1.0);\n#endif\n#include <aomap_fragment>\nreflectedLight.indirectDiffuse*=diffuseColor.rgb;vec3 outgoingLight=reflectedLight.indirectDiffuse;\n#include <envmap_fragment>\n#include <opaque_fragment>\n#include <tonemapping_fragment>\n#include <colorspace_fragment>\n#include <fog_fragment>\n#include <premultiplied_alpha_fragment>\ngl_FragColor=mix(gl_FragColor,vec4(gl_FragColor.rgb,gl_FragColor.a*pow(gl_FragColor.b,0.667)),overlayMode);}",e.uniforms.overlayMode={value:s?1:0})},s&&(e.material.transparent=!0,e.material.alphaTest=.1)))}))})),o.addEventListener("load-tile-set",(e=>{})),this.tiles=o,this.add(o.group)}update(){super.update(),this.visible&&this.tiles.update()}dispose(){var e,t,n,r;super.dispose(),this.tiles&&(this.tiles.dispose(),this.remove(this.tiles.group),this.tiles=null),null==(t=null==(e=this.dracoLoader)?void 0:e.dispose)||t.call(e),null==(r=null==(n=this.ktx2loader)?void 0:n.dispose)||r.call(n)}}class Dm extends Em{constructor(e,t={}){super(),this.type="MeshLayer",this.isMeshLayer=!0;const n=(null==t?void 0:t.renderOrder)??0;null==t||t.offset;(new rt).load(e,(e=>{const t=e.scene;e.scene.layers.set(6);for(let n=0;n<t.children[0].children.length;n++){const e=t.children[0].children[n];e.layers.set(6),e.material.transparent=!0,e.material.onBeforeCompile=e=>{e.fragmentShader="uniform vec3 diffuse;uniform float opacity;\n#ifndef FLAT_SHADED\nvarying vec3 vNormal;\n#endif\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main(){vec4 diffuseColor=vec4(diffuse,opacity);\n#include <clipping_planes_fragment>\n#include <logdepthbuf_fragment>\n#include <map_fragment>\n#include <alphamap_fragment>\n#include <alphatest_fragment>\n#include <alphahash_fragment>\n#include <specularmap_fragment>\nReflectedLight reflectedLight=ReflectedLight(vec3(0.0),vec3(0.0),vec3(0.0),vec3(0.0));\n#ifdef USE_LIGHTMAP\nvec4 lightMapTexel=texture2D(lightMap,vLightMapUv);reflectedLight.indirectDiffuse+=lightMapTexel.rgb*lightMapIntensity*RECIPROCAL_PI;\n#else\nreflectedLight.indirectDiffuse+=vec3(1.0);\n#endif\n#include <aomap_fragment>\nreflectedLight.indirectDiffuse*=diffuseColor.rgb;vec3 outgoingLight=reflectedLight.indirectDiffuse;\n#include <envmap_fragment>\n#include <opaque_fragment>\n#include <tonemapping_fragment>\n#include <colorspace_fragment>\n#include <fog_fragment>\n#include <premultiplied_alpha_fragment>\n#include <dithering_fragment>\n#ifdef USE_COLOR\ngl_FragColor.a=vColor.r;\n#endif\n}"}}this.mesh=t,this.add(t)})),this.layers.set(n)}dispose(){this.mesh&&(this.disposeObjectResources(this.mesh),this.mesh.removeFromParent(),this.mesh=null)}}var km="#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvarying float vOpacity;void main(){\n#include <uv_vertex>\n#include <color_vertex>\n#include <morphinstance_vertex>\n#include <morphcolor_vertex>\n#include <batching_vertex>\n#if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )\n#include <beginnormal_vertex>\n#include <morphnormal_vertex>\n#include <skinbase_vertex>\n#include <skinnormal_vertex>\n#include <defaultnormal_vertex>\n#endif\n#include <begin_vertex>\n#include <morphtarget_vertex>\n#include <skinning_vertex>\n#include <project_vertex>\n#include <logdepthbuf_vertex>\n#include <clipping_planes_vertex>\n#include <worldpos_vertex>\n#include <envmap_vertex>\n#include <fog_vertex>\nvOpacity=smoothstep(100.0,500.0,-mvPosition.z);}",Im="uniform vec3 diffuse;uniform float opacity;\n#ifndef FLAT_SHADED\nvarying vec3 vNormal;\n#endif\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvarying float vOpacity;void main(){vec4 diffuseColor=vec4(diffuse,opacity);\n#include <clipping_planes_fragment>\n#include <logdepthbuf_fragment>\n#include <map_fragment>\n#include <color_fragment>\n#include <alphamap_fragment>\n#include <alphatest_fragment>\n#include <alphahash_fragment>\n#include <specularmap_fragment>\nReflectedLight reflectedLight=ReflectedLight(vec3(0.0),vec3(0.0),vec3(0.0),vec3(0.0));\n#ifdef USE_LIGHTMAP\nvec4 lightMapTexel=texture2D(lightMap,vLightMapUv);reflectedLight.indirectDiffuse+=lightMapTexel.rgb*lightMapIntensity*RECIPROCAL_PI;\n#else\nreflectedLight.indirectDiffuse+=vec3(1.0);\n#endif\n#include <aomap_fragment>\nreflectedLight.indirectDiffuse*=diffuseColor.rgb;vec3 outgoingLight=reflectedLight.indirectDiffuse;\n#include <envmap_fragment>\n#include <opaque_fragment>\n#include <tonemapping_fragment>\n#include <colorspace_fragment>\n#include <fog_fragment>\n#include <premultiplied_alpha_fragment>\n#include <dithering_fragment>\ngl_FragColor.a*=vOpacity;}";const Pm=new class{constructor(e=4){this.limit=e,this.queue=[],this.workers=[],this.workersResolve=[],this.workerStatus=0,this.workerCreator=null}initWorker(e){if(!this.workers[e]){const t=this.workerCreator();t.addEventListener("message",this.onMessage.bind(this,e)),this.workers[e]=t}}getIdleWorker(){for(let e=0;e<this.limit;e++)if(!(this.workerStatus&1<<e))return e;return-1}onMessage(e,t){const n=this.workersResolve[e];if(n&&n(t),this.queue.length){const{resolve:t,msg:n,transfer:r}=this.queue.shift();this.workersResolve[e]=t,this.workers[e].postMessage(n,r)}else this.workerStatus^=1<<e}setWorkerCreator(e){this.workerCreator=e}setWorkerLimit(e){this.limit=e}postMessage(e,t){return new Promise((n=>{const r=this.getIdleWorker();-1!==r?(this.initWorker(r),this.workerStatus|=1<<r,this.workersResolve[r]=n,this.workers[r].postMessage(e,t)):this.queue.push({resolve:n,msg:e,transfer:t})}))}dispose(){this.workers.forEach((e=>e.terminate())),this.workersResolve.length=0,this.workers.length=0,this.queue.length=0,this.workerStatus=0}};function Lm(e=new Date(-864e13),t=new Date(864e13),n,r){return n&&r?n<=t&&r>e:n?n<=t:!r||r>e}Pm.setWorkerCreator((function(e){return new Worker(new URL("./assets/viewer/geojson.worker-bpUFQjm2.js", require("url").pathToFileURL(__filename)),{name:null==e?void 0:e.name})}));class Um extends r.Object3D{constructor(e,t={}){var n,i,s;super(),this.type="ArrowFeature",this.isArrowFeature=!0,this.timeStart=(null==(n=null==e?void 0:e.properties)?void 0:n.timeStart)?new Date(e.properties.timeStart):null,this.timeEnd=(null==(i=null==e?void 0:e.properties)?void 0:i.timeEnd)?new Date(e.properties.timeEnd):null;const a=(null==t?void 0:t.renderOrder)??0,o=(null==(s=null==e?void 0:e.properties)?void 0:s.color)??15955057;Pm.postMessage({type:"arrow",data:e,color:o}).then((e=>{const{success:t,code:n,error:i,meshVertexBuffer:s}=e.data;if(t){const e=new r.BufferGeometry;e.setAttribute("position",new r.BufferAttribute(s,3));const t=new r.MeshBasicMaterial({color:o,side:r.DoubleSide,depthTest:!1,opacity:.75,transparent:!0,toneMapped:!1});t.onBeforeCompile=e=>{e.vertexShader=km,e.fragmentShader=Im};const n=new r.Mesh(e,t);n.layers.set(a),this.add(n)}}))}}class Fm extends r.Object3D{constructor(e,t={}){var n,i,s;super(),this.type="PerimeterFeature",this.isPerimeterFeature=!0,this.timeStart=(null==(n=null==e?void 0:e.properties)?void 0:n.timeStart)?new Date(e.properties.timeStart):null,this.timeEnd=(null==(i=null==e?void 0:e.properties)?void 0:i.timeEnd)?new Date(e.properties.timeEnd):null;const a=(null==t?void 0:t.renderOrder)??0,o=(null==(s=null==e?void 0:e.properties)?void 0:s.color)??15955057;Pm.postMessage({type:"perimeter",data:e,color:o}).then((e=>{const{success:t,code:n,error:i,lineVertexBuffer:s,lineVertexRGBBuffer:o,meshVertexBuffer:l,meshVertexRGBBuffer:c,meshIndexBuffer:u}=e.data;if(t){const e=new r.BufferGeometry;e.setAttribute("position",new r.BufferAttribute(l,3)),e.setAttribute("color",new r.BufferAttribute(c,3,!0)),e.setIndex(new r.BufferAttribute(u,1));const t=new r.MeshBasicMaterial({opacity:.2,transparent:!0,side:r.DoubleSide,depthTest:!1,vertexColors:!0,toneMapped:!1});t.onBeforeCompile=e=>{e.vertexShader=km,e.fragmentShader=Im};const n=new r.Mesh(e,t);n.layers.set(a);const i=new r.BufferGeometry;i.setAttribute("position",new r.BufferAttribute(s,3)),i.setAttribute("color",new r.BufferAttribute(o,3,!0));const h=new r.LineSegments(i,new r.LineBasicMaterial({vertexColors:!0,toneMapped:!1}));h.layers.set(a),h.add(n),this.add(h)}}))}}class zm extends Em{constructor(e,t={}){var n;super(),this.type="GeojsonLayer",this.isGeojsonLayer=!0;for(let r=0;r<(null==(n=e.features)?void 0:n.length);r++){const n=e.features[r];switch(n.properties.type){case"arrow":const e=new Um(n,t);this.add(e);break;case"perimeter":const r=new Fm(n,t);this.add(r)}}}setTimeFrame(e,t){e&&!e.isDate&&(e=new Date(e)),t&&!t.isDate&&(t=new Date(t));for(let n=0;n<this.children.length;n++){const r=this.children[n],i=r.timeStart,s=r.timeEnd;r.visible=Lm(e,t,i,s)}}dispose(){this.disposeObjectResources(),this.clear()}}const Bm=new Set(["ply","sog"]);function Vm(e,t){return Array.isArray(e)&&e.length===t&&e.every(Number.isFinite)}function Om(e,t){if("string"!=typeof e||0===e.trim().length)throw new Error(`${t} must be a non-empty string.`)}function Nm(e){var t,n,r,i;if(!e||"object"!=typeof e)throw new Error("Gaussian splat layer definition must be an object.");if(Om(e.id,"id"),Om(e.name,"name"),"gaussian-splat"!==e.type)throw new Error('type must be "gaussian-splat".');if(!Array.isArray(e.labels)||!e.labels.every((e=>"string"==typeof e)))throw new Error("labels must be an array of strings.");if(Om(null==(t=e.data)?void 0:t.url,"data.url"),!Bm.has(null==(n=e.data)?void 0:n.format))throw new Error('data.format must be "ply" or "sog".');if(0!==((null==(r=e.options)?void 0:r.renderOrder)??0))throw new Error("Gaussian splat layers only support renderOrder 0.");const s=null==(i=e.options)?void 0:i.transform,a=null==s?void 0:s.anchor;if(!(a&&Number.isFinite(a.longitude)&&Number.isFinite(a.latitude)&&Number.isFinite(a.altitude)))throw new Error("options.transform.anchor must contain finite longitude, latitude, and altitude values.");if(a.longitude<-180||a.longitude>180||a.latitude<-90||a.latitude>90)throw new Error("Anchor longitude must be within [-180, 180] and latitude within [-90, 90].");const o=s.translationENU??[0,0,0],l=s.rotationDegrees??[0,0,0],c=s.scale??1;if(!Vm(o,3))throw new Error("translationENU must be a finite three-number tuple.");if(!Vm(l,3))throw new Error("rotationDegrees must be a finite three-number tuple.");if(!Number.isFinite(c)||c<=0)throw new Error("scale must be a finite positive number.");return{...e,labels:[...e.labels],data:{...e.data},options:{...e.options,renderOrder:0,transform:{anchor:{...a},translationENU:[...o],rotationDegrees:[...l],scale:c}}}}function $m(e){const{anchor:t,translationENU:n,rotationDegrees:i,scale:s}=e,a=t.longitude*Math.PI/180,o=t.latitude*Math.PI/180,l=new r.Vector3(-Math.sin(a),Math.cos(a),0).normalize(),c=new r.Vector3(Math.cos(o)*Math.cos(a),Math.cos(o)*Math.sin(a),Math.sin(o)).normalize(),u=(new r.Vector3).crossVectors(c,l).normalize(),h=(new r.Matrix4).makeBasis(l,u,c);h.setPosition((new r.Vector3).fromArray(function(e,t,n){const r=.0066943799901414,i=t*Math.PI/180,s=e*Math.PI/180,a=6378137/Math.sqrt(1-r*Math.sin(i)**2);return[(a+n)*Math.cos(i)*Math.cos(s),(a+n)*Math.cos(i)*Math.sin(s),(.9933056200098586*a+n)*Math.sin(i)]}(t.longitude,t.latitude,t.altitude)));const d=(new r.Quaternion).setFromEuler(new r.Euler(i[0]*Math.PI/180,i[1]*Math.PI/180,i[2]*Math.PI/180,"XYZ")),p=(new r.Matrix4).compose((new r.Vector3).fromArray(n),d,new r.Vector3(s,s,s));return h.multiply(p)}const Gm={ply:Tr.PLY,sog:Tr.PCSOGSZIP};class qm extends Em{constructor(e,t={}){super(),this.type="GaussianSplatLayer",this.isGaussianSplatLayer=!0,this.contentLayerId=e.id,this.definition=e,this.callbacks=t,this.loadState="idle",this.loadAttempt=0,this.abortController=null,this.splatMesh=null,this.visible=!1,this.layers.set(0),this.setLabels(e.labels),this.transformMatrix=$m(e.options.transform)}setEnabled(e){if("disposed"===this.loadState)return;const t=this.visible;this.visible=e,!e||t||"idle"!==this.loadState&&"error"!==this.loadState||this.load()}async load(){var e,t,n,r,i,s,a,o,l;if("loading"===this.loadState||"ready"===this.loadState||"disposed"===this.loadState)return;const c=++this.loadAttempt;this.loadState="loading",this.abortController=new AbortController;let u=null;try{null==(t=(e=this.callbacks).onStart)||t.call(e,this),null==(r=(n=this.callbacks).ensureRenderer)||r.call(n);const a=await fetch(this.definition.data.url,{signal:this.abortController.signal});if(!a.ok)throw new Error(`Failed to load Gaussian splat: ${a.status} ${a.statusText}`);if(!a.body)throw new Error("Failed to load Gaussian splat: response body is unavailable.");const o=a.headers.get("Content-Length"),l=null===o?void 0:Number.parseInt(o,10);if(u=new lo({stream:a.body,streamLength:Number.isFinite(l)&&l>=0?l:void 0,fileType:Gm[this.definition.data.format],onProgress:e=>{var t,n;"disposed"!==this.loadState&&c===this.loadAttempt&&(null==(n=(t=this.callbacks).onProgress)||n.call(t,this,{loaded:e.loaded,total:e.total,lengthComputable:e.lengthComputable}))}}),u.layers.set(0),u.matrix.copy(this.transformMatrix),u.matrix.decompose(u.position,u.quaternion,u.scale),u.matrixAutoUpdate=!1,u.matrixWorldNeedsUpdate=!0,this.splatMesh=u,this.add(u),await u.initialized,"disposed"===this.loadState||c!==this.loadAttempt)return void this.disposeMesh(u);this.abortController=null,this.loadState="ready",null==(s=(i=this.callbacks).onReady)||s.call(i,this)}catch(h){this.disposeMesh(u);const e=null==(a=this.abortController)?void 0:a.signal.aborted;if(this.abortController=null,"disposed"===this.loadState||c!==this.loadAttempt||e)return;this.loadState="error",null==(l=(o=this.callbacks).onError)||l.call(o,this,function(e){return e instanceof Error?e:new Error(String(e))}(h))}}disposeMesh(e){e&&!e.userData.gaussianSplatDisposed&&(e.userData.gaussianSplatDisposed=!0,e.removeFromParent(),e.dispose(),this.splatMesh===e&&(this.splatMesh=null))}dispose(){var e;"disposed"!==this.loadState&&(this.loadState="disposed",this.loadAttempt++,null==(e=this.abortController)||e.abort(),this.abortController=null,this.disposeMesh(this.splatMesh),this.callbacks={})}}const Hm=document.createElement("canvas");Hm.width=128,Hm.height=128;const jm=Hm.getContext("2d"),Wm=Hm.width/2,Xm=Hm.height/2,Ym=Math.min(Hm.width,Hm.height)/2,Km="0, 0, 0",Qm=jm.createRadialGradient(Wm,Xm,0,Wm,Xm,Ym);Qm.addColorStop(0,`rgba(${Km}, 1)`),Qm.addColorStop(.5,`rgba(${Km}, 0.25)`),Qm.addColorStop(1,`rgba(${Km}, 0)`),jm.fillStyle=Qm,jm.fillRect(0,0,Hm.width,Hm.height);const Zm={APPENDED:"viewer-appended",READY:"viewer-ready",ANIMATED:"viewer-animated",TRANSITIONED:"viewer-transitioned",CONTENT_LAYER_LOAD_START:"content-layer-load-start",CONTENT_LAYER_LOAD_PROGRESS:"content-layer-load-progress",CONTENT_LAYER_READY:"content-layer-ready",CONTENT_LAYER_ERROR:"content-layer-error"};exports.computeElevation=r.computeElevation,exports.Viewer=class extends Do{constructor(e,t={}){super(),this.isViewer=!0,this.type="viewer",this.disposed=!1,this.sparkRenderer=null,mm.CESIUM=t.cesiumToken||void 0,mm.GOOGLEMAPS=t.googleMapsToken||void 0,this.state=new Fo({time:{type:"f",value:0},loaded:!1,added:!1}),this.renderer=new r.WebGLRenderer({antialias:!0,powerPreference:"high-performance"}),this.renderer.setClearColor(16777215,1),this.renderer.toneMapping=r.AgXToneMapping,this.renderer.outputColorSpace=r.SRGBColorSpace,this.renderer.toneMappingExposure=1,this.renderer.supportedFloatType=this.renderer.getContext().getSupportedExtensions().indexOf("OES_texture_float_linear")>=0?r.FloatType:r.HalfFloatType,this.renderer.autoClear=!1,this.css2DRenderer=new An,this.css2DRenderer.domElement.style.setProperty("position","absolute"),this.css2DRenderer.domElement.style.setProperty("left","0"),this.css2DRenderer.domElement.style.setProperty("top","0"),this.css2DRenderer.domElement.style.setProperty("pointer-events","none"),this.clock=new r.Clock,this.camera=new r.PerspectiveCamera(90,1,10,1e8),this.camera.up.set(0,0,1),this.camera.position.fromArray(wm(-105.18896,39.93,9e3)),this.camera.lookAt((new r.Vector3).fromArray(wm(-105.18896,40,0))),this.cameraForward=new r.Vector3,this.cameraRight=new r.Vector3,this.cameraUp=new r.Vector3,this.scene=new r.Scene,this.content=new r.Group,this.scene.add(this.content),this.topLayerIndex=0,this.enabledLayers=[],this.labels=new Map,this.features=new Map,this.globeControls=new qc(this.scene,this.camera,this.renderer.domElement),this.globeControls.enableDamping=!0,this._onGlobeControlsStart=()=>{this.transitionControls.cancel()},this.globeControls.addEventListener("start",this._onGlobeControlsStart),this.transitionControls=new Mm(this.camera),this.globeManager=new sm(this.scene,this.camera,this.renderer,{apiToken:mm.CESIUM,googleMapsToken:mm.GOOGLEMAPS}),this.globeControls.setTilesRenderer(this.globeManager.tiles),this.cameraCoords={},this.pointerCoords={},this.pointerXYZ=new r.Vector3,this.keysDown={},this.keysEnabled=!0,this.movementKeys={BOOST:["ShiftLeft","ShiftRight"],FRONT:["KeyW"],BACK:["KeyS"],LEFT:["KeyA"],RIGHT:["KeyD"],UP:["KeyE"],DOWN:["KeyQ"]},this.movementState={BOOST:!1,FRONT:!1,BACK:!1,LEFT:!1,RIGHT:!1,UP:!1,DOWN:!1},this._onKeyDown=e=>{this.keysDown[e.code]=!0,this.updateMovementState()},this._onKeyUp=e=>{this.keysDown[e.code]=!1,this.updateMovementState()},this._onResize=e=>{this.resizeView(e)},window.addEventListener("keydown",this._onKeyDown),window.addEventListener("keyup",this._onKeyUp),window.addEventListener("resize",this._onResize),this.setAnimate(),e&&this.appendTo(e),this.sky=new Am,this.sky.scale.setScalar(2e7),this.scene.add(this.sky);const n=r.MathUtils.degToRad(80),i=r.MathUtils.degToRad(180),s=(new r.Vector3).setFromSphericalCoords(1,n,i);this.sky.material.uniforms.sunPosition.value=s,this.pointerRaycaster=new r.Raycaster,this._onPointerMove=e=>{const t={};t.x=e.clientX/window.innerWidth*2-1,t.y=-e.clientY/window.innerHeight*2+1,this.pointerRaycaster.setFromCamera(t,this.camera);const n=this.pointerRaycaster.intersectObject(this.globeManager.tiles.group,!0);if(n.length>0){const e=n[0];e?(this.pointerCoords=bm(e.point.x,e.point.y,e.point.z),this.pointerXYZ.copy(e.point)):this.pointerCoords={}}else this.pointerCoords={}},window.addEventListener("pointermove",this._onPointerMove)}updateMovementState(){if(this.keysEnabled)for(const e in this.movementKeys){this.movementState[e]=!1;for(let t=0;t<this.movementKeys[e].length;t++){const n=this.movementKeys[e][t];if(this.keysDown[n]){this.movementState[e]=!0;break}}}}getElevation(e,t){const n=(new r.Vector3).fromArray(wm(e,t,1e4)),i=(new r.Vector3).sub(n).normalize(),s=new r.Raycaster;s.ray.set(n,i);const a=this.globeControls.raycast(s);return bm(a.point.x,a.point.y,a.point.z)}updateCoordsElevation(e){for(let t=0;t<e.length;t++){const[n,r]=e[t];e[t][2]=this.getElevation(n,r).alt}return e}setBackgroundColor(e){this.renderer.setClearColor(e,0)}appendTo(e){this.container=e,this.container.appendChild(this.renderer.domElement),this.container.appendChild(this.css2DRenderer.domElement),this.resizeView(),this.dispatchEvent({type:Zm.APPENDED})}updateCameraDirections(){const e=new r.Matrix4;e.extractRotation(this.camera.matrixWorld),this.cameraForward.set(0,0,-1).applyMatrix4(e),this.cameraRight.set(1,0,0).applyMatrix4(e),this.cameraUp.set(0,1,0).applyMatrix4(e)}setAnimate(e=!0){e?this.renderer.setAnimationLoop(((e,t)=>{this.animate(e)})):this.renderer.setAnimationLoop(null)}resizeView(e){if(this.container){const e=this.container.offsetWidth,t=this.container.offsetHeight;this.camera.aspect=e/t,this.camera.updateProjectionMatrix(),this.renderer.setSize(e,t),this.css2DRenderer.setSize(e,t),this.renderer.render(this.scene,this.camera),this.css2DRenderer.render(this.scene,this.camera)}}async loadEnv(e){const t=await new gm(e,{floatType:this.renderer.supportedFloatType});t.mapping=r.EquirectangularReflectionMapping,this.scene.environment=t,this.scene.environmentRotation.set(Math.PI/2,0,0)}clearContentLayers(){for(var e;this.content.children.length>0;){const t=this.content.children[0];null==(e=t.dispose)||e.call(t),this.content.remove(t)}this.disposeSparkRenderer()}ensureSparkRenderer(){return this.sparkRenderer||(this.sparkRenderer=new Ja({renderer:this.renderer}),this.sparkRenderer.layers.set(0),this.scene.add(this.sparkRenderer)),this.sparkRenderer}disposeSparkRenderer(){var e,t;this.sparkRenderer&&(this.sparkRenderer.removeFromParent(),null==(t=(e=this.sparkRenderer).clearSplats)||t.call(e),this.sparkRenderer.dispose(),this.sparkRenderer=null)}defineContentLayers(e=[]){var t,n,r;this.topLayerIndex=0,this.clearContentLayers();for(let s=0;s<e.length;s++){const a=e[s];try{const e="gaussian-splat"===(null==a?void 0:a.type)?Nm(a):a;switch(this.topLayerIndex=Math.max(this.topLayerIndex,(null==(t=null==e?void 0:e.options)?void 0:t.renderOrder)??0),null==e?void 0:e.type){case"3d-tiles":{const t=new Rm(e.data.url,{camera:this.camera,renderer:this.renderer,...e.options});t.setLabels(e.labels),null==(n=t.setTimeFrame)||n.call(t,this.timeFrameStart,this.timeFrameEnd),t.setEnabled(!1),this.content.add(t);break}case"mesh":{const t=new Dm(e.data.url,{...e.options});t.setLabels(e.labels),t.setEnabled(!1),this.content.add(t);break}case"geojson":{const t=new zm(e.data,e.options);t.setLabels(e.labels),null==(r=t.setTimeFrame)||r.call(t,this.timeFrameStart,this.timeFrameEnd),t.setEnabled(!1),this.content.add(t);break}case"gaussian-splat":{const t=new qm(e,{ensureRenderer:()=>this.ensureSparkRenderer(),onStart:e=>this.dispatchEvent({type:Zm.CONTENT_LAYER_LOAD_START,layerId:e.contentLayerId}),onProgress:(e,t)=>this.dispatchEvent({type:Zm.CONTENT_LAYER_LOAD_PROGRESS,layerId:e.contentLayerId,progress:t}),onReady:e=>this.dispatchEvent({type:Zm.CONTENT_LAYER_READY,layerId:e.contentLayerId}),onError:(e,t)=>this.dispatchEvent({type:Zm.CONTENT_LAYER_ERROR,layerId:e.contentLayerId,error:t})});this.content.add(t);break}default:throw new Error(`Unsupported content layer type: ${String(null==e?void 0:e.type)}`)}}catch(i){this.dispatchEvent({type:Zm.CONTENT_LAYER_ERROR,layerId:"string"==typeof(null==a?void 0:a.id)&&a.id.length>0?a.id:null,error:i instanceof Error?i:new Error(String(i))})}}this.globeControls.pivotMesh.layers.set(this.topLayerIndex),this.enableContentLayers(this.enabledLayers)}enableContentLayers(e=[]){this.enabledLayers=e;for(let t=0;t<this.content.children.length;t++){const n=this.content.children[t];let r=!1;for(let t=0;t<e.length;t++){const i=e[t];if(n.labels.has(i)){r=!0;break}}n.setEnabled(r)}}setTimeFrame(e,t){var n;this.timeFrameStart=e?new Date(e):null,this.timeFrameEnd=t?new Date(t):null;for(let r=0;r<this.content.children.length;r++){const e=this.content.children[r];null==(n=e.setTimeFrame)||n.call(e,this.timeFrameStart,this.timeFrameEnd)}}updateLabel(e,t={}){const n=(null==t?void 0:t.element)??document.createElement("div"),i=(null==t?void 0:t.lat)??0,s=(null==t?void 0:t.lon)??0,a=(null==t?void 0:t.alt)??0,o=(null==t?void 0:t.visible)??!0,l=(null==t?void 0:t.hovered)??!1,c=(null==t?void 0:t.selected)??!1;let u=null;if(this.labels.has(e))u=this.labels.get(e);else{u=new bn(n),u.position.fromArray(wm(s,i,a));const t=new r.Mesh(new r.PlaneGeometry(1e3,1e3),new r.MeshBasicMaterial({map:new r.CanvasTexture(Hm),opacity:1,transparent:!0,side:r.DoubleSide}));t.layers.set(this.topLayerIndex),u.add(t),u.lookAt(0,0,0),this.scene.add(u),this.labels.set(e,u)}return u.visible=o,l?u.element.classList.add("hovered"):u.element.classList.remove("hovered"),c?u.element.classList.add("selected"):u.element.classList.remove("selected"),u.element}animate(e){this.stats&&this.stats.begin(),this.transitionControls.update(e),this.state.get("time").value=e;const t=this.clock.getDelta();this.globeControls.update(),this.camera.updateMatrixWorld(),this.updateCameraDirections(),this.sky.setSurfaceUp(Tm(this.cameraCoords.lon,this.cameraCoords.lat));const n=this.movementState.BOOST?5:1;this.movementState.FRONT&&this.camera.position.addScaledVector(this.cameraForward,100*t*n),this.movementState.BACK&&this.camera.position.addScaledVector(this.cameraForward,-100*t*n),this.movementState.LEFT&&this.camera.position.addScaledVector(this.cameraRight,-100*t*n),this.movementState.RIGHT&&this.camera.position.addScaledVector(this.cameraRight,100*t*n),this.movementState.UP&&this.camera.position.addScaledVector(this.cameraUp,100*t*n),this.movementState.DOWN&&this.camera.position.addScaledVector(this.cameraUp,-100*t*n),this.globeManager.update();for(let r=0;r<this.content.children.length;r++){this.content.children[r].update()}for(const[i,s]of this.labels)if(s.element){s.element.classList.remove("far"),s.element.classList.remove("mid"),s.element.classList.remove("close");const e=(new r.Vector3).subVectors(s.position,this.camera.position).dot(this.cameraForward);s.scale.setScalar(e/1e4),s.children[0].material.opacity=Math.min(Math.max(1-e/2e3,.1),1),e>3200?s.element.classList.add("far"):e>1e3?s.element.classList.add("mid"):s.element.classList.add("close")}for(let r=0;r<this.topLayerIndex+1;r++)this.camera.layers.set(r),0==r?(this.renderer.clear(),this.render()):(this.renderer.clearDepth(),this.renderer.render(this.scene,this.camera));this.cameraCoords=function(e,t,n,i){const{lon:s,lat:a,alt:o}=bm(e,t,n),l=s*(Math.PI/180),c=a*(Math.PI/180),u=new r.Vector3(Math.cos(c)*Math.cos(l),Math.cos(c)*Math.sin(l),Math.sin(c)),h=new r.Vector3(0,0,1),d=h.clone().sub(u.clone().multiplyScalar(h.dot(u))).normalize(),p=(new r.Vector3).crossVectors(d,u).normalize(),m=(new r.Matrix4).makeBasis(p,d,u),f=(new r.Quaternion).setFromRotationMatrix(m).clone().invert().multiply(i),g=(new r.Euler).setFromQuaternion(f,"ZYX");return{lon:s,lat:a,alt:o,pitch:r.MathUtils.radToDeg(g.x)-90,yaw:r.MathUtils.radToDeg(g.z),roll:r.MathUtils.radToDeg(g.y)}}(this.camera.position.x,this.camera.position.y,this.camera.position.z,this.camera.quaternion),this.dispatchEvent({type:Zm.ANIMATED,time:e,deltaTime:t}),this.stats&&this.stats.end()}render(){this.renderer.render(this.scene,this.camera),this.css2DRenderer.render(this.scene,this.camera),!0===this.state.get("added")&&!1===this.state.get("ready")&&(this.state.update({ready:!0}),window.setTimeout((()=>{this.dispatchEvent({type:Zm.READY})}),0))}getCameraPivot(){let e=null;const t=new r.Raycaster;t.setFromCamera({x:0,y:0},this.camera);const n=t.intersectObject(this.globeManager.tiles.group,!0);if(n.length>0){const t=n[0];t&&(e=t.point.clone())}return e||(e=(new r.Vector3).subVectors(this.camera.position,this.cameraForward.clone().multiplyScalar(2e3))),e}async alignCamera(e,t,n,i=this.cameraCoords.pitch,s=this.cameraCoords.yaw,a=this.cameraCoords.roll,o=fm){const l=(new r.Vector3).fromArray(wm(e,t,n)),c=Sm(e,t,i,s,a);return this.transitionControls.animateTo(l,c,o).then((()=>{this.dispatchEvent({type:Zm.TRANSITIONED,lon:e,lat:t,alt:n,pitch:i,yaw:s,roll:a})}))}async focusCamera(e,t,n,i=2e3,s=this.cameraCoords.pitch,a=fm){const o=(new r.Vector3).fromArray(wm(e,t,n)),l=Sm(e,t,s,0,0),c=new r.Vector3(0,0,1).applyQuaternion(l);return o.addScaledVector(c,i),this.transitionControls.animateTo(o,l,a).then((()=>{this.dispatchEvent({type:Zm.TRANSITIONED,lon:e,lat:t,alt:n})}))}async angleCamera(e=this.cameraCoords.pitch,t=this.cameraCoords.yaw,n=fm){const i=this.getCameraPivot(),{lon:s,lat:a,alt:o}=bm(i.x,i.y,i.z),l=this.camera.position.distanceTo(i),c=(new r.Vector3).fromArray(wm(s,a,o)),u=Sm(s,a,e,t,0),h=new r.Vector3(0,0,1).applyQuaternion(u);return c.addScaledVector(h,l),this.transitionControls.animateTo(c,u,n).then((()=>{this.dispatchEvent({type:Zm.TRANSITIONED,lon:s,lat:a,alt:o})}))}setViewMode(e="3d"){"3d"==e?(this.globeControls.rotationSpeed=1,this.angleCamera(-60,void 0,500)):(this.globeControls.rotationSpeed=0,this.angleCamera(-90,0,500))}exportScene(){return e=this.scene,void(new c).parse(e,(e=>{const t=new Blob([e],{type:"application/octet-stream"}),n=URL.createObjectURL(t),r=document.createElement("a");r.href=n,r.download="scene.glb",document.body.appendChild(r),r.click(),document.body.removeChild(r)}),(e=>{}),{binary:!0});var e}saveScreenshot(e="screenshot"){for(let r=0;r<this.topLayerIndex+1;r++)this.camera.layers.set(r),0==r?(this.renderer.clear(),this.render()):(this.renderer.clearDepth(),this.renderer.render(this.scene,this.camera));const t=this.renderer.domElement.toDataURL(),n=document.createElement("a");n.setAttribute("href",t),n.setAttribute("target","_blank"),n.setAttribute("download",`${e}.png`),n.click()}dispose(){var e,t,n,r,i,s,a,o,l,c,u,h,d,p,m;if(!this.disposed){this.disposed=!0,this.setAnimate(!1),this.transitionControls.cancel(),this.clearContentLayers(),window.removeEventListener("keydown",this._onKeyDown),window.removeEventListener("keyup",this._onKeyUp),window.removeEventListener("resize",this._onResize),window.removeEventListener("pointermove",this._onPointerMove),this.globeControls.removeEventListener("start",this._onGlobeControlsStart),this.globeControls.dispose(),this.globeManager.dispose();for(const e of this.labels.values())e.traverse((e=>{var t,n,r,i,s;if(null==(n=null==(t=e.geometry)?void 0:t.dispose)||n.call(t),e.material){const t=Array.isArray(e.material)?e.material:[e.material];for(const e of t)null==(i=null==(r=e.map)?void 0:r.dispose)||i.call(r),null==(s=e.dispose)||s.call(e)}})),e.removeFromParent();this.labels.clear(),this.features.clear(),null==(t=null==(e=this.scene.environment)?void 0:e.dispose)||t.call(e),this.scene.environment=null,null==(i=null==(r=null==(n=this.sky)?void 0:n.geometry)?void 0:r.dispose)||i.call(r),null==(o=null==(a=null==(s=this.sky)?void 0:s.material)?void 0:a.dispose)||o.call(a),null==(l=this.sky)||l.removeFromParent(),null==(u=null==(c=this.stats)?void 0:c.dom)||u.remove(),this.css2DRenderer.domElement.remove(),this.renderer.domElement.remove(),null==(d=null==(h=this.renderer.renderLists)?void 0:h.dispose)||d.call(h),this.renderer.dispose(),null==(m=(p=this.renderer).forceContextLoss)||m.call(p),this.container=null,this.listeners={}}}},exports.ViewerEvents=Zm;
|