s3m-three 0.4.28 → 0.4.29

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.
@@ -940,7 +940,7 @@ var S3M=(function(e,t){Object.defineProperties(e,{__esModule:{value:!0},[Symbol.
940
940
  float o = uObjectId + 1.0;
941
941
  gl_FragColor = vec4(mod(o, 256.0) / 255.0, floor(o / 256.0) / 255.0, 0.0, 0.0);
942
942
  }
943
- `,side:t.DoubleSide,depthTest:!0,depthWrite:!0})}function ho(e){let t=e.getAttribute(`iCenter`);if(!t)return null;let n=t.array,r=t.count;if(!r)return null;let i=1/0,a=1/0,o=1/0,s=-1/0,c=-1/0,l=-1/0;for(let e=0;e<r;e++){let t=n[e*3],r=n[e*3+1],u=n[e*3+2];t<i&&(i=t),t>s&&(s=t),r<a&&(a=r),r>c&&(c=r),u<o&&(o=u),u>l&&(l=u)}return{minX:i,minY:a,minZ:o,maxX:s,maxY:c,maxZ:l,count:r}}var go,_o,vo,yo,bo=c((()=>{yn(),go=new t.Vector2(1e3,1e3),_o=new t.Sphere,vo=new t.Matrix4,yo=new t.Ray})),xo=l({LINE_PRIMITIVE:()=>13,POINT_PRIMITIVE:()=>1,buildTileObjects:()=>Po,setSplatViewport:()=>wo});function So(e){return e===1}function Co(){return Fo??(Fo=uo()),Fo}function wo(e,t){Fo&&Fo.uniforms.uViewport.value.set(e,t)}function To(e,n){let r=n.vertexAttributes.find(e=>e.semantic===`gsScale`),i=n.vertexAttributes.find(e=>e.semantic===`gsRotation`),a=e.attributes.position;if(!r||!i||!a)return null;let o=Math.min(n.verticesCount,Math.floor(a.array.length/a.components));if(o<=0)return null;let s=ro(r.data,r.stride,r.offsetInBytes,o),c=io(i.data,i.stride,i.offsetInBytes,o),l=Eo(s,o),u=fo();u.instanceCount=o,u.setAttribute(`iCenter`,new t.InstancedBufferAttribute(a.array,3)),u.setAttribute(`iScale`,new t.InstancedBufferAttribute(s,3)),u.setAttribute(`iQuat`,new t.InstancedBufferAttribute(c,4));let d=new Float32Array(o*4);d.fill(1);let f=n.vertexAttributes.find(e=>e.semantic===`color`);if(f&&f.dtype===`u8`){let e=f.components??4,t=Math.min(o,Math.floor(f.data.length/f.stride));for(let n=0;n<t;n++){let t=n*f.stride+f.offsetInBytes;d[n*4]=f.data[t]/255,d[n*4+1]=f.data[t+1]/255,d[n*4+2]=f.data[t+2]/255,e>=4&&(d[n*4+3]=f.data[t+3]/255)}}else if(e.attributes.aColor){let t=e.attributes.aColor,n=t.components??4;for(let e=0;e<o;e++)for(let r=0;r<Math.min(n,4);r++)d[e*4+r]=t.array[e*n+r]}u.setAttribute(`iColor`,new t.InstancedBufferAttribute(d,4));let p=a.array,m=1/0,h=1/0,g=1/0,_=-1/0,v=-1/0,y=-1/0,b=0;for(let e=0;e<o;e++){let t=p[e*3],n=p[e*3+1],r=p[e*3+2];t<m&&(m=t),t>_&&(_=t),n<h&&(h=n),n>v&&(v=n),r<g&&(g=r),r>y&&(y=r);let i=s[e*3],a=s[e*3+1],o=s[e*3+2];i>b&&(b=i),a>b&&(b=a),o>b&&(b=o)}let x=new t.Box3;o>0&&(x.min.set(m,h,g),x.max.set(_,v,y));let S=new t.Sphere(new t.Vector3,0);return x.isEmpty()||x.getBoundingSphere(S),S.radius+=3*b,u.boundingSphere=S,{geo:u,sigma:l}}function Eo(e,t){let n=Math.max(1,Math.floor(t/512)),r=[];for(let i=0;i<t;i+=n){let t=Math.max(e[i*3],e[i*3+1],e[i*3+2]);Number.isFinite(t)&&t>0&&r.push(t)}return r.length?(r.sort((e,t)=>e-t),r[r.length>>1]):0}function Do(){return Io||(Io=new t.PointsMaterial({size:2,sizeAttenuation:!1,vertexColors:!0})),Io}function Oo(e){if(!e)return[];if(Array.isArray(e))return e;let t=e,n=t.materials??t.material;return Array.isArray(n)?n:[]}function ko(e){return e?.material??e}function Ao(e){return e?.name??e?.id}function jo(e){return(e?.textureStates??e?.textureunitstates??[]).map(e=>e?.textureunitstate??e).filter(e=>!!e)}function Mo(e){return e.length===16&&e[0]===1&&e[1]===0&&e[2]===0&&e[3]===0&&e[4]===0&&e[5]===1&&e[6]===0&&e[7]===0&&e[8]===0&&e[9]===0&&e[10]===1&&e[11]===0&&e[12]===0&&e[13]===0&&e[14]===0&&e[15]===1}function No(e){let n=String(e?.cullMode??``).toUpperCase();return n===`CULL_BACK`||n===`BACKWARD`?t.FrontSide:n===`CULL_FRONT`?t.BackSide:t.DoubleSide}async function Po(e,n={}){let r=n.uniforms??aa(),i=n.textureCache??new Map,a=new t.Group,o=[],s=[],c={meshes:0,vertices:0,triangles:0,textures:0,instanced:0,edgeLines:0,skipped:[]},l=new t.LineBasicMaterial({color:new t.Color(n.edgeColor??`#1f2937`),transparent:!0,opacity:.75,depthWrite:!1});a.userData.hasNativeEdges=!1;let u=t=>{let n=e.textures?.[t];return n?.packKey?`${t}#${n.packKey}`:t};for(let[t,r]of Object.entries(e.textures??{})){let e=u(t),a=i.get(e);if(a){let t=a.image;if((t?.width??0)*(t?.height??0)>=(r.width??0)*(r.height??0))continue;i.delete(e)}let{texture:o,decoded:l}=await Ri(r,n.textureOptions);o?(i.set(e,o),s.push(e),c.textures++):c.skipped.push(`texture ${t} → ${l}`)}let d=Oo(e.materials),f=e=>d.findIndex(t=>Ao(ko(t))===e),p=(e,a=!1,o=!1,s=1,c=!1)=>{let l=ko(d.find(t=>Ao(ko(t))===e)),f=jo(l),p=f[0],m=p?i.get(u(Ao(p)??p.id??``))??null:null,h=f[1],g=globalThis.__S3M_NO_BAKE===!0,_=a&&h&&!g?i.get(u(Ao(h)??h.id??``))??null:null,v=p?.texmodmatrix??p?.matrix;if(m&&Array.isArray(v)&&v.length===16&&!Mo(v)&&(m=m.clone(),m.matrixAutoUpdate=!1,m.matrix.set(v[0],v[4],v[12],v[1],v[5],v[13],0,0,1)),m&&p?.addressmode){let e=p.addressmode.u,n=p.addressmode.v;(e!==void 0||n!==void 0)&&(m.matrixAutoUpdate&&(m=m.clone()),e!==void 0&&(m.wrapS=e===0?t.RepeatWrapping:t.ClampToEdgeWrapping),n!==void 0&&(m.wrapT=n===0?t.RepeatWrapping:t.ClampToEdgeWrapping))}let y=l?.diffuse??{r:1,g:1,b:1,a:1},b=[p,h].some(e=>/\.water$/i.test(String(Ao(e)??e?.id??``))),x=Na({alphaMode:l?.alphaMode,diffuseAlpha:y.a??1,transparentSorting:l?.transparentsorting===!0,vertexAlphaMin:s,isWaterWithoutMap:b&&!m}),S=typeof l?.shininess==`number`&&l.shininess>0?Math.max(.15,1-l.shininess/128):.95,C=m?.userData?.s3mHasAlpha?Math.max(l?.alphaCutoff??0,.01):0,w;if(n.tileAnchor){let e=sn(n.tileAnchor.lon,n.tileAnchor.lat,n.tileAnchor.height),t=e.meterInMercatorEast??e.meterInMercator,r=e.meterInMercatorNorth??e.meterInMercator,i=e.meterInMercatorUp??t;w=[1/t,1/r,1/i]}let T=oa({uniforms:r,map:m,color:b&&!m?Lo.clone():new t.Color(y.r??1,y.g??1,y.b??1),side:No(l),transparent:x,opacity:b&&!m?.86:y.a??1,roughness:b&&!m?.12:S,alphaTest:C,atlas:a&&!!m,texCoordZ:o&&!!m,secMap:_,materialQuality:n.materialQuality,colorPipeline:n.colorPipeline,bakeMercator:c||n.bakeMercator,tilePivot:n.tileCenter?new t.Vector3(n.tileCenter.x,n.tileCenter.y,n.tileCenter.z):void 0,invTileScale:w?new t.Vector3(...w):void 0});return n.polygonOffset&&(T.polygonOffset=!0,T.polygonOffsetFactor=n.polygonOffset.factor,T.polygonOffsetUnits=n.polygonOffset.units),T};if(n.assembled&&n.bakeMercator&&n.tileAnchor){for(let e of n.assembled.primitives)if(!e.attributes.aMercatorOffset&&e.attributes.position){let t=mi(e.attributes.position.array,e.vertexCount,n.tileAnchor,n.tileCenter??{x:0,y:0,z:0});e.attributes.aMercatorOffset={array:t,components:3,normalized:!1}}}let m=n.assembled??$a(e,{batching:n.batching!==!1,dedupeCoincident:n.dedupeCoincident,bakeMercator:n.bakeMercator,tileAnchor:n.tileAnchor,tileCenter:n.tileCenter});c.vertices=m.stats.vertices,c.edgeLines=m.stats.edgeLines,c.instanced=m.stats.instanced,m.stats.originalMeshes!=null&&(c.originalMeshes=m.stats.originalMeshes),c.skipped.push(...m.stats.skipped);let h=new t.Matrix4,g=e=>{let n=new t.BufferGeometry;for(let[r,i]of Object.entries(e.attributes))i&&n.setAttribute(r,new t.BufferAttribute(i.array,i.components,i.normalized));return e.index?n.setIndex(new t.BufferAttribute(e.index,1)):n.setDrawRange(0,e.vertexCount),n.boundingBox=new t.Box3(new t.Vector3(...e.bounds.boxMin),new t.Vector3(...e.bounds.boxMax)),n.boundingSphere=new t.Sphere(new t.Vector3(...e.bounds.sphereCenter),e.bounds.sphereRadius),n};for(let r of m.primitives){let i=g(r),s=e.geoPackage[r.geoNames[0]]??null,u=s?.vertexPackage,m=!!r.attributes.aMercatorOffset,_=p(r.passNames[0],!!r.attributes.aAtlasRect,!!r.attributes.aTexCoordZ,Pa(r.attributes.aColor),m),v=r.matrix&&r.matrix.length===16?new t.Matrix4().fromArray(r.matrix):null;if(r.primitiveType===13){let e=new t.LineSegments(i,l);e.visible=n.edges===!0,e.renderOrder=Ro,e.raycast=()=>{},e.userData.isEdgeLines=!0,e.userData.skeletonName=r.skeletonName,v&&!v.equals(h)&&v.decompose(e.position,e.quaternion,e.scale),a.add(e),o.push(e),a.userData.hasNativeEdges=!0;continue}if(r.primitiveType===2||r.primitiveType===3){let n=ko(d.find(e=>Ao(ko(e))===r.passNames[0]))?.diffuse,l=n?new t.Color(n.r??1,n.g??1,n.b??1):new t.Color(16777215),u=!!i.getAttribute(`aColor`)||!!i.getAttribute(`color`);u&&!i.getAttribute(`color`)&&i.setAttribute(`color`,i.getAttribute(`aColor`));let f=new t.LineBasicMaterial({color:l,vertexColors:u,transparent:n?.a!==void 0&&n.a<1,opacity:n?.a??1}),p=r.primitiveType===3?new t.Line(i,f):new t.LineSegments(i,f);p.visible=!0,p.userData.skeletonName=r.skeletonName,p.userData.geoRef=s,p.userData.tileRef=e,p.userData.primitiveType=r.primitiveType,v&&!v.equals(h)&&v.decompose(p.position,p.quaternion,p.scale),a.add(p),o.push(p),c.meshes++;continue}if(So(r.primitiveType)){let n=u?To(r,u):null;if(n){let i=new t.InstancedMesh(n.geo,Co(),n.geo.instanceCount);i.raycast=po,i.frustumCulled=!1,i.renderOrder=zo,n.sigma>0&&(c.splatSigma=Math.max(c.splatSigma??0,n.sigma)),c.splatCount=(c.splatCount??0)+n.geo.instanceCount,i.userData.isPointCloud=!0,i.userData.isGaussianSplat=!0,i.userData.skeletonName=r.skeletonName,i.userData.geoRef=s,i.userData.tileRef=e,i.userData.primitiveType=r.primitiveType,v&&!v.equals(h)&&v.decompose(i.position,i.quaternion,i.scale),a.add(i),o.push(i),c.meshes++;continue}i.getAttribute(`color`)||i.setAttribute(`color`,i.getAttribute(`aColor`));let l=new t.Points(i,Do());l.userData.isPointCloud=!0,l.userData.skeletonName=r.skeletonName,l.userData.geoRef=s,l.userData.tileRef=e,l.userData.primitiveType=r.primitiveType,v&&!v.equals(h)&&v.decompose(l.position,l.quaternion,l.scale),a.add(l),o.push(l),c.meshes++;continue}let y;if(u&&u.instanceIndex!==-1&&(u.instanceMode===16||u.instanceMode===17)&&u.instanceBuffer&&(u.instanceCount??0)>0&&u){if(!i.getAttribute(`aInstanceBatchId`)){let e=u.instanceBatchIds,n=e&&e.length===u.instanceCount?e.slice():new Float32Array(u.instanceCount).fill(-1);i.setAttribute(`aInstanceBatchId`,new t.InstancedBufferAttribute(n,1));let r=new Float32Array(u.instanceCount);for(let e=0;e<r.length;e++)r[e]=e;i.setAttribute(`aInstanceIndex`,new t.InstancedBufferAttribute(r,1))}let e=new t.InstancedMesh(i,_,u.instanceCount);e.instanceMatrix.setUsage(t.StaticDrawUsage);let n=new t.Matrix4,r=new t.Color,a=u.instanceMode,o=new Float32Array(u.instanceBuffer.buffer,u.instanceBuffer.byteOffset,u.instanceCount*a);for(let t=0;t<u.instanceCount;t++){let i=t*a;if(n.set(o[i+0],o[i+1],o[i+2],o[i+3],o[i+4],o[i+5],o[i+6],o[i+7],o[i+8],o[i+9],o[i+10],o[i+11],0,0,0,1),e.setMatrixAt(t,n),a>=16){let n=o[i+12],a=o[i+13],s=o[i+14];Number.isFinite(n)&&Number.isFinite(a)&&Number.isFinite(s)&&(r.setRGB(n,a,s),e.setColorAt(t,r))}}e.instanceMatrix.needsUpdate=!0,e.instanceColor&&(e.instanceColor.needsUpdate=!0),e.frustumCulled=!1,y=e}else y=new t.Mesh(i,_);v&&!v.equals(h)&&v.decompose(y.position,y.quaternion,y.scale),y.userData.skeletonName=r.skeletonName,y.userData.geoRef=s,y.userData.tileRef=e,y.userData.primitiveType=r.primitiveType;let b=f(r.passNames[0]);if(b>=0&&!_.transparent&&(y.renderOrder=Math.min(b,Bo)),r.batchedFrom!=null&&r.batchedFrom>1){y.userData.isBatched=!0,y.userData.batchedCount=r.batchedFrom;let t=new Map;for(let n of r.geoNames){let r=e.geoPackage[n];if(r?.pickInfo)for(let e of Object.values(r.pickInfo))typeof e.batchId==`number`&&e.batchId>=0&&t.set(e.batchId,r)}t.size>0&&(y.userData.geoByBatchId=t)}a.add(y),o.push(y),c.meshes++,r.primitiveType===4&&(c.triangles+=r.indexCount/3)}a.children.length||c.skipped.push(`tile 无可用几何`);let _=0;for(let e of o){let t=e,n=t.geometry;if(n){if(n.attributes)for(let e of Object.values(n.attributes))e&&e.array&&(_+=e.array.byteLength);n.index&&n.index.array&&(_+=n.index.array.byteLength)}if(t.isInstancedMesh){let e=t;e.instanceMatrix&&e.instanceMatrix.array&&(_+=e.instanceMatrix.array.byteLength),e.instanceColor&&e.instanceColor.array&&(_+=e.instanceColor.array.byteLength)}}return c.memory=_,a.userData.textureKeys=s,{group:a,stats:c,objects:o,textureKeys:s}}var Fo,Io,Lo,Ro,zo,Bo,Vo=c((()=>{Gi(),ja(),Fa(),no(),gi(),gn(),lo(),bo(),yn(),Fo=null,Io=null,Lo=new t.Color(1920611),Ro=1e3,zo=1001,Bo=999}));gi(),b();function Ho(e){return e.slice(0,e.lastIndexOf(`/`)+1)}function Uo(e){if(!e)return e;try{let t=typeof document<`u`?document.baseURI:void 0;return t?new URL(e,t).href:new URL(e).href}catch{return e}}function Wo(e,t){if(!t)return null;try{return Go(new URL(t,e).href)}catch{return Go(`${Ho(e)}${t}`)}}function Go(e){if(!/[+ ]/.test(e))return e;let t=e.indexOf(`#`),n=t<0?``:e.slice(t),r=t<0?e:e.slice(0,t),i=r.indexOf(`?`),a=i<0?r:r.slice(0,i),o=i<0?``:r.slice(i);return`${a.replace(/\+/g,`%2B`).replace(/ /g,`%20`)}${o}${n}`}var Ko=110540,qo=111320;function Jo(e){if(!e||typeof e!=`object`)return null;let t=e;if(![t.left,t.bottom,t.right,t.top].every(e=>typeof e==`number`&&Number.isFinite(e)))return null;let{left:n,bottom:r,right:i,top:a}=t;return Math.abs(n)>180||Math.abs(i)>180||Math.abs(a)>90||Math.abs(r)>90||i===n&&a===r?null:{left:n,bottom:r,right:i,top:a}}function Yo(e,t){if(!t)return null;let n=t.replace(/\.(osgb|s3mb|s3m)$/i,`.s3m`),r=e.split(`/`),i=r.pop()??``,a=r.pop()??``,o=r.lastIndexOf(`datas`);return!i||!a||o<1?Wo(Ho(e),n):Go(`${r[r.length-1]===`path`&&r[r.length-2]===`data`?`${r.join(`/`)}/${a}`:`${r.join(`/`)}/data/path/${a}`}/${n}`)}function Xo(e){let t=e.trim();if(t.startsWith(`<`)){let e=e=>{let n=RegExp(`<(?:[a-zA-Z0-9_-]+:)?${e}[^>]*>([^<]+)<\\/`,`i`).exec(t);return n?n[1].trim():null},n=t=>parseFloat(e(t)??``),r=n(`X`)||0,i=n(`Y`)||0,a=n(`Z`)||0,o=n(`Left`),s=n(`Right`),c=n(`Top`),l=n(`Bottom`);if(![o,s,c,l].every(Number.isFinite)){let e=n(`MinX`),t=n(`MaxX`),a=n(`MinY`),u=n(`MaxY`);if([e,t,a,u].every(Number.isFinite)&&r&&i){let n=qo*Math.cos(i*Math.PI/180);n>1e-6&&(o=r+e/n,s=r+t/n,l=i+a/Ko,c=i+u/Ko)}}let u=t.matchAll(/<(?:[a-zA-Z0-9_-]+:)?FileName[^>]*>([^<]+)<\//gi),d=[];for(let e of u)d.push({url:e[1].trim()});let f=n(`MinHeight`),p=n(`MaxHeight`);return{fileType:e(`FileType`)??void 0,fileExtentName:e(`FileExtentName`)??void 0,cacheType:e(`Type`)??void 0,position:{x:r,y:i,z:a,units:`Degree`},geoBounds:{left:o,right:s,top:c,bottom:l},heightRange:Number.isFinite(f)||Number.isFinite(p)?{min:f,max:p}:void 0,rootTiles:d,tiles:d}}return JSON.parse(t)}function Zo(e){return!e||typeof e!=`object`?`model`:String(e.fileExtentName??``).trim().toLowerCase()===`terrainz`?`terrain`:String(e.cacheType??``).trim().toLowerCase()===`image`?`imagery`:`model`}function Qo(e){let t=[];return e.fileExtentName&&t.push(`FileExtentName=${e.fileExtentName}`),e.cacheType&&t.push(`Type=${e.cacheType}`),e.fileType&&t.push(`fileType=${e.fileType}`),e.dataType&&t.push(`dataType=${e.dataType}`),t.length?t.join(`, `):`无类型标记`}function $o(e){let t=/\/datas\/([^/?#]+)/i.exec(e);if(!t)return e;try{return decodeURIComponent(t[1])}catch{return t[1]}}function es(e){if(!e)return 0;if(Array.isArray(e.mipmaps)&&e.mipmaps.length>0){let t=0;for(let n of e.mipmaps)n?.data?.byteLength&&(t+=n.data.byteLength);if(t>0)return t}let t=e.image;if(!t)return 0;if(t.data&&typeof t.data.byteLength==`number`)return t.data.byteLength;let n=t.width??0,r=t.height??0;if(n>0&&r>0){let t=e.generateMipmaps?1.3333333333333333:1;return Math.round(n*r*4*t)}return 0}function ts(e){let t=0;return e?(e.traverse?.(e=>{let n=e.geometry;if(n){if(n.attributes)for(let e of Object.values(n.attributes))e?.array?.byteLength&&(t+=e.array.byteLength);n.index?.array?.byteLength&&(t+=n.index.array.byteLength)}e.isInstancedMesh&&(e.instanceMatrix?.array?.byteLength&&(t+=e.instanceMatrix.array.byteLength),e.instanceColor?.array?.byteLength&&(t+=e.instanceColor.array.byteLength))}),t):0}var ns=class{get heightRange(){let e=this.config?.heightRange;return e&&typeof e.min==`number`&&typeof e.max==`number`?{min:e.min,max:e.max}:null}shouldBakeMercator(e){return this._bakeMercator===void 0?(e??this.rootRadius??0)>hi:this._bakeMercator}constructor(e){y(this,`configUrl`,void 0),y(this,`config`,null),y(this,`_blockTileIndex`,null),y(this,`anchor`,{lon:0,lat:0,height:0}),y(this,`rootUrls`,[]),y(this,`nodes`,new Map),y(this,`failed`,new Set),y(this,`textureCache`,new Map),y(this,`maxImageCache`,void 0),y(this,`_textureRefs`,new Map),y(this,`_tileTextureKeys`,new Map),y(this,`pending`,new Set),y(this,`atlasLod`,void 0),y(this,`atlasLodCache`,new Map),y(this,`_groupCache`,new Map),y(this,`externalAtlasCache`,new Map),y(this,`leafRequestCache`,new Map),y(this,`_leafPending`,new Map),y(this,`atlasUpgraded`,new Set),y(this,`atlasUpgradeSkipped`,new Map),y(this,`stats`,{tiles:0,loading:0,failed:0,meshes:0,vertices:0,triangles:0,datasets:1,drawCalls:0,programs:0,textures:0,geometries:0,degradations:[]}),y(this,`maxConcurrent`,void 0),y(this,`maxTiles`,void 0),y(this,`maxTriangles`,void 0),y(this,`maxMemory`,void 0),y(this,`lodRangeScale`,void 0),y(this,`lodTransition`,void 0),y(this,`fallbackOffset`,void 0),y(this,`primaryNodes`,new Set),y(this,`fallbackNodes`,new Set),y(this,`_onTile`,void 0),y(this,`_onTileRemoved`,void 0),y(this,`_onError`,void 0),y(this,`_onProgress`,void 0),y(this,`_maxRetries`,void 0),y(this,`authenticate`,void 0),y(this,`_unsupported`,void 0),y(this,`_retryCount`,new Map),y(this,`_retryAt`,new Map),y(this,`_parentOf`,new Map),y(this,`_frame`,0),y(this,`_permanentReported`,!1),y(this,`hardCap`,96),y(this,`isS3MV1`,!1),y(this,`_buildTile`,void 0),y(this,`_bakeMercator`,void 0),y(this,`rootRadius`,void 0),y(this,`_polygonOffset`,void 0),y(this,`_materialQuality`,void 0),y(this,`_colorPipeline`,void 0),y(this,`_textureOptions`,void 0),y(this,`_uniforms`,void 0),y(this,`_workerClient`,void 0),y(this,`_useWorker`,void 0),y(this,`_queue`,[]),y(this,`_active`,0),this.configUrl=e.configUrl,this.lodRangeScale=e.lodRangeScale??3,this.lodTransition=e.lodTransition??`binary`,this.fallbackOffset={factor:e.fallbackOffset?.factor??1,units:e.fallbackOffset?.units??2},this._onTile=e.onTile??(()=>{}),this._onTileRemoved=e.onTileRemoved??(()=>{}),this._onError=e.onError??(e=>console.warn(e)),this._onProgress=e.onProgress??(()=>{}),this._maxRetries=Math.max(0,e.maxRetries??2),this.authenticate=e.authenticate,this._unsupported=e.unsupported??`warn`,this._buildTile=e.buildTile??null,this._bakeMercator=e.bakeMercator,this._polygonOffset=e.polygonOffset,this._materialQuality=e.materialQuality,this._colorPipeline=e.colorPipeline,this._textureOptions=e.textureOptions,this._uniforms=e.uniforms??null,this._useWorker=e.useWorker!==!1,this.maxConcurrent=e.maxConcurrent??4,this.maxTiles=e.maxTiles??64,this.maxTriangles=e.maxTriangles??1/0,this.maxMemory=Number.isFinite(e.maxMemory)&&e.maxMemory>0?e.maxMemory:1/0,this.maxImageCache=e.maxImageCache??128,this.hardCap=this.maxTiles+Math.max(8,Math.ceil(this.maxTiles*.5)),this.atlasLod=e.atlasLod!==!1}async init(){this.configUrl=Uo(this.configUrl);let e=await Xt(this.configUrl,this.authenticate,`config`);if(!e.ok)throw Error(`配置读取失败 ${e.status} ${this.configUrl}`);let t=Xo(await e.text());this.config=t;let n=Zo(t);if(n!==`model`){let e=Error(`数据集 ${$o(this.configUrl)} 是${n===`terrain`?`地形`:`影像`}缓存(${Qo(t)}),本层仅支持模型类 S3M 数据集`);throw e.datasetKind=n,e}this.anchor=this._resolveAnchor(t);let r=t.rootTiles??t.tiles??[];if(!r.length)throw Error(`配置中缺少 root tile(${Qo(t)})——若是地形/影像数据集,或 configUrl 误指向 …/datas 数据集清单,本层仅支持模型类 S3M 数据集`);this.rootUrls.length=0;for(let e of r){let t=Wo(this.configUrl,e.url);t&&this.rootUrls.push(t)}if(this.isS3MV1=/OSGB/i.test(String(t.fileType??``))||/OSGB/i.test(String(t.dataType??``))||this.rootUrls.length>0&&this.rootUrls.every(e=>/\.s3m($|\?)/i.test(e)),this.rootUrls.every(e=>/\.s3mblock($|\?)/i.test(e))){this._blockTileIndex=new Set(this.rootUrls);for(let e of r){let t=Wo(this.configUrl,e.url);t&&this._blockTileIndex.add(t)}}await this._load(this.rootUrls[0]);for(let e of this.rootUrls.slice(1))this._enqueue(e);return this}_enqueue(e,t){if(!e||(t&&this._parentOf.set(e,t),this.nodes.has(e)||this.pending.has(e)||this.failed.has(e))||this._queue.includes(e))return;let n=this._retryAt.get(e);n!==void 0&&performance.now()<n||this.nodes.size+this.pending.size+this._queue.length>=this.hardCap||(this._queue.push(e),this._pump())}registerTileTextures(e,t){this._tileTextureKeys.set(e,t);let n=this.nodes.get(e);n&&(n.textureKeys=t);for(let e of t)this._textureRefs.set(e,(this._textureRefs.get(e)??0)+1)}_evictTileNode(e){this.nodes.delete(e.url),e.group?.parent?.remove(e.group),this._onTileRemoved(e),this._parentOf.delete(e.url),this.stats.tiles=Math.max(0,this.stats.tiles-1),e.stats&&(this.stats.meshes=Math.max(0,this.stats.meshes-(e.stats.meshes??0)),this.stats.vertices=Math.max(0,this.stats.vertices-(e.stats.vertices??0)),this.stats.triangles=Math.max(0,this.stats.triangles-(e.stats.triangles??0)));let t=e.textureKeys??this._tileTextureKeys.get(e.url)??e.group?.userData?.textureKeys;if(this._tileTextureKeys.delete(e.url),t?.length)for(let e of t){let t=(this._textureRefs.get(e)??1)-1;if(t<=0){this._textureRefs.delete(e);let t=this.textureCache.get(e);t&&(t.dispose?.(),this.textureCache.delete(e))}else this._textureRefs.set(e,t)}}putExternalAtlas(e,t){if(this.externalAtlasCache.size>=this.maxImageCache&&!this.externalAtlasCache.has(e)){let e=this.externalAtlasCache.keys().next().value;e!==void 0&&this.externalAtlasCache.delete(e)}Map.prototype.set.call(this.externalAtlasCache,e,t)}getExternalAtlas(e){return this.externalAtlasCache.get(e)}putLeafRecords(e,t){if(this.leafRequestCache.size>=this.maxImageCache&&!this.leafRequestCache.has(e)){let e=this.leafRequestCache.keys().next().value;e!==void 0&&this.leafRequestCache.delete(e)}Map.prototype.set.call(this.leafRequestCache,e,t)}getLeafRecords(e){return this.leafRequestCache.get(e)}_evictOne(e=!1){let t=this._pickVictim(!0,e)??this._pickVictim(!1,e);if(!t)return!1;let n=t.parentUrl??this._parentOf.get(t.url),r=t.childUrls??(t.childUrl?[t.childUrl]:[]);r.some(e=>e!==t.url&&this.nodes.has(e)),this._evictTileNode(t);let i=r.filter(e=>e!==t.url&&this.nodes.has(e));if(i.length){for(let e of i){let t=this.nodes.get(e);t&&(t.parentUrl=n??void 0,n?this._parentOf.set(e,n):this._parentOf.delete(e))}if(n){let e=this.nodes.get(n);if(e){let n=new Set(e.childUrls??[]);e.childUrl&&n.add(e.childUrl),n.delete(t.url);for(let e of i)n.add(e);e.childUrls=[...n],e.childUrl=e.childUrls[0]??null}}}return!0}_residentTriangles(){let e=0;for(let t of this.nodes.values())e+=t.stats?.triangles??0;return e}setMaxTriangles(e){this.maxTriangles=e>0?e:1/0}setMaxMemory(e){this.maxMemory=Number.isFinite(e)&&e>0?e:1/0}setMaterialQuality(e){this._materialQuality=e}setRenderProfile(e){e.colorPipeline!==void 0&&(this._colorPipeline=e.colorPipeline),e.textureOptions!==void 0&&(this._textureOptions=e.textureOptions)}residentMemory(){return this._residentGeometryBytes()+this._residentTextureBytes()}_residentGeometryBytes(){let e=0;for(let t of this.nodes.values())t.stats&&typeof t.stats.memory==`number`?e+=t.stats.memory:t.group&&(e+=ts(t.group));return e}_residentTextureBytes(){let e=0;for(let t of this.textureCache.values())e+=es(t);return e}_trimBudget(){let e=!1,t=0,n=()=>this.nodes.size+this.pending.size>this.maxTiles,r=()=>Number.isFinite(this.maxTriangles)&&this._residentTriangles()>this.maxTriangles,i=()=>Number.isFinite(this.maxMemory)&&this.residentMemory()>this.maxMemory,a=this.nodes.size+this.maxTiles+16;for(;(n()||r()||i())&&t++<=a&&this._evictOne(this.nodes.size+this.pending.size>this.hardCap);)e=!0;return e}_pickVictim(e,t=!1){let n=null;for(let r of this.nodes.values()){let i=r.childUrls??(r.childUrl?[r.childUrl]:[]);if((i.length>0&&i.some(e=>e!==r.url&&this.nodes.has(e)))!==e||!t&&r.group.visible&&(this.lodTransition===`incremental`||!i.some(e=>{let t=this.nodes.get(e);return!!t&&t.group.visible})))continue;if(!n){n=r;continue}let a=+!!r.group.visible,o=+!!n.group.visible;if(a!==o){a<o&&(n=r);continue}let s=r.lastSeen??-1,c=n.lastSeen??-1;(s<c||s===c&&(r.distance??0)>(n.distance??0))&&(n=r)}return n}retryFailed(){let e=this.failed.size;return this.failed.clear(),this._retryCount.clear(),this._retryAt.clear(),e}_pump(){for(;this._active<this.maxConcurrent&&this._queue.length;){let e=this._queue.shift();this._active++,this._load(e).finally(()=>{this._active--,this._pump()})}}_resolveAnchor(e){let t=e.position,n=t?.point3D??t,r=!!n&&Number.isFinite(n.x)&&Number.isFinite(n.y),i=Jo(e.geoBounds),a=i?(i.left+i.right)/2:void 0,o=i?(i.bottom+i.top)/2:void 0,s=n?.z??0;if(!r)return{lon:a??0,lat:o??0,height:0};if((t?.units??t?.unit??`Degree`)!==`Degree`)return{lon:n.x,lat:n.y,height:s};let c=a===void 0?0:Math.abs(n.x-a),l=o===void 0?0:Math.abs(n.y-o);return c>.5||l>.5?(console.warn(`[s3m] position 与 geoBounds 不一致,改用 geoBounds 中心作为锚点`,{position:n,geoBounds:i}),{lon:a,lat:o,height:s}):{lon:n.x,lat:n.y,height:s}}_pickLod(e){let t=e.groupNode?.pageLods??[];return t.length?t.find(e=>e.childTile&&e.rangeValue>0)??t[0]:null}async _builder(){if(!this._buildTile){let e=await Promise.resolve().then(()=>(Vo(),xo));this._buildTile=e.buildTileObjects}return this._buildTile}async _parseClassicTile(e){if(this._useWorker&&this._workerClient===void 0&&(this._workerClient=En()),this._workerClient)try{return await this._workerClient.parseTile(e,!0,!0,this.config?.vertexAttributeDescript)}catch(e){if(e instanceof Cn)this._workerClient=null;else throw e}return{tile:await Vt(e,{vertexAttributeDescript:this.config?.vertexAttributeDescript})}}_rememberGroups(e,t){for(this._groupCache.delete(e),this._groupCache.set(e,t);this._groupCache.size>24;){let e=this._groupCache.keys().next().value;if(e===void 0)break;this._groupCache.delete(e)}}async _fillExternalAtlases(e,t){let n=e,r=n.texturePackage;if(!r)return;let i=Xr(n),a=!1,o=new Map,s=new Map,c=[];for(let[e,t]of Object.entries(r)){let n=si(t.requestNames);if(n.names.length){o.set(e,{tex:t,plan:n});for(let[e,t]of n.packGroups){let n=t.filter(e=>!this.leafRequestCache.has(e));if(!n.length)continue;let r=s.get(e)??[];for(let e of n)r.includes(e)||r.push(e);s.set(e,r)}for(let e of n.plain)!this.leafRequestCache.has(e)&&!c.includes(e)&&c.push(e)}}let l=[];for(let[e,n]of s){let r=null,i=()=>r??(r=this._fetchLeafPack(t,e,n));for(let e of n)l.push(this._ensureLeafFetch(e,i))}for(let e of c)l.push(this._ensureLeafFetch(e,()=>this._fetchLeafFile(t,e)));l.length&&await Promise.all(l);for(let[e,{tex:t,plan:n}]of o){let r=new Map;for(let e of n.names){let t=this.leafRequestCache.get(e);if(t)for(let n of t)r.set(n.id,{source:e,image:n})}let i=ci(t,r);if(i){let n=t;n.composed=!0,n.leafSig=i.sig,n.flipY=!1,t.data=i.data,t.compressType=0,t.pixelFormat=28,t.width=i.width,t.height=i.height,t.rectScale=1,this.atlasUpgraded.add(e),a=!0,(i.missing.length||i.mismatched.length)&&console.warn(`[s3m] leaf 图集部分精灵异常:`,e,{missing:i.missing,mismatched:i.mismatched});continue}let o=!!t.data,s=n=>{if(!o){let r=t.width/t.height,i=n.width/n.height;return Math.abs(i/r-1)<=.02||(this.atlasUpgradeSkipped.set(e,`aspect(no-baseline) ${t.width}x${t.height} vs ${n.width}x${n.height}`),!1)}let r=fi(t,n);return r.ok?!0:(this.atlasUpgradeSkipped.set(e,`${r.reason} aspectΔ=${(r.aspectDelta*100).toFixed(1)}% scale=${r.scale} err=${Number.isNaN(r.meanAbsError)?`n/a`:r.meanAbsError.toFixed(1)}`),!1)},c=n=>{let r=t;r.composed=!1,r.leafSig=void 0,r.flipY=!0,t.data=n.data,t.compressType=n.compressType,t.pixelFormat=n.pixelFormat,t.rectScale=t.width>0?n.width/t.width:1,t.width=n.width||t.width,t.height=n.height||t.height,this.atlasUpgraded.add(e),a=!0},l=this.externalAtlasCache.get(e);if(l!==null){if(l===void 0){l=null;for(let e of n.plain){let t=this.leafRequestCache.get(e);if(t?.length){l=t[0];break}}this.putExternalAtlas(e,l)}l?s(l)&&c(l):this.atlasUpgradeSkipped.has(e)||this.atlasUpgradeSkipped.set(e,`no usable external image(请求失败或只拿到子精灵)`)}}(i||a)&&Zr(n)}_ensureLeafFetch(e,t){if(this.leafRequestCache.has(e))return Promise.resolve();let n=this._leafPending.get(e);if(n)return n;let r=t().finally(()=>this._leafPending.delete(e));return this._leafPending.set(e,r),r}async _fetchLeafPack(e,t,n){let r=Wo(Ho(e),`${n[0]}.texblock?extratiles=${n.join(`;`)}`);try{if(!r)throw Error(`无法拼出 URL`);let e=await Xt(r,this.authenticate,`texblock`);if(!e.ok)throw Error(`HTTP ${e.status}`);let t=await ei(await e.arrayBuffer());if(t.length!==n.length)throw Error(`pack 段数 ${t.length} ≠ 请求名 ${n.length}`);n.forEach((e,n)=>this.putLeafRecords(e,t[n]))}catch(e){console.warn(`[s3m] leaf pack 请求失败:`,r,e);for(let e of n)this.leafRequestCache.has(e)||this.putLeafRecords(e,null)}}async _fetchLeafFile(e,t){let n=Wo(Ho(e),`${t}.texblock`);try{if(!n)throw Error(`无法拼出 URL`);let e=await Xt(n,this.authenticate,`texblock`);if(!e.ok)throw Error(`HTTP ${e.status}`);let r=(await ei(await e.arrayBuffer())).flat();this.putLeafRecords(t,r)}catch(e){console.warn(`[s3m] leaf texblock 请求失败:`,n,e),this.leafRequestCache.has(t)||this.putLeafRecords(t,null)}}async _upgradeAtlasLod(e,t){}_noteDegradations(e){let t=e.degradations;if(!t?.length)return;let n=Ut(t,this.stats.degradations,this._unsupported);this.stats.degradations=n.known;for(let e of n.messages)console.warn(e);if(n.error)throw n.error}async _load(e){if(!(this.nodes.has(e)||this.pending.has(e)||this.failed.has(e))){this.pending.add(e),this.stats.loading++;try{let t=e.indexOf(`#`),n=t>=0?e.slice(0,t):e,r=t>=0&&Number(e.slice(t+1))||0,i=/\.s3mblock($|\?)/i.test(n),a,o,s=[],c=this._groupCache.get(n);if(c)s=c.names,a=c.tiles[r]??c.tiles[0];else{let e=await Xt(n,this.authenticate,`tile`);if(!e.ok)throw Error(`HTTP ${e.status} 加载瓦片失败: ${n}`);if((e.headers.get(`content-type`)||``).includes(`text/html`))throw Error(`瓦片请求返回了 HTML 页面(通常为 404/500 服务端拦截): ${n}`);let t=await e.arrayBuffer();if(i){let e=await li(t);this._rememberGroups(n,e),s=e.names,a=e.tiles[r]??e.tiles[0]}else{let e=await this._parseClassicTile(t);a=e.tile,o=e.geometry}}i&&(await this._fillExternalAtlases(a,n),await this._upgradeAtlasLod(a,n)),this._noteDegradations(a);let l=this._pickLod(a);this.rootRadius===void 0&&l?.boundingSphere?.radius&&(this.rootRadius=l.boundingSphere.radius);let u=this.shouldBakeMercator(l?.boundingSphere?.radius),d=await(await this._builder())(a,{textureCache:this.textureCache,uniforms:this._uniforms,assembled:o,polygonOffset:this._polygonOffset,materialQuality:this._materialQuality,colorPipeline:this._colorPipeline,textureOptions:this._textureOptions,bakeMercator:u,tileAnchor:this.anchor,tileCenter:l?.boundingSphere?.center}),{group:f,stats:p}=d,m=d.textureKeys??f.userData?.textureKeys??Object.keys(a.textures??{});this.registerTileTextures(e,m);let h=this._pickLod(a),g=[];for(let t of a.groupNode?.pageLods??[]){let r=String(t.childTile??``).replace(/\.s3mblock$/i,``),a=i&&r?s.indexOf(r):-1,o=a>=0?`${n}#${a}`:this.isS3MV1?Yo(e,t.childTile):Wo(Ho(e),t.childTile);o&&o!==e&&!g.includes(o)&&g.push(o)}let _={url:e,tile:a,group:f,sphere:h?.boundingSphere??null,rangeValue:h?.rangeValue??0,rangeMode:h?.rangeMode??1,childUrl:g[0]??(this.isS3MV1?Yo(e,h?.childTile):Wo(Ho(e),h?.childTile)),childUrls:g,parentUrl:this._parentOf.get(e),state:`ready`,...p.splatSigma?{splatSigma:p.splatSigma}:{},...p.splatCount?{splatCount:p.splatCount}:{},stats:{meshes:p.meshes??0,vertices:p.vertices??0,triangles:p.triangles??0,memory:p.memory??ts(f)}};this.nodes.set(e,_),this.stats.tiles++,this.stats.meshes+=p.meshes??0,this.stats.vertices+=p.vertices??0,this.stats.triangles+=p.triangles??0,this._onTile(_)}catch(t){let n=t?.permanent===!0,r=(this._retryCount.get(e)??0)+1;if(this._retryCount.set(e,r),!n&&r<=this._maxRetries)this._retryAt.set(e,performance.now()+800*r);else{this.stats.failed++,this.failed.add(e),this._retryAt.delete(e);let t=this._parentOf.get(e),n=t?this.nodes.get(t):void 0;n?.childUrls&&(n.childUrls=n.childUrls.filter(t=>t!==e),n.childUrl=n.childUrls[0]??null)}n?this._permanentReported||(this._permanentReported=!0,this._onError(t)):this._onError(t)}finally{this.pending.delete(e),this.stats.loading--,this._onProgress(this.stats)}}}update(e,t,n){this._frame++;let r=!1;for(let t of this.nodes.values()){var i;if(!t.sphere){t.lastSeen=this._frame,t.needRefine=!1;continue}let a=t.sphere.center,o=a.x-e[0],s=a.y-e[1],c=a.z-e[2],l=Math.sqrt(o*o+s*s+c*c)||1e-6;t.distance=l;let u,d=t.rangeMode===0;u=d?l:n*.5/Math.tan(Math.PI/8)*(t.sphere.radius/l)*2;let f=this.lodRangeScale>0?this.lodRangeScale:1,p=t.rangeValue*f;(d?l<p*2:u>p*.5)&&(t.lastSeen=this._frame);let m=t.childUrls??(t.childUrl?[t.childUrl]:[]),h=t.needRefine?d?1.08:.92:1,g=t.splatSigma&&t.sphere?Sn({splats:t.splatCount??t.stats?.vertices??0,radius:t.sphere.radius,distance:l,sigma:t.splatSigma,screenHeight:n,hasChild:m.length>0}):null,_=g?g.needRefine:m.length>0&&(d?u<p*h:u>p*h);t.needRefine=_;let v=(i=globalThis).__S3M_LOD_SEEN??(i.__S3M_LOD_SEEN=new Set);if(globalThis.__S3M_LOD_DEBUG&&!v.has(t.url)&&v.size<260&&(v.add(t.url),console.log(`[LOD]`,JSON.stringify({url:t.url.split(`/`).pop(),mode:t.rangeMode,rangeValue:t.rangeValue,radius:t.sphere.radius,dist:+l.toFixed(1),metric:+u.toFixed(1),threshold:+p.toFixed(1),needRefine:_,childUrls:m.map(e=>e.split(`/`).pop()),parent:t.parentUrl?t.parentUrl.split(`/`).pop():null}))),_)for(let e of m)this.failed.has(e)||this.nodes.has(e)||this.pending.has(e)||(this._enqueue(e,t.url),r=!0)}let a=new Set,o=new Set(this.rootUrls);for(let[e,t]of this.nodes){let n=t.parentUrl??this._parentOf.get(e);n&&this.nodes.has(n)||o.add(e)}if(this.lodTransition===`incremental`)this._updateVisibilityIncremental(o,a)&&(r=!0);else{for(let e of o)this._updateNodeVisibility(e,!0,a)&&(r=!0);this.primaryNodes.clear();for(let[e,t]of this.nodes)t.group.visible&&this.primaryNodes.add(e);this.fallbackNodes.clear()}for(let[e,t]of this.nodes)a.has(e)||(t.group.visible&&(t.group.visible=!1,r=!0),this.lodTransition===`incremental`&&this._restoreNodePolygonOffset(t));this._trimBudget()&&(r=!0);let s=!1;for(let e of this.nodes.values())if(e.group.visible){s=!0;break}if(!s&&this.nodes.size>0)for(let e of this.nodes.values())!(e.childUrls??(e.childUrl?[e.childUrl]:[])).some(t=>{let n=this.nodes.get(t);return!!n&&n!==e&&n.group.visible})&&!e.group.visible&&(e.group.visible=!0,r=!0);return r}_updateNodeVisibility(e,t,n){let r=this.nodes.get(e);if(!r||n.has(e))return!1;n.add(e);let i=!1,a=r.childUrls??(r.childUrl?[r.childUrl]:[]);if(!t){r.group.visible&&(r.group.visible=!1,i=!0);for(let e of a)this._updateNodeVisibility(e,!1,n)&&(i=!0);return i}let o=a.length>0,s=a.filter(e=>this.nodes.has(e)),c=a.every(e=>this.nodes.has(e)||this.failed.has(e));if(r.needRefine&&o&&s.length>0&&c){r.group.visible&&(r.group.visible=!1,i=!0);for(let e of a)this._updateNodeVisibility(e,!0,n)&&(i=!0)}else{r.group.visible||(r.group.visible=!0,i=!0);for(let e of a)this._updateNodeVisibility(e,!1,n)&&(i=!0)}return i}getLodTransition(){return this.lodTransition}setLodTransition(e){if(this.lodTransition!==e&&(this.lodTransition=e,e===`binary`)){for(let e of this.nodes.values())this._restoreNodePolygonOffset(e);this.fallbackNodes.clear()}}_applyNodeFallbackPolygonOffset(e,t){let n=this.fallbackOffset.factor,r=Math.max(2,(10-Math.min(t,8))*this.fallbackOffset.units),i=!1;return e.group.traverse(e=>{let t=e;if((t.isMesh||t.isPoints||t.isLine)&&t.material){let e=Array.isArray(t.material)?t.material:[t.material];for(let t of e){if(!t)continue;t.userData||(t.userData={}),t.userData._basePolygonOffset||(t.userData._basePolygonOffset={polygonOffset:t.polygonOffset===!0,factor:t.polygonOffsetFactor??0,units:t.polygonOffsetUnits??0});let e=t.userData._basePolygonOffset,a=e.factor+n,o=e.units+r;(t.polygonOffset!==!0||t.polygonOffsetFactor!==a||t.polygonOffsetUnits!==o)&&(t.polygonOffset=!0,t.polygonOffsetFactor=a,t.polygonOffsetUnits=o,i=!0)}}}),i}_restoreNodePolygonOffset(e){let t=!1;return e.group.traverse(e=>{let n=e;if((n.isMesh||n.isPoints||n.isLine)&&n.material){let e=Array.isArray(n.material)?n.material:[n.material];for(let n of e)if(n?.userData?._basePolygonOffset){let e=n.userData._basePolygonOffset;(n.polygonOffset!==e.polygonOffset||n.polygonOffsetFactor!==e.factor||n.polygonOffsetUnits!==e.units)&&(n.polygonOffset=e.polygonOffset,n.polygonOffsetFactor=e.factor,n.polygonOffsetUnits=e.units,t=!0)}}}),t}_updateVisibilityIncremental(e,t){let n=new Set,r=new Set,i=new Map,a=(e,o)=>{if(t.has(e))return;t.add(e),i.set(e,o);let s=this.nodes.get(e);if(!s)return;let c=s.childUrls??(s.childUrl?[s.childUrl]:[]),l=c.length>0,u=c.filter(e=>this.nodes.has(e)),d=c.filter(e=>!this.nodes.has(e)&&!this.failed.has(e));if(s.needRefine&&l&&u.length>0){d.length>0&&r.add(e);for(let e of u)a(e,o+1)}else n.add(e)};for(let t of e)a(t,0);let o=!1;for(let[e,a]of this.nodes)if(t.has(e)){if(n.has(e)){a.group.visible||(a.group.visible=!0,o=!0);let t=100+(i.get(e)??0);a.group.renderOrder!==t&&(a.group.renderOrder=t,o=!0),this._restoreNodePolygonOffset(a)&&(o=!0)}else if(r.has(e)){a.group.visible||(a.group.visible=!0,o=!0);let t=i.get(e)??0,n=t;a.group.renderOrder!==n&&(a.group.renderOrder=n,o=!0),this._applyNodeFallbackPolygonOffset(a,t)&&(o=!0)}else a.group.visible&&(a.group.visible=!1,o=!0),this._restoreNodePolygonOffset(a)&&(o=!0)}this.primaryNodes.clear();for(let e of n)this.primaryNodes.add(e);this.fallbackNodes.clear();for(let e of r)this.fallbackNodes.add(e);return o}dispose(){this._workerClient?.dispose();for(let e of this.nodes.values())e.group.traverse(e=>{let t=e;t.geometry?.dispose?.(),Array.isArray(t.material)?t.material.forEach(e=>e.dispose?.()):t.material?.dispose?.()});for(let e of this.textureCache.values())e.dispose?.();this.textureCache.clear(),this.nodes.clear()}};Vo();var rs={ambientIntensity:.4,hemisphereIntensity:.8,keyLightIntensity:1,fillLightIntensity:.35},is={ambientIntensity:.12,hemisphereIntensity:.2,keyLightIntensity:1.95,fillLightIntensity:.15},as={default:rs,supermap:is};function os(e){return e&&Object.prototype.hasOwnProperty.call(as,e)?as[e]:rs}b();var ss={ambientIntensity:.4,ambientColor:16777215,hemisphereIntensity:.8,hemisphereColor:16777215,hemisphereGroundColor:11976907,keyLightIntensity:1,keyLightColor:16777215,fillLightIntensity:.35,fillLightColor:16777215,mode:`headlamp`,azimuth:150,altitude:50},cs=class{get envRT(){return this._envRT}set envRT(e){this._envRT=e}constructor(e){y(this,`ctx`,void 0),y(this,`ambient`,null),y(this,`hemi`,null),y(this,`key`,null),y(this,`fill`,null),y(this,`_state`,void 0),y(this,`_envRT`,null),this.ctx=e,this._state={...ss};let t=e.options;t.lightingPreset&&t.lightingPreset!=="default"&&(Object.assign(this._state,os(t.lightingPreset)),this.applyColorPipeline(t.lightingPreset,!0)),t.light&&Object.assign(this._state,t.light)}_create(){this.ambient=new t.AmbientLight(this._state.ambientColor,this._state.ambientIntensity),this.hemi=new t.HemisphereLight(this._state.hemisphereColor,this._state.hemisphereGroundColor,this._state.hemisphereIntensity),this.key=new t.DirectionalLight(this._state.keyLightColor,this._state.keyLightIntensity),this.fill=new t.DirectionalLight(this._state.fillLightColor,this._state.fillLightIntensity),this.update()}addToScene(){let e=this.ctx.scene();e&&(this.ambient||this._create(),e.add(this.ambient,this.hemi,this.key,this.fill))}get created(){return this.ambient!==null}_applyOptions(){let e=this._state;this.ambient&&(this.ambient.intensity=e.ambientIntensity,this.ambient.color.set(e.ambientColor)),this.hemi&&(this.hemi.intensity=e.hemisphereIntensity,this.hemi.color.set(e.hemisphereColor),this.hemi.groundColor.set(e.hemisphereGroundColor)),this.key&&(this.key.intensity=e.keyLightIntensity,this.key.color.set(e.keyLightColor)),this.fill&&(this.fill.intensity=e.fillLightIntensity,this.fill.color.set(e.fillLightColor))}update(){if(!this.key||!this.fill)return;let e=this._state,t=e.mode===`fixed`?0:(this.ctx.getBearing?.()??0)*Math.PI/180,n=(e,n,r)=>{if(!e)return;let i=t+n*Math.PI/180,a=r*Math.PI/180,o=Math.cos(a);e.position.set(Math.sin(i)*o,Math.cos(i)*o,Math.sin(a)).multiplyScalar(1e3)};n(this.key,e.azimuth,e.altitude),n(this.fill,e.azimuth+65,Math.max(10,e.altitude-20));let r=this.ctx.uniforms?.uSunDirection;r&&r.value.copy(this.key.position).normalize()}applyColorPipeline(e,t=!1){let n=e===`supermap`;this.ctx.applyRenderProfile({colorPipeline:n?`direct`:`linear`,anisotropyCap:n?1:1/0},t)}setLightingPreset(e){Object.assign(this._state,os(e)),this.applyColorPipeline(e),this.ctx.options.lightingPreset=e,this._applyOptions(),this.update(),this.ctx.repaint()}setLight(e){let t={...e};t.mainColor!==void 0&&t.keyLightColor===void 0&&(t.keyLightColor=t.mainColor),t.mainIntensity!==void 0&&t.keyLightIntensity===void 0&&(t.keyLightIntensity=t.mainIntensity),Object.assign(this._state,t),this._applyOptions(),this.update(),this.ctx.repaint()}getLight(){return{...this._state}}setToneMapping(e,t=1){this.ctx.options.toneMapping=e,this.ctx.options.toneMappingExposure=t;let n=this.ctx.renderer();n&&(n.toneMapping=e,n.toneMappingExposure=t,this.ctx.repaint())}getToneMapping(){let e=this.ctx.renderer();return{toneMapping:e?e.toneMapping:this.ctx.options.toneMapping??t.NoToneMapping,toneMappingExposure:e?e.toneMappingExposure:this.ctx.options.toneMappingExposure??1}}async setEnvironment(e,n=1){let r=this.ctx.renderer(),i=this.ctx.scene();if(!r||!i)return;if(i.environmentIntensity=Math.max(0,n),e==null){i.environment=null,this._envRT?.dispose(),this._envRT=null,this.ctx.repaint();return}let a=typeof e==`string`,o=a?await new t.TextureLoader().loadAsync(e):e;o.mapping=t.EquirectangularReflectionMapping;let s=new t.PMREMGenerator(r);s.compileEquirectangularShader();let c=s.fromEquirectangular(o);s.dispose(),a&&o.dispose(),i.environment=c.texture,this._envRT?.dispose(),this._envRT=c,this.ctx.repaint()}dispose(){this._envRT?.dispose(),this._envRT=null}};b();var ls=class{constructor(e){y(this,`uniforms`,void 0),y(this,`_meshHeight`,new Map),y(this,`_min`,1/0),y(this,`_max`,-1/0),y(this,`_box`,new t.Box3),this.uniforms=e}get size(){return this._meshHeight.size}add(e){let t=e.geometry?.boundingBox;if(!t)return;this._box.copy(t).applyMatrix4(e.matrixWorld);let n=this._box.min.z,r=this._box.max.z;Number.isFinite(n)&&Number.isFinite(r)&&(this._meshHeight.set(e,{min:n,max:r}),n<this._min&&(this._min=n),r>this._max&&(this._max=r),this._push())}remove(e){let t=this._meshHeight.get(e);t&&(this._meshHeight.delete(e),t.min===this._min||t.max===this._max?this._recompute():this._push())}refreshAll(){if(this._meshHeight.size===0)return;let e=[...this._meshHeight.keys()];this._meshHeight.clear(),this._min=1/0,this._max=-1/0;for(let t of e)this.add(t);this._push()}clear(){this._meshHeight.clear(),this._min=1/0,this._max=-1/0}get range(){return{min:this._min,max:this._max}}_recompute(){let e=1/0,t=-1/0;for(let n of this._meshHeight.values())n.min<e&&(e=n.min),n.max>t&&(t=n.max);this._min=e,this._max=t,this._push()}_push(){let e=this._min,t=this._max;(!Number.isFinite(e)||!Number.isFinite(t)||t<=e)&&(e=0,t=100),this.uniforms.uHeightMin.value=e,this.uniforms.uHeightMax.value=t}},us=new Uint32Array,ds=new Uint32Array,fs=new Uint32Array(256),ps=new Float32Array(1),ms=new Uint32Array(ps.buffer);function hs(e){ps[0]=e;let t=ms[0];return t&2147483648?~t>>>0:(t|2147483648)>>>0}function gs(e,t,n,r){let i=r&&r.length>=t?r:new Uint32Array(t);if(t<=1)return t===1&&(i[0]=0),i;us.length<t&&(us=new Uint32Array(t)),ds.length<t&&(ds=new Uint32Array(t));let a=us,o=ds,s=n.elements,c=s[2],l=s[6],u=s[10],d=s[14];for(let n=0;n<t;n++)a[n]=hs(c*e[n*3]+l*e[n*3+1]+u*e[n*3+2]+d),i[n]=n;let f=i,p=o;for(let e=0;e<4;e++){let n=e*8;fs.fill(0);for(let e=0;e<t;e++)fs[a[f[e]]>>>n&255]++;let r=0;for(let e=0;e<256;e++){let t=fs[e];fs[e]=r,r+=t}for(let e=0;e<t;e++){let t=f[e];p[fs[a[t]>>>n&255]++]=t}let i=f;f=p,p=i}return f!==i&&i.set(f),i}var _s=[`iCenter`,`iScale`,`iQuat`,`iColor`],vs=new t.Matrix4,ys=new WeakMap,bs=new WeakMap;function xs(e,t){let n=e.geometry,r=n.getAttribute(`iCenter`);if(!r)return!1;let i=Math.min(n.instanceCount??1/0,r.count);if(i<=1)return!1;vs.multiplyMatrices(t,e.matrixWorld);let a=bs.get(r);(!a||a.length<i)&&(a=new Uint32Array(i),bs.set(r,a)),gs(r.array,i,vs,a);let o=!0;for(let e=0;e<i;e++)if(a[e]!==e){o=!1;break}if(o)return!1;for(let e of _s){let t=n.getAttribute(e);if(!t)continue;let r=t.array,o=t.itemSize,s=i*o,c=ys.get(t);(!c||c.length<s)&&(c=new r.constructor(s),ys.set(t,c));for(let e=0;e<i;e++){let t=a[e]*o,n=e*o;for(let e=0;e<o;e++)c[n+e]=r[t+e]}r.set(c.subarray(0,s)),t.needsUpdate=!0}return!0}b();var Ss=class{constructor(){y(this,`_lastView`,new t.Matrix4),y(this,`_sorted`,!1)}markDirty(){this._sorted=!1}sort(e,t){if(e&&!(this._sorted&&this._lastView.equals(e.matrixWorldInverse))){for(let n of t)n.userData.isGaussianSplat&&xs(n,e.matrixWorldInverse);this._lastView.copy(e.matrixWorldInverse),this._sorted=!0}}reset(){this._sorted=!1,this._lastView.identity()}};ja(),Xi();function Cs(){return{uResolution:{value:new t.Vector2(1,1)},uDpr:{value:1}}}var ws=`
943
+ `,side:t.DoubleSide,depthTest:!0,depthWrite:!0})}function ho(e){let t=e.getAttribute(`iCenter`);if(!t)return null;let n=t.array,r=t.count;if(!r)return null;let i=1/0,a=1/0,o=1/0,s=-1/0,c=-1/0,l=-1/0;for(let e=0;e<r;e++){let t=n[e*3],r=n[e*3+1],u=n[e*3+2];t<i&&(i=t),t>s&&(s=t),r<a&&(a=r),r>c&&(c=r),u<o&&(o=u),u>l&&(l=u)}return{minX:i,minY:a,minZ:o,maxX:s,maxY:c,maxZ:l,count:r}}var go,_o,vo,yo,bo=c((()=>{yn(),go=new t.Vector2(1e3,1e3),_o=new t.Sphere,vo=new t.Matrix4,yo=new t.Ray})),xo=l({LINE_PRIMITIVE:()=>13,POINT_PRIMITIVE:()=>1,buildTileObjects:()=>Po,setSplatViewport:()=>wo});function So(e){return e===1}function Co(){return Fo??(Fo=uo()),Fo}function wo(e,t){Fo&&Fo.uniforms.uViewport.value.set(e,t)}function To(e,n){let r=n.vertexAttributes.find(e=>e.semantic===`gsScale`),i=n.vertexAttributes.find(e=>e.semantic===`gsRotation`),a=e.attributes.position;if(!r||!i||!a)return null;let o=Math.min(n.verticesCount,Math.floor(a.array.length/a.components));if(o<=0)return null;let s=ro(r.data,r.stride,r.offsetInBytes,o),c=io(i.data,i.stride,i.offsetInBytes,o),l=Eo(s,o),u=fo();u.instanceCount=o,u.setAttribute(`iCenter`,new t.InstancedBufferAttribute(a.array,3)),u.setAttribute(`iScale`,new t.InstancedBufferAttribute(s,3)),u.setAttribute(`iQuat`,new t.InstancedBufferAttribute(c,4));let d=new Float32Array(o*4);d.fill(1);let f=n.vertexAttributes.find(e=>e.semantic===`color`);if(f&&f.dtype===`u8`){let e=f.components??4,t=Math.min(o,Math.floor(f.data.length/f.stride));for(let n=0;n<t;n++){let t=n*f.stride+f.offsetInBytes;d[n*4]=f.data[t]/255,d[n*4+1]=f.data[t+1]/255,d[n*4+2]=f.data[t+2]/255,e>=4&&(d[n*4+3]=f.data[t+3]/255)}}else if(e.attributes.aColor){let t=e.attributes.aColor,n=t.components??4;for(let e=0;e<o;e++)for(let r=0;r<Math.min(n,4);r++)d[e*4+r]=t.array[e*n+r]}u.setAttribute(`iColor`,new t.InstancedBufferAttribute(d,4));let p=a.array,m=1/0,h=1/0,g=1/0,_=-1/0,v=-1/0,y=-1/0,b=0;for(let e=0;e<o;e++){let t=p[e*3],n=p[e*3+1],r=p[e*3+2];t<m&&(m=t),t>_&&(_=t),n<h&&(h=n),n>v&&(v=n),r<g&&(g=r),r>y&&(y=r);let i=s[e*3],a=s[e*3+1],o=s[e*3+2];i>b&&(b=i),a>b&&(b=a),o>b&&(b=o)}let x=new t.Box3;o>0&&(x.min.set(m,h,g),x.max.set(_,v,y));let S=new t.Sphere(new t.Vector3,0);return x.isEmpty()||x.getBoundingSphere(S),S.radius+=3*b,u.boundingSphere=S,{geo:u,sigma:l}}function Eo(e,t){let n=Math.max(1,Math.floor(t/512)),r=[];for(let i=0;i<t;i+=n){let t=Math.max(e[i*3],e[i*3+1],e[i*3+2]);Number.isFinite(t)&&t>0&&r.push(t)}return r.length?(r.sort((e,t)=>e-t),r[r.length>>1]):0}function Do(){return Io||(Io=new t.PointsMaterial({size:2,sizeAttenuation:!1,vertexColors:!0})),Io}function Oo(e){if(!e)return[];if(Array.isArray(e))return e;let t=e,n=t.materials??t.material;return Array.isArray(n)?n:[]}function ko(e){return e?.material??e}function Ao(e){return e?.name??e?.id}function jo(e){return(e?.textureStates??e?.textureunitstates??[]).map(e=>e?.textureunitstate??e).filter(e=>!!e)}function Mo(e){return e.length===16&&e[0]===1&&e[1]===0&&e[2]===0&&e[3]===0&&e[4]===0&&e[5]===1&&e[6]===0&&e[7]===0&&e[8]===0&&e[9]===0&&e[10]===1&&e[11]===0&&e[12]===0&&e[13]===0&&e[14]===0&&e[15]===1}function No(e){let n=String(e?.cullMode??``).toUpperCase();return n===`CULL_BACK`||n===`BACKWARD`?t.FrontSide:n===`CULL_FRONT`?t.BackSide:t.DoubleSide}async function Po(e,n={}){let r=n.uniforms??aa(),i=n.textureCache??new Map,a=new t.Group,o=[],s=[],c={meshes:0,vertices:0,triangles:0,textures:0,instanced:0,edgeLines:0,skipped:[]},l=new t.LineBasicMaterial({color:new t.Color(n.edgeColor??`#1f2937`),transparent:!0,opacity:.75,depthWrite:!1});a.userData.hasNativeEdges=!1;let u=t=>{let n=e.textures?.[t];return n?.packKey?`${t}#${n.packKey}`:t};for(let[t,r]of Object.entries(e.textures??{})){let e=u(t),a=i.get(e);if(a){let t=a.image;if((t?.width??0)*(t?.height??0)>=(r.width??0)*(r.height??0))continue;i.delete(e)}let{texture:o,decoded:l}=await Ri(r,n.textureOptions);o?(i.set(e,o),s.push(e),c.textures++):c.skipped.push(`texture ${t} → ${l}`)}let d=Oo(e.materials),f=e=>d.findIndex(t=>Ao(ko(t))===e),p=(e,a=!1,o=!1,s=1,c=!1)=>{let l=ko(d.find(t=>Ao(ko(t))===e)),f=jo(l),p=f[0],m=p?i.get(u(Ao(p)??p.id??``))??null:null,h=f[1],g=globalThis.__S3M_NO_BAKE===!0,_=a&&h&&!g?i.get(u(Ao(h)??h.id??``))??null:null,v=p?.texmodmatrix??p?.matrix;if(m&&Array.isArray(v)&&v.length===16&&!Mo(v)&&(m=m.clone(),m.matrixAutoUpdate=!1,m.matrix.set(v[0],v[4],v[12],v[1],v[5],v[13],0,0,1)),m&&p?.addressmode){let e=p.addressmode.u,n=p.addressmode.v;(e!==void 0||n!==void 0)&&(m.matrixAutoUpdate&&(m=m.clone()),e!==void 0&&(m.wrapS=e===0?t.RepeatWrapping:t.ClampToEdgeWrapping),n!==void 0&&(m.wrapT=n===0?t.RepeatWrapping:t.ClampToEdgeWrapping))}let y=l?.diffuse??{r:1,g:1,b:1,a:1},b=[p,h].some(e=>/\.water$/i.test(String(Ao(e)??e?.id??``))),x=Na({alphaMode:l?.alphaMode,diffuseAlpha:y.a??1,transparentSorting:l?.transparentsorting===!0,vertexAlphaMin:s,isWaterWithoutMap:b&&!m}),S=typeof l?.shininess==`number`&&l.shininess>0?Math.max(.15,1-l.shininess/128):.95,C=m?.userData?.s3mHasAlpha?Math.max(l?.alphaCutoff??0,.01):0,w;if(n.tileAnchor){let e=sn(n.tileAnchor.lon,n.tileAnchor.lat,n.tileAnchor.height),t=e.meterInMercatorEast??e.meterInMercator,r=e.meterInMercatorNorth??e.meterInMercator,i=e.meterInMercatorUp??t;w=[1/t,1/r,1/i]}let T=oa({uniforms:r,map:m,color:b&&!m?Lo.clone():new t.Color(y.r??1,y.g??1,y.b??1),side:No(l),transparent:x,opacity:b&&!m?.86:y.a??1,roughness:b&&!m?.12:S,alphaTest:C,atlas:a&&!!m,texCoordZ:o&&!!m,secMap:_,materialQuality:n.materialQuality,colorPipeline:n.colorPipeline,bakeMercator:c||n.bakeMercator,tilePivot:n.tileCenter?new t.Vector3(n.tileCenter.x,n.tileCenter.y,n.tileCenter.z):void 0,invTileScale:w?new t.Vector3(...w):void 0});return n.polygonOffset&&(T.polygonOffset=!0,T.polygonOffsetFactor=n.polygonOffset.factor,T.polygonOffsetUnits=n.polygonOffset.units),T};if(n.assembled&&n.bakeMercator&&n.tileAnchor){for(let e of n.assembled.primitives)if(!e.attributes.aMercatorOffset&&e.attributes.position){let t=mi(e.attributes.position.array,e.vertexCount,n.tileAnchor,n.tileCenter??{x:0,y:0,z:0});e.attributes.aMercatorOffset={array:t,components:3,normalized:!1}}}let m=n.assembled??$a(e,{batching:n.batching!==!1,dedupeCoincident:n.dedupeCoincident,bakeMercator:n.bakeMercator,tileAnchor:n.tileAnchor,tileCenter:n.tileCenter});c.vertices=m.stats.vertices,c.edgeLines=m.stats.edgeLines,c.instanced=m.stats.instanced,m.stats.originalMeshes!=null&&(c.originalMeshes=m.stats.originalMeshes),c.skipped.push(...m.stats.skipped);let h=new t.Matrix4,g=e=>{let n=new t.BufferGeometry;for(let[r,i]of Object.entries(e.attributes))i&&n.setAttribute(r,new t.BufferAttribute(i.array,i.components,i.normalized));return e.index?n.setIndex(new t.BufferAttribute(e.index,1)):n.setDrawRange(0,e.vertexCount),n.boundingBox=new t.Box3(new t.Vector3(...e.bounds.boxMin),new t.Vector3(...e.bounds.boxMax)),n.boundingSphere=new t.Sphere(new t.Vector3(...e.bounds.sphereCenter),e.bounds.sphereRadius),n};for(let r of m.primitives){let i=g(r),s=e.geoPackage[r.geoNames[0]]??null,u=s?.vertexPackage,m=!!r.attributes.aMercatorOffset,_=p(r.passNames[0],!!r.attributes.aAtlasRect,!!r.attributes.aTexCoordZ,Pa(r.attributes.aColor),m),v=r.matrix&&r.matrix.length===16?new t.Matrix4().fromArray(r.matrix):null;if(r.primitiveType===13){let e=new t.LineSegments(i,l);e.visible=n.edges===!0,e.renderOrder=Ro,e.raycast=()=>{},e.userData.isEdgeLines=!0,e.userData.skeletonName=r.skeletonName,v&&!v.equals(h)&&v.decompose(e.position,e.quaternion,e.scale),a.add(e),o.push(e),a.userData.hasNativeEdges=!0;continue}if(r.primitiveType===2||r.primitiveType===3){let n=ko(d.find(e=>Ao(ko(e))===r.passNames[0]))?.diffuse,l=n?new t.Color(n.r??1,n.g??1,n.b??1):new t.Color(16777215),u=!!i.getAttribute(`aColor`)||!!i.getAttribute(`color`);u&&!i.getAttribute(`color`)&&i.setAttribute(`color`,i.getAttribute(`aColor`));let f=new t.LineBasicMaterial({color:l,vertexColors:u,transparent:n?.a!==void 0&&n.a<1,opacity:n?.a??1}),p=r.primitiveType===3?new t.Line(i,f):new t.LineSegments(i,f);p.visible=!0,p.userData.skeletonName=r.skeletonName,p.userData.geoRef=s,p.userData.tileRef=e,p.userData.primitiveType=r.primitiveType,v&&!v.equals(h)&&v.decompose(p.position,p.quaternion,p.scale),a.add(p),o.push(p),c.meshes++;continue}if(So(r.primitiveType)){let n=u?To(r,u):null;if(n){let i=new t.InstancedMesh(n.geo,Co(),n.geo.instanceCount);i.raycast=po,i.frustumCulled=!1,i.renderOrder=zo,n.sigma>0&&(c.splatSigma=Math.max(c.splatSigma??0,n.sigma)),c.splatCount=(c.splatCount??0)+n.geo.instanceCount,i.userData.isPointCloud=!0,i.userData.isGaussianSplat=!0,i.userData.skeletonName=r.skeletonName,i.userData.geoRef=s,i.userData.tileRef=e,i.userData.primitiveType=r.primitiveType,v&&!v.equals(h)&&v.decompose(i.position,i.quaternion,i.scale),a.add(i),o.push(i),c.meshes++;continue}i.getAttribute(`color`)||i.setAttribute(`color`,i.getAttribute(`aColor`));let l=new t.Points(i,Do());l.userData.isPointCloud=!0,l.userData.skeletonName=r.skeletonName,l.userData.geoRef=s,l.userData.tileRef=e,l.userData.primitiveType=r.primitiveType,v&&!v.equals(h)&&v.decompose(l.position,l.quaternion,l.scale),a.add(l),o.push(l),c.meshes++;continue}let y;if(u&&u.instanceIndex!==-1&&(u.instanceMode===16||u.instanceMode===17)&&u.instanceBuffer&&(u.instanceCount??0)>0&&u){if(!i.getAttribute(`aInstanceBatchId`)){let e=u.instanceBatchIds,n=e&&e.length===u.instanceCount?e.slice():new Float32Array(u.instanceCount).fill(-1);i.setAttribute(`aInstanceBatchId`,new t.InstancedBufferAttribute(n,1));let r=new Float32Array(u.instanceCount);for(let e=0;e<r.length;e++)r[e]=e;i.setAttribute(`aInstanceIndex`,new t.InstancedBufferAttribute(r,1))}let e=new t.InstancedMesh(i,_,u.instanceCount);e.instanceMatrix.setUsage(t.StaticDrawUsage);let n=new t.Matrix4,r=new t.Color,a=u.instanceMode,o=new Float32Array(u.instanceBuffer.buffer,u.instanceBuffer.byteOffset,u.instanceCount*a);for(let t=0;t<u.instanceCount;t++){let i=t*a;if(n.set(o[i+0],o[i+1],o[i+2],o[i+3],o[i+4],o[i+5],o[i+6],o[i+7],o[i+8],o[i+9],o[i+10],o[i+11],0,0,0,1),e.setMatrixAt(t,n),a>=16){let n=o[i+12],a=o[i+13],s=o[i+14];Number.isFinite(n)&&Number.isFinite(a)&&Number.isFinite(s)&&(r.setRGB(n,a,s),e.setColorAt(t,r))}}e.instanceMatrix.needsUpdate=!0,e.instanceColor&&(e.instanceColor.needsUpdate=!0),e.frustumCulled=!1,y=e}else y=new t.Mesh(i,_);v&&!v.equals(h)&&v.decompose(y.position,y.quaternion,y.scale),y.userData.skeletonName=r.skeletonName,y.userData.geoRef=s,y.userData.tileRef=e,y.userData.primitiveType=r.primitiveType;let b=f(r.passNames[0]);if(b>=0&&!_.transparent&&(y.renderOrder=Math.min(b,Bo)),r.batchedFrom!=null&&r.batchedFrom>1){y.userData.isBatched=!0,y.userData.batchedCount=r.batchedFrom;let t=new Map;for(let n of r.geoNames){let r=e.geoPackage[n];if(r?.pickInfo)for(let e of Object.values(r.pickInfo))typeof e.batchId==`number`&&e.batchId>=0&&t.set(e.batchId,r)}t.size>0&&(y.userData.geoByBatchId=t)}a.add(y),o.push(y),c.meshes++,r.primitiveType===4&&(c.triangles+=r.indexCount/3)}a.children.length||c.skipped.push(`tile 无可用几何`);let _=0;for(let e of o){let t=e,n=t.geometry;if(n){if(n.attributes)for(let e of Object.values(n.attributes))e&&e.array&&(_+=e.array.byteLength);n.index&&n.index.array&&(_+=n.index.array.byteLength)}if(t.isInstancedMesh){let e=t;e.instanceMatrix&&e.instanceMatrix.array&&(_+=e.instanceMatrix.array.byteLength),e.instanceColor&&e.instanceColor.array&&(_+=e.instanceColor.array.byteLength)}}return c.memory=_,a.userData.textureKeys=s,{group:a,stats:c,objects:o,textureKeys:s}}var Fo,Io,Lo,Ro,zo,Bo,Vo=c((()=>{Gi(),ja(),Fa(),no(),gi(),gn(),lo(),bo(),yn(),Fo=null,Io=null,Lo=new t.Color(1920611),Ro=1e3,zo=1001,Bo=999}));gi(),b();function Ho(e){return e.slice(0,e.lastIndexOf(`/`)+1)}function Uo(e){if(!e)return e;try{let t=typeof document<`u`?document.baseURI:void 0;return t?new URL(e,t).href:new URL(e).href}catch{return e}}function Wo(e,t){if(!t)return null;try{return Go(new URL(t,e).href)}catch{return Go(`${Ho(e)}${t}`)}}function Go(e){if(!/[+ ]/.test(e))return e;let t=e.indexOf(`#`),n=t<0?``:e.slice(t),r=t<0?e:e.slice(0,t),i=r.indexOf(`?`),a=i<0?r:r.slice(0,i),o=i<0?``:r.slice(i);return`${a.replace(/\+/g,`%2B`).replace(/ /g,`%20`)}${o}${n}`}var Ko=110540,qo=111320;function Jo(e){if(!e||typeof e!=`object`)return null;let t=e;if(![t.left,t.bottom,t.right,t.top].every(e=>typeof e==`number`&&Number.isFinite(e)))return null;let{left:n,bottom:r,right:i,top:a}=t;return Math.abs(n)>180||Math.abs(i)>180||Math.abs(a)>90||Math.abs(r)>90||i===n&&a===r?null:{left:n,bottom:r,right:i,top:a}}function Yo(e,t){if(!t)return null;let n=t.replace(/\.(osgb|s3mb|s3m)$/i,`.s3m`),r=e.split(`/`),i=r.pop()??``,a=r.pop()??``,o=r.lastIndexOf(`datas`);return!i||!a||o<1?Wo(Ho(e),n):Go(`${r[r.length-1]===`path`&&r[r.length-2]===`data`?`${r.join(`/`)}/${a}`:`${r.join(`/`)}/data/path/${a}`}/${n}`)}function Xo(e){let t=e.trim();if(t.startsWith(`<`)){let e=e=>{let n=RegExp(`<(?:[a-zA-Z0-9_-]+:)?${e}[^>]*>([^<]+)<\\/`,`i`).exec(t);return n?n[1].trim():null},n=t=>parseFloat(e(t)??``),r=n(`X`)||0,i=n(`Y`)||0,a=n(`Z`)||0,o=n(`Left`),s=n(`Right`),c=n(`Top`),l=n(`Bottom`);if(![o,s,c,l].every(Number.isFinite)){let e=n(`MinX`),t=n(`MaxX`),a=n(`MinY`),u=n(`MaxY`);if([e,t,a,u].every(Number.isFinite)&&r&&i){let n=qo*Math.cos(i*Math.PI/180);n>1e-6&&(o=r+e/n,s=r+t/n,l=i+a/Ko,c=i+u/Ko)}}let u=t.matchAll(/<(?:[a-zA-Z0-9_-]+:)?FileName[^>]*>([^<]+)<\//gi),d=[];for(let e of u)d.push({url:e[1].trim()});let f=n(`MinHeight`),p=n(`MaxHeight`);return{fileType:e(`FileType`)??void 0,fileExtentName:e(`FileExtentName`)??void 0,cacheType:e(`Type`)??void 0,position:{x:r,y:i,z:a,units:`Degree`},geoBounds:{left:o,right:s,top:c,bottom:l},heightRange:Number.isFinite(f)||Number.isFinite(p)?{min:f,max:p}:void 0,rootTiles:d,tiles:d}}return JSON.parse(t)}function Zo(e){return!e||typeof e!=`object`?`model`:String(e.fileExtentName??``).trim().toLowerCase()===`terrainz`?`terrain`:String(e.cacheType??``).trim().toLowerCase()===`image`?`imagery`:`model`}function Qo(e){let t=[];return e.fileExtentName&&t.push(`FileExtentName=${e.fileExtentName}`),e.cacheType&&t.push(`Type=${e.cacheType}`),e.fileType&&t.push(`fileType=${e.fileType}`),e.dataType&&t.push(`dataType=${e.dataType}`),t.length?t.join(`, `):`无类型标记`}function $o(e){let t=/\/datas\/([^/?#]+)/i.exec(e);if(!t)return e;try{return decodeURIComponent(t[1])}catch{return t[1]}}function es(e){if(!e)return 0;if(Array.isArray(e.mipmaps)&&e.mipmaps.length>0){let t=0;for(let n of e.mipmaps)n?.data?.byteLength&&(t+=n.data.byteLength);if(t>0)return t}let t=e.image;if(!t)return 0;if(t.data&&typeof t.data.byteLength==`number`)return t.data.byteLength;let n=t.width??0,r=t.height??0;if(n>0&&r>0){let t=e.generateMipmaps?1.3333333333333333:1;return Math.round(n*r*4*t)}return 0}function ts(e){let t=0;return e?(e.traverse?.(e=>{let n=e.geometry;if(n){if(n.attributes)for(let e of Object.values(n.attributes))e?.array?.byteLength&&(t+=e.array.byteLength);n.index?.array?.byteLength&&(t+=n.index.array.byteLength)}e.isInstancedMesh&&(e.instanceMatrix?.array?.byteLength&&(t+=e.instanceMatrix.array.byteLength),e.instanceColor?.array?.byteLength&&(t+=e.instanceColor.array.byteLength))}),t):0}var ns=class{get heightRange(){let e=this.config?.heightRange;return e&&typeof e.min==`number`&&typeof e.max==`number`?{min:e.min,max:e.max}:null}shouldBakeMercator(e){return this._bakeMercator===void 0?(e??this.rootRadius??0)>hi:this._bakeMercator}constructor(e){y(this,`configUrl`,void 0),y(this,`config`,null),y(this,`_blockTileIndex`,null),y(this,`anchor`,{lon:0,lat:0,height:0}),y(this,`rootUrls`,[]),y(this,`nodes`,new Map),y(this,`failed`,new Set),y(this,`textureCache`,new Map),y(this,`maxImageCache`,void 0),y(this,`_textureRefs`,new Map),y(this,`_tileTextureKeys`,new Map),y(this,`pending`,new Set),y(this,`atlasLod`,void 0),y(this,`atlasLodCache`,new Map),y(this,`_groupCache`,new Map),y(this,`externalAtlasCache`,new Map),y(this,`leafRequestCache`,new Map),y(this,`_leafPending`,new Map),y(this,`atlasUpgraded`,new Set),y(this,`atlasUpgradeSkipped`,new Map),y(this,`stats`,{tiles:0,loading:0,failed:0,meshes:0,vertices:0,triangles:0,datasets:1,drawCalls:0,programs:0,textures:0,geometries:0,degradations:[]}),y(this,`maxConcurrent`,void 0),y(this,`maxTiles`,void 0),y(this,`maxTriangles`,void 0),y(this,`maxMemory`,void 0),y(this,`lodRangeScale`,void 0),y(this,`lodTransition`,void 0),y(this,`fallbackOffset`,void 0),y(this,`primaryNodes`,new Set),y(this,`fallbackNodes`,new Set),y(this,`_onTile`,void 0),y(this,`_onTileRemoved`,void 0),y(this,`_onError`,void 0),y(this,`_onProgress`,void 0),y(this,`_maxRetries`,void 0),y(this,`authenticate`,void 0),y(this,`_unsupported`,void 0),y(this,`_retryCount`,new Map),y(this,`_retryAt`,new Map),y(this,`_parentOf`,new Map),y(this,`_frame`,0),y(this,`_permanentReported`,!1),y(this,`hardCap`,96),y(this,`isS3MV1`,!1),y(this,`_buildTile`,void 0),y(this,`_bakeMercator`,void 0),y(this,`rootRadius`,void 0),y(this,`_polygonOffset`,void 0),y(this,`_materialQuality`,void 0),y(this,`_colorPipeline`,void 0),y(this,`_textureOptions`,void 0),y(this,`_uniforms`,void 0),y(this,`_workerClient`,void 0),y(this,`_useWorker`,void 0),y(this,`_queue`,[]),y(this,`_active`,0),this.configUrl=e.configUrl,this.lodRangeScale=e.lodRangeScale??3,this.lodTransition=e.lodTransition??`binary`,this.fallbackOffset={factor:e.fallbackOffset?.factor??1,units:e.fallbackOffset?.units??2},this._onTile=e.onTile??(()=>{}),this._onTileRemoved=e.onTileRemoved??(()=>{}),this._onError=e.onError??(e=>console.warn(e)),this._onProgress=e.onProgress??(()=>{}),this._maxRetries=Math.max(0,e.maxRetries??2),this.authenticate=e.authenticate,this._unsupported=e.unsupported??`warn`,this._buildTile=e.buildTile??null,this._bakeMercator=e.bakeMercator,this._polygonOffset=e.polygonOffset,this._materialQuality=e.materialQuality,this._colorPipeline=e.colorPipeline,this._textureOptions=e.textureOptions,this._uniforms=e.uniforms??null,this._useWorker=e.useWorker!==!1,this.maxConcurrent=e.maxConcurrent??4,this.maxTiles=e.maxTiles??64,this.maxTriangles=e.maxTriangles??1/0,this.maxMemory=Number.isFinite(e.maxMemory)&&e.maxMemory>0?e.maxMemory:1/0,this.maxImageCache=e.maxImageCache??128,this.hardCap=this.maxTiles+Math.max(8,Math.ceil(this.maxTiles*.5)),this.atlasLod=e.atlasLod!==!1}async init(){this.configUrl=Uo(this.configUrl);let e=await Xt(this.configUrl,this.authenticate,`config`);if(!e.ok)throw Error(`配置读取失败 ${e.status} ${this.configUrl}`);let t=Xo(await e.text());this.config=t;let n=Zo(t);if(n!==`model`){let e=Error(`数据集 ${$o(this.configUrl)} 是${n===`terrain`?`地形`:`影像`}缓存(${Qo(t)}),本层仅支持模型类 S3M 数据集`);throw e.datasetKind=n,e}this.anchor=this._resolveAnchor(t);let r=t.rootTiles??t.tiles??[];if(!r.length)throw Error(`配置中缺少 root tile(${Qo(t)})——若是地形/影像数据集,或 configUrl 误指向 …/datas 数据集清单,本层仅支持模型类 S3M 数据集`);this.rootUrls.length=0;for(let e of r){let t=Wo(this.configUrl,e.url);t&&this.rootUrls.push(t)}if(this.isS3MV1=/OSGB/i.test(String(t.fileType??``))||/OSGB/i.test(String(t.dataType??``))||this.rootUrls.length>0&&this.rootUrls.every(e=>/\.s3m($|\?)/i.test(e)),this.rootUrls.every(e=>/\.s3mblock($|\?)/i.test(e))){this._blockTileIndex=new Set(this.rootUrls);for(let e of r){let t=Wo(this.configUrl,e.url);t&&this._blockTileIndex.add(t)}}await this._load(this.rootUrls[0]);for(let e of this.rootUrls.slice(1))this._enqueue(e);return this}_enqueue(e,t){if(!e||(t&&this._parentOf.set(e,t),this.nodes.has(e)||this.pending.has(e)||this.failed.has(e))||this._queue.includes(e))return;let n=this._retryAt.get(e);n!==void 0&&performance.now()<n||this.nodes.size+this.pending.size+this._queue.length>=this.hardCap||(this._queue.push(e),this._pump())}registerTileTextures(e,t){this._tileTextureKeys.set(e,t);let n=this.nodes.get(e);n&&(n.textureKeys=t);for(let e of t)this._textureRefs.set(e,(this._textureRefs.get(e)??0)+1)}_evictTileNode(e){this.nodes.delete(e.url),e.group?.parent?.remove(e.group),this._onTileRemoved(e),this._parentOf.delete(e.url),this.stats.tiles=Math.max(0,this.stats.tiles-1),e.stats&&(this.stats.meshes=Math.max(0,this.stats.meshes-(e.stats.meshes??0)),this.stats.vertices=Math.max(0,this.stats.vertices-(e.stats.vertices??0)),this.stats.triangles=Math.max(0,this.stats.triangles-(e.stats.triangles??0)));let t=e.textureKeys??this._tileTextureKeys.get(e.url)??e.group?.userData?.textureKeys;if(this._tileTextureKeys.delete(e.url),t?.length)for(let e of t){let t=(this._textureRefs.get(e)??1)-1;if(t<=0){this._textureRefs.delete(e);let t=this.textureCache.get(e);t&&(t.dispose?.(),this.textureCache.delete(e))}else this._textureRefs.set(e,t)}}putExternalAtlas(e,t){if(this.externalAtlasCache.size>=this.maxImageCache&&!this.externalAtlasCache.has(e)){let e=this.externalAtlasCache.keys().next().value;e!==void 0&&this.externalAtlasCache.delete(e)}Map.prototype.set.call(this.externalAtlasCache,e,t)}getExternalAtlas(e){return this.externalAtlasCache.get(e)}putLeafRecords(e,t){if(this.leafRequestCache.size>=this.maxImageCache&&!this.leafRequestCache.has(e)){let e=this.leafRequestCache.keys().next().value;e!==void 0&&this.leafRequestCache.delete(e)}Map.prototype.set.call(this.leafRequestCache,e,t)}getLeafRecords(e){return this.leafRequestCache.get(e)}_evictOne(e=!1){let t=this._pickVictim(!0,e)??this._pickVictim(!1,e);if(!t)return!1;let n=t.parentUrl??this._parentOf.get(t.url),r=t.childUrls??(t.childUrl?[t.childUrl]:[]);r.some(e=>e!==t.url&&this.nodes.has(e)),this._evictTileNode(t);let i=r.filter(e=>e!==t.url&&this.nodes.has(e));if(i.length){for(let e of i){let t=this.nodes.get(e);t&&(t.parentUrl=n??void 0,n?this._parentOf.set(e,n):this._parentOf.delete(e))}if(n){let e=this.nodes.get(n);if(e){let n=new Set(e.childUrls??[]);e.childUrl&&n.add(e.childUrl),n.delete(t.url);for(let e of i)n.add(e);e.childUrls=[...n],e.childUrl=e.childUrls[0]??null}}}return!0}_residentTriangles(){let e=0;for(let t of this.nodes.values())e+=t.stats?.triangles??0;return e}setMaxTriangles(e){this.maxTriangles=e>0?e:1/0}setMaxMemory(e){this.maxMemory=Number.isFinite(e)&&e>0?e:1/0}setMaterialQuality(e){this._materialQuality=e}setRenderProfile(e){e.colorPipeline!==void 0&&(this._colorPipeline=e.colorPipeline),e.textureOptions!==void 0&&(this._textureOptions=e.textureOptions)}residentMemory(){return this._residentGeometryBytes()+this._residentTextureBytes()}_residentGeometryBytes(){let e=0;for(let t of this.nodes.values())t.stats&&typeof t.stats.memory==`number`?e+=t.stats.memory:t.group&&(e+=ts(t.group));return e}_residentTextureBytes(){let e=0;for(let t of this.textureCache.values())e+=es(t);return e}_trimBudget(){let e=!1,t=0,n=()=>this.nodes.size+this.pending.size>this.maxTiles,r=()=>Number.isFinite(this.maxTriangles)&&this._residentTriangles()>this.maxTriangles,i=()=>Number.isFinite(this.maxMemory)&&this.residentMemory()>this.maxMemory,a=this.nodes.size+this.maxTiles+16;for(;(n()||r()||i())&&t++<=a&&this._evictOne(this.nodes.size+this.pending.size>this.hardCap);)e=!0;return e}_pickVictim(e,t=!1){let n=null;for(let r of this.nodes.values()){let i=r.childUrls??(r.childUrl?[r.childUrl]:[]);if((i.length>0&&i.some(e=>e!==r.url&&this.nodes.has(e)))!==e||!t&&r.group.visible&&(this.lodTransition===`incremental`||!i.some(e=>{let t=this.nodes.get(e);return!!t&&t.group.visible})))continue;if(!n){n=r;continue}let a=+!!r.group.visible,o=+!!n.group.visible;if(a!==o){a<o&&(n=r);continue}let s=r.lastSeen??-1,c=n.lastSeen??-1;(s<c||s===c&&(r.distance??0)>(n.distance??0))&&(n=r)}return n}retryFailed(){let e=this.failed.size;return this.failed.clear(),this._retryCount.clear(),this._retryAt.clear(),e}_pump(){for(;this._active<this.maxConcurrent&&this._queue.length;){let e=this._queue.shift();this._active++,this._load(e).finally(()=>{this._active--,this._pump()})}}_resolveAnchor(e){let t=e.position,n=t?.point3D??t,r=!!n&&Number.isFinite(n.x)&&Number.isFinite(n.y),i=Jo(e.geoBounds),a=i?(i.left+i.right)/2:void 0,o=i?(i.bottom+i.top)/2:void 0,s=n?.z??0;if(!r)return{lon:a??0,lat:o??0,height:0};if((t?.units??t?.unit??`Degree`)!==`Degree`)return{lon:n.x,lat:n.y,height:s};let c=a===void 0?0:Math.abs(n.x-a),l=o===void 0?0:Math.abs(n.y-o);return c>.5||l>.5?(console.warn(`[s3m] position 与 geoBounds 不一致,改用 geoBounds 中心作为锚点`,{position:n,geoBounds:i}),{lon:a,lat:o,height:s}):{lon:n.x,lat:n.y,height:s}}_pickLod(e){let t=e.groupNode?.pageLods??[];return t.length?t.find(e=>e.childTile&&e.rangeValue>0)??t[0]:null}async _builder(){if(!this._buildTile){let e=await Promise.resolve().then(()=>(Vo(),xo));this._buildTile=e.buildTileObjects}return this._buildTile}async _parseClassicTile(e){if(this._useWorker&&this._workerClient===void 0&&(this._workerClient=En()),this._workerClient)try{return await this._workerClient.parseTile(e,!0,!0,this.config?.vertexAttributeDescript)}catch(e){if(e instanceof Cn)this._workerClient=null;else throw e}return{tile:await Vt(e,{vertexAttributeDescript:this.config?.vertexAttributeDescript})}}_rememberGroups(e,t){for(this._groupCache.delete(e),this._groupCache.set(e,t);this._groupCache.size>24;){let e=this._groupCache.keys().next().value;if(e===void 0)break;this._groupCache.delete(e)}}async _fillExternalAtlases(e,t){let n=e,r=n.texturePackage;if(!r)return;let i=Xr(n),a=!1,o=new Map,s=new Map,c=[];for(let[e,t]of Object.entries(r)){let n=si(t.requestNames);if(n.names.length){o.set(e,{tex:t,plan:n});for(let[e,t]of n.packGroups){let n=t.filter(e=>!this.leafRequestCache.has(e));if(!n.length)continue;let r=s.get(e)??[];for(let e of n)r.includes(e)||r.push(e);s.set(e,r)}for(let e of n.plain)!this.leafRequestCache.has(e)&&!c.includes(e)&&c.push(e)}}let l=[];for(let[e,n]of s){let r=null,i=()=>r??(r=this._fetchLeafPack(t,e,n));for(let e of n)l.push(this._ensureLeafFetch(e,i))}for(let e of c)l.push(this._ensureLeafFetch(e,()=>this._fetchLeafFile(t,e)));l.length&&await Promise.all(l);for(let[e,{tex:t,plan:n}]of o){let r=new Map;for(let e of n.names){let t=this.leafRequestCache.get(e);if(t)for(let n of t)r.set(n.id,{source:e,image:n})}let i=ci(t,r);if(i){let n=t;n.composed=!0,n.leafSig=i.sig,n.flipY=!1,t.data=i.data,t.compressType=0,t.pixelFormat=28,t.width=i.width,t.height=i.height,t.rectScale=1,this.atlasUpgraded.add(e),a=!0,(i.missing.length||i.mismatched.length)&&console.warn(`[s3m] leaf 图集部分精灵异常:`,e,{missing:i.missing,mismatched:i.mismatched});continue}let o=!!t.data,s=n=>{if(!o){let r=t.width/t.height,i=n.width/n.height;return Math.abs(i/r-1)<=.02||(this.atlasUpgradeSkipped.set(e,`aspect(no-baseline) ${t.width}x${t.height} vs ${n.width}x${n.height}`),!1)}let r=fi(t,n);return r.ok?!0:(this.atlasUpgradeSkipped.set(e,`${r.reason} aspectΔ=${(r.aspectDelta*100).toFixed(1)}% scale=${r.scale} err=${Number.isNaN(r.meanAbsError)?`n/a`:r.meanAbsError.toFixed(1)}`),!1)},c=n=>{let r=t;r.composed=!1,r.leafSig=void 0,r.flipY=!0,t.data=n.data,t.compressType=n.compressType,t.pixelFormat=n.pixelFormat,t.rectScale=t.width>0?n.width/t.width:1,t.width=n.width||t.width,t.height=n.height||t.height,this.atlasUpgraded.add(e),a=!0},l=this.externalAtlasCache.get(e);if(l!==null){if(l===void 0){l=null;for(let e of n.plain){let t=this.leafRequestCache.get(e);if(t?.length){l=t[0];break}}this.putExternalAtlas(e,l)}l?s(l)&&c(l):this.atlasUpgradeSkipped.has(e)||this.atlasUpgradeSkipped.set(e,`no usable external image(请求失败或只拿到子精灵)`)}}(i||a)&&Zr(n)}_ensureLeafFetch(e,t){if(this.leafRequestCache.has(e))return Promise.resolve();let n=this._leafPending.get(e);if(n)return n;let r=t().finally(()=>this._leafPending.delete(e));return this._leafPending.set(e,r),r}async _fetchLeafPack(e,t,n){let r=Wo(Ho(e),`${n[0]}.texblock?extratiles=${n.join(`;`)}`);try{if(!r)throw Error(`无法拼出 URL`);let e=await Xt(r,this.authenticate,`texblock`);if(!e.ok)throw Error(`HTTP ${e.status}`);let t=await ei(await e.arrayBuffer());if(t.length!==n.length)throw Error(`pack 段数 ${t.length} ≠ 请求名 ${n.length}`);n.forEach((e,n)=>this.putLeafRecords(e,t[n]))}catch(e){console.warn(`[s3m] leaf pack 请求失败:`,r,e);for(let e of n)this.leafRequestCache.has(e)||this.putLeafRecords(e,null)}}async _fetchLeafFile(e,t){let n=Wo(Ho(e),`${t}.texblock`);try{if(!n)throw Error(`无法拼出 URL`);let e=await Xt(n,this.authenticate,`texblock`);if(!e.ok)throw Error(`HTTP ${e.status}`);let r=(await ei(await e.arrayBuffer())).flat();this.putLeafRecords(t,r)}catch(e){console.warn(`[s3m] leaf texblock 请求失败:`,n,e),this.leafRequestCache.has(t)||this.putLeafRecords(t,null)}}async _upgradeAtlasLod(e,t){}_noteDegradations(e){let t=e.degradations;if(!t?.length)return;let n=Ut(t,this.stats.degradations,this._unsupported);this.stats.degradations=n.known;for(let e of n.messages)console.warn(e);if(n.error)throw n.error}async _load(e){if(!(this.nodes.has(e)||this.pending.has(e)||this.failed.has(e))){this.pending.add(e),this.stats.loading++;try{let t=e.indexOf(`#`),n=t>=0?e.slice(0,t):e,r=t>=0&&Number(e.slice(t+1))||0,i=/\.s3mblock($|\?)/i.test(n),a,o,s=[],c=this._groupCache.get(n);if(c)s=c.names,a=c.tiles[r]??c.tiles[0];else{let e=await Xt(n,this.authenticate,`tile`);if(!e.ok)throw Error(`HTTP ${e.status} 加载瓦片失败: ${n}`);if((e.headers.get(`content-type`)||``).includes(`text/html`))throw Error(`瓦片请求返回了 HTML 页面(通常为 404/500 服务端拦截): ${n}`);let t=await e.arrayBuffer();if(i){let e=await li(t);this._rememberGroups(n,e),s=e.names,a=e.tiles[r]??e.tiles[0]}else{let e=await this._parseClassicTile(t);a=e.tile,o=e.geometry}}i&&(await this._fillExternalAtlases(a,n),await this._upgradeAtlasLod(a,n)),this._noteDegradations(a);let l=this._pickLod(a);this.rootRadius===void 0&&l?.boundingSphere?.radius&&(this.rootRadius=l.boundingSphere.radius);let u=this.shouldBakeMercator(l?.boundingSphere?.radius),d=await(await this._builder())(a,{textureCache:this.textureCache,uniforms:this._uniforms,assembled:o,polygonOffset:this._polygonOffset,materialQuality:this._materialQuality,colorPipeline:this._colorPipeline,textureOptions:this._textureOptions,bakeMercator:u,tileAnchor:this.anchor,tileCenter:l?.boundingSphere?.center}),{group:f,stats:p}=d,m=d.textureKeys??f.userData?.textureKeys??Object.keys(a.textures??{});this.registerTileTextures(e,m);let h=this._pickLod(a),g=[];for(let t of a.groupNode?.pageLods??[]){let r=String(t.childTile??``).replace(/\.s3mblock$/i,``),a=i&&r?s.indexOf(r):-1,o=a>=0?`${n}#${a}`:this.isS3MV1?Yo(e,t.childTile):Wo(Ho(e),t.childTile);o&&o!==e&&!g.includes(o)&&g.push(o)}let _={url:e,tile:a,group:f,sphere:h?.boundingSphere??null,rangeValue:h?.rangeValue??0,rangeMode:h?.rangeMode??1,childUrl:g[0]??(this.isS3MV1?Yo(e,h?.childTile):Wo(Ho(e),h?.childTile)),childUrls:g,parentUrl:this._parentOf.get(e),state:`ready`,...p.splatSigma?{splatSigma:p.splatSigma}:{},...p.splatCount?{splatCount:p.splatCount}:{},stats:{meshes:p.meshes??0,vertices:p.vertices??0,triangles:p.triangles??0,memory:p.memory??ts(f)}};this.nodes.set(e,_),this.stats.tiles++,this.stats.meshes+=p.meshes??0,this.stats.vertices+=p.vertices??0,this.stats.triangles+=p.triangles??0,this._onTile(_)}catch(t){let n=t?.permanent===!0,r=(this._retryCount.get(e)??0)+1;if(this._retryCount.set(e,r),!n&&r<=this._maxRetries)this._retryAt.set(e,performance.now()+800*r);else{this.stats.failed++,this.failed.add(e),this._retryAt.delete(e);let t=this._parentOf.get(e),n=t?this.nodes.get(t):void 0;n?.childUrls&&(n.childUrls=n.childUrls.filter(t=>t!==e),n.childUrl=n.childUrls[0]??null)}n?this._permanentReported||(this._permanentReported=!0,this._onError(t)):this._onError(t)}finally{this.pending.delete(e),this.stats.loading--,this._onProgress(this.stats)}}}update(e,t,n,r){this._frame++;let i=!1;for(let t of this.nodes.values()){var a;if(!t.sphere){t.lastSeen=this._frame,t.needRefine=!1;continue}let o=t.sphere.center,s=o.x-e[0],c=o.y-e[1],l=o.z-e[2],u=Math.sqrt(s*s+c*c+l*l)||1e-6;t.distance=u;let d,f=t.rangeMode===0;d=f?u:n*.5/Math.tan(Math.PI/8)*(t.sphere.radius/u)*2;let p=this.lodRangeScale>0?this.lodRangeScale:1,m=t.rangeValue*p;(f?u<m*2:d>m*.5)&&(t.lastSeen=this._frame);let h=t.childUrls??(t.childUrl?[t.childUrl]:[]),g=t.needRefine?f?1.08:.92:1,_=t.splatSigma&&t.sphere?Sn({splats:t.splatCount??t.stats?.vertices??0,radius:t.sphere.radius,distance:u,sigma:t.splatSigma,screenHeight:n,hasChild:h.length>0}):null,v=_?_.needRefine:h.length>0&&(f?d<m*g:d>m*g);v&&r&&!r(o,t.sphere.radius,t)&&(v=!1),t.needRefine=v;let y=(a=globalThis).__S3M_LOD_SEEN??(a.__S3M_LOD_SEEN=new Set);if(globalThis.__S3M_LOD_DEBUG&&!y.has(t.url)&&y.size<260&&(y.add(t.url),console.log(`[LOD]`,JSON.stringify({url:t.url.split(`/`).pop(),mode:t.rangeMode,rangeValue:t.rangeValue,radius:t.sphere.radius,dist:+u.toFixed(1),metric:+d.toFixed(1),threshold:+m.toFixed(1),needRefine:v,childUrls:h.map(e=>e.split(`/`).pop()),parent:t.parentUrl?t.parentUrl.split(`/`).pop():null}))),v)for(let e of h)this.failed.has(e)||this.nodes.has(e)||this.pending.has(e)||(this._enqueue(e,t.url),i=!0)}let o=new Set,s=new Set(this.rootUrls);for(let[e,t]of this.nodes){let n=t.parentUrl??this._parentOf.get(e);n&&this.nodes.has(n)||s.add(e)}if(this.lodTransition===`incremental`)this._updateVisibilityIncremental(s,o)&&(i=!0);else{for(let e of s)this._updateNodeVisibility(e,!0,o)&&(i=!0);this.primaryNodes.clear();for(let[e,t]of this.nodes)t.group.visible&&this.primaryNodes.add(e);this.fallbackNodes.clear()}for(let[e,t]of this.nodes)o.has(e)||(t.group.visible&&(t.group.visible=!1,i=!0),this.lodTransition===`incremental`&&this._restoreNodePolygonOffset(t));this._trimBudget()&&(i=!0);let c=!1;for(let e of this.nodes.values())if(e.group.visible){c=!0;break}if(!c&&this.nodes.size>0)for(let e of this.nodes.values())!(e.childUrls??(e.childUrl?[e.childUrl]:[])).some(t=>{let n=this.nodes.get(t);return!!n&&n!==e&&n.group.visible})&&!e.group.visible&&(e.group.visible=!0,i=!0);return i}_updateNodeVisibility(e,t,n){let r=this.nodes.get(e);if(!r||n.has(e))return!1;n.add(e);let i=!1,a=r.childUrls??(r.childUrl?[r.childUrl]:[]);if(!t){r.group.visible&&(r.group.visible=!1,i=!0);for(let e of a)this._updateNodeVisibility(e,!1,n)&&(i=!0);return i}let o=a.length>0,s=a.filter(e=>this.nodes.has(e)),c=a.every(e=>this.nodes.has(e)||this.failed.has(e));if(r.needRefine&&o&&s.length>0&&c){r.group.visible&&(r.group.visible=!1,i=!0);for(let e of a)this._updateNodeVisibility(e,!0,n)&&(i=!0)}else{r.group.visible||(r.group.visible=!0,i=!0);for(let e of a)this._updateNodeVisibility(e,!1,n)&&(i=!0)}return i}getLodTransition(){return this.lodTransition}setLodTransition(e){if(this.lodTransition!==e&&(this.lodTransition=e,e===`binary`)){for(let e of this.nodes.values())this._restoreNodePolygonOffset(e);this.fallbackNodes.clear()}}_applyNodeFallbackPolygonOffset(e,t){let n=this.fallbackOffset.factor,r=Math.max(2,(10-Math.min(t,8))*this.fallbackOffset.units),i=!1;return e.group.traverse(e=>{let t=e;if((t.isMesh||t.isPoints||t.isLine)&&t.material){let e=Array.isArray(t.material)?t.material:[t.material];for(let t of e){if(!t)continue;t.userData||(t.userData={}),t.userData._basePolygonOffset||(t.userData._basePolygonOffset={polygonOffset:t.polygonOffset===!0,factor:t.polygonOffsetFactor??0,units:t.polygonOffsetUnits??0});let e=t.userData._basePolygonOffset,a=e.factor+n,o=e.units+r;(t.polygonOffset!==!0||t.polygonOffsetFactor!==a||t.polygonOffsetUnits!==o)&&(t.polygonOffset=!0,t.polygonOffsetFactor=a,t.polygonOffsetUnits=o,i=!0)}}}),i}_restoreNodePolygonOffset(e){let t=!1;return e.group.traverse(e=>{let n=e;if((n.isMesh||n.isPoints||n.isLine)&&n.material){let e=Array.isArray(n.material)?n.material:[n.material];for(let n of e)if(n?.userData?._basePolygonOffset){let e=n.userData._basePolygonOffset;(n.polygonOffset!==e.polygonOffset||n.polygonOffsetFactor!==e.factor||n.polygonOffsetUnits!==e.units)&&(n.polygonOffset=e.polygonOffset,n.polygonOffsetFactor=e.factor,n.polygonOffsetUnits=e.units,t=!0)}}}),t}_updateVisibilityIncremental(e,t){let n=new Set,r=new Set,i=new Map,a=(e,o)=>{if(t.has(e))return;t.add(e),i.set(e,o);let s=this.nodes.get(e);if(!s)return;let c=s.childUrls??(s.childUrl?[s.childUrl]:[]),l=c.length>0,u=c.filter(e=>this.nodes.has(e)),d=c.filter(e=>!this.nodes.has(e)&&!this.failed.has(e));if(s.needRefine&&l&&u.length>0){d.length>0&&r.add(e);for(let e of u)a(e,o+1)}else n.add(e)};for(let t of e)a(t,0);let o=!1;for(let[e,a]of this.nodes)if(t.has(e)){if(n.has(e)){a.group.visible||(a.group.visible=!0,o=!0);let t=100+(i.get(e)??0);a.group.renderOrder!==t&&(a.group.renderOrder=t,o=!0),this._restoreNodePolygonOffset(a)&&(o=!0)}else if(r.has(e)){a.group.visible||(a.group.visible=!0,o=!0);let t=i.get(e)??0,n=t;a.group.renderOrder!==n&&(a.group.renderOrder=n,o=!0),this._applyNodeFallbackPolygonOffset(a,t)&&(o=!0)}else a.group.visible&&(a.group.visible=!1,o=!0),this._restoreNodePolygonOffset(a)&&(o=!0)}this.primaryNodes.clear();for(let e of n)this.primaryNodes.add(e);this.fallbackNodes.clear();for(let e of r)this.fallbackNodes.add(e);return o}dispose(){this._workerClient?.dispose();for(let e of this.nodes.values())e.group.traverse(e=>{let t=e;t.geometry?.dispose?.(),Array.isArray(t.material)?t.material.forEach(e=>e.dispose?.()):t.material?.dispose?.()});for(let e of this.textureCache.values())e.dispose?.();this.textureCache.clear(),this.nodes.clear()}};Vo();var rs={ambientIntensity:.4,hemisphereIntensity:.8,keyLightIntensity:1,fillLightIntensity:.35},is={ambientIntensity:.12,hemisphereIntensity:.2,keyLightIntensity:1.95,fillLightIntensity:.15},as={default:rs,supermap:is};function os(e){return e&&Object.prototype.hasOwnProperty.call(as,e)?as[e]:rs}b();var ss={ambientIntensity:.4,ambientColor:16777215,hemisphereIntensity:.8,hemisphereColor:16777215,hemisphereGroundColor:11976907,keyLightIntensity:1,keyLightColor:16777215,fillLightIntensity:.35,fillLightColor:16777215,mode:`headlamp`,azimuth:150,altitude:50},cs=class{get envRT(){return this._envRT}set envRT(e){this._envRT=e}constructor(e){y(this,`ctx`,void 0),y(this,`ambient`,null),y(this,`hemi`,null),y(this,`key`,null),y(this,`fill`,null),y(this,`_state`,void 0),y(this,`_envRT`,null),this.ctx=e,this._state={...ss};let t=e.options;t.lightingPreset&&t.lightingPreset!=="default"&&(Object.assign(this._state,os(t.lightingPreset)),this.applyColorPipeline(t.lightingPreset,!0)),t.light&&Object.assign(this._state,t.light)}_create(){this.ambient=new t.AmbientLight(this._state.ambientColor,this._state.ambientIntensity),this.hemi=new t.HemisphereLight(this._state.hemisphereColor,this._state.hemisphereGroundColor,this._state.hemisphereIntensity),this.key=new t.DirectionalLight(this._state.keyLightColor,this._state.keyLightIntensity),this.fill=new t.DirectionalLight(this._state.fillLightColor,this._state.fillLightIntensity),this.update()}addToScene(){let e=this.ctx.scene();e&&(this.ambient||this._create(),e.add(this.ambient,this.hemi,this.key,this.fill))}get created(){return this.ambient!==null}_applyOptions(){let e=this._state;this.ambient&&(this.ambient.intensity=e.ambientIntensity,this.ambient.color.set(e.ambientColor)),this.hemi&&(this.hemi.intensity=e.hemisphereIntensity,this.hemi.color.set(e.hemisphereColor),this.hemi.groundColor.set(e.hemisphereGroundColor)),this.key&&(this.key.intensity=e.keyLightIntensity,this.key.color.set(e.keyLightColor)),this.fill&&(this.fill.intensity=e.fillLightIntensity,this.fill.color.set(e.fillLightColor))}update(){if(!this.key||!this.fill)return;let e=this._state,t=e.mode===`fixed`?0:(this.ctx.getBearing?.()??0)*Math.PI/180,n=(e,n,r)=>{if(!e)return;let i=t+n*Math.PI/180,a=r*Math.PI/180,o=Math.cos(a);e.position.set(Math.sin(i)*o,Math.cos(i)*o,Math.sin(a)).multiplyScalar(1e3)};n(this.key,e.azimuth,e.altitude),n(this.fill,e.azimuth+65,Math.max(10,e.altitude-20));let r=this.ctx.uniforms?.uSunDirection;r&&r.value.copy(this.key.position).normalize()}applyColorPipeline(e,t=!1){let n=e===`supermap`;this.ctx.applyRenderProfile({colorPipeline:n?`direct`:`linear`,anisotropyCap:n?1:1/0},t)}setLightingPreset(e){Object.assign(this._state,os(e)),this.applyColorPipeline(e),this.ctx.options.lightingPreset=e,this._applyOptions(),this.update(),this.ctx.repaint()}setLight(e){let t={...e};t.mainColor!==void 0&&t.keyLightColor===void 0&&(t.keyLightColor=t.mainColor),t.mainIntensity!==void 0&&t.keyLightIntensity===void 0&&(t.keyLightIntensity=t.mainIntensity),Object.assign(this._state,t),this._applyOptions(),this.update(),this.ctx.repaint()}getLight(){return{...this._state}}setToneMapping(e,t=1){this.ctx.options.toneMapping=e,this.ctx.options.toneMappingExposure=t;let n=this.ctx.renderer();n&&(n.toneMapping=e,n.toneMappingExposure=t,this.ctx.repaint())}getToneMapping(){let e=this.ctx.renderer();return{toneMapping:e?e.toneMapping:this.ctx.options.toneMapping??t.NoToneMapping,toneMappingExposure:e?e.toneMappingExposure:this.ctx.options.toneMappingExposure??1}}async setEnvironment(e,n=1){let r=this.ctx.renderer(),i=this.ctx.scene();if(!r||!i)return;if(i.environmentIntensity=Math.max(0,n),e==null){i.environment=null,this._envRT?.dispose(),this._envRT=null,this.ctx.repaint();return}let a=typeof e==`string`,o=a?await new t.TextureLoader().loadAsync(e):e;o.mapping=t.EquirectangularReflectionMapping;let s=new t.PMREMGenerator(r);s.compileEquirectangularShader();let c=s.fromEquirectangular(o);s.dispose(),a&&o.dispose(),i.environment=c.texture,this._envRT?.dispose(),this._envRT=c,this.ctx.repaint()}dispose(){this._envRT?.dispose(),this._envRT=null}};b();var ls=class{constructor(e){y(this,`uniforms`,void 0),y(this,`_meshHeight`,new Map),y(this,`_min`,1/0),y(this,`_max`,-1/0),y(this,`_box`,new t.Box3),this.uniforms=e}get size(){return this._meshHeight.size}add(e){let t=e.geometry?.boundingBox;if(!t)return;this._box.copy(t).applyMatrix4(e.matrixWorld);let n=this._box.min.z,r=this._box.max.z;Number.isFinite(n)&&Number.isFinite(r)&&(this._meshHeight.set(e,{min:n,max:r}),n<this._min&&(this._min=n),r>this._max&&(this._max=r),this._push())}remove(e){let t=this._meshHeight.get(e);t&&(this._meshHeight.delete(e),t.min===this._min||t.max===this._max?this._recompute():this._push())}refreshAll(){if(this._meshHeight.size===0)return;let e=[...this._meshHeight.keys()];this._meshHeight.clear(),this._min=1/0,this._max=-1/0;for(let t of e)this.add(t);this._push()}clear(){this._meshHeight.clear(),this._min=1/0,this._max=-1/0}get range(){return{min:this._min,max:this._max}}_recompute(){let e=1/0,t=-1/0;for(let n of this._meshHeight.values())n.min<e&&(e=n.min),n.max>t&&(t=n.max);this._min=e,this._max=t,this._push()}_push(){let e=this._min,t=this._max;(!Number.isFinite(e)||!Number.isFinite(t)||t<=e)&&(e=0,t=100),this.uniforms.uHeightMin.value=e,this.uniforms.uHeightMax.value=t}},us=new Uint32Array,ds=new Uint32Array,fs=new Uint32Array(256),ps=new Float32Array(1),ms=new Uint32Array(ps.buffer);function hs(e){ps[0]=e;let t=ms[0];return t&2147483648?~t>>>0:(t|2147483648)>>>0}function gs(e,t,n,r){let i=r&&r.length>=t?r:new Uint32Array(t);if(t<=1)return t===1&&(i[0]=0),i;us.length<t&&(us=new Uint32Array(t)),ds.length<t&&(ds=new Uint32Array(t));let a=us,o=ds,s=n.elements,c=s[2],l=s[6],u=s[10],d=s[14];for(let n=0;n<t;n++)a[n]=hs(c*e[n*3]+l*e[n*3+1]+u*e[n*3+2]+d),i[n]=n;let f=i,p=o;for(let e=0;e<4;e++){let n=e*8;fs.fill(0);for(let e=0;e<t;e++)fs[a[f[e]]>>>n&255]++;let r=0;for(let e=0;e<256;e++){let t=fs[e];fs[e]=r,r+=t}for(let e=0;e<t;e++){let t=f[e];p[fs[a[t]>>>n&255]++]=t}let i=f;f=p,p=i}return f!==i&&i.set(f),i}var _s=[`iCenter`,`iScale`,`iQuat`,`iColor`],vs=new t.Matrix4,ys=new WeakMap,bs=new WeakMap;function xs(e,t){let n=e.geometry,r=n.getAttribute(`iCenter`);if(!r)return!1;let i=Math.min(n.instanceCount??1/0,r.count);if(i<=1)return!1;vs.multiplyMatrices(t,e.matrixWorld);let a=bs.get(r);(!a||a.length<i)&&(a=new Uint32Array(i),bs.set(r,a)),gs(r.array,i,vs,a);let o=!0;for(let e=0;e<i;e++)if(a[e]!==e){o=!1;break}if(o)return!1;for(let e of _s){let t=n.getAttribute(e);if(!t)continue;let r=t.array,o=t.itemSize,s=i*o,c=ys.get(t);(!c||c.length<s)&&(c=new r.constructor(s),ys.set(t,c));for(let e=0;e<i;e++){let t=a[e]*o,n=e*o;for(let e=0;e<o;e++)c[n+e]=r[t+e]}r.set(c.subarray(0,s)),t.needsUpdate=!0}return!0}b();var Ss=class{constructor(){y(this,`_lastView`,new t.Matrix4),y(this,`_sorted`,!1)}markDirty(){this._sorted=!1}sort(e,t){if(e&&!(this._sorted&&this._lastView.equals(e.matrixWorldInverse))){for(let n of t)n.userData.isGaussianSplat&&xs(n,e.matrixWorldInverse);this._lastView.copy(e.matrixWorldInverse),this._sorted=!0}}reset(){this._sorted=!1,this._lastView.identity()}};ja(),Xi();function Cs(){return{uResolution:{value:new t.Vector2(1,1)},uDpr:{value:1}}}var ws=`
944
944
  attribute vec3 aOther;
945
945
  attribute float aSide;
946
946
  attribute float aBatchId;
@@ -1492,4 +1492,4 @@ var S3M=(function(e,t){Object.defineProperties(e,{__esModule:{value:!0},[Symbol.
1492
1492
  }
1493
1493
  gl_FragColor = vec4(1.0);
1494
1494
  }
1495
- `}),a=new t.Mesh(e,i);a.position.set(0,0,-.02),a.renderOrder=-1e3,a.name=`s3m-ground-depth`,a.visible=!1,this.group.add(a),this._depthMesh=a,this._depthMaterial=i,this._syncUniforms()}_applyMode(){this._mesh&&(this._mesh.visible=this.mode!==`none`),this._material&&(this._material.uniforms.uMode.value=this.mode===`excavate`?2:+(this.mode===`translucent`),this._material.depthWrite=this.mode===`excavate`),this._depthMesh&&(this._depthMesh.visible=this.occlude,this._depthMaterial&&(this._depthMaterial.uniforms.uPunchPit.value=+(this.mode===`excavate`)))}update(e){e&&this.group.position.set(e.position.x,e.position.y,this.groundHeight)}setGroundHeight(e){this.groundHeight=e,this.group.position.z=e}setMode(e){this.mode=e,this._occludeExplicit||(this.occlude=e===`excavate`),this._applyMode()}setOcclude(e){this.occlude=e,this._occludeExplicit=!0,this._applyMode()}setOpacity(e){this.opacity=Math.max(0,Math.min(1,e)),this._material&&(this._material.uniforms.uOpacity.value=this.opacity)}setColors(e,t){this.color.set(e),t&&this.gridColor.set(t),this._material&&(this._material.uniforms.uColor.value=this.color,this._material.uniforms.uGridColor.value=this.gridColor)}setExcavationBounds(e){this.excavationBounds=e,this._syncUniforms()}autoFitExcavation(e){let t=1/0,n=1/0,r=-1/0,i=-1/0,a=!1;for(let o of e){let e=o.tileset?.config,s=e?.rootTiles??e?.tiles;if(Array.isArray(s))for(let e of s){let s=e.boundingBox;if(!s)continue;let c=s.center??{x:0,y:0},l=s.xExtent?.x?Math.abs(s.xExtent.x):50,u=s.yExtent?.y?Math.abs(s.yExtent.y):50,d=c.x+o.offset[0]-l,f=c.x+o.offset[0]+l,p=c.y+o.offset[1]-u,m=c.y+o.offset[1]+u;d<t&&(t=d),f>r&&(r=f),p<n&&(n=p),m>i&&(i=m),a=!0}}a&&Number.isFinite(t)&&this.setExcavationBounds([t-5,n-5,r+5,i+5])}_syncUniforms(){let e=this.excavationBounds;if(this._material){let t=this._material.uniforms;e?(t.uHasExcavation.value=1,t.uExcavationMin.value.set(e[0],e[1]),t.uExcavationMax.value.set(e[2],e[3])):t.uHasExcavation.value=0}if(this._depthMaterial){let t=this._depthMaterial.uniforms;e?(t.uHasExcavation.value=1,t.uExcavationMin.value.set(e[0],e[1]),t.uExcavationMax.value.set(e[2],e[3])):t.uHasExcavation.value=0}}dispose(){this._geom?.dispose(),this._geom=null,this._material?.dispose(),this._material=null,this._depthMaterial?.dispose(),this._depthMaterial=null,this._mesh=null,this._depthMesh=null,this.group.clear()}};Gi(),ja(),qi(),Xi(),gn(),b();function Gl(e){return e===`clear`?`clear`:e===`auto`?`auto`:`scene`}function Kl(e){let t=Array.isArray(e.material)?e.material[0]:e.material;return t?.userData?.isStyled?t:null}function ql(e){return e.isPoints===!0}function Jl(e){let t=e??1;return t<0?0:t>1?1:t}var Yl=.001,Xl=new t.Matrix4,Zl=[`opacity`,`floorHeight`,`selectOpacity`,`selectEmissive`,`selectElevation`,`dimFactor`,`texMix`,`roofThreshold`,`ambientGain`,`metalness`,`roughness`,`edgeWidth`,`edgeOpacity`,`edgeOffset`,`edgeHullWidth`,`outlineWidth`],Ql={metalness:0,roughness:.95},$l=[`colorA`,`colorB`,`colorC`,`selectColor`,`edgeColor`],eu=[`translation`,`elevation`,`opacity`,`color`,`rotation`],tu=class{get datasets(){return this._datasetManager.datasets}get sceneAnchor(){return this._datasetManager.sceneAnchor}set sceneAnchor(e){this._datasetManager.sceneAnchor=e,this._reapplyTilePlacements()}_requestRepaint(){this._onRequestRepaint()}triggerRepaint(){this._requestRepaint()}constructor(e={}){y(this,`options`,void 0),y(this,`pickable`,void 0),y(this,`onStats`,void 0),y(this,`onReady`,void 0),y(this,`onPick`,void 0),y(this,`onError`,void 0),y(this,`geo`,null),y(this,`canvas`,null),y(this,`renderer`,null),y(this,`scene`,null),y(this,`camera`,null),y(this,`picker`,null),y(this,`uniforms`,void 0),y(this,`style`,void 0),y(this,`_styleTarget`,void 0),y(this,`outlineMaterial`,void 0),y(this,`lineShared`,void 0),y(this,`edgeMaterial`,void 0),y(this,`selectionEdgeMaterial`,void 0),y(this,`_edges`,void 0),y(this,`groundManager`,void 0),y(this,`_datasetManager`,new Ul),y(this,`_materialQuality`,void 0),y(this,`_lodTransition`,void 0),y(this,`_fallbackOffset`,void 0),y(this,`_colorPipeline`,void 0),y(this,`_pipelineGen`,0),y(this,`_clip`,null),y(this,`_featureStyleManager`,void 0),y(this,`gpuPathManager`,new Yi),y(this,`_customPathTime`,!1),y(this,`_picks`,void 0),y(this,`_smidMeshes`,new Map),y(this,`_heights`,void 0),y(this,`_sel`,void 0),y(this,`_tileFadeSeq`,0),y(this,`_modeGen`,0),y(this,`_shadingPrewarmed`,!1),y(this,`_prewarmShadingEnabled`,!0),y(this,`_prewarming`,!1),y(this,`_pathSpecs`,new Map),y(this,`_pathScratch`,new Float32Array(3)),y(this,`_pathScratch2`,new Float32Array(3)),y(this,`_pointClouds`,new Set),y(this,`_splats`,new Ss),y(this,`_opacityTransparent`,!1),y(this,`animator`,new tl),y(this,`attributeQuery`,null),y(this,`_enuMatrix`,new t.Matrix4),y(this,`_frameMvp`,new t.Matrix4),y(this,`_colorScratch`,new t.Color),y(this,`_frame`,0),y(this,`_fps`,{value:0,last:0}),y(this,`_lights`,void 0),y(this,`_datasetQueue`,void 0),y(this,`_onRequestRepaint`,()=>{}),y(this,`_getBearing`,void 0),y(this,`_authenticate`,void 0),y(this,`_lodRangeScale`,1),y(this,`_unsupported`,void 0),y(this,`_lodPixelRatioCap`,1/0),y(this,`_motionBlurCfg`,null),y(this,`_motionBlur`,null),y(this,`_perTilePlacement`,void 0),y(this,`_depthMode`,`scene`),this.options=e,this.pickable=e.pickable!==!1,this._lodRangeScale=e.lodRangeScale??1,this._unsupported=e.unsupported??`warn`,this._lodPixelRatioCap=e.lodPixelRatioCap??1/0,this._perTilePlacement=e.perTilePlacement!==!1,this._depthMode=Gl(e.depthMode),ji(e.maxTextureSize??1/0),this._motionBlurCfg=_c(e.motionBlur),this._materialQuality=$i(e.materialQuality),this._datasetManager.defaultMaterialQuality=this._materialQuality,this._lodTransition=e.lodTransition??`binary`,this._fallbackOffset=e.fallbackOffset,this._datasetManager.defaultLodTransition=this._lodTransition,this._datasetManager.defaultFallbackOffset=this._fallbackOffset,this._datasetManager.defaultBakeMercator=e.bakeMercator,e.totalMaxTiles&&(this._datasetManager.totalMaxTiles=e.totalMaxTiles),this._onRequestRepaint=e.onRequestRepaint??(()=>{}),this._getBearing=e.getBearing,this._authenticate=e.authenticate,this.onStats=e.onStats??(()=>{}),this.onReady=e.onReady??(()=>{}),this.onPick=e.onPick??(()=>{}),this.onError=e.onError??(e=>console.warn(`[s3m]`,e)),this._prewarmShadingEnabled=e.prewarmShading!==!1,this.groundManager=new Wl(e.ground),this.scene||(this.scene=new t.Scene,this.scene.add(this.groundManager.group)),this._featureStyleManager=new Ys(()=>this.style.floorHeight,()=>this._requestRepaint(),()=>{this._sel.selection&&this._sel.syncStyle()},()=>this.getAllMeshes(),e=>this._applyOverridesToMesh(e),()=>this._opacityTransparent),this.uniforms=aa(),this._colorPipeline=ia(e.colorPipeline),this._applyRenderProfile({},!0),this._lights=new cs({scene:()=>this.scene,renderer:()=>this.renderer,uniforms:this.uniforms,options:this.options,getBearing:()=>this._getBearing?.(),repaint:()=>this.triggerRepaint(),applyRenderProfile:(e,t)=>this._applyRenderProfile(e,t)}),this._lights.addToScene(),this._heights=new ls(this.uniforms);let n=this;this._picks=new Zs({get picker(){return n.picker},get camera(){return n.camera},get scene(){return n.scene},get canvas(){return n.canvas},get style(){return n.style},get sceneAnchor(){return n.sceneAnchor},get datasets(){return n.datasets},get featureStyleManager(){return n._featureStyleManager},get smidMeshes(){return n._smidMeshes},lngLatFromWorld:(e,t)=>n._lngLatFromWorld(e,t),toCanonicalScene:(e,t)=>n._toCanonicalScene(e,t),gpuPathPoseAt:e=>n._gpuPathPoseAt(e),isFeatureHidden:(e,t)=>n._isFeatureHidden(e,t)}),Ni(Dn),this.style={...fa,...e.style??{}},this._styleTarget={...this.style},this._opacityTransparent=(this.style.opacity??1)<.999,this._applyStyleUniforms(),this._registerAnimChannels(),this.animator.onActive=()=>this._requestRepaint(),this.outlineMaterial=ca(this.uniforms),this._edges=new Vs({uniforms:this.uniforms,style:this.style,styleTarget:this._styleTarget,animator:this.animator,pickables:this._picks.pickables,get scene(){return n.scene},get renderer(){return n.renderer},get camera(){return n.camera},authenticate:this._authenticate,requestRepaint:()=>this.triggerRepaint()}),this.lineShared=this._edges.lineShared,this.edgeMaterial=this._edges.edgeMaterial,this.selectionEdgeMaterial=this._edges.selectionEdgeMaterial,this._sel=new tc({uniforms:this.uniforms,style:this.style,outlineMaterial:this.outlineMaterial,selectionEdgeMaterial:this.selectionEdgeMaterial,featureStyleManager:this._featureStyleManager,smidMeshes:this._smidMeshes,pointClouds:this._pointClouds,applyPointCloudStyle:(e,t)=>this._applyPointCloudStyle(e,t),onPick:e=>this.onPick(e),requestRepaint:()=>this.triggerRepaint(),createSelectionEdgeMaterial:e=>this._edges.createSelectionEdgeMaterial(e)}),this.setEdges(this.style.edges),this._applyOpacity(),this._fps.last=performance.now(),this._datasetQueue=this._normalizeDatasets(e),e.attributes&&(this.attributeQuery=new tn({...e.attributes,authenticate:e.attributes.authenticate??this._authenticate}))}_createRenderer(e,n){let r=new t.WebGLRenderer({canvas:e,context:n,antialias:!0});return r.autoClear=!1,r.setPixelRatio(1),r.toneMapping=this.options.toneMapping===void 0?t.NoToneMapping:this.options.toneMapping,r.toneMappingExposure=this.options.toneMappingExposure??1,r}_syncTextureCapabilities(e){let t=!!e.getExtension(`WEBGL_compressed_texture_s3tc`),n=!!e.getExtension(`WEBGL_compressed_texture_s3tc_srgb`);Mi(t&&n)}mount(e,n){this.canvas=e,this.renderer=this._createRenderer(e,n),Oi(this.renderer.capabilities.getMaxAnisotropy(),this.options.anisotropyCap??1/0),this._syncTextureCapabilities(n),this._applyClipping(),this.scene=new t.Scene,this.scene.add(this.groundManager.group),this._addLights(),this.camera=new t.Camera,this.camera.matrixAutoUpdate=!1,this.picker=new gc(this.renderer),this._applyStyleUniforms();for(let e of this._datasetQueue)this.addDataset(e).catch(e=>this.onError(e));this._recomputeAnchors()}restoreContext(e){if(!this.canvas)console.warn(`[s3m] restoreContext 调用过早(尚未 mount),按首次挂载处理`);else{try{this.renderer?.dispose?.()}catch{}this.renderer=this._createRenderer(this.canvas,e),Oi(this.renderer.capabilities.getMaxAnisotropy(),this.options.anisotropyCap??1/0),this._syncTextureCapabilities(e),this._applyClipping(),this.picker?.dispose(),this.picker=new gc(this.renderer),this._edges.disposeGpuEdge(),this._requestRepaint()}}unmount(){for(let e of[...this.datasets.keys()])this.removeDataset(e);this.clearCreases(),this.groundManager.dispose(),this.picker?.dispose(),this.picker=null,this._lights.dispose(),this.outlineMaterial.dispose(),this._edges.disposeGpuEdge(),this._motionBlur?.dispose(),this._motionBlur=null,this.edgeMaterial.dispose(),this.selectionEdgeMaterial.dispose(),this.scene?.clear(),this._sel.reset(),this._smidMeshes.clear(),this._heights.clear(),this.animator.clear(),this.animator.unregisterPrefix(`tile.`),this.animator.unregisterPrefix(`feature.`),this._pathSpecs.clear(),this.renderer?.dispose?.(),this.renderer=null,this.canvas=null}get _ambientLight(){return this._lights.ambient}get _hemiLight(){return this._lights.hemi}get _keyLight(){return this._lights.key}get _fillLight(){return this._lights.fill}_updateLights(){this._lights.update()}_addLights(){this._lights.addToScene()}setLightingPreset(e){this._lights.setLightingPreset(e)}setLight(e){this._lights.setLight(e)}getLight(){return this._lights.getLight()}setToneMapping(e,t=1){this._lights.setToneMapping(e,t)}getToneMapping(){return this._lights.getToneMapping()}setEnvironment(e,t=1){return this._lights.setEnvironment(e,t)}_normalizeDatasets(e){return Array.isArray(e.datasets)?e.datasets.filter(e=>!!e?.configUrl).map(t=>({...t,polygonOffset:t.polygonOffset??e.polygonOffset})):e.configUrl?[{id:`default`,name:`默认数据集`,configUrl:e.configUrl,useWorker:e.useWorker,polygonOffset:e.polygonOffset,lodTransition:e.lodTransition,fallbackOffset:e.fallbackOffset}]:[]}async addDataset(e){if(!this.scene)throw Error(`[s3m] 图层尚未 addLayer,不能添加数据集`);let t={...e,unsupported:e.unsupported??this._unsupported,lodTransition:e.lodTransition??this._lodTransition,fallbackOffset:e.fallbackOffset??this._fallbackOffset};return await this._datasetManager.addDataset(t,this.scene,this.geo,this.uniforms,this._lodRangeScale,this.options.buildTile,this.options.maxTiles??64,this.options.maxConcurrent??4,{onTile:(e,t)=>{this._registerTile(e,t),this.onStats(this.stats),this._requestRepaint()},onTileRemoved:(e,t)=>{this._unregisterTile(e,t),this.onStats(this.stats),this._requestRepaint()},onStats:()=>{this.onStats(this.stats),this._requestRepaint()},onError:e=>{this.onError(e),this.onStats(this.stats)},onReady:e=>{this.onReady(e),this._heights.refreshAll(),this.groundManager.excavationBounds||this.groundManager.autoFitExcavation(this.datasets.values())},triggerRepaint:()=>{this._requestRepaint()}},this.options.maxTriangles??1/0,this.options.maxImageCache??128,this._authenticate,this.options.maxMemory??1/0)}_lngLatFromWorld(e,t){return un(this.geo,e,t)}recomputeAnchors(){this._datasetManager.recomputeAnchors(this.geo),this._reapplyTilePlacements(),this._heights.refreshAll(),this._requestRepaint()}_recomputeAnchors(){this.recomputeAnchors()}getDatasetHeight(e){return this._datasetManager.getDatasetHeight(e)}setDatasetHeight(e,t){let n,r;typeof e==`number`?(n=this.datasets.keys().next().value??``,r=e):(n=e,r=t??0),this._datasetManager.setDatasetHeight(n,r,this.geo),this._syncGroundHeight(),this._heights.refreshAll(),this._requestRepaint()}_syncGroundHeight(){if(!this.groundManager.trackHeight)return;let e=this.datasets.keys().next().value;if(!e)return;let t=this._datasetManager.getDatasetHeight(e);this.groundManager.setGroundHeight(t)}setDatasetAlign(e,t){let n,r;t===void 0&&(e===`origin`||e===`bottom`||e===`top`||e===`center`)?(n=this.datasets.keys().next().value??``,r=e):(n=e,r=t??`origin`),this._datasetManager.setDatasetAlign(n,r,this.geo),this._heights.refreshAll(),this._requestRepaint()}_computeAlignOffset(e,t){return this._datasetManager.computeAlignOffset(e,t)}computeAlignOffset(e,t){return this._datasetManager.computeAlignOffset(e,t)}setFeatureStyle(e,t){this._featureStyleManager.setFeatureStyle(e,t,this._meshesOf([e]))}setFeaturesStyle(e,t){this._featureStyleManager.setFeaturesStyle(e,t,this._meshesOf(e))}moveFeature(e,t,n){let r=this._ensureFeatureChannel(e,`translation`);this.animator.to(r,t,n)}moveFeatureBy(e,t,n){let r=this._featureStyleManager.getFeatureStyle(e)?.translation??[0,0,0];this.moveFeature(e,[r[0]+t[0],r[1]+t[1],r[2]+t[2]],n)}rotateFeature(e,t,n,r){let i=this._featureStyleManager.getFeatureStyle(e)??{};n&&this._featureStyleManager.setFeatureStyle(e,{...i,pivot:n},this._meshesOf([e]));let a=Ws(t),o=this._ensureFeatureChannel(e,`rotation`);this.animator.to(o,a,r)}rotateFeatureBy(e,t,n,r){let i=Ws(this._featureStyleManager.getFeatureStyle(e)?.rotation),a=typeof t==`number`?[0,0,t]:t;this.rotateFeature(e,[i[0]+a[0],i[1]+a[1],i[2]+a[2]],n,r)}crossFadeStyles(e,t){let n=e instanceof Map?e:new Map(Object.entries(e).map(([e,t])=>[Number(e),t])),r=this.getAllMeshes();this._featureStyleManager.prepareCrossFade(n,r);let i=`batch.mix`;this.animator.has(i)||this.animator.register(i,{dim:1,read:e=>{e[0]=this.uniforms.uBatchMix?.value??0},write:e=>{this.uniforms.uBatchMix&&(this.uniforms.uBatchMix.value=e[0]),this.triggerRepaint()}}),(t?.duration??0)>0||t?.spring?(this.uniforms.uBatchMix&&(this.uniforms.uBatchMix.value=0),this.animator.to(i,1,{...t,onComplete:()=>{this.uniforms.uBatchMix&&(this.uniforms.uBatchMix.value=0),this._featureStyleManager.commitCrossFade(n,r),this.triggerRepaint(),t?.onComplete?.()}})):(this.animator.has(i)&&this.animator.cancel(i),this.uniforms.uBatchMix&&(this.uniforms.uBatchMix.value=0),this._featureStyleManager.commitCrossFade(n,r),this.triggerRepaint(),t?.onComplete?.())}followPath(e,t,n={}){let r=t instanceof Ki?t:new Ki(t,{closed:n.closed});if(r.length<=0)return;let i=n.offset??[0,0,0],a=n.duration??(n.speed&&n.speed>0?r.length/n.speed*1e3:2e3),o=`feature.${e}.path`;this._pathSpecs.set(o,{path:r,offset:i}),this.animator.has(o)||this.animator.register(o,{dim:1,read:e=>{e[0]=0},write:t=>{let n=this._pathSpecs.get(o);if(!n)return;n.path.sampleAt(t[0],this._pathScratch);let r=this._meshesOf([e]),i=this._featureStyleManager.getFeatureStyle(e)??{};this._featureStyleManager.setFeatureStyle(e,{...i,translation:[n.offset[0]+this._pathScratch[0],n.offset[1]+this._pathScratch[1],n.offset[2]+this._pathScratch[2]]},r);for(let e of r)e.frustumCulled=!1}});let s=()=>{this.animator.to(o,1,{duration:a,easing:n.easing??`linear`,onComplete:()=>{n.loop?s():n.onComplete?.()}})};s()}stopPath(e){let t=`feature.${e}.path`;this.animator.cancel(t),this.animator.unregister(t),this._pathSpecs.delete(t)}_gpuPathPoseAt(e){let t=this._featureStyleManager.getFeatureStyle(e)?.gpuPath;if(!t)return null;let n=this.gpuPathManager.getPath(t.pathId);if(!n||n.length<=0)return null;let r=this.uniforms.uPathTime?.value??0,i=(t.phase??0)+r*(t.speed??0),a=t.loop;a===`clamp`||a===!1?i=Math.min(1,Math.max(0,i)):a===`pingpong`?(i%=2,i<0&&(i+=2),i=i>1?2-i:i):i-=Math.floor(i),n.sampleAt(i,this._pathScratch);let o=[this._pathScratch[0],this._pathScratch[1],this._pathScratch[2]],s=0;if(t.autoHeading!==!1){let e=.001;n.sampleAt(Math.min(1,i+e),this._pathScratch2);let t=this._pathScratch2[0]-o[0],r=this._pathScratch2[1]-o[1];t*t+r*r<1e-8&&(n.sampleAt(Math.max(0,i-e),this._pathScratch2),t=o[0]-this._pathScratch2[0],r=o[1]-this._pathScratch2[1]),t*t+r*r>=1e-8&&(s=Math.atan2(r,t))}return{pos:o,yaw:s}}registerGPUPath(e,t={}){let n=this.gpuPathManager.registerPath(e,t);return this.gpuPathManager.updateUniforms(this.uniforms),n}unregisterGPUPath(e){let t=this.gpuPathManager.unregisterPath(e);return this.gpuPathManager.updateUniforms(this.uniforms),t}getGPUPathManager(){return this.gpuPathManager}bindGPUPath(e,t,n={}){let r;r=typeof t==`number`?t:this.registerGPUPath(t);let i=this._meshesOf([e]);this._featureStyleManager.bindGPUPath(e,r,n,i);for(let e of i)e.frustumCulled=!1;return this.gpuPathManager.updateUniforms(this.uniforms),r}unbindGPUPath(e){let t=this._meshesOf([e]);this._featureStyleManager.unbindGPUPath(e,t),this.gpuPathManager.updateUniforms(this.uniforms)}setGPUPathProgress(e,t){let n=this._meshesOf([e]);this._featureStyleManager.setGPUPathProgress(e,t,n);for(let e of n)e.frustumCulled=!1}setGPUPathTime(e,t=!1){this.uniforms.uPathTime&&(this.uniforms.uPathTime.value=e),this._customPathTime=!t}getGPUPathTime(){return this.uniforms.uPathTime?.value??0}animateFeature(e,t,n){if(t.translation&&this.moveFeature(e,t.translation,n),t.rotation!=null&&this.rotateFeature(e,t.rotation,t.pivot,n),t.elevation!=null&&this.animator.to(this._ensureFeatureChannel(e,`elevation`),t.elevation,n),t.opacity!=null&&this.animator.to(this._ensureFeatureChannel(e,`opacity`),t.opacity,n),t.color&&(this._colorScratch.set(t.color),this.animator.to(this._ensureFeatureChannel(e,`color`),[this._colorScratch.r,this._colorScratch.g,this._colorScratch.b],n)),t.hidden!=null){let n=this._featureStyleManager.getFeatureStyle(e)??{};this.setFeatureStyle(e,{...n,hidden:t.hidden})}}animateFeatures(e,t,n){let r=n?.stagger??0;if(r<=0){for(let r of e)this.animateFeature(r,t,n);return}let i=n?.delay??0;for(let a=0;a<e.length;a++)this.animateFeature(e[a],t,{...n,delay:i+a*r})}setMode(e,t={}){let n=Math.max(0,t.duration??300),r=Math.min(1,Math.max(.05,t.dim??.35));if(this.style.mode===e)return Promise.resolve();if(n<=0)return this.setStyle({mode:e}),Promise.resolve();let i=++this._modeGen;return new Promise(t=>{this.animator.to(`style.fade`,r,{duration:n,easing:`easeInOutQuad`,onComplete:()=>{i===this._modeGen?(this.setStyle({mode:e}),this.animator.to(`style.fade`,1,{duration:n,easing:`easeInOutQuad`,onComplete:t})):t()}})})}_ensureFeatureChannel(e,t){let n=`feature.${e}.${t}`;if(this.animator.has(n))return n;let r=t===`translation`||t===`color`||t===`rotation`?{dim:3,read:n=>{if(t===`translation`){let t=this._featureStyleManager.getFeatureStyle(e)?.translation;n[0]=t?.[0]??0,n[1]=t?.[1]??0,n[2]=t?.[2]??0}else if(t===`rotation`){let t=this._featureStyleManager.getFeatureStyle(e)?.rotation,r=Ws(t);n[0]=r[0],n[1]=r[1],n[2]=r[2]}else{let t=this._featureStyleManager.getFeatureStyle(e)?.color??this.style.colorA;this._colorScratch.set(t),n[0]=this._colorScratch.r,n[1]=this._colorScratch.g,n[2]=this._colorScratch.b}},write:n=>{let r=this._meshesOf([e]),i=this._featureStyleManager.getFeatureStyle(e)??{};if(t===`translation`){this._featureStyleManager.setFeatureStyle(e,{...i,translation:[n[0],n[1],n[2]]},r);let t=Math.abs(n[0])>1e-6||Math.abs(n[1])>1e-6||Math.abs(n[2])>1e-6,a=Ws(i.rotation),o=Math.abs(a[0])>1e-6||Math.abs(a[1])>1e-6||Math.abs(a[2])>1e-6;for(let e of r)e.frustumCulled=!(t||o)}else if(t===`rotation`){this._featureStyleManager.setFeatureStyle(e,{...i,rotation:[n[0],n[1],n[2]]},r);let t=Math.abs(n[0])>1e-6||Math.abs(n[1])>1e-6||Math.abs(n[2])>1e-6,a=i.translation??[0,0,0],o=Math.abs(a[0])>1e-6||Math.abs(a[1])>1e-6||Math.abs(a[2])>1e-6;for(let e of r)e.frustumCulled=!(t||o)}else{let t=this._colorScratch.setRGB(n[0],n[1],n[2]);this._featureStyleManager.setFeatureStyle(e,{...i,color:`#${t.getHexString()}`},r)}}}:{dim:1,read:n=>{let r=this._featureStyleManager.getFeatureStyle(e);n[0]=(t===`elevation`?r?.elevation:r?.opacity)??+(t===`opacity`)},write:n=>{let r=this._featureStyleManager.getFeatureStyle(e)??{},i=t===`elevation`?{...r,elevation:n[0]}:{...r,opacity:n[0]};this._featureStyleManager.setFeatureStyle(e,i,this._meshesOf([e]))}};return this.animator.register(n,r),n}_releaseFeatureChannels(e){for(let t of eu)this.animator.unregister(`feature.${e}.${t}`);let t=`feature.${e}.path`;this.animator.unregister(t),this._pathSpecs.delete(t)}getFeatureStyle(e){return this._featureStyleManager.getFeatureStyle(e)}getFeatureStyles(){return this._featureStyleManager.getFeatureStyles()}removeFeatureStyle(e){this._releaseFeatureChannels(e),this._featureStyleManager.removeFeatureStyle(e,this._meshesOf([e]))}clearFeatureStyles(){for(let e of this._featureStyleManager.getFeatureStyles().keys())this._releaseFeatureChannels(e);this._featureStyleManager.clearFeatureStyles()}setAttributeSource(e){this.attributeQuery=e?new tn({...e,authenticate:e.authenticate??this._authenticate}):null}getLoadedSmids(){return[...this._smidMeshes.keys()]}auditBatches(){let e=this._featureStyleManager.auditBatches(this._picks.pickables.values());return e.smids=this._smidMeshes.size,e}getThematicField(){return this._featureStyleManager.thematicField}setThematicColors(e,t=`custom`){this._featureStyleManager.setThematicColors(e,t)}clearThematic(){this._featureStyleManager.clearThematicColors()}getFilterField(){return this._featureStyleManager.fieldFilter?.field??null}filterByField(e){return this._featureStyleManager.filterByField(e,this.attributeQuery,this.getLoadedSmids())}clearFieldFilter(){this._featureStyleManager.clearFieldFilter()}getElevationField(){return this._featureStyleManager.elevationField}elevateByField(e){return this._featureStyleManager.elevateByField(e,this.attributeQuery,this.getLoadedSmids())}setThematicElevation(e,t=`custom`){this._featureStyleManager.setThematicElevation(e,t)}clearThematicElevation(){this._featureStyleManager.clearThematicElevation()}colorByField(e){return this._featureStyleManager.colorByField(e,this.attributeQuery,this.getLoadedSmids())}setFilter(e){this._featureStyleManager.setFilter(e,this.uniforms)}getFilter(){return this._featureStyleManager.filter}clearFilter(){this._featureStyleManager.clearFilter(this.uniforms)}setGroundMode(e){this.groundManager.setMode(e),this._requestRepaint()}setGroundOpacity(e){this.groundManager.setOpacity(e),this._requestRepaint()}setExcavationBounds(e){this.groundManager.setExcavationBounds(e),this._requestRepaint()}setGroundOcclude(e){this.groundManager.setOcclude(e),this._requestRepaint()}_isFeatureHidden(e,t){if(e==null)return!1;let n=this._featureStyleManager.fieldFilter;if(n){let t=n.matched.has(e);if(n.mode===`keep`?!t:t)return!0}let r=this._featureStyleManager.filter;return!!(r&&(r.include&&r.include.length>0&&!r.include.includes(e)||r.exclude&&r.exclude.length>0&&r.exclude.includes(e))||this._featureStyleManager.featureStyles.get(e)?.hidden)}getAllMeshes(){let e=[];for(let t of this._picks.pickables.values())e.push(t.mesh);return e}_meshesOf(e){let t=new Set;for(let n of e){let e=this._smidMeshes.get(n);if(e)for(let n of e)t.add(n)}return t}flushOverrides(){this._featureStyleManager.flushOverrides()}_applyOverridesToMesh(e){this._featureStyleManager.applyOverridesToMesh(e)}removeDataset(e){if(this.datasets.get(e)){this._sel.selection?.datasetId===e&&this.select(null),this._datasetManager.removeDataset(e,this.scene,this.geo,e=>{e.root.traverse(e=>{let t=e,n=t.userData;n.pickId!=null&&(this._picks.pickables.delete(n.pickId),this._releasePickId(n.pickId),n.pickId=void 0),this._unindexMeshSmids(t),this._heights.remove(t),t.geometry?.dispose?.();let r=Kl(t);r&&r.dispose(),lc(t.material)&&t.material.dispose(),this._featureStyleManager.disposeMesh(t)})});for(let[t,n]of this._picks.pickables)n.datasetId===e&&this._picks.pickables.delete(t);this.onStats(this.stats),this._requestRepaint()}}clearDatasets(){for(let e of[...this.datasets.keys()])this.removeDataset(e)}setDatasetVisible(e,t){this._datasetManager.setDatasetVisible(e,t),!t&&this._sel.selection?.datasetId===e&&this.select(null),this._requestRepaint()}_registerTile(e,t){let n=e.sphere?.center??this._localCenterOf(e.group);if(this._perTilePlacement&&n&&this._applyTilePlacement(e.group,n,t),e.group.matrixAutoUpdate){let t=this.sceneAnchor;if(t){let n=t.meterInMercatorEast??t.meterInMercator,r=t.meterInMercatorNorth??t.meterInMercator,i=t.meterInMercatorUp??n,a=e.sphere?[e.sphere.center.x,e.sphere.center.y,e.sphere.center.z]:[0,0,0];this._updateTileUniforms(e.group,a,[1/n,1/r,1/i])}}t.root.add(e.group),e.group.updateMatrixWorld(!0);let r=e.group.userData.hasNativeEdges===!0,i=this._edges.useNativeEdges(r);for(let n of e.group.children){if(n.isLineSegments&&n.userData.isEdgeLines){this._edges.registerNativeLine(n,i&&this._edges.enabled);continue}let a=ql(n),o=n;if(!o.isMesh&&!a)continue;a&&this._pointClouds.add(n),a&&this._splats.markDirty();let s=o.userData;if(s.pickId=this._allocPickId(),s.datasetId=t.id,s.nativeEdges=i,s.nativeEdgesRaw=r,this._picks.pickables.set(s.pickId,{datasetId:t.id,mesh:o,tile:e.tile,skeletonName:s.skeletonName??``}),this._indexMeshSmids(o),this._heights.add(o),this._edges.autoDecorate(o,t,i),a)this._applyPointCloudStyle(n);else{let e=Kl(o);if(e){let t=Jl(this.style.opacity),n=this.style.depthWrite!==!1;sa(e,t<.999,n),e.userData.uFlatShading&&(e.userData.uFlatShading.value=this.style.shading===`smooth`?0:1),this._featureStyleManager.applyOverridesToMesh(o),this._startTileFade(o,e)}}this._sel.replayOnto(o)}}_localCenterOf(e){if(!e.children.length)return null;let n=new t.Box3().setFromObject(e);if(n.isEmpty())return null;let r=n.getCenter(new t.Vector3);return!Number.isFinite(r.x)||!Number.isFinite(r.y)||!Number.isFinite(r.z)?null:{x:r.x,y:r.y,z:r.z}}_applyTilePlacement(e,n,r){var i;let a=this.sceneAnchor;if(!a||!r.anchor)return;let o=Hl({center:n,datasetAnchor:r.anchor,sceneAnchor:a,datasetOffset:r.offset,geo:this.geo});if(!o)return;let s=o.scaleEast??o.scale,c=o.scaleNorth??o.scale,l=s;e.matrixAutoUpdate=!1,e.matrix.makeScale(s,c,l),e.matrix.setPosition(o.position[0]-s*o.pivot[0],o.position[1]-c*o.pivot[1],o.position[2]-l*o.pivot[2]),e.matrixWorldNeedsUpdate=!0,e.userData.tileCenter={x:n.x,y:n.y,z:n.z},((i=e.userData).placementInverse??(i.placementInverse=new t.Matrix4)).copy(e.matrix).invert();let u=a.meterInMercatorEast??a.meterInMercator,d=a.meterInMercatorNorth??a.meterInMercator,f=a.meterInMercatorUp??u,p=o.invTileScale??[1/(u*s),1/(d*c),1/(f*l)];this._updateTileUniforms(e,o.pivot,p)}_updateTileUniforms(e,t,n){e.traverse(e=>{let r=e;if((e.isMesh||e.isPoints)&&e.material){let e=Array.isArray(r.material)?r.material:[r.material];for(let r of e){let e=r.userData?.uTilePivot,i=r.userData?.uInvTileScale;e?.value&&e.value.set(t[0],t[1],t[2]),i?.value&&i.value.set(n[0],n[1],n[2])}}})}_toCanonicalScene(e,t){if(!this._perTilePlacement||!t)return e;let n=t.parent;for(;n&&!n.userData.tileCenter;)n=n.parent;if(!n)return e;let r=n.parent;return r?e.clone().sub(r.position).applyMatrix4(n.userData.placementInverse??Xl.copy(n.matrix).invert()).add(r.position):e}_reapplyTilePlacements(){for(let e of this._datasetManager.values())if(e.anchor)for(let t of e.root.children){let n=t.userData.tileCenter;n&&this._applyTilePlacement(t,n,e)}}_startTileFade(e,t){let n=this.style.fadeIn??0;if(n<=0)return;let r=t.userData.uTileFade;if(!r)return;r.value=0,t.transparent=!0,t.depthWrite=!0;let i=`tile.${this._tileFadeSeq++}.fade`;e.userData.tileFadeKey=i,this.animator.register(i,{dim:1,read:e=>{e[0]=r.value},write:e=>{r.value=e[0]}}),this.animator.to(i,1,{duration:n,easing:`easeOutQuad`,onComplete:()=>{r.value=1,e.userData.tileFadeKey=void 0,this.animator.unregister(i),sa(t,this._opacityTransparent,this.style.depthWrite!==!1),this._featureStyleManager.applyOverridesToMesh(e),this._requestRepaint()}})}_replaySelectionOnto(e){this._sel.replayOnto(e)}_unregisterTile(e,t){e.group.traverse(e=>{let t=e;if(e.isLineSegments&&t.userData?.isEdgeLines&&this._edges.unregisterNativeLine(e),ql(e)&&this._pointClouds.delete(e),t.userData?.tileFadeKey&&(this.animator.unregister(t.userData.tileFadeKey),t.userData.tileFadeKey=void 0),t.userData?.pickId!=null&&(this._picks.pickables.delete(t.userData.pickId),this._releasePickId(t.userData.pickId),t.userData.pickId=void 0),t.isMesh){this._sel.selectedMeshes.includes(t)&&(this._sel.selectedMeshes=this._sel.selectedMeshes.filter(e=>e!==t));let e=this._sel.selection;if(e&&e.mesh===t){let n=e.smid,r=n==null?this._sel.selectedMeshes.find(e=>e!==t&&e.parent&&e.parent.visible)??this._sel.selectedMeshes.find(e=>e!==t&&e.parent):[...this._smidMeshes.get(n)??[]].find(e=>e!==t&&e.parent);r?(this._sel.selection={...e,mesh:r},this._sel.replayOnto(r)):this.select(null)}this._unindexMeshSmids(t),this._heights.remove(t),this._featureStyleManager.disposeMesh(t),Kl(t)?.dispose?.()}lc(t.material)?t.material.dispose():t.material&&(Array.isArray(t.material)?t.material.forEach(e=>e?.dispose?.()):t.material.dispose?.()),t.geometry?.dispose?.()}),t.root.remove(e.group)}setOpacity(e,t){this.setStyle({opacity:e},t)}setStyle(e={},t){Object.assign(this._styleTarget,e);let n=t?.duration??0,r=n>0||!!t?.spring,i=e;if(`edges`in e){let{edges:n,...a}=e;if(i=a,this.setEdges(n,r?t:void 0),Object.keys(i).length===0){this._requestRepaint();return}}let a=[],o={};for(let e of Object.keys(i))r&&this.animator.has(`style.${String(e)}`)?a.push(String(e)):o[e]=i[e];Object.keys(o).length>0&&(Object.assign(this.style,o),this._applyStyleEffects(o));for(let e of a)this.animator.to(`style.${e}`,this._animTargetOf(e,i),{...t,duration:n});this._requestRepaint()}getStyle(){return{...this._styleTarget,modeLabel:la[this._styleTarget.mode]}}_animTargetOf(e,t){let n=t[e];return this._animDimOf(e)===1?Number(n):(this._colorScratch.set(String(n)),[this._colorScratch.r,this._colorScratch.g,this._colorScratch.b])}_animDimOf(e){return $l.includes(e)?3:1}_registerAnimChannels(){for(let e of Zl)this.animator.register(`style.${e}`,{dim:1,read:t=>{t[0]=Number(this.style[e]??Ql[e]??0)},write:t=>{this.style[e]=t[0],this._onStyleChannelWrote(e)}});for(let e of $l)this.animator.register(`style.${e}`,{dim:3,read:t=>{let n=this._uniformColorOf(e);t[0]=n.r,t[1]=n.g,t[2]=n.b},write:t=>{let n=this._uniformColorOf(e);n.setRGB(t[0],t[1],t[2]),this.style[e]=`#${n.getHexString()}`,this._onStyleChannelWrote(e)}});this.animator.register(`style.edgeFade`,{dim:1,read:e=>{e[0]=this.uniforms.uEdgeFade?.value??1},write:e=>{this.uniforms.uEdgeFade&&(this.uniforms.uEdgeFade.value=e[0]),this._edges.syncStyle()}}),this.animator.register(`style.fade`,{dim:1,read:e=>{e[0]=this.uniforms.uFade?.value??1},write:e=>{this.uniforms.uFade&&(this.uniforms.uFade.value=e[0]),this._requestRepaint()}})}_onStyleChannelWrote(e){e===`opacity`?this._applyOpacity():(this._applyStyleUniforms(),(e===`edgeColor`||e===`edgeWidth`||e===`edgeOpacity`||e===`edgeOffset`||e===`edgeHullWidth`)&&this._edges.refreshLines())}_uniformColorOf(e){let t=this.uniforms;switch(e){case`colorA`:return t.uColorA.value;case`colorB`:return t.uColorB.value;case`colorC`:return t.uColorC.value;case`selectColor`:return t.uSelColor.value;case`edgeColor`:return this.edgeMaterial.uniforms.uColor.value;default:return t.uColorA.value}}_applyStyleEffects(e){this._applyStyleUniforms(),(`opacity`in e||`depthWrite`in e)&&this._applyOpacity(),`mode`in e&&this._applyPointCloudStyles(),`shading`in e&&this._applyShading(),(`edgeThreshold`in e||`forceCpuEdges`in e)&&this._edges.enabled?(this._edges.disposeEdgeGeometry(),this.setEdges(this.style.edges)):(`edgeColor`in e||`edgeWidth`in e||`opacity`in e||`edgeOpacity`in e||`edgeOffset`in e||`edgeHullWidth`in e)&&this._edges.refreshLines(),this._sel.selection&&(`outline`in e||`outlineStyle`in e?this.select(this._sel.selection,{silent:!0}):this._sel.syncStyle())}_applyStyleUniforms(){let e=this.uniforms,t=this.style;e.uMode.value=t.mode,e.uColorA.value.set(t.colorA),e.uColorB.value.set(t.colorB),e.uColorC.value.set(t.colorC),e.uSelColor.value.set(t.selectColor),e.uFloorHeight.value=t.floorHeight;let n=t.selectMode??$.OVERLAY;e.uSelMode&&(e.uSelMode.value=n===$.REPLACE?0:n===$.MULTIPLY?2:n===$.GLOW_ONLY?3:1),e.uSelOpacity&&t.selectOpacity!=null&&(e.uSelOpacity.value=t.selectOpacity),e.uSelEmissive&&t.selectEmissive!=null&&(e.uSelEmissive.value=t.selectEmissive),e.uSelElevation&&t.selectElevation!=null&&(e.uSelElevation.value=t.selectElevation),e.uDimFactor&&t.dimFactor!=null&&(e.uDimFactor.value=t.dimFactor),e.uRoofThreshold&&t.roofThreshold!=null&&(e.uRoofThreshold.value=t.roofThreshold),e.uTexMix&&t.texMix!=null&&(e.uTexMix.value=t.texMix),e.uAmbientGain&&t.ambientGain!=null&&(e.uAmbientGain.value=t.ambientGain),e.uMetalness&&(e.uMetalness.value=t.metalness??-1),e.uRoughness&&(e.uRoughness.value=t.roughness??-1),e.uOpacity&&t.opacity!=null&&(e.uOpacity.value=Jl(t.opacity)),this.outlineMaterial&&(this.outlineMaterial.uniforms.uElevation&&t.selectElevation!=null&&(this.outlineMaterial.uniforms.uElevation.value=t.selectElevation),t.outlineWidth!=null&&(this.outlineMaterial.uniforms.uWidth.value=t.outlineWidth),t.outlineColor==null?this.outlineMaterial.uniforms.uColor.value.set(t.selectColor):this.outlineMaterial.uniforms.uColor.value.set(t.outlineColor))}_applyOpacity(){let e=Jl(this.style.opacity);this.uniforms.uOpacity&&(this.uniforms.uOpacity.value=e);let t=e<.999;if(t!==this._opacityTransparent){this._opacityTransparent=t;let e=this.style.depthWrite!==!1;for(let n of this._picks.pickables.values()){if(ql(n.mesh))continue;let r=Kl(n.mesh);r&&(r.userData.uBatchTexActive?.value||(r.userData.uTileFade?.value??1)<1||sa(r,t,e))}}for(let e of this._pointClouds)this._applyPointCloudStyle(e);this._edges.syncStyle(),this._requestRepaint()}_applyPointCloudStyle(e,t=this._sel.selectedMeshes.includes(e)){cc(e,this.style,this.uniforms,t)}_applyPointCloudStyles(){for(let e of this._pointClouds)this._applyPointCloudStyle(e);this._requestRepaint()}_applyShading(){let e=this.style.shading===`smooth`?0:1;for(let t of this._picks.pickables.values()){let n=Kl(t.mesh)?.userData.uFlatShading;n&&n.value!==e&&(n.value=e)}this._requestRepaint()}setMaterialQuality(e){this._materialQuality=$i(e)??`pbr`,this._datasetManager.setDefaultMaterialQuality(this._materialQuality),this._rebuildStyledMaterials(),this._requestRepaint()}get lodTransition(){return this._lodTransition}setLodTransition(e){this._lodTransition!==e&&(this._lodTransition=e,this._datasetManager.setDefaultLodTransition(e),this.triggerRepaint())}get materialQuality(){return this._materialQuality??ta()}setMotionBlur(e){this._motionBlurCfg=_c(e),this._motionBlurCfg||(this._motionBlur?.dispose(),this._motionBlur=null),this.triggerRepaint()}setDepthMode(e){let t=Gl(e);this._depthMode!==t&&(this._depthMode=t,this.triggerRepaint())}get depthMode(){return this._depthMode}resolveDepthMode(){if(this._depthMode===`clear`)return`clear`;if(this._depthMode===`scene`)return`scene`;if(this.groundManager&&this.groundManager.mode!==`none`)return`clear`;for(let e of this._datasetManager.datasets.values()){if(!e.visible)continue;if(e.options.depthMode===`clear`)return`clear`;if(e.options.depthMode===`scene`)continue;if(e.tileset?.isS3MV1)return`clear`;let t=e.tileset?.config;if(t){let e=`${t.fileType??``} ${t.dataType??``} ${t.datasetType??``} ${t.cacheType??``} ${t.fileExtentName??``}`;if(/osgb|oblique|ground|dem|tin|terrain/i.test(e))return`clear`}if(e.options.configUrl&&/osgb|oblique/i.test(e.options.configUrl))return`clear`}return`scene`}get motionBlur(){return this._motionBlurCfg?{...this._motionBlurCfg}:null}setColorPipeline(e,t={}){let n=ia(e)??`linear`;if(n===this.colorPipeline)return Promise.resolve();let r=Math.max(0,t.duration??0);if(r<=0)return this._applyRenderProfile({colorPipeline:n}),Promise.resolve();let i=Math.min(1,Math.max(.05,t.dim??.35)),a=++this._pipelineGen;return new Promise(e=>{this.animator.to(`style.fade`,i,{duration:r,easing:`easeInOutQuad`,onComplete:()=>{a===this._pipelineGen?(this._applyRenderProfile({colorPipeline:n}),this.animator.to(`style.fade`,1,{duration:r,easing:`easeInOutQuad`,onComplete:e})):e()}})})}get colorPipeline(){return this._colorPipeline??ra()}_textureOptions(){return{srgbDecode:this.colorPipeline!==`direct`,maxSize:this.options.maxTextureSize??1/0,anisotropyCap:this.options.anisotropyCap??1/0}}_applyRenderProfile(e,t=!1){let n=this.colorPipeline;e.colorPipeline!==void 0&&(this._colorPipeline=ia(e.colorPipeline)??`linear`),e.anisotropyCap!==void 0&&(this.options.anisotropyCap=e.anisotropyCap);let r=this._textureOptions();this._datasetManager.setRenderProfile({colorPipeline:this.colorPipeline,textureOptions:r}),!t&&(this.colorPipeline!==n&&this._rebuildStyledMaterials(),this._syncCachedTextures(r),this._requestRepaint())}_syncCachedTextures(e){let n=e.srgbDecode?t.SRGBColorSpace:t.NoColorSpace;for(let t of this.datasets.values()){let r=t.tileset?.textureCache;if(r){for(let e of r.values())e.colorSpace!==n&&(e.colorSpace=n,e.needsUpdate=!0);Ai(r.values(),e.anisotropyCap??1/0)}}}_rebuildStyledMaterials(){let e=[`uSelBatch`,`uSelWhole`,`uBatchTex`,`uBatchTex2`,`uBatchTexWidth`,`uBatchTexActive`,`uTileFade`];for(let t of this._picks.pickables.values()){let n=t.mesh,r=n.material;if(Array.isArray(r))continue;let i=r;if(!i?.userData?.isStyled||!i.userData?.s3mOpts)continue;let a=i.userData.s3mOpts,o=oa({...a,uniforms:this.uniforms,materialQuality:this.materialQuality,colorPipeline:this.colorPipeline});for(let t of e){let e=i.userData[t],n=o.userData[t];e&&n&&(n.value=e.value)}n.material=o,i.dispose()}}async prewarmShading(){if(this._shadingPrewarmed||this._prewarming)return;let e=this.renderer,t=this.scene,n=this.camera;if(!e||!t||!n)return;let r=!1;for(let e of this._picks.pickables.values())if(Kl(e.mesh)){r=!0;break}if(r){this._shadingPrewarmed=!0;try{let r=e;typeof r.compileAsync==`function`?await r.compileAsync(t,n):e.compile(t,n)}catch{}this._requestRepaint()}}_addMeshHeight(e){this._heights.add(e)}_removeMeshHeight(e){this._heights.remove(e)}_indexMeshSmids(e){let t=e.userData.geoRef?.pickInfo;if(t)for(let n of Object.keys(t)){let t=Number(n);if(!Number.isFinite(t)||t<0)continue;let r=this._smidMeshes.get(t);r||this._smidMeshes.set(t,r=new Set),r.add(e)}}_unindexMeshSmids(e){let t=e.userData.geoRef?.pickInfo;if(t)for(let n of Object.keys(t)){let t=Number(n),r=this._smidMeshes.get(t);r&&(r.delete(e),r.size===0&&this._smidMeshes.delete(t))}}get _edgesEnabled(){return this._edges.enabled}get _edgeModes(){return this._edges.modes}get _gpuEdge(){return this._edges.gpuEdge}set _gpuEdge(e){this._edges.gpuEdge=e}_ensureEdges(e){this._edges.ensureEdges(e)}_removeEdges(e){this._edges.removeEdges(e)}setEdges(e,t){this._edges.setEdges(e,t)}loadCreases(e){return this._edges.loadCreases(e)}clearCreases(){this._edges.clearCreases()}getRayAt(e,t){return this._picks.getRayAt(e,t)}pick(e,t){return this._picks.pick(e,t)}pickPosition(e,t){return this._picks.pickPosition(e,t)}drillPick(e,t,n=10){return this._picks.drillPick(e,t,n)}getFeatureBounds(e){return this._picks.getFeatureBounds(e)}_sceneFromLngLat(e){let t=this.sceneAnchor;if(!t)return[0,0,0];let n=t.meterInMercatorEast??t.meterInMercator,r=t.meterInMercatorNorth??t.meterInMercator,i=ln(this.geo,e.lng,e.lat,e.altitude);return[(i.x-t.x)/n,-(i.y-t.y)/r,e.altitude-(t.altitude??0)]}lngLatToPoint(e){return this._sceneFromLngLat(e)}pointToLngLat(e){return this._lngLatFromScene(e)}_lngLatFromScene(e){let t=this.sceneAnchor;if(!t)return{lng:0,lat:0,altitude:e[2]};let n=t.meterInMercatorEast??t.meterInMercator,r=t.meterInMercatorNorth??t.meterInMercator,[i,a]=un(this.geo,e[0]*n+t.x,-e[1]*r+t.y);return{lng:i,lat:a,altitude:e[2]+(t.altitude??0)}}measureDistance(e,t){return ul(this._sceneFromLngLat(e),this._sceneFromLngLat(t))}measurePolyline(e){let t=e.map(e=>this._sceneFromLngLat(e));return{length3D:al(t),lengthHorizontal:ol(t)}}measurePolygon(e){let t=e.map(e=>this._sceneFromLngLat(e));return{area3D:cl(t),areaHorizontal:ll(t),perimeter:sl(t)}}lineOfSight(e,t,n={}){return dl(this._sceneFromLngLat(e),this._sceneFromLngLat(t),(e,t,n)=>{let r=this._picks.raycastDistance(e,t,n);return r?{distance:r.distance,point:r.point}:null},n)}setClipping(e){this._clip=e,this._applyClipping(),this._requestRepaint()}get clipping(){return this._clip}_applyClipping(){let e=this.renderer;e&&(e.clippingPlanes=this._clip?yl(this._clip).map(e=>new t.Plane(new t.Vector3(e.normal[0],e.normal[1],e.normal[2]),e.constant)):[])}_depthCtx(){return{renderer:()=>this.renderer,scene:()=>this.scene,camera:()=>this.camera}}skyline(e={}){let t=Rl(this._depthCtx(),e.width??640,e.height??360,e.include);return t?Al({rgba:t.rgba,width:t.width,height:t.height,inverseViewProj:t.inverseViewProj,cameraPos:t.cameraPos,step:e.step}):null}viewshed(e){let t=e.eyeHeight??1.7,n=this._sceneFromLngLat({...e.origin,altitude:e.origin.altitude+t}),r=e.size??128,i=Vl(this._depthCtx(),n,r,e.radius,e.include);return i?jl(n,Ml(i,r,e.radius),{radius:e.radius,grid:e.grid,groundZ:0}):null}_intersectMeshAtRay(e,t,n){return this._picks.intersectMeshAtRay(e,t,n)}_buildPickResult(e,t,n,r){return this._picks.buildPickResult(e,t,n,r)}_buildSplatPickResult(e,t,n,r){return this._picks.buildSplatPickResult(e,t,n,r)}_instanceFeature(e,t,n){return this._picks.instanceFeature(e,t,n)}_instanceBox(e,t){return this._picks.instanceBox(e,t)}_allocPickId(){return this._picks.allocPickId()}_releasePickId(e){this._picks.releasePickId(e)}get _pickables(){return this._picks.pickables}select(e,t={}){this._sel.select(e,t)}_syncSelectionStyle(){this._sel.syncStyle()}get _selection(){return this._sel.selection}get _selectedMeshes(){return this._sel.selectedMeshes}get _selectionEdgeMeshes(){return this._sel.selectionEdgeMeshes}_updateLineResolution(e){let t=e.width||1,n=e.height||1,r=e.clientWidth||t;this.lineShared.uResolution.value.set(t,n),this.lineShared.uDpr.value=Math.max(1,t/r)}get lodRangeScale(){return this._lodRangeScale}get lodPixelRatioCap(){return this._lodPixelRatioCap}setLodPixelRatioCap(e){let t=e>0?e:1/0;this._lodPixelRatioCap=t,this.options.lodPixelRatioCap=t,this._requestRepaint()}_lodScreenHeight(e){let t=this._lodPixelRatioCap;if(!Number.isFinite(t))return e;let n=this.canvas?.clientHeight??0;return n<=0?e:Math.min(e,n*t)}get maxImageCache(){return this.options.maxImageCache??128}setMaxImageCache(e,t){let n=Number.isFinite(e)?Math.max(1,Math.floor(e)):128;if(t){let e=this.datasets.get(t);e?.tileset&&(e.tileset.maxImageCache=n)}else{this.options.maxImageCache=n;for(let e of this.datasets.values())e.tileset&&(e.tileset.maxImageCache=n)}this._requestRepaint()}get maxTriangles(){return this.options.maxTriangles??1/0}setMaxTriangles(e,t){let n=e>0?e:1/0;if(t){let e=this.datasets.get(t);e?.tileset&&e.tileset.setMaxTriangles(n)}else{this.options.maxTriangles=n;for(let e of this.datasets.values())e.tileset&&e.tileset.setMaxTriangles(n)}}get maxMemory(){return this.options.maxMemory??1/0}setMaxMemory(e,t){let n=Number.isFinite(e)&&e>0?e:1/0;if(t){let e=this.datasets.get(t);e?.tileset&&e.tileset.setMaxMemory(n)}else{this.options.maxMemory=n;for(let e of this.datasets.values())e.tileset&&e.tileset.setMaxMemory(n)}}get anisotropyCap(){return this.options.anisotropyCap??1/0}setAnisotropyCap(e){let t=Number.isFinite(e)&&e>0?Math.max(1,e):1/0;this.options.anisotropyCap=t,Oi(this.renderer?.capabilities.getMaxAnisotropy?.()??1,t),this._applyRenderProfile({anisotropyCap:t})}get maxTextureSize(){return this.options.maxTextureSize??1/0}setMaxTextureSize(e){let t=Number.isFinite(e)&&e>=1?e:1/0;this.options.maxTextureSize=t,ji(t),this._datasetManager.setRenderProfile({textureOptions:this._textureOptions()}),this._requestRepaint()}setLodRangeScale(e,t){if(!(e<=0)){if(t){let n=this.datasets.get(t);n?.tileset&&(n.tileset.lodRangeScale=e)}else{this._lodRangeScale=e;for(let t of this.datasets.values())t.tileset&&(t.tileset.lodRangeScale=e)}this._requestRepaint()}}_sortSplats(){this._splats.sort(this.camera,this._pointClouds)}_renderMotionBlur(e,t){let n=this.renderer,r=this.scene,i=this.camera,a=this._motionBlurCfg;return!n||!r||!i||!a||(this._motionBlur||(this._motionBlur=new Cc),!this._motionBlur.supported(n))?!1:(this._motionBlur.render(n,r,i,e,t,{mode:a.mode,damp:a.damp===`auto`?vc(this.fps):a.damp,maxOffset:a.maxOffset,mvp:this._frameMvp,mvpInverse:i.projectionMatrixInverse}),!0)}renderFrame(e){if(!this.renderer||!this.scene||!this.camera||!this.sceneAnchor||!this.canvas)return!1;let t=this.renderer.getContext();if(t&&typeof t.isContextLost==`function`&&t.isContextLost())return!1;if(this._prewarming)return!0;let n=this.animator.tick();this.flushOverrides();let r=this.canvas,i=this.sceneAnchor.meterInMercatorEast??this.sceneAnchor.meterInMercator,a=this.sceneAnchor.meterInMercatorNorth??this.sceneAnchor.meterInMercator,o=this.sceneAnchor.meterInMercatorUp??i;this._enuMatrix.set(i,0,0,this.sceneAnchor.x,0,-a,0,this.sceneAnchor.y,0,0,o,this.sceneAnchor.z,0,0,0,1);let s=this._frameMvp.fromArray(e.mvp);s.multiply(this._enuMatrix),this.camera.projectionMatrix.copy(s),this.camera.projectionMatrixInverse.copy(s).invert();let c=e.cameraEnu;this.camera.position.set(c[0],c[1],c[2]),this.camera.matrixWorld.setPosition(c[0],c[1],c[2]),this.camera.matrixWorldInverse.copy(this.camera.matrixWorld).invert(),this.groundManager.update(this.camera);let l=!1,u=this._lodScreenHeight(e.canvasHeight);for(let t of this.datasets.values()){if(!t.visible||!t.tileset)continue;let n=[c[0]-t.offset[0],c[1]-t.offset[1],c[2]-t.offset[2]];t.tileset.update(n,e.fovRad,u)&&(l=!0)}this.style.mode===Q.DYNAMIC&&(this.uniforms.uTime.value+=.016*(this.style.speed??1)),this.gpuPathManager.updateUniforms(this.uniforms);let d=(this.uniforms.uPathTexActive?.value??0)>0;d&&!this._customPathTime&&this.uniforms.uPathTime&&(this.uniforms.uPathTime.value+=.016),this._updateLights(),this._updateLineResolution(r),wo(r.width,r.height),this.renderer.setViewport(0,0,r.width,r.height);let f=(this.uniforms.uOpacity?.value??1)>Yl?this.resolveDepthMode():`scene`;f===`clear`&&t&&(t.depthMask(!0),t.clear(t.DEPTH_BUFFER_BIT)),this.renderer.resetState(),(this.uniforms.uOpacity?.value??1)>Yl&&(this._sortSplats(),this._motionBlurCfg&&this._renderMotionBlur(r.width,r.height)||this.renderer.render(this.scene,this.camera),f!==`clear`&&this._edges.renderGpuEdges(r)),this._frame++;let p=performance.now();p-this._fps.last>500&&(this._fps.value=Math.round(this._frame*1e3/(p-this._fps.last)),this._frame=0,this._fps.last=p);let m=n||this.style.mode===Q.DYNAMIC||d||this.stats.loading>0||l;return this._prewarmShadingEnabled&&!this._shadingPrewarmed&&this._picks.pickables.size>0&&this.prewarmShading(),m}get fps(){return this._fps.value}get stats(){let e={tiles:0,loading:0,failed:0,meshes:0,vertices:0,triangles:0,datasets:this.datasets.size,drawCalls:0,programs:0,textures:0,geometries:0,degradations:[]},t=null;for(let n of this.datasets.values()){let r=n.tileset?.stats;if(r&&(e.tiles+=r.tiles,e.loading+=r.loading,e.failed+=r.failed,e.meshes+=r.meshes,e.vertices+=r.vertices,e.triangles+=r.triangles,r.degradations?.length)){t??(t=[]);for(let e of r.degradations)t.includes(e)||t.push(e)}}t&&(e.degradations=t);let n=this.renderer?.info;return n&&(e.drawCalls=n.render.calls,e.programs=n.programs?.length??0,e.textures=n.memory.textures,e.geometries=n.memory.geometries),e}getBounds(){let e=1/0,t=1/0,n=-1/0,r=-1/0;for(let i of this.datasets.values()){let a=Jo(i.tileset?.config?.geoBounds);a&&(e=Math.min(e,a.left),n=Math.max(n,a.right),t=Math.min(t,a.bottom),r=Math.max(r,a.top))}return isFinite(e)?[[e,t],[n,r]]:null}dispose(){this.unmount()}};b();var nu=class e{constructor(t={}){y(this,`id`,void 0),y(this,`options`,void 0),y(this,`pickable`,void 0),y(this,`onStats`,void 0),y(this,`onReady`,void 0),y(this,`onPick`,void 0),y(this,`onError`,void 0),y(this,`viewer`,void 0),y(this,`_projection`,`perspective`),y(this,`_projectionT`,0),y(this,`_orthoWarned`,!1),y(this,`_nearPlaneScale`,1),this.id=t.id??`s3m`,this.options=t,this.pickable=t.pickable!==!1,this._projection=t.projection===`orthographic`?`orthographic`:`perspective`,this._nearPlaneScale=e.normalizeNearPlaneScale(t.nearPlaneScale),this._projectionT=+(this._projection===`orthographic`),this.onStats=t.onStats??(()=>{}),this.onReady=t.onReady??(()=>{}),this.onPick=t.onPick??(()=>{}),this.onError=t.onError??(e=>console.warn(`[s3m]`,e));let{id:n,projection:r,nearPlaneScale:i,...a}=t;this.viewer=new tu({...a,onRequestRepaint:()=>this.requestRepaint(),getBearing:()=>this.getBearing(),onStats:e=>this.onStats(e),onReady:e=>this.onReady(e),onPick:e=>this.onPick(e),onError:e=>this.onError(e)})}getBearing(){return 0}mountViewer(e,t){this.viewer.renderer?this.viewer.restoreContext(t):this.viewer.mount(e,t)}unmountViewer(){this.viewer.unmount()}driveFrame(e){let t=this.viewer.renderFrame(e);return t&&this.requestRepaint(),t}setProjection(e,t){let n=e===`orthographic`?`orthographic`:`perspective`,r=+(n===`orthographic`),i=t?.duration??0,a=i>0||!!t?.spring;this._projection=n,this._orthoWarned=!1,a?(this._ensureProjectionChannel(),this.viewer.animator.to(`projection.t`,r,{...t,duration:i,easing:t?.easing??`easeInOutCubic`,onComplete:()=>{this._projectionT=r,this.requestRepaint()}}),this.requestRepaint()):(this.viewer.animator.has(`projection.t`)&&this.viewer.animator.cancel(`projection.t`),this._projectionT=r,this.requestRepaint())}get projection(){return this._projection}get projectionT(){return this._projectionT}_ensureProjectionChannel(){this.viewer.animator.has(`projection.t`)||this.viewer.animator.register(`projection.t`,{dim:1,read:e=>{e[0]=this._projectionT},write:e=>{this._projectionT=e[0],this.requestRepaint()}})}setNearPlaneScale(t){this._nearPlaneScale=e.normalizeNearPlaneScale(t),this.requestRepaint()}get nearPlaneScale(){return this._nearPlaneScale}static normalizeNearPlaneScale(e){return typeof e!=`number`||!Number.isFinite(e)?1:e>0&&e<1?e:1}},ru=1e-4;function iu(e,t){let n=e.elements;for(let e=0;e<16;e++){let r=Math.max(1,Math.abs(n[e]),Math.abs(t[e]));if(Math.abs(n[e]-t[e])>ru*r)return!1}return!0}function au(e){let t=e.elements,n=1;for(let e=0;e<16;e++){let r=Math.abs(t[e]);r>n&&(n=r)}let r=1e-6*n;return Math.abs(t[3])<r&&Math.abs(t[7])<r&&Math.abs(t[11])<r&&Math.abs(t[15]-1)<r}function ou(e,t){return t>0&&Math.abs(e.elements[5]*Math.tan(t/2)-1)<.001}function su(e){if(!e||typeof e!=`object`)return null;let t=e;return t.defaultProjectionData?.projectionMatrix??t.projectionMatrix??null}function cu(e){let t={nearZ:null,farZ:null};if(!e||typeof e!=`object`)return t;let n=e,r=n.defaultProjectionData,i=e=>{let t=n[e];if(typeof t==`number`&&Number.isFinite(t))return t;let i=r?.[e];return typeof i==`number`&&Number.isFinite(i)?i:null};return{nearZ:i(`nearZ`),farZ:i(`farZ`)}}function lu(e,t){if(e&&typeof e==`object`){let t=e.fov;if(typeof t==`number`&&Number.isFinite(t)&&t>0)return t}return typeof t==`number`&&Number.isFinite(t)&&t>0?t:null}function uu(e,n){let r=e.projectionMatrix;if(!r||r.length<16)return null;let i=new t.Matrix4().fromArray(Array.from(r)),a=new t.Matrix4().fromArray(Array.from(e.mvp));if(i.determinant()===0||!ou(i,n.fov))return null;let o=i.clone().invert().multiply(a);if(!iu(i.clone().multiply(o),Array.from(e.mvp))||!au(o)||!ou(i,n.fov))return null;let{distance:s,fov:c,aspect:l}=n;if(!(s>0)||!(c>0)||!(l>0))return null;let u=s*Math.tan(c/2),d=u*l,f=e.nearZ!=null&&e.nearZ>0?e.nearZ:1,p=e.farZ!=null&&e.farZ>f?e.farZ:s*4+1e3;p>f||(p=f+1e3);let m=new t.OrthographicCamera(-d,d,u,-u,f,p);return m.updateProjectionMatrix(),{matrix:m.projectionMatrix.clone().multiply(o),view:o}}function du(e,n){if(!(n>0)||n>=1)return null;let r=e.projectionMatrix;if(!r||r.length<16)return null;let i=new t.Matrix4().fromArray(Array.from(r));if(!Number.isFinite(i.determinant())||i.determinant()===0||Math.abs(i.elements[11]+1)>1e-6)return null;let a=e.nearZ!=null&&e.nearZ>0?e.nearZ:NaN,o=e.farZ!=null&&e.farZ>a?e.farZ:NaN;if(!(a>0)||!(o>a)){let e=-i.elements[10];if(!(e>1)||(a=-i.elements[14]/(e+1),o=a*(e+1)/(e-1),!(a>0)||!(o>a)))return null}let s=a*n;if(!(s>0)||!(s<o))return null;let c=i.clone();c.elements[10]=-(o+s)/(o-s),c.elements[14]=-2*o*s/(o-s);let l=c.multiply(i.clone().invert()).multiply(new t.Matrix4().fromArray(Array.from(e.mvp)));for(let e=0;e<16;e++)if(!Number.isFinite(l.elements[e]))return null;return l}function fu(e,n,r){let i=e.projectionMatrix;if(!i||i.length<16)return null;let a=new t.Matrix4().fromArray(Array.from(i)),o=new t.Matrix4().fromArray(Array.from(e.mvp));if(a.determinant()===0||!ou(a,n.fov))return null;let s=a.clone().invert().multiply(o);if(!iu(a.clone().multiply(s),Array.from(e.mvp))||!au(s))return null;let c=Math.max(0,Math.min(1,r));if(c<=0)return{matrix:o,view:s};let{distance:l,fov:u,aspect:d}=n;if(!(l>0)||!(u>0)||!(d>0))return null;let f=l*Math.tan(u/2),p=f*d,m=e.nearZ!=null&&e.nearZ>0?e.nearZ:1,h=e.farZ!=null&&e.farZ>m?e.farZ:l*4+1e3;h>m||(h=m+1e3);let g=new t.OrthographicCamera(-p,p,f,-f,m,h);if(g.updateProjectionMatrix(),c>=1)return{matrix:g.projectionMatrix.clone().multiply(s),view:s};let _=new t.Matrix4,v=a.elements,y=g.projectionMatrix.elements,b=_.elements;for(let e=0;e<16;e++)b[e]=(1-c)*v[e]+c*y[e];return{matrix:_.multiply(s),view:s}}var pu=l({Animator:()=>tl,AttributeQuery:()=>tn,BinaryReader:()=>x,CUBE_FACES:()=>zl,DEFAULT_FLOOR_HEIGHT:()=>qt,DEFAULT_LIGHT_PRESET:()=>rs,DEFAULT_STYLE:()=>fa,DatasetManager:()=>Ul,EARTH_RADIUS:()=>hn,EASING_NAMES:()=>Pc,FeatureStyleManager:()=>Ys,GPUPathManager:()=>Yi,GpuEdgePass:()=>Ls,GroundManager:()=>Wl,HostRenderer:()=>nu,LIGHT_PRESETS:()=>as,MotionBlurPass:()=>Cc,Path:()=>Ki,Picker:()=>gc,PixelFormat:()=>X,S3MFormatError:()=>Bt,S3MTileset:()=>ns,S3MViewer:()=>tu,S3M_VERSION:()=>ut,SAMPLES_PER_PATH:()=>256,SELECT_MODE:()=>$,SELECT_MODE_LABELS:()=>ua,STYLE:()=>Q,STYLE_LABELS:()=>la,SUPERMAP_LIGHT_PRESET:()=>is,TextureCompress:()=>Z,VertexTag:()=>B,VertexTagV3:()=>dt,WGS84_A:()=>dn,WGS84_B:()=>pn,WGS84_E2:()=>mn,WGS84_F:()=>fn,authFetch:()=>Xt,autoMotionBlurDamp:()=>vc,azimuthElevation:()=>kl,boxClipping:()=>_l,buildAttributes:()=>Kt,buildBlendedMVP:()=>fu,buildClipPlanes:()=>yl,buildCubeCameras:()=>Bl,buildFeatureEdgeSegments:()=>Ms,buildNearScaledMVP:()=>du,buildOrthoMVP:()=>uu,buildThickLineGeometry:()=>Ds,buildTileObjects:()=>Po,captureRadialCube:()=>Vl,captureSkylineDepth:()=>Rl,classifyDatasetKind:()=>Zo,computeViewshed:()=>jl,createLineSharedUniforms:()=>Cs,createOutlineMaterial:()=>ca,createSharedUniforms:()=>aa,createStyledMaterial:()=>oa,createTexture:()=>Ri,createThickLineMaterial:()=>Es,crossClipping:()=>vl,cubicBezier:()=>Gc,default:()=>tu,distance3D:()=>nl,distanceHorizontal:()=>rl,dxtPixelFormatOf:()=>Ur,easing:()=>Fc,enuToLngLat:()=>an,extractEulerAngles:()=>Ws,extractFovRadians:()=>lu,extractNearFar:()=>cu,extractProjectionMatrix:()=>su,getColorPipeline:()=>ra,getMaterialQuality:()=>ta,heightDifference:()=>il,isPointKept:()=>hl,isS3M1Buffer:()=>He,lineOfSight:()=>dl,lngLatFromMercator:()=>cn,lngLatFromWorld:()=>un,lngLatToEnu:()=>on,makeCubeDistanceSampler:()=>Ml,measureSegment:()=>ul,measureSegments:()=>Gt,mercatorFromLngLat:()=>sn,meridianRadius:()=>rn,normalizeDepthMode:()=>Gl,normalizeMotionBlur:()=>_c,packRGBADepth:()=>wl,parseConfigText:()=>Xo,parseS3M1:()=>lt,parseS3MB:()=>Vt,pixelToNdc:()=>Ol,planDegradations:()=>Ut,planeClipping:()=>gl,planeFromPointNormal:()=>ml,polygonArea:()=>cl,polygonAreaHorizontal:()=>ll,polygonPerimeter:()=>sl,polylineLength:()=>al,polylineLengthHorizontal:()=>ol,primeVerticalRadius:()=>nn,resolveAuthRequest:()=>Yt,resolveEdgeModes:()=>Zi,resolveFeature:()=>U,resolveLightingPreset:()=>os,resolveRotationMatrix:()=>Us,resolveTextureKind:()=>Hr,sameEdgeModes:()=>Qi,setColorPipeline:()=>na,setMaterialQuality:()=>ea,setMaxAnisotropy:()=>Oi,setMaxTextureSize:()=>ji,setSrgbTextureDecode:()=>Fi,skylineFromDepth:()=>Al,steps:()=>Kc,unpackRGBADepth:()=>Tl,unprojectNdc:()=>Dl,worldFromLngLat:()=>ln});Jt(),gn(),ja(),Xi(),Vo(),Gi(),Kr(),qi(),Jt(),gn(),Kr(),Gi(),qi(),Xi(),ja(),Vo();var mu=globalThis;return mu.THREE||(mu.THREE=t),mu.S3M=pu,e.Animator=tl,e.AttributeQuery=tn,e.BinaryReader=x,e.CUBE_FACES=zl,e.DEFAULT_FLOOR_HEIGHT=qt,e.DEFAULT_LIGHT_PRESET=rs,e.DEFAULT_STYLE=fa,e.DatasetManager=Ul,e.EARTH_RADIUS=hn,e.EASING_NAMES=Pc,e.FeatureStyleManager=Ys,e.GPUPathManager=Yi,e.GpuEdgePass=Ls,e.GroundManager=Wl,e.HostRenderer=nu,e.LIGHT_PRESETS=as,e.MotionBlurPass=Cc,e.Path=Ki,e.Picker=gc,e.PixelFormat=X,e.S3MFormatError=Bt,e.S3MTileset=ns,e.S3MViewer=tu,e.default=tu,e.S3M_VERSION=ut,e.SAMPLES_PER_PATH=Ji,e.SELECT_MODE=$,e.SELECT_MODE_LABELS=ua,e.STYLE=Q,e.STYLE_LABELS=la,e.SUPERMAP_LIGHT_PRESET=is,e.TextureCompress=Z,e.VertexTag=B,e.VertexTagV3=dt,e.WGS84_A=dn,e.WGS84_B=pn,e.WGS84_E2=mn,e.WGS84_F=fn,e.authFetch=Xt,e.autoMotionBlurDamp=vc,e.azimuthElevation=kl,e.boxClipping=_l,e.buildAttributes=Kt,e.buildBlendedMVP=fu,e.buildClipPlanes=yl,e.buildCubeCameras=Bl,e.buildFeatureEdgeSegments=Ms,e.buildNearScaledMVP=du,e.buildOrthoMVP=uu,e.buildThickLineGeometry=Ds,e.buildTileObjects=Po,e.captureRadialCube=Vl,e.captureSkylineDepth=Rl,e.classifyDatasetKind=Zo,e.computeViewshed=jl,e.createLineSharedUniforms=Cs,e.createOutlineMaterial=ca,e.createSharedUniforms=aa,e.createStyledMaterial=oa,e.createTexture=Ri,e.createThickLineMaterial=Es,e.crossClipping=vl,e.cubicBezier=Gc,e.distance3D=nl,e.distanceHorizontal=rl,e.dxtPixelFormatOf=Ur,e.easing=Fc,e.enuToLngLat=an,e.extractEulerAngles=Ws,e.extractFovRadians=lu,e.extractNearFar=cu,e.extractProjectionMatrix=su,e.getColorPipeline=ra,e.getMaterialQuality=ta,e.heightDifference=il,e.isPointKept=hl,e.isS3M1Buffer=He,e.lineOfSight=dl,e.lngLatFromMercator=cn,e.lngLatFromWorld=un,e.lngLatToEnu=on,e.makeCubeDistanceSampler=Ml,e.measureSegment=ul,e.measureSegments=Gt,e.mercatorFromLngLat=sn,e.meridianRadius=rn,e.normalizeDepthMode=Gl,e.normalizeMotionBlur=_c,e.packRGBADepth=wl,e.parseConfigText=Xo,e.parseS3M1=lt,e.parseS3MB=Vt,e.pixelToNdc=Ol,e.planDegradations=Ut,e.planeClipping=gl,e.planeFromPointNormal=ml,e.polygonArea=cl,e.polygonAreaHorizontal=ll,e.polygonPerimeter=sl,e.polylineLength=al,e.polylineLengthHorizontal=ol,e.primeVerticalRadius=nn,e.resolveAuthRequest=Yt,e.resolveEdgeModes=Zi,e.resolveFeature=U,e.resolveLightingPreset=os,e.resolveRotationMatrix=Us,e.resolveTextureKind=Hr,e.sameEdgeModes=Qi,e.setColorPipeline=na,e.setMaterialQuality=ea,e.setMaxAnisotropy=Oi,e.setMaxTextureSize=ji,e.setSrgbTextureDecode=Fi,e.skylineFromDepth=Al,e.steps=Kc,e.unpackRGBADepth=Tl,e.unprojectNdc=Dl,e.worldFromLngLat=ln,e})({},THREE);
1495
+ `}),a=new t.Mesh(e,i);a.position.set(0,0,-.02),a.renderOrder=-1e3,a.name=`s3m-ground-depth`,a.visible=!1,this.group.add(a),this._depthMesh=a,this._depthMaterial=i,this._syncUniforms()}_applyMode(){this._mesh&&(this._mesh.visible=this.mode!==`none`),this._material&&(this._material.uniforms.uMode.value=this.mode===`excavate`?2:+(this.mode===`translucent`),this._material.depthWrite=this.mode===`excavate`),this._depthMesh&&(this._depthMesh.visible=this.occlude,this._depthMaterial&&(this._depthMaterial.uniforms.uPunchPit.value=+(this.mode===`excavate`)))}update(e){e&&this.group.position.set(e.position.x,e.position.y,this.groundHeight)}setGroundHeight(e){this.groundHeight=e,this.group.position.z=e}setMode(e){this.mode=e,this._occludeExplicit||(this.occlude=e===`excavate`),this._applyMode()}setOcclude(e){this.occlude=e,this._occludeExplicit=!0,this._applyMode()}setOpacity(e){this.opacity=Math.max(0,Math.min(1,e)),this._material&&(this._material.uniforms.uOpacity.value=this.opacity)}setColors(e,t){this.color.set(e),t&&this.gridColor.set(t),this._material&&(this._material.uniforms.uColor.value=this.color,this._material.uniforms.uGridColor.value=this.gridColor)}setExcavationBounds(e){this.excavationBounds=e,this._syncUniforms()}autoFitExcavation(e){let t=1/0,n=1/0,r=-1/0,i=-1/0,a=!1;for(let o of e){let e=o.tileset?.config,s=e?.rootTiles??e?.tiles;if(Array.isArray(s))for(let e of s){let s=e.boundingBox;if(!s)continue;let c=s.center??{x:0,y:0},l=s.xExtent?.x?Math.abs(s.xExtent.x):50,u=s.yExtent?.y?Math.abs(s.yExtent.y):50,d=c.x+o.offset[0]-l,f=c.x+o.offset[0]+l,p=c.y+o.offset[1]-u,m=c.y+o.offset[1]+u;d<t&&(t=d),f>r&&(r=f),p<n&&(n=p),m>i&&(i=m),a=!0}}a&&Number.isFinite(t)&&this.setExcavationBounds([t-5,n-5,r+5,i+5])}_syncUniforms(){let e=this.excavationBounds;if(this._material){let t=this._material.uniforms;e?(t.uHasExcavation.value=1,t.uExcavationMin.value.set(e[0],e[1]),t.uExcavationMax.value.set(e[2],e[3])):t.uHasExcavation.value=0}if(this._depthMaterial){let t=this._depthMaterial.uniforms;e?(t.uHasExcavation.value=1,t.uExcavationMin.value.set(e[0],e[1]),t.uExcavationMax.value.set(e[2],e[3])):t.uHasExcavation.value=0}}dispose(){this._geom?.dispose(),this._geom=null,this._material?.dispose(),this._material=null,this._depthMaterial?.dispose(),this._depthMaterial=null,this._mesh=null,this._depthMesh=null,this.group.clear()}};Gi(),ja(),qi(),Xi(),gn(),b();function Gl(e){return e===`clear`?`clear`:e===`auto`?`auto`:`scene`}function Kl(e){let t=Array.isArray(e.material)?e.material[0]:e.material;return t?.userData?.isStyled?t:null}function ql(e){return e.isPoints===!0}function Jl(e){let t=e??1;return t<0?0:t>1?1:t}var Yl=.001,Xl=new t.Matrix4,Zl=[`opacity`,`floorHeight`,`selectOpacity`,`selectEmissive`,`selectElevation`,`dimFactor`,`texMix`,`roofThreshold`,`ambientGain`,`metalness`,`roughness`,`edgeWidth`,`edgeOpacity`,`edgeOffset`,`edgeHullWidth`,`outlineWidth`],Ql={metalness:0,roughness:.95},$l=[`colorA`,`colorB`,`colorC`,`selectColor`,`edgeColor`],eu=[`translation`,`elevation`,`opacity`,`color`,`rotation`],tu=class{get datasets(){return this._datasetManager.datasets}get sceneAnchor(){return this._datasetManager.sceneAnchor}set sceneAnchor(e){this._datasetManager.sceneAnchor=e,this._reapplyTilePlacements()}_requestRepaint(){this._onRequestRepaint()}triggerRepaint(){this._requestRepaint()}constructor(e={}){y(this,`options`,void 0),y(this,`pickable`,void 0),y(this,`onStats`,void 0),y(this,`onReady`,void 0),y(this,`onPick`,void 0),y(this,`onError`,void 0),y(this,`geo`,null),y(this,`canvas`,null),y(this,`renderer`,null),y(this,`scene`,null),y(this,`camera`,null),y(this,`picker`,null),y(this,`uniforms`,void 0),y(this,`style`,void 0),y(this,`_styleTarget`,void 0),y(this,`outlineMaterial`,void 0),y(this,`lineShared`,void 0),y(this,`edgeMaterial`,void 0),y(this,`selectionEdgeMaterial`,void 0),y(this,`_edges`,void 0),y(this,`groundManager`,void 0),y(this,`_datasetManager`,new Ul),y(this,`_materialQuality`,void 0),y(this,`_lodTransition`,void 0),y(this,`_fallbackOffset`,void 0),y(this,`_colorPipeline`,void 0),y(this,`_pipelineGen`,0),y(this,`_clip`,null),y(this,`_featureStyleManager`,void 0),y(this,`gpuPathManager`,new Yi),y(this,`_customPathTime`,!1),y(this,`_picks`,void 0),y(this,`_smidMeshes`,new Map),y(this,`_heights`,void 0),y(this,`_sel`,void 0),y(this,`_tileFadeSeq`,0),y(this,`_modeGen`,0),y(this,`_shadingPrewarmed`,!1),y(this,`_prewarmShadingEnabled`,!0),y(this,`_prewarming`,!1),y(this,`_pathSpecs`,new Map),y(this,`_pathScratch`,new Float32Array(3)),y(this,`_pathScratch2`,new Float32Array(3)),y(this,`_pointClouds`,new Set),y(this,`_splats`,new Ss),y(this,`_opacityTransparent`,!1),y(this,`animator`,new tl),y(this,`attributeQuery`,null),y(this,`_enuMatrix`,new t.Matrix4),y(this,`_frameMvp`,new t.Matrix4),y(this,`_colorScratch`,new t.Color),y(this,`_frame`,0),y(this,`_fps`,{value:0,last:0}),y(this,`_lights`,void 0),y(this,`_datasetQueue`,void 0),y(this,`_onRequestRepaint`,()=>{}),y(this,`_getBearing`,void 0),y(this,`_authenticate`,void 0),y(this,`_cullRefine`,!1),y(this,`_frustum`,void 0),y(this,`_cullTestVec`,void 0),y(this,`_lodRangeScale`,1),y(this,`_unsupported`,void 0),y(this,`_lodPixelRatioCap`,1/0),y(this,`_motionBlurCfg`,null),y(this,`_motionBlur`,null),y(this,`_perTilePlacement`,void 0),y(this,`_depthMode`,`scene`),this.options=e,this.pickable=e.pickable!==!1,this._lodRangeScale=e.lodRangeScale??1,this._unsupported=e.unsupported??`warn`,this._lodPixelRatioCap=e.lodPixelRatioCap??1/0,this._cullRefine=e.cullRefine===!0||e.frustumCullRefine===!0,this._perTilePlacement=e.perTilePlacement!==!1,this._depthMode=Gl(e.depthMode),ji(e.maxTextureSize??1/0),this._motionBlurCfg=_c(e.motionBlur),this._materialQuality=$i(e.materialQuality),this._datasetManager.defaultMaterialQuality=this._materialQuality,this._lodTransition=e.lodTransition??`binary`,this._fallbackOffset=e.fallbackOffset,this._datasetManager.defaultLodTransition=this._lodTransition,this._datasetManager.defaultFallbackOffset=this._fallbackOffset,this._datasetManager.defaultBakeMercator=e.bakeMercator,e.totalMaxTiles&&(this._datasetManager.totalMaxTiles=e.totalMaxTiles),this._onRequestRepaint=e.onRequestRepaint??(()=>{}),this._getBearing=e.getBearing,this._authenticate=e.authenticate,this.onStats=e.onStats??(()=>{}),this.onReady=e.onReady??(()=>{}),this.onPick=e.onPick??(()=>{}),this.onError=e.onError??(e=>console.warn(`[s3m]`,e)),this._prewarmShadingEnabled=e.prewarmShading!==!1,this.groundManager=new Wl(e.ground),this.scene||(this.scene=new t.Scene,this.scene.add(this.groundManager.group)),this._featureStyleManager=new Ys(()=>this.style.floorHeight,()=>this._requestRepaint(),()=>{this._sel.selection&&this._sel.syncStyle()},()=>this.getAllMeshes(),e=>this._applyOverridesToMesh(e),()=>this._opacityTransparent),this.uniforms=aa(),this._colorPipeline=ia(e.colorPipeline),this._applyRenderProfile({},!0),this._lights=new cs({scene:()=>this.scene,renderer:()=>this.renderer,uniforms:this.uniforms,options:this.options,getBearing:()=>this._getBearing?.(),repaint:()=>this.triggerRepaint(),applyRenderProfile:(e,t)=>this._applyRenderProfile(e,t)}),this._lights.addToScene(),this._heights=new ls(this.uniforms);let n=this;this._picks=new Zs({get picker(){return n.picker},get camera(){return n.camera},get scene(){return n.scene},get canvas(){return n.canvas},get style(){return n.style},get sceneAnchor(){return n.sceneAnchor},get datasets(){return n.datasets},get featureStyleManager(){return n._featureStyleManager},get smidMeshes(){return n._smidMeshes},lngLatFromWorld:(e,t)=>n._lngLatFromWorld(e,t),toCanonicalScene:(e,t)=>n._toCanonicalScene(e,t),gpuPathPoseAt:e=>n._gpuPathPoseAt(e),isFeatureHidden:(e,t)=>n._isFeatureHidden(e,t)}),Ni(Dn),this.style={...fa,...e.style??{}},this._styleTarget={...this.style},this._opacityTransparent=(this.style.opacity??1)<.999,this._applyStyleUniforms(),this._registerAnimChannels(),this.animator.onActive=()=>this._requestRepaint(),this.outlineMaterial=ca(this.uniforms),this._edges=new Vs({uniforms:this.uniforms,style:this.style,styleTarget:this._styleTarget,animator:this.animator,pickables:this._picks.pickables,get scene(){return n.scene},get renderer(){return n.renderer},get camera(){return n.camera},authenticate:this._authenticate,requestRepaint:()=>this.triggerRepaint()}),this.lineShared=this._edges.lineShared,this.edgeMaterial=this._edges.edgeMaterial,this.selectionEdgeMaterial=this._edges.selectionEdgeMaterial,this._sel=new tc({uniforms:this.uniforms,style:this.style,outlineMaterial:this.outlineMaterial,selectionEdgeMaterial:this.selectionEdgeMaterial,featureStyleManager:this._featureStyleManager,smidMeshes:this._smidMeshes,pointClouds:this._pointClouds,applyPointCloudStyle:(e,t)=>this._applyPointCloudStyle(e,t),onPick:e=>this.onPick(e),requestRepaint:()=>this.triggerRepaint(),createSelectionEdgeMaterial:e=>this._edges.createSelectionEdgeMaterial(e)}),this.setEdges(this.style.edges),this._applyOpacity(),this._fps.last=performance.now(),this._datasetQueue=this._normalizeDatasets(e),e.attributes&&(this.attributeQuery=new tn({...e.attributes,authenticate:e.attributes.authenticate??this._authenticate}))}_createRenderer(e,n){let r=new t.WebGLRenderer({canvas:e,context:n,antialias:!0});return r.autoClear=!1,r.setPixelRatio(1),r.toneMapping=this.options.toneMapping===void 0?t.NoToneMapping:this.options.toneMapping,r.toneMappingExposure=this.options.toneMappingExposure??1,r}_syncTextureCapabilities(e){let t=!!e.getExtension(`WEBGL_compressed_texture_s3tc`),n=!!e.getExtension(`WEBGL_compressed_texture_s3tc_srgb`);Mi(t&&n)}mount(e,n){this.canvas=e,this.renderer=this._createRenderer(e,n),Oi(this.renderer.capabilities.getMaxAnisotropy(),this.options.anisotropyCap??1/0),this._syncTextureCapabilities(n),this._applyClipping(),this.scene=new t.Scene,this.scene.add(this.groundManager.group),this._addLights(),this.camera=new t.Camera,this.camera.matrixAutoUpdate=!1,this.picker=new gc(this.renderer),this._applyStyleUniforms();for(let e of this._datasetQueue)this.addDataset(e).catch(e=>this.onError(e));this._recomputeAnchors()}restoreContext(e){if(!this.canvas)console.warn(`[s3m] restoreContext 调用过早(尚未 mount),按首次挂载处理`);else{try{this.renderer?.dispose?.()}catch{}this.renderer=this._createRenderer(this.canvas,e),Oi(this.renderer.capabilities.getMaxAnisotropy(),this.options.anisotropyCap??1/0),this._syncTextureCapabilities(e),this._applyClipping(),this.picker?.dispose(),this.picker=new gc(this.renderer),this._edges.disposeGpuEdge(),this._requestRepaint()}}unmount(){for(let e of[...this.datasets.keys()])this.removeDataset(e);this.clearCreases(),this.groundManager.dispose(),this.picker?.dispose(),this.picker=null,this._lights.dispose(),this.outlineMaterial.dispose(),this._edges.disposeGpuEdge(),this._motionBlur?.dispose(),this._motionBlur=null,this.edgeMaterial.dispose(),this.selectionEdgeMaterial.dispose(),this.scene?.clear(),this._sel.reset(),this._smidMeshes.clear(),this._heights.clear(),this.animator.clear(),this.animator.unregisterPrefix(`tile.`),this.animator.unregisterPrefix(`feature.`),this._pathSpecs.clear(),this.renderer?.dispose?.(),this.renderer=null,this.canvas=null}get _ambientLight(){return this._lights.ambient}get _hemiLight(){return this._lights.hemi}get _keyLight(){return this._lights.key}get _fillLight(){return this._lights.fill}_updateLights(){this._lights.update()}_addLights(){this._lights.addToScene()}setLightingPreset(e){this._lights.setLightingPreset(e)}setLight(e){this._lights.setLight(e)}getLight(){return this._lights.getLight()}setToneMapping(e,t=1){this._lights.setToneMapping(e,t)}getToneMapping(){return this._lights.getToneMapping()}setEnvironment(e,t=1){return this._lights.setEnvironment(e,t)}_normalizeDatasets(e){return Array.isArray(e.datasets)?e.datasets.filter(e=>!!e?.configUrl).map(t=>({...t,polygonOffset:t.polygonOffset??e.polygonOffset})):e.configUrl?[{id:`default`,name:`默认数据集`,configUrl:e.configUrl,useWorker:e.useWorker,polygonOffset:e.polygonOffset,lodTransition:e.lodTransition,fallbackOffset:e.fallbackOffset}]:[]}async addDataset(e){if(!this.scene)throw Error(`[s3m] 图层尚未 addLayer,不能添加数据集`);let t={...e,unsupported:e.unsupported??this._unsupported,lodTransition:e.lodTransition??this._lodTransition,fallbackOffset:e.fallbackOffset??this._fallbackOffset};return await this._datasetManager.addDataset(t,this.scene,this.geo,this.uniforms,this._lodRangeScale,this.options.buildTile,this.options.maxTiles??64,this.options.maxConcurrent??4,{onTile:(e,t)=>{this._registerTile(e,t),this.onStats(this.stats),this._requestRepaint()},onTileRemoved:(e,t)=>{this._unregisterTile(e,t),this.onStats(this.stats),this._requestRepaint()},onStats:()=>{this.onStats(this.stats),this._requestRepaint()},onError:e=>{this.onError(e),this.onStats(this.stats)},onReady:e=>{this.onReady(e),this._heights.refreshAll(),this.groundManager.excavationBounds||this.groundManager.autoFitExcavation(this.datasets.values())},triggerRepaint:()=>{this._requestRepaint()}},this.options.maxTriangles??1/0,this.options.maxImageCache??128,this._authenticate,this.options.maxMemory??1/0)}_lngLatFromWorld(e,t){return un(this.geo,e,t)}recomputeAnchors(){this._datasetManager.recomputeAnchors(this.geo),this._reapplyTilePlacements(),this._heights.refreshAll(),this._requestRepaint()}_recomputeAnchors(){this.recomputeAnchors()}getDatasetHeight(e){return this._datasetManager.getDatasetHeight(e)}setDatasetHeight(e,t){let n,r;typeof e==`number`?(n=this.datasets.keys().next().value??``,r=e):(n=e,r=t??0),this._datasetManager.setDatasetHeight(n,r,this.geo),this._syncGroundHeight(),this._heights.refreshAll(),this._requestRepaint()}_syncGroundHeight(){if(!this.groundManager.trackHeight)return;let e=this.datasets.keys().next().value;if(!e)return;let t=this._datasetManager.getDatasetHeight(e);this.groundManager.setGroundHeight(t)}setDatasetAlign(e,t){let n,r;t===void 0&&(e===`origin`||e===`bottom`||e===`top`||e===`center`)?(n=this.datasets.keys().next().value??``,r=e):(n=e,r=t??`origin`),this._datasetManager.setDatasetAlign(n,r,this.geo),this._heights.refreshAll(),this._requestRepaint()}_computeAlignOffset(e,t){return this._datasetManager.computeAlignOffset(e,t)}computeAlignOffset(e,t){return this._datasetManager.computeAlignOffset(e,t)}setFeatureStyle(e,t){this._featureStyleManager.setFeatureStyle(e,t,this._meshesOf([e]))}setFeaturesStyle(e,t){this._featureStyleManager.setFeaturesStyle(e,t,this._meshesOf(e))}moveFeature(e,t,n){let r=this._ensureFeatureChannel(e,`translation`);this.animator.to(r,t,n)}moveFeatureBy(e,t,n){let r=this._featureStyleManager.getFeatureStyle(e)?.translation??[0,0,0];this.moveFeature(e,[r[0]+t[0],r[1]+t[1],r[2]+t[2]],n)}rotateFeature(e,t,n,r){let i=this._featureStyleManager.getFeatureStyle(e)??{};n&&this._featureStyleManager.setFeatureStyle(e,{...i,pivot:n},this._meshesOf([e]));let a=Ws(t),o=this._ensureFeatureChannel(e,`rotation`);this.animator.to(o,a,r)}rotateFeatureBy(e,t,n,r){let i=Ws(this._featureStyleManager.getFeatureStyle(e)?.rotation),a=typeof t==`number`?[0,0,t]:t;this.rotateFeature(e,[i[0]+a[0],i[1]+a[1],i[2]+a[2]],n,r)}crossFadeStyles(e,t){let n=e instanceof Map?e:new Map(Object.entries(e).map(([e,t])=>[Number(e),t])),r=this.getAllMeshes();this._featureStyleManager.prepareCrossFade(n,r);let i=`batch.mix`;this.animator.has(i)||this.animator.register(i,{dim:1,read:e=>{e[0]=this.uniforms.uBatchMix?.value??0},write:e=>{this.uniforms.uBatchMix&&(this.uniforms.uBatchMix.value=e[0]),this.triggerRepaint()}}),(t?.duration??0)>0||t?.spring?(this.uniforms.uBatchMix&&(this.uniforms.uBatchMix.value=0),this.animator.to(i,1,{...t,onComplete:()=>{this.uniforms.uBatchMix&&(this.uniforms.uBatchMix.value=0),this._featureStyleManager.commitCrossFade(n,r),this.triggerRepaint(),t?.onComplete?.()}})):(this.animator.has(i)&&this.animator.cancel(i),this.uniforms.uBatchMix&&(this.uniforms.uBatchMix.value=0),this._featureStyleManager.commitCrossFade(n,r),this.triggerRepaint(),t?.onComplete?.())}followPath(e,t,n={}){let r=t instanceof Ki?t:new Ki(t,{closed:n.closed});if(r.length<=0)return;let i=n.offset??[0,0,0],a=n.duration??(n.speed&&n.speed>0?r.length/n.speed*1e3:2e3),o=`feature.${e}.path`;this._pathSpecs.set(o,{path:r,offset:i}),this.animator.has(o)||this.animator.register(o,{dim:1,read:e=>{e[0]=0},write:t=>{let n=this._pathSpecs.get(o);if(!n)return;n.path.sampleAt(t[0],this._pathScratch);let r=this._meshesOf([e]),i=this._featureStyleManager.getFeatureStyle(e)??{};this._featureStyleManager.setFeatureStyle(e,{...i,translation:[n.offset[0]+this._pathScratch[0],n.offset[1]+this._pathScratch[1],n.offset[2]+this._pathScratch[2]]},r);for(let e of r)e.frustumCulled=!1}});let s=()=>{this.animator.to(o,1,{duration:a,easing:n.easing??`linear`,onComplete:()=>{n.loop?s():n.onComplete?.()}})};s()}stopPath(e){let t=`feature.${e}.path`;this.animator.cancel(t),this.animator.unregister(t),this._pathSpecs.delete(t)}_gpuPathPoseAt(e){let t=this._featureStyleManager.getFeatureStyle(e)?.gpuPath;if(!t)return null;let n=this.gpuPathManager.getPath(t.pathId);if(!n||n.length<=0)return null;let r=this.uniforms.uPathTime?.value??0,i=(t.phase??0)+r*(t.speed??0),a=t.loop;a===`clamp`||a===!1?i=Math.min(1,Math.max(0,i)):a===`pingpong`?(i%=2,i<0&&(i+=2),i=i>1?2-i:i):i-=Math.floor(i),n.sampleAt(i,this._pathScratch);let o=[this._pathScratch[0],this._pathScratch[1],this._pathScratch[2]],s=0;if(t.autoHeading!==!1){let e=.001;n.sampleAt(Math.min(1,i+e),this._pathScratch2);let t=this._pathScratch2[0]-o[0],r=this._pathScratch2[1]-o[1];t*t+r*r<1e-8&&(n.sampleAt(Math.max(0,i-e),this._pathScratch2),t=o[0]-this._pathScratch2[0],r=o[1]-this._pathScratch2[1]),t*t+r*r>=1e-8&&(s=Math.atan2(r,t))}return{pos:o,yaw:s}}registerGPUPath(e,t={}){let n=this.gpuPathManager.registerPath(e,t);return this.gpuPathManager.updateUniforms(this.uniforms),n}unregisterGPUPath(e){let t=this.gpuPathManager.unregisterPath(e);return this.gpuPathManager.updateUniforms(this.uniforms),t}getGPUPathManager(){return this.gpuPathManager}bindGPUPath(e,t,n={}){let r;r=typeof t==`number`?t:this.registerGPUPath(t);let i=this._meshesOf([e]);this._featureStyleManager.bindGPUPath(e,r,n,i);for(let e of i)e.frustumCulled=!1;return this.gpuPathManager.updateUniforms(this.uniforms),r}unbindGPUPath(e){let t=this._meshesOf([e]);this._featureStyleManager.unbindGPUPath(e,t),this.gpuPathManager.updateUniforms(this.uniforms)}setGPUPathProgress(e,t){let n=this._meshesOf([e]);this._featureStyleManager.setGPUPathProgress(e,t,n);for(let e of n)e.frustumCulled=!1}setGPUPathTime(e,t=!1){this.uniforms.uPathTime&&(this.uniforms.uPathTime.value=e),this._customPathTime=!t}getGPUPathTime(){return this.uniforms.uPathTime?.value??0}animateFeature(e,t,n){if(t.translation&&this.moveFeature(e,t.translation,n),t.rotation!=null&&this.rotateFeature(e,t.rotation,t.pivot,n),t.elevation!=null&&this.animator.to(this._ensureFeatureChannel(e,`elevation`),t.elevation,n),t.opacity!=null&&this.animator.to(this._ensureFeatureChannel(e,`opacity`),t.opacity,n),t.color&&(this._colorScratch.set(t.color),this.animator.to(this._ensureFeatureChannel(e,`color`),[this._colorScratch.r,this._colorScratch.g,this._colorScratch.b],n)),t.hidden!=null){let n=this._featureStyleManager.getFeatureStyle(e)??{};this.setFeatureStyle(e,{...n,hidden:t.hidden})}}animateFeatures(e,t,n){let r=n?.stagger??0;if(r<=0){for(let r of e)this.animateFeature(r,t,n);return}let i=n?.delay??0;for(let a=0;a<e.length;a++)this.animateFeature(e[a],t,{...n,delay:i+a*r})}setMode(e,t={}){let n=Math.max(0,t.duration??300),r=Math.min(1,Math.max(.05,t.dim??.35));if(this.style.mode===e)return Promise.resolve();if(n<=0)return this.setStyle({mode:e}),Promise.resolve();let i=++this._modeGen;return new Promise(t=>{this.animator.to(`style.fade`,r,{duration:n,easing:`easeInOutQuad`,onComplete:()=>{i===this._modeGen?(this.setStyle({mode:e}),this.animator.to(`style.fade`,1,{duration:n,easing:`easeInOutQuad`,onComplete:t})):t()}})})}_ensureFeatureChannel(e,t){let n=`feature.${e}.${t}`;if(this.animator.has(n))return n;let r=t===`translation`||t===`color`||t===`rotation`?{dim:3,read:n=>{if(t===`translation`){let t=this._featureStyleManager.getFeatureStyle(e)?.translation;n[0]=t?.[0]??0,n[1]=t?.[1]??0,n[2]=t?.[2]??0}else if(t===`rotation`){let t=this._featureStyleManager.getFeatureStyle(e)?.rotation,r=Ws(t);n[0]=r[0],n[1]=r[1],n[2]=r[2]}else{let t=this._featureStyleManager.getFeatureStyle(e)?.color??this.style.colorA;this._colorScratch.set(t),n[0]=this._colorScratch.r,n[1]=this._colorScratch.g,n[2]=this._colorScratch.b}},write:n=>{let r=this._meshesOf([e]),i=this._featureStyleManager.getFeatureStyle(e)??{};if(t===`translation`){this._featureStyleManager.setFeatureStyle(e,{...i,translation:[n[0],n[1],n[2]]},r);let t=Math.abs(n[0])>1e-6||Math.abs(n[1])>1e-6||Math.abs(n[2])>1e-6,a=Ws(i.rotation),o=Math.abs(a[0])>1e-6||Math.abs(a[1])>1e-6||Math.abs(a[2])>1e-6;for(let e of r)e.frustumCulled=!(t||o)}else if(t===`rotation`){this._featureStyleManager.setFeatureStyle(e,{...i,rotation:[n[0],n[1],n[2]]},r);let t=Math.abs(n[0])>1e-6||Math.abs(n[1])>1e-6||Math.abs(n[2])>1e-6,a=i.translation??[0,0,0],o=Math.abs(a[0])>1e-6||Math.abs(a[1])>1e-6||Math.abs(a[2])>1e-6;for(let e of r)e.frustumCulled=!(t||o)}else{let t=this._colorScratch.setRGB(n[0],n[1],n[2]);this._featureStyleManager.setFeatureStyle(e,{...i,color:`#${t.getHexString()}`},r)}}}:{dim:1,read:n=>{let r=this._featureStyleManager.getFeatureStyle(e);n[0]=(t===`elevation`?r?.elevation:r?.opacity)??+(t===`opacity`)},write:n=>{let r=this._featureStyleManager.getFeatureStyle(e)??{},i=t===`elevation`?{...r,elevation:n[0]}:{...r,opacity:n[0]};this._featureStyleManager.setFeatureStyle(e,i,this._meshesOf([e]))}};return this.animator.register(n,r),n}_releaseFeatureChannels(e){for(let t of eu)this.animator.unregister(`feature.${e}.${t}`);let t=`feature.${e}.path`;this.animator.unregister(t),this._pathSpecs.delete(t)}getFeatureStyle(e){return this._featureStyleManager.getFeatureStyle(e)}getFeatureStyles(){return this._featureStyleManager.getFeatureStyles()}removeFeatureStyle(e){this._releaseFeatureChannels(e),this._featureStyleManager.removeFeatureStyle(e,this._meshesOf([e]))}clearFeatureStyles(){for(let e of this._featureStyleManager.getFeatureStyles().keys())this._releaseFeatureChannels(e);this._featureStyleManager.clearFeatureStyles()}setAttributeSource(e){this.attributeQuery=e?new tn({...e,authenticate:e.authenticate??this._authenticate}):null}getLoadedSmids(){return[...this._smidMeshes.keys()]}auditBatches(){let e=this._featureStyleManager.auditBatches(this._picks.pickables.values());return e.smids=this._smidMeshes.size,e}getThematicField(){return this._featureStyleManager.thematicField}setThematicColors(e,t=`custom`){this._featureStyleManager.setThematicColors(e,t)}clearThematic(){this._featureStyleManager.clearThematicColors()}getFilterField(){return this._featureStyleManager.fieldFilter?.field??null}filterByField(e){return this._featureStyleManager.filterByField(e,this.attributeQuery,this.getLoadedSmids())}clearFieldFilter(){this._featureStyleManager.clearFieldFilter()}getElevationField(){return this._featureStyleManager.elevationField}elevateByField(e){return this._featureStyleManager.elevateByField(e,this.attributeQuery,this.getLoadedSmids())}setThematicElevation(e,t=`custom`){this._featureStyleManager.setThematicElevation(e,t)}clearThematicElevation(){this._featureStyleManager.clearThematicElevation()}colorByField(e){return this._featureStyleManager.colorByField(e,this.attributeQuery,this.getLoadedSmids())}setFilter(e){this._featureStyleManager.setFilter(e,this.uniforms)}getFilter(){return this._featureStyleManager.filter}clearFilter(){this._featureStyleManager.clearFilter(this.uniforms)}setGroundMode(e){this.groundManager.setMode(e),this._requestRepaint()}setGroundOpacity(e){this.groundManager.setOpacity(e),this._requestRepaint()}setExcavationBounds(e){this.groundManager.setExcavationBounds(e),this._requestRepaint()}setGroundOcclude(e){this.groundManager.setOcclude(e),this._requestRepaint()}_isFeatureHidden(e,t){if(e==null)return!1;let n=this._featureStyleManager.fieldFilter;if(n){let t=n.matched.has(e);if(n.mode===`keep`?!t:t)return!0}let r=this._featureStyleManager.filter;return!!(r&&(r.include&&r.include.length>0&&!r.include.includes(e)||r.exclude&&r.exclude.length>0&&r.exclude.includes(e))||this._featureStyleManager.featureStyles.get(e)?.hidden)}getAllMeshes(){let e=[];for(let t of this._picks.pickables.values())e.push(t.mesh);return e}_meshesOf(e){let t=new Set;for(let n of e){let e=this._smidMeshes.get(n);if(e)for(let n of e)t.add(n)}return t}flushOverrides(){this._featureStyleManager.flushOverrides()}_applyOverridesToMesh(e){this._featureStyleManager.applyOverridesToMesh(e)}removeDataset(e){if(this.datasets.get(e)){this._sel.selection?.datasetId===e&&this.select(null),this._datasetManager.removeDataset(e,this.scene,this.geo,e=>{e.root.traverse(e=>{let t=e,n=t.userData;n.pickId!=null&&(this._picks.pickables.delete(n.pickId),this._releasePickId(n.pickId),n.pickId=void 0),this._unindexMeshSmids(t),this._heights.remove(t),t.geometry?.dispose?.();let r=Kl(t);r&&r.dispose(),lc(t.material)&&t.material.dispose(),this._featureStyleManager.disposeMesh(t)})});for(let[t,n]of this._picks.pickables)n.datasetId===e&&this._picks.pickables.delete(t);this.onStats(this.stats),this._requestRepaint()}}clearDatasets(){for(let e of[...this.datasets.keys()])this.removeDataset(e)}setDatasetVisible(e,t){this._datasetManager.setDatasetVisible(e,t),!t&&this._sel.selection?.datasetId===e&&this.select(null),this._requestRepaint()}_registerTile(e,t){let n=e.sphere?.center??this._localCenterOf(e.group);if(this._perTilePlacement&&n&&this._applyTilePlacement(e.group,n,t),e.group.matrixAutoUpdate){let t=this.sceneAnchor;if(t){let n=t.meterInMercatorEast??t.meterInMercator,r=t.meterInMercatorNorth??t.meterInMercator,i=t.meterInMercatorUp??n,a=e.sphere?[e.sphere.center.x,e.sphere.center.y,e.sphere.center.z]:[0,0,0];this._updateTileUniforms(e.group,a,[1/n,1/r,1/i])}}t.root.add(e.group),e.group.updateMatrixWorld(!0);let r=e.group.userData.hasNativeEdges===!0,i=this._edges.useNativeEdges(r);for(let n of e.group.children){if(n.isLineSegments&&n.userData.isEdgeLines){this._edges.registerNativeLine(n,i&&this._edges.enabled);continue}let a=ql(n),o=n;if(!o.isMesh&&!a)continue;a&&this._pointClouds.add(n),a&&this._splats.markDirty();let s=o.userData;if(s.pickId=this._allocPickId(),s.datasetId=t.id,s.nativeEdges=i,s.nativeEdgesRaw=r,this._picks.pickables.set(s.pickId,{datasetId:t.id,mesh:o,tile:e.tile,skeletonName:s.skeletonName??``}),this._indexMeshSmids(o),this._heights.add(o),this._edges.autoDecorate(o,t,i),a)this._applyPointCloudStyle(n);else{let e=Kl(o);if(e){let t=Jl(this.style.opacity),n=this.style.depthWrite!==!1;sa(e,t<.999,n),e.userData.uFlatShading&&(e.userData.uFlatShading.value=this.style.shading===`smooth`?0:1),this._featureStyleManager.applyOverridesToMesh(o),this._startTileFade(o,e)}}this._sel.replayOnto(o)}}_localCenterOf(e){if(!e.children.length)return null;let n=new t.Box3().setFromObject(e);if(n.isEmpty())return null;let r=n.getCenter(new t.Vector3);return!Number.isFinite(r.x)||!Number.isFinite(r.y)||!Number.isFinite(r.z)?null:{x:r.x,y:r.y,z:r.z}}_applyTilePlacement(e,n,r){var i;let a=this.sceneAnchor;if(!a||!r.anchor)return;let o=Hl({center:n,datasetAnchor:r.anchor,sceneAnchor:a,datasetOffset:r.offset,geo:this.geo});if(!o)return;let s=o.scaleEast??o.scale,c=o.scaleNorth??o.scale,l=s;e.matrixAutoUpdate=!1,e.matrix.makeScale(s,c,l),e.matrix.setPosition(o.position[0]-s*o.pivot[0],o.position[1]-c*o.pivot[1],o.position[2]-l*o.pivot[2]),e.matrixWorldNeedsUpdate=!0,e.userData.tileCenter={x:n.x,y:n.y,z:n.z},((i=e.userData).placementInverse??(i.placementInverse=new t.Matrix4)).copy(e.matrix).invert();let u=a.meterInMercatorEast??a.meterInMercator,d=a.meterInMercatorNorth??a.meterInMercator,f=a.meterInMercatorUp??u,p=o.invTileScale??[1/(u*s),1/(d*c),1/(f*l)];this._updateTileUniforms(e,o.pivot,p)}_updateTileUniforms(e,t,n){e.traverse(e=>{let r=e;if((e.isMesh||e.isPoints)&&e.material){let e=Array.isArray(r.material)?r.material:[r.material];for(let r of e){let e=r.userData?.uTilePivot,i=r.userData?.uInvTileScale;e?.value&&e.value.set(t[0],t[1],t[2]),i?.value&&i.value.set(n[0],n[1],n[2])}}})}_toCanonicalScene(e,t){if(!this._perTilePlacement||!t)return e;let n=t.parent;for(;n&&!n.userData.tileCenter;)n=n.parent;if(!n)return e;let r=n.parent;return r?e.clone().sub(r.position).applyMatrix4(n.userData.placementInverse??Xl.copy(n.matrix).invert()).add(r.position):e}_reapplyTilePlacements(){for(let e of this._datasetManager.values())if(e.anchor)for(let t of e.root.children){let n=t.userData.tileCenter;n&&this._applyTilePlacement(t,n,e)}}_startTileFade(e,t){let n=this.style.fadeIn??0;if(n<=0)return;let r=t.userData.uTileFade;if(!r)return;r.value=0,t.transparent=!0,t.depthWrite=!0;let i=`tile.${this._tileFadeSeq++}.fade`;e.userData.tileFadeKey=i,this.animator.register(i,{dim:1,read:e=>{e[0]=r.value},write:e=>{r.value=e[0]}}),this.animator.to(i,1,{duration:n,easing:`easeOutQuad`,onComplete:()=>{r.value=1,e.userData.tileFadeKey=void 0,this.animator.unregister(i),sa(t,this._opacityTransparent,this.style.depthWrite!==!1),this._featureStyleManager.applyOverridesToMesh(e),this._requestRepaint()}})}_replaySelectionOnto(e){this._sel.replayOnto(e)}_unregisterTile(e,t){e.group.traverse(e=>{let t=e;if(e.isLineSegments&&t.userData?.isEdgeLines&&this._edges.unregisterNativeLine(e),ql(e)&&this._pointClouds.delete(e),t.userData?.tileFadeKey&&(this.animator.unregister(t.userData.tileFadeKey),t.userData.tileFadeKey=void 0),t.userData?.pickId!=null&&(this._picks.pickables.delete(t.userData.pickId),this._releasePickId(t.userData.pickId),t.userData.pickId=void 0),t.isMesh){this._sel.selectedMeshes.includes(t)&&(this._sel.selectedMeshes=this._sel.selectedMeshes.filter(e=>e!==t));let e=this._sel.selection;if(e&&e.mesh===t){let n=e.smid,r=n==null?this._sel.selectedMeshes.find(e=>e!==t&&e.parent&&e.parent.visible)??this._sel.selectedMeshes.find(e=>e!==t&&e.parent):[...this._smidMeshes.get(n)??[]].find(e=>e!==t&&e.parent);r?(this._sel.selection={...e,mesh:r},this._sel.replayOnto(r)):this.select(null)}this._unindexMeshSmids(t),this._heights.remove(t),this._featureStyleManager.disposeMesh(t),Kl(t)?.dispose?.()}lc(t.material)?t.material.dispose():t.material&&(Array.isArray(t.material)?t.material.forEach(e=>e?.dispose?.()):t.material.dispose?.()),t.geometry?.dispose?.()}),t.root.remove(e.group)}setOpacity(e,t){this.setStyle({opacity:e},t)}setStyle(e={},t){Object.assign(this._styleTarget,e);let n=t?.duration??0,r=n>0||!!t?.spring,i=e;if(`edges`in e){let{edges:n,...a}=e;if(i=a,this.setEdges(n,r?t:void 0),Object.keys(i).length===0){this._requestRepaint();return}}let a=[],o={};for(let e of Object.keys(i))r&&this.animator.has(`style.${String(e)}`)?a.push(String(e)):o[e]=i[e];Object.keys(o).length>0&&(Object.assign(this.style,o),this._applyStyleEffects(o));for(let e of a)this.animator.to(`style.${e}`,this._animTargetOf(e,i),{...t,duration:n});this._requestRepaint()}getStyle(){return{...this._styleTarget,modeLabel:la[this._styleTarget.mode]}}_animTargetOf(e,t){let n=t[e];return this._animDimOf(e)===1?Number(n):(this._colorScratch.set(String(n)),[this._colorScratch.r,this._colorScratch.g,this._colorScratch.b])}_animDimOf(e){return $l.includes(e)?3:1}_registerAnimChannels(){for(let e of Zl)this.animator.register(`style.${e}`,{dim:1,read:t=>{t[0]=Number(this.style[e]??Ql[e]??0)},write:t=>{this.style[e]=t[0],this._onStyleChannelWrote(e)}});for(let e of $l)this.animator.register(`style.${e}`,{dim:3,read:t=>{let n=this._uniformColorOf(e);t[0]=n.r,t[1]=n.g,t[2]=n.b},write:t=>{let n=this._uniformColorOf(e);n.setRGB(t[0],t[1],t[2]),this.style[e]=`#${n.getHexString()}`,this._onStyleChannelWrote(e)}});this.animator.register(`style.edgeFade`,{dim:1,read:e=>{e[0]=this.uniforms.uEdgeFade?.value??1},write:e=>{this.uniforms.uEdgeFade&&(this.uniforms.uEdgeFade.value=e[0]),this._edges.syncStyle()}}),this.animator.register(`style.fade`,{dim:1,read:e=>{e[0]=this.uniforms.uFade?.value??1},write:e=>{this.uniforms.uFade&&(this.uniforms.uFade.value=e[0]),this._requestRepaint()}})}_onStyleChannelWrote(e){e===`opacity`?this._applyOpacity():(this._applyStyleUniforms(),(e===`edgeColor`||e===`edgeWidth`||e===`edgeOpacity`||e===`edgeOffset`||e===`edgeHullWidth`)&&this._edges.refreshLines())}_uniformColorOf(e){let t=this.uniforms;switch(e){case`colorA`:return t.uColorA.value;case`colorB`:return t.uColorB.value;case`colorC`:return t.uColorC.value;case`selectColor`:return t.uSelColor.value;case`edgeColor`:return this.edgeMaterial.uniforms.uColor.value;default:return t.uColorA.value}}_applyStyleEffects(e){this._applyStyleUniforms(),(`opacity`in e||`depthWrite`in e)&&this._applyOpacity(),`mode`in e&&this._applyPointCloudStyles(),`shading`in e&&this._applyShading(),(`edgeThreshold`in e||`forceCpuEdges`in e)&&this._edges.enabled?(this._edges.disposeEdgeGeometry(),this.setEdges(this.style.edges)):(`edgeColor`in e||`edgeWidth`in e||`opacity`in e||`edgeOpacity`in e||`edgeOffset`in e||`edgeHullWidth`in e)&&this._edges.refreshLines(),this._sel.selection&&(`outline`in e||`outlineStyle`in e?this.select(this._sel.selection,{silent:!0}):this._sel.syncStyle())}_applyStyleUniforms(){let e=this.uniforms,t=this.style;e.uMode.value=t.mode,e.uColorA.value.set(t.colorA),e.uColorB.value.set(t.colorB),e.uColorC.value.set(t.colorC),e.uSelColor.value.set(t.selectColor),e.uFloorHeight.value=t.floorHeight;let n=t.selectMode??$.OVERLAY;e.uSelMode&&(e.uSelMode.value=n===$.REPLACE?0:n===$.MULTIPLY?2:n===$.GLOW_ONLY?3:1),e.uSelOpacity&&t.selectOpacity!=null&&(e.uSelOpacity.value=t.selectOpacity),e.uSelEmissive&&t.selectEmissive!=null&&(e.uSelEmissive.value=t.selectEmissive),e.uSelElevation&&t.selectElevation!=null&&(e.uSelElevation.value=t.selectElevation),e.uDimFactor&&t.dimFactor!=null&&(e.uDimFactor.value=t.dimFactor),e.uRoofThreshold&&t.roofThreshold!=null&&(e.uRoofThreshold.value=t.roofThreshold),e.uTexMix&&t.texMix!=null&&(e.uTexMix.value=t.texMix),e.uAmbientGain&&t.ambientGain!=null&&(e.uAmbientGain.value=t.ambientGain),e.uMetalness&&(e.uMetalness.value=t.metalness??-1),e.uRoughness&&(e.uRoughness.value=t.roughness??-1),e.uOpacity&&t.opacity!=null&&(e.uOpacity.value=Jl(t.opacity)),this.outlineMaterial&&(this.outlineMaterial.uniforms.uElevation&&t.selectElevation!=null&&(this.outlineMaterial.uniforms.uElevation.value=t.selectElevation),t.outlineWidth!=null&&(this.outlineMaterial.uniforms.uWidth.value=t.outlineWidth),t.outlineColor==null?this.outlineMaterial.uniforms.uColor.value.set(t.selectColor):this.outlineMaterial.uniforms.uColor.value.set(t.outlineColor))}_applyOpacity(){let e=Jl(this.style.opacity);this.uniforms.uOpacity&&(this.uniforms.uOpacity.value=e);let t=e<.999;if(t!==this._opacityTransparent){this._opacityTransparent=t;let e=this.style.depthWrite!==!1;for(let n of this._picks.pickables.values()){if(ql(n.mesh))continue;let r=Kl(n.mesh);r&&(r.userData.uBatchTexActive?.value||(r.userData.uTileFade?.value??1)<1||sa(r,t,e))}}for(let e of this._pointClouds)this._applyPointCloudStyle(e);this._edges.syncStyle(),this._requestRepaint()}_applyPointCloudStyle(e,t=this._sel.selectedMeshes.includes(e)){cc(e,this.style,this.uniforms,t)}_applyPointCloudStyles(){for(let e of this._pointClouds)this._applyPointCloudStyle(e);this._requestRepaint()}_applyShading(){let e=this.style.shading===`smooth`?0:1;for(let t of this._picks.pickables.values()){let n=Kl(t.mesh)?.userData.uFlatShading;n&&n.value!==e&&(n.value=e)}this._requestRepaint()}setMaterialQuality(e){this._materialQuality=$i(e)??`pbr`,this._datasetManager.setDefaultMaterialQuality(this._materialQuality),this._rebuildStyledMaterials(),this._requestRepaint()}get lodTransition(){return this._lodTransition}setLodTransition(e){this._lodTransition!==e&&(this._lodTransition=e,this._datasetManager.setDefaultLodTransition(e),this.triggerRepaint())}get materialQuality(){return this._materialQuality??ta()}setMotionBlur(e){this._motionBlurCfg=_c(e),this._motionBlurCfg||(this._motionBlur?.dispose(),this._motionBlur=null),this.triggerRepaint()}setDepthMode(e){let t=Gl(e);this._depthMode!==t&&(this._depthMode=t,this.triggerRepaint())}get depthMode(){return this._depthMode}resolveDepthMode(){if(this._depthMode===`clear`)return`clear`;if(this._depthMode===`scene`)return`scene`;if(this.groundManager&&this.groundManager.mode!==`none`)return`clear`;for(let e of this._datasetManager.datasets.values()){if(!e.visible)continue;if(e.options.depthMode===`clear`)return`clear`;if(e.options.depthMode===`scene`)continue;if(e.tileset?.isS3MV1)return`clear`;let t=e.tileset?.config;if(t){let e=`${t.fileType??``} ${t.dataType??``} ${t.datasetType??``} ${t.cacheType??``} ${t.fileExtentName??``}`;if(/osgb|oblique|ground|dem|tin|terrain/i.test(e))return`clear`}if(e.options.configUrl&&/osgb|oblique/i.test(e.options.configUrl))return`clear`}return`scene`}get motionBlur(){return this._motionBlurCfg?{...this._motionBlurCfg}:null}setColorPipeline(e,t={}){let n=ia(e)??`linear`;if(n===this.colorPipeline)return Promise.resolve();let r=Math.max(0,t.duration??0);if(r<=0)return this._applyRenderProfile({colorPipeline:n}),Promise.resolve();let i=Math.min(1,Math.max(.05,t.dim??.35)),a=++this._pipelineGen;return new Promise(e=>{this.animator.to(`style.fade`,i,{duration:r,easing:`easeInOutQuad`,onComplete:()=>{a===this._pipelineGen?(this._applyRenderProfile({colorPipeline:n}),this.animator.to(`style.fade`,1,{duration:r,easing:`easeInOutQuad`,onComplete:e})):e()}})})}get colorPipeline(){return this._colorPipeline??ra()}_textureOptions(){return{srgbDecode:this.colorPipeline!==`direct`,maxSize:this.options.maxTextureSize??1/0,anisotropyCap:this.options.anisotropyCap??1/0}}_applyRenderProfile(e,t=!1){let n=this.colorPipeline;e.colorPipeline!==void 0&&(this._colorPipeline=ia(e.colorPipeline)??`linear`),e.anisotropyCap!==void 0&&(this.options.anisotropyCap=e.anisotropyCap);let r=this._textureOptions();this._datasetManager.setRenderProfile({colorPipeline:this.colorPipeline,textureOptions:r}),!t&&(this.colorPipeline!==n&&this._rebuildStyledMaterials(),this._syncCachedTextures(r),this._requestRepaint())}_syncCachedTextures(e){let n=e.srgbDecode?t.SRGBColorSpace:t.NoColorSpace;for(let t of this.datasets.values()){let r=t.tileset?.textureCache;if(r){for(let e of r.values())e.colorSpace!==n&&(e.colorSpace=n,e.needsUpdate=!0);Ai(r.values(),e.anisotropyCap??1/0)}}}_rebuildStyledMaterials(){let e=[`uSelBatch`,`uSelWhole`,`uBatchTex`,`uBatchTex2`,`uBatchTexWidth`,`uBatchTexActive`,`uTileFade`];for(let t of this._picks.pickables.values()){let n=t.mesh,r=n.material;if(Array.isArray(r))continue;let i=r;if(!i?.userData?.isStyled||!i.userData?.s3mOpts)continue;let a=i.userData.s3mOpts,o=oa({...a,uniforms:this.uniforms,materialQuality:this.materialQuality,colorPipeline:this.colorPipeline});for(let t of e){let e=i.userData[t],n=o.userData[t];e&&n&&(n.value=e.value)}n.material=o,i.dispose()}}async prewarmShading(){if(this._shadingPrewarmed||this._prewarming)return;let e=this.renderer,t=this.scene,n=this.camera;if(!e||!t||!n)return;let r=!1;for(let e of this._picks.pickables.values())if(Kl(e.mesh)){r=!0;break}if(r){this._shadingPrewarmed=!0;try{let r=e;typeof r.compileAsync==`function`?await r.compileAsync(t,n):e.compile(t,n)}catch{}this._requestRepaint()}}_addMeshHeight(e){this._heights.add(e)}_removeMeshHeight(e){this._heights.remove(e)}_indexMeshSmids(e){let t=e.userData.geoRef?.pickInfo;if(t)for(let n of Object.keys(t)){let t=Number(n);if(!Number.isFinite(t)||t<0)continue;let r=this._smidMeshes.get(t);r||this._smidMeshes.set(t,r=new Set),r.add(e)}}_unindexMeshSmids(e){let t=e.userData.geoRef?.pickInfo;if(t)for(let n of Object.keys(t)){let t=Number(n),r=this._smidMeshes.get(t);r&&(r.delete(e),r.size===0&&this._smidMeshes.delete(t))}}get _edgesEnabled(){return this._edges.enabled}get _edgeModes(){return this._edges.modes}get _gpuEdge(){return this._edges.gpuEdge}set _gpuEdge(e){this._edges.gpuEdge=e}_ensureEdges(e){this._edges.ensureEdges(e)}_removeEdges(e){this._edges.removeEdges(e)}setEdges(e,t){this._edges.setEdges(e,t)}loadCreases(e){return this._edges.loadCreases(e)}clearCreases(){this._edges.clearCreases()}getRayAt(e,t){return this._picks.getRayAt(e,t)}pick(e,t){return this._picks.pick(e,t)}pickPosition(e,t){return this._picks.pickPosition(e,t)}drillPick(e,t,n=10){return this._picks.drillPick(e,t,n)}getFeatureBounds(e){return this._picks.getFeatureBounds(e)}_sceneFromLngLat(e){let t=this.sceneAnchor;if(!t)return[0,0,0];let n=t.meterInMercatorEast??t.meterInMercator,r=t.meterInMercatorNorth??t.meterInMercator,i=ln(this.geo,e.lng,e.lat,e.altitude);return[(i.x-t.x)/n,-(i.y-t.y)/r,e.altitude-(t.altitude??0)]}lngLatToPoint(e){return this._sceneFromLngLat(e)}pointToLngLat(e){return this._lngLatFromScene(e)}_lngLatFromScene(e){let t=this.sceneAnchor;if(!t)return{lng:0,lat:0,altitude:e[2]};let n=t.meterInMercatorEast??t.meterInMercator,r=t.meterInMercatorNorth??t.meterInMercator,[i,a]=un(this.geo,e[0]*n+t.x,-e[1]*r+t.y);return{lng:i,lat:a,altitude:e[2]+(t.altitude??0)}}measureDistance(e,t){return ul(this._sceneFromLngLat(e),this._sceneFromLngLat(t))}measurePolyline(e){let t=e.map(e=>this._sceneFromLngLat(e));return{length3D:al(t),lengthHorizontal:ol(t)}}measurePolygon(e){let t=e.map(e=>this._sceneFromLngLat(e));return{area3D:cl(t),areaHorizontal:ll(t),perimeter:sl(t)}}lineOfSight(e,t,n={}){return dl(this._sceneFromLngLat(e),this._sceneFromLngLat(t),(e,t,n)=>{let r=this._picks.raycastDistance(e,t,n);return r?{distance:r.distance,point:r.point}:null},n)}setClipping(e){this._clip=e,this._applyClipping(),this._requestRepaint()}get clipping(){return this._clip}_applyClipping(){let e=this.renderer;e&&(e.clippingPlanes=this._clip?yl(this._clip).map(e=>new t.Plane(new t.Vector3(e.normal[0],e.normal[1],e.normal[2]),e.constant)):[])}_depthCtx(){return{renderer:()=>this.renderer,scene:()=>this.scene,camera:()=>this.camera}}skyline(e={}){let t=Rl(this._depthCtx(),e.width??640,e.height??360,e.include);return t?Al({rgba:t.rgba,width:t.width,height:t.height,inverseViewProj:t.inverseViewProj,cameraPos:t.cameraPos,step:e.step}):null}viewshed(e){let t=e.eyeHeight??1.7,n=this._sceneFromLngLat({...e.origin,altitude:e.origin.altitude+t}),r=e.size??128,i=Vl(this._depthCtx(),n,r,e.radius,e.include);return i?jl(n,Ml(i,r,e.radius),{radius:e.radius,grid:e.grid,groundZ:0}):null}_intersectMeshAtRay(e,t,n){return this._picks.intersectMeshAtRay(e,t,n)}_buildPickResult(e,t,n,r){return this._picks.buildPickResult(e,t,n,r)}_buildSplatPickResult(e,t,n,r){return this._picks.buildSplatPickResult(e,t,n,r)}_instanceFeature(e,t,n){return this._picks.instanceFeature(e,t,n)}_instanceBox(e,t){return this._picks.instanceBox(e,t)}_allocPickId(){return this._picks.allocPickId()}_releasePickId(e){this._picks.releasePickId(e)}get _pickables(){return this._picks.pickables}select(e,t={}){this._sel.select(e,t)}_syncSelectionStyle(){this._sel.syncStyle()}get _selection(){return this._sel.selection}get _selectedMeshes(){return this._sel.selectedMeshes}get _selectionEdgeMeshes(){return this._sel.selectionEdgeMeshes}_updateLineResolution(e){let t=e.width||1,n=e.height||1,r=e.clientWidth||t;this.lineShared.uResolution.value.set(t,n),this.lineShared.uDpr.value=Math.max(1,t/r)}get lodRangeScale(){return this._lodRangeScale}get lodPixelRatioCap(){return this._lodPixelRatioCap}setLodPixelRatioCap(e){let t=e>0?e:1/0;this._lodPixelRatioCap=t,this.options.lodPixelRatioCap=t,this._requestRepaint()}_lodScreenHeight(e){let t=this._lodPixelRatioCap;if(!Number.isFinite(t))return e;let n=this.canvas?.clientHeight??0;return n<=0?e:Math.min(e,n*t)}get maxImageCache(){return this.options.maxImageCache??128}setMaxImageCache(e,t){let n=Number.isFinite(e)?Math.max(1,Math.floor(e)):128;if(t){let e=this.datasets.get(t);e?.tileset&&(e.tileset.maxImageCache=n)}else{this.options.maxImageCache=n;for(let e of this.datasets.values())e.tileset&&(e.tileset.maxImageCache=n)}this._requestRepaint()}get maxTriangles(){return this.options.maxTriangles??1/0}setMaxTriangles(e,t){let n=e>0?e:1/0;if(t){let e=this.datasets.get(t);e?.tileset&&e.tileset.setMaxTriangles(n)}else{this.options.maxTriangles=n;for(let e of this.datasets.values())e.tileset&&e.tileset.setMaxTriangles(n)}}get maxMemory(){return this.options.maxMemory??1/0}setMaxMemory(e,t){let n=Number.isFinite(e)&&e>0?e:1/0;if(t){let e=this.datasets.get(t);e?.tileset&&e.tileset.setMaxMemory(n)}else{this.options.maxMemory=n;for(let e of this.datasets.values())e.tileset&&e.tileset.setMaxMemory(n)}}get anisotropyCap(){return this.options.anisotropyCap??1/0}setAnisotropyCap(e){let t=Number.isFinite(e)&&e>0?Math.max(1,e):1/0;this.options.anisotropyCap=t,Oi(this.renderer?.capabilities.getMaxAnisotropy?.()??1,t),this._applyRenderProfile({anisotropyCap:t})}get maxTextureSize(){return this.options.maxTextureSize??1/0}setMaxTextureSize(e){let t=Number.isFinite(e)&&e>=1?e:1/0;this.options.maxTextureSize=t,ji(t),this._datasetManager.setRenderProfile({textureOptions:this._textureOptions()}),this._requestRepaint()}get cullRefine(){return this._cullRefine}set cullRefine(e){this.setCullRefine(e)}setCullRefine(e){let t=!!e;this._cullRefine!==t&&(this._cullRefine=t,this._requestRepaint())}setLodRangeScale(e,t){if(!(e<=0)){if(t){let n=this.datasets.get(t);n?.tileset&&(n.tileset.lodRangeScale=e)}else{this._lodRangeScale=e;for(let t of this.datasets.values())t.tileset&&(t.tileset.lodRangeScale=e)}this._requestRepaint()}}_sortSplats(){this._splats.sort(this.camera,this._pointClouds)}_renderMotionBlur(e,t){let n=this.renderer,r=this.scene,i=this.camera,a=this._motionBlurCfg;return!n||!r||!i||!a||(this._motionBlur||(this._motionBlur=new Cc),!this._motionBlur.supported(n))?!1:(this._motionBlur.render(n,r,i,e,t,{mode:a.mode,damp:a.damp===`auto`?vc(this.fps):a.damp,maxOffset:a.maxOffset,mvp:this._frameMvp,mvpInverse:i.projectionMatrixInverse}),!0)}renderFrame(e){if(!this.renderer||!this.scene||!this.camera||!this.sceneAnchor||!this.canvas)return!1;let n=this.renderer.getContext();if(n&&typeof n.isContextLost==`function`&&n.isContextLost())return!1;if(this._prewarming)return!0;let r=this.animator.tick();this.flushOverrides();let i=this.canvas,a=this.sceneAnchor.meterInMercatorEast??this.sceneAnchor.meterInMercator,o=this.sceneAnchor.meterInMercatorNorth??this.sceneAnchor.meterInMercator,s=this.sceneAnchor.meterInMercatorUp??a;this._enuMatrix.set(a,0,0,this.sceneAnchor.x,0,-o,0,this.sceneAnchor.y,0,0,s,this.sceneAnchor.z,0,0,0,1);let c=this._frameMvp.fromArray(e.mvp);c.multiply(this._enuMatrix),this.camera.projectionMatrix.copy(c),this.camera.projectionMatrixInverse.copy(c).invert();let l=e.cameraEnu;this.camera.position.set(l[0],l[1],l[2]),this.camera.matrixWorld.setPosition(l[0],l[1],l[2]),this.camera.matrixWorldInverse.copy(this.camera.matrixWorld).invert(),this.groundManager.update(this.camera);let u=!1,d=this._lodScreenHeight(e.canvasHeight),f=null,p=null;this._cullRefine&&(f=this._frustum??(this._frustum=new t.Frustum),f.setFromProjectionMatrix(c),p=this._cullTestVec??(this._cullTestVec=new t.Vector3));for(let t of this.datasets.values()){if(!t.visible||!t.tileset)continue;let n=[l[0]-t.offset[0],l[1]-t.offset[1],l[2]-t.offset[2]],r;if(f&&p){let e=f,n=p,i=t.offset;r=(t,r,a)=>{let o,s,c,l=r;a?.group&&a.group.parent?(n.set(t.x,t.y,t.z).applyMatrix4(a.group.matrixWorld),o=n.x,s=n.y,c=n.z,l*=a.group.matrixWorld.getMaxScaleOnAxis()):(o=t.x+i[0],s=t.y+i[1],c=t.z+i[2]);let u=Math.max(l*.15,10),d=-(l+u),f=e.planes;for(let e=0;e<6;e++){let t=f[e];if(t.normal.x*o+t.normal.y*s+t.normal.z*c+t.constant<d)return!1}return!0}}t.tileset.update(n,e.fovRad,d,r)&&(u=!0)}this.style.mode===Q.DYNAMIC&&(this.uniforms.uTime.value+=.016*(this.style.speed??1)),this.gpuPathManager.updateUniforms(this.uniforms);let m=(this.uniforms.uPathTexActive?.value??0)>0;m&&!this._customPathTime&&this.uniforms.uPathTime&&(this.uniforms.uPathTime.value+=.016),this._updateLights(),this._updateLineResolution(i),wo(i.width,i.height),this.renderer.setViewport(0,0,i.width,i.height);let h=(this.uniforms.uOpacity?.value??1)>Yl?this.resolveDepthMode():`scene`;h===`clear`&&n&&(n.depthMask(!0),n.clear(n.DEPTH_BUFFER_BIT)),this.renderer.resetState(),(this.uniforms.uOpacity?.value??1)>Yl&&(this._sortSplats(),this._motionBlurCfg&&this._renderMotionBlur(i.width,i.height)||this.renderer.render(this.scene,this.camera),h!==`clear`&&this._edges.renderGpuEdges(i)),this._frame++;let g=performance.now();g-this._fps.last>500&&(this._fps.value=Math.round(this._frame*1e3/(g-this._fps.last)),this._frame=0,this._fps.last=g);let _=r||this.style.mode===Q.DYNAMIC||m||this.stats.loading>0||u;return this._prewarmShadingEnabled&&!this._shadingPrewarmed&&this._picks.pickables.size>0&&this.prewarmShading(),_}get fps(){return this._fps.value}get stats(){let e={tiles:0,loading:0,failed:0,meshes:0,vertices:0,triangles:0,datasets:this.datasets.size,drawCalls:0,programs:0,textures:0,geometries:0,degradations:[]},t=null;for(let n of this.datasets.values()){let r=n.tileset?.stats;if(r&&(e.tiles+=r.tiles,e.loading+=r.loading,e.failed+=r.failed,e.meshes+=r.meshes,e.vertices+=r.vertices,e.triangles+=r.triangles,r.degradations?.length)){t??(t=[]);for(let e of r.degradations)t.includes(e)||t.push(e)}}t&&(e.degradations=t);let n=this.renderer?.info;return n&&(e.drawCalls=n.render.calls,e.programs=n.programs?.length??0,e.textures=n.memory.textures,e.geometries=n.memory.geometries),e}getBounds(){let e=1/0,t=1/0,n=-1/0,r=-1/0;for(let i of this.datasets.values()){let a=Jo(i.tileset?.config?.geoBounds);a&&(e=Math.min(e,a.left),n=Math.max(n,a.right),t=Math.min(t,a.bottom),r=Math.max(r,a.top))}return isFinite(e)?[[e,t],[n,r]]:null}dispose(){this.unmount()}};b();var nu=class e{constructor(t={}){y(this,`id`,void 0),y(this,`options`,void 0),y(this,`pickable`,void 0),y(this,`onStats`,void 0),y(this,`onReady`,void 0),y(this,`onPick`,void 0),y(this,`onError`,void 0),y(this,`viewer`,void 0),y(this,`_projection`,`perspective`),y(this,`_projectionT`,0),y(this,`_orthoWarned`,!1),y(this,`_nearPlaneScale`,1),this.id=t.id??`s3m`,this.options=t,this.pickable=t.pickable!==!1,this._projection=t.projection===`orthographic`?`orthographic`:`perspective`,this._nearPlaneScale=e.normalizeNearPlaneScale(t.nearPlaneScale),this._projectionT=+(this._projection===`orthographic`),this.onStats=t.onStats??(()=>{}),this.onReady=t.onReady??(()=>{}),this.onPick=t.onPick??(()=>{}),this.onError=t.onError??(e=>console.warn(`[s3m]`,e));let{id:n,projection:r,nearPlaneScale:i,...a}=t;this.viewer=new tu({...a,onRequestRepaint:()=>this.requestRepaint(),getBearing:()=>this.getBearing(),onStats:e=>this.onStats(e),onReady:e=>this.onReady(e),onPick:e=>this.onPick(e),onError:e=>this.onError(e)})}getBearing(){return 0}mountViewer(e,t){this.viewer.renderer?this.viewer.restoreContext(t):this.viewer.mount(e,t)}unmountViewer(){this.viewer.unmount()}driveFrame(e){let t=this.viewer.renderFrame(e);return t&&this.requestRepaint(),t}setProjection(e,t){let n=e===`orthographic`?`orthographic`:`perspective`,r=+(n===`orthographic`),i=t?.duration??0,a=i>0||!!t?.spring;this._projection=n,this._orthoWarned=!1,a?(this._ensureProjectionChannel(),this.viewer.animator.to(`projection.t`,r,{...t,duration:i,easing:t?.easing??`easeInOutCubic`,onComplete:()=>{this._projectionT=r,this.requestRepaint()}}),this.requestRepaint()):(this.viewer.animator.has(`projection.t`)&&this.viewer.animator.cancel(`projection.t`),this._projectionT=r,this.requestRepaint())}get projection(){return this._projection}get projectionT(){return this._projectionT}_ensureProjectionChannel(){this.viewer.animator.has(`projection.t`)||this.viewer.animator.register(`projection.t`,{dim:1,read:e=>{e[0]=this._projectionT},write:e=>{this._projectionT=e[0],this.requestRepaint()}})}setNearPlaneScale(t){this._nearPlaneScale=e.normalizeNearPlaneScale(t),this.requestRepaint()}get nearPlaneScale(){return this._nearPlaneScale}static normalizeNearPlaneScale(e){return typeof e!=`number`||!Number.isFinite(e)?1:e>0&&e<1?e:1}},ru=1e-4;function iu(e,t){let n=e.elements;for(let e=0;e<16;e++){let r=Math.max(1,Math.abs(n[e]),Math.abs(t[e]));if(Math.abs(n[e]-t[e])>ru*r)return!1}return!0}function au(e){let t=e.elements,n=1;for(let e=0;e<16;e++){let r=Math.abs(t[e]);r>n&&(n=r)}let r=1e-6*n;return Math.abs(t[3])<r&&Math.abs(t[7])<r&&Math.abs(t[11])<r&&Math.abs(t[15]-1)<r}function ou(e,t){return t>0&&Math.abs(e.elements[5]*Math.tan(t/2)-1)<.001}function su(e){if(!e||typeof e!=`object`)return null;let t=e;return t.defaultProjectionData?.projectionMatrix??t.projectionMatrix??null}function cu(e){let t={nearZ:null,farZ:null};if(!e||typeof e!=`object`)return t;let n=e,r=n.defaultProjectionData,i=e=>{let t=n[e];if(typeof t==`number`&&Number.isFinite(t))return t;let i=r?.[e];return typeof i==`number`&&Number.isFinite(i)?i:null};return{nearZ:i(`nearZ`),farZ:i(`farZ`)}}function lu(e,t){if(e&&typeof e==`object`){let t=e.fov;if(typeof t==`number`&&Number.isFinite(t)&&t>0)return t}return typeof t==`number`&&Number.isFinite(t)&&t>0?t:null}function uu(e,n){let r=e.projectionMatrix;if(!r||r.length<16)return null;let i=new t.Matrix4().fromArray(Array.from(r)),a=new t.Matrix4().fromArray(Array.from(e.mvp));if(i.determinant()===0||!ou(i,n.fov))return null;let o=i.clone().invert().multiply(a);if(!iu(i.clone().multiply(o),Array.from(e.mvp))||!au(o)||!ou(i,n.fov))return null;let{distance:s,fov:c,aspect:l}=n;if(!(s>0)||!(c>0)||!(l>0))return null;let u=s*Math.tan(c/2),d=u*l,f=e.nearZ!=null&&e.nearZ>0?e.nearZ:1,p=e.farZ!=null&&e.farZ>f?e.farZ:s*4+1e3;p>f||(p=f+1e3);let m=new t.OrthographicCamera(-d,d,u,-u,f,p);return m.updateProjectionMatrix(),{matrix:m.projectionMatrix.clone().multiply(o),view:o}}function du(e,n){if(!(n>0)||n>=1)return null;let r=e.projectionMatrix;if(!r||r.length<16)return null;let i=new t.Matrix4().fromArray(Array.from(r));if(!Number.isFinite(i.determinant())||i.determinant()===0||Math.abs(i.elements[11]+1)>1e-6)return null;let a=e.nearZ!=null&&e.nearZ>0?e.nearZ:NaN,o=e.farZ!=null&&e.farZ>a?e.farZ:NaN;if(!(a>0)||!(o>a)){let e=-i.elements[10];if(!(e>1)||(a=-i.elements[14]/(e+1),o=a*(e+1)/(e-1),!(a>0)||!(o>a)))return null}let s=a*n;if(!(s>0)||!(s<o))return null;let c=i.clone();c.elements[10]=-(o+s)/(o-s),c.elements[14]=-2*o*s/(o-s);let l=c.multiply(i.clone().invert()).multiply(new t.Matrix4().fromArray(Array.from(e.mvp)));for(let e=0;e<16;e++)if(!Number.isFinite(l.elements[e]))return null;return l}function fu(e,n,r){let i=e.projectionMatrix;if(!i||i.length<16)return null;let a=new t.Matrix4().fromArray(Array.from(i)),o=new t.Matrix4().fromArray(Array.from(e.mvp));if(a.determinant()===0||!ou(a,n.fov))return null;let s=a.clone().invert().multiply(o);if(!iu(a.clone().multiply(s),Array.from(e.mvp))||!au(s))return null;let c=Math.max(0,Math.min(1,r));if(c<=0)return{matrix:o,view:s};let{distance:l,fov:u,aspect:d}=n;if(!(l>0)||!(u>0)||!(d>0))return null;let f=l*Math.tan(u/2),p=f*d,m=e.nearZ!=null&&e.nearZ>0?e.nearZ:1,h=e.farZ!=null&&e.farZ>m?e.farZ:l*4+1e3;h>m||(h=m+1e3);let g=new t.OrthographicCamera(-p,p,f,-f,m,h);if(g.updateProjectionMatrix(),c>=1)return{matrix:g.projectionMatrix.clone().multiply(s),view:s};let _=new t.Matrix4,v=a.elements,y=g.projectionMatrix.elements,b=_.elements;for(let e=0;e<16;e++)b[e]=(1-c)*v[e]+c*y[e];return{matrix:_.multiply(s),view:s}}var pu=l({Animator:()=>tl,AttributeQuery:()=>tn,BinaryReader:()=>x,CUBE_FACES:()=>zl,DEFAULT_FLOOR_HEIGHT:()=>qt,DEFAULT_LIGHT_PRESET:()=>rs,DEFAULT_STYLE:()=>fa,DatasetManager:()=>Ul,EARTH_RADIUS:()=>hn,EASING_NAMES:()=>Pc,FeatureStyleManager:()=>Ys,GPUPathManager:()=>Yi,GpuEdgePass:()=>Ls,GroundManager:()=>Wl,HostRenderer:()=>nu,LIGHT_PRESETS:()=>as,MotionBlurPass:()=>Cc,Path:()=>Ki,Picker:()=>gc,PixelFormat:()=>X,S3MFormatError:()=>Bt,S3MTileset:()=>ns,S3MViewer:()=>tu,S3M_VERSION:()=>ut,SAMPLES_PER_PATH:()=>256,SELECT_MODE:()=>$,SELECT_MODE_LABELS:()=>ua,STYLE:()=>Q,STYLE_LABELS:()=>la,SUPERMAP_LIGHT_PRESET:()=>is,TextureCompress:()=>Z,VertexTag:()=>B,VertexTagV3:()=>dt,WGS84_A:()=>dn,WGS84_B:()=>pn,WGS84_E2:()=>mn,WGS84_F:()=>fn,authFetch:()=>Xt,autoMotionBlurDamp:()=>vc,azimuthElevation:()=>kl,boxClipping:()=>_l,buildAttributes:()=>Kt,buildBlendedMVP:()=>fu,buildClipPlanes:()=>yl,buildCubeCameras:()=>Bl,buildFeatureEdgeSegments:()=>Ms,buildNearScaledMVP:()=>du,buildOrthoMVP:()=>uu,buildThickLineGeometry:()=>Ds,buildTileObjects:()=>Po,captureRadialCube:()=>Vl,captureSkylineDepth:()=>Rl,classifyDatasetKind:()=>Zo,computeViewshed:()=>jl,createLineSharedUniforms:()=>Cs,createOutlineMaterial:()=>ca,createSharedUniforms:()=>aa,createStyledMaterial:()=>oa,createTexture:()=>Ri,createThickLineMaterial:()=>Es,crossClipping:()=>vl,cubicBezier:()=>Gc,default:()=>tu,distance3D:()=>nl,distanceHorizontal:()=>rl,dxtPixelFormatOf:()=>Ur,easing:()=>Fc,enuToLngLat:()=>an,extractEulerAngles:()=>Ws,extractFovRadians:()=>lu,extractNearFar:()=>cu,extractProjectionMatrix:()=>su,getColorPipeline:()=>ra,getMaterialQuality:()=>ta,heightDifference:()=>il,isPointKept:()=>hl,isS3M1Buffer:()=>He,lineOfSight:()=>dl,lngLatFromMercator:()=>cn,lngLatFromWorld:()=>un,lngLatToEnu:()=>on,makeCubeDistanceSampler:()=>Ml,measureSegment:()=>ul,measureSegments:()=>Gt,mercatorFromLngLat:()=>sn,meridianRadius:()=>rn,normalizeDepthMode:()=>Gl,normalizeMotionBlur:()=>_c,packRGBADepth:()=>wl,parseConfigText:()=>Xo,parseS3M1:()=>lt,parseS3MB:()=>Vt,pixelToNdc:()=>Ol,planDegradations:()=>Ut,planeClipping:()=>gl,planeFromPointNormal:()=>ml,polygonArea:()=>cl,polygonAreaHorizontal:()=>ll,polygonPerimeter:()=>sl,polylineLength:()=>al,polylineLengthHorizontal:()=>ol,primeVerticalRadius:()=>nn,resolveAuthRequest:()=>Yt,resolveEdgeModes:()=>Zi,resolveFeature:()=>U,resolveLightingPreset:()=>os,resolveRotationMatrix:()=>Us,resolveTextureKind:()=>Hr,sameEdgeModes:()=>Qi,setColorPipeline:()=>na,setMaterialQuality:()=>ea,setMaxAnisotropy:()=>Oi,setMaxTextureSize:()=>ji,setSrgbTextureDecode:()=>Fi,skylineFromDepth:()=>Al,steps:()=>Kc,unpackRGBADepth:()=>Tl,unprojectNdc:()=>Dl,worldFromLngLat:()=>ln});Jt(),gn(),ja(),Xi(),Vo(),Gi(),Kr(),qi(),Jt(),gn(),Kr(),Gi(),qi(),Xi(),ja(),Vo();var mu=globalThis;return mu.THREE||(mu.THREE=t),mu.S3M=pu,e.Animator=tl,e.AttributeQuery=tn,e.BinaryReader=x,e.CUBE_FACES=zl,e.DEFAULT_FLOOR_HEIGHT=qt,e.DEFAULT_LIGHT_PRESET=rs,e.DEFAULT_STYLE=fa,e.DatasetManager=Ul,e.EARTH_RADIUS=hn,e.EASING_NAMES=Pc,e.FeatureStyleManager=Ys,e.GPUPathManager=Yi,e.GpuEdgePass=Ls,e.GroundManager=Wl,e.HostRenderer=nu,e.LIGHT_PRESETS=as,e.MotionBlurPass=Cc,e.Path=Ki,e.Picker=gc,e.PixelFormat=X,e.S3MFormatError=Bt,e.S3MTileset=ns,e.S3MViewer=tu,e.default=tu,e.S3M_VERSION=ut,e.SAMPLES_PER_PATH=Ji,e.SELECT_MODE=$,e.SELECT_MODE_LABELS=ua,e.STYLE=Q,e.STYLE_LABELS=la,e.SUPERMAP_LIGHT_PRESET=is,e.TextureCompress=Z,e.VertexTag=B,e.VertexTagV3=dt,e.WGS84_A=dn,e.WGS84_B=pn,e.WGS84_E2=mn,e.WGS84_F=fn,e.authFetch=Xt,e.autoMotionBlurDamp=vc,e.azimuthElevation=kl,e.boxClipping=_l,e.buildAttributes=Kt,e.buildBlendedMVP=fu,e.buildClipPlanes=yl,e.buildCubeCameras=Bl,e.buildFeatureEdgeSegments=Ms,e.buildNearScaledMVP=du,e.buildOrthoMVP=uu,e.buildThickLineGeometry=Ds,e.buildTileObjects=Po,e.captureRadialCube=Vl,e.captureSkylineDepth=Rl,e.classifyDatasetKind=Zo,e.computeViewshed=jl,e.createLineSharedUniforms=Cs,e.createOutlineMaterial=ca,e.createSharedUniforms=aa,e.createStyledMaterial=oa,e.createTexture=Ri,e.createThickLineMaterial=Es,e.crossClipping=vl,e.cubicBezier=Gc,e.distance3D=nl,e.distanceHorizontal=rl,e.dxtPixelFormatOf=Ur,e.easing=Fc,e.enuToLngLat=an,e.extractEulerAngles=Ws,e.extractFovRadians=lu,e.extractNearFar=cu,e.extractProjectionMatrix=su,e.getColorPipeline=ra,e.getMaterialQuality=ta,e.heightDifference=il,e.isPointKept=hl,e.isS3M1Buffer=He,e.lineOfSight=dl,e.lngLatFromMercator=cn,e.lngLatFromWorld=un,e.lngLatToEnu=on,e.makeCubeDistanceSampler=Ml,e.measureSegment=ul,e.measureSegments=Gt,e.mercatorFromLngLat=sn,e.meridianRadius=rn,e.normalizeDepthMode=Gl,e.normalizeMotionBlur=_c,e.packRGBADepth=wl,e.parseConfigText=Xo,e.parseS3M1=lt,e.parseS3MB=Vt,e.pixelToNdc=Ol,e.planDegradations=Ut,e.planeClipping=gl,e.planeFromPointNormal=ml,e.polygonArea=cl,e.polygonAreaHorizontal=ll,e.polygonPerimeter=sl,e.polylineLength=al,e.polylineLengthHorizontal=ol,e.primeVerticalRadius=nn,e.resolveAuthRequest=Yt,e.resolveEdgeModes=Zi,e.resolveFeature=U,e.resolveLightingPreset=os,e.resolveRotationMatrix=Us,e.resolveTextureKind=Hr,e.sameEdgeModes=Qi,e.setColorPipeline=na,e.setMaterialQuality=ea,e.setMaxAnisotropy=Oi,e.setMaxTextureSize=ji,e.setSrgbTextureDecode=Fi,e.skylineFromDepth=Al,e.steps=Kc,e.unpackRGBADepth=Tl,e.unprojectNdc=Dl,e.worldFromLngLat=ln,e})({},THREE);