mapbox-3d-tiles
Version:
Integrate threejs with mapbox-gl to enable 3dtiles / 3dgs / gltf rendering.
5 lines • 509 kB
JavaScript
(function(ae,A){typeof exports=="object"&&typeof module<"u"?A(exports,require("three"),require("mapbox-gl")):typeof define=="function"&&define.amd?define(["exports","three","mapbox-gl"],A):(ae=typeof globalThis<"u"?globalThis:ae||self,A(ae["mapbox-3d-tiles"]={},ae.THREE,ae.mapboxgl))})(this,function(ae,A,Gs){"use strict";var ot;function no(a){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(a){for(const t in a)if(t!=="default"){const s=Object.getOwnPropertyDescriptor(a,t);Object.defineProperty(e,t,s.get?s:{enumerable:!0,get:()=>a[t]})}}return e.default=a,Object.freeze(e)}const Y=no(A);class ai extends A.Object3D{constructor(e=document.createElement("div")){super(),this.isCSS2DObject=!0,this.element=e,this.element.style.position="absolute",this.element.style.userSelect="none",this.element.setAttribute("draggable",!1),this.center=new A.Vector2(.5,.5),this.addEventListener("removed",function(){this.traverse(function(t){t.element instanceof t.element.ownerDocument.defaultView.Element&&t.element.parentNode!==null&&t.element.remove()})})}copy(e,t){return super.copy(e,t),this.element=e.element.cloneNode(!0),this.center=e.center,this}}const lt=new A.Vector3,oi=new A.Matrix4,ci=new A.Matrix4,Ai=new A.Vector3,li=new A.Vector3;class io{constructor(e={}){const t=this;let s,n,i,r;const o={objects:new WeakMap},c=e.element!==void 0?e.element:document.createElement("div");c.style.overflow="hidden",this.domElement=c,this.getSize=function(){return{width:s,height:n}},this.render=function(p,g){p.matrixWorldAutoUpdate===!0&&p.updateMatrixWorld(),g.parent===null&&g.matrixWorldAutoUpdate===!0&&g.updateMatrixWorld(),oi.copy(g.matrixWorldInverse),ci.multiplyMatrices(g.projectionMatrix,oi),h(p,p,g),f(p)},this.setSize=function(p,g){s=p,n=g,i=s/2,r=n/2,c.style.width=p+"px",c.style.height=g+"px"};function l(p){p.isCSS2DObject&&(p.element.style.display="none");for(let g=0,m=p.children.length;g<m;g++)l(p.children[g])}function h(p,g,m){if(p.visible===!1){l(p);return}if(p.isCSS2DObject){lt.setFromMatrixPosition(p.matrixWorld),lt.applyMatrix4(ci);const I=lt.z>=-1&<.z<=1&&p.layers.test(m.layers)===!0,b=p.element;b.style.display=I===!0?"":"none",I===!0&&(p.onBeforeRender(t,g,m),b.style.transform="translate("+-100*p.center.x+"%,"+-100*p.center.y+"%)translate("+(lt.x*i+i)+"px,"+(-lt.y*r+r)+"px)",b.parentNode!==c&&c.appendChild(b),p.onAfterRender(t,g,m));const C={distanceToCameraSquared:u(m,p)};o.objects.set(p,C)}for(let I=0,b=p.children.length;I<b;I++)h(p.children[I],g,m)}function u(p,g){return Ai.setFromMatrixPosition(p.matrixWorld),li.setFromMatrixPosition(g.matrixWorld),Ai.distanceToSquared(li)}function d(p){const g=[];return p.traverseVisible(function(m){m.isCSS2DObject&&g.push(m)}),g}function f(p){const g=d(p).sort(function(I,b){if(I.renderOrder!==b.renderOrder)return b.renderOrder-I.renderOrder;const C=o.objects.get(I).distanceToCameraSquared,y=o.objects.get(b).distanceToCameraSquared;return C-y}),m=g.length;for(let I=0,b=g.length;I<b;I++)g[I].element.style.zIndex=m-I}}}class ro{constructor(e,t){if(this._map=e,this._renderer&&this._labelRenderer)return;let s=new A.WebGLRenderer({alpha:!0,antialias:!0,canvas:e.getCanvas(),context:t});s.shadowMap.enabled=!0,s.autoClear=!1;let n=new io;n.setSize(e._containerWidth,e._containerHeight),n.domElement.style.position="absolute",n.domElement.style.top="0px",n.domElement.style.pointerEvents="none",e._container.appendChild(n.domElement),e.on("resize",()=>{n.setSize(e._containerWidth,e._containerHeight)}),this._renderer=s,this._labelRenderer=n}getRenderer(){return this._renderer}render(e,t){this._renderer.resetState(),this._renderer.render(e,t),this._labelRenderer.render(e,t)}}class ao extends A.DataTextureLoader{constructor(e){super(e),this.type=A.HalfFloatType}parse(e){const r=function(x,w){switch(x){case 1:throw new Error("THREE.RGBELoader: Read Error: "+(w||""));case 2:throw new Error("THREE.RGBELoader: Write Error: "+(w||""));case 3:throw new Error("THREE.RGBELoader: Bad File Format: "+(w||""));default:case 4:throw new Error("THREE.RGBELoader: Memory Error: "+(w||""))}},h=`
`,u=function(x,w,S){w=w||1024;let E=x.pos,N=-1,k=0,O="",P=String.fromCharCode.apply(null,new Uint16Array(x.subarray(E,E+128)));for(;0>(N=P.indexOf(h))&&k<w&&E<x.byteLength;)O+=P,k+=P.length,E+=128,P+=String.fromCharCode.apply(null,new Uint16Array(x.subarray(E,E+128)));return-1<N?(x.pos+=k+N+1,O+P.slice(0,N)):!1},d=function(x){const w=/^#\?(\S+)/,S=/^\s*GAMMA\s*=\s*(\d+(\.\d+)?)\s*$/,Q=/^\s*EXPOSURE\s*=\s*(\d+(\.\d+)?)\s*$/,E=/^\s*FORMAT=(\S+)\s*$/,N=/^\s*\-Y\s+(\d+)\s+\+X\s+(\d+)\s*$/,k={valid:0,string:"",comments:"",programtype:"RGBE",format:"",gamma:1,exposure:1,width:0,height:0};let O,P;for((x.pos>=x.byteLength||!(O=u(x)))&&r(1,"no header found"),(P=O.match(w))||r(3,"bad initial token"),k.valid|=1,k.programtype=P[1],k.string+=O+`
`;O=u(x),O!==!1;){if(k.string+=O+`
`,O.charAt(0)==="#"){k.comments+=O+`
`;continue}if((P=O.match(S))&&(k.gamma=parseFloat(P[1])),(P=O.match(Q))&&(k.exposure=parseFloat(P[1])),(P=O.match(E))&&(k.valid|=2,k.format=P[1]),(P=O.match(N))&&(k.valid|=4,k.height=parseInt(P[1],10),k.width=parseInt(P[2],10)),k.valid&2&&k.valid&4)break}return k.valid&2||r(3,"missing format specifier"),k.valid&4||r(3,"missing image size specifier"),k},f=function(x,w,S){const Q=w;if(Q<8||Q>32767||x[0]!==2||x[1]!==2||x[2]&128)return new Uint8Array(x);Q!==(x[2]<<8|x[3])&&r(3,"wrong scanline width");const E=new Uint8Array(4*w*S);E.length||r(4,"unable to allocate buffer space");let N=0,k=0;const O=4*Q,P=new Uint8Array(4),M=new Uint8Array(O);let j=S;for(;j>0&&k<x.byteLength;){k+4>x.byteLength&&r(1),P[0]=x[k++],P[1]=x[k++],P[2]=x[k++],P[3]=x[k++],(P[0]!=2||P[1]!=2||(P[2]<<8|P[3])!=Q)&&r(3,"bad rgbe scanline format");let q=0,z;for(;q<O&&k<x.byteLength;){z=x[k++];const X=z>128;if(X&&(z-=128),(z===0||q+z>O)&&r(3,"bad scanline data"),X){const $=x[k++];for(let de=0;de<z;de++)M[q++]=$}else M.set(x.subarray(k,k+z),q),q+=z,k+=z}const Z=Q;for(let X=0;X<Z;X++){let $=0;E[N]=M[X+$],$+=Q,E[N+1]=M[X+$],$+=Q,E[N+2]=M[X+$],$+=Q,E[N+3]=M[X+$],N+=4}j--}return E},p=function(x,w,S,Q){const E=x[w+3],N=Math.pow(2,E-128)/255;S[Q+0]=x[w+0]*N,S[Q+1]=x[w+1]*N,S[Q+2]=x[w+2]*N,S[Q+3]=1},g=function(x,w,S,Q){const E=x[w+3],N=Math.pow(2,E-128)/255;S[Q+0]=A.DataUtils.toHalfFloat(Math.min(x[w+0]*N,65504)),S[Q+1]=A.DataUtils.toHalfFloat(Math.min(x[w+1]*N,65504)),S[Q+2]=A.DataUtils.toHalfFloat(Math.min(x[w+2]*N,65504)),S[Q+3]=A.DataUtils.toHalfFloat(1)},m=new Uint8Array(e);m.pos=0;const I=d(m),b=I.width,C=I.height,y=f(m.subarray(m.pos),b,C);let B,v,_;switch(this.type){case A.FloatType:_=y.length/4;const x=new Float32Array(_*4);for(let S=0;S<_;S++)p(y,S*4,x,S*4);B=x,v=A.FloatType;break;case A.HalfFloatType:_=y.length/4;const w=new Uint16Array(_*4);for(let S=0;S<_;S++)g(y,S*4,w,S*4);B=w,v=A.HalfFloatType;break;default:throw new Error("THREE.RGBELoader: Unsupported type: "+this.type)}return{width:b,height:C,data:B,header:I.string,gamma:I.gamma,exposure:I.exposure,type:v}}setDataType(e){return this.type=e,this}load(e,t,s,n){function i(r,o){switch(r.type){case A.FloatType:case A.HalfFloatType:r.colorSpace=A.LinearSRGBColorSpace,r.minFilter=A.LinearFilter,r.magFilter=A.LinearFilter,r.generateMipmaps=!1,r.flipY=!0;break}t&&t(r,o)}return super.load(e,i,s,n)}}class _e{static updateWorldMatrix(e,t=null){const s=t||e.getCenter(),n=Gs.MercatorCoordinate.fromLngLat(s),i=n.meterInMercatorCoordinateUnits(),r=[0,0,0],o=new A.Matrix4;return o.compose(new A.Vector3(n.x,n.y,n.z),new A.Quaternion().setFromEuler(new A.Euler(r[0],r[1],r[2])),new A.Vector3(i,-i,i)),o}static toScenePositionMercator(e,t){return new A.Vector3(t.x,t.y,t.z).applyMatrix4(e)}static toMapPositionMercator(e,t){const s=t.clone().applyMatrix4(e);return new Gs.MercatorCoordinate(s.x,s.y,s.z)}static toScenePosition(e,t,s){const n=Gs.MercatorCoordinate.fromLngLat(t,s);return this.toScenePositionMercator(e,n)}static toMapPosition(e,t){const s=this.toMapPositionMercator(e,t),n=s.toLngLat(),i=s.toAltitude();return[n.lng,n.lat,i]}static degToRad(e){return e/180*Math.PI}static radToDeg(e){return e/Math.PI*180}static toSceneGeometry(e){}}class oo{createScene(e=!0){const t=new A.Scene;if(e){const s=new A.DirectionalLight(16777215,4);s.position.set(1,2,3),t.add(s);const n=new A.AmbientLight(16777215,.2);t.add(n)}return t}createGroup(e,t){const s=new A.Group;return s.name=t,e.add(s),s}createCamera(e,t){const s=new A.PerspectiveCamera;s.name=t;const n=new A.Group;return n.name=t+"-parent",n.add(s),e.add(n),s}_calcProjectionMatrices(e){const t=e.centerOffset;let s;const n=e._camera.getCameraToClipPerspective(e._fov,e.width/e.height,e._nearZ,e._farZ);if(n[8]=-t.x*2/e.width,n[9]=t.y*2/e.height,e.isOrthographic){const r=(g,m,I)=>(1-I)*g+I*m,o=g=>g*g*g*g*g,c=(g,m,I,b)=>{for(let C=0;C<16;C++)g[C]=r(m[C],I[C],b);return g};let h=.5*e.height/Math.tan(e._fov/2)*1*Math.tan(e._fov*.5),u=h*e.aspect,d=-u,f=-h;u-=t.x,d-=t.x,h+=t.y,f+=t.y,s=e._camera.getCameraToClipOrthographic(d,u,f,h,e._nearZ,e._farZ);const p=e.pitch>=15?1:e.pitch/15;c(s,s,n,o(p))}else s=n;return new A.Matrix4().fromArray(s)}updateCameraForRender(e,t,s,n,i){const r=new A.Matrix4().fromArray(s),o=new A.Matrix4().multiplyMatrices(r,n);e.fov=_e.radToDeg(t.transform.fovX),e.aspect=t.transform.aspect,e.near=t.transform._nearZ,e.far=t.transform._farZ;const c=t.transform;this._calcProjectionMatrices(c);const l=this._calcProjectionMatrices(c);e.projectionMatrix.copy(l),e.projectionMatrixInverse.copy(e.projectionMatrix).invert();const h=e.projectionMatrixInverse,u=new A.Matrix4().multiplyMatrices(h,o),d=u.clone().invert();e.matrixWorld.copy(d),e.matrixWorldInverse.copy(u),e.matrixAutoUpdate=!1,e.matrixWorldAutoUpdate=!1;const f=new A.Vector3,p=new A.Quaternion,g=new A.Vector3;e.matrixWorld.decompose(f,p,g),e.position.set(f.x,f.y,f.z);const m=new A.Euler().setFromQuaternion(p,"YXZ");e.rotation.set(m.x,m.y,m.z)}createEnvTexture(e,t){e&&e.length>3&&e.indexOf(".hdr")===e.length-4&&new ao().load(e,n=>{n.mapping=A.EquirectangularReflectionMapping,t.environment=n,t.environmentRotation.x=Math.PI/2})}}const ht="scene-update",Kt="scene-recenter";function hi(a){if(!a)return null;const e=a.replace(/[a-z]+:\/\/[^/]+/i,"").replace(/\?.*$/i,"").replace(/.*\//g,""),t=e.lastIndexOf(".");return t===-1?null:e.substring(t+1)||null}const ui=2**30;class di{get unloadPriorityCallback(){return this._unloadPriorityCallback}set unloadPriorityCallback(e){e.length===1?(console.warn('LRUCache: "unloadPriorityCallback" function has been changed to take two arguments.'),this._unloadPriorityCallback=(t,s)=>{const n=e(t),i=e(s);return n<i?-1:n>i?1:0}):this._unloadPriorityCallback=e}constructor(){this.minSize=6e3,this.maxSize=8e3,this.minBytesSize=.3*ui,this.maxBytesSize=.4*ui,this.unloadPercent=.05,this.autoMarkUnused=!0,this.itemSet=new Map,this.itemList=[],this.usedSet=new Set,this.callbacks=new Map,this.unloadingHandle=-1,this.cachedBytes=0,this.bytesMap=new Map,this.loadedSet=new Set,this._unloadPriorityCallback=null;const e=this.itemSet;this.defaultPriorityCallback=t=>e.get(t)}isFull(){return this.itemSet.size>=this.maxSize||this.cachedBytes>=this.maxBytesSize}getMemoryUsage(e){return this.bytesMap.get(e)||0}setMemoryUsage(e,t){const{bytesMap:s,itemSet:n}=this;n.has(e)&&(this.cachedBytes-=s.get(e)||0,s.set(e,t),this.cachedBytes+=t)}add(e,t){const s=this.itemSet;if(s.has(e)||this.isFull())return!1;const n=this.usedSet,i=this.itemList,r=this.callbacks;return i.push(e),n.add(e),s.set(e,Date.now()),r.set(e,t),!0}has(e){return this.itemSet.has(e)}remove(e){const t=this.usedSet,s=this.itemSet,n=this.itemList,i=this.bytesMap,r=this.callbacks,o=this.loadedSet;if(s.has(e)){this.cachedBytes-=i.get(e)||0,i.delete(e),r.get(e)(e);const c=n.indexOf(e);return n.splice(c,1),t.delete(e),s.delete(e),r.delete(e),o.delete(e),!0}return!1}setLoaded(e,t){const{itemSet:s,loadedSet:n}=this;s.has(e)&&(t===!0?n.add(e):n.delete(e))}markUsed(e){const t=this.itemSet,s=this.usedSet;t.has(e)&&!s.has(e)&&(t.set(e,Date.now()),s.add(e))}markUnused(e){this.usedSet.delete(e)}markAllUnused(){this.usedSet.clear()}unloadUnusedContent(){const{unloadPercent:e,minSize:t,maxSize:s,itemList:n,itemSet:i,usedSet:r,loadedSet:o,callbacks:c,bytesMap:l,minBytesSize:h,maxBytesSize:u}=this,d=n.length-r.size,f=n.length-o.size,p=Math.max(Math.min(n.length-t,d),0),g=this.cachedBytes-h,m=this.unloadPriorityCallback||this.defaultPriorityCallback;let I=!1;const b=p>0&&d>0||f&&n.length>s;if(d&&this.cachedBytes>h||f&&this.cachedBytes>u||b){n.sort((S,Q)=>{const E=r.has(S),N=r.has(Q);if(E===N){const k=o.has(S),O=o.has(Q);return k===O?-m(S,Q):k?1:-1}else return E?1:-1});const y=Math.max(t*e,p*e),B=Math.ceil(Math.min(y,d,p)),v=Math.max(e*g,e*h),_=Math.min(v,g);let x=0,w=0;for(;this.cachedBytes-w>u||n.length-x>s;){const S=n[x],Q=l.get(S)||0;if(r.has(S)&&o.has(S)||this.cachedBytes-w-Q<u&&n.length-x<=s)break;w+=Q,x++}for(;w<_||x<B;){const S=n[x],Q=l.get(S)||0;if(r.has(S)||this.cachedBytes-w-Q<h&&x>=B)break;w+=Q,x++}n.splice(0,x).forEach(S=>{this.cachedBytes-=l.get(S)||0,c.get(S)(S),l.delete(S),i.delete(S),c.delete(S),o.delete(S),r.delete(S)}),I=x<p||w<g&&x<d,I=I&&x>0}I&&(this.unloadingHandle=requestAnimationFrame(()=>this.scheduleUnload()))}scheduleUnload(){cancelAnimationFrame(this.unloadingHandle),this.scheduled||(this.scheduled=!0,queueMicrotask(()=>{this.scheduled=!1,this.unloadUnusedContent()}))}}class Ps{get running(){return this.items.length!==0||this.currJobs!==0}constructor(){this.maxJobs=6,this.items=[],this.callbacks=new Map,this.currJobs=0,this.scheduled=!1,this.autoUpdate=!0,this.priorityCallback=()=>{throw new Error("PriorityQueue: PriorityCallback function not defined.")},this.schedulingCallback=e=>{requestAnimationFrame(e)},this._runjobs=()=>{this.scheduled=!1,this.tryRunJobs()}}sort(){const e=this.priorityCallback;this.items.sort(e)}has(e){return this.callbacks.has(e)}add(e,t){const s={callback:t,reject:null,resolve:null,promise:null};return s.promise=new Promise((n,i)=>{const r=this.items,o=this.callbacks;s.resolve=n,s.reject=i,r.push(e),o.set(e,s),this.autoUpdate&&this.scheduleJobRun()}),s.promise}remove(e){const t=this.items,s=this.callbacks,n=t.indexOf(e);if(n!==-1){const i=s.get(e);i.promise.catch(()=>{}),i.reject(new Error("PriorityQueue: Item removed.")),t.splice(n,1),s.delete(e)}}removeByFilter(e){const{items:t}=this;for(let s=0;s<t.length;s++){const n=t[s];e(n)&&this.remove(n)}}tryRunJobs(){this.sort();const e=this.items,t=this.callbacks,s=this.maxJobs;let n=0;const i=()=>{this.currJobs--,this.autoUpdate&&this.scheduleJobRun()};for(;s>this.currJobs&&e.length>0&&n<s;){this.currJobs++,n++;const r=e.pop(),{callback:o,resolve:c,reject:l}=t.get(r);t.delete(r);let h;try{h=o(r)}catch(u){l(u),i()}h instanceof Promise?h.then(c).catch(l).finally(i):(c(h),i())}}scheduleJobRun(){this.scheduled||(this.schedulingCallback(this._runjobs),this.scheduled=!0)}}const ut=-1,ke=0,Jt=1,Us=2,yt=3,fi=6378137,co=6356752314245179e-9,Yt={inView:!1,error:1/0,distanceFromCamera:1/0};function pi(a){return a===yt||a===ut}function ze(a,e){return a.__lastFrameVisited===e&&a.__used}function Ns(a){return a.__childrenProcessed===a.children.length}function Os(a,e){a.__lastFrameVisited!==e.frameCount&&(a.__lastFrameVisited=e.frameCount,a.__used=!1,a.__inFrustum=!1,a.__isLeaf=!1,a.__visible=!1,a.__active=!1,a.__error=1/0,a.__distanceFromCamera=1/0,a.__childrenWereVisible=!1,a.__allChildrenLoaded=!1,e.calculateTileViewError(a,Yt),a.__inFrustum=Yt.inView,a.__error=Yt.error,a.__distanceFromCamera=Yt.distanceFromCamera)}function gi(a,e){if(e.ensureChildrenArePreprocessed(a),Os(a,e),Rs(a,e),!a.__hasRenderableContent&&Ns(a)){const t=a.children;for(let s=0,n=t.length;s<n;s++)gi(t[s],e)}}function mi(a,e){if(e.ensureChildrenArePreprocessed(a),ze(a,e.frameCount)&&(a.__hasContent&&a.__loadingState===ke&&!e.lruCache.isFull()&&e.queueTileForDownload(a),Ns(a))){const t=a.children;for(let s=0,n=t.length;s<n;s++)mi(t[s],e)}}function Rs(a,e){a.__used||(a.__used=!0,e.markTileUsed(a),e.stats.used++,a.__inFrustum===!0&&e.stats.inFrustum++)}function Ao(a,e){return!(a.__error<=e.errorTarget||e.maxDepth>0&&a.__depth+1>=e.maxDepth||!Ns(a))}function Vs(a,e=null,t=null){const s=[];for(s.push(a),s.push(null),s.push(0);s.length>0;){const n=s.pop(),i=s.pop(),r=s.pop();if(e&&e(r,i,n)){t&&t(r,i,n);return}const o=r.children;if(o)for(let c=o.length-1;c>=0;c--)s.push(o[c]),s.push(r),s.push(n+1);t&&t(r,i,n)}}function bi(a,e){if(e.ensureChildrenArePreprocessed(a),Os(a,e),!a.__inFrustum)return;if(!Ao(a,e)){Rs(a,e);return}let t=!1,s=!1;const n=a.children;for(let i=0,r=n.length;i<r;i++){const o=n[i];bi(o,e),t=t||ze(o,e.frameCount),s=s||o.__inFrustum}if(Rs(a,e),t&&a.refine==="REPLACE")for(let i=0,r=n.length;i<r;i++){const o=n[i];gi(o,e)}}function Ci(a,e){const t=e.frameCount;if(!ze(a,t))return;const s=a.children;let n=!1;for(let i=0,r=s.length;i<r;i++){const o=s[i];n=n||ze(o,t)}if(!n)a.__isLeaf=!0;else{let i=!1,r=!0;for(let o=0,c=s.length;o<c;o++){const l=s[o];if(Ci(l,e),i=i||l.__wasSetVisible||l.__childrenWereVisible,ze(l,t)){const h=l.__allChildrenLoaded||l.__hasRenderableContent&&pi(l.__loadingState)||!l.__hasContent&&l.children.length===0||l.__hasUnrenderableContent&&l.__loadingState===ut;r=r&&h}}a.__childrenWereVisible=i,a.__allChildrenLoaded=r}}function Ii(a,e){const t=e.stats;if(!ze(a,e.frameCount))return;const s=e.lruCache;if(a.__isLeaf){a.__loadingState===yt?(a.__inFrustum&&(a.__visible=!0,t.visible++),a.__active=!0,t.active++):!s.isFull()&&a.__hasContent&&e.queueTileForDownload(a);return}const n=a.children,i=a.__hasContent,r=pi(a.__loadingState)&&i,o=(e.errorTarget+1)*e.errorThreshold,c=a.__error<=o,l=a.__childrenWereVisible,h=a.__allChildrenLoaded;if((c||a.refine==="ADD")&&!r&&!s.isFull()&&i&&e.queueTileForDownload(a),(c&&!h&&!l&&r||a.refine==="ADD"&&r)&&(a.__inFrustum&&(a.__visible=!0,t.visible++),a.__active=!0,t.active++),a.refine==="REPLACE"&&c&&!h)for(let d=0,f=n.length;d<f;d++){const p=n[d];ze(p,e.frameCount)&&mi(p,e)}else for(let d=0,f=n.length;d<f;d++)Ii(n[d],e)}function yi(a,e){const t=ze(a,e.frameCount);if(t||a.__usedLastFrame){let s=!1,n=!1;t?(s=a.__active,e.displayActiveTiles?n=a.__active||a.__visible:n=a.__visible):Os(a,e),a.__hasRenderableContent&&a.__loadingState===yt&&(a.__wasSetActive!==s&&e.invokeOnePlugin(r=>r.setTileActive&&r.setTileActive(a,s)),a.__wasSetVisible!==n&&e.invokeOnePlugin(r=>r.setTileVisible&&r.setTileVisible(a,n))),a.__wasSetActive=s,a.__wasSetVisible=n,a.__usedLastFrame=t;const i=a.children;for(let r=0,o=i.length;r<o;r++){const c=i[r];yi(c,e)}}}function lo(a,e=null){let t=a;for(;t;){const s=t.__depth,n=t.parent;e&&e(t,n,s),t=n}}function ho(a){let e=null;return()=>{e===null&&(e=requestAnimationFrame(()=>{e=null,a()}))}}const Bi=Symbol("PLUGIN_REGISTERED"),zs=(a,e)=>{const t=a.priority||0,s=e.priority||0;return t!==s?t>s?1:-1:a.__depthFromRenderedParent!==e.__depthFromRenderedParent?a.__depthFromRenderedParent>e.__depthFromRenderedParent?-1:1:a.__inFrustum!==e.__inFrustum?a.__inFrustum?1:-1:a.__used!==e.__used?a.__used?1:-1:a.__error!==e.__error?a.__error>e.__error?1:-1:a.__distanceFromCamera!==e.__distanceFromCamera?a.__distanceFromCamera>e.__distanceFromCamera?-1:1:0},uo=(a,e)=>{const t=a.priority||0,s=e.priority||0;return t!==s?t>s?1:-1:a.__depthFromRenderedParent!==e.__depthFromRenderedParent?a.__depthFromRenderedParent>e.__depthFromRenderedParent?1:-1:a.__loadingState!==e.__loadingState?a.__loadingState>e.__loadingState?-1:1:a.__lastFrameVisited!==e.__lastFrameVisited?a.__lastFrameVisited>e.__lastFrameVisited?-1:1:a.__hasUnrenderableContent!==e.__hasUnrenderableContent?a.__hasUnrenderableContent?-1:1:a.__error!==e.__error?a.__error>e.__error?-1:1:0};class fo{get root(){const e=this.rootTileSet;return e?e.root:null}get loadProgress(){const{stats:e,isLoading:t}=this,s=e.downloading+e.parsing,n=e.inCacheSinceLoad+(t?1:0);return n===0?1:1-s/n}get errorThreshold(){return this._errorThreshold}set errorThreshold(e){console.warn('TilesRenderer: The "errorThreshold" option has been deprecated.'),this._errorThreshold=e}constructor(e=null){this.rootLoadingState=ke,this.rootTileSet=null,this.rootURL=e,this.fetchOptions={},this.plugins=[],this.queuedTiles=[],this.cachedSinceLoadComplete=new Set,this.isLoading=!1;const t=new di;t.unloadPriorityCallback=uo;const s=new Ps;s.maxJobs=25,s.priorityCallback=zs;const n=new Ps;n.maxJobs=5,n.priorityCallback=zs;const i=new Ps;i.maxJobs=25,i.priorityCallback=zs,i.log=!0,this.processedTiles=new WeakSet,this.visibleTiles=new Set,this.activeTiles=new Set,this.usedSet=new Set,this.lruCache=t,this.downloadQueue=s,this.parseQueue=n,this.processNodeQueue=i,this.stats={inCacheSinceLoad:0,inCache:0,parsing:0,downloading:0,failed:0,inFrustum:0,used:0,active:0,visible:0},this.frameCount=0,this._dispatchNeedsUpdateEvent=ho(()=>{this.dispatchEvent({type:"needs-update"})}),this.errorTarget=16,this._errorThreshold=1/0,this.displayActiveTiles=!1,this.maxDepth=1/0}registerPlugin(e){if(e[Bi]===!0)throw new Error("TilesRendererBase: A plugin can only be registered to a single tile set");const t=this.plugins,s=e.priority||0;let n=t.length;for(let i=0;i<t.length;i++)if((t[i].priority||0)>s){n=i;break}t.splice(n,0,e),e[Bi]=!0,e.init&&e.init(this)}unregisterPlugin(e){const t=this.plugins;if(typeof e=="string"&&(e=this.getPluginByName(name)),t.includes(e)){const s=t.indexOf(e);return t.splice(s,1),e.dispose&&e.dispose(),!0}return!1}getPluginByName(e){return this.plugins.find(t=>t.name===e)||null}traverse(e,t,s=!0){this.root&&Vs(this.root,(n,...i)=>(s&&this.ensureChildrenArePreprocessed(n,!0),e?e(n,...i):!1),t)}queueTileForDownload(e){e.__loadingState===ke&&this.queuedTiles.push(e)}markTileUsed(e){this.usedSet.add(e),this.lruCache.markUsed(e)}update(){const{lruCache:e,usedSet:t,stats:s,root:n,downloadQueue:i,parseQueue:r,processNodeQueue:o}=this;if(this.rootLoadingState===ke&&(this.rootLoadingState=Jt,this.invokeOnePlugin(h=>h.loadRootTileSet&&h.loadRootTileSet()).then(h=>{let u=this.rootURL;u!==null&&this.invokeAllPlugins(d=>u=d.preprocessURL?d.preprocessURL(u,null):u),this.rootLoadingState=yt,this.rootTileSet=h,this.dispatchEvent({type:"needs-update"}),this.dispatchEvent({type:"load-content"}),this.dispatchEvent({type:"load-tile-set",tileSet:h,url:u})}).catch(h=>{this.rootLoadingState=ut,console.error(h),this.rootTileSet=null,this.dispatchEvent({type:"load-error",tile:null,error:h,url:this.rootURL})})),!n)return;s.inFrustum=0,s.used=0,s.active=0,s.visible=0,this.frameCount++,t.forEach(h=>e.markUnused(h)),t.clear(),bi(n,this),Ci(n,this),Ii(n,this),yi(n,this);const c=this.queuedTiles;c.sort(e.unloadPriorityCallback);for(let h=0,u=c.length;h<u&&!e.isFull();h++)this.requestTileContents(c[h]);c.length=0,e.scheduleUnload(),(i.running||r.running||o.running)===!1&&this.isLoading===!0&&(this.cachedSinceLoadComplete.clear(),s.inCacheSinceLoad=0,this.dispatchEvent({type:"tiles-load-end"}),this.isLoading=!1)}resetFailedTiles(){this.rootLoadingState===ut&&(this.rootLoadingState=ke);const e=this.stats;e.failed!==0&&(this.traverse(t=>{t.__loadingState===ut&&(t.__loadingState=ke)},null,!1),e.failed=0)}dispose(){[...this.plugins].forEach(n=>{this.unregisterPlugin(n)});const t=this.lruCache,s=[];this.traverse(n=>(s.push(n),!1),null,!1);for(let n=0,i=s.length;n<i;n++)t.remove(s[n]);this.stats={parsing:0,downloading:0,failed:0,inFrustum:0,used:0,active:0,visible:0},this.frameCount=0}calculateBytesUsed(e,t){return 0}dispatchEvent(e){}fetchData(e,t){return fetch(e,t)}parseTile(e,t,s){return null}disposeTile(e){e.__visible&&(this.invokeOnePlugin(t=>t.setTileVisible&&t.setTileVisible(e,!1)),e.__visible=!1),e.__active&&(this.invokeOnePlugin(t=>t.setTileActive&&t.setTileActive(e,!1)),e.__active=!1)}preprocessNode(e,t,s=null){var n;if(this.processedTiles.add(e),e.content&&(!("uri"in e.content)&&"url"in e.content&&(e.content.uri=e.content.url,delete e.content.url),e.content.boundingVolume&&!("box"in e.content.boundingVolume||"sphere"in e.content.boundingVolume||"region"in e.content.boundingVolume)&&delete e.content.boundingVolume),e.parent=s,e.children=e.children||[],(n=e.content)!=null&&n.uri){const i=hi(e.content.uri);e.__hasContent=!0,e.__hasUnrenderableContent=!!(i&&/json$/.test(i)),e.__hasRenderableContent=!e.__hasUnrenderableContent}else e.__hasContent=!1,e.__hasUnrenderableContent=!1,e.__hasRenderableContent=!1;e.__childrenProcessed=0,s&&s.__childrenProcessed++,e.__distanceFromCamera=1/0,e.__error=1/0,e.__inFrustum=!1,e.__isLeaf=!1,e.__usedLastFrame=!1,e.__used=!1,e.__wasSetVisible=!1,e.__visible=!1,e.__childrenWereVisible=!1,e.__allChildrenLoaded=!1,e.__wasSetActive=!1,e.__active=!1,e.__loadingState=ke,s===null?(e.__depth=0,e.__depthFromRenderedParent=e.__hasRenderableContent?1:0,e.refine=e.refine||"REPLACE"):(e.__depth=s.__depth+1,e.__depthFromRenderedParent=s.__depthFromRenderedParent+(e.__hasRenderableContent?1:0),e.refine=e.refine||s.refine),e.__basePath=t,e.__lastFrameVisited=-1,this.invokeAllPlugins(i=>{i!==this&&i.preprocessNode&&i.preprocessNode(e,t,s)})}setTileActive(e,t){t?this.activeTiles.add(e):this.activeTiles.delete(e)}setTileVisible(e,t){t?this.visibleTiles.add(e):this.visibleTiles.delete(e)}calculateTileViewError(e,t){}ensureChildrenArePreprocessed(e,t=!1){const s=e.children;for(let n=0,i=s.length;n<i;n++){const r=s[n];if("__depth"in r)break;t?(this.processNodeQueue.remove(r),this.preprocessNode(r,e.__basePath,e)):this.processNodeQueue.has(r)||this.processNodeQueue.add(r,o=>{this.preprocessNode(o,e.__basePath,e),this._dispatchNeedsUpdateEvent()})}}getBytesUsed(e){let t=0;return this.invokeAllPlugins(s=>{s.calculateBytesUsed&&(t+=s.calculateBytesUsed(e,e.cached.scene)||0)}),t}recalculateBytesUsed(e=null){const{lruCache:t,processedTiles:s}=this;e===null?t.itemSet.forEach(n=>{s.has(n)&&t.setMemoryUsage(n,this.getBytesUsed(n))}):t.setMemoryUsage(e,this.getBytesUsed(e))}preprocessTileSet(e,t,s=null){const n=e.asset.version,[i,r]=n.split(".").map(c=>parseInt(c));console.assert(i<=1,"TilesRenderer: asset.version is expected to be a 1.x or a compatible version."),i===1&&r>0&&console.warn("TilesRenderer: tiles versions at 1.1 or higher have limited support. Some new extensions and features may not be supported.");let o=t.replace(/\/[^/]*$/,"");o=new URL(o,window.location.href).toString(),this.preprocessNode(e.root,o,s)}loadRootTileSet(){let e=this.rootURL;return this.invokeAllPlugins(s=>e=s.preprocessURL?s.preprocessURL(e,null):e),this.invokeOnePlugin(s=>s.fetchData&&s.fetchData(e,this.fetchOptions)).then(s=>{if(s instanceof Response){if(s.ok)return s.json();throw new Error(`TilesRenderer: Failed to load tileset "${e}" with status ${s.status} : ${s.statusText}`)}else return s}).then(s=>(this.preprocessTileSet(s,e),s))}requestTileContents(e){if(e.__loadingState!==ke)return;let t=!1,s=null,n=new URL(e.content.uri,e.__basePath+"/").toString();this.invokeAllPlugins(f=>n=f.preprocessURL?f.preprocessURL(n,e):n);const i=this.stats,r=this.lruCache,o=this.downloadQueue,c=this.parseQueue,l=hi(n),h=new AbortController,u=h.signal;if(r.add(e,f=>{h.abort(),t?(f.children.length=0,f.__childrenProcessed=0):this.invokeAllPlugins(p=>{p.disposeTile&&p.disposeTile(f)}),i.inCache--,this.cachedSinceLoadComplete.has(e)&&(this.cachedSinceLoadComplete.delete(e),i.inCacheSinceLoad--),f.__loadingState===Jt?i.downloading--:f.__loadingState===Us&&i.parsing--,f.__loadingState=ke,c.remove(f),o.remove(f)}))return this.isLoading||(this.isLoading=!0,this.dispatchEvent({type:"tiles-load-start"})),r.setMemoryUsage(e,this.getBytesUsed(e)),this.cachedSinceLoadComplete.add(e),i.inCacheSinceLoad++,i.inCache++,i.downloading++,e.__loadingState=Jt,o.add(e,f=>{if(u.aborted)return Promise.resolve();const p=this.invokeOnePlugin(g=>g.fetchData&&g.fetchData(n,{...this.fetchOptions,signal:u}));return this.dispatchEvent({type:"tile-download-start",tile:e}),p}).then(f=>{if(!u.aborted)if(f instanceof Response){if(f.ok)return l==="json"?f.json():f.arrayBuffer();throw new Error(`Failed to load model with error code ${f.status}`)}else return f}).then(f=>{if(!u.aborted)return i.downloading--,i.parsing++,e.__loadingState=Us,c.add(e,p=>u.aborted?Promise.resolve():l==="json"&&f.root?(this.preprocessTileSet(f,n,e),e.children.push(f.root),s=f,t=!0,Promise.resolve()):this.invokeOnePlugin(g=>g.parseTile&&g.parseTile(f,p,l,n,u)))}).then(()=>{if(!u.aborted){if(i.parsing--,e.__loadingState=yt,r.setLoaded(e,!0),r.getMemoryUsage(e)===0){const f=this.getBytesUsed(e);if(r.isFull()&&f>0){r.remove(e);return}else r.setMemoryUsage(e,f)}this.dispatchEvent({type:"needs-update"}),this.dispatchEvent({type:"load-content"}),t&&this.dispatchEvent({type:"load-tile-set",tileSet:s,url:n}),e.cached.scene&&this.dispatchEvent({type:"load-model",scene:e.cached.scene,tile:e})}}).catch(f=>{u.aborted||(f.name!=="AbortError"?(c.remove(e),o.remove(e),e.__loadingState===Us?i.parsing--:e.__loadingState===Jt&&i.downloading--,i.failed++,console.error(`TilesRenderer : Failed to load tile at url "${e.content.uri}".`),console.error(f),e.__loadingState=ut,r.setLoaded(e,!0),this.dispatchEvent({type:"load-error",tile:e,error:f,url:n})):r.remove(e))})}getAttributions(e=[]){return this.invokeAllPlugins(t=>t!==this&&t.getAttributions&&t.getAttributions(e)),e}invokeOnePlugin(e){const t=[...this.plugins,this];for(let s=0;s<t.length;s++){const n=e(t[s]);if(n)return n}return null}invokeAllPlugins(e){const t=[...this.plugins,this],s=[];for(let n=0;n<t.length;n++){const i=e(t[n]);i&&s.push(i)}return s.length===0?null:Promise.all(s)}}class Bt{constructor(){this.fetchOptions={},this.workingPath=""}load(...e){return console.warn('Loader: "load" function has been deprecated in favor of "loadAsync".'),this.loadAsync(...e)}loadAsync(e){return fetch(e,this.fetchOptions).then(t=>{if(!t.ok)throw new Error(`Failed to load file "${e}" with status ${t.status} : ${t.statusText}`);return t.arrayBuffer()}).then(t=>(this.workingPath===""&&(this.workingPath=this.workingPathForURL(e)),this.parse(t)))}resolveExternalURL(e){return/^[^\\/]/.test(e)&&!/^http/.test(e)?this.workingPath+"/"+e:e}workingPathForURL(e){const t=e.split(/[\\/]/g);return t.pop(),t.join("/")+"/"}parse(e){throw new Error("LoaderBase: Parse not implemented.")}}const po=new TextDecoder;function js(a){return po.decode(a)}function xi(a,e,t,s,n,i){let r;switch(s){case"SCALAR":r=1;break;case"VEC2":r=2;break;case"VEC3":r=3;break;case"VEC4":r=4;break;default:throw new Error(`FeatureTable : Feature type not provided for "${i}".`)}let o;const c=t*r;switch(n){case"BYTE":o=new Int8Array(a,e,c);break;case"UNSIGNED_BYTE":o=new Uint8Array(a,e,c);break;case"SHORT":o=new Int16Array(a,e,c);break;case"UNSIGNED_SHORT":o=new Uint16Array(a,e,c);break;case"INT":o=new Int32Array(a,e,c);break;case"UNSIGNED_INT":o=new Uint32Array(a,e,c);break;case"FLOAT":o=new Float32Array(a,e,c);break;case"DOUBLE":o=new Float64Array(a,e,c);break;default:throw new Error(`FeatureTable : Feature component type not provided for "${i}".`)}return o}class Xt{constructor(e,t,s,n){this.buffer=e,this.binOffset=t+s,this.binLength=n;let i=null;if(s!==0){const r=new Uint8Array(e,t,s);i=JSON.parse(js(r))}else i={};this.header=i}getKeys(){return Object.keys(this.header)}getData(e,t,s=null,n=null){const i=this.header;if(!(e in i))return null;const r=i[e];if(r instanceof Object){if(Array.isArray(r))return r;{const{buffer:o,binOffset:c,binLength:l}=this,h=r.byteOffset||0,u=r.type||n,d=r.componentType||s;if("type"in r&&n&&r.type!==n)throw new Error("FeatureTable: Specified type does not match expected type.");const f=c+h,p=xi(o,f,t,u,d,e);if(f+p.byteLength>c+l)throw new Error("FeatureTable: Feature data read outside binary body length.");return p}}else return r}getBuffer(e,t){const{buffer:s,binOffset:n}=this;return s.slice(n+e,n+e+t)}}class go{constructor(e){this.batchTable=e;const t=e.header.extensions["3DTILES_batch_table_hierarchy"];this.classes=t.classes;for(const n of this.classes){const i=n.instances;for(const r in i)n.instances[r]=this._parseProperty(i[r],n.length,r)}if(this.instancesLength=t.instancesLength,this.classIds=this._parseProperty(t.classIds,this.instancesLength,"classIds"),t.parentCounts?this.parentCounts=this._parseProperty(t.parentCounts,this.instancesLength,"parentCounts"):this.parentCounts=new Array(this.instancesLength).fill(1),t.parentIds){const n=this.parentCounts.reduce((i,r)=>i+r,0);this.parentIds=this._parseProperty(t.parentIds,n,"parentIds")}else this.parentIds=null;this.instancesIds=[];const s={};for(const n of this.classIds)s[n]=s[n]??0,this.instancesIds.push(s[n]),s[n]++}_parseProperty(e,t,s){if(Array.isArray(e))return e;{const{buffer:n,binOffset:i}=this.batchTable,r=e.byteOffset,o=e.componentType||"UNSIGNED_SHORT",c=i+r;return xi(n,c,t,"SCALAR",o,s)}}getDataFromId(e,t={}){const s=this.parentCounts[e];if(this.parentIds&&s>0){let c=0;for(let l=0;l<e;l++)c+=this.parentCounts[l];for(let l=0;l<s;l++){const h=this.parentIds[c+l];h!==e&&this.getDataFromId(h,t)}}const n=this.classIds[e],i=this.classes[n].instances,r=this.classes[n].name,o=this.instancesIds[e];for(const c in i)t[r]=t[r]||{},t[r][c]=i[c][o];return t}}class qs extends Xt{get batchSize(){return console.warn("BatchTable.batchSize has been deprecated and replaced with BatchTable.count."),this.count}constructor(e,t,s,n,i){super(e,s,n,i),this.count=t,this.extensions={};const r=this.header.extensions;r&&r["3DTILES_batch_table_hierarchy"]&&(this.extensions["3DTILES_batch_table_hierarchy"]=new go(this))}getData(e,t=null,s=null){return console.warn("BatchTable: BatchTable.getData is deprecated. Use BatchTable.getDataFromId to get allproperties for an id or BatchTable.getPropertyArray for getting an array of value for a property."),super.getData(e,this.count,t,s)}getDataFromId(e,t={}){if(e<0||e>=this.count)throw new Error(`BatchTable: id value "${e}" out of bounds for "${this.count}" features number.`);for(const s of this.getKeys())s!=="extensions"&&(t[s]=super.getData(s,this.count)[e]);for(const s in this.extensions){const n=this.extensions[s];n.getDataFromId instanceof Function&&(t[s]=t[s]||{},n.getDataFromId(e,t[s]))}return t}getPropertyArray(e){return super.getData(e,this.count)}}function He(a){if(a===null||a.byteLength<4)return"";let e;if(a instanceof DataView?e=a:e=new DataView(a),String.fromCharCode(e.getUint8(0))==="{")return null;let t="";for(let s=0;s<4;s++)t+=String.fromCharCode(e.getUint8(s));return t}class mo extends Bt{parse(e){const t=new DataView(e),s=He(t);console.assert(s==="b3dm");const n=t.getUint32(4,!0);console.assert(n===1);const i=t.getUint32(8,!0);console.assert(i===e.byteLength);const r=t.getUint32(12,!0),o=t.getUint32(16,!0),c=t.getUint32(20,!0),l=t.getUint32(24,!0),h=28,u=e.slice(h,h+r+o),d=new Xt(u,0,r,o),f=h+r+o,p=e.slice(f,f+c+l),g=new qs(p,d.getData("BATCH_LENGTH"),0,c,l),m=f+c+l,I=new Uint8Array(e,m,i-m);return{version:n,featureTable:d,batchTable:g,glbBytes:I}}}class bo extends Bt{parse(e){const t=new DataView(e),s=He(t);console.assert(s==="i3dm");const n=t.getUint32(4,!0);console.assert(n===1);const i=t.getUint32(8,!0);console.assert(i===e.byteLength);const r=t.getUint32(12,!0),o=t.getUint32(16,!0),c=t.getUint32(20,!0),l=t.getUint32(24,!0),h=t.getUint32(28,!0),u=32,d=e.slice(u,u+r+o),f=new Xt(d,0,r,o),p=u+r+o,g=e.slice(p,p+c+l),m=new qs(g,f.getData("INSTANCES_LENGTH"),0,c,l),I=p+c+l,b=new Uint8Array(e,I,i-I);let C=null,y=null,B=null;if(h)C=b,y=Promise.resolve();else{const v=this.resolveExternalURL(js(b)),_=v.split(/[\\/]/g);_.pop(),B=_.join("/"),y=fetch(v,this.fetchOptions).then(x=>{if(!x.ok)throw new Error(`I3DMLoaderBase : Failed to load file "${v}" with status ${x.status} : ${x.statusText}`);return x.arrayBuffer()}).then(x=>{C=new Uint8Array(x)})}return y.then(()=>({version:n,featureTable:f,batchTable:m,glbBytes:C,gltfWorkingPath:B}))}}class Co extends Bt{parse(e){const t=new DataView(e),s=He(t);console.assert(s==="pnts");const n=t.getUint32(4,!0);console.assert(n===1);const i=t.getUint32(8,!0);console.assert(i===e.byteLength);const r=t.getUint32(12,!0),o=t.getUint32(16,!0),c=t.getUint32(20,!0),l=t.getUint32(24,!0),h=28,u=e.slice(h,h+r+o),d=new Xt(u,0,r,o),f=h+r+o,p=e.slice(f,f+c+l),g=new qs(p,d.getData("BATCH_LENGTH")||d.getData("POINTS_LENGTH"),0,c,l);return Promise.resolve({version:n,featureTable:d,batchTable:g})}}class Io extends Bt{parse(e){const t=new DataView(e),s=He(t);console.assert(s==="cmpt",'CMPTLoader: The magic bytes equal "cmpt".');const n=t.getUint32(4,!0);console.assert(n===1,'CMPTLoader: The version listed in the header is "1".');const i=t.getUint32(8,!0);console.assert(i===e.byteLength,"CMPTLoader: The contents buffer length listed in the header matches the file.");const r=t.getUint32(12,!0),o=[];let c=16;for(let l=0;l<r;l++){const h=new DataView(e,c,12),u=He(h),d=h.getUint32(4,!0),f=h.getUint32(8,!0),p=new Uint8Array(e,c,f);o.push({type:u,buffer:p,version:d}),c+=f}return{version:n,tiles:o}}}function yo(a){let e=0;for(const s in a.attributes){const n=a.getAttribute(s);e+=n.count*n.itemSize*n.array.BYTES_PER_ELEMENT}const t=a.getIndex();return e+=t?t.count*t.itemSize*t.array.BYTES_PER_ELEMENT:0,e}function _i(a,e){if(e===A.TrianglesDrawMode)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),a;if(e===A.TriangleFanDrawMode||e===A.TriangleStripDrawMode){let t=a.getIndex();if(t===null){const r=[],o=a.getAttribute("position");if(o!==void 0){for(let c=0;c<o.count;c++)r.push(c);a.setIndex(r),t=a.getIndex()}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible."),a}const s=t.count-2,n=[];if(e===A.TriangleFanDrawMode)for(let r=1;r<=s;r++)n.push(t.getX(0)),n.push(t.getX(r)),n.push(t.getX(r+1));else for(let r=0;r<s;r++)r%2===0?(n.push(t.getX(r)),n.push(t.getX(r+1)),n.push(t.getX(r+2))):(n.push(t.getX(r+2)),n.push(t.getX(r+1)),n.push(t.getX(r)));n.length/3!==s&&console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.");const i=a.clone();return i.setIndex(n),i.clearGroups(),i}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:",e),a}let Zt=class extends A.Loader{constructor(e){super(e),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(t){return new vo(t)}),this.register(function(t){return new So(t)}),this.register(function(t){return new Go(t)}),this.register(function(t){return new Po(t)}),this.register(function(t){return new Uo(t)}),this.register(function(t){return new Mo(t)}),this.register(function(t){return new Do(t)}),this.register(function(t){return new Lo(t)}),this.register(function(t){return new Eo(t)}),this.register(function(t){return new wo(t)}),this.register(function(t){return new Fo(t)}),this.register(function(t){return new Qo(t)}),this.register(function(t){return new ko(t)}),this.register(function(t){return new To(t)}),this.register(function(t){return new xo(t)}),this.register(function(t){return new No(t)}),this.register(function(t){return new Oo(t)})}load(e,t,s,n){const i=this;let r;if(this.resourcePath!=="")r=this.resourcePath;else if(this.path!==""){const l=A.LoaderUtils.extractUrlBase(e);r=A.LoaderUtils.resolveURL(l,this.path)}else r=A.LoaderUtils.extractUrlBase(e);this.manager.itemStart(e);const o=function(l){n?n(l):console.error(l),i.manager.itemError(e),i.manager.itemEnd(e)},c=new A.FileLoader(this.manager);c.setPath(this.path),c.setResponseType("arraybuffer"),c.setRequestHeader(this.requestHeader),c.setWithCredentials(this.withCredentials),c.load(e,function(l){try{i.parse(l,r,function(h){t(h),i.manager.itemEnd(e)},o)}catch(h){o(h)}},s,o)}setDRACOLoader(e){return this.dracoLoader=e,this}setKTX2Loader(e){return this.ktx2Loader=e,this}setMeshoptDecoder(e){return this.meshoptDecoder=e,this}register(e){return this.pluginCallbacks.indexOf(e)===-1&&this.pluginCallbacks.push(e),this}unregister(e){return this.pluginCallbacks.indexOf(e)!==-1&&this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(e),1),this}parse(e,t,s,n){let i;const r={},o={},c=new TextDecoder;if(typeof e=="string")i=JSON.parse(e);else if(e instanceof ArrayBuffer)if(c.decode(new Uint8Array(e,0,4))===wi){try{r[W.KHR_BINARY_GLTF]=new Ro(e)}catch(u){n&&n(u);return}i=JSON.parse(r[W.KHR_BINARY_GLTF].content)}else i=JSON.parse(c.decode(e));else i=e;if(i.asset===void 0||i.asset.version[0]<2){n&&n(new Error("THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported."));return}const l=new ec(i,{path:t||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});l.fileLoader.setRequestHeader(this.requestHeader);for(let h=0;h<this.pluginCallbacks.length;h++){const u=this.pluginCallbacks[h](l);u.name||console.error("THREE.GLTFLoader: Invalid plugin found: missing name"),o[u.name]=u,r[u.name]=!0}if(i.extensionsUsed)for(let h=0;h<i.extensionsUsed.length;++h){const u=i.extensionsUsed[h],d=i.extensionsRequired||[];switch(u){case W.KHR_MATERIALS_UNLIT:r[u]=new _o;break;case W.KHR_DRACO_MESH_COMPRESSION:r[u]=new Vo(i,this.dracoLoader);break;case W.KHR_TEXTURE_TRANSFORM:r[u]=new zo;break;case W.KHR_MESH_QUANTIZATION:r[u]=new jo;break;default:d.indexOf(u)>=0&&o[u]===void 0&&console.warn('THREE.GLTFLoader: Unknown extension "'+u+'".')}}l.setExtensions(r),l.setPlugins(o),l.parse(s,n)}parseAsync(e,t){const s=this;return new Promise(function(n,i){s.parse(e,t,n,i)})}};function Bo(){let a={};return{get:function(e){return a[e]},add:function(e,t){a[e]=t},remove:function(e){delete a[e]},removeAll:function(){a={}}}}const W={KHR_BINARY_GLTF:"KHR_binary_glTF",KHR_DRACO_MESH_COMPRESSION:"KHR_draco_mesh_compression",KHR_LIGHTS_PUNCTUAL:"KHR_lights_punctual",KHR_MATERIALS_CLEARCOAT:"KHR_materials_clearcoat",KHR_MATERIALS_DISPERSION:"KHR_materials_dispersion",KHR_MATERIALS_IOR:"KHR_materials_ior",KHR_MATERIALS_SHEEN:"KHR_materials_sheen",KHR_MATERIALS_SPECULAR:"KHR_materials_specular",KHR_MATERIALS_TRANSMISSION:"KHR_materials_transmission",KHR_MATERIALS_IRIDESCENCE:"KHR_materials_iridescence",KHR_MATERIALS_ANISOTROPY:"KHR_materials_anisotropy",KHR_MATERIALS_UNLIT:"KHR_materials_unlit",KHR_MATERIALS_VOLUME:"KHR_materials_volume",KHR_TEXTURE_BASISU:"KHR_texture_basisu",KHR_TEXTURE_TRANSFORM:"KHR_texture_transform",KHR_MESH_QUANTIZATION:"KHR_mesh_quantization",KHR_MATERIALS_EMISSIVE_STRENGTH:"KHR_materials_emissive_strength",EXT_MATERIALS_BUMP:"EXT_materials_bump",EXT_TEXTURE_WEBP:"EXT_texture_webp",EXT_TEXTURE_AVIF:"EXT_texture_avif",EXT_MESHOPT_COMPRESSION:"EXT_meshopt_compression",EXT_MESH_GPU_INSTANCING:"EXT_mesh_gpu_instancing"};let xo=class{constructor(e){this.parser=e,this.name=W.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){const e=this.parser,t=this.parser.json.nodes||[];for(let s=0,n=t.length;s<n;s++){const i=t[s];i.extensions&&i.extensions[this.name]&&i.extensions[this.name].light!==void 0&&e._addNodeRef(this.cache,i.extensions[this.name].light)}}_loadLight(e){const t=this.parser,s="light:"+e;let n=t.cache.get(s);if(n)return n;const i=t.json,c=((i.extensions&&i.extensions[this.name]||{}).lights||[])[e];let l;const h=new A.Color(16777215);c.color!==void 0&&h.setRGB(c.color[0],c.color[1],c.color[2],A.LinearSRGBColorSpace);const u=c.range!==void 0?c.range:0;switch(c.type){case"directional":l=new A.DirectionalLight(h),l.target.position.set(0,0,-1),l.add(l.target);break;case"point":l=new A.PointLight(h),l.distance=u;break;case"spot":l=new A.SpotLight(h),l.distance=u,c.spot=c.spot||{},c.spot.innerConeAngle=c.spot.innerConeAngle!==void 0?c.spot.innerConeAngle:0,c.spot.outerConeAngle=c.spot.outerConeAngle!==void 0?c.spot.outerConeAngle:Math.PI/4,l.angle=c.spot.outerConeAngle,l.penumbra=1-c.spot.innerConeAngle/c.spot.outerConeAngle,l.target.position.set(0,0,-1),l.add(l.target);break;default:throw new Error("THREE.GLTFLoader: Unexpected light type: "+c.type)}return l.position.set(0,0,0),Ge(l,c),c.intensity!==void 0&&(l.intensity=c.intensity),l.name=t.createUniqueName(c.name||"light_"+e),n=Promise.resolve(l),t.cache.add(s,n),n}getDependency(e,t){if(e==="light")return this._loadLight(t)}createNodeAttachment(e){const t=this,s=this.parser,i=s.json.nodes[e],o=(i.extensions&&i.extensions[this.name]||{}).light;return o===void 0?null:this._loadLight(o).then(function(c){return s._getNodeRef(t.cache,o,c)})}},_o=class{constructor(){this.name=W.KHR_MATERIALS_UNLIT}getMaterialType(){return A.MeshBasicMaterial}extendParams(e,t,s){const n=[];e.color=new A.Color(1,1,1),e.opacity=1;const i=t.pbrMetallicRoughness;if(i){if(Array.isArray(i.baseColorFactor)){const r=i.baseColorFactor;e.color.setRGB(r[0],r[1],r[2],A.LinearSRGBColorSpace),e.opacity=r[3]}i.baseColorTexture!==void 0&&n.push(s.assignTexture(e,"map",i.baseColorTexture,A.SRGBColorSpace))}return Promise.all(n)}},wo=class{constructor(e){this.parser=e,this.name=W.KHR_MATERIALS_EMISSIVE_STRENGTH}extendMaterialParams(e,t){const n=this.parser.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const i=n.extensions[this.name].emissiveStrength;return i!==void 0&&(t.emissiveIntensity=i),Promise.resolve()}},vo=class{constructor(e){this.parser=e,this.name=W.KHR_MATERIALS_CLEARCOAT}getMaterialType(e){const s=this.parser.json.materials[e];return!s.extensions||!s.extensions[this.name]?null:A.MeshPhysicalMaterial}extendMaterialParams(e,t){const s=this.parser,n=s.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const i=[],r=n.extensions[this.name];if(r.clearcoatFactor!==void 0&&(t.clearcoat=r.clearcoatFactor),r.clearcoatTexture!==void 0&&i.push(s.assignTexture(t,"clearcoatMap",r.clearcoatTexture)),r.clearcoatRoughnessFactor!==void 0&&(t.clearcoatRoughness=r.clearcoatRoughnessFactor),r.clearcoatRoughnessTexture!==void 0&&i.push(s.assignTexture(t,"clearcoatRoughnessMap",r.clearcoatRoughnessTexture)),r.clearcoatNormalTexture!==void 0&&(i.push(s.assignTexture(t,"clearcoatNormalMap",r.clearcoatNormalTexture)),r.clearcoatNormalTexture.scale!==void 0)){const o=r.clearcoatNormalTexture.scale;t.clearcoatNormalScale=new A.Vector2(o,o)}return Promise.all(i)}},So=class{constructor(e){this.parser=e,this.name=W.KHR_MATERIALS_DISPERSION}getMaterialType(e){const s=this.parser.json.materials[e];return!s.extensions||!s.extensions[this.name]?null:A.MeshPhysicalMaterial}extendMaterialParams(e,t){const n=this.parser.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const i=n.extensions[this.name];return t.dispersion=i.dispersion!==void 0?i.dispersion:0,Promise.resolve()}},Qo=class{constructor(e){this.parser=e,this.name=W.KHR_MATERIALS_IRIDESCENCE}getMaterialType(e){const s=this.parser.json.materials[e];return!s.extensions||!s.extensions[this.name]?null:A.MeshPhysicalMaterial}extendMaterialParams(e,t){const s=this.parser,n=s.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const i=[],r=n.extensions[this.name];return r.iridescenceFactor!==void 0&&(t.iridescence=r.iridescenceFactor),r.iridescenceTexture!==void 0&&i.push(s.assignTexture(t,"iridescenceMap",r.iridescenceTexture)),r.iridescenceIor!==void 0&&(t.iridescenceIOR=r.iridescenceIor),t.iridescenceThicknessRange===void 0&&(t.iridescenceThicknessRange=[100,400]),r.iridescenceThicknessMinimum!==void 0&&(t.iridescenceThicknessRange[0]=r.iridescenceThicknessMinimum),r.iridescenceThicknessMaximum!==void 0&&(t.iridescenceThicknessRange[1]=r.iridescenceThicknessMaximum),r.iridescenceThicknessTexture!==void 0&&i.push(s.assignTexture(t,"iridescenceThicknessMap",r.iridescenceThicknessTexture)),Promise.all(i)}},Mo=class{constructor(e){this.parser=e,this.name=W.KHR_MATERIALS_SHEEN}getMaterialType(e){const s=this.parser.json.materials[e];return!s.extensions||!s.extensions[this.name]?null:A.MeshPhysicalMaterial}extendMaterialParams(e,t){const s=this.parser,n=s.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const i=[];t.sheenColor=new A.Color(0,0,0),t.sheenRoughness=0,t.sheen=1;const r=n.extensions[this.name];if(r.sheenColorFactor!==void 0){const o=r.sheenColorFactor;t.sheenColor.setRGB(o[0],o[1],o[2],A.LinearSRGBColorSpace)}return r.sheenRoughnessFactor!==void 0&&(t.sheenRoughness=r.sheenRoughnessFactor),r.sheenColorTexture!==void 0&&i.push(s.assignTexture(t,"sheenColorMap",r.sheenColorTexture,A.SRGBColorSpace)),r.sheenRoughnessTexture!==void 0&&i.push(s.assignTexture(t,"sheenRoughnessMap",r.sheenRoughnessTexture)),Promise.all(i)}},Do=class{constructor(e){this.parser=e,this.name=W.KHR_MATERIALS_TRANSMISSION}getMaterialType(e){const s=this.parser.json.materials[e];return!s.extensions||!s.extensions[this.name]?null:A.MeshPhysicalMaterial}extendMaterialParams(e,t){const s=this.parser,n=s.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const i=[],r=n.extensions[this.name];return r.transmissionFactor!==void 0&&(t.transmission=r.transmissionFactor),r.transmissionTexture!==void 0&&i.push(s.assignTexture(t,"transmissionMap",r.transmissionTexture)),Promise.all(i)}},Lo=class{constructor(e){this.parser=e,this.name=W.KHR_MATERIALS_VOLUME}getMaterialType(e){const s=this.parser.json.materials[e];return!s.extensions||!s.extensions[this.name]?null:A.MeshPhysicalMaterial}extendMaterialParams(e,t){const s=this.parser,n=s.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const i=[],r=n.extensions[this.name];t.thickness=r.thicknessFactor!==void 0?r.thicknessFactor:0,r.thicknessTexture!==void 0&&i.push(s.assignTexture(t,"thicknessMap",r.thicknessTexture)),t.attenuationDistance=r.attenuationDistance||1/0;const o=r.attenuationColor||[1,1,1];return t.attenuationColor=new A.Color().setRGB(o[0],o[1],o[2],A.LinearSRGBColorSpace),Promise.all(i)}},Eo=class{constructor(e){this.parser=e,this.name=W.KHR_MATERIALS_IOR}getMaterialType(e){const s=this.parser.json.materials[e];return!s.extensions||!s.extensions[this.name]?null:A.MeshPhysicalMaterial}extendMaterialParams(e,t){const n=this.parser.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const i=n.extensions[this.name];return t.ior=i.ior!==void 0?i.ior:1.5,Promise.resol